@odoo/o-spreadsheet 19.1.1 → 19.2.0-alpha.1
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.
- package/dist/o-spreadsheet-engine.esm.js +4 -4
- package/dist/o-spreadsheet-engine.iife.js +4 -4
- package/dist/o-spreadsheet-engine.min.iife.js +1 -1
- package/dist/o_spreadsheet.css +3 -3
- package/dist/o_spreadsheet.esm.js +11 -8
- package/dist/o_spreadsheet.iife.js +11 -8
- package/dist/o_spreadsheet.min.iife.js +2 -2
- package/dist/o_spreadsheet.xml +3 -3
- package/package.json +2 -2
|
@@ -832,7 +832,7 @@
|
|
|
832
832
|
<tableParts count="${e.tables.length}">
|
|
833
833
|
${t_(a)}
|
|
834
834
|
</tableParts>
|
|
835
|
-
`}var xM;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(xM||(xM={}));function RM(e,t={}){const s=he(t);return s.type=e,s}const TM={showHeaders:!0,headerDesign:{align:"center",fillColor:"#808080",bold:!0,fontSize:15},showValues:!0,showLabels:!0,valuesDesign:{align:"left",verticalAlign:"bottom",fontSize:12},coloringOptions:{type:"categoryColor",colors:[],useValueBasedGradient:!0}},AM={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},_M=function(e){return Math.floor(e/AM.second)},DM=function(e){return Math.floor(e/AM.minute)},OM=function(e){return Math.floor(e/AM.hour)},FM=function(e){return Math.floor(e/AM.day)},PM=function(e){return Math.floor(e/AM.month)},MM=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function NM(e,t,s){const o=function(e){const t=e.indexOf("h");e=t>=0?e.slice(0,t).replace(/m/g,"M")+e.slice(t):e.replace(/m/g,"M");e.includes("a")||(e=e.replace(/h/g,"H"));return e}(t),i=function(e,t,s){const o=e.map(e=>Qs(e,s)?.jsDate);if(o.some(e=>void 0===e)||e.length<2)return;const i=o.map(e=>e.getTime()),n=tt(i)-st(i),r=function(e){if(e.includes("s"))return"second";if(e.includes("m"))return"minute";if(e.includes("h")||e.includes("H"))return"hour";if(e.includes("d"))return"day";if(e.includes("M"))return"month";return"year"}(t);if(AM.second>=AM[r]&&_M(n)<180)return"second";if(AM.minute>=AM[r]&&DM(n)<180)return"minute";if(AM.hour>=AM[r]&&OM(n)<96)return"hour";if(AM.day>=AM[r]&&FM(n)<90)return"day";if(AM.month>=AM[r]&&PM(n)<36)return"month";return"year"}(e,o,s),n={};return i&&(n[i]=o),{parser:o,displayFormats:n,unit:i??!1,tooltipFormat:o}}function kM(e,t){let s={};const{trendDataSetsValues:o,locale:i,axisFormats:n}=t,r={stacked:e.stacked,locale:i};if(e.horizontal)s.x=jM(e,"bottom","values",{...r,format:n?.x}),s.y=jM(e,"left","labels",r);else{s.x=jM(e,"bottom","labels",r);const t={...r,format:n?.y};s.y=jM(e,"left","values",t);const o={...r,format:n?.y1};s.y1=jM(e,"right","values",o)}if(s=Ue(s),o&&o.length&&o.some(De)){const e=Math.max(...o.map(e=>e?.length||0));s[_y]={...s.x,labels:Array(e).fill(""),offset:!1,display:!1},s[Dy]={...s.x,offset:!0,display:!1}}return s}function LM(e,t){const s=t.map(e=>e.label||""),o=Uy(e.background);return{y:{title:ZM(e.axesDesign?.y),stacked:!0,min:0,max:s.length,ticks:{stepSize:.5,color:o,callback:function(e,t,o){if(t%2!=0)return s[Math.floor((t-1)/2)]}},grid:{display:!1},border:{display:!1}},x:{title:ZM(e.axesDesign?.x),stacked:!0,grid:{display:!1},position:"top",ticks:{color:o},border:{display:!1}}}}function VM(e,t){const{dataSetsValues:s}=t;if(!s.length||"none"===e.legendPosition)return;const o=s.flatMap(e=>e.data).filter(De),i=Math.min(...o),n=Math.max(...o);let r=[];return r="object"==typeof e.colorScale?[e.colorScale.minColor,e.colorScale.midColor,e.colorScale.maxColor].filter(De):[...wb[e.colorScale??"oranges"]],{position:"right"===e.legendPosition?"right":"left",colorScale:r,fontColor:Uy(e.background),minValue:i,maxValue:n,locale:t.locale}}function zM(e,t){const{locale:s,axisType:o,trendDataSetsValues:i,labels:n,axisFormats:r}=t,a=r?.x,l=e.stacked;let c={x:jM(e,"bottom","labels",{locale:s}),y:jM(e,"left","values",{locale:s,stacked:l,format:r?.y}),y1:jM(e,"right","values",{locale:s,stacked:l,format:r?.y1})};if(c=Ue(c),"time"===o&&n&&a){const e={type:"time",time:NM(n,a,s)};Object.assign(c.x,e),c.x.ticks.maxTicksLimit=15,delete c?.x?.ticks?.callback}else"linear"===o&&(c.x.type="linear",c.x.ticks.callback=e.humanize?e=>rn({value:e,format:a},s):e=>zi(e,{format:a,locale:s}));if(i&&i.length&&i.some(De)&&(c[_y]={...c.x,display:!1},c[Dy]={...c.x,display:!1},"category"===o||"time"===o)){const e=Math.max(...i.map(e=>e?.length||0));c[_y].type="category",c[_y].labels=fe(0,e).map(e=>e.toString()),c[_y].offset=!1,c[Dy].type="category",c[Dy].offset=!1}return c}function HM(e,t){const s=zM(e,t);return{...s,x:{...s.x,grid:{display:!0}}}}function UM(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;e.dataSets;const n={x:{...jM(e,"bottom","labels",{locale:s}),grid:{display:!1}},y:{position:e.verticalAxisPosition,ticks:{color:Uy(e.background),callback:jy({locale:s,format:i},e.humanize)},grid:{lineWidth:e=>0===e.tick.value?2:1},title:ZM(e.axesDesign?.y)}},r=n?.y||n?.y1;return r&&(r.grid={lineWidth:e=>0===e.tick.value?2:1}),n}function BM(e,t){const{dataSetsValues:s}=t,o=kM(e,t),i=o.x.ticks.callback;o.x.ticks.callback=e=>i(Math.abs(e));const n=Math.max(...s.map(e=>Math.max(...e.data.map(Math.abs))));return o.x.suggestedMin=-n,o.x.suggestedMax=n,o}function GM(e,t){const{locale:s,axisFormats:o,dataSetsValues:i}=t,n=Math.min(...i.map(e=>Math.min(...e.data.filter(e=>!isNaN(e)))));return{r:{beginAtZero:!0,ticks:{callback:jy({format:o?.r,locale:s},e.humanize),backdropColor:e.background||"#FFFFFF"},pointLabels:{color:Uy(e.background),callback:e=>Ky(e)},suggestedMin:n<0?n-1:0}}}function WM(e,t){const{locale:s,axisFormats:o,availableRegions:i}=t,n=function(e){switch(e){case"top":return"top-left";case"right":return"top-right";case"bottom":return"bottom-right";case"left":case"none":return"bottom-left"}}(e.legendPosition),r=e.region?i.find(t=>t.id===e.region):i[0],a=o?.y||o?.y1;return{projection:{projection:qM(r?.defaultProjection||"mercator"),axis:"x"},color:{axis:"x",display:"none"!==e.legendPosition,border:{color:S},grid:{color:S},ticks:{color:Uy(e.background),callback:jy({locale:s,format:a},e.humanize)},legend:{position:n,align:n.includes("right")?"left":"right",margin:XM(e)},interpolate:YM(e.colorScale??A),missing:e.missingValueColor||"#ffffff"}}}function $M(e,t){const s=t.dataSetsValues[0];return{x:{display:!1},y:{grid:{offset:!1},ticks:{callback:function(e){return Ky(this.getLabelForValue(e))}},border:{display:!1}},percentages:{position:"right",border:{display:!1},ticks:{callback:function(e,o,i){const n=s.data?.[o],r=s.data?.[0];return r&&void 0!==n?zi(n/r,{format:"0%",locale:t.locale}):""}},grid:{display:!1}}}}function qM(e){return"conicConformal"===e?globalThis.ChartGeo.geoConicConformal().rotate([100,0]):e}function ZM(e){if(e?.title?.text){const{text:t,color:s,align:o,italic:i,bold:n}=e.title;return{display:!0,text:t,color:s,font:{style:i?"italic":"normal",weight:n?"bold":"normal",size:e.title.fontSize??12},align:"left"===o?"start":"right"===o?"end":"center"}}}function jM(e,t,s,o){const{useLeftAxis:i,useRightAxis:n}=qy(e);if("left"===t&&!i||"right"===t&&!n)return;const r=Uy(e.background);let a;if(a="bottom"===t?e.axesDesign?.x:"left"===t?e.axesDesign?.y:e.axesDesign?.y1,"values"===s){const s=!("right"===t&&i);return{position:t,title:ZM(a),grid:{display:s},beginAtZero:!0,stacked:o?.stacked,ticks:{color:r,callback:jy(o,e.humanize)}}}return{ticks:{padding:5,color:r,callback:function(e,t,s){return Ky(this.getLabelForValue(e))}},grid:{display:!1},stacked:o?.stacked,title:ZM(a)}}function YM(e,t=0,s=1){if(t===s){const t=e.midColor??e.minColor;return e=>t}const o=[{value:t,color:e.minColor}];return e.midColor&&o.push({value:(t+s)/2,color:e.midColor}),o.push({value:s,color:e.maxColor}),xb(o)}function XM(e){switch(e.legendPosition){case"top":case"right":return{top:!!e.title.text?45:R,left:E,right:E};case"bottom":case"left":case"none":return{left:E,right:E,bottom:x}}}const KM="nullValue";function JM(e,t){const{dataSetsValues:s}=t,o=[],i=vN(e,s.length),n=[];for(const r in s){let{label:a,data:l,hidden:h}=s[r];a=e.dataSets?.[r].label||a;const d=i.next(),u={label:a,data:l,hidden:h,borderColor:e.background||c,borderWidth:e.stacked?1:0,backgroundColor:d,yAxisID:e.horizontal?"y":e.dataSets?.[r].yAxisId||"y",xAxisID:"x",barPercentage:.9,categoryPercentage:s.length>1?.8:1,borderRadius:2};o.push(u);const g=e.dataSets?.[r].trend,p=t.trendDataSetsValues?.[r];g?.display&&!e.horizontal&&p&&n.push(mN(u,g,p))}return o.push(...n),o}function QM(e,t){const{labels:s,dataSetsValues:o}=t,i=o.map(e=>e.data).flat().filter(De),n=Math.max(...i),r=Math.min(...i),a=YM(e.colorScale??A,r,n),l=[];for(const t of o)l.push({label:t.label,data:t.data.map(e=>1),backgroundColor:t.data.map(t=>void 0!==t?a(t):e.missingValueColor||p),borderColor:e.background||c,borderSkipped:!1,borderWidth:1,barPercentage:1,categoryPercentage:1,values:t.data});return{labels:s,datasets:l}}function eN(e,t){const{dataSetsValues:s,labels:o}=t,i=e.negativeValuesColor||f,n=e.positiveValuesColor||m,r=e.subTotalValuesColor||v,a=[],l=[],c={label:"",data:l,backgroundColor:a},h=[];let d=0;for(const t of s)if(!t.hidden){for(let c=0;c<t.data.length;c++){const u=t.data[c];if(h.push(o[c]),isNaN(Number(u))){l.push([d,d]),a.push("");continue}l.push([d,u+d]);let g=u>=0?n:i;0===c&&t===s[0]&&e.firstValueAsSubtotal&&(g=r),a.push(g),d+=u}e.showSubTotals&&(h.push(Cs("Subtotal")),l.push([0,d]),a.push(r))}return{datasets:[c],labels:h}}function tN(e,t){const{dataSetsValues:s,axisType:o,labels:i}=t,n=[],r=!!e.fillArea,a=!!e.stacked,l=[],c=vN(e,s.length);for(let h=0;h<s.length;h++){let{label:d,data:u,hidden:g}=s[h];d=e.dataSets?.[h].label||d;const p=c.next();o&&["linear","time"].includes(o)&&(u=u.map((e,t)=>({x:i[t]||void 0,y:e})));const m={label:d,data:u,hidden:g,tension:0,borderColor:p,backgroundColor:r?ab(p,.4):p,pointBackgroundColor:p,fill:!!r&&fN(h,a),pointRadius:e.hideDataMarkers?0:3,yAxisID:e.dataSets?.[h].yAxisId||"y"};n.push(m);const f=e.dataSets?.[h].trend,v=t.trendDataSetsValues?.[h];f?.display&&v&&l.push(mN(m,f,v))}return n.push(...l),n}function sN(e,t){const s=tN(e,t);for(const e of s)Jy(e.xAxisID)||(e.showLine=!1);return s}function oN(e,t){const{dataSetsValues:s}=t,o=[],i=Math.max(0,...s.map(e=>e?.data?.length??0)),n=Xy(new yb(i),s);for(const{label:t,data:i,hidden:r}of s){if(r)continue;const s={label:t,data:i,borderColor:e.background||"#FFFFFF",backgroundColor:n,hoverOffset:10};o.push(s)}return o}function iN(e,t){const{dataSetsValues:s}=t,o=[],i=vN(e,s.length),n=[],r=s.filter((t,s)=>"bar"===(e.dataSets?.[s].type??"line"));for(let a=0;a<s.length;a++){let{label:l,data:c,hidden:h}=s[a];l=e.dataSets?.[a].label||l;const d=e.dataSets?.[a],u=i.next(),g=d?.type??"line",p={label:l,data:c,hidden:h,borderColor:u,backgroundColor:u,yAxisID:e.dataSets?.[a].yAxisId||"y",xAxisID:"x",type:g,order:"bar"===g?s.length+a:a,pointRadius:e.hideDataMarkers?0:3};"bar"===p.type&&(p.barPercentage=.9,p.categoryPercentage=r.length>1?.8:1,p.borderRadius=2),o.push(p);const m=e.dataSets?.[a].trend,f=t.trendDataSetsValues?.[a];m?.display&&f&&n.push(mN(p,m,f))}return o.push(...n),o}function nN(e,t){const{dataSetsValues:s}=t,o=[],i=e.fillArea??!1,n=vN(e,s.length);for(let t=0;t<s.length;t++){let{label:r,data:a,hidden:l}=s[t];e.dataSets?.[t]?.label&&(r=e.dataSets[t].label);const c=n.next(),h={label:r,data:a,hidden:l,borderColor:c,backgroundColor:c,pointRadius:e.hideDataMarkers?0:3};i&&(h.backgroundColor=ab(c,.4),h.fill="start"),o.push(h)}return o}function rN(e,t){const{availableRegions:s,dataSetsValues:o,labels:i}=t,n=e.region||s[0]?.id,r=n?t.getGeoJsonFeatures(n):void 0,a={outline:r,showOutline:!!r,data:[]};if(r&&n){const e={};if(o[0])for(let s=0;s<o[0].data.length;s++){if(!i[s]||void 0===o[0].data[s])continue;const r=t.geoFeatureNameToId(n,i[s]);r&&(e[r]={value:o[0].data[s],label:i[s]})}for(const t of r)t.id&&a.data.push({feature:{...t,properties:{name:e[t.id]?.label}},value:e[t.id]?.value})}return[a]}function aN(e,t){const s=t.dataSetsValues[0],o=t.labels;if(!s)return[];let{label:i,data:n}=s;i=e.dataSets?.[0].label||i;return[{label:i,data:n.map(e=>e<=0?[0,0]:[-e,e]),backgroundColor:lN(o,e.funnelColors),yAxisID:"y",xAxisID:"x",barPercentage:1,categoryPercentage:1,borderColor:e.background||c,borderWidth:3}]}function lN(e,t){const s=new yb(e.length,t);return e.map(()=>s.next())}function cN(e,t){const{dataSetsValues:s,labels:o}=t,i=uN(hN(s,o)),n=i[0]||[],r=new yb(n.length,e.groupColors||[]),a=n.map(e=>({label:e.label,color:r.next()})),l=[];for(let t=i.length-1;t>=0;t--){const s={groupColors:a,parsing:{key:"value"},data:i[t],borderColor:t=>{const s="data"===t.type?t.raw:void 0;return s&&s.label!==KM?e.background||c:p},backgroundColor:e=>{const t="data"===e.type?e.raw:void 0;if(!t||t.label===KM)return p;const s=t.groups[0];return a.find(e=>e.label===s)?.color},hoverOffset:10};l.push(s)}return l}function hN(e,t){const s=function(e,t){const s=[],o=Math.max(...e.map(e=>e.data.length));for(let i=0;i<o;i++){s[i]={};for(let t=0;t<e.length;t++){const o=null===e[t].data[i]?KM:String(e[t].data[i]);s[i][t]=o}s[i].value=Number(t[i])}return s}(e,t);return dN(s,0,e.length,[])}function dN(e,t,s,o){if(t>=s)return[];const i=Object.groupBy(e,e=>e[t]);return Object.keys(i).map(e=>{const n=i[e]?.reduce((e,t)=>e+Number(t.value),0)||0,r=[...o,e];return{label:e,value:n,children:dN(i[e]||[],t+1,s,[...o,e]),groups:r,depth:t}}).sort((e,t)=>t.value-e.value)}function uN(e){const t=[],s=[...e];for(;s.length>0;){const e=s.shift();e&&(t[e.depth]||(t[e.depth]=[]),t[e.depth].push(e),e.children&&s.push(...e.children))}return t}function gN(e,t){const{dataSetsValues:s,labels:o,locale:i,axisFormats:n}=t,r={locale:i,format:n?.y};if(0===s.length)return[];const a=hN(s,o).sort((e,t)=>t.value-e.value),l=function(e,t){const s="categoryColor"===e.coloringOptions?.type?e.coloringOptions.colors:[],o=new yb(t.length,s);return t.map(e=>({label:e.label,color:o.next()}))}(e,a),c=[],h=Math.max(...s.map(e=>e.data.length));for(let e=0;e<h;e++){c[e]={};for(let t=0;t<s.length;t++)c[e][t]=s[t].data[e]?String(s[t].data[e]):void 0;c[e].value=Number(o[e])}const d=e.showLabels??TM.showLabels,u=e.showValues??TM.showValues,g=e.coloringOptions||TM.coloringOptions;let p;"colorScale"===g?.type&&(p=function(e,t){if(0===e.length)return;const s=uN(e),o=s[s.length-1],i=Math.min(...o.map(e=>e.value)),n=Math.max(...o.map(e=>e.value));if(Number.isFinite(i)&&Number.isFinite(n)){const e=[{value:i,color:t.minColor}];if(t.midColor){const s=(i+n)/2;e.push({value:s,color:t.midColor})}return e.push({value:n,color:t.maxColor}),xb(e)}return}(a,g));const m=[{data:[],tree:c,labels:{display:d||u,overflow:"hidden",...pN(e.valuesDesign,TM.valuesDesign),formatter:e=>[d?e.raw.g:void 0,u?zi(e.raw.v,r):void 0].filter(De)},captions:{display:e.showHeaders??TM.showHeaders,padding:6,...pN(e.headerDesign,TM.headerDesign)},key:"value",groups:fe(0,s.length).map(e=>String(e)),borderWidth:0,spacing:1,displayMode:"headerBoxes",groupColors:l,backgroundColor:t=>{if("data"!==t.type)return"transparent";if(!t.raw.isLeaf)return e.headerDesign?.fillColor||TM.headerDesign?.fillColor;if("colorScale"===g.type)return p?.(t.raw.v)||"#FF0000";if("categoryColor"===g.type)return function(e,t,s,o){const i=e.raw._data.children[0][0],n=o.find(e=>e.label===i)?.color;if(!n||!s.useValueBasedGradient)return n||"#FF0000";const r=t.find(e=>e.label===i);if(!r||!r.children.length)return n;const a=uN(r.children),l=a[a.length-1],c=Math.max(...l.map(e=>e.value)),h=Math.min(...l.map(e=>e.value));if(h===c||!isFinite(h)||!isFinite(c))return n;const d=Number(e.raw.v)||0,u=(d-c)/(h-c)*.5;return lb(n,u)}(t,a,g,l);throw new Error("Unsupported coloring option type}")}}];return m}function pN(e,t){const s=e=>Qv(e.element.options.backgroundColor)>.7?"#666666":"#FFFFFF";return{align:e?.align??t?.align,position:e?.verticalAlign??t?.verticalAlign,color:e?.color||s,hoverColor:e?.color||s,font:{weight:e?.bold??t?.bold?"bold":"normal",style:e?.italic??t?.italic?"italic":"normal",size:e?.fontSize??t?.fontSize}}}function mN(e,t,s){const o=tb(e.backgroundColor);o.a=1;const i=t.color||lb(eb(o),.5);return{type:"line",xAxisID:"trailingMovingAverage"===t.type?Dy:_y,yAxisID:e.yAxisID,label:e.label?Cs("Trend line for %s",e.label):"",data:s,order:-1,showLine:!0,pointRadius:0,backgroundColor:i,borderColor:i,borderDash:[5,5],borderWidth:void 0,fill:!1,pointBackgroundColor:i}}function fN(e,t){return t?0===e?"origin":"-1":"origin"}function vN(e,t){return new yb(t,e.dataSets?.map(e=>e.backgroundColor)||[])}const bN={id:"sunburstHoverPlugin",afterEvent(e,t,s){if(!s.enabled)return;const o=e.getActiveElements();let i=o.map(e=>({datasetIndex:e.datasetIndex,index:e.index}));for(const t of o){const s=e.data.datasets[t.datasetIndex].data[t.index];for(let t=0;t<e.data.datasets.length;t++){const o=e.data.datasets[t];for(let e=0;e<o.data.length;e++){const n=o.data[e];SN(s.groups,n.groups)&&i.push({datasetIndex:t,index:e})}}}i=i.filter(t=>{const{datasetIndex:s,index:o}=t;return e.data.datasets[s].data[o].label!==KM}),e.setActiveElements(i);for(const t of e.getSortedVisibleDatasetMetas())for(const e of t.data){const t=e.$context,{datasetIndex:s,index:o,dataset:n,raw:r}=t;if(r.label===KM)continue;const a="function"==typeof n.backgroundColor?n.backgroundColor(t):n.backgroundColor;i.length&&!i.some(e=>e.datasetIndex===s&&e.index===o)?e.options.backgroundColor=lb(a,.5):e.options.backgroundColor=a}}};function SN(e,t){return t.length>e.length&&e.every((e,s)=>e===t[s])}const yN={id:"sunburstLabelsPlugin",afterDatasetsDraw(e,t,s){if(!s.showValues&&!s.showLabels||"doughnut"!==e.config.type)return;!function(e,t,s){const o=t.style,i=o.fontSize||13,n=i+3;for(const r of e._metasets)for(let a=0;a<r._dataset.data.length;a++){const l=r._dataset.data[a];if(l.label===KM)continue;const c=[t.showLabels?l.label:void 0,t.showValues?t.callback(l.value,"y"):void 0].filter(De),h=r.data[a];let{startAngle:d,endAngle:u,innerRadius:g,outerRadius:p,circumference:m}=h;const f=h.options.offset/4,v=f*(1-Math.sin(Math.min(Math.PI,m||0)));g+=v,p+=v;const b=(d+u)/2,S=(g+p)/2,y=.9*(p-g),C=u-d;if((C>=Math.PI?p:Math.sin(C/2)*g*2)<c.length*n)continue;s.save();const I={x:Math.cos(b)*f,y:Math.sin(b)*f},w=e.chartArea.left+e.chartArea.width/2+I.x,E=e.chartArea.top+e.chartArea.height/2+I.y;let x;s.translate(w,E),b>Math.PI/2?(s.rotate(b-Math.PI),x=-S):(x=S,s.rotate(b));const R=Qv(h.options.backgroundColor)>.7?"#666666":"#FFFFFF";s.fillStyle=o.textColor||R,s.textAlign="center",s.textBaseline="middle",s.font=yS(i,o.bold,o.italic);const T=-(c.length-1)*n/2;for(let e=0;e<c.length;e++){const t=NS(s,y,c[e],o,"px");s.fillText(t,x,T+e*n)}s.restore()}}(e,s,e.ctx)}};const CN={id:"waterfallLinesPlugin",beforeDraw(e,t,s){if(!s.showConnectorLines)return;const o=e._metasets?.[0]?.data;if(!o)return;const i=e.ctx;i.save(),i.setLineDash([3,2]);for(let e=0;e<o.length;e++){const t=o[e];if(0===t.height)continue;const s=wN(o,e);if(!s)break;const n=IN(t),r=IN(s),a=t.$context.raw,l=a[1]-a[0],c=Math.round(l<0?n.bottom-1:n.top),h=Math.round(n.right),d=Math.round(r.left);i.strokeStyle="#999",i.beginPath(),i.moveTo(h+1,c+.5),i.lineTo(d,c+.5),i.stroke()}i.restore()}};function IN(e){const t=e.base<e.y;return{left:e.x-e.width/2,right:e.x+e.width/2,bottom:t?e.base+e.height:e.y+e.height,top:t?e.base:e.y}}function wN(e,t){return e.find((e,s)=>s>t&&0!==e.height)}const EN={id:"zoomWindowPlugin",afterDatasetsDraw:function(e,t,s){if(!s.getLowerBound||!s.getUpperBound)return;const{ctx:o,chartArea:{left:i,right:n,top:r,bottom:a}}=e;let l=s.getLowerBound()??i,c=s.getUpperBound()??n;l>c&&([l,c]=[c,l]),l=Math.max(i,l),c=Math.min(n,c),l===i&&(l-=1),c===n&&(c+=1),o.save(),o.fillStyle="rgba(255,255,255,0.5)",o.beginPath(),o.rect(i,a,l-i,r-a),o.rect(c,a,n-c,r-a),o.fill(),o.beginPath(),o.strokeStyle="#bbb",o.rect(l,a,c-l,r-a),o.stroke(),o.lineWidth=2,o.beginPath(),o.moveTo(l-3,(r+a)/2-7),o.lineTo(l-3,(r+a)/2+7),o.stroke(),o.beginPath(),o.moveTo(c+3,(r+a)/2-7),o.lineTo(c+3,(r+a)/2+7),o.stroke(),o.restore()}};Hv.add("chartShowValuesPlugin",{register:e=>e.register(Tx),unregister:e=>e.unregister(Tx)}),Hv.add("waterfallLinesPlugin",{register:e=>e.register(CN),unregister:e=>e.unregister(CN)}),Hv.add("funnelController",{register:e=>e.register(US()),unregister:e=>e.unregister(US())}),Hv.add("funnelElement",{register:e=>e.register(BS()),unregister:e=>e.unregister(BS())}),Hv.add("funnelTooltipPositioner",{register:e=>e.Tooltip.positioners.funnelTooltipPositioner=WS,unregister:e=>e.Tooltip.positioners.funnelTooltipPositioner=void 0}),Hv.add("sunburstLabelsPlugin",{register:e=>e.register(yN),unregister:e=>e.unregister(yN)}),Hv.add("sunburstHoverPlugin",{register:e=>e.register(bN),unregister:e=>e.unregister(bN)}),Hv.add("chartColorScalePlugin",{register:e=>e.register(HS),unregister:e=>e.unregister(HS)}),Hv.add("calendarController",{register:e=>e.register(zS()),unregister:e=>e.unregister(zS())}),Hv.add("zoomWindowPlugin",{register:e=>e.register(EN),unregister:e=>e.unregister(EN)});class xN extends t.Component{static template="o-spreadsheet-ChartJsComponent";static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=t.useRef("graphContainer");chart;currentRuntime;animationStore;currentDevicePixelRatio=window.devicePixelRatio;get background(){return this.chartRuntime.background}get canvasStyle(){return`background-color: ${this.background}`}get chartRuntime(){const e=this.env.model.getters.getChartRuntime(this.props.chartId);if(!("chartJsConfig"in e))throw new Error("Unsupported chart runtime");return e}setup(){this.shouldAnimate&&(this.animationStore=Tv(VS)),t.onMounted(()=>{Bv();const e=this.chartRuntime;this.currentRuntime=e,this.createChart(he(e))}),t.onWillUnmount(this.unmount.bind(this)),t.useEffect(()=>{const e=this.chartRuntime;e!==this.currentRuntime?(e.chartJsConfig.type!==this.currentRuntime.chartJsConfig.type?(this.chart?.destroy(),this.createChart(he(e))):this.updateChartJs(he(e)),this.currentRuntime=e):this.currentDevicePixelRatio!==window.devicePixelRatio&&(this.currentDevicePixelRatio=window.devicePixelRatio,this.updateChartJs(he(this.currentRuntime)))})}unmount(){this.chart?.destroy()}get shouldAnimate(){return this.env.model.getters.isDashboard()}createChart(e){if(!globalThis.Chart)throw new Error("Chart.js library is not loaded");let t=e.chartJsConfig;if(this.shouldAnimate&&this.animationStore){const e=this.env.model.getters.getChart(this.props.chartId)?.type;e&&this.animationStore.animationPlayed[this.animationChartId]!==e&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}const s=this.canvas.el.getContext("2d");this.chart=new globalThis.Chart(s,t)}updateChartJs(e){let t=e.chartJsConfig;if(this.shouldAnimate){const e=this.env.model.getters.getChart(this.props.chartId)?.type;e&&this.hasChartDataChanged()&&this.animationStore&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}t.data&&t.data.datasets?(this.chart.data=t.data,t.options?.plugins?.title&&(this.chart.config.options.plugins.title=t.options.plugins.title)):this.chart.data.datasets=[],this.chart.config.options=t.options,this.chart.update()}hasChartDataChanged(){return!Le(this.getChartDataInRuntime(this.currentRuntime),this.getChartDataInRuntime(this.chartRuntime))}enableAnimationInChartData(e){return{...e,options:{...e.options,animation:{animateRotate:!0}}}}getChartDataInRuntime(e){const t=e.chartJsConfig.data;return{labels:t.labels,dataset:t.datasets.map(e=>({data:e.data,label:e.label,tree:e.tree}))}}get animationChartId(){return this.props.isFullScreen?this.props.chartId+"-fullscreen":this.props.chartId}}const RN=/Mac/i,TN=["Shift","Control","Alt","Meta"];function AN(e,t){return!!e&&(!!t.target&&e.contains(t.target))}function _N(e=1){const t=document.querySelector(".o-grid-overlay"),s=t&&DN(t,e);if(!s)throw new Error("Can't find spreadsheet position");return s}function DN(e,t){const s=e.closest(".o-zoomable");let o,i=1;s?(o=s,i=/Safari/i.test(navigator.userAgent)?t:1):o=e;const n=o.getBoundingClientRect();return{x:n.x*i,y:n.y*i,width:n.width*i,height:n.height*i}}function ON(e){return e.el?FN(e.el):{x:0,y:0,width:0,height:0}}function FN(e){const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*PN(e){if(yield e,e.hasChildNodes())for(const t of e.childNodes)yield*PN(t)}function MN(e){const{startElement:t,endElement:s,startSelectionOffset:o,endSelectionOffset:i}=function(e){const t=document.getSelection();return{startElement:t.anchorNode||e,startSelectionOffset:t.anchorOffset,endElement:t.focusNode||e,endSelectionOffset:t.focusOffset}}(e);return{start:NN(e,t,o),end:NN(e,s,i)}}function NN(e,t,s){let o=0;const i=PN(e);let n=i.next(),r=!0;for(;!n.done&&n.value!==t;)n.value.hasChildNodes()||n.value.textContent&&(o+=n.value.textContent.length),("P"===n.value.nodeName||"DIV"===n.value.nodeName&&n.value!==e)&&(r?r=!1:o++),n=i.next();if(n.value!==t)return 0;if(n.value.hasChildNodes()){const e=[...n.value.childNodes].slice(0,s);o+=e.reduce((t,s,o)=>{if(null!==s.textContent){let i=s.textContent.length;return"P"===s.nodeName&&o!==e.length-1&&i++,t+i}return t},0)}else o+=s;return"P"!==t.nodeName||r||""!==t.textContent||o++,o}const kN=/^[a-zA-Z]$/;function LN(e,t="key"){let s="";TN.includes(e.key)||(zN(e)&&(s+="Ctrl+"),e.altKey&&(s+="Alt+"),e.shiftKey&&(s+="Shift+"));const o="key"===t?e.key:e.code;return s+=kN.test(o)?o.toUpperCase():o,s}function VN(){return Boolean(RN.test(navigator.userAgent))}function zN(e){return VN()||GN()?e.metaKey:e.ctrlKey}function HN(e){return 1===e.button||zN(e)&&0===e.button}function UN(e,t){const s=document.createElement("a");s.href=e,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s)}function BN(){return/Firefox/i.test(navigator.userAgent)}function GN(){return/(iPad|iPhone|iPod)/i.test(navigator.userAgent)||"MacIntel"===navigator.platform&&(navigator.maxTouchPoints||1)>1}function WN(){return/Android/i.test(navigator.userAgent)||GN()||/(webOS|BlackBerry|Windows Phone)/i.test(navigator.userAgent)}function $N(e,t,s){const o=e.model.getters.getViewportZoomLevel();if(void 0===s&&(s=function(e,t){const s=e.target;if(!(s&&"classList"in s&&s instanceof Element))return null;return DN(s,t)}(t,o)),!s)return function(e){return{ev:e,clientX:e.clientX,clientY:e.clientY,offsetX:e.offsetX,offsetY:e.offsetY}}(t);const i=t.clientX-s.x,n=t.clientY-s.y,r=i/o,a=n/o;return{ev:t,clientX:t.clientX-i+r,clientY:t.clientY-n+a,offsetX:r,offsetY:a}}function qN(e,t){return{height:t.height*e,width:t.width*e,x:t.x*e,y:t.y*e}}class ZN extends t.Component{static template="o-spreadsheet-ScorecardChart";static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=t.useRef("chartContainer");get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}get title(){const e=this.env.model.getters.getChartDefinition(this.props.chartId).title.text;return e?this.env.model.getters.dynamicTranslate(e):""}setup(){t.useEffect(this.createChart.bind(this),()=>{const e=this.canvas.el.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}createChart(){const e=this.canvas.el;jO(JO(qN(1/this.env.model.getters.getViewportZoomLevel(),e.getBoundingClientRect()),this.runtime),e)}}const jN=new Set(["containsText","notContainsText","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","beginsWithText","endsWithText","isNotEmpty","isEmpty","isNotEqual","isEqual","customFormula","dateIs","dateIsBefore","dateIsAfter","dateIsOnOrBefore","dateIsOnOrAfter"]),YN=new Set(["containsText","notContainsText","isEqualText","isEmail","isLink","dateIs","dateIsBefore","dateIsOnOrBefore","dateIsAfter","dateIsOnOrAfter","dateIsBetween","dateIsNotBetween","dateIsValid","isEqual","isNotEqual","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","isBoolean","isValueInList","isValueInRange","customFormula"]);new Set(["containsText","notContainsText","isEqualText","dateIs","dateIsBefore","dateIsOnOrBefore","dateIsAfter","dateIsOnOrAfter","dateIsBetween","dateIsNotBetween","isEqual","isNotEqual","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","customFormula","beginsWithText","endsWithText","isNotEmpty","isEmpty"]);const XN=["containsText","notContainsText","isEqualText","isEmpty","isNotEmpty","beginsWithText","endsWithText"],KN=["isEqual","isNotEqual","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","isEmpty","isNotEmpty"],JN=["dateIs","dateIsBefore","dateIsOnOrBefore","dateIsAfter","dateIsOnOrAfter","dateIsBetween","dateIsNotBetween","isEmpty","isNotEmpty"];function QN(e,t,s,o){let i=yk(o,t,s).formattedValues,n=Ik(o,t);$y(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=vk(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=bk(i,n));const r=Ck(o,t,"left"),a=Ck(o,t,"right"),l=e.horizontal?{x:r||a}:{y:r,y1:a},c=[];for(const t in n){const{data:s}=n[t],o=e.dataSets?.[t].trend;if(!o?.display||e.horizontal){c.push(void 0);continue}const i=ck(o,s);c.push(i)}return{dataSetsValues:n,trendDataSetsValues:c,axisFormats:l,labels:i,locale:o.getLocale(),topPadding:Ek(e,o)}}function ek(e,t){switch(t){case"day_of_week":return Li[e-1].toString();case"hour_number":{const t=String(e%12).padStart(2,"0");return Cs(e<12?"%(hour)s AM":"%(hour)s PM",{hour:t})}case"month_number":return ki[e-1].toString();case"iso_week_number":{const t=String(e).padStart(2,"0");return Cs("W%(weekNumber)s",{weekNumber:t})}case"quarter_number":return Cs("Q%(value)s",{value:e});default:return e.toString()}}function tk(e,t,s,o){let i=yk(o,t,s).values,n=Ik(o,t);$y(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift();const r=o.getLocale()||gi;({labels:i,dataSetsValues:n}=function(e,t){const s=Math.max(e.length,...t.map(e=>e.data?.length||0)),o=fe(0,s).filter(s=>{const o=e[s],i=t.map(e=>e.data?.[s]);return o&&mo(o,gi)&&"number"==typeof i[0]});return{labels:o.map(t=>e[t]||""),dataSetsValues:t.map(e=>({...e,data:o.map(t=>"number"==typeof e.data[t]?e.data[t]:null)}))}}(i,n)),({labels:i,dataSetsValues:n}=function(e,t,s,o,i){const n={},r=[],a=[],l=[];for(let c=0;c<e?.length;c++){const h=Eo(xD({granularity:s,type:"date",displayName:"date"},e[c],gi),i);h in n||(r.push(h),n[h]={});const d=Eo(xD({granularity:o,type:"date",displayName:"date"},e[c],gi),i);l.includes(d)||(a.push(d),l.push(d)),d in n[h]||(n[h][d]=0),n[h][d]+=t[c]}return r.sort((e,t)=>e-t),a.sort((e,t)=>t-e),{dataSetsValues:a.map(e=>({data:r.map(t=>n?.[t]?.[e]),label:ek(e,o),hidden:!1})),labels:r.map(e=>ek(e,s))}}(i,n[0].data,e.horizontalGroupBy??"day_of_week",e.verticalGroupBy??"hour_number",r));return{dataSetsValues:n,axisFormats:{y:Ck(o,t,"left")},labels:i,locale:o.getLocale(),topPadding:Ek(e,o)}}function sk(e,t,s,o){const i=QN(e,t.slice(0,2),s,o),n=i.dataSetsValues.filter(e=>!e.hidden),r=[];if(n[0]){const e=n[0].data.map(e=>e>0?e:0);r.push({...n[0],data:e})}if(n[1]){const e=n[1].data.map(e=>e>0?-e:0);r.push({...n[1],data:e})}return{...i,dataSetsValues:r}}function ok(e,t,s,o){const i=function(e,t,s,o){if(function(e,t,s,o){return!e.labelsAsText&&gk(e,t,s,o)}(e,t,s,o)&&function(){if(!window.Chart)return!1;const e="luxon"===new window.Chart._adapters._date({})._id;e||mk||(mk=!0,console.warn("'chartjs-adapter-luxon' time adapter is not installed. Time scale axes are disabled."));return e}())return"time";if(function(e,t,s,o){return!e.labelsAsText&&pk(e,t,s,o)}(e,t,s,o))return"linear";return"category"}(e,t,s,o),n=yk(o,t,s);let r="linear"===i?n.values:n.formattedValues,a=Ik(o,t);const l=$y(s,t[0],e.dataSetsHaveTitle||!1);l&&r.shift(),({labels:r,dataSetsValues:a}=vk(r,a)),"time"===i&&({labels:r,dataSetsValues:a}=function(e,t){if(0===e.length||e.every(e=>!e))return{labels:e,dataSetsValues:t};const s=[...e],o=he(t);for(let e=0;e<s.length;e++)if(!s[e]){s[e]=Ne(s,e);for(const t of o)t.data[e]=void 0}return{labels:s,dataSetsValues:o}}(r,a)),e.aggregated&&({labels:r,dataSetsValues:a}=bk(r,a)),e.cumulative&&(a=wk(a,"asc"));const c={y:Ck(o,t,"left"),y1:Ck(o,t,"right"),x:Sk(o,s,l)},h=[];for(const t in a){const s=e.dataSets?.[t].trend;if(!s?.display){h.push(void 0);continue}const{data:n}=a[t];h.push(hk(s,n,r,i,o.getLocale()))}return{dataSetsValues:a,axisFormats:c,labels:r,locale:o.getLocale(),trendDataSetsValues:h,axisType:i,topPadding:Ek(e,o)}}function ik(e,t,s,o){let i=yk(o,t,s).formattedValues,n=Ik(o,t);$y(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=vk(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=bk(i,n)),({dataSetsValues:n,labels:i}=function(e,t){const s=Math.max(e.length,...t.map(e=>e.data?.length||0)),o=fe(0,s).filter(e=>t.some(t=>"number"==typeof t.data[e]&&t.data[e]>0));return{labels:o.map(t=>e[t]||""),dataSetsValues:t.map(e=>({...e,data:o.map(t=>"number"==typeof e.data[t]&&e.data[t]>0?e.data[t]:null)}))}}(i,n));return{dataSetsValues:n,axisFormats:{y:Ck(o,t,"left")},labels:i,locale:o.getLocale(),topPadding:Ek(e,o)}}function nk(e,t,s,o){let i=yk(o,t,s).formattedValues,n=Ik(o,t);$y(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=vk(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=bk(i,n));return{dataSetsValues:n,axisFormats:{r:Ck(o,t,"left")||Ck(o,t,"right")},labels:i,locale:o.getLocale()}}function rk(e,t,s,o){const i=t.slice(0,1);let n=yk(o,i,s).formattedValues;$y(s,i[0],e.dataSetsHaveTitle||!1)&&n.shift();let r=Ik(o,i);({labels:n,dataSetsValues:r}=bk(n,r));return{dataSetsValues:r,axisFormats:{y:Ck(o,i,"left")||Ck(o,i,"right")},labels:n,locale:o.getLocale(),availableRegions:o.getGeoChartAvailableRegions(),geoFeatureNameToId:o.geoFeatureNameToId,getGeoJsonFeatures:o.getGeoJsonFeatures}}function ak(e,t,s,o){let i=yk(o,t,s).formattedValues,n=Ik(o,t);$y(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=vk(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=bk(i,n)),e.cumulative&&(n=wk(n,"desc"));return{dataSetsValues:n,axisFormats:{x:Ck(o,t,"left")||Ck(o,t,"right")},labels:i,locale:o.getLocale()}}function lk(e,t,s,o){let i=yk(o,t,s).values,n=function(e,t){t=t.filter(t=>!e.isColHidden(t.dataRange.sheetId,t.dataRange.zone.left));const s=t.map(()=>({data:[],label:""})),o=t.map(t=>fk(e,t));if(!o.length)return s;const i=Math.min(...o.map(e=>e.length));let n=[];const r=t.length-1;for(let e=0;e<i;e++)for(let t=0;t<o.length;t++){let i=o[t][e];null==i&&t!==r&&(i=n[t]),i!==n[t]&&(n=n.slice(0,t),n[t]=i),s[t].data.push(i??null)}return s.filter(e=>e.data.some(e=>null!==e))}(o,t);const r=$y(s,t[0],e.dataSetsHaveTitle||!1);return r&&i.shift(),({labels:i,dataSetsValues:n}=function(e,t){const s=[],o=[];for(let t=0;t<e.length;t++)Number(e[t])<=0?o.push(t):Number(e[t])>0&&s.push(t);const i=s.length?s:o;return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}(i,n)),({labels:i,dataSetsValues:n}=function(e,t){const s=Math.max(e.length,...t.map(e=>e.data?.length||0)),o=e=>null==e||""===e,i=fe(0,s).filter(s=>{const i=t.map(e=>e.data?.[s]);if(o(i[0]))return!1;let n=!1;for(const e of i)if(n||=o(e),n&&!o(e))return!1;return e[s]&&!isNaN(Number(e[s]))});return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}(i,n)),{dataSetsValues:n,axisFormats:{y:Sk(o,s,r)},labels:i,locale:o.getLocale()}}function ck(e,t){const s=[],o=[],i=[];for(let e=0;e<t.length;e++)"number"==typeof t[e]&&(s.push(t[e]),o.push(e+1)),i.push(e+1);const n=dk(e,s,o,fe(.5,i.length+.55,.2));return n.length?n:void 0}function hk(e,t,s,o,i){const n=[],r=[],a=[],l=t.length;if(l<2)return;switch(o){case"category":for(let e=0;e<l;e++)"number"==typeof t[e]&&(n.push(t[e]),r.push(e+1)),a.push(e+1);break;case"linear":for(let e=0;e<t.length;e++){const o=Number(s[e]);isNaN(o)||("number"==typeof t[e]&&(n.push(t[e]),r.push(o)),a.push(o))}break;case"time":for(let e=0;e<t.length;e++){const o=Eo({value:s[e]},i);null!==t[e]&&(n.push(t[e]),r.push(o)),a.push(o)}}const c=Math.min(...a),h=Math.max(...a);if(h===c)return;const d=(h-c)/(5*a.length),u=dk(e,n,r,fe(c,h+d/2,d));return u.length?u:void 0}function dk(e,t,s,o){if(t.length<2||s.length<2||0===o.length)return[];const{normalizedLabels:i,normalizedNewLabels:n}=function(e,t,s){let o=[],i=[];if("logarithmic"===s.type){const s=Math.max(...e.map(Math.abs));o=e.map(e=>e/s),i=t.map(e=>e/s)}else{const s=Math.max(...e),n=Math.min(...e),r=s-n;o=e.map(e=>(e-s)/r),i=t.map(e=>(e-s)/r)}return{normalizedLabels:o,normalizedNewLabels:i}}(s,o,e);try{switch(e.type){case"polynomial":{const s=e.order;if(!s)return o.map(e=>({x:e,y:NaN}));if(1===s)return yl([t],[i],[n],!0)[0].map((e,t)=>({x:o[t],y:e}));const r=ml(t,i,s,!0).flat();return n.map((e,t)=>({x:o[t],y:vl(r,e,s)}))}case"exponential":{const e=[],s=[];for(let o=0;o<t.length;o++)t[o]>0&&(e.push(Math.log(t[o])),s.push(i[o]));return s.length?bl(yl([e],[s],[n],!0))[0].map((e,t)=>({x:o[t],y:e})):o.map(e=>({x:e,y:NaN}))}case"logarithmic":return yl([t],Sl([i]),Sl([n]),!0)[0].map((e,t)=>({x:o[t],y:e}));case"trailingMovingAverage":return function(e,t,s=2){const o=[];for(let e=0;e<s-1;e++)o.push({x:t[e],y:NaN});for(let i=0;i<=e.length-s;i++){let n=0;for(let t=i;t<i+s;t++)n+=e[t];o.push({x:t[i+s-1],y:n/s})}return o}(t,s,e.window);default:return o.map(e=>({x:e,y:NaN}))}}catch(e){return o.map(e=>({x:e,y:NaN}))}}function uk(e,t,s,o){return gk(e,t,s,o)||pk(e,t,s,o)}function gk(e,t,s,o){if(!s||!pk(e,t,s,o))return!1;const i=Sk(o,s,$y(s,t[0],e.dataSetsHaveTitle||!1));return Boolean(i&&MM.test(i))}function pk(e,t,s,o){if(!s)return!1;const i=o.getRangeValues(s);return $y(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),!i.some(e=>isNaN(Number(e))&&e)&&!i.every(e=>!e)}let mk=!1;function fk(e,t){if(t.dataRange){const s=t.labelCell?[t.labelCell.zone]:[],o=yt([t.dataRange.zone],s)[0];if(void 0===o)return[];const i=e.getRangeFromZone(t.dataRange.sheetId,o);return e.getRangeValues(i).map(e=>""===e?void 0:e)}return[]}function vk(e,t){const s=fe(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(s=>{const o=e[s],i=t.map(e=>e.data?.[s]);return o||i.some(e=>"number"==typeof e)});return{labels:s.map(t=>e[t]||""),dataSetsValues:t.map(e=>({...e,data:s.map(t=>"number"==typeof e.data[t]?e.data[t]:null)}))}}function bk(e,t){const s=e=>"number"==typeof e?e:0,o=new Set(e),i={};o.forEach(e=>{i[e]=new Array(t.length).fill(0)});for(const o of fe(0,e.length)){const n=e[o];for(const e of fe(0,t.length))i[n][e]+=s(t[e].data[o])}return{labels:Array.from(o),dataSetsValues:t.map((e,t)=>({...e,data:Array.from(o).map(e=>i[e][t])}))}}function Sk(e,t,s){if(!t)return;const{sheetId:o,zone:i}=t,n=Zt(i).map(t=>e.getEvaluatedCell({sheetId:o,...t}).format);return s&&n.shift(),n.find(e=>void 0!==e)}function yk(e,t,s){let o={values:[],formattedValues:[]};if(s){const{left:i}=s.zone;if(s.invalidXc||s.invalidSheetName||e.isColHidden(s.sheetId,i)){if(t[0]){o={formattedValues:fe(0,fk(e,t[0]).length).map(e=>e.toString()),values:o.formattedValues}}}else o={formattedValues:e.getRangeFormattedValues(s),values:e.getRangeValues(s).map(e=>String(e??""))}}else if(1===t.length){const s=fk(e,t[0]).length;for(let e=0;e<s;e++)o.formattedValues.push(""),o.values.push("")}else if(t[0]){o={formattedValues:fe(0,fk(e,t[0]).length).map(e=>e.toString()),values:o.formattedValues}}return o}function Ck(e,t,s){const o=t.filter(e=>"right"===s==!!e.rightYAxis);for(const t of o){const s=e.getRangeFormats(t.dataRange).find(e=>void 0!==e&&!ji(e));if(s)return s}}function Ik(e,t){const s=[];for(const[o,i]of Object.entries(t)){let t=`${Bg.Series} ${parseInt(o)+1}`,n=e.isColHidden(i.dataRange.sheetId,i.dataRange.zone.left);if(i.labelCell){const{sheetId:s,zone:o}=i.labelCell,n=e.getEvaluatedCell({sheetId:s,col:o.left,row:o.top});n&&(t=n.formattedValue)}let r=i.dataRange?fk(e,i):[];r.every(e=>!e||"string"==typeof e&&!Co(e))&&r.filter(e=>"string"==typeof e).length>1?r=r.map(e=>e&&!Co(e)?1:null):r.every(e=>null==e||!mo(e.toString(),gi))&&(n=!0),s.push({data:r,label:t,hidden:n})}return s}function wk(e,t){return e.map(e=>{const s=[];let o=0;const i="asc"===t?Object.keys(e.data):Object.keys(e.data).reverse();for(const t of i)isNaN(parseFloat(e.data[t]))?s[t]=e.data[t]:(o+=parseFloat(e.data[t]),s[t]=o);return{...e,data:s}})}function Ek(e,t){const{title:s,legendPosition:o}=e,i=s&&s.text||"top"===o;return t.isDashboard()&&!i?30:0}function xk(e,t){return{padding:{left:E,right:E,top:Math.max(R,t.topPadding||0),bottom:x}}}function Rk(e,t){const s=e.legendPosition;return{padding:{left:E+("left"===s?70:0),right:E+("right"===s?70:0),top:Math.max(R,t.topPadding||0),bottom:x}}}function Tk(e,t){return{display:"none"!==e.legendPosition,position:"none"!==e.legendPosition?e.legendPosition:void 0}}function Ak(e,t){return{...kk,...Tk(e),...Lk(Uy(e.background),{pointStyle:"rect",lineWidth:3})}}function _k(e,t){const s=e.fillArea,o=s?"rect":"line",i=s?2:3;return{...kk,...Tk(e),...Lk(Uy(e.background),{pointStyle:o,lineWidth:i})}}function Dk(e,t){const{dataSetsValues:s}=t,o=Math.max(0,...s.map(e=>e?.data?.length??0)),i=Xy(new yb(o),s),n=Uy(e.background);return{...Tk(e),labels:{usePointStyle:!0,generateLabels:e=>(e.data.labels?.map((e,t)=>({text:Ky(String(e)),strokeStyle:i[t],fillStyle:i[t],pointStyle:"rect",lineWidth:2,fontColor:n}))||[]).filter(e=>e.text),filter:(e,t)=>!("datasetIndex"in e)||!t.datasets[e.datasetIndex].hidden}}}function Ok(e,t){return{...kk,...Tk(e),...Lk(Uy(e.background),{pointStyle:"circle",strokeStyle:e.background||"#ffffff",lineWidth:8})}}function Fk(e,t){return{...kk,...Tk(e),...Lk(Uy(e.background),{lineWidth:3})}}function Pk(e,t){const s=Uy(e.background),o=e.negativeValuesColor||f,i=e.positiveValuesColor||m,n=e.subTotalValuesColor||v;return{...Tk(e),labels:{usePointStyle:!0,generateLabels:()=>{const t=[{text:Cs("Positive values"),fontColor:s,fillStyle:i,strokeStyle:i,pointStyle:"rect"},{text:Cs("Negative values"),fontColor:s,fillStyle:o,strokeStyle:o,pointStyle:"rect"}];return(e.showSubTotals||e.firstValueAsSubtotal)&&t.push({text:Cs("Subtotals"),fontColor:s,fillStyle:n,strokeStyle:n,pointStyle:"rect"}),t},filter:(e,t)=>!("datasetIndex"in e)||!t.datasets[e.datasetIndex].hidden},onClick:()=>{}}}function Mk(e,t){const s=e.fillArea??!1,o=s?"rect":"line",i=s?2:3;return{...kk,...Tk(e),...Lk(Uy(e.background),{pointStyle:o,lineWidth:i})}}function Nk(e,t){const s=Uy(e.background);return{...Tk(e),labels:{usePointStyle:!0,generateLabels:e=>{const t=e.data.datasets.at(-1);if(!t)return[];return t.groupColors.map(({color:e,label:t})=>({text:Ky(t),fontColor:s,fillStyle:e,strokeStyle:e,pointStyle:"rect"}))}}}}const kk={onHover:e=>{const t=e.native?.target;t&&(t.style.cursor="pointer")},onLeave:e=>{const t=e.native?.target;t&&(t.style.cursor="default")},onClick:(e,t,s)=>{if("click"!==e.type)return;const o=t.datasetIndex;s.legendItems&&void 0!==o&&(s.chart.isDatasetVisible(o)?s.chart.hide(o):s.chart.show(o),e.native.preventDefault(),e.native.stopPropagation())}};function Lk(e,t){return{labels:{color:e,usePointStyle:!0,generateLabels:s=>s.data.datasets.map((o,i)=>Jy(o.xAxisID)?{text:Ky(o.label),fontColor:e,strokeStyle:o.borderColor,hidden:!s.isDatasetVisible(i),pointStyle:"line",datasetIndex:i,lineWidth:3}:{text:Ky(o.label),fontColor:e,strokeStyle:o.borderColor,fillStyle:o.backgroundColor,hidden:!s.isDatasetVisible(i),pointStyle:"line"===o.type?"line":"rect",datasetIndex:i,...t}).filter(e=>e.text),filter:(e,t)=>!("datasetIndex"in e)||!t.datasets[e.datasetIndex].hidden}}}function Vk(e,t){const{axisFormats:s,locale:o}=t;return{type:e.type,horizontal:"horizontal"in e&&e.horizontal,showValues:"showValues"in e&&!!e.showValues,background:()=>e.background,callback:(t,i)=>{const n=function(e,t){if(t.rAxisID)return t.rAxisID;const s="horizontal"in e&&e.horizontal?t.xAxisID:t.yAxisID;return s||"y"}(e,i);return Zy(s,o,e.humanize)(t,n)}}}function zk(e,t){const{locale:s,axisFormats:o}=t;let i=(t,s,o)=>e.background;const n=t.dataSetsValues.flat().map(e=>e?.data.filter(e=>null!=e)).flat()||[];if(n.length){const t=Math.min(...n),s=Math.max(...n),o=YM(e.colorScale??w_("oranges"),t,s);i=(t,s,i)=>{const n=s._dataset.values[i];return void 0===n?e.background:Uy(o(n))}}return{type:"calendar",horizontal:!1,showValues:"showValues"in e&&!!e.showValues,background:i,callback:(e,t,i)=>{const n=t._dataset.values[i];return void 0===n?"":rn({value:n,format:o?.y},s)}}}function Hk(e,t){const{axisFormats:s,locale:o}=t;return{callback:Zy(s,o,e.humanize),showLabels:e.showLabels??E_.showLabels,showValues:e.showValues??E_.showValues,style:{fontSize:e.valuesDesign?.fontSize??E_.valuesDesign.fontSize,align:e.valuesDesign?.align??E_.valuesDesign.align,bold:e.valuesDesign?.bold??E_.valuesDesign.bold,italic:e.valuesDesign?.italic??E_.valuesDesign.italic,textColor:e.valuesDesign?.color??E_.valuesDesign.color}}}function Uk(e,t){const{axisFormats:s,locale:o}=t;return{type:"pyramid",horizontal:!0,showValues:"showValues"in e&&!!e.showValues,background:()=>e.background,callback:(e,t)=>0===(e=Math.abs(Number(e)))?"":Zy(s,o)(e,t.xAxisID||"x")}}function Bk(e,t){const{axisFormats:s,locale:o,dataSetsValues:i}=t,n=i.reduce((e,t)=>(e.push((e.at(-1)||-1)+t.data.length+1),e),[]);return{type:"waterfall",showValues:"showValues"in e&&!!e.showValues,background:()=>e.background,callback:(t,i,r)=>{const a=i._dataset.data[r],l=a[1]-a[0];let c=l>=0?"+":"";return e.showSubTotals&&n.includes(r)&&"+"===c&&(c=""),`${c}${Zy(s,o,e.humanize)(l,i.yAxisID)}`}}}function Gk(e,t){const s=e.title,o=By(e.background);return{display:!!s.text,text:s.text?t.dynamicTranslate(s.text):"",color:s?.color??o,align:"center"===s.align?"center":"right"===s.align?"end":"start",font:{size:e.title.fontSize??T,weight:s.bold?"bold":"normal",style:s.italic?"italic":"normal"},padding:{bottom:"top"===e.legendPosition?0:E}}}const Wk='\n<templates>\n <t t-name="o-spreadsheet-CustomTooltip">\n <div\n class="o-chart-custom-tooltip border rounded px-2 py-1 pe-none mw-100 position-absolute text-nowrap shadow opacity-100">\n <table class="overflow-hidden m-0">\n <thead t-if="title">\n <tr>\n <th class="o-tooltip-title align-baseline border-0 text-truncate" t-esc="title" t-attf-style="max-width: {{ labelsMaxWidth }}"/>\n </tr>\n </thead>\n <tbody>\n <tr t-foreach="tooltipItems" t-as="tooltipItem" t-key="tooltipItem_index">\n <td>\n <span\n class="badge ps-2 py-2 rounded-0 align-middle"\n t-attf-style="background-color: {{ tooltipItem.boxColor }}"\n > </span>\n <small\n t-if="tooltipItem.label"\n class="o-tooltip-label d-inline-block text-truncate align-middle smaller ms-2"\n t-esc="tooltipItem.label"\n t-attf-style="max-width: {{ labelsMaxWidth }}"\n />\n </td>\n <td class="o-tooltip-value ps-2 fw-bolder text-end">\n <small class="smaller d-inline-block text-truncate align-middle" t-attf-style="max-width: {{ valuesMaxWidth }}">\n <t t-esc="tooltipItem.value"/>\n <t t-if="tooltipItem.percentage">\n (\n <t t-esc="tooltipItem.percentage"/>\n %)\n </t>\n </small>\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n </t>\n</templates>\n';let $k;function qk(e,s={}){return function(e,s={}){$k||($k=new t.App(t.Component,{templates:Wk,translateFn:Cs}));const o=$k.getTemplate(e),i=o(s,{}),n=document.createElement("div");return t.blockDom.mount(i,n),n}(e,s).innerHTML}function Zk(e,t){return{enabled:!1,external:iL,callbacks:{title:function(e){return e.some(e=>!Jy(e.dataset.xAxisID))?void 0:""},beforeLabel:e=>e.dataset?.label||e.label,label:function(s){const o=e.horizontal;let i=o?s.parsed.x:s.parsed.y;null==i&&(i=s.parsed);const n=o?s.dataset.xAxisID:s.dataset.yAxisID;return Zy(t.axisFormats,t.locale,e.humanize)(i,n)}}}}function jk(e,t){const{locale:s,axisFormats:o}=t;return{enabled:!1,filter:e=>void 0!==e.dataset.values[e.dataIndex],external:iL,callbacks:{title:e=>"",beforeLabel:e=>`${e.dataset?.label}, ${e.label}`,label:function(e){return rn({value:e.dataset.values[e.dataIndex],format:o?.y},s)}}}}function Yk(e,t){const{axisType:s,locale:o,axisFormats:i}=t,n=i?.x,r={enabled:!1,external:iL,callbacks:{}};return r.callbacks.label="linear"===s?t=>{const s=t.parsed.y;let r=Jy(t.dataset.xAxisID)?"":t.parsed.x;"string"==typeof r&&mo(r,o)&&(r=Eo(r,o));const a=Vi(r,n,o,e.humanize),l=t.dataset.yAxisID||"y",c=Vi(s,i?.[l],o,e.humanize);return a?`(${a}, ${c})`:`${c}`}:function(t){const s=t.parsed.y,n=t.dataset.yAxisID;return Zy(i,o,e.humanize)(s,n)},r.callbacks.beforeLabel=e=>e.dataset?.label||e.label,r.callbacks.title=function(e){return"linear"!==s&&e.some(e=>!Jy(e.dataset.xAxisID))?void 0:""},r}function Xk(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;return{enabled:!1,external:iL,callbacks:{title:function(e){return e[0].dataset.label},beforeLabel:e=>e.label||e.dataset.label,label:function(t){const o=function(e,t){const s=e.filter(e=>"number"==typeof e).reduce((e,t)=>e+t,0);if(!s)return"";const o=e[t]/s*100;return o.toFixed(2)}(t.dataset.data,t.dataIndex),n=t.parsed.y??t.parsed;return`${Vi(n,!i&&n>=1e3?"#,##":i,s,e.humanize)} (${o}%)`}}}}function Kk(e,t){const{dataSetsValues:s,locale:o,axisFormats:i,labels:n}=t,r=i?.y||i?.y1,a=s.map(e=>e.label);return{enabled:!1,external:iL,callbacks:{beforeLabel:function(e){const t=n.length?Math.floor(e.dataIndex/n.length):0;return a[t]},label:function(t){const[s,i]=t.raw,n=i-s;return Vi(n,!r&&Math.abs(n)>1e3?"#,##":r,o,e.humanize)}}}}function Jk(e,t){const s=Zk(e,t);return{...s,callbacks:{...s.callbacks,label:e=>{const t={...e,parsed:{y:e.parsed.y,x:Math.abs(e.parsed.x)}};return(s?.callbacks?.label)(t)}}}}function Qk(e,t){const{locale:s,axisFormats:o}=t;return{enabled:!1,external:iL,callbacks:{beforeLabel:e=>e.dataset?.label||e.label,label:function(t){return Vi(t.parsed.r,o?.r,s,e.humanize)}}}}function eL(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;return{enabled:!1,external:iL,filter:function(e){return void 0!==e.raw.value},callbacks:{beforeLabel:e=>e.raw.feature.properties.name,label:function(t){const o=t.raw.value;return Vi(o,!i&&Math.abs(o)>=1e3?"#,##":i,s,e.humanize)}}}}function tL(e,t){return{enabled:!1,external:iL,position:"funnelTooltipPositioner",callbacks:{title:()=>"",beforeLabel:e=>e.label,label:function(s){const o=s.parsed.x,i=s.dataset.xAxisID;return Zy(t.axisFormats,t.locale,e.humanize)(o,i)}}}}function sL(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;return{enabled:!1,external:iL,filter:function(e){const t=e.raw;return t?.label!==KM},callbacks:{title:()=>"",beforeLabel:e=>e.raw.groups.join(" / "),label:function(t){const o=t.raw.value;return Vi(o,!i&&o>=1e3?"#,##":i,s,e.humanize)}}}}function oL(e,t){const{locale:s,axisFormats:o}=t,i=o?.y;return{enabled:!1,external:iL,filter:(e,t,s)=>t===s.length-1,callbacks:{title:()=>"",beforeLabel:e=>{const t=e.raw._data.children[0];if(!t)return"";const s=[];for(let o=0;o<=e.raw.l;o++)s.push(t[o]);return s.join(" / ")},label:t=>{const o=t.raw.v;return Vi(o,!i&&o>=1e3?"#,##":i,s,e.humanize)}}}}function iL({chart:e,tooltip:t}){if(e.canvas.parentNode.querySelector("div.o-chart-custom-tooltip")?.remove(),0===t.opacity||0===t.dataPoints.length)return;const s=t.body.map((e,s)=>{let o=e.before[0],i=e.lines[0];i||(i=o,o="");const n=t.labelColors[s].backgroundColor;return{label:o,value:i,boxColor:"string"==typeof n?ab(n,1):n}}),o=qk("o-spreadsheet-CustomTooltip",{labelsMaxWidth:Math.floor(.5*e.canvas.clientWidth)+"px",valuesMaxWidth:Math.floor(.25*e.canvas.clientWidth)+"px",title:t.title[0],tooltipItems:s}),i=Object.assign(document.createElement("template"),{innerHTML:o}).content.firstChild;e.canvas.parentNode?.appendChild(i),Object.assign(i.style,{left:nL(e,t,i.clientWidth)+"px",top:Math.floor(t.caretY-i.clientHeight/2)+"px"})}function nL(e,t,s){const o=t.caretX;return o+s>e.chartArea.right?Math.max(0,o-s):o}var rL=Object.freeze({__proto__:null,GHOST_SUNBURST_VALUE:KM,INTERACTIVE_LEGEND_CONFIG:kk,canChartParseLabels:uk,getBarChartData:QN,getBarChartDatasets:JM,getBarChartLegend:Ak,getBarChartScales:kM,getBarChartTooltip:Zk,getCalendarChartData:tk,getCalendarChartDatasetAndLabels:QM,getCalendarChartLayout:Rk,getCalendarChartScales:LM,getCalendarChartShowValues:zk,getCalendarChartTooltip:jk,getCalendarColorScale:VM,getChartColorsGenerator:vN,getChartLabelFormat:Sk,getChartLayout:xk,getChartShowValues:Vk,getChartTitle:Gk,getComboChartDatasets:iN,getComboChartLegend:Fk,getData:fk,getFunnelChartData:ak,getFunnelChartDatasets:aN,getFunnelChartScales:$M,getFunnelChartTooltip:tL,getFunnelLabelColors:lN,getGeoChartData:rk,getGeoChartDatasets:rN,getGeoChartScales:WM,getGeoChartTooltip:eL,getHierarchalChartData:lk,getLineChartData:ok,getLineChartDatasets:tN,getLineChartLegend:_k,getLineChartScales:zM,getLineChartTooltip:Yk,getPieChartData:ik,getPieChartDatasets:oN,getPieChartLegend:Dk,getPieChartTooltip:Xk,getPyramidChartData:sk,getPyramidChartScales:BM,getPyramidChartShowValues:Uk,getPyramidChartTooltip:Jk,getRadarChartData:nk,getRadarChartDatasets:nN,getRadarChartLegend:Mk,getRadarChartScales:GM,getRadarChartTooltip:Qk,getRuntimeColorScale:YM,getScatterChartDatasets:sN,getScatterChartLegend:Ok,getScatterChartScales:HM,getSunburstChartDatasets:cN,getSunburstChartLegend:Nk,getSunburstChartTooltip:sL,getSunburstShowValues:Hk,getTopPaddingForDashboard:Ek,getTreeMapChartDatasets:gN,getTreeMapChartTooltip:oL,getTrendDatasetForBarChart:ck,getTrendDatasetForLineChart:hk,getWaterfallChartLegend:Pk,getWaterfallChartScales:UM,getWaterfallChartShowValues:Bk,getWaterfallChartTooltip:Kk,getWaterfallDatasetAndLabels:eN,makeDatasetsCumulative:wk});class aL extends zO{dataSets;labelRange;background;legendPosition;stacked;aggregated;type="bar";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.horizontal=e.horizontal,this.showValues=e.showValues,this.zoomable=e.zoomable}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"bar",labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,showValues:e.showValues,horizontal:e.horizontal,zoomable:e.zoomable,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new aL(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new aL(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"bar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated,axesDesign:this.axesDesign,horizontal:this.horizontal,showValues:this.showValues,zoomable:this.horizontal?void 0:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,$y(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:IP(this.background||c),fontColor:IP(Uy(this.background)),dataSets:e,labelRange:t,verticalAxis:qy(s)}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new aL(i,this.sheetId,this.getters)}}function lL(e,t){const s=e.getDefinition(),o=QN(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:JM(s,o)},options:{...eF,indexAxis:e.horizontal?"y":"x",layout:xk(0,o),scales:kM(s,o),plugins:{title:Gk(s,t),legend:Ak(s),tooltip:Zk(s,o),chartShowValuesPlugin:Vk(s,o)}}},background:e.background||c}}function cL(e){return e.dataRange&&!mr.test(e.dataRange)?"InvalidGaugeDataRange":"Success"}function hL(e,t){return t(t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):"Success",t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):"Success")}function dL(e,t){if(""===e)switch(t){case"rangeMin":return"EmptyGaugeRangeMin";case"rangeMax":return"EmptyGaugeRangeMax"}return"Success"}function uL(e,t){if(e.startsWith("="))return"Success";if(isNaN(e))switch(t){case"rangeMin":return"GaugeRangeMinNaN";case"rangeMax":return"GaugeRangeMaxNaN";case"lowerInflectionPointValue":return"GaugeLowerInflectionPointNaN";case"upperInflectionPointValue":return"GaugeUpperInflectionPointNaN"}return"Success"}class gL extends zO{dataRange;sectionRule;background;type="gauge";constructor(e,t,s){super(e,t,s),this.dataRange=Jb(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,cL,e.chainValidations(hL(dL,e.batchValidations),hL(uL,e.batchValidations)),e.chainValidations((s=uL,(0,e.batchValidations)(e=>e.sectionRule?s(e.sectionRule.lowerInflectionPoint.value,"lowerInflectionPointValue"):"Success",e=>e.sectionRule?s(e.sectionRule.upperInflectionPoint.value,"upperInflectionPointValue"):"Success"))));var s}static transformDefinition(e,t,s){let o;if(t.dataRange){const i=Ty(e,t.dataRange,s);i!==ws.InvalidReference&&(o=i)}return{...t,dataRange:o}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||{text:""},type:"gauge",dataRange:e.range?.[0]?.dataRange,sectionRule:{colors:{lowerColor:"#EA6175",middleColor:"#FFD86D",upperColor:"#43C5B1"},rangeMin:"0",rangeMax:"100",lowerInflectionPoint:{type:"percentage",value:"15",operator:"<="},upperInflectionPoint:{type:"percentage",value:"40",operator:"<="}},humanize:e.humanize}}duplicateInDuplicatedSheet(e){const t=My(this.sheetId,e,this.dataRange),s=vL(this.sectionRule,t=>this.getters.copyFormulaStringForSheet(this.sheetId,e,t,"moveReference")),o=this.getDefinitionWithSpecificRanges(t,s,e);return new gL(o,e,this.getters)}copyInSheetId(e){const t=vL(this.sectionRule,t=>this.getters.copyFormulaStringForSheet(this.sheetId,e,t,"keepSameReference")),s=this.getDefinitionWithSpecificRanges(this.dataRange,t,e);return new gL(s,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.dataRange,this.sectionRule)}getDefinitionWithSpecificRanges(e,t,s){return{background:this.background,sectionRule:t,title:this.title,type:"gauge",dataRange:e?this.getters.getRangeString(e,s||this.sheetId):void 0,humanize:this.humanize}}getDefinitionForExcel(){}getContextCreation(){return{...this,range:this.dataRange?[{dataRange:this.getters.getRangeString(this.dataRange,this.sheetId)}]:void 0}}updateRanges(e,t,s){const o=Ny(this.dataRange,e),i=vL(this.sectionRule,o=>Ry(this.sheetId,o,{applyChange:e,sheetId:t,sheetName:s})),n=this.getDefinitionWithSpecificRanges(o,i);return new gL(n,this.sheetId,this.getters)}}function pL(e,t){const s=t.getLocale(),o=e.sectionRule.colors;let i,n,r;const a=e.dataRange;if(void 0!==a){const e=t.getEvaluatedCell({sheetId:a.sheetId,col:a.zone.left,row:a.zone.top});e.type===Xd.number&&(i=e.value,n=e.formattedValue,r=e.format)}let l=fL(e.sheetId,e.sectionRule.rangeMin,t),c=fL(e.sheetId,e.sectionRule.rangeMax,t);if(void 0===l||void 0===c)return function(e,t){return{background:t.getStyleOfSingleCellChart(e.background,e.dataRange).background,title:e.title??{text:""},minValue:{value:0,label:""},maxValue:{value:100,label:""},gaugeValue:{value:0,label:ws.GenericError},inflectionValues:[],colors:[]}}(e,t);c<l&&([l,c]=[c,l]);const h=e.sectionRule.lowerInflectionPoint,d=e.sectionRule.upperInflectionPoint,u=mL(e.sheetId,e.sectionRule.lowerInflectionPoint,l,c,t),g=mL(e.sheetId,e.sectionRule.upperInflectionPoint,l,c,t),p=[],m=[];return void 0!==u&&(p.push({value:u,label:Vi(u,r,s,e.humanize),operator:h.operator}),m.push(o.lowerColor)),void 0!==g&&g!==u&&(p.push({value:g,label:Vi(g,r,s,e.humanize),operator:d.operator}),m.push(o.middleColor)),void 0!==g&&void 0!==u&&u>g&&(p.reverse(),m.reverse()),m.push(o.upperColor),{background:t.getStyleOfSingleCellChart(e.background,a).background,title:{...e.title,text:e.title.text?t.dynamicTranslate(e.title.text):""},minValue:{value:l,label:Vi(l,r,s,e.humanize)},maxValue:{value:c,label:Vi(c,r,s,e.humanize)},gaugeValue:void 0!==i&&n?{value:i,label:e.humanize?rn({value:i,format:r},s):n}:void 0,inflectionValues:p,colors:m}}function mL(e,t,s,o,i){const n=fL(e,t.value,i);if(void 0===n)return;return me("number"===t.type?n:s+(o-s)*n/100,s,o)}function fL(e,t,s){const o=s.evaluateFormula(e,t);return _n(o)?void 0:xo(Tn(o),s.getLocale())}function vL(e,t){return{...e,rangeMin:t(e.rangeMin),rangeMax:t(e.rangeMax),lowerInflectionPoint:{...e.lowerInflectionPoint,value:t(e.lowerInflectionPoint.value)},upperInflectionPoint:{...e.upperInflectionPoint,value:t(e.upperInflectionPoint.value)}}}class bL extends zO{dataSets;labelRange;background;legendPosition;labelsAsText;stacked;aggregated;type="line";dataSetsHaveTitle;cumulative;dataSetDesign;axesDesign;fillArea;showValues;hideDataMarkers;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=ky(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.cumulative=e.cumulative,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.fillArea=e.fillArea,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers,this.zoomable=e.zoomable}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static transformDefinition(e,t,s){return Hy(e,t,s)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"line",labelRange:e.auxiliaryRange||void 0,stacked:e.stacked??!1,aggregated:e.aggregated??!1,cumulative:e.cumulative??!1,axesDesign:e.axesDesign,fillArea:e.fillArea,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"line",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,stacked:this.stacked,aggregated:this.aggregated,cumulative:this.cumulative,axesDesign:this.axesDesign,fillArea:this.fillArea,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,zoomable:this.zoomable,humanize:this.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new bL(i,this.sheetId,this.getters)}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,$y(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:IP(this.background||c),fontColor:IP(Uy(this.background)),dataSets:e,labelRange:t,verticalAxis:qy(s)}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new bL(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new bL(t,e,this.getters)}}function SL(e,t){const s=e.getDefinition(),o=ok(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"line",data:{labels:o.labels,datasets:tN(s,o)},options:{...eF,layout:xk(0,o),scales:zM(s,o),plugins:{title:Gk(s,t),legend:_k(s),tooltip:Yk(s,o),chartShowValuesPlugin:Vk(s,o)}}},background:e.background||c}}class yL extends zO{dataSets;labelRange;background;legendPosition;type="pie";aggregated;dataSetsHaveTitle;isDoughnut;showValues;pieHolePercentage;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.isDoughnut=e.isDoughnut,this.showValues=e.showValues,this.pieHolePercentage=e.pieHolePercentage}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"pie",labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,isDoughnut:e.isDoughnut,pieHolePercentage:e.pieHolePercentage,showValues:e.showValues,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{...this,range:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)})),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,s){return{type:"pie",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,isDoughnut:this.isDoughnut,showValues:this.showValues,pieHolePercentage:this.pieHolePercentage,humanize:this.humanize}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new yL(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new yL(t,e,this.getters)}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,$y(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:IP(this.background||c),fontColor:IP(Uy(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new yL(i,this.sheetId,this.getters)}}function CL(e,t){const s=e.getDefinition(),o=ik(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:e.isDoughnut?"doughnut":"pie",data:{labels:o.labels,datasets:oN(s,o)},options:{...eF,cutout:e.isDoughnut&&void 0!==s.pieHolePercentage?s.pieHolePercentage+"%":void 0,layout:xk(0,o),plugins:{title:Gk(s,t),legend:Dk(s,o),tooltip:Xk(s,o),chartShowValuesPlugin:Vk(s,o)}}},background:e.background||c}}class IL extends zO{dataSets;labelRange;background;verticalAxisPosition;legendPosition;aggregated;type="waterfall";dataSetsHaveTitle;showSubTotals;firstValueAsSubtotal;showConnectorLines;positiveValuesColor;negativeValuesColor;subTotalValuesColor;dataSetDesign;axesDesign;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showSubTotals=e.showSubTotals,this.showConnectorLines=e.showConnectorLines,this.positiveValuesColor=e.positiveValuesColor,this.negativeValuesColor=e.negativeValuesColor,this.subTotalValuesColor=e.subTotalValuesColor,this.firstValueAsSubtotal=e.firstValueAsSubtotal,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.zoomable=e.zoomable}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"waterfall",verticalAxisPosition:"left",labelRange:e.auxiliaryRange||void 0,showSubTotals:e.showSubTotals??!1,showConnectorLines:e.showConnectorLines??!0,firstValueAsSubtotal:e.firstValueAsSubtotal??!1,axesDesign:e.axesDesign,showValues:e.showValues,zoomable:e.zoomable??!1,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new IL(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new IL(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"waterfall",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,showSubTotals:this.showSubTotals,showConnectorLines:this.showConnectorLines,positiveValuesColor:this.positiveValuesColor,negativeValuesColor:this.negativeValuesColor,subTotalValuesColor:this.subTotalValuesColor,firstValueAsSubtotal:this.firstValueAsSubtotal,axesDesign:this.axesDesign,showValues:this.showValues,zoomable:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new IL(i,this.sheetId,this.getters)}}function wL(e,t){const s=e.getDefinition(),o=QN(s,e.dataSets,e.labelRange,t),{labels:i,datasets:n}=eN(s,o);return{chartJsConfig:{type:"bar",data:{labels:i,datasets:n},options:{...eF,layout:xk(0,o),scales:UM(s,o),plugins:{title:Gk(s,t),legend:Pk(s),tooltip:Kk(s,o),chartShowValuesPlugin:Bk(s,o),waterfallLinesPlugin:{showConnectorLines:s.showConnectorLines}}}},background:e.background||c}}var EL=Object.freeze({__proto__:null,AbstractChart:zO,BarChart:aL,CHART_AXIS_CHOICES:Yy,CHART_COMMON_OPTIONS:eF,GaugeChart:gL,LineChart:bL,MOVING_AVERAGE_TREND_LINE_XAXIS_ID:Dy,PieChart:yL,SPREADSHEET_TO_EXCEL_TRENDLINE_TYPE_MAPPING:Oy,ScorecardChart:ZO,TREND_LINE_XAXIS_ID:_y,WaterfallChart:IL,adaptChartRange:Ny,chartFactory:bR,chartFontColor:Uy,chartMutedFontColor:By,chartRuntimeFactory:SR,chartToImageFile:sF,chartToImageUrl:tF,checkDataset:Gy,checkLabelRange:Wy,createBarChartRuntime:lL,createDataSets:ky,createGaugeChartRuntime:pL,createLineChartRuntime:SL,createPieChartRuntime:CL,createScorecardChartRuntime:YO,createWaterfallChartRuntime:wL,drawScoreChart:jO,duplicateDataSetsInDuplicatedSheet:Py,duplicateLabelRangeInDuplicatedSheet:My,formatChartDatasetValue:Zy,formatTickValue:jy,getChartPositionAtCenterOfViewport:function(e,t){const{x:s,y:o}=e.getMainViewportCoordinates(),{scrollX:i,scrollY:n}=e.getActiveSheetScrollInfo(),{width:r,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:s+i+Math.max(0,(r-t.width)/2),y:o+n+Math.max(0,(a-t.height)/2)}},getDefinedAxis:qy,getPieColors:Xy,isTrendLineAxis:Jy,shouldRemoveFirstLabel:$y,toExcelDataset:Vy,toExcelLabelRange:zy,transformChartDefinitionWithDataSetsWithZone:Hy,transformDefinition:CR,truncateLabel:Ky,updateChartRangesWithDataSets:Fy,validateChartDefinition:yR});function xL(e,t){if(!t.model.getters.getChartIdFromFigureId(e))return[];return Sv([{id:"edit",name:Cs("Edit"),execute:()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e}),t.openSidePanel("ChartPanel")},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall},RL(e,t),TL(e,t),AL(e,t),_L(e,t),DL(e,t)]).filter(e=>!t.model.getters.isReadonly()||e.isReadonlyAllowed)}function RL(e,t,s){return{id:"copy",name:Cs("Copy"),description:"Ctrl+C",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e}),t.model.dispatch("COPY");const o=await t.model.getters.getClipboardTextAndImageContent();await t.clipboard.write(o),s&&t.notifyUser({sticky:!1,type:"success",text:s})},icon:"o-spreadsheet-Icon.CLIPBOARD"}}function TL(e,t){return{id:"cut",name:Cs("Cut"),description:"Ctrl+X",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e}),t.model.dispatch("CUT"),await t.clipboard.write(await t.model.getters.getClipboardTextAndImageContent())},icon:"o-spreadsheet-Icon.CUT"}}function AL(e,t){return{id:"copy_as_image",name:Cs("Copy as image"),icon:"o-spreadsheet-Icon.COPY_AS_IMAGE",execute:async()=>{const s=t.model.getters.getFigureSheetId(e),o=t.model.getters.getFigure(s,e),i=t.model.getters.getChartIdFromFigureId(e);if(!i)return;const n=t.model.getters.getChartType(i),r=t.model.getters.getChartRuntime(i),a=await sF(r,o,n);if(!a)return;const l=await new Promise(e=>{const t=new FileReader;t.addEventListener("loadend",s=>{const o=t.result;e(o)}),t.readAsArrayBuffer(a)}),c=`<img src="data:image/png;base64,${new Uint8Array(l).toBase64()}" />`;t.clipboard.write({"text/html":c,"image/png":a}),t.notifyUser({sticky:!1,type:"success",text:Cs("Chart copied to clipboard")})},isReadonlyAllowed:!0}}function _L(e,t){return{id:"download",name:Cs("Download"),icon:"o-spreadsheet-Icon.DOWNLOAD",execute:async()=>{const s=t.model.getters.getFigureSheetId(e),o=t.model.getters.getFigure(s,e),i=t.model.getters.getChartIdFromFigureId(e);if(!i)return;const n=t.model.getters.getChartType(i),r=t.model.getters.getChartRuntime(i),a=await tF(r,o,n);a&&UN(a,"chart")},isReadonlyAllowed:!0}}function DL(e,t){return{id:"delete",name:Cs("Delete"),execute:()=>{t.model.dispatch("DELETE_FIGURE",{sheetId:t.model.getters.getActiveSheetId(),figureId:e})},icon:"o-spreadsheet-Icon.TRASH"}}const OL=[_y,Dy],FL=["x",...OL];class PL extends Lv{mutators=["resetAxisLimits","updateAxisLimits","updateTrendLineConfiguration","clearAxisLimits"];originalAxisLimits={};currentAxesLimits={};idConversion={};handle(e){switch(e.type){case"DELETE_FIGURE":if(e.figureId&&this.idConversion[e.figureId])for(const t of this.idConversion[e.figureId])delete this.originalAxisLimits[t],delete this.currentAxesLimits[t];break;case"UPDATE_CHART":const t=`${e.definition.type}-${e.figureId}`;this.idConversion[e.figureId]||(this.idConversion[e.figureId]=new Set),this.idConversion[e.figureId].add(t),"zoomable"in e.definition&&e.definition.zoomable||this.clearAxisLimits(t)}}clearAxisLimits(e){return delete this.originalAxisLimits[e],delete this.currentAxesLimits[e],"noStateChange"}resetAxisLimits(e,t){for(const s of FL)t[s]?this.originalAxisLimits[e]={...this.originalAxisLimits[e],[s]:{...t[s]}}:this.originalAxisLimits[e]?.[s]&&delete this.originalAxisLimits[e][s];return"noStateChange"}updateAxisLimits(e,t){let{min:s,max:o}=t;return s>o&&([s,o]=[o,s]),this.currentAxesLimits[e]={x:{min:s,max:o}},"noStateChange"}updateTrendLineConfiguration(e){if(!this.originalAxisLimits[e]?.x||!this.currentAxesLimits[e]?.x)return"noStateChange";const t=this.originalAxisLimits[e].x;for(const s of OL){if(!this.originalAxisLimits[e][s])continue;const o=t.max-t.min,i=this.originalAxisLimits[e][s],n=(i.max-i.min)/o,r=i.min-t.min*n,a=this.currentAxesLimits[e].x.min,l=this.currentAxesLimits[e].x.max;this.currentAxesLimits[e][s]={min:a*n+r,max:l*n+r}}return"noStateChange"}}class ML extends xN{static template="o-spreadsheet-ZoomableChartJsComponent";store;masterChartCanvas=t.useRef("masterChartCanvas");masterChart;mode;hasLinearScale;isBarChart;chartId="";datasetBoundaries={min:0,max:0};removeEventListeners=()=>{};isMasterChartAllowed=!1;setup(){this.store=Tv(PL),super.setup()}unmount(){super.unmount(),this.masterChart?.destroy(),this.removeEventListeners()}get containerStyle(){return`\n height:${this.sliceable?"calc(100% - 60px)":"100%"};\n `}get masterChartContainerStyle(){const e=this.env.model.getters.getChartRuntime(this.props.chartId);return e&&!e.chartJsConfig.data.datasets.some(e=>e.data.length>1)?"opacity: 0.3;":""}get sliceable(){if(this.props.isFullScreen)return!0;const e=this.env.model.getters.getChartDefinition(this.props.chartId);return("zoomable"in e&&e.zoomable)??!1}get axisOffset(){return!this.hasLinearScale&&this.isBarChart?.5:0}getMasterChartConfiguration(e){const t=e;return{...t,options:{...t.options,plugins:{...t.options.plugins,zoomWindowPlugin:{getLowerBound:()=>this.lowerBound,getUpperBound:()=>this.upperBound}}}}}getDetailChartConfiguration(e){if(!this.sliceable)return e;let t=e.options.scales.x;const s=this.store.currentAxesLimits[this.chartId]?.x;return s&&(t={...t,...this.getStoredBoundaries()}),{...e,options:{...e.options,scales:{...e.options.scales,x:t},layout:{...e.options.layout,padding:{...e.options.layout?.padding,bottom:5}}}}}getAxisLimitsFromDataset(e){const t=e.data.datasets.map(e=>e.data).flat().map((e,t)=>"object"==typeof e&&null!==e?e.x:t);return{min:Math.min(...t),max:Math.max(...t)}}setMasterChartCursor(e){const t=this.masterChartCanvas?.el;if(e&&!e.chartJsConfig.data.datasets.some(e=>e.data.length>1))return t.style.cursor="not-allowed",void(this.isMasterChartAllowed=!1);t.style.cursor="default",this.isMasterChartAllowed=!0}createChart(e){if(!globalThis.Chart)throw new Error("Chart.js library is not loaded");const t=e.chartJsConfig;if(this.isBarChart="bar"===t.type,this.chartId=`${t.type}-${this.props.chartId}`,this.datasetBoundaries=this.getAxisLimitsFromDataset(t),this.sliceable){const s=this.getDetailChartConfiguration(t);e.chartJsConfig=s}if(super.createChart(e),this.hasLinearScale="linear"===this.chart?.scales?.x?.type,!this.sliceable||!("masterChartConfig"in e))return void(this.isMasterChartAllowed=!1);this.masterChart?.destroy();const s=(this.masterChartCanvas?.el).getContext("2d");this.setMasterChartCursor(e),this.masterChart=new globalThis.Chart(s,this.getMasterChartConfiguration(e.masterChartConfig)),this.resetAxesLimits(),this.chart?.options&&(this.chart.options.animation=!1)}updateChartJs(e){if(!globalThis.Chart)throw new Error("Chart.js library is not loaded");const t=e.chartJsConfig,{min:s,max:o}=this.getAxisLimitsFromDataset(t);if(this.datasetBoundaries.min===s&&this.datasetBoundaries.max===o||(this.store.clearAxisLimits(this.chartId),this.datasetBoundaries={min:s,max:o}),this.isBarChart="bar"===t?.type,this.chartId=`${t.type}-${this.props.chartId}`,this.sliceable){const s=this.getDetailChartConfiguration(t);e.chartJsConfig=s}if(super.updateChartJs(e),this.hasLinearScale="linear"===this.chart?.scales?.x?.type,this.sliceable&&"masterChartConfig"in e){const t=this.getMasterChartConfiguration(e.masterChartConfig);if(this.masterChart)this.masterChart.data=t.data,this.masterChart.config.options=t.options,this.masterChart.update();else{const e=this.masterChartCanvas.el.getContext("2d");this.masterChart=new globalThis.Chart(e,t)}this.setMasterChartCursor(e)}else this.masterChart=void 0,this.isMasterChartAllowed=!1;this.resetAxesLimits(),this.chart?.options&&(this.chart.options.animation=!1)}resetAxesLimits(){if(!this.chart)return;const e=this.store.originalAxisLimits[this.chartId]?.x;if(!e){let e=this.masterChart?this.masterChart.scales:this.chart.scales;return!this.hasLinearScale&&e.x&&(e={...e,x:this.adjustBoundaries(e.x)}),void this.store.resetAxisLimits(this.chartId,e)}this.updateTrendingLineAxes(),this.chart.update(),this.masterChart&&this.masterChart.update()}updateTrendingLineAxes(){this.store.updateTrendLineConfiguration(this.chartId);const e=this.store.currentAxesLimits[this.chartId];for(const t of[_y,Dy])this.chart?.config?.options?.scales?.[t]&&e?.[t]&&(this.chart.config.options.scales[t].min=e[t].min,this.chart.config.options.scales[t].max=e[t].max)}get upperBound(){return this.computePosition(this.store.currentAxesLimits[this.chartId]?.x?.max)}get lowerBound(){return this.computePosition(this.store.currentAxesLimits[this.chartId]?.x?.min)}computePosition(e){if(void 0===e||!this.masterChart?.scales?.x)return;const t=this.masterChart.scales.x;if(this.hasLinearScale)return t.getPixelForValue(e);if(!this.masterChart.chartArea)return;const{left:s,right:o}=this.masterChart.chartArea,{min:i,max:n}=t,r=this.axisOffset;return s+(o-s)*(r+e-i)/(2*r+n-i)}computeCoordinate(e){if(!this.masterChart)return;const t=this.masterChart.scales.x;if(this.hasLinearScale){const s=t.getValueForPixel(e);if(void 0===s)return;return Math.round(100*s)/100}const{left:s,right:o}=this.masterChart.chartArea,i=this.axisOffset;return t.min-i+(t.max+2*i-t.min)*(e-s)/(o-s)}getStoredBoundaries(){let{min:e,max:t}=this.store.currentAxesLimits[this.chartId].x;return this.hasLinearScale||(e=Math.ceil(e),t=Math.floor(t)),{min:e,max:t}}adjustBoundaries({min:e,max:t}){return this.hasLinearScale||(e=Math.ceil(e)-this.axisOffset,t=Math.floor(t)+this.axisOffset),{min:e,max:t}}updateAxisLimits(e,t){if(e===t)return;if(!this.chart)return;this.store.updateAxisLimits(this.chartId,{min:e,max:t});const{min:s,max:o}=this.getStoredBoundaries();(o>s||this.isBarChart&&o===s)&&(this.chart.config.options.scales.x.min=s,this.chart.config.options.scales.x.max=o,this.updateTrendingLineAxes(),this.chart.update()),this.masterChart?.update()}onMasterChartPointerDown(e){this.removeEventListeners();const t=$N(this.env,e,this.masterChartCanvas.el?.getBoundingClientRect()),s=t.offsetX;if(!this.masterChart?.chartArea||!this.chart?.scales?.x)return;const{left:o,right:i,top:n,bottom:r}=this.masterChart.chartArea,a=this.upperBound??i,l=this.lowerBound??o;if(s<o-5||s>i+5||t.offsetY<n||t.offsetY>r)return;let c,h,d;e.preventDefault(),e.stopPropagation();const u=s;if((l!==o||a!==i)&&s>l+5&&s<a-5){c=t.offsetX-l,this.mode="moveInMaster";const e=this.store.currentAxesLimits[this.chartId]?.x;h=(e?.max??this.chart.scales.x.max)-(e?.min??this.chart.scales.x.min)}else this.mode="selectInMaster",c=Math.abs(s-l)<5?a:Math.abs(s-a)<5?l:me(s,o,i),d=this.computeCoordinate(c);const g=this.store.originalAxisLimits[this.chartId].x.min,p=this.store.originalAxisLimits[this.chartId].x.max,m=e=>{if("moveInMaster"===this.mode){let t=this.computeCoordinate(e-c);return t<g?t=g:t>p-h&&(t=p-h),{min:t,max:t+h}}if("selectInMaster"===this.mode){const t=me(e,o,i);if(Math.abs(c-t)>5){const e=this.computeCoordinate(t);return void 0===d||void 0===e?{}:{min:Math.min(d,e),max:Math.max(d,e)}}}return{}},f=e=>{const t=$N(this.env,e,this.masterChartCanvas.el?.getBoundingClientRect()).offsetX;if(Math.abs(t-u)<5)return;const{min:s,max:o}=m(t);void 0!==s&&void 0!==o&&this.updateAxisLimits(s,o)},v=e=>{this.removeEventListeners();let{min:t,max:s}=this.chart.scales.x;this.hasLinearScale||("moveInMaster"===this.mode?(t=Math.round(t)-this.axisOffset,s=t+h):({min:t,max:s}=this.adjustBoundaries({min:t,max:s}))),this.updateAxisLimits(t,s),this.mode=void 0};this.removeEventListeners=()=>{window.removeEventListener("pointermove",f,!0),window.removeEventListener("pointerup",v,!0)},window.addEventListener("pointermove",f,!0),window.addEventListener("pointerup",v,!0)}onMasterChartPointerMove(e){const t=e.target,{offsetX:s,offsetY:o}=$N(this.env,e,t?.getBoundingClientRect());if(t&&this.isMasterChartAllowed&&void 0===this.mode){if(!this.masterChart?.chartArea)return void(t.style.cursor="default");const{left:e,right:i,top:n,bottom:r}=this.masterChart.chartArea,a=this.lowerBound??e,l=this.upperBound??i;o<n||o>r?t.style.cursor="default":Math.abs(a-s)<5||Math.abs(l-s)<5?t.style.cursor="ew-resize":t.style.cursor=a<s&&s<l&&(a!==e||l!==i)?"grab":"crosshair"}}onMasterChartMouseLeave(e){const t=e.target;t&&this.isMasterChartAllowed&&(t.style.cursor="default")}onMasterChartDoubleClick(e){this.mode=void 0;const t=$N(this.env,e,this.masterChartCanvas.el?.getBoundingClientRect()),s=t.offsetX;if(!this.masterChart?.chartArea||!this.chart?.scales.x)return;const{left:o,right:i,top:n,bottom:r}=this.masterChart.chartArea;let a=this.upperBound??i,l=this.lowerBound??o;if(a<l&&([a,l]=[l,a]),s<o-5||s>i+5||t.offsetY<n||t.offsetY>r)return;e.preventDefault(),e.stopPropagation();let{min:c,max:h}=this.store.currentAxesLimits[this.chartId]?.x??this.chart.scales.x;const d=this.store.originalAxisLimits[this.chartId].x;if(d){if(Math.abs(s-l)<5)c=d.min;else if(Math.abs(s-a)<5)h=d.max;else{if(!(l<s&&s<a))return;c=d.min,h=d.max}this.updateAxisLimits(c,h)}}}const NL=new Jg;NL.add("animatedBackgroundColorChange",{id:"animatedBackgroundColorChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>e?.style?.fillColor!==t?.style?.fillColor,updateAnimation:function(e,t,s,o){const i=xb([{value:0,color:s.style.fillColor||"#ffffff"},{value:1,color:o.style.fillColor||"#ffffff"}]);t.style.fillColor=i(kL[this.easingFn](e))}}),NL.add("animatedTextColorChange",{id:"animatedTextColorChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>e?.style?.textColor!==t?.style?.textColor,updateAnimation:function(e,t,s,o){const i=xb([{value:0,color:s.style.textColor||"#000000"},{value:1,color:o.style.textColor||"#000000"}]);t.style.textColor=i(kL[this.easingFn](e))}}),NL.add("animatedDataBar",{id:"animatedDataBar",easingFn:"easeOutCubic",hasAnimation:(e,t)=>e?.dataBarFill?.percentage!==t?.dataBarFill?.percentage,updateAnimation:function(e,t,s,o){const i=s?.dataBarFill?.percentage||0,n=i+((o?.dataBarFill?.percentage||0)-i)*kL[this.easingFn](e);t.dataBarFill={color:o.dataBarFill?.color||s.dataBarFill?.color||"#ffffff",percentage:n}}}),NL.add("textFadeIn",{id:"textFadeIn",easingFn:"easeInCubic",hasAnimation:(e,t)=>{const s=e?.content?.textLines?.join("\n"),o=t?.content?.textLines?.join("\n");return Boolean(!s&&o)},updateAnimation:function(e,t,s,o){t.textOpacity=kL[this.easingFn](e)}}),NL.add("textFadeOut",{id:"textFadeOut",easingFn:"easeOutCubic",hasAnimation:(e,t)=>{const s=e?.content?.textLines?.join("\n"),o=t?.content?.textLines?.join("\n");return Boolean(s&&!o)},updateAnimation:function(e,t,s,o){const i=1-kL[this.easingFn](e),n={...s.style};delete n.fillColor,t.textOpacity=i,t.content=s.content,t.clipRect=s.clipRect,Object.assign(t.style,n)}}),NL.add("iconFadeIn",{id:"iconFadeIn",easingFn:"easeInCubic",hasAnimation:(e,t)=>Boolean(!e?.icons?.left&&t?.icons?.left||!e?.icons?.right&&t?.icons?.right||!e?.icons?.center&&t?.icons?.center),updateAnimation:function(e,t,s,o){const i=kL[this.easingFn](e);t.icons.left&&o.icons.left&&!s.icons.left&&(t.icons.left.opacity=i),t.icons.right&&o.icons.right&&!s.icons.right&&(t.icons.right.opacity=i),t.icons.center&&o.icons.center&&!s.icons.center&&(t.icons.center.opacity=i)}}),NL.add("iconFadeOut",{id:"iconFadeOut",easingFn:"easeOutCubic",hasAnimation:(e,t)=>Boolean(e?.icons?.left&&!t?.icons?.left||e?.icons?.right&&!t?.icons?.right||e?.icons?.center&&!t?.icons?.center),updateAnimation:function(e,t,s,o){const i=1-kL[this.easingFn](e);t.icons||(t.icons={}),s.icons.left&&!o.icons.left&&(t.icons.left={...s.icons.left,opacity:i}),s.icons.right&&!o.icons.right&&(t.icons.right={...s.icons.right,opacity:i}),s.icons.center&&!o.icons.center&&(t.icons.center={...s.icons.center,opacity:i})}}),NL.add("textChange",{id:"textChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>{const s=e?.content?.textLines?.join("\n"),o=t?.content?.textLines?.join("\n");return Boolean(s&&o&&(s!==o||zL(t,e)))},updateAnimation:function(e,t,s,o){const i=kL[this.easingFn](e),n=o.y+(i-1)*o.height,r=o.y+i*o.height,a=zL(o,s),l={id:o.id+"-text-slide-in",x:o.x,y:n,width:o.width,height:o.height,style:{...o.style},skipCellGridLines:!0,content:o.content?{...o.content}:void 0,clipRect:o.clipRect||{...o,x:Math.max(0,o.x-(o.content?.width||0)),width:o.width+2*(o.content?.width||0)},icons:a?VL(o.icons,o):LL(o.icons)},c={id:s.id+"-text-slide-out",x:o.x,y:r,width:o.width,height:o.height,style:{...s.style},skipCellGridLines:!0,content:s.content?{...s.content}:void 0,clipRect:s.clipRect||{...o,x:Math.max(0,o.x-(s.content?.width||0)),width:o.width+2*(s.content?.width||0)},icons:a?VL(s.icons,o):LL(s.icons)};if(o.content&&s.content&&l.content&&c.content){const e=o.content.y+(i-1)*o.height,t=o.content.y+i*o.height;l.content.y=e,c.content.y=t}return c.style.fillColor=l.style.fillColor=void 0,t.content=void 0,t.icons=a?{}:t.icons,{newBoxes:[l,c]}}}),NL.add("borderFadeIn",{id:"borderFadeIn",easingFn:"easeInCubic",hasAnimation:(e,t)=>Boolean(!e?.border?.bottom&&t?.border?.bottom||!e?.border?.top&&t?.border?.top||!e?.border?.left&&t?.border?.left||!e?.border?.right&&t?.border?.right),updateAnimation:function(e,t,s,o){const i=kL[this.easingFn](e);t.border?.top&&o.border?.top&&!s.border?.top&&(t.border.top.opacity=i),t.border?.bottom&&o.border?.bottom&&!s.border?.bottom&&(t.border.bottom.opacity=i),t.border?.left&&o.border?.left&&!s.border?.left&&(t.border.left.opacity=i),t.border?.right&&o.border?.right&&!s.border?.right&&(t.border.right.opacity=i)}}),NL.add("borderFadeOut",{id:"borderFadeOut",easingFn:"easeOutCubic",hasAnimation:(e,t)=>Boolean(e?.border?.bottom&&!t?.border?.bottom||e?.border?.top&&!t?.border?.top||e?.border?.left&&!t?.border?.left||e?.border?.right&&!t?.border?.right),updateAnimation:function(e,t,s,o){const i=1-kL[this.easingFn](e);t.border||(t.border={}),s.border?.top&&!o.border?.top&&(t.border.top={...s.border.top,opacity:i}),s.border?.bottom&&!o.border?.bottom&&(t.border.bottom={...s.border.bottom,opacity:i}),s.border?.left&&!o.border?.left&&(t.border.left={...s.border.left,opacity:i}),s.border?.right&&!o.border?.right&&(t.border.right={...s.border.right,opacity:i})}}),NL.add("borderColorChange",{id:"borderColorChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>{const s=e?.border,o=t?.border;return!(!s||!o)&&Boolean(s.bottom?.color!==o.bottom?.color||s.top?.color!==o.top?.color||s.left?.color!==o.left?.color||s.right?.color!==o.right?.color)},updateAnimation:function(e,t,s,o){const i=i=>{const n=s?.border?.[i],r=o?.border?.[i],a=t.border?.[i];if(n&&r&&a){const t=xb([{value:0,color:n.color||"#000000"},{value:1,color:r.color||"#000000"}]);a.color=t(kL[this.easingFn](e))}};i("top"),i("bottom"),i("left"),i("right")}}),NL.add("iconChange",{id:"iconChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>!zL(t,e)&&Boolean(e?.icons?.center?.svg?.name!==t?.icons?.center?.svg?.name||e?.icons?.left?.svg?.name!==t?.icons?.left?.svg?.name||e?.icons?.right?.svg?.name!==t?.icons?.right?.svg?.name),updateAnimation:function(e,t,s,o){const i=kL[this.easingFn](e),n=o.y+(i-1)*o.height,r=o.y+i*o.height,a=[],l=e=>{const i=s.icons?.[e],l=o.icons?.[e],c={id:`${o.id}-icon-${e}-slide-in`,style:{verticalAlign:o.style.verticalAlign},x:o.x,y:n,width:o.width,height:o.height,skipCellGridLines:!0,icons:{[e]:{...l,clipRect:o}}},h={id:`${o.id}-icon-${e}-slide-out`,style:{verticalAlign:s.style.verticalAlign},x:o.x,y:r,width:o.width,height:o.height,skipCellGridLines:!0,icons:{[e]:{...i,clipRect:o}}};t.icons[e]=LL(o.icons)[e],a.push(c,h)};return l("left"),l("right"),l("center"),{newBoxes:a}}});const kL={linear:e=>e,easeInCubic:e=>e*e*e,easeOutCubic:e=>(e-=1)*e*e+1,easeInOutCubic:e=>(e/=.5)<1?.5*e*e*e:.5*((e-=2)*e*e+2),easeOutQuart:e=>-((e-=1)*e*e*e-1)};function LL(e){return{left:e.left?{...e.left,svg:void 0}:void 0,right:e.right?{...e.right,svg:void 0}:void 0,center:e.center?{...e.center,svg:void 0}:void 0}}function VL(e,t){return{left:e.left?{...e.left,clipRect:t}:void 0,right:e.right?{...e.right,clipRect:t}:void 0,center:e.center?{...e.center,clipRect:t}:void 0}}function zL(e,t){const s=(e,t)=>t&&e?!!(e.horizontalAlign!==t.horizontalAlign||e.size!==t.size||e.margin!==t.margin||e.svg&&!t.svg||!e.svg&&t.svg):!!(e&&!t||!e&&t);return s(e?.icons.left,t?.icons.left)||s(e?.icons.right,t?.icons.right)||s(e?.icons.center,t?.icons.center)}class HL extends t.Component{static template="o-spreadsheet-GaugeChartComponent";static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=t.useRef("chartContainer");animationStore;get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}setup(){this.env.model.getters.isDashboard()&&(this.animationStore=Tv(VS));let e,s=null;t.useEffect(()=>(this.env.isDashboard()&&void 0===e&&"gauge"!==this.animationStore?.animationPlayed[this.animationChartId]||this.env.isDashboard()&&void 0!==e&&!Le(this.runtime,e)?(s=this.drawGaugeWithAnimation(),this.animationStore?.disableAnimationForChart(this.animationChartId,"gauge")):FO(this.canvasEl,this.runtime),e=this.runtime,()=>s?.stop()),()=>{const e=this.canvasEl.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}drawGaugeWithAnimation(){FO(this.canvasEl,{...this.runtime,animationValue:0},void 0);const e=this.runtime.gaugeValue?.value||0,t=this.runtime.maxValue.value,s=Math.sign(e)*Math.min(Math.abs(e),Math.abs(t));if(0===s)return null;const o=this.runtime.minValue.value,i=new UL(o,s,1e3,e=>FO(this.canvasEl,{...this.runtime,animationValue:e},void 0));return i.start(),i}get canvasEl(){return this.canvas.el}get animationChartId(){return this.props.isFullScreen?this.props.chartId+"-fullscreen":this.props.chartId}}class UL{startValue;endValue;duration;callback;startTime=void 0;animationFrameId=null;constructor(e,t,s,o){this.startValue=e,this.endValue=t,this.duration=s,this.callback=o}start(){this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}stop(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}animate(e){this.startTime||(this.startTime=e);const t=e-this.startTime,s=Math.min(t/this.duration,1),o=this.startValue+(this.endValue-this.startValue)*kL.easeOutQuart(s);this.callback(o),s<1?this.animationFrameId=requestAnimationFrame(this.animate.bind(this)):this.stop()}}const BL=new Jg;BL.add("line",ML),BL.add("bar",ML),BL.add("combo",ML),BL.add("pie",xN),BL.add("gauge",HL),BL.add("scatter",ML),BL.add("scorecard",ZN),BL.add("waterfall",ML),BL.add("pyramid",xN),BL.add("radar",xN),BL.add("geo",xN),BL.add("funnel",xN),BL.add("sunburst",xN),BL.add("treemap",xN),BL.add("calendar",xN);class GL extends Lv{mutators=["toggleFullScreenFigure"];fullScreenFigure=void 0;toggleFullScreenFigure(e){this.fullScreenFigure?.id===e?this.fullScreenFigure=void 0:this.makeFullScreen(e)}makeFullScreen(e){const t=this.getters.getActiveSheetId(),s=this.getters.getFigure(t,e);s&&(this.fullScreenFigure={...s,x:0,y:0,width:0,height:0})}}class WL extends t.Component{static template="o-spreadsheet-Menu";static props={menuItems:Array,onClose:Function,onClickMenu:{type:Function,optional:!0},onMouseEnter:{type:Function,optional:!0},onMouseOver:{type:Function,optional:!0},onMouseLeave:{type:Function,optional:!0},width:{type:Number,optional:!0},isActive:{type:Function,optional:!0},onScroll:{type:Function,optional:!0}};static components={};static defaultProps={};hoveredMenu=void 0;setup(){t.onWillUnmount(()=>{this.hoveredMenu?.onStopHover?.(this.env)})}get menuItemsAndSeparators(){const e=[];for(let t=0;t<this.props.menuItems.length;t++){const s=this.props.menuItems[t];!s.isVisible(this.env)||this.isRoot(s)&&!this.hasVisibleChildren(s)||e.push(s),s.separator&&t!==this.props.menuItems.length-1&&"separator"!==e[e.length-1]&&e.push("separator")}return"separator"===e[e.length-1]&&e.pop(),1===e.length&&"separator"===e[0]?[]:e}get childrenHaveIcon(){return this.props.menuItems.some(e=>!!this.getIconName(e))}getIconName(e){return e.icon(this.env)?e.icon(this.env):e.isActive?.(this.env)?"o-spreadsheet-Icon.CHECK":""}getColor(e){return JF({color:e.textColor})}getIconColor(e){return JF({color:e.iconColor})}getName(e){return e.name(this.env)}isRoot(e){return!e.execute}hasVisibleChildren(e){return e.children(this.env).some(e=>e.isVisible(this.env))}isEnabled(e){const t=e.children?.(this.env);return t.length?t.some(e=>this.isEnabled(e)):!!e.isEnabled(this.env)&&(!this.env.model.getters.isReadonly()||e.isReadonlyAllowed)}get menuStyle(){return this.props.width?JF({width:this.props.width+"px"}):""}onMouseEnter(e,t){this.hoveredMenu=e,e.onStartHover?.(this.env),this.props.onMouseEnter?.(e,t)}onMouseLeave(e,t){this.hoveredMenu=void 0,e.onStopHover?.(this.env),this.props.onMouseLeave?.(e,t)}onClickMenu(e,t){this.isEnabled(e)&&this.props.onClickMenu?.(e,t)}}function $L(e){return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}function qL(e){if(e)return{x:e.left,y:e.top,width:e.right-e.left,height:e.bottom-e.top}}function ZL(){const e=t.useState({x:0,y:0,width:0,height:0});let s=null;function o(){if(s||(s=document.querySelector(".o-spreadsheet")),s){const{top:t,left:o,width:i,height:n}=s.getBoundingClientRect();e.x=o,e.y=t,e.width=i,e.height=n}}return t.onMounted(o),t.onPatched(o),e}class jL extends t.Component{static template="o-spreadsheet-Popover";static props={anchorRect:Object,containerRect:{type:Object,optional:!0},positioning:{type:String,optional:!0},maxWidth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},verticalOffset:{type:Number,optional:!0},onMouseWheel:{type:Function,optional:!0},onPopoverHidden:{type:Function,optional:!0},onPopoverMoved:{type:Function,optional:!0},zIndex:{type:Number,optional:!0},class:{type:String,optional:!0},slots:Object};static defaultProps={positioning:"bottom-left",verticalOffset:0,onMouseWheel:()=>{},onPopoverMoved:()=>{},onPopoverHidden:()=>{}};popoverRef=t.useRef("popover");popoverContentRef=t.useRef("popoverContent");currentPosition=void 0;currentDisplayValue=void 0;spreadsheetRect=ZL();containerRect;setup(){this.containerRect=function(){const e=t.useState({x:0,y:0,width:0,height:0}),s=t.useComponent(),o=ZL();function i(){const t=s.env,i="getPopoverContainerRect"in t&&t.getPopoverContainerRect?t.getPopoverContainerRect():o;e.x=i.x,e.y=i.y,e.width=i.width,e.height=i.height}return i(),t.onMounted(i),t.onPatched(i),e}();const e=new ResizeObserver(this.computePopoverPosition.bind(this));t.onMounted(()=>{e.observe(this.popoverContentRef.el)}),t.onWillUnmount(()=>{e.disconnect()}),t.useEffect(this.computePopoverPosition.bind(this))}computePopoverPosition(){if(!this.containerRect)throw new Error("Popover container is not defined");const e=this.popoverRef.el,t=this.popoverContentRef.el,s=(o=this.props.anchorRect,i=this.containerRect,qL(zt($L(o),$L(i))));var o,i;const n=s?"block":"none";if("none"!==this.currentDisplayValue&&"none"===n&&this.props.onPopoverHidden?.(),e.style.display=n,this.currentDisplayValue=n,!s)return;const r={width:this.props.maxWidth,height:this.props.maxHeight};let a={width:t.getBoundingClientRect().width,height:t.getBoundingClientRect().height};const l=this.spreadsheetRect,c="bottom-left"===this.props.positioning?new XL(s,this.containerRect,r,l,this.currentPosition):new KL(s,this.containerRect,r,l,this.currentPosition);e.style["max-height"]=c.getMaxHeight(a.height)+"px",e.style["max-width"]=c.getMaxWidth(a.width)+"px",a={width:e.getBoundingClientRect().width,height:e.getBoundingClientRect().height};const h=c.getCss(a,this.props.verticalOffset);for(const t of Object.keys(h))e.style[t]=h[t];const d=c.getCurrentPosition(a);this.currentPosition&&d!==this.currentPosition&&this.props.onPopoverMoved?.(),this.currentPosition=d}}class YL{anchorRect;containerRect;propsMaxSize;spreadsheetOffset;lastPosition;constructor(e,t,s,o,i){this.anchorRect=e,this.containerRect=t,this.propsMaxSize=s,this.spreadsheetOffset=o,this.lastPosition=i}shouldRenderAtBottom(e){if("top-left"===this.lastPosition||"top-right"===this.lastPosition){return!(e<=this.availableHeightUp||this.availableHeightUp>=this.availableHeightDown)}return e<=this.availableHeightDown||this.availableHeightDown>=this.availableHeightUp}shouldRenderAtRight(e){if("bottom-left"===this.lastPosition||"top-left"===this.lastPosition){return!(e<=this.availableWidthLeft||this.availableWidthLeft>=this.availableWidthRight)}return e<=this.availableWidthRight||this.availableWidthRight>=this.availableWidthLeft}getMaxHeight(e){const t=this.shouldRenderAtBottom(e)?this.availableHeightDown:this.availableHeightUp;return this.propsMaxSize.height?Math.min(t,this.propsMaxSize.height):t}getMaxWidth(e){const t=this.shouldRenderAtRight(e)?this.availableWidthRight:this.availableWidthLeft;return this.propsMaxSize.width?Math.min(t,this.propsMaxSize.width):t}getCss(e,t){const s=this.getMaxHeight(e.height),o=this.getMaxWidth(e.width),i=Math.min(s,e.height),n=Math.min(o,e.width),r=this.shouldRenderAtBottom(e.height),a=this.shouldRenderAtRight(e.width);return t=r?t:-t,{top:this.getTopCoordinate(i,r)-this.spreadsheetOffset.y-t+"px",left:this.getLeftCoordinate(n,a)-this.spreadsheetOffset.x+"px"}}getCurrentPosition(e){const t=this.shouldRenderAtBottom(e.height),s=this.shouldRenderAtRight(e.width);return t&&s?"bottom-right":t&&!s?"bottom-left":!t&&s?"top-right":"top-left"}}class XL extends YL{get availableHeightUp(){return this.anchorRect.y-this.containerRect.y}get availableHeightDown(){return this.containerRect.height-this.availableHeightUp-this.anchorRect.height}get availableWidthRight(){return this.containerRect.x+this.containerRect.width-this.anchorRect.x}get availableWidthLeft(){return this.anchorRect.x+this.anchorRect.width-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y+this.anchorRect.height:this.anchorRect.y-e}getLeftCoordinate(e,t){return t?this.anchorRect.x:this.anchorRect.x+this.anchorRect.width-e}}class KL extends YL{get availableHeightUp(){return this.anchorRect.y+this.anchorRect.height-this.containerRect.y}get availableHeightDown(){return this.containerRect.y+this.containerRect.height-this.anchorRect.y}get availableWidthRight(){return this.containerRect.width-this.anchorRect.width-this.availableWidthLeft}get availableWidthLeft(){return this.anchorRect.x-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y:this.anchorRect.y+this.anchorRect.height-e}getLeftCoordinate(e,t){return t?this.anchorRect.x+this.anchorRect.width:this.anchorRect.x-e}}class JL extends t.Component{static template="o-spreadsheet-Menu-Popover";static props={anchorRect:Object,popoverPositioning:{type:String,optional:!0},menuItems:Array,depth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},onClose:Function,onMenuClicked:{type:Function,optional:!0},menuId:{type:String,optional:!0},onMouseOver:{type:Function,optional:!0},width:{type:Number,optional:!0}};static components={MenuPopover:JL,Menu:WL,Popover:jL};static defaultProps={depth:1,popoverPositioning:"top-right"};subMenu=t.useState({isOpen:!1,anchorRect:null,scrollOffset:0,menuItems:[],isHoveringChild:!1});menuRef=t.useRef("menu");hoveredMenu=void 0;openingTimeOut=function(){let e;function s(){void 0!==e&&(clearTimeout(e),e=void 0)}return t.onWillUnmount(s),{clear:s,schedule:function(t,o){s(),e=setTimeout(t,o)}}}();setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.useExternalListener(window,"contextmenu",this.onExternalClick,{capture:!0}),t.onWillUpdateProps(e=>{e.menuItems!==this.props.menuItems&&this.closeSubMenu()}),t.onWillUnmount(()=>{this.hoveredMenu?.onStopHover?.(this.env)})}get menuProps(){return{menuItems:this.props.menuItems,onClose:this.close.bind(this),onClickMenu:this.onClickMenu.bind(this),onMouseOver:this.onMouseOver.bind(this),onMouseLeave:this.onMouseLeave.bind(this),width:this.props.width||250,isActive:this.isActive.bind(this),onScroll:this.onScroll.bind(this)}}get subMenuAnchorRect(){const e=Object.assign({},this.subMenu.anchorRect);return e.y-=this.subMenu.scrollOffset||0,e}get popoverProps(){const e=1===this.props.depth;return{anchorRect:{x:this.props.anchorRect.x,y:this.props.anchorRect.y,width:e?this.props.anchorRect.width:this.props.width||250,height:e?this.props.anchorRect.height:26},positioning:this.props.popoverPositioning,verticalOffset:e?0:6,onPopoverHidden:()=>this.closeSubMenu(),onPopoverMoved:()=>this.closeSubMenu(),maxHeight:this.props.maxHeight}}get childrenHaveIcon(){return this.props.menuItems.some(e=>!!this.getIconName(e))}getIconName(e){return e.icon(this.env)?e.icon(this.env):e.isActive?.(this.env)?"o-spreadsheet-Icon.CHECK":""}getColor(e){return JF({color:e.textColor})}getIconColor(e){return JF({color:e.iconColor})}async activateMenu(e,t){const s=await(e.execute?.(this.env,t));this.close(),this.props.onMenuClicked?.({detail:s})}close(){this.closeSubMenu(),this.props.onClose()}onExternalClick(e){this.menuRef.el&&Array.from(document.querySelectorAll(".o-spreadsheet .o-menu")).some(t=>AN(t,e))||(e.closedMenuId=this.props.menuId,this.close())}getName(e){return e.name(this.env)}isRoot(e){return!e.execute}isEnabled(e){return!!e.isEnabled(this.env)&&(!this.env.model.getters.isReadonly()||e.isReadonlyAllowed)}isActive(e){return!!this.subMenu?.isHoveringChild&&this.isParentMenu(this.subMenu,e)}onScroll(e){this.subMenu.scrollOffset=e.target.scrollTop}openSubMenu(e,t){if(!t)return;const s=t.getBoundingClientRect().top;this.subMenu.anchorRect={x:ON(this.menuRef).x,y:s-(this.subMenu.scrollOffset||0),width:this.props.width||250,height:26},this.subMenu.menuItems=e.children(this.env),this.subMenu.isOpen=!0,this.subMenu.parentMenu=e}isParentMenu(e,t){return e.parentMenu?.id===t.id}closeSubMenu(){this.subMenu.isHoveringChild||(this.subMenu.isOpen=!1,this.subMenu.parentMenu=void 0)}onClickMenu(e,t){this.isRoot(e)?this.openSubMenu(e,t.currentTarget):this.activateMenu(e,HN(t))}onMouseOver(e,t){if(this.isParentMenu(this.subMenu,e))return void this.openingTimeOut.clear();const s=t.currentTarget;this.isRoot(e)&&this.openingTimeOut.schedule(()=>{this.openSubMenu(e,s)},250)}onMouseOverMainMenu(){this.props.onMouseOver?.(),this.subMenu.isHoveringChild=!1}onMouseOverChildMenu(){this.subMenu.isHoveringChild=!0,this.openingTimeOut.clear()}onMouseLeave(e){this.openingTimeOut.schedule(this.closeSubMenu.bind(this),250)}get menuStyle(){return this.props.width?JF({width:this.props.width+"px"}):""}}class QL extends t.Component{static template="o-spreadsheet-ChartDashboardMenu";static components={MenuPopover:JL};static props={chartId:String,hasFullScreenButton:{type:Boolean,optional:!0}};static defaultProps={hasFullScreenButton:!0};fullScreenFigureStore;menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});setup(){super.setup(),this.fullScreenFigureStore=Tv(GL)}getMenuItems(){return[this.fullScreenMenuItem].filter(De)}get backgroundColor(){return"background-color: "+(this.env.model.getters.getChartDefinition(this.props.chartId).background||c)}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.anchorRect=FN(e.currentTarget);const t=this.env.model.getters.getFigureIdFromChartId(this.props.chartId);this.menuState.menuItems=xL(t,this.env)}get fullScreenMenuItem(){if(!this.props.hasFullScreenButton)return;const e=this.env.model.getters.getChartDefinition(this.props.chartId),t=this.env.model.getters.getFigureIdFromChartId(this.props.chartId);if("scorecard"===e.type)return;const s=t===this.fullScreenFigureStore.fullScreenFigure?.id;return{id:"fullScreenChart",label:Cs(s?"Exit Full Screen":"Full Screen"),class:"text-muted fa "+(s?"fa-compress":"fa-expand"),onClick:()=>{this.fullScreenFigureStore.toggleFullScreenFigure(t)}}}}class eV extends t.Component{static template="o-spreadsheet-CarouselFigure";static props={figureUI:Object,editFigureStyle:{type:Function,optional:!0},isFullScreen:{type:Boolean,optional:!0},openContextMenu:{type:Function,optional:!0}};static components={ChartDashboardMenu:QL,MenuPopover:JL};carouselTabsRef=t.useRef("carouselTabs");carouselTabsDropdownRef=t.useRef("carouselTabsDropdown");menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});hiddenItems=[];animationStore;fullScreenFigureStore;setup(){this.animationStore=Tv(VS),this.fullScreenFigureStore=Tv(GL),t.useEffect(()=>{"carouselDataView"===this.selectedCarouselItem?.type?this.props.editFigureStyle?.({"pointer-events":"none"}):this.props.editFigureStyle?.({"pointer-events":"auto"}),this.updateTabsVisibility()})}get carousel(){return this.env.model.getters.getCarousel(this.props.figureUI.id)}get selectedCarouselItem(){return this.env.model.getters.getSelectedCarouselItem(this.props.figureUI.id)}get chartComponent(){const e=this.selectedCarouselItem;if("chart"!==e?.type)throw new Error("Selected item is not a chart");const t=this.env.model.getters.getChartType(e.chartId),s=BL.get(t);if(!s)throw new Error(`Component is not defined for type ${t}`);return s}onCarouselDoubleClick(){this.env.model.dispatch("SELECT_FIGURE",{figureId:this.props.figureUI.id}),this.env.openSidePanel("CarouselPanel",{figureId:this.props.figureUI.id})}isItemSelected(e){return Le(this.selectedCarouselItem,e)}getItemTitle(e){return jF(this.env.model.getters,e)}onCarouselTabClick(e){if(this.env.model.dispatch("UPDATE_CAROUSEL_ACTIVE_ITEM",{figureId:this.props.figureUI.id,sheetId:this.env.model.getters.getActiveSheetId(),item:e}),"chart"===e.type){const t=e.chartId+(this.props.isFullScreen?"-fullscreen":"");this.animationStore?.enableAnimationForChart(t)}}get headerStyle(){const e={};if("chart"===this.selectedCarouselItem?.type){const t=this.env.model.getters.getChartRuntime(this.selectedCarouselItem.chartId);e["background-color"]=t.background}else e["background-color"]="#ffffff";return JF(e)}get title(){return this.carousel.title?.text??""}get titleStyle(){return JF(KF(function(e){return{bold:e.bold,italic:e.italic,fontSize:e.fontSize,textColor:e.color,align:e.align}}({...ie,...this.carousel.title})))}updateTabsVisibility(){const e=this.carouselTabsRef.el,t=this.carouselTabsDropdownRef.el;if(!e||!t)return;this.hiddenItems=[];const s=FN(e),o=Array.from(e.children);for(const e of o)e.style.display="block";const i=o.map(e=>FN(e).width);let n=0;for(let e=0;e<o.length;e++){const t=n+i[e]>s.width;n+=i[e],t&&(o[e].style.display="none",this.hiddenItems.push(this.carousel.items[e]))}t.style.display=this.hiddenItems.length?"block":"none"}get menuId(){return"carousel-tabs-menu-"}toggleMenu(e){if(e.closedMenuId===this.menuId)return void(this.menuState.isOpen=!1);const t=ON(this.carouselTabsDropdownRef),s=this.hiddenItems.map(e=>({name:this.getItemTitle(e),execute:()=>this.onCarouselTabClick(e),isActive:()=>this.isItemSelected(e),isReadonlyAllowed:!0}));this.menuState.isOpen=!0,this.menuState.anchorRect=t,this.menuState.menuItems=Sv(s)}toggleFullScreen(){"chart"===this.selectedCarouselItem?.type&&this.fullScreenFigureStore.toggleFullScreenFigure(this.props.figureUI.id)}get fullScreenButtonTitle(){return this.props.isFullScreen?Cs("Exit Full Screen"):Cs("Full Screen")}get visibleCarouselItems(){return this.carousel.items.filter(e=>"carouselDataView"!==e.type||!this.props.isFullScreen)}openContextMenu(e){const t=e.currentTarget;t&&this.props.openContextMenu?.(FN(t))}}class tV extends t.Component{static template="o-spreadsheet-ChartFigure";static props={figureUI:Object,editFigureStyle:{type:Function,optional:!0},isFullScreen:{type:Boolean,optional:!0},openContextMenu:{type:Function,optional:!0}};static components={ChartDashboardMenu:QL};onDoubleClick(){this.env.model.dispatch("SELECT_FIGURE",{figureId:this.props.figureUI.id}),this.env.openSidePanel("ChartPanel")}get chartType(){return this.env.model.getters.getChartType(this.chartId)}get chartId(){const e=this.env.model.getters.getChartIdFromFigureId(this.props.figureUI.id);if(!e)throw new Error(`No chart found for figure ID: ${this.props.figureUI.id}`);return e}get chartComponent(){const e=this.chartType,t=BL.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}class sV extends t.Component{static template="o-spreadsheet-ImageFigure";static props={figureUI:Object,editFigureStyle:{type:Function,optional:!0},openContextMenu:{type:Function,optional:!0}};static components={};get figureId(){return this.props.figureUI.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}}const oV=new Jg;oV.add("chart",{Component:tV,SidePanelComponent:"ChartPanel",menuBuilder:xL}),oV.add("image",{Component:sV,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t){return Sv([RL(e,t,Cs("Image copied to clipboard")),TL(e,t),{id:"reset_size",name:Cs("Reset size"),execute:async()=>{const s=t.model.getters.getActiveSheetId(),o=t.model.getters.getFigure(s,e);if(!o)return;const i=t.model.getters.getImagePath(e),n=t.model.getters.getImageSize(e)??await(t.imageProvider?.getImageOriginalSize(i));if(!t.model.getters.getImageSize(e)){t.model.getters.getImage(e).size=n}const{col:r,row:a}=o,{height:l,width:c}=cP(t.model.getters,n);t.model.dispatch("UPDATE_FIGURE",{sheetId:s,figureId:e,height:l,width:c,col:r,row:a})},icon:"o-spreadsheet-Icon.REFRESH"},{id:"download",name:Cs("Download"),execute:async()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e});UN(t.model.getters.getImagePath(e),"image")},icon:"o-spreadsheet-Icon.DOWNLOAD"},DL(e,t)])}}),oV.add("carousel",{Component:eV,menuBuilder:function(e,t){const s=t=>"chart"===t.model.getters.getSelectedCarouselItem(e)?.type;return Sv([{id:"edit_carousel",name:Cs("Edit carousel"),execute:()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e}),t.openSidePanel("CarouselPanel",{figureId:e})},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall},{...RL(e,t,Cs("Carousel copied to clipboard")),name:Cs("Copy carousel")},{...TL(e,t),name:Cs("Cut carousel")},{...DL(e,t),name:Cs("Delete carousel"),separator:!0},{id:"edit_chart",name:Cs("Edit chart"),execute:()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e}),t.openSidePanel("ChartPanel",{})},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall,isVisible:s},{...AL(e,t),isVisible:s,name:Cs("Copy chart as image")},{..._L(e,t),isVisible:s,name:Cs("Download chart")},{id:"popout_chart",name:Cs("Pop out chart"),icon:"o-spreadsheet-Icon.EXTERNAL",execute:()=>{const s=t.model.getters.getSelectedCarouselItem(e);s&&"chart"===s.type&&t.model.dispatch("POPOUT_CHART_FROM_CAROUSEL",{carouselId:e,chartId:s.chartId,sheetId:t.model.getters.getActiveSheetId()})},isVisible:s},{id:"delete_carousel_item",name:t=>{const s=t.model.getters.getSelectedCarouselItem(e);return Cs("chart"===s?.type?"Delete chart":"Delete data view")},execute:()=>{const s=t.model.getters.getSelectedCarouselItem(e);if(!s)return;const o=t.model.getters.getCarousel(e),i=o.items.filter(e=>!Le(e,s));t.model.dispatch("UPDATE_CAROUSEL",{figureId:e,sheetId:t.model.getters.getActiveSheetId(),definition:{...o,items:i}})},icon:"o-spreadsheet-Icon.TRASH",isVisible:t=>t.model.getters.getCarousel(e).items.length>=1}]).filter(e=>!t.model.getters.isReadonly()||e.isReadonlyAllowed)}});class iV extends t.Component{static template="o-spreadsheet-FigureComponent";static props={figureUI:Object,style:{type:String,optional:!0},class:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}};static components={MenuPopover:JL};static defaultProps={onMouseDown:()=>{},onClickAnchor:()=>{}};menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});figureRef=t.useRef("figure");figureWrapperRef=t.useRef("figureWrapper");menuButtonRef=t.useRef("menuButton");borderWidth;get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figureUI.id}get figureRegistry(){return oV}getBorderWidth(){return this.env.isDashboard()?0:this.isSelected?2:this.borderWidth}getBorderStyle(e){return`border-${e}-width: ${this.getBorderWidth()}px;`}get wrapperStyle(){const{x:e,y:t,width:s,height:o}=this.props.figureUI;return JF({left:`${e}px`,top:`${t}px`,width:`${s}px`,height:`${o}px`})}getResizerPosition(e){const t={};return e.includes("top")?t.top="-3px":e.includes("bottom")?t.bottom="-3px":t.bottom="calc(50% - 3px)",e.includes("left")?t.left="-3px":e.includes("right")?t.right="-3px":t.right="calc(50% - 3px)",JF(t)}setup(){const e=oV.get(this.props.figureUI.tag).borderWidth;this.borderWidth=void 0!==e?e:1,t.useEffect((e,t,s)=>{e===t&&s?.focus({preventScroll:!0})},()=>[this.env.model.getters.getSelectedFigureId(),this.props.figureUI.id,this.figureRef.el])}clickAnchor(e,t,s){this.props.onClickAnchor(e,t,s)}onMouseDown(e){this.env.isMobile()||this.props.onMouseDown(e)}onClick(e){this.env.isMobile()&&this.props.onMouseDown(e)}onKeyDown(e){const t=LN(e);switch(t){case"Delete":case"Backspace":this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),figureId:this.props.figureUI.id}),e.preventDefault(),e.stopPropagation();break;case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":const{col:s,row:o,offset:i}=this.postionInBoundary(this.props.figureUI,e.key);this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),figureId:this.props.figureUI.id,offset:i,col:s,row:o}),e.preventDefault(),e.stopPropagation();break;case"Ctrl+A":e.preventDefault(),e.stopPropagation();break;case"Ctrl+Y":case"Ctrl+Z":"Ctrl+Y"===t?this.env.model.dispatch("REQUEST_REDO"):"Ctrl+Z"===t&&this.env.model.dispatch("REQUEST_UNDO"),e.preventDefault(),e.stopPropagation()}}postionInBoundary(e,t){const s=this.env.model.getters.getActiveSheetId();let{col:o,row:i,offset:n}=e;switch(n={...n},t){case"ArrowUp":0===n.y?(i--,n.y=this.env.model.getters.getRowSize(s,i)-1):n.y--;break;case"ArrowLeft":0===n.x?(o--,n.x=this.env.model.getters.getColSize(s,o)-1):n.x--;break;case"ArrowDown":n.y===this.env.model.getters.getRowSize(s,i)?(i++,n.y=0):n.y++;break;case"ArrowRight":n.x===this.env.model.getters.getColSize(s,i)?(o++,n.x=0):n.x++}return{col:o,row:i,offset:n}}onContextMenu(e){if(this.env.isDashboard())return;const t=$N(this.env,e);this.openContextMenu({x:t.clientX,y:t.clientY,width:0,height:0})}showMenu(){this.openContextMenu(ON(this.menuButtonRef))}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.anchorRect=e,this.menuState.menuItems=oV.get(this.props.figureUI.tag).menuBuilder(this.props.figureUI.id,this.env)}editWrapperStyle(e){if(this.figureWrapperRef.el)for(const t in e)this.figureWrapperRef.el.style.setProperty(t,e[t]||null)}}class nV extends Lv{mutators=["clear","hover"];col;row;handle(e){if("ACTIVATE_SHEET"===e.type)this.clear()}hover(e){if(e.col===this.col&&e.row===this.row)return"noStateChange";this.col=e.col,this.row=e.row}clear(){if(void 0===this.col&&void 0===this.row)return"noStateChange";this.col=void 0,this.row=void 0}}const rV=new Jg;class aV extends Lv{mutators=["open","close"];persistentPopover;hoveredCell=this.get(nV);handle(e){if("ACTIVATE_SHEET"===e.type)this.close()}open({col:e,row:t},s){const o=this.getters.getActiveSheetId();rV.contains(s)&&(this.persistentPopover={col:e,row:t,sheetId:o,type:s})}close(){if(!this.persistentPopover)return"noStateChange";this.persistentPopover=void 0}get persistentCellPopover(){return this.persistentPopover&&{isOpen:!0,...this.persistentPopover}||{isOpen:!1}}get isOpen(){return void 0!==this.persistentPopover}get cellPopover(){const e=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=rV.get(this.persistentPopover.type).onOpen?.(e,this.getters);return t?.isOpen?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}const{col:t,row:s}=this.hoveredCell;if(void 0===t||void 0===s||!this.getters.isVisibleInViewport({sheetId:e,col:t,row:s}))return{isOpen:!1};const o=this.getters.getMainCellPosition({sheetId:e,col:t,row:s}),i=rV.getAll().map(e=>e.onHover?.(o,this.getters)).find(e=>e?.isOpen);return i?.isOpen?{...i,anchorRect:this.computePopoverAnchorRect(o)}:{isOpen:!1}}computePopoverAnchorRect({col:e,row:t}){const s=this.getters.getActiveSheetId(),o=this.getters.getMerge({sheetId:s,col:e,row:t});return o?this.getters.getVisibleRect(o):this.getters.getVisibleRect(Jt({col:e,row:t}))}}class lV extends t.Component{static maxSize={maxHeight:80};static template="o-spreadsheet-ErrorToolTip";static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};get dataValidationErrorMessage(){return this.env.model.getters.getInvalidDataValidationMessage(this.props.cellPosition)}get evaluationError(){const e=this.env.model.getters.getEvaluatedCell(this.props.cellPosition);if(e.message)return e}get errorOriginPositionString(){if(this.env.model.getters.isDashboard())return"";const e=this.evaluationError,t=e?.errorOriginPosition;if(!t||Le(t,this.props.cellPosition))return"";const s=t.sheetId;return this.env.model.getters.getRangeString(this.env.model.getters.getRangeFromZone(s,Jt(t)),this.env.model.getters.getActiveSheetId())}selectCell(){const e=this.evaluationError?.errorOriginPosition;if(!e)return;const t=this.env.model.getters.getActiveSheetId();e.sheetId!==t&&this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:e.sheetId}),this.env.model.selection.selectCell(e.col,e.row)}}const cV={onHover:(e,t)=>{const s=t.getEvaluatedCell(e);return s.type===Xd.error&&s.message||t.getInvalidDataValidationMessage(e)?{isOpen:!0,props:{cellPosition:e},Component:lV,cellCorner:"top-right"}:{isOpen:!1}}};function hV(e,t,s,o,i){let n=o.right>o.left;if(e.model.getters.doesIntersectMerge(t,o)){let s;n=!1;for(let i=o.top;i<=o.bottom;i++){s=[];for(let n=o.left;n<=o.right;n++){const o=e.model.getters.getMerge({sheetId:t,col:n,row:i});o&&!s.includes(o.id.toString())&&s.push(o.id.toString())}if(s.length>=2){n=!0;break}}}if(n)return void dV(e,t,s,o,i);const r=e.model.getters.getContiguousZone(t,o);Ht(r,o)?dV(e,t,s,o,i):e.askConfirmation(Cs("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),()=>dV(e,t,s,r,i),()=>dV(e,t,s,o,i))}function dV(e,t,s,o,i,n){const r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:s.col,row:s.row,zone:o,sortDirection:i,sortOptions:n});if(r.isCancelledBecause("InvalidSortZone")){const{col:t,row:i}=s;e.model.selection.selectZone({cell:{col:t,row:i},zone:o}),e.raiseError(Cs("Cannot sort. To sort, select only cells or only merges that have the same size."))}if(r.isCancelledBecause("SortZoneWithArrayFormulas")){const{col:t,row:i}=s;e.model.selection.selectZone({cell:{col:t,row:i},zone:o}),e.raiseError(Cs("Cannot sort a zone with array formulas."))}}class uV extends t.Component{static template="o-spreadsheet-Collapse";static props={isCollapsed:Boolean,slots:Object};contentRef=t.useRef("content");setup(){t.onMounted(()=>{this.props.isCollapsed&&this.contentRef.el?.classList.add("d-none")}),t.onWillUpdateProps(e=>{e.isCollapsed!==this.props.isCollapsed&&this.startTransition(e.isCollapsed)})}startTransition(e){const t=this.contentRef.el;if(!t)return;t.classList.remove("d-none"),t.classList.add("overflow-hidden");const s=e?t.scrollHeight:0,o=e?0:t.scrollHeight;t.animate([{maxHeight:s+"px"},{maxHeight:o+"px"}],{duration:350,easing:"ease"}).onfinish=()=>{t.classList.remove("overflow-hidden"),this.props.isCollapsed&&t.classList.add("d-none")}}}class gV extends t.Component{static template="o-spreadsheet-SidePanelCollapsible";static props={slots:Object,title:{type:String,optional:!0},isInitiallyCollapsed:{type:Boolean,optional:!0},class:{type:String,optional:!0}};static components={Collapse:uV};state=t.useState({isCollapsed:this.props.isInitiallyCollapsed});toggle(){this.state.isCollapsed=!this.state.isCollapsed}}class pV extends t.Component{static props={criterion:Object,onCriterionChanged:Function,disableFormulas:{type:Boolean,optional:!0},autofocus:{type:Boolean,optional:!0}};setup(){const e=Tv(zv);"inactive"!==e.activeComposer.editionMode&&e.activeComposer.stopEdition()}updateCriterion(e){const t={...this.props.criterion,...e};this.props.onCriterionChanged(t)}}class mV{mutators=["setFocusableElement","focus"];focusableElement=void 0;setFocusableElement(e){return this.focusableElement=e,"noStateChange"}focus(){if(this.focusableElement===document.activeElement)return"noStateChange";this.focusableElement?.focus()}}const fV={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function vV(e,t){const s=fV[e.key];e.shiftKey?t.resizeAnchorZone(s,zN(e)?"end":1):t.moveAnchorCell(s,zN(e)?"end":1)}class bV extends t.Component{static template="o-spreadsheet-TextValueProvider";static props={proposals:Array,selectedIndex:{type:Number,optional:!0},onValueSelected:Function,onValueHovered:Function};autoCompleteListRef=t.useRef("autoCompleteList");setup(){t.useEffect(()=>{const e=this.props.selectedIndex;if(void 0===e)return;const t=this.autoCompleteListRef.el?.children[e];t?.scrollIntoView?.({block:"nearest"})},()=>[this.props.selectedIndex,this.autoCompleteListRef.el])}getCss(e){return JF({color:e.color,background:e.backgroundColor})}}class SV{el;constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){const s=window.getSelection(),{start:o,end:i}=this.getCurrentSelection();if(o===e&&i===t)return;if(0===s.rangeCount){const e=document.createRange();s.addRange(e)}const n=s.getRangeAt(0);let r;if(this.el.contains(n.startContainer)?r=n:(r=document.createRange(),s.removeAllRanges(),s.addRange(r)),e===t&&0===e)r.setStart(this.el,0),r.setEnd(this.el,0);else{const s=this.getText().length;(e<0||t>s)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${s}`),e<0&&(e=0),t>s&&(t=s),e>s&&(e=s));const o=this.findChildAtCharacterIndex(e),i=this.findChildAtCharacterIndex(t);e<=t?(r.setStart(o.node,o.offset),r.setEnd(i.node,i.offset)):(r.setStart(i.node,i.offset),r.setEnd(o.node,o.offset))}}findChildAtCharacterIndex(e){const t=PN(this.el);let s,o,i=e,n=!0;do{s=t.next(),s.done||s.value.hasChildNodes()||(s.value.textContent&&s.value.textContent.length<i?i-=s.value.textContent.length:s.value.textContent&&s.value.textContent.length>=i&&t.return(s.value),o=s.value),s.done||"P"!==s.value.nodeName||(n?n=!1:i--)}while(!s.done&&i);return s.value?{node:s.value,offset:i}:{node:o,offset:i}}setText(e){if(0===e.length)return void this.removeAll();const t=Array.from(this.el.childNodes),s=e.length;for(let o=0;o<s;o++){const s=e[o],i=t[o];let n,r=!1;i&&"P"===i.nodeName?n=i:(r=!0,n=document.createElement("p"));const a=s.length,l=Array.from(n.childNodes);for(let e=0;e<a;e++){const t=s[e],o=l[e];if(o&&"tagName"in o&&"SPAN"===o.tagName&&yV(t,o))continue;if(!t.value&&!t.classes?.length){o&&n.removeChild(o);continue}const i=document.createElement("span");i.innerText=t.value,i.style.color=t.color||"",void 0!==t.opacity&&1!==t.opacity&&(i.style.opacity=t.opacity.toString()),i.addEventListener("mousemove",()=>{t.onHover?.(FN(i))}),i.addEventListener("mouseleave",()=>{t.onStopHover?.()}),i.classList.add(...t.classes||[]),o?n.replaceChild(i,o):n.appendChild(i)}if(l.length>a)for(let e=a;e<l.length;e++)n.removeChild(l[e]);n.hasChildNodes()||n.appendChild(document.createElement("span")),r&&(i?this.el.replaceChild(n,i):this.el.appendChild(n))}if(t.length>s)for(let e=s;e<t.length;e++)this.el.removeChild(t[e])}scrollSelectionIntoView(){const e=document.getSelection()?.focusNode;if(!e||!this.el.contains(e))return;const t=e instanceof HTMLElement?e:e.parentElement;t?.scrollIntoView?.({block:"nearest"})}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){return MN(this.el)}getText(){let e="",t=!0,s=!1;const o=PN(this.el);for(let i=o.next();!i.done;i=o.next())"P"===i.value.nodeName||"DIV"===i.value.nodeName&&i.value!==this.el?(t?t=!1:e+=Q,s=EV(i.value)):i.value.hasChildNodes()||("BR"!==i.value.nodeName||s||(e+=Q),e+=i.value.textContent);return e}}function yV(e,t){const s=e.color||"",o=t.style?.color||"",i=t.style?.opacity||"1",n=s===o,r=Le(e.classes,[...t.classList]),a=t.innerText===e.value,l=(e.opacity??1).toString()===i;return n&&r&&a&&l}const CV=new DOMParser,IV=CV.parseFromString("<br>","text/html").body.firstChild,wV=CV.parseFromString("<span><br></span>","text/html").body.firstChild;function EV(e){if(e.childNodes.length>1)return!1;const t=e.firstChild?.cloneNode(!0);return!t||t instanceof Element&&(t.removeAttribute("class"),t.removeAttribute("style"),t.isEqualNode(IV)||t.isEqualNode(wV)||!1)}class xV extends t.Component{static template="o-spreadsheet-FunctionDescriptionProvider";static props={functionDescription:Object,argsToFocus:Array,repeatingArgGroupIndex:{type:Number,optional:!0}};static components={Collapse:uV};state=t.useState({isCollapsed:!0});toggle(){this.state.isCollapsed=!this.state.isCollapsed}getContext(){return this.props}get formulaHeaderContent(){const{functionDescription:e,repeatingArgGroupIndex:t,argsToFocus:s}=this.props,o=this.env.model.getters.getLocale().formulaArgSeparator+" ",i=[{content:e.name+" ( "}];for(let n=0;n<e.args.length;n++){const r=e.args[n],a=r.repeating;if(n>0&&i.push({content:o}),a){const a=r.optional||(t??0)>0,l=e.args.slice(n,n+e.nbrArgRepeating).map(e=>e.name);t&&i.push({content:"... "+o}),a&&i.push({content:"["});for(let e=0;e<l.length;e++){const r=l[e],a=n+e,c=s.includes(a);i.push({content:r+((t??0)+1),focused:c}),e<l.length-1&&i.push({content:o})}if(a&&i.push({content:"]"}),e.nbrArgRepeating<=1){i.push({content:o+"["});for(let e=0;e<l.length;e++){const s=l[e];i.push({content:s+((t??0)+2)}),e<l.length-1&&i.push({content:o})}i.push({content:"]"})}i.push({content:o+"... "}),n+=e.nbrArgRepeating-1}else{const e=r.optional||r.default,t=s.includes(n);e&&i.push({content:"["}),i.push({content:r.name,focused:t}),e&&i.push({content:"]"})}}return i.push({content:" )"}),i}}class RV extends t.Component{static template="o-spreadsheet-SpeechBubble";static props={content:String,anchorRect:Object};static components={};spreadsheetRect=ZL();bubbleRef=t.useRef("bubble");setup(){t.useEffect(()=>{const e=this.bubbleRef.el;if(!e)return;const t=this.props.anchorRect,s=FN(e),o=t.x+t.width/2-s.width/2-this.spreadsheetRect.x,i=t.y-s.height-7-this.spreadsheetRect.y;e.style.left=`${o}px`,e.style.top=`${i}px`})}}const TV=zf.content,AV=300;class _V extends t.Component{static template="o-spreadsheet-Composer";static props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},inputStyle:{type:String,optional:!0},rect:{type:Object,optional:!0},delimitation:{type:Object,optional:!0},onComposerCellFocused:{type:Function,optional:!0},onComposerContentFocused:Function,isDefaultFocus:{type:Boolean,optional:!0},onInputContextMenu:{type:Function,optional:!0},composerStore:Object,placeholder:{type:String,optional:!0},inputMode:{type:String,optional:!0},showAssistant:{type:Boolean,optional:!0}};static components={TextValueProvider:bV,FunctionDescriptionProvider:xV,SpeechBubble:RV};static defaultProps={inputStyle:"",isDefaultFocus:!1,inputMode:"text",showAssistant:!0};DOMFocusableElementStore;composerRef=t.useRef("o_composer");containerRef=t.useRef("composerContainer");contentHelper=new SV(this.composerRef.el);composerState=t.useState({positionStart:0,positionEnd:0,hoveredRect:void 0});functionDescriptionState=t.useState({showDescription:!1,functionDescription:{},argsToFocus:[],repeatingArgGroupIndex:0});assistant=t.useState({forcedClosed:!1});compositionActive=!1;spreadsheetRect=ZL();lastHoveredTokenIndex=void 0;debouncedHover=Fe((e,t)=>{const s=this.contentHelper.getCurrentSelection();if(s.start!==s.end)return;const o=this.props.composerStore.hoveredTokens;this.props.composerStore.hoverToken(e),Le(o,this.props.composerStore.hoveredTokens)||(this.composerState.hoveredRect=t)},120);get assistantStyleProperties(){const e=this.composerRef.el.getBoundingClientRect(),t={},s=Math.min(this.props.rect?.width||1/0,AV);t["min-width"]=`${s}px`;const o=this.props.composerStore.autoCompleteProposals,i=o?.some(e=>e.description);if((this.functionDescriptionState.showDescription||i)&&(t.width="300px"),this.props.delimitation&&this.props.rect){const{x:e,y:s,height:o}=this.props.rect,i=this.props.delimitation.height-(s+o);if(t["max-height"]=`${i}px`,s>i){const e=s;t["max-height"]=e-9+"px",t.top="-3px",t.transform="translate(0, -100%)"}e+AV>this.props.delimitation.width&&(t.right="0px")}else t["max-height"]=this.spreadsheetRect.height-e.bottom-1+"px",e.left+AV+15+9>this.spreadsheetRect.width&&(t.right="9px");return t}get assistantStyle(){const e=this.assistantStyleProperties;return JF({"max-height":e["max-height"],width:e.width,"min-width":e["min-width"]})}get assistantContainerStyle(){const e=this.assistantStyleProperties;return JF({top:e.top,right:e.right,transform:e.transform})}shouldProcessInputEvents=!1;tokens=[];keyMapping={Enter:e=>this.processEnterKey(e,"down"),"Shift+Enter":e=>this.processEnterKey(e,"up"),"Alt+Enter":this.processNewLineEvent,"Ctrl+Enter":this.processNewLineEvent,Escape:this.processEscapeKey,F2:e=>this.toggleEditionMode(e),F4:e=>this.processF4Key(e),Tab:e=>this.processTabKey(e,"right"),"Shift+Tab":e=>this.processTabKey(e,"left")};keyCodeMapping={NumpadDecimal:this.processNumpadDecimal};setup(){this.DOMFocusableElementStore=Tv(mV),t.onMounted(()=>{const e=this.composerRef.el;this.props.isDefaultFocus&&this.DOMFocusableElementStore.setFocusableElement(e),this.contentHelper.updateEl(e)}),t.onWillUnmount(()=>{this.debouncedHover.stopDebounce()}),t.useEffect(()=>{this.processContent(),document.activeElement!==this.contentHelper.el||"inactive"!==this.props.composerStore.editionMode||this.props.isDefaultFocus||this.DOMFocusableElementStore.focus()}),t.useEffect(()=>{this.processTokenAtCursor()},()=>["inactive"!==this.props.composerStore.editionMode]),t.useEffect(()=>{this.contentHelper.scrollSelectionIntoView()},()=>[this.props.composerStore.composerSelection.start,this.props.composerStore.composerSelection.end])}processArrowKeys(e){const t=this.props.composerStore.tokenAtCursor;if((this.props.composerStore.isSelectingRange||"inactive"===this.props.composerStore.editionMode)&&(!["ArrowUp","ArrowDown"].includes(e.key)||!this.props.composerStore.isAutoCompleteDisplayed||"REFERENCE"===t?.type))return this.functionDescriptionState.showDescription=!1,this.props.composerStore.hideHelp(),e.preventDefault(),e.stopPropagation(),void vV(e,this.env.model.selection);const s=this.props.composerStore.currentContent;"cellFocus"!==this.props.focus||this.props.composerStore.isAutoCompleteDisplayed||at(s)?(e.stopPropagation(),this.handleArrowKeysForAutocomplete(e)):this.props.composerStore.stopEdition()}handleArrowKeysForAutocomplete(e){["ArrowUp","ArrowDown"].includes(e.key)&&this.props.composerStore.isAutoCompleteDisplayed&&(e.preventDefault(),this.props.composerStore.moveAutoCompleteSelection("ArrowDown"===e.key?"next":"previous"))}processTabKey(e,t){e.preventDefault(),e.stopPropagation(),this.props.composerStore.autoCompleteOrStop(t,this.assistant.forcedClosed)}processEnterKey(e,t){e.preventDefault(),e.stopPropagation(),this.props.composerStore.autoCompleteOrStop(t,this.assistant.forcedClosed)}processNewLineEvent(e){e.preventDefault(),e.stopPropagation();const t=this.contentHelper.getText(),s=this.contentHelper.getCurrentSelection(),o=Math.min(s.start,s.end),i=Math.max(s.start,s.end);this.props.composerStore.stopComposerRangeSelection(),this.props.composerStore.setCurrentContent(t.slice(0,o)+Q+t.slice(i),{start:o+1,end:o+1}),this.processContent()}processEscapeKey(e){this.props.composerStore.cancelEdition(),e.stopPropagation(),e.preventDefault()}processF4Key(e){e.stopPropagation(),this.props.composerStore.cycleReferences(),this.processContent()}toggleEditionMode(e){e.stopPropagation(),this.props.composerStore.toggleEditionMode(),this.processContent()}processNumpadDecimal(e){e.stopPropagation(),e.preventDefault();const t=this.env.model.getters.getLocale(),s=this.contentHelper.getCurrentSelection(),o=this.props.composerStore.currentContent,i=o.slice(0,s.start)+t.decimalSeparator+o.slice(s.end);this.props.composerStore.setCurrentContent(i,{start:s.start+1,end:s.start+1}),this.processContent()}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){if("inactive"===this.props.composerStore.editionMode)return;if(e.key.startsWith("Arrow"))return void this.processArrowKeys(e);const t=this.keyMapping[LN(e)]||this.keyCodeMapping[LN(e,"code")];t?t.call(this,e):e.stopPropagation()}onPaste(e){"inactive"!==this.props.composerStore.editionMode?e.stopPropagation():e.preventDefault()}onInput(e){if(!this.shouldProcessInputEvents)return;let t;if(e.stopPropagation(),t="inactive"===this.props.composerStore.editionMode?e.data||"":this.contentHelper.getText(),"inactive"===this.props.focus)return this.props.onComposerCellFocused?.(t);const s=this.contentHelper.getCurrentSelection();this.props.composerStore.stopComposerRangeSelection(),this.props.composerStore.setCurrentContent(t,s),this.processTokenAtCursor()}onKeyup(e){if(this.contentHelper.el===document.activeElement){if(this.props.composerStore.isAutoCompleteDisplayed&&["ArrowUp","ArrowDown"].includes(e.key))return;if(this.props.composerStore.isSelectingRange&&e.key?.startsWith("Arrow"))return;const{start:t,end:s}=this.props.composerStore.composerSelection,{start:o,end:i}=this.contentHelper.getCurrentSelection();o===t&&i===s||this.props.composerStore.changeComposerCursorSelection(o,i),this.processTokenAtCursor()}}onBlur(e){if("inactive"===this.props.composerStore.editionMode)return;const t=e.relatedTarget;t&&t instanceof HTMLElement?this.containerRef.el?.contains(e.relatedTarget)||(t.attributes.getNamedItem("composerFocusableElement")?this.contentHelper.el.focus():t.classList.contains("o-composer")||this.props.composerStore.stopEdition()):this.props.composerStore.stopEdition()}onMousedown(e){e.button>0||this.env.isMobile()&&!GN()||(this.debouncedHover.stopDebounce(),this.contentHelper.removeSelection())}onMouseup(){if(this.env.model.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection();e.start!==e.end&&this.props.composerStore.hoverToken(void 0)}onClick(){if(this.env.model.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection(),t="inactive"===this.props.composerStore.editionMode;this.props.onComposerContentFocused(e),t||this.props.composerStore.changeComposerCursorSelection(e.start,e.end),this.processTokenAtCursor()}onDblClick(){if(this.env.model.getters.isReadonly())return;const e=this.props.composerStore.currentContent;if(at(e)){const t=this.props.composerStore.currentTokens,s=this.contentHelper.getCurrentSelection();if(s.start===s.end)return;const o=e.substring(s.start,s.end),i=t.filter(e=>e.value.includes(o)&&e.start<=s.start&&e.end>=s.end)[0];if(!i)return;"REFERENCE"===i.type&&this.props.composerStore.changeComposerCursorSelection(i.start,i.end)}}onContextMenu(e){"inactive"===this.props.composerStore.editionMode&&this.props.onInputContextMenu?.(e)}closeAssistant(){this.props.composerStore.canBeToggled&&(this.assistant.forcedClosed=!0)}openAssistant(){this.props.composerStore.canBeToggled&&(this.assistant.forcedClosed=!1)}onWheel(e){this.composerRef.el&&this.composerRef.el.scrollHeight>this.composerRef.el.clientHeight&&e.stopPropagation()}processContent(){if(this.compositionActive)return;this.shouldProcessInputEvents=!1,"inactive"!==this.props.focus&&document.activeElement!==this.contentHelper.el&&this.contentHelper.el.focus();const e=this.getContentLines();if(this.contentHelper.setText(e),0!==e.length&&0!==e.length[0]&&"inactive"!==this.props.focus){const{start:e,end:t}=this.props.composerStore.composerSelection;this.contentHelper.selectRange(e,t)}this.shouldProcessInputEvents=!0}getContentLines(){const e=this.props.composerStore.currentContent,t=at(e);return""===e?[]:t&&"inactive"!==this.props.focus?this.splitHtmlContentIntoLines(this.getHtmlContentFromTokens()):this.splitHtmlContentIntoLines([{value:e,classes:[]}])}getHtmlContentFromTokens(){const e=this.props.composerStore.currentTokens,t=[],{end:s,start:o}=this.props.composerStore.composerSelection;for(let i=0;i<e.length;i++){const n=e[i],r=[];"REFERENCE"===n.type&&this.props.composerStore.tokenAtCursor===n&&"selecting"===this.props.composerStore.editionMode&&r.push("text-decoration-underline"),s===o&&n.isParenthesisLinkedToCursor&&r.push("highlight-parenthesis-flag"),n.isInHoverContext&&r.push("highlight-flag"),this.props.composerStore.showSelectionIndicator&&s===o&&s===n.end&&r.push("selector-flag"),t.push({value:n.value,color:n.color||ne,opacity:n.isBlurred?.5:1,classes:r,onHover:e=>this.onTokenHover(i,e),onStopHover:()=>this.onTokenHover(void 0)})}return t}onTokenHover(e,t){this.lastHoveredTokenIndex!==e&&(this.lastHoveredTokenIndex=e,this.debouncedHover(e,t))}splitHtmlContentIntoLines(e){const t=[];let s=[];for(const o of e)if(o.value.includes(Q)){const e=o.value.split(Q),i=e.pop();for(const i of e)s.push({color:o.color,value:i}),t.push(s),s=[];s.push({...o,value:i})}else s.push(o);s.length&&t.push(s);const o=[];for(const e of t)e.every(this.isContentEmpty)?o.push([e[0]]):o.push(e.filter(e=>!this.isContentEmpty(e)));return o}isContentEmpty(e){return!(e.value||e.classes?.length)}processTokenAtCursor(){const e=this.props.composerStore;this.functionDescriptionState.showDescription=!1;const t=this.props.composerStore.tokenAtCursor;if(at(e.currentContent)&&t&&"SYMBOL"!==t.type){const e=t.functionContext,s=e?.parent.toUpperCase();if(e&&s&&s in TV&&"UNKNOWN"!==t.type){const o=TV[s],i=e.argPosition,n=e.args.length;this.functionDescriptionState.functionDescription=o;const r=this.props.composerStore.currentTokens.some(e=>"RIGHT_PAREN"===e.type&&e.parenthesesCode===t.parenthesesCode);this.functionDescriptionState.argsToFocus=this.getArgsToFocus(r,o,n,i),this.functionDescriptionState.showDescription=!0,this.functionDescriptionState.repeatingArgGroupIndex=this.getRepeatingArgGroupIndex(o,n,i)}}}getRepeatingArgGroupIndex(e,t,s){const{minArgRequired:o,maxArgPossible:i,nbrArgRepeating:n}=e;if(!n)return;const r=(n?Math.ceil((t-o)/n):0)*n+o;return ps(e,Math.max(Math.min(i,r),o))(s).repeatingGroupIndex??0}getArgsToFocus(e,t,s,o){const{nbrArgRepeating:i,minArgRequired:n,nbrOptionalNonRepeatingArgs:r,maxArgPossible:a}=t;if(e){const e=ps(t,Math.max(Math.min(a,s),n))(o)?.index;return void 0!==e?[e]:[]}const l=Math.max(s,n),c=i?n+Math.ceil((l-n)/i)*i+r:a,h=[];for(let e=l;e<=c;e++){const s=ps(t,e)(o)?.index;void 0!==s&&h.push(s)}return[...new Set(h)]}autoComplete(e){!e||this.assistant.forcedClosed&&this.props.composerStore.canBeToggled||(this.props.composerStore.insertAutoCompleteValue(e),this.processTokenAtCursor())}get displaySpeechBubble(){return!("inactive"===this.props.focus||!this.composerState.hoveredRect||!this.props.composerStore.hoveredContentEvaluation)}}function DV(e,t){return function(e){for(const t of e)if(t.functionContext){const{argsTokens:e,args:s}=t.functionContext;if(delete t.functionContext.argsTokens,s.length||!e)continue;"LEFT_PAREN"===e[0]?.[0]?.type&&(e[0]=e[0].slice(1));for(const t of e){let e=t;"ARG_SEPARATOR"===e.at(0)?.type&&(e=e.slice(1));try{s.push(ov(e))}catch(e){s.push(void 0)}}}return e}(function(e){const t=[];let s="";function o(e){if(0===t.length)return;const s=t.at(-1);if(s&&s.argsTokens){const{argsTokens:t,argPosition:o}=s;t[o]||(t[o]=[]),t[o].push({value:e.value,type:e.type})}}return e.map((e,i)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(s=""),e.type){case"SYMBOL":o(e),s=e.value;break;case"LEFT_PAREN":t.push({parent:s,argPosition:0,argsTokens:[],args:[]}),o(e),s="";break;case"RIGHT_PAREN":const i=t.pop();i?.argsTokens?.flat().forEach(o),o(e);break;case"ARG_SEPARATOR":t.length&&t[t.length-1].argPosition++,o(e);break;default:o(e)}if(t.length){const s=t[t.length-1];s.parent&&(e.functionContext=Object.assign({},s))}return e})}(function(e){const t=[];let s=0;return e.map((o,i)=>{if("LEFT_PAREN"===o.type){t.push(s+1),s=0;for(let s=i-1;s>=0;s--){if("SPACE"!==e[s].type){"SYMBOL"===e[s].type&&(e[s].parenthesesCode=t.join(":"));break}e[s].parenthesesCode=t.join(":")}}return o.parenthesesCode=t.join(":"),"RIGHT_PAREN"===o.type&&t.length&&(s=t.pop()),o})}(function(e){let t=0;return e.map(e=>{const s=e.value.toString().length,o=Object.assign({},e,{start:t,end:t+s,length:s});return t=o.end,o})}(qf(e,t)))))}class OV{lastId=0;add(e){this.lastId++;const t=this.lastId;return new Promise((s,o)=>{e.then(e=>{this.lastId===t&&s(e)}).catch(e=>{this.lastId===t&&o(e)})})}}function FV(e,t,s){const o=(t.startsWith("=")?DV(t,s):[]).filter(t=>t.start<=e.start&&t.end>=e.start||t.start>=e.start&&t.start<e.end),i=o.filter(e=>"REFERENCE"===e.type);if(0===i.length)return;const n=o.map(Ir).map(e=>e.value).join(""),r=o[0].start,a=o[o.length-1].end,l=t.slice(0,r)+n+t.slice(a),c=l.length-t.length,h={start:i[0].start,end:i[i.length-1].end+c};return 1===i.length&&e.start===e.end&&(h.start=h.end),{content:l,selection:h}}const PV=new Jg;function MV(e,t,s){const{x:i,y:n,width:r,height:a}=s;if(r<0||a<0)return;const l=t.color||o,{ctx:c}=e;c.save(),t.noBorder||(t.dashed&&c.setLineDash([5,3]),c.strokeStyle=l,t.thinLine?(c.lineWidth=1,c.strokeRect(i,n,r,a)):(c.lineWidth=2,c.strokeRect(i+.5,n+.5,r,a))),t.noFill||(c.fillStyle=ab(Yv(l),t.fillAlpha??.12),c.fillRect(i,n,r,a)),c.restore()}class NV extends Lv{mutators=["register","unRegister"];providers=[];constructor(e){super(e),this.onDispose(()=>{this.providers=[]})}get renderingLayers(){return["Highlights"]}get highlights(){const e=this.getters.getActiveSheetId();return this.providers.flatMap(e=>e.highlights).filter(t=>t.range.sheetId===e).map(e=>{const{numberOfRows:t,numberOfCols:s}=$t(e.range.zone),o=t*s===1?this.getters.expandZone(e.range.sheetId,e.range.zone):e.range.unboundedZone;return{...e,range:this.model.getters.getRangeFromZone(e.range.sheetId,o)}})}register(e){this.providers.push(e)}unRegister(e){this.providers=this.providers.filter(t=>t!==e)}drawLayer(e,t){if("Highlights"===t)for(const t of this.highlights){MV(e,t,this.getters.getVisibleRect(t.range.zone))}}}class kV{mutators=["notifyUser","raiseError","askConfirmation","updateNotificationCallbacks"];notifyUser=e=>window.alert(e.text);askConfirmation=(e,t,s)=>{window.confirm(e)?t():s?.()};raiseError=(e,t)=>{window.alert(e),t?.()};updateNotificationCallbacks(e){this.notifyUser=e.notifyUser||this.notifyUser,this.raiseError=e.raiseError||this.raiseError,this.askConfirmation=e.askConfirmation||this.askConfirmation}}class LV extends Lv{mutators=["useProvider","moveSelection","hide","selectIndex"];selectedIndex=void 0;provider;get selectedProposal(){if(void 0!==this.selectedIndex&&void 0!==this.provider)return this.provider.proposals[this.selectedIndex]}useProvider(e){this.provider=e,this.selectedIndex=e.autoSelectFirstProposal?0:void 0}hide(){this.provider=void 0,this.selectedIndex=void 0}selectIndex(e){this.selectedIndex=e}moveSelection(e){this.provider&&(void 0!==this.selectedIndex?"previous"===e?(this.selectedIndex--,this.selectedIndex<0&&(this.selectedIndex=this.provider.proposals.length-1)):this.selectedIndex=(this.selectedIndex+1)%this.provider.proposals.length:this.selectedIndex=0)}}class VV extends Lv{mutators=["startEdition","setCurrentContent","stopEdition","stopComposerRangeSelection","cancelEdition","cycleReferences","hideHelp","autoCompleteOrStop","insertAutoCompleteValue","moveAutoCompleteSelection","selectAutoCompleteIndex","toggleEditionMode","changeComposerCursorSelection","replaceComposerCursorSelection","hoverToken"];col=0;row=0;editionMode="inactive";sheetId="";_currentContent="";currentTokens=[];selectionStart=0;selectionEnd=0;initialContent="";colorIndexByRange={};autoComplete=new LV(this.get);hoveredTokens=[];hoveredContentEvaluation="";autoCompleteKeepLast=new OV;notificationStore=this.get(kV);highlightStore=this.get(NV);constructor(e){super(e),this.highlightStore.register(this),this.onDispose(()=>{this.highlightStore.unRegister(this),this._cancelEdition()})}handleEvent(e){this.hideHelp();const t=this.getters.getActiveSheetId();let s;if(s=e.options.unbounded?this.getters.getUnboundedZone(t,e.anchor.zone):e.anchor.zone,"newAnchor"===e.mode)"selecting"===this.editionMode&&this.insertSelectedRange(s);else"selecting"===this.editionMode?this.replaceSelectedRange(s):this.updateComposerRange(e.previousAnchor.zone,s)}changeComposerCursorSelection(e,t){this.isSelectionValid(this._currentContent.length,e,t)&&(this.selectionStart=e,this.selectionEnd=t,this.stopComposerRangeSelection(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor(),this.updateAutoCompleteProvider())}stopComposerRangeSelection(){this.isSelectingRange&&(this.editionMode="editing")}startEdition(e,t){const{col:s,row:o}=this.getters.getActivePosition();this.model.dispatch("SELECT_FIGURE",{figureId:null}),this.model.dispatch("SCROLL_TO_CELL",{col:s,row:o}),"inactive"!==this.editionMode&&e?this.setContent(e,t):this._startEdition(e,t),this.updateTokenColor(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor(),this.updateAutoCompleteProvider()}cancelEdition(){this.resetContent(),this.cancelEditionAndActivateSheet()}setCurrentContent(e,t){t&&!this.isSelectionValid(e.length,t.start,t.end)||(this.setContent(e,t,!0),this.updateTokenColor(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor())}replaceComposerCursorSelection(e){this.replaceSelection(e)}handle(e){switch(e.type){case"SELECT_FIGURE":e.figureId&&(this.resetContent(),this.cancelEditionAndActivateSheet());break;case"START_CHANGE_HIGHLIGHT":const{left:t,top:s}=e.zone;this.isSelectingRange&&(this.editionMode="editing"),this.model.selection.resetAnchor(this,{cell:{col:t,row:s},zone:e.zone})}}get currentContent(){return"inactive"===this.editionMode?this.getComposerContent(this.getters.getActivePosition()).text:this._currentContent}get composerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}get isSelectingRange(){return"selecting"===this.editionMode}get showSelectionIndicator(){return this.isSelectingRange&&this.canStartComposerRangeSelection()}get tokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find(s=>s.start<=e&&s.end>=t)}get autoCompleteProposals(){return this.autoComplete.provider?.proposals||[]}get autoCompleteSelectedIndex(){return this.autoComplete.selectedIndex}get isAutoCompleteDisplayed(){return!!this.autoComplete.provider}get canBeToggled(){return this.autoComplete.provider?.canBeToggled??!0}cycleReferences(){const e=this.getters.getLocale(),t=FV(this.composerSelection,this._currentContent,e);void 0!==t&&this.setCurrentContent(t.content,t.selection)}toggleEditionMode(){if("inactive"===this.editionMode)return;const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd),s=[...this.currentTokens].reverse().find(s=>s.end>=e&&t>=s.start&&"REFERENCE"===s.type);if("editing"===this.editionMode&&s){const e=this.getters.getActiveSheetId(),{sheetName:t,xc:o}=yr(s.value),i=this.getters.getSheetIdByName(t);i&&i!==e&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:i}),this.selectionStart=this.selectionEnd=s.end;const n=this.getters.getRangeFromSheetXC(this.sheetId,o).zone;this.captureSelection(n),this.editionMode="selecting"}else this.editionMode="editing"}hoverToken(e){this.currentTokens.forEach(e=>e.isInHoverContext=void 0);const t=[...this.currentTokens];if(void 0===e||["ARG_SEPARATOR","SPACE"].includes(t[e].type))return this.hoveredContentEvaluation="",void(this.hoveredTokens=[]);const s=this.getNumberOfMissingParenthesis(t);s>0&&t.push(...Array(s).fill({value:")",type:"RIGHT_PAREN"}));let o=t;if(0!==e){const s=this.getRelatedTokens(t,e),i=t.filter(e=>!s.includes(e)&&"SPACE"!==e.type);o=1===i.length&&i[0]===t[0]?t:s}o.forEach(e=>e.isInHoverContext=!0);let i=o.map(e=>e.value).join("");at(i)||(i=`=${i}`);const n=vh(i,this.getters.getLocale()),r=this.getters.evaluateFormulaResult(this.sheetId,n);this.hoveredTokens=o,this.hoveredContentEvaluation=mn(r,"0",this.getters.getLocale())}getRelatedTokens(e,t){try{const s=ov(e);let o;for(const e of nv(s))if(t>=e.tokenStartIndex&&t<=e.tokenEndIndex)o=e;else if(t<e.tokenStartIndex)break;return o?e.slice(o.tokenStartIndex,o.tokenEndIndex+1):e}catch(t){if(t instanceof xs)return e;throw t}}captureSelection(e,t,s){this.model.selection.capture(this,{cell:{col:t??e.left,row:s??e.right},zone:e},{handleEvent:this.handleEvent.bind(this),release:()=>{this._stopEdition()}})}isSelectionValid(e,t,s){return t>=0&&t<=e&&s>=0&&s<=e}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=Jt({col:this.col,row:this.row});this.model.selection.resetAnchor(this,{cell:{col:this.col,row:this.row},zone:e})}this.editionMode="selecting"}_startEdition(e,t){const s=this.getters.getActiveCell(),o=this.getters.getLocale();e&&s.format?.includes("%")&&mo(e,o)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const{col:i,row:n,sheetId:r}=this.getters.getActivePosition();this.col=i,this.sheetId=r,this.row=n,this.editionMode="editing";const{text:a,adjustedSelection:l}=this.getComposerContent({sheetId:r,col:i,row:n},t);this.initialContent=a,this.setContent(e||this.initialContent,l??t),this.colorIndexByRange={};const c=Jt({col:this.col,row:this.row});this.captureSelection(c,i,n)}_stopEdition(){if("inactive"!==this.editionMode){this.cancelEditionAndActivateSheet();let e=this.getCurrentCanonicalContent();if(!(this.initialContent!==e))return;if(e&&at(e)){const t=this.getNumberOfMissingParenthesis(this.currentTokens);t>0&&(e+=Pe(new Array(t).fill(")")))}this.confirmEdition(e)}}getCurrentCanonicalContent(){return vh(this._currentContent,this.getters.getLocale())}cancelEditionAndActivateSheet(){if("inactive"===this.editionMode)return;this._cancelEdition();this.getters.getActiveSheetId()!==this.sheetId&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}_cancelEdition(){"inactive"!==this.editionMode&&(this.editionMode="inactive",this.model.selection.release(this),this.colorIndexByRange={},this.hoveredTokens=[],this.hoveredContentEvaluation="")}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,s){const o=this._currentContent!==e;if(this._currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,o||"inactive"!==this.editionMode){const t=this.getters.getLocale();this.currentTokens=at(e)?DV(e,t):[];this.currentTokens.filter(e=>"SPACE"!==e.type).length>1e3&&s&&this.notificationStore.raiseError(Cs("This formula has over 1000 parts. It can't be processed properly, consider splitting it into multiple cells"))}this.canStartComposerRangeSelection()&&this.startComposerRangeSelection(),this.updateAutoCompleteProvider()}getAutoCompleteProviders(){return PV.getAll()}insertSelectedRange(e){const t=Math.min(this.selectionStart,this.selectionEnd),s=this.getZoneReference(e);this.canStartComposerRangeSelection()?this.insertText(s,t):this.insertText(","+s,t)}replaceSelectedRange(e){const t=this.getZoneReference(e),s=this.tokenAtCursor,o="REFERENCE"===s?.type?s.start:this.selectionStart;this.replaceText(t,o,this.selectionEnd)}updateComposerRange(e,t){const s=this.getters.getActiveSheetId(),o=this.tokenAtCursor,i=(o?[o,...this.currentTokens]:this.currentTokens).filter(e=>"REFERENCE"===e.type).find(t=>{const{xc:o,sheetName:i}=yr(t.value),n=i||this.getters.getSheetName(this.sheetId);if(!fS(this.getters.getSheetName(s),n))return!1;const r=this.getters.getRangeFromSheetXC(s,o);return Ht(this.getters.expandZone(s,r.zone),e)});if(!i)return;const n=this.getters.getRangeFromSheetXC(s,i.value);this.selectionStart=i.start,this.selectionEnd=this.selectionStart+i.value.length;const r=this.getters.getRangeFromZone(s,t),a=this.getRangeReference(r,n.parts);this.replaceSelection(a)}getZoneReference(e){const t=this.sheetId,s=this.getters.getActiveSheetId(),o=this.getters.getRangeFromZone(s,e);return this.getters.getSelectionRangeString(o,t)}getRangeReference(e,t){const s={...e,parts:[...t]};return this.getters.getSelectionRangeString(s,this.sheetId)}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),s=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,s)}replaceText(e,t,s){this._currentContent=this._currentContent.slice(0,t)+this._currentContent.slice(s,this._currentContent.length),this.insertText(e,t)}insertText(e,t){const s=this._currentContent.slice(0,t)+e+this._currentContent.slice(t),o=t+e.length;this.setCurrentContent(s,{start:o,end:o})}updateTokenColor(){this.updateRangeColor();for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].color=this.getTokenColor(this.currentTokens[e])}getTokenColor(e){if("REFERENCE"===e.type){const{xc:t,sheetName:s}=yr(e.value);return this.rangeColor(t,s)||ne}if("SYMBOL"===e.type){const t=e.value.toUpperCase();if("TRUE"===t||"FALSE"===t)return ae.NUMBER;if(t in zf.content)return ae.FUNCTION}return["LEFT_PAREN","RIGHT_PAREN"].includes(e.type)&&""===e.parenthesesCode?ae.ORPHAN_RIGHT_PAREN:ae[e.type]||ne}rangeColor(e,t){const s=t?this.model.getters.getSheetIdByName(t):this.sheetId,o=this.highlights.find(t=>{if(t.range.sheetId!==s)return!1;let o=this.model.getters.getRangeFromSheetXC(s,e).zone;return o=1===ss(o)?this.model.getters.expandZone(s,o):o,Ht(o,t.range.zone)});return o&&o.color?o.color:void 0}computeFormulaCursorContext(){for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].isBlurred=!1;if(this.selectionStart!==this.selectionEnd)return;const e=this.getParenthesesCodeAfterCursor(),t=[...this.currentTokens].reverse().find(t=>e.startsWith(t.parenthesesCode)&&"SYMBOL"===t.type);if(t)for(let e=0;e<this.currentTokens.length;e++)(this.currentTokens[e].parenthesesCode||"").startsWith(t.parenthesesCode||"")||(this.currentTokens[e].isBlurred=!0)}getParenthesesCodeAfterCursor(){const e=this.tokenAtCursor?.parenthesesCode||"";return"RIGHT_PAREN"===this.tokenAtCursor?.type?e.slice(0,-1)||"":e}computeParenthesisRelatedToCursor(){for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].isParenthesisLinkedToCursor=!1;const e=this.tokenAtCursor;if(e&&""!==e.parenthesesCode&&["LEFT_PAREN","RIGHT_PAREN"].includes(e.type))for(let t=0;t<this.currentTokens.length;t++){const s=this.currentTokens[t];["LEFT_PAREN","RIGHT_PAREN"].includes(s.type)&&s.parenthesesCode===e.parenthesesCode&&s!==e&&(this.currentTokens[t].isParenthesisLinkedToCursor=!0,this.tokenAtCursor.isParenthesisLinkedToCursor=!0)}}updateRangeColor(){if(!at(this._currentContent)||"inactive"===this.editionMode)return;const e=this.sheetId,t=this.getReferencedRanges().map(t=>this.getters.getRangeString(t,e)),s={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(s[e]=this.colorIndexByRange[e]);const o=new Set(Object.values(s));let i=0;const n=()=>{for(;o.has(i);)i++;return o.add(i),i};for(const e of t){const t=e in s?s[e]:n();s[e]=t}this.colorIndexByRange=s}get highlights(){if(!at(this.currentContent)||"inactive"===this.editionMode)return[];const e=this.sheetId,t=e=>{const t=this.colorIndexByRange[e];return qv[t%qv.length]};return this.getReferencedRanges().map(s=>{const o=this.getters.getRangeString(s,e),{numberOfRows:i,numberOfCols:n}=$t(s.zone),r=i*n===1?this.getters.expandZone(s.sheetId,s.zone):s.unboundedZone;return{range:this.model.getters.getRangeFromZone(s.sheetId,r),color:t(o),interactive:!0}})}getReferencedRanges(){const e=this.sheetId;return this.currentTokens.filter(e=>"REFERENCE"===e.type).map(t=>this.getters.getRangeFromSheetXC(e,t.value)).filter(e=>!e.invalidSheetName&&!e.invalidXc)}async updateAutoCompleteProvider(){this.autoComplete.hide();const e=await this.autoCompleteKeepLast.add(this.findAutocompleteProvider());e&&(this.autoComplete.useProvider(e),this.model.trigger("update"))}async findAutocompleteProvider(){const e=this.currentContent,t=at(e)?this.tokenAtCursor:{type:"STRING",value:e};if("inactive"===this.editionMode||!t||["TRUE","FALSE"].includes(t.value.toUpperCase())||!this.canStartComposerRangeSelection()&&!["SYMBOL","STRING","UNKNOWN"].includes(t.type))return;const s={composer:this,getters:this.getters},o=this.getAutoCompleteProviders().sort((e,t)=>(e.sequence??1/0)-(t.sequence??1/0)).map(o=>({...o,getProposals:o.getProposals.bind(s,t,e),selectProposal:o.selectProposal.bind(s,t)}));for(const e of o){let s=await e.getProposals();const o=s?.find(e=>e.text===t.value),i=t.value.replace(/[ ,\(\)]/g,"");if(this._currentContent===this.initialContent&&e.displayAllOnInitialContent&&s?.length)return{proposals:s,selectProposal:e.selectProposal,autoSelectFirstProposal:e.autoSelectFirstProposal??!1,canBeToggled:e.canBeToggled};if(o&&this._currentContent!==this.initialContent)return;if(i&&s&&!["ARG_SEPARATOR","LEFT_PAREN","OPERATOR"].includes(t.type)){const e=LS(i,s,e=>e.fuzzySearchKey||e.text);o&&!e.length||(s=e)}if(e.maxDisplayedProposals&&(s=s?.slice(0,e.maxDisplayedProposals)),s?.length)return{proposals:s,selectProposal:e.selectProposal,autoSelectFirstProposal:e.autoSelectFirstProposal??!1,canBeToggled:e.canBeToggled}}}hideHelp(){this.autoComplete.hide()}autoCompleteOrStop(e,t=!1){if("inactive"!==this.editionMode){const s=this.autoComplete;if(!(t&&this.canBeToggled)&&s.provider&&void 0!==s.selectedIndex){const e=s.provider.proposals[s.selectedIndex]?.text;if(e)return void this.autoComplete.provider?.selectProposal(e)}this.stopEdition(e)}}insertAutoCompleteValue(e){this.autoComplete.provider?.selectProposal(e)}selectAutoCompleteIndex(e){this.autoComplete.selectIndex(me(0,e,10))}moveAutoCompleteSelection(e){this.autoComplete.moveSelection(e)}canStartComposerRangeSelection(){if(at(this._currentContent)){const e=this.tokenAtCursor;if(!e)return!1;const t=this.currentTokens.map(e=>e.start).indexOf(e.start);let s=t,o=e;for(;!["ARG_SEPARATOR","ARRAY_ROW_SEPARATOR","LEFT_PAREN","LEFT_BRACE","OPERATOR"].includes(o.type)||Yc.includes(o.value);){if("SPACE"!==o.type||s<1)return!1;s--,o=this.currentTokens[s]}for(s=t+1,o=this.currentTokens[s];o&&!["ARG_SEPARATOR","ARRAY_ROW_SEPARATOR","RIGHT_PAREN","RIGHT_BRACE","OPERATOR"].includes(o.type);){if("SPACE"!==o.type)return!1;s++,o=this.currentTokens[s]}return!0}return!1}getNumberOfMissingParenthesis(e){return e.filter(e=>"LEFT_PAREN"===e.type).length-e.filter(e=>"RIGHT_PAREN"===e.type).length}}class zV extends VV{args;constructor(e,t){super(e),this.args=t,this._currentContent=this.getComposerContent().text}getAutoCompleteProviders(){const e=super.getAutoCompleteProviders(),t=this.args().contextualAutocomplete;return t&&e.push(t),e}getZoneReference(e){const t=super.getZoneReference(e);return this.args().defaultStatic?Er(t,"colrow"):t}getComposerContent(){let e=this._currentContent;if("inactive"===this.editionMode){const t=this.args().defaultRangeSheetId;e=qf(this.args().content).map(e=>{if("REFERENCE"===e.type){const s=this.getters.getRangeFromSheetXC(t,e.value);return this.getters.getRangeString(s,this.getters.getActiveSheetId())}return e.value}).join("")}return{text:Sh(e,this.getters.getLocale())}}stopEdition(){this._stopEdition()}confirmEdition(e){this.args().onConfirm(e)}getTokenColor(e){if("SYMBOL"===e.type){const t=this.args().getContextualColoredSymbolToken?.(e);if(t)return t}return super.getTokenColor(e)}}class HV extends t.Component{static template="o-spreadsheet-StandaloneComposer";static props={composerContent:{type:String,optional:!0},defaultRangeSheetId:{type:String,optional:!0},defaultStatic:{type:Boolean,optional:!0},onConfirm:Function,contextualAutocomplete:{type:Object,optional:!0},placeholder:{type:String,optional:!0},title:{type:String,optional:!0},class:{type:String,optional:!0},invalid:{type:Boolean,optional:!0},autofocus:{type:Boolean,optional:!0},getContextualColoredSymbolToken:{type:Function,optional:!0}};static components={Composer:_V};static defaultProps={composerContent:"",defaultStatic:!1};composerFocusStore;standaloneComposerStore;composerInterface;spreadsheetRect=ZL();setup(){this.composerFocusStore=Tv(zv);const e=Av(zV,()=>({onConfirm:this.props.onConfirm,content:this.props.composerContent,defaultStatic:this.props.defaultStatic??!1,contextualAutocomplete:this.props.contextualAutocomplete,defaultRangeSheetId:this.props.defaultRangeSheetId,getContextualColoredSymbolToken:this.props.getContextualColoredSymbolToken}));this.standaloneComposerStore=e,this.composerInterface={id:"standaloneComposer",get editionMode(){return e.editionMode},startEdition:this.standaloneComposerStore.startEdition,setCurrentContent:this.standaloneComposerStore.setCurrentContent,stopEdition:this.standaloneComposerStore.stopEdition},t.onMounted(()=>{this.props.autofocus&&"inactive"===this.focus&&(this.composerFocusStore.focusComposer(this.composerInterface,{}),this.composerFocusStore.activeComposer.editionMode)})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get composerStyle(){return this.props.invalid?JF({padding:"1px 0px 0px 0px"}):JF({padding:"1px 0px"})}get containerClass(){return["inactive"===this.focus?"":"active",this.props.invalid?"o-invalid":"",this.props.class||""].join(" ")}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}}class UV extends t.Component{static template="o-spreadsheet-CriterionInput";static props={value:{type:String,optional:!0},criterionType:String,onValueChanged:Function,onKeyDown:{type:Function,optional:!0},focused:{type:Boolean,optional:!0},onBlur:{type:Function,optional:!0},onFocus:{type:Function,optional:!0},disableFormulas:{type:Boolean,optional:!0}};static defaultProps={value:"",onKeyDown:()=>{},focused:!1,onBlur:()=>{}};static components={StandaloneComposer:HV};inputRef=t.useRef("input");setup(){t.useEffect(()=>{this.props.focused&&this.inputRef.el&&this.inputRef.el.focus()},()=>[this.props.focused,this.inputRef.el])}state=t.useState({shouldDisplayError:!!this.props.value});get placeholder(){return"onlyFormulas"===this.allowedValues?Cs("Formula"):"onlyLiterals"===this.allowedValues?Cs("Value"):Cs("Value or formula")}get allowedValues(){const e=W_.get(this.props.criterionType);if("onlyFormulas"===e.allowedValues&&this.props.disableFormulas)throw new Error(`Cannot disable formulas for criterion type ${this.props.criterionType} that accept only formulas`);return(this.props.disableFormulas?"onlyLiterals":e.allowedValues)??"any"}onInputValueChanged(e){this.state.shouldDisplayError=!0,this.props.onValueChanged(e.target.value)}onChangeComposerValue(e){this.state.shouldDisplayError=!0,this.props.onValueChanged(e)}getDataValidationRuleInputComposerProps(){return{onConfirm:e=>this.onChangeComposerValue(e),composerContent:this.props.value,placeholder:this.placeholder,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId(),invalid:this.state.shouldDisplayError&&!!this.errorMessage,defaultStatic:!0,autofocus:this.props.focused}}get errorMessage(){if(this.state.shouldDisplayError)return this.env.model.getters.getDataValidationInvalidCriterionValueMessage(this.props.criterionType,bh(this.props.value,this.env.model.getters.getLocale()))}}const BV={today:Cs("today"),yesterday:Cs("yesterday"),tomorrow:Cs("tomorrow"),lastWeek:Cs("in the past week"),lastMonth:Cs("in the past month"),lastYear:Cs("in the past year"),exactDate:Cs("exact date")};class GV extends pV{static template="o-spreadsheet-DataValidationDateCriterion";static components={CriterionInput:UV};get currentDateValue(){return this.props.criterion.dateValue||"exactDate"}onValueChanged(e){this.updateCriterion({values:[e],dateValue:this.currentDateValue})}onDateValueChanged(e){const t=e.target.value;this.updateCriterion({dateValue:t})}get dateValues(){return Object.keys(BV).map(e=>({value:e,title:BV[e]}))}}class WV extends pV{static template="o-spreadsheet-DoubleInputCriterionForm";static components={CriterionInput:UV};onFirstValueChanged(e){const t=this.props.criterion.values;this.updateCriterion({values:[e,t[1]||""]})}onSecondValueChanged(e){const t=this.props.criterion.values;this.updateCriterion({values:[t[0]||"",e]})}}class $V extends pV{static template="o-spreadsheet-SingleInputCriterionForm";static components={CriterionInput:UV};onValueChanged(e){const t=he(this.props.criterion);t.values[0]=e,this.updateCriterion(t)}}function qV(e,t){const s=()=>{window.removeEventListener("pointerup",o,{capture:!0}),window.removeEventListener("dragstart",i),window.removeEventListener("pointermove",e),window.removeEventListener("wheel",e)},o=e=>{t(e),s()};function i(e){e.preventDefault()}return window.addEventListener("pointerup",o,{capture:!0}),window.addEventListener("dragstart",i),window.addEventListener("pointermove",e),window.addEventListener("wheel",e,{passive:!1}),s}const ZV=216;class jV extends t.Component{static template="o-spreadsheet-ColorPicker";static props={onColorPicked:Function,currentColor:{type:String,optional:!0},maxHeight:{type:Number,optional:!0},anchorRect:Object,disableNoColor:{type:Boolean,optional:!0}};static defaultProps={currentColor:""};static components={Popover:jL};COLORS=D;state=t.useState({showGradient:!1,currentHslaColor:Xv(this.props.currentColor)?{...nb(this.props.currentColor),a:1}:{h:0,s:100,l:100,a:1},customHexColor:Xv(this.props.currentColor)?Yv(this.props.currentColor):""});get colorPickerStyle(){return void 0!==this.props.maxHeight&&this.props.maxHeight<=0?JF({display:"none"}):""}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"bottom-left",verticalOffset:0}}get gradientHueStyle(){return JF({background:`hsl(${this.state.currentHslaColor?.h||0} 100% 50%)`})}get sliderStyle(){const e=this.state.currentHslaColor?.h||0;return JF({"margin-left":`${me(Math.round(e/360*ZV),1,ZV)-9}px`})}get pointerStyle(){const{s:e,l:t}=this.state.currentHslaColor||{s:0,l:0};return JF({left:`${-8+Math.round(ZV*me(e/100,0,1))}px`,top:`${-8+Math.round(186*me(1-2*t/(200-e),0,1))}px`,background:ib(this.state.currentHslaColor)})}get colorPreviewStyle(){return JF({"background-color":ib(this.state.currentHslaColor)})}get checkmarkColor(){return Uy(this.props.currentColor)}get isHexColorInputValid(){return!this.state.customHexColor||Xv(this.state.customHexColor)}setCustomGradient({x:e,y:t}){const s=me(e,0,ZV),o=me(t,0,186),i=s/ZV,n=100*i,r=100*(1-o/186)*(1-.5*i);this.updateColor({s:n,l:r})}setCustomHue(e){const t=Math.round(me(360*e/ZV,0,359));this.updateColor({h:t})}updateColor(e){this.state.currentHslaColor={...this.state.currentHslaColor,...e},this.state.customHexColor=ib(this.state.currentHslaColor)}onColorClick(e){e&&this.props.onColorPicked(Yv(e))}resetColor(){this.props.onColorPicked("")}toggleColorPicker(){this.state.showGradient=!this.state.showGradient}dragGradientPointer(e){const t={x:e.offsetX,y:e.offsetY};this.setCustomGradient(t);const s=e.clientX,o=e.clientY;qV(e=>{const i=e.clientX,n=e.clientY,r={x:t.x+(i-s),y:t.y+(n-o)};this.setCustomGradient(r)},()=>{})}dragHuePointer(e){const t=e.offsetX,s=e.clientX;this.setCustomHue(t);qV(e=>{const o=e.clientX,i=t+(o-s);this.setCustomHue(i)},()=>{})}setHexColor(e){const t=e.target.value.replace("##","#").slice(0,7);this.state.customHexColor=t,Xv(t)&&(this.state.currentHslaColor={...nb(t),a:1})}addCustomColor(e){(function(e){try{return ib(e),!0}catch(e){return!1}})(this.state.currentHslaColor)&&Xv(this.state.customHexColor)&&this.props.onColorPicked(Yv(this.state.customHexColor))}isSameColor(e,t){return function(e,t,s=0){if(!Xv(e)||!Xv(t))return!1;const o=tb(e),i=tb(t);return o.a===i.a&&Math.sqrt(((o.r-i.r)/255)**2+((o.g-i.g)/255)**2+((o.b-i.b)/255)**2)<=s}(e,t)}}class YV extends t.Component{static template="o_spreadsheet.Section";static props={class:{type:String,optional:!0},title:{type:String,optional:!0},slots:Object}}class XV extends t.Component{static template="o-spreadsheet.RoundColorPicker";static components={Section:YV,ColorPicker:jV};static props={currentColor:{type:String,optional:!0},title:{type:String,optional:!0},onColorPicked:Function,disableNoColor:{type:Boolean,optional:!0}};colorPickerButtonRef=t.useRef("colorPickerButton");state;setup(){this.state=t.useState({pickerOpened:!1}),t.useExternalListener(window,"click",this.closePicker)}closePicker(){this.state.pickerOpened=!1}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.props.onColorPicked(e),this.state.pickerOpened=!1}get colorPickerAnchorRect(){return FN(this.colorPickerButtonRef.el)}get buttonStyle(){return JF({background:this.props.currentColor})}}function KV(){let e;const s=document.body.style.cursor;let o=[];const i=()=>{e=void 0,document.body.style.cursor=s,o.forEach(e=>e()),o=[]};t.onWillUnmount(()=>{i()});const n=t.useState({itemsStyle:{},draggedItemId:void 0,start:(t,r)=>{n.cancel=()=>{n.draggedItemId=void 0,n.itemsStyle={},document.body.style.cursor=s,r.onCancel?.(),i()};document.body.style.cursor="move",n.draggedItemId=r.draggedItemId;const a="horizontal"===t?new tz(r.scrollableContainerEl):new ez(r.scrollableContainerEl);e=new JV({...r,container:a,onChange:()=>{document.body.style.cursor="move",e&&(Object.assign(n.itemsStyle,e.getItemStyles()),r.onChange?.())},onDragEnd:(e,t)=>{n.draggedItemId=void 0,n.itemsStyle={},document.body.style.cursor=s,r.onDragEnd?.(e,t),i()},onCancel:n.cancel});const l=qV(e.onMouseMove.bind(e),e.onMouseUp.bind(e));o.push(l);const c=e.onScroll.bind(e);r.scrollableContainerEl.addEventListener("scroll",c),o.push(()=>r.scrollableContainerEl.removeEventListener("scroll",c)),o.push(e.destroy.bind(e))},cancel:()=>{}});return n}class JV{draggedItemId;items;container;initialMousePosition;currentMousePosition;initialScroll;minPosition;maxPosition;edgeScrollIntervalId;onChange;onCancel;onDragEnd;deadZone;constructor(e){this.items=e.items.map(e=>({...e,positionAtStart:e.position})),this.draggedItemId=e.draggedItemId,this.container=e.container,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onDragEnd=e.onDragEnd,this.initialMousePosition=e.initialMousePosition,this.currentMousePosition=e.initialMousePosition,this.initialScroll=this.container.scroll,this.minPosition=this.items[0].position,this.maxPosition=this.items[this.items.length-1].position+this.items[this.items.length-1].size}getItemStyles(){const e={};for(const t of this.items)e[t.id]=this.getItemStyle(t.id);return e}getItemStyle(e){const t=this.container.cssPositionProperty,s={position:"relative"};return s[t]=(this.getItemsPositions()[e]||0)+"px",s.transition=`${t} 0.5s`,s["pointer-events"]="none",this.draggedItemId===e&&(s.transition=`${t} 0s`,s["z-index"]="1000"),JF(s)}onScroll(){this.moveDraggedItemToPosition(this.currentMousePosition+this.scrollOffset)}onMouseMove(e){if(e.button>1)return void this.onCancel();const t=this.container.getMousePosition(e);this.currentMousePosition=t,t<this.container.start||t>this.container.end?this.startEdgeScroll(t<this.container.start?-1:1):(this.stopEdgeScroll(),this.moveDraggedItemToPosition(t+this.scrollOffset))}moveDraggedItemToPosition(e){const t=this.getHoveredItemIndex(e,this.items),s=this.items.findIndex(e=>e.id===this.draggedItemId),o=this.items[s];if(this.deadZone&&this.isInZone(e,this.deadZone))return void this.onChange(this.getItemsPositions());if(this.isInZone(e,{start:o.position,end:o.position+o.size})&&(this.deadZone=void 0),s===t)return void this.onChange(this.getItemsPositions());const i=Math.min(s,t),n=Math.max(s,t),r=Math.sign(t-s);let a=0;for(let e=i;e<=n;e++)e!==s&&(this.items[e].position-=r*o.size,a+=this.items[e].size);o.position+=r*a,this.items.sort((e,t)=>e.position-t.position),this.deadZone=r>0?{start:e,end:o.position}:{start:o.position+o.size,end:e},this.onChange(this.getItemsPositions())}onMouseUp(e){0!==e.button&&this.onCancel(),e.stopPropagation(),e.preventDefault();const t=this.items.findIndex(e=>e.id===this.draggedItemId);return this.onDragEnd(this.draggedItemId,t),this.stopEdgeScroll(),!1}startEdgeScroll(e){this.edgeScrollIntervalId||(this.edgeScrollIntervalId=window.setInterval(()=>{const t=3*e;this.container.scroll+=t},5))}stopEdgeScroll(){window.clearInterval(this.edgeScrollIntervalId),this.edgeScrollIntervalId=void 0}getHoveredItemIndex(e,t){return e<=this.minPosition?0:e>=this.maxPosition?t.length-1:t.findIndex(t=>t.position+t.size>=e)}getItemsPositions(){const e={};for(const t of this.items){if(t.id!==this.draggedItemId){e[t.id]=t.position-t.positionAtStart;continue}let s=this.currentMousePosition-this.initialMousePosition+this.scrollOffset;s=Math.max(this.minPosition-t.positionAtStart,s),s=Math.min(this.maxPosition-t.positionAtStart-t.size,s),e[t.id]=s}return e}isInZone(e,t){return e>=t.start&&e<=t.end}get scrollOffset(){return this.container.scroll-this.initialScroll}destroy(){this.stopEdgeScroll()}}class QV{el;constructor(e){this.el=e}get containerRect(){return this.el.getBoundingClientRect()}}class ez extends QV{get start(){return this.containerRect.top}get end(){return this.containerRect.bottom}get cssPositionProperty(){return"top"}get scroll(){return this.el.scrollTop}set scroll(e){this.el.scrollTop=e}getMousePosition(e){return e.clientY}}class tz extends QV{get start(){return this.containerRect.left}get end(){return this.containerRect.right}get cssPositionProperty(){return"left"}get scroll(){return this.el.scrollLeft}set scroll(e){this.el.scrollLeft=e}getMousePosition(e){return e.clientX}}class sz{mutators=["focus","unfocus"];focusedElement=null;focus(e){this.focusedElement=e}unfocus(e){this.focusedElement&&this.focusedElement===e&&(this.focusedElement=null)}}class oz extends Lv{initialRanges;inputHasSingleRange;colors;disabledRanges;mutators=["resetWithRanges","focusById","unfocus","addEmptyRange","removeRange","changeRange","reset","confirm","updateColors","updateDisabledRanges"];ranges=[];focusedRangeIndex=null;inputSheetId;focusStore=this.get(sz);highlightStore=this.get(NV);constructor(e,t=[],s=!1,o=[],i=[]){if(super(e),this.initialRanges=t,this.inputHasSingleRange=s,this.colors=o,this.disabledRanges=i,s&&t.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");this.inputSheetId=this.getters.getActiveSheetId(),this.resetWithRanges(t),this.highlightStore.register(this),this.onDispose(()=>{this.unfocus(),this.highlightStore.unRegister(this)})}handleEvent(e){if(null===this.focusedRangeIndex)return;const t=this.inputSheetId,s=this.getters.getActiveSheetId(),o=e.options.unbounded?this.getters.getUnboundedZone(s,e.anchor.zone):e.anchor.zone,i=this.getters.getRangeFromZone(s,o);if("newAnchor"===e.mode&&!this.inputHasSingleRange&&""!==this.ranges[this.focusedRangeIndex].xc.trim()){const e=this.getters.getSelectionRangeString(i,t);this.insertNewRange(this.ranges.length,[e]),this.focusLast()}else{let e=i.parts;const s=this.ranges[this.focusedRangeIndex].xc.trim();s&&(e=this.getters.getRangeFromSheetXC(t,s).parts);const o={...i,parts:e},n=this.getters.getSelectionRangeString(o,t);this.setRange(this.focusedRangeIndex,[n])}}handle(e){switch(e.type){case"ACTIVATE_SHEET":if(e.sheetIdFrom!==e.sheetIdTo){const{col:t,row:s}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),o=this.getters.expandZone(e.sheetIdTo,Jt({col:t,row:s}));this.model.selection.resetAnchor(this,{cell:{col:t,row:s},zone:o})}break;case"START_CHANGE_HIGHLIGHT":const t=this.getters.getActiveSheetId(),s=this.getters.expandZone(t,e.zone),o=this.ranges.findIndex(e=>{const{xc:o,sheetName:i}=yr(e.xc),n=i||this.getters.getSheetName(this.inputSheetId);if(this.getters.getSheetName(t)!==n)return!1;const r=this.getters.getRangeFromSheetXC(t,o);return Ht(this.getters.expandZone(t,r.zone),s)});if(-1!==o){this.focus(o);const{left:e,top:t}=s;this.model.selection.resetAnchor(this,{cell:{col:e,row:t},zone:s})}}}changeRange(e,t){if(this.inputHasSingleRange&&t.split(",").length>1)return;const s=this.getIndex(e);if(null!==s&&this.focusedRangeIndex!==s&&this.focus(s),null!==s){const e=t.replace(/^,+/,"").split(",").map(e=>e.trim());this.setRange(s,e),this.captureSelection()}}addEmptyRange(){this.inputHasSingleRange&&1===this.ranges.length||(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}removeRange(e){if(1===this.ranges.length)return;const t=this.getIndex(e);null!==t&&this.removeRangeByIndex(t)}updateColors(e){this.colors=e;const t=new yb(this.ranges.length,this.colors);this.ranges=this.ranges.map(e=>({...e,color:t.next()}))}updateDisabledRanges(e){this.disabledRanges=e}confirm(){for(const e of this.selectionInputs)""===e.xc&&this.removeRange(e.id);const e=this.getters.getActiveSheetId();this.inputSheetId!==e&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:this.inputSheetId}),this.selectionInputValues.join()!==this.initialRanges.join()&&this.resetWithRanges(this.selectionInputValues),this.initialRanges=this.selectionInputValues,this.unfocus()}reset(){this.resetWithRanges(this.initialRanges),this.confirm()}get selectionInputValues(){return this.cleanInputs(this.ranges.map(e=>e.xc?e.xc:""))}get selectionInputs(){return this.ranges.map((e,t)=>Object.assign({},e,{color:this.hasMainFocus&&null!==this.focusedRangeIndex&&this.getters.isRangeValid(e.xc)?e.color:null,isFocused:this.hasMainFocus&&this.focusedRangeIndex===t,isValidRange:""===e.xc||this.getters.isRangeValid(e.xc),disabled:this.disabledRanges?.[t]}))}get isResettable(){return this.initialRanges.join()!==this.ranges.map(e=>e.xc).join()}get isConfirmable(){return this.selectionInputs.every(e=>e.isValidRange)}get hasFocus(){return this.selectionInputs.some(e=>e.isFocused)}get hasMainFocus(){const e=this.focusStore.focusedElement;return!!e&&e===this}get highlights(){return this.hasMainFocus?this.ranges.map(e=>this.inputToHighlights(e)).flat():[]}focusById(e){this.focus(this.getIndex(e))}focus(e){this.focusStore.focus(this),this.focusedRangeIndex=e,this.captureSelection()}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null,this.focusStore.unfocus(this),this.model.selection.release(this)}captureSelection(){if(null===this.focusedRangeIndex)return;const e=this.ranges[this.focusedRangeIndex],t=this.getters.getActiveSheetId(),s=this.getters.getRangeFromSheetXC(t,e?.xc||"A1").zone;this.model.selection.capture(this,{cell:{col:s.left,row:s.top},zone:s},{handleEvent:this.handleEvent.bind(this),release:this.unfocus.bind(this)})}resetWithRanges(e){e.length&&e.every(e=>this.getters.isRangeValid(e))&&(this.initialRanges=e),this.ranges=[],this.insertNewRange(0,e),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){const s=Math.max(0,...this.ranges.map(e=>Number(e.id))),o=new yb(this.ranges.length,this.colors);for(let t=0;t<e;t++)o.next();this.ranges.splice(e,0,...t.map((e,t)=>({xc:e,id:s+t+1,color:o.next()})))}setRange(e,t){const[,...s]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,s),s.length&&this.focus(e+s.length)}removeRangeByIndex(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const s=this.cleanInputs([e]).filter(e=>this.getters.isRangeValid(e)).filter(e=>this.shouldBeHighlighted(this.inputSheetId,e));return s.map(e=>{const{sheetName:s}=yr(e),o=s&&this.getters.getSheetIdByName(s)||this.inputSheetId;return{range:this.getters.getRangeFromSheetXC(o,e),color:t,interactive:!0}})}cleanInputs(e){return e.map(e=>e.split(",")).flat().map(e=>e.trim()).filter(e=>""!==e)}shouldBeHighlighted(e,t){const{sheetName:s}=yr(t),o=this.getters.getSheetIdByName(s),i=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(o===i||void 0===o&&i===e)}getIndex(e){const t=this.ranges.findIndex(t=>t.id===e);return t>=0?t:null}}class iz extends t.Component{static template="o-spreadsheet-SelectionInput";static props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},required:{type:Boolean,optional:!0},autofocus:{type:Boolean,optional:!0},isInvalid:{type:Boolean,optional:!0},class:{type:String,optional:!0},onSelectionChanged:{type:Function,optional:!0},onSelectionConfirmed:{type:Function,optional:!0},onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},colors:{type:Array,optional:!0,default:[]},disabledRanges:{type:Array,optional:!0,default:[]},disabledRangeTitle:{type:String,optional:!0}};state=t.useState({isMissing:!1,mode:"select-range"});dragAndDrop=KV();focusedInput=t.useRef("focusedInput");selectionRef=t.useRef("o-selection");store;get ranges(){return this.store.selectionInputs}get canAddRange(){return!this.props.hasSingleRange}get isInvalid(){return this.props.isInvalid||this.state.isMissing}get isConfirmable(){return this.store.isConfirmable}get isResettable(){return this.store.isResettable}get hasDisabledRanges(){return this.store.disabledRanges.some(Boolean)}setup(){t.useEffect(()=>this.focusedInput.el?.focus(),()=>[this.focusedInput.el]),t.useEffect(()=>{this.store.hasFocus&&null===this.selectionRef.el?.offsetParent&&this.reset()}),this.store=Av(oz,this.props.ranges,this.props.hasSingleRange||!1,this.props.colors,this.props.disabledRanges),this.props.autofocus&&this.store.focusById(this.store.selectionInputs[0]?.id),t.onWillUpdateProps(e=>{e.ranges.join()!==this.store.selectionInputValues.join()&&this.triggerChange(),e.ranges.join()!==this.props.ranges.join()&&e.ranges.join()!==this.store.selectionInputValues.join()&&this.store.resetWithRanges(e.ranges),e.colors?.join()!==this.props.colors?.join()&&e.colors?.join()!==this.store.colors.join()&&this.store.updateColors(e.colors||[]),Le(e.disabledRanges,this.props.disabledRanges)||Le(e.disabledRanges,this.store.disabledRanges)||this.store.updateDisabledRanges(e.disabledRanges||[])})}startDragAndDrop(e,t){if(0!==t.button||"SELECT"===t.target.tagName)return;const s=this.getRangeElementsRects(),o=this.ranges.map(e=>e.id),i=o.map((e,t)=>({id:e.toString(),size:s[t].height,position:s[t].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.toString(),initialMousePosition:t.clientY,items:i,scrollableContainerEl:this.selectionRef.el,onDragEnd:(t,s)=>{const i=o.findIndex(t=>t===e);if(i===s)return;const n=fe(0,o.length);n.splice(i,1),n.splice(s,0,i),this.props.onSelectionReordered?.(n),this.props.onSelectionConfirmed?.(),this.store.confirm()}})}getRangeElementsRects(){return Array.from(this.selectionRef.el.children).map(e=>e.getBoundingClientRect())}getColor(e){return e.color?JF({color:e.color}):""}triggerChange(){const e=this.store.selectionInputValues;this.props.onSelectionChanged?.(e)}onKeydown(e){if("F2"===e.key)e.preventDefault(),e.stopPropagation(),this.state.mode="select-range"===this.state.mode?"text-edit":"select-range";else if(e.key.startsWith("Arrow"))e.stopPropagation(),"select-range"===this.state.mode&&(e.preventDefault(),vV(e,this.env.model.selection));else if("Enter"===e.key){e.target.blur(),this.isConfirmable&&this.confirm()}}extractRanges(e){return this.props.hasSingleRange?e.split(",")[0]:e}focus(e){this.state.isMissing=!1,this.state.mode="select-range",this.store.focusById(e)}addEmptyInput(){this.store.addEmptyRange()}removeInput(e){const t=this.store.selectionInputs.findIndex(t=>t.id===e);this.ranges.find(t=>t.id===e)?.xc&&(this.props.onSelectionRemoved?.(t),this.props.onSelectionConfirmed?.()),this.store.removeRange(e)}onInputChanged(e,t){const s=t.target,o=this.extractRanges(s.value);this.store.changeRange(e,o),this.triggerChange()}reset(){this.store.reset(),this.triggerChange()}confirm(){this.store.confirm();const e=this.store.selectionInputs.some(e=>this.env.model.getters.isRangeValid(e.xc));this.props.required&&!e&&(this.state.isMissing=!0),this.props.onSelectionChanged?.(this.store.selectionInputValues),this.props.onSelectionConfirmed?.()}}const nz={list:10,text:20,number:30,date:40,misc:50},rz=new Jg;function az(e,t){const s=rz.getAll().filter(e=>t.has(e.type)).sort((e,t)=>e.category===t.category?e.sequence-t.sequence:nz[e.category]-nz[t.category]);return Sv(s.map((t,o)=>({name:W_.get(t.type).name,id:t.type,separator:t.category!==s[o+1]?.category,execute:()=>e(t.type)})))}rz.add("containsText",{type:"containsText",component:$V,category:"text",sequence:10}),rz.add("notContainsText",{type:"notContainsText",component:$V,category:"text",sequence:20}),rz.add("beginsWithText",{type:"beginsWithText",component:$V,category:"text",sequence:25}),rz.add("endsWithText",{type:"endsWithText",component:$V,category:"text",sequence:26}),rz.add("isEqualText",{type:"isEqualText",component:$V,category:"text",sequence:30}),rz.add("isEmail",{type:"isEmail",component:void 0,category:"text",sequence:40}),rz.add("isLink",{type:"isLink",component:void 0,category:"text",sequence:50}),rz.add("dateIs",{type:"dateIs",component:GV,category:"date",sequence:20}),rz.add("dateIsBefore",{type:"dateIsBefore",component:GV,category:"date",sequence:30}),rz.add("dateIsOnOrBefore",{type:"dateIsOnOrBefore",component:GV,category:"date",sequence:40}),rz.add("dateIsAfter",{type:"dateIsAfter",component:GV,category:"date",sequence:50}),rz.add("dateIsOnOrAfter",{type:"dateIsOnOrAfter",component:GV,category:"date",sequence:60}),rz.add("dateIsBetween",{type:"dateIsBetween",component:WV,category:"date",sequence:70}),rz.add("dateIsNotBetween",{type:"dateIsNotBetween",component:WV,category:"date",sequence:80}),rz.add("dateIsValid",{type:"dateIsValid",component:void 0,category:"date",sequence:10}),rz.add("isEqual",{type:"isEqual",component:$V,category:"number",sequence:10}),rz.add("isNotEqual",{type:"isNotEqual",component:$V,category:"number",sequence:20}),rz.add("isGreaterThan",{type:"isGreaterThan",component:$V,category:"number",sequence:50}),rz.add("isGreaterOrEqualTo",{type:"isGreaterOrEqualTo",component:$V,category:"number",sequence:60}),rz.add("isLessThan",{type:"isLessThan",component:$V,category:"number",sequence:30}),rz.add("isLessOrEqualTo",{type:"isLessOrEqualTo",component:$V,category:"number",sequence:40}),rz.add("isBetween",{type:"isBetween",component:WV,category:"number",sequence:70}),rz.add("isNotBetween",{type:"isNotBetween",component:WV,category:"number",sequence:80}),rz.add("isBoolean",{type:"isBoolean",component:void 0,category:"misc",sequence:10}),rz.add("isValueInList",{type:"isValueInList",component:class extends pV{static template="o-spreadsheet-ListCriterionForm";static components={CriterionInput:UV,RoundColorPicker:XV};state=t.useState({numberOfValues:Math.max(this.props.criterion.values.length,2),focusedValueIndex:this.props.autofocus?0:void 0});setup(){super.setup();const e=e=>{void 0===e.criterion.displayStyle&&this.updateCriterion({displayStyle:"chip"})};t.onWillUpdateProps(e),t.onWillStart(()=>e(this.props))}onValueChanged(e,t){const s=[...this.displayedValues];s[t]=e,this.updateCriterion({values:s})}onColorChanged(e,t){const s={...this.props.criterion.colors};s[t]=e||void 0,this.updateCriterion({colors:s})}onAddAnotherValue(){this.state.numberOfValues++}removeItem(e){const t=[...this.displayedValues];t.splice(e,1),this.state.numberOfValues--,this.updateCriterion({values:t})}onChangedDisplayStyle(e){const t=e.target.value;this.updateCriterion({displayStyle:t})}onKeyDown(e,t){"Enter"!==e.key&&"Tab"!==e.key||t!==this.state.numberOfValues-1?"Enter"===e.key&&(this.state.focusedValueIndex=t+1):(this.onAddAnotherValue(),this.state.focusedValueIndex=t+1,e.preventDefault())}onBlurInput(){this.state.focusedValueIndex=void 0}get displayedValues(){const e=[];for(let t=0;t<this.state.numberOfValues;t++)e.push(this.props.criterion.values[t]||"");return e}},category:"list",sequence:10}),rz.add("isValueInRange",{type:"isValueInRange",component:class extends pV{static template="o-spreadsheet-ValueInRangeCriterionForm";static components={RoundColorPicker:XV,SelectionInput:iz};setup(){super.setup();const e=e=>{void 0===e.criterion.displayStyle&&this.updateCriterion({displayStyle:"chip"})};t.onWillUpdateProps(e),t.onWillStart(()=>e(this.props))}onRangeChanged(e){this.updateCriterion({values:[e]})}onChangedDisplayStyle(e){const t=e.target.value;this.updateCriterion({displayStyle:t})}onColorChanged(e,t){const s={...this.props.criterion.colors};s[t]=e||void 0,this.updateCriterion({colors:s})}get values(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getDataValidationRangeValues(e,this.props.criterion);return new Set(t)}},category:"list",sequence:20}),rz.add("customFormula",{type:"customFormula",component:$V,category:"misc",sequence:20}),rz.add("isEmpty",{type:"isEmpty",component:void 0,category:"misc",sequence:5}),rz.add("isNotEmpty",{type:"isNotEmpty",component:void 0,category:"misc",sequence:6});class lz extends t.Component{static template="o-spreadsheet-SelectMenu";static props={menuItems:Array,selectedValue:String,class:{type:String,optional:!0}};static components={MenuPopover:JL};menuId=(new Tr).uuidv4();selectRef=t.useRef("select");state=t.useState({isMenuOpen:!1});onClick(e){e.closedMenuId!==this.menuId&&(this.state.isMenuOpen=!this.state.isMenuOpen)}onMenuClosed(){this.state.isMenuOpen=!1}get menuAnchorRect(){return ON(this.selectRef)}}class cz extends t.Component{static template="o-spreadsheet-FilterMenuCriterion";static props={filterPosition:Object,onCriterionChanged:Function,criterionOperators:Array};static components={SelectMenu:lz};state;setup(){t.onWillUpdateProps(e=>{Le(e.filterPosition,this.props.filterPosition)||(this.state.criterion=this.getFilterCriterionValue(e.filterPosition))}),this.state=t.useState({criterion:this.getFilterCriterionValue(this.props.filterPosition)})}getFilterCriterionValue(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getFilterCriterionValue({sheetId:t,...e});return"criterion"===s?.filterType?he(s):{filterType:"criterion",type:"none",values:[]}}get criterionMenuItems(){return[Cv({name:Cs("None"),id:"none",separator:!0,execute:()=>this.onCriterionTypeChange("none")}),...az(e=>this.onCriterionTypeChange(e),new Set(this.props.criterionOperators))]}get selectedCriterionName(){return"none"===this.state.criterion.type?Cs("None"):W_.get(this.state.criterion.type).name}get criterionComponent(){return"none"===this.state.criterion.type?void 0:rz.get(this.state.criterion.type).component}onCriterionChanged(e){this.state.criterion.values=e.values,this.state.criterion.dateValue=e.dateValue,this.props.onCriterionChanged(this.state.criterion)}onCriterionTypeChange(e){this.state.criterion.type=e,this.props.onCriterionChanged(this.state.criterion)}}class hz extends t.Component{static template="o-spreadsheet.Checkbox";static props={label:{type:String,optional:!0},value:{type:Boolean,optional:!0},className:{type:String,optional:!0},name:{type:String,optional:!0},title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},onChange:Function};static defaultProps={value:!1};onChange(e){const t=e.target.checked;this.props.onChange(t)}}class dz extends t.Component{static template="o-spreadsheet-FilterMenuValueItem";static components={Checkbox:hz};static props={value:String,isChecked:Boolean,isSelected:Boolean,onMouseMove:Function,onClick:Function,scrolledTo:{type:String,optional:!0}};itemRef=t.useRef("menuValueItem");setup(){t.onWillPatch(()=>{this.props.scrolledTo&&this.scrollListToSelectedValue()})}scrollListToSelectedValue(){this.itemRef.el&&this.itemRef.el.scrollIntoView?.({block:"bottom"===this.props.scrolledTo?"end":"start"})}}class uz extends t.Component{static template="o-spreadsheet-FilterMenuValueList";static props={filterPosition:Object,onUpdateHiddenValues:Function};static components={FilterMenuValueItem:dz};state=t.useState({values:[],displayedValues:[],textFilter:"",selectedValue:void 0,numberOfDisplayedValues:50,hasMoreValues:!1});searchBar=t.useRef("filterMenuSearchBar");setup(){t.onWillUpdateProps(e=>{Le(e.filterPosition,this.props.filterPosition)||(this.state.values=this.getFilterHiddenValues(e.filterPosition),this.computeDisplayedValues())}),this.state.values=this.getFilterHiddenValues(this.props.filterPosition),this.computeDisplayedValues()}getFilterHiddenValues(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getFilter({sheetId:t,...e});if(!s)return[];const o=this.env.model.getters.getFilterValue({sheetId:t,...e});let i=(s.filteredRange?Zt(s.filteredRange.zone):[]).map(e=>({position:e,cellValue:this.env.model.getters.getEvaluatedCell({sheetId:t,...e}).formattedValue}));"criterion"!==o?.filterType&&(i=i.filter(e=>!this.env.model.getters.isRowHidden(t,e.position.row)));const n=i.map(e=>e.cellValue),r="values"===o?.filterType?o.hiddenValues:[],a=new Set(r.map(OS)),l=new Set,c=[],h=e=>{const t=OS(e);l.has(t)||(c.push({string:e||"",checked:"criterion"!==o?.filterType&&!a.has(t),normalizedValue:t}),l.add(t))};return n.forEach(h),r.forEach(h),c.sort((e,t)=>e.normalizedValue.localeCompare(t.normalizedValue,void 0,{numeric:!0,sensitivity:"base"}))}checkValue(e){this.state.selectedValue=e.string,e.checked=!e.checked,this.searchBar.el?.focus(),this.updateHiddenValues()}onMouseMove(e){this.state.selectedValue=e.string}selectAll(){this.state.displayedValues.forEach(e=>e.checked=!0),this.props.onUpdateHiddenValues([])}clearAll(){this.state.displayedValues.forEach(e=>e.checked=!1);const e=this.state.values.map(e=>e.string);this.props.onUpdateHiddenValues(e)}updateHiddenValues(){const e=this.state.values.filter(e=>!e.checked).map(e=>e.string);this.props.onUpdateHiddenValues(e)}updateSearch(e){const t=e.target;this.state.textFilter=t.value,this.state.selectedValue=void 0,this.computeDisplayedValues()}computeDisplayedValues(){const e=this.state.textFilter?LS(this.state.textFilter,this.state.values,e=>e.string):this.state.values;this.state.displayedValues=e.slice(0,this.state.numberOfDisplayedValues),this.state.hasMoreValues=e.length>this.state.numberOfDisplayedValues}loadMoreValues(){this.state.numberOfDisplayedValues+=100,this.computeDisplayedValues()}onKeyDown(e){const t=this.state.displayedValues;if(0===t.length)return;let s;if(void 0!==this.state.selectedValue){const e=t.findIndex(e=>e.string===this.state.selectedValue);s=-1===e?void 0:e}switch(e.key){case"ArrowDown":s=void 0===s?0:Math.min(s+1,t.length-1),e.preventDefault(),e.stopPropagation();break;case"ArrowUp":s=void 0===s?t.length-1:Math.max(s-1,0),e.preventDefault(),e.stopPropagation();break;case"Enter":void 0!==s&&this.checkValue(t[s]),e.stopPropagation(),e.preventDefault()}this.state.selectedValue=void 0!==s?t[s].string:void 0,"ArrowUp"!==e.key&&"ArrowDown"!==e.key||this.scrollListToSelectedValue(e.key)}clearScrolledToValue(){this.state.values.forEach(e=>e.scrolledTo=void 0)}scrollListToSelectedValue(e){this.clearScrolledToValue();const t=this.state.values.find(e=>e.string===this.state.selectedValue);t&&(t.scrolledTo="ArrowUp"===e?"top":"bottom")}}class gz extends t.Component{static template="o-spreadsheet-FilterMenu";static props={filterPosition:Object,onClosed:{type:Function,optional:!0}};static components={FilterMenuValueList:uz,SidePanelCollapsible:gV,FilterMenuCriterion:cz};criterionCategory="text";updatedCriterionValue;setup(){t.onWillUpdateProps(e=>{Le(e.filterPosition,this.props.filterPosition)||(this.updatedCriterionValue=void 0,this.criterionCategory=this.getCriterionCategory(e.filterPosition))}),this.criterionCategory=this.getCriterionCategory(this.props.filterPosition)}get isSortable(){if(!this.table)return!1;const e=this.env.model.getters.getCoreTableMatchingTopLeft(this.table.range.sheetId,this.table.range.zone);return!this.env.model.getters.isReadonly()&&"dynamic"!==e?.type}get table(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition;return this.env.model.getters.getTable({sheetId:e,...t})}get filterValueType(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition,s=this.env.model.getters.getFilterValue({sheetId:e,...t});return s?.filterType}getCriterionCategory(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getFilter({sheetId:t,...e});if(!s||!s.filteredRange)return"text";const o={text:0,number:0,date:0},i=s.filteredRange.zone;for(let s=i.top;s<=i.bottom&&!(s>100);s++){const i=this.env.model.getters.getEvaluatedCell({sheetId:t,row:s,col:e.col});i.type===Xd.text||i.type===Xd.boolean?o.text++:i.type===Xd.number&&(i.format&&ji(i.format)?o.date++:o.number++)}const n=Math.max(o.text,o.number,o.date);return Object.keys(o).find(e=>o[e]===n)||"text"}onUpdateHiddenValues(e){this.updatedCriterionValue={filterType:"values",hiddenValues:e}}onCriterionChanged(e){this.updatedCriterionValue=e}confirm(){if(!this.updatedCriterionValue)return void this.props.onClosed?.();const e=this.props.filterPosition;this.env.model.dispatch("UPDATE_FILTER",{...e,sheetId:this.env.model.getters.getActiveSheetId(),value:this.updatedCriterionValue}),this.props.onClosed?.()}get criterionOperators(){return"date"===this.criterionCategory?JN:"number"===this.criterionCategory?KN:XN}cancel(){this.props.onClosed?.()}sortFilterZone(e){const t=this.props.filterPosition,s=this.table,o=s?.range.zone;if(!t||!o||o.top===o.bottom)return;const i=this.env.model.getters.getActiveSheetId(),n={...o,top:o.top+1},r={col:t.col,row:n.top};dV(this.env,i,r,n,e,{emptyCellAsZero:!0,sortHeaders:!0}),this.props.onClosed?.()}}const pz={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:gz,cellCorner:"bottom-left"})};class mz extends t.Component{static template="o-spreadsheet-LinkDisplay";static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};cellPopovers;setup(){this.cellPopovers=Tv(aV)}get cell(){const{col:e,row:t}=this.props.cellPosition,s=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getEvaluatedCell({sheetId:s,col:e,row:t})}get link(){if(this.cell.link)return this.cell.link;const{col:e,row:t}=this.props.cellPosition;throw new Error(`LinkDisplay Component can only be used with link cells. ${St(e,t)} is not a link.`)}getUrlRepresentation(e){return fv(e,this.env.model.getters)}openLink(e){vv(this.link,this.env,HN(e))}edit(){const{col:e,row:t}=this.props.cellPosition;this.env.model.selection.selectCell(e,t),this.cellPopovers.open({col:e,row:t},"LinkEditor")}unlink(){const e=this.env.model.getters.getActiveSheetId(),{col:t,row:s}=this.props.cellPosition,o=this.env.model.getters.getCellComputedStyle({sheetId:e,col:t,row:s}),i=o?.textColor===d?void 0:o?.textColor;this.env.model.dispatch("UPDATE_CELL",{col:t,row:s,sheetId:e,content:this.link.label,style:{...o,textColor:i,underline:void 0}})}}const fz={onHover:(e,t)=>{const s=t.getEvaluatedCell(e);return!t.isDashboard()&&s.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:mz,props:{cellPosition:e},cellCorner:"bottom-left"}:{isOpen:!1}}},vz={name:Cs("Link sheet"),children:[e=>e.model.getters.getSheetIds().map(t=>e.model.getters.getSheet(t)).map(e=>({id:e.id,name:e.name,execute:()=>Ee(e.name,Ae(e.id))}))]},bz={name:Cs("Delete"),isVisible:e=>e.model.getters.getVisibleSheetIds().length>1,execute:e=>e.askConfirmation(Cs("Are you sure you want to delete this sheet?"),()=>{e.model.dispatch("DELETE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName()})}),icon:"o-spreadsheet-Icon.TRASH"},Sz={name:Cs("Duplicate"),execute:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSheetName(t),o=e.model.uuidGenerator.smallUuid(),i=e.model.getters.getDuplicateSheetName(s);e.model.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:o,sheetNameTo:i}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},icon:"o-spreadsheet-Icon.COPY"},yz=e=>({name:Cs("Rename"),execute:e.renameSheetCallback,icon:"o-spreadsheet-Icon.RENAME_SHEET"}),Cz=e=>({name:Cs("Change color"),execute:e.openSheetColorPickerCallback,icon:"o-spreadsheet-Icon.PAINT_FORMAT"}),Iz={name:Cs("Move right"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getVisibleSheetIds();return s.indexOf(t)!==s.length-1},execute:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:1}),icon:"o-spreadsheet-Icon.MOVE_SHEET_RIGHT"},wz={name:Cs("Move left"),isVisible:e=>{const t=e.model.getters.getActiveSheetId();return e.model.getters.getVisibleSheetIds()[0]!==t},execute:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:-1}),icon:"o-spreadsheet-Icon.MOVE_SHEET_LEFT"},Ez={name:Cs("Hide sheet"),isVisible:e=>1!==e.model.getters.getVisibleSheetIds().length,execute:e=>e.model.dispatch("HIDE_SHEET",{sheetId:e.model.getters.getActiveSheetId()}),icon:"o-spreadsheet-Icon.HIDE_SHEET"};class xz extends Jg{replace(e,t){return void 0===t.id&&(t.id=e),this.content[e]=t,this}addChild(e,t,s){return this._replaceChild(e,t,s,{force:!1})}replaceChild(e,t,s){return this._replaceChild(e,t,s,{force:!0})}_replaceChild(e,t,s,o={force:!0}){"function"!=typeof s&&void 0===s.id&&(s.id=e);const i=t.splice(0,1)[0];let n=this.content[i];if(!n)throw new Error(`Path ${i+":"+t.join(":")} not found`);for(const e of t){const s=n.children;if(!s||"function"==typeof s)throw new Error(`${e} is either not a node or it's dynamically computed`);if(n=s.find(t=>t.id===e),!n)throw new Error(`Path ${i+":"+t.join(":")} not found`)}n.children||(n.children=[]);const r=n.children;if(!r||"function"==typeof r)throw new Error(`${t} is either not a node or it's dynamically computed`);if("id"in s){const e=r.findIndex(e=>"id"in e&&e.id===s.id);if(e>-1){if(!o.force)throw new Error(`A child with the id "${s.id}" already exists.`);return n.children.splice(e,1,s),this}}return n.children.push(s),this}getMenuItems(){return Sv(this.getAll())}}const Rz=new xz;Rz.add("sheet",{...vz,sequence:10});class Tz extends t.Component{static template="o-spreadsheet-LinkEditor";static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};static components={MenuPopover:JL};menuItems=Rz.getMenuItems();link=t.useState(this.defaultState);menu=t.useState({isOpen:!1});linkEditorMenuButtonRef=t.useRef("linkEditorMenuButton");urlInput=t.useRef("urlInput");setup(){t.onMounted(()=>this.urlInput.el?.focus())}get defaultState(){const{col:e,row:t}=this.props.cellPosition,s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getEvaluatedCell({sheetId:s,col:e,row:t});return o.link?{url:o.link.url,label:o.formattedValue,isUrlEditable:o.link.isUrlEditable}:{label:o.formattedValue,url:"",isUrlEditable:!0}}get menuButtonRect(){return ON(this.linkEditorMenuButtonRef)}onSpecialLink(e){const{detail:t}=e,s=bv(t);s&&(this.link.url=s.url,this.link.label=s.label,this.link.isUrlEditable=s.isUrlEditable)}getUrlRepresentation(e){return fv(e,this.env.model.getters)}openMenu(){this.menu.isOpen=!0}removeLink(){this.link.url="",this.link.isUrlEditable=!0}save(){const{col:e,row:t}=this.props.cellPosition,s=this.env.model.getters.getLocale(),o=this.link.label?vh(this.link.label,s):this.link.url;this.env.model.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:this.env.model.getters.getActiveSheetId(),content:Ee(o,this.link.url)}),this.props.onClosed?.()}cancel(){this.props.onClosed?.()}onKeyDown(e){switch(e.key){case"Enter":this.link.url&&this.save(),e.stopPropagation(),e.preventDefault();break;case"Escape":this.cancel(),e.stopPropagation()}}}const Az={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:Tz,cellCorner:"bottom-left"})};rV.add("ErrorToolTip",cV).add("LinkCell",fz).add("LinkEditor",Az).add("FilterMenu",pz);const _z={type:"bar",title:{},dataSets:[],legendPosition:"none",dataSetsHaveTitle:!1,stacked:!1},Dz={type:"line",title:{},dataSets:[],legendPosition:"none",dataSetsHaveTitle:!1,stacked:!1,cumulative:!1,labelsAsText:!1};function Oz(e,t){return Pt(e.getUnboundedZone(e.getActiveSheetId(),t))}function Fz(e){if(!e.length)return"empty";const t={number:0,text:0,date:0,percentage:0};let s=0,o="empty";for(const i of e){let e=null;if(i.type===Xd.number?e=i.format&&ji(i.format)?"date":i.format?.includes("%")?"percentage":"number":i.type===Xd.text&&(e="text"),e){const i=++t[e];i>s&&(s=i,o=e)}}return o}function Pz(e,t){const s=[];for(const o of function(e){const t=new Map;for(const s of e)for(let e=s.left;e<=s.right;e++){const o=t.get(e);o?(o.top=Math.min(o.top,s.top),o.bottom=Math.max(o.bottom,s.bottom)):t.set(e,{left:e,right:e,top:s.top,bottom:s.bottom})}return Array.from(t.values())}(e)){const e=t.getEvaluatedCellsInZone(t.getActiveSheetId(),o);s.push({zone:o,type:Fz(e)})}return s}function Mz(e,t){const s=e.getEvaluatedCell({sheetId:e.getActiveSheetId(),col:t.zone.left,row:t.zone.top});return![Xd.number,Xd.empty].includes(s.type)}function Nz(e,t){const{type:s,zone:o}=e,i=t.getActiveSheetId(),n=Mz(t,e),r=Oz(t,o),a=t.getEvaluatedCell({sheetId:i,col:o.left,row:o.top});if(1===ss(o))return function(e,t){const s=t.getCellStyle({sheetId:t.getActiveSheetId(),col:e.left,row:e.top});return{type:"scorecard",title:{},keyValue:Oz(t,e),background:s?.fillColor,baselineMode:$,baselineColorUp:q,baselineColorDown:Z}}(o,t);switch(s){case"percentage":return{type:"pie",title:n?{text:String(a.value)}:{},dataSets:[{dataRange:r}],legendPosition:"none",dataSetsHaveTitle:n};case"text":const e=t.getEvaluatedCellsInZone(i,o).reduce((e,t)=>t.value===a.value?e+1:e,0),s=null!==a.value&&1===e;return{type:"pie",title:s?{text:String(a.value)}:{},dataSets:[{dataRange:r}],labelRange:r,dataSetsHaveTitle:s,aggregated:!0,legendPosition:"top"};case"date":return{...Dz,type:"line",title:n?{text:String(a.value)}:{},dataSets:[{dataRange:r}],dataSetsHaveTitle:n}}return{..._z,title:n?{text:String(a.value)}:{},dataSets:[{dataRange:r}],dataSetsHaveTitle:n}}function kz(e,t){if(2!==e.length)throw new Error("buildTwoColumnChart expects exactly two columns");if("percentage"===e[1].type)return{type:"pie",title:{},dataSets:[{dataRange:Oz(t,e[1].zone)}],labelRange:Oz(t,e[0].zone),dataSetsHaveTitle:Mz(t,e[1]),aggregated:!0,legendPosition:"none"};if("number"===e[0].type&&"number"===e[1].type)return{type:"scatter",title:{},dataSets:[{dataRange:Oz(t,e[1].zone)}],labelRange:Oz(t,e[0].zone),dataSetsHaveTitle:Mz(t,e[1]),labelsAsText:!1,legendPosition:"none"};if("date"===e[0].type&&"number"===e[1].type)return{...Dz,type:"line",dataSets:[{dataRange:Oz(t,e[1].zone)}],labelRange:Oz(t,e[0].zone),dataSetsHaveTitle:Mz(t,e[0])};if("text"===e[0].type&&"number"===e[1].type){const s=e[0],o=e[1],{uniqueCount:i,totalCount:n}=function(e,t){const s=e.getEvaluatedCellsInZone(e.getActiveSheetId(),t).map(e=>e.value?.toString().trim()||"").filter(e=>e);return{uniqueCount:new Set(s).size,totalCount:s.length}}(t,s.zone),r=Mz(t,o);if(i!==n)return{type:"treemap",title:{},dataSets:[{dataRange:Oz(t,s.zone)}],labelRange:Oz(t,o.zone),dataSetsHaveTitle:r,legendPosition:"none"}}return{..._z,dataSets:[{dataRange:Oz(t,e[1].zone)}],labelRange:Oz(t,e[0].zone),dataSetsHaveTitle:Mz(t,e[1])}}function Lz(e,t){const s=Pz(e,t);if(0===s.length||s.every(e=>"empty"===e.type)){const e=s.map(({zone:e})=>({dataRange:Oz(t,e)}));return{..._z,dataSets:e}}const o=s.filter(e=>"empty"!==e.type);switch(o.length){case 1:return Nz(o[0],t);case 2:return kz(o,t);default:return function(e,t){if(e.length<3)throw new Error("buildMultiColumnChart expects at least three columns");const s=e.some(e=>"text"!==e.type&&Mz(t,e)),o=e[e.length-1],i=e.slice(0,e.length-1);if(("percentage"===o.type||"number"===o.type)&&i.every(e=>"text"===e.type)){const e=i.map(({zone:e})=>({dataRange:Oz(t,e)}));return{type:i.length>=3?"sunburst":"treemap",title:{},dataSets:e,labelRange:Oz(t,o.zone),dataSetsHaveTitle:s,legendPosition:"none"}}const n=e[0],r=e.slice(1),a=r.map(({zone:e})=>({dataRange:Oz(t,e)}));return r.every(e=>"percentage"===e.type)?{type:"pie",title:{},dataSets:a,labelRange:Oz(t,n.zone),dataSetsHaveTitle:s,aggregated:!1,legendPosition:"top"}:"date"===n.type&&r.every(e=>"number"===e.type)?{...Dz,type:"line",dataSets:a,labelRange:Oz(t,n.zone),dataSetsHaveTitle:s,legendPosition:"top"}:{..._z,dataSets:a,labelRange:Oz(t,n.zone),dataSetsHaveTitle:s,legendPosition:"top"}}(o,t)}}const Vz={wrongPasteSelection:Cs("This operation is not allowed with multiple selections."),willRemoveExistingMerge:Zg.Errors.WillRemoveExistingMerge,wrongFigurePasteOption:Cs("Cannot do a special paste of a figure."),frozenPaneOverlap:Cs("This operation is not allowed due to an overlapping frozen pane.")};function zz(e,t){t.isSuccessful||(t.reasons.includes("WrongPasteSelection")?e.raiseError(Vz.wrongPasteSelection):t.reasons.includes("WillRemoveExistingMerge")?e.raiseError(Vz.willRemoveExistingMerge):t.reasons.includes("WrongFigurePasteOption")?e.raiseError(Vz.wrongFigurePasteOption):t.reasons.includes("FrozenPaneOverlap")&&e.raiseError(Vz.frozenPaneOverlap))}function Hz(e,t,s){const o=e.model.dispatch("PASTE",{target:t,pasteOption:s});zz(e,o)}async function Uz(e,t,s,o){let i;try{const n=s;if(s.imageBlob){try{const t=await(e.imageProvider?.uploadFile(s.imageBlob));n.imageData=t}catch(t){const s=Cs("An error occurred while uploading the image. %s",t.message);console.error(t),e.raiseError(s)}delete s.imageBlob}i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,clipboardContent:s,pasteOption:o})}catch(n){const r=s.data;r?.version!==__()?e.raiseError(Cs("An unexpected error occurred while pasting content. This is probably due to a spreadsheet version mismatch.")):(e.raiseError(Cs("An unexpected error occurred while pasting content. Additional information can be found in the browser console.")),console.error(n)),i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,clipboardContent:{text:s.text},pasteOption:o})}zz(e,i)}function Bz(e,t,s=Zx){let o=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,o);1!==o.length||i||1!==ss(o[0])||(e.model.selection.selectTableAroundSelection(),o=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,o));const n=o.map(s=>e.model.getters.getRangeDataFromZone(t,s)),r=e.model.dispatch("CREATE_TABLE",{ranges:n,sheetId:t,config:s,tableType:i?"dynamic":"static"});return r.isCancelledBecause("TableOverlap")?e.raiseError(Yg.Errors.TableOverlap):r.isCancelledBecause("NonContinuousTargets")&&e.raiseError(Yg.Errors.NonContinuousTargets),r}function Gz(e,t){e.model.dispatch("SET_FORMATTING_WITH_PIVOT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function Wz(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const $z=async e=>qz(e,"asValue");async function qz(e,t){const s=await e.clipboard.read();switch(s.status){case"ok":const o=e.model.getters.getClipboardId(),i=iP(s.content),n=i.data?.clipboardId,r=e.model.getters.getSelectedZones();o!==n?await Uz(e,r,i,t):Hz(e,r,t),e.model.getters.isCutOperation()&&"asValue"!==t&&await e.clipboard.write({[QF.PlainText]:""});break;case"notImplemented":e.raiseError(Cs("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(Cs("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const Zz=(e,t)=>{if("COL"===e&&t.model.getters.getActiveRows().size>0||"ROW"===e&&t.model.getters.getActiveCols().size>0)return!1;const s=t.model.getters.getActiveSheetId(),o=t.model.getters.getElementsFromSelection(e),i=t.model.getters.checkElementsIncludeAllVisibleHeaders(s,e,o),n=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(s,e,o);return!i&&!n},jz=e=>{const t=e.model.getters.getActiveRows();let s,o;if(t.size)s=st([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.top,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"before",base:s,quantity:o,dimension:"ROW"})},Yz=e=>{const t=e.model.getters.getActiveCols();let s,o;if(t.size)s=st([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.left,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"before",dimension:"COL",base:s,quantity:o})},Xz=e=>{const t=e.model.getters.getActiveCols();let s,o;if(t.size)s=tt([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.right,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"after",dimension:"COL",base:s,quantity:o})},Kz=async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),s=e.model.uuidGenerator.smallUuid(),o=await e.imageProvider.requestImage(),i=cP(e.model.getters,o.size),{col:n,row:r,offset:a}=lP(e.model.getters,i);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:s,col:n,row:r,offset:a,size:i,definition:o})}},Jz=e=>{const{col:t,row:s}=e.model.getters.getActivePosition();e.getStore(aV).open({col:t,row:s},"LinkEditor")},Qz=e=>{const t=e.model.getters.getFirstTableInSelection();return t?.config.hasFilters||!1},eH=e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZones();return 1===e.model.getters.getTablesOverlappingZones(t,s).length},tH=e=>is(e.model.getters.getSelectedZones()),sH=e=>1===e.model.getters.getSelectedZones().length,oH=(e,t)=>{if(!sH(e))return!1;const s="COL"===t?e.model.getters.getActiveCols():e.model.getters.getActiveRows(),o="COL"===t?e.model.getters.getActiveRows():e.model.getters.getActiveCols(),i=e.model.getters.getActiveSheetId(),n=Ht(e.model.getters.getSelectedZone(),e.model.getters.getSheetZone(i));return Ze(s)&&(0===o.size||n)},iH={name:e=>Qz(e)?Cs("Remove selected filters"):Cs("Add filters"),isEnabled:e=>tH(e),execute:e=>Qz(e)?(e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getFirstTableInSelection();s&&e.model.dispatch("UPDATE_TABLE",{sheetId:t,zone:s.range.zone,config:{hasFilters:!1}})})(e):(e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getFirstTableInSelection();s?e.model.dispatch("UPDATE_TABLE",{sheetId:t,zone:s.range.zone,config:{hasFilters:!0}}):Bz(e,t,{...Zx,hasFilters:!0,bandedRows:!1,styleId:"TableStyleLight11"})})(e),icon:"o-spreadsheet-Icon.FILTER_ICON_ACTIVE"};function nH(e,t,s){const o=e.model.getters.getActiveSheetId(),i="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(i,{sheetId:o,quantity:s}).isCancelledBecause("MergeOverlap")&&e.raiseError(Wg)}class rH extends Lv{mutators=["enable","disable"];isInvalidated=!1;fingerprintColors={[aH]:"#D9D9D9"};isEnabled=!1;colors=new H_;handle(e){switch(kr(e)&&this.isEnabled&&(this.isInvalidated=!0),e.type){case"UNDO":case"REDO":case"ACTIVATE_SHEET":this.isEnabled&&(this.isInvalidated=!0)}}finalize(){this.isInvalidated&&(this.isInvalidated=!1,this.computeFingerprints())}enable(){this.isEnabled=!0,this.computeFingerprints()}disable(){this.isEnabled=!1,this.colors=new H_}computeFingerprints(){this.colors=new H_;const e=new H_,t=new Set,s=this.getters.getActiveSheetId(),o=this.getters.getCells(s);for(const s in o){const i=this.computeFingerprint(o[s]);if(!i)continue;t.add(i);const n=this.getters.getCellPosition(s);e.set(n,i)}this.assignColors(t);for(const[t,s]of e.entries()){const e=this.fingerprintColors[s];this.colors.set(t,e),this.colorSpreadZone(t,e)}}colorSpreadZone(e,t){const s=this.getters.getSpreadZone(e);if(!s)return;const o=e.sheetId;for(let e=s.top;e<=s.bottom;e++)for(let i=s.left;i<=s.right;i++){const s={sheetId:o,col:i,row:e};this.colors.set(s,t)}}assignColors(e){const t=new Cb(e.size);Object.keys(this.fingerprintColors).forEach(()=>t.next());for(const s of e)this.fingerprintColors[s]||(this.fingerprintColors[s]=ab(t.next(),.8))}computeFingerprint(e){const t=this.getters.getCellPosition(e.id);return e.isFormula?this.computeFormulaFingerprint(t,e):this.getLiteralFingerprint(t)}computeFormulaFingerprint(e,t){const s=t.compiledFormula.dependencies,o=e.col,i=e.row,n=this.getters.getSheetIds().indexOf(e.sheetId),r={dx:0,dy:0,dSheet:0};for(const e of s){const t=e.zone,[s,a]=e.parts,l=this.getters.getSheetIds().indexOf(e.sheetId);r.dSheet=l-n;const c=Yb(e)&&!e.unboundedZone.hasHeader,h=jb(e)&&!e.unboundedZone.hasHeader,d=c||s?.colFixed?0:o,u=h||s?.rowFixed?0:i,g=!a&&s?.colFixed||a?.colFixed,p=!a&&s?.rowFixed||a?.rowFixed,m=void 0===e.unboundedZone.right||g?0:o,f=void 0===e.unboundedZone.bottom||p?0:i,v=Yt({top:t.top-u,left:t.left-d,right:t.right-m,bottom:t.bottom-f});for(let e=v.top;e<=v.bottom;e++)for(let t=v.left;t<=v.right;t++)r.dx+=t,r.dy+=e}const a=t.compiledFormula.normalizedFormula;return l=r,Object.entries(l).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t).join(",")+a;var l}getLiteralFingerprint(e){switch(this.getters.getEvaluatedCell(e).type){case Xd.number:case Xd.boolean:return aH;case Xd.text:case Xd.empty:case Xd.error:return}}}const aH="DATA_FINGERPRINT",lH={name:e=>{const t=e.model.getters.getElementsFromSelection("COL"),s=t[0],o=t[t.length-1];return 1===t.length?Cs("Hide column %s",lt(s).toString()):o-s+1===t.length?Cs("Hide columns %s - %s",lt(s).toString(),lt(o).toString()):Cs("Hide columns")},execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getElementsFromSelection("COL");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"COL",s)},icon:"o-spreadsheet-Icon.HIDE_COL"},cH={name:Cs("Unhide columns"),execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("COL").some(e=>t.includes(e))},icon:"o-spreadsheet-Icon.UNHIDE_COL"},hH={name:Cs("Unhide all columns"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"COL",elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0,icon:"o-spreadsheet-Icon.UNHIDE_COL"},dH={name:e=>{const t=e.model.getters.getElementsFromSelection("ROW"),s=t[0],o=t[t.length-1];return 1===t.length?Cs("Hide row %s",(s+1).toString()):o-s+1===t.length?Cs("Hide rows %s - %s",(s+1).toString(),(o+1).toString()):Cs("Hide rows")},execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getElementsFromSelection("ROW");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"ROW",s)},icon:"o-spreadsheet-Icon.HIDE_ROW"},uH={name:Cs("Unhide rows"),execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("ROW").some(e=>t.includes(e))},icon:"o-spreadsheet-Icon.UNHIDE_ROW"},gH={name:Cs("Unhide all rows"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"ROW",elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0,icon:"o-spreadsheet-Icon.UNHIDE_ROW"},pH={name:Cs("Unfreeze"),isVisible:e=>{const{xSplit:t,ySplit:s}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+s>0},execute:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),icon:"o-spreadsheet-Icon.UNFREEZE"},mH={name:Cs("Freeze"),icon:"o-spreadsheet-Icon.FREEZE"},fH={name:Cs("No rows"),execute:e=>e.model.dispatch("UNFREEZE_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit},vH={name:Cs("1 row"),execute:e=>nH(e,"ROW",1)},bH={name:Cs("2 rows"),execute:e=>nH(e,"ROW",2)},SH={name:Cs("Up to current row"),execute:e=>{const{bottom:t}=e.model.getters.getSelectedZone();nH(e,"ROW",t+1)}},yH={name:Cs("No columns"),execute:e=>e.model.dispatch("UNFREEZE_COLUMNS",{sheetId:e.model.getters.getActiveSheetId()}),isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit},CH={name:Cs("1 column"),execute:e=>nH(e,"COL",1)},IH={name:Cs("2 columns"),execute:e=>nH(e,"COL",2)},wH={name:Cs("Up to current column"),execute:e=>{const{right:t}=e.model.getters.getSelectedZone();nH(e,"COL",t+1)}},EH={name:Cs("Gridlines"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},isActive:e=>{const t=e.model.getters.getActiveSheetId();return e.model.getters.getGridLinesVisibility(t)}},xH={name:Cs("Irregularity map"),execute:e=>{const t=e.getStore(rH);t.isEnabled?t.disable():t.enable()},isReadonlyAllowed:!0,icon:"o-spreadsheet-Icon.IRREGULARITY_MAP"};const RH={name:Cs("Formulas"),isActive:e=>e.model.getters.shouldShowFormulas(),execute:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0},TH={name:e=>{const t=e.model.getters.getSelectedZone();return t.left===t.right?Cs("Group column %s",lt(t.left)):Cs("Group columns %s - %s",lt(t.left),lt(t.right))},execute:e=>OH(e,"COL"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZone(),o=e.model.getters.getHeaderGroupsInZone(t,"COL",s);return sH(e)&&!o.some(e=>e.start===s.left&&e.end===s.right)},icon:"o-spreadsheet-Icon.GROUP_COLUMNS"},AH={name:e=>{const t=e.model.getters.getSelectedZone();return t.top===t.bottom?Cs("Group row %s",String(t.top+1)):Cs("Group rows %s - %s",String(t.top+1),String(t.bottom+1))},execute:e=>OH(e,"ROW"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZone(),o=e.model.getters.getHeaderGroupsInZone(t,"ROW",s);return sH(e)&&!o.some(e=>e.start===s.top&&e.end===s.bottom)},icon:"o-spreadsheet-Icon.GROUP_ROWS"},_H={name:e=>{const t=e.model.getters.getSelectedZone();return t.left===t.right?Cs("Ungroup column %s",lt(t.left)):Cs("Ungroup columns %s - %s",lt(t.left),lt(t.right))},execute:e=>FH(e,"COL"),icon:"o-spreadsheet-Icon.UNGROUP_COLUMNS"},DH={name:e=>{const t=e.model.getters.getSelectedZone();return t.top===t.bottom?Cs("Ungroup row %s",String(t.top+1)):Cs("Ungroup rows %s - %s",String(t.top+1),String(t.bottom+1))},execute:e=>FH(e,"ROW"),icon:"o-spreadsheet-Icon.UNGROUP_ROWS"};function OH(e,t){const s=e.model.getters.getSelectedZone(),o=e.model.getters.getActiveSheetId();e.model.dispatch("GROUP_HEADERS",{sheetId:o,dimension:t,start:"COL"===t?s.left:s.top,end:"COL"===t?s.right:s.bottom})}function FH(e,t){const s=e.model.getters.getSelectedZone(),o=e.model.getters.getActiveSheetId();e.model.dispatch("UNGROUP_HEADERS",{sheetId:o,dimension:t,start:"COL"===t?s.left:s.top,end:"COL"===t?s.right:s.bottom})}function PH(e,t){const s=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return 1===o.length&&e.model.getters.getHeaderGroupsInZone(s,t,o[0]).length>0}function MH(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause("WrongCutSelection")&&e.raiseError(Cs("This operation is not allowed with multiple selections."))}const NH={MergeIsDestructive:Cs("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:Cs("You can't merge cells inside of an existing filter.")};const kH={name:Cs("Undo"),description:"Ctrl+Z",execute:e=>e.model.dispatch("REQUEST_UNDO"),isEnabled:e=>e.model.getters.canUndo(),icon:"o-spreadsheet-Icon.UNDO"},LH={name:Cs("Redo"),description:"Ctrl+Y",execute:e=>e.model.dispatch("REQUEST_REDO"),isEnabled:e=>e.model.getters.canRedo(),icon:"o-spreadsheet-Icon.REDO"},VH={name:Cs("Copy"),description:"Ctrl+C",isReadonlyAllowed:!0,execute:async e=>{e.model.dispatch("COPY"),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},icon:"o-spreadsheet-Icon.CLIPBOARD"},zH={name:Cs("Cut"),description:"Ctrl+X",execute:async e=>{MH(e),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},icon:"o-spreadsheet-Icon.CUT"},HH={name:Cs("Paste"),description:"Ctrl+V",execute:async e=>qz(e),icon:"o-spreadsheet-Icon.PASTE"},UH={name:Cs("Paste special"),isVisible:e=>!e.model.getters.isCutOperation(),icon:"o-spreadsheet-Icon.PASTE"},BH={name:Cs("Paste as value"),description:"Ctrl+Shift+V",execute:$z},GH={name:Cs("Paste format only"),execute:e=>qz(e,"onlyFormat")},WH={name:Cs("Find and replace"),description:"Ctrl+H",isReadonlyAllowed:!0,execute:e=>{e.openSidePanel("FindAndReplace",{})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.SEARCH"},$H={name:Cs("Delete values"),execute:e=>e.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},qH={name:e=>{if(e.model.getters.getSelectedZones().length>1)return Cs("Delete rows");let t,s;const o=e.model.getters.getActiveRows();if(0!==o.size)t=st([...o]),s=tt([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?Cs("Delete row %s",(t+1).toString()):Cs("Delete rows %s - %s",(t+1).toString(),(s+1).toString())},execute:e=>{const t=[...e.model.getters.getActiveRows()];if(!t.length){const s=e.model.getters.getSelectedZones()[0];for(let e=s.top;e<=s.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:"ROW",elements:t})},isVisible:e=>Zz("ROW",e)},ZH={...qH,isVisible:sH},jH={name:e=>{if(e.model.getters.getSelectedZones().length>1)return Cs("Clear rows");let t,s;const o=e.model.getters.getActiveRows();if(0!==o.size)t=st([...o]),s=tt([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?Cs("Clear row %s",(t+1).toString()):Cs("Clear rows %s - %s",(t+1).toString(),(s+1).toString())},execute:e=>{const t=e.model.getters.getActiveSheetId(),s=[...e.model.getters.getActiveRows()].map(s=>e.model.getters.getRowsZone(t,s,s));e.model.dispatch("DELETE_CONTENT",{target:s,sheetId:e.model.getters.getActiveSheetId()})}},YH={name:e=>{if(e.model.getters.getSelectedZones().length>1)return Cs("Delete columns");let t,s;const o=e.model.getters.getActiveCols();if(0!==o.size)t=st([...o]),s=tt([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?Cs("Delete column %s",lt(t)):Cs("Delete columns %s - %s",lt(t),lt(s))},execute:e=>{const t=[...e.model.getters.getActiveCols()];if(!t.length){const s=e.model.getters.getSelectedZones()[0];for(let e=s.left;e<=s.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:"COL",elements:t})},isVisible:e=>Zz("COL",e)},XH={...YH,isVisible:sH},KH={name:e=>{if(e.model.getters.getSelectedZones().length>1)return Cs("Clear columns");let t,s;const o=e.model.getters.getActiveCols();if(0!==o.size)t=st([...o]),s=tt([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?Cs("Clear column %s",lt(t)):Cs("Clear columns %s - %s",lt(t),lt(s))},execute:e=>{const t=e.model.getters.getActiveSheetId(),s=[...e.model.getters.getActiveCols()].map(s=>e.model.getters.getColsZone(t,s,s));e.model.dispatch("DELETE_CONTENT",{target:s,sheetId:e.model.getters.getActiveSheetId()})}},JH={name:Cs("Delete cells"),isVisible:sH},QH={name:Cs("Delete cell and shift up"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});zz(e,s)}},eU={name:Cs("Delete cell and shift left"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});zz(e,s)}},tU={name:Cs("Merge cells"),isEnabled:e=>!iU(e),isActive:e=>nU(e),execute:e=>function(e){if(iU(e))return;const t=e.model.getters.getSelectedZones(),s=e.model.getters.getActiveSheetId();if(nU(e)){const o=t.flatMap(t=>e.model.getters.getMergesInZone(s,t));e.model.dispatch("REMOVE_MERGE",{sheetId:s,target:o})}else!function(e,t,s){const o=e.model.dispatch("ADD_MERGE",{sheetId:t,target:s});o.isCancelledBecause("MergeInTable")?e.raiseError(NH.MergeInFilter):o.isCancelledBecause("MergeIsDestructive")&&e.askConfirmation(NH.MergeIsDestructive,()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:s,force:!0})})}(e,s,t)}(e),icon:"o-spreadsheet-Icon.MERGE_CELL"},sU={name:()=>Cs("Edit table"),execute:e=>e.openSidePanel("TableSidePanel",{}),icon:"o-spreadsheet-Icon.EDIT_TABLE"},oU={name:()=>Cs("Delete table"),execute:e=>{const t=e.model.getters.getActivePosition(),s=e.model.getters.getTable(t);s&&e.model.dispatch("REMOVE_TABLE",{sheetId:t.sheetId,target:[s.range.zone]})},icon:"o-spreadsheet-Icon.DELETE_TABLE"};function iU(e){const t=e.model.getters.getSelectedZones(),{sheetId:s}=e.model.getters.getActivePosition(),{xSplit:o,ySplit:i}=e.model.getters.getPaneDivisions(s);return t.every(e=>1===ss(e))||os(t,o,i)||function(e){for(let t=0;t<e.length-1;t++)for(let s=t+1;s<e.length;s++)if(Bt(e[t],e[s]))return!0;return!1}(t)}function nU(e){if(iU(e))return!1;const t=e.model.getters.getActiveSheetId();return e.model.getters.getSelectedZones().some(s=>e.model.getters.getMergesInZone(t,s).length>0)}const rU={name:e=>{const t=VU(e);return 1===t?Cs("Insert row"):Cs("Insert %s rows",t.toString())},isVisible:e=>oH(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW"},aU={name:e=>{const t=VU(e);return 1===t?Cs("Insert row above"):Cs("Insert %s rows above",t.toString())},execute:jz,isVisible:e=>oH(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},lU={...aU,name:e=>{const t=VU(e);return 1===t?Cs("Row above"):Cs("%s Rows above",t.toString())}},cU={...aU,name:e=>{const t=VU(e);return 1===t?Cs("Insert row"):Cs("Insert %s rows",t.toString())},isVisible:sH,icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},hU={execute:e=>{const t=e.model.getters.getActiveRows();let s,o;if(t.size)s=tt([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.bottom,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"after",base:s,quantity:o,dimension:"ROW"})},name:e=>{const t=VU(e);return 1===t?Cs("Insert row below"):Cs("Insert %s rows below",t.toString())},isVisible:e=>oH(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_AFTER"},dU={...hU,name:e=>{const t=VU(e);return 1===t?Cs("Row below"):Cs("%s Rows below",t.toString())}},uU={name:e=>{const t=zU(e);return 1===t?Cs("Insert column"):Cs("Insert %s columns",t.toString())},isVisible:e=>oH(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL"},gU={name:e=>{const t=zU(e);return 1===t?Cs("Insert column left"):Cs("Insert %s columns left",t.toString())},execute:Yz,isVisible:e=>oH(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},pU={...gU,name:e=>{const t=zU(e);return 1===t?Cs("Column left"):Cs("%s Columns left",t.toString())}},mU={...gU,name:e=>{const t=zU(e);return 1===t?Cs("Insert column"):Cs("Insert %s columns",t.toString())},isVisible:sH,icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},fU={name:e=>{const t=zU(e);return 1===t?Cs("Insert column right"):Cs("Insert %s columns right",t.toString())},execute:Xz,isVisible:e=>oH(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_AFTER"},vU={...fU,name:e=>{const t=zU(e);return 1===t?Cs("Column right"):Cs("%s Columns right",t.toString())},execute:Xz},bU={name:Cs("Insert cells"),isVisible:e=>sH(e)&&0===e.model.getters.getActiveCols().size&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_CELL"},SU={name:Cs("Insert cells and shift down"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});zz(e,s)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN"},yU={name:Cs("Insert cells and shift right"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});zz(e,s)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT"},CU={name:Cs("Chart"),execute:e=>{const t=e.model.getters,s=e.model.uuidGenerator.smallUuid(),o=t.getActiveSheetId();let i=t.getSelectedZones();1===i.length&&1===ss(i[0])&&(e.model.selection.selectTableAroundSelection(),i=t.getSelectedZones());const n={width:536,height:335},{col:r,row:a,offset:l}=lP(t,n);e.model.dispatch("CREATE_CHART",{sheetId:o,figureId:s,chartId:e.model.uuidGenerator.smallUuid(),col:r,row:a,offset:l,size:n,definition:Lz(i,e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{figureId:s}),e.openSidePanel("ChartPanel"))},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.INSERT_CHART"},IU={name:Cs("Carousel"),execute:e=>{const t=e.model.getters,s=e.model.uuidGenerator.smallUuid(),o=t.getActiveSheetId(),i={width:536,height:335},{col:n,row:r,offset:a}=lP(t,i);e.model.dispatch("CREATE_CAROUSEL",{sheetId:o,figureId:s,col:n,row:r,offset:a,size:i,definition:{items:[]}}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{figureId:s}),e.openSidePanel("CarouselPanel",{figureId:s}))},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.CAROUSEL"},wU={name:Cs("Pivot table"),execute:e=>{const t=e.model.uuidGenerator.smallUuid(),s=e.model.uuidGenerator.smallUuid();e.model.dispatch("INSERT_NEW_PIVOT",{pivotId:t,newSheetId:s}).isSuccessful&&e.openSidePanel("PivotSidePanel",{pivotId:t})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.PIVOT"},EU={name:Cs("Image"),description:"Ctrl+O",execute:Kz,isVisible:e=>void 0!==e.imageProvider,isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.INSERT_IMAGE"},xU={name:()=>Cs("Table"),execute:e=>{const t=e.model.getters.getActiveSheetId();Bz(e,t).isSuccessful&&e.openSidePanel("TableSidePanel",{})},isVisible:e=>tH(e)&&!e.model.getters.getFirstTableInSelection(),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.PAINT_TABLE"},RU={name:Cs("Function"),icon:"o-spreadsheet-Icon.FORMULA"},TU={name:Cs("SUM"),execute:e=>e.startCellEdition("=SUM(")},AU={name:Cs("AVERAGE"),execute:e=>e.startCellEdition("=AVERAGE(")},_U={name:Cs("COUNT"),execute:e=>e.startCellEdition("=COUNT(")},DU={name:Cs("MAX"),execute:e=>e.startCellEdition("=MAX(")},OU={name:Cs("MIN"),execute:e=>e.startCellEdition("=MIN(")},FU={name:Cs("All"),children:[function(){return LU(zf.getKeys().filter(e=>!zf.get(e).hidden))}]};const PU={name:Cs("Link"),execute:Jz,icon:"o-spreadsheet-Icon.INSERT_LINK"},MU={name:Cs("Checkbox"),execute:e=>{const t=e.model.getters.getSelectedZones(),s=e.model.getters.getActiveSheetId(),o=t.map(t=>e.model.getters.getRangeDataFromZone(s,t));e.model.dispatch("ADD_DATA_VALIDATION_RULE",{ranges:o,sheetId:s,rule:{id:e.model.uuidGenerator.smallUuid(),criterion:{type:"isBoolean",values:[]}}})},icon:"o-spreadsheet-Icon.INSERT_CHECKBOX"},NU={name:Cs("Dropdown list"),execute:e=>{const t=e.model.getters.getSelectedZones(),s=e.model.getters.getActiveSheetId(),o=t.map(t=>e.model.getters.getRangeDataFromZone(s,t)),i=e.model.uuidGenerator.smallUuid();e.model.dispatch("ADD_DATA_VALIDATION_RULE",{ranges:o,sheetId:s,rule:{id:i,criterion:{type:"isValueInList",values:[],displayStyle:"chip"}}});const n=e.model.getters.getDataValidationRule(s,i);n&&e.openSidePanel("DataValidationEditor",{rule:Th(n,e.model.getters.getLocale()),onExit:()=>{e.replaceSidePanel("DataValidation","DataValidationEditor")}})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.INSERT_DROPDOWN"},kU={name:Cs("Insert sheet"),execute:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSheetIds().indexOf(t)+1,o=e.model.uuidGenerator.smallUuid();e.model.dispatch("CREATE_SHEET",{sheetId:o,position:s,name:e.model.getters.getNextSheetName()}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},icon:"o-spreadsheet-Icon.INSERT_SHEET"};function LU(e){return e.sort().map((e,t)=>({name:e,sequence:10*t,execute:t=>t.startCellEdition(`=${e}(`)}))}function VU(e){const t=e.model.getters.getActiveRows();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function zU(e){const t=e.model.getters.getActiveCols();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.right-t.left+1}}const HU={name:Cs("See pivot properties"),execute(e){const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotIdFromPosition(t);e.openSidePanel("PivotSidePanel",{pivotId:s})},isVisible:e=>{const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotIdFromPosition(t);return!e.isSmall&&s&&e.model.getters.isExistingPivot(s)||!1},isReadonlyAllowed:!0,icon:"o-spreadsheet-Icon.PIVOT"},UU={name:Cs("Ascending"),execute:e=>QU(e,e.model.getters.getActivePosition(),"asc"),isActive:e=>"asc"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},BU={name:Cs("Descending"),execute:e=>QU(e,e.model.getters.getActivePosition(),"desc"),isActive:e=>"desc"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},GU={name:Cs("No sorting"),execute:e=>QU(e,e.model.getters.getActivePosition(),"none"),isActive:e=>"none"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},WU={name:Cs("Convert to individual formulas"),execute(e){const t=e.model.getters.getActivePosition(),s=e.model.getters.getCorrespondingFormulaCell(t),o=e.model.getters.getPivotIdFromPosition(t);if(!s||!o)return;const{sheetId:i,col:n,row:r}=e.model.getters.getCellPosition(s.id),a=e.model.getters.getPivot(o);a.init(),a.isValid()&&e.model.dispatch("SPLIT_PIVOT_FORMULA",{sheetId:i,col:n,row:r,pivotId:o})},isVisible:e=>{const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotIdFromPosition(t);if(!s)return!1;const o=e.model.getters.getPivot(s),i=e.model.getters.getEvaluatedCell(t);return o.isValid()&&e.model.getters.isSpillPivotFormula(t)&&i.type!==Xd.error},icon:"o-spreadsheet-Icon.PIVOT"},$U={name:Cs("Group pivot dimensions"),execute:e=>{const t=eB(e);if(!t)return;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s),r=he(e.model.getters.getPivotCoreDefinition(s));if(i.isCustomField){const e=(r.customFields||{})[i.name];if(!e)return;!function(e,t){const s=new Set,o=[];for(const i of t){const t=e.groups.find(e=>e.name===i);t?(o.push(t),t.values.forEach(e=>s.add(e))):s.add(i)}if(o.some(e=>e.isOtherGroup))e.groups=e.groups.filter(e=>e.isOtherGroup||!o.includes(e));else if(0===o.length){const s={name:kp(Cs("Group"),e),values:t};e.groups.push(s)}else{const t=o.slice(1);e.groups=e.groups.filter(e=>!t.includes(e)),o[0].values=Array.from(s)}}(e,o)}else!function(e,t,s,o){const i=Up(e,s,o);zp(t,i);const n={name:kp(Cs("Group"),i),values:t};i.groups.push(n),e.customFields||(e.customFields={});e.customFields[i.name]=i,Hp(e,s.name,i.name)}(r,o,i,n.getFields());e.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:r})},isVisible:e=>{const t=eB(e);if(!t)return!1;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s);return o.length>1&&(i.isCustomField||AD.get(n.type).canHaveCustomGroup(i))}},qU={name:Cs("Group all remaining dimensions"),execute:e=>{const t=eB(e);if(!t)return;const{pivotId:s,field:o}=t,i=e.model.getters.getPivot(s),n=he(e.model.getters.getPivotCoreDefinition(s)),r=o.isCustomField?(n.customFields||{})[o.name]:Up(n,o,i.getFields());r&&(r.groups.push({name:kp(Cs("Others"),r),values:[],isOtherGroup:!0}),Hp(n,o.name,r.name),e.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:n}))},isVisible:e=>{const t=eB(e);if(!t)return!1;const{pivotId:s,field:o,values:i}=t;return function(e,t,s,o){const i=e.model.getters.getPivot(t),n=e.model.getters.getPivotCoreDefinition(t),r=o.isCustomField?(n.customFields||{})[o.name]:Object.values(n.customFields||{}).find(e=>e.parentField===o.name),a=i.definition.getDimension(o.name);if(!a||!r||tB(n,s,o,i.getFields()))return!1;const l=new Set(i.getPossibleFieldValues(a).map(e=>e.value)),c=o.isCustomField?r.groups.map(e=>e.name):r.groups.flatMap(e=>e.values);for(const e of[...s,...c])l.delete(e);return 0===l.size}(e,s,i,o)}},ZU={name:Cs("Ungroup pivot dimensions"),execute:e=>{const t=eB(e);if(!t)return;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s),r=he(e.model.getters.getPivotCoreDefinition(s));!function(e,t,s,o){let i;if(s.isCustomField){if(i=(e.customFields||{})[s.name],!i)return;i.groups=i.groups.filter(e=>!t.includes(e.name))}else i=Up(e,s,o),i.groups.some(e=>e.isOtherGroup)&&t.some(e=>!i?.groups.some(t=>t.values.includes(e)))&&(i.groups=i.groups.filter(e=>!e.isOtherGroup)),zp(t,i);i.groups.every(e=>0===e.values.length&&!e.isOtherGroup)&&(!function(e,t){const s=e.customFields?.[t];if(!s)return;const o=[...e.rows,...e.columns].some(e=>e.fieldName===s.parentField);for(const i of[e.rows,e.columns]){const e=i.findIndex(e=>e.fieldName===t);-1!==e&&(o?i.splice(e,1):i.splice(e,1,{fieldName:s.parentField}))}}(e,i.name),delete e.customFields?.[i.name])}(r,o,i,n.getFields()),e.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:r})},isVisible:e=>{const t=eB(e);if(!t)return!1;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s),r=e.model.getters.getPivotCoreDefinition(s);if(!i.isCustomField){const e=Up(r,i,n.getFields());if(![...r.rows,...r.columns].some(t=>t.fieldName===e.name))return!1}return tB(r,o,i,n.getFields())}},jU={name:e=>{const t=e.model.getters.getActivePosition(),s=KU(e.model.getters,t);return s.isPivotGroup?s.isCollapsed?Cs("Expand"):Cs("Collapse"):""},execute(e){Bp(e.model.getters.getActivePosition(),e)},isVisible:e=>{const t=e.model.getters.getActivePosition();return KU(e.model.getters,t).isPivotGroup}},YU={name:Cs("Collapse all"),execute(e){const t=e.model.getters.getActivePosition(),s=KU(e.model.getters,t);if(!s.isPivotGroup)return;const{pivotCell:o,pivotId:i,siblingDomains:n}=s,r=he(e.model.getters.getPivotCoreDefinition(i));r.collapsedDomains=r.collapsedDomains||{COL:[],ROW:[]};const a=[...r.collapsedDomains[o.dimension]||[],...n],l=a.filter((e,t)=>t===a.findIndex(t=>Le(t,e)));r.collapsedDomains[o.dimension]=l,e.model.dispatch("UPDATE_PIVOT",{pivotId:i,pivot:r})},isVisible:e=>{const t=e.model.getters.getActivePosition(),s=KU(e.model.getters,t);if(!s.isPivotGroup)return!1;const{pivotCell:o,pivotId:i,siblingDomains:n}=s,r=e.model.getters.getPivotCoreDefinition(i);return!n.every(e=>(r.collapsedDomains?.[o.dimension]||[]).some(t=>Le(t,e)))}},XU={name:Cs("Expand all"),execute(e){const t=e.model.getters.getActivePosition(),s=KU(e.model.getters,t);if(!s.isPivotGroup)return;const{pivotCell:o,pivotId:i,siblingDomains:n}=s,r=he(e.model.getters.getPivotCoreDefinition(i));r.collapsedDomains=r.collapsedDomains||{COL:[],ROW:[]};const a=(r.collapsedDomains[o.dimension]||[]).filter(e=>!n.find(t=>Le(t,e)));r.collapsedDomains[o.dimension]=a,e.model.dispatch("UPDATE_PIVOT",{pivotId:i,pivot:r})},isVisible:e=>{const t=e.model.getters.getActivePosition(),s=KU(e.model.getters,t);if(!s.isPivotGroup)return!1;const{pivotCell:o,pivotId:i,siblingDomains:n}=s,r=e.model.getters.getPivotCoreDefinition(i);return(r.collapsedDomains?.[o.dimension]||[]).some(e=>n.some(t=>Le(t,e)))}};function KU(e,t){if(!e.isSpillPivotFormula(t))return{isPivotGroup:!1};const s=e.getPivotCellFromPosition(t),o=e.getPivotIdFromPosition(t);if("HEADER"!==s.type||!o||!s.domain.length)return{isPivotGroup:!1};const i=e.getPivotCoreDefinition(o),n=e.isDashboard(),r="COL"===s.dimension?i.columns:i.rows;if(!(!n&&s.domain.length!==r.length))return{isPivotGroup:!1};const a=(i.collapsedDomains?.[s.dimension]??[]).some(e=>Le(e,s.domain)),l=e.getPivot(o).getExpandedTableStructure(),c=s.domain.length-1,h="ROW"===s.dimension?l.getRowDomainsAtDepth(c):l.getColumnDomainsAtDepth(c);return{isPivotGroup:!0,isCollapsed:a,pivotCell:s,pivotId:o,siblingDomains:h}}function JU(e,t){const s=e.getPivotIdFromPosition(t);if(!s||!e.isExistingPivot(s)||!e.isSpillPivotFormula(t))return!1;if(!e.getPivot(s).isValid())return!1;const o=e.getPivotCellFromPosition(t);return"VALUE"===o.type||"MEASURE_HEADER"===o.type}function QU(e,t,s){const o=e.model.getters.getPivotIdFromPosition(t),i=e.model.getters.getPivotCellFromPosition(t);if("EMPTY"===i.type||"HEADER"===i.type||!o)return;if("none"===s)return void e.model.dispatch("UPDATE_PIVOT",{pivotId:o,pivot:{...e.model.getters.getPivotCoreDefinition(o),sortedColumn:void 0}});const n=oD(e.model.getters.getPivot(o),i.domain).colDomain;e.model.dispatch("UPDATE_PIVOT",{pivotId:o,pivot:{...e.model.getters.getPivotCoreDefinition(o),sortedColumn:{domain:n,order:s,measure:i.measure}}})}function eB(e){let t,s;const o=[];for(const i of e.model.getters.getSelectedZones()){const n=e.model.getters.getActiveSheetId();for(const r of jt(n,i)){const i=e.model.getters.getPivotIdFromPosition(r);if(t){if(i&&t!==i)return}else t=i;if(!t)continue;const n=e.model.getters.getPivotCellFromPosition(r);if("HEADER"!==n.type||!e.model.getters.isSpillPivotFormula(r))continue;const a=n.domain.at(-1)?.field;if(!s&&a)s=a;else if(s&&a&&s!==a)return;o.push(n)}}if(!t||!s||0===o.length)return;const i=e.model.getters.getPivot(t).getFields()[s];if(!i)return;return{pivotId:t,values:o.map(e=>e.domain.at(-1)?.value).filter(e=>void 0!==e),field:i}}function tB(e,t,s,o){if(s.isCustomField){const o=(e.customFields||{})[s.name];return!!o&&o.groups.some(e=>t.includes(e.name))}return Up(e,s,o).groups.some(e=>e.isOtherGroup||t.some(t=>e.values.includes(t)))}const sB=new xz;sB.add("cut",{...zH,sequence:10}).add("copy",{...VH,sequence:20}).add("paste",{...HH,sequence:30}).add("paste_special",{...UH,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...BH,sequence:10}).addChild("paste_format_only",["paste_special"],{...GH,sequence:20}).add("add_row_before",{...cU,sequence:70}).add("add_column_before",{...mU,sequence:90}).add("insert_cell",{...bU,sequence:100,separator:!0}).addChild("insert_cell_down",["insert_cell"],{...SU,name:Cs("Shift down"),sequence:10}).addChild("insert_cell_right",["insert_cell"],{...yU,name:Cs("Shift right"),sequence:20}).add("delete_row",{...ZH,sequence:110,icon:"o-spreadsheet-Icon.TRASH"}).add("delete_column",{...XH,sequence:120,icon:"o-spreadsheet-Icon.TRASH"}).add("delete_cell",{...JH,sequence:130,separator:!0,icon:"o-spreadsheet-Icon.TRASH"}).addChild("delete_cell_up",["delete_cell"],{...QH,name:Cs("Shift up"),sequence:10,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP"}).addChild("delete_cell_left",["delete_cell"],{...eU,name:Cs("Shift left"),sequence:20,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT"}).add("edit_table",{...sU,isVisible:eH,isEnabled:e=>!e.isSmall,sequence:140}).add("delete_table",{...oU,isVisible:eH,sequence:145,separator:!0}).add("insert_link",{...PU,name:e=>{const t=e.model.getters.getActiveSheetId(),{col:s,row:o}=e.model.getters.getActivePosition(),i=e.model.getters.getEvaluatedCell({sheetId:t,col:s,row:o});return i&&i.link?Cs("Edit link"):Cs("Insert link")},sequence:150,separator:!0}).add("pivot_headers_group",{sequence:155,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",...$U}).add("pivot_group_remaining",{sequence:155,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",...qU}).add("pivot_headers_ungroup",{sequence:155,icon:"o-spreadsheet-Icon.MINUS_IN_BOX",...ZU}).add("collapse_pivot",{sequence:156,name:Cs("Expand/Collapse"),icon:"o-spreadsheet-Icon.COLLAPSE"}).addChild("toggle_collapse_pivot_cell",["collapse_pivot"],{sequence:10,...jU}).addChild("collapse_all_pivot",["collapse_pivot"],{sequence:20,...YU}).addChild("expand_all_pivot",["collapse_pivot"],{sequence:30,...XU}).add("pivot_sorting",{name:Cs("Sort pivot"),sequence:155,icon:"o-spreadsheet-Icon.SORT_RANGE",isVisible:e=>{const t=e.model.getters.getActivePosition();return JU(e.model.getters,t)}}).add("pivot_fix_formulas",{...WU,sequence:160}).add("pivot_properties",{...HU,sequence:170,separator:!0}).addChild("pivot_sorting_asc",["pivot_sorting"],{...UU,sequence:10}).addChild("pivot_sorting_desc",["pivot_sorting"],{...BU,sequence:20}).addChild("pivot_sorting_none",["pivot_sorting"],{...GU,sequence:30});const oB={name:Cs("Sort range"),isVisible:sH,icon:"o-spreadsheet-Icon.SORT_RANGE"},iB={name:Cs("Ascending (A ⟶ Z)"),execute:e=>{const{anchor:t,zones:s}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();hV(e,o,t.cell,s[0],"asc")},icon:"o-spreadsheet-Icon.SORT_ASCENDING"},nB={name:Cs("Data cleanup"),icon:"o-spreadsheet-Icon.DATA_CLEANUP"},rB={name:Cs("Remove duplicates"),execute:e=>{1===ss(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection(),e.openSidePanel("RemoveDuplicates",{})},isEnabled:e=>!e.isSmall},aB={name:Cs("Trim whitespace"),execute:e=>{e.model.dispatch("TRIM_WHITESPACE")}},lB={name:Cs("Descending (Z ⟶ A)"),execute:e=>{const{anchor:t,zones:s}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();hV(e,o,t.cell,s[0],"desc")},icon:"o-spreadsheet-Icon.SORT_DESCENDING"},cB={...iH},hB={...iH,isActive:e=>Qz(e)},dB={name:Cs("Split text to columns"),sequence:1,execute:e=>e.openSidePanel("SplitToColumns",{}),isEnabled:e=>!e.isSmall&&e.model.getters.isSingleColSelected(),icon:"o-spreadsheet-Icon.SPLIT_TEXT"},uB={id:"reinsert_dynamic_pivot",name:Cs("Re-insert dynamic pivot"),sequence:60,icon:"o-spreadsheet-Icon.INSERT_PIVOT",children:[e=>e.model.getters.getPivotIds().map((t,s)=>({id:`reinsert_dynamic_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:s,execute:e=>{const s=e.model.getters.getSelectedZone(),o=e.model.getters.getPivot(t).getCollapsedTableStructure().export();e.model.dispatch("INSERT_PIVOT_WITH_TABLE",{pivotId:t,table:o,col:s.left,row:s.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:"dynamic"}),e.model.dispatch("REFRESH_PIVOT",{id:t})},isVisible:e=>e.model.getters.getPivot(t).isValid()}))],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())},gB={id:"reinsert_static_pivot",name:Cs("Re-insert static pivot"),sequence:70,icon:"o-spreadsheet-Icon.INSERT_PIVOT",children:[e=>e.model.getters.getPivotIds().map((t,s)=>({id:`reinsert_static_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:s,execute:e=>{const s=e.model.getters.getSelectedZone(),o=e.model.getters.getPivot(t).getExpandedTableStructure();o.numberOfCells>se?e.notifyUser({type:"warning",text:Kg(o.numberOfCells,e.model.getters.getLocale()),sticky:!0}):(e.model.dispatch("INSERT_PIVOT_WITH_TABLE",{pivotId:t,table:o.export(),col:s.left,row:s.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:"static"}),e.model.dispatch("REFRESH_PIVOT",{id:t}))},isVisible:e=>e.model.getters.getPivot(t).isValid()}))],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())};function pB({name:e,format:t,descriptionValue:s}){const o="function"==typeof t?t:()=>t;return{name:e,description:e=>zi(s,{format:o(e),locale:e.model.getters.getLocale()}),execute:e=>Gz(e,o(e)),isActive:e=>aG(e,o(e)),format:t}}const mB={name:Cs("Automatic"),execute:e=>Gz(e,""),isActive:e=>function(e){const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotCellFromPosition(t);if("VALUE"===s.type)return!e.model.getters.getEvaluatedCell(t).format;return!e.model.getters.getCell(t)?.format}(e)},fB={name:Cs("Plain text"),execute:e=>Gz(e,"@"),isActive:e=>aG(e,"@")},vB=pB({name:Cs("Number"),descriptionValue:1000.12,format:"#,##0.00"}),bB={name:Cs("Format as percent"),execute:e=>Gz(e,"0.00%"),icon:"o-spreadsheet-Icon.PERCENT"},SB=pB({name:Cs("Percent"),descriptionValue:.1012,format:"0.00%"}),yB=pB({name:Cs("Scientific"),descriptionValue:.1012,format:"0.00e"}),CB=pB({name:Cs("Currency"),descriptionValue:1000.12,format:e=>en(e.model.config.defaultCurrency||oe)}),IB={...pB({name:Cs("Currency rounded"),descriptionValue:1e3,format:e=>on(en(e.model.config.defaultCurrency||oe))}),isVisible:e=>{const t=en(e.model.config.defaultCurrency||oe);return t!==on(t)}},wB=pB({name:Cs("Accounting"),descriptionValue:-1000.12,format:e=>tn(e.model.config.defaultCurrency||oe)}),EB=_b("2023/09/26 10:43:00 PM",gi),xB={name:Cs("Custom currency"),isVisible:e=>void 0!==e.loadCurrencies&&!e.isSmall,execute:e=>e.openSidePanel("MoreFormats",{category:"currency"})},RB=pB({name:Cs("Date"),descriptionValue:EB,format:e=>e.model.getters.getLocale().dateFormat}),TB=pB({name:Cs("Time"),descriptionValue:EB,format:e=>e.model.getters.getLocale().timeFormat}),AB=pB({name:Cs("Date time"),descriptionValue:EB,format:e=>Dh(e.model.getters.getLocale())}),_B=pB({name:Cs("Duration"),descriptionValue:"27:51:38",format:"hhhh:mm:ss"}),DB={name:Cs("Custom date and time"),isVisible:e=>!e.isSmall,execute:e=>e.openSidePanel("MoreFormats",{category:"date"})},OB={name:Cs("Custom number format"),isVisible:e=>!e.isSmall,execute:e=>e.openSidePanel("MoreFormats",{category:"number"})};pB({name:Cs("Full date time"),format:"dddd d mmmm yyyy hh:mm:ss a",descriptionValue:EB});const FB={name:Cs("Increase decimal places"),icon:"o-spreadsheet-Icon.INCREASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:1})},PB={name:Cs("Decrease decimal places"),icon:"o-spreadsheet-Icon.DECRASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:-1})},MB={name:Cs("Bold"),description:"Ctrl+B",execute:e=>Wz(e,{bold:!e.model.getters.getCurrentStyle().bold}),icon:"o-spreadsheet-Icon.BOLD",isActive:e=>!!e.model.getters.getCurrentStyle().bold},NB={name:Cs("Italic"),description:"Ctrl+I",execute:e=>Wz(e,{italic:!e.model.getters.getCurrentStyle().italic}),icon:"o-spreadsheet-Icon.ITALIC",isActive:e=>!!e.model.getters.getCurrentStyle().italic},kB={name:Cs("Underline"),description:"Ctrl+U",execute:e=>Wz(e,{underline:!e.model.getters.getCurrentStyle().underline}),icon:"o-spreadsheet-Icon.UNDERLINE",isActive:e=>!!e.model.getters.getCurrentStyle().underline},LB={name:Cs("Rotation"),icon:e=>function(e){switch(function(e){const t=e.model.getters.getCurrentStyle();return t.rotation??0}(e)){case Math.PI/2:return"o-spreadsheet-Icon.ROTATION-90";case-Math.PI/2:return"o-spreadsheet-Icon.ROTATION-270";case Math.PI/4:return"o-spreadsheet-Icon.ROTATION-45";case-Math.PI/4:return"o-spreadsheet-Icon.ROTATION-315";default:return"o-spreadsheet-Icon.ROTATION-0"}}(e)},VB={name:Cs("No rotation"),execute:e=>Wz(e,{rotation:0}),icon:"o-spreadsheet-Icon.ROTATION-0",isActive:e=>0===e.model.getters.getCurrentStyle().rotation},zB={name:Cs("45° rotation"),execute:e=>Wz(e,{rotation:Math.PI/4}),icon:"o-spreadsheet-Icon.ROTATION-45",isActive:e=>e.model.getters.getCurrentStyle().rotation===Math.PI/4},HB={name:Cs("90° rotation"),execute:e=>Wz(e,{rotation:Math.PI/2}),icon:"o-spreadsheet-Icon.ROTATION-90",isActive:e=>e.model.getters.getCurrentStyle().rotation===Math.PI/2},UB={name:Cs("-90° rotation"),execute:e=>Wz(e,{rotation:-Math.PI/2}),icon:"o-spreadsheet-Icon.ROTATION-270",isActive:e=>e.model.getters.getCurrentStyle().rotation===-Math.PI/2},BB={name:Cs("-45° rotation"),execute:e=>Wz(e,{rotation:-Math.PI/4}),icon:"o-spreadsheet-Icon.ROTATION-315",isActive:e=>e.model.getters.getCurrentStyle().rotation===-Math.PI/4},GB={name:Cs("Strikethrough"),execute:e=>Wz(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),icon:"o-spreadsheet-Icon.STRIKE",isActive:e=>!!e.model.getters.getCurrentStyle().strikethrough},WB={name:Cs("Font size"),children:ee.map(e=>({name:e.toString(),sequence:e,id:`font_size_${e}`,execute:t=>Wz(t,{fontSize:e}),isActive:t=>function(e,t){const s=e.model.getters.getCurrentStyle().fontSize||z;return s===t}(t,e)})),icon:"o-spreadsheet-Icon.FONT_SIZE"},$B={name:Cs("Alignment"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},qB={name:Cs("Horizontal align"),icon:e=>function(e){switch(lG(e)){case"right":return"o-spreadsheet-Icon.ALIGN_RIGHT";case"center":return"o-spreadsheet-Icon.ALIGN_CENTER";default:return"o-spreadsheet-Icon.ALIGN_LEFT"}}(e)},ZB={name:Cs("Left"),description:"Ctrl+Shift+L",execute:e=>Wz(e,{align:"left"}),isActive:e=>"left"===lG(e),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},jB={name:Cs("Center"),description:"Ctrl+Shift+E",execute:e=>Wz(e,{align:"center"}),isActive:e=>"center"===lG(e),icon:"o-spreadsheet-Icon.ALIGN_CENTER"},YB={name:Cs("Right"),description:"Ctrl+Shift+R",execute:e=>Wz(e,{align:"right"}),isActive:e=>"right"===lG(e),icon:"o-spreadsheet-Icon.ALIGN_RIGHT"},XB={name:Cs("Vertical align"),icon:e=>function(e){switch(cG(e)){case"top":return"o-spreadsheet-Icon.ALIGN_TOP";case"middle":return"o-spreadsheet-Icon.ALIGN_MIDDLE";default:return"o-spreadsheet-Icon.ALIGN_BOTTOM"}}(e)},KB={name:Cs("Top"),execute:e=>Wz(e,{verticalAlign:"top"}),isActive:e=>"top"===cG(e),icon:"o-spreadsheet-Icon.ALIGN_TOP"},JB={name:Cs("Middle"),execute:e=>Wz(e,{verticalAlign:"middle"}),isActive:e=>"middle"===cG(e),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},QB={name:Cs("Bottom"),execute:e=>Wz(e,{verticalAlign:"bottom"}),isActive:e=>"bottom"===cG(e),icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"},eG={name:Cs("Wrapping"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},tG={name:Cs("Wrapping"),icon:e=>function(e){switch(hG(e)){case"wrap":return"o-spreadsheet-Icon.WRAPPING_WRAP";case"clip":return"o-spreadsheet-Icon.WRAPPING_CLIP";default:return"o-spreadsheet-Icon.WRAPPING_OVERFLOW"}}(e)},sG={name:Cs("Overflow"),execute:e=>Wz(e,{wrapping:"overflow"}),isActive:e=>"overflow"===hG(e),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},oG={name:Cs("Wrap"),execute:e=>Wz(e,{wrapping:"wrap"}),isActive:e=>"wrap"===hG(e),icon:"o-spreadsheet-Icon.WRAPPING_WRAP"},iG={name:Cs("Clip"),execute:e=>Wz(e,{wrapping:"clip"}),isActive:e=>"clip"===hG(e),icon:"o-spreadsheet-Icon.WRAPPING_CLIP"};Cs("Text Color"),Cs("Fill Color");const nG={name:Cs("Conditional formatting"),execute:e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.CONDITIONAL_FORMAT"},rG={name:Cs("Clear formatting"),description:"Ctrl+<",execute:e=>e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()}),icon:"o-spreadsheet-Icon.CLEAR_FORMAT"};function aG(e,t){const s=e.model.getters.getActivePosition();return"VALUE"===e.model.getters.getPivotCellFromPosition(s).type?e.model.getters.getEvaluatedCell(s).format===t:e.model.getters.getCell(s)?.format===t}function lG(e){const t=e.model.getters.getCurrentStyle();if(t.align)return t.align;return e.model.getters.getActiveCell().defaultAlign}function cG(e){const t=e.model.getters.getCurrentStyle();return t.verticalAlign?t.verticalAlign:L}function hG(e){const t=e.model.getters.getCurrentStyle();return t.wrapping?t.wrapping:V}const dG=new xz;dG.add("cut",{...zH,sequence:10}).add("copy",{...VH,sequence:20}).add("paste",{...HH,sequence:30}).add("paste_special",{...UH,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...BH,sequence:10}).addChild("paste_format_only",["paste_special"],{...GH,sequence:20}).add("sort_columns",{...oB,name:e=>e.model.getters.getActiveCols().size>1?Cs("Sort columns"):Cs("Sort column"),sequence:50,separator:!0}).addChild("sort_ascending",["sort_columns"],{...iB,sequence:10}).addChild("sort_descending",["sort_columns"],{...lB,sequence:20}).add("add_column_before",{...gU,sequence:70}).add("add_column_after",{...fU,sequence:80}).add("delete_column",{...YH,sequence:90,icon:"o-spreadsheet-Icon.TRASH"}).add("clear_column",{...KH,sequence:100,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_columns",{...lH,sequence:105,separator:!0}).add("unhide_columns",{...cH,sequence:106,separator:!0}).add("conditional_formatting",{...nG,sequence:110,separator:!0}).add("edit_table",{...sU,isVisible:eH,sequence:120}).add("delete_table",{...oU,isVisible:eH,sequence:125,separator:!0}).add("group_columns",{sequence:150,...TH}).add("ungroup_columns",{sequence:155,..._H,isVisible:e=>PH(e,"COL")});const uG={CannotHideAllRows:Cs("Cannot hide all the rows of a sheet."),CannotHideAllColumns:Cs("Cannot hide all the columns of a sheet.")};function gG(e,t,s,o,i){const n=e.model.getters.getHeaderGroup(t,s,o,i);if(!n)return;const r=n.isFolded?"UNFOLD_HEADER_GROUP":"FOLD_HEADER_GROUP",a=e.model.dispatch(r,{sheetId:t,dimension:s,start:n.start,end:n.end});if(!a.isSuccessful&&a.isCancelledBecause("NotEnoughElements")){const t="ROW"===s?uG.CannotHideAllRows:uG.CannotHideAllColumns;e.raiseError(t)}}function pG(e,t){return Sv([{id:"unfold_all",name:Cs("ROW"===t?"Expand all row groups":"Expand all column groups"),execute:s=>{s.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:e,dimension:t})},icon:"o-spreadsheet-Icon.EXPAND"},{id:"fold_all",name:Cs("ROW"===t?"Collapse all row groups":"Collapse all column groups"),execute:s=>{s.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:e,dimension:t})},icon:"o-spreadsheet-Icon.COLLAPSE"}])}const mG=new xz;mG.add("group_columns",{sequence:10,...TH,isVisible:()=>!0,isEnabled:TH.isVisible}).add("group_rows",{sequence:20,...AH,isVisible:()=>!0,isEnabled:AH.isVisible});const fG=new xz;fG.add("ungroup_columns",{sequence:10,..._H,isEnabled:e=>PH(e,"COL")}).add("ungroup_rows",{sequence:20,...DH,isEnabled:e=>PH(e,"ROW")});const vG=new xz;vG.add("cut",{...zH,sequence:10}).add("copy",{...VH,sequence:20}).add("paste",{...HH,sequence:30}).add("paste_special",{...UH,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...BH,sequence:10}).addChild("paste_format_only",["paste_special"],{...GH,sequence:20}).add("add_row_before",{...aU,sequence:50}).add("add_row_after",{...hU,sequence:60}).add("delete_row",{...qH,sequence:70,icon:"o-spreadsheet-Icon.TRASH"}).add("clear_row",{...jH,sequence:80,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_rows",{...dH,sequence:85,separator:!0}).add("unhide_rows",{...uH,sequence:86,separator:!0}).add("conditional_formatting",{...nG,sequence:90,separator:!0}).add("group_rows",{sequence:100,...AH}).add("ungroup_rows",{sequence:110,...DH,isVisible:e=>PH(e,"ROW")});class bG extends Lv{highlightStore=this.get(NV);constructor(e){super(e),this.highlightStore.register(this)}get highlights(){const e=this.model.getters.getActivePosition(),t=this.model.getters.getArrayFormulaSpreadingOn(e),s=t?this.model.getters.getSpreadZone(t,{ignoreSpillError:!0}):this.model.getters.getSpreadZone(e,{ignoreSpillError:!0});if(!s)return[];const o=this.model.getters.isArrayFormulaSpillBlocked(t??e);return[{range:this.model.getters.getRangeFromZone(e.sheetId,s),dashed:o,color:"#17A2B8",noFill:!0,thinLine:!0}]}}class SG extends Lv{mutators=["focusClient","unfocusClient","showClientTag","hideClientTag","jumpToClient"];_showClientTag=!1;clientFocusTimeout={};constructor(e){super(e),this.onDispose(()=>{for(const e in this.clientFocusTimeout)this.unfocusClient(e)})}get focusedClients(){const e=new Set;return this.model.getters.getConnectedClients().forEach(t=>{(this._showClientTag||void 0!==this.clientFocusTimeout[t.id])&&e.add(t.id)}),e}jumpToClient(e){const t=this.model.getters.getClient(e);this.focusClient(e),t.position&&(this.model.dispatch("ACTIVATE_SHEET",{sheetIdTo:t.position.sheetId,sheetIdFrom:this.getters.getActiveSheetId()}),this.model.dispatch("SCROLL_TO_CELL",{col:t.position.col,row:t.position.row}))}showClientTag(){this._showClientTag=!0}hideClientTag(){this._showClientTag=!1}focusClient(e){this.clientFocusTimeout[e]&&clearTimeout(this.clientFocusTimeout[e]),this.clientFocusTimeout[e]=setTimeout(()=>this.unfocusClient(e),3e3)}unfocusClient(e){this.clientFocusTimeout[e]&&clearTimeout(this.clientFocusTimeout[e]),this.clientFocusTimeout[e]=void 0}}function yG(e){let s,o,i,n,r=null,a="all";const l=e.model.getters,c=e=>e.preventDefault(),h=()=>removeEventListener("keydown",c,{capture:!0});let d=[];const u=()=>{clearTimeout(r),r=null,d.forEach(e=>e()),d=[]};let g,p;const m=t=>{if(s=t,r)return;const c=l.getActiveSheetId(),h=_N(e.model.getters.getViewportZoomLevel()),d=$N(e,s,h),{x:u,y:p}=l.getMainViewportCoordinates(),{top:f,left:v,bottom:b,right:S}=l.getActiveMainViewport();let{scrollX:y,scrollY:C}=l.getActiveSheetScrollInfo();const{xSplit:I,ySplit:w}=l.getPaneDivisions(c);let E=!1,x=140;const R=d.clientX-h.x;let T=l.getColIndex(R);if("vertical"!==a){const t=o.clientX-h.x,s=l.getEdgeScrollCol(R,t,i);if(s.canEdgeScroll){E=!0,x=Math.min(x,s.delay);let t=T;switch(s.direction){case"reset":T=t=I;break;case 1:T=S,t=v+1;break;case-1:for(T=v-1;e.model.getters.isColHidden(c,T);)T--;t=T}y=l.getColDimensions(c,t).start-u}}const A=d.clientY-h.y;let _=l.getRowIndex(A);if("horizontal"!==a){const t=o.clientY-h.y,s=l.getEdgeScrollRow(A,t,n);if(s.canEdgeScroll){E=!0,x=Math.min(x,s.delay);let t=_;switch(s.direction){case"reset":_=t=w;break;case 1:_=b,t=f+1;break;case-1:for(_=f-1;e.model.getters.isRowHidden(c,_);)_--;t=_}C=e.model.getters.getRowDimensions(c,t).start-p}}E||(T=CG(T,R,l.getNumberCols(c)-1),_=CG(_,A,l.getNumberRows(c)-1)),g?.(T,_,s),E&&(e.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:y,offsetY:C}),r=setTimeout(()=>{r=null,m(s)},Math.round(x))),o={clientX:d.clientX,clientY:d.clientY}},f=()=>{p?.(),u()};return t.onWillUnmount(()=>{u()}),t.useEffect(()=>{u()},()=>[l.getActiveSheetId()]),{start:(t,s,r,l="all")=>{u();const v=_N(e.model.getters.getViewportZoomLevel());a=l,i=t.clientX-v.x,n=t.clientY-v.y,o={clientX:t.clientX,clientY:t.clientY},g=s,p=r,addEventListener("keydown",c,{capture:!0}),d.push(qV(m,f),h)}}}function CG(e,t,s){return-1===e?t<0?0:s:e}class IG extends t.Component{static template="o-spreadsheet-Autofill";static props={position:Object,isVisible:Boolean};state=t.useState({position:{x:0,y:0},handler:!1});dragNDropGrid=yG(this.env);get style(){const{x:e,y:t}=this.props.position;return JF({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?"visible":"hidden"})}get handlerStyle(){const{x:e,y:t}=this.state.handler?this.state.position:this.props.position;return JF({top:`${t}px`,left:`${e}px`})}get styleNextValue(){const{x:e,y:t}=this.state.position;return JF({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){const e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=wG),e}onMouseDown(e){this.state.handler=!0;const t=$N(this.env,e),s=this.env.model.getters.getViewportZoomLevel();let o,i;const n=e.clientX/s-this.props.position.x,r=e.clientY/s-this.props.position.y;this.dragNDropGrid.start(t,(e,t,a)=>{if(this.state.position={x:a.clientX/s-n,y:a.clientY/s-r},o!==e||i!==t){const s=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getNumberCols(s),r=this.env.model.getters.getNumberRows(s);o=-1===e?o:me(e,0,n),i=-1===t?i:me(t,0,r),void 0!==o&&void 0!==i&&this.env.model.dispatch("AUTOFILL_SELECT",{col:o,row:i})}},()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch("AUTOFILL")})}onDblClick(){this.env.model.dispatch("AUTOFILL_AUTO")}}class wG extends t.Component{static props={content:String};static template=t.xml`
|
|
835
|
+
`}var xM;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(xM||(xM={}));function RM(e,t={}){const s=he(t);return s.type=e,s}const TM={showHeaders:!0,headerDesign:{align:"center",fillColor:"#808080",bold:!0,fontSize:15},showValues:!0,showLabels:!0,valuesDesign:{align:"left",verticalAlign:"bottom",fontSize:12},coloringOptions:{type:"categoryColor",colors:[],useValueBasedGradient:!0}},AM={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},_M=function(e){return Math.floor(e/AM.second)},DM=function(e){return Math.floor(e/AM.minute)},OM=function(e){return Math.floor(e/AM.hour)},FM=function(e){return Math.floor(e/AM.day)},PM=function(e){return Math.floor(e/AM.month)},MM=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function NM(e,t,s){const o=function(e){const t=e.indexOf("h");e=t>=0?e.slice(0,t).replace(/m/g,"M")+e.slice(t):e.replace(/m/g,"M");e.includes("a")||(e=e.replace(/h/g,"H"));return e}(t),i=function(e,t,s){const o=e.map(e=>Qs(e,s)?.jsDate);if(o.some(e=>void 0===e)||e.length<2)return;const i=o.map(e=>e.getTime()),n=tt(i)-st(i),r=function(e){if(e.includes("s"))return"second";if(e.includes("m"))return"minute";if(e.includes("h")||e.includes("H"))return"hour";if(e.includes("d"))return"day";if(e.includes("M"))return"month";return"year"}(t);if(AM.second>=AM[r]&&_M(n)<180)return"second";if(AM.minute>=AM[r]&&DM(n)<180)return"minute";if(AM.hour>=AM[r]&&OM(n)<96)return"hour";if(AM.day>=AM[r]&&FM(n)<90)return"day";if(AM.month>=AM[r]&&PM(n)<36)return"month";return"year"}(e,o,s),n={};return i&&(n[i]=o),{parser:o,displayFormats:n,unit:i??!1,tooltipFormat:o}}function kM(e,t){let s={};const{trendDataSetsValues:o,locale:i,axisFormats:n}=t,r={stacked:e.stacked,locale:i};if(e.horizontal)s.x=jM(e,"bottom","values",{...r,format:n?.x}),s.y=jM(e,"left","labels",r);else{s.x=jM(e,"bottom","labels",r);const t={...r,format:n?.y};s.y=jM(e,"left","values",t);const o={...r,format:n?.y1};s.y1=jM(e,"right","values",o)}if(s=Ue(s),o&&o.length&&o.some(De)){const e=Math.max(...o.map(e=>e?.length||0));s[_y]={...s.x,labels:Array(e).fill(""),offset:!1,display:!1},s[Dy]={...s.x,offset:!0,display:!1}}return s}function LM(e,t){const s=t.map(e=>e.label||""),o=Uy(e.background);return{y:{title:ZM(e.axesDesign?.y),stacked:!0,min:0,max:s.length,ticks:{stepSize:.5,color:o,callback:function(e,t,o){if(t%2!=0)return s[Math.floor((t-1)/2)]}},grid:{display:!1},border:{display:!1}},x:{title:ZM(e.axesDesign?.x),stacked:!0,grid:{display:!1},position:"top",ticks:{color:o},border:{display:!1}}}}function VM(e,t){const{dataSetsValues:s}=t;if(!s.length||"none"===e.legendPosition)return;const o=s.flatMap(e=>e.data).filter(De),i=Math.min(...o),n=Math.max(...o);let r=[];return r="object"==typeof e.colorScale?[e.colorScale.minColor,e.colorScale.midColor,e.colorScale.maxColor].filter(De):[...wb[e.colorScale??"oranges"]],{position:"right"===e.legendPosition?"right":"left",colorScale:r,fontColor:Uy(e.background),minValue:i,maxValue:n,locale:t.locale}}function zM(e,t){const{locale:s,axisType:o,trendDataSetsValues:i,labels:n,axisFormats:r}=t,a=r?.x,l=e.stacked;let c={x:jM(e,"bottom","labels",{locale:s}),y:jM(e,"left","values",{locale:s,stacked:l,format:r?.y}),y1:jM(e,"right","values",{locale:s,stacked:l,format:r?.y1})};if(c=Ue(c),"time"===o&&n&&a){const e={type:"time",time:NM(n,a,s)};Object.assign(c.x,e),c.x.ticks.maxTicksLimit=15,delete c?.x?.ticks?.callback}else"linear"===o&&(c.x.type="linear",c.x.ticks.callback=e.humanize?e=>rn({value:e,format:a},s):e=>zi(e,{format:a,locale:s}));if(i&&i.length&&i.some(De)&&(c[_y]={...c.x,display:!1},c[Dy]={...c.x,display:!1},"category"===o||"time"===o)){const e=Math.max(...i.map(e=>e?.length||0));c[_y].type="category",c[_y].labels=fe(0,e).map(e=>e.toString()),c[_y].offset=!1,c[Dy].type="category",c[Dy].offset=!1}return c}function HM(e,t){const s=zM(e,t);return{...s,x:{...s.x,grid:{display:!0}}}}function UM(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;e.dataSets;const n={x:{...jM(e,"bottom","labels",{locale:s}),grid:{display:!1}},y:{position:e.verticalAxisPosition,ticks:{color:Uy(e.background),callback:jy({locale:s,format:i},e.humanize)},grid:{lineWidth:e=>0===e.tick.value?2:1},title:ZM(e.axesDesign?.y)}},r=n?.y||n?.y1;return r&&(r.grid={lineWidth:e=>0===e.tick.value?2:1}),n}function BM(e,t){const{dataSetsValues:s}=t,o=kM(e,t),i=o.x.ticks.callback;o.x.ticks.callback=e=>i(Math.abs(e));const n=Math.max(...s.map(e=>Math.max(...e.data.map(Math.abs))));return o.x.suggestedMin=-n,o.x.suggestedMax=n,o}function GM(e,t){const{locale:s,axisFormats:o,dataSetsValues:i}=t,n=Math.min(...i.map(e=>Math.min(...e.data.filter(e=>!isNaN(e)))));return{r:{beginAtZero:!0,ticks:{callback:jy({format:o?.r,locale:s},e.humanize),backdropColor:e.background||"#FFFFFF"},pointLabels:{color:Uy(e.background),callback:e=>Ky(e)},suggestedMin:n<0?n-1:0}}}function WM(e,t){const{locale:s,axisFormats:o,availableRegions:i}=t,n=function(e){switch(e){case"top":return"top-left";case"right":return"top-right";case"bottom":return"bottom-right";case"left":case"none":return"bottom-left"}}(e.legendPosition),r=e.region?i.find(t=>t.id===e.region):i[0],a=o?.y||o?.y1;return{projection:{projection:qM(r?.defaultProjection||"mercator"),axis:"x"},color:{axis:"x",display:"none"!==e.legendPosition,border:{color:S},grid:{color:S},ticks:{color:Uy(e.background),callback:jy({locale:s,format:a},e.humanize)},legend:{position:n,align:n.includes("right")?"left":"right",margin:XM(e)},interpolate:YM(e.colorScale??A),missing:e.missingValueColor||"#ffffff"}}}function $M(e,t){const s=t.dataSetsValues[0];return{x:{display:!1},y:{grid:{offset:!1},ticks:{callback:function(e){return Ky(this.getLabelForValue(e))}},border:{display:!1}},percentages:{position:"right",border:{display:!1},ticks:{callback:function(e,o,i){const n=s.data?.[o],r=s.data?.[0];return r&&void 0!==n?zi(n/r,{format:"0%",locale:t.locale}):""}},grid:{display:!1}}}}function qM(e){return"conicConformal"===e?globalThis.ChartGeo.geoConicConformal().rotate([100,0]):e}function ZM(e){if(e?.title?.text){const{text:t,color:s,align:o,italic:i,bold:n}=e.title;return{display:!0,text:t,color:s,font:{style:i?"italic":"normal",weight:n?"bold":"normal",size:e.title.fontSize??12},align:"left"===o?"start":"right"===o?"end":"center"}}}function jM(e,t,s,o){const{useLeftAxis:i,useRightAxis:n}=qy(e);if("left"===t&&!i||"right"===t&&!n)return;const r=Uy(e.background);let a;if(a="bottom"===t?e.axesDesign?.x:"left"===t?e.axesDesign?.y:e.axesDesign?.y1,"values"===s){const s=!("right"===t&&i);return{position:t,title:ZM(a),grid:{display:s},beginAtZero:!0,stacked:o?.stacked,ticks:{color:r,callback:jy(o,e.humanize)}}}return{ticks:{padding:5,color:r,callback:function(e,t,s){return Ky(this.getLabelForValue(e))}},grid:{display:!1},stacked:o?.stacked,title:ZM(a)}}function YM(e,t=0,s=1){if(t===s){const t=e.midColor??e.minColor;return e=>t}const o=[{value:t,color:e.minColor}];return e.midColor&&o.push({value:(t+s)/2,color:e.midColor}),o.push({value:s,color:e.maxColor}),xb(o)}function XM(e){switch(e.legendPosition){case"top":case"right":return{top:!!e.title.text?45:R,left:E,right:E};case"bottom":case"left":case"none":return{left:E,right:E,bottom:x}}}const KM="nullValue";function JM(e,t){const{dataSetsValues:s}=t,o=[],i=vN(e,s.length),n=[];for(const r in s){let{label:a,data:l,hidden:h}=s[r];a=e.dataSets?.[r].label||a;const d=i.next(),u={label:a,data:l,hidden:h,borderColor:e.background||c,borderWidth:e.stacked?1:0,backgroundColor:d,yAxisID:e.horizontal?"y":e.dataSets?.[r].yAxisId||"y",xAxisID:"x",barPercentage:.9,categoryPercentage:s.length>1?.8:1,borderRadius:2};o.push(u);const g=e.dataSets?.[r].trend,p=t.trendDataSetsValues?.[r];g?.display&&!e.horizontal&&p&&n.push(mN(u,g,p))}return o.push(...n),o}function QM(e,t){const{labels:s,dataSetsValues:o}=t,i=o.map(e=>e.data).flat().filter(De),n=Math.max(...i),r=Math.min(...i),a=YM(e.colorScale??A,r,n),l=[];for(const t of o)l.push({label:t.label,data:t.data.map(e=>1),backgroundColor:t.data.map(t=>void 0!==t?a(t):e.missingValueColor||p),borderColor:e.background||c,borderSkipped:!1,borderWidth:1,barPercentage:1,categoryPercentage:1,values:t.data});return{labels:s,datasets:l}}function eN(e,t){const{dataSetsValues:s,labels:o}=t,i=e.negativeValuesColor||f,n=e.positiveValuesColor||m,r=e.subTotalValuesColor||v,a=[],l=[],c={label:"",data:l,backgroundColor:a},h=[];let d=0;for(const t of s)if(!t.hidden){for(let c=0;c<t.data.length;c++){const u=t.data[c];if(h.push(o[c]),isNaN(Number(u))){l.push([d,d]),a.push("");continue}l.push([d,u+d]);let g=u>=0?n:i;0===c&&t===s[0]&&e.firstValueAsSubtotal&&(g=r),a.push(g),d+=u}e.showSubTotals&&(h.push(Cs("Subtotal")),l.push([0,d]),a.push(r))}return{datasets:[c],labels:h}}function tN(e,t){const{dataSetsValues:s,axisType:o,labels:i}=t,n=[],r=!!e.fillArea,a=!!e.stacked,l=[],c=vN(e,s.length);for(let h=0;h<s.length;h++){let{label:d,data:u,hidden:g}=s[h];d=e.dataSets?.[h].label||d;const p=c.next();o&&["linear","time"].includes(o)&&(u=u.map((e,t)=>({x:i[t]||void 0,y:e})));const m={label:d,data:u,hidden:g,tension:0,borderColor:p,backgroundColor:r?ab(p,.4):p,pointBackgroundColor:p,fill:!!r&&fN(h,a),pointRadius:e.hideDataMarkers?0:3,yAxisID:e.dataSets?.[h].yAxisId||"y"};n.push(m);const f=e.dataSets?.[h].trend,v=t.trendDataSetsValues?.[h];f?.display&&v&&l.push(mN(m,f,v))}return n.push(...l),n}function sN(e,t){const s=tN(e,t);for(const e of s)Jy(e.xAxisID)||(e.showLine=!1);return s}function oN(e,t){const{dataSetsValues:s}=t,o=[],i=Math.max(0,...s.map(e=>e?.data?.length??0)),n=Xy(new yb(i),s);for(const{label:t,data:i,hidden:r}of s){if(r)continue;const s={label:t,data:i,borderColor:e.background||"#FFFFFF",backgroundColor:n,hoverOffset:10};o.push(s)}return o}function iN(e,t){const{dataSetsValues:s}=t,o=[],i=vN(e,s.length),n=[],r=s.filter((t,s)=>"bar"===(e.dataSets?.[s].type??"line"));for(let a=0;a<s.length;a++){let{label:l,data:c,hidden:h}=s[a];l=e.dataSets?.[a].label||l;const d=e.dataSets?.[a],u=i.next(),g=d?.type??"line",p={label:l,data:c,hidden:h,borderColor:u,backgroundColor:u,yAxisID:e.dataSets?.[a].yAxisId||"y",xAxisID:"x",type:g,order:"bar"===g?s.length+a:a,pointRadius:e.hideDataMarkers?0:3};"bar"===p.type&&(p.barPercentage=.9,p.categoryPercentage=r.length>1?.8:1,p.borderRadius=2),o.push(p);const m=e.dataSets?.[a].trend,f=t.trendDataSetsValues?.[a];m?.display&&f&&n.push(mN(p,m,f))}return o.push(...n),o}function nN(e,t){const{dataSetsValues:s}=t,o=[],i=e.fillArea??!1,n=vN(e,s.length);for(let t=0;t<s.length;t++){let{label:r,data:a,hidden:l}=s[t];e.dataSets?.[t]?.label&&(r=e.dataSets[t].label);const c=n.next(),h={label:r,data:a,hidden:l,borderColor:c,backgroundColor:c,pointRadius:e.hideDataMarkers?0:3};i&&(h.backgroundColor=ab(c,.4),h.fill="start"),o.push(h)}return o}function rN(e,t){const{availableRegions:s,dataSetsValues:o,labels:i}=t,n=e.region||s[0]?.id,r=n?t.getGeoJsonFeatures(n):void 0,a={outline:r,showOutline:!!r,data:[]};if(r&&n){const e={};if(o[0])for(let s=0;s<o[0].data.length;s++){if(!i[s]||void 0===o[0].data[s])continue;const r=t.geoFeatureNameToId(n,i[s]);r&&(e[r]={value:o[0].data[s],label:i[s]})}for(const t of r)t.id&&a.data.push({feature:{...t,properties:{name:e[t.id]?.label}},value:e[t.id]?.value})}return[a]}function aN(e,t){const s=t.dataSetsValues[0],o=t.labels;if(!s)return[];let{label:i,data:n}=s;i=e.dataSets?.[0].label||i;return[{label:i,data:n.map(e=>e<=0?[0,0]:[-e,e]),backgroundColor:lN(o,e.funnelColors),yAxisID:"y",xAxisID:"x",barPercentage:1,categoryPercentage:1,borderColor:e.background||c,borderWidth:3}]}function lN(e,t){const s=new yb(e.length,t);return e.map(()=>s.next())}function cN(e,t){const{dataSetsValues:s,labels:o}=t,i=uN(hN(s,o)),n=i[0]||[],r=new yb(n.length,e.groupColors||[]),a=n.map(e=>({label:e.label,color:r.next()})),l=[];for(let t=i.length-1;t>=0;t--){const s={groupColors:a,parsing:{key:"value"},data:i[t],borderColor:t=>{const s="data"===t.type?t.raw:void 0;return s&&s.label!==KM?e.background||c:p},backgroundColor:e=>{const t="data"===e.type?e.raw:void 0;if(!t||t.label===KM)return p;const s=t.groups[0];return a.find(e=>e.label===s)?.color},hoverOffset:10};l.push(s)}return l}function hN(e,t){const s=function(e,t){const s=[],o=Math.max(...e.map(e=>e.data.length));for(let i=0;i<o;i++){s[i]={};for(let t=0;t<e.length;t++){const o=null===e[t].data[i]?KM:String(e[t].data[i]);s[i][t]=o}s[i].value=Number(t[i])}return s}(e,t);return dN(s,0,e.length,[])}function dN(e,t,s,o){if(t>=s)return[];const i=Object.groupBy(e,e=>e[t]);return Object.keys(i).map(e=>{const n=i[e]?.reduce((e,t)=>e+Number(t.value),0)||0,r=[...o,e];return{label:e,value:n,children:dN(i[e]||[],t+1,s,[...o,e]),groups:r,depth:t}}).sort((e,t)=>t.value-e.value)}function uN(e){const t=[],s=[...e];for(;s.length>0;){const e=s.shift();e&&(t[e.depth]||(t[e.depth]=[]),t[e.depth].push(e),e.children&&s.push(...e.children))}return t}function gN(e,t){const{dataSetsValues:s,labels:o,locale:i,axisFormats:n}=t,r={locale:i,format:n?.y};if(0===s.length)return[];const a=hN(s,o).sort((e,t)=>t.value-e.value),l=function(e,t){const s="categoryColor"===e.coloringOptions?.type?e.coloringOptions.colors:[],o=new yb(t.length,s);return t.map(e=>({label:e.label,color:o.next()}))}(e,a),c=[],h=Math.max(...s.map(e=>e.data.length));for(let e=0;e<h;e++){c[e]={};for(let t=0;t<s.length;t++)c[e][t]=s[t].data[e]?String(s[t].data[e]):void 0;c[e].value=Number(o[e])}const d=e.showLabels??TM.showLabels,u=e.showValues??TM.showValues,g=e.coloringOptions||TM.coloringOptions;let p;"colorScale"===g?.type&&(p=function(e,t){if(0===e.length)return;const s=uN(e),o=s[s.length-1],i=Math.min(...o.map(e=>e.value)),n=Math.max(...o.map(e=>e.value));if(Number.isFinite(i)&&Number.isFinite(n)){const e=[{value:i,color:t.minColor}];if(t.midColor){const s=(i+n)/2;e.push({value:s,color:t.midColor})}return e.push({value:n,color:t.maxColor}),xb(e)}return}(a,g));const m=[{data:[],tree:c,labels:{display:d||u,overflow:"hidden",...pN(e.valuesDesign,TM.valuesDesign),formatter:e=>[d?e.raw.g:void 0,u?zi(e.raw.v,r):void 0].filter(De)},captions:{display:e.showHeaders??TM.showHeaders,padding:6,...pN(e.headerDesign,TM.headerDesign)},key:"value",groups:fe(0,s.length).map(e=>String(e)),borderWidth:0,spacing:1,displayMode:"headerBoxes",groupColors:l,backgroundColor:t=>{if("data"!==t.type)return"transparent";if(!t.raw.isLeaf)return e.headerDesign?.fillColor||TM.headerDesign?.fillColor;if("colorScale"===g.type)return p?.(t.raw.v)||"#FF0000";if("categoryColor"===g.type)return function(e,t,s,o){const i=e.raw._data.children[0][0],n=o.find(e=>e.label===i)?.color;if(!n||!s.useValueBasedGradient)return n||"#FF0000";const r=t.find(e=>e.label===i);if(!r||!r.children.length)return n;const a=uN(r.children),l=a[a.length-1],c=Math.max(...l.map(e=>e.value)),h=Math.min(...l.map(e=>e.value));if(h===c||!isFinite(h)||!isFinite(c))return n;const d=Number(e.raw.v)||0,u=(d-c)/(h-c)*.5;return lb(n,u)}(t,a,g,l);throw new Error("Unsupported coloring option type}")}}];return m}function pN(e,t){const s=e=>Qv(e.element.options.backgroundColor)>.7?"#666666":"#FFFFFF";return{align:e?.align??t?.align,position:e?.verticalAlign??t?.verticalAlign,color:e?.color||s,hoverColor:e?.color||s,font:{weight:e?.bold??t?.bold?"bold":"normal",style:e?.italic??t?.italic?"italic":"normal",size:e?.fontSize??t?.fontSize}}}function mN(e,t,s){const o=tb(e.backgroundColor);o.a=1;const i=t.color||lb(eb(o),.5);return{type:"line",xAxisID:"trailingMovingAverage"===t.type?Dy:_y,yAxisID:e.yAxisID,label:e.label?Cs("Trend line for %s",e.label):"",data:s,order:-1,showLine:!0,pointRadius:0,backgroundColor:i,borderColor:i,borderDash:[5,5],borderWidth:void 0,fill:!1,pointBackgroundColor:i}}function fN(e,t){return t?0===e?"origin":"-1":"origin"}function vN(e,t){return new yb(t,e.dataSets?.map(e=>e.backgroundColor)||[])}const bN={id:"sunburstHoverPlugin",afterEvent(e,t,s){if(!s.enabled)return;const o=e.getActiveElements();let i=o.map(e=>({datasetIndex:e.datasetIndex,index:e.index}));for(const t of o){const s=e.data.datasets[t.datasetIndex].data[t.index];for(let t=0;t<e.data.datasets.length;t++){const o=e.data.datasets[t];for(let e=0;e<o.data.length;e++){const n=o.data[e];SN(s.groups,n.groups)&&i.push({datasetIndex:t,index:e})}}}i=i.filter(t=>{const{datasetIndex:s,index:o}=t;return e.data.datasets[s].data[o].label!==KM}),e.setActiveElements(i);for(const t of e.getSortedVisibleDatasetMetas())for(const e of t.data){const t=e.$context,{datasetIndex:s,index:o,dataset:n,raw:r}=t;if(r.label===KM)continue;const a="function"==typeof n.backgroundColor?n.backgroundColor(t):n.backgroundColor;i.length&&!i.some(e=>e.datasetIndex===s&&e.index===o)?e.options.backgroundColor=lb(a,.5):e.options.backgroundColor=a}}};function SN(e,t){return t.length>e.length&&e.every((e,s)=>e===t[s])}const yN={id:"sunburstLabelsPlugin",afterDatasetsDraw(e,t,s){if(!s.showValues&&!s.showLabels||"doughnut"!==e.config.type)return;!function(e,t,s){const o=t.style,i=o.fontSize||13,n=i+3;for(const r of e._metasets)for(let a=0;a<r._dataset.data.length;a++){const l=r._dataset.data[a];if(l.label===KM)continue;const c=[t.showLabels?l.label:void 0,t.showValues?t.callback(l.value,"y"):void 0].filter(De),h=r.data[a];let{startAngle:d,endAngle:u,innerRadius:g,outerRadius:p,circumference:m}=h;const f=h.options.offset/4,v=f*(1-Math.sin(Math.min(Math.PI,m||0)));g+=v,p+=v;const b=(d+u)/2,S=(g+p)/2,y=.9*(p-g),C=u-d;if((C>=Math.PI?p:Math.sin(C/2)*g*2)<c.length*n)continue;s.save();const I={x:Math.cos(b)*f,y:Math.sin(b)*f},w=e.chartArea.left+e.chartArea.width/2+I.x,E=e.chartArea.top+e.chartArea.height/2+I.y;let x;s.translate(w,E),b>Math.PI/2?(s.rotate(b-Math.PI),x=-S):(x=S,s.rotate(b));const R=Qv(h.options.backgroundColor)>.7?"#666666":"#FFFFFF";s.fillStyle=o.textColor||R,s.textAlign="center",s.textBaseline="middle",s.font=yS(i,o.bold,o.italic);const T=-(c.length-1)*n/2;for(let e=0;e<c.length;e++){const t=NS(s,y,c[e],o,"px");s.fillText(t,x,T+e*n)}s.restore()}}(e,s,e.ctx)}};const CN={id:"waterfallLinesPlugin",beforeDraw(e,t,s){if(!s.showConnectorLines)return;const o=e._metasets?.[0]?.data;if(!o)return;const i=e.ctx;i.save(),i.setLineDash([3,2]);for(let e=0;e<o.length;e++){const t=o[e];if(0===t.height)continue;const s=wN(o,e);if(!s)break;const n=IN(t),r=IN(s),a=t.$context.raw,l=a[1]-a[0],c=Math.round(l<0?n.bottom-1:n.top),h=Math.round(n.right),d=Math.round(r.left);i.strokeStyle="#999",i.beginPath(),i.moveTo(h+1,c+.5),i.lineTo(d,c+.5),i.stroke()}i.restore()}};function IN(e){const t=e.base<e.y;return{left:e.x-e.width/2,right:e.x+e.width/2,bottom:t?e.base+e.height:e.y+e.height,top:t?e.base:e.y}}function wN(e,t){return e.find((e,s)=>s>t&&0!==e.height)}const EN={id:"zoomWindowPlugin",afterDatasetsDraw:function(e,t,s){if(!s.getLowerBound||!s.getUpperBound)return;const{ctx:o,chartArea:{left:i,right:n,top:r,bottom:a}}=e;let l=s.getLowerBound()??i,c=s.getUpperBound()??n;l>c&&([l,c]=[c,l]),l=Math.max(i,l),c=Math.min(n,c),l===i&&(l-=1),c===n&&(c+=1),o.save(),o.fillStyle="rgba(255,255,255,0.5)",o.beginPath(),o.rect(i,a,l-i,r-a),o.rect(c,a,n-c,r-a),o.fill(),o.beginPath(),o.strokeStyle="#bbb",o.rect(l,a,c-l,r-a),o.stroke(),o.lineWidth=2,o.beginPath(),o.moveTo(l-3,(r+a)/2-7),o.lineTo(l-3,(r+a)/2+7),o.stroke(),o.beginPath(),o.moveTo(c+3,(r+a)/2-7),o.lineTo(c+3,(r+a)/2+7),o.stroke(),o.restore()}};Hv.add("chartShowValuesPlugin",{register:e=>e.register(Tx),unregister:e=>e.unregister(Tx)}),Hv.add("waterfallLinesPlugin",{register:e=>e.register(CN),unregister:e=>e.unregister(CN)}),Hv.add("funnelController",{register:e=>e.register(US()),unregister:e=>e.unregister(US())}),Hv.add("funnelElement",{register:e=>e.register(BS()),unregister:e=>e.unregister(BS())}),Hv.add("funnelTooltipPositioner",{register:e=>e.Tooltip.positioners.funnelTooltipPositioner=WS,unregister:e=>e.Tooltip.positioners.funnelTooltipPositioner=void 0}),Hv.add("sunburstLabelsPlugin",{register:e=>e.register(yN),unregister:e=>e.unregister(yN)}),Hv.add("sunburstHoverPlugin",{register:e=>e.register(bN),unregister:e=>e.unregister(bN)}),Hv.add("chartColorScalePlugin",{register:e=>e.register(HS),unregister:e=>e.unregister(HS)}),Hv.add("calendarController",{register:e=>e.register(zS()),unregister:e=>e.unregister(zS())}),Hv.add("zoomWindowPlugin",{register:e=>e.register(EN),unregister:e=>e.unregister(EN)});class xN extends t.Component{static template="o-spreadsheet-ChartJsComponent";static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=t.useRef("graphContainer");chart;currentRuntime;animationStore;currentDevicePixelRatio=window.devicePixelRatio;get background(){return this.chartRuntime.background}get canvasStyle(){return`background-color: ${this.background}`}get chartRuntime(){const e=this.env.model.getters.getChartRuntime(this.props.chartId);if(!("chartJsConfig"in e))throw new Error("Unsupported chart runtime");return e}setup(){this.shouldAnimate&&(this.animationStore=Tv(VS)),t.onMounted(()=>{Bv();const e=this.chartRuntime;this.currentRuntime=e,this.createChart(he(e))}),t.onWillUnmount(this.unmount.bind(this)),t.useEffect(()=>{const e=this.chartRuntime;e!==this.currentRuntime?(e.chartJsConfig.type!==this.currentRuntime.chartJsConfig.type?(this.chart?.destroy(),this.createChart(he(e))):this.updateChartJs(he(e)),this.currentRuntime=e):this.currentDevicePixelRatio!==window.devicePixelRatio&&(this.currentDevicePixelRatio=window.devicePixelRatio,this.updateChartJs(he(this.currentRuntime)))})}unmount(){this.chart?.destroy()}get shouldAnimate(){return this.env.model.getters.isDashboard()}createChart(e){if(!globalThis.Chart)throw new Error("Chart.js library is not loaded");let t=e.chartJsConfig;if(this.shouldAnimate&&this.animationStore){const e=this.env.model.getters.getChart(this.props.chartId)?.type;e&&this.animationStore.animationPlayed[this.animationChartId]!==e&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}const s=this.canvas.el.getContext("2d");this.chart=new globalThis.Chart(s,t)}updateChartJs(e){let t=e.chartJsConfig;if(this.shouldAnimate){const e=this.env.model.getters.getChart(this.props.chartId)?.type;e&&this.hasChartDataChanged()&&this.animationStore&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}t.data&&t.data.datasets?(this.chart.data=t.data,t.options?.plugins?.title&&(this.chart.config.options.plugins.title=t.options.plugins.title)):this.chart.data.datasets=[],this.chart.config.options=t.options,this.chart.update()}hasChartDataChanged(){return!Le(this.getChartDataInRuntime(this.currentRuntime),this.getChartDataInRuntime(this.chartRuntime))}enableAnimationInChartData(e){return{...e,options:{...e.options,animation:{animateRotate:!0}}}}getChartDataInRuntime(e){const t=e.chartJsConfig.data;return{labels:t.labels,dataset:t.datasets.map(e=>({data:e.data,label:e.label,tree:e.tree}))}}get animationChartId(){return this.props.isFullScreen?this.props.chartId+"-fullscreen":this.props.chartId}}const RN=/Mac/i,TN=["Shift","Control","Alt","Meta"];function AN(e,t){return!!e&&(!!t.target&&e.contains(t.target))}function _N(e=1){const t=document.querySelector(".o-grid-overlay"),s=t&&DN(t,e);if(!s)throw new Error("Can't find spreadsheet position");return s}function DN(e,t){const s=e.closest(".o-zoomable");let o,i=1;s?(o=s,i=!/Chrome/i.test(navigator.userAgent)&&/Safari/i.test(navigator.userAgent)?t:1):o=e;const n=o.getBoundingClientRect();return{x:n.x*i,y:n.y*i,width:n.width*i,height:n.height*i}}function ON(e){return e.el?FN(e.el):{x:0,y:0,width:0,height:0}}function FN(e){const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*PN(e){if(yield e,e.hasChildNodes())for(const t of e.childNodes)yield*PN(t)}function MN(e){const{startElement:t,endElement:s,startSelectionOffset:o,endSelectionOffset:i}=function(e){const t=document.getSelection();return{startElement:t.anchorNode||e,startSelectionOffset:t.anchorOffset,endElement:t.focusNode||e,endSelectionOffset:t.focusOffset}}(e);return{start:NN(e,t,o),end:NN(e,s,i)}}function NN(e,t,s){let o=0;const i=PN(e);let n=i.next(),r=!0;for(;!n.done&&n.value!==t;)n.value.hasChildNodes()||n.value.textContent&&(o+=n.value.textContent.length),("P"===n.value.nodeName||"DIV"===n.value.nodeName&&n.value!==e)&&(r?r=!1:o++),n=i.next();if(n.value!==t)return 0;if(n.value.hasChildNodes()){const e=[...n.value.childNodes].slice(0,s);o+=e.reduce((t,s,o)=>{if(null!==s.textContent){let i=s.textContent.length;return"P"===s.nodeName&&o!==e.length-1&&i++,t+i}return t},0)}else o+=s;return"P"!==t.nodeName||r||""!==t.textContent||o++,o}const kN=/^[a-zA-Z]$/;function LN(e,t="key"){let s="";TN.includes(e.key)||(zN(e)&&(s+="Ctrl+"),e.altKey&&(s+="Alt+"),e.shiftKey&&(s+="Shift+"));const o="key"===t?e.key:e.code;return s+=kN.test(o)?o.toUpperCase():o,s}function VN(){return Boolean(RN.test(navigator.userAgent))}function zN(e){return VN()||GN()?e.metaKey:e.ctrlKey}function HN(e){return 1===e.button||zN(e)&&0===e.button}function UN(e,t){const s=document.createElement("a");s.href=e,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s)}function BN(){return/Firefox/i.test(navigator.userAgent)}function GN(){return/(iPad|iPhone|iPod)/i.test(navigator.userAgent)||"MacIntel"===navigator.platform&&(navigator.maxTouchPoints||1)>1}function WN(){return/Android/i.test(navigator.userAgent)||GN()||/(webOS|BlackBerry|Windows Phone)/i.test(navigator.userAgent)}function $N(e,t,s){const o=e.model.getters.getViewportZoomLevel();if(void 0===s&&(s=function(e,t){const s=e.target;if(!(s&&"classList"in s&&s instanceof Element))return null;return DN(s,t)}(t,o)),!s)return function(e){return{ev:e,clientX:e.clientX,clientY:e.clientY,offsetX:e.offsetX,offsetY:e.offsetY}}(t);const i=t.clientX-s.x,n=t.clientY-s.y,r=i/o,a=n/o;return{ev:t,clientX:t.clientX-i+r,clientY:t.clientY-n+a,offsetX:r,offsetY:a}}function qN(e,t){return{height:t.height*e,width:t.width*e,x:t.x*e,y:t.y*e}}class ZN extends t.Component{static template="o-spreadsheet-ScorecardChart";static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=t.useRef("chartContainer");get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}get title(){const e=this.env.model.getters.getChartDefinition(this.props.chartId).title.text;return e?this.env.model.getters.dynamicTranslate(e):""}setup(){t.useEffect(this.createChart.bind(this),()=>{const e=this.canvas.el.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}createChart(){const e=this.canvas.el;jO(JO(qN(1/this.env.model.getters.getViewportZoomLevel(),e.getBoundingClientRect()),this.runtime),e)}}const jN=new Set(["containsText","notContainsText","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","beginsWithText","endsWithText","isNotEmpty","isEmpty","isNotEqual","isEqual","customFormula","dateIs","dateIsBefore","dateIsAfter","dateIsOnOrBefore","dateIsOnOrAfter"]),YN=new Set(["containsText","notContainsText","isEqualText","isEmail","isLink","dateIs","dateIsBefore","dateIsOnOrBefore","dateIsAfter","dateIsOnOrAfter","dateIsBetween","dateIsNotBetween","dateIsValid","isEqual","isNotEqual","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","isBoolean","isValueInList","isValueInRange","customFormula"]);new Set(["containsText","notContainsText","isEqualText","dateIs","dateIsBefore","dateIsOnOrBefore","dateIsAfter","dateIsOnOrAfter","dateIsBetween","dateIsNotBetween","isEqual","isNotEqual","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","customFormula","beginsWithText","endsWithText","isNotEmpty","isEmpty"]);const XN=["containsText","notContainsText","isEqualText","isEmpty","isNotEmpty","beginsWithText","endsWithText"],KN=["isEqual","isNotEqual","isGreaterThan","isGreaterOrEqualTo","isLessThan","isLessOrEqualTo","isBetween","isNotBetween","isEmpty","isNotEmpty"],JN=["dateIs","dateIsBefore","dateIsOnOrBefore","dateIsAfter","dateIsOnOrAfter","dateIsBetween","dateIsNotBetween","isEmpty","isNotEmpty"];function QN(e,t,s,o){let i=yk(o,t,s).formattedValues,n=Ik(o,t);$y(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=vk(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=bk(i,n));const r=Ck(o,t,"left"),a=Ck(o,t,"right"),l=e.horizontal?{x:r||a}:{y:r,y1:a},c=[];for(const t in n){const{data:s}=n[t],o=e.dataSets?.[t].trend;if(!o?.display||e.horizontal){c.push(void 0);continue}const i=ck(o,s);c.push(i)}return{dataSetsValues:n,trendDataSetsValues:c,axisFormats:l,labels:i,locale:o.getLocale(),topPadding:Ek(e,o)}}function ek(e,t){switch(t){case"day_of_week":return Li[e-1].toString();case"hour_number":{const t=String(e%12).padStart(2,"0");return Cs(e<12?"%(hour)s AM":"%(hour)s PM",{hour:t})}case"month_number":return ki[e-1].toString();case"iso_week_number":{const t=String(e).padStart(2,"0");return Cs("W%(weekNumber)s",{weekNumber:t})}case"quarter_number":return Cs("Q%(value)s",{value:e});default:return e.toString()}}function tk(e,t,s,o){let i=yk(o,t,s).values,n=Ik(o,t);$y(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift();const r=o.getLocale()||gi;({labels:i,dataSetsValues:n}=function(e,t){const s=Math.max(e.length,...t.map(e=>e.data?.length||0)),o=fe(0,s).filter(s=>{const o=e[s],i=t.map(e=>e.data?.[s]);return o&&mo(o,gi)&&"number"==typeof i[0]});return{labels:o.map(t=>e[t]||""),dataSetsValues:t.map(e=>({...e,data:o.map(t=>"number"==typeof e.data[t]?e.data[t]:null)}))}}(i,n)),({labels:i,dataSetsValues:n}=function(e,t,s,o,i){const n={},r=[],a=[],l=[];for(let c=0;c<e?.length;c++){const h=Eo(xD({granularity:s,type:"date",displayName:"date"},e[c],gi),i);h in n||(r.push(h),n[h]={});const d=Eo(xD({granularity:o,type:"date",displayName:"date"},e[c],gi),i);l.includes(d)||(a.push(d),l.push(d)),d in n[h]||(n[h][d]=0),n[h][d]+=t[c]}return r.sort((e,t)=>e-t),a.sort((e,t)=>t-e),{dataSetsValues:a.map(e=>({data:r.map(t=>n?.[t]?.[e]),label:ek(e,o),hidden:!1})),labels:r.map(e=>ek(e,s))}}(i,n[0].data,e.horizontalGroupBy??"day_of_week",e.verticalGroupBy??"hour_number",r));return{dataSetsValues:n,axisFormats:{y:Ck(o,t,"left")},labels:i,locale:o.getLocale(),topPadding:Ek(e,o)}}function sk(e,t,s,o){const i=QN(e,t.slice(0,2),s,o),n=i.dataSetsValues.filter(e=>!e.hidden),r=[];if(n[0]){const e=n[0].data.map(e=>e>0?e:0);r.push({...n[0],data:e})}if(n[1]){const e=n[1].data.map(e=>e>0?-e:0);r.push({...n[1],data:e})}return{...i,dataSetsValues:r}}function ok(e,t,s,o){const i=function(e,t,s,o){if(function(e,t,s,o){return!e.labelsAsText&&gk(e,t,s,o)}(e,t,s,o)&&function(){if(!window.Chart)return!1;const e="luxon"===new window.Chart._adapters._date({})._id;e||mk||(mk=!0,console.warn("'chartjs-adapter-luxon' time adapter is not installed. Time scale axes are disabled."));return e}())return"time";if(function(e,t,s,o){return!e.labelsAsText&&pk(e,t,s,o)}(e,t,s,o))return"linear";return"category"}(e,t,s,o),n=yk(o,t,s);let r="linear"===i?n.values:n.formattedValues,a=Ik(o,t);const l=$y(s,t[0],e.dataSetsHaveTitle||!1);l&&r.shift(),({labels:r,dataSetsValues:a}=vk(r,a)),"time"===i&&({labels:r,dataSetsValues:a}=function(e,t){if(0===e.length||e.every(e=>!e))return{labels:e,dataSetsValues:t};const s=[...e],o=he(t);for(let e=0;e<s.length;e++)if(!s[e]){s[e]=Ne(s,e);for(const t of o)t.data[e]=void 0}return{labels:s,dataSetsValues:o}}(r,a)),e.aggregated&&({labels:r,dataSetsValues:a}=bk(r,a)),e.cumulative&&(a=wk(a,"asc"));const c={y:Ck(o,t,"left"),y1:Ck(o,t,"right"),x:Sk(o,s,l)},h=[];for(const t in a){const s=e.dataSets?.[t].trend;if(!s?.display){h.push(void 0);continue}const{data:n}=a[t];h.push(hk(s,n,r,i,o.getLocale()))}return{dataSetsValues:a,axisFormats:c,labels:r,locale:o.getLocale(),trendDataSetsValues:h,axisType:i,topPadding:Ek(e,o)}}function ik(e,t,s,o){let i=yk(o,t,s).formattedValues,n=Ik(o,t);$y(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=vk(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=bk(i,n)),({dataSetsValues:n,labels:i}=function(e,t){const s=Math.max(e.length,...t.map(e=>e.data?.length||0)),o=fe(0,s).filter(e=>t.some(t=>"number"==typeof t.data[e]&&t.data[e]>0));return{labels:o.map(t=>e[t]||""),dataSetsValues:t.map(e=>({...e,data:o.map(t=>"number"==typeof e.data[t]&&e.data[t]>0?e.data[t]:null)}))}}(i,n));return{dataSetsValues:n,axisFormats:{y:Ck(o,t,"left")},labels:i,locale:o.getLocale(),topPadding:Ek(e,o)}}function nk(e,t,s,o){let i=yk(o,t,s).formattedValues,n=Ik(o,t);$y(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=vk(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=bk(i,n));return{dataSetsValues:n,axisFormats:{r:Ck(o,t,"left")||Ck(o,t,"right")},labels:i,locale:o.getLocale()}}function rk(e,t,s,o){const i=t.slice(0,1);let n=yk(o,i,s).formattedValues;$y(s,i[0],e.dataSetsHaveTitle||!1)&&n.shift();let r=Ik(o,i);({labels:n,dataSetsValues:r}=bk(n,r));return{dataSetsValues:r,axisFormats:{y:Ck(o,i,"left")||Ck(o,i,"right")},labels:n,locale:o.getLocale(),availableRegions:o.getGeoChartAvailableRegions(),geoFeatureNameToId:o.geoFeatureNameToId,getGeoJsonFeatures:o.getGeoJsonFeatures}}function ak(e,t,s,o){let i=yk(o,t,s).formattedValues,n=Ik(o,t);$y(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),({labels:i,dataSetsValues:n}=vk(i,n)),e.aggregated&&({labels:i,dataSetsValues:n}=bk(i,n)),e.cumulative&&(n=wk(n,"desc"));return{dataSetsValues:n,axisFormats:{x:Ck(o,t,"left")||Ck(o,t,"right")},labels:i,locale:o.getLocale()}}function lk(e,t,s,o){let i=yk(o,t,s).values,n=function(e,t){t=t.filter(t=>!e.isColHidden(t.dataRange.sheetId,t.dataRange.zone.left));const s=t.map(()=>({data:[],label:""})),o=t.map(t=>fk(e,t));if(!o.length)return s;const i=Math.min(...o.map(e=>e.length));let n=[];const r=t.length-1;for(let e=0;e<i;e++)for(let t=0;t<o.length;t++){let i=o[t][e];null==i&&t!==r&&(i=n[t]),i!==n[t]&&(n=n.slice(0,t),n[t]=i),s[t].data.push(i??null)}return s.filter(e=>e.data.some(e=>null!==e))}(o,t);const r=$y(s,t[0],e.dataSetsHaveTitle||!1);return r&&i.shift(),({labels:i,dataSetsValues:n}=function(e,t){const s=[],o=[];for(let t=0;t<e.length;t++)Number(e[t])<=0?o.push(t):Number(e[t])>0&&s.push(t);const i=s.length?s:o;return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}(i,n)),({labels:i,dataSetsValues:n}=function(e,t){const s=Math.max(e.length,...t.map(e=>e.data?.length||0)),o=e=>null==e||""===e,i=fe(0,s).filter(s=>{const i=t.map(e=>e.data?.[s]);if(o(i[0]))return!1;let n=!1;for(const e of i)if(n||=o(e),n&&!o(e))return!1;return e[s]&&!isNaN(Number(e[s]))});return{labels:i.map(t=>e[t]),dataSetsValues:t.map(e=>({...e,data:i.map(t=>e.data[t])}))}}(i,n)),{dataSetsValues:n,axisFormats:{y:Sk(o,s,r)},labels:i,locale:o.getLocale()}}function ck(e,t){const s=[],o=[],i=[];for(let e=0;e<t.length;e++)"number"==typeof t[e]&&(s.push(t[e]),o.push(e+1)),i.push(e+1);const n=dk(e,s,o,fe(.5,i.length+.55,.2));return n.length?n:void 0}function hk(e,t,s,o,i){const n=[],r=[],a=[],l=t.length;if(l<2)return;switch(o){case"category":for(let e=0;e<l;e++)"number"==typeof t[e]&&(n.push(t[e]),r.push(e+1)),a.push(e+1);break;case"linear":for(let e=0;e<t.length;e++){const o=Number(s[e]);isNaN(o)||("number"==typeof t[e]&&(n.push(t[e]),r.push(o)),a.push(o))}break;case"time":for(let e=0;e<t.length;e++){const o=Eo({value:s[e]},i);null!==t[e]&&(n.push(t[e]),r.push(o)),a.push(o)}}const c=Math.min(...a),h=Math.max(...a);if(h===c)return;const d=(h-c)/(5*a.length),u=dk(e,n,r,fe(c,h+d/2,d));return u.length?u:void 0}function dk(e,t,s,o){if(t.length<2||s.length<2||0===o.length)return[];const{normalizedLabels:i,normalizedNewLabels:n}=function(e,t,s){let o=[],i=[];if("logarithmic"===s.type){const s=Math.max(...e.map(Math.abs));o=e.map(e=>e/s),i=t.map(e=>e/s)}else{const s=Math.max(...e),n=Math.min(...e),r=s-n;o=e.map(e=>(e-s)/r),i=t.map(e=>(e-s)/r)}return{normalizedLabels:o,normalizedNewLabels:i}}(s,o,e);try{switch(e.type){case"polynomial":{const s=e.order;if(!s)return o.map(e=>({x:e,y:NaN}));if(1===s)return yl([t],[i],[n],!0)[0].map((e,t)=>({x:o[t],y:e}));const r=ml(t,i,s,!0).flat();return n.map((e,t)=>({x:o[t],y:vl(r,e,s)}))}case"exponential":{const e=[],s=[];for(let o=0;o<t.length;o++)t[o]>0&&(e.push(Math.log(t[o])),s.push(i[o]));return s.length?bl(yl([e],[s],[n],!0))[0].map((e,t)=>({x:o[t],y:e})):o.map(e=>({x:e,y:NaN}))}case"logarithmic":return yl([t],Sl([i]),Sl([n]),!0)[0].map((e,t)=>({x:o[t],y:e}));case"trailingMovingAverage":return function(e,t,s=2){const o=[];for(let e=0;e<s-1;e++)o.push({x:t[e],y:NaN});for(let i=0;i<=e.length-s;i++){let n=0;for(let t=i;t<i+s;t++)n+=e[t];o.push({x:t[i+s-1],y:n/s})}return o}(t,s,e.window);default:return o.map(e=>({x:e,y:NaN}))}}catch(e){return o.map(e=>({x:e,y:NaN}))}}function uk(e,t,s,o){return gk(e,t,s,o)||pk(e,t,s,o)}function gk(e,t,s,o){if(!s||!pk(e,t,s,o))return!1;const i=Sk(o,s,$y(s,t[0],e.dataSetsHaveTitle||!1));return Boolean(i&&MM.test(i))}function pk(e,t,s,o){if(!s)return!1;const i=o.getRangeValues(s);return $y(s,t[0],e.dataSetsHaveTitle||!1)&&i.shift(),!i.some(e=>isNaN(Number(e))&&e)&&!i.every(e=>!e)}let mk=!1;function fk(e,t){if(t.dataRange){const s=t.labelCell?[t.labelCell.zone]:[],o=yt([t.dataRange.zone],s)[0];if(void 0===o)return[];const i=e.getRangeFromZone(t.dataRange.sheetId,o);return e.getRangeValues(i).map(e=>""===e?void 0:e)}return[]}function vk(e,t){const s=fe(0,Math.max(e.length,...t.map(e=>e.data?.length||0))).filter(s=>{const o=e[s],i=t.map(e=>e.data?.[s]);return o||i.some(e=>"number"==typeof e)});return{labels:s.map(t=>e[t]||""),dataSetsValues:t.map(e=>({...e,data:s.map(t=>"number"==typeof e.data[t]?e.data[t]:null)}))}}function bk(e,t){const s=e=>"number"==typeof e?e:0,o=new Set(e),i={};o.forEach(e=>{i[e]=new Array(t.length).fill(0)});for(const o of fe(0,e.length)){const n=e[o];for(const e of fe(0,t.length))i[n][e]+=s(t[e].data[o])}return{labels:Array.from(o),dataSetsValues:t.map((e,t)=>({...e,data:Array.from(o).map(e=>i[e][t])}))}}function Sk(e,t,s){if(!t)return;const{sheetId:o,zone:i}=t,n=Zt(i).map(t=>e.getEvaluatedCell({sheetId:o,...t}).format);return s&&n.shift(),n.find(e=>void 0!==e)}function yk(e,t,s){let o={values:[],formattedValues:[]};if(s){const{left:i}=s.zone;if(s.invalidXc||s.invalidSheetName||e.isColHidden(s.sheetId,i)){if(t[0]){o={formattedValues:fe(0,fk(e,t[0]).length).map(e=>e.toString()),values:o.formattedValues}}}else o={formattedValues:e.getRangeFormattedValues(s),values:e.getRangeValues(s).map(e=>String(e??""))}}else if(1===t.length){const s=fk(e,t[0]).length;for(let e=0;e<s;e++)o.formattedValues.push(""),o.values.push("")}else if(t[0]){o={formattedValues:fe(0,fk(e,t[0]).length).map(e=>e.toString()),values:o.formattedValues}}return o}function Ck(e,t,s){const o=t.filter(e=>"right"===s==!!e.rightYAxis);for(const t of o){const s=e.getRangeFormats(t.dataRange).find(e=>void 0!==e&&!ji(e));if(s)return s}}function Ik(e,t){const s=[];for(const[o,i]of Object.entries(t)){let t=`${Bg.Series} ${parseInt(o)+1}`,n=e.isColHidden(i.dataRange.sheetId,i.dataRange.zone.left);if(i.labelCell){const{sheetId:s,zone:o}=i.labelCell,n=e.getEvaluatedCell({sheetId:s,col:o.left,row:o.top});n&&(t=n.formattedValue)}let r=i.dataRange?fk(e,i):[];r.every(e=>!e||"string"==typeof e&&!Co(e))&&r.filter(e=>"string"==typeof e).length>1?r=r.map(e=>e&&!Co(e)?1:null):r.every(e=>null==e||!mo(e.toString(),gi))&&(n=!0),s.push({data:r,label:t,hidden:n})}return s}function wk(e,t){return e.map(e=>{const s=[];let o=0;const i="asc"===t?Object.keys(e.data):Object.keys(e.data).reverse();for(const t of i)isNaN(parseFloat(e.data[t]))?s[t]=e.data[t]:(o+=parseFloat(e.data[t]),s[t]=o);return{...e,data:s}})}function Ek(e,t){const{title:s,legendPosition:o}=e,i=s&&s.text||"top"===o;return t.isDashboard()&&!i?30:0}function xk(e,t){return{padding:{left:E,right:E,top:Math.max(R,t.topPadding||0),bottom:x}}}function Rk(e,t){const s=e.legendPosition;return{padding:{left:E+("left"===s?70:0),right:E+("right"===s?70:0),top:Math.max(R,t.topPadding||0),bottom:x}}}function Tk(e,t){return{display:"none"!==e.legendPosition,position:"none"!==e.legendPosition?e.legendPosition:void 0}}function Ak(e,t){return{...kk,...Tk(e),...Lk(Uy(e.background),{pointStyle:"rect",lineWidth:3})}}function _k(e,t){const s=e.fillArea,o=s?"rect":"line",i=s?2:3;return{...kk,...Tk(e),...Lk(Uy(e.background),{pointStyle:o,lineWidth:i})}}function Dk(e,t){const{dataSetsValues:s}=t,o=Math.max(0,...s.map(e=>e?.data?.length??0)),i=Xy(new yb(o),s),n=Uy(e.background);return{...Tk(e),labels:{usePointStyle:!0,generateLabels:e=>(e.data.labels?.map((e,t)=>({text:Ky(String(e)),strokeStyle:i[t],fillStyle:i[t],pointStyle:"rect",lineWidth:2,fontColor:n}))||[]).filter(e=>e.text),filter:(e,t)=>!("datasetIndex"in e)||!t.datasets[e.datasetIndex].hidden}}}function Ok(e,t){return{...kk,...Tk(e),...Lk(Uy(e.background),{pointStyle:"circle",strokeStyle:e.background||"#ffffff",lineWidth:8})}}function Fk(e,t){return{...kk,...Tk(e),...Lk(Uy(e.background),{lineWidth:3})}}function Pk(e,t){const s=Uy(e.background),o=e.negativeValuesColor||f,i=e.positiveValuesColor||m,n=e.subTotalValuesColor||v;return{...Tk(e),labels:{usePointStyle:!0,generateLabels:()=>{const t=[{text:Cs("Positive values"),fontColor:s,fillStyle:i,strokeStyle:i,pointStyle:"rect"},{text:Cs("Negative values"),fontColor:s,fillStyle:o,strokeStyle:o,pointStyle:"rect"}];return(e.showSubTotals||e.firstValueAsSubtotal)&&t.push({text:Cs("Subtotals"),fontColor:s,fillStyle:n,strokeStyle:n,pointStyle:"rect"}),t},filter:(e,t)=>!("datasetIndex"in e)||!t.datasets[e.datasetIndex].hidden},onClick:()=>{}}}function Mk(e,t){const s=e.fillArea??!1,o=s?"rect":"line",i=s?2:3;return{...kk,...Tk(e),...Lk(Uy(e.background),{pointStyle:o,lineWidth:i})}}function Nk(e,t){const s=Uy(e.background);return{...Tk(e),labels:{usePointStyle:!0,generateLabels:e=>{const t=e.data.datasets.at(-1);if(!t)return[];return t.groupColors.map(({color:e,label:t})=>({text:Ky(t),fontColor:s,fillStyle:e,strokeStyle:e,pointStyle:"rect"}))}}}}const kk={onHover:e=>{const t=e.native?.target;t&&(t.style.cursor="pointer")},onLeave:e=>{const t=e.native?.target;t&&(t.style.cursor="default")},onClick:(e,t,s)=>{if("click"!==e.type)return;const o=t.datasetIndex;s.legendItems&&void 0!==o&&(s.chart.isDatasetVisible(o)?s.chart.hide(o):s.chart.show(o),e.native.preventDefault(),e.native.stopPropagation())}};function Lk(e,t){return{labels:{color:e,usePointStyle:!0,generateLabels:s=>s.data.datasets.map((o,i)=>Jy(o.xAxisID)?{text:Ky(o.label),fontColor:e,strokeStyle:o.borderColor,hidden:!s.isDatasetVisible(i),pointStyle:"line",datasetIndex:i,lineWidth:3}:{text:Ky(o.label),fontColor:e,strokeStyle:o.borderColor,fillStyle:o.backgroundColor,hidden:!s.isDatasetVisible(i),pointStyle:"line"===o.type?"line":"rect",datasetIndex:i,...t}).filter(e=>e.text),filter:(e,t)=>!("datasetIndex"in e)||!t.datasets[e.datasetIndex].hidden}}}function Vk(e,t){const{axisFormats:s,locale:o}=t;return{type:e.type,horizontal:"horizontal"in e&&e.horizontal,showValues:"showValues"in e&&!!e.showValues,background:()=>e.background,callback:(t,i)=>{const n=function(e,t){if(t.rAxisID)return t.rAxisID;const s="horizontal"in e&&e.horizontal?t.xAxisID:t.yAxisID;return s||"y"}(e,i);return Zy(s,o,e.humanize)(t,n)}}}function zk(e,t){const{locale:s,axisFormats:o}=t;let i=(t,s,o)=>e.background;const n=t.dataSetsValues.flat().map(e=>e?.data.filter(e=>null!=e)).flat()||[];if(n.length){const t=Math.min(...n),s=Math.max(...n),o=YM(e.colorScale??w_("oranges"),t,s);i=(t,s,i)=>{const n=s._dataset.values[i];return void 0===n?e.background:Uy(o(n))}}return{type:"calendar",horizontal:!1,showValues:"showValues"in e&&!!e.showValues,background:i,callback:(e,t,i)=>{const n=t._dataset.values[i];return void 0===n?"":rn({value:n,format:o?.y},s)}}}function Hk(e,t){const{axisFormats:s,locale:o}=t;return{callback:Zy(s,o,e.humanize),showLabels:e.showLabels??E_.showLabels,showValues:e.showValues??E_.showValues,style:{fontSize:e.valuesDesign?.fontSize??E_.valuesDesign.fontSize,align:e.valuesDesign?.align??E_.valuesDesign.align,bold:e.valuesDesign?.bold??E_.valuesDesign.bold,italic:e.valuesDesign?.italic??E_.valuesDesign.italic,textColor:e.valuesDesign?.color??E_.valuesDesign.color}}}function Uk(e,t){const{axisFormats:s,locale:o}=t;return{type:"pyramid",horizontal:!0,showValues:"showValues"in e&&!!e.showValues,background:()=>e.background,callback:(e,t)=>0===(e=Math.abs(Number(e)))?"":Zy(s,o)(e,t.xAxisID||"x")}}function Bk(e,t){const{axisFormats:s,locale:o,dataSetsValues:i}=t,n=i.reduce((e,t)=>(e.push((e.at(-1)||-1)+t.data.length+1),e),[]);return{type:"waterfall",showValues:"showValues"in e&&!!e.showValues,background:()=>e.background,callback:(t,i,r)=>{const a=i._dataset.data[r],l=a[1]-a[0];let c=l>=0?"+":"";return e.showSubTotals&&n.includes(r)&&"+"===c&&(c=""),`${c}${Zy(s,o,e.humanize)(l,i.yAxisID)}`}}}function Gk(e,t){const s=e.title,o=By(e.background);return{display:!!s.text,text:s.text?t.dynamicTranslate(s.text):"",color:s?.color??o,align:"center"===s.align?"center":"right"===s.align?"end":"start",font:{size:e.title.fontSize??T,weight:s.bold?"bold":"normal",style:s.italic?"italic":"normal"},padding:{bottom:"top"===e.legendPosition?0:E}}}const Wk='\n<templates>\n <t t-name="o-spreadsheet-CustomTooltip">\n <div\n class="o-chart-custom-tooltip border rounded px-2 py-1 pe-none mw-100 position-absolute text-nowrap shadow opacity-100">\n <table class="overflow-hidden m-0">\n <thead t-if="title">\n <tr>\n <th class="o-tooltip-title align-baseline border-0 text-truncate" t-esc="title" t-attf-style="max-width: {{ labelsMaxWidth }}"/>\n </tr>\n </thead>\n <tbody>\n <tr t-foreach="tooltipItems" t-as="tooltipItem" t-key="tooltipItem_index">\n <td>\n <span\n class="badge ps-2 py-2 rounded-0 align-middle"\n t-attf-style="background-color: {{ tooltipItem.boxColor }}"\n > </span>\n <small\n t-if="tooltipItem.label"\n class="o-tooltip-label d-inline-block text-truncate align-middle smaller ms-2"\n t-esc="tooltipItem.label"\n t-attf-style="max-width: {{ labelsMaxWidth }}"\n />\n </td>\n <td class="o-tooltip-value ps-2 fw-bolder text-end">\n <small class="smaller d-inline-block text-truncate align-middle" t-attf-style="max-width: {{ valuesMaxWidth }}">\n <t t-esc="tooltipItem.value"/>\n <t t-if="tooltipItem.percentage">\n (\n <t t-esc="tooltipItem.percentage"/>\n %)\n </t>\n </small>\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n </t>\n</templates>\n';let $k;function qk(e,s={}){return function(e,s={}){$k||($k=new t.App(t.Component,{templates:Wk,translateFn:Cs}));const o=$k.getTemplate(e),i=o(s,{}),n=document.createElement("div");return t.blockDom.mount(i,n),n}(e,s).innerHTML}function Zk(e,t){return{enabled:!1,external:iL,callbacks:{title:function(e){return e.some(e=>!Jy(e.dataset.xAxisID))?void 0:""},beforeLabel:e=>e.dataset?.label||e.label,label:function(s){const o=e.horizontal;let i=o?s.parsed.x:s.parsed.y;null==i&&(i=s.parsed);const n=o?s.dataset.xAxisID:s.dataset.yAxisID;return Zy(t.axisFormats,t.locale,e.humanize)(i,n)}}}}function jk(e,t){const{locale:s,axisFormats:o}=t;return{enabled:!1,filter:e=>void 0!==e.dataset.values[e.dataIndex],external:iL,callbacks:{title:e=>"",beforeLabel:e=>`${e.dataset?.label}, ${e.label}`,label:function(e){return rn({value:e.dataset.values[e.dataIndex],format:o?.y},s)}}}}function Yk(e,t){const{axisType:s,locale:o,axisFormats:i}=t,n=i?.x,r={enabled:!1,external:iL,callbacks:{}};return r.callbacks.label="linear"===s?t=>{const s=t.parsed.y;let r=Jy(t.dataset.xAxisID)?"":t.parsed.x;"string"==typeof r&&mo(r,o)&&(r=Eo(r,o));const a=Vi(r,n,o,e.humanize),l=t.dataset.yAxisID||"y",c=Vi(s,i?.[l],o,e.humanize);return a?`(${a}, ${c})`:`${c}`}:function(t){const s=t.parsed.y,n=t.dataset.yAxisID;return Zy(i,o,e.humanize)(s,n)},r.callbacks.beforeLabel=e=>e.dataset?.label||e.label,r.callbacks.title=function(e){return"linear"!==s&&e.some(e=>!Jy(e.dataset.xAxisID))?void 0:""},r}function Xk(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;return{enabled:!1,external:iL,callbacks:{title:function(e){return e[0].dataset.label},beforeLabel:e=>e.label||e.dataset.label,label:function(t){const o=function(e,t){const s=e.filter(e=>"number"==typeof e).reduce((e,t)=>e+t,0);if(!s)return"";const o=e[t]/s*100;return o.toFixed(2)}(t.dataset.data,t.dataIndex),n=t.parsed.y??t.parsed;return`${Vi(n,!i&&n>=1e3?"#,##":i,s,e.humanize)} (${o}%)`}}}}function Kk(e,t){const{dataSetsValues:s,locale:o,axisFormats:i,labels:n}=t,r=i?.y||i?.y1,a=s.map(e=>e.label);return{enabled:!1,external:iL,callbacks:{beforeLabel:function(e){const t=n.length?Math.floor(e.dataIndex/n.length):0;return a[t]},label:function(t){const[s,i]=t.raw,n=i-s;return Vi(n,!r&&Math.abs(n)>1e3?"#,##":r,o,e.humanize)}}}}function Jk(e,t){const s=Zk(e,t);return{...s,callbacks:{...s.callbacks,label:e=>{const t={...e,parsed:{y:e.parsed.y,x:Math.abs(e.parsed.x)}};return(s?.callbacks?.label)(t)}}}}function Qk(e,t){const{locale:s,axisFormats:o}=t;return{enabled:!1,external:iL,callbacks:{beforeLabel:e=>e.dataset?.label||e.label,label:function(t){return Vi(t.parsed.r,o?.r,s,e.humanize)}}}}function eL(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;return{enabled:!1,external:iL,filter:function(e){return void 0!==e.raw.value},callbacks:{beforeLabel:e=>e.raw.feature.properties.name,label:function(t){const o=t.raw.value;return Vi(o,!i&&Math.abs(o)>=1e3?"#,##":i,s,e.humanize)}}}}function tL(e,t){return{enabled:!1,external:iL,position:"funnelTooltipPositioner",callbacks:{title:()=>"",beforeLabel:e=>e.label,label:function(s){const o=s.parsed.x,i=s.dataset.xAxisID;return Zy(t.axisFormats,t.locale,e.humanize)(o,i)}}}}function sL(e,t){const{locale:s,axisFormats:o}=t,i=o?.y||o?.y1;return{enabled:!1,external:iL,filter:function(e){const t=e.raw;return t?.label!==KM},callbacks:{title:()=>"",beforeLabel:e=>e.raw.groups.join(" / "),label:function(t){const o=t.raw.value;return Vi(o,!i&&o>=1e3?"#,##":i,s,e.humanize)}}}}function oL(e,t){const{locale:s,axisFormats:o}=t,i=o?.y;return{enabled:!1,external:iL,filter:(e,t,s)=>t===s.length-1,callbacks:{title:()=>"",beforeLabel:e=>{const t=e.raw._data.children[0];if(!t)return"";const s=[];for(let o=0;o<=e.raw.l;o++)s.push(t[o]);return s.join(" / ")},label:t=>{const o=t.raw.v;return Vi(o,!i&&o>=1e3?"#,##":i,s,e.humanize)}}}}function iL({chart:e,tooltip:t}){if(e.canvas.parentNode.querySelector("div.o-chart-custom-tooltip")?.remove(),0===t.opacity||0===t.dataPoints.length)return;const s=t.body.map((e,s)=>{let o=e.before[0],i=e.lines[0];i||(i=o,o="");const n=t.labelColors[s].backgroundColor;return{label:o,value:i,boxColor:"string"==typeof n?ab(n,1):n}}),o=qk("o-spreadsheet-CustomTooltip",{labelsMaxWidth:Math.floor(.5*e.canvas.clientWidth)+"px",valuesMaxWidth:Math.floor(.25*e.canvas.clientWidth)+"px",title:t.title[0],tooltipItems:s}),i=Object.assign(document.createElement("template"),{innerHTML:o}).content.firstChild;e.canvas.parentNode?.appendChild(i),Object.assign(i.style,{left:nL(e,t,i.clientWidth)+"px",top:Math.floor(t.caretY-i.clientHeight/2)+"px"})}function nL(e,t,s){const o=t.caretX;return o+s>e.chartArea.right?Math.max(0,o-s):o}var rL=Object.freeze({__proto__:null,GHOST_SUNBURST_VALUE:KM,INTERACTIVE_LEGEND_CONFIG:kk,canChartParseLabels:uk,getBarChartData:QN,getBarChartDatasets:JM,getBarChartLegend:Ak,getBarChartScales:kM,getBarChartTooltip:Zk,getCalendarChartData:tk,getCalendarChartDatasetAndLabels:QM,getCalendarChartLayout:Rk,getCalendarChartScales:LM,getCalendarChartShowValues:zk,getCalendarChartTooltip:jk,getCalendarColorScale:VM,getChartColorsGenerator:vN,getChartLabelFormat:Sk,getChartLayout:xk,getChartShowValues:Vk,getChartTitle:Gk,getComboChartDatasets:iN,getComboChartLegend:Fk,getData:fk,getFunnelChartData:ak,getFunnelChartDatasets:aN,getFunnelChartScales:$M,getFunnelChartTooltip:tL,getFunnelLabelColors:lN,getGeoChartData:rk,getGeoChartDatasets:rN,getGeoChartScales:WM,getGeoChartTooltip:eL,getHierarchalChartData:lk,getLineChartData:ok,getLineChartDatasets:tN,getLineChartLegend:_k,getLineChartScales:zM,getLineChartTooltip:Yk,getPieChartData:ik,getPieChartDatasets:oN,getPieChartLegend:Dk,getPieChartTooltip:Xk,getPyramidChartData:sk,getPyramidChartScales:BM,getPyramidChartShowValues:Uk,getPyramidChartTooltip:Jk,getRadarChartData:nk,getRadarChartDatasets:nN,getRadarChartLegend:Mk,getRadarChartScales:GM,getRadarChartTooltip:Qk,getRuntimeColorScale:YM,getScatterChartDatasets:sN,getScatterChartLegend:Ok,getScatterChartScales:HM,getSunburstChartDatasets:cN,getSunburstChartLegend:Nk,getSunburstChartTooltip:sL,getSunburstShowValues:Hk,getTopPaddingForDashboard:Ek,getTreeMapChartDatasets:gN,getTreeMapChartTooltip:oL,getTrendDatasetForBarChart:ck,getTrendDatasetForLineChart:hk,getWaterfallChartLegend:Pk,getWaterfallChartScales:UM,getWaterfallChartShowValues:Bk,getWaterfallChartTooltip:Kk,getWaterfallDatasetAndLabels:eN,makeDatasetsCumulative:wk});class aL extends zO{dataSets;labelRange;background;legendPosition;stacked;aggregated;type="bar";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.horizontal=e.horizontal,this.showValues=e.showValues,this.zoomable=e.zoomable}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"bar",labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,showValues:e.showValues,horizontal:e.horizontal,zoomable:e.zoomable,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new aL(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new aL(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"bar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated,axesDesign:this.axesDesign,horizontal:this.horizontal,showValues:this.showValues,zoomable:this.horizontal?void 0:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,$y(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:IP(this.background||c),fontColor:IP(Uy(this.background)),dataSets:e,labelRange:t,verticalAxis:qy(s)}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new aL(i,this.sheetId,this.getters)}}function lL(e,t){const s=e.getDefinition(),o=QN(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:JM(s,o)},options:{...eF,indexAxis:e.horizontal?"y":"x",layout:xk(0,o),scales:kM(s,o),plugins:{title:Gk(s,t),legend:Ak(s),tooltip:Zk(s,o),chartShowValuesPlugin:Vk(s,o)}}},background:e.background||c}}function cL(e){return e.dataRange&&!mr.test(e.dataRange)?"InvalidGaugeDataRange":"Success"}function hL(e,t){return t(t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):"Success",t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):"Success")}function dL(e,t){if(""===e)switch(t){case"rangeMin":return"EmptyGaugeRangeMin";case"rangeMax":return"EmptyGaugeRangeMax"}return"Success"}function uL(e,t){if(e.startsWith("="))return"Success";if(isNaN(e))switch(t){case"rangeMin":return"GaugeRangeMinNaN";case"rangeMax":return"GaugeRangeMaxNaN";case"lowerInflectionPointValue":return"GaugeLowerInflectionPointNaN";case"upperInflectionPointValue":return"GaugeUpperInflectionPointNaN"}return"Success"}class gL extends zO{dataRange;sectionRule;background;type="gauge";constructor(e,t,s){super(e,t,s),this.dataRange=Jb(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,cL,e.chainValidations(hL(dL,e.batchValidations),hL(uL,e.batchValidations)),e.chainValidations((s=uL,(0,e.batchValidations)(e=>e.sectionRule?s(e.sectionRule.lowerInflectionPoint.value,"lowerInflectionPointValue"):"Success",e=>e.sectionRule?s(e.sectionRule.upperInflectionPoint.value,"upperInflectionPointValue"):"Success"))));var s}static transformDefinition(e,t,s){let o;if(t.dataRange){const i=Ty(e,t.dataRange,s);i!==ws.InvalidReference&&(o=i)}return{...t,dataRange:o}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||{text:""},type:"gauge",dataRange:e.range?.[0]?.dataRange,sectionRule:{colors:{lowerColor:"#EA6175",middleColor:"#FFD86D",upperColor:"#43C5B1"},rangeMin:"0",rangeMax:"100",lowerInflectionPoint:{type:"percentage",value:"15",operator:"<="},upperInflectionPoint:{type:"percentage",value:"40",operator:"<="}},humanize:e.humanize}}duplicateInDuplicatedSheet(e){const t=My(this.sheetId,e,this.dataRange),s=vL(this.sectionRule,t=>this.getters.copyFormulaStringForSheet(this.sheetId,e,t,"moveReference")),o=this.getDefinitionWithSpecificRanges(t,s,e);return new gL(o,e,this.getters)}copyInSheetId(e){const t=vL(this.sectionRule,t=>this.getters.copyFormulaStringForSheet(this.sheetId,e,t,"keepSameReference")),s=this.getDefinitionWithSpecificRanges(this.dataRange,t,e);return new gL(s,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.dataRange,this.sectionRule)}getDefinitionWithSpecificRanges(e,t,s){return{background:this.background,sectionRule:t,title:this.title,type:"gauge",dataRange:e?this.getters.getRangeString(e,s||this.sheetId):void 0,humanize:this.humanize}}getDefinitionForExcel(){}getContextCreation(){return{...this,range:this.dataRange?[{dataRange:this.getters.getRangeString(this.dataRange,this.sheetId)}]:void 0}}updateRanges(e,t,s){const o=Ny(this.dataRange,e),i=vL(this.sectionRule,o=>Ry(this.sheetId,o,{applyChange:e,sheetId:t,sheetName:s})),n=this.getDefinitionWithSpecificRanges(o,i);return new gL(n,this.sheetId,this.getters)}}function pL(e,t){const s=t.getLocale(),o=e.sectionRule.colors;let i,n,r;const a=e.dataRange;if(void 0!==a){const e=t.getEvaluatedCell({sheetId:a.sheetId,col:a.zone.left,row:a.zone.top});e.type===Xd.number&&(i=e.value,n=e.formattedValue,r=e.format)}let l=fL(e.sheetId,e.sectionRule.rangeMin,t),c=fL(e.sheetId,e.sectionRule.rangeMax,t);if(void 0===l||void 0===c)return function(e,t){return{background:t.getStyleOfSingleCellChart(e.background,e.dataRange).background,title:e.title??{text:""},minValue:{value:0,label:""},maxValue:{value:100,label:""},gaugeValue:{value:0,label:ws.GenericError},inflectionValues:[],colors:[]}}(e,t);c<l&&([l,c]=[c,l]);const h=e.sectionRule.lowerInflectionPoint,d=e.sectionRule.upperInflectionPoint,u=mL(e.sheetId,e.sectionRule.lowerInflectionPoint,l,c,t),g=mL(e.sheetId,e.sectionRule.upperInflectionPoint,l,c,t),p=[],m=[];return void 0!==u&&(p.push({value:u,label:Vi(u,r,s,e.humanize),operator:h.operator}),m.push(o.lowerColor)),void 0!==g&&g!==u&&(p.push({value:g,label:Vi(g,r,s,e.humanize),operator:d.operator}),m.push(o.middleColor)),void 0!==g&&void 0!==u&&u>g&&(p.reverse(),m.reverse()),m.push(o.upperColor),{background:t.getStyleOfSingleCellChart(e.background,a).background,title:{...e.title,text:e.title.text?t.dynamicTranslate(e.title.text):""},minValue:{value:l,label:Vi(l,r,s,e.humanize)},maxValue:{value:c,label:Vi(c,r,s,e.humanize)},gaugeValue:void 0!==i&&n?{value:i,label:e.humanize?rn({value:i,format:r},s):n}:void 0,inflectionValues:p,colors:m}}function mL(e,t,s,o,i){const n=fL(e,t.value,i);if(void 0===n)return;return me("number"===t.type?n:s+(o-s)*n/100,s,o)}function fL(e,t,s){const o=s.evaluateFormula(e,t);return _n(o)?void 0:xo(Tn(o),s.getLocale())}function vL(e,t){return{...e,rangeMin:t(e.rangeMin),rangeMax:t(e.rangeMax),lowerInflectionPoint:{...e.lowerInflectionPoint,value:t(e.lowerInflectionPoint.value)},upperInflectionPoint:{...e.upperInflectionPoint,value:t(e.upperInflectionPoint.value)}}}class bL extends zO{dataSets;labelRange;background;legendPosition;labelsAsText;stacked;aggregated;type="line";dataSetsHaveTitle;cumulative;dataSetDesign;axesDesign;fillArea;showValues;hideDataMarkers;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=ky(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.cumulative=e.cumulative,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.fillArea=e.fillArea,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers,this.zoomable=e.zoomable}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static transformDefinition(e,t,s){return Hy(e,t,s)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"line",labelRange:e.auxiliaryRange||void 0,stacked:e.stacked??!1,aggregated:e.aggregated??!1,cumulative:e.cumulative??!1,axesDesign:e.axesDesign,fillArea:e.fillArea,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"line",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,stacked:this.stacked,aggregated:this.aggregated,cumulative:this.cumulative,axesDesign:this.axesDesign,fillArea:this.fillArea,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,zoomable:this.zoomable,humanize:this.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new bL(i,this.sheetId,this.getters)}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,$y(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:IP(this.background||c),fontColor:IP(Uy(this.background)),dataSets:e,labelRange:t,verticalAxis:qy(s)}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new bL(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new bL(t,e,this.getters)}}function SL(e,t){const s=e.getDefinition(),o=ok(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"line",data:{labels:o.labels,datasets:tN(s,o)},options:{...eF,layout:xk(0,o),scales:zM(s,o),plugins:{title:Gk(s,t),legend:_k(s),tooltip:Yk(s,o),chartShowValuesPlugin:Vk(s,o)}}},background:e.background||c}}class yL extends zO{dataSets;labelRange;background;legendPosition;type="pie";aggregated;dataSetsHaveTitle;isDoughnut;showValues;pieHolePercentage;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.isDoughnut=e.isDoughnut,this.showValues=e.showValues,this.pieHolePercentage=e.pieHolePercentage}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"pie",labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,isDoughnut:e.isDoughnut,pieHolePercentage:e.pieHolePercentage,showValues:e.showValues,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{...this,range:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)})),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,s){return{type:"pie",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,isDoughnut:this.isDoughnut,showValues:this.showValues,pieHolePercentage:this.pieHolePercentage,humanize:this.humanize}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new yL(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new yL(t,e,this.getters)}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,$y(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:IP(this.background||c),fontColor:IP(Uy(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new yL(i,this.sheetId,this.getters)}}function CL(e,t){const s=e.getDefinition(),o=ik(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:e.isDoughnut?"doughnut":"pie",data:{labels:o.labels,datasets:oN(s,o)},options:{...eF,cutout:e.isDoughnut&&void 0!==s.pieHolePercentage?s.pieHolePercentage+"%":void 0,layout:xk(0,o),plugins:{title:Gk(s,t),legend:Dk(s,o),tooltip:Xk(s,o),chartShowValuesPlugin:Vk(s,o)}}},background:e.background||c}}class IL extends zO{dataSets;labelRange;background;verticalAxisPosition;legendPosition;aggregated;type="waterfall";dataSetsHaveTitle;showSubTotals;firstValueAsSubtotal;showConnectorLines;positiveValuesColor;negativeValuesColor;subTotalValuesColor;dataSetDesign;axesDesign;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showSubTotals=e.showSubTotals,this.showConnectorLines=e.showConnectorLines,this.positiveValuesColor=e.positiveValuesColor,this.negativeValuesColor=e.negativeValuesColor,this.subTotalValuesColor=e.subTotalValuesColor,this.firstValueAsSubtotal=e.firstValueAsSubtotal,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.zoomable=e.zoomable}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"waterfall",verticalAxisPosition:"left",labelRange:e.auxiliaryRange||void 0,showSubTotals:e.showSubTotals??!1,showConnectorLines:e.showConnectorLines??!0,firstValueAsSubtotal:e.firstValueAsSubtotal??!1,axesDesign:e.axesDesign,showValues:e.showValues,zoomable:e.zoomable??!1,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new IL(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new IL(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"waterfall",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,showSubTotals:this.showSubTotals,showConnectorLines:this.showConnectorLines,positiveValuesColor:this.positiveValuesColor,negativeValuesColor:this.negativeValuesColor,subTotalValuesColor:this.subTotalValuesColor,firstValueAsSubtotal:this.firstValueAsSubtotal,axesDesign:this.axesDesign,showValues:this.showValues,zoomable:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new IL(i,this.sheetId,this.getters)}}function wL(e,t){const s=e.getDefinition(),o=QN(s,e.dataSets,e.labelRange,t),{labels:i,datasets:n}=eN(s,o);return{chartJsConfig:{type:"bar",data:{labels:i,datasets:n},options:{...eF,layout:xk(0,o),scales:UM(s,o),plugins:{title:Gk(s,t),legend:Pk(s),tooltip:Kk(s,o),chartShowValuesPlugin:Bk(s,o),waterfallLinesPlugin:{showConnectorLines:s.showConnectorLines}}}},background:e.background||c}}var EL=Object.freeze({__proto__:null,AbstractChart:zO,BarChart:aL,CHART_AXIS_CHOICES:Yy,CHART_COMMON_OPTIONS:eF,GaugeChart:gL,LineChart:bL,MOVING_AVERAGE_TREND_LINE_XAXIS_ID:Dy,PieChart:yL,SPREADSHEET_TO_EXCEL_TRENDLINE_TYPE_MAPPING:Oy,ScorecardChart:ZO,TREND_LINE_XAXIS_ID:_y,WaterfallChart:IL,adaptChartRange:Ny,chartFactory:bR,chartFontColor:Uy,chartMutedFontColor:By,chartRuntimeFactory:SR,chartToImageFile:sF,chartToImageUrl:tF,checkDataset:Gy,checkLabelRange:Wy,createBarChartRuntime:lL,createDataSets:ky,createGaugeChartRuntime:pL,createLineChartRuntime:SL,createPieChartRuntime:CL,createScorecardChartRuntime:YO,createWaterfallChartRuntime:wL,drawScoreChart:jO,duplicateDataSetsInDuplicatedSheet:Py,duplicateLabelRangeInDuplicatedSheet:My,formatChartDatasetValue:Zy,formatTickValue:jy,getChartPositionAtCenterOfViewport:function(e,t){const{x:s,y:o}=e.getMainViewportCoordinates(),{scrollX:i,scrollY:n}=e.getActiveSheetScrollInfo(),{width:r,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:s+i+Math.max(0,(r-t.width)/2),y:o+n+Math.max(0,(a-t.height)/2)}},getDefinedAxis:qy,getPieColors:Xy,isTrendLineAxis:Jy,shouldRemoveFirstLabel:$y,toExcelDataset:Vy,toExcelLabelRange:zy,transformChartDefinitionWithDataSetsWithZone:Hy,transformDefinition:CR,truncateLabel:Ky,updateChartRangesWithDataSets:Fy,validateChartDefinition:yR});function xL(e,t){if(!t.model.getters.getChartIdFromFigureId(e))return[];return Sv([{id:"edit",name:Cs("Edit"),execute:()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e}),t.openSidePanel("ChartPanel")},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall},RL(e,t),TL(e,t),AL(e,t),_L(e,t),DL(e,t)]).filter(e=>!t.model.getters.isReadonly()||e.isReadonlyAllowed)}function RL(e,t,s){return{id:"copy",name:Cs("Copy"),description:"Ctrl+C",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e}),t.model.dispatch("COPY");const o=await t.model.getters.getClipboardTextAndImageContent();await t.clipboard.write(o),s&&t.notifyUser({sticky:!1,type:"success",text:s})},icon:"o-spreadsheet-Icon.CLIPBOARD"}}function TL(e,t){return{id:"cut",name:Cs("Cut"),description:"Ctrl+X",execute:async()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e}),t.model.dispatch("CUT"),await t.clipboard.write(await t.model.getters.getClipboardTextAndImageContent())},icon:"o-spreadsheet-Icon.CUT"}}function AL(e,t){return{id:"copy_as_image",name:Cs("Copy as image"),icon:"o-spreadsheet-Icon.COPY_AS_IMAGE",execute:async()=>{const s=t.model.getters.getFigureSheetId(e),o=t.model.getters.getFigure(s,e),i=t.model.getters.getChartIdFromFigureId(e);if(!i)return;const n=t.model.getters.getChartType(i),r=t.model.getters.getChartRuntime(i),a=await sF(r,o,n);if(!a)return;const l=await new Promise(e=>{const t=new FileReader;t.addEventListener("loadend",s=>{const o=t.result;e(o)}),t.readAsArrayBuffer(a)}),c=`<img src="data:image/png;base64,${new Uint8Array(l).toBase64()}" />`;t.clipboard.write({"text/html":c,"image/png":a}),t.notifyUser({sticky:!1,type:"success",text:Cs("Chart copied to clipboard")})},isReadonlyAllowed:!0}}function _L(e,t){return{id:"download",name:Cs("Download"),icon:"o-spreadsheet-Icon.DOWNLOAD",execute:async()=>{const s=t.model.getters.getFigureSheetId(e),o=t.model.getters.getFigure(s,e),i=t.model.getters.getChartIdFromFigureId(e);if(!i)return;const n=t.model.getters.getChartType(i),r=t.model.getters.getChartRuntime(i),a=await tF(r,o,n);a&&UN(a,"chart")},isReadonlyAllowed:!0}}function DL(e,t){return{id:"delete",name:Cs("Delete"),execute:()=>{t.model.dispatch("DELETE_FIGURE",{sheetId:t.model.getters.getActiveSheetId(),figureId:e})},icon:"o-spreadsheet-Icon.TRASH"}}const OL=[_y,Dy],FL=["x",...OL];class PL extends Lv{mutators=["resetAxisLimits","updateAxisLimits","updateTrendLineConfiguration","clearAxisLimits"];originalAxisLimits={};currentAxesLimits={};idConversion={};handle(e){switch(e.type){case"DELETE_FIGURE":if(e.figureId&&this.idConversion[e.figureId])for(const t of this.idConversion[e.figureId])delete this.originalAxisLimits[t],delete this.currentAxesLimits[t];break;case"UPDATE_CHART":const t=`${e.definition.type}-${e.figureId}`;this.idConversion[e.figureId]||(this.idConversion[e.figureId]=new Set),this.idConversion[e.figureId].add(t),"zoomable"in e.definition&&e.definition.zoomable||this.clearAxisLimits(t)}}clearAxisLimits(e){return delete this.originalAxisLimits[e],delete this.currentAxesLimits[e],"noStateChange"}resetAxisLimits(e,t){for(const s of FL)t[s]?this.originalAxisLimits[e]={...this.originalAxisLimits[e],[s]:{...t[s]}}:this.originalAxisLimits[e]?.[s]&&delete this.originalAxisLimits[e][s];return"noStateChange"}updateAxisLimits(e,t){let{min:s,max:o}=t;return s>o&&([s,o]=[o,s]),this.currentAxesLimits[e]={x:{min:s,max:o}},"noStateChange"}updateTrendLineConfiguration(e){if(!this.originalAxisLimits[e]?.x||!this.currentAxesLimits[e]?.x)return"noStateChange";const t=this.originalAxisLimits[e].x;for(const s of OL){if(!this.originalAxisLimits[e][s])continue;const o=t.max-t.min,i=this.originalAxisLimits[e][s],n=(i.max-i.min)/o,r=i.min-t.min*n,a=this.currentAxesLimits[e].x.min,l=this.currentAxesLimits[e].x.max;this.currentAxesLimits[e][s]={min:a*n+r,max:l*n+r}}return"noStateChange"}}class ML extends xN{static template="o-spreadsheet-ZoomableChartJsComponent";store;masterChartCanvas=t.useRef("masterChartCanvas");masterChart;mode;hasLinearScale;isBarChart;chartId="";datasetBoundaries={min:0,max:0};removeEventListeners=()=>{};isMasterChartAllowed=!1;setup(){this.store=Tv(PL),super.setup()}unmount(){super.unmount(),this.masterChart?.destroy(),this.removeEventListeners()}get containerStyle(){return`\n height:${this.sliceable?"calc(100% - 60px)":"100%"};\n `}get masterChartContainerStyle(){const e=this.env.model.getters.getChartRuntime(this.props.chartId);return e&&!e.chartJsConfig.data.datasets.some(e=>e.data.length>1)?"opacity: 0.3;":""}get sliceable(){if(this.props.isFullScreen)return!0;const e=this.env.model.getters.getChartDefinition(this.props.chartId);return("zoomable"in e&&e.zoomable)??!1}get axisOffset(){return!this.hasLinearScale&&this.isBarChart?.5:0}getMasterChartConfiguration(e){const t=e;return{...t,options:{...t.options,plugins:{...t.options.plugins,zoomWindowPlugin:{getLowerBound:()=>this.lowerBound,getUpperBound:()=>this.upperBound}}}}}getDetailChartConfiguration(e){if(!this.sliceable)return e;let t=e.options.scales.x;const s=this.store.currentAxesLimits[this.chartId]?.x;return s&&(t={...t,...this.getStoredBoundaries()}),{...e,options:{...e.options,scales:{...e.options.scales,x:t},layout:{...e.options.layout,padding:{...e.options.layout?.padding,bottom:5}}}}}getAxisLimitsFromDataset(e){const t=e.data.datasets.map(e=>e.data).flat().map((e,t)=>"object"==typeof e&&null!==e?e.x:t);return{min:Math.min(...t),max:Math.max(...t)}}setMasterChartCursor(e){const t=this.masterChartCanvas?.el;if(e&&!e.chartJsConfig.data.datasets.some(e=>e.data.length>1))return t.style.cursor="not-allowed",void(this.isMasterChartAllowed=!1);t.style.cursor="default",this.isMasterChartAllowed=!0}createChart(e){if(!globalThis.Chart)throw new Error("Chart.js library is not loaded");const t=e.chartJsConfig;if(this.isBarChart="bar"===t.type,this.chartId=`${t.type}-${this.props.chartId}`,this.datasetBoundaries=this.getAxisLimitsFromDataset(t),this.sliceable){const s=this.getDetailChartConfiguration(t);e.chartJsConfig=s}if(super.createChart(e),this.hasLinearScale="linear"===this.chart?.scales?.x?.type,!this.sliceable||!("masterChartConfig"in e))return void(this.isMasterChartAllowed=!1);this.masterChart?.destroy();const s=(this.masterChartCanvas?.el).getContext("2d");this.setMasterChartCursor(e),this.masterChart=new globalThis.Chart(s,this.getMasterChartConfiguration(e.masterChartConfig)),this.resetAxesLimits(),this.chart?.options&&(this.chart.options.animation=!1)}updateChartJs(e){if(!globalThis.Chart)throw new Error("Chart.js library is not loaded");const t=e.chartJsConfig,{min:s,max:o}=this.getAxisLimitsFromDataset(t);if(this.datasetBoundaries.min===s&&this.datasetBoundaries.max===o||(this.store.clearAxisLimits(this.chartId),this.datasetBoundaries={min:s,max:o}),this.isBarChart="bar"===t?.type,this.chartId=`${t.type}-${this.props.chartId}`,this.sliceable){const s=this.getDetailChartConfiguration(t);e.chartJsConfig=s}if(super.updateChartJs(e),this.hasLinearScale="linear"===this.chart?.scales?.x?.type,this.sliceable&&"masterChartConfig"in e){const t=this.getMasterChartConfiguration(e.masterChartConfig);if(this.masterChart)this.masterChart.data=t.data,this.masterChart.config.options=t.options,this.masterChart.update();else{const e=this.masterChartCanvas.el.getContext("2d");this.masterChart=new globalThis.Chart(e,t)}this.setMasterChartCursor(e)}else this.masterChart=void 0,this.isMasterChartAllowed=!1;this.resetAxesLimits(),this.chart?.options&&(this.chart.options.animation=!1)}resetAxesLimits(){if(!this.chart)return;const e=this.store.originalAxisLimits[this.chartId]?.x;if(!e){let e=this.masterChart?this.masterChart.scales:this.chart.scales;return!this.hasLinearScale&&e.x&&(e={...e,x:this.adjustBoundaries(e.x)}),void this.store.resetAxisLimits(this.chartId,e)}this.updateTrendingLineAxes(),this.chart.update(),this.masterChart&&this.masterChart.update()}updateTrendingLineAxes(){this.store.updateTrendLineConfiguration(this.chartId);const e=this.store.currentAxesLimits[this.chartId];for(const t of[_y,Dy])this.chart?.config?.options?.scales?.[t]&&e?.[t]&&(this.chart.config.options.scales[t].min=e[t].min,this.chart.config.options.scales[t].max=e[t].max)}get upperBound(){return this.computePosition(this.store.currentAxesLimits[this.chartId]?.x?.max)}get lowerBound(){return this.computePosition(this.store.currentAxesLimits[this.chartId]?.x?.min)}computePosition(e){if(void 0===e||!this.masterChart?.scales?.x)return;const t=this.masterChart.scales.x;if(this.hasLinearScale)return t.getPixelForValue(e);if(!this.masterChart.chartArea)return;const{left:s,right:o}=this.masterChart.chartArea,{min:i,max:n}=t,r=this.axisOffset;return s+(o-s)*(r+e-i)/(2*r+n-i)}computeCoordinate(e){if(!this.masterChart)return;const t=this.masterChart.scales.x;if(this.hasLinearScale){const s=t.getValueForPixel(e);if(void 0===s)return;return Math.round(100*s)/100}const{left:s,right:o}=this.masterChart.chartArea,i=this.axisOffset;return t.min-i+(t.max+2*i-t.min)*(e-s)/(o-s)}getStoredBoundaries(){let{min:e,max:t}=this.store.currentAxesLimits[this.chartId].x;return this.hasLinearScale||(e=Math.ceil(e),t=Math.floor(t)),{min:e,max:t}}adjustBoundaries({min:e,max:t}){return this.hasLinearScale||(e=Math.ceil(e)-this.axisOffset,t=Math.floor(t)+this.axisOffset),{min:e,max:t}}updateAxisLimits(e,t){if(e===t)return;if(!this.chart)return;this.store.updateAxisLimits(this.chartId,{min:e,max:t});const{min:s,max:o}=this.getStoredBoundaries();(o>s||this.isBarChart&&o===s)&&(this.chart.config.options.scales.x.min=s,this.chart.config.options.scales.x.max=o,this.updateTrendingLineAxes(),this.chart.update()),this.masterChart?.update()}onMasterChartPointerDown(e){this.removeEventListeners();const t=$N(this.env,e,this.masterChartCanvas.el?.getBoundingClientRect()),s=t.offsetX;if(!this.masterChart?.chartArea||!this.chart?.scales?.x)return;const{left:o,right:i,top:n,bottom:r}=this.masterChart.chartArea,a=this.upperBound??i,l=this.lowerBound??o;if(s<o-5||s>i+5||t.offsetY<n||t.offsetY>r)return;let c,h,d;e.preventDefault(),e.stopPropagation();const u=s;if((l!==o||a!==i)&&s>l+5&&s<a-5){c=t.offsetX-l,this.mode="moveInMaster";const e=this.store.currentAxesLimits[this.chartId]?.x;h=(e?.max??this.chart.scales.x.max)-(e?.min??this.chart.scales.x.min)}else this.mode="selectInMaster",c=Math.abs(s-l)<5?a:Math.abs(s-a)<5?l:me(s,o,i),d=this.computeCoordinate(c);const g=this.store.originalAxisLimits[this.chartId].x.min,p=this.store.originalAxisLimits[this.chartId].x.max,m=e=>{if("moveInMaster"===this.mode){let t=this.computeCoordinate(e-c);return t<g?t=g:t>p-h&&(t=p-h),{min:t,max:t+h}}if("selectInMaster"===this.mode){const t=me(e,o,i);if(Math.abs(c-t)>5){const e=this.computeCoordinate(t);return void 0===d||void 0===e?{}:{min:Math.min(d,e),max:Math.max(d,e)}}}return{}},f=e=>{const t=$N(this.env,e,this.masterChartCanvas.el?.getBoundingClientRect()).offsetX;if(Math.abs(t-u)<5)return;const{min:s,max:o}=m(t);void 0!==s&&void 0!==o&&this.updateAxisLimits(s,o)},v=e=>{this.removeEventListeners();let{min:t,max:s}=this.chart.scales.x;this.hasLinearScale||("moveInMaster"===this.mode?(t=Math.round(t)-this.axisOffset,s=t+h):({min:t,max:s}=this.adjustBoundaries({min:t,max:s}))),this.updateAxisLimits(t,s),this.mode=void 0};this.removeEventListeners=()=>{window.removeEventListener("pointermove",f,!0),window.removeEventListener("pointerup",v,!0)},window.addEventListener("pointermove",f,!0),window.addEventListener("pointerup",v,!0)}onMasterChartPointerMove(e){const t=e.target,{offsetX:s,offsetY:o}=$N(this.env,e,t?.getBoundingClientRect());if(t&&this.isMasterChartAllowed&&void 0===this.mode){if(!this.masterChart?.chartArea)return void(t.style.cursor="default");const{left:e,right:i,top:n,bottom:r}=this.masterChart.chartArea,a=this.lowerBound??e,l=this.upperBound??i;o<n||o>r?t.style.cursor="default":Math.abs(a-s)<5||Math.abs(l-s)<5?t.style.cursor="ew-resize":t.style.cursor=a<s&&s<l&&(a!==e||l!==i)?"grab":"crosshair"}}onMasterChartMouseLeave(e){const t=e.target;t&&this.isMasterChartAllowed&&(t.style.cursor="default")}onMasterChartDoubleClick(e){this.mode=void 0;const t=$N(this.env,e,this.masterChartCanvas.el?.getBoundingClientRect()),s=t.offsetX;if(!this.masterChart?.chartArea||!this.chart?.scales.x)return;const{left:o,right:i,top:n,bottom:r}=this.masterChart.chartArea;let a=this.upperBound??i,l=this.lowerBound??o;if(a<l&&([a,l]=[l,a]),s<o-5||s>i+5||t.offsetY<n||t.offsetY>r)return;e.preventDefault(),e.stopPropagation();let{min:c,max:h}=this.store.currentAxesLimits[this.chartId]?.x??this.chart.scales.x;const d=this.store.originalAxisLimits[this.chartId].x;if(d){if(Math.abs(s-l)<5)c=d.min;else if(Math.abs(s-a)<5)h=d.max;else{if(!(l<s&&s<a))return;c=d.min,h=d.max}this.updateAxisLimits(c,h)}}}const NL=new Jg;NL.add("animatedBackgroundColorChange",{id:"animatedBackgroundColorChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>e?.style?.fillColor!==t?.style?.fillColor,updateAnimation:function(e,t,s,o){const i=xb([{value:0,color:s.style.fillColor||"#ffffff"},{value:1,color:o.style.fillColor||"#ffffff"}]);t.style.fillColor=i(kL[this.easingFn](e))}}),NL.add("animatedTextColorChange",{id:"animatedTextColorChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>e?.style?.textColor!==t?.style?.textColor,updateAnimation:function(e,t,s,o){const i=xb([{value:0,color:s.style.textColor||"#000000"},{value:1,color:o.style.textColor||"#000000"}]);t.style.textColor=i(kL[this.easingFn](e))}}),NL.add("animatedDataBar",{id:"animatedDataBar",easingFn:"easeOutCubic",hasAnimation:(e,t)=>e?.dataBarFill?.percentage!==t?.dataBarFill?.percentage,updateAnimation:function(e,t,s,o){const i=s?.dataBarFill?.percentage||0,n=i+((o?.dataBarFill?.percentage||0)-i)*kL[this.easingFn](e);t.dataBarFill={color:o.dataBarFill?.color||s.dataBarFill?.color||"#ffffff",percentage:n}}}),NL.add("textFadeIn",{id:"textFadeIn",easingFn:"easeInCubic",hasAnimation:(e,t)=>{const s=e?.content?.textLines?.join("\n"),o=t?.content?.textLines?.join("\n");return Boolean(!s&&o)},updateAnimation:function(e,t,s,o){t.textOpacity=kL[this.easingFn](e)}}),NL.add("textFadeOut",{id:"textFadeOut",easingFn:"easeOutCubic",hasAnimation:(e,t)=>{const s=e?.content?.textLines?.join("\n"),o=t?.content?.textLines?.join("\n");return Boolean(s&&!o)},updateAnimation:function(e,t,s,o){const i=1-kL[this.easingFn](e),n={...s.style};delete n.fillColor,t.textOpacity=i,t.content=s.content,t.clipRect=s.clipRect,Object.assign(t.style,n)}}),NL.add("iconFadeIn",{id:"iconFadeIn",easingFn:"easeInCubic",hasAnimation:(e,t)=>Boolean(!e?.icons?.left&&t?.icons?.left||!e?.icons?.right&&t?.icons?.right||!e?.icons?.center&&t?.icons?.center),updateAnimation:function(e,t,s,o){const i=kL[this.easingFn](e);t.icons.left&&o.icons.left&&!s.icons.left&&(t.icons.left.opacity=i),t.icons.right&&o.icons.right&&!s.icons.right&&(t.icons.right.opacity=i),t.icons.center&&o.icons.center&&!s.icons.center&&(t.icons.center.opacity=i)}}),NL.add("iconFadeOut",{id:"iconFadeOut",easingFn:"easeOutCubic",hasAnimation:(e,t)=>Boolean(e?.icons?.left&&!t?.icons?.left||e?.icons?.right&&!t?.icons?.right||e?.icons?.center&&!t?.icons?.center),updateAnimation:function(e,t,s,o){const i=1-kL[this.easingFn](e);t.icons||(t.icons={}),s.icons.left&&!o.icons.left&&(t.icons.left={...s.icons.left,opacity:i}),s.icons.right&&!o.icons.right&&(t.icons.right={...s.icons.right,opacity:i}),s.icons.center&&!o.icons.center&&(t.icons.center={...s.icons.center,opacity:i})}}),NL.add("textChange",{id:"textChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>{const s=e?.content?.textLines?.join("\n"),o=t?.content?.textLines?.join("\n");return Boolean(s&&o&&(s!==o||zL(t,e)))},updateAnimation:function(e,t,s,o){const i=kL[this.easingFn](e),n=o.y+(i-1)*o.height,r=o.y+i*o.height,a=zL(o,s),l={id:o.id+"-text-slide-in",x:o.x,y:n,width:o.width,height:o.height,style:{...o.style},skipCellGridLines:!0,content:o.content?{...o.content}:void 0,clipRect:o.clipRect||{...o,x:Math.max(0,o.x-(o.content?.width||0)),width:o.width+2*(o.content?.width||0)},icons:a?VL(o.icons,o):LL(o.icons)},c={id:s.id+"-text-slide-out",x:o.x,y:r,width:o.width,height:o.height,style:{...s.style},skipCellGridLines:!0,content:s.content?{...s.content}:void 0,clipRect:s.clipRect||{...o,x:Math.max(0,o.x-(s.content?.width||0)),width:o.width+2*(s.content?.width||0)},icons:a?VL(s.icons,o):LL(s.icons)};if(o.content&&s.content&&l.content&&c.content){const e=o.content.y+(i-1)*o.height,t=o.content.y+i*o.height;l.content.y=e,c.content.y=t}return c.style.fillColor=l.style.fillColor=void 0,t.content=void 0,t.icons=a?{}:t.icons,{newBoxes:[l,c]}}}),NL.add("borderFadeIn",{id:"borderFadeIn",easingFn:"easeInCubic",hasAnimation:(e,t)=>Boolean(!e?.border?.bottom&&t?.border?.bottom||!e?.border?.top&&t?.border?.top||!e?.border?.left&&t?.border?.left||!e?.border?.right&&t?.border?.right),updateAnimation:function(e,t,s,o){const i=kL[this.easingFn](e);t.border?.top&&o.border?.top&&!s.border?.top&&(t.border.top.opacity=i),t.border?.bottom&&o.border?.bottom&&!s.border?.bottom&&(t.border.bottom.opacity=i),t.border?.left&&o.border?.left&&!s.border?.left&&(t.border.left.opacity=i),t.border?.right&&o.border?.right&&!s.border?.right&&(t.border.right.opacity=i)}}),NL.add("borderFadeOut",{id:"borderFadeOut",easingFn:"easeOutCubic",hasAnimation:(e,t)=>Boolean(e?.border?.bottom&&!t?.border?.bottom||e?.border?.top&&!t?.border?.top||e?.border?.left&&!t?.border?.left||e?.border?.right&&!t?.border?.right),updateAnimation:function(e,t,s,o){const i=1-kL[this.easingFn](e);t.border||(t.border={}),s.border?.top&&!o.border?.top&&(t.border.top={...s.border.top,opacity:i}),s.border?.bottom&&!o.border?.bottom&&(t.border.bottom={...s.border.bottom,opacity:i}),s.border?.left&&!o.border?.left&&(t.border.left={...s.border.left,opacity:i}),s.border?.right&&!o.border?.right&&(t.border.right={...s.border.right,opacity:i})}}),NL.add("borderColorChange",{id:"borderColorChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>{const s=e?.border,o=t?.border;return!(!s||!o)&&Boolean(s.bottom?.color!==o.bottom?.color||s.top?.color!==o.top?.color||s.left?.color!==o.left?.color||s.right?.color!==o.right?.color)},updateAnimation:function(e,t,s,o){const i=i=>{const n=s?.border?.[i],r=o?.border?.[i],a=t.border?.[i];if(n&&r&&a){const t=xb([{value:0,color:n.color||"#000000"},{value:1,color:r.color||"#000000"}]);a.color=t(kL[this.easingFn](e))}};i("top"),i("bottom"),i("left"),i("right")}}),NL.add("iconChange",{id:"iconChange",easingFn:"easeOutCubic",hasAnimation:(e,t)=>!zL(t,e)&&Boolean(e?.icons?.center?.svg?.name!==t?.icons?.center?.svg?.name||e?.icons?.left?.svg?.name!==t?.icons?.left?.svg?.name||e?.icons?.right?.svg?.name!==t?.icons?.right?.svg?.name),updateAnimation:function(e,t,s,o){const i=kL[this.easingFn](e),n=o.y+(i-1)*o.height,r=o.y+i*o.height,a=[],l=e=>{const i=s.icons?.[e],l=o.icons?.[e],c={id:`${o.id}-icon-${e}-slide-in`,style:{verticalAlign:o.style.verticalAlign},x:o.x,y:n,width:o.width,height:o.height,skipCellGridLines:!0,icons:{[e]:{...l,clipRect:o}}},h={id:`${o.id}-icon-${e}-slide-out`,style:{verticalAlign:s.style.verticalAlign},x:o.x,y:r,width:o.width,height:o.height,skipCellGridLines:!0,icons:{[e]:{...i,clipRect:o}}};t.icons[e]=LL(o.icons)[e],a.push(c,h)};return l("left"),l("right"),l("center"),{newBoxes:a}}});const kL={linear:e=>e,easeInCubic:e=>e*e*e,easeOutCubic:e=>(e-=1)*e*e+1,easeInOutCubic:e=>(e/=.5)<1?.5*e*e*e:.5*((e-=2)*e*e+2),easeOutQuart:e=>-((e-=1)*e*e*e-1)};function LL(e){return{left:e.left?{...e.left,svg:void 0}:void 0,right:e.right?{...e.right,svg:void 0}:void 0,center:e.center?{...e.center,svg:void 0}:void 0}}function VL(e,t){return{left:e.left?{...e.left,clipRect:t}:void 0,right:e.right?{...e.right,clipRect:t}:void 0,center:e.center?{...e.center,clipRect:t}:void 0}}function zL(e,t){const s=(e,t)=>t&&e?!!(e.horizontalAlign!==t.horizontalAlign||e.size!==t.size||e.margin!==t.margin||e.svg&&!t.svg||!e.svg&&t.svg):!!(e&&!t||!e&&t);return s(e?.icons.left,t?.icons.left)||s(e?.icons.right,t?.icons.right)||s(e?.icons.center,t?.icons.center)}class HL extends t.Component{static template="o-spreadsheet-GaugeChartComponent";static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=t.useRef("chartContainer");animationStore;get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}setup(){this.env.model.getters.isDashboard()&&(this.animationStore=Tv(VS));let e,s=null;t.useEffect(()=>(this.env.isDashboard()&&void 0===e&&"gauge"!==this.animationStore?.animationPlayed[this.animationChartId]||this.env.isDashboard()&&void 0!==e&&!Le(this.runtime,e)?(s=this.drawGaugeWithAnimation(),this.animationStore?.disableAnimationForChart(this.animationChartId,"gauge")):FO(this.canvasEl,this.runtime),e=this.runtime,()=>s?.stop()),()=>{const e=this.canvasEl.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}drawGaugeWithAnimation(){FO(this.canvasEl,{...this.runtime,animationValue:0},void 0);const e=this.runtime.gaugeValue?.value||0,t=this.runtime.maxValue.value,s=Math.sign(e)*Math.min(Math.abs(e),Math.abs(t));if(0===s)return null;const o=this.runtime.minValue.value,i=new UL(o,s,1e3,e=>FO(this.canvasEl,{...this.runtime,animationValue:e},void 0));return i.start(),i}get canvasEl(){return this.canvas.el}get animationChartId(){return this.props.isFullScreen?this.props.chartId+"-fullscreen":this.props.chartId}}class UL{startValue;endValue;duration;callback;startTime=void 0;animationFrameId=null;constructor(e,t,s,o){this.startValue=e,this.endValue=t,this.duration=s,this.callback=o}start(){this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}stop(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}animate(e){this.startTime||(this.startTime=e);const t=e-this.startTime,s=Math.min(t/this.duration,1),o=this.startValue+(this.endValue-this.startValue)*kL.easeOutQuart(s);this.callback(o),s<1?this.animationFrameId=requestAnimationFrame(this.animate.bind(this)):this.stop()}}const BL=new Jg;BL.add("line",ML),BL.add("bar",ML),BL.add("combo",ML),BL.add("pie",xN),BL.add("gauge",HL),BL.add("scatter",ML),BL.add("scorecard",ZN),BL.add("waterfall",ML),BL.add("pyramid",xN),BL.add("radar",xN),BL.add("geo",xN),BL.add("funnel",xN),BL.add("sunburst",xN),BL.add("treemap",xN),BL.add("calendar",xN);class GL extends Lv{mutators=["toggleFullScreenFigure"];fullScreenFigure=void 0;toggleFullScreenFigure(e){this.fullScreenFigure?.id===e?this.fullScreenFigure=void 0:this.makeFullScreen(e)}makeFullScreen(e){const t=this.getters.getActiveSheetId(),s=this.getters.getFigure(t,e);s&&(this.fullScreenFigure={...s,x:0,y:0,width:0,height:0})}}class WL extends t.Component{static template="o-spreadsheet-Menu";static props={menuItems:Array,onClose:Function,onClickMenu:{type:Function,optional:!0},onMouseEnter:{type:Function,optional:!0},onMouseOver:{type:Function,optional:!0},onMouseLeave:{type:Function,optional:!0},width:{type:Number,optional:!0},isActive:{type:Function,optional:!0},onScroll:{type:Function,optional:!0}};static components={};static defaultProps={};hoveredMenu=void 0;setup(){t.onWillUnmount(()=>{this.hoveredMenu?.onStopHover?.(this.env)})}get menuItemsAndSeparators(){const e=[];for(let t=0;t<this.props.menuItems.length;t++){const s=this.props.menuItems[t];!s.isVisible(this.env)||this.isRoot(s)&&!this.hasVisibleChildren(s)||e.push(s),s.separator&&t!==this.props.menuItems.length-1&&"separator"!==e[e.length-1]&&e.push("separator")}return"separator"===e[e.length-1]&&e.pop(),1===e.length&&"separator"===e[0]?[]:e}get childrenHaveIcon(){return this.props.menuItems.some(e=>!!this.getIconName(e))}getIconName(e){return e.icon(this.env)?e.icon(this.env):e.isActive?.(this.env)?"o-spreadsheet-Icon.CHECK":""}getColor(e){return JF({color:e.textColor})}getIconColor(e){return JF({color:e.iconColor})}getName(e){return e.name(this.env)}isRoot(e){return!e.execute}hasVisibleChildren(e){return e.children(this.env).some(e=>e.isVisible(this.env))}isEnabled(e){const t=e.children?.(this.env);return t.length?t.some(e=>this.isEnabled(e)):!!e.isEnabled(this.env)&&(!this.env.model.getters.isReadonly()||e.isReadonlyAllowed)}get menuStyle(){return this.props.width?JF({width:this.props.width+"px"}):""}onMouseEnter(e,t){this.hoveredMenu=e,e.onStartHover?.(this.env),this.props.onMouseEnter?.(e,t)}onMouseLeave(e,t){this.hoveredMenu=void 0,e.onStopHover?.(this.env),this.props.onMouseLeave?.(e,t)}onClickMenu(e,t){this.isEnabled(e)&&this.props.onClickMenu?.(e,t)}}function $L(e){return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}function qL(e){if(e)return{x:e.left,y:e.top,width:e.right-e.left,height:e.bottom-e.top}}function ZL(){const e=t.useState({x:0,y:0,width:0,height:0});let s=null;function o(){if(s||(s=document.querySelector(".o-spreadsheet")),s){const{top:t,left:o,width:i,height:n}=s.getBoundingClientRect();e.x=o,e.y=t,e.width=i,e.height=n}}return t.onMounted(o),t.onPatched(o),e}class jL extends t.Component{static template="o-spreadsheet-Popover";static props={anchorRect:Object,containerRect:{type:Object,optional:!0},positioning:{type:String,optional:!0},maxWidth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},verticalOffset:{type:Number,optional:!0},onMouseWheel:{type:Function,optional:!0},onPopoverHidden:{type:Function,optional:!0},onPopoverMoved:{type:Function,optional:!0},zIndex:{type:Number,optional:!0},class:{type:String,optional:!0},slots:Object};static defaultProps={positioning:"bottom-left",verticalOffset:0,onMouseWheel:()=>{},onPopoverMoved:()=>{},onPopoverHidden:()=>{}};popoverRef=t.useRef("popover");popoverContentRef=t.useRef("popoverContent");currentPosition=void 0;currentDisplayValue=void 0;spreadsheetRect=ZL();containerRect;setup(){this.containerRect=function(){const e=t.useState({x:0,y:0,width:0,height:0}),s=t.useComponent(),o=ZL();function i(){const t=s.env,i="getPopoverContainerRect"in t&&t.getPopoverContainerRect?t.getPopoverContainerRect():o;e.x=i.x,e.y=i.y,e.width=i.width,e.height=i.height}return i(),t.onMounted(i),t.onPatched(i),e}();const e=new ResizeObserver(this.computePopoverPosition.bind(this));t.onMounted(()=>{e.observe(this.popoverContentRef.el)}),t.onWillUnmount(()=>{e.disconnect()}),t.useEffect(this.computePopoverPosition.bind(this))}computePopoverPosition(){if(!this.containerRect)throw new Error("Popover container is not defined");const e=this.popoverRef.el,t=this.popoverContentRef.el,s=(o=this.props.anchorRect,i=this.containerRect,qL(zt($L(o),$L(i))));var o,i;const n=s?"block":"none";if("none"!==this.currentDisplayValue&&"none"===n&&this.props.onPopoverHidden?.(),e.style.display=n,this.currentDisplayValue=n,!s)return;const r={width:this.props.maxWidth,height:this.props.maxHeight};let a={width:t.getBoundingClientRect().width,height:t.getBoundingClientRect().height};const l=this.spreadsheetRect,c="bottom-left"===this.props.positioning?new XL(s,this.containerRect,r,l,this.currentPosition):new KL(s,this.containerRect,r,l,this.currentPosition);e.style["max-height"]=c.getMaxHeight(a.height)+"px",e.style["max-width"]=c.getMaxWidth(a.width)+"px",a={width:e.getBoundingClientRect().width,height:e.getBoundingClientRect().height};const h=c.getCss(a,this.props.verticalOffset);for(const t of Object.keys(h))e.style[t]=h[t];const d=c.getCurrentPosition(a);this.currentPosition&&d!==this.currentPosition&&this.props.onPopoverMoved?.(),this.currentPosition=d}}class YL{anchorRect;containerRect;propsMaxSize;spreadsheetOffset;lastPosition;constructor(e,t,s,o,i){this.anchorRect=e,this.containerRect=t,this.propsMaxSize=s,this.spreadsheetOffset=o,this.lastPosition=i}shouldRenderAtBottom(e){if("top-left"===this.lastPosition||"top-right"===this.lastPosition){return!(e<=this.availableHeightUp||this.availableHeightUp>=this.availableHeightDown)}return e<=this.availableHeightDown||this.availableHeightDown>=this.availableHeightUp}shouldRenderAtRight(e){if("bottom-left"===this.lastPosition||"top-left"===this.lastPosition){return!(e<=this.availableWidthLeft||this.availableWidthLeft>=this.availableWidthRight)}return e<=this.availableWidthRight||this.availableWidthRight>=this.availableWidthLeft}getMaxHeight(e){const t=this.shouldRenderAtBottom(e)?this.availableHeightDown:this.availableHeightUp;return this.propsMaxSize.height?Math.min(t,this.propsMaxSize.height):t}getMaxWidth(e){const t=this.shouldRenderAtRight(e)?this.availableWidthRight:this.availableWidthLeft;return this.propsMaxSize.width?Math.min(t,this.propsMaxSize.width):t}getCss(e,t){const s=this.getMaxHeight(e.height),o=this.getMaxWidth(e.width),i=Math.min(s,e.height),n=Math.min(o,e.width),r=this.shouldRenderAtBottom(e.height),a=this.shouldRenderAtRight(e.width);return t=r?t:-t,{top:this.getTopCoordinate(i,r)-this.spreadsheetOffset.y-t+"px",left:this.getLeftCoordinate(n,a)-this.spreadsheetOffset.x+"px"}}getCurrentPosition(e){const t=this.shouldRenderAtBottom(e.height),s=this.shouldRenderAtRight(e.width);return t&&s?"bottom-right":t&&!s?"bottom-left":!t&&s?"top-right":"top-left"}}class XL extends YL{get availableHeightUp(){return this.anchorRect.y-this.containerRect.y}get availableHeightDown(){return this.containerRect.height-this.availableHeightUp-this.anchorRect.height}get availableWidthRight(){return this.containerRect.x+this.containerRect.width-this.anchorRect.x}get availableWidthLeft(){return this.anchorRect.x+this.anchorRect.width-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y+this.anchorRect.height:this.anchorRect.y-e}getLeftCoordinate(e,t){return t?this.anchorRect.x:this.anchorRect.x+this.anchorRect.width-e}}class KL extends YL{get availableHeightUp(){return this.anchorRect.y+this.anchorRect.height-this.containerRect.y}get availableHeightDown(){return this.containerRect.y+this.containerRect.height-this.anchorRect.y}get availableWidthRight(){return this.containerRect.width-this.anchorRect.width-this.availableWidthLeft}get availableWidthLeft(){return this.anchorRect.x-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y:this.anchorRect.y+this.anchorRect.height-e}getLeftCoordinate(e,t){return t?this.anchorRect.x+this.anchorRect.width:this.anchorRect.x-e}}class JL extends t.Component{static template="o-spreadsheet-Menu-Popover";static props={anchorRect:Object,popoverPositioning:{type:String,optional:!0},menuItems:Array,depth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},onClose:Function,onMenuClicked:{type:Function,optional:!0},menuId:{type:String,optional:!0},onMouseOver:{type:Function,optional:!0},width:{type:Number,optional:!0}};static components={MenuPopover:JL,Menu:WL,Popover:jL};static defaultProps={depth:1,popoverPositioning:"top-right"};subMenu=t.useState({isOpen:!1,anchorRect:null,scrollOffset:0,menuItems:[],isHoveringChild:!1});menuRef=t.useRef("menu");hoveredMenu=void 0;openingTimeOut=function(){let e;function s(){void 0!==e&&(clearTimeout(e),e=void 0)}return t.onWillUnmount(s),{clear:s,schedule:function(t,o){s(),e=setTimeout(t,o)}}}();setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.useExternalListener(window,"contextmenu",this.onExternalClick,{capture:!0}),t.onWillUpdateProps(e=>{e.menuItems!==this.props.menuItems&&this.closeSubMenu()}),t.onWillUnmount(()=>{this.hoveredMenu?.onStopHover?.(this.env)})}get menuProps(){return{menuItems:this.props.menuItems,onClose:this.close.bind(this),onClickMenu:this.onClickMenu.bind(this),onMouseOver:this.onMouseOver.bind(this),onMouseLeave:this.onMouseLeave.bind(this),width:this.props.width||250,isActive:this.isActive.bind(this),onScroll:this.onScroll.bind(this)}}get subMenuAnchorRect(){const e=Object.assign({},this.subMenu.anchorRect);return e.y-=this.subMenu.scrollOffset||0,e}get popoverProps(){const e=1===this.props.depth;return{anchorRect:{x:this.props.anchorRect.x,y:this.props.anchorRect.y,width:e?this.props.anchorRect.width:this.props.width||250,height:e?this.props.anchorRect.height:26},positioning:this.props.popoverPositioning,verticalOffset:e?0:6,onPopoverHidden:()=>this.closeSubMenu(),onPopoverMoved:()=>this.closeSubMenu(),maxHeight:this.props.maxHeight}}get childrenHaveIcon(){return this.props.menuItems.some(e=>!!this.getIconName(e))}getIconName(e){return e.icon(this.env)?e.icon(this.env):e.isActive?.(this.env)?"o-spreadsheet-Icon.CHECK":""}getColor(e){return JF({color:e.textColor})}getIconColor(e){return JF({color:e.iconColor})}async activateMenu(e,t){const s=await(e.execute?.(this.env,t));this.close(),this.props.onMenuClicked?.({detail:s})}close(){this.closeSubMenu(),this.props.onClose()}onExternalClick(e){this.menuRef.el&&Array.from(document.querySelectorAll(".o-spreadsheet .o-menu")).some(t=>AN(t,e))||(e.closedMenuId=this.props.menuId,this.close())}getName(e){return e.name(this.env)}isRoot(e){return!e.execute}isEnabled(e){return!!e.isEnabled(this.env)&&(!this.env.model.getters.isReadonly()||e.isReadonlyAllowed)}isActive(e){return!!this.subMenu?.isHoveringChild&&this.isParentMenu(this.subMenu,e)}onScroll(e){this.subMenu.scrollOffset=e.target.scrollTop}openSubMenu(e,t){if(!t)return;const s=t.getBoundingClientRect().top;this.subMenu.anchorRect={x:ON(this.menuRef).x,y:s-(this.subMenu.scrollOffset||0),width:this.props.width||250,height:26},this.subMenu.menuItems=e.children(this.env),this.subMenu.isOpen=!0,this.subMenu.parentMenu=e}isParentMenu(e,t){return e.parentMenu?.id===t.id}closeSubMenu(){this.subMenu.isHoveringChild||(this.subMenu.isOpen=!1,this.subMenu.parentMenu=void 0)}onClickMenu(e,t){this.isRoot(e)?this.openSubMenu(e,t.currentTarget):this.activateMenu(e,HN(t))}onMouseOver(e,t){if(this.isParentMenu(this.subMenu,e))return void this.openingTimeOut.clear();const s=t.currentTarget;this.isRoot(e)&&this.openingTimeOut.schedule(()=>{this.openSubMenu(e,s)},250)}onMouseOverMainMenu(){this.props.onMouseOver?.(),this.subMenu.isHoveringChild=!1}onMouseOverChildMenu(){this.subMenu.isHoveringChild=!0,this.openingTimeOut.clear()}onMouseLeave(e){this.openingTimeOut.schedule(this.closeSubMenu.bind(this),250)}get menuStyle(){return this.props.width?JF({width:this.props.width+"px"}):""}}class QL extends t.Component{static template="o-spreadsheet-ChartDashboardMenu";static components={MenuPopover:JL};static props={chartId:String,hasFullScreenButton:{type:Boolean,optional:!0}};static defaultProps={hasFullScreenButton:!0};fullScreenFigureStore;menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});setup(){super.setup(),this.fullScreenFigureStore=Tv(GL)}getMenuItems(){return[this.fullScreenMenuItem].filter(De)}get backgroundColor(){return"background-color: "+(this.env.model.getters.getChartDefinition(this.props.chartId).background||c)}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.anchorRect=FN(e.currentTarget);const t=this.env.model.getters.getFigureIdFromChartId(this.props.chartId);this.menuState.menuItems=xL(t,this.env)}get fullScreenMenuItem(){if(!this.props.hasFullScreenButton)return;const e=this.env.model.getters.getChartDefinition(this.props.chartId),t=this.env.model.getters.getFigureIdFromChartId(this.props.chartId);if("scorecard"===e.type)return;const s=t===this.fullScreenFigureStore.fullScreenFigure?.id;return{id:"fullScreenChart",label:Cs(s?"Exit Full Screen":"Full Screen"),class:"text-muted fa "+(s?"fa-compress":"fa-expand"),onClick:()=>{this.fullScreenFigureStore.toggleFullScreenFigure(t)}}}}class eV extends t.Component{static template="o-spreadsheet-CarouselFigure";static props={figureUI:Object,editFigureStyle:{type:Function,optional:!0},isFullScreen:{type:Boolean,optional:!0},openContextMenu:{type:Function,optional:!0}};static components={ChartDashboardMenu:QL,MenuPopover:JL};carouselTabsRef=t.useRef("carouselTabs");carouselTabsDropdownRef=t.useRef("carouselTabsDropdown");menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});hiddenItems=[];animationStore;fullScreenFigureStore;setup(){this.animationStore=Tv(VS),this.fullScreenFigureStore=Tv(GL),t.useEffect(()=>{"carouselDataView"===this.selectedCarouselItem?.type?this.props.editFigureStyle?.({"pointer-events":"none"}):this.props.editFigureStyle?.({"pointer-events":"auto"}),this.updateTabsVisibility()})}get carousel(){return this.env.model.getters.getCarousel(this.props.figureUI.id)}get selectedCarouselItem(){return this.env.model.getters.getSelectedCarouselItem(this.props.figureUI.id)}get chartComponent(){const e=this.selectedCarouselItem;if("chart"!==e?.type)throw new Error("Selected item is not a chart");const t=this.env.model.getters.getChartType(e.chartId),s=BL.get(t);if(!s)throw new Error(`Component is not defined for type ${t}`);return s}onCarouselDoubleClick(){this.env.model.dispatch("SELECT_FIGURE",{figureId:this.props.figureUI.id}),this.env.openSidePanel("CarouselPanel",{figureId:this.props.figureUI.id})}isItemSelected(e){return Le(this.selectedCarouselItem,e)}getItemTitle(e){return jF(this.env.model.getters,e)}onCarouselTabClick(e){if(this.env.model.dispatch("UPDATE_CAROUSEL_ACTIVE_ITEM",{figureId:this.props.figureUI.id,sheetId:this.env.model.getters.getActiveSheetId(),item:e}),"chart"===e.type){const t=e.chartId+(this.props.isFullScreen?"-fullscreen":"");this.animationStore?.enableAnimationForChart(t)}}get headerStyle(){const e={};if("chart"===this.selectedCarouselItem?.type){const t=this.env.model.getters.getChartRuntime(this.selectedCarouselItem.chartId);e["background-color"]=t.background}else e["background-color"]="#ffffff";return JF(e)}get title(){return this.carousel.title?.text??""}get titleStyle(){return JF(KF(function(e){return{bold:e.bold,italic:e.italic,fontSize:e.fontSize,textColor:e.color,align:e.align}}({...ie,...this.carousel.title})))}updateTabsVisibility(){const e=this.carouselTabsRef.el,t=this.carouselTabsDropdownRef.el;if(!e||!t)return;this.hiddenItems=[];const s=FN(e),o=Array.from(e.children);for(const e of o)e.style.display="block";const i=o.map(e=>FN(e).width);let n=0;for(let e=0;e<o.length;e++){const t=n+i[e]>s.width;n+=i[e],t&&(o[e].style.display="none",this.hiddenItems.push(this.carousel.items[e]))}t.style.display=this.hiddenItems.length?"block":"none"}get menuId(){return"carousel-tabs-menu-"}toggleMenu(e){if(e.closedMenuId===this.menuId)return void(this.menuState.isOpen=!1);const t=ON(this.carouselTabsDropdownRef),s=this.hiddenItems.map(e=>({name:this.getItemTitle(e),execute:()=>this.onCarouselTabClick(e),isActive:()=>this.isItemSelected(e),isReadonlyAllowed:!0}));this.menuState.isOpen=!0,this.menuState.anchorRect=t,this.menuState.menuItems=Sv(s)}toggleFullScreen(){"chart"===this.selectedCarouselItem?.type&&this.fullScreenFigureStore.toggleFullScreenFigure(this.props.figureUI.id)}get fullScreenButtonTitle(){return this.props.isFullScreen?Cs("Exit Full Screen"):Cs("Full Screen")}get visibleCarouselItems(){return this.carousel.items.filter(e=>"carouselDataView"!==e.type||!this.props.isFullScreen)}openContextMenu(e){const t=e.currentTarget;t&&this.props.openContextMenu?.(FN(t))}}class tV extends t.Component{static template="o-spreadsheet-ChartFigure";static props={figureUI:Object,editFigureStyle:{type:Function,optional:!0},isFullScreen:{type:Boolean,optional:!0},openContextMenu:{type:Function,optional:!0}};static components={ChartDashboardMenu:QL};onDoubleClick(){this.env.model.dispatch("SELECT_FIGURE",{figureId:this.props.figureUI.id}),this.env.openSidePanel("ChartPanel")}get chartType(){return this.env.model.getters.getChartType(this.chartId)}get chartId(){const e=this.env.model.getters.getChartIdFromFigureId(this.props.figureUI.id);if(!e)throw new Error(`No chart found for figure ID: ${this.props.figureUI.id}`);return e}get chartComponent(){const e=this.chartType,t=BL.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}class sV extends t.Component{static template="o-spreadsheet-ImageFigure";static props={figureUI:Object,editFigureStyle:{type:Function,optional:!0},openContextMenu:{type:Function,optional:!0}};static components={};get figureId(){return this.props.figureUI.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}}const oV=new Jg;oV.add("chart",{Component:tV,SidePanelComponent:"ChartPanel",menuBuilder:xL}),oV.add("image",{Component:sV,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t){return Sv([RL(e,t,Cs("Image copied to clipboard")),TL(e,t),{id:"reset_size",name:Cs("Reset size"),execute:async()=>{const s=t.model.getters.getActiveSheetId(),o=t.model.getters.getFigure(s,e);if(!o)return;const i=t.model.getters.getImagePath(e),n=t.model.getters.getImageSize(e)??await(t.imageProvider?.getImageOriginalSize(i));if(!t.model.getters.getImageSize(e)){t.model.getters.getImage(e).size=n}const{col:r,row:a}=o,{height:l,width:c}=cP(t.model.getters,n);t.model.dispatch("UPDATE_FIGURE",{sheetId:s,figureId:e,height:l,width:c,col:r,row:a})},icon:"o-spreadsheet-Icon.REFRESH"},{id:"download",name:Cs("Download"),execute:async()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e});UN(t.model.getters.getImagePath(e),"image")},icon:"o-spreadsheet-Icon.DOWNLOAD"},DL(e,t)])}}),oV.add("carousel",{Component:eV,menuBuilder:function(e,t){const s=t=>"chart"===t.model.getters.getSelectedCarouselItem(e)?.type;return Sv([{id:"edit_carousel",name:Cs("Edit carousel"),execute:()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e}),t.openSidePanel("CarouselPanel",{figureId:e})},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall},{...RL(e,t,Cs("Carousel copied to clipboard")),name:Cs("Copy carousel")},{...TL(e,t),name:Cs("Cut carousel")},{...DL(e,t),name:Cs("Delete carousel"),separator:!0},{id:"edit_chart",name:Cs("Edit chart"),execute:()=>{t.model.dispatch("SELECT_FIGURE",{figureId:e}),t.openSidePanel("ChartPanel",{})},icon:"o-spreadsheet-Icon.EDIT",isEnabled:e=>!e.isSmall,isVisible:s},{...AL(e,t),isVisible:s,name:Cs("Copy chart as image")},{..._L(e,t),isVisible:s,name:Cs("Download chart")},{id:"popout_chart",name:Cs("Pop out chart"),icon:"o-spreadsheet-Icon.EXTERNAL",execute:()=>{const s=t.model.getters.getSelectedCarouselItem(e);s&&"chart"===s.type&&t.model.dispatch("POPOUT_CHART_FROM_CAROUSEL",{carouselId:e,chartId:s.chartId,sheetId:t.model.getters.getActiveSheetId()})},isVisible:s},{id:"delete_carousel_item",name:t=>{const s=t.model.getters.getSelectedCarouselItem(e);return Cs("chart"===s?.type?"Delete chart":"Delete data view")},execute:()=>{const s=t.model.getters.getSelectedCarouselItem(e);if(!s)return;const o=t.model.getters.getCarousel(e),i=o.items.filter(e=>!Le(e,s));t.model.dispatch("UPDATE_CAROUSEL",{figureId:e,sheetId:t.model.getters.getActiveSheetId(),definition:{...o,items:i}})},icon:"o-spreadsheet-Icon.TRASH",isVisible:t=>t.model.getters.getCarousel(e).items.length>=1}]).filter(e=>!t.model.getters.isReadonly()||e.isReadonlyAllowed)}});class iV extends t.Component{static template="o-spreadsheet-FigureComponent";static props={figureUI:Object,style:{type:String,optional:!0},class:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}};static components={MenuPopover:JL};static defaultProps={onMouseDown:()=>{},onClickAnchor:()=>{}};menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});figureRef=t.useRef("figure");figureWrapperRef=t.useRef("figureWrapper");menuButtonRef=t.useRef("menuButton");borderWidth;get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figureUI.id}get figureRegistry(){return oV}getBorderWidth(){return this.env.isDashboard()?0:this.isSelected?2:this.borderWidth}getBorderStyle(e){return`border-${e}-width: ${this.getBorderWidth()}px;`}get wrapperStyle(){const{x:e,y:t,width:s,height:o}=this.props.figureUI;return JF({left:`${e}px`,top:`${t}px`,width:`${s}px`,height:`${o}px`})}getResizerPosition(e){const t={};return e.includes("top")?t.top="-3px":e.includes("bottom")?t.bottom="-3px":t.bottom="calc(50% - 3px)",e.includes("left")?t.left="-3px":e.includes("right")?t.right="-3px":t.right="calc(50% - 3px)",JF(t)}setup(){const e=oV.get(this.props.figureUI.tag).borderWidth;this.borderWidth=void 0!==e?e:1,t.useEffect((e,t,s)=>{e===t&&s?.focus({preventScroll:!0})},()=>[this.env.model.getters.getSelectedFigureId(),this.props.figureUI.id,this.figureRef.el])}clickAnchor(e,t,s){this.props.onClickAnchor(e,t,s)}onMouseDown(e){this.env.isMobile()||this.props.onMouseDown(e)}onClick(e){this.env.isMobile()&&this.props.onMouseDown(e)}onKeyDown(e){const t=LN(e);switch(t){case"Delete":case"Backspace":this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),figureId:this.props.figureUI.id}),e.preventDefault(),e.stopPropagation();break;case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":const{col:s,row:o,offset:i}=this.postionInBoundary(this.props.figureUI,e.key);this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),figureId:this.props.figureUI.id,offset:i,col:s,row:o}),e.preventDefault(),e.stopPropagation();break;case"Ctrl+A":e.preventDefault(),e.stopPropagation();break;case"Ctrl+Y":case"Ctrl+Z":"Ctrl+Y"===t?this.env.model.dispatch("REQUEST_REDO"):"Ctrl+Z"===t&&this.env.model.dispatch("REQUEST_UNDO"),e.preventDefault(),e.stopPropagation()}}postionInBoundary(e,t){const s=this.env.model.getters.getActiveSheetId();let{col:o,row:i,offset:n}=e;switch(n={...n},t){case"ArrowUp":0===n.y?(i--,n.y=this.env.model.getters.getRowSize(s,i)-1):n.y--;break;case"ArrowLeft":0===n.x?(o--,n.x=this.env.model.getters.getColSize(s,o)-1):n.x--;break;case"ArrowDown":n.y===this.env.model.getters.getRowSize(s,i)?(i++,n.y=0):n.y++;break;case"ArrowRight":n.x===this.env.model.getters.getColSize(s,i)?(o++,n.x=0):n.x++}return{col:o,row:i,offset:n}}onContextMenu(e){if(this.env.isDashboard())return;const t=$N(this.env,e);this.openContextMenu({x:t.clientX,y:t.clientY,width:0,height:0})}showMenu(){this.openContextMenu(ON(this.menuButtonRef))}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.anchorRect=e,this.menuState.menuItems=oV.get(this.props.figureUI.tag).menuBuilder(this.props.figureUI.id,this.env)}editWrapperStyle(e){if(this.figureWrapperRef.el)for(const t in e)this.figureWrapperRef.el.style.setProperty(t,e[t]||null)}}class nV extends Lv{mutators=["clear","hover"];col;row;handle(e){if("ACTIVATE_SHEET"===e.type)this.clear()}hover(e){if(e.col===this.col&&e.row===this.row)return"noStateChange";this.col=e.col,this.row=e.row}clear(){if(void 0===this.col&&void 0===this.row)return"noStateChange";this.col=void 0,this.row=void 0}}const rV=new Jg;class aV extends Lv{mutators=["open","close"];persistentPopover;hoveredCell=this.get(nV);handle(e){if("ACTIVATE_SHEET"===e.type)this.close()}open({col:e,row:t},s){const o=this.getters.getActiveSheetId();rV.contains(s)&&(this.persistentPopover={col:e,row:t,sheetId:o,type:s})}close(){if(!this.persistentPopover)return"noStateChange";this.persistentPopover=void 0}get persistentCellPopover(){return this.persistentPopover&&{isOpen:!0,...this.persistentPopover}||{isOpen:!1}}get isOpen(){return void 0!==this.persistentPopover}get cellPopover(){const e=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=rV.get(this.persistentPopover.type).onOpen?.(e,this.getters);return t?.isOpen?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}const{col:t,row:s}=this.hoveredCell;if(void 0===t||void 0===s||!this.getters.isVisibleInViewport({sheetId:e,col:t,row:s}))return{isOpen:!1};const o=this.getters.getMainCellPosition({sheetId:e,col:t,row:s}),i=rV.getAll().map(e=>e.onHover?.(o,this.getters)).find(e=>e?.isOpen);return i?.isOpen?{...i,anchorRect:this.computePopoverAnchorRect(o)}:{isOpen:!1}}computePopoverAnchorRect({col:e,row:t}){const s=this.getters.getActiveSheetId(),o=this.getters.getMerge({sheetId:s,col:e,row:t});return o?this.getters.getVisibleRect(o):this.getters.getVisibleRect(Jt({col:e,row:t}))}}class lV extends t.Component{static maxSize={maxHeight:80};static template="o-spreadsheet-ErrorToolTip";static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};get dataValidationErrorMessage(){return this.env.model.getters.getInvalidDataValidationMessage(this.props.cellPosition)}get evaluationError(){const e=this.env.model.getters.getEvaluatedCell(this.props.cellPosition);if(e.message)return e}get errorOriginPositionString(){if(this.env.model.getters.isDashboard())return"";const e=this.evaluationError,t=e?.errorOriginPosition;if(!t||Le(t,this.props.cellPosition))return"";const s=t.sheetId;return this.env.model.getters.getRangeString(this.env.model.getters.getRangeFromZone(s,Jt(t)),this.env.model.getters.getActiveSheetId())}selectCell(){const e=this.evaluationError?.errorOriginPosition;if(!e)return;const t=this.env.model.getters.getActiveSheetId();e.sheetId!==t&&this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:e.sheetId}),this.env.model.selection.selectCell(e.col,e.row)}}const cV={onHover:(e,t)=>{const s=t.getEvaluatedCell(e);return s.type===Xd.error&&s.message||t.getInvalidDataValidationMessage(e)?{isOpen:!0,props:{cellPosition:e},Component:lV,cellCorner:"top-right"}:{isOpen:!1}}};function hV(e,t,s,o,i){let n=o.right>o.left;if(e.model.getters.doesIntersectMerge(t,o)){let s;n=!1;for(let i=o.top;i<=o.bottom;i++){s=[];for(let n=o.left;n<=o.right;n++){const o=e.model.getters.getMerge({sheetId:t,col:n,row:i});o&&!s.includes(o.id.toString())&&s.push(o.id.toString())}if(s.length>=2){n=!0;break}}}if(n)return void dV(e,t,s,o,i);const r=e.model.getters.getContiguousZone(t,o);Ht(r,o)?dV(e,t,s,o,i):e.askConfirmation(Cs("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),()=>dV(e,t,s,r,i),()=>dV(e,t,s,o,i))}function dV(e,t,s,o,i,n){const r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:s.col,row:s.row,zone:o,sortDirection:i,sortOptions:n});if(r.isCancelledBecause("InvalidSortZone")){const{col:t,row:i}=s;e.model.selection.selectZone({cell:{col:t,row:i},zone:o}),e.raiseError(Cs("Cannot sort. To sort, select only cells or only merges that have the same size."))}if(r.isCancelledBecause("SortZoneWithArrayFormulas")){const{col:t,row:i}=s;e.model.selection.selectZone({cell:{col:t,row:i},zone:o}),e.raiseError(Cs("Cannot sort a zone with array formulas."))}}class uV extends t.Component{static template="o-spreadsheet-Collapse";static props={isCollapsed:Boolean,slots:Object};contentRef=t.useRef("content");setup(){t.onMounted(()=>{this.props.isCollapsed&&this.contentRef.el?.classList.add("d-none")}),t.onWillUpdateProps(e=>{e.isCollapsed!==this.props.isCollapsed&&this.startTransition(e.isCollapsed)})}startTransition(e){const t=this.contentRef.el;if(!t)return;t.classList.remove("d-none"),t.classList.add("overflow-hidden");const s=e?t.scrollHeight:0,o=e?0:t.scrollHeight;t.animate([{maxHeight:s+"px"},{maxHeight:o+"px"}],{duration:350,easing:"ease"}).onfinish=()=>{t.classList.remove("overflow-hidden"),this.props.isCollapsed&&t.classList.add("d-none")}}}class gV extends t.Component{static template="o-spreadsheet-SidePanelCollapsible";static props={slots:Object,title:{type:String,optional:!0},isInitiallyCollapsed:{type:Boolean,optional:!0},class:{type:String,optional:!0}};static components={Collapse:uV};state=t.useState({isCollapsed:this.props.isInitiallyCollapsed});toggle(){this.state.isCollapsed=!this.state.isCollapsed}}class pV extends t.Component{static props={criterion:Object,onCriterionChanged:Function,disableFormulas:{type:Boolean,optional:!0},autofocus:{type:Boolean,optional:!0}};setup(){const e=Tv(zv);"inactive"!==e.activeComposer.editionMode&&e.activeComposer.stopEdition()}updateCriterion(e){const t={...this.props.criterion,...e};this.props.onCriterionChanged(t)}}class mV{mutators=["setFocusableElement","focus"];focusableElement=void 0;setFocusableElement(e){return this.focusableElement=e,"noStateChange"}focus(){if(this.focusableElement===document.activeElement)return"noStateChange";this.focusableElement?.focus()}}const fV={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function vV(e,t){const s=fV[e.key];e.shiftKey?t.resizeAnchorZone(s,zN(e)?"end":1):t.moveAnchorCell(s,zN(e)?"end":1)}class bV extends t.Component{static template="o-spreadsheet-TextValueProvider";static props={proposals:Array,selectedIndex:{type:Number,optional:!0},onValueSelected:Function,onValueHovered:Function};autoCompleteListRef=t.useRef("autoCompleteList");setup(){t.useEffect(()=>{const e=this.props.selectedIndex;if(void 0===e)return;const t=this.autoCompleteListRef.el?.children[e];t?.scrollIntoView?.({block:"nearest"})},()=>[this.props.selectedIndex,this.autoCompleteListRef.el])}getCss(e){return JF({color:e.color,background:e.backgroundColor})}}class SV{el;constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){const s=window.getSelection(),{start:o,end:i}=this.getCurrentSelection();if(o===e&&i===t)return;if(0===s.rangeCount){const e=document.createRange();s.addRange(e)}const n=s.getRangeAt(0);let r;if(this.el.contains(n.startContainer)?r=n:(r=document.createRange(),s.removeAllRanges(),s.addRange(r)),e===t&&0===e)r.setStart(this.el,0),r.setEnd(this.el,0);else{const s=this.getText().length;(e<0||t>s)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${s}`),e<0&&(e=0),t>s&&(t=s),e>s&&(e=s));const o=this.findChildAtCharacterIndex(e),i=this.findChildAtCharacterIndex(t);e<=t?(r.setStart(o.node,o.offset),r.setEnd(i.node,i.offset)):(r.setStart(i.node,i.offset),r.setEnd(o.node,o.offset))}}findChildAtCharacterIndex(e){const t=PN(this.el);let s,o,i=e,n=!0;do{s=t.next(),s.done||s.value.hasChildNodes()||(s.value.textContent&&s.value.textContent.length<i?i-=s.value.textContent.length:s.value.textContent&&s.value.textContent.length>=i&&t.return(s.value),o=s.value),s.done||"P"!==s.value.nodeName||(n?n=!1:i--)}while(!s.done&&i);return s.value?{node:s.value,offset:i}:{node:o,offset:i}}setText(e){if(0===e.length)return void this.removeAll();const t=Array.from(this.el.childNodes),s=e.length;for(let o=0;o<s;o++){const s=e[o],i=t[o];let n,r=!1;i&&"P"===i.nodeName?n=i:(r=!0,n=document.createElement("p"));const a=s.length,l=Array.from(n.childNodes);for(let e=0;e<a;e++){const t=s[e],o=l[e];if(o&&"tagName"in o&&"SPAN"===o.tagName&&yV(t,o))continue;if(!t.value&&!t.classes?.length){o&&n.removeChild(o);continue}const i=document.createElement("span");i.innerText=t.value,i.style.color=t.color||"",void 0!==t.opacity&&1!==t.opacity&&(i.style.opacity=t.opacity.toString()),i.addEventListener("mousemove",()=>{t.onHover?.(FN(i))}),i.addEventListener("mouseleave",()=>{t.onStopHover?.()}),i.classList.add(...t.classes||[]),o?n.replaceChild(i,o):n.appendChild(i)}if(l.length>a)for(let e=a;e<l.length;e++)n.removeChild(l[e]);n.hasChildNodes()||n.appendChild(document.createElement("span")),r&&(i?this.el.replaceChild(n,i):this.el.appendChild(n))}if(t.length>s)for(let e=s;e<t.length;e++)this.el.removeChild(t[e])}scrollSelectionIntoView(){const e=document.getSelection()?.focusNode;if(!e||!this.el.contains(e))return;const t=e instanceof HTMLElement?e:e.parentElement;t?.scrollIntoView?.({block:"nearest"})}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){return MN(this.el)}getText(){let e="",t=!0,s=!1;const o=PN(this.el);for(let i=o.next();!i.done;i=o.next())"P"===i.value.nodeName||"DIV"===i.value.nodeName&&i.value!==this.el?(t?t=!1:e+=Q,s=EV(i.value)):i.value.hasChildNodes()||("BR"!==i.value.nodeName||s||(e+=Q),e+=i.value.textContent);return e}}function yV(e,t){const s=e.color||"",o=t.style?.color||"",i=t.style?.opacity||"1",n=s===o,r=Le(e.classes,[...t.classList]),a=t.innerText===e.value,l=(e.opacity??1).toString()===i;return n&&r&&a&&l}const CV=new DOMParser,IV=CV.parseFromString("<br>","text/html").body.firstChild,wV=CV.parseFromString("<span><br></span>","text/html").body.firstChild;function EV(e){if(e.childNodes.length>1)return!1;const t=e.firstChild?.cloneNode(!0);return!t||t instanceof Element&&(t.removeAttribute("class"),t.removeAttribute("style"),t.isEqualNode(IV)||t.isEqualNode(wV)||!1)}class xV extends t.Component{static template="o-spreadsheet-FunctionDescriptionProvider";static props={functionDescription:Object,argsToFocus:Array,repeatingArgGroupIndex:{type:Number,optional:!0}};static components={Collapse:uV};state=t.useState({isCollapsed:!0});toggle(){this.state.isCollapsed=!this.state.isCollapsed}getContext(){return this.props}get formulaHeaderContent(){const{functionDescription:e,repeatingArgGroupIndex:t,argsToFocus:s}=this.props,o=this.env.model.getters.getLocale().formulaArgSeparator+" ",i=[{content:e.name+" ( "}];for(let n=0;n<e.args.length;n++){const r=e.args[n],a=r.repeating;if(n>0&&i.push({content:o}),a){const a=r.optional||(t??0)>0,l=e.args.slice(n,n+e.nbrArgRepeating).map(e=>e.name);t&&i.push({content:"... "+o}),a&&i.push({content:"["});for(let e=0;e<l.length;e++){const r=l[e],a=n+e,c=s.includes(a);i.push({content:r+((t??0)+1),focused:c}),e<l.length-1&&i.push({content:o})}if(a&&i.push({content:"]"}),e.nbrArgRepeating<=1){i.push({content:o+"["});for(let e=0;e<l.length;e++){const s=l[e];i.push({content:s+((t??0)+2)}),e<l.length-1&&i.push({content:o})}i.push({content:"]"})}i.push({content:o+"... "}),n+=e.nbrArgRepeating-1}else{const e=r.optional||r.default,t=s.includes(n);e&&i.push({content:"["}),i.push({content:r.name,focused:t}),e&&i.push({content:"]"})}}return i.push({content:" )"}),i}}class RV extends t.Component{static template="o-spreadsheet-SpeechBubble";static props={content:String,anchorRect:Object};static components={};spreadsheetRect=ZL();bubbleRef=t.useRef("bubble");setup(){t.useEffect(()=>{const e=this.bubbleRef.el;if(!e)return;const t=this.props.anchorRect,s=FN(e),o=t.x+t.width/2-s.width/2-this.spreadsheetRect.x,i=t.y-s.height-7-this.spreadsheetRect.y;e.style.left=`${o}px`,e.style.top=`${i}px`})}}const TV=zf.content,AV=300;class _V extends t.Component{static template="o-spreadsheet-Composer";static props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},inputStyle:{type:String,optional:!0},rect:{type:Object,optional:!0},delimitation:{type:Object,optional:!0},onComposerCellFocused:{type:Function,optional:!0},onComposerContentFocused:Function,isDefaultFocus:{type:Boolean,optional:!0},onInputContextMenu:{type:Function,optional:!0},composerStore:Object,placeholder:{type:String,optional:!0},inputMode:{type:String,optional:!0},showAssistant:{type:Boolean,optional:!0}};static components={TextValueProvider:bV,FunctionDescriptionProvider:xV,SpeechBubble:RV};static defaultProps={inputStyle:"",isDefaultFocus:!1,inputMode:"text",showAssistant:!0};DOMFocusableElementStore;composerRef=t.useRef("o_composer");containerRef=t.useRef("composerContainer");contentHelper=new SV(this.composerRef.el);composerState=t.useState({positionStart:0,positionEnd:0,hoveredRect:void 0});functionDescriptionState=t.useState({showDescription:!1,functionDescription:{},argsToFocus:[],repeatingArgGroupIndex:0});assistant=t.useState({forcedClosed:!1});compositionActive=!1;spreadsheetRect=ZL();lastHoveredTokenIndex=void 0;debouncedHover=Fe((e,t)=>{const s=this.contentHelper.getCurrentSelection();if(s.start!==s.end)return;const o=this.props.composerStore.hoveredTokens;this.props.composerStore.hoverToken(e),Le(o,this.props.composerStore.hoveredTokens)||(this.composerState.hoveredRect=t)},120);get assistantStyleProperties(){const e=this.composerRef.el.getBoundingClientRect(),t={},s=Math.min(this.props.rect?.width||1/0,AV);t["min-width"]=`${s}px`;const o=this.props.composerStore.autoCompleteProposals,i=o?.some(e=>e.description);if((this.functionDescriptionState.showDescription||i)&&(t.width="300px"),this.props.delimitation&&this.props.rect){const{x:e,y:s,height:o}=this.props.rect,i=this.props.delimitation.height-(s+o);if(t["max-height"]=`${i}px`,s>i){const e=s;t["max-height"]=e-9+"px",t.top="-3px",t.transform="translate(0, -100%)"}e+AV>this.props.delimitation.width&&(t.right="0px")}else t["max-height"]=this.spreadsheetRect.height-e.bottom-1+"px",e.left+AV+15+9>this.spreadsheetRect.width&&(t.right="9px");return t}get assistantStyle(){const e=this.assistantStyleProperties;return JF({"max-height":e["max-height"],width:e.width,"min-width":e["min-width"]})}get assistantContainerStyle(){const e=this.assistantStyleProperties;return JF({top:e.top,right:e.right,transform:e.transform})}shouldProcessInputEvents=!1;tokens=[];keyMapping={Enter:e=>this.processEnterKey(e,"down"),"Shift+Enter":e=>this.processEnterKey(e,"up"),"Alt+Enter":this.processNewLineEvent,"Ctrl+Enter":this.processNewLineEvent,Escape:this.processEscapeKey,F2:e=>this.toggleEditionMode(e),F4:e=>this.processF4Key(e),Tab:e=>this.processTabKey(e,"right"),"Shift+Tab":e=>this.processTabKey(e,"left")};keyCodeMapping={NumpadDecimal:this.processNumpadDecimal};setup(){this.DOMFocusableElementStore=Tv(mV),t.onMounted(()=>{const e=this.composerRef.el;this.props.isDefaultFocus&&this.DOMFocusableElementStore.setFocusableElement(e),this.contentHelper.updateEl(e)}),t.onWillUnmount(()=>{this.debouncedHover.stopDebounce()}),t.useEffect(()=>{this.processContent(),document.activeElement!==this.contentHelper.el||"inactive"!==this.props.composerStore.editionMode||this.props.isDefaultFocus||this.DOMFocusableElementStore.focus()}),t.useEffect(()=>{this.processTokenAtCursor()},()=>["inactive"!==this.props.composerStore.editionMode]),t.useEffect(()=>{this.contentHelper.scrollSelectionIntoView()},()=>[this.props.composerStore.composerSelection.start,this.props.composerStore.composerSelection.end])}processArrowKeys(e){const t=this.props.composerStore.tokenAtCursor;if((this.props.composerStore.isSelectingRange||"inactive"===this.props.composerStore.editionMode)&&(!["ArrowUp","ArrowDown"].includes(e.key)||!this.props.composerStore.isAutoCompleteDisplayed||"REFERENCE"===t?.type))return this.functionDescriptionState.showDescription=!1,this.props.composerStore.hideHelp(),e.preventDefault(),e.stopPropagation(),void vV(e,this.env.model.selection);const s=this.props.composerStore.currentContent;"cellFocus"!==this.props.focus||this.props.composerStore.isAutoCompleteDisplayed||at(s)?(e.stopPropagation(),this.handleArrowKeysForAutocomplete(e)):this.props.composerStore.stopEdition()}handleArrowKeysForAutocomplete(e){["ArrowUp","ArrowDown"].includes(e.key)&&this.props.composerStore.isAutoCompleteDisplayed&&(e.preventDefault(),this.props.composerStore.moveAutoCompleteSelection("ArrowDown"===e.key?"next":"previous"))}processTabKey(e,t){e.preventDefault(),e.stopPropagation(),this.props.composerStore.autoCompleteOrStop(t,this.assistant.forcedClosed)}processEnterKey(e,t){e.preventDefault(),e.stopPropagation(),this.props.composerStore.autoCompleteOrStop(t,this.assistant.forcedClosed)}processNewLineEvent(e){e.preventDefault(),e.stopPropagation();const t=this.contentHelper.getText(),s=this.contentHelper.getCurrentSelection(),o=Math.min(s.start,s.end),i=Math.max(s.start,s.end);this.props.composerStore.stopComposerRangeSelection(),this.props.composerStore.setCurrentContent(t.slice(0,o)+Q+t.slice(i),{start:o+1,end:o+1}),this.processContent()}processEscapeKey(e){this.props.composerStore.cancelEdition(),e.stopPropagation(),e.preventDefault()}processF4Key(e){e.stopPropagation(),this.props.composerStore.cycleReferences(),this.processContent()}toggleEditionMode(e){e.stopPropagation(),this.props.composerStore.toggleEditionMode(),this.processContent()}processNumpadDecimal(e){e.stopPropagation(),e.preventDefault();const t=this.env.model.getters.getLocale(),s=this.contentHelper.getCurrentSelection(),o=this.props.composerStore.currentContent,i=o.slice(0,s.start)+t.decimalSeparator+o.slice(s.end);this.props.composerStore.setCurrentContent(i,{start:s.start+1,end:s.start+1}),this.processContent()}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){if("inactive"===this.props.composerStore.editionMode)return;if(e.key.startsWith("Arrow"))return void this.processArrowKeys(e);const t=this.keyMapping[LN(e)]||this.keyCodeMapping[LN(e,"code")];t?t.call(this,e):e.stopPropagation()}onPaste(e){"inactive"!==this.props.composerStore.editionMode?e.stopPropagation():e.preventDefault()}onInput(e){if(!this.shouldProcessInputEvents)return;let t;if(e.stopPropagation(),t="inactive"===this.props.composerStore.editionMode?e.data||"":this.contentHelper.getText(),"inactive"===this.props.focus)return this.props.onComposerCellFocused?.(t);const s=this.contentHelper.getCurrentSelection();this.props.composerStore.stopComposerRangeSelection(),this.props.composerStore.setCurrentContent(t,s),this.processTokenAtCursor()}onKeyup(e){if(this.contentHelper.el===document.activeElement){if(this.props.composerStore.isAutoCompleteDisplayed&&["ArrowUp","ArrowDown"].includes(e.key))return;if(this.props.composerStore.isSelectingRange&&e.key?.startsWith("Arrow"))return;const{start:t,end:s}=this.props.composerStore.composerSelection,{start:o,end:i}=this.contentHelper.getCurrentSelection();o===t&&i===s||this.props.composerStore.changeComposerCursorSelection(o,i),this.processTokenAtCursor()}}onBlur(e){if("inactive"===this.props.composerStore.editionMode)return;const t=e.relatedTarget;t&&t instanceof HTMLElement?this.containerRef.el?.contains(e.relatedTarget)||(t.attributes.getNamedItem("composerFocusableElement")?this.contentHelper.el.focus():t.classList.contains("o-composer")||this.props.composerStore.stopEdition()):this.props.composerStore.stopEdition()}onMousedown(e){e.button>0||this.env.isMobile()&&!GN()||(this.debouncedHover.stopDebounce(),this.contentHelper.removeSelection())}onMouseup(){if(this.env.model.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection();e.start!==e.end&&this.props.composerStore.hoverToken(void 0)}onClick(){if(this.env.model.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection(),t="inactive"===this.props.composerStore.editionMode;this.props.onComposerContentFocused(e),t||this.props.composerStore.changeComposerCursorSelection(e.start,e.end),this.processTokenAtCursor()}onDblClick(){if(this.env.model.getters.isReadonly())return;const e=this.props.composerStore.currentContent;if(at(e)){const t=this.props.composerStore.currentTokens,s=this.contentHelper.getCurrentSelection();if(s.start===s.end)return;const o=e.substring(s.start,s.end),i=t.filter(e=>e.value.includes(o)&&e.start<=s.start&&e.end>=s.end)[0];if(!i)return;"REFERENCE"===i.type&&this.props.composerStore.changeComposerCursorSelection(i.start,i.end)}}onContextMenu(e){"inactive"===this.props.composerStore.editionMode&&this.props.onInputContextMenu?.(e)}closeAssistant(){this.props.composerStore.canBeToggled&&(this.assistant.forcedClosed=!0)}openAssistant(){this.props.composerStore.canBeToggled&&(this.assistant.forcedClosed=!1)}onWheel(e){this.composerRef.el&&this.composerRef.el.scrollHeight>this.composerRef.el.clientHeight&&e.stopPropagation()}processContent(){if(this.compositionActive)return;this.shouldProcessInputEvents=!1,"inactive"!==this.props.focus&&document.activeElement!==this.contentHelper.el&&this.contentHelper.el.focus();const e=this.getContentLines();if(this.contentHelper.setText(e),0!==e.length&&0!==e.length[0]&&"inactive"!==this.props.focus){const{start:e,end:t}=this.props.composerStore.composerSelection;this.contentHelper.selectRange(e,t)}this.shouldProcessInputEvents=!0}getContentLines(){const e=this.props.composerStore.currentContent,t=at(e);return""===e?[]:t&&"inactive"!==this.props.focus?this.splitHtmlContentIntoLines(this.getHtmlContentFromTokens()):this.splitHtmlContentIntoLines([{value:e,classes:[]}])}getHtmlContentFromTokens(){const e=this.props.composerStore.currentTokens,t=[],{end:s,start:o}=this.props.composerStore.composerSelection;for(let i=0;i<e.length;i++){const n=e[i],r=[];"REFERENCE"===n.type&&this.props.composerStore.tokenAtCursor===n&&"selecting"===this.props.composerStore.editionMode&&r.push("text-decoration-underline"),s===o&&n.isParenthesisLinkedToCursor&&r.push("highlight-parenthesis-flag"),n.isInHoverContext&&r.push("highlight-flag"),this.props.composerStore.showSelectionIndicator&&s===o&&s===n.end&&r.push("selector-flag"),t.push({value:n.value,color:n.color||ne,opacity:n.isBlurred?.5:1,classes:r,onHover:e=>this.onTokenHover(i,e),onStopHover:()=>this.onTokenHover(void 0)})}return t}onTokenHover(e,t){this.lastHoveredTokenIndex!==e&&(this.lastHoveredTokenIndex=e,this.debouncedHover(e,t))}splitHtmlContentIntoLines(e){const t=[];let s=[];for(const o of e)if(o.value.includes(Q)){const e=o.value.split(Q),i=e.pop();for(const i of e)s.push({color:o.color,value:i}),t.push(s),s=[];s.push({...o,value:i})}else s.push(o);s.length&&t.push(s);const o=[];for(const e of t)e.every(this.isContentEmpty)?o.push([e[0]]):o.push(e.filter(e=>!this.isContentEmpty(e)));return o}isContentEmpty(e){return!(e.value||e.classes?.length)}processTokenAtCursor(){const e=this.props.composerStore;this.functionDescriptionState.showDescription=!1;const t=this.props.composerStore.tokenAtCursor;if(at(e.currentContent)&&t&&"SYMBOL"!==t.type){const e=t.functionContext,s=e?.parent.toUpperCase();if(e&&s&&s in TV&&"UNKNOWN"!==t.type){const o=TV[s],i=e.argPosition,n=e.args.length;this.functionDescriptionState.functionDescription=o;const r=this.props.composerStore.currentTokens.some(e=>"RIGHT_PAREN"===e.type&&e.parenthesesCode===t.parenthesesCode);this.functionDescriptionState.argsToFocus=this.getArgsToFocus(r,o,n,i),this.functionDescriptionState.showDescription=!0,this.functionDescriptionState.repeatingArgGroupIndex=this.getRepeatingArgGroupIndex(o,n,i)}}}getRepeatingArgGroupIndex(e,t,s){const{minArgRequired:o,maxArgPossible:i,nbrArgRepeating:n}=e;if(!n)return;const r=(n?Math.ceil((t-o)/n):0)*n+o;return ps(e,Math.max(Math.min(i,r),o))(s).repeatingGroupIndex??0}getArgsToFocus(e,t,s,o){const{nbrArgRepeating:i,minArgRequired:n,nbrOptionalNonRepeatingArgs:r,maxArgPossible:a}=t;if(e){const e=ps(t,Math.max(Math.min(a,s),n))(o)?.index;return void 0!==e?[e]:[]}const l=Math.max(s,n),c=i?n+Math.ceil((l-n)/i)*i+r:a,h=[];for(let e=l;e<=c;e++){const s=ps(t,e)(o)?.index;void 0!==s&&h.push(s)}return[...new Set(h)]}autoComplete(e){!e||this.assistant.forcedClosed&&this.props.composerStore.canBeToggled||(this.props.composerStore.insertAutoCompleteValue(e),this.processTokenAtCursor())}get displaySpeechBubble(){return!("inactive"===this.props.focus||!this.composerState.hoveredRect||!this.props.composerStore.hoveredContentEvaluation)}}function DV(e,t){return function(e){for(const t of e)if(t.functionContext){const{argsTokens:e,args:s}=t.functionContext;if(delete t.functionContext.argsTokens,s.length||!e)continue;"LEFT_PAREN"===e[0]?.[0]?.type&&(e[0]=e[0].slice(1));for(const t of e){let e=t;"ARG_SEPARATOR"===e.at(0)?.type&&(e=e.slice(1));try{s.push(ov(e))}catch(e){s.push(void 0)}}}return e}(function(e){const t=[];let s="";function o(e){if(0===t.length)return;const s=t.at(-1);if(s&&s.argsTokens){const{argsTokens:t,argPosition:o}=s;t[o]||(t[o]=[]),t[o].push({value:e.value,type:e.type})}}return e.map((e,i)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(s=""),e.type){case"SYMBOL":o(e),s=e.value;break;case"LEFT_PAREN":t.push({parent:s,argPosition:0,argsTokens:[],args:[]}),o(e),s="";break;case"RIGHT_PAREN":const i=t.pop();i?.argsTokens?.flat().forEach(o),o(e);break;case"ARG_SEPARATOR":t.length&&t[t.length-1].argPosition++,o(e);break;default:o(e)}if(t.length){const s=t[t.length-1];s.parent&&(e.functionContext=Object.assign({},s))}return e})}(function(e){const t=[];let s=0;return e.map((o,i)=>{if("LEFT_PAREN"===o.type){t.push(s+1),s=0;for(let s=i-1;s>=0;s--){if("SPACE"!==e[s].type){"SYMBOL"===e[s].type&&(e[s].parenthesesCode=t.join(":"));break}e[s].parenthesesCode=t.join(":")}}return o.parenthesesCode=t.join(":"),"RIGHT_PAREN"===o.type&&t.length&&(s=t.pop()),o})}(function(e){let t=0;return e.map(e=>{const s=e.value.toString().length,o=Object.assign({},e,{start:t,end:t+s,length:s});return t=o.end,o})}(qf(e,t)))))}class OV{lastId=0;add(e){this.lastId++;const t=this.lastId;return new Promise((s,o)=>{e.then(e=>{this.lastId===t&&s(e)}).catch(e=>{this.lastId===t&&o(e)})})}}function FV(e,t,s){const o=(t.startsWith("=")?DV(t,s):[]).filter(t=>t.start<=e.start&&t.end>=e.start||t.start>=e.start&&t.start<e.end),i=o.filter(e=>"REFERENCE"===e.type);if(0===i.length)return;const n=o.map(Ir).map(e=>e.value).join(""),r=o[0].start,a=o[o.length-1].end,l=t.slice(0,r)+n+t.slice(a),c=l.length-t.length,h={start:i[0].start,end:i[i.length-1].end+c};return 1===i.length&&e.start===e.end&&(h.start=h.end),{content:l,selection:h}}const PV=new Jg;function MV(e,t,s){const{x:i,y:n,width:r,height:a}=s;if(r<0||a<0)return;const l=t.color||o,{ctx:c}=e;c.save(),t.noBorder||(t.dashed&&c.setLineDash([5,3]),c.strokeStyle=l,t.thinLine?(c.lineWidth=1,c.strokeRect(i,n,r,a)):(c.lineWidth=2,c.strokeRect(i+.5,n+.5,r,a))),t.noFill||(c.fillStyle=ab(Yv(l),t.fillAlpha??.12),c.fillRect(i,n,r,a)),c.restore()}class NV extends Lv{mutators=["register","unRegister"];providers=[];constructor(e){super(e),this.onDispose(()=>{this.providers=[]})}get renderingLayers(){return["Highlights"]}get highlights(){const e=this.getters.getActiveSheetId();return this.providers.flatMap(e=>e.highlights).filter(t=>t.range.sheetId===e).map(e=>{const{numberOfRows:t,numberOfCols:s}=$t(e.range.zone),o=t*s===1?this.getters.expandZone(e.range.sheetId,e.range.zone):e.range.unboundedZone;return{...e,range:this.model.getters.getRangeFromZone(e.range.sheetId,o)}})}register(e){this.providers.push(e)}unRegister(e){this.providers=this.providers.filter(t=>t!==e)}drawLayer(e,t){if("Highlights"===t)for(const t of this.highlights){MV(e,t,this.getters.getVisibleRect(t.range.zone))}}}class kV{mutators=["notifyUser","raiseError","askConfirmation","updateNotificationCallbacks"];notifyUser=e=>window.alert(e.text);askConfirmation=(e,t,s)=>{window.confirm(e)?t():s?.()};raiseError=(e,t)=>{window.alert(e),t?.()};updateNotificationCallbacks(e){this.notifyUser=e.notifyUser||this.notifyUser,this.raiseError=e.raiseError||this.raiseError,this.askConfirmation=e.askConfirmation||this.askConfirmation}}class LV extends Lv{mutators=["useProvider","moveSelection","hide","selectIndex"];selectedIndex=void 0;provider;get selectedProposal(){if(void 0!==this.selectedIndex&&void 0!==this.provider)return this.provider.proposals[this.selectedIndex]}useProvider(e){this.provider=e,this.selectedIndex=e.autoSelectFirstProposal?0:void 0}hide(){this.provider=void 0,this.selectedIndex=void 0}selectIndex(e){this.selectedIndex=e}moveSelection(e){this.provider&&(void 0!==this.selectedIndex?"previous"===e?(this.selectedIndex--,this.selectedIndex<0&&(this.selectedIndex=this.provider.proposals.length-1)):this.selectedIndex=(this.selectedIndex+1)%this.provider.proposals.length:this.selectedIndex=0)}}class VV extends Lv{mutators=["startEdition","setCurrentContent","stopEdition","stopComposerRangeSelection","cancelEdition","cycleReferences","hideHelp","autoCompleteOrStop","insertAutoCompleteValue","moveAutoCompleteSelection","selectAutoCompleteIndex","toggleEditionMode","changeComposerCursorSelection","replaceComposerCursorSelection","hoverToken"];col=0;row=0;editionMode="inactive";sheetId="";_currentContent="";currentTokens=[];selectionStart=0;selectionEnd=0;initialContent="";colorIndexByRange={};autoComplete=new LV(this.get);hoveredTokens=[];hoveredContentEvaluation="";autoCompleteKeepLast=new OV;notificationStore=this.get(kV);highlightStore=this.get(NV);constructor(e){super(e),this.highlightStore.register(this),this.onDispose(()=>{this.highlightStore.unRegister(this),this._cancelEdition()})}handleEvent(e){this.hideHelp();const t=this.getters.getActiveSheetId();let s;if(s=e.options.unbounded?this.getters.getUnboundedZone(t,e.anchor.zone):e.anchor.zone,"newAnchor"===e.mode)"selecting"===this.editionMode&&this.insertSelectedRange(s);else"selecting"===this.editionMode?this.replaceSelectedRange(s):this.updateComposerRange(e.previousAnchor.zone,s)}changeComposerCursorSelection(e,t){this.isSelectionValid(this._currentContent.length,e,t)&&(this.selectionStart=e,this.selectionEnd=t,this.stopComposerRangeSelection(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor(),this.updateAutoCompleteProvider())}stopComposerRangeSelection(){this.isSelectingRange&&(this.editionMode="editing")}startEdition(e,t){const{col:s,row:o}=this.getters.getActivePosition();this.model.dispatch("SELECT_FIGURE",{figureId:null}),this.model.dispatch("SCROLL_TO_CELL",{col:s,row:o}),"inactive"!==this.editionMode&&e?this.setContent(e,t):this._startEdition(e,t),this.updateTokenColor(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor(),this.updateAutoCompleteProvider()}cancelEdition(){this.resetContent(),this.cancelEditionAndActivateSheet()}setCurrentContent(e,t){t&&!this.isSelectionValid(e.length,t.start,t.end)||(this.setContent(e,t,!0),this.updateTokenColor(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor())}replaceComposerCursorSelection(e){this.replaceSelection(e)}handle(e){switch(e.type){case"SELECT_FIGURE":e.figureId&&(this.resetContent(),this.cancelEditionAndActivateSheet());break;case"START_CHANGE_HIGHLIGHT":const{left:t,top:s}=e.zone;this.isSelectingRange&&(this.editionMode="editing"),this.model.selection.resetAnchor(this,{cell:{col:t,row:s},zone:e.zone})}}get currentContent(){return"inactive"===this.editionMode?this.getComposerContent(this.getters.getActivePosition()).text:this._currentContent}get composerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}get isSelectingRange(){return"selecting"===this.editionMode}get showSelectionIndicator(){return this.isSelectingRange&&this.canStartComposerRangeSelection()}get tokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find(s=>s.start<=e&&s.end>=t)}get autoCompleteProposals(){return this.autoComplete.provider?.proposals||[]}get autoCompleteSelectedIndex(){return this.autoComplete.selectedIndex}get isAutoCompleteDisplayed(){return!!this.autoComplete.provider}get canBeToggled(){return this.autoComplete.provider?.canBeToggled??!0}cycleReferences(){const e=this.getters.getLocale(),t=FV(this.composerSelection,this._currentContent,e);void 0!==t&&this.setCurrentContent(t.content,t.selection)}toggleEditionMode(){if("inactive"===this.editionMode)return;const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd),s=[...this.currentTokens].reverse().find(s=>s.end>=e&&t>=s.start&&"REFERENCE"===s.type);if("editing"===this.editionMode&&s){const e=this.getters.getActiveSheetId(),{sheetName:t,xc:o}=yr(s.value),i=this.getters.getSheetIdByName(t);i&&i!==e&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:i}),this.selectionStart=this.selectionEnd=s.end;const n=this.getters.getRangeFromSheetXC(this.sheetId,o).zone;this.captureSelection(n),this.editionMode="selecting"}else this.editionMode="editing"}hoverToken(e){this.currentTokens.forEach(e=>e.isInHoverContext=void 0);const t=[...this.currentTokens];if(void 0===e||["ARG_SEPARATOR","SPACE"].includes(t[e].type))return this.hoveredContentEvaluation="",void(this.hoveredTokens=[]);const s=this.getNumberOfMissingParenthesis(t);s>0&&t.push(...Array(s).fill({value:")",type:"RIGHT_PAREN"}));let o=t;if(0!==e){const s=this.getRelatedTokens(t,e),i=t.filter(e=>!s.includes(e)&&"SPACE"!==e.type);o=1===i.length&&i[0]===t[0]?t:s}o.forEach(e=>e.isInHoverContext=!0);let i=o.map(e=>e.value).join("");at(i)||(i=`=${i}`);const n=vh(i,this.getters.getLocale()),r=this.getters.evaluateFormulaResult(this.sheetId,n);this.hoveredTokens=o,this.hoveredContentEvaluation=mn(r,"0",this.getters.getLocale())}getRelatedTokens(e,t){try{const s=ov(e);let o;for(const e of nv(s))if(t>=e.tokenStartIndex&&t<=e.tokenEndIndex)o=e;else if(t<e.tokenStartIndex)break;return o?e.slice(o.tokenStartIndex,o.tokenEndIndex+1):e}catch(t){if(t instanceof xs)return e;throw t}}captureSelection(e,t,s){this.model.selection.capture(this,{cell:{col:t??e.left,row:s??e.right},zone:e},{handleEvent:this.handleEvent.bind(this),release:()=>{this._stopEdition()}})}isSelectionValid(e,t,s){return t>=0&&t<=e&&s>=0&&s<=e}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=Jt({col:this.col,row:this.row});this.model.selection.resetAnchor(this,{cell:{col:this.col,row:this.row},zone:e})}this.editionMode="selecting"}_startEdition(e,t){const s=this.getters.getActiveCell(),o=this.getters.getLocale();e&&s.format?.includes("%")&&mo(e,o)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const{col:i,row:n,sheetId:r}=this.getters.getActivePosition();this.col=i,this.sheetId=r,this.row=n,this.editionMode="editing";const{text:a,adjustedSelection:l}=this.getComposerContent({sheetId:r,col:i,row:n},t);this.initialContent=a,this.setContent(e||this.initialContent,l??t),this.colorIndexByRange={};const c=Jt({col:this.col,row:this.row});this.captureSelection(c,i,n)}_stopEdition(){if("inactive"!==this.editionMode){this.cancelEditionAndActivateSheet();let e=this.getCurrentCanonicalContent();if(!(this.initialContent!==e))return;if(e&&at(e)){const t=this.getNumberOfMissingParenthesis(this.currentTokens);t>0&&(e+=Pe(new Array(t).fill(")")))}this.confirmEdition(e)}}getCurrentCanonicalContent(){return vh(this._currentContent,this.getters.getLocale())}cancelEditionAndActivateSheet(){if("inactive"===this.editionMode)return;this._cancelEdition();this.getters.getActiveSheetId()!==this.sheetId&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}_cancelEdition(){"inactive"!==this.editionMode&&(this.editionMode="inactive",this.model.selection.release(this),this.colorIndexByRange={},this.hoveredTokens=[],this.hoveredContentEvaluation="")}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,s){const o=this._currentContent!==e;if(this._currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,o||"inactive"!==this.editionMode){const t=this.getters.getLocale();this.currentTokens=at(e)?DV(e,t):[];this.currentTokens.filter(e=>"SPACE"!==e.type).length>1e3&&s&&this.notificationStore.raiseError(Cs("This formula has over 1000 parts. It can't be processed properly, consider splitting it into multiple cells"))}this.canStartComposerRangeSelection()&&this.startComposerRangeSelection(),this.updateAutoCompleteProvider()}getAutoCompleteProviders(){return PV.getAll()}insertSelectedRange(e){const t=Math.min(this.selectionStart,this.selectionEnd),s=this.getZoneReference(e);this.canStartComposerRangeSelection()?this.insertText(s,t):this.insertText(","+s,t)}replaceSelectedRange(e){const t=this.getZoneReference(e),s=this.tokenAtCursor,o="REFERENCE"===s?.type?s.start:this.selectionStart;this.replaceText(t,o,this.selectionEnd)}updateComposerRange(e,t){const s=this.getters.getActiveSheetId(),o=this.tokenAtCursor,i=(o?[o,...this.currentTokens]:this.currentTokens).filter(e=>"REFERENCE"===e.type).find(t=>{const{xc:o,sheetName:i}=yr(t.value),n=i||this.getters.getSheetName(this.sheetId);if(!fS(this.getters.getSheetName(s),n))return!1;const r=this.getters.getRangeFromSheetXC(s,o);return Ht(this.getters.expandZone(s,r.zone),e)});if(!i)return;const n=this.getters.getRangeFromSheetXC(s,i.value);this.selectionStart=i.start,this.selectionEnd=this.selectionStart+i.value.length;const r=this.getters.getRangeFromZone(s,t),a=this.getRangeReference(r,n.parts);this.replaceSelection(a)}getZoneReference(e){const t=this.sheetId,s=this.getters.getActiveSheetId(),o=this.getters.getRangeFromZone(s,e);return this.getters.getSelectionRangeString(o,t)}getRangeReference(e,t){const s={...e,parts:[...t]};return this.getters.getSelectionRangeString(s,this.sheetId)}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),s=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,s)}replaceText(e,t,s){this._currentContent=this._currentContent.slice(0,t)+this._currentContent.slice(s,this._currentContent.length),this.insertText(e,t)}insertText(e,t){const s=this._currentContent.slice(0,t)+e+this._currentContent.slice(t),o=t+e.length;this.setCurrentContent(s,{start:o,end:o})}updateTokenColor(){this.updateRangeColor();for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].color=this.getTokenColor(this.currentTokens[e])}getTokenColor(e){if("REFERENCE"===e.type){const{xc:t,sheetName:s}=yr(e.value);return this.rangeColor(t,s)||ne}if("SYMBOL"===e.type){const t=e.value.toUpperCase();if("TRUE"===t||"FALSE"===t)return ae.NUMBER;if(t in zf.content)return ae.FUNCTION}return["LEFT_PAREN","RIGHT_PAREN"].includes(e.type)&&""===e.parenthesesCode?ae.ORPHAN_RIGHT_PAREN:ae[e.type]||ne}rangeColor(e,t){const s=t?this.model.getters.getSheetIdByName(t):this.sheetId,o=this.highlights.find(t=>{if(t.range.sheetId!==s)return!1;let o=this.model.getters.getRangeFromSheetXC(s,e).zone;return o=1===ss(o)?this.model.getters.expandZone(s,o):o,Ht(o,t.range.zone)});return o&&o.color?o.color:void 0}computeFormulaCursorContext(){for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].isBlurred=!1;if(this.selectionStart!==this.selectionEnd)return;const e=this.getParenthesesCodeAfterCursor(),t=[...this.currentTokens].reverse().find(t=>e.startsWith(t.parenthesesCode)&&"SYMBOL"===t.type);if(t)for(let e=0;e<this.currentTokens.length;e++)(this.currentTokens[e].parenthesesCode||"").startsWith(t.parenthesesCode||"")||(this.currentTokens[e].isBlurred=!0)}getParenthesesCodeAfterCursor(){const e=this.tokenAtCursor?.parenthesesCode||"";return"RIGHT_PAREN"===this.tokenAtCursor?.type?e.slice(0,-1)||"":e}computeParenthesisRelatedToCursor(){for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].isParenthesisLinkedToCursor=!1;const e=this.tokenAtCursor;if(e&&""!==e.parenthesesCode&&["LEFT_PAREN","RIGHT_PAREN"].includes(e.type))for(let t=0;t<this.currentTokens.length;t++){const s=this.currentTokens[t];["LEFT_PAREN","RIGHT_PAREN"].includes(s.type)&&s.parenthesesCode===e.parenthesesCode&&s!==e&&(this.currentTokens[t].isParenthesisLinkedToCursor=!0,this.tokenAtCursor.isParenthesisLinkedToCursor=!0)}}updateRangeColor(){if(!at(this._currentContent)||"inactive"===this.editionMode)return;const e=this.sheetId,t=this.getReferencedRanges().map(t=>this.getters.getRangeString(t,e)),s={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(s[e]=this.colorIndexByRange[e]);const o=new Set(Object.values(s));let i=0;const n=()=>{for(;o.has(i);)i++;return o.add(i),i};for(const e of t){const t=e in s?s[e]:n();s[e]=t}this.colorIndexByRange=s}get highlights(){if(!at(this.currentContent)||"inactive"===this.editionMode)return[];const e=this.sheetId,t=e=>{const t=this.colorIndexByRange[e];return qv[t%qv.length]};return this.getReferencedRanges().map(s=>{const o=this.getters.getRangeString(s,e),{numberOfRows:i,numberOfCols:n}=$t(s.zone),r=i*n===1?this.getters.expandZone(s.sheetId,s.zone):s.unboundedZone;return{range:this.model.getters.getRangeFromZone(s.sheetId,r),color:t(o),interactive:!0}})}getReferencedRanges(){const e=this.sheetId;return this.currentTokens.filter(e=>"REFERENCE"===e.type).map(t=>this.getters.getRangeFromSheetXC(e,t.value)).filter(e=>!e.invalidSheetName&&!e.invalidXc)}async updateAutoCompleteProvider(){this.autoComplete.hide();const e=await this.autoCompleteKeepLast.add(this.findAutocompleteProvider());e&&(this.autoComplete.useProvider(e),this.model.trigger("update"))}async findAutocompleteProvider(){const e=this.currentContent,t=at(e)?this.tokenAtCursor:{type:"STRING",value:e};if("inactive"===this.editionMode||!t||["TRUE","FALSE"].includes(t.value.toUpperCase())||!this.canStartComposerRangeSelection()&&!["SYMBOL","STRING","UNKNOWN"].includes(t.type))return;const s={composer:this,getters:this.getters},o=this.getAutoCompleteProviders().sort((e,t)=>(e.sequence??1/0)-(t.sequence??1/0)).map(o=>({...o,getProposals:o.getProposals.bind(s,t,e),selectProposal:o.selectProposal.bind(s,t)}));for(const e of o){let s=await e.getProposals();const o=s?.find(e=>e.text===t.value),i=t.value.replace(/[ ,\(\)]/g,"");if(this._currentContent===this.initialContent&&e.displayAllOnInitialContent&&s?.length)return{proposals:s,selectProposal:e.selectProposal,autoSelectFirstProposal:e.autoSelectFirstProposal??!1,canBeToggled:e.canBeToggled};if(o&&this._currentContent!==this.initialContent)return;if(i&&s&&!["ARG_SEPARATOR","LEFT_PAREN","OPERATOR"].includes(t.type)){const e=LS(i,s,e=>e.fuzzySearchKey||e.text);o&&!e.length||(s=e)}if(e.maxDisplayedProposals&&(s=s?.slice(0,e.maxDisplayedProposals)),s?.length)return{proposals:s,selectProposal:e.selectProposal,autoSelectFirstProposal:e.autoSelectFirstProposal??!1,canBeToggled:e.canBeToggled}}}hideHelp(){this.autoComplete.hide()}autoCompleteOrStop(e,t=!1){if("inactive"!==this.editionMode){const s=this.autoComplete;if(!(t&&this.canBeToggled)&&s.provider&&void 0!==s.selectedIndex){const e=s.provider.proposals[s.selectedIndex]?.text;if(e)return void this.autoComplete.provider?.selectProposal(e)}this.stopEdition(e)}}insertAutoCompleteValue(e){this.autoComplete.provider?.selectProposal(e)}selectAutoCompleteIndex(e){this.autoComplete.selectIndex(me(0,e,10))}moveAutoCompleteSelection(e){this.autoComplete.moveSelection(e)}canStartComposerRangeSelection(){if(at(this._currentContent)){const e=this.tokenAtCursor;if(!e)return!1;const t=this.currentTokens.map(e=>e.start).indexOf(e.start);let s=t,o=e;for(;!["ARG_SEPARATOR","ARRAY_ROW_SEPARATOR","LEFT_PAREN","LEFT_BRACE","OPERATOR"].includes(o.type)||Yc.includes(o.value);){if("SPACE"!==o.type||s<1)return!1;s--,o=this.currentTokens[s]}for(s=t+1,o=this.currentTokens[s];o&&!["ARG_SEPARATOR","ARRAY_ROW_SEPARATOR","RIGHT_PAREN","RIGHT_BRACE","OPERATOR"].includes(o.type);){if("SPACE"!==o.type)return!1;s++,o=this.currentTokens[s]}return!0}return!1}getNumberOfMissingParenthesis(e){return e.filter(e=>"LEFT_PAREN"===e.type).length-e.filter(e=>"RIGHT_PAREN"===e.type).length}}class zV extends VV{args;constructor(e,t){super(e),this.args=t,this._currentContent=this.getComposerContent().text}getAutoCompleteProviders(){const e=super.getAutoCompleteProviders(),t=this.args().contextualAutocomplete;return t&&e.push(t),e}getZoneReference(e){const t=super.getZoneReference(e);return this.args().defaultStatic?Er(t,"colrow"):t}getComposerContent(){let e=this._currentContent;if("inactive"===this.editionMode){const t=this.args().defaultRangeSheetId;e=qf(this.args().content).map(e=>{if("REFERENCE"===e.type){const s=this.getters.getRangeFromSheetXC(t,e.value);return this.getters.getRangeString(s,this.getters.getActiveSheetId())}return e.value}).join("")}return{text:Sh(e,this.getters.getLocale())}}stopEdition(){this._stopEdition()}confirmEdition(e){this.args().onConfirm(e)}getTokenColor(e){if("SYMBOL"===e.type){const t=this.args().getContextualColoredSymbolToken?.(e);if(t)return t}return super.getTokenColor(e)}}class HV extends t.Component{static template="o-spreadsheet-StandaloneComposer";static props={composerContent:{type:String,optional:!0},defaultRangeSheetId:{type:String,optional:!0},defaultStatic:{type:Boolean,optional:!0},onConfirm:Function,contextualAutocomplete:{type:Object,optional:!0},placeholder:{type:String,optional:!0},title:{type:String,optional:!0},class:{type:String,optional:!0},invalid:{type:Boolean,optional:!0},autofocus:{type:Boolean,optional:!0},getContextualColoredSymbolToken:{type:Function,optional:!0}};static components={Composer:_V};static defaultProps={composerContent:"",defaultStatic:!1};composerFocusStore;standaloneComposerStore;composerInterface;spreadsheetRect=ZL();setup(){this.composerFocusStore=Tv(zv);const e=Av(zV,()=>({onConfirm:this.props.onConfirm,content:this.props.composerContent,defaultStatic:this.props.defaultStatic??!1,contextualAutocomplete:this.props.contextualAutocomplete,defaultRangeSheetId:this.props.defaultRangeSheetId,getContextualColoredSymbolToken:this.props.getContextualColoredSymbolToken}));this.standaloneComposerStore=e,this.composerInterface={id:"standaloneComposer",get editionMode(){return e.editionMode},startEdition:this.standaloneComposerStore.startEdition,setCurrentContent:this.standaloneComposerStore.setCurrentContent,stopEdition:this.standaloneComposerStore.stopEdition},t.onMounted(()=>{this.props.autofocus&&"inactive"===this.focus&&(this.composerFocusStore.focusComposer(this.composerInterface,{}),this.composerFocusStore.activeComposer.editionMode)})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get composerStyle(){return this.props.invalid?JF({padding:"1px 0px 0px 0px"}):JF({padding:"1px 0px"})}get containerClass(){return["inactive"===this.focus?"":"active",this.props.invalid?"o-invalid":"",this.props.class||""].join(" ")}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}}class UV extends t.Component{static template="o-spreadsheet-CriterionInput";static props={value:{type:String,optional:!0},criterionType:String,onValueChanged:Function,onKeyDown:{type:Function,optional:!0},focused:{type:Boolean,optional:!0},onBlur:{type:Function,optional:!0},onFocus:{type:Function,optional:!0},disableFormulas:{type:Boolean,optional:!0}};static defaultProps={value:"",onKeyDown:()=>{},focused:!1,onBlur:()=>{}};static components={StandaloneComposer:HV};inputRef=t.useRef("input");setup(){t.useEffect(()=>{this.props.focused&&this.inputRef.el&&this.inputRef.el.focus()},()=>[this.props.focused,this.inputRef.el])}state=t.useState({shouldDisplayError:!!this.props.value});get placeholder(){return"onlyFormulas"===this.allowedValues?Cs("Formula"):"onlyLiterals"===this.allowedValues?Cs("Value"):Cs("Value or formula")}get allowedValues(){const e=W_.get(this.props.criterionType);if("onlyFormulas"===e.allowedValues&&this.props.disableFormulas)throw new Error(`Cannot disable formulas for criterion type ${this.props.criterionType} that accept only formulas`);return(this.props.disableFormulas?"onlyLiterals":e.allowedValues)??"any"}onInputValueChanged(e){this.state.shouldDisplayError=!0,this.props.onValueChanged(e.target.value)}onChangeComposerValue(e){this.state.shouldDisplayError=!0,this.props.onValueChanged(e)}getDataValidationRuleInputComposerProps(){return{onConfirm:e=>this.onChangeComposerValue(e),composerContent:this.props.value,placeholder:this.placeholder,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId(),invalid:this.state.shouldDisplayError&&!!this.errorMessage,defaultStatic:!0,autofocus:this.props.focused}}get errorMessage(){if(this.state.shouldDisplayError)return this.env.model.getters.getDataValidationInvalidCriterionValueMessage(this.props.criterionType,bh(this.props.value,this.env.model.getters.getLocale()))}}const BV={today:Cs("today"),yesterday:Cs("yesterday"),tomorrow:Cs("tomorrow"),lastWeek:Cs("in the past week"),lastMonth:Cs("in the past month"),lastYear:Cs("in the past year"),exactDate:Cs("exact date")};class GV extends pV{static template="o-spreadsheet-DataValidationDateCriterion";static components={CriterionInput:UV};get currentDateValue(){return this.props.criterion.dateValue||"exactDate"}onValueChanged(e){this.updateCriterion({values:[e],dateValue:this.currentDateValue})}onDateValueChanged(e){const t=e.target.value;this.updateCriterion({dateValue:t})}get dateValues(){return Object.keys(BV).map(e=>({value:e,title:BV[e]}))}}class WV extends pV{static template="o-spreadsheet-DoubleInputCriterionForm";static components={CriterionInput:UV};onFirstValueChanged(e){const t=this.props.criterion.values;this.updateCriterion({values:[e,t[1]||""]})}onSecondValueChanged(e){const t=this.props.criterion.values;this.updateCriterion({values:[t[0]||"",e]})}}class $V extends pV{static template="o-spreadsheet-SingleInputCriterionForm";static components={CriterionInput:UV};onValueChanged(e){const t=he(this.props.criterion);t.values[0]=e,this.updateCriterion(t)}}function qV(e,t){const s=()=>{window.removeEventListener("pointerup",o,{capture:!0}),window.removeEventListener("dragstart",i),window.removeEventListener("pointermove",e),window.removeEventListener("wheel",e)},o=e=>{t(e),s()};function i(e){e.preventDefault()}return window.addEventListener("pointerup",o,{capture:!0}),window.addEventListener("dragstart",i),window.addEventListener("pointermove",e),window.addEventListener("wheel",e,{passive:!1}),s}const ZV=216;class jV extends t.Component{static template="o-spreadsheet-ColorPicker";static props={onColorPicked:Function,currentColor:{type:String,optional:!0},maxHeight:{type:Number,optional:!0},anchorRect:Object,disableNoColor:{type:Boolean,optional:!0}};static defaultProps={currentColor:""};static components={Popover:jL};COLORS=D;state=t.useState({showGradient:!1,currentHslaColor:Xv(this.props.currentColor)?{...nb(this.props.currentColor),a:1}:{h:0,s:100,l:100,a:1},customHexColor:Xv(this.props.currentColor)?Yv(this.props.currentColor):""});get colorPickerStyle(){return void 0!==this.props.maxHeight&&this.props.maxHeight<=0?JF({display:"none"}):""}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"bottom-left",verticalOffset:0}}get gradientHueStyle(){return JF({background:`hsl(${this.state.currentHslaColor?.h||0} 100% 50%)`})}get sliderStyle(){const e=this.state.currentHslaColor?.h||0;return JF({"margin-left":`${me(Math.round(e/360*ZV),1,ZV)-9}px`})}get pointerStyle(){const{s:e,l:t}=this.state.currentHslaColor||{s:0,l:0};return JF({left:`${-8+Math.round(ZV*me(e/100,0,1))}px`,top:`${-8+Math.round(186*me(1-2*t/(200-e),0,1))}px`,background:ib(this.state.currentHslaColor)})}get colorPreviewStyle(){return JF({"background-color":ib(this.state.currentHslaColor)})}get checkmarkColor(){return Uy(this.props.currentColor)}get isHexColorInputValid(){return!this.state.customHexColor||Xv(this.state.customHexColor)}setCustomGradient({x:e,y:t}){const s=me(e,0,ZV),o=me(t,0,186),i=s/ZV,n=100*i,r=100*(1-o/186)*(1-.5*i);this.updateColor({s:n,l:r})}setCustomHue(e){const t=Math.round(me(360*e/ZV,0,359));this.updateColor({h:t})}updateColor(e){this.state.currentHslaColor={...this.state.currentHslaColor,...e},this.state.customHexColor=ib(this.state.currentHslaColor)}onColorClick(e){e&&this.props.onColorPicked(Yv(e))}resetColor(){this.props.onColorPicked("")}toggleColorPicker(){this.state.showGradient=!this.state.showGradient}dragGradientPointer(e){const t={x:e.offsetX,y:e.offsetY};this.setCustomGradient(t);const s=e.clientX,o=e.clientY;qV(e=>{const i=e.clientX,n=e.clientY,r={x:t.x+(i-s),y:t.y+(n-o)};this.setCustomGradient(r)},()=>{})}dragHuePointer(e){const t=e.offsetX,s=e.clientX;this.setCustomHue(t);qV(e=>{const o=e.clientX,i=t+(o-s);this.setCustomHue(i)},()=>{})}setHexColor(e){const t=e.target.value.replace("##","#").slice(0,7);this.state.customHexColor=t,Xv(t)&&(this.state.currentHslaColor={...nb(t),a:1})}addCustomColor(e){(function(e){try{return ib(e),!0}catch(e){return!1}})(this.state.currentHslaColor)&&Xv(this.state.customHexColor)&&this.props.onColorPicked(Yv(this.state.customHexColor))}isSameColor(e,t){return function(e,t,s=0){if(!Xv(e)||!Xv(t))return!1;const o=tb(e),i=tb(t);return o.a===i.a&&Math.sqrt(((o.r-i.r)/255)**2+((o.g-i.g)/255)**2+((o.b-i.b)/255)**2)<=s}(e,t)}}class YV extends t.Component{static template="o_spreadsheet.Section";static props={class:{type:String,optional:!0},title:{type:String,optional:!0},slots:Object}}class XV extends t.Component{static template="o-spreadsheet.RoundColorPicker";static components={Section:YV,ColorPicker:jV};static props={currentColor:{type:String,optional:!0},title:{type:String,optional:!0},onColorPicked:Function,disableNoColor:{type:Boolean,optional:!0}};colorPickerButtonRef=t.useRef("colorPickerButton");state;setup(){this.state=t.useState({pickerOpened:!1}),t.useExternalListener(window,"click",this.closePicker)}closePicker(){this.state.pickerOpened=!1}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.props.onColorPicked(e),this.state.pickerOpened=!1}get colorPickerAnchorRect(){return FN(this.colorPickerButtonRef.el)}get buttonStyle(){return JF({background:this.props.currentColor})}}function KV(){let e;const s=document.body.style.cursor;let o=[];const i=()=>{e=void 0,document.body.style.cursor=s,o.forEach(e=>e()),o=[]};t.onWillUnmount(()=>{i()});const n=t.useState({itemsStyle:{},draggedItemId:void 0,start:(t,r)=>{n.cancel=()=>{n.draggedItemId=void 0,n.itemsStyle={},document.body.style.cursor=s,r.onCancel?.(),i()};document.body.style.cursor="move",n.draggedItemId=r.draggedItemId;const a="horizontal"===t?new tz(r.scrollableContainerEl):new ez(r.scrollableContainerEl);e=new JV({...r,container:a,onChange:()=>{document.body.style.cursor="move",e&&(Object.assign(n.itemsStyle,e.getItemStyles()),r.onChange?.())},onDragEnd:(e,t)=>{n.draggedItemId=void 0,n.itemsStyle={},document.body.style.cursor=s,r.onDragEnd?.(e,t),i()},onCancel:n.cancel});const l=qV(e.onMouseMove.bind(e),e.onMouseUp.bind(e));o.push(l);const c=e.onScroll.bind(e);r.scrollableContainerEl.addEventListener("scroll",c),o.push(()=>r.scrollableContainerEl.removeEventListener("scroll",c)),o.push(e.destroy.bind(e))},cancel:()=>{}});return n}class JV{draggedItemId;items;container;initialMousePosition;currentMousePosition;initialScroll;minPosition;maxPosition;edgeScrollIntervalId;onChange;onCancel;onDragEnd;deadZone;constructor(e){this.items=e.items.map(e=>({...e,positionAtStart:e.position})),this.draggedItemId=e.draggedItemId,this.container=e.container,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onDragEnd=e.onDragEnd,this.initialMousePosition=e.initialMousePosition,this.currentMousePosition=e.initialMousePosition,this.initialScroll=this.container.scroll,this.minPosition=this.items[0].position,this.maxPosition=this.items[this.items.length-1].position+this.items[this.items.length-1].size}getItemStyles(){const e={};for(const t of this.items)e[t.id]=this.getItemStyle(t.id);return e}getItemStyle(e){const t=this.container.cssPositionProperty,s={position:"relative"};return s[t]=(this.getItemsPositions()[e]||0)+"px",s.transition=`${t} 0.5s`,s["pointer-events"]="none",this.draggedItemId===e&&(s.transition=`${t} 0s`,s["z-index"]="1000"),JF(s)}onScroll(){this.moveDraggedItemToPosition(this.currentMousePosition+this.scrollOffset)}onMouseMove(e){if(e.button>1)return void this.onCancel();const t=this.container.getMousePosition(e);this.currentMousePosition=t,t<this.container.start||t>this.container.end?this.startEdgeScroll(t<this.container.start?-1:1):(this.stopEdgeScroll(),this.moveDraggedItemToPosition(t+this.scrollOffset))}moveDraggedItemToPosition(e){const t=this.getHoveredItemIndex(e,this.items),s=this.items.findIndex(e=>e.id===this.draggedItemId),o=this.items[s];if(this.deadZone&&this.isInZone(e,this.deadZone))return void this.onChange(this.getItemsPositions());if(this.isInZone(e,{start:o.position,end:o.position+o.size})&&(this.deadZone=void 0),s===t)return void this.onChange(this.getItemsPositions());const i=Math.min(s,t),n=Math.max(s,t),r=Math.sign(t-s);let a=0;for(let e=i;e<=n;e++)e!==s&&(this.items[e].position-=r*o.size,a+=this.items[e].size);o.position+=r*a,this.items.sort((e,t)=>e.position-t.position),this.deadZone=r>0?{start:e,end:o.position}:{start:o.position+o.size,end:e},this.onChange(this.getItemsPositions())}onMouseUp(e){0!==e.button&&this.onCancel(),e.stopPropagation(),e.preventDefault();const t=this.items.findIndex(e=>e.id===this.draggedItemId);return this.onDragEnd(this.draggedItemId,t),this.stopEdgeScroll(),!1}startEdgeScroll(e){this.edgeScrollIntervalId||(this.edgeScrollIntervalId=window.setInterval(()=>{const t=3*e;this.container.scroll+=t},5))}stopEdgeScroll(){window.clearInterval(this.edgeScrollIntervalId),this.edgeScrollIntervalId=void 0}getHoveredItemIndex(e,t){return e<=this.minPosition?0:e>=this.maxPosition?t.length-1:t.findIndex(t=>t.position+t.size>=e)}getItemsPositions(){const e={};for(const t of this.items){if(t.id!==this.draggedItemId){e[t.id]=t.position-t.positionAtStart;continue}let s=this.currentMousePosition-this.initialMousePosition+this.scrollOffset;s=Math.max(this.minPosition-t.positionAtStart,s),s=Math.min(this.maxPosition-t.positionAtStart-t.size,s),e[t.id]=s}return e}isInZone(e,t){return e>=t.start&&e<=t.end}get scrollOffset(){return this.container.scroll-this.initialScroll}destroy(){this.stopEdgeScroll()}}class QV{el;constructor(e){this.el=e}get containerRect(){return this.el.getBoundingClientRect()}}class ez extends QV{get start(){return this.containerRect.top}get end(){return this.containerRect.bottom}get cssPositionProperty(){return"top"}get scroll(){return this.el.scrollTop}set scroll(e){this.el.scrollTop=e}getMousePosition(e){return e.clientY}}class tz extends QV{get start(){return this.containerRect.left}get end(){return this.containerRect.right}get cssPositionProperty(){return"left"}get scroll(){return this.el.scrollLeft}set scroll(e){this.el.scrollLeft=e}getMousePosition(e){return e.clientX}}class sz{mutators=["focus","unfocus"];focusedElement=null;focus(e){this.focusedElement=e}unfocus(e){this.focusedElement&&this.focusedElement===e&&(this.focusedElement=null)}}class oz extends Lv{initialRanges;inputHasSingleRange;colors;disabledRanges;mutators=["resetWithRanges","focusById","unfocus","addEmptyRange","removeRange","changeRange","reset","confirm","updateColors","updateDisabledRanges"];ranges=[];focusedRangeIndex=null;inputSheetId;focusStore=this.get(sz);highlightStore=this.get(NV);constructor(e,t=[],s=!1,o=[],i=[]){if(super(e),this.initialRanges=t,this.inputHasSingleRange=s,this.colors=o,this.disabledRanges=i,s&&t.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");this.inputSheetId=this.getters.getActiveSheetId(),this.resetWithRanges(t),this.highlightStore.register(this),this.onDispose(()=>{this.unfocus(),this.highlightStore.unRegister(this)})}handleEvent(e){if(null===this.focusedRangeIndex)return;const t=this.inputSheetId,s=this.getters.getActiveSheetId(),o=e.options.unbounded?this.getters.getUnboundedZone(s,e.anchor.zone):e.anchor.zone,i=this.getters.getRangeFromZone(s,o);if("newAnchor"===e.mode&&!this.inputHasSingleRange&&""!==this.ranges[this.focusedRangeIndex].xc.trim()){const e=this.getters.getSelectionRangeString(i,t);this.insertNewRange(this.ranges.length,[e]),this.focusLast()}else{let e=i.parts;const s=this.ranges[this.focusedRangeIndex].xc.trim();s&&(e=this.getters.getRangeFromSheetXC(t,s).parts);const o={...i,parts:e},n=this.getters.getSelectionRangeString(o,t);this.setRange(this.focusedRangeIndex,[n])}}handle(e){switch(e.type){case"ACTIVATE_SHEET":if(e.sheetIdFrom!==e.sheetIdTo){const{col:t,row:s}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),o=this.getters.expandZone(e.sheetIdTo,Jt({col:t,row:s}));this.model.selection.resetAnchor(this,{cell:{col:t,row:s},zone:o})}break;case"START_CHANGE_HIGHLIGHT":const t=this.getters.getActiveSheetId(),s=this.getters.expandZone(t,e.zone),o=this.ranges.findIndex(e=>{const{xc:o,sheetName:i}=yr(e.xc),n=i||this.getters.getSheetName(this.inputSheetId);if(this.getters.getSheetName(t)!==n)return!1;const r=this.getters.getRangeFromSheetXC(t,o);return Ht(this.getters.expandZone(t,r.zone),s)});if(-1!==o){this.focus(o);const{left:e,top:t}=s;this.model.selection.resetAnchor(this,{cell:{col:e,row:t},zone:s})}}}changeRange(e,t){if(this.inputHasSingleRange&&t.split(",").length>1)return;const s=this.getIndex(e);if(null!==s&&this.focusedRangeIndex!==s&&this.focus(s),null!==s){const e=t.replace(/^,+/,"").split(",").map(e=>e.trim());this.setRange(s,e),this.captureSelection()}}addEmptyRange(){this.inputHasSingleRange&&1===this.ranges.length||(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}removeRange(e){if(1===this.ranges.length)return;const t=this.getIndex(e);null!==t&&this.removeRangeByIndex(t)}updateColors(e){this.colors=e;const t=new yb(this.ranges.length,this.colors);this.ranges=this.ranges.map(e=>({...e,color:t.next()}))}updateDisabledRanges(e){this.disabledRanges=e}confirm(){for(const e of this.selectionInputs)""===e.xc&&this.removeRange(e.id);const e=this.getters.getActiveSheetId();this.inputSheetId!==e&&this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:this.inputSheetId}),this.selectionInputValues.join()!==this.initialRanges.join()&&this.resetWithRanges(this.selectionInputValues),this.initialRanges=this.selectionInputValues,this.unfocus()}reset(){this.resetWithRanges(this.initialRanges),this.confirm()}get selectionInputValues(){return this.cleanInputs(this.ranges.map(e=>e.xc?e.xc:""))}get selectionInputs(){return this.ranges.map((e,t)=>Object.assign({},e,{color:this.hasMainFocus&&null!==this.focusedRangeIndex&&this.getters.isRangeValid(e.xc)?e.color:null,isFocused:this.hasMainFocus&&this.focusedRangeIndex===t,isValidRange:""===e.xc||this.getters.isRangeValid(e.xc),disabled:this.disabledRanges?.[t]}))}get isResettable(){return this.initialRanges.join()!==this.ranges.map(e=>e.xc).join()}get isConfirmable(){return this.selectionInputs.every(e=>e.isValidRange)}get hasFocus(){return this.selectionInputs.some(e=>e.isFocused)}get hasMainFocus(){const e=this.focusStore.focusedElement;return!!e&&e===this}get highlights(){return this.hasMainFocus?this.ranges.map(e=>this.inputToHighlights(e)).flat():[]}focusById(e){this.focus(this.getIndex(e))}focus(e){this.focusStore.focus(this),this.focusedRangeIndex=e,this.captureSelection()}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null,this.focusStore.unfocus(this),this.model.selection.release(this)}captureSelection(){if(null===this.focusedRangeIndex)return;const e=this.ranges[this.focusedRangeIndex],t=this.getters.getActiveSheetId(),s=this.getters.getRangeFromSheetXC(t,e?.xc||"A1").zone;this.model.selection.capture(this,{cell:{col:s.left,row:s.top},zone:s},{handleEvent:this.handleEvent.bind(this),release:this.unfocus.bind(this)})}resetWithRanges(e){e.length&&e.every(e=>this.getters.isRangeValid(e))&&(this.initialRanges=e),this.ranges=[],this.insertNewRange(0,e),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){const s=Math.max(0,...this.ranges.map(e=>Number(e.id))),o=new yb(this.ranges.length,this.colors);for(let t=0;t<e;t++)o.next();this.ranges.splice(e,0,...t.map((e,t)=>({xc:e,id:s+t+1,color:o.next()})))}setRange(e,t){const[,...s]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,s),s.length&&this.focus(e+s.length)}removeRangeByIndex(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const s=this.cleanInputs([e]).filter(e=>this.getters.isRangeValid(e)).filter(e=>this.shouldBeHighlighted(this.inputSheetId,e));return s.map(e=>{const{sheetName:s}=yr(e),o=s&&this.getters.getSheetIdByName(s)||this.inputSheetId;return{range:this.getters.getRangeFromSheetXC(o,e),color:t,interactive:!0}})}cleanInputs(e){return e.map(e=>e.split(",")).flat().map(e=>e.trim()).filter(e=>""!==e)}shouldBeHighlighted(e,t){const{sheetName:s}=yr(t),o=this.getters.getSheetIdByName(s),i=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(o===i||void 0===o&&i===e)}getIndex(e){const t=this.ranges.findIndex(t=>t.id===e);return t>=0?t:null}}class iz extends t.Component{static template="o-spreadsheet-SelectionInput";static props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},required:{type:Boolean,optional:!0},autofocus:{type:Boolean,optional:!0},isInvalid:{type:Boolean,optional:!0},class:{type:String,optional:!0},onSelectionChanged:{type:Function,optional:!0},onSelectionConfirmed:{type:Function,optional:!0},onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},colors:{type:Array,optional:!0,default:[]},disabledRanges:{type:Array,optional:!0,default:[]},disabledRangeTitle:{type:String,optional:!0}};state=t.useState({isMissing:!1,mode:"select-range"});dragAndDrop=KV();focusedInput=t.useRef("focusedInput");selectionRef=t.useRef("o-selection");store;get ranges(){return this.store.selectionInputs}get canAddRange(){return!this.props.hasSingleRange}get isInvalid(){return this.props.isInvalid||this.state.isMissing}get isConfirmable(){return this.store.isConfirmable}get isResettable(){return this.store.isResettable}get hasDisabledRanges(){return this.store.disabledRanges.some(Boolean)}setup(){t.useEffect(()=>this.focusedInput.el?.focus(),()=>[this.focusedInput.el]),t.useEffect(()=>{this.store.hasFocus&&null===this.selectionRef.el?.offsetParent&&this.reset()}),this.store=Av(oz,this.props.ranges,this.props.hasSingleRange||!1,this.props.colors,this.props.disabledRanges),this.props.autofocus&&this.store.focusById(this.store.selectionInputs[0]?.id),t.onWillUpdateProps(e=>{e.ranges.join()!==this.store.selectionInputValues.join()&&this.triggerChange(),e.ranges.join()!==this.props.ranges.join()&&e.ranges.join()!==this.store.selectionInputValues.join()&&this.store.resetWithRanges(e.ranges),e.colors?.join()!==this.props.colors?.join()&&e.colors?.join()!==this.store.colors.join()&&this.store.updateColors(e.colors||[]),Le(e.disabledRanges,this.props.disabledRanges)||Le(e.disabledRanges,this.store.disabledRanges)||this.store.updateDisabledRanges(e.disabledRanges||[])})}startDragAndDrop(e,t){if(0!==t.button||"SELECT"===t.target.tagName)return;const s=this.getRangeElementsRects(),o=this.ranges.map(e=>e.id),i=o.map((e,t)=>({id:e.toString(),size:s[t].height,position:s[t].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.toString(),initialMousePosition:t.clientY,items:i,scrollableContainerEl:this.selectionRef.el,onDragEnd:(t,s)=>{const i=o.findIndex(t=>t===e);if(i===s)return;const n=fe(0,o.length);n.splice(i,1),n.splice(s,0,i),this.props.onSelectionReordered?.(n),this.props.onSelectionConfirmed?.(),this.store.confirm()}})}getRangeElementsRects(){return Array.from(this.selectionRef.el.children).map(e=>e.getBoundingClientRect())}getColor(e){return e.color?JF({color:e.color}):""}triggerChange(){const e=this.store.selectionInputValues;this.props.onSelectionChanged?.(e)}onKeydown(e){if("F2"===e.key)e.preventDefault(),e.stopPropagation(),this.state.mode="select-range"===this.state.mode?"text-edit":"select-range";else if(e.key.startsWith("Arrow"))e.stopPropagation(),"select-range"===this.state.mode&&(e.preventDefault(),vV(e,this.env.model.selection));else if("Enter"===e.key){e.target.blur(),this.isConfirmable&&this.confirm()}}extractRanges(e){return this.props.hasSingleRange?e.split(",")[0]:e}focus(e){this.state.isMissing=!1,this.state.mode="select-range",this.store.focusById(e)}addEmptyInput(){this.store.addEmptyRange()}removeInput(e){const t=this.store.selectionInputs.findIndex(t=>t.id===e);this.ranges.find(t=>t.id===e)?.xc&&(this.props.onSelectionRemoved?.(t),this.props.onSelectionConfirmed?.()),this.store.removeRange(e)}onInputChanged(e,t){const s=t.target,o=this.extractRanges(s.value);this.store.changeRange(e,o),this.triggerChange()}reset(){this.store.reset(),this.triggerChange()}confirm(){this.store.confirm();const e=this.store.selectionInputs.some(e=>this.env.model.getters.isRangeValid(e.xc));this.props.required&&!e&&(this.state.isMissing=!0),this.props.onSelectionChanged?.(this.store.selectionInputValues),this.props.onSelectionConfirmed?.()}}const nz={list:10,text:20,number:30,date:40,misc:50},rz=new Jg;function az(e,t){const s=rz.getAll().filter(e=>t.has(e.type)).sort((e,t)=>e.category===t.category?e.sequence-t.sequence:nz[e.category]-nz[t.category]);return Sv(s.map((t,o)=>({name:W_.get(t.type).name,id:t.type,separator:t.category!==s[o+1]?.category,execute:()=>e(t.type)})))}rz.add("containsText",{type:"containsText",component:$V,category:"text",sequence:10}),rz.add("notContainsText",{type:"notContainsText",component:$V,category:"text",sequence:20}),rz.add("beginsWithText",{type:"beginsWithText",component:$V,category:"text",sequence:25}),rz.add("endsWithText",{type:"endsWithText",component:$V,category:"text",sequence:26}),rz.add("isEqualText",{type:"isEqualText",component:$V,category:"text",sequence:30}),rz.add("isEmail",{type:"isEmail",component:void 0,category:"text",sequence:40}),rz.add("isLink",{type:"isLink",component:void 0,category:"text",sequence:50}),rz.add("dateIs",{type:"dateIs",component:GV,category:"date",sequence:20}),rz.add("dateIsBefore",{type:"dateIsBefore",component:GV,category:"date",sequence:30}),rz.add("dateIsOnOrBefore",{type:"dateIsOnOrBefore",component:GV,category:"date",sequence:40}),rz.add("dateIsAfter",{type:"dateIsAfter",component:GV,category:"date",sequence:50}),rz.add("dateIsOnOrAfter",{type:"dateIsOnOrAfter",component:GV,category:"date",sequence:60}),rz.add("dateIsBetween",{type:"dateIsBetween",component:WV,category:"date",sequence:70}),rz.add("dateIsNotBetween",{type:"dateIsNotBetween",component:WV,category:"date",sequence:80}),rz.add("dateIsValid",{type:"dateIsValid",component:void 0,category:"date",sequence:10}),rz.add("isEqual",{type:"isEqual",component:$V,category:"number",sequence:10}),rz.add("isNotEqual",{type:"isNotEqual",component:$V,category:"number",sequence:20}),rz.add("isGreaterThan",{type:"isGreaterThan",component:$V,category:"number",sequence:50}),rz.add("isGreaterOrEqualTo",{type:"isGreaterOrEqualTo",component:$V,category:"number",sequence:60}),rz.add("isLessThan",{type:"isLessThan",component:$V,category:"number",sequence:30}),rz.add("isLessOrEqualTo",{type:"isLessOrEqualTo",component:$V,category:"number",sequence:40}),rz.add("isBetween",{type:"isBetween",component:WV,category:"number",sequence:70}),rz.add("isNotBetween",{type:"isNotBetween",component:WV,category:"number",sequence:80}),rz.add("isBoolean",{type:"isBoolean",component:void 0,category:"misc",sequence:10}),rz.add("isValueInList",{type:"isValueInList",component:class extends pV{static template="o-spreadsheet-ListCriterionForm";static components={CriterionInput:UV,RoundColorPicker:XV};state=t.useState({numberOfValues:Math.max(this.props.criterion.values.length,2),focusedValueIndex:this.props.autofocus?0:void 0});setup(){super.setup();const e=e=>{void 0===e.criterion.displayStyle&&this.updateCriterion({displayStyle:"chip"})};t.onWillUpdateProps(e),t.onWillStart(()=>e(this.props))}onValueChanged(e,t){const s=[...this.displayedValues];s[t]=e,this.updateCriterion({values:s})}onColorChanged(e,t){const s={...this.props.criterion.colors};s[t]=e||void 0,this.updateCriterion({colors:s})}onAddAnotherValue(){this.state.numberOfValues++}removeItem(e){const t=[...this.displayedValues];t.splice(e,1),this.state.numberOfValues--,this.updateCriterion({values:t})}onChangedDisplayStyle(e){const t=e.target.value;this.updateCriterion({displayStyle:t})}onKeyDown(e,t){"Enter"!==e.key&&"Tab"!==e.key||t!==this.state.numberOfValues-1?"Enter"===e.key&&(this.state.focusedValueIndex=t+1):(this.onAddAnotherValue(),this.state.focusedValueIndex=t+1,e.preventDefault())}onBlurInput(){this.state.focusedValueIndex=void 0}get displayedValues(){const e=[];for(let t=0;t<this.state.numberOfValues;t++)e.push(this.props.criterion.values[t]||"");return e}},category:"list",sequence:10}),rz.add("isValueInRange",{type:"isValueInRange",component:class extends pV{static template="o-spreadsheet-ValueInRangeCriterionForm";static components={RoundColorPicker:XV,SelectionInput:iz};setup(){super.setup();const e=e=>{void 0===e.criterion.displayStyle&&this.updateCriterion({displayStyle:"chip"})};t.onWillUpdateProps(e),t.onWillStart(()=>e(this.props))}onRangeChanged(e){this.updateCriterion({values:[e]})}onChangedDisplayStyle(e){const t=e.target.value;this.updateCriterion({displayStyle:t})}onColorChanged(e,t){const s={...this.props.criterion.colors};s[t]=e||void 0,this.updateCriterion({colors:s})}get values(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getDataValidationRangeValues(e,this.props.criterion);return new Set(t)}},category:"list",sequence:20}),rz.add("customFormula",{type:"customFormula",component:$V,category:"misc",sequence:20}),rz.add("isEmpty",{type:"isEmpty",component:void 0,category:"misc",sequence:5}),rz.add("isNotEmpty",{type:"isNotEmpty",component:void 0,category:"misc",sequence:6});class lz extends t.Component{static template="o-spreadsheet-SelectMenu";static props={menuItems:Array,selectedValue:String,class:{type:String,optional:!0}};static components={MenuPopover:JL};menuId=(new Tr).uuidv4();selectRef=t.useRef("select");state=t.useState({isMenuOpen:!1});onClick(e){e.closedMenuId!==this.menuId&&(this.state.isMenuOpen=!this.state.isMenuOpen)}onMenuClosed(){this.state.isMenuOpen=!1}get menuAnchorRect(){return ON(this.selectRef)}}class cz extends t.Component{static template="o-spreadsheet-FilterMenuCriterion";static props={filterPosition:Object,onCriterionChanged:Function,criterionOperators:Array};static components={SelectMenu:lz};state;setup(){t.onWillUpdateProps(e=>{Le(e.filterPosition,this.props.filterPosition)||(this.state.criterion=this.getFilterCriterionValue(e.filterPosition))}),this.state=t.useState({criterion:this.getFilterCriterionValue(this.props.filterPosition)})}getFilterCriterionValue(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getFilterCriterionValue({sheetId:t,...e});return"criterion"===s?.filterType?he(s):{filterType:"criterion",type:"none",values:[]}}get criterionMenuItems(){return[Cv({name:Cs("None"),id:"none",separator:!0,execute:()=>this.onCriterionTypeChange("none")}),...az(e=>this.onCriterionTypeChange(e),new Set(this.props.criterionOperators))]}get selectedCriterionName(){return"none"===this.state.criterion.type?Cs("None"):W_.get(this.state.criterion.type).name}get criterionComponent(){return"none"===this.state.criterion.type?void 0:rz.get(this.state.criterion.type).component}onCriterionChanged(e){this.state.criterion.values=e.values,this.state.criterion.dateValue=e.dateValue,this.props.onCriterionChanged(this.state.criterion)}onCriterionTypeChange(e){this.state.criterion.type=e,this.props.onCriterionChanged(this.state.criterion)}}class hz extends t.Component{static template="o-spreadsheet.Checkbox";static props={label:{type:String,optional:!0},value:{type:Boolean,optional:!0},className:{type:String,optional:!0},name:{type:String,optional:!0},title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},onChange:Function};static defaultProps={value:!1};onChange(e){const t=e.target.checked;this.props.onChange(t)}}class dz extends t.Component{static template="o-spreadsheet-FilterMenuValueItem";static components={Checkbox:hz};static props={value:String,isChecked:Boolean,isSelected:Boolean,onMouseMove:Function,onClick:Function,scrolledTo:{type:String,optional:!0}};itemRef=t.useRef("menuValueItem");setup(){t.onWillPatch(()=>{this.props.scrolledTo&&this.scrollListToSelectedValue()})}scrollListToSelectedValue(){this.itemRef.el&&this.itemRef.el.scrollIntoView?.({block:"bottom"===this.props.scrolledTo?"end":"start"})}}class uz extends t.Component{static template="o-spreadsheet-FilterMenuValueList";static props={filterPosition:Object,onUpdateHiddenValues:Function};static components={FilterMenuValueItem:dz};state=t.useState({values:[],displayedValues:[],textFilter:"",selectedValue:void 0,numberOfDisplayedValues:50,hasMoreValues:!1});searchBar=t.useRef("filterMenuSearchBar");setup(){t.onWillUpdateProps(e=>{Le(e.filterPosition,this.props.filterPosition)||(this.state.values=this.getFilterHiddenValues(e.filterPosition),this.computeDisplayedValues())}),this.state.values=this.getFilterHiddenValues(this.props.filterPosition),this.computeDisplayedValues()}getFilterHiddenValues(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getFilter({sheetId:t,...e});if(!s)return[];const o=this.env.model.getters.getFilterValue({sheetId:t,...e});let i=(s.filteredRange?Zt(s.filteredRange.zone):[]).map(e=>({position:e,cellValue:this.env.model.getters.getEvaluatedCell({sheetId:t,...e}).formattedValue}));"criterion"!==o?.filterType&&(i=i.filter(e=>!this.env.model.getters.isRowHidden(t,e.position.row)));const n=i.map(e=>e.cellValue),r="values"===o?.filterType?o.hiddenValues:[],a=new Set(r.map(OS)),l=new Set,c=[],h=e=>{const t=OS(e);l.has(t)||(c.push({string:e||"",checked:"criterion"!==o?.filterType&&!a.has(t),normalizedValue:t}),l.add(t))};return n.forEach(h),r.forEach(h),c.sort((e,t)=>e.normalizedValue.localeCompare(t.normalizedValue,void 0,{numeric:!0,sensitivity:"base"}))}checkValue(e){this.state.selectedValue=e.string,e.checked=!e.checked,this.searchBar.el?.focus(),this.updateHiddenValues()}onMouseMove(e){this.state.selectedValue=e.string}selectAll(){this.state.displayedValues.forEach(e=>e.checked=!0),this.props.onUpdateHiddenValues([])}clearAll(){this.state.displayedValues.forEach(e=>e.checked=!1);const e=this.state.values.map(e=>e.string);this.props.onUpdateHiddenValues(e)}updateHiddenValues(){const e=this.state.values.filter(e=>!e.checked).map(e=>e.string);this.props.onUpdateHiddenValues(e)}updateSearch(e){const t=e.target;this.state.textFilter=t.value,this.state.selectedValue=void 0,this.computeDisplayedValues()}computeDisplayedValues(){const e=this.state.textFilter?LS(this.state.textFilter,this.state.values,e=>e.string):this.state.values;this.state.displayedValues=e.slice(0,this.state.numberOfDisplayedValues),this.state.hasMoreValues=e.length>this.state.numberOfDisplayedValues}loadMoreValues(){this.state.numberOfDisplayedValues+=100,this.computeDisplayedValues()}onKeyDown(e){const t=this.state.displayedValues;if(0===t.length)return;let s;if(void 0!==this.state.selectedValue){const e=t.findIndex(e=>e.string===this.state.selectedValue);s=-1===e?void 0:e}switch(e.key){case"ArrowDown":s=void 0===s?0:Math.min(s+1,t.length-1),e.preventDefault(),e.stopPropagation();break;case"ArrowUp":s=void 0===s?t.length-1:Math.max(s-1,0),e.preventDefault(),e.stopPropagation();break;case"Enter":void 0!==s&&this.checkValue(t[s]),e.stopPropagation(),e.preventDefault()}this.state.selectedValue=void 0!==s?t[s].string:void 0,"ArrowUp"!==e.key&&"ArrowDown"!==e.key||this.scrollListToSelectedValue(e.key)}clearScrolledToValue(){this.state.values.forEach(e=>e.scrolledTo=void 0)}scrollListToSelectedValue(e){this.clearScrolledToValue();const t=this.state.values.find(e=>e.string===this.state.selectedValue);t&&(t.scrolledTo="ArrowUp"===e?"top":"bottom")}}class gz extends t.Component{static template="o-spreadsheet-FilterMenu";static props={filterPosition:Object,onClosed:{type:Function,optional:!0}};static components={FilterMenuValueList:uz,SidePanelCollapsible:gV,FilterMenuCriterion:cz};criterionCategory="text";updatedCriterionValue;setup(){t.onWillUpdateProps(e=>{Le(e.filterPosition,this.props.filterPosition)||(this.updatedCriterionValue=void 0,this.criterionCategory=this.getCriterionCategory(e.filterPosition))}),this.criterionCategory=this.getCriterionCategory(this.props.filterPosition)}get isSortable(){if(!this.table)return!1;const e=this.env.model.getters.getCoreTableMatchingTopLeft(this.table.range.sheetId,this.table.range.zone);return!this.env.model.getters.isReadonly()&&"dynamic"!==e?.type}get table(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition;return this.env.model.getters.getTable({sheetId:e,...t})}get filterValueType(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition,s=this.env.model.getters.getFilterValue({sheetId:e,...t});return s?.filterType}getCriterionCategory(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getFilter({sheetId:t,...e});if(!s||!s.filteredRange)return"text";const o={text:0,number:0,date:0},i=s.filteredRange.zone;for(let s=i.top;s<=i.bottom&&!(s>100);s++){const i=this.env.model.getters.getEvaluatedCell({sheetId:t,row:s,col:e.col});i.type===Xd.text||i.type===Xd.boolean?o.text++:i.type===Xd.number&&(i.format&&ji(i.format)?o.date++:o.number++)}const n=Math.max(o.text,o.number,o.date);return Object.keys(o).find(e=>o[e]===n)||"text"}onUpdateHiddenValues(e){this.updatedCriterionValue={filterType:"values",hiddenValues:e}}onCriterionChanged(e){this.updatedCriterionValue=e}confirm(){if(!this.updatedCriterionValue)return void this.props.onClosed?.();const e=this.props.filterPosition;this.env.model.dispatch("UPDATE_FILTER",{...e,sheetId:this.env.model.getters.getActiveSheetId(),value:this.updatedCriterionValue}),this.props.onClosed?.()}get criterionOperators(){return"date"===this.criterionCategory?JN:"number"===this.criterionCategory?KN:XN}cancel(){this.props.onClosed?.()}sortFilterZone(e){const t=this.props.filterPosition,s=this.table,o=s?.range.zone;if(!t||!o||o.top===o.bottom)return;const i=this.env.model.getters.getActiveSheetId(),n={...o,top:o.top+1},r={col:t.col,row:n.top};dV(this.env,i,r,n,e,{emptyCellAsZero:!0,sortHeaders:!0}),this.props.onClosed?.()}}const pz={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:gz,cellCorner:"bottom-left"})};class mz extends t.Component{static template="o-spreadsheet-LinkDisplay";static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};cellPopovers;setup(){this.cellPopovers=Tv(aV)}get cell(){const{col:e,row:t}=this.props.cellPosition,s=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getEvaluatedCell({sheetId:s,col:e,row:t})}get link(){if(this.cell.link)return this.cell.link;const{col:e,row:t}=this.props.cellPosition;throw new Error(`LinkDisplay Component can only be used with link cells. ${St(e,t)} is not a link.`)}getUrlRepresentation(e){return fv(e,this.env.model.getters)}openLink(e){vv(this.link,this.env,HN(e))}edit(){const{col:e,row:t}=this.props.cellPosition;this.env.model.selection.selectCell(e,t),this.cellPopovers.open({col:e,row:t},"LinkEditor")}unlink(){const e=this.env.model.getters.getActiveSheetId(),{col:t,row:s}=this.props.cellPosition,o=this.env.model.getters.getCellComputedStyle({sheetId:e,col:t,row:s}),i=o?.textColor===d?void 0:o?.textColor;this.env.model.dispatch("UPDATE_CELL",{col:t,row:s,sheetId:e,content:this.link.label,style:{...o,textColor:i,underline:void 0}})}}const fz={onHover:(e,t)=>{const s=t.getEvaluatedCell(e);return!t.isDashboard()&&s.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:mz,props:{cellPosition:e},cellCorner:"bottom-left"}:{isOpen:!1}}},vz={name:Cs("Link sheet"),children:[e=>e.model.getters.getSheetIds().map(t=>e.model.getters.getSheet(t)).map(e=>({id:e.id,name:e.name,execute:()=>Ee(e.name,Ae(e.id))}))]},bz={name:Cs("Delete"),isVisible:e=>e.model.getters.getVisibleSheetIds().length>1,execute:e=>e.askConfirmation(Cs("Are you sure you want to delete this sheet?"),()=>{e.model.dispatch("DELETE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName()})}),icon:"o-spreadsheet-Icon.TRASH"},Sz={name:Cs("Duplicate"),execute:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSheetName(t),o=e.model.uuidGenerator.smallUuid(),i=e.model.getters.getDuplicateSheetName(s);e.model.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:o,sheetNameTo:i}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},icon:"o-spreadsheet-Icon.COPY"},yz=e=>({name:Cs("Rename"),execute:e.renameSheetCallback,icon:"o-spreadsheet-Icon.RENAME_SHEET"}),Cz=e=>({name:Cs("Change color"),execute:e.openSheetColorPickerCallback,icon:"o-spreadsheet-Icon.PAINT_FORMAT"}),Iz={name:Cs("Move right"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getVisibleSheetIds();return s.indexOf(t)!==s.length-1},execute:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:1}),icon:"o-spreadsheet-Icon.MOVE_SHEET_RIGHT"},wz={name:Cs("Move left"),isVisible:e=>{const t=e.model.getters.getActiveSheetId();return e.model.getters.getVisibleSheetIds()[0]!==t},execute:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:-1}),icon:"o-spreadsheet-Icon.MOVE_SHEET_LEFT"},Ez={name:Cs("Hide sheet"),isVisible:e=>1!==e.model.getters.getVisibleSheetIds().length,execute:e=>e.model.dispatch("HIDE_SHEET",{sheetId:e.model.getters.getActiveSheetId()}),icon:"o-spreadsheet-Icon.HIDE_SHEET"};class xz extends Jg{replace(e,t){return void 0===t.id&&(t.id=e),this.content[e]=t,this}addChild(e,t,s){return this._replaceChild(e,t,s,{force:!1})}replaceChild(e,t,s){return this._replaceChild(e,t,s,{force:!0})}_replaceChild(e,t,s,o={force:!0}){"function"!=typeof s&&void 0===s.id&&(s.id=e);const i=t.splice(0,1)[0];let n=this.content[i];if(!n)throw new Error(`Path ${i+":"+t.join(":")} not found`);for(const e of t){const s=n.children;if(!s||"function"==typeof s)throw new Error(`${e} is either not a node or it's dynamically computed`);if(n=s.find(t=>t.id===e),!n)throw new Error(`Path ${i+":"+t.join(":")} not found`)}n.children||(n.children=[]);const r=n.children;if(!r||"function"==typeof r)throw new Error(`${t} is either not a node or it's dynamically computed`);if("id"in s){const e=r.findIndex(e=>"id"in e&&e.id===s.id);if(e>-1){if(!o.force)throw new Error(`A child with the id "${s.id}" already exists.`);return n.children.splice(e,1,s),this}}return n.children.push(s),this}getMenuItems(){return Sv(this.getAll())}}const Rz=new xz;Rz.add("sheet",{...vz,sequence:10});class Tz extends t.Component{static template="o-spreadsheet-LinkEditor";static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};static components={MenuPopover:JL};menuItems=Rz.getMenuItems();link=t.useState(this.defaultState);menu=t.useState({isOpen:!1});linkEditorMenuButtonRef=t.useRef("linkEditorMenuButton");urlInput=t.useRef("urlInput");setup(){t.onMounted(()=>this.urlInput.el?.focus())}get defaultState(){const{col:e,row:t}=this.props.cellPosition,s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getEvaluatedCell({sheetId:s,col:e,row:t});return o.link?{url:o.link.url,label:o.formattedValue,isUrlEditable:o.link.isUrlEditable}:{label:o.formattedValue,url:"",isUrlEditable:!0}}get menuButtonRect(){return ON(this.linkEditorMenuButtonRef)}onSpecialLink(e){const{detail:t}=e,s=bv(t);s&&(this.link.url=s.url,this.link.label=s.label,this.link.isUrlEditable=s.isUrlEditable)}getUrlRepresentation(e){return fv(e,this.env.model.getters)}openMenu(){this.menu.isOpen=!0}removeLink(){this.link.url="",this.link.isUrlEditable=!0}save(){const{col:e,row:t}=this.props.cellPosition,s=this.env.model.getters.getLocale(),o=this.link.label?vh(this.link.label,s):this.link.url;this.env.model.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:this.env.model.getters.getActiveSheetId(),content:Ee(o,this.link.url)}),this.props.onClosed?.()}cancel(){this.props.onClosed?.()}onKeyDown(e){switch(e.key){case"Enter":this.link.url&&this.save(),e.stopPropagation(),e.preventDefault();break;case"Escape":this.cancel(),e.stopPropagation()}}}const Az={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:Tz,cellCorner:"bottom-left"})};rV.add("ErrorToolTip",cV).add("LinkCell",fz).add("LinkEditor",Az).add("FilterMenu",pz);const _z={type:"bar",title:{},dataSets:[],legendPosition:"none",dataSetsHaveTitle:!1,stacked:!1},Dz={type:"line",title:{},dataSets:[],legendPosition:"none",dataSetsHaveTitle:!1,stacked:!1,cumulative:!1,labelsAsText:!1};function Oz(e,t){return Pt(e.getUnboundedZone(e.getActiveSheetId(),t))}function Fz(e){if(!e.length)return"empty";const t={number:0,text:0,date:0,percentage:0};let s=0,o="empty";for(const i of e){let e=null;if(i.type===Xd.number?e=i.format&&ji(i.format)?"date":i.format?.includes("%")?"percentage":"number":i.type===Xd.text&&(e="text"),e){const i=++t[e];i>s&&(s=i,o=e)}}return o}function Pz(e,t){const s=[];for(const o of function(e){const t=new Map;for(const s of e)for(let e=s.left;e<=s.right;e++){const o=t.get(e);o?(o.top=Math.min(o.top,s.top),o.bottom=Math.max(o.bottom,s.bottom)):t.set(e,{left:e,right:e,top:s.top,bottom:s.bottom})}return Array.from(t.values())}(e)){const e=t.getEvaluatedCellsInZone(t.getActiveSheetId(),o);s.push({zone:o,type:Fz(e)})}return s}function Mz(e,t){const s=e.getEvaluatedCell({sheetId:e.getActiveSheetId(),col:t.zone.left,row:t.zone.top});return![Xd.number,Xd.empty].includes(s.type)}function Nz(e,t){const{type:s,zone:o}=e,i=t.getActiveSheetId(),n=Mz(t,e),r=Oz(t,o),a=t.getEvaluatedCell({sheetId:i,col:o.left,row:o.top});if(1===ss(o))return function(e,t){const s=t.getCellStyle({sheetId:t.getActiveSheetId(),col:e.left,row:e.top});return{type:"scorecard",title:{},keyValue:Oz(t,e),background:s?.fillColor,baselineMode:$,baselineColorUp:q,baselineColorDown:Z}}(o,t);switch(s){case"percentage":return{type:"pie",title:n?{text:String(a.value)}:{},dataSets:[{dataRange:r}],legendPosition:"none",dataSetsHaveTitle:n};case"text":const e=t.getEvaluatedCellsInZone(i,o).reduce((e,t)=>t.value===a.value?e+1:e,0),s=null!==a.value&&1===e;return{type:"pie",title:s?{text:String(a.value)}:{},dataSets:[{dataRange:r}],labelRange:r,dataSetsHaveTitle:s,aggregated:!0,legendPosition:"top"};case"date":return{...Dz,type:"line",title:n?{text:String(a.value)}:{},dataSets:[{dataRange:r}],dataSetsHaveTitle:n}}return{..._z,title:n?{text:String(a.value)}:{},dataSets:[{dataRange:r}],dataSetsHaveTitle:n}}function kz(e,t){if(2!==e.length)throw new Error("buildTwoColumnChart expects exactly two columns");if("percentage"===e[1].type)return{type:"pie",title:{},dataSets:[{dataRange:Oz(t,e[1].zone)}],labelRange:Oz(t,e[0].zone),dataSetsHaveTitle:Mz(t,e[1]),aggregated:!0,legendPosition:"none"};if("number"===e[0].type&&"number"===e[1].type)return{type:"scatter",title:{},dataSets:[{dataRange:Oz(t,e[1].zone)}],labelRange:Oz(t,e[0].zone),dataSetsHaveTitle:Mz(t,e[1]),labelsAsText:!1,legendPosition:"none"};if("date"===e[0].type&&"number"===e[1].type)return{...Dz,type:"line",dataSets:[{dataRange:Oz(t,e[1].zone)}],labelRange:Oz(t,e[0].zone),dataSetsHaveTitle:Mz(t,e[0])};if("text"===e[0].type&&"number"===e[1].type){const s=e[0],o=e[1],{uniqueCount:i,totalCount:n}=function(e,t){const s=e.getEvaluatedCellsInZone(e.getActiveSheetId(),t).map(e=>e.value?.toString().trim()||"").filter(e=>e);return{uniqueCount:new Set(s).size,totalCount:s.length}}(t,s.zone),r=Mz(t,o);if(i!==n)return{type:"treemap",title:{},dataSets:[{dataRange:Oz(t,s.zone)}],labelRange:Oz(t,o.zone),dataSetsHaveTitle:r,legendPosition:"none"}}return{..._z,dataSets:[{dataRange:Oz(t,e[1].zone)}],labelRange:Oz(t,e[0].zone),dataSetsHaveTitle:Mz(t,e[1])}}function Lz(e,t){const s=Pz(e,t);if(0===s.length||s.every(e=>"empty"===e.type)){const e=s.map(({zone:e})=>({dataRange:Oz(t,e)}));return{..._z,dataSets:e}}const o=s.filter(e=>"empty"!==e.type);switch(o.length){case 1:return Nz(o[0],t);case 2:return kz(o,t);default:return function(e,t){if(e.length<3)throw new Error("buildMultiColumnChart expects at least three columns");const s=e.some(e=>"text"!==e.type&&Mz(t,e)),o=e[e.length-1],i=e.slice(0,e.length-1);if(("percentage"===o.type||"number"===o.type)&&i.every(e=>"text"===e.type)){const e=i.map(({zone:e})=>({dataRange:Oz(t,e)}));return{type:i.length>=3?"sunburst":"treemap",title:{},dataSets:e,labelRange:Oz(t,o.zone),dataSetsHaveTitle:s,legendPosition:"none"}}const n=e[0],r=e.slice(1),a=r.map(({zone:e})=>({dataRange:Oz(t,e)}));return r.every(e=>"percentage"===e.type)?{type:"pie",title:{},dataSets:a,labelRange:Oz(t,n.zone),dataSetsHaveTitle:s,aggregated:!1,legendPosition:"top"}:"date"===n.type&&r.every(e=>"number"===e.type)?{...Dz,type:"line",dataSets:a,labelRange:Oz(t,n.zone),dataSetsHaveTitle:s,legendPosition:"top"}:{..._z,dataSets:a,labelRange:Oz(t,n.zone),dataSetsHaveTitle:s,legendPosition:"top"}}(o,t)}}const Vz={wrongPasteSelection:Cs("This operation is not allowed with multiple selections."),willRemoveExistingMerge:Zg.Errors.WillRemoveExistingMerge,wrongFigurePasteOption:Cs("Cannot do a special paste of a figure."),frozenPaneOverlap:Cs("This operation is not allowed due to an overlapping frozen pane.")};function zz(e,t){t.isSuccessful||(t.reasons.includes("WrongPasteSelection")?e.raiseError(Vz.wrongPasteSelection):t.reasons.includes("WillRemoveExistingMerge")?e.raiseError(Vz.willRemoveExistingMerge):t.reasons.includes("WrongFigurePasteOption")?e.raiseError(Vz.wrongFigurePasteOption):t.reasons.includes("FrozenPaneOverlap")&&e.raiseError(Vz.frozenPaneOverlap))}function Hz(e,t,s){const o=e.model.dispatch("PASTE",{target:t,pasteOption:s});zz(e,o)}async function Uz(e,t,s,o){let i;try{const n=s;if(s.imageBlob){try{const t=await(e.imageProvider?.uploadFile(s.imageBlob));n.imageData=t}catch(t){const s=Cs("An error occurred while uploading the image. %s",t.message);console.error(t),e.raiseError(s)}delete s.imageBlob}i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,clipboardContent:s,pasteOption:o})}catch(n){const r=s.data;r?.version!==__()?e.raiseError(Cs("An unexpected error occurred while pasting content. This is probably due to a spreadsheet version mismatch.")):(e.raiseError(Cs("An unexpected error occurred while pasting content. Additional information can be found in the browser console.")),console.error(n)),i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,clipboardContent:{text:s.text},pasteOption:o})}zz(e,i)}function Bz(e,t,s=Zx){let o=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,o);1!==o.length||i||1!==ss(o[0])||(e.model.selection.selectTableAroundSelection(),o=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,o));const n=o.map(s=>e.model.getters.getRangeDataFromZone(t,s)),r=e.model.dispatch("CREATE_TABLE",{ranges:n,sheetId:t,config:s,tableType:i?"dynamic":"static"});return r.isCancelledBecause("TableOverlap")?e.raiseError(Yg.Errors.TableOverlap):r.isCancelledBecause("NonContinuousTargets")&&e.raiseError(Yg.Errors.NonContinuousTargets),r}function Gz(e,t){e.model.dispatch("SET_FORMATTING_WITH_PIVOT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function Wz(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const $z=async e=>qz(e,"asValue");async function qz(e,t){const s=await e.clipboard.read();switch(s.status){case"ok":const o=e.model.getters.getClipboardId(),i=iP(s.content),n=i.data?.clipboardId,r=e.model.getters.getSelectedZones();o!==n?await Uz(e,r,i,t):Hz(e,r,t),e.model.getters.isCutOperation()&&"asValue"!==t&&await e.clipboard.write({[QF.PlainText]:""});break;case"notImplemented":e.raiseError(Cs("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(Cs("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const Zz=(e,t)=>{if("COL"===e&&t.model.getters.getActiveRows().size>0||"ROW"===e&&t.model.getters.getActiveCols().size>0)return!1;const s=t.model.getters.getActiveSheetId(),o=t.model.getters.getElementsFromSelection(e),i=t.model.getters.checkElementsIncludeAllVisibleHeaders(s,e,o),n=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(s,e,o);return!i&&!n},jz=e=>{const t=e.model.getters.getActiveRows();let s,o;if(t.size)s=st([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.top,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"before",base:s,quantity:o,dimension:"ROW"})},Yz=e=>{const t=e.model.getters.getActiveCols();let s,o;if(t.size)s=st([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.left,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"before",dimension:"COL",base:s,quantity:o})},Xz=e=>{const t=e.model.getters.getActiveCols();let s,o;if(t.size)s=tt([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.right,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"after",dimension:"COL",base:s,quantity:o})},Kz=async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),s=e.model.uuidGenerator.smallUuid(),o=await e.imageProvider.requestImage(),i=cP(e.model.getters,o.size),{col:n,row:r,offset:a}=lP(e.model.getters,i);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:s,col:n,row:r,offset:a,size:i,definition:o})}},Jz=e=>{const{col:t,row:s}=e.model.getters.getActivePosition();e.getStore(aV).open({col:t,row:s},"LinkEditor")},Qz=e=>{const t=e.model.getters.getFirstTableInSelection();return t?.config.hasFilters||!1},eH=e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZones();return 1===e.model.getters.getTablesOverlappingZones(t,s).length},tH=e=>is(e.model.getters.getSelectedZones()),sH=e=>1===e.model.getters.getSelectedZones().length,oH=(e,t)=>{if(!sH(e))return!1;const s="COL"===t?e.model.getters.getActiveCols():e.model.getters.getActiveRows(),o="COL"===t?e.model.getters.getActiveRows():e.model.getters.getActiveCols(),i=e.model.getters.getActiveSheetId(),n=Ht(e.model.getters.getSelectedZone(),e.model.getters.getSheetZone(i));return Ze(s)&&(0===o.size||n)},iH={name:e=>Qz(e)?Cs("Remove selected filters"):Cs("Add filters"),isEnabled:e=>tH(e),execute:e=>Qz(e)?(e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getFirstTableInSelection();s&&e.model.dispatch("UPDATE_TABLE",{sheetId:t,zone:s.range.zone,config:{hasFilters:!1}})})(e):(e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getFirstTableInSelection();s?e.model.dispatch("UPDATE_TABLE",{sheetId:t,zone:s.range.zone,config:{hasFilters:!0}}):Bz(e,t,{...Zx,hasFilters:!0,bandedRows:!1,styleId:"TableStyleLight11"})})(e),icon:"o-spreadsheet-Icon.FILTER_ICON_ACTIVE"};function nH(e,t,s){const o=e.model.getters.getActiveSheetId(),i="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(i,{sheetId:o,quantity:s}).isCancelledBecause("MergeOverlap")&&e.raiseError(Wg)}class rH extends Lv{mutators=["enable","disable"];isInvalidated=!1;fingerprintColors={[aH]:"#D9D9D9"};isEnabled=!1;colors=new H_;handle(e){switch(kr(e)&&this.isEnabled&&(this.isInvalidated=!0),e.type){case"UNDO":case"REDO":case"ACTIVATE_SHEET":this.isEnabled&&(this.isInvalidated=!0)}}finalize(){this.isInvalidated&&(this.isInvalidated=!1,this.computeFingerprints())}enable(){this.isEnabled=!0,this.computeFingerprints()}disable(){this.isEnabled=!1,this.colors=new H_}computeFingerprints(){this.colors=new H_;const e=new H_,t=new Set,s=this.getters.getActiveSheetId(),o=this.getters.getCells(s);for(const s in o){const i=this.computeFingerprint(o[s]);if(!i)continue;t.add(i);const n=this.getters.getCellPosition(s);e.set(n,i)}this.assignColors(t);for(const[t,s]of e.entries()){const e=this.fingerprintColors[s];this.colors.set(t,e),this.colorSpreadZone(t,e)}}colorSpreadZone(e,t){const s=this.getters.getSpreadZone(e);if(!s)return;const o=e.sheetId;for(let e=s.top;e<=s.bottom;e++)for(let i=s.left;i<=s.right;i++){const s={sheetId:o,col:i,row:e};this.colors.set(s,t)}}assignColors(e){const t=new Cb(e.size);Object.keys(this.fingerprintColors).forEach(()=>t.next());for(const s of e)this.fingerprintColors[s]||(this.fingerprintColors[s]=ab(t.next(),.8))}computeFingerprint(e){const t=this.getters.getCellPosition(e.id);return e.isFormula?this.computeFormulaFingerprint(t,e):this.getLiteralFingerprint(t)}computeFormulaFingerprint(e,t){const s=t.compiledFormula.dependencies,o=e.col,i=e.row,n=this.getters.getSheetIds().indexOf(e.sheetId),r={dx:0,dy:0,dSheet:0};for(const e of s){const t=e.zone,[s,a]=e.parts,l=this.getters.getSheetIds().indexOf(e.sheetId);r.dSheet=l-n;const c=Yb(e)&&!e.unboundedZone.hasHeader,h=jb(e)&&!e.unboundedZone.hasHeader,d=c||s?.colFixed?0:o,u=h||s?.rowFixed?0:i,g=!a&&s?.colFixed||a?.colFixed,p=!a&&s?.rowFixed||a?.rowFixed,m=void 0===e.unboundedZone.right||g?0:o,f=void 0===e.unboundedZone.bottom||p?0:i,v=Yt({top:t.top-u,left:t.left-d,right:t.right-m,bottom:t.bottom-f});for(let e=v.top;e<=v.bottom;e++)for(let t=v.left;t<=v.right;t++)r.dx+=t,r.dy+=e}const a=t.compiledFormula.normalizedFormula;return l=r,Object.entries(l).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t).join(",")+a;var l}getLiteralFingerprint(e){switch(this.getters.getEvaluatedCell(e).type){case Xd.number:case Xd.boolean:return aH;case Xd.text:case Xd.empty:case Xd.error:return}}}const aH="DATA_FINGERPRINT",lH={name:e=>{const t=e.model.getters.getElementsFromSelection("COL"),s=t[0],o=t[t.length-1];return 1===t.length?Cs("Hide column %s",lt(s).toString()):o-s+1===t.length?Cs("Hide columns %s - %s",lt(s).toString(),lt(o).toString()):Cs("Hide columns")},execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getElementsFromSelection("COL");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"COL",s)},icon:"o-spreadsheet-Icon.HIDE_COL"},cH={name:Cs("Unhide columns"),execute:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("COL").some(e=>t.includes(e))},icon:"o-spreadsheet-Icon.UNHIDE_COL"},hH={name:Cs("Unhide all columns"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"COL",elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0,icon:"o-spreadsheet-Icon.UNHIDE_COL"},dH={name:e=>{const t=e.model.getters.getElementsFromSelection("ROW"),s=t[0],o=t[t.length-1];return 1===t.length?Cs("Hide row %s",(s+1).toString()):o-s+1===t.length?Cs("Hide rows %s - %s",(s+1).toString(),(o+1).toString()):Cs("Hide rows")},execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getElementsFromSelection("ROW");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"ROW",s)},icon:"o-spreadsheet-Icon.HIDE_ROW"},uH={name:Cs("Unhide rows"),execute:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("ROW").some(e=>t.includes(e))},icon:"o-spreadsheet-Icon.UNHIDE_ROW"},gH={name:Cs("Unhide all rows"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"ROW",elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0,icon:"o-spreadsheet-Icon.UNHIDE_ROW"},pH={name:Cs("Unfreeze"),isVisible:e=>{const{xSplit:t,ySplit:s}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+s>0},execute:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),icon:"o-spreadsheet-Icon.UNFREEZE"},mH={name:Cs("Freeze"),icon:"o-spreadsheet-Icon.FREEZE"},fH={name:Cs("No rows"),execute:e=>e.model.dispatch("UNFREEZE_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit},vH={name:Cs("1 row"),execute:e=>nH(e,"ROW",1)},bH={name:Cs("2 rows"),execute:e=>nH(e,"ROW",2)},SH={name:Cs("Up to current row"),execute:e=>{const{bottom:t}=e.model.getters.getSelectedZone();nH(e,"ROW",t+1)}},yH={name:Cs("No columns"),execute:e=>e.model.dispatch("UNFREEZE_COLUMNS",{sheetId:e.model.getters.getActiveSheetId()}),isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit},CH={name:Cs("1 column"),execute:e=>nH(e,"COL",1)},IH={name:Cs("2 columns"),execute:e=>nH(e,"COL",2)},wH={name:Cs("Up to current column"),execute:e=>{const{right:t}=e.model.getters.getSelectedZone();nH(e,"COL",t+1)}},EH={name:Cs("Gridlines"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},isActive:e=>{const t=e.model.getters.getActiveSheetId();return e.model.getters.getGridLinesVisibility(t)}},xH={name:Cs("Irregularity map"),execute:e=>{const t=e.getStore(rH);t.isEnabled?t.disable():t.enable()},isReadonlyAllowed:!0,icon:"o-spreadsheet-Icon.IRREGULARITY_MAP"};const RH={name:Cs("Formulas"),isActive:e=>e.model.getters.shouldShowFormulas(),execute:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0},TH={name:e=>{const t=e.model.getters.getSelectedZone();return t.left===t.right?Cs("Group column %s",lt(t.left)):Cs("Group columns %s - %s",lt(t.left),lt(t.right))},execute:e=>OH(e,"COL"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZone(),o=e.model.getters.getHeaderGroupsInZone(t,"COL",s);return sH(e)&&!o.some(e=>e.start===s.left&&e.end===s.right)},icon:"o-spreadsheet-Icon.GROUP_COLUMNS"},AH={name:e=>{const t=e.model.getters.getSelectedZone();return t.top===t.bottom?Cs("Group row %s",String(t.top+1)):Cs("Group rows %s - %s",String(t.top+1),String(t.bottom+1))},execute:e=>OH(e,"ROW"),isVisible:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSelectedZone(),o=e.model.getters.getHeaderGroupsInZone(t,"ROW",s);return sH(e)&&!o.some(e=>e.start===s.top&&e.end===s.bottom)},icon:"o-spreadsheet-Icon.GROUP_ROWS"},_H={name:e=>{const t=e.model.getters.getSelectedZone();return t.left===t.right?Cs("Ungroup column %s",lt(t.left)):Cs("Ungroup columns %s - %s",lt(t.left),lt(t.right))},execute:e=>FH(e,"COL"),icon:"o-spreadsheet-Icon.UNGROUP_COLUMNS"},DH={name:e=>{const t=e.model.getters.getSelectedZone();return t.top===t.bottom?Cs("Ungroup row %s",String(t.top+1)):Cs("Ungroup rows %s - %s",String(t.top+1),String(t.bottom+1))},execute:e=>FH(e,"ROW"),icon:"o-spreadsheet-Icon.UNGROUP_ROWS"};function OH(e,t){const s=e.model.getters.getSelectedZone(),o=e.model.getters.getActiveSheetId();e.model.dispatch("GROUP_HEADERS",{sheetId:o,dimension:t,start:"COL"===t?s.left:s.top,end:"COL"===t?s.right:s.bottom})}function FH(e,t){const s=e.model.getters.getSelectedZone(),o=e.model.getters.getActiveSheetId();e.model.dispatch("UNGROUP_HEADERS",{sheetId:o,dimension:t,start:"COL"===t?s.left:s.top,end:"COL"===t?s.right:s.bottom})}function PH(e,t){const s=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return 1===o.length&&e.model.getters.getHeaderGroupsInZone(s,t,o[0]).length>0}function MH(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause("WrongCutSelection")&&e.raiseError(Cs("This operation is not allowed with multiple selections."))}const NH={MergeIsDestructive:Cs("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:Cs("You can't merge cells inside of an existing filter.")};const kH={name:Cs("Undo"),description:"Ctrl+Z",execute:e=>e.model.dispatch("REQUEST_UNDO"),isEnabled:e=>e.model.getters.canUndo(),icon:"o-spreadsheet-Icon.UNDO"},LH={name:Cs("Redo"),description:"Ctrl+Y",execute:e=>e.model.dispatch("REQUEST_REDO"),isEnabled:e=>e.model.getters.canRedo(),icon:"o-spreadsheet-Icon.REDO"},VH={name:Cs("Copy"),description:"Ctrl+C",isReadonlyAllowed:!0,execute:async e=>{e.model.dispatch("COPY"),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},icon:"o-spreadsheet-Icon.CLIPBOARD"},zH={name:Cs("Cut"),description:"Ctrl+X",execute:async e=>{MH(e),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},icon:"o-spreadsheet-Icon.CUT"},HH={name:Cs("Paste"),description:"Ctrl+V",execute:async e=>qz(e),icon:"o-spreadsheet-Icon.PASTE"},UH={name:Cs("Paste special"),isVisible:e=>!e.model.getters.isCutOperation(),icon:"o-spreadsheet-Icon.PASTE"},BH={name:Cs("Paste as value"),description:"Ctrl+Shift+V",execute:$z},GH={name:Cs("Paste format only"),execute:e=>qz(e,"onlyFormat")},WH={name:Cs("Find and replace"),description:"Ctrl+H",isReadonlyAllowed:!0,execute:e=>{e.openSidePanel("FindAndReplace",{})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.SEARCH"},$H={name:Cs("Delete values"),execute:e=>e.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},qH={name:e=>{if(e.model.getters.getSelectedZones().length>1)return Cs("Delete rows");let t,s;const o=e.model.getters.getActiveRows();if(0!==o.size)t=st([...o]),s=tt([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?Cs("Delete row %s",(t+1).toString()):Cs("Delete rows %s - %s",(t+1).toString(),(s+1).toString())},execute:e=>{const t=[...e.model.getters.getActiveRows()];if(!t.length){const s=e.model.getters.getSelectedZones()[0];for(let e=s.top;e<=s.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:"ROW",elements:t})},isVisible:e=>Zz("ROW",e)},ZH={...qH,isVisible:sH},jH={name:e=>{if(e.model.getters.getSelectedZones().length>1)return Cs("Clear rows");let t,s;const o=e.model.getters.getActiveRows();if(0!==o.size)t=st([...o]),s=tt([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,s=o.bottom}return t===s?Cs("Clear row %s",(t+1).toString()):Cs("Clear rows %s - %s",(t+1).toString(),(s+1).toString())},execute:e=>{const t=e.model.getters.getActiveSheetId(),s=[...e.model.getters.getActiveRows()].map(s=>e.model.getters.getRowsZone(t,s,s));e.model.dispatch("DELETE_CONTENT",{target:s,sheetId:e.model.getters.getActiveSheetId()})}},YH={name:e=>{if(e.model.getters.getSelectedZones().length>1)return Cs("Delete columns");let t,s;const o=e.model.getters.getActiveCols();if(0!==o.size)t=st([...o]),s=tt([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?Cs("Delete column %s",lt(t)):Cs("Delete columns %s - %s",lt(t),lt(s))},execute:e=>{const t=[...e.model.getters.getActiveCols()];if(!t.length){const s=e.model.getters.getSelectedZones()[0];for(let e=s.left;e<=s.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:"COL",elements:t})},isVisible:e=>Zz("COL",e)},XH={...YH,isVisible:sH},KH={name:e=>{if(e.model.getters.getSelectedZones().length>1)return Cs("Clear columns");let t,s;const o=e.model.getters.getActiveCols();if(0!==o.size)t=st([...o]),s=tt([...o]);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,s=o.right}return t===s?Cs("Clear column %s",lt(t)):Cs("Clear columns %s - %s",lt(t),lt(s))},execute:e=>{const t=e.model.getters.getActiveSheetId(),s=[...e.model.getters.getActiveCols()].map(s=>e.model.getters.getColsZone(t,s,s));e.model.dispatch("DELETE_CONTENT",{target:s,sheetId:e.model.getters.getActiveSheetId()})}},JH={name:Cs("Delete cells"),isVisible:sH},QH={name:Cs("Delete cell and shift up"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});zz(e,s)}},eU={name:Cs("Delete cell and shift left"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});zz(e,s)}},tU={name:Cs("Merge cells"),isEnabled:e=>!iU(e),isActive:e=>nU(e),execute:e=>function(e){if(iU(e))return;const t=e.model.getters.getSelectedZones(),s=e.model.getters.getActiveSheetId();if(nU(e)){const o=t.flatMap(t=>e.model.getters.getMergesInZone(s,t));e.model.dispatch("REMOVE_MERGE",{sheetId:s,target:o})}else!function(e,t,s){const o=e.model.dispatch("ADD_MERGE",{sheetId:t,target:s});o.isCancelledBecause("MergeInTable")?e.raiseError(NH.MergeInFilter):o.isCancelledBecause("MergeIsDestructive")&&e.askConfirmation(NH.MergeIsDestructive,()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:s,force:!0})})}(e,s,t)}(e),icon:"o-spreadsheet-Icon.MERGE_CELL"},sU={name:()=>Cs("Edit table"),execute:e=>e.openSidePanel("TableSidePanel",{}),icon:"o-spreadsheet-Icon.EDIT_TABLE"},oU={name:()=>Cs("Delete table"),execute:e=>{const t=e.model.getters.getActivePosition(),s=e.model.getters.getTable(t);s&&e.model.dispatch("REMOVE_TABLE",{sheetId:t.sheetId,target:[s.range.zone]})},icon:"o-spreadsheet-Icon.DELETE_TABLE"};function iU(e){const t=e.model.getters.getSelectedZones(),{sheetId:s}=e.model.getters.getActivePosition(),{xSplit:o,ySplit:i}=e.model.getters.getPaneDivisions(s);return t.every(e=>1===ss(e))||os(t,o,i)||function(e){for(let t=0;t<e.length-1;t++)for(let s=t+1;s<e.length;s++)if(Bt(e[t],e[s]))return!0;return!1}(t)}function nU(e){if(iU(e))return!1;const t=e.model.getters.getActiveSheetId();return e.model.getters.getSelectedZones().some(s=>e.model.getters.getMergesInZone(t,s).length>0)}const rU={name:e=>{const t=VU(e);return 1===t?Cs("Insert row"):Cs("Insert %s rows",t.toString())},isVisible:e=>oH(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW"},aU={name:e=>{const t=VU(e);return 1===t?Cs("Insert row above"):Cs("Insert %s rows above",t.toString())},execute:jz,isVisible:e=>oH(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},lU={...aU,name:e=>{const t=VU(e);return 1===t?Cs("Row above"):Cs("%s Rows above",t.toString())}},cU={...aU,name:e=>{const t=VU(e);return 1===t?Cs("Insert row"):Cs("Insert %s rows",t.toString())},isVisible:sH,icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},hU={execute:e=>{const t=e.model.getters.getActiveRows();let s,o;if(t.size)s=tt([...t]),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];s=t.bottom,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:"after",base:s,quantity:o,dimension:"ROW"})},name:e=>{const t=VU(e);return 1===t?Cs("Insert row below"):Cs("Insert %s rows below",t.toString())},isVisible:e=>oH(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_AFTER"},dU={...hU,name:e=>{const t=VU(e);return 1===t?Cs("Row below"):Cs("%s Rows below",t.toString())}},uU={name:e=>{const t=zU(e);return 1===t?Cs("Insert column"):Cs("Insert %s columns",t.toString())},isVisible:e=>oH(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL"},gU={name:e=>{const t=zU(e);return 1===t?Cs("Insert column left"):Cs("Insert %s columns left",t.toString())},execute:Yz,isVisible:e=>oH(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},pU={...gU,name:e=>{const t=zU(e);return 1===t?Cs("Column left"):Cs("%s Columns left",t.toString())}},mU={...gU,name:e=>{const t=zU(e);return 1===t?Cs("Insert column"):Cs("Insert %s columns",t.toString())},isVisible:sH,icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},fU={name:e=>{const t=zU(e);return 1===t?Cs("Insert column right"):Cs("Insert %s columns right",t.toString())},execute:Xz,isVisible:e=>oH(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_AFTER"},vU={...fU,name:e=>{const t=zU(e);return 1===t?Cs("Column right"):Cs("%s Columns right",t.toString())},execute:Xz},bU={name:Cs("Insert cells"),isVisible:e=>sH(e)&&0===e.model.getters.getActiveCols().size&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_CELL"},SU={name:Cs("Insert cells and shift down"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});zz(e,s)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN"},yU={name:Cs("Insert cells and shift right"),execute:e=>{const t=e.model.getters.getSelectedZone(),s=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});zz(e,s)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT"},CU={name:Cs("Chart"),execute:e=>{const t=e.model.getters,s=e.model.uuidGenerator.smallUuid(),o=t.getActiveSheetId();let i=t.getSelectedZones();1===i.length&&1===ss(i[0])&&(e.model.selection.selectTableAroundSelection(),i=t.getSelectedZones());const n={width:536,height:335},{col:r,row:a,offset:l}=lP(t,n);e.model.dispatch("CREATE_CHART",{sheetId:o,figureId:s,chartId:e.model.uuidGenerator.smallUuid(),col:r,row:a,offset:l,size:n,definition:Lz(i,e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{figureId:s}),e.openSidePanel("ChartPanel"))},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.INSERT_CHART"},IU={name:Cs("Carousel"),execute:e=>{const t=e.model.getters,s=e.model.uuidGenerator.smallUuid(),o=t.getActiveSheetId(),i={width:536,height:335},{col:n,row:r,offset:a}=lP(t,i);e.model.dispatch("CREATE_CAROUSEL",{sheetId:o,figureId:s,col:n,row:r,offset:a,size:i,definition:{items:[]}}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{figureId:s}),e.openSidePanel("CarouselPanel",{figureId:s}))},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.CAROUSEL"},wU={name:Cs("Pivot table"),execute:e=>{const t=e.model.uuidGenerator.smallUuid(),s=e.model.uuidGenerator.smallUuid();e.model.dispatch("INSERT_NEW_PIVOT",{pivotId:t,newSheetId:s}).isSuccessful&&e.openSidePanel("PivotSidePanel",{pivotId:t})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.PIVOT"},EU={name:Cs("Image"),description:"Ctrl+O",execute:Kz,isVisible:e=>void 0!==e.imageProvider,isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.INSERT_IMAGE"},xU={name:()=>Cs("Table"),execute:e=>{const t=e.model.getters.getActiveSheetId();Bz(e,t).isSuccessful&&e.openSidePanel("TableSidePanel",{})},isVisible:e=>tH(e)&&!e.model.getters.getFirstTableInSelection(),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.PAINT_TABLE"},RU={name:Cs("Function"),icon:"o-spreadsheet-Icon.FORMULA"},TU={name:Cs("SUM"),execute:e=>e.startCellEdition("=SUM(")},AU={name:Cs("AVERAGE"),execute:e=>e.startCellEdition("=AVERAGE(")},_U={name:Cs("COUNT"),execute:e=>e.startCellEdition("=COUNT(")},DU={name:Cs("MAX"),execute:e=>e.startCellEdition("=MAX(")},OU={name:Cs("MIN"),execute:e=>e.startCellEdition("=MIN(")},FU={name:Cs("All"),children:[function(){return LU(zf.getKeys().filter(e=>!zf.get(e).hidden))}]};const PU={name:Cs("Link"),execute:Jz,icon:"o-spreadsheet-Icon.INSERT_LINK"},MU={name:Cs("Checkbox"),execute:e=>{const t=e.model.getters.getSelectedZones(),s=e.model.getters.getActiveSheetId(),o=t.map(t=>e.model.getters.getRangeDataFromZone(s,t));e.model.dispatch("ADD_DATA_VALIDATION_RULE",{ranges:o,sheetId:s,rule:{id:e.model.uuidGenerator.smallUuid(),criterion:{type:"isBoolean",values:[]}}})},icon:"o-spreadsheet-Icon.INSERT_CHECKBOX"},NU={name:Cs("Dropdown list"),execute:e=>{const t=e.model.getters.getSelectedZones(),s=e.model.getters.getActiveSheetId(),o=t.map(t=>e.model.getters.getRangeDataFromZone(s,t)),i=e.model.uuidGenerator.smallUuid();e.model.dispatch("ADD_DATA_VALIDATION_RULE",{ranges:o,sheetId:s,rule:{id:i,criterion:{type:"isValueInList",values:[],displayStyle:"chip"}}});const n=e.model.getters.getDataValidationRule(s,i);n&&e.openSidePanel("DataValidationEditor",{rule:Th(n,e.model.getters.getLocale()),onExit:()=>{e.replaceSidePanel("DataValidation","DataValidationEditor")}})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.INSERT_DROPDOWN"},kU={name:Cs("Insert sheet"),execute:e=>{const t=e.model.getters.getActiveSheetId(),s=e.model.getters.getSheetIds().indexOf(t)+1,o=e.model.uuidGenerator.smallUuid();e.model.dispatch("CREATE_SHEET",{sheetId:o,position:s,name:e.model.getters.getNextSheetName()}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},icon:"o-spreadsheet-Icon.INSERT_SHEET"};function LU(e){return e.sort().map((e,t)=>({name:e,sequence:10*t,execute:t=>t.startCellEdition(`=${e}(`)}))}function VU(e){const t=e.model.getters.getActiveRows();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function zU(e){const t=e.model.getters.getActiveCols();if(t.size)return t.size;{const t=e.model.getters.getSelectedZones()[0];return t.right-t.left+1}}const HU={name:Cs("See pivot properties"),execute(e){const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotIdFromPosition(t);e.openSidePanel("PivotSidePanel",{pivotId:s})},isVisible:e=>{const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotIdFromPosition(t);return!e.isSmall&&s&&e.model.getters.isExistingPivot(s)||!1},isReadonlyAllowed:!0,icon:"o-spreadsheet-Icon.PIVOT"},UU={name:Cs("Ascending"),execute:e=>QU(e,e.model.getters.getActivePosition(),"asc"),isActive:e=>"asc"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},BU={name:Cs("Descending"),execute:e=>QU(e,e.model.getters.getActivePosition(),"desc"),isActive:e=>"desc"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},GU={name:Cs("No sorting"),execute:e=>QU(e,e.model.getters.getActivePosition(),"none"),isActive:e=>"none"===e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())},WU={name:Cs("Convert to individual formulas"),execute(e){const t=e.model.getters.getActivePosition(),s=e.model.getters.getCorrespondingFormulaCell(t),o=e.model.getters.getPivotIdFromPosition(t);if(!s||!o)return;const{sheetId:i,col:n,row:r}=e.model.getters.getCellPosition(s.id),a=e.model.getters.getPivot(o);a.init(),a.isValid()&&e.model.dispatch("SPLIT_PIVOT_FORMULA",{sheetId:i,col:n,row:r,pivotId:o})},isVisible:e=>{const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotIdFromPosition(t);if(!s)return!1;const o=e.model.getters.getPivot(s),i=e.model.getters.getEvaluatedCell(t);return o.isValid()&&e.model.getters.isSpillPivotFormula(t)&&i.type!==Xd.error},icon:"o-spreadsheet-Icon.PIVOT"},$U={name:Cs("Group pivot dimensions"),execute:e=>{const t=eB(e);if(!t)return;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s),r=he(e.model.getters.getPivotCoreDefinition(s));if(i.isCustomField){const e=(r.customFields||{})[i.name];if(!e)return;!function(e,t){const s=new Set,o=[];for(const i of t){const t=e.groups.find(e=>e.name===i);t?(o.push(t),t.values.forEach(e=>s.add(e))):s.add(i)}if(o.some(e=>e.isOtherGroup))e.groups=e.groups.filter(e=>e.isOtherGroup||!o.includes(e));else if(0===o.length){const s={name:kp(Cs("Group"),e),values:t};e.groups.push(s)}else{const t=o.slice(1);e.groups=e.groups.filter(e=>!t.includes(e)),o[0].values=Array.from(s)}}(e,o)}else!function(e,t,s,o){const i=Up(e,s,o);zp(t,i);const n={name:kp(Cs("Group"),i),values:t};i.groups.push(n),e.customFields||(e.customFields={});e.customFields[i.name]=i,Hp(e,s.name,i.name)}(r,o,i,n.getFields());e.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:r})},isVisible:e=>{const t=eB(e);if(!t)return!1;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s);return o.length>1&&(i.isCustomField||AD.get(n.type).canHaveCustomGroup(i))}},qU={name:Cs("Group all remaining dimensions"),execute:e=>{const t=eB(e);if(!t)return;const{pivotId:s,field:o}=t,i=e.model.getters.getPivot(s),n=he(e.model.getters.getPivotCoreDefinition(s)),r=o.isCustomField?(n.customFields||{})[o.name]:Up(n,o,i.getFields());r&&(r.groups.push({name:kp(Cs("Others"),r),values:[],isOtherGroup:!0}),Hp(n,o.name,r.name),e.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:n}))},isVisible:e=>{const t=eB(e);if(!t)return!1;const{pivotId:s,field:o,values:i}=t;return function(e,t,s,o){const i=e.model.getters.getPivot(t),n=e.model.getters.getPivotCoreDefinition(t),r=o.isCustomField?(n.customFields||{})[o.name]:Object.values(n.customFields||{}).find(e=>e.parentField===o.name),a=i.definition.getDimension(o.name);if(!a||!r||tB(n,s,o,i.getFields()))return!1;const l=new Set(i.getPossibleFieldValues(a).map(e=>e.value)),c=o.isCustomField?r.groups.map(e=>e.name):r.groups.flatMap(e=>e.values);for(const e of[...s,...c])l.delete(e);return 0===l.size}(e,s,i,o)}},ZU={name:Cs("Ungroup pivot dimensions"),execute:e=>{const t=eB(e);if(!t)return;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s),r=he(e.model.getters.getPivotCoreDefinition(s));!function(e,t,s,o){let i;if(s.isCustomField){if(i=(e.customFields||{})[s.name],!i)return;i.groups=i.groups.filter(e=>!t.includes(e.name))}else i=Up(e,s,o),i.groups.some(e=>e.isOtherGroup)&&t.some(e=>!i?.groups.some(t=>t.values.includes(e)))&&(i.groups=i.groups.filter(e=>!e.isOtherGroup)),zp(t,i);i.groups.every(e=>0===e.values.length&&!e.isOtherGroup)&&(!function(e,t){const s=e.customFields?.[t];if(!s)return;const o=[...e.rows,...e.columns].some(e=>e.fieldName===s.parentField);for(const i of[e.rows,e.columns]){const e=i.findIndex(e=>e.fieldName===t);-1!==e&&(o?i.splice(e,1):i.splice(e,1,{fieldName:s.parentField}))}}(e,i.name),delete e.customFields?.[i.name])}(r,o,i,n.getFields()),e.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:r})},isVisible:e=>{const t=eB(e);if(!t)return!1;const{pivotId:s,values:o,field:i}=t,n=e.model.getters.getPivot(s),r=e.model.getters.getPivotCoreDefinition(s);if(!i.isCustomField){const e=Up(r,i,n.getFields());if(![...r.rows,...r.columns].some(t=>t.fieldName===e.name))return!1}return tB(r,o,i,n.getFields())}},jU={name:e=>{const t=e.model.getters.getActivePosition(),s=KU(e.model.getters,t);return s.isPivotGroup?s.isCollapsed?Cs("Expand"):Cs("Collapse"):""},execute(e){Bp(e.model.getters.getActivePosition(),e)},isVisible:e=>{const t=e.model.getters.getActivePosition();return KU(e.model.getters,t).isPivotGroup}},YU={name:Cs("Collapse all"),execute(e){const t=e.model.getters.getActivePosition(),s=KU(e.model.getters,t);if(!s.isPivotGroup)return;const{pivotCell:o,pivotId:i,siblingDomains:n}=s,r=he(e.model.getters.getPivotCoreDefinition(i));r.collapsedDomains=r.collapsedDomains||{COL:[],ROW:[]};const a=[...r.collapsedDomains[o.dimension]||[],...n],l=a.filter((e,t)=>t===a.findIndex(t=>Le(t,e)));r.collapsedDomains[o.dimension]=l,e.model.dispatch("UPDATE_PIVOT",{pivotId:i,pivot:r})},isVisible:e=>{const t=e.model.getters.getActivePosition(),s=KU(e.model.getters,t);if(!s.isPivotGroup)return!1;const{pivotCell:o,pivotId:i,siblingDomains:n}=s,r=e.model.getters.getPivotCoreDefinition(i);return!n.every(e=>(r.collapsedDomains?.[o.dimension]||[]).some(t=>Le(t,e)))}},XU={name:Cs("Expand all"),execute(e){const t=e.model.getters.getActivePosition(),s=KU(e.model.getters,t);if(!s.isPivotGroup)return;const{pivotCell:o,pivotId:i,siblingDomains:n}=s,r=he(e.model.getters.getPivotCoreDefinition(i));r.collapsedDomains=r.collapsedDomains||{COL:[],ROW:[]};const a=(r.collapsedDomains[o.dimension]||[]).filter(e=>!n.find(t=>Le(t,e)));r.collapsedDomains[o.dimension]=a,e.model.dispatch("UPDATE_PIVOT",{pivotId:i,pivot:r})},isVisible:e=>{const t=e.model.getters.getActivePosition(),s=KU(e.model.getters,t);if(!s.isPivotGroup)return!1;const{pivotCell:o,pivotId:i,siblingDomains:n}=s,r=e.model.getters.getPivotCoreDefinition(i);return(r.collapsedDomains?.[o.dimension]||[]).some(e=>n.some(t=>Le(t,e)))}};function KU(e,t){if(!e.isSpillPivotFormula(t))return{isPivotGroup:!1};const s=e.getPivotCellFromPosition(t),o=e.getPivotIdFromPosition(t);if("HEADER"!==s.type||!o||!s.domain.length)return{isPivotGroup:!1};const i=e.getPivotCoreDefinition(o),n=e.isDashboard(),r="COL"===s.dimension?i.columns:i.rows;if(!(!n&&s.domain.length!==r.length))return{isPivotGroup:!1};const a=(i.collapsedDomains?.[s.dimension]??[]).some(e=>Le(e,s.domain)),l=e.getPivot(o).getExpandedTableStructure(),c=s.domain.length-1,h="ROW"===s.dimension?l.getRowDomainsAtDepth(c):l.getColumnDomainsAtDepth(c);return{isPivotGroup:!0,isCollapsed:a,pivotCell:s,pivotId:o,siblingDomains:h}}function JU(e,t){const s=e.getPivotIdFromPosition(t);if(!s||!e.isExistingPivot(s)||!e.isSpillPivotFormula(t))return!1;if(!e.getPivot(s).isValid())return!1;const o=e.getPivotCellFromPosition(t);return"VALUE"===o.type||"MEASURE_HEADER"===o.type}function QU(e,t,s){const o=e.model.getters.getPivotIdFromPosition(t),i=e.model.getters.getPivotCellFromPosition(t);if("EMPTY"===i.type||"HEADER"===i.type||!o)return;if("none"===s)return void e.model.dispatch("UPDATE_PIVOT",{pivotId:o,pivot:{...e.model.getters.getPivotCoreDefinition(o),sortedColumn:void 0}});const n=oD(e.model.getters.getPivot(o),i.domain).colDomain;e.model.dispatch("UPDATE_PIVOT",{pivotId:o,pivot:{...e.model.getters.getPivotCoreDefinition(o),sortedColumn:{domain:n,order:s,measure:i.measure}}})}function eB(e){let t,s;const o=[];for(const i of e.model.getters.getSelectedZones()){const n=e.model.getters.getActiveSheetId();for(const r of jt(n,i)){const i=e.model.getters.getPivotIdFromPosition(r);if(t){if(i&&t!==i)return}else t=i;if(!t)continue;const n=e.model.getters.getPivotCellFromPosition(r);if("HEADER"!==n.type||!e.model.getters.isSpillPivotFormula(r))continue;const a=n.domain.at(-1)?.field;if(!s&&a)s=a;else if(s&&a&&s!==a)return;o.push(n)}}if(!t||!s||0===o.length)return;const i=e.model.getters.getPivot(t).getFields()[s];if(!i)return;return{pivotId:t,values:o.map(e=>e.domain.at(-1)?.value).filter(e=>void 0!==e),field:i}}function tB(e,t,s,o){if(s.isCustomField){const o=(e.customFields||{})[s.name];return!!o&&o.groups.some(e=>t.includes(e.name))}return Up(e,s,o).groups.some(e=>e.isOtherGroup||t.some(t=>e.values.includes(t)))}const sB=new xz;sB.add("cut",{...zH,sequence:10}).add("copy",{...VH,sequence:20}).add("paste",{...HH,sequence:30}).add("paste_special",{...UH,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...BH,sequence:10}).addChild("paste_format_only",["paste_special"],{...GH,sequence:20}).add("add_row_before",{...cU,sequence:70}).add("add_column_before",{...mU,sequence:90}).add("insert_cell",{...bU,sequence:100,separator:!0}).addChild("insert_cell_down",["insert_cell"],{...SU,name:Cs("Shift down"),sequence:10}).addChild("insert_cell_right",["insert_cell"],{...yU,name:Cs("Shift right"),sequence:20}).add("delete_row",{...ZH,sequence:110,icon:"o-spreadsheet-Icon.TRASH"}).add("delete_column",{...XH,sequence:120,icon:"o-spreadsheet-Icon.TRASH"}).add("delete_cell",{...JH,sequence:130,separator:!0,icon:"o-spreadsheet-Icon.TRASH"}).addChild("delete_cell_up",["delete_cell"],{...QH,name:Cs("Shift up"),sequence:10,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP"}).addChild("delete_cell_left",["delete_cell"],{...eU,name:Cs("Shift left"),sequence:20,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT"}).add("edit_table",{...sU,isVisible:eH,isEnabled:e=>!e.isSmall,sequence:140}).add("delete_table",{...oU,isVisible:eH,sequence:145,separator:!0}).add("insert_link",{...PU,name:e=>{const t=e.model.getters.getActiveSheetId(),{col:s,row:o}=e.model.getters.getActivePosition(),i=e.model.getters.getEvaluatedCell({sheetId:t,col:s,row:o});return i&&i.link?Cs("Edit link"):Cs("Insert link")},sequence:150,separator:!0}).add("pivot_headers_group",{sequence:155,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",...$U}).add("pivot_group_remaining",{sequence:155,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",...qU}).add("pivot_headers_ungroup",{sequence:155,icon:"o-spreadsheet-Icon.MINUS_IN_BOX",...ZU}).add("collapse_pivot",{sequence:156,name:Cs("Expand/Collapse"),icon:"o-spreadsheet-Icon.COLLAPSE"}).addChild("toggle_collapse_pivot_cell",["collapse_pivot"],{sequence:10,...jU}).addChild("collapse_all_pivot",["collapse_pivot"],{sequence:20,...YU}).addChild("expand_all_pivot",["collapse_pivot"],{sequence:30,...XU}).add("pivot_sorting",{name:Cs("Sort pivot"),sequence:155,icon:"o-spreadsheet-Icon.SORT_RANGE",isVisible:e=>{const t=e.model.getters.getActivePosition();return JU(e.model.getters,t)}}).add("pivot_fix_formulas",{...WU,sequence:160}).add("pivot_properties",{...HU,sequence:170,separator:!0}).addChild("pivot_sorting_asc",["pivot_sorting"],{...UU,sequence:10}).addChild("pivot_sorting_desc",["pivot_sorting"],{...BU,sequence:20}).addChild("pivot_sorting_none",["pivot_sorting"],{...GU,sequence:30});const oB={name:Cs("Sort range"),isVisible:sH,icon:"o-spreadsheet-Icon.SORT_RANGE"},iB={name:Cs("Ascending (A ⟶ Z)"),execute:e=>{const{anchor:t,zones:s}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();hV(e,o,t.cell,s[0],"asc")},icon:"o-spreadsheet-Icon.SORT_ASCENDING"},nB={name:Cs("Data cleanup"),icon:"o-spreadsheet-Icon.DATA_CLEANUP"},rB={name:Cs("Remove duplicates"),execute:e=>{1===ss(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection(),e.openSidePanel("RemoveDuplicates",{})},isEnabled:e=>!e.isSmall},aB={name:Cs("Trim whitespace"),execute:e=>{e.model.dispatch("TRIM_WHITESPACE")}},lB={name:Cs("Descending (Z ⟶ A)"),execute:e=>{const{anchor:t,zones:s}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();hV(e,o,t.cell,s[0],"desc")},icon:"o-spreadsheet-Icon.SORT_DESCENDING"},cB={...iH},hB={...iH,isActive:e=>Qz(e)},dB={name:Cs("Split text to columns"),sequence:1,execute:e=>e.openSidePanel("SplitToColumns",{}),isEnabled:e=>!e.isSmall&&e.model.getters.isSingleColSelected(),icon:"o-spreadsheet-Icon.SPLIT_TEXT"},uB={id:"reinsert_dynamic_pivot",name:Cs("Re-insert dynamic pivot"),sequence:60,icon:"o-spreadsheet-Icon.INSERT_PIVOT",children:[e=>e.model.getters.getPivotIds().map((t,s)=>({id:`reinsert_dynamic_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:s,execute:e=>{const s=e.model.getters.getSelectedZone(),o=e.model.getters.getPivot(t).getCollapsedTableStructure().export();e.model.dispatch("INSERT_PIVOT_WITH_TABLE",{pivotId:t,table:o,col:s.left,row:s.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:"dynamic"}),e.model.dispatch("REFRESH_PIVOT",{id:t})},isVisible:e=>e.model.getters.getPivot(t).isValid()}))],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())},gB={id:"reinsert_static_pivot",name:Cs("Re-insert static pivot"),sequence:70,icon:"o-spreadsheet-Icon.INSERT_PIVOT",children:[e=>e.model.getters.getPivotIds().map((t,s)=>({id:`reinsert_static_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:s,execute:e=>{const s=e.model.getters.getSelectedZone(),o=e.model.getters.getPivot(t).getExpandedTableStructure();o.numberOfCells>se?e.notifyUser({type:"warning",text:Kg(o.numberOfCells,e.model.getters.getLocale()),sticky:!0}):(e.model.dispatch("INSERT_PIVOT_WITH_TABLE",{pivotId:t,table:o.export(),col:s.left,row:s.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:"static"}),e.model.dispatch("REFRESH_PIVOT",{id:t}))},isVisible:e=>e.model.getters.getPivot(t).isValid()}))],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())};function pB({name:e,format:t,descriptionValue:s}){const o="function"==typeof t?t:()=>t;return{name:e,description:e=>zi(s,{format:o(e),locale:e.model.getters.getLocale()}),execute:e=>Gz(e,o(e)),isActive:e=>aG(e,o(e)),format:t}}const mB={name:Cs("Automatic"),execute:e=>Gz(e,""),isActive:e=>function(e){const t=e.model.getters.getActivePosition(),s=e.model.getters.getPivotCellFromPosition(t);if("VALUE"===s.type)return!e.model.getters.getEvaluatedCell(t).format;return!e.model.getters.getCell(t)?.format}(e)},fB={name:Cs("Plain text"),execute:e=>Gz(e,"@"),isActive:e=>aG(e,"@")},vB=pB({name:Cs("Number"),descriptionValue:1000.12,format:"#,##0.00"}),bB={name:Cs("Format as percent"),execute:e=>Gz(e,"0.00%"),icon:"o-spreadsheet-Icon.PERCENT"},SB=pB({name:Cs("Percent"),descriptionValue:.1012,format:"0.00%"}),yB=pB({name:Cs("Scientific"),descriptionValue:.1012,format:"0.00e"}),CB=pB({name:Cs("Currency"),descriptionValue:1000.12,format:e=>en(e.model.config.defaultCurrency||oe)}),IB={...pB({name:Cs("Currency rounded"),descriptionValue:1e3,format:e=>on(en(e.model.config.defaultCurrency||oe))}),isVisible:e=>{const t=en(e.model.config.defaultCurrency||oe);return t!==on(t)}},wB=pB({name:Cs("Accounting"),descriptionValue:-1000.12,format:e=>tn(e.model.config.defaultCurrency||oe)}),EB=_b("2023/09/26 10:43:00 PM",gi),xB={name:Cs("Custom currency"),isVisible:e=>void 0!==e.loadCurrencies&&!e.isSmall,execute:e=>e.openSidePanel("MoreFormats",{category:"currency"})},RB=pB({name:Cs("Date"),descriptionValue:EB,format:e=>e.model.getters.getLocale().dateFormat}),TB=pB({name:Cs("Time"),descriptionValue:EB,format:e=>e.model.getters.getLocale().timeFormat}),AB=pB({name:Cs("Date time"),descriptionValue:EB,format:e=>Dh(e.model.getters.getLocale())}),_B=pB({name:Cs("Duration"),descriptionValue:"27:51:38",format:"hhhh:mm:ss"}),DB={name:Cs("Custom date and time"),isVisible:e=>!e.isSmall,execute:e=>e.openSidePanel("MoreFormats",{category:"date"})},OB={name:Cs("Custom number format"),isVisible:e=>!e.isSmall,execute:e=>e.openSidePanel("MoreFormats",{category:"number"})};pB({name:Cs("Full date time"),format:"dddd d mmmm yyyy hh:mm:ss a",descriptionValue:EB});const FB={name:Cs("Increase decimal places"),icon:"o-spreadsheet-Icon.INCREASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:1})},PB={name:Cs("Decrease decimal places"),icon:"o-spreadsheet-Icon.DECRASE_DECIMAL",execute:e=>e.model.dispatch("SET_DECIMAL",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:-1})},MB={name:Cs("Bold"),description:"Ctrl+B",execute:e=>Wz(e,{bold:!e.model.getters.getCurrentStyle().bold}),icon:"o-spreadsheet-Icon.BOLD",isActive:e=>!!e.model.getters.getCurrentStyle().bold},NB={name:Cs("Italic"),description:"Ctrl+I",execute:e=>Wz(e,{italic:!e.model.getters.getCurrentStyle().italic}),icon:"o-spreadsheet-Icon.ITALIC",isActive:e=>!!e.model.getters.getCurrentStyle().italic},kB={name:Cs("Underline"),description:"Ctrl+U",execute:e=>Wz(e,{underline:!e.model.getters.getCurrentStyle().underline}),icon:"o-spreadsheet-Icon.UNDERLINE",isActive:e=>!!e.model.getters.getCurrentStyle().underline},LB={name:Cs("Rotation"),icon:e=>function(e){switch(function(e){const t=e.model.getters.getCurrentStyle();return t.rotation??0}(e)){case Math.PI/2:return"o-spreadsheet-Icon.ROTATION-90";case-Math.PI/2:return"o-spreadsheet-Icon.ROTATION-270";case Math.PI/4:return"o-spreadsheet-Icon.ROTATION-45";case-Math.PI/4:return"o-spreadsheet-Icon.ROTATION-315";default:return"o-spreadsheet-Icon.ROTATION-0"}}(e)},VB={name:Cs("No rotation"),execute:e=>Wz(e,{rotation:0}),icon:"o-spreadsheet-Icon.ROTATION-0",isActive:e=>0===e.model.getters.getCurrentStyle().rotation},zB={name:Cs("45° rotation"),execute:e=>Wz(e,{rotation:Math.PI/4}),icon:"o-spreadsheet-Icon.ROTATION-45",isActive:e=>e.model.getters.getCurrentStyle().rotation===Math.PI/4},HB={name:Cs("90° rotation"),execute:e=>Wz(e,{rotation:Math.PI/2}),icon:"o-spreadsheet-Icon.ROTATION-90",isActive:e=>e.model.getters.getCurrentStyle().rotation===Math.PI/2},UB={name:Cs("-90° rotation"),execute:e=>Wz(e,{rotation:-Math.PI/2}),icon:"o-spreadsheet-Icon.ROTATION-270",isActive:e=>e.model.getters.getCurrentStyle().rotation===-Math.PI/2},BB={name:Cs("-45° rotation"),execute:e=>Wz(e,{rotation:-Math.PI/4}),icon:"o-spreadsheet-Icon.ROTATION-315",isActive:e=>e.model.getters.getCurrentStyle().rotation===-Math.PI/4},GB={name:Cs("Strikethrough"),execute:e=>Wz(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),icon:"o-spreadsheet-Icon.STRIKE",isActive:e=>!!e.model.getters.getCurrentStyle().strikethrough},WB={name:Cs("Font size"),children:ee.map(e=>({name:e.toString(),sequence:e,id:`font_size_${e}`,execute:t=>Wz(t,{fontSize:e}),isActive:t=>function(e,t){const s=e.model.getters.getCurrentStyle().fontSize||z;return s===t}(t,e)})),icon:"o-spreadsheet-Icon.FONT_SIZE"},$B={name:Cs("Alignment"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},qB={name:Cs("Horizontal align"),icon:e=>function(e){switch(lG(e)){case"right":return"o-spreadsheet-Icon.ALIGN_RIGHT";case"center":return"o-spreadsheet-Icon.ALIGN_CENTER";default:return"o-spreadsheet-Icon.ALIGN_LEFT"}}(e)},ZB={name:Cs("Left"),description:"Ctrl+Shift+L",execute:e=>Wz(e,{align:"left"}),isActive:e=>"left"===lG(e),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},jB={name:Cs("Center"),description:"Ctrl+Shift+E",execute:e=>Wz(e,{align:"center"}),isActive:e=>"center"===lG(e),icon:"o-spreadsheet-Icon.ALIGN_CENTER"},YB={name:Cs("Right"),description:"Ctrl+Shift+R",execute:e=>Wz(e,{align:"right"}),isActive:e=>"right"===lG(e),icon:"o-spreadsheet-Icon.ALIGN_RIGHT"},XB={name:Cs("Vertical align"),icon:e=>function(e){switch(cG(e)){case"top":return"o-spreadsheet-Icon.ALIGN_TOP";case"middle":return"o-spreadsheet-Icon.ALIGN_MIDDLE";default:return"o-spreadsheet-Icon.ALIGN_BOTTOM"}}(e)},KB={name:Cs("Top"),execute:e=>Wz(e,{verticalAlign:"top"}),isActive:e=>"top"===cG(e),icon:"o-spreadsheet-Icon.ALIGN_TOP"},JB={name:Cs("Middle"),execute:e=>Wz(e,{verticalAlign:"middle"}),isActive:e=>"middle"===cG(e),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},QB={name:Cs("Bottom"),execute:e=>Wz(e,{verticalAlign:"bottom"}),isActive:e=>"bottom"===cG(e),icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"},eG={name:Cs("Wrapping"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},tG={name:Cs("Wrapping"),icon:e=>function(e){switch(hG(e)){case"wrap":return"o-spreadsheet-Icon.WRAPPING_WRAP";case"clip":return"o-spreadsheet-Icon.WRAPPING_CLIP";default:return"o-spreadsheet-Icon.WRAPPING_OVERFLOW"}}(e)},sG={name:Cs("Overflow"),execute:e=>Wz(e,{wrapping:"overflow"}),isActive:e=>"overflow"===hG(e),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},oG={name:Cs("Wrap"),execute:e=>Wz(e,{wrapping:"wrap"}),isActive:e=>"wrap"===hG(e),icon:"o-spreadsheet-Icon.WRAPPING_WRAP"},iG={name:Cs("Clip"),execute:e=>Wz(e,{wrapping:"clip"}),isActive:e=>"clip"===hG(e),icon:"o-spreadsheet-Icon.WRAPPING_CLIP"};Cs("Text Color"),Cs("Fill Color");const nG={name:Cs("Conditional formatting"),execute:e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.CONDITIONAL_FORMAT"},rG={name:Cs("Clear formatting"),description:"Ctrl+<",execute:e=>e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()}),icon:"o-spreadsheet-Icon.CLEAR_FORMAT"};function aG(e,t){const s=e.model.getters.getActivePosition();return"VALUE"===e.model.getters.getPivotCellFromPosition(s).type?e.model.getters.getEvaluatedCell(s).format===t:e.model.getters.getCell(s)?.format===t}function lG(e){const t=e.model.getters.getCurrentStyle();if(t.align)return t.align;return e.model.getters.getActiveCell().defaultAlign}function cG(e){const t=e.model.getters.getCurrentStyle();return t.verticalAlign?t.verticalAlign:L}function hG(e){const t=e.model.getters.getCurrentStyle();return t.wrapping?t.wrapping:V}const dG=new xz;dG.add("cut",{...zH,sequence:10}).add("copy",{...VH,sequence:20}).add("paste",{...HH,sequence:30}).add("paste_special",{...UH,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...BH,sequence:10}).addChild("paste_format_only",["paste_special"],{...GH,sequence:20}).add("sort_columns",{...oB,name:e=>e.model.getters.getActiveCols().size>1?Cs("Sort columns"):Cs("Sort column"),sequence:50,separator:!0}).addChild("sort_ascending",["sort_columns"],{...iB,sequence:10}).addChild("sort_descending",["sort_columns"],{...lB,sequence:20}).add("add_column_before",{...gU,sequence:70}).add("add_column_after",{...fU,sequence:80}).add("delete_column",{...YH,sequence:90,icon:"o-spreadsheet-Icon.TRASH"}).add("clear_column",{...KH,sequence:100,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_columns",{...lH,sequence:105,separator:!0}).add("unhide_columns",{...cH,sequence:106,separator:!0}).add("conditional_formatting",{...nG,sequence:110,separator:!0}).add("edit_table",{...sU,isVisible:eH,sequence:120}).add("delete_table",{...oU,isVisible:eH,sequence:125,separator:!0}).add("group_columns",{sequence:150,...TH}).add("ungroup_columns",{sequence:155,..._H,isVisible:e=>PH(e,"COL")});const uG={CannotHideAllRows:Cs("Cannot hide all the rows of a sheet."),CannotHideAllColumns:Cs("Cannot hide all the columns of a sheet.")};function gG(e,t,s,o,i){const n=e.model.getters.getHeaderGroup(t,s,o,i);if(!n)return;const r=n.isFolded?"UNFOLD_HEADER_GROUP":"FOLD_HEADER_GROUP",a=e.model.dispatch(r,{sheetId:t,dimension:s,start:n.start,end:n.end});if(!a.isSuccessful&&a.isCancelledBecause("NotEnoughElements")){const t="ROW"===s?uG.CannotHideAllRows:uG.CannotHideAllColumns;e.raiseError(t)}}function pG(e,t){return Sv([{id:"unfold_all",name:Cs("ROW"===t?"Expand all row groups":"Expand all column groups"),execute:s=>{s.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:e,dimension:t})},icon:"o-spreadsheet-Icon.EXPAND"},{id:"fold_all",name:Cs("ROW"===t?"Collapse all row groups":"Collapse all column groups"),execute:s=>{s.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:e,dimension:t})},icon:"o-spreadsheet-Icon.COLLAPSE"}])}const mG=new xz;mG.add("group_columns",{sequence:10,...TH,isVisible:()=>!0,isEnabled:TH.isVisible}).add("group_rows",{sequence:20,...AH,isVisible:()=>!0,isEnabled:AH.isVisible});const fG=new xz;fG.add("ungroup_columns",{sequence:10,..._H,isEnabled:e=>PH(e,"COL")}).add("ungroup_rows",{sequence:20,...DH,isEnabled:e=>PH(e,"ROW")});const vG=new xz;vG.add("cut",{...zH,sequence:10}).add("copy",{...VH,sequence:20}).add("paste",{...HH,sequence:30}).add("paste_special",{...UH,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...BH,sequence:10}).addChild("paste_format_only",["paste_special"],{...GH,sequence:20}).add("add_row_before",{...aU,sequence:50}).add("add_row_after",{...hU,sequence:60}).add("delete_row",{...qH,sequence:70,icon:"o-spreadsheet-Icon.TRASH"}).add("clear_row",{...jH,sequence:80,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_rows",{...dH,sequence:85,separator:!0}).add("unhide_rows",{...uH,sequence:86,separator:!0}).add("conditional_formatting",{...nG,sequence:90,separator:!0}).add("group_rows",{sequence:100,...AH}).add("ungroup_rows",{sequence:110,...DH,isVisible:e=>PH(e,"ROW")});class bG extends Lv{highlightStore=this.get(NV);constructor(e){super(e),this.highlightStore.register(this)}get highlights(){const e=this.model.getters.getActivePosition(),t=this.model.getters.getArrayFormulaSpreadingOn(e),s=t?this.model.getters.getSpreadZone(t,{ignoreSpillError:!0}):this.model.getters.getSpreadZone(e,{ignoreSpillError:!0});if(!s)return[];const o=this.model.getters.isArrayFormulaSpillBlocked(t??e);return[{range:this.model.getters.getRangeFromZone(e.sheetId,s),dashed:o,color:"#17A2B8",noFill:!0,thinLine:!0}]}}class SG extends Lv{mutators=["focusClient","unfocusClient","showClientTag","hideClientTag","jumpToClient"];_showClientTag=!1;clientFocusTimeout={};constructor(e){super(e),this.onDispose(()=>{for(const e in this.clientFocusTimeout)this.unfocusClient(e)})}get focusedClients(){const e=new Set;return this.model.getters.getConnectedClients().forEach(t=>{(this._showClientTag||void 0!==this.clientFocusTimeout[t.id])&&e.add(t.id)}),e}jumpToClient(e){const t=this.model.getters.getClient(e);this.focusClient(e),t.position&&(this.model.dispatch("ACTIVATE_SHEET",{sheetIdTo:t.position.sheetId,sheetIdFrom:this.getters.getActiveSheetId()}),this.model.dispatch("SCROLL_TO_CELL",{col:t.position.col,row:t.position.row}))}showClientTag(){this._showClientTag=!0}hideClientTag(){this._showClientTag=!1}focusClient(e){this.clientFocusTimeout[e]&&clearTimeout(this.clientFocusTimeout[e]),this.clientFocusTimeout[e]=setTimeout(()=>this.unfocusClient(e),3e3)}unfocusClient(e){this.clientFocusTimeout[e]&&clearTimeout(this.clientFocusTimeout[e]),this.clientFocusTimeout[e]=void 0}}function yG(e){let s,o,i,n,r=null,a="all";const l=e.model.getters,c=e=>e.preventDefault(),h=()=>removeEventListener("keydown",c,{capture:!0});let d=[];const u=()=>{clearTimeout(r),r=null,d.forEach(e=>e()),d=[]};let g,p;const m=t=>{if(s=t,r)return;const c=l.getActiveSheetId(),h=_N(e.model.getters.getViewportZoomLevel()),d=$N(e,s,h),{x:u,y:p}=l.getMainViewportCoordinates(),{top:f,left:v,bottom:b,right:S}=l.getActiveMainViewport();let{scrollX:y,scrollY:C}=l.getActiveSheetScrollInfo();const{xSplit:I,ySplit:w}=l.getPaneDivisions(c);let E=!1,x=140;const R=d.clientX-h.x;let T=l.getColIndex(R);if("vertical"!==a){const t=o.clientX-h.x,s=l.getEdgeScrollCol(R,t,i);if(s.canEdgeScroll){E=!0,x=Math.min(x,s.delay);let t=T;switch(s.direction){case"reset":T=t=I;break;case 1:T=S,t=v+1;break;case-1:for(T=v-1;e.model.getters.isColHidden(c,T);)T--;t=T}y=l.getColDimensions(c,t).start-u}}const A=d.clientY-h.y;let _=l.getRowIndex(A);if("horizontal"!==a){const t=o.clientY-h.y,s=l.getEdgeScrollRow(A,t,n);if(s.canEdgeScroll){E=!0,x=Math.min(x,s.delay);let t=_;switch(s.direction){case"reset":_=t=w;break;case 1:_=b,t=f+1;break;case-1:for(_=f-1;e.model.getters.isRowHidden(c,_);)_--;t=_}C=e.model.getters.getRowDimensions(c,t).start-p}}E||(T=CG(T,R,l.getNumberCols(c)-1),_=CG(_,A,l.getNumberRows(c)-1)),g?.(T,_,s),E&&(e.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:y,offsetY:C}),r=setTimeout(()=>{r=null,m(s)},Math.round(x))),o={clientX:d.clientX,clientY:d.clientY}},f=()=>{p?.(),u()};return t.onWillUnmount(()=>{u()}),t.useEffect(()=>{u()},()=>[l.getActiveSheetId()]),{start:(t,s,r,l="all")=>{u();const v=_N(e.model.getters.getViewportZoomLevel());a=l,i=t.clientX-v.x,n=t.clientY-v.y,o={clientX:t.clientX,clientY:t.clientY},g=s,p=r,addEventListener("keydown",c,{capture:!0}),d.push(qV(m,f),h)}}}function CG(e,t,s){return-1===e?t<0?0:s:e}class IG extends t.Component{static template="o-spreadsheet-Autofill";static props={position:Object,isVisible:Boolean};state=t.useState({position:{x:0,y:0},handler:!1});dragNDropGrid=yG(this.env);get style(){const{x:e,y:t}=this.props.position;return JF({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?"visible":"hidden"})}get handlerStyle(){const{x:e,y:t}=this.state.handler?this.state.position:this.props.position;return JF({top:`${t}px`,left:`${e}px`})}get styleNextValue(){const{x:e,y:t}=this.state.position;return JF({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){const e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=wG),e}onMouseDown(e){this.state.handler=!0;const t=$N(this.env,e),s=this.env.model.getters.getViewportZoomLevel();let o,i;const n=e.clientX/s-this.props.position.x,r=e.clientY/s-this.props.position.y;this.dragNDropGrid.start(t,(e,t,a)=>{if(this.state.position={x:a.clientX/s-n,y:a.clientY/s-r},o!==e||i!==t){const s=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getNumberCols(s),r=this.env.model.getters.getNumberRows(s);o=-1===e?o:me(e,0,n),i=-1===t?i:me(t,0,r),void 0!==o&&void 0!==i&&this.env.model.dispatch("AUTOFILL_SELECT",{col:o,row:i})}},()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch("AUTOFILL")})}onDblClick(){this.env.model.dispatch("AUTOFILL_AUTO")}}class wG extends t.Component{static props={content:String};static template=t.xml`
|
|
836
836
|
<div t-esc="props.content"/>
|
|
837
837
|
`}class EG extends t.Component{static template="o-spreadsheet-ClientTag";static props={active:Boolean,name:String,color:String,col:Number,row:Number};get tagStyle(){const{col:e,row:t,color:s}=this.props,{height:o}=this.env.model.getters.getSheetViewDimensionWithHeaders(),i=this.env.model.getters.isVisibleInViewport({sheetId:this.env.model.getters.getActiveSheetId(),col:e,row:t}),{x:n,y:r}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return JF({bottom:o-r+15+"px",left:n-1+"px",border:`1px solid ${s}`,"background-color":s,visibility:i?"visible":"hidden"})}}const xG=Cs("The cell you are trying to edit has been deleted.");class RG extends VV{canStopEdition(){return"inactive"===this.editionMode||this.checkDataValidation()}stopEdition(e){if(this.canStopEdition())return this._stopEdition(),void(e&&this.model.selection.moveAnchorCell(e,1));const t=this.currentEditedCell,s=St(t.col,t.row),o=this.getters.getValidationRuleForCell(t);if(!o)return;const i=W_.get(o.criterion.type).getErrorString(o.criterion,this.getters,t.sheetId);this.notificationStore.raiseError(Cs("The data you entered in %s violates the data validation rule set on the cell:\n%s",s,i)),this.cancelEdition()}handle(e){switch(super.handle(e),e.type){case"SET_FORMATTING":this.cancelEdition();break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"ACTIVATE_SHEET":if(at(this._currentContent)||(this._cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){const t=this.getters.getActivePosition(),{col:s,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),i=this.getters.expandZone(e.sheetIdTo,Jt({col:s,row:o}));this.model.selection.resetAnchor(this,{cell:{col:s,row:o},zone:i})}break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheetId)||"inactive"===this.editionMode||(this.sheetId=this.getters.getActiveSheetId(),this.resetContent(),this.cancelEditionAndActivateSheet(),this.notificationStore.raiseError(xG))}}get placeholder(){const e=this.getters.getActivePosition(),t=this.model.getters.getArrayFormulaSpreadingOn(e);if(t)return this.getters.getCellText(t,{showFormula:!0})}get currentEditedCell(){return{sheetId:this.sheetId,col:this.col,row:this.row}}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.editionMode)return this.cancelEdition(),void this.notificationStore.raiseError(xG);const{top:t,left:s}=kt({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=s,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.editionMode)return this.cancelEdition(),void this.notificationStore.raiseError(xG);const{top:t,left:s}=kt({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=s,this.row=t}onAddElements(e){const{top:t,left:s}=Nt({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=s,this.row=t}confirmEdition(e){if(e){const t=this.getters.getActiveSheetId(),s=this.getters.getEvaluatedCell({sheetId:t,col:this.col,row:this.row});s.link&&!at(e)&&(e=Ee(e,s.link.url)),this.addHeadersForSpreadingFormula(e),this.model.dispatch("UPDATE_CELL",{...this.currentEditedCell,content:e})}else this.model.dispatch("UPDATE_CELL",{...this.currentEditedCell,content:""});this.model.dispatch("AUTOFILL_TABLE_COLUMN",{...this.currentEditedCell}),this.setContent("")}getComposerContent(e,t){const s=this.getters.getLocale(),o=this.getters.getCell(e);if(o?.isFormula){const l=this.getPrettifiedFormula(o);function c(e){let t=0,s=0;for(;s<e;){t++;const e=l[t];"\n"!==e&&"\t"!==e&&s++}return t}let h=t;return t&&(h={start:c(t.start),end:c(t.end)}),{text:Ih(l,s),adjustedSelection:h}}if(this.model.getters.getArrayFormulaSpreadingOn(e))return{text:""};if(o?.content.startsWith("'"))return{text:o.content};const{format:i,value:n,type:r,formattedValue:a}=this.getters.getEvaluatedCell(e);switch(r){case Xd.empty:return{text:""};case Xd.text:case Xd.error:return{text:n};case Xd.boolean:return{text:a};case Xd.number:if(i&&ji(i)){if(null!==Qs(a,s))return{text:a};return{text:zi(n,{locale:s,format:Number.isInteger(n)?s.dateFormat:Dh(s)})}}return{text:this.numberComposerContent(n,i,s)}}}getPrettifiedFormula(e){if(e.compiledFormula.isBadExpression)return e.content;const t="inactive"===this.editionMode?1/0:80;return cF(ov(e.compiledFormula.tokens),t)}numberComposerContent(e,t,s){return t?.includes("%")?`${Zi(100*e,s.decimalSeparator)}%`:Zi(e,s.decimalSeparator)}addHeadersForSpreadingFormula(e){if(!at(e))return;const t=this.getters.evaluateFormula(this.sheetId,e);if(!Ns(t))return;const s=this.getters.getNumberRows(this.sheetId),o=this.getters.getNumberCols(this.sheetId),i=this.row+t[0].length-s,n=this.col+t.length-o;n>0&&this.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:this.sheetId,sheetName:this.getters.getSheetName(this.sheetId),dimension:"COL",base:o-1,position:"after",quantity:n+20}),i>0&&this.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:this.sheetId,sheetName:this.getters.getSheetName(this.sheetId),dimension:"ROW",base:s-1,position:"after",quantity:i+50})}checkDataValidation(){const e={sheetId:this.sheetId,col:this.col,row:this.row},t=this.getCurrentCanonicalContent(),s=at(t)?this.getters.evaluateFormula(this.sheetId,t):_b(t,this.getters.getLocale());if(_n(s))return!0;const o=this.getters.getValidationResultForCellValue(Tn(s),e);return!(!o.isValid&&o.rule.isBlocking)}}const TG=3*.4*window.devicePixelRatio||1;class AG extends t.Component{static template="o-spreadsheet-GridComposer";static props={gridDims:Object,onInputContextMenu:Function};static components={Composer:_V};rect=this.defaultRect;isEditing=!1;isCellReferenceVisible=!1;currentEditedCell={col:0,row:0,sheetId:this.env.model.getters.getActiveSheetId()};composerStore;composerFocusStore;composerInterface;get defaultRect(){return{x:0,y:0,width:0,height:0}}setup(){const e=Tv(RG);this.composerStore=e,this.composerFocusStore=Tv(zv),this.composerInterface={id:"gridComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"inactive"}),t.onWillUpdateProps(()=>{this.updateComponentPosition(),this.updateCellReferenceVisibility()})}get shouldDisplayCellReference(){return!this.env.isMobile()&&this.isCellReferenceVisible}get cellReference(){const{col:e,row:t,sheetId:s}=this.composerStore.currentEditedCell;return Cr(s!==this.env.model.getters.getActiveSheetId()?this.env.model.getters.getSheetName(s):void 0,St(e,t))}get cellReferenceStyle(){const{x:e,y:t}=this.rect;return JF({left:e-TG+"px",top:t-28+"px"})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get composerProps(){const{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders(),s=this.props.gridDims.height-this.rect.y-2*TG;return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,isDefaultFocus:!0,onComposerContentFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus",selection:e}),onComposerCellFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"cellFocus",content:e}),onInputContextMenu:this.props.onInputContextMenu,composerStore:this.composerStore,inputStyle:`max-height: ${s}px;`,inputMode:"inactive"===this.composerStore.editionMode?"none":void 0}}get containerStyle(){if("inactive"===this.composerStore.editionMode||this.env.isMobile())return"z-index: -1000; opacity: 0;";const e=at(this.composerStore.currentContent),t=this.env.model.getters.getActiveCell(),s=this.env.model.getters.getActivePosition(),o=this.env.model.getters.getCellComputedStyle(s),{x:i,y:n,width:r,height:a}=this.rect,c=!e&&o.fillColor||"#ffffff",h=!e&&o.textColor||"#000000",d=!e&&o.fontSize||10,u=!e&&o.bold?"bold":void 0,g=!e&&o.italic?"italic":"normal",p=e?"none":YF(o);let m="left";e||(m=o.align||t.defaultAlign);const f=this.props.gridDims.height-this.rect.y,v=this.props.gridDims.width-this.rect.x,b=Math.min(a+1,f),S=Math.min(r+1,v);return JF({left:i-1+"px",top:`${n}px`,border:`${TG}px solid ${l}`,"min-width":`${S}px`,"min-height":`${b}px`,"max-width":`${v}px`,"max-height":`${f}px`,background:c,color:h,"font-size":`${RS(d)}px`,"font-weight":u,"font-style":g,"text-decoration":p,"text-align":m})}updateComponentPosition(){const e="inactive"!==this.composerFocusStore.activeComposer.editionMode;e||this.composerFocusStore.activeComposer===this.composerInterface||this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"inactive"});let t=!Le(this.currentEditedCell,this.composerStore.currentEditedCell);if(this.isEditing!==e){if(this.isEditing=e,!e)return void(this.rect=this.defaultRect);this.currentEditedCell=this.composerStore.currentEditedCell,t=!0}if(t){const e=this.env.model.getters.getActivePosition(),t=this.env.model.getters.expandZone(e.sheetId,Jt(e));this.rect=this.env.model.getters.getVisibleRect(t)}}updateCellReferenceVisibility(){if("inactive"===this.composerStore.editionMode)return void(this.isCellReferenceVisible=!1);if(this.isCellReferenceVisible)return;const e=this.env.model.getters.getActiveSheetId(),t=Jt(this.env.model.getters.getSelection().anchor.cell);Le(this.env.model.getters.getVisibleRect(t),this.rect)&&e===this.composerStore.currentEditedCell.sheetId||(this.isCellReferenceVisible=!0)}onFocus(){this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"})}}function _G(e,t,s){return s.map(s=>FG(e,t,!1,s)).filter(s=>function(e,t,s){const{x:o,y:i}=e.getMainViewportCoordinates(),n=[];switch(s.axisType){case"top":case"bottom":case"vCenter":if(t.y<i)return!0;n.push({x:t.x,y:s.position}),n.push({x:t.x+t.width,y:s.position});break;case"left":case"right":case"hCenter":if(t.x<o)return!0;n.push({x:s.position,y:t.y}),n.push({x:s.position,y:t.y+t.height})}return n.some(e.isPixelPositionVisible)}(e,t,s))}function DG(e,t,s,o,i){const n=s.map(s=>FG(e,t,!0,s));let r;for(const t of o){const s=_G(e,t,i);for(const e of n)for(const o of s){if(!OG(e.position,o.position))continue;const s=e.position-o.position;r&&s===r.snapOffset?r.matchedFigIds.push(t.id):(!r||Math.abs(s)<=Math.abs(r.snapOffset))&&(r={matchedFigIds:[t.id],snapOffset:s,snappedAxisType:e.axisType,position:o.position})}}return r}function OG(e,t){return Math.abs(e-t)<=5}function FG(e,t,s,o){let i=0;const{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo(),{x:a,y:l}=e.getMainViewportCoordinates(),c=!s&&t.y<l?t.y+r:t.y,h=!s&&t.x<a?t.x+n:t.x;switch(o){case"top":i=c;break;case"bottom":i=c+t.height-1;break;case"vCenter":i=c+Math.floor(t.height/2)-1;break;case"left":i=h;break;case"right":i=h+t.width-1;break;case"hCenter":i=h+Math.floor(t.width/2)-1}return{position:i,axisType:o}}class PG extends t.Component{static template="o-spreadsheet-FiguresContainer";static props={};static components={FigureComponent:iV};dnd=t.useState({draggedFigure:void 0,horizontalSnap:void 0,verticalSnap:void 0,cancelDnd:void 0,overlappingCarousel:void 0});setup(){t.onMounted(()=>{this.render()}),t.onWillUpdateProps(()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.dnd.draggedFigure?.id;t&&!this.env.model.getters.getFigure(e,t)&&(this.dnd.cancelDnd&&this.dnd.cancelDnd(),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0,this.dnd.cancelDnd=void 0)})}getVisibleFigures(){const e=this.env.model.getters.getVisibleFigures();return this.dnd.draggedFigure&&!e.some(e=>e.id===this.dnd.draggedFigure?.id)&&this.dnd.draggedFigure&&e.push(this.dnd.draggedFigure),e}get containers(){const e=this.getVisibleFigures(),t=[];for(const s of["topLeft","topRight","bottomLeft","bottomRight"]){const o=e.filter(e=>this.getFigureContainer(e)===s);o.length>0&&t.push({type:s,figures:o,style:this.getContainerStyle(s),inverseViewportStyle:this.getInverseViewportPositionStyle(s)})}return this.dnd.draggedFigure&&t.push({type:"dnd",figures:[this.getDndFigure()],style:this.getContainerStyle("dnd"),inverseViewportStyle:this.getInverseViewportPositionStyle("dnd")}),t}getContainerStyle(e){return this.rectToCss(this.getContainerRect(e))}rectToCss(e){return JF({left:`${e.x}px`,top:`${e.y}px`,width:`${e.width}px`,height:`${e.height}px`})}getContainerRect(e){const{width:t,height:s}=this.env.model.getters.getSheetViewDimension(),{x:o,y:i}=this.env.model.getters.getMainViewportCoordinates(),n=["bottomRight","topRight"].includes(e)?o:0,r=t-n,a=["bottomRight","bottomLeft"].includes(e)?i:0;return{x:n,y:a,width:r,height:s-a}}getInverseViewportPositionStyle(e){const{scrollX:t,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo(),{x:o,y:i}=this.env.model.getters.getMainViewportCoordinates();let n=0,r=0;return"dnd"===e&&(n=-t,r=-s),["bottomRight","topRight"].includes(e)&&(n=-t-o),["bottomRight","bottomLeft"].includes(e)&&(r=-s-i),JF({left:`${n}px`,top:`${r}px`})}getFigureContainer(e){const{x:t,y:s}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.draggedFigure?.id?"dnd":e.x<t&&e.y<s?"topLeft":e.x<t?"bottomLeft":e.y<s?"topRight":"bottomRight"}toBottomRightViewport(e){const t=this.getFigureContainer(e),s=this.env.model.getters.getActiveSheetScrollInfo(),o={...e};return["bottomLeft","topLeft"].includes(t)&&(o.x+=s.scrollX),["topLeft","topRight"].includes(t)&&(o.y+=s.scrollY),o}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly())return;if(!this.env.model.dispatch("SELECT_FIGURE",{figureId:e.id}).isSuccessful)return;if(this.env.isMobile())return;const s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getViewportZoomLevel(),i={x:t.clientX/o,y:t.clientY/o},n=this.env.model.getters.getActiveSheetScrollInfo(),r=this.toBottomRightViewport(e),a={maxX:this.env.model.getters.getColDimensions(s,this.env.model.getters.getNumberCols(s)-1).end,maxY:this.env.model.getters.getRowDimensions(s,this.env.model.getters.getNumberRows(s)-1).end};let l=!1;this.dnd.cancelDnd=qV(e=>{const t=this.env.model.getters,s={x:e.clientX/o,y:e.clientY/o},c=Math.abs(s.x-i.x),h=Math.abs(s.y-i.y);if(!l&&c<5&&h<5)return;l=!0;const d=function({x:e,y:t},{x:s,y:o},i,{maxX:n,maxY:r},{scrollX:a,scrollY:l},{scrollX:c,scrollY:h}){const d=e-s+c-a,u=me(i.x+d,0,n-i.width),g=t-o+h-l,p=me(i.y+g,0,r-i.height);return{...i,x:u,y:p}}(s,i,r,a,n,t.getActiveSheetScrollInfo()),u=this.getOtherFigures(r.id),g=this.getCarouselOverlappingChart(d,u);if(this.dnd.overlappingCarousel=g,g)this.dnd.draggedFigure=d,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0;else{const e=function(e,t,s){const o=DG(e,t,["hCenter","right","left"],s,["hCenter","right","left"]),i=DG(e,t,["vCenter","bottom","top"],s,["vCenter","bottom","top"]),{y:n,x:r}=e.getMainViewportCoordinates(),{scrollY:a,scrollX:l}=e.getActiveSheetScrollInfo();if(i){t.y-=i.snapOffset;const e=t.y<n,s=t.y<n;e&&!s?t.y+=a:!e&&s&&(t.y-=a)}if(o){t.x-=o.snapOffset;const e=t.x<r,s=t.x<r;e&&!s?t.x+=l:!e&&s&&(t.x-=l)}return{snappedFigure:t,verticalSnapLine:o,horizontalSnapLine:i}}(t,d,u);this.dnd.draggedFigure=e.snappedFigure,this.dnd.horizontalSnap=this.getSnap(e.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(e.verticalSnapLine)}},t=>{if(!this.dnd.draggedFigure)return;const{col:o,row:i,offset:n}=this.env.model.getters.getPositionAnchorOffset(this.dnd.draggedFigure);this.dnd.overlappingCarousel?this.env.model.dispatch("ADD_FIGURE_CHART_TO_CAROUSEL",{sheetId:s,carouselFigureId:this.dnd.overlappingCarousel.id,chartFigureId:e.id}):this.env.model.dispatch("UPDATE_FIGURE",{sheetId:s,figureId:e.id,offset:n,col:o,row:i}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0})}startResize(e,t,s,o){o.stopPropagation();const i=this.env.model.getters.getActiveSheetScrollInfo(),n=oV.get(e.tag).keepRatio||!1,r=oV.get(e.tag).minFigSize||80,a=this.env.model.getters.getViewportZoomLevel(),l=this.env.model.getters.getActiveSheetId(),c={x:o.clientX/a,y:o.clientY/a},h={maxX:this.env.model.getters.getColDimensions(l,this.env.model.getters.getNumberCols(l)-1).end,maxY:this.env.model.getters.getRowDimensions(l,this.env.model.getters.getNumberRows(l)-1).end};this.dnd.cancelDnd=qV(o=>{const l={x:o.clientX/a,y:o.clientY/a},d=function(e,t,s,{x:o,y:i},{x:n,y:r},a,l,{scrollX:c,scrollY:h},{scrollX:d,scrollY:u},{maxX:g,maxY:p}){let{x:m,y:f,width:v,height:b}=e;if(a&&0!==t&&0!==s){const e=Math.min(t*(n-o+d-c),v-l),a=Math.min(s*(r-i+u-h),b-l),g=Math.min(e/v,a/b);t<0&&(m+=v*g),s<0&&(f+=b*g),v*=1-g,b*=1-g}else{const e=Math.max(t*(o-n+d-c),l-v),a=Math.max(s*(i-r+u-h),l-b);v+=e,b+=a,t<0&&(m-=e),s<0&&(f-=a)}return m+d<=0?(v=v+m+d,m=-d):m+v>g&&(v=g-m),f+u<=0?(b=b+f+u,f=-u):f+b>p&&(b=p-f),{...e,x:m,y:f,width:v,height:b}}(e,t,s,l,c,n,r,i,this.env.model.getters.getActiveSheetScrollInfo(),h),u=this.getOtherFigures(e.id),g=function(e,t,s,o,i){const n=DG(e,o,[-1===t?"left":"right"],i,["right","left"]);n&&(1===t?o.width-=n.snapOffset:-1===t&&(o.x-=n.snapOffset,o.width+=n.snapOffset));const r=DG(e,o,[-1===s?"top":"bottom"],i,["bottom","top"]);return r&&(1===s?o.height-=r.snapOffset:-1===s&&(o.y-=r.snapOffset,o.height+=r.snapOffset)),o.x=Math.round(o.x),o.y=Math.round(o.y),o.height=Math.round(o.height),o.width=Math.round(o.width),{snappedFigure:o,verticalSnapLine:n,horizontalSnapLine:r}}(this.env.model.getters,t,s,d,u);this.dnd.draggedFigure=g.snappedFigure,this.dnd.horizontalSnap=this.getSnap(g.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(g.verticalSnapLine)},o=>{if(!this.dnd.draggedFigure)return;const i=this.env.model.getters.getPositionAnchorOffset(this.dnd.draggedFigure);t&&(i.width=this.dnd.draggedFigure.width),s&&(i.height=this.dnd.draggedFigure.height),this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),figureId:e.id,...i}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0})}getOtherFigures(e){return this.getVisibleFigures().filter(t=>t.id!==e)}getDndFigure(){const e=this.dnd.draggedFigure;if(!e)throw new Error("Dnd figure not found");return e}getFigureStyle(e){return e.id!==this.dnd.draggedFigure?.id?"":JF({opacity:this.dnd.overlappingCarousel?.id?"0.6":"0.9",cursor:"grabbing"})}getFigureClass(e){return e.id!==this.dnd.overlappingCarousel?.id?"":"o-add-to-carousel"}getSnap(e){if(!e||!this.dnd.draggedFigure)return;const{scrollX:t,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo(),o=e.matchedFigIds.map(e=>this.getVisibleFigures().find(t=>t.id===e)).filter(De).map(e=>({x:e.x-t,y:e.y-s,width:e.width,height:e.height})).filter(De),i=function(...e){return qL(Vt(...e.map($L)))}({...this.dnd.draggedFigure,x:this.dnd.draggedFigure.x-t,y:this.dnd.draggedFigure.y-s},...o);return{line:e,containerStyle:this.rectToCss(i),lineStyle:this.getSnapLineStyle(e,i)}}getSnapLineStyle(e,t){if(!e)return"";const{scrollX:s,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo();return["top","vCenter","bottom"].includes(e.snappedAxisType)?JF({top:e.position-t.y-o+"px",left:"0px",width:"100%"}):JF({top:"0px",left:e.position-t.x-s+"px",height:"100%"})}getCarouselOverlappingChart(e,t){if("chart"!==e.tag)return;const s=e.x+e.width/2,o=e.y+e.height/2;let i,n=1/0;for(const r of t){if("carousel"!==r.tag)continue;const t=r.x+r.width/2,a=r.y+r.height/2,l=Math.abs(s-t),c=Math.abs(o-a),h=l**2+c**2;l<=e.width/2&&c<=e.height/2&&h<n&&(n=h,i=r)}return i}}class MG extends t.Component{static template="o-spreadsheet-ValidationMessages";static props={messages:Array,msgType:String,singleBox:{type:Boolean,optional:!0}};get divClasses(){return"warning"===this.props.msgType?"o-validation-warning":"info"===this.props.msgType?"o-validation-info":"o-validation-error"}get alertBoxes(){return this.props.singleBox?[this.props.messages]:this.props.messages.map(e=>[e])}}class NG extends t.Component{static template="o-spreadsheet-GridAddRowsFooter";static props={};static components={ValidationMessages:MG};DOMFocusableElementStore;inputRef=t.useRef("inputRef");state=t.useState({inputValue:"100",errorFlag:!1});setup(){this.DOMFocusableElementStore=Tv(mV),t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}get addRowsPosition(){const e=this.env.model.getters.getActiveSheetId(),{numberOfRows:t}=this.env.model.getters.getSheetSize(e),{scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo();return JF({top:`${this.env.model.getters.getRowDimensions(e,t-1).end-s}px`})}get errorMessages(){return[Cs("Please enter a number between 0 and 10000.")]}onKeydown(e){"ESCAPE"===e.key.toUpperCase()?this.focusDefaultElement():"ENTER"===e.key.toUpperCase()&&this.onConfirm()}onInput(e){const t=e.target.value;this.state.inputValue=t;const s=Number(t);this.state.errorFlag=Number.isNaN(s)||s<=0||s>1e4}onConfirm(){if(this.state.errorFlag)return;const e=Number(this.state.inputValue),t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getNumberRows(t);this.env.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:t,sheetName:this.env.model.getters.getSheetName(t),position:"after",base:s-1,quantity:e,dimension:"ROW"}),this.focusDefaultElement();const{scrollX:o}=this.env.model.getters.getActiveSheetScrollInfo(),{end:i}=this.env.model.getters.getRowDimensions(t,s+e-1);this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o,offsetY:i})}onExternalClick(e){this.inputRef.el===document.activeElement&&e.target!==this.inputRef.el&&this.focusDefaultElement()}focusDefaultElement(){document.activeElement===this.inputRef.el&&this.DOMFocusableElementStore.focus()}}function kG(e,...s){t.useEffect(e=>(e?.addEventListener(...s),()=>e?.removeEventListener(...s)),()=>[e.el])}const LG=["cell","border","style","table","conditionalFormat","merge"];class VG extends Lv{mutators=["activate","cancel","pasteFormat"];highlightStore=this.get(NV);status="inactive";copiedData;constructor(e){super(e),this.highlightStore.register(this),this.onDispose(()=>{this.highlightStore.unRegister(this)})}handle(e){if("PAINT_FORMAT"===e.type)this.paintFormat(e.sheetId,e.target)}activate(e){this.copiedData=this.copyFormats(),this.status=e.persistent?"persistent":"oneOff"}cancel(){this.status="inactive",this.copiedData=void 0}pasteFormat(e){this.model.dispatch("PAINT_FORMAT",{target:e,sheetId:this.getters.getActiveSheetId()})}get isActive(){return"inactive"!==this.status}get clipboardHandlers(){return LG.map(e=>({handlerName:e,handler:new(hP.cellHandlers.get(e))(this.getters,this.model.dispatch)}))}copyFormats(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones(),s={zones:t,sheetId:e};for(const{handlerName:o,handler:i}of this.clipboardHandlers){const n=i.copy(tP(e,t),!1);void 0!==n&&(s[o]=n)}return s}paintFormat(e,t){if(!this.copiedData)return;const s={isCutOperation:!1,pasteOption:"onlyFormat"},{target:o,selectedZones:i}=rP(e,t,this.copiedData,this.clipboardHandlers,s);nP(this.clipboardHandlers,this.copiedData,o,s),aP(this.model.selection,t,i),"oneOff"===this.status&&this.cancel()}get highlights(){const e=this.copiedData;return e?e.zones.map(t=>({range:this.model.getters.getRangeFromZone(e.sheetId,t),color:l,dashed:!0,sheetId:e.sheetId,noFill:!0,thinLine:!0,interactive:!1})):[]}}class zG extends Lv{mutators=["clear","hover"];col;row;overlayColors=new H_;handle(e){if("ACTIVATE_SHEET"===e.type)this.clear()}hover(e){if(!this.getters.isDashboard()||e.col===this.col&&e.row===this.row)return"noStateChange";this.col=e.col,this.row=e.row,this.computeOverlay()}clear(){this.col=void 0,this.row=void 0}computeOverlay(){this.overlayColors=new H_;const{col:e,row:t}=this;if(void 0===e||void 0===t)return;const s=this.getters.getActiveSheetId(),o=this.getters.getTable({sheetId:s,col:e,row:t});if(!o)return;const{left:i,right:n,top:r}=o.range.zone,a=t<r+o.config.numberOfHeaders,l=fe(i,n+1).some(e=>!this.getters.isColHidden(s,e)&&this.getters.getEvaluatedCell({sheetId:s,col:e,row:t}).formattedValue);if(!a&&l)for(let e=i;e<=n;e++)this.overlayColors.set({sheetId:s,col:e,row:t},"#017E8414")}}class HG extends Lv{mutators=["setHoveredIcon"];hoveredIcon=void 0;setHoveredIcon(e){this.hoveredIcon=e}}function UG(e,s){const o=Tv(nV),i=Tv(zG),n={col:void 0,row:void 0},{Date:r}=window;let a,l,c=0;function h(){if(void 0===a||void 0===l)return{col:-1,row:-1};return{col:e.model.getters.getColIndex(a),row:e.model.getters.getRowIndex(l)}}function d(e){const t=FN(s.el);return{x:e.clientX-t.x,y:e.clientY-t.y}}const{pause:u,resume:g}=function(e,s){let o;const{setInterval:i,clearInterval:n}=window,r=()=>{n(o),o=void 0},a=()=>{try{e()}catch(e){throw r(),e}};return t.useEffect(()=>(o=i(a,s),()=>n(o)),()=>[s]),{pause:r,resume:()=>{void 0===o&&(o=i(a,s))}}}(function(){const{col:e,row:t}=h(),s=r.now()-c;s>300&&(e!==n.col||t!==n.row)&&m(void 0,void 0);if(s>300){if(e<0||t<0)return;m(e,t)}},200);function p(e){AN(s.el,e.ev)&&(({x:a,y:l}=d(e)),c=r.now(),i.hover(h()))}function m(e,t){e===n.col&&t===n.row||(n.col=e,n.row=t,o.hover({col:e,row:t}))}return kG(s,"pointermove",t=>!e.isMobile()&&p($N(e,t))),kG(s,"mouseleave",function(t){const o=$N(e,t),{x:i,y:n}=d(o),r=FN(s.el);return n<0||n>r.height||i<0||i>r.width?p(o):u()}),kG(s,"mouseenter",g),kG(s,"pointerdown",function(){const{col:e,row:t}=h();e===n.col&&t===n.row||m(void 0,void 0)}),kG(s,"pointerdown",t=>e.isMobile()&&p($N(e,t))),t.useExternalListener(window,"click",function(e){const t=e.target;s.el.contains(t)||m(void 0,void 0)}),n}class BG extends t.Component{static template="o-spreadsheet-GridOverlay";static props={onCellDoubleClicked:{type:Function,optional:!0},onCellClicked:{type:Function,optional:!0},onCellRightClicked:{type:Function,optional:!0},onGridResized:{type:Function,optional:!0},onGridMoved:Function,gridOverlayDimensions:String,slots:{type:Object,optional:!0},getGridSize:Function};static components={FiguresContainer:PG,GridAddRowsFooter:NG};static defaultProps={onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{}};gridOverlay=t.useRef("gridOverlay");cellPopovers;paintFormatStore;hoveredIconStore;setup(){UG(this.env,this.gridOverlay);const e=new ResizeObserver(()=>{const e=this.gridOverlayEl.getBoundingClientRect(),{width:t,height:s}=this.props.getGridSize();this.props.onGridResized({x:e.left,y:e.top,height:s,width:t})});t.onMounted(()=>{e.observe(this.gridOverlayEl)}),t.onWillUnmount(()=>{e.disconnect()}),this.cellPopovers=Tv(aV),this.paintFormatStore=Tv(VG),this.hoveredIconStore=Tv(HG)}get gridOverlayEl(){if(!this.gridOverlay.el)throw new Error("GridOverlay el is not defined.");return this.gridOverlay.el}get style(){return this.props.gridOverlayDimensions+JF({cursor:this.hoveredIconStore.hoveredIcon?"pointer":"default"})}get isPaintingFormat(){return this.paintFormatStore.isActive}onPointerMove(e){if(this.env.isMobile())return;const t=this.getInteractiveIconAtEvent($N(this.env,e)),s=t?.type?{id:t.type,position:t.position}:void 0;Le(s,this.hoveredIconStore.hoveredIcon)||this.hoveredIconStore.setHoveredIcon(s)}onPointerDown(e){e.button>0||this.env.isMobile()||this.onCellClicked($N(this.env,e))}onClick(e){e.button>0||!this.env.isMobile()||this.onCellClicked($N(this.env,e))}onCellClicked(e){const t=this.cellPopovers.persistentCellPopover,[s,o]=this.getCartesianCoordinates(e),i=this.getInteractiveIconAtEvent(e);i&&this.env.model.selection.getBackToDefault(),this.props.onCellClicked(s,o,{expandZone:e.ev.shiftKey,addZone:zN(e.ev)},e),i?.onClick&&i.onClick(i.position,this.env),e.ev.target===this.gridOverlay.el&&this.cellPopovers.isOpen&&Le(t,this.cellPopovers.persistentCellPopover)&&this.cellPopovers.close()}onDoubleClick(e){const t=$N(this.env,e);if(this.getInteractiveIconAtEvent(t))return;const[s,o]=this.getCartesianCoordinates(t);this.props.onCellDoubleClicked(s,o)}onContextMenu(e){const[t,s]=this.getCartesianCoordinates($N(this.env,e));this.props.onCellRightClicked(t,s,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){return[this.env.model.getters.getColIndex(e.offsetX),this.env.model.getters.getRowIndex(e.offsetY)]}getInteractiveIconAtEvent(e){const t=ON(this.gridOverlay),s=this.env.model.getters.getGridOffset(),o=e.clientX-t.x+s.x,i=e.clientY-t.y+s.y,[n,r]=this.getCartesianCoordinates(e),a=this.env.model.getters.getActiveSheetId();let l={col:n,row:r,sheetId:a};const c=this.env.model.getters.getMerge(l);c&&(l={col:c.left,row:c.top,sheetId:a});const h=this.env.model.getters.getCellIcons(l).find(e=>{const t=this.env.model.getters.getMerge(l)||Jt(l),s=this.env.model.getters.getRect(t);return function(e,t,s){return e>=s.x&&e<=s.x+s.width&&t>=s.y&&t<=s.y+s.height}(o,i,this.env.model.getters.getCellIconRect(e,s))});return h?.onClick?h:void 0}}class GG extends t.Component{static template="o-spreadsheet-GridPopover";static props={onClosePopover:Function,onMouseWheel:Function,gridRect:Object};static components={Popover:jL};cellPopovers;setup(){this.cellPopovers=Tv(aV)}get cellPopover(){const e=this.cellPopovers.cellPopover;if(!e.isOpen)return{isOpen:!1};const t=qN(this.env.model.getters.getViewportZoomLevel(),e.anchorRect);return{...e,anchorRect:{...t,x:t.x+this.props.gridRect.x,y:t.y+this.props.gridRect.y}}}}class WG extends t.Component{static template="o-spreadsheet-UnhideRowHeaders";static props={headersGroups:Array,headerRange:Object,offset:{type:Number,optional:!0}};static defaultProps={offset:0};get sheetId(){return this.env.model.getters.getActiveSheetId()}getUnhidePreviousButtonStyle(e){const t=this.env.model.getters.getRect(Jt({col:0,row:e}));return JF({top:t.y+t.height-O-this.props.offset+"px","margin-right":"1px"})}getUnhideNextButtonStyle(e){return JF({top:this.env.model.getters.getRect(Jt({col:0,row:e})).y-O-this.props.offset+"px","margin-right":"1px"})}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.sheetId,dimension:"ROW",elements:e})}isVisible(e){return e>=this.props.headerRange.start&&e<=this.props.headerRange.end}}class $G extends t.Component{static template="o-spreadsheet-UnhideColumnHeaders";static props={headersGroups:Array,headerRange:Object,offset:{type:Number,optional:!0}};static defaultProps={offset:0};get sheetId(){return this.env.model.getters.getActiveSheetId()}getUnhidePreviousButtonStyle(e){const t=this.env.model.getters.getRect(Jt({col:e,row:0}));return JF({left:t.x+t.width-F-this.props.offset+"px"})}getUnhideNextButtonStyle(e){return JF({left:this.env.model.getters.getRect(Jt({col:e,row:0})).x-F-this.props.offset+"px"})}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.sheetId,dimension:"COL",elements:e})}isVisible(e){return e>=this.props.headerRange.start&&e<=this.props.headerRange.end}}class qG extends t.Component{static props={onOpenContextMenu:Function};composerFocusStore;PADDING=0;MAX_SIZE_MARGIN=0;MIN_ELEMENT_SIZE=0;lastSelectedElementIndex=null;state=t.useState({resizerIsActive:!1,isResizing:!1,isMoving:!1,isSelecting:!1,waitingForMove:!1,activeElement:0,draggerLinePosition:0,draggerShadowPosition:0,draggerShadowThickness:0,delta:0,base:0,position:"before"});dragNDropGrid=yG(this.env);setup(){this.composerFocusStore=Tv(zv)}_computeHandleDisplay(e){const t=this._getEvOffset(e),s=this._getElementIndex(t);if(s<0)return;const o=this._getDimensionsInViewport(s);t-o.start<this.PADDING&&s!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=o.start,this.state.activeElement=this._getPreviousVisibleElement(s)):o.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=o.end,this.state.activeElement=s):this.state.resizerIsActive=!1}_computeGrabDisplay(e){if(zN(e.ev))return void(this.state.waitingForMove=!1);const t=this._getElementIndex(this._getEvOffset(e)),s=this._getActiveElements(),o=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();s.has(o)&&o<=t&&t<=i?this.state.waitingForMove=!0:this.state.waitingForMove=!1}onMouseMove(e){if(this.env.isMobile()||this.env.model.getters.isReadonly()||this.state.isResizing||this.state.isMoving||this.state.isSelecting)return;const t=$N(this.env,e);this._computeHandleDisplay(t),this._computeGrabDisplay(t)}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(e){const t=$N(this.env,e);this._fitElementSize(this.state.activeElement),this.state.isResizing=!1,this._computeHandleDisplay(t),this._computeGrabDisplay(t)}onMouseDown(e){this.state.isResizing=!0,this.state.delta=0;const t=$N(this.env,e),s=this._getClientPosition(t),o=this.state.draggerLinePosition,i=this._getElementSize(this.state.activeElement),n=o-i+this.MIN_ELEMENT_SIZE,r=this._getMaxSize();qV(e=>{this.state.delta=this._getClientPosition($N(this.env,e))-s,this.state.draggerLinePosition=o+this.state.delta,this.state.draggerLinePosition<n&&(this.state.draggerLinePosition=n,this.state.delta=this.MIN_ELEMENT_SIZE-i),this.state.draggerLinePosition>r&&(this.state.draggerLinePosition=r,this.state.delta=r-o)},e=>{this.state.isResizing=!1,0!==this.state.delta&&this._updateSize()})}onClick(e){if(!this.env.isMobile())return;if(e.button>0)return;const t=$N(this.env,e),s=this._getElementIndex(this._getEvOffset(t));this._selectElement(s,!1)}select(e){if(this.env.isMobile())return;if(e.button>0)return;const t=$N(this.env,e),s=this._getElementIndex(this._getEvOffset(t));s<0||(this.env.model.getters.isReadonly()?this._selectElement(s,!1):zN(e)||!this.state.waitingForMove?("editing"===this.composerFocusStore.activeComposer.editionMode&&this.env.model.selection.getBackToDefault(),this.startSelection(e,s)):this.env.model.getters.isGridSelectionActive()?this.startMovement(e):this._selectElement(s,!1))}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;const t=$N(this.env,e),s=this._getDimensionsInViewport(this._getSelectedZoneStart()),o=this._getDimensionsInViewport(this._getSelectedZoneEnd()),i=s.start;this.state.draggerLinePosition=i,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=i,this.state.draggerShadowThickness=o.end-s.start;this.dragNDropGrid.start(t,(e,t)=>{const o="COL"===this._getType()?e:t;if(o>=0){const e=this._getDimensionsInViewport(o);o<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=o,this.state.position="before"):this._getSelectedZoneEnd()<o?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=o,this.state.position="after"):(this.state.draggerLinePosition=s.start,this.state.draggerShadowPosition=s.start,this.state.base=this._getSelectedZoneStart())}},()=>{this.state.isMoving=!1,this.state.base!==this._getSelectedZoneStart()&&this._moveElements();const t=$N(this.env,e);this._computeGrabDisplay(t)})}startSelection(e,t){if(this.env.isMobile())return;this.state.isSelecting=!0,e.shiftKey?this._increaseSelection(t):this._selectElement(t,zN(e)),this.lastSelectedElementIndex=t;const s=$N(this.env,e);this.dragNDropGrid.start(s,(e,t)=>{const s="COL"===this._getType()?e:t;s!==this.lastSelectedElementIndex&&-1!==s&&(this._increaseSelection(s),this.lastSelectedElementIndex=s)},()=>{this.env.model.selection.commitSelection(),this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this._computeGrabDisplay(s)})}onContextMenu(e){e.preventDefault();const t=this._getElementIndex(this._getEvOffset($N(this.env,e)));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);const s=this._getType();this.props.onOpenContextMenu(s,e.clientX,e.clientY)}}class ZG extends qG{static props={onOpenContextMenu:Function};static template="o-spreadsheet-ColResizer";static components={UnhideColumnHeaders:$G};colResizerRef;setup(){super.setup(),this.colResizerRef=t.useRef("colResizer"),this.PADDING=15,this.MAX_SIZE_MARGIN=90,this.MIN_ELEMENT_SIZE=5}get sheetId(){return this.env.model.getters.getActiveSheetId()}_getEvOffset(e){return e.offsetX}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().left}_getClientPosition(e){return e.clientX}_getElementIndex(e){return this.env.model.getters.getColIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().left}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().right}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollCol(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getColDimensionsInViewport(this.sheetId,e)}_getElementSize(e){return this.env.model.getters.getColSize(this.sheetId,e)}_getMaxSize(){return this.colResizerRef.el.clientWidth}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),s=this.env.model.getters.getActiveCols();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"COL",sheetId:this.sheetId,elements:s.has(e)?[...s]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),s=this._getSelectedZoneEnd();for(let o=t;o<=s;o++)e.push(o);const o=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.sheetId,sheetName:this.env.model.getters.getActiveSheetName(),dimension:"COL",base:this.state.base,elements:e,position:this.state.position});!o.isSuccessful&&o.reasons.includes("WillRemoveExistingMerge")&&this.env.raiseError(Wg)}_selectElement(e,t){this.env.model.selection.selectColumn(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectColumn(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveCols();this.env.model.dispatch("AUTORESIZE_COLUMNS",{sheetId:this.sheetId,cols:t.has(e)?[...t]:[e]})}_getType(){return"COL"}_getActiveElements(){return this.env.model.getters.getActiveCols()}_getPreviousVisibleElement(e){const t=this.sheetId;let s;for(s=e-1;s>=0&&this.env.model.getters.isColHidden(t,s);s--);return s}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.sheetId,elements:e,dimension:"COL"})}get mainUnhideHeadersProps(){const{left:e,right:t}=this.env.model.getters.getActiveMainViewport(),{xSplit:s}=this.env.model.getters.getPaneDivisions(this.sheetId),o=this.env.model.getters.getHiddenColsGroups(this.sheetId),i=o.findIndex(e=>e[0]>=s-1);return{headersGroups:o.slice(i),offset:this.env.model.getters.getMainViewportCoordinates().x,headerRange:{start:e,end:t}}}get frozenUnhideHeadersProps(){const{xSplit:e}=this.env.model.getters.getPaneDivisions(this.sheetId),t=this.env.model.getters.getHiddenColsGroups(this.sheetId),s=t.findIndex(t=>t[0]>=e-1);return{headersGroups:t.slice(0,s+1),headerRange:{start:0,end:e-1}}}get frozenContainerStyle(){return JF({width:this.env.model.getters.getMainViewportCoordinates().x+"px"})}get hasFrozenPane(){return this.env.model.getters.getPaneDivisions(this.sheetId).xSplit>0}}class jG extends qG{static props={onOpenContextMenu:Function};static template="o-spreadsheet-RowResizer";static components={UnhideRowHeaders:WG};setup(){super.setup(),this.rowResizerRef=t.useRef("rowResizer"),this.PADDING=5,this.MAX_SIZE_MARGIN=60,this.MIN_ELEMENT_SIZE=10}rowResizerRef;get sheetId(){return this.env.model.getters.getActiveSheetId()}_getEvOffset(e){return e.offsetY}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().top}_getClientPosition(e){return e.clientY}_getElementIndex(e){return this.env.model.getters.getRowIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().top}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().bottom}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollRow(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getRowDimensionsInViewport(this.sheetId,e)}_getElementSize(e){return this.env.model.getters.getRowSize(this.sheetId,e)}_getMaxSize(){return this.rowResizerRef.el.clientHeight}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),s=this.env.model.getters.getActiveRows();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"ROW",sheetId:this.sheetId,elements:s.has(e)?[...s]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),s=this._getSelectedZoneEnd();for(let o=t;o<=s;o++)e.push(o);const o=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.sheetId,sheetName:this.env.model.getters.getActiveSheetName(),dimension:"ROW",base:this.state.base,elements:e,position:this.state.position});o.isSuccessful||(o.reasons.includes("WillRemoveExistingMerge")?this.env.raiseError(Wg):o.reasons.includes("CannotMoveTableHeader")&&this.env.raiseError($g))}_selectElement(e,t){this.env.model.selection.selectRow(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectRow(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveRows();this.env.model.dispatch("AUTORESIZE_ROWS",{sheetId:this.sheetId,rows:t.has(e)?[...t]:[e]})}_getType(){return"ROW"}_getActiveElements(){return this.env.model.getters.getActiveRows()}_getPreviousVisibleElement(e){const t=this.sheetId;let s;for(s=e-1;s>=0&&this.env.model.getters.isRowHidden(t,s);s--);return s}get mainUnhideHeadersProps(){const{top:e,bottom:t}=this.env.model.getters.getActiveMainViewport(),{ySplit:s}=this.env.model.getters.getPaneDivisions(this.sheetId),o=this.env.model.getters.getHiddenRowsGroups(this.sheetId),i=o.findIndex(e=>e[0]>=s-1);return{headersGroups:o.slice(i),offset:this.env.model.getters.getMainViewportCoordinates().y,headerRange:{start:e,end:t}}}get frozenUnhideHeadersProps(){const{ySplit:e}=this.env.model.getters.getPaneDivisions(this.sheetId),t=this.env.model.getters.getHiddenRowsGroups(this.sheetId),s=t.findIndex(t=>t[0]>=e-1);return{headersGroups:t.slice(0,s+1),headerRange:{start:0,end:e-1}}}get frozenContainerStyle(){return JF({height:this.env.model.getters.getMainViewportCoordinates().y+"px"})}get hasFrozenPane(){return this.env.model.getters.getPaneDivisions(this.sheetId).ySplit>0}}class YG extends t.Component{static props={onOpenContextMenu:Function};static template="o-spreadsheet-HeadersOverlay";static components={ColResizer:ZG,RowResizer:jG};selectAll(){this.env.model.selection.selectAll()}}class XG extends Lv{fingerprints;hoveredTables;hoveredIcon;lastRenderBoxes=new Map;preventNewAnimationsInNextFrame=!1;zonesWithPreventedAnimationsInNextFrame=[];animations=new Map;constructor(e){super(e),this.getters=e(Fv).getters,this.fingerprints=e(rH),this.hoveredTables=e(zG),this.hoveredIcon=e(HG)}handle(e){switch(e.type){case"START":case"ACTIVATE_SHEET":case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":this.animations.clear(),this.preventNewAnimationsInNextFrame=!0;break;case"RESIZE_COLUMNS_ROWS":this.preventNewAnimationsInNextFrame=!0;break;case"REDO":this.zonesWithPreventedAnimationsInNextFrame=[];break;case"UNDO":for(const t of e.commands)if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type||"RESIZE_COLUMNS_ROWS"===t.type){this.animations.clear(),this.preventNewAnimationsInNextFrame=!0;break}break;case"PASTE":this.zonesWithPreventedAnimationsInNextFrame.push(...this.getters.getSelectedZones());break;case"UPDATE_CELL":const t=this.getters.getCommandZones(e);this.zonesWithPreventedAnimationsInNextFrame.push(...t)}}finalize(){this.zonesWithPreventedAnimationsInNextFrame=yt(this.zonesWithPreventedAnimationsInNextFrame)}get renderingLayers(){return["Background","Headers"]}drawLayer(e,t,s){switch(t){case"Background":this.drawGlobalBackground(e);const t=this.lastRenderBoxes;this.lastRenderBoxes=new Map;for(const{zone:o,rect:i}of this.getters.getAllActiveViewportsZonesAndRect()){const{ctx:n}=e;n.save(),n.beginPath(),n.rect(i.x,i.y,i.width,i.height),n.clip();const r=this.getGridBoxes(o),a=this.getBoxesWithAnimations(r,t,s);this.drawBackground(e,a),this.drawOverflowingCellBackground(e,a),this.drawCellBackground(e,a),this.drawBorders(e,a),this.drawTexts(e,a),this.drawIcon(e,a),n.restore()}this.drawFrozenPanes(e),this.preventNewAnimationsInNextFrame=!1,this.zonesWithPreventedAnimationsInNextFrame=[];break;case"Headers":this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawGlobalBackground(e){const{ctx:t}=e,{width:o,height:i}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,o+s,i+s)}drawBackground(e,t){const{ctx:s,thinLineWidth:o}=e,i=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),n=i?.1*o:0;if(i)for(const e of t)e.skipCellGridLines||(s.strokeStyle="#E2E3E3",s.lineWidth=o,s.strokeRect(e.x+n,e.y+n,e.width-2*n,e.height-2*n))}drawCellBackground(e,t){const{ctx:s}=e;for(const e of t){const t=e.style;if(t.fillColor&&"#ffffff"!==t.fillColor&&(s.fillStyle=t.fillColor||"#ffffff",s.fillRect(e.x,e.y,e.width,e.height)),e.dataBarFill){s.fillStyle=e.dataBarFill.color;const t=e.dataBarFill.percentage,o=e.width*(t/100);s.fillRect(e.x,e.y,o,e.height)}if(e?.chip){s.save(),s.beginPath(),s.rect(e.x,e.y,e.width,e.height),s.clip();const t=e.chip;s.fillStyle=t.color;const o=10;s.beginPath(),s.roundRect(t.x,t.y,t.width,t.height,o),s.fill(),s.restore()}e.overlayColor&&(s.fillStyle=e.overlayColor,s.fillRect(e.x,e.y,e.width,e.height)),e.isError&&(s.fillStyle="red",s.beginPath(),s.moveTo(e.x+e.width-5,e.y),s.lineTo(e.x+e.width,e.y),s.lineTo(e.x+e.width,e.y+5),s.fill())}}drawOverflowingCellBackground(e,t){const{ctx:s,thinLineWidth:o}=e;for(const e of t)if(e.content&&e.isOverflow){const t=e.content.align||"left";let i,n;const r=e.y+o/2,a=e.height-o,l=Math.min(e.clipRect?.width||1/0,e.content.width);"left"===t?(i=e.x+o/2,n=l-2*o):"right"===t?(i=e.x+e.width-o/2,n=2*o-l):(i=(e.clipRect?.x||e.x+e.width/2-e.content.width/2)+o/2,n=l-2*o),s.fillStyle="#ffffff",s.fillRect(i,r,n,a)}}drawBorders(e,t){const{ctx:s}=e;for(const e of t){const t=e.border;if(t){const{x:s,y:i,width:n,height:r}=e;t.left&&o(t.left,s,i,s,i+r),t.top&&o(t.top,s,i,s+n,i),t.right&&o(t.right,s+n,i,s+n,i+r),t.bottom&&o(t.bottom,s,i+r,s+n,i+r)}}function o({color:e,style:t,opacity:o},i,n,r,a){switch(s.globalAlpha=o??1,s.strokeStyle=e,t){case"medium":s.lineWidth=2,n+=(i+=n===a?-.5:.5)===(r+=n===a?1.5:.5)?-.5:.5,a+=i===r?1.5:.5;break;case"thick":s.lineWidth=3,n===a&&(i--,r++),i===r&&(n--,a++);break;case"dashed":s.lineWidth=1,s.setLineDash([1,3]);break;case"dotted":s.lineWidth=1,n===a&&(i+=.5,r+=.5),i===r&&(n+=.5,a+=.5),s.setLineDash([1,1]);break;default:s.lineWidth=1}s.beginPath(),s.moveTo(i,n),s.lineTo(r,a),s.stroke(),s.lineWidth=1,s.setLineDash([]),s.globalAlpha=1}}drawTexts(e,t){const{ctx:s}=e;let o;s.textBaseline="top";for(const e of t)if(e.content){s.globalAlpha=e.textOpacity??1;const t=e.content.align||"left",i=e.chip?0:e.style.rotation,n={...e.style,align:t,rotation:i},r=TS(n);if(r!==o&&(o=r,s.font=r),s.fillStyle=n.textColor||"#000",s.textAlign=t,e.clipRect){s.save(),s.beginPath();const{x:t,y:o,width:i,height:n}=e.clipRect;s.rect(t,o,i,n),s.clip()}let a=e.content.x,l=e.content.y;n.rotation&&(s.save(),s.rotate(n.rotation),({x:a,y:l}=kS(e.content,n)));for(const t of e.content.textLines)MS(s,t,{x:a,y:l},n.underline,n.strikethrough),l+=4+e.content.fontSizePx;n.rotation&&s.restore(),e.clipRect&&s.restore(),s.globalAlpha=1}}drawIcon(e,t){const{ctx:s}=e;for(const e of t)for(const t of Object.values(e.icons)){if(!t)continue;const o=Le({id:t.type,position:t.position},this.hoveredIcon.hoveredIcon)&&t.hoverSvg||t.svg;if(!o)continue;s.save(),s.globalAlpha=t.opacity??1,s.beginPath();const i=t.clipRect||e;s.rect(i.x,i.y,i.width,i.height),s.clip();const n=t.size,{x:r,y:a}=this.getters.getCellIconRect(t,e);s.translate(r,a),s.scale(n/o.width,n/o.height);for(const e of o.paths)s.fillStyle=e.fillColor,s.fill(nT(e.path));s.restore()}}drawHeaders(e){const{ctx:t,thinLineWidth:s}=e,o=this.getters.getSheetViewVisibleCols(),l=o[0],c=this.getters.getSheetViewVisibleRows(),h=c[0],{width:d,height:u}=this.getters.getSheetViewDimensionWithHeaders(),g=this.getters.getSelectedZones(),p=function(e){const t=new Set;for(const s of yt(e))for(const e of fe(s.left,s.right+1))t.add(e);return t}(g),m=function(e){const t=new Set;for(const s of yt(e))for(const e of fe(s.top,s.bottom+1))t.add(e);return t}(g),f=this.getters.getActiveSheetId(),v=this.getters.getNumberCols(f),b=this.getters.getNumberRows(f),S=this.getters.getActiveCols(),y=this.getters.getActiveRows();t.font=`400 11px ${H}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=s,t.strokeStyle="#333";for(const e of o){const s={left:e,right:e,top:0,bottom:b-1},{x:o,width:a}=this.getters.getVisibleRect(s),l=S.has(e),c=p.has(e);t.fillStyle=l?r:c?n:i,t.fillRect(o,0,a,O)}for(const e of c){const s={top:e,bottom:e,left:0,right:v-1},{y:o,height:a}=this.getters.getVisibleRect(s),l=y.has(e),c=m.has(e);t.fillStyle=l?r:c?n:i,t.fillRect(0,o,F,a)}t.beginPath(),t.moveTo(F,0),t.lineTo(F,u),t.moveTo(0,O),t.lineTo(d,O),t.strokeStyle="#C0C0C0",t.stroke();for(const e of o){const s=lt(e);t.fillStyle=S.has(e)?"#fff":a;const o={left:e,right:e,top:h,bottom:h},{x:i,width:n}=this.getters.getRect(o),{x:r,width:l}=this.getters.getVisibleRect(o);t.save(),t.beginPath(),t.rect(r,0,l,O),t.clip(),t.fillText(s,i+n/2,13),t.restore(),t.beginPath(),t.moveTo(i+n,0),t.lineTo(i+n,O),t.stroke()}for(const e of c){t.fillStyle=y.has(e)?"#fff":a;const s={top:e,bottom:e,left:l,right:l},{y:o,height:i}=this.getters.getRect(s),{y:n,height:r}=this.getters.getVisibleRect(s);t.save(),t.beginPath(),t.rect(0,n,F,r),t.clip(),t.fillText(String(e+1),24,o+i/2),t.restore(),t.beginPath(),t.moveTo(0,o+i),t.lineTo(F,o+i),t.stroke()}}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:s}=e,{x:o,y:i}=this.getters.getMainViewportCoordinates(),n=this.getters.isDashboard()?0:F,r=this.getters.isDashboard()?0:O;t.lineWidth=6*s,t.strokeStyle="#BCBCBC",t.beginPath(),o&&(t.moveTo(n+o,0),t.lineTo(n+o,r)),i&&(t.moveTo(0,r+i),t.lineTo(n,r+i)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:s}=e,{x:o,y:i}=this.getters.getMainViewportCoordinates(),n=this.getters.getSheetViewVisibleCols(),r=n[0],a=n[n.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:r,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:F,u=this.getters.isDashboard()?0:O;t.lineWidth=6*s,t.strokeStyle="#DADFE8",t.beginPath(),o&&(t.moveTo(d+o,u),t.lineTo(d+o,h.height+u)),i&&(t.moveTo(d,u+i),t.lineTo(h.width+d,u+i)),t.stroke()}findNextEmptyCol(e,t,s){const o=this.getters.getActiveSheetId();let i=e;for(;i<t;){const e={sheetId:o,col:i+1,row:s},t=this.getters.getEvaluatedCell(e),n=this.getters.getCellComputedBorder(e),r=this.getters.doesCellHaveGridIcon(e);if(t.type!==Xd.empty||this.getters.isInMerge(e)||n?.left||r)return i;i++}return i}findPreviousEmptyCol(e,t,s){const o=this.getters.getActiveSheetId();let i=e;for(;i>t;){const e={sheetId:o,col:i-1,row:s},t=this.getters.getEvaluatedCell(e),n=this.getters.getCellComputedBorder(e),r=this.getters.doesCellHaveGridIcon(e);if(t.type!==Xd.empty||this.getters.isInMerge(e)||n?.right||r)return i;i--}return i}computeCellAlignment(e,t){const s=this.getters.getCell(e);if(s?.isFormula&&this.getters.shouldShowFormulas())return"left";const o=this.getters.getCellComputedStyle(e)?.align,i=this.getters.getEvaluatedCell(e);return function(e,t){if(!t)return!1;try{const s=Ai(t),{format:o}=Hi(e,s);if("text"===o?.type||"date"===o?.type)return o.tokens.some(e=>"REPEATED_CHAR"===e.type);if("number"===o?.type)return o.integerPart.some(e=>"REPEATED_CHAR"===e.type)||!!o.decimalPart&&o.decimalPart.some(e=>"REPEATED_CHAR"===e.type)}catch{}return!1}(i.value,i.format)?"left":t&&i.type===Xd.number?"center"!==o?"left":o:o||i.defaultAlign}createZoneBox(e,t,s){const{left:o,right:i}=s,n=t.left,r=t.top,a={sheetId:e,col:n,row:r},l=this.getters.getEvaluatedCell(a),c=this.getters.shouldShowFormulas(),{x:h,y:d,width:u,height:g}=this.getters.getRect(t),p=this.getters.getDataValidationChipStyle(a),m=this.getters.getCellComputedBorder(a,s);let f=this.getters.getCellComputedStyle(a,s);if(this.fingerprints.isEnabled){const e=this.fingerprints.colors.get(a);f={...f,fillColor:e}}p?.textColor&&(f={...f,textColor:p.textColor});const v=this.fingerprints.isEnabled?void 0:this.getters.getConditionalDataBar(a),b=this.getters.getCellIcons(a),S={left:b.find(e=>"left"===e?.horizontalAlign),right:b.find(e=>"right"===e?.horizontalAlign),center:b.find(e=>"center"===e?.horizontalAlign)},y={id:Pt(t),x:h,y:d,width:u,height:g,border:m||void 0,style:f,dataBarFill:v,overlayColor:this.hoveredTables.overlayColors.get(a),isError:l.type===Xd.error&&!!l.message||this.getters.isDataValidationInvalid(a),icons:S,disabledAnimation:this.zonesWithPreventedAnimationsInNextFrame.some(e=>Wt(t,e)||Bt(t,e))},C=AS(y.style);if(l.type===Xd.empty||y.icons.center)return y;const I=f.wrapping||"overflow",w="wrap"===I&&!c,E=u-8,x=this.getters.getCellMultiLineText(a,{maxWidth:E,wrapText:w}),R={...f,align:"left",rotation:0},T=Math.max(...x.map(e=>this.getters.getTextWidth(e,R)))+4,A=this.getters.getMultilineTextSize(x,f),_=p?5:0,D=(y.icons.left?y.icons.left.size+y.icons.left.margin:0)+_,O=(y.icons.right?y.icons.right.size+y.icons.right.margin:0)+_,F=D+A.width+O+4,P=this.computeCellAlignment(a,F>u),M=x.length,N=Math.round(this.getters.computeTextYCoordinate(y,C,f.verticalAlign,M));let k=y.x;k+="left"===P?4+D:"right"===P?y.width-4-O:y.width/2,k=Math.round(k);const L=vS(C,M);if(y.content={textLines:x,width:"overflow"===I?T:u,textHeight:L,textWidth:T,align:P,x:k,y:N,fontSizePx:C},p?.fillColor){const e=D,t=5;y.chip={color:p.fillColor,width:y.width-e-t,height:L+2,x:y.x+e,y:N-2}}const V=F>u||A.height>g;if(y.icons.left||y.icons.right||y.chip)y.clipRect={x:y.x+D,y:y.y,width:Math.max(0,u-D-O),height:g};else if(V&&"overflow"===I){let e,s;switch(this.getters.isInMerge(a)?(e=this.getters.getMerge(a).right,s=n):(e=y.border?.right?t.right:this.findNextEmptyCol(n,i,r),s=y.border?.left?t.left:this.findPreviousEmptyCol(n,o,r),y.isOverflow=!0),P){case"left":{const s=Jt({col:e,row:r}),{x:o,y:i,width:n,height:a}=this.getters.getVisibleRect(Vt(t,s));(n<F||C>a||x.length>1)&&(y.clipRect={x:o,y:i,width:n,height:a});break}case"right":{const e=Jt({col:s,row:r}),{x:o,y:i,width:n,height:a}=this.getters.getVisibleRect(Vt(t,e));(n<F||C>a||x.length>1)&&(y.clipRect={x:o,y:i,width:n,height:a});break}case"center":{const o={...t,left:s,right:e},{x:i,y:n,height:r,width:a}=this.getters.getVisibleRect(o),l=F/2,c=y.x+y.width/2;if(i+a<c+l||i>c-l||C>r||x.length>1){const e=i>c-l?i:c-l,t=i+a-e;y.clipRect={x:e,y:n,width:t,height:r}}break}}}else("clip"===I||"wrap"===I||x.length>1)&&(y.clipRect={x:y.x,y:y.y,width:u,height:g});return y}getGridBoxes(e){const t=[],s=this.getters.getSheetViewVisibleCols().filter(t=>t>=e.left&&t<=e.right),o=s[0],i=s[s.length-1],n=this.getters.getSheetViewVisibleRows().filter(t=>t>=e.top&&t<=e.bottom),r={left:o,right:i,top:n[0],bottom:n[n.length-1]},a=this.getters.getActiveSheetId();for(const e of n)for(const o of s){const s={sheetId:a,col:o,row:e};this.getters.isInMerge(s)||t.push(this.createZoneBox(a,Jt(s),r))}for(const s of this.getters.getMerges(a))if(!this.getters.isMergeHidden(a,s)&&Bt(s,r)){const o=this.createZoneBox(a,s,r),i=this.getters.getCellComputedBorder({sheetId:a,col:s.right,row:s.bottom},e);o.border={...o.border,bottom:i?i.bottom:void 0,right:i?i.right:void 0},o.isMerge=!0,t.push(o)}return t}getBoxesWithAnimations(e,t,s){return this.updateAnimationsProgress(s),this.addNewAnimations(e,t,s),this.animations.size>0?(this.renderer.startAnimation("grid_renderer_animation"),this.updateBoxesWithAnimations(e)):(this.renderer.stopAnimation("grid_renderer_animation"),e)}updateBoxesWithAnimations(e){const t=[];for(const s of e){const e=this.animations.get(s.id);if(!e){t.push(s);continue}const o=he(s);t.push(o);for(const i of e.animationTypes){const n=NL.get(i).updateAnimation(e.progress,o,e.oldBox,s);n&&t.push(...n.newBoxes)}}return t}updateAnimationsProgress(e){if(void 0!==e)for(const t of this.animations.keys()){const s=this.animations.get(t);if(void 0===s.startTime){s.startTime=e;continue}const o=e-s.startTime,i=Math.min(1,o/200);i>=1&&this.animations.delete(t),s.progress=i}}addNewAnimations(e,t,s){for(const o of e){this.lastRenderBoxes.set(o.id,o);const e=t.get(o.id);if(this.preventNewAnimationsInNextFrame||!e||o.disabledAnimation)continue;const i=[];for(const t of NL.getAll())t.hasAnimation(e,o)&&i.push(t.id);const n=i.length>0?{animationTypes:i,oldBox:e,progress:0,startTime:s}:void 0;n&&this.animations.set(o.id,n)}}}function KG(e,s,o){const i=t.useRef(e);t.useEffect(function(){const e=i.el,t=window.devicePixelRatio||1,r=e.getContext("2d",{alpha:!1}),a=Math.max(s.getters.getViewportZoomLevel(),1),l={ctx:r,dpr:t,thinLineWidth:.4*t};let{width:c,height:h}=o();if(c*=a,h*=a,e.style.width=`${c}px`,e.style.height=`${h}px`,e.width=c*t,e.height=h*t,e.setAttribute("style",`width:${c}px;height:${h}px;zoom:${1/a}`),0===c||0===h)return;r.translate(-.5,-.5),r.scale(t*a,t*a),n.draw(l)});const n=Tv(kv);Tv(XG)}function JG(e,t,s,o){let i=0,n=0,r=0,a=0,l=!1,c=0,h=null;function d(){if(Math.abs(r)<.05&&(r=0),Math.abs(a)<.05&&(a=0),!r&&!a)return;const e=Date.now(),s=Math.abs(e-c);t(1*(r*s),1*(a*s)),c=e,r*=.95,a*=.95,requestAnimationFrame(d)}kG(e,"touchstart",function(e){l=!0,({clientX:i,clientY:n}=e.touches[0]),r=0,a=0},{capture:!1}),kG(e,"touchmove",function(e){if(!l)return;h&&(clearTimeout(h),h=null);const d=Date.now(),{clientX:u,clientY:g}=e.touches[0],p=i-u,m=n-g,f=d-c;if(!f)return;r=p/f,a=m/f,i=u,n=g,c=d,(m<0&&s()||m>0&&o())&&(e.cancelable&&e.preventDefault(),e.stopPropagation());h=setTimeout(()=>{r=0,a=0},100),t(1*p,1*m)},{capture:!1}),kG(e,"touchend",function(e){l=!1,i=n=0,h&&clearTimeout(h);r*=1.2,a*=1.2,requestAnimationFrame(d)},{capture:!1})}function QG(e){function t(e,t){return e*(0===t?1:P)}return s=>{const o=t(s.shiftKey&&!VN()?s.deltaY:s.deltaX,s.deltaMode),i=t(s.shiftKey&&!VN()?s.deltaX:s.deltaY,s.deltaMode);e(o,i)}}class eW extends t.Component{static template="o-spreadsheet-Border";static props={zone:Object,orientation:String,isMoving:Boolean,onMoveHighlight:Function};get style(){const e=["n","w","e"].includes(this.props.orientation),t=["n","w","s"].includes(this.props.orientation),s=["n","s"].includes(this.props.orientation),o=["w","e"].includes(this.props.orientation),i=this.props.zone,n=this.env.model.getters.getVisibleRect(i),r=n.x,a=n.x+n.width-4,l=n.y,c=n.y+n.height-4;return JF({left:`${t?r:a}px`,top:`${e?l:c}px`,width:`${s?a-r:4}px`,height:`${o?c-l:4}px`})}onMouseDown(e){this.props.onMoveHighlight(e)}}class tW extends t.Component{static template="o-spreadsheet-Corner";static props={zone:Object,color:String,orientation:String,isResizing:Boolean,onResizeHighlight:Function};dirX;dirY;setup(){const{dirX:e,dirY:t}=function(e){const t=e.includes("w")?-1:e.includes("e")?1:0,s=e.includes("n")?-1:e.includes("s")?1:0;return{dirX:t,dirY:s}}(this.props.orientation);this.dirX=e,this.dirY=t}get handlerStyle(){const e=this.props.zone,t=this.env.model.getters.getVisibleRect({left:1===this.dirX?e.right:e.left,right:-1===this.dirX?e.left:e.right,top:1===this.dirY?e.bottom:e.top,bottom:-1===this.dirY?e.top:e.bottom});if(t.width*t.height===0)return"display: none !important;";const s=t.x+t.width/2+this.dirX*t.width/2,o=t.y+t.height/2+this.dirY*t.height/2,i=this.getHandlerEdgeLength(),n={left:s-i/2+"px",top:o-i/2+"px",height:`${i}px`,width:`${i}px`};return this.env.isMobile()&&(n["border-radius"]=i/2+"px"),JF(n)}getHandlerEdgeLength(){return this.env.isMobile()?40:8}get buttonLook(){const e={"background-color":this.props.color,cursor:`${this.props.orientation}-resize`};return this.env.isMobile()&&(e["border-radius"]="4px"),JF(e)}onMouseDown(e){this.props.onResizeHighlight(e,this.dirX,this.dirY)}}class sW extends t.Component{static template="o-spreadsheet-Highlight";static props={range:Object,color:String};static components={Corner:tW,Border:eW};highlightState=t.useState({shiftingMode:"none"});dragNDropGrid=yG(this.env);get cornerOrientations(){if(!this.env.isMobile())return["nw","ne","sw","se"];const e=this.props.range.unboundedZone;return void 0===e.bottom?["w","e"]:void 0===e.right?["n","s"]:["nw","se"]}onResizeHighlight(e,t,s){const o=this.env.model.getters.getActiveSheetId(),i=$N(this.env,e);this.highlightState.shiftingMode="isResizing";const n=this.props.range.zone,r=1===t?n.left:n.right,a=1===s?n.top:n.bottom;let l=1===t?n.right:n.left,c=1===s?n.bottom:n.top,h=n,d="all";this.env.isMobile()&&(d=0===t?"vertical":0===s?"horizontal":"all"),this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{zone:h});this.dragNDropGrid.start(i,(e,t)=>{if(l!==e||c!==t){let{left:s,right:i,top:n,bottom:u}=h;"horizontal"!==d&&(c=c=me(-1===t?c:t,0,this.env.model.getters.getNumberRows(o)-1),n=Math.min(a,c),u=Math.max(a,c)),"vertical"!==d&&(l=me(-1===e?l:e,0,this.env.model.getters.getNumberCols(o)-1),s=Math.min(r,l),i=Math.max(r,l));const g={left:s,right:i,top:n,bottom:u};Ht(g,h)||(this.env.model.selection.selectZone({cell:{col:g.left,row:g.top},zone:g},{unbounded:!0}),h=g)}},()=>{this.highlightState.shiftingMode="none"},d)}onMoveHighlight(e){this.highlightState.shiftingMode="isMoving";const t=this.props.range.zone,s=_N(this.env.model.getters.getViewportZoomLevel()),o=$N(this.env,e,s),i=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getColIndex(o.clientX-s.x),r=this.env.model.getters.getRowIndex(o.clientY-s.y),a=-t.left,l=this.env.model.getters.getNumberCols(i)-t.right-1,c=-t.top,h=this.env.model.getters.getNumberRows(i)-t.bottom-1;let d=t;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{zone:d});let u=n,g=r;this.dragNDropGrid.start(o,(e,s)=>{if(u!==e||g!==s){u=-1===e?u:e,g=-1===s?g:s;const o=me(u-n,a,l),i=me(g-r,c,h),p={left:t.left+o,top:t.top+i,right:t.right+o,bottom:t.bottom+i};Ht(p,d)||(this.env.model.selection.selectZone({cell:{col:p.left,row:p.top},zone:p},{unbounded:!0}),d=p)}},()=>{this.highlightState.shiftingMode="none"})}}let oW=class{direction;el;constructor(e,t){this.el=e,this.direction=t}get scroll(){return"horizontal"===this.direction?this.el.scrollLeft:this.el.scrollTop}set scroll(e){"horizontal"===this.direction?this.el.scrollLeft=e:this.el.scrollTop=e}};class iW extends t.Component{static props={width:{type:Number,optional:!0},height:{type:Number,optional:!0},direction:String,position:Object,offset:Number,onScroll:Function};static template=t.xml`
|
|
838
838
|
<div
|
|
@@ -858,4 +858,4 @@
|
|
|
858
858
|
offset="offset"
|
|
859
859
|
direction="'vertical'"
|
|
860
860
|
onScroll.bind="onScroll"
|
|
861
|
-
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){const{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{y:e}=this.env.model.getters.getMainViewportRect(),t=this.env.model.getters.getScrollBarWidth();return{top:`${this.props.topOffset+e}px`,right:"0px",width:`${t}px`,bottom:BN()?`${t}px`:"0"}}onScroll(e){const{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:t,offsetY:e})}}class aW extends t.Component{static template="o-spreadsheet-Selection";static props={};static components={Highlight:sW};get highlightProps(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getUnboundedZone(e,this.env.model.getters.getSelectedZone());return{range:this.env.model.getters.getRangeFromZone(e,t),color:l}}}function lW({refName:e}){const s=t.useRef(e);t.useEffect(e=>{e?.focus()},()=>[s.el])}class cW extends t.Component{static props={value:[Number,String],onChange:Function,class:{type:String,optional:!0},id:{type:String,optional:!0},placeholder:{type:String,optional:!0},autofocus:{type:Boolean,optional:!0},alwaysShowBorder:{type:Boolean,optional:!0},selectContentOnFocus:{type:Boolean,optional:!0}};refName="input";inputRef;setup(){this.inputRef=t.useRef(this.refName),t.useExternalListener(window,"click",e=>{e.target!==this.inputRef.el&&this.inputRef.el?.value!==this.props.value&&this.save()},{capture:!0}),this.props.autofocus&&lW({refName:this.refName}),t.onWillUpdateProps(e=>{document.activeElement!==this.inputRef.el&&this.inputRef.el&&(this.inputRef.el.value=e.value)}),t.onMounted(()=>{this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString())})}onKeyDown(e){switch(e.key){case"Enter":this.save(),e.preventDefault(),e.stopPropagation();break;case"Escape":this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString(),this.inputRef.el.blur()),e.preventDefault(),e.stopPropagation()}}save(e=!1){const t=(this.inputRef.el?.value||"").trim();t!==this.props.value.toString()&&this.props.onChange(t),e||this.inputRef.el?.blur()}onMouseDown(e){e.target!==document.activeElement&&this.props.selectContentOnFocus&&(e.preventDefault(),e.stopPropagation())}onMouseUp(e){const t=e.target;t!==document.activeElement&&this.props.selectContentOnFocus&&(t.focus(),this.props.selectContentOnFocus&&t.select(),e.preventDefault(),e.stopPropagation())}}class hW extends cW{static template="o-spreadsheet-TextInput";static components={};static props={...cW.props,errorMessage:{type:String,optional:!0}};get inputClass(){return[this.props.class,"w-100 os-input",this.props.alwaysShowBorder?"o-input-border":void 0,this.props.errorMessage?"o-invalid":void 0].filter(De).join(" ")}}class dW extends t.Component{static template="o-spreadsheet-ActionButton";static props={action:Object,hasTriangleDownIcon:{type:Boolean,optional:!0},selectedColor:{type:String,optional:!0},class:{type:String,optional:!0},onClick:{type:Function,optional:!0}};actionButton=Cv(this.props.action);setup(){t.onWillUpdateProps(e=>{e.action!==this.props.action&&(this.actionButton=Cv(e.action))})}get isVisible(){return this.actionButton.isVisible(this.env)}get isEnabled(){return this.actionButton.isEnabled(this.env)}get isActive(){return this.actionButton.isActive?.(this.env)}get title(){const e=this.actionButton.name(this.env),t=this.actionButton.description(this.env);return e+(t?` (${t})`:"")}get iconTitle(){return this.actionButton.icon(this.env)}onClick(e){this.isEnabled&&(this.props.onClick?.(e),this.actionButton.execute?.(this.env))}get buttonStyle(){return this.props.selectedColor?JF({"border-bottom":`4px solid ${this.props.selectedColor}`,height:"16px","margin-top":"2px"}):""}}class uW extends t.Component{static template="o-spreadsheet-ColorPickerWidget";static props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={ColorPicker:jV};colorPickerButtonRef=t.useRef("colorPickerButton");get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:"border-bottom-style: hidden"}get colorPickerAnchorRect(){const e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}}class gW extends t.Component{static template="o-spreadsheet-NumberEditor";static props={currentValue:Number,onValueChange:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String,valueIcon:{type:String,optional:!0},min:Number,max:Number,title:String,valueList:Array};static defaultProps={onFocusInput:()=>{}};static components={Popover:jL};dropdown=t.useState({isOpen:!1});inputRef=t.useRef("inputNumber");rootEditorRef=t.useRef("NumberEditor");valueListRef=t.useRef("numberList");DOMFocusableElementStore;setup(){this.DOMFocusableElementStore=Tv(mV),t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.onWillUpdateProps(e=>{this.inputRef.el&&document.activeElement!==this.inputRef.el&&(this.inputRef.el.value=e.currentValue)}),t.onMounted(()=>{this.inputRef.el&&(this.inputRef.el.value=this.props.currentValue.toString())})}get popoverProps(){const{x:e,y:t,width:s,height:o}=this.rootEditorRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:s,height:o},positioning:"bottom-left",verticalOffset:0}}onExternalClick(e){AN(this.valueListRef.el,e)||AN(this.rootEditorRef.el,e)||this.closeList()}toggleList(){this.dropdown.isOpen?this.closeList():(this.props.onToggle?.(),this.inputRef.el.focus())}closeList(){this.dropdown.isOpen=!1}setValue(e){const t=me(Math.floor(parseFloat(e)),this.props.min,this.props.max);this.props.onValueChange(t),this.closeList()}setValueFromInput(e){this.setValue(e.target.value)}setValueFromList(e){this.setValue(e)}get currentValue(){return`${this.props.currentValue}`}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if("Enter"===e.key||"Escape"===e.key){this.closeList();const t=e.target;"Escape"===e.key&&(t.value=`${this.props.currentValue}`),this.props.onToggle?.()}if("Tab"===e.key)return e.preventDefault(),e.stopPropagation(),this.closeList(),void this.DOMFocusableElementStore.focus()}}class pW extends t.Component{static template="o-spreadsheet-FontSizeEditor";static components={NumberEditor:gW};static props={currentFontSize:Number,onFontSizeChanged:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String};static defaultProps={onFocusInput:()=>{}};fontSizes=ee}class mW extends t.Component{static template="o-spreadsheet.TextStyler";static components={ColorPickerWidget:uW,ActionButton:dW,FontSizeEditor:pW};static props={style:Object,updateStyle:{type:Function,optional:!0},defaultStyle:{type:Object,optional:!0},hasVerticalAlign:{type:Boolean,optional:!0},hasHorizontalAlign:{type:Boolean,optional:!0},hasBackgroundColor:{type:Boolean,optional:!0},class:{type:String,optional:!0}};openedEl=null;setup(){t.useExternalListener(window,"click",this.onExternalClick)}state=t.useState({activeTool:""});updateFontSize(e){this.props.updateStyle?.({...this.props.style,fontSize:e})}toggleDropdownTool(e,t){const s=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=s?"":e,this.openedEl=s?null:t.target}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onTextColorChange(e){this.props.updateStyle?.({...this.props.style,color:e}),this.closeMenus()}onFillColorChange(e){this.props.updateStyle?.({...this.props.style,fillColor:e}),this.closeMenus()}updateAlignment(e){this.props.updateStyle?.({...this.props.style,align:e}),this.closeMenus()}updateVerticalAlignment(e){this.props.updateStyle?.({...this.props.style,verticalAlign:e}),this.closeMenus()}toggleBold(){this.props.updateStyle?.({...this.props.style,bold:!this.bold})}toggleItalic(){this.props.updateStyle?.({...this.props.style,italic:!this.italic})}closeMenus(){this.state.activeTool="",this.openedEl=null}get align(){return this.props.style.align??this.props.defaultStyle?.align}get verticalAlign(){return this.props.style.verticalAlign||this.props.defaultStyle?.verticalAlign}get bold(){return this.props.style.bold??this.props.defaultStyle?.bold}get italic(){return this.props.style.italic??this.props.defaultStyle?.italic}get currentFontSize(){return this.props.style.fontSize??this.props.defaultStyle?.fontSize??k}get boldButtonAction(){return{name:Cs("Bold"),execute:()=>this.toggleBold(),isActive:()=>this.bold||!1,icon:"o-spreadsheet-Icon.BOLD"}}get italicButtonAction(){return{name:Cs("Italic"),execute:()=>this.toggleItalic(),isActive:()=>this.italic||!1,icon:"o-spreadsheet-Icon.ITALIC"}}get horizontalAlignButtonAction(){let e="o-spreadsheet-Icon.ALIGN_LEFT";return"center"===this.align?e="o-spreadsheet-Icon.ALIGN_CENTER":"right"===this.align&&(e="o-spreadsheet-Icon.ALIGN_RIGHT"),{name:Cs("Horizontal alignment"),icon:e}}get horizontalAlignActions(){return[{name:Cs("Left"),execute:()=>this.updateAlignment("left"),isActive:()=>"left"===this.align,icon:"o-spreadsheet-Icon.ALIGN_LEFT"},{name:Cs("Center"),execute:()=>this.updateAlignment("center"),isActive:()=>"center"===this.align,icon:"o-spreadsheet-Icon.ALIGN_CENTER"},{name:Cs("Right"),execute:()=>this.updateAlignment("right"),isActive:()=>"right"===this.align,icon:"o-spreadsheet-Icon.ALIGN_RIGHT"}]}get verticalAlignButtonAction(){let e="o-spreadsheet-Icon.ALIGN_MIDDLE";return"top"===this.verticalAlign?e="o-spreadsheet-Icon.ALIGN_TOP":"bottom"===this.verticalAlign&&(e="o-spreadsheet-Icon.ALIGN_BOTTOM"),{name:Cs("Vertical alignment"),icon:e}}get verticalAlignActions(){return[{name:Cs("Top"),execute:()=>this.updateVerticalAlignment("top"),isActive:()=>"top"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_TOP"},{name:Cs("Middle"),execute:()=>this.updateVerticalAlignment("middle"),isActive:()=>"middle"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},{name:Cs("Bottom"),execute:()=>this.updateVerticalAlignment("bottom"),isActive:()=>"bottom"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"}]}}class fW extends t.Component{static template="o-spreadsheet-CogWheelMenu";static components={MenuPopover:JL};static props={items:Array};buttonRef=t.useRef("button");menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});menuId=this.env.model.uuidGenerator.uuidv4();toggleMenu(e){e.closedMenuId!==this.menuId&&(this.menuState.isOpen=!this.menuState.isOpen,this.menuState.anchorRect=FN(this.buttonRef.el),this.menuState.menuItems=Sv(this.props.items))}}class vW extends t.Component{static template="o-spreadsheet-CarouselPanel";static props={onCloseSidePanel:Function,figureId:String};static components={Section:YV,TextInput:hW,TextStyler:mW,CogWheelMenu:fW};DEFAULT_CAROUSEL_TITLE_STYLE=ie;dragAndDrop=KV();previewListRef=t.useRef("previewList");setup(){let e=[...this.carouselItems];t.onWillUpdateProps(()=>{Le(this.carouselItems,e)||this.dragAndDrop.cancel(),e=[...this.carouselItems]})}get carouselItems(){return this.env.model.getters.getCarousel(this.props.figureId).items}get title(){return this.env.model.getters.getCarousel(this.props.figureId).title}get carousel(){return this.env.model.getters.getCarousel(this.props.figureId)}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[this.getItemId(e)]||""}getItemId(e){return"chart"===e.type?e.chartId:"transparent-carousel"}addNewChartToCarousel(){this.env.model.dispatch("ADD_NEW_CHART_TO_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId})}get hasDataView(){return this.carouselItems.some(e=>"carouselDataView"===e.type)}isCarouselItemActive(e){return Le(this.env.model.getters.getSelectedCarouselItem(this.props.figureId),e)}addDataViewToCarousel(){const e=this.env.model.getters.getCarousel(this.props.figureId);this.updateItems([...e.items,{type:"carouselDataView"}])}activateCarouselItem(e){this.env.model.dispatch("UPDATE_CAROUSEL_ACTIVE_ITEM",{figureId:this.props.figureId,sheetId:this.carouselSheetId,item:e})}editCarouselItem(e){"chart"===e.type&&(this.activateCarouselItem(e),this.env.model.dispatch("SELECT_FIGURE",{figureId:this.props.figureId}),this.env.openSidePanel("ChartPanel",{chartId:e.chartId}))}renameCarouselItem(e,t){const s=t.trim();if(!s||s===this.getItemTitle(e).toString())return;const o=[...this.carouselItems],i=this.carouselItems.findIndex(t=>Le(t,e));-1!==i&&(o[i]={...e,title:s},this.updateItems(o))}deleteCarouselItem(e){const t=this.env.model.getters.getCarousel(this.props.figureId).items.filter(t=>!Le(t,e));this.updateItems(t)}popOutCarouselItem(e){"chart"===e.type&&this.env.model.dispatch("POPOUT_CHART_FROM_CAROUSEL",{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId})}duplicateCarouselChart(e){"chart"===e.type&&this.env.model.dispatch("DUPLICATE_CAROUSEL_CHART",{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId,duplicatedChartId:this.env.model.uuidGenerator.smallUuid()})}onDragHandleMouseDown(e,t){if(0!==t.button)return;const s=Array.from(this.previewListRef.el.children).map(e=>FN(e)),o=this.carouselItems.map((e,t)=>({id:this.getItemId(e),size:s[t].height,position:s[t].y}));this.dragAndDrop.start("vertical",{draggedItemId:this.getItemId(e),initialMousePosition:t.clientY,items:o,scrollableContainerEl:this.previewListRef.el,onDragEnd:(t,s)=>this.onDragEnd(e,s)})}onDragEnd(e,t){const s=this.carouselItems.findIndex(t=>Le(t,e));if(-1===s||s===t)return;const o=[...this.env.model.getters.getCarousel(this.props.figureId).items];o.splice(s,1),o.splice(t,0,e),this.updateItems(o)}getItemTitle(e){return jF(this.env.model.getters,e)}getItemPreview(e){return function(e,t){if("carouselDataView"===t.type)return"o-spreadsheet-Icon.DATA";const s=e.getChartDefinition(t.chartId);return(qF.getAll().find(e=>e.matcher?.(s))||qF.get(s.type)).preview}(this.env.model.getters,e)}updateItems(e){this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...this.carousel,items:e}})}updateTitleText(e){const t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,text:e}}})}updateTitleStyle(e){const t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,...e}}})}get carouselAddChartInfoMessage(){return Cs("Add a chart to the carousel. You can also add a chart by dragging and dropping it over the carousel figure.")}getCogWheelMenuItems(e){const t=[];return"chart"===e.type&&(t.push({name:Cs("Edit chart"),execute:()=>this.editCarouselItem(e),icon:"o-spreadsheet-Icon.EDIT"}),t.push({name:Cs("Pop out chart"),execute:()=>this.popOutCarouselItem(e),icon:"o-spreadsheet-Icon.EXTERNAL"}),t.push({name:Cs("Duplicate chart"),execute:()=>this.duplicateCarouselChart(e),icon:"o-spreadsheet-Icon.COPY"})),t.push({name:Cs("Delete item"),execute:()=>this.deleteCarouselItem(e),icon:"o-spreadsheet-Icon.TRASH"}),t}get carouselSheetId(){const e=this.env.model.getters.getFigureSheetId(this.props.figureId);if(!e)throw new Error("Could not find the sheetId of the carousel figure");return e}get carouselDataViewMessage(){return Cs("The data view makes the carousel transparent, revealing the data underneath.")}}const bW={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function};class SW extends t.Component{static template="o-spreadsheet.ChartDataSeries";static components={SelectionInput:iz,Section:YV};static props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},onSelectionChanged:Function,onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},onSelectionConfirmed:Function,title:{type:String,optional:!0},maxNumberOfUsedRanges:{type:Number,optional:!0},datasetOrientation:{type:String,optional:!0},canChangeDatasetOrientation:{type:Boolean,optional:!0},onFlipAxis:{type:Function,optional:!0}};get ranges(){return this.props.ranges.map(e=>e.dataRange)}get disabledRanges(){return this.props.ranges.map((e,t)=>!!this.props.maxNumberOfUsedRanges&&t>=this.props.maxNumberOfUsedRanges)}get colors(){return this.props.ranges.map(e=>e.backgroundColor)}get title(){return this.props.title?this.props.title:this.props.hasSingleRange?Cs("Data range"):Cs("Data series")}}class yW extends t.Component{static template="o-spreadsheet.ChartErrorSection";static components={Section:YV,ValidationMessages:MG};static props={messages:{type:Array,element:String}}}class CW extends t.Component{static template="o-spreadsheet.ChartLabelRange";static components={SelectionInput:iz,Checkbox:hz,Section:YV};static props={title:{type:String,optional:!0},range:String,isInvalid:Boolean,onSelectionChanged:Function,onSelectionConfirmed:Function,options:{type:Array,optional:!0}};static defaultProps={title:Cs("Categories / Labels"),options:[]}}class IW extends t.Component{static template="o-spreadsheet-GenericChartConfigPanel";static components={ChartDataSeries:SW,ChartLabelRange:CW,Section:YV,Checkbox:hz,ChartErrorSection:yW};static props=bW;state=t.useState({datasetDispatchResult:void 0,labelsDispatchResult:void 0});dataSets=[];labelRange;datasetOrientation=void 0;chartTerms=Bg;setup(){this.dataSets=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange,this.datasetOrientation=this.computeDatasetOrientation()}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[]].filter(e=>"NoChanges"!==e).map(e=>Bg.Errors[e]||Bg.Errors.Unexpected)}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause("InvalidDataSet")}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause("InvalidLabelRange")}get dataSetsHaveTitleLabel(){return"rows"===this.datasetOrientation?Cs("Use col %(column_name)s as headers",{column_name:lt(this.calculateHeaderPosition()||0)}):Cs("Use row %(row_position)s as headers",{row_position:this.calculateHeaderPosition()||""})}getLabelRangeOptions(){const e=this.props.definition;return[{name:"aggregated",label:this.chartTerms.AggregatedChart,value:("aggregated"in e&&e.aggregated)??!1,onChange:this.onUpdateAggregated.bind(this)},{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.chartId,{dataSetsHaveTitle:e})}get canChangeDatasetOrientation(){const e=new Set,t=[],s=this.env.model.getters.getActiveSheetName(),o=this.dataSets.map(e=>e.dataRange);this.labelRange&&o.push(this.labelRange);for(const i of o){if(!Dt(i))return!1;const o=yr(i),n=At(o.xc);if(void 0===n.bottom||void 0===n.right)return!1;if(t.push(n),e.add(o.sheetName||s),e.size>1)return!1}const i=ns(t);if(1!==i.length)return!1;const{left:n,right:r,top:a,bottom:l}=i[0];return!t.some(e=>!(e.top===a&&e.bottom===l||e.left===n&&e.right===r))}computeDatasetOrientation(){let e=!1,t=!1;for(const s of this.dataSets){if(!Dt(s.dataRange))return;const o=At(s.dataRange);if(void 0===o.bottom||void 0===o.right)return;o.top===o.bottom&&(e=!0),o.left===o.right&&(t=!0)}return e&&!t?"rows":!e&&t?"columns":void 0}setDatasetOrientation(e){const t=this.props.definition.dataSets.map(e=>e.dataRange),s=this.transposeDataSet([this.props.definition.labelRange,...t],e);if(0===s.length)return;const o=s.length>1?s.shift().dataRange:"";this.props.updateChart(this.props.chartId,{labelRange:o,dataSets:s}),this.dataSets=s,this.labelRange=o,this.datasetOrientation=e}onDataSeriesRangesChanged(e){this.dataSets=e.map((e,t)=>({...this.dataSets?.[t],dataRange:e})),this.state.datasetDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesReordered(e){const t=vN({dataSets:this.dataSets},this.dataSets.length);this.datasetOrientation=void 0;const s=this.dataSets.map(e=>t.next());this.dataSets=e.map(e=>({backgroundColor:s[e],...this.dataSets[e]})),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesRemoved(e){const t=vN({dataSets:this.dataSets},this.dataSets.length),s=this.dataSets.map(e=>t.next());this.dataSets=this.dataSets.map((e,t)=>({backgroundColor:s[t],...e})).filter((t,s)=>s!==e),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesConfirmed(){this.dataSets=this.splitRanges,this.datasetOrientation=this.computeDatasetOrientation(),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets}),this.state.datasetDispatchResult.isSuccessful&&(this.dataSets=this.env.model.getters.getChartDefinition(this.props.chartId).dataSets)}get splitRanges(){const e=[];for(const t of this.dataSets){const s=t.dataRange;if(!this.env.model.getters.isRangeValid(s)){e.push(t);continue}const{sheetName:o}=yr(s),i=o?`${o}!`:"",n=At(s);if(n.bottom!==n.top&&n.left!==n.right){if("rows"!==this.datasetOrientation){if(void 0!==n.right)for(let s=n.left;s<=n.right;++s){const o=s===n.left?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Pt({left:s,right:s,top:n.top,bottom:n.bottom})}`})}else if(void 0!==n.bottom)for(let s=n.top;s<=n.bottom;++s){const o=s===n.top?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Pt({left:n.left,right:n.right,top:s,bottom:s})}`})}}else if(void 0!==n.bottom)for(let s=n.top;s<=n.bottom;++s){const o=s===n.top?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Pt({left:n.left,right:n.right,top:s,bottom:s})}`})}else if(void 0!==n.right)for(let s=n.left;s<=n.right;++s){const o=s===n.left?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Pt({left:s,right:s,top:n.top,bottom:n.bottom})}`})}}else e.push(t)}return e}getDataSeriesRanges(){return this.dataSets}onLabelRangeChanged(e){this.labelRange=e[0],this.state.labelsDispatchResult=this.props.canUpdateChart(this.props.chartId,{labelRange:this.labelRange})}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.chartId,{labelRange:this.labelRange})}getLabelRange(){return this.labelRange||""}onUpdateAggregated(e){this.props.updateChart(this.props.chartId,{aggregated:e})}calculateHeaderPosition(){if(this.isDatasetInvalid||this.isLabelInvalid)return;const e=this.env.model.getters,t=e.getActiveSheetId(),s=Jb(e,t,this.labelRange),o=ky(e,this.dataSets,t,this.props.definition.dataSetsHaveTitle);return o.length?"rows"===this.datasetOrientation?o[0].dataRange.zone.left:o[0].dataRange.zone.top+1:s?s.zone.top+1:void 0}get maxNumberOfUsedRanges(){return vR.get(this.props.definition.type).dataSeriesLimit}transposeDataSet(e,t){const s=this.env.model.getters;if(void 0===t)return e.filter(De).map(e=>({dataRange:e}));const o={},i=[],n=s.getFigureIdFromChartId(this.props.chartId),r=s.getFigureSheetId(n);let a=s.getActiveSheet().name;r&&(a=s.getSheet(r).name);for(const t of e){if(!t)continue;if(!Dt(t))return e.filter(De).map(e=>({dataRange:e}));let{sheetName:s,xc:i}=yr(t);s=s??a,o[s]||(o[s]=[]),o[s].push(_t(i))}for(const e in o){const s=ns(o[e]);if("columns"===t)for(const t of s)for(let s=t.left;s<=t.right;s++){const o=`${e===a?"":e+"!"}${Pt({...t,left:s,right:s})}`;i.push({dataRange:o})}else for(const t of s)for(let s=t.top;s<=t.bottom;s++){const o=`${e===a?"":e+"!"}${Pt({...t,top:s,bottom:s})}`;i.push({dataRange:o})}}return i}}class wW extends IW{static template="o-spreadsheet-BarConfigPanel";get stackedLabel(){return this.props.definition.horizontal?this.chartTerms.StackedBarChart:this.chartTerms.StackedColumnChart}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}}class EW extends t.Component{static template="o-spreadsheet.BadgeSelection";static props={choices:Array,onChange:Function,selectedValue:String}}class xW extends t.Component{static template="o-spreadsheet.ChartTitle";static components={Section:YV,TextStyler:mW,TextInput:hW};static props={title:{type:String,optional:!0},placeholder:{type:String,optional:!0},updateTitle:Function,name:{type:String},style:Object,defaultStyle:{type:Object,optional:!0},updateStyle:Function};static defaultProps={title:"",placeholder:""};updateTitle(e){this.props.updateTitle(e)}}class RW extends t.Component{static template="o-spreadsheet-AxisDesignEditor";static components={Section:YV,ChartTitle:xW,BadgeSelection:EW};static props={chartId:String,definition:Object,updateChart:Function,axesList:Array};state=t.useState({currentAxis:"x"});defaultFontSize=12;get axisTitleStyle(){return this.props.definition.axesDesign?.[this.state.currentAxis]?.title??{}}get badgeAxes(){return this.props.axesList.map(e=>({value:e.id,label:e.name}))}updateAxisEditor(e){this.state.currentAxis=e.target.value}getAxisTitle(){const e=this.props.definition.axesDesign??{};return e[this.state.currentAxis]?.title.text||""}updateAxisTitle(e){const t=he(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:{...t?.[this.state.currentAxis]?.title,text:e}},this.props.updateChart(this.props.chartId,{axesDesign:t})}updateAxisTitleStyle(e){const t=he(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:e},this.props.updateChart(this.props.chartId,{axesDesign:t})}}class TW extends t.Component{static template="o-spreadsheet.RadioSelection";static props={choices:Array,onChange:Function,selectedValue:{optional:!1},name:String,direction:{type:String,optional:!0}};static defaultProps={direction:"horizontal"}}class AW extends t.Component{static template="o-spreadsheet-GeneralDesignEditor";static components={RoundColorPicker:XV,ChartTitle:xW,Section:YV,SidePanelCollapsible:gV,RadioSelection:TW};static props={...bW,defaultChartTitleFontSize:{type:Number,optional:!0},slots:{type:Object,optional:!0}};static defaultProps={defaultChartTitleFontSize:T};state;setup(){this.state=t.useState({activeTool:""})}get title(){return this.props.definition.title}toggleDropdownTool(e,t){const s=this.state.activeTool===e;this.state.activeTool=s?"":e}updateBackgroundColor(e){this.props.updateChart(this.props.chartId,{background:e})}updateTitle(e){const t={...this.title,text:e};this.props.updateChart(this.props.chartId,{title:t})}updateChartTitleStyle(e){const t={...this.title,...e};this.props.updateChart(this.props.chartId,{title:t}),this.state.activeTool=""}}class _W extends t.Component{static template="o-spreadsheet-ChartHumanizeNumbers";static components={Checkbox:hz};static props=bW;get title(){const e=this.env.model.getters.getLocale(),t=zi(1234567,{format:an({value:1234567},void 0,e),locale:e});return Cs("E.g. 1234567 -> %(value)s",{value:t})}}class DW extends t.Component{static template="o-spreadsheet-ChartLegend";static components={Section:YV};static props=bW;updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e.target.value})}}class OW extends cW{static template="o-spreadsheet-NumberInput";static components={};static props={...cW.props,min:{type:Number,optional:!0},max:{type:Number,optional:!0}};debouncedOnChange=Fe(this.props.onChange.bind(this),100,!0);save(){const e=(this.inputRef.el?.value||"").trim();e!==this.props.value.toString()&&this.debouncedOnChange(e)}get inputClass(){return[this.props.class,"o-input"].join(" ")}}class FW extends t.Component{static template="o-spreadsheet-SeriesDesignEditor";static components={SidePanelCollapsible:gV,Section:YV,RoundColorPicker:XV};static props={...bW,slots:{type:Object,optional:!0}};state=t.useState({index:0});getDataSeries(){const e=this.env.model.getters.getChartRuntime(this.props.chartId);return e&&"chartJsConfig"in e?e.chartJsConfig.data.datasets.filter(e=>!Jy(e.xAxisID??"")).map(e=>e.label):[]}updateEditedSeries(e){this.state.index=e.target.selectedIndex}updateDataSeriesColor(e){const t=this.props.definition.dataSets;t?.[this.state.index]&&(t[this.state.index]={...t[this.state.index],backgroundColor:e},this.props.updateChart(this.props.chartId,{dataSets:t}))}getDataSeriesColor(){const e=this.props.definition.dataSets;if(!e?.[this.state.index])return"";const t=e[this.state.index].backgroundColor;return t?Yv(t):bb(this.state.index,Sb(this.props.definition.dataSets.length))}updateDataSeriesLabel(e){const t=e.target.value,s=this.props.definition.dataSets;s?.[this.state.index]&&(s[this.state.index]={...s[this.state.index],label:t},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSeriesLabel(){const e=this.props.definition.dataSets;return e[this.state.index]?.label||this.getDataSeries()[this.state.index]}}class PW extends t.Component{static template="o-spreadsheet-SeriesWithAxisDesignEditor";static components={SeriesDesignEditor:FW,Checkbox:hz,RadioSelection:TW,Section:YV,RoundColorPicker:XV,NumberInput:OW};static props={...bW,slots:{type:Object,optional:!0}};axisChoices=Yy;updateDataSeriesAxis(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],yAxisId:"left"===t?"y":"y1"},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSerieAxis(e){const t=this.props.definition.dataSets;return t?.[e]&&"y1"===t[e].yAxisId?"right":"left"}get canHaveTwoVerticalAxis(){return!("horizontal"in this.props.definition&&this.props.definition.horizontal)}toggleDataTrend(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],trend:{type:"polynomial",order:1,...s[e].trend,display:t}},this.props.updateChart(this.props.chartId,{dataSets:s}))}getTrendLineConfiguration(e){const t=this.props.definition.dataSets;return t?.[e]?.trend}getTrendType(e){return e?"polynomial"===e.type&&1===e.order?"linear":e.type:""}onChangeTrendType(e,t){const s=t.target.value;let o;switch(s){case"linear":case"polynomial":o={type:"polynomial",order:"linear"===s?1:this.getMaxPolynomialDegree(e)};break;case"exponential":case"logarithmic":case"trailingMovingAverage":o={type:s};break;default:return}this.updateTrendLineValue(e,o)}getPolynomialDegrees(e){return fe(1,this.getMaxPolynomialDegree(e)+1)}onChangePolynomialDegree(e,t){const s=t.target;this.updateTrendLineValue(e,{order:parseInt(s.value)})}getMaxPolynomialDegree(e){const t=this.env.model.getters.getChartRuntime(this.props.chartId);return Math.min(10,t.chartJsConfig.data.datasets[e].data.length-1)}get defaultWindowSize(){return 2}onChangeMovingAverageWindow(e,t){let s=parseInt(t)||2;s<=1&&(s=2),this.updateTrendLineValue(e,{window:s})}getDataSeriesColor(e){const t=this.props.definition.dataSets;if(!t?.[e])return"";const s=t[e].backgroundColor;return s?Yv(s):bb(e,Sb(this.props.definition.dataSets.length))}getTrendLineColor(e){return this.getTrendLineConfiguration(e)?.color??ab(this.getDataSeriesColor(e),.5)}updateTrendLineColor(e,t){this.updateTrendLineValue(e,{color:t})}updateTrendLineValue(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],trend:{...s[e].trend,...t}},this.props.updateChart(this.props.chartId,{dataSets:s}))}}class MW extends t.Component{static template="o-spreadsheet-ChartShowValues";static components={Checkbox:hz};static props={...bW,defaultValue:{type:Boolean,optional:!0}}}class NW extends t.Component{static template="o-spreadsheet-ChartWithAxisDesignPanel";static components={GeneralDesignEditor:AW,SidePanelCollapsible:gV,Section:YV,AxisDesignEditor:RW,SeriesWithAxisDesignEditor:PW,ChartLegend:DW,ChartShowValues:MW,ChartHumanizeNumbers:_W};static props=bW;get axesList(){const{useLeftAxis:e,useRightAxis:t}=qy(this.props.definition),s=[{id:"x",name:Cs("Horizontal axis")}];return e&&s.push({id:"y",name:Cs(t?"Left axis":"Vertical axis")}),t&&s.push({id:"y1",name:Cs(e?"Right axis":"Vertical axis")}),s}}class kW extends NW{static template="o-spreadsheet-GenericZoomableChartDesignPanel";static components={...NW.components,Checkbox:hz};onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}}const LW=["year","quarter_number","month_number","iso_week_number","day_of_month","day_of_week","hour_number","minute_number","second_number"];class VW extends t.Component{static template="o-spreadsheet-ColorScalePicker";static components={Section:YV,RoundColorPicker:XV,Popover:jL};static props={definition:Object,onUpdateColorScale:Function};colorScales=Eb.map(e=>({value:e,label:Bg.ColorScales[e],className:`${e}-color-scale`}));state=t.useState({popoverProps:void 0,popoverStyle:""});popoverRef=t.useRef("popoverRef");setup(){t.useExternalListener(window,"click",this.closePopover)}get currentColorScale(){return this.props.definition.colorScale||w_("oranges")}get currentColorScaleStyle(){const e=this.currentColorScale,t=e.minColor||"#fff",s=e.midColor,o=e.maxColor||"#000";return s?`background: linear-gradient(90deg, ${t}, ${s}, ${o});`:`background: linear-gradient(90deg, ${t}, ${o});`}colorScalePreviewStyle(e){return`background: linear-gradient(90deg, ${wb[e].join(",")});`}get currentColorScaleLabel(){return Bg.ColorScales[this.selectedColorScale]}onColorScaleChange(e){"custom"===e?this.props.onUpdateColorScale(A):this.props.onUpdateColorScale(w_(e)),this.closePopover()}onPointerDown(e){if(this.state.popoverProps)return void this.closePopover();const t=e.currentTarget,{bottom:s,right:o,width:i}=t.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:o,y:s,width:0,height:0},positioning:"top-right",verticalOffset:0},this.state.popoverStyle=JF({width:`${i}px`})}closePopover(){this.state.popoverProps=void 0}get selectedColorScale(){if(!this.props.definition.colorScale)return"oranges";const{minColor:e,midColor:t,maxColor:s}=this.props.definition.colorScale||{};for(const[o,i]of Object.entries(wb))if(i[0]===e&&i[2]===s&&i[1]===t)return o;return"custom"}getCustomColorScaleColor(e){return this.props.definition.colorScale?.[e]??""}setCustomColorScaleColor(e,t){t||"midColor"===e||(t="#fff");const s=this.currentColorScale;s&&this.props.onUpdateColorScale({...s,[e]:t})}}class zW extends t.Component{static template="o-spreadsheet-CalendarChartDesignPanel";static components={GeneralDesignEditor:AW,SidePanelCollapsible:gV,Section:YV,AxisDesignEditor:RW,ChartShowValues:MW,ColorScalePicker:VW,RoundColorPicker:XV};static props=bW;get axesList(){return[{id:"x",name:Cs("Horizontal axis")},{id:"y",name:Cs("Vertical axis")}]}onColormapChange(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}get selectedMissingValueColor(){return this.props.definition.missingValueColor}updateLegendPosition(e){const t=e.target.value;this.props.updateChart(this.props.chartId,{legendPosition:t})}}class HW extends t.Component{static template="o-spreadsheet-ChartShowDataMarkers";static components={Checkbox:hz};static props=bW}class UW extends kW{static template="o-spreadsheet-ComboChartDesignPanel";static components={...kW.components,ChartShowDataMarkers:HW,RadioSelection:TW};seriesTypeChoices=[{value:"bar",label:Cs("Bar")},{value:"line",label:Cs("Line")}];updateDataSeriesType(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],type:t},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSeriesType(e){const t=this.props.definition.dataSets;return t?.[e]?t[e].type??"line":"bar"}}class BW extends t.Component{static template="o-spreadsheet-FunnelChartDesignPanel";static components={ChartShowValues:MW,GeneralDesignEditor:AW,SidePanelCollapsible:gV,RoundColorPicker:XV,Section:YV,ChartHumanizeNumbers:_W};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};getFunnelColorItems(){const e=this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig.data.labels||[],t=lN(e,this.props.definition.funnelColors);return e.map((e,s)=>({label:e||Cs("Value %s",s+1),color:t[s]}))}updateFunnelItemColor(e,t){const s=Ke(this.props.definition.funnelColors||[],t,e);this.props.updateChart(this.props.chartId,{funnelColors:s})}}class GW extends t.Component{static template="o-spreadsheet-GaugeChartConfigPanel";static components={ChartErrorSection:yW,ChartDataSeries:SW};static props=bW;state=t.useState({dataRangeDispatchResult:void 0});dataRange=this.props.definition.dataRange;get configurationErrorMessages(){return[...this.state.dataRangeDispatchResult?.reasons||[]].map(e=>Bg.Errors[e]||Bg.Errors.Unexpected)}get isDataRangeInvalid(){return!!this.state.dataRangeDispatchResult?.isCancelledBecause("InvalidGaugeDataRange")}onDataRangeChanged(e){this.dataRange=e[0],this.state.dataRangeDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataRange:this.dataRange})}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.chartId,{dataRange:this.dataRange})}getDataRange(){return{dataRange:this.dataRange||""}}}class WW extends t.Component{static template="o-spreadsheet-GaugeChartDesignPanel";static components={SidePanelCollapsible:gV,Section:YV,RoundColorPicker:XV,GeneralDesignEditor:AW,ChartErrorSection:yW,StandaloneComposer:HV,ChartHumanizeNumbers:_W};static props=bW;state;setup(){this.state=t.useState({sectionRuleCancelledReasons:this.checkSectionRuleFormulasAreValid(this.props.definition.sectionRule),sectionRule:he(this.props.definition.sectionRule)})}get designErrorMessages(){return[...this.state.sectionRuleCancelledReasons||[]].map(e=>Bg.Errors[e]||Bg.Errors.Unexpected)}get isRangeMinInvalid(){return!(!this.state.sectionRuleCancelledReasons?.includes("EmptyGaugeRangeMin")&&!this.state.sectionRuleCancelledReasons?.includes("GaugeRangeMinNaN"))}get isRangeMaxInvalid(){return!(!this.state.sectionRuleCancelledReasons?.includes("EmptyGaugeRangeMax")&&!this.state.sectionRuleCancelledReasons?.includes("GaugeRangeMaxNaN"))}get isLowerInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.includes("GaugeLowerInflectionPointNaN")}get isUpperInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.includes("GaugeUpperInflectionPointNaN")}updateSectionColor(e,t){const s=he(this.state.sectionRule);s.colors[e]=t,this.updateSectionRule(s)}updateSectionRule(e){this.state.sectionRuleCancelledReasons=[],this.state.sectionRuleCancelledReasons.push(...this.checkSectionRuleFormulasAreValid(this.state.sectionRule));const t=this.props.updateChart(this.props.chartId,{sectionRule:e});t.isSuccessful?this.state.sectionRule=he(e):this.state.sectionRuleCancelledReasons.push(...t.reasons)}onConfirmGaugeRange(e,t){this.state.sectionRule={...this.state.sectionRule,[e]:t},this.updateSectionRule(this.state.sectionRule)}getGaugeInflectionComposerProps(e){const t="lowerColor"===e?"lowerInflectionPoint":"upperInflectionPoint",s=this.state.sectionRule[t];return{onConfirm:e=>{this.state.sectionRule={...this.state.sectionRule,[t]:{...s,value:e}},this.updateSectionRule(this.state.sectionRule)},composerContent:s.value,invalid:"lowerColor"===e?this.isLowerInflectionPointInvalid:this.isUpperInflectionPointInvalid,defaultRangeSheetId:this.sheetId,class:t,placeholder:Cs("Value"),title:Cs("Value or formula")}}checkSectionRuleFormulasAreValid(e){const t=[];return this.valueIsValidNumber(e.rangeMin)||t.push("GaugeRangeMinNaN"),this.valueIsValidNumber(e.rangeMax)||t.push("GaugeRangeMaxNaN"),this.valueIsValidNumber(e.lowerInflectionPoint.value)||t.push("GaugeLowerInflectionPointNaN"),this.valueIsValidNumber(e.upperInflectionPoint.value)||t.push("GaugeUpperInflectionPointNaN"),t}valueIsValidNumber(e){const t=this.env.model.getters.getLocale();if(!e.startsWith("="))return void 0!==xo(e,t);const s=this.env.model.getters.evaluateFormula(this.sheetId,e);return!_n(s)&&void 0!==xo(Tn(s),t)}get sheetId(){const e=this.env.model.getters.getChart(this.props.chartId);if(!e)throw new Error("Chart not found with id "+this.props.chartId);return e.sheetId}}class $W extends t.Component{static template="o-spreadsheet-GeoChartRegionSelectSection";static components={Section:YV};static props={chartId:String,definition:Object,updateChart:Function};updateSelectedRegion(e){const t=e.target.value;this.props.updateChart(this.props.chartId,{region:t})}get availableRegions(){return this.env.model.getters.getGeoChartAvailableRegions()}get selectedRegion(){return this.props.definition.region||this.availableRegions[0]?.id}}class qW extends IW{static template="o-spreadsheet-GeoChartConfigPanel";static components={...IW.components,GeoChartRegionSelectSection:$W};get dataRanges(){return this.getDataSeriesRanges()}get disabledRanges(){return this.props.definition.dataSets.map((e,t)=>t>0)}getLabelRangeOptions(){return[{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}}class ZW extends NW{static template="o-spreadsheet-GeoChartDesignPanel";static components={...NW.components,RoundColorPicker:XV,ColorScalePicker:VW};updateColorScale(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}updateLegendPosition(e){const t=e.target.value;this.props.updateChart(this.props.chartId,{legendPosition:t})}get selectedMissingValueColor(){return this.props.definition.missingValueColor||"#ffffff"}}class jW extends IW{static template="o-spreadsheet-HierarchicalChartConfigPanel";static components={...IW.components};getLabelRangeOptions(){return[{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}}class YW extends IW{static template="o-spreadsheet-LineConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.chartId);return!!(e&&e instanceof bL)&&uk(e.getDefinition(),e.dataSets,e.labelRange,this.env.model.getters)}get stackedLabel(){return this.props.definition.fillArea?this.chartTerms.StackedAreaChart:this.chartTerms.StackedLineChart}getLabelRangeOptions(){const e=super.getLabelRangeOptions();return this.canTreatLabelsAsText&&e.push({name:"labelsAsText",value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}onUpdateLabelsAsText(e){this.props.updateChart(this.props.chartId,{labelsAsText:e})}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}}class XW extends kW{static template="o-spreadsheet-LineChartDesignPanel";static components={...kW.components,ChartShowDataMarkers:HW}}class KW extends t.Component{static template="o-spreadsheet.PieHoleSize";static components={Section:YV,NumberInput:OW};static props={onValueChange:Function,value:Number};onChange(e){isNaN(Number(e))||this.props.onValueChange(me(Number(e),0,95))}}class JW extends t.Component{static template="o-spreadsheet-PieChartDesignPanel";static components={GeneralDesignEditor:AW,Section:YV,ChartLegend:DW,ChartShowValues:MW,PieHoleSize:KW,Checkbox:hz,ChartHumanizeNumbers:_W};static props=bW;onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}get defaultHoleSize(){return 50}}class QW extends t.Component{static template="o-spreadsheet-RadarChartDesignPanel";static components={GeneralDesignEditor:AW,SeriesDesignEditor:FW,Section:YV,ChartLegend:DW,ChartShowValues:MW,ChartShowDataMarkers:HW,Checkbox:hz,ChartHumanizeNumbers:_W};static props=bW}class e$ extends zO{dataSets;labelRange;background;legendPosition;labelsAsText;aggregated;type="scatter";dataSetsHaveTitle;dataSetDesign;axesDesign;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=ky(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.zoomable=e.zoomable}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static transformDefinition(e,t,s){return Hy(e,t,s)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"scatter",labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues,zoomable:e.zoomable,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"scatter",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,zoomable:this.zoomable,humanize:this.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new e$(i,this.sheetId,this.getters)}getDefinitionForExcel(){const e=this.dataSets.map(e=>Vy(this.getters,e)).filter(e=>""!==e.range),t=zy(this.getters,this.labelRange,$y(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:IP(this.background||c),fontColor:IP(Uy(this.background)),dataSets:e,labelRange:t,verticalAxis:qy(s)}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new e$(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new e$(t,e,this.getters)}}class t$ extends t.Component{static template="o-spreadsheet-ScorecardChartConfigPanel";static components={SelectionInput:iz,ChartErrorSection:yW,Section:YV};static props=bW;state=t.useState({keyValueDispatchResult:void 0,baselineDispatchResult:void 0});keyValue=this.props.definition.keyValue;baseline=this.props.definition.baseline;get errorMessages(){return[...this.state.keyValueDispatchResult?.reasons||[],...this.state.baselineDispatchResult?.reasons||[]].map(e=>Bg.Errors[e]||Bg.Errors.Unexpected)}get isKeyValueInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause("InvalidScorecardKeyValue")}get isBaselineInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause("InvalidScorecardBaseline")}onKeyValueRangeChanged(e){this.keyValue=e[0],this.state.keyValueDispatchResult=this.props.canUpdateChart(this.props.chartId,{keyValue:this.keyValue})}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.chartId,{keyValue:this.keyValue})}getKeyValueRange(){return this.keyValue||""}onBaselineRangeChanged(e){this.baseline=e[0],this.state.baselineDispatchResult=this.props.canUpdateChart(this.props.chartId,{baseline:this.baseline})}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.chartId,{baseline:this.baseline})}getBaselineRange(){return this.baseline||""}updateBaselineMode(e){this.props.updateChart(this.props.chartId,{baselineMode:e.target.value})}}class s$ extends t.Component{static template="o-spreadsheet-ScorecardChartDesignPanel";static components={GeneralDesignEditor:AW,RoundColorPicker:XV,SidePanelCollapsible:gV,Section:YV,Checkbox:hz,ChartTitle:xW,ChartHumanizeNumbers:_W};static props=bW;get colorsSectionTitle(){return"progress"===this.props.definition.baselineMode?Cs("Progress bar colors"):Cs("Baseline colors")}get defaultScorecardTitleFontSize(){return 14}translate(e){return this.env.model.getters.dynamicTranslate(e)}setColor(e,t){switch(t){case"backgroundColor":this.props.updateChart(this.props.chartId,{background:e});break;case"baselineColorDown":this.props.updateChart(this.props.chartId,{baselineColorDown:e});break;case"baselineColorUp":this.props.updateChart(this.props.chartId,{baselineColorUp:e})}}get keyStyle(){return{align:"center",fontSize:32,...this.props.definition.keyDescr}}get baselineStyle(){return{align:"center",fontSize:16,...this.props.definition.baselineDescr}}setKeyText(e){this.props.updateChart(this.props.chartId,{keyDescr:{...this.props.definition.keyDescr,text:e}})}updateKeyStyle(e){const t={...this.keyStyle,...e};this.props.updateChart(this.props.chartId,{keyDescr:t})}setBaselineText(e){this.props.updateChart(this.props.chartId,{baselineDescr:{...this.props.definition.baselineDescr,text:e}})}updateBaselineStyle(e){const t={...this.baselineStyle,...e};this.props.updateChart(this.props.chartId,{baselineDescr:t})}}class o$ extends t.Component{static template="o-spreadsheet-SunburstChartDesignPanel";static components={GeneralDesignEditor:AW,Section:YV,SidePanelCollapsible:gV,ChartShowValues:MW,Checkbox:hz,TextStyler:mW,RoundColorPicker:XV,ChartLegend:DW,PieHoleSize:KW,ChartHumanizeNumbers:_W};static props=bW;defaults=E_;get showValues(){return this.props.definition.showValues??E_.showValues}get showLabels(){return this.props.definition.showLabels??E_.showLabels}get groupColors(){const e=this.props.chartId,t=this.env.model.getters.getChartRuntime(e).chartJsConfig.data.datasets[0];return t?.groupColors||[]}onGroupColorChanged(e,t){const s=he(this.props.definition.groupColors)??[];s[e]=t,this.props.updateChart(this.props.chartId,{groupColors:s})}onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}}class i$ extends t.Component{static template="o-spreadsheet-TreeMapCategoryColors";static components={Checkbox:hz,RoundColorPicker:XV};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){const e=this.props.definition.coloringOptions??TM.coloringOptions;if("categoryColor"!==e.type)throw new Error("Coloring options is not solid color");return e}getTreeGroupAndColors(){const e=this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig;return e.data.datasets[0]?.groupColors||[]}onGroupColorChanged(e,t){const s=he(this.coloringOptions);s.colors[e]=t||void 0,this.props.onColorChanged(s)}useValueBasedGradient(e){if("categoryColor"!==this.coloringOptions.type)throw new Error("Coloring options is not solid color");this.props.onColorChanged({...this.coloringOptions,useValueBasedGradient:e})}}class n$ extends t.Component{static template="o-spreadsheet-TreeMapColorScale";static components={RoundColorPicker:XV};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){const e=this.props.definition.coloringOptions??TM.coloringOptions;if("colorScale"!==e.type)throw new Error("Coloring options is not a color scale");return e}setColorScaleColor(e,t){this.props.onColorChanged({...this.coloringOptions,[e]:t})}}const r$={type:"colorScale",minColor:"#FFF5EB",midColor:"#FD8D3C",maxColor:"#7F2704"},a$={type:"categoryColor",colors:[],useValueBasedGradient:!0};class l$ extends t.Component{static template="o-spreadsheet-TreeMapChartDesignPanel";static components={GeneralDesignEditor:AW,Section:YV,SidePanelCollapsible:gV,ChartShowValues:MW,Checkbox:hz,TextStyler:mW,RoundColorPicker:XV,BadgeSelection:EW,TreeMapCategoryColors:i$,TreeMapColorScale:n$,ChartHumanizeNumbers:_W};static props=bW;savedColors={categoryColors:a$,colorScale:r$};defaults=TM;get showHeaders(){return this.props.definition.showHeaders??TM.showHeaders}get showValues(){return this.props.definition.showValues??TM.showValues}get showLabels(){return this.props.definition.showLabels??TM.showLabels}get coloringOptions(){return this.props.definition.coloringOptions??TM.coloringOptions}changeColoringOption(e){const t="categoryColor"===e?this.savedColors.categoryColors:this.savedColors.colorScale;this.props.updateChart(this.props.chartId,{coloringOptions:t})}onCategoryColorChange(e){this.savedColors.categoryColors=e,this.props.updateChart(this.props.chartId,{coloringOptions:e})}onColorScaleChange(e){this.savedColors.colorScale=e,this.props.updateChart(this.props.chartId,{coloringOptions:e})}get coloringOptionChoices(){return[{label:Cs("Category color"),value:"categoryColor"},{label:Cs("Color scale"),value:"colorScale"}]}}class c$ extends t.Component{static template="o-spreadsheet-WaterfallChartDesignPanel";static components={GeneralDesignEditor:AW,ChartShowValues:MW,Checkbox:hz,SidePanelCollapsible:gV,Section:YV,RoundColorPicker:XV,AxisDesignEditor:RW,RadioSelection:TW,ChartLegend:DW,ChartHumanizeNumbers:_W};static props=bW;axisChoices=Yy;onUpdateShowSubTotals(e){this.props.updateChart(this.props.chartId,{showSubTotals:e})}onUpdateShowConnectorLines(e){this.props.updateChart(this.props.chartId,{showConnectorLines:e})}onUpdateFirstValueAsSubtotal(e){this.props.updateChart(this.props.chartId,{firstValueAsSubtotal:e})}updateColor(e,t){this.props.updateChart(this.props.chartId,{[e]:t})}get axesList(){return[{id:"x",name:Cs("Horizontal axis")},{id:"y",name:Cs("Vertical axis")}]}get positiveValuesColor(){return this.props.definition.positiveValuesColor||m}get negativeValuesColor(){return this.props.definition.negativeValuesColor||f}get subTotalValuesColor(){return this.props.definition.subTotalValuesColor||v}updateVerticalAxisPosition(e){this.props.updateChart(this.props.chartId,{verticalAxisPosition:e})}onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}}const h$=new Jg;h$.add("line",{configuration:YW,design:XW}).add("scatter",{configuration:class extends IW{static template="o-spreadsheet-ScatterConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.chartId);return!!(e&&e instanceof e$)&&uk(e.getDefinition(),e.dataSets,e.labelRange,this.env.model.getters)}onUpdateLabelsAsText(e){this.props.updateChart(this.props.chartId,{labelsAsText:e})}getLabelRangeOptions(){const e=super.getLabelRangeOptions();return this.canTreatLabelsAsText&&e.push({name:"labelsAsText",value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}},design:kW}).add("bar",{configuration:wW,design:class extends kW{static template="o-spreadsheet-BarChartDesignPanel";get isZoomable(){return!this.props.definition.horizontal}}}).add("combo",{configuration:IW,design:UW}).add("pie",{configuration:IW,design:JW}).add("gauge",{configuration:GW,design:WW}).add("scorecard",{configuration:t$,design:s$}).add("waterfall",{configuration:IW,design:c$}).add("pyramid",{configuration:IW,design:NW}).add("radar",{configuration:IW,design:QW}).add("sunburst",{configuration:jW,design:o$}).add("geo",{configuration:qW,design:ZW}).add("funnel",{configuration:class extends IW{getLabelRangeOptions(){const e=this.props.definition;return[{name:"aggregated",label:this.chartTerms.AggregatedChart,value:e.aggregated??!1,onChange:this.onUpdateAggregated.bind(this)},{name:"cumulative",label:this.chartTerms.CumulativeData,value:e.cumulative??!1,onChange:this.onUpdateCumulative.bind(this)},{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}},design:BW}).add("treemap",{configuration:jW,design:l$}).add("calendar",{configuration:class extends IW{static template="o-spreadsheet-CalendarChartConfigPanel";groupByChoices=LW.map(e=>({value:e,label:yp[e]}));getLabelRangeOptions(){return[{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}getGroupByOptions(){const e=this.env.model.getters.getFigureSheetId(this.env.model.getters.getFigureIdFromChartId(this.props.chartId)),t=ky(this.env.model.getters,this.props.definition.dataSets,e,this.props.definition.dataSetsHaveTitle);if(0===t.length)return[];const s=Jb(this.env.model.getters,e,this.props.definition.labelRange),o=QN(this.props.definition,t,s,this.env.model.getters).labels.filter(e=>Ks(e,gi));if(0===o.length)return[];const i=o.map(e=>Mo(e,this.env.model.getters.getLocale())),n=new Set,r=new Set,a=new Set,l=new Set,c=new Set,h=new Set;for(const e of i)n.add(e.getFullYear()),r.add(e.getMonth()),a.add(e.getDate()),l.add(e.getHours()),c.add(e.getMinutes()),h.add(e.getSeconds());return this.groupByChoices.filter(e=>{switch(e.value){case"year":return n.size>1;case"quarter_number":case"month_number":return r.size>1;case"iso_week_number":case"day_of_month":case"day_of_week":return a.size>1;case"hour_number":return l.size>1;case"minute_number":return c.size>1;case"second_number":return h.size>1;default:return!1}})}getGroupByType(e){return("horizontal"===e?this.props.definition.horizontalGroupBy:this.props.definition.verticalGroupBy)||"year"}updateGroupBy(e,t){this.props.updateChart(this.props.chartId,{["horizontal"===e?"horizontalGroupBy":"verticalGroupBy"]:t})}},design:zW});const d$={line:Cs("Line"),column:Cs("Column"),bar:Cs("Bar"),area:Cs("Area"),pie:Cs("Pie"),hierarchical:Cs("Hierarchical"),misc:Cs("Miscellaneous")};class u$ extends t.Component{static template="o-spreadsheet-ChartTypePicker";static components={Section:YV,Popover:jL};static props={chartId:String,chartPanelStore:Object};categories=d$;chartTypeByCategories={};popoverRef=t.useRef("popoverRef");selectRef=t.useRef("selectRef");state=t.useState({popoverProps:void 0,popoverStyle:""});setup(){t.useExternalListener(window,"pointerdown",this.onExternalClick,{capture:!0});for(const e of qF.getAll())this.chartTypeByCategories[e.category]?this.chartTypeByCategories[e.category].push(e):this.chartTypeByCategories[e.category]=[e]}onExternalClick(e){AN(this.popoverRef.el?.parentElement,e)||AN(this.selectRef.el,e)||this.closePopover()}onTypeChange(e){this.props.chartPanelStore.changeChartType(this.props.chartId,e),this.closePopover()}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}getSelectedChartSubtypeProperties(){const e=this.getChartDefinition(this.props.chartId);return qF.getAll().find(t=>t.matcher?.(e)||!1)||qF.get(e.type)}onPointerDown(e){if(this.state.popoverProps)return void this.closePopover();const t=e.currentTarget,{bottom:s,right:o,width:i}=t.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:o,y:s,width:0,height:0},positioning:"top-right",verticalOffset:0},this.state.popoverStyle=JF({width:`${i}px`})}closePopover(){this.state.popoverProps=void 0}}class g$ extends Lv{mutators=["activatePanel","changeChartType"];panel="configuration";creationContexts={};activatePanel(e){this.panel=e}changeChartType(e,t){const s=this.getters.getContextCreationChart(e),o=this.creationContexts[e]||{};let i=s?.range;i?.every((e,t)=>Le(e,o.range?.[t]))&&(i=Object.assign([],o.range,s?.range)),this.creationContexts[e]={...o,...s,range:i};const n=this.getters.getFigureIdFromChartId(e),r=this.getters.getFigureSheetId(n);if(!r)return;const a=this.getChartDefinitionFromContextCreation(e,t);this.model.dispatch("UPDATE_CHART",{definition:a,chartId:e,figureId:n,sheetId:r})}getChartDefinitionFromContextCreation(e,t){const s=qF.get(t);return{...vR.get(s.chartType).getChartDefinitionFromContextCreation(this.creationContexts[e]),...s.subtypeDefinition}}}class p$ extends t.Component{static template="o-spreadsheet-ChartPanel";static components={Section:YV,ChartTypePicker:u$};static props={onCloseSidePanel:Function,chartId:String};panelContentRef;scrollPositions={configuration:0,design:0};store;get chartId(){return this.props.chartId}setup(){this.store=Av(g$),this.panelContentRef=t.useRef("panelContent"),t.useEffect(()=>{const e=this.panelContentRef.el,t=this.store.panel;e&&(e.scrollTop=this.scrollPositions[t])},()=>[this.store.panel])}switchPanel(e){const t=this.panelContentRef.el;t&&(this.scrollPositions[this.store.panel]=t.scrollTop),this.store.activatePanel(e)}updateChart(e,t){const s=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId)return;const o={...this.getChartDefinition(this.chartId),...t};return this.env.model.dispatch("UPDATE_CHART",{definition:o,chartId:e,figureId:s,sheetId:this.env.model.getters.getFigureSheetId(s)})}canUpdateChart(e,t){const s=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId||!this.env.model.getters.isChartDefined(e))return;const o={...this.getChartDefinition(this.chartId),...t};return this.env.model.canDispatch("UPDATE_CHART",{definition:o,chartId:e,figureId:s,sheetId:this.env.model.getters.getFigureSheetId(s)})}onTypeChange(e){this.chartId&&this.store.changeChartType(this.chartId,e)}get chartPanel(){if(!this.chartId)throw new Error("Chart not defined.");const e=this.env.model.getters.getChartType(this.chartId);if(!e)throw new Error("Chart not defined.");const t=h$.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}}class m$ extends t.Component{static template="o-spreadsheet-IconPicker";static props={onIconPicked:Function};icons=sT;iconSets=oT;onIconClick(e){e&&this.props.onIconPicked(e)}}function f$(e,s){const o=function(e){const s=t.useState({hovered:!1});return kG(e,"mouseenter",()=>s.hovered=!0),kG(e,"mouseleave",()=>s.hovered=!1),s}(e);v$({get highlights(){return o.hovered?s.highlights:[]}})}function v$(e){const s=Rv(),o=Av(NV);t.onMounted(()=>{o.register(e)});let i=e.highlights;t.useEffect(e=>{Le(e,i)||(i=e,s.trigger("store-updated"))},()=>[e.highlights])}class b$ extends t.Component{static template="o-spreadsheet-ConditionalFormatPreview";icons=sT;ref=t.useRef("cfPreview");setup(){f$(this.ref,this)}getPreviewImageStyle(){const e=this.props.conditionalFormat.rule;if("CellIsRule"===e.type)return JF(XF(e.style));if("ColorScaleRule"===e.type){const t=Zv(e.minimum.color),s=e.midpoint?Zv(e.midpoint.color):null,o=Zv(e.maximum.color),i="background-image: linear-gradient(to right, ";return s?i+t+", "+s+", "+o+")":i+t+", "+o+")"}if("DataBarRule"===e.type){return`${`background-image: linear-gradient(to right, ${Zv(e.color)} 50%, white 50%)`}; color: ${C};`}return""}getDescription(){const e=this.props.conditionalFormat;switch(e.rule.type){case"CellIsRule":return W_.get(e.rule.operator).getPreview({...e.rule,type:e.rule.operator},this.env.model.getters);case"ColorScaleRule":return Ug.ColorScale;case"IconSetRule":return Ug.IconSet;case"DataBarRule":return Ug.DataBar}}deleteConditionalFormat(){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:this.props.conditionalFormat.id,sheetId:this.env.model.getters.getActiveSheetId()})}onMouseDown(e){this.props.onMouseDown(e)}get highlights(){const e=this.env.model.getters.getActiveSheetId();return this.props.conditionalFormat.ranges.map(t=>({range:this.env.model.getters.getRangeFromSheetXC(e,t),color:o,fillAlpha:.06}))}}b$.props={conditionalFormat:Object,onPreviewClick:Function,onMouseDown:Function,class:String};class S$ extends t.Component{static template="o-spreadsheet-ConditionalFormatPreviewList";static props={conditionalFormats:Array,onPreviewClick:Function,onAddConditionalFormat:Function};static components={ConditionalFormatPreview:b$};icons=sT;dragAndDrop=KV();cfListRef=t.useRef("cfList");setup(){t.onWillUpdateProps(e=>{Le(this.props.conditionalFormats,e.conditionalFormats)||this.dragAndDrop.cancel()})}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[e.id]||""}onPreviewMouseDown(e,t){if(0!==t.button)return;const s=Array.from(this.cfListRef.el.children).map(e=>FN(e)),o=this.props.conditionalFormats.map((e,t)=>({id:e.id,size:s[t].height,position:s[t].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.id,initialMousePosition:t.clientY,items:o,scrollableContainerEl:this.cfListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const s=this.props.conditionalFormats.findIndex(t=>t.id===e)-t;0!==s&&this.env.model.dispatch("CHANGE_CONDITIONAL_FORMAT_PRIORITY",{cfId:e,delta:s,sheetId:this.env.model.getters.getActiveSheetId()})}}class y$ extends t.Component{static template="o-spreadsheet-ConditionalFormattingEditor";static props={editedCf:Object,onCancel:Function,onExit:Function,isNewCf:Boolean};static components={SelectionInput:iz,IconPicker:m$,ColorPickerWidget:uW,ConditionalFormatPreviewList:S$,Section:YV,RoundColorPicker:XV,StandaloneComposer:HV,BadgeSelection:EW,ValidationMessages:MG,SelectMenu:lz};icons=sT;iconSets=oT;getTextDecoration=YF;colorNumberToHex=Zv;state;setup(){switch(this.state=t.useState({errors:[],currentCFType:this.props.editedCf.rule.type,ranges:this.props.editedCf.ranges,rules:this.getDefaultRules(),hasEditedCf:this.props.isNewCf}),this.props.editedCf.rule.type){case"CellIsRule":this.state.rules.cellIs=this.props.editedCf.rule;break;case"ColorScaleRule":this.state.rules.colorScale=this.props.editedCf.rule;break;case"IconSetRule":this.state.rules.iconSet=this.props.editedCf.rule;break;case"DataBarRule":this.state.rules.dataBar=this.props.editedCf.rule}t.useExternalListener(window,"click",this.closeMenus)}get isRangeValid(){return this.state.errors.includes("EmptyRange")}get errorMessages(){return this.state.errors.map(e=>Ug.Errors[e]||Ug.Errors.Unexpected)}get cfTypesValues(){return[{value:"CellIsRule",label:Cs("Single color")},{value:"ColorScaleRule",label:Cs("Color scale")},{value:"IconSetRule",label:Cs("Icon set")},{value:"DataBarRule",label:Cs("Data bar")}]}updateConditionalFormat(e){const t=e.ranges||this.state.ranges;if(this.state.ranges.some(e=>!e.match(mr)))return e.suppressErrors||(this.state.errors=["InvalidRange"]),["InvalidRange"];const s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getLocale(),i=e.rule||this.getEditedRule(this.state.currentCFType),n=this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:xh(i,o),id:this.props.editedCf.id},ranges:t.map(e=>this.env.model.getters.getRangeDataFromXc(s,e)),sheetId:s});n.isSuccessful&&(this.state.hasEditedCf=!0);const r=n.reasons.filter(e=>"NoChanges"!==e);return e.suppressErrors||(this.state.errors=r),r}getEditedRule(e){switch(e){case"CellIsRule":return this.state.rules.cellIs;case"ColorScaleRule":return this.state.rules.colorScale;case"IconSetRule":return this.state.rules.iconSet;case"DataBarRule":return this.state.rules.dataBar}}onSave(){0===this.updateConditionalFormat({}).length&&this.props.onExit()}onCancel(){this.state.hasEditedCf?this.props.onCancel():this.props.onExit()}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"isNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:HT("EFF7FF")},midpoint:void 0,maximum:{type:"value",color:6989903}},iconSet:{type:"IconSetRule",icons:{upper:"arrowGood",middle:"arrowNeutral",lower:"arrowBad"},upperInflectionPoint:{type:"percentage",value:"66",operator:"gt"},lowerInflectionPoint:{type:"percentage",value:"33",operator:"gt"}},dataBar:{type:"DataBarRule",color:14281427}}}changeRuleType(e){this.state.currentCFType!==e&&(this.state.errors=[],this.state.currentCFType=e,this.updateConditionalFormat({rule:this.getEditedRule(e),suppressErrors:!0}))}onRangeUpdate(e){this.state.ranges=e}onRangeConfirmed(){this.updateConditionalFormat({ranges:this.state.ranges})}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){return this.state.errors.includes("FirstArgMissing")||this.state.errors.includes("ValueCellIsInvalidFormula")}get isValue2Invalid(){return this.state.errors.includes("SecondArgMissing")}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}onKeydown(e){if("F4"===e.key){const t=e.target,s=FV({start:t.selectionStart??0,end:t.selectionEnd??0},t.value,this.env.model.getters.getLocale());if(!s)return;t.value=s.content,t.setSelectionRange(s.selection.start,s.selection.end),t.dispatchEvent(new Event("input"))}}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}editOperator(e){this.state.rules.cellIs.operator=e,e.includes("date")&&!this.state.rules.cellIs.dateValue&&(this.state.rules.cellIs.dateValue="exactDate"),this.updateConditionalFormat({rule:this.state.rules.cellIs,suppressErrors:!0}),this.closeMenus()}get cfCriterionMenuItems(){return az(e=>this.editOperator(e),jN)}get selectedCriterionName(){return W_.get(this.state.rules.cellIs.operator).name}get criterionComponent(){return rz.get(this.state.rules.cellIs.operator).component}get genericCriterion(){return{type:this.state.rules.cellIs.operator,values:this.state.rules.cellIs.values,dateValue:this.state.rules.cellIs.dateValue}}onRuleValuesChanged(e){this.state.rules.cellIs.values=e.values,this.state.rules.cellIs.dateValue=e.dateValue,this.updateConditionalFormat({rule:{...this.state.rules.cellIs,values:e.values,dateValue:e.dateValue}})}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes("MinInvalidFormula")||this.state.errors.includes("MinBiggerThanMid")||this.state.errors.includes("MinBiggerThanMax")||this.state.errors.includes("MinNaN");case"midpoint":return this.state.errors.includes("MidInvalidFormula")||this.state.errors.includes("MidNaN")||this.state.errors.includes("MidBiggerThanMax");case"maximum":return this.state.errors.includes("MaxInvalidFormula")||this.state.errors.includes("MaxNaN");default:return!1}}setColorScaleColor(e,t){if(!Xv(t))return;const s=this.state.rules.colorScale[e];s&&(s.color=jv(t)),this.updateConditionalFormat({rule:this.state.rules.colorScale}),this.closeMenus()}getColorScalePreviewStyle(){const e=this.state.rules.colorScale,t=Zv(e.minimum.color),s=Zv(e.midpoint?.color||h),o=Zv(e.maximum.color),i="linear-gradient(to right, ";return JF({"background-image":void 0===e.midpoint?i+t+", "+o+")":i+t+", "+s+", "+o+")",color:"#000"})}getThresholdColor(e){return Zv(e?e.color:h)}onMidpointChange(e){const t=e.target.value,s=this.state.rules.colorScale;s.midpoint="none"===t?void 0:{color:h,value:"",...s.midpoint,type:t},this.updateConditionalFormat({rule:s,suppressErrors:!0})}updateThresholdType(e,t){this.state.rules.colorScale[e].type=t,this.updateConditionalFormat({rule:this.state.rules.colorScale,suppressErrors:!0})}updateThresholdValue(e,t){this.state.rules.colorScale[e].value=t,this.updateConditionalFormat({rule:this.state.rules.colorScale})}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes("ValueLowerInflectionNaN")||this.state.errors.includes("ValueLowerInvalidFormula")||this.state.errors.includes("LowerBiggerThanUpper");case"upperInflectionPoint":return this.state.errors.includes("ValueUpperInflectionNaN")||this.state.errors.includes("ValueUpperInvalidFormula")||this.state.errors.includes("LowerBiggerThanUpper");default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIcon(e,t){this.state.rules.iconSet.icons[e]=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionOperator(e,t){this.state.rules.iconSet[e].operator=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionValue(e,t){this.state.rules.iconSet[e].value=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionType(e,t,s){this.state.rules.iconSet[e].type=t,this.updateConditionalFormat({rule:this.state.rules.iconSet,suppressErrors:!0})}getColorScaleComposerProps(e){const t=this.state.rules.colorScale[e];if(!t)throw new Error("Threshold not found");const s=this.isValueInvalid(e);return{onConfirm:e=>{t.value=e,this.updateConditionalFormat({rule:this.state.rules.colorScale})},composerContent:t.value||"",placeholder:Cs("Formula"),defaultStatic:!0,invalid:s,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getColorIconSetComposerProps(e){const t=this.state.rules.iconSet[e],s=this.isInflectionPointInvalid(e);return{onConfirm:e=>{t.value=e,this.updateConditionalFormat({rule:this.state.rules.iconSet})},composerContent:t.value||"",placeholder:Cs("Formula"),defaultStatic:!0,invalid:s,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getRangeValues(){return[this.state.rules.dataBar.rangeValues||""]}updateDataBarColor(e){Xv(e)&&(this.state.rules.dataBar.color=Number.parseInt(e.slice(1),16),this.updateConditionalFormat({rule:this.state.rules.dataBar}))}onDataBarRangeUpdate(e){this.state.rules.dataBar.rangeValues=e[0]}onDataBarRangeChange(){this.updateConditionalFormat({rule:this.state.rules.dataBar})}}class C$ extends t.Component{static template="o-spreadsheet-ConditionalFormattingPanel";static props={selection:{type:Object,optional:!0},onCloseSidePanel:Function};static components={ConditionalFormatPreviewList:S$,ConditionalFormattingEditor:y$,Section:YV};activeSheetId;originalEditedCf=void 0;state=t.useState({mode:"list"});setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId();const e=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===s.length){const e=this.conditionalFormats.find(e=>e.id===s[0]);e&&this.editConditionalFormat(e)}t.onWillUpdateProps(e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===s.length){const e=this.conditionalFormats.find(e=>e.id===s[0]);e&&this.editConditionalFormat(e)}else this.switchToList()}else this.editedCF||this.switchToList()})}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId()).map(e=>({...e,rule:Rh(e.rule,this.env.model.getters.getLocale())}))}switchToList(){this.state.mode="list",this.state.editedCfId=void 0,this.originalEditedCf=void 0}addConditionalFormat(){const e=this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,ranges:this.env.model.getters.getSelectedZones().map(e=>this.env.model.getters.getRangeDataFromZone(this.activeSheetId,e)),cf:{id:e,rule:{type:"CellIsRule",operator:"isNotEmpty",style:{fillColor:"#b6d7a8"},values:[]}}}),this.state.editedCfId=e,this.state.mode="edit",this.originalEditedCf=void 0}editConditionalFormat(e){this.state.mode="edit",this.state.editedCfId=e.id,this.originalEditedCf=e}cancelEdition(){this.originalEditedCf?this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,ranges:this.originalEditedCf.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.activeSheetId,e)),cf:this.originalEditedCf}):this.state.editedCfId&&this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,id:this.state.editedCfId}),this.switchToList()}get editedCF(){return this.conditionalFormats.find(e=>e.id===this.state.editedCfId)}}class I$ extends t.Component{static template="o-spreadsheet-DataValidationEditor";static components={SelectionInput:iz,SelectMenu:lz,Section:YV,ValidationMessages:MG};static props={rule:{type:Object,optional:!0},onExit:Function,onCloseSidePanel:{type:Function,optional:!0}};state=t.useState({rule:this.defaultDataValidationRule,errors:[],isTypeUpdated:!1});editingSheetId;setup(){this.editingSheetId=this.env.model.getters.getActiveSheetId(),this.props.rule&&(this.state.rule={...this.props.rule,ranges:this.props.rule.ranges.map(e=>this.env.model.getters.getRangeString(e,this.editingSheetId))},this.state.rule.criterion.type=this.props.rule.criterion.type)}onCriterionTypeChanged(e){this.state.rule.criterion.type=e,this.state.isTypeUpdated=!0}onRangesChanged(e){this.state.rule.ranges=e}onCriterionChanged(e){this.state.rule.criterion=e}changeRuleIsBlocking(e){const t=e.target.value;this.state.rule.isBlocking="true"===t}onSave(){if(this.state.rule){const e=this.env.model.dispatch("ADD_DATA_VALIDATION_RULE",this.dispatchPayload);e.isSuccessful?this.props.onExit():this.state.errors=e.reasons}}get dispatchPayload(){const e={...this.state.rule,ranges:void 0},t=this.env.model.getters.getLocale(),s=e.criterion,o=W_.get(s.type),i=s.values.slice(0,o.numberOfValues(s)).map(e=>e?.trim()).filter(e=>""!==e&&void 0!==e).map(e=>bh(e,t));return e.criterion={...s,values:i},{sheetId:this.editingSheetId,ranges:this.state.rule.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.editingSheetId,e)),rule:e}}get dvCriterionMenuItems(){return az(e=>this.onCriterionTypeChanged(e),YN)}get selectedCriterionName(){const e=this.state.rule.criterion.type;return W_.get(e).name}get defaultDataValidationRule(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones().map(t=>Pt(this.env.model.getters.getUnboundedZone(e,t)));return{id:this.env.model.uuidGenerator.smallUuid(),criterion:{type:"containsText",values:[""]},ranges:t}}get criterionComponent(){return rz.get(this.state.rule.criterion.type).component}get errorMessages(){return this.state.errors.map(e=>jg.Errors[e]||jg.Errors.Unexpected)}}class w$ extends t.Component{static template="o-spreadsheet-DataValidationPreview";static props={onClick:Function,rule:Object};ref=t.useRef("dvPreview");setup(){f$(this.ref,this)}deleteDataValidation(){const e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("REMOVE_DATA_VALIDATION_RULE",{sheetId:e,id:this.props.rule.id})}get highlights(){return this.props.rule.ranges.map(e=>({range:e,color:o,fillAlpha:.06}))}get rangesString(){const e=this.env.model.getters.getActiveSheetId();return this.props.rule.ranges.map(t=>this.env.model.getters.getRangeString(t,e)).join(", ")}get descriptionString(){return W_.get(this.props.rule.criterion.type).getPreview(this.props.rule.criterion,this.env.model.getters)}}class E$ extends t.Component{static template="o-spreadsheet-DataValidationPanel";static props={onCloseSidePanel:Function};static components={DataValidationPreview:w$,DataValidationEditor:I$};state=t.useState({mode:"list",activeRule:void 0});onPreviewClick(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getDataValidationRule(t,e);s&&(this.state.mode="edit",this.state.activeRule=s)}addDataValidationRule(){this.state.mode="edit",this.state.activeRule=void 0}onExitEditMode(){this.state.mode="list",this.state.activeRule=void 0}localizeDVRule(e){if(!e)return e;return Th(e,this.env.model.getters.getLocale())}get validationRules(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getDataValidationRules(e)}}const x$="#8B008B";var R$;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(R$||(R$={}));class T$ extends Lv{mutators=["updateSearchOptions","updateSearchContent","searchFormulas","selectPreviousMatch","selectNextMatch","replace"];allSheetsMatches=[];activeSheetMatches=[];specificRangeMatches=[];currentSearchRegex=null;initialShowFormulaState;preserveSelectedMatchIndex=!1;irreplaceableMatchCount=0;isSearchDirty=!1;shouldFinalizeUpdateSelection=!1;notificationStore=this.get(kV);selectedMatchIndex=null;toSearch="";toReplace="";searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1,searchScope:"activeSheet",specificRange:void 0};constructor(e){super(e),this.initialShowFormulaState=this.model.getters.shouldShowFormulas(),this.searchOptions.searchFormulas=this.initialShowFormulaState;const t=e(NV);t.register(this),this.onDispose(()=>{this.model.dispatch("SET_FORMULA_VISIBILITY",{show:this.initialShowFormulaState}),t.unRegister(this)})}get searchMatches(){switch(this.searchOptions.searchScope){case"allSheets":return this.allSheetsMatches;case"activeSheet":return this.activeSheetMatches;case"specificRange":return this.specificRangeMatches}}updateSearchContent(e){this._updateSearch(e,this.searchOptions)}updateSearchOptions(e){this._updateSearch(this.toSearch,{...this.searchOptions,...e})}searchFormulas(e){this.model.dispatch("SET_FORMULA_VISIBILITY",{show:e}),this.updateSearchOptions({searchFormulas:e})}selectPreviousMatch(){this.selectNextCell(R$.previous,{jumpToMatchSheet:!0,updateSelection:!0})}selectNextMatch(){this.selectNextCell(R$.next,{jumpToMatchSheet:!0,updateSelection:!0})}handle(e){switch(e.type){case"SET_FORMULA_VISIBILITY":this.updateSearchOptions({searchFormulas:e.show});break;case"UNDO":case"REDO":case"REMOVE_TABLE":case"UPDATE_FILTER":case"REMOVE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"EVALUATE_CELLS":case"UPDATE_CELL":this.isSearchDirty=!0;break;case"ACTIVATE_SHEET":this.isSearchDirty=!0,this.shouldFinalizeUpdateSelection=!0;break;case"REPLACE_SEARCH":for(const t of e.matches)this.replaceMatch(t,e.searchString,e.replaceWith,e.searchOptions);this.irreplaceableMatchCount>0&&this.showReplaceWarningMessage(e.matches.length,this.irreplaceableMatchCount),this.irreplaceableMatchCount=0}}finalize(){this.isSearchDirty&&(this.refreshSearch({jumpToMatchSheet:!1,updateSelection:this.shouldFinalizeUpdateSelection}),this.shouldFinalizeUpdateSelection=!1,this.isSearchDirty=!1)}get allSheetMatchesCount(){return this.allSheetsMatches.length}get activeSheetMatchesCount(){return this.activeSheetMatches.length}get specificRangeMatchesCount(){return this.specificRangeMatches.length}_updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null),this.toSearch=e,this.currentSearchRegex=et(this.toSearch,this.searchOptions),this.refreshSearch({jumpToMatchSheet:!0,updateSelection:!0})}refreshSearch(e){this.preserveSelectedMatchIndex||(this.selectedMatchIndex=null),this.findMatches(),this.selectNextCell(R$.current,e)}getSheetsInSearchOrder(){switch(this.searchOptions.searchScope){case"allSheets":const e=this.getters.getSheetIds(),t=e.findIndex(e=>e===this.getters.getActiveSheetId());return[e[t],...e.slice(t+1),...e.slice(0,t)];case"activeSheet":return[this.getters.getActiveSheetId()];case"specificRange":const s=this.searchOptions.specificRange;return s&&s?[s.sheetId]:[]}}findMatches(){const e=[];if(this.toSearch)for(const t of this.getters.getSheetIds())e.push(...this.findMatchesInSheet(t));if(this.allSheetsMatches=e,this.activeSheetMatches=e.filter(e=>e.sheetId===this.getters.getActiveSheetId()),this.searchOptions.specificRange){const{sheetId:t,zone:s}=this.searchOptions.specificRange;this.specificRangeMatches=e.filter(e=>e.sheetId===t&&Gt(e.col,e.row,s))}else this.specificRangeMatches=[]}findMatchesInSheet(e){const t=[],{left:s,right:o,top:i,bottom:n}=this.getters.getSheetZone(e);for(let r=i;r<=n;r++)for(let i=s;i<=o;i++){const s=this.getters.isColHidden(e,i),o=this.getters.isRowHidden(e,r);if(s||o)continue;const n={sheetId:e,col:i,row:r};if(this.currentSearchRegex?.test(this.getSearchableString(n))){const s={sheetId:e,col:i,row:r};t.push(s)}}return t}selectNextCell(e,t){const s=this.searchMatches;if(!s.length)return void(this.selectedMatchIndex=null);let o;if(null===this.selectedMatchIndex){let e=-1;for(const t of this.getSheetsInSearchOrder())if(e=s.findIndex(e=>e.sheetId===t),-1!==e)break;o=e}else o=this.selectedMatchIndex+e;o=(o+s.length)%s.length,this.selectedMatchIndex=o;const i=s[o];t.jumpToMatchSheet&&this.getters.getActiveSheetId()!==i.sheetId&&(this.preserveSelectedMatchIndex=!0,this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:i.sheetId}),this.preserveSelectedMatchIndex=!1,this.isSearchDirty=!1),this.model.selection.getBackToDefault(),t.updateSelection&&this.model.selection.selectCell(i.col,i.row)}replace(){null!==this.selectedMatchIndex&&(this.preserveSelectedMatchIndex=!0,this.shouldFinalizeUpdateSelection=!0,this.model.dispatch("REPLACE_SEARCH",{searchString:this.toSearch,replaceWith:this.toReplace,matches:[this.searchMatches[this.selectedMatchIndex]],searchOptions:this.searchOptions}),this.preserveSelectedMatchIndex=!1)}replaceAll(){this.model.dispatch("REPLACE_SEARCH",{searchString:this.toSearch,replaceWith:this.toReplace,matches:this.searchMatches,searchOptions:this.searchOptions})}showReplaceWarningMessage(e,t){const s=e-t;0===s?this.notificationStore.notifyUser({type:"warning",sticky:!1,text:Cs("Match(es) cannot be replaced as they are part of a formula.")}):this.notificationStore.notifyUser({type:"warning",sticky:!1,text:Cs("%(replaceable_count)s match(es) replaced. %(irreplaceable_count)s match(es) cannot be replaced as they are part of a formula.",{replaceable_count:s,irreplaceable_count:t})})}replaceMatch(e,t,s,o){const i=this.getters.getCell(e);if(!i?.content)return;if(i?.isFormula&&!o.searchFormulas)return void this.irreplaceableMatchCount++;const n=et(t,o),r=new RegExp(n.source,n.flags+"g"),a=vh(this.getters.getCellText(e,{showFormula:o.searchFormulas}).replace(r,s),this.getters.getLocale());this.model.dispatch("UPDATE_CELL",{...e,content:a})}getSearchableString(e){return this.getters.getCellText(e,{showFormula:this.searchOptions.searchFormulas})}get highlights(){const e=[],t=this.getters.getActiveSheetId();for(const[s,o]of this.searchMatches.entries()){if(o.sheetId!==t)continue;const i=Jt(o),n=this.getters.expandZone(t,i),{width:r,height:a}=this.getters.getVisibleRect(n);r>0&&a>0&&e.push({range:this.model.getters.getRangeFromZone(t,n),color:x$,noBorder:s!==this.selectedMatchIndex,thinLine:!0,fillAlpha:.2})}if("specificRange"===this.searchOptions.searchScope){const s=this.searchOptions.specificRange;s&&s.sheetId===t&&e.push({range:s,color:x$,noFill:!0,thinLine:!0})}return e}}class A$ extends t.Component{static template="o-spreadsheet-FindAndReplacePanel";static components={SelectionInput:iz,Section:YV,Checkbox:hz,ValidationMessages:MG};static props={onCloseSidePanel:Function};searchInput=t.useRef("searchInput");store;state;updateSearchContent;get hasSearchResult(){return null!==this.store.selectedMatchIndex}get searchOptions(){return this.store.searchOptions}get allSheetsMatchesCount(){return Cs("%s matches in all sheets",this.store.allSheetMatchesCount)}get currentSheetMatchesCount(){return Cs("%(matches)s matches in %(sheetName)s",{matches:this.store.activeSheetMatchesCount,sheetName:this.env.model.getters.getSheetName(this.env.model.getters.getActiveSheetId())})}get specificRangeMatchesCount(){const e=this.searchOptions.specificRange;if(!e)return"";const{sheetId:t,zone:s}=e;return Cs("%(matches)s matches in range %(range)s of %(sheetName)s",{matches:this.store.specificRangeMatchesCount,range:Pt(s),sheetName:this.env.model.getters.getSheetName(t)})}get searchInfo(){return this.store.toSearch?[this.specificRangeMatchesCount,this.currentSheetMatchesCount,this.allSheetsMatchesCount]:[]}setup(){this.store=Av(T$),this.state=t.useState({dataRange:""}),t.onMounted(()=>this.searchInput.el?.focus()),t.onWillUnmount(()=>this.updateSearchContent.stopDebounce()),this.updateSearchContent=Fe(this.store.updateSearchContent,200),t.useExternalListener(window,"keydown",e=>{const t=LN(e);"Ctrl+F"!==t&&"Ctrl+H"!==t||(this.searchInput.el?.focus(),e.preventDefault(),e.stopPropagation())},{capture:!0})}onFocusSearch(){this.updateDataRange()}onSearchInput(e){this.updateSearchContent(e.target.value)}onKeydownSearch(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),e.shiftKey?this.store.selectPreviousMatch():this.store.selectNextMatch())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),this.store.replace())}searchFormulas(e){this.store.searchFormulas(e)}searchExactMatch(e){this.store.updateSearchOptions({exactMatch:e})}searchMatchCase(e){this.store.updateSearchOptions({matchCase:e})}changeSearchScope(e){const t=e.target.value;this.store.updateSearchOptions({searchScope:t})}onSearchRangeChanged(e){this.state.dataRange=e[0]}updateDataRange(){if(!this.state.dataRange||"specificRange"!==this.searchOptions.searchScope)return;const e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.dataRange);this.store.updateSearchOptions({specificRange:e})}get pendingSearch(){return this.updateSearchContent.isDebouncePending()}}const _$=new Jg,D$={name:Gg.Custom,code:"",symbol:"",decimalPlaces:2,position:"after"};class O$ extends Lv{mutators=["updateFormat","changeCategory","selectCurrency","changeCurrencyCode","changeCurrencySymbol","updateAvailableCurrencies"];invalidFormat=!1;currentFormat=this.formatInSelection;category=this.detectFormatCategory(this.formatInSelection);selectedCurrencyIndex=0;currencyCode="";currencySymbol="";isAccountingFormat=!1;availableCurrencies=[D$,..._$.getAll()];lastFormatInSelection=this.currentFormat;usedFormatForCategory={};constructor(e,t){super(e),t&&(this.category=t),this.model.selection.observe(this,{handleEvent:this.handleSelectionEvent.bind(this)}),this.onDispose(()=>{this.model.selection.unobserve(this)})}handle(){const e=this.formatInSelection;e&&this.lastFormatInSelection!==e&&(this.setActiveFormat(e),this.lastFormatInSelection=e)}handleSelectionEvent(){if(this.getters.isGridSelectionActive()){const e=this.formatInSelection;e&&e!==this.lastFormatInSelection&&(this.setActiveFormat(e),this.lastFormatInSelection=e)}}setActiveFormat(e){this.currentFormat=e,this.invalidFormat=!pn(e||""),this.category=this.detectFormatCategory(e)}get categories(){return[{label:Cs("Number"),value:"number"},{label:Cs("Date"),value:"date"},{label:Cs("Currency"),value:"currency"}]}get formatInSelection(){const e=this.getters.getActivePosition();return"VALUE"===this.getters.getPivotCellFromPosition(e).type?this.getters.getEvaluatedCell(e).format:this.getters.getCell(e)?.format}detectFormatCategory(e){return e?ji(e)?"date":e.includes("$")||e.includes('"')?"currency":"number":"number"}get formatProposals(){return"date"===this.category?this.dateFormatProposals:"currency"===this.category?this.currencyFormatProposals:"number"===this.category?this.numberFormatProposals:[]}get numberFormatProposals(){const e=["0.00","0","#,##0","#,##0.00","0%","0.00%","0.00e","0.00;(0.00);-"].map(e=>({label:zi(-1234.56,{format:e,locale:this.getters.getLocale()}),format:e}));return[{label:Cs("Automatic"),format:void 0},{label:Cs("Plain text"),format:"@"},...e]}get dateFormatProposals(){const e=this.getters.getLocale();return[e.dateFormat,e.timeFormat,e.dateFormat+" "+e.timeFormat,"dddd d mmmm yyyy hh:mm:ss a","yyyy-mm-dd","yyyy-mm-dd hh:mm:ss","dddd d mmmm yyyy","d mmmm yyyy","ddd d mmm yyyy","d mmm yyyy","mmmm yyyy","mmm yyyy","hhhh:mm:ss","qq yyyy","qqqq yyyy"].map(t=>({label:zi(EB,{format:t,locale:e}),format:t}))}get currencyFormatProposals(){const e=this.availableCurrencies[this.selectedCurrencyIndex],t=e.position,s="before"===e.position?"after":"before",o=this.currencySymbol.trim()?this.currencySymbol:"",i=this.currencyCode.trim()?this.currencyCode:"",n=e.decimalPlaces;if(!o&&!i)return[];const r=[{symbol:o,position:t,decimalPlaces:0},{symbol:o,position:t,decimalPlaces:n},{symbol:o,position:t,decimalPlaces:0,code:i},{symbol:o,position:t,decimalPlaces:n,code:i},{symbol:o,position:s,decimalPlaces:0},{symbol:o,position:s,decimalPlaces:n},{symbol:o,position:s,decimalPlaces:0,code:i},{symbol:o,position:s,decimalPlaces:n,code:i}],a=new Set,l=this.getters.getLocale();return r.map(e=>{const t=this.isAccountingFormat?tn(e):en(e);if((e.symbol||e.code)&&!a.has(t))return a.add(t),{format:t,label:zi(1e3,{format:t,locale:l})}}).filter(De)}get formatExamples(){const e=this.currentFormat,t=this.getters.getLocale();if(!e||!pn(e))return[];if("date"===this.category)return[{label:Cs("Sample:"),value:zi(EB,{format:e,locale:t})}];{const s=function(e){return pi(e).length}(e),o=[{label:Cs("Positive:"),value:zi(1234.56,{format:e,locale:t})},{label:Cs("Negative:"),value:zi(-1234.56,{format:e,locale:t})},{label:Cs("Zero:"),value:zi(0,{format:e,locale:t})}];return 4===s&&o.push({label:Cs("Text:"),value:zi("Text",{format:e,locale:t})}),o}}updateAvailableCurrencies(){this.availableCurrencies=[D$,..._$.getAll()]}updateFormat(e){this.currentFormat=e,this.invalidFormat=!pn(e),this.invalidFormat||(this.lastFormatInSelection=e,this.model.dispatch("SET_FORMATTING_WITH_PIVOT",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),format:e||""}))}changeCategory(e){if(e===this.category)return"noStateChange";this.usedFormatForCategory[this.category]=this.currentFormat,this.category=e;const t=this.usedFormatForCategory[e]||this.formatProposals[0]?.format||"";this.updateFormat(t)}selectCurrency(e){const t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.selectedCurrencyIndex=e;const s=this.availableCurrencies[e];this.currencyCode=s.code,this.currencySymbol=s.symbol,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||"")}changeCurrencyCode(e){const t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.currencyCode=e,this.selectedCurrencyIndex=0,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||"")}changeCurrencySymbol(e){const t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.currencySymbol=e,this.selectedCurrencyIndex=0,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||"")}toggleAccountingFormat(){const e=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.isAccountingFormat=!this.isAccountingFormat,this.updateFormat(this.formatProposals[e]?.format||this.formatProposals[0]?.format||"")}get invalidFormatMessage(){return this.invalidFormat?Cs("The format entered is not valid."):void 0}}class F$ extends t.Component{static template="o-spreadsheet-MoreFormatsPanel";static props={onCloseSidePanel:Function,category:{type:String,optional:!0}};static components={BadgeSelection:EW,Section:YV,TextInput:hW,Checkbox:hz};store;setup(){this.store=Av(O$,this.props.category),t.onWillStart(()=>this.loadCurrencies()),t.onWillUpdateProps(e=>{e.category&&e.category!==this.props.category&&this.store.changeCategory(e.category)})}async loadCurrencies(){if(0===_$.getAll().length){(await(this.env.loadCurrencies?.()??Promise.resolve([]))).forEach((e,t)=>{_$.replace(t.toString(),e)}),this.store.updateAvailableCurrencies()}}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:"")}updateSelectCurrency(e){const t=e.target,s=parseInt(t.value,10);this.store.selectCurrency(s)}isFormatSelected(e){return e===this.store.currentFormat}}class P$ extends Lv{pivotId;initialMeasure;mutators=["cancelMeasureDisplayEdition","updateMeasureDisplayType","updateMeasureDisplayField","updateMeasureDisplayValue"];measureDisplay;constructor(e,t,s){super(e),this.pivotId=t,this.initialMeasure=s,this.measureDisplay=s.display||{type:"no_calculations"}}updateMeasureDisplayType(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(e,this.measureDisplay.fieldNameWithGranularity,this.measureDisplay.value))}updateMeasureDisplayField(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,e,this.measureDisplay.value))}updateMeasureDisplayValue(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,this.measureDisplay.fieldNameWithGranularity,e))}updatePivotMeasureDisplay(e){const t=he(this.model.getters.getPivotCoreDefinition(this.pivotId)),s=this.getMeasureIndex(this.initialMeasure.id,t),o={...t.measures[s],display:e};t.measures[s]=o;this.model.dispatch("UPDATE_PIVOT",{pivot:t,pivotId:this.pivotId}).isSuccessful&&(this.measureDisplay=e)}getMeasureDisplay(e,t,s){switch(e){case"no_calculations":case"%_of_grand_total":case"%_of_col_total":case"%_of_row_total":case"%_of_parent_row_total":case"%_of_parent_col_total":case"index":return{type:e};case"%_of_parent_total":case"running_total":case"%_running_total":case"rank_asc":case"rank_desc":return t||(t=this.fields[0]?.nameWithGranularity),{type:e,fieldNameWithGranularity:t};case"%_of":case"difference_from":case"%_difference_from":t||(t=this.fields[0]?.nameWithGranularity);const o=this.getPossibleValues(t);return void 0!==s&&o.find(e=>e.value===s)||(s=tD),{type:e,fieldNameWithGranularity:t,value:s??tD}}}getMeasureIndex(e,t){const s=t.measures.findIndex(t=>t.id===e);if(-1===s)throw new Error(`Measure with id ${e} not found in pivot.`);return s}get doesDisplayNeedsField(){return["%_of_parent_total","running_total","%_running_total","rank_asc","rank_desc"].includes(this.measureDisplay.type)||this.doesDisplayNeedsValue}get fields(){const e=this.getters.getPivot(this.pivotId).definition;return[...e.columns,...e.rows].map(e=>({...e,displayName:Pp(e)}))}get doesDisplayNeedsValue(){return this.isDisplayValueDependant(this.measureDisplay)}isDisplayValueDependant(e){return["%_of","difference_from","%_difference_from"].includes(e.type)}get values(){const e=this.measureDisplay;return this.isDisplayValueDependant(e)?this.getPossibleValues(e.fieldNameWithGranularity):[]}getPossibleValues(e){const t=[{value:tD,label:Cs("(previous)")},{value:sD,label:Cs("(next)")}],s=this.fields.find(t=>t.nameWithGranularity===e);if(!s)return[];return[...t,...this.getters.getPivot(this.pivotId).getPossibleFieldValues(s)]}cancelMeasureDisplayEdition(){const e=he(this.model.getters.getPivotCoreDefinition(this.pivotId)),t=this.getMeasureIndex(this.initialMeasure.id,e);e.measures[t]={...e.measures[t],display:this.initialMeasure.display},this.model.dispatch("UPDATE_PIVOT",{pivot:e,pivotId:this.pivotId})}}class M$ extends t.Component{static template="o-spreadsheet-PivotMeasureDisplayPanel";static props={onCloseSidePanel:Function,pivotId:String,measure:Object};static components={Section:YV,Checkbox:hz,RadioSelection:TW};measureDisplayTypeLabels=Xg.labels;measureDisplayDescription=Xg.documentation;store;setup(){this.store=Av(P$,this.props.pivotId,this.props.measure)}onSave(){this.env.replaceSidePanel("PivotSidePanel",`pivot_measure_display_${this.props.pivotId}_${this.props.measure.id}`,{pivotId:this.props.pivotId})}onCancel(){this.store.cancelMeasureDisplayEdition(),this.env.replaceSidePanel("PivotSidePanel",`pivot_measure_display_${this.props.pivotId}_${this.props.measure.id}`,{pivotId:this.props.pivotId})}get fieldChoices(){return this.store.fields.map(e=>({value:e.nameWithGranularity,label:e.displayName}))}}function N$(e,t){const s=e.getActiveSheetId(),i=function(e,t){const s=[],o=e.getActiveSheetId();for(const i of e.getSheetViewVisibleCols())for(const n of e.getSheetViewVisibleRows()){const r={sheetId:o,col:i,row:n};t===e.getPivotIdFromPosition(r)&&s.push(r)}return s}(e,t);return ns(i.map(Jt)).map(t=>({range:e.getRangeFromZone(s,t),noFill:!0,color:o}))}class k$ extends t.Component{static template="o-spreadsheet-PivotDeferUpdate";static props={deferUpdate:Boolean,isDirty:Boolean,toggleDeferUpdate:Function,discard:Function,apply:Function};static components={Section:YV,Checkbox:hz};get deferUpdatesLabel(){return Cs("Defer updates")}get deferUpdatesTooltip(){return Cs("Changing the pivot definition requires to reload the data. It may take some time.")}}class L$ extends t.Component{static template="o-spreadsheet-PivotCustomGroupsCollapsible";static props={pivotId:String,customField:Object,onCustomFieldUpdated:Function};static components={SidePanelCollapsible:gV,TextInput:hW,Checkbox:hz};get groups(){return this.props.customField.groups.sort((e,t)=>e.isOtherGroup||t.isOtherGroup?e.isOtherGroup?1:-1:0)}get hasOthersGroup(){return this.props.customField.groups.some(e=>e.isOtherGroup)}addOthersGroup(){if(this.hasOthersGroup)return;const e={name:kp(Cs("Others"),this.props.customField),values:[],isOtherGroup:!0},t=[...this.props.customField.groups,e];this.updateCustomField({...this.props.customField,groups:t})}onDeleteGroup(e){const t=[...this.props.customField.groups];t.splice(e,1),this.updateCustomField({...this.props.customField,groups:t})}onRenameGroup(e,t){const s=he(this.props.customField.groups),o=s[e];o&&(o.name=kp(t,this.props.customField),this.updateCustomField({...this.props.customField,groups:s}))}updateCustomField(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.props.onCustomFieldUpdated({customFields:{...t.customFields,[e.name]:e}})}}function V$(e,t,s,o){const i=[];e=e.toLowerCase();for(const n of e){const e=t.toLocaleLowerCase().indexOf(n);-1!==e&&(i.push({value:t.slice(0,e),color:""},{value:t[e],color:s,classes:[o]}),t=t.slice(e+1))}return i.push({value:t}),i.filter(e=>e.value)}class z$ extends t.Component{static template="o-spreadsheet-AddDimensionButton";static components={Popover:jL,TextValueProvider:bV};static props={onFieldPicked:Function,fields:Array,slots:{type:Object,optional:!0}};buttonRef=t.useRef("button");popover=t.useState({isOpen:!1});search=t.useState({input:""});autoComplete;setup(){this.autoComplete=Av(LV),this.autoComplete.useProvider(this.getProvider()),t.useExternalListener(window,"click",e=>{e.target!==this.buttonRef.el&&(this.popover.isOpen=!1)}),lW({refName:"autofocus"})}getProvider(){return{proposals:this.proposals,autoSelectFirstProposal:!1,selectProposal:e=>{const t=this.props.fields.find(t=>t.string===e);t&&this.pickField(t)}}}get proposals(){let e;return e=this.search.input?LS(this.search.input,this.props.fields,e=>e.string===e.name?e.string:e.string+e.name):this.props.fields,e.map(e=>{const t=e.string;return{text:t,fuzzySearchKey:t,htmlContent:V$(this.search.input,t,g,"o-semi-bold")}})}get popoverProps(){const{x:e,y:t,width:s,height:o}=this.buttonRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:s,height:o},positioning:"bottom-left"}}updateSearch(e){this.search.input=e,this.autoComplete.useProvider(this.getProvider())}pickField(e){this.props.onFieldPicked(e.name),this.togglePopover()}togglePopover(){this.popover.isOpen=!this.popover.isOpen,this.search.input="",this.autoComplete.useProvider(this.getProvider())}onKeyDown(e){switch(e.key){case"Enter":const t=this.autoComplete.provider?.proposals;1===t?.length&&this.autoComplete.provider?.selectProposal(t[0].text||"");const s=this.autoComplete.selectedProposal;this.autoComplete.provider?.selectProposal(s?.text||"");break;case"ArrowUp":case"ArrowDown":this.autoComplete.moveSelection("ArrowDown"===e.key?"next":"previous");break;case"Escape":this.popover.isOpen=!1}}}class H$ extends t.Component{static template="o-spreadsheet-PivotDimension";static props={dimension:Object,onRemoved:{type:Function,optional:!0},onNameUpdated:{type:Function,optional:!0},slots:{type:Object,optional:!0}};static components={CogWheelMenu:fW,TextInput:hW};updateName(e){this.props.onNameUpdated?.(this.props.dimension,""===e||e.startsWith("=")?void 0:e)}}class U$ extends t.Component{static template="o-spreadsheet-PivotDimensionGranularity";static props={dimension:Object,onUpdated:Function,availableGranularities:Set,allGranularities:Array};periods=yp}class B$ extends t.Component{static template="o-spreadsheet-PivotDimensionOrder";static props={dimension:Object,onUpdated:Function}}class G$ extends t.Component{static template="o-spreadsheet-PivotMeasureEditor";static components={PivotDimension:H$,StandaloneComposer:HV};static props={definition:Object,measure:Object,onMeasureUpdated:Function,onRemoved:Function,generateMeasureId:Function,aggregators:Object,pivotId:String};getMeasureAutocomplete(){return e=this.props.definition,t=this.props.measure,{sequence:0,autoSelectFirstProposal:!0,getProposals(s){const o=e.measures.filter(e=>e!==t).map(e=>{const t=ge(e.id);return{text:t,description:e.displayName,htmlContent:[{value:t,color:_}],fuzzySearchKey:e.displayName+t+e.fieldName}}),i=e.rows.concat(e.columns).map(e=>{const t=ge(e.nameWithGranularity);return{text:t,description:e.displayName,htmlContent:[{value:t,color:_}],fuzzySearchKey:e.displayName+t+e.fieldName}});return o.concat(i)},selectProposal(e,t){let s=e.end;"SYMBOL"===e.type&&(s=e.start);const o=e.end;this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}};var e,t}updateMeasureFormula(e){this.props.onMeasureUpdated({...this.props.measure,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:"="===e[0]?e:"="+e}})}updateAggregator(e){this.props.onMeasureUpdated({...this.props.measure,aggregator:e,id:this.props.generateMeasureId(this.props.measure.fieldName,e)})}updateName(e,t){this.props.measure.computedBy&&t?this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t,id:this.props.generateMeasureId(t,this.props.measure.aggregator),fieldName:t}):this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t})}toggleMeasureVisibility(){this.props.onMeasureUpdated({...this.props.measure,isHidden:!this.props.measure.isHidden})}openShowValuesAs(){this.env.replaceSidePanel("PivotMeasureDisplayPanel",`pivot_key_${this.props.pivotId}`,{pivotId:this.props.pivotId,measure:this.props.measure})}getColoredSymbolToken(e){if("SYMBOL"!==e.type)return;const t=ue(e.value,"'");return this.props.definition.columns.some(e=>e.nameWithGranularity===t)||this.props.definition.rows.some(e=>e.nameWithGranularity===t)||this.props.definition.measures.some(e=>e.id===t&&e.id!==this.props.measure.id)?_:void 0}get isCalculatedMeasureInvalid(){return zx(this.props.measure.computedBy?.formula??"").isBadExpression}}class W$ extends t.Component{static template="o-spreadsheet-PivotSortSection";static components={Section:YV};static props={definition:Object,pivotId:String};get hasValidSort(){const e=this.env.model.getters.getPivot(this.props.pivotId);return!!this.props.definition.sortedColumn&&Np(this.props.definition.sortedColumn,e)}get sortDescription(){const e="asc"===this.props.definition.sortedColumn?.order?Cs("ascending"):Cs("descending");return Cs("Sorted on column (%(ascOrDesc)s):",{ascOrDesc:e})}get sortValuesAndFields(){const e=this.props.definition.sortedColumn;if(!e)return[];const t=this.env.model.getters.getPivot(this.props.pivotId),s=this.env.model.getters.getLocale(),o=[],i=[];for(const n of e.domain){o.push(n);const{value:e,format:r}=t.getPivotHeaderValueAndFormat(o),a=zi(e,{format:r,locale:s}),l=t.definition.getDimension(n.field);i.push({field:Pp(l),value:a})}0===e.domain.length&&i.push({value:Cs("Total")});const n=t.getMeasure(e.measure).displayName;return i.push({value:n,field:Cs("Measure")}),i}}class $$ extends t.Component{static template="o-spreadsheet-PivotLayoutConfigurator";static components={AddDimensionButton:z$,PivotDimension:H$,PivotDimensionOrder:B$,PivotDimensionGranularity:U$,PivotMeasureEditor:G$,PivotSortSection:W$,PivotCustomGroupsCollapsible:L$};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=t.useRef("pivot-dimensions");dragAndDrop=KV();AGGREGATORS=vp;composerFocus;isDateOrDatetimeField=wp;setup(){this.composerFocus=Tv(zv)}startDragAndDrop(e,t){if(0!==t.button||"SELECT"===t.target.tagName)return;const s=this.getDimensionElementsRects(),o=this.props.definition,{columns:i,rows:n}=o,r=[...i.map(e=>e.nameWithGranularity),"__rows_title__",...n.map(e=>e.nameWithGranularity)],a=i.concat(n),l=r.map((e,t)=>({id:e,size:s[t+1].height,position:s[t+1].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:l,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{const s=r.findIndex(t=>t===e);if(s===t)return;const o=[...r];o.splice(s,1),o.splice(t,0,e);const i=o.slice(0,o.indexOf("__rows_title__")),n=o.slice(o.indexOf("__rows_title__")+1);this.props.onDimensionsUpdated({columns:i.map(e=>a.find(t=>t.nameWithGranularity===e)).filter(De),rows:n.map(e=>a.find(t=>t.nameWithGranularity===e)).filter(De)})}})}getGranularitiesFor(e){return wp(e)?"date"===e.type?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(0!==t.button||"SELECT"===t.target.tagName||"INPUT"===t.target.tagName||"inactive"!==this.composerFocus.focusMode)return;const s=this.getDimensionElementsRects(),o=this.props.definition,{measures:i,columns:n,rows:r}=o,a=i.map(e=>e.id),l=3+n.length+r.length,c=a.map((e,t)=>({id:e,size:s[t+l].height,position:s[t+l].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{const s=a.findIndex(t=>t===e);if(s===t)return;const o=[...a];o.splice(s,1),o.splice(t,0,e),this.props.onDimensionsUpdated({measures:o.map(e=>i.find(t=>t.id===e)).filter(De)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{const t=getComputedStyle(e),s=e.getBoundingClientRect();return{x:s.x,y:s.y,width:s.width+parseInt(t.marginLeft||"0")+parseInt(t.marginRight||"0"),height:s.height+parseInt(t.marginTop||"0")+parseInt(t.marginBottom||"0")}})}removeDimension(e){const{columns:t,rows:s}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:s.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){const{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){const{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:"asc"}])})}addRowDimension(e){const{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:"asc"}])})}addMeasureDimension(e){const{measures:t}=this.props.definition,s=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,s),fieldName:e,aggregator:s}])})}updateMeasure(e,t){const{measures:s}=this.props.definition,o={measures:s.map(s=>s.id===e.id?t:s)};this.props.definition.sortedColumn?.measure===e.id&&(o.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(o)}getMeasureId(e,t){const s=e.replaceAll("'","")+(t?`:${t}`:"");let o=s,i=2;for(;this.props.definition.measures.some(e=>e.id===o);)o=`${s}:${i}`,i++;return o}getDefaultMeasureAggregator(e){const t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:"count"}addCalculatedMeasure(){const{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,"sum"),fieldName:t,aggregator:"sum",computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:"=0"}}])})}getCustomField(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);return t.customFields?.[e.nameWithGranularity]}updateOrder(e,t){const{rows:s,columns:o}=this.props.definition;this.props.onDimensionsUpdated({rows:s.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,order:t||void 0}:s),columns:o.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,order:t||void 0}:s)})}updateGranularity(e,t){const{rows:s,columns:o}=this.props.definition;this.props.onDimensionsUpdated({rows:s.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,granularity:t}:s),columns:o.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,granularity:t}:s)})}getMeasureDescription(e){const t=e.display;if(!t||"no_calculations"===t.type)return"";const s=this.env.model.getters.getPivot(this.props.pivotId),o=[...s.definition.columns,...s.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=o?Pp(o):"";return Xg.descriptions[t.type](i)}getHugeDimensionErrorMessage(e){const t=this.env.model.getters.getPivot(this.props.pivotId).getPossibleFieldValues(e);return t.length>100?Cs("This dimension contains a lot of values (%s), and might slow down the pivot table.",t.length):void 0}}class q$ extends t.Component{static template="o-spreadsheet-PivotTitleSection";static components={CogWheelMenu:fW,Section:YV,TextInput:hW};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:Cs("Flip axes"),icon:"o-spreadsheet-Icon.EXCHANGE",execute:this.props.flipAxis},{name:Cs("Duplicate"),icon:"o-spreadsheet-Icon.COPY",execute:()=>this.duplicatePivot()},{name:Cs("Delete"),icon:"o-spreadsheet-Icon.TRASH",execute:()=>this.delete()}]}get name(){return this.env.model.getters.getPivotName(this.props.pivotId)}get displayName(){return this.env.model.getters.getPivotDisplayName(this.props.pivotId)}duplicatePivot(){const e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),s=this.env.model.dispatch("DUPLICATE_PIVOT_IN_NEW_SHEET",{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t});let o;o=s.isSuccessful?Cs("Pivot duplicated."):s.isCancelledBecause("PivotInError")?Cs("Cannot duplicate a pivot in error."):Cs("Pivot duplication failed.");const i=s.isSuccessful?"success":"danger";this.env.notifyUser({text:o,sticky:!1,type:i}),s.isSuccessful&&this.env.openSidePanel("PivotSidePanel",{pivotId:e})}delete(){this.env.askConfirmation(Cs("Are you sure you want to delete this pivot?"),()=>{this.env.model.dispatch("REMOVE_PIVOT",{pivotId:this.props.pivotId})})}onNameChanged(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch("UPDATE_PIVOT",{pivotId:this.props.pivotId,pivot:{...t,name:e}})}}class Z$ extends Lv{pivotId;updateMode;mutators=["reset","deferUpdates","applyUpdate","discardPendingUpdate","update"];_updatesAreDeferred;draft=null;notification=this.get(kV);alreadyNotified=!1;alreadyNotifiedForPivotSize=!1;constructor(e,t,s="canDefer"){super(e),this.pivotId=t,this.updateMode=s,this._updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){if("UPDATE_PIVOT"===e.type)e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}get updatesAreDeferred(){return"neverDefer"!==this.updateMode&&this._updatesAreDeferred}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){const e=AD.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){const e=[{name:"__count",string:Cs("Count"),type:"integer",aggregator:"sum"}],t=this.fields;for(const s in t){const o=t[s];o&&(AD.get(this.pivot.type).isMeasureCandidate(o)&&e.push(o))}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){const e=[],t=this.fields;for(const s in t){const o=t[s];o&&(AD.get(this.pivot.type).isGroupable(o)&&e.push(o))}const{columns:s,rows:o,measures:i}=this.definition,n=i.concat(o).concat(s).map(e=>e.fieldName),r=this.unusedGranularities;return e.filter(e=>wp(e)?!n.includes(e.name)||r[e.name].size>0:!n.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return AD.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return AD.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this._updatesAreDeferred=!0,this.draft=null}deferUpdates(e){!1===e&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this._updatesAreDeferred=e}applyUpdate(){if(this.draft){if(this.model.dispatch("UPDATE_PIVOT",{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot()){const e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:"info",text:Cs("Pivot updates only work with dynamic pivot tables. Use the formula '%s' or re-insert the static pivot from the Data menu.",e),sticky:!0})}const e=this.getters.getPivot(this.pivotId),t=e.isValid()?e.getExpandedTableStructure().numberOfCells:0;!this.alreadyNotifiedForPivotSize&&t>se&&(this.alreadyNotifiedForPivotSize=!0,this.notification.notifyUser({type:"warning",text:Kg(t,this.getters.getLocale()),sticky:!0}))}}discardPendingUpdate(){this.draft=null}update(e){const t=this.getters.getPivotCoreDefinition(this.pivotId),s={...t,...this.draft,...e},o={...s,columns:s.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:s.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:s.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display})),sortedColumn:this.shouldKeepSortedColumn(s)?s.sortedColumn:void 0};if(o.collapsedDomains){const{COL:e,ROW:t}=o.collapsedDomains;o.collapsedDomains={COL:e.filter(e=>this.areDomainFieldsValid(e,o.columns)),ROW:t.filter(e=>this.areDomainFieldsValid(e,o.rows))}}if(!this.draft&&Le(t,o))return;const i=this.addDefaultDateTimeGranularity(this.fields,o);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0;const t=this.getters.getPivotFormulaId(this.pivotId);for(const s of this.getters.getVisibleCellPositions()){const o=this.getters.getCell(s);if(o?.isFormula){const s=EF(o.compiledFormula.tokens),i=s?.args[0]?.value;if(s&&t===i.toString()){if("PIVOT"===s.functionName)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){const{columns:s,rows:o}=t,i=he(s),n=he(o),r=this.getUnusedGranularities(e,t);for(const t of i.concat(n)){const s=e[t.fieldName]?.type;if(("date"===s||"datetime"===s)&&!t.granularity){const e=r[t.fieldName]?.values().next().value||"year";r[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:n}}getUnusedGranularities(e,t){const{columns:s,rows:o,measures:i}=t,n=s.concat(o).concat(i).filter(t=>{const s=e[t.fieldName]?.type;return"date"===s||"datetime"===s}),r={};for(const t of n)r[t.fieldName]=new Set("date"===e[t.fieldName]?.type?this.dateGranularities:this.datetimeGranularities);for(const e of n)r[e.fieldName].delete(e.granularity||"month");return r}shouldKeepSortedColumn(e){const{sortedColumn:t}=e;if(!t)return!0;const s=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find(e=>e.id===t.measure)&&Le(s.columns,e.columns)}areDomainFieldsValid(e,t){const s=t.map(({fieldName:e,granularity:t})=>e+(t?`:${t}`:""));for(let t=0;t<e.length;t++)if(e[t].field!==s[t])return!1;return!0}}class j$ extends t.Component{static template="o-spreadsheet-PivotSpreadsheetSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:$$,Section:YV,SelectionInput:iz,Checkbox:hz,PivotDeferUpdate:k$,PivotTitleSection:q$};store;state;pivotSidePanelRef=t.useRef("pivotSidePanel");setup(){this.store=Av(Z$,this.props.pivotId),this.state=t.useState({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return(!this.store.isDirty||!this.state.rangeHasChanged)&&this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,"forceSheetReference")]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){const e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;const t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){const{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}}const Y$=new Jg;Y$.add("SPREADSHEET",{editor:j$});class X$ extends t.Component{static template="o-spreadsheet-PivotDesignPanel";static props={pivotId:String};static components={Section:YV,Checkbox:hz,NumberInput:OW};store;setup(){this.store=Av(Z$,this.props.pivotId,"neverDefer")}updatePivotStyleNumberProperty(e,t){const s=parseInt(e);this.store.update({style:{...this.pivotStyle,[t]:isNaN(s)?void 0:s}})}updatePivotStyleProperty(e,t){this.store.update({style:{...this.pivotStyle,[e]:t}})}get pivotStyle(){return this.env.model.getters.getPivotCoreDefinition(this.props.pivotId).style||{}}get defaultStyle(){return gp}}class K$ extends t.Component{static template="o-spreadsheet-PivotSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:$$,Section:YV,PivotDesignPanel:X$};state=t.useState({panel:"configuration"});panelContentRef=t.useRef("panelContent");scrollPositions={configuration:0,design:0};setup(){v$(this)}get sidePanelEditor(){const e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw new Error("pivotId does not correspond to a pivot.");return Y$.get(e.type).editor}get highlights(){return N$(this.env.model.getters,this.props.pivotId)}switchPanel(e){const t=this.panelContentRef.el;t&&(this.scrollPositions[this.state.panel]=t.scrollTop),this.state.panel=e}}class J$ extends t.Component{static template="o-spreadsheet-RemoveDuplicatesPanel";static components={ValidationMessages:MG,Section:YV,Checkbox:hz};static props={onCloseSidePanel:Function};state=t.useState({hasHeader:!1,columns:{}});setup(){this.updateColumns(),t.onWillUpdateProps(()=>this.updateColumns())}toggleHasHeader(){this.state.hasHeader=!this.state.hasHeader}toggleAllColumns(){const e=!this.isEveryColumnSelected;for(const t in this.state.columns)this.state.columns[t]=e}toggleColumn(e){this.state.columns[e]=!this.state.columns[e]}onRemoveDuplicates(){this.env.model.dispatch("REMOVE_DUPLICATES",{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()})}getColLabel(e){const t=parseInt(e);let s=Cs("Column %s",lt(t));if(this.state.hasHeader){const e=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSelectedZone().top,i=this.env.model.getters.getEvaluatedCell({sheetId:e,col:t,row:o});"empty"!==i.type&&(s+=` - ${i.value}`)}return s}get isEveryColumnSelected(){return Object.values(this.state.columns).every(e=>e)}get errorMessages(){const e=this.env.model.canDispatch("REMOVE_DUPLICATES",{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()}).reasons,t=new Set;for(const s of e)t.add(Zg.Errors[s]||Zg.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){const e=$t(this.env.model.getters.getSelectedZone());return Cs("%(row_count)s rows and %(column_count)s columns selected",{row_count:e.numberOfRows,column_count:e.numberOfCols})}get canConfirm(){return 0===this.errorMessages.length}updateColumns(){const e=this.env.model.getters.getSelectedZone(),t=this.state.columns,s={};for(let o=e.left;o<=e.right;o++)s[o]=!(o in t)||t[o];this.state.columns=s}getColsToAnalyze(){return Object.keys(this.state.columns).filter(e=>this.state.columns[e]).map(e=>parseInt(e))}}class Q$ extends t.Component{static template="o-spreadsheet-SettingsPanel";static components={Section:YV,ValidationMessages:MG,BadgeSelection:EW};static props={onCloseSidePanel:Function};loadedLocales=[];setup(){t.onWillStart(()=>this.loadLocales())}onLocaleChange(e){const t=this.loadedLocales.find(t=>t.code===e);t&&this.env.model.dispatch("UPDATE_LOCALE",{locale:t})}async loadLocales(){this.loadedLocales=(await this.env.loadLocales()).filter(e=>{const t=fh(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t}).sort((e,t)=>e.name.localeCompare(t.name))}get numberFormatPreview(){return zi(1234567.89,{format:"#,##0.00",locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){const e=this.env.model.getters.getLocale();return zi(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){const e=this.env.model.getters.getLocale();return zi(1.6,{format:Dh(e),locale:e})}get firstDayOfWeek(){const e=this.env.model.getters.getLocale().weekStart;return Li[e%7]}get currentLocale(){return this.env.model.getters.getLocale()}get supportedLocales(){const e=this.currentLocale,t=this.loadedLocales.find(t=>t.code===e.code);if(!t)return[...this.loadedLocales,e].sort((e,t)=>e.name.localeCompare(t.name));if(!Le(e,t)){const s=this.loadedLocales.indexOf(t),o=[...this.loadedLocales];return o[s]=e,o.sort((e,t)=>e.name.localeCompare(t.name)),o}return this.loadedLocales}}const eq={SplitIsDestructive:Cs("This will overwrite data in the subsequent columns. Split anyway?")};const tq=[{name:Cs("Detect automatically"),value:"auto"},{name:Cs("Custom separator"),value:"custom"},{name:Cs("Space"),value:" "},{name:Cs("Comma"),value:","},{name:Cs("Semicolon"),value:";"},{name:Cs("Line Break"),value:Q}];class sq extends t.Component{static template="o-spreadsheet-SplitIntoColumnsPanel";static components={ValidationMessages:MG,Section:YV,Checkbox:hz};static props={onCloseSidePanel:Function};state=t.useState({separatorValue:"auto",addNewColumns:!1,customSeparator:""});setup(){const e=Tv(zv);t.useEffect(e=>{"inactive"!==e&&this.props.onCloseSidePanel()},()=>[e.focusMode]),t.onMounted(()=>{e.activeComposer.stopEdition()})}onSeparatorChange(e){this.state.separatorValue=e}updateCustomSeparator(e){e.target&&(this.state.customSeparator=e.target.value)}updateAddNewColumnsCheckbox(e){this.state.addNewColumns=e}confirm(){(function(e,t,s){let o=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:s});return o.isCancelledBecause("SplitWillOverwriteContent")&&e.askConfirmation(eq.SplitIsDestructive,()=>{o=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:s,force:!0})}),o})(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){const e=this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(const s of e)switch(s){case"SplitWillOverwriteContent":case"EmptySplitSeparator":break;default:t.add(qg.Errors[s]||qg.Errors.Unexpected)}return Array.from(t)}get warningMessages(){const e=[];return this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes("SplitWillOverwriteContent")&&e.push(qg.Errors.SplitWillOverwriteContent),e}get separatorValue(){return"custom"===this.state.separatorValue?this.state.customSeparator:"auto"===this.state.separatorValue?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return tq}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}}function oq(e,t,s,o){e.resetTransform(),function(e,t,s,o){e.save();for(let i=0;i<5;i++)for(let n=0;n<5;n++)e.fillStyle=t.styles[i][n].fillColor||"#fff",e.fillRect(i*s,n*o,s,o);e.restore()}(e,t,s,o),function(e,t,s,o){e.save(),e.translate(0,.5),e.lineWidth=1;for(let i=0;i<5;i++)for(let n=0;n<5;n++){const r=t.borders[i][n];r.top&&(e.strokeStyle=r.top.color,e.beginPath(),e.moveTo(i*s,n*o),e.lineTo(i*s+s,n*o),e.stroke()),r.bottom&&(e.strokeStyle=r.bottom.color,e.beginPath(),e.moveTo(i*s,n*o+o),e.lineTo(i*s+s,n*o+o),e.stroke())}e.resetTransform(),e.translate(.5,0);for(let i=0;i<5;i++)for(let n=0;n<5;n++){const r=t.borders[i][n];r.left&&(e.strokeStyle=r.left.color,e.beginPath(),e.moveTo(i*s,n*o),e.lineTo(i*s,n*o+o),e.stroke()),r.right&&(e.strokeStyle=r.right.color,e.beginPath(),e.moveTo(i*s+s,n*o),e.lineTo(i*s+s,n*o+o+1),e.stroke())}e.restore()}(e,t,s,o),function(e,t,s,o){e.save(),e.translate(0,.5),e.lineWidth=1;const i=Math.floor(s/4),n=Math.floor(o/2);for(let r=0;r<5;r++)for(let a=0;a<5;a++)e.strokeStyle=t.styles[r][a].textColor||"#000",e.beginPath(),e.moveTo(r*s+i+1,a*o+n),e.lineTo(r*s+s-i,a*o+n),e.stroke();e.restore()}(e,t,s,o)}class iq extends t.Component{static template="o-spreadsheet-TableStylePreview";static components={MenuPopover:JL};static props={tableConfig:Object,tableStyle:Object,class:String,styleId:{type:String,optional:!0},selected:{type:Boolean,optional:!0},onClick:{type:Function,optional:!0}};canvasRef=t.useRef("canvas");menu=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});setup(){t.onWillUpdateProps(e=>{Le(this.props.tableConfig,e.tableConfig)&&Le(this.props.tableStyle,e.tableStyle)||this.drawTable(e)}),t.onMounted(()=>this.drawTable(this.props))}drawTable(e){const t=this.canvasRef.el.getContext("2d"),{width:s,height:o}=this.canvasRef.el.getBoundingClientRect();this.canvasRef.el.width=s,this.canvasRef.el.height=o;oq(t,ND(e.tableConfig,e.tableStyle,5,5),(s-1)/5,(o-1)/5)}onContextMenu(e){var t,s;this.props.styleId&&(this.menu.menuItems=(t=this.env,s=this.props.styleId,t.model.getters.isTableStyleEditable(s)?Sv([{id:"editTableStyle",name:Cs("Edit table style"),execute:e=>e.openSidePanel("TableStyleEditorPanel",{styleId:s}),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.EDIT"},{id:"deleteTableStyle",name:Cs("Delete table style"),execute:e=>e.model.dispatch("REMOVE_TABLE_STYLE",{tableStyleId:s}),icon:"o-spreadsheet-Icon.TRASH"}]):[]),this.menu.isOpen=!0,this.menu.anchorRect={x:e.clientX,y:e.clientY,width:0,height:0})}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get styleName(){return this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId).displayName:""}get isStyleEditable(){return!!this.props.styleId&&this.env.model.getters.isTableStyleEditable(this.props.styleId)}editTableStyle(){this.env.openSidePanel("TableStyleEditorPanel",{styleId:this.props.styleId})}}class nq extends t.Component{static template="o-spreadsheet-TableStylesPopover";static components={Popover:jL,TableStylePreview:iq};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0}};categories=qx;tableStyleListRef=t.useRef("tableStyleList");state=t.useState({selectedCategory:this.initialSelectedCategory});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!AN(this.tableStyleListRef.el,e)&&(this.props.closePopover(),e.hasClosedTableStylesPopover=!0)}get displayedStyles(){const e=this.env.model.getters.getTableStyles();return Object.keys(e).filter(t=>e[t].category===this.state.selectedCategory)}get initialSelectedCategory(){return this.props.selectedStyleId?this.env.model.getters.getTableStyle(this.props.selectedStyleId).category:"medium"}newTableStyle(){this.props.closePopover(),this.env.openSidePanel("TableStyleEditorPanel",{onStylePicked:this.props.onStylePicked})}}class rq extends t.Component{static template="o-spreadsheet-TableStylePicker";static components={TableStylesPopover:nq,TableStylePreview:iq};static props={table:Object};state=t.useState({popoverProps:void 0});getDisplayedTableStyles(){const e=this.env.model.getters.getTableStyles(),t=e[this.props.table.config.styleId].category,s=Object.keys(e).filter(s=>e[s].category===t),o=s.indexOf(this.props.table.config.styleId);if(-1===o)return o;const i=4*Math.floor(o/4);return s.slice(i)}onStylePicked(e){const t=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("UPDATE_TABLE",{sheetId:t,zone:this.props.table.range.zone,config:{styleId:e}}),this.closePopover()}onArrowButtonClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps)return void this.closePopover();const t=e.currentTarget,{bottom:s,right:o}=t.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:o,y:s,width:0,height:0},positioning:"top-right",verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}}class aq extends t.Component{static template="o-spreadsheet-TablePanel";static components={TableStylePicker:rq,SelectionInput:iz,ValidationMessages:MG,Checkbox:hz,Section:YV,NumberInput:OW};static props={onCloseSidePanel:Function,table:Object};state;setup(){const e=this.env.model.getters.getActiveSheetId();this.state=t.useState({tableZoneErrors:[],tableXc:this.env.model.getters.getRangeString(this.props.table.range,e),filtersEnabledIfPossible:this.props.table.config.hasFilters})}updateHasFilters(e){this.state.filtersEnabledIfPossible=e,this.updateTableConfig("hasFilters",e)}updateTableConfig(e,t){const s=this.env.model.getters.getActiveSheetId();return this.env.model.dispatch("UPDATE_TABLE",{sheetId:s,zone:this.props.table.range.zone,config:{[e]:t}})}updateHasHeaders(e){const t=e?1:0;this.updateNumberOfHeaders(t)}updateTableIsDynamic(e){const t=e?"dynamic":"forceStatic";if(t===this.props.table.type)return;const s=this.env.model.getters.getTable(FD(this.props.table));if(!s)return;const o=this.env.model.getters.getActiveSheetId(),i=this.env.model.dispatch("UPDATE_TABLE",{sheetId:o,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(s.range),tableType:t}),n=this.env.model.getters.getCoreTable(FD(this.props.table));if(i.isSuccessful&&n){const e=n.range;this.state.tableXc=this.env.model.getters.getRangeString(e,o),this.state.tableZoneErrors=[]}}onChangeNumberOfHeaders(e){const t=parseInt(e);this.updateNumberOfHeaders(t)}updateNumberOfHeaders(e){const t=e>0&&(this.tableConfig.hasFilters||this.state.filtersEnabledIfPossible);return this.env.model.dispatch("UPDATE_TABLE",{sheetId:this.env.model.getters.getActiveSheetId(),zone:this.props.table.range.zone,config:{numberOfHeaders:e,hasFilters:t}})}onRangeChanged(e){const t=this.env.model.getters.getActiveSheetId();this.state.tableXc=e[0];const s=this.env.model.getters.getRangeFromSheetXC(t,this.state.tableXc);this.state.tableZoneErrors=this.env.model.canDispatch("UPDATE_TABLE",{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromXc(t,this.state.tableXc),tableType:this.getNewTableType(s.zone)}).reasons}onRangeConfirmed(){const e=this.env.model.getters.getActiveSheetId();let t=this.env.model.getters.getRangeFromSheetXC(e,this.state.tableXc);if(1===ss(t.zone)){const s=this.env.model.getters.getContiguousZone(e,t.zone);t=this.env.model.getters.getRangeFromZone(e,s)}const s=t.zone,o=this.props.table.range.zone,i=s.top===o.top&&s.left===o.left?"RESIZE_TABLE":"UPDATE_TABLE",n=this.env.model.dispatch(i,{sheetId:e,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(t),tableType:this.getNewTableType(t.zone)}),r={sheetId:e,col:t.zone.left,row:t.zone.top},a=this.env.model.getters.getCoreTable(r);if(n.isSuccessful&&a){const t=FD(a);this.env.model.selection.selectZone({zone:Jt(t),cell:t});const s=a.range;this.state.tableXc=this.env.model.getters.getRangeString(s,e)}}deleteTable(){const e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("REMOVE_TABLE",{sheetId:e,target:[this.props.table.range.zone]})}getNewTableType(e){if("forceStatic"===this.props.table.type)return"forceStatic";const t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.canCreateDynamicTableOnZones(t,[e])?"dynamic":"static"}get tableConfig(){return this.props.table.config}get errorMessages(){return(this.state.tableZoneErrors||[]).map(e=>Yg.Errors[e]||Yg.Errors.Unexpected)}getCheckboxLabel(e){return Yg.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:Yg.Tooltips.filterWithoutHeader}get canBeDynamic(){const e=this.env.model.getters.getActiveSheetId();return"dynamic"===this.props.table.type||this.env.model.getters.canCreateDynamicTableOnZones(e,[this.props.table.range.zone])}get dynamicTableTooltip(){return Yg.Tooltips.isDynamic}}const lq="#3C78D8";class cq extends t.Component{static template="o-spreadsheet-TableStyleEditorPanel";static components={Section:YV,RoundColorPicker:XV,TableStylePreview:iq};static props={onCloseSidePanel:Function,onStylePicked:{type:Function,optional:!0},styleId:{type:String,optional:!0}};state=t.useState(this.getInitialState());setup(){t.useExternalListener(window,"click",()=>this.state.pickerOpened=!1)}getInitialState(){const e=this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId):null;return{pickerOpened:!1,primaryColor:e?.primaryColor||lq,selectedTemplateName:e?.templateName||"lightColoredText",styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=Xv(e)?e:lq,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){const e=this.props.styleId||this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch("CREATE_TABLE_STYLE",{tableStyleId:e,tableStyleName:this.state.styleName,templateName:this.state.selectedTemplateName,primaryColor:this.state.primaryColor}),this.props.onStylePicked?.(e),this.props.onCloseSidePanel()}onCancel(){this.props.onCloseSidePanel()}onDelete(){this.props.styleId&&(this.env.model.dispatch("REMOVE_TABLE_STYLE",{tableStyleId:this.props.styleId}),this.props.onCloseSidePanel())}get colorPreviewStyle(){return JF({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(hR).filter(e=>"none"!==e)}get previewTableConfig(){return{bandedColumns:!1,bandedRows:!0,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,totalRow:!0,hasFilters:!0,styleId:""}}get selectedStyle(){return this.computeTableStyle(this.state.selectedTemplateName)}computeTableStyle(e){return dR(this.state.styleName,e,this.state.primaryColor)}}const hq=new Jg;hq.add("ConditionalFormatting",{title:Cs("Conditional formatting"),Body:C$}),hq.add("ChartPanel",{title:Cs("Chart"),Body:p$,computeState:(e,t)=>{const s=e.getSelectedFigureId(),o=s?e.getChartIdFromFigureId(s):t.chartId;return o&&e.isChartDefined(o)?{isOpen:!0,props:{chartId:o}}:{isOpen:!1}}}),hq.add("FindAndReplace",{title:Cs("Find and Replace"),Body:A$}),hq.add("SplitToColumns",{title:Cs("Split text into columns"),Body:sq}),hq.add("Settings",{title:Cs("Spreadsheet settings"),Body:Q$}),hq.add("RemoveDuplicates",{title:Cs("Remove duplicates"),Body:J$}),hq.add("DataValidation",{title:Cs("Data validation"),Body:E$}),hq.add("DataValidationEditor",{title:Cs("Data validation"),Body:I$}),hq.add("MoreFormats",{title:Cs("More formats"),Body:F$}),hq.add("TableSidePanel",{title:Cs("Edit table"),Body:aq,computeState:e=>{const t=e.getFirstTableInSelection();if(!t)return{isOpen:!1};return{isOpen:!0,props:{table:e.getCoreTable(FD(t))},key:t.id}}}),hq.add("TableStyleEditorPanel",{title:Cs("Create custom table style"),Body:cq,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??"new"})}),hq.add("PivotSidePanel",{title:(e,t)=>Cs("Pivot #%s",e.model.getters.getPivotFormulaId(t.pivotId)),Body:K$,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),hq.add("PivotMeasureDisplayPanel",{title:(e,t)=>{const s=e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id);return Cs('Measure "%s" options',s.displayName)},Body:M$,computeState:(e,t)=>{try{return e.getPivot(t.pivotId).getMeasure(t.measure.id),{isOpen:!0,props:t,key:`pivot_measure_display_${t.pivotId}_${t.measure.id}`}}catch(e){return{isOpen:!1}}}}),hq.add("CarouselPanel",{title:Cs("Carousel"),Body:vW,computeState:(e,t)=>{const s=t.figureId||e.getSelectedFigureId();return s&&e.doesCarouselExist(s)?{isOpen:!0,props:{figureId:s}}:{isOpen:!1}}});class dq{mutators=["setSmallThreshhold"];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}}const uq=350,gq=150;class pq extends Lv{mutators=["open","replace","toggle","close","changePanelSize","resetPanelSize","togglePinPanel","closeMainPanel","changeSpreadsheetWidth","toggleCollapsePanel"];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(dq);get isMainPanelOpen(){return!(!this.mainPanel||!this.mainPanel.componentTag)&&this.computeState(this.mainPanel).isOpen}get isSecondaryPanelOpen(){return!(!this.secondaryPanel||!this.secondaryPanel.componentTag)&&this.computeState(this.secondaryPanel).isOpen}get mainPanelProps(){return this.mainPanel?this.getPanelProps(this.mainPanel):void 0}get mainPanelKey(){return this.mainPanel?this.getPanelKey(this.mainPanel):void 0}get secondaryPanelProps(){return this.secondaryPanel?this.getPanelProps(this.secondaryPanel):void 0}get secondaryPanelKey(){return this.secondaryPanel?this.getPanelKey(this.secondaryPanel):void 0}get totalPanelSize(){return(this.mainPanel?.size||0)+(this.secondaryPanel?.size??0)}getPanelProps(e){const t=this.computeState(e);return t.isOpen?(e.currentPanelProps=t.props??e.currentPanelProps,t.props??{}):{}}getPanelKey(e){const t=this.computeState(e);if(t.isOpen)return t.key}open(e,t={}){if(this.screenWidthStore.isSmall)return;const s={currentPanelProps:t,componentTag:e,size:uq},o=this.computeState(s);if(!o.isOpen)return;if(!this.mainPanel||!this.mainPanel.isPinned||this.mainPanelKey===o.key)return void this._openPanel("mainPanel",s,o);const i=this.mainPanel.isCollapsed?uq:this.mainPanel.size;!this.secondaryPanel&&i+uq>this.availableWidth?this.get(kV).notifyUser({sticky:!1,type:"warning",text:Cs("The window is too small to display multiple side panels.")}):this._openPanel("secondaryPanel",s,o)}replace(e,t,s={}){const o={currentPanelProps:s,componentTag:e,size:uq},i=this.computeState(o);if(!i.isOpen)return;const n=()=>{this.mainPanel?.isCollapsed&&this.toggleCollapsePanel("mainPanel")},r=this.mainPanelKey===i.key,a=this.secondaryPanelKey===i.key;if(r&&this.secondaryPanel)return this.close(),void n();if(a)return this.closeMainPanel(),this.togglePinPanel(),void n();const l=this.mainPanelKey===t?"mainPanel":"secondaryPanel";this._openPanel(l,o,i)}_openPanel(e,t,s){const o=this[e];o&&t.componentTag!==o.componentTag&&o.currentPanelProps?.onCloseSidePanel?.(),this[e]={currentPanelProps:s.props??{},componentTag:t.componentTag,size:o?.size||uq,isCollapsed:o?.isCollapsed||!1,isPinned:!(!o||!("isPinned"in o))&&o.isPinned},this[e].isCollapsed&&this.toggleCollapsePanel(e)}toggle(e,t){const s=this.mainPanel?.isPinned?this.secondaryPanel:this.mainPanel;s&&e===s.componentTag?this.close():this.open(e,t)}close(){this.mainPanel?.isPinned?this.secondaryPanel&&(this.secondaryPanel.currentPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0):(this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=void 0)}closeMainPanel(){this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel||void 0,this.secondaryPanel=void 0}changePanelSize(e,t){const s=this[e];if(!s||"isCollapsed"in s&&s.isCollapsed)return;t=Math.max(t,uq);let o="mainPanel"===e?this.secondaryPanel?.size||0:this.mainPanel?.size||0;t>this.availableWidth-o&&("mainPanel"===e&&this.secondaryPanel&&(this.secondaryPanel.size=Math.max(this.availableWidth-t,uq),o=this.secondaryPanel.size),t=Math.max(this.availableWidth-o,uq)),s.size=t}resetPanelSize(e){this[e]&&(this[e].size=uq)}togglePinPanel(){this.mainPanel&&(this.mainPanel.isPinned=!this.mainPanel.isPinned,!this.mainPanel.isPinned&&this.secondaryPanel&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel,this.secondaryPanel=void 0))}toggleCollapsePanel(e){const t=this[e];t&&(t.isCollapsed?(t.isCollapsed=!1,this.changePanelSize(e,uq)):(t.isCollapsed=!0,t.size=45))}computeState({componentTag:e,currentPanelProps:t}){const s=hq.get(e).computeState,o=s?s(this.getters,t):{isOpen:!0,props:t};return o.isOpen?{...o,key:o.key||e}:o}changeSpreadsheetWidth(e){this.availableWidth=e-gq,this.secondaryPanel&&e-this.totalPanelSize<gq&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0),this.mainPanel&&e-this.totalPanelSize<gq&&(this.mainPanel.size=Math.max(e-gq,uq))}}class mq extends t.Component{static template="o-spreadsheet-TableResizer";static props={table:Object};state=t.useState({highlightZone:void 0});dragNDropGrid=yG(this.env);setup(){v$(this)}get containerStyle(){const e=this.props.table.range.zone,t={...e,left:e.right,top:e.bottom},s=this.env.model.getters.getVisibleRect(t);return 0===s.height||0===s.width?JF({display:"none"}):JF({top:s.y+s.height-6+"px",left:s.x+s.width-6+"px"})}onMouseDown(e){const t=this.props.table.range.zone,s={col:t.left,row:t.top};document.body.style.cursor="nwse-resize";const o=$N(this.env,e);this.dragNDropGrid.start(o,(e,t,o)=>{this.state.highlightZone={left:s.col,top:s.row,right:Math.max(e,s.col),bottom:Math.max(t,s.row)}},()=>{document.body.style.cursor="";const e=this.state.highlightZone;if(!e)return;const t=this.props.table.range.sheetId;this.env.model.dispatch("RESIZE_TABLE",{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0})}get highlights(){return this.state.highlightZone?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:"#777",noFill:!0}]:[]}}const fq={ROW:vG,COL:dG,CELL:sB,GROUP_HEADERS:mG,UNGROUP_HEADERS:fG};class vq extends t.Component{static template="o-spreadsheet-Grid";static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:AG,GridOverlay:BG,GridPopover:GG,HeadersOverlay:YG,MenuPopover:JL,Autofill:IG,ClientTag:EG,Highlight:sW,Popover:jL,VerticalScrollBar:rW,HorizontalScrollBar:nW,TableResizer:mq,Selection:aW};HEADER_HEIGHT=O;HEADER_WIDTH=F;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=yG(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=Tv(NV),this.menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.hoveredCell=Tv(nV),this.composerFocusStore=Tv(zv),this.DOMFocusableElementStore=Tv(mV),this.sidePanel=Tv(pq),this.paintFormatStore=Tv(VG),this.clientFocusStore=Tv(SG),Tv(bG),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),t.useExternalListener(document.body,"cut",this.copy.bind(this,!0)),t.useExternalListener(document.body,"copy",this.copy.bind(this,!1)),t.useExternalListener(document.body,"paste",this.paste),t.onMounted(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),KG("canvas",this.env.model,()=>this.env.model.getters.getSheetViewDimensionWithHeaders()),this.onMouseWheel=QG((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=Tv(aV),t.useEffect((e,t)=>{e||t||this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),JG(this.gridRef,this.moveCanvas.bind(this),()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},()=>{const{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){const e=this.env.model.getters.getScrollBarWidth();return JF({top:"26px",left:"48px",height:`calc(100% - ${O+e}px)`,width:`calc(100% - ${F+e}px)`})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>{this.env.model.getters.getActiveCell().type===Xd.empty?this.onComposerCellFocused():this.onComposerContentFocused()},Tab:()=>this.env.model.selection.moveAnchorCell("right",1),"Shift+Tab":()=>this.env.model.selection.moveAnchorCell("left",1),F2:()=>{this.env.model.getters.getActiveCell().type===Xd.empty?this.onComposerCellFocused():this.onComposerContentFocused()},Delete:()=>{this.env.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch("CLEAN_CLIPBOARD_HIGHLIGHT")},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch("REQUEST_UNDO"),"Ctrl+Y":()=>this.env.model.dispatch("REQUEST_REDO"),F4:()=>this.env.model.dispatch("REQUEST_REDO"),"Ctrl+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>Kz(this.env),"Alt+=":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:s}=this.env.model.getters.getSelection(),o=this.env.model.getters.getAutomaticSums(e,t,s.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&o.length<=1){const t=o[0]?.zone,s=t?this.env.model.getters.zoneToXC(e,o[0].zone):"",i=`=SUM(${s})`;this.onComposerCellFocused(i,{start:5,end:5+s.length})}else this.env.model.dispatch("SUM_SELECTION")},"Alt+Enter":()=>{const e=this.env.model.getters.getActiveCell();e.link&&vv(e.link,this.env)},"Ctrl+Home":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:s}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,s)},"Ctrl+End":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),s=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,s)},"Shift+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},s=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:s,zone:t})},"Ctrl+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},s=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:s,zone:t})},"Ctrl+D":async()=>this.env.model.dispatch("COPY_PASTE_CELLS_ABOVE"),"Ctrl+R":async()=>this.env.model.dispatch("COPY_PASTE_CELLS_ON_LEFT"),"Ctrl+H":()=>this.sidePanel.open("FindAndReplace",{}),"Ctrl+F":()=>this.sidePanel.open("FindAndReplace",{}),"Ctrl+Shift+E":()=>this.setHorizontalAlign("center"),"Ctrl+Shift+L":()=>this.setHorizontalAlign("left"),"Ctrl+Shift+R":()=>this.setHorizontalAlign("right"),"Ctrl+Shift+V":()=>$z(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{const e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),s=1===this.env.model.getters.getSelectedZones().length,o=e.size>0&&s,i=t.size>0&&s;o&&!i?Yz(this.env):i&&!o&&jz(this.env)},"Ctrl+Alt+-":()=>{const e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&0===t.length?this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:"COL",elements:e}):t.length>0&&0===e.length&&this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:"ROW",elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"Shift+PageUp":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PageDown:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PageUp:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"Ctrl+K":()=>Jz(this.env),"Alt+Shift+ArrowRight":()=>this.processHeaderGroupingKey("right"),"Alt+Shift+ArrowLeft":()=>this.processHeaderGroupingKey("left"),"Alt+Shift+ArrowUp":()=>this.processHeaderGroupingKey("up"),"Alt+Shift+ArrowDown":()=>this.processHeaderGroupingKey("down")};focusDefaultElement(){this.env.model.getters.getSelectedFigureId()||"inactive"!==this.composerFocusStore.activeComposer.editionMode||this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw new Error("Grid el is not defined.");return this.gridRef.el}getAutofillPosition(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{x:t.x+t.width-4,y:t.y+t.height-4}}get isAutofillVisible(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(0===t.width||0===t.height)}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t-F,height:e-O,gridOffsetX:F,gridOffsetY:O})}moveCanvas(e,t){const{scrollX:s,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s+e,offsetY:o+t})}processSpaceKey(e){this.env.model.getters.hasBooleanValidationInZones(this.env.model.getters.getSelectedZones())&&(e.preventDefault(),e.stopPropagation(),this.env.model.dispatch("TOGGLE_CHECKBOX",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()}))}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}get focusedClients(){return this.clientFocusStore.focusedClients}getGridRect(){const e=this.env.model.getters.getViewportZoomLevel(),{width:t,height:s}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{...ON(this.gridRef),width:t*e,height:s*e}}onCellClicked(e,t,s,o){if(o.ev.preventDefault(),"editing"===this.composerFocusStore.activeComposer.editionMode&&this.composerFocusStore.activeComposer.stopEdition(),s.expandZone?this.env.model.selection.setAnchorCorner(e,t):s.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t),this.env.isMobile())return;let i=e,n=t;this.dragNDropGrid.start(o,(e,t,s)=>{s.preventDefault(),(e!==i&&-1!==e||t!==n&&-1!==t)&&(i=-1===e?i:e,n=-1===t?n:t,this.env.model.selection.setAnchorCorner(i,n))},()=>{this.env.model.selection.commitSelection(),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){const s=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:s,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:s,col:e,row:t}).type===Xd.empty?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),vV(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){const t=LN(e),s=this.keyDownMapping[t];if(s)return e.preventDefault(),e.stopPropagation(),void s();" "!==t?e.key.startsWith("Arrow")&&this.processArrows(e):this.processSpaceKey(e)}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:s,top:o}=t;let i="CELL";this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(s)?i="COL":this.env.model.getters.getActiveRows().has(o)&&(i="ROW");const{x:n,y:r,width:a}=this.env.model.getters.getVisibleRectWithZoom(t),l=this.getGridRect();this.toggleContextMenu(i,l.x+n+a,l.y+r)}onCellRightClicked(e,t,{x:s,y:o}){const i=this.env.model.getters.getSelectedZones();let n="CELL";Gt(e,t,i[i.length-1])?this.env.model.getters.getActiveCols().has(e)?n="COL":this.env.model.getters.getActiveRows().has(t)&&(n="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(n,s,o)}toggleContextMenu(e,t,s){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.anchorRect={x:t,y:s,width:0,height:0},this.menuState.menuItems=fq[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement))return;if("inactive"!==this.composerFocusStore.activeComposer.editionMode)return;e?MH(this.env):this.env.model.dispatch("COPY");const s=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(s),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();const t=e.clipboardData;if(!t)return;const s=[...t.files]?.find(e=>eP.includes(e.type)),o={content:{[QF.PlainText]:t?.getData(QF.PlainText),[QF.Html]:t?.getData(QF.Html)}};s&&(o.content[s.type]=s);const i=this.env.model.getters.getSelectedZones(),n=this.env.model.getters.isCutOperation(),r=this.env.model.getters.getClipboardId(),a=iP(o.content),l=a.data?.clipboardId;r===l?Hz(this.env,i):await Uz(this.env,i,a),n&&await this.env.clipboard.write({[QF.PlainText]:""})}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(1!==this.env.model.getters.getSelectedZones().length)return;const t=this.env.model.getters.getActiveRows().size>0,s=this.env.model.getters.getActiveCols().size>0;s&&t?this.processHeaderGroupingEventOnWholeSheet(e):s?this.processHeaderGroupingEventOnHeaders(e,"COL"):t?this.processHeaderGroupingEventOnHeaders(e,"ROW"):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){const s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSelectedZone(),i="COL"===t?o.left:o.top,n="COL"===t?o.right:o.bottom;switch(e){case"right":this.env.model.dispatch("GROUP_HEADERS",{sheetId:s,dimension:t,start:i,end:n});break;case"left":this.env.model.dispatch("UNGROUP_HEADERS",{sheetId:s,dimension:t,start:i,end:n});break;case"down":this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:s,dimension:t,zone:o});break;case"up":this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:s,dimension:t,zone:o})}}processHeaderGroupingEventOnWholeSheet(e){const t=this.env.model.getters.getActiveSheetId();"up"===e?(this.env.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"ROW"}),this.env.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"COL"})):"down"===e&&(this.env.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"ROW"}),this.env.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"COL"}))}processHeaderGroupingEventOnGrid(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getSelectedZone();switch(e){case"down":this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"ROW",zone:s}),this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"COL",zone:s});break;case"up":this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"ROW",zone:s}),this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"COL",zone:s});break;case"right":{const{x:e,y:t,width:o}=this.env.model.getters.getVisibleRectWithZoom(s),i=this.getGridRect();this.toggleContextMenu("GROUP_HEADERS",e+o+i.x,t+i.y);break}case"left":{if(!PH(this.env,"COL")&&!PH(this.env,"ROW"))return;const{x:e,y:t,width:o}=this.env.model.getters.getVisibleRectWithZoom(s),i=this.getGridRect();this.toggleContextMenu("UNGROUP_HEADERS",e+o+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:"cellFocus"})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:"contentFocus"})}get staticTables(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(MD)}get displaySelectionHandler(){return this.env.isMobile()&&"inactive"===this.composerFocusStore.activeComposer.editionMode}}function bq(e,t){const s=`"${t?`${e.name}:${t}`:e.name}"`,o=e.string!==e.name?e.string+s:s;return{text:s,description:e.string+(e.help?` (${e.help})`:""),htmlContent:[{value:s,color:ae.STRING}],fuzzySearchKey:o}}function Sq(e){const t=e.functionContext?.args[0];if(t&&["STRING","NUMBER"].includes(t.type))return t.value}const yq=new Jg;yq.add("SPREADSHEET",!1);class Cq extends t.Component{static template="o-spreadsheet-ClickableCellSortIcon";static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=Tv(zG)}get style(){const e=this.env.model.getters.getCellComputedStyle(this.props.position);return JF({color:e.textColor||I,"background-color":this.getBackgroundColor(e)})}get verticalJustifyClass(){switch(this.env.model.getters.getCellComputedStyle(this.props.position).verticalAlign){case"top":return"justify-content-start";case"middle":return"justify-content-center";default:return"justify-content-end"}}getBackgroundColor(e){const t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?function(e,t){const s=tb(t),o=tb(e),i=s.a+o.a*(1-s.a);return eb({r:Math.round((s.r*s.a+o.r*o.a*(1-s.a))/i),g:Math.round((s.g*s.a+o.g*o.a*(1-s.a))/i),b:Math.round((s.b*s.a+o.b*o.a*(1-s.a))/i),a:i})}(e.fillColor||"#FFFFFF",t):e.fillColor||"#FFFFFF"}}class Iq extends t.Component{static template="o-spreadsheet-FullScreenFigure";static props={};static components={ChartFigure:tV};fullScreenFigureStore;ref=t.useRef("fullScreenFigure");spreadsheetRect=ZL();figureRegistry=oV;setup(){this.fullScreenFigureStore=Tv(GL);const e=Tv(VS);let s;t.onWillUpdateProps(()=>{s!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+"-fullscreen"),s=this.figureUI?.id}),t.useEffect(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){"Escape"===e.key&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return oV.get(this.figureUI.tag).Component}}class wq extends t.Component{static template="o_spreadsheet.PivotHTMLRenderer";static components={Checkbox:hz};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=t.useState({showMissingValuesOnly:!1});setup(){const e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;const e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){const t=this.pivot.getExpandedTableStructure().rows,s=[...t[e].values];if(s.length<=1)return[e];s.pop();const o=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(s));return[e].concat(this.addRecursiveRow(o))}buildColumnsMissing(e){const t=[];for(const e of this.data.columns){const s=[];for(const t in e)for(let o=0;o<e[t].span;o++)s.push(parseInt(t,10));t.push(s)}for(let s=t[t.length-1].length;s>=0;s--)if(!e.includes(s))for(const e of t)e.splice(s,1);const s=[];for(const e in t){const o=[];let i,n=1;for(let s=0;s<t[e].length;s++)i!==t[e][s]?(void 0!==i&&o.push(Object.assign({},this.data.columns[e][i],{span:n})),i=t[e][s],n=1):n++;void 0!==i&&o.push(Object.assign({},this.data.columns[e][i],{span:n})),s.push(o)}return s}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){const s=e.map(()=>[]);for(const o of t)for(const t in e)s[t].push(this.data.values[e[t]][o]);return s}getColumnsIndexes(){const e=new Set;for(let t=0;t<this.data.columns.length;t++){const s=[];for(let e=0;e<this.data.columns[t].length;e++)for(let o=0;o<this.data.columns[t][e].span;o++)s.push(this.data.columns[t][e]);for(let t=0;t<s.length;t++)s[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++){this.data.values[t].find(e=>e.isMissing)&&e.add(t)}return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){const e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(const s of this.data.values)s[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){const s=[];for(const o of t.columns){const t=[];for(const s of o){const o=[];for(let e=0;e<s.fields.length;e++)o.push({value:s.fields[e]},{value:s.values[e]});const i=this.pivot.parseArgsToPivotDomain(o),n=this.env.model.getters.getLocale();if("measure"===i.at(-1)?.field){const{value:o,format:r}=this.pivot.getPivotMeasureValue(Do(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Ep(e,i).join(",")})`,value:zi(o,{format:r,locale:n}),span:s.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{const{value:o,format:r}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Ep(e,i).join(",")})`,value:zi(o,{format:r,locale:n}),span:s.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}s.push(t)}const o=s[s.length-1];return s[s.length-1]=o.map(e=>(e.isMissing||(e.style="color: #756f6f;"),e)),s}_buildRowHeaders(e,t){const s=[];for(const o of t.rows){const t=[];for(let e=0;e<o.fields.length;e++)t.push({value:o.fields[e]},{value:o.values[e]});const i=this.pivot.parseArgsToPivotDomain(t),{value:n,format:r}=this.pivot.getPivotHeaderValueAndFormat(i),a=this.env.model.getters.getLocale(),l={formula:`=PIVOT.HEADER(${Ep(e,i).join(",")})`,value:zi(n,{format:r,locale:a}),isMissing:!this.tracker?.isHeaderPresent(i)};o.indent>1&&(l.style=`padding-left: ${o.indent-10}px`),s.push(l)}return s}_buildValues(e,t){const s=[];for(const o of t.columns.at(-1)||[]){const i=[],n=Do(o.values[o.values.length-1]);for(const s of t.rows){const t=[];for(let e=0;e<s.fields.length;e++)t.push({value:s.fields[e]},{value:s.values[e]});for(let e=0;e<o.fields.length-1;e++)t.push({value:o.fields[e]},{value:o.values[e]});const r=this.pivot.parseArgsToPivotDomain(t),{value:a,format:l}=this.pivot.getPivotCellValueAndFormat(n,r),c=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${Ep(e,r,n).join(",")})`,value:zi(a,{format:l,locale:c}),isMissing:!this.tracker?.isValuePresent(n,r)})}s.push(i)}return s}}class Eq{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,s="copyPaste"){}paste(e,t,s){}isPasteAllowed(e,t,s,o){return"Success"}isCutAllowed(e){return"Success"}getPasteTarget(e,t,s,o){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}}class xq extends Eq{copy(e,t,s="copyPaste"){}pasteFromCopy(e,t,s,o){if(1===t.length)for(const i of oP(t,s))this.pasteZone(e,i.left,i.top,s,o);else for(const i of yt(t))for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++)this.pasteZone(e,t,n,s,o)}pasteZone(e,t,s,o,i){}}class Rq extends xq{isCutAllowed(e){return 1!==e.zones.length?"WrongCutSelection":"Success"}copy(e,t,s="copyPaste"){const o=e.sheetId,{clippedZones:i,rowsIndexes:n,columnsIndexes:r}=e,a=[],l=1===n.length&&1===r.length;for(const t of n){const i=[];for(const a of r){const c={col:a,row:t,sheetId:o};let h=this.getters.getCell(c);const d=this.getters.getEvaluatedCell(c),u=this.getters.getPivotIdFromPosition(c),g=this.getters.getArrayFormulaSpreadingOn(c);if("shiftCells"!==s&&u&&g){const t=this.getters.getSpreadZone(g);if((!Le(g,c)||!l)&&t&&!e.zones.some(e=>Wt(t,e))){const e=this.getters.getPivotCellFromPosition(c),t=Rp(this.getters.getPivotFormulaId(u),e);h={id:h?.id||"",format:h?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if("shiftCells"!==s&&g&&!Le(g,c)){const e=n.includes(g.row)&&r.includes(g.col)?"":zi(d.value,{locale:this.getters.getLocale()});h={id:h?.id||"",format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:h?.content??"",format:h?.format,tokens:h?.isFormula?h.compiledFormula.tokens.map(({value:e,type:t})=>({value:e,type:t})):[],border:this.getters.getCellBorder(c)||void 0,evaluatedCell:d,position:c})}a.push(i)}return{cells:a,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,s,o){if(!s.cells)return"Success";if(o?.isCutOperation&&void 0!==o?.pasteOption)return"WrongPasteOption";if(t.length>1&&(s.cells.length>1||s.cells[0].length>1))return"WrongPasteSelection";const i=s.cells.length,n=s.cells[0].length;for(const o of oP(t,s.cells))if(this.getters.doesIntersectMerge(e,o)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*n!==1))return"WillRemoveExistingMerge";return"Success"}paste(e,t,s){const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t,s):this.pasteFromCopy(i,o,t.cells,s)}getPasteTarget(e,t,s,o){const i=s.cells[0].length,n=s.cells.length;return o?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+n-1}]}:1===i&&1===n?{zones:[],sheetId:e}:{sheetId:e,zones:oP(t,s.cells)}}pasteFromCut(e,t,s,o){this.clearClippedZones(s);const i=t[0];this.pasteZone(e,i.left,i.top,s.cells,o)}clearClippedZones(e){this.dispatch("CLEAR_CELLS",{sheetId:e.sheetId,target:e.zones}),this.dispatch("CLEAR_FORMATTING",{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){if(!a)continue;const r={col:t+o,row:s+n,sheetId:e};this.pasteCell(a,r,i)}}pasteCell(e,t,s){const{sheetId:o,col:i,row:n}=t,r=this.getters.getEvaluatedCell(t),a=e?.format||e.evaluatedCell.format;if("asValue"===s?.pasteOption)return void this.dispatch("UPDATE_CELL",{...t,content:e.evaluatedCell.value?.toString()||"",format:a});if("onlyFormat"===s?.pasteOption)return void this.dispatch("UPDATE_CELL",{...t,style:e?.style??null,format:a??r.format});let l=e?.content;e?.tokens&&e.tokens.length>0&&!s?.isCutOperation?l=this.getters.getTranslatedCellFormula(o,i-e.position.col,n-e.position.row,e.tokens):e?.tokens&&e.tokens.length>0&&(l=this.getters.getFormulaMovedInSheet(e.position.sheetId,o,e.tokens)),""!==l||e?.format||e?.style?this.dispatch("UPDATE_CELL",{...t,content:l,style:e?.style||null,format:e?.format}):r&&this.dispatch("CLEAR_CELL",t)}convertTextToClipboardData(e){const t=this.getters.getLocale(),s={cells:[]},o=[];let i=0;for(const[t,s]of e.replace(/\r/g,"").split("\n").entries())o.push(s.split("\t")),o[t].length>i&&(i=o[t].length);for(const e of o){const o=[];for(let s=0;s<i;s++){const i=yh(e[s]||"",t);o.push({content:i,evaluatedCell:{formattedValue:i}})}s.cells.push(o)}return s}}function Tq(e,t){for(let s=0;s<t.length;s++){const o=t[s].proposalValues;if(void 0===o||0===o.length)continue;const i=t=>{const i=t.functionContext;if(!i||i.parent.toUpperCase()!==e.toUpperCase()||i.argPosition!==s)return;const n=[];let r="";for(const{value:e,label:t}of o){switch(typeof e){case"string":r=`"${e}"`;break;case"number":r=e.toString();break;case"boolean":r=e?"TRUE":"FALSE"}n.push({text:r,description:t,htmlContent:[{value:r,color:"string"==typeof e?ae.STRING:ae.NUMBER}],fuzzySearchKey:r,alwaysExpanded:!0})}return n};PV.add(`${e}_function_${t[s].name}_argument_proposals`,{sequence:50,autoSelectFirstProposal:!0,selectProposal:Aq,getProposals:i})}}function Aq(e,t){let s=e.end;const o=e.end;["LEFT_PAREN","ARG_SEPARATOR"].includes(e.type)||(s=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}mP.add("data_cleanup",class extends Ur{allowDispatch(e){return"REMOVE_DUPLICATES"===e.type?this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique)):"Success"}handle(e){switch(e.type){case"REMOVE_DUPLICATES":this.removeDuplicates(e.columns,e.hasHeader);break;case"TRIM_WHITESPACE":this.trimWhitespace()}}removeDuplicates(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.getSelectedZone();t&&(o.top+=1);const i=this.getUniqueRowsIndexes(s,o.top,o.bottom,e),n=i.length;if(n===$t(o).numberOfRows)return void this.notifyRowsRemovedAndRemaining(0,n);const r=i.map(e=>({left:o.left,top:e,right:o.right,bottom:e})),a=new Rq(this.getters,this.dispatch),l=a.copy(tP(s,r),!1);if(!l)return;this.dispatch("CLEAR_CELLS",{target:[o],sheetId:s});const c={left:o.left,top:o.top,right:o.left,bottom:o.top};a.paste({zones:[c],sheetId:s},l,{isCutOperation:!1});const h={left:o.left,top:o.top-(t?1:0),right:o.right,bottom:o.top+n-1};this.selection.selectZone({cell:{col:h.left,row:h.top},zone:h});const d=o.bottom-o.top+1-n;this.notifyRowsRemovedAndRemaining(d,n)}getUniqueRowsIndexes(e,t,s,o){const i=new Map;for(const n of fe(t,s+1)){const t=o.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).value);!Object.values(i).some(e=>Le(e,t))&&(i[n]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:"info",text:Cs("%s duplicate rows found and removed.\n%s unique rows remain.",e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return 1!==this.getters.getSelectedZones().length?"MoreThanOneRangeSelected":"Success"}checkNoMergeInZone(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?"WillRemoveExistingMerge":"Success"}checkRangeContainsValues(e){const t=this.getters.getActiveSheetId(),s=this.getters.getSelectedZone();e.hasHeader&&(s.top+=1);return this.getters.getEvaluatedCellsInZone(t,s).every(e=>"empty"===e.type)?"EmptyTarget":"Success"}checkNoColumnProvided(e){return 0===e.columns.length?"NoColumnsProvided":"Success"}checkColumnsIncludedInZone(e){const t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?"ColumnsNotIncludedInZone":"Success"}checkColumnsAreUnique(e){return e.columns.length!==new Set(e.columns).size?"DuplicatesColumnsSelected":"Success"}trimWhitespace(){const e=yt(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId();let s=0;for(const{col:o,row:i}of e.map(Zt).flat()){const e=this.getters.getCell({col:o,row:i,sheetId:t});if(!e)continue;const n=Je(e.content);n!==e.content&&(s+=1,this.dispatch("UPDATE_CELL",{sheetId:t,col:o,row:i,content:n}))}const o=s?Cs("Trimmed whitespace from %s cells.",s):Cs("No selected cells had whitespace trimmed.");this.ui.notifyUI({type:"info",text:o,sticky:!1})}}),PV.add("dataValidation",{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(at(t))return[];if(!this.composer.currentEditedCell)return[];const s=this.composer.currentEditedCell,o=this.getters.getValidationRuleForCell(s);if(!o||"isValueInList"!==o.criterion.type&&"isValueInRange"!==o.criterion.type)return[];const i=this.composer.currentEditedCell.sheetId,n="isValueInRange"===o.criterion.type?this.getters.getDataValidationRangeValues(i,o.criterion):o.criterion.values.map(e=>({label:e,value:e}));if(!("chip"===o.criterion.displayStyle))return n.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));const r=o.criterion.colors;return n.map(e=>{const t=r?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:hb(t||y),backgroundColor:t||y,classes:["badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start"]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t),this.composer.stopEdition()}}),PV.add("functions",{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if("SYMBOL"!==e.type)return[];const t=e.value;if(!at(this.composer.currentContent))return[];const s=Object.entries(zf.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:s}])=>({text:e,description:s,htmlContent:V$(t,e,g,"o-semi-bold")})).sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text));return s},selectProposal(e,t){let s=e.end,o=e.end;["SYMBOL","FUNCTION"].includes(e.type)&&(s=e.start);const i=this.composer.currentTokens;t+="(";const n=i.map(e=>e.start).indexOf(e.start);if(n+1<i.length){const e=i[n+1];"LEFT_PAREN"===e?.type&&o++}this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}}),zf.getAll().forEach(e=>Tq(e.name,e.args)),PV.add("pivot_ids",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!["PIVOT.VALUE","PIVOT.HEADER","PIVOT"].includes(t.parent.toUpperCase())||0!==t.argPosition)return;const s=this.getters.getPivotIds();return s.includes(e.value)?void 0:s.map(e=>{const t=this.getters.getPivotCoreDefinition(e),s=`${this.getters.getPivotFormulaId(e)}`;return{text:s,description:t.name,htmlContent:[{value:s,color:ae.NUMBER}],fuzzySearchKey:s+t.name,alwaysExpanded:!0}}).filter(De)},selectProposal:Aq}),PV.add("pivot_measures",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if("PIVOT.VALUE"!==t?.parent.toUpperCase()||1!==t.argPosition)return[];const s=Sq(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return[];const i=this.getters.getPivot(o);return i.init(),i.isValid()?i.definition.measures.map(e=>{if("__count"===e.fieldName){const e='"__count"';return{text:e,description:Cs("Count"),htmlContent:[{value:e,color:ae.STRING}],fuzzySearchKey:Cs("Count")+e}}return function(e){const t=`"${e.id}"`,s=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:ae.STRING}],fuzzySearchKey:s}}(e)}).filter(De):[]},selectProposal:Aq}),PV.add("pivot_group_fields",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!function(e){const t=e.functionContext;return"PIVOT.VALUE"===t?.parent.toUpperCase()&&t.argPosition>=2&&t.argPosition%2==0}(e)&&!function(e){const t=e.functionContext;return"PIVOT.HEADER"===t?.parent.toUpperCase()&&t.argPosition>=1&&t.argPosition%2==1}(e))return;const s=Sq(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return;const i=this.getters.getPivot(o);i.init();const n=i.getFields(),{columns:r,rows:a}=i.definition;let l=t.args;"PIVOT.VALUE"===t?.parent.toUpperCase()?(l=l.filter((e,t)=>t%2==0),l=l.slice(1,t.argPosition)):l=l.filter((e,t)=>t%2==1);const c=l.map(e=>e?.value).filter(De),h=r.map(e=>e.nameWithGranularity),d=a.map(e=>e.nameWithGranularity),u=[];let g=["ARG_SEPARATOR","SPACE"].includes(e.type)?c.at(-1):c.at(-2);const p=yq.get(i.type);if(p&&g?.startsWith("#")&&(g=g.slice(1)),void 0===g&&(u.push(h[0]),u.push(d[0])),d.includes(g)){const e=d[d.indexOf(g)+1];u.push(e),u.push(h[0])}if(h.includes(g)){const e=h[h.indexOf(g)+1];u.push(e)}const m=u.filter(De);return m.map(e=>{const[t,s]=e.split(":"),o=n[t];return o?bq(o,s):void 0}).concat(m.map(e=>{if(!p)return;const t=e.split(":")[0],s=n[t];if(!s)return;const o=`"#${e}"`;return{text:o,description:Cs("%s (positional)",s.string)+(s.help?` (${s.help})`:""),htmlContent:[{value:o,color:ae.STRING}],fuzzySearchKey:s.string+o}})).filter(De)},selectProposal:Aq}),PV.add("pivot_group_values",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!e||!function(e){const t=e.functionContext;return"PIVOT.VALUE"===t?.parent.toUpperCase()&&t.argPosition>=2&&t.argPosition%2==1}(e)&&!function(e){const t=e.functionContext;return"PIVOT.HEADER"===t?.parent.toUpperCase()&&t.argPosition>=1&&t.argPosition%2==0}(e))return;const s=Sq(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return;const i=this.getters.getPivot(o);if(!i.isValid())return;const n=t.argPosition,r=e.functionContext?.args[n-1]?.value;if(!r)return;let a;try{a=i.definition.getDimension(r)}catch(e){return}return"month_number"===a.granularity?Object.values(ki).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:ae.NUMBER}]})):"quarter_number"===a.granularity?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:Cs("Quarter %s",e),htmlContent:[{value:`${e}`,color:ae.NUMBER}]})):"day_of_month"===a.granularity?fe(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ae.NUMBER}]})):"iso_week_number"===a.granularity?fe(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ae.NUMBER}]})):"day_of_week"===a.granularity?fe(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ae.NUMBER}]})):"hour_number"===a.granularity?fe(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ae.NUMBER}]})):"minute_number"===a.granularity?fe(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ae.NUMBER}]})):"second_number"===a.granularity?fe(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ae.NUMBER}]})):i.getPossibleFieldValues(a).map(({value:e,label:t})=>{const s="string"==typeof e,o=s?`"${e}"`:e.toString(),i=t===e?"":t;return{text:o,description:i,htmlContent:[{value:o,color:s?ae.STRING:ae.NUMBER}],fuzzySearchKey:o+i}})},selectProposal:Aq}),PV.add("sheet_names",{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return"SYMBOL"===e.type||"UNKNOWN"===e.type&&e.value.startsWith("'")?this.getters.getSheetIds().map(e=>{const t=ge(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith("'")?t:"'"+t}}):[]},selectProposal(e,t){const s=e.start,o=e.end;this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t+"!")}});const _q=new Jg;_q.add("link",{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,s)=>vv(t.model.getters.getEvaluatedCell(e).link,t,s),title:(e,t)=>{const s=t.getEvaluatedCell(e).link;return s?s.isExternal?Cs("Go to url: %(url)s",{url:s.url}):Cs("Go to %(label)s",{label:s.label}):""},sequence:5}),_q.add("dashboard_pivot_sorting",{condition:(e,t)=>{if(!t.isDashboard())return!1;const s=t.getPivotCellFromPosition(e);return JU(t,e)&&"MEASURE_HEADER"===s.type},execute:(e,t)=>{QU(t,e,function(e,t){return Dq[e.getPivotCellSortDirection(t)??"none"]}(t.model.getters,e))},component:Cq,componentProps:(e,t)=>({position:e,sortDirection:t.getPivotCellSortDirection(e)}),sequence:2});const Dq={none:"asc",asc:"desc",desc:"none"};AO.add("filter_icon",(e,t)=>{if(e.isFilterHeader(t)){const s=e.isFilterActive(t),o=Qv(e.getCellComputedStyle(t).fillColor||"#fff")<.45;return{type:"filter_icon",svg:tT(s,o,!1),hoverSvg:tT(s,o,!0),priority:3,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const s=t.getStore(aV),o=s.persistentCellPopover;o.isOpen&&o.col===e.col&&o.row===e.row&&"FilterMenu"===o.type?s.close():s.open(e,"FilterMenu")}}}});const Oq=new Jg;Oq.add("format_number_automatic",{...mB,id:"format_number_automatic",sequence:10}).add("format_number_plain_text",{...fB,id:"format_number_plain_text",sequence:15,separator:!0}).add("format_number_number",{...vB,id:"format_number_number",sequence:20}).add("format_number_percent",{...SB,id:"format_number_percent",sequence:30,separator:!1}).add("format_number_scientific",{...yB,id:"format_number_scientific",sequence:33,separator:!0}).add("format_number_currency",{...CB,id:"format_number_currency",sequence:40}).add("format_number_accounting",{...wB,id:"format_number_accounting",sequence:45}).add("format_number_currency_rounded",{...IB,id:"format_number_currency_rounded",sequence:50,separator:!0}).add("format_number_date",{...RB,id:"format_number_date",sequence:70}).add("format_number_time",{...TB,id:"format_number_time",sequence:80}).add("format_number_date_time",{...AB,id:"format_number_date_time",sequence:90}).add("format_number_duration",{..._B,id:"format_number_duration",sequence:100,separator:!0}).add("format_custom_currency",{...xB,id:"format_custom_currency",sequence:120}).add("format_custom_date",{...DB,id:"format_custom_date",sequence:130}).add("format_custom_number",{...OB,id:"format_custom_number",sequence:140});const Fq=je(e=>ji(e)?"date":e.includes("[$")?"currency":"number"),Pq={name:Cs("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[e=>{const t=function(e){const t=new Set(Oq.getAll().map(t=>"function"==typeof t.format?t.format(e):t.format)),s=new Map;for(const o of e.model.getters.getSheetIds()){const i=e.model.getters.getEvaluatedCells(o);for(const e in i){const o=i[e];if(o.format&&!s.has(o.format)&&!t.has(o.format)){const e=Fq(o.format);"date"!==e&&"currency"!==e||s.set(o.format,pB({descriptionValue:"currency"===e?1e3:EB,format:o.format,name:o.format}))}}}return[...s.values()]}(e).map(e=>({...e,sequence:110}));return t.length>0&&(t[t.length-1].separator=!0),[...Oq.getAll(),...t]}]};const Mq=new xz;Mq.add("file",{name:Cs("File"),sequence:10}).addChild("settings",["file"],{name:Cs("Settings"),sequence:200,execute:e=>e.openSidePanel("Settings"),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.COG"}).add("edit",{name:Cs("Edit"),sequence:20}).addChild("undo",["edit"],{...kH,sequence:10}).addChild("redo",["edit"],{...LH,sequence:20,separator:!0}).addChild("copy",["edit"],{...VH,sequence:30}).addChild("cut",["edit"],{...zH,sequence:40}).addChild("paste",["edit"],{...HH,sequence:50}).addChild("paste_special",["edit"],{...UH,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...BH,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{...GH,sequence:20}).addChild("edit_table",["edit"],{...sU,isVisible:eH,sequence:60}).addChild("find_and_replace",["edit"],{...WH,sequence:65,separator:!0}).addChild("delete",["edit"],{name:Cs("Delete"),icon:"o-spreadsheet-Icon.TRASH",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...$H,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...qH,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...YH,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{...QH,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...eU,sequence:50}).addChild("edit_unhide_columns",["edit"],{...hH,sequence:80}).addChild("edit_unhide_rows",["edit"],{...gH,sequence:80}).add("view",{name:Cs("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...pH,sequence:4}).addChild("freeze_panes",["view"],{...mH,sequence:5}).addChild("unfreeze_rows",["view","freeze_panes"],{...fH,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...vH,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...bH,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...SH,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...yH,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...CH,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...IH,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...wH,sequence:40}).addChild("group_headers",["view"],{name:Cs("Group"),sequence:15,separator:!0,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",isVisible:sH}).addChild("group_columns",["view","group_headers"],{...TH,sequence:5}).addChild("ungroup_columns",["view","group_headers"],{..._H,isVisible:e=>PH(e,"COL"),sequence:10}).addChild("group_rows",["view","group_headers"],{...AH,sequence:15}).addChild("ungroup_rows",["view","group_headers"],{...DH,isVisible:e=>PH(e,"ROW"),sequence:20}).addChild("show",["view"],{name:Cs("Show"),sequence:1,icon:"o-spreadsheet-Icon.SHOW"}).addChild("view_gridlines",["view","show"],{...EH,sequence:5}).addChild("view_formulas",["view","show"],{...RH,sequence:10}).addChild("zoom",["view"],{name:Cs("Zoom"),sequence:1,icon:"o-spreadsheet-Icon.ZOOM"}).addChild("view_irregularity_map",["view"],{...xH,sequence:40,separator:!0}).add("insert",{name:Cs("Insert"),sequence:40}).addChild("insert_row",["insert"],{...rU,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...lU,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...dU,sequence:20}).addChild("insert_column",["insert"],{...uU,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...pU,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...vU,sequence:20}).addChild("insert_cell",["insert"],{...bU,sequence:30}).addChild("insert_cell_down",["insert","insert_cell"],{...SU,name:Cs("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...yU,name:Cs("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...kU,sequence:40,separator:!0}).addChild("insert_chart",["insert"],{...CU,sequence:50}).addChild("insert_carousel",["insert"],{...IU,sequence:51}).addChild("insert_pivot",["insert"],{...wU,sequence:52}).addChild("insert_image",["insert"],{...EU,sequence:55}).addChild("insert_table",["insert"],{...xU,sequence:57}).addChild("insert_function",["insert"],{...RU,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...TU,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...AU,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{..._U,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...DU,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...OU,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...FU,sequence:50}).addChild("categories_function_list",["insert","insert_function"],()=>{const e=zf.content;return[...new Set(zf.getAll().filter(e=>!e.hidden).map(e=>e.category))].filter(De).sort().map((t,s)=>{const o=Object.keys(e).filter(s=>e[s].category===t&&!e[s].hidden);return{name:t,children:LU(o)}})}).addChild("insert_link",["insert"],{...PU,separator:!0,sequence:70}).addChild("insert_checkbox",["insert"],{...MU,sequence:80}).addChild("insert_dropdown",["insert"],{...NU,separator:!0,sequence:90}).add("format",{name:Cs("Format"),sequence:50}).addChild("format_number",["format"],{...Pq,name:Cs("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{...MB,sequence:20}).addChild("format_italic",["format"],{...NB,sequence:30}).addChild("format_underline",["format"],{...kB,sequence:40}).addChild("format_strikethrough",["format"],{...GB,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...WB,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...$B,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...ZB,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...jB,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...YB,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{...KB,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...JB,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{...QB,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...eG,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...sG,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...oG,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...iG,sequence:30}).addChild("format_cf",["format"],{...nG,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...rG,sequence:100,separator:!0}).add("data",{name:Cs("Data"),sequence:60}).addChild("sort_range",["data"],{...oB,sequence:10,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...iB,sequence:10}).addChild("sort_descending",["data","sort_range"],{...lB,sequence:20}).addChild("data_cleanup",["data"],{...nB,sequence:15}).addChild("remove_duplicates",["data","data_cleanup"],{...rB,sequence:10}).addChild("trim_whitespace",["data","data_cleanup"],{...aB,sequence:20}).addChild("split_to_columns",["data"],{...dB,sequence:20}).addChild("data_validation",["data"],{name:Cs("Data Validation"),execute:e=>{e.openSidePanel("DataValidation")},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.DATA_VALIDATION",sequence:30,separator:!0}).addChild("add_remove_data_filter",["data"],{...cB,sequence:40,separator:!0}).addChild("pivot_data_sources",["data"],e=>{const t=e.model.getters.getPivotIds().length;return e.model.getters.getPivotIds().map((s,o)=>{const i={get highlights(){return N$(e.model.getters,s)}};return{id:`item_pivot_${e.model.getters.getPivotFormulaId(s)}`,name:e.model.getters.getPivotDisplayName(s),sequence:50+o/t,isReadonlyAllowed:!0,execute:e=>e.openSidePanel("PivotSidePanel",{pivotId:s}),isEnabled:e=>!e.isSmall,onStartHover:e=>e.getStore(NV).register(i),onStopHover:e=>e.getStore(NV).unRegister(i),icon:"o-spreadsheet-Icon.PIVOT",separator:o===e.model.getters.getPivotIds().length-1,secondaryIcon:e=>e.model.getters.isPivotUnused(s)?"o-spreadsheet-Icon.UNUSED_PIVOT_WARNING":void 0}})}).addChild("reinsert_dynamic_pivot",["data"],uB).addChild("reinsert_static_pivot",["data"],gB),N.forEach(e=>{Mq.addChild(`zoom${e}`,["view","zoom"],function(e){return{name:Cs("%(zoom_percentage)s%",{zoom_percentage:e}),execute:t=>{t.model.dispatch("SET_ZOOM",{zoom:e/100})},isActive:t=>t.model.getters.getViewportZoomLevel()===e/100,isReadonlyAllowed:!0,sequence:e}}(e))});const Nq=[kq,function(e,t){return"target"in t&&Array.isArray(t.target)?{...he(t),target:e.getSelectedZones()}:t},Vq,function(e,t){return"ranges"in t?{...he(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}];function kq(e,t){return"sheetId"in t?{...he(t),sheetId:e.getActiveSheetId()}:t}function Lq(e,t){return"zone"in t?{...he(t),zone:e.getSelectedZone()}:t}function Vq(e,t){if(!("row"in t)||!("col"in t))return t;const{col:s,row:o}=e.getActivePosition();return{...he(t),col:s,row:o}}const zq=new Tr;function Hq(e,t){const s=e.getSelectedZone();return{...kq(e,t),elements:"COL"===t.dimension?fe(s.left,s.right+1):fe(s.top,s.bottom+1)}}function Uq(e,t){const s=e.getSelectedZone();return{...he(t),zone:s}}function Bq(e,t){const s=he(t),o=e.getSelectedZone(),{top:i,bottom:n,left:r,right:a}=o;return"cols"in s?s.cols=fe(r,a+1):"rows"in s&&(s.rows=fe(i,n+1)),s}function Gq(e,t){const s=e.getSelectedZone();return{...kq(e,t),start:"COL"===t.dimension?s.left:s.top,end:"COL"===t.dimension?s.right:s.bottom}}function Wq(e,t){let s=he(t);for(const t of Nq)s=t(e,s);return s}BF.add("UPDATE_CELL",Wq),BF.add("CLEAR_CELL",Wq),BF.add("CLEAR_CELLS",Wq),BF.add("DELETE_CONTENT",Wq),BF.add("ADD_MERGE",Wq),BF.add("REMOVE_MERGE",Wq),BF.add("SET_FORMATTING",Wq),BF.add("CLEAR_FORMATTING",Wq),BF.add("SET_BORDER",Wq),BF.add("CREATE_TABLE",Wq),BF.add("REMOVE_TABLE",Wq),BF.add("HIDE_SHEET",Wq),BF.add("ADD_COLUMNS_ROWS",function(e,t){const s=e.getActivePosition();return{...kq(e,t),base:"COL"===t.dimension?s.col:s.row}}),BF.add("REMOVE_COLUMNS_ROWS",Hq),BF.add("HIDE_COLUMNS_ROWS",Hq),BF.add("RESIZE_COLUMNS_ROWS",Hq),BF.add("CREATE_SHEET",function(e,t){const s=he(t);s.sheetId=zq.smallUuid();const o=t.name||e.getSheet(e.getActiveSheetId()).name,i=o.match(/(.+?)\d*$/)?.[1]||o;return s.name=e.getNextSheetName(i),s}),BF.add("CREATE_FIGURE",function(e,t){const s=Vq(e,kq(e,t));return s.figureId=zq.smallUuid(),s}),BF.add("CREATE_CHART",function(e,t){const s=zq.smallUuid();return{...kq(e,t),figureId:s,chartId:s}}),BF.add("CREATE_IMAGE",function(e,t){return{...kq(e,t),figureId:zq.smallUuid()}}),BF.add("GROUP_HEADERS",Gq),BF.add("UNGROUP_HEADERS",Gq),BF.add("UNFOLD_HEADER_GROUPS_IN_ZONE",Lq),BF.add("FOLD_HEADER_GROUPS_IN_ZONE",Lq),GF.add("PASTE",function(e,t){return{type:"REPEAT_PASTE",pasteOption:he(t.pasteOption),target:e.getSelectedZones()}}),GF.add("INSERT_CELL",Uq),GF.add("DELETE_CELL",Uq),GF.add("AUTORESIZE_COLUMNS",Bq),GF.add("AUTORESIZE_ROWS",Bq),GF.add("SORT_CELLS",function(e,t){const s=e.getSelectedZone();return{...kq(e,t),col:s.left,row:s.top,zone:s}}),GF.add("SUM_SELECTION",Wq),GF.add("SET_DECIMAL",Wq),GF.add("DELETE_UNFILTERED_CONTENT",Wq);const $q=new class extends Jg{mapping={};uuidGenerator=new Tr;replace(e,t){const s={...t,id:this.uuidGenerator.uuidv4()};return super.replace(e,s)}getAllOrdered(){return this.getAll().sort((e,t)=>e.sequence-t.sequence)}};class qq{fileStore;constructor(e){this.fileStore=e}async requestImage(){const e=await this.userImageUpload(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}async uploadFile(e){const t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}userImageUpload(){return new Promise((e,t)=>{const s=document.createElement("input");s.setAttribute("type","file"),s.setAttribute("accept","image/*"),s.addEventListener("change",async()=>{null===s.files||1!==s.files.length?t():e(s.files[0])}),s.click()})}getImageOriginalSize(e){return new Promise((t,s)=>{const o=new Image;o.addEventListener("load",()=>{const e={width:o.width,height:o.height};t(e)}),o.addEventListener("error",s),o.src=e})}}const Zq=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];class jq extends t.Component{static template="o-spreadsheet-RippleEffect";static props={x:String,y:String,color:String,opacity:Number,duration:Number,width:Number,height:Number,offsetY:Number,offsetX:Number,allowOverflow:Boolean,onAnimationEnd:Function,style:String};rippleRef=t.useRef("ripple");setup(){let e;t.onMounted(()=>{const t=this.rippleRef.el;t&&t.animate&&(e=t.animate(Zq,{duration:this.props.duration,easing:"ease-out"}),e.addEventListener("finish",this.props.onAnimationEnd))}),t.onWillUnmount(()=>{e?.removeEventListener("finish",this.props.onAnimationEnd)})}get rippleStyle(){const{x:e,y:t,width:s,height:o}=this.props;return JF({transform:"scale(0)",left:e,top:t,"margin-left":`${-s/2+(this.props.offsetX||0)}px`,"margin-top":`${-o/2+(this.props.offsetY||0)}px`,width:`${s}px`,height:`${o}px`,background:this.props.color,"border-radius":"100%",opacity:`${this.props.opacity}`})}}class Yq extends t.Component{static template="o-spreadsheet-Ripple";static props={color:{type:String,optional:!0},opacity:{type:Number,optional:!0},duration:{type:Number,optional:!0},ignoreClickPosition:{type:Boolean,optional:!0},width:{type:Number,optional:!0},height:{type:Number,optional:!0},offsetY:{type:Number,optional:!0},offsetX:{type:Number,optional:!0},allowOverflow:{type:Boolean,optional:!0},enabled:{type:Boolean,optional:!0},onAnimationEnd:{type:Function,optional:!0},slots:Object,class:{type:String,optional:!0}};static components={RippleEffect:jq};static defaultProps={color:"#aaaaaa",opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:""};childContainer=t.useRef("childContainer");state=t.useState({ripples:[]});currentId=1;onClick(e){if(!this.props.enabled)return;if(!this.childContainer.el)return;const t=this.getRippleChildRectInfo(),{x:s,y:o,width:i,height:n}=t,r=Math.max(i,n),a={x:e.clientX-s,y:e.clientY-o,width:this.props.width||2.85*r,height:this.props.height||2.85*r};this.state.ripples.push({rippleRect:a,id:this.currentId++})}getRippleStyle(){const e=this.childContainer.el;if(!e||1!==e.childElementCount||!e.firstElementChild)return"";const t=this.getRippleChildRectInfo();return JF({top:t.marginTop+"px",left:t.marginLeft+"px",width:t.width+"px",height:t.height+"px"})}getRippleChildRectInfo(){const e=this.childContainer.el;if(!e)throw new Error("No child container element found");if(1!==e.childElementCount||!e.firstElementChild){return{...FN(e),marginLeft:0,marginTop:0}}const t=e.firstElementChild,s=function(e){const t=window.getComputedStyle(e);return{top:parseInt(t.marginTop,10)||0,bottom:parseInt(t.marginBottom,10)||0,left:parseInt(t.marginLeft,10)||0,right:parseInt(t.marginRight,10)||0}}(t);return{...FN(t),marginLeft:s.left,marginTop:s.top}}removeRipple(e){const t=this.state.ripples.findIndex(t=>t.id===e);-1!==t&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){const t=this.state.ripples.find(t=>t.id===e)?.rippleRect;if(!t)throw new Error("Cannot find a ripple with the id "+e);return{color:this.props.color,opacity:this.props.opacity,duration:this.props.duration,x:this.props.ignoreClickPosition?"50%":t.x+"px",y:this.props.ignoreClickPosition?"50%":t.y+"px",width:t.width,height:t.height,offsetX:this.props.offsetX||0,offsetY:this.props.offsetY||0,allowOverflow:this.props.allowOverflow||!1,style:this.getRippleStyle(),onAnimationEnd:()=>this.removeRipple(e)}}}class Xq extends t.Component{static template="o-spreadsheet-BottomBarSheet";static props={sheetId:String,openContextMenu:Function,style:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0}};static components={Ripple:Yq,ColorPicker:jV};static defaultProps={onMouseDown:()=>{},style:""};state=t.useState({isEditing:!1,pickerOpened:!1});sheetDivRef=t.useRef("sheetDiv");sheetNameRef=t.useRef("sheetNameSpan");editionState="initializing";DOMFocusableElementStore;setup(){t.onPatched(()=>{this.sheetNameRef.el&&this.state.isEditing&&"initializing"===this.editionState&&(this.editionState="editing",this.focusInputAndSelectContent())}),this.DOMFocusableElementStore=Tv(mV),t.useExternalListener(window,"click",()=>this.state.pickerOpened=!1),t.useEffect(e=>{this.props.sheetId===e&&this.scrollToSheet()},()=>[this.env.model.getters.getActiveSheetId()])}focusInputAndSelectContent(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.sheetNameRef.el.focus();const e=window.getSelection();e&&this.sheetNameRef.el.firstChild&&e.setBaseAndExtent(this.sheetNameRef.el.firstChild,0,this.sheetNameRef.el.firstChild,this.sheetNameRef.el.textContent?.length||0)}scrollToSheet(){this.sheetDivRef.el?.scrollIntoView?.({behavior:"smooth",inline:"nearest"})}onFocusOut(){this.state.isEditing&&"initializing"!==this.editionState&&this.stopEdition()}onClick(){this.env.isMobile()&&this.activateSheet()}onMouseDown(e){this.env.isMobile()||(this.activateSheet(),this.props.onMouseDown(e))}activateSheet(){this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:this.props.sheetId}),this.scrollToSheet()}onDblClick(){this.env.model.getters.isReadonly()||this.startEdition()}onKeyDown(e){this.state.isEditing&&("Enter"===e.key&&(e.preventDefault(),this.stopEdition(),this.DOMFocusableElementStore.focus()),"Escape"===e.key&&(this.cancelEdition(),this.DOMFocusableElementStore.focus()))}onMouseEventSheetName(e){this.state.isEditing&&e.stopPropagation()}startEdition(){this.state.isEditing=!0,this.editionState="initializing"}stopEdition(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el.blur();const e=this.getInputContent()||"";!function(e,t,s,o){const i=e.model.dispatch("RENAME_SHEET",{sheetId:t,newName:s,oldName:e.model.getters.getSheetName(t)});i.reasons.includes("MissingSheetName")?e.raiseError(Cs("The sheet name cannot be empty."),o):i.reasons.includes("DuplicatedSheetName")?e.raiseError(Cs("A sheet with the name %s already exists. Please select another name.",s),o):i.reasons.includes("ForbiddenCharactersInSheetName")&&e.raiseError(Cs("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",j.join(" ")),o)}(this.env,this.props.sheetId,e,()=>this.startEdition())}cancelEdition(){this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el?.blur(),this.setInputContent(this.sheetName)}onIconClick(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}onContextMenu(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}getInputContent(){return this.sheetNameRef.el?.textContent}setInputContent(e){this.sheetNameRef.el&&(this.sheetNameRef.el.textContent=e)}onColorPicked(e){this.state.pickerOpened=!1,this.env.model.dispatch("COLOR_SHEET",{sheetId:this.props.sheetId,color:e})}get colorPickerAnchorRect(){return FN(this.sheetDivRef.el)}get contextMenuRegistry(){return function(e){const t=new xz;return t.add("delete",{...bz,sequence:10}).add("hide_sheet",{...Ez,sequence:20}).add("duplicate",{...Sz,sequence:30,separator:!0}).add("rename",{...yz(e),sequence:40}).add("change_color",{...Cz(e),sequence:50,separator:!0}).add("move_right",{...Iz,sequence:60}).add("move_left",{...wz,sequence:70}),t}({renameSheetCallback:()=>{this.scrollToSheet(),this.startEdition()},openSheetColorPickerCallback:()=>{this.state.pickerOpened=!0}})}get isSheetActive(){return this.env.model.getters.getActiveSheetId()===this.props.sheetId}get sheetName(){return this.env.model.getters.getSheetName(this.props.sheetId)}get sheetColorStyle(){return JF({background:this.env.model.getters.getSheet(this.props.sheetId).color||""})}}const Kq=[{name:Cs("Sum"),types:[Xd.number],compute:(e,t)=>Gr([[e]],t)},{name:Cs("Avg"),types:[Xd.number],compute:(e,t)=>ll([[e]],t)},{name:Cs("Min"),types:[Xd.number],compute:(e,t)=>ul([[e]],t).value},{name:Cs("Max"),types:[Xd.number],compute:(e,t)=>dl([[e]],t).value},{name:Cs("Count"),types:[Xd.number,Xd.text,Xd.boolean,Xd.error],compute:e=>hl([[e]])},{name:Cs("Count Numbers"),types:[Xd.number,Xd.text,Xd.boolean,Xd.error],compute:(e,t)=>cl([[e]],t)}];class Jq extends Lv{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.onDispose(()=>{this.model.selection.unobserve(this)})}handle(e){switch((Ar.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this.isDirty=!0),e.type){case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"GROUP_HEADERS":case"UNGROUP_HEADERS":case"ACTIVATE_SHEET":case"ACTIVATE_NEXT_SHEET":case"ACTIVATE_PREVIOUS_SHEET":case"EVALUATE_CELLS":case"UNDO":case"REDO":this.isDirty=!0}}finalize(){this.isDirty&&(this.isDirty=!1,this.statisticFnResults=this._computeStatisticFnResults())}handleEvent(){this.getters.isGridSelectionActive()&&(this.statisticFnResults=this._computeStatisticFnResults())}_computeStatisticFnResults(){const e=this.getters,t=e.getActiveSheetId(),s=[],o=yt(e.getSelectedZones(),[]),i=this.getters.getSheetSize(t).numberOfRows-1,n=this.getters.getSheetSize(t).numberOfCols-1;for(const r of o)for(let o=r.left;o<=(r.right??n);o++)for(let n=r.top;n<=(r.bottom??i);n++){if(e.isRowHidden(t,n)||e.isColHidden(t,o))continue;const i=e.getEvaluatedCell({sheetId:t,col:o,row:n});i.type!==Xd.empty&&s.push(i)}const r=e.getLocale(),a={},l=je(e=>{const t=e.split(",");return s.filter(e=>t.includes(e.type))});for(const e of Kq){let t;const s=l(e.types.sort().join(","));s.length&&(t=Me(()=>e.compute(s,r))),a[e.name]=t}return a}}class Qq extends t.Component{static template="o-spreadsheet-BottomBarStatistic";static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:Yq};selectedStatisticFn="";store;setup(){this.store=Tv(Jq),t.onWillUpdateProps(()=>{Object.values(this.store.statisticFnResults).every(e=>void 0===e)&&this.props.closeContextMenu()})}getSelectedStatistic(){if(!Object.values(this.store.statisticFnResults).every(e=>void 0===e))return""===this.selectedStatisticFn&&(this.selectedStatisticFn=Object.keys(this.store.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn)}listSelectionStatistics(e){const t=new xz;let s=0;for(const[e]of Object.entries(this.store.statisticFnResults))t.add(e,{name:()=>this.getComposedFnName(e),sequence:s,isReadonlyAllowed:!0,execute:()=>{this.selectedStatisticFn=e}}),s++;const o=e.currentTarget,{top:i,left:n,width:r}=o.getBoundingClientRect();this.props.openContextMenu(n+r,i,t)}getComposedFnName(e){const t=this.env.model.getters.getLocale(),s=this.store.statisticFnResults[e];return e+": "+(void 0!==s?zi(s(),{locale:t}):"__")}}class eZ extends t.Component{static template="o-spreadsheet-BottomBar";static props={onClick:Function};static components={MenuPopover:JL,Ripple:Yq,BottomBarSheet:Xq,BottomBarStatistic:Qq};bottomBarRef=t.useRef("bottomBar");sheetListRef=t.useRef("sheetList");dragAndDrop=KV();targetScroll=void 0;state=t.useState({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=t.useState({isOpen:!1,menuId:void 0,anchorRect:null,menuItems:[]});sheetList=this.getVisibleSheets();setup(){t.onWillUpdateProps(()=>{this.updateScrollState();const e=this.getVisibleSheets();Le(this.sheetList,e)||this.dragAndDrop.cancel(),this.sheetList=e})}clickAddSheet(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getSheetIds().findIndex(e=>e===t)+1,o=this.env.model.uuidGenerator.smallUuid(),i=this.env.model.getters.getNextSheetName(Cs("Sheet"));this.env.model.dispatch("CREATE_SHEET",{sheetId:o,position:s,name:i}),this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map(e=>{const t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}})}clickListSheets(e){const t=new xz,s=this.env.model.getters.getActiveSheetId();let o=0;for(const e of this.env.model.getters.getSheetIds()){const i=this.env.model.getters.getSheet(e);t.add(e,{name:i.name,sequence:o,isReadonlyAllowed:!0,textColor:i.isVisible?void 0:"#808080",execute:t=>{this.env.model.getters.isSheetVisible(e)||this.env.model.dispatch("SHOW_SHEET",{sheetId:e}),t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:s,sheetIdTo:e})},isEnabled:e=>!e.model.getters.isReadonly()||i.isVisible,icon:i.color?"o-spreadsheet-Icon.SMALL_DOT_RIGHT_ALIGN":void 0,iconColor:i.color}),o++}const i=e.currentTarget,{left:n}=i.getBoundingClientRect(),r=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(n,r,"listSheets",t)}openContextMenu(e,t,s,o){this.menuState.isOpen=!0,this.menuState.menuId=s,this.menuState.menuItems=o.getMenuItems(),this.menuState.anchorRect={x:e,y:t,width:0,height:0}}onSheetContextMenu(e,t,s){const o=s.currentTarget,{top:i,left:n}=o.getBoundingClientRect();s.closedMenuId!==e?this.openContextMenu(n,i,e,t):this.closeMenu()}closeMenu(){this.menuState.isOpen=!1,this.menuState.menuId=void 0,this.menuState.menuItems=[],this.menuState.anchorRect=null}closeContextMenuWithId(e){this.menuState.menuId===e&&this.closeMenu()}onWheel(e){this.targetScroll=void 0;e.currentTarget.scrollLeft+=.5*e.deltaY}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll+this.sheetListWidth;this.scrollSheetListTo(Math.min(this.sheetListMaxScroll,t))}updateScrollState(){this.state.isSheetListScrollableLeft=this.sheetListCurrentScroll>0,this.state.isSheetListScrollableRight=this.sheetListCurrentScroll<this.sheetListMaxScroll}scrollSheetListTo(e){this.sheetListRef.el&&(this.targetScroll=e,this.sheetListRef.el.scrollTo({top:0,left:e,behavior:"smooth"}))}onSheetMouseDown(e,t){if(0!==t.button||this.env.model.getters.isReadonly())return;if(this.closeMenu(),this.env.isMobile())return;const s=this.getVisibleSheets(),o=this.getSheetItemRects(),i=s.map((e,t)=>({id:e.id,size:o[t].width,position:o[t].x}));this.dragAndDrop.start("horizontal",{draggedItemId:e,initialMousePosition:t.clientX,items:i,scrollableContainerEl:this.sheetListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const s=t-this.getVisibleSheets().findIndex(t=>t.id===e);e&&0!==s&&this.env.model.dispatch("MOVE_SHEET",{sheetId:e,delta:s})}getSheetStyle(e){return this.dragAndDrop.itemsStyle[e]||""}getSheetItemRects(){return Array.from(this.bottomBarRef.el.querySelectorAll(".o-sheet")).map(e=>e.getBoundingClientRect()).map(e=>({x:e.x,width:e.width-1,y:e.y,height:e.height}))}get sheetListCurrentScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollLeft:0}get sheetListWidth(){return this.sheetListRef.el?this.sheetListRef.el.clientWidth:0}get sheetListMaxScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollWidth-this.sheetListRef.el.clientWidth:0}}class tZ extends Lv{_clickableCells=t.markRaw({});_registryItems=t.markRaw(_q.getAll().sort((e,t)=>e.sequence-t.sequence));handle(e){(Ar.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this._clickableCells=t.markRaw({}),this._registryItems=t.markRaw(_q.getAll().sort((e,t)=>e.sequence-t.sequence)))}getClickableItem(e){const{sheetId:t,col:s,row:o}=e,i=this._clickableCells,n=St(s,o);if(i[t]||(i[t]={}),!(n in i[t])){const s=this.findClickableItem(e);i[t][n]=s}return i[t][n]}findClickableItem(e){const t=this.getters;for(const s of this._registryItems)if(s.condition(e,t))return s}get clickableCells(){const e=[],t=this.getters;for(const s of this.getters.getVisibleCellPositions()){const o=this.getClickableItem(s);if(!o)continue;const i="function"==typeof o.title?o.title(s,t):o.title,n=this.getClickableCellRect(s);n&&e.push({coordinates:n,position:s,action:o.execute,title:i||"",component:o.component,componentProps:o.componentProps?.(s,t)??{}})}return e}getClickableCellRect(e){const t=this.getters.expandZone(e.sheetId,Jt(e)),s=this.getters.getVisibleRect(t),o=this.getters.getCellIcons(e),i={center:o.find(e=>"center"===e.horizontalAlign),left:o.find(e=>"left"===e.horizontalAlign),right:o.find(e=>"right"===e.horizontalAlign)};if(!i.center?.onClick){if(i.right?.onClick){const e=this.getters.getRect(t),o=this.getters.getCellIconRect(i.right,e);s.width-=o.width+i.right.margin}if(i.left?.onClick){const e=this.getters.getRect(t),o=this.getters.getCellIconRect(i.left,e);s.x+=o.width+i.left.margin,s.width-=o.width+i.left.margin}return s}}}class sZ extends t.Component{static template="o-spreadsheet-SpreadsheetDashboard";static props={getGridSize:Function};static components={GridOverlay:BG,GridPopover:GG,Popover:jL,VerticalScrollBar:rW,HorizontalScrollBar:nW};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;gridRef;setup(){this.gridRef=t.useRef("grid"),this.hoveredCell=Tv(nV),this.clickableCellsStore=Tv(tZ),t.useChildSubEnv({getPopoverContainerRect:()=>qN(this.env.model.getters.getViewportZoomLevel(),this.getGridRect())}),KG("canvas",this.env.model,()=>this.env.model.getters.getSheetViewDimension()),this.onMouseWheel=QG((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=Tv(aV),JG(this.gridRef,this.moveCanvas.bind(this),()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},()=>{const{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e})}get gridContainer(){const e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e),{end:s}=this.env.model.getters.getColDimensions(e,t);return JF({"max-width":`${s}px`})}get gridOverlayDimensions(){return JF({height:"100%",width:"100%"})}getCellClickableStyle(e){return JF({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){return t.toRaw(this.clickableCellsStore.clickableCells)}selectClickableCell(e,t){const{position:s,action:o}=t;o(s,this.env,HN(e))}onClosePopover(){this.cellPopovers.close()}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:0,gridOffsetY:0})}moveCanvas(e,t){const{scrollX:s,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s+e,offsetY:o+t})}getGridRect(){return{...ON(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}}class oZ extends t.Component{static template="o-spreadsheet-HeaderGroup";static props={group:Object,layerOffset:Number,openContextMenu:Function};toggleGroup(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group;gG(this.env,e,this.dimension,t,s)}get groupBoxStyle(){const e=this.groupBox;return JF({top:`${e.groupRect.y}px`,left:`${e.groupRect.x}px`,width:`${e.groupRect.width}px`,height:`${e.groupRect.height}px`})}get groupButtonStyle(){return JF({"background-color":this.isGroupFolded?"#333":"#fff",color:this.isGroupFolded?"#fff":"#333"})}get groupButtonIcon(){return this.isGroupFolded?"o-spreadsheet-Icon.PLUS":"o-spreadsheet-Icon.MINUS"}get isGroupFolded(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.group;return this.env.model.getters.isGroupFolded(e,this.dimension,t.start,t.end)}onContextMenu(e){const t=this.env.model.getters.getActiveSheetId(),s={x:e.clientX,y:e.clientY},o=this.props.group,i=function(e,t,s,o){const i=Sv([{id:"toggle_group",name:e=>{const i=e.model.getters.getActiveSheetId(),n=e.model.getters.isGroupFolded(i,t,s,o);return Cs(n?"ROW"===t?"Expand row group":"Expand column group":"ROW"===t?"Collapse row group":"Collapse column group")},execute:e=>{const i=e.model.getters.getActiveSheetId();gG(e,i,t,s,o)},icon:e=>{const i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,s,o)?"o-spreadsheet-Icon.EXPAND":"o-spreadsheet-Icon.COLLAPSE"}},{id:"remove_group",name:Cs("ROW"===t?"Remove row group":"Remove column group"),execute:e=>{const i=e.model.getters.getActiveSheetId();e.model.dispatch("UNGROUP_HEADERS",{sheetId:i,dimension:t,start:s,end:o})},icon:"o-spreadsheet-Icon.TRASH",separator:!0}]);return[...i,...pG(e,t)]}(t,this.dimension,o.start,o.end);this.props.openContextMenu(s,i)}}class iZ extends oZ{dimension="ROW";get groupBorderStyle(){const e=this.groupBox;return 0===this.groupBox.groupRect.height?"":JF({top:e.headerRect.height/2+"px",left:"calc(50% - 1px)",width:"30%",height:`calc(100% - ${e.headerRect.height/2}px)`,"border-left":"1px solid","border-bottom":e.isEndHidden?"":"1px solid"})}get groupHeaderStyle(){return JF({width:"100%",height:`${this.groupBox.headerRect.height}px`})}get groupBox(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group,o=this.env.model.getters.getRowDimensions(e,t).start,i=this.env.model.getters.getRowDimensions(e,s).end;let n=0,r=O;if(0!==t){const s=this.env.model.getters.getRowDimensions(e,t-1);n=O+s.start,r=s.end-s.start}const a={x:this.props.layerOffset,y:n,width:M,height:r};return{headerRect:a,groupRect:{x:this.props.layerOffset,y:a.y,width:M,height:a.height+(i-o)},isEndHidden:this.env.model.getters.isRowHidden(e,s)}}}class nZ extends oZ{dimension="COL";get groupBorderStyle(){const e=this.groupBox;return 0===e.groupRect.width?"":JF({top:"calc(50% - 1px)",left:e.headerRect.width/2+"px",width:`calc(100% - ${e.headerRect.width/2}px)`,height:"30%","border-top":"1px solid","border-right":e.isEndHidden?"":"1px solid"})}get groupHeaderStyle(){return JF({width:`${this.groupBox.headerRect.width}px`,height:"100%"})}get groupBox(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group,o=this.env.model.getters.getColDimensions(e,t).start,i=this.env.model.getters.getColDimensions(e,s).end;let n=0,r=F;if(0!==t){const s=this.env.model.getters.getColDimensions(e,t-1);n=F+s.start,r=s.end-s.start}const a={x:n,y:this.props.layerOffset,width:r,height:M};return{headerRect:a,groupRect:{x:a.x,y:this.props.layerOffset,width:a.width+(i-o),height:M},isEndHidden:this.env.model.getters.isColHidden(e,s)}}}class rZ extends t.Component{static template="o-spreadsheet-HeaderGroupContainer";static props={dimension:String,layers:Array};static components={RowGroup:iZ,ColGroup:nZ,MenuPopover:JL};menu=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});getLayerOffset(e){return e*M}onContextMenu(e){const t=this.env.model.getters.getActiveSheetId(),s={x:e.clientX,y:e.clientY},o=pG(t,this.props.dimension);this.openContextMenu(s,o)}openContextMenu(e,t){this.menu.isOpen=!0,this.menu.anchorRect={...e,width:0,height:0},this.menu.menuItems=t}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get groupComponent(){return"ROW"===this.props.dimension?iZ:nZ}get hasFrozenPane(){const e=this.env.model.getters.getMainViewportCoordinates();return"COL"===this.props.dimension?e.x>0:e.y>0}get scrollContainerStyle(){const{scrollX:e,scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo(),s={};return"COL"===this.props.dimension?s.left=-e-this.frozenPaneContainerSize+"px":s.top=-t-this.frozenPaneContainerSize+"px",JF(s)}get frozenPaneContainerStyle(){const e={};return"COL"===this.props.dimension?e.width=`${this.frozenPaneContainerSize}px`:e.height=`${this.frozenPaneContainerSize}px`,JF(e)}get frozenPaneContainerSize(){if(!this.hasFrozenPane)return 0;const e=this.env.model.getters.getMainViewportCoordinates();return"COL"===this.props.dimension?F+e.x:O+e.y}}class aZ extends t.Component{static template="o-spreadsheet-SidePanel";static props={panelContent:Object,panelProps:Object,onCloseSidePanel:Function,onStartHandleDrag:Function,onResetPanelSize:Function,isPinned:{type:Boolean,optional:!0},onTogglePinPanel:{type:Function,optional:!0},onToggleCollapsePanel:{type:Function,optional:!0},isCollapsed:{type:Boolean,optional:!0}};spreadsheetRect=ZL();getTitle(){const e=this.props.panelContent;return"function"==typeof e.title?e.title(this.env,this.props.panelProps):e.title}get pinInfoMessage(){return Cs("Pin this panel to allow to open another side panel beside it.")}}class lZ extends t.Component{static template="o-spreadsheet-SidePanels";static props={};static components={SidePanel:aZ};sidePanelStore;spreadsheetRect=ZL();setup(){this.sidePanelStore=Tv(pq),t.useEffect(()=>{this.sidePanelStore.mainPanel&&!this.sidePanelStore.isMainPanelOpen&&this.sidePanelStore.closeMainPanel(),this.sidePanelStore.secondaryPanel&&!this.sidePanelStore.isSecondaryPanelOpen&&this.sidePanelStore.close()},()=>[this.sidePanelStore.isMainPanelOpen,this.sidePanelStore.isSecondaryPanelOpen])}startHandleDrag(e,t){const s=document.body.style.cursor,o="mainPanel"===e?this.sidePanelStore.mainPanel:this.sidePanelStore.secondaryPanel;if(!o)return;const i=o.size,n=t.clientX;qV(t=>{document.body.style.cursor="col-resize";const s=i+n-t.clientX;this.sidePanelStore.changePanelSize(e,s)},()=>{document.body.style.cursor=s})}get mainPanelProps(){const e=this.sidePanelStore.mainPanelProps;if(this.sidePanelStore.mainPanel&&e)return{panelContent:hq.get(this.sidePanelStore.mainPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.closeMainPanel(),onTogglePinPanel:()=>this.sidePanelStore.togglePinPanel(),onStartHandleDrag:e=>this.startHandleDrag("mainPanel",e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize("mainPanel"),isPinned:this.sidePanelStore.mainPanel?.isPinned,onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel("mainPanel"),isCollapsed:this.sidePanelStore.mainPanel?.isCollapsed}}get secondaryPanelProps(){const e=this.sidePanelStore.secondaryPanelProps;if(this.sidePanelStore.secondaryPanel&&e)return{panelContent:hq.get(this.sidePanelStore.secondaryPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.close(),onStartHandleDrag:e=>this.startHandleDrag("secondaryPanel",e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize("secondaryPanel"),onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel("secondaryPanel"),isCollapsed:this.sidePanelStore.secondaryPanel?.isCollapsed}}get panelList(){return[{key:this.sidePanelStore.secondaryPanelKey,props:this.secondaryPanelProps,style:this.sidePanelStore.secondaryPanel?JF({width:`${this.sidePanelStore.secondaryPanel.size}px`}):""},{key:this.sidePanelStore.mainPanelKey,props:this.mainPanelProps,style:this.sidePanelStore.mainPanel?JF({width:`${this.sidePanelStore.mainPanel.size}px`}):""}].filter(e=>e.key&&e.props)}}class cZ extends t.Component{static template="o-spreadsheet-RibbonMenu";static props={onClose:Function};static components={Menu:WL};rootItems=Mq.getMenuItems();menuRef=t.useRef("menu");containerRef=t.useRef("container");state=t.useState({menuItems:this.rootItems,title:Cs("Menu Bar"),parentState:void 0});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.onMounted(this.updateShadows)}onExternalClick(e){this.menuRef.el?.contains(e.target)||this.props.onClose()}onClickMenu(e){const t=e.children(this.env);t.length?(this.state.parentState={...this.state},this.state.menuItems=t,this.state.title=e.name(this.env),this.containerRef.el?.scrollTo({top:0})):(this.state.menuItems=this.rootItems,this.state.title=void 0,this.state.parentState=void 0,e.execute?.(this.env),this.props.onClose())}get menuProps(){return{menuItems:this.state.menuItems,onClose:this.props.onClose,onClickMenu:this.onClickMenu.bind(this)}}get style(){return JF({height:`${this.props.height}px`})}updateShadows(){if(!this.containerRef.el)return;this.containerRef.el.classList.remove("scroll-top","scroll-bottom");const e=this.containerRef.el.scrollHeight-this.containerRef.el.clientHeight||0;this.containerRef.el.scrollTop<e-1&&this.containerRef.el.classList.add("scroll-bottom"),this.containerRef.el.scrollTop>0&&this.containerRef.el.classList.add("scroll-top")}onClickBack(){this.state.parentState?(this.state.menuItems=this.state.parentState.menuItems,this.state.title=this.state.parentState.title,this.state.parentState=this.state.parentState.parentState,this.containerRef.el?.scrollTo({top:0})):this.props.onClose()}get backTitle(){return this.state.parentState?Cs("Go to previous menu"):Cs("Close menu bar")}}class hZ extends t.Component{static components={Composer:_V,BottomBar:eZ,Ripple:Yq,RibbonMenu:cZ};static template="o-spreadsheet-SmallBottomBar";static props={onClick:Function};composerFocusStore;composerStore;composerInterface;composerRef=t.useRef("bottombarComposer");menuState=t.useState({isOpen:!1});setup(){this.composerFocusStore=Tv(zv);const e=Tv(RG);this.composerStore=e,this.composerInterface={id:"bottombarComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},t.useEffect(()=>{this.env.isMobile()&&!this.menuState.isOpen&&"inactive"!==this.composerStore.editionMode&&this.composerFocusStore.activeComposer!==this.composerInterface&&this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"})})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get showFxIcon(){return"inactive"===this.focus&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get rect(){return this.composerRef.el?FN(this.composerRef.el):{x:0,y:0,width:0,height:0}}get composerProps(){const{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,composerStore:this.composerStore,onComposerContentFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus",selection:e}),isDefaultFocus:!1,inputStyle:JF({height:"inactive"===this.focus?"26px":"fit-content","max-height":"130px"}),showAssistant:!1,placeholder:this.composerStore.placeholder}}get symbols(){return["=","(",")",":","-","/","*",",","+","$","."]}insertSymbol(e){this.composerStore.replaceComposerCursorSelection(e),this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"})}toggleRibbon(){this.composerStore.cancelEdition(),this.menuState.isOpen=!this.menuState.isOpen}}class dZ extends t.Component{static template="o-spreadsheet-TopBarComposer";static props={};static components={Composer:_V};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=Tv(zv);const e=Tv(RG);this.composerStore=e,this.composerInterface={id:"topbarComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition}}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get showFxIcon(){return"inactive"===this.focus&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get composerStyle(){const e={padding:"5px 0px 5px 8px","max-height":"300px","line-height":"24px"};return e.height="inactive"===this.focus?"34px":"fit-content",JF(e)}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}}class uZ{mutators=["closeDropdowns","openDropdown"];_currentDropdown=null;closeDropdowns(){this._currentDropdown=null}openDropdown(e){this._currentDropdown=e}get currentDropdown(){return this._currentDropdown}}function gZ(){const e=t.useComponent(),s=Tv(uZ);return t.onWillUnmount(()=>{e===s.currentDropdown&&s.closeDropdowns()}),{closeDropdowns:()=>s.closeDropdowns(),openDropdown:()=>{s.openDropdown(e)},get isActive(){return s.currentDropdown===e}}}const pZ=[[["all","o-spreadsheet-Icon.BORDERS"],["hv","o-spreadsheet-Icon.BORDER_HV"],["h","o-spreadsheet-Icon.BORDER_H"],["v","o-spreadsheet-Icon.BORDER_V"],["external","o-spreadsheet-Icon.BORDER_EXTERNAL"]],[["left","o-spreadsheet-Icon.BORDER_LEFT"],["top","o-spreadsheet-Icon.BORDER_TOP"],["right","o-spreadsheet-Icon.BORDER_RIGHT"],["bottom","o-spreadsheet-Icon.BORDER_BOTTOM"],["clear","o-spreadsheet-Icon.BORDER_CLEAR"]]];class mZ extends t.Component{static template="o-spreadsheet-BorderEditor";static props={class:{type:String,optional:!0},currentBorderColor:{type:String,optional:!1},currentBorderStyle:{type:String,optional:!1},currentBorderPosition:{type:String,optional:!0},onBorderColorPicked:Function,onBorderStylePicked:Function,onBorderPositionPicked:Function,maxHeight:{type:Number,optional:!0},anchorRect:Object};static components={ColorPickerWidget:uW,Popover:jL};BORDER_POSITIONS=pZ;lineStyleButtonRef=t.useRef("lineStyleButton");borderStyles=Ms;state=t.useState({activeTool:void 0});toggleDropdownTool(e){const t=this.state.activeTool===e;this.state.activeTool=t?void 0:e}closeDropdown(){this.state.activeTool=void 0}setBorderPosition(e){this.props.onBorderPositionPicked(e),this.closeDropdown()}setBorderColor(e){this.props.onBorderColorPicked(e),this.closeDropdown()}setBorderStyle(e){this.props.onBorderStylePicked(e),this.closeDropdown()}get lineStylePickerPopoverProps(){return{anchorRect:this.lineStylePickerAnchorRect,positioning:"bottom-left",verticalOffset:0}}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"bottom-left",verticalOffset:0}}get lineStylePickerAnchorRect(){const e=this.lineStyleButtonRef.el;if(null===e)return{x:0,y:0,width:0,height:0};const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}}class fZ extends t.Component{static template="o-spreadsheet-BorderEditorWidget";static props={disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={BorderEditor:mZ};topBarToolStore;borderEditorButtonRef=t.useRef("borderEditorButton");state=t.useState({currentColor:B,currentStyle:U,currentPosition:void 0});setup(){this.topBarToolStore=gZ(),t.onWillUpdateProps(()=>{this.isActive||(this.state.currentPosition=void 0)})}get dropdownMaxHeight(){return this.env.model.getters.getSheetViewDimension().height}get borderEditorAnchorRect(){const e=this.borderEditorButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}onBorderPositionPicked(e){this.state.currentPosition=e,this.updateBorder()}onBorderColorPicked(e){this.state.currentColor=e,this.updateBorder()}onBorderStylePicked(e){this.state.currentStyle=e,this.updateBorder()}get isActive(){return this.topBarToolStore.isActive}toggleBorderEditor(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}updateBorder(){void 0!==this.state.currentPosition&&this.env.model.dispatch("SET_ZONE_BORDERS",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),border:{position:this.state.currentPosition,color:this.state.currentColor,style:this.state.currentStyle}})}}class vZ extends t.Component{static template="o-spreadsheet-PaintFormatButton";static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=Tv(VG)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}}class bZ extends t.Component{static template="o-spreadsheet-TableDropdownButton";static components={TableStylesPopover:nq,ActionButton:dW};static props={class:{type:String,optional:!0}};topBarToolStore;state=t.useState({popoverProps:void 0});setup(){this.topBarToolStore=gZ()}onStylePicked(e){const t=this.env.model.getters.getActiveSheetId(),s={...this.tableConfig,styleId:e};Bz(this.env,t,s).isSuccessful&&this.env.openSidePanel("TableSidePanel",{}),this.closePopover()}onClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps)return void this.closePopover();if(this.env.model.getters.getFirstTableInSelection())return this.topBarToolStore.closeDropdowns(),void this.env.toggleSidePanel("TableSidePanel",{});const t=e.currentTarget,{left:s,bottom:o}=t.getBoundingClientRect();this.topBarToolStore.openDropdown(),this.state.popoverProps={anchorRect:{x:s,y:o,width:0,height:0},positioning:"bottom-left",verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}get action(){return{name:e=>e.model.getters.getFirstTableInSelection()?Cs("Edit table"):Cs("Insert table"),icon:e=>e.model.getters.getFirstTableInSelection()?"o-spreadsheet-Icon.EDIT_TABLE":"o-spreadsheet-Icon.PAINT_TABLE"}}get tableConfig(){return{...Zx,numberOfHeaders:1,bandedRows:!0}}}class SZ extends t.Component{static components={ColorPickerWidget:uW};static props={class:String,style:String,icon:String,title:String};static template="o-spreadsheet-ColorEditor";topBarToolStore;state=t.useState({isOpen:!1});setup(){this.topBarToolStore=gZ()}get currentColor(){return this.env.model.getters.getCurrentStyle()[this.props.style]||("textColor"===this.props.style?"#000000":"#ffffff")}setColor(e){Wz(this.env,{[this.props.style]:e}),this.state.isOpen=!1}get isMenuOpen(){return this.topBarToolStore.isActive}onClick(){this.isMenuOpen?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}}class yZ extends t.Component{static template="o-spreadsheet-DropdownAction";static components={ActionButton:dW,Popover:jL};static props={parentAction:Object,childActions:Array,class:String,childClass:String};topBarToolStore;actionRef=t.useRef("actionRef");setup(){this.topBarToolStore=gZ()}toggleDropdown(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}get popoverProps(){return{anchorRect:this.actionRef.el?this.actionRef.el.getBoundingClientRect():{x:0,y:0,width:0,height:0},positioning:"bottom-left",verticalOffset:0,class:"rounded"}}}class CZ extends t.Component{static components={FontSizeEditor:pW};static props={class:String};static template="o-spreadsheet-TopBarFontSizeEditor";topBarToolStore;setup(){this.topBarToolStore=gZ()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||z}setFontSize(e){Wz(this.env,{fontSize:e})}onToggle(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}}class IZ extends t.Component{static template="o-spreadsheet-NumberFormatsTool";static components={MenuPopover:JL,ActionButton:dW};static props={class:String};formatNumberMenuItemSpec=Pq;topBarToolStore;buttonRef=t.useRef("buttonRef");state=t.useState({anchorRect:{x:0,y:0,width:0,height:0},menuItems:[]});setup(){this.topBarToolStore=gZ()}toggleMenu(){if(this.isActive)this.topBarToolStore.closeDropdowns();else{const e=Cv(this.formatNumberMenuItemSpec);this.state.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.anchorRect=FN(this.buttonRef.el),this.topBarToolStore.openDropdown()}}get isActive(){return this.topBarToolStore.isActive}}class wZ extends t.Component{static template="o-spreadsheet-TopBarZoom";static components={NumberEditor:gW};static props={class:String};topBarToolStore;valueList=N;setup(){this.topBarToolStore=gZ()}get currentFontSize(){return 100*(this.env.model.getters.getViewportZoomLevel()||1)}setZoom(e){this.env.model.dispatch("SET_ZOOM",{zoom:e/100})}toggle(){this.topBarToolStore.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}}const EZ=new class{content={};add(e){if(e in this.content)throw new Error(`${e} is already present in this registry!`);return this.content[e]=[],this}addChild(e,t){return this.content[e].push(t),this}getEntries(e){return this.content[e].sort((e,t)=>e.sequence-t.sequence)}getCategories(){return Object.keys(this.content)}};EZ.add("edit").addChild("edit",{component:dW,props:{action:kH,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("edit",{component:dW,props:{action:LH,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("edit",{component:vZ,props:{class:"o-hoverable-button o-toolbar-button o-mobile-disabled"},sequence:3}).addChild("edit",{component:dW,props:{action:rG,class:"o-hoverable-button o-toolbar-button"},sequence:4}).addChild("edit",{component:wZ,props:{class:"o-menu-item-button o-hoverable-button o-toolbar-button"},sequence:5}).add("numberFormat").addChild("numberFormat",{component:dW,props:{action:bB,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("numberFormat",{component:dW,props:{action:PB,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("numberFormat",{component:dW,props:{action:FB,class:"o-hoverable-button o-toolbar-button"},sequence:3}).addChild("numberFormat",{component:IZ,props:{class:"o-menu-item-button o-hoverable-button o-toolbar-button"},sequence:4}).add("fontSize").addChild("fontSize",{component:CZ,props:{class:"o-hoverable-button o-toolbar-button"},sequence:3}).add("textStyle").addChild("textStyle",{component:dW,props:{action:MB,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("textStyle",{component:dW,props:{action:NB,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("textStyle",{component:dW,props:{action:GB,class:"o-hoverable-button o-toolbar-button"},sequence:3}).addChild("textStyle",{component:SZ,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button",style:"textColor",icon:"o-spreadsheet-Icon.TEXT_COLOR",title:Cs("Text Color")},sequence:4}).add("cellStyle").addChild("cellStyle",{component:SZ,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button",style:"fillColor",icon:"o-spreadsheet-Icon.FILL_COLOR",title:Cs("Fill Color")},sequence:1}).addChild("cellStyle",{component:fZ,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:2}).addChild("cellStyle",{component:dW,props:{action:tU,class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:3}).add("alignment").addChild("alignment",{component:yZ,props:{parentAction:qB,childActions:[ZB,jB,YB],class:"o-hoverable-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:1}).addChild("alignment",{component:yZ,props:{parentAction:XB,childActions:[KB,JB,QB],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:2}).addChild("alignment",{component:yZ,props:{parentAction:tG,childActions:[sG,oG,iG],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:3}).addChild("alignment",{component:yZ,props:{parentAction:LB,childActions:[VB,zB,HB,UB,BB],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:4}).add("misc").addChild("misc",{component:bZ,props:{class:"o-toolbar-button o-hoverable-button o-menu-item-button o-mobile-disabled"},sequence:1}).addChild("misc",{component:dW,props:{action:hB,class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:2});class xZ extends t.Component{static template="o-spreadsheet-TopBar";static props={onClick:Function,dropdownMaxHeight:Number};static components={MenuPopover:JL,TopBarComposer:dZ,Popover:jL};toolsCategories=EZ.getCategories();state=t.useState({menuState:{isOpen:!1,anchorRect:null,menuItems:[]},invisibleToolsCategories:[],toolsPopoverState:{isOpen:!1}});isSelectingMenu=!1;openedEl=null;menus=[];toolbarMenuRegistry=EZ;formatNumberMenuItemSpec=Pq;isntToolbarMenu=!1;composerFocusStore;fingerprints;topBarToolStore;toolBarContainerRef=t.useRef("toolBarContainer");toolbarRef=t.useRef("toolBar");moreToolsContainerRef=t.useRef("moreToolsContainer");moreToolsButtonRef=t.useRef("moreToolsButton");spreadsheetRect=ZL();setup(){this.composerFocusStore=Tv(zv),this.fingerprints=Tv(rH),this.topBarToolStore=Tv(uZ),t.useExternalListener(window,"click",this.onExternalClick),t.onWillStart(()=>this.updateCellState()),t.onWillUpdateProps(()=>this.updateCellState()),t.useEffect(()=>{this.state.toolsPopoverState.isOpen=!1,this.setVisibilityToolsGroups()},()=>[this.spreadsheetRect.width])}setVisibilityToolsGroups(){if(this.env.model.getters.isReadonly())return;const e=[],{x:t}=this.toolbarRef.el.getBoundingClientRect(),{x:s}=this.toolBarContainerRef.el.getBoundingClientRect();this.moreToolsContainerRef.el?.classList.remove("d-none");const o=this.moreToolsButtonRef.el?.getBoundingClientRect().width||0,i=Math.round(this.spreadsheetRect.width)-o-(t-s)-16,n=document.querySelectorAll(".tool-container");let r=0;for(let t=0;t<n.length;t++){const s=n[t];s.classList.remove("d-none");const{width:o}=s.getBoundingClientRect();r+=o,r>i&&(s.classList.add("d-none"),e.push(this.toolsCategories[t]))}this.state.invisibleToolsCategories=e,e.length||this.moreToolsContainerRef.el?.classList.add("d-none")}get topbarComponents(){return $q.getAllOrdered().filter(e=>!e.isVisible||e.isVisible(this.env))}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||z}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.isntToolbarMenu&&this.openMenu(e,t)}toggleContextMenu(e,t){this.state.menuState.isOpen&&this.isntToolbarMenu?this.closeMenus():(this.openMenu(e,t),this.isntToolbarMenu=!0)}openMenu(e,t){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!0,this.state.menuState.anchorRect=FN(t.currentTarget),this.state.menuState.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.composerFocusStore.activeComposer.stopEdition()}closeMenus(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){this.menus=Mq.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){Wz(this.env,{[e]:t}),this.onClick()}setFontSize(e){Wz(this.env,{fontSize:e})}toggleMoreTools(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!this.state.toolsPopoverState.isOpen}get toolsPopoverProps(){return{anchorRect:this.moreToolsButtonRef.el?FN(this.moreToolsButtonRef.el):{x:0,y:0,width:0,height:0},positioning:"bottom-left",verticalOffset:0,class:"rounded",maxWidth:300}}showDivider(e){return e<this.toolsCategories.length-1||this.state.invisibleToolsCategories.length>0}}class RZ{clipboard;constructor(e){this.clipboard=e}async write(e){if(this.clipboard?.write)try{await(this.clipboard?.write(this.getClipboardItems(e)))}catch(t){console.log("Failed to write on the clipboard, falling back to plain/html text. Error %s",t);try{await(this.clipboard?.write([new ClipboardItem({[QF.PlainText]:this.getBlob(e,QF.PlainText),[QF.Html]:this.getBlob(e,QF.Html)})]))}catch(e){}}else await this.writeText(e[QF.PlainText]??"")}async writeText(e){try{this.clipboard?.writeText(e)}catch(e){}}async read(){let e;try{e=await navigator.permissions.query({name:"clipboard-read"})}catch(e){}if(!this.clipboard?.read)return{status:"ok",content:{[QF.PlainText]:await(this.clipboard?.readText())}};try{const e=await this.clipboard.read(),t={};for(const s of e)for(const e of s.types){const o=await s.getType(e);if(eP.includes(e))t[e]=o;else{const s=await o.text();t[e]=s}}return{status:"ok",content:t}}catch(t){return{status:"denied"===e?.state?"permissionDenied":"notImplemented"}}}getClipboardItems(e){const t={};for(const s of Object.keys(e))t[s]=this.getBlob(e,s);return[new ClipboardItem(t)]}getBlob(e,t){const s=e[t];return s instanceof Blob||s instanceof File?s:new Blob([e[t]||""],{type:t})}}class TZ extends t.Component{static template="o-spreadsheet-Spreadsheet";static props={model:Object,notifyUser:{type:Function,optional:!0},raiseError:{type:Function,optional:!0},askConfirmation:{type:Function,optional:!0},colorScheme:{type:String,optional:!0}};static components={TopBar:xZ,Grid:vq,BottomBar:eZ,SmallBottomBar:hZ,SidePanels:lZ,SpreadsheetDashboard:sZ,HeaderGroupContainer:rZ,FullScreenFigure:Iq};sidePanel;spreadsheetRef=t.useRef("spreadsheet");spreadsheetRect=ZL();_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){const e={},t=this.env.model.getters.getScrollBarWidth();this.env.isDashboard()?e["grid-template-rows"]="auto":e["grid-template-rows"]="min-content auto min-content";const s=this.sidePanel.mainPanel?`${this.sidePanel.totalPanelSize||uq}px`:"auto";return e["grid-template-columns"]=`auto ${s}`,e["--os-scrollbar-width"]=`${t}px`,e["color-scheme"]=this.props.colorScheme,JF(e)}setup(){if(!("isSmall"in this.env)){const e=function(){const e=ZL();return{get isSmall(){return e.width<768}}}();t.useSubEnv({get isSmall(){return e.isSmall}})}const e=Rv();e.inject(Fv,this.model);const s=this.env;e.get(dq).setSmallThreshhold(()=>s.isSmall),this.notificationStore=Tv(kV),this.composerFocusStore=Tv(zv),this.sidePanel=Tv(pq);const o=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:o?new qq(o):void 0,loadCurrencies:this.model.config.external.loadCurrencies,loadLocales:this.model.config.external.loadLocales,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.sidePanel.open.bind(this.sidePanel),replaceSidePanel:this.sidePanel.replace.bind(this.sidePanel),toggleSidePanel:this.sidePanel.toggle.bind(this.sidePanel),clipboard:this.env.clipboard||new RZ(navigator.clipboard),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,s)=>this.notificationStore.askConfirmation(e,t,s),raiseError:(e,t)=>this.notificationStore.raiseError(e,t),isMobile:WN}),this.notificationStore.updateNotificationCallbacks({...this.props}),t.useEffect(()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()}),t.useExternalListener(window,"resize",()=>this.render(!0)),t.useExternalListener(document.body,"wheel",()=>{}),this.bindModelEvents(),t.onWillUpdateProps(e=>{if(e.model!==this.props.model)throw new Error("Changing the props model is not supported at the moment.");e.notifyUser===this.props.notifyUser&&e.askConfirmation===this.props.askConfirmation&&e.raiseError===this.props.raiseError||this.notificationStore.updateNotificationCallbacks({...e})});const i=function(e){let t=!1;return async(...s)=>{t||(t=!0,await Promise.resolve(),t=!1,e(...s))}}(this.render.bind(this,!0));t.onMounted(()=>{this.checkViewportSize(),e.on("store-updated",this,i),n.observe(this.spreadsheetRef.el)}),t.onWillUnmount(()=>{this.unbindModelEvents(),e.off("store-updated",this),n.disconnect(),Gv()}),t.onPatched(()=>{this.checkViewportSize()});const n=new ResizeObserver(()=>{this.sidePanel.changeSpreadsheetWidth(this.spreadsheetRect.width)})}bindModelEvents(){this.model.on("update",this,()=>this.render(!0)),this.model.on("notify-ui",this,e=>this.notificationStore.notifyUser(e)),this.model.on("raise-error-ui",this,({text:e})=>this.notificationStore.raiseError(e))}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this),this.model.off("raise-error-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(isFinite(e)&&isFinite(t))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.notificationStore.notifyUser({text:Cs("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),type:"warning",sticky:!1}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}focusGrid(){this._focusGrid&&this._focusGrid()}get gridHeight(){return this.env.model.getters.getSheetViewDimension().height}get gridContainerStyle(){const e=M*this.rowLayers.length,t=M*this.colLayers.length;return JF({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`,zoom:`${this.env.model.getters.getViewportZoomLevel()}`})}get rowLayers(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,"ROW")}get colLayers(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,"COL")}getGridSize(){const e=this.spreadsheetRef.el;if(!e)return{width:0,height:0};const t=this.env.model.getters.getViewportZoomLevel(),s=this.env.model.getters.getScrollBarWidth(),o=s=>e.querySelector(s)&&DN(e.querySelector(s),t).height||0,i=e.getBoundingClientRect(),n=o(".o-spreadsheet-topbar-wrapper"),r=o(".o-spreadsheet-bottombar-wrapper"),a=o(".o-column-groups"),l=(c=".o-grid",e.querySelector(c)&&DN(e.querySelector(c),t).width||0);var c;const h=i.height-a-n-r;return{width:Math.max(l/t-s,0),height:Math.max(h/t-s,0)}}getSpreadSheetClasses(){return[this.env.isSmall?"o-spreadsheet-mobile":"","dark"===this.props.colorScheme?"dark":""].join(" ")}}function AZ(e){return LW.includes(e.horizontalGroupBy)&&LW.includes(e.verticalGroupBy)?"Success":"InvalidChartDefinition"}class _Z extends zO{dataSets;labelRange;background;type="calendar";showValues;colorScale;axesDesign;horizontalGroupBy;verticalGroupBy;legendPosition;missingValueColor;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.showValues=e.showValues,this.colorScale=e.colorScale,this.axesDesign=e.axesDesign,this.horizontalGroupBy=e.horizontalGroupBy,this.verticalGroupBy=e.verticalGroupBy,this.legendPosition=e.legendPosition,this.missingValueColor=e.missingValueColor}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy,AZ)}static getDefinitionFromContextCreation(e){let t="left";return"right"===e.legendPosition&&(t="right"),{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,title:e.title||{text:""},type:"calendar",labelRange:e.auxiliaryRange||void 0,showValues:e.showValues,axesDesign:e.axesDesign,legendPosition:t,horizontalGroupBy:"day_of_week",verticalGroupBy:"month_number"}}getContextCreation(){const e=[{dataRange:this.getters.getRangeString(this.dataSets[0].dataRange,this.sheetId)}];return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new _Z(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new _Z(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)}));return{type:"calendar",background:this.background,dataSets:o,dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,showValues:this.showValues,colorScale:this.colorScale,axesDesign:this.axesDesign,horizontalGroupBy:this.horizontalGroupBy,verticalGroupBy:this.verticalGroupBy,legendPosition:this.legendPosition,missingValueColor:this.missingValueColor}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new _Z(i,this.sheetId,this.getters)}}class DZ extends zO{dataSets;labelRange;background;legendPosition;aggregated;dataSetsHaveTitle;dataSetDesign;axesDesign;type="combo";showValues;hideDataMarkers;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers,this.zoomable=e.zoomable}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId),type:this.dataSetDesign?.[t]?.type??(t?"line":"bar")});return{type:"combo",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,zoomable:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,$y(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:IP(this.background||c),fontColor:IP(Uy(this.background)),dataSets:e,labelRange:t,verticalAxis:qy(s)}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new DZ(i,this.sheetId,this.getters)}static getDefinitionFromContextCreation(e){const t=(e.range??[]).map((e,t)=>({...e,type:t?"line":"bar"}));return{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated,legendPosition:e.legendPosition??"top",title:e.title||{text:""},labelRange:e.auxiliaryRange||void 0,type:"combo",axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new DZ(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new DZ(t,e,this.getters)}}class OZ extends zO{dataSets;labelRange;background;legendPosition;aggregated;type="funnel";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;showValues;funnelColors;cumulative;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.horizontal=!0,this.funnelColors=e.funnelColors,this.cumulative=e.cumulative}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:"none",title:e.title||{text:""},type:"funnel",labelRange:e.auxiliaryRange||void 0,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new OZ(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new OZ(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"funnel",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,horizontal:this.horizontal,axesDesign:this.axesDesign,showValues:this.showValues,funnelColors:this.funnelColors,cumulative:this.cumulative,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new OZ(i,this.sheetId,this.getters)}}class FZ extends zO{dataSets;labelRange;background;legendPosition;type="geo";dataSetsHaveTitle;dataSetDesign;colorScale;missingValueColor;region;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.colorScale=e.colorScale,this.missingValueColor=e.missingValueColor,this.region=e.region}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"geo",labelRange:e.auxiliaryRange||void 0,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new FZ(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new FZ(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"geo",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,colorScale:this.colorScale,missingValueColor:this.missingValueColor,region:this.region,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new FZ(i,this.sheetId,this.getters)}}class PZ extends zO{dataSets;labelRange;background;legendPosition;aggregated;type="pyramid";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;stacked=!0;showValues;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"pyramid",labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new PZ(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new PZ(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"pyramid",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,horizontal:!0,stacked:!0,showValues:this.showValues,humanize:this.humanize}}getDefinitionForExcel(e){const{dataSets:t,labelRange:s}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,$y(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),o=this.getDefinition(),i=sk(o,this.dataSets,this.labelRange,e),{dataSetsValues:n}=i,r=Math.max(...n.map(e=>Math.max(...e.data.map(Math.abs))));return{...o,horizontal:!0,backgroundColor:IP(this.background||c),fontColor:IP(Uy(this.background)),dataSets:t,labelRange:s,verticalAxis:qy(o),maxValue:r}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new PZ(i,this.sheetId,this.getters)}}class MZ extends zO{dataSets;labelRange;background;legendPosition;stacked;aggregated;type="radar";dataSetsHaveTitle;dataSetDesign;fillArea;showValues;hideDataMarkers;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.fillArea=e.fillArea,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"radar",labelRange:e.auxiliaryRange||void 0,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new MZ(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new MZ(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"radar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated,fillArea:this.fillArea,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,humanize:this.humanize}}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,$y(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:IP(this.background||c),fontColor:IP(Uy(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new MZ(i,this.sheetId,this.getters)}}class NZ extends zO{dataSets;labelRange;background;legendPosition;type="sunburst";dataSetsHaveTitle;showValues;showLabels;valuesDesign;groupColors;pieHolePercentage;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.groupColors=e.groupColors,this.pieHolePercentage=e.pieHolePercentage}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){const t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"sunburst",labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){const e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}getDefinitionWithSpecificDataSets(e,t,s){return{type:"sunburst",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,showValues:this.showValues,showLabels:this.showLabels,valuesDesign:this.valuesDesign,groupColors:this.groupColors,pieHolePercentage:this.pieHolePercentage,humanize:this.humanize}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new NZ(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new NZ(t,e,this.getters)}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new NZ(i,this.sheetId,this.getters)}}class kZ extends zO{static defaults={background:c,legendPosition:"top",dataSetsHaveTitle:!1,showHeaders:!0,headersColor:"#000000"};dataSets;labelRange;background;legendPosition;type="treemap";dataSetsHaveTitle;showHeaders;headerDesign;showValues;showLabels;valuesDesign;coloringOptions;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showHeaders=e.showHeaders,this.headerDesign=e.headerDesign,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.coloringOptions=e.coloringOptions}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){const t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"treemap",labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions,humanize:e.humanize}}getContextCreation(){const e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new kZ(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new kZ(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)}));return{type:"treemap",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,showValues:this.showValues,showHeaders:this.showHeaders,headerDesign:this.headerDesign,showLabels:this.showLabels,valuesDesign:this.valuesDesign,coloringOptions:this.coloringOptions,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new kZ(i,this.sheetId,this.getters)}}vR.add("bar",{match:e=>"bar"===e,createChart:(e,t,s)=>new aL(e,t,s),getChartRuntime:lL,validateChartDefinition:aL.validateChartDefinition,transformDefinition:aL.transformDefinition,getChartDefinitionFromContextCreation:aL.getDefinitionFromContextCreation,sequence:10}),vR.add("combo",{match:e=>"combo"===e,createChart:(e,t,s)=>new DZ(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=QN(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:iN(s,o)},options:{...eF,layout:xk(0,o),scales:kM(s,o),plugins:{title:Gk(s,t),legend:Fk(s),tooltip:Zk(s,o),chartShowValuesPlugin:Vk(s,o)}}},background:e.background||c}},validateChartDefinition:DZ.validateChartDefinition,transformDefinition:DZ.transformDefinition,getChartDefinitionFromContextCreation:DZ.getDefinitionFromContextCreation,sequence:15}),vR.add("line",{match:e=>"line"===e,createChart:(e,t,s)=>new bL(e,t,s),getChartRuntime:SL,validateChartDefinition:bL.validateChartDefinition,transformDefinition:bL.transformDefinition,getChartDefinitionFromContextCreation:bL.getDefinitionFromContextCreation,sequence:20}),vR.add("pie",{match:e=>"pie"===e,createChart:(e,t,s)=>new yL(e,t,s),getChartRuntime:CL,validateChartDefinition:yL.validateChartDefinition,transformDefinition:yL.transformDefinition,getChartDefinitionFromContextCreation:yL.getDefinitionFromContextCreation,sequence:30}),vR.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,s)=>new ZO(e,t,s),getChartRuntime:YO,validateChartDefinition:ZO.validateChartDefinition,transformDefinition:ZO.transformDefinition,getChartDefinitionFromContextCreation:ZO.getDefinitionFromContextCreation,sequence:40}),vR.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,s)=>new gL(e,t,s),getChartRuntime:pL,validateChartDefinition:gL.validateChartDefinition,transformDefinition:gL.transformDefinition,getChartDefinitionFromContextCreation:gL.getDefinitionFromContextCreation,sequence:50}),vR.add("scatter",{match:e=>"scatter"===e,createChart:(e,t,s)=>new e$(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=ok(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"line",data:{labels:o.labels,datasets:sN(s,o)},options:{...eF,layout:xk(0,o),scales:HM(s,o),plugins:{title:Gk(s,t),legend:Ok(s),tooltip:Yk(s,o),chartShowValuesPlugin:Vk(s,o)}}},background:e.background||c}},validateChartDefinition:e$.validateChartDefinition,transformDefinition:e$.transformDefinition,getChartDefinitionFromContextCreation:e$.getDefinitionFromContextCreation,sequence:60}),vR.add("waterfall",{match:e=>"waterfall"===e,createChart:(e,t,s)=>new IL(e,t,s),getChartRuntime:wL,validateChartDefinition:IL.validateChartDefinition,transformDefinition:IL.transformDefinition,getChartDefinitionFromContextCreation:IL.getDefinitionFromContextCreation,sequence:70}),vR.add("pyramid",{match:e=>"pyramid"===e,createChart:(e,t,s)=>new PZ(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=sk(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:JM(s,o)},options:{...eF,indexAxis:"y",layout:xk(0,o),scales:BM(s,o),plugins:{title:Gk(s,t),legend:Ak(s),tooltip:Jk(s,o),chartShowValuesPlugin:Uk(s,o)}}},background:e.background||c}},validateChartDefinition:PZ.validateChartDefinition,transformDefinition:PZ.transformDefinition,getChartDefinitionFromContextCreation:PZ.getDefinitionFromContextCreation,sequence:80,dataSeriesLimit:2}),vR.add("radar",{match:e=>"radar"===e,createChart:(e,t,s)=>new MZ(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=nk(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"radar",data:{labels:o.labels,datasets:nN(s,o)},options:{...eF,layout:xk(0,o),scales:GM(s,o),plugins:{title:Gk(s,t),legend:Mk(s),tooltip:Qk(s,o),chartShowValuesPlugin:Vk(s,o)}}},background:e.background||c}},validateChartDefinition:MZ.validateChartDefinition,transformDefinition:MZ.transformDefinition,getChartDefinitionFromContextCreation:MZ.getDefinitionFromContextCreation,sequence:80}),vR.add("geo",{match:e=>"geo"===e,createChart:(e,t,s)=>new FZ(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=rk(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"choropleth",data:{datasets:rN(s,o)},options:{...eF,layout:xk(0,o),scales:WM(s,o),plugins:{title:Gk(s,t),tooltip:eL(s,o),legend:{display:!1}}}},background:e.background||c}},validateChartDefinition:FZ.validateChartDefinition,transformDefinition:FZ.transformDefinition,getChartDefinitionFromContextCreation:FZ.getDefinitionFromContextCreation,sequence:90,dataSeriesLimit:1}),vR.add("funnel",{match:e=>"funnel"===e,createChart:(e,t,s)=>new OZ(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=ak(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"funnel",data:{labels:o.labels,datasets:aN(s,o)},options:{...eF,indexAxis:"y",layout:xk(0,o),scales:$M(0,o),plugins:{title:Gk(s,t),legend:{display:!1},tooltip:tL(s,o),chartShowValuesPlugin:Vk(s,o)}}},background:e.background||c}},validateChartDefinition:OZ.validateChartDefinition,transformDefinition:OZ.transformDefinition,getChartDefinitionFromContextCreation:OZ.getDefinitionFromContextCreation,sequence:100,dataSeriesLimit:1}),vR.add("sunburst",{match:e=>"sunburst"===e,createChart:(e,t,s)=>new NZ(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=lk(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"doughnut",data:{datasets:cN(s,o)},options:{cutout:void 0===e.pieHolePercentage?"25%":`${e.pieHolePercentage}%`,...eF,layout:xk(0,o),plugins:{title:Gk(s,t),legend:Nk(s),tooltip:sL(s,o),sunburstLabelsPlugin:Hk(s,o),sunburstHoverPlugin:{enabled:!0}}}},background:e.background||c}},validateChartDefinition:NZ.validateChartDefinition,transformDefinition:NZ.transformDefinition,getChartDefinitionFromContextCreation:NZ.getDefinitionFromContextCreation,sequence:30}),vR.add("treemap",{match:e=>"treemap"===e,createChart:(e,t,s)=>new kZ(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=lk(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"treemap",data:{labels:o.labels,datasets:gN(s,o)},options:{...eF,layout:xk(0,o),plugins:{title:Gk(s,t),legend:{display:!1},tooltip:oL(s,o)}}},background:e.background||c}},validateChartDefinition:kZ.validateChartDefinition,transformDefinition:kZ.transformDefinition,getChartDefinitionFromContextCreation:kZ.getDefinitionFromContextCreation,sequence:100}),vR.add("calendar",{match:e=>"calendar"===e,createChart:(e,t,s)=>new _Z(e,t,s),getChartRuntime:(e,t)=>function(e,t){const s=e.getDefinition(),o=tk(s,e.dataSets,e.labelRange,t),{labels:i,datasets:n}=QM(s,o);return{chartJsConfig:{type:"calendar",data:{labels:i,datasets:n},options:{...eF,indexAxis:"x",layout:Rk(s,o),scales:LM(s,n),plugins:{title:Gk(s,t),legend:{display:!1},tooltip:jk(0,o),chartShowValuesPlugin:zk(s,o),chartColorScalePlugin:VM(s,o)},chartBackground:s.background||c}},background:e.background||c}}(e,t),validateChartDefinition:_Z.validateChartDefinition,transformDefinition:_Z.transformDefinition,getChartDefinitionFromContextCreation:_Z.getDefinitionFromContextCreation,sequence:110,dataSeriesLimit:1}),qF.add("line",{matcher:e=>"line"===e.type&&!e.stacked&&!e.fillArea,displayName:Cs("Line"),chartType:"line",chartSubtype:"line",subtypeDefinition:{stacked:!1,fillArea:!1},category:"line",preview:"o-spreadsheet-ChartPreview.LINE_CHART"}).add("stacked_line",{matcher:e=>"line"===e.type&&!e.fillArea&&!!e.stacked,displayName:Cs("Stacked Line"),chartType:"line",chartSubtype:"stacked_line",subtypeDefinition:{stacked:!0,fillArea:!1},category:"line",preview:"o-spreadsheet-ChartPreview.STACKED_LINE_CHART"}).add("area",{matcher:e=>"line"===e.type&&!e.stacked&&!!e.fillArea,displayName:Cs("Area"),chartType:"line",chartSubtype:"area",subtypeDefinition:{stacked:!1,fillArea:!0},category:"area",preview:"o-spreadsheet-ChartPreview.AREA_CHART"}).add("stacked_area",{matcher:e=>"line"===e.type&&e.stacked&&!!e.fillArea,displayName:Cs("Stacked Area"),chartType:"line",chartSubtype:"stacked_area",subtypeDefinition:{stacked:!0,fillArea:!0},category:"area",preview:"o-spreadsheet-ChartPreview.STACKED_AREA_CHART"}).add("scatter",{displayName:Cs("Scatter"),chartType:"scatter",chartSubtype:"scatter",category:"misc",preview:"o-spreadsheet-ChartPreview.SCATTER_CHART"}).add("column",{matcher:e=>"bar"===e.type&&!e.stacked&&!e.horizontal,displayName:Cs("Column"),chartType:"bar",chartSubtype:"column",subtypeDefinition:{stacked:!1,horizontal:!1},category:"column",preview:"o-spreadsheet-ChartPreview.COLUMN_CHART"}).add("stacked_column",{matcher:e=>"bar"===e.type&&e.stacked&&!e.horizontal,displayName:Cs("Stacked Column"),chartType:"bar",chartSubtype:"stacked_column",subtypeDefinition:{stacked:!0,horizontal:!1},category:"column",preview:"o-spreadsheet-ChartPreview.STACKED_COLUMN_CHART"}).add("bar",{matcher:e=>"bar"===e.type&&!e.stacked&&!!e.horizontal,displayName:Cs("Bar"),chartType:"bar",chartSubtype:"bar",subtypeDefinition:{horizontal:!0,stacked:!1},category:"bar",preview:"o-spreadsheet-ChartPreview.BAR_CHART"}).add("stacked_bar",{matcher:e=>"bar"===e.type&&e.stacked&&!!e.horizontal,displayName:Cs("Stacked Bar"),chartType:"bar",chartSubtype:"stacked_bar",subtypeDefinition:{horizontal:!0,stacked:!0},category:"bar",preview:"o-spreadsheet-ChartPreview.STACKED_BAR_CHART"}).add("combo",{displayName:Cs("Combo"),chartSubtype:"combo",chartType:"combo",category:"line",preview:"o-spreadsheet-ChartPreview.COMBO_CHART"}).add("pie",{matcher:e=>"pie"===e.type&&!e.isDoughnut,displayName:Cs("Pie"),chartSubtype:"pie",chartType:"pie",subtypeDefinition:{isDoughnut:!1},category:"pie",preview:"o-spreadsheet-ChartPreview.PIE_CHART"}).add("doughnut",{matcher:e=>"pie"===e.type&&!!e.isDoughnut,displayName:Cs("Doughnut"),chartSubtype:"doughnut",chartType:"pie",subtypeDefinition:{isDoughnut:!0},category:"pie",preview:"o-spreadsheet-ChartPreview.DOUGHNUT_CHART"}).add("gauge",{displayName:Cs("Gauge"),chartSubtype:"gauge",chartType:"gauge",category:"misc",preview:"o-spreadsheet-ChartPreview.GAUGE_CHART"}).add("scorecard",{displayName:Cs("Scorecard"),chartSubtype:"scorecard",chartType:"scorecard",category:"misc",preview:"o-spreadsheet-ChartPreview.SCORECARD_CHART"}).add("waterfall",{displayName:Cs("Waterfall"),chartSubtype:"waterfall",chartType:"waterfall",category:"misc",preview:"o-spreadsheet-ChartPreview.WATERFALL_CHART"}).add("pyramid",{displayName:Cs("Population Pyramid"),chartSubtype:"pyramid",chartType:"pyramid",category:"misc",preview:"o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART"}).add("radar",{matcher:e=>"radar"===e.type&&!e.fillArea,displayName:Cs("Radar"),chartSubtype:"radar",chartType:"radar",subtypeDefinition:{fillArea:!1},category:"misc",preview:"o-spreadsheet-ChartPreview.RADAR_CHART"}).add("filled_radar",{matcher:e=>"radar"===e.type&&!!e.fillArea,displayName:Cs("Filled Radar"),chartType:"radar",chartSubtype:"filled_radar",subtypeDefinition:{fillArea:!0},category:"misc",preview:"o-spreadsheet-ChartPreview.FILLED_RADAR_CHART"}).add("geo",{displayName:Cs("Geo Chart"),chartSubtype:"geo",chartType:"geo",category:"misc",preview:"o-spreadsheet-ChartPreview.GEO_CHART"}).add("funnel",{displayName:Cs("Funnel"),chartSubtype:"funnel",chartType:"funnel",category:"misc",preview:"o-spreadsheet-ChartPreview.FUNNEL_CHART"}).add("sunburst",{matcher:e=>"sunburst"===e.type,displayName:Cs("Sunburst"),chartSubtype:"sunburst",chartType:"sunburst",category:"hierarchical",preview:"o-spreadsheet-ChartPreview.SUNBURST_CHART"}).add("treemap",{matcher:e=>"treemap"===e.type,displayName:Cs("Tree Map"),chartType:"treemap",chartSubtype:"treemap",category:"hierarchical",preview:"o-spreadsheet-ChartPreview.TREE_MAP_CHART"}).add("calendar",{displayName:Cs("Calendar"),chartSubtype:"calendar",chartType:"calendar",category:"misc",preview:"o-spreadsheet-ChartPreview.CALENDAR_CHART"});class LZ extends Eq{copy(e){}}hP.figureHandlers.add("chart",class extends LZ{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);if("chart"!==s.tag)return;const o={...s},i=this.getters.getChartFromFigureId(e.figureId);if(!i)throw new Error(`No chart for the given id: ${e.figureId}`);const n=i.copyInSheetId(t);return{figureId:e.figureId,copiedFigure:o,copiedChart:n}}getPasteTarget(e,t,s,o){return{zones:[],figureId:(new Tr).smallUuid(),sheetId:e}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=e.sheetId,{width:r,height:a}=t.copiedFigure,l=t.copiedChart.copyInSheetId(n),c=this.getters.getMaxAnchorOffset(n,a,r);let{left:h,top:d}=o[0];const u={x:0,y:0};h>c.col&&(h=c.col,u.x=c.offset.x),d>c.row&&(d=c.row,u.y=c.offset.y),this.dispatch("CREATE_CHART",{figureId:i,chartId:(new Tr).smallUuid(),sheetId:n,definition:l.getDefinition(),col:h,row:d,offset:u,size:{height:a,width:r}}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}).add("image",class extends LZ{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);const o={...s};if("image"!==s.tag)return;const i=he(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:o,copiedImage:i,sheetId:t}}getPasteTarget(e,t,s,o){return{sheetId:e,zones:[],figureId:(new Tr).smallUuid()}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=this.getters.getActiveSheetId(),{width:r,height:a}=t.copiedFigure,l=he(t.copiedImage),c=this.getters.getMaxAnchorOffset(n,a,r);let{left:h,top:d}=o[0];const u={x:0,y:0};h>c.col&&(h=c.col,u.x=c.offset.x),d>c.row&&(d=c.row,u.y=c.offset.y),this.dispatch("CREATE_IMAGE",{figureId:i,sheetId:n,col:h,row:d,offset:u,size:{height:a,width:r},definition:l}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}).add("carousel",class extends LZ{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);if("carousel"!==s.tag)return;const o={...s},i=this.getters.getCarousel(e.figureId),n={};for(const e of i.items)if("chart"===e.type){const s=this.getters.getChart(e.chartId);if(!s)throw new Error(`No chart for the given id: ${e.chartId}`);n[e.chartId]=s.copyInSheetId(t)}return{figureId:e.figureId,copiedFigure:o,copiedCarousel:i,copiedCharts:n,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:(new Tr).smallUuid(),sheetId:e}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=e.sheetId,{width:r,height:a}=t.copiedFigure,l=this.getters.getMaxAnchorOffset(n,a,r);let{left:c,top:h}=o[0];const d={x:0,y:0};c>l.col&&(c=l.col,d.x=l.offset.x),h>l.row&&(h=l.row,d.y=l.offset.y),this.dispatch("CREATE_CAROUSEL",{figureId:i,sheetId:n,definition:{items:[]},col:c,row:h,offset:d,size:{height:a,width:r}});const u=new Tr,g=he(t.copiedCarousel.items);for(const e of g){if("chart"!==e.type)continue;const s=t.copiedCharts[e.chartId],o=u.smallUuid(),r=s.copyInSheetId(n).getDefinition();this.dispatch("CREATE_CHART",{figureId:i,chartId:o,sheetId:n,definition:r}),e.chartId=o}this.dispatch("UPDATE_CAROUSEL",{sheetId:n,figureId:i,definition:{...t.copiedCarousel,items:g}}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}),hP.cellHandlers.add("dataValidation",class extends xq{uuidGenerator=new Tr;queuedChanges={};copy(e){const{rowsIndexes:t,columnsIndexes:s}=e,o=e.sheetId,i=[];for(const e of t){const t=[];for(const i of s){const s={sheetId:o,col:i,row:e},n=this.getters.getValidationRuleForCell(s);t.push({position:s,rule:n})}i.push(t)}return{dvRules:i}}paste(e,t,s){if(this.queuedChanges={},s.pasteOption)return;const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t):this.pasteFromCopy(i,o,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,s){const o=t[0];this.pasteZone(e,o.left,o.top,s.dvRules,{isCutOperation:!0})}pasteZone(e,t,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){const r={col:t+o,row:s+n,sheetId:e};this.pasteDataValidation(a,r,i?.isCutOperation)}}pasteDataValidation(e,t,s){if(e){const o=Jt(t),i=Jt(e.position),n=e.rule;if(!n){const e=this.getters.getValidationRuleForCell(t);return void(e&&this.adaptDataValidationRule(t.sheetId,e,[],[o]))}const r=[];if(s&&r.push(i),e.position.sheetId===t.sheetId){const s=this.getDataValidationRuleToCopyTo(t.sheetId,n,!1);this.adaptDataValidationRule(e.position.sheetId,s,[o],r)}else{const s=this.getters.getValidationRuleForCell(e.position);s&&this.adaptDataValidationRule(e.position.sheetId,s,[],r);const i=this.getDataValidationRuleToCopyTo(t.sheetId,n);this.adaptDataValidationRule(t.sheetId,i,[o],[])}}}getDataValidationRuleToCopyTo(e,t,s=!0){let o=this.getters.getDataValidationRules(e).find(e=>Le(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking);const i=this.queuedChanges[e];return!o&&i&&(o=i.find(e=>Le(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),o||{...t,id:s?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,s,o){this.queuedChanges[e]||(this.queuedChanges[e]=[]);const i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...s),i.toRemove.push(...o)):this.queuedChanges[e].push({toAdd:s,toRemove:o,rule:t})}executeQueuedChanges(){for(const e in this.queuedChanges)for(const{toAdd:t,toRemove:s,rule:o}of this.queuedChanges[e]){const i=o.ranges.map(e=>e.zone),n=yt(i,s),r=yt([...n,...t],[]);0!==r.length?this.dispatch("ADD_DATA_VALIDATION_RULE",{rule:{id:o.id,criterion:o.criterion,isBlocking:o.isBlocking},ranges:r.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e}):this.dispatch("REMOVE_DATA_VALIDATION_RULE",{sheetId:e,id:o.id})}}}).add("cell",Rq).add("sheet",class extends xq{isPasteAllowed(e,t,s,o){if(!("cells"in s))return"Success";const{xSplit:i,ySplit:n}=this.getters.getPaneDivisions(e);return os(oP(t,s.cells),i,n)?"FrozenPaneOverlap":"Success"}}).add("merge",class extends xq{copy(e){const t=this.getters.getActiveSheetId(),{rowsIndexes:s,columnsIndexes:o}=e,i=[];for(const e of s){const s=[];for(const i of o){const o={col:i,row:e,sheetId:t};s.push(this.getters.getMerge(o))}i.push(s)}return{merges:i,sheetId:t}}paste(e,t,s){if(s.isCutOperation){const e=t.merges.flat().filter(De);this.dispatch("REMOVE_MERGE",{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,s)}pasteZone(e,t,s,o){for(const[i,n]of o.entries())for(const[o,r]of n.entries()){const n={col:t+o,row:s+i,sheetId:e};this.pasteMerge(r,n)}}pasteMerge(e,t){if(!e)return;if(this.getters.isInMerge(t))return;const{sheetId:s,col:o,row:i}=t;this.dispatch("ADD_MERGE",{sheetId:s,force:!0,target:[{left:o,top:i,right:o+e.right-e.left,bottom:i+e.bottom-e.top}]})}}).add("table",class extends xq{copy(e,t,s="copyPaste"){const o=e.sheetId,{rowsIndexes:i,columnsIndexes:n,zones:r}=e,a=new Set,l=[];for(const e of i){const c=[];l.push(c);for(const l of n){const n={col:l,row:e,sheetId:o},h=this.getters.getTable(n);if(!h){c.push({});continue}const d=this.getters.getCoreTable(n),u=d?.range.zone;let g;if(!a.has(h.id)&&d&&u&&r.some(e=>Wt(u,e))){a.add(h.id);let{numberOfRows:e}=$t(u);for(let s=u.top;s<=u.bottom;s++)t||i.includes(s)||e--;const s=d.range,o=this.getters.extendRange(d.range,"ROW",s.zone.top+e-1-s.zone.bottom);g={range:this.getters.getRangeData(o),config:d.config,type:d.type}}"shiftCells"!==s&&c.push({table:g,style:this.getTableStyleToCopy(n),isWholeTableCopied:a.has(h.id)})}}return{tableCells:l,sheetId:e.sheetId}}getTableStyleToCopy(e){const t=this.getters.getCellTableStyle(e),s=this.getters.getCellStyle(e),o=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Ue(s)},border:{...o,...Ue(i)}}}paste(e,t,s){const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t,s):this.pasteFromCopy(i,o,t.tableCells,s)}pasteFromCut(e,t,s,o){for(const e of s.tableCells)for(const t of e)t.table&&this.dispatch("REMOVE_TABLE",{sheetId:s.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});const i=t[0];this.pasteZone(e,i.left,i.top,s.tableCells,o)}pasteZone(e,t,s,o,i){for(let n=0;n<o.length;n++){const r=o[n];for(let o=0;o<r.length;o++){const a=r[o];if(!a)continue;const l={col:t+o,row:s+n,sheetId:e};this.pasteTableCell(e,a,l,i)}}if(1===o.length)for(let i=0;i<o[0].length;i++)this.dispatch("AUTOFILL_TABLE_COLUMN",{col:t+i,row:s,sheetId:e})}pasteTableCell(e,t,s,o){if(t.table&&!o?.pasteOption){const{range:o}=t.table,i=$t(this.getters.getRangeFromRangeData(o).zone),n={left:s.col,top:s.row,right:s.col+i.numberOfCols-1,bottom:s.row+i.numberOfRows-1};this.dispatch("CREATE_TABLE",{sheetId:s.sheetId,ranges:[this.getters.getRangeDataFromZone(e,n)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(s)||"asValue"===o?.pasteOption||(o?.pasteOption||t.isWholeTableCopied)&&"onlyFormat"!==o?.pasteOption||(t.style?.style&&this.dispatch("UPDATE_CELL",{...s,style:t.style.style}),t.style?.border&&this.dispatch("SET_BORDER",{...s,border:t.style.border}))}}).add("conditionalFormat",class extends xq{uuidGenerator=new Tr;queuedChanges={};copy(e){if(!e.zones.length)return;const{rowsIndexes:t,columnsIndexes:s}=e,o=e.sheetId,i=[];for(const e of t){const t=[];for(const i of s){const s=Array.from(this.getters.getRulesByCell(o,i,e));t.push({position:{col:i,row:e,sheetId:o},rules:s})}i.push(t)}return{cfRules:i}}paste(e,t,s){if(this.queuedChanges={},"asValue"===s.pasteOption)return;const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t):this.pasteFromCopy(i,o,t.cfRules,s),this.executeQueuedChanges()}pasteFromCut(e,t,s){const o=t[0];this.pasteZone(e,o.left,o.top,s.cfRules,{isCutOperation:!0})}pasteZone(e,t,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){const r={col:t+o,row:s+n,sheetId:e};this.pasteCf(a,r,i?.isCutOperation)}}pasteCf(e,t,s){if(e?.rules&&e.rules.length>0){const o=Jt(e.position),i=Jt(t);for(const n of e.rules){const r=[];if(s&&r.push(o),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,n,[i],r);else{this.adaptCFRules(e.position.sheetId,n,[],r);const s=this.getCFToCopyTo(t.sheetId,n);this.adaptCFRules(t.sheetId,s,[i],[])}}}}adaptCFRules(e,t,s,o){this.queuedChanges[e]||(this.queuedChanges[e]=[]);const i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...s),i.toRemove.push(...o)):this.queuedChanges[e].push({toAdd:s,toRemove:o,cf:t})}executeQueuedChanges(){for(const e in this.queuedChanges)for(const{toAdd:t,toRemove:s,cf:o}of this.queuedChanges[e]){const i=this.getters.getAdaptedCfRanges(e,o,t,s);i&&(0!==i.length?this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:o.id,rule:o.rule,stopIfTrue:o.stopIfTrue},ranges:i,sheetId:e}):this.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:o.id,sheetId:e}))}}getCFToCopyTo(e,t){let s=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&Le(e.rule,t.rule));const o=this.queuedChanges[e];return!s&&o&&(s=o.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&Le(e.cf.rule,t.rule))?.cf),s||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}}).add("references",class extends xq{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,s){if(s.isCutOperation){const s=e.zones[0];this.dispatch("MOVE_RANGES",{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:s.left,row:s.top})}}}).add("border",class extends xq{copy(e){const t=e.sheetId;if(0===e.zones.length)return;const s=[];let o=0;for(const i of ve(e.columnsIndexes)){let n=0;for(const r of ve(e.rowsIndexes)){const e={left:i[0],right:i[i.length-1],top:r[0],bottom:r[r.length-1]};s.push(...this.getters.getBorders(t,e).map(({zone:t,style:s})=>({zone:{left:t.left-e.left+o,right:t.right&&t.right-e.left+o,top:t.top-e.top+n,bottom:t.bottom&&t.bottom-e.top+n},style:s}))),n+=r.length}o+=i.length}return{borders:s,width:e.columnsIndexes.length,height:e.rowsIndexes.length}}paste(e,t,s){const o=e.sheetId;if("asValue"===s.pasteOption)return;const i=e.zones;if(s.isCutOperation){const{left:e,top:s}=i[0];this.pasteBorderZone(o,e,s,t.borders)}else for(const e of i)for(const s of sP(e,t.width,t.height))this.pasteBorderZone(o,s.left,s.top,t.borders)}pasteBorderZone(e,t,s,o){for(const i of o){const o={left:i.zone.left+t,right:i.zone.right&&i.zone.right+t||i.zone.left+t,top:i.zone.top+s,bottom:i.zone.bottom&&i.zone.bottom+s||i.zone.top+s};for(const[t,s]of this.getOptimalBorderCommands(i.style))s&&this.dispatch("SET_ZONE_BORDERS",{sheetId:e,target:[o],border:{position:t,...s}})}}getOptimalBorderCommands(e){const t=Le(e.horizontal,e.vertical),s=Le(e.left,e.right,e.top,e.bottom);return t&&s&&Le(e.horizontal,e.left)?[["all",e.top]]:t&&s?[["hv",e.horizontal],["external",e.top]]:s?[["h",e.horizontal],["v",e.vertical],["external",e.top]]:t?[["hv",e.horizontal],["top",e.top],["bottom",e.bottom],["left",e.left],["right",e.right]]:[["h",e.horizontal],["v",e.vertical],["top",e.top],["bottom",e.bottom],["left",e.left],["right",e.right]]}}).add("style",class extends xq{copy(e){const t=e.sheetId;if(0===e.zones.length)return;const s=[];let o=0;for(const i of ve(e.columnsIndexes)){let n=0;for(const r of ve(e.rowsIndexes)){const e={left:i[0],right:i[i.length-1],top:r[0],bottom:r[r.length-1]};s.push(...this.getters.getZoneStyles(t,e).map(t=>({zone:{left:t.zone.left-e.left+o,right:t.zone.right&&t.zone.right-e.left+o,top:t.zone.top-e.top+n,bottom:t.zone.bottom&&t.zone.bottom-e.top+n},style:t.style}))),n+=r.length}o+=i.length}return{styles:s,width:e.columnsIndexes.length,height:e.rowsIndexes.length}}paste(e,t,s){const o=e.sheetId;if("asValue"===s.pasteOption)return;const i=e.zones;if(s.isCutOperation){const{left:e,top:s}=i[0];this.pasteStyleZone(o,e,s,t.styles)}else for(const e of i)for(const s of sP(e,t.width,t.height))this.pasteStyleZone(o,s.left,s.top,t.styles)}pasteStyleZone(e,t,s,o){for(const i of o){const o={left:i.zone.left+t,right:i.zone.right&&i.zone.right+t||i.zone.left+t,top:i.zone.top+s,bottom:i.zone.bottom&&i.zone.bottom+s||i.zone.top+s};this.dispatch("SET_FORMATTING",{sheetId:e,target:[o],style:i.style})}}});const VZ={},zZ={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:O,HEADER_WIDTH:F,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:P,SCROLLBAR_WIDTH:15},HZ={autoCompleteProviders:PV,autofillModifiersRegistry:DF,autofillRulesRegistry:OF,cellMenuRegistry:sB,colMenuRegistry:dG,errorTypes:Es,linkMenuRegistry:Rz,functionRegistry:zf,featurePluginRegistry:mP,iconsOnCellRegistry:AO,statefulUIPluginRegistry:fP,coreViewsPluginRegistry:vP,corePluginRegistry:pP,rowMenuRegistry:vG,sidePanelRegistry:hq,figureRegistry:oV,chartSidePanelComponentRegistry:h$,chartComponentRegistry:BL,chartRegistry:vR,chartSubtypeRegistry:qF,topbarMenuRegistry:Mq,topbarComponentRegistry:$q,clickableCellRegistry:_q,otRegistry:Wx,inverseCommandRegistry:OR,urlRegistry:uv,cellPopoverRegistry:rV,numberFormatMenuRegistry:Oq,repeatLocalCommandTransformRegistry:GF,repeatCommandTransformRegistry:BF,clipboardHandlersRegistries:hP,pivotRegistry:AD,pivotTimeAdapterRegistry:Qg,pivotSidePanelRegistry:Y$,pivotNormalizationValueRegistry:Op,supportedPivotPositionalFormulaRegistry:yq,pivotToFunctionValueRegistry:Fp,migrationStepRegistry:T_,chartJsExtensionRegistry:Hv},UZ={arg:us,isEvaluationError:Co,toBoolean:Po,toJsDate:Mo,toNumber:Eo,toString:Do,toNormalizedPivotValue:Tp,toFunctionPivotValue:_p,toXC:St,toZone:_t,toUnboundedZone:At,toCartesian:bt,numberToLetters:lt,lettersToNumber:ct,UuidGenerator:Tr,formatValue:zi,createCurrencyFormat:en,ColorGenerator:yb,computeTextWidth:IS,createEmptyWorkbookData:V_,createEmptySheet:L_,createEmptyExcelSheet:z_,rgbaToHex:eb,colorToRGBA:tb,positionToZone:Jt,isDefined:De,isMatrix:Ns,lazy:Me,genericRepeat:Wq,createAction:Cv,createActions:Sv,transformRangeData:ls,deepEquals:Le,overlap:Bt,union:Vt,isInside:Gt,deepCopy:he,expandZoneOnInsertion:Mt,reduceZoneOnDeletion:Lt,unquote:ue,getMaxObjectId:Sp,getFunctionsFromTokens:hv,getFirstPivotFunction:EF,getNumberOfPivotFunctions:xF,parseDimension:Ip,isDateOrDatetimeField:wp,makeFieldProposal:bq,insertTokenAfterArgSeparator:function(e,t){let s=e.end;const o=e.end;"ARG_SEPARATOR"!==e.type&&(s=e.start),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)},insertTokenAfterLeftParenthesis:function(e,t){let s=e.end;const o=e.end;"LEFT_PAREN"!==e.type&&(s=e.start),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)},mergeContiguousZones:ns,getPivotHighlights:N$,pivotTimeAdapter:ep,UNDO_REDO_PIVOT_COMMANDS:AF,createPivotFormula:Rp,areDomainArgsFieldsValid:xp,splitReference:yr,sanitizeSheetName:pe,getUniqueText:rt,isNumber:mo,isDateTime:Ks,createCustomFields:Vp,schemeToColorScale:w_,isDateTimeFormat:ji,jsDateToNumber:so,numberToJsDate:eo,DateTime:Ls,parseFormat:Ai,isFormula:at},BZ={isMarkdownLink:Ie,parseMarkdownLink:xe,markdownLink:Ee,openLink:vv,urlRepresentation:fv},GZ={Checkbox:hz,Section:YV,RoundColorPicker:XV,ChartDataSeries:SW,ChartErrorSection:yW,ChartLabelRange:CW,ChartTitle:xW,ChartPanel:p$,ChartFigure:tV,ChartJsComponent:xN,ClickableCellSortIcon:Cq,ZoomableChartJsComponent:ML,Grid:vq,GridOverlay:BG,ScorecardChart:ZN,GaugeChartComponent:HL,LineConfigPanel:YW,BarConfigPanel:wW,PieChartDesignPanel:JW,GenericChartConfigPanel:IW,ChartWithAxisDesignPanel:NW,GenericZoomableChartDesignPanel:kW,LineChartDesignPanel:XW,GaugeChartConfigPanel:GW,GaugeChartDesignPanel:WW,ScorecardChartConfigPanel:t$,ScorecardChartDesignPanel:s$,GeoChartDesignPanel:ZW,RadarChartDesignPanel:QW,WaterfallChartDesignPanel:c$,ComboChartDesignPanel:UW,FunnelChartDesignPanel:BW,SunburstChartDesignPanel:o$,TreeMapChartDesignPanel:l$,ChartTypePicker:u$,FigureComponent:iV,MenuPopover:JL,Popover:jL,SelectionInput:iz,ValidationMessages:MG,AddDimensionButton:z$,PivotDimensionGranularity:U$,PivotDimensionOrder:B$,PivotDimension:H$,PivotLayoutConfigurator:$$,PivotHTMLRenderer:wq,PivotDeferUpdate:k$,PivotTitleSection:q$,CogWheelMenu:fW,TextInput:hW,SidePanelCollapsible:gV,RadioSelection:TW,GeoChartRegionSelectSection:$W,ChartDashboardMenu:QL,FullScreenFigure:Iq,NumberInput:OW,TopBar:xZ,Composer:_V},WZ={useDragAndDropListItems:KV,useHighlights:v$,useHighlightsOnHover:f$},$Z={useStoreProvider:Rv,DependencyContainer:wv,CellPopoverStore:aV,ComposerFocusStore:zv,CellComposerStore:RG,FindAndReplaceStore:T$,HighlightStore:NV,DelayedHoveredCellStore:nV,HoveredTableStore:zG,ModelStore:Fv,NotificationStore:kV,RendererStore:kv,SelectionInputStore:oz,SpreadsheetStore:Lv,useStore:Tv,useLocalStore:Av,SidePanelStore:pq,PivotSidePanelStore:Z$,PivotMeasureDisplayPanelStore:P$,ClientFocusStore:SG,GridRenderer:XG};const qZ={DEFAULT_LOCALE:gi,HIGHLIGHT_COLOR:o,PIVOT_TABLE_CONFIG:te,ChartTerms:Bg,FIGURE_ID_SPLITTER:W,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2},ZZ={...EL,...rL};e.AbstractCellClipboardHandler=xq,e.AbstractChart=zO,e.AbstractFigureClipboardHandler=LZ,e.CellErrorType=ws,e.ClientDisconnectedError=_R,e.CorePlugin=U_,e.CoreViewPlugin=UD,e.DEFAULT_LOCALE=gi,e.DEFAULT_LOCALES=ui,e.DispatchResult=Lr,e.EvaluationError=xs,e.LocalTransportService=Bx,e.Model=class extends Iv{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},s=[],o=new Tr,i=!1){const n=performance.now();console.debug("##### Model creation #####"),super(),bs===fs&&Ss===vs&&(Ss=()=>!0),s=N_(e,s);const r=F_(e,i);this.state=new CP,this.uuidGenerator=o,this.config=this.setupConfig(t),this.session=this.setupSession(r.revisionId),this.coreGetters={},this.range=new bP(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.adaptFormulaStringDependencies=this.range.adaptFormulaStringDependencies.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.getters={isReadonly:()=>"readonly"===this.config.mode||"dashboard"===this.config.mode,isDashboard:()=>"dashboard"===this.config.mode},this.selection=new yP(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(const e of pP.getAll())this.setupCorePlugin(e,r);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(s);for(const e of vP.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(const e of fP.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(const e of mP.getAll()){const t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.joinSession(),t.snapshotRequested||e["[Content_Types].xml"]&&!this.getters.isReadonly()){const e=performance.now();console.debug("Snapshot requested"),this.session.snapshot(this.exportData()),console.debug("Snapshot taken in",performance.now()-e,"ms")}console.debug("Model created in",performance.now()-n,"ms"),console.debug("######")}joinSession(){this.session.join(this.config.client)}async leaveSession(){const e=this.getters.isReadonly()?void 0:Me(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(const s of e.getters){if(!(s in t))throw new Error(`Invalid getter name: ${s} for plugin ${t.constructor}`);if(s in this.getters)throw new Error(`Getter "${s}" is already defined.`);this.getters[s]=t[s].bind(t)}for(const s of e.layers)this.renderers[s]||(this.renderers[s]=[]),this.renderers[s].push(t);return t}setupCoreViewPlugin(e){const t=new e(this.coreViewPluginConfig);for(const s of e.getters){if(!(s in t))throw new Error(`Invalid getter name: ${s} for plugin ${t.constructor}`);if(s in this.getters)throw new Error(`Getter "${s}" is already defined.`);this.getters[s]=t[s].bind(t)}return t}setupCorePlugin(e,t){const s=new e(this.corePluginConfig);for(const t of e.getters){if(!(t in s))throw new Error(`Invalid getter name: ${t} for plugin ${s.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=s[t].bind(s)}s.import(t),this.corePlugins.push(s),this.coreHandlers.push(s),this.handlers.push(s)}onRemoteRevisionReceived({commands:e}){for(const t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new DR(HR({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{this.checkDispatchAllowed(e).isSuccessful?(this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1):this.dispatchToHandlers(this.coreHandlers,{type:"UNDO",commands:[e]})}}),this.config.transportService,e)}setupSessionEvents(){this.session.on("remote-revision-received",this,this.onRemoteRevisionReceived),this.session.on("revision-undone",this,({commands:e})=>{this.dispatchFromCorePlugin("UNDO",{commands:e}),this.finalize()}),this.session.on("revision-redone",this,({commands:e})=>{this.dispatchFromCorePlugin("REDO",{commands:e}),this.finalize()}),this.session.on("unexpected-revision-id",this,()=>this.trigger("unexpected-revision-id")),this.session.on("collaborative-event-received",this,()=>{this.trigger("update")})}setupConfig(e){const t=e.client||{id:this.uuidGenerator.smallUuid(),name:Cs("Anonymous").toString()},s=e.transportService||new Bx,o="readonly"===e.mode||"dashboard"===e.mode;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:o?new Gx(s):s,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),raiseBlockingErrorUI:e=>this.trigger("raise-error-ui",{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){const t=e.loadLocales||(()=>Promise.resolve(ui));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,custom:this.config.custom,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){const t=kr(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>"Success"!==e)?new Lr(t.flat()):Lr.Success}checkDispatchAllowedCoreCommand(e){const t=this.corePlugins.map(t=>t.allowDispatch(e));return t.push(this.range.allowDispatch(e)),t}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0,this.trigger("command-finalized")}canDispatch=(e,t)=>this.checkDispatchAllowed(RM(e,t));dispatch=(e,t)=>{const s=RM(e,t),o=this.status;if(this.getters.isReadonly()&&(i=s,!Mr.has(i.type)))return new Lr("Readonly");var i;if(!this.session.canApplyOptimisticUpdate())return new Lr("WaitingSessionConfirmation");switch(o){case 0:const t=this.checkDispatchAllowed(s);if(!t.isSuccessful)return this.trigger("update"),t;this.status=1;const{changes:o,commands:i}=this.state.recordChanges(()=>{const t=performance.now();kr(s)&&this.state.addCommand(s),this.dispatchToHandlers(this.handlers,s),this.finalize();const o=performance.now()-t;o>5&&console.debug(e,o,"ms")});this.session.save(s,i,o),this.status=0,this.trigger("update");break;case 1:if(kr(s)){const e=this.checkDispatchAllowed(s);if(!e.isSuccessful)return e;this.state.addCommand(s)}this.dispatchToHandlers(this.handlers,s);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(kr(s))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,s)}return Lr.Success};dispatchFromCorePlugin=(e,t)=>{const s=RM(e,t),o=this.status;this.status=2;const i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,s),this.status=o,Lr.Success};dispatchToHandlers(e,t){const s=kr(t);for(const o of e)!s&&o instanceof U_||o.beforeHandle(t);for(const o of e)!s&&o instanceof U_||o.handle(t);this.trigger("command-dispatched",t)}drawLayer(e,t){const s=this.renderers[t];if(s)for(const o of s)e.ctx.save(),o.drawLayer(e,t),e.ctx.restore()}exportData(){let e=V_();for(const t of this.handlers)t instanceof U_&&t.export(e);return e.revisionId=this.session.getRevisionId()||G,e=he(e),e}updateMode(e){this.config.mode=e,this.trigger("update")}async exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={...V_(),sheets:[z_(O_,"Sheet1")]};for(const t of this.handlers)t instanceof Hr&&await t.exportForExcel(e);return e=he(e),wM(e)}},e.PivotRuntimeDefinition=Q_,e.Registry=Jg,e.Revision=AR,e.SPREADSHEET_DIMENSIONS=zZ,e.Spreadsheet=TZ,e.SpreadsheetPivotTable=fD,e.UIPlugin=Ur,e.__info__=VZ,e.addFunction=function e(t,s){return zf.add(t,s),{addFunction:(t,s)=>e(t,s)}},e.addRenderingLayer=function(e,t){if(Mv[e])throw new Error(`Layer ${e} already exists`);Mv[e]=t},e.astToFormula=yF,e.categories=Hf,e.chartHelpers=ZZ,e.compile=zx,e.compileTokens=Hx,e.components=GZ,e.constants=qZ,e.convertAstNodes=iv,e.coreTypes=Nr,e.createAutocompleteArgumentsProvider=Tq,e.findCellInNewZone=Kt,e.functionCache=Vx,e.getCaretDownSvg=$R,e.getCaretUpSvg=qR,e.helpers=UZ,e.hooks=WZ,e.invalidateCFEvaluationCommands=Or,e.invalidateChartEvaluationCommands=_r,e.invalidateDependenciesCommands=Dr,e.invalidateEvaluationCommands=Ar,e.iterateAstNodes=nv,e.links=BZ,e.load=F_,e.parse=sv,e.parseTokens=ov,e.readonlyAllowedCommands=Mr,e.registries=HZ,e.setDefaultSheetViewSize=function(e){K=e},e.setTranslationMethod=function(e,t=()=>!0){bs=e,Ss=t},e.stores=$Z,e.tokenColors=ae,e.tokenize=Kc,VZ.version="19.1.1",VZ.date="2025-12-26T10:26:46.141Z",VZ.hash="e6313bd"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|
|
861
|
+
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){const{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{y:e}=this.env.model.getters.getMainViewportRect(),t=this.env.model.getters.getScrollBarWidth();return{top:`${this.props.topOffset+e}px`,right:"0px",width:`${t}px`,bottom:BN()?`${t}px`:"0"}}onScroll(e){const{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:t,offsetY:e})}}class aW extends t.Component{static template="o-spreadsheet-Selection";static props={};static components={Highlight:sW};get highlightProps(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getUnboundedZone(e,this.env.model.getters.getSelectedZone());return{range:this.env.model.getters.getRangeFromZone(e,t),color:l}}}function lW({refName:e}){const s=t.useRef(e);t.useEffect(e=>{e?.focus()},()=>[s.el])}class cW extends t.Component{static props={value:[Number,String],onChange:Function,class:{type:String,optional:!0},id:{type:String,optional:!0},placeholder:{type:String,optional:!0},autofocus:{type:Boolean,optional:!0},alwaysShowBorder:{type:Boolean,optional:!0},selectContentOnFocus:{type:Boolean,optional:!0}};refName="input";inputRef;setup(){this.inputRef=t.useRef(this.refName),t.useExternalListener(window,"click",e=>{e.target!==this.inputRef.el&&this.inputRef.el?.value!==this.props.value&&this.save()},{capture:!0}),this.props.autofocus&&lW({refName:this.refName}),t.onWillUpdateProps(e=>{document.activeElement!==this.inputRef.el&&this.inputRef.el&&(this.inputRef.el.value=e.value)}),t.onMounted(()=>{this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString())})}onKeyDown(e){switch(e.key){case"Enter":this.save(),e.preventDefault(),e.stopPropagation();break;case"Escape":this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString(),this.inputRef.el.blur()),e.preventDefault(),e.stopPropagation()}}save(e=!1){const t=(this.inputRef.el?.value||"").trim();t!==this.props.value.toString()&&this.props.onChange(t),e||this.inputRef.el?.blur()}onMouseDown(e){e.target!==document.activeElement&&this.props.selectContentOnFocus&&(e.preventDefault(),e.stopPropagation())}onMouseUp(e){const t=e.target;t!==document.activeElement&&this.props.selectContentOnFocus&&(t.focus(),this.props.selectContentOnFocus&&t.select(),e.preventDefault(),e.stopPropagation())}}class hW extends cW{static template="o-spreadsheet-TextInput";static components={};static props={...cW.props,errorMessage:{type:String,optional:!0}};get inputClass(){return[this.props.class,"w-100 os-input",this.props.alwaysShowBorder?"o-input-border":void 0,this.props.errorMessage?"o-invalid":void 0].filter(De).join(" ")}}class dW extends t.Component{static template="o-spreadsheet-ActionButton";static props={action:Object,hasTriangleDownIcon:{type:Boolean,optional:!0},selectedColor:{type:String,optional:!0},class:{type:String,optional:!0},onClick:{type:Function,optional:!0}};actionButton=Cv(this.props.action);setup(){t.onWillUpdateProps(e=>{e.action!==this.props.action&&(this.actionButton=Cv(e.action))})}get isVisible(){return this.actionButton.isVisible(this.env)}get isEnabled(){return this.actionButton.isEnabled(this.env)}get isActive(){return this.actionButton.isActive?.(this.env)}get title(){const e=this.actionButton.name(this.env),t=this.actionButton.description(this.env);return e+(t?` (${t})`:"")}get iconTitle(){return this.actionButton.icon(this.env)}onClick(e){this.isEnabled&&(this.props.onClick?.(e),this.actionButton.execute?.(this.env))}get buttonStyle(){return this.props.selectedColor?JF({"border-bottom":`4px solid ${this.props.selectedColor}`,height:"16px","margin-top":"2px"}):""}}class uW extends t.Component{static template="o-spreadsheet-ColorPickerWidget";static props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={ColorPicker:jV};colorPickerButtonRef=t.useRef("colorPickerButton");get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:"border-bottom-style: hidden"}get colorPickerAnchorRect(){const e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}}class gW extends t.Component{static template="o-spreadsheet-NumberEditor";static props={currentValue:Number,onValueChange:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String,valueIcon:{type:String,optional:!0},min:Number,max:Number,title:String,valueList:Array};static defaultProps={onFocusInput:()=>{}};static components={Popover:jL};dropdown=t.useState({isOpen:!1});inputRef=t.useRef("inputNumber");rootEditorRef=t.useRef("NumberEditor");valueListRef=t.useRef("numberList");DOMFocusableElementStore;setup(){this.DOMFocusableElementStore=Tv(mV),t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.onWillUpdateProps(e=>{this.inputRef.el&&document.activeElement!==this.inputRef.el&&(this.inputRef.el.value=e.currentValue)}),t.onMounted(()=>{this.inputRef.el&&(this.inputRef.el.value=this.props.currentValue.toString())})}get popoverProps(){const{x:e,y:t,width:s,height:o}=this.rootEditorRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:s,height:o},positioning:"bottom-left",verticalOffset:0}}onExternalClick(e){AN(this.valueListRef.el,e)||AN(this.rootEditorRef.el,e)||this.closeList()}toggleList(){this.dropdown.isOpen?this.closeList():(this.props.onToggle?.(),this.inputRef.el.focus())}closeList(){this.dropdown.isOpen=!1}setValue(e){const t=me(Math.floor(parseFloat(e)),this.props.min,this.props.max);this.props.onValueChange(t),this.closeList()}setValueFromInput(e){this.setValue(e.target.value)}setValueFromList(e){this.setValue(e)}get currentValue(){return`${this.props.currentValue}`}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if("Enter"===e.key||"Escape"===e.key){this.closeList();const t=e.target;"Escape"===e.key&&(t.value=`${this.props.currentValue}`),this.props.onToggle?.()}if("Tab"===e.key)return e.preventDefault(),e.stopPropagation(),this.closeList(),void this.DOMFocusableElementStore.focus()}}class pW extends t.Component{static template="o-spreadsheet-FontSizeEditor";static components={NumberEditor:gW};static props={currentFontSize:Number,onFontSizeChanged:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String};static defaultProps={onFocusInput:()=>{}};fontSizes=ee}class mW extends t.Component{static template="o-spreadsheet.TextStyler";static components={ColorPickerWidget:uW,ActionButton:dW,FontSizeEditor:pW};static props={style:Object,updateStyle:{type:Function,optional:!0},defaultStyle:{type:Object,optional:!0},hasVerticalAlign:{type:Boolean,optional:!0},hasHorizontalAlign:{type:Boolean,optional:!0},hasBackgroundColor:{type:Boolean,optional:!0},class:{type:String,optional:!0}};openedEl=null;setup(){t.useExternalListener(window,"click",this.onExternalClick)}state=t.useState({activeTool:""});updateFontSize(e){this.props.updateStyle?.({...this.props.style,fontSize:e})}toggleDropdownTool(e,t){const s=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=s?"":e,this.openedEl=s?null:t.target}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onTextColorChange(e){this.props.updateStyle?.({...this.props.style,color:e}),this.closeMenus()}onFillColorChange(e){this.props.updateStyle?.({...this.props.style,fillColor:e}),this.closeMenus()}updateAlignment(e){this.props.updateStyle?.({...this.props.style,align:e}),this.closeMenus()}updateVerticalAlignment(e){this.props.updateStyle?.({...this.props.style,verticalAlign:e}),this.closeMenus()}toggleBold(){this.props.updateStyle?.({...this.props.style,bold:!this.bold})}toggleItalic(){this.props.updateStyle?.({...this.props.style,italic:!this.italic})}closeMenus(){this.state.activeTool="",this.openedEl=null}get align(){return this.props.style.align??this.props.defaultStyle?.align}get verticalAlign(){return this.props.style.verticalAlign||this.props.defaultStyle?.verticalAlign}get bold(){return this.props.style.bold??this.props.defaultStyle?.bold}get italic(){return this.props.style.italic??this.props.defaultStyle?.italic}get currentFontSize(){return this.props.style.fontSize??this.props.defaultStyle?.fontSize??k}get boldButtonAction(){return{name:Cs("Bold"),execute:()=>this.toggleBold(),isActive:()=>this.bold||!1,icon:"o-spreadsheet-Icon.BOLD"}}get italicButtonAction(){return{name:Cs("Italic"),execute:()=>this.toggleItalic(),isActive:()=>this.italic||!1,icon:"o-spreadsheet-Icon.ITALIC"}}get horizontalAlignButtonAction(){let e="o-spreadsheet-Icon.ALIGN_LEFT";return"center"===this.align?e="o-spreadsheet-Icon.ALIGN_CENTER":"right"===this.align&&(e="o-spreadsheet-Icon.ALIGN_RIGHT"),{name:Cs("Horizontal alignment"),icon:e}}get horizontalAlignActions(){return[{name:Cs("Left"),execute:()=>this.updateAlignment("left"),isActive:()=>"left"===this.align,icon:"o-spreadsheet-Icon.ALIGN_LEFT"},{name:Cs("Center"),execute:()=>this.updateAlignment("center"),isActive:()=>"center"===this.align,icon:"o-spreadsheet-Icon.ALIGN_CENTER"},{name:Cs("Right"),execute:()=>this.updateAlignment("right"),isActive:()=>"right"===this.align,icon:"o-spreadsheet-Icon.ALIGN_RIGHT"}]}get verticalAlignButtonAction(){let e="o-spreadsheet-Icon.ALIGN_MIDDLE";return"top"===this.verticalAlign?e="o-spreadsheet-Icon.ALIGN_TOP":"bottom"===this.verticalAlign&&(e="o-spreadsheet-Icon.ALIGN_BOTTOM"),{name:Cs("Vertical alignment"),icon:e}}get verticalAlignActions(){return[{name:Cs("Top"),execute:()=>this.updateVerticalAlignment("top"),isActive:()=>"top"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_TOP"},{name:Cs("Middle"),execute:()=>this.updateVerticalAlignment("middle"),isActive:()=>"middle"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},{name:Cs("Bottom"),execute:()=>this.updateVerticalAlignment("bottom"),isActive:()=>"bottom"===this.verticalAlign,icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"}]}}class fW extends t.Component{static template="o-spreadsheet-CogWheelMenu";static components={MenuPopover:JL};static props={items:Array};buttonRef=t.useRef("button");menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});menuId=this.env.model.uuidGenerator.uuidv4();toggleMenu(e){e.closedMenuId!==this.menuId&&(this.menuState.isOpen=!this.menuState.isOpen,this.menuState.anchorRect=FN(this.buttonRef.el),this.menuState.menuItems=Sv(this.props.items))}}class vW extends t.Component{static template="o-spreadsheet-CarouselPanel";static props={onCloseSidePanel:Function,figureId:String};static components={Section:YV,TextInput:hW,TextStyler:mW,CogWheelMenu:fW};DEFAULT_CAROUSEL_TITLE_STYLE=ie;dragAndDrop=KV();previewListRef=t.useRef("previewList");setup(){let e=[...this.carouselItems];t.onWillUpdateProps(()=>{Le(this.carouselItems,e)||this.dragAndDrop.cancel(),e=[...this.carouselItems]})}get carouselItems(){return this.env.model.getters.getCarousel(this.props.figureId).items}get title(){return this.env.model.getters.getCarousel(this.props.figureId).title}get carousel(){return this.env.model.getters.getCarousel(this.props.figureId)}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[this.getItemId(e)]||""}getItemId(e){return"chart"===e.type?e.chartId:"transparent-carousel"}addNewChartToCarousel(){this.env.model.dispatch("ADD_NEW_CHART_TO_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId})}get hasDataView(){return this.carouselItems.some(e=>"carouselDataView"===e.type)}isCarouselItemActive(e){return Le(this.env.model.getters.getSelectedCarouselItem(this.props.figureId),e)}addDataViewToCarousel(){const e=this.env.model.getters.getCarousel(this.props.figureId);this.updateItems([...e.items,{type:"carouselDataView"}])}activateCarouselItem(e){this.env.model.dispatch("UPDATE_CAROUSEL_ACTIVE_ITEM",{figureId:this.props.figureId,sheetId:this.carouselSheetId,item:e})}editCarouselItem(e){"chart"===e.type&&(this.activateCarouselItem(e),this.env.model.dispatch("SELECT_FIGURE",{figureId:this.props.figureId}),this.env.openSidePanel("ChartPanel",{chartId:e.chartId}))}renameCarouselItem(e,t){const s=t.trim();if(!s||s===this.getItemTitle(e).toString())return;const o=[...this.carouselItems],i=this.carouselItems.findIndex(t=>Le(t,e));-1!==i&&(o[i]={...e,title:s},this.updateItems(o))}deleteCarouselItem(e){const t=this.env.model.getters.getCarousel(this.props.figureId).items.filter(t=>!Le(t,e));this.updateItems(t)}popOutCarouselItem(e){"chart"===e.type&&this.env.model.dispatch("POPOUT_CHART_FROM_CAROUSEL",{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId})}duplicateCarouselChart(e){"chart"===e.type&&this.env.model.dispatch("DUPLICATE_CAROUSEL_CHART",{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId,duplicatedChartId:this.env.model.uuidGenerator.smallUuid()})}onDragHandleMouseDown(e,t){if(0!==t.button)return;const s=Array.from(this.previewListRef.el.children).map(e=>FN(e)),o=this.carouselItems.map((e,t)=>({id:this.getItemId(e),size:s[t].height,position:s[t].y}));this.dragAndDrop.start("vertical",{draggedItemId:this.getItemId(e),initialMousePosition:t.clientY,items:o,scrollableContainerEl:this.previewListRef.el,onDragEnd:(t,s)=>this.onDragEnd(e,s)})}onDragEnd(e,t){const s=this.carouselItems.findIndex(t=>Le(t,e));if(-1===s||s===t)return;const o=[...this.env.model.getters.getCarousel(this.props.figureId).items];o.splice(s,1),o.splice(t,0,e),this.updateItems(o)}getItemTitle(e){return jF(this.env.model.getters,e)}getItemPreview(e){return function(e,t){if("carouselDataView"===t.type)return"o-spreadsheet-Icon.DATA";const s=e.getChartDefinition(t.chartId);return(qF.getAll().find(e=>e.matcher?.(s))||qF.get(s.type)).preview}(this.env.model.getters,e)}updateItems(e){this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...this.carousel,items:e}})}updateTitleText(e){const t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,text:e}}})}updateTitleStyle(e){const t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch("UPDATE_CAROUSEL",{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,...e}}})}get carouselAddChartInfoMessage(){return Cs("Add a chart to the carousel. You can also add a chart by dragging and dropping it over the carousel figure.")}getCogWheelMenuItems(e){const t=[];return"chart"===e.type&&(t.push({name:Cs("Edit chart"),execute:()=>this.editCarouselItem(e),icon:"o-spreadsheet-Icon.EDIT"}),t.push({name:Cs("Pop out chart"),execute:()=>this.popOutCarouselItem(e),icon:"o-spreadsheet-Icon.EXTERNAL"}),t.push({name:Cs("Duplicate chart"),execute:()=>this.duplicateCarouselChart(e),icon:"o-spreadsheet-Icon.COPY"})),t.push({name:Cs("Delete item"),execute:()=>this.deleteCarouselItem(e),icon:"o-spreadsheet-Icon.TRASH"}),t}get carouselSheetId(){const e=this.env.model.getters.getFigureSheetId(this.props.figureId);if(!e)throw new Error("Could not find the sheetId of the carousel figure");return e}get carouselDataViewMessage(){return Cs("The data view makes the carousel transparent, revealing the data underneath.")}}const bW={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function};class SW extends t.Component{static template="o-spreadsheet.ChartDataSeries";static components={SelectionInput:iz,Section:YV};static props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},onSelectionChanged:Function,onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},onSelectionConfirmed:Function,title:{type:String,optional:!0},maxNumberOfUsedRanges:{type:Number,optional:!0},datasetOrientation:{type:String,optional:!0},canChangeDatasetOrientation:{type:Boolean,optional:!0},onFlipAxis:{type:Function,optional:!0}};get ranges(){return this.props.ranges.map(e=>e.dataRange)}get disabledRanges(){return this.props.ranges.map((e,t)=>!!this.props.maxNumberOfUsedRanges&&t>=this.props.maxNumberOfUsedRanges)}get colors(){return this.props.ranges.map(e=>e.backgroundColor)}get title(){return this.props.title?this.props.title:this.props.hasSingleRange?Cs("Data range"):Cs("Data series")}}class yW extends t.Component{static template="o-spreadsheet.ChartErrorSection";static components={Section:YV,ValidationMessages:MG};static props={messages:{type:Array,element:String}}}class CW extends t.Component{static template="o-spreadsheet.ChartLabelRange";static components={SelectionInput:iz,Checkbox:hz,Section:YV};static props={title:{type:String,optional:!0},range:String,isInvalid:Boolean,onSelectionChanged:Function,onSelectionConfirmed:Function,options:{type:Array,optional:!0}};static defaultProps={title:Cs("Categories / Labels"),options:[]}}class IW extends t.Component{static template="o-spreadsheet-GenericChartConfigPanel";static components={ChartDataSeries:SW,ChartLabelRange:CW,Section:YV,Checkbox:hz,ChartErrorSection:yW};static props=bW;state=t.useState({datasetDispatchResult:void 0,labelsDispatchResult:void 0});dataSets=[];labelRange;datasetOrientation=void 0;chartTerms=Bg;setup(){this.dataSets=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange,this.datasetOrientation=this.computeDatasetOrientation()}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[]].filter(e=>"NoChanges"!==e).map(e=>Bg.Errors[e]||Bg.Errors.Unexpected)}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause("InvalidDataSet")}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause("InvalidLabelRange")}get dataSetsHaveTitleLabel(){return"rows"===this.datasetOrientation?Cs("Use col %(column_name)s as headers",{column_name:lt(this.calculateHeaderPosition()||0)}):Cs("Use row %(row_position)s as headers",{row_position:this.calculateHeaderPosition()||""})}getLabelRangeOptions(){const e=this.props.definition;return[{name:"aggregated",label:this.chartTerms.AggregatedChart,value:("aggregated"in e&&e.aggregated)??!1,onChange:this.onUpdateAggregated.bind(this)},{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.chartId,{dataSetsHaveTitle:e})}get canChangeDatasetOrientation(){const e=new Set,t=[],s=this.env.model.getters.getActiveSheetName(),o=this.dataSets.map(e=>e.dataRange);this.labelRange&&o.push(this.labelRange);for(const i of o){if(!Dt(i))return!1;const o=yr(i),n=At(o.xc);if(void 0===n.bottom||void 0===n.right)return!1;if(t.push(n),e.add(o.sheetName||s),e.size>1)return!1}const i=ns(t);if(1!==i.length)return!1;const{left:n,right:r,top:a,bottom:l}=i[0];return!t.some(e=>!(e.top===a&&e.bottom===l||e.left===n&&e.right===r))}computeDatasetOrientation(){let e=!1,t=!1;for(const s of this.dataSets){if(!Dt(s.dataRange))return;const o=At(s.dataRange);if(void 0===o.bottom||void 0===o.right)return;o.top===o.bottom&&(e=!0),o.left===o.right&&(t=!0)}return e&&!t?"rows":!e&&t?"columns":void 0}setDatasetOrientation(e){const t=this.props.definition.dataSets.map(e=>e.dataRange),s=this.transposeDataSet([this.props.definition.labelRange,...t],e);if(0===s.length)return;const o=s.length>1?s.shift().dataRange:"";this.props.updateChart(this.props.chartId,{labelRange:o,dataSets:s}),this.dataSets=s,this.labelRange=o,this.datasetOrientation=e}onDataSeriesRangesChanged(e){this.dataSets=e.map((e,t)=>({...this.dataSets?.[t],dataRange:e})),this.state.datasetDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesReordered(e){const t=vN({dataSets:this.dataSets},this.dataSets.length);this.datasetOrientation=void 0;const s=this.dataSets.map(e=>t.next());this.dataSets=e.map(e=>({backgroundColor:s[e],...this.dataSets[e]})),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesRemoved(e){const t=vN({dataSets:this.dataSets},this.dataSets.length),s=this.dataSets.map(e=>t.next());this.dataSets=this.dataSets.map((e,t)=>({backgroundColor:s[t],...e})).filter((t,s)=>s!==e),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesConfirmed(){this.dataSets=this.splitRanges,this.datasetOrientation=this.computeDatasetOrientation(),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets}),this.state.datasetDispatchResult.isSuccessful&&(this.dataSets=this.env.model.getters.getChartDefinition(this.props.chartId).dataSets)}get splitRanges(){const e=[];for(const t of this.dataSets){const s=t.dataRange;if(!this.env.model.getters.isRangeValid(s)){e.push(t);continue}const{sheetName:o}=yr(s),i=o?`${o}!`:"",n=At(s);if(n.bottom!==n.top&&n.left!==n.right){if("rows"!==this.datasetOrientation){if(void 0!==n.right)for(let s=n.left;s<=n.right;++s){const o=s===n.left?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Pt({left:s,right:s,top:n.top,bottom:n.bottom})}`})}else if(void 0!==n.bottom)for(let s=n.top;s<=n.bottom;++s){const o=s===n.top?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Pt({left:n.left,right:n.right,top:s,bottom:s})}`})}}else if(void 0!==n.bottom)for(let s=n.top;s<=n.bottom;++s){const o=s===n.top?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Pt({left:n.left,right:n.right,top:s,bottom:s})}`})}else if(void 0!==n.right)for(let s=n.left;s<=n.right;++s){const o=s===n.left?t:{yAxisId:t.yAxisId};e.push({...o,dataRange:`${i}${Pt({left:s,right:s,top:n.top,bottom:n.bottom})}`})}}else e.push(t)}return e}getDataSeriesRanges(){return this.dataSets}onLabelRangeChanged(e){this.labelRange=e[0],this.state.labelsDispatchResult=this.props.canUpdateChart(this.props.chartId,{labelRange:this.labelRange})}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.chartId,{labelRange:this.labelRange})}getLabelRange(){return this.labelRange||""}onUpdateAggregated(e){this.props.updateChart(this.props.chartId,{aggregated:e})}calculateHeaderPosition(){if(this.isDatasetInvalid||this.isLabelInvalid)return;const e=this.env.model.getters,t=e.getActiveSheetId(),s=Jb(e,t,this.labelRange),o=ky(e,this.dataSets,t,this.props.definition.dataSetsHaveTitle);return o.length?"rows"===this.datasetOrientation?o[0].dataRange.zone.left:o[0].dataRange.zone.top+1:s?s.zone.top+1:void 0}get maxNumberOfUsedRanges(){return vR.get(this.props.definition.type).dataSeriesLimit}transposeDataSet(e,t){const s=this.env.model.getters;if(void 0===t)return e.filter(De).map(e=>({dataRange:e}));const o={},i=[],n=s.getFigureIdFromChartId(this.props.chartId),r=s.getFigureSheetId(n);let a=s.getActiveSheet().name;r&&(a=s.getSheet(r).name);for(const t of e){if(!t)continue;if(!Dt(t))return e.filter(De).map(e=>({dataRange:e}));let{sheetName:s,xc:i}=yr(t);s=s??a,o[s]||(o[s]=[]),o[s].push(_t(i))}for(const e in o){const s=ns(o[e]);if("columns"===t)for(const t of s)for(let s=t.left;s<=t.right;s++){const o=`${e===a?"":e+"!"}${Pt({...t,left:s,right:s})}`;i.push({dataRange:o})}else for(const t of s)for(let s=t.top;s<=t.bottom;s++){const o=`${e===a?"":e+"!"}${Pt({...t,top:s,bottom:s})}`;i.push({dataRange:o})}}return i}}class wW extends IW{static template="o-spreadsheet-BarConfigPanel";get stackedLabel(){return this.props.definition.horizontal?this.chartTerms.StackedBarChart:this.chartTerms.StackedColumnChart}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}}class EW extends t.Component{static template="o-spreadsheet.BadgeSelection";static props={choices:Array,onChange:Function,selectedValue:String}}class xW extends t.Component{static template="o-spreadsheet.ChartTitle";static components={Section:YV,TextStyler:mW,TextInput:hW};static props={title:{type:String,optional:!0},placeholder:{type:String,optional:!0},updateTitle:Function,name:{type:String},style:Object,defaultStyle:{type:Object,optional:!0},updateStyle:Function};static defaultProps={title:"",placeholder:""};updateTitle(e){this.props.updateTitle(e)}}class RW extends t.Component{static template="o-spreadsheet-AxisDesignEditor";static components={Section:YV,ChartTitle:xW,BadgeSelection:EW};static props={chartId:String,definition:Object,updateChart:Function,axesList:Array};state=t.useState({currentAxis:"x"});defaultFontSize=12;get axisTitleStyle(){return this.props.definition.axesDesign?.[this.state.currentAxis]?.title??{}}get badgeAxes(){return this.props.axesList.map(e=>({value:e.id,label:e.name}))}updateAxisEditor(e){this.state.currentAxis=e.target.value}getAxisTitle(){const e=this.props.definition.axesDesign??{};return e[this.state.currentAxis]?.title.text||""}updateAxisTitle(e){const t=he(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:{...t?.[this.state.currentAxis]?.title,text:e}},this.props.updateChart(this.props.chartId,{axesDesign:t})}updateAxisTitleStyle(e){const t=he(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:e},this.props.updateChart(this.props.chartId,{axesDesign:t})}}class TW extends t.Component{static template="o-spreadsheet.RadioSelection";static props={choices:Array,onChange:Function,selectedValue:{optional:!1},name:String,direction:{type:String,optional:!0}};static defaultProps={direction:"horizontal"}}class AW extends t.Component{static template="o-spreadsheet-GeneralDesignEditor";static components={RoundColorPicker:XV,ChartTitle:xW,Section:YV,SidePanelCollapsible:gV,RadioSelection:TW};static props={...bW,defaultChartTitleFontSize:{type:Number,optional:!0},slots:{type:Object,optional:!0}};static defaultProps={defaultChartTitleFontSize:T};state;setup(){this.state=t.useState({activeTool:""})}get title(){return this.props.definition.title}toggleDropdownTool(e,t){const s=this.state.activeTool===e;this.state.activeTool=s?"":e}updateBackgroundColor(e){this.props.updateChart(this.props.chartId,{background:e})}updateTitle(e){const t={...this.title,text:e};this.props.updateChart(this.props.chartId,{title:t})}updateChartTitleStyle(e){const t={...this.title,...e};this.props.updateChart(this.props.chartId,{title:t}),this.state.activeTool=""}}class _W extends t.Component{static template="o-spreadsheet-ChartHumanizeNumbers";static components={Checkbox:hz};static props=bW;get title(){const e=this.env.model.getters.getLocale(),t=zi(1234567,{format:an({value:1234567},void 0,e),locale:e});return Cs("E.g. 1234567 -> %(value)s",{value:t})}}class DW extends t.Component{static template="o-spreadsheet-ChartLegend";static components={Section:YV};static props=bW;updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e.target.value})}}class OW extends cW{static template="o-spreadsheet-NumberInput";static components={};static props={...cW.props,min:{type:Number,optional:!0},max:{type:Number,optional:!0}};debouncedOnChange=Fe(this.props.onChange.bind(this),100,!0);save(){const e=(this.inputRef.el?.value||"").trim();e!==this.props.value.toString()&&this.debouncedOnChange(e)}get inputClass(){return[this.props.class,"o-input"].join(" ")}}class FW extends t.Component{static template="o-spreadsheet-SeriesDesignEditor";static components={SidePanelCollapsible:gV,Section:YV,RoundColorPicker:XV};static props={...bW,slots:{type:Object,optional:!0}};state=t.useState({index:0});getDataSeries(){const e=this.env.model.getters.getChartRuntime(this.props.chartId);return e&&"chartJsConfig"in e?e.chartJsConfig.data.datasets.filter(e=>!Jy(e.xAxisID??"")).map(e=>e.label):[]}updateEditedSeries(e){this.state.index=e.target.selectedIndex}updateDataSeriesColor(e){const t=this.props.definition.dataSets;t?.[this.state.index]&&(t[this.state.index]={...t[this.state.index],backgroundColor:e},this.props.updateChart(this.props.chartId,{dataSets:t}))}getDataSeriesColor(){const e=this.props.definition.dataSets;if(!e?.[this.state.index])return"";const t=e[this.state.index].backgroundColor;return t?Yv(t):bb(this.state.index,Sb(this.props.definition.dataSets.length))}updateDataSeriesLabel(e){const t=e.target.value,s=this.props.definition.dataSets;s?.[this.state.index]&&(s[this.state.index]={...s[this.state.index],label:t},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSeriesLabel(){const e=this.props.definition.dataSets;return e[this.state.index]?.label||this.getDataSeries()[this.state.index]}}class PW extends t.Component{static template="o-spreadsheet-SeriesWithAxisDesignEditor";static components={SeriesDesignEditor:FW,Checkbox:hz,RadioSelection:TW,Section:YV,RoundColorPicker:XV,NumberInput:OW};static props={...bW,slots:{type:Object,optional:!0}};axisChoices=Yy;updateDataSeriesAxis(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],yAxisId:"left"===t?"y":"y1"},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSerieAxis(e){const t=this.props.definition.dataSets;return t?.[e]&&"y1"===t[e].yAxisId?"right":"left"}get canHaveTwoVerticalAxis(){return!("horizontal"in this.props.definition&&this.props.definition.horizontal)}toggleDataTrend(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],trend:{type:"polynomial",order:1,...s[e].trend,display:t}},this.props.updateChart(this.props.chartId,{dataSets:s}))}getTrendLineConfiguration(e){const t=this.props.definition.dataSets;return t?.[e]?.trend}getTrendType(e){return e?"polynomial"===e.type&&1===e.order?"linear":e.type:""}onChangeTrendType(e,t){const s=t.target.value;let o;switch(s){case"linear":case"polynomial":o={type:"polynomial",order:"linear"===s?1:this.getMaxPolynomialDegree(e)};break;case"exponential":case"logarithmic":case"trailingMovingAverage":o={type:s};break;default:return}this.updateTrendLineValue(e,o)}getPolynomialDegrees(e){return fe(1,this.getMaxPolynomialDegree(e)+1)}onChangePolynomialDegree(e,t){const s=t.target;this.updateTrendLineValue(e,{order:parseInt(s.value)})}getMaxPolynomialDegree(e){const t=this.env.model.getters.getChartRuntime(this.props.chartId);return Math.min(10,t.chartJsConfig.data.datasets[e].data.length-1)}get defaultWindowSize(){return 2}onChangeMovingAverageWindow(e,t){let s=parseInt(t)||2;s<=1&&(s=2),this.updateTrendLineValue(e,{window:s})}getDataSeriesColor(e){const t=this.props.definition.dataSets;if(!t?.[e])return"";const s=t[e].backgroundColor;return s?Yv(s):bb(e,Sb(this.props.definition.dataSets.length))}getTrendLineColor(e){return this.getTrendLineConfiguration(e)?.color??ab(this.getDataSeriesColor(e),.5)}updateTrendLineColor(e,t){this.updateTrendLineValue(e,{color:t})}updateTrendLineValue(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],trend:{...s[e].trend,...t}},this.props.updateChart(this.props.chartId,{dataSets:s}))}}class MW extends t.Component{static template="o-spreadsheet-ChartShowValues";static components={Checkbox:hz};static props={...bW,defaultValue:{type:Boolean,optional:!0}}}class NW extends t.Component{static template="o-spreadsheet-ChartWithAxisDesignPanel";static components={GeneralDesignEditor:AW,SidePanelCollapsible:gV,Section:YV,AxisDesignEditor:RW,SeriesWithAxisDesignEditor:PW,ChartLegend:DW,ChartShowValues:MW,ChartHumanizeNumbers:_W};static props=bW;get axesList(){const{useLeftAxis:e,useRightAxis:t}=qy(this.props.definition),s=[{id:"x",name:Cs("Horizontal axis")}];return e&&s.push({id:"y",name:Cs(t?"Left axis":"Vertical axis")}),t&&s.push({id:"y1",name:Cs(e?"Right axis":"Vertical axis")}),s}}class kW extends NW{static template="o-spreadsheet-GenericZoomableChartDesignPanel";static components={...NW.components,Checkbox:hz};onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}}const LW=["year","quarter_number","month_number","iso_week_number","day_of_month","day_of_week","hour_number","minute_number","second_number"];class VW extends t.Component{static template="o-spreadsheet-ColorScalePicker";static components={Section:YV,RoundColorPicker:XV,Popover:jL};static props={definition:Object,onUpdateColorScale:Function};colorScales=Eb.map(e=>({value:e,label:Bg.ColorScales[e],className:`${e}-color-scale`}));state=t.useState({popoverProps:void 0,popoverStyle:""});popoverRef=t.useRef("popoverRef");setup(){t.useExternalListener(window,"click",this.closePopover)}get currentColorScale(){return this.props.definition.colorScale||w_("oranges")}get currentColorScaleStyle(){const e=this.currentColorScale,t=e.minColor||"#fff",s=e.midColor,o=e.maxColor||"#000";return s?`background: linear-gradient(90deg, ${t}, ${s}, ${o});`:`background: linear-gradient(90deg, ${t}, ${o});`}colorScalePreviewStyle(e){return`background: linear-gradient(90deg, ${wb[e].join(",")});`}get currentColorScaleLabel(){return Bg.ColorScales[this.selectedColorScale]}onColorScaleChange(e){"custom"===e?this.props.onUpdateColorScale(A):this.props.onUpdateColorScale(w_(e)),this.closePopover()}onPointerDown(e){if(this.state.popoverProps)return void this.closePopover();const t=e.currentTarget,{bottom:s,right:o,width:i}=t.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:o,y:s,width:0,height:0},positioning:"top-right",verticalOffset:0},this.state.popoverStyle=JF({width:`${i}px`})}closePopover(){this.state.popoverProps=void 0}get selectedColorScale(){if(!this.props.definition.colorScale)return"oranges";const{minColor:e,midColor:t,maxColor:s}=this.props.definition.colorScale||{};for(const[o,i]of Object.entries(wb))if(i[0]===e&&i[2]===s&&i[1]===t)return o;return"custom"}getCustomColorScaleColor(e){return this.props.definition.colorScale?.[e]??""}setCustomColorScaleColor(e,t){t||"midColor"===e||(t="#fff");const s=this.currentColorScale;s&&this.props.onUpdateColorScale({...s,[e]:t})}}class zW extends t.Component{static template="o-spreadsheet-CalendarChartDesignPanel";static components={GeneralDesignEditor:AW,SidePanelCollapsible:gV,Section:YV,AxisDesignEditor:RW,ChartShowValues:MW,ColorScalePicker:VW,RoundColorPicker:XV};static props=bW;get axesList(){return[{id:"x",name:Cs("Horizontal axis")},{id:"y",name:Cs("Vertical axis")}]}onColormapChange(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}get selectedMissingValueColor(){return this.props.definition.missingValueColor}updateLegendPosition(e){const t=e.target.value;this.props.updateChart(this.props.chartId,{legendPosition:t})}}class HW extends t.Component{static template="o-spreadsheet-ChartShowDataMarkers";static components={Checkbox:hz};static props=bW}class UW extends kW{static template="o-spreadsheet-ComboChartDesignPanel";static components={...kW.components,ChartShowDataMarkers:HW,RadioSelection:TW};seriesTypeChoices=[{value:"bar",label:Cs("Bar")},{value:"line",label:Cs("Line")}];updateDataSeriesType(e,t){const s=[...this.props.definition.dataSets];s?.[e]&&(s[e]={...s[e],type:t},this.props.updateChart(this.props.chartId,{dataSets:s}))}getDataSeriesType(e){const t=this.props.definition.dataSets;return t?.[e]?t[e].type??"line":"bar"}}class BW extends t.Component{static template="o-spreadsheet-FunnelChartDesignPanel";static components={ChartShowValues:MW,GeneralDesignEditor:AW,SidePanelCollapsible:gV,RoundColorPicker:XV,Section:YV,ChartHumanizeNumbers:_W};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};getFunnelColorItems(){const e=this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig.data.labels||[],t=lN(e,this.props.definition.funnelColors);return e.map((e,s)=>({label:e||Cs("Value %s",s+1),color:t[s]}))}updateFunnelItemColor(e,t){const s=Ke(this.props.definition.funnelColors||[],t,e);this.props.updateChart(this.props.chartId,{funnelColors:s})}}class GW extends t.Component{static template="o-spreadsheet-GaugeChartConfigPanel";static components={ChartErrorSection:yW,ChartDataSeries:SW};static props=bW;state=t.useState({dataRangeDispatchResult:void 0});dataRange=this.props.definition.dataRange;get configurationErrorMessages(){return[...this.state.dataRangeDispatchResult?.reasons||[]].map(e=>Bg.Errors[e]||Bg.Errors.Unexpected)}get isDataRangeInvalid(){return!!this.state.dataRangeDispatchResult?.isCancelledBecause("InvalidGaugeDataRange")}onDataRangeChanged(e){this.dataRange=e[0],this.state.dataRangeDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataRange:this.dataRange})}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.chartId,{dataRange:this.dataRange})}getDataRange(){return{dataRange:this.dataRange||""}}}class WW extends t.Component{static template="o-spreadsheet-GaugeChartDesignPanel";static components={SidePanelCollapsible:gV,Section:YV,RoundColorPicker:XV,GeneralDesignEditor:AW,ChartErrorSection:yW,StandaloneComposer:HV,ChartHumanizeNumbers:_W};static props=bW;state;setup(){this.state=t.useState({sectionRuleCancelledReasons:this.checkSectionRuleFormulasAreValid(this.props.definition.sectionRule),sectionRule:he(this.props.definition.sectionRule)})}get designErrorMessages(){return[...this.state.sectionRuleCancelledReasons||[]].map(e=>Bg.Errors[e]||Bg.Errors.Unexpected)}get isRangeMinInvalid(){return!(!this.state.sectionRuleCancelledReasons?.includes("EmptyGaugeRangeMin")&&!this.state.sectionRuleCancelledReasons?.includes("GaugeRangeMinNaN"))}get isRangeMaxInvalid(){return!(!this.state.sectionRuleCancelledReasons?.includes("EmptyGaugeRangeMax")&&!this.state.sectionRuleCancelledReasons?.includes("GaugeRangeMaxNaN"))}get isLowerInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.includes("GaugeLowerInflectionPointNaN")}get isUpperInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.includes("GaugeUpperInflectionPointNaN")}updateSectionColor(e,t){const s=he(this.state.sectionRule);s.colors[e]=t,this.updateSectionRule(s)}updateSectionRule(e){this.state.sectionRuleCancelledReasons=[],this.state.sectionRuleCancelledReasons.push(...this.checkSectionRuleFormulasAreValid(this.state.sectionRule));const t=this.props.updateChart(this.props.chartId,{sectionRule:e});t.isSuccessful?this.state.sectionRule=he(e):this.state.sectionRuleCancelledReasons.push(...t.reasons)}onConfirmGaugeRange(e,t){this.state.sectionRule={...this.state.sectionRule,[e]:t},this.updateSectionRule(this.state.sectionRule)}getGaugeInflectionComposerProps(e){const t="lowerColor"===e?"lowerInflectionPoint":"upperInflectionPoint",s=this.state.sectionRule[t];return{onConfirm:e=>{this.state.sectionRule={...this.state.sectionRule,[t]:{...s,value:e}},this.updateSectionRule(this.state.sectionRule)},composerContent:s.value,invalid:"lowerColor"===e?this.isLowerInflectionPointInvalid:this.isUpperInflectionPointInvalid,defaultRangeSheetId:this.sheetId,class:t,placeholder:Cs("Value"),title:Cs("Value or formula")}}checkSectionRuleFormulasAreValid(e){const t=[];return this.valueIsValidNumber(e.rangeMin)||t.push("GaugeRangeMinNaN"),this.valueIsValidNumber(e.rangeMax)||t.push("GaugeRangeMaxNaN"),this.valueIsValidNumber(e.lowerInflectionPoint.value)||t.push("GaugeLowerInflectionPointNaN"),this.valueIsValidNumber(e.upperInflectionPoint.value)||t.push("GaugeUpperInflectionPointNaN"),t}valueIsValidNumber(e){const t=this.env.model.getters.getLocale();if(!e.startsWith("="))return void 0!==xo(e,t);const s=this.env.model.getters.evaluateFormula(this.sheetId,e);return!_n(s)&&void 0!==xo(Tn(s),t)}get sheetId(){const e=this.env.model.getters.getChart(this.props.chartId);if(!e)throw new Error("Chart not found with id "+this.props.chartId);return e.sheetId}}class $W extends t.Component{static template="o-spreadsheet-GeoChartRegionSelectSection";static components={Section:YV};static props={chartId:String,definition:Object,updateChart:Function};updateSelectedRegion(e){const t=e.target.value;this.props.updateChart(this.props.chartId,{region:t})}get availableRegions(){return this.env.model.getters.getGeoChartAvailableRegions()}get selectedRegion(){return this.props.definition.region||this.availableRegions[0]?.id}}class qW extends IW{static template="o-spreadsheet-GeoChartConfigPanel";static components={...IW.components,GeoChartRegionSelectSection:$W};get dataRanges(){return this.getDataSeriesRanges()}get disabledRanges(){return this.props.definition.dataSets.map((e,t)=>t>0)}getLabelRangeOptions(){return[{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}}class ZW extends NW{static template="o-spreadsheet-GeoChartDesignPanel";static components={...NW.components,RoundColorPicker:XV,ColorScalePicker:VW};updateColorScale(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}updateLegendPosition(e){const t=e.target.value;this.props.updateChart(this.props.chartId,{legendPosition:t})}get selectedMissingValueColor(){return this.props.definition.missingValueColor||"#ffffff"}}class jW extends IW{static template="o-spreadsheet-HierarchicalChartConfigPanel";static components={...IW.components};getLabelRangeOptions(){return[{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}}class YW extends IW{static template="o-spreadsheet-LineConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.chartId);return!!(e&&e instanceof bL)&&uk(e.getDefinition(),e.dataSets,e.labelRange,this.env.model.getters)}get stackedLabel(){return this.props.definition.fillArea?this.chartTerms.StackedAreaChart:this.chartTerms.StackedLineChart}getLabelRangeOptions(){const e=super.getLabelRangeOptions();return this.canTreatLabelsAsText&&e.push({name:"labelsAsText",value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}onUpdateLabelsAsText(e){this.props.updateChart(this.props.chartId,{labelsAsText:e})}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}}class XW extends kW{static template="o-spreadsheet-LineChartDesignPanel";static components={...kW.components,ChartShowDataMarkers:HW}}class KW extends t.Component{static template="o-spreadsheet.PieHoleSize";static components={Section:YV,NumberInput:OW};static props={onValueChange:Function,value:Number};onChange(e){isNaN(Number(e))||this.props.onValueChange(me(Number(e),0,95))}}class JW extends t.Component{static template="o-spreadsheet-PieChartDesignPanel";static components={GeneralDesignEditor:AW,Section:YV,ChartLegend:DW,ChartShowValues:MW,PieHoleSize:KW,Checkbox:hz,ChartHumanizeNumbers:_W};static props=bW;onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}get defaultHoleSize(){return 50}}class QW extends t.Component{static template="o-spreadsheet-RadarChartDesignPanel";static components={GeneralDesignEditor:AW,SeriesDesignEditor:FW,Section:YV,ChartLegend:DW,ChartShowValues:MW,ChartShowDataMarkers:HW,Checkbox:hz,ChartHumanizeNumbers:_W};static props=bW}class e$ extends zO{dataSets;labelRange;background;legendPosition;labelsAsText;aggregated;type="scatter";dataSetsHaveTitle;dataSetDesign;axesDesign;showValues;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=ky(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.zoomable=e.zoomable}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static transformDefinition(e,t,s){return Hy(e,t,s)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"scatter",labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues,zoomable:e.zoomable,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"scatter",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,zoomable:this.zoomable,humanize:this.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new e$(i,this.sheetId,this.getters)}getDefinitionForExcel(){const e=this.dataSets.map(e=>Vy(this.getters,e)).filter(e=>""!==e.range),t=zy(this.getters,this.labelRange,$y(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:IP(this.background||c),fontColor:IP(Uy(this.background)),dataSets:e,labelRange:t,verticalAxis:qy(s)}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new e$(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new e$(t,e,this.getters)}}class t$ extends t.Component{static template="o-spreadsheet-ScorecardChartConfigPanel";static components={SelectionInput:iz,ChartErrorSection:yW,Section:YV};static props=bW;state=t.useState({keyValueDispatchResult:void 0,baselineDispatchResult:void 0});keyValue=this.props.definition.keyValue;baseline=this.props.definition.baseline;get errorMessages(){return[...this.state.keyValueDispatchResult?.reasons||[],...this.state.baselineDispatchResult?.reasons||[]].map(e=>Bg.Errors[e]||Bg.Errors.Unexpected)}get isKeyValueInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause("InvalidScorecardKeyValue")}get isBaselineInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause("InvalidScorecardBaseline")}onKeyValueRangeChanged(e){this.keyValue=e[0],this.state.keyValueDispatchResult=this.props.canUpdateChart(this.props.chartId,{keyValue:this.keyValue})}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.chartId,{keyValue:this.keyValue})}getKeyValueRange(){return this.keyValue||""}onBaselineRangeChanged(e){this.baseline=e[0],this.state.baselineDispatchResult=this.props.canUpdateChart(this.props.chartId,{baseline:this.baseline})}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.chartId,{baseline:this.baseline})}getBaselineRange(){return this.baseline||""}updateBaselineMode(e){this.props.updateChart(this.props.chartId,{baselineMode:e.target.value})}}class s$ extends t.Component{static template="o-spreadsheet-ScorecardChartDesignPanel";static components={GeneralDesignEditor:AW,RoundColorPicker:XV,SidePanelCollapsible:gV,Section:YV,Checkbox:hz,ChartTitle:xW,ChartHumanizeNumbers:_W};static props=bW;get colorsSectionTitle(){return"progress"===this.props.definition.baselineMode?Cs("Progress bar colors"):Cs("Baseline colors")}get defaultScorecardTitleFontSize(){return 14}translate(e){return this.env.model.getters.dynamicTranslate(e)}setColor(e,t){switch(t){case"backgroundColor":this.props.updateChart(this.props.chartId,{background:e});break;case"baselineColorDown":this.props.updateChart(this.props.chartId,{baselineColorDown:e});break;case"baselineColorUp":this.props.updateChart(this.props.chartId,{baselineColorUp:e})}}get keyStyle(){return{align:"center",fontSize:32,...this.props.definition.keyDescr}}get baselineStyle(){return{align:"center",fontSize:16,...this.props.definition.baselineDescr}}setKeyText(e){this.props.updateChart(this.props.chartId,{keyDescr:{...this.props.definition.keyDescr,text:e}})}updateKeyStyle(e){const t={...this.keyStyle,...e};this.props.updateChart(this.props.chartId,{keyDescr:t})}setBaselineText(e){this.props.updateChart(this.props.chartId,{baselineDescr:{...this.props.definition.baselineDescr,text:e}})}updateBaselineStyle(e){const t={...this.baselineStyle,...e};this.props.updateChart(this.props.chartId,{baselineDescr:t})}}class o$ extends t.Component{static template="o-spreadsheet-SunburstChartDesignPanel";static components={GeneralDesignEditor:AW,Section:YV,SidePanelCollapsible:gV,ChartShowValues:MW,Checkbox:hz,TextStyler:mW,RoundColorPicker:XV,ChartLegend:DW,PieHoleSize:KW,ChartHumanizeNumbers:_W};static props=bW;defaults=E_;get showValues(){return this.props.definition.showValues??E_.showValues}get showLabels(){return this.props.definition.showLabels??E_.showLabels}get groupColors(){const e=this.props.chartId,t=this.env.model.getters.getChartRuntime(e).chartJsConfig.data.datasets[0];return t?.groupColors||[]}onGroupColorChanged(e,t){const s=he(this.props.definition.groupColors)??[];s[e]=t,this.props.updateChart(this.props.chartId,{groupColors:s})}onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}}class i$ extends t.Component{static template="o-spreadsheet-TreeMapCategoryColors";static components={Checkbox:hz,RoundColorPicker:XV};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){const e=this.props.definition.coloringOptions??TM.coloringOptions;if("categoryColor"!==e.type)throw new Error("Coloring options is not solid color");return e}getTreeGroupAndColors(){const e=this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig;return e.data.datasets[0]?.groupColors||[]}onGroupColorChanged(e,t){const s=he(this.coloringOptions);s.colors[e]=t||void 0,this.props.onColorChanged(s)}useValueBasedGradient(e){if("categoryColor"!==this.coloringOptions.type)throw new Error("Coloring options is not solid color");this.props.onColorChanged({...this.coloringOptions,useValueBasedGradient:e})}}class n$ extends t.Component{static template="o-spreadsheet-TreeMapColorScale";static components={RoundColorPicker:XV};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){const e=this.props.definition.coloringOptions??TM.coloringOptions;if("colorScale"!==e.type)throw new Error("Coloring options is not a color scale");return e}setColorScaleColor(e,t){this.props.onColorChanged({...this.coloringOptions,[e]:t})}}const r$={type:"colorScale",minColor:"#FFF5EB",midColor:"#FD8D3C",maxColor:"#7F2704"},a$={type:"categoryColor",colors:[],useValueBasedGradient:!0};class l$ extends t.Component{static template="o-spreadsheet-TreeMapChartDesignPanel";static components={GeneralDesignEditor:AW,Section:YV,SidePanelCollapsible:gV,ChartShowValues:MW,Checkbox:hz,TextStyler:mW,RoundColorPicker:XV,BadgeSelection:EW,TreeMapCategoryColors:i$,TreeMapColorScale:n$,ChartHumanizeNumbers:_W};static props=bW;savedColors={categoryColors:a$,colorScale:r$};defaults=TM;get showHeaders(){return this.props.definition.showHeaders??TM.showHeaders}get showValues(){return this.props.definition.showValues??TM.showValues}get showLabels(){return this.props.definition.showLabels??TM.showLabels}get coloringOptions(){return this.props.definition.coloringOptions??TM.coloringOptions}changeColoringOption(e){const t="categoryColor"===e?this.savedColors.categoryColors:this.savedColors.colorScale;this.props.updateChart(this.props.chartId,{coloringOptions:t})}onCategoryColorChange(e){this.savedColors.categoryColors=e,this.props.updateChart(this.props.chartId,{coloringOptions:e})}onColorScaleChange(e){this.savedColors.colorScale=e,this.props.updateChart(this.props.chartId,{coloringOptions:e})}get coloringOptionChoices(){return[{label:Cs("Category color"),value:"categoryColor"},{label:Cs("Color scale"),value:"colorScale"}]}}class c$ extends t.Component{static template="o-spreadsheet-WaterfallChartDesignPanel";static components={GeneralDesignEditor:AW,ChartShowValues:MW,Checkbox:hz,SidePanelCollapsible:gV,Section:YV,RoundColorPicker:XV,AxisDesignEditor:RW,RadioSelection:TW,ChartLegend:DW,ChartHumanizeNumbers:_W};static props=bW;axisChoices=Yy;onUpdateShowSubTotals(e){this.props.updateChart(this.props.chartId,{showSubTotals:e})}onUpdateShowConnectorLines(e){this.props.updateChart(this.props.chartId,{showConnectorLines:e})}onUpdateFirstValueAsSubtotal(e){this.props.updateChart(this.props.chartId,{firstValueAsSubtotal:e})}updateColor(e,t){this.props.updateChart(this.props.chartId,{[e]:t})}get axesList(){return[{id:"x",name:Cs("Horizontal axis")},{id:"y",name:Cs("Vertical axis")}]}get positiveValuesColor(){return this.props.definition.positiveValuesColor||m}get negativeValuesColor(){return this.props.definition.negativeValuesColor||f}get subTotalValuesColor(){return this.props.definition.subTotalValuesColor||v}updateVerticalAxisPosition(e){this.props.updateChart(this.props.chartId,{verticalAxisPosition:e})}onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}}const h$=new Jg;h$.add("line",{configuration:YW,design:XW}).add("scatter",{configuration:class extends IW{static template="o-spreadsheet-ScatterConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.chartId);return!!(e&&e instanceof e$)&&uk(e.getDefinition(),e.dataSets,e.labelRange,this.env.model.getters)}onUpdateLabelsAsText(e){this.props.updateChart(this.props.chartId,{labelsAsText:e})}getLabelRangeOptions(){const e=super.getLabelRangeOptions();return this.canTreatLabelsAsText&&e.push({name:"labelsAsText",value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}},design:kW}).add("bar",{configuration:wW,design:class extends kW{static template="o-spreadsheet-BarChartDesignPanel";get isZoomable(){return!this.props.definition.horizontal}}}).add("combo",{configuration:IW,design:UW}).add("pie",{configuration:IW,design:JW}).add("gauge",{configuration:GW,design:WW}).add("scorecard",{configuration:t$,design:s$}).add("waterfall",{configuration:IW,design:c$}).add("pyramid",{configuration:IW,design:NW}).add("radar",{configuration:IW,design:QW}).add("sunburst",{configuration:jW,design:o$}).add("geo",{configuration:qW,design:ZW}).add("funnel",{configuration:class extends IW{getLabelRangeOptions(){const e=this.props.definition;return[{name:"aggregated",label:this.chartTerms.AggregatedChart,value:e.aggregated??!1,onChange:this.onUpdateAggregated.bind(this)},{name:"cumulative",label:this.chartTerms.CumulativeData,value:e.cumulative??!1,onChange:this.onUpdateCumulative.bind(this)},{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}},design:BW}).add("treemap",{configuration:jW,design:l$}).add("calendar",{configuration:class extends IW{static template="o-spreadsheet-CalendarChartConfigPanel";groupByChoices=LW.map(e=>({value:e,label:yp[e]}));getLabelRangeOptions(){return[{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}getGroupByOptions(){const e=this.env.model.getters.getFigureSheetId(this.env.model.getters.getFigureIdFromChartId(this.props.chartId)),t=ky(this.env.model.getters,this.props.definition.dataSets,e,this.props.definition.dataSetsHaveTitle);if(0===t.length)return[];const s=Jb(this.env.model.getters,e,this.props.definition.labelRange),o=QN(this.props.definition,t,s,this.env.model.getters).labels.filter(e=>Ks(e,gi));if(0===o.length)return[];const i=o.map(e=>Mo(e,this.env.model.getters.getLocale())),n=new Set,r=new Set,a=new Set,l=new Set,c=new Set,h=new Set;for(const e of i)n.add(e.getFullYear()),r.add(e.getMonth()),a.add(e.getDate()),l.add(e.getHours()),c.add(e.getMinutes()),h.add(e.getSeconds());return this.groupByChoices.filter(e=>{switch(e.value){case"year":return n.size>1;case"quarter_number":case"month_number":return r.size>1;case"iso_week_number":case"day_of_month":case"day_of_week":return a.size>1;case"hour_number":return l.size>1;case"minute_number":return c.size>1;case"second_number":return h.size>1;default:return!1}})}getGroupByType(e){return("horizontal"===e?this.props.definition.horizontalGroupBy:this.props.definition.verticalGroupBy)||"year"}updateGroupBy(e,t){this.props.updateChart(this.props.chartId,{["horizontal"===e?"horizontalGroupBy":"verticalGroupBy"]:t})}},design:zW});const d$={line:Cs("Line"),column:Cs("Column"),bar:Cs("Bar"),area:Cs("Area"),pie:Cs("Pie"),hierarchical:Cs("Hierarchical"),misc:Cs("Miscellaneous")};class u$ extends t.Component{static template="o-spreadsheet-ChartTypePicker";static components={Section:YV,Popover:jL};static props={chartId:String,chartPanelStore:Object};categories=d$;chartTypeByCategories={};popoverRef=t.useRef("popoverRef");selectRef=t.useRef("selectRef");state=t.useState({popoverProps:void 0,popoverStyle:""});setup(){t.useExternalListener(window,"pointerdown",this.onExternalClick,{capture:!0});for(const e of qF.getAll())this.chartTypeByCategories[e.category]?this.chartTypeByCategories[e.category].push(e):this.chartTypeByCategories[e.category]=[e]}onExternalClick(e){AN(this.popoverRef.el?.parentElement,e)||AN(this.selectRef.el,e)||this.closePopover()}onTypeChange(e){this.props.chartPanelStore.changeChartType(this.props.chartId,e),this.closePopover()}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}getSelectedChartSubtypeProperties(){const e=this.getChartDefinition(this.props.chartId);return qF.getAll().find(t=>t.matcher?.(e)||!1)||qF.get(e.type)}onPointerDown(e){if(this.state.popoverProps)return void this.closePopover();const t=e.currentTarget,{bottom:s,right:o,width:i}=t.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:o,y:s,width:0,height:0},positioning:"top-right",verticalOffset:0},this.state.popoverStyle=JF({width:`${i}px`})}closePopover(){this.state.popoverProps=void 0}}class g$ extends Lv{mutators=["activatePanel","changeChartType"];panel="configuration";creationContexts={};activatePanel(e){this.panel=e}changeChartType(e,t){const s=this.getters.getContextCreationChart(e),o=this.creationContexts[e]||{};let i=s?.range;i?.every((e,t)=>Le(e,o.range?.[t]))&&(i=Object.assign([],o.range,s?.range)),this.creationContexts[e]={...o,...s,range:i};const n=this.getters.getFigureIdFromChartId(e),r=this.getters.getFigureSheetId(n);if(!r)return;const a=this.getChartDefinitionFromContextCreation(e,t);this.model.dispatch("UPDATE_CHART",{definition:a,chartId:e,figureId:n,sheetId:r})}getChartDefinitionFromContextCreation(e,t){const s=qF.get(t);return{...vR.get(s.chartType).getChartDefinitionFromContextCreation(this.creationContexts[e]),...s.subtypeDefinition}}}class p$ extends t.Component{static template="o-spreadsheet-ChartPanel";static components={Section:YV,ChartTypePicker:u$};static props={onCloseSidePanel:Function,chartId:String};panelContentRef;scrollPositions={configuration:0,design:0};store;get chartId(){return this.props.chartId}setup(){this.store=Av(g$),this.panelContentRef=t.useRef("panelContent"),t.useEffect(()=>{const e=this.panelContentRef.el,t=this.store.panel;e&&(e.scrollTop=this.scrollPositions[t])},()=>[this.store.panel])}switchPanel(e){const t=this.panelContentRef.el;t&&(this.scrollPositions[this.store.panel]=t.scrollTop),this.store.activatePanel(e)}updateChart(e,t){const s=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId)return;const o={...this.getChartDefinition(this.chartId),...t};return this.env.model.dispatch("UPDATE_CHART",{definition:o,chartId:e,figureId:s,sheetId:this.env.model.getters.getFigureSheetId(s)})}canUpdateChart(e,t){const s=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId||!this.env.model.getters.isChartDefined(e))return;const o={...this.getChartDefinition(this.chartId),...t};return this.env.model.canDispatch("UPDATE_CHART",{definition:o,chartId:e,figureId:s,sheetId:this.env.model.getters.getFigureSheetId(s)})}onTypeChange(e){this.chartId&&this.store.changeChartType(this.chartId,e)}get chartPanel(){if(!this.chartId)throw new Error("Chart not defined.");const e=this.env.model.getters.getChartType(this.chartId);if(!e)throw new Error("Chart not defined.");const t=h$.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}}class m$ extends t.Component{static template="o-spreadsheet-IconPicker";static props={onIconPicked:Function};icons=sT;iconSets=oT;onIconClick(e){e&&this.props.onIconPicked(e)}}function f$(e,s){const o=function(e){const s=t.useState({hovered:!1});return kG(e,"mouseenter",()=>s.hovered=!0),kG(e,"mouseleave",()=>s.hovered=!1),s}(e);v$({get highlights(){return o.hovered?s.highlights:[]}})}function v$(e){const s=Rv(),o=Av(NV);t.onMounted(()=>{o.register(e)});let i=e.highlights;t.useEffect(e=>{Le(e,i)||(i=e,s.trigger("store-updated"))},()=>[e.highlights])}class b$ extends t.Component{static template="o-spreadsheet-ConditionalFormatPreview";icons=sT;ref=t.useRef("cfPreview");setup(){f$(this.ref,this)}getPreviewImageStyle(){const e=this.props.conditionalFormat.rule;if("CellIsRule"===e.type)return JF(XF(e.style));if("ColorScaleRule"===e.type){const t=Zv(e.minimum.color),s=e.midpoint?Zv(e.midpoint.color):null,o=Zv(e.maximum.color),i="background-image: linear-gradient(to right, ";return s?i+t+", "+s+", "+o+")":i+t+", "+o+")"}if("DataBarRule"===e.type){return`${`background-image: linear-gradient(to right, ${Zv(e.color)} 50%, white 50%)`}; color: ${C};`}return""}getDescription(){const e=this.props.conditionalFormat;switch(e.rule.type){case"CellIsRule":return W_.get(e.rule.operator).getPreview({...e.rule,type:e.rule.operator},this.env.model.getters);case"ColorScaleRule":return Ug.ColorScale;case"IconSetRule":return Ug.IconSet;case"DataBarRule":return Ug.DataBar}}deleteConditionalFormat(){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:this.props.conditionalFormat.id,sheetId:this.env.model.getters.getActiveSheetId()})}onMouseDown(e){this.props.onMouseDown(e)}get highlights(){const e=this.env.model.getters.getActiveSheetId();return this.props.conditionalFormat.ranges.map(t=>({range:this.env.model.getters.getRangeFromSheetXC(e,t),color:o,fillAlpha:.06}))}}b$.props={conditionalFormat:Object,onPreviewClick:Function,onMouseDown:Function,class:String};class S$ extends t.Component{static template="o-spreadsheet-ConditionalFormatPreviewList";static props={conditionalFormats:Array,onPreviewClick:Function,onAddConditionalFormat:Function};static components={ConditionalFormatPreview:b$};icons=sT;dragAndDrop=KV();cfListRef=t.useRef("cfList");setup(){t.onWillUpdateProps(e=>{Le(this.props.conditionalFormats,e.conditionalFormats)||this.dragAndDrop.cancel()})}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[e.id]||""}onPreviewMouseDown(e,t){if(0!==t.button)return;const s=Array.from(this.cfListRef.el.children).map(e=>FN(e)),o=this.props.conditionalFormats.map((e,t)=>({id:e.id,size:s[t].height,position:s[t].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.id,initialMousePosition:t.clientY,items:o,scrollableContainerEl:this.cfListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const s=this.props.conditionalFormats.findIndex(t=>t.id===e)-t;0!==s&&this.env.model.dispatch("CHANGE_CONDITIONAL_FORMAT_PRIORITY",{cfId:e,delta:s,sheetId:this.env.model.getters.getActiveSheetId()})}}class y$ extends t.Component{static template="o-spreadsheet-ConditionalFormattingEditor";static props={editedCf:Object,onCancel:Function,onExit:Function,isNewCf:Boolean};static components={SelectionInput:iz,IconPicker:m$,ColorPickerWidget:uW,ConditionalFormatPreviewList:S$,Section:YV,RoundColorPicker:XV,StandaloneComposer:HV,BadgeSelection:EW,ValidationMessages:MG,SelectMenu:lz};icons=sT;iconSets=oT;getTextDecoration=YF;colorNumberToHex=Zv;state;setup(){switch(this.state=t.useState({errors:[],currentCFType:this.props.editedCf.rule.type,ranges:this.props.editedCf.ranges,rules:this.getDefaultRules(),hasEditedCf:this.props.isNewCf}),this.props.editedCf.rule.type){case"CellIsRule":this.state.rules.cellIs=this.props.editedCf.rule;break;case"ColorScaleRule":this.state.rules.colorScale=this.props.editedCf.rule;break;case"IconSetRule":this.state.rules.iconSet=this.props.editedCf.rule;break;case"DataBarRule":this.state.rules.dataBar=this.props.editedCf.rule}t.useExternalListener(window,"click",this.closeMenus)}get isRangeValid(){return this.state.errors.includes("EmptyRange")}get errorMessages(){return this.state.errors.map(e=>Ug.Errors[e]||Ug.Errors.Unexpected)}get cfTypesValues(){return[{value:"CellIsRule",label:Cs("Single color")},{value:"ColorScaleRule",label:Cs("Color scale")},{value:"IconSetRule",label:Cs("Icon set")},{value:"DataBarRule",label:Cs("Data bar")}]}updateConditionalFormat(e){const t=e.ranges||this.state.ranges;if(this.state.ranges.some(e=>!e.match(mr)))return e.suppressErrors||(this.state.errors=["InvalidRange"]),["InvalidRange"];const s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getLocale(),i=e.rule||this.getEditedRule(this.state.currentCFType),n=this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:xh(i,o),id:this.props.editedCf.id},ranges:t.map(e=>this.env.model.getters.getRangeDataFromXc(s,e)),sheetId:s});n.isSuccessful&&(this.state.hasEditedCf=!0);const r=n.reasons.filter(e=>"NoChanges"!==e);return e.suppressErrors||(this.state.errors=r),r}getEditedRule(e){switch(e){case"CellIsRule":return this.state.rules.cellIs;case"ColorScaleRule":return this.state.rules.colorScale;case"IconSetRule":return this.state.rules.iconSet;case"DataBarRule":return this.state.rules.dataBar}}onSave(){0===this.updateConditionalFormat({}).length&&this.props.onExit()}onCancel(){this.state.hasEditedCf?this.props.onCancel():this.props.onExit()}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"isNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:HT("EFF7FF")},midpoint:void 0,maximum:{type:"value",color:6989903}},iconSet:{type:"IconSetRule",icons:{upper:"arrowGood",middle:"arrowNeutral",lower:"arrowBad"},upperInflectionPoint:{type:"percentage",value:"66",operator:"gt"},lowerInflectionPoint:{type:"percentage",value:"33",operator:"gt"}},dataBar:{type:"DataBarRule",color:14281427}}}changeRuleType(e){this.state.currentCFType!==e&&(this.state.errors=[],this.state.currentCFType=e,this.updateConditionalFormat({rule:this.getEditedRule(e),suppressErrors:!0}))}onRangeUpdate(e){this.state.ranges=e}onRangeConfirmed(){this.updateConditionalFormat({ranges:this.state.ranges})}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){return this.state.errors.includes("FirstArgMissing")||this.state.errors.includes("ValueCellIsInvalidFormula")}get isValue2Invalid(){return this.state.errors.includes("SecondArgMissing")}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}onKeydown(e){if("F4"===e.key){const t=e.target,s=FV({start:t.selectionStart??0,end:t.selectionEnd??0},t.value,this.env.model.getters.getLocale());if(!s)return;t.value=s.content,t.setSelectionRange(s.selection.start,s.selection.end),t.dispatchEvent(new Event("input"))}}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}editOperator(e){this.state.rules.cellIs.operator=e,e.includes("date")&&!this.state.rules.cellIs.dateValue&&(this.state.rules.cellIs.dateValue="exactDate"),this.updateConditionalFormat({rule:this.state.rules.cellIs,suppressErrors:!0}),this.closeMenus()}get cfCriterionMenuItems(){return az(e=>this.editOperator(e),jN)}get selectedCriterionName(){return W_.get(this.state.rules.cellIs.operator).name}get criterionComponent(){return rz.get(this.state.rules.cellIs.operator).component}get genericCriterion(){return{type:this.state.rules.cellIs.operator,values:this.state.rules.cellIs.values,dateValue:this.state.rules.cellIs.dateValue}}onRuleValuesChanged(e){this.state.rules.cellIs.values=e.values,this.state.rules.cellIs.dateValue=e.dateValue,this.updateConditionalFormat({rule:{...this.state.rules.cellIs,values:e.values,dateValue:e.dateValue}})}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes("MinInvalidFormula")||this.state.errors.includes("MinBiggerThanMid")||this.state.errors.includes("MinBiggerThanMax")||this.state.errors.includes("MinNaN");case"midpoint":return this.state.errors.includes("MidInvalidFormula")||this.state.errors.includes("MidNaN")||this.state.errors.includes("MidBiggerThanMax");case"maximum":return this.state.errors.includes("MaxInvalidFormula")||this.state.errors.includes("MaxNaN");default:return!1}}setColorScaleColor(e,t){if(!Xv(t))return;const s=this.state.rules.colorScale[e];s&&(s.color=jv(t)),this.updateConditionalFormat({rule:this.state.rules.colorScale}),this.closeMenus()}getColorScalePreviewStyle(){const e=this.state.rules.colorScale,t=Zv(e.minimum.color),s=Zv(e.midpoint?.color||h),o=Zv(e.maximum.color),i="linear-gradient(to right, ";return JF({"background-image":void 0===e.midpoint?i+t+", "+o+")":i+t+", "+s+", "+o+")",color:"#000"})}getThresholdColor(e){return Zv(e?e.color:h)}onMidpointChange(e){const t=e.target.value,s=this.state.rules.colorScale;s.midpoint="none"===t?void 0:{color:h,value:"",...s.midpoint,type:t},this.updateConditionalFormat({rule:s,suppressErrors:!0})}updateThresholdType(e,t){this.state.rules.colorScale[e].type=t,this.updateConditionalFormat({rule:this.state.rules.colorScale,suppressErrors:!0})}updateThresholdValue(e,t){this.state.rules.colorScale[e].value=t,this.updateConditionalFormat({rule:this.state.rules.colorScale})}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes("ValueLowerInflectionNaN")||this.state.errors.includes("ValueLowerInvalidFormula")||this.state.errors.includes("LowerBiggerThanUpper");case"upperInflectionPoint":return this.state.errors.includes("ValueUpperInflectionNaN")||this.state.errors.includes("ValueUpperInvalidFormula")||this.state.errors.includes("LowerBiggerThanUpper");default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIcon(e,t){this.state.rules.iconSet.icons[e]=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionOperator(e,t){this.state.rules.iconSet[e].operator=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionValue(e,t){this.state.rules.iconSet[e].value=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionType(e,t,s){this.state.rules.iconSet[e].type=t,this.updateConditionalFormat({rule:this.state.rules.iconSet,suppressErrors:!0})}getColorScaleComposerProps(e){const t=this.state.rules.colorScale[e];if(!t)throw new Error("Threshold not found");const s=this.isValueInvalid(e);return{onConfirm:e=>{t.value=e,this.updateConditionalFormat({rule:this.state.rules.colorScale})},composerContent:t.value||"",placeholder:Cs("Formula"),defaultStatic:!0,invalid:s,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getColorIconSetComposerProps(e){const t=this.state.rules.iconSet[e],s=this.isInflectionPointInvalid(e);return{onConfirm:e=>{t.value=e,this.updateConditionalFormat({rule:this.state.rules.iconSet})},composerContent:t.value||"",placeholder:Cs("Formula"),defaultStatic:!0,invalid:s,class:"o-sidePanel-composer",defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getRangeValues(){return[this.state.rules.dataBar.rangeValues||""]}updateDataBarColor(e){Xv(e)&&(this.state.rules.dataBar.color=Number.parseInt(e.slice(1),16),this.updateConditionalFormat({rule:this.state.rules.dataBar}))}onDataBarRangeUpdate(e){this.state.rules.dataBar.rangeValues=e[0]}onDataBarRangeChange(){this.updateConditionalFormat({rule:this.state.rules.dataBar})}}class C$ extends t.Component{static template="o-spreadsheet-ConditionalFormattingPanel";static props={selection:{type:Object,optional:!0},onCloseSidePanel:Function};static components={ConditionalFormatPreviewList:S$,ConditionalFormattingEditor:y$,Section:YV};activeSheetId;originalEditedCf=void 0;state=t.useState({mode:"list"});setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId();const e=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===s.length){const e=this.conditionalFormats.find(e=>e.id===s[0]);e&&this.editConditionalFormat(e)}t.onWillUpdateProps(e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===s.length){const e=this.conditionalFormats.find(e=>e.id===s[0]);e&&this.editConditionalFormat(e)}else this.switchToList()}else this.editedCF||this.switchToList()})}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId()).map(e=>({...e,rule:Rh(e.rule,this.env.model.getters.getLocale())}))}switchToList(){this.state.mode="list",this.state.editedCfId=void 0,this.originalEditedCf=void 0}addConditionalFormat(){const e=this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,ranges:this.env.model.getters.getSelectedZones().map(e=>this.env.model.getters.getRangeDataFromZone(this.activeSheetId,e)),cf:{id:e,rule:{type:"CellIsRule",operator:"isNotEmpty",style:{fillColor:"#b6d7a8"},values:[]}}}),this.state.editedCfId=e,this.state.mode="edit",this.originalEditedCf=void 0}editConditionalFormat(e){this.state.mode="edit",this.state.editedCfId=e.id,this.originalEditedCf=e}cancelEdition(){this.originalEditedCf?this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,ranges:this.originalEditedCf.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.activeSheetId,e)),cf:this.originalEditedCf}):this.state.editedCfId&&this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{sheetId:this.activeSheetId,id:this.state.editedCfId}),this.switchToList()}get editedCF(){return this.conditionalFormats.find(e=>e.id===this.state.editedCfId)}}class I$ extends t.Component{static template="o-spreadsheet-DataValidationEditor";static components={SelectionInput:iz,SelectMenu:lz,Section:YV,ValidationMessages:MG};static props={rule:{type:Object,optional:!0},onExit:Function,onCloseSidePanel:{type:Function,optional:!0}};state=t.useState({rule:this.defaultDataValidationRule,errors:[],isTypeUpdated:!1});editingSheetId;setup(){this.editingSheetId=this.env.model.getters.getActiveSheetId(),this.props.rule&&(this.state.rule={...this.props.rule,ranges:this.props.rule.ranges.map(e=>this.env.model.getters.getRangeString(e,this.editingSheetId))},this.state.rule.criterion.type=this.props.rule.criterion.type)}onCriterionTypeChanged(e){this.state.rule.criterion.type=e,this.state.isTypeUpdated=!0}onRangesChanged(e){this.state.rule.ranges=e}onCriterionChanged(e){this.state.rule.criterion=e}changeRuleIsBlocking(e){const t=e.target.value;this.state.rule.isBlocking="true"===t}onSave(){if(this.state.rule){const e=this.env.model.dispatch("ADD_DATA_VALIDATION_RULE",this.dispatchPayload);e.isSuccessful?this.props.onExit():this.state.errors=e.reasons}}get dispatchPayload(){const e={...this.state.rule,ranges:void 0},t=this.env.model.getters.getLocale(),s=e.criterion,o=W_.get(s.type),i=s.values.slice(0,o.numberOfValues(s)).map(e=>e?.trim()).filter(e=>""!==e&&void 0!==e).map(e=>bh(e,t));return e.criterion={...s,values:i},{sheetId:this.editingSheetId,ranges:this.state.rule.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.editingSheetId,e)),rule:e}}get dvCriterionMenuItems(){return az(e=>this.onCriterionTypeChanged(e),YN)}get selectedCriterionName(){const e=this.state.rule.criterion.type;return W_.get(e).name}get defaultDataValidationRule(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones().map(t=>Pt(this.env.model.getters.getUnboundedZone(e,t)));return{id:this.env.model.uuidGenerator.smallUuid(),criterion:{type:"containsText",values:[""]},ranges:t}}get criterionComponent(){return rz.get(this.state.rule.criterion.type).component}get errorMessages(){return this.state.errors.map(e=>jg.Errors[e]||jg.Errors.Unexpected)}}class w$ extends t.Component{static template="o-spreadsheet-DataValidationPreview";static props={onClick:Function,rule:Object};ref=t.useRef("dvPreview");setup(){f$(this.ref,this)}deleteDataValidation(){const e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("REMOVE_DATA_VALIDATION_RULE",{sheetId:e,id:this.props.rule.id})}get highlights(){return this.props.rule.ranges.map(e=>({range:e,color:o,fillAlpha:.06}))}get rangesString(){const e=this.env.model.getters.getActiveSheetId();return this.props.rule.ranges.map(t=>this.env.model.getters.getRangeString(t,e)).join(", ")}get descriptionString(){return W_.get(this.props.rule.criterion.type).getPreview(this.props.rule.criterion,this.env.model.getters)}}class E$ extends t.Component{static template="o-spreadsheet-DataValidationPanel";static props={onCloseSidePanel:Function};static components={DataValidationPreview:w$,DataValidationEditor:I$};state=t.useState({mode:"list",activeRule:void 0});onPreviewClick(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getDataValidationRule(t,e);s&&(this.state.mode="edit",this.state.activeRule=s)}addDataValidationRule(){this.state.mode="edit",this.state.activeRule=void 0}onExitEditMode(){this.state.mode="list",this.state.activeRule=void 0}localizeDVRule(e){if(!e)return e;return Th(e,this.env.model.getters.getLocale())}get validationRules(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getDataValidationRules(e)}}const x$="#8B008B";var R$;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(R$||(R$={}));class T$ extends Lv{mutators=["updateSearchOptions","updateSearchContent","searchFormulas","selectPreviousMatch","selectNextMatch","replace"];allSheetsMatches=[];activeSheetMatches=[];specificRangeMatches=[];currentSearchRegex=null;initialShowFormulaState;preserveSelectedMatchIndex=!1;irreplaceableMatchCount=0;isSearchDirty=!1;shouldFinalizeUpdateSelection=!1;notificationStore=this.get(kV);selectedMatchIndex=null;toSearch="";toReplace="";searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1,searchScope:"activeSheet",specificRange:void 0};constructor(e){super(e),this.initialShowFormulaState=this.model.getters.shouldShowFormulas(),this.searchOptions.searchFormulas=this.initialShowFormulaState;const t=e(NV);t.register(this),this.onDispose(()=>{this.model.dispatch("SET_FORMULA_VISIBILITY",{show:this.initialShowFormulaState}),t.unRegister(this)})}get searchMatches(){switch(this.searchOptions.searchScope){case"allSheets":return this.allSheetsMatches;case"activeSheet":return this.activeSheetMatches;case"specificRange":return this.specificRangeMatches}}updateSearchContent(e){this._updateSearch(e,this.searchOptions)}updateSearchOptions(e){this._updateSearch(this.toSearch,{...this.searchOptions,...e})}searchFormulas(e){this.model.dispatch("SET_FORMULA_VISIBILITY",{show:e}),this.updateSearchOptions({searchFormulas:e})}selectPreviousMatch(){this.selectNextCell(R$.previous,{jumpToMatchSheet:!0,updateSelection:!0})}selectNextMatch(){this.selectNextCell(R$.next,{jumpToMatchSheet:!0,updateSelection:!0})}handle(e){switch(e.type){case"SET_FORMULA_VISIBILITY":this.updateSearchOptions({searchFormulas:e.show});break;case"UNDO":case"REDO":case"REMOVE_TABLE":case"UPDATE_FILTER":case"REMOVE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"EVALUATE_CELLS":case"UPDATE_CELL":this.isSearchDirty=!0;break;case"ACTIVATE_SHEET":this.isSearchDirty=!0,this.shouldFinalizeUpdateSelection=!0;break;case"REPLACE_SEARCH":for(const t of e.matches)this.replaceMatch(t,e.searchString,e.replaceWith,e.searchOptions);this.irreplaceableMatchCount>0&&this.showReplaceWarningMessage(e.matches.length,this.irreplaceableMatchCount),this.irreplaceableMatchCount=0}}finalize(){this.isSearchDirty&&(this.refreshSearch({jumpToMatchSheet:!1,updateSelection:this.shouldFinalizeUpdateSelection}),this.shouldFinalizeUpdateSelection=!1,this.isSearchDirty=!1)}get allSheetMatchesCount(){return this.allSheetsMatches.length}get activeSheetMatchesCount(){return this.activeSheetMatches.length}get specificRangeMatchesCount(){return this.specificRangeMatches.length}_updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null),this.toSearch=e,this.currentSearchRegex=et(this.toSearch,this.searchOptions),this.refreshSearch({jumpToMatchSheet:!0,updateSelection:!0})}refreshSearch(e){this.preserveSelectedMatchIndex||(this.selectedMatchIndex=null),this.findMatches(),this.selectNextCell(R$.current,e)}getSheetsInSearchOrder(){switch(this.searchOptions.searchScope){case"allSheets":const e=this.getters.getSheetIds(),t=e.findIndex(e=>e===this.getters.getActiveSheetId());return[e[t],...e.slice(t+1),...e.slice(0,t)];case"activeSheet":return[this.getters.getActiveSheetId()];case"specificRange":const s=this.searchOptions.specificRange;return s&&s?[s.sheetId]:[]}}findMatches(){const e=[];if(this.toSearch)for(const t of this.getters.getSheetIds())e.push(...this.findMatchesInSheet(t));if(this.allSheetsMatches=e,this.activeSheetMatches=e.filter(e=>e.sheetId===this.getters.getActiveSheetId()),this.searchOptions.specificRange){const{sheetId:t,zone:s}=this.searchOptions.specificRange;this.specificRangeMatches=e.filter(e=>e.sheetId===t&&Gt(e.col,e.row,s))}else this.specificRangeMatches=[]}findMatchesInSheet(e){const t=[],{left:s,right:o,top:i,bottom:n}=this.getters.getSheetZone(e);for(let r=i;r<=n;r++)for(let i=s;i<=o;i++){const s=this.getters.isColHidden(e,i),o=this.getters.isRowHidden(e,r);if(s||o)continue;const n={sheetId:e,col:i,row:r};if(this.currentSearchRegex?.test(this.getSearchableString(n))){const s={sheetId:e,col:i,row:r};t.push(s)}}return t}selectNextCell(e,t){const s=this.searchMatches;if(!s.length)return void(this.selectedMatchIndex=null);let o;if(null===this.selectedMatchIndex){let e=-1;for(const t of this.getSheetsInSearchOrder())if(e=s.findIndex(e=>e.sheetId===t),-1!==e)break;o=e}else o=this.selectedMatchIndex+e;o=(o+s.length)%s.length,this.selectedMatchIndex=o;const i=s[o];t.jumpToMatchSheet&&this.getters.getActiveSheetId()!==i.sheetId&&(this.preserveSelectedMatchIndex=!0,this.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:i.sheetId}),this.preserveSelectedMatchIndex=!1,this.isSearchDirty=!1),this.model.selection.getBackToDefault(),t.updateSelection&&this.model.selection.selectCell(i.col,i.row)}replace(){null!==this.selectedMatchIndex&&(this.preserveSelectedMatchIndex=!0,this.shouldFinalizeUpdateSelection=!0,this.model.dispatch("REPLACE_SEARCH",{searchString:this.toSearch,replaceWith:this.toReplace,matches:[this.searchMatches[this.selectedMatchIndex]],searchOptions:this.searchOptions}),this.preserveSelectedMatchIndex=!1)}replaceAll(){this.model.dispatch("REPLACE_SEARCH",{searchString:this.toSearch,replaceWith:this.toReplace,matches:this.searchMatches,searchOptions:this.searchOptions})}showReplaceWarningMessage(e,t){const s=e-t;0===s?this.notificationStore.notifyUser({type:"warning",sticky:!1,text:Cs("Match(es) cannot be replaced as they are part of a formula.")}):this.notificationStore.notifyUser({type:"warning",sticky:!1,text:Cs("%(replaceable_count)s match(es) replaced. %(irreplaceable_count)s match(es) cannot be replaced as they are part of a formula.",{replaceable_count:s,irreplaceable_count:t})})}replaceMatch(e,t,s,o){const i=this.getters.getCell(e);if(!i?.content)return;if(i?.isFormula&&!o.searchFormulas)return void this.irreplaceableMatchCount++;const n=et(t,o),r=new RegExp(n.source,n.flags+"g"),a=vh(this.getters.getCellText(e,{showFormula:o.searchFormulas}).replace(r,s),this.getters.getLocale());this.model.dispatch("UPDATE_CELL",{...e,content:a})}getSearchableString(e){return this.getters.getCellText(e,{showFormula:this.searchOptions.searchFormulas})}get highlights(){const e=[],t=this.getters.getActiveSheetId();for(const[s,o]of this.searchMatches.entries()){if(o.sheetId!==t)continue;const i=Jt(o),n=this.getters.expandZone(t,i),{width:r,height:a}=this.getters.getVisibleRect(n);r>0&&a>0&&e.push({range:this.model.getters.getRangeFromZone(t,n),color:x$,noBorder:s!==this.selectedMatchIndex,thinLine:!0,fillAlpha:.2})}if("specificRange"===this.searchOptions.searchScope){const s=this.searchOptions.specificRange;s&&s.sheetId===t&&e.push({range:s,color:x$,noFill:!0,thinLine:!0})}return e}}class A$ extends t.Component{static template="o-spreadsheet-FindAndReplacePanel";static components={SelectionInput:iz,Section:YV,Checkbox:hz,ValidationMessages:MG};static props={onCloseSidePanel:Function};searchInput=t.useRef("searchInput");store;state;updateSearchContent;get hasSearchResult(){return null!==this.store.selectedMatchIndex}get searchOptions(){return this.store.searchOptions}get allSheetsMatchesCount(){return Cs("%s matches in all sheets",this.store.allSheetMatchesCount)}get currentSheetMatchesCount(){return Cs("%(matches)s matches in %(sheetName)s",{matches:this.store.activeSheetMatchesCount,sheetName:this.env.model.getters.getSheetName(this.env.model.getters.getActiveSheetId())})}get specificRangeMatchesCount(){const e=this.searchOptions.specificRange;if(!e)return"";const{sheetId:t,zone:s}=e;return Cs("%(matches)s matches in range %(range)s of %(sheetName)s",{matches:this.store.specificRangeMatchesCount,range:Pt(s),sheetName:this.env.model.getters.getSheetName(t)})}get searchInfo(){return this.store.toSearch?[this.specificRangeMatchesCount,this.currentSheetMatchesCount,this.allSheetsMatchesCount]:[]}setup(){this.store=Av(T$),this.state=t.useState({dataRange:""}),t.onMounted(()=>this.searchInput.el?.focus()),t.onWillUnmount(()=>this.updateSearchContent.stopDebounce()),this.updateSearchContent=Fe(this.store.updateSearchContent,200),t.useExternalListener(window,"keydown",e=>{const t=LN(e);"Ctrl+F"!==t&&"Ctrl+H"!==t||(this.searchInput.el?.focus(),e.preventDefault(),e.stopPropagation())},{capture:!0})}onFocusSearch(){this.updateDataRange()}onSearchInput(e){this.updateSearchContent(e.target.value)}onKeydownSearch(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),e.shiftKey?this.store.selectPreviousMatch():this.store.selectNextMatch())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),this.store.replace())}searchFormulas(e){this.store.searchFormulas(e)}searchExactMatch(e){this.store.updateSearchOptions({exactMatch:e})}searchMatchCase(e){this.store.updateSearchOptions({matchCase:e})}changeSearchScope(e){const t=e.target.value;this.store.updateSearchOptions({searchScope:t})}onSearchRangeChanged(e){this.state.dataRange=e[0]}updateDataRange(){if(!this.state.dataRange||"specificRange"!==this.searchOptions.searchScope)return;const e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.dataRange);this.store.updateSearchOptions({specificRange:e})}get pendingSearch(){return this.updateSearchContent.isDebouncePending()}}const _$=new Jg,D$={name:Gg.Custom,code:"",symbol:"",decimalPlaces:2,position:"after"};class O$ extends Lv{mutators=["updateFormat","changeCategory","selectCurrency","changeCurrencyCode","changeCurrencySymbol","updateAvailableCurrencies"];invalidFormat=!1;currentFormat=this.formatInSelection;category=this.detectFormatCategory(this.formatInSelection);selectedCurrencyIndex=0;currencyCode="";currencySymbol="";isAccountingFormat=!1;availableCurrencies=[D$,..._$.getAll()];lastFormatInSelection=this.currentFormat;usedFormatForCategory={};constructor(e,t){super(e),t&&(this.category=t),this.model.selection.observe(this,{handleEvent:this.handleSelectionEvent.bind(this)}),this.onDispose(()=>{this.model.selection.unobserve(this)})}handle(){const e=this.formatInSelection;e&&this.lastFormatInSelection!==e&&(this.setActiveFormat(e),this.lastFormatInSelection=e)}handleSelectionEvent(){if(this.getters.isGridSelectionActive()){const e=this.formatInSelection;e&&e!==this.lastFormatInSelection&&(this.setActiveFormat(e),this.lastFormatInSelection=e)}}setActiveFormat(e){this.currentFormat=e,this.invalidFormat=!pn(e||""),this.category=this.detectFormatCategory(e)}get categories(){return[{label:Cs("Number"),value:"number"},{label:Cs("Date"),value:"date"},{label:Cs("Currency"),value:"currency"}]}get formatInSelection(){const e=this.getters.getActivePosition();return"VALUE"===this.getters.getPivotCellFromPosition(e).type?this.getters.getEvaluatedCell(e).format:this.getters.getCell(e)?.format}detectFormatCategory(e){return e?ji(e)?"date":e.includes("$")||e.includes('"')?"currency":"number":"number"}get formatProposals(){return"date"===this.category?this.dateFormatProposals:"currency"===this.category?this.currencyFormatProposals:"number"===this.category?this.numberFormatProposals:[]}get numberFormatProposals(){const e=["0.00","0","#,##0","#,##0.00","0%","0.00%","0.00e","0.00;(0.00);-"].map(e=>({label:zi(-1234.56,{format:e,locale:this.getters.getLocale()}),format:e}));return[{label:Cs("Automatic"),format:void 0},{label:Cs("Plain text"),format:"@"},...e]}get dateFormatProposals(){const e=this.getters.getLocale();return[e.dateFormat,e.timeFormat,e.dateFormat+" "+e.timeFormat,"dddd d mmmm yyyy hh:mm:ss a","yyyy-mm-dd","yyyy-mm-dd hh:mm:ss","dddd d mmmm yyyy","d mmmm yyyy","ddd d mmm yyyy","d mmm yyyy","mmmm yyyy","mmm yyyy","hhhh:mm:ss","qq yyyy","qqqq yyyy"].map(t=>({label:zi(EB,{format:t,locale:e}),format:t}))}get currencyFormatProposals(){const e=this.availableCurrencies[this.selectedCurrencyIndex],t=e.position,s="before"===e.position?"after":"before",o=this.currencySymbol.trim()?this.currencySymbol:"",i=this.currencyCode.trim()?this.currencyCode:"",n=e.decimalPlaces;if(!o&&!i)return[];const r=[{symbol:o,position:t,decimalPlaces:0},{symbol:o,position:t,decimalPlaces:n},{symbol:o,position:t,decimalPlaces:0,code:i},{symbol:o,position:t,decimalPlaces:n,code:i},{symbol:o,position:s,decimalPlaces:0},{symbol:o,position:s,decimalPlaces:n},{symbol:o,position:s,decimalPlaces:0,code:i},{symbol:o,position:s,decimalPlaces:n,code:i}],a=new Set,l=this.getters.getLocale();return r.map(e=>{const t=this.isAccountingFormat?tn(e):en(e);if((e.symbol||e.code)&&!a.has(t))return a.add(t),{format:t,label:zi(1e3,{format:t,locale:l})}}).filter(De)}get formatExamples(){const e=this.currentFormat,t=this.getters.getLocale();if(!e||!pn(e))return[];if("date"===this.category)return[{label:Cs("Sample:"),value:zi(EB,{format:e,locale:t})}];{const s=function(e){return pi(e).length}(e),o=[{label:Cs("Positive:"),value:zi(1234.56,{format:e,locale:t})},{label:Cs("Negative:"),value:zi(-1234.56,{format:e,locale:t})},{label:Cs("Zero:"),value:zi(0,{format:e,locale:t})}];return 4===s&&o.push({label:Cs("Text:"),value:zi("Text",{format:e,locale:t})}),o}}updateAvailableCurrencies(){this.availableCurrencies=[D$,..._$.getAll()]}updateFormat(e){this.currentFormat=e,this.invalidFormat=!pn(e),this.invalidFormat||(this.lastFormatInSelection=e,this.model.dispatch("SET_FORMATTING_WITH_PIVOT",{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),format:e||""}))}changeCategory(e){if(e===this.category)return"noStateChange";this.usedFormatForCategory[this.category]=this.currentFormat,this.category=e;const t=this.usedFormatForCategory[e]||this.formatProposals[0]?.format||"";this.updateFormat(t)}selectCurrency(e){const t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.selectedCurrencyIndex=e;const s=this.availableCurrencies[e];this.currencyCode=s.code,this.currencySymbol=s.symbol,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||"")}changeCurrencyCode(e){const t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.currencyCode=e,this.selectedCurrencyIndex=0,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||"")}changeCurrencySymbol(e){const t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.currencySymbol=e,this.selectedCurrencyIndex=0,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||"")}toggleAccountingFormat(){const e=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.isAccountingFormat=!this.isAccountingFormat,this.updateFormat(this.formatProposals[e]?.format||this.formatProposals[0]?.format||"")}get invalidFormatMessage(){return this.invalidFormat?Cs("The format entered is not valid."):void 0}}class F$ extends t.Component{static template="o-spreadsheet-MoreFormatsPanel";static props={onCloseSidePanel:Function,category:{type:String,optional:!0}};static components={BadgeSelection:EW,Section:YV,TextInput:hW,Checkbox:hz};store;setup(){this.store=Av(O$,this.props.category),t.onWillStart(()=>this.loadCurrencies()),t.onWillUpdateProps(e=>{e.category&&e.category!==this.props.category&&this.store.changeCategory(e.category)})}async loadCurrencies(){if(0===_$.getAll().length){(await(this.env.loadCurrencies?.()??Promise.resolve([]))).forEach((e,t)=>{_$.replace(t.toString(),e)}),this.store.updateAvailableCurrencies()}}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:"")}updateSelectCurrency(e){const t=e.target,s=parseInt(t.value,10);this.store.selectCurrency(s)}isFormatSelected(e){return e===this.store.currentFormat}}class P$ extends Lv{pivotId;initialMeasure;mutators=["cancelMeasureDisplayEdition","updateMeasureDisplayType","updateMeasureDisplayField","updateMeasureDisplayValue"];measureDisplay;constructor(e,t,s){super(e),this.pivotId=t,this.initialMeasure=s,this.measureDisplay=s.display||{type:"no_calculations"}}updateMeasureDisplayType(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(e,this.measureDisplay.fieldNameWithGranularity,this.measureDisplay.value))}updateMeasureDisplayField(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,e,this.measureDisplay.value))}updateMeasureDisplayValue(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,this.measureDisplay.fieldNameWithGranularity,e))}updatePivotMeasureDisplay(e){const t=he(this.model.getters.getPivotCoreDefinition(this.pivotId)),s=this.getMeasureIndex(this.initialMeasure.id,t),o={...t.measures[s],display:e};t.measures[s]=o;this.model.dispatch("UPDATE_PIVOT",{pivot:t,pivotId:this.pivotId}).isSuccessful&&(this.measureDisplay=e)}getMeasureDisplay(e,t,s){switch(e){case"no_calculations":case"%_of_grand_total":case"%_of_col_total":case"%_of_row_total":case"%_of_parent_row_total":case"%_of_parent_col_total":case"index":return{type:e};case"%_of_parent_total":case"running_total":case"%_running_total":case"rank_asc":case"rank_desc":return t||(t=this.fields[0]?.nameWithGranularity),{type:e,fieldNameWithGranularity:t};case"%_of":case"difference_from":case"%_difference_from":t||(t=this.fields[0]?.nameWithGranularity);const o=this.getPossibleValues(t);return void 0!==s&&o.find(e=>e.value===s)||(s=tD),{type:e,fieldNameWithGranularity:t,value:s??tD}}}getMeasureIndex(e,t){const s=t.measures.findIndex(t=>t.id===e);if(-1===s)throw new Error(`Measure with id ${e} not found in pivot.`);return s}get doesDisplayNeedsField(){return["%_of_parent_total","running_total","%_running_total","rank_asc","rank_desc"].includes(this.measureDisplay.type)||this.doesDisplayNeedsValue}get fields(){const e=this.getters.getPivot(this.pivotId).definition;return[...e.columns,...e.rows].map(e=>({...e,displayName:Pp(e)}))}get doesDisplayNeedsValue(){return this.isDisplayValueDependant(this.measureDisplay)}isDisplayValueDependant(e){return["%_of","difference_from","%_difference_from"].includes(e.type)}get values(){const e=this.measureDisplay;return this.isDisplayValueDependant(e)?this.getPossibleValues(e.fieldNameWithGranularity):[]}getPossibleValues(e){const t=[{value:tD,label:Cs("(previous)")},{value:sD,label:Cs("(next)")}],s=this.fields.find(t=>t.nameWithGranularity===e);if(!s)return[];return[...t,...this.getters.getPivot(this.pivotId).getPossibleFieldValues(s)]}cancelMeasureDisplayEdition(){const e=he(this.model.getters.getPivotCoreDefinition(this.pivotId)),t=this.getMeasureIndex(this.initialMeasure.id,e);e.measures[t]={...e.measures[t],display:this.initialMeasure.display},this.model.dispatch("UPDATE_PIVOT",{pivot:e,pivotId:this.pivotId})}}class M$ extends t.Component{static template="o-spreadsheet-PivotMeasureDisplayPanel";static props={onCloseSidePanel:Function,pivotId:String,measure:Object};static components={Section:YV,Checkbox:hz,RadioSelection:TW};measureDisplayTypeLabels=Xg.labels;measureDisplayDescription=Xg.documentation;store;setup(){this.store=Av(P$,this.props.pivotId,this.props.measure)}onSave(){this.env.replaceSidePanel("PivotSidePanel",`pivot_measure_display_${this.props.pivotId}_${this.props.measure.id}`,{pivotId:this.props.pivotId})}onCancel(){this.store.cancelMeasureDisplayEdition(),this.env.replaceSidePanel("PivotSidePanel",`pivot_measure_display_${this.props.pivotId}_${this.props.measure.id}`,{pivotId:this.props.pivotId})}get fieldChoices(){return this.store.fields.map(e=>({value:e.nameWithGranularity,label:e.displayName}))}}function N$(e,t){const s=e.getActiveSheetId(),i=function(e,t){const s=[],o=e.getActiveSheetId();for(const i of e.getSheetViewVisibleCols())for(const n of e.getSheetViewVisibleRows()){const r={sheetId:o,col:i,row:n};t===e.getPivotIdFromPosition(r)&&s.push(r)}return s}(e,t);return ns(i.map(Jt)).map(t=>({range:e.getRangeFromZone(s,t),noFill:!0,color:o}))}class k$ extends t.Component{static template="o-spreadsheet-PivotDeferUpdate";static props={deferUpdate:Boolean,isDirty:Boolean,toggleDeferUpdate:Function,discard:Function,apply:Function};static components={Section:YV,Checkbox:hz};get deferUpdatesLabel(){return Cs("Defer updates")}get deferUpdatesTooltip(){return Cs("Changing the pivot definition requires to reload the data. It may take some time.")}}class L$ extends t.Component{static template="o-spreadsheet-PivotCustomGroupsCollapsible";static props={pivotId:String,customField:Object,onCustomFieldUpdated:Function};static components={SidePanelCollapsible:gV,TextInput:hW,Checkbox:hz};get groups(){return this.props.customField.groups.sort((e,t)=>e.isOtherGroup||t.isOtherGroup?e.isOtherGroup?1:-1:0)}get hasOthersGroup(){return this.props.customField.groups.some(e=>e.isOtherGroup)}addOthersGroup(){if(this.hasOthersGroup)return;const e={name:kp(Cs("Others"),this.props.customField),values:[],isOtherGroup:!0},t=[...this.props.customField.groups,e];this.updateCustomField({...this.props.customField,groups:t})}onDeleteGroup(e){const t=[...this.props.customField.groups];t.splice(e,1),this.updateCustomField({...this.props.customField,groups:t})}onRenameGroup(e,t){const s=he(this.props.customField.groups),o=s[e];o&&(o.name=kp(t,this.props.customField),this.updateCustomField({...this.props.customField,groups:s}))}updateCustomField(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.props.onCustomFieldUpdated({customFields:{...t.customFields,[e.name]:e}})}}function V$(e,t,s,o){const i=[];e=e.toLowerCase();for(const n of e){const e=t.toLocaleLowerCase().indexOf(n);-1!==e&&(i.push({value:t.slice(0,e),color:""},{value:t[e],color:s,classes:[o]}),t=t.slice(e+1))}return i.push({value:t}),i.filter(e=>e.value)}class z$ extends t.Component{static template="o-spreadsheet-AddDimensionButton";static components={Popover:jL,TextValueProvider:bV};static props={onFieldPicked:Function,fields:Array,slots:{type:Object,optional:!0}};buttonRef=t.useRef("button");popover=t.useState({isOpen:!1});search=t.useState({input:""});autoComplete;setup(){this.autoComplete=Av(LV),this.autoComplete.useProvider(this.getProvider()),t.useExternalListener(window,"click",e=>{e.target!==this.buttonRef.el&&(this.popover.isOpen=!1)}),lW({refName:"autofocus"})}getProvider(){return{proposals:this.proposals,autoSelectFirstProposal:!1,selectProposal:e=>{const t=this.props.fields.find(t=>t.string===e);t&&this.pickField(t)}}}get proposals(){let e;return e=this.search.input?LS(this.search.input,this.props.fields,e=>e.string===e.name?e.string:e.string+e.name):this.props.fields,e.map(e=>{const t=e.string;return{text:t,fuzzySearchKey:t,htmlContent:V$(this.search.input,t,g,"o-semi-bold")}})}get popoverProps(){const{x:e,y:t,width:s,height:o}=this.buttonRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:s,height:o},positioning:"bottom-left"}}updateSearch(e){this.search.input=e,this.autoComplete.useProvider(this.getProvider())}pickField(e){this.props.onFieldPicked(e.name),this.togglePopover()}togglePopover(){this.popover.isOpen=!this.popover.isOpen,this.search.input="",this.autoComplete.useProvider(this.getProvider())}onKeyDown(e){switch(e.key){case"Enter":const t=this.autoComplete.provider?.proposals;1===t?.length&&this.autoComplete.provider?.selectProposal(t[0].text||"");const s=this.autoComplete.selectedProposal;this.autoComplete.provider?.selectProposal(s?.text||"");break;case"ArrowUp":case"ArrowDown":this.autoComplete.moveSelection("ArrowDown"===e.key?"next":"previous");break;case"Escape":this.popover.isOpen=!1}}}class H$ extends t.Component{static template="o-spreadsheet-PivotDimension";static props={dimension:Object,onRemoved:{type:Function,optional:!0},onNameUpdated:{type:Function,optional:!0},slots:{type:Object,optional:!0}};static components={CogWheelMenu:fW,TextInput:hW};updateName(e){this.props.onNameUpdated?.(this.props.dimension,""===e||e.startsWith("=")?void 0:e)}}class U$ extends t.Component{static template="o-spreadsheet-PivotDimensionGranularity";static props={dimension:Object,onUpdated:Function,availableGranularities:Set,allGranularities:Array};periods=yp}class B$ extends t.Component{static template="o-spreadsheet-PivotDimensionOrder";static props={dimension:Object,onUpdated:Function}}class G$ extends t.Component{static template="o-spreadsheet-PivotMeasureEditor";static components={PivotDimension:H$,StandaloneComposer:HV};static props={definition:Object,measure:Object,onMeasureUpdated:Function,onRemoved:Function,generateMeasureId:Function,aggregators:Object,pivotId:String};getMeasureAutocomplete(){return e=this.props.definition,t=this.props.measure,{sequence:0,autoSelectFirstProposal:!0,getProposals(s){const o=e.measures.filter(e=>e!==t).map(e=>{const t=ge(e.id);return{text:t,description:e.displayName,htmlContent:[{value:t,color:_}],fuzzySearchKey:e.displayName+t+e.fieldName}}),i=e.rows.concat(e.columns).map(e=>{const t=ge(e.nameWithGranularity);return{text:t,description:e.displayName,htmlContent:[{value:t,color:_}],fuzzySearchKey:e.displayName+t+e.fieldName}});return o.concat(i)},selectProposal(e,t){let s=e.end;"SYMBOL"===e.type&&(s=e.start);const o=e.end;this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}};var e,t}updateMeasureFormula(e){this.props.onMeasureUpdated({...this.props.measure,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:"="===e[0]?e:"="+e}})}updateAggregator(e){this.props.onMeasureUpdated({...this.props.measure,aggregator:e,id:this.props.generateMeasureId(this.props.measure.fieldName,e)})}updateName(e,t){this.props.measure.computedBy&&t?this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t,id:this.props.generateMeasureId(t,this.props.measure.aggregator),fieldName:t}):this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t})}toggleMeasureVisibility(){this.props.onMeasureUpdated({...this.props.measure,isHidden:!this.props.measure.isHidden})}openShowValuesAs(){this.env.replaceSidePanel("PivotMeasureDisplayPanel",`pivot_key_${this.props.pivotId}`,{pivotId:this.props.pivotId,measure:this.props.measure})}getColoredSymbolToken(e){if("SYMBOL"!==e.type)return;const t=ue(e.value,"'");return this.props.definition.columns.some(e=>e.nameWithGranularity===t)||this.props.definition.rows.some(e=>e.nameWithGranularity===t)||this.props.definition.measures.some(e=>e.id===t&&e.id!==this.props.measure.id)?_:void 0}get isCalculatedMeasureInvalid(){return zx(this.props.measure.computedBy?.formula??"").isBadExpression}}class W$ extends t.Component{static template="o-spreadsheet-PivotSortSection";static components={Section:YV};static props={definition:Object,pivotId:String};get hasValidSort(){const e=this.env.model.getters.getPivot(this.props.pivotId);return!!this.props.definition.sortedColumn&&Np(this.props.definition.sortedColumn,e)}get sortDescription(){const e="asc"===this.props.definition.sortedColumn?.order?Cs("ascending"):Cs("descending");return Cs("Sorted on column (%(ascOrDesc)s):",{ascOrDesc:e})}get sortValuesAndFields(){const e=this.props.definition.sortedColumn;if(!e)return[];const t=this.env.model.getters.getPivot(this.props.pivotId),s=this.env.model.getters.getLocale(),o=[],i=[];for(const n of e.domain){o.push(n);const{value:e,format:r}=t.getPivotHeaderValueAndFormat(o),a=zi(e,{format:r,locale:s}),l=t.definition.getDimension(n.field);i.push({field:Pp(l),value:a})}0===e.domain.length&&i.push({value:Cs("Total")});const n=t.getMeasure(e.measure).displayName;return i.push({value:n,field:Cs("Measure")}),i}}class $$ extends t.Component{static template="o-spreadsheet-PivotLayoutConfigurator";static components={AddDimensionButton:z$,PivotDimension:H$,PivotDimensionOrder:B$,PivotDimensionGranularity:U$,PivotMeasureEditor:G$,PivotSortSection:W$,PivotCustomGroupsCollapsible:L$};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=t.useRef("pivot-dimensions");dragAndDrop=KV();AGGREGATORS=vp;composerFocus;isDateOrDatetimeField=wp;setup(){this.composerFocus=Tv(zv)}startDragAndDrop(e,t){if(0!==t.button||"SELECT"===t.target.tagName)return;const s=this.getDimensionElementsRects(),o=this.props.definition,{columns:i,rows:n}=o,r=[...i.map(e=>e.nameWithGranularity),"__rows_title__",...n.map(e=>e.nameWithGranularity)],a=i.concat(n),l=r.map((e,t)=>({id:e,size:s[t+1].height,position:s[t+1].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:l,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{const s=r.findIndex(t=>t===e);if(s===t)return;const o=[...r];o.splice(s,1),o.splice(t,0,e);const i=o.slice(0,o.indexOf("__rows_title__")),n=o.slice(o.indexOf("__rows_title__")+1);this.props.onDimensionsUpdated({columns:i.map(e=>a.find(t=>t.nameWithGranularity===e)).filter(De),rows:n.map(e=>a.find(t=>t.nameWithGranularity===e)).filter(De)})}})}getGranularitiesFor(e){return wp(e)?"date"===e.type?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(0!==t.button||"SELECT"===t.target.tagName||"INPUT"===t.target.tagName||"inactive"!==this.composerFocus.focusMode)return;const s=this.getDimensionElementsRects(),o=this.props.definition,{measures:i,columns:n,rows:r}=o,a=i.map(e=>e.id),l=3+n.length+r.length,c=a.map((e,t)=>({id:e,size:s[t+l].height,position:s[t+l].y}));this.dragAndDrop.start("vertical",{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{const s=a.findIndex(t=>t===e);if(s===t)return;const o=[...a];o.splice(s,1),o.splice(t,0,e),this.props.onDimensionsUpdated({measures:o.map(e=>i.find(t=>t.id===e)).filter(De)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{const t=getComputedStyle(e),s=e.getBoundingClientRect();return{x:s.x,y:s.y,width:s.width+parseInt(t.marginLeft||"0")+parseInt(t.marginRight||"0"),height:s.height+parseInt(t.marginTop||"0")+parseInt(t.marginBottom||"0")}})}removeDimension(e){const{columns:t,rows:s}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:s.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){const{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){const{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:"asc"}])})}addRowDimension(e){const{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:"asc"}])})}addMeasureDimension(e){const{measures:t}=this.props.definition,s=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,s),fieldName:e,aggregator:s}])})}updateMeasure(e,t){const{measures:s}=this.props.definition,o={measures:s.map(s=>s.id===e.id?t:s)};this.props.definition.sortedColumn?.measure===e.id&&(o.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(o)}getMeasureId(e,t){const s=e.replaceAll("'","")+(t?`:${t}`:"");let o=s,i=2;for(;this.props.definition.measures.some(e=>e.id===o);)o=`${s}:${i}`,i++;return o}getDefaultMeasureAggregator(e){const t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:"count"}addCalculatedMeasure(){const{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,"sum"),fieldName:t,aggregator:"sum",computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:"=0"}}])})}getCustomField(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);return t.customFields?.[e.nameWithGranularity]}updateOrder(e,t){const{rows:s,columns:o}=this.props.definition;this.props.onDimensionsUpdated({rows:s.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,order:t||void 0}:s),columns:o.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,order:t||void 0}:s)})}updateGranularity(e,t){const{rows:s,columns:o}=this.props.definition;this.props.onDimensionsUpdated({rows:s.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,granularity:t}:s),columns:o.map(s=>s.nameWithGranularity===e.nameWithGranularity?{...s,granularity:t}:s)})}getMeasureDescription(e){const t=e.display;if(!t||"no_calculations"===t.type)return"";const s=this.env.model.getters.getPivot(this.props.pivotId),o=[...s.definition.columns,...s.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=o?Pp(o):"";return Xg.descriptions[t.type](i)}getHugeDimensionErrorMessage(e){const t=this.env.model.getters.getPivot(this.props.pivotId).getPossibleFieldValues(e);return t.length>100?Cs("This dimension contains a lot of values (%s), and might slow down the pivot table.",t.length):void 0}}class q$ extends t.Component{static template="o-spreadsheet-PivotTitleSection";static components={CogWheelMenu:fW,Section:YV,TextInput:hW};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:Cs("Flip axes"),icon:"o-spreadsheet-Icon.EXCHANGE",execute:this.props.flipAxis},{name:Cs("Duplicate"),icon:"o-spreadsheet-Icon.COPY",execute:()=>this.duplicatePivot()},{name:Cs("Delete"),icon:"o-spreadsheet-Icon.TRASH",execute:()=>this.delete()}]}get name(){return this.env.model.getters.getPivotName(this.props.pivotId)}get displayName(){return this.env.model.getters.getPivotDisplayName(this.props.pivotId)}duplicatePivot(){const e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),s=this.env.model.dispatch("DUPLICATE_PIVOT_IN_NEW_SHEET",{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t});let o;o=s.isSuccessful?Cs("Pivot duplicated."):s.isCancelledBecause("PivotInError")?Cs("Cannot duplicate a pivot in error."):Cs("Pivot duplication failed.");const i=s.isSuccessful?"success":"danger";this.env.notifyUser({text:o,sticky:!1,type:i}),s.isSuccessful&&this.env.openSidePanel("PivotSidePanel",{pivotId:e})}delete(){this.env.askConfirmation(Cs("Are you sure you want to delete this pivot?"),()=>{this.env.model.dispatch("REMOVE_PIVOT",{pivotId:this.props.pivotId})})}onNameChanged(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch("UPDATE_PIVOT",{pivotId:this.props.pivotId,pivot:{...t,name:e}})}}class Z$ extends Lv{pivotId;updateMode;mutators=["reset","deferUpdates","applyUpdate","discardPendingUpdate","update"];_updatesAreDeferred;draft=null;notification=this.get(kV);alreadyNotified=!1;alreadyNotifiedForPivotSize=!1;constructor(e,t,s="canDefer"){super(e),this.pivotId=t,this.updateMode=s,this._updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){if("UPDATE_PIVOT"===e.type)e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}get updatesAreDeferred(){return"neverDefer"!==this.updateMode&&this._updatesAreDeferred}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){const e=AD.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){const e=[{name:"__count",string:Cs("Count"),type:"integer",aggregator:"sum"}],t=this.fields;for(const s in t){const o=t[s];o&&(AD.get(this.pivot.type).isMeasureCandidate(o)&&e.push(o))}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){const e=[],t=this.fields;for(const s in t){const o=t[s];o&&(AD.get(this.pivot.type).isGroupable(o)&&e.push(o))}const{columns:s,rows:o,measures:i}=this.definition,n=i.concat(o).concat(s).map(e=>e.fieldName),r=this.unusedGranularities;return e.filter(e=>wp(e)?!n.includes(e.name)||r[e.name].size>0:!n.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return AD.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return AD.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this._updatesAreDeferred=!0,this.draft=null}deferUpdates(e){!1===e&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this._updatesAreDeferred=e}applyUpdate(){if(this.draft){if(this.model.dispatch("UPDATE_PIVOT",{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot()){const e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:"info",text:Cs("Pivot updates only work with dynamic pivot tables. Use the formula '%s' or re-insert the static pivot from the Data menu.",e),sticky:!0})}const e=this.getters.getPivot(this.pivotId),t=e.isValid()?e.getExpandedTableStructure().numberOfCells:0;!this.alreadyNotifiedForPivotSize&&t>se&&(this.alreadyNotifiedForPivotSize=!0,this.notification.notifyUser({type:"warning",text:Kg(t,this.getters.getLocale()),sticky:!0}))}}discardPendingUpdate(){this.draft=null}update(e){const t=this.getters.getPivotCoreDefinition(this.pivotId),s={...t,...this.draft,...e},o={...s,columns:s.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:s.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:s.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display})),sortedColumn:this.shouldKeepSortedColumn(s)?s.sortedColumn:void 0};if(o.collapsedDomains){const{COL:e,ROW:t}=o.collapsedDomains;o.collapsedDomains={COL:e.filter(e=>this.areDomainFieldsValid(e,o.columns)),ROW:t.filter(e=>this.areDomainFieldsValid(e,o.rows))}}if(!this.draft&&Le(t,o))return;const i=this.addDefaultDateTimeGranularity(this.fields,o);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0;const t=this.getters.getPivotFormulaId(this.pivotId);for(const s of this.getters.getVisibleCellPositions()){const o=this.getters.getCell(s);if(o?.isFormula){const s=EF(o.compiledFormula.tokens),i=s?.args[0]?.value;if(s&&t===i.toString()){if("PIVOT"===s.functionName)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){const{columns:s,rows:o}=t,i=he(s),n=he(o),r=this.getUnusedGranularities(e,t);for(const t of i.concat(n)){const s=e[t.fieldName]?.type;if(("date"===s||"datetime"===s)&&!t.granularity){const e=r[t.fieldName]?.values().next().value||"year";r[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:n}}getUnusedGranularities(e,t){const{columns:s,rows:o,measures:i}=t,n=s.concat(o).concat(i).filter(t=>{const s=e[t.fieldName]?.type;return"date"===s||"datetime"===s}),r={};for(const t of n)r[t.fieldName]=new Set("date"===e[t.fieldName]?.type?this.dateGranularities:this.datetimeGranularities);for(const e of n)r[e.fieldName].delete(e.granularity||"month");return r}shouldKeepSortedColumn(e){const{sortedColumn:t}=e;if(!t)return!0;const s=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find(e=>e.id===t.measure)&&Le(s.columns,e.columns)}areDomainFieldsValid(e,t){const s=t.map(({fieldName:e,granularity:t})=>e+(t?`:${t}`:""));for(let t=0;t<e.length;t++)if(e[t].field!==s[t])return!1;return!0}}class j$ extends t.Component{static template="o-spreadsheet-PivotSpreadsheetSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:$$,Section:YV,SelectionInput:iz,Checkbox:hz,PivotDeferUpdate:k$,PivotTitleSection:q$};store;state;pivotSidePanelRef=t.useRef("pivotSidePanel");setup(){this.store=Av(Z$,this.props.pivotId),this.state=t.useState({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return(!this.store.isDirty||!this.state.rangeHasChanged)&&this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,"forceSheetReference")]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){const e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;const t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){const{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}}const Y$=new Jg;Y$.add("SPREADSHEET",{editor:j$});class X$ extends t.Component{static template="o-spreadsheet-PivotDesignPanel";static props={pivotId:String};static components={Section:YV,Checkbox:hz,NumberInput:OW};store;setup(){this.store=Av(Z$,this.props.pivotId,"neverDefer")}updatePivotStyleNumberProperty(e,t){const s=parseInt(e);this.store.update({style:{...this.pivotStyle,[t]:isNaN(s)?void 0:s}})}updatePivotStyleProperty(e,t){this.store.update({style:{...this.pivotStyle,[e]:t}})}get pivotStyle(){return this.env.model.getters.getPivotCoreDefinition(this.props.pivotId).style||{}}get defaultStyle(){return gp}}class K$ extends t.Component{static template="o-spreadsheet-PivotSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:$$,Section:YV,PivotDesignPanel:X$};state=t.useState({panel:"configuration"});panelContentRef=t.useRef("panelContent");scrollPositions={configuration:0,design:0};setup(){v$(this)}get sidePanelEditor(){const e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw new Error("pivotId does not correspond to a pivot.");return Y$.get(e.type).editor}get highlights(){return N$(this.env.model.getters,this.props.pivotId)}switchPanel(e){const t=this.panelContentRef.el;t&&(this.scrollPositions[this.state.panel]=t.scrollTop),this.state.panel=e}}class J$ extends t.Component{static template="o-spreadsheet-RemoveDuplicatesPanel";static components={ValidationMessages:MG,Section:YV,Checkbox:hz};static props={onCloseSidePanel:Function};state=t.useState({hasHeader:!1,columns:{}});setup(){this.updateColumns(),t.onWillUpdateProps(()=>this.updateColumns())}toggleHasHeader(){this.state.hasHeader=!this.state.hasHeader}toggleAllColumns(){const e=!this.isEveryColumnSelected;for(const t in this.state.columns)this.state.columns[t]=e}toggleColumn(e){this.state.columns[e]=!this.state.columns[e]}onRemoveDuplicates(){this.env.model.dispatch("REMOVE_DUPLICATES",{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()})}getColLabel(e){const t=parseInt(e);let s=Cs("Column %s",lt(t));if(this.state.hasHeader){const e=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSelectedZone().top,i=this.env.model.getters.getEvaluatedCell({sheetId:e,col:t,row:o});"empty"!==i.type&&(s+=` - ${i.value}`)}return s}get isEveryColumnSelected(){return Object.values(this.state.columns).every(e=>e)}get errorMessages(){const e=this.env.model.canDispatch("REMOVE_DUPLICATES",{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()}).reasons,t=new Set;for(const s of e)t.add(Zg.Errors[s]||Zg.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){const e=$t(this.env.model.getters.getSelectedZone());return Cs("%(row_count)s rows and %(column_count)s columns selected",{row_count:e.numberOfRows,column_count:e.numberOfCols})}get canConfirm(){return 0===this.errorMessages.length}updateColumns(){const e=this.env.model.getters.getSelectedZone(),t=this.state.columns,s={};for(let o=e.left;o<=e.right;o++)s[o]=!(o in t)||t[o];this.state.columns=s}getColsToAnalyze(){return Object.keys(this.state.columns).filter(e=>this.state.columns[e]).map(e=>parseInt(e))}}class Q$ extends t.Component{static template="o-spreadsheet-SettingsPanel";static components={Section:YV,ValidationMessages:MG,BadgeSelection:EW};static props={onCloseSidePanel:Function};loadedLocales=[];setup(){t.onWillStart(()=>this.loadLocales())}onLocaleChange(e){const t=this.loadedLocales.find(t=>t.code===e);t&&this.env.model.dispatch("UPDATE_LOCALE",{locale:t})}async loadLocales(){this.loadedLocales=(await this.env.loadLocales()).filter(e=>{const t=fh(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t}).sort((e,t)=>e.name.localeCompare(t.name))}get numberFormatPreview(){return zi(1234567.89,{format:"#,##0.00",locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){const e=this.env.model.getters.getLocale();return zi(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){const e=this.env.model.getters.getLocale();return zi(1.6,{format:Dh(e),locale:e})}get firstDayOfWeek(){const e=this.env.model.getters.getLocale().weekStart;return Li[e%7]}get currentLocale(){return this.env.model.getters.getLocale()}get supportedLocales(){const e=this.currentLocale,t=this.loadedLocales.find(t=>t.code===e.code);if(!t)return[...this.loadedLocales,e].sort((e,t)=>e.name.localeCompare(t.name));if(!Le(e,t)){const s=this.loadedLocales.indexOf(t),o=[...this.loadedLocales];return o[s]=e,o.sort((e,t)=>e.name.localeCompare(t.name)),o}return this.loadedLocales}}const eq={SplitIsDestructive:Cs("This will overwrite data in the subsequent columns. Split anyway?")};const tq=[{name:Cs("Detect automatically"),value:"auto"},{name:Cs("Custom separator"),value:"custom"},{name:Cs("Space"),value:" "},{name:Cs("Comma"),value:","},{name:Cs("Semicolon"),value:";"},{name:Cs("Line Break"),value:Q}];class sq extends t.Component{static template="o-spreadsheet-SplitIntoColumnsPanel";static components={ValidationMessages:MG,Section:YV,Checkbox:hz};static props={onCloseSidePanel:Function};state=t.useState({separatorValue:"auto",addNewColumns:!1,customSeparator:""});setup(){const e=Tv(zv);t.useEffect(e=>{"inactive"!==e&&this.props.onCloseSidePanel()},()=>[e.focusMode]),t.onMounted(()=>{e.activeComposer.stopEdition()})}onSeparatorChange(e){this.state.separatorValue=e}updateCustomSeparator(e){e.target&&(this.state.customSeparator=e.target.value)}updateAddNewColumnsCheckbox(e){this.state.addNewColumns=e}confirm(){(function(e,t,s){let o=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:s});return o.isCancelledBecause("SplitWillOverwriteContent")&&e.askConfirmation(eq.SplitIsDestructive,()=>{o=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:s,force:!0})}),o})(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){const e=this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(const s of e)switch(s){case"SplitWillOverwriteContent":case"EmptySplitSeparator":break;default:t.add(qg.Errors[s]||qg.Errors.Unexpected)}return Array.from(t)}get warningMessages(){const e=[];return this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes("SplitWillOverwriteContent")&&e.push(qg.Errors.SplitWillOverwriteContent),e}get separatorValue(){return"custom"===this.state.separatorValue?this.state.customSeparator:"auto"===this.state.separatorValue?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return tq}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}}function oq(e,t,s,o){e.resetTransform(),function(e,t,s,o){e.save();for(let i=0;i<5;i++)for(let n=0;n<5;n++)e.fillStyle=t.styles[i][n].fillColor||"#fff",e.fillRect(i*s,n*o,s,o);e.restore()}(e,t,s,o),function(e,t,s,o){e.save(),e.translate(0,.5),e.lineWidth=1;for(let i=0;i<5;i++)for(let n=0;n<5;n++){const r=t.borders[i][n];r.top&&(e.strokeStyle=r.top.color,e.beginPath(),e.moveTo(i*s,n*o),e.lineTo(i*s+s,n*o),e.stroke()),r.bottom&&(e.strokeStyle=r.bottom.color,e.beginPath(),e.moveTo(i*s,n*o+o),e.lineTo(i*s+s,n*o+o),e.stroke())}e.resetTransform(),e.translate(.5,0);for(let i=0;i<5;i++)for(let n=0;n<5;n++){const r=t.borders[i][n];r.left&&(e.strokeStyle=r.left.color,e.beginPath(),e.moveTo(i*s,n*o),e.lineTo(i*s,n*o+o),e.stroke()),r.right&&(e.strokeStyle=r.right.color,e.beginPath(),e.moveTo(i*s+s,n*o),e.lineTo(i*s+s,n*o+o+1),e.stroke())}e.restore()}(e,t,s,o),function(e,t,s,o){e.save(),e.translate(0,.5),e.lineWidth=1;const i=Math.floor(s/4),n=Math.floor(o/2);for(let r=0;r<5;r++)for(let a=0;a<5;a++)e.strokeStyle=t.styles[r][a].textColor||"#000",e.beginPath(),e.moveTo(r*s+i+1,a*o+n),e.lineTo(r*s+s-i,a*o+n),e.stroke();e.restore()}(e,t,s,o)}class iq extends t.Component{static template="o-spreadsheet-TableStylePreview";static components={MenuPopover:JL};static props={tableConfig:Object,tableStyle:Object,class:String,styleId:{type:String,optional:!0},selected:{type:Boolean,optional:!0},onClick:{type:Function,optional:!0}};canvasRef=t.useRef("canvas");menu=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});setup(){t.onWillUpdateProps(e=>{Le(this.props.tableConfig,e.tableConfig)&&Le(this.props.tableStyle,e.tableStyle)||this.drawTable(e)}),t.onMounted(()=>this.drawTable(this.props))}drawTable(e){const t=this.canvasRef.el.getContext("2d"),{width:s,height:o}=this.canvasRef.el.getBoundingClientRect();this.canvasRef.el.width=s,this.canvasRef.el.height=o;oq(t,ND(e.tableConfig,e.tableStyle,5,5),(s-1)/5,(o-1)/5)}onContextMenu(e){var t,s;this.props.styleId&&(this.menu.menuItems=(t=this.env,s=this.props.styleId,t.model.getters.isTableStyleEditable(s)?Sv([{id:"editTableStyle",name:Cs("Edit table style"),execute:e=>e.openSidePanel("TableStyleEditorPanel",{styleId:s}),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.EDIT"},{id:"deleteTableStyle",name:Cs("Delete table style"),execute:e=>e.model.dispatch("REMOVE_TABLE_STYLE",{tableStyleId:s}),icon:"o-spreadsheet-Icon.TRASH"}]):[]),this.menu.isOpen=!0,this.menu.anchorRect={x:e.clientX,y:e.clientY,width:0,height:0})}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get styleName(){return this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId).displayName:""}get isStyleEditable(){return!!this.props.styleId&&this.env.model.getters.isTableStyleEditable(this.props.styleId)}editTableStyle(){this.env.openSidePanel("TableStyleEditorPanel",{styleId:this.props.styleId})}}class nq extends t.Component{static template="o-spreadsheet-TableStylesPopover";static components={Popover:jL,TableStylePreview:iq};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0}};categories=qx;tableStyleListRef=t.useRef("tableStyleList");state=t.useState({selectedCategory:this.initialSelectedCategory});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!AN(this.tableStyleListRef.el,e)&&(this.props.closePopover(),e.hasClosedTableStylesPopover=!0)}get displayedStyles(){const e=this.env.model.getters.getTableStyles();return Object.keys(e).filter(t=>e[t].category===this.state.selectedCategory)}get initialSelectedCategory(){return this.props.selectedStyleId?this.env.model.getters.getTableStyle(this.props.selectedStyleId).category:"medium"}newTableStyle(){this.props.closePopover(),this.env.openSidePanel("TableStyleEditorPanel",{onStylePicked:this.props.onStylePicked})}}class rq extends t.Component{static template="o-spreadsheet-TableStylePicker";static components={TableStylesPopover:nq,TableStylePreview:iq};static props={table:Object};state=t.useState({popoverProps:void 0});getDisplayedTableStyles(){const e=this.env.model.getters.getTableStyles(),t=e[this.props.table.config.styleId].category,s=Object.keys(e).filter(s=>e[s].category===t),o=s.indexOf(this.props.table.config.styleId);if(-1===o)return o;const i=4*Math.floor(o/4);return s.slice(i)}onStylePicked(e){const t=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("UPDATE_TABLE",{sheetId:t,zone:this.props.table.range.zone,config:{styleId:e}}),this.closePopover()}onArrowButtonClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps)return void this.closePopover();const t=e.currentTarget,{bottom:s,right:o}=t.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:o,y:s,width:0,height:0},positioning:"top-right",verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}}class aq extends t.Component{static template="o-spreadsheet-TablePanel";static components={TableStylePicker:rq,SelectionInput:iz,ValidationMessages:MG,Checkbox:hz,Section:YV,NumberInput:OW};static props={onCloseSidePanel:Function,table:Object};state;setup(){const e=this.env.model.getters.getActiveSheetId();this.state=t.useState({tableZoneErrors:[],tableXc:this.env.model.getters.getRangeString(this.props.table.range,e),filtersEnabledIfPossible:this.props.table.config.hasFilters})}updateHasFilters(e){this.state.filtersEnabledIfPossible=e,this.updateTableConfig("hasFilters",e)}updateTableConfig(e,t){const s=this.env.model.getters.getActiveSheetId();return this.env.model.dispatch("UPDATE_TABLE",{sheetId:s,zone:this.props.table.range.zone,config:{[e]:t}})}updateHasHeaders(e){const t=e?1:0;this.updateNumberOfHeaders(t)}updateTableIsDynamic(e){const t=e?"dynamic":"forceStatic";if(t===this.props.table.type)return;const s=this.env.model.getters.getTable(FD(this.props.table));if(!s)return;const o=this.env.model.getters.getActiveSheetId(),i=this.env.model.dispatch("UPDATE_TABLE",{sheetId:o,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(s.range),tableType:t}),n=this.env.model.getters.getCoreTable(FD(this.props.table));if(i.isSuccessful&&n){const e=n.range;this.state.tableXc=this.env.model.getters.getRangeString(e,o),this.state.tableZoneErrors=[]}}onChangeNumberOfHeaders(e){const t=parseInt(e);this.updateNumberOfHeaders(t)}updateNumberOfHeaders(e){const t=e>0&&(this.tableConfig.hasFilters||this.state.filtersEnabledIfPossible);return this.env.model.dispatch("UPDATE_TABLE",{sheetId:this.env.model.getters.getActiveSheetId(),zone:this.props.table.range.zone,config:{numberOfHeaders:e,hasFilters:t}})}onRangeChanged(e){const t=this.env.model.getters.getActiveSheetId();this.state.tableXc=e[0];const s=this.env.model.getters.getRangeFromSheetXC(t,this.state.tableXc);this.state.tableZoneErrors=this.env.model.canDispatch("UPDATE_TABLE",{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromXc(t,this.state.tableXc),tableType:this.getNewTableType(s.zone)}).reasons}onRangeConfirmed(){const e=this.env.model.getters.getActiveSheetId();let t=this.env.model.getters.getRangeFromSheetXC(e,this.state.tableXc);if(1===ss(t.zone)){const s=this.env.model.getters.getContiguousZone(e,t.zone);t=this.env.model.getters.getRangeFromZone(e,s)}const s=t.zone,o=this.props.table.range.zone,i=s.top===o.top&&s.left===o.left?"RESIZE_TABLE":"UPDATE_TABLE",n=this.env.model.dispatch(i,{sheetId:e,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(t),tableType:this.getNewTableType(t.zone)}),r={sheetId:e,col:t.zone.left,row:t.zone.top},a=this.env.model.getters.getCoreTable(r);if(n.isSuccessful&&a){const t=FD(a);this.env.model.selection.selectZone({zone:Jt(t),cell:t});const s=a.range;this.state.tableXc=this.env.model.getters.getRangeString(s,e)}}deleteTable(){const e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("REMOVE_TABLE",{sheetId:e,target:[this.props.table.range.zone]})}getNewTableType(e){if("forceStatic"===this.props.table.type)return"forceStatic";const t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.canCreateDynamicTableOnZones(t,[e])?"dynamic":"static"}get tableConfig(){return this.props.table.config}get errorMessages(){return(this.state.tableZoneErrors||[]).map(e=>Yg.Errors[e]||Yg.Errors.Unexpected)}getCheckboxLabel(e){return Yg.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:Yg.Tooltips.filterWithoutHeader}get canBeDynamic(){const e=this.env.model.getters.getActiveSheetId();return"dynamic"===this.props.table.type||this.env.model.getters.canCreateDynamicTableOnZones(e,[this.props.table.range.zone])}get dynamicTableTooltip(){return Yg.Tooltips.isDynamic}}const lq="#3C78D8";class cq extends t.Component{static template="o-spreadsheet-TableStyleEditorPanel";static components={Section:YV,RoundColorPicker:XV,TableStylePreview:iq};static props={onCloseSidePanel:Function,onStylePicked:{type:Function,optional:!0},styleId:{type:String,optional:!0}};state=t.useState(this.getInitialState());setup(){t.useExternalListener(window,"click",()=>this.state.pickerOpened=!1)}getInitialState(){const e=this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId):null;return{pickerOpened:!1,primaryColor:e?.primaryColor||lq,selectedTemplateName:e?.templateName||"lightColoredText",styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=Xv(e)?e:lq,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){const e=this.props.styleId||this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch("CREATE_TABLE_STYLE",{tableStyleId:e,tableStyleName:this.state.styleName,templateName:this.state.selectedTemplateName,primaryColor:this.state.primaryColor}),this.props.onStylePicked?.(e),this.props.onCloseSidePanel()}onCancel(){this.props.onCloseSidePanel()}onDelete(){this.props.styleId&&(this.env.model.dispatch("REMOVE_TABLE_STYLE",{tableStyleId:this.props.styleId}),this.props.onCloseSidePanel())}get colorPreviewStyle(){return JF({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(hR).filter(e=>"none"!==e)}get previewTableConfig(){return{bandedColumns:!1,bandedRows:!0,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,totalRow:!0,hasFilters:!0,styleId:""}}get selectedStyle(){return this.computeTableStyle(this.state.selectedTemplateName)}computeTableStyle(e){return dR(this.state.styleName,e,this.state.primaryColor)}}const hq=new Jg;hq.add("ConditionalFormatting",{title:Cs("Conditional formatting"),Body:C$}),hq.add("ChartPanel",{title:Cs("Chart"),Body:p$,computeState:(e,t)=>{const s=e.getSelectedFigureId(),o=s?e.getChartIdFromFigureId(s):t.chartId;return o&&e.isChartDefined(o)?{isOpen:!0,props:{chartId:o}}:{isOpen:!1}}}),hq.add("FindAndReplace",{title:Cs("Find and Replace"),Body:A$}),hq.add("SplitToColumns",{title:Cs("Split text into columns"),Body:sq}),hq.add("Settings",{title:Cs("Spreadsheet settings"),Body:Q$}),hq.add("RemoveDuplicates",{title:Cs("Remove duplicates"),Body:J$}),hq.add("DataValidation",{title:Cs("Data validation"),Body:E$}),hq.add("DataValidationEditor",{title:Cs("Data validation"),Body:I$}),hq.add("MoreFormats",{title:Cs("More formats"),Body:F$}),hq.add("TableSidePanel",{title:Cs("Edit table"),Body:aq,computeState:e=>{const t=e.getFirstTableInSelection();if(!t)return{isOpen:!1};return{isOpen:!0,props:{table:e.getCoreTable(FD(t))},key:t.id}}}),hq.add("TableStyleEditorPanel",{title:Cs("Create custom table style"),Body:cq,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??"new"})}),hq.add("PivotSidePanel",{title:(e,t)=>Cs("Pivot #%s",e.model.getters.getPivotFormulaId(t.pivotId)),Body:K$,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),hq.add("PivotMeasureDisplayPanel",{title:(e,t)=>{const s=e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id);return Cs('Measure "%s" options',s.displayName)},Body:M$,computeState:(e,t)=>{try{return e.getPivot(t.pivotId).getMeasure(t.measure.id),{isOpen:!0,props:t,key:`pivot_measure_display_${t.pivotId}_${t.measure.id}`}}catch(e){return{isOpen:!1}}}}),hq.add("CarouselPanel",{title:Cs("Carousel"),Body:vW,computeState:(e,t)=>{const s=t.figureId||e.getSelectedFigureId();return s&&e.doesCarouselExist(s)?{isOpen:!0,props:{figureId:s}}:{isOpen:!1}}});class dq{mutators=["setSmallThreshhold"];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}}const uq=350,gq=150;class pq extends Lv{mutators=["open","replace","toggle","close","changePanelSize","resetPanelSize","togglePinPanel","closeMainPanel","changeSpreadsheetWidth","toggleCollapsePanel"];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(dq);get isMainPanelOpen(){return!(!this.mainPanel||!this.mainPanel.componentTag)&&this.computeState(this.mainPanel).isOpen}get isSecondaryPanelOpen(){return!(!this.secondaryPanel||!this.secondaryPanel.componentTag)&&this.computeState(this.secondaryPanel).isOpen}get mainPanelProps(){return this.mainPanel?this.getPanelProps(this.mainPanel):void 0}get mainPanelKey(){return this.mainPanel?this.getPanelKey(this.mainPanel):void 0}get secondaryPanelProps(){return this.secondaryPanel?this.getPanelProps(this.secondaryPanel):void 0}get secondaryPanelKey(){return this.secondaryPanel?this.getPanelKey(this.secondaryPanel):void 0}get totalPanelSize(){return(this.mainPanel?.size||0)+(this.secondaryPanel?.size??0)}getPanelProps(e){const t=this.computeState(e);return t.isOpen?(e.currentPanelProps=t.props??e.currentPanelProps,t.props??{}):{}}getPanelKey(e){const t=this.computeState(e);if(t.isOpen)return t.key}open(e,t={}){if(this.screenWidthStore.isSmall)return;const s={currentPanelProps:t,componentTag:e,size:uq},o=this.computeState(s);if(!o.isOpen)return;if(!this.mainPanel||!this.mainPanel.isPinned||this.mainPanelKey===o.key)return void this._openPanel("mainPanel",s,o);const i=this.mainPanel.isCollapsed?uq:this.mainPanel.size;!this.secondaryPanel&&i+uq>this.availableWidth?this.get(kV).notifyUser({sticky:!1,type:"warning",text:Cs("The window is too small to display multiple side panels.")}):this._openPanel("secondaryPanel",s,o)}replace(e,t,s={}){const o={currentPanelProps:s,componentTag:e,size:uq},i=this.computeState(o);if(!i.isOpen)return;const n=()=>{this.mainPanel?.isCollapsed&&this.toggleCollapsePanel("mainPanel")},r=this.mainPanelKey===i.key,a=this.secondaryPanelKey===i.key;if(r&&this.secondaryPanel)return this.close(),void n();if(a)return this.closeMainPanel(),this.togglePinPanel(),void n();const l=this.mainPanelKey===t?"mainPanel":"secondaryPanel";this._openPanel(l,o,i)}_openPanel(e,t,s){const o=this[e];o&&t.componentTag!==o.componentTag&&o.currentPanelProps?.onCloseSidePanel?.(),this[e]={currentPanelProps:s.props??{},componentTag:t.componentTag,size:o?.size||uq,isCollapsed:o?.isCollapsed||!1,isPinned:!(!o||!("isPinned"in o))&&o.isPinned},this[e].isCollapsed&&this.toggleCollapsePanel(e)}toggle(e,t){const s=this.mainPanel?.isPinned?this.secondaryPanel:this.mainPanel;s&&e===s.componentTag?this.close():this.open(e,t)}close(){this.mainPanel?.isPinned?this.secondaryPanel&&(this.secondaryPanel.currentPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0):(this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=void 0)}closeMainPanel(){this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel||void 0,this.secondaryPanel=void 0}changePanelSize(e,t){const s=this[e];if(!s||"isCollapsed"in s&&s.isCollapsed)return;t=Math.max(t,uq);let o="mainPanel"===e?this.secondaryPanel?.size||0:this.mainPanel?.size||0;t>this.availableWidth-o&&("mainPanel"===e&&this.secondaryPanel&&(this.secondaryPanel.size=Math.max(this.availableWidth-t,uq),o=this.secondaryPanel.size),t=Math.max(this.availableWidth-o,uq)),s.size=t}resetPanelSize(e){this[e]&&(this[e].size=uq)}togglePinPanel(){this.mainPanel&&(this.mainPanel.isPinned=!this.mainPanel.isPinned,!this.mainPanel.isPinned&&this.secondaryPanel&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel,this.secondaryPanel=void 0))}toggleCollapsePanel(e){const t=this[e];t&&(t.isCollapsed?(t.isCollapsed=!1,this.changePanelSize(e,uq)):(t.isCollapsed=!0,t.size=45))}computeState({componentTag:e,currentPanelProps:t}){const s=hq.get(e).computeState,o=s?s(this.getters,t):{isOpen:!0,props:t};return o.isOpen?{...o,key:o.key||e}:o}changeSpreadsheetWidth(e){this.availableWidth=e-gq,this.secondaryPanel&&e-this.totalPanelSize<gq&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0),this.mainPanel&&e-this.totalPanelSize<gq&&(this.mainPanel.size=Math.max(e-gq,uq))}}class mq extends t.Component{static template="o-spreadsheet-TableResizer";static props={table:Object};state=t.useState({highlightZone:void 0});dragNDropGrid=yG(this.env);setup(){v$(this)}get containerStyle(){const e=this.props.table.range.zone,t={...e,left:e.right,top:e.bottom},s=this.env.model.getters.getVisibleRect(t);return 0===s.height||0===s.width?JF({display:"none"}):JF({top:s.y+s.height-6+"px",left:s.x+s.width-6+"px"})}onMouseDown(e){const t=this.props.table.range.zone,s={col:t.left,row:t.top};document.body.style.cursor="nwse-resize";const o=$N(this.env,e);this.dragNDropGrid.start(o,(e,t,o)=>{this.state.highlightZone={left:s.col,top:s.row,right:Math.max(e,s.col),bottom:Math.max(t,s.row)}},()=>{document.body.style.cursor="";const e=this.state.highlightZone;if(!e)return;const t=this.props.table.range.sheetId;this.env.model.dispatch("RESIZE_TABLE",{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0})}get highlights(){return this.state.highlightZone?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:"#777",noFill:!0}]:[]}}const fq={ROW:vG,COL:dG,CELL:sB,GROUP_HEADERS:mG,UNGROUP_HEADERS:fG};class vq extends t.Component{static template="o-spreadsheet-Grid";static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:AG,GridOverlay:BG,GridPopover:GG,HeadersOverlay:YG,MenuPopover:JL,Autofill:IG,ClientTag:EG,Highlight:sW,Popover:jL,VerticalScrollBar:rW,HorizontalScrollBar:nW,TableResizer:mq,Selection:aW};HEADER_HEIGHT=O;HEADER_WIDTH=F;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=yG(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=Tv(NV),this.menuState=t.useState({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.hoveredCell=Tv(nV),this.composerFocusStore=Tv(zv),this.DOMFocusableElementStore=Tv(mV),this.sidePanel=Tv(pq),this.paintFormatStore=Tv(VG),this.clientFocusStore=Tv(SG),Tv(bG),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),t.useExternalListener(document.body,"cut",this.copy.bind(this,!0)),t.useExternalListener(document.body,"copy",this.copy.bind(this,!1)),t.useExternalListener(document.body,"paste",this.paste),t.onMounted(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),KG("canvas",this.env.model,()=>this.env.model.getters.getSheetViewDimensionWithHeaders()),this.onMouseWheel=QG((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=Tv(aV),t.useEffect((e,t)=>{e||t||this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),JG(this.gridRef,this.moveCanvas.bind(this),()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},()=>{const{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){const e=this.env.model.getters.getScrollBarWidth();return JF({top:"26px",left:"48px",height:`calc(100% - ${O+e}px)`,width:`calc(100% - ${F+e}px)`})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>{this.env.model.getters.getActiveCell().type===Xd.empty?this.onComposerCellFocused():this.onComposerContentFocused()},Tab:()=>this.env.model.selection.moveAnchorCell("right",1),"Shift+Tab":()=>this.env.model.selection.moveAnchorCell("left",1),F2:()=>{this.env.model.getters.getActiveCell().type===Xd.empty?this.onComposerCellFocused():this.onComposerContentFocused()},Delete:()=>{this.env.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch("DELETE_UNFILTERED_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch("CLEAN_CLIPBOARD_HIGHLIGHT")},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch("REQUEST_UNDO"),"Ctrl+Y":()=>this.env.model.dispatch("REQUEST_REDO"),F4:()=>this.env.model.dispatch("REQUEST_REDO"),"Ctrl+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>Kz(this.env),"Alt+=":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:s}=this.env.model.getters.getSelection(),o=this.env.model.getters.getAutomaticSums(e,t,s.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&o.length<=1){const t=o[0]?.zone,s=t?this.env.model.getters.zoneToXC(e,o[0].zone):"",i=`=SUM(${s})`;this.onComposerCellFocused(i,{start:5,end:5+s.length})}else this.env.model.dispatch("SUM_SELECTION")},"Alt+Enter":()=>{const e=this.env.model.getters.getActiveCell();e.link&&vv(e.link,this.env)},"Ctrl+Home":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:s}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,s)},"Ctrl+End":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),s=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,s)},"Shift+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},s=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:s,zone:t})},"Ctrl+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},s=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:s,zone:t})},"Ctrl+D":async()=>this.env.model.dispatch("COPY_PASTE_CELLS_ABOVE"),"Ctrl+R":async()=>this.env.model.dispatch("COPY_PASTE_CELLS_ON_LEFT"),"Ctrl+H":()=>this.sidePanel.open("FindAndReplace",{}),"Ctrl+F":()=>this.sidePanel.open("FindAndReplace",{}),"Ctrl+Shift+E":()=>this.setHorizontalAlign("center"),"Ctrl+Shift+L":()=>this.setHorizontalAlign("left"),"Ctrl+Shift+R":()=>this.setHorizontalAlign("right"),"Ctrl+Shift+V":()=>$z(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{const e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),s=1===this.env.model.getters.getSelectedZones().length,o=e.size>0&&s,i=t.size>0&&s;o&&!i?Yz(this.env):i&&!o&&jz(this.env)},"Ctrl+Alt+-":()=>{const e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&0===t.length?this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:"COL",elements:e}):t.length>0&&0===e.length&&this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:"ROW",elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"Shift+PageUp":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PageDown:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PageUp:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"Ctrl+K":()=>Jz(this.env),"Alt+Shift+ArrowRight":()=>this.processHeaderGroupingKey("right"),"Alt+Shift+ArrowLeft":()=>this.processHeaderGroupingKey("left"),"Alt+Shift+ArrowUp":()=>this.processHeaderGroupingKey("up"),"Alt+Shift+ArrowDown":()=>this.processHeaderGroupingKey("down")};focusDefaultElement(){this.env.model.getters.getSelectedFigureId()||"inactive"!==this.composerFocusStore.activeComposer.editionMode||this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw new Error("Grid el is not defined.");return this.gridRef.el}getAutofillPosition(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{x:t.x+t.width-4,y:t.y+t.height-4}}get isAutofillVisible(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(0===t.width||0===t.height)}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t-F,height:e-O,gridOffsetX:F,gridOffsetY:O})}moveCanvas(e,t){const{scrollX:s,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s+e,offsetY:o+t})}processSpaceKey(e){this.env.model.getters.hasBooleanValidationInZones(this.env.model.getters.getSelectedZones())&&(e.preventDefault(),e.stopPropagation(),this.env.model.dispatch("TOGGLE_CHECKBOX",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()}))}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}get focusedClients(){return this.clientFocusStore.focusedClients}getGridRect(){const e=this.env.model.getters.getViewportZoomLevel(),{width:t,height:s}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{...ON(this.gridRef),width:t*e,height:s*e}}onCellClicked(e,t,s,o){if(o.ev.preventDefault(),"editing"===this.composerFocusStore.activeComposer.editionMode&&this.composerFocusStore.activeComposer.stopEdition(),s.expandZone?this.env.model.selection.setAnchorCorner(e,t):s.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t),this.env.isMobile())return;let i=e,n=t;this.dragNDropGrid.start(o,(e,t,s)=>{s.preventDefault(),(e!==i&&-1!==e||t!==n&&-1!==t)&&(i=-1===e?i:e,n=-1===t?n:t,this.env.model.selection.setAnchorCorner(i,n))},()=>{this.env.model.selection.commitSelection(),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){const s=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:s,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:s,col:e,row:t}).type===Xd.empty?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),vV(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){const t=LN(e),s=this.keyDownMapping[t];if(s)return e.preventDefault(),e.stopPropagation(),void s();" "!==t?e.key.startsWith("Arrow")&&this.processArrows(e):this.processSpaceKey(e)}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:s,top:o}=t;let i="CELL";this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(s)?i="COL":this.env.model.getters.getActiveRows().has(o)&&(i="ROW");const{x:n,y:r,width:a}=this.env.model.getters.getVisibleRectWithZoom(t),l=this.getGridRect();this.toggleContextMenu(i,l.x+n+a,l.y+r)}onCellRightClicked(e,t,{x:s,y:o}){const i=this.env.model.getters.getSelectedZones();let n="CELL";Gt(e,t,i[i.length-1])?this.env.model.getters.getActiveCols().has(e)?n="COL":this.env.model.getters.getActiveRows().has(t)&&(n="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(n,s,o)}toggleContextMenu(e,t,s){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.anchorRect={x:t,y:s,width:0,height:0},this.menuState.menuItems=fq[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement))return;if("inactive"!==this.composerFocusStore.activeComposer.editionMode)return;e?MH(this.env):this.env.model.dispatch("COPY");const s=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(s),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();const t=e.clipboardData;if(!t)return;const s=[...t.files]?.find(e=>eP.includes(e.type)),o={content:{[QF.PlainText]:t?.getData(QF.PlainText),[QF.Html]:t?.getData(QF.Html)}};s&&(o.content[s.type]=s);const i=this.env.model.getters.getSelectedZones(),n=this.env.model.getters.isCutOperation(),r=this.env.model.getters.getClipboardId(),a=iP(o.content),l=a.data?.clipboardId;r===l?Hz(this.env,i):await Uz(this.env,i,a),n&&await this.env.clipboard.write({[QF.PlainText]:""})}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(1!==this.env.model.getters.getSelectedZones().length)return;const t=this.env.model.getters.getActiveRows().size>0,s=this.env.model.getters.getActiveCols().size>0;s&&t?this.processHeaderGroupingEventOnWholeSheet(e):s?this.processHeaderGroupingEventOnHeaders(e,"COL"):t?this.processHeaderGroupingEventOnHeaders(e,"ROW"):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){const s=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSelectedZone(),i="COL"===t?o.left:o.top,n="COL"===t?o.right:o.bottom;switch(e){case"right":this.env.model.dispatch("GROUP_HEADERS",{sheetId:s,dimension:t,start:i,end:n});break;case"left":this.env.model.dispatch("UNGROUP_HEADERS",{sheetId:s,dimension:t,start:i,end:n});break;case"down":this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:s,dimension:t,zone:o});break;case"up":this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:s,dimension:t,zone:o})}}processHeaderGroupingEventOnWholeSheet(e){const t=this.env.model.getters.getActiveSheetId();"up"===e?(this.env.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"ROW"}),this.env.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"COL"})):"down"===e&&(this.env.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"ROW"}),this.env.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"COL"}))}processHeaderGroupingEventOnGrid(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getSelectedZone();switch(e){case"down":this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"ROW",zone:s}),this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"COL",zone:s});break;case"up":this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"ROW",zone:s}),this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"COL",zone:s});break;case"right":{const{x:e,y:t,width:o}=this.env.model.getters.getVisibleRectWithZoom(s),i=this.getGridRect();this.toggleContextMenu("GROUP_HEADERS",e+o+i.x,t+i.y);break}case"left":{if(!PH(this.env,"COL")&&!PH(this.env,"ROW"))return;const{x:e,y:t,width:o}=this.env.model.getters.getVisibleRectWithZoom(s),i=this.getGridRect();this.toggleContextMenu("UNGROUP_HEADERS",e+o+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:"cellFocus"})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:"contentFocus"})}get staticTables(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(MD)}get displaySelectionHandler(){return this.env.isMobile()&&"inactive"===this.composerFocusStore.activeComposer.editionMode}}function bq(e,t){const s=`"${t?`${e.name}:${t}`:e.name}"`,o=e.string!==e.name?e.string+s:s;return{text:s,description:e.string+(e.help?` (${e.help})`:""),htmlContent:[{value:s,color:ae.STRING}],fuzzySearchKey:o}}function Sq(e){const t=e.functionContext?.args[0];if(t&&["STRING","NUMBER"].includes(t.type))return t.value}const yq=new Jg;yq.add("SPREADSHEET",!1);class Cq extends t.Component{static template="o-spreadsheet-ClickableCellSortIcon";static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=Tv(zG)}get style(){const e=this.env.model.getters.getCellComputedStyle(this.props.position);return JF({color:e.textColor||I,"background-color":this.getBackgroundColor(e)})}get verticalJustifyClass(){switch(this.env.model.getters.getCellComputedStyle(this.props.position).verticalAlign){case"top":return"justify-content-start";case"middle":return"justify-content-center";default:return"justify-content-end"}}getBackgroundColor(e){const t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?function(e,t){const s=tb(t),o=tb(e),i=s.a+o.a*(1-s.a);return eb({r:Math.round((s.r*s.a+o.r*o.a*(1-s.a))/i),g:Math.round((s.g*s.a+o.g*o.a*(1-s.a))/i),b:Math.round((s.b*s.a+o.b*o.a*(1-s.a))/i),a:i})}(e.fillColor||"#FFFFFF",t):e.fillColor||"#FFFFFF"}}class Iq extends t.Component{static template="o-spreadsheet-FullScreenFigure";static props={};static components={ChartFigure:tV};fullScreenFigureStore;ref=t.useRef("fullScreenFigure");spreadsheetRect=ZL();figureRegistry=oV;setup(){this.fullScreenFigureStore=Tv(GL);const e=Tv(VS);let s;t.onWillUpdateProps(()=>{s!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+"-fullscreen"),s=this.figureUI?.id}),t.useEffect(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){"Escape"===e.key&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return oV.get(this.figureUI.tag).Component}}class wq extends t.Component{static template="o_spreadsheet.PivotHTMLRenderer";static components={Checkbox:hz};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=t.useState({showMissingValuesOnly:!1});setup(){const e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;const e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){const t=this.pivot.getExpandedTableStructure().rows,s=[...t[e].values];if(s.length<=1)return[e];s.pop();const o=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(s));return[e].concat(this.addRecursiveRow(o))}buildColumnsMissing(e){const t=[];for(const e of this.data.columns){const s=[];for(const t in e)for(let o=0;o<e[t].span;o++)s.push(parseInt(t,10));t.push(s)}for(let s=t[t.length-1].length;s>=0;s--)if(!e.includes(s))for(const e of t)e.splice(s,1);const s=[];for(const e in t){const o=[];let i,n=1;for(let s=0;s<t[e].length;s++)i!==t[e][s]?(void 0!==i&&o.push(Object.assign({},this.data.columns[e][i],{span:n})),i=t[e][s],n=1):n++;void 0!==i&&o.push(Object.assign({},this.data.columns[e][i],{span:n})),s.push(o)}return s}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){const s=e.map(()=>[]);for(const o of t)for(const t in e)s[t].push(this.data.values[e[t]][o]);return s}getColumnsIndexes(){const e=new Set;for(let t=0;t<this.data.columns.length;t++){const s=[];for(let e=0;e<this.data.columns[t].length;e++)for(let o=0;o<this.data.columns[t][e].span;o++)s.push(this.data.columns[t][e]);for(let t=0;t<s.length;t++)s[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++){this.data.values[t].find(e=>e.isMissing)&&e.add(t)}return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){const e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(const s of this.data.values)s[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){const s=[];for(const o of t.columns){const t=[];for(const s of o){const o=[];for(let e=0;e<s.fields.length;e++)o.push({value:s.fields[e]},{value:s.values[e]});const i=this.pivot.parseArgsToPivotDomain(o),n=this.env.model.getters.getLocale();if("measure"===i.at(-1)?.field){const{value:o,format:r}=this.pivot.getPivotMeasureValue(Do(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Ep(e,i).join(",")})`,value:zi(o,{format:r,locale:n}),span:s.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{const{value:o,format:r}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Ep(e,i).join(",")})`,value:zi(o,{format:r,locale:n}),span:s.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}s.push(t)}const o=s[s.length-1];return s[s.length-1]=o.map(e=>(e.isMissing||(e.style="color: #756f6f;"),e)),s}_buildRowHeaders(e,t){const s=[];for(const o of t.rows){const t=[];for(let e=0;e<o.fields.length;e++)t.push({value:o.fields[e]},{value:o.values[e]});const i=this.pivot.parseArgsToPivotDomain(t),{value:n,format:r}=this.pivot.getPivotHeaderValueAndFormat(i),a=this.env.model.getters.getLocale(),l={formula:`=PIVOT.HEADER(${Ep(e,i).join(",")})`,value:zi(n,{format:r,locale:a}),isMissing:!this.tracker?.isHeaderPresent(i)};o.indent>1&&(l.style=`padding-left: ${o.indent-10}px`),s.push(l)}return s}_buildValues(e,t){const s=[];for(const o of t.columns.at(-1)||[]){const i=[],n=Do(o.values[o.values.length-1]);for(const s of t.rows){const t=[];for(let e=0;e<s.fields.length;e++)t.push({value:s.fields[e]},{value:s.values[e]});for(let e=0;e<o.fields.length-1;e++)t.push({value:o.fields[e]},{value:o.values[e]});const r=this.pivot.parseArgsToPivotDomain(t),{value:a,format:l}=this.pivot.getPivotCellValueAndFormat(n,r),c=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${Ep(e,r,n).join(",")})`,value:zi(a,{format:l,locale:c}),isMissing:!this.tracker?.isValuePresent(n,r)})}s.push(i)}return s}}class Eq{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,s="copyPaste"){}paste(e,t,s){}isPasteAllowed(e,t,s,o){return"Success"}isCutAllowed(e){return"Success"}getPasteTarget(e,t,s,o){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}}class xq extends Eq{copy(e,t,s="copyPaste"){}pasteFromCopy(e,t,s,o){if(1===t.length)for(const i of oP(t,s))this.pasteZone(e,i.left,i.top,s,o);else for(const i of yt(t))for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++)this.pasteZone(e,t,n,s,o)}pasteZone(e,t,s,o,i){}}class Rq extends xq{isCutAllowed(e){return 1!==e.zones.length?"WrongCutSelection":"Success"}copy(e,t,s="copyPaste"){const o=e.sheetId,{clippedZones:i,rowsIndexes:n,columnsIndexes:r}=e,a=[],l=1===n.length&&1===r.length;for(const t of n){const i=[];for(const a of r){const c={col:a,row:t,sheetId:o};let h=this.getters.getCell(c);const d=this.getters.getEvaluatedCell(c),u=this.getters.getPivotIdFromPosition(c),g=this.getters.getArrayFormulaSpreadingOn(c);if("shiftCells"!==s&&u&&g){const t=this.getters.getSpreadZone(g);if((!Le(g,c)||!l)&&t&&!e.zones.some(e=>Wt(t,e))){const e=this.getters.getPivotCellFromPosition(c),t=Rp(this.getters.getPivotFormulaId(u),e);h={id:h?.id||"",format:h?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if("shiftCells"!==s&&g&&!Le(g,c)){const e=n.includes(g.row)&&r.includes(g.col)?"":zi(d.value,{locale:this.getters.getLocale()});h={id:h?.id||"",format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:h?.content??"",format:h?.format,tokens:h?.isFormula?h.compiledFormula.tokens.map(({value:e,type:t})=>({value:e,type:t})):[],border:this.getters.getCellBorder(c)||void 0,evaluatedCell:d,position:c})}a.push(i)}return{cells:a,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,s,o){if(!s.cells)return"Success";if(o?.isCutOperation&&void 0!==o?.pasteOption)return"WrongPasteOption";if(t.length>1&&(s.cells.length>1||s.cells[0].length>1))return"WrongPasteSelection";const i=s.cells.length,n=s.cells[0].length;for(const o of oP(t,s.cells))if(this.getters.doesIntersectMerge(e,o)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*n!==1))return"WillRemoveExistingMerge";return"Success"}paste(e,t,s){const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t,s):this.pasteFromCopy(i,o,t.cells,s)}getPasteTarget(e,t,s,o){const i=s.cells[0].length,n=s.cells.length;return o?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+n-1}]}:1===i&&1===n?{zones:[],sheetId:e}:{sheetId:e,zones:oP(t,s.cells)}}pasteFromCut(e,t,s,o){this.clearClippedZones(s);const i=t[0];this.pasteZone(e,i.left,i.top,s.cells,o)}clearClippedZones(e){this.dispatch("CLEAR_CELLS",{sheetId:e.sheetId,target:e.zones}),this.dispatch("CLEAR_FORMATTING",{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){if(!a)continue;const r={col:t+o,row:s+n,sheetId:e};this.pasteCell(a,r,i)}}pasteCell(e,t,s){const{sheetId:o,col:i,row:n}=t,r=this.getters.getEvaluatedCell(t),a=e?.format||e.evaluatedCell.format;if("asValue"===s?.pasteOption)return void this.dispatch("UPDATE_CELL",{...t,content:e.evaluatedCell.value?.toString()||"",format:a});if("onlyFormat"===s?.pasteOption)return void this.dispatch("UPDATE_CELL",{...t,style:e?.style??null,format:a??r.format});let l=e?.content;e?.tokens&&e.tokens.length>0&&!s?.isCutOperation?l=this.getters.getTranslatedCellFormula(o,i-e.position.col,n-e.position.row,e.tokens):e?.tokens&&e.tokens.length>0&&(l=this.getters.getFormulaMovedInSheet(e.position.sheetId,o,e.tokens)),""!==l||e?.format||e?.style?this.dispatch("UPDATE_CELL",{...t,content:l,style:e?.style||null,format:e?.format}):r&&this.dispatch("CLEAR_CELL",t)}convertTextToClipboardData(e){const t=this.getters.getLocale(),s={cells:[]},o=[];let i=0;for(const[t,s]of e.replace(/\r/g,"").split("\n").entries())o.push(s.split("\t")),o[t].length>i&&(i=o[t].length);for(const e of o){const o=[];for(let s=0;s<i;s++){const i=yh(e[s]||"",t);o.push({content:i,evaluatedCell:{formattedValue:i}})}s.cells.push(o)}return s}}function Tq(e,t){for(let s=0;s<t.length;s++){const o=t[s].proposalValues;if(void 0===o||0===o.length)continue;const i=t=>{const i=t.functionContext;if(!i||i.parent.toUpperCase()!==e.toUpperCase()||i.argPosition!==s)return;const n=[];let r="";for(const{value:e,label:t}of o){switch(typeof e){case"string":r=`"${e}"`;break;case"number":r=e.toString();break;case"boolean":r=e?"TRUE":"FALSE"}n.push({text:r,description:t,htmlContent:[{value:r,color:"string"==typeof e?ae.STRING:ae.NUMBER}],fuzzySearchKey:r,alwaysExpanded:!0})}return n};PV.add(`${e}_function_${t[s].name}_argument_proposals`,{sequence:50,autoSelectFirstProposal:!0,selectProposal:Aq,getProposals:i})}}function Aq(e,t){let s=e.end;const o=e.end;["LEFT_PAREN","ARG_SEPARATOR"].includes(e.type)||(s=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}mP.add("data_cleanup",class extends Ur{allowDispatch(e){return"REMOVE_DUPLICATES"===e.type?this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique)):"Success"}handle(e){switch(e.type){case"REMOVE_DUPLICATES":this.removeDuplicates(e.columns,e.hasHeader);break;case"TRIM_WHITESPACE":this.trimWhitespace()}}removeDuplicates(e,t){const s=this.getters.getActiveSheetId(),o=this.getters.getSelectedZone();t&&(o.top+=1);const i=this.getUniqueRowsIndexes(s,o.top,o.bottom,e),n=i.length;if(n===$t(o).numberOfRows)return void this.notifyRowsRemovedAndRemaining(0,n);const r=i.map(e=>({left:o.left,top:e,right:o.right,bottom:e})),a=new Rq(this.getters,this.dispatch),l=a.copy(tP(s,r),!1);if(!l)return;this.dispatch("CLEAR_CELLS",{target:[o],sheetId:s});const c={left:o.left,top:o.top,right:o.left,bottom:o.top};a.paste({zones:[c],sheetId:s},l,{isCutOperation:!1});const h={left:o.left,top:o.top-(t?1:0),right:o.right,bottom:o.top+n-1};this.selection.selectZone({cell:{col:h.left,row:h.top},zone:h});const d=o.bottom-o.top+1-n;this.notifyRowsRemovedAndRemaining(d,n)}getUniqueRowsIndexes(e,t,s,o){const i=new Map;for(const n of fe(t,s+1)){const t=o.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).value);!Object.values(i).some(e=>Le(e,t))&&(i[n]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:"info",text:Cs("%s duplicate rows found and removed.\n%s unique rows remain.",e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return 1!==this.getters.getSelectedZones().length?"MoreThanOneRangeSelected":"Success"}checkNoMergeInZone(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?"WillRemoveExistingMerge":"Success"}checkRangeContainsValues(e){const t=this.getters.getActiveSheetId(),s=this.getters.getSelectedZone();e.hasHeader&&(s.top+=1);return this.getters.getEvaluatedCellsInZone(t,s).every(e=>"empty"===e.type)?"EmptyTarget":"Success"}checkNoColumnProvided(e){return 0===e.columns.length?"NoColumnsProvided":"Success"}checkColumnsIncludedInZone(e){const t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?"ColumnsNotIncludedInZone":"Success"}checkColumnsAreUnique(e){return e.columns.length!==new Set(e.columns).size?"DuplicatesColumnsSelected":"Success"}trimWhitespace(){const e=yt(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId();let s=0;for(const{col:o,row:i}of e.map(Zt).flat()){const e=this.getters.getCell({col:o,row:i,sheetId:t});if(!e)continue;const n=Je(e.content);n!==e.content&&(s+=1,this.dispatch("UPDATE_CELL",{sheetId:t,col:o,row:i,content:n}))}const o=s?Cs("Trimmed whitespace from %s cells.",s):Cs("No selected cells had whitespace trimmed.");this.ui.notifyUI({type:"info",text:o,sticky:!1})}}),PV.add("dataValidation",{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(at(t))return[];if(!this.composer.currentEditedCell)return[];const s=this.composer.currentEditedCell,o=this.getters.getValidationRuleForCell(s);if(!o||"isValueInList"!==o.criterion.type&&"isValueInRange"!==o.criterion.type)return[];const i=this.composer.currentEditedCell.sheetId,n="isValueInRange"===o.criterion.type?this.getters.getDataValidationRangeValues(i,o.criterion):o.criterion.values.map(e=>({label:e,value:e}));if(!("chip"===o.criterion.displayStyle))return n.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));const r=o.criterion.colors;return n.map(e=>{const t=r?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:hb(t||y),backgroundColor:t||y,classes:["badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start"]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t),this.composer.stopEdition()}}),PV.add("functions",{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if("SYMBOL"!==e.type)return[];const t=e.value;if(!at(this.composer.currentContent))return[];const s=Object.entries(zf.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:s}])=>({text:e,description:s,htmlContent:V$(t,e,g,"o-semi-bold")})).sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text));return s},selectProposal(e,t){let s=e.end,o=e.end;["SYMBOL","FUNCTION"].includes(e.type)&&(s=e.start);const i=this.composer.currentTokens;t+="(";const n=i.map(e=>e.start).indexOf(e.start);if(n+1<i.length){const e=i[n+1];"LEFT_PAREN"===e?.type&&o++}this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)}}),zf.getAll().forEach(e=>Tq(e.name,e.args)),PV.add("pivot_ids",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!["PIVOT.VALUE","PIVOT.HEADER","PIVOT"].includes(t.parent.toUpperCase())||0!==t.argPosition)return;const s=this.getters.getPivotIds();return s.includes(e.value)?void 0:s.map(e=>{const t=this.getters.getPivotCoreDefinition(e),s=`${this.getters.getPivotFormulaId(e)}`;return{text:s,description:t.name,htmlContent:[{value:s,color:ae.NUMBER}],fuzzySearchKey:s+t.name,alwaysExpanded:!0}}).filter(De)},selectProposal:Aq}),PV.add("pivot_measures",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if("PIVOT.VALUE"!==t?.parent.toUpperCase()||1!==t.argPosition)return[];const s=Sq(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return[];const i=this.getters.getPivot(o);return i.init(),i.isValid()?i.definition.measures.map(e=>{if("__count"===e.fieldName){const e='"__count"';return{text:e,description:Cs("Count"),htmlContent:[{value:e,color:ae.STRING}],fuzzySearchKey:Cs("Count")+e}}return function(e){const t=`"${e.id}"`,s=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:ae.STRING}],fuzzySearchKey:s}}(e)}).filter(De):[]},selectProposal:Aq}),PV.add("pivot_group_fields",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!function(e){const t=e.functionContext;return"PIVOT.VALUE"===t?.parent.toUpperCase()&&t.argPosition>=2&&t.argPosition%2==0}(e)&&!function(e){const t=e.functionContext;return"PIVOT.HEADER"===t?.parent.toUpperCase()&&t.argPosition>=1&&t.argPosition%2==1}(e))return;const s=Sq(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return;const i=this.getters.getPivot(o);i.init();const n=i.getFields(),{columns:r,rows:a}=i.definition;let l=t.args;"PIVOT.VALUE"===t?.parent.toUpperCase()?(l=l.filter((e,t)=>t%2==0),l=l.slice(1,t.argPosition)):l=l.filter((e,t)=>t%2==1);const c=l.map(e=>e?.value).filter(De),h=r.map(e=>e.nameWithGranularity),d=a.map(e=>e.nameWithGranularity),u=[];let g=["ARG_SEPARATOR","SPACE"].includes(e.type)?c.at(-1):c.at(-2);const p=yq.get(i.type);if(p&&g?.startsWith("#")&&(g=g.slice(1)),void 0===g&&(u.push(h[0]),u.push(d[0])),d.includes(g)){const e=d[d.indexOf(g)+1];u.push(e),u.push(h[0])}if(h.includes(g)){const e=h[h.indexOf(g)+1];u.push(e)}const m=u.filter(De);return m.map(e=>{const[t,s]=e.split(":"),o=n[t];return o?bq(o,s):void 0}).concat(m.map(e=>{if(!p)return;const t=e.split(":")[0],s=n[t];if(!s)return;const o=`"#${e}"`;return{text:o,description:Cs("%s (positional)",s.string)+(s.help?` (${s.help})`:""),htmlContent:[{value:o,color:ae.STRING}],fuzzySearchKey:s.string+o}})).filter(De)},selectProposal:Aq}),PV.add("pivot_group_values",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!e||!function(e){const t=e.functionContext;return"PIVOT.VALUE"===t?.parent.toUpperCase()&&t.argPosition>=2&&t.argPosition%2==1}(e)&&!function(e){const t=e.functionContext;return"PIVOT.HEADER"===t?.parent.toUpperCase()&&t.argPosition>=1&&t.argPosition%2==0}(e))return;const s=Sq(e),o=this.getters.getPivotId(s);if(!o||!this.getters.isExistingPivot(o))return;const i=this.getters.getPivot(o);if(!i.isValid())return;const n=t.argPosition,r=e.functionContext?.args[n-1]?.value;if(!r)return;let a;try{a=i.definition.getDimension(r)}catch(e){return}return"month_number"===a.granularity?Object.values(ki).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:ae.NUMBER}]})):"quarter_number"===a.granularity?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:Cs("Quarter %s",e),htmlContent:[{value:`${e}`,color:ae.NUMBER}]})):"day_of_month"===a.granularity?fe(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ae.NUMBER}]})):"iso_week_number"===a.granularity?fe(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ae.NUMBER}]})):"day_of_week"===a.granularity?fe(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ae.NUMBER}]})):"hour_number"===a.granularity?fe(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ae.NUMBER}]})):"minute_number"===a.granularity?fe(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ae.NUMBER}]})):"second_number"===a.granularity?fe(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:ae.NUMBER}]})):i.getPossibleFieldValues(a).map(({value:e,label:t})=>{const s="string"==typeof e,o=s?`"${e}"`:e.toString(),i=t===e?"":t;return{text:o,description:i,htmlContent:[{value:o,color:s?ae.STRING:ae.NUMBER}],fuzzySearchKey:o+i}})},selectProposal:Aq}),PV.add("sheet_names",{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return"SYMBOL"===e.type||"UNKNOWN"===e.type&&e.value.startsWith("'")?this.getters.getSheetIds().map(e=>{const t=ge(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith("'")?t:"'"+t}}):[]},selectProposal(e,t){const s=e.start,o=e.end;this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t+"!")}});const _q=new Jg;_q.add("link",{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,s)=>vv(t.model.getters.getEvaluatedCell(e).link,t,s),title:(e,t)=>{const s=t.getEvaluatedCell(e).link;return s?s.isExternal?Cs("Go to url: %(url)s",{url:s.url}):Cs("Go to %(label)s",{label:s.label}):""},sequence:5}),_q.add("dashboard_pivot_sorting",{condition:(e,t)=>{if(!t.isDashboard())return!1;const s=t.getPivotCellFromPosition(e);return JU(t,e)&&"MEASURE_HEADER"===s.type},execute:(e,t)=>{QU(t,e,function(e,t){return Dq[e.getPivotCellSortDirection(t)??"none"]}(t.model.getters,e))},component:Cq,componentProps:(e,t)=>({position:e,sortDirection:t.getPivotCellSortDirection(e)}),sequence:2});const Dq={none:"asc",asc:"desc",desc:"none"};AO.add("filter_icon",(e,t)=>{if(e.isFilterHeader(t)){const s=e.isFilterActive(t),o=Qv(e.getCellComputedStyle(t).fillColor||"#fff")<.45;return{type:"filter_icon",svg:tT(s,o,!1),hoverSvg:tT(s,o,!0),priority:3,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const s=t.getStore(aV),o=s.persistentCellPopover;o.isOpen&&o.col===e.col&&o.row===e.row&&"FilterMenu"===o.type?s.close():s.open(e,"FilterMenu")}}}});const Oq=new Jg;Oq.add("format_number_automatic",{...mB,id:"format_number_automatic",sequence:10}).add("format_number_plain_text",{...fB,id:"format_number_plain_text",sequence:15,separator:!0}).add("format_number_number",{...vB,id:"format_number_number",sequence:20}).add("format_number_percent",{...SB,id:"format_number_percent",sequence:30,separator:!1}).add("format_number_scientific",{...yB,id:"format_number_scientific",sequence:33,separator:!0}).add("format_number_currency",{...CB,id:"format_number_currency",sequence:40}).add("format_number_accounting",{...wB,id:"format_number_accounting",sequence:45}).add("format_number_currency_rounded",{...IB,id:"format_number_currency_rounded",sequence:50,separator:!0}).add("format_number_date",{...RB,id:"format_number_date",sequence:70}).add("format_number_time",{...TB,id:"format_number_time",sequence:80}).add("format_number_date_time",{...AB,id:"format_number_date_time",sequence:90}).add("format_number_duration",{..._B,id:"format_number_duration",sequence:100,separator:!0}).add("format_custom_currency",{...xB,id:"format_custom_currency",sequence:120}).add("format_custom_date",{...DB,id:"format_custom_date",sequence:130}).add("format_custom_number",{...OB,id:"format_custom_number",sequence:140});const Fq=je(e=>ji(e)?"date":e.includes("[$")?"currency":"number"),Pq={name:Cs("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[e=>{const t=function(e){const t=new Set(Oq.getAll().map(t=>"function"==typeof t.format?t.format(e):t.format)),s=new Map;for(const o of e.model.getters.getSheetIds()){const i=e.model.getters.getEvaluatedCells(o);for(const e in i){const o=i[e];if(o.format&&!s.has(o.format)&&!t.has(o.format)){const e=Fq(o.format);"date"!==e&&"currency"!==e||s.set(o.format,pB({descriptionValue:"currency"===e?1e3:EB,format:o.format,name:o.format}))}}}return[...s.values()]}(e).map(e=>({...e,sequence:110}));return t.length>0&&(t[t.length-1].separator=!0),[...Oq.getAll(),...t]}]};const Mq=new xz;Mq.add("file",{name:Cs("File"),sequence:10}).addChild("settings",["file"],{name:Cs("Settings"),sequence:200,execute:e=>e.openSidePanel("Settings"),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.COG"}).add("edit",{name:Cs("Edit"),sequence:20}).addChild("undo",["edit"],{...kH,sequence:10}).addChild("redo",["edit"],{...LH,sequence:20,separator:!0}).addChild("copy",["edit"],{...VH,sequence:30}).addChild("cut",["edit"],{...zH,sequence:40}).addChild("paste",["edit"],{...HH,sequence:50}).addChild("paste_special",["edit"],{...UH,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...BH,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{...GH,sequence:20}).addChild("edit_table",["edit"],{...sU,isVisible:eH,sequence:60}).addChild("find_and_replace",["edit"],{...WH,sequence:65,separator:!0}).addChild("delete",["edit"],{name:Cs("Delete"),icon:"o-spreadsheet-Icon.TRASH",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...$H,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...qH,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...YH,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{...QH,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...eU,sequence:50}).addChild("edit_unhide_columns",["edit"],{...hH,sequence:80}).addChild("edit_unhide_rows",["edit"],{...gH,sequence:80}).add("view",{name:Cs("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...pH,sequence:4}).addChild("freeze_panes",["view"],{...mH,sequence:5}).addChild("unfreeze_rows",["view","freeze_panes"],{...fH,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...vH,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...bH,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...SH,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...yH,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...CH,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...IH,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...wH,sequence:40}).addChild("group_headers",["view"],{name:Cs("Group"),sequence:15,separator:!0,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",isVisible:sH}).addChild("group_columns",["view","group_headers"],{...TH,sequence:5}).addChild("ungroup_columns",["view","group_headers"],{..._H,isVisible:e=>PH(e,"COL"),sequence:10}).addChild("group_rows",["view","group_headers"],{...AH,sequence:15}).addChild("ungroup_rows",["view","group_headers"],{...DH,isVisible:e=>PH(e,"ROW"),sequence:20}).addChild("show",["view"],{name:Cs("Show"),sequence:1,icon:"o-spreadsheet-Icon.SHOW"}).addChild("view_gridlines",["view","show"],{...EH,sequence:5}).addChild("view_formulas",["view","show"],{...RH,sequence:10}).addChild("zoom",["view"],{name:Cs("Zoom"),sequence:1,icon:"o-spreadsheet-Icon.ZOOM"}).addChild("view_irregularity_map",["view"],{...xH,sequence:40,separator:!0}).add("insert",{name:Cs("Insert"),sequence:40}).addChild("insert_row",["insert"],{...rU,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...lU,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...dU,sequence:20}).addChild("insert_column",["insert"],{...uU,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...pU,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...vU,sequence:20}).addChild("insert_cell",["insert"],{...bU,sequence:30}).addChild("insert_cell_down",["insert","insert_cell"],{...SU,name:Cs("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...yU,name:Cs("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...kU,sequence:40,separator:!0}).addChild("insert_chart",["insert"],{...CU,sequence:50}).addChild("insert_carousel",["insert"],{...IU,sequence:51}).addChild("insert_pivot",["insert"],{...wU,sequence:52}).addChild("insert_image",["insert"],{...EU,sequence:55}).addChild("insert_table",["insert"],{...xU,sequence:57}).addChild("insert_function",["insert"],{...RU,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...TU,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...AU,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{..._U,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...DU,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...OU,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...FU,sequence:50}).addChild("categories_function_list",["insert","insert_function"],()=>{const e=zf.content;return[...new Set(zf.getAll().filter(e=>!e.hidden).map(e=>e.category))].filter(De).sort().map((t,s)=>{const o=Object.keys(e).filter(s=>e[s].category===t&&!e[s].hidden);return{name:t,children:LU(o)}})}).addChild("insert_link",["insert"],{...PU,separator:!0,sequence:70}).addChild("insert_checkbox",["insert"],{...MU,sequence:80}).addChild("insert_dropdown",["insert"],{...NU,separator:!0,sequence:90}).add("format",{name:Cs("Format"),sequence:50}).addChild("format_number",["format"],{...Pq,name:Cs("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{...MB,sequence:20}).addChild("format_italic",["format"],{...NB,sequence:30}).addChild("format_underline",["format"],{...kB,sequence:40}).addChild("format_strikethrough",["format"],{...GB,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...WB,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...$B,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...ZB,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...jB,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...YB,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{...KB,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...JB,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{...QB,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...eG,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...sG,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...oG,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...iG,sequence:30}).addChild("format_cf",["format"],{...nG,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...rG,sequence:100,separator:!0}).add("data",{name:Cs("Data"),sequence:60}).addChild("sort_range",["data"],{...oB,sequence:10,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...iB,sequence:10}).addChild("sort_descending",["data","sort_range"],{...lB,sequence:20}).addChild("data_cleanup",["data"],{...nB,sequence:15}).addChild("remove_duplicates",["data","data_cleanup"],{...rB,sequence:10}).addChild("trim_whitespace",["data","data_cleanup"],{...aB,sequence:20}).addChild("split_to_columns",["data"],{...dB,sequence:20}).addChild("data_validation",["data"],{name:Cs("Data Validation"),execute:e=>{e.openSidePanel("DataValidation")},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.DATA_VALIDATION",sequence:30,separator:!0}).addChild("add_remove_data_filter",["data"],{...cB,sequence:40,separator:!0}).addChild("pivot_data_sources",["data"],e=>{const t=e.model.getters.getPivotIds().length;return e.model.getters.getPivotIds().map((s,o)=>{const i={get highlights(){return N$(e.model.getters,s)}};return{id:`item_pivot_${e.model.getters.getPivotFormulaId(s)}`,name:e.model.getters.getPivotDisplayName(s),sequence:50+o/t,isReadonlyAllowed:!0,execute:e=>e.openSidePanel("PivotSidePanel",{pivotId:s}),isEnabled:e=>!e.isSmall,onStartHover:e=>e.getStore(NV).register(i),onStopHover:e=>e.getStore(NV).unRegister(i),icon:"o-spreadsheet-Icon.PIVOT",separator:o===e.model.getters.getPivotIds().length-1,secondaryIcon:e=>e.model.getters.isPivotUnused(s)?"o-spreadsheet-Icon.UNUSED_PIVOT_WARNING":void 0}})}).addChild("reinsert_dynamic_pivot",["data"],uB).addChild("reinsert_static_pivot",["data"],gB),N.forEach(e=>{Mq.addChild(`zoom${e}`,["view","zoom"],function(e){return{name:Cs("%(zoom_percentage)s%",{zoom_percentage:e}),execute:t=>{t.model.dispatch("SET_ZOOM",{zoom:e/100})},isActive:t=>t.model.getters.getViewportZoomLevel()===e/100,isReadonlyAllowed:!0,sequence:e}}(e))});const Nq=[kq,function(e,t){return"target"in t&&Array.isArray(t.target)?{...he(t),target:e.getSelectedZones()}:t},Vq,function(e,t){return"ranges"in t?{...he(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}];function kq(e,t){return"sheetId"in t?{...he(t),sheetId:e.getActiveSheetId()}:t}function Lq(e,t){return"zone"in t?{...he(t),zone:e.getSelectedZone()}:t}function Vq(e,t){if(!("row"in t)||!("col"in t))return t;const{col:s,row:o}=e.getActivePosition();return{...he(t),col:s,row:o}}const zq=new Tr;function Hq(e,t){const s=e.getSelectedZone();return{...kq(e,t),elements:"COL"===t.dimension?fe(s.left,s.right+1):fe(s.top,s.bottom+1)}}function Uq(e,t){const s=e.getSelectedZone();return{...he(t),zone:s}}function Bq(e,t){const s=he(t),o=e.getSelectedZone(),{top:i,bottom:n,left:r,right:a}=o;return"cols"in s?s.cols=fe(r,a+1):"rows"in s&&(s.rows=fe(i,n+1)),s}function Gq(e,t){const s=e.getSelectedZone();return{...kq(e,t),start:"COL"===t.dimension?s.left:s.top,end:"COL"===t.dimension?s.right:s.bottom}}function Wq(e,t){let s=he(t);for(const t of Nq)s=t(e,s);return s}BF.add("UPDATE_CELL",Wq),BF.add("CLEAR_CELL",Wq),BF.add("CLEAR_CELLS",Wq),BF.add("DELETE_CONTENT",Wq),BF.add("ADD_MERGE",Wq),BF.add("REMOVE_MERGE",Wq),BF.add("SET_FORMATTING",Wq),BF.add("CLEAR_FORMATTING",Wq),BF.add("SET_BORDER",Wq),BF.add("CREATE_TABLE",Wq),BF.add("REMOVE_TABLE",Wq),BF.add("HIDE_SHEET",Wq),BF.add("ADD_COLUMNS_ROWS",function(e,t){const s=e.getActivePosition();return{...kq(e,t),base:"COL"===t.dimension?s.col:s.row}}),BF.add("REMOVE_COLUMNS_ROWS",Hq),BF.add("HIDE_COLUMNS_ROWS",Hq),BF.add("RESIZE_COLUMNS_ROWS",Hq),BF.add("CREATE_SHEET",function(e,t){const s=he(t);s.sheetId=zq.smallUuid();const o=t.name||e.getSheet(e.getActiveSheetId()).name,i=o.match(/(.+?)\d*$/)?.[1]||o;return s.name=e.getNextSheetName(i),s}),BF.add("CREATE_FIGURE",function(e,t){const s=Vq(e,kq(e,t));return s.figureId=zq.smallUuid(),s}),BF.add("CREATE_CHART",function(e,t){const s=zq.smallUuid();return{...kq(e,t),figureId:s,chartId:s}}),BF.add("CREATE_IMAGE",function(e,t){return{...kq(e,t),figureId:zq.smallUuid()}}),BF.add("GROUP_HEADERS",Gq),BF.add("UNGROUP_HEADERS",Gq),BF.add("UNFOLD_HEADER_GROUPS_IN_ZONE",Lq),BF.add("FOLD_HEADER_GROUPS_IN_ZONE",Lq),GF.add("PASTE",function(e,t){return{type:"REPEAT_PASTE",pasteOption:he(t.pasteOption),target:e.getSelectedZones()}}),GF.add("INSERT_CELL",Uq),GF.add("DELETE_CELL",Uq),GF.add("AUTORESIZE_COLUMNS",Bq),GF.add("AUTORESIZE_ROWS",Bq),GF.add("SORT_CELLS",function(e,t){const s=e.getSelectedZone();return{...kq(e,t),col:s.left,row:s.top,zone:s}}),GF.add("SUM_SELECTION",Wq),GF.add("SET_DECIMAL",Wq),GF.add("DELETE_UNFILTERED_CONTENT",Wq);const $q=new class extends Jg{mapping={};uuidGenerator=new Tr;replace(e,t){const s={...t,id:this.uuidGenerator.uuidv4()};return super.replace(e,s)}getAllOrdered(){return this.getAll().sort((e,t)=>e.sequence-t.sequence)}};class qq{fileStore;constructor(e){this.fileStore=e}async requestImage(){const e=await this.userImageUpload(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}async uploadFile(e){const t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}userImageUpload(){return new Promise((e,t)=>{const s=document.createElement("input");s.setAttribute("type","file"),s.setAttribute("accept","image/*"),s.addEventListener("change",async()=>{null===s.files||1!==s.files.length?t():e(s.files[0])}),s.click()})}getImageOriginalSize(e){return new Promise((t,s)=>{const o=new Image;o.addEventListener("load",()=>{const e={width:o.width,height:o.height};t(e)}),o.addEventListener("error",s),o.src=e})}}const Zq=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];class jq extends t.Component{static template="o-spreadsheet-RippleEffect";static props={x:String,y:String,color:String,opacity:Number,duration:Number,width:Number,height:Number,offsetY:Number,offsetX:Number,allowOverflow:Boolean,onAnimationEnd:Function,style:String};rippleRef=t.useRef("ripple");setup(){let e;t.onMounted(()=>{const t=this.rippleRef.el;t&&t.animate&&(e=t.animate(Zq,{duration:this.props.duration,easing:"ease-out"}),e.addEventListener("finish",this.props.onAnimationEnd))}),t.onWillUnmount(()=>{e?.removeEventListener("finish",this.props.onAnimationEnd)})}get rippleStyle(){const{x:e,y:t,width:s,height:o}=this.props;return JF({transform:"scale(0)",left:e,top:t,"margin-left":`${-s/2+(this.props.offsetX||0)}px`,"margin-top":`${-o/2+(this.props.offsetY||0)}px`,width:`${s}px`,height:`${o}px`,background:this.props.color,"border-radius":"100%",opacity:`${this.props.opacity}`})}}class Yq extends t.Component{static template="o-spreadsheet-Ripple";static props={color:{type:String,optional:!0},opacity:{type:Number,optional:!0},duration:{type:Number,optional:!0},ignoreClickPosition:{type:Boolean,optional:!0},width:{type:Number,optional:!0},height:{type:Number,optional:!0},offsetY:{type:Number,optional:!0},offsetX:{type:Number,optional:!0},allowOverflow:{type:Boolean,optional:!0},enabled:{type:Boolean,optional:!0},onAnimationEnd:{type:Function,optional:!0},slots:Object,class:{type:String,optional:!0}};static components={RippleEffect:jq};static defaultProps={color:"#aaaaaa",opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:""};childContainer=t.useRef("childContainer");state=t.useState({ripples:[]});currentId=1;onClick(e){if(!this.props.enabled)return;if(!this.childContainer.el)return;const t=this.getRippleChildRectInfo(),{x:s,y:o,width:i,height:n}=t,r=Math.max(i,n),a={x:e.clientX-s,y:e.clientY-o,width:this.props.width||2.85*r,height:this.props.height||2.85*r};this.state.ripples.push({rippleRect:a,id:this.currentId++})}getRippleStyle(){const e=this.childContainer.el;if(!e||1!==e.childElementCount||!e.firstElementChild)return"";const t=this.getRippleChildRectInfo();return JF({top:t.marginTop+"px",left:t.marginLeft+"px",width:t.width+"px",height:t.height+"px"})}getRippleChildRectInfo(){const e=this.childContainer.el;if(!e)throw new Error("No child container element found");if(1!==e.childElementCount||!e.firstElementChild){return{...FN(e),marginLeft:0,marginTop:0}}const t=e.firstElementChild,s=function(e){const t=window.getComputedStyle(e);return{top:parseInt(t.marginTop,10)||0,bottom:parseInt(t.marginBottom,10)||0,left:parseInt(t.marginLeft,10)||0,right:parseInt(t.marginRight,10)||0}}(t);return{...FN(t),marginLeft:s.left,marginTop:s.top}}removeRipple(e){const t=this.state.ripples.findIndex(t=>t.id===e);-1!==t&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){const t=this.state.ripples.find(t=>t.id===e)?.rippleRect;if(!t)throw new Error("Cannot find a ripple with the id "+e);return{color:this.props.color,opacity:this.props.opacity,duration:this.props.duration,x:this.props.ignoreClickPosition?"50%":t.x+"px",y:this.props.ignoreClickPosition?"50%":t.y+"px",width:t.width,height:t.height,offsetX:this.props.offsetX||0,offsetY:this.props.offsetY||0,allowOverflow:this.props.allowOverflow||!1,style:this.getRippleStyle(),onAnimationEnd:()=>this.removeRipple(e)}}}class Xq extends t.Component{static template="o-spreadsheet-BottomBarSheet";static props={sheetId:String,openContextMenu:Function,style:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0}};static components={Ripple:Yq,ColorPicker:jV};static defaultProps={onMouseDown:()=>{},style:""};state=t.useState({isEditing:!1,pickerOpened:!1});sheetDivRef=t.useRef("sheetDiv");sheetNameRef=t.useRef("sheetNameSpan");editionState="initializing";DOMFocusableElementStore;setup(){t.onPatched(()=>{this.sheetNameRef.el&&this.state.isEditing&&"initializing"===this.editionState&&(this.editionState="editing",this.focusInputAndSelectContent())}),this.DOMFocusableElementStore=Tv(mV),t.useExternalListener(window,"click",()=>this.state.pickerOpened=!1),t.useEffect(e=>{this.props.sheetId===e&&this.scrollToSheet()},()=>[this.env.model.getters.getActiveSheetId()])}focusInputAndSelectContent(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.sheetNameRef.el.focus();const e=window.getSelection();e&&this.sheetNameRef.el.firstChild&&e.setBaseAndExtent(this.sheetNameRef.el.firstChild,0,this.sheetNameRef.el.firstChild,this.sheetNameRef.el.textContent?.length||0)}scrollToSheet(){this.sheetDivRef.el?.scrollIntoView?.({behavior:"smooth",inline:"nearest"})}onFocusOut(){this.state.isEditing&&"initializing"!==this.editionState&&this.stopEdition()}onClick(){this.env.isMobile()&&this.activateSheet()}onMouseDown(e){this.env.isMobile()||(this.activateSheet(),this.props.onMouseDown(e))}activateSheet(){this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:this.props.sheetId}),this.scrollToSheet()}onDblClick(){this.env.model.getters.isReadonly()||this.startEdition()}onKeyDown(e){this.state.isEditing&&("Enter"===e.key&&(e.preventDefault(),this.stopEdition(),this.DOMFocusableElementStore.focus()),"Escape"===e.key&&(this.cancelEdition(),this.DOMFocusableElementStore.focus()))}onMouseEventSheetName(e){this.state.isEditing&&e.stopPropagation()}startEdition(){this.state.isEditing=!0,this.editionState="initializing"}stopEdition(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el.blur();const e=this.getInputContent()||"";!function(e,t,s,o){const i=e.model.dispatch("RENAME_SHEET",{sheetId:t,newName:s,oldName:e.model.getters.getSheetName(t)});i.reasons.includes("MissingSheetName")?e.raiseError(Cs("The sheet name cannot be empty."),o):i.reasons.includes("DuplicatedSheetName")?e.raiseError(Cs("A sheet with the name %s already exists. Please select another name.",s),o):i.reasons.includes("ForbiddenCharactersInSheetName")&&e.raiseError(Cs("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",j.join(" ")),o)}(this.env,this.props.sheetId,e,()=>this.startEdition())}cancelEdition(){this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el?.blur(),this.setInputContent(this.sheetName)}onIconClick(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}onContextMenu(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}getInputContent(){return this.sheetNameRef.el?.textContent}setInputContent(e){this.sheetNameRef.el&&(this.sheetNameRef.el.textContent=e)}onColorPicked(e){this.state.pickerOpened=!1,this.env.model.dispatch("COLOR_SHEET",{sheetId:this.props.sheetId,color:e})}get colorPickerAnchorRect(){return FN(this.sheetDivRef.el)}get contextMenuRegistry(){return function(e){const t=new xz;return t.add("delete",{...bz,sequence:10}).add("hide_sheet",{...Ez,sequence:20}).add("duplicate",{...Sz,sequence:30,separator:!0}).add("rename",{...yz(e),sequence:40}).add("change_color",{...Cz(e),sequence:50,separator:!0}).add("move_right",{...Iz,sequence:60}).add("move_left",{...wz,sequence:70}),t}({renameSheetCallback:()=>{this.scrollToSheet(),this.startEdition()},openSheetColorPickerCallback:()=>{this.state.pickerOpened=!0}})}get isSheetActive(){return this.env.model.getters.getActiveSheetId()===this.props.sheetId}get sheetName(){return this.env.model.getters.getSheetName(this.props.sheetId)}get sheetColorStyle(){return JF({background:this.env.model.getters.getSheet(this.props.sheetId).color||""})}}const Kq=[{name:Cs("Sum"),types:[Xd.number],compute:(e,t)=>Gr([[e]],t)},{name:Cs("Avg"),types:[Xd.number],compute:(e,t)=>ll([[e]],t)},{name:Cs("Min"),types:[Xd.number],compute:(e,t)=>ul([[e]],t).value},{name:Cs("Max"),types:[Xd.number],compute:(e,t)=>dl([[e]],t).value},{name:Cs("Count"),types:[Xd.number,Xd.text,Xd.boolean,Xd.error],compute:e=>hl([[e]])},{name:Cs("Count Numbers"),types:[Xd.number,Xd.text,Xd.boolean,Xd.error],compute:(e,t)=>cl([[e]],t)}];class Jq extends Lv{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.onDispose(()=>{this.model.selection.unobserve(this)})}handle(e){switch((Ar.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this.isDirty=!0),e.type){case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"GROUP_HEADERS":case"UNGROUP_HEADERS":case"ACTIVATE_SHEET":case"ACTIVATE_NEXT_SHEET":case"ACTIVATE_PREVIOUS_SHEET":case"EVALUATE_CELLS":case"UNDO":case"REDO":this.isDirty=!0}}finalize(){this.isDirty&&(this.isDirty=!1,this.statisticFnResults=this._computeStatisticFnResults())}handleEvent(){this.getters.isGridSelectionActive()&&(this.statisticFnResults=this._computeStatisticFnResults())}_computeStatisticFnResults(){const e=this.getters,t=e.getActiveSheetId(),s=[],o=yt(e.getSelectedZones(),[]),i=this.getters.getSheetSize(t).numberOfRows-1,n=this.getters.getSheetSize(t).numberOfCols-1;for(const r of o)for(let o=r.left;o<=(r.right??n);o++)for(let n=r.top;n<=(r.bottom??i);n++){if(e.isRowHidden(t,n)||e.isColHidden(t,o))continue;const i=e.getEvaluatedCell({sheetId:t,col:o,row:n});i.type!==Xd.empty&&s.push(i)}const r=e.getLocale(),a={},l=je(e=>{const t=e.split(",");return s.filter(e=>t.includes(e.type))});for(const e of Kq){let t;const s=l(e.types.sort().join(","));s.length&&(t=Me(()=>e.compute(s,r))),a[e.name]=t}return a}}class Qq extends t.Component{static template="o-spreadsheet-BottomBarStatistic";static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:Yq};selectedStatisticFn="";store;setup(){this.store=Tv(Jq),t.onWillUpdateProps(()=>{Object.values(this.store.statisticFnResults).every(e=>void 0===e)&&this.props.closeContextMenu()})}getSelectedStatistic(){if(!Object.values(this.store.statisticFnResults).every(e=>void 0===e))return""===this.selectedStatisticFn&&(this.selectedStatisticFn=Object.keys(this.store.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn)}listSelectionStatistics(e){const t=new xz;let s=0;for(const[e]of Object.entries(this.store.statisticFnResults))t.add(e,{name:()=>this.getComposedFnName(e),sequence:s,isReadonlyAllowed:!0,execute:()=>{this.selectedStatisticFn=e}}),s++;const o=e.currentTarget,{top:i,left:n,width:r}=o.getBoundingClientRect();this.props.openContextMenu(n+r,i,t)}getComposedFnName(e){const t=this.env.model.getters.getLocale(),s=this.store.statisticFnResults[e];return e+": "+(void 0!==s?zi(s(),{locale:t}):"__")}}class eZ extends t.Component{static template="o-spreadsheet-BottomBar";static props={onClick:Function};static components={MenuPopover:JL,Ripple:Yq,BottomBarSheet:Xq,BottomBarStatistic:Qq};bottomBarRef=t.useRef("bottomBar");sheetListRef=t.useRef("sheetList");dragAndDrop=KV();targetScroll=void 0;state=t.useState({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=t.useState({isOpen:!1,menuId:void 0,anchorRect:null,menuItems:[]});sheetList=this.getVisibleSheets();setup(){t.onWillUpdateProps(()=>{this.updateScrollState();const e=this.getVisibleSheets();Le(this.sheetList,e)||this.dragAndDrop.cancel(),this.sheetList=e})}clickAddSheet(e){const t=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getSheetIds().findIndex(e=>e===t)+1,o=this.env.model.uuidGenerator.smallUuid(),i=this.env.model.getters.getNextSheetName(Cs("Sheet"));this.env.model.dispatch("CREATE_SHEET",{sheetId:o,position:s,name:i}),this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map(e=>{const t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}})}clickListSheets(e){const t=new xz,s=this.env.model.getters.getActiveSheetId();let o=0;for(const e of this.env.model.getters.getSheetIds()){const i=this.env.model.getters.getSheet(e);t.add(e,{name:i.name,sequence:o,isReadonlyAllowed:!0,textColor:i.isVisible?void 0:"#808080",execute:t=>{this.env.model.getters.isSheetVisible(e)||this.env.model.dispatch("SHOW_SHEET",{sheetId:e}),t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:s,sheetIdTo:e})},isEnabled:e=>!e.model.getters.isReadonly()||i.isVisible,icon:i.color?"o-spreadsheet-Icon.SMALL_DOT_RIGHT_ALIGN":void 0,iconColor:i.color}),o++}const i=e.currentTarget,{left:n}=i.getBoundingClientRect(),r=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(n,r,"listSheets",t)}openContextMenu(e,t,s,o){this.menuState.isOpen=!0,this.menuState.menuId=s,this.menuState.menuItems=o.getMenuItems(),this.menuState.anchorRect={x:e,y:t,width:0,height:0}}onSheetContextMenu(e,t,s){const o=s.currentTarget,{top:i,left:n}=o.getBoundingClientRect();s.closedMenuId!==e?this.openContextMenu(n,i,e,t):this.closeMenu()}closeMenu(){this.menuState.isOpen=!1,this.menuState.menuId=void 0,this.menuState.menuItems=[],this.menuState.anchorRect=null}closeContextMenuWithId(e){this.menuState.menuId===e&&this.closeMenu()}onWheel(e){this.targetScroll=void 0;e.currentTarget.scrollLeft+=.5*e.deltaY}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll+this.sheetListWidth;this.scrollSheetListTo(Math.min(this.sheetListMaxScroll,t))}updateScrollState(){this.state.isSheetListScrollableLeft=this.sheetListCurrentScroll>0,this.state.isSheetListScrollableRight=this.sheetListCurrentScroll<this.sheetListMaxScroll}scrollSheetListTo(e){this.sheetListRef.el&&(this.targetScroll=e,this.sheetListRef.el.scrollTo({top:0,left:e,behavior:"smooth"}))}onSheetMouseDown(e,t){if(0!==t.button||this.env.model.getters.isReadonly())return;if(this.closeMenu(),this.env.isMobile())return;const s=this.getVisibleSheets(),o=this.getSheetItemRects(),i=s.map((e,t)=>({id:e.id,size:o[t].width,position:o[t].x}));this.dragAndDrop.start("horizontal",{draggedItemId:e,initialMousePosition:t.clientX,items:i,scrollableContainerEl:this.sheetListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const s=t-this.getVisibleSheets().findIndex(t=>t.id===e);e&&0!==s&&this.env.model.dispatch("MOVE_SHEET",{sheetId:e,delta:s})}getSheetStyle(e){return this.dragAndDrop.itemsStyle[e]||""}getSheetItemRects(){return Array.from(this.bottomBarRef.el.querySelectorAll(".o-sheet")).map(e=>e.getBoundingClientRect()).map(e=>({x:e.x,width:e.width-1,y:e.y,height:e.height}))}get sheetListCurrentScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollLeft:0}get sheetListWidth(){return this.sheetListRef.el?this.sheetListRef.el.clientWidth:0}get sheetListMaxScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollWidth-this.sheetListRef.el.clientWidth:0}}class tZ extends Lv{_clickableCells=t.markRaw({});_registryItems=t.markRaw(_q.getAll().sort((e,t)=>e.sequence-t.sequence));handle(e){(Ar.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this._clickableCells=t.markRaw({}),this._registryItems=t.markRaw(_q.getAll().sort((e,t)=>e.sequence-t.sequence)))}getClickableItem(e){const{sheetId:t,col:s,row:o}=e,i=this._clickableCells,n=St(s,o);if(i[t]||(i[t]={}),!(n in i[t])){const s=this.findClickableItem(e);i[t][n]=s}return i[t][n]}findClickableItem(e){const t=this.getters;for(const s of this._registryItems)if(s.condition(e,t))return s}get clickableCells(){const e=[],t=this.getters;for(const s of this.getters.getVisibleCellPositions()){const o=this.getClickableItem(s);if(!o)continue;const i="function"==typeof o.title?o.title(s,t):o.title,n=this.getClickableCellRect(s);n&&e.push({coordinates:n,position:s,action:o.execute,title:i||"",component:o.component,componentProps:o.componentProps?.(s,t)??{}})}return e}getClickableCellRect(e){const t=this.getters.expandZone(e.sheetId,Jt(e)),s=this.getters.getVisibleRect(t),o=this.getters.getCellIcons(e),i={center:o.find(e=>"center"===e.horizontalAlign),left:o.find(e=>"left"===e.horizontalAlign),right:o.find(e=>"right"===e.horizontalAlign)};if(!i.center?.onClick){if(i.right?.onClick){const e=this.getters.getRect(t),o=this.getters.getCellIconRect(i.right,e);s.width-=o.width+i.right.margin}if(i.left?.onClick){const e=this.getters.getRect(t),o=this.getters.getCellIconRect(i.left,e);s.x+=o.width+i.left.margin,s.width-=o.width+i.left.margin}return s}}}class sZ extends t.Component{static template="o-spreadsheet-SpreadsheetDashboard";static props={getGridSize:Function};static components={GridOverlay:BG,GridPopover:GG,Popover:jL,VerticalScrollBar:rW,HorizontalScrollBar:nW};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;gridRef;setup(){this.gridRef=t.useRef("grid"),this.hoveredCell=Tv(nV),this.clickableCellsStore=Tv(tZ),t.useChildSubEnv({getPopoverContainerRect:()=>qN(this.env.model.getters.getViewportZoomLevel(),this.getGridRect())}),KG("canvas",this.env.model,()=>this.env.model.getters.getSheetViewDimension()),this.onMouseWheel=QG((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=Tv(aV),JG(this.gridRef,this.moveCanvas.bind(this),()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},()=>{const{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e})}get gridContainer(){const e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e),{end:s}=this.env.model.getters.getColDimensions(e,t);return JF({"max-width":`${s}px`})}get gridOverlayDimensions(){return JF({height:"100%",width:"100%"})}getCellClickableStyle(e){return JF({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){return t.toRaw(this.clickableCellsStore.clickableCells)}selectClickableCell(e,t){const{position:s,action:o}=t;o(s,this.env,HN(e))}onClosePopover(){this.cellPopovers.close()}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:0,gridOffsetY:0})}moveCanvas(e,t){const{scrollX:s,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s+e,offsetY:o+t})}getGridRect(){return{...ON(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}}class oZ extends t.Component{static template="o-spreadsheet-HeaderGroup";static props={group:Object,layerOffset:Number,openContextMenu:Function};toggleGroup(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group;gG(this.env,e,this.dimension,t,s)}get groupBoxStyle(){const e=this.groupBox;return JF({top:`${e.groupRect.y}px`,left:`${e.groupRect.x}px`,width:`${e.groupRect.width}px`,height:`${e.groupRect.height}px`})}get groupButtonStyle(){return JF({"background-color":this.isGroupFolded?"#333":"#fff",color:this.isGroupFolded?"#fff":"#333"})}get groupButtonIcon(){return this.isGroupFolded?"o-spreadsheet-Icon.PLUS":"o-spreadsheet-Icon.MINUS"}get isGroupFolded(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.group;return this.env.model.getters.isGroupFolded(e,this.dimension,t.start,t.end)}onContextMenu(e){const t=this.env.model.getters.getActiveSheetId(),s={x:e.clientX,y:e.clientY},o=this.props.group,i=function(e,t,s,o){const i=Sv([{id:"toggle_group",name:e=>{const i=e.model.getters.getActiveSheetId(),n=e.model.getters.isGroupFolded(i,t,s,o);return Cs(n?"ROW"===t?"Expand row group":"Expand column group":"ROW"===t?"Collapse row group":"Collapse column group")},execute:e=>{const i=e.model.getters.getActiveSheetId();gG(e,i,t,s,o)},icon:e=>{const i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,s,o)?"o-spreadsheet-Icon.EXPAND":"o-spreadsheet-Icon.COLLAPSE"}},{id:"remove_group",name:Cs("ROW"===t?"Remove row group":"Remove column group"),execute:e=>{const i=e.model.getters.getActiveSheetId();e.model.dispatch("UNGROUP_HEADERS",{sheetId:i,dimension:t,start:s,end:o})},icon:"o-spreadsheet-Icon.TRASH",separator:!0}]);return[...i,...pG(e,t)]}(t,this.dimension,o.start,o.end);this.props.openContextMenu(s,i)}}class iZ extends oZ{dimension="ROW";get groupBorderStyle(){const e=this.groupBox;return 0===this.groupBox.groupRect.height?"":JF({top:e.headerRect.height/2+"px",left:"calc(50% - 1px)",width:"30%",height:`calc(100% - ${e.headerRect.height/2}px)`,"border-left":"1px solid","border-bottom":e.isEndHidden?"":"1px solid"})}get groupHeaderStyle(){return JF({width:"100%",height:`${this.groupBox.headerRect.height}px`})}get groupBox(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group,o=this.env.model.getters.getRowDimensions(e,t).start,i=this.env.model.getters.getRowDimensions(e,s).end;let n=0,r=O;if(0!==t){const s=this.env.model.getters.getRowDimensions(e,t-1);n=O+s.start,r=s.end-s.start}const a={x:this.props.layerOffset,y:n,width:M,height:r};return{headerRect:a,groupRect:{x:this.props.layerOffset,y:a.y,width:M,height:a.height+(i-o)},isEndHidden:this.env.model.getters.isRowHidden(e,s)}}}class nZ extends oZ{dimension="COL";get groupBorderStyle(){const e=this.groupBox;return 0===e.groupRect.width?"":JF({top:"calc(50% - 1px)",left:e.headerRect.width/2+"px",width:`calc(100% - ${e.headerRect.width/2}px)`,height:"30%","border-top":"1px solid","border-right":e.isEndHidden?"":"1px solid"})}get groupHeaderStyle(){return JF({width:`${this.groupBox.headerRect.width}px`,height:"100%"})}get groupBox(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:s}=this.props.group,o=this.env.model.getters.getColDimensions(e,t).start,i=this.env.model.getters.getColDimensions(e,s).end;let n=0,r=F;if(0!==t){const s=this.env.model.getters.getColDimensions(e,t-1);n=F+s.start,r=s.end-s.start}const a={x:n,y:this.props.layerOffset,width:r,height:M};return{headerRect:a,groupRect:{x:a.x,y:this.props.layerOffset,width:a.width+(i-o),height:M},isEndHidden:this.env.model.getters.isColHidden(e,s)}}}class rZ extends t.Component{static template="o-spreadsheet-HeaderGroupContainer";static props={dimension:String,layers:Array};static components={RowGroup:iZ,ColGroup:nZ,MenuPopover:JL};menu=t.useState({isOpen:!1,anchorRect:null,menuItems:[]});getLayerOffset(e){return e*M}onContextMenu(e){const t=this.env.model.getters.getActiveSheetId(),s={x:e.clientX,y:e.clientY},o=pG(t,this.props.dimension);this.openContextMenu(s,o)}openContextMenu(e,t){this.menu.isOpen=!0,this.menu.anchorRect={...e,width:0,height:0},this.menu.menuItems=t}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get groupComponent(){return"ROW"===this.props.dimension?iZ:nZ}get hasFrozenPane(){const e=this.env.model.getters.getMainViewportCoordinates();return"COL"===this.props.dimension?e.x>0:e.y>0}get scrollContainerStyle(){const{scrollX:e,scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo(),s={};return"COL"===this.props.dimension?s.left=-e-this.frozenPaneContainerSize+"px":s.top=-t-this.frozenPaneContainerSize+"px",JF(s)}get frozenPaneContainerStyle(){const e={};return"COL"===this.props.dimension?e.width=`${this.frozenPaneContainerSize}px`:e.height=`${this.frozenPaneContainerSize}px`,JF(e)}get frozenPaneContainerSize(){if(!this.hasFrozenPane)return 0;const e=this.env.model.getters.getMainViewportCoordinates();return"COL"===this.props.dimension?F+e.x:O+e.y}}class aZ extends t.Component{static template="o-spreadsheet-SidePanel";static props={panelContent:Object,panelProps:Object,onCloseSidePanel:Function,onStartHandleDrag:Function,onResetPanelSize:Function,isPinned:{type:Boolean,optional:!0},onTogglePinPanel:{type:Function,optional:!0},onToggleCollapsePanel:{type:Function,optional:!0},isCollapsed:{type:Boolean,optional:!0}};spreadsheetRect=ZL();getTitle(){const e=this.props.panelContent;return"function"==typeof e.title?e.title(this.env,this.props.panelProps):e.title}get pinInfoMessage(){return Cs("Pin this panel to allow to open another side panel beside it.")}}class lZ extends t.Component{static template="o-spreadsheet-SidePanels";static props={};static components={SidePanel:aZ};sidePanelStore;spreadsheetRect=ZL();setup(){this.sidePanelStore=Tv(pq),t.useEffect(()=>{this.sidePanelStore.mainPanel&&!this.sidePanelStore.isMainPanelOpen&&this.sidePanelStore.closeMainPanel(),this.sidePanelStore.secondaryPanel&&!this.sidePanelStore.isSecondaryPanelOpen&&this.sidePanelStore.close()},()=>[this.sidePanelStore.isMainPanelOpen,this.sidePanelStore.isSecondaryPanelOpen])}startHandleDrag(e,t){const s=document.body.style.cursor,o="mainPanel"===e?this.sidePanelStore.mainPanel:this.sidePanelStore.secondaryPanel;if(!o)return;const i=o.size,n=t.clientX;qV(t=>{document.body.style.cursor="col-resize";const s=i+n-t.clientX;this.sidePanelStore.changePanelSize(e,s)},()=>{document.body.style.cursor=s})}get mainPanelProps(){const e=this.sidePanelStore.mainPanelProps;if(this.sidePanelStore.mainPanel&&e)return{panelContent:hq.get(this.sidePanelStore.mainPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.closeMainPanel(),onTogglePinPanel:()=>this.sidePanelStore.togglePinPanel(),onStartHandleDrag:e=>this.startHandleDrag("mainPanel",e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize("mainPanel"),isPinned:this.sidePanelStore.mainPanel?.isPinned,onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel("mainPanel"),isCollapsed:this.sidePanelStore.mainPanel?.isCollapsed}}get secondaryPanelProps(){const e=this.sidePanelStore.secondaryPanelProps;if(this.sidePanelStore.secondaryPanel&&e)return{panelContent:hq.get(this.sidePanelStore.secondaryPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.close(),onStartHandleDrag:e=>this.startHandleDrag("secondaryPanel",e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize("secondaryPanel"),onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel("secondaryPanel"),isCollapsed:this.sidePanelStore.secondaryPanel?.isCollapsed}}get panelList(){return[{key:this.sidePanelStore.secondaryPanelKey,props:this.secondaryPanelProps,style:this.sidePanelStore.secondaryPanel?JF({width:`${this.sidePanelStore.secondaryPanel.size}px`}):""},{key:this.sidePanelStore.mainPanelKey,props:this.mainPanelProps,style:this.sidePanelStore.mainPanel?JF({width:`${this.sidePanelStore.mainPanel.size}px`}):""}].filter(e=>e.key&&e.props)}}class cZ extends t.Component{static template="o-spreadsheet-RibbonMenu";static props={onClose:Function};static components={Menu:WL};rootItems=Mq.getMenuItems();menuRef=t.useRef("menu");containerRef=t.useRef("container");state=t.useState({menuItems:this.rootItems,title:Cs("Menu Bar"),parentState:void 0});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.onMounted(this.updateShadows)}onExternalClick(e){this.menuRef.el?.contains(e.target)||this.props.onClose()}onClickMenu(e){const t=e.children(this.env);t.length?(this.state.parentState={...this.state},this.state.menuItems=t,this.state.title=e.name(this.env),this.containerRef.el?.scrollTo({top:0})):(this.state.menuItems=this.rootItems,this.state.title=void 0,this.state.parentState=void 0,e.execute?.(this.env),this.props.onClose())}get menuProps(){return{menuItems:this.state.menuItems,onClose:this.props.onClose,onClickMenu:this.onClickMenu.bind(this)}}get style(){return JF({height:`${this.props.height}px`})}updateShadows(){if(!this.containerRef.el)return;this.containerRef.el.classList.remove("scroll-top","scroll-bottom");const e=this.containerRef.el.scrollHeight-this.containerRef.el.clientHeight||0;this.containerRef.el.scrollTop<e-1&&this.containerRef.el.classList.add("scroll-bottom"),this.containerRef.el.scrollTop>0&&this.containerRef.el.classList.add("scroll-top")}onClickBack(){this.state.parentState?(this.state.menuItems=this.state.parentState.menuItems,this.state.title=this.state.parentState.title,this.state.parentState=this.state.parentState.parentState,this.containerRef.el?.scrollTo({top:0})):this.props.onClose()}get backTitle(){return this.state.parentState?Cs("Go to previous menu"):Cs("Close menu bar")}}class hZ extends t.Component{static components={Composer:_V,BottomBar:eZ,Ripple:Yq,RibbonMenu:cZ};static template="o-spreadsheet-SmallBottomBar";static props={onClick:Function};composerFocusStore;composerStore;composerInterface;composerRef=t.useRef("bottombarComposer");menuState=t.useState({isOpen:!1});setup(){this.composerFocusStore=Tv(zv);const e=Tv(RG);this.composerStore=e,this.composerInterface={id:"bottombarComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},t.useEffect(()=>{this.env.isMobile()&&!this.menuState.isOpen&&"inactive"!==this.composerStore.editionMode&&this.composerFocusStore.activeComposer!==this.composerInterface&&this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"})})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get showFxIcon(){return"inactive"===this.focus&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get rect(){return this.composerRef.el?FN(this.composerRef.el):{x:0,y:0,width:0,height:0}}get composerProps(){const{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,composerStore:this.composerStore,onComposerContentFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus",selection:e}),isDefaultFocus:!1,inputStyle:JF({height:"inactive"===this.focus?"26px":"fit-content","max-height":"130px"}),showAssistant:!1,placeholder:this.composerStore.placeholder}}get symbols(){return["=","(",")",":","-","/","*",",","+","$","."]}insertSymbol(e){this.composerStore.replaceComposerCursorSelection(e),this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"})}toggleRibbon(){this.composerStore.cancelEdition(),this.menuState.isOpen=!this.menuState.isOpen}}class dZ extends t.Component{static template="o-spreadsheet-TopBarComposer";static props={};static components={Composer:_V};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=Tv(zv);const e=Tv(RG);this.composerStore=e,this.composerInterface={id:"topbarComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition}}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get showFxIcon(){return"inactive"===this.focus&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get composerStyle(){const e={padding:"5px 0px 5px 8px","max-height":"300px","line-height":"24px"};return e.height="inactive"===this.focus?"34px":"fit-content",JF(e)}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}}class uZ{mutators=["closeDropdowns","openDropdown"];_currentDropdown=null;closeDropdowns(){this._currentDropdown=null}openDropdown(e){this._currentDropdown=e}get currentDropdown(){return this._currentDropdown}}function gZ(){const e=t.useComponent(),s=Tv(uZ);return t.onWillUnmount(()=>{e===s.currentDropdown&&s.closeDropdowns()}),{closeDropdowns:()=>s.closeDropdowns(),openDropdown:()=>{s.openDropdown(e)},get isActive(){return s.currentDropdown===e}}}const pZ=[[["all","o-spreadsheet-Icon.BORDERS"],["hv","o-spreadsheet-Icon.BORDER_HV"],["h","o-spreadsheet-Icon.BORDER_H"],["v","o-spreadsheet-Icon.BORDER_V"],["external","o-spreadsheet-Icon.BORDER_EXTERNAL"]],[["left","o-spreadsheet-Icon.BORDER_LEFT"],["top","o-spreadsheet-Icon.BORDER_TOP"],["right","o-spreadsheet-Icon.BORDER_RIGHT"],["bottom","o-spreadsheet-Icon.BORDER_BOTTOM"],["clear","o-spreadsheet-Icon.BORDER_CLEAR"]]];class mZ extends t.Component{static template="o-spreadsheet-BorderEditor";static props={class:{type:String,optional:!0},currentBorderColor:{type:String,optional:!1},currentBorderStyle:{type:String,optional:!1},currentBorderPosition:{type:String,optional:!0},onBorderColorPicked:Function,onBorderStylePicked:Function,onBorderPositionPicked:Function,maxHeight:{type:Number,optional:!0},anchorRect:Object};static components={ColorPickerWidget:uW,Popover:jL};BORDER_POSITIONS=pZ;lineStyleButtonRef=t.useRef("lineStyleButton");borderStyles=Ms;state=t.useState({activeTool:void 0});toggleDropdownTool(e){const t=this.state.activeTool===e;this.state.activeTool=t?void 0:e}closeDropdown(){this.state.activeTool=void 0}setBorderPosition(e){this.props.onBorderPositionPicked(e),this.closeDropdown()}setBorderColor(e){this.props.onBorderColorPicked(e),this.closeDropdown()}setBorderStyle(e){this.props.onBorderStylePicked(e),this.closeDropdown()}get lineStylePickerPopoverProps(){return{anchorRect:this.lineStylePickerAnchorRect,positioning:"bottom-left",verticalOffset:0}}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"bottom-left",verticalOffset:0}}get lineStylePickerAnchorRect(){const e=this.lineStyleButtonRef.el;if(null===e)return{x:0,y:0,width:0,height:0};const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}}class fZ extends t.Component{static template="o-spreadsheet-BorderEditorWidget";static props={disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={BorderEditor:mZ};topBarToolStore;borderEditorButtonRef=t.useRef("borderEditorButton");state=t.useState({currentColor:B,currentStyle:U,currentPosition:void 0});setup(){this.topBarToolStore=gZ(),t.onWillUpdateProps(()=>{this.isActive||(this.state.currentPosition=void 0)})}get dropdownMaxHeight(){return this.env.model.getters.getSheetViewDimension().height}get borderEditorAnchorRect(){const e=this.borderEditorButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}onBorderPositionPicked(e){this.state.currentPosition=e,this.updateBorder()}onBorderColorPicked(e){this.state.currentColor=e,this.updateBorder()}onBorderStylePicked(e){this.state.currentStyle=e,this.updateBorder()}get isActive(){return this.topBarToolStore.isActive}toggleBorderEditor(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}updateBorder(){void 0!==this.state.currentPosition&&this.env.model.dispatch("SET_ZONE_BORDERS",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),border:{position:this.state.currentPosition,color:this.state.currentColor,style:this.state.currentStyle}})}}class vZ extends t.Component{static template="o-spreadsheet-PaintFormatButton";static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=Tv(VG)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}}class bZ extends t.Component{static template="o-spreadsheet-TableDropdownButton";static components={TableStylesPopover:nq,ActionButton:dW};static props={class:{type:String,optional:!0}};topBarToolStore;state=t.useState({popoverProps:void 0});setup(){this.topBarToolStore=gZ()}onStylePicked(e){const t=this.env.model.getters.getActiveSheetId(),s={...this.tableConfig,styleId:e};Bz(this.env,t,s).isSuccessful&&this.env.openSidePanel("TableSidePanel",{}),this.closePopover()}onClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps)return void this.closePopover();if(this.env.model.getters.getFirstTableInSelection())return this.topBarToolStore.closeDropdowns(),void this.env.toggleSidePanel("TableSidePanel",{});const t=e.currentTarget,{left:s,bottom:o}=t.getBoundingClientRect();this.topBarToolStore.openDropdown(),this.state.popoverProps={anchorRect:{x:s,y:o,width:0,height:0},positioning:"bottom-left",verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}get action(){return{name:e=>e.model.getters.getFirstTableInSelection()?Cs("Edit table"):Cs("Insert table"),icon:e=>e.model.getters.getFirstTableInSelection()?"o-spreadsheet-Icon.EDIT_TABLE":"o-spreadsheet-Icon.PAINT_TABLE"}}get tableConfig(){return{...Zx,numberOfHeaders:1,bandedRows:!0}}}class SZ extends t.Component{static components={ColorPickerWidget:uW};static props={class:String,style:String,icon:String,title:String};static template="o-spreadsheet-ColorEditor";topBarToolStore;state=t.useState({isOpen:!1});setup(){this.topBarToolStore=gZ()}get currentColor(){return this.env.model.getters.getCurrentStyle()[this.props.style]||("textColor"===this.props.style?"#000000":"#ffffff")}setColor(e){Wz(this.env,{[this.props.style]:e}),this.state.isOpen=!1}get isMenuOpen(){return this.topBarToolStore.isActive}onClick(){this.isMenuOpen?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}}class yZ extends t.Component{static template="o-spreadsheet-DropdownAction";static components={ActionButton:dW,Popover:jL};static props={parentAction:Object,childActions:Array,class:String,childClass:String};topBarToolStore;actionRef=t.useRef("actionRef");setup(){this.topBarToolStore=gZ()}toggleDropdown(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}get popoverProps(){return{anchorRect:this.actionRef.el?this.actionRef.el.getBoundingClientRect():{x:0,y:0,width:0,height:0},positioning:"bottom-left",verticalOffset:0,class:"rounded"}}}class CZ extends t.Component{static components={FontSizeEditor:pW};static props={class:String};static template="o-spreadsheet-TopBarFontSizeEditor";topBarToolStore;setup(){this.topBarToolStore=gZ()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||z}setFontSize(e){Wz(this.env,{fontSize:e})}onToggle(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}}class IZ extends t.Component{static template="o-spreadsheet-NumberFormatsTool";static components={MenuPopover:JL,ActionButton:dW};static props={class:String};formatNumberMenuItemSpec=Pq;topBarToolStore;buttonRef=t.useRef("buttonRef");state=t.useState({anchorRect:{x:0,y:0,width:0,height:0},menuItems:[]});setup(){this.topBarToolStore=gZ()}toggleMenu(){if(this.isActive)this.topBarToolStore.closeDropdowns();else{const e=Cv(this.formatNumberMenuItemSpec);this.state.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.anchorRect=FN(this.buttonRef.el),this.topBarToolStore.openDropdown()}}get isActive(){return this.topBarToolStore.isActive}}class wZ extends t.Component{static template="o-spreadsheet-TopBarZoom";static components={NumberEditor:gW};static props={class:String};topBarToolStore;valueList=N;setup(){this.topBarToolStore=gZ()}get currentFontSize(){return 100*(this.env.model.getters.getViewportZoomLevel()||1)}setZoom(e){this.env.model.dispatch("SET_ZOOM",{zoom:e/100})}toggle(){this.topBarToolStore.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}}const EZ=new class{content={};add(e){if(e in this.content)throw new Error(`${e} is already present in this registry!`);return this.content[e]=[],this}addChild(e,t){return this.content[e].push(t),this}getEntries(e){return this.content[e].sort((e,t)=>e.sequence-t.sequence)}getCategories(){return Object.keys(this.content)}};EZ.add("edit").addChild("edit",{component:dW,props:{action:kH,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("edit",{component:dW,props:{action:LH,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("edit",{component:vZ,props:{class:"o-hoverable-button o-toolbar-button o-mobile-disabled"},sequence:3}).addChild("edit",{component:dW,props:{action:rG,class:"o-hoverable-button o-toolbar-button"},sequence:4}).addChild("edit",{component:wZ,props:{class:"o-menu-item-button o-hoverable-button o-toolbar-button"},sequence:5}).add("numberFormat").addChild("numberFormat",{component:dW,props:{action:bB,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("numberFormat",{component:dW,props:{action:PB,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("numberFormat",{component:dW,props:{action:FB,class:"o-hoverable-button o-toolbar-button"},sequence:3}).addChild("numberFormat",{component:IZ,props:{class:"o-menu-item-button o-hoverable-button o-toolbar-button"},sequence:4}).add("fontSize").addChild("fontSize",{component:CZ,props:{class:"o-hoverable-button o-toolbar-button"},sequence:3}).add("textStyle").addChild("textStyle",{component:dW,props:{action:MB,class:"o-hoverable-button o-toolbar-button"},sequence:1}).addChild("textStyle",{component:dW,props:{action:NB,class:"o-hoverable-button o-toolbar-button"},sequence:2}).addChild("textStyle",{component:dW,props:{action:GB,class:"o-hoverable-button o-toolbar-button"},sequence:3}).addChild("textStyle",{component:SZ,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button",style:"textColor",icon:"o-spreadsheet-Icon.TEXT_COLOR",title:Cs("Text Color")},sequence:4}).add("cellStyle").addChild("cellStyle",{component:SZ,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button",style:"fillColor",icon:"o-spreadsheet-Icon.FILL_COLOR",title:Cs("Fill Color")},sequence:1}).addChild("cellStyle",{component:fZ,props:{class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:2}).addChild("cellStyle",{component:dW,props:{action:tU,class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:3}).add("alignment").addChild("alignment",{component:yZ,props:{parentAction:qB,childActions:[ZB,jB,YB],class:"o-hoverable-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:1}).addChild("alignment",{component:yZ,props:{parentAction:XB,childActions:[KB,JB,QB],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:2}).addChild("alignment",{component:yZ,props:{parentAction:tG,childActions:[sG,oG,iG],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:3}).addChild("alignment",{component:yZ,props:{parentAction:LB,childActions:[VB,zB,HB,UB,BB],class:"o-hoverable-button o-menu-item-button o-toolbar-button",childClass:"o-hoverable-button"},sequence:4}).add("misc").addChild("misc",{component:bZ,props:{class:"o-toolbar-button o-hoverable-button o-menu-item-button o-mobile-disabled"},sequence:1}).addChild("misc",{component:dW,props:{action:hB,class:"o-hoverable-button o-menu-item-button o-toolbar-button"},sequence:2});class xZ extends t.Component{static template="o-spreadsheet-TopBar";static props={onClick:Function,dropdownMaxHeight:Number};static components={MenuPopover:JL,TopBarComposer:dZ,Popover:jL};toolsCategories=EZ.getCategories();state=t.useState({menuState:{isOpen:!1,anchorRect:null,menuItems:[]},invisibleToolsCategories:[],toolsPopoverState:{isOpen:!1}});isSelectingMenu=!1;openedEl=null;menus=[];toolbarMenuRegistry=EZ;formatNumberMenuItemSpec=Pq;isntToolbarMenu=!1;composerFocusStore;fingerprints;topBarToolStore;toolBarContainerRef=t.useRef("toolBarContainer");toolbarRef=t.useRef("toolBar");moreToolsContainerRef=t.useRef("moreToolsContainer");moreToolsButtonRef=t.useRef("moreToolsButton");spreadsheetRect=ZL();setup(){this.composerFocusStore=Tv(zv),this.fingerprints=Tv(rH),this.topBarToolStore=Tv(uZ),t.useExternalListener(window,"click",this.onExternalClick),t.onWillStart(()=>this.updateCellState()),t.onWillUpdateProps(()=>this.updateCellState()),t.useEffect(()=>{this.state.toolsPopoverState.isOpen=!1,this.setVisibilityToolsGroups()},()=>[this.spreadsheetRect.width])}setVisibilityToolsGroups(){if(this.env.model.getters.isReadonly())return;const e=[],{x:t}=this.toolbarRef.el.getBoundingClientRect(),{x:s}=this.toolBarContainerRef.el.getBoundingClientRect();this.moreToolsContainerRef.el?.classList.remove("d-none");const o=this.moreToolsButtonRef.el?.getBoundingClientRect().width||0,i=Math.round(this.spreadsheetRect.width)-o-(t-s)-16,n=document.querySelectorAll(".tool-container");let r=0;for(let t=0;t<n.length;t++){const s=n[t];s.classList.remove("d-none");const{width:o}=s.getBoundingClientRect();r+=o,r>i&&(s.classList.add("d-none"),e.push(this.toolsCategories[t]))}this.state.invisibleToolsCategories=e,e.length||this.moreToolsContainerRef.el?.classList.add("d-none")}get topbarComponents(){return $q.getAllOrdered().filter(e=>!e.isVisible||e.isVisible(this.env))}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||z}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.isntToolbarMenu&&this.openMenu(e,t)}toggleContextMenu(e,t){this.state.menuState.isOpen&&this.isntToolbarMenu?this.closeMenus():(this.openMenu(e,t),this.isntToolbarMenu=!0)}openMenu(e,t){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!0,this.state.menuState.anchorRect=FN(t.currentTarget),this.state.menuState.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.composerFocusStore.activeComposer.stopEdition()}closeMenus(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){this.menus=Mq.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){Wz(this.env,{[e]:t}),this.onClick()}setFontSize(e){Wz(this.env,{fontSize:e})}toggleMoreTools(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!this.state.toolsPopoverState.isOpen}get toolsPopoverProps(){return{anchorRect:this.moreToolsButtonRef.el?FN(this.moreToolsButtonRef.el):{x:0,y:0,width:0,height:0},positioning:"bottom-left",verticalOffset:0,class:"rounded",maxWidth:300}}showDivider(e){return e<this.toolsCategories.length-1||this.state.invisibleToolsCategories.length>0}}class RZ{clipboard;constructor(e){this.clipboard=e}async write(e){if(this.clipboard?.write)try{await(this.clipboard?.write(this.getClipboardItems(e)))}catch(t){console.log("Failed to write on the clipboard, falling back to plain/html text. Error %s",t);try{await(this.clipboard?.write([new ClipboardItem({[QF.PlainText]:this.getBlob(e,QF.PlainText),[QF.Html]:this.getBlob(e,QF.Html)})]))}catch(e){}}else await this.writeText(e[QF.PlainText]??"")}async writeText(e){try{this.clipboard?.writeText(e)}catch(e){}}async read(){let e;try{e=await navigator.permissions.query({name:"clipboard-read"})}catch(e){}if(!this.clipboard?.read)return{status:"ok",content:{[QF.PlainText]:await(this.clipboard?.readText())}};try{const e=await this.clipboard.read(),t={};for(const s of e)for(const e of s.types){const o=await s.getType(e);if(eP.includes(e))t[e]=o;else{const s=await o.text();t[e]=s}}return{status:"ok",content:t}}catch(t){return{status:"denied"===e?.state?"permissionDenied":"notImplemented"}}}getClipboardItems(e){const t={};for(const s of Object.keys(e))t[s]=this.getBlob(e,s);return[new ClipboardItem(t)]}getBlob(e,t){const s=e[t];return s instanceof Blob||s instanceof File?s:new Blob([e[t]||""],{type:t})}}class TZ extends t.Component{static template="o-spreadsheet-Spreadsheet";static props={model:Object,notifyUser:{type:Function,optional:!0},raiseError:{type:Function,optional:!0},askConfirmation:{type:Function,optional:!0},colorScheme:{type:String,optional:!0}};static components={TopBar:xZ,Grid:vq,BottomBar:eZ,SmallBottomBar:hZ,SidePanels:lZ,SpreadsheetDashboard:sZ,HeaderGroupContainer:rZ,FullScreenFigure:Iq};sidePanel;spreadsheetRef=t.useRef("spreadsheet");spreadsheetRect=ZL();_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){const e={},t=this.env.model.getters.getScrollBarWidth();this.env.isDashboard()?e["grid-template-rows"]="auto":e["grid-template-rows"]="min-content auto min-content";const s=this.sidePanel.mainPanel?`${this.sidePanel.totalPanelSize||uq}px`:"auto";return e["grid-template-columns"]=`auto ${s}`,e["--os-scrollbar-width"]=`${t}px`,e["color-scheme"]=this.props.colorScheme,JF(e)}setup(){if(!("isSmall"in this.env)){const e=function(){const e=ZL();return{get isSmall(){return e.width<768}}}();t.useSubEnv({get isSmall(){return e.isSmall}})}const e=Rv();e.inject(Fv,this.model);const s=this.env;e.get(dq).setSmallThreshhold(()=>s.isSmall),this.notificationStore=Tv(kV),this.composerFocusStore=Tv(zv),this.sidePanel=Tv(pq);const o=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:o?new qq(o):void 0,loadCurrencies:this.model.config.external.loadCurrencies,loadLocales:this.model.config.external.loadLocales,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.sidePanel.open.bind(this.sidePanel),replaceSidePanel:this.sidePanel.replace.bind(this.sidePanel),toggleSidePanel:this.sidePanel.toggle.bind(this.sidePanel),clipboard:this.env.clipboard||new RZ(navigator.clipboard),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,s)=>this.notificationStore.askConfirmation(e,t,s),raiseError:(e,t)=>this.notificationStore.raiseError(e,t),isMobile:WN}),this.notificationStore.updateNotificationCallbacks({...this.props}),t.useEffect(()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()}),t.useExternalListener(window,"resize",()=>this.render(!0)),t.useExternalListener(document.body,"wheel",()=>{}),this.bindModelEvents(),t.onWillUpdateProps(e=>{if(e.model!==this.props.model)throw new Error("Changing the props model is not supported at the moment.");e.notifyUser===this.props.notifyUser&&e.askConfirmation===this.props.askConfirmation&&e.raiseError===this.props.raiseError||this.notificationStore.updateNotificationCallbacks({...e})});const i=function(e){let t=!1;return async(...s)=>{t||(t=!0,await Promise.resolve(),t=!1,e(...s))}}(this.render.bind(this,!0));t.onMounted(()=>{this.checkViewportSize(),e.on("store-updated",this,i),n.observe(this.spreadsheetRef.el)}),t.onWillUnmount(()=>{this.unbindModelEvents(),e.off("store-updated",this),n.disconnect(),Gv()}),t.onPatched(()=>{this.checkViewportSize()});const n=new ResizeObserver(()=>{this.sidePanel.changeSpreadsheetWidth(this.spreadsheetRect.width)})}bindModelEvents(){this.model.on("update",this,()=>this.render(!0)),this.model.on("notify-ui",this,e=>this.notificationStore.notifyUser(e)),this.model.on("raise-error-ui",this,({text:e})=>this.notificationStore.raiseError(e))}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this),this.model.off("raise-error-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(isFinite(e)&&isFinite(t))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.notificationStore.notifyUser({text:Cs("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),type:"warning",sticky:!1}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}focusGrid(){this._focusGrid&&this._focusGrid()}get gridHeight(){return this.env.model.getters.getSheetViewDimension().height}get gridContainerStyle(){const e=M*this.rowLayers.length,t=M*this.colLayers.length;return JF({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`,zoom:`${this.env.model.getters.getViewportZoomLevel()}`})}get rowLayers(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,"ROW")}get colLayers(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,"COL")}getGridSize(){const e=this.spreadsheetRef.el;if(!e)return{width:0,height:0};const t=this.env.model.getters.getViewportZoomLevel(),s=this.env.model.getters.getScrollBarWidth(),o=s=>e.querySelector(s)&&DN(e.querySelector(s),t).height||0,i=e.getBoundingClientRect(),n=o(".o-spreadsheet-topbar-wrapper"),r=o(".o-spreadsheet-bottombar-wrapper"),a=o(".o-column-groups"),l=(c=".o-grid",e.querySelector(c)&&DN(e.querySelector(c),t).width||0);var c;const h=i.height-a-n-r;return{width:Math.max(l/t-s,0),height:Math.max(h/t-s,0)}}getSpreadSheetClasses(){return[this.env.isSmall?"o-spreadsheet-mobile":"","dark"===this.props.colorScheme?"dark":""].join(" ")}}function AZ(e){return LW.includes(e.horizontalGroupBy)&&LW.includes(e.verticalGroupBy)?"Success":"InvalidChartDefinition"}class _Z extends zO{dataSets;labelRange;background;type="calendar";showValues;colorScale;axesDesign;horizontalGroupBy;verticalGroupBy;legendPosition;missingValueColor;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.showValues=e.showValues,this.colorScale=e.colorScale,this.axesDesign=e.axesDesign,this.horizontalGroupBy=e.horizontalGroupBy,this.verticalGroupBy=e.verticalGroupBy,this.legendPosition=e.legendPosition,this.missingValueColor=e.missingValueColor}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy,AZ)}static getDefinitionFromContextCreation(e){let t="left";return"right"===e.legendPosition&&(t="right"),{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,title:e.title||{text:""},type:"calendar",labelRange:e.auxiliaryRange||void 0,showValues:e.showValues,axesDesign:e.axesDesign,legendPosition:t,horizontalGroupBy:"day_of_week",verticalGroupBy:"month_number"}}getContextCreation(){const e=[{dataRange:this.getters.getRangeString(this.dataSets[0].dataRange,this.sheetId)}];return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new _Z(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new _Z(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)}));return{type:"calendar",background:this.background,dataSets:o,dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,showValues:this.showValues,colorScale:this.colorScale,axesDesign:this.axesDesign,horizontalGroupBy:this.horizontalGroupBy,verticalGroupBy:this.verticalGroupBy,legendPosition:this.legendPosition,missingValueColor:this.missingValueColor}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new _Z(i,this.sheetId,this.getters)}}class DZ extends zO{dataSets;labelRange;background;legendPosition;aggregated;dataSetsHaveTitle;dataSetDesign;axesDesign;type="combo";showValues;hideDataMarkers;zoomable;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers,this.zoomable=e.zoomable}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId),type:this.dataSetDesign?.[t]?.type??(t?"line":"bar")});return{type:"combo",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,zoomable:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,$y(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),s=this.getDefinition();return{...s,backgroundColor:IP(this.background||c),fontColor:IP(Uy(this.background)),dataSets:e,labelRange:t,verticalAxis:qy(s)}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new DZ(i,this.sheetId,this.getters)}static getDefinitionFromContextCreation(e){const t=(e.range??[]).map((e,t)=>({...e,type:t?"line":"bar"}));return{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated,legendPosition:e.legendPosition??"top",title:e.title||{text:""},labelRange:e.auxiliaryRange||void 0,type:"combo",axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new DZ(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new DZ(t,e,this.getters)}}class OZ extends zO{dataSets;labelRange;background;legendPosition;aggregated;type="funnel";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;showValues;funnelColors;cumulative;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.horizontal=!0,this.funnelColors=e.funnelColors,this.cumulative=e.cumulative}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:"none",title:e.title||{text:""},type:"funnel",labelRange:e.auxiliaryRange||void 0,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new OZ(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new OZ(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"funnel",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,horizontal:this.horizontal,axesDesign:this.axesDesign,showValues:this.showValues,funnelColors:this.funnelColors,cumulative:this.cumulative,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new OZ(i,this.sheetId,this.getters)}}class FZ extends zO{dataSets;labelRange;background;legendPosition;type="geo";dataSetsHaveTitle;dataSetDesign;colorScale;missingValueColor;region;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.colorScale=e.colorScale,this.missingValueColor=e.missingValueColor,this.region=e.region}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"geo",labelRange:e.auxiliaryRange||void 0,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new FZ(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new FZ(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"geo",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,colorScale:this.colorScale,missingValueColor:this.missingValueColor,region:this.region,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new FZ(i,this.sheetId,this.getters)}}class PZ extends zO{dataSets;labelRange;background;legendPosition;aggregated;type="pyramid";dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;stacked=!0;showValues;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"pyramid",labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new PZ(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new PZ(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"pyramid",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,horizontal:!0,stacked:!0,showValues:this.showValues,humanize:this.humanize}}getDefinitionForExcel(e){const{dataSets:t,labelRange:s}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,$y(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),o=this.getDefinition(),i=sk(o,this.dataSets,this.labelRange,e),{dataSetsValues:n}=i,r=Math.max(...n.map(e=>Math.max(...e.data.map(Math.abs))));return{...o,horizontal:!0,backgroundColor:IP(this.background||c),fontColor:IP(Uy(this.background)),dataSets:t,labelRange:s,verticalAxis:qy(o),maxValue:r}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new PZ(i,this.sheetId,this.getters)}}class MZ extends zO{dataSets;labelRange;background;legendPosition;stacked;aggregated;type="radar";dataSetsHaveTitle;dataSetDesign;fillArea;showValues;hideDataMarkers;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.fillArea=e.fillArea,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"radar",labelRange:e.auxiliaryRange||void 0,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers,humanize:e.humanize}}getContextCreation(){const e=[];for(const[t,s]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(s.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new MZ(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new MZ(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=[];for(const[t,i]of e.entries())o.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,s||this.sheetId)});return{type:"radar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated,fillArea:this.fillArea,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,humanize:this.humanize}}getDefinitionForExcel(){const{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,$y(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:IP(this.background||c),fontColor:IP(Uy(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new MZ(i,this.sheetId,this.getters)}}class NZ extends zO{dataSets;labelRange;background;legendPosition;type="sunburst";dataSetsHaveTitle;showValues;showLabels;valuesDesign;groupColors;pieHolePercentage;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.groupColors=e.groupColors,this.pieHolePercentage=e.pieHolePercentage}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){const t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"sunburst",labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){const e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}getDefinitionWithSpecificDataSets(e,t,s){return{type:"sunburst",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,showValues:this.showValues,showLabels:this.showLabels,valuesDesign:this.valuesDesign,groupColors:this.groupColors,pieHolePercentage:this.pieHolePercentage,humanize:this.humanize}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new NZ(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new NZ(t,e,this.getters)}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new NZ(i,this.sheetId,this.getters)}}class kZ extends zO{static defaults={background:c,legendPosition:"top",dataSetsHaveTitle:!1,showHeaders:!0,headersColor:"#000000"};dataSets;labelRange;background;legendPosition;type="treemap";dataSetsHaveTitle;showHeaders;headerDesign;showValues;showLabels;valuesDesign;coloringOptions;constructor(e,t,s){super(e,t,s),this.dataSets=ky(s,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Jb(s,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showHeaders=e.showHeaders,this.headerDesign=e.headerDesign,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.coloringOptions=e.coloringOptions}static transformDefinition(e,t,s){return Hy(e,t,s)}static validateChartDefinition(e,t){return e.checkValidations(t,Gy,Wy)}static getDefinitionFromContextCreation(e){const t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??"top",title:e.title||{text:""},type:"treemap",labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions,humanize:e.humanize}}getContextCreation(){const e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}duplicateInDuplicatedSheet(e){const t=Py(this.sheetId,e,this.dataSets),s=My(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,s,e);return new kZ(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new kZ(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,s){const o=e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,s||this.sheetId)}));return{type:"treemap",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:o,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,s||this.sheetId):void 0,title:this.title,showValues:this.showValues,showHeaders:this.showHeaders,headerDesign:this.headerDesign,showLabels:this.showLabels,valuesDesign:this.valuesDesign,coloringOptions:this.coloringOptions,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges(e){const{dataSets:t,labelRange:s,isStale:o}=Fy(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const i=this.getDefinitionWithSpecificDataSets(t,s);return new kZ(i,this.sheetId,this.getters)}}vR.add("bar",{match:e=>"bar"===e,createChart:(e,t,s)=>new aL(e,t,s),getChartRuntime:lL,validateChartDefinition:aL.validateChartDefinition,transformDefinition:aL.transformDefinition,getChartDefinitionFromContextCreation:aL.getDefinitionFromContextCreation,sequence:10}),vR.add("combo",{match:e=>"combo"===e,createChart:(e,t,s)=>new DZ(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=QN(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:iN(s,o)},options:{...eF,layout:xk(0,o),scales:kM(s,o),plugins:{title:Gk(s,t),legend:Fk(s),tooltip:Zk(s,o),chartShowValuesPlugin:Vk(s,o)}}},background:e.background||c}},validateChartDefinition:DZ.validateChartDefinition,transformDefinition:DZ.transformDefinition,getChartDefinitionFromContextCreation:DZ.getDefinitionFromContextCreation,sequence:15}),vR.add("line",{match:e=>"line"===e,createChart:(e,t,s)=>new bL(e,t,s),getChartRuntime:SL,validateChartDefinition:bL.validateChartDefinition,transformDefinition:bL.transformDefinition,getChartDefinitionFromContextCreation:bL.getDefinitionFromContextCreation,sequence:20}),vR.add("pie",{match:e=>"pie"===e,createChart:(e,t,s)=>new yL(e,t,s),getChartRuntime:CL,validateChartDefinition:yL.validateChartDefinition,transformDefinition:yL.transformDefinition,getChartDefinitionFromContextCreation:yL.getDefinitionFromContextCreation,sequence:30}),vR.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,s)=>new ZO(e,t,s),getChartRuntime:YO,validateChartDefinition:ZO.validateChartDefinition,transformDefinition:ZO.transformDefinition,getChartDefinitionFromContextCreation:ZO.getDefinitionFromContextCreation,sequence:40}),vR.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,s)=>new gL(e,t,s),getChartRuntime:pL,validateChartDefinition:gL.validateChartDefinition,transformDefinition:gL.transformDefinition,getChartDefinitionFromContextCreation:gL.getDefinitionFromContextCreation,sequence:50}),vR.add("scatter",{match:e=>"scatter"===e,createChart:(e,t,s)=>new e$(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=ok(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"line",data:{labels:o.labels,datasets:sN(s,o)},options:{...eF,layout:xk(0,o),scales:HM(s,o),plugins:{title:Gk(s,t),legend:Ok(s),tooltip:Yk(s,o),chartShowValuesPlugin:Vk(s,o)}}},background:e.background||c}},validateChartDefinition:e$.validateChartDefinition,transformDefinition:e$.transformDefinition,getChartDefinitionFromContextCreation:e$.getDefinitionFromContextCreation,sequence:60}),vR.add("waterfall",{match:e=>"waterfall"===e,createChart:(e,t,s)=>new IL(e,t,s),getChartRuntime:wL,validateChartDefinition:IL.validateChartDefinition,transformDefinition:IL.transformDefinition,getChartDefinitionFromContextCreation:IL.getDefinitionFromContextCreation,sequence:70}),vR.add("pyramid",{match:e=>"pyramid"===e,createChart:(e,t,s)=>new PZ(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=sk(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"bar",data:{labels:o.labels,datasets:JM(s,o)},options:{...eF,indexAxis:"y",layout:xk(0,o),scales:BM(s,o),plugins:{title:Gk(s,t),legend:Ak(s),tooltip:Jk(s,o),chartShowValuesPlugin:Uk(s,o)}}},background:e.background||c}},validateChartDefinition:PZ.validateChartDefinition,transformDefinition:PZ.transformDefinition,getChartDefinitionFromContextCreation:PZ.getDefinitionFromContextCreation,sequence:80,dataSeriesLimit:2}),vR.add("radar",{match:e=>"radar"===e,createChart:(e,t,s)=>new MZ(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=nk(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"radar",data:{labels:o.labels,datasets:nN(s,o)},options:{...eF,layout:xk(0,o),scales:GM(s,o),plugins:{title:Gk(s,t),legend:Mk(s),tooltip:Qk(s,o),chartShowValuesPlugin:Vk(s,o)}}},background:e.background||c}},validateChartDefinition:MZ.validateChartDefinition,transformDefinition:MZ.transformDefinition,getChartDefinitionFromContextCreation:MZ.getDefinitionFromContextCreation,sequence:80}),vR.add("geo",{match:e=>"geo"===e,createChart:(e,t,s)=>new FZ(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=rk(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"choropleth",data:{datasets:rN(s,o)},options:{...eF,layout:xk(0,o),scales:WM(s,o),plugins:{title:Gk(s,t),tooltip:eL(s,o),legend:{display:!1}}}},background:e.background||c}},validateChartDefinition:FZ.validateChartDefinition,transformDefinition:FZ.transformDefinition,getChartDefinitionFromContextCreation:FZ.getDefinitionFromContextCreation,sequence:90,dataSeriesLimit:1}),vR.add("funnel",{match:e=>"funnel"===e,createChart:(e,t,s)=>new OZ(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=ak(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"funnel",data:{labels:o.labels,datasets:aN(s,o)},options:{...eF,indexAxis:"y",layout:xk(0,o),scales:$M(0,o),plugins:{title:Gk(s,t),legend:{display:!1},tooltip:tL(s,o),chartShowValuesPlugin:Vk(s,o)}}},background:e.background||c}},validateChartDefinition:OZ.validateChartDefinition,transformDefinition:OZ.transformDefinition,getChartDefinitionFromContextCreation:OZ.getDefinitionFromContextCreation,sequence:100,dataSeriesLimit:1}),vR.add("sunburst",{match:e=>"sunburst"===e,createChart:(e,t,s)=>new NZ(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=lk(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"doughnut",data:{datasets:cN(s,o)},options:{cutout:void 0===e.pieHolePercentage?"25%":`${e.pieHolePercentage}%`,...eF,layout:xk(0,o),plugins:{title:Gk(s,t),legend:Nk(s),tooltip:sL(s,o),sunburstLabelsPlugin:Hk(s,o),sunburstHoverPlugin:{enabled:!0}}}},background:e.background||c}},validateChartDefinition:NZ.validateChartDefinition,transformDefinition:NZ.transformDefinition,getChartDefinitionFromContextCreation:NZ.getDefinitionFromContextCreation,sequence:30}),vR.add("treemap",{match:e=>"treemap"===e,createChart:(e,t,s)=>new kZ(e,t,s),getChartRuntime:function(e,t){const s=e.getDefinition(),o=lk(s,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:"treemap",data:{labels:o.labels,datasets:gN(s,o)},options:{...eF,layout:xk(0,o),plugins:{title:Gk(s,t),legend:{display:!1},tooltip:oL(s,o)}}},background:e.background||c}},validateChartDefinition:kZ.validateChartDefinition,transformDefinition:kZ.transformDefinition,getChartDefinitionFromContextCreation:kZ.getDefinitionFromContextCreation,sequence:100}),vR.add("calendar",{match:e=>"calendar"===e,createChart:(e,t,s)=>new _Z(e,t,s),getChartRuntime:(e,t)=>function(e,t){const s=e.getDefinition(),o=tk(s,e.dataSets,e.labelRange,t),{labels:i,datasets:n}=QM(s,o);return{chartJsConfig:{type:"calendar",data:{labels:i,datasets:n},options:{...eF,indexAxis:"x",layout:Rk(s,o),scales:LM(s,n),plugins:{title:Gk(s,t),legend:{display:!1},tooltip:jk(0,o),chartShowValuesPlugin:zk(s,o),chartColorScalePlugin:VM(s,o)},chartBackground:s.background||c}},background:e.background||c}}(e,t),validateChartDefinition:_Z.validateChartDefinition,transformDefinition:_Z.transformDefinition,getChartDefinitionFromContextCreation:_Z.getDefinitionFromContextCreation,sequence:110,dataSeriesLimit:1}),qF.add("line",{matcher:e=>"line"===e.type&&!e.stacked&&!e.fillArea,displayName:Cs("Line"),chartType:"line",chartSubtype:"line",subtypeDefinition:{stacked:!1,fillArea:!1},category:"line",preview:"o-spreadsheet-ChartPreview.LINE_CHART"}).add("stacked_line",{matcher:e=>"line"===e.type&&!e.fillArea&&!!e.stacked,displayName:Cs("Stacked Line"),chartType:"line",chartSubtype:"stacked_line",subtypeDefinition:{stacked:!0,fillArea:!1},category:"line",preview:"o-spreadsheet-ChartPreview.STACKED_LINE_CHART"}).add("area",{matcher:e=>"line"===e.type&&!e.stacked&&!!e.fillArea,displayName:Cs("Area"),chartType:"line",chartSubtype:"area",subtypeDefinition:{stacked:!1,fillArea:!0},category:"area",preview:"o-spreadsheet-ChartPreview.AREA_CHART"}).add("stacked_area",{matcher:e=>"line"===e.type&&e.stacked&&!!e.fillArea,displayName:Cs("Stacked Area"),chartType:"line",chartSubtype:"stacked_area",subtypeDefinition:{stacked:!0,fillArea:!0},category:"area",preview:"o-spreadsheet-ChartPreview.STACKED_AREA_CHART"}).add("scatter",{displayName:Cs("Scatter"),chartType:"scatter",chartSubtype:"scatter",category:"misc",preview:"o-spreadsheet-ChartPreview.SCATTER_CHART"}).add("column",{matcher:e=>"bar"===e.type&&!e.stacked&&!e.horizontal,displayName:Cs("Column"),chartType:"bar",chartSubtype:"column",subtypeDefinition:{stacked:!1,horizontal:!1},category:"column",preview:"o-spreadsheet-ChartPreview.COLUMN_CHART"}).add("stacked_column",{matcher:e=>"bar"===e.type&&e.stacked&&!e.horizontal,displayName:Cs("Stacked Column"),chartType:"bar",chartSubtype:"stacked_column",subtypeDefinition:{stacked:!0,horizontal:!1},category:"column",preview:"o-spreadsheet-ChartPreview.STACKED_COLUMN_CHART"}).add("bar",{matcher:e=>"bar"===e.type&&!e.stacked&&!!e.horizontal,displayName:Cs("Bar"),chartType:"bar",chartSubtype:"bar",subtypeDefinition:{horizontal:!0,stacked:!1},category:"bar",preview:"o-spreadsheet-ChartPreview.BAR_CHART"}).add("stacked_bar",{matcher:e=>"bar"===e.type&&e.stacked&&!!e.horizontal,displayName:Cs("Stacked Bar"),chartType:"bar",chartSubtype:"stacked_bar",subtypeDefinition:{horizontal:!0,stacked:!0},category:"bar",preview:"o-spreadsheet-ChartPreview.STACKED_BAR_CHART"}).add("combo",{displayName:Cs("Combo"),chartSubtype:"combo",chartType:"combo",category:"line",preview:"o-spreadsheet-ChartPreview.COMBO_CHART"}).add("pie",{matcher:e=>"pie"===e.type&&!e.isDoughnut,displayName:Cs("Pie"),chartSubtype:"pie",chartType:"pie",subtypeDefinition:{isDoughnut:!1},category:"pie",preview:"o-spreadsheet-ChartPreview.PIE_CHART"}).add("doughnut",{matcher:e=>"pie"===e.type&&!!e.isDoughnut,displayName:Cs("Doughnut"),chartSubtype:"doughnut",chartType:"pie",subtypeDefinition:{isDoughnut:!0},category:"pie",preview:"o-spreadsheet-ChartPreview.DOUGHNUT_CHART"}).add("gauge",{displayName:Cs("Gauge"),chartSubtype:"gauge",chartType:"gauge",category:"misc",preview:"o-spreadsheet-ChartPreview.GAUGE_CHART"}).add("scorecard",{displayName:Cs("Scorecard"),chartSubtype:"scorecard",chartType:"scorecard",category:"misc",preview:"o-spreadsheet-ChartPreview.SCORECARD_CHART"}).add("waterfall",{displayName:Cs("Waterfall"),chartSubtype:"waterfall",chartType:"waterfall",category:"misc",preview:"o-spreadsheet-ChartPreview.WATERFALL_CHART"}).add("pyramid",{displayName:Cs("Population Pyramid"),chartSubtype:"pyramid",chartType:"pyramid",category:"misc",preview:"o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART"}).add("radar",{matcher:e=>"radar"===e.type&&!e.fillArea,displayName:Cs("Radar"),chartSubtype:"radar",chartType:"radar",subtypeDefinition:{fillArea:!1},category:"misc",preview:"o-spreadsheet-ChartPreview.RADAR_CHART"}).add("filled_radar",{matcher:e=>"radar"===e.type&&!!e.fillArea,displayName:Cs("Filled Radar"),chartType:"radar",chartSubtype:"filled_radar",subtypeDefinition:{fillArea:!0},category:"misc",preview:"o-spreadsheet-ChartPreview.FILLED_RADAR_CHART"}).add("geo",{displayName:Cs("Geo Chart"),chartSubtype:"geo",chartType:"geo",category:"misc",preview:"o-spreadsheet-ChartPreview.GEO_CHART"}).add("funnel",{displayName:Cs("Funnel"),chartSubtype:"funnel",chartType:"funnel",category:"misc",preview:"o-spreadsheet-ChartPreview.FUNNEL_CHART"}).add("sunburst",{matcher:e=>"sunburst"===e.type,displayName:Cs("Sunburst"),chartSubtype:"sunburst",chartType:"sunburst",category:"hierarchical",preview:"o-spreadsheet-ChartPreview.SUNBURST_CHART"}).add("treemap",{matcher:e=>"treemap"===e.type,displayName:Cs("Tree Map"),chartType:"treemap",chartSubtype:"treemap",category:"hierarchical",preview:"o-spreadsheet-ChartPreview.TREE_MAP_CHART"}).add("calendar",{displayName:Cs("Calendar"),chartSubtype:"calendar",chartType:"calendar",category:"misc",preview:"o-spreadsheet-ChartPreview.CALENDAR_CHART"});class LZ extends Eq{copy(e){}}hP.figureHandlers.add("chart",class extends LZ{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);if("chart"!==s.tag)return;const o={...s},i=this.getters.getChartFromFigureId(e.figureId);if(!i)throw new Error(`No chart for the given id: ${e.figureId}`);const n=i.copyInSheetId(t);return{figureId:e.figureId,copiedFigure:o,copiedChart:n}}getPasteTarget(e,t,s,o){return{zones:[],figureId:(new Tr).smallUuid(),sheetId:e}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=e.sheetId,{width:r,height:a}=t.copiedFigure,l=t.copiedChart.copyInSheetId(n),c=this.getters.getMaxAnchorOffset(n,a,r);let{left:h,top:d}=o[0];const u={x:0,y:0};h>c.col&&(h=c.col,u.x=c.offset.x),d>c.row&&(d=c.row,u.y=c.offset.y),this.dispatch("CREATE_CHART",{figureId:i,chartId:(new Tr).smallUuid(),sheetId:n,definition:l.getDefinition(),col:h,row:d,offset:u,size:{height:a,width:r}}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}).add("image",class extends LZ{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);const o={...s};if("image"!==s.tag)return;const i=he(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:o,copiedImage:i,sheetId:t}}getPasteTarget(e,t,s,o){return{sheetId:e,zones:[],figureId:(new Tr).smallUuid()}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=this.getters.getActiveSheetId(),{width:r,height:a}=t.copiedFigure,l=he(t.copiedImage),c=this.getters.getMaxAnchorOffset(n,a,r);let{left:h,top:d}=o[0];const u={x:0,y:0};h>c.col&&(h=c.col,u.x=c.offset.x),d>c.row&&(d=c.row,u.y=c.offset.y),this.dispatch("CREATE_IMAGE",{figureId:i,sheetId:n,col:h,row:d,offset:u,size:{height:a,width:r},definition:l}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}).add("carousel",class extends LZ{copy(e){const t=e.sheetId,s=this.getters.getFigure(t,e.figureId);if(!s)throw new Error(`No figure for the given id: ${e.figureId}`);if("carousel"!==s.tag)return;const o={...s},i=this.getters.getCarousel(e.figureId),n={};for(const e of i.items)if("chart"===e.type){const s=this.getters.getChart(e.chartId);if(!s)throw new Error(`No chart for the given id: ${e.chartId}`);n[e.chartId]=s.copyInSheetId(t)}return{figureId:e.figureId,copiedFigure:o,copiedCarousel:i,copiedCharts:n,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:(new Tr).smallUuid(),sheetId:e}}paste(e,t,s){if(!e.figureId)return;const{zones:o,figureId:i}=e,n=e.sheetId,{width:r,height:a}=t.copiedFigure,l=this.getters.getMaxAnchorOffset(n,a,r);let{left:c,top:h}=o[0];const d={x:0,y:0};c>l.col&&(c=l.col,d.x=l.offset.x),h>l.row&&(h=l.row,d.y=l.offset.y),this.dispatch("CREATE_CAROUSEL",{figureId:i,sheetId:n,definition:{items:[]},col:c,row:h,offset:d,size:{height:a,width:r}});const u=new Tr,g=he(t.copiedCarousel.items);for(const e of g){if("chart"!==e.type)continue;const s=t.copiedCharts[e.chartId],o=u.smallUuid(),r=s.copyInSheetId(n).getDefinition();this.dispatch("CREATE_CHART",{figureId:i,chartId:o,sheetId:n,definition:r}),e.chartId=o}this.dispatch("UPDATE_CAROUSEL",{sheetId:n,figureId:i,definition:{...t.copiedCarousel,items:g}}),s.isCutOperation&&this.dispatch("DELETE_FIGURE",{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{figureId:i})}isPasteAllowed(e,t,s,o){return 0===t.length?"EmptyTarget":void 0!==o?.pasteOption?"WrongFigurePasteOption":"Success"}}),hP.cellHandlers.add("dataValidation",class extends xq{uuidGenerator=new Tr;queuedChanges={};copy(e){const{rowsIndexes:t,columnsIndexes:s}=e,o=e.sheetId,i=[];for(const e of t){const t=[];for(const i of s){const s={sheetId:o,col:i,row:e},n=this.getters.getValidationRuleForCell(s);t.push({position:s,rule:n})}i.push(t)}return{dvRules:i}}paste(e,t,s){if(this.queuedChanges={},s.pasteOption)return;const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t):this.pasteFromCopy(i,o,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,s){const o=t[0];this.pasteZone(e,o.left,o.top,s.dvRules,{isCutOperation:!0})}pasteZone(e,t,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){const r={col:t+o,row:s+n,sheetId:e};this.pasteDataValidation(a,r,i?.isCutOperation)}}pasteDataValidation(e,t,s){if(e){const o=Jt(t),i=Jt(e.position),n=e.rule;if(!n){const e=this.getters.getValidationRuleForCell(t);return void(e&&this.adaptDataValidationRule(t.sheetId,e,[],[o]))}const r=[];if(s&&r.push(i),e.position.sheetId===t.sheetId){const s=this.getDataValidationRuleToCopyTo(t.sheetId,n,!1);this.adaptDataValidationRule(e.position.sheetId,s,[o],r)}else{const s=this.getters.getValidationRuleForCell(e.position);s&&this.adaptDataValidationRule(e.position.sheetId,s,[],r);const i=this.getDataValidationRuleToCopyTo(t.sheetId,n);this.adaptDataValidationRule(t.sheetId,i,[o],[])}}}getDataValidationRuleToCopyTo(e,t,s=!0){let o=this.getters.getDataValidationRules(e).find(e=>Le(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking);const i=this.queuedChanges[e];return!o&&i&&(o=i.find(e=>Le(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),o||{...t,id:s?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,s,o){this.queuedChanges[e]||(this.queuedChanges[e]=[]);const i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...s),i.toRemove.push(...o)):this.queuedChanges[e].push({toAdd:s,toRemove:o,rule:t})}executeQueuedChanges(){for(const e in this.queuedChanges)for(const{toAdd:t,toRemove:s,rule:o}of this.queuedChanges[e]){const i=o.ranges.map(e=>e.zone),n=yt(i,s),r=yt([...n,...t],[]);0!==r.length?this.dispatch("ADD_DATA_VALIDATION_RULE",{rule:{id:o.id,criterion:o.criterion,isBlocking:o.isBlocking},ranges:r.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e}):this.dispatch("REMOVE_DATA_VALIDATION_RULE",{sheetId:e,id:o.id})}}}).add("cell",Rq).add("sheet",class extends xq{isPasteAllowed(e,t,s,o){if(!("cells"in s))return"Success";const{xSplit:i,ySplit:n}=this.getters.getPaneDivisions(e);return os(oP(t,s.cells),i,n)?"FrozenPaneOverlap":"Success"}}).add("merge",class extends xq{copy(e){const t=this.getters.getActiveSheetId(),{rowsIndexes:s,columnsIndexes:o}=e,i=[];for(const e of s){const s=[];for(const i of o){const o={col:i,row:e,sheetId:t};s.push(this.getters.getMerge(o))}i.push(s)}return{merges:i,sheetId:t}}paste(e,t,s){if(s.isCutOperation){const e=t.merges.flat().filter(De);this.dispatch("REMOVE_MERGE",{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,s)}pasteZone(e,t,s,o){for(const[i,n]of o.entries())for(const[o,r]of n.entries()){const n={col:t+o,row:s+i,sheetId:e};this.pasteMerge(r,n)}}pasteMerge(e,t){if(!e)return;if(this.getters.isInMerge(t))return;const{sheetId:s,col:o,row:i}=t;this.dispatch("ADD_MERGE",{sheetId:s,force:!0,target:[{left:o,top:i,right:o+e.right-e.left,bottom:i+e.bottom-e.top}]})}}).add("table",class extends xq{copy(e,t,s="copyPaste"){const o=e.sheetId,{rowsIndexes:i,columnsIndexes:n,zones:r}=e,a=new Set,l=[];for(const e of i){const c=[];l.push(c);for(const l of n){const n={col:l,row:e,sheetId:o},h=this.getters.getTable(n);if(!h){c.push({});continue}const d=this.getters.getCoreTable(n),u=d?.range.zone;let g;if(!a.has(h.id)&&d&&u&&r.some(e=>Wt(u,e))){a.add(h.id);let{numberOfRows:e}=$t(u);for(let s=u.top;s<=u.bottom;s++)t||i.includes(s)||e--;const s=d.range,o=this.getters.extendRange(d.range,"ROW",s.zone.top+e-1-s.zone.bottom);g={range:this.getters.getRangeData(o),config:d.config,type:d.type}}"shiftCells"!==s&&c.push({table:g,style:this.getTableStyleToCopy(n),isWholeTableCopied:a.has(h.id)})}}return{tableCells:l,sheetId:e.sheetId}}getTableStyleToCopy(e){const t=this.getters.getCellTableStyle(e),s=this.getters.getCellStyle(e),o=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Ue(s)},border:{...o,...Ue(i)}}}paste(e,t,s){const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t,s):this.pasteFromCopy(i,o,t.tableCells,s)}pasteFromCut(e,t,s,o){for(const e of s.tableCells)for(const t of e)t.table&&this.dispatch("REMOVE_TABLE",{sheetId:s.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});const i=t[0];this.pasteZone(e,i.left,i.top,s.tableCells,o)}pasteZone(e,t,s,o,i){for(let n=0;n<o.length;n++){const r=o[n];for(let o=0;o<r.length;o++){const a=r[o];if(!a)continue;const l={col:t+o,row:s+n,sheetId:e};this.pasteTableCell(e,a,l,i)}}if(1===o.length)for(let i=0;i<o[0].length;i++)this.dispatch("AUTOFILL_TABLE_COLUMN",{col:t+i,row:s,sheetId:e})}pasteTableCell(e,t,s,o){if(t.table&&!o?.pasteOption){const{range:o}=t.table,i=$t(this.getters.getRangeFromRangeData(o).zone),n={left:s.col,top:s.row,right:s.col+i.numberOfCols-1,bottom:s.row+i.numberOfRows-1};this.dispatch("CREATE_TABLE",{sheetId:s.sheetId,ranges:[this.getters.getRangeDataFromZone(e,n)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(s)||"asValue"===o?.pasteOption||(o?.pasteOption||t.isWholeTableCopied)&&"onlyFormat"!==o?.pasteOption||(t.style?.style&&this.dispatch("UPDATE_CELL",{...s,style:t.style.style}),t.style?.border&&this.dispatch("SET_BORDER",{...s,border:t.style.border}))}}).add("conditionalFormat",class extends xq{uuidGenerator=new Tr;queuedChanges={};copy(e){if(!e.zones.length)return;const{rowsIndexes:t,columnsIndexes:s}=e,o=e.sheetId,i=[];for(const e of t){const t=[];for(const i of s){const s=Array.from(this.getters.getRulesByCell(o,i,e));t.push({position:{col:i,row:e,sheetId:o},rules:s})}i.push(t)}return{cfRules:i}}paste(e,t,s){if(this.queuedChanges={},"asValue"===s.pasteOption)return;const o=e.zones,i=e.sheetId;s.isCutOperation?this.pasteFromCut(i,o,t):this.pasteFromCopy(i,o,t.cfRules,s),this.executeQueuedChanges()}pasteFromCut(e,t,s){const o=t[0];this.pasteZone(e,o.left,o.top,s.cfRules,{isCutOperation:!0})}pasteZone(e,t,s,o,i){for(const[n,r]of o.entries())for(const[o,a]of r.entries()){const r={col:t+o,row:s+n,sheetId:e};this.pasteCf(a,r,i?.isCutOperation)}}pasteCf(e,t,s){if(e?.rules&&e.rules.length>0){const o=Jt(e.position),i=Jt(t);for(const n of e.rules){const r=[];if(s&&r.push(o),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,n,[i],r);else{this.adaptCFRules(e.position.sheetId,n,[],r);const s=this.getCFToCopyTo(t.sheetId,n);this.adaptCFRules(t.sheetId,s,[i],[])}}}}adaptCFRules(e,t,s,o){this.queuedChanges[e]||(this.queuedChanges[e]=[]);const i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...s),i.toRemove.push(...o)):this.queuedChanges[e].push({toAdd:s,toRemove:o,cf:t})}executeQueuedChanges(){for(const e in this.queuedChanges)for(const{toAdd:t,toRemove:s,cf:o}of this.queuedChanges[e]){const i=this.getters.getAdaptedCfRanges(e,o,t,s);i&&(0!==i.length?this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:o.id,rule:o.rule,stopIfTrue:o.stopIfTrue},ranges:i,sheetId:e}):this.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:o.id,sheetId:e}))}}getCFToCopyTo(e,t){let s=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&Le(e.rule,t.rule));const o=this.queuedChanges[e];return!s&&o&&(s=o.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&Le(e.cf.rule,t.rule))?.cf),s||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}}).add("references",class extends xq{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,s){if(s.isCutOperation){const s=e.zones[0];this.dispatch("MOVE_RANGES",{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:s.left,row:s.top})}}}).add("border",class extends xq{copy(e){const t=e.sheetId;if(0===e.zones.length)return;const s=[];let o=0;for(const i of ve(e.columnsIndexes)){let n=0;for(const r of ve(e.rowsIndexes)){const e={left:i[0],right:i[i.length-1],top:r[0],bottom:r[r.length-1]};s.push(...this.getters.getBorders(t,e).map(({zone:t,style:s})=>({zone:{left:t.left-e.left+o,right:t.right&&t.right-e.left+o,top:t.top-e.top+n,bottom:t.bottom&&t.bottom-e.top+n},style:s}))),n+=r.length}o+=i.length}return{borders:s,width:e.columnsIndexes.length,height:e.rowsIndexes.length}}paste(e,t,s){const o=e.sheetId;if("asValue"===s.pasteOption)return;const i=e.zones;if(s.isCutOperation){const{left:e,top:s}=i[0];this.pasteBorderZone(o,e,s,t.borders)}else for(const e of i)for(const s of sP(e,t.width,t.height))this.pasteBorderZone(o,s.left,s.top,t.borders)}pasteBorderZone(e,t,s,o){for(const i of o){const o={left:i.zone.left+t,right:i.zone.right&&i.zone.right+t||i.zone.left+t,top:i.zone.top+s,bottom:i.zone.bottom&&i.zone.bottom+s||i.zone.top+s};for(const[t,s]of this.getOptimalBorderCommands(i.style))s&&this.dispatch("SET_ZONE_BORDERS",{sheetId:e,target:[o],border:{position:t,...s}})}}getOptimalBorderCommands(e){const t=Le(e.horizontal,e.vertical),s=Le(e.left,e.right,e.top,e.bottom);return t&&s&&Le(e.horizontal,e.left)?[["all",e.top]]:t&&s?[["hv",e.horizontal],["external",e.top]]:s?[["h",e.horizontal],["v",e.vertical],["external",e.top]]:t?[["hv",e.horizontal],["top",e.top],["bottom",e.bottom],["left",e.left],["right",e.right]]:[["h",e.horizontal],["v",e.vertical],["top",e.top],["bottom",e.bottom],["left",e.left],["right",e.right]]}}).add("style",class extends xq{copy(e){const t=e.sheetId;if(0===e.zones.length)return;const s=[];let o=0;for(const i of ve(e.columnsIndexes)){let n=0;for(const r of ve(e.rowsIndexes)){const e={left:i[0],right:i[i.length-1],top:r[0],bottom:r[r.length-1]};s.push(...this.getters.getZoneStyles(t,e).map(t=>({zone:{left:t.zone.left-e.left+o,right:t.zone.right&&t.zone.right-e.left+o,top:t.zone.top-e.top+n,bottom:t.zone.bottom&&t.zone.bottom-e.top+n},style:t.style}))),n+=r.length}o+=i.length}return{styles:s,width:e.columnsIndexes.length,height:e.rowsIndexes.length}}paste(e,t,s){const o=e.sheetId;if("asValue"===s.pasteOption)return;const i=e.zones;if(s.isCutOperation){const{left:e,top:s}=i[0];this.pasteStyleZone(o,e,s,t.styles)}else for(const e of i)for(const s of sP(e,t.width,t.height))this.pasteStyleZone(o,s.left,s.top,t.styles)}pasteStyleZone(e,t,s,o){for(const i of o){const o={left:i.zone.left+t,right:i.zone.right&&i.zone.right+t||i.zone.left+t,top:i.zone.top+s,bottom:i.zone.bottom&&i.zone.bottom+s||i.zone.top+s};this.dispatch("SET_FORMATTING",{sheetId:e,target:[o],style:i.style})}}});const VZ={},zZ={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:O,HEADER_WIDTH:F,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:P,SCROLLBAR_WIDTH:15},HZ={autoCompleteProviders:PV,autofillModifiersRegistry:DF,autofillRulesRegistry:OF,cellMenuRegistry:sB,colMenuRegistry:dG,errorTypes:Es,linkMenuRegistry:Rz,functionRegistry:zf,featurePluginRegistry:mP,iconsOnCellRegistry:AO,statefulUIPluginRegistry:fP,coreViewsPluginRegistry:vP,corePluginRegistry:pP,rowMenuRegistry:vG,sidePanelRegistry:hq,figureRegistry:oV,chartSidePanelComponentRegistry:h$,chartComponentRegistry:BL,chartRegistry:vR,chartSubtypeRegistry:qF,topbarMenuRegistry:Mq,topbarComponentRegistry:$q,clickableCellRegistry:_q,otRegistry:Wx,inverseCommandRegistry:OR,urlRegistry:uv,cellPopoverRegistry:rV,numberFormatMenuRegistry:Oq,repeatLocalCommandTransformRegistry:GF,repeatCommandTransformRegistry:BF,clipboardHandlersRegistries:hP,pivotRegistry:AD,pivotTimeAdapterRegistry:Qg,pivotSidePanelRegistry:Y$,pivotNormalizationValueRegistry:Op,supportedPivotPositionalFormulaRegistry:yq,pivotToFunctionValueRegistry:Fp,migrationStepRegistry:T_,chartJsExtensionRegistry:Hv},UZ={arg:us,isEvaluationError:Co,toBoolean:Po,toJsDate:Mo,toNumber:Eo,toString:Do,toNormalizedPivotValue:Tp,toFunctionPivotValue:_p,toXC:St,toZone:_t,toUnboundedZone:At,toCartesian:bt,numberToLetters:lt,lettersToNumber:ct,UuidGenerator:Tr,formatValue:zi,createCurrencyFormat:en,ColorGenerator:yb,computeTextWidth:IS,createEmptyWorkbookData:V_,createEmptySheet:L_,createEmptyExcelSheet:z_,rgbaToHex:eb,colorToRGBA:tb,positionToZone:Jt,isDefined:De,isMatrix:Ns,lazy:Me,genericRepeat:Wq,createAction:Cv,createActions:Sv,transformRangeData:ls,deepEquals:Le,overlap:Bt,union:Vt,isInside:Gt,deepCopy:he,expandZoneOnInsertion:Mt,reduceZoneOnDeletion:Lt,unquote:ue,getMaxObjectId:Sp,getFunctionsFromTokens:hv,getFirstPivotFunction:EF,getNumberOfPivotFunctions:xF,parseDimension:Ip,isDateOrDatetimeField:wp,makeFieldProposal:bq,insertTokenAfterArgSeparator:function(e,t){let s=e.end;const o=e.end;"ARG_SEPARATOR"!==e.type&&(s=e.start),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)},insertTokenAfterLeftParenthesis:function(e,t){let s=e.end;const o=e.end;"LEFT_PAREN"!==e.type&&(s=e.start),this.composer.changeComposerCursorSelection(s,o),this.composer.replaceComposerCursorSelection(t)},mergeContiguousZones:ns,getPivotHighlights:N$,pivotTimeAdapter:ep,UNDO_REDO_PIVOT_COMMANDS:AF,createPivotFormula:Rp,areDomainArgsFieldsValid:xp,splitReference:yr,sanitizeSheetName:pe,getUniqueText:rt,isNumber:mo,isDateTime:Ks,createCustomFields:Vp,schemeToColorScale:w_,isDateTimeFormat:ji,jsDateToNumber:so,numberToJsDate:eo,DateTime:Ls,parseFormat:Ai,isFormula:at},BZ={isMarkdownLink:Ie,parseMarkdownLink:xe,markdownLink:Ee,openLink:vv,urlRepresentation:fv},GZ={Checkbox:hz,Section:YV,RoundColorPicker:XV,ChartDataSeries:SW,ChartErrorSection:yW,ChartLabelRange:CW,ChartTitle:xW,ChartPanel:p$,ChartFigure:tV,ChartJsComponent:xN,ClickableCellSortIcon:Cq,ZoomableChartJsComponent:ML,Grid:vq,GridOverlay:BG,ScorecardChart:ZN,GaugeChartComponent:HL,LineConfigPanel:YW,BarConfigPanel:wW,PieChartDesignPanel:JW,GenericChartConfigPanel:IW,ChartWithAxisDesignPanel:NW,GenericZoomableChartDesignPanel:kW,LineChartDesignPanel:XW,GaugeChartConfigPanel:GW,GaugeChartDesignPanel:WW,ScorecardChartConfigPanel:t$,ScorecardChartDesignPanel:s$,GeoChartDesignPanel:ZW,RadarChartDesignPanel:QW,WaterfallChartDesignPanel:c$,ComboChartDesignPanel:UW,FunnelChartDesignPanel:BW,SunburstChartDesignPanel:o$,TreeMapChartDesignPanel:l$,ChartTypePicker:u$,FigureComponent:iV,MenuPopover:JL,Popover:jL,SelectionInput:iz,ValidationMessages:MG,AddDimensionButton:z$,PivotDimensionGranularity:U$,PivotDimensionOrder:B$,PivotDimension:H$,PivotLayoutConfigurator:$$,PivotHTMLRenderer:wq,PivotDeferUpdate:k$,PivotTitleSection:q$,CogWheelMenu:fW,TextInput:hW,SidePanelCollapsible:gV,RadioSelection:TW,GeoChartRegionSelectSection:$W,ChartDashboardMenu:QL,FullScreenFigure:Iq,NumberInput:OW,TopBar:xZ,Composer:_V},WZ={useDragAndDropListItems:KV,useHighlights:v$,useHighlightsOnHover:f$},$Z={useStoreProvider:Rv,DependencyContainer:wv,CellPopoverStore:aV,ComposerFocusStore:zv,CellComposerStore:RG,FindAndReplaceStore:T$,HighlightStore:NV,DelayedHoveredCellStore:nV,HoveredTableStore:zG,ModelStore:Fv,NotificationStore:kV,RendererStore:kv,SelectionInputStore:oz,SpreadsheetStore:Lv,useStore:Tv,useLocalStore:Av,SidePanelStore:pq,PivotSidePanelStore:Z$,PivotMeasureDisplayPanelStore:P$,ClientFocusStore:SG,GridRenderer:XG};const qZ={DEFAULT_LOCALE:gi,HIGHLIGHT_COLOR:o,PIVOT_TABLE_CONFIG:te,ChartTerms:Bg,FIGURE_ID_SPLITTER:W,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2},ZZ={...EL,...rL};e.AbstractCellClipboardHandler=xq,e.AbstractChart=zO,e.AbstractFigureClipboardHandler=LZ,e.CellErrorType=ws,e.ClientDisconnectedError=_R,e.CorePlugin=U_,e.CoreViewPlugin=UD,e.DEFAULT_LOCALE=gi,e.DEFAULT_LOCALES=ui,e.DispatchResult=Lr,e.EvaluationError=xs,e.LocalTransportService=Bx,e.Model=class extends Iv{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},s=[],o=new Tr,i=!1){const n=performance.now();console.debug("##### Model creation #####"),super(),bs===fs&&Ss===vs&&(Ss=()=>!0),s=N_(e,s);const r=F_(e,i);this.state=new CP,this.uuidGenerator=o,this.config=this.setupConfig(t),this.session=this.setupSession(r.revisionId),this.coreGetters={},this.range=new bP(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.adaptFormulaStringDependencies=this.range.adaptFormulaStringDependencies.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.getters={isReadonly:()=>"readonly"===this.config.mode||"dashboard"===this.config.mode,isDashboard:()=>"dashboard"===this.config.mode},this.selection=new yP(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(const e of pP.getAll())this.setupCorePlugin(e,r);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(s);for(const e of vP.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(const e of fP.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(const e of mP.getAll()){const t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.joinSession(),t.snapshotRequested||e["[Content_Types].xml"]&&!this.getters.isReadonly()){const e=performance.now();console.debug("Snapshot requested"),this.session.snapshot(this.exportData()),console.debug("Snapshot taken in",performance.now()-e,"ms")}console.debug("Model created in",performance.now()-n,"ms"),console.debug("######")}joinSession(){this.session.join(this.config.client)}async leaveSession(){const e=this.getters.isReadonly()?void 0:Me(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(const s of e.getters){if(!(s in t))throw new Error(`Invalid getter name: ${s} for plugin ${t.constructor}`);if(s in this.getters)throw new Error(`Getter "${s}" is already defined.`);this.getters[s]=t[s].bind(t)}for(const s of e.layers)this.renderers[s]||(this.renderers[s]=[]),this.renderers[s].push(t);return t}setupCoreViewPlugin(e){const t=new e(this.coreViewPluginConfig);for(const s of e.getters){if(!(s in t))throw new Error(`Invalid getter name: ${s} for plugin ${t.constructor}`);if(s in this.getters)throw new Error(`Getter "${s}" is already defined.`);this.getters[s]=t[s].bind(t)}return t}setupCorePlugin(e,t){const s=new e(this.corePluginConfig);for(const t of e.getters){if(!(t in s))throw new Error(`Invalid getter name: ${t} for plugin ${s.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=s[t].bind(s)}s.import(t),this.corePlugins.push(s),this.coreHandlers.push(s),this.handlers.push(s)}onRemoteRevisionReceived({commands:e}){for(const t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new DR(HR({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{this.checkDispatchAllowed(e).isSuccessful?(this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1):this.dispatchToHandlers(this.coreHandlers,{type:"UNDO",commands:[e]})}}),this.config.transportService,e)}setupSessionEvents(){this.session.on("remote-revision-received",this,this.onRemoteRevisionReceived),this.session.on("revision-undone",this,({commands:e})=>{this.dispatchFromCorePlugin("UNDO",{commands:e}),this.finalize()}),this.session.on("revision-redone",this,({commands:e})=>{this.dispatchFromCorePlugin("REDO",{commands:e}),this.finalize()}),this.session.on("unexpected-revision-id",this,()=>this.trigger("unexpected-revision-id")),this.session.on("collaborative-event-received",this,()=>{this.trigger("update")})}setupConfig(e){const t=e.client||{id:this.uuidGenerator.smallUuid(),name:Cs("Anonymous").toString()},s=e.transportService||new Bx,o="readonly"===e.mode||"dashboard"===e.mode;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:o?new Gx(s):s,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),raiseBlockingErrorUI:e=>this.trigger("raise-error-ui",{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){const t=e.loadLocales||(()=>Promise.resolve(ui));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,custom:this.config.custom,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){const t=kr(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>"Success"!==e)?new Lr(t.flat()):Lr.Success}checkDispatchAllowedCoreCommand(e){const t=this.corePlugins.map(t=>t.allowDispatch(e));return t.push(this.range.allowDispatch(e)),t}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0,this.trigger("command-finalized")}canDispatch=(e,t)=>this.checkDispatchAllowed(RM(e,t));dispatch=(e,t)=>{const s=RM(e,t),o=this.status;if(this.getters.isReadonly()&&(i=s,!Mr.has(i.type)))return new Lr("Readonly");var i;if(!this.session.canApplyOptimisticUpdate())return new Lr("WaitingSessionConfirmation");switch(o){case 0:const t=this.checkDispatchAllowed(s);if(!t.isSuccessful)return this.trigger("update"),t;this.status=1;const{changes:o,commands:i}=this.state.recordChanges(()=>{const t=performance.now();kr(s)&&this.state.addCommand(s),this.dispatchToHandlers(this.handlers,s),this.finalize();const o=performance.now()-t;o>5&&console.debug(e,o,"ms")});this.session.save(s,i,o),this.status=0,this.trigger("update");break;case 1:if(kr(s)){const e=this.checkDispatchAllowed(s);if(!e.isSuccessful)return e;this.state.addCommand(s)}this.dispatchToHandlers(this.handlers,s);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(kr(s))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,s)}return Lr.Success};dispatchFromCorePlugin=(e,t)=>{const s=RM(e,t),o=this.status;this.status=2;const i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,s),this.status=o,Lr.Success};dispatchToHandlers(e,t){const s=kr(t);for(const o of e)!s&&o instanceof U_||o.beforeHandle(t);for(const o of e)!s&&o instanceof U_||o.handle(t);this.trigger("command-dispatched",t)}drawLayer(e,t){const s=this.renderers[t];if(s)for(const o of s)e.ctx.save(),o.drawLayer(e,t),e.ctx.restore()}exportData(){let e=V_();for(const t of this.handlers)t instanceof U_&&t.export(e);return e.revisionId=this.session.getRevisionId()||G,e=he(e),e}updateMode(e){this.config.mode=e,this.trigger("update")}async exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={...V_(),sheets:[z_(O_,"Sheet1")]};for(const t of this.handlers)t instanceof Hr&&await t.exportForExcel(e);return e=he(e),wM(e)}},e.PivotRuntimeDefinition=Q_,e.Registry=Jg,e.Revision=AR,e.SPREADSHEET_DIMENSIONS=zZ,e.Spreadsheet=TZ,e.SpreadsheetPivotTable=fD,e.UIPlugin=Ur,e.__info__=VZ,e.addFunction=function e(t,s){return zf.add(t,s),{addFunction:(t,s)=>e(t,s)}},e.addRenderingLayer=function(e,t){if(Mv[e])throw new Error(`Layer ${e} already exists`);Mv[e]=t},e.astToFormula=yF,e.categories=Hf,e.chartHelpers=ZZ,e.compile=zx,e.compileTokens=Hx,e.components=GZ,e.constants=qZ,e.convertAstNodes=iv,e.coreTypes=Nr,e.createAutocompleteArgumentsProvider=Tq,e.findCellInNewZone=Kt,e.functionCache=Vx,e.getCaretDownSvg=$R,e.getCaretUpSvg=qR,e.helpers=UZ,e.hooks=WZ,e.invalidateCFEvaluationCommands=Or,e.invalidateChartEvaluationCommands=_r,e.invalidateDependenciesCommands=Dr,e.invalidateEvaluationCommands=Ar,e.iterateAstNodes=nv,e.links=BZ,e.load=F_,e.parse=sv,e.parseTokens=ov,e.readonlyAllowedCommands=Mr,e.registries=HZ,e.setDefaultSheetViewSize=function(e){K=e},e.setTranslationMethod=function(e,t=()=>!0){bs=e,Ss=t},e.stores=$Z,e.tokenColors=ae,e.tokenize=Kc,VZ.version="19.2.0-alpha.1",VZ.date="2025-12-26T10:20:28.360Z",VZ.hash="3296c7e"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|