@deephaven/code-studio 0.38.1-beta.2 → 0.38.1-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
- import{C as r,G as ee,A as v,I as sm,B as z,F as Y,J as jc,H as de,K as ge,L as Pa,M as vs,N as Ye,O as Re,P as Hc,Q as st,S as sr,T as im,U as om,V as lm,W as am,X as he,R as al,Y as rd,Z as qe,_ as ir,$ as rm,a0 as dm,a1 as Bc,a2 as Oe,a3 as ja,E as cm,D as Wt,a4 as Pl,a5 as Uc,a6 as or,a7 as hm,a8 as Rn,a9 as um,aa as mm,ab as gm,ac as pm,ad as Ha,ae as fm,af as Cm,ag as bm,ah as dd,ai as Sm,aj as cd,ak as wm,al as vm,am as Tm,an as Em,ao as ym,ap as Rm,aq as St,ar as Vc,as as xm,at as $c,au as Dm,av as Wc,aw as Im,ax as Fm,ay as Nm,az as km,aA as hd,aB as Mm}from"./vendor-4a7e2c7c.js";import{P as ye,s as I,T as jl,B,a as N,S as We,M as ve,K as xe,G as Kn,b as en,C as ie,c as nn,D as Vn,d as Di,e as Hl,f as ot,g as ho,I as yi,U as Lm,h as be,i as F,j as Xs,F as $n,k as gn,u as lr,E as ke,l as k,m as Pn,n as Ts,o as nl,p as ct,q as Ke,r as dt,t as Bl,v as Om,O as Bn,w as Am,x as hn,y as rn,z as _m,A as Pm,R as Ul,H as Wn,J as Vl,L as Gc,N as zc,Q as jm,V as Hm,W as ud,X as ze,Y as md,Z as Kc,_ as ar,$ as gd,a0 as oo,a1 as Yc,a2 as Bm,a3 as qc,a4 as Um,a5 as sn,a6 as Vm,a7 as $m,a8 as Wm,a9 as Gm,aa as zm,ab as Km,ac as Ym,ad as qm,ae as Xm,af as Zm,ag as Qm,ah as Jm}from"./useConnection-2334ddd0.js";import{e as Gn,l as yn,K as tn,a as pd,R as eg,b as ps,W as tg}from"./monaco-6eaf53f7.js";import{v as Ba,d as ng,a as Xc,b as rr,L as In,c as uo,e as Un,f as Zc,g as ne,h as fd,i as sg,j as ig,k as og,l as lg,m as Gt,n as ws,o as Qc,p as zn,q as $l,r as Ri,s as ag,t as rg,u as Cd,w as rl,x as bd,y as Jc,z as dg,A as mo,B as eh,C as cg,D as hg,T as Je,E as dr,F as cr,G as dl,H as Mn,I as ug,J as mg,K as gg,M as pg,N as fg,O as hr,P as Es,Q as Sd,R as go,S as ur,U as mr,V as th,W as Cg,X as Wl,Y as bg,Z as cl,_ as Sg,$ as gr,a0 as nh,a1 as Ws,a2 as wg,a3 as vg,a4 as Tg,a5 as Eg,a6 as yg,a7 as Rg,a8 as wd,a9 as pa,aa as xg,ab as Dg,ac as Ig,ad as Gl,ae as zl,af as Fg,ag as Ng,ah as Kl,ai as sh,aj as kg,ak as Mg,al as Lg,am as ih,an as Og,ao as Ag,ap as _g,aq as Pg,ar as jg,as as Hg,at as Bg,au as Ug,av as Vg,aw as $g,ax as Wg,ay as Gg,az as zg,aA as oh,aB as Kg,aC as Ua,aD as Va,aE as Yg,aF as qg,aG as Xg,aH as Zg,aI as Qg,aJ as Jg,aK as ep,aL as tp,aM as np,aN as sp,aO as ip,aP as op,aQ as lp,aR as vd,aS as ap,aT as rp,aU as dp}from"./index-77c2e65e.js";import{P as hl,b as cp,h as hp,p as up,o as mp,s as gp,t as pp,c as fa}from"./plotly-788bff8c.js";import"./helpers-042e6b4d.js";class pr{static isDark(e){const t=document.createElement("div");t.style.display="none",t.style.color=e;const n=getComputedStyle(document.body.appendChild(t)).color,s=n.match(/\d+/g);let i=[];if(s)i=s.map(l=>parseInt(l,10));else throw new Error(`Invalid color received. Got ${n}`);return document.body.removeChild(t),pr.getBrightness(i)<125}static getBrightness(e){return Math.round((e[0]*299+e[1]*587+e[2]*114)/1e3)}}const lh=pr,fp="table_",Td="column_",Cp=new Set(["in","not","i","ii","k"]),bp=new Set(["abstract","continue","for","new","switch","assert","default","if","package","synchronized","boolean","do","goto","private","this","break","double","implements","protected","throw","byte","else","import","public","throws","case","enum","instanceof","return","transient","catch","extends","int","short","try","char","final","interface","static","void","class","finally","long","strictfp","volatile","const","float","native","super","while","null","true","false"]),Sp=/[^a-zA-Z0-9_$+@-]/g,wp=/[^A-Za-z0-9_$]/g;class Ps{static legalize=(e,t,n,s,i)=>{let o=e.trim().replace(/[- ]/g,"_");return s&&(Cp.has(o)||bp.has(o))&&(o=t+o),o=o.replace(n,""),o||(o=t+i),Number.isNaN(Number(o.charAt(0)))||(o=t+o),o};static legalizeTableName=e=>Ps.legalize(e,fp,Sp,!1,0);static legalizeColumnNames=e=>{const t=[];return e.forEach((n,s)=>{let i=Ps.legalizeColumnName(n,s);t.includes(i)&&(i=Td+s),t.push(i)}),t};static legalizeColumnName=(e,t=0)=>Ps.legalize(e,Td,wp,!0,t);static isValidTableName=e=>Ps.legalizeTableName(e)===e;static isValidColumnName=e=>Ps.legalizeColumnName(e)===e}const Ii=Ps;function vp(c,e){return c?c.closest(`.${e}`):null}const Tp={getClosestByClassName:vp};class Ep{pending=[];resolved=[];add(e,t){const n=ye.makeCancelable(e,t);return this.pending.push(n),n.then(()=>{this.resolve(n)},()=>{this.resolve(n)}),n}remove(e){for(let t=0;t<this.pending.length;t+=1)if(this.pending[t]===e){this.pending.splice(t,1);return}}resolve(e){this.remove(e),this.resolved.push(e)}cancel(){const e=[...this.pending,...this.resolved];for(let t=0;t<e.length;t+=1)e[t].cancel();this.pending=[],this.resolved=[]}}const Yn=Ep;class yp extends Error{isInvalid=!0}const vi=yp;function ah({type:c}){switch(c){case I.VariableType.TABLE:case I.VariableType.TABLEMAP:case I.VariableType.TREETABLE:case I.VariableType.HIERARCHICALTABLE:return r.jsx(ee,{icon:rr});case I.VariableType.FIGURE:return r.jsx(ee,{icon:Xc});case I.VariableType.PANDAS:return r.jsx(ee,{icon:ng});default:return r.jsx(ee,{icon:Ba})}}class Rp extends v.Component{constructor(e){super(e),this.container=null}componentDidMount(){this.colorize()}container;colorize(){const{children:e}=this.props;this.container&&e!=null&&Gn.colorizeElement(this.container,{theme:"dh-dark"})}render(){const{children:e,language:t}=this.props;return r.jsx("div",{children:r.jsx("div",{"data-lang":t,ref:n=>{this.container=n},style:{pointerEvents:"none"},children:e})})}}const Yl=Rp;class xp{static get LANGUAGE_MAP(){return new Map([["python","Python"],["groovy","Groovy"],["scala","Scala"]])}}const rh=xp;class ul{static hasComment(e){return e.comment!==void 0}static hasPattern(e){return e.pattern!==void 0}static hasOp(e){return e.op!==void 0}static parseArguments(e){return e==null||!(typeof e=="string"||e instanceof String)?[]:sm.parse(e).filter(t=>!this.hasComment(t)).map(t=>this.hasPattern(t)?t.pattern:this.hasOp(t)?t.op:`${t}`)}static formatTimestamp(e){if(e==null||!(e instanceof Date))return null;const t=`${e.getHours()}`.padStart(2,"0"),n=`${e.getMinutes()}`.padStart(2,"0"),s=`${e.getSeconds()}`.padStart(2,"0"),i=`${e.getMilliseconds()}`.padStart(3,"0");return`${t}:${n}:${s}.${i}`}static isTableType(e){return e===I.VariableType.TABLE||e===I.VariableType.TREETABLE||e===I.VariableType.HIERARCHICALTABLE}static isWidgetType(e){return e===I.VariableType.FIGURE||e===I.VariableType.OTHERWIDGET||e===I.VariableType.PANDAS}static isOpenableType(e){return ul.isTableType(e)||ul.isWidgetType(e)}static isFigureType(e){return e===I.VariableType.FIGURE}static isPandas(e){return e===I.VariableType.PANDAS}}const $a=ul;function ch({children:c}){return r.jsxs("div",{className:"console-history-item-result",children:[r.jsx("div",{className:"console-history-gutter",children:"-"}),r.jsx("div",{className:"console-history-content",children:c})]})}ch.propTypes={children:z.node.isRequired};class Dp extends v.Component{static defaultProps={disabled:!1};constructor(e){super(e),this.updateElapsed=this.updateElapsed.bind(this),this.startTime=Date.now(),this.state={elapsed:0}}componentDidMount(){this.timer=setInterval(this.updateElapsed,1e3)}componentWillUnmount(){this.timer&&clearInterval(this.timer),this.timer=void 0}timer;startTime;updateElapsed(){this.setState({elapsed:Math.round((Date.now()-this.startTime)/1e3)})}render(){const{disabled:e,onCancelClick:t}=this.props,{elapsed:n}=this.state;return r.jsx("div",{className:Y("console-history-result-in-progress",{disabled:e}),children:r.jsxs("span",{className:"badge",children:[r.jsx(In,{})," Running... ",jl.formatElapsedTime(n)," ",r.jsx(B,{className:"console-history-result-in-progress-cancel",kind:"ghost",icon:uo,tooltip:"Cancel",onClick:t,disabled:e})]})})}}const Ip=Dp;class ml extends v.PureComponent{static defaultProps={message:""};static mouseDragThreshold=5;constructor(e){super(e),this.handleKeyPress=this.handleKeyPress.bind(this),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseMove=this.handleMouseMove.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this),this.handleToggleError=this.handleToggleError.bind(this),this.handleMouseEnter=this.handleMouseEnter.bind(this),this.handleMouseLeave=this.handleMouseLeave.bind(this),this.mouseX=null,this.mouseY=null,this.isClicking=!1,this.state={isExpanded:!1,isTriggerHovered:!1}}mouseX;mouseY;isClicking;handleKeyPress(e){switch(e.key){case"Enter":case" ":this.handleToggleError(),e.stopPropagation(),e.preventDefault();break}}handleMouseDown(e){this.mouseX=e.clientX,this.mouseY=e.clientY,this.isClicking=!0}handleMouseMove(e){this.mouseX!=null&&this.mouseY!=null?(Math.abs(e.clientX-this.mouseX)>=ml.mouseDragThreshold||Math.abs(e.clientY-this.mouseY)>=ml.mouseDragThreshold)&&(this.isClicking=!1):this.isClicking&&(this.isClicking=!1)}handleMouseUp(e){this.isClicking&&!e.shiftKey&&!e.metaKey&&!e.altKey&&this.handleToggleError(),this.mouseX=null,this.mouseY=null,this.isClicking=!1}handleToggleError(){this.setState(e=>({isExpanded:!e.isExpanded}))}handleMouseEnter(){this.setState({isTriggerHovered:!0})}handleMouseLeave(){this.setState({isTriggerHovered:!1})}render(){const{isExpanded:e,isTriggerHovered:t}=this.state,{message:n}=this.props;N(n);const s=n.indexOf(`
2
- `),i=s>-1;let o=n;i&&(o=n.slice(0,s));const l=n.slice(s),a=t?"error-btn-link error-btn-link--active":"error-btn-link";return r.jsxs("div",{className:Y("error-message",{expanded:e}),children:[i&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"error-gutter",children:r.jsx("button",{type:"button",onClick:this.handleToggleError,className:a,tabIndex:-1,children:r.jsx(ee,{icon:e?Un:Zc,transform:"left-3"})})}),r.jsxs("div",{className:"error-content",children:[r.jsx("div",{className:"console-error-text-trigger",role:"button",tabIndex:0,onKeyPress:this.handleKeyPress,onMouseDown:this.handleMouseDown,onMouseMove:this.handleMouseMove,onMouseEnter:this.handleMouseEnter,onMouseLeave:this.handleMouseLeave,onMouseUp:this.handleMouseUp,children:o}),e?l:""]})]}),!i&&r.jsx("div",{className:"error-content",children:r.jsx("div",{className:"console-error-text",children:o})})]},"error")}}const Fp=ml;const Ed=ne.module("ConsoleHistoryItem");class Np extends v.PureComponent{static defaultProps={disabled:!1};constructor(e){super(e),this.handleCancelClick=this.handleCancelClick.bind(this),this.handleObjectClick=this.handleObjectClick.bind(this)}handleObjectClick(e){Ed.debug("handleObjectClick",e);const{openObject:t}=this.props;t(e)}handleCancelClick(){const{item:e}=this.props;e!=null&&e.cancelResult&&(Ed.debug(`Cancelling command: ${e.command}`),e.cancelResult())}render(){const{disabled:e,item:t,language:n}=this.props,{disabledObjects:s,result:i}=t;let o=null;t.command!=null&&t.command!==""&&(o=r.jsxs("div",{className:"console-history-item-command",children:[r.jsx("div",{className:"console-history-gutter",children:">"}),r.jsx("div",{className:"console-history-content",children:r.jsx(Yl,{language:n,children:t.command})})]}));const l=[];let a=!1;if(i){const{error:h,message:u,changes:m}=i;if(m){const{created:g,updated:p}=m;[...g,...p].forEach(C=>{a=!0;const{title:f}=C,b=`${f}`,w=e===void 0||e||(s??[]).indexOf(b)>=0,S=r.jsx(B,{kind:"primary",onClick:()=>this.handleObjectClick(C),className:"btn-console-object",disabled:w,icon:r.jsx(ah,{type:C.type}),children:f},b);l.push(S)})}if(h!=null&&t.command==null){let g=`${h.message??h}`;g||(g=h);const p=r.jsx(Fp,{message:g},"result-error");l.push(p)}if(u!==void 0&&u!==""){const g=r.jsx("div",{className:"log-message",children:u},"log-message");l.push(g)}}else{a=!0;const h=r.jsx(Ip,{onCancelClick:this.handleCancelClick,disabled:e},"in_progress");l.push(h)}let d=null;return l.length>0&&(d=r.jsx(ch,{children:l})),r.jsxs("div",{className:Y("console-command-result",{"console-result-buttons":a}),children:[o,d]})}}const kp=Np;class fr extends v.Component{static defaultProps={disabled:!1};static itemKey(e,t){return`${e}.${t.command}.${t.result&&t.result.message}.${t.result&&t.result.error}`}render(){const{disabled:e,items:t,language:n,openObject:s}=this.props,i=[];for(let o=0;o<t.length;o+=1){const l=t[o],a=r.jsx(kp,{disabled:e,item:l,openObject:s,language:n},fr.itemKey(o,l));i.push(a)}return r.jsx("div",{className:"container-fluid console-history",children:i})}}const Mp=fr,Lp={name:"Console",CLEAR:We.createAndAdd({id:"CONSOLE.CLEAR",name:"Clear",shortcut:[ve.CTRL,xe.L],macShortcut:[ve.CTRL,xe.C]}),FOCUS_HISTORY:We.createAndAdd({id:"CONSOLE.FOCUS_HISTORY",name:"Focus History",shortcut:[ve.CTRL,xe.H],macShortcut:[ve.CTRL,ve.OPTION,xe.H]})},Op={name:"Command History",FOCUS_HISTORY:We.createAndAdd({id:"COMMAND_HISTORY.FOCUS_HISTORY",name:"Focus History Search",shortcut:[ve.CTRL,xe.H],macShortcut:[ve.CTRL,ve.OPTION,xe.H]}),SEND_TO_CONSOLE:We.createAndAdd({id:"COMMAND_HISTORY.SEND_TO_CONSOLE",name:"Send to Console",shortcut:[xe.ENTER],macShortcut:[xe.ENTER]}),SEND_TO_NOTEBOOK:We.createAndAdd({id:"COMMAND_HISTORY.SEND_TO_NOTEBOOK",name:"Send to Notebook",shortcut:[ve.CTRL,xe.ENTER],macShortcut:[ve.CMD,xe.ENTER]}),RUN:We.createAndAdd({id:"COMMAND_HISTORY.RUN",name:"Run",shortcut:[ve.ALT,xe.R],macShortcut:[ve.OPTION,xe.R]})},Ap={name:"Notebook",RUN:We.createAndAdd({id:"NOTEBOOK.RUN",name:"Run",shortcut:[ve.ALT,xe.R],macShortcut:[ve.OPTION,xe.R]}),RUN_SELECTED:We.createAndAdd({id:"NOTEBOOK.RUN_SELECTED",name:"Run Selected",shortcut:[ve.ALT,ve.SHIFT,xe.R],macShortcut:[ve.OPTION,ve.SHIFT,xe.R]}),FIND:We.createAndAdd({id:"NOTEBOOK.FIND",name:"Find",shortcut:[ve.CTRL,xe.F],macShortcut:[ve.CMD,xe.F],isEditable:!1}),MINIMAP:We.createAndAdd({id:"NOTEBOOK.MINIMAP",name:"Show Minimap",shortcut:[ve.ALT,xe.M],macShortcut:[ve.OPTION,xe.M]}),WORDWRAP:We.createAndAdd({id:"NOTEBOOK.WORDWRAP",name:"Word Wrap",shortcut:[ve.ALT,xe.Z],macShortcut:[ve.OPTION,xe.Z]})},_p={CONSOLE:Lp,COMMAND_HISTORY:Op,NOTEBOOK:Ap},Nt=_p,Ct=Object.freeze({FATAL:"FATAL",STDERR:"STDERR",ERROR:"ERROR",WARN:"WARN",STDOUT:"STDOUT",INFO:"INFO",DEBUG:"DEBUG",TRACE:"TRACE"}),Pp="#2d2a2e",jp="#fcfcfa",Hp="#fcd65b",Bp="#b2b1b2",Up="#9edc6f",Vp="#76d9e4",$p="#f95d84",Wp="#aa9af4",Gp="#f95d84",zp="#fcfcfa",Kp="#7c7b7c",pe={"error-foreground":"#f95d84",background:Pp,foreground:jp,"line-height":"19px",string:Hp,"string-delim":"#929192",delimiter:Bp,predefined:Up,keyword:Vp,storage:$p,number:Wp,operator:Gp,identifier:zp,"namespace-identifier":"#f95d84","identifier-js":"#fcd65b",comment:Kp,"input-option-active-border":"#929192","focus-border":"rgba(72, 120, 234, 0.85)","input-background":"#555356","input-foreground":"#f0f0ee","input-border":"#929192","editor-line-number-foreground":"#929192","editor-selection-background":"#676368","editor-line-highlight-bg":"#373438","context-menu-background":"#555356","context-menu-foreground":"#f0f0ee","menu-selection-background":"#4878ea","log-date":"#929192","log-error":"#f95d84","log-info":"#76d9e4","log-stdout":"#f0f0ee","log-warn":"#fcd65b","log-debug":"#aa9af4","log-trace":"#9edc6f","editor-find-match-background":"#3c5595","editor-find-match-highlight-background":"#343e5d","editor-widget-background":"#403e41","input-option-active-background":"#4878ea","input-option-active-foreground":"#f0f0ee","editor-suggest-widget-background":"#403e41","editor-suggest-widget-border":"#5b5a5c","editor-suggest-widget-foreground":"#f0f0ee","editor-suggest-widget-selected-background":"#41475a","editor-suggest-widget-highlightForeground":"#4878ea","list-hover-background":"#555356","text-link-foreground":"#929192","text-link-active-foreground":"#f0f0ee","editor-link-active-foreground":"#f0f0ee"},Yp="python",qp={comments:{lineComment:"#",blockComment:["'''","'''"]},brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"',notIn:["string"]},{open:"'",close:"'",notIn:["string","comment"]}],surroundingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],onEnterRules:[{beforeText:/^\s*(?:def|class|for|if|elif|else|while|try|with|finally|except|async).*?:\s*$/,action:{indentAction:1}}],folding:{offSide:!0,markers:{start:/^\s*#region\b/,end:/^\s*#endregion\b/}}},Xp={keywords:["and","del","from","not","while","as","elif","global","or","with","assert","else","if","pass","yield","break","except","import","print","exec","in","raise","continue","finally","is","return","for","try",":","=","isinstance","__debug__"],storage:["class","def","async","lambda"],operators:["+","-","*","**","/","//","%","<<",">>","&","|","^","~","<",">","<=",">=","==","!=","<>","+=","-=","*=","/","//=","%=","&=","|=","^=",">>=","<<=","**="],brackets:[{open:"{",close:"}",token:"delimiter.curly"},{open:"[",close:"]",token:"delimiter.square"},{open:"(",close:")",token:"delimiter.parenthesis"}],symbols:/[=><!~&|+\-*/^%]+/,delimiters:/[;=.@:,`]/,escapes:/\\(?:[abfnrtv\\"'\n\r]|x[0-9A-Fa-f]{2}|[0-7]{3}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8}|N\{\w+\})/,rawpre:/(?:[rR]|ur|Ur|uR|UR|br|Br|bR|BR)/,strpre:/(?:[buBU])/,tokenizer:{root:[[/@strpre?("""|''')/,{token:"string.delim",bracket:"@open",next:"@mstring.$1"}],[/@strpre?"([^"\\]|\\.)*$/,"string.invalid"],[/@strpre?'([^'\\]|\\.)*$/,"string.invalid"],[/@strpre?(["])/,{token:"string.delim",bracket:"@open",next:"@sstring.$1",nextEmbedded:"deephavenDb"}],[/@strpre?(["'])/,{token:"string.delim",bracket:"@open",next:"@string.$1"}],[/@rawpre("""|''')/,{token:"string.delim",bracket:"@open",next:"@mrawstring.$1"}],[/@rawpre"([^"\\]|\\.)*$/,"string.invalid"],[/@rawpre'([^'\\]|\\.)*$/,"string.invalid"],[/@rawpre(["'])/,{token:"string.delim",bracket:"@open",next:"@rawstring.$1"}],[/__[\w$]*/,"predefined"],[/[a-z_$][\w$]*/,{cases:{"@keywords":"keyword","@storage":"storage","@default":"identifier"}}],[/[A-Z][\w]*/,{cases:{"~[A-Z0-9_]+":"constructor.identifier","@default":"namespace.identifier"}}],{include:"@whitespace"},[/[{}()[\]]/,"@brackets"],[/@symbols/,{cases:{"@keywords":"keyword","@operators":"operator","@default":""}}],[/\d*\.\d+([eE][-+]?\d+)?/,"number.float"],[/0[xX][0-9a-fA-F]+[lL]?/,"number.hex"],[/0[bB][0-1]+[lL]?/,"number.binary"],[/(0[oO][0-7]+|0[0-7]+)[lL]?/,"number.octal"],[/(0|[1-9]\d*)[lL]?/,"number"],[":",{token:"keyword",bracket:"@open"}],[/@delimiters/,{cases:{"@keywords":"keyword","@default":"delimiter"}}]],comment:[[/[^/*]+/,"comment"],[/\/\*/,"comment","@push"],["\\*/","comment","@pop"],[/[/*]/,"comment"]],mstring:[{include:"@strcontent"},[/"""|'''/,{cases:{"$#==$S2":{token:"string.delim",bracket:"@close",next:"@pop"},"@default":{token:"string"}}}],[/["']/,"string"],[/./,"string.invalid"]],sstring:[{include:"@strcontent"},[/["]/,{token:"string.delim",bracket:"@close",next:"@pop",nextEmbedded:"@pop"}],[/./,"string.invalid"]],string:[{include:"@strcontent"},[/[']/,{token:"string.delim",bracket:"@close",next:"@pop"}],[/./,"string.invalid"]],strcontent:[[/[^\\"']+/,"string"],[/\\$/,"string.escape"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"]],mrawstring:[{include:"@rawstrcontent"},[/"""|'''/,{cases:{"$#==$S2":{token:"string.delim",bracket:"@close",next:"@pop"},"@default":{token:"string"}}}],[/["']/,"string"],[/./,"string.invalid"]],rawstring:[{include:"@rawstrcontent"},[/["']/,{cases:{"$#==$S2":{token:"string.delim",bracket:"@close",next:"@pop"},"@default":{token:"string"}}}],[/./,"string.invalid"]],rawstrcontent:[[/[^\\"']+/,"string"],[/\\["']/,"string"],[/\\u[0-9A-Fa-f]{4}/,"string.escape"],[/\\/,"string"]],whitespace:[[/\s+/,"white"],[/(^#.*$)/,"comment"],[/'''/,"string","@endDocString"],[/"""/,"string","@endDblDocString"]],endDocString:[[/[^']+/,"string"],[/\\'/,"string"],[/'''/,"string","@popall"],[/'/,"string"]],endDblDocString:[[/[^"]+/,"string"],[/\\"/,"string"],[/"""/,"string","@popall"],[/"/,"string"]]}},Zp={id:Yp,conf:qp,language:Xp},Qp=Zp,Jp="groovy",ef={comments:{lineComment:"//",blockComment:["/*","*/"]},brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"',notIn:["string"]},{open:"'",close:"'",notIn:["string","comment"]}],surroundingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],onEnterRules:[{beforeText:/^\s*(?:def|class|for|if|elif|else|while|try|with|finally|except|async).*?:\s*$/,action:{indentAction:1}}],folding:{offSide:!0,markers:{start:/^\s*#region\b/,end:/^\s*#endregion\b/}}},tf={keywords:["and","del","from","not","while","as","elif","global","or","with","assert","else","if","pass","yield","break","except","import","print","println","class","exec","in","raise","continue","finally","is","return","def","for","lambda","try",":","=","isinstance","__debug__"],operators:["+","-","*","**","/","//","%","<<",">>","&","|","^","~","<",">","<=",">=","==","!=","<>","+=","-=","*=","/","//=","%=","&=","|=","^=",">>=","<<=","**="],brackets:[{open:"{",close:"}",token:"delimiter.curly"},{open:"[",close:"]",token:"delimiter.square"},{open:"(",close:")",token:"delimiter.parenthesis"}],symbols:/[=><!~&|+\-*/^%]+/,delimiters:/[;=.@:,`]/,escapes:/\\(?:[abfnrtv\\"'\n\r]|x[0-9A-Fa-f]{2}|[0-7]{3}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8}|N\{\w+\})/,rawpre:/(?:[rR]|ur|Ur|uR|UR|br|Br|bR|BR)/,strpre:/(?:[buBU])/,tokenizer:{root:[[/@strpre?("""|''')/,{token:"string.delim",bracket:"@open",next:"@mstring.$1"}],[/@strpre?"([^"\\]|\\.)*$/,"string.invalid"],[/@strpre?'([^'\\]|\\.)*$/,"string.invalid"],[/@strpre?(["])/,{token:"string.delim",bracket:"@open",next:"@sstring.$1",nextEmbedded:"deephavenDb"}],[/@strpre?(["'])/,{token:"string.delim",bracket:"@open",next:"@string.$1"}],[/@rawpre("""|''')/,{token:"string.delim",bracket:"@open",next:"@mrawstring.$1"}],[/@rawpre"([^"\\]|\\.)*$/,"string.invalid"],[/@rawpre'([^'\\]|\\.)*$/,"string.invalid"],[/@rawpre(["'])/,{token:"string.delim",bracket:"@open",next:"@rawstring.$1"}],[/__[\w$]*/,"predefined"],[/[a-z_$][\w$]*/,{cases:{"@keywords":"keyword","@default":"identifier"}}],[/[A-Z][\w]*/,{cases:{"~[A-Z0-9_]+":"constructor.identifier","@default":"namespace.identifier"}}],{include:"@whitespace"},[/[{}()[\]]/,"@brackets"],[/@symbols/,{cases:{"@keywords":"keyword","@operators":"operator","@default":""}}],[/\d*\.\d+([eE][-+]?\d+)?/,"number.float"],[/0[xX][0-9a-fA-F]+[lL]?/,"number.hex"],[/0[bB][0-1]+[lL]?/,"number.binary"],[/(0[oO][0-7]+|0[0-7]+)[lL]?/,"number.octal"],[/(0|[1-9]\d*)[lL]?/,"number"],[":",{token:"keyword",bracket:"@open"}],[/@delimiters/,{cases:{"@keywords":"keyword","@default":"delimiter"}}]],mstring:[{include:"@strcontent"},[/"""|'''/,{cases:{"$#==$S2":{token:"string.delim",bracket:"@close",next:"@pop"},"@default":{token:"string"}}}],[/["']/,"string"],[/./,"string.invalid"]],sstring:[{include:"@strcontent"},[/["]/,{token:"string.delim",bracket:"@close",next:"@pop",nextEmbedded:"@pop"}],[/./,"string.invalid"]],string:[{include:"@strcontent"},[/[']/,{token:"string.delim",bracket:"@close",next:"@pop"}],[/./,"string.invalid"]],strcontent:[[/[^\\"']+/,"string"],[/\\$/,"string.escape"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"]],mrawstring:[{include:"@rawstrcontent"},[/"""|'''/,{cases:{"$#==$S2":{token:"string.delim",bracket:"@close",next:"@pop"},"@default":{token:"string"}}}],[/["']/,"string"],[/./,"string.invalid"]],rawstring:[{include:"@rawstrcontent"},[/["']/,{cases:{"$#==$S2":{token:"string.delim",bracket:"@close",next:"@pop"},"@default":{token:"string"}}}],[/./,"string.invalid"]],rawstrcontent:[[/[^\\"']+/,"string"],[/\\["']/,"string"],[/\\u[0-9A-Fa-f]{4}/,"string.escape"],[/\\/,"string"]],whitespace:[[/[ \t\r\n]+/,""],[/\/\*\*(?!\/)/,"comment.doc","@doccomment"],[/\/\*/,"comment","@comment"],[/\/\/.*$/,"comment"]],comment:[[/[^/*]+/,"comment"],[/\*\//,"comment","@pop"],[/[/*]/,"comment"]],doccomment:[[/[^/*]+/,"comment.doc"],[/\*\//,"comment.doc","@pop"],[/[/*]/,"comment.doc"]]}},nf={id:Jp,conf:ef,language:tf},sf=nf,of="scala",lf={wordPattern:/(unary_[@~!#%^&*()\-=+\\|:<>/?]+)|([a-zA-Z_$][\w$]*?_=)|(`[^`]+`)|([a-zA-Z_$][\w$]*)/g,comments:{lineComment:"//",blockComment:["/*","*/"]},brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],surroundingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],folding:{markers:{start:/^\s*\/\/\s*(?:(?:#?region\b)|(?:<editor-fold\b))/,end:/^\s*\/\/\s*(?:(?:#?endregion\b)|(?:<\/editor-fold>))/}}},af={keywords:["asInstanceOf","catch","class","classOf","def","do","else","extends","finally","for","foreach","forSome","if","import","isInstanceOf","macro","match","new","object","package","return","throw","trait","try","type","until","val","var","while","with","yield","given","enum","then"],softKeywords:["as","export","extension","end","derives","on"],constants:["true","false","null","this","super"],modifiers:["abstract","final","implicit","lazy","override","private","protected","sealed"],softModifiers:["inline","opaque","open","transparent","using"],name:/(?:[a-z_$][\w$]*|`[^`]+`)/,type:/(?:[A-Z][\w$]*)/,symbols:/[=><!~?:&|+\-*/^\\%@#]+/,digits:/\d+(_+\d+)*/,hexdigits:/[[0-9a-fA-F]+(_+[0-9a-fA-F]+)*/,escapes:/\\(?:[btnfr\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,fstring_conv:/[bBhHsScCdoxXeEfgGaAt]|[Tn](?:[HIklMSLNpzZsQ]|[BbhAaCYyjmde]|[RTrDFC])/,tokenizer:{root:[[/\braw"""/,{token:"string.quote",bracket:"@open",next:"@rawstringt"}],[/\braw"/,{token:"string.quote",bracket:"@open",next:"@rawstring"}],[/\bs"""/,{token:"string.quote",bracket:"@open",next:"@sstringt"}],[/\bs"/,{token:"string.quote",bracket:"@open",next:"@sstring"}],[/\bf""""/,{token:"string.quote",bracket:"@open",next:"@fstringt"}],[/\bf"/,{token:"string.quote",bracket:"@open",next:"@fstring"}],[/"""/,{token:"string.quote",bracket:"@open",next:"@stringt"}],[/"/,{token:"string.quote",bracket:"@open",next:"@string"}],[/(@digits)[eE]([-+]?(@digits))?[fFdD]?/,"number.float","@allowMethod"],[/(@digits)\.(@digits)([eE][-+]?(@digits))?[fFdD]?/,"number.float","@allowMethod"],[/0[xX](@hexdigits)[Ll]?/,"number.hex","@allowMethod"],[/(@digits)[fFdD]/,"number.float","@allowMethod"],[/(@digits)[lL]?/,"number","@allowMethod"],[/\b_\*/,"key"],[/\b(_)\b/,"keyword","@allowMethod"],[/\bimport\b/,"keyword","@import"],[/\b(case)([ \t]+)(class)\b/,["keyword.modifier","white","keyword"]],[/\bcase\b/,"keyword","@case"],[/\bva[lr]\b/,"keyword","@vardef"],[/\b(def)([ \t]+)((?:unary_)?@symbols|@name(?:_=)|@name)/,["keyword","white","identifier"]],[/@name(?=[ \t]*:(?!:))/,"variable"],[/(\.)(@name|@symbols)/,[{token:"operator"},{token:"@rematch",next:"@allowMethod"}]],[/([{(])(\s*)(@name(?=\s*=>))/,["@brackets","white","variable"]],[/@name/,{cases:{"@keywords":"keyword","@softKeywords":"keyword","@modifiers":"keyword.modifier","@softModifiers":"keyword.modifier","@constants":{token:"constant",next:"@allowMethod"},"@default":{token:"identifier",next:"@allowMethod"}}}],[/@type/,"type","@allowMethod"],{include:"@whitespace"},[/@[a-zA-Z_$][\w$]*(?:\.[a-zA-Z_$][\w$]*)*/,"annotation"],[/[{(]/,"@brackets"],[/[})]/,"@brackets","@allowMethod"],[/\[/,"operator.square"],[/](?!\s*(?:va[rl]|def|type)\b)/,"operator.square","@allowMethod"],[/]/,"operator.square"],[/([=-]>|<-|>:|<:|:>|<%)(?=[\s\w()[\]{},."'`])/,"keyword"],[/@symbols/,"operator"],[/[;,.]/,"delimiter"],[/'[a-zA-Z$][\w$]*(?!')/,"attribute.name"],[/'[^\\']'/,"string","@allowMethod"],[/(')(@escapes)(')/,[{token:"string"},{token:"string.escape"},{token:"string",next:"@allowMethod"}]],[/'/,"string.invalid"]],import:[[/;/,"delimiter","@pop"],[/^|$/,"","@pop"],[/[ \t]+/,"white"],[/[\n\r]+/,"white","@pop"],[/\/\*/,"comment","@comment"],[/@name|@type/,"type"],[/[(){}]/,"@brackets"],[/[[\]]/,"operator.square"],[/[.,]/,"delimiter"]],allowMethod:[[/^|$/,"","@pop"],[/[ \t]+/,"white"],[/[\n\r]+/,"white","@pop"],[/\/\*/,"comment","@comment"],[/(?==>[\s\w([{])/,"keyword","@pop"],[/(@name|@symbols)(?=[ \t]*[[({"'`]|[ \t]+(?:[+-]?\.?\d|\w))/,{cases:{"@keywords":{token:"keyword",next:"@pop"},"->|<-|>:|<:|<%":{token:"keyword",next:"@pop"},"@default":{token:"@rematch",next:"@pop"}}}],["","","@pop"]],comment:[[/[^/*]+/,"comment"],[/\/\*/,"comment","@push"],[/\*\//,"comment","@pop"],[/[/*]/,"comment"]],case:[[/\b_\*/,"key"],[/\b(_|true|false|null|this|super)\b/,"keyword","@allowMethod"],[/\bif\b|=>/,"keyword","@pop"],[/`[^`]+`/,"identifier","@allowMethod"],[/@name/,"variable","@allowMethod"],[/:::?|\||@(?![a-z_$])/,"keyword"],{include:"@root"}],vardef:[[/\b_\*/,"key"],[/\b(_|true|false|null|this|super)\b/,"keyword"],[/@name/,"variable"],[/:::?|\||@(?![a-z_$])/,"keyword"],[/=|:(?!:)/,"operator","@pop"],[/$/,"white","@pop"],{include:"@root"}],string:[[/[^\\"\n\r]+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/"/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}]],stringt:[[/[^\\"\n\r]+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/"(?=""")/,"string"],[/"""/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}],[/"/,"string"]],fstring:[[/@escapes/,"string.escape"],[/"/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}],[/\$\$/,"string"],[/(\$)([a-z_]\w*)/,["operator","identifier"]],[/\$\{/,"operator","@interp"],[/%%/,"string"],[/(%)([-#+ 0,(])(\d+|\.\d+|\d+\.\d+)(@fstring_conv)/,["metatag","keyword.modifier","number","metatag"]],[/(%)(\d+|\.\d+|\d+\.\d+)(@fstring_conv)/,["metatag","number","metatag"]],[/(%)([-#+ 0,(])(@fstring_conv)/,["metatag","keyword.modifier","metatag"]],[/(%)(@fstring_conv)/,["metatag","metatag"]],[/./,"string"]],fstringt:[[/@escapes/,"string.escape"],[/"(?=""")/,"string"],[/"""/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}],[/\$\$/,"string"],[/(\$)([a-z_]\w*)/,["operator","identifier"]],[/\$\{/,"operator","@interp"],[/%%/,"string"],[/(%)([-#+ 0,(])(\d+|\.\d+|\d+\.\d+)(@fstring_conv)/,["metatag","keyword.modifier","number","metatag"]],[/(%)(\d+|\.\d+|\d+\.\d+)(@fstring_conv)/,["metatag","number","metatag"]],[/(%)([-#+ 0,(])(@fstring_conv)/,["metatag","keyword.modifier","metatag"]],[/(%)(@fstring_conv)/,["metatag","metatag"]],[/./,"string"]],sstring:[[/@escapes/,"string.escape"],[/"/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}],[/\$\$/,"string"],[/(\$)([a-z_]\w*)/,["operator","identifier"]],[/\$\{/,"operator","@interp"],[/./,"string"]],sstringt:[[/@escapes/,"string.escape"],[/"(?=""")/,"string"],[/"""/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}],[/\$\$/,"string"],[/(\$)([a-z_]\w*)/,["operator","identifier"]],[/\$\{/,"operator","@interp"],[/./,"string"]],interp:[[/{/,"operator","@push"],[/}/,"operator","@pop"],{include:"@root"}],rawstring:[[/[^"]/,"string"],[/"/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}]],rawstringt:[[/[^"]/,"string"],[/"(?=""")/,"string"],[/"""/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}],[/"/,"string"]],whitespace:[[/[ \t\r\n]+/,"white"],[/\/\*/,"comment","@comment"],[/\/\/.*$/,"comment"]]}},rf={id:of,conf:lf,language:af},df=rf,cf="deephavenDb",hf={comments:{lineComment:"#",blockComment:["'''","'''"]},brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"',notIn:["string"]},{open:"'",close:"'",notIn:["string","comment"]}],surroundingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],onEnterRules:[{beforeText:/^\s*(?:def|class|for|if|elif|else|while|try|with|finally|except|async).*?:\s*$/,action:{indentAction:1}}],folding:{offSide:!0,markers:{start:/^\s*#region\b/,end:/^\s*#endregion\b/}}},uf={tokenPostfix:".js",keywords:["boolean","break","byte","case","catch","char","class","const","continue","debugger","default","delete","do","double","else","enum","export","extends","false","final","finally","float","for","function","goto","if","implements","import","in","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","super","switch","synchronized","this","throw","throws","transient","true","try","typeof","var","void","volatile","while","with"],builtins:["define","require","window","document","undefined"],operators:["=",">","<","!","~","?",":","==","<=",">=","!=","&&","||","++","--","+","-","*","/","&","|","^","%","<<",">>",">>>","+=","-=","*=","/=","&=","|=","^=","%=","<<=",">>=",">>>="],brackets:[{open:"{",close:"}",token:"delimiter.curly"},{open:"[",close:"]",token:"delimiter.bracket"},{open:"(",close:")",token:"delimiter.parenthesis"}],symbols:/[~!@#%\^&*-+=|\\:`<>.?\/]+/,escapes:/\\(?:[btnfr\\"']|[0-7][0-7]?|[0-3][0-7]{2})/,exponent:/[eE][\-+]?[0-9]+/,regexpctl:/[(){}\[\]\$\^|\-*+?\.]/,regexpesc:/\\(?:[bBdDfnrstvwWn0\\\/]|@regexpctl|c[A-Z]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4})/,tokenizer:{root:[[/([a-zA-Z_\$][\w\$]*)(\s*)(:?)/,{cases:{"$1@keywords":["keyword","white","delimiter"],$3:["key.identifier","white","delimiter"],"$1@builtins":["predefined.identifier","white","delimiter"],"@default":["identifier","white","delimiter"]}}],{include:"@whitespace"},[/\/(?=([^\\\/]|\\.)+\/)/,{token:"regexp.slash",bracket:"@open",next:"@regexp"}],[/[{}()\[\]]/,"@brackets"],[/[;,.]/,"delimiter"],[/@symbols/,{cases:{"@operators":"operator","@default":""}}],[/\d+\.\d*(@exponent)?/,"number.float"],[/\.\d+(@exponent)?/,"number.float"],[/\d+@exponent/,"number.float"],[/0[xX][\da-fA-F]+/,"number.hex"],[/0[0-7]+/,"number.octal"],[/\d+/,"number"],[/"([^"\\]|\\.)*$/,"string.invalid"],[/'([^'\\]|\\.)*$/,"string.invalid"],[/"/,"string",'@string."'],[/'/,"string","@string.'"]],whitespace:[[/[ \t\r\n]+/,"white"],[/\/\*/,"comment","@comment"],[/\/\/.*$/,"comment"]],comment:[[/[^\/*]+/,"comment"],[/\/\*/,"comment.invalid"],["\\*/","comment","@pop"],[/[\/*]/,"comment"]],string:[[/[^\\"']+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/["']/,{cases:{"$#==$S2":{token:"string",next:"@pop"},"@default":"string"}}]],regexp:[[/(\{)(\d+(?:,\d*)?)(\})/,["@brackets.regexp.escape.control","regexp.escape.control","@brackets.regexp.escape.control"]],[/(\[)(\^?)(?=(?:[^\]\\\/]|\\.)+)/,[{token:"@brackets.regexp.escape.control"},{token:"regexp.escape.control",next:"@regexrange"}]],[/(\()(\?:|\?=|\?!)/,["@brackets.regexp.escape.control","regexp.escape.control"]],[/[()]/,"@brackets.regexp.escape.control"],[/@regexpctl/,"regexp.escape.control"],[/[^\\\/]/,"regexp"],[/@regexpesc/,"regexp.escape"],[/\\\./,"regexp.invalid"],["/",{token:"regexp.slash",bracket:"@close"},"@pop"]],regexrange:[[/-/,"regexp.escape.control"],[/\^/,"regexp.invalid"],[/@regexpesc/,"regexp.escape"],[/[^\]]/,"regexp"],[/\]/,"@brackets.regexp.escape.control","@pop"]]}},mf={id:cf,conf:hf,language:uf},gf=mf,pf="log",ff={},Cf={tokenizer:{root:[[/ FATAL[\s\S]*/,{token:"error",next:"@error"}],[/ ERROR[\s\S]*/,{token:"error",next:"@error"}],[/ STDERR[\s\S]*/,{token:"error",next:"@error"}],[/ STDOUT.*/,{token:"stdout",next:"@stdout"}],[/ INFO[\s\S]*/,{token:"info",next:"@info"}],[/ WARN.*/,{token:"warn",next:"@warn"}],[/ TRACE[\s\S]*/,{token:"trace",next:"@trace"}],[/ DEBUG[.\s\S]*/,{token:"debug",next:"@debug"}],[/^\d{2}:\d{2}:\d{2}.\d{3}/,"date"]],error:[{include:"@body"}],info:[{include:"@body"}],warn:[{include:"@body"}],stdout:[{include:"@body"}],trace:[{include:"@body"}],debug:[{include:"@body"}],body:[[/^\d{2}:\d{2}:\d{2}.\d{3}/,{token:"date",next:"@pop"}],[/[\s\S]*/,{token:"$S0"}]]}},bf={id:pf,conf:ff,language:Cf},Sf=bf,bn=ne.module("MonacoUtils");class wn{static init({getWorker:e}={}){bn.debug("Initializing Monaco..."),e!==void 0&&wn.registerGetWorker(e);const{registerLanguages:t,removeHashtag:n}=wn,s=[{token:"",foreground:n(pe.foreground)},{token:"string",foreground:n(pe.string)},{token:"string.delim",foreground:n(pe["string-delim"])},{token:"keyword",foreground:n(pe.keyword)},{token:"identifier.js",foreground:n(pe["identifier-js"])},{token:"delimiter",foreground:n(pe.delimiter)},{token:"comment",foreground:n(pe.comment)},{token:"number",foreground:n(pe.number)},{token:"storage",foreground:n(pe.storage)},{token:"identifier",foreground:n(pe.identifier)},{token:"namespace.identifier",foreground:n(pe["namespace-identifier"])},{token:"operator",foreground:n(pe.operator)},{token:"predefined",foreground:n(pe.predefined)},{token:"error.log",foreground:pe["log-error"].substring(1)},{token:"warn.log",foreground:n(pe["log-warn"])},{token:"info.log",foreground:n(pe["log-info"])},{token:"stdout.log",foreground:n(pe["log-stdout"])},{token:"trace.log",foreground:n(pe["log-trace"])},{token:"debug.log",foreground:n(pe["log-debug"])},{token:"date.log",foreground:n(pe["log-date"])}],i={errorForeground:pe["error-foreground"],"inputOption.activeBorder":pe["input-option-active-border"],"editor.background":pe.background,"editor.foreground":pe.foreground,"editor.lineHighlightBackground":pe["editor-line-highlight-bg"],"editorLineNumber.foreground":pe["editor-line-number-foreground"],"editor.selectionBackground":pe["editor-selection-background"],"editor.findMatchBackground":pe["editor-find-match-background"],"editor.findMatchHighlightBackground":pe["editor-find-match-highlight-background"],"editorSuggestWidget.background":pe["editor-suggest-widget-background"],"editorSuggestWidget.border":pe["editor-suggest-widget-border"],"editorSuggestWidget.foreground":pe["editor-suggest-widget-foreground"],"editorSuggestWidget.selectedBackground":pe["editor-suggest-widget-selected-background"],"editorSuggestWidget.highlightForeground":pe["editor-suggest-widget-highlightForeground"],"list.hoverBackground":pe["list-hover-background"],"dropdown.background":pe["context-menu-background"],"dropdown.foreground":pe["context-menu-foreground"],"menu.selectionBackground":pe["menu-selection-background"],"list.focusBackground":pe["menu-selection-background"],"editorWidget.background":pe["editor-widget-background"],"inputOption.activeBackground":pe["input-option-active-background"],"inputOption.activeForeground":pe["input-option-active-foreground"],focusBorder:pe["focus-border"],"input.background":pe["input-background"],"input.foreground":pe["input-foreground"],"input.border":pe["input-border"],"textLink.foreground":pe["text-link-foreground"],"textLink.activeForeground":pe["text-link-active-foreground"],"editorLink.activeForeground":pe["editor-link-active-foreground"]};Gn.defineTheme("dh-dark",{base:"vs-dark",inherit:!0,rules:s,colors:i}),bn.debug2("monaco theme: ",pe),Gn.setTheme("dh-dark"),t([gf,Qp,sf,Sf,df]),bn.debug("Monaco initialized.")}static registerGetWorker(e){window.MonacoEnvironment={...window.MonacoEnvironment,getWorker:e}}static removeHashtag(e){return e.substring(1)}static registerLanguages(e){const t=e.map(({id:n})=>n);yn.getLanguages().filter(({id:n})=>t.includes(n)).forEach(n=>{const s=n;bn.debug2("Overriding default language loader:",s.id)}),e.forEach(n=>{wn.registerLanguage(n)})}static registerLanguage(e){bn.debug2("Registering language: ",e.id),yn.register(e),yn.onLanguage(e.id,()=>{yn.setLanguageConfiguration(e.id,e.conf),yn.setMonarchTokensProvider(e.id,e.language)})}static setEOL(e,t=Gn.EndOfLineSequence.LF){e.getModel()?.setEOL(t)}static openDocument(e,t){const n=e.getModel();N(n);const s={textDocument:{uri:`${n.uri}`,languageId:n.getLanguageId(),version:n.getVersionId(),text:n.getValue()}};return bn.debug2("didOpenDocumentParams: ",s),t.openDocument(s),e.onDidChangeModelContent(o=>{const{changes:l,versionId:a}=o,d=[];for(let h=0;h<l.length;h+=1){const u=l[h],{range:m,rangeLength:g,text:p}=u,C={range:{start:{line:m.startLineNumber-1,character:m.startColumn-1},end:{line:m.endLineNumber-1,character:m.endColumn-1}},rangeLength:g,text:p};d.push(C)}if(d.length>0){const h={textDocument:{version:a,uri:`${n.uri}`},contentChanges:d};bn.debug2("didChangeDocumentParams",h),t.changeDocument(h)}})}static closeDocument(e,t){const n=e.getModel();N(n);const s={textDocument:{uri:`${n.uri}`}};t.closeDocument(s)}static registerPasteHandler(e){e.onDidPaste(t=>{const n=/“|”/g,s=/\u200b/g,i=/\u00A0/g,o=e.getModel();N(o);const l=o.getValueInRange(t.range);(n.test(l)||s.test(l)||i.test(l))&&o.applyEdits([{range:t.range,text:l.replace(n,'"').replace(s,"").replace(i," ")}])})}static isMacPlatform(){const{platform:e}=window.navigator;return e.startsWith("Mac")}static removeConflictingKeybindings(e){const t=[{windows:"ctrl+D",mac:"meta+D"},{windows:"ctrl+H"}];try{t.forEach(n=>{wn.isMacPlatform()&&n.mac===""||!wn.isMacPlatform()&&n.windows===""||wn.removeKeybinding(e,wn.isMacPlatform()?n.mac:n.windows)})}catch(n){bn.error(n)}}static removeKeybinding(e,t){if(t===void 0)return;const n=e._standaloneKeybindingService._getResolver()._map.get(t);n!=null?n.forEach(s=>{bn.debug2(`Removing Monaco keybinding ${t} for ${s.command}`),e._standaloneKeybindingService.addDynamicKeybinding(`-${s.command}`,null,()=>{})}):bn.warn(`Did not find any keybindings to remove for ${t}`)}static getMonacoKeyCodeFromShortcut(e){const{keyState:t}=e,{keyValue:n}=t;return n===null?0:wn.isMacPlatform()?(t.metaKey?tn.CtrlCmd:0)|(t.shiftKey?tn.Shift:0)|(t.altKey?tn.Alt:0)|(t.ctrlKey?tn.WinCtrl:0)|pd.fromString(n):(t.ctrlKey?tn.CtrlCmd:0)|(t.shiftKey?tn.Shift:0)|(t.altKey?tn.Alt:0)|(t.metaKey?tn.WinCtrl:0)|pd.fromString(n)}static provideLinks(e){const t=[];for(let n=1;n<=e.getLineCount();n+=1){const s=e.getLineContent(n);jc(s).filter(l=>l.type==="url"?/^https?:\/\//.test(l.value):!0).forEach(l=>{t.push({url:l.href,range:new eg(n,l.start+1,n,l.end+1)})})}return{links:t}}}const _t=wn,Ln=ne.module("MonacoCompletionProvider");class js extends v.PureComponent{static lspToMonacoKind(e){const t=yn.CompletionItemKind;switch(e){case 1:return t.Text;case 2:return t.Method;case 3:return t.Function;case 4:return t.Constructor;case 5:return t.Field;case 6:return t.Variable;case 7:return t.Class;case 8:return t.Interface;case 9:return t.Module;case 10:return t.Property;case 11:return t.Unit;case 12:return t.Value;case 13:return t.Enum;case 14:return t.Keyword;case 15:return t.Snippet;case 16:return t.Color;case 17:return t.File;case 18:return t.Reference;case 19:return t.Folder;case 20:return t.EnumMember;case 21:return t.Constant;case 22:return t.Struct;case 23:return t.Event;case 24:return t.Operator;case 25:return t.TypeParameter;default:return t.Variable}}static lspToMonacoRange(e){const{start:t,end:n}=e;return{startLineNumber:t.line+1,startColumn:t.character+1,endLineNumber:n.line+1,endColumn:n.character+1}}static monacoToLspPosition(e){return{line:e.lineNumber-1,character:e.column-1}}constructor(e){super(e),this.handleCompletionRequest=this.handleCompletionRequest.bind(this),this.handleSignatureRequest=this.handleSignatureRequest.bind(this),this.handleHoverRequest=this.handleHoverRequest.bind(this)}componentDidMount(){const{language:e,session:t}=this.props;this.registeredCompletionProvider=yn.registerCompletionItemProvider(e,{provideCompletionItems:this.handleCompletionRequest,triggerCharacters:[".",'"',"'"]}),t.getSignatureHelp&&(this.registeredSignatureProvider=yn.registerSignatureHelpProvider(e,{provideSignatureHelp:this.handleSignatureRequest,signatureHelpTriggerCharacters:["(",","]})),t.getHover&&(this.registeredHoverProvider=yn.registerHoverProvider(e,{provideHover:this.handleHoverRequest}))}componentWillUnmount(){this.registeredCompletionProvider?.dispose(),this.registeredSignatureProvider?.dispose(),this.registeredHoverProvider?.dispose()}registeredCompletionProvider;registeredSignatureProvider;registeredHoverProvider;handleCompletionRequest(e,t,n){const{model:s,session:i}=this.props;if(e!==s)return null;const o={textDocument:{uri:`${e.uri}`,version:e.getVersionId()},position:js.monacoToLspPosition(t),context:n},l=i.getCompletionItems(o);return Ln.debug("Requested completion items",o),l.then(d=>(Ln.debug("Completion items received: ",o,d),{incomplete:!0,suggestions:d.map(u=>{const{label:m,kind:g,detail:p,documentation:C,sortText:f,filterText:b,textEdit:w,insertTextFormat:S}=u;return{label:m,kind:js.lspToMonacoKind(g),detail:p,documentation:C?.kind==="markdown"?C:C?.value,sortText:f,filterText:b,insertText:w.text,insertTextRules:S===2?4:S,range:js.lspToMonacoRange(w.range)}})})).catch(d=>(Ln.error("There was an error retrieving completion items",d),{suggestions:[]}))}handleSignatureRequest(e,t,n,s){const i={value:{signatures:[],activeSignature:0,activeParameter:0},dispose:()=>{}},{model:o,session:l}=this.props;if(e!==o||!l.getSignatureHelp)return null;const a={textDocument:{uri:`${e.uri}`,version:e.getVersionId()},position:js.monacoToLspPosition(t),context:s},d=l.getSignatureHelp(a);return Ln.debug("Requested signature help",a),d.then(u=>{Ln.debug("Signatures received: ",a,d);const m=u.map(p=>{const{label:C,documentation:f,parameters:b}=p;return{documentation:f?.kind==="markdown"?f:f?.value,label:C,parameters:b??[]}});if(m.length===0)return i;const g=0;return{value:{signatures:m,activeSignature:g,activeParameter:u[g].activeParameter},dispose:()=>{}}}).catch(u=>(Ln.error("There was an error retrieving completion items",u),i))}handleHoverRequest(e,t){const{model:n,session:s}=this.props;if(e!==n||!s.getHover)return null;const i={textDocument:{uri:`${e.uri}`,version:e.getVersionId()},position:js.monacoToLspPosition(t)},o=s.getHover(i);return Ln.debug("Requested hover",i),o.then(a=>{Ln.debug("Hover received: ",i,a);const{contents:d}=a;return{contents:d?[d]:[]}}).catch(a=>(Ln.error("There was an error retrieving hover",a),{contents:[]}))}render(){return null}}const hh=js;const Ca=ne.module("ConsoleInput"),sl=parseInt(pe["line-height"],10),uh=6,mh=6,wf=sl+uh+mh,ba=100;class Cr extends v.PureComponent{static defaultProps={maxHeight:sl*10,scope:null,disabled:!1};static INPUT_CLASS_NAME="console-input";constructor(e){super(e),this.handleWindowResize=this.handleWindowResize.bind(this),this.commandContainer=de.createRef(),this.commandHistoryIndex=null,this.timestamp=Date.now(),this.bufferIndex=0,this.history=[],this.modifiedCommands=new Map,this.state={commandEditorHeight:sl,isFocused:!1,model:null}}componentDidMount(){this.initCommandEditor(),window.addEventListener("resize",this.handleWindowResize),this.loadMoreHistory()}componentDidUpdate(){this.layoutEditor()}componentWillUnmount(){window.removeEventListener("resize",this.handleWindowResize),this.loadingPromise!=null&&this.loadingPromise.cancel(),this.destroyCommandEditor()}cancelListener;commandContainer;commandEditor;commandHistoryIndex;commandSuggestionContainer;loadingPromise;timestamp;bufferIndex;history;modifiedCommands;setConsoleText(e,t=!0,n=!1){e&&(Ca.debug("Command received: ",e),n||(this.commandHistoryIndex=null,this.commandEditor?.setValue(e)),t&&this.focusEnd(),this.updateDimensions(),n&&this.processCommand(e))}initCommandEditor(){const{language:e,session:t}=this.props,n={copyWithSyntaxHighlighting:!1,cursorStyle:"block",fixedOverflowWidgets:!0,folding:!1,fontFamily:"Fira Mono",glyphMargin:!1,language:e,lineHeight:sl,lineDecorationsWidth:3,lineNumbers:"off",minimap:{enabled:!1},renderLineHighlight:"none",scrollBeyondLastLine:!1,scrollbar:{arrowSize:0,horizontal:"hidden",horizontalScrollbarSize:0},padding:{top:uh,bottom:mh},tabCompletion:"on",value:"",wordWrap:"on"},s=this.commandContainer.current;N(s),this.commandEditor=Gn.create(s,n),_t.setEOL(this.commandEditor),_t.openDocument(this.commandEditor,t),this.commandEditor.onDidChangeModelContent(()=>{const i=this.commandEditor?.getValue();this.modifiedCommands.set(this.commandHistoryIndex,i??null),this.updateDimensions()}),this.commandEditor.onDidFocusEditorText(()=>{this.setState({isFocused:!0})}),this.commandEditor.onDidBlurEditorText(()=>{this.setState({isFocused:!1})}),this.commandEditor.onKeyDown(i=>{const{commandEditor:o,commandHistoryIndex:l}=this,a=o?.getPosition();N(a);const{lineNumber:d}=a,h=o?.getModel();if(i.code==="ArrowUp"&&!this.isSuggestionMenuPopulated()&&d===1){l!=null?this.loadCommand(l+1):this.loadCommand(0),this.focusStart(),i.stopPropagation(),i.preventDefault();return}if(i.code==="ArrowDown"&&!this.isSuggestionMenuPopulated()&&d===h?.getLineCount()){l!=null&&l>0?this.loadCommand(l-1):this.loadCommand(null),this.focusEnd(),i.stopPropagation(),i.preventDefault();return}if(!i.altKey&&!i.shiftKey&&!i.metaKey)if(i.keyCode===ps.Enter){if(!this.isSuggestionMenuPopulated()){i.stopPropagation(),i.preventDefault();const u=this.commandEditor?.getValue().trim();u!==void 0&&(this.processCommand(u),this.commandEditor?.setValue(""))}}else i.keyCode===ps.Tab&&(this.isSuggestionMenuActive()?this.isSuggestionMenuPopulated()||(i.stopPropagation(),i.preventDefault()):(i.stopPropagation(),i.preventDefault(),this.commandEditor?.trigger("Tab key trigger suggestions","editor.action.triggerSuggest",{})))}),this.commandEditor.addCommand(tn.CtrlCmd|ps.KeyF,()=>{}),_t.removeConflictingKeybindings(this.commandEditor),_t.registerPasteHandler(this.commandEditor),this.commandEditor.focus(),this.updateDimensions(),this.setState({model:this.commandEditor.getModel()})}destroyCommandEditor(){const{session:e}=this.props;this.commandEditor&&(_t.closeDocument(this.commandEditor,e),this.commandEditor.dispose(),this.commandEditor=void 0)}handleWindowResize(){this.updateDimensions()}isSuggestionMenuActive(){return this.commandSuggestionContainer||(this.commandSuggestionContainer=this.commandEditor?.getDomNode()?.querySelector(".suggest-widget")),(this.commandSuggestionContainer&&this.commandSuggestionContainer.classList.contains("visible"))??!1}isSuggestionMenuPopulated(){return this.isSuggestionMenuActive()&&(this.commandSuggestionContainer?.querySelector(".monaco-list-rows")?.childElementCount??0)>0}focus(){this.commandEditor?.focus()}focusStart(){const e=this.commandEditor?.getModel();N(e);const t=e.getLineLength(1)+1,n=this.commandEditor?.getTopForPosition(1,t);N(n),this.commandEditor?.setPosition({lineNumber:1,column:t}),this.commandEditor?.setScrollTop(n),this.commandEditor?.focus()}focusEnd(){const e=this.commandEditor?.getModel();N(e);const t=e.getLineCount(),n=e.getLineLength(t)+1,s=this.commandEditor?.getTopForPosition(t,n);N(s),this.commandEditor?.setPosition({lineNumber:t,column:n}),this.commandEditor?.setScrollTop(s),this.commandEditor?.focus()}clear(){this.commandEditor?.focus(),this.commandEditor?.getModel()?.setValue(""),this.commandHistoryIndex=null}layoutEditor(){this.commandEditor&&this.commandEditor.layout()}loadCommand(e){if(e!==null&&e>=this.history.length)return;const t=this.modifiedCommands.get(e),n=e===null?"":this.history[this.history.length-e-1];this.commandHistoryIndex=e,this.commandEditor?.getModel()?.setValue(t??n),e!==null&&e>this.history.length-ba&&this.loadMoreHistory()}async loadMoreHistory(){try{if(this.loadingPromise!=null||this.bufferIndex==null)return;const{commandHistoryStorage:e,language:t,scope:n}=this.props;this.loadingPromise=ye.makeCancelable(e.getTable(t,n??"",this.timestamp),o=>o.close());const s=await this.loadingPromise;s.setReversed(!0),s.setViewport({top:this.bufferIndex,bottom:this.bufferIndex+ba-1}),this.loadingPromise=ye.makeCancelable(s.getViewportData(),()=>s.close());const i=await this.loadingPromise;this.bufferIndex+=ba,this.bufferIndex>=s.size&&(this.bufferIndex=null),this.history=[...i.items.filter(({name:o},l,a)=>l===0||o!==a[l-1].name).map(({name:o})=>o).reverse(),...this.history],this.loadingPromise=void 0,s.close()}catch(e){if(this.loadingPromise=void 0,ye.isCanceled(e)){Ca.debug2("Promise canceled, not loading history");return}Ca.error("Error fetching history",e)}}processCommand(e){this.commandHistoryIndex=null,this.modifiedCommands.clear(),N(e),e!==""&&(this.history.length===0||e!==this.history[this.history.length-1])&&this.history.push(e),this.updateDimensions();const{onSubmit:t}=this.props;t(e)}updateDimensions(){if(!this.commandEditor)return;const{maxHeight:e}=this.props;N(e);const t=this.commandEditor.getContentHeight(),n=Math.max(Math.min(t,e),wf),i={overviewRulerLanes:t>n?void 0:0};this.setState({commandEditorHeight:n},()=>{this.commandEditor?.updateOptions(i),this.commandEditor?.layout()})}render(){const{disabled:e,language:t,session:n}=this.props,{commandEditorHeight:s,isFocused:i,model:o}=this.state;return r.jsx("div",{className:Y("console-input-wrapper",{disabled:e}),children:r.jsxs("div",{className:Y("console-input-inner-wrapper",{focus:i}),children:[r.jsx("div",{className:Cr.INPUT_CLASS_NAME,ref:this.commandContainer,style:{height:s}}),o&&r.jsx(hh,{model:o,language:t,session:n})]})})}}const yd=Cr;const Rd="pasted values",vf=[/^audio.*/,/^font.*/,/^image.*/,/^video.*/],Sa=[".csv",".tsv",".tab",".psv",".dsv",".txt"],xd=[".zip"];class Hs extends v.Component{static defaultProps={allowZip:!1,dragError:null};static MULTIPLE_FILE_ERROR="Please select only one file";static FILE_TYPE_ERROR="Filetype not supported.";static isValidDropItem(e){return e!=null&&e.kind==="file"&&!vf.find(t=>t.test(e.type))}static isValidExtension(e,t=!1){return Sa.some(n=>e.endsWith(n))||t&&xd.some(n=>e.endsWith(n))}static handleDragOver(e){e.preventDefault(),e.stopPropagation()}static getIcon(e){return e===Rd?fd:e.endsWith(".csv")?sg:e.endsWith(".zip")?ig:og}constructor(e){super(e),this.handleSelectFile=this.handleSelectFile.bind(this),this.handleFiles=this.handleFiles.bind(this),this.handleDrop=this.handleDrop.bind(this),this.unstageFile=this.unstageFile.bind(this),this.handleMenuPaste=this.handleMenuPaste.bind(this),this.handlePasteEvent=this.handlePasteEvent.bind(this),this.fileElem=de.createRef(),this.divElem=de.createRef(),this.state={selectedFileName:""}}componentDidMount(){this.divElem.current?.addEventListener("paste",this.handlePasteEvent),this.divElem.current?.focus()}componentWillUnmount(){this.divElem.current?.removeEventListener("paste",this.handlePasteEvent)}fileElem;divElem;handleSelectFile(){this.fileElem.current&&(this.fileElem.current.value="",this.fileElem.current?.click())}handleFiles(e){e.stopPropagation(),e.preventDefault();const{files:t}=e.target;t!=null&&this.handleFile(t[0])}handleDrop(e){const{allowZip:t,clearDragError:n,dragError:s}=this.props;if(e.preventDefault(),e.stopPropagation(),s!=null){n();return}if(e.dataTransfer==null||e.dataTransfer.items==null||e.dataTransfer.items.length===0)return;const i=e.dataTransfer.items[0].getAsFile();N(i),Hs.isValidExtension(i.name,t)?this.handleFile(i):this.setState({dropError:Hs.FILE_TYPE_ERROR})}unstageFile(e){const{onCancel:t}=this.props;e.stopPropagation(),e.preventDefault(),t(),this.setState({selectedFileName:"",dropError:void 0})}handleFile(e){const{onFileOpened:t}=this.props;t(e),this.setState({selectedFileName:e.name,dropError:void 0})}handleMenuPaste(){const{onPaste:e,onError:t,uploadInProgress:n}=this.props;n||navigator.clipboard.readText().then(s=>{e(s),this.setState({selectedFileName:Rd,dropError:void 0})}).catch(s=>t(s))}handlePasteEvent(e){e.stopPropagation(),e.preventDefault(),this.handleMenuPaste()}makeContextMenuItems(){const{uploadInProgress:e}=this.props;return[{title:"Paste",icon:fd,action:this.handleMenuPaste,shortcut:Kn.PASTE,disabled:e}]}getValidExtensions=ge(e=>e?[...Sa,...xd]:[...Sa]);getAcceptString=ge(e=>this.getValidExtensions(e).join(", "));getFileTypeErrorString=ge(e=>en.join(this.getValidExtensions(e),"or"));render(){const{allowZip:e,dragError:t,uploadInProgress:n}=this.props,{selectedFileName:s,dropError:i}=this.state,o=t??i,l=this.makeContextMenuItems();return r.jsxs("div",{ref:this.divElem,className:"csv-overlay fill-parent-absolute",onDragOver:Hs.handleDragOver,onDrop:this.handleDrop,tabIndex:-1,children:[r.jsx(ie,{actions:l}),r.jsx("input",{ref:this.fileElem,type:"file",id:"fileElem",accept:this.getAcceptString(e),style:{display:"none"},onChange:this.handleFiles,"data-testid":"fileElem"}),!s&&(o===void 0||o==="")&&r.jsxs("div",{className:"message-content",children:[r.jsx("div",{className:"message-icon",children:r.jsx(ee,{icon:lg})}),r.jsx("label",{children:"Drop file (or paste values) here to import"}),r.jsx("div",{className:"message-small",children:r.jsx("label",{children:"or"})}),r.jsx(B,{kind:"primary",onClick:this.handleSelectFile,children:"Select File..."})]}),s&&(o===void 0||o==="")&&r.jsxs("div",{className:"selected-content",children:[r.jsx("div",{className:"selected-icon",children:r.jsx(ee,{icon:Hs.getIcon(s)})}),r.jsxs("div",{className:"selected-text",children:[r.jsx("label",{children:"Selected File"}),r.jsxs("label",{className:"selected-name",children:[s,!n&&r.jsx(B,{kind:"ghost",className:"ml-2",onClick:this.unstageFile,icon:Gt,tooltip:"Remove"})]})]})]}),Boolean(o)&&r.jsxs("div",{className:"message-content",children:[r.jsx("div",{className:"message-icon",children:r.jsx(ee,{icon:ws})}),r.jsx("label",{children:o}),o===Hs.FILE_TYPE_ERROR&&r.jsx("div",{className:"message-small",children:r.jsx("label",{children:this.getFileTypeErrorString(e)})})]})]})}}const ui=Hs;class Tf{static INTEGER="int";static LONG="long";static DOUBLE="double";static BOOLEAN="bool";static STRING="string";static DATE_TIME="datetime";static LOCAL_TIME="localtime"}const _e=Tf,Dd="unknown",Ef=2147483647,yf=-2147483648,Id=/^[0-9]{4}-[0-1][0-9]-[0-3][0-9][ T][0-2][0-9]:[0-5][0-9]:[0-6][0-9](?:\.[0-9]{1,9})?(?: [a-zA-Z]+)?$/,Fd=/^([0-9]+T)?([0-9]+):([0-9]+)(:[0-9]+)?(?:\.[0-9]{1,9})?$/;class yt{static determineType(e,t,n){if(!e||e===n)return t;switch(t){case _e.STRING:return _e.STRING;case _e.INTEGER:return yt.checkInteger(e);case _e.LONG:return yt.checkLong(e);case _e.DOUBLE:return yt.checkDouble(e);case _e.BOOLEAN:return yt.checkBoolean(e);case _e.DATE_TIME:return yt.checkDateTime(e);case _e.LOCAL_TIME:return yt.checkLocalTime(e);default:return yt.getTypeFromUnknown(e)}}static isNotParsableNumber(e){return isNaN(e)||e==="Infinity"||e==="-Infinity"}static checkInteger(e){const t=e.replace(/,/g,"");return yt.isNotParsableNumber(t)?_e.STRING:yt.getNumberType(t)}static checkLong(e){const t=e.replace(/,/g,"");return yt.isNotParsableNumber(t)?_e.STRING:t.includes(".")?_e.DOUBLE:_e.LONG}static checkDouble(e){const t=e.replace(/,/g,"");return yt.isNotParsableNumber(t)?_e.STRING:_e.DOUBLE}static checkBoolean(e){const t=e.toLowerCase();return t==="true"||t==="false"?_e.BOOLEAN:_e.STRING}static checkDateTime(e){return Id.test(e)?_e.DATE_TIME:_e.STRING}static checkLocalTime(e){return Fd.test(e)?_e.LOCAL_TIME:_e.STRING}static getTypeFromUnknown(e){const t=e.replace(/,/g,"");if(yt.isNotParsableNumber(t)){const n=e.toLowerCase();return n==="true"||n==="false"?_e.BOOLEAN:Id.test(e)&&e.includes(":")?_e.DATE_TIME:Fd.test(e)?_e.LOCAL_TIME:_e.STRING}return yt.getNumberType(t)}static getNumberType(e){if(e.includes("."))return _e.DOUBLE;const t=e.startsWith("-")?11:10;if(e.length>t)return _e.LONG;const n=parseInt(e,10);return n>Ef||n<yf?_e.LONG:_e.INTEGER}constructor(e,t,n,s,i,o,l,a,d,h){this.onFileCompleted=e,this.file=t,this.readHeaders=n,this.nullString=i,this.onProgress=o,this.onError=l,this.chunks=0,this.totalChunks=a,this.isZip=d,this.shouldTrim=h,this.zipProgress=0,this.handleChunk=this.handleChunk.bind(this),this.handleComplete=this.handleComplete.bind(this),this.handleError=this.handleError.bind(this),this.handleNodeUpdate=this.handleNodeUpdate.bind(this),this.config={...s,error:this.handleError,chunk:this.handleChunk,complete:this.handleComplete}}onFileCompleted;file;readHeaders;nullString;onProgress;onError;types;chunks;totalChunks;isZip;shouldTrim;zipProgress;config;parse(){const e=this.isZip?this.file.nodeStream("nodebuffer",this.handleNodeUpdate):this.file;Pa.parse(e,this.config)}handleChunk(e,t){let{data:n}=e;if(!this.types){if(n==null||n.length===0){t.abort(),this.onError("Error parsing CSV: no data in file.");return}this.types=new Array(n[0].length).fill(Dd),this.readHeaders&&(n=n.slice(1))}N(this.types);const s=[...this.types];n.forEach(l=>{if(l.length>=s.length){for(let a=0;a<s.length;a+=1)s[a]=yt.determineType(this.shouldTrim?l[a].trim():l[a],s[a],this.nullString);this.types=s}else t.abort(),this.onError(`Error parsing CSV: Insufficient data in row.
1
+ import{C as r,G as ee,A as v,I as sm,B as z,F as Y,J as jc,H as de,K as ge,L as Pa,M as vs,N as Ye,O as Re,P as Hc,Q as st,S as sr,T as im,U as om,V as lm,W as am,X as ce,R as al,Y as rd,Z as qe,_ as ir,$ as rm,a0 as dm,a1 as Bc,a2 as Oe,a3 as ja,E as cm,D as Wt,a4 as Pl,a5 as Uc,a6 as or,a7 as hm,a8 as Rn,a9 as um,aa as mm,ab as gm,ac as pm,ad as Ha,ae as fm,af as Cm,ag as bm,ah as dd,ai as Sm,aj as cd,ak as wm,al as vm,am as Tm,an as Em,ao as ym,ap as Rm,aq as St,ar as Vc,as as xm,at as $c,au as Dm,av as Wc,aw as Im,ax as Fm,ay as Nm,az as km,aA as hd,aB as Mm}from"./vendor-4a7e2c7c.js";import{P as ye,s as I,T as jl,B,a as N,S as We,M as ve,K as xe,G as Kn,b as en,C as ie,c as nn,D as Vn,d as Di,e as Hl,f as ot,g as ho,I as yi,U as Lm,h as be,i as F,j as Xs,F as $n,k as gn,u as lr,E as ke,l as k,m as Pn,n as Ts,o as nl,p as ct,q as Ke,r as dt,t as Bl,v as Om,O as Bn,w as Am,x as hn,y as rn,z as _m,A as Pm,R as Ul,H as Wn,J as Vl,L as Gc,N as zc,Q as jm,V as Hm,W as ud,X as ze,Y as md,Z as Kc,_ as ar,$ as gd,a0 as oo,a1 as Yc,a2 as Bm,a3 as qc,a4 as Um,a5 as sn,a6 as Vm,a7 as $m,a8 as Wm,a9 as Gm,aa as zm,ab as Km,ac as Ym,ad as qm,ae as Xm,af as Zm,ag as Qm,ah as Jm}from"./useConnection-d93998de.js";import{e as Gn,l as yn,K as tn,a as pd,R as eg,b as ps,W as tg}from"./monaco-6eaf53f7.js";import{v as Ba,d as ng,a as Xc,b as rr,L as In,c as uo,e as Un,f as Zc,g as ne,h as fd,i as sg,j as ig,k as og,l as lg,m as Gt,n as ws,o as Qc,p as zn,q as $l,r as Ri,s as ag,t as rg,u as Cd,w as rl,x as bd,y as Jc,z as dg,A as mo,B as eh,C as cg,D as hg,T as Je,E as dr,F as cr,G as dl,H as Mn,I as ug,J as mg,K as gg,M as pg,N as fg,O as hr,P as Es,Q as Sd,R as go,S as ur,U as mr,V as th,W as Cg,X as Wl,Y as bg,Z as cl,_ as Sg,$ as gr,a0 as nh,a1 as Ws,a2 as wg,a3 as vg,a4 as Tg,a5 as Eg,a6 as yg,a7 as Rg,a8 as wd,a9 as pa,aa as xg,ab as Dg,ac as Ig,ad as Gl,ae as zl,af as Fg,ag as Ng,ah as Kl,ai as sh,aj as kg,ak as Mg,al as Lg,am as ih,an as Og,ao as Ag,ap as _g,aq as Pg,ar as jg,as as Hg,at as Bg,au as Ug,av as Vg,aw as $g,ax as Wg,ay as Gg,az as zg,aA as oh,aB as Kg,aC as Ua,aD as Va,aE as Yg,aF as qg,aG as Xg,aH as Zg,aI as Qg,aJ as Jg,aK as ep,aL as tp,aM as np,aN as sp,aO as ip,aP as op,aQ as lp,aR as vd,aS as ap,aT as rp,aU as dp}from"./index-fa08e3d2.js";import{P as hl,b as cp,h as hp,p as up,o as mp,s as gp,t as pp,c as fa}from"./plotly-788bff8c.js";import"./helpers-042e6b4d.js";class pr{static isDark(e){const t=document.createElement("div");t.style.display="none",t.style.color=e;const n=getComputedStyle(document.body.appendChild(t)).color,s=n.match(/\d+/g);let i=[];if(s)i=s.map(l=>parseInt(l,10));else throw new Error(`Invalid color received. Got ${n}`);return document.body.removeChild(t),pr.getBrightness(i)<125}static getBrightness(e){return Math.round((e[0]*299+e[1]*587+e[2]*114)/1e3)}}const lh=pr,fp="table_",Td="column_",Cp=new Set(["in","not","i","ii","k"]),bp=new Set(["abstract","continue","for","new","switch","assert","default","if","package","synchronized","boolean","do","goto","private","this","break","double","implements","protected","throw","byte","else","import","public","throws","case","enum","instanceof","return","transient","catch","extends","int","short","try","char","final","interface","static","void","class","finally","long","strictfp","volatile","const","float","native","super","while","null","true","false"]),Sp=/[^a-zA-Z0-9_$+@-]/g,wp=/[^A-Za-z0-9_$]/g;class Ps{static legalize=(e,t,n,s,i)=>{let o=e.trim().replace(/[- ]/g,"_");return s&&(Cp.has(o)||bp.has(o))&&(o=t+o),o=o.replace(n,""),o||(o=t+i),Number.isNaN(Number(o.charAt(0)))||(o=t+o),o};static legalizeTableName=e=>Ps.legalize(e,fp,Sp,!1,0);static legalizeColumnNames=e=>{const t=[];return e.forEach((n,s)=>{let i=Ps.legalizeColumnName(n,s);t.includes(i)&&(i=Td+s),t.push(i)}),t};static legalizeColumnName=(e,t=0)=>Ps.legalize(e,Td,wp,!0,t);static isValidTableName=e=>Ps.legalizeTableName(e)===e;static isValidColumnName=e=>Ps.legalizeColumnName(e)===e}const Ii=Ps;function vp(c,e){return c?c.closest(`.${e}`):null}const Tp={getClosestByClassName:vp};class Ep{pending=[];resolved=[];add(e,t){const n=ye.makeCancelable(e,t);return this.pending.push(n),n.then(()=>{this.resolve(n)},()=>{this.resolve(n)}),n}remove(e){for(let t=0;t<this.pending.length;t+=1)if(this.pending[t]===e){this.pending.splice(t,1);return}}resolve(e){this.remove(e),this.resolved.push(e)}cancel(){const e=[...this.pending,...this.resolved];for(let t=0;t<e.length;t+=1)e[t].cancel();this.pending=[],this.resolved=[]}}const Yn=Ep;class yp extends Error{isInvalid=!0}const vi=yp;function ah({type:c}){switch(c){case I.VariableType.TABLE:case I.VariableType.TABLEMAP:case I.VariableType.TREETABLE:case I.VariableType.HIERARCHICALTABLE:return r.jsx(ee,{icon:rr});case I.VariableType.FIGURE:return r.jsx(ee,{icon:Xc});case I.VariableType.PANDAS:return r.jsx(ee,{icon:ng});default:return r.jsx(ee,{icon:Ba})}}class Rp extends v.Component{constructor(e){super(e),this.container=null}componentDidMount(){this.colorize()}container;colorize(){const{children:e}=this.props;this.container&&e!=null&&Gn.colorizeElement(this.container,{theme:"dh-dark"})}render(){const{children:e,language:t}=this.props;return r.jsx("div",{children:r.jsx("div",{"data-lang":t,ref:n=>{this.container=n},style:{pointerEvents:"none"},children:e})})}}const Yl=Rp;class xp{static get LANGUAGE_MAP(){return new Map([["python","Python"],["groovy","Groovy"],["scala","Scala"]])}}const rh=xp;class ul{static hasComment(e){return e.comment!==void 0}static hasPattern(e){return e.pattern!==void 0}static hasOp(e){return e.op!==void 0}static parseArguments(e){return e==null||!(typeof e=="string"||e instanceof String)?[]:sm.parse(e).filter(t=>!this.hasComment(t)).map(t=>this.hasPattern(t)?t.pattern:this.hasOp(t)?t.op:`${t}`)}static formatTimestamp(e){if(e==null||!(e instanceof Date))return null;const t=`${e.getHours()}`.padStart(2,"0"),n=`${e.getMinutes()}`.padStart(2,"0"),s=`${e.getSeconds()}`.padStart(2,"0"),i=`${e.getMilliseconds()}`.padStart(3,"0");return`${t}:${n}:${s}.${i}`}static isTableType(e){return e===I.VariableType.TABLE||e===I.VariableType.TREETABLE||e===I.VariableType.HIERARCHICALTABLE}static isWidgetType(e){return e===I.VariableType.FIGURE||e===I.VariableType.OTHERWIDGET||e===I.VariableType.PANDAS}static isOpenableType(e){return ul.isTableType(e)||ul.isWidgetType(e)}static isFigureType(e){return e===I.VariableType.FIGURE}static isPandas(e){return e===I.VariableType.PANDAS}}const $a=ul;function ch({children:c}){return r.jsxs("div",{className:"console-history-item-result",children:[r.jsx("div",{className:"console-history-gutter",children:"-"}),r.jsx("div",{className:"console-history-content",children:c})]})}ch.propTypes={children:z.node.isRequired};class Dp extends v.Component{static defaultProps={disabled:!1};constructor(e){super(e),this.updateElapsed=this.updateElapsed.bind(this),this.startTime=Date.now(),this.state={elapsed:0}}componentDidMount(){this.timer=setInterval(this.updateElapsed,1e3)}componentWillUnmount(){this.timer&&clearInterval(this.timer),this.timer=void 0}timer;startTime;updateElapsed(){this.setState({elapsed:Math.round((Date.now()-this.startTime)/1e3)})}render(){const{disabled:e,onCancelClick:t}=this.props,{elapsed:n}=this.state;return r.jsx("div",{className:Y("console-history-result-in-progress",{disabled:e}),children:r.jsxs("span",{className:"badge",children:[r.jsx(In,{})," Running... ",jl.formatElapsedTime(n)," ",r.jsx(B,{className:"console-history-result-in-progress-cancel",kind:"ghost",icon:uo,tooltip:"Cancel",onClick:t,disabled:e})]})})}}const Ip=Dp;class ml extends v.PureComponent{static defaultProps={message:""};static mouseDragThreshold=5;constructor(e){super(e),this.handleKeyPress=this.handleKeyPress.bind(this),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseMove=this.handleMouseMove.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this),this.handleToggleError=this.handleToggleError.bind(this),this.handleMouseEnter=this.handleMouseEnter.bind(this),this.handleMouseLeave=this.handleMouseLeave.bind(this),this.mouseX=null,this.mouseY=null,this.isClicking=!1,this.state={isExpanded:!1,isTriggerHovered:!1}}mouseX;mouseY;isClicking;handleKeyPress(e){switch(e.key){case"Enter":case" ":this.handleToggleError(),e.stopPropagation(),e.preventDefault();break}}handleMouseDown(e){this.mouseX=e.clientX,this.mouseY=e.clientY,this.isClicking=!0}handleMouseMove(e){this.mouseX!=null&&this.mouseY!=null?(Math.abs(e.clientX-this.mouseX)>=ml.mouseDragThreshold||Math.abs(e.clientY-this.mouseY)>=ml.mouseDragThreshold)&&(this.isClicking=!1):this.isClicking&&(this.isClicking=!1)}handleMouseUp(e){this.isClicking&&!e.shiftKey&&!e.metaKey&&!e.altKey&&this.handleToggleError(),this.mouseX=null,this.mouseY=null,this.isClicking=!1}handleToggleError(){this.setState(e=>({isExpanded:!e.isExpanded}))}handleMouseEnter(){this.setState({isTriggerHovered:!0})}handleMouseLeave(){this.setState({isTriggerHovered:!1})}render(){const{isExpanded:e,isTriggerHovered:t}=this.state,{message:n}=this.props;N(n);const s=n.indexOf(`
2
+ `),i=s>-1;let o=n;i&&(o=n.slice(0,s));const l=n.slice(s),a=t?"error-btn-link error-btn-link--active":"error-btn-link";return r.jsxs("div",{className:Y("error-message",{expanded:e}),children:[i&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"error-gutter",children:r.jsx("button",{type:"button",onClick:this.handleToggleError,className:a,tabIndex:-1,children:r.jsx(ee,{icon:e?Un:Zc,transform:"left-3"})})}),r.jsxs("div",{className:"error-content",children:[r.jsx("div",{className:"console-error-text-trigger",role:"button",tabIndex:0,onKeyPress:this.handleKeyPress,onMouseDown:this.handleMouseDown,onMouseMove:this.handleMouseMove,onMouseEnter:this.handleMouseEnter,onMouseLeave:this.handleMouseLeave,onMouseUp:this.handleMouseUp,children:o}),e?l:""]})]}),!i&&r.jsx("div",{className:"error-content",children:r.jsx("div",{className:"console-error-text",children:o})})]},"error")}}const Fp=ml;const Ed=ne.module("ConsoleHistoryItem");class Np extends v.PureComponent{static defaultProps={disabled:!1};constructor(e){super(e),this.handleCancelClick=this.handleCancelClick.bind(this),this.handleObjectClick=this.handleObjectClick.bind(this)}handleObjectClick(e){Ed.debug("handleObjectClick",e);const{openObject:t}=this.props;t(e)}handleCancelClick(){const{item:e}=this.props;e!=null&&e.cancelResult&&(Ed.debug(`Cancelling command: ${e.command}`),e.cancelResult())}render(){const{disabled:e,item:t,language:n}=this.props,{disabledObjects:s,result:i}=t;let o=null;t.command!=null&&t.command!==""&&(o=r.jsxs("div",{className:"console-history-item-command",children:[r.jsx("div",{className:"console-history-gutter",children:">"}),r.jsx("div",{className:"console-history-content",children:r.jsx(Yl,{language:n,children:t.command})})]}));const l=[];let a=!1;if(i){const{error:h,message:u,changes:m}=i;if(m){const{created:g,updated:p}=m;[...g,...p].forEach(C=>{a=!0;const{title:f}=C,b=`${f}`,w=e===void 0||e||(s??[]).indexOf(b)>=0,S=r.jsx(B,{kind:"primary",onClick:()=>this.handleObjectClick(C),className:"btn-console-object",disabled:w,icon:r.jsx(ah,{type:C.type}),children:f},b);l.push(S)})}if(h!=null&&t.command==null){let g=`${h.message??h}`;g||(g=h);const p=r.jsx(Fp,{message:g},"result-error");l.push(p)}if(u!==void 0&&u!==""){const g=r.jsx("div",{className:"log-message",children:u},"log-message");l.push(g)}}else{a=!0;const h=r.jsx(Ip,{onCancelClick:this.handleCancelClick,disabled:e},"in_progress");l.push(h)}let d=null;return l.length>0&&(d=r.jsx(ch,{children:l})),r.jsxs("div",{className:Y("console-command-result",{"console-result-buttons":a}),children:[o,d]})}}const kp=Np;class fr extends v.Component{static defaultProps={disabled:!1};static itemKey(e,t){return`${e}.${t.command}.${t.result&&t.result.message}.${t.result&&t.result.error}`}render(){const{disabled:e,items:t,language:n,openObject:s}=this.props,i=[];for(let o=0;o<t.length;o+=1){const l=t[o],a=r.jsx(kp,{disabled:e,item:l,openObject:s,language:n},fr.itemKey(o,l));i.push(a)}return r.jsx("div",{className:"container-fluid console-history",children:i})}}const Mp=fr,Lp={name:"Console",CLEAR:We.createAndAdd({id:"CONSOLE.CLEAR",name:"Clear",shortcut:[ve.CTRL,xe.L],macShortcut:[ve.CTRL,xe.C]}),FOCUS_HISTORY:We.createAndAdd({id:"CONSOLE.FOCUS_HISTORY",name:"Focus History",shortcut:[ve.CTRL,xe.H],macShortcut:[ve.CTRL,ve.OPTION,xe.H]})},Op={name:"Command History",FOCUS_HISTORY:We.createAndAdd({id:"COMMAND_HISTORY.FOCUS_HISTORY",name:"Focus History Search",shortcut:[ve.CTRL,xe.H],macShortcut:[ve.CTRL,ve.OPTION,xe.H]}),SEND_TO_CONSOLE:We.createAndAdd({id:"COMMAND_HISTORY.SEND_TO_CONSOLE",name:"Send to Console",shortcut:[xe.ENTER],macShortcut:[xe.ENTER]}),SEND_TO_NOTEBOOK:We.createAndAdd({id:"COMMAND_HISTORY.SEND_TO_NOTEBOOK",name:"Send to Notebook",shortcut:[ve.CTRL,xe.ENTER],macShortcut:[ve.CMD,xe.ENTER]}),RUN:We.createAndAdd({id:"COMMAND_HISTORY.RUN",name:"Run",shortcut:[ve.ALT,xe.R],macShortcut:[ve.OPTION,xe.R]})},Ap={name:"Notebook",RUN:We.createAndAdd({id:"NOTEBOOK.RUN",name:"Run",shortcut:[ve.ALT,xe.R],macShortcut:[ve.OPTION,xe.R]}),RUN_SELECTED:We.createAndAdd({id:"NOTEBOOK.RUN_SELECTED",name:"Run Selected",shortcut:[ve.ALT,ve.SHIFT,xe.R],macShortcut:[ve.OPTION,ve.SHIFT,xe.R]}),FIND:We.createAndAdd({id:"NOTEBOOK.FIND",name:"Find",shortcut:[ve.CTRL,xe.F],macShortcut:[ve.CMD,xe.F],isEditable:!1}),MINIMAP:We.createAndAdd({id:"NOTEBOOK.MINIMAP",name:"Show Minimap",shortcut:[ve.ALT,xe.M],macShortcut:[ve.OPTION,xe.M]}),WORDWRAP:We.createAndAdd({id:"NOTEBOOK.WORDWRAP",name:"Word Wrap",shortcut:[ve.ALT,xe.Z],macShortcut:[ve.OPTION,xe.Z]})},_p={CONSOLE:Lp,COMMAND_HISTORY:Op,NOTEBOOK:Ap},Nt=_p,Ct=Object.freeze({FATAL:"FATAL",STDERR:"STDERR",ERROR:"ERROR",WARN:"WARN",STDOUT:"STDOUT",INFO:"INFO",DEBUG:"DEBUG",TRACE:"TRACE"}),Pp="#2d2a2e",jp="#fcfcfa",Hp="#fcd65b",Bp="#b2b1b2",Up="#9edc6f",Vp="#76d9e4",$p="#f95d84",Wp="#aa9af4",Gp="#f95d84",zp="#fcfcfa",Kp="#7c7b7c",pe={"error-foreground":"#f95d84",background:Pp,foreground:jp,"line-height":"19px",string:Hp,"string-delim":"#929192",delimiter:Bp,predefined:Up,keyword:Vp,storage:$p,number:Wp,operator:Gp,identifier:zp,"namespace-identifier":"#f95d84","identifier-js":"#fcd65b",comment:Kp,"input-option-active-border":"#929192","focus-border":"rgba(72, 120, 234, 0.85)","input-background":"#555356","input-foreground":"#f0f0ee","input-border":"#929192","editor-line-number-foreground":"#929192","editor-selection-background":"#676368","editor-line-highlight-bg":"#373438","context-menu-background":"#555356","context-menu-foreground":"#f0f0ee","menu-selection-background":"#4878ea","log-date":"#929192","log-error":"#f95d84","log-info":"#76d9e4","log-stdout":"#f0f0ee","log-warn":"#fcd65b","log-debug":"#aa9af4","log-trace":"#9edc6f","editor-find-match-background":"#3c5595","editor-find-match-highlight-background":"#343e5d","editor-widget-background":"#403e41","input-option-active-background":"#4878ea","input-option-active-foreground":"#f0f0ee","editor-suggest-widget-background":"#403e41","editor-suggest-widget-border":"#5b5a5c","editor-suggest-widget-foreground":"#f0f0ee","editor-suggest-widget-selected-background":"#41475a","editor-suggest-widget-highlightForeground":"#4878ea","list-hover-background":"#555356","text-link-foreground":"#929192","text-link-active-foreground":"#f0f0ee","editor-link-active-foreground":"#f0f0ee"},Yp="python",qp={comments:{lineComment:"#",blockComment:["'''","'''"]},brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"',notIn:["string"]},{open:"'",close:"'",notIn:["string","comment"]}],surroundingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],onEnterRules:[{beforeText:/^\s*(?:def|class|for|if|elif|else|while|try|with|finally|except|async).*?:\s*$/,action:{indentAction:1}}],folding:{offSide:!0,markers:{start:/^\s*#region\b/,end:/^\s*#endregion\b/}}},Xp={keywords:["and","del","from","not","while","as","elif","global","or","with","assert","else","if","pass","yield","break","except","import","print","exec","in","raise","continue","finally","is","return","for","try",":","=","isinstance","__debug__"],storage:["class","def","async","lambda"],operators:["+","-","*","**","/","//","%","<<",">>","&","|","^","~","<",">","<=",">=","==","!=","<>","+=","-=","*=","/","//=","%=","&=","|=","^=",">>=","<<=","**="],brackets:[{open:"{",close:"}",token:"delimiter.curly"},{open:"[",close:"]",token:"delimiter.square"},{open:"(",close:")",token:"delimiter.parenthesis"}],symbols:/[=><!~&|+\-*/^%]+/,delimiters:/[;=.@:,`]/,escapes:/\\(?:[abfnrtv\\"'\n\r]|x[0-9A-Fa-f]{2}|[0-7]{3}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8}|N\{\w+\})/,rawpre:/(?:[rR]|ur|Ur|uR|UR|br|Br|bR|BR)/,strpre:/(?:[buBU])/,tokenizer:{root:[[/@strpre?("""|''')/,{token:"string.delim",bracket:"@open",next:"@mstring.$1"}],[/@strpre?"([^"\\]|\\.)*$/,"string.invalid"],[/@strpre?'([^'\\]|\\.)*$/,"string.invalid"],[/@strpre?(["])/,{token:"string.delim",bracket:"@open",next:"@sstring.$1",nextEmbedded:"deephavenDb"}],[/@strpre?(["'])/,{token:"string.delim",bracket:"@open",next:"@string.$1"}],[/@rawpre("""|''')/,{token:"string.delim",bracket:"@open",next:"@mrawstring.$1"}],[/@rawpre"([^"\\]|\\.)*$/,"string.invalid"],[/@rawpre'([^'\\]|\\.)*$/,"string.invalid"],[/@rawpre(["'])/,{token:"string.delim",bracket:"@open",next:"@rawstring.$1"}],[/__[\w$]*/,"predefined"],[/[a-z_$][\w$]*/,{cases:{"@keywords":"keyword","@storage":"storage","@default":"identifier"}}],[/[A-Z][\w]*/,{cases:{"~[A-Z0-9_]+":"constructor.identifier","@default":"namespace.identifier"}}],{include:"@whitespace"},[/[{}()[\]]/,"@brackets"],[/@symbols/,{cases:{"@keywords":"keyword","@operators":"operator","@default":""}}],[/\d*\.\d+([eE][-+]?\d+)?/,"number.float"],[/0[xX][0-9a-fA-F]+[lL]?/,"number.hex"],[/0[bB][0-1]+[lL]?/,"number.binary"],[/(0[oO][0-7]+|0[0-7]+)[lL]?/,"number.octal"],[/(0|[1-9]\d*)[lL]?/,"number"],[":",{token:"keyword",bracket:"@open"}],[/@delimiters/,{cases:{"@keywords":"keyword","@default":"delimiter"}}]],comment:[[/[^/*]+/,"comment"],[/\/\*/,"comment","@push"],["\\*/","comment","@pop"],[/[/*]/,"comment"]],mstring:[{include:"@strcontent"},[/"""|'''/,{cases:{"$#==$S2":{token:"string.delim",bracket:"@close",next:"@pop"},"@default":{token:"string"}}}],[/["']/,"string"],[/./,"string.invalid"]],sstring:[{include:"@strcontent"},[/["]/,{token:"string.delim",bracket:"@close",next:"@pop",nextEmbedded:"@pop"}],[/./,"string.invalid"]],string:[{include:"@strcontent"},[/[']/,{token:"string.delim",bracket:"@close",next:"@pop"}],[/./,"string.invalid"]],strcontent:[[/[^\\"']+/,"string"],[/\\$/,"string.escape"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"]],mrawstring:[{include:"@rawstrcontent"},[/"""|'''/,{cases:{"$#==$S2":{token:"string.delim",bracket:"@close",next:"@pop"},"@default":{token:"string"}}}],[/["']/,"string"],[/./,"string.invalid"]],rawstring:[{include:"@rawstrcontent"},[/["']/,{cases:{"$#==$S2":{token:"string.delim",bracket:"@close",next:"@pop"},"@default":{token:"string"}}}],[/./,"string.invalid"]],rawstrcontent:[[/[^\\"']+/,"string"],[/\\["']/,"string"],[/\\u[0-9A-Fa-f]{4}/,"string.escape"],[/\\/,"string"]],whitespace:[[/\s+/,"white"],[/(^#.*$)/,"comment"],[/'''/,"string","@endDocString"],[/"""/,"string","@endDblDocString"]],endDocString:[[/[^']+/,"string"],[/\\'/,"string"],[/'''/,"string","@popall"],[/'/,"string"]],endDblDocString:[[/[^"]+/,"string"],[/\\"/,"string"],[/"""/,"string","@popall"],[/"/,"string"]]}},Zp={id:Yp,conf:qp,language:Xp},Qp=Zp,Jp="groovy",ef={comments:{lineComment:"//",blockComment:["/*","*/"]},brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"',notIn:["string"]},{open:"'",close:"'",notIn:["string","comment"]}],surroundingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],onEnterRules:[{beforeText:/^\s*(?:def|class|for|if|elif|else|while|try|with|finally|except|async).*?:\s*$/,action:{indentAction:1}}],folding:{offSide:!0,markers:{start:/^\s*#region\b/,end:/^\s*#endregion\b/}}},tf={keywords:["and","del","from","not","while","as","elif","global","or","with","assert","else","if","pass","yield","break","except","import","print","println","class","exec","in","raise","continue","finally","is","return","def","for","lambda","try",":","=","isinstance","__debug__"],operators:["+","-","*","**","/","//","%","<<",">>","&","|","^","~","<",">","<=",">=","==","!=","<>","+=","-=","*=","/","//=","%=","&=","|=","^=",">>=","<<=","**="],brackets:[{open:"{",close:"}",token:"delimiter.curly"},{open:"[",close:"]",token:"delimiter.square"},{open:"(",close:")",token:"delimiter.parenthesis"}],symbols:/[=><!~&|+\-*/^%]+/,delimiters:/[;=.@:,`]/,escapes:/\\(?:[abfnrtv\\"'\n\r]|x[0-9A-Fa-f]{2}|[0-7]{3}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8}|N\{\w+\})/,rawpre:/(?:[rR]|ur|Ur|uR|UR|br|Br|bR|BR)/,strpre:/(?:[buBU])/,tokenizer:{root:[[/@strpre?("""|''')/,{token:"string.delim",bracket:"@open",next:"@mstring.$1"}],[/@strpre?"([^"\\]|\\.)*$/,"string.invalid"],[/@strpre?'([^'\\]|\\.)*$/,"string.invalid"],[/@strpre?(["])/,{token:"string.delim",bracket:"@open",next:"@sstring.$1",nextEmbedded:"deephavenDb"}],[/@strpre?(["'])/,{token:"string.delim",bracket:"@open",next:"@string.$1"}],[/@rawpre("""|''')/,{token:"string.delim",bracket:"@open",next:"@mrawstring.$1"}],[/@rawpre"([^"\\]|\\.)*$/,"string.invalid"],[/@rawpre'([^'\\]|\\.)*$/,"string.invalid"],[/@rawpre(["'])/,{token:"string.delim",bracket:"@open",next:"@rawstring.$1"}],[/__[\w$]*/,"predefined"],[/[a-z_$][\w$]*/,{cases:{"@keywords":"keyword","@default":"identifier"}}],[/[A-Z][\w]*/,{cases:{"~[A-Z0-9_]+":"constructor.identifier","@default":"namespace.identifier"}}],{include:"@whitespace"},[/[{}()[\]]/,"@brackets"],[/@symbols/,{cases:{"@keywords":"keyword","@operators":"operator","@default":""}}],[/\d*\.\d+([eE][-+]?\d+)?/,"number.float"],[/0[xX][0-9a-fA-F]+[lL]?/,"number.hex"],[/0[bB][0-1]+[lL]?/,"number.binary"],[/(0[oO][0-7]+|0[0-7]+)[lL]?/,"number.octal"],[/(0|[1-9]\d*)[lL]?/,"number"],[":",{token:"keyword",bracket:"@open"}],[/@delimiters/,{cases:{"@keywords":"keyword","@default":"delimiter"}}]],mstring:[{include:"@strcontent"},[/"""|'''/,{cases:{"$#==$S2":{token:"string.delim",bracket:"@close",next:"@pop"},"@default":{token:"string"}}}],[/["']/,"string"],[/./,"string.invalid"]],sstring:[{include:"@strcontent"},[/["]/,{token:"string.delim",bracket:"@close",next:"@pop",nextEmbedded:"@pop"}],[/./,"string.invalid"]],string:[{include:"@strcontent"},[/[']/,{token:"string.delim",bracket:"@close",next:"@pop"}],[/./,"string.invalid"]],strcontent:[[/[^\\"']+/,"string"],[/\\$/,"string.escape"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"]],mrawstring:[{include:"@rawstrcontent"},[/"""|'''/,{cases:{"$#==$S2":{token:"string.delim",bracket:"@close",next:"@pop"},"@default":{token:"string"}}}],[/["']/,"string"],[/./,"string.invalid"]],rawstring:[{include:"@rawstrcontent"},[/["']/,{cases:{"$#==$S2":{token:"string.delim",bracket:"@close",next:"@pop"},"@default":{token:"string"}}}],[/./,"string.invalid"]],rawstrcontent:[[/[^\\"']+/,"string"],[/\\["']/,"string"],[/\\u[0-9A-Fa-f]{4}/,"string.escape"],[/\\/,"string"]],whitespace:[[/[ \t\r\n]+/,""],[/\/\*\*(?!\/)/,"comment.doc","@doccomment"],[/\/\*/,"comment","@comment"],[/\/\/.*$/,"comment"]],comment:[[/[^/*]+/,"comment"],[/\*\//,"comment","@pop"],[/[/*]/,"comment"]],doccomment:[[/[^/*]+/,"comment.doc"],[/\*\//,"comment.doc","@pop"],[/[/*]/,"comment.doc"]]}},nf={id:Jp,conf:ef,language:tf},sf=nf,of="scala",lf={wordPattern:/(unary_[@~!#%^&*()\-=+\\|:<>/?]+)|([a-zA-Z_$][\w$]*?_=)|(`[^`]+`)|([a-zA-Z_$][\w$]*)/g,comments:{lineComment:"//",blockComment:["/*","*/"]},brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],surroundingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],folding:{markers:{start:/^\s*\/\/\s*(?:(?:#?region\b)|(?:<editor-fold\b))/,end:/^\s*\/\/\s*(?:(?:#?endregion\b)|(?:<\/editor-fold>))/}}},af={keywords:["asInstanceOf","catch","class","classOf","def","do","else","extends","finally","for","foreach","forSome","if","import","isInstanceOf","macro","match","new","object","package","return","throw","trait","try","type","until","val","var","while","with","yield","given","enum","then"],softKeywords:["as","export","extension","end","derives","on"],constants:["true","false","null","this","super"],modifiers:["abstract","final","implicit","lazy","override","private","protected","sealed"],softModifiers:["inline","opaque","open","transparent","using"],name:/(?:[a-z_$][\w$]*|`[^`]+`)/,type:/(?:[A-Z][\w$]*)/,symbols:/[=><!~?:&|+\-*/^\\%@#]+/,digits:/\d+(_+\d+)*/,hexdigits:/[[0-9a-fA-F]+(_+[0-9a-fA-F]+)*/,escapes:/\\(?:[btnfr\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,fstring_conv:/[bBhHsScCdoxXeEfgGaAt]|[Tn](?:[HIklMSLNpzZsQ]|[BbhAaCYyjmde]|[RTrDFC])/,tokenizer:{root:[[/\braw"""/,{token:"string.quote",bracket:"@open",next:"@rawstringt"}],[/\braw"/,{token:"string.quote",bracket:"@open",next:"@rawstring"}],[/\bs"""/,{token:"string.quote",bracket:"@open",next:"@sstringt"}],[/\bs"/,{token:"string.quote",bracket:"@open",next:"@sstring"}],[/\bf""""/,{token:"string.quote",bracket:"@open",next:"@fstringt"}],[/\bf"/,{token:"string.quote",bracket:"@open",next:"@fstring"}],[/"""/,{token:"string.quote",bracket:"@open",next:"@stringt"}],[/"/,{token:"string.quote",bracket:"@open",next:"@string"}],[/(@digits)[eE]([-+]?(@digits))?[fFdD]?/,"number.float","@allowMethod"],[/(@digits)\.(@digits)([eE][-+]?(@digits))?[fFdD]?/,"number.float","@allowMethod"],[/0[xX](@hexdigits)[Ll]?/,"number.hex","@allowMethod"],[/(@digits)[fFdD]/,"number.float","@allowMethod"],[/(@digits)[lL]?/,"number","@allowMethod"],[/\b_\*/,"key"],[/\b(_)\b/,"keyword","@allowMethod"],[/\bimport\b/,"keyword","@import"],[/\b(case)([ \t]+)(class)\b/,["keyword.modifier","white","keyword"]],[/\bcase\b/,"keyword","@case"],[/\bva[lr]\b/,"keyword","@vardef"],[/\b(def)([ \t]+)((?:unary_)?@symbols|@name(?:_=)|@name)/,["keyword","white","identifier"]],[/@name(?=[ \t]*:(?!:))/,"variable"],[/(\.)(@name|@symbols)/,[{token:"operator"},{token:"@rematch",next:"@allowMethod"}]],[/([{(])(\s*)(@name(?=\s*=>))/,["@brackets","white","variable"]],[/@name/,{cases:{"@keywords":"keyword","@softKeywords":"keyword","@modifiers":"keyword.modifier","@softModifiers":"keyword.modifier","@constants":{token:"constant",next:"@allowMethod"},"@default":{token:"identifier",next:"@allowMethod"}}}],[/@type/,"type","@allowMethod"],{include:"@whitespace"},[/@[a-zA-Z_$][\w$]*(?:\.[a-zA-Z_$][\w$]*)*/,"annotation"],[/[{(]/,"@brackets"],[/[})]/,"@brackets","@allowMethod"],[/\[/,"operator.square"],[/](?!\s*(?:va[rl]|def|type)\b)/,"operator.square","@allowMethod"],[/]/,"operator.square"],[/([=-]>|<-|>:|<:|:>|<%)(?=[\s\w()[\]{},."'`])/,"keyword"],[/@symbols/,"operator"],[/[;,.]/,"delimiter"],[/'[a-zA-Z$][\w$]*(?!')/,"attribute.name"],[/'[^\\']'/,"string","@allowMethod"],[/(')(@escapes)(')/,[{token:"string"},{token:"string.escape"},{token:"string",next:"@allowMethod"}]],[/'/,"string.invalid"]],import:[[/;/,"delimiter","@pop"],[/^|$/,"","@pop"],[/[ \t]+/,"white"],[/[\n\r]+/,"white","@pop"],[/\/\*/,"comment","@comment"],[/@name|@type/,"type"],[/[(){}]/,"@brackets"],[/[[\]]/,"operator.square"],[/[.,]/,"delimiter"]],allowMethod:[[/^|$/,"","@pop"],[/[ \t]+/,"white"],[/[\n\r]+/,"white","@pop"],[/\/\*/,"comment","@comment"],[/(?==>[\s\w([{])/,"keyword","@pop"],[/(@name|@symbols)(?=[ \t]*[[({"'`]|[ \t]+(?:[+-]?\.?\d|\w))/,{cases:{"@keywords":{token:"keyword",next:"@pop"},"->|<-|>:|<:|<%":{token:"keyword",next:"@pop"},"@default":{token:"@rematch",next:"@pop"}}}],["","","@pop"]],comment:[[/[^/*]+/,"comment"],[/\/\*/,"comment","@push"],[/\*\//,"comment","@pop"],[/[/*]/,"comment"]],case:[[/\b_\*/,"key"],[/\b(_|true|false|null|this|super)\b/,"keyword","@allowMethod"],[/\bif\b|=>/,"keyword","@pop"],[/`[^`]+`/,"identifier","@allowMethod"],[/@name/,"variable","@allowMethod"],[/:::?|\||@(?![a-z_$])/,"keyword"],{include:"@root"}],vardef:[[/\b_\*/,"key"],[/\b(_|true|false|null|this|super)\b/,"keyword"],[/@name/,"variable"],[/:::?|\||@(?![a-z_$])/,"keyword"],[/=|:(?!:)/,"operator","@pop"],[/$/,"white","@pop"],{include:"@root"}],string:[[/[^\\"\n\r]+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/"/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}]],stringt:[[/[^\\"\n\r]+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/"(?=""")/,"string"],[/"""/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}],[/"/,"string"]],fstring:[[/@escapes/,"string.escape"],[/"/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}],[/\$\$/,"string"],[/(\$)([a-z_]\w*)/,["operator","identifier"]],[/\$\{/,"operator","@interp"],[/%%/,"string"],[/(%)([-#+ 0,(])(\d+|\.\d+|\d+\.\d+)(@fstring_conv)/,["metatag","keyword.modifier","number","metatag"]],[/(%)(\d+|\.\d+|\d+\.\d+)(@fstring_conv)/,["metatag","number","metatag"]],[/(%)([-#+ 0,(])(@fstring_conv)/,["metatag","keyword.modifier","metatag"]],[/(%)(@fstring_conv)/,["metatag","metatag"]],[/./,"string"]],fstringt:[[/@escapes/,"string.escape"],[/"(?=""")/,"string"],[/"""/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}],[/\$\$/,"string"],[/(\$)([a-z_]\w*)/,["operator","identifier"]],[/\$\{/,"operator","@interp"],[/%%/,"string"],[/(%)([-#+ 0,(])(\d+|\.\d+|\d+\.\d+)(@fstring_conv)/,["metatag","keyword.modifier","number","metatag"]],[/(%)(\d+|\.\d+|\d+\.\d+)(@fstring_conv)/,["metatag","number","metatag"]],[/(%)([-#+ 0,(])(@fstring_conv)/,["metatag","keyword.modifier","metatag"]],[/(%)(@fstring_conv)/,["metatag","metatag"]],[/./,"string"]],sstring:[[/@escapes/,"string.escape"],[/"/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}],[/\$\$/,"string"],[/(\$)([a-z_]\w*)/,["operator","identifier"]],[/\$\{/,"operator","@interp"],[/./,"string"]],sstringt:[[/@escapes/,"string.escape"],[/"(?=""")/,"string"],[/"""/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}],[/\$\$/,"string"],[/(\$)([a-z_]\w*)/,["operator","identifier"]],[/\$\{/,"operator","@interp"],[/./,"string"]],interp:[[/{/,"operator","@push"],[/}/,"operator","@pop"],{include:"@root"}],rawstring:[[/[^"]/,"string"],[/"/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}]],rawstringt:[[/[^"]/,"string"],[/"(?=""")/,"string"],[/"""/,{token:"string.quote",bracket:"@close",switchTo:"@allowMethod"}],[/"/,"string"]],whitespace:[[/[ \t\r\n]+/,"white"],[/\/\*/,"comment","@comment"],[/\/\/.*$/,"comment"]]}},rf={id:of,conf:lf,language:af},df=rf,cf="deephavenDb",hf={comments:{lineComment:"#",blockComment:["'''","'''"]},brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"',notIn:["string"]},{open:"'",close:"'",notIn:["string","comment"]}],surroundingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],onEnterRules:[{beforeText:/^\s*(?:def|class|for|if|elif|else|while|try|with|finally|except|async).*?:\s*$/,action:{indentAction:1}}],folding:{offSide:!0,markers:{start:/^\s*#region\b/,end:/^\s*#endregion\b/}}},uf={tokenPostfix:".js",keywords:["boolean","break","byte","case","catch","char","class","const","continue","debugger","default","delete","do","double","else","enum","export","extends","false","final","finally","float","for","function","goto","if","implements","import","in","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","super","switch","synchronized","this","throw","throws","transient","true","try","typeof","var","void","volatile","while","with"],builtins:["define","require","window","document","undefined"],operators:["=",">","<","!","~","?",":","==","<=",">=","!=","&&","||","++","--","+","-","*","/","&","|","^","%","<<",">>",">>>","+=","-=","*=","/=","&=","|=","^=","%=","<<=",">>=",">>>="],brackets:[{open:"{",close:"}",token:"delimiter.curly"},{open:"[",close:"]",token:"delimiter.bracket"},{open:"(",close:")",token:"delimiter.parenthesis"}],symbols:/[~!@#%\^&*-+=|\\:`<>.?\/]+/,escapes:/\\(?:[btnfr\\"']|[0-7][0-7]?|[0-3][0-7]{2})/,exponent:/[eE][\-+]?[0-9]+/,regexpctl:/[(){}\[\]\$\^|\-*+?\.]/,regexpesc:/\\(?:[bBdDfnrstvwWn0\\\/]|@regexpctl|c[A-Z]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4})/,tokenizer:{root:[[/([a-zA-Z_\$][\w\$]*)(\s*)(:?)/,{cases:{"$1@keywords":["keyword","white","delimiter"],$3:["key.identifier","white","delimiter"],"$1@builtins":["predefined.identifier","white","delimiter"],"@default":["identifier","white","delimiter"]}}],{include:"@whitespace"},[/\/(?=([^\\\/]|\\.)+\/)/,{token:"regexp.slash",bracket:"@open",next:"@regexp"}],[/[{}()\[\]]/,"@brackets"],[/[;,.]/,"delimiter"],[/@symbols/,{cases:{"@operators":"operator","@default":""}}],[/\d+\.\d*(@exponent)?/,"number.float"],[/\.\d+(@exponent)?/,"number.float"],[/\d+@exponent/,"number.float"],[/0[xX][\da-fA-F]+/,"number.hex"],[/0[0-7]+/,"number.octal"],[/\d+/,"number"],[/"([^"\\]|\\.)*$/,"string.invalid"],[/'([^'\\]|\\.)*$/,"string.invalid"],[/"/,"string",'@string."'],[/'/,"string","@string.'"]],whitespace:[[/[ \t\r\n]+/,"white"],[/\/\*/,"comment","@comment"],[/\/\/.*$/,"comment"]],comment:[[/[^\/*]+/,"comment"],[/\/\*/,"comment.invalid"],["\\*/","comment","@pop"],[/[\/*]/,"comment"]],string:[[/[^\\"']+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/["']/,{cases:{"$#==$S2":{token:"string",next:"@pop"},"@default":"string"}}]],regexp:[[/(\{)(\d+(?:,\d*)?)(\})/,["@brackets.regexp.escape.control","regexp.escape.control","@brackets.regexp.escape.control"]],[/(\[)(\^?)(?=(?:[^\]\\\/]|\\.)+)/,[{token:"@brackets.regexp.escape.control"},{token:"regexp.escape.control",next:"@regexrange"}]],[/(\()(\?:|\?=|\?!)/,["@brackets.regexp.escape.control","regexp.escape.control"]],[/[()]/,"@brackets.regexp.escape.control"],[/@regexpctl/,"regexp.escape.control"],[/[^\\\/]/,"regexp"],[/@regexpesc/,"regexp.escape"],[/\\\./,"regexp.invalid"],["/",{token:"regexp.slash",bracket:"@close"},"@pop"]],regexrange:[[/-/,"regexp.escape.control"],[/\^/,"regexp.invalid"],[/@regexpesc/,"regexp.escape"],[/[^\]]/,"regexp"],[/\]/,"@brackets.regexp.escape.control","@pop"]]}},mf={id:cf,conf:hf,language:uf},gf=mf,pf="log",ff={},Cf={tokenizer:{root:[[/ FATAL[\s\S]*/,{token:"error",next:"@error"}],[/ ERROR[\s\S]*/,{token:"error",next:"@error"}],[/ STDERR[\s\S]*/,{token:"error",next:"@error"}],[/ STDOUT.*/,{token:"stdout",next:"@stdout"}],[/ INFO[\s\S]*/,{token:"info",next:"@info"}],[/ WARN.*/,{token:"warn",next:"@warn"}],[/ TRACE[\s\S]*/,{token:"trace",next:"@trace"}],[/ DEBUG[.\s\S]*/,{token:"debug",next:"@debug"}],[/^\d{2}:\d{2}:\d{2}.\d{3}/,"date"]],error:[{include:"@body"}],info:[{include:"@body"}],warn:[{include:"@body"}],stdout:[{include:"@body"}],trace:[{include:"@body"}],debug:[{include:"@body"}],body:[[/^\d{2}:\d{2}:\d{2}.\d{3}/,{token:"date",next:"@pop"}],[/[\s\S]*/,{token:"$S0"}]]}},bf={id:pf,conf:ff,language:Cf},Sf=bf,bn=ne.module("MonacoUtils");class wn{static init({getWorker:e}={}){bn.debug("Initializing Monaco..."),e!==void 0&&wn.registerGetWorker(e);const{registerLanguages:t,removeHashtag:n}=wn,s=[{token:"",foreground:n(pe.foreground)},{token:"string",foreground:n(pe.string)},{token:"string.delim",foreground:n(pe["string-delim"])},{token:"keyword",foreground:n(pe.keyword)},{token:"identifier.js",foreground:n(pe["identifier-js"])},{token:"delimiter",foreground:n(pe.delimiter)},{token:"comment",foreground:n(pe.comment)},{token:"number",foreground:n(pe.number)},{token:"storage",foreground:n(pe.storage)},{token:"identifier",foreground:n(pe.identifier)},{token:"namespace.identifier",foreground:n(pe["namespace-identifier"])},{token:"operator",foreground:n(pe.operator)},{token:"predefined",foreground:n(pe.predefined)},{token:"error.log",foreground:pe["log-error"].substring(1)},{token:"warn.log",foreground:n(pe["log-warn"])},{token:"info.log",foreground:n(pe["log-info"])},{token:"stdout.log",foreground:n(pe["log-stdout"])},{token:"trace.log",foreground:n(pe["log-trace"])},{token:"debug.log",foreground:n(pe["log-debug"])},{token:"date.log",foreground:n(pe["log-date"])}],i={errorForeground:pe["error-foreground"],"inputOption.activeBorder":pe["input-option-active-border"],"editor.background":pe.background,"editor.foreground":pe.foreground,"editor.lineHighlightBackground":pe["editor-line-highlight-bg"],"editorLineNumber.foreground":pe["editor-line-number-foreground"],"editor.selectionBackground":pe["editor-selection-background"],"editor.findMatchBackground":pe["editor-find-match-background"],"editor.findMatchHighlightBackground":pe["editor-find-match-highlight-background"],"editorSuggestWidget.background":pe["editor-suggest-widget-background"],"editorSuggestWidget.border":pe["editor-suggest-widget-border"],"editorSuggestWidget.foreground":pe["editor-suggest-widget-foreground"],"editorSuggestWidget.selectedBackground":pe["editor-suggest-widget-selected-background"],"editorSuggestWidget.highlightForeground":pe["editor-suggest-widget-highlightForeground"],"list.hoverBackground":pe["list-hover-background"],"dropdown.background":pe["context-menu-background"],"dropdown.foreground":pe["context-menu-foreground"],"menu.selectionBackground":pe["menu-selection-background"],"list.focusBackground":pe["menu-selection-background"],"editorWidget.background":pe["editor-widget-background"],"inputOption.activeBackground":pe["input-option-active-background"],"inputOption.activeForeground":pe["input-option-active-foreground"],focusBorder:pe["focus-border"],"input.background":pe["input-background"],"input.foreground":pe["input-foreground"],"input.border":pe["input-border"],"textLink.foreground":pe["text-link-foreground"],"textLink.activeForeground":pe["text-link-active-foreground"],"editorLink.activeForeground":pe["editor-link-active-foreground"]};Gn.defineTheme("dh-dark",{base:"vs-dark",inherit:!0,rules:s,colors:i}),bn.debug2("monaco theme: ",pe),Gn.setTheme("dh-dark"),t([gf,Qp,sf,Sf,df]),bn.debug("Monaco initialized.")}static registerGetWorker(e){window.MonacoEnvironment={...window.MonacoEnvironment,getWorker:e}}static removeHashtag(e){return e.substring(1)}static registerLanguages(e){const t=e.map(({id:n})=>n);yn.getLanguages().filter(({id:n})=>t.includes(n)).forEach(n=>{const s=n;bn.debug2("Overriding default language loader:",s.id)}),e.forEach(n=>{wn.registerLanguage(n)})}static registerLanguage(e){bn.debug2("Registering language: ",e.id),yn.register(e),yn.onLanguage(e.id,()=>{yn.setLanguageConfiguration(e.id,e.conf),yn.setMonarchTokensProvider(e.id,e.language)})}static setEOL(e,t=Gn.EndOfLineSequence.LF){e.getModel()?.setEOL(t)}static openDocument(e,t){const n=e.getModel();N(n);const s={textDocument:{uri:`${n.uri}`,languageId:n.getLanguageId(),version:n.getVersionId(),text:n.getValue()}};return bn.debug2("didOpenDocumentParams: ",s),t.openDocument(s),e.onDidChangeModelContent(o=>{const{changes:l,versionId:a}=o,d=[];for(let h=0;h<l.length;h+=1){const u=l[h],{range:m,rangeLength:g,text:p}=u,C={range:{start:{line:m.startLineNumber-1,character:m.startColumn-1},end:{line:m.endLineNumber-1,character:m.endColumn-1}},rangeLength:g,text:p};d.push(C)}if(d.length>0){const h={textDocument:{version:a,uri:`${n.uri}`},contentChanges:d};bn.debug2("didChangeDocumentParams",h),t.changeDocument(h)}})}static closeDocument(e,t){const n=e.getModel();N(n);const s={textDocument:{uri:`${n.uri}`}};t.closeDocument(s)}static registerPasteHandler(e){e.onDidPaste(t=>{const n=/“|”/g,s=/\u200b/g,i=/\u00A0/g,o=e.getModel();N(o);const l=o.getValueInRange(t.range);(n.test(l)||s.test(l)||i.test(l))&&o.applyEdits([{range:t.range,text:l.replace(n,'"').replace(s,"").replace(i," ")}])})}static isMacPlatform(){const{platform:e}=window.navigator;return e.startsWith("Mac")}static removeConflictingKeybindings(e){const t=[{windows:"ctrl+D",mac:"meta+D"},{windows:"ctrl+H"}];try{t.forEach(n=>{wn.isMacPlatform()&&n.mac===""||!wn.isMacPlatform()&&n.windows===""||wn.removeKeybinding(e,wn.isMacPlatform()?n.mac:n.windows)})}catch(n){bn.error(n)}}static removeKeybinding(e,t){if(t===void 0)return;const n=e._standaloneKeybindingService._getResolver()._map.get(t);n!=null?n.forEach(s=>{bn.debug2(`Removing Monaco keybinding ${t} for ${s.command}`),e._standaloneKeybindingService.addDynamicKeybinding(`-${s.command}`,null,()=>{})}):bn.warn(`Did not find any keybindings to remove for ${t}`)}static getMonacoKeyCodeFromShortcut(e){const{keyState:t}=e,{keyValue:n}=t;return n===null?0:wn.isMacPlatform()?(t.metaKey?tn.CtrlCmd:0)|(t.shiftKey?tn.Shift:0)|(t.altKey?tn.Alt:0)|(t.ctrlKey?tn.WinCtrl:0)|pd.fromString(n):(t.ctrlKey?tn.CtrlCmd:0)|(t.shiftKey?tn.Shift:0)|(t.altKey?tn.Alt:0)|(t.metaKey?tn.WinCtrl:0)|pd.fromString(n)}static provideLinks(e){const t=[];for(let n=1;n<=e.getLineCount();n+=1){const s=e.getLineContent(n);jc(s).filter(l=>l.type==="url"?/^https?:\/\//.test(l.value):!0).forEach(l=>{t.push({url:l.href,range:new eg(n,l.start+1,n,l.end+1)})})}return{links:t}}}const At=wn,Ln=ne.module("MonacoCompletionProvider");class js extends v.PureComponent{static lspToMonacoKind(e){const t=yn.CompletionItemKind;switch(e){case 1:return t.Text;case 2:return t.Method;case 3:return t.Function;case 4:return t.Constructor;case 5:return t.Field;case 6:return t.Variable;case 7:return t.Class;case 8:return t.Interface;case 9:return t.Module;case 10:return t.Property;case 11:return t.Unit;case 12:return t.Value;case 13:return t.Enum;case 14:return t.Keyword;case 15:return t.Snippet;case 16:return t.Color;case 17:return t.File;case 18:return t.Reference;case 19:return t.Folder;case 20:return t.EnumMember;case 21:return t.Constant;case 22:return t.Struct;case 23:return t.Event;case 24:return t.Operator;case 25:return t.TypeParameter;default:return t.Variable}}static lspToMonacoRange(e){const{start:t,end:n}=e;return{startLineNumber:t.line+1,startColumn:t.character+1,endLineNumber:n.line+1,endColumn:n.character+1}}static monacoToLspPosition(e){return{line:e.lineNumber-1,character:e.column-1}}constructor(e){super(e),this.handleCompletionRequest=this.handleCompletionRequest.bind(this),this.handleSignatureRequest=this.handleSignatureRequest.bind(this),this.handleHoverRequest=this.handleHoverRequest.bind(this)}componentDidMount(){const{language:e,session:t}=this.props;this.registeredCompletionProvider=yn.registerCompletionItemProvider(e,{provideCompletionItems:this.handleCompletionRequest,triggerCharacters:[".",'"',"'"]}),t.getSignatureHelp&&(this.registeredSignatureProvider=yn.registerSignatureHelpProvider(e,{provideSignatureHelp:this.handleSignatureRequest,signatureHelpTriggerCharacters:["(",","]})),t.getHover&&(this.registeredHoverProvider=yn.registerHoverProvider(e,{provideHover:this.handleHoverRequest}))}componentWillUnmount(){this.registeredCompletionProvider?.dispose(),this.registeredSignatureProvider?.dispose(),this.registeredHoverProvider?.dispose()}registeredCompletionProvider;registeredSignatureProvider;registeredHoverProvider;handleCompletionRequest(e,t,n){const{model:s,session:i}=this.props;if(e!==s)return null;const o={textDocument:{uri:`${e.uri}`,version:e.getVersionId()},position:js.monacoToLspPosition(t),context:n},l=i.getCompletionItems(o);return Ln.debug("Requested completion items",o),l.then(d=>(Ln.debug("Completion items received: ",o,d),{incomplete:!0,suggestions:d.map(u=>{const{label:m,kind:g,detail:p,documentation:C,sortText:f,filterText:b,textEdit:w,insertTextFormat:S}=u;return{label:m,kind:js.lspToMonacoKind(g),detail:p,documentation:C?.kind==="markdown"?C:C?.value,sortText:f,filterText:b,insertText:w.text,insertTextRules:S===2?4:S,range:js.lspToMonacoRange(w.range)}})})).catch(d=>(Ln.error("There was an error retrieving completion items",d),{suggestions:[]}))}handleSignatureRequest(e,t,n,s){const i={value:{signatures:[],activeSignature:0,activeParameter:0},dispose:()=>{}},{model:o,session:l}=this.props;if(e!==o||!l.getSignatureHelp)return null;const a={textDocument:{uri:`${e.uri}`,version:e.getVersionId()},position:js.monacoToLspPosition(t),context:s},d=l.getSignatureHelp(a);return Ln.debug("Requested signature help",a),d.then(u=>{Ln.debug("Signatures received: ",a,d);const m=u.map(p=>{const{label:C,documentation:f,parameters:b}=p;return{documentation:f?.kind==="markdown"?f:f?.value,label:C,parameters:b??[]}});if(m.length===0)return i;const g=0;return{value:{signatures:m,activeSignature:g,activeParameter:u[g].activeParameter},dispose:()=>{}}}).catch(u=>(Ln.error("There was an error retrieving completion items",u),i))}handleHoverRequest(e,t){const{model:n,session:s}=this.props;if(e!==n||!s.getHover)return null;const i={textDocument:{uri:`${e.uri}`,version:e.getVersionId()},position:js.monacoToLspPosition(t)},o=s.getHover(i);return Ln.debug("Requested hover",i),o.then(a=>{Ln.debug("Hover received: ",i,a);const{contents:d}=a;return{contents:d?[d]:[]}}).catch(a=>(Ln.error("There was an error retrieving hover",a),{contents:[]}))}render(){return null}}const hh=js;const Ca=ne.module("ConsoleInput"),sl=parseInt(pe["line-height"],10),uh=6,mh=6,wf=sl+uh+mh,ba=100;class Cr extends v.PureComponent{static defaultProps={maxHeight:sl*10,scope:null,disabled:!1};static INPUT_CLASS_NAME="console-input";constructor(e){super(e),this.handleWindowResize=this.handleWindowResize.bind(this),this.commandContainer=de.createRef(),this.commandHistoryIndex=null,this.timestamp=Date.now(),this.bufferIndex=0,this.history=[],this.modifiedCommands=new Map,this.state={commandEditorHeight:sl,isFocused:!1,model:null}}componentDidMount(){this.initCommandEditor(),window.addEventListener("resize",this.handleWindowResize),this.loadMoreHistory()}componentDidUpdate(){this.layoutEditor()}componentWillUnmount(){window.removeEventListener("resize",this.handleWindowResize),this.loadingPromise!=null&&this.loadingPromise.cancel(),this.destroyCommandEditor()}cancelListener;commandContainer;commandEditor;commandHistoryIndex;commandSuggestionContainer;loadingPromise;timestamp;bufferIndex;history;modifiedCommands;setConsoleText(e,t=!0,n=!1){e&&(Ca.debug("Command received: ",e),n||(this.commandHistoryIndex=null,this.commandEditor?.setValue(e)),t&&this.focusEnd(),this.updateDimensions(),n&&this.processCommand(e))}initCommandEditor(){const{language:e,session:t}=this.props,n={copyWithSyntaxHighlighting:!1,cursorStyle:"block",fixedOverflowWidgets:!0,folding:!1,fontFamily:"Fira Mono",glyphMargin:!1,language:e,lineHeight:sl,lineDecorationsWidth:3,lineNumbers:"off",minimap:{enabled:!1},renderLineHighlight:"none",scrollBeyondLastLine:!1,scrollbar:{arrowSize:0,horizontal:"hidden",horizontalScrollbarSize:0},padding:{top:uh,bottom:mh},tabCompletion:"on",value:"",wordWrap:"on"},s=this.commandContainer.current;N(s),this.commandEditor=Gn.create(s,n),At.setEOL(this.commandEditor),At.openDocument(this.commandEditor,t),this.commandEditor.onDidChangeModelContent(()=>{const i=this.commandEditor?.getValue();this.modifiedCommands.set(this.commandHistoryIndex,i??null),this.updateDimensions()}),this.commandEditor.onDidFocusEditorText(()=>{this.setState({isFocused:!0})}),this.commandEditor.onDidBlurEditorText(()=>{this.setState({isFocused:!1})}),this.commandEditor.onKeyDown(i=>{const{commandEditor:o,commandHistoryIndex:l}=this,a=o?.getPosition();N(a);const{lineNumber:d}=a,h=o?.getModel();if(i.code==="ArrowUp"&&!this.isSuggestionMenuPopulated()&&d===1){l!=null?this.loadCommand(l+1):this.loadCommand(0),this.focusStart(),i.stopPropagation(),i.preventDefault();return}if(i.code==="ArrowDown"&&!this.isSuggestionMenuPopulated()&&d===h?.getLineCount()){l!=null&&l>0?this.loadCommand(l-1):this.loadCommand(null),this.focusEnd(),i.stopPropagation(),i.preventDefault();return}if(!i.altKey&&!i.shiftKey&&!i.metaKey)if(i.keyCode===ps.Enter){if(!this.isSuggestionMenuPopulated()){i.stopPropagation(),i.preventDefault();const u=this.commandEditor?.getValue().trim();u!==void 0&&(this.processCommand(u),this.commandEditor?.setValue(""))}}else i.keyCode===ps.Tab&&(this.isSuggestionMenuActive()?this.isSuggestionMenuPopulated()||(i.stopPropagation(),i.preventDefault()):(i.stopPropagation(),i.preventDefault(),this.commandEditor?.trigger("Tab key trigger suggestions","editor.action.triggerSuggest",{})))}),this.commandEditor.addCommand(tn.CtrlCmd|ps.KeyF,()=>{}),At.removeConflictingKeybindings(this.commandEditor),At.registerPasteHandler(this.commandEditor),this.commandEditor.focus(),this.updateDimensions(),this.setState({model:this.commandEditor.getModel()})}destroyCommandEditor(){const{session:e}=this.props;this.commandEditor&&(At.closeDocument(this.commandEditor,e),this.commandEditor.dispose(),this.commandEditor=void 0)}handleWindowResize(){this.updateDimensions()}isSuggestionMenuActive(){return this.commandSuggestionContainer||(this.commandSuggestionContainer=this.commandEditor?.getDomNode()?.querySelector(".suggest-widget")),(this.commandSuggestionContainer&&this.commandSuggestionContainer.classList.contains("visible"))??!1}isSuggestionMenuPopulated(){return this.isSuggestionMenuActive()&&(this.commandSuggestionContainer?.querySelector(".monaco-list-rows")?.childElementCount??0)>0}focus(){this.commandEditor?.focus()}focusStart(){const e=this.commandEditor?.getModel();N(e);const t=e.getLineLength(1)+1,n=this.commandEditor?.getTopForPosition(1,t);N(n),this.commandEditor?.setPosition({lineNumber:1,column:t}),this.commandEditor?.setScrollTop(n),this.commandEditor?.focus()}focusEnd(){const e=this.commandEditor?.getModel();N(e);const t=e.getLineCount(),n=e.getLineLength(t)+1,s=this.commandEditor?.getTopForPosition(t,n);N(s),this.commandEditor?.setPosition({lineNumber:t,column:n}),this.commandEditor?.setScrollTop(s),this.commandEditor?.focus()}clear(){this.commandEditor?.focus(),this.commandEditor?.getModel()?.setValue(""),this.commandHistoryIndex=null}layoutEditor(){this.commandEditor&&this.commandEditor.layout()}loadCommand(e){if(e!==null&&e>=this.history.length)return;const t=this.modifiedCommands.get(e),n=e===null?"":this.history[this.history.length-e-1];this.commandHistoryIndex=e,this.commandEditor?.getModel()?.setValue(t??n),e!==null&&e>this.history.length-ba&&this.loadMoreHistory()}async loadMoreHistory(){try{if(this.loadingPromise!=null||this.bufferIndex==null)return;const{commandHistoryStorage:e,language:t,scope:n}=this.props;this.loadingPromise=ye.makeCancelable(e.getTable(t,n??"",this.timestamp),o=>o.close());const s=await this.loadingPromise;s.setReversed(!0),s.setViewport({top:this.bufferIndex,bottom:this.bufferIndex+ba-1}),this.loadingPromise=ye.makeCancelable(s.getViewportData(),()=>s.close());const i=await this.loadingPromise;this.bufferIndex+=ba,this.bufferIndex>=s.size&&(this.bufferIndex=null),this.history=[...i.items.filter(({name:o},l,a)=>l===0||o!==a[l-1].name).map(({name:o})=>o).reverse(),...this.history],this.loadingPromise=void 0,s.close()}catch(e){if(this.loadingPromise=void 0,ye.isCanceled(e)){Ca.debug2("Promise canceled, not loading history");return}Ca.error("Error fetching history",e)}}processCommand(e){this.commandHistoryIndex=null,this.modifiedCommands.clear(),N(e),e!==""&&(this.history.length===0||e!==this.history[this.history.length-1])&&this.history.push(e),this.updateDimensions();const{onSubmit:t}=this.props;t(e)}updateDimensions(){if(!this.commandEditor)return;const{maxHeight:e}=this.props;N(e);const t=this.commandEditor.getContentHeight(),n=Math.max(Math.min(t,e),wf),i={overviewRulerLanes:t>n?void 0:0};this.setState({commandEditorHeight:n},()=>{this.commandEditor?.updateOptions(i),this.commandEditor?.layout()})}render(){const{disabled:e,language:t,session:n}=this.props,{commandEditorHeight:s,isFocused:i,model:o}=this.state;return r.jsx("div",{className:Y("console-input-wrapper",{disabled:e}),children:r.jsxs("div",{className:Y("console-input-inner-wrapper",{focus:i}),children:[r.jsx("div",{className:Cr.INPUT_CLASS_NAME,ref:this.commandContainer,style:{height:s}}),o&&r.jsx(hh,{model:o,language:t,session:n})]})})}}const yd=Cr;const Rd="pasted values",vf=[/^audio.*/,/^font.*/,/^image.*/,/^video.*/],Sa=[".csv",".tsv",".tab",".psv",".dsv",".txt"],xd=[".zip"];class Hs extends v.Component{static defaultProps={allowZip:!1,dragError:null};static MULTIPLE_FILE_ERROR="Please select only one file";static FILE_TYPE_ERROR="Filetype not supported.";static isValidDropItem(e){return e!=null&&e.kind==="file"&&!vf.find(t=>t.test(e.type))}static isValidExtension(e,t=!1){return Sa.some(n=>e.endsWith(n))||t&&xd.some(n=>e.endsWith(n))}static handleDragOver(e){e.preventDefault(),e.stopPropagation()}static getIcon(e){return e===Rd?fd:e.endsWith(".csv")?sg:e.endsWith(".zip")?ig:og}constructor(e){super(e),this.handleSelectFile=this.handleSelectFile.bind(this),this.handleFiles=this.handleFiles.bind(this),this.handleDrop=this.handleDrop.bind(this),this.unstageFile=this.unstageFile.bind(this),this.handleMenuPaste=this.handleMenuPaste.bind(this),this.handlePasteEvent=this.handlePasteEvent.bind(this),this.fileElem=de.createRef(),this.divElem=de.createRef(),this.state={selectedFileName:""}}componentDidMount(){this.divElem.current?.addEventListener("paste",this.handlePasteEvent),this.divElem.current?.focus()}componentWillUnmount(){this.divElem.current?.removeEventListener("paste",this.handlePasteEvent)}fileElem;divElem;handleSelectFile(){this.fileElem.current&&(this.fileElem.current.value="",this.fileElem.current?.click())}handleFiles(e){e.stopPropagation(),e.preventDefault();const{files:t}=e.target;t!=null&&this.handleFile(t[0])}handleDrop(e){const{allowZip:t,clearDragError:n,dragError:s}=this.props;if(e.preventDefault(),e.stopPropagation(),s!=null){n();return}if(e.dataTransfer==null||e.dataTransfer.items==null||e.dataTransfer.items.length===0)return;const i=e.dataTransfer.items[0].getAsFile();N(i),Hs.isValidExtension(i.name,t)?this.handleFile(i):this.setState({dropError:Hs.FILE_TYPE_ERROR})}unstageFile(e){const{onCancel:t}=this.props;e.stopPropagation(),e.preventDefault(),t(),this.setState({selectedFileName:"",dropError:void 0})}handleFile(e){const{onFileOpened:t}=this.props;t(e),this.setState({selectedFileName:e.name,dropError:void 0})}handleMenuPaste(){const{onPaste:e,onError:t,uploadInProgress:n}=this.props;n||navigator.clipboard.readText().then(s=>{e(s),this.setState({selectedFileName:Rd,dropError:void 0})}).catch(s=>t(s))}handlePasteEvent(e){e.stopPropagation(),e.preventDefault(),this.handleMenuPaste()}makeContextMenuItems(){const{uploadInProgress:e}=this.props;return[{title:"Paste",icon:fd,action:this.handleMenuPaste,shortcut:Kn.PASTE,disabled:e}]}getValidExtensions=ge(e=>e?[...Sa,...xd]:[...Sa]);getAcceptString=ge(e=>this.getValidExtensions(e).join(", "));getFileTypeErrorString=ge(e=>en.join(this.getValidExtensions(e),"or"));render(){const{allowZip:e,dragError:t,uploadInProgress:n}=this.props,{selectedFileName:s,dropError:i}=this.state,o=t??i,l=this.makeContextMenuItems();return r.jsxs("div",{ref:this.divElem,className:"csv-overlay fill-parent-absolute",onDragOver:Hs.handleDragOver,onDrop:this.handleDrop,tabIndex:-1,children:[r.jsx(ie,{actions:l}),r.jsx("input",{ref:this.fileElem,type:"file",id:"fileElem",accept:this.getAcceptString(e),style:{display:"none"},onChange:this.handleFiles,"data-testid":"fileElem"}),!s&&(o===void 0||o==="")&&r.jsxs("div",{className:"message-content",children:[r.jsx("div",{className:"message-icon",children:r.jsx(ee,{icon:lg})}),r.jsx("label",{children:"Drop file (or paste values) here to import"}),r.jsx("div",{className:"message-small",children:r.jsx("label",{children:"or"})}),r.jsx(B,{kind:"primary",onClick:this.handleSelectFile,children:"Select File..."})]}),s&&(o===void 0||o==="")&&r.jsxs("div",{className:"selected-content",children:[r.jsx("div",{className:"selected-icon",children:r.jsx(ee,{icon:Hs.getIcon(s)})}),r.jsxs("div",{className:"selected-text",children:[r.jsx("label",{children:"Selected File"}),r.jsxs("label",{className:"selected-name",children:[s,!n&&r.jsx(B,{kind:"ghost",className:"ml-2",onClick:this.unstageFile,icon:Gt,tooltip:"Remove"})]})]})]}),Boolean(o)&&r.jsxs("div",{className:"message-content",children:[r.jsx("div",{className:"message-icon",children:r.jsx(ee,{icon:ws})}),r.jsx("label",{children:o}),o===Hs.FILE_TYPE_ERROR&&r.jsx("div",{className:"message-small",children:r.jsx("label",{children:this.getFileTypeErrorString(e)})})]})]})}}const ui=Hs;class Tf{static INTEGER="int";static LONG="long";static DOUBLE="double";static BOOLEAN="bool";static STRING="string";static DATE_TIME="datetime";static LOCAL_TIME="localtime"}const _e=Tf,Dd="unknown",Ef=2147483647,yf=-2147483648,Id=/^[0-9]{4}-[0-1][0-9]-[0-3][0-9][ T][0-2][0-9]:[0-5][0-9]:[0-6][0-9](?:\.[0-9]{1,9})?(?: [a-zA-Z]+)?$/,Fd=/^([0-9]+T)?([0-9]+):([0-9]+)(:[0-9]+)?(?:\.[0-9]{1,9})?$/;class yt{static determineType(e,t,n){if(!e||e===n)return t;switch(t){case _e.STRING:return _e.STRING;case _e.INTEGER:return yt.checkInteger(e);case _e.LONG:return yt.checkLong(e);case _e.DOUBLE:return yt.checkDouble(e);case _e.BOOLEAN:return yt.checkBoolean(e);case _e.DATE_TIME:return yt.checkDateTime(e);case _e.LOCAL_TIME:return yt.checkLocalTime(e);default:return yt.getTypeFromUnknown(e)}}static isNotParsableNumber(e){return isNaN(e)||e==="Infinity"||e==="-Infinity"}static checkInteger(e){const t=e.replace(/,/g,"");return yt.isNotParsableNumber(t)?_e.STRING:yt.getNumberType(t)}static checkLong(e){const t=e.replace(/,/g,"");return yt.isNotParsableNumber(t)?_e.STRING:t.includes(".")?_e.DOUBLE:_e.LONG}static checkDouble(e){const t=e.replace(/,/g,"");return yt.isNotParsableNumber(t)?_e.STRING:_e.DOUBLE}static checkBoolean(e){const t=e.toLowerCase();return t==="true"||t==="false"?_e.BOOLEAN:_e.STRING}static checkDateTime(e){return Id.test(e)?_e.DATE_TIME:_e.STRING}static checkLocalTime(e){return Fd.test(e)?_e.LOCAL_TIME:_e.STRING}static getTypeFromUnknown(e){const t=e.replace(/,/g,"");if(yt.isNotParsableNumber(t)){const n=e.toLowerCase();return n==="true"||n==="false"?_e.BOOLEAN:Id.test(e)&&e.includes(":")?_e.DATE_TIME:Fd.test(e)?_e.LOCAL_TIME:_e.STRING}return yt.getNumberType(t)}static getNumberType(e){if(e.includes("."))return _e.DOUBLE;const t=e.startsWith("-")?11:10;if(e.length>t)return _e.LONG;const n=parseInt(e,10);return n>Ef||n<yf?_e.LONG:_e.INTEGER}constructor(e,t,n,s,i,o,l,a,d,h){this.onFileCompleted=e,this.file=t,this.readHeaders=n,this.nullString=i,this.onProgress=o,this.onError=l,this.chunks=0,this.totalChunks=a,this.isZip=d,this.shouldTrim=h,this.zipProgress=0,this.handleChunk=this.handleChunk.bind(this),this.handleComplete=this.handleComplete.bind(this),this.handleError=this.handleError.bind(this),this.handleNodeUpdate=this.handleNodeUpdate.bind(this),this.config={...s,error:this.handleError,chunk:this.handleChunk,complete:this.handleComplete}}onFileCompleted;file;readHeaders;nullString;onProgress;onError;types;chunks;totalChunks;isZip;shouldTrim;zipProgress;config;parse(){const e=this.isZip?this.file.nodeStream("nodebuffer",this.handleNodeUpdate):this.file;Pa.parse(e,this.config)}handleChunk(e,t){let{data:n}=e;if(!this.types){if(n==null||n.length===0){t.abort(),this.onError("Error parsing CSV: no data in file.");return}this.types=new Array(n[0].length).fill(Dd),this.readHeaders&&(n=n.slice(1))}N(this.types);const s=[...this.types];n.forEach(l=>{if(l.length>=s.length){for(let a=0;a<s.length;a+=1)s[a]=yt.determineType(this.shouldTrim?l[a].trim():l[a],s[a],this.nullString);this.types=s}else t.abort(),this.onError(`Error parsing CSV: Insufficient data in row.
3
3
  Expected length ${s.length} but found ${l.length}.
4
4
  Row = ${l}`)}),this.chunks+=1;let i=0;this.totalChunks>0?i=Math.round(this.chunks/this.totalChunks*50):i=Math.round(this.zipProgress/2),this.onProgress(i)&&t.abort()}handleComplete(e){const{types:t,onFileCompleted:n}=this;N(t),(e==null||!e.meta.aborted)&&n(t.map(s=>s===Dd?_e.STRING:s))}handleError(e){const{onError:t}=this;t(e)}handleNodeUpdate(e){this.zipProgress=e.percent}}const Rf=yt,Po=ne.module("CsvParser"),xf=650;class Zi{static generateHeaders=e=>{const t=[];for(let n=0;n<e;n+=1)t.push(Zi.generateHeaderRecursive(n));return t};static generateHeaderRecursive(e){let t="",n=e;return e>=26&&(t=t.concat(Zi.generateHeaderRecursive(Math.floor(e/26)-1)),n=e%26),t.concat(String.fromCharCode(65+n))}constructor({onFileCompleted:e,session:t,file:n,type:s,readHeaders:i=!0,onProgress:o,onError:l,timeZone:a,isZip:d}){this.onFileCompleted=e,this.session=t,this.file=n,this.isZip=d,this.type=s,this.readHeaders=i,this.timeZone=a,this.onProgress=o,this.onError=l,this.tables=[],this.chunks=0,this.totalChunks=d?0:Math.ceil(n.size/Pa.LocalChunkSize),this.isComplete=!1,this.zipProgress=0,this.numConsolidated=0,this.isCancelled=!1,this.handleChunk=this.handleChunk.bind(this),this.handleError=this.handleError.bind(this),this.handleComplete=this.handleComplete.bind(this),this.handleNodeUpdate=this.handleNodeUpdate.bind(this),this.handleCreateTable=this.handleCreateTable.bind(this),this.config={delimiter:s.delimiter,newline:s.newline,escapeChar:s.escapeChar,dynamicTyping:!1,error:this.handleError,skipEmptyLines:s.skipEmptyLines,chunk:this.handleChunk,complete:this.handleComplete,fastMode:!1}}onFileCompleted;session;file;isZip;type;readHeaders;timeZone;onProgress;onError;tables;headers;types;chunks;totalChunks;isComplete;zipProgress;consolidatedChunks;numConsolidated;isCancelled;config;cancel(){this.isCancelled=!0}transpose(e,t){const n=t.length,s=new Array(e).fill(null).map(()=>new Array(n));for(let i=0;i<n;i+=1){const o=t[i];if(o.length<e)throw new Error(`Insufficient columns. Expected ${e} but found ${o.length}
5
5
  ${o}`);for(let l=0;l<e;l+=1){const a=this.type.shouldTrim?t[i][l].trim():t[i][l];s[l][i]=this.nullCheck(a)}}return s}nullCheck(e){return e===this.type.nullString?"":e}parse(){const e=n=>{const s=this.isZip?this.file.nodeStream("nodebuffer",this.handleNodeUpdate):this.file;this.types=n,Pa.parse(s,this.config)};new Rf(e,this.file,this.readHeaders,this.config,this.type.nullString,this.onProgress,this.onError,this.totalChunks,this.isZip,this.type.shouldTrim).parse()}handleChunk(e,t){const{readHeaders:n,onError:s,handleCreateTable:i,isZip:o,tables:l}=this;if(this.isCancelled){Po.debug2("CSV parser cancelled."),t.abort(),l.forEach(h=>h.close());return}let{data:a}=e;this.headers||(n?(this.headers=Ii.legalizeColumnNames(a[0]),a=a.slice(1)):this.headers=Zi.generateHeaders(a[0].length));let d=[];try{if(d=this.transpose(this.headers.length,a),o)this.consolidateChunks(d,t);else{const h=this.chunks;this.chunks+=1,i(h,d,t)}}catch(h){s(h)}}consolidateChunks(e,t){if(!this.consolidatedChunks)this.consolidatedChunks=e.slice();else for(let n=0;n<e.length;n+=1)this.consolidatedChunks[n]=this.consolidatedChunks[n].concat(e[n]);this.numConsolidated+=1,(this.numConsolidated>=xf||this.isComplete)&&this.uploadConsolidatedChunks(t)}uploadConsolidatedChunks(e){const{handleCreateTable:t}=this,n=this.chunks;this.chunks+=1;const s=this.consolidatedChunks?.slice();this.consolidatedChunks=void 0,this.numConsolidated=0,N(s),t(n,s,e)}handleCreateTable(e,t,n){const{session:s,tables:i,onFileCompleted:o,totalChunks:l,types:a,onProgress:d,onError:h}=this;n&&n.pause(),N(this.headers),N(a),s.newTable(this.headers,a,t,this.timeZone).then(u=>{if(this.isCancelled){Po.debug2("CSV parser cancelled."),n&&n.abort(),i.forEach(g=>g.close());return}n&&n.resume(),i[e]=u;let m=0;l>0?m=Math.round(i.length/l*50)+50:m=Math.round(50+this.zipProgress/2),Po.debug2(`CSV parser progress ${m}`),d(m),this.isComplete&&i.length===this.chunks&&(Po.debug2("CSV parser complete."),o(i))}).catch(u=>{!this.isComplete&&n&&n.abort(),h(u)})}handleComplete(e){(e==null||e.meta.aborted==null)&&(this.isComplete=!0,this.consolidatedChunks&&this.uploadConsolidatedChunks(null))}handleError(e){const{onError:t}=this;t(e)}handleNodeUpdate(e){this.zipProgress=e.percent}}const Df=Zi;class If{static DEFAULT_TYPE="DEFAULT_CSV";static AUTO="AUTODETECT";static fromExtension(e){return e.endsWith(".csv")?"DEFAULT_CSV":e.endsWith(".tsv")||e.endsWith(".tab")?"TSV":e.endsWith(".psv")?"PIPE_SV":"AUTODETECT"}static TYPES=Object.freeze({DEFAULT_CSV:{name:"Default csv (trimmed)",delimiter:",",newline:void 0,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!0,nullString:"(null)"},TSV:{name:"Tab seperated (tsv)",delimiter:" ",newline:void 0,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!0,nullString:"(null)"},APACHE_COMMON_CSV:{name:"Apache Common csv",delimiter:",",newline:`\r
6
6
  `,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!0,nullString:null},EXCEL_CSV:{name:"Excel csv (strict)",delimiter:",",newline:`\r
7
7
  `,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!1,nullString:null},MY_SQL_CSV:{name:"MySQL csv",delimiter:" ",newline:`
8
8
  `,escapeChar:"\\",shouldTrim:!0,skipEmptyLines:!1,nullString:"\\N"},RFC4180_CSV:{name:"RFC4180 csv",delimiter:",",newline:`\r
9
- `,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!1,nullString:null},COLON_SV:{name:": colon sv",delimiter:":",newline:void 0,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!0,nullString:"(null)"},SEMI_COLON_SV:{name:"; semi-colon sv",delimiter:";",newline:void 0,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!0,nullString:"(null)"},PIPE_SV:{name:"| pipe separated (psv)",delimiter:"|",newline:void 0,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!0,nullString:"(null)"},SPACE_SV:{name:'" " space sv',delimiter:" ",newline:void 0,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!0,nullString:"(null)"},AUTODETECT:{name:"autodetect",delimiter:void 0,newline:void 0,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!0,nullString:"(null)"}})}const Yi=If;const Nd=ne.module("CsvInputBar"),Ff=Object.entries(Yi.TYPES).map(([c,e])=>r.jsx("option",{value:c,children:e.name},c));class Nf extends v.Component{static defaultProps={file:null,paste:null,unzip:null};constructor(e){super(e),this.handleUpload=this.handleUpload.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleError=this.handleError.bind(this),this.handleTableName=this.handleTableName.bind(this),this.toggleFirstRowHeaders=this.toggleFirstRowHeaders.bind(this),this.handleProgress=this.handleProgress.bind(this),this.handleCancelInProgress=this.handleCancelInProgress.bind(this),this.handleQueryTypeChange=this.handleQueryTypeChange.bind(this),this.inputRef=de.createRef(),this.state={tableName:"",tableNameSet:!1,isFirstRowHeaders:!0,showProgress:!1,progressValue:0,type:Yi.DEFAULT_TYPE,parser:null}}componentDidUpdate(e){const{file:t,paste:n}=this.props,{tableName:s,tableNameSet:i}=this.state;if(!i&&t!=null&&!s){const o=t.name.lastIndexOf("."),l=Ii.legalizeTableName(t.name.substring(0,o));this.setState({tableName:l,tableNameSet:!0}),this.inputRef.current?.focus()}else(t==null&&e.file!=null||n==null&&e.paste!=null)&&this.setState({tableName:"",tableNameSet:!1});n!=null&&n!==""&&!s&&this.inputRef.current&&this.inputRef.current.focus(),t!=null&&t!==e.file?this.setState({type:Yi.fromExtension(t.name)}):n!=null&&n!==""&&(e.paste===void 0||e.paste==="")&&this.setState({type:Yi.AUTO})}componentWillUnmount(){const{parser:e}=this.state;e&&e.cancel()}inputRef;handleCancel(){const{onClose:e}=this.props;e()}handleError(e){const{onClose:t,onError:n}=this.props;Nd.error(e),n(e),t()}handleTableName(e){this.setState({tableName:e.target.value,tableNameSet:!0})}toggleFirstRowHeaders(){const{isFirstRowHeaders:e}=this.state;this.setState({isFirstRowHeaders:!e})}handleUpload(e){e.stopPropagation(),e.preventDefault();const{file:t,paste:n}=this.props;t!=null?t.name.endsWith(".zip")?this.handleZipFile(t):this.handleFile(t):n!==void 0&&n!==""&&this.handleFile(new Blob([n],{type:"text/plain"}))}handleFile(e,t=!1){Nd.info(`Starting CSV parser for ${e instanceof File?e.name:"pasted values"} ${t?"":e.size} bytes`);const{session:n,timeZone:s,onInProgress:i}=this.props,{tableName:o,isFirstRowHeaders:l,type:a}=this.state,d=u=>{u.length===1?n.bindTableToVariable(u[0],o).then(()=>this.openTable()).catch(m=>this.handleError(m)):n.mergeTables(u).then(m=>{n.bindTableToVariable(m,o).then(()=>this.openTable()).catch(g=>this.handleError(g)),u.forEach(g=>g.close())}).catch(m=>this.handleError(m))},h=new Df({onFileCompleted:d,session:n,file:e,type:Yi.TYPES[a],readHeaders:l,onProgress:this.handleProgress,onError:this.handleError,timeZone:s,isZip:t});h.parse(),this.setState({showProgress:!0,parser:h}),i(!0)}handleZipFile(e){const{onUpdate:t,unzip:n}=this.props;if(n==null){this.handleError(new Error("No support for zip files available."));return}n(e).then(s=>{let i=!1;for(let o=0;o<s.length;o+=1){const l=s[o];if(ui.isValidExtension(l.name)){t(`Loading ${l.name} as csv from ${e.name}`),i=!0,this.handleFile(l,!0);break}}if(!i)throw new Error(`No csv file found in ${e.name}`)}).catch(s=>this.handleError(s))}handleProgress(e){const{showProgress:t}=this.state;return t&&this.setState({progressValue:e}),!t}handleCancelInProgress(){const{onInProgress:e}=this.props,{parser:t}=this.state;t&&t.cancel(),this.setState({showProgress:!1,progressValue:0}),e(!1)}openTable(){const{onOpenTable:e,onClose:t}=this.props,{tableName:n}=this.state;e(n),t()}handleQueryTypeChange(e){this.setState({type:e.target.value})}render(){const{file:e,paste:t}=this.props,{tableName:n,isFirstRowHeaders:s,showProgress:i,progressValue:o,type:l}=this.state,a=Boolean(t)&&!n;return r.jsxs("div",{className:"csv-input-bar",children:[!i&&r.jsxs("form",{onSubmit:this.handleUpload,className:"csv-input-bar-container form-inline",children:[r.jsxs("div",{className:"form-group",children:[r.jsx("label",{htmlFor:"tableNameInput",children:"Table name"}),r.jsx("input",{ref:this.inputRef,id:"tableNameInput",type:"text",className:Y("form-control",{"is-invalid":a}),value:n,onChange:this.handleTableName})]}),r.jsxs("div",{className:"form-group",children:[r.jsx("label",{htmlFor:"formatSelect",children:"File format"}),r.jsx("select",{id:"formatSelect",className:"custom-select",value:l,onChange:this.handleQueryTypeChange,children:Ff})]}),r.jsx(nn,{className:"firstRowHeaders",checked:s,onChange:this.toggleFirstRowHeaders,children:"First row is column headers"}),r.jsxs("div",{className:"csv-input-buttons form-group",children:[r.jsx(B,{kind:"secondary",onClick:this.handleCancel,children:"Cancel"}),r.jsx(B,{kind:"primary",type:"submit",disabled:!(e!==null||t!==void 0&&t!=="")||!n,children:"Upload"})]})]}),i&&r.jsxs("div",{className:"csv-progress-container",children:[r.jsx("label",{children:"Uploading Table"}),r.jsx("div",{className:"progress",children:r.jsx("div",{className:"progress-bar bg-primary",style:{width:`${o}%`},"aria-valuenow":o,"aria-valuemin":0,"aria-valuemax":100})}),r.jsxs("label",{children:[o,"%"]}),r.jsx(B,{kind:"primary",onClick:this.handleCancelInProgress,children:"Cancel"})]})]})}}const kf=Nf;const kd=ne.module("ConsoleMenu");class gl extends v.PureComponent{static makeItemActions(e,t,n,s,i){if(e.length===0)return[];const o={menuElement:r.jsx(Di,{value:t,onChange:s,className:"console-menu",ref:n})};let l=e;t&&(l=l.filter(({title:d})=>d!=null&&d.toLowerCase().indexOf(t.toLowerCase())>=0));const a=l.map(d=>({title:d.title,action:()=>{i(d)}}));return[o,...a]}constructor(e){super(e),this.handleTableFilterChange=this.handleTableFilterChange.bind(this),this.handleTableMenuClosed=this.handleTableMenuClosed.bind(this),this.handleTableMenuOpened=this.handleTableMenuOpened.bind(this),this.handleWidgetFilterChange=this.handleWidgetFilterChange.bind(this),this.handleWidgetMenuClosed=this.handleWidgetMenuClosed.bind(this),this.handleWidgetMenuOpened=this.handleWidgetMenuOpened.bind(this),this.state={tableFilterText:"",widgetFilterText:""}}tableSearchField;widgetSearchField;makeTableActions=ge((e,t,n)=>{const s=e.filter(i=>$a.isTableType(i.type));return gl.makeItemActions(s,t,i=>{this.tableSearchField=i},this.handleTableFilterChange,n)});makeWidgetActions=ge((e,t,n)=>{const s=e.filter(i=>$a.isWidgetType(i.type));return gl.makeItemActions(s,t,i=>{this.widgetSearchField=i},this.handleWidgetFilterChange,n)});handleTableFilterChange(e){kd.debug("filtering tables..."),this.setState({tableFilterText:e.target.value})}handleTableMenuClosed(){this.setState({tableFilterText:""})}handleTableMenuOpened(){this.tableSearchField?.focus()}handleWidgetFilterChange(e){kd.debug("filtering widgets..."),this.setState({widgetFilterText:e.target.value})}handleWidgetMenuClosed(){this.setState({widgetFilterText:""})}handleWidgetMenuOpened(){this.widgetSearchField?.focus()}render(){const{overflowActions:e,objects:t,openObject:n}=this.props,{tableFilterText:s,widgetFilterText:i}=this.state,o=this.makeTableActions(t,s,n),l=this.makeWidgetActions(t,i,n),a={placement:"bottom-end"},d=o.length===0,h=l.length===0;return r.jsxs("div",{className:"console-pane-menu",children:[r.jsxs(B,{kind:"ghost",className:"btn-link-icon",disabled:d,onClick:()=>{},tooltip:d?"No tables available":"Tables",children:[r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx(ee,{mask:rr,icon:Un,transform:"right-5 down-5"}),r.jsx(ee,{icon:Un,transform:"right-8 down-6"})]}),r.jsx(Vn,{actions:o,onMenuOpened:this.handleTableMenuOpened,onMenuClosed:this.handleTableMenuClosed,options:{initialKeyboardIndex:1},popperOptions:a},"table-actions ")]}),r.jsxs(B,{kind:"ghost",className:"btn-link-icon",disabled:l.length===0,onClick:()=>{},tooltip:h?"No widgets available":"Widgets",children:[r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx(ee,{mask:Xc,icon:Un,transform:"right-5 down-5"}),r.jsx(ee,{icon:Un,transform:"right-8 down-6"})]}),r.jsx(Vn,{actions:l,onMenuOpened:this.handleWidgetMenuOpened,onMenuClosed:this.handleWidgetMenuClosed,options:{initialKeyboardIndex:1},popperOptions:a},"table-actions")]}),r.jsx(B,{kind:"ghost",className:"btn-overflow btn-link-icon",icon:Qc,tooltip:"More Actions...",onClick:()=>{},children:r.jsx(Vn,{actions:e,popperOptions:a})})]})}}const Mf=gl;class Lf extends v.PureComponent{static defaultProps={children:null};constructor(e){super(e),this.handleCommandStarted=this.handleCommandStarted.bind(this),this.handleCommandCompleted=this.handleCommandCompleted.bind(this),this.pending=new Yn,this.state={isDisconnected:!1,isCommandRunning:!1}}componentDidMount(){this.startListening()}componentWillUnmount(){this.stopListening(),this.cancelPendingPromises()}pending;startListening(){const{session:e}=this.props;e.addEventListener(I.IdeSession.EVENT_COMMANDSTARTED,this.handleCommandStarted)}stopListening(){const{session:e}=this.props;e.removeEventListener(I.IdeSession.EVENT_COMMANDSTARTED,this.handleCommandStarted)}cancelPendingPromises(){this.pending.cancel()}handleCommandStarted(e){const{result:t}=e.detail;this.pending.add(t).then(()=>this.handleCommandCompleted(null)).catch(n=>this.handleCommandCompleted(n)),this.setState({isCommandRunning:!0})}handleCommandCompleted(e){e instanceof Hl||this.setState({isCommandRunning:this.pending.pending.length>0})}render(){const{children:e,openObject:t,overflowActions:n,objects:s}=this.props,{isDisconnected:i,isCommandRunning:o}=this.state;let l=null,a=null;return i?(l="console-status-icon-disconnected",a="Worker is disconnected"):o?(l="console-status-icon-pending",a="Worker is busy"):(l="console-status-icon-idle",a="Worker is idle"),r.jsxs("div",{className:"console-pane-status-bar",children:[r.jsxs("div",{children:[r.jsx("div",{className:Y("console-status-icon",l)}),r.jsx(ot,{children:a})]}),e,r.jsx(Mf,{overflowActions:n,openObject:t,objects:s})]})}}const Of=Lf,On=ne.module("Console"),Md={isAutoLaunchPanelsEnabled:!0,isPrintStdOutEnabled:!0,isClosePanelsOnDisconnectEnabled:!0};class mi extends v.PureComponent{static defaultProps={statusBarChildren:null,settings:{},onSettingsChange:()=>{},scope:null,actions:[],historyChildren:null,timeZone:"America/New_York",objectMap:new Map,disabled:!1,unzip:null};static LOG_THROTTLE=500;static isErrorLevel(e){return e===Ct.STDERR||e===Ct.ERROR||e===Ct.FATAL}static isOutputLevel(e){return e===Ct.STDOUT||mi.isErrorLevel(e)}constructor(e){super(e),this.handleCommandResult=this.handleCommandResult.bind(this),this.handleCommandStarted=this.handleCommandStarted.bind(this),this.handleCommandSubmit=this.handleCommandSubmit.bind(this),this.handleClearShortcut=this.handleClearShortcut.bind(this),this.handleFocusHistory=this.handleFocusHistory.bind(this),this.handleLogMessage=this.handleLogMessage.bind(this),this.handleOverflowActions=this.handleOverflowActions.bind(this),this.handleScrollPaneScroll=this.handleScrollPaneScroll.bind(this),this.handleToggleAutoLaunchPanels=this.handleToggleAutoLaunchPanels.bind(this),this.handleToggleClosePanelsOnDisconnect=this.handleToggleClosePanelsOnDisconnect.bind(this),this.handleTogglePrintStdout=this.handleTogglePrintStdout.bind(this),this.handleUploadCsv=this.handleUploadCsv.bind(this),this.handleHideCsv=this.handleHideCsv.bind(this),this.handleCsvFileCanceled=this.handleCsvFileCanceled.bind(this),this.handleCsvFileOpened=this.handleCsvFileOpened.bind(this),this.handleCsvPaste=this.handleCsvPaste.bind(this),this.handleDragEnter=this.handleDragEnter.bind(this),this.handleDragLeave=this.handleDragLeave.bind(this),this.handleClearDragError=this.handleClearDragError.bind(this),this.handleOpenCsvTable=this.handleOpenCsvTable.bind(this),this.handleCsvUpdate=this.handleCsvUpdate.bind(this),this.handleCsvError=this.handleCsvError.bind(this),this.handleCsvInProgress=this.handleCsvInProgress.bind(this),this.consolePane=de.createRef(),this.consoleInput=de.createRef(),this.consoleHistoryScrollPane=de.createRef(),this.pending=new Yn,this.queuedLogMessages=[];const{objectMap:t,settings:n}=this.props;this.state={consoleHistory:[],consoleHeight:0,isScrollDecorationShown:!1,objectHistoryMap:new Map,objectMap:new Map(t),showCsvOverlay:!1,csvFile:null,csvPaste:null,dragError:null,csvUploadInProgress:!1,...Md,...n}}componentDidMount(){this.initConsoleLogging();const{session:e}=this.props;e.addEventListener(I.IdeSession.EVENT_COMMANDSTARTED,this.handleCommandStarted),this.updateDimensions()}componentDidUpdate(e,t){const{props:n,state:s}=this;this.sendSettingsChange(t,s),n.objectMap!==e.objectMap&&this.updateObjectMap()}componentWillUnmount(){const{session:e}=this.props;e.removeEventListener(I.IdeSession.EVENT_COMMANDSTARTED,this.handleCommandStarted),this.pending.cancel(),this.processLogMessageQueue.cancel(),this.deinitConsoleLogging()}cancelListener;consolePane;consoleInput;consoleHistoryScrollPane;pending;queuedLogMessages;initConsoleLogging(){const{session:e}=this.props;this.cancelListener=e.onLogMessage(this.handleLogMessage)}deinitConsoleLogging(){this.cancelListener!=null&&(this.cancelListener(),this.cancelListener=void 0)}handleClearShortcut(e){e.preventDefault(),e.stopPropagation(),this.consoleInput.current?.clear()}handleCommandStarted(e){const{code:t,result:n}=e.detail,s=this.pending.add(n),i={command:t,disabledObjects:[],startTime:Date.now(),cancelResult:()=>{n.cancel()},wrappedResult:s},{commandHistoryStorage:o,language:l,scope:a}=this.props,d=o.addItem(l,a,t,{command:t,startTime:new Date().toJSON()});d.catch(h=>{On.debug("Error adding workspace item",h)}),this.setState(h=>({consoleHistory:h.consoleHistory.concat(i)}),()=>{this.scrollConsoleHistoryToBottom(!0)}),s.then(h=>{this.handleCommandResult(h,i,d)}).catch(h=>{this.handleCommandError(h,i,d)})}handleCommandResult(e,t,n){const s={...t,wrappedResult:void 0,cancelResult:void 0,result:e??t.result};this.setState(({consoleHistory:i})=>{const o=i.lastIndexOf(t);if(o<0)return On.error("historyItem not found in consoleHistory"),null;const l=i.concat();return l[o]=s,{consoleHistory:l}}),e&&(this.updateHistory(e,s),this.updateKnownObjects(s),this.updateWorkspaceHistoryItem({error:e.error},n),this.closeRemovedItems(e.changes),this.openUpdatedItems(e.changes))}handleCommandError(e,t,n){if(ye.isCanceled(e)){On.debug("Called handleCommandError on a cancelled promise result");return}this.updateWorkspaceHistoryItem({error:`${e}`},n),this.setState(s=>{const i=s.consoleHistory.concat(),o=i.lastIndexOf(t),l={...t};return l.wrappedResult=void 0,l.cancelResult=void 0,l.endTime=Date.now(),l.result={error:e},i[o]=l,{consoleHistory:i}})}handleFocusHistory(e){e.preventDefault(),e.stopPropagation();const{focusCommandHistory:t}=this.props;t()}handleLogMessage(e){const{isPrintStdOutEnabled:t}=this.state;t&&mi.isOutputLevel(e.logLevel)&&this.queueLogMessage(e.message,e.logLevel)}queueLogMessage(e,t){const n={};mi.isErrorLevel(t)?n.error=e:n.message=e;const s={command:void 0,result:n};this.queuedLogMessages.push(s),this.processLogMessageQueue()}processLogMessageQueue=vs(()=>{this.scrollConsoleHistoryToBottom(),this.setState(e=>{On.debug2("processLogMessageQueue",this.queuedLogMessages.length," items");let{consoleHistory:t}=e;return t=t.concat(this.queuedLogMessages),this.queuedLogMessages=[],{consoleHistory:t}})},mi.LOG_THROTTLE);openUpdatedItems(e){const{isAutoLaunchPanelsEnabled:t}=this.state;if(e==null||!t)return;const{openObject:n}=this.props;[...e.created,...e.updated].forEach(s=>n(s))}closeRemovedItems(e){if(e==null||e.removed==null||e.removed.length===0)return;const{closeObject:t}=this.props,{removed:n}=e;n.forEach(s=>t(s))}updateHistory(e,t){const n=t;e==null||e.changes==null||n==null||(n.endTime=Date.now(),this.scrollConsoleHistoryToBottom(),this.setState(s=>({consoleHistory:s.consoleHistory.concat()})))}updateKnownObjects(e){let t;if(e.result&&(t=e.result.changes),!t||(t.created==null||t.created.length===0)&&(t.updated==null||t.updated.length===0)&&(t.removed==null||t.removed.length===0)){On.debug2("updateKnownObjects no changes");return}this.setState(n=>{let{consoleHistory:s}=n;const i=s.lastIndexOf(e);if(i<0)return On.error("historyItem not found in state.consoleHistory"),null;const o=new Map(n.objectHistoryMap),l=new Map(n.objectMap),a=(d,h=!1)=>{const{title:u}=d;N(u);const m=o.get(u);if(m!=null&&m>=0){s===n.consoleHistory&&(s=s.concat());const g={...s[m],disabledObjects:[...s[m].disabledObjects??[],u]};s[m]=g}o.set(u,i),h?l.delete(u):l.set(u,d)};return t?.updated.forEach(d=>a(d)),t?.removed.forEach(d=>a(d,!0)),t?.created.forEach(d=>{const{title:h}=d;N(h),o.set(h,i),l.set(h,d)}),{objectHistoryMap:o,objectMap:l,consoleHistory:s}})}updateObjectMap(){const{objectMap:e}=this.props;this.setState({objectMap:e})}updateWorkspaceHistoryItem(e,t){const n=this.pending.add(t),s=new Date().toJSON();n.then(i=>{const o={...i,data:{...i.data,endTime:s,result:e}},{commandHistoryStorage:l,language:a}=this.props;l.updateItem(a,o).catch(d=>{On.warn("Error updating command history storage",d)})}).catch(i=>{On.debug("Error updating workspace history item",i)})}scrollConsoleHistoryToBottom(e=!1){const t=this.consoleHistoryScrollPane.current;N(t),!(!e&&t.scrollTop<t.scrollHeight-t.offsetHeight)&&window.requestAnimationFrame(()=>{t.scrollTop=t.scrollHeight})}handleScrollPaneScroll(){const e=this.consoleHistoryScrollPane.current;N(e),e.scrollTop>0&&e.scrollHeight>e.clientHeight?this.setState({isScrollDecorationShown:!0}):this.setState({isScrollDecorationShown:!1})}handleToggleAutoLaunchPanels(){this.setState(e=>({isAutoLaunchPanelsEnabled:!e.isAutoLaunchPanelsEnabled}))}handleToggleClosePanelsOnDisconnect(){this.setState(e=>({isClosePanelsOnDisconnectEnabled:!e.isClosePanelsOnDisconnectEnabled}))}handleTogglePrintStdout(){this.setState(e=>({isPrintStdOutEnabled:!e.isPrintStdOutEnabled}))}handleUploadCsv(){this.setState({showCsvOverlay:!0,dragError:null,csvUploadInProgress:!1})}handleHideCsv(){this.setState({showCsvOverlay:!1,csvFile:null,csvPaste:null,dragError:null,csvUploadInProgress:!1})}handleCsvFileCanceled(){this.setState({csvFile:null,csvPaste:null})}handleCsvFileOpened(e){this.setState({csvFile:e,csvPaste:null})}handleCsvPaste(e){this.setState({csvFile:null,csvPaste:e})}handleDragEnter(e){if(e.dataTransfer==null||e.dataTransfer.items==null||e.dataTransfer.items.length===0||e.dataTransfer.items[0].kind==="string")return;e.preventDefault(),e.stopPropagation(),this.setState({showCsvOverlay:!0});const{items:t}=e.dataTransfer;if(t.length>1){this.setState({dragError:ui.MULTIPLE_FILE_ERROR});return}const n=t[0];ui.isValidDropItem(n)?this.setState({dragError:null}):this.setState({dragError:ui.FILE_TYPE_ERROR})}handleDragLeave(e){e.currentTarget==null||e.currentTarget instanceof Element&&e.relatedTarget instanceof Element&&e.currentTarget.contains(e.relatedTarget)||(e.preventDefault(),e.stopPropagation(),this.setState({showCsvOverlay:!1,dragError:null}))}handleClearDragError(){this.setState({dragError:null})}handleOpenCsvTable(e){const{openObject:t,commandHistoryStorage:n,language:s,scope:i}=this.props,{consoleHistory:o,objectMap:l}=this.state,a={name:e,title:e,type:I.VariableType.TABLE},d=l.has(e),h={startTime:Date.now(),endTime:Date.now(),disabledObjects:[],result:{changes:{created:[],updated:[],removed:[],[d?"updated":"created"]:[a]}}},u=o.concat(h);this.setState({consoleHistory:u}),this.scrollConsoleHistoryToBottom(!0),this.updateKnownObjects(h),t({name:e,title:e,type:I.VariableType.TABLE}),n.addItem(s,i,e,{command:e,startTime:new Date().toJSON(),endTime:new Date().toJSON()})}addConsoleHistoryMessage(e,t){const{consoleHistory:n}=this.state,s={command:"",startTime:Date.now(),endTime:Date.now(),result:{message:e,error:t}},i=n.concat(s);this.setState({consoleHistory:i})}handleCsvUpdate(e){this.addConsoleHistoryMessage(e)}handleCsvError(e){this.addConsoleHistoryMessage(void 0,e!=null?`${e}`:void 0)}handleCsvInProgress(e){this.setState({csvUploadInProgress:e})}handleOverflowActions(){const{isAutoLaunchPanelsEnabled:e,isClosePanelsOnDisconnectEnabled:t,isPrintStdOutEnabled:n}=this.state,{actions:s}=this.props;return[...s,{title:"Print Stdout",action:this.handleTogglePrintStdout,group:ie.groups.high,icon:n?zn:void 0,order:10},{title:"Auto Launch Panels",action:this.handleToggleAutoLaunchPanels,group:ie.groups.high,icon:e?zn:void 0,order:20},{title:"Close Panels on Disconnect",action:this.handleToggleClosePanelsOnDisconnect,group:ie.groups.high,icon:t?zn:void 0,order:30},{title:"Upload Table from File",action:this.handleUploadCsv,group:ie.groups.high+10,order:40}]}handleCommandSubmit(e){if(e==="clear"||e==="cls")this.clearConsoleHistory();else if(e.length>0){const{session:t}=this.props;t.runCode(e).catch(n=>{On.error("There was an error initiating the command",n)})}else{const t={command:" ",result:{},startTime:Date.now(),endTime:Date.now()};this.scrollConsoleHistoryToBottom(!0),this.setState(n=>({consoleHistory:n.consoleHistory.concat(t)}))}}clearConsoleHistory(){this.pending.cancel(),this.setState(e=>{const t=new Map([...e.objectHistoryMap.keys()].map(n=>[n,-1]));return{consoleHistory:[],objectHistoryMap:t}})}getObjects=ge(e=>[...e.values()]);getContextActions=ge(e=>[...e,{action:this.handleClearShortcut,shortcut:Nt.CONSOLE.CLEAR},{action:this.handleFocusHistory,shortcut:Nt.CONSOLE.FOCUS_HISTORY}]);addCommand(e,t=!0,n=!1){this.consoleInput.current&&(this.consoleInput.current.setConsoleText(e,t,n),t&&this.scrollConsoleHistoryToBottom(!0))}focus(){this.consoleInput.current?.focus()}sendSettingsChange(e,t,n=!0){const s=Object.keys(Md),i={};let o=!1;for(let a=0;a<s.length;a+=1){const d=s[a],{[d]:h}=t,{[d]:u}=e;h!==u&&(o=!0),i[d]=h}if(n&&!o)return;const{onSettingsChange:l}=this.props;l(i)}updateDimensions(){this.consolePane.current&&this.setState({consoleHeight:this.consolePane.current.clientHeight}),this.consoleInput.current&&this.consoleInput.current.updateDimensions()}render(){const{actions:e,historyChildren:t,language:n,statusBarChildren:s,openObject:i,session:o,scope:l,commandHistoryStorage:a,timeZone:d,disabled:h,unzip:u}=this.props,{consoleHeight:m,consoleHistory:g,isScrollDecorationShown:p,objectMap:C,showCsvOverlay:f,csvFile:b,csvPaste:w,dragError:S,csvUploadInProgress:T}=this.state,y=this.getObjects(C),E=Math.round(m*.7),R=this.getContextActions(e);return r.jsxs("div",{role:"presentation",className:Y("iris-console","h-100","w-100",{disabled:h}),children:[r.jsxs("div",{className:"console-pane",ref:this.consolePane,children:[r.jsx(Of,{session:o,overflowActions:this.handleOverflowActions,openObject:i,objects:y,children:s}),r.jsxs("div",{className:"console-csv-container",onDragOver:ui.handleDragOver,onDragEnter:this.handleDragEnter,onDragLeave:this.handleDragLeave,children:[f&&r.jsx(ui,{onCancel:this.handleCsvFileCanceled,onFileOpened:this.handleCsvFileOpened,onPaste:this.handleCsvPaste,clearDragError:this.handleClearDragError,dragError:S,onError:this.handleCsvError,uploadInProgress:T,allowZip:u!=null}),r.jsxs("div",{role:"presentation",className:Y("scroll-pane no-scroll-x",{"scroll-decoration":p}),onScroll:this.handleScrollPaneScroll,ref:this.consoleHistoryScrollPane,children:[r.jsx(Mp,{items:g,openObject:i,language:n,disabled:h}),t]})]}),!f&&r.jsx(yd,{ref:this.consoleInput,session:o,language:n,scope:l,onSubmit:this.handleCommandSubmit,maxHeight:E,commandHistoryStorage:a}),f&&r.jsx(kf,{session:o,onOpenTable:this.handleOpenCsvTable,onClose:this.handleHideCsv,onUpdate:this.handleCsvUpdate,onError:this.handleCsvError,file:b??void 0,paste:w??void 0,onInProgress:this.handleCsvInProgress,timeZone:d,unzip:u})]}),r.jsx(ie,{actions:R,ignoreClassNames:[yd.INPUT_CLASS_NAME]})]})}}const Af=mi;class _f extends v.Component{static defaultProps={className:"fill-parent-absolute",onEditorInitialized:()=>{},onEditorWillDestroy:()=>{},settings:{}};constructor(e){super(e),this.handleResize=this.handleResize.bind(this),this.container=null,this.state={}}componentDidMount(){this.initEditor(),window.addEventListener("resize",this.handleResize)}componentWillUnmount(){window.removeEventListener("resize",this.handleResize),this.destroyEditor()}container;editor;setLanguage(e){if(this.editor){const t=this.editor.getModel();N(t),Gn.setModelLanguage(t,e)}}handleResize(){this.updateDimensions()}toggleFind(){this.editor&&(this.editor.focus(),this.editor.trigger("toggleFind","actions.find",void 0))}updateDimensions(){this.editor?.layout()}initEditor(){const{onEditorInitialized:e}=this.props;let{settings:t}=this.props;t={copyWithSyntaxHighlighting:!1,fixedOverflowWidgets:!0,folding:!1,fontFamily:"Fira Mono",glyphMargin:!1,language:"python",lineNumbersMinChars:3,minimap:{enabled:!1},scrollBeyondLastLine:!1,tabCompletion:"on",value:"",wordWrap:"off",links:!0,...t},N(this.container),this.editor=Gn.create(this.container,t),this.editor.addAction({id:"find",label:"Find",keybindings:[tn.CtrlCmd|ps.KeyF],precondition:void 0,keybindingContext:void 0,contextMenuGroupId:"navigation",contextMenuOrder:1,run:()=>{this.toggleFind()}}),this.editor.layout(),_t.removeConflictingKeybindings(this.editor),yn.registerLinkProvider("plaintext",{provideLinks:_t.provideLinks}),e(this.editor)}destroyEditor(){const{onEditorWillDestroy:e}=this.props;N(this.editor),e(this.editor),this.editor.dispose(),this.editor=void 0}render(){const{className:e}=this.props;return r.jsx("div",{className:Y("editor-container",e),ref:t=>{this.container=t}})}}const br=_f;const qt=ne.module("ScriptEditor");class Pf extends v.Component{static defaultProps={error:null,isLoading:!1,isLoaded:!1,focusOnMount:!0,onChange:()=>{},onEditorInitialized:()=>{},onEditorWillDestroy:()=>{},session:null};constructor(e){super(e),this.handleEditorInitialized=this.handleEditorInitialized.bind(this),this.handleEditorWillDestroy=this.handleEditorWillDestroy.bind(this),this.handleRun=this.handleRun.bind(this),this.handleRunSelected=this.handleRunSelected.bind(this),this.updateShortcuts=this.updateShortcuts.bind(this),this.contextActionCleanups=[],this.editorComponent=de.createRef(),this.state={model:null}}componentDidMount(){We.addEventListener("onUpdate",this.updateShortcuts)}componentDidUpdate(e){const{sessionLanguage:t,settings:n}=this.props,s=n?.language;s!==e.settings?.language&&(qt.debug("Set language",s),this.setLanguage(s));const o=t==null&&e.sessionLanguage!=null,l=s===t,a=e.settings?.language===e.sessionLanguage;(o||t!==void 0&&a&&!l)&&(qt.debug("De-init completion and context actions"),this.deInitContextActions(),this.deInitCodeCompletion()),(t!=null&&e.sessionLanguage==null&&l||t!==void 0&&!a&&l)&&(qt.debug("Init completion and context actions"),this.initContextActions(),this.initCodeCompletion())}componentWillUnmount(){We.removeEventListener("onUpdate",this.updateShortcuts)}contextActionCleanups;completionCleanup;editor;editorComponent;getValue(){return this.editor?this.editor.getValue():(qt.error("Editor not initialized"),null)}getSelectedCommand(){const e=this.editor?.getSelection();N(e);const t=this.editor?.getModel();N(t);const{startLineNumber:n,endColumn:s}=e;let{endLineNumber:i}=e;s===1&&i>n&&(i-=1);const o=t?.getLineMinColumn(n),l=t?.getLineMaxColumn(i),a=e.setStartPosition(n,o).setEndPosition(i,l);return t?.getValueInRange(a)}handleEditorInitialized(e){const{focusOnMount:t,onChange:n,onEditorInitialized:s,settings:i,session:o,sessionLanguage:l}=this.props;qt.debug("handleEditorInitialized",l,o,i),this.editor=e,this.setState({model:this.editor.getModel()}),_t.setEOL(e),_t.registerPasteHandler(e),o!=null&&i&&l===i.language&&(this.initContextActions(),this.initCodeCompletion()),e.onDidChangeModelContent(n),t!=null&&t&&e.focus(),s(this.editor)}handleEditorWillDestroy(e){qt.debug("handleEditorWillDestroy");const{onEditorWillDestroy:t}=this.props;t(e),this.deInitContextActions(),this.deInitCodeCompletion(),this.setState({model:null}),this.editor=void 0}handleRun(){const{onRunCommand:e}=this.props,t=this.getValue();t!=null&&e(t)}handleRunSelected(){const{onRunCommand:e}=this.props,t=this.getSelectedCommand();e(t)}initContextActions(){if(this.contextActionCleanups.length>0){qt.error("Context actions already initialized.");return}if(!this.editor)return;const e=[];e.push(this.editor.addAction({id:"run-code",label:"Run",keybindings:[_t.getMonacoKeyCodeFromShortcut(Nt.NOTEBOOK.RUN)],contextMenuGroupId:"navigation",contextMenuOrder:1.5,run:()=>{this.handleRun()}})),e.push(this.editor.addAction({id:"run-selected-code",label:"Run Selected",keybindings:[_t.getMonacoKeyCodeFromShortcut(Nt.NOTEBOOK.RUN_SELECTED)],contextMenuGroupId:"navigation",contextMenuOrder:1.5,run:()=>{this.handleRunSelected()}})),this.contextActionCleanups=e}deInitContextActions(){this.contextActionCleanups.length>0&&(this.contextActionCleanups.forEach(e=>e.dispose()),this.contextActionCleanups=[])}updateShortcuts(){this.deInitContextActions(),this.initContextActions()}initCodeCompletion(){if(this.completionCleanup!=null){qt.error("Code completion already initialized.");return}const{session:e}=this.props;qt.debug("initCodeCompletion",this.editor,e),this.editor&&e!=null&&(this.completionCleanup=_t.openDocument(this.editor,e))}deInitCodeCompletion(){const{session:e}=this.props;qt.debug("deInitCodeCompletion",this.editor,e),this.completionCleanup&&(this.completionCleanup.dispose(),this.completionCleanup=void 0,this.editor&&e!=null&&_t.closeDocument(this.editor,e))}append(e,t=!0){N(this.editor);const n=this.editor.getModel();N(n);const s=n.getValue();s?n.setValue(`${s}
9
+ `,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!1,nullString:null},COLON_SV:{name:": colon sv",delimiter:":",newline:void 0,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!0,nullString:"(null)"},SEMI_COLON_SV:{name:"; semi-colon sv",delimiter:";",newline:void 0,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!0,nullString:"(null)"},PIPE_SV:{name:"| pipe separated (psv)",delimiter:"|",newline:void 0,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!0,nullString:"(null)"},SPACE_SV:{name:'" " space sv',delimiter:" ",newline:void 0,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!0,nullString:"(null)"},AUTODETECT:{name:"autodetect",delimiter:void 0,newline:void 0,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!0,nullString:"(null)"}})}const Yi=If;const Nd=ne.module("CsvInputBar"),Ff=Object.entries(Yi.TYPES).map(([c,e])=>r.jsx("option",{value:c,children:e.name},c));class Nf extends v.Component{static defaultProps={file:null,paste:null,unzip:null};constructor(e){super(e),this.handleUpload=this.handleUpload.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleError=this.handleError.bind(this),this.handleTableName=this.handleTableName.bind(this),this.toggleFirstRowHeaders=this.toggleFirstRowHeaders.bind(this),this.handleProgress=this.handleProgress.bind(this),this.handleCancelInProgress=this.handleCancelInProgress.bind(this),this.handleQueryTypeChange=this.handleQueryTypeChange.bind(this),this.inputRef=de.createRef(),this.state={tableName:"",tableNameSet:!1,isFirstRowHeaders:!0,showProgress:!1,progressValue:0,type:Yi.DEFAULT_TYPE,parser:null}}componentDidUpdate(e){const{file:t,paste:n}=this.props,{tableName:s,tableNameSet:i}=this.state;if(!i&&t!=null&&!s){const o=t.name.lastIndexOf("."),l=Ii.legalizeTableName(t.name.substring(0,o));this.setState({tableName:l,tableNameSet:!0}),this.inputRef.current?.focus()}else(t==null&&e.file!=null||n==null&&e.paste!=null)&&this.setState({tableName:"",tableNameSet:!1});n!=null&&n!==""&&!s&&this.inputRef.current&&this.inputRef.current.focus(),t!=null&&t!==e.file?this.setState({type:Yi.fromExtension(t.name)}):n!=null&&n!==""&&(e.paste===void 0||e.paste==="")&&this.setState({type:Yi.AUTO})}componentWillUnmount(){const{parser:e}=this.state;e&&e.cancel()}inputRef;handleCancel(){const{onClose:e}=this.props;e()}handleError(e){const{onClose:t,onError:n}=this.props;Nd.error(e),n(e),t()}handleTableName(e){this.setState({tableName:e.target.value,tableNameSet:!0})}toggleFirstRowHeaders(){const{isFirstRowHeaders:e}=this.state;this.setState({isFirstRowHeaders:!e})}handleUpload(e){e.stopPropagation(),e.preventDefault();const{file:t,paste:n}=this.props;t!=null?t.name.endsWith(".zip")?this.handleZipFile(t):this.handleFile(t):n!==void 0&&n!==""&&this.handleFile(new Blob([n],{type:"text/plain"}))}handleFile(e,t=!1){Nd.info(`Starting CSV parser for ${e instanceof File?e.name:"pasted values"} ${t?"":e.size} bytes`);const{session:n,timeZone:s,onInProgress:i}=this.props,{tableName:o,isFirstRowHeaders:l,type:a}=this.state,d=u=>{u.length===1?n.bindTableToVariable(u[0],o).then(()=>this.openTable()).catch(m=>this.handleError(m)):n.mergeTables(u).then(m=>{n.bindTableToVariable(m,o).then(()=>this.openTable()).catch(g=>this.handleError(g)),u.forEach(g=>g.close())}).catch(m=>this.handleError(m))},h=new Df({onFileCompleted:d,session:n,file:e,type:Yi.TYPES[a],readHeaders:l,onProgress:this.handleProgress,onError:this.handleError,timeZone:s,isZip:t});h.parse(),this.setState({showProgress:!0,parser:h}),i(!0)}handleZipFile(e){const{onUpdate:t,unzip:n}=this.props;if(n==null){this.handleError(new Error("No support for zip files available."));return}n(e).then(s=>{let i=!1;for(let o=0;o<s.length;o+=1){const l=s[o];if(ui.isValidExtension(l.name)){t(`Loading ${l.name} as csv from ${e.name}`),i=!0,this.handleFile(l,!0);break}}if(!i)throw new Error(`No csv file found in ${e.name}`)}).catch(s=>this.handleError(s))}handleProgress(e){const{showProgress:t}=this.state;return t&&this.setState({progressValue:e}),!t}handleCancelInProgress(){const{onInProgress:e}=this.props,{parser:t}=this.state;t&&t.cancel(),this.setState({showProgress:!1,progressValue:0}),e(!1)}openTable(){const{onOpenTable:e,onClose:t}=this.props,{tableName:n}=this.state;e(n),t()}handleQueryTypeChange(e){this.setState({type:e.target.value})}render(){const{file:e,paste:t}=this.props,{tableName:n,isFirstRowHeaders:s,showProgress:i,progressValue:o,type:l}=this.state,a=Boolean(t)&&!n;return r.jsxs("div",{className:"csv-input-bar",children:[!i&&r.jsxs("form",{onSubmit:this.handleUpload,className:"csv-input-bar-container form-inline",children:[r.jsxs("div",{className:"form-group",children:[r.jsx("label",{htmlFor:"tableNameInput",children:"Table name"}),r.jsx("input",{ref:this.inputRef,id:"tableNameInput",type:"text",className:Y("form-control",{"is-invalid":a}),value:n,onChange:this.handleTableName})]}),r.jsxs("div",{className:"form-group",children:[r.jsx("label",{htmlFor:"formatSelect",children:"File format"}),r.jsx("select",{id:"formatSelect",className:"custom-select",value:l,onChange:this.handleQueryTypeChange,children:Ff})]}),r.jsx(nn,{className:"firstRowHeaders",checked:s,onChange:this.toggleFirstRowHeaders,children:"First row is column headers"}),r.jsxs("div",{className:"csv-input-buttons form-group",children:[r.jsx(B,{kind:"secondary",onClick:this.handleCancel,children:"Cancel"}),r.jsx(B,{kind:"primary",type:"submit",disabled:!(e!==null||t!==void 0&&t!=="")||!n,children:"Upload"})]})]}),i&&r.jsxs("div",{className:"csv-progress-container",children:[r.jsx("label",{children:"Uploading Table"}),r.jsx("div",{className:"progress",children:r.jsx("div",{className:"progress-bar bg-primary",style:{width:`${o}%`},"aria-valuenow":o,"aria-valuemin":0,"aria-valuemax":100})}),r.jsxs("label",{children:[o,"%"]}),r.jsx(B,{kind:"primary",onClick:this.handleCancelInProgress,children:"Cancel"})]})]})}}const kf=Nf;const kd=ne.module("ConsoleMenu");class gl extends v.PureComponent{static makeItemActions(e,t,n,s,i){if(e.length===0)return[];const o={menuElement:r.jsx(Di,{value:t,onChange:s,className:"console-menu",ref:n})};let l=e;t&&(l=l.filter(({title:d})=>d!=null&&d.toLowerCase().indexOf(t.toLowerCase())>=0));const a=l.map(d=>({title:d.title,action:()=>{i(d)}}));return[o,...a]}constructor(e){super(e),this.handleTableFilterChange=this.handleTableFilterChange.bind(this),this.handleTableMenuClosed=this.handleTableMenuClosed.bind(this),this.handleTableMenuOpened=this.handleTableMenuOpened.bind(this),this.handleWidgetFilterChange=this.handleWidgetFilterChange.bind(this),this.handleWidgetMenuClosed=this.handleWidgetMenuClosed.bind(this),this.handleWidgetMenuOpened=this.handleWidgetMenuOpened.bind(this),this.state={tableFilterText:"",widgetFilterText:""}}tableSearchField;widgetSearchField;makeTableActions=ge((e,t,n)=>{const s=e.filter(i=>$a.isTableType(i.type));return gl.makeItemActions(s,t,i=>{this.tableSearchField=i},this.handleTableFilterChange,n)});makeWidgetActions=ge((e,t,n)=>{const s=e.filter(i=>$a.isWidgetType(i.type));return gl.makeItemActions(s,t,i=>{this.widgetSearchField=i},this.handleWidgetFilterChange,n)});handleTableFilterChange(e){kd.debug("filtering tables..."),this.setState({tableFilterText:e.target.value})}handleTableMenuClosed(){this.setState({tableFilterText:""})}handleTableMenuOpened(){this.tableSearchField?.focus()}handleWidgetFilterChange(e){kd.debug("filtering widgets..."),this.setState({widgetFilterText:e.target.value})}handleWidgetMenuClosed(){this.setState({widgetFilterText:""})}handleWidgetMenuOpened(){this.widgetSearchField?.focus()}render(){const{overflowActions:e,objects:t,openObject:n}=this.props,{tableFilterText:s,widgetFilterText:i}=this.state,o=this.makeTableActions(t,s,n),l=this.makeWidgetActions(t,i,n),a={placement:"bottom-end"},d=o.length===0,h=l.length===0;return r.jsxs("div",{className:"console-pane-menu",children:[r.jsxs(B,{kind:"ghost",className:"btn-link-icon",disabled:d,onClick:()=>{},tooltip:d?"No tables available":"Tables",children:[r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx(ee,{mask:rr,icon:Un,transform:"right-5 down-5"}),r.jsx(ee,{icon:Un,transform:"right-8 down-6"})]}),r.jsx(Vn,{actions:o,onMenuOpened:this.handleTableMenuOpened,onMenuClosed:this.handleTableMenuClosed,options:{initialKeyboardIndex:1},popperOptions:a},"table-actions ")]}),r.jsxs(B,{kind:"ghost",className:"btn-link-icon",disabled:l.length===0,onClick:()=>{},tooltip:h?"No widgets available":"Widgets",children:[r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx(ee,{mask:Xc,icon:Un,transform:"right-5 down-5"}),r.jsx(ee,{icon:Un,transform:"right-8 down-6"})]}),r.jsx(Vn,{actions:l,onMenuOpened:this.handleWidgetMenuOpened,onMenuClosed:this.handleWidgetMenuClosed,options:{initialKeyboardIndex:1},popperOptions:a},"table-actions")]}),r.jsx(B,{kind:"ghost",className:"btn-overflow btn-link-icon",icon:Qc,tooltip:"More Actions...",onClick:()=>{},children:r.jsx(Vn,{actions:e,popperOptions:a})})]})}}const Mf=gl;class Lf extends v.PureComponent{static defaultProps={children:null};constructor(e){super(e),this.handleCommandStarted=this.handleCommandStarted.bind(this),this.handleCommandCompleted=this.handleCommandCompleted.bind(this),this.pending=new Yn,this.state={isDisconnected:!1,isCommandRunning:!1}}componentDidMount(){this.startListening()}componentWillUnmount(){this.stopListening(),this.cancelPendingPromises()}pending;startListening(){const{session:e}=this.props;e.addEventListener(I.IdeSession.EVENT_COMMANDSTARTED,this.handleCommandStarted)}stopListening(){const{session:e}=this.props;e.removeEventListener(I.IdeSession.EVENT_COMMANDSTARTED,this.handleCommandStarted)}cancelPendingPromises(){this.pending.cancel()}handleCommandStarted(e){const{result:t}=e.detail;this.pending.add(t).then(()=>this.handleCommandCompleted(null)).catch(n=>this.handleCommandCompleted(n)),this.setState({isCommandRunning:!0})}handleCommandCompleted(e){e instanceof Hl||this.setState({isCommandRunning:this.pending.pending.length>0})}render(){const{children:e,openObject:t,overflowActions:n,objects:s}=this.props,{isDisconnected:i,isCommandRunning:o}=this.state;let l=null,a=null;return i?(l="console-status-icon-disconnected",a="Worker is disconnected"):o?(l="console-status-icon-pending",a="Worker is busy"):(l="console-status-icon-idle",a="Worker is idle"),r.jsxs("div",{className:"console-pane-status-bar",children:[r.jsxs("div",{children:[r.jsx("div",{className:Y("console-status-icon",l)}),r.jsx(ot,{children:a})]}),e,r.jsx(Mf,{overflowActions:n,openObject:t,objects:s})]})}}const Of=Lf,On=ne.module("Console"),Md={isAutoLaunchPanelsEnabled:!0,isPrintStdOutEnabled:!0,isClosePanelsOnDisconnectEnabled:!0};class mi extends v.PureComponent{static defaultProps={statusBarChildren:null,settings:{},onSettingsChange:()=>{},scope:null,actions:[],historyChildren:null,timeZone:"America/New_York",objectMap:new Map,disabled:!1,unzip:null};static LOG_THROTTLE=500;static isErrorLevel(e){return e===Ct.STDERR||e===Ct.ERROR||e===Ct.FATAL}static isOutputLevel(e){return e===Ct.STDOUT||mi.isErrorLevel(e)}constructor(e){super(e),this.handleCommandResult=this.handleCommandResult.bind(this),this.handleCommandStarted=this.handleCommandStarted.bind(this),this.handleCommandSubmit=this.handleCommandSubmit.bind(this),this.handleClearShortcut=this.handleClearShortcut.bind(this),this.handleFocusHistory=this.handleFocusHistory.bind(this),this.handleLogMessage=this.handleLogMessage.bind(this),this.handleOverflowActions=this.handleOverflowActions.bind(this),this.handleScrollPaneScroll=this.handleScrollPaneScroll.bind(this),this.handleToggleAutoLaunchPanels=this.handleToggleAutoLaunchPanels.bind(this),this.handleToggleClosePanelsOnDisconnect=this.handleToggleClosePanelsOnDisconnect.bind(this),this.handleTogglePrintStdout=this.handleTogglePrintStdout.bind(this),this.handleUploadCsv=this.handleUploadCsv.bind(this),this.handleHideCsv=this.handleHideCsv.bind(this),this.handleCsvFileCanceled=this.handleCsvFileCanceled.bind(this),this.handleCsvFileOpened=this.handleCsvFileOpened.bind(this),this.handleCsvPaste=this.handleCsvPaste.bind(this),this.handleDragEnter=this.handleDragEnter.bind(this),this.handleDragLeave=this.handleDragLeave.bind(this),this.handleClearDragError=this.handleClearDragError.bind(this),this.handleOpenCsvTable=this.handleOpenCsvTable.bind(this),this.handleCsvUpdate=this.handleCsvUpdate.bind(this),this.handleCsvError=this.handleCsvError.bind(this),this.handleCsvInProgress=this.handleCsvInProgress.bind(this),this.consolePane=de.createRef(),this.consoleInput=de.createRef(),this.consoleHistoryScrollPane=de.createRef(),this.pending=new Yn,this.queuedLogMessages=[];const{objectMap:t,settings:n}=this.props;this.state={consoleHistory:[],consoleHeight:0,isScrollDecorationShown:!1,objectHistoryMap:new Map,objectMap:new Map(t),showCsvOverlay:!1,csvFile:null,csvPaste:null,dragError:null,csvUploadInProgress:!1,...Md,...n}}componentDidMount(){this.initConsoleLogging();const{session:e}=this.props;e.addEventListener(I.IdeSession.EVENT_COMMANDSTARTED,this.handleCommandStarted),this.updateDimensions()}componentDidUpdate(e,t){const{props:n,state:s}=this;this.sendSettingsChange(t,s),n.objectMap!==e.objectMap&&this.updateObjectMap()}componentWillUnmount(){const{session:e}=this.props;e.removeEventListener(I.IdeSession.EVENT_COMMANDSTARTED,this.handleCommandStarted),this.pending.cancel(),this.processLogMessageQueue.cancel(),this.deinitConsoleLogging()}cancelListener;consolePane;consoleInput;consoleHistoryScrollPane;pending;queuedLogMessages;initConsoleLogging(){const{session:e}=this.props;this.cancelListener=e.onLogMessage(this.handleLogMessage)}deinitConsoleLogging(){this.cancelListener!=null&&(this.cancelListener(),this.cancelListener=void 0)}handleClearShortcut(e){e.preventDefault(),e.stopPropagation(),this.consoleInput.current?.clear()}handleCommandStarted(e){const{code:t,result:n}=e.detail,s=this.pending.add(n),i={command:t,disabledObjects:[],startTime:Date.now(),cancelResult:()=>{n.cancel()},wrappedResult:s},{commandHistoryStorage:o,language:l,scope:a}=this.props,d=o.addItem(l,a,t,{command:t,startTime:new Date().toJSON()});d.catch(h=>{On.debug("Error adding workspace item",h)}),this.setState(h=>({consoleHistory:h.consoleHistory.concat(i)}),()=>{this.scrollConsoleHistoryToBottom(!0)}),s.then(h=>{this.handleCommandResult(h,i,d)}).catch(h=>{this.handleCommandError(h,i,d)})}handleCommandResult(e,t,n){const s={...t,wrappedResult:void 0,cancelResult:void 0,result:e??t.result};this.setState(({consoleHistory:i})=>{const o=i.lastIndexOf(t);if(o<0)return On.error("historyItem not found in consoleHistory"),null;const l=i.concat();return l[o]=s,{consoleHistory:l}}),e&&(this.updateHistory(e,s),this.updateKnownObjects(s),this.updateWorkspaceHistoryItem({error:e.error},n),this.closeRemovedItems(e.changes),this.openUpdatedItems(e.changes))}handleCommandError(e,t,n){if(ye.isCanceled(e)){On.debug("Called handleCommandError on a cancelled promise result");return}this.updateWorkspaceHistoryItem({error:`${e}`},n),this.setState(s=>{const i=s.consoleHistory.concat(),o=i.lastIndexOf(t),l={...t};return l.wrappedResult=void 0,l.cancelResult=void 0,l.endTime=Date.now(),l.result={error:e},i[o]=l,{consoleHistory:i}})}handleFocusHistory(e){e.preventDefault(),e.stopPropagation();const{focusCommandHistory:t}=this.props;t()}handleLogMessage(e){const{isPrintStdOutEnabled:t}=this.state;t&&mi.isOutputLevel(e.logLevel)&&this.queueLogMessage(e.message,e.logLevel)}queueLogMessage(e,t){const n={};mi.isErrorLevel(t)?n.error=e:n.message=e;const s={command:void 0,result:n};this.queuedLogMessages.push(s),this.processLogMessageQueue()}processLogMessageQueue=vs(()=>{this.scrollConsoleHistoryToBottom(),this.setState(e=>{On.debug2("processLogMessageQueue",this.queuedLogMessages.length," items");let{consoleHistory:t}=e;return t=t.concat(this.queuedLogMessages),this.queuedLogMessages=[],{consoleHistory:t}})},mi.LOG_THROTTLE);openUpdatedItems(e){const{isAutoLaunchPanelsEnabled:t}=this.state;if(e==null||!t)return;const{openObject:n}=this.props;[...e.created,...e.updated].forEach(s=>n(s))}closeRemovedItems(e){if(e==null||e.removed==null||e.removed.length===0)return;const{closeObject:t}=this.props,{removed:n}=e;n.forEach(s=>t(s))}updateHistory(e,t){const n=t;e==null||e.changes==null||n==null||(n.endTime=Date.now(),this.scrollConsoleHistoryToBottom(),this.setState(s=>({consoleHistory:s.consoleHistory.concat()})))}updateKnownObjects(e){let t;if(e.result&&(t=e.result.changes),!t||(t.created==null||t.created.length===0)&&(t.updated==null||t.updated.length===0)&&(t.removed==null||t.removed.length===0)){On.debug2("updateKnownObjects no changes");return}this.setState(n=>{let{consoleHistory:s}=n;const i=s.lastIndexOf(e);if(i<0)return On.error("historyItem not found in state.consoleHistory"),null;const o=new Map(n.objectHistoryMap),l=new Map(n.objectMap),a=(d,h=!1)=>{const{title:u}=d;N(u);const m=o.get(u);if(m!=null&&m>=0){s===n.consoleHistory&&(s=s.concat());const g={...s[m],disabledObjects:[...s[m].disabledObjects??[],u]};s[m]=g}o.set(u,i),h?l.delete(u):l.set(u,d)};return t?.updated.forEach(d=>a(d)),t?.removed.forEach(d=>a(d,!0)),t?.created.forEach(d=>{const{title:h}=d;N(h),o.set(h,i),l.set(h,d)}),{objectHistoryMap:o,objectMap:l,consoleHistory:s}})}updateObjectMap(){const{objectMap:e}=this.props;this.setState({objectMap:e})}updateWorkspaceHistoryItem(e,t){const n=this.pending.add(t),s=new Date().toJSON();n.then(i=>{const o={...i,data:{...i.data,endTime:s,result:e}},{commandHistoryStorage:l,language:a}=this.props;l.updateItem(a,o).catch(d=>{On.warn("Error updating command history storage",d)})}).catch(i=>{On.debug("Error updating workspace history item",i)})}scrollConsoleHistoryToBottom(e=!1){const t=this.consoleHistoryScrollPane.current;N(t),!(!e&&t.scrollTop<t.scrollHeight-t.offsetHeight)&&window.requestAnimationFrame(()=>{t.scrollTop=t.scrollHeight})}handleScrollPaneScroll(){const e=this.consoleHistoryScrollPane.current;N(e),e.scrollTop>0&&e.scrollHeight>e.clientHeight?this.setState({isScrollDecorationShown:!0}):this.setState({isScrollDecorationShown:!1})}handleToggleAutoLaunchPanels(){this.setState(e=>({isAutoLaunchPanelsEnabled:!e.isAutoLaunchPanelsEnabled}))}handleToggleClosePanelsOnDisconnect(){this.setState(e=>({isClosePanelsOnDisconnectEnabled:!e.isClosePanelsOnDisconnectEnabled}))}handleTogglePrintStdout(){this.setState(e=>({isPrintStdOutEnabled:!e.isPrintStdOutEnabled}))}handleUploadCsv(){this.setState({showCsvOverlay:!0,dragError:null,csvUploadInProgress:!1})}handleHideCsv(){this.setState({showCsvOverlay:!1,csvFile:null,csvPaste:null,dragError:null,csvUploadInProgress:!1})}handleCsvFileCanceled(){this.setState({csvFile:null,csvPaste:null})}handleCsvFileOpened(e){this.setState({csvFile:e,csvPaste:null})}handleCsvPaste(e){this.setState({csvFile:null,csvPaste:e})}handleDragEnter(e){if(e.dataTransfer==null||e.dataTransfer.items==null||e.dataTransfer.items.length===0||e.dataTransfer.items[0].kind==="string")return;e.preventDefault(),e.stopPropagation(),this.setState({showCsvOverlay:!0});const{items:t}=e.dataTransfer;if(t.length>1){this.setState({dragError:ui.MULTIPLE_FILE_ERROR});return}const n=t[0];ui.isValidDropItem(n)?this.setState({dragError:null}):this.setState({dragError:ui.FILE_TYPE_ERROR})}handleDragLeave(e){e.currentTarget==null||e.currentTarget instanceof Element&&e.relatedTarget instanceof Element&&e.currentTarget.contains(e.relatedTarget)||(e.preventDefault(),e.stopPropagation(),this.setState({showCsvOverlay:!1,dragError:null}))}handleClearDragError(){this.setState({dragError:null})}handleOpenCsvTable(e){const{openObject:t,commandHistoryStorage:n,language:s,scope:i}=this.props,{consoleHistory:o,objectMap:l}=this.state,a={name:e,title:e,type:I.VariableType.TABLE},d=l.has(e),h={startTime:Date.now(),endTime:Date.now(),disabledObjects:[],result:{changes:{created:[],updated:[],removed:[],[d?"updated":"created"]:[a]}}},u=o.concat(h);this.setState({consoleHistory:u}),this.scrollConsoleHistoryToBottom(!0),this.updateKnownObjects(h),t({name:e,title:e,type:I.VariableType.TABLE}),n.addItem(s,i,e,{command:e,startTime:new Date().toJSON(),endTime:new Date().toJSON()})}addConsoleHistoryMessage(e,t){const{consoleHistory:n}=this.state,s={command:"",startTime:Date.now(),endTime:Date.now(),result:{message:e,error:t}},i=n.concat(s);this.setState({consoleHistory:i})}handleCsvUpdate(e){this.addConsoleHistoryMessage(e)}handleCsvError(e){this.addConsoleHistoryMessage(void 0,e!=null?`${e}`:void 0)}handleCsvInProgress(e){this.setState({csvUploadInProgress:e})}handleOverflowActions(){const{isAutoLaunchPanelsEnabled:e,isClosePanelsOnDisconnectEnabled:t,isPrintStdOutEnabled:n}=this.state,{actions:s}=this.props;return[...s,{title:"Print Stdout",action:this.handleTogglePrintStdout,group:ie.groups.high,icon:n?zn:void 0,order:10},{title:"Auto Launch Panels",action:this.handleToggleAutoLaunchPanels,group:ie.groups.high,icon:e?zn:void 0,order:20},{title:"Close Panels on Disconnect",action:this.handleToggleClosePanelsOnDisconnect,group:ie.groups.high,icon:t?zn:void 0,order:30},{title:"Upload Table from File",action:this.handleUploadCsv,group:ie.groups.high+10,order:40}]}handleCommandSubmit(e){if(e==="clear"||e==="cls")this.clearConsoleHistory();else if(e.length>0){const{session:t}=this.props;t.runCode(e).catch(n=>{On.error("There was an error initiating the command",n)})}else{const t={command:" ",result:{},startTime:Date.now(),endTime:Date.now()};this.scrollConsoleHistoryToBottom(!0),this.setState(n=>({consoleHistory:n.consoleHistory.concat(t)}))}}clearConsoleHistory(){this.pending.cancel(),this.setState(e=>{const t=new Map([...e.objectHistoryMap.keys()].map(n=>[n,-1]));return{consoleHistory:[],objectHistoryMap:t}})}getObjects=ge(e=>[...e.values()]);getContextActions=ge(e=>[...e,{action:this.handleClearShortcut,shortcut:Nt.CONSOLE.CLEAR},{action:this.handleFocusHistory,shortcut:Nt.CONSOLE.FOCUS_HISTORY}]);addCommand(e,t=!0,n=!1){this.consoleInput.current&&(this.consoleInput.current.setConsoleText(e,t,n),t&&this.scrollConsoleHistoryToBottom(!0))}focus(){this.consoleInput.current?.focus()}sendSettingsChange(e,t,n=!0){const s=Object.keys(Md),i={};let o=!1;for(let a=0;a<s.length;a+=1){const d=s[a],{[d]:h}=t,{[d]:u}=e;h!==u&&(o=!0),i[d]=h}if(n&&!o)return;const{onSettingsChange:l}=this.props;l(i)}updateDimensions(){this.consolePane.current&&this.setState({consoleHeight:this.consolePane.current.clientHeight}),this.consoleInput.current&&this.consoleInput.current.updateDimensions()}render(){const{actions:e,historyChildren:t,language:n,statusBarChildren:s,openObject:i,session:o,scope:l,commandHistoryStorage:a,timeZone:d,disabled:h,unzip:u}=this.props,{consoleHeight:m,consoleHistory:g,isScrollDecorationShown:p,objectMap:C,showCsvOverlay:f,csvFile:b,csvPaste:w,dragError:S,csvUploadInProgress:T}=this.state,y=this.getObjects(C),E=Math.round(m*.7),R=this.getContextActions(e);return r.jsxs("div",{role:"presentation",className:Y("iris-console","h-100","w-100",{disabled:h}),children:[r.jsxs("div",{className:"console-pane",ref:this.consolePane,children:[r.jsx(Of,{session:o,overflowActions:this.handleOverflowActions,openObject:i,objects:y,children:s}),r.jsxs("div",{className:"console-csv-container",onDragOver:ui.handleDragOver,onDragEnter:this.handleDragEnter,onDragLeave:this.handleDragLeave,children:[f&&r.jsx(ui,{onCancel:this.handleCsvFileCanceled,onFileOpened:this.handleCsvFileOpened,onPaste:this.handleCsvPaste,clearDragError:this.handleClearDragError,dragError:S,onError:this.handleCsvError,uploadInProgress:T,allowZip:u!=null}),r.jsxs("div",{role:"presentation",className:Y("scroll-pane no-scroll-x",{"scroll-decoration":p}),onScroll:this.handleScrollPaneScroll,ref:this.consoleHistoryScrollPane,children:[r.jsx(Mp,{items:g,openObject:i,language:n,disabled:h}),t]})]}),!f&&r.jsx(yd,{ref:this.consoleInput,session:o,language:n,scope:l,onSubmit:this.handleCommandSubmit,maxHeight:E,commandHistoryStorage:a}),f&&r.jsx(kf,{session:o,onOpenTable:this.handleOpenCsvTable,onClose:this.handleHideCsv,onUpdate:this.handleCsvUpdate,onError:this.handleCsvError,file:b??void 0,paste:w??void 0,onInProgress:this.handleCsvInProgress,timeZone:d,unzip:u})]}),r.jsx(ie,{actions:R,ignoreClassNames:[yd.INPUT_CLASS_NAME]})]})}}const Af=mi;class _f extends v.Component{static defaultProps={className:"fill-parent-absolute",onEditorInitialized:()=>{},onEditorWillDestroy:()=>{},settings:{}};constructor(e){super(e),this.handleResize=this.handleResize.bind(this),this.container=null,this.state={}}componentDidMount(){this.initEditor(),window.addEventListener("resize",this.handleResize)}componentWillUnmount(){window.removeEventListener("resize",this.handleResize),this.destroyEditor()}container;editor;setLanguage(e){if(this.editor){const t=this.editor.getModel();N(t),Gn.setModelLanguage(t,e)}}handleResize(){this.updateDimensions()}toggleFind(){this.editor&&(this.editor.focus(),this.editor.trigger("toggleFind","actions.find",void 0))}updateDimensions(){this.editor?.layout()}initEditor(){const{onEditorInitialized:e}=this.props;let{settings:t}=this.props;t={copyWithSyntaxHighlighting:!1,fixedOverflowWidgets:!0,folding:!1,fontFamily:"Fira Mono",glyphMargin:!1,language:"python",lineNumbersMinChars:3,minimap:{enabled:!1},scrollBeyondLastLine:!1,tabCompletion:"on",value:"",wordWrap:"off",links:!0,...t},N(this.container),this.editor=Gn.create(this.container,t),this.editor.addAction({id:"find",label:"Find",keybindings:[tn.CtrlCmd|ps.KeyF],precondition:void 0,keybindingContext:void 0,contextMenuGroupId:"navigation",contextMenuOrder:1,run:()=>{this.toggleFind()}}),this.editor.layout(),At.removeConflictingKeybindings(this.editor),yn.registerLinkProvider("plaintext",{provideLinks:At.provideLinks}),e(this.editor)}destroyEditor(){const{onEditorWillDestroy:e}=this.props;N(this.editor),e(this.editor),this.editor.dispose(),this.editor=void 0}render(){const{className:e}=this.props;return r.jsx("div",{className:Y("editor-container",e),ref:t=>{this.container=t}})}}const br=_f;const qt=ne.module("ScriptEditor");class Pf extends v.Component{static defaultProps={error:null,isLoading:!1,isLoaded:!1,focusOnMount:!0,onChange:()=>{},onEditorInitialized:()=>{},onEditorWillDestroy:()=>{},session:null};constructor(e){super(e),this.handleEditorInitialized=this.handleEditorInitialized.bind(this),this.handleEditorWillDestroy=this.handleEditorWillDestroy.bind(this),this.handleRun=this.handleRun.bind(this),this.handleRunSelected=this.handleRunSelected.bind(this),this.updateShortcuts=this.updateShortcuts.bind(this),this.contextActionCleanups=[],this.editorComponent=de.createRef(),this.state={model:null}}componentDidMount(){We.addEventListener("onUpdate",this.updateShortcuts)}componentDidUpdate(e){const{sessionLanguage:t,settings:n}=this.props,s=n?.language;s!==e.settings?.language&&(qt.debug("Set language",s),this.setLanguage(s));const o=t==null&&e.sessionLanguage!=null,l=s===t,a=e.settings?.language===e.sessionLanguage;(o||t!==void 0&&a&&!l)&&(qt.debug("De-init completion and context actions"),this.deInitContextActions(),this.deInitCodeCompletion()),(t!=null&&e.sessionLanguage==null&&l||t!==void 0&&!a&&l)&&(qt.debug("Init completion and context actions"),this.initContextActions(),this.initCodeCompletion())}componentWillUnmount(){We.removeEventListener("onUpdate",this.updateShortcuts)}contextActionCleanups;completionCleanup;editor;editorComponent;getValue(){return this.editor?this.editor.getValue():(qt.error("Editor not initialized"),null)}getSelectedCommand(){const e=this.editor?.getSelection();N(e);const t=this.editor?.getModel();N(t);const{startLineNumber:n,endColumn:s}=e;let{endLineNumber:i}=e;s===1&&i>n&&(i-=1);const o=t?.getLineMinColumn(n),l=t?.getLineMaxColumn(i),a=e.setStartPosition(n,o).setEndPosition(i,l);return t?.getValueInRange(a)}handleEditorInitialized(e){const{focusOnMount:t,onChange:n,onEditorInitialized:s,settings:i,session:o,sessionLanguage:l}=this.props;qt.debug("handleEditorInitialized",l,o,i),this.editor=e,this.setState({model:this.editor.getModel()}),At.setEOL(e),At.registerPasteHandler(e),o!=null&&i&&l===i.language&&(this.initContextActions(),this.initCodeCompletion()),e.onDidChangeModelContent(n),t!=null&&t&&e.focus(),s(this.editor)}handleEditorWillDestroy(e){qt.debug("handleEditorWillDestroy");const{onEditorWillDestroy:t}=this.props;t(e),this.deInitContextActions(),this.deInitCodeCompletion(),this.setState({model:null}),this.editor=void 0}handleRun(){const{onRunCommand:e}=this.props,t=this.getValue();t!=null&&e(t)}handleRunSelected(){const{onRunCommand:e}=this.props,t=this.getSelectedCommand();e(t)}initContextActions(){if(this.contextActionCleanups.length>0){qt.error("Context actions already initialized.");return}if(!this.editor)return;const e=[];e.push(this.editor.addAction({id:"run-code",label:"Run",keybindings:[At.getMonacoKeyCodeFromShortcut(Nt.NOTEBOOK.RUN)],contextMenuGroupId:"navigation",contextMenuOrder:1.5,run:()=>{this.handleRun()}})),e.push(this.editor.addAction({id:"run-selected-code",label:"Run Selected",keybindings:[At.getMonacoKeyCodeFromShortcut(Nt.NOTEBOOK.RUN_SELECTED)],contextMenuGroupId:"navigation",contextMenuOrder:1.5,run:()=>{this.handleRunSelected()}})),this.contextActionCleanups=e}deInitContextActions(){this.contextActionCleanups.length>0&&(this.contextActionCleanups.forEach(e=>e.dispose()),this.contextActionCleanups=[])}updateShortcuts(){this.deInitContextActions(),this.initContextActions()}initCodeCompletion(){if(this.completionCleanup!=null){qt.error("Code completion already initialized.");return}const{session:e}=this.props;qt.debug("initCodeCompletion",this.editor,e),this.editor&&e!=null&&(this.completionCleanup=At.openDocument(this.editor,e))}deInitCodeCompletion(){const{session:e}=this.props;qt.debug("deInitCodeCompletion",this.editor,e),this.completionCleanup&&(this.completionCleanup.dispose(),this.completionCleanup=void 0,this.editor&&e!=null&&At.closeDocument(this.editor,e))}append(e,t=!0){N(this.editor);const n=this.editor.getModel();N(n);const s=n.getValue();s?n.setValue(`${s}
10
10
  ${e}`):n.setValue(`${e}`);const i=n.getLineCount(),o=n.getLineLength(i)+1;this.editor.setPosition({lineNumber:i,column:o}),t&&this.editor.focus()}updateDimensions(){qt.debug("updateDimensions"),this.editor&&this.editor.layout()}focus(){qt.debug("focus"),this.editor&&this.editor.focus()}toggleFind(){this.editorComponent.current&&this.editorComponent.current.toggleFind()}setLanguage(e){this.editorComponent.current&&e!==void 0&&this.editorComponent.current.setLanguage(e)}render(){const{error:e,isLoaded:t,isLoading:n,session:s,sessionLanguage:i,settings:o}=this.props,{model:l}=this.state,a=e?`Unable to open document. ${e}`:null,d=o?o.language??null:null,h=l&&s&&d===i;return r.jsxs(r.Fragment,{children:[(e||n)&&r.jsx("div",{className:"h-100 w-100 position-relative",children:r.jsx($l,{errorMessage:a,isLoading:n,isLoaded:t})}),t&&r.jsx("div",{className:"h-100 w-100 script-editor",children:o&&r.jsxs(r.Fragment,{children:[r.jsx(br,{ref:this.editorComponent,settings:o,onEditorInitialized:this.handleEditorInitialized,onEditorWillDestroy:this.handleEditorWillDestroy}),h!=null&&h&&r.jsx(hh,{model:l,language:d,session:s})]})})]})}}const jf=Pf,Hf={groovy:"Groovy",python:"Python",scala:"Scala"};class Bf{static normalizeScriptLanguage(e){return Hf[e]||null}static getDisabledRunTooltip(e,t,n,s){return e?t?null:`${n} doesn't match the session language – ${s} disabled`:`Console session not connected – ${s} disabled`}}const Ld=Bf;const Uf=250,Vf=2500;class Sr extends v.Component{static defaultProps={onUpdate:()=>{}};static getTimeString(e,t){if(e==null||t===""||t===0)return null;const n=Math.round((new Date(t).valueOf()-new Date(e).valueOf())/1e3);return n<1?"<1s":jl.formatElapsedTime(n)}constructor(e){super(e),this.handleUpdate=this.handleUpdate.bind(this),this.handleError=this.handleError.bind(this),this.handleTimeout=this.handleTimeout.bind(this),this.state={currentTime:Date.now()}}componentDidMount(){this.loadData()}componentDidUpdate(e,t){const{data:n}=this.state;this.timer==null&&!n?.result&&Boolean(n?.startTime)&&!(n==null||n.endTime===void 0)?this.startTimer():(n?.result&&!t.data?.result||Boolean(n?.endTime)&&!(t.data==null||t.data.endTime===void 0))&&this.stopTimer()}componentWillUnmount(){this.loadData.cancel(),this.cleanup!=null&&this.cleanup(),this.stopTimer()}timer;cleanup;loadData=Ye(()=>{const{commandHistoryStorage:e,item:t,language:n}=this.props,{id:s}=t;this.cleanup=e.listenItem(n,s,this.handleUpdate,this.handleError)},Uf);startTimer(){this.stopTimer(),this.timer=setInterval(this.handleTimeout,1e3)}stopTimer(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}updateTime(){this.setState({currentTime:Date.now()})}handleError(e){this.setState({error:`${e}`})}handleUpdate(e){const{data:t}=e??{};this.setState({data:t});const{onUpdate:n}=this.props;n?.(t)}handleTimeout(){this.updateTime()}getPreviewText=Re(e=>e.split(`
11
11
  `,Vf).join(`
12
12
  `),{max:1});render(){const{item:{name:e},language:t}=this.props,{currentTime:n,data:s,error:i}=this.state,{result:o,startTime:l,endTime:a}=s??{},d=o?.error??i,h=Sr.getTimeString(l,a??n),u=this.getPreviewText(e),m=Boolean(h);return r.jsxs("div",{className:"command-history-item-tooltip",children:[r.jsxs("div",{className:"scroll-container",children:[r.jsx(Yl,{language:t,children:u}),u.length<e.length&&r.jsx("p",{children:"Preview Truncated..."})]}),r.jsxs("div",{className:"result-info",children:[r.jsxs("div",{className:"d-flex justify-content-between",children:[Boolean(d)&&r.jsxs("div",{className:"text-danger mr-1",children:[r.jsx(ee,{icon:ws})," Executed with errors"]}),r.jsxs("div",{className:"time-wrapper",children:["Elapsed time:"," ",m?r.jsx("span",{className:"time-string",children:h}):r.jsx(In,{})]})]}),Boolean(d)&&r.jsx("div",{className:"error-message",children:d})]})]})}}const $f=Sr,Wf=512;function gh(c){const{item:e,language:t,isSelected:n,commandHistoryStorage:s}=c,i=e.name.substring(0,Wf),o=v.useRef(null),l=v.useCallback(()=>{o.current?.update()},[o]);return r.jsxs("div",{className:Y("command-history-item",{selected:n}),children:[i,r.jsx(ot,{ref:o,interactive:!0,options:{placement:"left",modifiers:{preventOverflow:{enabled:!0,boundariesElement:"viewport",order:825}}},popperClassName:"command-history-item-popper",children:r.jsx($f,{item:e,language:t,onUpdate:l,commandHistoryStorage:s})})]})}gh.defaultProps={isSelected:!1};class pl extends v.Component{static itemKey(e,t){return`${t.title}`}static renderContent(e){return e.selectionRequired!==void 0&&e.selectionRequired?r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx(ee,{icon:Ri,mask:e.icon,transform:"right-5 down-5 shrink-4"}),r.jsx(ee,{icon:ag,transform:"shrink-3 right-7 down-6"})]}):r.jsx(ee,{icon:e.icon})}render(){const{actions:e,hasSelection:t}=this.props;return r.jsx("div",{className:"command-history-actions",children:e.map((n,s)=>r.jsx(B,{kind:"inline",className:Y(n.className),onClick:n.action,tooltip:n.description,disabled:n.selectionRequired!==void 0&&n.selectionRequired&&!t,icon:pl.renderContent(n)},pl.itemKey(s,n)))})}}const Gf=pl;const zf=150,Kf=150,Od=3,Ad=ne.module("CommandHistoryViewportUpdater");function Yf({table:c,columns:e,top:t=0,bottom:n=0,search:s,isReversed:i=!1,onUpdate:o}){const l=v.useMemo(()=>Ye(d=>{c.setSearch(d??"")},zf),[c]),a=v.useMemo(()=>vs(d=>{const h=d.bottom-d.top,u=Math.max(0,d.top-h*Od),m=d.bottom+h*Od;c.setViewport({top:u,bottom:m,columns:d.columns})},Kf),[c]);return v.useEffect(function(){const h=c.onUpdate(u=>{o({items:u.items??[],offset:u.offset??0})});return()=>{Ad.debug("onUpdate cleanup"),h()}},[c,o]),v.useEffect(function(){l(s)},[l,s]),v.useEffect(function(){a({top:t,bottom:n,columns:e})},[a,t,n,e,s,i]),v.useEffect(()=>()=>{Ad.debug2("Cancel throttledUpdateViewport"),a.cancel()},[a]),null}const es=ne.module("CommandHistory");class vn extends v.Component{static ITEM_HEIGHT=29;static MAX_SELECTION_COUNT=1e4;static menuGroups={send:ie.groups.medium+100};static getCommandsFromViewport(e,t,n){const s=[];for(let i=0;i<n.length;i+=1){const o=n[i];for(let l=o[0];l<=o[1];l+=1)if(l>=t&&l<t+e.length){const{name:a}=e[l-t];s.push(a)}}return s}static async getCommandsFromSnapshot(e,t){return[...(await e.getSnapshot(t)).values()].map(s=>s.name)}constructor(e){super(e),this.copySelectedCommands=this.copySelectedCommands.bind(this),this.createNotebook=this.createNotebook.bind(this),this.sendToConsole=this.sendToConsole.bind(this),this.renderItem=this.renderItem.bind(this),this.runInConsole=this.runInConsole.bind(this),this.sendToNotebook=this.sendToNotebook.bind(this),this.handleSelect=this.handleSelect.bind(this),this.handleSelectionChange=this.handleSelectionChange.bind(this),this.handleSearchChange=this.handleSearchChange.bind(this),this.handleViewportChange=this.handleViewportChange.bind(this),this.handleViewportUpdate=this.handleViewportUpdate.bind(this),this.itemActions=[{title:"Copy Selection",description:"Copy selected commands to clipboard",icon:rg,shortcut:Kn.COPY,action:this.copySelectedCommands,group:ie.groups.edit},{title:"Send to Console",description:"Open selected commands in the console",icon:Cd,shortcut:Nt.COMMAND_HISTORY.SEND_TO_CONSOLE,action:this.sendToConsole,group:vn.menuGroups.send,order:10},{title:"Run in Console",description:"Run selected commands in the console",icon:rl,shortcut:Nt.COMMAND_HISTORY.RUN,action:this.runInConsole,group:vn.menuGroups.send,order:10},{title:"Send to Active Notebook",description:"Open selected commands in a notebook",icon:bd,shortcut:Nt.COMMAND_HISTORY.SEND_TO_NOTEBOOK,action:this.sendToNotebook,group:vn.menuGroups.send,order:20},{title:"Send to New Notebook",description:"Open selected commands in a new notebook",icon:Jc,action:this.createNotebook,group:vn.menuGroups.send,order:30}],this.historyActions=[{title:"Send to Console",icon:Cd,selectionRequired:!0,description:"Open selected commands in the console",action:this.sendToConsole},{title:"Send to Notebook",icon:bd,selectionRequired:!0,description:"Open selected commands in a notebook",action:this.sendToNotebook}],this.pending=new Yn,this.searchInputRef=de.createRef(),this.itemListRef=de.createRef();const{table:t}=e;this.state={actions:[],historyActions:this.historyActions,top:0,bottom:0,itemCount:t.size,items:[],offset:0,selectedRanges:[],searchText:""}}componentWillUnmount(){this.pending.cancel()}itemActions;historyActions;pending;searchInputRef;itemListRef;async getSelectedCommands(){const{items:e,offset:t,selectedRanges:n}=this.state,s=n.slice().sort((o,l)=>o[0]-l[0]);if(s.length===0)return[];if(s[0][0]>=t&&s[s.length-1][1]<t+e.length)return vn.getCommandsFromViewport(e,t,s);const{table:i}=this.props;return this.pending.add(vn.getCommandsFromSnapshot(i,s))}getSelectedCommandText(){return this.getSelectedCommands().then(e=>e.join(`
@@ -15,9 +15,9 @@ ${e}`):n.setValue(`${e}`);const i=n.getLineCount(),o=n.getLineLength(i)+1;this.e
15
15
  `&&(n+=`
16
16
  `))}}if(n=n.trimRight(),this.editor.setValue(n),t){const s=this.editor.getModel()?.getLineCount();N(s),this.editor.revealLine(s,1)}this.stopFlushTimer(),this.bufferedMessages=[]}truncateLogIfNecessary(){this.messages.length>Rt.maxLogSize&&(this.messages=this.messages.splice(this.messages.length-Rt.truncateSize))}scrollToBottom(){if(!this.editor)return;const e=this.editor?.getModel?.()?.getLineCount();N(e),this.editor.revealLine(e,1)}isBottomVisible(){if(!this.editor)return!0;const t=this.editor.getModel()?.getLineCount();return N(t),this.isLineVisible(t)}isLineVisible(e){const t=this.editor?.getVisibleRanges();if(t==null||t.length===0)return!1;for(let n=0;n<t.length;n+=1){const s=t[n];if(s.startLineNumber<=e&&e<=s.endLineNumber)return!0}return!1}isLogItemVisible(e){const{shownLogLevels:t}=this.state;return t[e.logLevel]}flush(){let e="";for(let t=0;t<this.bufferedMessages.length;t+=1){const n=this.bufferedMessages[t],s=Rt.getLogText(n);e+=s,s.charAt(s.length-1)!==`
17
17
  `&&(e+=`
18
- `)}this.bufferedMessages=[],this.appendLogText(e)}queue(e){this.bufferedMessages.push(e),this.bufferedMessages.length===1&&(this.flushTimer=setTimeout(this.handleFlushTimeout,Rt.bufferTimeout))}stopFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}updateDimensions(){this.editor&&this.editor.layout()}handleClearClick(){this.clearLogs()}clearLogs(){this.messages=[],this.refreshLogText()}handleFlushTimeout(){this.stopFlushTimer(),this.flush()}handleLogMessage(e){this.messages.push(e),this.editor&&this.isLogItemVisible(e)&&this.queue(e)}handleMenuItemClick(e){this.toggleLogLevel(e)}handleResetClick(){this.resetLogLevels()}handleResize(){this.updateDimensions()}handleToggleAllClick(){this.toggleAll()}render(){const e={placement:"bottom-end"},{shownLogLevels:t}=this.state,n=this.getMenuActions(t);return r.jsxs("div",{className:"log-pane h-100 w-100",children:[r.jsxs("div",{className:"log-pane-menu",children:[r.jsx(B,{kind:"ghost",className:"btn-clear-logs",onClick:this.handleClearClick,icon:dg,tooltip:"Clear log"}),r.jsx(B,{kind:"ghost",className:"btn-link-icon btn-overflow",icon:mo,tooltip:"Log Settings",onClick:()=>{},children:r.jsx(Vn,{actions:n,popperClassName:"log-level-menu-popper",popperOptions:e})})]}),r.jsx("div",{className:"log-pane-editor h-100 w-100",ref:s=>{this.editorContainer=s}})]})}}const Qf=Rt;function ph(c){switch(c){case be.eq:return"is exactly";case be.eqIgnoreCase:return"is exactly (ignore case)";case be.notEq:return"is not exactly";case be.notEqIgnoreCase:return"is not exactly (ignore case)";case be.contains:return"contains";case be.notContains:return"does not contain";case be.startsWith:return"starts with";case be.endsWith:return"ends with";default:throw new Error(`Unrecognized text filter type ${c}`)}}function fh(c){switch(c){case be.eq:return"is equal to";case be.notEq:return"is not equal to";case be.greaterThan:return"greater than";case be.greaterThanOrEqualTo:return"greater than or equal to";case be.lessThan:return"less than";case be.lessThanOrEqualTo:return"less than or equal to";default:throw new Error(`Unrecognized number filter type ${c}`)}}function Ch(c){switch(c){case be.eq:return"date is";case be.notEq:return"date is not";case be.notEqIgnoreCase:case be.greaterThan:return"date is after";case be.greaterThanOrEqualTo:return"date is after or equal";case be.lessThan:return"date is before";case be.lessThanOrEqualTo:return"date is before or equal";default:throw new Error(`Unrecognized date filter type ${c}`)}}function Jf(c){switch(c){case be.isTrue:return"Is True";case be.isFalse:return"Is False";case be.isNull:return"Is Null";default:throw new Error(`Unrecognized boolean filter type ${c}`)}}hl.register([cp,hp,up,mp,gp,pp]);const bh=typeof fa=="function"?fa(hl):fa.default(hl);class Tn{static EVENT_UPDATED="ChartModel.EVENT_UPDATED";static EVENT_DISCONNECT="ChartModel.EVENT_DISCONNECT";static EVENT_RECONNECT="ChartModel.EVENT_RECONNECT";static EVENT_DOWNSAMPLESTARTED="ChartModel.EVENT_DOWNSAMPLESTARTED";static EVENT_DOWNSAMPLEFINISHED="ChartModel.EVENT_DOWNSAMPLEFINISHED";static EVENT_DOWNSAMPLEFAILED="ChartModel.EVENT_DOWNSAMPLEFAILED";static EVENT_DOWNSAMPLENEEDED="ChartModel.EVENT_DOWNSAMPLENEEDED";static EVENT_LOADFINISHED="ChartModel.EVENT_LOADFINISHED";constructor(){this.listeners=[],this.isDownsamplingDisabled=!1}listeners;formatter;rect;isDownsamplingDisabled;title;getData(){return[]}getDefaultTitle(){return""}getLayout(){return{}}getFilterColumnMap(){return new Map}isFilterRequired(){return!1}setFilter(e){}close(){}setFormatter(e){this.formatter=e}setDownsamplingDisabled(e){this.isDownsamplingDisabled=e}setDimensions(e){this.rect=e}setTitle(e){this.title=e}subscribe(e){this.listeners.push(e)}unsubscribe(e){this.listeners=this.listeners.filter(t=>t!==e)}fireEvent(e){for(let t=0;t<this.listeners.length;t+=1)this.listeners[t](e)}fireUpdate(e){this.fireEvent(new CustomEvent(Tn.EVENT_UPDATED,{detail:e}))}fireDisconnect(){this.fireEvent(new CustomEvent(Tn.EVENT_DISCONNECT))}fireReconnect(){this.fireEvent(new CustomEvent(Tn.EVENT_RECONNECT))}fireDownsampleStart(e){this.fireEvent(new CustomEvent(Tn.EVENT_DOWNSAMPLESTARTED,{detail:e}))}fireDownsampleFinish(e){this.fireEvent(new CustomEvent(Tn.EVENT_DOWNSAMPLEFINISHED,{detail:e}))}fireDownsampleFail(e){this.fireEvent(new CustomEvent(Tn.EVENT_DOWNSAMPLEFAILED,{detail:e}))}fireDownsampleNeeded(e){this.fireEvent(new CustomEvent(Tn.EVENT_DOWNSAMPLENEEDED,{detail:e}))}fireLoadFinished(){this.fireEvent(new CustomEvent(Tn.EVENT_LOADFINISHED))}}const _n=Tn,eC="#76d9e4 #9edc6f #fcd65b #aa9af4 #f37e3f #f95d84 #f0f0ee",tC="#403e41",nC="#5b5a5c",sC="#c0bfbf",iC="#4878ea",oC="rgba(91, 90, 92, 0.7)",Tt={"paper-bgcolor":"#2d2a2e","plot-bgcolor":"#322f33","title-color":"#f0f0ee",colorway:eC,gridcolor:tC,linecolor:nC,zerolinecolor:sC,activecolor:iC,rangebgcolor:oC,"area-color":"#76d9e4","trend-color":"#d5f0c1","line-color":"#9edc6f","error-band-line-color":"white","error-band-fill-color":"rgba(213, 240, 193, 0.1)","ohlc-increasing":"#9edc6f","ohlc-decreasing":"#f95d84"},At=Object.freeze({paper_bgcolor:Tt["paper-bgcolor"],plot_bgcolor:Tt["plot-bgcolor"],title_color:Tt["title-color"],colorway:Tt.colorway,gridcolor:Tt.gridcolor,linecolor:Tt.linecolor,zerolinecolor:Tt.zerolinecolor,activecolor:Tt.activecolor,rangebgcolor:Tt.rangebgcolor,area_color:Tt["area-color"],trend_color:Tt["trend-color"],line_color:Tt["line-color"],error_band_line_color:Tt["error-band-line-color"],error_band_fill_color:Tt["error-band-fill-color"],ohlc_increasing:Tt["ohlc-increasing"],ohlc_decreasing:Tt["ohlc-decreasing"]}),ji=ne.module("ChartUtils"),ts=Object.freeze(I.calendar.DayOfWeek.values()),_d="io.deephaven.time.DateTime",lC=36e5,aC=1e6;function rC(c){return c.asDate!==void 0}function dC(c){return c.asNumber!==void 0}function Pd(c){return c.dhTimeZone!==void 0}function cC(c){return c!=null&&c.range!=null&&(c.autorange===!1||c.autorange===void 0)}class se{static DEFAULT_AXIS_SIZE=.15;static MIN_AXIS_SIZE=.025;static MAX_AXIS_SIZE=.2;static AXIS_SIZE_PX=75;static LEGEND_WIDTH_PX=50;static MAX_LEGEND_SIZE=.25;static ORIENTATION=Object.freeze({HORIZONTAL:"h",VERTICAL:"v"});static DATE_FORMAT="yyyy-MM-dd HH:mm:ss.SSSSSS";static DEFAULT_MARGIN=Object.freeze({l:60,r:50,t:30,b:60,pad:0});static DEFAULT_TITLE_PADDING=Object.freeze({t:8});static SUBTITLE_LINE_HEIGHT=25;static DEFAULT_MARKER_SIZE=6;static MODE_MARKERS="markers";static MODE_LINES="lines";static getPlotlyChartType(e,t){switch(e){case I.plot.SeriesPlotStyle.SCATTER:return t?"scatter":"scattergl";case I.plot.SeriesPlotStyle.LINE:return"scatter";case I.plot.SeriesPlotStyle.BAR:case I.plot.SeriesPlotStyle.STACKED_BAR:return"bar";case I.plot.SeriesPlotStyle.PIE:return"pie";case I.plot.SeriesPlotStyle.TREEMAP:return"treemap";case I.plot.SeriesPlotStyle.HISTOGRAM:return"histogram";case I.plot.SeriesPlotStyle.OHLC:return"ohlc";default:return}}static getPlotlyChartMode(e,t,n){const s=new Set;switch(e){case I.plot.SeriesPlotStyle.SCATTER:(t??!1)&&s.add(se.MODE_LINES),(n??!0)&&s.add(se.MODE_MARKERS);break;case I.plot.SeriesPlotStyle.LINE:(t??!0)&&s.add(se.MODE_LINES),(n??!1)&&s.add(se.MODE_MARKERS);break}return s.size>0?[...s].join("+"):void 0}static getPlotlyProperty(e,t){switch(e){case I.plot.SeriesPlotStyle.PIE:switch(t){case I.plot.SourceType.X:return"labels";case I.plot.SourceType.Y:return"values"}break;case I.plot.SeriesPlotStyle.OHLC:switch(t){case I.plot.SourceType.TIME:return"x"}break;case I.plot.SeriesPlotStyle.TREEMAP:switch(t){case I.plot.SourceType.X:return"ids";case I.plot.SourceType.Y:return"values";case I.plot.SourceType.LABEL:return"labels";case I.plot.SourceType.PARENT:return"parents";case I.plot.SourceType.COLOR:return"marker.colors"}break}switch(t){case I.plot.SourceType.X:return"x";case I.plot.SourceType.Y:return"y";case I.plot.SourceType.Z:return"z";case I.plot.SourceType.X_LOW:return"xLow";case I.plot.SourceType.X_HIGH:return"xHigh";case I.plot.SourceType.Y_LOW:return"yLow";case I.plot.SourceType.Y_HIGH:return"yHigh";case I.plot.SourceType.TIME:return"time";case I.plot.SourceType.OPEN:return"open";case I.plot.SourceType.HIGH:return"high";case I.plot.SourceType.LOW:return"low";case I.plot.SourceType.CLOSE:return"close";case I.plot.SourceType.SHAPE:return"shape";case I.plot.SourceType.SIZE:return"size";case I.plot.SourceType.LABEL:return"label";case I.plot.SourceType.COLOR:return"color";case I.plot.SourceType.PARENT:return"parent";case I.plot.SourceType.HOVER_TEXT:return"hovertext";case I.plot.SourceType.TEXT:return"text";default:throw new Error(`Unrecognized source type: ${t}`)}}static getPlotlySeriesOrientation(e){const{sources:t}=e;return t.length===2&&t[0]?.axis?.type===I.plot.AxisType.Y?se.ORIENTATION.HORIZONTAL:se.ORIENTATION.VERTICAL}static getPlotlyErrorBars(e,t,n){const s=n.map((o,l)=>o-e[l]),i=t.map((o,l)=>e[l]-o);return{type:"data",symmetric:!1,array:s,arrayminus:i}}static getPlotlyDateFormat(e,t,n){const s=n?.replace("%","%%").replace(/S{9}/g,"%9f").replace(/S{8}/g,"%8f").replace(/S{7}/g,"%7f").replace(/S{6}/g,"%6f").replace(/S{5}/g,"%5f").replace(/S{4}/g,"%4f").replace(/S{3}/g,"%3f").replace(/S{2}/g,"%2f").replace(/S{1}/g,"%1f").replace(/y{4}/g,"%Y").replace(/y{2}/g,"%y").replace(/M{4}/g,"%B").replace(/M{3}/g,"%b").replace(/M{2}/g,"%m").replace(/M{1}/g,"%-m").replace(/E{4,}/g,"%A").replace(/E{1,}/g,"%a").replace(/d{2}/g,"%d").replace(/([^%]|^)d{1}/g,"$1%-d").replace(/H{2}/g,"%H").replace(/h{2}/g,"%I").replace(/h{1}/g,"%-I").replace(/m{2}/g,"%M").replace(/s{2}/g,"%S").replace("'T'","T").replace(" z","");let i;const o=e?.getColumnTypeFormatter(t);return o!=null&&Pd(o)&&o.dhTimeZone!=null&&o.showTimeZone&&(i=I.i18n.DateTimeFormat.format(" z",new Date,o.dhTimeZone)),{tickformat:s,ticksuffix:i,automargin:!0}}static convertNumberPrefix(e){return e.replace(/\u00A4\u00A4/g,"USD").replace(/\u00A4/g,"$")}static getPlotlyNumberFormat(e,t,n){if(!n)return null;const i=n.split(";")[0].match(/^([^#,0.]*)([#,]*)([0,]*)(\.?)(0*)(#*)(E?0*)(%?)(.*)/);N(i);const[,o,l,a,,d,h,u,m,g]=i,p=a.replace(",","").length,f=l.indexOf(",")>=0||a.indexOf(",")>=0?",":"",b=u!=null&&u!==""?"e":"f",w=m!==""?m:b,S=d.length+h.length,y=`0${p}${f}.${S}${w}`,E=se.convertNumberPrefix(o),R=se.convertNumberPrefix(g);return{tickformat:y,tickprefix:E,ticksuffix:R,automargin:!0}}static getPlotlyAxisFormat(e,t=null){const{axis:n,columnType:s}=e,{formatPattern:i}=n;let o=null;return F.isDateType(s)?(o=se.getPlotlyDateFormat(t,s,i),o=se.addTickSpacing(o,n,!0)):F.isNumberType(s)&&(o=se.getPlotlyNumberFormat(t,s,i),o=se.addTickSpacing(o,n,!1)),n.formatType===I.plot.AxisFormatType.CATEGORY&&(o?o.type="category":o={type:"category",tickformat:void 0,ticksuffix:void 0}),o}static addTickSpacing(e,t,n){const{gapBetweenMajorTicks:s}=t;if(s>0){const i=e||{};let o=s;return n&&(o=s/aC),t.log&&(o=Math.log(o)),i.tickmode="linear",i.dtick=o,i}return e}static getSourceForAxis(e,t){for(let n=0;n<e.series.length;n+=1){const s=e.series[n];for(let i=0;i<s.sources.length;i+=1){const o=s.sources[i];if(o.axis===t)return o}}return null}static getSeriesVisibility(e,t){return t!=null&&t.hiddenSeries!=null&&t.hiddenSeries.includes(e)?"legendonly":!0}static getHiddenLabels(e){return e?.hiddenSeries?[...e.hiddenSeries]:[]}static makeSeriesData(e,t,n,s,i=se.ORIENTATION.VERTICAL){return{type:e,mode:t,name:n,orientation:i,showlegend:s??void 0}}static makeSeriesDataFromSeries(e,t,n,s=null,i=At){const{name:o,isLinesVisible:l,isShapesVisible:a,plotStyle:d,lineColor:h,shapeColor:u,sources:m,shape:g,shapeSize:p}=e,C=m.some(T=>T.axis?.businessCalendar),f=se.getChartType(d,C),b=se.getPlotlyChartMode(d,l??void 0,a??void 0),w=se.getPlotlySeriesOrientation(e),S=se.makeSeriesData(f,b,o,s,w);return se.addSourcesToSeriesData(S,d,m,t),se.addStylingToSeriesData(S,d,i,h,u,g,p,n),S}static addSourcesToSeriesData(e,t,n,s){const i=e;for(let o=0;o<n.length;o+=1){const l=n[o],{axis:a,type:d}=l,h=se.getPlotlyProperty(t,d);Hc(i,h,[]);const u=a!=null?se.getAxisPropertyName(a.type):null;if(u!=null){const m=s.get(a.type);if(m){const g=m.indexOf(a),p=g>0?`${g+1}`:"";i[`${u}axis`]=`${u}${p}`}}}}static addStylingToSeriesData(e,t,n=At,s=null,i=null,o=null,l=null,a=null){const d=e;if(d.marker={line:{}},d.line={width:1},t===I.plot.SeriesPlotStyle.AREA?d.fill="tozeroy":t===I.plot.SeriesPlotStyle.STACKED_AREA?d.stackgroup="stack":t===I.plot.SeriesPlotStyle.STEP?d.line.shape="hv":t===I.plot.SeriesPlotStyle.HISTOGRAM?(d.width=[],d.marker.line!==void 0&&Object.assign(d.marker.line,{color:n.paper_bgcolor,width:1})):t===I.plot.SeriesPlotStyle.OHLC?(d.increasing={line:{color:n.ohlc_increasing}},d.decreasing={line:{color:n.ohlc_decreasing}}):t===I.plot.SeriesPlotStyle.PIE?(d.textinfo="label+percent",d.outsidetextfont={color:n.title_color}):t===I.plot.SeriesPlotStyle.TREEMAP&&(d.hoverinfo="text",d.textinfo="label+text",d.tiling={packing:"squarify",pad:0},d.textposition="middle center",d.outsidetextfont={color:n.title_color}),s!=null&&(t===I.plot.SeriesPlotStyle.BAR?d.marker.color=s:d.line.color=s),i!=null&&(d.marker.color=i),o!=null&&o.length>0)try{d.marker.symbol=se.getMarkerSymbol(o)}catch(h){ji.warn("Unable to handle shape",o,":",h)}l!=null&&(d.marker.size=l*se.DEFAULT_MARKER_SIZE),a!=null&&t!==I.plot.SeriesPlotStyle.PIE&&(d.visible=a)}static getMarkerSymbol(e){switch(e){case"SQUARE":return"square";case"CIRCLE":return"circle";case"DIAMOND":return"diamond";case"UP_TRIANGLE":return"triangle-up";case"DOWN_TRIANGLE":return"triangle-down";case"RIGHT_TRIANGLE":return"triangle-right";case"LEFT_TRIANGLE":return"triangle-left";case"ELLIPSE":case"HORIZONTAL_RECTANGLE":case"VERTICAL_RECTANGLE":default:throw new Error(`Unrecognized shape ${e}`)}}static getAxisFormats(e,t){const n=new Map,s={tickformat:null,ticksuffix:null},i=se.getAllAxes(e),o=se.groupArray(i,"type"),{charts:l}=e;for(let a=0;a<l.length;a+=1){const d=l[a];for(let h=0;h<d.series.length;h+=1){const u=d.series[h],{sources:m}=u,g=m.filter(p=>p.axis);for(let p=0;p<g.length;p+=1){const C=g[p],{axis:f}=C,{type:b}=f,w=o.get(b);N(w);const S=w.indexOf(f),T=se.getAxisPropertyName(b);if(T!=null){const y=se.getAxisLayoutProperty(T,S);if(n.has(y))ji.debug(`${y} already added.`);else{ji.debug(`Adding ${y} to axisFormats.`);const E=se.getPlotlyAxisFormat(C,t);if(E===null)n.set(y,s);else{n.set(y,E);const{businessCalendar:R}=f;if(R!=null){const x=[],{businessPeriods:D,businessDays:M,holidays:O,timeZone:H}=R,L=t?.getColumnTypeFormatter(_d);let V;Pd(L)&&(V=L.dhTimeZone);const U=V?(H.standardOffset-V.standardOffset)/60:0;O.length>0&&x.push(...se.createRangeBreakValuesFromHolidays(O,H,V)),D.forEach(j=>x.push({pattern:"hour",bounds:[se.periodToDecimal(j.close)+U,se.periodToDecimal(j.open)+U]})),M.length<ts.length&&se.createBoundsFromDays(M).forEach(j=>x.push({pattern:"day of week",bounds:j})),E.rangebreaks=x}if(n.size===d.axes.length)return n}}}}}}return n}static getChartType(e,t){switch(e){case I.plot.SeriesPlotStyle.HISTOGRAM:return"bar";default:return se.getPlotlyChartType(e,t)}}static getAxisPropertyName(e){switch(e){case I.plot.AxisType.X:return"x";case I.plot.AxisType.Y:return"y";default:return null}}static getAxisSide(e){switch(e){case I.plot.AxisPosition.BOTTOM:return"bottom";case I.plot.AxisPosition.TOP:return"top";case I.plot.AxisPosition.LEFT:return"left";case I.plot.AxisPosition.RIGHT:return"right";default:return}}static getAllAxes(e){return e.charts.reduce((t,n)=>[...t,...n.axes],[])}static getChartForSeries(e,t){const{charts:n}=e;for(let s=0;s<n.length;s+=1){const i=n[s];for(let o=0;o<i.series.length;o+=1)if(t===i.series[o])return i}return null}static getLayoutRanges(e){const t={},n=Object.keys(e).filter(s=>s.indexOf("axis")>=0);for(let s=0;s<n.length;s+=1){const i=n[s],o=e[i];cC(o)&&(t[i]=[...o.range])}return t}static updateFigureAxes(e,t,n,s=0,i=0,o=At){const l=e,a=se.getAllAxes(t);for(let d=0;d<t.charts.length;d+=1){const h=t.charts[d],u=n?.(h),m=se.getChartBounds(t,h,s,i);se.updateLayoutAxes(l,h.axes,a,s,i,m,u,o)}se.removeStaleAxes(l,a)}static getChartBounds(e,t,n,s){const{cols:i,rows:o}=e,{column:l,colspan:a,row:d,rowspan:h}=t,u=l+a,m=d+h,g=1/i,p=1/o,C=se.AXIS_SIZE_PX/n,f=se.AXIS_SIZE_PX/s,b={bottom:(o-m)*p+(m<o?f/2:0),top:(o-d)*p-(d>0?f/2:0),left:l*g+(l>0?C/2:0),right:u*g-(u<i?C/2:0)};return(se.groupArray(t.axes,"position").get(I.plot.AxisPosition.RIGHT)??[]).length>0&&(n>0?b.right-=(b.right-b.left)*Math.max(0,Math.min(se.LEGEND_WIDTH_PX/n,se.MAX_LEGEND_SIZE)):b.right-=(b.right-b.left)*se.DEFAULT_AXIS_SIZE),b}static updateLayoutAxes(e,t,n,s=0,i=0,o={left:0,top:0,right:1,bottom:1},l,a=At){const d=s>0?Math.max(se.MIN_AXIS_SIZE,Math.min(se.AXIS_SIZE_PX/i,se.MAX_AXIS_SIZE)):se.DEFAULT_AXIS_SIZE,h=i>0?Math.max(se.MIN_AXIS_SIZE,Math.min(se.AXIS_SIZE_PX/s,se.MAX_AXIS_SIZE)):se.DEFAULT_AXIS_SIZE,u=e,m=se.groupArray(t,"position"),g=se.groupArray(t,"type"),p=[...g.keys()],C=se.groupArray(n,"type");for(let f=0;f<p.length;f+=1){const b=p[f],w=se.getAxisPropertyName(b);if(w!=null){const S=g.get(b),T=C.get(b),E=b===I.plot.AxisType.Y?i:s;N(S),N(T);for(let R=0;R<S.length;R+=1){const x=S[R],D=T.indexOf(x),M=se.getAxisLayoutProperty(w,D);u[M]==null&&(u[M]=se.makeLayoutAxis(b,a));const O=u[M];if(O!=null){se.updateLayoutAxis(O,x,R,m,d,h,o);const{range:H,autorange:L}=O;if(l!=null&&H!==void 0&&(L===void 0||L===!1)){const V=l(x),[U,j]=V(H);ji.debug("Setting downsample range",E,U,j),x.range(E,U,j)}else x.range(E)}}}}}static removeStaleAxes(e,t){const n=e,s=se.groupArray(t,"type"),i=[...s.keys()];for(let o=0;o<i.length;o+=1){const l=i[o],a=s.get(l);N(a);let d=a.length;const h=se.getAxisPropertyName(l);if(h!=null){let u=se.getAxisLayoutProperty(h,d);for(;n[u]!=null;)delete n[u],d+=1,u=se.getAxisLayoutProperty(h,d)}}}static getAxisLayoutProperty(e,t){const n=t>0?`${t+1}`:"";return`${e??""}axis${n}`}static updateLayoutAxis(e,t,n,s,i,o,l){const d=t.type===I.plot.AxisType.Y?o:i,h=e,u=t.label??"";if(h.title!==void 0&&typeof h.title!="string"?h.title.text=u:h.title={text:u},t.log&&(h.type="log"),h.side=se.getAxisSide(t.position),n>0){h.overlaying=se.getAxisPropertyName(t.type)??void 0;const m=s.get(t.position)??[],g=m.indexOf(t);g>0&&(h.anchor="free",t.position===I.plot.AxisPosition.RIGHT?h.position=l.right+(g-m.length+1)*d:t.position===I.plot.AxisPosition.TOP?h.position=l.top+(g-m.length+1)*d:t.position===I.plot.AxisPosition.BOTTOM?h.position=l.bottom+(m.length-g+1)*d:t.position===I.plot.AxisPosition.LEFT&&(h.position=l.left+(m.length-g+1)*d))}else if(t.type===I.plot.AxisType.X){const m=s.get(I.plot.AxisPosition.LEFT)||[],g=s.get(I.plot.AxisPosition.RIGHT)||[],p=Math.max(l.left,l.left+(m.length-1)*o),C=Math.min(l.right-(g.length-1)*o,l.right);h.domain=[p,C]}else if(t.type===I.plot.AxisType.Y){const m=s.get(I.plot.AxisPosition.BOTTOM)||[],g=s.get(I.plot.AxisPosition.TOP)||[],p=Math.max(l.bottom,l.bottom+(m.length-1)*i),C=Math.min(l.top-(g.length-1)*i,l.top);h.domain=[p,C]}}static periodToDecimal(e){const t=e.split(":");return Number(t[0])+Number(t[1])/60}static createBoundsFromDays(e){const t=e.map(o=>ts.indexOf(o)),n=ts.filter(o=>!e.includes(o)).map(o=>ts.indexOf(o)),s=new Set;n.forEach(o=>{for(let l=o+1;l<o+ts.length;l+=1){const a=l%ts.length;if(t.includes(a)){s.add(a);break}}});const i=[];return s.forEach(o=>{for(let l=o-1;l>o-ts.length;l-=1){const a=l<0?l+ts.length:l;if(t.includes(a)){const d=(a+1)%7;i.push([d,o]);break}}}),i}static createRangeBreakValuesFromHolidays(e,t,n){const s=[],i=[];return e.forEach(o=>{o.businessPeriods.length>0?i.push(...se.createPartialHoliday(o,t,n)):s.push(se.createFullHoliday(o,t,n))}),[{values:s},...i]}static createFullHoliday(e,t,n){return se.adjustDateForTimeZone(`${e.date.toString()} 00:00:00.000000`,t,n)}static createPartialHoliday(e,t,n){const s=e.date.toString(),i=["00:00"];e.businessPeriods.forEach(l=>{i.push(l.open),i.push(l.close)}),i.push("24:00");const o=[];for(let l=0;l<i.length;l+=2){const a=i[l],d=i[l+1];if(a!==d){const h=[se.adjustDateForTimeZone(`${s} ${a}:00.000000`,t,n)],u=lC*(se.periodToDecimal(d)-se.periodToDecimal(a));o.push({values:h,dvalue:u})}}return o}static adjustDateForTimeZone(e,t,n){return n&&n.standardOffset!==t.standardOffset?se.unwrapValue(se.wrapValue(e,_d,t),n):e}static groupArray(e,t){return e.reduce((n,s)=>{const i=s[t],o=n.get(i)??[];return o.push(s),n.set(i,o),n},new Map)}static unwrapValue(e,t){if(e!=null){if(rC(e))return I.i18n.DateTimeFormat.format(se.DATE_FORMAT,e,t);if(dC(e))return e.asNumber()}return e}static wrapValue(e,t,n=null){if(F.isDateType(t)&&typeof e=="string"){const s=e,i=se.DATE_FORMAT.substr(0,e.length),o=I.i18n.DateTimeFormat.parse(i,s);if(!n)return o;const l=`${i} Z`,a=I.i18n.DateTimeFormat.format("Z",o,n),d=I.i18n.DateTimeFormat.parse(l,`${s} ${a}`),h=I.i18n.DateTimeFormat.format("Z",d,n);return I.i18n.DateTimeFormat.parse(l,`${s} ${h}`)}return e}static makeLayoutAxis(e,t=At){const n={automargin:!0,gridcolor:t.gridcolor,linecolor:t.linecolor,rangeslider:{visible:!1},showline:!0,ticklen:5,tickcolor:t.paper_bgcolor,tickfont:{color:t.zerolinecolor},title:{font:{color:t.title_color}}};return e===I.plot.AxisType.X?Object.assign(n,{showgrid:!0}):e===I.plot.AxisType.Y&&Object.assign(n,{zerolinecolor:t.zerolinecolor,zerolinewidth:2}),n}static getColorwayFromTheme(e=At){let t=[];return e.colorway&&(Array.isArray(e.colorway)?t=e.colorway:typeof e.colorway=="string"?t=e.colorway.split(" "):ji.warn(`Unable to handle colorway property: ${e.colorway}`)),t}static makeDefaultLayout(e=At){const t={...e,autosize:!0,colorway:se.getColorwayFromTheme(e),font:{family:"'Fira Sans', sans-serif"},title:{font:{color:e.title_color},yanchor:"top",pad:{...se.DEFAULT_TITLE_PADDING},y:1},legend:{font:{color:e.title_color}},margin:{...se.DEFAULT_MARGIN},xaxis:se.makeLayoutAxis(I.plot.AxisType.X,e),yaxis:se.makeLayoutAxis(I.plot.AxisType.Y,e)};return t.datarevision=0,t}static hydrateSettings(e){return{...e,type:e.type!=null?I.plot.SeriesPlotStyle[e.type]:void 0}}static titleFromSettings(e){const{series:t,xAxis:n,title:s=`${(t??[]).join(", ")} by ${n}`}=e;return s}static makeFigureSettings(e,t){const{series:n,xAxis:s,type:i}=e,o=se.titleFromSettings(e),l={formatType:`${I.plot.AxisFormatType.NUMBER}`,type:`${I.plot.AxisType.X}`,position:`${I.plot.AxisPosition.BOTTOM}`},a={formatType:`${I.plot.AxisFormatType.NUMBER}`,type:`${I.plot.AxisType.Y}`,position:`${I.plot.AxisPosition.LEFT}`};return{charts:[{chartType:`${I.plot.ChartType.XY}`,axes:[l,a],series:(n??[]).map(d=>({plotStyle:`${i}`,name:d,dataSources:[{type:`${I.plot.SourceType.X}`,columnName:s??"",axis:l,table:t},{type:`${I.plot.SourceType.Y}`,columnName:d,axis:a,table:t}]}))}],title:o}}}const Qe=se;const ns=ne.module("Chart");class gi extends v.Component{static defaultProps={isActive:!0,settings:{timeZone:"America/New_York",defaultDateTimeFormat:Xs.FULL_DATE_FORMAT,showTimeZone:!1,showTSeparator:!0,formatter:[]},onDisconnect:()=>{},onReconnect:()=>{},onUpdate:()=>{},onError:()=>{},onSettingsChanged:()=>{}};static convertIcon(e){const[t,,,,n]=e.icon,s=`${n}`;return{width:t,path:s,ascent:t,descent:0,transform:"matrix(1, 0, 0, 1, 0, 0)"}}static downsampleButtonTitle(e,t){return e?"Downsampling in progress...":t?"Downsampling disabled, click to enable":"Downsampling enabled, click to disable"}static downsampleButtonAttr(e,t){return e?"animation-spin":t?void 0:"fill-active"}constructor(e){super(e),this.handleAfterPlot=this.handleAfterPlot.bind(this),this.handleDownsampleClick=this.handleDownsampleClick.bind(this),this.handleModelEvent=this.handleModelEvent.bind(this),this.handlePlotUpdate=this.handlePlotUpdate.bind(this),this.handleRelayout=this.handleRelayout.bind(this),this.handleRestyle=this.handleRestyle.bind(this),this.plot=de.createRef(),this.plotWrapper=de.createRef(),this.columnFormats=[],this.dateTimeFormatterOptions={},this.decimalFormatOptions={},this.integerFormatOptions={},this.isSubscribed=!1,this.isLoadedFired=!1,this.currentSeries=0,this.state={data:null,downsamplingError:null,isDownsampleFinished:!1,isDownsampleInProgress:!1,isDownsamplingDisabled:!1,layout:{datarevision:0},revision:0}}componentDidMount(){this.updateDimensions(),this.updateModelDimensions(),this.initData(),this.initFormatter();const{isActive:e}=this.props;e&&this.subscribe()}componentDidUpdate(e){const{isActive:t,settings:n}=this.props;this.updateFormatterSettings(n),t!==e.isActive&&(t?this.subscribe():this.unsubscribe())}componentWillUnmount(){this.unsubscribe()}currentSeries;plot;plotWrapper;columnFormats;dateTimeFormatterOptions;decimalFormatOptions;integerFormatOptions;rect;ranges;isSubscribed;isLoadedFired;getCachedConfig=ge((e,t,n,s)=>{const i=[],o=Boolean(e);if(o&&i.push({name:`Downsampling failed: ${e}`,click:()=>{},icon:gi.convertIcon(eh),attr:"fill-warning"}),t||n||s||o){const l=gi.downsampleButtonTitle(n,s),a=gi.downsampleButtonAttr(n,s),d=n?cg:hg;i.push({name:l,icon:gi.convertIcon(d),click:this.handleDownsampleClick,attr:a})}return{displaylogo:!1,displayModeBar:n||o?!0:"hover",modeBarButtons:[i,["toImage"],["zoom2d","pan2d"],["zoomIn2d","zoomOut2d","autoScale2d","resetScale2d"]]}});getPlotRect(){return this.plotWrapper.current?.getBoundingClientRect()??null}initData(){const{model:e}=this.props,{layout:t}=this.state;this.setState({data:e.getData(),layout:{...t,...e.getLayout()}})}subscribe(){if(this.isSubscribed)return;const{model:e}=this.props;if(!this.rect||this.rect.width===0||this.rect.height===0){ns.debug2("Delaying subscription until model dimensions are set");return}e.subscribe(this.handleModelEvent),this.isSubscribed=!0}unsubscribe(){if(!this.isSubscribed)return;const{model:e}=this.props;e.unsubscribe(this.handleModelEvent),this.isSubscribed=!1}handleAfterPlot(){this.plot.current!=null}handleDownsampleClick(){this.setState(({isDownsamplingDisabled:e})=>({downsamplingError:null,isDownsampleInProgress:!1,isDownsampleFinished:!1,isDownsamplingDisabled:!e}),()=>{const{model:e}=this.props,{isDownsamplingDisabled:t}=this.state;e.setDownsamplingDisabled(t)})}handleModelEvent(e){const{type:t,detail:n}=e;switch(ns.debug2("Received data update",t,n),t){case _n.EVENT_UPDATED:{this.currentSeries+=1,this.setState(i=>{const{layout:o,revision:l}=i;return typeof o.datarevision=="number"&&(o.datarevision+=1),{data:n,layout:o,revision:l+1}});const{onUpdate:s}=this.props;s({isLoading:!this.isLoadedFired});break}case _n.EVENT_LOADFINISHED:{const{onUpdate:s}=this.props;this.isLoadedFired=!0,s({isLoading:!1});break}case _n.EVENT_DISCONNECT:{const{onDisconnect:s}=this.props;s();break}case _n.EVENT_RECONNECT:{const{onReconnect:s}=this.props;s();break}case _n.EVENT_DOWNSAMPLESTARTED:{this.setState({isDownsampleFinished:!1,isDownsampleInProgress:!0,downsamplingError:null});break}case _n.EVENT_DOWNSAMPLEFINISHED:{this.setState({isDownsampleFinished:!0,isDownsampleInProgress:!1,downsamplingError:null});break}case _n.EVENT_DOWNSAMPLENEEDED:case _n.EVENT_DOWNSAMPLEFAILED:{const s=n.message??n;this.setState({isDownsampleFinished:!1,isDownsampleInProgress:!1,isDownsamplingDisabled:!1,downsamplingError:s});const{onError:i}=this.props;i(new Error(s));break}default:ns.debug("Unknown event type",t,e)}}handlePlotUpdate(e){const{layout:t}=e,n=Qe.getLayoutRanges(t);!st(n,this.ranges)&&(this.ranges=n,this.updateModelDimensions(!0))}handleRelayout(e){if(ns.debug("handleRelayout",e),e.hiddenlabels!=null){const{onSettingsChanged:t}=this.props,n=[...e.hiddenlabels];t({hiddenSeries:n})}this.updateModelDimensions()}handleRestyle([e,t]){if(ns.debug("handleRestyle",e,t),Object.keys(e).includes("visible")){const{data:n}=this.state,{onSettingsChanged:s}=this.props;if(n!=null){const i=n.reduce((o,{name:l,visible:a})=>l!=null&&a==="legendonly"?[...o,l]:o,[]);s({hiddenSeries:i})}}}updateModelDimensions(e=!1){const t=this.getPlotRect();if(!t){ns.warn("Unable to get plotting rect");return}if(!this.rect||this.rect.width!==t.width||this.rect.height!==t.height||e){this.rect=t;const{isActive:s,model:i}=this.props;i.setDimensions(t),s&&this.subscribe()}}initFormatter(){const{settings:e}=this.props;this.updateFormatterSettings(e)}updateFormatterSettings(e){const t=$n.getColumnFormats(e),n=$n.getDateTimeFormatterOptions(e),{decimalFormatOptions:s={},integerFormatOptions:i={}}=e;(!st(this.columnFormats,t)||!st(this.dateTimeFormatterOptions,n)||!st(this.decimalFormatOptions,s)||!st(this.integerFormatOptions,i))&&(this.columnFormats=$n.getColumnFormats(e),this.dateTimeFormatterOptions=n,this.decimalFormatOptions=s,this.integerFormatOptions=i,this.updateFormatter())}updateFormatter(){const e=new gn(this.columnFormats,this.dateTimeFormatterOptions,this.decimalFormatOptions,this.integerFormatOptions),{model:t}=this.props;t.setFormatter(e)}updateDimensions(){const e=this.getPlotRect();this.plot.current!=null&&e!=null&&e.width>0&&e.height>0&&hl.relayout(this.plot.current.el,{autosize:!0}).catch(t=>{ns.debug("Unable to resize, promise rejected",t)})}render(){const{data:e,downsamplingError:t,isDownsampleFinished:n,isDownsampleInProgress:s,isDownsamplingDisabled:i,layout:o,revision:l}=this.state,a=this.getCachedConfig(t,n,s,i),d=e!=null;return r.jsx("div",{className:"h-100 w-100 chart-wrapper",ref:this.plotWrapper,children:d&&r.jsx(bh,{ref:this.plot,data:e,layout:o,revision:l,config:a,onAfterPlot:this.handleAfterPlot,onError:ns.error,onRelayout:this.handleRelayout,onUpdate:this.handlePlotUpdate,onRestyle:this.handleRestyle,useResizeHandler:!0,style:{height:"100%",width:"100%"}})})}}const hC=gi,Dt=ne.module("FigureChartModel");class wr extends _n{static ADD_SERIES_DEBOUNCE=50;constructor(e,t={},n=At){super(),this.handleFigureUpdated=this.handleFigureUpdated.bind(this),this.handleFigureDisconnected=this.handleFigureDisconnected.bind(this),this.handleFigureReconnected=this.handleFigureReconnected.bind(this),this.handleFigureSeriesAdded=this.handleFigureSeriesAdded.bind(this),this.handleDownsampleStart=this.handleDownsampleStart.bind(this),this.handleDownsampleFinish=this.handleDownsampleFinish.bind(this),this.handleDownsampleFail=this.handleDownsampleFail.bind(this),this.handleDownsampleNeeded=this.handleDownsampleNeeded.bind(this),this.handleRequestFailed=this.handleRequestFailed.bind(this),this.figure=e,this.settings=t,this.theme=n,this.data=[];const s={data:{},layout:Qe.makeDefaultLayout(n)};this.layout={grid:{rows:e.rows,columns:e.cols,pattern:"independent"},template:s},this.seriesDataMap=new Map,this.pendingSeries=[],this.oneClicks=[],this.filterColumnMap=new Map,this.lastFilter=new Map,this.isConnected=!0,this.seriesToProcess=new Set,this.setTitle(this.getDefaultTitle()),this.initAllSeries(),this.updateAxisPositions(),this.startListeningFigure()}figure;settings;theme;data;layout;seriesDataMap;pendingSeries;oneClicks;filterColumnMap;lastFilter;isConnected;seriesToProcess;close(){this.figure.close(),this.addPendingSeries.cancel(),this.stopListeningFigure()}getDefaultTitle(){return this.figure.charts.length>0?this.figure.charts[0].title:""}initAllSeries(){this.oneClicks=[],this.filterColumnMap.clear();const{charts:e}=this.figure,t=Qe.getAllAxes(this.figure),n=[];for(let o=0;o<e.length;o+=1){const l=e[o];for(let a=0;a<l.series.length;a+=1){const d=l.series[a];n.push(d.name),this.addSeries(d,t,l.showLegend)}}const i=[...this.seriesDataMap.keys()].filter(o=>n.indexOf(o)<0);for(let o=0;o<i.length;o+=1){const l=i[o];this.seriesDataMap.delete(l)}this.seriesToProcess=new Set([...this.seriesDataMap.keys()])}addSeries(e,t,n){const s=Qe.groupArray(t,"type"),i=Qe.makeSeriesDataFromSeries(e,s,Qe.getSeriesVisibility(e.name,this.settings),n,this.theme);if(this.seriesDataMap.set(e.name,i),this.data=[...this.seriesDataMap.values()],e.plotStyle===I.plot.SeriesPlotStyle.STACKED_BAR?this.layout.barmode="stack":e.plotStyle===I.plot.SeriesPlotStyle.PIE&&(this.layout.hiddenlabels=Qe.getHiddenLabels(this.settings)),this.layout.showlegend=this.data.length>1||e.plotStyle===I.plot.SeriesPlotStyle.PIE?n??void 0:!1,e.oneClick!=null){const{oneClick:o}=e,{columns:l}=o;for(let a=0;a<l.length;a+=1)this.filterColumnMap.set(l[a].name,l[a]);this.oneClicks.push(o)}this.updateLayoutFormats()}addPendingSeries=Ye(()=>{const e=Qe.getAllAxes(this.figure),{pendingSeries:t}=this;for(let n=0;n<t.length;n+=1){const s=t[n],i=this.figure.charts.find(o=>o.series.includes(s));this.addSeries(s,e,i?.showLegend??null),s.subscribe()}this.pendingSeries=[]},wr.ADD_SERIES_DEBOUNCE);subscribe(e){super.subscribe(e),this.listeners.length===1&&(this.initAllSeries(),this.subscribeFigure())}unsubscribe(e){super.unsubscribe(e),this.listeners.length===0&&this.unsubscribeFigure()}subscribeFigure(){if(!this.isConnected){Dt.debug("Ignoring subscribe when figure in disconnected state");return}this.figure.subscribe(this.isDownsamplingDisabled?I.plot.DownsampleOptions.DISABLE:I.plot.DownsampleOptions.DEFAULT)}unsubscribeFigure(){this.figure.unsubscribe()}startListeningFigure(){this.figure.addEventListener(I.plot.Figure.EVENT_UPDATED,this.handleFigureUpdated),this.figure.addEventListener(I.plot.Figure.EVENT_SERIES_ADDED,this.handleFigureSeriesAdded),this.figure.addEventListener(I.plot.Figure.EVENT_DISCONNECT,this.handleFigureDisconnected),this.figure.addEventListener(I.plot.Figure.EVENT_RECONNECT,this.handleFigureReconnected),this.figure.addEventListener(I.plot.Figure.EVENT_DOWNSAMPLESTARTED,this.handleDownsampleStart),this.figure.addEventListener(I.plot.Figure.EVENT_DOWNSAMPLEFINISHED,this.handleDownsampleFinish),this.figure.addEventListener(I.plot.Figure.EVENT_DOWNSAMPLEFAILED,this.handleDownsampleFail),this.figure.addEventListener(I.plot.Figure.EVENT_DOWNSAMPLENEEDED,this.handleDownsampleNeeded),this.figure.addEventListener(I.Client.EVENT_REQUEST_FAILED,this.handleRequestFailed)}stopListeningFigure(){this.figure.removeEventListener(I.plot.Figure.EVENT_UPDATED,this.handleFigureUpdated),this.figure.removeEventListener(I.plot.Figure.EVENT_SERIES_ADDED,this.handleFigureSeriesAdded),this.figure.removeEventListener(I.plot.Figure.EVENT_DISCONNECT,this.handleFigureDisconnected),this.figure.removeEventListener(I.plot.Figure.EVENT_RECONNECT,this.handleFigureReconnected),this.figure.removeEventListener(I.plot.Figure.EVENT_DOWNSAMPLESTARTED,this.handleDownsampleStart),this.figure.removeEventListener(I.plot.Figure.EVENT_DOWNSAMPLEFINISHED,this.handleDownsampleFinish),this.figure.removeEventListener(I.plot.Figure.EVENT_DOWNSAMPLEFAILED,this.handleDownsampleFail),this.figure.removeEventListener(I.plot.Figure.EVENT_DOWNSAMPLENEEDED,this.handleDownsampleNeeded),this.figure.removeEventListener(I.Client.EVENT_REQUEST_FAILED,this.handleRequestFailed)}getTimeZone=Re((e,t)=>{if(t!=null){const n=t.getColumnTypeFormatter(e);if(n!=null)return n.dhTimeZone}});getValueTranslator=Re((e,t)=>{const n=this.getTimeZone(e,t);return s=>Qe.unwrapValue(s,n)});getValueParser=Re((e,t)=>{const n=this.getTimeZone(e,t);return s=>Qe.wrapValue(s,e,n)});getRangeParser=Re((e,t)=>n=>{let[s,i]=n;const o=this.getValueParser(e,t);return s=o(s),i=o(i),[s,i]});getAxisRangeParser=Re((e,t)=>n=>{const s=Qe.getSourceForAxis(e,n);return s?this.getRangeParser(s.columnType,t):i=>i});handleDownsampleStart(e){Dt.debug("Downsample started",e),this.fireDownsampleStart(e.detail)}handleDownsampleFinish(e){Dt.debug("Downsample finished",e),this.fireDownsampleFinish(e.detail)}handleDownsampleFail(e){Dt.error("Downsample failed",e),this.fireDownsampleFail(e.detail)}handleDownsampleNeeded(e){Dt.info("Downsample needed",e),this.fireDownsampleNeeded(e.detail)}handleFigureUpdated(e){const{detail:t}=e,{series:n}=t;Dt.debug2("handleFigureUpdated",n);for(let i=0;i<n.length;i+=1){const o=n[i];Dt.debug2("handleFigureUpdated updating series",o.name);const{sources:l}=o;for(let a=0;a<l.length;a+=1){const d=l[a],{columnType:h,type:u}=d,m=this.getValueTranslator(h,this.formatter),g=t.getArray(o,u,m);this.setDataArrayForSeries(o,u,g)}this.seriesToProcess.delete(o.name),this.seriesToProcess.size===0&&this.fireLoadFinished(),this.cleanSeries(o)}const{data:s}=this;this.fireUpdate(s)}handleRequestFailed(e){Dt.error("Request failed",e)}resubscribe(){this.listeners.length>0&&(this.unsubscribeFigure(),this.subscribeFigure())}setFormatter(e){super.setFormatter(e),this.updateLayoutFormats(),this.resubscribe()}setDownsamplingDisabled(e){super.setDownsamplingDisabled(e),this.resubscribe()}handleFigureDisconnected(e){Dt.debug("Figure disconnected",e),this.isConnected=!1,this.listeners.length>0&&this.unsubscribeFigure(),this.fireDisconnect()}handleFigureReconnected(e){Dt.debug("Figure reconnected",e),this.isConnected=!0,this.initAllSeries(),this.fireReconnect(),this.listeners.length>0&&this.subscribeFigure()}handleFigureSeriesAdded(e){const{detail:t}=e;Dt.debug("handleFigureSeriesAdded",t),this.pendingSeries.push(t),this.addPendingSeries()}setDimensions(e){super.setDimensions(e),this.updateAxisPositions()}setTitle(e){super.setTitle(e);const t=(e??"").match(/<br>/g)?.length??0,n=Qe.DEFAULT_MARGIN.t+t*Qe.SUBTITLE_LINE_HEIGHT;this.layout.margin?this.layout.margin.t=n:this.layout.margin={t:n},typeof this.layout.title=="string"?this.layout.title=e:(this.layout.title={...this.layout.title},this.layout.title.text=e,this.layout.title.pad={...this.layout.title.pad},this.layout.title.pad.t=Qe.DEFAULT_TITLE_PADDING.t+t*Qe.SUBTITLE_LINE_HEIGHT*.5)}getPlotWidth(){return!this.rect||!this.rect.width?0:Math.max(this.rect.width-(this.layout.margin?.l??0)-(this.layout.margin?.r??0),0)}getPlotHeight(){return!this.rect||!this.rect.height?0:Math.max(this.rect.height-(this.layout.margin?.t??0)-(this.layout.margin?.b??0),0)}updateAxisPositions(){const e=this.getPlotWidth(),t=this.getPlotHeight();Qe.updateFigureAxes(this.layout,this.figure,n=>this.getAxisRangeParser(n,this.formatter),e,t,this.theme)}updateLayoutFormats(){if(!this.formatter)return;Qe.getAxisFormats(this.figure,this.formatter).forEach((t,n)=>{Dt.debug(`Assigning ${n}`,this.layout[n],t);const s=this.layout[n];s!=null?Object.assign(s,t):Dt.debug(`Ignoring null layout.${n}`)})}setDataArrayForSeries(e,t,n){const{name:s,plotStyle:i}=e,o=this.seriesDataMap.get(s),l=Qe.getPlotlyProperty(i,t);o&&Hc(o,l,n)}cleanSeries(e){const{name:t,plotStyle:n}=e,s=this.seriesDataMap.get(t);if(s!=null){if(n===I.plot.SeriesPlotStyle.HISTOGRAM){const{xLow:i,xHigh:o}=s;if(i&&o&&i.length===o.length){const l=[];for(let a=0;a<i.length;a+=1)l.push(o[a]-i[a]);s.width=l}}else if(n===I.plot.SeriesPlotStyle.LINE){const{x:i,xLow:o,xHigh:l,y:a,yLow:d,yHigh:h}=s;o&&l&&o!==i&&(s.error_x=Qe.getPlotlyErrorBars(i,o,l)),d&&h&&d!==a&&(s.error_y=Qe.getPlotlyErrorBars(a,d,h))}else if(n===I.plot.SeriesPlotStyle.TREEMAP){const{ids:i,labels:o}=s;i!==void 0&&o===void 0&&(s.labels=i)}}}getData(){return this.data}getLayout(){return this.layout}getFilterColumnMap(){return new Map(this.filterColumnMap)}isFilterRequired(){return this.oneClicks.find(e=>e.requireAllFiltersToDisplay)!=null}setFilter(e){if(this.oneClicks.length===0){Dt.warn("Trying to set a filter, but no one click!");return}Dt.debug("setFilter",e);for(let t=0;t<this.oneClicks.length;t+=1){const n=this.oneClicks[t],{columns:s}=n;new Set([...e.keys(),...this.lastFilter.keys()]).forEach(o=>{const l=e.get(o);this.lastFilter.get(o)!==l&&s.find(a=>a.name===o)!=null&&n.setValueForColumn(o,l)})}this.lastFilter=new Map(e)}setFigure(e){this.close(),this.figure=e,this.setTitle(this.getDefaultTitle()),this.initAllSeries(),this.updateAxisPositions(),this.startListeningFigure(),this.listeners.length>0&&this.subscribeFigure()}updateSettings(e){this.settings=e}}const jd=wr;class vr{static async makeModelFromSettings(e,t,n=At){const s=await vr.makeFigureFromSettings(e,t);return new jd(s,e,n)}static async makeFigureFromSettings(e,t){const n=await t.copy();return n.applyCustomColumns(t.customColumns),n.applyFilter(t.filter),n.applySort(t.sort),I.plot.Figure.create(Qe.makeFigureSettings(e,n))}static async makeModel(e,t,n=At){return new jd(t,e,n)}}const fl=vr;function Hd(c){return c.setFigure!==void 0}const uC=ne.module("HeapUsage");function mC({connection:c,defaultUpdateInterval:e,hoverUpdateInterval:t,bgMonitoring:n=!0,monitorDuration:s}){const[i,o]=v.useState({freeMemory:0,maximumHeapSize:999,totalHeapSize:0}),[l,a]=v.useState(!1),d=v.useRef({timestamps:[],usages:[]});v.useEffect(function(){const O=async()=>{try{const L=await c.getWorkerHeapInfo();if(o(L),n||l){const V=(L.totalHeapSize-L.freeMemory)/L.maximumHeapSize,U=Date.now(),{timestamps:j,usages:P}=d.current;for(;j.length!==0&&U-j[0]>s*1.5;)j.shift(),P.shift();j.push(U),P.push(V)}else d.current={timestamps:[],usages:[]}}catch(L){uC.warn("Unable to get heap usage",L)}};O();const H=setInterval(O,l?t:e);return()=>{clearInterval(H)}},[l,t,c,e,s,n]);const h=(M,O)=>Math.round(M*10**O)/10**O,u=2,m=1024**3,{freeMemory:g,totalHeapSize:p,maximumHeapSize:C}=i,f=h(g/m,u),b=h(p/m,u),w=h(C/m,u),S=b-f,T=(M,O,H=!1)=>r.jsxs("div",{className:Y("heap-usage-info-row",{"heading-bottom-border":H}),children:[r.jsx("div",{className:"font-weight-bold",children:M}),r.jsx("div",{children:O})]}),{timestamps:y,usages:E}=d.current,R=y[y.length-1]??0,x=p/C,D=(p-g)/C;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"max-memory",children:[r.jsx("div",{className:"total-memory",style:{width:`calc(${x*100}% - ${x*2}px`}}),r.jsx("div",{className:Y("used-memory",{"heap-overflow":(p-g)/C>.95}),style:{width:`calc(${D*100}% - ${D*2}px`}}),r.jsxs("div",{className:"memory-text",children:[w.toFixed(1)," GB"]})]}),r.jsx(ot,{onEntered:()=>a(!0),onExited:()=>a(!1),interactive:!0,children:r.jsxs("div",{className:"heap-tooltip",children:[T("In use:",`${S.toFixed(u)} of ${w.toFixed(u)} GB`,!0),T("Free:",`${f.toFixed(u)} GB`),T("Total:",`${b.toFixed(u)} GB`),T("Max:",`${w.toFixed(u)} GB`),r.jsx("div",{className:"heap-plot",children:r.jsx(bh,{data:[{x:[...y],y:[...E],type:"scatter",mode:"lines"}],config:{staticPlot:!0,responsive:!0},style:{width:"196px",height:"100px"},layout:{legend:!1,margin:{l:2,t:2,r:2,b:2},plot_bgcolor:"transparent",paper_bgcolor:"transparent",colorway:["#4878ea"],xaxis:{dtick:Math.round(s/6),gridcolor:At.linecolor,range:[R-s,R],linecolor:At.linecolor,linewidth:2,mirror:!0},yaxis:{dtick:.2,gridcolor:At.linecolor,range:[0,1],linecolor:At.linecolor,linewidth:2,mirror:!0}}})}),r.jsxs("div",{className:"heap-utilisation-text",children:["% utilization over ",Math.round(s/1e3/60)," min."]})]})})]})}const Tr=Object.freeze({}),gC=new Map,Sh=c=>c.user,Er=c=>c.storage,wh=c=>Er(c).commandHistoryStorage,vh=c=>Er(c).fileStorage,pC=c=>Er(c).workspaceStorage,ql=c=>c.workspace,wt=c=>ql(c).data.settings,Th=c=>wt(c).defaultDateTimeFormat,Eh=c=>wt(c).defaultDecimalFormatOptions??Tr,yh=c=>wt(c).defaultIntegerFormatOptions??Tr,Rh=c=>wt(c).formatter,po=c=>wt(c).timeZone,xh=c=>wt(c).showTimeZone,Dh=c=>wt(c).showTSeparator,Ih=c=>wt(c).truncateNumbersWithPound,fC=c=>wt(c).shortcutOverrides,CC=c=>wt(c).defaultNotebookSettings??Tr,Xl=c=>c.activeTool,bC=c=>c.plugins??gC,Fh="SET_ACTIVE_TOOL",Nh="SET_COMMAND_HISTORY_STORAGE",kh="SET_FILE_STORAGE",Mh="SET_PLUGINS",Lh="SET_USER",Oh="SET_WORKSPACE",Ah="SET_WORKSPACE_STORAGE",_h="SET_SERVER_CONFIG_VALUES",SC=c=>({type:Lh,payload:c}),Ph=c=>({type:Oh,payload:c}),wC=c=>({type:Ah,payload:c}),vC=c=>({type:Nh,payload:c}),TC=c=>({type:kh,payload:c}),EC=c=>(e,t)=>{e(Ph(c));const{storage:n}=t(),{workspaceStorage:s}=n;return s.save(c)},jh=c=>(e,t)=>{const{workspace:n}=t(),{data:s}=n,i={...n,data:{...s,...c}};return e(EC(i))},Zl=c=>e=>e(jh({settings:c})),Ql=c=>({type:Fh,payload:c}),yC=c=>({type:Mh,payload:c}),RC=c=>({type:_h,payload:c});function Hh(c,e){return(t=e,n)=>{switch(n.type){case c:{const s=n.payload;return s==null?null:t!=null?{...t,...s}:{...s}}default:return t}}}function xC(c,e={},t=!0){return(n=e,s)=>{switch(s.type){case c:{const{id:i,payload:o}=s;return t&&st({payload:o},{payload:n[i]})?n:{...n,[i]:o}}default:return n}}}function Js(c,e){return(t=e,n)=>{switch(n.type){case c:return n.payload;default:return t}}}const DC=Js(Fh,null),IC=Js(Mh,null),FC=Js(Nh,null),NC=Js(kh,null),kC=Js(Ah,null),MC=sr({commandHistoryStorage:FC,fileStorage:NC,workspaceStorage:kC}),LC=Hh(Lh,null),OC=Hh(Oh,null),AC=Js(_h,null),_C={activeTool:DC,plugins:IC,storage:MC,user:LC,workspace:OC,serverConfigValues:AC},PC=_C;class jC{reducers={};listener=null;register(e,t){this.reducers={...this.reducers,[e]:t},this.listener?.(this.reducers)}setListener(e){this.listener=e}}const HC=new jC,fo=HC,Bd=ne.module("redux-logger"),BC=c=>e=>t=>{Bd.debug("dispatching",t);const n=e(t);return Bd.debug("next state",c.getState()),n},UC=BC,VC=ne.module("redux-crashReporter"),$C=c=>e=>t=>{try{return e(t)}catch(n){throw VC.error("Error executing",t," with state ",c.getState(),":",n),n}},WC=$C,GC=[UC,WC,im];Object.entries(PC).map(([c,e])=>fo.register(c,e));const zC=window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__??am,Bh=om(sr(fo.reducers),zC(lm(...GC)));fo.setListener(c=>{Bh.replaceReducer(sr(c))});const yr=Bh,Uh=Object.freeze({openPopouts:[],settings:{hasHeaders:!0,constrainDragToContainer:!0,reorderEnabled:!0,selectionEnabled:!1,popoutWholeStack:!1,blockedPopoutsThrowError:!0,closePopoutsOnUnload:!0,showPopoutIcon:!0,showMaximiseIcon:!0,showCloseIcon:!0,responsiveMode:"onload",tabOverlapAllowance:0,tabControlOffset:10},dimensions:{borderWidth:5,borderGrabWidth:10,minItemHeight:10,minItemWidth:10,headerHeight:20,dragProxyWidth:300,dragProxyHeight:200},labels:{close:"Close",maximise:"Maximize",minimise:"Minimize",popout:"Open in new window",popin:"Pop in",tabDropdown:"Additional tabs",tabNextLabel:"Next",tabPreviousLabel:"Previous"},content:[]});function Vh(c){return c.componentName!==void 0}function KC(c){return c.component!==void 0}const $h=Object.freeze({type:"default",isClosable:!0,isFocusOnShow:!0,reorderEnabled:!0,title:""}),YC=Object.freeze(Object.defineProperty({__proto__:null,defaultConfig:Uh,isGLComponentConfig:Vh,isReactComponentConfig:KC,itemDefaultConfig:$h},Symbol.toStringTag,{value:"Module"}));class Cl{static ALL_EVENT="__all";_mSubscriptions;constructor(){this._mSubscriptions={},this._mSubscriptions[Cl.ALL_EVENT]=[]}on(e,t,n){if(typeof t!="function")throw new Error("Tried to listen to event "+e+" with non-function callback "+t);this._mSubscriptions[e]||(this._mSubscriptions[e]=[]),this._mSubscriptions[e].push({fn:t,ctx:n})}emit(e,...t){const n=this._mSubscriptions[e];if(n)for(let i=0;i<n.length;i++){const o=n[i].ctx||{};n[i].fn.apply(o,t)}t.unshift(e);const s=this._mSubscriptions[Cl.ALL_EVENT];for(let i=0;i<s.length;i++){const o=s[i].ctx||{};s[i].fn.apply(o,t)}}unbind(e,t,n){if(!this._mSubscriptions[e])throw new Error("No subscribtions to unsubscribe for event "+e);let s=!1;for(let i=0;i<this._mSubscriptions[e].length;i++)(!t||this._mSubscriptions[e][i].fn===t)&&(!n||n===this._mSubscriptions[e][i].ctx)&&(this._mSubscriptions[e].splice(i,1),s=!0);if(s===!1)throw new Error("Nothing to unbind for "+e)}off=this.unbind;trigger=this.emit}const fn=Cl;class Wa extends fn{width;height;title;parent;layoutManager;tab;_config;isHidden=!1;beforeCloseHandler;_element=he(['<div class="lm_item_container">','<div class="lm_content" tabindex="-1"></div>',"</div>"].join(""));_contentElement;constructor(e,t,n){super(),this.title=Vh(e)?e.componentName:"",this.parent=t,this.layoutManager=n,this._config=e,this._contentElement=this._element.find(".lm_content"),this.beforeCloseHandler=null}getElement(){return this._contentElement}hide(){this.emit("hide"),this.isHidden=!0,this._element.hide()}show(){this.emit("show"),this.isHidden=!1,this._element.show(),(this.height!=0||this.width!=0)&&this.emit("shown")}setSize(e,t){let n=this.parent,s=null;for(;n&&!n.isColumn&&!n.isRow;)if(s=n,n=n.parent,n?.isRoot)return!1;if(!n||!s)return!1;const i=n.isColumn?"height":"width",o=i==="height"?t:e,l=(this[i]??0)*(1/((s.config[i]??0)/100)),a=o/l*100,d=((s.config[i]??0)-a)/(n.contentItems.length-1);for(let h=0;h<n.contentItems.length;h++)n.contentItems[h]===s?n.contentItems[h].config[i]=a:n.contentItems[h].config[i]=(n.contentItems[h].config[i]??0)+d;return n.callDownwards("setSize"),!0}close(e){this._config.isClosable&&(this.beforeCloseHandler?.(e)??!0)&&(this.emit("close"),this.parent.close())}beforeClose(e){this.beforeCloseHandler=e}getState(){return this._config.componentState}extendState(e){this.setState(he.extend(!0,this.getState(),e))}setState(e){this._config.componentState=e,this.parent.emitBubblingEvent("stateChanged")}setTitle(e){this.parent.setTitle(e)}_$setSize(e=0,t=0){if(e!==this.width||t!==this.height){this.width=e,this.height=t;var n=this._contentElement[0],s=n.offsetWidth-n.clientWidth,i=n.offsetHeight-n.clientHeight;this._contentElement.width(this.width-s).height(this.height-i),this.emit("resize")}}}const qC=Object.freeze(Object.defineProperty({__proto__:null,Container:Wa,ItemContainer:Wa},Symbol.toStringTag,{value:"Module"}));function Wh(c){var e=location.hash.match(new RegExp(c+"=([^&]*)"));return e?e[1]:null}function Gh(c){if(window.location.hash)return Wh(c);if(!window.location.search)return null;var e=window.location.search.substr(1).split("&"),t={},n,s;for(s=0;s<e.length;s++)n=e[s].split("="),t[n[0]]=n[1];return t[c]||null}function Jl(c){return window.requestAnimationFrame(c)}function XC(c,e){var t=e.indexOf(c);if(t===-1)throw new Error("Can't remove item from array. Item is not in the array");e.splice(t,1)}function Rr(){return(Math.random()*1e15).toString(36).replace(".","")}function ZC(c,e){var t=c.replace(/javascript/gi,"j&#97;vascript").replace(/expression/gi,"expr&#101;ssion").replace(/onload/gi,"onlo&#97;d").replace(/script/gi,"&#115;cript").replace(/onerror/gi,"on&#101;rror");return e===!0?t:t.replace(/>/g,"&gt;").replace(/</g,"&lt;")}function xr(c){return he.trim(c.replace(/(<([^>]+)>)/gi,""))}class QC extends fn{_eElement;_oDocument;_eBody;_destroyAfterMouseUp;_nDelay=400;_timeout;timeout;_nDistance=10;_nX=0;_nY=0;_nOriginalX=0;_nOriginalY=0;_bDragging=!1;constructor(e,t=!1){super(),this._eElement=e,this._oDocument=he(document),this._eBody=he(document.body),this._destroyAfterMouseUp=t,this.onMouseMove=this.onMouseMove.bind(this),this.onMouseUp=this.onMouseUp.bind(this),this.onMouseDown=this.onMouseDown.bind(this),this._startDrag=this._startDrag.bind(this),this._eElement?.on("mousedown",this.onMouseDown)}destroy(){this._eElement?.unbind("mousedown",this.onMouseDown),this._oDocument?.unbind("mouseup",this.onMouseUp),this._eElement=void 0,this._oDocument=void 0,this._eBody=void 0,clearTimeout(this._timeout),this._timeout=void 0}onMouseDown(e){if(e.preventDefault(),e.button===0){var t=this._getCoordinates(e);this._nOriginalX=t.x??0,this._nOriginalY=t.y??0,this._oDocument?.on("mousemove",this.onMouseMove),this._oDocument?.on("mouseup",this.onMouseUp),this._timeout=window.setTimeout(this._startDrag,this._nDelay)}}onMouseMove(e){if(this._timeout!=null){e.preventDefault();var t=this._getCoordinates(e);this._nX=(t.x??0)-this._nOriginalX,this._nY=(t.y??0)-this._nOriginalY,this._bDragging===!1&&(Math.abs(this._nX)>this._nDistance||Math.abs(this._nY)>this._nDistance)&&this._startDrag(),this._bDragging&&this.emit("drag",this._nX,this._nY,e)}}onMouseUp(e){this._timeout!=null&&(clearTimeout(this._timeout),this._oDocument?.unbind("mousemove",this.onMouseMove),this._oDocument?.unbind("mouseup",this.onMouseUp),this._oDocument?.find("iframe")?.css("pointer-events",""),this._bDragging===!0&&(this._bDragging=!1,this.emit("dragStop",e,this._nOriginalX+this._nX)),this._eBody?.removeClass("lm_dragging"),this._eElement instanceof Window||this._eElement?.removeClass("lm_dragging"),this._destroyAfterMouseUp&&this.destroy())}_startDrag(){window.clearTimeout(this._timeout),this._bDragging=!0,this._eBody?.addClass("lm_dragging"),this._eElement?.addClass("lm_dragging"),this._oDocument?.find("iframe")?.css("pointer-events","none"),this.emit("dragStart",this._nOriginalX,this._nOriginalY)}_getCoordinates(e){return{x:e.pageX??0,y:e.pageY??0}}}const Co=QC;class zh{_container;_reactComponent=null;_originalComponentWillUpdate=null;_initialState;_reactClass;constructor(e,t){this._reactComponent=null,this._originalComponentWillUpdate=null,this._container=e,this._initialState=t,this._reactClass=this._getReactClass(),this._container.on("open",this._render,this),this._container.on("destroy",this._destroy,this)}_render(){al.render(this._getReactComponent(),this._container.getElement()[0])}_gotReactComponent(e){if(!e)return;this._reactComponent=e,this._originalComponentWillUpdate=this._reactComponent.componentWillUpdate||function(){},this._reactComponent.componentWillUpdate=this._onUpdate.bind(this);const t=this._container.getState();t&&this._reactComponent.setState(t)}_destroy(){al.unmountComponentAtNode(this._container.getElement()[0]),this._container.off("open",this._render,this),this._container.off("destroy",this._destroy,this)}_onUpdate(e,t){this._container.setState(t),this._originalComponentWillUpdate?.call(this._reactComponent,e,t)}_getReactClass(){var e=this._container._config.component;if(!e)throw new Error("No react component name. type: react-component needs a field `component`");const t=this._container.layoutManager.getComponent(e)||this._container.layoutManager.getFallbackComponent();if(!t)throw new Error('React component "'+e+'" not found. Please register all components with GoldenLayout using `registerComponent(name, component)`');return t}_getReactComponent(){var e={glEventHub:this._container.layoutManager.eventHub,glContainer:this._container,ref:this._gotReactComponent.bind(this)},t=he.extend(e,this._container._config.props);return de.createElement(this._reactClass,t)}}const bl=["settings","hasHeaders","constrainDragToContainer","selectionEnabled","dimensions","borderWidth","minItemHeight","minItemWidth","headerHeight","dragProxyWidth","dragProxyHeight","labels","close","maximise","minimise","popout","content","componentName","componentState","id","width","type","height","isClosable","title","popoutWholeStack","openPopouts","parentId","activeItemIndex","reorderEnabled","borderGrabWidth"],JC=[!0,!1,"row","column","stack","component","close","maximise","minimise","open in new window"];function Dr(c){if(bl.length>36)throw new Error("Too many keys in config minifier map");const e={};return Ir(c,e,"_min"),e}function Ga(c){if(bl.length>36)throw new Error("Too many keys in config minifier map");const e={};return Ir(c,e,"_max"),e}function Ir(c,e,t){const n=t==="_min"?eb:tb;for(let s in c){if(!c.hasOwnProperty(s))continue;const i=Array.isArray(c)?c[Number.parseInt(s,10)]:c[s];if(typeof i=="object"&&i!=null){const o=i instanceof Array?[]:{};if(Array.isArray(e))e[Number.parseInt(s,10)]=o;else{const l=n(s,bl);e[l]=o}Ir(i,o,t)}else{const o=n(i,JC);if(Array.isArray(e))e[Number.parseInt(s,10)]=o;else{const l=n(s,bl);e[l]=o}}}}function eb(c,e){if(typeof c=="string"&&c.length===1)return"___"+c;var t=e.indexOf(c);return t===-1?c:t.toString(36)}function tb(c,e){return typeof c=="string"&&c.length===1?e[parseInt(c,36)]:typeof c=="string"&&c.substr(0,3)==="___"?c[3]:c}class za{name;origin;isPropagationStopped;constructor(e,t){this.name=e,this.origin=t,this.isPropagationStopped=!1}stopPropagation(){this.isPropagationStopped=!0}}let nb=class extends fn{_layoutManager;_dontPropagateToParent;_childEventSource;_boundOnEventFromChild;constructor(e){super(),this._layoutManager=e,this._dontPropagateToParent=null,this._childEventSource=null,this.on(fn.ALL_EVENT,this._onEventFromThis.bind(this)),this._boundOnEventFromChild=this._onEventFromChild.bind(this),he(window).on("gl_child_event",this._boundOnEventFromChild)}_onEventFromThis(...e){this._layoutManager.isSubWindow&&e[0]!==this._dontPropagateToParent&&this._propagateToParent(e),this._propagateToChildren(e),this._dontPropagateToParent=null,this._childEventSource=null}_$onEventFromParent(e){this._dontPropagateToParent=e[0],this.emit.apply(this,e)}_onEventFromChild(e){this._childEventSource=e.originalEvent.__gl,this.emit.apply(this,e.originalEvent.__glArgs)}_propagateToParent(e){const t="gl_child_event",n=window.opener?.document.createEvent("HTMLEvents");n.initEvent(t,!0,!0),n.eventName=t,n.__glArgs=e,n.__gl=this._layoutManager,window.opener.dispatchEvent(n)}_propagateToChildren(e){for(let t=0;t<this._layoutManager.openPopouts.length;t++){const n=this._layoutManager.openPopouts[t].getGlInstance();n&&n!==this._childEventSource&&n.eventHub._$onEventFromParent(e)}}destroy(){he(window).off("gl_child_event",this._boundOnEventFromChild)}};const Kh=nb,sb=Object.freeze(Object.defineProperty({__proto__:null,BubblingEvent:za,DragListener:Co,EventEmitter:fn,EventHub:Kh,ReactComponentHandler:zh,animFrame:Jl,filterXss:ZC,getHashValue:Wh,getQueryStringParam:Gh,getUniqueId:Rr,minifyConfig:Dr,removeFromArray:XC,stripTags:xr,unminifyConfig:Ga},Symbol.toStringTag,{value:"Module"}));class Yh extends fn{isInitialised=!1;_config;_dimensions;_parentId;_indexInParent;_layoutManager;_popoutWindow=null;_id=null;constructor(e,t,n,s,i){super(),this._config=e,this._dimensions=t,this._parentId=n,this._indexInParent=s,this._layoutManager=i,this._createWindow()}toConfig(){if(this.isInitialised===!1)throw new Error("Can't create config, layout not yet initialised");return{dimensions:{width:this.getGlInstance()?.width,height:this.getGlInstance()?.height,left:this._popoutWindow?.screenX??this._popoutWindow?.screenLeft??0,top:this._popoutWindow?.screenY??this._popoutWindow?.screenTop??0},content:this.getGlInstance()?.toConfig().content,parentId:this._parentId,indexInParent:this._indexInParent}}getGlInstance(){return this._popoutWindow?.__glInstance}getWindow(){return this._popoutWindow}close(){if(this.getGlInstance())this.getGlInstance()?._$closeWindow();else try{this.getWindow()?.close()}catch{}}popIn(){this._indexInParent;let e=null,t=null;this._parentId&&(e=he.extend(!0,{},this.getGlInstance()?.toConfig()).content[0],t=this._layoutManager.root.getItemsById(this._parentId)[0],t||((this._layoutManager.root.contentItems.length??0)>0?t=this._layoutManager.root.contentItems[0]:t=this._layoutManager.root)),e&&(t?.addChild(e,this._indexInParent),this.close())}_createWindow(){const e=this._createUrl(),t=Math.floor(Math.random()*1e6).toString(36),n=this._serializeWindowOptions({width:this._dimensions.width,height:this._dimensions.height,innerWidth:this._dimensions.width,innerHeight:this._dimensions.height,menubar:"no",toolbar:"no",location:"no",personalbar:"no",resizable:"yes",scrollbars:"no",status:"no"});if(this._popoutWindow=window.open(e,t,n),!this._popoutWindow)if(this._layoutManager.config.settings.blockedPopoutsThrowError===!0){const i=new Error("Popout blocked");throw i.type="popoutBlocked",i}else return;he(this._popoutWindow).on("load",this._positionWindow.bind(this)).on("unload beforeunload",this._onClose.bind(this));let s=window.setInterval(()=>{this._popoutWindow?.__glInstance&&this._popoutWindow.__glInstance.isInitialised&&(this._onInitialised(),window.clearInterval(s))},10)}_serializeWindowOptions(e){var t=[],n;for(n in e)t.push(n+"="+e[n]);return t.join(",")}_createUrl(){var e={content:this._config};const t="gl-window-config-"+Rr();e=Dr(e);try{localStorage.setItem(t,JSON.stringify(e))}catch(s){throw new Error("Error while writing to localStorage "+s.toString())}const n=document.location.href.split("?");return n.length===1?n[0]+"?gl-window="+t:document.location.href+"&gl-window="+t}_positionWindow(){this._popoutWindow?.moveTo(this._dimensions.left,this._dimensions.top),this._popoutWindow?.focus()}_onInitialised(){this.isInitialised=!0,this.getGlInstance()?.on("popIn",this.popIn,this),this.emit("initialised")}_onClose(){setTimeout(this.emit.bind(this,"closed"),50)}}class Fi extends fn{static _template='<div class="lm_dragProxy"><div class="lm_header"><ul class="lm_tabs"><li class="lm_tab lm_active"><i class="lm_left"></i><span class="lm_title"></span><i class="lm_right"></i></li></ul></div><div class="lm_content"></div></div>';_dragListener;_layoutManager;_contentItem;_originalParent;_area=null;_lastValidArea=null;_minX;_maxX;_minY;_maxY;_width;_height;_sided;element;childElementContainer;_proxyTab;constructor(e,t,n,s,i,o){super(),this._dragListener=n,this._layoutManager=s,this._contentItem=i,this._originalParent=o,this._dragListener.on("drag",this._onDrag,this),this._dragListener.on("dragStop",this._onDrop,this),this._contentItem.tab&&this._contentItem.tab.element&&(this._layoutManager.tabDropPlaceholder.width(this._contentItem.tab.element.outerWidth(!0)??0),this._layoutManager.tabDropPlaceholder.height(this._contentItem.tab.element.outerHeight(!0)??0)),this.element=he(Fi._template),o&&o._side&&(this._sided=o._sided,this.element.addClass("lm_"+o._side),["right","bottom"].indexOf(o._side.toString())>=0&&this.element.find(".lm_content").after(this.element.find(".lm_header"))),this.element.css({left:e,top:t}),this._proxyTab=this.element.find(".lm_tab"),this._proxyTab.attr("title",xr(this._contentItem.config.title??"")),this.element.find(".lm_title").html(this._contentItem.config.title??""),this.childElementContainer=this.element.find(".lm_content"),this.childElementContainer.append(i.element),this._updateTree(),this._layoutManager._$calculateItemAreas(),he(document.body).append(this.element),this._setDimensions(),!this._contentItem.tab&&this._proxyTab.length&&(this._layoutManager.tabDropPlaceholder.width(this._proxyTab.outerWidth(!0)??0),this._layoutManager.tabDropPlaceholder.height(this._proxyTab.outerHeight(!0)??0));var l=this._layoutManager.container.offset();this._minX=l?.left??0,this._minY=l?.top??0,this._maxX=(this._layoutManager.container.width()??0)+this._minX,this._maxY=(this._layoutManager.container.height()??0)+this._minY,this._width=this.element.width()??0,this._height=this.element.height()??0,this._setDropPosition(e,t),this._layoutManager.emit("itemPickedUp",this._contentItem)}_onDrag(e,t,n){const s=n.pageX??0,i=n.pageY??0;!(s>this._minX&&s<this._maxX&&i>this._minY&&i<this._maxY)&&this._layoutManager.config.settings.constrainDragToContainer===!0||this._setDropPosition(s,i)}_setDropPosition(e,t){this.element.css({left:e,top:t}),this._area=this._layoutManager._$getArea(e,t),this._area!==null&&(this._lastValidArea=this._area,this._area.contentItem._$highlightDropZone(e,t,this._area))}_onDrop(){this._layoutManager.dropTargetIndicator?.hide(),this._area!==null?this._area.contentItem._$onDrop(this._contentItem,this._area):this._lastValidArea!==null?this._lastValidArea.contentItem._$onDrop(this._contentItem,this._lastValidArea):this._originalParent?this._originalParent.addChild(this._contentItem):this._contentItem._$destroy(),this._dragListener.off("drag",this._onDrag,this),this._dragListener.off("dragStop",this._onDrop,this),this.element.remove(),this._layoutManager.emit("itemDropped",this._contentItem)}_updateTree(){this._contentItem.parent&&this._contentItem.parent.removeChild(this._contentItem,!0),this._contentItem._$setParent(null)}_setDimensions(){const e=this._layoutManager.config.dimensions;let t=e.dragProxyWidth,n=e.dragProxyHeight;this.element.width(t),this.element.height(n),t-=this._sided?e.headerHeight:0,n-=this._sided?0:e.headerHeight,this.childElementContainer.width(t),this.childElementContainer.height(n),this._contentItem.element.width(t),this._contentItem.element.height(n),this._contentItem.callDownwards("_$show"),this._contentItem.callDownwards("setSize")}}class qh{_element;_itemConfig;_layoutManager;_dragListener;constructor(e,t,n){this._element=e,this._itemConfig=t,this._layoutManager=n,this._dragListener=this._createDragListener()}_createDragListener(){return this._dragListener=new Co(this._element,!0),this._dragListener.on("dragStart",this._onDragStart,this),this._dragListener.on("dragStop",this._createDragListener,this),this._dragListener}_onDragStart(e,t){let n=this._itemConfig;typeof n=="function"&&(n=n());const s=this._layoutManager._$normalizeContentItem(he.extend(!0,{},n)),i=new Fi(e,t,this._dragListener,this._layoutManager,s,null);this._layoutManager.transitionIndicator?.transitionElements(this._element,i.element)}}class Xh{_element=he(window);_itemConfig;_layoutManager;_dragListener;constructor(e,t,n){this._itemConfig=e,this._layoutManager=t,this._createDragListener(n)}_createDragListener(e){this._dragListener&&this._dragListener.destroy(),this._element&&(this._dragListener=new Co(this._element,!0),this._dragListener.on("dragStart",this._onDragStart,this),this._dragListener.on("dragStop",this._destroy,this),this._dragListener.onMouseDown(e),this._dragListener._startDrag())}_destroy(){this._dragListener=void 0,this._element=void 0,this._itemConfig=void 0,this._layoutManager=void 0}_onDragStart(e,t){if(!(!this._dragListener||!this._layoutManager)){var n=this._itemConfig;typeof n=="function"&&(n=n());var s=this._layoutManager._$normalizeContentItem(he.extend(!0,{},n));new Fi(e,t,this._dragListener,this._layoutManager,s,null)}}}class ea{static _template='<div class="lm_dropTargetIndicator"><div class="lm_inner"></div></div>';element=he(ea._template);constructor(){he(document.body).append(this.element)}destroy(){this.element.remove()}highlightArea(e){this.element.css({left:e.x1,top:e.y1,width:Math.floor(e.x2-e.x1),height:Math.floor(e.y2-e.y1)}).show()}hide(){this.element.hide()}}class qi{element;_header;_action;constructor(e,t,n,s){this._header=e,this.element=he('<li class="'+n+'" title="'+t+'"></li>'),this._header.on("destroy",this._$destroy,this),this._action=s,this.element.on("click",this._action),this._header.controlsContainer.append(this.element)}_$destroy(){this.element.off(),this.element.remove()}}class ib extends Error{node;constructor(e,t){super(),this.name="Configuration Error",this.message=e,this.node=t}}const Gs=ib,ob=Object.freeze(Object.defineProperty({__proto__:null,ConfigurationError:Gs},Symbol.toStringTag,{value:"Module"}));function lo(c){return c.isStack}function Ot(c){return c.isComponent}function Zh(c){return c.isRoot}class bt extends fn{config;type;contentItems;parent;layoutManager;element;childElementContainer;componentName;isInitialised=!1;isMaximised=!1;isRoot=!1;isRow=!1;isColumn=!1;isStack=!1;isComponent=!1;tab;_pendingEventPropagations;_throttledEvents;constructor(e,t,n,s){super(),this.element=s,this.config=this._extendItemNode(t),this.type=t.type,this.contentItems=[],this.parent=n,this.layoutManager=e,this._pendingEventPropagations={},this._throttledEvents=["stateChanged"],this.on(fn.ALL_EVENT,this._propagateEvent,this),t.content&&this._createContentItems(t)}callDownwards(e,t=[],n=!1,s=!1){n!==!0&&s!==!0&&this[e].apply(this,t);for(let i=0;i<this.contentItems.length;i++)this.contentItems[i].callDownwards(e,t,n);n===!0&&s!==!0&&this[e].apply(this,t)}removeChild(e,t=!1){const n=this.contentItems.indexOf(e);if(n===-1)throw new Error("Can't remove child item. Unknown content item");t!==!0&&this.contentItems[n]._$destroy(),this.contentItems.splice(n,1),this.config.content?.splice(n,1),this.contentItems.length>0?this.callDownwards("setSize"):this.type!=="root"&&this.config.isClosable&&this.parent?.removeChild(this)}addChild(e,t){e=this.layoutManager._$normalizeContentItem(e,this),t===void 0&&(t=this.contentItems.length),this.contentItems.splice(t,0,e),this.config.content===void 0&&(this.config.content=[]),this.config.content.splice(t,0,e.config),e.parent=this,e.parent.isInitialised===!0&&e.isInitialised===!1&&e._$init()}replaceChild(e,t,n=!1){t=this.layoutManager._$normalizeContentItem(t);const s=this.contentItems.indexOf(e),i=e.element[0].parentNode;if(s===-1)throw new Error("Can't replace child. oldChild is not child of this");i?.replaceChild(t.element[0],e.element[0]),n===!0&&(e.parent=null,e._$destroy()),this.contentItems[s]=t,t.parent=this,lo(this)&&(this.header.tabs[s].contentItem=t),t.parent.isInitialised===!0&&t.isInitialised===!1&&t._$init(),this.callDownwards("setSize")}remove(){this.parent?.removeChild(this)}popout(){var e=this.layoutManager.createPopout(this);return this.emitBubblingEvent("stateChanged"),e}toggleMaximise(e){e&&e.preventDefault(),this.isMaximised===!0?this.layoutManager._$minimiseItem(this):this.layoutManager._$maximiseItem(this),this.isMaximised=!this.isMaximised,this.emitBubblingEvent("stateChanged")}select(){this.layoutManager.selectedItem!==this&&(this.layoutManager.selectItem(this,!0),this.element.addClass("lm_selected"))}deselect(){this.layoutManager.selectedItem===this&&(this.layoutManager.selectedItem=null,this.element.removeClass("lm_selected"))}setTitle(e){this.config.title=e,this.emit("titleChanged",e),this.emitBubblingEvent("stateChanged")}hasId(e){if(this.config.id){if(typeof this.config.id=="string")return this.config.id===e;if(this.config.id instanceof Array)return this.config.id.indexOf(e)!==-1}else return!1}addId(e){this.hasId(e)||(this.config.id?typeof this.config.id=="string"?this.config.id=[this.config.id,e]:this.config.id instanceof Array&&this.config.id.push(e):this.config.id=e)}removeId(e){if(!this.hasId(e))throw new Error("Id not found");if(typeof this.config.id=="string")delete this.config.id;else if(this.config.id instanceof Array){var t=this.config.id.indexOf(e);this.config.id.splice(t,1)}}getItemsByFilter(e){const t=[],n=function(s){for(let i=0;i<s.contentItems.length;i++)e(s.contentItems[i])===!0&&t.push(s.contentItems[i]),n(s.contentItems[i])};return n(this),t}getItemsById(e){return this.getItemsByFilter(function(t){return t.config.id instanceof Array?t.config.id.indexOf(e)!==-1:t.config.id===e})}getItemsByType(e){return this._$getItemsByProperty("type",e)}getComponentsByName(e){const t=this._$getItemsByProperty("componentName",e),n=[];for(let s=0;s<t.length;s++)n.push(t[s].instance);return n}_$getItemsByProperty(e,t){return this.getItemsByFilter(function(n){return n[e]===t})}_$setParent(e){this.parent=e}_$highlightDropZone(e,t,n){this.layoutManager.dropTargetIndicator?.highlightArea(n)}_$onDrop(e,t){this.addChild(e)}_$hide(){this._callOnActiveComponents("hide"),this.element.hide(),this.layoutManager.updateSize()}_$show(){this._callOnActiveComponents("show"),this.element.show(),this.layoutManager.updateSize()}_callOnActiveComponents(e){const t=this.getItemsByType("stack");let n=null;for(let s=0;s<t.length;s++)n=t[s].getActiveContentItem(),n&&Ot(n)&&n.container[e]()}_$destroy(){this.emitBubblingEvent("beforeItemDestroyed"),this.callDownwards("_$destroy",[],!0,!0),this.element.remove(),this.emitBubblingEvent("itemDestroyed")}_$getArea(e){e=e||this.element;const t=e.offset()??{left:0,top:0},n=e.width()??0,s=e.height()??0;return{x1:t.left,y1:t.top,x2:t.left+n,y2:t.top+s,surface:n*s,contentItem:this,side:""}}_$init(){this.setSize();for(let e=0;e<this.contentItems.length;e++)this.childElementContainer?.append(this.contentItems[e].element);this.isInitialised=!0,this.emitBubblingEvent("itemCreated"),this.emitBubblingEvent(this.type+"Created")}emitBubblingEvent(e){var t=new za(e,this);this.emit(e,t)}_createContentItems(e){var t;if(!(e.content instanceof Array))throw new Gs("content must be an Array",e);for(let n=0;n<e.content.length;n++)t=this.layoutManager.createContentItem(e.content[n],this),this.contentItems.push(t)}_extendItemNode(e){for(let[t,n]of Object.entries($h)){const s=t;e[s]===void 0&&(e[s]=n)}return e}_propagateEvent(e,t){t instanceof za&&t.isPropagationStopped===!1&&this.isInitialised===!0&&(this.isRoot===!1&&this.parent?this.parent.emit.apply(this.parent,[e,t]):this._scheduleEventPropagationToLayoutManager(e,t))}_scheduleEventPropagationToLayoutManager(e,t){this._throttledEvents.indexOf(e)===-1?this.layoutManager.emit(e,t.origin):this._pendingEventPropagations[e]!==!0&&(this._pendingEventPropagations[e]=!0,Jl(this._propagateEventToLayoutManager.bind(this,e,t)))}_propagateEventToLayoutManager(e,t){this._pendingEventPropagations[e]=!1,this.layoutManager.emit(e,t)}}class Qh extends bt{config;componentName;container;parent;instance;constructor(e,t,n){super(e,t,n,he()),this.config=t,this.parent=n;const s=e.getComponent(this.config.componentName)||e.getFallbackComponent(),i=he.extend(!0,{},this.config.componentState||{});if(s==null)throw new Gs('Unknown component "'+this.config.componentName+'"');i.componentName=this.config.componentName,this.componentName=this.config.componentName,this.config.title===""&&(this.config.title=this.config.componentName),this.isComponent=!0,this.container=new Wa(this.config,this,e),this.instance=new s(this.container,i),this.element=this.container._element}close(){this.parent.removeChild(this)}setSize(){this.element.is(":visible")&&this.container._$setSize(this.element.width(),this.element.height())}_$init(){bt.prototype._$init.call(this),this.container.emit("open")}_$hide(){this.container.hide(),bt.prototype._$hide.call(this)}_$show(){this.container.show(),this.container._config.isFocusOnShow&&this.container._contentElement[0].focus({preventScroll:!0}),bt.prototype._$show.call(this)}_$destroy(){this.container.emit("destroy",this),bt.prototype._$destroy.call(this)}_$getArea(){return null}}class Sl extends bt{isRow;isColumn;childElementContainer;parent;_splitter=[];_splitterSize;_splitterGrabSize;_isColumn;_dimension;_splitterPosition=null;_splitterMinPosition=null;_splitterMaxPosition=null;constructor(e,t,n,s){super(t,n,s,he('<div class="lm_item lm_'+(e?"column":"row")+'"></div>')),this.parent=s,this.isRow=!e,this.isColumn=e,this.childElementContainer=this.element,this._splitterSize=t.config.dimensions.borderWidth,this._splitterGrabSize=t.config.dimensions.borderGrabWidth,this._isColumn=e,this._dimension=e?"height":"width",this._splitterPosition=null,this._splitterMinPosition=null,this._splitterMaxPosition=null}addChild(e,t,n){var s,i,o,l;if(e=this.layoutManager._$normalizeContentItem(e,this),t===void 0&&(t=this.contentItems.length),this.contentItems.length>0?(l=this._createSplitter(Math.max(0,t-1)).element,t>0?(this.contentItems[t-1].element.after(l),l.after(e.element)):(this.contentItems[0].element.before(l),l.before(e.element))):this.childElementContainer.append(e.element),bt.prototype.addChild.call(this,e,t),s=1/this.contentItems.length*100,n===!0){this.emitBubblingEvent("stateChanged");return}for(o=0;o<this.contentItems.length;o++)this.contentItems[o]===e?e.config[this._dimension]=s:(i=(this.contentItems[o].config[this._dimension]??0)*(100-s)/100,this.contentItems[o].config[this._dimension]=i);this.callDownwards("setSize"),this.emitBubblingEvent("stateChanged")}removeChild(e,t){var n=e.config[this._dimension]??0,s=this.contentItems.indexOf(e),i=Math.max(s-1,0),o,l;if(s===-1)throw new Error("Can't remove child. ContentItem is not child of this Row or Column");for(this._splitter[i]&&(this._splitter[i]._$destroy(),this._splitter.splice(i,1)),o=0;o<this.contentItems.length;o++)this.contentItems[o]!==e&&(this.contentItems[o].config[this._dimension]=(this.contentItems[o].config[this._dimension]??0)+n/(this.contentItems.length-1));bt.prototype.removeChild.call(this,e,t),this.contentItems.length===1&&this.config.isClosable===!0?(l=this.contentItems[0],this.contentItems=[],this.parent.replaceChild(this,l,!0)):(this.callDownwards("setSize"),this.emitBubblingEvent("stateChanged"))}replaceChild(e,t){var n=e.config[this._dimension];super.replaceChild(e,t),t.config[this._dimension]=n,this.callDownwards("setSize"),this.emitBubblingEvent("stateChanged")}setSize(){this.contentItems.length>0&&(this._calculateRelativeSizes(),this._setAbsoluteSizes()),this.emitBubblingEvent("stateChanged"),this.emit("resize")}_$init(){if(this.isInitialised!==!0){var e;for(bt.prototype._$init.call(this),e=0;e<this.contentItems.length-1;e++)this.contentItems[e].element.after(this._createSplitter(e).element)}}_setAbsoluteSizes(){var e,t=this._calculateAbsoluteSizes();for(e=0;e<this.contentItems.length;e++)t.additionalPixel-e>0&&t.itemSizes[e]++,this._isColumn?(this.contentItems[e].element.width(t.totalWidth),this.contentItems[e].element.height(t.itemSizes[e])):(this.contentItems[e].element.width(t.itemSizes[e]),this.contentItems[e].element.height(t.totalHeight))}_calculateAbsoluteSizes(){const e=(this.contentItems.length-1)*this._splitterSize;let t=this.element.width()??0,n=this.element.height()??0,s=0;const i=[];this._isColumn?n-=e:t-=e;for(let l=0;l<this.contentItems.length;l++){const a=this._isColumn?Math.floor(n*((this.contentItems[l].config.height??0)/100)):Math.floor(t*((this.contentItems[l].config.width??0)/100));s+=a,i.push(a)}const o=Math.floor((this._isColumn?n:t)-s);return{itemSizes:i,additionalPixel:o,totalWidth:t,totalHeight:n}}_calculateRelativeSizes(){let e=0;const t=[],n=this._isColumn?"height":"width";for(let s=0;s<this.contentItems.length;s++)this.contentItems[s].config[n]!==void 0?e+=this.contentItems[s].config[n]??0:t.push(this.contentItems[s]);if(Math.round(e)===100){this._respectMinItemWidth();return}if(Math.round(e)<100&&t.length>0){for(let s=0;s<t.length;s++)t[s].config[n]=(100-e)/t.length;this._respectMinItemWidth();return}if(Math.round(e)>100)for(let s=0;s<t.length;s++)t[s].config[n]=50,e+=50;for(let s=0;s<this.contentItems.length;s++)this.contentItems[s].config[n]=(this.contentItems[s].config[n]??0)/e*100;this._respectMinItemWidth()}_respectMinItemWidth(){const e=this.layoutManager.config.dimensions?this.layoutManager.config.dimensions.minItemWidth??0:0,t=[];let n=0,s=0,i=0;const o=[];let l;if(this._isColumn||!e||this.contentItems.length<=1)return;const a=this._calculateAbsoluteSizes();for(let h=0;h<this.contentItems.length;h++){this.contentItems[h];const u=a.itemSizes[h];u<e?(s+=e-u,l={width:e}):(n+=u-e,l={width:u},t.push(l)),o.push(l)}if(s===0||s>n)return;const d=s/n;i=s;for(let h=0;h<t.length;h++){l=t[h];const u=Math.round((l.width-e)*d);i-=u,l.width-=u}i!==0&&(o[o.length-1].width-=i);for(let h=0;h<this.contentItems.length;h++)this.contentItems[h].config.width=o[h].width/a.totalWidth*100}_createSplitter(e){var t;return t=new Jh(this._isColumn,this._splitterSize,this._splitterGrabSize),t.on("drag",this._onSplitterDrag.bind(this,t),this),t.on("dragStop",this._onSplitterDragStop.bind(this,t),this),t.on("dragStart",this._onSplitterDragStart.bind(this,t),this),this._splitter.splice(e,0,t),t}_getItemsForSplitter(e){const t=this._splitter.indexOf(e);if(t<0)throw new Error("Splitter not found in RowOrColumn");return{before:this.contentItems[t],after:this.contentItems[t+1]}}_getMinimumDimensions(e){for(var t=0,n=0,s=0;s<e.length;++s)t=Math.max(e[s].minWidth??0,t),n=Math.max(e[s].minHeight??0,n);return{horizontal:t,vertical:n}}_onSplitterDragStart(e){const t=this._getItemsForSplitter(e),n=this.layoutManager.config.dimensions[this._isColumn?"minItemHeight":"minItemWidth"];var s=this._getMinimumDimensions(t.before.config.content??[]),i=this._isColumn?s.vertical:s.horizontal,o=this._getMinimumDimensions(t.after.config.content??[]),l=this._isColumn?o.vertical:o.horizontal;this._splitterPosition=0,this._splitterMinPosition=-1*((t.before.element[this._dimension]()??0)-(i||n)),this._splitterMaxPosition=(t.after.element[this._dimension]()??0)-(l||n)}_onSplitterDrag(e,t,n){const s=this._isColumn?n:t;this._splitterMaxPosition==null||this._splitterMinPosition==null||s>this._splitterMinPosition&&s<this._splitterMaxPosition&&(this._splitterPosition=s,e.element.css(this._isColumn?"top":"left",s))}_onSplitterDragStop(e){const t=this._getItemsForSplitter(e),n=t.before.element[this._dimension]()??0,s=t.after.element[this._dimension]()??0,i=((this._splitterPosition??0)+n)/(n+s),o=(t.before.config[this._dimension]??0)+(t.after.config[this._dimension]??0);t.before.config[this._dimension]=i*o,t.after.config[this._dimension]=(1-i)*o,e.element.css({top:0,left:0}),Jl(this.callDownwards.bind(this,"setSize",void 0,void 0,void 0))}}class Ka extends bt{childElementContainer;_containerElement;constructor(e,t,n){super(e,{...t,type:"root"},null,he('<div class="lm_goldenlayout lm_item lm_root"></div>')),this.isRoot=!0,this.type="root",this.childElementContainer=this.element,this._containerElement=n,this._containerElement.append(this.element)}addChild(e,t){if(this.contentItems.length>0)throw new Error("Root node can only have a single child");e=this.layoutManager._$normalizeContentItem(e,this),this.childElementContainer.append(e.element),super.addChild(e,t),this.callDownwards("setSize"),this.emitBubblingEvent("stateChanged")}setSize(e,t){e=typeof e>"u"?this._containerElement.width()??0:e,t=typeof t>"u"?this._containerElement.height()??0:t,this.element.width(e),this.element.height(t),this.contentItems[0]&&(this.contentItems[0].element.width(e),this.contentItems[0].element.height(t))}_$getArea(){const e=super._$getArea();if(e==null)throw new Error("Unable to get root area");return e}_$highlightDropZone(e,t,n){this.layoutManager.tabDropPlaceholder.remove(),super._$highlightDropZone(e,t,n)}_$onDrop(e,t){var n;if(Ot(e)&&(n=this.layoutManager.createContentItem({type:"stack",header:e.config.header||{}},this),n._$init(),n.addChild(e),e=n),!this.contentItems.length)this.addChild(e);else{const{side:s}=t,i=s==="left"||s==="right"?"row":"column",o=s==="left"||s==="right"?"width":"height",l=s==="left"||s==="top",a=this.contentItems[0];if(!(a instanceof Sl)||a.type!=i){const d=this.layoutManager.createContentItem({type:i},this);this.replaceChild(a,d),d.addChild(e,l?0:void 0,!0),d.addChild(a,l?void 0:0,!0),a.config[o]=50,e.config[o]=50,d.callDownwards("setSize")}else{const d=a.contentItems[l?0:a.contentItems.length-1];a.addChild(e,l?0:void 0,!0),d.config[o]=(d.config[o]??0)*.5,e.config[o]=d.config[o],a.callDownwards("setSize")}}}}class Ya extends bt{_activeContentItem=null;_header;childElementContainer=he('<div class="lm_items"></div>');header;parent;isStack=!0;_dropZones={};_dropSegment=null;_contentAreaDimensions=null;_dropIndex;_side;_sided=!1;config;constructor(e,t,n){super(e,t,n,he('<div class="lm_item lm_stack"></div>')),this.parent=n,this.config=t;const s=e.config;this._side=!1,this._header={show:s.settings?.hasHeaders&&t.hasHeaders!==!1,popout:s.settings?.showPopoutIcon?s.labels?.popout:void 0,maximise:s.settings?.showMaximiseIcon?s.labels?.maximise:void 0,close:s.settings?.showCloseIcon?s.labels?.close:void 0,minimise:s.labels?.minimise??void 0},s.header&&(this._header={...this._header,...s.header}),t.header&&(this._header={...this._header,...t.header}),t.content&&t.content[0]&&t.content[0].header&&(this._header={...this._header,...t.content[0].header}),this.header=new Ti(e,this),this.element.append(this.header.element),this.element.append(this.childElementContainer),this._setupHeaderPosition(),this._$validateClosability()}setSize(){var e,t=this._header.show?this.layoutManager.config.dimensions?.headerHeight??0:0,n=(this.element.width()??0)-(this._sided?t:0),s=(this.element.height()??0)-(this._sided?0:t);for(this.childElementContainer.width(n),this.childElementContainer.height(s),e=0;e<this.contentItems.length;e++)this.contentItems[e].element.width(n).height(s);this.emit("resize"),this.emitBubblingEvent("stateChanged")}_$init(){if(this.isInitialised!==!0){this.header._attachWheelListener(),super._$init();for(let e=0;e<this.contentItems.length;e++)this.header.createTab(this.contentItems[e]),this.contentItems[e]._$hide();if(this.contentItems.length>0){const e=this.contentItems[this.config.activeItemIndex||0];if(!e)throw new Error("Configured activeItemIndex out of bounds");this.setActiveContentItem(e)}}}setActiveContentItem(e){if(this.contentItems.indexOf(e)===-1)throw new Error("contentItem is not a child of this stack");this._activeContentItem!==null&&this._activeContentItem._$hide(),this._activeContentItem=e,this.header.setActiveContentItem(e),e._$show(),this.emit("activeContentItemChanged",e),this.layoutManager.emit("activeContentItemChanged",e),this.emitBubblingEvent("stateChanged")}getActiveContentItem(){return this.header.activeContentItem}addChild(e,t){e=this.layoutManager._$normalizeContentItem(e,this),super.addChild(e,t),this.childElementContainer.append(e.element),this.header.createTab(e,t),this.setActiveContentItem(e),this.callDownwards("setSize"),this._$validateClosability(),this.emitBubblingEvent("stateChanged")}removeChild(e,t=!1){var n=this.contentItems.indexOf(e);super.removeChild(e,t),this.header.removeTab(e),this.header.activeContentItem===e&&(this.contentItems.length>0?this.setActiveContentItem(this.contentItems[Math.max(n-1,0)]):this._activeContentItem=null),this._$validateClosability(),this.emitBubblingEvent("stateChanged")}_$validateClosability(){let e=this.header._isClosable();for(let t=0,n=this.contentItems.length;t<n&&e;t++)e=this.contentItems[t].config.isClosable??!1;this.header._$setClosable(e)}_$destroy(){bt.prototype._$destroy.call(this),this.header._$destroy()}_$onDrop(e){if(this._dropSegment==="header"){this._resetHeaderDropZone(),this.addChild(e,this._dropIndex);return}if(this._dropSegment==="body"){this.addChild(e);return}const t=this._dropSegment==="top"||this._dropSegment==="bottom",n=this._dropSegment==="left"||this._dropSegment==="right",s=this._dropSegment==="top"||this._dropSegment==="left",i=t&&this.parent.isColumn||n&&this.parent.isRow,o=t?"column":"row",l=t?"height":"width";if(Ot(e)){const a=this.layoutManager.createContentItem({type:"stack",header:e.config.header||{}},this);a._$init(),a.addChild(e),e=a}if(i){const a=this.parent.contentItems.indexOf(this);this.parent.addChild(e,s?a:a+1,!0),this.config[l]=(this.config[l]??0)*.5,e.config[l]=this.config[l],this.parent.callDownwards("setSize")}else{const a=this.layoutManager.createContentItem({type:o},this);this.parent.replaceChild(this,a),a.addChild(e,s?0:void 0,!0),a.addChild(this,s?void 0:0,!0),this.config[l]=50,e.config[l]=50,a.callDownwards("setSize")}}_$highlightDropZone(e,t){if(this._contentAreaDimensions)for(let[n,s]of Object.entries(this._contentAreaDimensions)){const i=s.hoverArea;if(i.x1<e&&i.x2>e&&i.y1<t&&i.y2>t){n==="header"?(this._dropSegment="header",this._highlightHeaderDropZone(e)):(this._resetHeaderDropZone(),this._highlightBodyDropZone(n));return}}}_$getArea(){if(this.element.is(":visible")===!1)return null;const e=super._$getArea(this.header.element),t=super._$getArea(this.childElementContainer);if(e==null||t==null)return null;const n=t.x2-t.x1,s=t.y2-t.y1;return this._contentAreaDimensions={header:{hoverArea:{x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2},highlightArea:{x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2}}},this._activeContentItem&&this._activeContentItem.isComponent===!1?e:this.contentItems.length===0?(this._contentAreaDimensions.body={hoverArea:{x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2},highlightArea:{x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2}},super._$getArea(this.element)):(this._contentAreaDimensions.left={hoverArea:{x1:t.x1,y1:t.y1,x2:t.x1+n*.25,y2:t.y2},highlightArea:{x1:t.x1,y1:t.y1,x2:t.x1+n*.5,y2:t.y2}},this._contentAreaDimensions.top={hoverArea:{x1:t.x1+n*.25,y1:t.y1,x2:t.x1+n*.75,y2:t.y1+s*.5},highlightArea:{x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y1+s*.5}},this._contentAreaDimensions.right={hoverArea:{x1:t.x1+n*.75,y1:t.y1,x2:t.x2,y2:t.y2},highlightArea:{x1:t.x1+n*.5,y1:t.y1,x2:t.x2,y2:t.y2}},this._contentAreaDimensions.bottom={hoverArea:{x1:t.x1+n*.25,y1:t.y1+s*.5,x2:t.x1+n*.75,y2:t.y2},highlightArea:{x1:t.x1,y1:t.y1+s*.5,x2:t.x2,y2:t.y2}},super._$getArea(this.element))}_highlightHeaderDropZone(e){const t=this.header.tabs.length;if(t===0){const u=this.header.element.offset();this.layoutManager.dropTargetIndicator?.highlightArea({x1:u?.left??0,x2:(u?.left??0)+100,y1:this.header.element.offset()?.top??0,y2:(this.header.element.offset()?.top??0)+(this.header.element.innerHeight()??0)});return}const s=this.header.tabsContainer.get(0)?.getBoundingClientRect(),i=this.layoutManager.tabDropPlaceholder.get(0)?.getBoundingClientRect();if(!s||!i)return;e<s.left?e=s.left+1:e>s.right&&(e=s.right-1);let o,l;if(!(i.left<e&&e<i.right)){for(var a=0;a<t;a++)if(o=this.header.tabs[a].element,l=o.get(0)?.getBoundingClientRect(),l&&l.left<e&&e<l.right){this._dropIndex=a;break}o&&l&&e<l.left+l.width*.5?o.before(this.layoutManager.tabDropPlaceholder):o&&(this._dropIndex=Math.min((this._dropIndex??0)+1,t),o.after(this.layoutManager.tabDropPlaceholder))}let d=this.layoutManager.tabDropPlaceholder.offset()?.left??0;d=Math.max(d,this.header.tabsContainer.offset()?.left??0);var h=d+(this.layoutManager.tabDropPlaceholder.width()??0);h=Math.min(h,(this.header.tabsContainer.offset()?.left??0)+(this.header.tabsContainer.innerWidth()??0)),this.layoutManager.dropTargetIndicator?.highlightArea({x1:d,x2:h,y1:this.header.element.offset()?.top??0,y2:(this.header.element.offset()?.top??0)+(this.header.element.innerHeight()??0)})}_resetHeaderDropZone(){this.layoutManager.tabDropPlaceholder.remove()}_setupHeaderPosition(){const e=["right","left","bottom"].some(t=>t===this._header.show)?this._header.show:void 0;if(this.header.element.toggle(!!this._header.show),!!e&&(this._side=e,this._sided=["right","left"].indexOf(this._side.toString())>=0,this.element.removeClass("lm_left lm_right lm_bottom"),this._side&&this.element.addClass("lm_"+this._side),this.element.find(".lm_header").length&&this.childElementContainer)){const t=["right","bottom"].indexOf(this._side.toString())>=0?"before":"after";this.header.element[t](this.childElementContainer),this.callDownwards("setSize")}}_highlightBodyDropZone(e){const t=this._contentAreaDimensions?.[e]?.highlightArea;t&&this.layoutManager.dropTargetIndicator?.highlightArea(t),this._dropSegment=e}}const lb=Object.freeze(Object.defineProperty({__proto__:null,AbstractContentItem:bt,Component:Qh,ContentItem:bt,Root:Ka,RowOrColumn:Sl,Stack:Ya,isComponent:Ot,isRoot:Zh,isStack:lo},Symbol.toStringTag,{value:"Module"}));class ta{static _template=['<li class="lm_tab">','<span class="lm_title_before"></span>','<span class="lm_title"></span>','<div class="lm_close_tab"></div>',"</li>"].join("");header;contentItem;element=he(ta._template);titleElement;closeElement;isActive=!1;_layoutManager;_dragListener;constructor(e,t){this.header=e,this.contentItem=t,this.titleElement=this.element.find(".lm_title"),this.closeElement=this.element.find(".lm_close_tab"),this.closeElement[t.config.isClosable?"show":"hide"](),this.setTitle(t.config.title),this.contentItem.on("titleChanged",this.setTitle,this),this._layoutManager=this.contentItem.layoutManager,this._layoutManager.config.settings?.reorderEnabled&&t.config.reorderEnabled&&(this._dragListener=new Co(this.element),this._dragListener.on("dragStart",this._onDragStart,this),this.contentItem.on("destroy",this._dragListener.destroy,this._dragListener)),this._onTabClick=this._onTabClick.bind(this),this._onCloseClick=this._onCloseClick.bind(this),this._onTabContentFocusIn=this._onTabContentFocusIn.bind(this),this._onTabContentFocusOut=this._onTabContentFocusOut.bind(this),this.element.on("click",this._onTabClick),this.element.on("auxclick",this._onTabClick),this.contentItem.config.isClosable?(this.closeElement.on("click",this._onCloseClick),this.closeElement.on("mousedown",this._onCloseMousedown)):this.closeElement.remove(),this.contentItem.tab=this,this.contentItem.emit("tab",this),this.contentItem.layoutManager.emit("tabCreated",this),Ot(this.contentItem)&&(this.contentItem.container._contentElement.on("focusin",this._onTabContentFocusIn).on("focusout",this._onTabContentFocusOut),this.contentItem.container._contentElement[0].addEventListener("click",this._onTabContentFocusIn,!0),this.contentItem.container.tab=this,this.contentItem.container.emit("tab",this))}setTitle(e=""){this.titleElement.html(e)}setActive(e){e!==this.isActive&&(this.isActive=e,e?this.element.addClass("lm_active"):this.element.removeClass("lm_active"))}_$destroy(){this.element.off("click",this._onTabClick),this.element.off("auxclick",this._onTabClick),this.closeElement.off("click",this._onCloseClick),Ot(this.contentItem)&&(this.contentItem.container._contentElement.off(),this.contentItem.container._contentElement[0].removeEventListener("click",this._onTabContentFocusIn,!0)),this._dragListener&&(this.contentItem.off("destroy",this._dragListener.destroy,this._dragListener),this._dragListener.off("dragStart",this._onDragStart),this._dragListener=void 0),this.element.remove()}_onDragStart(e,t){this.contentItem.parent?.isMaximised&&this.contentItem.parent.toggleMaximise(),this._dragListener&&new Fi(e,t,this._dragListener,this._layoutManager,this.contentItem,this.header.parent)}_onTabContentFocusIn(){Ot(this.contentItem)&&!this.contentItem.container._contentElement[0].contains(document.activeElement)&&this.contentItem.container._contentElement[0].focus(),this.element.addClass("lm_focusin")}_onTabContentFocusOut(){Ot(this.contentItem)&&!this.contentItem.container._contentElement[0].contains(document.activeElement)&&this.element.removeClass("lm_focusin")}_onTabClick(e){if(!e||e.button===0){var t=this.header.parent.getActiveContentItem();this.contentItem!==t&&Ot(this.contentItem)?this.header.parent.setActiveContentItem(this.contentItem):Ot(this.contentItem)&&!this.contentItem.container._contentElement[0].contains(document.activeElement)&&this.contentItem.container._contentElement.focus(),Ot(this.contentItem)&&this.contentItem.container.emit("tabClicked",e),this.header._hideAdditionalTabsDropdown(),this.element.get(0)?.scrollIntoView({inline:"nearest"})}else e.button===1&&this.contentItem.config.isClosable&&this._onCloseClick(e)}_onCloseClick(e){e.stopPropagation(),Ot(this.contentItem)?this.contentItem.container.close():this.header.parent.removeChild(this.contentItem)}_onCloseMousedown(e){e.stopPropagation()}}class Ti extends fn{static _template=['<div class="lm_header">','<ul class="lm_tabs"></ul>','<ul class="lm_controls"></ul>','<ul class="lm_tabdropdown_list">','<li class="lm_tabdropdown_search"><input type="text" placeholder="Find tab..."></li>',"</ul>","</div>"].join("");static _previousButtonTemplate=['<ul class="lm_controls">','<li class="lm_tabpreviousbutton"></li>',"</ul>"].join("");static _nextButtonTemplate=['<li class="lm_tabnextbutton"></li>'].join("");layoutManager;element=he(Ti._template);tabsContainer;tabDropdownContainer;tabDropdownSearch;tabDropdownList=null;controlsContainer;parent;tabs=[];activeContentItem=null;closeButton=null;tabDropdownButton=null;tabNextButton=he(Ti._nextButtonTemplate);tabPreviousButton=he(Ti._previousButtonTemplate);holdTimer=null;rAF=null;CLICK_TIMEOUT=500;START_SPEED=.01;ACCELERATION=5e-4;SCROLL_LEFT="left";SCROLL_RIGHT="right";isDraggingTab=!1;isOverflowing=!1;isDropdownShown=!1;dropdownKeyIndex=0;_lastVisibleTabIndex=-1;_tabControlOffset;constructor(e,t){super(),this.layoutManager=e,this.layoutManager.config.settings?.selectionEnabled&&(this.element.addClass("lm_selectable"),this.element.on("click",this._onHeaderClick.bind(this))),this.tabsContainer=this.element.find(".lm_tabs"),this.tabDropdownContainer=this.element.find(".lm_tabdropdown_list"),this.tabDropdownContainer.hide(),this.tabDropdownSearch=this.element.find(".lm_tabdropdown_search input"),this._handleFilterInput=this._handleFilterInput.bind(this),this._handleFilterKeydown=this._handleFilterKeydown.bind(this),this.tabDropdownSearch.on("input",this._handleFilterInput),this.tabDropdownSearch.on("keydown",this._handleFilterKeydown),this.controlsContainer=this.element.find(".lm_controls"),this.parent=t,this.parent.on("resize",this._updateTabSizes,this),this._handleItemPickedUp=this._handleItemPickedUp.bind(this),this._handleItemDropped=this._handleItemDropped.bind(this),this._handleNextMouseEnter=this._handleNextMouseEnter.bind(this),this._handleNextMouseLeave=this._handleNextMouseLeave.bind(this),this._handlePreviousMouseEnter=this._handlePreviousMouseEnter.bind(this),this._handlePreviousMouseLeave=this._handlePreviousMouseLeave.bind(this),this._handleScrollRepeat=this._handleScrollRepeat.bind(this),this._handleNextButtonMouseDown=this._handleNextButtonMouseDown.bind(this),this._handlePreviousButtonMouseDown=this._handlePreviousButtonMouseDown.bind(this),this._handleScrollButtonMouseDown=this._handleScrollButtonMouseDown.bind(this),this._handleScrollButtonMouseUp=this._handleScrollButtonMouseUp.bind(this),this._handleScrollEvent=this._handleScrollEvent.bind(this),this.tabNextButton.on("mousedown",this._handleNextButtonMouseDown),this.tabPreviousButton.on("mousedown",this._handlePreviousButtonMouseDown),this.tabsContainer.on("scroll",this._handleScrollEvent),this.layoutManager.on("itemPickedUp",this._handleItemPickedUp),this.layoutManager.on("itemDropped",this._handleItemDropped),this.tabsContainer.before(this.tabPreviousButton),this.tabPreviousButton=this.tabPreviousButton.find(">:first-child"),this.tabPreviousButton.hide(),this._showAdditionalTabsDropdown=this._showAdditionalTabsDropdown.bind(this),this._hideAdditionalTabsDropdown=this._hideAdditionalTabsDropdown.bind(this),this._tabControlOffset=this.layoutManager.config.settings?.tabControlOffset,this._createControls()}createTab(e,t){for(let s=0;s<this.tabs.length;s++)if(this.tabs[s].contentItem===e)return;const n=new ta(this,e);if(this.tabs.length===0){this.tabs.push(n),this.tabsContainer.append(n.element);return}t===void 0&&(t=this.tabs.length),t>0?this.tabs[t-1].element.after(n.element):this.tabs[0].element.before(n.element),this.tabs.splice(t,0,n),this._updateTabSizes()}removeTab(e){for(var t=0;t<this.tabs.length;t++)if(this.tabs[t].contentItem===e){this.tabs[t]._$destroy(),this.tabs.splice(t,1);return}throw new Error("contentItem is not controlled by this header")}setActiveContentItem(e){for(var t,n=0;n<this.tabs.length;n++)t=this.tabs[n].contentItem===e,this.tabs[n].setActive(t),t===!0&&(this.activeContentItem=e,this.parent.config.activeItemIndex=n);this.tabs[this.parent.config.activeItemIndex??0].element.get(0)?.scrollIntoView({inline:"nearest"}),this._hideAdditionalTabsDropdown(),this._updateTabSizes(),this.parent.emitBubblingEvent("stateChanged")}position(e){let t=this.parent._header.show;return t&&!this.parent._side&&(t="top"),e!==void 0&&this.parent._header.show!==e&&(this.parent._header.show=e,this.parent._setupHeaderPosition()),t}_attachWheelListener(){this.tabsContainer.get(0)?.addEventListener("wheel",this._handleWheelEvent,{passive:!0})}_detachWheelListener(){this.tabsContainer.get(0)?.removeEventListener("wheel",this._handleWheelEvent)}_handleWheelEvent(e){const t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=Math.abs(e.deltaY)>Math.abs(e.deltaX)?e.deltaY:e.deltaX;e.deltaMode===WheelEvent.DOM_DELTA_PAGE?n*=this.tabsContainer.innerWidth()??1:e.deltaMode===WheelEvent.DOM_DELTA_LINE&&(n*=100/3),t.scrollLeft+=Math.round(n)}_handleScrollEvent(){this._checkScrollArrows()}_handleItemPickedUp(){this.isDraggingTab=!0,this.controlsContainer.on("mouseenter",this._handleNextMouseEnter),this.tabPreviousButton.on("mouseenter",this._handlePreviousMouseEnter)}_handleItemDropped(){this.isDraggingTab=!1,window.cancelAnimationFrame(this.rAF??-1),this.rAF=null,this.controlsContainer.off("mouseenter",this._handleNextMouseEnter),this.controlsContainer.off("mouseleave",this._handleNextMouseLeave),this.tabPreviousButton.off("mouseenter",this._handlePreviousMouseEnter),this.tabPreviousButton.off("mouseleave",this._handlePreviousMouseLeave)}_handleNextMouseEnter(){this.controlsContainer.on("mouseleave",this._handleNextMouseLeave),this._handleScrollRepeat(this.SCROLL_RIGHT,this.tabsContainer.scrollLeft()??0)}_handlePreviousMouseEnter(){this.tabPreviousButton.on("mouseleave",this._handlePreviousMouseLeave),this._handleScrollRepeat(this.SCROLL_LEFT,this.tabsContainer.scrollLeft()??0)}_handleNextMouseLeave(){window.cancelAnimationFrame(this.rAF??-1),this.rAF=null,this.controlsContainer.off("mouseleave",this._handleNextMouseLeave)}_handlePreviousMouseLeave(){window.cancelAnimationFrame(this.rAF??-1),this.rAF=null,this.tabPreviousButton.off("mouseleave",this._handlePreviousMouseLeave)}_handleNextButtonMouseDown(){var e;for(let t=0;t<this.tabs.length;t+=1)if((this.tabs[t].element.get(0)?.offsetLeft??0)>(this.tabsContainer.get(0)?.offsetWidth??0)+(this.tabsContainer.scrollLeft()??0)){e=this.tabs[t].element.get(0);break}if(e)e.scrollIntoView({behavior:"smooth",inline:"nearest"}),this._handleScrollButtonMouseDown(this.SCROLL_RIGHT);else{const t=this.tabsContainer.get(0);t&&(t.scrollLeft=this.tabsContainer.get(0)?.scrollWidth??0)}}_handlePreviousButtonMouseDown(){for(var e,t=this.tabs.length-1;t>=0;t-=1)if((this.tabs[t].element.get(0)?.offsetLeft??0)<(this.tabsContainer.scrollLeft()??0)){e=this.tabs[t].element.get(0);break}if(e)e.scrollIntoView({behavior:"smooth",inline:"start"}),this._handleScrollButtonMouseDown(this.SCROLL_LEFT);else{const n=this.tabsContainer.get(0);n&&(n.scrollLeft=0)}}_handleScrollButtonMouseDown(e){this.holdTimer=window.setTimeout(()=>{this._handleScrollRepeat(e,this.tabsContainer.scrollLeft()??0,100)},this.CLICK_TIMEOUT),window.addEventListener("mouseup",this._handleScrollButtonMouseUp)}_handleScrollButtonMouseUp(){clearTimeout(this.holdTimer??-1),this.holdTimer=null,cancelAnimationFrame(this.rAF??-1),this.rAF=null,window.removeEventListener("mouseup",this._handleScrollButtonMouseUp)}_checkScrollArrows(){this.tabsContainer.scrollLeft()===0?this.tabPreviousButton.first().prop("disabled",!0):(this.tabsContainer.scrollLeft()??0)+(this.tabsContainer.innerWidth()??0)===this.tabsContainer.get(0)?.scrollWidth?this.tabNextButton.prop("disabled",!0):(this.tabNextButton.prop("disabled",!1),this.tabPreviousButton.first().prop("disabled",!1))}_handleScrollRepeat(e,t,n=0,s){const i=this.tabsContainer.get(0);if(!i)return;const o=i.getBoundingClientRect();if(e===this.SCROLL_LEFT){if(this.tabsContainer.scrollLeft(t-n),this.isDraggingTab&&this.parent._highlightHeaderDropZone(o.left-1),this.tabsContainer.scrollLeft()===0){this._checkScrollArrows();return}}else if(e===this.SCROLL_RIGHT&&(this.tabsContainer.scrollLeft(t+n),this.isDraggingTab&&this.parent._highlightHeaderDropZone(o.right+1),(this.tabsContainer.scrollLeft()??0)+(this.tabsContainer.innerWidth()??0)===i.scrollWidth)){this._checkScrollArrows();return}window.cancelAnimationFrame(this.rAF??-1),this.rAF=window.requestAnimationFrame(l=>{var a=s||l,d=l-a,h=this.START_SPEED*d+.5*this.ACCELERATION*(d*d);h=Math.min(h,this.tabsContainer.get(0)?.scrollWidth??1/0),this._handleScrollRepeat(e,t,h,a)})}_$setClosable(e){return this.closeButton&&this._isClosable()?(this.closeButton.element[e?"show":"hide"](),!0):!1}_$destroy(){this.emit("destroy",this);for(var e=0;e<this.tabs.length;e++)this.tabs[e]._$destroy();this._detachWheelListener(),this._handleItemDropped(),he(document).off("mouseup",this._hideAdditionalTabsDropdown),this.tabDropdownSearch.off("input",this._handleFilterInput),this.tabDropdownSearch.off("keydown",this._handleFilterKeydown),this.element.remove()}_getHeaderSetting(e){if(e in this.parent._header)return this.parent._header[e]}_createControls(){var e,t,n,s,i;if(i=this.layoutManager.config.labels.tabDropdown,this.layoutManager.config.labels.tabNextLabel,this.layoutManager.config.labels.tabPreviousLabel,this.tabDropdownButton=new qi(this,i,"lm_tabdropdown",this._showAdditionalTabsDropdown),this.tabDropdownButton.element.hide(),this.controlsContainer.prepend(this.tabNextButton),this.tabNextButton.hide(),this._getHeaderSetting("popout")&&(t=this._onPopoutClick.bind(this),n=this._getHeaderSetting("popout"),new qi(this,n,"lm_popout",t)),this._getHeaderSetting("maximise")){s=this.parent.toggleMaximise.bind(this.parent);const o=this._getHeaderSetting("maximise"),l=this._getHeaderSetting("minimise"),a=new qi(this,o,"lm_maximise",s);this.parent.on("maximised",function(){a.element.attr("title",l??"")}),this.parent.on("minimised",function(){a.element.attr("title",o??"")})}this._isClosable()&&(e=this.parent.remove.bind(this.parent),n=this._getHeaderSetting("close"),this.closeButton=new qi(this,n,"lm_close",e))}_showAdditionalTabsDropdown(){if(this.isDropdownShown){this._hideAdditionalTabsDropdown();return}this.tabDropdownList=this.tabsContainer.clone(!0).appendTo(this.tabDropdownContainer).children().removeClass("lm_active"),this.tabDropdownContainer.show(),this.isDropdownShown=!0,this.element.addClass("lm_dropdown_open"),this.tabDropdownSearch.val("").focus(),this.dropdownKeyIndex=0,this.tabDropdownList.eq(this.dropdownKeyIndex).addClass("lm_keyboard_active"),he(document).on("mousedown",this._hideAdditionalTabsDropdown),this._updateAdditionalTabsDropdown()}_handleFilterKeydown(e){if(this.dropdownKeyIndex===-1)return;if(e.key==="Escape"){this._hideAdditionalTabsDropdown();return}if(e.key==="Enter"||e.key===" "){this._hideAdditionalTabsDropdown(),this.tabs[this.dropdownKeyIndex]._onTabClick();return}function t(n,s,i){if(i==null||i.length<2)return-1;for(var o=(n+s+i.length)%i.length;o!==n;){if(i.eq(o).css("display")!=="none")return o;o=(o+s+i.length)%i.length}return n}e.key==="ArrowDown"||e.key==="Tab"&&e.shiftKey===!1?(e.preventDefault(),this.tabDropdownList?.eq(this.dropdownKeyIndex).removeClass("lm_keyboard_active"),this.dropdownKeyIndex=t(this.dropdownKeyIndex,1,this.tabDropdownList),this.tabDropdownList?.eq(this.dropdownKeyIndex).addClass("lm_keyboard_active")):(e.key==="ArrowUp"||e.key==="Tab")&&(e.preventDefault(),this.tabDropdownList?.eq(this.dropdownKeyIndex).removeClass("lm_keyboard_active"),this.dropdownKeyIndex=t(this.dropdownKeyIndex,-1,this.tabDropdownList),this.tabDropdownList?.eq(this.dropdownKeyIndex).addClass("lm_keyboard_active"))}_handleFilterInput(e){if(this.tabDropdownList!=null){this.tabDropdownList.eq(this.dropdownKeyIndex).removeClass("lm_keyboard_active"),this.dropdownKeyIndex=-1;for(var t=0;t<this.tabDropdownList.length;t++)(this.tabs[t].contentItem.config.title?.toLowerCase().indexOf(e.target.value.toLowerCase())??-1)!==-1?(this.tabDropdownList.eq(t).css("display",""),this.dropdownKeyIndex===-1&&(this.dropdownKeyIndex=t)):this.tabDropdownList.eq(t).css("display","none");this.dropdownKeyIndex!==-1&&this.tabDropdownList.eq(this.dropdownKeyIndex).addClass("lm_keyboard_active")}}_hideAdditionalTabsDropdown(e){this.isDropdownShown&&(e&&this.tabDropdownContainer.get(0)?.contains(e.target)||e&&this.tabDropdownButton?.element.get(0)===e.target||(this.element.removeClass("lm_dropdown_open"),this.tabDropdownContainer.hide(),this.isDropdownShown=!1,this.tabDropdownContainer.find(".lm_tabs").remove(),he(document).off("mousedown",this._hideAdditionalTabsDropdown)))}_updateAdditionalTabsDropdown(){this.tabDropdownContainer.css("max-height","");const e=this.tabDropdownContainer[0].scrollHeight;if(e===0)return;const t=(this.tabDropdownContainer.offset()?.top??0)-(he(window).scrollTop()??0);t+e>(he(window).height()??0)&&this.tabDropdownContainer.css("max-height",(he(window).height()??0)-t-10)}_isClosable(){return Boolean(this.parent.config.isClosable&&this.layoutManager.config.settings.showCloseIcon)}_onPopoutClick(){this.layoutManager.config.settings.popoutWholeStack===!0?this.parent.popout():this.activeContentItem?.popout()}_onHeaderClick(e){e.target===this.element[0]&&this.parent.select()}_updateTabSizes(){if(this.tabs.length===0)return;const e=this.tabsContainer.get(0);e&&(!this.isOverflowing&&e.scrollWidth>e.clientWidth?(this.tabDropdownButton?.element.show(),this.tabNextButton.show(),this.tabPreviousButton.show(),this.isOverflowing=!0):this.isOverflowing&&e.scrollWidth<=e.clientWidth&&(this.tabDropdownButton?.element.hide(),this.tabNextButton.hide(),this.tabPreviousButton.hide(),this.isOverflowing=!1),this.isOverflowing&&this._checkScrollArrows())}}class Jh{_isVertical;_size;_grabSize;_dragListener;element;constructor(e,t,n){this._isVertical=e,this._size=t,this._grabSize=n<t?t:n,this.element=this._createElement(),this._dragListener=new Co(this.element)}on(e,t,n){this._dragListener?.on(e,t,n)}_$destroy(){this._dragListener?.destroy(),this._dragListener=null,this.element.remove()}_createElement(){var e=he('<div class="lm_drag_handle"></div>'),t=he('<div class="lm_splitter"></div>');t.append(e);var n=this._grabSize-this._size,s=n/2;return this._isVertical?(e.css("top",-s),e.css("height",this._size+n),t.addClass("lm_vertical"),t.height(this._size)):(e.css("left",-s),e.css("width",this._size+n),t.addClass("lm_horizontal"),t.width(this._size)),t}}class eu{_element=he('<div class="lm_transition_indicator"></div>');_toElement=null;_fromDimensions={};_totalAnimationDuration=200;_animationStartTime=null;constructor(){he(document.body).append(this._element)}destroy(){this._element.remove()}transitionElements(e,t){}_nextAnimationFrame(){if(!this._toElement||this._animationStartTime==null)return;const e=this._measure(this._toElement),t=(Date.now()-this._animationStartTime)/this._totalAnimationDuration,n={};if(t>=1){this._element.hide();return}e.opacity=0;const s=Object.keys(this._fromDimensions);for(let i of s)n[i]=(this._fromDimensions[i]??0)+((e[i]??0)-(this._fromDimensions[i]??0))*t;this._element.css(n),Jl(this._nextAnimationFrame.bind(this))}_measure(e){const t=e.offset();return{left:t?.left,top:t?.top,width:e.outerWidth(),height:e.outerHeight()}}}const ab=Object.freeze(Object.defineProperty({__proto__:null,BrowserPopout:Yh,DragProxy:Fi,DragSource:qh,DragSourceFromEvent:Xh,DropTargetIndicator:ea,Header:Ti,HeaderButton:qi,Splitter:Jh,Tab:ta,TransitionIndicator:eu},Symbol.toStringTag,{value:"Module"})),rb={config:YC,container:qC,controls:ab,errors:ob,items:lb,utils:sb},db=rb;class tu extends fn{static __lm=db;static minifyConfig(e){return Dr(e)}static unminifyConfig(e){return Ga(e)}isInitialised=!1;_isFullPage=!1;_resizeTimeoutId;_components={"lm-react-component":zh};_fallbackComponent;_itemAreas=[];_maximisedItem=null;_maximisePlaceholder=he('<div class="lm_maximise_place"></div>');_creationTimeoutPassed=!1;_subWindowsCreated=!1;_dragSources=[];_updatingColumnsResponsive=!1;_firstLoad=!0;width=null;height=null;root;openPopouts=[];selectedItem=null;isSubWindow=!1;eventHub=new Kh(this);config;container;_originalContainer;dropTargetIndicator=null;transitionIndicator=null;tabDropPlaceholder=he('<div class="lm_drop_tab_placeholder"></div>');_typeToItem;constructor(e,t){super(),this._onResize=this._onResize.bind(this),this._onUnload=this._onUnload.bind(this),this._windowBlur=this._windowBlur.bind(this),this._windowFocus=this._windowFocus.bind(this),this.config=this._createConfig(e),this._originalContainer=t,this.container=this._getContainer(),this.isSubWindow&&he("body").css("visibility","hidden"),this._typeToItem={column:Sl.bind(this,!0),row:Sl.bind(this,!1),stack:Ya,component:Qh}}registerComponent(e,t){if(typeof t!="function"&&(t==null||t.render==null||typeof t.render!="function"))throw new Error("Please register a constructor function");if(this._components[e]!==void 0)throw new Error("Component "+e+" is already registered");return this._components[e]=t,()=>{if(this._components[e]===void 0)throw new Error("Component "+e+" is not registered");delete this._components[e]}}setFallbackComponent(e){this._fallbackComponent=e}toConfig(e){if(this.isInitialised===!1)throw new Error("Can't create config, layout not yet initialised");if(e&&!(e instanceof bt))throw new Error("Root must be a ContentItem");const t={settings:{...this.config.settings},dimensions:{...this.config.dimensions},labels:{...this.config.labels},content:[]},n=function(s,i){for(let o in i.config)o!=="content"&&(s[o]=i.config[o]);if(s.componentName==="lm-react-component"&&(s.type="react-component"),i.contentItems.length){s.content=[];for(let o=0;o<i.contentItems.length;o++)s.content[o]={},n(s.content[o],i.contentItems[o])}};e?n(t,{contentItems:[e]}):n(t,this.root),this._$reconcilePopoutWindows(),t.openPopouts=[];for(let s=0;s<this.openPopouts.length;s++)t.openPopouts.push(this.openPopouts[s].toConfig());return t.maximisedItemId=this._maximisedItem?"__glMaximised":void 0,t}getComponent(e){return this._components[e]}getFallbackComponent(){return this._fallbackComponent}init(){if(this._subWindowsCreated===!1&&(this._createSubWindows(),this._subWindowsCreated=!0),document.readyState==="loading"||document.body===null){he(document).ready(this.init.bind(this));return}if(this.isSubWindow===!0&&this._creationTimeoutPassed===!1){setTimeout(this.init.bind(this),7),this._creationTimeoutPassed=!0;return}this.isSubWindow===!0&&this._adjustToWindowMode(),this._setContainer(),this.dropTargetIndicator=new ea,this.transitionIndicator=new eu,this.updateSize(),this._create(this.config),this._bindEvents(),this.isInitialised=!0,this._adjustColumnsResponsive(),this.emit("initialised")}updateSize(e,t){this.width=e??this.container.width()??0,this.height=t??this.container.height()??0,this.isInitialised===!0&&(this.root.callDownwards("setSize",[this.width,this.height]),this._maximisedItem&&(this._maximisedItem.element.width(this.container.width()??0),this._maximisedItem.element.height(this.container.height()??0),this._maximisedItem.callDownwards("setSize")),this._adjustColumnsResponsive())}destroy(){this.isInitialised===!1||!this.root||(this._onUnload(),he(window).off("resize",this._onResize),he(window).off("unload beforeunload",this._onUnload),he(window).off("blur.lm").off("focus.lm"),this.root.callDownwards("_$destroy",[],!0),this.root.contentItems=[],this.tabDropPlaceholder.remove(),this.dropTargetIndicator?.destroy(),this.transitionIndicator?.destroy(),this.eventHub.destroy(),this._dragSources.forEach(function(e){e._dragListener.destroy()}),this._dragSources=[])}createContentItem(e,t){var n,s;if(typeof e.type!="string")throw new Gs("Missing parameter 'type'",e);if(e.type==="react-component"&&(e.type="component",e.componentName="lm-react-component"),!this._typeToItem[e.type])throw n="Unknown type '"+e.type+"'. Valid types are "+Object.keys(this._typeToItem).join(","),new Gs(n);return e.type==="component"&&!(t instanceof Ya)&&t&&!(this.isSubWindow===!0&&t instanceof Ka)&&(e={type:"stack",width:e.width,height:e.height,content:[e]}),s=new this._typeToItem[e.type](this,e,t),s}createPopout(e,t,n,s){let i=[];const o=e instanceof bt,l=this;if(o){i=this.toConfig(e).content,n=Rr();let d=e.parent,h=e;for(;d?.contentItems.length===1&&!d.isRoot;)h=d,d=d.parent;d?.addId(n),(s==null||Number.isNaN(s))&&(s=d?.contentItems.indexOf(h))}else e instanceof Array?i=e:i=[e];if(!t&&o){const d=window.screenX||window.screenLeft,h=window.screenY||window.screenTop,u=e.element.offset()??{left:0,top:0};t={left:d+u.left,top:h+u.top,width:e.element.width()??0,height:e.element.height()??0}}if(!t&&!o&&(t={left:window.screenX||window.screenLeft+20,top:window.screenY||window.screenTop+20,width:500,height:309}),o&&e.remove(),!t||!n||s===void 0)return;const a=new Yh(i,t,n,s,this);return a.on("initialised",function(){l.emit("windowOpened",a)}),a.on("closed",function(){l._$reconcilePopoutWindows()}),this.openPopouts.push(a),a}createDragSource(e,t){this.config.settings.constrainDragToContainer=!1;var n=new qh(e,t,this);return this._dragSources.push(n),n}createDragSourceFromEvent(e,t){return this.config.settings.constrainDragToContainer=!1,new Xh(e,this,t)}selectItem(e,t){if(this.config.settings.selectionEnabled!==!0)throw new Error("Please set selectionEnabled to true to use this feature");e!==this.selectedItem&&(this.selectedItem!==null&&this.selectedItem.deselect(),e&&t!==!0&&e.select(),this.selectedItem=e,this.emit("selectionChanged",e))}_$maximiseItem(e){this._maximisedItem!==null&&this._$minimiseItem(this._maximisedItem),this._maximisedItem=e,this._maximisedItem.addId("__glMaximised"),e.element.addClass("lm_maximised"),e.element.after(this._maximisePlaceholder),this.root.element.prepend(e.element),e.element.width(this.container.width()??0),e.element.height(this.container.height()??0),e.callDownwards("setSize"),this._maximisedItem.emit("maximised"),this.emit("stateChanged")}_$minimiseItem(e){e.element.removeClass("lm_maximised"),e.removeId("__glMaximised"),this._maximisePlaceholder.after(e.element),this._maximisePlaceholder.remove(),e.parent?.callDownwards("setSize"),this._maximisedItem=null,e.emit("minimised"),this.emit("stateChanged")}_$closeWindow(){window.setTimeout(function(){window.close()},1)}_$getArea(e,t){let n=1/0,s=null;for(let i=0;i<this._itemAreas.length;i++){const o=this._itemAreas[i];e>o.x1&&e<o.x2&&t>o.y1&&t<o.y2&&n>o.surface&&(n=o.surface,s=o)}return s}_$createRootItemAreas(){const t={...this.root._$getArea()},n=[{...t,side:"left",x2:t.x1+50},{...t,side:"right",x1:t.x2-50},{...t,side:"top",y2:t.y1+50},{...t,side:"bottom",y1:t.y2-50}];n.forEach(s=>{s.surface=(s.x2-s.x1)*(s.y2-s.y1)}),this._itemAreas.push(...n)}_$calculateItemAreas(){const e=this._getAllContentItems();if(this._itemAreas=[],e.length===1){this._itemAreas.push(this.root._$getArea());return}this._$createRootItemAreas();for(let t=0;t<e.length;t++){const n=e[t];if(!lo(n))continue;const s=n._$getArea();if(s!==null)if(s instanceof Array)this._itemAreas=this._itemAreas.concat(s);else{this._itemAreas.push(s);let i={...s,...s.contentItem._contentAreaDimensions?.header.highlightArea};i.surface=(i.x2-i.x1)*(i.y2-i.y1),this._itemAreas.push(i)}}}_$normalizeContentItem(e,t){if(!e)throw new Error("No content item defined");if(typeof e=="function"&&(e=e()),e instanceof bt)return e;if(he.isPlainObject(e)&&e.type){var n=this.createContentItem(e,t);return n.callDownwards("_$init"),n}else throw new Error("Invalid contentItem")}_$reconcilePopoutWindows(){const e=[];for(let t=0;t<this.openPopouts.length;t++)this.openPopouts[t].getWindow()?.closed===!1?e.push(this.openPopouts[t]):this.emit("windowClosed",this.openPopouts[t]);this.openPopouts.length!==e.length&&(this.emit("stateChanged"),this.openPopouts=e)}_getAllContentItems(){const e=[],t=n=>{if(e.push(n),n.contentItems instanceof Array)for(let s=0;s<n.contentItems.length;s++)t(n.contentItems[s])};return t(this.root),e}_bindEvents(){this._isFullPage&&he(window).resize(this._onResize),he(window).on("unload beforeunload",this._onUnload).on("blur.lm",this._windowBlur).on("focus.lm",this._windowFocus)}_windowBlur(){this.root.element.addClass("lm_window_blur")}_windowFocus(){this.root.element.removeClass("lm_window_blur")}_onResize(){clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=window.setTimeout(this.updateSize.bind(this),100)}_createConfig(e){var t=Gh("gl-window");t&&(this.isSubWindow=!0,e=JSON.parse(localStorage.getItem(t)||"{}"),e=Ga(e),localStorage.removeItem(t)),e=he.extend(!0,{},Uh,e);var n=function(s){for(var i in s){const o=s[i];i!=="props"&&typeof o=="object"&&o!=null?n(o):i==="type"&&o==="react-component"&&(s.type="component",s.componentName="lm-react-component")}};return n(e),e.settings?.hasHeaders===!1&&(e.dimensions.headerHeight=0),e}_adjustToWindowMode(){var e=he('<div class="lm_popin" title="'+this.config.labels.popin+'"><div class="lm_icon"></div><div class="lm_bg"></div></div>');e.click(()=>{this.emit("popIn")}),document.title=xr(this.config.content[0].title??""),he("head").append(he("body link, body style, template, .gl_keep")),this.container=he("body").html("").css("visibility","visible").append(e),document.body.offsetHeight,window.__glInstance=this}_createSubWindows(){if(this.config.openPopouts)for(let e=0;e<this.config.openPopouts.length;e++){const t=this.config.openPopouts[e];this.createPopout(t.content,t.dimensions,t.parentId,t.indexInParent)}}_getContainer(){const e=this._originalContainer?he(this._originalContainer):he("body");if(e.length===0)throw new Error("GoldenLayout container not found");if(e.length>1)throw new Error("GoldenLayout more than one container element specified");return e}_setContainer(){const e=this._getContainer();e[0]===document.body&&(this._isFullPage=!0,he("html, body").css({height:"100%",margin:0,padding:0,overflow:"hidden"})),this.container=e}_create(e){var t;if(!(e.content instanceof Array))throw e.content===void 0?t="Missing setting 'content' on top level of configuration":t="Configuration parameter 'content' must be an array",new Gs(t,e);if(e.content.length>1)throw t="Top level content can't contain more then one element.",new Gs(t,e);this.root=new Ka(this,{content:e.content},this.container),this.root.callDownwards("_$init"),e.maximisedItemId==="__glMaximised"&&this.root.getItemsById(e.maximisedItemId)[0].toggleMaximise()}_onUnload(){if(this.config.settings.closePopoutsOnUnload===!0)for(var e=0;e<this.openPopouts.length;e++)this.openPopouts[e].close()}_adjustColumnsResponsive(){if(!this._useResponsiveLayout()||this._updatingColumnsResponsive||!this.config.dimensions||!this.config.dimensions.minItemWidth||this.root.contentItems.length===0||!this.root.contentItems[0].isRow){this._firstLoad=!1;return}this._firstLoad=!1;var e=this.root.contentItems[0].contentItems.length;if(!(e<=1)){var t=this.config.dimensions.minItemWidth,n=e*t;if(!(this.width==null||n<=this.width)){this._updatingColumnsResponsive=!0;for(var s=Math.max(Math.floor(this.width/t),1),i=e-s,o=this.root.contentItems[0],l=this._findAllStackContainers()[0],a=0;a<i;a++){var d=o.contentItems[o.contentItems.length-1];this._addChildContentItemsToContainer(l,d)}this._updatingColumnsResponsive=!1}}}_useResponsiveLayout(){return this.config.settings&&(this.config.settings.responsiveMode=="always"||this.config.settings.responsiveMode=="onload"&&this._firstLoad)}_addChildContentItemsToContainer(e,t){t.type==="stack"?t.contentItems.forEach(function(n){e.addChild(n),t.removeChild(n,!0)}):t.contentItems.forEach(n=>{this._addChildContentItemsToContainer(e,n)})}_findAllStackContainers(){const e=[];return this._findAllStackContainersRecursive(e,this.root),e}_findAllStackContainersRecursive(e,t){t.contentItems.forEach(n=>{lo(n)?e.push(n):n.isComponent||this._findAllStackContainersRecursive(e,n)})}}const cb="_lm_root_15d73_3",hb="_lm_row_15d73_7",ub="_lm_item_15d73_7",mb="_lm_content_15d73_11",gb="_lm_dragging_15d73_17",pb="_lm_maximised_15d73_23",fb="_lm_maximise_placeholder_15d73_30",Cb="_lm_splitter_15d73_34",bb="_lm_vertical_15d73_41",Sb="_lm_drag_handle_15d73_41",wb="_lm_horizontal_15d73_46",vb="_lm_header_15d73_56",Tb="_lm_dropdown_open_15d73_63",Eb="_lm_controls_15d73_69",yb="_lm_tabs_15d73_89",Rb="_lm_tab_15d73_89",xb="_lm_title_15d73_104",Db="_lm_close_tab_15d73_111",Ib="_lm_stack_15d73_120",Fb="_lm_left_15d73_120",Nb="_lm_right_15d73_121",kb="_lm_dragProxy_15d73_125",Mb="_lm_items_15d73_148",Lb="_lm_tabdropdown_list_15d73_165",Ob="_lm_bottom_15d73_192",Ab="_lm_drop_tab_placeholder_15d73_207",_b="_lm_tabdropdown_15d73_165",Pb="_lm_dropTargetIndicator_15d73_258",jb="_lm_inner_15d73_264",Hb="_lm_transition_indicator_15d73_272",Bb="_lm_popin_15d73_282",Ub="_lm_bg_15d73_297",Vb="_lm_icon_15d73_300",$b="_lm_goldenlayout_15d73_304",Wb="_lm_selectable_15d73_340",Gb="_lm_active_15d73_370",zb="_lm_selected_15d73_388",Kb="_lm_keyboard_active_15d73_397",Yb="_lm_popout_15d73_416",qb="_lm_maximise_15d73_23",Xb="_lm_close_15d73_111",Zb="_lm_tabnextbutton_15d73_425",Qb="_lm_tabpreviousbutton_15d73_428",Jb="_lm_title_before_15d73_544",eS="_lm_focusin_15d73_568",tS="_lm_window_blur_15d73_573",nS="_lm_tabdropdown_search_15d73_631",sS="_march_15d73_1",iS="_app_15d73_712",oS="_plotly_15d73_721",Ud={"tab-height":"28px","drag-border-width":"5px",lm_root:cb,lm_row:hb,lm_item:ub,lm_content:mb,lm_dragging:gb,lm_maximised:pb,lm_maximise_placeholder:fb,lm_splitter:Cb,lm_vertical:bb,lm_drag_handle:Sb,lm_horizontal:wb,lm_header:vb,lm_dropdown_open:Tb,lm_controls:Eb,lm_tabs:yb,lm_tab:Rb,lm_title:xb,lm_close_tab:Db,lm_stack:Ib,lm_left:Fb,lm_right:Nb,lm_dragProxy:kb,lm_items:Mb,lm_tabdropdown_list:Lb,lm_bottom:Ob,lm_drop_tab_placeholder:Ab,lm_tabdropdown:_b,lm_dropTargetIndicator:Pb,lm_inner:jb,lm_transition_indicator:Hb,lm_popin:Bb,lm_bg:Ub,lm_icon:Vb,lm_goldenlayout:$b,lm_selectable:Wb,lm_active:Gb,lm_selected:zb,lm_keyboard_active:Kb,lm_popout:Yb,lm_maximise:qb,lm_close:Xb,lm_tabnextbutton:Zb,lm_tabpreviousbutton:Qb,lm_title_before:Jb,"editor-unsaved-indicator":"_editor-unsaved-indicator_15d73_548","is-unsaved":"_is-unsaved_15d73_556",lm_focusin:eS,lm_window_blur:tS,lm_tabdropdown_search:nS,march:sS,app:iS,"js-plotly-plot":"_js-plotly-plot_15d73_721",plotly:oS},Vd=Object.freeze({tabHeight:parseInt(Ud["tab-height"],10),dragBorderWidth:parseInt(Ud["drag-border-width"],10)}),ss=ne.module("LayoutUtils");function nu(c){return c.componentName!==void 0}function pi(c){const e=c;return(nu(c)&&c.componentName==="lm-react-component"||c.type==="react-component")&&e.component!==void 0}function jo(c){return c.focus!==void 0}function $d(c){return c.type==="stack"}class K{static DEFAULT_FOCUS_SELECTOR="input, select, textarea, button";static activateTab(e,t){const n=K.getStackForRoot(e,t,!1);if(!n){ss.error("Could not find stack for config",t);return}const s=K.getContentItemInStack(n,t);s&&n.setActiveContentItem(s)}static isActiveTab(e,t){const n=K.getStackForRoot(e,t,!1);if(!n)return ss.error("Could not find stack for config",t),!1;const s=K.getContentItemInStack(n,t);return n.getActiveContentItem()===s}static addStack(e,t=!0){const n=t?"column":"row";if(Zh(e)){(e.contentItems==null||e.contentItems.length===0)&&e.addChild({type:n});const o=e.contentItems[0];if(!(t?o.isColumn:o.isRow)){e.removeChild(o,!0),e.addChild({type:n});const a=document.activeElement;e.contentItems[0].addChild(o),a&&a.focus!=null&&a.focus()}return this.addStack(e.contentItems[0],t)}if(e.contentItems.length<2)return e.addChild({type:"stack"}),e.contentItems[e.contentItems.length-1];let s=e.contentItems[e.contentItems.length-1];return(t?s.isRow:s.isColumn)||(e.addChild({type:t?"row":"column"}),e.removeChild(s,!0),e.contentItems[e.contentItems.length-1].addChild(s),s=e.contentItems[e.contentItems.length-1]),this.addStack(s,!t)}static getStackForConfig(e,t={},n=!1){if(n&&lo(e)&&e.contentItems.length===0)return e;if(e.contentItems==null)return null;for(let s=0;s<e.contentItems.length;s+=1){const i=e.contentItems[s];if(i.isComponent&&i.config!=null&&rd(i.config,t))return e;const o=this.getStackForConfig(i,t,n);if(o)return o}return null}static getStackForRoot(e,t,n=!0,s=!0,i=!0){let o=this.getStackForConfig(e,t);return!o&&s&&(o=this.getStackForConfig(e,{component:t.component},i)),!o&&n&&(o=this.addStack(e)),o}static getStackForComponentTypes(e,t,n=!0,s=!0,i=!0){for(let o=0;o<t.length;o+=1){const l=t[o],a=o===t.length-1,d=K.getStackForRoot(e,{component:l},n&&a,s,i);if(d)return d}return null}static getContentItemInStack(e,t){if(!e)return null;for(let n=0;n<e.contentItems.length;n+=1){const s=e.contentItems[n];if(s.isComponent&&s.config!=null&&rd(s.config,t))return s}return null}static dehydrateLayoutConfig(e,t){if(e==null||!e.length)return[];const n=[];for(let s=0;s<e.length;s+=1){const i=e[s],{component:o,content:l}=i;if(o){const a=t(o,i);a!=null?n.push(a):ss.debug2(`dehydrateLayoutConfig: skipping unmapped component "${o}"`)}else if(l){const a={...i,content:K.dehydrateLayoutConfig(l,t)};n.push(a)}else n.push(i)}return n}static getTabPoint(e){const{tab:t}=e;if(t==null)throw new Error(`Cannot get tab for panel container ${e}`);const n=t.element[0].getBoundingClientRect();return[n.left+n.width*.5,n.bottom-8]}static dropLayoutMinorChange(e){for(let t=0;t<e.length;t+=1){const n=e[t],{content:s}=n;s!==void 0?($d(n)&&delete n.activeItemIndex,K.dropLayoutMinorChange(s)):pi(n)&&n.component==="IrisGridPanel"&&n.props.panelState!=null&&(delete n.id,n.props.panelState.irisGridState.sorts=[],n.props.panelState.irisGridState.quickFilters=[])}}static isEqual(e,t,n=!1){if(n){const s=K.cloneLayout(e),i=K.cloneLayout(t);return K.dropLayoutMinorChange(s),K.dropLayoutMinorChange(i),st(s,i)}return st(e,t)}static cloneLayout(e){return JSON.parse(JSON.stringify(e))}static hydrateLayoutConfig(e,t){if(e==null||!e.length)return[];const n=[];for(let s=0;s<e.length;s+=1){const i=e[s];if(pi(i)){const{component:o,props:l={}}=i;n.push({...i,id:i?.id??qe(),props:t(o,l)})}else if(i.content!==void 0){const o=K.hydrateLayoutConfig(i.content,t);$d(i)&&i.activeItemIndex!=null&&i.activeItemIndex>=o.length&&(ss.warn("Fixing bad activeItemIndex!",i.activeItemIndex,i),i.activeItemIndex=0),n.push({...i,content:o})}else n.push(i)}return n}static openComponent({root:e,config:t,replaceExisting:n=!0,replaceConfig:s=void 0,createNewStack:i=!1,focusElement:o=void 0,dragEvent:l=void 0}={}){const a=document.activeElement,d={...t};if(d.id==null&&(d.id=qe.generate()),l){e?.layoutManager.createDragSourceFromEvent(d,l);return}const h=s||{id:d.id,component:d.component};N(e);const u=i?K.addStack(e):K.getStackForRoot(e,h);N(u);const m=K.getContentItemInStack(u,h);if(o!=null){const g=p=>{ss.debug("Component created, focusing element",o),u.off("componentCreated",g);const{element:C}=p.origin;requestAnimationFrame(()=>{K.focusElement(C[0],o)})};u.on("componentCreated",g)}if(n&&m){const g=u.contentItems.indexOf(m);u.addChild(d,g+1),u.removeChild(m),u.setActiveContentItem(u.contentItems[g])}else u.addChild(d);o==null&&a&&jo(a)&&a.focus()}static openComponentInStack(e,t,n=!0){const s=document.activeElement,i={id:t.id},o=K.getContentItemInStack(e,i);if(n&&o&&e){const l=e?.contentItems.indexOf(o);e.addChild(t,l+1),e.removeChild(o),e.setActiveContentItem(e.contentItems[l])}else e?.addChild(t);s&&jo(s)&&s.focus()}static closeComponent(e,t,n){const s=K.getStackForRoot(e,t,!1,!1,!1);if(!s){ss.warn("Cannot find stack for component, ignoring close",t);return}const i=K.getContentItemInStack(s,t),o=document.activeElement;i&&(Ot(i)?i.container.close(n):s.removeChild(i)),o&&document.contains(o)&&jo(o)&&o.focus()}static renameComponent(e,t,n){const s=K.getStackForRoot(e,t,!1);if(!s){ss.error("Could not find stack for config",t);return}const i=K.getContentItemInStack(s,t);i&&i.setTitle(n)}static cloneComponent(e,t){const n=K.getStackForRoot(e,t,!1);if(!n)return ss.error("Could not find stack for config",t),null;const{props:s={}}=t,i=K.getPanelComponentState(t),o={type:"react-component",component:t.component,props:{...s,panelState:i},title:`${t.title} Copy`,id:qe.generate()};return K.openComponentInStack(n,o),o}static getPanelComponentState(e){return nu(e)?e.componentState?.panelState:pi(e)?e.props?.panelState:null}static makeDefaultLayout(){return{dimensions:{headerHeight:Vd.tabHeight,borderWidth:Vd.dragBorderWidth,borderGrabWidth:10},settings:{showPopoutIcon:!1,showCloseIcon:!1,constrainDragToContainer:!1}}}static getRootFromContainer(e){return e.layoutManager.root}static getComponentConfigFromContainer(e){return e?e.tab!=null&&e.tab.contentItem!=null?e.tab.contentItem.config:e._config:null}static getTitleFromContainer(e){return e!=null&&e.tab!=null&&e.tab.contentItem!=null?e.tab.contentItem.config.title:null}static getTitleFromTab(e){return e!=null&&e.contentItem!=null?e.contentItem.config.title:null}static getIdFromContainer(e){const t=K.getComponentConfigFromContainer(e);return t?t.id:null}static getIdFromPanel(e){const{glContainer:t}=e.props;return K.getIdFromContainer(t)}static getComponentNameFromPanel(e){const{glContainer:t}=e.props,n=K.getComponentConfigFromContainer(t);return n&&pi(n)?n.component??null:null}static getComponentName(e){const t=e.WrappedComponent?.displayName??e.displayName;if(t==null)throw new Error(`Component displayName not defined ${e}`);return t}static focusElement(e,t=K.DEFAULT_FOCUS_SELECTOR){if(e==null)return null;const n=e.querySelector(t);return n==null?null:(jo(n)&&n.focus(),n)}static onInitialized(e){return new Promise(t=>{if(e.isInitialised){t();return}const n=()=>{e.off("initialised",n),t()};e.on("initialised",n)})}}const su=de.forwardRef((c,e)=>{const t=K.getComponentNameFromPanel({props:c});return r.jsxs("div",{ref:e,className:"panel-placeholder",children:['Component "',t,'" is not registered.']})});su.displayName="PanelPlaceholder";const Ee=Object.freeze({FOCUS:"PanelEvent.FOCUS",MOUNT:"PanelEvent.MOUNT",UNMOUNT:"PanelEvent.UNMOUNT",TITLE_CHANGED:"PanelEvent.TITLE_CHANGED",REOPEN:"PanelEvent.REOPEN",DELETE:"PanelEvent.DELETE",CLONED:"PanelEvent.CLONED",CLOSED:"PanelEvent.CLOSED",OPEN:"PanelEvent.OPEN",CLOSE:"PanelEvent.CLOSE",DRAGGING:"PanelEvent.DRAGGING",DROPPED:"PanelEvent.DROPPED"});function Wd(c){return c?.WrappedComponent!==void 0}function lS(c){return typeof c.id=="string"&&c.layout instanceof tu&&c.panelManager instanceof iu&&typeof c.registerComponent=="function"}function ys(c){if(!lS(c))throw new Error(`Expected dashboard plugin props, but instead received ${c}`)}const Xt=ne.module("PanelManager");class iu{static MAX_CLOSED_PANEL_COUNT=100;layout;hydrateComponent;dehydrateComponent;onPanelsUpdated;closed;openedMap;constructor(e,t=(l,a)=>a,n=(l,a)=>a,s=new Map,i=[],o=()=>{}){this.handleFocus=this.handleFocus.bind(this),this.handleMount=this.handleMount.bind(this),this.handleUnmount=this.handleUnmount.bind(this),this.handleReopen=this.handleReopen.bind(this),this.handleDeleted=this.handleDeleted.bind(this),this.handleClosed=this.handleClosed.bind(this),this.handleControlClose=this.handleControlClose.bind(this),this.layout=e,this.hydrateComponent=t,this.dehydrateComponent=n,this.onPanelsUpdated=o,this.openedMap=new Map(s),this.closed=[...i],this.startListening()}startListening(){const{eventHub:e}=this.layout;e.on(Ee.FOCUS,this.handleFocus),e.on(Ee.MOUNT,this.handleMount),e.on(Ee.UNMOUNT,this.handleUnmount),e.on(Ee.REOPEN,this.handleReopen),e.on(Ee.DELETE,this.handleDeleted),e.on(Ee.CLOSED,this.handleClosed),e.on(Ee.CLOSE,this.handleControlClose)}stopListening(){const{eventHub:e}=this.layout;e.off(Ee.FOCUS,this.handleFocus),e.off(Ee.MOUNT,this.handleMount),e.off(Ee.UNMOUNT,this.handleUnmount),e.off(Ee.REOPEN,this.handleReopen),e.off(Ee.DELETE,this.handleDeleted),e.off(Ee.CLOSED,this.handleClosed),e.off(Ee.CLOSE,this.handleControlClose)}getClosedPanelConfigsOfType(e){return this.closed.filter(t=>t.component===e)}getOpenedPanels(){return Array.from(this.openedMap.values())}getOpenedPanelConfigs(){return this.getOpenedPanels().map(e=>{const{glContainer:t}=e.props;return K.getComponentConfigFromContainer(t)})}getOpenedPanelConfigsOfType(e){return this.getOpenedPanelConfigs().filter(t=>t!=null&&pi(t)&&t.component===e)}getOpenedPanelById(e){return this.openedMap.get(e)}getContainerByPanelId(e){const t=K.getStackForConfig(this.layout.root,{id:e});return(t&&K.getContentItemInStack(t,{id:e}))??null}getLastUsedPanel(e){const t=this.getOpenedPanels();for(let n=t.length-1;n>=0;n-=1){const s=t[n];if(e==null||e(s))return s}}getLastUsedPanelOfType(e){return this.getLastUsedPanelOfTypes([e])}getLastUsedPanelOfTypes(e){return this.getLastUsedPanel(t=>e.some(n=>Wd(n)&&t instanceof n.WrappedComponent||!Wd(n)&&t instanceof n))}updatePanel(e){const t=K.getIdFromPanel(e);if(t==null){Xt.error("updatePanel Panel did not have an ID",e);return}Xt.debug2(`Updating panel ID ${t} in open panels map`),this.openedMap.delete(t),this.openedMap.set(t,e)}removePanel(e){const t=K.getIdFromPanel(e);if(t==null){Xt.error("removePanel Panel did not have an ID",e);return}if(!this.openedMap.has(t)){Xt.error(`Missing panel ID ${t} in open panels map`);return}if(this.openedMap.get(t)!==e){Xt.debug(`Panel argument doesn't match the open panels map entry for ${t}, removePanel ignored`);return}Xt.debug2(`Removing panel ID ${t} from open panels map`),this.openedMap.delete(t)}removeClosedPanelConfig(e){const t=this.closed.findIndex(n=>n===e||n.id!=null&&e.id!=null&&n.id===e.id);t>=0&&this.closed.splice(t,1)}handleFocus(e){Xt.debug2("Focus: ",e),this.updatePanel(e)}handleMount(e){Xt.debug2("Mount: ",e),this.updatePanel(e),this.sendUpdate()}handleUnmount(e){Xt.debug2("Unmount: ",e),this.removePanel(e),this.sendUpdate()}handleReopen(e,t){Xt.debug2("Reopen:",e,t),this.removeClosedPanelConfig(e);const{component:n}=e;let{props:s}=e;s=this.hydrateComponent(n,s);const i={...e,props:s},{root:o}=this.layout;K.openComponent({root:o,config:i,replaceConfig:t})}handleDeleted(e){Xt.debug2("Deleted:",e),this.removeClosedPanelConfig(e),this.sendUpdate()}handleClosed(e,t){Xt.debug2("Closed: ",e),this.addClosedPanel(t),this.sendUpdate()}handleControlClose(e){const t={id:e},{root:n}=this.layout;K.closeComponent(n,t)}addClosedPanel(e){const t=K.getComponentConfigFromContainer(e);if(t&&pi(t)){const n=this.dehydrateComponent(t.component,t);n!=null&&this.closed.push(n)}}sendUpdate(){const{closed:e,openedMap:t}=this;this.onPanelsUpdated({closed:[...e],openedMap:new Map(t)})}}const aS=ne.module("PanelErrorBoundary");class rS extends v.Component{constructor(e){super(e),this.state={error:null}}componentDidCatch(e){this.setState({error:e})}componentWillUnmount(){const{glContainer:e,glEventHub:t}=this.props,n=K.getIdFromContainer(e);aS.debug("componentWillUnmount",n),t.emit(Ee.CLOSED,n,e)}render(){const{children:e}=this.props,{error:t}=this.state;return t!=null?r.jsx("div",{className:"panel-error-boundary",children:r.jsx($l,{errorMessage:`${t}`,isLoading:!1,isLoaded:!1})}):e}}function Fr(c){const{props:e,componentState:t}=c,{metadata:n}=e;let{panelState:s=null}=e;t&&({panelState:s}=t);const i={};return n!=null&&(i.metadata=n),s!=null&&(i.panelState=s),{...c,componentState:null,props:i,type:"react-component"}}function Nr(c,e=""){return{metadata:{},...c,localDashboardId:e}}const qa={dehydrate:Fr,hydrate:Nr},dS=z.shape({on:z.func,off:z.func,isHidden:z.bool,tab:z.shape({header:z.shape({tabs:z.arrayOf(z.shape({contentItem:z.shape({})}))})}),title:z.string,setTitle:z.func,close:z.func}),ou=z.shape({on:z.func,off:z.func,emit:z.func}),cS=z.shape({registerComponent:z.func,root:z.shape({addChild:z.func}),on:z.func,off:z.func,eventHub:ou}),kr=Object.freeze({Container:dS,EventHub:ou,Layout:cS}),Ve=(c,e,t)=>v.useEffect(function(){return c.on(e,t),()=>{c.off(e,t)}},[c,e,t]),lu="SET_DASHBOARD_DATA",hS=xC(lu,{},!1),uS={dashboardData:hS},mS=new Map,gS=Object.freeze({}),pS=Object.freeze([]),fS=c=>c.dashboardData,jt=(c,e)=>fS(c)[e]??gS,CS=(c,e)=>jt(c,e).closed??pS,au=(c,e)=>jt(c,e).openedMap??mS,ru=(c,e)=>({type:lu,id:c,payload:e}),Fn=(c,e)=>(t,n)=>t(ru(c,{...jt(n(),c),...e}));Object.entries(uS).map(([c,e])=>fo.register(c,e));const Ho=ne.module("DashboardLayout"),bS=Object.freeze({}),SS=[],Gd=()=>{},zd=c=>c;function du({id:c,children:e,emptyDashboard:t=r.jsx("div",{children:"Dashboard is empty."}),layout:n,layoutConfig:s=SS,onLayoutChange:i=Gd,onLayoutInitialized:o=Gd,hydrate:l=Nr,dehydrate:a=Fr}){const d=ir(),h=rm(j=>jt(j,c))??bS,[u,m]=v.useState(!1),[g,p]=v.useState(!1),[C,f]=v.useState(),[b]=v.useState(h?.closed??[]),[w,S]=v.useState(!1),T=v.useMemo(()=>new Map,[]),y=v.useMemo(()=>new Map,[]),E=dm(),R=v.useCallback((j,P,Q=l,$=a)=>{Ho.debug2("registerComponent",j,P,Q,$);function J(q,Z){const le=P,{glContainer:G,glEventHub:oe}=q;return r.jsx(Bc,{store:E,children:r.jsx(rS,{glContainer:G,glEventHub:oe,children:r.jsx(le,{...q,ref:Z})})})}const A=de.forwardRef(J),W=n.registerComponent(j,A);return T.set(j,Q),y.set(j,$),W},[l,a,T,y,n,E]),x=v.useCallback((j,P)=>(T.get(j)??zd)(P,c),[T,c]),D=v.useCallback((j,P)=>(y.get(j)??zd)(P,c),[y,c]),M=v.useMemo(()=>new iu(n,x,D,new Map,b,({closed:j,openedMap:P})=>{d(Fn(c,{closed:j,openedMap:P}))}),[D,d,x,c,b,n]),O=v.useCallback(()=>{if(g)return;w||(o(),S(!0));const P=n.toConfig().content,Q=K.dehydrateLayoutConfig(P,D),$=C==null||!K.isEqual(C,Q);Ho.debug("handleLayoutStateChanged",$,P,Q),$&&(m(n.root.contentItems.length===0),f(Q),i(Q))},[D,w,g,C,n,i,o]),H=v.useCallback(j=>{const P=K.getIdFromContainer(j);n.eventHub.emit(Ee.DRAGGING,P),p(!0)},[n.eventHub]),L=v.useCallback(j=>{const P=K.getIdFromContainer(j);n.eventHub.emit(Ee.DROPPED,P),p(!1)},[n.eventHub]),V=v.useCallback(j=>{if(Ho.debug2("handleComponentCreated",j),j==null||j.config==null||j.config.component==null||j.element==null)return;const Q=`${j.config.component.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}-component`;j.element.addClass(Q)},[]);Ve(n,"stateChanged",O),Ve(n,"itemPickedUp",H),Ve(n,"itemDropped",L),Ve(n,"componentCreated",V),Ve(n.eventHub,Ee.TITLE_CHANGED,O);const U=lr(s);return v.useEffect(function(){if(U!==s&&s!==C){Ho.debug("Setting new layout content...");const P=K.hydrateLayoutConfig(s,x);for(;n.root.contentItems.length>0;)n.root.contentItems[0].remove();for(let Q=0;Q<P.length;Q+=1)n.root.addChild(P[Q]);m(n.root.contentItems.length===0)}},[x,n,s,C,M,U]),r.jsxs(r.Fragment,{children:[u&&t,de.Children.map(e,j=>j!=null?de.cloneElement(j,{id:c,layout:n,panelManager:M,registerComponent:R}):null)]})}du.propTypes={id:z.string.isRequired,children:z.node,data:z.shape({}),emptyDashboard:z.node,layout:kr.Layout.isRequired,layoutConfig:z.arrayOf(z.shape({})),onLayoutChange:z.func,onLayoutInitialized:z.func};const wS=100,wa=()=>{},vS=Object.freeze({});function TS({id:c="default",children:e,emptyDashboard:t,layoutConfig:n,layoutSettings:s=vS,onLayoutConfigChange:i=wa,onGoldenLayoutChange:o=wa,onLayoutInitialized:l=wa,fallbackComponent:a=su,hydrate:d,dehydrate:h}){const u=v.useRef(null),[m,g]=v.useState(!1),[p,C]=v.useState();v.useEffect(function(){if(!u.current){C(void 0);return}const w={...K.makeDefaultLayout()};w.settings===void 0&&(w.settings={}),Object.assign(w.settings,s),w.content=[];const S=new tu(w,u.current),T=()=>{S.off("initialised",T),g(!0)};return S.on("initialised",T),a!=null&&S.setFallbackComponent(a),S.init(),C(S),o(S),()=>{S.destroy()}},[s,a,o,g,C]);const f=v.useMemo(()=>vs(()=>{p!=null&&p.isInitialised&&p?.updateSize()},wS),[p]);return v.useEffect(function(){return window.addEventListener("resize",f),()=>{window.removeEventListener("resize",f)}},[f]),r.jsxs("div",{className:"dashboard-container w-100 h-100",children:[r.jsx("div",{className:"w-100 h-100",ref:u}),m&&p&&r.jsx(du,{emptyDashboard:t,id:c,layout:p,layoutConfig:n,onLayoutChange:i,onLayoutInitialized:l,hydrate:d,dehydrate:h,children:e})]})}const un="default";class ES extends Error{isAssertionFailed=!0}const cu=ES;function Kd(c){if(c==null)throw new cu(`Expected 'val' to be defined, but received ${c}`)}class yS extends Error{isPasteError=!0}const va=yS;function Xe(c){return c?.isEditable!==void 0}function Yd(c){if(!Xe(c))throw new cu(`Expected 'model' to be editable, but received ${c}`)}function je(c){return c?.hasExpandableRows!==void 0}var mn=(c=>(c.DOWN="DOWN",c.UP="UP",c.LEFT="LEFT",c.RIGHT="RIGHT",c))(mn||{});class te{startColumn;startRow;endColumn;endRow;static SELECTION_DIRECTION=mn;static normalize(e,t,n,s){let i=e,o=t,l=n,a=s;return i!=null&&l!=null&&l<i&&(i=l,l=e),o!=null&&a!=null&&a<o&&(o=a,a=t),[i,o,l,a]}static makeNormalized(e,t,n,s){return new te(...te.normalize(e,t,n,s))}static makeCell(e,t){return new te(e,t,e,t)}static makeColumn(e){return new te(e,null,e,null)}static makeRow(e){return new te(null,e,null,e)}static minOrNull(e,t){return e==null||t==null?null:Math.min(e,t)}static maxOrNull(e,t){return e==null||t==null?null:Math.max(e,t)}static consolidate(e){const t=e.slice();let n=!0;for(;n;){n=!1;for(let s=0;s<t.length&&!n;s+=1){const i=t[s];for(let o=t.length-1;o>s;o-=1){const l=t[o];if(i.contains(l))t.splice(o,1);else if(l.contains(i)){n=!0,t[s]=l,t.splice(o,1);break}else if(i.startRow===l.startRow&&i.endRow===l.endRow){if(i.touches(l)){const{startRow:a,endRow:d}=i,h=te.minOrNull(i.startColumn,l.startColumn),u=te.maxOrNull(i.endColumn,l.endColumn);n=!0,t[s]=new te(h,a,u,d),t.splice(o,1);break}}else if(i.startColumn===l.startColumn&&i.endColumn===l.endColumn&&i.touches(l)){const{startColumn:a,endColumn:d}=i,h=te.minOrNull(i.startRow,l.startRow),u=te.maxOrNull(i.endRow,l.endRow);n=!0,t[s]=new te(a,h,d,u),t.splice(o,1);break}}}}return t}static isAxisRangeTouching(e,t,n,s){return e==null?t==null||n==null?!0:n<=t+1:t==null?s==null?!0:s>=e-1:n==null?s==null?!0:e<=s+1:s==null?t>=n-1:n>=e-1?n<=t+1:s>=e-1}static rangeArraysEqual(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!e[n].equals(t[n]))return!1;return!0}static intersection(e,t){if(e.equals(t))return e;let{startColumn:n,startRow:s,endColumn:i,endRow:o}=e;return n=n!=null&&t.startColumn!=null?Math.max(n,t.startColumn):n??t.startColumn,i=i!=null&&t.endColumn!=null?Math.min(i,t.endColumn):i??t.endColumn,s=s!=null&&t.startRow!=null?Math.max(s,t.startRow):s??t.startRow,o=o!=null&&t.endRow!=null?Math.min(o,t.endRow):o??t.endRow,n!=null&&n>(i??-1)||s!=null&&s>(o??-1)?null:new te(n,s,i,o)}static subtractFromRange(e,t){const n=[],s=te.intersection(e,t);return s==null?[e]:(s.startRow!=null&&(e.startRow==null||e.startRow<s.startRow)&&n.push(new te(e.startColumn,e.startRow,e.endColumn,s.startRow-1)),s.startColumn!=null&&(e.startColumn==null||e.startColumn<s.startColumn)&&n.push(new te(e.startColumn,s.startRow,s.startColumn-1,s.endRow)),s.endColumn!=null&&(e.endColumn==null||e.endColumn>s.endColumn)&&n.push(new te(s.endColumn+1,s.startRow,e.endColumn,s.endRow)),s.endRow!=null&&(e.endRow==null||e.endRow>s.endRow)&&n.push(new te(e.startColumn,s.endRow+1,e.endColumn,e.endRow)),n)}static subtractFromRanges(e,t){const n=[];for(let s=0;s<e.length;s+=1)n.push(...te.subtractFromRange(e[s],t));return n}static subtractRangesFromRanges(e,t){let n=[...e];for(let s=0;s<t.length;s+=1)n=te.subtractFromRanges(n,t[s]);return n}static isBounded(e){return e.startRow!=null&&e.startColumn!=null&&e.endRow!=null&&e.endColumn!=null}static boundedRange(e,t,n){return te.isBounded(e)?e:new te(e.startColumn??0,e.startRow??0,e.endColumn??t-1,e.endRow??n-1)}static boundedRanges(e,t,n){return e.map(s=>te.boundedRange(s,t,n))}static offset(e,t,n){return new te(e.startColumn!=null?e.startColumn+t:null,e.startRow!=null?e.startRow+n:null,e.endColumn!=null?e.endColumn+t:null,e.endRow!=null?e.endRow+n:null)}static nextCell(e,t=null,n=null,s=te.SELECTION_DIRECTION.DOWN){if(e.length===0)return null;let i=-1;if(t!=null&&n!=null&&(i=e.findIndex(o=>o.containsCell(t,n)),i>=0)){const l=e[i].nextCell(t,n,s);if(l!=null)return l}switch(s){case te.SELECTION_DIRECTION.DOWN:case te.SELECTION_DIRECTION.RIGHT:{const o=i<e.length-1?i+1:0;return e[o].startCell(s)}case te.SELECTION_DIRECTION.LEFT:case te.SELECTION_DIRECTION.UP:{const o=i>0?i-1:e.length-1;return e[o].startCell(s)}default:throw new Error(`Invalid direction: ${s}`)}}static cellCount(e){return e.reduce((t,n)=>t+((n.endRow??NaN)-(n.startRow??NaN)+1)*((n.endColumn??NaN)-(n.startColumn??NaN)+1),0)}static rowCount(e){return e.reduce((t,n)=>t+(n.endRow??NaN)-(n.startRow??NaN)+1,0)}static columnCount(e){return e.reduce((t,n)=>t+(n.endColumn??NaN)-(n.startColumn??NaN)+1,0)}static containsCell(e,t,n){for(let s=0;s<e.length;s+=1)if(e[s].containsCell(t,n))return!0;return!1}static forEachCell(e,t,n=te.SELECTION_DIRECTION.RIGHT){for(let s=0;s<e.length;s+=1)e[s].forEach(t,n)}constructor(e,t,n,s){this.startColumn=e,this.startRow=t,this.endColumn=n,this.endRow=s}equals(e){return this.startColumn===e.startColumn&&this.startRow===e.startRow&&this.endColumn===e.endColumn&&this.endRow===e.endRow}contains(e){return(this.startColumn==null||e.startColumn!=null&&this.startColumn<=e.startColumn)&&(this.startRow==null||e.startRow!=null&&this.startRow<=e.startRow)&&(this.endColumn==null||e.endColumn!=null&&this.endColumn>=e.endColumn)&&(this.endRow==null||e.endRow!=null&&this.endRow>=e.endRow)}containsCell(e,t){return e==null||t==null?!1:(this.startColumn==null||this.startColumn<=e)&&(this.endColumn==null||this.endColumn>=e)&&(this.startRow==null||this.startRow<=t)&&(this.endRow==null||this.endRow>=t)}touches(e){return te.isAxisRangeTouching(this.startRow,this.endRow,e.startRow,e.endRow)&&te.isAxisRangeTouching(this.startColumn,this.endColumn,e.startColumn,e.endColumn)}subtract(e){return te.subtractFromRange(this,e)}startCell(e=te.SELECTION_DIRECTION.DOWN){if(!te.isBounded(this))throw new Error("Cannot get the startCell of an unbounded range");switch(e){case te.SELECTION_DIRECTION.DOWN:case te.SELECTION_DIRECTION.RIGHT:return{column:this.startColumn,row:this.startRow};case te.SELECTION_DIRECTION.LEFT:case te.SELECTION_DIRECTION.UP:return{column:this.endColumn,row:this.endRow};default:throw new Error(`Invalid direction: ${e}`)}}nextCell(e,t,n){if(!te.isBounded(this))throw new Error("Bounded range required");if(e==null||t==null)throw new Error("Require a non-null cursor");const{startColumn:s,endColumn:i,startRow:o,endRow:l}=this;switch(n){case te.SELECTION_DIRECTION.DOWN:if(t<l)return{column:e,row:Math.max(t+1,o)};if(e<i)return{column:Math.max(e+1,s),row:o};break;case te.SELECTION_DIRECTION.UP:if(t>o)return{column:e,row:Math.min(t-1,l)};if(e>s)return{column:Math.min(e-1,i),row:l};break;case te.SELECTION_DIRECTION.RIGHT:if(e<i)return{column:Math.max(e+1,s),row:t};if(t<l)return{column:s,row:Math.max(t+1,o)};break;case te.SELECTION_DIRECTION.LEFT:if(e>s)return{column:Math.min(e-1,i),row:t};if(t>o)return{column:i,row:Math.min(t-1,l)};break;default:throw new Error(`Invalid direction: ${n}`)}return null}forEach(e,t=te.SELECTION_DIRECTION.RIGHT){let n=0,{column:s,row:i}=this.startCell(t);for(;s!=null&&i!=null;)e(s,i,n),n+=1,{column:s,row:i}=this.nextCell(s,i,t)??{}}}const Ie=te;function RS(c){return Array.isArray(c)&&c.length===2&&(c[0]===null||typeof c[0]=="number")&&(c[1]===null||typeof c[1]=="number")}function Bo(c){return RS(c)&&c[0]!=null&&c[1]!=null}function wl(c){return c?.href!==void 0}class _{static PIXELS_PER_LINE=100/3;static getGridPointFromXY(e,t,n){const s=_.getColumnAtX(e,n),i=_.getRowAtY(t,n),o=_.getColumnHeaderDepthAtY(t,n);return{x:e,y:t,row:i,column:s,columnHeaderDepth:o}}static getCellInfoFromXY(e,t,n){const{row:s,column:i}=_.getGridPointFromXY(e,t,n),{allColumnWidths:o,allRowHeights:l,allColumnXs:a,allRowYs:d,modelColumns:h,modelRows:u}=n,m=s!==null?u.get(s):null,g=i!==null?h.get(i):null,p=i!==null?a.get(i):null,C=s!==null?d.get(s):null,f=i!==null?o.get(i):null,b=s!==null?l.get(s):null;return{row:s,column:i,modelRow:m??null,modelColumn:g??null,left:p??null,top:C??null,columnWidth:f??null,rowHeight:b??null}}static getColumnHeaderDepthAtY(e,t){const n=_.getRowAtY(e,t),{columnHeaderHeight:s,columnHeaderMaxDepth:i}=t;if(n===null&&e<=s*i)return Oe(i-Math.ceil(e/s),0,i-1)}static iterateFloatingStart(e,t,n){for(let s=0;s<e&&s<t;s+=1){const i=n(s);if(i!==void 0)return i}}static iterateFloatingEnd(e,t,n){for(let s=0;s<e&&t-(e-s)>=0;s+=1){const i=n(t-(e-s));if(i!==void 0)return i}}static iterateFloating(e,t,n,s){const i=_.iterateFloatingStart(e,n,s);return i!==void 0?i:_.iterateFloatingEnd(t,n,s)}static iterateAllItems(e,t,n,s,i,o){const l=Math.max(e,n),a=Math.min(t,i-s-1);let d=_.iterateFloating(n,s,i,o);if(d!==void 0)return d;for(let h=l;h<=a;h+=1)if(d=o(h),d!==void 0)return d}static isInItem(e,t,n,s){const i=t.get(e)??0,o=n.get(e)??0;return i<=s&&s<=i+o}static getItemAtOffset(e,t,n,s,i,o,l,a=!1){const d=a?void 0:_.iterateFloating(n,s,t,h=>{if(_.isInItem(h,o,l,e))return h});if(!a&&d!==void 0)return d;for(let h=0;h<i.length;h+=1){const u=i[h];if(_.isInItem(u,o,l,e))return u}return null}static getColumnAtX(e,t,n=!1){const{columnCount:s,floatingLeftColumnCount:i,floatingRightColumnCount:o,visibleColumns:l,allColumnXs:a,allColumnWidths:d,gridX:h}=t;return e<h?null:this.getItemAtOffset(e-h,s,i,o,l,a,d,n)}static getRowAtY(e,t){const{floatingTopRowCount:n,floatingBottomRowCount:s,rowCount:i,visibleRows:o,allRowYs:l,allRowHeights:a,gridY:d}=t;return e<d?null:this.getItemAtOffset(e-d,i,n,s,o,l,a)}static getNextShownItem(e,t,n,s){let i=n.findIndex(o=>o===e)||0;for(i-=1;i!=null&&i>=0;){const o=n[i],l=t.get(o);if(l!=null&&s.get(l)!==0)return o;i-=1}return null}static getNextShownColumn(e,t){const{modelColumns:n,visibleColumns:s,userColumnWidths:i}=t;return _.getNextShownItem(e,n,s,i)}static getNextShownRow(e,t){const{modelRows:n,visibleRows:s,userRowHeights:i}=t;return _.getNextShownItem(e,n,s,i)}static getColumnSeparatorIndex(e,t,n,s){const{rowHeaderWidth:i,columnHeaderHeight:o,floatingColumns:l,floatingLeftWidth:a,visibleColumns:d,allColumnXs:h,allColumnWidths:u,columnHeaderMaxDepth:m}=n,{allowColumnResize:g,headerSeparatorHandleSize:p}=s;if(m*o<t||!g||p<=0)return null;const C=e-i,f=p*.5;let b=!1;for(let w=l.length-1;w>=0;w-=1){const S=l[w],T=h.get(S)??0,y=u.get(S)??0,E=y===0;if(!b||!E){let R=T+y;E?R+=f:b&&(R-=f);const x=R-f,D=R+f;if(x<=C&&C<=D)return S;b=E}}b=!1;for(let w=d.length-1;w>=0;w-=1){const S=d[w],T=h.get(S)??0,y=u.get(S)??0,E=y===0;if(T<a-y)return null;if(!b||!E){let R=T+y;E?R+=f:b&&(R-=f);const x=R-f,D=R+f;if(x<=C&&C<=D)return S;b=E}}return null}static isItemHidden(e,t){return t.get(e)===0}static isColumnHidden(e,t){const{allColumnWidths:n}=t;return _.isItemHidden(e,n)}static isFloatingRow(e,t){if(e==null)return!1;const{floatingTopRowCount:n,floatingBottomRowCount:s,rowCount:i}=t;return e<n||e>=i-s}static isFloatingColumn(e,t){if(e==null)return!1;const{floatingLeftColumnCount:n,floatingRightColumnCount:s,columnCount:i}=t;return e<n||e>=i-s}static getHiddenItems(e,t,n){if(!_.isItemHidden(e,t))return[];const s=[e],i=n.findIndex(o=>o===e);for(let o=i-1;o>=0;o-=1){const l=n[o];if(!_.isItemHidden(l,t))break;s.push(l)}return s}static getHiddenColumns(e,t){const{visibleColumns:n,allColumnWidths:s}=t;return _.getHiddenItems(e,s,n)}static getRowSeparatorIndex(e,t,n,s){const{rowHeaderWidth:i,columnHeaderHeight:o,visibleRows:l,allRowYs:a,allRowHeights:d}=n,{allowRowResize:h,headerSeparatorHandleSize:u}=s;if(i<e||!h||u<=0)return null;const m=t-o,g=u*.5;let p=!1;for(let C=l.length-1;C>=0;C-=1){const f=l[C],b=a.get(f)??0,w=d.get(f)??0,S=w===0;if(!p||!S){let T=b+w;S?T+=g:p&&(T-=g);const y=T-g,E=T+g;if(y<=m&&m<=E)return f;p=S}}return null}static isRowHidden(e,t){const{allRowHeights:n}=t;return _.isItemHidden(e,n)}static getHiddenRows(e,t){const{visibleRows:n,allRowHeights:s}=t;return _.getHiddenItems(e,s,n)}static moveItem(e,t,n){if(e===t)return[...n];const s=[...n],i=s[s.length-1];return i!=null&&!Bo(i.from)&&i.to===e?i.from===t?s.pop():s[s.length-1]={...i,to:t}:s.push({from:e,to:t}),s}static moveRange(e,t,n,s=!1){if(e[0]===e[1])return _.moveItem(e[0],t,n);let i=t;if(s&&e[0]<t&&(i-=e[1]-e[0]),e[0]===i)return[...n];const o=[...n],l=o[o.length-1];l!=null&&Bo(l.from)&&l.from[1]-l.from[0]===e[1]-e[0]&&l.to===e[0]?o[o.length-1]={...l,to:i}:o.push({from:e,to:i});const a=o[o.length-1];return Bo(a.from)&&a.from[0]===a.to&&o.pop(),o}static moveItemOrRange(e,t,n,s=!1){return Array.isArray(e)?_.moveRange(e,t,n,s):_.moveItem(e,t,n)}static applyItemMoves(e,t,n,s=!1){let i=[[e,t]];for(let o=s?n.length-1:0;s?o>=0:o<n.length;s?o-=1:o+=1){const{from:l,to:a}=n[o];let d=1,h;Bo(l)?(d=l[1]-l[0]+1,[h]=l):h=l;const u=s?a:h,m=u+d-1,g=s?h:a,p=g-u,C=[];for(let f=0;f<i.length;f+=1){const b=i[f][0]??Number.NEGATIVE_INFINITY,w=i[f][1]??Number.POSITIVE_INFINITY;let S;const T=[[b,u-1],[u,m],[m+1,w]].map(([y,E])=>[Math.max(y,b),Math.min(E,w)]).filter(([y,E])=>y<=E).map(y=>{const[E,R]=y;return u<=E&&m>=R?(S=[E+p,R+p],S):m<E?[E-d,R-d]:y}).map(y=>{const[E,R]=y;return g>E&&g<=R?[[E,g-1],[g+d,R+d]]:y===S?[y]:g<=E?[[E+d,R+d]]:[y]}).flat();C.push(...T)}i=C.map(([f,b])=>[Number.isFinite(f)?f:null,Number.isFinite(b)?b:null])}return i}static translateRange(e,t,n,s){const i=_.applyItemMoves(e.startColumn,e.endColumn,t,s),o=_.applyItemMoves(e.startRow,e.endRow,n,s),l=[];for(let a=0;a<i.length;a+=1){const d=i[a];for(let h=0;h<o.length;h+=1){const u=o[h];l.push(new Ie(d[0],u[0],d[1],u[1]))}}return l}static getModelIndex(e,t){return _.applyItemMoves(e,e,t,!0)[0][0]}static getModelIndexes(e,t){return e.map(n=>_.getModelIndex(n,t))}static getModelRangeIndexes(e,t,n){return _.applyItemMoves(e,t,n,!0)}static getModelRange(e,t=ke,n=ke){return _.translateRange(e,t,n,!0)}static getModelRanges(e,t=ke,n=ke){const s=[];for(let i=0;i<e.length;i+=1)s.push(..._.getModelRange(e[i],t,n));return s}static getVisibleRangeIndexes(e,t,n){return _.applyItemMoves(e,t,n,!1)}static getVisibleRange(e,t=ke,n=ke){return this.translateRange(e,t,n,!1)}static getVisibleRanges(e,t=ke,n=ke){const s=[];for(let i=0;i<e.length;i+=1)s.push(..._.getVisibleRange(e[i],t,n));return s}static getVisibleIndex(e,t){return _.applyItemMoves(e,e,t)[0][0]}static getVisibleIndexes(e,t){return e.map(n=>_.getVisibleIndex(n,t))}static isMacPlatform(){const{platform:e}=window.navigator;return e.startsWith("Mac")}static getModifierKey(){return _.isMacPlatform()?"metaKey":"ctrlKey"}static isModifierKeyDown(e){const t=_.getModifierKey();return e[t]}static checkColumnHidden(e,t){return t.get(e)===0}static checkAllColumnsHidden(e,t){return t.size===0?!1:e.every(n=>t.get(n)===0)}static getScrollDragBounds(e,t,n){const{gridX:s,gridY:i,width:o,height:l,floatingTopRowCount:a,floatingBottomRowCount:d,floatingLeftColumnCount:h,floatingRightColumnCount:u,floatingLeftWidth:m,floatingRightWidth:g,floatingTopHeight:p,floatingBottomHeight:C,columnCount:f,rowCount:b}=e;let w=s,S=i,T=o,y=l;return n!=null&&(n>h&&(w+=m),n<f-u&&(T-=g)),t!=null&&(t>a&&(S+=p),t<b-d&&(y-=C)),{x1:w,y1:S,x2:T,y2:y}}static getScrollDelta(e,t=1024,n=768,s=20,i=20){let{deltaX:o,deltaY:l}=e;return!_.isMacPlatform()&&e.shiftKey&&e.deltaX===0&&e.deltaY!==0&&(o=e.deltaY,l=e.deltaX),e?.deltaMode===WheelEvent.DOM_DELTA_PAGE?(o*=t,l*=n):e?.deltaMode===WheelEvent.DOM_DELTA_LINE&&(_.isMacPlatform()?(o=Math.round(o*s),l=Math.round(l*i)):(o=Math.round(o*this.PIXELS_PER_LINE),l=Math.round(l*this.PIXELS_PER_LINE))),{deltaX:o,deltaY:l}}static compareRanges(e,t){return e[0]==null||e[1]==null||t[0]==null||t[1]==null?0:e[0]!==t[0]?e[0]-t[0]:e[1]-t[1]}static mergeSortedRanges(e){const t=[];for(let n=0;n<e.length;n+=1){const s=e[n],i=s[0],o=s[1];n===0?t.push([i,o]):i-1<=t[t.length-1][1]?t[t.length-1][1]=Math.max(t[t.length-1][1],o):t.push([i,o])}return t}static translateTokenBox(e,t){const{x1:n,y1:s,x2:i,y2:o}=e,{gridX:l,gridY:a,width:d,height:h,verticalBarWidth:u,horizontalBarHeight:m}=t,g=Oe(l+n,l,d-u),p=Oe(l+i,l,d-u),C=Oe(a+s,a,h-m),f=Oe(a+o,a,h-m);return{x1:g,y1:C,x2:p,y2:f,token:e.token}}static getTextRenderMetrics(e,t,n){const{metrics:s,model:i,theme:o}=e,{firstColumn:l,allColumnXs:a,allColumnWidths:d,allRowYs:h,allRowHeights:u,modelRows:m,modelColumns:g}=s,{cellHorizontalPadding:p,treeDepthIndent:C,treeHorizontalPadding:f}=o,b=k(m,n),w=k(g,t),S=i.textAlignForCell(w,b),T=k(a,t),y=k(h,n),E=k(d,t),R=k(u,n),x=t===l;let D=0;je(i)&&i.hasExpandableRows&&x&&(D=C*(i.depthForRow(n)+1)+f);const M=E-D;let O=T+p;const H=y+R*.5;return S==="right"?O=T+M-p:S==="center"&&(O=T+M*.5),O+=D,{width:M-p*2,x:O,y:H}}static findTokensWithProtocolInText(e){return jc(e).filter(n=>n.type==="url"?/^https?:\/\//.test(n.value):!0)}}function Uo(c,e=bo.CACHE_SIZE,t=Math.floor(e/2)){if(c.size>e){const n=c.keys();for(;c.size>t;)c.delete(n.next().value)}}function qd(c,e,t,n,s){const i=new Map;let o=0;for(let l=0;l<c&&l<t;l+=1)i.set(l,o),o+=k(s,l);o=n;for(let l=0;l<e&&t-l-1>=0;l+=1)o-=k(s,t-l-1),i.set(t-l-1,o);return i}class bo{static CACHE_SIZE=1e4;static MAX_COLUMN_WIDTH=.8;initialRowHeights;initialColumnWidths;userColumnWidths;userRowHeights;calculatedColumnWidths;calculatedRowHeights;fontWidths;modelRows;modelColumns;movedRows;movedColumns;constructor({userColumnWidths:e=new Map,userRowHeights:t=new Map,calculatedColumnWidths:n=new Map,calculatedRowHeights:s=new Map,fontWidths:i=new Map,modelRows:o=new Map,modelColumns:l=new Map,movedRows:a=[],movedColumns:d=[],initialRowHeights:h=new Map,initialColumnWidths:u=new Map}={}){this.userColumnWidths=e,this.userRowHeights=t,this.calculatedRowHeights=s,this.calculatedColumnWidths=n,this.fontWidths=i,this.modelRows=o,this.modelColumns=l,this.movedRows=a,this.movedColumns=d,this.initialRowHeights=h,this.initialColumnWidths=u}getMetrics(e){const{left:t,top:n,leftOffset:s,topOffset:i,width:o,height:l,theme:a,model:d,movedRows:h,movedColumns:u,draggingColumn:m}=e,{rowHeight:g,rowHeaderWidth:p,rowFooterWidth:C,columnWidth:f,columnHeaderHeight:b,minScrollHandleSize:w,scrollBarSize:S}=a;h!==this.movedRows&&(this.movedRows=h,this.modelRows.clear()),u!==this.movedColumns&&(this.movedColumns=u,this.modelColumns.clear());const{columnCount:T,rowCount:y,floatingTopRowCount:E,floatingBottomRowCount:R,floatingLeftColumnCount:x,floatingRightColumnCount:D,columnHeaderMaxDepth:M}=d,O=this.getFirstRow(e),H=this.getFirstColumn(e),L=this.getGridX(e),V=this.getGridY(e),U=je(d)&&d.hasExpandableRows?this.calculateTreePaddingX(e):0,j=0,P=this.getVisibleRowHeights(e),Q=this.getVisibleColumnWidths(e,H,U),$=Array.from(P.keys()),J=Array.from(Q.keys()),A=new Map([...P,...this.getFloatingRowHeights(e)]),W=new Map([...Q,...this.getFloatingColumnWidths(e)]),q=this.getVisibleColumnXs(W,J,s),Z=this.getVisibleRowYs(A,$,i),le=$.length>0?$[$.length-1]:n,G=J.length>0?J[J.length-1]:t,oe=this.getBottomViewport(e,$,Z,A),ue=this.getRightViewport(e,J,q,W),ae=this.getFloatingTopHeight(e,A),ce=this.getFloatingBottomHeight(e,A),we=this.getFloatingLeftWidth(e,W),He=this.getFloatingRightWidth(e,W),Fe=Array.from(W.values()),mt=Array.from(A.values()),et=Fe.reduce((Ae,Yt)=>Ae+Yt,0)-s,De=mt.reduce((Ae,Yt)=>Ae+Yt,0)-i,gt=s+et+C,lt=i+De,vt=o-L,kt=l-V,Cn=this.getLastLeft(e,null,vt-C),zt=this.getLastLeft(e,null,vt-C-S),So=this.getLastTop(e,null,kt-ce),Rs=this.getLastTop(e,null,kt-ce-S);let Kt=zt,Xn=Rs;Cn===0&&So===0&&(Kt=0,Xn=0);const ti=Kt>0,ki=ti?S:0,ni=Xn>0,si=ni?S:0,wo=L,vo=M*b,Zn=o-wo-si,xs=l-vo-ki,la=T===1?Zn/gt:(T-Kt)/T,To=y===1?xs/lt:(y-Xn)/y,Mi=ti?Oe(Zn*la,w,Zn-1):0,Li=ni?Oe(xs*To,w,xs-1):0,Oi=k(W,t,0),Eo=k(A,n,0),aa=Oi>0?s/Oi:0,ra=Eo>0?i/Eo:0,da=T===1?s/(gt-vt):(t+aa)/Kt,ca=y===1?i/(lt-kt):(n+ra)/Xn,ha=ti?da*(Zn-Mi):0,Ds=ni?ca*(xs-Li):0,yo=[...Array(E).keys(),...[...Array(R).keys()].map(Ae=>y-Ae-1)],ii=new Map([...Z,...this.getFloatingRowYs(e,A,Math.floor(l-V-ki))]),Ro=[...Array(x).keys(),...[...Array(D).keys()].map(Ae=>T-Ae-1)],Is=new Map([...q,...this.getFloatingColumnXs(e,W,Math.floor(o-L-si))]),xo=[];if(m)for(let Ae=m.range[0];Ae<=m.range[1];Ae+=1)xo.push(Ae),W.has(Ae)||W.set(Ae,this.getVisibleColumnWidth(Ae,e)),Is.has(Ae)||Is.set(Ae,0);const Ai=$.concat(yo),_i=J.concat(Ro).concat(xo),Do=this.getModelRows(Ai,e),Io=this.getModelColumns(_i,e),Fo=this.getVisibleRowTreeBoxes(A,Do,e),ua=this.getTopVisible(e,ii,A,$),No=this.getLeftVisible(e,Is,W,J),ko=Xn>0?this.getBottomVisible(e,ii,A,$,V):le,Mo=Kt>0?this.getRightVisible(e,Is,W,J,L):G,{fontWidths:Lo,userColumnWidths:Oo,userRowHeights:Ao,calculatedRowHeights:ma,calculatedColumnWidths:Ge}=this;return{rowHeight:g,rowHeaderWidth:p,rowFooterWidth:C,rowCount:y,columnWidth:f,columnCount:T,columnHeaderHeight:b,floatingTopRowCount:E,floatingBottomRowCount:R,floatingLeftColumnCount:x,floatingRightColumnCount:D,gridX:L,gridY:V,firstRow:O,firstColumn:H,treePaddingX:U,treePaddingY:j,left:t,top:n,bottom:le,right:G,topOffset:i,leftOffset:s,topVisible:ua,leftVisible:No,bottomVisible:ko,rightVisible:Mo,bottomViewport:oe,rightViewport:ue,width:o,height:l,maxX:et,maxY:De,lastLeft:Kt,lastTop:Xn,barHeight:xs,barTop:vo,barWidth:Zn,barLeft:wo,handleHeight:Li,handleWidth:Mi,hasHorizontalBar:ti,hasVerticalBar:ni,verticalBarWidth:si,horizontalBarHeight:ki,scrollX:ha,scrollY:Ds,scrollableContentWidth:gt,scrollableContentHeight:lt,scrollableViewportWidth:vt,scrollableViewportHeight:kt,visibleRows:$,visibleColumns:J,visibleRowHeights:P,visibleColumnWidths:Q,floatingRows:yo,floatingColumns:Ro,allRows:Ai,allColumns:_i,allRowHeights:A,allColumnWidths:W,floatingTopHeight:ae,floatingBottomHeight:ce,floatingLeftWidth:we,floatingRightWidth:He,visibleRowYs:Z,visibleColumnXs:q,allRowYs:ii,allColumnXs:Is,visibleRowTreeBoxes:Fo,modelRows:Do,modelColumns:Io,movedRows:h,movedColumns:u,fontWidths:Lo,userColumnWidths:Oo,userRowHeights:Ao,calculatedRowHeights:ma,calculatedColumnWidths:Ge,columnHeaderMaxDepth:M}}getGridX(e){const{theme:t}=e,{rowHeaderWidth:n}=t;return n}getGridY(e){const{theme:t,model:n}=e,{columnHeaderHeight:s}=t,{columnHeaderMaxDepth:i}=n;return i*s}getVisibleHeight(e,t=this.getFloatingRowHeights(e)){const{height:n,theme:s}=e,{scrollBarSize:i}=s,o=this.getGridY(e),l=this.getFloatingBottomHeight(e,t),a=this.getFloatingTopHeight(e,t);return n-l-a-o-i}getVisibleWidth(e,t=this.getFloatingColumnWidths(e)){const{width:n,theme:s}=e,{scrollBarSize:i,rowFooterWidth:o}=s,l=this.getGridX(e),a=this.getFloatingRightWidth(e,t),d=this.getFloatingLeftWidth(e,t);return n-d-a-l-i-o}getFirstIndex(e,t,n){const s=e.size+1;for(let i=0;i<s;i+=1){const o=t(i,n);if(e.get(o)!==0)return i}return 0}getFirstColumn(e){return this.getFirstIndex(this.userColumnWidths,this.getModelColumn.bind(this),e)}getFirstRow(e){return this.getFirstIndex(this.userRowHeights,this.getModelRow.bind(this),e)}getLastLeft(e,t,n){const{model:s}=e,{columnCount:i,floatingRightColumnCount:o}=s;let l=Math.max(0,i-o-1);t!=null&&(l=t);let a=0;for(;l>=0;){const d=this.getVisibleColumnWidth(l,e);if(a+=d,a>=n)return Oe(l+1,0,t??i-1);l-=1}return 0}getLastTop(e,t,n){const{model:s}=e,{rowCount:i,floatingBottomRowCount:o}=s;let l=Math.max(0,i-o-1);t!=null&&(l=t);let a=0;for(;l>=0;){const d=this.getVisibleRowHeight(l,e);if(a+=d,a>=n)return Oe(l+1,0,i-1);l-=1}return 0}getTopForTopVisible(e,t){const n=this.getFloatingTopHeight(e);let s=t,i=0;for(;s>0&&i<n;)s-=1,i+=this.getVisibleRowHeight(s,e);return s}getTopForBottomVisible(e,t){const{height:n}=e,s=this.getGridY(e),i=this.getFloatingBottomHeight(e),o=n-s-i;return this.getLastTop(e,t,o)}getLeftForLeftVisible(e,t){const n=this.getFloatingLeftWidth(e);let s=t,i=0;for(;s>0&&i<n;)s-=1,i+=this.getVisibleColumnWidth(s,e);return s}getLeftForRightVisible(e,t){const{width:n}=e,s=this.getGridX(e),i=this.getFloatingRightWidth(e),o=n-s-i;return this.getLastLeft(e,t,o)}getFloatingRowHeights(e){const{model:t}=e,{floatingTopRowCount:n,floatingBottomRowCount:s,rowCount:i}=t,o=new Map;for(let l=0;l<n&&l<i;l+=1)o.set(l,this.getVisibleRowHeight(l,e));for(let l=0;l<s&&i-l-1>=0;l+=1){const a=i-l-1;o.set(a,this.getVisibleRowHeight(a,e))}return o}getVisibleRowHeights(e){const{top:t,topOffset:n,height:s,model:i}=e;let o=0,l=t;const a=new Map,{rowCount:d}=i;for(;o<s+n&&l<d;){const h=this.getVisibleRowHeight(l,e);a.set(l,h),o+=h,l+=1}return a}getFloatingColumnWidths(e,t=this.getFirstColumn(e),n=this.calculateTreePaddingX(e)){const{model:s}=e,{columnCount:i,floatingLeftColumnCount:o,floatingRightColumnCount:l}=s,a=new Map;for(let d=0;d<o&&d<i;d+=1)a.set(d,this.getVisibleColumnWidth(d,e,t,n));for(let d=0;d<l&&i-d-1>=0;d+=1){const h=i-d-1;a.set(h,this.getVisibleColumnWidth(h,e,t,n))}return a}getVisibleColumnWidths(e,t=this.getFirstColumn(e),n=this.calculateTreePaddingX(e)){const{left:s,leftOffset:i,width:o,model:l}=e;let a=0,d=s;const h=new Map,{columnCount:u}=l;for(;a<o+i&&d<u;){const m=this.getVisibleColumnWidth(d,e,t,n);h.set(d,m),a+=m,d+=1}return h}getFloatingColumnXs(e,t,n){const{model:s}=e,{columnCount:i,floatingLeftColumnCount:o,floatingRightColumnCount:l}=s;return qd(o,l,i,n,t)}getVisibleColumnXs(e,t,n){const s=new Map;let i=-n;for(let o=0;o<t.length;o+=1){const l=t[o],a=k(e,l);s.set(l,i),i+=a}return s}getFloatingRowYs(e,t,n){const{model:s}=e,{floatingTopRowCount:i,floatingBottomRowCount:o,rowCount:l}=s;return qd(i,o,l,n,t)}getVisibleRowYs(e,t,n){const s=new Map;let i=-n;for(let o=0;o<t.length;o+=1){const l=t[o],a=k(e,l);s.set(l,i),i+=a}return s}getVisibleRowTreeBoxes(e,t,n){const s=new Map,{model:i,theme:o}=n,{treeDepthIndent:l,treeHorizontalPadding:a}=o;return je(i)&&i.hasExpandableRows&&e.forEach((d,h)=>{const u=k(t,h);if(i.isRowExpandable(u)){const m=i.depthForRow(u),g=m*l+a,p=(m+1)*l+a,C=0,f=d;s.set(h,{x1:g,y1:C,x2:p,y2:f})}}),s}getFloatingLeftWidth(e,t=this.getFloatingColumnWidths(e)){const{model:n}=e,{floatingLeftColumnCount:s}=n;let i=0;for(let o=0;o<s;o+=1)i+=k(t,o);return i}getFloatingRightWidth(e,t=this.getFloatingColumnWidths(e)){const{model:n}=e,{floatingRightColumnCount:s,columnCount:i}=n;let o=0;for(let l=0;l<s;l+=1)o+=k(t,i-l-1);return o}getFloatingTopHeight(e,t=this.getFloatingRowHeights(e)){const{model:n}=e,{floatingTopRowCount:s}=n;let i=0;for(let o=0;o<s;o+=1)i+=k(t,o);return i}getFloatingBottomHeight(e,t=this.getFloatingRowHeights(e)){const{model:n}=e,{floatingBottomRowCount:s,rowCount:i}=n;let o=0;for(let l=0;l<s;l+=1)o+=k(t,i-l-1);return o}getTopVisible(e,t,n,s){const i=this.getFloatingTopHeight(e,n);for(let o=0;o<s.length;o+=1){const l=s[o];if(k(t,l)>=i)return l}return 0}getLeftVisible(e,t,n,s){const i=this.getFloatingLeftWidth(e,n);for(let o=0;o<s.length;o+=1){const l=s[o];if(k(t,l)>=i)return l}return 0}getBottomVisible(e,t,n,s,i){const{height:o,theme:l}=e,{scrollBarSize:a}=l,d=this.getFloatingBottomHeight(e,n),h=o-i-a-d;for(let u=s.length-1;u>=0;u-=1){const m=s[u],g=k(t,m),p=k(n,m);if(g+p<=h)return m}return 0}getRightVisible(e,t,n,s,i){const{width:o,theme:l}=e,{scrollBarSize:a}=l,d=this.getFloatingRightWidth(e,n),h=o-i-a-d;for(let u=s.length-1;u>=0;u-=1){const m=s[u],g=k(t,m),p=k(n,m);if(g+p<=h)return m}return 0}getBottomViewport(e,t,n,s){const{height:i,theme:o}=e,{rowHeight:l}=o;return this.getLastIndexViewport(t,n,s,i,l)}getRightViewport(e,t,n,s){const{width:i,theme:o}=e,{columnWidth:l}=o;return this.getLastIndexViewport(t,n,s,i,l)}getLastIndexViewport(e,t,n,s,i){let o=0,l=0;return e.length>0&&(o=e[e.length-1],l=k(t,o)+k(n,o)),l<s&&(o+=Math.ceil((s-l)/i)),o}getVisibleItemSize(e,t,n){return t.get(e)??n()}getVisibleRowHeight(e,t){const n=this.getModelRow(e,t),s=this.calculateRowHeight(e,n,t);return this.getVisibleItemSize(n,this.userRowHeights,()=>{const i=this.initialRowHeights.get(n);return i!==void 0?i:s})}getVisibleColumnWidth(e,t,n=this.getFirstColumn(t),s=this.calculateTreePaddingX(t)){const i=this.getModelColumn(e,t),o=this.calculateColumnWidth(e,i,t,n,s);return this.getVisibleItemSize(i,this.userColumnWidths,()=>{const l=this.initialColumnWidths.get(i);return l!==void 0?l:o})}getModelRows(e,t){const n=new Map;for(let s=0;s<e.length;s+=1){const i=e[s],o=this.getModelRow(i,t);n.set(i,o)}return n}getModelRow(e,t){if(this.modelRows.has(e))return k(this.modelRows,e);const{movedRows:n}=t,s=_.getModelIndex(e,n);return this.modelRows.set(e,s),s}getModelColumns(e,t){const n=new Map;for(let s=0;s<e.length;s+=1){const i=e[s],o=this.getModelColumn(i,t);n.set(i,o)}return n}getModelColumn(e,t){if(this.modelColumns.has(e))return k(this.modelColumns,e);const{movedColumns:s}=t,i=_.getModelIndex(e,s);return this.modelColumns.set(e,i),i}calculateRowHeight(e,t,n){const{theme:s}=n,{autoSizeRows:i,rowHeight:o}=s;if(!i)return o;const l=this.calculatedRowHeights.get(t);return l??(this.calculatedRowHeights.set(t,Math.ceil(o)),Uo(this.calculatedRowHeights),o)}calculateColumnWidth(e,t,n,s=this.getFirstColumn(n),i=this.calculateTreePaddingX(n)){const{theme:o}=n,{autoSizeColumns:l,minColumnWidth:a}=o;if(!l){const{columnWidth:g}=o;return g}const d=this.calculateColumnHeaderWidth(t,n),h=this.calculateColumnDataWidth(t,n),u=this.calculatedColumnWidths.get(t);let m=Math.ceil(Math.max(d,h));return m=Math.max(a,m),u!=null&&u>m?m=u:(this.calculatedColumnWidths.set(t,m),Uo(this.calculatedColumnWidths)),e===s&&(m+=i),m}calculateColumnHeaderWidth(e,t){const{model:n,theme:s}=t,{headerFont:i,headerHorizontalPadding:o}=s,l=n.textForColumnHeader(e,0);if(l!==void 0&&l!==""){const a=this.getWidthForFont(i,t);return l.length*a+o*2}return o*2}calculateColumnDataWidth(e,t){const{top:n,height:s,width:i,model:o,theme:l}=t,{floatingTopRowCount:a,floatingBottomRowCount:d,rowCount:h}=o,{font:u,cellHorizontalPadding:m,rowHeight:g,rowHeaderWidth:p,rowFooterWidth:C,scrollBarSize:f,dataBarHorizontalPadding:b}=l;let w=0;const S=this.getWidthForFont(u,t),T=s/g,y=Math.ceil(n+T);return _.iterateAllItems(n,y,a,d,h,E=>{const R=this.getModelRow(E,t),x=o.textForCell(e,R),D=o.renderTypeForCell(e,R);let M=0;if(x){const O=m*2;M=x.length*S+O}D==="dataBar"&&(M+=b),w=Math.max(w,M)}),w=Math.max(Math.min(w,(i-p-f-C)*bo.MAX_COLUMN_WIDTH),m*2),w}calculateTreePaddingX(e){const{top:t,height:n,model:s,theme:i}=e,{rowHeight:o,treeDepthIndent:l}=i;if(!je(s)||!s.hasExpandableRows)return 0;let a=0;const d=n/o,h=Math.ceil(t+d);for(let u=t;u<=h;u+=1){const m=this.getModelRow(u,e),g=s.depthForRow(m);a=Math.max(a,l*(g+1))}return a}getWidthForFont(e,t){if(this.fontWidths.has(e))return k(this.fontWidths,e);const{context:n}=t;n.font=e;const s=n.measureText("8"),{width:i}=s;return this.fontWidths.set(e,i),this.fontWidths.set(n.font,i),i}setColumnWidth(e,t){const n=new Map(this.userColumnWidths);n.set(e,Math.ceil(t)),Uo(n),this.userColumnWidths=n}resetColumnWidth(e){const t=new Map(this.userColumnWidths);t.delete(e),this.userColumnWidths=t}setRowHeight(e,t){const n=new Map(this.userRowHeights);n.set(e,Math.ceil(t)),Uo(n),this.userRowHeights=n}resetRowHeight(e){const t=new Map(this.userRowHeights);t.delete(e),this.userRowHeights=t,this.calculatedRowHeights.delete(e)}}const xS=bo,DS=Object.freeze({allowColumnResize:!0,allowRowResize:!0,autoSelectRow:!1,autoSelectColumn:!1,autoSizeColumns:!0,autoSizeRows:!0,backgroundColor:"#000000",black:"#000000",white:"#ffffff",cellHorizontalPadding:5,headerHorizontalPadding:5,font:"12px Arial, sans serif",gridColumnColor:"#8f8f8f66",gridRowColor:"#8f8f8f66",headerBackgroundColor:"#222222",headerSeparatorColor:"#000000",headerSeparatorHoverColor:"#888888",headerSeparatorHandleSize:5,headerHiddenSeparatorSize:5,headerHiddenSeparatorHoverColor:"#8888FF",headerColor:"#d5d5d5",headerFont:"10px Arial, sans serif",columnHoverBackgroundColor:"#444444",selectedColumnHoverBackgroundColor:"#494949",rowBackgroundColors:"#333333 #222222",rowHoverBackgroundColor:"#444444",selectedRowHoverBackgroundColor:"#494949",minScrollHandleSize:50,scrollBarBackgroundColor:"#111111",scrollBarHoverBackgroundColor:"#333333",scrollBarCasingColor:"#000000",scrollBarCornerColor:"#000000",scrollBarColor:"#555555",scrollBarHoverColor:"#888888",scrollBarActiveColor:"#AAAAAA",scrollBarSize:12,scrollBarHoverSize:16,scrollBarCasingWidth:1,scrollSnapToColumn:!1,scrollSnapToRow:!1,selectionColor:"#4286f433",selectionOutlineColor:"#4286f4",selectionOutlineCasingColor:"#222222",scrollBarSelectionTick:!0,scrollBarSelectionTickColor:"#4286f433",scrollBarActiveSelectionTickColor:"#4286f480",shadowBlur:8,shadowColor:"#000000",textColor:"#ffffff",hyperlinkColor:"#4878ea",maxDepth:6,treeDepthIndent:10,treeHorizontalPadding:5,treeLineColor:"#888888",treeMarkerColor:"#cccccc",treeMarkerHoverColor:"#ffffff",rowHeight:20,columnWidth:100,minRowHeight:20,minColumnWidth:55,columnHeaderHeight:20,rowHeaderWidth:30,rowFooterWidth:0,headerResizeSnapThreshold:10,headerResizeHiddenSnapThreshold:8,allowColumnReorder:!0,allowRowReorder:!0,reorderOffset:2,floatingGridColumnColor:"#8f8f8f66",floatingGridRowColor:"#8f8f8f66",floatingRowBackgroundColors:"#393939 #292929",floatingDividerOuterColor:"#000000",floatingDividerInnerColor:"#cccccc",zeroLineColor:"#888888",positiveBarColor:"#00ff00",negativeBarColor:"#ff0000",dataBarHorizontalPadding:90}),IS=DS,FS=(c,e)=>{let t=!1;const n=Re(c,{...e,dispose:()=>{t||(t=!0,n.clear(),t=!1)}});return n},pn=FS;function NS(c,e,t=6){const n=ja.hex.lab.raw(c);return n[0]=Math.max(n[0]-n[0]/t*e,0),`#${ja.lab.hex(n)}`}function kS(c,e){const[t,n,s]=ja.hex.rgb(c);return`rgba(${t}, ${n}, ${s}, ${e})`}const MS=c=>{const{r:e,g:t,b:n}=c,s=.4122214708*e+.5363325363*t+.0514459929*n,i=.2119034982*e+.6806995451*t+.1073969566*n,o=.0883024619*e+.2817188376*t+.6299787005*n,l=Math.cbrt(s),a=Math.cbrt(i),d=Math.cbrt(o);return{L:.2104542553*l+.793617785*a-.0040720468*d,a:1.9779984951*l-2.428592205*a+.4505937099*d,b:.0259040371*l+.7827717662*a-.808675766*d}},LS=c=>{const{L:e,a:t,b:n}=c,s=e+.3963377774*t+.2158037573*n,i=e-.1055613458*t-.0638541728*n,o=e-.0894841775*t-1.291485548*n,l=s*s*s,a=i*i*i,d=o*o*o;return{r:Oe(4.0767416621*l-3.3077115913*a+.2309699292*d,0,255),g:Oe(-1.2684380046*l+2.6097574011*a-.3413193965*d,0,255),b:Oe(-.0041960863*l-.7034186147*a+1.707614701*d,0,255)}},OS=c=>{const e=c.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(t,n,s,i)=>`#${n}${n}${s}${s}${i}${i}`).substring(1).match(/.{2}/g)?.map(t=>parseInt(t,16))??[0,0,0];return{r:e[0],g:e[1],b:e[2]}},AS=c=>{const e=Math.round(c.r),t=Math.round(c.g),n=Math.round(c.b);return`#${[e,t,n].map(s=>{const i=s.toString(16);return i.length===1?`0${i}`:i}).join("")}`},_S=(c,e,t)=>{const{L:n,a:s,b:i}=c,{L:o,a:l,b:a}=e,d=n+(o-n)*t,h=s+(l-s)*t,u=i+(a-i)*t;return{L:d,a:h,b:u}},Bs={colorWithAlpha:kS,darkenForDepth:NS,linearSRGBToOklab:MS,OklabToLinearSRGB:LS,hexToRgb:OS,rgbToHex:AS,lerpColor:_S};class ht{order;constructor(e=5e3){this.order=e}cursor=null;onDown(e,t,n){return!1}onMove(e,t,n){return!1}onDrag(e,t,n){return!1}onLeave(e,t,n){return!1}onClick(e,t,n){return!1}onContextMenu(e,t,n){return!1}onDoubleClick(e,t,n){return!1}onUp(e,t,n){return!1}onWheel(e,t,n){return!1}}class PS extends ht{draggingIndex;resizingItems=[];hiddenItems=[];targetSizes=new Map;dragOffset=0;onDown(e,t){const{metrics:n}=t,{model:s}=t.props,i=t.getTheme();if(!n)throw new Error("metrics not set");const o=this.getSeparator(e,n,s,i);if(o!=null){const l=o.index;return this.dragOffset=0,this.draggingIndex=l,this.resizingItems=[l],this.hiddenItems=this.getHiddenItems(l,n).reverse(),this.targetSizes.clear(),this.addTargetSize(n,l),this.updateCursor(n,l),this.updateSeparator(t,o),!0}return!1}onMove(e,t){const{metrics:n}=t,{model:s}=t.props,i=t.getTheme();if(!n)throw new Error("metrics not set");const o=this.getSeparator(e,n,s,i);return o!=null?(this.updateCursor(n,o.index),!0):!1}onDrag(e,t){if(this.draggingIndex==null)return!1;const n=e[this.pointProperty],{metricCalculator:s,metrics:i}=t;if(!i)throw new Error("metrics not set");const o=t.getTheme(),l=i[this.visibleOffsetProperty],a=i[this.marginProperty],d=i[this.calculatedSizesProperty],h=i[this.modelIndexesProperty],u=i[this.firstIndexProperty],m=i[this.treePaddingProperty],g=new Map;let p=this.resizingItems[this.resizingItems.length-1];for(;p!=null;){const C=k(l,p),f=n-a-C-this.dragOffset,b=k(h,p),w=this.targetSizes.get(b),S=this.resizingItems.length>1,T=this.hiddenItems.indexOf(p);let y=k(d,b);p===u&&(y+=m);let E=f;Math.abs(f-y)<=o.headerResizeSnapThreshold?E=y:w!==void 0&&f>w&&(S&&T!==0||T>0)?E=w:f<=o.headerResizeHiddenSnapThreshold&&(E=0),g.set(b,E),f<-o.headerResizeSnapThreshold&&E===0?T>=0&&S?(this.resizingItems.pop(),this.removeTargetSize(i,p),p=this.resizingItems[this.resizingItems.length-1],this.dragOffset-=this.targetSizes.get(k(h,p))??0):(p=this.getNextShownItem(p,i),p!==null&&(this.resizingItems.push(p),this.addTargetSize(i,p))):w!==void 0&&f>w+o.headerResizeSnapThreshold&&E===w?T>0?(this.dragOffset+=E,p=this.hiddenItems[T-1],this.resizingItems.push(p),this.addTargetSize(i,p)):S?(this.resizingItems.pop(),this.removeTargetSize(i,p),p=this.resizingItems[this.resizingItems.length-1]):p=null:p=null}return g.forEach((C,f)=>{const b=s[this.initialSizesProperty].get(f)??d.get(f);C===b?this.resetSize(s,f):this.setSize(s,f,C)}),this.updateCursor(i,this.draggingIndex),!0}onUp(e,t){return this.draggingIndex!=null&&(this.draggingIndex=void 0,this.resizingItems=[],this.hiddenItems=[],this.targetSizes.clear(),this.updateSeparator(t,null)),!1}onDoubleClick(e,t){const{metrics:n,metricCalculator:s}=t,{model:i}=t.props,o=t.getTheme();if(!n)throw new Error("metrics not set");const l=this.getSeparator(e,n,i,o);if(l!=null){const a=n[this.modelIndexesProperty],d=k(a,l.index),h=k(n[this.calculatedSizesProperty],d),u=s[this.initialSizesProperty].get(d);return h===u?this.resetSize(s,d):this.setSize(s,d,h),t.forceUpdate(),!0}return!1}updateCursor(e,t){const n=e[this.visibleSizesProperty];k(n,t)===0?this.cursor=this.hiddenCursor:this.cursor=this.defaultCursor}addTargetSize(e,t){const n=e[this.modelIndexesProperty],s=e[this.userSizesProperty],i=e[this.calculatedSizesProperty],o=t===0?e[this.treePaddingProperty]:0,l=k(n,t);let a=s.get(l);(a==null||a===0)&&(a=k(i,l)+o),this.targetSizes.set(l,a)}removeTargetSize(e,t){const n=e[this.modelIndexesProperty],s=k(n,t);this.targetSizes.delete(s)}}const hu=PS;class Mr extends hu{static getColumnSeparator(e,t,n,s){if(!s.allowColumnResize)return null;const{x:i,y:o,columnHeaderDepth:l}=e,{modelColumns:a}=t,d=_.getColumnSeparatorIndex(i,o,t,s);return d==null||l==null||l>0?null:a.get(d)!=null?{index:d,depth:0}:null}hiddenCursor="e-resize";defaultCursor="col-resize";pointProperty="x";userSizesProperty="userColumnWidths";visibleOffsetProperty="visibleColumnXs";visibleSizesProperty="visibleColumnWidths";marginProperty="rowHeaderWidth";calculatedSizesProperty="calculatedColumnWidths";initialSizesProperty="initialColumnWidths";modelIndexesProperty="modelColumns";firstIndexProperty="firstColumn";treePaddingProperty="treePaddingX";getHiddenItems=_.getHiddenColumns;getNextShownItem=_.getNextShownColumn;setSize(e,t,n){e.setColumnWidth(t,n)}resetSize(e,t){e.resetColumnWidth(t)}updateSeparator(e,t){e.setState({draggingColumnSeparator:t,isDragging:t!==null})}getSeparator=Mr.getColumnSeparator}const uu=Mr,Zs=10;class jS{drawCellRowTreeMarker(e,t,n){const{metrics:s,model:i,mouseX:o,mouseY:l,theme:a}=t,{firstColumn:d,gridX:h,gridY:u,allColumnXs:m,allColumnWidths:g,allRowYs:p,allRowHeights:C,visibleRowTreeBoxes:f}=s,{treeMarkerColor:b,treeMarkerHoverColor:w}=a,S=k(m,d),T=k(g,d),y=k(p,n),E=k(C,n);if(!je(i)||!i.isRowExpandable(n))return;const R=k(f,n),x=o!=null&&l!=null&&o>=h+S&&o<=h+S+T&&l>=u+y&&l<=u+y+E?w:b;this.drawTreeMarker(e,t,S,y,R,x,i.isRowExpanded(n))}drawTreeMarker(e,t,n,s,i,o,l){const{x1:a,y1:d,x2:h,y2:u}=i,m=l?"⊟":"⊞",g=n+(a+h)*.5+.5,p=s+(d+u)*.5+.5;e.fillStyle=o,e.textAlign="center",e.fillText(m,g,p)}getCachedTruncatedString=pn((e,t,n,s,i)=>fu.truncateToWidth(e,t,n,s,i),{max:1e4})}const mu=jS;function Xd(c){return c?.dataBarOptionsForCell!==void 0}class HS extends mu{heightOfDigits;drawCellContent(e,t,n,s){const{metrics:i,model:o,theme:l}=t;if(!Xd(o))return;const{modelColumns:a,modelRows:d,allRowHeights:h,allRowYs:u,firstColumn:m,fontWidths:g}=i,p=n===m,C=k(h,s),f=k(d,s),b=k(a,n),w=k(u,s),S=o.textAlignForCell(b,f),T=o.textForCell(b,f),{x:y,width:E}=_.getTextRenderMetrics(t,n,s),R=g?.get(e.font)??Zs,x=o.truncationCharForCell(b,f),D=this.getCachedTruncatedString(e,T,E,R,x),{columnMin:M,columnMax:O,axis:H,color:L,valuePlacement:V,opacity:U,markers:j,direction:P,value:Q}=o.dataBarOptionsForCell(b,f),$=Array.isArray(L);if(M==null||O==null)return;const{maxWidth:J,x:A,y:W,zeroPosition:q,leftmostPosition:Z,markerXs:le,totalValueRange:G,dataBarWidth:oe}=this.getDataBarRenderMetrics(e,t,n,s);if(this.heightOfDigits===void 0){const{actualBoundingBoxAscent:ae,actualBoundingBoxDescent:ce}=e.measureText("1234567890");this.heightOfDigits=ae+ce}if(e.save(),e.textAlign=S,$){const ae=Q>=0?L[L.length-1]:L[0];e.fillStyle=ae}else e.fillStyle=L;if(e.textBaseline="top",e.font=l.font,V!=="hide"&&e.fillText(D,y,w+(C-this.heightOfDigits)/2),$){const ae=L.map(ce=>Bs.linearSRGBToOklab(Bs.hexToRgb(ce)));if(e.save(),e.beginPath(),e.roundRect(A,W,oe,C-2,1),e.clip(),Q<0){if(P==="LTR"){const we=Math.round(Math.abs(M)/G*J)/(L.length-1);let He=Math.round(Z);for(let Fe=0;Fe<L.length-1;Fe+=1){const mt=ae[Fe],et=ae[Fe+1];this.drawGradient(e,mt,et,He,w+1,we,C),He+=we}}else if(P==="RTL"){const we=Math.round(J-Math.abs(O)/G*J)/(L.length-1);let He=Math.round(q);for(let Fe=L.length-1;Fe>0;Fe-=1){const mt=ae[Fe],et=ae[Fe-1];this.drawGradient(e,mt,et,He,w+1,we,C),He+=we}}}else if(P==="LTR"){const we=(Math.round(J-Math.abs(M)/G*J)-1)/(L.length-1);let He=Math.round(q);for(let Fe=0;Fe<L.length-1;Fe+=1){const mt=ae[Fe],et=ae[Fe+1];this.drawGradient(e,mt,et,He,w+1,we,C-2),He+=we}}else if(P==="RTL"){const we=Math.round(Math.abs(O)/G*J)/(L.length-1);let He=Math.round(Z);for(let Fe=L.length-1;Fe>0;Fe-=1){const mt=ae[Fe],et=ae[Fe-1];this.drawGradient(e,mt,et,He,w+1,we,C-2),He+=we}}e.restore()}else e.save(),e.globalAlpha=U,e.beginPath(),e.roundRect(A,W,oe,C-2,1),e.fill(),e.restore();J>0&&le.forEach((ae,ce)=>{e.fillStyle=j[ce].color,e.fillRect(ae,W,1,C-2)}),!(H==="directional"&&(V==="beside"&&S==="right"&&P==="LTR"||V==="beside"&&S==="left"&&P==="RTL"||V!=="beside"))&&(e.strokeStyle=l.zeroLineColor,e.beginPath(),e.setLineDash([2,1]),e.moveTo(q,w),e.lineTo(q,w+C),e.stroke()),e.restore(),p&&je(o)&&o.hasExpandableRows&&this.drawCellRowTreeMarker(e,t,s)}getDataBarRenderMetrics(e,t,n,s){const{metrics:i,model:o,theme:l}=t;if(!Xd(o))throw new Error("Grid model is not a data bar grid model");const{firstColumn:a,allColumnXs:d,allColumnWidths:h,allRowYs:u,modelColumns:m,modelRows:g,visibleRows:p}=i,{cellHorizontalPadding:C,treeDepthIndent:f,treeHorizontalPadding:b}=l,w=k(m,n),S=k(g,s),T=k(d,n),y=k(u,s),E=k(h,n),R=n===a;let x=0;je(o)&&o.hasExpandableRows&&R&&(x=f*(o.depthForRow(s)+1)+b);const D=o.textAlignForCell(w,S),{columnMin:M,columnMax:O,axis:H,valuePlacement:L,markers:V,direction:U,value:j}=o.dataBarOptionsForCell(w,S),P=this.getCachedWidestValueForColumn(e,p,g,o,w),Q=2,$=L==="beside"&&D==="right"?2:1;let J=O-M;O>=0&&M>=0||M===O?J=O:O<=0&&M<=0&&(J=Math.abs(M));let A=E-x-$-Q;L==="beside"&&(A=A-C-P),A<0&&(A=0);const W=Math.max(Math.abs(M),Math.abs(O));let q=Math.abs(j)/J*A;A===0?q=0:H==="middle"?q=Math.abs(j)/W*(A/2):H==="directional"&&(q=Math.abs(j)/W*A);let Z=M>=0?0:Math.abs(M)/J*A,le=j>=0?Z:Z-Math.abs(j)/J*A,G=V.map(ae=>{const{column:ce}=ae,we=Number(o.textForCell(ce,S));return we>=0?Z+Math.abs(we)/J*A:Z-Math.abs(we)/J*A}),oe=L==="beside"&&D==="left"?C+P+Q:Q,ue=L==="beside"&&D==="right"?E-C-P-$:$;return U==="RTL"&&(Z=M>=0?E:E-Math.abs(M)/J*A,le=j>=0?Z-j/J*A:Z,G=V.map(ae=>{const{column:ce}=ae,we=Number(o.textForCell(ce,S));return we>=0?Z-Math.abs(we)/J*A:Z+Math.abs(we)/J*A})),H==="middle"?(Z=A/2,U==="LTR"?(le=j>=0?Z:Z-Math.abs(j)/W*(A/2),G=V.map(ae=>{const{column:ce}=ae,we=Number(o.textForCell(ce,S));return we>=0?Z+Math.abs(we)/W*(A/2):Z-Math.abs(we)/W*(A/2)})):U==="RTL"&&(le=j<=0?Z:Z-Math.abs(j)/W*(A/2),G=V.map(ae=>{const{column:ce}=ae,we=Number(o.textForCell(ce,S));return we<=0?Z+Math.abs(we)/W*(A/2):Z-Math.abs(we)/W*(A/2)}))):H==="directional"&&(U==="LTR"?(Z=0,le=Z,G=V.map(ae=>{const{column:ce}=ae,we=Number(o.textForCell(ce,S));return Z+Math.abs(we)/W*A})):U==="RTL"&&(Z=E,le=Z-Math.abs(j)/W*A,G=V.map(ae=>{const{column:ce}=ae,we=Number(o.textForCell(ce,S));return Z-Math.abs(we)/W*A}))),U==="LTR"?(Z+=T+Q+x,le+=T+Q+x,G=G.map(ae=>ae+T+Q+x),L==="beside"&&D==="left"&&(Z+=P+C,le+=P+C,G=G.map(ae=>ae+P+C))):U==="RTL"&&(Z=Z+T-$,le=le+T-$,G=G.map(ae=>ae+T-$),L==="beside"&&D==="right"&&(Z=Z-C-P,le=le-C-P,G=G.map(ae=>ae-C-P))),oe+=T+x,ue+=T,{maxWidth:A,x:le,y:y+1.5,zeroPosition:Z,leftmostPosition:oe,rightmostPosition:ue,totalValueRange:J,dataBarWidth:q,markerXs:G}}drawGradient(e,t,n,s,i,o,l){let a=t;for(let d=s;d<=s+o;d+=.5)this.drawGradientPart(e,d,i,1,l,Bs.rgbToHex(Bs.OklabToLinearSRGB(a))),a=Bs.lerpColor(t,n,(d-s)/o)}drawGradientPart(e,t,n,s,i,o){e.fillStyle=o,e.fillRect(t,n,s,i)}getCachedWidestValueForColumn=pn((e,t,n,s,i)=>{let o=0;for(let l=0;l<t.length;l+=1){const a=t[l],d=k(n,a),h=s.textForCell(i,d);o=Math.max(o,e.measureText(h).width)}return o},{max:1e3})}const gu=HS;class BS extends mu{drawCellContent(e,t,n,s){const{metrics:i,model:o,theme:l}=t,{fontWidths:a,modelColumns:d,modelRows:h,allRowHeights:u,firstColumn:m}=i,g=n===m,{textColor:p}=l,C=k(u,s),f=k(h,s),b=k(d,n),w=o.textForCell(b,f),S=o.truncationCharForCell(b,f);if(w&&C>0){const T=o.textAlignForCell(b,f)||"left";e.textAlign=T;const y=o.colorForCell(b,f,l)||p;e.fillStyle=y,e.save();const{width:E,x:R,y:x}=_.getTextRenderMetrics(t,n,s),D=a.get(e.font)??Zs,M=this.getCachedTruncatedString(e,w,E,D,S),O=o.tokensForCell(b,f,M.length);if(M){let H=0,L=0,V=R;const{actualBoundingBoxDescent:U}=e.measureText(M);for(;L<M.length;){const j=O[H],P=L===j?.start?j:null,Q=P?.end??j?.start??M.length,$=M.substring(L,Q),{width:J}=e.measureText($),A=$.endsWith("…")?e.measureText($.substring(0,$.length-1)).width:J;P!=null?(e.fillStyle=l.hyperlinkColor,e.fillText($,V,x),e.fillRect(V,x+U,A,1)):(e.fillStyle=y,e.fillText($,V,x)),V+=J,L=Q,P!=null&&(H+=1)}}e.restore()}g&&je(o)&&o.hasExpandableRows&&this.drawCellRowTreeMarker(e,t,s)}getTokenBoxesForVisibleCell(e,t,n){const{metrics:s,context:i,model:o,theme:l}=n;if(i==null||s==null)return ke;const{modelRows:a,modelColumns:d}=s,h=k(a,t),u=k(d,e),m=o.textForCell(u,h),{width:g,x:p,y:C}=_.getTextRenderMetrics(n,e,t),{fontWidths:f}=s;i.save(),this.configureContext(i,n);const b=f?.get(i.font)??Zs,w=o.truncationCharForCell(u,h),S=this.getCachedTruncatedString(i,m,g,b,w),{actualBoundingBoxAscent:T,actualBoundingBoxDescent:y}=i.measureText(S),E=T+y,R=o.tokensForCell(u,h,S.length);if(R.length===0)return i.restore(),ke;const x=this.getCachedTokenBoxesForVisibleCell(S,R,l.font,"middle",E,i).map(D=>({x1:D.x1+p,y1:D.y1+(C-T),x2:D.x2+p,y2:D.y2+(C-T),token:D.token}));return i.restore(),x}configureContext(e,t){const{theme:n}=t;e.font=n.font,e.textBaseline="middle",e.lineCap="butt"}getCachedTokenBoxesForVisibleCell=pn((e,t,n,s,i,o)=>{const a=i,d=[];let h=0,u=0;for(let m=0;m<t.length;m+=1){const g=t[m],{start:p,end:C}=g,f=C>e.length?e.substring(p):g.value;u+=o.measureText(e.substring(h,p)).width;const b=o.measureText(f).width,w=u,S=w+b,T={x1:w,y1:0,x2:S,y2:a,token:g};d.push(T),h=C,u+=b}return d},{max:1e4})}const pu=BS;class fs{static DEFAULT_EDGE_RADIUS=2;static ACTIVE_CELL_BORDER_WIDTH=2;textCellRenderer=new pu;dataBarCellRenderer=new gu;static truncate(e,t){return t<e.length?e.substr(0,t)+"…":e}static binaryTruncateToWidth(e,t,n,s=0,i=t.length,o){if(i>=t.length&&e.measureText(t).width<=n)return t;if(o!==void 0){const h=e.measureText(o).width;return o.repeat(Math.max(1,Math.floor(n/h)))}let l=s,a=Math.min(t.length-1,i),d=t;for(;a>=l;){const h=Math.ceil((a+l)/2),u=fs.truncate(t,h);if(e.measureText(u).width<=n){if(d=u,l===h)break;l=h}else if(h===0){d=u;break}else a=h-1}return d}static truncateToWidth(e,t,n,s=Zs,i){if(n<=0||t.length<=0)return"";const o=Math.min(Math.max(0,Math.floor(n/s/2)-5),t.length),l=Math.min(Math.ceil(n/s*2),t.length);return fs.binaryTruncateToWidth(e,t,n,o,l,i)}drawCanvas(e){const{context:t}=e;t.save(),this.configureContext(t,e),this.drawBackground(t,e),this.drawGrid(t,e),this.drawHeaders(t,e),this.drawFooters(t,e),this.drawDraggingColumn(t,e),this.drawDraggingRow(t,e),this.drawScrollBars(t,e),t.restore()}configureContext(e,t){const{theme:n}=t;e.font=n.font,e.textBaseline="middle",e.lineCap="butt"}drawBackground(e,t){const{theme:n,metrics:s}=t,{width:i,height:o}=s;e.fillStyle=n.backgroundColor,e.fillRect(0,0,i,o)}drawGrid(e,t){const{metrics:n,draggingRow:s,draggingColumn:i}=t,{gridX:o,gridY:l}=n;e.translate(o,l),this.drawGridBackground(e,t,s==null&&i==null),this.drawCellContents(e,t),this.drawFloatingRows(e,t),this.drawFloatingColumns(e,t),e.translate(-o,-l)}drawFloatingRows(e,t){const{draggingRow:n,draggingColumn:s,metrics:i,theme:o}=t,{floatingTopRowCount:l,floatingBottomRowCount:a,floatingRows:d,rowCount:h,visibleColumns:u,allRowYs:m,allRowHeights:g}=i;if(d.length!==0){o.floatingRowBackgroundColors&&this.drawRowStripesForRows(e,t,d,o.floatingRowBackgroundColors),n==null&&s==null&&this.drawFloatingMouseRowHover(e,t),this.drawGridLinesForItems(e,t,u,d,o.floatingGridColumnColor,o.floatingGridRowColor),this.drawCellBackgroundsForItems(e,t,u,d),this.drawFloatingBorders(e,t),l>0&&this.drawSelectedRanges(e,t,{top:0,bottom:l-1,maxY:k(m,l-1)+k(g,l-1)-.5}),a>0&&this.drawSelectedRanges(e,t,{top:h-a-1,bottom:h-1,minY:k(m,h-a)+.5,maxY:k(m,h-1)+k(g,h-1)-.5});for(let p=0;p<u.length;p+=1){const C=u[p];for(let f=0;f<d.length;f+=1){const b=d[f];this.drawCellContent(e,t,C,b)}}}}drawFloatingColumns(e,t){const{draggingRow:n,draggingColumn:s,metrics:i,theme:o}=t,{floatingLeftColumnCount:l,floatingRightColumnCount:a,floatingLeftWidth:d,floatingRightWidth:h,floatingColumns:u,gridX:m,maxX:g,columnCount:p,visibleRows:C,allColumnXs:f,allColumnWidths:b,width:w,height:S}=i;if(u.length!==0){o.floatingRowBackgroundColors&&(this.drawRowStripesForRows(e,t,C,o.floatingRowBackgroundColors,0,d),this.drawRowStripesForRows(e,t,C,o.floatingRowBackgroundColors,w-m-h,g)),n==null&&s==null&&this.drawFloatingMouseRowHover(e,t),e.save(),e.beginPath(),e.rect(0,0,d,S),e.clip(),this.drawGridLinesForItems(e,t,u,C,o.floatingGridColumnColor,o.floatingGridRowColor),e.restore(),this.drawCellBackgroundsForItems(e,t,u,C),this.drawFloatingBorders(e,t),l>0&&this.drawSelectedRanges(e,t,{left:0,maxX:k(f,l-1)+k(b,l-1)}),a>0&&this.drawSelectedRanges(e,t,{left:p-a,right:p-1,minX:k(f,p-a)+.5,maxX:k(f,p-1)+k(b,p-1)});for(let T=0;T<u.length;T+=1){const y=u[T];for(let E=0;E<C.length;E+=1){const R=C[E];this.drawCellContent(e,t,y,R)}}}}drawFloatingBorders(e,t){const{metrics:n,theme:s}=t,{floatingTopRowCount:i,floatingBottomRowCount:o,floatingLeftColumnCount:l,floatingRightColumnCount:a,rowCount:d,columnCount:h,allRowYs:u,allColumnXs:m,allRowHeights:g,allColumnWidths:p,maxX:C,maxY:f}=n,{floatingDividerOuterColor:b,floatingDividerInnerColor:w}=s;if(e.lineWidth=3,e.beginPath(),e.strokeStyle=b,i>0){const S=k(u,i-1)+k(g,i-1)+.5;e.moveTo(0,S),e.lineTo(C,S)}if(o>0){const S=k(u,d-o)-.5;e.moveTo(0,S),e.lineTo(C,S)}if(l>0){const S=k(m,l-1)+k(p,l-1)+.5;e.moveTo(S,0),e.lineTo(S,f)}if(a>0){const S=k(m,h-a)-.5;e.moveTo(S,0),e.lineTo(S,f)}if(e.stroke(),e.beginPath(),e.lineWidth=1,e.strokeStyle=w,i>0){const S=k(u,i-1)+k(g,i-1)+.5;e.moveTo(0,S),e.lineTo(C,S)}if(o>0){const S=k(u,d-o)-.5;e.moveTo(0,S),e.lineTo(C,S)}if(l>0){const S=k(m,l-1)+k(p,l-1)+.5;e.moveTo(S,0),e.lineTo(S,f)}if(a>0){const S=k(m,h-a)-.5;e.moveTo(S,0),e.lineTo(S,f)}e.stroke()}drawGridBackground(e,t,n=!1){this.drawRowStripes(e,t),n&&(this.drawMouseColumnHover(e,t),this.drawMouseRowHover(e,t)),this.drawGridLines(e,t),this.drawCellBackgrounds(e,t);const{metrics:s}=t,{bottom:i,right:o,floatingBottomRowCount:l,floatingLeftColumnCount:a,floatingRightColumnCount:d,floatingTopRowCount:h,columnCount:u,rowCount:m,allRowHeights:g,allRowYs:p,allColumnXs:C,allColumnWidths:f,width:b,height:w}=s;this.drawSelectedRanges(e,t,{bottom:Math.min(i,m-l-1),right:Math.min(o,u-d-1),minX:a>0&&C.has(a+1)?k(C,a+1):-10,minY:h>0&&p.has(h+1)?k(p,h+1):-10,maxX:d>0&&C.has(u-d-1)?k(C,u-d-1)+k(f,u-d-1)-.5:b+10,maxY:l>0&&p.has(m-l-1)?k(p,m-l-1)+k(g,m-l-1)-.5:w+10})}drawRowStripes(e,t){const{metrics:n,theme:s}=t,{visibleRows:i}=n,{rowBackgroundColors:o}=s;o&&this.drawRowStripesForRows(e,t,i,o)}drawRowStripesForRows(e,t,n,s,i=0,o=t.metrics.maxX){const{theme:l,metrics:a,model:d}=t,{maxDepth:h,shadowBlur:u,shadowColor:m}=l,g=this.getCachedBackgroundColors(s,h),{allRowYs:p,allRowHeights:C}=a,f=new Map,b=[],w=[],S=(T,y)=>{const E=je(d)?d.depthForRow(T):0,R=g[T%g.length],x=R[Math.min(E,R.length-1)];if(f.has(x)||f.set(x,[]),f.get(x).push(T),y!=null){const D=je(d)?d.depthForRow(y):0;D<E?b.push(T):D>E&&w.push(y)}};for(let T=0;T<n.length;T+=1){const y=n[T],E=T>0?n[T-1]:void 0;S(y,E)}if(f.forEach((T,y)=>{e.fillStyle=y,e.beginPath();for(let E=0;E<T.length;E+=1){const R=T[E],x=k(p,R),D=k(C,R);e.rect(i,x,o,D)}e.fill()}),b.length>0){e.save();const T=this.getCachedColorWithAlpha(m,.15),y=this.getCachedColorWithAlpha(m,0),E=e.createLinearGradient(0,0,0,u);E.addColorStop(0,T),E.addColorStop(1,y),e.fillStyle=E;for(let R=0;R<b.length;R+=1){const x=b[R],D=k(p,x);e.translate(0,D),e.fillRect(i,0,o,u),e.translate(0,-D)}e.restore()}if(w.length>0){e.save();const T=this.getCachedColorWithAlpha(m,0),y=this.getCachedColorWithAlpha(m,.15),E=e.createLinearGradient(0,0,0,u);E.addColorStop(0,T),E.addColorStop(1,y),e.fillStyle=E;for(let R=0;R<w.length;R+=1){const x=w[R],D=k(p,x),M=k(C,x),O=D+M-u;e.translate(0,O),e.fillRect(i,0,o,u),e.translate(0,-O)}e.restore()}}drawMouseColumnHover(e,t){const{mouseX:n,mouseY:s,theme:i,metrics:o}=t;if(n==null||s==null)return;const l=_.getColumnAtX(n,o);if(l==null||i.columnHoverBackgroundColor==null)return;const{allColumnWidths:a,allColumnXs:d,maxY:h}=o;if(s>h)return;const u=k(d,l),m=k(a,l);e.fillStyle=i.columnHoverBackgroundColor,e.fillRect(u,0,m,h)}drawMouseRowHover(e,t){const{mouseX:n,mouseY:s,theme:i,metrics:o}=t;if(n==null||s==null)return;const{maxX:l}=o;if(n>l||i.rowHoverBackgroundColor==null)return;const a=_.getRowAtY(s,o);a!=null&&this.drawMouseRowHoverForRow(e,t,a)}drawFloatingMouseRowHover(e,t){const{mouseX:n,mouseY:s,theme:i,metrics:o}=t,{maxX:l,floatingTopRowCount:a,floatingBottomRowCount:d,rowCount:h,rowFooterWidth:u}=o;if(n==null||s==null||n>l+u||i.rowHoverBackgroundColor==null)return;const m=_.getRowAtY(s,o);m!=null&&(m<a||h-d<=m)&&this.drawMouseRowHoverForRow(e,t,m)}drawMouseRowHoverForRow(e,t,n){const{metrics:s,selectedRanges:i,theme:o}=t,{allRowHeights:l,allRowYs:a,maxX:d}=s,h=k(a,n),u=k(l,n);o.rowHoverBackgroundColor!=null&&(e.fillStyle=o.rowHoverBackgroundColor);for(let m=0;m<i.length;m+=1){const{startRow:g,endRow:p}=i[m];if(g!=null&&p!=null&&g<=n&&p>=n){o.selectedRowHoverBackgroundColor!=null&&(e.fillStyle=o.selectedRowHoverBackgroundColor);break}}e.fillRect(0,h,d,u)}drawGridLines(e,t){const{metrics:n,theme:s}=t,{visibleColumns:i,visibleRows:o}=n;this.drawGridLinesForItems(e,t,i,o,s.gridColumnColor,s.gridRowColor)}drawGridLinesForItems(e,t,n,s,i,o){i==null&&o==null||(e.lineWidth=1,e.beginPath(),i!=null&&(e.strokeStyle=i,this.drawGridLinesForColumns(e,t,n)),o!=null&&(e.strokeStyle=o,this.drawGridLinesForRows(e,t,s)),e.stroke())}drawGridLinesForColumns(e,t,n){const{metrics:s}=t,{allColumnXs:i,maxY:o}=s;for(let l=0;l<n.length;l+=1){const a=n[l],d=k(i,a)+.5;e.moveTo(d,0),e.lineTo(d,o)}}drawGridLinesForRows(e,t,n){const{metrics:s}=t,{allRowYs:i,maxX:o}=s,l=o;for(let a=0;a<n.length;a+=1){const d=n[a],h=k(i,d)+.5;e.moveTo(.5,h),e.lineTo(l-.5,h)}}drawCellBackgrounds(e,t){const{metrics:n}=t,{visibleColumns:s,visibleRows:i}=n;this.drawCellBackgroundsForItems(e,t,s,i)}drawCellBackgroundsForItems(e,t,n,s){e.save();for(let i=0;i<n.length;i+=1){const o=n[i];for(let l=0;l<s.length;l+=1){const a=s[l],d=l+1<s.length?s[l+1]:void 0;this.drawCellBackground(e,t,o,a,d)}}e.restore()}drawCellBackground(e,t,n,s,i){const{metrics:o,model:l,theme:a}=t,{firstColumn:d,modelColumns:h,modelRows:u,allColumnXs:m,allColumnWidths:g,allRowYs:p,allRowHeights:C}=o,f=k(u,s),b=k(h,n),w=l.backgroundColorForCell(b,f,a),S=n===d,T=je(l)&&l.hasExpandableRows;if(w!=null){const y=k(m,n)+1,E=k(p,s)+1,R=k(g,n)-1,x=k(C,s)-1;e.fillStyle=w,e.fillRect(y,E,R,x)}S&&T&&this.drawCellRowTreeDepthLines(e,t,s,i)}drawCellContents(e,t){const{metrics:n}=t,{visibleColumns:s}=n;for(let i=0;i<s.length;i+=1){const o=s[i];this.drawColumnCellContents(e,t,o)}}drawColumnCellContents(e,t,n){const{metrics:s}=t,{allColumnXs:i,allColumnWidths:o,visibleRows:l,height:a}=s,d=k(i,n),h=k(o,n);e.save(),e.beginPath(),e.rect(d,0,h,a),e.clip();for(let u=0;u<l.length;u+=1){const m=l[u];this.drawCellContent(e,t,n,m)}e.restore()}drawCellContent(e,t,n,s){const{metrics:i,model:o}=t,{modelColumns:l,modelRows:a}=i,d=k(a,s),h=k(l,n),u=o.renderTypeForCell(h,d);this.getCellRenderer(u).drawCellContent(e,t,n,s)}getCellRenderer(e){switch(e){case"dataBar":return this.dataBarCellRenderer;default:return this.textCellRenderer}}drawCellRowTreeDepthLines(e,t,n,s){const{metrics:i,model:o,theme:l}=t;if(!je(o))return;const a=o.depthForRow(n);if(a===0)return;const{firstColumn:d,allColumnXs:h,allRowYs:u,allRowHeights:m}=i,{treeDepthIndent:g,treeHorizontalPadding:p,treeLineColor:C}=l,f=k(h,d),b=k(u,n),w=k(m,n),S=s!==void 0?o.depthForRow(s):0,T=a>S?a-S:0;if(e.strokeStyle=C,e.lineWidth=1,a-T>0){e.beginPath();for(let y=0;y<a-T;y+=1){const E=f+y*g+g*.5+p+.5;e.moveTo(E,b),e.lineTo(E,b+w)}e.stroke()}if(T>0){e.beginPath();for(let y=a-T;y<a;y+=1){const E=f+y*g+g*.5+p+.5;e.moveTo(E,b),e.lineTo(E,b+Math.ceil(w/2)),e.moveTo(E-.5,b+Math.ceil(w/2)+.5),e.lineTo(E+g-.5,b+Math.ceil(w/2)+.5)}e.stroke()}}getCachedBackgroundColors=pn((e,t)=>e.split(" ").map(n=>{const s=[];for(let i=0;i<t;i+=1)s.push(Bs.darkenForDepth(n,i,t));return s}),{max:1e3});getCachedColorWithAlpha=pn((e,t)=>Bs.colorWithAlpha(e,t),{max:1e3});getCachedColorIsDark=pn(e=>lh.isDark(e),{max:1e3});drawHeaders(e,t){const{theme:n}=t;e.font=n.headerFont,this.drawColumnHeaders(e,t),this.drawRowHeaders(e,t)}drawFooters(e,t){const{theme:n}=t;e.font=n.headerFont,this.drawRowFooters(e,t)}drawColumnHeaders(e,t){const{mouseX:n,mouseY:s,theme:i,metrics:o,draggingColumnSeparator:l,isDragging:a,model:d}=t,{columnHeaderHeight:h,floatingColumns:u,gridX:m,width:g,visibleColumns:p,allColumnWidths:C,allColumnXs:f,floatingLeftColumnCount:b,floatingLeftWidth:w,floatingRightWidth:S,modelColumns:T,columnHeaderMaxDepth:y}=o;if(h<=0)return;const{headerHiddenSeparatorSize:E,headerHiddenSeparatorHoverColor:R,headerSeparatorColor:x,headerSeparatorHoverColor:D}=i,M=h*.5,O=h*(y-1)+h*.5-M*.5,H=b>0;if(e.save(),this.drawColumnHeadersForRange(e,t,[p[0],p[p.length-1]],{minX:m+w,maxX:g-S}),H&&this.drawColumnHeadersForRange(e,t,[u[0],u[u.length-1]],{minX:m,maxX:m+w}),x){e.strokeStyle=x;const L=[...C.entries()].filter(([V,U])=>U===0).map(([V])=>V);e.beginPath(),e.fillStyle=x;for(let V=0;V<L.length;V+=1){const U=L[V],j=k(f,U),P=k(C,U),Q=m+j+P+.5-E*.5;e.rect(Q,O,E,M)}e.fill()}if(D){let{index:L,depth:V}=l??{};if(L==null&&n!=null&&s!=null){const j=uu.getColumnSeparator(_.getGridPointFromXY(n,s,o),o,d,i);L=j?.index,V=j?.depth}let U;if(L==null)U=!1;else{const j=T.get(L),P=T.get(L+1);j==null||P==null?U=!1:U=d.textForColumnHeader(j,V)!==d.textForColumnHeader(P,V)}if(U&&L!=null&&V!=null&&(!a||l!=null)){e.strokeStyle=D;const j=k(f,L),P=k(C,L),Q=m+j+P+.5,$=p.indexOf(L),J=$<p.length-1?p[$+1]:null,A=J!=null?C.get(J):null,W=P===0,q=A!=null&&A===0;W?(e.strokeStyle=R,e.fillStyle=R,e.fillRect(Q,O,E*.5,M)):q&&(e.fillStyle=D,e.fillRect(Q-E*.5,O,E*.5,M)),e.beginPath(),e.moveTo(Q,(y-V-1)*h),e.lineTo(Q,(y-V)*h-1),e.stroke()}}e.restore()}drawColumnHeadersForRange(e,t,n,s){const{model:i}=t,{columnHeaderMaxDepth:o}=i;if(o!==0)for(let l=0;l<=o;l+=1)this.drawColumnHeadersAtDepth(e,t,n,s,l)}drawColumnHeadersAtDepth(e,t,n,s,i){const{metrics:o,model:l,theme:a}=t,{modelColumns:d,allColumnXs:h,gridX:u,userColumnWidths:m,allColumnWidths:g,movedColumns:p}=o,{columnHeaderHeight:C,columnWidth:f}=a,{columnHeaderMaxDepth:b}=l,{minX:w,maxX:S}=s,T=S-w;if(b===0)return;const y=n[0],E=n[1];if(e.save(),e.translate(0,(b-i-1)*C),i===0){this.drawColumnHeader(e,t,"",w,S);for(let R=y;R<=E;R+=1)this.drawColumnHeaderAtIndex(e,t,R,s)}if(i>0){let R=y;for(;R<=E;){const{columnCount:x}=o,D=k(d,R),M=l.textForColumnHeader(D,i),O=l.colorForColumnHeader(D,i);let H=k(h,R)+u,L=H+k(g,R);if(M!=null){let V=R-1;for(;V>=0&&(L-H<T||H>w);){const Q=d.get(V)??_.getModelIndex(V,p);if(Q==null||l.textForColumnHeader(Q,i)!==M)break;const $=m.get(Q)??g.get(V)??f;H-=$,V-=1}let U=R+1;for(;U<x&&(L-H<T||L<S);){const Q=d.get(U)??_.getModelIndex(U,p);if(l.textForColumnHeader(Q,i)!==M)break;const $=m.get(Q)??g.get(U)??f;L+=$,U+=1}R=U-1;const j=L-H>=T;let P=H;j&&(L<S?P=L-T:H<w&&(P=w)),this.drawColumnHeader(e,t,M,P,Math.min(L-H,T),{backgroundColor:O??void 0},s)}R+=1}}e.restore()}drawColumnHeaderAtIndex(e,t,n,s){const{metrics:i,model:o}=t,{modelColumns:l,allColumnWidths:a,allColumnXs:d,gridX:h}=i,u=k(a,n),m=k(d,n)+h,g=k(l,n),p=o.textForColumnHeader(g);p!=null&&this.drawColumnHeader(e,t,p,m,u,{backgroundColor:o.colorForColumnHeader(g)??void 0},s)}drawColumnHeader(e,t,n,s,i,o,l){if(i<=0)return;const{metrics:a,theme:d}=t,{headerHorizontalPadding:h,columnHeaderHeight:u,headerBackgroundColor:m,headerColor:g,headerSeparatorColor:p,black:C,white:f}=d,{fontWidths:b,width:w}=a,S=b.get(e.font)??Zs,y=(i-h*2)/S,{backgroundColor:E=m,separatorColor:R=p}=o??{};let{textColor:x=g}=o??{};try{const W=this.getCachedColorIsDark(E),q=this.getCachedColorIsDark(x);W&&q?x=f:!W&&!q&&(x=C)}catch{}let{minX:D=0,maxX:M=w}=l??{};e.save(),e.rect(D,0,M-D,u),e.clip(),E!=null&&(e.fillStyle=E,e.fillRect(s,0,i,u)),R!=null&&(e.strokeStyle=R,e.beginPath(),s>0&&(e.moveTo(s+.5,0),e.lineTo(s+.5,u)),e.moveTo(s+i+.5,0),e.lineTo(s+i+.5,u),e.moveTo(s,u-.5),e.lineTo(s+i,u-.5),e.stroke()),e.beginPath(),e.rect(s,0,i,u),e.clip(),e.fillStyle=x;let O=n;y<=0?O="":O.length>y&&(O=`${O.substring(0,y-1)}…`);const H=O.length*S;let L=s+i*.5;const V=u*.5;D+=h,M-=h;const U=s+h,j=Oe(U,D,M),P=s+i-h,$=Oe(P,D,M)-j,J=L-H*.5<D,A=L+H*.5>M;J?H<$?L=D+H*.5:L=P-H*.5:A&&(H<$?L=M-H*.5:L=U+H*.5),e.textAlign="center",e.fillText(O,L,V),e.restore()}drawRowHeaders(e,t){const{mouseX:n,mouseY:s,metrics:i,theme:o,draggingRowSeparator:l}=t,{gridY:a,rowHeaderWidth:d,height:h,visibleRows:u,allRowHeights:m,allRowYs:g}=i;if(d<=0)return;const{headerBackgroundColor:p,headerColor:C,headerHiddenSeparatorSize:f,headerHiddenSeparatorHoverColor:b,headerSeparatorColor:w,headerSeparatorHoverColor:S}=o,T=d*.5,y=d*.5-T*.5;if(e.save(),e.beginPath(),e.fillStyle=p,e.fillRect(0,0,d,h),w){e.strokeStyle=w,e.beginPath(),e.moveTo(0,a+.5),e.lineTo(d,a+.5);const E=[];let R=!1;for(let x=0;x<u.length;x+=1){const D=u[x],M=k(g,D),O=k(m,D);if(O>0){const H=a+M+O+.5;e.moveTo(0,H),e.lineTo(d,H),R=!1}else R||(R=!0,E.push(D))}e.moveTo(d-.5,0),e.lineTo(d-.5,h),e.stroke(),e.beginPath(),e.fillStyle=w;for(let x=0;x<E.length;x+=1){const D=E[x],M=k(g,D),O=k(m,D),H=a+M+O+.5-f*.5;e.rect(y,H,T,f)}e.fill()}if(S){let{index:E=null}=l??{};if(E==null&&n!=null&&s!=null&&(E=_.getRowSeparatorIndex(n,s,i,o)),E!=null){e.strokeStyle=S;const R=k(g,E),x=k(m,E),D=a+R+x+.5,M=u.indexOf(E),O=M<u.length-1?u[M+1]:null,H=O!=null?m.get(O):null,L=x===0,V=H!=null&&H===0;L?(e.strokeStyle=b,e.fillStyle=b,e.fillRect(y,D,T,f*.5)):V&&(e.fillStyle=S,e.fillRect(y,D-f*.5,T,f*.5)),e.beginPath(),e.moveTo(.5,D),e.lineTo(d+.5,D),e.stroke()}}e.beginPath(),e.rect(0,a,d,h),e.clip(),e.fillStyle=C,e.textAlign="right";for(let E=0;E<u.length;E+=1){const R=u[E],x=k(m,R),D=k(g,R)+a;this.drawRowHeader(e,t,R,D,x)}e.restore()}drawRowHeader(e,t,n,s,i){if(i<=0)return;const{metrics:o,model:l,theme:a}=t,{modelRows:d,rowHeaderWidth:h}=o,u=k(d,n),m=h-a.cellHorizontalPadding,g=s+i*.5;e.fillText(l.textForRowHeader(u),m,g)}drawRowFooters(e,t){const{mouseX:n,mouseY:s,metrics:i,model:o,theme:l,draggingRowSeparator:a}=t,{gridY:d,gridX:h,maxX:u,modelRows:m,rowFooterWidth:g,height:p,verticalBarWidth:C,visibleRows:f,allRowHeights:b,allRowYs:w,width:S}=i;if(g<=0)return;const{cellHorizontalPadding:T,headerBackgroundColor:y,headerColor:E,headerHiddenSeparatorSize:R,headerHiddenSeparatorHoverColor:x,headerSeparatorColor:D,headerSeparatorHoverColor:M}=l,O=g*.5,H=g*.5-O*.5,L=Math.min(h+u,S-g-C);if(e.save(),e.beginPath(),e.fillStyle=y,e.fillRect(L,d,g,p),D){e.strokeStyle=D,e.beginPath(),e.moveTo(L,d+.5),e.lineTo(g,d+.5);const U=[];let j=!1;for(let P=0;P<f.length;P+=1){const Q=f[P],$=k(w,Q),J=k(b,Q);if(J>0){const A=d+$+J+.5;e.moveTo(L+.5,A),e.lineTo(L+g-.5,A),j=!1}else j||(j=!0,U.push(Q))}e.moveTo(L+.5,d),e.lineTo(L+.5,p),e.stroke(),e.beginPath(),e.fillStyle=D;for(let P=0;P<U.length;P+=1){const Q=U[P],$=k(w,Q),J=k(b,Q),A=d+$+J+.5-R*.5;e.rect(L+H,A,O,R)}e.fill()}if(M){let{index:U=null}=a??{};if(U==null&&n!=null&&s!=null&&(U=_.getRowSeparatorIndex(n,s,i,l)),U!=null){e.strokeStyle=M;const j=k(w,U),P=k(b,U),Q=d+j+P+.5,$=f.indexOf(U),J=$<f.length-1?f[$+1]:null,A=J!=null?b.get(J):null,W=P===0,q=A!=null&&A===0;W?(e.strokeStyle=x,e.fillStyle=x,e.fillRect(H,Q,O,R*.5)):q&&(e.fillStyle=M,e.fillRect(H,Q-R*.5,O,R*.5)),e.beginPath(),e.moveTo(L+.5,Q),e.lineTo(L+g+.5,Q),e.stroke()}}e.beginPath(),e.rect(L,d,g,p),e.clip(),e.fillStyle=E,e.textAlign="left";const V=L+T;for(let U=0;U<f.length;U+=1){const j=f[U],P=k(b,j);if(P>0){const Q=k(w,j)+d,$=k(m,j),J=Q+P*.5;e.fillText(o.textForRowFooter($),V,J)}}e.restore()}drawSelectedRanges(e,t,n={}){const{cursorColumn:s,cursorRow:i,draggingRow:o,draggingColumn:l,editingCell:a,metrics:d,model:h,selectedRanges:u,theme:m}=t,{allColumnWidths:g,allColumnXs:p,allRowHeights:C,allRowYs:f,width:b,height:w}=d,{left:S=d.left,top:T=d.top,right:y=d.right,bottom:E=d.bottom,minY:R=-10,maxY:x=w+10,minX:D=-10,maxX:M=b+10}=n;if(u.length===0)return;const O=Xe(h)&&h.isEditable&&a==null&&o==null&&l==null&&s!=null&&i!=null&&p.has(s)&&f.has(i);if(O){const H=k(p,s),L=k(f,i),V=k(g,s),U=k(C,i);e.save(),e.beginPath(),e.rect(0,0,b,w),e.rect(H,L,V,U),e.clip("evenodd")}e.beginPath();for(let H=0;H<u.length;H+=1){const L=u[H],V=L.startColumn!==null?L.startColumn:S,U=L.startRow!==null?L.startRow:T,j=L.endColumn!==null?L.endColumn:y,P=L.endRow!==null?L.endRow:E;if(P>=T&&E>=U&&j>=S&&y>=V){const Q=V>=S&&p.has(V)?Math.round(k(p,V))+.5:D,$=U>=T&&f.has(U)?Math.max(Math.round(k(f,U))+.5,.5):R,J=j<=y&&p.has(j)?Math.round(k(p,j)+k(g,j))-.5:M,A=P<=E&&f.has(P)?Math.round(k(f,P)+k(C,P))-.5:x;e.rect(Q,$,J-Q,A-$)}e.fillStyle=m.selectionColor,e.fill(),e.save(),e.clip(),e.strokeStyle=m.selectionOutlineCasingColor,e.lineWidth=3,e.stroke(),e.restore(),e.strokeStyle=m.selectionOutlineColor,e.lineWidth=1,e.stroke()}O&&s!=null&&i!=null&&(e.restore(),this.drawActiveCell(e,t,s,i))}drawActiveCell(e,t,n,s,i=fs.ACTIVE_CELL_BORDER_WIDTH){const{metrics:o,theme:l}=t,{allColumnWidths:a,allColumnXs:d,allRowHeights:h,allRowYs:u}=o,m=k(d,n),g=k(u,s),p=k(a,n),C=k(h,s);let f=m-i*.5,b=g-i*.5,w=p+i,S=C+i;f<=0&&(w+=f-1,f=1),b<=0&&(S+=b-1,b=1);const{lineWidth:T}=e;e.beginPath(),e.lineWidth=i,e.strokeStyle=l.selectionOutlineColor,this.drawRoundedRect(e,f,b,w,S),e.stroke(),e.lineWidth=T}drawRoundedRect(e,t,n,s,i,o=fs.DEFAULT_EDGE_RADIUS){e.beginPath(),e.moveTo(t+o,n),e.lineTo(t+s-o,n),e.quadraticCurveTo(t+s,n,t+s,n+o),e.lineTo(t+s,n+i-o),e.quadraticCurveTo(t+s,n+i,t+s-o,n+i),e.lineTo(t+o,n+i),e.quadraticCurveTo(t,n+i,t,n+i-o),e.lineTo(t,n+o),e.quadraticCurveTo(t,n,t+o,n),e.closePath()}drawDraggingColumn(e,t){const{draggingColumn:n,metrics:s,mouseX:i,theme:o,model:l}=t;if(n==null||i==null)return;const{range:a,depth:d}=n,{gridX:h,gridY:u,allColumnXs:m,allColumnWidths:g,height:p,width:C,columnHeaderMaxDepth:f,columnHeaderHeight:b,movedColumns:w,modelColumns:S,floatingLeftWidth:T}=s,y=S.get(a[0])??_.getModelIndex(a[0],w),E=l.getColumnHeaderGroup(y,d);if(d>0&&!E)return;const[R,x]=a,D=k(m,R),O=k(m,x)+k(g,x)-D,H=n.left,{backgroundColor:L,font:V,headerFont:U,reorderOffset:j,shadowBlur:P,shadowColor:Q}=o,$=(f-d-1)*b;e.save(),e.translate(h,0),e.save(),e.beginPath(),e.rect(T,0,C,p),e.clip(),e.fillStyle=L,e.fillRect(D,$,O,p),e.restore(),e.translate(0,j),e.save(),e.shadowColor=Q,e.shadowBlur=P,e.fillStyle=L,e.fillRect(n.left,$+j,n.width,p),e.restore(),e.beginPath(),e.rect(n.left,$,n.width+1,p),e.clip(),e.translate(H-D,0),e.font=U;const J=[];for(let A=n.range[0];A<=n.range[1];A+=1)J.push(A);this.drawColumnHeaders(e,t),this.drawColumnHeadersForRange(e,t,[J[0],J[J.length-1]],{minX:D,maxX:C}),e.translate(0,u),e.font=V,this.drawGridBackground(e,t);for(let A=R;A<=x;A+=1)this.drawColumnCellContents(e,t,A);e.restore()}drawDraggingRow(e,t){const{draggingRow:n,draggingRowOffset:s,metrics:i,mouseY:o,theme:l}=t;if(n==null||o==null)return;const{gridX:a,gridY:d,allRowYs:h,allRowHeights:u,width:m}=i,g=k(h,n),p=k(u,n)+1,{backgroundColor:C,font:f,headerFont:b,reorderOffset:w,shadowBlur:S,shadowColor:T}=l;e.save(),e.translate(0,d),e.fillStyle=C,e.fillRect(0,g,m,p),e.translate(a+w,o-g-d-(s??0)),e.save(),e.shadowColor=T,e.shadowBlur=S,e.fillStyle=C,e.fillRect(-a,g,m,p),e.restore(),e.beginPath(),e.rect(-a,g,m,p),e.clip(),e.font=f,this.drawGridBackground(e,t),this.drawCellContents(e,t),e.translate(-a,-d),e.font=b,this.drawRowHeaders(e,t),e.restore()}drawScrollBars(e,t){const{isDraggingHorizontalScrollBar:n,isDraggingVerticalScrollBar:s,isDragging:i,metrics:o,mouseX:l,mouseY:a,theme:d}=t;if(d.scrollBarSize<=0)return;const{width:h,height:u,handleHeight:m,handleWidth:g,scrollX:p,scrollY:C,hasHorizontalBar:f,hasVerticalBar:b,barWidth:w,barHeight:S,barLeft:T,barTop:y}=o,{scrollBarBackgroundColor:E,scrollBarHoverBackgroundColor:R,scrollBarCasingColor:x,scrollBarCornerColor:D,scrollBarColor:M,scrollBarHoverColor:O,scrollBarActiveColor:H,scrollBarSize:L,scrollBarHoverSize:V,scrollBarCasingWidth:U,scrollBarSelectionTick:j,scrollBarSelectionTickColor:P,scrollBarActiveSelectionTickColor:Q,autoSelectRow:$,autoSelectColumn:J}=d,A=l!=null&&a!=null&&l<=h&&a<=u,W=s||b&&!n&&!i&&l!=null&&a!=null&&l>=h-V&&a>=y&&A,q=n||f&&!s&&!i&&!W&&l!=null&&a!=null&&a>=u-V&&l>=T&&A,Z=q?V:L,le=W?V:L;if(e.translate(T,y),f&&b&&(e.fillStyle=x,e.fillRect(h-T-L,u-y-L,L,L),e.fillStyle=D,e.fillRect(h-T-L+U,u-y-L+U,L-U,L-U)),f){const G=p,oe=u-y-Z;if(e.fillStyle=x,e.fillRect(0,oe,w,Z-U),e.fillStyle=q?R:E,e.fillRect(0,oe+U,w,Z-U),n?e.fillStyle=H:q?e.fillStyle=O:e.fillStyle=M,e.fillRect(G,oe+U,g,Z-U),!$&&j&&P!=null&&Q!=null){e.fillStyle=P;const{selectedRanges:ue,cursorColumn:ae}=t,{lastLeft:ce,columnCount:we}=o,Fe=[...ue].filter(De=>De.startColumn!=null&&De.endColumn!=null).map(De=>[De.startColumn,De.endColumn]).sort(_.compareRanges),mt=_.mergeSortedRanges(Fe),et=De=>De<=ce?De/ce*(w-g):w-g+(De-ce)/(we-ce)*g;for(let De=0;De<mt.length;De+=1){const gt=mt[De],lt=gt[0],vt=gt[1];if(lt!=null&&vt!=null&&(lt!==ae||vt!==ae)){const kt=et(lt),Cn=Math.max(1,Math.round(et(vt+1)-kt)),zt=Z-U;e.fillRect(kt,oe+U+Math.round(zt/3),Cn,Math.round(zt/3))}}if(ae!=null){const De=et(ae),gt=2,lt=Z-U;e.fillStyle=Q,e.fillRect(De,oe+U,gt,lt)}}}if(b){const G=h-T-le,oe=C;if(e.fillStyle=x,e.fillRect(G,0,le-U,S),e.fillStyle=W?R:E,e.fillRect(G+U,0,le-U,S),s?e.fillStyle=H:W?e.fillStyle=O:e.fillStyle=M,e.fillRect(G+U,oe,le-U,m),!J&&j&&P!=null&&Q!=null){const{selectedRanges:ue,cursorRow:ae}=t,{lastTop:ce,rowCount:we}=o,He=De=>De<=ce?De/ce*(S-m):S-m+(De-ce)/(we-ce)*m;e.fillStyle=P;const mt=[...ue].filter(De=>De.startRow!=null&&De.endRow!=null).map(De=>[De.startRow,De.endRow]).sort(_.compareRanges),et=_.mergeSortedRanges(mt);for(let De=0;De<et.length;De+=1){const gt=et[De],lt=gt[0],vt=gt[1];if(lt!=null&&vt!=null&&(lt!==ae||vt!==ae)){const kt=He(lt),Cn=le-U,zt=Math.max(1,Math.round(He(vt+1)-kt));e.fillRect(G+U+Math.round(Cn/3),kt,Math.round(Cn/3),zt)}}if(ae!=null){const De=Math.round(He(ae)),gt=le-U,lt=2;e.fillStyle=Q,e.fillRect(G+U,De,gt,lt)}}}e.translate(-T,-y)}}const fu=fs,Zd=100;class US extends ht{startPoint;hasExtendedFloating=!1;timer;lastTriggerTime;dragBounds;onDown(e,t,n){const{x:s,y:i,column:o,row:l}=e,{metrics:a}=t;if(!a)throw new Error("metrics not set");const{gridX:d,gridY:h,maxX:u,maxY:m}=a,g=s-d,p=i-h;if(g<0||p<0||o==null&&g>u||l==null&&p>m)return!1;const C=_.isModifierKeyDown(n),f=n.shiftKey;C||(f?t.trimSelectedRanges():t.clearSelectedRanges());const b=t.getTheme(),{autoSelectRow:w,autoSelectColumn:S}=b;return(o!==null||!S)&&(l!==null||!w)&&(t.focus(),t.moveCursorToPosition(o,l,f,!1,f&&C)),this.startPoint=e,this.hasExtendedFloating=!1,this.dragBounds=_.getScrollDragBounds(a,l,o),!0}onDrag(e,t){if(this.startPoint===void 0)return!1;this.stopTimer();const{row:n,column:s}=this.startPoint,{x:i,y:o}=e;let{row:l,column:a}=e;const{metrics:d}=t;if(!d)throw new Error("metrics not set");const{left:h,lastLeft:u,top:m,lastTop:g,columnWidth:p,rowHeight:C}=d,f=_.getScrollDragBounds(d,n,s);let b=0,w=0;if(h<u&&(i<f.x1?b=i-f.x1:i>f.x2&&(b=i-f.x2)),m<g&&(o<f.y1?w=o-f.y1:o>f.y2&&(w=o-f.y2)),b!==0||w!==0)this.startTimer(t,e,b>0?Math.ceil(b/p):Math.floor(b/p),w>0?Math.ceil(w/C):Math.floor(w/C));else if(l!=null&&a!=null){const{floatingTopRowCount:S,floatingBottomRowCount:T,floatingLeftColumnCount:y,floatingRightColumnCount:E,columnCount:R,rowCount:x,bottom:D,right:M,topVisible:O,bottomVisible:H,leftVisible:L,rightVisible:V}=d;this.hasExtendedFloating||(n!==null&&n<S&&l>=S?(l=S,this.hasExtendedFloating=!0):n!==null&&n>=x-T&&l<x-T&&(l=x-T-1,this.hasExtendedFloating=!0),s!==null&&s<y&&a>=y?(a=y,this.hasExtendedFloating=!0):s!==null&&s>=R-E&&a<R-E&&(a=R-E-1,this.hasExtendedFloating=!0)),n!==null&&!_.isFloatingRow(n,d)&&_.isFloatingRow(l,d)&&(n>l&&l<m?l=O-1:n<l&&l>D&&(l=H+1)),s!==null&&!_.isFloatingColumn(s,d)&&_.isFloatingColumn(a,d)&&(s>a&&a<h?a=L-1:s<a&&a>M&&(a=V+1)),t.moveCursorToPosition(a,l,!0,!0)}return!0}onUp(e,t){return this.startPoint!==void 0&&(this.startPoint=void 0,this.dragBounds=void 0,this.stopTimer(),t.commitSelection()),!1}moveSelection(e,t,n,s){const{row:i,column:o}=t,{metrics:l}=e;if(!l)throw new Error("metrics not set");const{selectionEndRow:a,selectionEndColumn:d}=e.state;if(a==null||d==null)throw new Error("selection not set");const{rowCount:h,columnCount:u}=l,m=n<0&&o!=null?o:0,g=n>0&&o!=null?o:u-1,p=s<0&&i!=null?i:0,C=s>0&&i!=null?i:h-1;e.moveCursorToPosition(Math.min(Math.max(m,d+n),g),Math.min(Math.max(p,a+s),C),!0),this.lastTriggerTime=Date.now()}startTimer(e,t,n,s){this.stopTimer();const i=this.lastTriggerTime!=null?Zd-Math.min(Zd,Date.now()-this.lastTriggerTime):0;this.timer=setTimeout(()=>{this.moveSelection(e,t,n,s),this.startTimer(e,t,n,s)},i)}stopTimer(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}}const VS=US,Qd=5,$S=1e3/60,Vo=10;function is(c,e,t,n){const{modelColumns:s,movedColumns:i,allColumnXs:o,columnCount:l,allColumnWidths:a,userColumnWidths:d,calculatedColumnWidths:h,floatingLeftWidth:u,maxX:m}=t;if(e==null||c==null||c>l||c<0)return null;const g=s.get(c)??_.getModelIndex(c,i),p=n.getColumnHeaderGroup(g,e),C=p!=null;let f,b,w;if(p!=null){const[S,T]=p.getVisibleRange(i);f=o.get(S)??u,b=(o.get(T)??m)+(a.get(T)??0),w=[S,T]}else{const S=o.get(c);if(S==null)return null;f=S,b=f+(a.get(c)??d.get(g)??h.get(g)??0),w=[c,c]}return{visibleIndex:c,modelIndex:g,left:f,right:b,width:b-f,isColumnGroup:C,range:w,depth:e}}class WS extends ht{cursor=null;draggingOffset;initialOffset;initialGridPoint;scrollingInterval;scrollingDirection;draggingColumn=null;setScrollInterval(e,t){this.scrollingInterval!=null&&t===this.scrollingDirection||(this.scrollingDirection=t,this.scrollingInterval=window.setInterval(()=>{const{metrics:n}=e;if(!n)return;const{left:s,lastLeft:i,leftOffset:o,userColumnWidths:l,calculatedColumnWidths:a,movedColumns:d,allColumnWidths:h}=n;let u=s,m=o;if(t==="left")for(m-=Vo;m<0;){u-=1;const C=_.getModelIndex(s-1,d),f=l.get(C)??a.get(C);f===void 0?m=0:m+=f,u<0&&(m=0,u=0)}else{m+=Vo;let C=h.get(s);for(;C!==void 0&&m>C;){u+=1,m-=C;const f=_.getModelIndex(s+1,d);C=l.get(f)??a.get(f),u>i&&(m=0,u=i)}}const{mouseX:g,mouseY:p}=e.state;n==null||g==null||p==null||(this.moveDraggingColumn(g,e,t==="left"?-Vo:Vo),e.setState({left:u,leftOffset:m}),(t==="left"&&u===0&&o===0||t==="right"&&u===i)&&this.clearScrollInterval())},$S))}clearScrollInterval(){this.scrollingDirection=void 0,window.clearInterval(this.scrollingInterval),this.scrollingInterval=void 0}onLeave(){return this.clearScrollInterval(),!1}onDown(e,t){const{model:n}=t.props,{x:s,column:i,columnHeaderDepth:o}=e,{metrics:l}=t;if(!l)throw new Error("Metrics not set");const a=is(i,o,l,n);if(i==null||a==null||o==null||o>0&&!a.isColumnGroup)return!1;const{rowHeaderWidth:d}=l;return this.initialGridPoint=e,this.draggingColumn=null,this.cursor=null,a.modelIndex!=null&&o!=null&&n.isColumnMovable(a.modelIndex,o)&&(this.draggingOffset=s-a.left-d,this.initialOffset=this.draggingOffset),!1}onDrag(e,t,n){if(this.draggingOffset===void 0||this.initialGridPoint===void 0||this.initialOffset===void 0)return!1;const{x:s,y:i}=e,{columnHeaderDepth:o}=this.initialGridPoint,{model:l}=t.props;let{draggingColumn:a}=this;const{metrics:d}=t;if(!d)throw new Error("Metrics not set");if(!a&&Math.abs(this.initialGridPoint.x-s)<Qd&&Math.abs(this.initialGridPoint.y-i)<Qd)return!1;if(a==null){const h=is(this.initialGridPoint.column,o,d,l);if(!h||o==null||!l.isColumnMovable(h.modelIndex)||o>0&&!h.isColumnGroup||h.range[0]==null)return!1;a={range:h.range,depth:o,left:h.left,width:h.width};const u=is(a.range[0],0,d,l),m=is(a.range[1],0,d,l);if(!u||!m)return!1;this.draggingColumn=a,t.setState({draggingColumn:a,isDragging:!0})}return this.cursor="move",this.moveDraggingColumn(e.x,t,n.movementX),!0}moveDraggingColumn(e,t,n){if(this.draggingOffset===void 0||this.initialGridPoint===void 0||this.initialOffset===void 0||this.draggingColumn==null||n===0)return;if(this.initialOffset!==this.draggingOffset){this.draggingOffset<this.initialOffset&&this.initialOffset<this.draggingOffset+n||this.draggingOffset>this.initialOffset&&this.initialOffset>this.draggingOffset+n?this.draggingOffset=this.initialOffset:this.draggingOffset+=n,this.draggingColumn={...this.draggingColumn,left:e-this.draggingOffset},t.setState({draggingColumn:this.draggingColumn});return}const{depth:s}=this.draggingColumn,{model:i}=t.props,{movedColumns:o}=t.state,{metrics:l}=t;if(!l)throw new Error("Metrics not set");const{floatingLeftWidth:a,width:d,columnHeaderMaxDepth:h,allColumnXs:u}=l,m=n<0,g=is(this.draggingColumn.range[0],s,l,i);if(!g)return;const p=e-this.draggingOffset,C=p+g.width;this.draggingColumn={...this.draggingColumn,left:p},t.setState({draggingColumn:this.draggingColumn});const f=is(_.getColumnAtX(Oe(m?p:C,a,d),l,!0),s,l,i),b=i.getColumnHeaderParentGroup(g.modelIndex,g.depth);if(!f)return;if(b!==void 0){const R=b.getVisibleRange(o);if(f.visibleIndex<R[0]){const x=this.moveColumn(g,R[0],o);this.draggingOffset=e-(u.get(R[0])??0),this.draggingColumn={...this.draggingColumn,left:e-this.draggingOffset},this.clearScrollInterval(),t.setState({draggingColumn:this.draggingColumn,movedColumns:x});return}if(f.visibleIndex>R[1]){const x=this.moveColumn(g,R[1]-(g.range[1]-g.range[0]),o),{right:D=0}=is(R[1],0,l,i)??{};this.draggingOffset=e-(D-g.width),this.draggingColumn={...this.draggingColumn,left:e-this.draggingOffset},this.clearScrollInterval(),t.setState({draggingColumn:this.draggingColumn,movedColumns:x});return}}if(!i.isColumnMovable(f.modelIndex)){let R=f.visibleIndex;if(m)for(R+=1;R<g.visibleIndex&&!i.isColumnMovable(_.getModelIndex(R,o));)R+=1;else for(R-=1;R>g.visibleIndex&&!i.isColumnMovable(_.getModelIndex(R,o));)R-=1;if(R!==g.visibleIndex){m||(R-=g.range[1]-g.range[0]);const D=this.moveColumn(g,R,o);t.setState({movedColumns:D,draggingColumn:this.draggingColumn})}const x=is(R,0,l,i);m?this.draggingOffset=e-(x?.left??0):this.draggingOffset=e-((x?.right??0)-g.width),this.draggingColumn={...this.draggingColumn,left:e-this.draggingOffset},t.setState({draggingColumn:this.draggingColumn});return}if(p<=a?this.setScrollInterval(t,"left"):C>d?this.setScrollInterval(t,"right"):this.clearScrollInterval(),f.visibleIndex===g.visibleIndex||m&&g.visibleIndex<f.visibleIndex||!m&&g.visibleIndex>f.visibleIndex)return;const w=f.left+f.width*.5,S=i.getColumnHeaderParentGroup(g.modelIndex,g.depth);let T,y=(S?.depth??h)-1;for(;y>=0&&T===void 0;)T=i.getColumnHeaderGroup(f.modelIndex,y),y-=1;let E;m&&p<w&&(!T||f.visibleIndex===T.getVisibleRange(o)[0])&&(E=this.moveColumn(g,f.range[0],o)),!m&&C>w&&(!T||f.visibleIndex===T.getVisibleRange(o)[1])&&(E=this.moveColumn(g,f.range[1]-(g.range[1]-g.range[0]),o)),E&&(this.draggingColumn={...this.draggingColumn,left:p},t.setState({movedColumns:E,draggingColumn:this.draggingColumn}))}moveColumn(e,t,n){const s=e.isColumnGroup?_.moveRange(e.range,t,n):_.moveItem(e.visibleIndex,t,n),i=t-e.range[0],o=[e.range[0]+i,e.range[1]+i];return this.draggingColumn&&(this.draggingColumn={...this.draggingColumn,range:o}),s}onUp(e,t){return this.cursor=null,this.clearScrollInterval(),this.draggingOffset!=null?(this.draggingOffset=void 0,t.setState({draggingColumn:null,isDragging:!1}),!0):!1}}const GS=WS;class Lr extends ht{static getLeftWithOffsetFromRawLeft(e,t){const n=e.getTheme(),{metrics:s,metricCalculator:i}=e;if(!s)throw new Error("metrics not set");if(n.scrollSnapToColumn)return{left:Math.round(t),leftOffset:0};const o=Math.floor(t),l=t-o;let a=s.allColumnWidths.get(o);if(a==null){const h=e.getMetricState();a=i.getVisibleColumnWidth(o,h)}const d=a*l;return{left:o,leftOffset:d}}dragOffset;cursor="default";isInScrollBar(e,t){const n=t.getTheme(),{scrollBarSize:s,scrollBarHoverSize:i}=n,{metrics:o}=t;if(!o)throw new Error("metrics not set");const{x:l,y:a}=e,{barLeft:d,barWidth:h,height:u,hasHorizontalBar:m}=o;return m&&s>0&&a>=u-i&&a<u&&l>d&&l<d+h}getLeftWithOffset(e,t){const{metrics:n}=t;if(!n)throw new Error("metrics not set");const{x:s}=e,{barWidth:i,handleWidth:o,lastLeft:l,barLeft:a,columnCount:d,scrollableContentWidth:h,scrollableViewportWidth:u}=n,m=s-a,g=Oe((m-(this.dragOffset??0))/(i-o),0,1);if(d===1)return{left:0,leftOffset:g*(h-u)};const p=g*l;return Lr.getLeftWithOffsetFromRawLeft(t,p)}onDown(e,t){const{metrics:n}=t;if(!n)throw new Error("metrics not set");const{x:s}=e,{handleWidth:i,barLeft:o,scrollX:l}=n;if(!this.isInScrollBar(e,t))return!1;const a=s-o;if(a>=l&&a<=l+i)this.dragOffset=a-l,t.setState({isDraggingHorizontalScrollBar:!0});else{this.dragOffset=0;const{left:d,leftOffset:h}=this.getLeftWithOffset(e,t);t.setViewState({left:d,leftOffset:h,isDraggingHorizontalScrollBar:!0,isDragging:!0})}return!0}onDrag(e,t){if(this.dragOffset!=null){const{left:n,leftOffset:s}=this.getLeftWithOffset(e,t);return t.setViewState({left:n,leftOffset:s,isDraggingHorizontalScrollBar:!0,isDragging:!0}),!0}return!1}onMove(e,t){return this.isInScrollBar(e,t)}onUp(e,t){return this.dragOffset!==void 0&&(this.dragOffset=void 0,t.setState({isDraggingHorizontalScrollBar:!1,isDragging:!1})),this.isInScrollBar(e,t)}onClick(e,t){return this.isInScrollBar(e,t)}}const zS=Lr;class KS extends ht{cursor="move";draggingOffset;onDown(e,t){const{model:n}=t.props,{x:s,y:i,row:o}=e,{metrics:l}=t;if(!l)throw new Error("metrics not set");const{columnHeaderHeight:a,rowHeaderWidth:d,allRowYs:h}=l;if(s<=d&&o!==null&&n.isRowMovable(o)){const u=k(h,o);this.draggingOffset=i-u-a,t.setState({draggingRowOffset:this.draggingOffset})}return!1}onDrag(e,t){if(this.draggingOffset==null)return!1;const{model:n}=t.props;let{draggingRow:s}=t.state;const{mouseX:i,mouseY:o}=t.state;if(i==null||o==null)return!1;if(s==null){const{row:E}=t.getGridPointFromXY(i,o);if(E!=null&&!n.isRowMovable(E)||(s=E,t.setState({draggingRow:s,isDragging:!0}),s==null))return!1}const{metrics:l}=t;if(!l)throw new Error("metrics not set");const{top:a,lastTop:d,bottom:h,bottomVisible:u,rowCount:m,columnHeaderHeight:g,allRowHeights:p,allRowYs:C,height:f}=l;let b=g;if(a<s){const E=s-1;b=k(C,E)+k(p,E)*.5+g}let w=f;if(s<h){const E=s+1;w=k(C,E)+k(p,E)*.5+g}let{movedRows:S}=t.state;o<b&&s>0&&n.isRowMovable(s-1)?(S=_.moveItem(s,s-1,S),s-=1):w<o&&s<m-1&&n.isRowMovable(s+1)&&(S=_.moveItem(s,s+1,S),s+=1),t.setState({movedRows:S,draggingRow:s});const T=g+k(p,a)*.5,y=g+k(C,u)+k(p,u)*.5;return o<T&&a>0?t.setState({top:a-1}):o>y&&a<d&&t.setState({top:a+1}),!0}onUp(e,t){return this.draggingOffset!==void 0?(this.draggingOffset=void 0,t.setState({draggingRowOffset:null,draggingRow:null,isDragging:!1}),!0):!1}}const YS=KS;class Or extends hu{static getRowSeparator(e,t,n,s){if(!s.allowRowResize)return null;const{x:i,y:o}=e,l=_.getRowSeparatorIndex(i,o,t,s);return l!=null?{index:l,depth:0}:null}hiddenCursor="s-resize";defaultCursor="row-resize";pointProperty="y";userSizesProperty="userRowHeights";visibleOffsetProperty="visibleRowYs";visibleSizesProperty="visibleRowHeights";marginProperty="columnHeaderHeight";calculatedSizesProperty="calculatedRowHeights";initialSizesProperty="initialRowHeights";modelIndexesProperty="modelRows";firstIndexProperty="firstRow";treePaddingProperty="treePaddingY";getHiddenItems=_.getHiddenRows;getNextShownItem=_.getNextShownRow;setSize(e,t,n){e.setRowHeight(t,n)}resetSize(e,t){e.resetRowHeight(t)}updateSeparator(e,t){e.setState({draggingRowSeparator:t,isDragging:t!==null})}getSeparator=Or.getRowSeparator}const qS=Or;class vl extends ht{static isInTreeBox(e,t){const{column:n,row:s,x:i,y:o}=e,{metrics:l}=t;if(!l)throw new Error("metrics not set");const{gridX:a,gridY:d,firstColumn:h,allColumnXs:u,allColumnWidths:m,allRowHeights:g,allRowYs:p,visibleRowTreeBoxes:C}=l;if(n===h&&s!=null&&C.get(s)!=null&&i>a&&o>d){const f=k(u,n),b=k(m,n),w=k(p,s),S=k(g,s);if(i>=a+f&&i<=a+f+b&&o>=d+w&&o<=d+w+S)return!0}return!1}onDown(e,t){return vl.isInTreeBox(e,t)}onClick(e,t,n){if(vl.isInTreeBox(e,t)){const{row:s}=e;if(s!==null)return t.toggleRowExpanded(s,_.isModifierKeyDown(n)),!0}return!1}}const Xa=vl;class XS extends ht{isInCorner(e,t){const n=t.getTheme(),{scrollBarSize:s}=n,{metrics:i}=t;if(!i)throw new Error("metrics not set");const{x:o,y:l}=e,{width:a,height:d,hasVerticalBar:h,hasHorizontalBar:u}=i;return s>0&&h&&u&&o>=a-s&&l>=d-s&&o<=a&&l<=d}onDown(e,t){return this.isInCorner(e,t)}onUp(e,t){return this.isInCorner(e,t)}onClick(e,t){return this.isInCorner(e,t)}}const ZS=XS;class Ar extends ht{static getTopWithOffsetFromRawTop(e,t){const n=e.getTheme(),{metrics:s,metricCalculator:i}=e;if(!s)throw new Error("metrics not set");if(n.scrollSnapToRow)return{top:Math.round(t),topOffset:0};const o=Math.floor(t),l=t-o;let a=s.allRowHeights.get(o);if(a==null){const h=e.getMetricState();a=i.getVisibleRowHeight(o,h)}const d=a*l;return{top:o,topOffset:d}}dragOffset;cursor="default";isInScrollBar(e,t){const n=t.getTheme(),{scrollBarSize:s,scrollBarHoverSize:i}=n,{metrics:o}=t;if(!o)throw new Error("metrics not set");const{x:l,y:a}=e,{barTop:d,barHeight:h,width:u,hasVerticalBar:m}=o;return m&&s>0&&l>=u-i&&l<u&&a>d&&a<d+h}getTopWithOffset(e,t){const{metrics:n}=t;if(!n)throw new Error("metrics not set");const{y:s}=e,{barHeight:i,handleHeight:o,lastTop:l,barTop:a,rowCount:d,scrollableContentHeight:h,scrollableViewportHeight:u}=n,m=s-a,g=Oe((m-(this.dragOffset??0))/(i-o),0,1);if(d===1)return{top:0,topOffset:g*(h-u)};const p=g*l;return Ar.getTopWithOffsetFromRawTop(t,p)}onDown(e,t){const{metrics:n}=t;if(!n)throw new Error("metrics not set");const{y:s}=e,{handleHeight:i,barTop:o,scrollY:l}=n;if(!this.isInScrollBar(e,t))return!1;const a=s-o;if(a>=l&&a<=l+i)this.dragOffset=a-l,t.setState({isDraggingVerticalScrollBar:!0});else{this.dragOffset=0;const{top:d,topOffset:h}=this.getTopWithOffset(e,t);t.setViewState({top:d,topOffset:h,isDraggingVerticalScrollBar:!0,isDragging:!0})}return!0}onMove(e,t){return this.isInScrollBar(e,t)}onDrag(e,t){if(this.dragOffset!=null){const{top:n,topOffset:s}=this.getTopWithOffset(e,t);return t.setViewState({top:n,topOffset:s,isDraggingVerticalScrollBar:!0,isDragging:!0}),!0}return!1}onUp(e,t){return this.dragOffset!==void 0&&(this.dragOffset=void 0,t.setState({isDraggingVerticalScrollBar:!1,isDragging:!1})),this.isInScrollBar(e,t)}onClick(e,t){return this.isInScrollBar(e,t)}}const QS=Ar;class JS extends ht{onDoubleClick({column:e,row:t},n){const{model:s}=n.props;return Xe(s)&&e!=null&&t!=null&&s.isEditableRange(Ie.makeCell(e,t))?(n.startEditing(e,t),!0):!1}}const ew=JS;function Cu(c){return c?.getTokenBoxesForVisibleCell!==void 0}class _r extends ht{timeoutId;isHold=!1;isDown=!1;currentLinkBox;static HOLD_LENGTH=1e3;isHoveringLink(e,t){const{column:n,row:s,x:i,y:o}=e,{renderer:l,metrics:a,props:d}=t,{model:h}=d;if(n==null||s==null||a==null)return this.currentLinkBox=void 0,!1;const{modelRows:u,modelColumns:m}=a,g=k(u,s),p=k(m,n),C=h.renderTypeForCell(p,g),f=l.getCellRenderer(C);if(!Cu(f))return!1;if(this.currentLinkBox!=null){const{x1:S,y1:T,x2:y,y2:E}=this.currentLinkBox;if(i>=S&&i<=y&&o>=T&&o<=E)return!0}const b=t.updateRenderState(),w=f.getTokenBoxesForVisibleCell(n,s,b);for(let S=0;S<w.length;S+=1)if(wl(w[S].token)){const T=_.translateTokenBox(w[S],a),{x1:y,x2:E,y1:R,y2:x}=T;if(i>=y&&i<=E&&o>=R&&o<=x)return this.currentLinkBox=T,!0}return this.currentLinkBox=void 0,!1}setCursor(e,t){return this.isHoveringLink(e,t)?this.cursor="pointer":this.cursor=null,!1}onMove(e,t){return this.setCursor(e,t)}onDown(e,t,n){const s=this.isHoveringLink(e,t);return _.isModifierKeyDown(n)||n.shiftKey||!s?!1:(this.isDown=!0,this.timeoutId!=null&&clearTimeout(this.timeoutId),this.isHold=!1,this.timeoutId=setTimeout(()=>{this.isHold=!0;const{column:i,row:o}=e,{model:l}=t.props;t.clearSelectedRanges(),t.focus(),t.moveCursorToPosition(i,o),Xe(l)&&i!=null&&o!=null&&l.isEditableRange(Ie.makeCell(i,o))&&t.startEditing(i,o)},_r.HOLD_LENGTH),!0)}onClick(e,t){return!this.isHoveringLink(e,t)||!this.isDown||this.currentLinkBox==null?(this.isDown=!1,this.isHold=!1,!1):(this.isHold||(this.timeoutId!=null&&clearTimeout(this.timeoutId),this.timeoutId=void 0,t.props.onTokenClicked(this.currentLinkBox?.token)),this.isHold=!1,this.isDown=!1,!0)}}const tw=_r;class nw{order;constructor(e=5e3){this.order=e}onDown(e,t){return!1}}const ei=nw;class sw extends ei{onDown(e,t){switch(e.key){case"a":if(_.isModifierKeyDown(e))return t.selectAll(),!0;break;case"ArrowUp":return this.handleArrowMove(0,-1,e,t);case"ArrowDown":return this.handleArrowMove(0,1,e,t);case"ArrowRight":return this.handleArrowMove(1,0,e,t);case"ArrowLeft":return this.handleArrowMove(-1,0,e,t);case"k":case"K":return _.isModifierKeyDown(e)?!1:this.handlePageUp(e,t);case"j":case"J":return _.isModifierKeyDown(e)?!1:this.handlePageDown(e,t);case"h":case"H":return _.isModifierKeyDown(e)?!1:(e.shiftKey||t.clearSelectedRanges(),t.moveCursorToPosition(0,t.state.cursorRow,e.shiftKey),!0);case"l":case"L":{if(_.isModifierKeyDown(e))return!1;const{model:n}=t.props,{columnCount:s}=n;return e.shiftKey||t.clearSelectedRanges(),t.moveCursorToPosition(s-1,t.state.cursorRow,e.shiftKey),!0}case"PageDown":return this.handlePageDown(e,t);case"PageUp":return this.handlePageUp(e,t);case"Home":return e.shiftKey||t.clearSelectedRanges(),t.moveCursorToPosition(_.isModifierKeyDown(e)?t.state.cursorColumn:0,_.isModifierKeyDown(e)?0:t.state.cursorRow,e.shiftKey,!0,!0),!0;case"End":{const{model:n}=t.props,{columnCount:s,rowCount:i}=n;return e.shiftKey||t.clearSelectedRanges(),t.moveCursorToPosition(_.isModifierKeyDown(e)?t.state.cursorColumn:s-1,_.isModifierKeyDown(e)?i-1:t.state.cursorRow,e.shiftKey,!0,!0),!0}case"Escape":return t.clearSelectedRanges(),{preventDefault:!1,stopPropagation:!1};case"Enter":if(t.state.selectedRanges.length>0)return t.moveCursorInDirection(e.shiftKey?Ie.SELECTION_DIRECTION.UP:Ie.SELECTION_DIRECTION.DOWN),!0;break;case"Tab":if(t.state.selectedRanges.length>0)return t.moveCursorInDirection(e.shiftKey?Ie.SELECTION_DIRECTION.LEFT:Ie.SELECTION_DIRECTION.RIGHT),!0;break}return!1}handleArrowMove(e,t,n,s){const i=n.shiftKey,o=_.isModifierKeyDown(n);i?s.trimSelectedRanges():s.clearSelectedRanges();const{cursorRow:l,cursorColumn:a,selectionEndColumn:d,selectionEndRow:h}=s.state,u=i?d:a,m=i?h:l;if(o){const{model:g}=s.props,{columnCount:p,rowCount:C}=g,f=o&&i;let b=null,w=null;e<0?(b=0,w=m):e>0?(b=p-1,w=m):t<0?(b=u,w=0):t>0&&(b=u,w=C-1),b!=null&&w!=null&&s.moveCursorToPosition(b,w,i,!0,f)}else{if(!s.metrics)throw new Error("grid.metrics are not set");const{theme:g}=s.props,{autoSelectRow:p=!1,autoSelectColumn:C=!1}=g;if(p&&e!==0){const{lastLeft:f}=s.metrics;let{left:b}=s.state;b=Oe(b+e,0,f),s.moveCursorToPosition(b,l,i,!1),s.setViewState({left:b})}else if(C&&t!==0){const{lastTop:f}=s.metrics;let{top:b}=s.state;b=Oe(b+t,0,f),s.moveCursorToPosition(b,a,i,!1),s.setViewState({top:b})}else s.moveCursor(e,t,i)}return!0}handlePageUp(e,t){const n=e.shiftKey;n?t.trimSelectedRanges():t.clearSelectedRanges();const{cursorColumn:s,selectionEndRow:i}=t.state,o=i,l=s;if(o==null)return!1;const a=t.getMetricState(),{metricCalculator:d}=t,{bottomVisible:h,topVisible:u,hasHorizontalBar:m}=d.getMetrics(a);let g=o-(h-u);g-=m?0:1,g=Math.max(g,0);const p=Math.max(g-(o-u),0);return t.moveCursorToPosition(l,g,n,!1),t.setViewState({top:p}),!0}handlePageDown(e,t){const n=e.shiftKey;n?t.trimSelectedRanges():t.clearSelectedRanges();const{selectionEndRow:s,cursorColumn:i}=t.state,o=s,l=i;if(o===null)return!1;const a=t.getMetricState(),{metricCalculator:d}=t,{bottomVisible:h,topVisible:u,hasHorizontalBar:m,rowCount:g,lastTop:p}=d.getMetrics(a),C=g-1;let f=h-u+o;f+=m?0:1,f=Math.min(f,C);const b=Math.min(p,f-(o-u));return t.moveCursorToPosition(l,f,n,!1),t.setViewState({top:b}),!0}}const iw=sw;class ow extends ei{onDown(e,t){switch(e.key){case"Enter":case" ":return this.handleExpandKey(e,t)}return!1}handleExpandKey(e,t){const{selectedRanges:n}=t.state;if(n.length===1){const s=n[0];if(s.startRow===s.endRow&&s.startColumn===s.endColumn){if(!t.metrics)throw new Error("grid.metrics not set");const{model:i}=t.props,{startRow:o,startColumn:l}=s;if(o!=null){const a=t.getModelRow(o);if((l===0||l==null)&&je(i)&&i.isRowExpandable(a))return t.toggleRowExpanded(o),!0}}}return!1}}const lw=ow;class aw extends ei{onDown(e,t){if(_.isModifierKeyDown(e))return!1;const{model:n}=t.props,{cursorColumn:s,cursorRow:i}=t.state;if(s==null||i==null||!Xe(n)||!n.isEditableRange(Ie.makeCell(s,i)))return!1;const o=s,l=i;return o==null||l==null?!1:e.key.length===1?(t.startEditing(o,l,!0,[1,1],e.key),!0):e.key==="F2"?(t.startEditing(o,l),!0):e.key==="Backspace"?(t.startEditing(o,l,!0,void 0,""),!0):e.key==="Delete"?(t.setValueForCell(o,l,""),!0):!1}}const rw=aw;function dw(c){const e=[],t=c.querySelectorAll("tr");for(let n=0;n<t.length;n+=1){const i=t[n].querySelectorAll("td"),o=[];for(let l=0;l<i.length;l+=1){const a=i[l];o.push(a.textContent?.trim()??"")}e.push(o)}return e}function cw(c){const e=[];return c.forEach(t=>{const n=t.textContent??"";n.length>0&&e.push(n.split(/\t|\u00a0\u00a0 \u00a0/))}),e}function hw(c){const e=c.querySelector("table");if(e!=null)return dw(e);const t=c.textContent?.trim()??"";if(t.length>0){const{childNodes:n}=c,s=t.includes(" "),i=t.includes("    ");return s&&n.length!==0&&(n.length===1||n.length>1&&(n[0].textContent==null||!n[0].textContent.includes(" ")))?t.split(`
18
+ `)}this.bufferedMessages=[],this.appendLogText(e)}queue(e){this.bufferedMessages.push(e),this.bufferedMessages.length===1&&(this.flushTimer=setTimeout(this.handleFlushTimeout,Rt.bufferTimeout))}stopFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}updateDimensions(){this.editor&&this.editor.layout()}handleClearClick(){this.clearLogs()}clearLogs(){this.messages=[],this.refreshLogText()}handleFlushTimeout(){this.stopFlushTimer(),this.flush()}handleLogMessage(e){this.messages.push(e),this.editor&&this.isLogItemVisible(e)&&this.queue(e)}handleMenuItemClick(e){this.toggleLogLevel(e)}handleResetClick(){this.resetLogLevels()}handleResize(){this.updateDimensions()}handleToggleAllClick(){this.toggleAll()}render(){const e={placement:"bottom-end"},{shownLogLevels:t}=this.state,n=this.getMenuActions(t);return r.jsxs("div",{className:"log-pane h-100 w-100",children:[r.jsxs("div",{className:"log-pane-menu",children:[r.jsx(B,{kind:"ghost",className:"btn-clear-logs",onClick:this.handleClearClick,icon:dg,tooltip:"Clear log"}),r.jsx(B,{kind:"ghost",className:"btn-link-icon btn-overflow",icon:mo,tooltip:"Log Settings",onClick:()=>{},children:r.jsx(Vn,{actions:n,popperClassName:"log-level-menu-popper",popperOptions:e})})]}),r.jsx("div",{className:"log-pane-editor h-100 w-100",ref:s=>{this.editorContainer=s}})]})}}const Qf=Rt;function ph(c){switch(c){case be.eq:return"is exactly";case be.eqIgnoreCase:return"is exactly (ignore case)";case be.notEq:return"is not exactly";case be.notEqIgnoreCase:return"is not exactly (ignore case)";case be.contains:return"contains";case be.notContains:return"does not contain";case be.startsWith:return"starts with";case be.endsWith:return"ends with";default:throw new Error(`Unrecognized text filter type ${c}`)}}function fh(c){switch(c){case be.eq:return"is equal to";case be.notEq:return"is not equal to";case be.greaterThan:return"greater than";case be.greaterThanOrEqualTo:return"greater than or equal to";case be.lessThan:return"less than";case be.lessThanOrEqualTo:return"less than or equal to";default:throw new Error(`Unrecognized number filter type ${c}`)}}function Ch(c){switch(c){case be.eq:return"date is";case be.notEq:return"date is not";case be.notEqIgnoreCase:case be.greaterThan:return"date is after";case be.greaterThanOrEqualTo:return"date is after or equal";case be.lessThan:return"date is before";case be.lessThanOrEqualTo:return"date is before or equal";default:throw new Error(`Unrecognized date filter type ${c}`)}}function Jf(c){switch(c){case be.isTrue:return"Is True";case be.isFalse:return"Is False";case be.isNull:return"Is Null";default:throw new Error(`Unrecognized boolean filter type ${c}`)}}hl.register([cp,hp,up,mp,gp,pp]);const bh=typeof fa=="function"?fa(hl):fa.default(hl);class Tn{static EVENT_UPDATED="ChartModel.EVENT_UPDATED";static EVENT_DISCONNECT="ChartModel.EVENT_DISCONNECT";static EVENT_RECONNECT="ChartModel.EVENT_RECONNECT";static EVENT_DOWNSAMPLESTARTED="ChartModel.EVENT_DOWNSAMPLESTARTED";static EVENT_DOWNSAMPLEFINISHED="ChartModel.EVENT_DOWNSAMPLEFINISHED";static EVENT_DOWNSAMPLEFAILED="ChartModel.EVENT_DOWNSAMPLEFAILED";static EVENT_DOWNSAMPLENEEDED="ChartModel.EVENT_DOWNSAMPLENEEDED";static EVENT_LOADFINISHED="ChartModel.EVENT_LOADFINISHED";constructor(){this.listeners=[],this.isDownsamplingDisabled=!1}listeners;formatter;rect;isDownsamplingDisabled;title;getData(){return[]}getDefaultTitle(){return""}getLayout(){return{}}getFilterColumnMap(){return new Map}isFilterRequired(){return!1}setFilter(e){}close(){}setFormatter(e){this.formatter=e}setDownsamplingDisabled(e){this.isDownsamplingDisabled=e}setDimensions(e){this.rect=e}setTitle(e){this.title=e}subscribe(e){this.listeners.push(e)}unsubscribe(e){this.listeners=this.listeners.filter(t=>t!==e)}fireEvent(e){for(let t=0;t<this.listeners.length;t+=1)this.listeners[t](e)}fireUpdate(e){this.fireEvent(new CustomEvent(Tn.EVENT_UPDATED,{detail:e}))}fireDisconnect(){this.fireEvent(new CustomEvent(Tn.EVENT_DISCONNECT))}fireReconnect(){this.fireEvent(new CustomEvent(Tn.EVENT_RECONNECT))}fireDownsampleStart(e){this.fireEvent(new CustomEvent(Tn.EVENT_DOWNSAMPLESTARTED,{detail:e}))}fireDownsampleFinish(e){this.fireEvent(new CustomEvent(Tn.EVENT_DOWNSAMPLEFINISHED,{detail:e}))}fireDownsampleFail(e){this.fireEvent(new CustomEvent(Tn.EVENT_DOWNSAMPLEFAILED,{detail:e}))}fireDownsampleNeeded(e){this.fireEvent(new CustomEvent(Tn.EVENT_DOWNSAMPLENEEDED,{detail:e}))}fireLoadFinished(){this.fireEvent(new CustomEvent(Tn.EVENT_LOADFINISHED))}}const _n=Tn,eC="#76d9e4 #9edc6f #fcd65b #aa9af4 #f37e3f #f95d84 #f0f0ee",tC="#403e41",nC="#5b5a5c",sC="#c0bfbf",iC="#4878ea",oC="rgba(91, 90, 92, 0.7)",Tt={"paper-bgcolor":"#2d2a2e","plot-bgcolor":"#322f33","title-color":"#f0f0ee",colorway:eC,gridcolor:tC,linecolor:nC,zerolinecolor:sC,activecolor:iC,rangebgcolor:oC,"area-color":"#76d9e4","trend-color":"#d5f0c1","line-color":"#9edc6f","error-band-line-color":"white","error-band-fill-color":"rgba(213, 240, 193, 0.1)","ohlc-increasing":"#9edc6f","ohlc-decreasing":"#f95d84"},Ot=Object.freeze({paper_bgcolor:Tt["paper-bgcolor"],plot_bgcolor:Tt["plot-bgcolor"],title_color:Tt["title-color"],colorway:Tt.colorway,gridcolor:Tt.gridcolor,linecolor:Tt.linecolor,zerolinecolor:Tt.zerolinecolor,activecolor:Tt.activecolor,rangebgcolor:Tt.rangebgcolor,area_color:Tt["area-color"],trend_color:Tt["trend-color"],line_color:Tt["line-color"],error_band_line_color:Tt["error-band-line-color"],error_band_fill_color:Tt["error-band-fill-color"],ohlc_increasing:Tt["ohlc-increasing"],ohlc_decreasing:Tt["ohlc-decreasing"]}),ji=ne.module("ChartUtils"),ts=Object.freeze(I.calendar.DayOfWeek.values()),_d="io.deephaven.time.DateTime",lC=36e5,aC=1e6;function rC(c){return c.asDate!==void 0}function dC(c){return c.asNumber!==void 0}function Pd(c){return c.dhTimeZone!==void 0}function cC(c){return c!=null&&c.range!=null&&(c.autorange===!1||c.autorange===void 0)}class se{static DEFAULT_AXIS_SIZE=.15;static MIN_AXIS_SIZE=.025;static MAX_AXIS_SIZE=.2;static AXIS_SIZE_PX=75;static LEGEND_WIDTH_PX=50;static MAX_LEGEND_SIZE=.25;static ORIENTATION=Object.freeze({HORIZONTAL:"h",VERTICAL:"v"});static DATE_FORMAT="yyyy-MM-dd HH:mm:ss.SSSSSS";static DEFAULT_MARGIN=Object.freeze({l:60,r:50,t:30,b:60,pad:0});static DEFAULT_TITLE_PADDING=Object.freeze({t:8});static SUBTITLE_LINE_HEIGHT=25;static DEFAULT_MARKER_SIZE=6;static MODE_MARKERS="markers";static MODE_LINES="lines";static getPlotlyChartType(e,t){switch(e){case I.plot.SeriesPlotStyle.SCATTER:return t?"scatter":"scattergl";case I.plot.SeriesPlotStyle.LINE:return"scatter";case I.plot.SeriesPlotStyle.BAR:case I.plot.SeriesPlotStyle.STACKED_BAR:return"bar";case I.plot.SeriesPlotStyle.PIE:return"pie";case I.plot.SeriesPlotStyle.TREEMAP:return"treemap";case I.plot.SeriesPlotStyle.HISTOGRAM:return"histogram";case I.plot.SeriesPlotStyle.OHLC:return"ohlc";default:return}}static getPlotlyChartMode(e,t,n){const s=new Set;switch(e){case I.plot.SeriesPlotStyle.SCATTER:(t??!1)&&s.add(se.MODE_LINES),(n??!0)&&s.add(se.MODE_MARKERS);break;case I.plot.SeriesPlotStyle.LINE:(t??!0)&&s.add(se.MODE_LINES),(n??!1)&&s.add(se.MODE_MARKERS);break}return s.size>0?[...s].join("+"):void 0}static getPlotlyProperty(e,t){switch(e){case I.plot.SeriesPlotStyle.PIE:switch(t){case I.plot.SourceType.X:return"labels";case I.plot.SourceType.Y:return"values"}break;case I.plot.SeriesPlotStyle.OHLC:switch(t){case I.plot.SourceType.TIME:return"x"}break;case I.plot.SeriesPlotStyle.TREEMAP:switch(t){case I.plot.SourceType.X:return"ids";case I.plot.SourceType.Y:return"values";case I.plot.SourceType.LABEL:return"labels";case I.plot.SourceType.PARENT:return"parents";case I.plot.SourceType.COLOR:return"marker.colors"}break}switch(t){case I.plot.SourceType.X:return"x";case I.plot.SourceType.Y:return"y";case I.plot.SourceType.Z:return"z";case I.plot.SourceType.X_LOW:return"xLow";case I.plot.SourceType.X_HIGH:return"xHigh";case I.plot.SourceType.Y_LOW:return"yLow";case I.plot.SourceType.Y_HIGH:return"yHigh";case I.plot.SourceType.TIME:return"time";case I.plot.SourceType.OPEN:return"open";case I.plot.SourceType.HIGH:return"high";case I.plot.SourceType.LOW:return"low";case I.plot.SourceType.CLOSE:return"close";case I.plot.SourceType.SHAPE:return"shape";case I.plot.SourceType.SIZE:return"size";case I.plot.SourceType.LABEL:return"label";case I.plot.SourceType.COLOR:return"color";case I.plot.SourceType.PARENT:return"parent";case I.plot.SourceType.HOVER_TEXT:return"hovertext";case I.plot.SourceType.TEXT:return"text";default:throw new Error(`Unrecognized source type: ${t}`)}}static getPlotlySeriesOrientation(e){const{sources:t}=e;return t.length===2&&t[0]?.axis?.type===I.plot.AxisType.Y?se.ORIENTATION.HORIZONTAL:se.ORIENTATION.VERTICAL}static getPlotlyErrorBars(e,t,n){const s=n.map((o,l)=>o-e[l]),i=t.map((o,l)=>e[l]-o);return{type:"data",symmetric:!1,array:s,arrayminus:i}}static getPlotlyDateFormat(e,t,n){const s=n?.replace("%","%%").replace(/S{9}/g,"%9f").replace(/S{8}/g,"%8f").replace(/S{7}/g,"%7f").replace(/S{6}/g,"%6f").replace(/S{5}/g,"%5f").replace(/S{4}/g,"%4f").replace(/S{3}/g,"%3f").replace(/S{2}/g,"%2f").replace(/S{1}/g,"%1f").replace(/y{4}/g,"%Y").replace(/y{2}/g,"%y").replace(/M{4}/g,"%B").replace(/M{3}/g,"%b").replace(/M{2}/g,"%m").replace(/M{1}/g,"%-m").replace(/E{4,}/g,"%A").replace(/E{1,}/g,"%a").replace(/d{2}/g,"%d").replace(/([^%]|^)d{1}/g,"$1%-d").replace(/H{2}/g,"%H").replace(/h{2}/g,"%I").replace(/h{1}/g,"%-I").replace(/m{2}/g,"%M").replace(/s{2}/g,"%S").replace("'T'","T").replace(" z","");let i;const o=e?.getColumnTypeFormatter(t);return o!=null&&Pd(o)&&o.dhTimeZone!=null&&o.showTimeZone&&(i=I.i18n.DateTimeFormat.format(" z",new Date,o.dhTimeZone)),{tickformat:s,ticksuffix:i,automargin:!0}}static convertNumberPrefix(e){return e.replace(/\u00A4\u00A4/g,"USD").replace(/\u00A4/g,"$")}static getPlotlyNumberFormat(e,t,n){if(!n)return null;const i=n.split(";")[0].match(/^([^#,0.]*)([#,]*)([0,]*)(\.?)(0*)(#*)(E?0*)(%?)(.*)/);N(i);const[,o,l,a,,d,h,u,m,g]=i,p=a.replace(",","").length,f=l.indexOf(",")>=0||a.indexOf(",")>=0?",":"",b=u!=null&&u!==""?"e":"f",w=m!==""?m:b,S=d.length+h.length,y=`0${p}${f}.${S}${w}`,E=se.convertNumberPrefix(o),R=se.convertNumberPrefix(g);return{tickformat:y,tickprefix:E,ticksuffix:R,automargin:!0}}static getPlotlyAxisFormat(e,t=null){const{axis:n,columnType:s}=e,{formatPattern:i}=n;let o=null;return F.isDateType(s)?(o=se.getPlotlyDateFormat(t,s,i),o=se.addTickSpacing(o,n,!0)):F.isNumberType(s)&&(o=se.getPlotlyNumberFormat(t,s,i),o=se.addTickSpacing(o,n,!1)),n.formatType===I.plot.AxisFormatType.CATEGORY&&(o?o.type="category":o={type:"category",tickformat:void 0,ticksuffix:void 0}),o}static addTickSpacing(e,t,n){const{gapBetweenMajorTicks:s}=t;if(s>0){const i=e||{};let o=s;return n&&(o=s/aC),t.log&&(o=Math.log(o)),i.tickmode="linear",i.dtick=o,i}return e}static getSourceForAxis(e,t){for(let n=0;n<e.series.length;n+=1){const s=e.series[n];for(let i=0;i<s.sources.length;i+=1){const o=s.sources[i];if(o.axis===t)return o}}return null}static getSeriesVisibility(e,t){return t!=null&&t.hiddenSeries!=null&&t.hiddenSeries.includes(e)?"legendonly":!0}static getHiddenLabels(e){return e?.hiddenSeries?[...e.hiddenSeries]:[]}static makeSeriesData(e,t,n,s,i=se.ORIENTATION.VERTICAL){return{type:e,mode:t,name:n,orientation:i,showlegend:s??void 0}}static makeSeriesDataFromSeries(e,t,n,s=null,i=Ot){const{name:o,isLinesVisible:l,isShapesVisible:a,plotStyle:d,lineColor:h,shapeColor:u,sources:m,shape:g,shapeSize:p}=e,C=m.some(T=>T.axis?.businessCalendar),f=se.getChartType(d,C),b=se.getPlotlyChartMode(d,l??void 0,a??void 0),w=se.getPlotlySeriesOrientation(e),S=se.makeSeriesData(f,b,o,s,w);return se.addSourcesToSeriesData(S,d,m,t),se.addStylingToSeriesData(S,d,i,h,u,g,p,n),S}static addSourcesToSeriesData(e,t,n,s){const i=e;for(let o=0;o<n.length;o+=1){const l=n[o],{axis:a,type:d}=l,h=se.getPlotlyProperty(t,d);Hc(i,h,[]);const u=a!=null?se.getAxisPropertyName(a.type):null;if(u!=null){const m=s.get(a.type);if(m){const g=m.indexOf(a),p=g>0?`${g+1}`:"";i[`${u}axis`]=`${u}${p}`}}}}static addStylingToSeriesData(e,t,n=Ot,s=null,i=null,o=null,l=null,a=null){const d=e;if(d.marker={line:{}},d.line={width:1},t===I.plot.SeriesPlotStyle.AREA?d.fill="tozeroy":t===I.plot.SeriesPlotStyle.STACKED_AREA?d.stackgroup="stack":t===I.plot.SeriesPlotStyle.STEP?d.line.shape="hv":t===I.plot.SeriesPlotStyle.HISTOGRAM?(d.width=[],d.marker.line!==void 0&&Object.assign(d.marker.line,{color:n.paper_bgcolor,width:1})):t===I.plot.SeriesPlotStyle.OHLC?(d.increasing={line:{color:n.ohlc_increasing}},d.decreasing={line:{color:n.ohlc_decreasing}}):t===I.plot.SeriesPlotStyle.PIE?(d.textinfo="label+percent",d.outsidetextfont={color:n.title_color}):t===I.plot.SeriesPlotStyle.TREEMAP&&(d.hoverinfo="text",d.textinfo="label+text",d.tiling={packing:"squarify",pad:0},d.textposition="middle center",d.outsidetextfont={color:n.title_color}),s!=null&&(t===I.plot.SeriesPlotStyle.BAR?d.marker.color=s:d.line.color=s),i!=null&&(d.marker.color=i),o!=null&&o.length>0)try{d.marker.symbol=se.getMarkerSymbol(o)}catch(h){ji.warn("Unable to handle shape",o,":",h)}l!=null&&(d.marker.size=l*se.DEFAULT_MARKER_SIZE),a!=null&&t!==I.plot.SeriesPlotStyle.PIE&&(d.visible=a)}static getMarkerSymbol(e){switch(e){case"SQUARE":return"square";case"CIRCLE":return"circle";case"DIAMOND":return"diamond";case"UP_TRIANGLE":return"triangle-up";case"DOWN_TRIANGLE":return"triangle-down";case"RIGHT_TRIANGLE":return"triangle-right";case"LEFT_TRIANGLE":return"triangle-left";case"ELLIPSE":case"HORIZONTAL_RECTANGLE":case"VERTICAL_RECTANGLE":default:throw new Error(`Unrecognized shape ${e}`)}}static getAxisFormats(e,t){const n=new Map,s={tickformat:null,ticksuffix:null},i=se.getAllAxes(e),o=se.groupArray(i,"type"),{charts:l}=e;for(let a=0;a<l.length;a+=1){const d=l[a];for(let h=0;h<d.series.length;h+=1){const u=d.series[h],{sources:m}=u,g=m.filter(p=>p.axis);for(let p=0;p<g.length;p+=1){const C=g[p],{axis:f}=C,{type:b}=f,w=o.get(b);N(w);const S=w.indexOf(f),T=se.getAxisPropertyName(b);if(T!=null){const y=se.getAxisLayoutProperty(T,S);if(n.has(y))ji.debug(`${y} already added.`);else{ji.debug(`Adding ${y} to axisFormats.`);const E=se.getPlotlyAxisFormat(C,t);if(E===null)n.set(y,s);else{n.set(y,E);const{businessCalendar:R}=f;if(R!=null){const x=[],{businessPeriods:D,businessDays:M,holidays:O,timeZone:H}=R,L=t?.getColumnTypeFormatter(_d);let V;Pd(L)&&(V=L.dhTimeZone);const U=V?(H.standardOffset-V.standardOffset)/60:0;O.length>0&&x.push(...se.createRangeBreakValuesFromHolidays(O,H,V)),D.forEach(j=>x.push({pattern:"hour",bounds:[se.periodToDecimal(j.close)+U,se.periodToDecimal(j.open)+U]})),M.length<ts.length&&se.createBoundsFromDays(M).forEach(j=>x.push({pattern:"day of week",bounds:j})),E.rangebreaks=x}if(n.size===d.axes.length)return n}}}}}}return n}static getChartType(e,t){switch(e){case I.plot.SeriesPlotStyle.HISTOGRAM:return"bar";default:return se.getPlotlyChartType(e,t)}}static getAxisPropertyName(e){switch(e){case I.plot.AxisType.X:return"x";case I.plot.AxisType.Y:return"y";default:return null}}static getAxisSide(e){switch(e){case I.plot.AxisPosition.BOTTOM:return"bottom";case I.plot.AxisPosition.TOP:return"top";case I.plot.AxisPosition.LEFT:return"left";case I.plot.AxisPosition.RIGHT:return"right";default:return}}static getAllAxes(e){return e.charts.reduce((t,n)=>[...t,...n.axes],[])}static getChartForSeries(e,t){const{charts:n}=e;for(let s=0;s<n.length;s+=1){const i=n[s];for(let o=0;o<i.series.length;o+=1)if(t===i.series[o])return i}return null}static getLayoutRanges(e){const t={},n=Object.keys(e).filter(s=>s.indexOf("axis")>=0);for(let s=0;s<n.length;s+=1){const i=n[s],o=e[i];cC(o)&&(t[i]=[...o.range])}return t}static updateFigureAxes(e,t,n,s=0,i=0,o=Ot){const l=e,a=se.getAllAxes(t);for(let d=0;d<t.charts.length;d+=1){const h=t.charts[d],u=n?.(h),m=se.getChartBounds(t,h,s,i);se.updateLayoutAxes(l,h.axes,a,s,i,m,u,o)}se.removeStaleAxes(l,a)}static getChartBounds(e,t,n,s){const{cols:i,rows:o}=e,{column:l,colspan:a,row:d,rowspan:h}=t,u=l+a,m=d+h,g=1/i,p=1/o,C=se.AXIS_SIZE_PX/n,f=se.AXIS_SIZE_PX/s,b={bottom:(o-m)*p+(m<o?f/2:0),top:(o-d)*p-(d>0?f/2:0),left:l*g+(l>0?C/2:0),right:u*g-(u<i?C/2:0)};return(se.groupArray(t.axes,"position").get(I.plot.AxisPosition.RIGHT)??[]).length>0&&(n>0?b.right-=(b.right-b.left)*Math.max(0,Math.min(se.LEGEND_WIDTH_PX/n,se.MAX_LEGEND_SIZE)):b.right-=(b.right-b.left)*se.DEFAULT_AXIS_SIZE),b}static updateLayoutAxes(e,t,n,s=0,i=0,o={left:0,top:0,right:1,bottom:1},l,a=Ot){const d=s>0?Math.max(se.MIN_AXIS_SIZE,Math.min(se.AXIS_SIZE_PX/i,se.MAX_AXIS_SIZE)):se.DEFAULT_AXIS_SIZE,h=i>0?Math.max(se.MIN_AXIS_SIZE,Math.min(se.AXIS_SIZE_PX/s,se.MAX_AXIS_SIZE)):se.DEFAULT_AXIS_SIZE,u=e,m=se.groupArray(t,"position"),g=se.groupArray(t,"type"),p=[...g.keys()],C=se.groupArray(n,"type");for(let f=0;f<p.length;f+=1){const b=p[f],w=se.getAxisPropertyName(b);if(w!=null){const S=g.get(b),T=C.get(b),E=b===I.plot.AxisType.Y?i:s;N(S),N(T);for(let R=0;R<S.length;R+=1){const x=S[R],D=T.indexOf(x),M=se.getAxisLayoutProperty(w,D);u[M]==null&&(u[M]=se.makeLayoutAxis(b,a));const O=u[M];if(O!=null){se.updateLayoutAxis(O,x,R,m,d,h,o);const{range:H,autorange:L}=O;if(l!=null&&H!==void 0&&(L===void 0||L===!1)){const V=l(x),[U,j]=V(H);ji.debug("Setting downsample range",E,U,j),x.range(E,U,j)}else x.range(E)}}}}}static removeStaleAxes(e,t){const n=e,s=se.groupArray(t,"type"),i=[...s.keys()];for(let o=0;o<i.length;o+=1){const l=i[o],a=s.get(l);N(a);let d=a.length;const h=se.getAxisPropertyName(l);if(h!=null){let u=se.getAxisLayoutProperty(h,d);for(;n[u]!=null;)delete n[u],d+=1,u=se.getAxisLayoutProperty(h,d)}}}static getAxisLayoutProperty(e,t){const n=t>0?`${t+1}`:"";return`${e??""}axis${n}`}static updateLayoutAxis(e,t,n,s,i,o,l){const d=t.type===I.plot.AxisType.Y?o:i,h=e,u=t.label??"";if(h.title!==void 0&&typeof h.title!="string"?h.title.text=u:h.title={text:u},t.log&&(h.type="log"),h.side=se.getAxisSide(t.position),n>0){h.overlaying=se.getAxisPropertyName(t.type)??void 0;const m=s.get(t.position)??[],g=m.indexOf(t);g>0&&(h.anchor="free",t.position===I.plot.AxisPosition.RIGHT?h.position=l.right+(g-m.length+1)*d:t.position===I.plot.AxisPosition.TOP?h.position=l.top+(g-m.length+1)*d:t.position===I.plot.AxisPosition.BOTTOM?h.position=l.bottom+(m.length-g+1)*d:t.position===I.plot.AxisPosition.LEFT&&(h.position=l.left+(m.length-g+1)*d))}else if(t.type===I.plot.AxisType.X){const m=s.get(I.plot.AxisPosition.LEFT)||[],g=s.get(I.plot.AxisPosition.RIGHT)||[],p=Math.max(l.left,l.left+(m.length-1)*o),C=Math.min(l.right-(g.length-1)*o,l.right);h.domain=[p,C]}else if(t.type===I.plot.AxisType.Y){const m=s.get(I.plot.AxisPosition.BOTTOM)||[],g=s.get(I.plot.AxisPosition.TOP)||[],p=Math.max(l.bottom,l.bottom+(m.length-1)*i),C=Math.min(l.top-(g.length-1)*i,l.top);h.domain=[p,C]}}static periodToDecimal(e){const t=e.split(":");return Number(t[0])+Number(t[1])/60}static createBoundsFromDays(e){const t=e.map(o=>ts.indexOf(o)),n=ts.filter(o=>!e.includes(o)).map(o=>ts.indexOf(o)),s=new Set;n.forEach(o=>{for(let l=o+1;l<o+ts.length;l+=1){const a=l%ts.length;if(t.includes(a)){s.add(a);break}}});const i=[];return s.forEach(o=>{for(let l=o-1;l>o-ts.length;l-=1){const a=l<0?l+ts.length:l;if(t.includes(a)){const d=(a+1)%7;i.push([d,o]);break}}}),i}static createRangeBreakValuesFromHolidays(e,t,n){const s=[],i=[];return e.forEach(o=>{o.businessPeriods.length>0?i.push(...se.createPartialHoliday(o,t,n)):s.push(se.createFullHoliday(o,t,n))}),[{values:s},...i]}static createFullHoliday(e,t,n){return se.adjustDateForTimeZone(`${e.date.toString()} 00:00:00.000000`,t,n)}static createPartialHoliday(e,t,n){const s=e.date.toString(),i=["00:00"];e.businessPeriods.forEach(l=>{i.push(l.open),i.push(l.close)}),i.push("24:00");const o=[];for(let l=0;l<i.length;l+=2){const a=i[l],d=i[l+1];if(a!==d){const h=[se.adjustDateForTimeZone(`${s} ${a}:00.000000`,t,n)],u=lC*(se.periodToDecimal(d)-se.periodToDecimal(a));o.push({values:h,dvalue:u})}}return o}static adjustDateForTimeZone(e,t,n){return n&&n.standardOffset!==t.standardOffset?se.unwrapValue(se.wrapValue(e,_d,t),n):e}static groupArray(e,t){return e.reduce((n,s)=>{const i=s[t],o=n.get(i)??[];return o.push(s),n.set(i,o),n},new Map)}static unwrapValue(e,t){if(e!=null){if(rC(e))return I.i18n.DateTimeFormat.format(se.DATE_FORMAT,e,t);if(dC(e))return e.asNumber()}return e}static wrapValue(e,t,n=null){if(F.isDateType(t)&&typeof e=="string"){const s=e,i=se.DATE_FORMAT.substr(0,e.length),o=I.i18n.DateTimeFormat.parse(i,s);if(!n)return o;const l=`${i} Z`,a=I.i18n.DateTimeFormat.format("Z",o,n),d=I.i18n.DateTimeFormat.parse(l,`${s} ${a}`),h=I.i18n.DateTimeFormat.format("Z",d,n);return I.i18n.DateTimeFormat.parse(l,`${s} ${h}`)}return e}static makeLayoutAxis(e,t=Ot){const n={automargin:!0,gridcolor:t.gridcolor,linecolor:t.linecolor,rangeslider:{visible:!1},showline:!0,ticklen:5,tickcolor:t.paper_bgcolor,tickfont:{color:t.zerolinecolor},title:{font:{color:t.title_color}}};return e===I.plot.AxisType.X?Object.assign(n,{showgrid:!0}):e===I.plot.AxisType.Y&&Object.assign(n,{zerolinecolor:t.zerolinecolor,zerolinewidth:2}),n}static getColorwayFromTheme(e=Ot){let t=[];return e.colorway&&(Array.isArray(e.colorway)?t=e.colorway:typeof e.colorway=="string"?t=e.colorway.split(" "):ji.warn(`Unable to handle colorway property: ${e.colorway}`)),t}static makeDefaultLayout(e=Ot){const t={...e,autosize:!0,colorway:se.getColorwayFromTheme(e),font:{family:"'Fira Sans', sans-serif"},title:{font:{color:e.title_color},yanchor:"top",pad:{...se.DEFAULT_TITLE_PADDING},y:1},legend:{font:{color:e.title_color}},margin:{...se.DEFAULT_MARGIN},xaxis:se.makeLayoutAxis(I.plot.AxisType.X,e),yaxis:se.makeLayoutAxis(I.plot.AxisType.Y,e)};return t.datarevision=0,t}static hydrateSettings(e){return{...e,type:e.type!=null?I.plot.SeriesPlotStyle[e.type]:void 0}}static titleFromSettings(e){const{series:t,xAxis:n,title:s=`${(t??[]).join(", ")} by ${n}`}=e;return s}static makeFigureSettings(e,t){const{series:n,xAxis:s,type:i}=e,o=se.titleFromSettings(e),l={formatType:`${I.plot.AxisFormatType.NUMBER}`,type:`${I.plot.AxisType.X}`,position:`${I.plot.AxisPosition.BOTTOM}`},a={formatType:`${I.plot.AxisFormatType.NUMBER}`,type:`${I.plot.AxisType.Y}`,position:`${I.plot.AxisPosition.LEFT}`};return{charts:[{chartType:`${I.plot.ChartType.XY}`,axes:[l,a],series:(n??[]).map(d=>({plotStyle:`${i}`,name:d,dataSources:[{type:`${I.plot.SourceType.X}`,columnName:s??"",axis:l,table:t},{type:`${I.plot.SourceType.Y}`,columnName:d,axis:a,table:t}]}))}],title:o}}}const Qe=se;const ns=ne.module("Chart");class gi extends v.Component{static defaultProps={isActive:!0,settings:{timeZone:"America/New_York",defaultDateTimeFormat:Xs.FULL_DATE_FORMAT,showTimeZone:!1,showTSeparator:!0,formatter:[]},onDisconnect:()=>{},onReconnect:()=>{},onUpdate:()=>{},onError:()=>{},onSettingsChanged:()=>{}};static convertIcon(e){const[t,,,,n]=e.icon,s=`${n}`;return{width:t,path:s,ascent:t,descent:0,transform:"matrix(1, 0, 0, 1, 0, 0)"}}static downsampleButtonTitle(e,t){return e?"Downsampling in progress...":t?"Downsampling disabled, click to enable":"Downsampling enabled, click to disable"}static downsampleButtonAttr(e,t){return e?"animation-spin":t?void 0:"fill-active"}constructor(e){super(e),this.handleAfterPlot=this.handleAfterPlot.bind(this),this.handleDownsampleClick=this.handleDownsampleClick.bind(this),this.handleModelEvent=this.handleModelEvent.bind(this),this.handlePlotUpdate=this.handlePlotUpdate.bind(this),this.handleRelayout=this.handleRelayout.bind(this),this.handleRestyle=this.handleRestyle.bind(this),this.plot=de.createRef(),this.plotWrapper=de.createRef(),this.columnFormats=[],this.dateTimeFormatterOptions={},this.decimalFormatOptions={},this.integerFormatOptions={},this.isSubscribed=!1,this.isLoadedFired=!1,this.currentSeries=0,this.state={data:null,downsamplingError:null,isDownsampleFinished:!1,isDownsampleInProgress:!1,isDownsamplingDisabled:!1,layout:{datarevision:0},revision:0}}componentDidMount(){this.updateDimensions(),this.updateModelDimensions(),this.initData(),this.initFormatter();const{isActive:e}=this.props;e&&this.subscribe()}componentDidUpdate(e){const{isActive:t,settings:n}=this.props;this.updateFormatterSettings(n),t!==e.isActive&&(t?this.subscribe():this.unsubscribe())}componentWillUnmount(){this.unsubscribe()}currentSeries;plot;plotWrapper;columnFormats;dateTimeFormatterOptions;decimalFormatOptions;integerFormatOptions;rect;ranges;isSubscribed;isLoadedFired;getCachedConfig=ge((e,t,n,s)=>{const i=[],o=Boolean(e);if(o&&i.push({name:`Downsampling failed: ${e}`,click:()=>{},icon:gi.convertIcon(eh),attr:"fill-warning"}),t||n||s||o){const l=gi.downsampleButtonTitle(n,s),a=gi.downsampleButtonAttr(n,s),d=n?cg:hg;i.push({name:l,icon:gi.convertIcon(d),click:this.handleDownsampleClick,attr:a})}return{displaylogo:!1,displayModeBar:n||o?!0:"hover",modeBarButtons:[i,["toImage"],["zoom2d","pan2d"],["zoomIn2d","zoomOut2d","autoScale2d","resetScale2d"]]}});getPlotRect(){return this.plotWrapper.current?.getBoundingClientRect()??null}initData(){const{model:e}=this.props,{layout:t}=this.state;this.setState({data:e.getData(),layout:{...t,...e.getLayout()}})}subscribe(){if(this.isSubscribed)return;const{model:e}=this.props;if(!this.rect||this.rect.width===0||this.rect.height===0){ns.debug2("Delaying subscription until model dimensions are set");return}e.subscribe(this.handleModelEvent),this.isSubscribed=!0}unsubscribe(){if(!this.isSubscribed)return;const{model:e}=this.props;e.unsubscribe(this.handleModelEvent),this.isSubscribed=!1}handleAfterPlot(){this.plot.current!=null}handleDownsampleClick(){this.setState(({isDownsamplingDisabled:e})=>({downsamplingError:null,isDownsampleInProgress:!1,isDownsampleFinished:!1,isDownsamplingDisabled:!e}),()=>{const{model:e}=this.props,{isDownsamplingDisabled:t}=this.state;e.setDownsamplingDisabled(t)})}handleModelEvent(e){const{type:t,detail:n}=e;switch(ns.debug2("Received data update",t,n),t){case _n.EVENT_UPDATED:{this.currentSeries+=1,this.setState(i=>{const{layout:o,revision:l}=i;return typeof o.datarevision=="number"&&(o.datarevision+=1),{data:n,layout:o,revision:l+1}});const{onUpdate:s}=this.props;s({isLoading:!this.isLoadedFired});break}case _n.EVENT_LOADFINISHED:{const{onUpdate:s}=this.props;this.isLoadedFired=!0,s({isLoading:!1});break}case _n.EVENT_DISCONNECT:{const{onDisconnect:s}=this.props;s();break}case _n.EVENT_RECONNECT:{const{onReconnect:s}=this.props;s();break}case _n.EVENT_DOWNSAMPLESTARTED:{this.setState({isDownsampleFinished:!1,isDownsampleInProgress:!0,downsamplingError:null});break}case _n.EVENT_DOWNSAMPLEFINISHED:{this.setState({isDownsampleFinished:!0,isDownsampleInProgress:!1,downsamplingError:null});break}case _n.EVENT_DOWNSAMPLENEEDED:case _n.EVENT_DOWNSAMPLEFAILED:{const s=n.message??n;this.setState({isDownsampleFinished:!1,isDownsampleInProgress:!1,isDownsamplingDisabled:!1,downsamplingError:s});const{onError:i}=this.props;i(new Error(s));break}default:ns.debug("Unknown event type",t,e)}}handlePlotUpdate(e){const{layout:t}=e,n=Qe.getLayoutRanges(t);!st(n,this.ranges)&&(this.ranges=n,this.updateModelDimensions(!0))}handleRelayout(e){if(ns.debug("handleRelayout",e),e.hiddenlabels!=null){const{onSettingsChanged:t}=this.props,n=[...e.hiddenlabels];t({hiddenSeries:n})}this.updateModelDimensions()}handleRestyle([e,t]){if(ns.debug("handleRestyle",e,t),Object.keys(e).includes("visible")){const{data:n}=this.state,{onSettingsChanged:s}=this.props;if(n!=null){const i=n.reduce((o,{name:l,visible:a})=>l!=null&&a==="legendonly"?[...o,l]:o,[]);s({hiddenSeries:i})}}}updateModelDimensions(e=!1){const t=this.getPlotRect();if(!t){ns.warn("Unable to get plotting rect");return}if(!this.rect||this.rect.width!==t.width||this.rect.height!==t.height||e){this.rect=t;const{isActive:s,model:i}=this.props;i.setDimensions(t),s&&this.subscribe()}}initFormatter(){const{settings:e}=this.props;this.updateFormatterSettings(e)}updateFormatterSettings(e){const t=$n.getColumnFormats(e),n=$n.getDateTimeFormatterOptions(e),{decimalFormatOptions:s={},integerFormatOptions:i={}}=e;(!st(this.columnFormats,t)||!st(this.dateTimeFormatterOptions,n)||!st(this.decimalFormatOptions,s)||!st(this.integerFormatOptions,i))&&(this.columnFormats=$n.getColumnFormats(e),this.dateTimeFormatterOptions=n,this.decimalFormatOptions=s,this.integerFormatOptions=i,this.updateFormatter())}updateFormatter(){const e=new gn(this.columnFormats,this.dateTimeFormatterOptions,this.decimalFormatOptions,this.integerFormatOptions),{model:t}=this.props;t.setFormatter(e)}updateDimensions(){const e=this.getPlotRect();this.plot.current!=null&&e!=null&&e.width>0&&e.height>0&&hl.relayout(this.plot.current.el,{autosize:!0}).catch(t=>{ns.debug("Unable to resize, promise rejected",t)})}render(){const{data:e,downsamplingError:t,isDownsampleFinished:n,isDownsampleInProgress:s,isDownsamplingDisabled:i,layout:o,revision:l}=this.state,a=this.getCachedConfig(t,n,s,i),d=e!=null;return r.jsx("div",{className:"h-100 w-100 chart-wrapper",ref:this.plotWrapper,children:d&&r.jsx(bh,{ref:this.plot,data:e,layout:o,revision:l,config:a,onAfterPlot:this.handleAfterPlot,onError:ns.error,onRelayout:this.handleRelayout,onUpdate:this.handlePlotUpdate,onRestyle:this.handleRestyle,useResizeHandler:!0,style:{height:"100%",width:"100%"}})})}}const hC=gi,Dt=ne.module("FigureChartModel");class wr extends _n{static ADD_SERIES_DEBOUNCE=50;constructor(e,t={},n=Ot){super(),this.handleFigureUpdated=this.handleFigureUpdated.bind(this),this.handleFigureDisconnected=this.handleFigureDisconnected.bind(this),this.handleFigureReconnected=this.handleFigureReconnected.bind(this),this.handleFigureSeriesAdded=this.handleFigureSeriesAdded.bind(this),this.handleDownsampleStart=this.handleDownsampleStart.bind(this),this.handleDownsampleFinish=this.handleDownsampleFinish.bind(this),this.handleDownsampleFail=this.handleDownsampleFail.bind(this),this.handleDownsampleNeeded=this.handleDownsampleNeeded.bind(this),this.handleRequestFailed=this.handleRequestFailed.bind(this),this.figure=e,this.settings=t,this.theme=n,this.data=[];const s={data:{},layout:Qe.makeDefaultLayout(n)};this.layout={grid:{rows:e.rows,columns:e.cols,pattern:"independent"},template:s},this.seriesDataMap=new Map,this.pendingSeries=[],this.oneClicks=[],this.filterColumnMap=new Map,this.lastFilter=new Map,this.isConnected=!0,this.seriesToProcess=new Set,this.setTitle(this.getDefaultTitle()),this.initAllSeries(),this.updateAxisPositions(),this.startListeningFigure()}figure;settings;theme;data;layout;seriesDataMap;pendingSeries;oneClicks;filterColumnMap;lastFilter;isConnected;seriesToProcess;close(){this.figure.close(),this.addPendingSeries.cancel(),this.stopListeningFigure()}getDefaultTitle(){return this.figure.charts.length>0?this.figure.charts[0].title:""}initAllSeries(){this.oneClicks=[],this.filterColumnMap.clear();const{charts:e}=this.figure,t=Qe.getAllAxes(this.figure),n=[];for(let o=0;o<e.length;o+=1){const l=e[o];for(let a=0;a<l.series.length;a+=1){const d=l.series[a];n.push(d.name),this.addSeries(d,t,l.showLegend)}}const i=[...this.seriesDataMap.keys()].filter(o=>n.indexOf(o)<0);for(let o=0;o<i.length;o+=1){const l=i[o];this.seriesDataMap.delete(l)}this.seriesToProcess=new Set([...this.seriesDataMap.keys()])}addSeries(e,t,n){const s=Qe.groupArray(t,"type"),i=Qe.makeSeriesDataFromSeries(e,s,Qe.getSeriesVisibility(e.name,this.settings),n,this.theme);if(this.seriesDataMap.set(e.name,i),this.data=[...this.seriesDataMap.values()],e.plotStyle===I.plot.SeriesPlotStyle.STACKED_BAR?this.layout.barmode="stack":e.plotStyle===I.plot.SeriesPlotStyle.PIE&&(this.layout.hiddenlabels=Qe.getHiddenLabels(this.settings)),this.layout.showlegend=this.data.length>1||e.plotStyle===I.plot.SeriesPlotStyle.PIE?n??void 0:!1,e.oneClick!=null){const{oneClick:o}=e,{columns:l}=o;for(let a=0;a<l.length;a+=1)this.filterColumnMap.set(l[a].name,l[a]);this.oneClicks.push(o)}this.updateLayoutFormats()}addPendingSeries=Ye(()=>{const e=Qe.getAllAxes(this.figure),{pendingSeries:t}=this;for(let n=0;n<t.length;n+=1){const s=t[n],i=this.figure.charts.find(o=>o.series.includes(s));this.addSeries(s,e,i?.showLegend??null),s.subscribe()}this.pendingSeries=[]},wr.ADD_SERIES_DEBOUNCE);subscribe(e){super.subscribe(e),this.listeners.length===1&&(this.initAllSeries(),this.subscribeFigure())}unsubscribe(e){super.unsubscribe(e),this.listeners.length===0&&this.unsubscribeFigure()}subscribeFigure(){if(!this.isConnected){Dt.debug("Ignoring subscribe when figure in disconnected state");return}this.figure.subscribe(this.isDownsamplingDisabled?I.plot.DownsampleOptions.DISABLE:I.plot.DownsampleOptions.DEFAULT)}unsubscribeFigure(){this.figure.unsubscribe()}startListeningFigure(){this.figure.addEventListener(I.plot.Figure.EVENT_UPDATED,this.handleFigureUpdated),this.figure.addEventListener(I.plot.Figure.EVENT_SERIES_ADDED,this.handleFigureSeriesAdded),this.figure.addEventListener(I.plot.Figure.EVENT_DISCONNECT,this.handleFigureDisconnected),this.figure.addEventListener(I.plot.Figure.EVENT_RECONNECT,this.handleFigureReconnected),this.figure.addEventListener(I.plot.Figure.EVENT_DOWNSAMPLESTARTED,this.handleDownsampleStart),this.figure.addEventListener(I.plot.Figure.EVENT_DOWNSAMPLEFINISHED,this.handleDownsampleFinish),this.figure.addEventListener(I.plot.Figure.EVENT_DOWNSAMPLEFAILED,this.handleDownsampleFail),this.figure.addEventListener(I.plot.Figure.EVENT_DOWNSAMPLENEEDED,this.handleDownsampleNeeded),this.figure.addEventListener(I.Client.EVENT_REQUEST_FAILED,this.handleRequestFailed)}stopListeningFigure(){this.figure.removeEventListener(I.plot.Figure.EVENT_UPDATED,this.handleFigureUpdated),this.figure.removeEventListener(I.plot.Figure.EVENT_SERIES_ADDED,this.handleFigureSeriesAdded),this.figure.removeEventListener(I.plot.Figure.EVENT_DISCONNECT,this.handleFigureDisconnected),this.figure.removeEventListener(I.plot.Figure.EVENT_RECONNECT,this.handleFigureReconnected),this.figure.removeEventListener(I.plot.Figure.EVENT_DOWNSAMPLESTARTED,this.handleDownsampleStart),this.figure.removeEventListener(I.plot.Figure.EVENT_DOWNSAMPLEFINISHED,this.handleDownsampleFinish),this.figure.removeEventListener(I.plot.Figure.EVENT_DOWNSAMPLEFAILED,this.handleDownsampleFail),this.figure.removeEventListener(I.plot.Figure.EVENT_DOWNSAMPLENEEDED,this.handleDownsampleNeeded),this.figure.removeEventListener(I.Client.EVENT_REQUEST_FAILED,this.handleRequestFailed)}getTimeZone=Re((e,t)=>{if(t!=null){const n=t.getColumnTypeFormatter(e);if(n!=null)return n.dhTimeZone}});getValueTranslator=Re((e,t)=>{const n=this.getTimeZone(e,t);return s=>Qe.unwrapValue(s,n)});getValueParser=Re((e,t)=>{const n=this.getTimeZone(e,t);return s=>Qe.wrapValue(s,e,n)});getRangeParser=Re((e,t)=>n=>{let[s,i]=n;const o=this.getValueParser(e,t);return s=o(s),i=o(i),[s,i]});getAxisRangeParser=Re((e,t)=>n=>{const s=Qe.getSourceForAxis(e,n);return s?this.getRangeParser(s.columnType,t):i=>i});handleDownsampleStart(e){Dt.debug("Downsample started",e),this.fireDownsampleStart(e.detail)}handleDownsampleFinish(e){Dt.debug("Downsample finished",e),this.fireDownsampleFinish(e.detail)}handleDownsampleFail(e){Dt.error("Downsample failed",e),this.fireDownsampleFail(e.detail)}handleDownsampleNeeded(e){Dt.info("Downsample needed",e),this.fireDownsampleNeeded(e.detail)}handleFigureUpdated(e){const{detail:t}=e,{series:n}=t;Dt.debug2("handleFigureUpdated",n);for(let i=0;i<n.length;i+=1){const o=n[i];Dt.debug2("handleFigureUpdated updating series",o.name);const{sources:l}=o;for(let a=0;a<l.length;a+=1){const d=l[a],{columnType:h,type:u}=d,m=this.getValueTranslator(h,this.formatter),g=t.getArray(o,u,m);this.setDataArrayForSeries(o,u,g)}this.seriesToProcess.delete(o.name),this.seriesToProcess.size===0&&this.fireLoadFinished(),this.cleanSeries(o)}const{data:s}=this;this.fireUpdate(s)}handleRequestFailed(e){Dt.error("Request failed",e)}resubscribe(){this.listeners.length>0&&(this.unsubscribeFigure(),this.subscribeFigure())}setFormatter(e){super.setFormatter(e),this.updateLayoutFormats(),this.resubscribe()}setDownsamplingDisabled(e){super.setDownsamplingDisabled(e),this.resubscribe()}handleFigureDisconnected(e){Dt.debug("Figure disconnected",e),this.isConnected=!1,this.listeners.length>0&&this.unsubscribeFigure(),this.fireDisconnect()}handleFigureReconnected(e){Dt.debug("Figure reconnected",e),this.isConnected=!0,this.initAllSeries(),this.fireReconnect(),this.listeners.length>0&&this.subscribeFigure()}handleFigureSeriesAdded(e){const{detail:t}=e;Dt.debug("handleFigureSeriesAdded",t),this.pendingSeries.push(t),this.addPendingSeries()}setDimensions(e){super.setDimensions(e),this.updateAxisPositions()}setTitle(e){super.setTitle(e);const t=(e??"").match(/<br>/g)?.length??0,n=Qe.DEFAULT_MARGIN.t+t*Qe.SUBTITLE_LINE_HEIGHT;this.layout.margin?this.layout.margin.t=n:this.layout.margin={t:n},typeof this.layout.title=="string"?this.layout.title=e:(this.layout.title={...this.layout.title},this.layout.title.text=e,this.layout.title.pad={...this.layout.title.pad},this.layout.title.pad.t=Qe.DEFAULT_TITLE_PADDING.t+t*Qe.SUBTITLE_LINE_HEIGHT*.5)}getPlotWidth(){return!this.rect||!this.rect.width?0:Math.max(this.rect.width-(this.layout.margin?.l??0)-(this.layout.margin?.r??0),0)}getPlotHeight(){return!this.rect||!this.rect.height?0:Math.max(this.rect.height-(this.layout.margin?.t??0)-(this.layout.margin?.b??0),0)}updateAxisPositions(){const e=this.getPlotWidth(),t=this.getPlotHeight();Qe.updateFigureAxes(this.layout,this.figure,n=>this.getAxisRangeParser(n,this.formatter),e,t,this.theme)}updateLayoutFormats(){if(!this.formatter)return;Qe.getAxisFormats(this.figure,this.formatter).forEach((t,n)=>{Dt.debug(`Assigning ${n}`,this.layout[n],t);const s=this.layout[n];s!=null?Object.assign(s,t):Dt.debug(`Ignoring null layout.${n}`)})}setDataArrayForSeries(e,t,n){const{name:s,plotStyle:i}=e,o=this.seriesDataMap.get(s),l=Qe.getPlotlyProperty(i,t);o&&Hc(o,l,n)}cleanSeries(e){const{name:t,plotStyle:n}=e,s=this.seriesDataMap.get(t);if(s!=null){if(n===I.plot.SeriesPlotStyle.HISTOGRAM){const{xLow:i,xHigh:o}=s;if(i&&o&&i.length===o.length){const l=[];for(let a=0;a<i.length;a+=1)l.push(o[a]-i[a]);s.width=l}}else if(n===I.plot.SeriesPlotStyle.LINE){const{x:i,xLow:o,xHigh:l,y:a,yLow:d,yHigh:h}=s;o&&l&&o!==i&&(s.error_x=Qe.getPlotlyErrorBars(i,o,l)),d&&h&&d!==a&&(s.error_y=Qe.getPlotlyErrorBars(a,d,h))}else if(n===I.plot.SeriesPlotStyle.TREEMAP){const{ids:i,labels:o}=s;i!==void 0&&o===void 0&&(s.labels=i)}}}getData(){return this.data}getLayout(){return this.layout}getFilterColumnMap(){return new Map(this.filterColumnMap)}isFilterRequired(){return this.oneClicks.find(e=>e.requireAllFiltersToDisplay)!=null}setFilter(e){if(this.oneClicks.length===0){Dt.warn("Trying to set a filter, but no one click!");return}Dt.debug("setFilter",e);for(let t=0;t<this.oneClicks.length;t+=1){const n=this.oneClicks[t],{columns:s}=n;new Set([...e.keys(),...this.lastFilter.keys()]).forEach(o=>{const l=e.get(o);this.lastFilter.get(o)!==l&&s.find(a=>a.name===o)!=null&&n.setValueForColumn(o,l)})}this.lastFilter=new Map(e)}setFigure(e){this.close(),this.figure=e,this.setTitle(this.getDefaultTitle()),this.initAllSeries(),this.updateAxisPositions(),this.startListeningFigure(),this.listeners.length>0&&this.subscribeFigure()}updateSettings(e){this.settings=e}}const jd=wr;class vr{static async makeModelFromSettings(e,t,n=Ot){const s=await vr.makeFigureFromSettings(e,t);return new jd(s,e,n)}static async makeFigureFromSettings(e,t){const n=await t.copy();return n.applyCustomColumns(t.customColumns),n.applyFilter(t.filter),n.applySort(t.sort),I.plot.Figure.create(Qe.makeFigureSettings(e,n))}static async makeModel(e,t,n=Ot){return new jd(t,e,n)}}const fl=vr;function Hd(c){return c.setFigure!==void 0}const uC=ne.module("HeapUsage");function mC({connection:c,defaultUpdateInterval:e,hoverUpdateInterval:t,bgMonitoring:n=!0,monitorDuration:s}){const[i,o]=v.useState({freeMemory:0,maximumHeapSize:999,totalHeapSize:0}),[l,a]=v.useState(!1),d=v.useRef({timestamps:[],usages:[]});v.useEffect(function(){const O=async()=>{try{const L=await c.getWorkerHeapInfo();if(o(L),n||l){const V=(L.totalHeapSize-L.freeMemory)/L.maximumHeapSize,U=Date.now(),{timestamps:j,usages:P}=d.current;for(;j.length!==0&&U-j[0]>s*1.5;)j.shift(),P.shift();j.push(U),P.push(V)}else d.current={timestamps:[],usages:[]}}catch(L){uC.warn("Unable to get heap usage",L)}};O();const H=setInterval(O,l?t:e);return()=>{clearInterval(H)}},[l,t,c,e,s,n]);const h=(M,O)=>Math.round(M*10**O)/10**O,u=2,m=1024**3,{freeMemory:g,totalHeapSize:p,maximumHeapSize:C}=i,f=h(g/m,u),b=h(p/m,u),w=h(C/m,u),S=b-f,T=(M,O,H=!1)=>r.jsxs("div",{className:Y("heap-usage-info-row",{"heading-bottom-border":H}),children:[r.jsx("div",{className:"font-weight-bold",children:M}),r.jsx("div",{children:O})]}),{timestamps:y,usages:E}=d.current,R=y[y.length-1]??0,x=p/C,D=(p-g)/C;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"max-memory",children:[r.jsx("div",{className:"total-memory",style:{width:`calc(${x*100}% - ${x*2}px`}}),r.jsx("div",{className:Y("used-memory",{"heap-overflow":(p-g)/C>.95}),style:{width:`calc(${D*100}% - ${D*2}px`}}),r.jsxs("div",{className:"memory-text",children:[w.toFixed(1)," GB"]})]}),r.jsx(ot,{onEntered:()=>a(!0),onExited:()=>a(!1),interactive:!0,children:r.jsxs("div",{className:"heap-tooltip",children:[T("In use:",`${S.toFixed(u)} of ${w.toFixed(u)} GB`,!0),T("Free:",`${f.toFixed(u)} GB`),T("Total:",`${b.toFixed(u)} GB`),T("Max:",`${w.toFixed(u)} GB`),r.jsx("div",{className:"heap-plot",children:r.jsx(bh,{data:[{x:[...y],y:[...E],type:"scatter",mode:"lines"}],config:{staticPlot:!0,responsive:!0},style:{width:"196px",height:"100px"},layout:{legend:!1,margin:{l:2,t:2,r:2,b:2},plot_bgcolor:"transparent",paper_bgcolor:"transparent",colorway:["#4878ea"],xaxis:{dtick:Math.round(s/6),gridcolor:Ot.linecolor,range:[R-s,R],linecolor:Ot.linecolor,linewidth:2,mirror:!0},yaxis:{dtick:.2,gridcolor:Ot.linecolor,range:[0,1],linecolor:Ot.linecolor,linewidth:2,mirror:!0}}})}),r.jsxs("div",{className:"heap-utilisation-text",children:["% utilization over ",Math.round(s/1e3/60)," min."]})]})})]})}const Tr=Object.freeze({}),gC=new Map,Sh=c=>c.user,Er=c=>c.storage,wh=c=>Er(c).commandHistoryStorage,vh=c=>Er(c).fileStorage,pC=c=>Er(c).workspaceStorage,ql=c=>c.workspace,wt=c=>ql(c).data.settings,Th=c=>wt(c).defaultDateTimeFormat,Eh=c=>wt(c).defaultDecimalFormatOptions??Tr,yh=c=>wt(c).defaultIntegerFormatOptions??Tr,Rh=c=>wt(c).formatter,po=c=>wt(c).timeZone,xh=c=>wt(c).showTimeZone,Dh=c=>wt(c).showTSeparator,Ih=c=>wt(c).truncateNumbersWithPound,fC=c=>wt(c).shortcutOverrides,CC=c=>wt(c).defaultNotebookSettings??Tr,Xl=c=>c.activeTool,bC=c=>c.plugins??gC,Fh="SET_ACTIVE_TOOL",Nh="SET_COMMAND_HISTORY_STORAGE",kh="SET_FILE_STORAGE",Mh="SET_PLUGINS",Lh="SET_USER",Oh="SET_WORKSPACE",Ah="SET_WORKSPACE_STORAGE",_h="SET_SERVER_CONFIG_VALUES",SC=c=>({type:Lh,payload:c}),Ph=c=>({type:Oh,payload:c}),wC=c=>({type:Ah,payload:c}),vC=c=>({type:Nh,payload:c}),TC=c=>({type:kh,payload:c}),EC=c=>(e,t)=>{e(Ph(c));const{storage:n}=t(),{workspaceStorage:s}=n;return s.save(c)},jh=c=>(e,t)=>{const{workspace:n}=t(),{data:s}=n,i={...n,data:{...s,...c}};return e(EC(i))},Zl=c=>e=>e(jh({settings:c})),Ql=c=>({type:Fh,payload:c}),yC=c=>({type:Mh,payload:c}),RC=c=>({type:_h,payload:c});function Hh(c,e){return(t=e,n)=>{switch(n.type){case c:{const s=n.payload;return s==null?null:t!=null?{...t,...s}:{...s}}default:return t}}}function xC(c,e={},t=!0){return(n=e,s)=>{switch(s.type){case c:{const{id:i,payload:o}=s;return t&&st({payload:o},{payload:n[i]})?n:{...n,[i]:o}}default:return n}}}function Js(c,e){return(t=e,n)=>{switch(n.type){case c:return n.payload;default:return t}}}const DC=Js(Fh,null),IC=Js(Mh,null),FC=Js(Nh,null),NC=Js(kh,null),kC=Js(Ah,null),MC=sr({commandHistoryStorage:FC,fileStorage:NC,workspaceStorage:kC}),LC=Hh(Lh,null),OC=Hh(Oh,null),AC=Js(_h,null),_C={activeTool:DC,plugins:IC,storage:MC,user:LC,workspace:OC,serverConfigValues:AC},PC=_C;class jC{reducers={};listener=null;register(e,t){this.reducers={...this.reducers,[e]:t},this.listener?.(this.reducers)}setListener(e){this.listener=e}}const HC=new jC,fo=HC,Bd=ne.module("redux-logger"),BC=c=>e=>t=>{Bd.debug("dispatching",t);const n=e(t);return Bd.debug("next state",c.getState()),n},UC=BC,VC=ne.module("redux-crashReporter"),$C=c=>e=>t=>{try{return e(t)}catch(n){throw VC.error("Error executing",t," with state ",c.getState(),":",n),n}},WC=$C,GC=[UC,WC,im];Object.entries(PC).map(([c,e])=>fo.register(c,e));const zC=window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__??am,Bh=om(sr(fo.reducers),zC(lm(...GC)));fo.setListener(c=>{Bh.replaceReducer(sr(c))});const yr=Bh,Uh=Object.freeze({openPopouts:[],settings:{hasHeaders:!0,constrainDragToContainer:!0,reorderEnabled:!0,selectionEnabled:!1,popoutWholeStack:!1,blockedPopoutsThrowError:!0,closePopoutsOnUnload:!0,showPopoutIcon:!0,showMaximiseIcon:!0,showCloseIcon:!0,responsiveMode:"onload",tabOverlapAllowance:0,tabControlOffset:10},dimensions:{borderWidth:5,borderGrabWidth:10,minItemHeight:10,minItemWidth:10,headerHeight:20,dragProxyWidth:300,dragProxyHeight:200},labels:{close:"Close",maximise:"Maximize",minimise:"Minimize",popout:"Open in new window",popin:"Pop in",tabDropdown:"Additional tabs",tabNextLabel:"Next",tabPreviousLabel:"Previous"},content:[]});function Vh(c){return c.componentName!==void 0}function KC(c){return c.component!==void 0}const $h=Object.freeze({type:"default",isClosable:!0,isFocusOnShow:!0,reorderEnabled:!0,title:""}),YC=Object.freeze(Object.defineProperty({__proto__:null,defaultConfig:Uh,isGLComponentConfig:Vh,isReactComponentConfig:KC,itemDefaultConfig:$h},Symbol.toStringTag,{value:"Module"}));class Cl{static ALL_EVENT="__all";_mSubscriptions;constructor(){this._mSubscriptions={},this._mSubscriptions[Cl.ALL_EVENT]=[]}on(e,t,n){if(typeof t!="function")throw new Error("Tried to listen to event "+e+" with non-function callback "+t);this._mSubscriptions[e]||(this._mSubscriptions[e]=[]),this._mSubscriptions[e].push({fn:t,ctx:n})}emit(e,...t){const n=this._mSubscriptions[e];if(n)for(let i=0;i<n.length;i++){const o=n[i].ctx||{};n[i].fn.apply(o,t)}t.unshift(e);const s=this._mSubscriptions[Cl.ALL_EVENT];for(let i=0;i<s.length;i++){const o=s[i].ctx||{};s[i].fn.apply(o,t)}}unbind(e,t,n){if(!this._mSubscriptions[e])throw new Error("No subscribtions to unsubscribe for event "+e);let s=!1;for(let i=0;i<this._mSubscriptions[e].length;i++)(!t||this._mSubscriptions[e][i].fn===t)&&(!n||n===this._mSubscriptions[e][i].ctx)&&(this._mSubscriptions[e].splice(i,1),s=!0);if(s===!1)throw new Error("Nothing to unbind for "+e)}off=this.unbind;trigger=this.emit}const fn=Cl;class Wa extends fn{width;height;title;parent;layoutManager;tab;_config;isHidden=!1;beforeCloseHandler;_element=ce(['<div class="lm_item_container">','<div class="lm_content" tabindex="-1"></div>',"</div>"].join(""));_contentElement;constructor(e,t,n){super(),this.title=Vh(e)?e.componentName:"",this.parent=t,this.layoutManager=n,this._config=e,this._contentElement=this._element.find(".lm_content"),this.beforeCloseHandler=null}getElement(){return this._contentElement}hide(){this.emit("hide"),this.isHidden=!0,this._element.hide()}show(){this.emit("show"),this.isHidden=!1,this._element.show(),(this.height!=0||this.width!=0)&&this.emit("shown")}setSize(e,t){let n=this.parent,s=null;for(;n&&!n.isColumn&&!n.isRow;)if(s=n,n=n.parent,n?.isRoot)return!1;if(!n||!s)return!1;const i=n.isColumn?"height":"width",o=i==="height"?t:e,l=(this[i]??0)*(1/((s.config[i]??0)/100)),a=o/l*100,d=((s.config[i]??0)-a)/(n.contentItems.length-1);for(let h=0;h<n.contentItems.length;h++)n.contentItems[h]===s?n.contentItems[h].config[i]=a:n.contentItems[h].config[i]=(n.contentItems[h].config[i]??0)+d;return n.callDownwards("setSize"),!0}close(e){this._config.isClosable&&(this.beforeCloseHandler?.(e)??!0)&&(this.emit("close"),this.parent.close())}beforeClose(e){this.beforeCloseHandler=e}getState(){return this._config.componentState}extendState(e){this.setState(ce.extend(!0,this.getState(),e))}setState(e){this._config.componentState=e,this.parent.emitBubblingEvent("stateChanged")}setTitle(e){this.parent.setTitle(e)}_$setSize(e=0,t=0){if(e!==this.width||t!==this.height){this.width=e,this.height=t;var n=this._contentElement[0],s=n.offsetWidth-n.clientWidth,i=n.offsetHeight-n.clientHeight;this._contentElement.width(this.width-s).height(this.height-i),this.emit("resize")}}}const qC=Object.freeze(Object.defineProperty({__proto__:null,Container:Wa,ItemContainer:Wa},Symbol.toStringTag,{value:"Module"}));function Wh(c){var e=location.hash.match(new RegExp(c+"=([^&]*)"));return e?e[1]:null}function Gh(c){if(window.location.hash)return Wh(c);if(!window.location.search)return null;var e=window.location.search.substr(1).split("&"),t={},n,s;for(s=0;s<e.length;s++)n=e[s].split("="),t[n[0]]=n[1];return t[c]||null}function Jl(c){return window.requestAnimationFrame(c)}function XC(c,e){var t=e.indexOf(c);if(t===-1)throw new Error("Can't remove item from array. Item is not in the array");e.splice(t,1)}function Rr(){return(Math.random()*1e15).toString(36).replace(".","")}function ZC(c,e){var t=c.replace(/javascript/gi,"j&#97;vascript").replace(/expression/gi,"expr&#101;ssion").replace(/onload/gi,"onlo&#97;d").replace(/script/gi,"&#115;cript").replace(/onerror/gi,"on&#101;rror");return e===!0?t:t.replace(/>/g,"&gt;").replace(/</g,"&lt;")}function xr(c){return ce.trim(c.replace(/(<([^>]+)>)/gi,""))}class QC extends fn{_eElement;_oDocument;_eBody;_destroyAfterMouseUp;_nDelay=400;_timeout;timeout;_nDistance=10;_nX=0;_nY=0;_nOriginalX=0;_nOriginalY=0;_bDragging=!1;constructor(e,t=!1){super(),this._eElement=e,this._oDocument=ce(document),this._eBody=ce(document.body),this._destroyAfterMouseUp=t,this.onMouseMove=this.onMouseMove.bind(this),this.onMouseUp=this.onMouseUp.bind(this),this.onMouseDown=this.onMouseDown.bind(this),this._startDrag=this._startDrag.bind(this),this._eElement?.on("mousedown",this.onMouseDown)}destroy(){this._eElement?.unbind("mousedown",this.onMouseDown),this._oDocument?.unbind("mouseup",this.onMouseUp),this._eElement=void 0,this._oDocument=void 0,this._eBody=void 0,clearTimeout(this._timeout),this._timeout=void 0}onMouseDown(e){if(e.preventDefault(),e.button===0){var t=this._getCoordinates(e);this._nOriginalX=t.x??0,this._nOriginalY=t.y??0,this._oDocument?.on("mousemove",this.onMouseMove),this._oDocument?.on("mouseup",this.onMouseUp),this._timeout=window.setTimeout(this._startDrag,this._nDelay)}}onMouseMove(e){if(this._timeout!=null){e.preventDefault();var t=this._getCoordinates(e);this._nX=(t.x??0)-this._nOriginalX,this._nY=(t.y??0)-this._nOriginalY,this._bDragging===!1&&(Math.abs(this._nX)>this._nDistance||Math.abs(this._nY)>this._nDistance)&&this._startDrag(),this._bDragging&&this.emit("drag",this._nX,this._nY,e)}}onMouseUp(e){this._timeout!=null&&(clearTimeout(this._timeout),this._oDocument?.unbind("mousemove",this.onMouseMove),this._oDocument?.unbind("mouseup",this.onMouseUp),this._oDocument?.find("iframe")?.css("pointer-events",""),this._bDragging===!0&&(this._bDragging=!1,this.emit("dragStop",e,this._nOriginalX+this._nX)),this._eBody?.removeClass("lm_dragging"),this._eElement instanceof Window||this._eElement?.removeClass("lm_dragging"),this._destroyAfterMouseUp&&this.destroy())}_startDrag(){window.clearTimeout(this._timeout),this._bDragging=!0,this._eBody?.addClass("lm_dragging"),this._eElement?.addClass("lm_dragging"),this._oDocument?.find("iframe")?.css("pointer-events","none"),this.emit("dragStart",this._nOriginalX,this._nOriginalY)}_getCoordinates(e){return{x:e.pageX??0,y:e.pageY??0}}}const Co=QC;class zh{_container;_reactComponent=null;_originalComponentWillUpdate=null;_initialState;_reactClass;constructor(e,t){this._reactComponent=null,this._originalComponentWillUpdate=null,this._container=e,this._initialState=t,this._reactClass=this._getReactClass(),this._container.on("open",this._render,this),this._container.on("destroy",this._destroy,this)}_render(){al.render(this._getReactComponent(),this._container.getElement()[0])}_gotReactComponent(e){if(!e)return;this._reactComponent=e,this._originalComponentWillUpdate=this._reactComponent.componentWillUpdate||function(){},this._reactComponent.componentWillUpdate=this._onUpdate.bind(this);const t=this._container.getState();t&&this._reactComponent.setState(t)}_destroy(){al.unmountComponentAtNode(this._container.getElement()[0]),this._container.off("open",this._render,this),this._container.off("destroy",this._destroy,this)}_onUpdate(e,t){this._container.setState(t),this._originalComponentWillUpdate?.call(this._reactComponent,e,t)}_getReactClass(){var e=this._container._config.component;if(!e)throw new Error("No react component name. type: react-component needs a field `component`");const t=this._container.layoutManager.getComponent(e)||this._container.layoutManager.getFallbackComponent();if(!t)throw new Error('React component "'+e+'" not found. Please register all components with GoldenLayout using `registerComponent(name, component)`');return t}_getReactComponent(){var e={glEventHub:this._container.layoutManager.eventHub,glContainer:this._container,ref:this._gotReactComponent.bind(this)},t=ce.extend(e,this._container._config.props);return de.createElement(this._reactClass,t)}}const bl=["settings","hasHeaders","constrainDragToContainer","selectionEnabled","dimensions","borderWidth","minItemHeight","minItemWidth","headerHeight","dragProxyWidth","dragProxyHeight","labels","close","maximise","minimise","popout","content","componentName","componentState","id","width","type","height","isClosable","title","popoutWholeStack","openPopouts","parentId","activeItemIndex","reorderEnabled","borderGrabWidth"],JC=[!0,!1,"row","column","stack","component","close","maximise","minimise","open in new window"];function Dr(c){if(bl.length>36)throw new Error("Too many keys in config minifier map");const e={};return Ir(c,e,"_min"),e}function Ga(c){if(bl.length>36)throw new Error("Too many keys in config minifier map");const e={};return Ir(c,e,"_max"),e}function Ir(c,e,t){const n=t==="_min"?eb:tb;for(let s in c){if(!c.hasOwnProperty(s))continue;const i=Array.isArray(c)?c[Number.parseInt(s,10)]:c[s];if(typeof i=="object"&&i!=null){const o=i instanceof Array?[]:{};if(Array.isArray(e))e[Number.parseInt(s,10)]=o;else{const l=n(s,bl);e[l]=o}Ir(i,o,t)}else{const o=n(i,JC);if(Array.isArray(e))e[Number.parseInt(s,10)]=o;else{const l=n(s,bl);e[l]=o}}}}function eb(c,e){if(typeof c=="string"&&c.length===1)return"___"+c;var t=e.indexOf(c);return t===-1?c:t.toString(36)}function tb(c,e){return typeof c=="string"&&c.length===1?e[parseInt(c,36)]:typeof c=="string"&&c.substr(0,3)==="___"?c[3]:c}class za{name;origin;isPropagationStopped;constructor(e,t){this.name=e,this.origin=t,this.isPropagationStopped=!1}stopPropagation(){this.isPropagationStopped=!0}}let nb=class extends fn{_layoutManager;_dontPropagateToParent;_childEventSource;_boundOnEventFromChild;constructor(e){super(),this._layoutManager=e,this._dontPropagateToParent=null,this._childEventSource=null,this.on(fn.ALL_EVENT,this._onEventFromThis.bind(this)),this._boundOnEventFromChild=this._onEventFromChild.bind(this),ce(window).on("gl_child_event",this._boundOnEventFromChild)}_onEventFromThis(...e){this._layoutManager.isSubWindow&&e[0]!==this._dontPropagateToParent&&this._propagateToParent(e),this._propagateToChildren(e),this._dontPropagateToParent=null,this._childEventSource=null}_$onEventFromParent(e){this._dontPropagateToParent=e[0],this.emit.apply(this,e)}_onEventFromChild(e){this._childEventSource=e.originalEvent.__gl,this.emit.apply(this,e.originalEvent.__glArgs)}_propagateToParent(e){const t="gl_child_event",n=window.opener?.document.createEvent("HTMLEvents");n.initEvent(t,!0,!0),n.eventName=t,n.__glArgs=e,n.__gl=this._layoutManager,window.opener.dispatchEvent(n)}_propagateToChildren(e){for(let t=0;t<this._layoutManager.openPopouts.length;t++){const n=this._layoutManager.openPopouts[t].getGlInstance();n&&n!==this._childEventSource&&n.eventHub._$onEventFromParent(e)}}destroy(){ce(window).off("gl_child_event",this._boundOnEventFromChild)}};const Kh=nb,sb=Object.freeze(Object.defineProperty({__proto__:null,BubblingEvent:za,DragListener:Co,EventEmitter:fn,EventHub:Kh,ReactComponentHandler:zh,animFrame:Jl,filterXss:ZC,getHashValue:Wh,getQueryStringParam:Gh,getUniqueId:Rr,minifyConfig:Dr,removeFromArray:XC,stripTags:xr,unminifyConfig:Ga},Symbol.toStringTag,{value:"Module"}));class Yh extends fn{isInitialised=!1;_config;_dimensions;_parentId;_indexInParent;_layoutManager;_popoutWindow=null;_id=null;constructor(e,t,n,s,i){super(),this._config=e,this._dimensions=t,this._parentId=n,this._indexInParent=s,this._layoutManager=i,this._createWindow()}toConfig(){if(this.isInitialised===!1)throw new Error("Can't create config, layout not yet initialised");return{dimensions:{width:this.getGlInstance()?.width,height:this.getGlInstance()?.height,left:this._popoutWindow?.screenX??this._popoutWindow?.screenLeft??0,top:this._popoutWindow?.screenY??this._popoutWindow?.screenTop??0},content:this.getGlInstance()?.toConfig().content,parentId:this._parentId,indexInParent:this._indexInParent}}getGlInstance(){return this._popoutWindow?.__glInstance}getWindow(){return this._popoutWindow}close(){if(this.getGlInstance())this.getGlInstance()?._$closeWindow();else try{this.getWindow()?.close()}catch{}}popIn(){this._indexInParent;let e=null,t=null;this._parentId&&(e=ce.extend(!0,{},this.getGlInstance()?.toConfig()).content[0],t=this._layoutManager.root.getItemsById(this._parentId)[0],t||((this._layoutManager.root.contentItems.length??0)>0?t=this._layoutManager.root.contentItems[0]:t=this._layoutManager.root)),e&&(t?.addChild(e,this._indexInParent),this.close())}_createWindow(){const e=this._createUrl(),t=Math.floor(Math.random()*1e6).toString(36),n=this._serializeWindowOptions({width:this._dimensions.width,height:this._dimensions.height,innerWidth:this._dimensions.width,innerHeight:this._dimensions.height,menubar:"no",toolbar:"no",location:"no",personalbar:"no",resizable:"yes",scrollbars:"no",status:"no"});if(this._popoutWindow=window.open(e,t,n),!this._popoutWindow)if(this._layoutManager.config.settings.blockedPopoutsThrowError===!0){const i=new Error("Popout blocked");throw i.type="popoutBlocked",i}else return;ce(this._popoutWindow).on("load",this._positionWindow.bind(this)).on("unload beforeunload",this._onClose.bind(this));let s=window.setInterval(()=>{this._popoutWindow?.__glInstance&&this._popoutWindow.__glInstance.isInitialised&&(this._onInitialised(),window.clearInterval(s))},10)}_serializeWindowOptions(e){var t=[],n;for(n in e)t.push(n+"="+e[n]);return t.join(",")}_createUrl(){var e={content:this._config};const t="gl-window-config-"+Rr();e=Dr(e);try{localStorage.setItem(t,JSON.stringify(e))}catch(s){throw new Error("Error while writing to localStorage "+s.toString())}const n=document.location.href.split("?");return n.length===1?n[0]+"?gl-window="+t:document.location.href+"&gl-window="+t}_positionWindow(){this._popoutWindow?.moveTo(this._dimensions.left,this._dimensions.top),this._popoutWindow?.focus()}_onInitialised(){this.isInitialised=!0,this.getGlInstance()?.on("popIn",this.popIn,this),this.emit("initialised")}_onClose(){setTimeout(this.emit.bind(this,"closed"),50)}}class Fi extends fn{static _template='<div class="lm_dragProxy"><div class="lm_header"><ul class="lm_tabs"><li class="lm_tab lm_active"><i class="lm_left"></i><span class="lm_title"></span><i class="lm_right"></i></li></ul></div><div class="lm_content"></div></div>';_dragListener;_layoutManager;_contentItem;_originalParent;_area=null;_lastValidArea=null;_minX;_maxX;_minY;_maxY;_width;_height;_sided;element;childElementContainer;_proxyTab;constructor(e,t,n,s,i,o){super(),this._dragListener=n,this._layoutManager=s,this._contentItem=i,this._originalParent=o,this._dragListener.on("drag",this._onDrag,this),this._dragListener.on("dragStop",this._onDrop,this),this._contentItem.tab&&this._contentItem.tab.element&&(this._layoutManager.tabDropPlaceholder.width(this._contentItem.tab.element.outerWidth(!0)??0),this._layoutManager.tabDropPlaceholder.height(this._contentItem.tab.element.outerHeight(!0)??0)),this.element=ce(Fi._template),o&&o._side&&(this._sided=o._sided,this.element.addClass("lm_"+o._side),["right","bottom"].indexOf(o._side.toString())>=0&&this.element.find(".lm_content").after(this.element.find(".lm_header"))),this.element.css({left:e,top:t}),this._proxyTab=this.element.find(".lm_tab"),this._proxyTab.attr("title",xr(this._contentItem.config.title??"")),this.element.find(".lm_title").html(this._contentItem.config.title??""),this.childElementContainer=this.element.find(".lm_content"),this.childElementContainer.append(i.element),this._updateTree(),this._layoutManager._$calculateItemAreas(),ce(document.body).append(this.element),this._setDimensions(),!this._contentItem.tab&&this._proxyTab.length&&(this._layoutManager.tabDropPlaceholder.width(this._proxyTab.outerWidth(!0)??0),this._layoutManager.tabDropPlaceholder.height(this._proxyTab.outerHeight(!0)??0));var l=this._layoutManager.container.offset();this._minX=l?.left??0,this._minY=l?.top??0,this._maxX=(this._layoutManager.container.width()??0)+this._minX,this._maxY=(this._layoutManager.container.height()??0)+this._minY,this._width=this.element.width()??0,this._height=this.element.height()??0,this._setDropPosition(e,t),this._layoutManager.emit("itemPickedUp",this._contentItem)}_onDrag(e,t,n){const s=n.pageX??0,i=n.pageY??0;!(s>this._minX&&s<this._maxX&&i>this._minY&&i<this._maxY)&&this._layoutManager.config.settings.constrainDragToContainer===!0||this._setDropPosition(s,i)}_setDropPosition(e,t){this.element.css({left:e,top:t}),this._area=this._layoutManager._$getArea(e,t),this._area!==null&&(this._lastValidArea=this._area,this._area.contentItem._$highlightDropZone(e,t,this._area))}_onDrop(){this._layoutManager.dropTargetIndicator?.hide(),this._area!==null?this._area.contentItem._$onDrop(this._contentItem,this._area):this._lastValidArea!==null?this._lastValidArea.contentItem._$onDrop(this._contentItem,this._lastValidArea):this._originalParent?this._originalParent.addChild(this._contentItem):this._contentItem._$destroy(),this._dragListener.off("drag",this._onDrag,this),this._dragListener.off("dragStop",this._onDrop,this),this.element.remove(),this._layoutManager.emit("itemDropped",this._contentItem)}_updateTree(){this._contentItem.parent&&this._contentItem.parent.removeChild(this._contentItem,!0),this._contentItem._$setParent(null)}_setDimensions(){const e=this._layoutManager.config.dimensions;let t=e.dragProxyWidth,n=e.dragProxyHeight;this.element.width(t),this.element.height(n),t-=this._sided?e.headerHeight:0,n-=this._sided?0:e.headerHeight,this.childElementContainer.width(t),this.childElementContainer.height(n),this._contentItem.element.width(t),this._contentItem.element.height(n),this._contentItem.callDownwards("_$show"),this._contentItem.callDownwards("setSize")}}class qh{_element;_itemConfig;_layoutManager;_dragListener;constructor(e,t,n){this._element=e,this._itemConfig=t,this._layoutManager=n,this._dragListener=this._createDragListener()}_createDragListener(){return this._dragListener=new Co(this._element,!0),this._dragListener.on("dragStart",this._onDragStart,this),this._dragListener.on("dragStop",this._createDragListener,this),this._dragListener}_onDragStart(e,t){let n=this._itemConfig;typeof n=="function"&&(n=n());const s=this._layoutManager._$normalizeContentItem(ce.extend(!0,{},n)),i=new Fi(e,t,this._dragListener,this._layoutManager,s,null);this._layoutManager.transitionIndicator?.transitionElements(this._element,i.element)}}class Xh{_element=ce(window);_itemConfig;_layoutManager;_dragListener;constructor(e,t,n){this._itemConfig=e,this._layoutManager=t,this._createDragListener(n)}_createDragListener(e){this._dragListener&&this._dragListener.destroy(),this._element&&(this._dragListener=new Co(this._element,!0),this._dragListener.on("dragStart",this._onDragStart,this),this._dragListener.on("dragStop",this._destroy,this),this._dragListener.onMouseDown(e),this._dragListener._startDrag())}_destroy(){this._dragListener=void 0,this._element=void 0,this._itemConfig=void 0,this._layoutManager=void 0}_onDragStart(e,t){if(!(!this._dragListener||!this._layoutManager)){var n=this._itemConfig;typeof n=="function"&&(n=n());var s=this._layoutManager._$normalizeContentItem(ce.extend(!0,{},n));new Fi(e,t,this._dragListener,this._layoutManager,s,null)}}}class ea{static _template='<div class="lm_dropTargetIndicator"><div class="lm_inner"></div></div>';element=ce(ea._template);constructor(){ce(document.body).append(this.element)}destroy(){this.element.remove()}highlightArea(e){this.element.css({left:e.x1,top:e.y1,width:Math.floor(e.x2-e.x1),height:Math.floor(e.y2-e.y1)}).show()}hide(){this.element.hide()}}class qi{element;_header;_action;constructor(e,t,n,s){this._header=e,this.element=ce('<li class="'+n+'" title="'+t+'"></li>'),this._header.on("destroy",this._$destroy,this),this._action=s,this.element.on("click",this._action),this._header.controlsContainer.append(this.element)}_$destroy(){this.element.off(),this.element.remove()}}class ib extends Error{node;constructor(e,t){super(),this.name="Configuration Error",this.message=e,this.node=t}}const Gs=ib,ob=Object.freeze(Object.defineProperty({__proto__:null,ConfigurationError:Gs},Symbol.toStringTag,{value:"Module"}));function lo(c){return c.isStack}function Bt(c){return c.isComponent}function Zh(c){return c.isRoot}class bt extends fn{config;type;contentItems;parent;layoutManager;element;childElementContainer;componentName;isInitialised=!1;isMaximised=!1;isRoot=!1;isRow=!1;isColumn=!1;isStack=!1;isComponent=!1;tab;_pendingEventPropagations;_throttledEvents;constructor(e,t,n,s){super(),this.element=s,this.config=this._extendItemNode(t),this.type=t.type,this.contentItems=[],this.parent=n,this.layoutManager=e,this._pendingEventPropagations={},this._throttledEvents=["stateChanged"],this.on(fn.ALL_EVENT,this._propagateEvent,this),t.content&&this._createContentItems(t)}callDownwards(e,t=[],n=!1,s=!1){n!==!0&&s!==!0&&this[e].apply(this,t);for(let i=0;i<this.contentItems.length;i++)this.contentItems[i].callDownwards(e,t,n);n===!0&&s!==!0&&this[e].apply(this,t)}removeChild(e,t=!1){const n=this.contentItems.indexOf(e);if(n===-1)throw new Error("Can't remove child item. Unknown content item");t!==!0&&this.contentItems[n]._$destroy(),this.contentItems.splice(n,1),this.config.content?.splice(n,1),this.contentItems.length>0?this.callDownwards("setSize"):this.type!=="root"&&this.config.isClosable&&this.parent?.removeChild(this)}addChild(e,t){e=this.layoutManager._$normalizeContentItem(e,this),t===void 0&&(t=this.contentItems.length),this.contentItems.splice(t,0,e),this.config.content===void 0&&(this.config.content=[]),this.config.content.splice(t,0,e.config),e.parent=this,e.parent.isInitialised===!0&&e.isInitialised===!1&&e._$init()}replaceChild(e,t,n=!1){t=this.layoutManager._$normalizeContentItem(t);const s=this.contentItems.indexOf(e),i=e.element[0].parentNode;if(s===-1)throw new Error("Can't replace child. oldChild is not child of this");i?.replaceChild(t.element[0],e.element[0]),n===!0&&(e.parent=null,e._$destroy()),this.contentItems[s]=t,t.parent=this,lo(this)&&(this.header.tabs[s].contentItem=t),t.parent.isInitialised===!0&&t.isInitialised===!1&&t._$init(),this.callDownwards("setSize")}remove(){this.parent?.removeChild(this)}popout(){var e=this.layoutManager.createPopout(this);return this.emitBubblingEvent("stateChanged"),e}toggleMaximise(e){e&&e.preventDefault(),this.isMaximised===!0?this.layoutManager._$minimiseItem(this):this.layoutManager._$maximiseItem(this),this.isMaximised=!this.isMaximised,this.emitBubblingEvent("stateChanged")}select(){this.layoutManager.selectedItem!==this&&(this.layoutManager.selectItem(this,!0),this.element.addClass("lm_selected"))}deselect(){this.layoutManager.selectedItem===this&&(this.layoutManager.selectedItem=null,this.element.removeClass("lm_selected"))}setTitle(e){this.config.title=e,this.emit("titleChanged",e),this.emitBubblingEvent("stateChanged")}hasId(e){if(this.config.id){if(typeof this.config.id=="string")return this.config.id===e;if(this.config.id instanceof Array)return this.config.id.indexOf(e)!==-1}else return!1}addId(e){this.hasId(e)||(this.config.id?typeof this.config.id=="string"?this.config.id=[this.config.id,e]:this.config.id instanceof Array&&this.config.id.push(e):this.config.id=e)}removeId(e){if(!this.hasId(e))throw new Error("Id not found");if(typeof this.config.id=="string")delete this.config.id;else if(this.config.id instanceof Array){var t=this.config.id.indexOf(e);this.config.id.splice(t,1)}}getItemsByFilter(e){const t=[],n=function(s){for(let i=0;i<s.contentItems.length;i++)e(s.contentItems[i])===!0&&t.push(s.contentItems[i]),n(s.contentItems[i])};return n(this),t}getItemsById(e){return this.getItemsByFilter(function(t){return t.config.id instanceof Array?t.config.id.indexOf(e)!==-1:t.config.id===e})}getItemsByType(e){return this._$getItemsByProperty("type",e)}getComponentsByName(e){const t=this._$getItemsByProperty("componentName",e),n=[];for(let s=0;s<t.length;s++)n.push(t[s].instance);return n}_$getItemsByProperty(e,t){return this.getItemsByFilter(function(n){return n[e]===t})}_$setParent(e){this.parent=e}_$highlightDropZone(e,t,n){this.layoutManager.dropTargetIndicator?.highlightArea(n)}_$onDrop(e,t){this.addChild(e)}_$hide(){this._callOnActiveComponents("hide"),this.element.hide(),this.layoutManager.updateSize()}_$show(){this._callOnActiveComponents("show"),this.element.show(),this.layoutManager.updateSize()}_callOnActiveComponents(e){const t=this.getItemsByType("stack");let n=null;for(let s=0;s<t.length;s++)n=t[s].getActiveContentItem(),n&&Bt(n)&&n.container[e]()}_$destroy(){this.emitBubblingEvent("beforeItemDestroyed"),this.callDownwards("_$destroy",[],!0,!0),this.element.remove(),this.emitBubblingEvent("itemDestroyed")}_$getArea(e){e=e||this.element;const t=e.offset()??{left:0,top:0},n=e.width()??0,s=e.height()??0;return{x1:t.left,y1:t.top,x2:t.left+n,y2:t.top+s,surface:n*s,contentItem:this,side:""}}_$init(){this.setSize();for(let e=0;e<this.contentItems.length;e++)this.childElementContainer?.append(this.contentItems[e].element);this.isInitialised=!0,this.emitBubblingEvent("itemCreated"),this.emitBubblingEvent(this.type+"Created")}emitBubblingEvent(e){var t=new za(e,this);this.emit(e,t)}_createContentItems(e){var t;if(!(e.content instanceof Array))throw new Gs("content must be an Array",e);for(let n=0;n<e.content.length;n++)t=this.layoutManager.createContentItem(e.content[n],this),this.contentItems.push(t)}_extendItemNode(e){for(let[t,n]of Object.entries($h)){const s=t;e[s]===void 0&&(e[s]=n)}return e}_propagateEvent(e,t){t instanceof za&&t.isPropagationStopped===!1&&this.isInitialised===!0&&(this.isRoot===!1&&this.parent?this.parent.emit.apply(this.parent,[e,t]):this._scheduleEventPropagationToLayoutManager(e,t))}_scheduleEventPropagationToLayoutManager(e,t){this._throttledEvents.indexOf(e)===-1?this.layoutManager.emit(e,t.origin):this._pendingEventPropagations[e]!==!0&&(this._pendingEventPropagations[e]=!0,Jl(this._propagateEventToLayoutManager.bind(this,e,t)))}_propagateEventToLayoutManager(e,t){this._pendingEventPropagations[e]=!1,this.layoutManager.emit(e,t)}}class Qh extends bt{config;componentName;container;parent;instance;constructor(e,t,n){super(e,t,n,ce()),this.config=t,this.parent=n;const s=e.getComponent(this.config.componentName)||e.getFallbackComponent(),i=ce.extend(!0,{},this.config.componentState||{});if(s==null)throw new Gs('Unknown component "'+this.config.componentName+'"');i.componentName=this.config.componentName,this.componentName=this.config.componentName,this.config.title===""&&(this.config.title=this.config.componentName),this.isComponent=!0,this.container=new Wa(this.config,this,e),this.instance=new s(this.container,i),this.element=this.container._element}close(){this.parent.removeChild(this)}setSize(){this.element.is(":visible")&&this.container._$setSize(this.element.width(),this.element.height())}_$init(){bt.prototype._$init.call(this),this.container.emit("open")}_$hide(){this.container.hide(),bt.prototype._$hide.call(this)}_$show(){this.container.show(),this.container._config.isFocusOnShow&&this.container._contentElement[0].focus({preventScroll:!0}),bt.prototype._$show.call(this)}_$destroy(){this.container.emit("destroy",this),bt.prototype._$destroy.call(this)}_$getArea(){return null}}class Sl extends bt{isRow;isColumn;childElementContainer;parent;_splitter=[];_splitterSize;_splitterGrabSize;_isColumn;_dimension;_splitterPosition=null;_splitterMinPosition=null;_splitterMaxPosition=null;constructor(e,t,n,s){super(t,n,s,ce('<div class="lm_item lm_'+(e?"column":"row")+'"></div>')),this.parent=s,this.isRow=!e,this.isColumn=e,this.childElementContainer=this.element,this._splitterSize=t.config.dimensions.borderWidth,this._splitterGrabSize=t.config.dimensions.borderGrabWidth,this._isColumn=e,this._dimension=e?"height":"width",this._splitterPosition=null,this._splitterMinPosition=null,this._splitterMaxPosition=null}addChild(e,t,n){var s,i,o,l;if(e=this.layoutManager._$normalizeContentItem(e,this),t===void 0&&(t=this.contentItems.length),this.contentItems.length>0?(l=this._createSplitter(Math.max(0,t-1)).element,t>0?(this.contentItems[t-1].element.after(l),l.after(e.element)):(this.contentItems[0].element.before(l),l.before(e.element))):this.childElementContainer.append(e.element),bt.prototype.addChild.call(this,e,t),s=1/this.contentItems.length*100,n===!0){this.emitBubblingEvent("stateChanged");return}for(o=0;o<this.contentItems.length;o++)this.contentItems[o]===e?e.config[this._dimension]=s:(i=(this.contentItems[o].config[this._dimension]??0)*(100-s)/100,this.contentItems[o].config[this._dimension]=i);this.callDownwards("setSize"),this.emitBubblingEvent("stateChanged")}removeChild(e,t){var n=e.config[this._dimension]??0,s=this.contentItems.indexOf(e),i=Math.max(s-1,0),o,l;if(s===-1)throw new Error("Can't remove child. ContentItem is not child of this Row or Column");for(this._splitter[i]&&(this._splitter[i]._$destroy(),this._splitter.splice(i,1)),o=0;o<this.contentItems.length;o++)this.contentItems[o]!==e&&(this.contentItems[o].config[this._dimension]=(this.contentItems[o].config[this._dimension]??0)+n/(this.contentItems.length-1));bt.prototype.removeChild.call(this,e,t),this.contentItems.length===1&&this.config.isClosable===!0?(l=this.contentItems[0],this.contentItems=[],this.parent.replaceChild(this,l,!0)):(this.callDownwards("setSize"),this.emitBubblingEvent("stateChanged"))}replaceChild(e,t){var n=e.config[this._dimension];super.replaceChild(e,t),t.config[this._dimension]=n,this.callDownwards("setSize"),this.emitBubblingEvent("stateChanged")}setSize(){this.contentItems.length>0&&(this._calculateRelativeSizes(),this._setAbsoluteSizes()),this.emitBubblingEvent("stateChanged"),this.emit("resize")}_$init(){if(this.isInitialised!==!0){var e;for(bt.prototype._$init.call(this),e=0;e<this.contentItems.length-1;e++)this.contentItems[e].element.after(this._createSplitter(e).element)}}_setAbsoluteSizes(){var e,t=this._calculateAbsoluteSizes();for(e=0;e<this.contentItems.length;e++)t.additionalPixel-e>0&&t.itemSizes[e]++,this._isColumn?(this.contentItems[e].element.width(t.totalWidth),this.contentItems[e].element.height(t.itemSizes[e])):(this.contentItems[e].element.width(t.itemSizes[e]),this.contentItems[e].element.height(t.totalHeight))}_calculateAbsoluteSizes(){const e=(this.contentItems.length-1)*this._splitterSize;let t=this.element.width()??0,n=this.element.height()??0,s=0;const i=[];this._isColumn?n-=e:t-=e;for(let l=0;l<this.contentItems.length;l++){const a=this._isColumn?Math.floor(n*((this.contentItems[l].config.height??0)/100)):Math.floor(t*((this.contentItems[l].config.width??0)/100));s+=a,i.push(a)}const o=Math.floor((this._isColumn?n:t)-s);return{itemSizes:i,additionalPixel:o,totalWidth:t,totalHeight:n}}_calculateRelativeSizes(){let e=0;const t=[],n=this._isColumn?"height":"width";for(let s=0;s<this.contentItems.length;s++)this.contentItems[s].config[n]!==void 0?e+=this.contentItems[s].config[n]??0:t.push(this.contentItems[s]);if(Math.round(e)===100){this._respectMinItemWidth();return}if(Math.round(e)<100&&t.length>0){for(let s=0;s<t.length;s++)t[s].config[n]=(100-e)/t.length;this._respectMinItemWidth();return}if(Math.round(e)>100)for(let s=0;s<t.length;s++)t[s].config[n]=50,e+=50;for(let s=0;s<this.contentItems.length;s++)this.contentItems[s].config[n]=(this.contentItems[s].config[n]??0)/e*100;this._respectMinItemWidth()}_respectMinItemWidth(){const e=this.layoutManager.config.dimensions?this.layoutManager.config.dimensions.minItemWidth??0:0,t=[];let n=0,s=0,i=0;const o=[];let l;if(this._isColumn||!e||this.contentItems.length<=1)return;const a=this._calculateAbsoluteSizes();for(let h=0;h<this.contentItems.length;h++){this.contentItems[h];const u=a.itemSizes[h];u<e?(s+=e-u,l={width:e}):(n+=u-e,l={width:u},t.push(l)),o.push(l)}if(s===0||s>n)return;const d=s/n;i=s;for(let h=0;h<t.length;h++){l=t[h];const u=Math.round((l.width-e)*d);i-=u,l.width-=u}i!==0&&(o[o.length-1].width-=i);for(let h=0;h<this.contentItems.length;h++)this.contentItems[h].config.width=o[h].width/a.totalWidth*100}_createSplitter(e){var t;return t=new Jh(this._isColumn,this._splitterSize,this._splitterGrabSize),t.on("drag",this._onSplitterDrag.bind(this,t),this),t.on("dragStop",this._onSplitterDragStop.bind(this,t),this),t.on("dragStart",this._onSplitterDragStart.bind(this,t),this),this._splitter.splice(e,0,t),t}_getItemsForSplitter(e){const t=this._splitter.indexOf(e);if(t<0)throw new Error("Splitter not found in RowOrColumn");return{before:this.contentItems[t],after:this.contentItems[t+1]}}_getMinimumDimensions(e){for(var t=0,n=0,s=0;s<e.length;++s)t=Math.max(e[s].minWidth??0,t),n=Math.max(e[s].minHeight??0,n);return{horizontal:t,vertical:n}}_onSplitterDragStart(e){const t=this._getItemsForSplitter(e),n=this.layoutManager.config.dimensions[this._isColumn?"minItemHeight":"minItemWidth"];var s=this._getMinimumDimensions(t.before.config.content??[]),i=this._isColumn?s.vertical:s.horizontal,o=this._getMinimumDimensions(t.after.config.content??[]),l=this._isColumn?o.vertical:o.horizontal;this._splitterPosition=0,this._splitterMinPosition=-1*((t.before.element[this._dimension]()??0)-(i||n)),this._splitterMaxPosition=(t.after.element[this._dimension]()??0)-(l||n)}_onSplitterDrag(e,t,n){const s=this._isColumn?n:t;this._splitterMaxPosition==null||this._splitterMinPosition==null||s>this._splitterMinPosition&&s<this._splitterMaxPosition&&(this._splitterPosition=s,e.element.css(this._isColumn?"top":"left",s))}_onSplitterDragStop(e){const t=this._getItemsForSplitter(e),n=t.before.element[this._dimension]()??0,s=t.after.element[this._dimension]()??0,i=((this._splitterPosition??0)+n)/(n+s),o=(t.before.config[this._dimension]??0)+(t.after.config[this._dimension]??0);t.before.config[this._dimension]=i*o,t.after.config[this._dimension]=(1-i)*o,e.element.css({top:0,left:0}),Jl(this.callDownwards.bind(this,"setSize",void 0,void 0,void 0))}}class Ka extends bt{childElementContainer;_containerElement;constructor(e,t,n){super(e,{...t,type:"root"},null,ce('<div class="lm_goldenlayout lm_item lm_root"></div>')),this.isRoot=!0,this.type="root",this.childElementContainer=this.element,this._containerElement=n,this._containerElement.append(this.element)}addChild(e,t){if(this.contentItems.length>0)throw new Error("Root node can only have a single child");e=this.layoutManager._$normalizeContentItem(e,this),this.childElementContainer.append(e.element),super.addChild(e,t),this.callDownwards("setSize"),this.emitBubblingEvent("stateChanged")}setSize(e,t){e=typeof e>"u"?this._containerElement.width()??0:e,t=typeof t>"u"?this._containerElement.height()??0:t,this.element.width(e),this.element.height(t),this.contentItems[0]&&(this.contentItems[0].element.width(e),this.contentItems[0].element.height(t))}_$getArea(){const e=super._$getArea();if(e==null)throw new Error("Unable to get root area");return e}_$highlightDropZone(e,t,n){this.layoutManager.tabDropPlaceholder.remove(),super._$highlightDropZone(e,t,n)}_$onDrop(e,t){var n;if(Bt(e)&&(n=this.layoutManager.createContentItem({type:"stack",header:e.config.header||{}},this),n._$init(),n.addChild(e),e=n),!this.contentItems.length)this.addChild(e);else{const{side:s}=t,i=s==="left"||s==="right"?"row":"column",o=s==="left"||s==="right"?"width":"height",l=s==="left"||s==="top",a=this.contentItems[0];if(!(a instanceof Sl)||a.type!=i){const d=this.layoutManager.createContentItem({type:i},this);this.replaceChild(a,d),d.addChild(e,l?0:void 0,!0),d.addChild(a,l?void 0:0,!0),a.config[o]=50,e.config[o]=50,d.callDownwards("setSize")}else{const d=a.contentItems[l?0:a.contentItems.length-1];a.addChild(e,l?0:void 0,!0),d.config[o]=(d.config[o]??0)*.5,e.config[o]=d.config[o],a.callDownwards("setSize")}}}}class Ya extends bt{_activeContentItem=null;_header;childElementContainer=ce('<div class="lm_items"></div>');header;parent;isStack=!0;_dropZones={};_dropSegment=null;_contentAreaDimensions=null;_dropIndex;_side;_sided=!1;config;constructor(e,t,n){super(e,t,n,ce('<div class="lm_item lm_stack"></div>')),this.parent=n,this.config=t;const s=e.config;this._side=!1,this._header={show:s.settings?.hasHeaders&&t.hasHeaders!==!1,popout:s.settings?.showPopoutIcon?s.labels?.popout:void 0,maximise:s.settings?.showMaximiseIcon?s.labels?.maximise:void 0,close:s.settings?.showCloseIcon?s.labels?.close:void 0,minimise:s.labels?.minimise??void 0},s.header&&(this._header={...this._header,...s.header}),t.header&&(this._header={...this._header,...t.header}),t.content&&t.content[0]&&t.content[0].header&&(this._header={...this._header,...t.content[0].header}),this.header=new Ti(e,this),this.element.append(this.header.element),this.element.append(this.childElementContainer),this._setupHeaderPosition(),this._$validateClosability()}setSize(){var e,t=this._header.show?this.layoutManager.config.dimensions?.headerHeight??0:0,n=(this.element.width()??0)-(this._sided?t:0),s=(this.element.height()??0)-(this._sided?0:t);for(this.childElementContainer.width(n),this.childElementContainer.height(s),e=0;e<this.contentItems.length;e++)this.contentItems[e].element.width(n).height(s);this.emit("resize"),this.emitBubblingEvent("stateChanged")}_$init(){if(this.isInitialised!==!0){this.header._attachWheelListener(),super._$init();for(let e=0;e<this.contentItems.length;e++)this.header.createTab(this.contentItems[e]),this.contentItems[e]._$hide();if(this.contentItems.length>0){const e=this.contentItems[this.config.activeItemIndex||0];if(!e)throw new Error("Configured activeItemIndex out of bounds");this.setActiveContentItem(e)}}}setActiveContentItem(e){if(this.contentItems.indexOf(e)===-1)throw new Error("contentItem is not a child of this stack");this._activeContentItem!==null&&this._activeContentItem._$hide(),this._activeContentItem=e,this.header.setActiveContentItem(e),e._$show(),this.emit("activeContentItemChanged",e),this.layoutManager.emit("activeContentItemChanged",e),this.emitBubblingEvent("stateChanged")}getActiveContentItem(){return this.header.activeContentItem}addChild(e,t){e=this.layoutManager._$normalizeContentItem(e,this),super.addChild(e,t),this.childElementContainer.append(e.element),this.header.createTab(e,t),this.setActiveContentItem(e),this.callDownwards("setSize"),this._$validateClosability(),this.emitBubblingEvent("stateChanged")}removeChild(e,t=!1){var n=this.contentItems.indexOf(e);super.removeChild(e,t),this.header.removeTab(e),this.header.activeContentItem===e&&(this.contentItems.length>0?this.setActiveContentItem(this.contentItems[Math.max(n-1,0)]):this._activeContentItem=null),this._$validateClosability(),this.emitBubblingEvent("stateChanged")}_$validateClosability(){let e=this.header._isClosable();for(let t=0,n=this.contentItems.length;t<n&&e;t++)e=this.contentItems[t].config.isClosable??!1;this.header._$setClosable(e)}_$destroy(){bt.prototype._$destroy.call(this),this.header._$destroy()}_$onDrop(e){if(this._dropSegment==="header"){this._resetHeaderDropZone(),this.addChild(e,this._dropIndex);return}if(this._dropSegment==="body"){this.addChild(e);return}const t=this._dropSegment==="top"||this._dropSegment==="bottom",n=this._dropSegment==="left"||this._dropSegment==="right",s=this._dropSegment==="top"||this._dropSegment==="left",i=t&&this.parent.isColumn||n&&this.parent.isRow,o=t?"column":"row",l=t?"height":"width";if(Bt(e)){const a=this.layoutManager.createContentItem({type:"stack",header:e.config.header||{}},this);a._$init(),a.addChild(e),e=a}if(i){const a=this.parent.contentItems.indexOf(this);this.parent.addChild(e,s?a:a+1,!0),this.config[l]=(this.config[l]??0)*.5,e.config[l]=this.config[l],this.parent.callDownwards("setSize")}else{const a=this.layoutManager.createContentItem({type:o},this);this.parent.replaceChild(this,a),a.addChild(e,s?0:void 0,!0),a.addChild(this,s?void 0:0,!0),this.config[l]=50,e.config[l]=50,a.callDownwards("setSize")}}_$highlightDropZone(e,t){if(this._contentAreaDimensions)for(let[n,s]of Object.entries(this._contentAreaDimensions)){const i=s.hoverArea;if(i.x1<e&&i.x2>e&&i.y1<t&&i.y2>t){n==="header"?(this._dropSegment="header",this._highlightHeaderDropZone(e)):(this._resetHeaderDropZone(),this._highlightBodyDropZone(n));return}}}_$getArea(){if(this.element.is(":visible")===!1)return null;const e=super._$getArea(this.header.element),t=super._$getArea(this.childElementContainer);if(e==null||t==null)return null;const n=t.x2-t.x1,s=t.y2-t.y1;return this._contentAreaDimensions={header:{hoverArea:{x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2},highlightArea:{x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2}}},this._activeContentItem&&this._activeContentItem.isComponent===!1?e:this.contentItems.length===0?(this._contentAreaDimensions.body={hoverArea:{x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2},highlightArea:{x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2}},super._$getArea(this.element)):(this._contentAreaDimensions.left={hoverArea:{x1:t.x1,y1:t.y1,x2:t.x1+n*.25,y2:t.y2},highlightArea:{x1:t.x1,y1:t.y1,x2:t.x1+n*.5,y2:t.y2}},this._contentAreaDimensions.top={hoverArea:{x1:t.x1+n*.25,y1:t.y1,x2:t.x1+n*.75,y2:t.y1+s*.5},highlightArea:{x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y1+s*.5}},this._contentAreaDimensions.right={hoverArea:{x1:t.x1+n*.75,y1:t.y1,x2:t.x2,y2:t.y2},highlightArea:{x1:t.x1+n*.5,y1:t.y1,x2:t.x2,y2:t.y2}},this._contentAreaDimensions.bottom={hoverArea:{x1:t.x1+n*.25,y1:t.y1+s*.5,x2:t.x1+n*.75,y2:t.y2},highlightArea:{x1:t.x1,y1:t.y1+s*.5,x2:t.x2,y2:t.y2}},super._$getArea(this.element))}_highlightHeaderDropZone(e){const t=this.header.tabs.length;if(t===0){const u=this.header.element.offset();this.layoutManager.dropTargetIndicator?.highlightArea({x1:u?.left??0,x2:(u?.left??0)+100,y1:this.header.element.offset()?.top??0,y2:(this.header.element.offset()?.top??0)+(this.header.element.innerHeight()??0)});return}const s=this.header.tabsContainer.get(0)?.getBoundingClientRect(),i=this.layoutManager.tabDropPlaceholder.get(0)?.getBoundingClientRect();if(!s||!i)return;e<s.left?e=s.left+1:e>s.right&&(e=s.right-1);let o,l;if(!(i.left<e&&e<i.right)){for(var a=0;a<t;a++)if(o=this.header.tabs[a].element,l=o.get(0)?.getBoundingClientRect(),l&&l.left<e&&e<l.right){this._dropIndex=a;break}o&&l&&e<l.left+l.width*.5?o.before(this.layoutManager.tabDropPlaceholder):o&&(this._dropIndex=Math.min((this._dropIndex??0)+1,t),o.after(this.layoutManager.tabDropPlaceholder))}let d=this.layoutManager.tabDropPlaceholder.offset()?.left??0;d=Math.max(d,this.header.tabsContainer.offset()?.left??0);var h=d+(this.layoutManager.tabDropPlaceholder.width()??0);h=Math.min(h,(this.header.tabsContainer.offset()?.left??0)+(this.header.tabsContainer.innerWidth()??0)),this.layoutManager.dropTargetIndicator?.highlightArea({x1:d,x2:h,y1:this.header.element.offset()?.top??0,y2:(this.header.element.offset()?.top??0)+(this.header.element.innerHeight()??0)})}_resetHeaderDropZone(){this.layoutManager.tabDropPlaceholder.remove()}_setupHeaderPosition(){const e=["right","left","bottom"].some(t=>t===this._header.show)?this._header.show:void 0;if(this.header.element.toggle(!!this._header.show),!!e&&(this._side=e,this._sided=["right","left"].indexOf(this._side.toString())>=0,this.element.removeClass("lm_left lm_right lm_bottom"),this._side&&this.element.addClass("lm_"+this._side),this.element.find(".lm_header").length&&this.childElementContainer)){const t=["right","bottom"].indexOf(this._side.toString())>=0?"before":"after";this.header.element[t](this.childElementContainer),this.callDownwards("setSize")}}_highlightBodyDropZone(e){const t=this._contentAreaDimensions?.[e]?.highlightArea;t&&this.layoutManager.dropTargetIndicator?.highlightArea(t),this._dropSegment=e}}const lb=Object.freeze(Object.defineProperty({__proto__:null,AbstractContentItem:bt,Component:Qh,ContentItem:bt,Root:Ka,RowOrColumn:Sl,Stack:Ya,isComponent:Bt,isRoot:Zh,isStack:lo},Symbol.toStringTag,{value:"Module"}));class ta{static _template=['<li class="lm_tab">','<span class="lm_title_before"></span>','<span class="lm_title"></span>','<div class="lm_close_tab"></div>',"</li>"].join("");header;contentItem;element=ce(ta._template);titleElement;closeElement;isActive=!1;_layoutManager;_dragListener;constructor(e,t){this.header=e,this.contentItem=t,this.titleElement=this.element.find(".lm_title"),this.closeElement=this.element.find(".lm_close_tab"),this.closeElement[t.config.isClosable?"show":"hide"](),this.setTitle(t.config.title),this.contentItem.on("titleChanged",this.setTitle,this),this._layoutManager=this.contentItem.layoutManager,this._layoutManager.config.settings?.reorderEnabled&&t.config.reorderEnabled&&(this._dragListener=new Co(this.element),this._dragListener.on("dragStart",this._onDragStart,this),this.contentItem.on("destroy",this._dragListener.destroy,this._dragListener)),this._onTabClick=this._onTabClick.bind(this),this._onCloseClick=this._onCloseClick.bind(this),this._onTabContentFocusIn=this._onTabContentFocusIn.bind(this),this._onTabContentFocusOut=this._onTabContentFocusOut.bind(this),this.element.on("click",this._onTabClick),this.element.on("auxclick",this._onTabClick),this.contentItem.config.isClosable?(this.closeElement.on("click",this._onCloseClick),this.closeElement.on("mousedown",this._onCloseMousedown)):this.closeElement.remove(),this.contentItem.tab=this,this.contentItem.emit("tab",this),this.contentItem.layoutManager.emit("tabCreated",this),Bt(this.contentItem)&&(this.contentItem.container._contentElement.on("focusin",this._onTabContentFocusIn).on("focusout",this._onTabContentFocusOut),this.contentItem.container.tab=this,this.contentItem.container.emit("tab",this))}setTitle(e=""){this.titleElement.html(e)}setActive(e){e!==this.isActive&&(this.isActive=e,e?this.element.addClass("lm_active"):this.element.removeClass("lm_active"))}_$destroy(){this.element.off("click",this._onTabClick),this.element.off("auxclick",this._onTabClick),this.closeElement.off("click",this._onCloseClick),Bt(this.contentItem)&&(this.contentItem.container._contentElement.off(),this.contentItem.container._contentElement[0].removeEventListener("click",this._onTabContentFocusIn,!0)),this._dragListener&&(this.contentItem.off("destroy",this._dragListener.destroy,this._dragListener),this._dragListener.off("dragStart",this._onDragStart),this._dragListener=void 0),this.element.remove()}_onDragStart(e,t){this.contentItem.parent?.isMaximised&&this.contentItem.parent.toggleMaximise(),this._dragListener&&new Fi(e,t,this._dragListener,this._layoutManager,this.contentItem,this.header.parent)}_onTabContentFocusIn(){ce(".lm_focusin",this._layoutManager.root.element).removeClass("lm_focusin"),this.element.addClass("lm_focusin")}_onTabContentFocusOut(){Bt(this.contentItem)&&!this.contentItem.container._contentElement[0].contains(document.activeElement)&&this.element.removeClass("lm_focusin")}_onTabClick(e){if(!e||e.button===0){var t=this.header.parent.getActiveContentItem();this.contentItem!==t&&Bt(this.contentItem)?this.header.parent.setActiveContentItem(this.contentItem):Bt(this.contentItem)&&!this.contentItem.container._contentElement[0].contains(document.activeElement)&&this.contentItem.container._contentElement.focus(),Bt(this.contentItem)&&this.contentItem.container.emit("tabClicked",e),this.header._hideAdditionalTabsDropdown(),this.element.get(0)?.scrollIntoView({inline:"nearest"})}else e.button===1&&this.contentItem.config.isClosable&&this._onCloseClick(e)}_onCloseClick(e){e.stopPropagation(),Bt(this.contentItem)?this.contentItem.container.close():this.header.parent.removeChild(this.contentItem)}_onCloseMousedown(e){e.stopPropagation()}}class Ti extends fn{static _template=['<div class="lm_header">','<ul class="lm_tabs"></ul>','<ul class="lm_controls"></ul>','<ul class="lm_tabdropdown_list">','<li class="lm_tabdropdown_search"><input type="text" placeholder="Find tab..."></li>',"</ul>","</div>"].join("");static _previousButtonTemplate=['<ul class="lm_controls">','<li class="lm_tabpreviousbutton"></li>',"</ul>"].join("");static _nextButtonTemplate=['<li class="lm_tabnextbutton"></li>'].join("");layoutManager;element=ce(Ti._template);tabsContainer;tabDropdownContainer;tabDropdownSearch;tabDropdownList=null;controlsContainer;parent;tabs=[];activeContentItem=null;closeButton=null;tabDropdownButton=null;tabNextButton=ce(Ti._nextButtonTemplate);tabPreviousButton=ce(Ti._previousButtonTemplate);holdTimer=null;rAF=null;CLICK_TIMEOUT=500;START_SPEED=.01;ACCELERATION=5e-4;SCROLL_LEFT="left";SCROLL_RIGHT="right";isDraggingTab=!1;isOverflowing=!1;isDropdownShown=!1;dropdownKeyIndex=0;_lastVisibleTabIndex=-1;_tabControlOffset;constructor(e,t){super(),this.layoutManager=e,this.layoutManager.config.settings?.selectionEnabled&&(this.element.addClass("lm_selectable"),this.element.on("click",this._onHeaderClick.bind(this))),this.tabsContainer=this.element.find(".lm_tabs"),this.tabDropdownContainer=this.element.find(".lm_tabdropdown_list"),this.tabDropdownContainer.hide(),this.tabDropdownSearch=this.element.find(".lm_tabdropdown_search input"),this._handleFilterInput=this._handleFilterInput.bind(this),this._handleFilterKeydown=this._handleFilterKeydown.bind(this),this.tabDropdownSearch.on("input",this._handleFilterInput),this.tabDropdownSearch.on("keydown",this._handleFilterKeydown),this.controlsContainer=this.element.find(".lm_controls"),this.parent=t,this.parent.on("resize",this._updateTabSizes,this),this._handleItemPickedUp=this._handleItemPickedUp.bind(this),this._handleItemDropped=this._handleItemDropped.bind(this),this._handleNextMouseEnter=this._handleNextMouseEnter.bind(this),this._handleNextMouseLeave=this._handleNextMouseLeave.bind(this),this._handlePreviousMouseEnter=this._handlePreviousMouseEnter.bind(this),this._handlePreviousMouseLeave=this._handlePreviousMouseLeave.bind(this),this._handleScrollRepeat=this._handleScrollRepeat.bind(this),this._handleNextButtonMouseDown=this._handleNextButtonMouseDown.bind(this),this._handlePreviousButtonMouseDown=this._handlePreviousButtonMouseDown.bind(this),this._handleScrollButtonMouseDown=this._handleScrollButtonMouseDown.bind(this),this._handleScrollButtonMouseUp=this._handleScrollButtonMouseUp.bind(this),this._handleScrollEvent=this._handleScrollEvent.bind(this),this.tabNextButton.on("mousedown",this._handleNextButtonMouseDown),this.tabPreviousButton.on("mousedown",this._handlePreviousButtonMouseDown),this.tabsContainer.on("scroll",this._handleScrollEvent),this.layoutManager.on("itemPickedUp",this._handleItemPickedUp),this.layoutManager.on("itemDropped",this._handleItemDropped),this.tabsContainer.before(this.tabPreviousButton),this.tabPreviousButton=this.tabPreviousButton.find(">:first-child"),this.tabPreviousButton.hide(),this._showAdditionalTabsDropdown=this._showAdditionalTabsDropdown.bind(this),this._hideAdditionalTabsDropdown=this._hideAdditionalTabsDropdown.bind(this),this._tabControlOffset=this.layoutManager.config.settings?.tabControlOffset,this._createControls()}createTab(e,t){for(let s=0;s<this.tabs.length;s++)if(this.tabs[s].contentItem===e)return;const n=new ta(this,e);if(this.tabs.length===0){this.tabs.push(n),this.tabsContainer.append(n.element);return}t===void 0&&(t=this.tabs.length),t>0?this.tabs[t-1].element.after(n.element):this.tabs[0].element.before(n.element),this.tabs.splice(t,0,n),this._updateTabSizes()}removeTab(e){for(var t=0;t<this.tabs.length;t++)if(this.tabs[t].contentItem===e){this.tabs[t]._$destroy(),this.tabs.splice(t,1);return}throw new Error("contentItem is not controlled by this header")}setActiveContentItem(e){for(var t,n=0;n<this.tabs.length;n++)t=this.tabs[n].contentItem===e,this.tabs[n].setActive(t),t===!0&&(this.activeContentItem=e,this.parent.config.activeItemIndex=n);this.tabs[this.parent.config.activeItemIndex??0].element.get(0)?.scrollIntoView({inline:"nearest"}),this._hideAdditionalTabsDropdown(),this._updateTabSizes(),this.parent.emitBubblingEvent("stateChanged")}position(e){let t=this.parent._header.show;return t&&!this.parent._side&&(t="top"),e!==void 0&&this.parent._header.show!==e&&(this.parent._header.show=e,this.parent._setupHeaderPosition()),t}_attachWheelListener(){this.tabsContainer.get(0)?.addEventListener("wheel",this._handleWheelEvent,{passive:!0})}_detachWheelListener(){this.tabsContainer.get(0)?.removeEventListener("wheel",this._handleWheelEvent)}_handleWheelEvent(e){const t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=Math.abs(e.deltaY)>Math.abs(e.deltaX)?e.deltaY:e.deltaX;e.deltaMode===WheelEvent.DOM_DELTA_PAGE?n*=this.tabsContainer.innerWidth()??1:e.deltaMode===WheelEvent.DOM_DELTA_LINE&&(n*=100/3),t.scrollLeft+=Math.round(n)}_handleScrollEvent(){this._checkScrollArrows()}_handleItemPickedUp(){this.isDraggingTab=!0,this.controlsContainer.on("mouseenter",this._handleNextMouseEnter),this.tabPreviousButton.on("mouseenter",this._handlePreviousMouseEnter)}_handleItemDropped(){this.isDraggingTab=!1,window.cancelAnimationFrame(this.rAF??-1),this.rAF=null,this.controlsContainer.off("mouseenter",this._handleNextMouseEnter),this.controlsContainer.off("mouseleave",this._handleNextMouseLeave),this.tabPreviousButton.off("mouseenter",this._handlePreviousMouseEnter),this.tabPreviousButton.off("mouseleave",this._handlePreviousMouseLeave)}_handleNextMouseEnter(){this.controlsContainer.on("mouseleave",this._handleNextMouseLeave),this._handleScrollRepeat(this.SCROLL_RIGHT,this.tabsContainer.scrollLeft()??0)}_handlePreviousMouseEnter(){this.tabPreviousButton.on("mouseleave",this._handlePreviousMouseLeave),this._handleScrollRepeat(this.SCROLL_LEFT,this.tabsContainer.scrollLeft()??0)}_handleNextMouseLeave(){window.cancelAnimationFrame(this.rAF??-1),this.rAF=null,this.controlsContainer.off("mouseleave",this._handleNextMouseLeave)}_handlePreviousMouseLeave(){window.cancelAnimationFrame(this.rAF??-1),this.rAF=null,this.tabPreviousButton.off("mouseleave",this._handlePreviousMouseLeave)}_handleNextButtonMouseDown(){var e;for(let t=0;t<this.tabs.length;t+=1)if((this.tabs[t].element.get(0)?.offsetLeft??0)>(this.tabsContainer.get(0)?.offsetWidth??0)+(this.tabsContainer.scrollLeft()??0)){e=this.tabs[t].element.get(0);break}if(e)e.scrollIntoView({behavior:"smooth",inline:"nearest"}),this._handleScrollButtonMouseDown(this.SCROLL_RIGHT);else{const t=this.tabsContainer.get(0);t&&(t.scrollLeft=this.tabsContainer.get(0)?.scrollWidth??0)}}_handlePreviousButtonMouseDown(){for(var e,t=this.tabs.length-1;t>=0;t-=1)if((this.tabs[t].element.get(0)?.offsetLeft??0)<(this.tabsContainer.scrollLeft()??0)){e=this.tabs[t].element.get(0);break}if(e)e.scrollIntoView({behavior:"smooth",inline:"start"}),this._handleScrollButtonMouseDown(this.SCROLL_LEFT);else{const n=this.tabsContainer.get(0);n&&(n.scrollLeft=0)}}_handleScrollButtonMouseDown(e){this.holdTimer=window.setTimeout(()=>{this._handleScrollRepeat(e,this.tabsContainer.scrollLeft()??0,100)},this.CLICK_TIMEOUT),window.addEventListener("mouseup",this._handleScrollButtonMouseUp)}_handleScrollButtonMouseUp(){clearTimeout(this.holdTimer??-1),this.holdTimer=null,cancelAnimationFrame(this.rAF??-1),this.rAF=null,window.removeEventListener("mouseup",this._handleScrollButtonMouseUp)}_checkScrollArrows(){this.tabsContainer.scrollLeft()===0?this.tabPreviousButton.first().prop("disabled",!0):(this.tabsContainer.scrollLeft()??0)+(this.tabsContainer.innerWidth()??0)===this.tabsContainer.get(0)?.scrollWidth?this.tabNextButton.prop("disabled",!0):(this.tabNextButton.prop("disabled",!1),this.tabPreviousButton.first().prop("disabled",!1))}_handleScrollRepeat(e,t,n=0,s){const i=this.tabsContainer.get(0);if(!i)return;const o=i.getBoundingClientRect();if(e===this.SCROLL_LEFT){if(this.tabsContainer.scrollLeft(t-n),this.isDraggingTab&&this.parent._highlightHeaderDropZone(o.left-1),this.tabsContainer.scrollLeft()===0){this._checkScrollArrows();return}}else if(e===this.SCROLL_RIGHT&&(this.tabsContainer.scrollLeft(t+n),this.isDraggingTab&&this.parent._highlightHeaderDropZone(o.right+1),(this.tabsContainer.scrollLeft()??0)+(this.tabsContainer.innerWidth()??0)===i.scrollWidth)){this._checkScrollArrows();return}window.cancelAnimationFrame(this.rAF??-1),this.rAF=window.requestAnimationFrame(l=>{var a=s||l,d=l-a,h=this.START_SPEED*d+.5*this.ACCELERATION*(d*d);h=Math.min(h,this.tabsContainer.get(0)?.scrollWidth??1/0),this._handleScrollRepeat(e,t,h,a)})}_$setClosable(e){return this.closeButton&&this._isClosable()?(this.closeButton.element[e?"show":"hide"](),!0):!1}_$destroy(){this.emit("destroy",this);for(var e=0;e<this.tabs.length;e++)this.tabs[e]._$destroy();this._detachWheelListener(),this._handleItemDropped(),ce(document).off("mouseup",this._hideAdditionalTabsDropdown),this.tabDropdownSearch.off("input",this._handleFilterInput),this.tabDropdownSearch.off("keydown",this._handleFilterKeydown),this.element.remove()}_getHeaderSetting(e){if(e in this.parent._header)return this.parent._header[e]}_createControls(){var e,t,n,s,i;if(i=this.layoutManager.config.labels.tabDropdown,this.layoutManager.config.labels.tabNextLabel,this.layoutManager.config.labels.tabPreviousLabel,this.tabDropdownButton=new qi(this,i,"lm_tabdropdown",this._showAdditionalTabsDropdown),this.tabDropdownButton.element.hide(),this.controlsContainer.prepend(this.tabNextButton),this.tabNextButton.hide(),this._getHeaderSetting("popout")&&(t=this._onPopoutClick.bind(this),n=this._getHeaderSetting("popout"),new qi(this,n,"lm_popout",t)),this._getHeaderSetting("maximise")){s=this.parent.toggleMaximise.bind(this.parent);const o=this._getHeaderSetting("maximise"),l=this._getHeaderSetting("minimise"),a=new qi(this,o,"lm_maximise",s);this.parent.on("maximised",function(){a.element.attr("title",l??"")}),this.parent.on("minimised",function(){a.element.attr("title",o??"")})}this._isClosable()&&(e=this.parent.remove.bind(this.parent),n=this._getHeaderSetting("close"),this.closeButton=new qi(this,n,"lm_close",e))}_showAdditionalTabsDropdown(){if(this.isDropdownShown){this._hideAdditionalTabsDropdown();return}this.tabDropdownList=this.tabsContainer.clone(!0).appendTo(this.tabDropdownContainer).children().removeClass("lm_active"),this.tabDropdownContainer.show(),this.isDropdownShown=!0,this.element.addClass("lm_dropdown_open"),this.tabDropdownSearch.val("").focus(),this.dropdownKeyIndex=0,this.tabDropdownList.eq(this.dropdownKeyIndex).addClass("lm_keyboard_active"),ce(document).on("mousedown",this._hideAdditionalTabsDropdown),this._updateAdditionalTabsDropdown()}_handleFilterKeydown(e){if(this.dropdownKeyIndex===-1)return;if(e.key==="Escape"){this._hideAdditionalTabsDropdown();return}if(e.key==="Enter"||e.key===" "){this._hideAdditionalTabsDropdown(),this.tabs[this.dropdownKeyIndex]._onTabClick();return}function t(n,s,i){if(i==null||i.length<2)return-1;for(var o=(n+s+i.length)%i.length;o!==n;){if(i.eq(o).css("display")!=="none")return o;o=(o+s+i.length)%i.length}return n}e.key==="ArrowDown"||e.key==="Tab"&&e.shiftKey===!1?(e.preventDefault(),this.tabDropdownList?.eq(this.dropdownKeyIndex).removeClass("lm_keyboard_active"),this.dropdownKeyIndex=t(this.dropdownKeyIndex,1,this.tabDropdownList),this.tabDropdownList?.eq(this.dropdownKeyIndex).addClass("lm_keyboard_active")):(e.key==="ArrowUp"||e.key==="Tab")&&(e.preventDefault(),this.tabDropdownList?.eq(this.dropdownKeyIndex).removeClass("lm_keyboard_active"),this.dropdownKeyIndex=t(this.dropdownKeyIndex,-1,this.tabDropdownList),this.tabDropdownList?.eq(this.dropdownKeyIndex).addClass("lm_keyboard_active"))}_handleFilterInput(e){if(this.tabDropdownList!=null){this.tabDropdownList.eq(this.dropdownKeyIndex).removeClass("lm_keyboard_active"),this.dropdownKeyIndex=-1;for(var t=0;t<this.tabDropdownList.length;t++)(this.tabs[t].contentItem.config.title?.toLowerCase().indexOf(e.target.value.toLowerCase())??-1)!==-1?(this.tabDropdownList.eq(t).css("display",""),this.dropdownKeyIndex===-1&&(this.dropdownKeyIndex=t)):this.tabDropdownList.eq(t).css("display","none");this.dropdownKeyIndex!==-1&&this.tabDropdownList.eq(this.dropdownKeyIndex).addClass("lm_keyboard_active")}}_hideAdditionalTabsDropdown(e){this.isDropdownShown&&(e&&this.tabDropdownContainer.get(0)?.contains(e.target)||e&&this.tabDropdownButton?.element.get(0)===e.target||(this.element.removeClass("lm_dropdown_open"),this.tabDropdownContainer.hide(),this.isDropdownShown=!1,this.tabDropdownContainer.find(".lm_tabs").remove(),ce(document).off("mousedown",this._hideAdditionalTabsDropdown)))}_updateAdditionalTabsDropdown(){this.tabDropdownContainer.css("max-height","");const e=this.tabDropdownContainer[0].scrollHeight;if(e===0)return;const t=(this.tabDropdownContainer.offset()?.top??0)-(ce(window).scrollTop()??0);t+e>(ce(window).height()??0)&&this.tabDropdownContainer.css("max-height",(ce(window).height()??0)-t-10)}_isClosable(){return Boolean(this.parent.config.isClosable&&this.layoutManager.config.settings.showCloseIcon)}_onPopoutClick(){this.layoutManager.config.settings.popoutWholeStack===!0?this.parent.popout():this.activeContentItem?.popout()}_onHeaderClick(e){e.target===this.element[0]&&this.parent.select()}_updateTabSizes(){if(this.tabs.length===0)return;const e=this.tabsContainer.get(0);e&&(!this.isOverflowing&&e.scrollWidth>e.clientWidth?(this.tabDropdownButton?.element.show(),this.tabNextButton.show(),this.tabPreviousButton.show(),this.isOverflowing=!0):this.isOverflowing&&e.scrollWidth<=e.clientWidth&&(this.tabDropdownButton?.element.hide(),this.tabNextButton.hide(),this.tabPreviousButton.hide(),this.isOverflowing=!1),this.isOverflowing&&this._checkScrollArrows())}}class Jh{_isVertical;_size;_grabSize;_dragListener;element;constructor(e,t,n){this._isVertical=e,this._size=t,this._grabSize=n<t?t:n,this.element=this._createElement(),this._dragListener=new Co(this.element)}on(e,t,n){this._dragListener?.on(e,t,n)}_$destroy(){this._dragListener?.destroy(),this._dragListener=null,this.element.remove()}_createElement(){var e=ce('<div class="lm_drag_handle"></div>'),t=ce('<div class="lm_splitter"></div>');t.append(e);var n=this._grabSize-this._size,s=n/2;return this._isVertical?(e.css("top",-s),e.css("height",this._size+n),t.addClass("lm_vertical"),t.height(this._size)):(e.css("left",-s),e.css("width",this._size+n),t.addClass("lm_horizontal"),t.width(this._size)),t}}class eu{_element=ce('<div class="lm_transition_indicator"></div>');_toElement=null;_fromDimensions={};_totalAnimationDuration=200;_animationStartTime=null;constructor(){ce(document.body).append(this._element)}destroy(){this._element.remove()}transitionElements(e,t){}_nextAnimationFrame(){if(!this._toElement||this._animationStartTime==null)return;const e=this._measure(this._toElement),t=(Date.now()-this._animationStartTime)/this._totalAnimationDuration,n={};if(t>=1){this._element.hide();return}e.opacity=0;const s=Object.keys(this._fromDimensions);for(let i of s)n[i]=(this._fromDimensions[i]??0)+((e[i]??0)-(this._fromDimensions[i]??0))*t;this._element.css(n),Jl(this._nextAnimationFrame.bind(this))}_measure(e){const t=e.offset();return{left:t?.left,top:t?.top,width:e.outerWidth(),height:e.outerHeight()}}}const ab=Object.freeze(Object.defineProperty({__proto__:null,BrowserPopout:Yh,DragProxy:Fi,DragSource:qh,DragSourceFromEvent:Xh,DropTargetIndicator:ea,Header:Ti,HeaderButton:qi,Splitter:Jh,Tab:ta,TransitionIndicator:eu},Symbol.toStringTag,{value:"Module"})),rb={config:YC,container:qC,controls:ab,errors:ob,items:lb,utils:sb},db=rb;class tu extends fn{static __lm=db;static minifyConfig(e){return Dr(e)}static unminifyConfig(e){return Ga(e)}isInitialised=!1;_isFullPage=!1;_resizeTimeoutId;_components={"lm-react-component":zh};_fallbackComponent;_itemAreas=[];_maximisedItem=null;_maximisePlaceholder=ce('<div class="lm_maximise_place"></div>');_creationTimeoutPassed=!1;_subWindowsCreated=!1;_dragSources=[];_updatingColumnsResponsive=!1;_firstLoad=!0;width=null;height=null;root;openPopouts=[];selectedItem=null;isSubWindow=!1;eventHub=new Kh(this);config;container;_originalContainer;dropTargetIndicator=null;transitionIndicator=null;tabDropPlaceholder=ce('<div class="lm_drop_tab_placeholder"></div>');_typeToItem;constructor(e,t){super(),this._onResize=this._onResize.bind(this),this._onUnload=this._onUnload.bind(this),this._windowBlur=this._windowBlur.bind(this),this._windowFocus=this._windowFocus.bind(this),this.config=this._createConfig(e),this._originalContainer=t,this.container=this._getContainer(),this.isSubWindow&&ce("body").css("visibility","hidden"),this._typeToItem={column:Sl.bind(this,!0),row:Sl.bind(this,!1),stack:Ya,component:Qh}}registerComponent(e,t){if(typeof t!="function"&&(t==null||t.render==null||typeof t.render!="function"))throw new Error("Please register a constructor function");if(this._components[e]!==void 0)throw new Error("Component "+e+" is already registered");return this._components[e]=t,()=>{if(this._components[e]===void 0)throw new Error("Component "+e+" is not registered");delete this._components[e]}}setFallbackComponent(e){this._fallbackComponent=e}toConfig(e){if(this.isInitialised===!1)throw new Error("Can't create config, layout not yet initialised");if(e&&!(e instanceof bt))throw new Error("Root must be a ContentItem");const t={settings:{...this.config.settings},dimensions:{...this.config.dimensions},labels:{...this.config.labels},content:[]},n=function(s,i){for(let o in i.config)o!=="content"&&(s[o]=i.config[o]);if(s.componentName==="lm-react-component"&&(s.type="react-component"),i.contentItems.length){s.content=[];for(let o=0;o<i.contentItems.length;o++)s.content[o]={},n(s.content[o],i.contentItems[o])}};e?n(t,{contentItems:[e]}):n(t,this.root),this._$reconcilePopoutWindows(),t.openPopouts=[];for(let s=0;s<this.openPopouts.length;s++)t.openPopouts.push(this.openPopouts[s].toConfig());return t.maximisedItemId=this._maximisedItem?"__glMaximised":void 0,t}getComponent(e){return this._components[e]}getFallbackComponent(){return this._fallbackComponent}init(){if(this._subWindowsCreated===!1&&(this._createSubWindows(),this._subWindowsCreated=!0),document.readyState==="loading"||document.body===null){ce(document).ready(this.init.bind(this));return}if(this.isSubWindow===!0&&this._creationTimeoutPassed===!1){setTimeout(this.init.bind(this),7),this._creationTimeoutPassed=!0;return}this.isSubWindow===!0&&this._adjustToWindowMode(),this._setContainer(),this.dropTargetIndicator=new ea,this.transitionIndicator=new eu,this.updateSize(),this._create(this.config),this._bindEvents(),this.isInitialised=!0,this._adjustColumnsResponsive(),this.emit("initialised")}updateSize(e,t){this.width=e??this.container.width()??0,this.height=t??this.container.height()??0,this.isInitialised===!0&&(this.root.callDownwards("setSize",[this.width,this.height]),this._maximisedItem&&(this._maximisedItem.element.width(this.container.width()??0),this._maximisedItem.element.height(this.container.height()??0),this._maximisedItem.callDownwards("setSize")),this._adjustColumnsResponsive())}destroy(){this.isInitialised===!1||!this.root||(this._onUnload(),ce(window).off("resize",this._onResize),ce(window).off("unload beforeunload",this._onUnload),ce(window).off("blur.lm").off("focus.lm"),this.root.callDownwards("_$destroy",[],!0),this.root.contentItems=[],this.tabDropPlaceholder.remove(),this.dropTargetIndicator?.destroy(),this.transitionIndicator?.destroy(),this.eventHub.destroy(),this._dragSources.forEach(function(e){e._dragListener.destroy()}),this._dragSources=[])}createContentItem(e,t){var n,s;if(typeof e.type!="string")throw new Gs("Missing parameter 'type'",e);if(e.type==="react-component"&&(e.type="component",e.componentName="lm-react-component"),!this._typeToItem[e.type])throw n="Unknown type '"+e.type+"'. Valid types are "+Object.keys(this._typeToItem).join(","),new Gs(n);return e.type==="component"&&!(t instanceof Ya)&&t&&!(this.isSubWindow===!0&&t instanceof Ka)&&(e={type:"stack",width:e.width,height:e.height,content:[e]}),s=new this._typeToItem[e.type](this,e,t),s}createPopout(e,t,n,s){let i=[];const o=e instanceof bt,l=this;if(o){i=this.toConfig(e).content,n=Rr();let d=e.parent,h=e;for(;d?.contentItems.length===1&&!d.isRoot;)h=d,d=d.parent;d?.addId(n),(s==null||Number.isNaN(s))&&(s=d?.contentItems.indexOf(h))}else e instanceof Array?i=e:i=[e];if(!t&&o){const d=window.screenX||window.screenLeft,h=window.screenY||window.screenTop,u=e.element.offset()??{left:0,top:0};t={left:d+u.left,top:h+u.top,width:e.element.width()??0,height:e.element.height()??0}}if(!t&&!o&&(t={left:window.screenX||window.screenLeft+20,top:window.screenY||window.screenTop+20,width:500,height:309}),o&&e.remove(),!t||!n||s===void 0)return;const a=new Yh(i,t,n,s,this);return a.on("initialised",function(){l.emit("windowOpened",a)}),a.on("closed",function(){l._$reconcilePopoutWindows()}),this.openPopouts.push(a),a}createDragSource(e,t){this.config.settings.constrainDragToContainer=!1;var n=new qh(e,t,this);return this._dragSources.push(n),n}createDragSourceFromEvent(e,t){return this.config.settings.constrainDragToContainer=!1,new Xh(e,this,t)}selectItem(e,t){if(this.config.settings.selectionEnabled!==!0)throw new Error("Please set selectionEnabled to true to use this feature");e!==this.selectedItem&&(this.selectedItem!==null&&this.selectedItem.deselect(),e&&t!==!0&&e.select(),this.selectedItem=e,this.emit("selectionChanged",e))}_$maximiseItem(e){this._maximisedItem!==null&&this._$minimiseItem(this._maximisedItem),this._maximisedItem=e,this._maximisedItem.addId("__glMaximised"),e.element.addClass("lm_maximised"),e.element.after(this._maximisePlaceholder),this.root.element.prepend(e.element),e.element.width(this.container.width()??0),e.element.height(this.container.height()??0),e.callDownwards("setSize"),this._maximisedItem.emit("maximised"),this.emit("stateChanged")}_$minimiseItem(e){e.element.removeClass("lm_maximised"),e.removeId("__glMaximised"),this._maximisePlaceholder.after(e.element),this._maximisePlaceholder.remove(),e.parent?.callDownwards("setSize"),this._maximisedItem=null,e.emit("minimised"),this.emit("stateChanged")}_$closeWindow(){window.setTimeout(function(){window.close()},1)}_$getArea(e,t){let n=1/0,s=null;for(let i=0;i<this._itemAreas.length;i++){const o=this._itemAreas[i];e>o.x1&&e<o.x2&&t>o.y1&&t<o.y2&&n>o.surface&&(n=o.surface,s=o)}return s}_$createRootItemAreas(){const t={...this.root._$getArea()},n=[{...t,side:"left",x2:t.x1+50},{...t,side:"right",x1:t.x2-50},{...t,side:"top",y2:t.y1+50},{...t,side:"bottom",y1:t.y2-50}];n.forEach(s=>{s.surface=(s.x2-s.x1)*(s.y2-s.y1)}),this._itemAreas.push(...n)}_$calculateItemAreas(){const e=this._getAllContentItems();if(this._itemAreas=[],e.length===1){this._itemAreas.push(this.root._$getArea());return}this._$createRootItemAreas();for(let t=0;t<e.length;t++){const n=e[t];if(!lo(n))continue;const s=n._$getArea();if(s!==null)if(s instanceof Array)this._itemAreas=this._itemAreas.concat(s);else{this._itemAreas.push(s);let i={...s,...s.contentItem._contentAreaDimensions?.header.highlightArea};i.surface=(i.x2-i.x1)*(i.y2-i.y1),this._itemAreas.push(i)}}}_$normalizeContentItem(e,t){if(!e)throw new Error("No content item defined");if(typeof e=="function"&&(e=e()),e instanceof bt)return e;if(ce.isPlainObject(e)&&e.type){var n=this.createContentItem(e,t);return n.callDownwards("_$init"),n}else throw new Error("Invalid contentItem")}_$reconcilePopoutWindows(){const e=[];for(let t=0;t<this.openPopouts.length;t++)this.openPopouts[t].getWindow()?.closed===!1?e.push(this.openPopouts[t]):this.emit("windowClosed",this.openPopouts[t]);this.openPopouts.length!==e.length&&(this.emit("stateChanged"),this.openPopouts=e)}_getAllContentItems(){const e=[],t=n=>{if(e.push(n),n.contentItems instanceof Array)for(let s=0;s<n.contentItems.length;s++)t(n.contentItems[s])};return t(this.root),e}_bindEvents(){this._isFullPage&&ce(window).resize(this._onResize),ce(window).on("unload beforeunload",this._onUnload).on("blur.lm",this._windowBlur).on("focus.lm",this._windowFocus)}_windowBlur(){this.root.element.addClass("lm_window_blur")}_windowFocus(){this.root.element.removeClass("lm_window_blur")}_onResize(){clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=window.setTimeout(this.updateSize.bind(this),100)}_createConfig(e){var t=Gh("gl-window");t&&(this.isSubWindow=!0,e=JSON.parse(localStorage.getItem(t)||"{}"),e=Ga(e),localStorage.removeItem(t)),e=ce.extend(!0,{},Uh,e);var n=function(s){for(var i in s){const o=s[i];i!=="props"&&typeof o=="object"&&o!=null?n(o):i==="type"&&o==="react-component"&&(s.type="component",s.componentName="lm-react-component")}};return n(e),e.settings?.hasHeaders===!1&&(e.dimensions.headerHeight=0),e}_adjustToWindowMode(){var e=ce('<div class="lm_popin" title="'+this.config.labels.popin+'"><div class="lm_icon"></div><div class="lm_bg"></div></div>');e.click(()=>{this.emit("popIn")}),document.title=xr(this.config.content[0].title??""),ce("head").append(ce("body link, body style, template, .gl_keep")),this.container=ce("body").html("").css("visibility","visible").append(e),document.body.offsetHeight,window.__glInstance=this}_createSubWindows(){if(this.config.openPopouts)for(let e=0;e<this.config.openPopouts.length;e++){const t=this.config.openPopouts[e];this.createPopout(t.content,t.dimensions,t.parentId,t.indexInParent)}}_getContainer(){const e=this._originalContainer?ce(this._originalContainer):ce("body");if(e.length===0)throw new Error("GoldenLayout container not found");if(e.length>1)throw new Error("GoldenLayout more than one container element specified");return e}_setContainer(){const e=this._getContainer();e[0]===document.body&&(this._isFullPage=!0,ce("html, body").css({height:"100%",margin:0,padding:0,overflow:"hidden"})),this.container=e}_create(e){var t;if(!(e.content instanceof Array))throw e.content===void 0?t="Missing setting 'content' on top level of configuration":t="Configuration parameter 'content' must be an array",new Gs(t,e);if(e.content.length>1)throw t="Top level content can't contain more then one element.",new Gs(t,e);this.root=new Ka(this,{content:e.content},this.container),this.root.callDownwards("_$init"),e.maximisedItemId==="__glMaximised"&&this.root.getItemsById(e.maximisedItemId)[0].toggleMaximise()}_onUnload(){if(this.config.settings.closePopoutsOnUnload===!0)for(var e=0;e<this.openPopouts.length;e++)this.openPopouts[e].close()}_adjustColumnsResponsive(){if(!this._useResponsiveLayout()||this._updatingColumnsResponsive||!this.config.dimensions||!this.config.dimensions.minItemWidth||this.root.contentItems.length===0||!this.root.contentItems[0].isRow){this._firstLoad=!1;return}this._firstLoad=!1;var e=this.root.contentItems[0].contentItems.length;if(!(e<=1)){var t=this.config.dimensions.minItemWidth,n=e*t;if(!(this.width==null||n<=this.width)){this._updatingColumnsResponsive=!0;for(var s=Math.max(Math.floor(this.width/t),1),i=e-s,o=this.root.contentItems[0],l=this._findAllStackContainers()[0],a=0;a<i;a++){var d=o.contentItems[o.contentItems.length-1];this._addChildContentItemsToContainer(l,d)}this._updatingColumnsResponsive=!1}}}_useResponsiveLayout(){return this.config.settings&&(this.config.settings.responsiveMode=="always"||this.config.settings.responsiveMode=="onload"&&this._firstLoad)}_addChildContentItemsToContainer(e,t){t.type==="stack"?t.contentItems.forEach(function(n){e.addChild(n),t.removeChild(n,!0)}):t.contentItems.forEach(n=>{this._addChildContentItemsToContainer(e,n)})}_findAllStackContainers(){const e=[];return this._findAllStackContainersRecursive(e,this.root),e}_findAllStackContainersRecursive(e,t){t.contentItems.forEach(n=>{lo(n)?e.push(n):n.isComponent||this._findAllStackContainersRecursive(e,n)})}}const cb="_lm_root_15d73_3",hb="_lm_row_15d73_7",ub="_lm_item_15d73_7",mb="_lm_content_15d73_11",gb="_lm_dragging_15d73_17",pb="_lm_maximised_15d73_23",fb="_lm_maximise_placeholder_15d73_30",Cb="_lm_splitter_15d73_34",bb="_lm_vertical_15d73_41",Sb="_lm_drag_handle_15d73_41",wb="_lm_horizontal_15d73_46",vb="_lm_header_15d73_56",Tb="_lm_dropdown_open_15d73_63",Eb="_lm_controls_15d73_69",yb="_lm_tabs_15d73_89",Rb="_lm_tab_15d73_89",xb="_lm_title_15d73_104",Db="_lm_close_tab_15d73_111",Ib="_lm_stack_15d73_120",Fb="_lm_left_15d73_120",Nb="_lm_right_15d73_121",kb="_lm_dragProxy_15d73_125",Mb="_lm_items_15d73_148",Lb="_lm_tabdropdown_list_15d73_165",Ob="_lm_bottom_15d73_192",Ab="_lm_drop_tab_placeholder_15d73_207",_b="_lm_tabdropdown_15d73_165",Pb="_lm_dropTargetIndicator_15d73_258",jb="_lm_inner_15d73_264",Hb="_lm_transition_indicator_15d73_272",Bb="_lm_popin_15d73_282",Ub="_lm_bg_15d73_297",Vb="_lm_icon_15d73_300",$b="_lm_goldenlayout_15d73_304",Wb="_lm_selectable_15d73_340",Gb="_lm_active_15d73_370",zb="_lm_selected_15d73_388",Kb="_lm_keyboard_active_15d73_397",Yb="_lm_popout_15d73_416",qb="_lm_maximise_15d73_23",Xb="_lm_close_15d73_111",Zb="_lm_tabnextbutton_15d73_425",Qb="_lm_tabpreviousbutton_15d73_428",Jb="_lm_title_before_15d73_544",eS="_lm_focusin_15d73_568",tS="_lm_window_blur_15d73_573",nS="_lm_tabdropdown_search_15d73_631",sS="_march_15d73_1",iS="_app_15d73_712",oS="_plotly_15d73_721",Ud={"tab-height":"28px","drag-border-width":"5px",lm_root:cb,lm_row:hb,lm_item:ub,lm_content:mb,lm_dragging:gb,lm_maximised:pb,lm_maximise_placeholder:fb,lm_splitter:Cb,lm_vertical:bb,lm_drag_handle:Sb,lm_horizontal:wb,lm_header:vb,lm_dropdown_open:Tb,lm_controls:Eb,lm_tabs:yb,lm_tab:Rb,lm_title:xb,lm_close_tab:Db,lm_stack:Ib,lm_left:Fb,lm_right:Nb,lm_dragProxy:kb,lm_items:Mb,lm_tabdropdown_list:Lb,lm_bottom:Ob,lm_drop_tab_placeholder:Ab,lm_tabdropdown:_b,lm_dropTargetIndicator:Pb,lm_inner:jb,lm_transition_indicator:Hb,lm_popin:Bb,lm_bg:Ub,lm_icon:Vb,lm_goldenlayout:$b,lm_selectable:Wb,lm_active:Gb,lm_selected:zb,lm_keyboard_active:Kb,lm_popout:Yb,lm_maximise:qb,lm_close:Xb,lm_tabnextbutton:Zb,lm_tabpreviousbutton:Qb,lm_title_before:Jb,"editor-unsaved-indicator":"_editor-unsaved-indicator_15d73_548","is-unsaved":"_is-unsaved_15d73_556",lm_focusin:eS,lm_window_blur:tS,lm_tabdropdown_search:nS,march:sS,app:iS,"js-plotly-plot":"_js-plotly-plot_15d73_721",plotly:oS},Vd=Object.freeze({tabHeight:parseInt(Ud["tab-height"],10),dragBorderWidth:parseInt(Ud["drag-border-width"],10)}),ss=ne.module("LayoutUtils");function nu(c){return c.componentName!==void 0}function pi(c){const e=c;return(nu(c)&&c.componentName==="lm-react-component"||c.type==="react-component")&&e.component!==void 0}function jo(c){return c.focus!==void 0}function $d(c){return c.type==="stack"}class K{static DEFAULT_FOCUS_SELECTOR="input, select, textarea, button";static activateTab(e,t){const n=K.getStackForRoot(e,t,!1);if(!n){ss.error("Could not find stack for config",t);return}const s=K.getContentItemInStack(n,t);s&&n.setActiveContentItem(s)}static isActiveTab(e,t){const n=K.getStackForRoot(e,t,!1);if(!n)return ss.error("Could not find stack for config",t),!1;const s=K.getContentItemInStack(n,t);return n.getActiveContentItem()===s}static addStack(e,t=!0){const n=t?"column":"row";if(Zh(e)){(e.contentItems==null||e.contentItems.length===0)&&e.addChild({type:n});const o=e.contentItems[0];if(!(t?o.isColumn:o.isRow)){e.removeChild(o,!0),e.addChild({type:n});const a=document.activeElement;e.contentItems[0].addChild(o),a&&a.focus!=null&&a.focus()}return this.addStack(e.contentItems[0],t)}if(e.contentItems.length<2)return e.addChild({type:"stack"}),e.contentItems[e.contentItems.length-1];let s=e.contentItems[e.contentItems.length-1];return(t?s.isRow:s.isColumn)||(e.addChild({type:t?"row":"column"}),e.removeChild(s,!0),e.contentItems[e.contentItems.length-1].addChild(s),s=e.contentItems[e.contentItems.length-1]),this.addStack(s,!t)}static getStackForConfig(e,t={},n=!1){if(n&&lo(e)&&e.contentItems.length===0)return e;if(e.contentItems==null)return null;for(let s=0;s<e.contentItems.length;s+=1){const i=e.contentItems[s];if(i.isComponent&&i.config!=null&&rd(i.config,t))return e;const o=this.getStackForConfig(i,t,n);if(o)return o}return null}static getStackForRoot(e,t,n=!0,s=!0,i=!0){let o=this.getStackForConfig(e,t);return!o&&s&&(o=this.getStackForConfig(e,{component:t.component},i)),!o&&n&&(o=this.addStack(e)),o}static getStackForComponentTypes(e,t,n=!0,s=!0,i=!0){for(let o=0;o<t.length;o+=1){const l=t[o],a=o===t.length-1,d=K.getStackForRoot(e,{component:l},n&&a,s,i);if(d)return d}return null}static getContentItemInStack(e,t){if(!e)return null;for(let n=0;n<e.contentItems.length;n+=1){const s=e.contentItems[n];if(s.isComponent&&s.config!=null&&rd(s.config,t))return s}return null}static dehydrateLayoutConfig(e,t){if(e==null||!e.length)return[];const n=[];for(let s=0;s<e.length;s+=1){const i=e[s],{component:o,content:l}=i;if(o){const a=t(o,i);a!=null?n.push(a):ss.debug2(`dehydrateLayoutConfig: skipping unmapped component "${o}"`)}else if(l){const a={...i,content:K.dehydrateLayoutConfig(l,t)};n.push(a)}else n.push(i)}return n}static getTabPoint(e){const{tab:t}=e;if(t==null)throw new Error(`Cannot get tab for panel container ${e}`);const n=t.element[0].getBoundingClientRect();return[n.left+n.width*.5,n.bottom-8]}static dropLayoutMinorChange(e){for(let t=0;t<e.length;t+=1){const n=e[t],{content:s}=n;s!==void 0?($d(n)&&delete n.activeItemIndex,K.dropLayoutMinorChange(s)):pi(n)&&n.component==="IrisGridPanel"&&n.props.panelState!=null&&(delete n.id,n.props.panelState.irisGridState.sorts=[],n.props.panelState.irisGridState.quickFilters=[])}}static isEqual(e,t,n=!1){if(n){const s=K.cloneLayout(e),i=K.cloneLayout(t);return K.dropLayoutMinorChange(s),K.dropLayoutMinorChange(i),st(s,i)}return st(e,t)}static cloneLayout(e){return JSON.parse(JSON.stringify(e))}static hydrateLayoutConfig(e,t){if(e==null||!e.length)return[];const n=[];for(let s=0;s<e.length;s+=1){const i=e[s];if(pi(i)){const{component:o,props:l={}}=i;n.push({...i,id:i?.id??qe(),props:t(o,l)})}else if(i.content!==void 0){const o=K.hydrateLayoutConfig(i.content,t);$d(i)&&i.activeItemIndex!=null&&i.activeItemIndex>=o.length&&(ss.warn("Fixing bad activeItemIndex!",i.activeItemIndex,i),i.activeItemIndex=0),n.push({...i,content:o})}else n.push(i)}return n}static openComponent({root:e,config:t,replaceExisting:n=!0,replaceConfig:s=void 0,createNewStack:i=!1,focusElement:o=void 0,dragEvent:l=void 0}={}){const a=document.activeElement,d={...t};if(d.id==null&&(d.id=qe.generate()),l){e?.layoutManager.createDragSourceFromEvent(d,l);return}const h=s||{id:d.id,component:d.component};N(e);const u=i?K.addStack(e):K.getStackForRoot(e,h);N(u);const m=K.getContentItemInStack(u,h);if(o!=null){const g=p=>{ss.debug("Component created, focusing element",o),u.off("componentCreated",g);const{element:C}=p.origin;requestAnimationFrame(()=>{K.focusElement(C[0],o)})};u.on("componentCreated",g)}if(n&&m){const g=u.contentItems.indexOf(m);u.addChild(d,g+1),u.removeChild(m),u.setActiveContentItem(u.contentItems[g])}else u.addChild(d);o==null&&a&&jo(a)&&a.focus()}static openComponentInStack(e,t,n=!0){const s=document.activeElement,i={id:t.id},o=K.getContentItemInStack(e,i);if(n&&o&&e){const l=e?.contentItems.indexOf(o);e.addChild(t,l+1),e.removeChild(o),e.setActiveContentItem(e.contentItems[l])}else e?.addChild(t);s&&jo(s)&&s.focus()}static closeComponent(e,t,n){const s=K.getStackForRoot(e,t,!1,!1,!1);if(!s){ss.warn("Cannot find stack for component, ignoring close",t);return}const i=K.getContentItemInStack(s,t),o=document.activeElement;i&&(Bt(i)?i.container.close(n):s.removeChild(i)),o&&document.contains(o)&&jo(o)&&o.focus()}static renameComponent(e,t,n){const s=K.getStackForRoot(e,t,!1);if(!s){ss.error("Could not find stack for config",t);return}const i=K.getContentItemInStack(s,t);i&&i.setTitle(n)}static cloneComponent(e,t){const n=K.getStackForRoot(e,t,!1);if(!n)return ss.error("Could not find stack for config",t),null;const{props:s={}}=t,i=K.getPanelComponentState(t),o={type:"react-component",component:t.component,props:{...s,panelState:i},title:`${t.title} Copy`,id:qe.generate()};return K.openComponentInStack(n,o),o}static getPanelComponentState(e){return nu(e)?e.componentState?.panelState:pi(e)?e.props?.panelState:null}static makeDefaultLayout(){return{dimensions:{headerHeight:Vd.tabHeight,borderWidth:Vd.dragBorderWidth,borderGrabWidth:10},settings:{showPopoutIcon:!1,showCloseIcon:!1,constrainDragToContainer:!1}}}static getRootFromContainer(e){return e.layoutManager.root}static getComponentConfigFromContainer(e){return e?e.tab!=null&&e.tab.contentItem!=null?e.tab.contentItem.config:e._config:null}static getTitleFromContainer(e){return e!=null&&e.tab!=null&&e.tab.contentItem!=null?e.tab.contentItem.config.title:null}static getTitleFromTab(e){return e!=null&&e.contentItem!=null?e.contentItem.config.title:null}static getIdFromContainer(e){const t=K.getComponentConfigFromContainer(e);return t?t.id:null}static getIdFromPanel(e){const{glContainer:t}=e.props;return K.getIdFromContainer(t)}static getComponentNameFromPanel(e){const{glContainer:t}=e.props,n=K.getComponentConfigFromContainer(t);return n&&pi(n)?n.component??null:null}static getComponentName(e){const t=e.WrappedComponent?.displayName??e.displayName;if(t==null)throw new Error(`Component displayName not defined ${e}`);return t}static focusElement(e,t=K.DEFAULT_FOCUS_SELECTOR){if(e==null)return null;const n=e.querySelector(t);return n==null?null:(jo(n)&&n.focus(),n)}static onInitialized(e){return new Promise(t=>{if(e.isInitialised){t();return}const n=()=>{e.off("initialised",n),t()};e.on("initialised",n)})}}const su=de.forwardRef((c,e)=>{const t=K.getComponentNameFromPanel({props:c});return r.jsxs("div",{ref:e,className:"panel-placeholder",children:['Component "',t,'" is not registered.']})});su.displayName="PanelPlaceholder";const Ee=Object.freeze({FOCUS:"PanelEvent.FOCUS",MOUNT:"PanelEvent.MOUNT",UNMOUNT:"PanelEvent.UNMOUNT",TITLE_CHANGED:"PanelEvent.TITLE_CHANGED",REOPEN:"PanelEvent.REOPEN",DELETE:"PanelEvent.DELETE",CLONED:"PanelEvent.CLONED",CLOSED:"PanelEvent.CLOSED",OPEN:"PanelEvent.OPEN",CLOSE:"PanelEvent.CLOSE",DRAGGING:"PanelEvent.DRAGGING",DROPPED:"PanelEvent.DROPPED"});function Wd(c){return c?.WrappedComponent!==void 0}function lS(c){return typeof c.id=="string"&&c.layout instanceof tu&&c.panelManager instanceof iu&&typeof c.registerComponent=="function"}function ys(c){if(!lS(c))throw new Error(`Expected dashboard plugin props, but instead received ${c}`)}const Xt=ne.module("PanelManager");class iu{static MAX_CLOSED_PANEL_COUNT=100;layout;hydrateComponent;dehydrateComponent;onPanelsUpdated;closed;openedMap;constructor(e,t=(l,a)=>a,n=(l,a)=>a,s=new Map,i=[],o=()=>{}){this.handleFocus=this.handleFocus.bind(this),this.handleMount=this.handleMount.bind(this),this.handleUnmount=this.handleUnmount.bind(this),this.handleReopen=this.handleReopen.bind(this),this.handleDeleted=this.handleDeleted.bind(this),this.handleClosed=this.handleClosed.bind(this),this.handleControlClose=this.handleControlClose.bind(this),this.layout=e,this.hydrateComponent=t,this.dehydrateComponent=n,this.onPanelsUpdated=o,this.openedMap=new Map(s),this.closed=[...i],this.startListening()}startListening(){const{eventHub:e}=this.layout;e.on(Ee.FOCUS,this.handleFocus),e.on(Ee.MOUNT,this.handleMount),e.on(Ee.UNMOUNT,this.handleUnmount),e.on(Ee.REOPEN,this.handleReopen),e.on(Ee.DELETE,this.handleDeleted),e.on(Ee.CLOSED,this.handleClosed),e.on(Ee.CLOSE,this.handleControlClose)}stopListening(){const{eventHub:e}=this.layout;e.off(Ee.FOCUS,this.handleFocus),e.off(Ee.MOUNT,this.handleMount),e.off(Ee.UNMOUNT,this.handleUnmount),e.off(Ee.REOPEN,this.handleReopen),e.off(Ee.DELETE,this.handleDeleted),e.off(Ee.CLOSED,this.handleClosed),e.off(Ee.CLOSE,this.handleControlClose)}getClosedPanelConfigsOfType(e){return this.closed.filter(t=>t.component===e)}getOpenedPanels(){return Array.from(this.openedMap.values())}getOpenedPanelConfigs(){return this.getOpenedPanels().map(e=>{const{glContainer:t}=e.props;return K.getComponentConfigFromContainer(t)})}getOpenedPanelConfigsOfType(e){return this.getOpenedPanelConfigs().filter(t=>t!=null&&pi(t)&&t.component===e)}getOpenedPanelById(e){return this.openedMap.get(e)}getContainerByPanelId(e){const t=K.getStackForConfig(this.layout.root,{id:e});return(t&&K.getContentItemInStack(t,{id:e}))??null}getLastUsedPanel(e){const t=this.getOpenedPanels();for(let n=t.length-1;n>=0;n-=1){const s=t[n];if(e==null||e(s))return s}}getLastUsedPanelOfType(e){return this.getLastUsedPanelOfTypes([e])}getLastUsedPanelOfTypes(e){return this.getLastUsedPanel(t=>e.some(n=>Wd(n)&&t instanceof n.WrappedComponent||!Wd(n)&&t instanceof n))}updatePanel(e){const t=K.getIdFromPanel(e);if(t==null){Xt.error("updatePanel Panel did not have an ID",e);return}Xt.debug2(`Updating panel ID ${t} in open panels map`),this.openedMap.delete(t),this.openedMap.set(t,e)}removePanel(e){const t=K.getIdFromPanel(e);if(t==null){Xt.error("removePanel Panel did not have an ID",e);return}if(!this.openedMap.has(t)){Xt.error(`Missing panel ID ${t} in open panels map`);return}if(this.openedMap.get(t)!==e){Xt.debug(`Panel argument doesn't match the open panels map entry for ${t}, removePanel ignored`);return}Xt.debug2(`Removing panel ID ${t} from open panels map`),this.openedMap.delete(t)}removeClosedPanelConfig(e){const t=this.closed.findIndex(n=>n===e||n.id!=null&&e.id!=null&&n.id===e.id);t>=0&&this.closed.splice(t,1)}handleFocus(e){Xt.debug2("Focus: ",e),this.updatePanel(e)}handleMount(e){Xt.debug2("Mount: ",e),this.updatePanel(e),this.sendUpdate()}handleUnmount(e){Xt.debug2("Unmount: ",e),this.removePanel(e),this.sendUpdate()}handleReopen(e,t){Xt.debug2("Reopen:",e,t),this.removeClosedPanelConfig(e);const{component:n}=e;let{props:s}=e;s=this.hydrateComponent(n,s);const i={...e,props:s},{root:o}=this.layout;K.openComponent({root:o,config:i,replaceConfig:t})}handleDeleted(e){Xt.debug2("Deleted:",e),this.removeClosedPanelConfig(e),this.sendUpdate()}handleClosed(e,t){Xt.debug2("Closed: ",e),this.addClosedPanel(t),this.sendUpdate()}handleControlClose(e){const t={id:e},{root:n}=this.layout;K.closeComponent(n,t)}addClosedPanel(e){const t=K.getComponentConfigFromContainer(e);if(t&&pi(t)){const n=this.dehydrateComponent(t.component,t);n!=null&&this.closed.push(n)}}sendUpdate(){const{closed:e,openedMap:t}=this;this.onPanelsUpdated({closed:[...e],openedMap:new Map(t)})}}const aS=ne.module("PanelErrorBoundary");class rS extends v.Component{constructor(e){super(e),this.state={error:null}}componentDidCatch(e){this.setState({error:e})}componentWillUnmount(){const{glContainer:e,glEventHub:t}=this.props,n=K.getIdFromContainer(e);aS.debug("componentWillUnmount",n),t.emit(Ee.CLOSED,n,e)}render(){const{children:e}=this.props,{error:t}=this.state;return t!=null?r.jsx("div",{className:"panel-error-boundary",children:r.jsx($l,{errorMessage:`${t}`,isLoading:!1,isLoaded:!1})}):e}}function Fr(c){const{props:e,componentState:t}=c,{metadata:n}=e;let{panelState:s=null}=e;t&&({panelState:s}=t);const i={};return n!=null&&(i.metadata=n),s!=null&&(i.panelState=s),{...c,componentState:null,props:i,type:"react-component"}}function Nr(c,e=""){return{metadata:{},...c,localDashboardId:e}}const qa={dehydrate:Fr,hydrate:Nr},dS=z.shape({on:z.func,off:z.func,isHidden:z.bool,tab:z.shape({header:z.shape({tabs:z.arrayOf(z.shape({contentItem:z.shape({})}))})}),title:z.string,setTitle:z.func,close:z.func}),ou=z.shape({on:z.func,off:z.func,emit:z.func}),cS=z.shape({registerComponent:z.func,root:z.shape({addChild:z.func}),on:z.func,off:z.func,eventHub:ou}),kr=Object.freeze({Container:dS,EventHub:ou,Layout:cS}),Ve=(c,e,t)=>v.useEffect(function(){return c.on(e,t),()=>{c.off(e,t)}},[c,e,t]),lu="SET_DASHBOARD_DATA",hS=xC(lu,{},!1),uS={dashboardData:hS},mS=new Map,gS=Object.freeze({}),pS=Object.freeze([]),fS=c=>c.dashboardData,Pt=(c,e)=>fS(c)[e]??gS,CS=(c,e)=>Pt(c,e).closed??pS,au=(c,e)=>Pt(c,e).openedMap??mS,ru=(c,e)=>({type:lu,id:c,payload:e}),Fn=(c,e)=>(t,n)=>t(ru(c,{...Pt(n(),c),...e}));Object.entries(uS).map(([c,e])=>fo.register(c,e));const Ho=ne.module("DashboardLayout"),bS=Object.freeze({}),SS=[],Gd=()=>{},zd=c=>c;function du({id:c,children:e,emptyDashboard:t=r.jsx("div",{children:"Dashboard is empty."}),layout:n,layoutConfig:s=SS,onLayoutChange:i=Gd,onLayoutInitialized:o=Gd,hydrate:l=Nr,dehydrate:a=Fr}){const d=ir(),h=rm(j=>Pt(j,c))??bS,[u,m]=v.useState(!1),[g,p]=v.useState(!1),[C,f]=v.useState(),[b]=v.useState(h?.closed??[]),[w,S]=v.useState(!1),T=v.useMemo(()=>new Map,[]),y=v.useMemo(()=>new Map,[]),E=dm(),R=v.useCallback((j,P,Q=l,$=a)=>{Ho.debug2("registerComponent",j,P,Q,$);function J(q,Z){const le=P,{glContainer:G,glEventHub:oe}=q;return r.jsx(Bc,{store:E,children:r.jsx(rS,{glContainer:G,glEventHub:oe,children:r.jsx(le,{...q,ref:Z})})})}const A=de.forwardRef(J),W=n.registerComponent(j,A);return T.set(j,Q),y.set(j,$),W},[l,a,T,y,n,E]),x=v.useCallback((j,P)=>(T.get(j)??zd)(P,c),[T,c]),D=v.useCallback((j,P)=>(y.get(j)??zd)(P,c),[y,c]),M=v.useMemo(()=>new iu(n,x,D,new Map,b,({closed:j,openedMap:P})=>{d(Fn(c,{closed:j,openedMap:P}))}),[D,d,x,c,b,n]),O=v.useCallback(()=>{if(g)return;w||(o(),S(!0));const P=n.toConfig().content,Q=K.dehydrateLayoutConfig(P,D),$=C==null||!K.isEqual(C,Q);Ho.debug("handleLayoutStateChanged",$,P,Q),$&&(m(n.root.contentItems.length===0),f(Q),i(Q))},[D,w,g,C,n,i,o]),H=v.useCallback(j=>{const P=K.getIdFromContainer(j);n.eventHub.emit(Ee.DRAGGING,P),p(!0)},[n.eventHub]),L=v.useCallback(j=>{const P=K.getIdFromContainer(j);n.eventHub.emit(Ee.DROPPED,P),p(!1)},[n.eventHub]),V=v.useCallback(j=>{if(Ho.debug2("handleComponentCreated",j),j==null||j.config==null||j.config.component==null||j.element==null)return;const Q=`${j.config.component.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}-component`;j.element.addClass(Q)},[]);Ve(n,"stateChanged",O),Ve(n,"itemPickedUp",H),Ve(n,"itemDropped",L),Ve(n,"componentCreated",V),Ve(n.eventHub,Ee.TITLE_CHANGED,O);const U=lr(s);return v.useEffect(function(){if(U!==s&&s!==C){Ho.debug("Setting new layout content...");const P=K.hydrateLayoutConfig(s,x);for(;n.root.contentItems.length>0;)n.root.contentItems[0].remove();for(let Q=0;Q<P.length;Q+=1)n.root.addChild(P[Q]);m(n.root.contentItems.length===0)}},[x,n,s,C,M,U]),r.jsxs(r.Fragment,{children:[u&&t,de.Children.map(e,j=>j!=null?de.cloneElement(j,{id:c,layout:n,panelManager:M,registerComponent:R}):null)]})}du.propTypes={id:z.string.isRequired,children:z.node,data:z.shape({}),emptyDashboard:z.node,layout:kr.Layout.isRequired,layoutConfig:z.arrayOf(z.shape({})),onLayoutChange:z.func,onLayoutInitialized:z.func};const wS=100,wa=()=>{},vS=Object.freeze({});function TS({id:c="default",children:e,emptyDashboard:t,layoutConfig:n,layoutSettings:s=vS,onLayoutConfigChange:i=wa,onGoldenLayoutChange:o=wa,onLayoutInitialized:l=wa,fallbackComponent:a=su,hydrate:d,dehydrate:h}){const u=v.useRef(null),[m,g]=v.useState(!1),[p,C]=v.useState();v.useEffect(function(){if(!u.current){C(void 0);return}const w={...K.makeDefaultLayout()};w.settings===void 0&&(w.settings={}),Object.assign(w.settings,s),w.content=[];const S=new tu(w,u.current),T=()=>{S.off("initialised",T),g(!0)};return S.on("initialised",T),a!=null&&S.setFallbackComponent(a),S.init(),C(S),o(S),()=>{S.destroy()}},[s,a,o,g,C]);const f=v.useMemo(()=>vs(()=>{p!=null&&p.isInitialised&&p?.updateSize()},wS),[p]);return v.useEffect(function(){return window.addEventListener("resize",f),()=>{window.removeEventListener("resize",f)}},[f]),r.jsxs("div",{className:"dashboard-container w-100 h-100",children:[r.jsx("div",{className:"w-100 h-100",ref:u}),m&&p&&r.jsx(du,{emptyDashboard:t,id:c,layout:p,layoutConfig:n,onLayoutChange:i,onLayoutInitialized:l,hydrate:d,dehydrate:h,children:e})]})}const un="default";class ES extends Error{isAssertionFailed=!0}const cu=ES;function Kd(c){if(c==null)throw new cu(`Expected 'val' to be defined, but received ${c}`)}class yS extends Error{isPasteError=!0}const va=yS;function Xe(c){return c?.isEditable!==void 0}function Yd(c){if(!Xe(c))throw new cu(`Expected 'model' to be editable, but received ${c}`)}function je(c){return c?.hasExpandableRows!==void 0}var mn=(c=>(c.DOWN="DOWN",c.UP="UP",c.LEFT="LEFT",c.RIGHT="RIGHT",c))(mn||{});class te{startColumn;startRow;endColumn;endRow;static SELECTION_DIRECTION=mn;static normalize(e,t,n,s){let i=e,o=t,l=n,a=s;return i!=null&&l!=null&&l<i&&(i=l,l=e),o!=null&&a!=null&&a<o&&(o=a,a=t),[i,o,l,a]}static makeNormalized(e,t,n,s){return new te(...te.normalize(e,t,n,s))}static makeCell(e,t){return new te(e,t,e,t)}static makeColumn(e){return new te(e,null,e,null)}static makeRow(e){return new te(null,e,null,e)}static minOrNull(e,t){return e==null||t==null?null:Math.min(e,t)}static maxOrNull(e,t){return e==null||t==null?null:Math.max(e,t)}static consolidate(e){const t=e.slice();let n=!0;for(;n;){n=!1;for(let s=0;s<t.length&&!n;s+=1){const i=t[s];for(let o=t.length-1;o>s;o-=1){const l=t[o];if(i.contains(l))t.splice(o,1);else if(l.contains(i)){n=!0,t[s]=l,t.splice(o,1);break}else if(i.startRow===l.startRow&&i.endRow===l.endRow){if(i.touches(l)){const{startRow:a,endRow:d}=i,h=te.minOrNull(i.startColumn,l.startColumn),u=te.maxOrNull(i.endColumn,l.endColumn);n=!0,t[s]=new te(h,a,u,d),t.splice(o,1);break}}else if(i.startColumn===l.startColumn&&i.endColumn===l.endColumn&&i.touches(l)){const{startColumn:a,endColumn:d}=i,h=te.minOrNull(i.startRow,l.startRow),u=te.maxOrNull(i.endRow,l.endRow);n=!0,t[s]=new te(a,h,d,u),t.splice(o,1);break}}}}return t}static isAxisRangeTouching(e,t,n,s){return e==null?t==null||n==null?!0:n<=t+1:t==null?s==null?!0:s>=e-1:n==null?s==null?!0:e<=s+1:s==null?t>=n-1:n>=e-1?n<=t+1:s>=e-1}static rangeArraysEqual(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!e[n].equals(t[n]))return!1;return!0}static intersection(e,t){if(e.equals(t))return e;let{startColumn:n,startRow:s,endColumn:i,endRow:o}=e;return n=n!=null&&t.startColumn!=null?Math.max(n,t.startColumn):n??t.startColumn,i=i!=null&&t.endColumn!=null?Math.min(i,t.endColumn):i??t.endColumn,s=s!=null&&t.startRow!=null?Math.max(s,t.startRow):s??t.startRow,o=o!=null&&t.endRow!=null?Math.min(o,t.endRow):o??t.endRow,n!=null&&n>(i??-1)||s!=null&&s>(o??-1)?null:new te(n,s,i,o)}static subtractFromRange(e,t){const n=[],s=te.intersection(e,t);return s==null?[e]:(s.startRow!=null&&(e.startRow==null||e.startRow<s.startRow)&&n.push(new te(e.startColumn,e.startRow,e.endColumn,s.startRow-1)),s.startColumn!=null&&(e.startColumn==null||e.startColumn<s.startColumn)&&n.push(new te(e.startColumn,s.startRow,s.startColumn-1,s.endRow)),s.endColumn!=null&&(e.endColumn==null||e.endColumn>s.endColumn)&&n.push(new te(s.endColumn+1,s.startRow,e.endColumn,s.endRow)),s.endRow!=null&&(e.endRow==null||e.endRow>s.endRow)&&n.push(new te(e.startColumn,s.endRow+1,e.endColumn,e.endRow)),n)}static subtractFromRanges(e,t){const n=[];for(let s=0;s<e.length;s+=1)n.push(...te.subtractFromRange(e[s],t));return n}static subtractRangesFromRanges(e,t){let n=[...e];for(let s=0;s<t.length;s+=1)n=te.subtractFromRanges(n,t[s]);return n}static isBounded(e){return e.startRow!=null&&e.startColumn!=null&&e.endRow!=null&&e.endColumn!=null}static boundedRange(e,t,n){return te.isBounded(e)?e:new te(e.startColumn??0,e.startRow??0,e.endColumn??t-1,e.endRow??n-1)}static boundedRanges(e,t,n){return e.map(s=>te.boundedRange(s,t,n))}static offset(e,t,n){return new te(e.startColumn!=null?e.startColumn+t:null,e.startRow!=null?e.startRow+n:null,e.endColumn!=null?e.endColumn+t:null,e.endRow!=null?e.endRow+n:null)}static nextCell(e,t=null,n=null,s=te.SELECTION_DIRECTION.DOWN){if(e.length===0)return null;let i=-1;if(t!=null&&n!=null&&(i=e.findIndex(o=>o.containsCell(t,n)),i>=0)){const l=e[i].nextCell(t,n,s);if(l!=null)return l}switch(s){case te.SELECTION_DIRECTION.DOWN:case te.SELECTION_DIRECTION.RIGHT:{const o=i<e.length-1?i+1:0;return e[o].startCell(s)}case te.SELECTION_DIRECTION.LEFT:case te.SELECTION_DIRECTION.UP:{const o=i>0?i-1:e.length-1;return e[o].startCell(s)}default:throw new Error(`Invalid direction: ${s}`)}}static cellCount(e){return e.reduce((t,n)=>t+((n.endRow??NaN)-(n.startRow??NaN)+1)*((n.endColumn??NaN)-(n.startColumn??NaN)+1),0)}static rowCount(e){return e.reduce((t,n)=>t+(n.endRow??NaN)-(n.startRow??NaN)+1,0)}static columnCount(e){return e.reduce((t,n)=>t+(n.endColumn??NaN)-(n.startColumn??NaN)+1,0)}static containsCell(e,t,n){for(let s=0;s<e.length;s+=1)if(e[s].containsCell(t,n))return!0;return!1}static forEachCell(e,t,n=te.SELECTION_DIRECTION.RIGHT){for(let s=0;s<e.length;s+=1)e[s].forEach(t,n)}constructor(e,t,n,s){this.startColumn=e,this.startRow=t,this.endColumn=n,this.endRow=s}equals(e){return this.startColumn===e.startColumn&&this.startRow===e.startRow&&this.endColumn===e.endColumn&&this.endRow===e.endRow}contains(e){return(this.startColumn==null||e.startColumn!=null&&this.startColumn<=e.startColumn)&&(this.startRow==null||e.startRow!=null&&this.startRow<=e.startRow)&&(this.endColumn==null||e.endColumn!=null&&this.endColumn>=e.endColumn)&&(this.endRow==null||e.endRow!=null&&this.endRow>=e.endRow)}containsCell(e,t){return e==null||t==null?!1:(this.startColumn==null||this.startColumn<=e)&&(this.endColumn==null||this.endColumn>=e)&&(this.startRow==null||this.startRow<=t)&&(this.endRow==null||this.endRow>=t)}touches(e){return te.isAxisRangeTouching(this.startRow,this.endRow,e.startRow,e.endRow)&&te.isAxisRangeTouching(this.startColumn,this.endColumn,e.startColumn,e.endColumn)}subtract(e){return te.subtractFromRange(this,e)}startCell(e=te.SELECTION_DIRECTION.DOWN){if(!te.isBounded(this))throw new Error("Cannot get the startCell of an unbounded range");switch(e){case te.SELECTION_DIRECTION.DOWN:case te.SELECTION_DIRECTION.RIGHT:return{column:this.startColumn,row:this.startRow};case te.SELECTION_DIRECTION.LEFT:case te.SELECTION_DIRECTION.UP:return{column:this.endColumn,row:this.endRow};default:throw new Error(`Invalid direction: ${e}`)}}nextCell(e,t,n){if(!te.isBounded(this))throw new Error("Bounded range required");if(e==null||t==null)throw new Error("Require a non-null cursor");const{startColumn:s,endColumn:i,startRow:o,endRow:l}=this;switch(n){case te.SELECTION_DIRECTION.DOWN:if(t<l)return{column:e,row:Math.max(t+1,o)};if(e<i)return{column:Math.max(e+1,s),row:o};break;case te.SELECTION_DIRECTION.UP:if(t>o)return{column:e,row:Math.min(t-1,l)};if(e>s)return{column:Math.min(e-1,i),row:l};break;case te.SELECTION_DIRECTION.RIGHT:if(e<i)return{column:Math.max(e+1,s),row:t};if(t<l)return{column:s,row:Math.max(t+1,o)};break;case te.SELECTION_DIRECTION.LEFT:if(e>s)return{column:Math.min(e-1,i),row:t};if(t>o)return{column:i,row:Math.min(t-1,l)};break;default:throw new Error(`Invalid direction: ${n}`)}return null}forEach(e,t=te.SELECTION_DIRECTION.RIGHT){let n=0,{column:s,row:i}=this.startCell(t);for(;s!=null&&i!=null;)e(s,i,n),n+=1,{column:s,row:i}=this.nextCell(s,i,t)??{}}}const Ie=te;function RS(c){return Array.isArray(c)&&c.length===2&&(c[0]===null||typeof c[0]=="number")&&(c[1]===null||typeof c[1]=="number")}function Bo(c){return RS(c)&&c[0]!=null&&c[1]!=null}function wl(c){return c?.href!==void 0}class _{static PIXELS_PER_LINE=100/3;static getGridPointFromXY(e,t,n){const s=_.getColumnAtX(e,n),i=_.getRowAtY(t,n),o=_.getColumnHeaderDepthAtY(t,n);return{x:e,y:t,row:i,column:s,columnHeaderDepth:o}}static getCellInfoFromXY(e,t,n){const{row:s,column:i}=_.getGridPointFromXY(e,t,n),{allColumnWidths:o,allRowHeights:l,allColumnXs:a,allRowYs:d,modelColumns:h,modelRows:u}=n,m=s!==null?u.get(s):null,g=i!==null?h.get(i):null,p=i!==null?a.get(i):null,C=s!==null?d.get(s):null,f=i!==null?o.get(i):null,b=s!==null?l.get(s):null;return{row:s,column:i,modelRow:m??null,modelColumn:g??null,left:p??null,top:C??null,columnWidth:f??null,rowHeight:b??null}}static getColumnHeaderDepthAtY(e,t){const n=_.getRowAtY(e,t),{columnHeaderHeight:s,columnHeaderMaxDepth:i}=t;if(n===null&&e<=s*i)return Oe(i-Math.ceil(e/s),0,i-1)}static iterateFloatingStart(e,t,n){for(let s=0;s<e&&s<t;s+=1){const i=n(s);if(i!==void 0)return i}}static iterateFloatingEnd(e,t,n){for(let s=0;s<e&&t-(e-s)>=0;s+=1){const i=n(t-(e-s));if(i!==void 0)return i}}static iterateFloating(e,t,n,s){const i=_.iterateFloatingStart(e,n,s);return i!==void 0?i:_.iterateFloatingEnd(t,n,s)}static iterateAllItems(e,t,n,s,i,o){const l=Math.max(e,n),a=Math.min(t,i-s-1);let d=_.iterateFloating(n,s,i,o);if(d!==void 0)return d;for(let h=l;h<=a;h+=1)if(d=o(h),d!==void 0)return d}static isInItem(e,t,n,s){const i=t.get(e)??0,o=n.get(e)??0;return i<=s&&s<=i+o}static getItemAtOffset(e,t,n,s,i,o,l,a=!1){const d=a?void 0:_.iterateFloating(n,s,t,h=>{if(_.isInItem(h,o,l,e))return h});if(!a&&d!==void 0)return d;for(let h=0;h<i.length;h+=1){const u=i[h];if(_.isInItem(u,o,l,e))return u}return null}static getColumnAtX(e,t,n=!1){const{columnCount:s,floatingLeftColumnCount:i,floatingRightColumnCount:o,visibleColumns:l,allColumnXs:a,allColumnWidths:d,gridX:h}=t;return e<h?null:this.getItemAtOffset(e-h,s,i,o,l,a,d,n)}static getRowAtY(e,t){const{floatingTopRowCount:n,floatingBottomRowCount:s,rowCount:i,visibleRows:o,allRowYs:l,allRowHeights:a,gridY:d}=t;return e<d?null:this.getItemAtOffset(e-d,i,n,s,o,l,a)}static getNextShownItem(e,t,n,s){let i=n.findIndex(o=>o===e)||0;for(i-=1;i!=null&&i>=0;){const o=n[i],l=t.get(o);if(l!=null&&s.get(l)!==0)return o;i-=1}return null}static getNextShownColumn(e,t){const{modelColumns:n,visibleColumns:s,userColumnWidths:i}=t;return _.getNextShownItem(e,n,s,i)}static getNextShownRow(e,t){const{modelRows:n,visibleRows:s,userRowHeights:i}=t;return _.getNextShownItem(e,n,s,i)}static getColumnSeparatorIndex(e,t,n,s){const{rowHeaderWidth:i,columnHeaderHeight:o,floatingColumns:l,floatingLeftWidth:a,visibleColumns:d,allColumnXs:h,allColumnWidths:u,columnHeaderMaxDepth:m}=n,{allowColumnResize:g,headerSeparatorHandleSize:p}=s;if(m*o<t||!g||p<=0)return null;const C=e-i,f=p*.5;let b=!1;for(let w=l.length-1;w>=0;w-=1){const S=l[w],T=h.get(S)??0,y=u.get(S)??0,E=y===0;if(!b||!E){let R=T+y;E?R+=f:b&&(R-=f);const x=R-f,D=R+f;if(x<=C&&C<=D)return S;b=E}}b=!1;for(let w=d.length-1;w>=0;w-=1){const S=d[w],T=h.get(S)??0,y=u.get(S)??0,E=y===0;if(T<a-y)return null;if(!b||!E){let R=T+y;E?R+=f:b&&(R-=f);const x=R-f,D=R+f;if(x<=C&&C<=D)return S;b=E}}return null}static isItemHidden(e,t){return t.get(e)===0}static isColumnHidden(e,t){const{allColumnWidths:n}=t;return _.isItemHidden(e,n)}static isFloatingRow(e,t){if(e==null)return!1;const{floatingTopRowCount:n,floatingBottomRowCount:s,rowCount:i}=t;return e<n||e>=i-s}static isFloatingColumn(e,t){if(e==null)return!1;const{floatingLeftColumnCount:n,floatingRightColumnCount:s,columnCount:i}=t;return e<n||e>=i-s}static getHiddenItems(e,t,n){if(!_.isItemHidden(e,t))return[];const s=[e],i=n.findIndex(o=>o===e);for(let o=i-1;o>=0;o-=1){const l=n[o];if(!_.isItemHidden(l,t))break;s.push(l)}return s}static getHiddenColumns(e,t){const{visibleColumns:n,allColumnWidths:s}=t;return _.getHiddenItems(e,s,n)}static getRowSeparatorIndex(e,t,n,s){const{rowHeaderWidth:i,columnHeaderHeight:o,visibleRows:l,allRowYs:a,allRowHeights:d}=n,{allowRowResize:h,headerSeparatorHandleSize:u}=s;if(i<e||!h||u<=0)return null;const m=t-o,g=u*.5;let p=!1;for(let C=l.length-1;C>=0;C-=1){const f=l[C],b=a.get(f)??0,w=d.get(f)??0,S=w===0;if(!p||!S){let T=b+w;S?T+=g:p&&(T-=g);const y=T-g,E=T+g;if(y<=m&&m<=E)return f;p=S}}return null}static isRowHidden(e,t){const{allRowHeights:n}=t;return _.isItemHidden(e,n)}static getHiddenRows(e,t){const{visibleRows:n,allRowHeights:s}=t;return _.getHiddenItems(e,s,n)}static moveItem(e,t,n){if(e===t)return[...n];const s=[...n],i=s[s.length-1];return i!=null&&!Bo(i.from)&&i.to===e?i.from===t?s.pop():s[s.length-1]={...i,to:t}:s.push({from:e,to:t}),s}static moveRange(e,t,n,s=!1){if(e[0]===e[1])return _.moveItem(e[0],t,n);let i=t;if(s&&e[0]<t&&(i-=e[1]-e[0]),e[0]===i)return[...n];const o=[...n],l=o[o.length-1];l!=null&&Bo(l.from)&&l.from[1]-l.from[0]===e[1]-e[0]&&l.to===e[0]?o[o.length-1]={...l,to:i}:o.push({from:e,to:i});const a=o[o.length-1];return Bo(a.from)&&a.from[0]===a.to&&o.pop(),o}static moveItemOrRange(e,t,n,s=!1){return Array.isArray(e)?_.moveRange(e,t,n,s):_.moveItem(e,t,n)}static applyItemMoves(e,t,n,s=!1){let i=[[e,t]];for(let o=s?n.length-1:0;s?o>=0:o<n.length;s?o-=1:o+=1){const{from:l,to:a}=n[o];let d=1,h;Bo(l)?(d=l[1]-l[0]+1,[h]=l):h=l;const u=s?a:h,m=u+d-1,g=s?h:a,p=g-u,C=[];for(let f=0;f<i.length;f+=1){const b=i[f][0]??Number.NEGATIVE_INFINITY,w=i[f][1]??Number.POSITIVE_INFINITY;let S;const T=[[b,u-1],[u,m],[m+1,w]].map(([y,E])=>[Math.max(y,b),Math.min(E,w)]).filter(([y,E])=>y<=E).map(y=>{const[E,R]=y;return u<=E&&m>=R?(S=[E+p,R+p],S):m<E?[E-d,R-d]:y}).map(y=>{const[E,R]=y;return g>E&&g<=R?[[E,g-1],[g+d,R+d]]:y===S?[y]:g<=E?[[E+d,R+d]]:[y]}).flat();C.push(...T)}i=C.map(([f,b])=>[Number.isFinite(f)?f:null,Number.isFinite(b)?b:null])}return i}static translateRange(e,t,n,s){const i=_.applyItemMoves(e.startColumn,e.endColumn,t,s),o=_.applyItemMoves(e.startRow,e.endRow,n,s),l=[];for(let a=0;a<i.length;a+=1){const d=i[a];for(let h=0;h<o.length;h+=1){const u=o[h];l.push(new Ie(d[0],u[0],d[1],u[1]))}}return l}static getModelIndex(e,t){return _.applyItemMoves(e,e,t,!0)[0][0]}static getModelIndexes(e,t){return e.map(n=>_.getModelIndex(n,t))}static getModelRangeIndexes(e,t,n){return _.applyItemMoves(e,t,n,!0)}static getModelRange(e,t=ke,n=ke){return _.translateRange(e,t,n,!0)}static getModelRanges(e,t=ke,n=ke){const s=[];for(let i=0;i<e.length;i+=1)s.push(..._.getModelRange(e[i],t,n));return s}static getVisibleRangeIndexes(e,t,n){return _.applyItemMoves(e,t,n,!1)}static getVisibleRange(e,t=ke,n=ke){return this.translateRange(e,t,n,!1)}static getVisibleRanges(e,t=ke,n=ke){const s=[];for(let i=0;i<e.length;i+=1)s.push(..._.getVisibleRange(e[i],t,n));return s}static getVisibleIndex(e,t){return _.applyItemMoves(e,e,t)[0][0]}static getVisibleIndexes(e,t){return e.map(n=>_.getVisibleIndex(n,t))}static isMacPlatform(){const{platform:e}=window.navigator;return e.startsWith("Mac")}static getModifierKey(){return _.isMacPlatform()?"metaKey":"ctrlKey"}static isModifierKeyDown(e){const t=_.getModifierKey();return e[t]}static checkColumnHidden(e,t){return t.get(e)===0}static checkAllColumnsHidden(e,t){return t.size===0?!1:e.every(n=>t.get(n)===0)}static getScrollDragBounds(e,t,n){const{gridX:s,gridY:i,width:o,height:l,floatingTopRowCount:a,floatingBottomRowCount:d,floatingLeftColumnCount:h,floatingRightColumnCount:u,floatingLeftWidth:m,floatingRightWidth:g,floatingTopHeight:p,floatingBottomHeight:C,columnCount:f,rowCount:b}=e;let w=s,S=i,T=o,y=l;return n!=null&&(n>h&&(w+=m),n<f-u&&(T-=g)),t!=null&&(t>a&&(S+=p),t<b-d&&(y-=C)),{x1:w,y1:S,x2:T,y2:y}}static getScrollDelta(e,t=1024,n=768,s=20,i=20){let{deltaX:o,deltaY:l}=e;return!_.isMacPlatform()&&e.shiftKey&&e.deltaX===0&&e.deltaY!==0&&(o=e.deltaY,l=e.deltaX),e?.deltaMode===WheelEvent.DOM_DELTA_PAGE?(o*=t,l*=n):e?.deltaMode===WheelEvent.DOM_DELTA_LINE&&(_.isMacPlatform()?(o=Math.round(o*s),l=Math.round(l*i)):(o=Math.round(o*this.PIXELS_PER_LINE),l=Math.round(l*this.PIXELS_PER_LINE))),{deltaX:o,deltaY:l}}static compareRanges(e,t){return e[0]==null||e[1]==null||t[0]==null||t[1]==null?0:e[0]!==t[0]?e[0]-t[0]:e[1]-t[1]}static mergeSortedRanges(e){const t=[];for(let n=0;n<e.length;n+=1){const s=e[n],i=s[0],o=s[1];n===0?t.push([i,o]):i-1<=t[t.length-1][1]?t[t.length-1][1]=Math.max(t[t.length-1][1],o):t.push([i,o])}return t}static translateTokenBox(e,t){const{x1:n,y1:s,x2:i,y2:o}=e,{gridX:l,gridY:a,width:d,height:h,verticalBarWidth:u,horizontalBarHeight:m}=t,g=Oe(l+n,l,d-u),p=Oe(l+i,l,d-u),C=Oe(a+s,a,h-m),f=Oe(a+o,a,h-m);return{x1:g,y1:C,x2:p,y2:f,token:e.token}}static getTextRenderMetrics(e,t,n){const{metrics:s,model:i,theme:o}=e,{firstColumn:l,allColumnXs:a,allColumnWidths:d,allRowYs:h,allRowHeights:u,modelRows:m,modelColumns:g}=s,{cellHorizontalPadding:p,treeDepthIndent:C,treeHorizontalPadding:f}=o,b=k(m,n),w=k(g,t),S=i.textAlignForCell(w,b),T=k(a,t),y=k(h,n),E=k(d,t),R=k(u,n),x=t===l;let D=0;je(i)&&i.hasExpandableRows&&x&&(D=C*(i.depthForRow(n)+1)+f);const M=E-D;let O=T+p;const H=y+R*.5;return S==="right"?O=T+M-p:S==="center"&&(O=T+M*.5),O+=D,{width:M-p*2,x:O,y:H}}static findTokensWithProtocolInText(e){return jc(e).filter(n=>n.type==="url"?/^https?:\/\//.test(n.value):!0)}}function Uo(c,e=bo.CACHE_SIZE,t=Math.floor(e/2)){if(c.size>e){const n=c.keys();for(;c.size>t;)c.delete(n.next().value)}}function qd(c,e,t,n,s){const i=new Map;let o=0;for(let l=0;l<c&&l<t;l+=1)i.set(l,o),o+=k(s,l);o=n;for(let l=0;l<e&&t-l-1>=0;l+=1)o-=k(s,t-l-1),i.set(t-l-1,o);return i}class bo{static CACHE_SIZE=1e4;static MAX_COLUMN_WIDTH=.8;initialRowHeights;initialColumnWidths;userColumnWidths;userRowHeights;calculatedColumnWidths;calculatedRowHeights;fontWidths;modelRows;modelColumns;movedRows;movedColumns;constructor({userColumnWidths:e=new Map,userRowHeights:t=new Map,calculatedColumnWidths:n=new Map,calculatedRowHeights:s=new Map,fontWidths:i=new Map,modelRows:o=new Map,modelColumns:l=new Map,movedRows:a=[],movedColumns:d=[],initialRowHeights:h=new Map,initialColumnWidths:u=new Map}={}){this.userColumnWidths=e,this.userRowHeights=t,this.calculatedRowHeights=s,this.calculatedColumnWidths=n,this.fontWidths=i,this.modelRows=o,this.modelColumns=l,this.movedRows=a,this.movedColumns=d,this.initialRowHeights=h,this.initialColumnWidths=u}getMetrics(e){const{left:t,top:n,leftOffset:s,topOffset:i,width:o,height:l,theme:a,model:d,movedRows:h,movedColumns:u,draggingColumn:m}=e,{rowHeight:g,rowHeaderWidth:p,rowFooterWidth:C,columnWidth:f,columnHeaderHeight:b,minScrollHandleSize:w,scrollBarSize:S}=a;h!==this.movedRows&&(this.movedRows=h,this.modelRows.clear()),u!==this.movedColumns&&(this.movedColumns=u,this.modelColumns.clear());const{columnCount:T,rowCount:y,floatingTopRowCount:E,floatingBottomRowCount:R,floatingLeftColumnCount:x,floatingRightColumnCount:D,columnHeaderMaxDepth:M}=d,O=this.getFirstRow(e),H=this.getFirstColumn(e),L=this.getGridX(e),V=this.getGridY(e),U=je(d)&&d.hasExpandableRows?this.calculateTreePaddingX(e):0,j=0,P=this.getVisibleRowHeights(e),Q=this.getVisibleColumnWidths(e,H,U),$=Array.from(P.keys()),J=Array.from(Q.keys()),A=new Map([...P,...this.getFloatingRowHeights(e)]),W=new Map([...Q,...this.getFloatingColumnWidths(e)]),q=this.getVisibleColumnXs(W,J,s),Z=this.getVisibleRowYs(A,$,i),le=$.length>0?$[$.length-1]:n,G=J.length>0?J[J.length-1]:t,oe=this.getBottomViewport(e,$,Z,A),ue=this.getRightViewport(e,J,q,W),ae=this.getFloatingTopHeight(e,A),he=this.getFloatingBottomHeight(e,A),we=this.getFloatingLeftWidth(e,W),He=this.getFloatingRightWidth(e,W),Fe=Array.from(W.values()),mt=Array.from(A.values()),et=Fe.reduce((Ae,Yt)=>Ae+Yt,0)-s,De=mt.reduce((Ae,Yt)=>Ae+Yt,0)-i,gt=s+et+C,lt=i+De,vt=o-L,kt=l-V,Cn=this.getLastLeft(e,null,vt-C),zt=this.getLastLeft(e,null,vt-C-S),So=this.getLastTop(e,null,kt-he),Rs=this.getLastTop(e,null,kt-he-S);let Kt=zt,Xn=Rs;Cn===0&&So===0&&(Kt=0,Xn=0);const ti=Kt>0,ki=ti?S:0,ni=Xn>0,si=ni?S:0,wo=L,vo=M*b,Zn=o-wo-si,xs=l-vo-ki,la=T===1?Zn/gt:(T-Kt)/T,To=y===1?xs/lt:(y-Xn)/y,Mi=ti?Oe(Zn*la,w,Zn-1):0,Li=ni?Oe(xs*To,w,xs-1):0,Oi=k(W,t,0),Eo=k(A,n,0),aa=Oi>0?s/Oi:0,ra=Eo>0?i/Eo:0,da=T===1?s/(gt-vt):(t+aa)/Kt,ca=y===1?i/(lt-kt):(n+ra)/Xn,ha=ti?da*(Zn-Mi):0,Ds=ni?ca*(xs-Li):0,yo=[...Array(E).keys(),...[...Array(R).keys()].map(Ae=>y-Ae-1)],ii=new Map([...Z,...this.getFloatingRowYs(e,A,Math.floor(l-V-ki))]),Ro=[...Array(x).keys(),...[...Array(D).keys()].map(Ae=>T-Ae-1)],Is=new Map([...q,...this.getFloatingColumnXs(e,W,Math.floor(o-L-si))]),xo=[];if(m)for(let Ae=m.range[0];Ae<=m.range[1];Ae+=1)xo.push(Ae),W.has(Ae)||W.set(Ae,this.getVisibleColumnWidth(Ae,e)),Is.has(Ae)||Is.set(Ae,0);const Ai=$.concat(yo),_i=J.concat(Ro).concat(xo),Do=this.getModelRows(Ai,e),Io=this.getModelColumns(_i,e),Fo=this.getVisibleRowTreeBoxes(A,Do,e),ua=this.getTopVisible(e,ii,A,$),No=this.getLeftVisible(e,Is,W,J),ko=Xn>0?this.getBottomVisible(e,ii,A,$,V):le,Mo=Kt>0?this.getRightVisible(e,Is,W,J,L):G,{fontWidths:Lo,userColumnWidths:Oo,userRowHeights:Ao,calculatedRowHeights:ma,calculatedColumnWidths:Ge}=this;return{rowHeight:g,rowHeaderWidth:p,rowFooterWidth:C,rowCount:y,columnWidth:f,columnCount:T,columnHeaderHeight:b,floatingTopRowCount:E,floatingBottomRowCount:R,floatingLeftColumnCount:x,floatingRightColumnCount:D,gridX:L,gridY:V,firstRow:O,firstColumn:H,treePaddingX:U,treePaddingY:j,left:t,top:n,bottom:le,right:G,topOffset:i,leftOffset:s,topVisible:ua,leftVisible:No,bottomVisible:ko,rightVisible:Mo,bottomViewport:oe,rightViewport:ue,width:o,height:l,maxX:et,maxY:De,lastLeft:Kt,lastTop:Xn,barHeight:xs,barTop:vo,barWidth:Zn,barLeft:wo,handleHeight:Li,handleWidth:Mi,hasHorizontalBar:ti,hasVerticalBar:ni,verticalBarWidth:si,horizontalBarHeight:ki,scrollX:ha,scrollY:Ds,scrollableContentWidth:gt,scrollableContentHeight:lt,scrollableViewportWidth:vt,scrollableViewportHeight:kt,visibleRows:$,visibleColumns:J,visibleRowHeights:P,visibleColumnWidths:Q,floatingRows:yo,floatingColumns:Ro,allRows:Ai,allColumns:_i,allRowHeights:A,allColumnWidths:W,floatingTopHeight:ae,floatingBottomHeight:he,floatingLeftWidth:we,floatingRightWidth:He,visibleRowYs:Z,visibleColumnXs:q,allRowYs:ii,allColumnXs:Is,visibleRowTreeBoxes:Fo,modelRows:Do,modelColumns:Io,movedRows:h,movedColumns:u,fontWidths:Lo,userColumnWidths:Oo,userRowHeights:Ao,calculatedRowHeights:ma,calculatedColumnWidths:Ge,columnHeaderMaxDepth:M}}getGridX(e){const{theme:t}=e,{rowHeaderWidth:n}=t;return n}getGridY(e){const{theme:t,model:n}=e,{columnHeaderHeight:s}=t,{columnHeaderMaxDepth:i}=n;return i*s}getVisibleHeight(e,t=this.getFloatingRowHeights(e)){const{height:n,theme:s}=e,{scrollBarSize:i}=s,o=this.getGridY(e),l=this.getFloatingBottomHeight(e,t),a=this.getFloatingTopHeight(e,t);return n-l-a-o-i}getVisibleWidth(e,t=this.getFloatingColumnWidths(e)){const{width:n,theme:s}=e,{scrollBarSize:i,rowFooterWidth:o}=s,l=this.getGridX(e),a=this.getFloatingRightWidth(e,t),d=this.getFloatingLeftWidth(e,t);return n-d-a-l-i-o}getFirstIndex(e,t,n){const s=e.size+1;for(let i=0;i<s;i+=1){const o=t(i,n);if(e.get(o)!==0)return i}return 0}getFirstColumn(e){return this.getFirstIndex(this.userColumnWidths,this.getModelColumn.bind(this),e)}getFirstRow(e){return this.getFirstIndex(this.userRowHeights,this.getModelRow.bind(this),e)}getLastLeft(e,t,n){const{model:s}=e,{columnCount:i,floatingRightColumnCount:o}=s;let l=Math.max(0,i-o-1);t!=null&&(l=t);let a=0;for(;l>=0;){const d=this.getVisibleColumnWidth(l,e);if(a+=d,a>=n)return Oe(l+1,0,t??i-1);l-=1}return 0}getLastTop(e,t,n){const{model:s}=e,{rowCount:i,floatingBottomRowCount:o}=s;let l=Math.max(0,i-o-1);t!=null&&(l=t);let a=0;for(;l>=0;){const d=this.getVisibleRowHeight(l,e);if(a+=d,a>=n)return Oe(l+1,0,i-1);l-=1}return 0}getTopForTopVisible(e,t){const n=this.getFloatingTopHeight(e);let s=t,i=0;for(;s>0&&i<n;)s-=1,i+=this.getVisibleRowHeight(s,e);return s}getTopForBottomVisible(e,t){const{height:n}=e,s=this.getGridY(e),i=this.getFloatingBottomHeight(e),o=n-s-i;return this.getLastTop(e,t,o)}getLeftForLeftVisible(e,t){const n=this.getFloatingLeftWidth(e);let s=t,i=0;for(;s>0&&i<n;)s-=1,i+=this.getVisibleColumnWidth(s,e);return s}getLeftForRightVisible(e,t){const{width:n}=e,s=this.getGridX(e),i=this.getFloatingRightWidth(e),o=n-s-i;return this.getLastLeft(e,t,o)}getFloatingRowHeights(e){const{model:t}=e,{floatingTopRowCount:n,floatingBottomRowCount:s,rowCount:i}=t,o=new Map;for(let l=0;l<n&&l<i;l+=1)o.set(l,this.getVisibleRowHeight(l,e));for(let l=0;l<s&&i-l-1>=0;l+=1){const a=i-l-1;o.set(a,this.getVisibleRowHeight(a,e))}return o}getVisibleRowHeights(e){const{top:t,topOffset:n,height:s,model:i}=e;let o=0,l=t;const a=new Map,{rowCount:d}=i;for(;o<s+n&&l<d;){const h=this.getVisibleRowHeight(l,e);a.set(l,h),o+=h,l+=1}return a}getFloatingColumnWidths(e,t=this.getFirstColumn(e),n=this.calculateTreePaddingX(e)){const{model:s}=e,{columnCount:i,floatingLeftColumnCount:o,floatingRightColumnCount:l}=s,a=new Map;for(let d=0;d<o&&d<i;d+=1)a.set(d,this.getVisibleColumnWidth(d,e,t,n));for(let d=0;d<l&&i-d-1>=0;d+=1){const h=i-d-1;a.set(h,this.getVisibleColumnWidth(h,e,t,n))}return a}getVisibleColumnWidths(e,t=this.getFirstColumn(e),n=this.calculateTreePaddingX(e)){const{left:s,leftOffset:i,width:o,model:l}=e;let a=0,d=s;const h=new Map,{columnCount:u}=l;for(;a<o+i&&d<u;){const m=this.getVisibleColumnWidth(d,e,t,n);h.set(d,m),a+=m,d+=1}return h}getFloatingColumnXs(e,t,n){const{model:s}=e,{columnCount:i,floatingLeftColumnCount:o,floatingRightColumnCount:l}=s;return qd(o,l,i,n,t)}getVisibleColumnXs(e,t,n){const s=new Map;let i=-n;for(let o=0;o<t.length;o+=1){const l=t[o],a=k(e,l);s.set(l,i),i+=a}return s}getFloatingRowYs(e,t,n){const{model:s}=e,{floatingTopRowCount:i,floatingBottomRowCount:o,rowCount:l}=s;return qd(i,o,l,n,t)}getVisibleRowYs(e,t,n){const s=new Map;let i=-n;for(let o=0;o<t.length;o+=1){const l=t[o],a=k(e,l);s.set(l,i),i+=a}return s}getVisibleRowTreeBoxes(e,t,n){const s=new Map,{model:i,theme:o}=n,{treeDepthIndent:l,treeHorizontalPadding:a}=o;return je(i)&&i.hasExpandableRows&&e.forEach((d,h)=>{const u=k(t,h);if(i.isRowExpandable(u)){const m=i.depthForRow(u),g=m*l+a,p=(m+1)*l+a,C=0,f=d;s.set(h,{x1:g,y1:C,x2:p,y2:f})}}),s}getFloatingLeftWidth(e,t=this.getFloatingColumnWidths(e)){const{model:n}=e,{floatingLeftColumnCount:s}=n;let i=0;for(let o=0;o<s;o+=1)i+=k(t,o);return i}getFloatingRightWidth(e,t=this.getFloatingColumnWidths(e)){const{model:n}=e,{floatingRightColumnCount:s,columnCount:i}=n;let o=0;for(let l=0;l<s;l+=1)o+=k(t,i-l-1);return o}getFloatingTopHeight(e,t=this.getFloatingRowHeights(e)){const{model:n}=e,{floatingTopRowCount:s}=n;let i=0;for(let o=0;o<s;o+=1)i+=k(t,o);return i}getFloatingBottomHeight(e,t=this.getFloatingRowHeights(e)){const{model:n}=e,{floatingBottomRowCount:s,rowCount:i}=n;let o=0;for(let l=0;l<s;l+=1)o+=k(t,i-l-1);return o}getTopVisible(e,t,n,s){const i=this.getFloatingTopHeight(e,n);for(let o=0;o<s.length;o+=1){const l=s[o];if(k(t,l)>=i)return l}return 0}getLeftVisible(e,t,n,s){const i=this.getFloatingLeftWidth(e,n);for(let o=0;o<s.length;o+=1){const l=s[o];if(k(t,l)>=i)return l}return 0}getBottomVisible(e,t,n,s,i){const{height:o,theme:l}=e,{scrollBarSize:a}=l,d=this.getFloatingBottomHeight(e,n),h=o-i-a-d;for(let u=s.length-1;u>=0;u-=1){const m=s[u],g=k(t,m),p=k(n,m);if(g+p<=h)return m}return 0}getRightVisible(e,t,n,s,i){const{width:o,theme:l}=e,{scrollBarSize:a}=l,d=this.getFloatingRightWidth(e,n),h=o-i-a-d;for(let u=s.length-1;u>=0;u-=1){const m=s[u],g=k(t,m),p=k(n,m);if(g+p<=h)return m}return 0}getBottomViewport(e,t,n,s){const{height:i,theme:o}=e,{rowHeight:l}=o;return this.getLastIndexViewport(t,n,s,i,l)}getRightViewport(e,t,n,s){const{width:i,theme:o}=e,{columnWidth:l}=o;return this.getLastIndexViewport(t,n,s,i,l)}getLastIndexViewport(e,t,n,s,i){let o=0,l=0;return e.length>0&&(o=e[e.length-1],l=k(t,o)+k(n,o)),l<s&&(o+=Math.ceil((s-l)/i)),o}getVisibleItemSize(e,t,n){return t.get(e)??n()}getVisibleRowHeight(e,t){const n=this.getModelRow(e,t),s=this.calculateRowHeight(e,n,t);return this.getVisibleItemSize(n,this.userRowHeights,()=>{const i=this.initialRowHeights.get(n);return i!==void 0?i:s})}getVisibleColumnWidth(e,t,n=this.getFirstColumn(t),s=this.calculateTreePaddingX(t)){const i=this.getModelColumn(e,t),o=this.calculateColumnWidth(e,i,t,n,s);return this.getVisibleItemSize(i,this.userColumnWidths,()=>{const l=this.initialColumnWidths.get(i);return l!==void 0?l:o})}getModelRows(e,t){const n=new Map;for(let s=0;s<e.length;s+=1){const i=e[s],o=this.getModelRow(i,t);n.set(i,o)}return n}getModelRow(e,t){if(this.modelRows.has(e))return k(this.modelRows,e);const{movedRows:n}=t,s=_.getModelIndex(e,n);return this.modelRows.set(e,s),s}getModelColumns(e,t){const n=new Map;for(let s=0;s<e.length;s+=1){const i=e[s],o=this.getModelColumn(i,t);n.set(i,o)}return n}getModelColumn(e,t){if(this.modelColumns.has(e))return k(this.modelColumns,e);const{movedColumns:s}=t,i=_.getModelIndex(e,s);return this.modelColumns.set(e,i),i}calculateRowHeight(e,t,n){const{theme:s}=n,{autoSizeRows:i,rowHeight:o}=s;if(!i)return o;const l=this.calculatedRowHeights.get(t);return l??(this.calculatedRowHeights.set(t,Math.ceil(o)),Uo(this.calculatedRowHeights),o)}calculateColumnWidth(e,t,n,s=this.getFirstColumn(n),i=this.calculateTreePaddingX(n)){const{theme:o}=n,{autoSizeColumns:l,minColumnWidth:a}=o;if(!l){const{columnWidth:g}=o;return g}const d=this.calculateColumnHeaderWidth(t,n),h=this.calculateColumnDataWidth(t,n),u=this.calculatedColumnWidths.get(t);let m=Math.ceil(Math.max(d,h));return m=Math.max(a,m),u!=null&&u>m?m=u:(this.calculatedColumnWidths.set(t,m),Uo(this.calculatedColumnWidths)),e===s&&(m+=i),m}calculateColumnHeaderWidth(e,t){const{model:n,theme:s}=t,{headerFont:i,headerHorizontalPadding:o}=s,l=n.textForColumnHeader(e,0);if(l!==void 0&&l!==""){const a=this.getWidthForFont(i,t);return l.length*a+o*2}return o*2}calculateColumnDataWidth(e,t){const{top:n,height:s,width:i,model:o,theme:l}=t,{floatingTopRowCount:a,floatingBottomRowCount:d,rowCount:h}=o,{font:u,cellHorizontalPadding:m,rowHeight:g,rowHeaderWidth:p,rowFooterWidth:C,scrollBarSize:f,dataBarHorizontalPadding:b}=l;let w=0;const S=this.getWidthForFont(u,t),T=s/g,y=Math.ceil(n+T);return _.iterateAllItems(n,y,a,d,h,E=>{const R=this.getModelRow(E,t),x=o.textForCell(e,R),D=o.renderTypeForCell(e,R);let M=0;if(x){const O=m*2;M=x.length*S+O}D==="dataBar"&&(M+=b),w=Math.max(w,M)}),w=Math.max(Math.min(w,(i-p-f-C)*bo.MAX_COLUMN_WIDTH),m*2),w}calculateTreePaddingX(e){const{top:t,height:n,model:s,theme:i}=e,{rowHeight:o,treeDepthIndent:l}=i;if(!je(s)||!s.hasExpandableRows)return 0;let a=0;const d=n/o,h=Math.ceil(t+d);for(let u=t;u<=h;u+=1){const m=this.getModelRow(u,e),g=s.depthForRow(m);a=Math.max(a,l*(g+1))}return a}getWidthForFont(e,t){if(this.fontWidths.has(e))return k(this.fontWidths,e);const{context:n}=t;n.font=e;const s=n.measureText("8"),{width:i}=s;return this.fontWidths.set(e,i),this.fontWidths.set(n.font,i),i}setColumnWidth(e,t){const n=new Map(this.userColumnWidths);n.set(e,Math.ceil(t)),Uo(n),this.userColumnWidths=n}resetColumnWidth(e){const t=new Map(this.userColumnWidths);t.delete(e),this.userColumnWidths=t}setRowHeight(e,t){const n=new Map(this.userRowHeights);n.set(e,Math.ceil(t)),Uo(n),this.userRowHeights=n}resetRowHeight(e){const t=new Map(this.userRowHeights);t.delete(e),this.userRowHeights=t,this.calculatedRowHeights.delete(e)}}const xS=bo,DS=Object.freeze({allowColumnResize:!0,allowRowResize:!0,autoSelectRow:!1,autoSelectColumn:!1,autoSizeColumns:!0,autoSizeRows:!0,backgroundColor:"#000000",black:"#000000",white:"#ffffff",cellHorizontalPadding:5,headerHorizontalPadding:5,font:"12px Arial, sans serif",gridColumnColor:"#8f8f8f66",gridRowColor:"#8f8f8f66",headerBackgroundColor:"#222222",headerSeparatorColor:"#000000",headerSeparatorHoverColor:"#888888",headerSeparatorHandleSize:5,headerHiddenSeparatorSize:5,headerHiddenSeparatorHoverColor:"#8888FF",headerColor:"#d5d5d5",headerFont:"10px Arial, sans serif",columnHoverBackgroundColor:"#444444",selectedColumnHoverBackgroundColor:"#494949",rowBackgroundColors:"#333333 #222222",rowHoverBackgroundColor:"#444444",selectedRowHoverBackgroundColor:"#494949",minScrollHandleSize:50,scrollBarBackgroundColor:"#111111",scrollBarHoverBackgroundColor:"#333333",scrollBarCasingColor:"#000000",scrollBarCornerColor:"#000000",scrollBarColor:"#555555",scrollBarHoverColor:"#888888",scrollBarActiveColor:"#AAAAAA",scrollBarSize:12,scrollBarHoverSize:16,scrollBarCasingWidth:1,scrollSnapToColumn:!1,scrollSnapToRow:!1,selectionColor:"#4286f433",selectionOutlineColor:"#4286f4",selectionOutlineCasingColor:"#222222",scrollBarSelectionTick:!0,scrollBarSelectionTickColor:"#4286f433",scrollBarActiveSelectionTickColor:"#4286f480",shadowBlur:8,shadowColor:"#000000",textColor:"#ffffff",hyperlinkColor:"#4878ea",maxDepth:6,treeDepthIndent:10,treeHorizontalPadding:5,treeLineColor:"#888888",treeMarkerColor:"#cccccc",treeMarkerHoverColor:"#ffffff",rowHeight:20,columnWidth:100,minRowHeight:20,minColumnWidth:55,columnHeaderHeight:20,rowHeaderWidth:30,rowFooterWidth:0,headerResizeSnapThreshold:10,headerResizeHiddenSnapThreshold:8,allowColumnReorder:!0,allowRowReorder:!0,reorderOffset:2,floatingGridColumnColor:"#8f8f8f66",floatingGridRowColor:"#8f8f8f66",floatingRowBackgroundColors:"#393939 #292929",floatingDividerOuterColor:"#000000",floatingDividerInnerColor:"#cccccc",zeroLineColor:"#888888",positiveBarColor:"#00ff00",negativeBarColor:"#ff0000",dataBarHorizontalPadding:90}),IS=DS,FS=(c,e)=>{let t=!1;const n=Re(c,{...e,dispose:()=>{t||(t=!0,n.clear(),t=!1)}});return n},pn=FS;function NS(c,e,t=6){const n=ja.hex.lab.raw(c);return n[0]=Math.max(n[0]-n[0]/t*e,0),`#${ja.lab.hex(n)}`}function kS(c,e){const[t,n,s]=ja.hex.rgb(c);return`rgba(${t}, ${n}, ${s}, ${e})`}const MS=c=>{const{r:e,g:t,b:n}=c,s=.4122214708*e+.5363325363*t+.0514459929*n,i=.2119034982*e+.6806995451*t+.1073969566*n,o=.0883024619*e+.2817188376*t+.6299787005*n,l=Math.cbrt(s),a=Math.cbrt(i),d=Math.cbrt(o);return{L:.2104542553*l+.793617785*a-.0040720468*d,a:1.9779984951*l-2.428592205*a+.4505937099*d,b:.0259040371*l+.7827717662*a-.808675766*d}},LS=c=>{const{L:e,a:t,b:n}=c,s=e+.3963377774*t+.2158037573*n,i=e-.1055613458*t-.0638541728*n,o=e-.0894841775*t-1.291485548*n,l=s*s*s,a=i*i*i,d=o*o*o;return{r:Oe(4.0767416621*l-3.3077115913*a+.2309699292*d,0,255),g:Oe(-1.2684380046*l+2.6097574011*a-.3413193965*d,0,255),b:Oe(-.0041960863*l-.7034186147*a+1.707614701*d,0,255)}},OS=c=>{const e=c.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(t,n,s,i)=>`#${n}${n}${s}${s}${i}${i}`).substring(1).match(/.{2}/g)?.map(t=>parseInt(t,16))??[0,0,0];return{r:e[0],g:e[1],b:e[2]}},AS=c=>{const e=Math.round(c.r),t=Math.round(c.g),n=Math.round(c.b);return`#${[e,t,n].map(s=>{const i=s.toString(16);return i.length===1?`0${i}`:i}).join("")}`},_S=(c,e,t)=>{const{L:n,a:s,b:i}=c,{L:o,a:l,b:a}=e,d=n+(o-n)*t,h=s+(l-s)*t,u=i+(a-i)*t;return{L:d,a:h,b:u}},Bs={colorWithAlpha:kS,darkenForDepth:NS,linearSRGBToOklab:MS,OklabToLinearSRGB:LS,hexToRgb:OS,rgbToHex:AS,lerpColor:_S};class ht{order;constructor(e=5e3){this.order=e}cursor=null;onDown(e,t,n){return!1}onMove(e,t,n){return!1}onDrag(e,t,n){return!1}onLeave(e,t,n){return!1}onClick(e,t,n){return!1}onContextMenu(e,t,n){return!1}onDoubleClick(e,t,n){return!1}onUp(e,t,n){return!1}onWheel(e,t,n){return!1}}class PS extends ht{draggingIndex;resizingItems=[];hiddenItems=[];targetSizes=new Map;dragOffset=0;onDown(e,t){const{metrics:n}=t,{model:s}=t.props,i=t.getTheme();if(!n)throw new Error("metrics not set");const o=this.getSeparator(e,n,s,i);if(o!=null){const l=o.index;return this.dragOffset=0,this.draggingIndex=l,this.resizingItems=[l],this.hiddenItems=this.getHiddenItems(l,n).reverse(),this.targetSizes.clear(),this.addTargetSize(n,l),this.updateCursor(n,l),this.updateSeparator(t,o),!0}return!1}onMove(e,t){const{metrics:n}=t,{model:s}=t.props,i=t.getTheme();if(!n)throw new Error("metrics not set");const o=this.getSeparator(e,n,s,i);return o!=null?(this.updateCursor(n,o.index),!0):!1}onDrag(e,t){if(this.draggingIndex==null)return!1;const n=e[this.pointProperty],{metricCalculator:s,metrics:i}=t;if(!i)throw new Error("metrics not set");const o=t.getTheme(),l=i[this.visibleOffsetProperty],a=i[this.marginProperty],d=i[this.calculatedSizesProperty],h=i[this.modelIndexesProperty],u=i[this.firstIndexProperty],m=i[this.treePaddingProperty],g=new Map;let p=this.resizingItems[this.resizingItems.length-1];for(;p!=null;){const C=k(l,p),f=n-a-C-this.dragOffset,b=k(h,p),w=this.targetSizes.get(b),S=this.resizingItems.length>1,T=this.hiddenItems.indexOf(p);let y=k(d,b);p===u&&(y+=m);let E=f;Math.abs(f-y)<=o.headerResizeSnapThreshold?E=y:w!==void 0&&f>w&&(S&&T!==0||T>0)?E=w:f<=o.headerResizeHiddenSnapThreshold&&(E=0),g.set(b,E),f<-o.headerResizeSnapThreshold&&E===0?T>=0&&S?(this.resizingItems.pop(),this.removeTargetSize(i,p),p=this.resizingItems[this.resizingItems.length-1],this.dragOffset-=this.targetSizes.get(k(h,p))??0):(p=this.getNextShownItem(p,i),p!==null&&(this.resizingItems.push(p),this.addTargetSize(i,p))):w!==void 0&&f>w+o.headerResizeSnapThreshold&&E===w?T>0?(this.dragOffset+=E,p=this.hiddenItems[T-1],this.resizingItems.push(p),this.addTargetSize(i,p)):S?(this.resizingItems.pop(),this.removeTargetSize(i,p),p=this.resizingItems[this.resizingItems.length-1]):p=null:p=null}return g.forEach((C,f)=>{const b=s[this.initialSizesProperty].get(f)??d.get(f);C===b?this.resetSize(s,f):this.setSize(s,f,C)}),this.updateCursor(i,this.draggingIndex),!0}onUp(e,t){return this.draggingIndex!=null&&(this.draggingIndex=void 0,this.resizingItems=[],this.hiddenItems=[],this.targetSizes.clear(),this.updateSeparator(t,null)),!1}onDoubleClick(e,t){const{metrics:n,metricCalculator:s}=t,{model:i}=t.props,o=t.getTheme();if(!n)throw new Error("metrics not set");const l=this.getSeparator(e,n,i,o);if(l!=null){const a=n[this.modelIndexesProperty],d=k(a,l.index),h=k(n[this.calculatedSizesProperty],d),u=s[this.initialSizesProperty].get(d);return h===u?this.resetSize(s,d):this.setSize(s,d,h),t.forceUpdate(),!0}return!1}updateCursor(e,t){const n=e[this.visibleSizesProperty];k(n,t)===0?this.cursor=this.hiddenCursor:this.cursor=this.defaultCursor}addTargetSize(e,t){const n=e[this.modelIndexesProperty],s=e[this.userSizesProperty],i=e[this.calculatedSizesProperty],o=t===0?e[this.treePaddingProperty]:0,l=k(n,t);let a=s.get(l);(a==null||a===0)&&(a=k(i,l)+o),this.targetSizes.set(l,a)}removeTargetSize(e,t){const n=e[this.modelIndexesProperty],s=k(n,t);this.targetSizes.delete(s)}}const hu=PS;class Mr extends hu{static getColumnSeparator(e,t,n,s){if(!s.allowColumnResize)return null;const{x:i,y:o,columnHeaderDepth:l}=e,{modelColumns:a}=t,d=_.getColumnSeparatorIndex(i,o,t,s);return d==null||l==null||l>0?null:a.get(d)!=null?{index:d,depth:0}:null}hiddenCursor="e-resize";defaultCursor="col-resize";pointProperty="x";userSizesProperty="userColumnWidths";visibleOffsetProperty="visibleColumnXs";visibleSizesProperty="visibleColumnWidths";marginProperty="rowHeaderWidth";calculatedSizesProperty="calculatedColumnWidths";initialSizesProperty="initialColumnWidths";modelIndexesProperty="modelColumns";firstIndexProperty="firstColumn";treePaddingProperty="treePaddingX";getHiddenItems=_.getHiddenColumns;getNextShownItem=_.getNextShownColumn;setSize(e,t,n){e.setColumnWidth(t,n)}resetSize(e,t){e.resetColumnWidth(t)}updateSeparator(e,t){e.setState({draggingColumnSeparator:t,isDragging:t!==null})}getSeparator=Mr.getColumnSeparator}const uu=Mr,Zs=10;class jS{drawCellRowTreeMarker(e,t,n){const{metrics:s,model:i,mouseX:o,mouseY:l,theme:a}=t,{firstColumn:d,gridX:h,gridY:u,allColumnXs:m,allColumnWidths:g,allRowYs:p,allRowHeights:C,visibleRowTreeBoxes:f}=s,{treeMarkerColor:b,treeMarkerHoverColor:w}=a,S=k(m,d),T=k(g,d),y=k(p,n),E=k(C,n);if(!je(i)||!i.isRowExpandable(n))return;const R=k(f,n),x=o!=null&&l!=null&&o>=h+S&&o<=h+S+T&&l>=u+y&&l<=u+y+E?w:b;this.drawTreeMarker(e,t,S,y,R,x,i.isRowExpanded(n))}drawTreeMarker(e,t,n,s,i,o,l){const{x1:a,y1:d,x2:h,y2:u}=i,m=l?"⊟":"⊞",g=n+(a+h)*.5+.5,p=s+(d+u)*.5+.5;e.fillStyle=o,e.textAlign="center",e.fillText(m,g,p)}getCachedTruncatedString=pn((e,t,n,s,i)=>fu.truncateToWidth(e,t,n,s,i),{max:1e4})}const mu=jS;function Xd(c){return c?.dataBarOptionsForCell!==void 0}class HS extends mu{heightOfDigits;drawCellContent(e,t,n,s){const{metrics:i,model:o,theme:l}=t;if(!Xd(o))return;const{modelColumns:a,modelRows:d,allRowHeights:h,allRowYs:u,firstColumn:m,fontWidths:g}=i,p=n===m,C=k(h,s),f=k(d,s),b=k(a,n),w=k(u,s),S=o.textAlignForCell(b,f),T=o.textForCell(b,f),{x:y,width:E}=_.getTextRenderMetrics(t,n,s),R=g?.get(e.font)??Zs,x=o.truncationCharForCell(b,f),D=this.getCachedTruncatedString(e,T,E,R,x),{columnMin:M,columnMax:O,axis:H,color:L,valuePlacement:V,opacity:U,markers:j,direction:P,value:Q}=o.dataBarOptionsForCell(b,f),$=Array.isArray(L);if(M==null||O==null)return;const{maxWidth:J,x:A,y:W,zeroPosition:q,leftmostPosition:Z,markerXs:le,totalValueRange:G,dataBarWidth:oe}=this.getDataBarRenderMetrics(e,t,n,s);if(this.heightOfDigits===void 0){const{actualBoundingBoxAscent:ae,actualBoundingBoxDescent:he}=e.measureText("1234567890");this.heightOfDigits=ae+he}if(e.save(),e.textAlign=S,$){const ae=Q>=0?L[L.length-1]:L[0];e.fillStyle=ae}else e.fillStyle=L;if(e.textBaseline="top",e.font=l.font,V!=="hide"&&e.fillText(D,y,w+(C-this.heightOfDigits)/2),$){const ae=L.map(he=>Bs.linearSRGBToOklab(Bs.hexToRgb(he)));if(e.save(),e.beginPath(),e.roundRect(A,W,oe,C-2,1),e.clip(),Q<0){if(P==="LTR"){const we=Math.round(Math.abs(M)/G*J)/(L.length-1);let He=Math.round(Z);for(let Fe=0;Fe<L.length-1;Fe+=1){const mt=ae[Fe],et=ae[Fe+1];this.drawGradient(e,mt,et,He,w+1,we,C),He+=we}}else if(P==="RTL"){const we=Math.round(J-Math.abs(O)/G*J)/(L.length-1);let He=Math.round(q);for(let Fe=L.length-1;Fe>0;Fe-=1){const mt=ae[Fe],et=ae[Fe-1];this.drawGradient(e,mt,et,He,w+1,we,C),He+=we}}}else if(P==="LTR"){const we=(Math.round(J-Math.abs(M)/G*J)-1)/(L.length-1);let He=Math.round(q);for(let Fe=0;Fe<L.length-1;Fe+=1){const mt=ae[Fe],et=ae[Fe+1];this.drawGradient(e,mt,et,He,w+1,we,C-2),He+=we}}else if(P==="RTL"){const we=Math.round(Math.abs(O)/G*J)/(L.length-1);let He=Math.round(Z);for(let Fe=L.length-1;Fe>0;Fe-=1){const mt=ae[Fe],et=ae[Fe-1];this.drawGradient(e,mt,et,He,w+1,we,C-2),He+=we}}e.restore()}else e.save(),e.globalAlpha=U,e.beginPath(),e.roundRect(A,W,oe,C-2,1),e.fill(),e.restore();J>0&&le.forEach((ae,he)=>{e.fillStyle=j[he].color,e.fillRect(ae,W,1,C-2)}),!(H==="directional"&&(V==="beside"&&S==="right"&&P==="LTR"||V==="beside"&&S==="left"&&P==="RTL"||V!=="beside"))&&(e.strokeStyle=l.zeroLineColor,e.beginPath(),e.setLineDash([2,1]),e.moveTo(q,w),e.lineTo(q,w+C),e.stroke()),e.restore(),p&&je(o)&&o.hasExpandableRows&&this.drawCellRowTreeMarker(e,t,s)}getDataBarRenderMetrics(e,t,n,s){const{metrics:i,model:o,theme:l}=t;if(!Xd(o))throw new Error("Grid model is not a data bar grid model");const{firstColumn:a,allColumnXs:d,allColumnWidths:h,allRowYs:u,modelColumns:m,modelRows:g,visibleRows:p}=i,{cellHorizontalPadding:C,treeDepthIndent:f,treeHorizontalPadding:b}=l,w=k(m,n),S=k(g,s),T=k(d,n),y=k(u,s),E=k(h,n),R=n===a;let x=0;je(o)&&o.hasExpandableRows&&R&&(x=f*(o.depthForRow(s)+1)+b);const D=o.textAlignForCell(w,S),{columnMin:M,columnMax:O,axis:H,valuePlacement:L,markers:V,direction:U,value:j}=o.dataBarOptionsForCell(w,S),P=this.getCachedWidestValueForColumn(e,p,g,o,w),Q=2,$=L==="beside"&&D==="right"?2:1;let J=O-M;O>=0&&M>=0||M===O?J=O:O<=0&&M<=0&&(J=Math.abs(M));let A=E-x-$-Q;L==="beside"&&(A=A-C-P),A<0&&(A=0);const W=Math.max(Math.abs(M),Math.abs(O));let q=Math.abs(j)/J*A;A===0?q=0:H==="middle"?q=Math.abs(j)/W*(A/2):H==="directional"&&(q=Math.abs(j)/W*A);let Z=M>=0?0:Math.abs(M)/J*A,le=j>=0?Z:Z-Math.abs(j)/J*A,G=V.map(ae=>{const{column:he}=ae,we=Number(o.textForCell(he,S));return we>=0?Z+Math.abs(we)/J*A:Z-Math.abs(we)/J*A}),oe=L==="beside"&&D==="left"?C+P+Q:Q,ue=L==="beside"&&D==="right"?E-C-P-$:$;return U==="RTL"&&(Z=M>=0?E:E-Math.abs(M)/J*A,le=j>=0?Z-j/J*A:Z,G=V.map(ae=>{const{column:he}=ae,we=Number(o.textForCell(he,S));return we>=0?Z-Math.abs(we)/J*A:Z+Math.abs(we)/J*A})),H==="middle"?(Z=A/2,U==="LTR"?(le=j>=0?Z:Z-Math.abs(j)/W*(A/2),G=V.map(ae=>{const{column:he}=ae,we=Number(o.textForCell(he,S));return we>=0?Z+Math.abs(we)/W*(A/2):Z-Math.abs(we)/W*(A/2)})):U==="RTL"&&(le=j<=0?Z:Z-Math.abs(j)/W*(A/2),G=V.map(ae=>{const{column:he}=ae,we=Number(o.textForCell(he,S));return we<=0?Z+Math.abs(we)/W*(A/2):Z-Math.abs(we)/W*(A/2)}))):H==="directional"&&(U==="LTR"?(Z=0,le=Z,G=V.map(ae=>{const{column:he}=ae,we=Number(o.textForCell(he,S));return Z+Math.abs(we)/W*A})):U==="RTL"&&(Z=E,le=Z-Math.abs(j)/W*A,G=V.map(ae=>{const{column:he}=ae,we=Number(o.textForCell(he,S));return Z-Math.abs(we)/W*A}))),U==="LTR"?(Z+=T+Q+x,le+=T+Q+x,G=G.map(ae=>ae+T+Q+x),L==="beside"&&D==="left"&&(Z+=P+C,le+=P+C,G=G.map(ae=>ae+P+C))):U==="RTL"&&(Z=Z+T-$,le=le+T-$,G=G.map(ae=>ae+T-$),L==="beside"&&D==="right"&&(Z=Z-C-P,le=le-C-P,G=G.map(ae=>ae-C-P))),oe+=T+x,ue+=T,{maxWidth:A,x:le,y:y+1.5,zeroPosition:Z,leftmostPosition:oe,rightmostPosition:ue,totalValueRange:J,dataBarWidth:q,markerXs:G}}drawGradient(e,t,n,s,i,o,l){let a=t;for(let d=s;d<=s+o;d+=.5)this.drawGradientPart(e,d,i,1,l,Bs.rgbToHex(Bs.OklabToLinearSRGB(a))),a=Bs.lerpColor(t,n,(d-s)/o)}drawGradientPart(e,t,n,s,i,o){e.fillStyle=o,e.fillRect(t,n,s,i)}getCachedWidestValueForColumn=pn((e,t,n,s,i)=>{let o=0;for(let l=0;l<t.length;l+=1){const a=t[l],d=k(n,a),h=s.textForCell(i,d);o=Math.max(o,e.measureText(h).width)}return o},{max:1e3})}const gu=HS;class BS extends mu{drawCellContent(e,t,n,s){const{metrics:i,model:o,theme:l}=t,{fontWidths:a,modelColumns:d,modelRows:h,allRowHeights:u,firstColumn:m}=i,g=n===m,{textColor:p}=l,C=k(u,s),f=k(h,s),b=k(d,n),w=o.textForCell(b,f),S=o.truncationCharForCell(b,f);if(w&&C>0){const T=o.textAlignForCell(b,f)||"left";e.textAlign=T;const y=o.colorForCell(b,f,l)||p;e.fillStyle=y,e.save();const{width:E,x:R,y:x}=_.getTextRenderMetrics(t,n,s),D=a.get(e.font)??Zs,M=this.getCachedTruncatedString(e,w,E,D,S),O=o.tokensForCell(b,f,M.length);if(M){let H=0,L=0,V=R;const{actualBoundingBoxDescent:U}=e.measureText(M);for(;L<M.length;){const j=O[H],P=L===j?.start?j:null,Q=P?.end??j?.start??M.length,$=M.substring(L,Q),{width:J}=e.measureText($),A=$.endsWith("…")?e.measureText($.substring(0,$.length-1)).width:J;P!=null?(e.fillStyle=l.hyperlinkColor,e.fillText($,V,x),e.fillRect(V,x+U,A,1)):(e.fillStyle=y,e.fillText($,V,x)),V+=J,L=Q,P!=null&&(H+=1)}}e.restore()}g&&je(o)&&o.hasExpandableRows&&this.drawCellRowTreeMarker(e,t,s)}getTokenBoxesForVisibleCell(e,t,n){const{metrics:s,context:i,model:o,theme:l}=n;if(i==null||s==null)return ke;const{modelRows:a,modelColumns:d}=s,h=k(a,t),u=k(d,e),m=o.textForCell(u,h),{width:g,x:p,y:C}=_.getTextRenderMetrics(n,e,t),{fontWidths:f}=s;i.save(),this.configureContext(i,n);const b=f?.get(i.font)??Zs,w=o.truncationCharForCell(u,h),S=this.getCachedTruncatedString(i,m,g,b,w),{actualBoundingBoxAscent:T,actualBoundingBoxDescent:y}=i.measureText(S),E=T+y,R=o.tokensForCell(u,h,S.length);if(R.length===0)return i.restore(),ke;const x=this.getCachedTokenBoxesForVisibleCell(S,R,l.font,"middle",E,i).map(D=>({x1:D.x1+p,y1:D.y1+(C-T),x2:D.x2+p,y2:D.y2+(C-T),token:D.token}));return i.restore(),x}configureContext(e,t){const{theme:n}=t;e.font=n.font,e.textBaseline="middle",e.lineCap="butt"}getCachedTokenBoxesForVisibleCell=pn((e,t,n,s,i,o)=>{const a=i,d=[];let h=0,u=0;for(let m=0;m<t.length;m+=1){const g=t[m],{start:p,end:C}=g,f=C>e.length?e.substring(p):g.value;u+=o.measureText(e.substring(h,p)).width;const b=o.measureText(f).width,w=u,S=w+b,T={x1:w,y1:0,x2:S,y2:a,token:g};d.push(T),h=C,u+=b}return d},{max:1e4})}const pu=BS;class fs{static DEFAULT_EDGE_RADIUS=2;static ACTIVE_CELL_BORDER_WIDTH=2;textCellRenderer=new pu;dataBarCellRenderer=new gu;static truncate(e,t){return t<e.length?e.substr(0,t)+"…":e}static binaryTruncateToWidth(e,t,n,s=0,i=t.length,o){if(i>=t.length&&e.measureText(t).width<=n)return t;if(o!==void 0){const h=e.measureText(o).width;return o.repeat(Math.max(1,Math.floor(n/h)))}let l=s,a=Math.min(t.length-1,i),d=t;for(;a>=l;){const h=Math.ceil((a+l)/2),u=fs.truncate(t,h);if(e.measureText(u).width<=n){if(d=u,l===h)break;l=h}else if(h===0){d=u;break}else a=h-1}return d}static truncateToWidth(e,t,n,s=Zs,i){if(n<=0||t.length<=0)return"";const o=Math.min(Math.max(0,Math.floor(n/s/2)-5),t.length),l=Math.min(Math.ceil(n/s*2),t.length);return fs.binaryTruncateToWidth(e,t,n,o,l,i)}drawCanvas(e){const{context:t}=e;t.save(),this.configureContext(t,e),this.drawBackground(t,e),this.drawGrid(t,e),this.drawHeaders(t,e),this.drawFooters(t,e),this.drawDraggingColumn(t,e),this.drawDraggingRow(t,e),this.drawScrollBars(t,e),t.restore()}configureContext(e,t){const{theme:n}=t;e.font=n.font,e.textBaseline="middle",e.lineCap="butt"}drawBackground(e,t){const{theme:n,metrics:s}=t,{width:i,height:o}=s;e.fillStyle=n.backgroundColor,e.fillRect(0,0,i,o)}drawGrid(e,t){const{metrics:n,draggingRow:s,draggingColumn:i}=t,{gridX:o,gridY:l}=n;e.translate(o,l),this.drawGridBackground(e,t,s==null&&i==null),this.drawCellContents(e,t),this.drawFloatingRows(e,t),this.drawFloatingColumns(e,t),e.translate(-o,-l)}drawFloatingRows(e,t){const{draggingRow:n,draggingColumn:s,metrics:i,theme:o}=t,{floatingTopRowCount:l,floatingBottomRowCount:a,floatingRows:d,rowCount:h,visibleColumns:u,allRowYs:m,allRowHeights:g}=i;if(d.length!==0){o.floatingRowBackgroundColors&&this.drawRowStripesForRows(e,t,d,o.floatingRowBackgroundColors),n==null&&s==null&&this.drawFloatingMouseRowHover(e,t),this.drawGridLinesForItems(e,t,u,d,o.floatingGridColumnColor,o.floatingGridRowColor),this.drawCellBackgroundsForItems(e,t,u,d),this.drawFloatingBorders(e,t),l>0&&this.drawSelectedRanges(e,t,{top:0,bottom:l-1,maxY:k(m,l-1)+k(g,l-1)-.5}),a>0&&this.drawSelectedRanges(e,t,{top:h-a-1,bottom:h-1,minY:k(m,h-a)+.5,maxY:k(m,h-1)+k(g,h-1)-.5});for(let p=0;p<u.length;p+=1){const C=u[p];for(let f=0;f<d.length;f+=1){const b=d[f];this.drawCellContent(e,t,C,b)}}}}drawFloatingColumns(e,t){const{draggingRow:n,draggingColumn:s,metrics:i,theme:o}=t,{floatingLeftColumnCount:l,floatingRightColumnCount:a,floatingLeftWidth:d,floatingRightWidth:h,floatingColumns:u,gridX:m,maxX:g,columnCount:p,visibleRows:C,allColumnXs:f,allColumnWidths:b,width:w,height:S}=i;if(u.length!==0){o.floatingRowBackgroundColors&&(this.drawRowStripesForRows(e,t,C,o.floatingRowBackgroundColors,0,d),this.drawRowStripesForRows(e,t,C,o.floatingRowBackgroundColors,w-m-h,g)),n==null&&s==null&&this.drawFloatingMouseRowHover(e,t),e.save(),e.beginPath(),e.rect(0,0,d,S),e.clip(),this.drawGridLinesForItems(e,t,u,C,o.floatingGridColumnColor,o.floatingGridRowColor),e.restore(),this.drawCellBackgroundsForItems(e,t,u,C),this.drawFloatingBorders(e,t),l>0&&this.drawSelectedRanges(e,t,{left:0,maxX:k(f,l-1)+k(b,l-1)}),a>0&&this.drawSelectedRanges(e,t,{left:p-a,right:p-1,minX:k(f,p-a)+.5,maxX:k(f,p-1)+k(b,p-1)});for(let T=0;T<u.length;T+=1){const y=u[T];for(let E=0;E<C.length;E+=1){const R=C[E];this.drawCellContent(e,t,y,R)}}}}drawFloatingBorders(e,t){const{metrics:n,theme:s}=t,{floatingTopRowCount:i,floatingBottomRowCount:o,floatingLeftColumnCount:l,floatingRightColumnCount:a,rowCount:d,columnCount:h,allRowYs:u,allColumnXs:m,allRowHeights:g,allColumnWidths:p,maxX:C,maxY:f}=n,{floatingDividerOuterColor:b,floatingDividerInnerColor:w}=s;if(e.lineWidth=3,e.beginPath(),e.strokeStyle=b,i>0){const S=k(u,i-1)+k(g,i-1)+.5;e.moveTo(0,S),e.lineTo(C,S)}if(o>0){const S=k(u,d-o)-.5;e.moveTo(0,S),e.lineTo(C,S)}if(l>0){const S=k(m,l-1)+k(p,l-1)+.5;e.moveTo(S,0),e.lineTo(S,f)}if(a>0){const S=k(m,h-a)-.5;e.moveTo(S,0),e.lineTo(S,f)}if(e.stroke(),e.beginPath(),e.lineWidth=1,e.strokeStyle=w,i>0){const S=k(u,i-1)+k(g,i-1)+.5;e.moveTo(0,S),e.lineTo(C,S)}if(o>0){const S=k(u,d-o)-.5;e.moveTo(0,S),e.lineTo(C,S)}if(l>0){const S=k(m,l-1)+k(p,l-1)+.5;e.moveTo(S,0),e.lineTo(S,f)}if(a>0){const S=k(m,h-a)-.5;e.moveTo(S,0),e.lineTo(S,f)}e.stroke()}drawGridBackground(e,t,n=!1){this.drawRowStripes(e,t),n&&(this.drawMouseColumnHover(e,t),this.drawMouseRowHover(e,t)),this.drawGridLines(e,t),this.drawCellBackgrounds(e,t);const{metrics:s}=t,{bottom:i,right:o,floatingBottomRowCount:l,floatingLeftColumnCount:a,floatingRightColumnCount:d,floatingTopRowCount:h,columnCount:u,rowCount:m,allRowHeights:g,allRowYs:p,allColumnXs:C,allColumnWidths:f,width:b,height:w}=s;this.drawSelectedRanges(e,t,{bottom:Math.min(i,m-l-1),right:Math.min(o,u-d-1),minX:a>0&&C.has(a+1)?k(C,a+1):-10,minY:h>0&&p.has(h+1)?k(p,h+1):-10,maxX:d>0&&C.has(u-d-1)?k(C,u-d-1)+k(f,u-d-1)-.5:b+10,maxY:l>0&&p.has(m-l-1)?k(p,m-l-1)+k(g,m-l-1)-.5:w+10})}drawRowStripes(e,t){const{metrics:n,theme:s}=t,{visibleRows:i}=n,{rowBackgroundColors:o}=s;o&&this.drawRowStripesForRows(e,t,i,o)}drawRowStripesForRows(e,t,n,s,i=0,o=t.metrics.maxX){const{theme:l,metrics:a,model:d}=t,{maxDepth:h,shadowBlur:u,shadowColor:m}=l,g=this.getCachedBackgroundColors(s,h),{allRowYs:p,allRowHeights:C}=a,f=new Map,b=[],w=[],S=(T,y)=>{const E=je(d)?d.depthForRow(T):0,R=g[T%g.length],x=R[Math.min(E,R.length-1)];if(f.has(x)||f.set(x,[]),f.get(x).push(T),y!=null){const D=je(d)?d.depthForRow(y):0;D<E?b.push(T):D>E&&w.push(y)}};for(let T=0;T<n.length;T+=1){const y=n[T],E=T>0?n[T-1]:void 0;S(y,E)}if(f.forEach((T,y)=>{e.fillStyle=y,e.beginPath();for(let E=0;E<T.length;E+=1){const R=T[E],x=k(p,R),D=k(C,R);e.rect(i,x,o,D)}e.fill()}),b.length>0){e.save();const T=this.getCachedColorWithAlpha(m,.15),y=this.getCachedColorWithAlpha(m,0),E=e.createLinearGradient(0,0,0,u);E.addColorStop(0,T),E.addColorStop(1,y),e.fillStyle=E;for(let R=0;R<b.length;R+=1){const x=b[R],D=k(p,x);e.translate(0,D),e.fillRect(i,0,o,u),e.translate(0,-D)}e.restore()}if(w.length>0){e.save();const T=this.getCachedColorWithAlpha(m,0),y=this.getCachedColorWithAlpha(m,.15),E=e.createLinearGradient(0,0,0,u);E.addColorStop(0,T),E.addColorStop(1,y),e.fillStyle=E;for(let R=0;R<w.length;R+=1){const x=w[R],D=k(p,x),M=k(C,x),O=D+M-u;e.translate(0,O),e.fillRect(i,0,o,u),e.translate(0,-O)}e.restore()}}drawMouseColumnHover(e,t){const{mouseX:n,mouseY:s,theme:i,metrics:o}=t;if(n==null||s==null)return;const l=_.getColumnAtX(n,o);if(l==null||i.columnHoverBackgroundColor==null)return;const{allColumnWidths:a,allColumnXs:d,maxY:h}=o;if(s>h)return;const u=k(d,l),m=k(a,l);e.fillStyle=i.columnHoverBackgroundColor,e.fillRect(u,0,m,h)}drawMouseRowHover(e,t){const{mouseX:n,mouseY:s,theme:i,metrics:o}=t;if(n==null||s==null)return;const{maxX:l}=o;if(n>l||i.rowHoverBackgroundColor==null)return;const a=_.getRowAtY(s,o);a!=null&&this.drawMouseRowHoverForRow(e,t,a)}drawFloatingMouseRowHover(e,t){const{mouseX:n,mouseY:s,theme:i,metrics:o}=t,{maxX:l,floatingTopRowCount:a,floatingBottomRowCount:d,rowCount:h,rowFooterWidth:u}=o;if(n==null||s==null||n>l+u||i.rowHoverBackgroundColor==null)return;const m=_.getRowAtY(s,o);m!=null&&(m<a||h-d<=m)&&this.drawMouseRowHoverForRow(e,t,m)}drawMouseRowHoverForRow(e,t,n){const{metrics:s,selectedRanges:i,theme:o}=t,{allRowHeights:l,allRowYs:a,maxX:d}=s,h=k(a,n),u=k(l,n);o.rowHoverBackgroundColor!=null&&(e.fillStyle=o.rowHoverBackgroundColor);for(let m=0;m<i.length;m+=1){const{startRow:g,endRow:p}=i[m];if(g!=null&&p!=null&&g<=n&&p>=n){o.selectedRowHoverBackgroundColor!=null&&(e.fillStyle=o.selectedRowHoverBackgroundColor);break}}e.fillRect(0,h,d,u)}drawGridLines(e,t){const{metrics:n,theme:s}=t,{visibleColumns:i,visibleRows:o}=n;this.drawGridLinesForItems(e,t,i,o,s.gridColumnColor,s.gridRowColor)}drawGridLinesForItems(e,t,n,s,i,o){i==null&&o==null||(e.lineWidth=1,e.beginPath(),i!=null&&(e.strokeStyle=i,this.drawGridLinesForColumns(e,t,n)),o!=null&&(e.strokeStyle=o,this.drawGridLinesForRows(e,t,s)),e.stroke())}drawGridLinesForColumns(e,t,n){const{metrics:s}=t,{allColumnXs:i,maxY:o}=s;for(let l=0;l<n.length;l+=1){const a=n[l],d=k(i,a)+.5;e.moveTo(d,0),e.lineTo(d,o)}}drawGridLinesForRows(e,t,n){const{metrics:s}=t,{allRowYs:i,maxX:o}=s,l=o;for(let a=0;a<n.length;a+=1){const d=n[a],h=k(i,d)+.5;e.moveTo(.5,h),e.lineTo(l-.5,h)}}drawCellBackgrounds(e,t){const{metrics:n}=t,{visibleColumns:s,visibleRows:i}=n;this.drawCellBackgroundsForItems(e,t,s,i)}drawCellBackgroundsForItems(e,t,n,s){e.save();for(let i=0;i<n.length;i+=1){const o=n[i];for(let l=0;l<s.length;l+=1){const a=s[l],d=l+1<s.length?s[l+1]:void 0;this.drawCellBackground(e,t,o,a,d)}}e.restore()}drawCellBackground(e,t,n,s,i){const{metrics:o,model:l,theme:a}=t,{firstColumn:d,modelColumns:h,modelRows:u,allColumnXs:m,allColumnWidths:g,allRowYs:p,allRowHeights:C}=o,f=k(u,s),b=k(h,n),w=l.backgroundColorForCell(b,f,a),S=n===d,T=je(l)&&l.hasExpandableRows;if(w!=null){const y=k(m,n)+1,E=k(p,s)+1,R=k(g,n)-1,x=k(C,s)-1;e.fillStyle=w,e.fillRect(y,E,R,x)}S&&T&&this.drawCellRowTreeDepthLines(e,t,s,i)}drawCellContents(e,t){const{metrics:n}=t,{visibleColumns:s}=n;for(let i=0;i<s.length;i+=1){const o=s[i];this.drawColumnCellContents(e,t,o)}}drawColumnCellContents(e,t,n){const{metrics:s}=t,{allColumnXs:i,allColumnWidths:o,visibleRows:l,height:a}=s,d=k(i,n),h=k(o,n);e.save(),e.beginPath(),e.rect(d,0,h,a),e.clip();for(let u=0;u<l.length;u+=1){const m=l[u];this.drawCellContent(e,t,n,m)}e.restore()}drawCellContent(e,t,n,s){const{metrics:i,model:o}=t,{modelColumns:l,modelRows:a}=i,d=k(a,s),h=k(l,n),u=o.renderTypeForCell(h,d);this.getCellRenderer(u).drawCellContent(e,t,n,s)}getCellRenderer(e){switch(e){case"dataBar":return this.dataBarCellRenderer;default:return this.textCellRenderer}}drawCellRowTreeDepthLines(e,t,n,s){const{metrics:i,model:o,theme:l}=t;if(!je(o))return;const a=o.depthForRow(n);if(a===0)return;const{firstColumn:d,allColumnXs:h,allRowYs:u,allRowHeights:m}=i,{treeDepthIndent:g,treeHorizontalPadding:p,treeLineColor:C}=l,f=k(h,d),b=k(u,n),w=k(m,n),S=s!==void 0?o.depthForRow(s):0,T=a>S?a-S:0;if(e.strokeStyle=C,e.lineWidth=1,a-T>0){e.beginPath();for(let y=0;y<a-T;y+=1){const E=f+y*g+g*.5+p+.5;e.moveTo(E,b),e.lineTo(E,b+w)}e.stroke()}if(T>0){e.beginPath();for(let y=a-T;y<a;y+=1){const E=f+y*g+g*.5+p+.5;e.moveTo(E,b),e.lineTo(E,b+Math.ceil(w/2)),e.moveTo(E-.5,b+Math.ceil(w/2)+.5),e.lineTo(E+g-.5,b+Math.ceil(w/2)+.5)}e.stroke()}}getCachedBackgroundColors=pn((e,t)=>e.split(" ").map(n=>{const s=[];for(let i=0;i<t;i+=1)s.push(Bs.darkenForDepth(n,i,t));return s}),{max:1e3});getCachedColorWithAlpha=pn((e,t)=>Bs.colorWithAlpha(e,t),{max:1e3});getCachedColorIsDark=pn(e=>lh.isDark(e),{max:1e3});drawHeaders(e,t){const{theme:n}=t;e.font=n.headerFont,this.drawColumnHeaders(e,t),this.drawRowHeaders(e,t)}drawFooters(e,t){const{theme:n}=t;e.font=n.headerFont,this.drawRowFooters(e,t)}drawColumnHeaders(e,t){const{mouseX:n,mouseY:s,theme:i,metrics:o,draggingColumnSeparator:l,isDragging:a,model:d}=t,{columnHeaderHeight:h,floatingColumns:u,gridX:m,width:g,visibleColumns:p,allColumnWidths:C,allColumnXs:f,floatingLeftColumnCount:b,floatingLeftWidth:w,floatingRightWidth:S,modelColumns:T,columnHeaderMaxDepth:y}=o;if(h<=0)return;const{headerHiddenSeparatorSize:E,headerHiddenSeparatorHoverColor:R,headerSeparatorColor:x,headerSeparatorHoverColor:D}=i,M=h*.5,O=h*(y-1)+h*.5-M*.5,H=b>0;if(e.save(),this.drawColumnHeadersForRange(e,t,[p[0],p[p.length-1]],{minX:m+w,maxX:g-S}),H&&this.drawColumnHeadersForRange(e,t,[u[0],u[u.length-1]],{minX:m,maxX:m+w}),x){e.strokeStyle=x;const L=[...C.entries()].filter(([V,U])=>U===0).map(([V])=>V);e.beginPath(),e.fillStyle=x;for(let V=0;V<L.length;V+=1){const U=L[V],j=k(f,U),P=k(C,U),Q=m+j+P+.5-E*.5;e.rect(Q,O,E,M)}e.fill()}if(D){let{index:L,depth:V}=l??{};if(L==null&&n!=null&&s!=null){const j=uu.getColumnSeparator(_.getGridPointFromXY(n,s,o),o,d,i);L=j?.index,V=j?.depth}let U;if(L==null)U=!1;else{const j=T.get(L),P=T.get(L+1);j==null||P==null?U=!1:U=d.textForColumnHeader(j,V)!==d.textForColumnHeader(P,V)}if(U&&L!=null&&V!=null&&(!a||l!=null)){e.strokeStyle=D;const j=k(f,L),P=k(C,L),Q=m+j+P+.5,$=p.indexOf(L),J=$<p.length-1?p[$+1]:null,A=J!=null?C.get(J):null,W=P===0,q=A!=null&&A===0;W?(e.strokeStyle=R,e.fillStyle=R,e.fillRect(Q,O,E*.5,M)):q&&(e.fillStyle=D,e.fillRect(Q-E*.5,O,E*.5,M)),e.beginPath(),e.moveTo(Q,(y-V-1)*h),e.lineTo(Q,(y-V)*h-1),e.stroke()}}e.restore()}drawColumnHeadersForRange(e,t,n,s){const{model:i}=t,{columnHeaderMaxDepth:o}=i;if(o!==0)for(let l=0;l<=o;l+=1)this.drawColumnHeadersAtDepth(e,t,n,s,l)}drawColumnHeadersAtDepth(e,t,n,s,i){const{metrics:o,model:l,theme:a}=t,{modelColumns:d,allColumnXs:h,gridX:u,userColumnWidths:m,allColumnWidths:g,movedColumns:p}=o,{columnHeaderHeight:C,columnWidth:f}=a,{columnHeaderMaxDepth:b}=l,{minX:w,maxX:S}=s,T=S-w;if(b===0)return;const y=n[0],E=n[1];if(e.save(),e.translate(0,(b-i-1)*C),i===0){this.drawColumnHeader(e,t,"",w,S);for(let R=y;R<=E;R+=1)this.drawColumnHeaderAtIndex(e,t,R,s)}if(i>0){let R=y;for(;R<=E;){const{columnCount:x}=o,D=k(d,R),M=l.textForColumnHeader(D,i),O=l.colorForColumnHeader(D,i);let H=k(h,R)+u,L=H+k(g,R);if(M!=null){let V=R-1;for(;V>=0&&(L-H<T||H>w);){const Q=d.get(V)??_.getModelIndex(V,p);if(Q==null||l.textForColumnHeader(Q,i)!==M)break;const $=m.get(Q)??g.get(V)??f;H-=$,V-=1}let U=R+1;for(;U<x&&(L-H<T||L<S);){const Q=d.get(U)??_.getModelIndex(U,p);if(l.textForColumnHeader(Q,i)!==M)break;const $=m.get(Q)??g.get(U)??f;L+=$,U+=1}R=U-1;const j=L-H>=T;let P=H;j&&(L<S?P=L-T:H<w&&(P=w)),this.drawColumnHeader(e,t,M,P,Math.min(L-H,T),{backgroundColor:O??void 0},s)}R+=1}}e.restore()}drawColumnHeaderAtIndex(e,t,n,s){const{metrics:i,model:o}=t,{modelColumns:l,allColumnWidths:a,allColumnXs:d,gridX:h}=i,u=k(a,n),m=k(d,n)+h,g=k(l,n),p=o.textForColumnHeader(g);p!=null&&this.drawColumnHeader(e,t,p,m,u,{backgroundColor:o.colorForColumnHeader(g)??void 0},s)}drawColumnHeader(e,t,n,s,i,o,l){if(i<=0)return;const{metrics:a,theme:d}=t,{headerHorizontalPadding:h,columnHeaderHeight:u,headerBackgroundColor:m,headerColor:g,headerSeparatorColor:p,black:C,white:f}=d,{fontWidths:b,width:w}=a,S=b.get(e.font)??Zs,y=(i-h*2)/S,{backgroundColor:E=m,separatorColor:R=p}=o??{};let{textColor:x=g}=o??{};try{const W=this.getCachedColorIsDark(E),q=this.getCachedColorIsDark(x);W&&q?x=f:!W&&!q&&(x=C)}catch{}let{minX:D=0,maxX:M=w}=l??{};e.save(),e.rect(D,0,M-D,u),e.clip(),E!=null&&(e.fillStyle=E,e.fillRect(s,0,i,u)),R!=null&&(e.strokeStyle=R,e.beginPath(),s>0&&(e.moveTo(s+.5,0),e.lineTo(s+.5,u)),e.moveTo(s+i+.5,0),e.lineTo(s+i+.5,u),e.moveTo(s,u-.5),e.lineTo(s+i,u-.5),e.stroke()),e.beginPath(),e.rect(s,0,i,u),e.clip(),e.fillStyle=x;let O=n;y<=0?O="":O.length>y&&(O=`${O.substring(0,y-1)}…`);const H=O.length*S;let L=s+i*.5;const V=u*.5;D+=h,M-=h;const U=s+h,j=Oe(U,D,M),P=s+i-h,$=Oe(P,D,M)-j,J=L-H*.5<D,A=L+H*.5>M;J?H<$?L=D+H*.5:L=P-H*.5:A&&(H<$?L=M-H*.5:L=U+H*.5),e.textAlign="center",e.fillText(O,L,V),e.restore()}drawRowHeaders(e,t){const{mouseX:n,mouseY:s,metrics:i,theme:o,draggingRowSeparator:l}=t,{gridY:a,rowHeaderWidth:d,height:h,visibleRows:u,allRowHeights:m,allRowYs:g}=i;if(d<=0)return;const{headerBackgroundColor:p,headerColor:C,headerHiddenSeparatorSize:f,headerHiddenSeparatorHoverColor:b,headerSeparatorColor:w,headerSeparatorHoverColor:S}=o,T=d*.5,y=d*.5-T*.5;if(e.save(),e.beginPath(),e.fillStyle=p,e.fillRect(0,0,d,h),w){e.strokeStyle=w,e.beginPath(),e.moveTo(0,a+.5),e.lineTo(d,a+.5);const E=[];let R=!1;for(let x=0;x<u.length;x+=1){const D=u[x],M=k(g,D),O=k(m,D);if(O>0){const H=a+M+O+.5;e.moveTo(0,H),e.lineTo(d,H),R=!1}else R||(R=!0,E.push(D))}e.moveTo(d-.5,0),e.lineTo(d-.5,h),e.stroke(),e.beginPath(),e.fillStyle=w;for(let x=0;x<E.length;x+=1){const D=E[x],M=k(g,D),O=k(m,D),H=a+M+O+.5-f*.5;e.rect(y,H,T,f)}e.fill()}if(S){let{index:E=null}=l??{};if(E==null&&n!=null&&s!=null&&(E=_.getRowSeparatorIndex(n,s,i,o)),E!=null){e.strokeStyle=S;const R=k(g,E),x=k(m,E),D=a+R+x+.5,M=u.indexOf(E),O=M<u.length-1?u[M+1]:null,H=O!=null?m.get(O):null,L=x===0,V=H!=null&&H===0;L?(e.strokeStyle=b,e.fillStyle=b,e.fillRect(y,D,T,f*.5)):V&&(e.fillStyle=S,e.fillRect(y,D-f*.5,T,f*.5)),e.beginPath(),e.moveTo(.5,D),e.lineTo(d+.5,D),e.stroke()}}e.beginPath(),e.rect(0,a,d,h),e.clip(),e.fillStyle=C,e.textAlign="right";for(let E=0;E<u.length;E+=1){const R=u[E],x=k(m,R),D=k(g,R)+a;this.drawRowHeader(e,t,R,D,x)}e.restore()}drawRowHeader(e,t,n,s,i){if(i<=0)return;const{metrics:o,model:l,theme:a}=t,{modelRows:d,rowHeaderWidth:h}=o,u=k(d,n),m=h-a.cellHorizontalPadding,g=s+i*.5;e.fillText(l.textForRowHeader(u),m,g)}drawRowFooters(e,t){const{mouseX:n,mouseY:s,metrics:i,model:o,theme:l,draggingRowSeparator:a}=t,{gridY:d,gridX:h,maxX:u,modelRows:m,rowFooterWidth:g,height:p,verticalBarWidth:C,visibleRows:f,allRowHeights:b,allRowYs:w,width:S}=i;if(g<=0)return;const{cellHorizontalPadding:T,headerBackgroundColor:y,headerColor:E,headerHiddenSeparatorSize:R,headerHiddenSeparatorHoverColor:x,headerSeparatorColor:D,headerSeparatorHoverColor:M}=l,O=g*.5,H=g*.5-O*.5,L=Math.min(h+u,S-g-C);if(e.save(),e.beginPath(),e.fillStyle=y,e.fillRect(L,d,g,p),D){e.strokeStyle=D,e.beginPath(),e.moveTo(L,d+.5),e.lineTo(g,d+.5);const U=[];let j=!1;for(let P=0;P<f.length;P+=1){const Q=f[P],$=k(w,Q),J=k(b,Q);if(J>0){const A=d+$+J+.5;e.moveTo(L+.5,A),e.lineTo(L+g-.5,A),j=!1}else j||(j=!0,U.push(Q))}e.moveTo(L+.5,d),e.lineTo(L+.5,p),e.stroke(),e.beginPath(),e.fillStyle=D;for(let P=0;P<U.length;P+=1){const Q=U[P],$=k(w,Q),J=k(b,Q),A=d+$+J+.5-R*.5;e.rect(L+H,A,O,R)}e.fill()}if(M){let{index:U=null}=a??{};if(U==null&&n!=null&&s!=null&&(U=_.getRowSeparatorIndex(n,s,i,l)),U!=null){e.strokeStyle=M;const j=k(w,U),P=k(b,U),Q=d+j+P+.5,$=f.indexOf(U),J=$<f.length-1?f[$+1]:null,A=J!=null?b.get(J):null,W=P===0,q=A!=null&&A===0;W?(e.strokeStyle=x,e.fillStyle=x,e.fillRect(H,Q,O,R*.5)):q&&(e.fillStyle=M,e.fillRect(H,Q-R*.5,O,R*.5)),e.beginPath(),e.moveTo(L+.5,Q),e.lineTo(L+g+.5,Q),e.stroke()}}e.beginPath(),e.rect(L,d,g,p),e.clip(),e.fillStyle=E,e.textAlign="left";const V=L+T;for(let U=0;U<f.length;U+=1){const j=f[U],P=k(b,j);if(P>0){const Q=k(w,j)+d,$=k(m,j),J=Q+P*.5;e.fillText(o.textForRowFooter($),V,J)}}e.restore()}drawSelectedRanges(e,t,n={}){const{cursorColumn:s,cursorRow:i,draggingRow:o,draggingColumn:l,editingCell:a,metrics:d,model:h,selectedRanges:u,theme:m}=t,{allColumnWidths:g,allColumnXs:p,allRowHeights:C,allRowYs:f,width:b,height:w}=d,{left:S=d.left,top:T=d.top,right:y=d.right,bottom:E=d.bottom,minY:R=-10,maxY:x=w+10,minX:D=-10,maxX:M=b+10}=n;if(u.length===0)return;const O=Xe(h)&&h.isEditable&&a==null&&o==null&&l==null&&s!=null&&i!=null&&p.has(s)&&f.has(i);if(O){const H=k(p,s),L=k(f,i),V=k(g,s),U=k(C,i);e.save(),e.beginPath(),e.rect(0,0,b,w),e.rect(H,L,V,U),e.clip("evenodd")}e.beginPath();for(let H=0;H<u.length;H+=1){const L=u[H],V=L.startColumn!==null?L.startColumn:S,U=L.startRow!==null?L.startRow:T,j=L.endColumn!==null?L.endColumn:y,P=L.endRow!==null?L.endRow:E;if(P>=T&&E>=U&&j>=S&&y>=V){const Q=V>=S&&p.has(V)?Math.round(k(p,V))+.5:D,$=U>=T&&f.has(U)?Math.max(Math.round(k(f,U))+.5,.5):R,J=j<=y&&p.has(j)?Math.round(k(p,j)+k(g,j))-.5:M,A=P<=E&&f.has(P)?Math.round(k(f,P)+k(C,P))-.5:x;e.rect(Q,$,J-Q,A-$)}e.fillStyle=m.selectionColor,e.fill(),e.save(),e.clip(),e.strokeStyle=m.selectionOutlineCasingColor,e.lineWidth=3,e.stroke(),e.restore(),e.strokeStyle=m.selectionOutlineColor,e.lineWidth=1,e.stroke()}O&&s!=null&&i!=null&&(e.restore(),this.drawActiveCell(e,t,s,i))}drawActiveCell(e,t,n,s,i=fs.ACTIVE_CELL_BORDER_WIDTH){const{metrics:o,theme:l}=t,{allColumnWidths:a,allColumnXs:d,allRowHeights:h,allRowYs:u}=o,m=k(d,n),g=k(u,s),p=k(a,n),C=k(h,s);let f=m-i*.5,b=g-i*.5,w=p+i,S=C+i;f<=0&&(w+=f-1,f=1),b<=0&&(S+=b-1,b=1);const{lineWidth:T}=e;e.beginPath(),e.lineWidth=i,e.strokeStyle=l.selectionOutlineColor,this.drawRoundedRect(e,f,b,w,S),e.stroke(),e.lineWidth=T}drawRoundedRect(e,t,n,s,i,o=fs.DEFAULT_EDGE_RADIUS){e.beginPath(),e.moveTo(t+o,n),e.lineTo(t+s-o,n),e.quadraticCurveTo(t+s,n,t+s,n+o),e.lineTo(t+s,n+i-o),e.quadraticCurveTo(t+s,n+i,t+s-o,n+i),e.lineTo(t+o,n+i),e.quadraticCurveTo(t,n+i,t,n+i-o),e.lineTo(t,n+o),e.quadraticCurveTo(t,n,t+o,n),e.closePath()}drawDraggingColumn(e,t){const{draggingColumn:n,metrics:s,mouseX:i,theme:o,model:l}=t;if(n==null||i==null)return;const{range:a,depth:d}=n,{gridX:h,gridY:u,allColumnXs:m,allColumnWidths:g,height:p,width:C,columnHeaderMaxDepth:f,columnHeaderHeight:b,movedColumns:w,modelColumns:S,floatingLeftWidth:T}=s,y=S.get(a[0])??_.getModelIndex(a[0],w),E=l.getColumnHeaderGroup(y,d);if(d>0&&!E)return;const[R,x]=a,D=k(m,R),O=k(m,x)+k(g,x)-D,H=n.left,{backgroundColor:L,font:V,headerFont:U,reorderOffset:j,shadowBlur:P,shadowColor:Q}=o,$=(f-d-1)*b;e.save(),e.translate(h,0),e.save(),e.beginPath(),e.rect(T,0,C,p),e.clip(),e.fillStyle=L,e.fillRect(D,$,O,p),e.restore(),e.translate(0,j),e.save(),e.shadowColor=Q,e.shadowBlur=P,e.fillStyle=L,e.fillRect(n.left,$+j,n.width,p),e.restore(),e.beginPath(),e.rect(n.left,$,n.width+1,p),e.clip(),e.translate(H-D,0),e.font=U;const J=[];for(let A=n.range[0];A<=n.range[1];A+=1)J.push(A);this.drawColumnHeaders(e,t),this.drawColumnHeadersForRange(e,t,[J[0],J[J.length-1]],{minX:D,maxX:C}),e.translate(0,u),e.font=V,this.drawGridBackground(e,t);for(let A=R;A<=x;A+=1)this.drawColumnCellContents(e,t,A);e.restore()}drawDraggingRow(e,t){const{draggingRow:n,draggingRowOffset:s,metrics:i,mouseY:o,theme:l}=t;if(n==null||o==null)return;const{gridX:a,gridY:d,allRowYs:h,allRowHeights:u,width:m}=i,g=k(h,n),p=k(u,n)+1,{backgroundColor:C,font:f,headerFont:b,reorderOffset:w,shadowBlur:S,shadowColor:T}=l;e.save(),e.translate(0,d),e.fillStyle=C,e.fillRect(0,g,m,p),e.translate(a+w,o-g-d-(s??0)),e.save(),e.shadowColor=T,e.shadowBlur=S,e.fillStyle=C,e.fillRect(-a,g,m,p),e.restore(),e.beginPath(),e.rect(-a,g,m,p),e.clip(),e.font=f,this.drawGridBackground(e,t),this.drawCellContents(e,t),e.translate(-a,-d),e.font=b,this.drawRowHeaders(e,t),e.restore()}drawScrollBars(e,t){const{isDraggingHorizontalScrollBar:n,isDraggingVerticalScrollBar:s,isDragging:i,metrics:o,mouseX:l,mouseY:a,theme:d}=t;if(d.scrollBarSize<=0)return;const{width:h,height:u,handleHeight:m,handleWidth:g,scrollX:p,scrollY:C,hasHorizontalBar:f,hasVerticalBar:b,barWidth:w,barHeight:S,barLeft:T,barTop:y}=o,{scrollBarBackgroundColor:E,scrollBarHoverBackgroundColor:R,scrollBarCasingColor:x,scrollBarCornerColor:D,scrollBarColor:M,scrollBarHoverColor:O,scrollBarActiveColor:H,scrollBarSize:L,scrollBarHoverSize:V,scrollBarCasingWidth:U,scrollBarSelectionTick:j,scrollBarSelectionTickColor:P,scrollBarActiveSelectionTickColor:Q,autoSelectRow:$,autoSelectColumn:J}=d,A=l!=null&&a!=null&&l<=h&&a<=u,W=s||b&&!n&&!i&&l!=null&&a!=null&&l>=h-V&&a>=y&&A,q=n||f&&!s&&!i&&!W&&l!=null&&a!=null&&a>=u-V&&l>=T&&A,Z=q?V:L,le=W?V:L;if(e.translate(T,y),f&&b&&(e.fillStyle=x,e.fillRect(h-T-L,u-y-L,L,L),e.fillStyle=D,e.fillRect(h-T-L+U,u-y-L+U,L-U,L-U)),f){const G=p,oe=u-y-Z;if(e.fillStyle=x,e.fillRect(0,oe,w,Z-U),e.fillStyle=q?R:E,e.fillRect(0,oe+U,w,Z-U),n?e.fillStyle=H:q?e.fillStyle=O:e.fillStyle=M,e.fillRect(G,oe+U,g,Z-U),!$&&j&&P!=null&&Q!=null){e.fillStyle=P;const{selectedRanges:ue,cursorColumn:ae}=t,{lastLeft:he,columnCount:we}=o,Fe=[...ue].filter(De=>De.startColumn!=null&&De.endColumn!=null).map(De=>[De.startColumn,De.endColumn]).sort(_.compareRanges),mt=_.mergeSortedRanges(Fe),et=De=>De<=he?De/he*(w-g):w-g+(De-he)/(we-he)*g;for(let De=0;De<mt.length;De+=1){const gt=mt[De],lt=gt[0],vt=gt[1];if(lt!=null&&vt!=null&&(lt!==ae||vt!==ae)){const kt=et(lt),Cn=Math.max(1,Math.round(et(vt+1)-kt)),zt=Z-U;e.fillRect(kt,oe+U+Math.round(zt/3),Cn,Math.round(zt/3))}}if(ae!=null){const De=et(ae),gt=2,lt=Z-U;e.fillStyle=Q,e.fillRect(De,oe+U,gt,lt)}}}if(b){const G=h-T-le,oe=C;if(e.fillStyle=x,e.fillRect(G,0,le-U,S),e.fillStyle=W?R:E,e.fillRect(G+U,0,le-U,S),s?e.fillStyle=H:W?e.fillStyle=O:e.fillStyle=M,e.fillRect(G+U,oe,le-U,m),!J&&j&&P!=null&&Q!=null){const{selectedRanges:ue,cursorRow:ae}=t,{lastTop:he,rowCount:we}=o,He=De=>De<=he?De/he*(S-m):S-m+(De-he)/(we-he)*m;e.fillStyle=P;const mt=[...ue].filter(De=>De.startRow!=null&&De.endRow!=null).map(De=>[De.startRow,De.endRow]).sort(_.compareRanges),et=_.mergeSortedRanges(mt);for(let De=0;De<et.length;De+=1){const gt=et[De],lt=gt[0],vt=gt[1];if(lt!=null&&vt!=null&&(lt!==ae||vt!==ae)){const kt=He(lt),Cn=le-U,zt=Math.max(1,Math.round(He(vt+1)-kt));e.fillRect(G+U+Math.round(Cn/3),kt,Math.round(Cn/3),zt)}}if(ae!=null){const De=Math.round(He(ae)),gt=le-U,lt=2;e.fillStyle=Q,e.fillRect(G+U,De,gt,lt)}}}e.translate(-T,-y)}}const fu=fs,Zd=100;class US extends ht{startPoint;hasExtendedFloating=!1;timer;lastTriggerTime;dragBounds;onDown(e,t,n){const{x:s,y:i,column:o,row:l}=e,{metrics:a}=t;if(!a)throw new Error("metrics not set");const{gridX:d,gridY:h,maxX:u,maxY:m}=a,g=s-d,p=i-h;if(g<0||p<0||o==null&&g>u||l==null&&p>m)return!1;const C=_.isModifierKeyDown(n),f=n.shiftKey;C||(f?t.trimSelectedRanges():t.clearSelectedRanges());const b=t.getTheme(),{autoSelectRow:w,autoSelectColumn:S}=b;return(o!==null||!S)&&(l!==null||!w)&&(t.focus(),t.moveCursorToPosition(o,l,f,!1,f&&C)),this.startPoint=e,this.hasExtendedFloating=!1,this.dragBounds=_.getScrollDragBounds(a,l,o),!0}onDrag(e,t){if(this.startPoint===void 0)return!1;this.stopTimer();const{row:n,column:s}=this.startPoint,{x:i,y:o}=e;let{row:l,column:a}=e;const{metrics:d}=t;if(!d)throw new Error("metrics not set");const{left:h,lastLeft:u,top:m,lastTop:g,columnWidth:p,rowHeight:C}=d,f=_.getScrollDragBounds(d,n,s);let b=0,w=0;if(h<u&&(i<f.x1?b=i-f.x1:i>f.x2&&(b=i-f.x2)),m<g&&(o<f.y1?w=o-f.y1:o>f.y2&&(w=o-f.y2)),b!==0||w!==0)this.startTimer(t,e,b>0?Math.ceil(b/p):Math.floor(b/p),w>0?Math.ceil(w/C):Math.floor(w/C));else if(l!=null&&a!=null){const{floatingTopRowCount:S,floatingBottomRowCount:T,floatingLeftColumnCount:y,floatingRightColumnCount:E,columnCount:R,rowCount:x,bottom:D,right:M,topVisible:O,bottomVisible:H,leftVisible:L,rightVisible:V}=d;this.hasExtendedFloating||(n!==null&&n<S&&l>=S?(l=S,this.hasExtendedFloating=!0):n!==null&&n>=x-T&&l<x-T&&(l=x-T-1,this.hasExtendedFloating=!0),s!==null&&s<y&&a>=y?(a=y,this.hasExtendedFloating=!0):s!==null&&s>=R-E&&a<R-E&&(a=R-E-1,this.hasExtendedFloating=!0)),n!==null&&!_.isFloatingRow(n,d)&&_.isFloatingRow(l,d)&&(n>l&&l<m?l=O-1:n<l&&l>D&&(l=H+1)),s!==null&&!_.isFloatingColumn(s,d)&&_.isFloatingColumn(a,d)&&(s>a&&a<h?a=L-1:s<a&&a>M&&(a=V+1)),t.moveCursorToPosition(a,l,!0,!0)}return!0}onUp(e,t){return this.startPoint!==void 0&&(this.startPoint=void 0,this.dragBounds=void 0,this.stopTimer(),t.commitSelection()),!1}moveSelection(e,t,n,s){const{row:i,column:o}=t,{metrics:l}=e;if(!l)throw new Error("metrics not set");const{selectionEndRow:a,selectionEndColumn:d}=e.state;if(a==null||d==null)throw new Error("selection not set");const{rowCount:h,columnCount:u}=l,m=n<0&&o!=null?o:0,g=n>0&&o!=null?o:u-1,p=s<0&&i!=null?i:0,C=s>0&&i!=null?i:h-1;e.moveCursorToPosition(Math.min(Math.max(m,d+n),g),Math.min(Math.max(p,a+s),C),!0),this.lastTriggerTime=Date.now()}startTimer(e,t,n,s){this.stopTimer();const i=this.lastTriggerTime!=null?Zd-Math.min(Zd,Date.now()-this.lastTriggerTime):0;this.timer=setTimeout(()=>{this.moveSelection(e,t,n,s),this.startTimer(e,t,n,s)},i)}stopTimer(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}}const VS=US,Qd=5,$S=1e3/60,Vo=10;function is(c,e,t,n){const{modelColumns:s,movedColumns:i,allColumnXs:o,columnCount:l,allColumnWidths:a,userColumnWidths:d,calculatedColumnWidths:h,floatingLeftWidth:u,maxX:m}=t;if(e==null||c==null||c>l||c<0)return null;const g=s.get(c)??_.getModelIndex(c,i),p=n.getColumnHeaderGroup(g,e),C=p!=null;let f,b,w;if(p!=null){const[S,T]=p.getVisibleRange(i);f=o.get(S)??u,b=(o.get(T)??m)+(a.get(T)??0),w=[S,T]}else{const S=o.get(c);if(S==null)return null;f=S,b=f+(a.get(c)??d.get(g)??h.get(g)??0),w=[c,c]}return{visibleIndex:c,modelIndex:g,left:f,right:b,width:b-f,isColumnGroup:C,range:w,depth:e}}class WS extends ht{cursor=null;draggingOffset;initialOffset;initialGridPoint;scrollingInterval;scrollingDirection;draggingColumn=null;setScrollInterval(e,t){this.scrollingInterval!=null&&t===this.scrollingDirection||(this.scrollingDirection=t,this.scrollingInterval=window.setInterval(()=>{const{metrics:n}=e;if(!n)return;const{left:s,lastLeft:i,leftOffset:o,userColumnWidths:l,calculatedColumnWidths:a,movedColumns:d,allColumnWidths:h}=n;let u=s,m=o;if(t==="left")for(m-=Vo;m<0;){u-=1;const C=_.getModelIndex(s-1,d),f=l.get(C)??a.get(C);f===void 0?m=0:m+=f,u<0&&(m=0,u=0)}else{m+=Vo;let C=h.get(s);for(;C!==void 0&&m>C;){u+=1,m-=C;const f=_.getModelIndex(s+1,d);C=l.get(f)??a.get(f),u>i&&(m=0,u=i)}}const{mouseX:g,mouseY:p}=e.state;n==null||g==null||p==null||(this.moveDraggingColumn(g,e,t==="left"?-Vo:Vo),e.setState({left:u,leftOffset:m}),(t==="left"&&u===0&&o===0||t==="right"&&u===i)&&this.clearScrollInterval())},$S))}clearScrollInterval(){this.scrollingDirection=void 0,window.clearInterval(this.scrollingInterval),this.scrollingInterval=void 0}onLeave(){return this.clearScrollInterval(),!1}onDown(e,t){const{model:n}=t.props,{x:s,column:i,columnHeaderDepth:o}=e,{metrics:l}=t;if(!l)throw new Error("Metrics not set");const a=is(i,o,l,n);if(i==null||a==null||o==null||o>0&&!a.isColumnGroup)return!1;const{rowHeaderWidth:d}=l;return this.initialGridPoint=e,this.draggingColumn=null,this.cursor=null,a.modelIndex!=null&&o!=null&&n.isColumnMovable(a.modelIndex,o)&&(this.draggingOffset=s-a.left-d,this.initialOffset=this.draggingOffset),!1}onDrag(e,t,n){if(this.draggingOffset===void 0||this.initialGridPoint===void 0||this.initialOffset===void 0)return!1;const{x:s,y:i}=e,{columnHeaderDepth:o}=this.initialGridPoint,{model:l}=t.props;let{draggingColumn:a}=this;const{metrics:d}=t;if(!d)throw new Error("Metrics not set");if(!a&&Math.abs(this.initialGridPoint.x-s)<Qd&&Math.abs(this.initialGridPoint.y-i)<Qd)return!1;if(a==null){const h=is(this.initialGridPoint.column,o,d,l);if(!h||o==null||!l.isColumnMovable(h.modelIndex)||o>0&&!h.isColumnGroup||h.range[0]==null)return!1;a={range:h.range,depth:o,left:h.left,width:h.width};const u=is(a.range[0],0,d,l),m=is(a.range[1],0,d,l);if(!u||!m)return!1;this.draggingColumn=a,t.setState({draggingColumn:a,isDragging:!0})}return this.cursor="move",this.moveDraggingColumn(e.x,t,n.movementX),!0}moveDraggingColumn(e,t,n){if(this.draggingOffset===void 0||this.initialGridPoint===void 0||this.initialOffset===void 0||this.draggingColumn==null||n===0)return;if(this.initialOffset!==this.draggingOffset){this.draggingOffset<this.initialOffset&&this.initialOffset<this.draggingOffset+n||this.draggingOffset>this.initialOffset&&this.initialOffset>this.draggingOffset+n?this.draggingOffset=this.initialOffset:this.draggingOffset+=n,this.draggingColumn={...this.draggingColumn,left:e-this.draggingOffset},t.setState({draggingColumn:this.draggingColumn});return}const{depth:s}=this.draggingColumn,{model:i}=t.props,{movedColumns:o}=t.state,{metrics:l}=t;if(!l)throw new Error("Metrics not set");const{floatingLeftWidth:a,width:d,columnHeaderMaxDepth:h,allColumnXs:u}=l,m=n<0,g=is(this.draggingColumn.range[0],s,l,i);if(!g)return;const p=e-this.draggingOffset,C=p+g.width;this.draggingColumn={...this.draggingColumn,left:p},t.setState({draggingColumn:this.draggingColumn});const f=is(_.getColumnAtX(Oe(m?p:C,a,d),l,!0),s,l,i),b=i.getColumnHeaderParentGroup(g.modelIndex,g.depth);if(!f)return;if(b!==void 0){const R=b.getVisibleRange(o);if(f.visibleIndex<R[0]){const x=this.moveColumn(g,R[0],o);this.draggingOffset=e-(u.get(R[0])??0),this.draggingColumn={...this.draggingColumn,left:e-this.draggingOffset},this.clearScrollInterval(),t.setState({draggingColumn:this.draggingColumn,movedColumns:x});return}if(f.visibleIndex>R[1]){const x=this.moveColumn(g,R[1]-(g.range[1]-g.range[0]),o),{right:D=0}=is(R[1],0,l,i)??{};this.draggingOffset=e-(D-g.width),this.draggingColumn={...this.draggingColumn,left:e-this.draggingOffset},this.clearScrollInterval(),t.setState({draggingColumn:this.draggingColumn,movedColumns:x});return}}if(!i.isColumnMovable(f.modelIndex)){let R=f.visibleIndex;if(m)for(R+=1;R<g.visibleIndex&&!i.isColumnMovable(_.getModelIndex(R,o));)R+=1;else for(R-=1;R>g.visibleIndex&&!i.isColumnMovable(_.getModelIndex(R,o));)R-=1;if(R!==g.visibleIndex){m||(R-=g.range[1]-g.range[0]);const D=this.moveColumn(g,R,o);t.setState({movedColumns:D,draggingColumn:this.draggingColumn})}const x=is(R,0,l,i);m?this.draggingOffset=e-(x?.left??0):this.draggingOffset=e-((x?.right??0)-g.width),this.draggingColumn={...this.draggingColumn,left:e-this.draggingOffset},t.setState({draggingColumn:this.draggingColumn});return}if(p<=a?this.setScrollInterval(t,"left"):C>d?this.setScrollInterval(t,"right"):this.clearScrollInterval(),f.visibleIndex===g.visibleIndex||m&&g.visibleIndex<f.visibleIndex||!m&&g.visibleIndex>f.visibleIndex)return;const w=f.left+f.width*.5,S=i.getColumnHeaderParentGroup(g.modelIndex,g.depth);let T,y=(S?.depth??h)-1;for(;y>=0&&T===void 0;)T=i.getColumnHeaderGroup(f.modelIndex,y),y-=1;let E;m&&p<w&&(!T||f.visibleIndex===T.getVisibleRange(o)[0])&&(E=this.moveColumn(g,f.range[0],o)),!m&&C>w&&(!T||f.visibleIndex===T.getVisibleRange(o)[1])&&(E=this.moveColumn(g,f.range[1]-(g.range[1]-g.range[0]),o)),E&&(this.draggingColumn={...this.draggingColumn,left:p},t.setState({movedColumns:E,draggingColumn:this.draggingColumn}))}moveColumn(e,t,n){const s=e.isColumnGroup?_.moveRange(e.range,t,n):_.moveItem(e.visibleIndex,t,n),i=t-e.range[0],o=[e.range[0]+i,e.range[1]+i];return this.draggingColumn&&(this.draggingColumn={...this.draggingColumn,range:o}),s}onUp(e,t){return this.cursor=null,this.clearScrollInterval(),this.draggingOffset!=null?(this.draggingOffset=void 0,t.setState({draggingColumn:null,isDragging:!1}),!0):!1}}const GS=WS;class Lr extends ht{static getLeftWithOffsetFromRawLeft(e,t){const n=e.getTheme(),{metrics:s,metricCalculator:i}=e;if(!s)throw new Error("metrics not set");if(n.scrollSnapToColumn)return{left:Math.round(t),leftOffset:0};const o=Math.floor(t),l=t-o;let a=s.allColumnWidths.get(o);if(a==null){const h=e.getMetricState();a=i.getVisibleColumnWidth(o,h)}const d=a*l;return{left:o,leftOffset:d}}dragOffset;cursor="default";isInScrollBar(e,t){const n=t.getTheme(),{scrollBarSize:s,scrollBarHoverSize:i}=n,{metrics:o}=t;if(!o)throw new Error("metrics not set");const{x:l,y:a}=e,{barLeft:d,barWidth:h,height:u,hasHorizontalBar:m}=o;return m&&s>0&&a>=u-i&&a<u&&l>d&&l<d+h}getLeftWithOffset(e,t){const{metrics:n}=t;if(!n)throw new Error("metrics not set");const{x:s}=e,{barWidth:i,handleWidth:o,lastLeft:l,barLeft:a,columnCount:d,scrollableContentWidth:h,scrollableViewportWidth:u}=n,m=s-a,g=Oe((m-(this.dragOffset??0))/(i-o),0,1);if(d===1)return{left:0,leftOffset:g*(h-u)};const p=g*l;return Lr.getLeftWithOffsetFromRawLeft(t,p)}onDown(e,t){const{metrics:n}=t;if(!n)throw new Error("metrics not set");const{x:s}=e,{handleWidth:i,barLeft:o,scrollX:l}=n;if(!this.isInScrollBar(e,t))return!1;const a=s-o;if(a>=l&&a<=l+i)this.dragOffset=a-l,t.setState({isDraggingHorizontalScrollBar:!0});else{this.dragOffset=0;const{left:d,leftOffset:h}=this.getLeftWithOffset(e,t);t.setViewState({left:d,leftOffset:h,isDraggingHorizontalScrollBar:!0,isDragging:!0})}return!0}onDrag(e,t){if(this.dragOffset!=null){const{left:n,leftOffset:s}=this.getLeftWithOffset(e,t);return t.setViewState({left:n,leftOffset:s,isDraggingHorizontalScrollBar:!0,isDragging:!0}),!0}return!1}onMove(e,t){return this.isInScrollBar(e,t)}onUp(e,t){return this.dragOffset!==void 0&&(this.dragOffset=void 0,t.setState({isDraggingHorizontalScrollBar:!1,isDragging:!1})),this.isInScrollBar(e,t)}onClick(e,t){return this.isInScrollBar(e,t)}}const zS=Lr;class KS extends ht{cursor="move";draggingOffset;onDown(e,t){const{model:n}=t.props,{x:s,y:i,row:o}=e,{metrics:l}=t;if(!l)throw new Error("metrics not set");const{columnHeaderHeight:a,rowHeaderWidth:d,allRowYs:h}=l;if(s<=d&&o!==null&&n.isRowMovable(o)){const u=k(h,o);this.draggingOffset=i-u-a,t.setState({draggingRowOffset:this.draggingOffset})}return!1}onDrag(e,t){if(this.draggingOffset==null)return!1;const{model:n}=t.props;let{draggingRow:s}=t.state;const{mouseX:i,mouseY:o}=t.state;if(i==null||o==null)return!1;if(s==null){const{row:E}=t.getGridPointFromXY(i,o);if(E!=null&&!n.isRowMovable(E)||(s=E,t.setState({draggingRow:s,isDragging:!0}),s==null))return!1}const{metrics:l}=t;if(!l)throw new Error("metrics not set");const{top:a,lastTop:d,bottom:h,bottomVisible:u,rowCount:m,columnHeaderHeight:g,allRowHeights:p,allRowYs:C,height:f}=l;let b=g;if(a<s){const E=s-1;b=k(C,E)+k(p,E)*.5+g}let w=f;if(s<h){const E=s+1;w=k(C,E)+k(p,E)*.5+g}let{movedRows:S}=t.state;o<b&&s>0&&n.isRowMovable(s-1)?(S=_.moveItem(s,s-1,S),s-=1):w<o&&s<m-1&&n.isRowMovable(s+1)&&(S=_.moveItem(s,s+1,S),s+=1),t.setState({movedRows:S,draggingRow:s});const T=g+k(p,a)*.5,y=g+k(C,u)+k(p,u)*.5;return o<T&&a>0?t.setState({top:a-1}):o>y&&a<d&&t.setState({top:a+1}),!0}onUp(e,t){return this.draggingOffset!==void 0?(this.draggingOffset=void 0,t.setState({draggingRowOffset:null,draggingRow:null,isDragging:!1}),!0):!1}}const YS=KS;class Or extends hu{static getRowSeparator(e,t,n,s){if(!s.allowRowResize)return null;const{x:i,y:o}=e,l=_.getRowSeparatorIndex(i,o,t,s);return l!=null?{index:l,depth:0}:null}hiddenCursor="s-resize";defaultCursor="row-resize";pointProperty="y";userSizesProperty="userRowHeights";visibleOffsetProperty="visibleRowYs";visibleSizesProperty="visibleRowHeights";marginProperty="columnHeaderHeight";calculatedSizesProperty="calculatedRowHeights";initialSizesProperty="initialRowHeights";modelIndexesProperty="modelRows";firstIndexProperty="firstRow";treePaddingProperty="treePaddingY";getHiddenItems=_.getHiddenRows;getNextShownItem=_.getNextShownRow;setSize(e,t,n){e.setRowHeight(t,n)}resetSize(e,t){e.resetRowHeight(t)}updateSeparator(e,t){e.setState({draggingRowSeparator:t,isDragging:t!==null})}getSeparator=Or.getRowSeparator}const qS=Or;class vl extends ht{static isInTreeBox(e,t){const{column:n,row:s,x:i,y:o}=e,{metrics:l}=t;if(!l)throw new Error("metrics not set");const{gridX:a,gridY:d,firstColumn:h,allColumnXs:u,allColumnWidths:m,allRowHeights:g,allRowYs:p,visibleRowTreeBoxes:C}=l;if(n===h&&s!=null&&C.get(s)!=null&&i>a&&o>d){const f=k(u,n),b=k(m,n),w=k(p,s),S=k(g,s);if(i>=a+f&&i<=a+f+b&&o>=d+w&&o<=d+w+S)return!0}return!1}onDown(e,t){return vl.isInTreeBox(e,t)}onClick(e,t,n){if(vl.isInTreeBox(e,t)){const{row:s}=e;if(s!==null)return t.toggleRowExpanded(s,_.isModifierKeyDown(n)),!0}return!1}}const Xa=vl;class XS extends ht{isInCorner(e,t){const n=t.getTheme(),{scrollBarSize:s}=n,{metrics:i}=t;if(!i)throw new Error("metrics not set");const{x:o,y:l}=e,{width:a,height:d,hasVerticalBar:h,hasHorizontalBar:u}=i;return s>0&&h&&u&&o>=a-s&&l>=d-s&&o<=a&&l<=d}onDown(e,t){return this.isInCorner(e,t)}onUp(e,t){return this.isInCorner(e,t)}onClick(e,t){return this.isInCorner(e,t)}}const ZS=XS;class Ar extends ht{static getTopWithOffsetFromRawTop(e,t){const n=e.getTheme(),{metrics:s,metricCalculator:i}=e;if(!s)throw new Error("metrics not set");if(n.scrollSnapToRow)return{top:Math.round(t),topOffset:0};const o=Math.floor(t),l=t-o;let a=s.allRowHeights.get(o);if(a==null){const h=e.getMetricState();a=i.getVisibleRowHeight(o,h)}const d=a*l;return{top:o,topOffset:d}}dragOffset;cursor="default";isInScrollBar(e,t){const n=t.getTheme(),{scrollBarSize:s,scrollBarHoverSize:i}=n,{metrics:o}=t;if(!o)throw new Error("metrics not set");const{x:l,y:a}=e,{barTop:d,barHeight:h,width:u,hasVerticalBar:m}=o;return m&&s>0&&l>=u-i&&l<u&&a>d&&a<d+h}getTopWithOffset(e,t){const{metrics:n}=t;if(!n)throw new Error("metrics not set");const{y:s}=e,{barHeight:i,handleHeight:o,lastTop:l,barTop:a,rowCount:d,scrollableContentHeight:h,scrollableViewportHeight:u}=n,m=s-a,g=Oe((m-(this.dragOffset??0))/(i-o),0,1);if(d===1)return{top:0,topOffset:g*(h-u)};const p=g*l;return Ar.getTopWithOffsetFromRawTop(t,p)}onDown(e,t){const{metrics:n}=t;if(!n)throw new Error("metrics not set");const{y:s}=e,{handleHeight:i,barTop:o,scrollY:l}=n;if(!this.isInScrollBar(e,t))return!1;const a=s-o;if(a>=l&&a<=l+i)this.dragOffset=a-l,t.setState({isDraggingVerticalScrollBar:!0});else{this.dragOffset=0;const{top:d,topOffset:h}=this.getTopWithOffset(e,t);t.setViewState({top:d,topOffset:h,isDraggingVerticalScrollBar:!0,isDragging:!0})}return!0}onMove(e,t){return this.isInScrollBar(e,t)}onDrag(e,t){if(this.dragOffset!=null){const{top:n,topOffset:s}=this.getTopWithOffset(e,t);return t.setViewState({top:n,topOffset:s,isDraggingVerticalScrollBar:!0,isDragging:!0}),!0}return!1}onUp(e,t){return this.dragOffset!==void 0&&(this.dragOffset=void 0,t.setState({isDraggingVerticalScrollBar:!1,isDragging:!1})),this.isInScrollBar(e,t)}onClick(e,t){return this.isInScrollBar(e,t)}}const QS=Ar;class JS extends ht{onDoubleClick({column:e,row:t},n){const{model:s}=n.props;return Xe(s)&&e!=null&&t!=null&&s.isEditableRange(Ie.makeCell(e,t))?(n.startEditing(e,t),!0):!1}}const ew=JS;function Cu(c){return c?.getTokenBoxesForVisibleCell!==void 0}class _r extends ht{timeoutId;isHold=!1;isDown=!1;currentLinkBox;static HOLD_LENGTH=1e3;isHoveringLink(e,t){const{column:n,row:s,x:i,y:o}=e,{renderer:l,metrics:a,props:d}=t,{model:h}=d;if(n==null||s==null||a==null)return this.currentLinkBox=void 0,!1;const{modelRows:u,modelColumns:m}=a,g=k(u,s),p=k(m,n),C=h.renderTypeForCell(p,g),f=l.getCellRenderer(C);if(!Cu(f))return!1;if(this.currentLinkBox!=null){const{x1:S,y1:T,x2:y,y2:E}=this.currentLinkBox;if(i>=S&&i<=y&&o>=T&&o<=E)return!0}const b=t.updateRenderState(),w=f.getTokenBoxesForVisibleCell(n,s,b);for(let S=0;S<w.length;S+=1)if(wl(w[S].token)){const T=_.translateTokenBox(w[S],a),{x1:y,x2:E,y1:R,y2:x}=T;if(i>=y&&i<=E&&o>=R&&o<=x)return this.currentLinkBox=T,!0}return this.currentLinkBox=void 0,!1}setCursor(e,t){return this.isHoveringLink(e,t)?this.cursor="pointer":this.cursor=null,!1}onMove(e,t){return this.setCursor(e,t)}onDown(e,t,n){const s=this.isHoveringLink(e,t);return _.isModifierKeyDown(n)||n.shiftKey||!s?!1:(this.isDown=!0,this.timeoutId!=null&&clearTimeout(this.timeoutId),this.isHold=!1,this.timeoutId=setTimeout(()=>{this.isHold=!0;const{column:i,row:o}=e,{model:l}=t.props;t.clearSelectedRanges(),t.focus(),t.moveCursorToPosition(i,o),Xe(l)&&i!=null&&o!=null&&l.isEditableRange(Ie.makeCell(i,o))&&t.startEditing(i,o)},_r.HOLD_LENGTH),!0)}onClick(e,t){return!this.isHoveringLink(e,t)||!this.isDown||this.currentLinkBox==null?(this.isDown=!1,this.isHold=!1,!1):(this.isHold||(this.timeoutId!=null&&clearTimeout(this.timeoutId),this.timeoutId=void 0,t.props.onTokenClicked(this.currentLinkBox?.token)),this.isHold=!1,this.isDown=!1,!0)}}const tw=_r;class nw{order;constructor(e=5e3){this.order=e}onDown(e,t){return!1}}const ei=nw;class sw extends ei{onDown(e,t){switch(e.key){case"a":if(_.isModifierKeyDown(e))return t.selectAll(),!0;break;case"ArrowUp":return this.handleArrowMove(0,-1,e,t);case"ArrowDown":return this.handleArrowMove(0,1,e,t);case"ArrowRight":return this.handleArrowMove(1,0,e,t);case"ArrowLeft":return this.handleArrowMove(-1,0,e,t);case"k":case"K":return _.isModifierKeyDown(e)?!1:this.handlePageUp(e,t);case"j":case"J":return _.isModifierKeyDown(e)?!1:this.handlePageDown(e,t);case"h":case"H":return _.isModifierKeyDown(e)?!1:(e.shiftKey||t.clearSelectedRanges(),t.moveCursorToPosition(0,t.state.cursorRow,e.shiftKey),!0);case"l":case"L":{if(_.isModifierKeyDown(e))return!1;const{model:n}=t.props,{columnCount:s}=n;return e.shiftKey||t.clearSelectedRanges(),t.moveCursorToPosition(s-1,t.state.cursorRow,e.shiftKey),!0}case"PageDown":return this.handlePageDown(e,t);case"PageUp":return this.handlePageUp(e,t);case"Home":return e.shiftKey||t.clearSelectedRanges(),t.moveCursorToPosition(_.isModifierKeyDown(e)?t.state.cursorColumn:0,_.isModifierKeyDown(e)?0:t.state.cursorRow,e.shiftKey,!0,!0),!0;case"End":{const{model:n}=t.props,{columnCount:s,rowCount:i}=n;return e.shiftKey||t.clearSelectedRanges(),t.moveCursorToPosition(_.isModifierKeyDown(e)?t.state.cursorColumn:s-1,_.isModifierKeyDown(e)?i-1:t.state.cursorRow,e.shiftKey,!0,!0),!0}case"Escape":return t.clearSelectedRanges(),{preventDefault:!1,stopPropagation:!1};case"Enter":if(t.state.selectedRanges.length>0)return t.moveCursorInDirection(e.shiftKey?Ie.SELECTION_DIRECTION.UP:Ie.SELECTION_DIRECTION.DOWN),!0;break;case"Tab":if(t.state.selectedRanges.length>0)return t.moveCursorInDirection(e.shiftKey?Ie.SELECTION_DIRECTION.LEFT:Ie.SELECTION_DIRECTION.RIGHT),!0;break}return!1}handleArrowMove(e,t,n,s){const i=n.shiftKey,o=_.isModifierKeyDown(n);i?s.trimSelectedRanges():s.clearSelectedRanges();const{cursorRow:l,cursorColumn:a,selectionEndColumn:d,selectionEndRow:h}=s.state,u=i?d:a,m=i?h:l;if(o){const{model:g}=s.props,{columnCount:p,rowCount:C}=g,f=o&&i;let b=null,w=null;e<0?(b=0,w=m):e>0?(b=p-1,w=m):t<0?(b=u,w=0):t>0&&(b=u,w=C-1),b!=null&&w!=null&&s.moveCursorToPosition(b,w,i,!0,f)}else{if(!s.metrics)throw new Error("grid.metrics are not set");const{theme:g}=s.props,{autoSelectRow:p=!1,autoSelectColumn:C=!1}=g;if(p&&e!==0){const{lastLeft:f}=s.metrics;let{left:b}=s.state;b=Oe(b+e,0,f),s.moveCursorToPosition(b,l,i,!1),s.setViewState({left:b})}else if(C&&t!==0){const{lastTop:f}=s.metrics;let{top:b}=s.state;b=Oe(b+t,0,f),s.moveCursorToPosition(b,a,i,!1),s.setViewState({top:b})}else s.moveCursor(e,t,i)}return!0}handlePageUp(e,t){const n=e.shiftKey;n?t.trimSelectedRanges():t.clearSelectedRanges();const{cursorColumn:s,selectionEndRow:i}=t.state,o=i,l=s;if(o==null)return!1;const a=t.getMetricState(),{metricCalculator:d}=t,{bottomVisible:h,topVisible:u,hasHorizontalBar:m}=d.getMetrics(a);let g=o-(h-u);g-=m?0:1,g=Math.max(g,0);const p=Math.max(g-(o-u),0);return t.moveCursorToPosition(l,g,n,!1),t.setViewState({top:p}),!0}handlePageDown(e,t){const n=e.shiftKey;n?t.trimSelectedRanges():t.clearSelectedRanges();const{selectionEndRow:s,cursorColumn:i}=t.state,o=s,l=i;if(o===null)return!1;const a=t.getMetricState(),{metricCalculator:d}=t,{bottomVisible:h,topVisible:u,hasHorizontalBar:m,rowCount:g,lastTop:p}=d.getMetrics(a),C=g-1;let f=h-u+o;f+=m?0:1,f=Math.min(f,C);const b=Math.min(p,f-(o-u));return t.moveCursorToPosition(l,f,n,!1),t.setViewState({top:b}),!0}}const iw=sw;class ow extends ei{onDown(e,t){switch(e.key){case"Enter":case" ":return this.handleExpandKey(e,t)}return!1}handleExpandKey(e,t){const{selectedRanges:n}=t.state;if(n.length===1){const s=n[0];if(s.startRow===s.endRow&&s.startColumn===s.endColumn){if(!t.metrics)throw new Error("grid.metrics not set");const{model:i}=t.props,{startRow:o,startColumn:l}=s;if(o!=null){const a=t.getModelRow(o);if((l===0||l==null)&&je(i)&&i.isRowExpandable(a))return t.toggleRowExpanded(o),!0}}}return!1}}const lw=ow;class aw extends ei{onDown(e,t){if(_.isModifierKeyDown(e))return!1;const{model:n}=t.props,{cursorColumn:s,cursorRow:i}=t.state;if(s==null||i==null||!Xe(n)||!n.isEditableRange(Ie.makeCell(s,i)))return!1;const o=s,l=i;return o==null||l==null?!1:e.key.length===1?(t.startEditing(o,l,!0,[1,1],e.key),!0):e.key==="F2"?(t.startEditing(o,l),!0):e.key==="Backspace"?(t.startEditing(o,l,!0,void 0,""),!0):e.key==="Delete"?(t.setValueForCell(o,l,""),!0):!1}}const rw=aw;function dw(c){const e=[],t=c.querySelectorAll("tr");for(let n=0;n<t.length;n+=1){const i=t[n].querySelectorAll("td"),o=[];for(let l=0;l<i.length;l+=1){const a=i[l];o.push(a.textContent?.trim()??"")}e.push(o)}return e}function cw(c){const e=[];return c.forEach(t=>{const n=t.textContent??"";n.length>0&&e.push(n.split(/\t|\u00a0\u00a0 \u00a0/))}),e}function hw(c){const e=c.querySelector("table");if(e!=null)return dw(e);const t=c.textContent?.trim()??"";if(t.length>0){const{childNodes:n}=c,s=t.includes(" "),i=t.includes("    ");return s&&n.length!==0&&(n.length===1||n.length>1&&(n[0].textContent==null||!n[0].textContent.includes(" ")))?t.split(`
19
19
  `).map(o=>o.split(" ")):n.length>1||i?cw(c.childNodes):t}return null}class uw extends ei{onDown(e,t){switch(e.key){case"v":if(_.isModifierKeyDown(e)){const n=document.createElement("div");document.body.appendChild(n),n.setAttribute("contenteditable","true"),n.setAttribute("style",'clip-path: "inset(50%)"; height: 1px; width: 1px; margin: -1px; overflow: hidden; padding 0; position: absolute;');const s=()=>{n.removeEventListener("input",s),n.remove(),t.focus();const i=hw(n);i!=null&&t.pasteValue(i)};return n.addEventListener("input",s),n.focus(),{preventDefault:!1,stopPropagation:!0}}break}return!1}}const mw=uw;const gw=c=>{switch(c){case"ArrowDown":return mn.DOWN;case"ArrowUp":return mn.UP;case"ArrowLeft":return mn.LEFT;case"ArrowRight":return mn.RIGHT;default:return}};function Pr({selectionRange:c=void 0,className:e="",disabled:t=!1,value:n="",isQuickEdit:s=!0,onChange:i=()=>{},onCancel:o=()=>{},onDone:l=()=>{},onContextMenu:a=()=>{},style:d={}}){const h=v.useRef(null),u=v.useRef(!1),[m]=v.useState(n),[g,p]=v.useState(!1),[C,f]=v.useState(s),[b,w]=v.useState(n);v.useEffect(function(){const{current:H}=h;H!=null&&(H.focus(),c?H.setSelectionRange(c[0],c[1]):H.setSelectionRange(H.value.length,H.value.length))},[c]);const S=v.useCallback(O=>{i(O)},[i]),T=v.useCallback(O=>{const{value:H}=O.target;w(H),p(!0),S(H)},[S,w,p]),y=v.useCallback(()=>{u.current=!0,g&&S(m),p(!1),o()},[m,g,o,S]),E=v.useCallback(()=>{f(!1)},[f]),R=v.useCallback((O,H=!1)=>{l(b,{direction:O,fillRange:H})},[l,b]),x=v.useCallback(()=>{u.current||R(null)},[u,R]),D=v.useCallback(O=>{switch(O.stopPropagation(),O.key){case"Escape":O.preventDefault(),y();break;case"Enter":if(O.preventDefault(),_.isModifierKeyDown(O))R(void 0,!0);else if(O.altKey){const H=`${b}
20
- `;w(H),p(!0),S(H)}else R(O.shiftKey?mn.UP:mn.DOWN);break;case"Tab":O.preventDefault(),R(O.shiftKey?mn.LEFT:mn.RIGHT);break;case"ArrowDown":case"ArrowUp":case"ArrowLeft":case"ArrowRight":C&&(O.preventDefault(),R(gw(O.key)));break}},[y,R,C,w,p,S,b]),M=v.useCallback(O=>{a(O)},[a]);return r.jsx("textarea",{ref:h,className:Y("grid-cell-input-field",e),value:b,onBlur:x,onChange:T,onKeyDown:D,onContextMenu:M,onClick:E,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false",disabled:t,style:d})}Pr.propTypes={selectionRange:z.arrayOf(z.number),className:z.string,disabled:z.bool,isQuickEdit:z.bool,value:z.string,onChange:z.func,onCancel:z.func,onDone:z.func,onContextMenu:z.func,style:z.shape({})};Pr.defaultProps={selectionRange:null,className:"",disabled:!1,value:"",isQuickEdit:!0,onChange:()=>{},onCancel:()=>{},onDone:()=>{},onContextMenu:()=>{},style:{}};const pw=de.createContext({}),fw=pw;class hs extends v.PureComponent{static contextType=fw;static defaultProps={canvasOptions:{alpha:!1},isStickyBottom:!1,isStickyRight:!1,isStuckToBottom:!1,isStuckToRight:!1,keyHandlers:ke,mouseHandlers:ke,movedColumns:ke,movedRows:ke,onError:()=>{},onSelectionChanged:()=>{},onMovedColumnsChanged:e=>{},onMoveColumnComplete:()=>{},onMovedRowsChanged:()=>{},onMoveRowComplete:()=>{},onViewChanged:()=>{},onTokenClicked:e=>{wl(e)&&window.open(e.href,"_blank","noopener,noreferrer")},stateOverride:{},theme:{autoSelectColumn:!1,autoSelectRow:!1}};static pixelsPerLine=100/3;static dragTimeout=1e3;static getTheme=ge((e,t)=>({...IS,...e,...t}));static getScale(e){const t=window.devicePixelRatio||1,n=e,s=n.webkitBackingStorePixelRatio??n.mozBackingStorePixelRatio??n.msBackingStorePixelRatio??n.oBackingStorePixelRatio??n.backingStorePixelRatio??1;return t/s}static getCursorClassName(e){return e!=null&&e!==""?`grid-cursor-${e}`:null}renderer;metricCalculator;canvas;canvasContext;animationFrame;prevMetrics;metrics;renderState;documentCursor;dragTimer;keyHandlers;mouseHandlers;constructor(e){super(e),this.handleClick=this.handleClick.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.handleEditCellCancel=this.handleEditCellCancel.bind(this),this.handleEditCellChange=this.handleEditCellChange.bind(this),this.handleEditCellCommit=this.handleEditCellCommit.bind(this),this.handleDoubleClick=this.handleDoubleClick.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseDrag=this.handleMouseDrag.bind(this),this.handleMouseMove=this.handleMouseMove.bind(this),this.handleMouseLeave=this.handleMouseLeave.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this),this.handleResize=this.handleResize.bind(this),this.handleWheel=this.handleWheel.bind(this);const{isStuckToBottom:t,isStuckToRight:n,metricCalculator:s,movedColumns:i,movedRows:o,renderer:l}=e;this.renderer=l||new fu,this.metricCalculator=s||new xS,this.canvas=null,this.canvasContext=null,this.animationFrame=null,this.prevMetrics=null,this.metrics=null,this.renderState={},this.documentCursor=null,this.dragTimer=null,this.keyHandlers=[new rw(400),new mw(450),new iw(500),new lw(900)],this.mouseHandlers=[new qS(100),new uu(200),new YS(300),new GS(400),new ew(450),new QS(500),new zS(600),new ZS(700),new Xa(800),new tw(825),new VS(900)],this.state={top:0,left:0,topOffset:0,leftOffset:0,draggingColumn:null,draggingRow:null,draggingRowOffset:null,draggingColumnSeparator:null,draggingRowSeparator:null,isDraggingHorizontalScrollBar:!1,isDraggingVerticalScrollBar:!1,isDragging:!1,mouseX:null,mouseY:null,movedColumns:i,movedRows:o,cursorRow:null,cursorColumn:null,selectionStartRow:null,selectionStartColumn:null,selectionEndRow:null,selectionEndColumn:null,selectedRanges:ke,lastSelectedRanges:ke,cursor:null,editingCell:null,isStuckToBottom:t,isStuckToRight:n}}componentDidMount(){this.initContext(),this.canvas?.addEventListener("wheel",this.handleWheel,{passive:!1}),window.addEventListener("resize",this.handleResize),this.updateCanvas();const{isStuckToBottom:e,isStuckToRight:t}=this.props;e&&this.scrollToBottom(),t&&this.scrollToRight()}componentDidUpdate(e,t){const{isStickyBottom:n,isStickyRight:s,movedColumns:i,movedRows:o,onMovedColumnsChanged:l,onMoveColumnComplete:a,onMovedRowsChanged:d,onMoveRowComplete:h}=this.props,{isStickyBottom:u,isStickyRight:m,movedColumns:g,movedRows:p}=e,{movedColumns:C,movedRows:f}=t,{draggingColumn:b,draggingRow:w,movedColumns:S,movedRows:T}=this.state;g!==i&&this.setState({movedColumns:i}),p!==o&&this.setState({movedRows:o}),C!==S&&l(S),t.draggingColumn!=null&&b==null&&a(S),f!==T&&d(T),t.draggingRow!=null&&w==null&&h(T),n!==u&&this.setState({isStuckToBottom:!1}),s!==m&&this.setState({isStuckToRight:!1}),this.updateMetrics(),this.requestUpdateCanvas(),this.checkStickyScroll(),this.validateSelection()&&this.checkSelectionChange(t)}componentWillUnmount(){this.animationFrame!=null&&cancelAnimationFrame(this.animationFrame),this.canvas?.removeEventListener("wheel",this.handleWheel),window.removeEventListener("mousemove",this.handleMouseDrag,!0),window.removeEventListener("mouseup",this.handleMouseUp,!0),window.removeEventListener("resize",this.handleResize),this.stopDragTimer()}getTheme(){const{theme:e}=this.props;return hs.getTheme(this.context,e)}getGridPointFromEvent(e){Kd(this.canvas);const t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left,s=e.clientY-t.top;return this.getGridPointFromXY(n,s)}getGridPointFromXY(e,t){if(!this.metrics)throw new Error("metrics must be set");return _.getGridPointFromXY(e,t,this.metrics)}getMetricState(e=this.state){const t=this.getTheme(),{model:n,stateOverride:s}=this.props;if(!this.canvasContext||!this.canvas)throw new Error("Canvas and context must be defined to get metrics");const i=this.canvasContext,o=this.canvas.clientWidth,l=this.canvas.clientHeight,{left:a,top:d,leftOffset:h,topOffset:u,movedColumns:m,movedRows:g,isDraggingHorizontalScrollBar:p,isDraggingVerticalScrollBar:C,draggingColumn:f}=e;return{left:a,top:d,leftOffset:h,topOffset:u,width:o,height:l,context:i,theme:t,model:n,movedColumns:m,movedRows:g,isDraggingHorizontalScrollBar:p,isDraggingVerticalScrollBar:C,draggingColumn:f,...s}}getCachedKeyHandlers=ge(e=>[...e,...this.keyHandlers].sort((t,n)=>t.order-n.order));getKeyHandlers(){const{keyHandlers:e}=this.props;return this.getCachedKeyHandlers(e)}getCachedMouseHandlers=ge(e=>[...e,...this.mouseHandlers].sort((t,n)=>t.order-n.order));getMouseHandlers(){const{mouseHandlers:e}=this.props;return this.getCachedMouseHandlers(e)}getModelColumn(e){const t=this.metrics?.modelColumns?.get(e);if(t===void 0)throw new Error(`Unable to get ModelIndex for column ${e}`);return t}getModelRow(e){const t=this.metrics?.modelRows?.get(e);if(t===void 0)throw new Error(`Unable to get ModelIndex for row ${e}`);return t}toggleRowExpanded(e,t=!1){const n=this.getModelRow(e),{model:s}=this.props;je(s)&&s.isRowExpandable(n)&&s.setRowExpanded(n,!s.isRowExpanded(n),t),this.clearSelectedRanges(),this.commitSelection(),this.moveCursorToPosition(0,e),this.commitSelection(),this.setState({isStuckToBottom:!1})}scrollToBottom(){if(!this.metrics)return;const{bottomVisible:e,rowCount:t,top:n,lastTop:s}=this.metrics;(e<t-1&&e>0||n>s)&&this.setState({top:s})}scrollToRight(){if(!this.metrics)return;const{rightVisible:e,columnCount:t,left:n,lastLeft:s}=this.metrics;(e<t-1&&e>0||n>s)&&this.setState({left:s})}setSelectedRanges(e){const{model:t}=this.props,{columnCount:n,rowCount:s}=t,{cursorRow:i,cursorColumn:o,selectedRanges:l}=this.state;if(this.setState({selectedRanges:e,lastSelectedRanges:l}),e.length>0){const a=Ie.boundedRange(e[0],n,s);let d=i,h=o;a.containsCell(o,i)||({row:d,column:h}=a.startCell()),this.setState({selectionStartColumn:a.startColumn,selectionStartRow:a.startRow,selectionEndColumn:a.endColumn,selectionEndRow:a.endRow,cursorColumn:h,cursorRow:d})}}initContext(){const{canvas:e}=this,{canvasOptions:t}=this.props;if(!e)throw new Error("Canvas not set");this.canvasContext=e.getContext("2d",t)}requestUpdateCanvas(){this.animationFrame==null&&(this.animationFrame=requestAnimationFrame(()=>{this.animationFrame=null,this.updateCanvas()}))}updateCanvas(){this.updateCanvasScale(),this.updateMetrics(),this.updateRenderState();const{canvasContext:e,metrics:t,renderState:n}=this;N(e),N(t),N(n),this.renderer.configureContext(e,n);const{onViewChanged:s}=this.props;s(t),this.drawCanvas(t)}updateCanvasScale(){const{canvas:e,canvasContext:t}=this;if(!e)throw new Error("canvas not set");if(!t)throw new Error("canvasContext not set");if(!e.parentElement)throw new Error("Canvas has no parent element");const n=hs.getScale(t),s=e.parentElement.getBoundingClientRect(),i=Math.floor(s.width),o=Math.floor(s.height);e.style.width=`${i}px`,e.style.height=`${o}px`,e.width=i*n,e.height=o*n,t.scale(n,n)}updateScrollBounds(){if(!this.metrics)throw new Error("metrics not set");const{left:e,top:t}=this.state,{lastLeft:n,lastTop:s}=this.metrics;e>n&&this.setState({left:n,leftOffset:0}),t>s&&this.setState({top:s,topOffset:0})}checkStickyScroll(){if(this.metrics){if(this.prevMetrics){const{rowCount:e,columnCount:t,height:n,width:s}=this.metrics,{rowCount:i,columnCount:o,height:l,width:a}=this.prevMetrics;if(i!==e||n!==l){const{isStuckToBottom:d}=this.state;d&&this.scrollToBottom()}if(o!==t||s!==a){const{isStuckToRight:d}=this.state;d&&this.scrollToRight()}}this.prevMetrics=this.metrics}}updateMetrics(e=this.state){this.prevMetrics=this.metrics;const{metricCalculator:t}=this,n=this.getMetricState(e);return this.metrics=t.getMetrics(n),this.updateScrollBounds(),this.metrics}checkSelectionChange(e){const{selectedRanges:t}=e,{selectedRanges:n}=this.state;if(n!==t){const{onSelectionChanged:s}=this.props;s(n)}}validateSelection(){const{model:e}=this.props,{selectedRanges:t}=this.state,{columnCount:n,rowCount:s}=e;for(let i=0;i<t.length;i+=1){const o=t[i];if(o.endColumn!=null&&o.endColumn>=n||o.endRow!=null&&o.endRow>=s)return this.setState({selectedRanges:[],lastSelectedRanges:[]}),!1}return!0}clearSelectedRanges(){const{selectedRanges:e}=this.state;this.setState({selectedRanges:[],lastSelectedRanges:e})}trimSelectedRanges(){const{selectedRanges:e}=this.state;e.length>0&&this.setState({selectedRanges:e.slice(e.length-1)})}beginSelection(e,t){this.setState({selectionStartColumn:e,selectionStartRow:t,selectionEndColumn:e,selectionEndRow:t,cursorColumn:e,cursorRow:t})}moveSelection(e,t,n=!1,s=!1){this.setState(i=>{const{selectedRanges:o,selectionStartRow:l,selectionStartColumn:a}=i,{theme:d}=this.props,{autoSelectRow:h,autoSelectColumn:u}=d;if(n&&o.length>0){const C=o[o.length-1];let f=null,b=null,w=null,S=null;s?(f=h!==void 0&&h?null:Math.min(e??0,C.startColumn??0),b=u!==void 0&&u?null:Math.min(t??0,C.startRow??0),w=h!==void 0&&h?null:Math.max(e??0,C.endColumn??0),S=u!==void 0&&u?null:Math.max(t??0,C.endRow??0)):(f=C.startColumn,b=C.startRow,(a!=null||l!=null)&&((h===void 0||!h)&&(f=a),(u===void 0||!u)&&(b=l)),w=h!==void 0&&h?null:e,S=u!==void 0&&u?null:t);const T=Ie.makeNormalized(f,b,w,S);if(C.equals(T))return null;const y=[...o];return y[y.length-1]=T,{selectedRanges:y,selectionEndColumn:e,selectionEndRow:t}}const m=[...o],g=h!==void 0&&h?null:e,p=u!==void 0&&u?null:t;return m.push(Ie.makeNormalized(g,p,g,p)),{selectedRanges:m,selectionEndColumn:e,selectionEndRow:t}})}commitSelection(){this.setState(e=>{const{theme:t}=this.props,{autoSelectRow:n}=t,{selectedRanges:s,lastSelectedRanges:i,cursorRow:o,cursorColumn:l}=e;if(s.length===1&&(n!==void 0&&n?Ie.rowCount(s)===1:Ie.cellCount(s)===1)&&Ie.rangeArraysEqual(s,i))return{selectedRanges:[],lastSelectedRanges:[],cursorColumn:null,cursorRow:null};let a=s.slice();if(a.length>1){const u=a[a.length-1];for(let m=0;m<a.length-1;m+=1){const g=a[m];if(g.contains(u)){const p=g.subtract(u);a.pop(),a.splice(m,1),a=a.concat(p);break}}a=Ie.consolidate(a)}let d=l,h=o;if(!Ie.containsCell(a,l,o)){const{model:u}=this.props,{columnCount:m,rowCount:g}=u,p=Ie.nextCell(Ie.boundedRanges(s,m,g));p!=null?{column:d,row:h}=p:(d=null,h=null)}return a.length===0&&(d=null,h=null),{cursorRow:h,cursorColumn:d,selectedRanges:a,lastSelectedRanges:s}})}setFocusRow(e){if(!this.metrics||!this.prevMetrics)return;const{gridY:t,height:n,lastTop:s,userRowHeights:i,rowHeight:o}=this.metrics,l=n-t,a=Math.round(l/2)+(i.get(e)??o),d=this.getMetricState(),h=this.metricCalculator.getLastTop(d,e+1,a);this.setState({top:Math.min(s,h),selectedRanges:[new Ie(null,e,null,e)],isStuckToBottom:!1});const{cursorColumn:u}=this.state;this.moveCursorToPosition(u,e,!1,!1)}selectAll(){const{model:e,theme:t}=this.props,{autoSelectRow:n,autoSelectColumn:s}=t,i=s!==void 0&&s?null:0,o=s!==void 0&&s?null:e.rowCount-1,l=n!==void 0&&n?null:0,a=n!==void 0&&n?null:e.columnCount-1;this.setSelectedRanges([new Ie(l,i,a,o)])}moveCursor(e,t,n){const{cursorRow:s,cursorColumn:i,selectionEndColumn:o,selectionEndRow:l}=this.state,a=n?o:i,d=n?l:s;if(d===null||a===null){const{left:h,top:u}=this.state;this.moveCursorToPosition(h,u,n)}else{const{model:h}=this.props,{columnCount:u,rowCount:m}=h,g=Oe(a+e,0,u-1),p=Oe(d+t,0,m-1);this.moveCursorToPosition(g,p,n)}}moveCursorInDirection(e=Ie.SELECTION_DIRECTION.DOWN){const{model:t}=this.props,{columnCount:n,rowCount:s}=t,{cursorRow:i,cursorColumn:o,selectedRanges:l}=this.state,a=l.length>0?l:[Ie.makeCell(o,i)];let d=null;if(a.length===1&&Ie.cellCount(a)===1){const h=new Ie(0,0,n-1,s-1);d=h.nextCell(o,i,e)??h.startCell(e)}else d=Ie.nextCell(Ie.boundedRanges(a,n,s),o,i,e);if(d!=null){const{column:h,row:u}=d;this.setState({cursorColumn:h,cursorRow:u}),Ie.containsCell(l,h,u)||this.setState({selectedRanges:[Ie.makeCell(h,u)],selectionStartColumn:h,selectionStartRow:u,selectionEndColumn:h,selectionEndRow:u}),this.moveViewToCell(d.column,d.row)}}moveCursorToPosition(e,t,n=!1,s=!0,i=!1){n||this.beginSelection(e,t),this.moveSelection(e,t,n,i),s&&this.moveViewToCell(e,t)}moveViewToCell(e,t){if(!this.metrics)throw new Error("metrics not set");const{metricCalculator:n}=this,{bottomVisible:s,rightVisible:i,topVisible:o,leftVisible:l}=this.metrics,a=this.getMetricState(this.state);let{top:d,left:h,topOffset:u,leftOffset:m}=this.state;t!=null&&!_.isFloatingRow(t,this.metrics)&&(t<o?(d=n.getTopForTopVisible(a,t),u=0):t>s&&(d=n.getTopForBottomVisible(a,t),u=0)),e!=null&&!_.isFloatingColumn(e,this.metrics)&&(e<l?(h=n.getLeftForLeftVisible(a,e),m=0):e>i&&(h=n.getLeftForRightVisible(a,e),m=0)),this.setViewState({top:d,left:h,topOffset:u,leftOffset:m})}setViewState(e,t=!1){if(!this.metrics)throw new Error("metrics not set");const{isStickyBottom:n,isStickyRight:s}=this.props,{top:i,left:o}=e,{lastTop:l,lastLeft:a}=this.metrics;i!=null&&this.setState({isStuckToBottom:n&&i>=l}),o!=null&&this.setState({isStuckToRight:s&&o>=a}),this.setState(e),t&&this.forceUpdate()}startEditing(e,t,n=!1,s,i){const{model:o}=this.props;if(!Xe(o))throw new Error("model is not editable");const l=this.getModelColumn(e),a=this.getModelRow(t),d={column:e,row:t,selectionRange:s,value:i!==void 0?i:o.editValueForCell(l,a),isQuickEdit:n};this.setState({editingCell:d,cursorColumn:e,cursorRow:t}),this.moveViewToCell(e,t)}isValidForCell(e,t,n){const{model:s}=this.props,i=this.getModelColumn(e),o=this.getModelRow(t);return Xe(s)&&s.isValidForCell(i,o,n)}async pasteValue(e){const{model:t}=this.props,{movedColumns:n,movedRows:s,selectedRanges:i}=this.state;try{if(Yd(t),!t.isEditable||!i.every(m=>t.isEditableRange(m)))throw new va("Can't paste in to read-only area.");if(i.length<=0)throw new va("Select an area to paste to.");if(typeof e=="string"){const m=[],g=_.getModelRanges(i,n,s);Ie.forEachCell(g,(p,C)=>{m.push({column:p,row:C,text:e})}),await t.setValues(m);return}const o=e.length,l=e[0].length,{columnCount:a,rowCount:d}=t;let h=i;if(h.every(m=>Ie.cellCount([m])===1&&(m.startColumn??0)+l<=a&&(m.startRow??0)+o<=d)&&(h=h.map(m=>new Ie(m.startColumn,m.startRow,(m.startColumn??0)+l-1,(m.startRow??0)+o-1)),this.setSelectedRanges(h)),!h.every(m=>Ie.rowCount([m])===o&&Ie.columnCount([m])===l))throw new va("Copy and paste area are not same size.");const u=[];h.forEach(m=>{for(let g=0;g<l;g+=1)for(let p=0;p<o;p+=1)u.push({column:(m.startColumn??0)+g,row:(m.startRow??0)+p,text:e[p][g]})}),await t.setValues(u)}catch(o){const{onError:l}=this.props;l(o instanceof Error?o:new Error(`${o}`))}}setValueForCell(e,t,n){const{model:s}=this.props;Yd(s);const i=this.getModelColumn(e),o=this.getModelRow(t);return s.isValidForCell(i,o,n)?(s.setValueForCell(i,o,n),!0):!1}setValueForRanges(e,t){const{model:n}=this.props,{movedColumns:s,movedRows:i}=this.state,o=_.getModelRanges(e,s,i);Xe(n)&&n.setValueForRanges(o,t)}isSelected(e,t){const{selectedRanges:n}=this.state;for(let s=0;s<n.length;s+=1){const i=n[s],o=i.startRow===null||i.startRow<=e&&e<=(i.endRow??0),l=i.startColumn===null||i.startColumn<=t&&t<=(i.endColumn??0);if(o&&l)return!0}return!1}addDocumentCursor(e=null){this.documentCursor!==hs.getCursorClassName(e)&&(this.documentCursor!=null&&document.documentElement.classList.remove(this.documentCursor),this.documentCursor=hs.getCursorClassName(e),this.documentCursor!=null&&document.documentElement.classList.add(this.documentCursor),document.documentElement.classList.add("grid-block-events"))}removeDocumentCursor(){this.documentCursor!=null&&(document.documentElement.classList.remove(this.documentCursor),document.documentElement.classList.remove("grid-block-events"),this.documentCursor=null)}startDragTimer(e){this.stopDragTimer();const t=new MouseEvent("custom",e.nativeEvent);this.dragTimer=setTimeout(()=>{this.handleMouseDrag(t)},hs.dragTimeout)}stopDragTimer(){this.dragTimer&&(clearTimeout(this.dragTimer),this.dragTimer=null)}drawCanvas(e=this.updateMetrics()){if(!this.canvas)throw new Error("canvas is not set");if(!this.canvasContext)throw new Error("context not set");const{renderer:t,canvasContext:n,renderState:s}=this;n.save(),t.drawCanvas(s),n.restore()}focus(){this.canvas?.focus()}isFocused(){return document.activeElement===this.canvas}handleClick(e){const t=this.getGridPointFromEvent(e),n=this.getMouseHandlers();for(let s=0;s<n.length;s+=1)if(n[s].onClick(t,this,e)!==!1){e.stopPropagation(),e.preventDefault();break}this.canvas?.focus()}handleContextMenu(e){const t=this.getGridPointFromEvent(e),n=this.getMouseHandlers();for(let s=0;s<n.length;s+=1)if(n[s].onContextMenu(t,this,e)!==!1){e.stopPropagation(),e.preventDefault();break}}handleKeyDown(e){const t=this.getKeyHandlers();for(let n=0;n<t.length;n+=1){const i=t[n].onDown(e,this);if(i!==!1){const o=i;(o?.stopPropagation??!0)&&e.stopPropagation(),(o?.preventDefault??!0)&&e.preventDefault();break}}}notifyMouseHandlers(e,t,n=!0,s=!1){const i=this.getGridPointFromEvent(t),o=this.getMouseHandlers();let l=null;for(let a=0;a<o.length;a+=1){const d=o[a],h=d[e]!=null&&d[e](i,this,t);if(h!==!1){d.cursor!=null&&({cursor:l}=d,s&&this.addDocumentCursor(l));const u=h;(u?.stopPropagation??!0)&&t.stopPropagation(),(u?.preventDefault??!0)&&t.preventDefault();break}}if(this.setState({cursor:l}),n){const{x:a,y:d}=i;this.setState({mouseX:a,mouseY:d})}}handleMouseDown(e){window.addEventListener("mousemove",this.handleMouseDrag,!0),window.addEventListener("mouseup",this.handleMouseUp,!0),!(e.button!=null&&e.button!==0)&&(this.notifyMouseHandlers("onDown",e),this.startDragTimer(e))}handleDoubleClick(e){this.notifyMouseHandlers("onDoubleClick",e)}handleMouseMove(e){this.notifyMouseHandlers("onMove",e)}handleMouseLeave(e){this.notifyMouseHandlers("onLeave",e,!1),this.setState({mouseX:null,mouseY:null})}handleMouseDrag(e){this.setState({isDragging:!0}),this.notifyMouseHandlers("onDrag",e,!0,!0),this.stopDragTimer()}handleMouseUp(e){window.removeEventListener("mousemove",this.handleMouseDrag,!0),window.removeEventListener("mouseup",this.handleMouseUp,!0),!(e.button!=null&&e.button!==0)&&(this.notifyMouseHandlers("onUp",e,!1),this.stopDragTimer(),this.removeDocumentCursor())}handleResize(){if(this.updateCanvas(),!this.metrics)throw new Error("metrics not set");this.forceUpdate()}handleWheel(e){if(this.notifyMouseHandlers("onWheel",e),e.defaultPrevented)return;const{metricCalculator:t,metrics:n}=this,s=this.getMetricState();if(!n)throw new Error("metrics not set");const{lastTop:i,lastLeft:o,columnCount:l,rowCount:a,scrollableContentWidth:d,scrollableViewportWidth:h,scrollableContentHeight:u,scrollableViewportHeight:m,hasHorizontalBar:g,hasVerticalBar:p}=n;let{top:C,left:f,topOffset:b,leftOffset:w}=n;const S=this.getTheme();let{deltaX:T,deltaY:y}=_.getScrollDelta(e,n.barWidth,n.barHeight,n.rowHeight,n.rowHeight);for(;g&&T!==0;){if(w+=T,T=0,l>1){if(w>0&&f>=o||w<0&&f<=0){w=0;break}}else{if(w<=0){w=0;break}const E=d-h;if(w>=E){w=E;break}}if(w>0){const E=n.allColumnWidths.get(f)??t.getVisibleColumnWidth(f,s);w>=E?(T=w-E,w=0,f+=1):S.scrollSnapToColumn&&l>1&&(w=0,f+=1)}else if(w<0){const E=n.allColumnWidths.get(f-1)??t.getVisibleColumnWidth(f-1,s);Math.abs(w)<=E&&S.scrollSnapToColumn&&l>1?(w=0,f-=1):(T=w+E,w=0,f-=1)}}for(;p&&y!==0;){if(b+=y,y=0,a>1){if(b>0&&C>=i||b<0&&C<=0){b=0;break}}else{if(b<=0){b=0;break}const E=u-m;if(b>=E){b=E;break}}if(b>0){const E=n.allRowHeights.get(C)??t.getVisibleRowHeight(C,s);b>=E?(y=b-E,b=0,C+=1):S.scrollSnapToRow&&a>1&&(b=0,C+=1)}else if(b<0){const E=n.allRowHeights.get(C-1)??t.getVisibleRowHeight(C-1,s);Math.abs(b)<=E&&S.scrollSnapToRow&&a>1?(b=0,C-=1):(y=b+E,b=0,C-=1)}}this.setViewState({top:C,left:f,leftOffset:w,topOffset:b}),e.stopPropagation(),e.preventDefault()}handleEditCellCancel(){this.setState({editingCell:null}),this.focus()}handleEditCellChange(e){this.setState(({editingCell:t})=>{try{return Kd(t),{editingCell:{...t,value:e}}}catch(n){const{onError:s}=this.props;return s(n instanceof Error?n:new Error(`${n}`)),null}})}handleEditCellCommit(e,{direction:t=mn.DOWN,fillRange:n=!1}={}){const{editingCell:s,selectedRanges:i}=this.state;if(!s)throw new Error("editingCell not set");const{column:o,row:l}=s;if(!this.isValidForCell(o,l,e)){t===null&&this.setState({editingCell:null});return}n?this.setValueForRanges(i,e):this.setValueForCell(o,l,e),t!==null&&this.moveCursorInDirection(t),this.setState({editingCell:null}),this.focus()}renderInputField(){const{model:e}=this.props,{editingCell:t}=this.state,{metrics:n}=this;if(t==null||n==null||!Xe(e))return null;const{selectionRange:s,value:i,isQuickEdit:o}=t,{column:l,row:a}=t,{gridX:d,gridY:h,allColumnXs:u,allRowYs:m,allColumnWidths:g,allRowHeights:p}=n,C=u.get(l),f=m.get(a),b=g.get(l),w=p.get(a),S=C!=null&&f!=null&&b!=null&&w!=null?{position:"absolute",left:d+C,top:h+f,width:b,height:w}:{opacity:0},T=this.getModelColumn(l),y=this.getModelRow(a),E=T!=null&&y!=null?{textAlign:e.textAlignForCell(T,y)}:void 0,R=e.isValidForCell(T,y,i);return r.jsx("div",{style:S,children:r.jsx(Pr,{selectionRange:s,className:Y({error:!R}),onCancel:this.handleEditCellCancel,onChange:this.handleEditCellChange,onDone:this.handleEditCellCommit,isQuickEdit:o,style:E,value:i},`${l},${a}`)})}updateRenderState(){if(!this.canvas)throw new Error("canvas is not set");if(!this.canvasContext)throw new Error("context not set");const{cursorColumn:e,cursorRow:t,draggingColumn:n,draggingColumnSeparator:s,draggingRow:i,draggingRowOffset:o,draggingRowSeparator:l,editingCell:a,isDraggingHorizontalScrollBar:d,isDraggingVerticalScrollBar:h,isDragging:u,mouseX:m,mouseY:g,selectedRanges:p}=this.state,{model:C,stateOverride:f}=this.props,{metrics:b}=this,w=this.canvasContext,S=this.getTheme(),T=this.canvas.clientWidth,y=this.canvas.clientHeight;return N(b),this.renderState={width:T,height:y,context:w,theme:S,model:C,metrics:b,mouseX:m,mouseY:g,selectedRanges:p,draggingColumn:n,draggingColumnSeparator:s,draggingRow:i,draggingRowOffset:o,draggingRowSeparator:l,editingCell:a,isDraggingHorizontalScrollBar:d,isDraggingVerticalScrollBar:h,isDragging:u,cursorColumn:e,cursorRow:t,...f},this.renderState}render(){const{cursor:e}=this.state;return r.jsxs(r.Fragment,{children:[r.jsx("canvas",{className:Y("grid-canvas",hs.getCursorClassName(e)),ref:t=>{this.canvas=t},onClick:this.handleClick,onContextMenu:this.handleContextMenu,onDoubleClick:this.handleDoubleClick,onKeyDown:this.handleKeyDown,onMouseDown:this.handleMouseDown,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,tabIndex:0,children:"Your browser does not support HTML canvas. Update your browser?"}),this.renderInputField()]})}}const Cw=hs,Ta=5e3;class bw extends cm{get floatingTopRowCount(){return 0}get floatingBottomRowCount(){return 0}get floatingLeftColumnCount(){return 0}get floatingRightColumnCount(){return 0}get columnHeaderMaxDepth(){return 1}truncationCharForCell(e,t){}textAlignForCell(e,t){return"left"}colorForCell(e,t,n){return n.textColor}backgroundColorForCell(e,t,n){return null}colorForColumnHeader(e,t=0){return null}textForRowHeader(e){return""}textForRowFooter(e){return""}isColumnMovable(e,t=0){return!0}isRowMovable(e){return!0}getColumnHeaderGroup(e,t){}getColumnHeaderParentGroup(e,t){}tokensForCell(e,t,n=Ta){const s=this.textForCell(e,t);return this.getCachedTokensInText(s,n)}getCachedTokensInText=pn((e,t)=>{if(t>=e.length)return _.findTokensWithProtocolInText(e);const n=e.slice(t-1,Ta).search(/\s/);let s=t+n;n===-1&&(s=Math.min(Ta,e.length));const i=e.substring(0,s);return _.findTokensWithProtocolInText(i)});renderTypeForCell(e,t){return"text"}}const Sw=bw;function ww(c,e){const t=Ew(c);return t===void 0?void 0:`${Fw(c)} ? ${t} : ${e}`}function vw(c){return dh.Column.formatRowColor(c)}function Tw(c,e){return c.formatColor(e)}const Qi=ne.module("ConditionalFormattingUtils");var Dn=(c=>(c.CONDITIONAL="conditional",c.ROWS="rows",c))(Dn||{}),$e=(c=>(c.IS_EQUAL="is-equal",c.IS_NOT_EQUAL="is-not-equal",c.IS_BETWEEN="is-between",c.GREATER_THAN="greater-than",c.GREATER_THAN_OR_EQUAL="greater-than-or-equal",c.LESS_THAN="less-than",c.LESS_THAN_OR_EQUAL="less-than-or-equal",c.IS_NULL="is-null",c.IS_NOT_NULL="is-not-null",c))($e||{}),Bt=(c=>(c.IS_EXACTLY="is-exactly",c.IS_NOT_EXACTLY="is-not-exactly",c.CONTAINS="contains",c.DOES_NOT_CONTAIN="does-not-contain",c.STARTS_WITH="starts-with",c.ENDS_WITH="ends-with",c.IS_NULL="is-null",c.IS_NOT_NULL="is-not-null",c))(Bt||{}),Ft=(c=>(c.IS_EXACTLY="is-exactly",c.IS_NOT_EXACTLY="is-not-exactly",c.IS_BEFORE="is-before",c.IS_BEFORE_OR_EQUAL="is-before-or-equal",c.IS_AFTER="is-after",c.IS_AFTER_OR_EQUAL="is-after-or-equal",c.IS_NULL="is-null",c.IS_NOT_NULL="is-not-null",c))(Ft||{}),Xi=(c=>(c.IS_TRUE="is-true",c.IS_FALSE="is-false",c.IS_NULL="is-null",c.IS_NOT_NULL="is-not-null",c))(Xi||{}),zs=(c=>(c.IS_EQUAL="is-equal",c.IS_NOT_EQUAL="is-not-equal",c.IS_NULL="is-null",c.IS_NOT_NULL="is-not-null",c))(zs||{}),on=(c=>(c.NO_FORMATTING="no-formatting",c.POSITIVE="positive",c.NEGATIVE="negative",c.WARN="warn",c.NEUTRAL="neutral",c.ACCENT_1="accent-1",c.ACCENT_2="accent-2",c.CUSTOM="custom",c))(on||{});function Jd(c){switch(c){case"no-formatting":return"No formatting";case"positive":return"Positive";case"negative":return"Negative";case"warn":return"Warn";case"neutral":return"Neutral";case"accent-1":return"Accent 1";case"accent-2":return"Accent 2";case"custom":return"Custom..."}}function Tl(c){const{type:e,customConfig:t}=c;switch(e){case"no-formatting":return;case"positive":return"#9fde6f";case"negative":return"#ff6087";case"warn":return"#f67f40";case"neutral":return"#ffd95c";case"accent-1":return"#78dce8";case"accent-2":return"#ab9bf5";case"custom":return t?.background;default:return}}function El(c){const{type:e,customConfig:t}=c;switch(e){case"no-formatting":return;case"positive":return"#526a3f";case"negative":return"#802f44";case"warn":return"#663318";case"neutral":return"#63562b";case"accent-1":return"#3f6469";case"accent-2":return"#554d72";case"custom":return t?.color;default:return}}function Ew(c){const e=El(c.style),t=Tl(c.style);if(!(e===void 0||t===void 0))return`bgfg(\`${t}\`, \`${e}\`)`}function yw(c){const{column:e,value:t,start:n,end:s}=c;return Bw(e.name,c.condition,t,n,s)}function Rw(c){const{column:e,value:t}=c;return Uw(e.name,c.condition,t)}function xw(c){const{column:e,value:t}=c;return Vw(e.name,c.condition,t)}function Dw(c){const{column:e}=c;return $w(e.name,c.condition)}function Iw(c){const{column:e,value:t}=c;return Ww(e.name,c.condition,t)}function Fw(c){const{column:e}=c;if(F.isNumberType(e.type))return yw(c);if(F.isCharType(e.type))return Iw(c);if(F.isStringType(e.type))return Rw(c);if(F.isDateType(e.type))return xw(c);if(F.isBooleanType(e.type))return Dw(c);throw new Error("Invalid column type")}function Nw(c){switch(c){case"is-equal":return"is equal to";case"is-not-equal":return"is not equal to";case"is-between":return"is between";case"greater-than":return"greater than";case"greater-than-or-equal":return"greater than or equal to";case"less-than":return"less than";case"less-than-or-equal":return"less than or equal to";case"is-null":return"is null";case"is-not-null":return"is not null"}}function kw(c){switch(c){case"is-exactly":return"is exactly";case"is-not-exactly":return"is not exactly";case"contains":return"contains";case"does-not-contain":return"does not contain";case"starts-with":return"starts with";case"ends-with":return"ends with";case"is-null":return"is null";case"is-not-null":return"is not null"}}function Mw(c){switch(c){case"is-exactly":return"is";case"is-not-exactly":return"is not";case"is-before":return"is before";case"is-before-or-equal":return"is before or equal";case"is-after":return"is after";case"is-after-or-equal":return"is after or equal";case"is-null":return"is null";case"is-not-null":return"is not null"}}function Lw(c){switch(c){case"is-true":return"is true";case"is-false":return"is false";case"is-null":return"is null";case"is-not-null":return"is not null"}}function Ow(c){switch(c){case"is-equal":return"is";case"is-not-equal":return"is not";case"is-null":return"is null";case"is-not-null":return"is not null"}}function bu(c){if(F.isNumberType(c)||F.isCharType(c))return"is-equal";if(F.isStringType(c)||F.isDateType(c))return"is-exactly";if(F.isBooleanType(c))return"is-true";throw new Error("Invalid column type")}function Su(c){if(F.isCharType(c)||F.isStringType(c))return""}function wu(c){const{condition:e,value:t,start:n,end:s}=c;return{condition:e,value:t,start:n,end:s}}function na(c){return{condition:bu(c),value:Su(c),start:void 0,end:void 0}}function vu(){return{type:"no-formatting"}}function Aw(c){switch(c){case"is-exactly":return"==";case"is-not-exactly":return"!=";case"contains":return"contains";case"does-not-contain":return"does not contain";case"starts-with":return"starts with";case"ends-with":return"ends with";case"is-null":return"is null";case"is-not-null":return"is not null"}}function _w(c){switch(c){case"is-exactly":return"==";case"is-not-exactly":return"!=";case"is-before":return"<";case"is-before-or-equal":return"<=";case"is-after":return">";case"is-after-or-equal":return">=";case"is-null":return"is null";case"is-not-null":return"is not null"}}function Pw(c){switch(c){case"is-true":return"is true";case"is-false":return"is false";case"is-null":return"is null";case"is-not-null":return"is not null"}}function jw(c){switch(c){case"is-equal":return"==";case"is-not-equal":return"!=";case"is-null":return"is null";case"is-not-null":return"is not null"}}function Hw(c){switch(c){case"is-equal":return"==";case"is-not-equal":return"!=";case"is-between":return"==";case"greater-than":return">";case"greater-than-or-equal":return">=";case"less-than":return"<";case"less-than-or-equal":return"<=";case"is-null":return"is null";case"is-not-null":return"is not null"}}function Bw(c,e,t,n,s){switch(e){case"is-equal":return`${c} == ${t}`;case"is-not-equal":return`${c} != ${t}`;case"is-between":return`${c} > ${n} && ${c} < ${s}`;case"greater-than":return`${c} > ${t}`;case"greater-than-or-equal":return`${c} >= ${t}`;case"less-than":return`${c} < ${t}`;case"less-than-or-equal":return`${c} <= ${t}`;case"is-null":return`${c} == null`;case"is-not-null":return`${c} != null`}}function Uw(c,e,t){switch(e){case"is-exactly":return`${c} == "${t}"`;case"is-not-exactly":return`${c} != "${t}"`;case"contains":return`${c} != null && ${c}.contains("${t}")`;case"does-not-contain":return`${c} != null && !${c}.contains("${t}")`;case"starts-with":return`${c} != null && ${c}.startsWith("${t}")`;case"ends-with":return`${c} != null && ${c}.endsWith("${t}")`;case"is-null":return`${c} == null`;case"is-not-null":return`${c} != null`}}function Vw(c,e,t){switch(e){case"is-exactly":return`${c} == convertDateTime("${t}")`;case"is-not-exactly":return`${c} != convertDateTime(\`${t}\`)`;case"is-before":return`${c} < convertDateTime(\`${t}\`)`;case"is-before-or-equal":return`${c} <= convertDateTime("${t}")`;case"is-after":return`${c} > convertDateTime(\`${t}\`)`;case"is-after-or-equal":return`${c} >= convertDateTime(\`${t}\`)`;case"is-null":return`${c} == null`;case"is-not-null":return`${c} != null`}}function $w(c,e){switch(e){case"is-true":return`${c} == true`;case"is-false":return`${c} == false`;case"is-null":return`${c} == null`;case"is-not-null":return`${c} != null`}}function Ww(c,e,t){switch(e){case"is-equal":return`${c} == '${t}'`;case"is-not-equal":return`${c} != '${t}'`;case"is-null":return`isNull(${c})`;case"is-not-null":return`!isNull(${c})`}}function Gw(c,e){if(F.isNumberType(c))return Hw(e);if(F.isCharType(c))return jw(e);if(F.isStringType(c))return Aw(e);if(F.isDateType(c))return _w(e);if(F.isBooleanType(c))return Pw(e);throw new Error("Invalid column type")}function zw(c,e){if(e===void 0)return Qi.debug("no rules passed."),[];const t=[];let n;const s=new Map;return e.forEach(({config:i,type:o})=>{const{column:l}=i,a=c.find(({name:p,type:C})=>p===l.name&&C===l.type);if(a===void 0){Qi.debug(`Column ${l.name}:${l.type} not found. Ignoring format rule.`,i);return}const[d,h]=(o==="conditional"?s.get(a.name):n)??["null",void 0],u=ww(i,d);if(u===void 0){Qi.debug("Ignoring format rule.",i);return}const m=h===void 0?-1:t.indexOf(h);m>-1&&t.splice(m,1);const g=o==="conditional"?Tw(a,u):vw(u);t.push(g),o==="conditional"?s.set(a.name,[u,g]):n=[u,g]}),t}function Kw(c,e){switch(c){case"is-null":case"is-not-null":return!0;default:{const[t,...n]=(e??"").split(" "),s=n.join(" ");try{Xs.parseDateTimeString(t)}catch{return Qi.debug("Invalid datetime string",t),!1}try{dh.i18n.TimeZone.getTimeZone(s)}catch{return Qi.debug("Invalid timezone string",s),!1}return!0}}}function Yw({type:c}){return F.isNumberType(c)||F.isCharType(c)||F.isStringType(c)||F.isDateType(c)||F.isBooleanType(c)}function sa({animation:c="iris-grid-bottom-bar-slide-up",children:e,className:t,isShown:n,onClick:s,onEntering:i,onEntered:o,onExiting:l,onExited:a}){return r.jsx(Wt,{in:n,timeout:Je.transitionMs,classNames:c,onEntering:i,onEntered:o,onExiting:l,onExited:a,mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:Y("iris-grid-bottom-bar",t),role:"presentation",onClick:s,onKeyPress:s,children:e})})}const qw=3e3,Xw=5;function Zw({isSaving:c=!1,onSave:e,onDiscard:t,discardTooltip:n,saveTooltip:s,error:i,pendingDataErrors:o,pendingDataMap:l,onEntering:a,onEntered:d,onExiting:h,onExited:u}){const[m,g]=v.useState(!1),[p,C]=v.useState(!1),f=v.useRef(),b=lr(c),w=v.useMemo(()=>o.size===0?i:o.size<=Xw?`Key can't be empty (on pending row${o.size>1?"s":""} ${Array.from(o.keys()).join(", ").trim()})`:`Key can't be empty (on ${o.size} rows)`,[i,o]);v.useEffect(function(){b!=null&&b&&!c&&w==null&&(g(!0),C(!0),f.current=setTimeout(()=>{g(!1)},qw))},[w,c,b]),v.useEffect(function(){f.current&&l.size>0&&(clearTimeout(f.current),g(!1),C(!1))},[l]),v.useEffect(function(){return()=>f.current?clearTimeout(f.current):void 0},[]);const S=l.size;let T;return c?T=r.jsx(In,{}):p&&(T=dr),r.jsxs(sa,{className:"pending-data-bottom-bar",isShown:S>0||m||w!=null,onEntering:a,onEntered:d,onExiting:h,onExited:()=>{C(!1),u&&u()},children:[w!=null&&w!==""&&r.jsxs("div",{className:"error-message",children:[r.jsx(ee,{icon:ws}),r.jsx("span",{children:`${w}`})]}),(w==null||w==="")&&r.jsx("div",{className:"status-message",children:S>0&&r.jsx("span",{children:`${S} row${S>1?"s":""} pending`})}),r.jsxs("div",{className:"buttons-container",children:[!c&&!p&&r.jsx(B,{kind:"secondary",onClick:t,tooltip:n,children:"Discard"}),r.jsxs(B,{kind:p?"success":"primary",onClick:e,icon:T,disabled:c||p||w!=null,tooltip:s,children:[c&&"Committing...",!c&&p&&"Success",!c&&!p&&"Commit"]})]})]})}var Tu=(c=>(c.COUNT="Count",c.MIN="Min",c.MAX="Max",c.SUM="Sum",c.ABS_SUM="AbsSum",c.VAR="Var",c.AVG="Avg",c.STD="Std",c.FIRST="First",c.LAST="Last",c.SKIP="Skip",c.COUNT_DISTINCT="CountDistinct",c.DISTINCT="Distinct",c.UNIQUE="Unique",c))(Tu||{});const Le=Tu,Qw=[Le.SUM,Le.ABS_SUM,Le.MIN,Le.MAX,Le.VAR,Le.AVG,Le.STD,Le.FIRST,Le.LAST,Le.COUNT_DISTINCT,Le.DISTINCT,Le.COUNT,Le.UNIQUE],Jw=c=>{switch(c){default:return!1}},ev=(c,e)=>{switch(c){case Le.COUNT:case Le.FIRST:case Le.LAST:case Le.COUNT_DISTINCT:case Le.DISTINCT:case Le.UNIQUE:return!0;case Le.MIN:case Le.MAX:return F.isNumberType(e)||F.isDateType(e)||F.isTextType(e);case Le.SUM:case Le.ABS_SUM:case Le.VAR:case Le.AVG:case Le.STD:return F.isNumberType(e);case Le.SKIP:return!1}},jr=(c,e)=>c.filter(t=>ev(e,t.type)),tv=(c,e,t,n)=>jr(c,e).map(({name:s})=>s).filter(s=>t.includes(s)?!n:n),Cs={isRollupOperation:Jw,filterValidColumns:jr,getOperationColumnNames:tv};var Eu=(c=>(c.FILTER_CONTROL_CHANGE_CLEARS_ALL_FILTERS="filter-control-change-clears-all-filters",c.LINK_CHANGE_CLEARS_ALL_FILTERS="link-change-clears-all-filters",c))(Eu||{});const xi=Eu,nv=Object.freeze([[xi.FILTER_CONTROL_CHANGE_CLEARS_ALL_FILTERS,!1],[xi.LINK_CHANGE_CLEARS_ALL_FILTERS,!1]]),yu={DEFAULTS:nv},sv=ne.module("ColumnHeaderGroup");function Ea(c){return c instanceof dn}class dn{static NEW_GROUP_PREFIX=":newGroup";name;children;depth;parent;color;childIndexes;constructor({name:e,children:t,color:n,depth:s,childIndexes:i,parent:o}){this.name=e,this.children=t,this.color=n,this.depth=s,this.childIndexes=i,this.parent=o}getVisibleRange=ge(e=>{const t=this.childIndexes.flat(),n=_.getVisibleIndexes(t,e),s=Math.min(...n),i=Math.max(...n);return i-s!==t.length-1&&sv.warn(`Column header group ${this.name} is not contiguous`),[s,i]});setParent(e){this.parent=e}addChildren(e){const t=new Set(this.children.concat(e));this.children=[...t]}removeChildren(e){const t=new Set(this.children);e.forEach(n=>t.delete(n)),this.children=[...t]}get isNew(){return this.name.startsWith(dn.NEW_GROUP_PREFIX)}}const Hi=ne.module("IrisGridUtils");function os(c,e){return c>=0&&c<e.length}function iv(c){return c.asDate!=null}class Te{static dehydrateGridState(e,t){const{isStuckToBottom:n,isStuckToRight:s,movedColumns:i,movedRows:o}=t,{columns:l}=e;return{isStuckToBottom:n,isStuckToRight:s,movedColumns:[...i].filter(({to:a,from:d})=>os(a,l)&&(typeof d=="number"&&os(d,l)||Array.isArray(d)&&os(d[0],l)&&os(d[1],l))).map(({to:a,from:d})=>({to:l[a].name,from:Array.isArray(d)?[l[d[0]].name,l[d[1]].name]:l[d].name})),movedRows:[...o]}}static hydrateGridState(e,t,n=[]){const{isStuckToBottom:s,isStuckToRight:i,movedColumns:o,movedRows:l}=t,{columns:a}=e,d=Te.parseCustomColumnNames(n),h=a.map(({name:u})=>u).concat(d);return{isStuckToBottom:s,isStuckToRight:i,movedColumns:[...o].map(({to:u,from:m})=>{const g=p=>typeof p=="string"?h.findIndex(C=>C===p):p;return{to:g(u),from:Array.isArray(m)?[g(m[0]),g(m[1])]:g(m)}}).filter(({to:u,from:m})=>os(u,h)&&(typeof m=="number"&&os(m,h)||Array.isArray(m)&&os(m[0],h)&&os(m[1],h))),movedRows:[...l]}}static dehydrateIrisGridState(e,t){const{aggregationSettings:n={aggregations:ke,showOnTop:!1},advancedFilters:s,customColumnFormatMap:i,isFilterBarShown:o,metrics:l,quickFilters:a,customColumns:d,conditionalFormats:h=ke,reverseType:u,rollupConfig:m=void 0,showSearchBar:g,searchValue:p,selectDistinctColumns:C=ke,selectedSearchColumns:f,sorts:b,invertSearchColumns:w,pendingDataMap:S=Pn,frozenColumns:T,columnHeaderGroups:y}=t;N(l);const{userColumnWidths:E,userRowHeights:R}=l,{columns:x}=e;return{advancedFilters:Te.dehydrateAdvancedFilters(x,s),aggregationSettings:n,customColumnFormatMap:[...i],isFilterBarShown:o,quickFilters:Te.dehydrateQuickFilters(a),sorts:Te.dehydrateSort(b),userColumnWidths:[...E].filter(([D])=>D!=null&&D>=0&&D<x.length).map(([D,M])=>[x[D].name,M]),userRowHeights:[...R],customColumns:[...d],conditionalFormats:[...h],reverseType:u,rollupConfig:m,showSearchBar:g,searchValue:p,selectDistinctColumns:[...C],selectedSearchColumns:f,invertSearchColumns:w,pendingDataMap:Te.dehydratePendingDataMap(x,S),frozenColumns:T,columnHeaderGroups:y?.map(D=>({name:D.name,children:D.children,color:D.color}))}}static hydrateIrisGridState(e,t){const{advancedFilters:n,aggregationSettings:s={aggregations:[],showOnTop:!1},customColumnFormatMap:i,isFilterBarShown:o,quickFilters:l,sorts:a,customColumns:d,conditionalFormats:h,userColumnWidths:u,userRowHeights:m,reverseType:g,rollupConfig:p=void 0,showSearchBar:C,searchValue:f,selectDistinctColumns:b,selectedSearchColumns:w,invertSearchColumns:S=!0,pendingDataMap:T=[],frozenColumns:y,columnHeaderGroups:E}=t,{columns:R,formatter:x}=e;return{advancedFilters:Te.hydrateAdvancedFilters(R,n,x.timeZone),aggregationSettings:s,customColumnFormatMap:new Map(i),isFilterBarShown:o,quickFilters:Te.hydrateQuickFilters(R,l,x.timeZone),sorts:Te.hydrateSort(R,a),userColumnWidths:new Map(u.map(([D,M])=>typeof D=="string"||D instanceof String?[R.findIndex(({name:O})=>O===D),M]:[D,M]).filter(([D])=>D!=null&&D>=0&&D<R.length)),customColumns:d,conditionalFormats:h,userRowHeights:new Map(m),reverseType:g,rollupConfig:p,showSearchBar:C,searchValue:f,selectDistinctColumns:b,selectedSearchColumns:w,invertSearchColumns:S,pendingDataMap:Te.hydratePendingDataMap(R,T),frozenColumns:y,columnHeaderGroups:Te.parseColumnHeaderGroups(e,E??e.layoutHints?.columnGroups??[]).groups}}static dehydrateIrisGridPanelState(e,t){const{isSelectingPartition:n,partition:s,partitionColumn:i,advancedSettings:o}=t;return{isSelectingPartition:n,partition:s,partitionColumn:i?.name,advancedSettings:[...o]}}static hydrateIrisGridPanelState(e,t){const{isSelectingPartition:n,partition:s,partitionColumn:i,advancedSettings:o}=t,{columns:l}=e;return{isSelectingPartition:n,partition:s,partitionColumn:i!=null?Te.getColumnByName(l,i):void 0,advancedSettings:new Map([...yu.DEFAULTS,...o])}}static dehydrateQuickFilters(e){return[...e].map(([t,n])=>{const{text:s}=n;return[t,{text:s}]})}static hydrateQuickFilters(e,t,n){const s=t.map(([i,o])=>{const{text:l}=o;let a=null;try{const d=Te.getColumn(e,i);d!=null&&(a=F.makeQuickFilter(d,l,n))}catch(d){Hi.error("hydrateQuickFilters error with",l,d)}return[i,{text:l,filter:a}]});return new Map(s)}static dehydrateAdvancedFilters(e,t){return[...t].map(([n,s])=>{const i=Te.getColumn(e,n);N(i);const o=Te.dehydrateAdvancedFilterOptions(i,s.options);return[n,{options:o}]})}static hydrateAdvancedFilters(e,t,n){const s=t.map(([i,o])=>{const l=Te.getColumn(e,i);N(l);const a=Te.hydrateAdvancedFilterOptions(l,o.options);let d=null;try{Te.getColumn(e,i)!=null&&(d=F.makeAdvancedFilter(l,a,n))}catch(h){Hi.error("hydrateAdvancedFilters error with",a,h)}return[i,{options:a,filter:d}]});return new Map(s)}static dehydrateAdvancedFilterOptions(e,t){const{selectedValues:n,...s}=t;return{selectedValues:n?.map(i=>Te.dehydrateValue(i,e?.type)),...s}}static hydrateAdvancedFilterOptions(e,t){const{selectedValues:n,...s}=t;return{selectedValues:n?.map(i=>Te.hydrateValue(i,e?.type)),...s}}static dehydratePendingDataMap(e,t){return[...t].map(([n,{data:s}])=>[n,{data:[...s].map(([i,o])=>[e[i].name,Te.dehydrateValue(o,e[i].type)])}])}static hydratePendingDataMap(e,t){const n=new Map,s=i=>(n.has(i)||n.set(i,e.findIndex(({name:o})=>o===i)),n.get(i));return new Map(t.map(([i,{data:o}])=>[i,{data:new Map(o.map(([l,a])=>{const d=s(l);return N(d),[s(l)??null,Te.hydrateValue(a,e[d].type)]}))}]))}static dehydrateValue(e,t){return F.isDateType(t)?Te.dehydrateDateTime(e):F.isLongType(t)?Te.dehydrateLong(e):e}static hydrateValue(e,t){return F.isDateType(t)?Te.hydrateDateTime(e):F.isLongType(t)?Te.hydrateLong(e):e}static dehydrateDateTime(e){return e!=null?I.i18n.DateTimeFormat.format(Xs.FULL_DATE_FORMAT,e):null}static hydrateDateTime(e){return e!=null?I.i18n.DateTimeFormat.parse(Xs.FULL_DATE_FORMAT,e):null}static dehydrateLong(e){return e!=null?`${e}`:null}static hydrateLong(e){return e!=null?I.LongWrapper.ofString(e):null}static dehydrateSort(e){return e.map(t=>{const{column:n,isAbs:s,direction:i}=t;return{column:n.name,isAbs:s,direction:i}})}static hydrateSort(e,t){return t.map(n=>{const{column:s,isAbs:i,direction:o}=n;if(o===F.sortDirection.reverse)return I.Table.reverse();const l=typeof s=="string"?Te.getColumnByName(e,s):Te.getColumn(e,s);if(l!=null){let a=l.sort();return i&&(a=a.abs()),o===F.sortDirection.descending?a=a.desc():a=a.asc(),a}return null}).filter(n=>n!=null&&n.direction!==F.sortDirection.reverse)}static extractTableSettings(e,t=[]){const{irisGridPanelState:n,irisGridState:s}=e,{partitionColumn:i,partition:o}=n,{advancedFilters:l,quickFilters:a,sorts:d}=s;return{advancedFilters:l,inputFilters:t,partition:o,partitionColumn:i,quickFilters:a,sorts:d}}static applyTableSettings(e,t,n){const{columns:s}=e;let i=[];t.quickFilters&&(i=Te.getFiltersFromFilterMap(Te.hydrateQuickFilters(s,t.quickFilters,n)));let o=[];t.advancedFilters&&(o=Te.getFiltersFromFilterMap(Te.hydrateAdvancedFilters(s,t.advancedFilters,n)));const l=Te.getFiltersFromInputFilters(s,t.inputFilters,n);let a=[];t.sorts&&(a=Te.hydrateSort(s,t.sorts));let d=[...i,...o];const{partition:h,partitionColumn:u}=t;if(h!=null&&u!=null){const m=Te.getColumnByName(s,u);m&&(d=[m.filter().eq(I.FilterValue.ofString(h)),...d])}d=[...l,...d],e.applyFilter(d),e.applySort(a)}static getInputFiltersForColumns(e,t=[]){return t.filter(({name:n,type:s})=>e.find(({name:i,type:o})=>i===n&&o===s))}static getFiltersFromInputFilters(e,t=[],n){return t.map(({name:s,type:i,value:o})=>{const l=e.find(({name:a,type:d})=>a===s&&d===i);if(l)try{return F.makeQuickFilter(l,o,n)}catch(a){Hi.debug("Unable to create input filter",a)}return null}).filter(s=>s!=null)}static getFiltersFromFilterMap(e){const t=[],n=Array.from(e.keys());for(let s=0;s<n.length;s+=1){const i=n[s],o=e.get(i);o?.filter!=null&&t.push(o.filter)}return t}static getHiddenColumns(e){return[...e.entries()].filter(([,t])=>t===0).map(([t])=>t)}static parseCustomColumnNames(e){return e.map(t=>t.split("=")[0])}static getRemovedCustomColumnNames(e,t){const n=Te.parseCustomColumnNames(e),s=Te.parseCustomColumnNames(t);return n.filter(i=>!s.includes(i))}static removeSortsInColumns(e,t){return e.filter(n=>!t.includes(n.column.name))}static removeFiltersInColumns(e,t,n){const s=e.map(({name:o})=>o),i=new Map(t);return n.forEach(o=>i.delete(s.indexOf(o))),i}static removeColumnFromMovedColumns(e,t,n){const s=e.map(({name:o})=>o);let i=[...t];for(let o=0;o<n.length;o+=1){const l=n[o];let a=s.findIndex(h=>h===l);const d=[];for(let h=0;h<i.length;h+=1){const u=i[h],m={...u};let[g,p]=Array.isArray(u.from)?u.from:[u.from,u.from];a<=u.to&&(m.to-=1),a<g&&(g-=1),a<=p&&(p-=1),g<=p&&g!==m.to&&(g===p?d.push({...m,from:g}):d.push({...m,from:[g,p]})),a=_.applyItemMoves(a,a,[u])[0][0]}i=d,s.splice(s.findIndex(h=>h===l),1)}return i}static removeColumnsFromSelectDistinctColumns(e,t){return e.filter(n=>!t.includes(n))}static getVisibleColumnsInRange(e,t,n,s,i){const o=[];for(let l=t;l<=n;l+=1){const a=_.getModelIndex(l,s);a>=0&&a<e.length&&!i.includes(a)&&o.push(e[a])}return o}static getPrevVisibleColumns(e,t,n,s,i){const o=[];let l=t;for(;l>=0&&o.length<n;){const a=_.getModelIndex(l,s);a>=0&&a<e.length&&!i.includes(a)&&o.unshift(e[a]),l-=1}return o}static getNextVisibleColumns(e,t,n,s,i){const o=[];let l=t;for(;l<e.length&&o.length<n;){const a=_.getModelIndex(l,s);a>=0&&a<e.length&&!i.includes(a)&&o.push(e[a]),l+=1}return o}static getColumnsToFetch(e,t,n){const s=[...t];return n.forEach(i=>{const o=e.find(({name:l})=>l===i);o!=null&&!t.includes(o)&&s.push(o)}),s}static getModelViewportColumns(e,t,n,s,i=[],o=[],l=0){if(t==null||n==null)return null;const a=Te.getVisibleColumnsInRange(e,t,n,s,i),d=a.length*l,h=Te.getPrevVisibleColumns(e,t-1,d,s,i),u=Te.getNextVisibleColumns(e,n+1,d,s,i),m=[...h,...a,...u];return Te.getColumnsToFetch(e,m,o)}static rangeSetFromRanges(e){const t=e.slice().sort((n,s)=>(N(n.startRow),N(s.startRow),n.startRow-s.startRow)).map(n=>{const{startRow:s,endRow:i}=n;return N(s),N(i),I.RangeSet.ofRange(s,i)});return I.RangeSet.ofRanges(t)}static isValidSnapshotRanges(e){if(e==null||e.length===0)return!1;const t=new Map;for(let i=0;i<e.length;i+=1){const o=e[i],l=`${o.startRow}:${o.endRow}`,a=`${o.startColumn}:${o.endColumn}`;t.has(l)||t.set(l,[]),t.get(l).push(a)}const n=[...t.keys()],s=t.get(n[0]).sort().join(",");for(let i=1;i<n.length;i+=1)if(t.get(n[i]).sort().join(",")!==s)return!1;return!0}static isValidIndex(e){return!Number.isInteger(e)||typeof e!="number"?!1:e>=0}static columnsFromRanges(e,t){if(e==null||e.length===0)return[];if(e[0].startColumn===null&&e[0].endColumn===null)return[...t];const n=new Set;for(let s=0;s<e.length;s+=1){const i=e[s];N(i.startColumn),N(i.endColumn);for(let o=i.startColumn??0;o<=(i.endColumn??t.length-1);o+=1)n.add(o)}return[...n].map(s=>t[s])}static snapshotDataToMatrix(e){const{columns:t,rows:n}=e,s=[];for(let i=0;i<n.length;i+=1){const o=n[i],l=[];for(let a=0;a<t.length;a+=1){const d=t[a],h=o.get(d);l.push(h)}s.push(l)}return s}static getModelRollupConfig(e,t,n){if((t?.columns?.length??0)===0)return null;const{columns:s=[],showConstituents:i=!0,showNonAggregatedColumns:o=!0,includeDescriptions:l=!0}=t??{},{aggregations:a=[]}=n??{},d=a.map(({operation:u,selected:m,invert:g})=>Cs.isRollupOperation(u)?[]:Cs.getOperationColumnNames(e,u,m,g)),h={};for(let u=0;u<a.length;u+=1)h[a[u].operation]=d[u];if(o){const u=new Set(e.map(m=>m.name).filter(m=>!s.includes(m)));if(d.forEach(m=>{m.forEach(g=>u.delete(g))}),u.size>0){const m=h[Le.FIRST]??[];h[Le.FIRST]=[...m,...u]}}return{groupingColumns:s,includeConstituents:i,includeDescriptions:l,aggregations:h}}static getPendingErrors(e){e.forEach((t,n)=>{if(!Te.isValidIndex(n))throw new Error(`Invalid rowIndex ${n}`);const{data:s}=t;s.forEach((i,o)=>{if(!Te.isValidIndex(o))throw new Error(`Invalid columnIndex ${o}`)})})}static getColumn(e,t){return t<e.length?e[t]:(Hi.error("Unable to retrieve column",t,">=",e.length),null)}static getColumnByName(e,t){const n=e.find(({name:s})=>s===t);return n==null&&Hi.error("Unable to retrieve column by name",t,e.map(({name:s})=>s)),n}static changeFilterColumnNamesToIndexes(e,t){return t.map(({name:n,filter:s})=>{const i=e.findIndex(o=>o.name===n);return i<0?null:[i,s]}).filter(n=>n!=null)}static combineFiltersFromList(e,t){t.sort((s,i)=>s.operator==="eq"&&i.operator!=="eq"?1:s.operator!=="eq"&&i.operator==="eq"?-1:s.startColumnIndex-i.startColumnIndex);let n="";for(let s=0;s<t.length;s+=1){const{text:i,value:o,operator:l}=t[s];if(o!==void 0){let a="";l!==void 0&&(o==null&&l==="eq"?a="=":l!=="eq"&&(l==="startsWith"||l==="endsWith"?a="*":a=F.getFilterOperatorString(l)));let d=`${a}${i}`;l==="startsWith"&&(d=`${i}${a}`),e!=null&&o!==null&&F.isCharType(e)&&(d=`${a}${String.fromCharCode(parseInt(i,10))}`),s!==0&&(n+=l==="eq"?" || ":" && "),n+=d}}return n}static parseColumnHeaderGroups(e,t){let n=1;const s=new Map,i=new Map,o=t?.filter(({children:u})=>u.length>0);if(o.length===0)return{groups:[],maxDepth:n,parentMap:s,groupMap:i};const l=new Map(o.map(u=>[u.name,u])),a=new Set,d=u=>{const{name:m}=u;if(e.getColumnIndexByName(m)!=null)throw new Error(`Column header group has same name as column: ${m}`);const g=i.get(m);if(g)return g;const p=[];let C=1;u.children.forEach(b=>{if(a.has(b))throw new Error(`Column group child ${b} specified in multiple groups`);a.add(b);const w=l.get(b),S=e.getColumnIndexByName(b);if(w){const T=d(w);p.push(...T.childIndexes),C=Math.max(C,T.depth+1)}else if(S!=null)p.push(S),C=Math.max(C,1);else throw new Error(`Unknown child ${b} in group ${m}`)});const f=new dn({...u,depth:C,childIndexes:p.flat()});return i.set(m,f),u.children.forEach(b=>s.set(b,f)),n=Math.max(n,f.depth+1),f},h=new Set;return o.forEach(u=>{const{name:m}=u;if(h.has(m))throw new Error(`Duplicate column group name: ${m}`);h.add(m),d(u)}),i.forEach(u=>{u.setParent(s.get(u.name)?.name)}),{groups:[...i.values()],maxDepth:n,groupMap:i,parentMap:s}}static convertValueToText(e,t){if(t!=null&&F.isCharType(t)&&e!=null&&typeof e=="number")return String.fromCharCode(e);if(F.isDateType(t)&&iv(e)){const n=new Date(e.asDate()),s=n.getTimezoneOffset();return new Date(n.getTime()-s*60*1e3).toISOString().replace("T"," ").substring(0,23)}return e==null?"":`${e}`}}const Se=Te;const Ht=ne.module("IrisGridCopyHandler");class Me extends v.Component{static NO_PROMPT_THRESHOLD=1e4;static HIDE_TIMEOUT=3e3;static COPY_STATES={IDLE:"IDLE",CONFIRMATION_REQUIRED:"CONFIRMATION_REQUIRED",FETCH_IN_PROGRESS:"FETCH_IN_PROGRESS",FETCH_ERROR:"FETCH_ERROR",CLICK_REQUIRED:"CLICK_REQUIRED",DONE:"DONE"};static BUTTON_STATES={COPY:"COPY",FETCH_IN_PROGRESS:"FETCH_IN_PROGRESS",CLICK_TO_COPY:"CLICK_TO_COPY",RETRY:"RETRY"};static defaultProps={copyOperation:null,onEntering:()=>{},onEntered:()=>{},onExiting:()=>{},onExited:()=>{}};static getStatusMessageText(e,t){switch(e){case Me.COPY_STATES.CONFIRMATION_REQUIRED:return`Are you sure you want to copy ${t.toLocaleString()} rows to your clipboard?`;case Me.COPY_STATES.CLICK_REQUIRED:return`Fetched ${t.toLocaleString()} rows!`;case Me.COPY_STATES.FETCH_ERROR:return"Unable to copy data.";case Me.COPY_STATES.FETCH_IN_PROGRESS:return`Fetching ${t.toLocaleString()} rows for clipboard...`;case Me.COPY_STATES.DONE:return"Copied to Clipboard!";default:return""}}static getCopyButtonText(e){switch(e){case Me.BUTTON_STATES.FETCH_IN_PROGRESS:return"Fetching";case Me.BUTTON_STATES.CLICK_TO_COPY:return"Click to Copy";case Me.BUTTON_STATES.RETRY:return"Retry";default:return"Copy"}}constructor(e){super(e),this.handleBackgroundClick=this.handleBackgroundClick.bind(this),this.handleCancelClick=this.handleCancelClick.bind(this),this.handleCopyClick=this.handleCopyClick.bind(this),this.handleHideTimeout=this.handleHideTimeout.bind(this),this.state={error:void 0,copyState:Me.COPY_STATES.IDLE,buttonState:Me.BUTTON_STATES.COPY,isShown:!1,rowCount:0}}componentDidMount(){const{copyOperation:e}=this.props;e!=null&&this.startCopy()}componentDidUpdate(e){const{copyOperation:t}=this.props;e.copyOperation!==t&&this.startCopy()}componentWillUnmount(){this.stopCopy()}textData;hideTimer;fetchPromise;startCopy(){Ht.debug2("startCopy"),this.stopCopy();const{copyOperation:e}=this.props;if(e==null){Ht.debug2("No copy operation set, cancelling out"),this.setState({isShown:!1});return}const{ranges:t,error:n}=e;if(n!=null){Ht.debug("Showing copy error",n),this.setState({isShown:!0,copyState:Me.COPY_STATES.DONE,error:n}),this.startHideTimer();return}const s=te.rowCount(t);this.setState({rowCount:s,isShown:!0,error:void 0}),s>Me.NO_PROMPT_THRESHOLD?this.setState({buttonState:Me.BUTTON_STATES.COPY,copyState:Me.COPY_STATES.CONFIRMATION_REQUIRED}):this.startFetch()}stopCopy(){this.textData=void 0,this.stopFetch(),this.stopHideTimer()}handleBackgroundClick(){Ht.debug2("handleBackgroundClick");const{copyState:e}=this.state;e===Me.COPY_STATES.DONE&&this.setState({isShown:!1})}handleCancelClick(){Ht.debug2("handleCancelClick"),this.stopFetch(),this.setState({isShown:!1})}handleCopyClick(){Ht.debug2("handleCopyClick"),this.textData!=null?this.copyText(this.textData):this.startFetch()}handleHideTimeout(){Ht.debug2("handleHideTimeout"),this.stopHideTimer(),this.setState({isShown:!1})}copyText(e){Ht.debug2("copyText",e),this.textData=e,ho(e).then(()=>{this.setState({copyState:Me.COPY_STATES.DONE}),this.startHideTimer()},t=>{Ht.error("copyText error",t),this.setState({buttonState:Me.BUTTON_STATES.CLICK_TO_COPY,copyState:Me.COPY_STATES.CLICK_REQUIRED})})}startFetch(){this.stopFetch(),this.setState({buttonState:Me.BUTTON_STATES.FETCH_IN_PROGRESS,copyState:Me.COPY_STATES.FETCH_IN_PROGRESS});const{model:e,copyOperation:t}=this.props,{ranges:n,includeHeaders:s,userColumnWidths:i,movedColumns:o,formatValues:l}=t;Ht.debug("startFetch",n);const a=Se.getHiddenColumns(i);let d=_.getModelRanges(n,o);if(a.length>0){const u=a.map(te.makeColumn);d=te.subtractRangesFromRanges(d,u)}const h=l!=null&&l?(u,m)=>e.displayString(u,m.type,m.name):u=>`${u}`;this.fetchPromise=ye.makeCancelable(e.textSnapshot(d,s,h)),this.fetchPromise.then(u=>{this.fetchPromise=void 0,this.copyText(u)}).catch(u=>{u instanceof Hl?Ht.debug("User cancelled copy."):(Ht.error("Error fetching contents",u),this.fetchPromise=void 0,this.setState({buttonState:Me.BUTTON_STATES.RETRY,copyState:Me.COPY_STATES.FETCH_ERROR}))})}stopFetch(){this.fetchPromise&&(Ht.debug2("stopFetch"),this.fetchPromise.cancel(),this.fetchPromise=void 0)}startHideTimer(){this.stopHideTimer(),this.hideTimer=setTimeout(this.handleHideTimeout,Me.HIDE_TIMEOUT)}stopHideTimer(){this.hideTimer!=null&&(clearTimeout(this.hideTimer),this.hideTimer=void 0)}render(){const{onEntering:e,onEntered:t,onExiting:n,onExited:s}=this.props,{buttonState:i,copyState:o,isShown:l,rowCount:a,error:d}=this.state,h=o===Me.COPY_STATES.DONE?"fade":"copy-slide-up",u=Me.getCopyButtonText(i),m=d??Me.getStatusMessageText(o,a),g=o!==Me.COPY_STATES.DONE,p=i===Me.BUTTON_STATES.FETCH_IN_PROGRESS,C=o===Me.COPY_STATES.DONE;return r.jsxs(sa,{animation:h,isShown:l,className:Y("iris-grid-copy-handler",{"copy-done":C}),onClick:this.handleBackgroundClick,onEntering:e,onEntered:t,onExiting:n,onExited:s,children:[r.jsx("div",{className:"status-message",children:r.jsx("span",{children:m})}),r.jsx(Wt,{in:g,timeout:Je.transitionMs,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsxs("div",{className:"buttons-container",children:[r.jsx("button",{type:"button",className:"btn btn-outline-secondary btn-cancel",onClick:this.handleCancelClick,children:"Cancel"}),r.jsxs(B,{kind:p?"tertiary":"primary",className:Y("btn-copy",{"btn-spinner":p}),onClick:this.handleCopyClick,disabled:p,children:[p&&r.jsx(In,{}),u]})]})})]})}}const ov=Me;class lv extends v.PureComponent{static defaultProps={style:{},className:"",value:"",isAdvancedFilterSet:!1,onAdvancedFiltersTriggered:()=>{},onChange:()=>{},onDone:()=>{},onTab:()=>{},onContextMenu:()=>{},debounceMs:150};constructor(e){super(e);const{debounceMs:t}=e;this.debouncedSendUpdate=Ye(this.sendUpdate.bind(this),t),this.handleCancel=this.handleCancel.bind(this),this.handleChange=this.handleChange.bind(this),this.handleCommit=this.handleCommit.bind(this),this.handleFocus=this.handleFocus.bind(this),this.handleBlur=this.handleBlur.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.inputField=null;const{value:n}=e;this.initialValue=n,this.state={isChanged:!1,value:n}}componentDidMount(){this.inputField?.focus()}componentDidUpdate(e){const{debounceMs:t}=this.props;e.debounceMs!==t&&(this.debouncedSendUpdate.flush(),this.debouncedSendUpdate=Ye(this.sendUpdate.bind(this),t))}componentWillUnmount(){this.debouncedSendUpdate.cancel()}inputField;initialValue;debouncedSendUpdate;setValue(e){this.initialValue=e,this.setState({value:e})}focus(){this.inputField?.focus()}handleChange(e){const{value:t}=e.target;this.setState({value:t,isChanged:!0}),this.debouncedSendUpdate(t)}handleCancel(){this.debouncedSendUpdate.cancel();const{initialValue:e}=this,{isChanged:t}=this.state;t&&this.sendUpdate(e);const{onDone:n}=this.props;n()}handleCommit(e=!0,t=!0){this.debouncedSendUpdate.flush();const{onDone:n}=this.props;n(e,t)}handleFocus(){this.inputField?.select()}handleBlur(e){const{relatedTarget:t}=e;t!=null&&t.classList.contains("context-menu-container")?this.handleCommit(!1,!0):t!=null&&t.classList.contains("advanced-filter-button")?this.handleCommit(!1,!1):this.handleCommit(!0,!0)}handleTab(e=!1){this.debouncedSendUpdate.flush();const{onTab:t}=this.props;t(e)}handleKeyDown(e){switch(e.key){case"Escape":e.stopPropagation(),e.preventDefault(),this.handleCancel();break;case"Enter":e.stopPropagation(),e.preventDefault(),this.handleCommit();break;case"Tab":e.stopPropagation(),e.preventDefault(),this.handleTab(e.shiftKey);break}}handleContextMenu(e){const{onContextMenu:t}=this.props;t(e)}sendUpdate(e){const{onChange:t}=this.props;t(e)}render(){const{className:e,style:t,isAdvancedFilterSet:n,onAdvancedFiltersTriggered:s}=this.props,{value:i}=this.state;return r.jsxs("div",{style:t,className:"iris-grid-input-autosized-wrapper","data-value":i,children:[r.jsx("input",{ref:o=>{this.inputField=o},className:Y("iris-grid-input-field",e),type:"text",value:i,onBlur:this.handleBlur,onFocus:this.handleFocus,onChange:this.handleChange,onKeyDown:this.handleKeyDown,onContextMenu:this.handleContextMenu,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false"}),r.jsx("div",{className:"advanced-filter-button-container",children:r.jsx(B,{kind:"ghost",className:Y("btn-link-icon advanced-filter-button",{"filter-set":n}),onClick:s,onContextMenu:this.handleContextMenu,children:r.jsxs("div",{className:"fa-layers ",children:[r.jsx(ee,{icon:cr,className:"filter-solid"}),r.jsx(ee,{icon:dl,className:"filter-light"})]})})})]})}}const av=lv;class rv extends ei{irisGrid;constructor(e){super(),this.irisGrid=e}onDown(e){const{selectedRanges:t}=this.irisGrid.state;return e.key==="c"&&Ts.isModifierKeyDown(e)?(Se.isValidSnapshotRanges(t)?this.irisGrid.copyRanges(t):this.irisGrid.copyRanges(t,!1,!1,"Invalid copy ranges"),!0):!1}}const dv=rv,cv={TOGGLE_QUICK_FILTER:We.createAndAdd({id:"TABLE.TOGGLE_QUICK_FILTER",name:"Toggle Quick Filter",shortcut:[ve.CTRL,xe.F],macShortcut:[ve.CMD,xe.F]}),CLEAR_ALL_FILTERS:We.createAndAdd({id:"TABLE.CLEAR_ALL_FILTERS",name:"Clear All Table Filters",shortcut:[ve.CTRL,xe.E],macShortcut:[ve.CMD,xe.E]}),CLEAR_FILTERS:We.createAndAdd({id:"TABLE.CLEAR_FILTERS",name:"Clear Active Table Filters",shortcut:[ve.CTRL,ve.SHIFT,xe.E],macShortcut:[ve.CMD,ve.SHIFT,xe.E]}),REVERSE:We.createAndAdd({id:"TABLE.REVERSE",name:"Reverse",shortcut:[ve.CTRL,xe.I],macShortcut:[ve.CMD,xe.I]}),TOGGLE_SEARCH:We.createAndAdd({id:"TABLE.TOGGLE_SEARCH",name:"Toggle Search",shortcut:[ve.CTRL,ve.SHIFT,xe.F],macShortcut:[ve.CMD,ve.SHIFT,xe.F]}),GOTO_ROW:We.createAndAdd({id:"TABLE.GOTO_ROW",name:"Go to Row",shortcut:[ve.CTRL,xe.G],macShortcut:[ve.CMD,xe.G]})},hv={COMMIT:We.createAndAdd({id:"INPUT_TABLE.COMMIT",name:"Commit",shortcut:[ve.CTRL,xe.S],macShortcut:[ve.CMD,xe.S]}),DISCARD:We.createAndAdd({id:"INPUT_TABLE.DISCARD",name:"Discard",shortcut:[ve.CTRL,ve.ALT,xe.S],macShortcut:[ve.CMD,ve.OPTION,xe.S]})},uv={TABLE:cv,INPUT_TABLE:hv},Ut=uv;class mv extends ei{irisGrid;constructor(e){super(),this.irisGrid=e}onDown(e){if(Ut.TABLE.REVERSE.matchesEvent(e)){if(!this.irisGrid.isReversible())return!1;const{reverseType:t}=this.irisGrid.state;return t===F.REVERSE_TYPE.NONE?this.irisGrid.reverse(F.REVERSE_TYPE.POST_SORT):this.irisGrid.reverse(F.REVERSE_TYPE.NONE),!0}return!1}}const gv=mv;class pv extends ei{irisGrid;constructor(e){super(),this.irisGrid=e}onDown(e){return Ut.TABLE.CLEAR_FILTERS.matchesEvent(e)?(this.irisGrid.clearAllFilters(),!0):!1}}const fv=pv;class Cv extends ht{irisGrid;constructor(e){super(850),this.irisGrid=e}destroyColumnTooltip(){this.irisGrid.setState({overflowButtonTooltipProps:null})}setCursor(e){return this.isHoveringOverflowButton(e)?(this.cursor="pointer",{stopPropagation:!1,preventDefault:!1}):(this.cursor=null,!1)}getButtonPosition({x:e,y:t,column:n,row:s}){if(n==null||s==null)return null;const{renderer:i,grid:o,state:l,props:a}=this.irisGrid;if(!o)return null;const{metrics:d}=l,{model:h}=a,{canvasContext:u}=o,m=o.getTheme(),g={context:u,mouseX:e,mouseY:t,metrics:d,model:h,theme:m},{left:p,top:C,width:f,height:b}=i.getCellOverflowButtonPosition(g);return p==null||f==null||C==null||b==null?null:{left:p,top:C,width:f,height:b}}isHoveringOverflowButton(e){const{x:t,y:n}=e,{left:s,top:i,width:o,height:l}=this.getButtonPosition(e)??{};if(s==null||o==null||i==null||l==null)return!1;const{renderer:a,grid:d,state:h,props:u}=this.irisGrid;if(!d)return!1;const{metrics:m}=h,{model:g}=u,{canvasContext:p}=d,C=d.getTheme(),f={context:p,mouseX:t,mouseY:n,metrics:m,model:g,theme:C};return a.shouldRenderOverflowButton(f)&&t>=s&&t<=s+o&&n>=i&&n<=i+l}onMove(e){if(this.isHoveringOverflowButton(e)){const{overflowButtonTooltipProps:t}=this.irisGrid.state,n=this.getButtonPosition(e);st(t,n)||this.irisGrid.setState({overflowButtonTooltipProps:n})}else this.destroyColumnTooltip();return this.setCursor(e)}onWheel(e){return this.destroyColumnTooltip(),this.onMove(e)}onDown(e){this.destroyColumnTooltip();const{column:t,row:n}=e;return this.isHoveringOverflowButton(e)&&this.irisGrid.setState({showOverflowModal:!0,overflowText:this.irisGrid.getValueForCell(t,n)}),!1}onContextMenu(){return this.destroyColumnTooltip(),!1}onLeave(){return this.destroyColumnTooltip(),!1}}const bv=Cv;class Sv extends ht{constructor(e){super(),this.irisGrid=e,this.cursor=null}irisGrid;isActive(){const{isSelectingColumn:e}=this.irisGrid.props;return e}isValidColumn(e){if(e==null)return!1;const{columnSelectionValidator:t}=this.irisGrid.props;return t!=null?t(e):!0}updateColumnSelectionStatus(){const{columnSelectionValidator:e}=this.irisGrid.props;e?.(null)}getTableColumn(e){if(e==null)return null;const{model:t}=this.irisGrid.props,n=this.irisGrid.getModelColumn(e);return n==null?null:t.columns[n]}onMove(e){if(!this.isActive())return!1;const{columnAllowedCursor:t,columnNotAllowedCursor:n}=this.irisGrid.props,{column:s}=e,i=this.getTableColumn(s);return this.isValidColumn(i)?(this.cursor=t,this.irisGrid.setState({hoverSelectColumn:s})):(this.cursor=n,this.irisGrid.setState({hoverSelectColumn:null})),!0}onWheel(e){if(!this.isActive())return!1;const{columnAllowedCursor:t,columnNotAllowedCursor:n}=this.irisGrid.props,{column:s}=e,i=this.getTableColumn(s);return this.isValidColumn(i)?(this.cursor=t,this.irisGrid.setState({hoverSelectColumn:s})):(this.cursor=n,this.irisGrid.setState({hoverSelectColumn:null})),{preventDefault:!1,stopPropagation:!1}}onLeave(){return this.isActive()&&this.irisGrid.setState({hoverSelectColumn:null}),this.updateColumnSelectionStatus(),!1}onDown(){return this.isActive()}onClick(e){if(!this.isActive())return!1;const{column:t}=e,n=this.getTableColumn(t);return n!=null&&this.isValidColumn(n)&&this.irisGrid.selectColumn(n),!0}}const wv=Sv;class vv extends ht{constructor(e){super(),this.irisGrid=e}irisGrid;hideColumnTooltip(){const{tooltip:e}=this.irisGrid;e&&(e.stopTimer(),e.hide())}onDown(){return this.hideColumnTooltip(),!1}onContextMenu(){return this.hideColumnTooltip(),!1}onWheel(){return this.hideColumnTooltip(),!1}onLeave(e,t,n){const{relatedTarget:s}=n instanceof MouseEvent?n:n.nativeEvent,{tooltip:i}=this.irisGrid;if(!i)return!1;const o=i.popper.current;return o&&s instanceof Element&&o.element.contains(s)||this.hideColumnTooltip(),!1}onMove(e){const{column:t,row:n,columnHeaderDepth:s}=e,{shownColumnTooltip:i}=this.irisGrid.state;let o=null;return t!==null&&n===null&&s===0&&(o=t),o!==i&&this.irisGrid.setState({shownColumnTooltip:o}),!1}}const Tv=vv;class Hr extends v.Component{static defaultProps={formatString:"",forwardedProps:{menuItem:{},closeMenu(e){},iconElement:null},placeholder:"",title:"",onChange(e){}};constructor(e=Hr.defaultProps){super(e),this.handleInputChange=this.handleInputChange.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.inputRef=de.createRef()}inputRef;handleInputChange(){const{onChange:e}=this.props;this.inputRef.current&&e(this.inputRef.current.value)}closeContextMenu(){const{forwardedProps:e}=this.props,{closeMenu:t}=e;t(!0)}revertToDefault(){const{onChange:e}=this.props;e(null)}returnFocusToContextMenu(){const e=Tp.getClosestByClassName(this.inputRef.current,"context-menu-container");e instanceof HTMLElement&&e.focus()}handleKeyDown(e){switch(e.key){case"Enter":e.stopPropagation(),this.closeContextMenu();break;case"Escape":e.stopPropagation(),this.revertToDefault(),this.closeContextMenu();break;case"ArrowRight":case"ArrowLeft":e.stopPropagation();break;case"ArrowUp":case"ArrowDown":this.returnFocusToContextMenu();break;default:e.stopPropagation()}}render(){const{formatString:e,forwardedProps:t,placeholder:n,title:s}=this.props,{menuItem:{description:i},iconElement:o}=t;return r.jsxs("div",{className:"form-group flex-grow mb-0",children:[r.jsxs("div",{className:"custom-format-title",children:[r.jsx("span",{className:"icon",children:o}),r.jsxs("label",{className:"title mb-0",htmlFor:"custom-format-input",children:[s,i!=null&&r.jsx(ot,{children:i})]})]}),r.jsx("div",{className:"pl-2 pr-2 pb-2",children:r.jsx("input",{id:"custom-format-input",className:"form-control text-right mb-0",type:"text",defaultValue:e,ref:this.inputRef,placeholder:n,onKeyDown:this.handleKeyDown,onChange:this.handleInputChange,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false"})})]})}}const Ev=Hr;class yv{static isDefaultSelected(e){return!e||![nl.TYPE_CONTEXT_CUSTOM,nl.TYPE_CONTEXT_PRESET].includes(e.type)}static isCustomSelected(e){return e!=null&&e.type===nl.TYPE_CONTEXT_CUSTOM}static makeOption(e,t,n,s){return{title:e,description:e,group:n,format:t,isSelected:s}}static makeCustomFormatOption(e,t,n,s,i){return{title:e.label,description:e.label,format:e,group:t,isSelected:s,menuElement:r.jsx(Ev,{formatString:e.formatString,title:e.label,placeholder:n,onChange:i})}}}const Vt=yv;class ln{static dateGroup=10;static timeGroup=20;static dateTimeGroup=30;static getOptions(e,t){const n=new Date,i=[{group:ln.dateGroup,formatString:"yyyy-MM-dd"},{group:ln.dateGroup,formatString:"MM-dd-yyyy"},{group:ln.timeGroup,formatString:"HH:mm:ss"},{group:ln.timeGroup,formatString:"HH:mm:ss.SSS"},{group:ln.timeGroup,formatString:"HH:mm:ss.SSSSSSSSS"},{group:ln.dateTimeGroup,formatString:"yyyy-MM-dd HH:mm:ss"},{group:ln.dateTimeGroup,formatString:"yyyy-MM-dd HH:mm:ss.SSS"},{group:ln.dateTimeGroup,formatString:"yyyy-MM-dd HH:mm:ss.SSSSSSSSS"}].map(l=>{const a=ct.makeFormat("",l.formatString,ct.TYPE_CONTEXT_PRESET),d=e.getFormattedString(n,F.dataType.DATETIME,"",a);return Vt.makeOption(d,a,l.group,ct.isSameFormat(a,t))});return[Vt.makeOption("Default",null,ln.dateGroup,Vt.isDefaultSelected(t)),...i]}}const Rv=ln;class an{static defaultGroup=10;static presetGroup=20;static presetRoundGroup=30;static customGroup=40;static getOptions(e,t){const n=[{format:Ke.FORMAT_PERCENT,group:an.presetGroup},{format:Ke.FORMAT_BASIS_POINTS,group:an.presetGroup},{format:Ke.FORMAT_MILLIONS,group:an.presetGroup},{format:Ke.FORMAT_SCIENTIFIC_NOTATION,group:an.presetGroup},{format:Ke.FORMAT_ROUND,group:an.presetRoundGroup},{format:Ke.FORMAT_ROUND_TWO_DECIMALS,group:an.presetRoundGroup},{format:Ke.FORMAT_ROUND_FOUR_DECIMALS,group:an.presetRoundGroup}],s=Vt.makeOption("Default",null,an.defaultGroup,Vt.isDefaultSelected(e)),i=n.map(d=>Vt.makeOption(d.format.label,d.format,d.group,Ke.isSameFormat(d.format,e))),o=Vt.isCustomSelected(e),l=o?e:Ke.makeCustomFormat(),a=Vt.makeCustomFormatOption(l,an.customGroup,Ke.DEFAULT_FORMAT_STRING,o,d=>{if(d!=null){const h=Ke.makeCustomFormat(d);Ke.isValid(h)&&t(h)}else t(null)});return[s,...i,a]}}const xv=an;class fi{static defaultGroup=10;static presetGroup=20;static customGroup=30;static getOptions(e,t){const n=[{format:dt.FORMAT_MILLIONS,group:fi.presetGroup},{format:dt.FORMAT_SCIENTIFIC_NOTATION,group:fi.presetGroup}],s=Vt.makeOption("Default",null,fi.defaultGroup,Vt.isDefaultSelected(e)),i=n.map(d=>Vt.makeOption(d.format.label,d.format,d.group,dt.isSameFormat(d.format,e))),o=Vt.isCustomSelected(e),l=o?e:dt.makeCustomFormat(),a=Vt.makeCustomFormatOption(l,fi.customGroup,dt.DEFAULT_FORMAT_STRING,o,d=>{if(d!=null){const h=dt.makeCustomFormat(d);dt.isValid(h)&&t(h)}else t(null)});return[s,...i,a]}}const Dv=fi;const ec=ne.module("IrisGridContextMenuHandler"),Iv=150,tc="yyyy-MM-dd HH:mm:ss.SSSSSSSSS";class X extends ht{static GROUP_EDIT=ie.groups.high+10;static GROUP_HIDE_COLUMNS=ie.groups.high+25;static GROUP_FILTER=ie.groups.high+50;static GROUP_EXPAND_COLLAPSE=ie.groups.high+55;static GROUP_GOTO=ie.groups.high+60;static GROUP_SORT=ie.groups.high+75;static GROUP_COPY=ie.groups.high+100;static GROUP_FORMAT=ie.groups.high+150;static COLUMN_SORT_DIRECTION={ascending:"ASC",descending:"DESC",none:null};static getQuickFilterCondition(e,t,n){return e&&n==="&&"?e.and(t):e&&n==="||"?e.or(t):t}static getQuickFilterText(e,t,n){return n&&e!=null?`${e} ${n} ${t}`:t}static getOperatorAsText(e){return e==="&&"?"And":"Or"}static getNumberValueEqualsFilter(e,t){const n=e.filter();if(t===Number.POSITIVE_INFINITY)return I.FilterCondition.invoke("isInf",n).and(n.greaterThan(I.FilterValue.ofNumber(0)));if(t===Number.NEGATIVE_INFINITY)return I.FilterCondition.invoke("isInf",n).and(n.lessThan(I.FilterValue.ofNumber(0)));if(Number.isNaN(t))return I.FilterCondition.invoke("isNaN",n);const s=X.getFilterValueForNumberOrChar(e.type,t);return n.eq(s)}static getFilterValueForNumberOrChar(e,t){return F.isCharType(e)?I.FilterValue.ofString(String.fromCharCode(t)):I.FilterValue.ofNumber(t)}static getRowOptionFormatted(e,t,n=30){return`${e} "${fs.truncate(t,n-e.length-3)}"`}irisGrid;debouncedUpdateCustomFormat;constructor(e){super(),this.debouncedUpdateCustomFormat=Ye(e.handleFormatSelection,Iv),this.irisGrid=e}componentWillUnmount(){this.debouncedUpdateCustomFormat.flush()}getHeaderActions(e,t){const{irisGrid:n}=this,{column:s}=t;N(s);const{model:i}=n.props,{columns:o}=i,l=o[e],a=[],{metrics:d,reverseType:h,quickFilters:u,advancedFilters:m,searchFilter:g}=n.state,p=n.getTheme();N(d);const{filterIconColor:C,filterBarActiveColor:f,contextMenuSortIconColor:b,contextMenuReverseIconColor:w}=p,S=i.sort,T=F.getSortForColumn(S,l.name),y=h!==F.REVERSE_TYPE.NONE,{userColumnWidths:E}=d,R=[...E.values()].some(M=>M===0),x=i.getColumnHeaderParentGroup(e,0)===void 0&&!(je(i)&&i.hasExpandableRows),D=i.isColumnFrozen(e);return a.push({title:"Hide Column",group:X.GROUP_HIDE_COLUMNS,action:()=>{this.irisGrid.hideColumnByVisibleIndex(s)}}),a.push({title:D?"Unfreeze Column":"Freeze Column",group:X.GROUP_HIDE_COLUMNS,disabled:!x,action:()=>{D?this.irisGrid.unFreezeColumnByColumnName(l.name):this.irisGrid.freezeColumnByColumnName(l.name)},order:10}),a.push({title:"Show All Columns",group:X.GROUP_HIDE_COLUMNS,action:()=>{this.irisGrid.showAllColumns()},disabled:!R}),a.push({title:"Quick Filters",icon:Mn,iconColor:f,shortcut:Ut.TABLE.TOGGLE_QUICK_FILTER,group:X.GROUP_FILTER,order:10,action:()=>{this.irisGrid.toggleFilterBar(s)}}),a.push({title:"Advanced Filters",icon:m.get(e)?cr:dl,iconColor:C,group:X.GROUP_FILTER,order:20,action:()=>{this.irisGrid.handleAdvancedMenuOpened(s)}}),a.push({title:"Clear Table Filters",group:X.GROUP_FILTER,order:40,shortcut:Ut.TABLE.CLEAR_FILTERS,action:()=>{this.irisGrid.clearAllFilters()},disabled:!(u.size>0||m.size>0||g!=null)}),a.push({title:"Sort by",icon:Mn,iconColor:b,group:X.GROUP_SORT,order:10,actions:this.sortByActions(l,e,T)}),a.push({title:"Add Additional Sort",disabled:T&&S.length===1||y&&S.length===1||T&&y&&S.length===2||S.length===0,group:X.GROUP_SORT,order:20,actions:this.additionalSortActions(l,e)}),a.push({title:"Clear Table Sorting",disabled:S.length===0||y&&S.length===1,group:X.GROUP_SORT,action:()=>{this.irisGrid.sortColumn(s,X.COLUMN_SORT_DIRECTION.none)},order:30}),a.push({title:h===F.REVERSE_TYPE.NONE?"Reverse Table":"Clear Reverse Table",icon:Mn,iconColor:w,group:X.GROUP_SORT,order:40,disabled:!i.isReversible,shortcut:Ut.TABLE.REVERSE,action:()=>{h===F.REVERSE_TYPE.NONE?this.irisGrid.reverse(F.REVERSE_TYPE.POST_SORT):this.irisGrid.reverse(F.REVERSE_TYPE.NONE)}}),a.push({title:"Copy Column Name",group:X.GROUP_COPY,action:()=>{ho(i.textForColumnHeader(e)??"").catch(M=>ec.error("Unable to copy header",M))}}),F.isDateType(l.type)?a.push({title:"Date/Time Format",group:X.GROUP_FORMAT,actions:this.dateFormatActions(l)}):F.isNumberType(l.type)&&a.push({title:"Number Format",group:X.GROUP_FORMAT,actions:this.numberFormatActions(l)??void 0}),a}getCellActions(e,t,n){N(e);const{irisGrid:s}=this,{column:i,row:o}=n,{model:l,canCopy:a}=s.props,{columns:d}=l,h=s.getModelRow(o);N(h);const u=l.valueForCell(e,h),m=l.textForCell(e,h),g=d[e],p=[],{quickFilters:C}=s.state,f=s.getTheme(),{filterIconColor:b}=f,{settings:w}=s.props,S=new ct({timeZone:w?.timeZone,showTimeZone:!1,showTSeparator:!0,defaultDateTimeFormatString:tc}),T=new ct({timeZone:w?.timeZone,showTimeZone:w?.showTimeZone,showTSeparator:w?.showTSeparator,defaultDateTimeFormatString:tc});if(g==null||o==null)return p;if(l.isFilterable(e)){const E={title:"Filter by Value",icon:Mn,iconColor:b,group:X.GROUP_FILTER,order:10,actions:[]};if(u==null)C.get(e)&&E.actions.push({title:"And",actions:this.nullFilterActions(g,C.get(e),"&&"),order:2,group:ie.groups.high}),E.actions.push(...this.nullFilterActions(g));else if(F.isBooleanType(g.type))C.get(e)&&E.actions.push({title:"Or",actions:this.booleanFilterActions(g,m,C.get(e),"||"),order:2,group:ie.groups.high}),E.actions.push(...this.booleanFilterActions(g,m));else if(F.isNumberType(g.type)||F.isCharType(g.type)){N(e);const R=F.isCharType(g.type)?String.fromCharCode(u):`${u}`;C.get(e)&&E.actions.push({title:"And",actions:this.numberFilterActions(g,R,u,C.get(e),"&&"),order:2,group:ie.groups.high}),E.actions.push(...this.numberFilterActions(g,R,u,C.get(e)))}else if(F.isDateType(g.type)){const R=S.format(u),x=T.format(u);C.get(e)&&E.actions.push({title:"And",actions:this.dateFilterActions(g,R,x,u,C.get(e),"&&"),order:2,group:ie.groups.high}),E.actions.push(...this.dateFilterActions(g,R,x,u,C.get(e)))}else C.get(e)&&E.actions.push({title:"And",actions:this.stringFilterActions(g,m,u,C.get(e),"&&"),order:2,group:ie.groups.high}),E.actions.push(...this.stringFilterActions(g,m,u));E.actions!=null&&E.actions.length>0&&p.push(E)}if(je(l)&&l.isRowExpandable(h)){const E=l.groupedColumns.length>0?l.depthForRow(h)-1:0,x=l.valueForCell(E,h)==null?"null":l.textForCell(E,h);p.push({title:X.getRowOptionFormatted(l.isRowExpanded(h)?"Collapse":"Expand",x),group:X.GROUP_EXPAND_COLLAPSE,order:10,action:()=>{l.setRowExpanded(h,!l.isRowExpanded(h))}}),l.isExpandAllAvailable===!0&&p.push({title:X.getRowOptionFormatted("Expand All in",x),group:X.GROUP_EXPAND_COLLAPSE,order:20,action:()=>{l.setRowExpanded(h,!0,!0)}})}je(l)&&l.hasExpandableRows&&l.isExpandAllAvailable===!0&&(p.push({title:"Expand Entire Table",group:X.GROUP_EXPAND_COLLAPSE,order:30,action:()=>{l.expandAll()}}),p.push({title:"Collapse Entire Table",group:X.GROUP_EXPAND_COLLAPSE,order:40,action:()=>{l.collapseAll()}}));const y={title:"Go to",iconColor:b,shortcut:Ut.TABLE.GOTO_ROW,group:X.GROUP_GOTO,order:10,action:()=>this.irisGrid.toggleGotoRow(`${o+1}`,`${u}`,g.name)};return p.push(y),a&&(p.push({title:"Copy Cell",group:X.GROUP_COPY,order:10,action:()=>{s.copyCell(i,o)}}),p.push({title:"Copy Cell Unformatted",group:X.GROUP_COPY,order:20,action:()=>{s.copyCell(i,o,!0)}})),p}onContextMenu(e,t,n){const{irisGrid:s}=this,{y:i,column:o,row:l,columnHeaderDepth:a}=e,d=s.getModelColumn(o),h=s.getModelRow(l),{model:u,canCopy:m}=s.props,{columns:g}=u,{metrics:p,isFilterBarShown:C,quickFilters:f,advancedFilters:b,selectedRanges:w}=s.state;N(p);const{columnHeaderHeight:S,gridY:T,columnHeaderMaxDepth:y}=p,E=[];if(d!=null&&h!=null){const R=u.valueForCell(d,h),x=u.textForCell(d,h),D=g[d],{onContextMenu:M}=s.props;D!=null&&E.push(M({model:u,value:R,valueText:x,column:D,rowIndex:l,columnIndex:o,modelRow:h,modelColumn:d}))}return d!=null&&u.isFilterable(d)&&E.push({title:"Clear Column Filter",group:X.GROUP_FILTER,order:30,action:()=>{this.irisGrid.removeColumnFilter(d)},disabled:!(f.has(d)||b.has(d))}),(C?i<=T:i<=S*y&&a===0)?d!=null&&E.push(...this.getHeaderActions(d,e)):(d!=null&&h!=null&&E.push(...this.getCellActions(d,t,e)),m&&w.length>0&&(E.push({title:"Copy Selection",shortcut:Kn.COPY,group:X.GROUP_COPY,order:30,action:()=>{s.copyRanges(w)}}),E.push({title:"Copy Selection w/ Headers",group:X.GROUP_COPY,order:40,action:()=>{s.copyRanges(w,!0)}})),Xe(u)&&u.isEditable&&w.length>0&&E.push({title:"Delete Selected Rows",group:X.GROUP_EDIT,order:50,action:()=>{this.irisGrid.deleteRanges(w)}})),E.length===0?!1:(N(s.gridWrapper),ie.triggerMenu(s.gridWrapper,n.clientX,n.clientY,E),!0)}dateFormatActions(e){const{model:t}=this.irisGrid.props,{formatter:n}=t,s=n.getColumnFormat(e.type,e.name),i=Rv.getOptions(n,s),o=[];for(let l=0;l<i.length;l+=1){const{description:a,format:d,group:h,isSelected:u,title:m}=i[l];o.push({title:m,description:a,icon:u?zn:void 0,group:h,order:l,action:()=>{const g=t.getColumnIndexByName(e.name);N(g),this.irisGrid.handleFormatSelection(g,d)}})}return o}numberFormatActions(e){const{model:t}=this.irisGrid.props,{formatter:n}=t,s=n.getColumnFormat(e.type,e.name);let i;const o=t.getColumnIndexByName(e.name);if(F.isDecimalType(e.type))i=xv.getOptions(s,a=>{N(o),this.debouncedUpdateCustomFormat(o,a)});else if(F.isIntegerType(e.type))i=Dv.getOptions(s,a=>{N(o),this.debouncedUpdateCustomFormat(o,a)});else return ec.error("Invalid column type in numberFormatActions"),null;const l=[];for(let a=0;a<i.length;a+=1){const{format:d,isSelected:h}=i[a];l.push({...i[a],icon:h?zn:void 0,order:a,action:()=>{o===void 0&&d&&d.type===nl.TYPE_CONTEXT_CUSTOM||(N(o),this.irisGrid.handleFormatSelection(o,d))}})}return l}stringFilterActions(e,t,n,s,i){const o=I.FilterValue.ofString(n);let l=s;l||(l={filter:null,text:null});const{filter:a,text:d}=l,h=[],{model:u}=this.irisGrid.props,m=u.getColumnIndexByName(e.name);return N(m),h.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[i?X.getOperatorAsText(i):""," ",'"',t,'"']}),order:1,group:ie.groups.high}),h.push({title:"text is exactly",description:`Show only rows where ${e.name} is ${n} (case sensitive)`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(a,e.filter().eq(o),i),X.getQuickFilterText(d,`=${t}`,i))},order:10,group:ie.groups.low}),h.push({title:"text is not exactly",description:`Show only rows where ${e.name} is not ${t} (case sensitive)`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(a,e.filter().notEq(o),i),X.getQuickFilterText(d,`!=${t}`,i))},order:20,group:ie.groups.low}),h.push({title:"text contains",description:`Show only rows where ${e.name} contains ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(a,e.filter().contains(o),i),X.getQuickFilterText(d,`~${t}`,i))},order:30,group:ie.groups.low}),h.push({title:"text does not contain",description:`Show only rows where ${e.name} does not contain ${n}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(a,e.filter().contains(o).not(),i),X.getQuickFilterText(d,`!~${t}`,i))},order:40,group:ie.groups.low}),h.push({title:"text starts with",description:`Show only rows where ${e.name} starts with ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(a,e.filter().invoke("startsWith",o),i),X.getQuickFilterText(d,`${t}*`,i))},order:50,group:ie.groups.low}),h.push({title:"text ends with",description:`Show only rows where ${e.name} ends with ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(a,e.filter().invoke("endsWith",o),i),X.getQuickFilterText(d,`*${t}`,i))},order:60,group:ie.groups.low}),h}numberFilterActions(e,t,n,s,i){const o=X.getFilterValueForNumberOrChar(e.type,n);let l=null,a=null;s&&(l=s.filter,a=s.text);const d=[],h=n!==Number.POSITIVE_INFINITY&&n!==Number.NEGATIVE_INFINITY&&!Number.isNaN(n),{model:u}=this.irisGrid.props,m=u.getColumnIndexByName(e.name);return N(m),d.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[i?X.getOperatorAsText(i):""," ",'"',t,'"']}),order:1,group:ie.groups.high}),d.push({title:"is equal to",description:`Show only rows where ${e.name} is ${t}`,action:()=>{const g=X.getNumberValueEqualsFilter(e,n);this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(l,g,i),X.getQuickFilterText(a,`=${t}`,i))},order:10,group:ie.groups.low}),d.push({title:"is not equal to",description:`Show only rows where ${e.name} is not ${t}`,action:()=>{const g=X.getNumberValueEqualsFilter(e,n).not();this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(l,g,i),X.getQuickFilterText(a,`!=${t}`,i))},order:20,group:ie.groups.low}),h&&!F.isCharType(e.type)&&(d.push({title:"greater than",description:`Show only rows where ${e.name} is greater than ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(l,e.filter().greaterThan(o),i),X.getQuickFilterText(a,`>${t}`,i))},order:30,group:ie.groups.low}),d.push({title:"greater than or equal to",description:`Show only rows where ${e.name} is greater than or equal to ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(l,e.filter().greaterThanOrEqualTo(o),i),X.getQuickFilterText(a,`>=${t}`,i))},order:40,group:ie.groups.low}),d.push({title:"less than",description:`Show only rows where ${e.name} is less than ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(l,e.filter().lessThan(o),i),X.getQuickFilterText(a,`<${t}`,i))},order:50,group:ie.groups.low}),d.push({title:"less than or equal to",description:`Show only rows where ${e.name} is less than or equal to ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(l,e.filter().lessThanOrEqualTo(o),i),X.getQuickFilterText(a,`<=${t}`,i))},order:60,group:ie.groups.low})),d}booleanFilterActions(e,t,n,s){const i=[],{model:o}=this.irisGrid.props,{filter:l,text:a}=n||{},d=o.getColumnIndexByName(e.name);return N(d),i.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[s?X.getOperatorAsText(s):""," ",'"',t??"null",'"']}),order:1,group:ie.groups.high}),i.push({title:"true",description:`Show only rows where ${e.name} is true`,action:()=>{this.irisGrid.setQuickFilter(d,X.getQuickFilterCondition(l,e.filter().isTrue(),s),X.getQuickFilterText(a,"true",s))},order:10,group:ie.groups.low}),i.push({title:"false",description:`Show only rows where ${e.name} is false`,action:()=>{this.irisGrid.setQuickFilter(d,X.getQuickFilterCondition(l,e.filter().isFalse(),s),X.getQuickFilterText(a,"false",s))},order:20,group:ie.groups.low}),i.push({title:"is null",description:`Show only rows where ${e.name} is null`,action:()=>{this.irisGrid.setQuickFilter(d,X.getQuickFilterCondition(l,e.filter().isNull(),s),X.getQuickFilterText(a,"null",s))},order:30,group:ie.groups.low}),i.push({title:"is not null",description:`Show only rows where ${e.name} is not null`,action:()=>{this.irisGrid.setQuickFilter(d,X.getQuickFilterCondition(l,e.filter().isNull().not(),s),X.getQuickFilterText(a,"!null",s))},order:40,group:ie.groups.low}),i}dateFilterActions(e,t,n,s,i,o){const l=I.FilterValue.ofNumber(s);let a=null,d=null;i&&(a=i.filter,d=i.text);const{model:h}=this.irisGrid.props,u=h.getColumnIndexByName(e.name);N(u);const m=[];return m.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[o?X.getOperatorAsText(o):""," ",'"',n,'"']}),order:1,group:ie.groups.high}),m.push({title:"date is",description:`Show only rows where ${e.name} is ${n}`,action:()=>{this.irisGrid.setQuickFilter(u,X.getQuickFilterCondition(a,e.filter().eq(l),o),X.getQuickFilterText(d,`=${t}`,o))},order:10,group:ie.groups.low}),m.push({title:"date is not",description:`Show only rows where ${e.name} is not ${n}`,action:()=>{this.irisGrid.setQuickFilter(u,X.getQuickFilterCondition(a,e.filter().notEq(l),o),X.getQuickFilterText(d,`!=${t}`,o))},order:20,group:ie.groups.low}),m.push({title:"date is before",description:`Show only rows where ${e.name} is before ${n}`,action:()=>{this.irisGrid.setQuickFilter(u,X.getQuickFilterCondition(a,e.filter().lessThan(l),o),X.getQuickFilterText(d,`<${t}`,o))},order:30,group:ie.groups.low}),m.push({title:"date is before or equal",description:`Show only rows where ${e.name} is before or equal to ${n}`,action:()=>{this.irisGrid.setQuickFilter(u,X.getQuickFilterCondition(a,e.filter().lessThanOrEqualTo(l),o),X.getQuickFilterText(d,`<=${t}`,o))},order:40,group:ie.groups.low}),m.push({title:"date is after",description:`Show only rows where ${e.name} is greater than ${n}`,action:()=>{this.irisGrid.setQuickFilter(u,X.getQuickFilterCondition(a,e.filter().greaterThan(l),o),X.getQuickFilterText(d,`>${t}`,o))},order:50,group:ie.groups.low}),m.push({title:"date is after or equal",description:`Show only rows where ${e.name} is after or equal to ${n}`,action:()=>{this.irisGrid.setQuickFilter(u,X.getQuickFilterCondition(a,e.filter().greaterThanOrEqualTo(l),o),X.getQuickFilterText(d,`>=${t}`,o))},order:60,group:ie.groups.low}),m}nullFilterActions(e,t,n){let s=null,i=null;t&&(s=t.filter,i=t.text);const o=[],{model:l}=this.irisGrid.props,a=l.getColumnIndexByName(e.name);return N(a),o.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[n?X.getOperatorAsText(n):""," ",'"null"']}),order:1,group:ie.groups.high}),o.push({title:"is null",description:`Show only rows where ${e.name} is null`,action:()=>{this.irisGrid.setQuickFilter(a,X.getQuickFilterCondition(s,e.filter().isNull(),n),X.getQuickFilterText(i,"null",n))},order:10,group:ie.groups.low}),o.push({title:"is not null",description:`Show only rows where ${e.name} is not null`,action:()=>{this.irisGrid.setQuickFilter(a,X.getQuickFilterCondition(s,e.filter().isNull().not(),n),X.getQuickFilterText(i,"!null",n))},order:20,group:ie.groups.low}),o}sortByActions(e,t,n){const s=this.irisGrid.getTheme(),{contextMenuSortIconColor:i}=s,o=[{title:`${e.name} Ascending`,order:10,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.ascending)},icon:this.checkColumnSort(n,X.COLUMN_SORT_DIRECTION.ascending)?Mn:void 0,iconColor:i},{title:`${e.name} Descending`,order:20,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.descending)},icon:this.checkColumnSort(n,X.COLUMN_SORT_DIRECTION.descending)?Mn:void 0,iconColor:i},{title:"Remove Sort",order:50,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.none,!1,!0)},disabled:!n}];return F.isNumberType(e.type)&&(o.push({title:`ABS(${e.name}) Ascending`,order:30,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.ascending,!0)},icon:this.checkColumnSort(n,X.COLUMN_SORT_DIRECTION.ascending,!0)?Mn:void 0,iconColor:i}),o.push({title:`ABS(${e.name}) Descending`,order:40,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.descending,!0)},icon:this.checkColumnSort(n,X.COLUMN_SORT_DIRECTION.descending,!0)?Mn:void 0,iconColor:i})),o}additionalSortActions(e,t){const n=this.irisGrid.getTheme(),{contextMenuSortIconColor:s}=n,i=[{title:"Add Sort By",menuElement:r.jsxs("div",{className:"btn-context-menu menu-title",children:[r.jsx("span",{className:"icon",children:r.jsx(ee,{icon:Mn,style:{color:s??void 0}})}),r.jsx("span",{className:"title",children:"Add Additional Sort"}),r.jsx("span",{className:"shortcut",children:Ts.isMacPlatform()?"⌘Click":"Ctrl+Click"})]}),order:1},{title:`${e.name} Ascending`,order:10,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.ascending,!1,!0)}},{title:`${e.name} Descending`,order:20,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.descending,!1,!0)}}];return F.isNumberType(e.type)&&(i.push({title:`ABS(${e.name}) Ascending`,order:30,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.ascending,!0,!0)}}),i.push({title:`ABS(${e.name}) Descending`,order:40,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.descending,!0,!0)}})),i}checkColumnSort(e,t=null,n=!1){return e?e.direction===t&&e.isAbs===n:!1}}const Fv=X;class Nv extends ht{constructor(e){super(),this.irisGrid=e}irisGrid;onDoubleClick(e){const{column:t,row:n}=e;return n==null||t==null?!1:(this.irisGrid.selectData(t,n),!0)}}const kv=Nv;class Mv extends ht{constructor(e){super(),this.irisGrid=e}irisGrid;onDown(e){const{y:t,column:n,row:s}=e;if(n!==null&&s===null){const{isFilterBarShown:i,metrics:o}=this.irisGrid.state;if(!o)throw new Error("Metrics not set");const{columnHeaderMaxDepth:l}=o,a=this.irisGrid.getTheme();if(i&&a.columnHeaderHeight!=null&&a.filterBarHeight!=null&&t>a.columnHeaderHeight*l&&t<=a.columnHeaderHeight*l+a.filterBarHeight)return this.irisGrid.focusFilterBar(n),!0}return!1}onMove(e){const{y:t,column:n}=e,{isFilterBarShown:s,hoverAdvancedFilter:i,metrics:o}=this.irisGrid.state;if(!o)throw new Error("Metrics not set");const{columnHeaderMaxDepth:l}=o,a=this.irisGrid.getTheme();let d=null;return s&&a.columnHeaderHeight!=null&&a.filterBarHeight!=null&&n!==null&&t>=a.columnHeaderHeight*l&&t<=a.columnHeaderHeight*l+a.filterBarHeight&&(d=n),d!==i&&this.irisGrid.setState({hoverAdvancedFilter:d}),!1}onLeave(e){const{column:t}=e,{hoverAdvancedFilter:n}=this.irisGrid.state;return n!==null&&t!==n&&this.irisGrid.setState({hoverAdvancedFilter:null}),!1}}const Lv=Mv;class Ov extends ht{irisGrid;constructor(e){super(750),this.irisGrid=e}destroyTooltip(){this.irisGrid.setState({expandCellTooltipProps:null})}setCursor(e,t){return Xa.isInTreeBox(e,t)?(this.cursor="pointer",{stopPropagation:!1,preventDefault:!1}):(this.cursor=null,!1)}getButtonPosition({x:e,y:t,column:n,row:s}){if(n==null||s==null)return null;const{renderer:i,grid:o,state:l,props:a}=this.irisGrid;if(!o)return null;const{metrics:d}=l,{model:h}=a,{canvasContext:u}=o,m=o.getTheme(),g={context:u,mouseX:e,mouseY:t,metrics:d,model:h,theme:m},p=je(h)?h.depthForRow(s):null,{left:C,top:f,width:b,height:w}=i.getExpandButtonPosition(g,p);return C==null||b==null||f==null||w==null?null:{left:C,top:f,width:b,height:w}}onMove(e,t){if(Xa.isInTreeBox(e,t)){const{expandCellTooltipProps:n}=this.irisGrid.state,{model:s}=this.irisGrid.props,i=this.getButtonPosition(e),{row:o}=e;N(o);const l=je(s)&&s.isRowExpanded(o);st(n,i)||this.irisGrid.setState({expandCellTooltipProps:i,expandTooltipDisplayValue:l?"collapse":"expand"})}else this.destroyTooltip();return this.setCursor(e,t)}onDown(){return this.destroyTooltip(),!1}onContextMenu(){return this.destroyTooltip(),!1}onWheel(){return this.destroyTooltip(),!1}onLeave(){return this.destroyTooltip(),!1}}const Av=Ov;class _v extends ht{constructor(e){super(),this.column=null,this.irisGrid=e}irisGrid;column;getColumnFromGridPoint(e){const{column:t,row:n,columnHeaderDepth:s}=e;return t!==null&&n===null&&s===0?t:null}onDown(e){return this.column=this.getColumnFromGridPoint(e),!1}onClick(e,t,n){const s=this.getColumnFromGridPoint(e);if(s!=null&&s===this.column){const i=Ts.isModifierKeyDown(n);return this.irisGrid.toggleSort(s,i),!0}return!1}}const Pv=_v;class jv extends ht{constructor(e){super(),this.irisGrid=e}onWheel(e,t,n){const{irisGrid:s}=this,{model:i}=s.props,{metrics:o,pendingRowCount:l}=s.state;N(o);const{bottom:a,rowCount:d,rowHeight:h}=o,{deltaY:u}=_.getScrollDelta(n);return Xe(i)&&i.isEditable&&a>=d-1&&u>0&&s.setState({pendingRowCount:l+Math.ceil(u/h)}),!1}}const Hv=jv;class Bv extends ht{irisGrid;currentLinkBox;constructor(e){super(),this.irisGrid=e}destroyTooltip(){this.irisGrid.setState({linkHoverTooltipProps:null})}isHoveringLink(e,t){const{column:n,row:s,x:i,y:o}=e,{renderer:l,metrics:a,props:d}=t,{model:h}=d;if(n==null||s==null||a==null)return this.currentLinkBox=void 0,!1;const{modelRows:u,modelColumns:m}=a,g=k(u,s),p=k(m,n),C=h.renderTypeForCell(p,g),f=l.getCellRenderer(C);if(!Cu(f))return!1;if(this.currentLinkBox!=null){const{x1:S,y1:T,x2:y,y2:E}=this.currentLinkBox;if(i>=S&&i<=y&&o>=T&&o<=E)return!0}const b=t.updateRenderState(),w=f.getTokenBoxesForVisibleCell(n,s,b);for(let S=0;S<w.length;S+=1)if(wl(w[S].token)){const T=_.translateTokenBox(w[S],a),{x1:y,x2:E,y1:R,y2:x}=T;if(i>=y&&i<=E&&o>=R&&o<=x)return this.currentLinkBox=T,!0}return this.currentLinkBox=void 0,!1}setCursor(e,t){return this.isHoveringLink(e,t)?(this.cursor="pointer",{stopPropagation:!1,preventDefault:!1}):(this.cursor=null,!1)}onMove(e,t){if(this.isHoveringLink(e,t)&&this.currentLinkBox!=null&&wl(this.currentLinkBox.token)){const{linkHoverTooltipProps:s}=this.irisGrid.state;if(this.currentLinkBox==null)return!1;const{x1:i,y1:o,x2:l,y2:a}=this.currentLinkBox,{href:d}=this.currentLinkBox.token,h=l-i,u=a-o,m={left:i,top:o+1,width:h,height:u};st(s,m)||this.irisGrid.setState({linkHoverTooltipProps:m,linkHoverDisplayValue:d})}else this.destroyTooltip();return this.setCursor(e,t)}onDown(){return this.destroyTooltip(),!1}onContextMenu(){return this.destroyTooltip(),!1}onWheel(){return this.destroyTooltip(),!1}onLeave(){return this.destroyTooltip(),!1}}const Uv=Bv,Vv=3e3;function $v({children:c=null,onEntering:e,onEntered:t,onExiting:n,onExited:s}){const[i,o]=v.useState(!1),l=v.useRef(),a=lr(c),d=v.useCallback(()=>{o(!0),l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{o(!1)},Vv)},[o,l]);return v.useEffect(()=>{a!==c&&c!=null&&d()},[c,a,o,d]),v.useEffect(()=>()=>l.current?clearTimeout(l.current):void 0,[]),r.jsx(sa,{className:"toast-bottom-bar",isShown:i,onEntering:e,onEntered:t,onExiting:n,onExited:s,children:c})}class Wv extends bo{getGridY(e){let t=super.getGridY(e);const{isFilterBarShown:n,theme:s,advancedFilters:i,quickFilters:o,sorts:l,reverseType:a}=e;return n?t+=s.filterBarHeight:(o!=null&&o.size>0||i!=null&&i.size>0)&&(t+=s.filterBarCollapsedHeight),a!==F.REVERSE_TYPE.NONE&&l!=null&&l.length>0&&(t+=s.reverseHeaderBarHeight),t}getUserColumnWidths(){return this.userColumnWidths}}const Gv=Wv,zv=1,Ru=de.memo(({model:c,modelColumns:e,top:t,bottom:n,left:s,right:i,filter:o,formatter:l,reverseType:a=F.REVERSE_TYPE.NONE,sorts:d,customColumns:h,movedColumns:u,hiddenColumns:m,alwaysFetchColumns:g,rollupConfig:p=null,totalsConfig:C=null,selectDistinctColumns:f=ke,pendingRowCount:b=0,pendingDataMap:w=Pn,frozenColumns:S,formatColumns:T,columnHeaderGroups:y})=>{const E=v.useMemo(()=>Se.getModelViewportColumns(e,s,i,u,m,g,zv),[e,s,i,u,m,g]);return v.useEffect(function(){c.filter=o},[c,o]),v.useEffect(function(){const x=[...d];a!==F.REVERSE_TYPE.NONE&&x.push(I.Table.reverse()),c.sort=x},[c,d,a]),v.useEffect(function(){c.formatter=l},[c,l]),v.useEffect(function(){c.isCustomColumnsAvailable&&(c.customColumns=h)},[c,h]),v.useEffect(function(){c.isFormatColumnsAvailable&&(c.formatColumns=T)},[c,T]),v.useEffect(function(){c.setViewport(t,n,E)},[c,t,n,E]),v.useEffect(function(){c.isRollupAvailable&&(c.rollupConfig=p)},[c,c.isRollupAvailable,p]),v.useEffect(function(){c.isSelectDistinctAvailable&&(c.selectDistinctColumns=f)},[c,f]),v.useEffect(function(){c.isTotalsAvailable&&(c.totalsConfig=C)},[c,c.isTotalsAvailable,C]),v.useEffect(function(){c.pendingRowCount=b},[c,b]),v.useEffect(function(){c.pendingDataMap=w},[c,w]),v.useEffect(function(){S&&c.updateFrozenColumns(S)},[c,S]),v.useEffect(function(){c.columnHeaderGroups=y},[c,y]),null});Ru.displayName="IrisGridModelUpdater";const Kv=Ru,Za=16,Yv=new Map([["sortUp",ug],["sortDown",mg],["caretDown",Un],["caretRight",Zc],["cellOverflow",gg]]),qv=pn(c=>{const e=Yv.get(c);if(e===void 0)throw new Error("Icon is undefined");const t=Array.isArray(e.icon[4])?e.icon[4][0]:e.icon[4],n=new Path2D(t),s=new Path2D,i={a:Za/e.icon[0],d:Za/e.icon[1]};return s.addPath(n,i),s},{max:1e3});function Ji(c){return qv(c)}class Xv{static drawTreeMarker(e,t,n,s,i,o,l){e.save();const{x1:a,y1:d}=i,h=Ji(l?"caretDown":"caretRight"),u=n+a-2,m=s+d+2.5;e.fillStyle=o,e.textAlign="center",e.translate(u,m),e.fill(h),e.restore()}}const xu=Xv;class Zv extends pu{drawCellContent(e,t,n,s){const{metrics:i,model:o}=t,{modelColumns:l,modelRows:a}=i,d=k(a,s),h=l.get(n);if(h===void 0)return;const u=o.valueForCell(h,d);if(F.isTextType(o.columns[h]?.type)&&(u===null||u==="")){const m=e.font;e.font=`italic ${m}`,super.drawCellContent(e,t,n,s),e.font=m;return}super.drawCellContent(e,t,n,s)}getTextRenderMetrics(e,t,n){const s=_.getTextRenderMetrics(e,t,n),{mouseX:i,mouseY:o,metrics:l,theme:a}=e;if(i==null||o==null)return s;const{column:d,row:h}=_.getGridPointFromXY(i,o,l);if(t===d&&n===h){const{left:u}=this.getCellOverflowButtonPosition(i,o,l,a);this.shouldRenderOverflowButton(e)&&u!=null&&(s.width=u-l.gridX-s.x)}return s}getCellOverflowButtonPosition(e,t,n,s){const i={left:null,top:null,width:null,height:null};if(e==null||t==null||n==null)return i;const{rowHeight:o,columnWidth:l,left:a,top:d}=_.getCellInfoFromXY(e,t,n);if(a==null||l==null||d==null)return i;const{width:h,verticalBarWidth:u}=n,{cellHorizontalPadding:m}=s,g=Za+2*m,p=o,f=Math.min(n.gridX+a+l,h-u)-g,b=n.gridY+d;return{left:f,top:b,width:g,height:p}}shouldRenderOverflowButton(e){const{context:t,mouseX:n,mouseY:s,metrics:i,model:o,theme:l}=e;if(n==null||s==null)return!1;const{row:a,column:d,modelRow:h,modelColumn:u}=_.getCellInfoFromXY(n,s,i);if(a==null||d==null||h==null||u==null||!F.isStringType(o.columns[u].type))return!1;const m=o.textForCell(u,h)??"",{width:g}=_.getTextRenderMetrics(e,d,a),p=i.fontWidths.get(l.font)??Zs;t.save(),t.font=l.font;const C=this.getCachedTruncatedString(t,m,g,p,o.truncationCharForCell(u,h));return t.restore(),m!==""&&C!==m}drawTreeMarker(e,t,n,s,i,o,l){xu.drawTreeMarker(e,t,n,s,i,o,l)}}const Qv=Zv;class Jv extends gu{drawTreeMarker(e,t,n,s,i,o,l){xu.drawTreeMarker(e,t,n,s,i,o,l)}}const eT=Jv,ya=Object.freeze({SORT_UP:"sortUp",SORT_DOWN:"sortDown",CARET_DOWN:"caretDown",CARET_RIGHT:"caretRight",CELL_OVERFLOW:"cellOverflow"}),nc=10;class yl extends fs{static isFilterValid(e,t){const n=e==null||e.filter!=null,s=t==null||t.filter!=null;return n&&s}textCellRenderer=new Qv;dataBarCellRenderer=new eT;getSortIcon(e){return e?e.direction===F.sortDirection.ascending?Ji(ya.SORT_UP):e.direction===F.sortDirection.descending?Ji(ya.SORT_DOWN):null:null}drawCanvas(e){super.drawCanvas(e),this.drawScrim(e)}drawGrid(e,t){super.drawGrid(e,t),this.drawCellOverflowButton(t)}drawGridLines(e,t){super.drawGridLines(e,t),this.drawGroupedColumnLine(e,t),this.drawPendingRowLine(e,t)}drawCellContent(e,t,n,s){const{metrics:i,model:o}=t,{modelColumns:l,modelRows:a}=i,d=l.get(n),h=k(a,s);if(d===void 0)return;const u=o.renderTypeForCell(d,h);this.getCellRenderer(u).drawCellContent(e,t,n,s)}getCellOverflowButtonPosition({mouseX:e,mouseY:t,metrics:n,theme:s}){return this.textCellRenderer.getCellOverflowButtonPosition(e,t,n,s)}shouldRenderOverflowButton(e){return this.textCellRenderer.shouldRenderOverflowButton(e)}drawCellOverflowButton(e){const{context:t,mouseX:n,mouseY:s,theme:i}=e;if(n==null||s==null||!this.shouldRenderOverflowButton(e))return;const{left:o,top:l,width:a,height:d}=this.getCellOverflowButtonPosition(e),{cellHorizontalPadding:h,overflowButtonColor:u,overflowButtonHoverColor:m}=i;t.save(),m!=null&&o!=null&&a!=null&&l!=null&&d!=null&&n>=o&&n<=o+a&&s>=l&&s<=l+d?t.fillStyle=m:u!=null&&(t.fillStyle=u);const g=Ji(ya.CELL_OVERFLOW);o!=null&&l!=null&&t.translate(o+h,l+2),t.fill(g),t.restore()}drawGroupedColumnLine(e,t){const{metrics:n,model:s,theme:i}=t,{groupedColumns:o}=s,{maxY:l,allColumnWidths:a,allColumnXs:d}=n;if(o.length===0||i.groupedColumnDividerColor==null)return;const h=o.length-1,u=d.get(h),m=a.get(h);if(u==null||m==null)return;const g=u+m+.5;e.strokeStyle=i.groupedColumnDividerColor,e.lineWidth=1,e.beginPath(),e.moveTo(g,0),e.lineTo(g,l),e.stroke()}drawPendingRowLine(e,t){const{metrics:n,model:s,theme:i}=t,{allRowYs:o,maxX:l}=n,{pendingRowCount:a}=s;if(a<=0)return;const d=s.rowCount-s.pendingRowCount-s.floatingBottomRowCount;let h=o.get(d);h!=null&&(h-=.5,e.save(),e.setLineDash([4,2]),e.strokeStyle=i.pendingTextColor,e.lineWidth=1,e.beginPath(),e.moveTo(0,h),e.lineTo(l,h),e.stroke(),e.restore())}drawMouseColumnHover(e,t){const{theme:n,metrics:s,hoverSelectColumn:i}=t;if(i==null||n.linkerColumnHoverBackgroundColor==null)return;const{allColumnWidths:o,allColumnXs:l,maxY:a}=s,d=k(l,i),h=k(o,i);e.fillStyle=n.linkerColumnHoverBackgroundColor,e.fillRect(d,0,h,a)}drawMouseRowHover(e,t){const{isSelectingColumn:n}=t;n||super.drawMouseRowHover(e,t)}drawScrim(e){const{context:t,loadingScrimProgress:n,metrics:s,theme:i}=e;if(n==null)return;const{width:o,height:l,gridY:a}=s,{scrimBlurSize:d,scrimColor:h}=i;t.save(),t.globalCompositeOperation="color",t.filter=`blur(${d}px)`,h!=null&&(t.fillStyle=h),t.beginPath(),t.rect(0,a,o,l-a),t.clip(),t.fillRect(-d,-d+a,d*2+o,(d*2+(l-a))*n),t.globalCompositeOperation="overlay",t.filter=`blur(${d}px) opacity(15%)`,t.fillRect(-d,-d+a,d*2+o,(d*2+(l-a))*n),t.restore()}drawColumnHeaders(e,t){super.drawColumnHeaders(e,t);const{theme:n,metrics:s,model:i,reverseType:o}=t,{columnHeaderHeight:l}=s;if(this.drawFilterHeaders(e,t),l<=0)return;const{sort:a}=i;if(a.length===1){const d=o!==F.REVERSE_TYPE.NONE;let h;d?h=n.headerReverseBarColor:h=n.headerSortBarColor,this.drawHeaderBar(e,t,h,d?n.reverseHeaderBarHeight:n.sortHeaderBarHeight)}else a.length>1&&(o!==F.REVERSE_TYPE.NONE&&this.drawHeaderBar(e,t,n.headerReverseBarColor,n.reverseHeaderBarHeight,!1),this.drawHeaderBar(e,t,n.headerSortBarColor,n.sortHeaderBarHeight))}drawHeaderBar(e,t,n,s,i=!0){const{theme:o,metrics:l,model:a}=t,{columnHeaderHeight:d,width:h}=l;let u=0;i||(u=s),e.fillStyle=o.headerBarCasingColor,e.fillRect(0,a.columnHeaderMaxDepth*d-s-2+u,h,s+2),e.fillStyle=n,e.fillRect(0,a.columnHeaderMaxDepth*d-s-1+u,h,s)}drawColumnHeadersAtDepth(e,t,n,s,i){const{metrics:o,model:l,isMenuShown:a}=t,{columnHeaderMaxDepth:d}=l,{width:h}=o,u={...s,maxX:i===d-1&&s.maxX===h?h-(a?0:30):s.maxX};super.drawColumnHeadersAtDepth(e,t,n,u,i)}drawColumnHeaderAtIndex(e,t,n,s){super.drawColumnHeaderAtIndex(e,t,n,s);const{metrics:i,model:o,theme:l}=t,{modelColumns:a,allColumnWidths:d,allColumnXs:h,gridX:u,columnHeaderHeight:m,fontWidths:g}=i,{headerHorizontalPadding:p}=l,C=k(d,n,0),f=k(h,n)+u,b=a.get(n);if(b==null)return;const w=o.columns[b]?.name;if(w==null)return;const S=F.getSortForColumn(o.sort,w);if(!S)return;const T=this.getSortIcon(S);if(!T)return;const y=o.textForColumnHeader(b);if(y===void 0)return;const E=g.get(e.font)??Zs;N(E);const R=y.length*E,x=u+f+R+p;let{maxX:D}=s;D-=p;const M=u+f+C-p-1,O=x>D?x+1:Math.min(D,M),H=S.direction===F.sortDirection.ascending?-6:-12,L=m*.5+H;e.save(),e.beginPath(),e.rect(f,0,C,m),e.clip(),e.fillStyle=l.headerSortBarColor,e.translate(O,L),e.fill(T),e.restore()}drawFilterHeaders(e,t){const{isFilterBarShown:n,quickFilters:s,advancedFilters:i}=t;n?this.drawExpandedFilterHeaders(e,t):(s!=null&&s.size>0||i!=null&&i.size>0)&&this.drawCollapsedFilterHeaders(e,t)}drawExpandedFilterHeaders(e,t){const{metrics:n,model:s,theme:i,quickFilters:o,advancedFilters:l}=t,{filterBarHeight:a}=i;if(a<=0)return;const{gridX:d,gridY:h,maxX:u,modelColumns:m,visibleColumns:g,allColumnWidths:p,allColumnXs:C}=n,f=h-a;e.save(),e.font=i.font,e.textAlign="left",o!=null&&o.size>0||l!=null&&l.size>0?e.fillStyle=i.filterBarExpandedActiveBackgroundColor:e.fillStyle=i.filterBarExpandedBackgroundColor,e.fillRect(d,f,u,a-1),e.fillStyle=i.headerBarCasingColor,e.fillRect(d,f+a-1,u,1);const b=f;e.strokeStyle=i.filterBarSeparatorColor,e.beginPath();for(let w=0;w<g.length;w+=1){const S=g[w],T=k(m,S),y=k(C,S),E=k(p,S);if(s.isFilterable(T)&&E>0){const R=d+(y??0);e.rect(R+.5,b+.5,E,a-2)}}e.stroke();for(let w=0;w<g.length;w+=1){const S=g[w],T=k(p,S),E=k(C,S)+d;this.drawExpandedFilterHeader(e,t,S,E,T)}e.restore()}drawExpandedFilterHeader(e,t,n,s,i){if(i<=0)return;const{metrics:o,theme:l,quickFilters:a,advancedFilters:d}=t,{modelColumns:h,gridY:u}=o,{filterBarHeight:m,filterBarExpandedActiveCellBackgroundColor:g,filterBarErrorColor:p,filterBarHorizontalPadding:C,headerColor:f}=l,b=u-m,w=h.get(n);if(w===void 0)return;const S=a.get(w),T=d.get(w);if(S==null&&T==null)return;let y=null;if(S!=null){const{text:R}=S;if(y=R,y||(y=F.getFilterText(S.filter)),y!=null){const{fontWidths:x}=o;let D=x.get(e.font);(D==null||D===0)&&(D=e.measureText("8").width,D||(D=10));const M=(i-C*2)/D;M<=0?y="":y.length>M&&(y=`${y.substring(0,M-1)}…`)}}if(e.save(),yl.isFilterValid(T,S)&&g!=null)e.fillStyle=g,e.fillRect(s+1,b+1,i-1,m-3);else if(p!=null){e.fillStyle=p,e.lineWidth=2,e.strokeStyle=p;const R=s+2,x=b+2,D=i-3,M=m-5;e.strokeRect(R,x,D,M)}if(y!=null&&y!==""){const R=s+C,x=b+m*.5+1;e.fillStyle=f,e.fillText(y,R,x)}e.restore()}drawCollapsedFilterHeaders(e,t){const{metrics:n,theme:s}=t,{headerSeparatorColor:i,filterBarCollapsedHeight:o}=s;if(o<=0)return;const{gridX:l,gridY:a,maxX:d,visibleColumns:h,allColumnWidths:u,allColumnXs:m}=n,g=a-o;e.save(),e.fillStyle=i,e.fillRect(l,g,d,o);for(let p=0;p<h.length;p+=1){const C=h[p],f=u.get(C),b=m.get(C);if(b!=null&&f!=null){const w=b+l;this.drawCollapsedFilterHeader(e,t,C,w,f)}}e.restore()}drawCollapsedFilterHeader(e,t,n,s,i){if(i<=0)return;const{metrics:o,theme:l,quickFilters:a,advancedFilters:d}=t,{modelColumns:h,gridY:u}=o,m=h.get(n);if(m===void 0)return;const g=a.get(m),p=d.get(m),{filterBarCollapsedHeight:C,filterBarActiveColor:f,filterBarActiveBackgroundColor:b,filterBarErrorColor:w}=l;e.save();const S=yl.isFilterValid(p,g);b!=null&&g==null&&p==null?e.fillStyle=b:f!=null&&S?e.fillStyle=f:w!=null&&(e.fillStyle=w);const T=s+1,y=u-C,E=i-1,R=C-1;e.fillRect(T,y,E,R),e.restore()}drawRowFooters(e,t){const{metrics:n,model:s,mouseX:i,mouseY:o,theme:l}=t,{gridY:a,gridX:d,maxX:h,modelRows:u,floatingTopHeight:m,floatingBottomHeight:g,floatingRows:p,rowFooterWidth:C,height:f,horizontalBarHeight:b,verticalBarWidth:w,allRowHeights:S,allRowYs:T,width:y}=n;if(C<=0||p.length===0)return;const{cellHorizontalPadding:E,floatingGridRowColor:R,floatingRowBackgroundColors:x,headerColor:D,rowHoverBackgroundColor:M}=l;e.translate(d,a),e.beginPath();const O=Math.min(h,y-C-w-d);e.fillStyle=x,m>0&&e.rect(O,0,C,m),g>0&&e.rect(O,f-a-b-g,C,g),e.fill();const H=i!=null&&o!=null&&i>=d&&i<=h+C?_.getRowAtY(o,n):null;if(M!=null&&H!==null&&p.includes(H)){e.fillStyle=M;const V=T.get(H),U=S.get(H);N(V),N(U),e.fillRect(O,V,C,U)}if(e.beginPath(),R!=null&&(e.strokeStyle=R),m>0&&(e.moveTo(O+.5,.5),e.lineTo(O+.5,m-.5)),g>0){const V=f-a-b-g;e.moveTo(O-.5,V+.5),e.lineTo(O-.5,V+g-.5)}e.stroke(),e.fillStyle=D,e.textAlign="left";const L=O+E;for(let V=0;V<p.length;V+=1){const U=p[V],j=S.get(U),P=T.get(U),Q=u.get(U);if(P!=null&&j!=null&&Q!=null){const $=P+j*.5;e.fillText(s.textForRowFooter(Q),L,$)}}e.translate(-d,-a)}getExpandButtonPosition({mouseX:e,mouseY:t,metrics:n,theme:s},i){const o={left:null,top:null,width:null,height:null};if(e==null||t==null||i==null||!n)return o;const{rowHeight:l,left:a,top:d}=_.getCellInfoFromXY(e,t,n);N(a),N(l),N(d);const{cellHorizontalPadding:h}=s,u=nc+2*h,m=Math.max(a+nc*i,n.gridX),g=n.gridY+d;return{left:m,top:g,width:u,height:l}}}const tT=yl,nT="12px Fira Sans, sans-serif",sT="#f0f0ee",iT="#1a171a",re={"grid-bg":"#211f22",font:nT,white:sT,black:iT,"header-bg":"#2d2a2e","header-color":"#f0f0ee","header-height":"30px","header-separator-color":"#211f22","header-separator-hover-color":"#929192","header-hidden-separator-hover-color":"#4878ea","header-sort-bar-color":"#aa9af4","header-reverse-bar-color":"#548d29","header-bar-casing-color":"#211f22","header-font":"600 12px Fira Sans, sans-serif","row-height":"19px","row-background-colors":"#373438 #2d2a2e","selection-color":"rgba(118, 217, 228, 0.09)","selection-outline-color":"#76d9e4","selection-outline-casing-color":"#211f22","row-hover-bg":"#4b494c","selected-row-hover-bg":"rgba(118, 217, 228, 0.25)","scroll-bar-active-selection-tick-color":"rgba(118, 217, 228, 0.5)","scroll-bar-bg":"#322f33","scroll-bar-hover-bg":"#373438","scroll-bar-casing-color":"#555356","scroll-bar-corner-color":"#322f33","scroll-bar-color":"#5b5a5c","scroll-bar-hover-color":"#929192","scroll-bar-active-color":"#c0bfbf","text-color":"#f0f0ee","hyperlink-color":"#4878ea","positive-number-color":"#9edc6f","negative-number-color":"#f95d84","zero-number-color":"#fcd65b","date-color":"#fcd65b","pending-text-color":"#fde38d","error-text-color":"#f95d84","null-string-color":"#929192","filter-bar-active-bg":"#425175","filter-bar-active-color":"#4878ea","filter-bar-expanded-bg":"#373438","filter-bar-expanded-active-bg":"#313849","filter-bar-expanded-active-cell-bg":"#374d80","filter-bar-separator-color":"#929192","filter-bar-error-color":"#f95d84","filter-icon-color":"#4878ea","scrim-color":"#211f22","context-menu-sort-icon-color":"#aa9af4","context-menu-reverse-icon-color":"#548d29","linker-column-hover-bg":"rgba(118, 217, 228, 0.09)","tree-line-color":"#5b5a5c","tree-marker-color":"#c0bfbf","tree-marker-hover-color":"#fcfcfa","grouped-column-divider-color":"#1a171a","floating-grid-row-color":"#555356","floating-row-background-colors":"#403e41","floating-divider-inner-color":"#403e41","floating-divider-outer-color":"#211f22","overflow-button-color":"#c0bfbf","overflow-button-hover-color":"#fcfcfa","zero-line-color":"#5b5a5c","positive-bar-color":"#9edc6f","negative-bar-color":"#f95d84"},oT=Object.freeze({backgroundColor:re["grid-bg"],white:re.white,black:re.black,font:re.font,headerBackgroundColor:re["header-bg"],headerColor:re["header-color"],headerSeparatorColor:re["header-separator-color"],headerSeparatorHoverColor:re["header-separator-hover-color"],headerHiddenSeparatorHoverColor:re["header-hidden-separator-hover-color"],headerSortBarColor:re["header-sort-bar-color"],headerReverseBarColor:re["header-reverse-bar-color"],headerBarCasingColor:re["header-bar-casing-color"],headerFont:re["header-font"],rowBackgroundColors:re["row-background-colors"],rowHoverBackgroundColor:re["row-hover-bg"],selectionColor:re["selection-color"],selectionOutlineColor:re["selection-outline-color"],selectionOutlineCasingColor:re["selection-outline-casing-color"],selectedRowHoverBackgroundColor:re["selected-row-hover-bg"],scrollBarBackgroundColor:re["scroll-bar-bg"],scrollBarHoverBackgroundColor:re["scroll-bar-hover-bg"],scrollBarCasingColor:re["scroll-bar-casing-color"],scrollBarCornerColor:re["scroll-bar-corner-color"],scrollBarColor:re["scroll-bar-color"],scrollBarHoverColor:re["scroll-bar-hover-color"],scrollBarActiveColor:re["scroll-bar-active-color"],scrollBarSelectionTickColor:re["selected-row-hover-bg"],scrollBarActiveSelectionTickColor:re["scroll-bar-active-selection-tick-color"],textColor:re["text-color"],hyperlinkColor:re["hyperlink-color"],positiveNumberColor:re["positive-number-color"],negativeNumberColor:re["negative-number-color"],zeroNumberColor:re["zero-number-color"],dateColor:re["date-color"],pendingTextColor:re["pending-text-color"],errorTextColor:re["error-text-color"],nullStringColor:re["null-string-color"],filterBarActiveBackgroundColor:re["filter-bar-active-bg"],filterBarExpandedBackgroundColor:re["filter-bar-expanded-bg"],filterBarExpandedActiveBackgroundColor:re["filter-bar-expanded-active-bg"],filterBarExpandedActiveCellBackgroundColor:re["filter-bar-expanded-active-cell-bg"],filterBarSeparatorColor:re["filter-bar-separator-color"],filterBarActiveColor:re["filter-bar-active-color"],filterBarErrorColor:re["filter-bar-error-color"],filterIconColor:re["filter-icon-color"],scrimColor:re["scrim-color"],contextMenuSortIconColor:re["context-menu-sort-icon-color"],contextMenuReverseIconColor:re["context-menu-reverse-icon-color"],allowRowResize:!1,autoSelectRow:!0,gridColumnColor:null,gridRowColor:null,groupedColumnDividerColor:re["grouped-column-divider-color"],columnHoverBackgroundColor:null,headerHorizontalPadding:12,scrollBarSize:13,scrollBarHoverSize:16,minScrollHandleSize:24,rowHeight:parseInt(re["row-height"],10)||19,columnWidth:100,rowHeaderWidth:0,rowFooterWidth:60,columnHeaderHeight:parseInt(re["header-height"],10)||30,filterBarHeight:30,filterBarCollapsedHeight:5,sortHeaderBarHeight:2,reverseHeaderBarHeight:4,filterBarHorizontalPadding:4,scrimBlurSize:25,minScrimTransitionTime:150,maxScrimTransitionTime:350,scrollSnapToRow:!0,linkerColumnHoverBackgroundColor:re["linker-column-hover-bg"],treeLineColor:re["tree-line-color"],treeMarkerColor:re["tree-marker-color"],treeMarkerHoverColor:re["tree-marker-hover-color"],floatingGridColumnColor:null,floatingGridRowColor:re["floating-grid-row-color"],floatingRowBackgroundColors:re["floating-row-background-colors"],floatingDividerInnerColor:re["floating-divider-inner-color"],floatingDividerOuterColor:re["floating-divider-outer-color"],overflowButtonColor:re["overflow-button-color"],overflowButtonHoverColor:re["overflow-button-hover-color"],zeroLineColor:re["zero-line-color"],positiveBarColor:re["positive-bar-color"],negativeBarColor:re["negative-bar-color"]}),sc=oT;const Ra=ne.module("ColumnStatistics"),lT={SIZE:"Number of Rows"};class Rl extends v.Component{static AUTO_GENERATE_LIMIT=1e5;static getStatsLabel(e){return lT[e]??e.split(" ").map(t=>t[0].toUpperCase()+t.substr(1).toLowerCase()).join(" ")}constructor(e){super(e),this.handleError=this.handleError.bind(this),this.handleGenerateStatistics=this.handleGenerateStatistics.bind(this),this.handleStatistics=this.handleStatistics.bind(this),this.cancelablePromise=null,this.state={error:null,loading:!1,statistics:null,numRows:0}}componentDidMount(){this.maybeGenerateStatistics()}componentWillUnmount(){this.cancelablePromise&&this.cancelablePromise.cancel()}cancelablePromise;maybeGenerateStatistics(){const{model:e}=this.props,t=e.rowCount-e.pendingRowCount;this.setState({numRows:t}),e.isColumnStatisticsAvailable?t<Rl.AUTO_GENERATE_LIMIT&&this.handleGenerateStatistics():this.setState({loading:!1})}handleGenerateStatistics(){this.setState({loading:!0});const{column:e,model:t}=this.props;this.cancelablePromise=ye.makeCancelable(t.columnStatistics(e)),this.cancelablePromise.then(this.handleStatistics).catch(this.handleError)}handleStatistics(e){Ra.debug("Received statistics",e);const{model:t,onStatistics:n}=this.props,s=[];e.statisticsMap.forEach((i,o)=>{s.push({operation:Rl.getStatsLabel(o),value:i,type:e.getType(o)})}),e.uniqueValues.forEach((i,o)=>{s.push({operation:o,className:"column-statistics-unique-value",value:i,type:"long"})}),this.setState({loading:!1,statistics:s,numRows:t.rowCount-t.pendingRowCount}),n()}handleError(e){if(e!=null&&ye.isCanceled(e)){Ra.debug("Called handleError on a cancelled promise result");return}Ra.error("Error generating statistics",e),this.setState({error:e,loading:!1,statistics:null})}render(){const{column:e,model:t}=this.props,{error:n,loading:s,statistics:i,numRows:o}=this.state,l=!s&&n==null&&i==null&&t.isColumnStatisticsAvailable,a=[],d=e.type.substring(e.type.lastIndexOf(".")+1),h=e.description===null?null:e.description;if(i!=null)for(let p=0;p<i.length;p+=1){const{operation:C,className:f,value:b,type:w}=i[p],S=w?t.displayString(b,w):t.displayString(b,e.type,e.name),T=r.jsxs(de.Fragment,{children:[r.jsx("div",{className:Y("column-statistic-operation",f),children:C}),r.jsx("div",{className:"column-statistic-value",children:S})]},C);a.push(T)}const u=je(t)&&t.hasExpandableRows?"Expanded Rows":"Number of Rows",m=t.displayString(o,"long"),g=t.getColumnIndexByName(e.name);return r.jsxs("div",{className:"column-statistics",children:[r.jsxs("div",{className:"column-statistics-title",children:[e.name,r.jsxs("span",{className:"column-statistics-type",children:[" (",d,")"]}),r.jsx(Bl,{className:"column-statistics-copy",tooltip:"Copy column name",copy:e.name})]}),h!=null&&r.jsx("div",{className:"column-statistics-description",children:h}),g!=null&&!t.isColumnMovable(g)&&r.jsxs("div",{className:"column-statistics-status",children:[r.jsx(ee,{icon:t.isColumnFrozen(g)?pg:fg,className:"mr-1"}),t.isColumnFrozen(g)?"Frozen":"Not movable"]}),r.jsxs("div",{className:"column-statistics-grid",children:[i==null&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"column-statistic-operation",children:u}),r.jsx("div",{className:"column-statistic-value",children:m})]}),a]}),l&&r.jsx(B,{kind:"ghost",className:"px-0",onClick:this.handleGenerateStatistics,children:"Generate Stats"}),n!=null&&r.jsx("div",{className:"error-message",children:`${n}`}),i&&!s&&r.jsx(B,{kind:"ghost",className:"px-0",onClick:this.handleGenerateStatistics,icon:r.jsx(ee,{icon:hr,className:"mr-1"}),children:"Refresh"}),s&&r.jsxs("div",{className:"column-statistics-loading",children:[r.jsx(In,{className:"mr-2"}),"Calculating Stats..."]})]})}}const aT=Rl;const $o=ne.module("AdvancedFilterCreatorFilterItem");class Br extends v.PureComponent{static getLabelForFilter(e,t){try{if(F.isNumberType(e)||F.isCharType(e))return fh(t);if(F.isTextType(e))return ph(t);if(F.isDateType(e))return Ch(t);if(F.isBooleanType(e))return Jf(t);throw new Error(`Unrecognized column type: ${e}`)}catch(n){return $o.warn(n),""}}constructor(e){super(e),this.handleDelete=this.handleDelete.bind(this),this.handleTypeChange=this.handleTypeChange.bind(this),this.handleValueChange=this.handleValueChange.bind(this),this.typeDropdown=null;const{value:t="",filterTypes:n,selectedType:s=n[0]}=e;this.state={selectedType:s,value:t}}componentDidMount(){this.typeDropdown?.focus()}componentDidUpdate(e){const{value:t,selectedType:n}=this.props;n!==void 0&&e.selectedType!==n&&this.setState({selectedType:n}),t!==void 0&&e.value!==t&&this.setState({value:t})}typeDropdown;handleTypeChange(e){const t=e.target.value;$o.debug2("typeChange",t),this.setState({selectedType:t});const{onChange:n}=this.props,{value:s}=this.state;s!=null&&s.length>0&&n(t,s)}handleValueChange(e){$o.debug2("valueChange");const{value:t}=e.target;this.setState({value:t});const{onChange:n}=this.props,{selectedType:s}=this.state;s!=null&&n(s,t)}handleDelete(){$o.debug("delete");const{onDelete:e}=this.props;e()}getCachedIsValid=ge((e,t,n,s)=>{try{return!n||F.makeAdvancedValueFilter(e,t,n,s)!=null}catch{return!1}});render(){const{column:e,filterTypes:t,formatter:n}=this.props,{selectedType:s,value:i}=this.state,o=!F.isBooleanType(e.type),l=[],a=this.getCachedIsValid(e,s,i,n.timeZone);for(let d=0;d<t.length;d+=1){const h=t[d],u=Br.getLabelForFilter(e.type,h),m=r.jsx("option",{value:h,children:u},h);l.push(m)}return r.jsx("div",{className:"advanced-filter-creator-filter-item",children:r.jsxs("div",{className:"form-row",children:[r.jsx("div",{className:"form-group col",children:r.jsx("select",{className:"form-control custom-select",value:s,onChange:this.handleTypeChange,ref:d=>{this.typeDropdown=d},children:l})}),o&&r.jsx("div",{className:"form-group col",children:r.jsx("div",{className:"input-group",children:r.jsx("input",{type:"text",className:Y("form-control",{error:!a}),placeholder:"Enter value",value:i,onChange:this.handleValueChange})})}),r.jsx("div",{className:"form-group col-1 px-0",children:r.jsx(B,{kind:"ghost",className:"w-100 h-100 p-0 m-0",onClick:this.handleDelete,icon:Gt,tooltip:"Remove Filter"})})]})})}}const rT=Br,ic=ne.module("AdvancedFilterCreatorSelectValueList");class xl extends v.PureComponent{static defaultProps={invertSelection:!0,selectedValues:[],onChange:()=>{}};static indexOf(e,t){for(let n=0;n<t.length;n+=1){const s=t[n];if(s===e||s!=null&&s.valueOf!=null&&e!=null&&e.valueOf!=null&&s.valueOf()===e.valueOf())return n}return-1}constructor(e){super(e),this.handleSelect=this.handleSelect.bind(this),this.handleViewportChange=this.handleViewportChange.bind(this),this.handleSelectionUpdate=this.handleSelectionUpdate.bind(this),this.handleTableUpdate=this.handleTableUpdate.bind(this),this.list=null;const{selectedValues:t}=this.props;this.state={itemCount:0,items:[],offset:0,selectedValues:t,isLoading:!0}}componentDidMount(){const{table:e}=this.props;e&&this.startListening(e)}componentDidUpdate(e){const{filters:t,invertSelection:n,selectedValues:s,table:i}=this.props;e.table!==i&&(e.table&&this.stopListening(e.table),i&&this.startListening(i),this.resetViewport()),e.invertSelection!==n&&this.setState({selectedValues:[]},this.handleSelectionUpdate),e.selectedValues!==s&&this.setState({selectedValues:s},this.handleSelectionUpdate),e.filters!==t&&(i?.applyFilter(t),this.resetViewport())}componentWillUnmount(){const{table:e}=this.props;e&&this.stopListening(e)}list;handleSelect(e,t){const{invertSelection:n}=this.props;let{selectedValues:s}=this.state;s=[...s];const i=xl.indexOf(t,s);i>=0?s.splice(i,1):s.push(t);let o=i<0;n&&(o=!o);const{offset:l}=this.state;let{items:a}=this.state;a=[...a];const d=e-l;d>=0&&d<a.length&&(a[d].isSelected=o),this.setState({items:a,selectedValues:s});const{onChange:h}=this.props;h(s,n)}handleViewportChange(e,t){this.updateViewport(e,t)}handleSelectionUpdate(){this.updateItemSelection()}handleTableUpdate(e){const{table:t,formatter:n}=this.props;if(!t)return;const s=e.detail,{offset:i}=s,o=[],l=t.columns[0];for(let d=0;d<s.rows.length;d+=1){const u=s.rows[d].get(l),m=n.getFormattedString(u,l.type,l.name),g=this.isValueSelected(u);o.push({displayValue:m,value:u,isSelected:g})}ic.debug2("Received table update:",i,o.length);const a=t.size;this.setState({itemCount:a,items:o,offset:i,isLoading:!1})}isValueSelected(e){const{invertSelection:t}=this.props,{selectedValues:n}=this.state,s=xl.indexOf(e,n);return t?s<0:s>=0}startListening(e){e.addEventListener(I.Table.EVENT_UPDATED,this.handleTableUpdate)}stopListening(e){e.removeEventListener(I.Table.EVENT_UPDATED,this.handleTableUpdate)}resetViewport(){this.list&&this.list.topRow!=null&&this.list.bottomRow!=null&&this.updateViewport(this.list.topRow,this.list.bottomRow,!0)}updateItemSelection(){let{items:e}=this.state;e=[...e];for(let t=0;t<e.length;t+=1){const n=e[t],{value:s}=n;n.isSelected=this.isValueSelected(s)}this.setState({items:e})}updateViewport(e,t,n=!1){const{table:s}=this.props;if(s==null)return;n&&this.setState({isLoading:!0});const i=t-e+1,o=Math.max(0,e-i*3),l=Math.max(o,t+i*3);ic.debug2("Setting viewport",o,",",l),s.setViewport(o,l)}render(){const{offset:e,isLoading:t,items:n,itemCount:s}=this.state;return r.jsxs("div",{className:"select-value-list-wrapper",children:[r.jsx(Om,{itemCount:s,items:n,offset:e,onSelect:this.handleSelect,onViewportChange:this.handleViewportChange,ref:i=>{this.list=i}}),r.jsx(Wt,{in:t,timeout:250,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:"loading-list",children:r.jsx(In,{className:"loading-spinner-large"})})})]})}}const dT=xl;class Ur extends v.PureComponent{static searchDebounceTime=250;static defaultProps={invertSelection:!0,selectedValues:[],onChange:()=>{},showSearch:!0};constructor(e){super(e),this.handleSelectAllClick=this.handleSelectAllClick.bind(this),this.handleClearAllClick=this.handleClearAllClick.bind(this),this.handleListChange=this.handleListChange.bind(this),this.handleSearchChange=this.handleSearchChange.bind(this),this.handleUpdateFilterTimeout=this.handleUpdateFilterTimeout.bind(this);const{invertSelection:t,selectedValues:n}=e;this.state={filters:[],invertSelection:t,selectedValues:n,searchText:""}}componentDidMount(){this.initSearchTable()}componentDidUpdate(e,t){const{invertSelection:n,selectedValues:s,table:i}=this.props;e.table!==i&&this.initSearchTable(),e.invertSelection!==n&&this.setState({invertSelection:n}),e.selectedValues!==s&&this.setState({selectedValues:s});const{table:o,searchText:l}=this.state;o!==t.table&&(t.table!=null&&t.table.close(),o!=null&&this.startUpdateFilterTimer()),l!==t.searchText&&this.startUpdateFilterTimer()}componentWillUnmount(){const{table:e}=this.state;e?.close(),this.searchTablePromise=void 0,this.stopUpdateFilterTimer()}searchTablePromise;updateFilterTimer;getColumnName(){const{table:e}=this.props;return e!=null?e.columns[0].name:""}getDisplayedValuesCount(){const{invertSelection:e,selectedValues:t,table:n}=this.state;return n==null?null:e?n.totalSize-t.length:t.length}getDisplayedValueText(){const e=this.getDisplayedValuesCount(),{table:t}=this.state,{formatter:n}=this.props;if(e!=null&&t!=null){const s=n.getFormattedString(e,"long"),i=n.getFormattedString(t.totalSize,"long");let o="";return e<1e6&&(o="Displaying "),`${o}${s} of ${i}`}return null}initSearchTable(){const{table:e}=this.props;if(e==null)return;const t=e.copy();this.searchTablePromise=t,this.searchTablePromise.then(n=>{this.searchTablePromise===t?(this.setState({table:n}),this.searchTablePromise=void 0):n.close()})}handleListChange(e,t){this.setState({selectedValues:e,invertSelection:t});const{onChange:n}=this.props;n(e,t)}handleSearchChange(e){const t=e.target.value;this.setState({searchText:t})}handleSelectAllClick(){this.resetSelection(!0)}handleClearAllClick(){this.resetSelection(!1)}handleUpdateFilterTimeout(){this.updateFilterTimer=void 0,this.updateTableFilter()}resetSelection(e){const t=[];this.setState({invertSelection:e,selectedValues:t});const{onChange:n}=this.props;n(t,e)}startUpdateFilterTimer(){this.stopUpdateFilterTimer(),this.updateFilterTimer=setTimeout(this.handleUpdateFilterTimeout,Ur.searchDebounceTime)}stopUpdateFilterTimer(){this.updateFilterTimer!=null&&(clearTimeout(this.updateFilterTimer),this.updateFilterTimer=void 0)}updateTableFilter(){const{table:e,searchText:t}=this.state,{timeZone:n}=this.props,s=e?.columns[0],i=[];if(s==null)return;let o;if(t.length>0){let l=null;F.isCharType(s.type)?l=F.makeQuickFilter(s,t):F.isTextType(s.type)?l=F.makeQuickFilter(s,`~${t}`,n):l=F.makeQuickFilter(s,`>=${t}`,n),l!=null?i.push(l):o="Invalid search text"}this.setState({filters:i,error:o})}render(){const{error:e,filters:t,invertSelection:n,selectedValues:s,searchText:i,table:o}=this.state,{formatter:l,showSearch:a}=this.props,d=this.getColumnName(),h=this.getDisplayedValueText(),u=d?`Find ${d}...`:"";return r.jsxs("div",{className:"advanced-filter-creator-select-value",children:[r.jsxs("div",{className:a?"form-group":"",children:[r.jsx("label",{htmlFor:"advanced-filter-creator-select-value-input",children:"Select Values"}),a&&r.jsx("input",{type:"text",className:Y("form-control",{"is-invalid":e!=null}),id:"advanced-filter-creator-select-value-input",placeholder:u,value:i,onChange:this.handleSearchChange})]}),r.jsx(dT,{table:o,filters:t,invertSelection:n,selectedValues:s,formatter:l,onChange:this.handleListChange}),r.jsxs("div",{className:"advanced-filter-creator-select-meta-row",children:[r.jsxs("div",{children:[r.jsx(B,{kind:"ghost",onClick:this.handleSelectAllClick,children:"Select All"}),r.jsx(B,{kind:"ghost",onClick:this.handleClearAllClick,children:"Clear"})]}),r.jsx(Wt,{in:h!=null,timeout:250,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:"row-count-info",children:h})})]})]})}}const cT=Ur;const Bi=ne.module("AdvancedFilterCreator");class us extends v.PureComponent{static debounceFilterUpdate=250;static defaultProps={options:{filterItems:null,filterOperators:null,invertSelection:!0,selectedValues:[]},sortDirection:null};static makeFilterItem(){return{key:qe()}}constructor(e){super(e),this.handleAddAnd=this.handleAddAnd.bind(this),this.handleAddOr=this.handleAddOr.bind(this),this.handleChangeFilterOperator=this.handleChangeFilterOperator.bind(this),this.handleDone=this.handleDone.bind(this),this.handleFilterChange=this.handleFilterChange.bind(this),this.handleFilterDelete=this.handleFilterDelete.bind(this),this.handleSelectValueChange=this.handleSelectValueChange.bind(this),this.handleReset=this.handleReset.bind(this),this.handleSortDown=this.handleSortDown.bind(this),this.handleSortUp=this.handleSortUp.bind(this),this.handleSubmit=this.handleSubmit.bind(this),this.handleFocusTrapStart=this.handleFocusTrapStart.bind(this),this.handleFocusTrapEnd=this.handleFocusTrapEnd.bind(this),this.handleUpdateTimeout=this.handleUpdateTimeout.bind(this),this.focusTrapContainer=de.createRef();const{options:t}=e;let{filterOperators:n,invertSelection:s,selectedValues:i}=t;const o=t.filterItems?.map(({selectedType:l,value:a})=>({selectedType:l,value:a,key:qe()}))??[];o.length===0&&o.push(us.makeFilterItem()),n==null&&(n=[]),s==null&&(s=!0),i==null&&(i=[]),this.state={filterItems:o,filterOperators:n,invertSelection:s,selectedValues:i,valuesTableError:null,valuesTable:void 0}}componentDidMount(){this.initValuesTable()}componentWillUnmount(){this.debounceTimeout!=null&&(clearTimeout(this.debounceTimeout),this.sendUpdate()),this.valuesTablePromise!=null&&this.valuesTablePromise.cancel()}focusTrapContainer;debounceTimeout;valuesTablePromise;getFilterChangeHandler(e){return this.handleFilterChange.bind(this,e)}getFilterDeleteHandler(e){return this.handleFilterDelete.bind(this,e)}getFilterTypes=ge(e=>F.getFilterTypes(e));initValuesTable(){const{model:e,column:t}=this.props;if(!e.isValuesTableAvailable){Bi.debug("No values table for this model, just ignore");return}this.valuesTablePromise=F.makeCancelableTablePromise(e.valuesTable(t)),this.valuesTablePromise.then(n=>{const s=n.columns[0].sort().asc();n.applySort([s]),this.setState({valuesTable:n})}).catch(n=>{ye.isCanceled(n)||(Bi.error("Unable to open values table",n),this.setState({valuesTableError:n}))})}handleFocusTrapEnd(){(this.focusTrapContainer?.current?.querySelector("button,select,input,textarea")).focus()}handleFocusTrapStart(){const e=this.focusTrapContainer?.current?.querySelectorAll("button,select,input,textarea");e&&e.length>0&&e[e.length-1].focus()}handleAddAnd(){let{filterItems:e,filterOperators:t}=this.state;e=e.concat(us.makeFilterItem()),t=t.concat(Bn.and),this.setState({filterItems:e,filterOperators:t})}handleAddOr(){let{filterItems:e,filterOperators:t}=this.state;e=e.concat(us.makeFilterItem()),t=t.concat(Bn.or),this.setState({filterItems:e,filterOperators:t})}handleChangeFilterOperator(e,t){let{filterOperators:n}=this.state;n=[...n],Am(t),n[e]=t,this.setState({filterOperators:n}),this.startUpdateTimer()}handleFilterChange(e,t,n){let{filterItems:s}=this.state;s=[...s];const{key:i}=s[e];s[e]={key:i,selectedType:t,value:n},this.setState({filterItems:s}),this.startUpdateTimer()}handleFilterDelete(e){let{filterItems:t,filterOperators:n}=this.state;t=[...t],n=[...n],e<t.length&&t.splice(e,1),e<n.length?n.splice(e,1):e===n.length&&n.splice(n.length-1,1),t.length===0&&t.push(us.makeFilterItem()),this.setState({filterItems:t,filterOperators:n}),this.startUpdateTimer()}handleSelectValueChange(e,t){this.setState({selectedValues:e,invertSelection:t}),this.startUpdateTimer()}handleReset(){Bi.debug("Resetting Advanced Filter"),this.setState({filterItems:[us.makeFilterItem()],filterOperators:[],selectedValues:[],invertSelection:!0}),this.startUpdateTimer()}handleSortDown(e){const t=Ts.isModifierKeyDown(e);this.sortTable(F.sortDirection.descending,t)}handleSortUp(e){const t=Ts.isModifierKeyDown(e);this.sortTable(F.sortDirection.ascending,t)}handleSubmit(e){Bi.debug("Submitting Advanced Filter"),this.stopUpdateTimer(),this.sendUpdate(),e.preventDefault()}handleDone(e){Bi.debug("Submitting and Closing Advanced Filter"),this.stopUpdateTimer(),this.sendUpdate();const{onDone:t}=this.props;t(),e.preventDefault()}handleUpdateTimeout(){this.debounceTimeout=void 0,this.sendUpdate()}shouldShowAddFilter(){const{filterItems:e}=this.state;if(e.length===0)return!1;const t=e[e.length-1],{selectedType:n,value:s}=t;return n!=null&&n.length>0&&s!=null&&s.length>0}sortTable(e,t=!1){const{column:n,onSortChange:s}=this.props;s(n,e,t)}startUpdateTimer(){this.stopUpdateTimer(),this.debounceTimeout=setTimeout(this.handleUpdateTimeout,us.debounceFilterUpdate)}stopUpdateTimer(){this.debounceTimeout!==void 0&&(clearTimeout(this.debounceTimeout),this.debounceTimeout=void 0)}sendUpdate(){const{filterItems:e,filterOperators:t,invertSelection:n,selectedValues:s}=this.state,{column:i,onFilterChange:o,model:l}=this.props,{formatter:a}=l,d=e.filter(({selectedType:g,value:p})=>g!=null&&p!=null&&p!==""),h=t.filter((g,p)=>g!=null&&e[p].selectedType!=null&&e[p].value!=null&&e[p].value!=="").slice(0,d.length-1),u={filterItems:d,filterOperators:h,invertSelection:n,selectedValues:s},m=F.makeAdvancedFilter(i,u,a.timeZone);o(i,m,u)}render(){const{column:e,model:t,sortDirection:n,formatter:s}=this.props,{filterItems:i,filterOperators:o,invertSelection:l,selectedValues:a,valuesTable:d,valuesTableError:h}=this.state,{isValuesTableAvailable:u}=t,m=F.isBooleanType(e.type),g=F.isDateType(e.type),p=this.getFilterTypes(e.type),C=e.type.substring(e.type.lastIndexOf(".")+1),f=[];if(!m&&p.length)for(let S=0;S<i.length;S+=1){const T=i[S],{key:y,selectedType:E,value:R}=T,x=r.jsx(rT,{column:e,filterTypes:p,onChange:this.getFilterChangeHandler(S),onDelete:this.getFilterDeleteHandler(S),selectedType:E,value:R,formatter:s},y);if(f.push(x),S<o.length){const M=o[S]===Bn.and,O=r.jsxs("div",{className:"form-row justify-content-end advanced-filter-creator-filter-operator",children:[r.jsx(B,{kind:"ghost",className:Y("filter-operator",{active:M}),onClick:()=>this.handleChangeFilterOperator(S,Bn.and),children:"AND"}),r.jsx(B,{kind:"ghost",className:Y("filter-operator",{active:!M}),onClick:()=>this.handleChangeFilterOperator(S,Bn.or),children:"OR"})]},`filterOperator${y}`);f.push(O)}}const b=this.shouldShowAddFilter(),w=r.jsxs("div",{className:Y("form-row justify-content-end add-filter-item",{hidden:!b}),children:[r.jsx("span",{className:"text-muted",children:r.jsx(ee,{icon:Es})}),r.jsx(B,{kind:"ghost",className:"btn-filter-item",onClick:this.handleAddAnd,disabled:!b,tooltip:"Add filter with AND",children:"AND"}),r.jsx(B,{kind:"ghost",className:"btn-filter-item",onClick:this.handleAddOr,disabled:!b,tooltip:"Add filter with OR",children:"OR"})]},"addFilterItem");return f.push(w),r.jsxs("div",{className:"advanced-filter-creator",role:"presentation",children:[r.jsx("div",{tabIndex:0,onFocus:this.handleFocusTrapStart}),r.jsxs("form",{onSubmit:this.handleSubmit,ref:this.focusTrapContainer,children:[r.jsxs("div",{className:"title-bar",children:[r.jsx("h6",{className:"advanced-filter-title",children:"Advanced Filters"}),r.jsxs("div",{className:"advanced-filter-menu-buttons",children:[r.jsx(B,{kind:"ghost",className:Y("sort-operator",{active:n===F.sortDirection.descending}),onClick:this.handleSortDown,icon:Sd,tooltip:`Sort ${e.name} Descending`}),r.jsx(B,{kind:"ghost",className:Y("sort-operator",{active:n===F.sortDirection.ascending}),onClick:this.handleSortUp,icon:r.jsx(ee,{icon:Sd,rotation:180}),tooltip:`Sort ${e.name} Ascending`})]})]}),r.jsx("hr",{}),r.jsxs("div",{className:"advanced-filter-column-name",children:[e.name," ",r.jsxs("span",{className:"column-type",children:["(",C,")"]})]}),f,u&&h==null&&r.jsxs(r.Fragment,{children:[!m&&r.jsx("hr",{}),r.jsx("div",{className:"form-group",children:r.jsx(cT,{table:d,onChange:this.handleSelectValueChange,invertSelection:l,selectedValues:a,formatter:s,showSearch:!g,timeZone:s.timeZone})})]}),r.jsxs("div",{className:"form-row justify-content-end",children:[r.jsx(B,{kind:"secondary",className:"mr-2",onClick:this.handleReset,children:"Reset"}),r.jsx(B,{kind:"primary",onClick:this.handleDone,children:"Done"})]})]}),r.jsx("div",{tabIndex:0,onFocus:this.handleFocusTrapEnd})]})}}const hT=us;const oc=ne.module("Aggregations");function uT({isRollup:c,settings:e,onChange:t,onEdit:n}){const{aggregations:s,showOnTop:i}=e,o=v.useMemo(()=>Qw.filter(D=>!s.some(M=>M.operation===D)),[s]),[l,a]=v.useState(o[0]),[d,h]=v.useState([]),u=v.useCallback(D=>{t({...e,...D})},[t,e]),m=v.useCallback(D=>{u({aggregations:D})},[u]),g=v.useCallback(D=>{u({showOnTop:D})},[u]),p=v.useCallback(()=>{oc.debug("handleDragStart"),hn.startDragging()},[]),C=v.useCallback(({destination:D,source:M})=>{if(oc.debug("handleDragEnd",D,M),hn.stopDragging(),D===null)return;let O=D.index;M.index<D.index&&(O+=1);const H=[...s],L=hn.reorder(H,d,H,O),V=hn.adjustDestinationIndex(O,d),U=[[V,V+L.length-1]];m(H),h(U)},[m,s,d,h]),f=v.useCallback(D=>{a(D)},[a]),b=v.useCallback(()=>{m([...s,{operation:l,selected:[],invert:!0}])},[s,l,m]),w=v.useCallback(D=>{m(s.filter((M,O)=>O!==D))},[s,m]),S=v.useCallback(D=>{h(D)},[h]),T=v.useCallback(D=>{const M=s[D];Cs.isRollupOperation(M.operation)||n(M)},[s,n]),y=v.useCallback(D=>{g(D.target.value==="true")},[g]);v.useEffect(function(){o.length>0&&!o.includes(l)&&a(o[0])},[o,l]);const E=v.useCallback(({item:D,itemIndex:M,isClone:O=!1,selectedCount:H})=>{const L=D.operation,V=O?`${H}`:void 0,U=O?"item-list-item-clone":void 0,j=Cs.isRollupOperation(D.operation),P=!O&&!j;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:Y("item-list-item-content","draggable-item-list-item-content",U),children:[r.jsxs("span",{className:"title",children:[L,!c&&j&&r.jsxs("span",{className:"small text-warning",children:[r.jsx(ee,{icon:eh})," Requires rollup"]})]}),rn.renderBadge({text:V}),rn.renderHandle()]}),!O&&r.jsxs(r.Fragment,{children:[r.jsx(B,{kind:"ghost",className:"btn-edit",icon:go,tooltip:"Edit Columns",onClick:()=>n(D),disabled:!P}),r.jsx(B,{kind:"ghost",className:"btn-delete",icon:Gt,tooltip:"Delete Aggregation",onClick:()=>w(M)})]})]})},[w,n,c]),R=o.length>0,x=s.length>0;return r.jsxs("div",{className:"aggregations",children:[R&&r.jsxs("div",{className:"form-inline",children:[r.jsx(_m,{onChange:f,value:l,children:o.map(D=>r.jsx(Pm,{value:D,children:D},D))}),r.jsxs("button",{type:"button",className:"btn btn-link btn-add",onClick:b,children:[r.jsx(ee,{icon:Es}),"Add Aggregation"]})]}),R&&x&&r.jsx("hr",{}),x&&r.jsxs(r.Fragment,{children:[!c&&r.jsxs("div",{className:"form-inline",children:[r.jsx("label",{children:"Placement: "}),r.jsxs(Ul,{onChange:y,value:`${i}`,children:[r.jsx(Wn,{value:"true",children:"Top"}),r.jsx(Wn,{value:"false",children:"Bottom"})]})]}),r.jsx(Pl,{onDragStart:p,onDragEnd:C,children:r.jsx(rn,{className:"selected-aggregations",itemCount:s.length,items:s,renderItem:E,offset:0,onSelectionChange:S,onSelect:T,selectedRanges:d,isMultiSelect:!0})})]})]})}const mT=30;function gT({aggregation:c,columns:e,onChange:t}){const[n,s]=v.useState(-1),[i,o]=v.useState(-1),[l,a]=v.useState(0),{invert:d,selected:h}=c,u=v.useRef(null),m=v.useCallback(y=>h.includes(y)?!d:d,[d,h]),g=v.useMemo(()=>{let y=jr(e,c.operation);return l!==0&&(y=F.sortColumns(y,l===1)),y},[e,c.operation,l]),p=v.useMemo(()=>n>=0?g.slice(n,i+1).map(y=>({value:y.name,displayValue:y.name,isSelected:m(y.name)})):[],[g,m,i,n]),C=v.useCallback(y=>{const{name:E}=g[y],R=h.indexOf(E);let x=[...h],D=d;R>=0?x.splice(R,1):(x.push(E),x.length===g.length&&(x=[],D=!d)),t({...c,selected:x,invert:D})},[c,d,g,h,t]),f=v.useCallback(()=>{a(0),t({...c,selected:[],invert:!0})},[c,t]),b=v.useCallback((y,E)=>{s(y),o(E)},[s,o]),w=v.useCallback(()=>{h.length===0?t({...c,invert:!d}):t({...c,selected:[],invert:!0})},[c,d,t,h]),S=h.length===0?d:null,T=h.length!==0||!d||l!==0;return r.jsxs("div",{role:"menu",className:"aggregation-edit",children:[r.jsx("div",{className:"top-menu",children:r.jsxs("div",{className:"form-inline",children:[r.jsx(nn,{checked:S,onChange:w,children:"Toggle All"}),r.jsx("div",{className:"spacer"}),r.jsx(Wt,{in:T,timeout:Je.transitionSlowMs,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx(B,{kind:"ghost",className:"btn-reset",onClick:f,children:"Reset"})}),r.jsx(B,{kind:"ghost",className:Y({active:l===1}),icon:ur,tooltip:"Sort ascending",onClick:()=>a(1)}),r.jsx(B,{kind:"ghost",className:Y({active:l===2}),icon:mr,tooltip:"Sort descending",onClick:()=>a(2)})]})}),r.jsx("div",{className:"aggregation-edit-item-list",children:r.jsx(yi,{itemCount:g.length,items:p,offset:n,renderItem:({item:y})=>r.jsx(nn,{checked:m(y.value),children:y.displayValue}),onSelect:C,onViewportChange:b,rowHeight:mT,focusSelector:"input",ref:u})})]})}function pT(c){return r.jsx("svg",{width:48,height:48,xmlns:"http://www.w3.org/2000/svg",...c,children:r.jsxs("g",{fill:"none",fillRule:"evenodd",children:[r.jsx("path",{fill:"#C1C0C0",d:"M44 43v1H4v-1z"}),r.jsx("path",{fill:"#7DA4FF",d:"M8 26h4v15H8zM15 17h4v24h-4zM22 21h4v20h-4zM29 17h4v24h-4zM36 11h4v30h-4z"})]})})}function fT(c){return r.jsx("svg",{width:48,height:48,xmlns:"http://www.w3.org/2000/svg",...c,children:r.jsxs("g",{fill:"none",fillRule:"evenodd",children:[r.jsx("path",{fill:"#C1C0C0",d:"M44 43v1H4v-1z"}),r.jsx("path",{fill:"#7DA4FF",d:"M7 34h4v8H7zM12 31h4v11h-4zM17 27h4v15h-4zM22 22h4v20h-4zM27 27h4v15h-4zM32 29h4v13h-4zM37 31h4v11h-4z"})]})})}function CT(c){return r.jsx("svg",{width:48,height:48,xmlns:"http://www.w3.org/2000/svg",...c,children:r.jsxs("g",{fill:"none",fillRule:"evenodd",children:[r.jsx("path",{fill:"#C1C0C0",d:"M4 4h1v40H4zM44 43v1H5v-1z"}),r.jsx("path",{stroke:"#7DA4FF",d:"M7.984 32.44l7.982-11.378 5.273 3.739 9.952-10.838 2.826 1.894 7.45-5.802"}),r.jsx("path",{stroke:"#BECDEF",d:"M8.244 37.926L17 33.496l5 .87 10.637-10.35 10.615-1.381"})]})})}function bT(c){return r.jsx("svg",{width:48,height:48,xmlns:"http://www.w3.org/2000/svg",...c,children:r.jsxs("g",{fill:"none",fillRule:"evenodd",children:[r.jsx("path",{d:"M24 10c7.732 0 14 6.268 14 14s-6.268 14-14 14-14-6.268-14-14h14V10z",fill:"#80A6FF"}),r.jsx("path",{d:"M10 24c0-7.732 6.268-14 14-14v14H10z",fill:"#C1C0C0"})]})})}function ST(c){return r.jsx("svg",{width:48,height:48,xmlns:"http://www.w3.org/2000/svg",...c,children:r.jsxs("g",{fill:"none",fillRule:"evenodd",children:[r.jsx("path",{fill:"#C1C0C0",d:"M44 43v1H4v-1z"}),r.jsx("path",{fill:"#939293",d:"M44 34v1H4v-1zM44 25v1H4v-1zM44 16v1H4v-1z"}),r.jsx("circle",{fill:"#7DA4FF",cx:9.5,cy:37.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:16.5,cy:30.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:22.5,cy:36.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:28.5,cy:30.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:15.5,cy:38.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:23.5,cy:25.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:19.5,cy:19.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:29.5,cy:19.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:32.5,cy:26.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:36.5,cy:13.5,r:1.5})]})})}function wT(c){return r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none",xmlns:"http://www.w3.org/2000/svg",...c,children:[r.jsx("rect",{width:"48",height:"48",fill:"none"}),r.jsx("rect",{x:"26",y:"10",width:"15",height:"4",fill:"#9FDE70"}),r.jsx("rect",{x:"26",y:"22",width:"15",height:"4",fill:"#9FDE70"}),r.jsx("rect",{x:"26",y:"28",width:"15",height:"4",fill:"#FFD95C"}),r.jsx("rect",{x:"26",y:"34",width:"15",height:"4",fill:"#9FDE70"})]})}function vT(c){return r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none",xmlns:"http://www.w3.org/2000/svg",...c,children:[r.jsx("rect",{width:"48",height:"48",fill:"none"}),r.jsx("rect",{x:"4",y:"16",width:"40",height:"4",fill:"#FFD95C"}),r.jsx("rect",{x:"4",y:"10",width:"40",height:"4",fill:"#78DCE8"}),r.jsx("rect",{x:"4",y:"34",width:"40",height:"4",fill:"#78DCE8"})]})}const lc=ne.module("ChartBuilder");class ut extends v.PureComponent{static types=[I.plot.SeriesPlotStyle.LINE,I.plot.SeriesPlotStyle.BAR,I.plot.SeriesPlotStyle.SCATTER,I.plot.SeriesPlotStyle.PIE];static getTypeName(e){switch(e){case I.plot.SeriesPlotStyle.LINE:return"Line";case I.plot.SeriesPlotStyle.BAR:return"Bar";case I.plot.SeriesPlotStyle.SCATTER:return"Scatter";case I.plot.SeriesPlotStyle.PIE:return"Pie";case I.plot.SeriesPlotStyle.HISTOGRAM:return"Histogram";default:return e}}static getTypeIcon(e){switch(e){case I.plot.SeriesPlotStyle.LINE:return r.jsx(CT,{});case I.plot.SeriesPlotStyle.BAR:return r.jsx(pT,{});case I.plot.SeriesPlotStyle.SCATTER:return r.jsx(ST,{});case I.plot.SeriesPlotStyle.PIE:return r.jsx(bT,{});case I.plot.SeriesPlotStyle.HISTOGRAM:return r.jsx(fT,{});default:return null}}static getMaxSeriesCount(e){switch(e){case I.plot.SeriesPlotStyle.PIE:return 1;case I.plot.SeriesPlotStyle.HISTOGRAM:return 0;default:return 100}}static getXAxisLabel(e){switch(e){case I.plot.SeriesPlotStyle.PIE:return"Labels";case I.plot.SeriesPlotStyle.HISTOGRAM:return"Data";default:return"X-Axis"}}static getSeriesLabel(e){switch(e){case I.plot.SeriesPlotStyle.PIE:return"Values";default:return"Series"}}static makeSeriesItem(e){return{id:qe.generate(),value:e}}static makeDefaultSeriesItems(e,t){if(ut.getMaxSeriesCount(e)===0||t==null||t.length===0)return[];const s=t.length>1?t[1].name:t[0].name;return[ut.makeSeriesItem(s)]}static getDefaultXAxis(e,t){return t!=null&&t.length>0?t[0].name:null}constructor(e){super(e),this.handleAddSeries=this.handleAddSeries.bind(this),this.handleLinkStateChange=this.handleLinkStateChange.bind(this),this.handleReset=this.handleReset.bind(this),this.handleSeriesChange=this.handleSeriesChange.bind(this),this.handleSeriesDeleteClick=this.handleSeriesDeleteClick.bind(this),this.handleSubmit=this.handleSubmit.bind(this),this.handleTypeClick=this.handleTypeClick.bind(this),this.handleXAxisChange=this.handleXAxisChange.bind(this),this.sendChange=this.sendChange.bind(this);const{model:t}=e,{columns:n}=t,s=ut.types[0],i=ut.getDefaultXAxis(s,n),o=ut.makeDefaultSeriesItems(s,n);this.state={type:s,seriesItems:o,xAxis:i,isLinked:!0}}handleAddSeries(){this.setState(e=>{const{seriesItems:t}=e,n=[...t],{model:s}=this.props,{columns:i}=s;return n.push({id:qe.generate(),value:i[0].name}),{seriesItems:n}},this.sendChange)}handleLinkStateChange(e){this.setState({isLinked:e.target.value==="true"},this.sendChange)}handleReset(){const{model:e}=this.props,{columns:t}=e,n=ut.types[0],s=ut.getDefaultXAxis(n,t),i=ut.makeDefaultSeriesItems(n,t),o=!0;this.setState({type:n,seriesItems:i,xAxis:s,isLinked:o},this.sendChange)}handleSeriesChange(e){const{value:t}=e.target,n=e.target.getAttribute("data-index"),s=parseInt(n,10);this.setState(i=>{let{seriesItems:o}=i;return o=[...o],o[s].value=t,{seriesItems:o}},this.sendChange)}handleSeriesDeleteClick(e){const n=e.target.getAttribute("data-index"),s=parseInt(n,10);this.setState(i=>{const{seriesItems:o}=i,l=[...o];return l.splice(s,1),{seriesItems:l}},this.sendChange)}handleSubmit(e){e.preventDefault();const{onSubmit:t}=this.props,{type:n,seriesItems:s,xAxis:i,isLinked:o}=this.state,l=s.map(a=>a.value);t({type:`${n}`,series:l,xAxis:i,isLinked:o})}handleTypeClick(e){const n=e.target.getAttribute("data-index"),s=parseInt(n,10),i=ut.types[s];lc.debug2("handleTypeSelect",i),this.setState(o=>{const l=ut.getMaxSeriesCount(i);let{seriesItems:a}=o;if(a=a.slice(0,l),a.length===0&&l>0){const{model:d}=this.props,{columns:h}=d;a=ut.makeDefaultSeriesItems(i,h)}return{type:i,seriesItems:a}},this.sendChange)}handleXAxisChange(e){const t=e.target.value;lc.debug2("x-axis change",t),this.setState({xAxis:t},this.sendChange)}sendChange(){const{onChange:e}=this.props,{isLinked:t,type:n,seriesItems:s,xAxis:i}=this.state,o=s.map(l=>l.value);e({type:n,series:o,xAxis:i,isLinked:t})}render(){const{model:e}=this.props,{columns:t}=e,{seriesItems:n,type:s,xAxis:i,isLinked:o}=this.state,l=ut.getMaxSeriesCount(s),a=ut.getXAxisLabel(s),d=ut.getSeriesLabel(s),h=n.length>0,u=n.length<l;return r.jsx("div",{className:"chart-builder",children:r.jsxs("form",{onSubmit:this.handleSubmit,children:[r.jsxs("div",{className:"form-row",children:[r.jsx("label",{children:"Select Chart Type"}),r.jsx("div",{className:"form-row",children:ut.types.map((m,g)=>{const p=m;return r.jsx("div",{className:"col col-chart-type",children:r.jsxs("button",{type:"button",className:Y("btn","btn-icon","btn-chart-type",{active:m===s}),"data-index":g,onClick:this.handleTypeClick,children:[ut.getTypeIcon(m),ut.getTypeName(m)]})},p)})})]}),r.jsx("hr",{}),r.jsxs("div",{className:"form-row form-inline",children:[r.jsx("label",{className:"col-2 label-left",children:a}),r.jsx("select",{className:"form-control custom-select select-x-axis col",value:i,onChange:this.handleXAxisChange,children:t.map(m=>r.jsx("option",{value:m.name,children:m.name},m.name))})]}),h&&r.jsx("hr",{}),n.map((m,g)=>r.jsxs("div",{className:"form-row form-inline form-series-item","data-testid":`form-series-item-${g}`,children:[r.jsx("label",{className:"col-2 label-left",children:g===0?d:""}),r.jsx("select",{className:"form-control custom-select select-series col",value:m.value,onChange:this.handleSeriesChange,"data-testid":`select-series-item-${g}`,"data-index":g,children:t.map(p=>r.jsx("option",{value:p.name,"data-index":g,children:p.name},p.name))}),n.length>1&&r.jsx(B,{kind:"ghost",className:"btn-delete-series ml-2 px-2","data-index":g,"data-testid":`delete-series-${g}`,onClick:this.handleSeriesDeleteClick,icon:Gt,tooltip:"Delete"})]},m.id)),u&&r.jsxs("div",{className:"form-row",children:[r.jsx("div",{className:"col-2"}),r.jsx(B,{kind:"ghost",className:"btn-add-series mt-1",onClick:this.handleAddSeries,icon:Es,children:"Add Series"})]}),r.jsxs("div",{className:"form-row chart-builder-link",children:[r.jsx("label",{className:"col-2 label-right",children:r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx(ee,{mask:rr,icon:Ri,transform:"right-5 down-5"}),r.jsx(ee,{icon:o?th:Cg,transform:"grow-2 right-8 down-6"})]})}),r.jsxs(Ul,{onChange:this.handleLinkStateChange,value:`${o}`,children:[r.jsx(Wn,{value:"true",children:"Sync State"}),r.jsx(Wn,{value:"false",children:"Freeze State"})]})]}),r.jsxs("div",{className:"form-row",children:[r.jsx("div",{className:"col-2 label-right"}),r.jsx("div",{className:"col chart-builder-link-info",children:o?"Charts with synced state will update to match any filters or user modifications applied to the parent table.":"Freeze State disconnects the chart state from the parent table. New filters or user modifications on the parent table will not be applied."})]}),r.jsxs("div",{className:Y("form-row","justify-content-end","my-3"),children:[r.jsx(B,{kind:"secondary",className:"btn-reset",onClick:this.handleReset,children:"Reset"}),r.jsx(B,{kind:"primary",type:"submit",className:"btn-submit",children:"Create"})]})]})})}}const TT=ut;class ET extends v.Component{static defaultProps={value:"",onContentChanged:()=>{},editorSettings:{},editorIndex:0,onTab:()=>{},invalid:!1};constructor(e){super(e),this.handleContentChanged=this.handleContentChanged.bind(this),this.handleEditorFocus=this.handleEditorFocus.bind(this),this.handleEditorBlur=this.handleEditorBlur.bind(this),this.handleContainerClick=this.handleContainerClick.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.state={isEditorFocused:!1,isEditorEmpty:!0},this.editorContainer=null}componentDidMount(){this.initEditor()}componentWillUnmount(){this.destroyEditor()}editorContainer;editor;initEditor(){const{value:e,editorSettings:t}=this.props,n={copyWithSyntaxHighlighting:"false",fixedOverflowWidgets:!0,folding:!1,fontFamily:"Fira Mono",glyphMargin:!1,language:"groovyDB",lineDecorationsWidth:8,lineNumbers:"off",minimap:{enabled:!1},renderLineHighlight:"none",scrollbar:{arrowSize:0,horizontal:"hidden",horizontalScrollbarSize:0},scrollBeyondLastLine:!1,padding:{top:6,bottom:6},tabCompletion:"off",useTabStops:!0,value:e,wordWrap:"on",automaticLayout:!0,...t};if(!this.editorContainer)throw new Error("editorContainer is null");this.editor=Gn.create(this.editorContainer,n),this.editor.layout(),this.editor.getModel()?.updateOptions({tabSize:0}),this.editor.onKeyDown(this.handleKeyDown),this.editor.onDidChangeModelContent(this.handleContentChanged),this.editor.onDidFocusEditorText(this.handleEditorFocus),this.editor.onDidBlurEditorText(this.handleEditorBlur)}destroyEditor(){this.editor?.dispose(),this.editor=void 0}handleContentChanged(){const{onContentChanged:e}=this.props,t=this.editor?.getModel()?.getValue();t!==void 0&&this.setState({isEditorEmpty:t.length===0}),e(t)}handleEditorFocus(){this.setState({isEditorFocused:!0})}handleEditorBlur(){const e=this.editor?.getModel()?.getValue()??"";this.setState({isEditorEmpty:e.length===0,isEditorFocused:!1})}handleContainerClick(){const{isEditorFocused:e}=this.state;e||this.editor?.focus()}handleKeyDown(e){const{onTab:t,editorIndex:n}=this.props;e.code==="Tab"&&(e.stopPropagation(),e.preventDefault(),t(n,e.shiftKey))}render(){const{value:e,invalid:t}=this.props,{isEditorFocused:n,isEditorEmpty:s}=this.state;return r.jsxs("div",{className:Y("input-editor-wrapper",{focused:n,invalid:t}),role:"presentation",onClick:this.handleContainerClick,children:[r.jsx("div",{className:"editor-container",ref:i=>{this.editorContainer=i}}),s&&!e&&r.jsx("div",{className:"editor-placeholder text-muted",children:"Column Formula"})]})}}const ac=Object.freeze({NAME:"name",FORMULA:"formula"}),yT=()=>{};function RT({eventKey:c,name:e,inputIndex:t,formula:n,onChange:s,onDeleteColumn:i,onTabInEditor:o,invalid:l,isDuplicate:a}){const d=e===""||Ii.isValidColumnName(e),h=v.useCallback(u=>{u!==void 0&&(u.replace(/(\r\n|\n|\r)/gm,""),s(c,ac.FORMULA,u))},[s,c]);return r.jsx(Uc,{draggableId:c,index:t,disableInteractiveElementBlocking:!0,children:(u,m)=>r.jsxs("div",{className:Y("draggable-container",{dragging:m.isDragging}),ref:u.innerRef,...u.draggableProps,children:[r.jsxs("div",{className:"custom-column-input-container",children:[r.jsxs("div",{className:"pb-3",children:[r.jsxs("div",{className:"d-flex flex-row custom-column-name",children:[r.jsx("input",{className:Y("form-control custom-column-input",{"is-invalid":l||!d||a}),placeholder:"Column Name",value:e,onChange:g=>{s(c,ac.NAME,g.target.value)}}),r.jsx(B,{kind:"ghost",className:"ml-1 px-2",onClick:()=>{i(c)},icon:Gt,tooltip:"Delete custom column"}),r.jsx(B,{kind:"ghost",className:"btn-drag-handle",onClick:yT,...u.dragHandleProps,icon:Wl,tooltip:"Drag column to re-order"})]}),(!d||a)&&r.jsx("p",{className:"validate-label-error text-danger mb-0 mt-2 pl-1",children:d?"Duplicate name":"Invalid name"})]}),r.jsx(ET,{editorSettings:{language:"deephavenDb"},editorIndex:t,value:n,onContentChanged:h,onTab:o,invalid:l})]}),r.jsx("hr",{})]})})}const xa=[];class xT extends Sw{static EVENT=Object.freeze({UPDATED:"UPDATED",FORMATTER_UPDATED:"FORMATTER_UPDATED",REQUEST_FAILED:"REQUEST_FAILED",COLUMNS_CHANGED:"COLUMNS_CHANGED",TABLE_CHANGED:"TABLE_CHANGED",FILTERS_CHANGED:"FILTERS_CHANGED",SORTS_CHANGED:"SORTS_CHANGED",DISCONNECT:"DISCONNECT",RECONNECT:"RECONNECT",TOTALS_UPDATED:"TOTALS_UPDATED",PENDING_DATA_UPDATED:"PENDING_DATA_UPDATED"});constructor(){super(),this.listenerCount=0}listenerCount;addEventListener(e,t,n){super.addEventListener(e,t,n),this.listenerCount+=1,this.listenerCount===1&&this.startListening()}removeEventListener(e,t,n){super.removeEventListener(e,t,n),this.listenerCount-=1,this.listenerCount===0&&this.stopListening()}startListening(){}stopListening(){}get originalColumns(){return this.columns}get layoutHints(){return null}get frontColumns(){return xa}get backColumns(){return xa}get frozenColumns(){return xa}isColumnFrozen(e){return!1}get isFilterRequired(){return!1}get isReversible(){return!0}get isColumnStatisticsAvailable(){return!1}get description(){return""}get isCustomColumnsAvailable(){return!1}get isFormatColumnsAvailable(){return!1}get isExportAvailable(){return!1}get isValuesTableAvailable(){return!1}get isChartBuilderAvailable(){return!1}get isRollupAvailable(){return!1}get isSelectDistinctAvailable(){return!1}get isTotalsAvailable(){return!1}isFilterable(e){return!1}close(){}isRowMovable(){return!1}get isSeekRowAvailable(){return!1}}const Ce=xT;class Us extends v.Component{static SUCCESS_SHOW_DURATION=750;static makeCustomColumnInputEventKey(){return qe.generate()}static createCustomColumnInput(){return{eventKey:qe.generate(),name:"",formula:""}}constructor(e){super(e),this.handleAddColumnClick=this.handleAddColumnClick.bind(this),this.handleSaveClick=this.handleSaveClick.bind(this),this.handleInputChange=this.handleInputChange.bind(this),this.handleDeleteColumn=this.handleDeleteColumn.bind(this),this.handleCustomColumnUpdated=this.handleCustomColumnUpdated.bind(this),this.handleRequestFailed=this.handleRequestFailed.bind(this),this.handleDragEnd=this.handleDragEnd.bind(this),this.resetRequestFailed=this.resetRequestFailed.bind(this),this.handleEditorTabNavigation=this.handleEditorTabNavigation.bind(this),this.state={inputs:[],isCustomColumnApplying:!1,errorMessage:null,hasRequestFailed:!1,isSuccessShowing:!1},this.container=null,this.successButtonTimer=null}componentDidMount(){const{customColumns:e}=this.props;this.parseCustomColumns(e),this.startListening()}componentWillUnmount(){this.stopListening(),this.successButtonTimer&&clearTimeout(this.successButtonTimer)}container;successButtonTimer;getInput=ge((e,t)=>e.find(n=>n.eventKey===t));getInputIndex=ge((e,t)=>e.findIndex(n=>n.eventKey===t));resetErrorMessage(){this.setState({errorMessage:null})}startListening(){const{model:e}=this.props;e.addEventListener(Ce.EVENT.COLUMNS_CHANGED,this.handleCustomColumnUpdated),e.addEventListener(Ce.EVENT.UPDATED,this.handleCustomColumnUpdated),e.addEventListener(Ce.EVENT.REQUEST_FAILED,this.handleRequestFailed)}stopListening(){const{model:e}=this.props;e.removeEventListener(Ce.EVENT.COLUMNS_CHANGED,this.handleCustomColumnUpdated),e.removeEventListener(Ce.EVENT.UPDATED,this.handleCustomColumnUpdated),e.removeEventListener(Ce.EVENT.REQUEST_FAILED,this.handleRequestFailed)}parseCustomColumns(e){if(e.length>0){const t=e.map(n=>{const s=n.split(/=(.+)/,2);return{eventKey:Us.makeCustomColumnInputEventKey(),name:s[0],formula:s[1]}});this.setState({inputs:t})}else this.setState({inputs:[Us.createCustomColumnInput()]})}handleAddColumnClick(){const{inputs:e}=this.state,t=[...e];t.push(Us.createCustomColumnInput()),this.setState({inputs:t})}handleDeleteColumn(e){const{inputs:t}=this.state,n=this.getInputIndex(t,e),s=[...t];s.splice(n,1),s.length===0&&s.push(Us.createCustomColumnInput()),this.setState({inputs:s})}handleInputChange(e,t,n){const{inputs:s}=this.state,i=this.getInputIndex(s,e),l={...this.getInput(s,e)};l[t]=n;const a=[...s];a.splice(i,1,l),this.setState({inputs:a})}handleCustomColumnUpdated(){const{isCustomColumnApplying:e}=this.state;e&&this.setState({isCustomColumnApplying:!1,isSuccessShowing:!0},()=>{this.successButtonTimer=setTimeout(()=>this.setState({isSuccessShowing:!1}),Us.SUCCESS_SHOW_DURATION)})}handleRequestFailed(e){const t=e,{isCustomColumnApplying:n}=this.state;n&&this.setState({isCustomColumnApplying:!1,errorMessage:r.jsxs(r.Fragment,{children:[r.jsxs("p",{children:[r.jsx(ee,{icon:ws})," Failed to apply custom columns."]}),r.jsxs("div",{className:"error-box",children:[t.detail.errorMessage,r.jsx("br",{}),"Table configuration:"," ",JSON.stringify(t.detail.configuration)]})]}),hasRequestFailed:!0})}handleDragEnd(e){if(hn.stopDragging(),!e.destination)return;const{inputs:t}=this.state,n=e.source.index,s=e.destination.index,i=[...t],o=t[n];i.splice(n,1),i.splice(s,0,o),this.setState({inputs:i})}handleEditorTabNavigation(e,t){const{inputs:n}=this.state;if(t){(this.container?.querySelectorAll(".btn-drag-handle")[e]).focus();return}if(e===n.length-1)this.container?.querySelector(".btn-add-column")?.focus();else{const s=e+1;(this.container?.querySelectorAll(".custom-column-input")[s]).focus()}}handleSaveClick(){const{onSave:e,customColumns:t}=this.props,{inputs:n,isCustomColumnApplying:s}=this.state;if(s)return;const i=[];n.forEach(o=>{const{name:l,formula:a}=o;l&&a&&i.push(`${l}=${a}`)}),this.resetErrorMessage(),this.setState({isCustomColumnApplying:i.length>0||t.length>0}),e(i)}resetRequestFailed(){this.setState(({hasRequestFailed:e})=>e?{hasRequestFailed:!1}:null)}renderInputs(){const{inputs:e,hasRequestFailed:t}=this.state,n=new Map;return e.forEach(({name:s})=>n.set(s,(n.get(s)??0)+1)),e.map((s,i)=>{const{eventKey:o,name:l,formula:a}=s,d=(n.get(l)??0)>1;return r.jsx(RT,{inputIndex:i,eventKey:o,name:l,formula:a,onChange:this.handleInputChange,onDeleteColumn:this.handleDeleteColumn,onTabInEditor:this.handleEditorTabNavigation,invalid:t,isDuplicate:d},o)})}renderSaveButton(){const{inputs:e,isCustomColumnApplying:t,isSuccessShowing:n}=this.state,s=e.length>1?"Save Columns":"Save Column",i=e.every(({name:a})=>a===""||Ii.isValidColumnName(a)),o=e.filter(({name:a})=>a!=="").map(({name:a})=>a),l=new Set(o).size===o.length;return r.jsxs(B,{kind:n?"success":"primary",className:Y("btn-apply",{"btn-spinner":t}),disabled:n||t||!i||!l,onClick:this.handleSaveClick,children:[t&&r.jsxs("span",{children:[r.jsx(In,{}),r.jsx("span",{className:"btn-normal-content",children:"Applying"})]}),!n&&!t&&s,n&&r.jsxs(r.Fragment,{children:[r.jsx(ee,{icon:dr})," Success"]})]})}render(){const{onCancel:e}=this.props,{errorMessage:t}=this.state;return r.jsxs("div",{role:"presentation",className:"custom-column-builder-container",ref:n=>{this.container=n},onClick:this.resetRequestFailed,onFocus:this.resetRequestFailed,children:[r.jsx("hr",{}),r.jsx(Pl,{onDragStart:hn.startDragging,onDragEnd:this.handleDragEnd,children:r.jsx(or,{droppableId:"droppable-custom-columns",children:(n,s)=>r.jsxs("div",{ref:n.innerRef,...n.droppableProps,className:Y("droppable-container",{dragging:s.draggingFromThisWith}),children:[this.renderInputs(),n.placeholder]})})}),r.jsx("div",{className:"pt-1 px-3",children:r.jsx(B,{kind:"ghost",className:"btn-add-column",onClick:this.handleAddColumnClick,icon:Es,children:"Add Another Column"})}),r.jsxs("div",{className:"custom-column-builder-footer",children:[t&&r.jsx("div",{className:"error-message",children:t}),r.jsxs("div",{className:"d-flex justify-content-end",children:[r.jsx(B,{kind:"secondary",className:"mr-2",onClick:e,children:"Cancel"}),this.renderSaveButton()]})]})]})}}const DT=Us;var Du=(c=>(c.ADVANCED_SETTINGS="ADVANCED_SETTINGS",c.AGGREGATIONS="AGGREGATIONS",c.AGGREGATION_EDIT="AGGREGATIONS_EDIT",c.CHART_BUILDER="CHART_BUILDER",c.CUSTOM_COLUMN_BUILDER="CUSTOM_COLUMN_BUILDER",c.QUICK_FILTERS="QUICK_FILTERS",c.ROLLUP_ROWS="ROLLUP_ROWS",c.SEARCH_BAR="SEARCH_BAR",c.SELECT_DISTINCT="SELECT_DISTINCT",c.TABLE_EXPORTER="TABLE_EXPORTER",c.VISIBILITY_ORDERING_BUILDER="VISIBILITY_ORDERING_BUILDER",c.CONDITIONAL_FORMATTING="CONDITIONAL_FORMATTING",c.CONDITIONAL_FORMATTING_EDIT="CONDITIONAL_FORMATTING_EDIT",c.GOTO="GOTO",c))(Du||{});const Ne=Du;const Ui=ne.module("RollupRows"),IT=150,Wo="grouped-rollup-rows",Go="ungrouped-rollup-rows";class Qt extends v.Component{static SORT=Object.freeze({ASCENDING:"ASC",DESCENDING:"DESC"});static defaultProps={config:null,onChange:()=>{}};static renderColumn({item:e,isClone:t,selectedCount:n}){const s=e?.name,i=t!==void 0&&t?`${n}`:void 0,o=t!==void 0&&t?"item-list-item-clone":"";return rn.renderTextItem({text:s,badgeText:i,className:o})}static addGroupings(e,t,n=e.length){if(t==null||t.length===0)return e;let s=n;const i=e.filter((o,l)=>t.includes(o)?(l<s&&(s-=1),!1):!0);return i.splice(s,0,...t),i}static isGroupable(e){return!F.isDecimalType(e.type)}constructor(e){super(e),this.handleDeleteClicked=this.handleDeleteClicked.bind(this),this.handleSearchChange=this.handleSearchChange.bind(this),this.handleUngroupedSelect=this.handleUngroupedSelect.bind(this),this.handleUngroupedSelectionChange=this.handleUngroupedSelectionChange.bind(this),this.handleDragStart=this.handleDragStart.bind(this),this.handleDragEnd=this.handleDragEnd.bind(this),this.handleGroupedSelectionChange=this.handleGroupedSelectionChange.bind(this),this.handleShowConstituentsChange=this.handleShowConstituentsChange.bind(this),this.handleShowNonAggregatedColumnsChange=this.handleShowNonAggregatedColumnsChange.bind(this),this.handleSortAscending=this.handleSortAscending.bind(this),this.handleSortDescending=this.handleSortDescending.bind(this),this.renderGroupedItem=this.renderGroupedItem.bind(this),this.ungroupedList=de.createRef(),this.groupedList=de.createRef();const{config:t}=e,{columns:n=[],showConstituents:s=!0,showNonAggregatedColumns:i=!0}=t??{};this.state={ungroupedSelectedRanges:[],columns:n,groupedSelectedRanges:[],searchFilter:"",showConstituents:s,showNonAggregatedColumns:i,dragSource:null,sort:null}}componentDidUpdate(e,t){const{config:n}=this.props,{columns:s,showConstituents:i,showNonAggregatedColumns:o}=this.state;n!==e.config?this.updateFromConfig():(s!==t.columns||i!==t.showConstituents||o!==t.showNonAggregatedColumns)&&(n==null||s!==n.columns||i!==n.showConstituents||o!==n.showNonAggregatedColumns)&&this.sendChange()}componentWillUnmount(){this.search.cancel()}ungroupedList;groupedList;handleSearchChange(e){const t=e.target.value;if(this.setState({searchFilter:t}),!t){this.search.cancel(),this.resetSelection();return}this.search(t)}handleSortAscending(){this.setState(({sort:e})=>({sort:e===Qt.SORT.ASCENDING?null:Qt.SORT.ASCENDING}))}handleSortDescending(){this.setState(({sort:e})=>({sort:e===Qt.SORT.DESCENDING?null:Qt.SORT.DESCENDING}))}resetSelection(){this.setState({ungroupedSelectedRanges:[],groupedSelectedRanges:[]})}search=Ye(e=>{const t=this.getSortedUngroupedColumns(),n=[];let s=null;for(let i=0;i<t.length;i+=1)t[i].name.toLowerCase().includes(e.toLowerCase())&&(s==null&&(s=i),n.push([i,i]));N(s),this.setState({ungroupedSelectedRanges:n}),n.length>0&&this.ungroupedList.current&&this.ungroupedList.current.scrollToItem(s)},IT);handleDragStart(e){Ui.debug("handleDragStart",e),document.documentElement.classList.add("drag-pointer-events-none"),this.setState({dragSource:e.source})}handleDragEnd(e){Ui.debug("handleDragEnd",e),document.documentElement.classList.remove("drag-pointer-events-none"),this.setState({dragSource:null});const{destination:t,source:n}=e;if(t==null||n==null)return;if(t.droppableId===Go){this.setState(({groupedSelectedRanges:o,columns:l})=>{const a=[...l];return hn.reorder(a,o,[],0),{columns:a,ungroupedSelectedRanges:[],groupedSelectedRanges:[]}});return}const s=n.droppableId===Wo;let i=t.index;s&&n.index<t.index&&(i+=1),this.setState(({columns:o,ungroupedSelectedRanges:l,groupedSelectedRanges:a})=>{const d=[...o],h=s?d:this.getSortedUngroupedColumns().map(C=>C.name),u=s?a:l,m=hn.reorder(h,u,d,i),g=s?hn.adjustDestinationIndex(i,a):i,p=[[g,g+m.length-1]];return{columns:d,ungroupedSelectedRanges:[],groupedSelectedRanges:p}}),this.resetSelection()}handleUngroupedSelect(e){Ui.debug("handleUngroupedSelect"),this.setState(({columns:t})=>({columns:Qt.addGroupings(t,[this.getSortedUngroupedColumns()[e].name]),ungroupedSelectedRanges:[],groupedSelectedRanges:[]}))}handleUngroupedSelectionChange(e){Ui.debug2("handleUngroupedSelectionChange",e),this.setState(({ungroupedSelectedRanges:t})=>e===t?null:{ungroupedSelectedRanges:e,groupedSelectedRanges:[]})}handleGroupedSelectionChange(e){Ui.debug2("handleGroupedSelectedRanges",e),this.setState(({groupedSelectedRanges:t})=>e===t?null:{groupedSelectedRanges:e,ungroupedSelectedRanges:[]})}handleDeleteClicked(e){this.setState(({columns:t})=>{const n=t.slice();return n.splice(e,1),{columns:n}})}handleShowConstituentsChange(){this.setState(({showConstituents:e})=>({showConstituents:!e}))}handleShowNonAggregatedColumnsChange(){this.setState(({showNonAggregatedColumns:e})=>({showNonAggregatedColumns:!e}))}updateFromConfig(){const{config:e}=this.props,{columns:t=[],showConstituents:n=!0,showNonAggregatedColumns:s=!0}=e??{};this.setState({columns:t,showConstituents:n,showNonAggregatedColumns:s})}sendChange(){const{onChange:e}=this.props,{columns:t,showConstituents:n,showNonAggregatedColumns:s}=this.state;e({columns:t,showConstituents:n,showNonAggregatedColumns:s})}getCachedUngroupedColumns=Re((e,t)=>e.filter(n=>Qt.isGroupable(n)&&t.find(s=>s===n.name)==null));getCachedSortedColumns=Re((e,t)=>t==null?[...e]:F.sortColumns(e,t===Qt.SORT.ASCENDING));getUngroupedColumns(){const{model:e}=this.props,{columns:t}=this.state,{originalColumns:n}=e;return this.getCachedUngroupedColumns(n,t)}getSortedUngroupedColumns(){const{sort:e}=this.state,t=this.getUngroupedColumns();return this.getCachedSortedColumns(t,e)}renderGroupedItem({item:e,itemIndex:t,isClone:n,selectedCount:s}){const o=`${n!==void 0&&n?"":"  ".repeat(t)}${e}`,l=n!==void 0&&n?`${s}`:void 0,a=n!==void 0&&n?"item-list-item-clone":"";return r.jsxs(r.Fragment,{children:[rn.renderTextItem({text:o,badgeText:l,className:a}),(n===void 0||!n)&&r.jsx(B,{kind:"ghost",className:"btn btn-link btn-link-icon btn-delete-grouping float-right",onClick:()=>this.handleDeleteClicked(t),children:r.jsx(ee,{icon:Gt})})]})}render(){const{columns:e,dragSource:t,searchFilter:n,groupedSelectedRanges:s,ungroupedSelectedRanges:i,showConstituents:o,showNonAggregatedColumns:l,sort:a}=this.state,d=this.getSortedUngroupedColumns();let h=e.length*rn.DEFAULT_ROW_HEIGHT;t?.droppableId===Go&&(h+=rn.DEFAULT_ROW_HEIGHT);const u=d.length*rn.DEFAULT_ROW_HEIGHT+10,m=Math.min(3*rn.DEFAULT_ROW_HEIGHT,u);return r.jsx("div",{role:"menu",className:Y("rollup-rows",{"is-dragging":t!=null}),tabIndex:0,children:r.jsxs(Pl,{onDragEnd:this.handleDragEnd,onDragStart:this.handleDragStart,children:[r.jsxs("div",{className:"rollup-rows-group-by",children:[r.jsx("div",{className:"section-title",children:"Group By"}),e.length===0&&r.jsx(or,{droppableId:"placeholder",children:(g,p)=>r.jsx("div",{className:Y("placeholder","text-muted",{"is-dragging-from-this":p.draggingFromThisWith,"is-dragging-over":p.isDraggingOver,"is-dropping":p.draggingOverWith}),ref:g.innerRef,...g.droppableProps,children:"To create a rollup, drag columns from the list below and drop them into this area."})}),e.length>0&&r.jsx(rn,{draggingItemClassName:"rollup-rows-dragging-grouped-item",draggablePrefix:Wo,droppableId:Wo,itemCount:e.length,items:e,offset:0,onSelectionChange:this.handleGroupedSelectionChange,ref:this.groupedList,renderItem:this.renderGroupedItem,selectedRanges:s,style:{height:h},isMultiSelect:!0})]}),r.jsxs("div",{className:"rollup-rows-available-columns",children:[r.jsx("div",{className:"section-title",children:"Available Grouping Columns"}),r.jsxs("div",{className:"top-menu",children:[r.jsx(Di,{className:"w-100",value:n,matchCount:n?i.length:void 0,placeholder:"Find column...",onChange:this.handleSearchChange}),r.jsxs(B,{kind:"ghost",className:Y("btn-link btn-link-icon",{active:a===Qt.SORT.ASCENDING}),onClick:this.handleSortAscending,children:[r.jsx(ee,{icon:ur}),r.jsx(ot,{children:"Sort ascending"})]}),r.jsxs(B,{kind:"ghost",className:Y("btn-link btn-link-icon",{active:a===Qt.SORT.DESCENDING}),onClick:this.handleSortDescending,children:[r.jsx(ee,{icon:mr}),r.jsx(ot,{children:"Sort descending"})]})]}),r.jsx(rn,{className:"rollup-available-grouping-columns",draggablePrefix:Go,droppableId:Go,itemCount:d.length,items:d,renderItem:Qt.renderColumn,offset:0,onSelect:this.handleUngroupedSelect,onSelectionChange:this.handleUngroupedSelectionChange,ref:this.ungroupedList,selectedRanges:i,style:{maxHeight:u,minHeight:m},isDropDisabled:t?.droppableId!==Wo,isMultiSelect:!0}),r.jsxs("div",{className:"bottom-menu",children:[r.jsx("div",{className:"label",children:"Show:"}),r.jsx(nn,{checked:o,onChange:this.handleShowConstituentsChange,children:"Constituents"}),r.jsx(nn,{checked:l,onChange:this.handleShowNonAggregatedColumnsChange,children:"Non-Aggregated Columns"})]})]})]})})}}const FT=Qt;const NT=ne.module("TableCsvExporter");class Be extends v.Component{static FILENAME_DATE_FORMAT="yyyy-MM-dd-HHmmss";static DOWNLOAD_STATUS={INITIATING:"INITIATING",DOWNLOADING:"DOWNLOADING",FINISHED:"FINISHED",CANCELED:"CANCELED"};static DOWNLOAD_ROW_OPTIONS={ALL_ROWS:"ALL_ROWS",SELECTED_ROWS:"SELECTED_ROWS",CUSTOMIZED_ROWS:"CUSTOMIZED_ROWS"};static CUSTOMIZED_ROWS_OPTIONS={FIRST:"FIRST",LAST:"LAST"};static DEFAULT_DOWNLOAD_ROWS=100;static defaultProps={onDownloadStart:()=>{},isDownloading:!1,tableDownloadStatus:"",tableDownloadProgress:0,tableDownloadEstimatedTime:null,selectedRanges:[]};static getDateString(){return I.i18n.DateTimeFormat.format(Be.FILENAME_DATE_FORMAT,new Date)}constructor(e){super(e),this.handleDownloadClick=this.handleDownloadClick.bind(this),this.handleDownloadRowOptionChanged=this.handleDownloadRowOptionChanged.bind(this),this.handleCustomizedDownloadRowOptionChanged=this.handleCustomizedDownloadRowOptionChanged.bind(this),this.handleCustomizedDownloadRowsChanged=this.handleCustomizedDownloadRowsChanged.bind(this),this.handleIncludeColumnHeadersChanged=this.handleIncludeColumnHeadersChanged.bind(this),this.handleIncludeHiddenColumnsChanged=this.handleIncludeHiddenColumnsChanged.bind(this),this.handleUseUnformattedValuesChanged=this.handleUseUnformattedValuesChanged.bind(this);const{name:t}=e;this.state={fileName:`${t}-${Be.getDateString()}.csv`,downloadRowOption:Be.DOWNLOAD_ROW_OPTIONS.ALL_ROWS,customizedDownloadRowOption:Be.CUSTOMIZED_ROWS_OPTIONS.FIRST,customizedDownloadRows:Be.DEFAULT_DOWNLOAD_ROWS,includeColumnHeaders:!0,includeHiddenColumns:!1,useUnformattedValues:!1,errorMessage:null,id:qe.generate()}}getSnapshotRanges(){const{model:e,selectedRanges:t}=this.props,{downloadRowOption:n,customizedDownloadRowOption:s,customizedDownloadRows:i}=this.state,{rowCount:o,columnCount:l}=e;let a=[];switch(n){case Be.DOWNLOAD_ROW_OPTIONS.ALL_ROWS:a.push(new te(0,0,l-1,o-1));break;case Be.DOWNLOAD_ROW_OPTIONS.SELECTED_ROWS:a=t.map(d=>({...d,startColumn:0,endColumn:l-1})).sort((d,h)=>d.startRow!=null&&h.startRow!=null?d.startRow-h.startRow:0);break;case Be.DOWNLOAD_ROW_OPTIONS.CUSTOMIZED_ROWS:switch(s){case Be.CUSTOMIZED_ROWS_OPTIONS.FIRST:a.push(new te(0,0,l-1,Math.min(i-1,o-1)));break;case Be.CUSTOMIZED_ROWS_OPTIONS.LAST:a.push(new te(0,Math.max(0,o-i),l-1,o-1));break}break}return a}getModelRanges(e){const{userColumnWidths:t,movedColumns:n}=this.props,{includeHiddenColumns:s}=this.state,i=Se.getHiddenColumns(t);let o=_.getModelRanges(e,n);if(!s&&i.length>0){const l=i.map(te.makeColumn);o=te.subtractRangesFromRanges(o,l)}return o}resetDownloadState(){this.setState({errorMessage:null})}async handleDownloadClick(){const{model:e,isDownloading:t,onDownloadStart:n,onDownload:s,onCancel:i}=this.props,{fileName:o,includeColumnHeaders:l,useUnformattedValues:a}=this.state;if(t){i();return}this.resetDownloadState();const d=this.getSnapshotRanges(),h=this.getModelRanges(d);if(this.validateOptionInput()){n();try{const u=await e.export(),m=u.setViewport(0,0);await m.getViewportData(),s(o,u,m,d,h,l,a)}catch(u){NT.error("CSV download failed",u),this.setState({errorMessage:r.jsxs("p",{children:[r.jsx(ee,{icon:ws})," ",`${u}`]})}),i()}}}handleDownloadRowOptionChanged(e){this.setState({downloadRowOption:e.target.value})}handleCustomizedDownloadRowOptionChanged(e){this.setState({customizedDownloadRowOption:e.target.value})}handleCustomizedDownloadRowsChanged(e){this.setState({customizedDownloadRows:parseInt(e.target.value,10)})}handleIncludeColumnHeadersChanged(){this.setState(({includeColumnHeaders:e})=>({includeColumnHeaders:!e}))}handleIncludeHiddenColumnsChanged(){this.setState(({includeHiddenColumns:e})=>({includeHiddenColumns:!e}))}handleUseUnformattedValuesChanged(){this.setState(({useUnformattedValues:e})=>({useUnformattedValues:!e}))}validateOptionInput(){const{selectedRanges:e}=this.props,{downloadRowOption:t,customizedDownloadRows:n}=this.state;return t===Be.DOWNLOAD_ROW_OPTIONS.SELECTED_ROWS&&e.length===0?(this.setState({errorMessage:r.jsxs("p",{children:[r.jsx(ee,{icon:ws})," No rows selected. Please select some rows in the table."]})}),!1):t===Be.DOWNLOAD_ROW_OPTIONS.CUSTOMIZED_ROWS&&n<=0?(this.setState({errorMessage:r.jsxs("p",{children:[r.jsx(ee,{icon:ws})," Number of rows to output must be greater than 0"]})}),!1):!0}render(){const{model:e,isDownloading:t,tableDownloadProgress:n,tableDownloadEstimatedTime:s,selectedRanges:i,tableDownloadStatus:o}=this.props,{fileName:l,downloadRowOption:a,customizedDownloadRowOption:d,customizedDownloadRows:h,includeColumnHeaders:u,includeHiddenColumns:m,useUnformattedValues:g,errorMessage:p,id:C}=this.state,{rowCount:f}=e;return r.jsxs("div",{className:"table-csv-exporter",children:[r.jsx("div",{className:"section-title",children:"Download Rows"}),r.jsx("div",{className:"form-group",children:r.jsxs(Ul,{onChange:this.handleDownloadRowOptionChanged,value:a,disabled:t,children:[r.jsxs(Wn,{value:Be.DOWNLOAD_ROW_OPTIONS.ALL_ROWS,"data-testid":"radio-csv-exporter-download-all",children:["All Rows",r.jsx("span",{className:"text-muted ml-2",children:`(${f.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1,")} rows)`})]}),r.jsxs(Wn,{value:Be.DOWNLOAD_ROW_OPTIONS.SELECTED_ROWS,"data-testid":"radio-csv-exporter-only-selected",children:["Only Selected Rows",r.jsx("span",{className:"text-muted ml-2",children:i.length>0?`(${te.rowCount(i).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1,")} rows)`:null})]}),r.jsx(Wn,{value:Be.DOWNLOAD_ROW_OPTIONS.CUSTOMIZED_ROWS,"data-testid":"radio-csv-exporter-customized-rows",children:r.jsxs("div",{className:"radio-input-row",role:"presentation",onClick:()=>{this.setState({downloadRowOption:Be.DOWNLOAD_ROW_OPTIONS.CUSTOMIZED_ROWS})},children:[r.jsxs("select",{value:d,"data-testid":"select-csv-exporter-customized-rows",className:"custom-select",disabled:t,onChange:this.handleCustomizedDownloadRowOptionChanged,children:[r.jsx("option",{value:"FIRST",children:"First"}),r.jsx("option",{value:"LAST",children:"Last"})]}),r.jsx("input",{type:"number",className:"form-control",id:`customizedRows-${C}`,"data-testid":"input-csv-exporter-customized-rows",name:`customizedRows-${C}`,placeholder:"100",value:h,disabled:t,onChange:this.handleCustomizedDownloadRowsChanged}),r.jsx("div",{children:"Rows"})]})})]})}),r.jsxs("div",{className:"form-group",children:[r.jsx("label",{htmlFor:`customizedRows-${C}`,children:"File Name"}),r.jsx("input",{type:"text",className:"form-control",id:`filename-${C}`,"data-testid":"input-csv-exporter-file-name",name:`filename-${C}`,value:l,onChange:b=>{this.setState({fileName:b.target.value})},disabled:t})]}),r.jsxs("div",{className:"checkbox-options",children:[r.jsx(nn,{checked:u,onChange:this.handleIncludeColumnHeadersChanged,children:"Include column headers"}),r.jsx(nn,{checked:m,onChange:this.handleIncludeHiddenColumnsChanged,children:"Include hidden columns"}),r.jsx(nn,{checked:g,onChange:this.handleUseUnformattedValuesChanged,children:"Use unformatted values"})]}),r.jsxs("div",{className:"section-footer flex-column",children:[p!=null&&r.jsx("div",{className:"error-message",children:p}),o&&r.jsxs("div",{className:"download-status",children:[(o===Be.DOWNLOAD_STATUS.DOWNLOADING||o===Be.DOWNLOAD_STATUS.INITIATING)&&r.jsxs(r.Fragment,{children:[o===Be.DOWNLOAD_STATUS.INITIATING&&r.jsx("div",{className:"text-muted",children:"Starting Download..."}),o===Be.DOWNLOAD_STATUS.DOWNLOADING&&r.jsxs("div",{className:"text-muted d-flex justify-content-between",children:[r.jsx("span",{children:s||s===0?`Estimated time: ${jl.formatElapsedTime(s)}`:null}),r.jsx("span",{children:`${n}%`})]})]}),o===Be.DOWNLOAD_STATUS.FINISHED&&r.jsx("div",{className:"text-muted text-right",children:"Download Completed"}),o===Be.DOWNLOAD_STATUS.CANCELED&&r.jsx("div",{className:"text-muted",children:"Download Canceled"}),(o===Be.DOWNLOAD_STATUS.DOWNLOADING||o===Be.DOWNLOAD_STATUS.INITIATING)&&r.jsx("div",{className:"progress",children:r.jsx("div",{className:"progress-bar progress-bar-striped progress-bar-animated",style:{width:`${n}%`}})}),o===Be.DOWNLOAD_STATUS.FINISHED&&r.jsx("div",{className:"progress",children:r.jsx("div",{className:"progress-bar bg-success",style:{width:`${n}%`}})})]}),r.jsxs(B,{kind:"primary","data-testid":"btn-csv-exporter-download",className:Y("btn-downloading",{"btn-spinner btn-cancelable":t}),onClick:this.handleDownloadClick,children:[t&&r.jsxs("span",{children:[r.jsx(In,{}),r.jsx("span",{className:"btn-normal-content",children:"Downloading"}),r.jsx("span",{className:"btn-hover-content",children:"Cancel"})]}),!t&&"Download"]})]})]})}}const Ms=Be,An=ne.module("TableSaver"),kT="yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS z";function MT(c){return c.added!==void 0}function LT(c){if(!MT(c))throw new Error("event is not UpdateEventData")}class jn extends v.PureComponent{static DOWNLOAD_CELL_CHUNK=6e3;static SNAPSHOT_BUFFER_SIZE=5;static STREAM_TIMEOUT=8e3;static SNAPSHOT_HANDLER_TIMEOUT=5;static defaultProps={getDownloadWorker:()=>Promise.reject(new Error("Download worker not provided")),isDownloading:!1,onDownloadCompleted:()=>{},onDownloadCanceled:()=>{},onDownloadProgressUpdate:()=>{}};static csvEscapeString(e){return`"${e.replace(/"/g,'""')}"`}constructor(e){super(e),this.handlePortMessage=this.handlePortMessage.bind(this),this.handleSnapshotResolved=this.handleSnapshotResolved.bind(this),this.handleDownloadTimeout=this.handleDownloadTimeout.bind(this),this.state={},this.gridRanges=[],this.gridRangeCounter=0,this.rangedSnapshotsTotal=[],this.rangedSnapshotCounter=0,this.includeColumnHeaders=!0,this.useUnformattedValues=!1,this.snapshotsTotal=0,this.snapshotCounter=0,this.snapshotsBuffer=new Map,this.currentSnapshotIndex=0,this.snapshotPending=0,this.cancelableSnapshots=[],this.iframes=[],this.useBlobFallback=!1}componentDidMount(){const{getDownloadWorker:e}=this.props;e().then(t=>{An.info("found active service worker"),this.sw=t,this.sw.postMessage("ping")}).catch(t=>{An.warn("Download csv is not optimized.",t),this.useBlobFallback=!0})}componentWillUnmount(){this.iframes.length>0&&this.iframes.forEach(e=>{e.remove()}),this.streamTimeout&&clearTimeout(this.streamTimeout),this.snapshotHandlerTimeout&&clearTimeout(this.snapshotHandlerTimeout)}sw;port;fileWriter;table;tableSubscription;columns;fileName;includeColumnHeaders;useUnformattedValues;chunkRows;gridRanges;gridRangeCounter;rangedSnapshotsTotal;rangedSnapshotCounter;snapshotsTotal;snapshotCounter;snapshotsBuffer;currentSnapshotIndex;snapshotPending;cancelableSnapshots;streamTimeout;snapshotHandlerTimeout;downloadStartTime;iframes;useBlobFallback;getCachedCustomColumnFormatFlag=pn($n.isCustomColumnFormatDefined,{max:1e4});createWriterStream(e){const t=this.useBlobFallback,n=[];let s=null;t&&(s=TextEncoder.prototype.encode.bind(new TextEncoder));const{fileName:i}=this,o={};return t?(o.write=l=>{N(s),l.header!==void 0&&n.push(s(l.header)),l.rows!==void 0&&n.push(s(l.rows))},o.close=()=>{N(i);const l=new Blob(n,{type:"application/octet-stream; charset=utf-8"}),a=document.createElement("a");a.href=URL.createObjectURL(l),a.download=i,a.click()},o.abort=()=>{e.postMessage({cancel:!0}),e.close()}):(o.write=l=>{e.postMessage(l)},o.close=()=>{e.postMessage({end:!0}),e.close()},o.abort=()=>{e.postMessage({cancel:!0}),e.close()}),new WritableStream(o)}startDownload(e,t,n,s,i,o,l){const{isDownloading:a}=this.props;if(a)return;this.downloadStartTime=Date.now(),An.info(`start downloading ${e}`),this.table=t,this.columns=Se.columnsFromRanges(i,t.columns),this.tableSubscription=n,this.gridRanges=s,this.includeColumnHeaders=o,this.useUnformattedValues=l;const d=encodeURIComponent(e.replace(/\//g,":")).replace(/['()]/g,escape).replace(/\*/g,"%2A"),h=new MessageChannel;if(this.port=h.port1,this.fileName=e,this.fileWriter=this.createWriterStream(this.port).getWriter(),this.useBlobFallback){this.writeCsvTable(o);return}this.sw&&this.sw.postMessage({encodedFileName:d},[h.port2]),this.port.onmessage=this.handlePortMessage}finishDownload(){this.table&&this.table.close(),this.tableSubscription&&this.tableSubscription.close(),this.fileWriter&&this.fileWriter.close();const{onDownloadCompleted:e}=this.props;e(),this.resetTableSaver(),this.downloadStartTime!==void 0&&An.info(`download finished, total elapsed time ${(Date.now()-this.downloadStartTime)/1e3} seconds`)}cancelDownload(){this.table&&this.table.close(),this.tableSubscription&&this.tableSubscription.close(),this.fileWriter&&this.fileWriter.abort(),this.cancelableSnapshots.forEach(t=>{t&&(t.catch(()=>null),t.cancel())});const{onDownloadCanceled:e}=this.props;e(),this.resetTableSaver()}resetTableSaver(){this.table=void 0,this.tableSubscription=void 0,this.columns=void 0,this.chunkRows=void 0,this.gridRanges=[],this.gridRangeCounter=0,this.rangedSnapshotsTotal=[],this.rangedSnapshotCounter=0,this.includeColumnHeaders=!0,this.useUnformattedValues=!1,this.snapshotsTotal=0,this.snapshotCounter=0,this.snapshotsBuffer=new Map,this.currentSnapshotIndex=0,this.snapshotPending=0,this.cancelableSnapshots=[],this.streamTimeout!=null&&clearTimeout(this.streamTimeout),this.snapshotHandlerTimeout!=null&&clearTimeout(this.snapshotHandlerTimeout),this.streamTimeout=void 0,this.snapshotHandlerTimeout=void 0}handleDownloadTimeout(){An.info("download canceled"),this.cancelDownload()}writeTableHeader(){let e="";if(this.columns)for(let t=0;t<this.columns.length;t+=1)e+=this.columns[t].name,e+=t===this.columns.length-1?`
20
+ `;w(H),p(!0),S(H)}else R(O.shiftKey?mn.UP:mn.DOWN);break;case"Tab":O.preventDefault(),R(O.shiftKey?mn.LEFT:mn.RIGHT);break;case"ArrowDown":case"ArrowUp":case"ArrowLeft":case"ArrowRight":C&&(O.preventDefault(),R(gw(O.key)));break}},[y,R,C,w,p,S,b]),M=v.useCallback(O=>{a(O)},[a]);return r.jsx("textarea",{ref:h,className:Y("grid-cell-input-field",e),value:b,onBlur:x,onChange:T,onKeyDown:D,onContextMenu:M,onClick:E,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false",disabled:t,style:d})}Pr.propTypes={selectionRange:z.arrayOf(z.number),className:z.string,disabled:z.bool,isQuickEdit:z.bool,value:z.string,onChange:z.func,onCancel:z.func,onDone:z.func,onContextMenu:z.func,style:z.shape({})};Pr.defaultProps={selectionRange:null,className:"",disabled:!1,value:"",isQuickEdit:!0,onChange:()=>{},onCancel:()=>{},onDone:()=>{},onContextMenu:()=>{},style:{}};const pw=de.createContext({}),fw=pw;class hs extends v.PureComponent{static contextType=fw;static defaultProps={canvasOptions:{alpha:!1},isStickyBottom:!1,isStickyRight:!1,isStuckToBottom:!1,isStuckToRight:!1,keyHandlers:ke,mouseHandlers:ke,movedColumns:ke,movedRows:ke,onError:()=>{},onSelectionChanged:()=>{},onMovedColumnsChanged:e=>{},onMoveColumnComplete:()=>{},onMovedRowsChanged:()=>{},onMoveRowComplete:()=>{},onViewChanged:()=>{},onTokenClicked:e=>{wl(e)&&window.open(e.href,"_blank","noopener,noreferrer")},stateOverride:{},theme:{autoSelectColumn:!1,autoSelectRow:!1}};static pixelsPerLine=100/3;static dragTimeout=1e3;static getTheme=ge((e,t)=>({...IS,...e,...t}));static getScale(e){const t=window.devicePixelRatio||1,n=e,s=n.webkitBackingStorePixelRatio??n.mozBackingStorePixelRatio??n.msBackingStorePixelRatio??n.oBackingStorePixelRatio??n.backingStorePixelRatio??1;return t/s}static getCursorClassName(e){return e!=null&&e!==""?`grid-cursor-${e}`:null}renderer;metricCalculator;canvas;canvasContext;animationFrame;prevMetrics;metrics;renderState;documentCursor;dragTimer;keyHandlers;mouseHandlers;constructor(e){super(e),this.handleClick=this.handleClick.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.handleEditCellCancel=this.handleEditCellCancel.bind(this),this.handleEditCellChange=this.handleEditCellChange.bind(this),this.handleEditCellCommit=this.handleEditCellCommit.bind(this),this.handleDoubleClick=this.handleDoubleClick.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseDrag=this.handleMouseDrag.bind(this),this.handleMouseMove=this.handleMouseMove.bind(this),this.handleMouseLeave=this.handleMouseLeave.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this),this.handleResize=this.handleResize.bind(this),this.handleWheel=this.handleWheel.bind(this);const{isStuckToBottom:t,isStuckToRight:n,metricCalculator:s,movedColumns:i,movedRows:o,renderer:l}=e;this.renderer=l||new fu,this.metricCalculator=s||new xS,this.canvas=null,this.canvasContext=null,this.animationFrame=null,this.prevMetrics=null,this.metrics=null,this.renderState={},this.documentCursor=null,this.dragTimer=null,this.keyHandlers=[new rw(400),new mw(450),new iw(500),new lw(900)],this.mouseHandlers=[new qS(100),new uu(200),new YS(300),new GS(400),new ew(450),new QS(500),new zS(600),new ZS(700),new Xa(800),new tw(825),new VS(900)],this.state={top:0,left:0,topOffset:0,leftOffset:0,draggingColumn:null,draggingRow:null,draggingRowOffset:null,draggingColumnSeparator:null,draggingRowSeparator:null,isDraggingHorizontalScrollBar:!1,isDraggingVerticalScrollBar:!1,isDragging:!1,mouseX:null,mouseY:null,movedColumns:i,movedRows:o,cursorRow:null,cursorColumn:null,selectionStartRow:null,selectionStartColumn:null,selectionEndRow:null,selectionEndColumn:null,selectedRanges:ke,lastSelectedRanges:ke,cursor:null,editingCell:null,isStuckToBottom:t,isStuckToRight:n}}componentDidMount(){this.initContext(),this.canvas?.addEventListener("wheel",this.handleWheel,{passive:!1}),window.addEventListener("resize",this.handleResize),this.updateCanvas();const{isStuckToBottom:e,isStuckToRight:t}=this.props;e&&this.scrollToBottom(),t&&this.scrollToRight()}componentDidUpdate(e,t){const{isStickyBottom:n,isStickyRight:s,movedColumns:i,movedRows:o,onMovedColumnsChanged:l,onMoveColumnComplete:a,onMovedRowsChanged:d,onMoveRowComplete:h}=this.props,{isStickyBottom:u,isStickyRight:m,movedColumns:g,movedRows:p}=e,{movedColumns:C,movedRows:f}=t,{draggingColumn:b,draggingRow:w,movedColumns:S,movedRows:T}=this.state;g!==i&&this.setState({movedColumns:i}),p!==o&&this.setState({movedRows:o}),C!==S&&l(S),t.draggingColumn!=null&&b==null&&a(S),f!==T&&d(T),t.draggingRow!=null&&w==null&&h(T),n!==u&&this.setState({isStuckToBottom:!1}),s!==m&&this.setState({isStuckToRight:!1}),this.updateMetrics(),this.requestUpdateCanvas(),this.checkStickyScroll(),this.validateSelection()&&this.checkSelectionChange(t)}componentWillUnmount(){this.animationFrame!=null&&cancelAnimationFrame(this.animationFrame),this.canvas?.removeEventListener("wheel",this.handleWheel),window.removeEventListener("mousemove",this.handleMouseDrag,!0),window.removeEventListener("mouseup",this.handleMouseUp,!0),window.removeEventListener("resize",this.handleResize),this.stopDragTimer()}getTheme(){const{theme:e}=this.props;return hs.getTheme(this.context,e)}getGridPointFromEvent(e){Kd(this.canvas);const t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left,s=e.clientY-t.top;return this.getGridPointFromXY(n,s)}getGridPointFromXY(e,t){if(!this.metrics)throw new Error("metrics must be set");return _.getGridPointFromXY(e,t,this.metrics)}getMetricState(e=this.state){const t=this.getTheme(),{model:n,stateOverride:s}=this.props;if(!this.canvasContext||!this.canvas)throw new Error("Canvas and context must be defined to get metrics");const i=this.canvasContext,o=this.canvas.clientWidth,l=this.canvas.clientHeight,{left:a,top:d,leftOffset:h,topOffset:u,movedColumns:m,movedRows:g,isDraggingHorizontalScrollBar:p,isDraggingVerticalScrollBar:C,draggingColumn:f}=e;return{left:a,top:d,leftOffset:h,topOffset:u,width:o,height:l,context:i,theme:t,model:n,movedColumns:m,movedRows:g,isDraggingHorizontalScrollBar:p,isDraggingVerticalScrollBar:C,draggingColumn:f,...s}}getCachedKeyHandlers=ge(e=>[...e,...this.keyHandlers].sort((t,n)=>t.order-n.order));getKeyHandlers(){const{keyHandlers:e}=this.props;return this.getCachedKeyHandlers(e)}getCachedMouseHandlers=ge(e=>[...e,...this.mouseHandlers].sort((t,n)=>t.order-n.order));getMouseHandlers(){const{mouseHandlers:e}=this.props;return this.getCachedMouseHandlers(e)}getModelColumn(e){const t=this.metrics?.modelColumns?.get(e);if(t===void 0)throw new Error(`Unable to get ModelIndex for column ${e}`);return t}getModelRow(e){const t=this.metrics?.modelRows?.get(e);if(t===void 0)throw new Error(`Unable to get ModelIndex for row ${e}`);return t}toggleRowExpanded(e,t=!1){const n=this.getModelRow(e),{model:s}=this.props;je(s)&&s.isRowExpandable(n)&&s.setRowExpanded(n,!s.isRowExpanded(n),t),this.clearSelectedRanges(),this.commitSelection(),this.moveCursorToPosition(0,e),this.commitSelection(),this.setState({isStuckToBottom:!1})}scrollToBottom(){if(!this.metrics)return;const{bottomVisible:e,rowCount:t,top:n,lastTop:s}=this.metrics;(e<t-1&&e>0||n>s)&&this.setState({top:s})}scrollToRight(){if(!this.metrics)return;const{rightVisible:e,columnCount:t,left:n,lastLeft:s}=this.metrics;(e<t-1&&e>0||n>s)&&this.setState({left:s})}setSelectedRanges(e){const{model:t}=this.props,{columnCount:n,rowCount:s}=t,{cursorRow:i,cursorColumn:o,selectedRanges:l}=this.state;if(this.setState({selectedRanges:e,lastSelectedRanges:l}),e.length>0){const a=Ie.boundedRange(e[0],n,s);let d=i,h=o;a.containsCell(o,i)||({row:d,column:h}=a.startCell()),this.setState({selectionStartColumn:a.startColumn,selectionStartRow:a.startRow,selectionEndColumn:a.endColumn,selectionEndRow:a.endRow,cursorColumn:h,cursorRow:d})}}initContext(){const{canvas:e}=this,{canvasOptions:t}=this.props;if(!e)throw new Error("Canvas not set");this.canvasContext=e.getContext("2d",t)}requestUpdateCanvas(){this.animationFrame==null&&(this.animationFrame=requestAnimationFrame(()=>{this.animationFrame=null,this.updateCanvas()}))}updateCanvas(){this.updateCanvasScale(),this.updateMetrics(),this.updateRenderState();const{canvasContext:e,metrics:t,renderState:n}=this;N(e),N(t),N(n),this.renderer.configureContext(e,n);const{onViewChanged:s}=this.props;s(t),this.drawCanvas(t)}updateCanvasScale(){const{canvas:e,canvasContext:t}=this;if(!e)throw new Error("canvas not set");if(!t)throw new Error("canvasContext not set");if(!e.parentElement)throw new Error("Canvas has no parent element");const n=hs.getScale(t),s=e.parentElement.getBoundingClientRect(),i=Math.floor(s.width),o=Math.floor(s.height);e.style.width=`${i}px`,e.style.height=`${o}px`,e.width=i*n,e.height=o*n,t.scale(n,n)}updateScrollBounds(){if(!this.metrics)throw new Error("metrics not set");const{left:e,top:t}=this.state,{lastLeft:n,lastTop:s}=this.metrics;e>n&&this.setState({left:n,leftOffset:0}),t>s&&this.setState({top:s,topOffset:0})}checkStickyScroll(){if(this.metrics){if(this.prevMetrics){const{rowCount:e,columnCount:t,height:n,width:s}=this.metrics,{rowCount:i,columnCount:o,height:l,width:a}=this.prevMetrics;if(i!==e||n!==l){const{isStuckToBottom:d}=this.state;d&&this.scrollToBottom()}if(o!==t||s!==a){const{isStuckToRight:d}=this.state;d&&this.scrollToRight()}}this.prevMetrics=this.metrics}}updateMetrics(e=this.state){this.prevMetrics=this.metrics;const{metricCalculator:t}=this,n=this.getMetricState(e);return this.metrics=t.getMetrics(n),this.updateScrollBounds(),this.metrics}checkSelectionChange(e){const{selectedRanges:t}=e,{selectedRanges:n}=this.state;if(n!==t){const{onSelectionChanged:s}=this.props;s(n)}}validateSelection(){const{model:e}=this.props,{selectedRanges:t}=this.state,{columnCount:n,rowCount:s}=e;for(let i=0;i<t.length;i+=1){const o=t[i];if(o.endColumn!=null&&o.endColumn>=n||o.endRow!=null&&o.endRow>=s)return this.setState({selectedRanges:[],lastSelectedRanges:[]}),!1}return!0}clearSelectedRanges(){const{selectedRanges:e}=this.state;this.setState({selectedRanges:[],lastSelectedRanges:e})}trimSelectedRanges(){const{selectedRanges:e}=this.state;e.length>0&&this.setState({selectedRanges:e.slice(e.length-1)})}beginSelection(e,t){this.setState({selectionStartColumn:e,selectionStartRow:t,selectionEndColumn:e,selectionEndRow:t,cursorColumn:e,cursorRow:t})}moveSelection(e,t,n=!1,s=!1){this.setState(i=>{const{selectedRanges:o,selectionStartRow:l,selectionStartColumn:a}=i,{theme:d}=this.props,{autoSelectRow:h,autoSelectColumn:u}=d;if(n&&o.length>0){const C=o[o.length-1];let f=null,b=null,w=null,S=null;s?(f=h!==void 0&&h?null:Math.min(e??0,C.startColumn??0),b=u!==void 0&&u?null:Math.min(t??0,C.startRow??0),w=h!==void 0&&h?null:Math.max(e??0,C.endColumn??0),S=u!==void 0&&u?null:Math.max(t??0,C.endRow??0)):(f=C.startColumn,b=C.startRow,(a!=null||l!=null)&&((h===void 0||!h)&&(f=a),(u===void 0||!u)&&(b=l)),w=h!==void 0&&h?null:e,S=u!==void 0&&u?null:t);const T=Ie.makeNormalized(f,b,w,S);if(C.equals(T))return null;const y=[...o];return y[y.length-1]=T,{selectedRanges:y,selectionEndColumn:e,selectionEndRow:t}}const m=[...o],g=h!==void 0&&h?null:e,p=u!==void 0&&u?null:t;return m.push(Ie.makeNormalized(g,p,g,p)),{selectedRanges:m,selectionEndColumn:e,selectionEndRow:t}})}commitSelection(){this.setState(e=>{const{theme:t}=this.props,{autoSelectRow:n}=t,{selectedRanges:s,lastSelectedRanges:i,cursorRow:o,cursorColumn:l}=e;if(s.length===1&&(n!==void 0&&n?Ie.rowCount(s)===1:Ie.cellCount(s)===1)&&Ie.rangeArraysEqual(s,i))return{selectedRanges:[],lastSelectedRanges:[],cursorColumn:null,cursorRow:null};let a=s.slice();if(a.length>1){const u=a[a.length-1];for(let m=0;m<a.length-1;m+=1){const g=a[m];if(g.contains(u)){const p=g.subtract(u);a.pop(),a.splice(m,1),a=a.concat(p);break}}a=Ie.consolidate(a)}let d=l,h=o;if(!Ie.containsCell(a,l,o)){const{model:u}=this.props,{columnCount:m,rowCount:g}=u,p=Ie.nextCell(Ie.boundedRanges(s,m,g));p!=null?{column:d,row:h}=p:(d=null,h=null)}return a.length===0&&(d=null,h=null),{cursorRow:h,cursorColumn:d,selectedRanges:a,lastSelectedRanges:s}})}setFocusRow(e){if(!this.metrics||!this.prevMetrics)return;const{gridY:t,height:n,lastTop:s,userRowHeights:i,rowHeight:o}=this.metrics,l=n-t,a=Math.round(l/2)+(i.get(e)??o),d=this.getMetricState(),h=this.metricCalculator.getLastTop(d,e+1,a);this.setState({top:Math.min(s,h),selectedRanges:[new Ie(null,e,null,e)],isStuckToBottom:!1});const{cursorColumn:u}=this.state;this.moveCursorToPosition(u,e,!1,!1)}selectAll(){const{model:e,theme:t}=this.props,{autoSelectRow:n,autoSelectColumn:s}=t,i=s!==void 0&&s?null:0,o=s!==void 0&&s?null:e.rowCount-1,l=n!==void 0&&n?null:0,a=n!==void 0&&n?null:e.columnCount-1;this.setSelectedRanges([new Ie(l,i,a,o)])}moveCursor(e,t,n){const{cursorRow:s,cursorColumn:i,selectionEndColumn:o,selectionEndRow:l}=this.state,a=n?o:i,d=n?l:s;if(d===null||a===null){const{left:h,top:u}=this.state;this.moveCursorToPosition(h,u,n)}else{const{model:h}=this.props,{columnCount:u,rowCount:m}=h,g=Oe(a+e,0,u-1),p=Oe(d+t,0,m-1);this.moveCursorToPosition(g,p,n)}}moveCursorInDirection(e=Ie.SELECTION_DIRECTION.DOWN){const{model:t}=this.props,{columnCount:n,rowCount:s}=t,{cursorRow:i,cursorColumn:o,selectedRanges:l}=this.state,a=l.length>0?l:[Ie.makeCell(o,i)];let d=null;if(a.length===1&&Ie.cellCount(a)===1){const h=new Ie(0,0,n-1,s-1);d=h.nextCell(o,i,e)??h.startCell(e)}else d=Ie.nextCell(Ie.boundedRanges(a,n,s),o,i,e);if(d!=null){const{column:h,row:u}=d;this.setState({cursorColumn:h,cursorRow:u}),Ie.containsCell(l,h,u)||this.setState({selectedRanges:[Ie.makeCell(h,u)],selectionStartColumn:h,selectionStartRow:u,selectionEndColumn:h,selectionEndRow:u}),this.moveViewToCell(d.column,d.row)}}moveCursorToPosition(e,t,n=!1,s=!0,i=!1){n||this.beginSelection(e,t),this.moveSelection(e,t,n,i),s&&this.moveViewToCell(e,t)}moveViewToCell(e,t){if(!this.metrics)throw new Error("metrics not set");const{metricCalculator:n}=this,{bottomVisible:s,rightVisible:i,topVisible:o,leftVisible:l}=this.metrics,a=this.getMetricState(this.state);let{top:d,left:h,topOffset:u,leftOffset:m}=this.state;t!=null&&!_.isFloatingRow(t,this.metrics)&&(t<o?(d=n.getTopForTopVisible(a,t),u=0):t>s&&(d=n.getTopForBottomVisible(a,t),u=0)),e!=null&&!_.isFloatingColumn(e,this.metrics)&&(e<l?(h=n.getLeftForLeftVisible(a,e),m=0):e>i&&(h=n.getLeftForRightVisible(a,e),m=0)),this.setViewState({top:d,left:h,topOffset:u,leftOffset:m})}setViewState(e,t=!1){if(!this.metrics)throw new Error("metrics not set");const{isStickyBottom:n,isStickyRight:s}=this.props,{top:i,left:o}=e,{lastTop:l,lastLeft:a}=this.metrics;i!=null&&this.setState({isStuckToBottom:n&&i>=l}),o!=null&&this.setState({isStuckToRight:s&&o>=a}),this.setState(e),t&&this.forceUpdate()}startEditing(e,t,n=!1,s,i){const{model:o}=this.props;if(!Xe(o))throw new Error("model is not editable");const l=this.getModelColumn(e),a=this.getModelRow(t),d={column:e,row:t,selectionRange:s,value:i!==void 0?i:o.editValueForCell(l,a),isQuickEdit:n};this.setState({editingCell:d,cursorColumn:e,cursorRow:t}),this.moveViewToCell(e,t)}isValidForCell(e,t,n){const{model:s}=this.props,i=this.getModelColumn(e),o=this.getModelRow(t);return Xe(s)&&s.isValidForCell(i,o,n)}async pasteValue(e){const{model:t}=this.props,{movedColumns:n,movedRows:s,selectedRanges:i}=this.state;try{if(Yd(t),!t.isEditable||!i.every(m=>t.isEditableRange(m)))throw new va("Can't paste in to read-only area.");if(i.length<=0)throw new va("Select an area to paste to.");if(typeof e=="string"){const m=[],g=_.getModelRanges(i,n,s);Ie.forEachCell(g,(p,C)=>{m.push({column:p,row:C,text:e})}),await t.setValues(m);return}const o=e.length,l=e[0].length,{columnCount:a,rowCount:d}=t;let h=i;if(h.every(m=>Ie.cellCount([m])===1&&(m.startColumn??0)+l<=a&&(m.startRow??0)+o<=d)&&(h=h.map(m=>new Ie(m.startColumn,m.startRow,(m.startColumn??0)+l-1,(m.startRow??0)+o-1)),this.setSelectedRanges(h)),!h.every(m=>Ie.rowCount([m])===o&&Ie.columnCount([m])===l))throw new va("Copy and paste area are not same size.");const u=[];h.forEach(m=>{for(let g=0;g<l;g+=1)for(let p=0;p<o;p+=1)u.push({column:(m.startColumn??0)+g,row:(m.startRow??0)+p,text:e[p][g]})}),await t.setValues(u)}catch(o){const{onError:l}=this.props;l(o instanceof Error?o:new Error(`${o}`))}}setValueForCell(e,t,n){const{model:s}=this.props;Yd(s);const i=this.getModelColumn(e),o=this.getModelRow(t);return s.isValidForCell(i,o,n)?(s.setValueForCell(i,o,n),!0):!1}setValueForRanges(e,t){const{model:n}=this.props,{movedColumns:s,movedRows:i}=this.state,o=_.getModelRanges(e,s,i);Xe(n)&&n.setValueForRanges(o,t)}isSelected(e,t){const{selectedRanges:n}=this.state;for(let s=0;s<n.length;s+=1){const i=n[s],o=i.startRow===null||i.startRow<=e&&e<=(i.endRow??0),l=i.startColumn===null||i.startColumn<=t&&t<=(i.endColumn??0);if(o&&l)return!0}return!1}addDocumentCursor(e=null){this.documentCursor!==hs.getCursorClassName(e)&&(this.documentCursor!=null&&document.documentElement.classList.remove(this.documentCursor),this.documentCursor=hs.getCursorClassName(e),this.documentCursor!=null&&document.documentElement.classList.add(this.documentCursor),document.documentElement.classList.add("grid-block-events"))}removeDocumentCursor(){this.documentCursor!=null&&(document.documentElement.classList.remove(this.documentCursor),document.documentElement.classList.remove("grid-block-events"),this.documentCursor=null)}startDragTimer(e){this.stopDragTimer();const t=new MouseEvent("custom",e.nativeEvent);this.dragTimer=setTimeout(()=>{this.handleMouseDrag(t)},hs.dragTimeout)}stopDragTimer(){this.dragTimer&&(clearTimeout(this.dragTimer),this.dragTimer=null)}drawCanvas(e=this.updateMetrics()){if(!this.canvas)throw new Error("canvas is not set");if(!this.canvasContext)throw new Error("context not set");const{renderer:t,canvasContext:n,renderState:s}=this;n.save(),t.drawCanvas(s),n.restore()}focus(){this.canvas?.focus()}isFocused(){return document.activeElement===this.canvas}handleClick(e){const t=this.getGridPointFromEvent(e),n=this.getMouseHandlers();for(let s=0;s<n.length;s+=1)if(n[s].onClick(t,this,e)!==!1){e.stopPropagation(),e.preventDefault();break}this.canvas?.focus()}handleContextMenu(e){const t=this.getGridPointFromEvent(e),n=this.getMouseHandlers();for(let s=0;s<n.length;s+=1)if(n[s].onContextMenu(t,this,e)!==!1){e.stopPropagation(),e.preventDefault();break}}handleKeyDown(e){const t=this.getKeyHandlers();for(let n=0;n<t.length;n+=1){const i=t[n].onDown(e,this);if(i!==!1){const o=i;(o?.stopPropagation??!0)&&e.stopPropagation(),(o?.preventDefault??!0)&&e.preventDefault();break}}}notifyMouseHandlers(e,t,n=!0,s=!1){const i=this.getGridPointFromEvent(t),o=this.getMouseHandlers();let l=null;for(let a=0;a<o.length;a+=1){const d=o[a],h=d[e]!=null&&d[e](i,this,t);if(h!==!1){d.cursor!=null&&({cursor:l}=d,s&&this.addDocumentCursor(l));const u=h;(u?.stopPropagation??!0)&&t.stopPropagation(),(u?.preventDefault??!0)&&t.preventDefault();break}}if(this.setState({cursor:l}),n){const{x:a,y:d}=i;this.setState({mouseX:a,mouseY:d})}}handleMouseDown(e){window.addEventListener("mousemove",this.handleMouseDrag,!0),window.addEventListener("mouseup",this.handleMouseUp,!0),!(e.button!=null&&e.button!==0)&&(this.notifyMouseHandlers("onDown",e),this.startDragTimer(e))}handleDoubleClick(e){this.notifyMouseHandlers("onDoubleClick",e)}handleMouseMove(e){this.notifyMouseHandlers("onMove",e)}handleMouseLeave(e){this.notifyMouseHandlers("onLeave",e,!1),this.setState({mouseX:null,mouseY:null})}handleMouseDrag(e){this.setState({isDragging:!0}),this.notifyMouseHandlers("onDrag",e,!0,!0),this.stopDragTimer()}handleMouseUp(e){window.removeEventListener("mousemove",this.handleMouseDrag,!0),window.removeEventListener("mouseup",this.handleMouseUp,!0),!(e.button!=null&&e.button!==0)&&(this.notifyMouseHandlers("onUp",e,!1),this.stopDragTimer(),this.removeDocumentCursor())}handleResize(){if(this.updateCanvas(),!this.metrics)throw new Error("metrics not set");this.forceUpdate()}handleWheel(e){if(this.notifyMouseHandlers("onWheel",e),e.defaultPrevented)return;const{metricCalculator:t,metrics:n}=this,s=this.getMetricState();if(!n)throw new Error("metrics not set");const{lastTop:i,lastLeft:o,columnCount:l,rowCount:a,scrollableContentWidth:d,scrollableViewportWidth:h,scrollableContentHeight:u,scrollableViewportHeight:m,hasHorizontalBar:g,hasVerticalBar:p}=n;let{top:C,left:f,topOffset:b,leftOffset:w}=n;const S=this.getTheme();let{deltaX:T,deltaY:y}=_.getScrollDelta(e,n.barWidth,n.barHeight,n.rowHeight,n.rowHeight);for(;g&&T!==0;){if(w+=T,T=0,l>1){if(w>0&&f>=o||w<0&&f<=0){w=0;break}}else{if(w<=0){w=0;break}const E=d-h;if(w>=E){w=E;break}}if(w>0){const E=n.allColumnWidths.get(f)??t.getVisibleColumnWidth(f,s);w>=E?(T=w-E,w=0,f+=1):S.scrollSnapToColumn&&l>1&&(w=0,f+=1)}else if(w<0){const E=n.allColumnWidths.get(f-1)??t.getVisibleColumnWidth(f-1,s);Math.abs(w)<=E&&S.scrollSnapToColumn&&l>1?(w=0,f-=1):(T=w+E,w=0,f-=1)}}for(;p&&y!==0;){if(b+=y,y=0,a>1){if(b>0&&C>=i||b<0&&C<=0){b=0;break}}else{if(b<=0){b=0;break}const E=u-m;if(b>=E){b=E;break}}if(b>0){const E=n.allRowHeights.get(C)??t.getVisibleRowHeight(C,s);b>=E?(y=b-E,b=0,C+=1):S.scrollSnapToRow&&a>1&&(b=0,C+=1)}else if(b<0){const E=n.allRowHeights.get(C-1)??t.getVisibleRowHeight(C-1,s);Math.abs(b)<=E&&S.scrollSnapToRow&&a>1?(b=0,C-=1):(y=b+E,b=0,C-=1)}}this.setViewState({top:C,left:f,leftOffset:w,topOffset:b}),e.stopPropagation(),e.preventDefault()}handleEditCellCancel(){this.setState({editingCell:null}),this.focus()}handleEditCellChange(e){this.setState(({editingCell:t})=>{try{return Kd(t),{editingCell:{...t,value:e}}}catch(n){const{onError:s}=this.props;return s(n instanceof Error?n:new Error(`${n}`)),null}})}handleEditCellCommit(e,{direction:t=mn.DOWN,fillRange:n=!1}={}){const{editingCell:s,selectedRanges:i}=this.state;if(!s)throw new Error("editingCell not set");const{column:o,row:l}=s;if(!this.isValidForCell(o,l,e)){t===null&&this.setState({editingCell:null});return}n?this.setValueForRanges(i,e):this.setValueForCell(o,l,e),t!==null&&this.moveCursorInDirection(t),this.setState({editingCell:null}),this.focus()}renderInputField(){const{model:e}=this.props,{editingCell:t}=this.state,{metrics:n}=this;if(t==null||n==null||!Xe(e))return null;const{selectionRange:s,value:i,isQuickEdit:o}=t,{column:l,row:a}=t,{gridX:d,gridY:h,allColumnXs:u,allRowYs:m,allColumnWidths:g,allRowHeights:p}=n,C=u.get(l),f=m.get(a),b=g.get(l),w=p.get(a),S=C!=null&&f!=null&&b!=null&&w!=null?{position:"absolute",left:d+C,top:h+f,width:b,height:w}:{opacity:0},T=this.getModelColumn(l),y=this.getModelRow(a),E=T!=null&&y!=null?{textAlign:e.textAlignForCell(T,y)}:void 0,R=e.isValidForCell(T,y,i);return r.jsx("div",{style:S,children:r.jsx(Pr,{selectionRange:s,className:Y({error:!R}),onCancel:this.handleEditCellCancel,onChange:this.handleEditCellChange,onDone:this.handleEditCellCommit,isQuickEdit:o,style:E,value:i},`${l},${a}`)})}updateRenderState(){if(!this.canvas)throw new Error("canvas is not set");if(!this.canvasContext)throw new Error("context not set");const{cursorColumn:e,cursorRow:t,draggingColumn:n,draggingColumnSeparator:s,draggingRow:i,draggingRowOffset:o,draggingRowSeparator:l,editingCell:a,isDraggingHorizontalScrollBar:d,isDraggingVerticalScrollBar:h,isDragging:u,mouseX:m,mouseY:g,selectedRanges:p}=this.state,{model:C,stateOverride:f}=this.props,{metrics:b}=this,w=this.canvasContext,S=this.getTheme(),T=this.canvas.clientWidth,y=this.canvas.clientHeight;return N(b),this.renderState={width:T,height:y,context:w,theme:S,model:C,metrics:b,mouseX:m,mouseY:g,selectedRanges:p,draggingColumn:n,draggingColumnSeparator:s,draggingRow:i,draggingRowOffset:o,draggingRowSeparator:l,editingCell:a,isDraggingHorizontalScrollBar:d,isDraggingVerticalScrollBar:h,isDragging:u,cursorColumn:e,cursorRow:t,...f},this.renderState}render(){const{cursor:e}=this.state;return r.jsxs(r.Fragment,{children:[r.jsx("canvas",{className:Y("grid-canvas",hs.getCursorClassName(e)),ref:t=>{this.canvas=t},onClick:this.handleClick,onContextMenu:this.handleContextMenu,onDoubleClick:this.handleDoubleClick,onKeyDown:this.handleKeyDown,onMouseDown:this.handleMouseDown,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,tabIndex:0,children:"Your browser does not support HTML canvas. Update your browser?"}),this.renderInputField()]})}}const Cw=hs,Ta=5e3;class bw extends cm{get floatingTopRowCount(){return 0}get floatingBottomRowCount(){return 0}get floatingLeftColumnCount(){return 0}get floatingRightColumnCount(){return 0}get columnHeaderMaxDepth(){return 1}truncationCharForCell(e,t){}textAlignForCell(e,t){return"left"}colorForCell(e,t,n){return n.textColor}backgroundColorForCell(e,t,n){return null}colorForColumnHeader(e,t=0){return null}textForRowHeader(e){return""}textForRowFooter(e){return""}isColumnMovable(e,t=0){return!0}isRowMovable(e){return!0}getColumnHeaderGroup(e,t){}getColumnHeaderParentGroup(e,t){}tokensForCell(e,t,n=Ta){const s=this.textForCell(e,t);return this.getCachedTokensInText(s,n)}getCachedTokensInText=pn((e,t)=>{if(t>=e.length)return _.findTokensWithProtocolInText(e);const n=e.slice(t-1,Ta).search(/\s/);let s=t+n;n===-1&&(s=Math.min(Ta,e.length));const i=e.substring(0,s);return _.findTokensWithProtocolInText(i)});renderTypeForCell(e,t){return"text"}}const Sw=bw;function ww(c,e){const t=Ew(c);return t===void 0?void 0:`${Fw(c)} ? ${t} : ${e}`}function vw(c){return dh.Column.formatRowColor(c)}function Tw(c,e){return c.formatColor(e)}const Qi=ne.module("ConditionalFormattingUtils");var Dn=(c=>(c.CONDITIONAL="conditional",c.ROWS="rows",c))(Dn||{}),$e=(c=>(c.IS_EQUAL="is-equal",c.IS_NOT_EQUAL="is-not-equal",c.IS_BETWEEN="is-between",c.GREATER_THAN="greater-than",c.GREATER_THAN_OR_EQUAL="greater-than-or-equal",c.LESS_THAN="less-than",c.LESS_THAN_OR_EQUAL="less-than-or-equal",c.IS_NULL="is-null",c.IS_NOT_NULL="is-not-null",c))($e||{}),Ht=(c=>(c.IS_EXACTLY="is-exactly",c.IS_NOT_EXACTLY="is-not-exactly",c.CONTAINS="contains",c.DOES_NOT_CONTAIN="does-not-contain",c.STARTS_WITH="starts-with",c.ENDS_WITH="ends-with",c.IS_NULL="is-null",c.IS_NOT_NULL="is-not-null",c))(Ht||{}),Ft=(c=>(c.IS_EXACTLY="is-exactly",c.IS_NOT_EXACTLY="is-not-exactly",c.IS_BEFORE="is-before",c.IS_BEFORE_OR_EQUAL="is-before-or-equal",c.IS_AFTER="is-after",c.IS_AFTER_OR_EQUAL="is-after-or-equal",c.IS_NULL="is-null",c.IS_NOT_NULL="is-not-null",c))(Ft||{}),Xi=(c=>(c.IS_TRUE="is-true",c.IS_FALSE="is-false",c.IS_NULL="is-null",c.IS_NOT_NULL="is-not-null",c))(Xi||{}),zs=(c=>(c.IS_EQUAL="is-equal",c.IS_NOT_EQUAL="is-not-equal",c.IS_NULL="is-null",c.IS_NOT_NULL="is-not-null",c))(zs||{}),on=(c=>(c.NO_FORMATTING="no-formatting",c.POSITIVE="positive",c.NEGATIVE="negative",c.WARN="warn",c.NEUTRAL="neutral",c.ACCENT_1="accent-1",c.ACCENT_2="accent-2",c.CUSTOM="custom",c))(on||{});function Jd(c){switch(c){case"no-formatting":return"No formatting";case"positive":return"Positive";case"negative":return"Negative";case"warn":return"Warn";case"neutral":return"Neutral";case"accent-1":return"Accent 1";case"accent-2":return"Accent 2";case"custom":return"Custom..."}}function Tl(c){const{type:e,customConfig:t}=c;switch(e){case"no-formatting":return;case"positive":return"#9fde6f";case"negative":return"#ff6087";case"warn":return"#f67f40";case"neutral":return"#ffd95c";case"accent-1":return"#78dce8";case"accent-2":return"#ab9bf5";case"custom":return t?.background;default:return}}function El(c){const{type:e,customConfig:t}=c;switch(e){case"no-formatting":return;case"positive":return"#526a3f";case"negative":return"#802f44";case"warn":return"#663318";case"neutral":return"#63562b";case"accent-1":return"#3f6469";case"accent-2":return"#554d72";case"custom":return t?.color;default:return}}function Ew(c){const e=El(c.style),t=Tl(c.style);if(!(e===void 0||t===void 0))return`bgfg(\`${t}\`, \`${e}\`)`}function yw(c){const{column:e,value:t,start:n,end:s}=c;return Bw(e.name,c.condition,t,n,s)}function Rw(c){const{column:e,value:t}=c;return Uw(e.name,c.condition,t)}function xw(c){const{column:e,value:t}=c;return Vw(e.name,c.condition,t)}function Dw(c){const{column:e}=c;return $w(e.name,c.condition)}function Iw(c){const{column:e,value:t}=c;return Ww(e.name,c.condition,t)}function Fw(c){const{column:e}=c;if(F.isNumberType(e.type))return yw(c);if(F.isCharType(e.type))return Iw(c);if(F.isStringType(e.type))return Rw(c);if(F.isDateType(e.type))return xw(c);if(F.isBooleanType(e.type))return Dw(c);throw new Error("Invalid column type")}function Nw(c){switch(c){case"is-equal":return"is equal to";case"is-not-equal":return"is not equal to";case"is-between":return"is between";case"greater-than":return"greater than";case"greater-than-or-equal":return"greater than or equal to";case"less-than":return"less than";case"less-than-or-equal":return"less than or equal to";case"is-null":return"is null";case"is-not-null":return"is not null"}}function kw(c){switch(c){case"is-exactly":return"is exactly";case"is-not-exactly":return"is not exactly";case"contains":return"contains";case"does-not-contain":return"does not contain";case"starts-with":return"starts with";case"ends-with":return"ends with";case"is-null":return"is null";case"is-not-null":return"is not null"}}function Mw(c){switch(c){case"is-exactly":return"is";case"is-not-exactly":return"is not";case"is-before":return"is before";case"is-before-or-equal":return"is before or equal";case"is-after":return"is after";case"is-after-or-equal":return"is after or equal";case"is-null":return"is null";case"is-not-null":return"is not null"}}function Lw(c){switch(c){case"is-true":return"is true";case"is-false":return"is false";case"is-null":return"is null";case"is-not-null":return"is not null"}}function Ow(c){switch(c){case"is-equal":return"is";case"is-not-equal":return"is not";case"is-null":return"is null";case"is-not-null":return"is not null"}}function bu(c){if(F.isNumberType(c)||F.isCharType(c))return"is-equal";if(F.isStringType(c)||F.isDateType(c))return"is-exactly";if(F.isBooleanType(c))return"is-true";throw new Error("Invalid column type")}function Su(c){if(F.isCharType(c)||F.isStringType(c))return""}function wu(c){const{condition:e,value:t,start:n,end:s}=c;return{condition:e,value:t,start:n,end:s}}function na(c){return{condition:bu(c),value:Su(c),start:void 0,end:void 0}}function vu(){return{type:"no-formatting"}}function Aw(c){switch(c){case"is-exactly":return"==";case"is-not-exactly":return"!=";case"contains":return"contains";case"does-not-contain":return"does not contain";case"starts-with":return"starts with";case"ends-with":return"ends with";case"is-null":return"is null";case"is-not-null":return"is not null"}}function _w(c){switch(c){case"is-exactly":return"==";case"is-not-exactly":return"!=";case"is-before":return"<";case"is-before-or-equal":return"<=";case"is-after":return">";case"is-after-or-equal":return">=";case"is-null":return"is null";case"is-not-null":return"is not null"}}function Pw(c){switch(c){case"is-true":return"is true";case"is-false":return"is false";case"is-null":return"is null";case"is-not-null":return"is not null"}}function jw(c){switch(c){case"is-equal":return"==";case"is-not-equal":return"!=";case"is-null":return"is null";case"is-not-null":return"is not null"}}function Hw(c){switch(c){case"is-equal":return"==";case"is-not-equal":return"!=";case"is-between":return"==";case"greater-than":return">";case"greater-than-or-equal":return">=";case"less-than":return"<";case"less-than-or-equal":return"<=";case"is-null":return"is null";case"is-not-null":return"is not null"}}function Bw(c,e,t,n,s){switch(e){case"is-equal":return`${c} == ${t}`;case"is-not-equal":return`${c} != ${t}`;case"is-between":return`${c} > ${n} && ${c} < ${s}`;case"greater-than":return`${c} > ${t}`;case"greater-than-or-equal":return`${c} >= ${t}`;case"less-than":return`${c} < ${t}`;case"less-than-or-equal":return`${c} <= ${t}`;case"is-null":return`${c} == null`;case"is-not-null":return`${c} != null`}}function Uw(c,e,t){switch(e){case"is-exactly":return`${c} == "${t}"`;case"is-not-exactly":return`${c} != "${t}"`;case"contains":return`${c} != null && ${c}.contains("${t}")`;case"does-not-contain":return`${c} != null && !${c}.contains("${t}")`;case"starts-with":return`${c} != null && ${c}.startsWith("${t}")`;case"ends-with":return`${c} != null && ${c}.endsWith("${t}")`;case"is-null":return`${c} == null`;case"is-not-null":return`${c} != null`}}function Vw(c,e,t){switch(e){case"is-exactly":return`${c} == convertDateTime("${t}")`;case"is-not-exactly":return`${c} != convertDateTime(\`${t}\`)`;case"is-before":return`${c} < convertDateTime(\`${t}\`)`;case"is-before-or-equal":return`${c} <= convertDateTime("${t}")`;case"is-after":return`${c} > convertDateTime(\`${t}\`)`;case"is-after-or-equal":return`${c} >= convertDateTime(\`${t}\`)`;case"is-null":return`${c} == null`;case"is-not-null":return`${c} != null`}}function $w(c,e){switch(e){case"is-true":return`${c} == true`;case"is-false":return`${c} == false`;case"is-null":return`${c} == null`;case"is-not-null":return`${c} != null`}}function Ww(c,e,t){switch(e){case"is-equal":return`${c} == '${t}'`;case"is-not-equal":return`${c} != '${t}'`;case"is-null":return`isNull(${c})`;case"is-not-null":return`!isNull(${c})`}}function Gw(c,e){if(F.isNumberType(c))return Hw(e);if(F.isCharType(c))return jw(e);if(F.isStringType(c))return Aw(e);if(F.isDateType(c))return _w(e);if(F.isBooleanType(c))return Pw(e);throw new Error("Invalid column type")}function zw(c,e){if(e===void 0)return Qi.debug("no rules passed."),[];const t=[];let n;const s=new Map;return e.forEach(({config:i,type:o})=>{const{column:l}=i,a=c.find(({name:p,type:C})=>p===l.name&&C===l.type);if(a===void 0){Qi.debug(`Column ${l.name}:${l.type} not found. Ignoring format rule.`,i);return}const[d,h]=(o==="conditional"?s.get(a.name):n)??["null",void 0],u=ww(i,d);if(u===void 0){Qi.debug("Ignoring format rule.",i);return}const m=h===void 0?-1:t.indexOf(h);m>-1&&t.splice(m,1);const g=o==="conditional"?Tw(a,u):vw(u);t.push(g),o==="conditional"?s.set(a.name,[u,g]):n=[u,g]}),t}function Kw(c,e){switch(c){case"is-null":case"is-not-null":return!0;default:{const[t,...n]=(e??"").split(" "),s=n.join(" ");try{Xs.parseDateTimeString(t)}catch{return Qi.debug("Invalid datetime string",t),!1}try{dh.i18n.TimeZone.getTimeZone(s)}catch{return Qi.debug("Invalid timezone string",s),!1}return!0}}}function Yw({type:c}){return F.isNumberType(c)||F.isCharType(c)||F.isStringType(c)||F.isDateType(c)||F.isBooleanType(c)}function sa({animation:c="iris-grid-bottom-bar-slide-up",children:e,className:t,isShown:n,onClick:s,onEntering:i,onEntered:o,onExiting:l,onExited:a}){return r.jsx(Wt,{in:n,timeout:Je.transitionMs,classNames:c,onEntering:i,onEntered:o,onExiting:l,onExited:a,mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:Y("iris-grid-bottom-bar",t),role:"presentation",onClick:s,onKeyPress:s,children:e})})}const qw=3e3,Xw=5;function Zw({isSaving:c=!1,onSave:e,onDiscard:t,discardTooltip:n,saveTooltip:s,error:i,pendingDataErrors:o,pendingDataMap:l,onEntering:a,onEntered:d,onExiting:h,onExited:u}){const[m,g]=v.useState(!1),[p,C]=v.useState(!1),f=v.useRef(),b=lr(c),w=v.useMemo(()=>o.size===0?i:o.size<=Xw?`Key can't be empty (on pending row${o.size>1?"s":""} ${Array.from(o.keys()).join(", ").trim()})`:`Key can't be empty (on ${o.size} rows)`,[i,o]);v.useEffect(function(){b!=null&&b&&!c&&w==null&&(g(!0),C(!0),f.current=setTimeout(()=>{g(!1)},qw))},[w,c,b]),v.useEffect(function(){f.current&&l.size>0&&(clearTimeout(f.current),g(!1),C(!1))},[l]),v.useEffect(function(){return()=>f.current?clearTimeout(f.current):void 0},[]);const S=l.size;let T;return c?T=r.jsx(In,{}):p&&(T=dr),r.jsxs(sa,{className:"pending-data-bottom-bar",isShown:S>0||m||w!=null,onEntering:a,onEntered:d,onExiting:h,onExited:()=>{C(!1),u&&u()},children:[w!=null&&w!==""&&r.jsxs("div",{className:"error-message",children:[r.jsx(ee,{icon:ws}),r.jsx("span",{children:`${w}`})]}),(w==null||w==="")&&r.jsx("div",{className:"status-message",children:S>0&&r.jsx("span",{children:`${S} row${S>1?"s":""} pending`})}),r.jsxs("div",{className:"buttons-container",children:[!c&&!p&&r.jsx(B,{kind:"secondary",onClick:t,tooltip:n,children:"Discard"}),r.jsxs(B,{kind:p?"success":"primary",onClick:e,icon:T,disabled:c||p||w!=null,tooltip:s,children:[c&&"Committing...",!c&&p&&"Success",!c&&!p&&"Commit"]})]})]})}var Tu=(c=>(c.COUNT="Count",c.MIN="Min",c.MAX="Max",c.SUM="Sum",c.ABS_SUM="AbsSum",c.VAR="Var",c.AVG="Avg",c.STD="Std",c.FIRST="First",c.LAST="Last",c.SKIP="Skip",c.COUNT_DISTINCT="CountDistinct",c.DISTINCT="Distinct",c.UNIQUE="Unique",c))(Tu||{});const Le=Tu,Qw=[Le.SUM,Le.ABS_SUM,Le.MIN,Le.MAX,Le.VAR,Le.AVG,Le.STD,Le.FIRST,Le.LAST,Le.COUNT_DISTINCT,Le.DISTINCT,Le.COUNT,Le.UNIQUE],Jw=c=>{switch(c){default:return!1}},ev=(c,e)=>{switch(c){case Le.COUNT:case Le.FIRST:case Le.LAST:case Le.COUNT_DISTINCT:case Le.DISTINCT:case Le.UNIQUE:return!0;case Le.MIN:case Le.MAX:return F.isNumberType(e)||F.isDateType(e)||F.isTextType(e);case Le.SUM:case Le.ABS_SUM:case Le.VAR:case Le.AVG:case Le.STD:return F.isNumberType(e);case Le.SKIP:return!1}},jr=(c,e)=>c.filter(t=>ev(e,t.type)),tv=(c,e,t,n)=>jr(c,e).map(({name:s})=>s).filter(s=>t.includes(s)?!n:n),Cs={isRollupOperation:Jw,filterValidColumns:jr,getOperationColumnNames:tv};var Eu=(c=>(c.FILTER_CONTROL_CHANGE_CLEARS_ALL_FILTERS="filter-control-change-clears-all-filters",c.LINK_CHANGE_CLEARS_ALL_FILTERS="link-change-clears-all-filters",c))(Eu||{});const xi=Eu,nv=Object.freeze([[xi.FILTER_CONTROL_CHANGE_CLEARS_ALL_FILTERS,!1],[xi.LINK_CHANGE_CLEARS_ALL_FILTERS,!1]]),yu={DEFAULTS:nv},sv=ne.module("ColumnHeaderGroup");function Ea(c){return c instanceof dn}class dn{static NEW_GROUP_PREFIX=":newGroup";name;children;depth;parent;color;childIndexes;constructor({name:e,children:t,color:n,depth:s,childIndexes:i,parent:o}){this.name=e,this.children=t,this.color=n,this.depth=s,this.childIndexes=i,this.parent=o}getVisibleRange=ge(e=>{const t=this.childIndexes.flat(),n=_.getVisibleIndexes(t,e),s=Math.min(...n),i=Math.max(...n);return i-s!==t.length-1&&sv.warn(`Column header group ${this.name} is not contiguous`),[s,i]});setParent(e){this.parent=e}addChildren(e){const t=new Set(this.children.concat(e));this.children=[...t]}removeChildren(e){const t=new Set(this.children);e.forEach(n=>t.delete(n)),this.children=[...t]}get isNew(){return this.name.startsWith(dn.NEW_GROUP_PREFIX)}}const Hi=ne.module("IrisGridUtils");function os(c,e){return c>=0&&c<e.length}function iv(c){return c.asDate!=null}class Te{static dehydrateGridState(e,t){const{isStuckToBottom:n,isStuckToRight:s,movedColumns:i,movedRows:o}=t,{columns:l}=e;return{isStuckToBottom:n,isStuckToRight:s,movedColumns:[...i].filter(({to:a,from:d})=>os(a,l)&&(typeof d=="number"&&os(d,l)||Array.isArray(d)&&os(d[0],l)&&os(d[1],l))).map(({to:a,from:d})=>({to:l[a].name,from:Array.isArray(d)?[l[d[0]].name,l[d[1]].name]:l[d].name})),movedRows:[...o]}}static hydrateGridState(e,t,n=[]){const{isStuckToBottom:s,isStuckToRight:i,movedColumns:o,movedRows:l}=t,{columns:a}=e,d=Te.parseCustomColumnNames(n),h=a.map(({name:u})=>u).concat(d);return{isStuckToBottom:s,isStuckToRight:i,movedColumns:[...o].map(({to:u,from:m})=>{const g=p=>typeof p=="string"?h.findIndex(C=>C===p):p;return{to:g(u),from:Array.isArray(m)?[g(m[0]),g(m[1])]:g(m)}}).filter(({to:u,from:m})=>os(u,h)&&(typeof m=="number"&&os(m,h)||Array.isArray(m)&&os(m[0],h)&&os(m[1],h))),movedRows:[...l]}}static dehydrateIrisGridState(e,t){const{aggregationSettings:n={aggregations:ke,showOnTop:!1},advancedFilters:s,customColumnFormatMap:i,isFilterBarShown:o,metrics:l,quickFilters:a,customColumns:d,conditionalFormats:h=ke,reverseType:u,rollupConfig:m=void 0,showSearchBar:g,searchValue:p,selectDistinctColumns:C=ke,selectedSearchColumns:f,sorts:b,invertSearchColumns:w,pendingDataMap:S=Pn,frozenColumns:T,columnHeaderGroups:y}=t;N(l);const{userColumnWidths:E,userRowHeights:R}=l,{columns:x}=e;return{advancedFilters:Te.dehydrateAdvancedFilters(x,s),aggregationSettings:n,customColumnFormatMap:[...i],isFilterBarShown:o,quickFilters:Te.dehydrateQuickFilters(a),sorts:Te.dehydrateSort(b),userColumnWidths:[...E].filter(([D])=>D!=null&&D>=0&&D<x.length).map(([D,M])=>[x[D].name,M]),userRowHeights:[...R],customColumns:[...d],conditionalFormats:[...h],reverseType:u,rollupConfig:m,showSearchBar:g,searchValue:p,selectDistinctColumns:[...C],selectedSearchColumns:f,invertSearchColumns:w,pendingDataMap:Te.dehydratePendingDataMap(x,S),frozenColumns:T,columnHeaderGroups:y?.map(D=>({name:D.name,children:D.children,color:D.color}))}}static hydrateIrisGridState(e,t){const{advancedFilters:n,aggregationSettings:s={aggregations:[],showOnTop:!1},customColumnFormatMap:i,isFilterBarShown:o,quickFilters:l,sorts:a,customColumns:d,conditionalFormats:h,userColumnWidths:u,userRowHeights:m,reverseType:g,rollupConfig:p=void 0,showSearchBar:C,searchValue:f,selectDistinctColumns:b,selectedSearchColumns:w,invertSearchColumns:S=!0,pendingDataMap:T=[],frozenColumns:y,columnHeaderGroups:E}=t,{columns:R,formatter:x}=e;return{advancedFilters:Te.hydrateAdvancedFilters(R,n,x.timeZone),aggregationSettings:s,customColumnFormatMap:new Map(i),isFilterBarShown:o,quickFilters:Te.hydrateQuickFilters(R,l,x.timeZone),sorts:Te.hydrateSort(R,a),userColumnWidths:new Map(u.map(([D,M])=>typeof D=="string"||D instanceof String?[R.findIndex(({name:O})=>O===D),M]:[D,M]).filter(([D])=>D!=null&&D>=0&&D<R.length)),customColumns:d,conditionalFormats:h,userRowHeights:new Map(m),reverseType:g,rollupConfig:p,showSearchBar:C,searchValue:f,selectDistinctColumns:b,selectedSearchColumns:w,invertSearchColumns:S,pendingDataMap:Te.hydratePendingDataMap(R,T),frozenColumns:y,columnHeaderGroups:Te.parseColumnHeaderGroups(e,E??e.layoutHints?.columnGroups??[]).groups}}static dehydrateIrisGridPanelState(e,t){const{isSelectingPartition:n,partition:s,partitionColumn:i,advancedSettings:o}=t;return{isSelectingPartition:n,partition:s,partitionColumn:i?.name,advancedSettings:[...o]}}static hydrateIrisGridPanelState(e,t){const{isSelectingPartition:n,partition:s,partitionColumn:i,advancedSettings:o}=t,{columns:l}=e;return{isSelectingPartition:n,partition:s,partitionColumn:i!=null?Te.getColumnByName(l,i):void 0,advancedSettings:new Map([...yu.DEFAULTS,...o])}}static dehydrateQuickFilters(e){return[...e].map(([t,n])=>{const{text:s}=n;return[t,{text:s}]})}static hydrateQuickFilters(e,t,n){const s=t.map(([i,o])=>{const{text:l}=o;let a=null;try{const d=Te.getColumn(e,i);d!=null&&(a=F.makeQuickFilter(d,l,n))}catch(d){Hi.error("hydrateQuickFilters error with",l,d)}return[i,{text:l,filter:a}]});return new Map(s)}static dehydrateAdvancedFilters(e,t){return[...t].map(([n,s])=>{const i=Te.getColumn(e,n);N(i);const o=Te.dehydrateAdvancedFilterOptions(i,s.options);return[n,{options:o}]})}static hydrateAdvancedFilters(e,t,n){const s=t.map(([i,o])=>{const l=Te.getColumn(e,i);N(l);const a=Te.hydrateAdvancedFilterOptions(l,o.options);let d=null;try{Te.getColumn(e,i)!=null&&(d=F.makeAdvancedFilter(l,a,n))}catch(h){Hi.error("hydrateAdvancedFilters error with",a,h)}return[i,{options:a,filter:d}]});return new Map(s)}static dehydrateAdvancedFilterOptions(e,t){const{selectedValues:n,...s}=t;return{selectedValues:n?.map(i=>Te.dehydrateValue(i,e?.type)),...s}}static hydrateAdvancedFilterOptions(e,t){const{selectedValues:n,...s}=t;return{selectedValues:n?.map(i=>Te.hydrateValue(i,e?.type)),...s}}static dehydratePendingDataMap(e,t){return[...t].map(([n,{data:s}])=>[n,{data:[...s].map(([i,o])=>[e[i].name,Te.dehydrateValue(o,e[i].type)])}])}static hydratePendingDataMap(e,t){const n=new Map,s=i=>(n.has(i)||n.set(i,e.findIndex(({name:o})=>o===i)),n.get(i));return new Map(t.map(([i,{data:o}])=>[i,{data:new Map(o.map(([l,a])=>{const d=s(l);return N(d),[s(l)??null,Te.hydrateValue(a,e[d].type)]}))}]))}static dehydrateValue(e,t){return F.isDateType(t)?Te.dehydrateDateTime(e):F.isLongType(t)?Te.dehydrateLong(e):e}static hydrateValue(e,t){return F.isDateType(t)?Te.hydrateDateTime(e):F.isLongType(t)?Te.hydrateLong(e):e}static dehydrateDateTime(e){return e!=null?I.i18n.DateTimeFormat.format(Xs.FULL_DATE_FORMAT,e):null}static hydrateDateTime(e){return e!=null?I.i18n.DateTimeFormat.parse(Xs.FULL_DATE_FORMAT,e):null}static dehydrateLong(e){return e!=null?`${e}`:null}static hydrateLong(e){return e!=null?I.LongWrapper.ofString(e):null}static dehydrateSort(e){return e.map(t=>{const{column:n,isAbs:s,direction:i}=t;return{column:n.name,isAbs:s,direction:i}})}static hydrateSort(e,t){return t.map(n=>{const{column:s,isAbs:i,direction:o}=n;if(o===F.sortDirection.reverse)return I.Table.reverse();const l=typeof s=="string"?Te.getColumnByName(e,s):Te.getColumn(e,s);if(l!=null){let a=l.sort();return i&&(a=a.abs()),o===F.sortDirection.descending?a=a.desc():a=a.asc(),a}return null}).filter(n=>n!=null&&n.direction!==F.sortDirection.reverse)}static extractTableSettings(e,t=[]){const{irisGridPanelState:n,irisGridState:s}=e,{partitionColumn:i,partition:o}=n,{advancedFilters:l,quickFilters:a,sorts:d}=s;return{advancedFilters:l,inputFilters:t,partition:o,partitionColumn:i,quickFilters:a,sorts:d}}static applyTableSettings(e,t,n){const{columns:s}=e;let i=[];t.quickFilters&&(i=Te.getFiltersFromFilterMap(Te.hydrateQuickFilters(s,t.quickFilters,n)));let o=[];t.advancedFilters&&(o=Te.getFiltersFromFilterMap(Te.hydrateAdvancedFilters(s,t.advancedFilters,n)));const l=Te.getFiltersFromInputFilters(s,t.inputFilters,n);let a=[];t.sorts&&(a=Te.hydrateSort(s,t.sorts));let d=[...i,...o];const{partition:h,partitionColumn:u}=t;if(h!=null&&u!=null){const m=Te.getColumnByName(s,u);m&&(d=[m.filter().eq(I.FilterValue.ofString(h)),...d])}d=[...l,...d],e.applyFilter(d),e.applySort(a)}static getInputFiltersForColumns(e,t=[]){return t.filter(({name:n,type:s})=>e.find(({name:i,type:o})=>i===n&&o===s))}static getFiltersFromInputFilters(e,t=[],n){return t.map(({name:s,type:i,value:o})=>{const l=e.find(({name:a,type:d})=>a===s&&d===i);if(l)try{return F.makeQuickFilter(l,o,n)}catch(a){Hi.debug("Unable to create input filter",a)}return null}).filter(s=>s!=null)}static getFiltersFromFilterMap(e){const t=[],n=Array.from(e.keys());for(let s=0;s<n.length;s+=1){const i=n[s],o=e.get(i);o?.filter!=null&&t.push(o.filter)}return t}static getHiddenColumns(e){return[...e.entries()].filter(([,t])=>t===0).map(([t])=>t)}static parseCustomColumnNames(e){return e.map(t=>t.split("=")[0])}static getRemovedCustomColumnNames(e,t){const n=Te.parseCustomColumnNames(e),s=Te.parseCustomColumnNames(t);return n.filter(i=>!s.includes(i))}static removeSortsInColumns(e,t){return e.filter(n=>!t.includes(n.column.name))}static removeFiltersInColumns(e,t,n){const s=e.map(({name:o})=>o),i=new Map(t);return n.forEach(o=>i.delete(s.indexOf(o))),i}static removeColumnFromMovedColumns(e,t,n){const s=e.map(({name:o})=>o);let i=[...t];for(let o=0;o<n.length;o+=1){const l=n[o];let a=s.findIndex(h=>h===l);const d=[];for(let h=0;h<i.length;h+=1){const u=i[h],m={...u};let[g,p]=Array.isArray(u.from)?u.from:[u.from,u.from];a<=u.to&&(m.to-=1),a<g&&(g-=1),a<=p&&(p-=1),g<=p&&g!==m.to&&(g===p?d.push({...m,from:g}):d.push({...m,from:[g,p]})),a=_.applyItemMoves(a,a,[u])[0][0]}i=d,s.splice(s.findIndex(h=>h===l),1)}return i}static removeColumnsFromSelectDistinctColumns(e,t){return e.filter(n=>!t.includes(n))}static getVisibleColumnsInRange(e,t,n,s,i){const o=[];for(let l=t;l<=n;l+=1){const a=_.getModelIndex(l,s);a>=0&&a<e.length&&!i.includes(a)&&o.push(e[a])}return o}static getPrevVisibleColumns(e,t,n,s,i){const o=[];let l=t;for(;l>=0&&o.length<n;){const a=_.getModelIndex(l,s);a>=0&&a<e.length&&!i.includes(a)&&o.unshift(e[a]),l-=1}return o}static getNextVisibleColumns(e,t,n,s,i){const o=[];let l=t;for(;l<e.length&&o.length<n;){const a=_.getModelIndex(l,s);a>=0&&a<e.length&&!i.includes(a)&&o.push(e[a]),l+=1}return o}static getColumnsToFetch(e,t,n){const s=[...t];return n.forEach(i=>{const o=e.find(({name:l})=>l===i);o!=null&&!t.includes(o)&&s.push(o)}),s}static getModelViewportColumns(e,t,n,s,i=[],o=[],l=0){if(t==null||n==null)return null;const a=Te.getVisibleColumnsInRange(e,t,n,s,i),d=a.length*l,h=Te.getPrevVisibleColumns(e,t-1,d,s,i),u=Te.getNextVisibleColumns(e,n+1,d,s,i),m=[...h,...a,...u];return Te.getColumnsToFetch(e,m,o)}static rangeSetFromRanges(e){const t=e.slice().sort((n,s)=>(N(n.startRow),N(s.startRow),n.startRow-s.startRow)).map(n=>{const{startRow:s,endRow:i}=n;return N(s),N(i),I.RangeSet.ofRange(s,i)});return I.RangeSet.ofRanges(t)}static isValidSnapshotRanges(e){if(e==null||e.length===0)return!1;const t=new Map;for(let i=0;i<e.length;i+=1){const o=e[i],l=`${o.startRow}:${o.endRow}`,a=`${o.startColumn}:${o.endColumn}`;t.has(l)||t.set(l,[]),t.get(l).push(a)}const n=[...t.keys()],s=t.get(n[0]).sort().join(",");for(let i=1;i<n.length;i+=1)if(t.get(n[i]).sort().join(",")!==s)return!1;return!0}static isValidIndex(e){return!Number.isInteger(e)||typeof e!="number"?!1:e>=0}static columnsFromRanges(e,t){if(e==null||e.length===0)return[];if(e[0].startColumn===null&&e[0].endColumn===null)return[...t];const n=new Set;for(let s=0;s<e.length;s+=1){const i=e[s];N(i.startColumn),N(i.endColumn);for(let o=i.startColumn??0;o<=(i.endColumn??t.length-1);o+=1)n.add(o)}return[...n].map(s=>t[s])}static snapshotDataToMatrix(e){const{columns:t,rows:n}=e,s=[];for(let i=0;i<n.length;i+=1){const o=n[i],l=[];for(let a=0;a<t.length;a+=1){const d=t[a],h=o.get(d);l.push(h)}s.push(l)}return s}static getModelRollupConfig(e,t,n){if((t?.columns?.length??0)===0)return null;const{columns:s=[],showConstituents:i=!0,showNonAggregatedColumns:o=!0,includeDescriptions:l=!0}=t??{},{aggregations:a=[]}=n??{},d=a.map(({operation:u,selected:m,invert:g})=>Cs.isRollupOperation(u)?[]:Cs.getOperationColumnNames(e,u,m,g)),h={};for(let u=0;u<a.length;u+=1)h[a[u].operation]=d[u];if(o){const u=new Set(e.map(m=>m.name).filter(m=>!s.includes(m)));if(d.forEach(m=>{m.forEach(g=>u.delete(g))}),u.size>0){const m=h[Le.FIRST]??[];h[Le.FIRST]=[...m,...u]}}return{groupingColumns:s,includeConstituents:i,includeDescriptions:l,aggregations:h}}static getPendingErrors(e){e.forEach((t,n)=>{if(!Te.isValidIndex(n))throw new Error(`Invalid rowIndex ${n}`);const{data:s}=t;s.forEach((i,o)=>{if(!Te.isValidIndex(o))throw new Error(`Invalid columnIndex ${o}`)})})}static getColumn(e,t){return t<e.length?e[t]:(Hi.error("Unable to retrieve column",t,">=",e.length),null)}static getColumnByName(e,t){const n=e.find(({name:s})=>s===t);return n==null&&Hi.error("Unable to retrieve column by name",t,e.map(({name:s})=>s)),n}static changeFilterColumnNamesToIndexes(e,t){return t.map(({name:n,filter:s})=>{const i=e.findIndex(o=>o.name===n);return i<0?null:[i,s]}).filter(n=>n!=null)}static combineFiltersFromList(e,t){t.sort((s,i)=>s.operator==="eq"&&i.operator!=="eq"?1:s.operator!=="eq"&&i.operator==="eq"?-1:s.startColumnIndex-i.startColumnIndex);let n="";for(let s=0;s<t.length;s+=1){const{text:i,value:o,operator:l}=t[s];if(o!==void 0){let a="";l!==void 0&&(o==null&&l==="eq"?a="=":l!=="eq"&&(l==="startsWith"||l==="endsWith"?a="*":a=F.getFilterOperatorString(l)));let d=`${a}${i}`;l==="startsWith"&&(d=`${i}${a}`),e!=null&&o!==null&&F.isCharType(e)&&(d=`${a}${String.fromCharCode(parseInt(i,10))}`),s!==0&&(n+=l==="eq"?" || ":" && "),n+=d}}return n}static parseColumnHeaderGroups(e,t){let n=1;const s=new Map,i=new Map,o=t?.filter(({children:u})=>u.length>0);if(o.length===0)return{groups:[],maxDepth:n,parentMap:s,groupMap:i};const l=new Map(o.map(u=>[u.name,u])),a=new Set,d=u=>{const{name:m}=u;if(e.getColumnIndexByName(m)!=null)throw new Error(`Column header group has same name as column: ${m}`);const g=i.get(m);if(g)return g;const p=[];let C=1;u.children.forEach(b=>{if(a.has(b))throw new Error(`Column group child ${b} specified in multiple groups`);a.add(b);const w=l.get(b),S=e.getColumnIndexByName(b);if(w){const T=d(w);p.push(...T.childIndexes),C=Math.max(C,T.depth+1)}else if(S!=null)p.push(S),C=Math.max(C,1);else throw new Error(`Unknown child ${b} in group ${m}`)});const f=new dn({...u,depth:C,childIndexes:p.flat()});return i.set(m,f),u.children.forEach(b=>s.set(b,f)),n=Math.max(n,f.depth+1),f},h=new Set;return o.forEach(u=>{const{name:m}=u;if(h.has(m))throw new Error(`Duplicate column group name: ${m}`);h.add(m),d(u)}),i.forEach(u=>{u.setParent(s.get(u.name)?.name)}),{groups:[...i.values()],maxDepth:n,groupMap:i,parentMap:s}}static convertValueToText(e,t){if(t!=null&&F.isCharType(t)&&e!=null&&typeof e=="number")return String.fromCharCode(e);if(F.isDateType(t)&&iv(e)){const n=new Date(e.asDate()),s=n.getTimezoneOffset();return new Date(n.getTime()-s*60*1e3).toISOString().replace("T"," ").substring(0,23)}return e==null?"":`${e}`}}const Se=Te;const jt=ne.module("IrisGridCopyHandler");class Me extends v.Component{static NO_PROMPT_THRESHOLD=1e4;static HIDE_TIMEOUT=3e3;static COPY_STATES={IDLE:"IDLE",CONFIRMATION_REQUIRED:"CONFIRMATION_REQUIRED",FETCH_IN_PROGRESS:"FETCH_IN_PROGRESS",FETCH_ERROR:"FETCH_ERROR",CLICK_REQUIRED:"CLICK_REQUIRED",DONE:"DONE"};static BUTTON_STATES={COPY:"COPY",FETCH_IN_PROGRESS:"FETCH_IN_PROGRESS",CLICK_TO_COPY:"CLICK_TO_COPY",RETRY:"RETRY"};static defaultProps={copyOperation:null,onEntering:()=>{},onEntered:()=>{},onExiting:()=>{},onExited:()=>{}};static getStatusMessageText(e,t){switch(e){case Me.COPY_STATES.CONFIRMATION_REQUIRED:return`Are you sure you want to copy ${t.toLocaleString()} rows to your clipboard?`;case Me.COPY_STATES.CLICK_REQUIRED:return`Fetched ${t.toLocaleString()} rows!`;case Me.COPY_STATES.FETCH_ERROR:return"Unable to copy data.";case Me.COPY_STATES.FETCH_IN_PROGRESS:return`Fetching ${t.toLocaleString()} rows for clipboard...`;case Me.COPY_STATES.DONE:return"Copied to Clipboard!";default:return""}}static getCopyButtonText(e){switch(e){case Me.BUTTON_STATES.FETCH_IN_PROGRESS:return"Fetching";case Me.BUTTON_STATES.CLICK_TO_COPY:return"Click to Copy";case Me.BUTTON_STATES.RETRY:return"Retry";default:return"Copy"}}constructor(e){super(e),this.handleBackgroundClick=this.handleBackgroundClick.bind(this),this.handleCancelClick=this.handleCancelClick.bind(this),this.handleCopyClick=this.handleCopyClick.bind(this),this.handleHideTimeout=this.handleHideTimeout.bind(this),this.state={error:void 0,copyState:Me.COPY_STATES.IDLE,buttonState:Me.BUTTON_STATES.COPY,isShown:!1,rowCount:0}}componentDidMount(){const{copyOperation:e}=this.props;e!=null&&this.startCopy()}componentDidUpdate(e){const{copyOperation:t}=this.props;e.copyOperation!==t&&this.startCopy()}componentWillUnmount(){this.stopCopy()}textData;hideTimer;fetchPromise;startCopy(){jt.debug2("startCopy"),this.stopCopy();const{copyOperation:e}=this.props;if(e==null){jt.debug2("No copy operation set, cancelling out"),this.setState({isShown:!1});return}const{ranges:t,error:n}=e;if(n!=null){jt.debug("Showing copy error",n),this.setState({isShown:!0,copyState:Me.COPY_STATES.DONE,error:n}),this.startHideTimer();return}const s=te.rowCount(t);this.setState({rowCount:s,isShown:!0,error:void 0}),s>Me.NO_PROMPT_THRESHOLD?this.setState({buttonState:Me.BUTTON_STATES.COPY,copyState:Me.COPY_STATES.CONFIRMATION_REQUIRED}):this.startFetch()}stopCopy(){this.textData=void 0,this.stopFetch(),this.stopHideTimer()}handleBackgroundClick(){jt.debug2("handleBackgroundClick");const{copyState:e}=this.state;e===Me.COPY_STATES.DONE&&this.setState({isShown:!1})}handleCancelClick(){jt.debug2("handleCancelClick"),this.stopFetch(),this.setState({isShown:!1})}handleCopyClick(){jt.debug2("handleCopyClick"),this.textData!=null?this.copyText(this.textData):this.startFetch()}handleHideTimeout(){jt.debug2("handleHideTimeout"),this.stopHideTimer(),this.setState({isShown:!1})}copyText(e){jt.debug2("copyText",e),this.textData=e,ho(e).then(()=>{this.setState({copyState:Me.COPY_STATES.DONE}),this.startHideTimer()},t=>{jt.error("copyText error",t),this.setState({buttonState:Me.BUTTON_STATES.CLICK_TO_COPY,copyState:Me.COPY_STATES.CLICK_REQUIRED})})}startFetch(){this.stopFetch(),this.setState({buttonState:Me.BUTTON_STATES.FETCH_IN_PROGRESS,copyState:Me.COPY_STATES.FETCH_IN_PROGRESS});const{model:e,copyOperation:t}=this.props,{ranges:n,includeHeaders:s,userColumnWidths:i,movedColumns:o,formatValues:l}=t;jt.debug("startFetch",n);const a=Se.getHiddenColumns(i);let d=_.getModelRanges(n,o);if(a.length>0){const u=a.map(te.makeColumn);d=te.subtractRangesFromRanges(d,u)}const h=l!=null&&l?(u,m)=>e.displayString(u,m.type,m.name):u=>`${u}`;this.fetchPromise=ye.makeCancelable(e.textSnapshot(d,s,h)),this.fetchPromise.then(u=>{this.fetchPromise=void 0,this.copyText(u)}).catch(u=>{u instanceof Hl?jt.debug("User cancelled copy."):(jt.error("Error fetching contents",u),this.fetchPromise=void 0,this.setState({buttonState:Me.BUTTON_STATES.RETRY,copyState:Me.COPY_STATES.FETCH_ERROR}))})}stopFetch(){this.fetchPromise&&(jt.debug2("stopFetch"),this.fetchPromise.cancel(),this.fetchPromise=void 0)}startHideTimer(){this.stopHideTimer(),this.hideTimer=setTimeout(this.handleHideTimeout,Me.HIDE_TIMEOUT)}stopHideTimer(){this.hideTimer!=null&&(clearTimeout(this.hideTimer),this.hideTimer=void 0)}render(){const{onEntering:e,onEntered:t,onExiting:n,onExited:s}=this.props,{buttonState:i,copyState:o,isShown:l,rowCount:a,error:d}=this.state,h=o===Me.COPY_STATES.DONE?"fade":"copy-slide-up",u=Me.getCopyButtonText(i),m=d??Me.getStatusMessageText(o,a),g=o!==Me.COPY_STATES.DONE,p=i===Me.BUTTON_STATES.FETCH_IN_PROGRESS,C=o===Me.COPY_STATES.DONE;return r.jsxs(sa,{animation:h,isShown:l,className:Y("iris-grid-copy-handler",{"copy-done":C}),onClick:this.handleBackgroundClick,onEntering:e,onEntered:t,onExiting:n,onExited:s,children:[r.jsx("div",{className:"status-message",children:r.jsx("span",{children:m})}),r.jsx(Wt,{in:g,timeout:Je.transitionMs,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsxs("div",{className:"buttons-container",children:[r.jsx("button",{type:"button",className:"btn btn-outline-secondary btn-cancel",onClick:this.handleCancelClick,children:"Cancel"}),r.jsxs(B,{kind:p?"tertiary":"primary",className:Y("btn-copy",{"btn-spinner":p}),onClick:this.handleCopyClick,disabled:p,children:[p&&r.jsx(In,{}),u]})]})})]})}}const ov=Me;class lv extends v.PureComponent{static defaultProps={style:{},className:"",value:"",isAdvancedFilterSet:!1,onAdvancedFiltersTriggered:()=>{},onChange:()=>{},onDone:()=>{},onTab:()=>{},onContextMenu:()=>{},debounceMs:150};constructor(e){super(e);const{debounceMs:t}=e;this.debouncedSendUpdate=Ye(this.sendUpdate.bind(this),t),this.handleCancel=this.handleCancel.bind(this),this.handleChange=this.handleChange.bind(this),this.handleCommit=this.handleCommit.bind(this),this.handleFocus=this.handleFocus.bind(this),this.handleBlur=this.handleBlur.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.inputField=null;const{value:n}=e;this.initialValue=n,this.state={isChanged:!1,value:n}}componentDidMount(){this.inputField?.focus()}componentDidUpdate(e){const{debounceMs:t}=this.props;e.debounceMs!==t&&(this.debouncedSendUpdate.flush(),this.debouncedSendUpdate=Ye(this.sendUpdate.bind(this),t))}componentWillUnmount(){this.debouncedSendUpdate.cancel()}inputField;initialValue;debouncedSendUpdate;setValue(e){this.initialValue=e,this.setState({value:e})}focus(){this.inputField?.focus()}handleChange(e){const{value:t}=e.target;this.setState({value:t,isChanged:!0}),this.debouncedSendUpdate(t)}handleCancel(){this.debouncedSendUpdate.cancel();const{initialValue:e}=this,{isChanged:t}=this.state;t&&this.sendUpdate(e);const{onDone:n}=this.props;n()}handleCommit(e=!0,t=!0){this.debouncedSendUpdate.flush();const{onDone:n}=this.props;n(e,t)}handleFocus(){this.inputField?.select()}handleBlur(e){const{relatedTarget:t}=e;t!=null&&t.classList.contains("context-menu-container")?this.handleCommit(!1,!0):t!=null&&t.classList.contains("advanced-filter-button")?this.handleCommit(!1,!1):this.handleCommit(!0,!0)}handleTab(e=!1){this.debouncedSendUpdate.flush();const{onTab:t}=this.props;t(e)}handleKeyDown(e){switch(e.key){case"Escape":e.stopPropagation(),e.preventDefault(),this.handleCancel();break;case"Enter":e.stopPropagation(),e.preventDefault(),this.handleCommit();break;case"Tab":e.stopPropagation(),e.preventDefault(),this.handleTab(e.shiftKey);break}}handleContextMenu(e){const{onContextMenu:t}=this.props;t(e)}sendUpdate(e){const{onChange:t}=this.props;t(e)}render(){const{className:e,style:t,isAdvancedFilterSet:n,onAdvancedFiltersTriggered:s}=this.props,{value:i}=this.state;return r.jsxs("div",{style:t,className:"iris-grid-input-autosized-wrapper","data-value":i,children:[r.jsx("input",{ref:o=>{this.inputField=o},className:Y("iris-grid-input-field",e),type:"text",value:i,onBlur:this.handleBlur,onFocus:this.handleFocus,onChange:this.handleChange,onKeyDown:this.handleKeyDown,onContextMenu:this.handleContextMenu,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false"}),r.jsx("div",{className:"advanced-filter-button-container",children:r.jsx(B,{kind:"ghost",className:Y("btn-link-icon advanced-filter-button",{"filter-set":n}),onClick:s,onContextMenu:this.handleContextMenu,children:r.jsxs("div",{className:"fa-layers ",children:[r.jsx(ee,{icon:cr,className:"filter-solid"}),r.jsx(ee,{icon:dl,className:"filter-light"})]})})})]})}}const av=lv;class rv extends ei{irisGrid;constructor(e){super(),this.irisGrid=e}onDown(e){const{selectedRanges:t}=this.irisGrid.state;return e.key==="c"&&Ts.isModifierKeyDown(e)?(Se.isValidSnapshotRanges(t)?this.irisGrid.copyRanges(t):this.irisGrid.copyRanges(t,!1,!1,"Invalid copy ranges"),!0):!1}}const dv=rv,cv={TOGGLE_QUICK_FILTER:We.createAndAdd({id:"TABLE.TOGGLE_QUICK_FILTER",name:"Toggle Quick Filter",shortcut:[ve.CTRL,xe.F],macShortcut:[ve.CMD,xe.F]}),CLEAR_ALL_FILTERS:We.createAndAdd({id:"TABLE.CLEAR_ALL_FILTERS",name:"Clear All Table Filters",shortcut:[ve.CTRL,xe.E],macShortcut:[ve.CMD,xe.E]}),CLEAR_FILTERS:We.createAndAdd({id:"TABLE.CLEAR_FILTERS",name:"Clear Active Table Filters",shortcut:[ve.CTRL,ve.SHIFT,xe.E],macShortcut:[ve.CMD,ve.SHIFT,xe.E]}),REVERSE:We.createAndAdd({id:"TABLE.REVERSE",name:"Reverse",shortcut:[ve.CTRL,xe.I],macShortcut:[ve.CMD,xe.I]}),TOGGLE_SEARCH:We.createAndAdd({id:"TABLE.TOGGLE_SEARCH",name:"Toggle Search",shortcut:[ve.CTRL,ve.SHIFT,xe.F],macShortcut:[ve.CMD,ve.SHIFT,xe.F]}),GOTO_ROW:We.createAndAdd({id:"TABLE.GOTO_ROW",name:"Go to Row",shortcut:[ve.CTRL,xe.G],macShortcut:[ve.CMD,xe.G]})},hv={COMMIT:We.createAndAdd({id:"INPUT_TABLE.COMMIT",name:"Commit",shortcut:[ve.CTRL,xe.S],macShortcut:[ve.CMD,xe.S]}),DISCARD:We.createAndAdd({id:"INPUT_TABLE.DISCARD",name:"Discard",shortcut:[ve.CTRL,ve.ALT,xe.S],macShortcut:[ve.CMD,ve.OPTION,xe.S]})},uv={TABLE:cv,INPUT_TABLE:hv},Ut=uv;class mv extends ei{irisGrid;constructor(e){super(),this.irisGrid=e}onDown(e){if(Ut.TABLE.REVERSE.matchesEvent(e)){if(!this.irisGrid.isReversible())return!1;const{reverseType:t}=this.irisGrid.state;return t===F.REVERSE_TYPE.NONE?this.irisGrid.reverse(F.REVERSE_TYPE.POST_SORT):this.irisGrid.reverse(F.REVERSE_TYPE.NONE),!0}return!1}}const gv=mv;class pv extends ei{irisGrid;constructor(e){super(),this.irisGrid=e}onDown(e){return Ut.TABLE.CLEAR_FILTERS.matchesEvent(e)?(this.irisGrid.clearAllFilters(),!0):!1}}const fv=pv;class Cv extends ht{irisGrid;constructor(e){super(850),this.irisGrid=e}destroyColumnTooltip(){this.irisGrid.setState({overflowButtonTooltipProps:null})}setCursor(e){return this.isHoveringOverflowButton(e)?(this.cursor="pointer",{stopPropagation:!1,preventDefault:!1}):(this.cursor=null,!1)}getButtonPosition({x:e,y:t,column:n,row:s}){if(n==null||s==null)return null;const{renderer:i,grid:o,state:l,props:a}=this.irisGrid;if(!o)return null;const{metrics:d}=l,{model:h}=a,{canvasContext:u}=o,m=o.getTheme(),g={context:u,mouseX:e,mouseY:t,metrics:d,model:h,theme:m},{left:p,top:C,width:f,height:b}=i.getCellOverflowButtonPosition(g);return p==null||f==null||C==null||b==null?null:{left:p,top:C,width:f,height:b}}isHoveringOverflowButton(e){const{x:t,y:n}=e,{left:s,top:i,width:o,height:l}=this.getButtonPosition(e)??{};if(s==null||o==null||i==null||l==null)return!1;const{renderer:a,grid:d,state:h,props:u}=this.irisGrid;if(!d)return!1;const{metrics:m}=h,{model:g}=u,{canvasContext:p}=d,C=d.getTheme(),f={context:p,mouseX:t,mouseY:n,metrics:m,model:g,theme:C};return a.shouldRenderOverflowButton(f)&&t>=s&&t<=s+o&&n>=i&&n<=i+l}onMove(e){if(this.isHoveringOverflowButton(e)){const{overflowButtonTooltipProps:t}=this.irisGrid.state,n=this.getButtonPosition(e);st(t,n)||this.irisGrid.setState({overflowButtonTooltipProps:n})}else this.destroyColumnTooltip();return this.setCursor(e)}onWheel(e){return this.destroyColumnTooltip(),this.onMove(e)}onDown(e){this.destroyColumnTooltip();const{column:t,row:n}=e;return this.isHoveringOverflowButton(e)&&this.irisGrid.setState({showOverflowModal:!0,overflowText:this.irisGrid.getValueForCell(t,n)}),!1}onContextMenu(){return this.destroyColumnTooltip(),!1}onLeave(){return this.destroyColumnTooltip(),!1}}const bv=Cv;class Sv extends ht{constructor(e){super(),this.irisGrid=e,this.cursor=null}irisGrid;isActive(){const{isSelectingColumn:e}=this.irisGrid.props;return e}isValidColumn(e){if(e==null)return!1;const{columnSelectionValidator:t}=this.irisGrid.props;return t!=null?t(e):!0}updateColumnSelectionStatus(){const{columnSelectionValidator:e}=this.irisGrid.props;e?.(null)}getTableColumn(e){if(e==null)return null;const{model:t}=this.irisGrid.props,n=this.irisGrid.getModelColumn(e);return n==null?null:t.columns[n]}onMove(e){if(!this.isActive())return!1;const{columnAllowedCursor:t,columnNotAllowedCursor:n}=this.irisGrid.props,{column:s}=e,i=this.getTableColumn(s);return this.isValidColumn(i)?(this.cursor=t,this.irisGrid.setState({hoverSelectColumn:s})):(this.cursor=n,this.irisGrid.setState({hoverSelectColumn:null})),!0}onWheel(e){if(!this.isActive())return!1;const{columnAllowedCursor:t,columnNotAllowedCursor:n}=this.irisGrid.props,{column:s}=e,i=this.getTableColumn(s);return this.isValidColumn(i)?(this.cursor=t,this.irisGrid.setState({hoverSelectColumn:s})):(this.cursor=n,this.irisGrid.setState({hoverSelectColumn:null})),{preventDefault:!1,stopPropagation:!1}}onLeave(){return this.isActive()&&this.irisGrid.setState({hoverSelectColumn:null}),this.updateColumnSelectionStatus(),!1}onDown(){return this.isActive()}onClick(e){if(!this.isActive())return!1;const{column:t}=e,n=this.getTableColumn(t);return n!=null&&this.isValidColumn(n)&&this.irisGrid.selectColumn(n),!0}}const wv=Sv;class vv extends ht{constructor(e){super(),this.irisGrid=e}irisGrid;hideColumnTooltip(){const{tooltip:e}=this.irisGrid;e&&(e.stopTimer(),e.hide())}onDown(){return this.hideColumnTooltip(),!1}onContextMenu(){return this.hideColumnTooltip(),!1}onWheel(){return this.hideColumnTooltip(),!1}onLeave(e,t,n){const{relatedTarget:s}=n instanceof MouseEvent?n:n.nativeEvent,{tooltip:i}=this.irisGrid;if(!i)return!1;const o=i.popper.current;return o&&s instanceof Element&&o.element.contains(s)||this.hideColumnTooltip(),!1}onMove(e){const{column:t,row:n,columnHeaderDepth:s}=e,{shownColumnTooltip:i}=this.irisGrid.state;let o=null;return t!==null&&n===null&&s===0&&(o=t),o!==i&&this.irisGrid.setState({shownColumnTooltip:o}),!1}}const Tv=vv;class Hr extends v.Component{static defaultProps={formatString:"",forwardedProps:{menuItem:{},closeMenu(e){},iconElement:null},placeholder:"",title:"",onChange(e){}};constructor(e=Hr.defaultProps){super(e),this.handleInputChange=this.handleInputChange.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.inputRef=de.createRef()}inputRef;handleInputChange(){const{onChange:e}=this.props;this.inputRef.current&&e(this.inputRef.current.value)}closeContextMenu(){const{forwardedProps:e}=this.props,{closeMenu:t}=e;t(!0)}revertToDefault(){const{onChange:e}=this.props;e(null)}returnFocusToContextMenu(){const e=Tp.getClosestByClassName(this.inputRef.current,"context-menu-container");e instanceof HTMLElement&&e.focus()}handleKeyDown(e){switch(e.key){case"Enter":e.stopPropagation(),this.closeContextMenu();break;case"Escape":e.stopPropagation(),this.revertToDefault(),this.closeContextMenu();break;case"ArrowRight":case"ArrowLeft":e.stopPropagation();break;case"ArrowUp":case"ArrowDown":this.returnFocusToContextMenu();break;default:e.stopPropagation()}}render(){const{formatString:e,forwardedProps:t,placeholder:n,title:s}=this.props,{menuItem:{description:i},iconElement:o}=t;return r.jsxs("div",{className:"form-group flex-grow mb-0",children:[r.jsxs("div",{className:"custom-format-title",children:[r.jsx("span",{className:"icon",children:o}),r.jsxs("label",{className:"title mb-0",htmlFor:"custom-format-input",children:[s,i!=null&&r.jsx(ot,{children:i})]})]}),r.jsx("div",{className:"pl-2 pr-2 pb-2",children:r.jsx("input",{id:"custom-format-input",className:"form-control text-right mb-0",type:"text",defaultValue:e,ref:this.inputRef,placeholder:n,onKeyDown:this.handleKeyDown,onChange:this.handleInputChange,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false"})})]})}}const Ev=Hr;class yv{static isDefaultSelected(e){return!e||![nl.TYPE_CONTEXT_CUSTOM,nl.TYPE_CONTEXT_PRESET].includes(e.type)}static isCustomSelected(e){return e!=null&&e.type===nl.TYPE_CONTEXT_CUSTOM}static makeOption(e,t,n,s){return{title:e,description:e,group:n,format:t,isSelected:s}}static makeCustomFormatOption(e,t,n,s,i){return{title:e.label,description:e.label,format:e,group:t,isSelected:s,menuElement:r.jsx(Ev,{formatString:e.formatString,title:e.label,placeholder:n,onChange:i})}}}const Vt=yv;class ln{static dateGroup=10;static timeGroup=20;static dateTimeGroup=30;static getOptions(e,t){const n=new Date,i=[{group:ln.dateGroup,formatString:"yyyy-MM-dd"},{group:ln.dateGroup,formatString:"MM-dd-yyyy"},{group:ln.timeGroup,formatString:"HH:mm:ss"},{group:ln.timeGroup,formatString:"HH:mm:ss.SSS"},{group:ln.timeGroup,formatString:"HH:mm:ss.SSSSSSSSS"},{group:ln.dateTimeGroup,formatString:"yyyy-MM-dd HH:mm:ss"},{group:ln.dateTimeGroup,formatString:"yyyy-MM-dd HH:mm:ss.SSS"},{group:ln.dateTimeGroup,formatString:"yyyy-MM-dd HH:mm:ss.SSSSSSSSS"}].map(l=>{const a=ct.makeFormat("",l.formatString,ct.TYPE_CONTEXT_PRESET),d=e.getFormattedString(n,F.dataType.DATETIME,"",a);return Vt.makeOption(d,a,l.group,ct.isSameFormat(a,t))});return[Vt.makeOption("Default",null,ln.dateGroup,Vt.isDefaultSelected(t)),...i]}}const Rv=ln;class an{static defaultGroup=10;static presetGroup=20;static presetRoundGroup=30;static customGroup=40;static getOptions(e,t){const n=[{format:Ke.FORMAT_PERCENT,group:an.presetGroup},{format:Ke.FORMAT_BASIS_POINTS,group:an.presetGroup},{format:Ke.FORMAT_MILLIONS,group:an.presetGroup},{format:Ke.FORMAT_SCIENTIFIC_NOTATION,group:an.presetGroup},{format:Ke.FORMAT_ROUND,group:an.presetRoundGroup},{format:Ke.FORMAT_ROUND_TWO_DECIMALS,group:an.presetRoundGroup},{format:Ke.FORMAT_ROUND_FOUR_DECIMALS,group:an.presetRoundGroup}],s=Vt.makeOption("Default",null,an.defaultGroup,Vt.isDefaultSelected(e)),i=n.map(d=>Vt.makeOption(d.format.label,d.format,d.group,Ke.isSameFormat(d.format,e))),o=Vt.isCustomSelected(e),l=o?e:Ke.makeCustomFormat(),a=Vt.makeCustomFormatOption(l,an.customGroup,Ke.DEFAULT_FORMAT_STRING,o,d=>{if(d!=null){const h=Ke.makeCustomFormat(d);Ke.isValid(h)&&t(h)}else t(null)});return[s,...i,a]}}const xv=an;class fi{static defaultGroup=10;static presetGroup=20;static customGroup=30;static getOptions(e,t){const n=[{format:dt.FORMAT_MILLIONS,group:fi.presetGroup},{format:dt.FORMAT_SCIENTIFIC_NOTATION,group:fi.presetGroup}],s=Vt.makeOption("Default",null,fi.defaultGroup,Vt.isDefaultSelected(e)),i=n.map(d=>Vt.makeOption(d.format.label,d.format,d.group,dt.isSameFormat(d.format,e))),o=Vt.isCustomSelected(e),l=o?e:dt.makeCustomFormat(),a=Vt.makeCustomFormatOption(l,fi.customGroup,dt.DEFAULT_FORMAT_STRING,o,d=>{if(d!=null){const h=dt.makeCustomFormat(d);dt.isValid(h)&&t(h)}else t(null)});return[s,...i,a]}}const Dv=fi;const ec=ne.module("IrisGridContextMenuHandler"),Iv=150,tc="yyyy-MM-dd HH:mm:ss.SSSSSSSSS";class X extends ht{static GROUP_EDIT=ie.groups.high+10;static GROUP_HIDE_COLUMNS=ie.groups.high+25;static GROUP_FILTER=ie.groups.high+50;static GROUP_EXPAND_COLLAPSE=ie.groups.high+55;static GROUP_GOTO=ie.groups.high+60;static GROUP_SORT=ie.groups.high+75;static GROUP_COPY=ie.groups.high+100;static GROUP_FORMAT=ie.groups.high+150;static COLUMN_SORT_DIRECTION={ascending:"ASC",descending:"DESC",none:null};static getQuickFilterCondition(e,t,n){return e&&n==="&&"?e.and(t):e&&n==="||"?e.or(t):t}static getQuickFilterText(e,t,n){return n&&e!=null?`${e} ${n} ${t}`:t}static getOperatorAsText(e){return e==="&&"?"And":"Or"}static getNumberValueEqualsFilter(e,t){const n=e.filter();if(t===Number.POSITIVE_INFINITY)return I.FilterCondition.invoke("isInf",n).and(n.greaterThan(I.FilterValue.ofNumber(0)));if(t===Number.NEGATIVE_INFINITY)return I.FilterCondition.invoke("isInf",n).and(n.lessThan(I.FilterValue.ofNumber(0)));if(Number.isNaN(t))return I.FilterCondition.invoke("isNaN",n);const s=X.getFilterValueForNumberOrChar(e.type,t);return n.eq(s)}static getFilterValueForNumberOrChar(e,t){return F.isCharType(e)?I.FilterValue.ofString(String.fromCharCode(t)):I.FilterValue.ofNumber(t)}static getRowOptionFormatted(e,t,n=30){return`${e} "${fs.truncate(t,n-e.length-3)}"`}irisGrid;debouncedUpdateCustomFormat;constructor(e){super(),this.debouncedUpdateCustomFormat=Ye(e.handleFormatSelection,Iv),this.irisGrid=e}componentWillUnmount(){this.debouncedUpdateCustomFormat.flush()}getHeaderActions(e,t){const{irisGrid:n}=this,{column:s}=t;N(s);const{model:i}=n.props,{columns:o}=i,l=o[e],a=[],{metrics:d,reverseType:h,quickFilters:u,advancedFilters:m,searchFilter:g}=n.state,p=n.getTheme();N(d);const{filterIconColor:C,filterBarActiveColor:f,contextMenuSortIconColor:b,contextMenuReverseIconColor:w}=p,S=i.sort,T=F.getSortForColumn(S,l.name),y=h!==F.REVERSE_TYPE.NONE,{userColumnWidths:E}=d,R=[...E.values()].some(M=>M===0),x=i.getColumnHeaderParentGroup(e,0)===void 0&&!(je(i)&&i.hasExpandableRows),D=i.isColumnFrozen(e);return a.push({title:"Hide Column",group:X.GROUP_HIDE_COLUMNS,action:()=>{this.irisGrid.hideColumnByVisibleIndex(s)}}),a.push({title:D?"Unfreeze Column":"Freeze Column",group:X.GROUP_HIDE_COLUMNS,disabled:!x,action:()=>{D?this.irisGrid.unFreezeColumnByColumnName(l.name):this.irisGrid.freezeColumnByColumnName(l.name)},order:10}),a.push({title:"Show All Columns",group:X.GROUP_HIDE_COLUMNS,action:()=>{this.irisGrid.showAllColumns()},disabled:!R}),a.push({title:"Quick Filters",icon:Mn,iconColor:f,shortcut:Ut.TABLE.TOGGLE_QUICK_FILTER,group:X.GROUP_FILTER,order:10,action:()=>{this.irisGrid.toggleFilterBar(s)}}),a.push({title:"Advanced Filters",icon:m.get(e)?cr:dl,iconColor:C,group:X.GROUP_FILTER,order:20,action:()=>{this.irisGrid.handleAdvancedMenuOpened(s)}}),a.push({title:"Clear Table Filters",group:X.GROUP_FILTER,order:40,shortcut:Ut.TABLE.CLEAR_FILTERS,action:()=>{this.irisGrid.clearAllFilters()},disabled:!(u.size>0||m.size>0||g!=null)}),a.push({title:"Sort by",icon:Mn,iconColor:b,group:X.GROUP_SORT,order:10,actions:this.sortByActions(l,e,T)}),a.push({title:"Add Additional Sort",disabled:T&&S.length===1||y&&S.length===1||T&&y&&S.length===2||S.length===0,group:X.GROUP_SORT,order:20,actions:this.additionalSortActions(l,e)}),a.push({title:"Clear Table Sorting",disabled:S.length===0||y&&S.length===1,group:X.GROUP_SORT,action:()=>{this.irisGrid.sortColumn(s,X.COLUMN_SORT_DIRECTION.none)},order:30}),a.push({title:h===F.REVERSE_TYPE.NONE?"Reverse Table":"Clear Reverse Table",icon:Mn,iconColor:w,group:X.GROUP_SORT,order:40,disabled:!i.isReversible,shortcut:Ut.TABLE.REVERSE,action:()=>{h===F.REVERSE_TYPE.NONE?this.irisGrid.reverse(F.REVERSE_TYPE.POST_SORT):this.irisGrid.reverse(F.REVERSE_TYPE.NONE)}}),a.push({title:"Copy Column Name",group:X.GROUP_COPY,action:()=>{ho(i.textForColumnHeader(e)??"").catch(M=>ec.error("Unable to copy header",M))}}),F.isDateType(l.type)?a.push({title:"Date/Time Format",group:X.GROUP_FORMAT,actions:this.dateFormatActions(l)}):F.isNumberType(l.type)&&a.push({title:"Number Format",group:X.GROUP_FORMAT,actions:this.numberFormatActions(l)??void 0}),a}getCellActions(e,t,n){N(e);const{irisGrid:s}=this,{column:i,row:o}=n,{model:l,canCopy:a}=s.props,{columns:d}=l,h=s.getModelRow(o);N(h);const u=l.valueForCell(e,h),m=l.textForCell(e,h),g=d[e],p=[],{quickFilters:C}=s.state,f=s.getTheme(),{filterIconColor:b}=f,{settings:w}=s.props,S=new ct({timeZone:w?.timeZone,showTimeZone:!1,showTSeparator:!0,defaultDateTimeFormatString:tc}),T=new ct({timeZone:w?.timeZone,showTimeZone:w?.showTimeZone,showTSeparator:w?.showTSeparator,defaultDateTimeFormatString:tc});if(g==null||o==null)return p;if(l.isFilterable(e)){const E={title:"Filter by Value",icon:Mn,iconColor:b,group:X.GROUP_FILTER,order:10,actions:[]};if(u==null)C.get(e)&&E.actions.push({title:"And",actions:this.nullFilterActions(g,C.get(e),"&&"),order:2,group:ie.groups.high}),E.actions.push(...this.nullFilterActions(g));else if(F.isBooleanType(g.type))C.get(e)&&E.actions.push({title:"Or",actions:this.booleanFilterActions(g,m,C.get(e),"||"),order:2,group:ie.groups.high}),E.actions.push(...this.booleanFilterActions(g,m));else if(F.isNumberType(g.type)||F.isCharType(g.type)){N(e);const R=F.isCharType(g.type)?String.fromCharCode(u):`${u}`;C.get(e)&&E.actions.push({title:"And",actions:this.numberFilterActions(g,R,u,C.get(e),"&&"),order:2,group:ie.groups.high}),E.actions.push(...this.numberFilterActions(g,R,u,C.get(e)))}else if(F.isDateType(g.type)){const R=S.format(u),x=T.format(u);C.get(e)&&E.actions.push({title:"And",actions:this.dateFilterActions(g,R,x,u,C.get(e),"&&"),order:2,group:ie.groups.high}),E.actions.push(...this.dateFilterActions(g,R,x,u,C.get(e)))}else C.get(e)&&E.actions.push({title:"And",actions:this.stringFilterActions(g,m,u,C.get(e),"&&"),order:2,group:ie.groups.high}),E.actions.push(...this.stringFilterActions(g,m,u));E.actions!=null&&E.actions.length>0&&p.push(E)}if(je(l)&&l.isRowExpandable(h)){const E=l.groupedColumns.length>0?l.depthForRow(h)-1:0,x=l.valueForCell(E,h)==null?"null":l.textForCell(E,h);p.push({title:X.getRowOptionFormatted(l.isRowExpanded(h)?"Collapse":"Expand",x),group:X.GROUP_EXPAND_COLLAPSE,order:10,action:()=>{l.setRowExpanded(h,!l.isRowExpanded(h))}}),l.isExpandAllAvailable===!0&&p.push({title:X.getRowOptionFormatted("Expand All in",x),group:X.GROUP_EXPAND_COLLAPSE,order:20,action:()=>{l.setRowExpanded(h,!0,!0)}})}je(l)&&l.hasExpandableRows&&l.isExpandAllAvailable===!0&&(p.push({title:"Expand Entire Table",group:X.GROUP_EXPAND_COLLAPSE,order:30,action:()=>{l.expandAll()}}),p.push({title:"Collapse Entire Table",group:X.GROUP_EXPAND_COLLAPSE,order:40,action:()=>{l.collapseAll()}}));const y={title:"Go to",iconColor:b,shortcut:Ut.TABLE.GOTO_ROW,group:X.GROUP_GOTO,order:10,action:()=>this.irisGrid.toggleGotoRow(`${o+1}`,`${u}`,g.name)};return p.push(y),a&&(p.push({title:"Copy Cell",group:X.GROUP_COPY,order:10,action:()=>{s.copyCell(i,o)}}),p.push({title:"Copy Cell Unformatted",group:X.GROUP_COPY,order:20,action:()=>{s.copyCell(i,o,!0)}})),p}onContextMenu(e,t,n){const{irisGrid:s}=this,{y:i,column:o,row:l,columnHeaderDepth:a}=e,d=s.getModelColumn(o),h=s.getModelRow(l),{model:u,canCopy:m}=s.props,{columns:g}=u,{metrics:p,isFilterBarShown:C,quickFilters:f,advancedFilters:b,selectedRanges:w}=s.state;N(p);const{columnHeaderHeight:S,gridY:T,columnHeaderMaxDepth:y}=p,E=[];if(d!=null&&h!=null){const R=u.valueForCell(d,h),x=u.textForCell(d,h),D=g[d],{onContextMenu:M}=s.props;D!=null&&E.push(M({model:u,value:R,valueText:x,column:D,rowIndex:l,columnIndex:o,modelRow:h,modelColumn:d}))}return d!=null&&u.isFilterable(d)&&E.push({title:"Clear Column Filter",group:X.GROUP_FILTER,order:30,action:()=>{this.irisGrid.removeColumnFilter(d)},disabled:!(f.has(d)||b.has(d))}),(C?i<=T:i<=S*y&&a===0)?d!=null&&E.push(...this.getHeaderActions(d,e)):(d!=null&&h!=null&&E.push(...this.getCellActions(d,t,e)),m&&w.length>0&&(E.push({title:"Copy Selection",shortcut:Kn.COPY,group:X.GROUP_COPY,order:30,action:()=>{s.copyRanges(w)}}),E.push({title:"Copy Selection w/ Headers",group:X.GROUP_COPY,order:40,action:()=>{s.copyRanges(w,!0)}})),Xe(u)&&u.isEditable&&w.length>0&&E.push({title:"Delete Selected Rows",group:X.GROUP_EDIT,order:50,action:()=>{this.irisGrid.deleteRanges(w)}})),E.length===0?!1:(N(s.gridWrapper),ie.triggerMenu(s.gridWrapper,n.clientX,n.clientY,E),!0)}dateFormatActions(e){const{model:t}=this.irisGrid.props,{formatter:n}=t,s=n.getColumnFormat(e.type,e.name),i=Rv.getOptions(n,s),o=[];for(let l=0;l<i.length;l+=1){const{description:a,format:d,group:h,isSelected:u,title:m}=i[l];o.push({title:m,description:a,icon:u?zn:void 0,group:h,order:l,action:()=>{const g=t.getColumnIndexByName(e.name);N(g),this.irisGrid.handleFormatSelection(g,d)}})}return o}numberFormatActions(e){const{model:t}=this.irisGrid.props,{formatter:n}=t,s=n.getColumnFormat(e.type,e.name);let i;const o=t.getColumnIndexByName(e.name);if(F.isDecimalType(e.type))i=xv.getOptions(s,a=>{N(o),this.debouncedUpdateCustomFormat(o,a)});else if(F.isIntegerType(e.type))i=Dv.getOptions(s,a=>{N(o),this.debouncedUpdateCustomFormat(o,a)});else return ec.error("Invalid column type in numberFormatActions"),null;const l=[];for(let a=0;a<i.length;a+=1){const{format:d,isSelected:h}=i[a];l.push({...i[a],icon:h?zn:void 0,order:a,action:()=>{o===void 0&&d&&d.type===nl.TYPE_CONTEXT_CUSTOM||(N(o),this.irisGrid.handleFormatSelection(o,d))}})}return l}stringFilterActions(e,t,n,s,i){const o=I.FilterValue.ofString(n);let l=s;l||(l={filter:null,text:null});const{filter:a,text:d}=l,h=[],{model:u}=this.irisGrid.props,m=u.getColumnIndexByName(e.name);return N(m),h.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[i?X.getOperatorAsText(i):""," ",'"',t,'"']}),order:1,group:ie.groups.high}),h.push({title:"text is exactly",description:`Show only rows where ${e.name} is ${n} (case sensitive)`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(a,e.filter().eq(o),i),X.getQuickFilterText(d,`=${t}`,i))},order:10,group:ie.groups.low}),h.push({title:"text is not exactly",description:`Show only rows where ${e.name} is not ${t} (case sensitive)`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(a,e.filter().notEq(o),i),X.getQuickFilterText(d,`!=${t}`,i))},order:20,group:ie.groups.low}),h.push({title:"text contains",description:`Show only rows where ${e.name} contains ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(a,e.filter().contains(o),i),X.getQuickFilterText(d,`~${t}`,i))},order:30,group:ie.groups.low}),h.push({title:"text does not contain",description:`Show only rows where ${e.name} does not contain ${n}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(a,e.filter().contains(o).not(),i),X.getQuickFilterText(d,`!~${t}`,i))},order:40,group:ie.groups.low}),h.push({title:"text starts with",description:`Show only rows where ${e.name} starts with ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(a,e.filter().invoke("startsWith",o),i),X.getQuickFilterText(d,`${t}*`,i))},order:50,group:ie.groups.low}),h.push({title:"text ends with",description:`Show only rows where ${e.name} ends with ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(a,e.filter().invoke("endsWith",o),i),X.getQuickFilterText(d,`*${t}`,i))},order:60,group:ie.groups.low}),h}numberFilterActions(e,t,n,s,i){const o=X.getFilterValueForNumberOrChar(e.type,n);let l=null,a=null;s&&(l=s.filter,a=s.text);const d=[],h=n!==Number.POSITIVE_INFINITY&&n!==Number.NEGATIVE_INFINITY&&!Number.isNaN(n),{model:u}=this.irisGrid.props,m=u.getColumnIndexByName(e.name);return N(m),d.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[i?X.getOperatorAsText(i):""," ",'"',t,'"']}),order:1,group:ie.groups.high}),d.push({title:"is equal to",description:`Show only rows where ${e.name} is ${t}`,action:()=>{const g=X.getNumberValueEqualsFilter(e,n);this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(l,g,i),X.getQuickFilterText(a,`=${t}`,i))},order:10,group:ie.groups.low}),d.push({title:"is not equal to",description:`Show only rows where ${e.name} is not ${t}`,action:()=>{const g=X.getNumberValueEqualsFilter(e,n).not();this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(l,g,i),X.getQuickFilterText(a,`!=${t}`,i))},order:20,group:ie.groups.low}),h&&!F.isCharType(e.type)&&(d.push({title:"greater than",description:`Show only rows where ${e.name} is greater than ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(l,e.filter().greaterThan(o),i),X.getQuickFilterText(a,`>${t}`,i))},order:30,group:ie.groups.low}),d.push({title:"greater than or equal to",description:`Show only rows where ${e.name} is greater than or equal to ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(l,e.filter().greaterThanOrEqualTo(o),i),X.getQuickFilterText(a,`>=${t}`,i))},order:40,group:ie.groups.low}),d.push({title:"less than",description:`Show only rows where ${e.name} is less than ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(l,e.filter().lessThan(o),i),X.getQuickFilterText(a,`<${t}`,i))},order:50,group:ie.groups.low}),d.push({title:"less than or equal to",description:`Show only rows where ${e.name} is less than or equal to ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,X.getQuickFilterCondition(l,e.filter().lessThanOrEqualTo(o),i),X.getQuickFilterText(a,`<=${t}`,i))},order:60,group:ie.groups.low})),d}booleanFilterActions(e,t,n,s){const i=[],{model:o}=this.irisGrid.props,{filter:l,text:a}=n||{},d=o.getColumnIndexByName(e.name);return N(d),i.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[s?X.getOperatorAsText(s):""," ",'"',t??"null",'"']}),order:1,group:ie.groups.high}),i.push({title:"true",description:`Show only rows where ${e.name} is true`,action:()=>{this.irisGrid.setQuickFilter(d,X.getQuickFilterCondition(l,e.filter().isTrue(),s),X.getQuickFilterText(a,"true",s))},order:10,group:ie.groups.low}),i.push({title:"false",description:`Show only rows where ${e.name} is false`,action:()=>{this.irisGrid.setQuickFilter(d,X.getQuickFilterCondition(l,e.filter().isFalse(),s),X.getQuickFilterText(a,"false",s))},order:20,group:ie.groups.low}),i.push({title:"is null",description:`Show only rows where ${e.name} is null`,action:()=>{this.irisGrid.setQuickFilter(d,X.getQuickFilterCondition(l,e.filter().isNull(),s),X.getQuickFilterText(a,"null",s))},order:30,group:ie.groups.low}),i.push({title:"is not null",description:`Show only rows where ${e.name} is not null`,action:()=>{this.irisGrid.setQuickFilter(d,X.getQuickFilterCondition(l,e.filter().isNull().not(),s),X.getQuickFilterText(a,"!null",s))},order:40,group:ie.groups.low}),i}dateFilterActions(e,t,n,s,i,o){const l=I.FilterValue.ofNumber(s);let a=null,d=null;i&&(a=i.filter,d=i.text);const{model:h}=this.irisGrid.props,u=h.getColumnIndexByName(e.name);N(u);const m=[];return m.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[o?X.getOperatorAsText(o):""," ",'"',n,'"']}),order:1,group:ie.groups.high}),m.push({title:"date is",description:`Show only rows where ${e.name} is ${n}`,action:()=>{this.irisGrid.setQuickFilter(u,X.getQuickFilterCondition(a,e.filter().eq(l),o),X.getQuickFilterText(d,`=${t}`,o))},order:10,group:ie.groups.low}),m.push({title:"date is not",description:`Show only rows where ${e.name} is not ${n}`,action:()=>{this.irisGrid.setQuickFilter(u,X.getQuickFilterCondition(a,e.filter().notEq(l),o),X.getQuickFilterText(d,`!=${t}`,o))},order:20,group:ie.groups.low}),m.push({title:"date is before",description:`Show only rows where ${e.name} is before ${n}`,action:()=>{this.irisGrid.setQuickFilter(u,X.getQuickFilterCondition(a,e.filter().lessThan(l),o),X.getQuickFilterText(d,`<${t}`,o))},order:30,group:ie.groups.low}),m.push({title:"date is before or equal",description:`Show only rows where ${e.name} is before or equal to ${n}`,action:()=>{this.irisGrid.setQuickFilter(u,X.getQuickFilterCondition(a,e.filter().lessThanOrEqualTo(l),o),X.getQuickFilterText(d,`<=${t}`,o))},order:40,group:ie.groups.low}),m.push({title:"date is after",description:`Show only rows where ${e.name} is greater than ${n}`,action:()=>{this.irisGrid.setQuickFilter(u,X.getQuickFilterCondition(a,e.filter().greaterThan(l),o),X.getQuickFilterText(d,`>${t}`,o))},order:50,group:ie.groups.low}),m.push({title:"date is after or equal",description:`Show only rows where ${e.name} is after or equal to ${n}`,action:()=>{this.irisGrid.setQuickFilter(u,X.getQuickFilterCondition(a,e.filter().greaterThanOrEqualTo(l),o),X.getQuickFilterText(d,`>=${t}`,o))},order:60,group:ie.groups.low}),m}nullFilterActions(e,t,n){let s=null,i=null;t&&(s=t.filter,i=t.text);const o=[],{model:l}=this.irisGrid.props,a=l.getColumnIndexByName(e.name);return N(a),o.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[n?X.getOperatorAsText(n):""," ",'"null"']}),order:1,group:ie.groups.high}),o.push({title:"is null",description:`Show only rows where ${e.name} is null`,action:()=>{this.irisGrid.setQuickFilter(a,X.getQuickFilterCondition(s,e.filter().isNull(),n),X.getQuickFilterText(i,"null",n))},order:10,group:ie.groups.low}),o.push({title:"is not null",description:`Show only rows where ${e.name} is not null`,action:()=>{this.irisGrid.setQuickFilter(a,X.getQuickFilterCondition(s,e.filter().isNull().not(),n),X.getQuickFilterText(i,"!null",n))},order:20,group:ie.groups.low}),o}sortByActions(e,t,n){const s=this.irisGrid.getTheme(),{contextMenuSortIconColor:i}=s,o=[{title:`${e.name} Ascending`,order:10,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.ascending)},icon:this.checkColumnSort(n,X.COLUMN_SORT_DIRECTION.ascending)?Mn:void 0,iconColor:i},{title:`${e.name} Descending`,order:20,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.descending)},icon:this.checkColumnSort(n,X.COLUMN_SORT_DIRECTION.descending)?Mn:void 0,iconColor:i},{title:"Remove Sort",order:50,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.none,!1,!0)},disabled:!n}];return F.isNumberType(e.type)&&(o.push({title:`ABS(${e.name}) Ascending`,order:30,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.ascending,!0)},icon:this.checkColumnSort(n,X.COLUMN_SORT_DIRECTION.ascending,!0)?Mn:void 0,iconColor:i}),o.push({title:`ABS(${e.name}) Descending`,order:40,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.descending,!0)},icon:this.checkColumnSort(n,X.COLUMN_SORT_DIRECTION.descending,!0)?Mn:void 0,iconColor:i})),o}additionalSortActions(e,t){const n=this.irisGrid.getTheme(),{contextMenuSortIconColor:s}=n,i=[{title:"Add Sort By",menuElement:r.jsxs("div",{className:"btn-context-menu menu-title",children:[r.jsx("span",{className:"icon",children:r.jsx(ee,{icon:Mn,style:{color:s??void 0}})}),r.jsx("span",{className:"title",children:"Add Additional Sort"}),r.jsx("span",{className:"shortcut",children:Ts.isMacPlatform()?"⌘Click":"Ctrl+Click"})]}),order:1},{title:`${e.name} Ascending`,order:10,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.ascending,!1,!0)}},{title:`${e.name} Descending`,order:20,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.descending,!1,!0)}}];return F.isNumberType(e.type)&&(i.push({title:`ABS(${e.name}) Ascending`,order:30,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.ascending,!0,!0)}}),i.push({title:`ABS(${e.name}) Descending`,order:40,action:()=>{this.irisGrid.sortColumn(t,X.COLUMN_SORT_DIRECTION.descending,!0,!0)}})),i}checkColumnSort(e,t=null,n=!1){return e?e.direction===t&&e.isAbs===n:!1}}const Fv=X;class Nv extends ht{constructor(e){super(),this.irisGrid=e}irisGrid;onDoubleClick(e){const{column:t,row:n}=e;return n==null||t==null?!1:(this.irisGrid.selectData(t,n),!0)}}const kv=Nv;class Mv extends ht{constructor(e){super(),this.irisGrid=e}irisGrid;onDown(e){const{y:t,column:n,row:s}=e;if(n!==null&&s===null){const{isFilterBarShown:i,metrics:o}=this.irisGrid.state;if(!o)throw new Error("Metrics not set");const{columnHeaderMaxDepth:l}=o,a=this.irisGrid.getTheme();if(i&&a.columnHeaderHeight!=null&&a.filterBarHeight!=null&&t>a.columnHeaderHeight*l&&t<=a.columnHeaderHeight*l+a.filterBarHeight)return this.irisGrid.focusFilterBar(n),!0}return!1}onMove(e){const{y:t,column:n}=e,{isFilterBarShown:s,hoverAdvancedFilter:i,metrics:o}=this.irisGrid.state;if(!o)throw new Error("Metrics not set");const{columnHeaderMaxDepth:l}=o,a=this.irisGrid.getTheme();let d=null;return s&&a.columnHeaderHeight!=null&&a.filterBarHeight!=null&&n!==null&&t>=a.columnHeaderHeight*l&&t<=a.columnHeaderHeight*l+a.filterBarHeight&&(d=n),d!==i&&this.irisGrid.setState({hoverAdvancedFilter:d}),!1}onLeave(e){const{column:t}=e,{hoverAdvancedFilter:n}=this.irisGrid.state;return n!==null&&t!==n&&this.irisGrid.setState({hoverAdvancedFilter:null}),!1}}const Lv=Mv;class Ov extends ht{irisGrid;constructor(e){super(750),this.irisGrid=e}destroyTooltip(){this.irisGrid.setState({expandCellTooltipProps:null})}setCursor(e,t){return Xa.isInTreeBox(e,t)?(this.cursor="pointer",{stopPropagation:!1,preventDefault:!1}):(this.cursor=null,!1)}getButtonPosition({x:e,y:t,column:n,row:s}){if(n==null||s==null)return null;const{renderer:i,grid:o,state:l,props:a}=this.irisGrid;if(!o)return null;const{metrics:d}=l,{model:h}=a,{canvasContext:u}=o,m=o.getTheme(),g={context:u,mouseX:e,mouseY:t,metrics:d,model:h,theme:m},p=je(h)?h.depthForRow(s):null,{left:C,top:f,width:b,height:w}=i.getExpandButtonPosition(g,p);return C==null||b==null||f==null||w==null?null:{left:C,top:f,width:b,height:w}}onMove(e,t){if(Xa.isInTreeBox(e,t)){const{expandCellTooltipProps:n}=this.irisGrid.state,{model:s}=this.irisGrid.props,i=this.getButtonPosition(e),{row:o}=e;N(o);const l=je(s)&&s.isRowExpanded(o);st(n,i)||this.irisGrid.setState({expandCellTooltipProps:i,expandTooltipDisplayValue:l?"collapse":"expand"})}else this.destroyTooltip();return this.setCursor(e,t)}onDown(){return this.destroyTooltip(),!1}onContextMenu(){return this.destroyTooltip(),!1}onWheel(){return this.destroyTooltip(),!1}onLeave(){return this.destroyTooltip(),!1}}const Av=Ov;class _v extends ht{constructor(e){super(),this.column=null,this.irisGrid=e}irisGrid;column;getColumnFromGridPoint(e){const{column:t,row:n,columnHeaderDepth:s}=e;return t!==null&&n===null&&s===0?t:null}onDown(e){return this.column=this.getColumnFromGridPoint(e),!1}onClick(e,t,n){const s=this.getColumnFromGridPoint(e);if(s!=null&&s===this.column){const i=Ts.isModifierKeyDown(n);return this.irisGrid.toggleSort(s,i),!0}return!1}}const Pv=_v;class jv extends ht{constructor(e){super(),this.irisGrid=e}onWheel(e,t,n){const{irisGrid:s}=this,{model:i}=s.props,{metrics:o,pendingRowCount:l}=s.state;N(o);const{bottom:a,rowCount:d,rowHeight:h}=o,{deltaY:u}=_.getScrollDelta(n);return Xe(i)&&i.isEditable&&a>=d-1&&u>0&&s.setState({pendingRowCount:l+Math.ceil(u/h)}),!1}}const Hv=jv;class Bv extends ht{irisGrid;currentLinkBox;constructor(e){super(),this.irisGrid=e}destroyTooltip(){this.irisGrid.setState({linkHoverTooltipProps:null})}isHoveringLink(e,t){const{column:n,row:s,x:i,y:o}=e,{renderer:l,metrics:a,props:d}=t,{model:h}=d;if(n==null||s==null||a==null)return this.currentLinkBox=void 0,!1;const{modelRows:u,modelColumns:m}=a,g=k(u,s),p=k(m,n),C=h.renderTypeForCell(p,g),f=l.getCellRenderer(C);if(!Cu(f))return!1;if(this.currentLinkBox!=null){const{x1:S,y1:T,x2:y,y2:E}=this.currentLinkBox;if(i>=S&&i<=y&&o>=T&&o<=E)return!0}const b=t.updateRenderState(),w=f.getTokenBoxesForVisibleCell(n,s,b);for(let S=0;S<w.length;S+=1)if(wl(w[S].token)){const T=_.translateTokenBox(w[S],a),{x1:y,x2:E,y1:R,y2:x}=T;if(i>=y&&i<=E&&o>=R&&o<=x)return this.currentLinkBox=T,!0}return this.currentLinkBox=void 0,!1}setCursor(e,t){return this.isHoveringLink(e,t)?(this.cursor="pointer",{stopPropagation:!1,preventDefault:!1}):(this.cursor=null,!1)}onMove(e,t){if(this.isHoveringLink(e,t)&&this.currentLinkBox!=null&&wl(this.currentLinkBox.token)){const{linkHoverTooltipProps:s}=this.irisGrid.state;if(this.currentLinkBox==null)return!1;const{x1:i,y1:o,x2:l,y2:a}=this.currentLinkBox,{href:d}=this.currentLinkBox.token,h=l-i,u=a-o,m={left:i,top:o+1,width:h,height:u};st(s,m)||this.irisGrid.setState({linkHoverTooltipProps:m,linkHoverDisplayValue:d})}else this.destroyTooltip();return this.setCursor(e,t)}onDown(){return this.destroyTooltip(),!1}onContextMenu(){return this.destroyTooltip(),!1}onWheel(){return this.destroyTooltip(),!1}onLeave(){return this.destroyTooltip(),!1}}const Uv=Bv,Vv=3e3;function $v({children:c=null,onEntering:e,onEntered:t,onExiting:n,onExited:s}){const[i,o]=v.useState(!1),l=v.useRef(),a=lr(c),d=v.useCallback(()=>{o(!0),l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{o(!1)},Vv)},[o,l]);return v.useEffect(()=>{a!==c&&c!=null&&d()},[c,a,o,d]),v.useEffect(()=>()=>l.current?clearTimeout(l.current):void 0,[]),r.jsx(sa,{className:"toast-bottom-bar",isShown:i,onEntering:e,onEntered:t,onExiting:n,onExited:s,children:c})}class Wv extends bo{getGridY(e){let t=super.getGridY(e);const{isFilterBarShown:n,theme:s,advancedFilters:i,quickFilters:o,sorts:l,reverseType:a}=e;return n?t+=s.filterBarHeight:(o!=null&&o.size>0||i!=null&&i.size>0)&&(t+=s.filterBarCollapsedHeight),a!==F.REVERSE_TYPE.NONE&&l!=null&&l.length>0&&(t+=s.reverseHeaderBarHeight),t}getUserColumnWidths(){return this.userColumnWidths}}const Gv=Wv,zv=1,Ru=de.memo(({model:c,modelColumns:e,top:t,bottom:n,left:s,right:i,filter:o,formatter:l,reverseType:a=F.REVERSE_TYPE.NONE,sorts:d,customColumns:h,movedColumns:u,hiddenColumns:m,alwaysFetchColumns:g,rollupConfig:p=null,totalsConfig:C=null,selectDistinctColumns:f=ke,pendingRowCount:b=0,pendingDataMap:w=Pn,frozenColumns:S,formatColumns:T,columnHeaderGroups:y})=>{const E=v.useMemo(()=>Se.getModelViewportColumns(e,s,i,u,m,g,zv),[e,s,i,u,m,g]);return v.useEffect(function(){c.filter=o},[c,o]),v.useEffect(function(){const x=[...d];a!==F.REVERSE_TYPE.NONE&&x.push(I.Table.reverse()),c.sort=x},[c,d,a]),v.useEffect(function(){c.formatter=l},[c,l]),v.useEffect(function(){c.isCustomColumnsAvailable&&(c.customColumns=h)},[c,h]),v.useEffect(function(){c.isFormatColumnsAvailable&&(c.formatColumns=T)},[c,T]),v.useEffect(function(){c.setViewport(t,n,E)},[c,t,n,E]),v.useEffect(function(){c.isRollupAvailable&&(c.rollupConfig=p)},[c,c.isRollupAvailable,p]),v.useEffect(function(){c.isSelectDistinctAvailable&&(c.selectDistinctColumns=f)},[c,f]),v.useEffect(function(){c.isTotalsAvailable&&(c.totalsConfig=C)},[c,c.isTotalsAvailable,C]),v.useEffect(function(){c.pendingRowCount=b},[c,b]),v.useEffect(function(){c.pendingDataMap=w},[c,w]),v.useEffect(function(){S&&c.updateFrozenColumns(S)},[c,S]),v.useEffect(function(){c.columnHeaderGroups=y},[c,y]),null});Ru.displayName="IrisGridModelUpdater";const Kv=Ru,Za=16,Yv=new Map([["sortUp",ug],["sortDown",mg],["caretDown",Un],["caretRight",Zc],["cellOverflow",gg]]),qv=pn(c=>{const e=Yv.get(c);if(e===void 0)throw new Error("Icon is undefined");const t=Array.isArray(e.icon[4])?e.icon[4][0]:e.icon[4],n=new Path2D(t),s=new Path2D,i={a:Za/e.icon[0],d:Za/e.icon[1]};return s.addPath(n,i),s},{max:1e3});function Ji(c){return qv(c)}class Xv{static drawTreeMarker(e,t,n,s,i,o,l){e.save();const{x1:a,y1:d}=i,h=Ji(l?"caretDown":"caretRight"),u=n+a-2,m=s+d+2.5;e.fillStyle=o,e.textAlign="center",e.translate(u,m),e.fill(h),e.restore()}}const xu=Xv;class Zv extends pu{drawCellContent(e,t,n,s){const{metrics:i,model:o}=t,{modelColumns:l,modelRows:a}=i,d=k(a,s),h=l.get(n);if(h===void 0)return;const u=o.valueForCell(h,d);if(F.isTextType(o.columns[h]?.type)&&(u===null||u==="")){const m=e.font;e.font=`italic ${m}`,super.drawCellContent(e,t,n,s),e.font=m;return}super.drawCellContent(e,t,n,s)}getTextRenderMetrics(e,t,n){const s=_.getTextRenderMetrics(e,t,n),{mouseX:i,mouseY:o,metrics:l,theme:a}=e;if(i==null||o==null)return s;const{column:d,row:h}=_.getGridPointFromXY(i,o,l);if(t===d&&n===h){const{left:u}=this.getCellOverflowButtonPosition(i,o,l,a);this.shouldRenderOverflowButton(e)&&u!=null&&(s.width=u-l.gridX-s.x)}return s}getCellOverflowButtonPosition(e,t,n,s){const i={left:null,top:null,width:null,height:null};if(e==null||t==null||n==null)return i;const{rowHeight:o,columnWidth:l,left:a,top:d}=_.getCellInfoFromXY(e,t,n);if(a==null||l==null||d==null)return i;const{width:h,verticalBarWidth:u}=n,{cellHorizontalPadding:m}=s,g=Za+2*m,p=o,f=Math.min(n.gridX+a+l,h-u)-g,b=n.gridY+d;return{left:f,top:b,width:g,height:p}}shouldRenderOverflowButton(e){const{context:t,mouseX:n,mouseY:s,metrics:i,model:o,theme:l}=e;if(n==null||s==null)return!1;const{row:a,column:d,modelRow:h,modelColumn:u}=_.getCellInfoFromXY(n,s,i);if(a==null||d==null||h==null||u==null||!F.isStringType(o.columns[u].type))return!1;const m=o.textForCell(u,h)??"",{width:g}=_.getTextRenderMetrics(e,d,a),p=i.fontWidths.get(l.font)??Zs;t.save(),t.font=l.font;const C=this.getCachedTruncatedString(t,m,g,p,o.truncationCharForCell(u,h));return t.restore(),m!==""&&C!==m}drawTreeMarker(e,t,n,s,i,o,l){xu.drawTreeMarker(e,t,n,s,i,o,l)}}const Qv=Zv;class Jv extends gu{drawTreeMarker(e,t,n,s,i,o,l){xu.drawTreeMarker(e,t,n,s,i,o,l)}}const eT=Jv,ya=Object.freeze({SORT_UP:"sortUp",SORT_DOWN:"sortDown",CARET_DOWN:"caretDown",CARET_RIGHT:"caretRight",CELL_OVERFLOW:"cellOverflow"}),nc=10;class yl extends fs{static isFilterValid(e,t){const n=e==null||e.filter!=null,s=t==null||t.filter!=null;return n&&s}textCellRenderer=new Qv;dataBarCellRenderer=new eT;getSortIcon(e){return e?e.direction===F.sortDirection.ascending?Ji(ya.SORT_UP):e.direction===F.sortDirection.descending?Ji(ya.SORT_DOWN):null:null}drawCanvas(e){super.drawCanvas(e),this.drawScrim(e)}drawGrid(e,t){super.drawGrid(e,t),this.drawCellOverflowButton(t)}drawGridLines(e,t){super.drawGridLines(e,t),this.drawGroupedColumnLine(e,t),this.drawPendingRowLine(e,t)}drawCellContent(e,t,n,s){const{metrics:i,model:o}=t,{modelColumns:l,modelRows:a}=i,d=l.get(n),h=k(a,s);if(d===void 0)return;const u=o.renderTypeForCell(d,h);this.getCellRenderer(u).drawCellContent(e,t,n,s)}getCellOverflowButtonPosition({mouseX:e,mouseY:t,metrics:n,theme:s}){return this.textCellRenderer.getCellOverflowButtonPosition(e,t,n,s)}shouldRenderOverflowButton(e){return this.textCellRenderer.shouldRenderOverflowButton(e)}drawCellOverflowButton(e){const{context:t,mouseX:n,mouseY:s,theme:i}=e;if(n==null||s==null||!this.shouldRenderOverflowButton(e))return;const{left:o,top:l,width:a,height:d}=this.getCellOverflowButtonPosition(e),{cellHorizontalPadding:h,overflowButtonColor:u,overflowButtonHoverColor:m}=i;t.save(),m!=null&&o!=null&&a!=null&&l!=null&&d!=null&&n>=o&&n<=o+a&&s>=l&&s<=l+d?t.fillStyle=m:u!=null&&(t.fillStyle=u);const g=Ji(ya.CELL_OVERFLOW);o!=null&&l!=null&&t.translate(o+h,l+2),t.fill(g),t.restore()}drawGroupedColumnLine(e,t){const{metrics:n,model:s,theme:i}=t,{groupedColumns:o}=s,{maxY:l,allColumnWidths:a,allColumnXs:d}=n;if(o.length===0||i.groupedColumnDividerColor==null)return;const h=o.length-1,u=d.get(h),m=a.get(h);if(u==null||m==null)return;const g=u+m+.5;e.strokeStyle=i.groupedColumnDividerColor,e.lineWidth=1,e.beginPath(),e.moveTo(g,0),e.lineTo(g,l),e.stroke()}drawPendingRowLine(e,t){const{metrics:n,model:s,theme:i}=t,{allRowYs:o,maxX:l}=n,{pendingRowCount:a}=s;if(a<=0)return;const d=s.rowCount-s.pendingRowCount-s.floatingBottomRowCount;let h=o.get(d);h!=null&&(h-=.5,e.save(),e.setLineDash([4,2]),e.strokeStyle=i.pendingTextColor,e.lineWidth=1,e.beginPath(),e.moveTo(0,h),e.lineTo(l,h),e.stroke(),e.restore())}drawMouseColumnHover(e,t){const{theme:n,metrics:s,hoverSelectColumn:i}=t;if(i==null||n.linkerColumnHoverBackgroundColor==null)return;const{allColumnWidths:o,allColumnXs:l,maxY:a}=s,d=k(l,i),h=k(o,i);e.fillStyle=n.linkerColumnHoverBackgroundColor,e.fillRect(d,0,h,a)}drawMouseRowHover(e,t){const{isSelectingColumn:n}=t;n||super.drawMouseRowHover(e,t)}drawScrim(e){const{context:t,loadingScrimProgress:n,metrics:s,theme:i}=e;if(n==null)return;const{width:o,height:l,gridY:a}=s,{scrimBlurSize:d,scrimColor:h}=i;t.save(),t.globalCompositeOperation="color",t.filter=`blur(${d}px)`,h!=null&&(t.fillStyle=h),t.beginPath(),t.rect(0,a,o,l-a),t.clip(),t.fillRect(-d,-d+a,d*2+o,(d*2+(l-a))*n),t.globalCompositeOperation="overlay",t.filter=`blur(${d}px) opacity(15%)`,t.fillRect(-d,-d+a,d*2+o,(d*2+(l-a))*n),t.restore()}drawColumnHeaders(e,t){super.drawColumnHeaders(e,t);const{theme:n,metrics:s,model:i,reverseType:o}=t,{columnHeaderHeight:l}=s;if(this.drawFilterHeaders(e,t),l<=0)return;const{sort:a}=i;if(a.length===1){const d=o!==F.REVERSE_TYPE.NONE;let h;d?h=n.headerReverseBarColor:h=n.headerSortBarColor,this.drawHeaderBar(e,t,h,d?n.reverseHeaderBarHeight:n.sortHeaderBarHeight)}else a.length>1&&(o!==F.REVERSE_TYPE.NONE&&this.drawHeaderBar(e,t,n.headerReverseBarColor,n.reverseHeaderBarHeight,!1),this.drawHeaderBar(e,t,n.headerSortBarColor,n.sortHeaderBarHeight))}drawHeaderBar(e,t,n,s,i=!0){const{theme:o,metrics:l,model:a}=t,{columnHeaderHeight:d,width:h}=l;let u=0;i||(u=s),e.fillStyle=o.headerBarCasingColor,e.fillRect(0,a.columnHeaderMaxDepth*d-s-2+u,h,s+2),e.fillStyle=n,e.fillRect(0,a.columnHeaderMaxDepth*d-s-1+u,h,s)}drawColumnHeadersAtDepth(e,t,n,s,i){const{metrics:o,model:l,isMenuShown:a}=t,{columnHeaderMaxDepth:d}=l,{width:h}=o,u={...s,maxX:i===d-1&&s.maxX===h?h-(a?0:30):s.maxX};super.drawColumnHeadersAtDepth(e,t,n,u,i)}drawColumnHeaderAtIndex(e,t,n,s){super.drawColumnHeaderAtIndex(e,t,n,s);const{metrics:i,model:o,theme:l}=t,{modelColumns:a,allColumnWidths:d,allColumnXs:h,gridX:u,columnHeaderHeight:m,fontWidths:g}=i,{headerHorizontalPadding:p}=l,C=k(d,n,0),f=k(h,n)+u,b=a.get(n);if(b==null)return;const w=o.columns[b]?.name;if(w==null)return;const S=F.getSortForColumn(o.sort,w);if(!S)return;const T=this.getSortIcon(S);if(!T)return;const y=o.textForColumnHeader(b);if(y===void 0)return;const E=g.get(e.font)??Zs;N(E);const R=y.length*E,x=u+f+R+p;let{maxX:D}=s;D-=p;const M=u+f+C-p-1,O=x>D?x+1:Math.min(D,M),H=S.direction===F.sortDirection.ascending?-6:-12,L=m*.5+H;e.save(),e.beginPath(),e.rect(f,0,C,m),e.clip(),e.fillStyle=l.headerSortBarColor,e.translate(O,L),e.fill(T),e.restore()}drawFilterHeaders(e,t){const{isFilterBarShown:n,quickFilters:s,advancedFilters:i}=t;n?this.drawExpandedFilterHeaders(e,t):(s!=null&&s.size>0||i!=null&&i.size>0)&&this.drawCollapsedFilterHeaders(e,t)}drawExpandedFilterHeaders(e,t){const{metrics:n,model:s,theme:i,quickFilters:o,advancedFilters:l}=t,{filterBarHeight:a}=i;if(a<=0)return;const{gridX:d,gridY:h,maxX:u,modelColumns:m,visibleColumns:g,allColumnWidths:p,allColumnXs:C}=n,f=h-a;e.save(),e.font=i.font,e.textAlign="left",o!=null&&o.size>0||l!=null&&l.size>0?e.fillStyle=i.filterBarExpandedActiveBackgroundColor:e.fillStyle=i.filterBarExpandedBackgroundColor,e.fillRect(d,f,u,a-1),e.fillStyle=i.headerBarCasingColor,e.fillRect(d,f+a-1,u,1);const b=f;e.strokeStyle=i.filterBarSeparatorColor,e.beginPath();for(let w=0;w<g.length;w+=1){const S=g[w],T=k(m,S),y=k(C,S),E=k(p,S);if(s.isFilterable(T)&&E>0){const R=d+(y??0);e.rect(R+.5,b+.5,E,a-2)}}e.stroke();for(let w=0;w<g.length;w+=1){const S=g[w],T=k(p,S),E=k(C,S)+d;this.drawExpandedFilterHeader(e,t,S,E,T)}e.restore()}drawExpandedFilterHeader(e,t,n,s,i){if(i<=0)return;const{metrics:o,theme:l,quickFilters:a,advancedFilters:d}=t,{modelColumns:h,gridY:u}=o,{filterBarHeight:m,filterBarExpandedActiveCellBackgroundColor:g,filterBarErrorColor:p,filterBarHorizontalPadding:C,headerColor:f}=l,b=u-m,w=h.get(n);if(w===void 0)return;const S=a.get(w),T=d.get(w);if(S==null&&T==null)return;let y=null;if(S!=null){const{text:R}=S;if(y=R,y||(y=F.getFilterText(S.filter)),y!=null){const{fontWidths:x}=o;let D=x.get(e.font);(D==null||D===0)&&(D=e.measureText("8").width,D||(D=10));const M=(i-C*2)/D;M<=0?y="":y.length>M&&(y=`${y.substring(0,M-1)}…`)}}if(e.save(),yl.isFilterValid(T,S)&&g!=null)e.fillStyle=g,e.fillRect(s+1,b+1,i-1,m-3);else if(p!=null){e.fillStyle=p,e.lineWidth=2,e.strokeStyle=p;const R=s+2,x=b+2,D=i-3,M=m-5;e.strokeRect(R,x,D,M)}if(y!=null&&y!==""){const R=s+C,x=b+m*.5+1;e.fillStyle=f,e.fillText(y,R,x)}e.restore()}drawCollapsedFilterHeaders(e,t){const{metrics:n,theme:s}=t,{headerSeparatorColor:i,filterBarCollapsedHeight:o}=s;if(o<=0)return;const{gridX:l,gridY:a,maxX:d,visibleColumns:h,allColumnWidths:u,allColumnXs:m}=n,g=a-o;e.save(),e.fillStyle=i,e.fillRect(l,g,d,o);for(let p=0;p<h.length;p+=1){const C=h[p],f=u.get(C),b=m.get(C);if(b!=null&&f!=null){const w=b+l;this.drawCollapsedFilterHeader(e,t,C,w,f)}}e.restore()}drawCollapsedFilterHeader(e,t,n,s,i){if(i<=0)return;const{metrics:o,theme:l,quickFilters:a,advancedFilters:d}=t,{modelColumns:h,gridY:u}=o,m=h.get(n);if(m===void 0)return;const g=a.get(m),p=d.get(m),{filterBarCollapsedHeight:C,filterBarActiveColor:f,filterBarActiveBackgroundColor:b,filterBarErrorColor:w}=l;e.save();const S=yl.isFilterValid(p,g);b!=null&&g==null&&p==null?e.fillStyle=b:f!=null&&S?e.fillStyle=f:w!=null&&(e.fillStyle=w);const T=s+1,y=u-C,E=i-1,R=C-1;e.fillRect(T,y,E,R),e.restore()}drawRowFooters(e,t){const{metrics:n,model:s,mouseX:i,mouseY:o,theme:l}=t,{gridY:a,gridX:d,maxX:h,modelRows:u,floatingTopHeight:m,floatingBottomHeight:g,floatingRows:p,rowFooterWidth:C,height:f,horizontalBarHeight:b,verticalBarWidth:w,allRowHeights:S,allRowYs:T,width:y}=n;if(C<=0||p.length===0)return;const{cellHorizontalPadding:E,floatingGridRowColor:R,floatingRowBackgroundColors:x,headerColor:D,rowHoverBackgroundColor:M}=l;e.translate(d,a),e.beginPath();const O=Math.min(h,y-C-w-d);e.fillStyle=x,m>0&&e.rect(O,0,C,m),g>0&&e.rect(O,f-a-b-g,C,g),e.fill();const H=i!=null&&o!=null&&i>=d&&i<=h+C?_.getRowAtY(o,n):null;if(M!=null&&H!==null&&p.includes(H)){e.fillStyle=M;const V=T.get(H),U=S.get(H);N(V),N(U),e.fillRect(O,V,C,U)}if(e.beginPath(),R!=null&&(e.strokeStyle=R),m>0&&(e.moveTo(O+.5,.5),e.lineTo(O+.5,m-.5)),g>0){const V=f-a-b-g;e.moveTo(O-.5,V+.5),e.lineTo(O-.5,V+g-.5)}e.stroke(),e.fillStyle=D,e.textAlign="left";const L=O+E;for(let V=0;V<p.length;V+=1){const U=p[V],j=S.get(U),P=T.get(U),Q=u.get(U);if(P!=null&&j!=null&&Q!=null){const $=P+j*.5;e.fillText(s.textForRowFooter(Q),L,$)}}e.translate(-d,-a)}getExpandButtonPosition({mouseX:e,mouseY:t,metrics:n,theme:s},i){const o={left:null,top:null,width:null,height:null};if(e==null||t==null||i==null||!n)return o;const{rowHeight:l,left:a,top:d}=_.getCellInfoFromXY(e,t,n);N(a),N(l),N(d);const{cellHorizontalPadding:h}=s,u=nc+2*h,m=Math.max(a+nc*i,n.gridX),g=n.gridY+d;return{left:m,top:g,width:u,height:l}}}const tT=yl,nT="12px Fira Sans, sans-serif",sT="#f0f0ee",iT="#1a171a",re={"grid-bg":"#211f22",font:nT,white:sT,black:iT,"header-bg":"#2d2a2e","header-color":"#f0f0ee","header-height":"30px","header-separator-color":"#211f22","header-separator-hover-color":"#929192","header-hidden-separator-hover-color":"#4878ea","header-sort-bar-color":"#aa9af4","header-reverse-bar-color":"#548d29","header-bar-casing-color":"#211f22","header-font":"600 12px Fira Sans, sans-serif","row-height":"19px","row-background-colors":"#373438 #2d2a2e","selection-color":"rgba(118, 217, 228, 0.09)","selection-outline-color":"#76d9e4","selection-outline-casing-color":"#211f22","row-hover-bg":"#4b494c","selected-row-hover-bg":"rgba(118, 217, 228, 0.25)","scroll-bar-active-selection-tick-color":"rgba(118, 217, 228, 0.5)","scroll-bar-bg":"#322f33","scroll-bar-hover-bg":"#373438","scroll-bar-casing-color":"#555356","scroll-bar-corner-color":"#322f33","scroll-bar-color":"#5b5a5c","scroll-bar-hover-color":"#929192","scroll-bar-active-color":"#c0bfbf","text-color":"#f0f0ee","hyperlink-color":"#4878ea","positive-number-color":"#9edc6f","negative-number-color":"#f95d84","zero-number-color":"#fcd65b","date-color":"#fcd65b","pending-text-color":"#fde38d","error-text-color":"#f95d84","null-string-color":"#929192","filter-bar-active-bg":"#425175","filter-bar-active-color":"#4878ea","filter-bar-expanded-bg":"#373438","filter-bar-expanded-active-bg":"#313849","filter-bar-expanded-active-cell-bg":"#374d80","filter-bar-separator-color":"#929192","filter-bar-error-color":"#f95d84","filter-icon-color":"#4878ea","scrim-color":"#211f22","context-menu-sort-icon-color":"#aa9af4","context-menu-reverse-icon-color":"#548d29","linker-column-hover-bg":"rgba(118, 217, 228, 0.09)","tree-line-color":"#5b5a5c","tree-marker-color":"#c0bfbf","tree-marker-hover-color":"#fcfcfa","grouped-column-divider-color":"#1a171a","floating-grid-row-color":"#555356","floating-row-background-colors":"#403e41","floating-divider-inner-color":"#403e41","floating-divider-outer-color":"#211f22","overflow-button-color":"#c0bfbf","overflow-button-hover-color":"#fcfcfa","zero-line-color":"#5b5a5c","positive-bar-color":"#9edc6f","negative-bar-color":"#f95d84"},oT=Object.freeze({backgroundColor:re["grid-bg"],white:re.white,black:re.black,font:re.font,headerBackgroundColor:re["header-bg"],headerColor:re["header-color"],headerSeparatorColor:re["header-separator-color"],headerSeparatorHoverColor:re["header-separator-hover-color"],headerHiddenSeparatorHoverColor:re["header-hidden-separator-hover-color"],headerSortBarColor:re["header-sort-bar-color"],headerReverseBarColor:re["header-reverse-bar-color"],headerBarCasingColor:re["header-bar-casing-color"],headerFont:re["header-font"],rowBackgroundColors:re["row-background-colors"],rowHoverBackgroundColor:re["row-hover-bg"],selectionColor:re["selection-color"],selectionOutlineColor:re["selection-outline-color"],selectionOutlineCasingColor:re["selection-outline-casing-color"],selectedRowHoverBackgroundColor:re["selected-row-hover-bg"],scrollBarBackgroundColor:re["scroll-bar-bg"],scrollBarHoverBackgroundColor:re["scroll-bar-hover-bg"],scrollBarCasingColor:re["scroll-bar-casing-color"],scrollBarCornerColor:re["scroll-bar-corner-color"],scrollBarColor:re["scroll-bar-color"],scrollBarHoverColor:re["scroll-bar-hover-color"],scrollBarActiveColor:re["scroll-bar-active-color"],scrollBarSelectionTickColor:re["selected-row-hover-bg"],scrollBarActiveSelectionTickColor:re["scroll-bar-active-selection-tick-color"],textColor:re["text-color"],hyperlinkColor:re["hyperlink-color"],positiveNumberColor:re["positive-number-color"],negativeNumberColor:re["negative-number-color"],zeroNumberColor:re["zero-number-color"],dateColor:re["date-color"],pendingTextColor:re["pending-text-color"],errorTextColor:re["error-text-color"],nullStringColor:re["null-string-color"],filterBarActiveBackgroundColor:re["filter-bar-active-bg"],filterBarExpandedBackgroundColor:re["filter-bar-expanded-bg"],filterBarExpandedActiveBackgroundColor:re["filter-bar-expanded-active-bg"],filterBarExpandedActiveCellBackgroundColor:re["filter-bar-expanded-active-cell-bg"],filterBarSeparatorColor:re["filter-bar-separator-color"],filterBarActiveColor:re["filter-bar-active-color"],filterBarErrorColor:re["filter-bar-error-color"],filterIconColor:re["filter-icon-color"],scrimColor:re["scrim-color"],contextMenuSortIconColor:re["context-menu-sort-icon-color"],contextMenuReverseIconColor:re["context-menu-reverse-icon-color"],allowRowResize:!1,autoSelectRow:!0,gridColumnColor:null,gridRowColor:null,groupedColumnDividerColor:re["grouped-column-divider-color"],columnHoverBackgroundColor:null,headerHorizontalPadding:12,scrollBarSize:13,scrollBarHoverSize:16,minScrollHandleSize:24,rowHeight:parseInt(re["row-height"],10)||19,columnWidth:100,rowHeaderWidth:0,rowFooterWidth:60,columnHeaderHeight:parseInt(re["header-height"],10)||30,filterBarHeight:30,filterBarCollapsedHeight:5,sortHeaderBarHeight:2,reverseHeaderBarHeight:4,filterBarHorizontalPadding:4,scrimBlurSize:25,minScrimTransitionTime:150,maxScrimTransitionTime:350,scrollSnapToRow:!0,linkerColumnHoverBackgroundColor:re["linker-column-hover-bg"],treeLineColor:re["tree-line-color"],treeMarkerColor:re["tree-marker-color"],treeMarkerHoverColor:re["tree-marker-hover-color"],floatingGridColumnColor:null,floatingGridRowColor:re["floating-grid-row-color"],floatingRowBackgroundColors:re["floating-row-background-colors"],floatingDividerInnerColor:re["floating-divider-inner-color"],floatingDividerOuterColor:re["floating-divider-outer-color"],overflowButtonColor:re["overflow-button-color"],overflowButtonHoverColor:re["overflow-button-hover-color"],zeroLineColor:re["zero-line-color"],positiveBarColor:re["positive-bar-color"],negativeBarColor:re["negative-bar-color"]}),sc=oT;const Ra=ne.module("ColumnStatistics"),lT={SIZE:"Number of Rows"};class Rl extends v.Component{static AUTO_GENERATE_LIMIT=1e5;static getStatsLabel(e){return lT[e]??e.split(" ").map(t=>t[0].toUpperCase()+t.substr(1).toLowerCase()).join(" ")}constructor(e){super(e),this.handleError=this.handleError.bind(this),this.handleGenerateStatistics=this.handleGenerateStatistics.bind(this),this.handleStatistics=this.handleStatistics.bind(this),this.cancelablePromise=null,this.state={error:null,loading:!1,statistics:null,numRows:0}}componentDidMount(){this.maybeGenerateStatistics()}componentWillUnmount(){this.cancelablePromise&&this.cancelablePromise.cancel()}cancelablePromise;maybeGenerateStatistics(){const{model:e}=this.props,t=e.rowCount-e.pendingRowCount;this.setState({numRows:t}),e.isColumnStatisticsAvailable?t<Rl.AUTO_GENERATE_LIMIT&&this.handleGenerateStatistics():this.setState({loading:!1})}handleGenerateStatistics(){this.setState({loading:!0});const{column:e,model:t}=this.props;this.cancelablePromise=ye.makeCancelable(t.columnStatistics(e)),this.cancelablePromise.then(this.handleStatistics).catch(this.handleError)}handleStatistics(e){Ra.debug("Received statistics",e);const{model:t,onStatistics:n}=this.props,s=[];e.statisticsMap.forEach((i,o)=>{s.push({operation:Rl.getStatsLabel(o),value:i,type:e.getType(o)})}),e.uniqueValues.forEach((i,o)=>{s.push({operation:o,className:"column-statistics-unique-value",value:i,type:"long"})}),this.setState({loading:!1,statistics:s,numRows:t.rowCount-t.pendingRowCount}),n()}handleError(e){if(e!=null&&ye.isCanceled(e)){Ra.debug("Called handleError on a cancelled promise result");return}Ra.error("Error generating statistics",e),this.setState({error:e,loading:!1,statistics:null})}render(){const{column:e,model:t}=this.props,{error:n,loading:s,statistics:i,numRows:o}=this.state,l=!s&&n==null&&i==null&&t.isColumnStatisticsAvailable,a=[],d=e.type.substring(e.type.lastIndexOf(".")+1),h=e.description===null?null:e.description;if(i!=null)for(let p=0;p<i.length;p+=1){const{operation:C,className:f,value:b,type:w}=i[p],S=w?t.displayString(b,w):t.displayString(b,e.type,e.name),T=r.jsxs(de.Fragment,{children:[r.jsx("div",{className:Y("column-statistic-operation",f),children:C}),r.jsx("div",{className:"column-statistic-value",children:S})]},C);a.push(T)}const u=je(t)&&t.hasExpandableRows?"Expanded Rows":"Number of Rows",m=t.displayString(o,"long"),g=t.getColumnIndexByName(e.name);return r.jsxs("div",{className:"column-statistics",children:[r.jsxs("div",{className:"column-statistics-title",children:[e.name,r.jsxs("span",{className:"column-statistics-type",children:[" (",d,")"]}),r.jsx(Bl,{className:"column-statistics-copy",tooltip:"Copy column name",copy:e.name})]}),h!=null&&r.jsx("div",{className:"column-statistics-description",children:h}),g!=null&&!t.isColumnMovable(g)&&r.jsxs("div",{className:"column-statistics-status",children:[r.jsx(ee,{icon:t.isColumnFrozen(g)?pg:fg,className:"mr-1"}),t.isColumnFrozen(g)?"Frozen":"Not movable"]}),r.jsxs("div",{className:"column-statistics-grid",children:[i==null&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"column-statistic-operation",children:u}),r.jsx("div",{className:"column-statistic-value",children:m})]}),a]}),l&&r.jsx(B,{kind:"ghost",className:"px-0",onClick:this.handleGenerateStatistics,children:"Generate Stats"}),n!=null&&r.jsx("div",{className:"error-message",children:`${n}`}),i&&!s&&r.jsx(B,{kind:"ghost",className:"px-0",onClick:this.handleGenerateStatistics,icon:r.jsx(ee,{icon:hr,className:"mr-1"}),children:"Refresh"}),s&&r.jsxs("div",{className:"column-statistics-loading",children:[r.jsx(In,{className:"mr-2"}),"Calculating Stats..."]})]})}}const aT=Rl;const $o=ne.module("AdvancedFilterCreatorFilterItem");class Br extends v.PureComponent{static getLabelForFilter(e,t){try{if(F.isNumberType(e)||F.isCharType(e))return fh(t);if(F.isTextType(e))return ph(t);if(F.isDateType(e))return Ch(t);if(F.isBooleanType(e))return Jf(t);throw new Error(`Unrecognized column type: ${e}`)}catch(n){return $o.warn(n),""}}constructor(e){super(e),this.handleDelete=this.handleDelete.bind(this),this.handleTypeChange=this.handleTypeChange.bind(this),this.handleValueChange=this.handleValueChange.bind(this),this.typeDropdown=null;const{value:t="",filterTypes:n,selectedType:s=n[0]}=e;this.state={selectedType:s,value:t}}componentDidMount(){this.typeDropdown?.focus()}componentDidUpdate(e){const{value:t,selectedType:n}=this.props;n!==void 0&&e.selectedType!==n&&this.setState({selectedType:n}),t!==void 0&&e.value!==t&&this.setState({value:t})}typeDropdown;handleTypeChange(e){const t=e.target.value;$o.debug2("typeChange",t),this.setState({selectedType:t});const{onChange:n}=this.props,{value:s}=this.state;s!=null&&s.length>0&&n(t,s)}handleValueChange(e){$o.debug2("valueChange");const{value:t}=e.target;this.setState({value:t});const{onChange:n}=this.props,{selectedType:s}=this.state;s!=null&&n(s,t)}handleDelete(){$o.debug("delete");const{onDelete:e}=this.props;e()}getCachedIsValid=ge((e,t,n,s)=>{try{return!n||F.makeAdvancedValueFilter(e,t,n,s)!=null}catch{return!1}});render(){const{column:e,filterTypes:t,formatter:n}=this.props,{selectedType:s,value:i}=this.state,o=!F.isBooleanType(e.type),l=[],a=this.getCachedIsValid(e,s,i,n.timeZone);for(let d=0;d<t.length;d+=1){const h=t[d],u=Br.getLabelForFilter(e.type,h),m=r.jsx("option",{value:h,children:u},h);l.push(m)}return r.jsx("div",{className:"advanced-filter-creator-filter-item",children:r.jsxs("div",{className:"form-row",children:[r.jsx("div",{className:"form-group col",children:r.jsx("select",{className:"form-control custom-select",value:s,onChange:this.handleTypeChange,ref:d=>{this.typeDropdown=d},children:l})}),o&&r.jsx("div",{className:"form-group col",children:r.jsx("div",{className:"input-group",children:r.jsx("input",{type:"text",className:Y("form-control",{error:!a}),placeholder:"Enter value",value:i,onChange:this.handleValueChange})})}),r.jsx("div",{className:"form-group col-1 px-0",children:r.jsx(B,{kind:"ghost",className:"w-100 h-100 p-0 m-0",onClick:this.handleDelete,icon:Gt,tooltip:"Remove Filter"})})]})})}}const rT=Br,ic=ne.module("AdvancedFilterCreatorSelectValueList");class xl extends v.PureComponent{static defaultProps={invertSelection:!0,selectedValues:[],onChange:()=>{}};static indexOf(e,t){for(let n=0;n<t.length;n+=1){const s=t[n];if(s===e||s!=null&&s.valueOf!=null&&e!=null&&e.valueOf!=null&&s.valueOf()===e.valueOf())return n}return-1}constructor(e){super(e),this.handleSelect=this.handleSelect.bind(this),this.handleViewportChange=this.handleViewportChange.bind(this),this.handleSelectionUpdate=this.handleSelectionUpdate.bind(this),this.handleTableUpdate=this.handleTableUpdate.bind(this),this.list=null;const{selectedValues:t}=this.props;this.state={itemCount:0,items:[],offset:0,selectedValues:t,isLoading:!0}}componentDidMount(){const{table:e}=this.props;e&&this.startListening(e)}componentDidUpdate(e){const{filters:t,invertSelection:n,selectedValues:s,table:i}=this.props;e.table!==i&&(e.table&&this.stopListening(e.table),i&&this.startListening(i),this.resetViewport()),e.invertSelection!==n&&this.setState({selectedValues:[]},this.handleSelectionUpdate),e.selectedValues!==s&&this.setState({selectedValues:s},this.handleSelectionUpdate),e.filters!==t&&(i?.applyFilter(t),this.resetViewport())}componentWillUnmount(){const{table:e}=this.props;e&&this.stopListening(e)}list;handleSelect(e,t){const{invertSelection:n}=this.props;let{selectedValues:s}=this.state;s=[...s];const i=xl.indexOf(t,s);i>=0?s.splice(i,1):s.push(t);let o=i<0;n&&(o=!o);const{offset:l}=this.state;let{items:a}=this.state;a=[...a];const d=e-l;d>=0&&d<a.length&&(a[d].isSelected=o),this.setState({items:a,selectedValues:s});const{onChange:h}=this.props;h(s,n)}handleViewportChange(e,t){this.updateViewport(e,t)}handleSelectionUpdate(){this.updateItemSelection()}handleTableUpdate(e){const{table:t,formatter:n}=this.props;if(!t)return;const s=e.detail,{offset:i}=s,o=[],l=t.columns[0];for(let d=0;d<s.rows.length;d+=1){const u=s.rows[d].get(l),m=n.getFormattedString(u,l.type,l.name),g=this.isValueSelected(u);o.push({displayValue:m,value:u,isSelected:g})}ic.debug2("Received table update:",i,o.length);const a=t.size;this.setState({itemCount:a,items:o,offset:i,isLoading:!1})}isValueSelected(e){const{invertSelection:t}=this.props,{selectedValues:n}=this.state,s=xl.indexOf(e,n);return t?s<0:s>=0}startListening(e){e.addEventListener(I.Table.EVENT_UPDATED,this.handleTableUpdate)}stopListening(e){e.removeEventListener(I.Table.EVENT_UPDATED,this.handleTableUpdate)}resetViewport(){this.list&&this.list.topRow!=null&&this.list.bottomRow!=null&&this.updateViewport(this.list.topRow,this.list.bottomRow,!0)}updateItemSelection(){let{items:e}=this.state;e=[...e];for(let t=0;t<e.length;t+=1){const n=e[t],{value:s}=n;n.isSelected=this.isValueSelected(s)}this.setState({items:e})}updateViewport(e,t,n=!1){const{table:s}=this.props;if(s==null)return;n&&this.setState({isLoading:!0});const i=t-e+1,o=Math.max(0,e-i*3),l=Math.max(o,t+i*3);ic.debug2("Setting viewport",o,",",l),s.setViewport(o,l)}render(){const{offset:e,isLoading:t,items:n,itemCount:s}=this.state;return r.jsxs("div",{className:"select-value-list-wrapper",children:[r.jsx(Om,{itemCount:s,items:n,offset:e,onSelect:this.handleSelect,onViewportChange:this.handleViewportChange,ref:i=>{this.list=i}}),r.jsx(Wt,{in:t,timeout:250,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:"loading-list",children:r.jsx(In,{className:"loading-spinner-large"})})})]})}}const dT=xl;class Ur extends v.PureComponent{static searchDebounceTime=250;static defaultProps={invertSelection:!0,selectedValues:[],onChange:()=>{},showSearch:!0};constructor(e){super(e),this.handleSelectAllClick=this.handleSelectAllClick.bind(this),this.handleClearAllClick=this.handleClearAllClick.bind(this),this.handleListChange=this.handleListChange.bind(this),this.handleSearchChange=this.handleSearchChange.bind(this),this.handleUpdateFilterTimeout=this.handleUpdateFilterTimeout.bind(this);const{invertSelection:t,selectedValues:n}=e;this.state={filters:[],invertSelection:t,selectedValues:n,searchText:""}}componentDidMount(){this.initSearchTable()}componentDidUpdate(e,t){const{invertSelection:n,selectedValues:s,table:i}=this.props;e.table!==i&&this.initSearchTable(),e.invertSelection!==n&&this.setState({invertSelection:n}),e.selectedValues!==s&&this.setState({selectedValues:s});const{table:o,searchText:l}=this.state;o!==t.table&&(t.table!=null&&t.table.close(),o!=null&&this.startUpdateFilterTimer()),l!==t.searchText&&this.startUpdateFilterTimer()}componentWillUnmount(){const{table:e}=this.state;e?.close(),this.searchTablePromise=void 0,this.stopUpdateFilterTimer()}searchTablePromise;updateFilterTimer;getColumnName(){const{table:e}=this.props;return e!=null?e.columns[0].name:""}getDisplayedValuesCount(){const{invertSelection:e,selectedValues:t,table:n}=this.state;return n==null?null:e?n.totalSize-t.length:t.length}getDisplayedValueText(){const e=this.getDisplayedValuesCount(),{table:t}=this.state,{formatter:n}=this.props;if(e!=null&&t!=null){const s=n.getFormattedString(e,"long"),i=n.getFormattedString(t.totalSize,"long");let o="";return e<1e6&&(o="Displaying "),`${o}${s} of ${i}`}return null}initSearchTable(){const{table:e}=this.props;if(e==null)return;const t=e.copy();this.searchTablePromise=t,this.searchTablePromise.then(n=>{this.searchTablePromise===t?(this.setState({table:n}),this.searchTablePromise=void 0):n.close()})}handleListChange(e,t){this.setState({selectedValues:e,invertSelection:t});const{onChange:n}=this.props;n(e,t)}handleSearchChange(e){const t=e.target.value;this.setState({searchText:t})}handleSelectAllClick(){this.resetSelection(!0)}handleClearAllClick(){this.resetSelection(!1)}handleUpdateFilterTimeout(){this.updateFilterTimer=void 0,this.updateTableFilter()}resetSelection(e){const t=[];this.setState({invertSelection:e,selectedValues:t});const{onChange:n}=this.props;n(t,e)}startUpdateFilterTimer(){this.stopUpdateFilterTimer(),this.updateFilterTimer=setTimeout(this.handleUpdateFilterTimeout,Ur.searchDebounceTime)}stopUpdateFilterTimer(){this.updateFilterTimer!=null&&(clearTimeout(this.updateFilterTimer),this.updateFilterTimer=void 0)}updateTableFilter(){const{table:e,searchText:t}=this.state,{timeZone:n}=this.props,s=e?.columns[0],i=[];if(s==null)return;let o;if(t.length>0){let l=null;F.isCharType(s.type)?l=F.makeQuickFilter(s,t):F.isTextType(s.type)?l=F.makeQuickFilter(s,`~${t}`,n):l=F.makeQuickFilter(s,`>=${t}`,n),l!=null?i.push(l):o="Invalid search text"}this.setState({filters:i,error:o})}render(){const{error:e,filters:t,invertSelection:n,selectedValues:s,searchText:i,table:o}=this.state,{formatter:l,showSearch:a}=this.props,d=this.getColumnName(),h=this.getDisplayedValueText(),u=d?`Find ${d}...`:"";return r.jsxs("div",{className:"advanced-filter-creator-select-value",children:[r.jsxs("div",{className:a?"form-group":"",children:[r.jsx("label",{htmlFor:"advanced-filter-creator-select-value-input",children:"Select Values"}),a&&r.jsx("input",{type:"text",className:Y("form-control",{"is-invalid":e!=null}),id:"advanced-filter-creator-select-value-input",placeholder:u,value:i,onChange:this.handleSearchChange})]}),r.jsx(dT,{table:o,filters:t,invertSelection:n,selectedValues:s,formatter:l,onChange:this.handleListChange}),r.jsxs("div",{className:"advanced-filter-creator-select-meta-row",children:[r.jsxs("div",{children:[r.jsx(B,{kind:"ghost",onClick:this.handleSelectAllClick,children:"Select All"}),r.jsx(B,{kind:"ghost",onClick:this.handleClearAllClick,children:"Clear"})]}),r.jsx(Wt,{in:h!=null,timeout:250,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:"row-count-info",children:h})})]})]})}}const cT=Ur;const Bi=ne.module("AdvancedFilterCreator");class us extends v.PureComponent{static debounceFilterUpdate=250;static defaultProps={options:{filterItems:null,filterOperators:null,invertSelection:!0,selectedValues:[]},sortDirection:null};static makeFilterItem(){return{key:qe()}}constructor(e){super(e),this.handleAddAnd=this.handleAddAnd.bind(this),this.handleAddOr=this.handleAddOr.bind(this),this.handleChangeFilterOperator=this.handleChangeFilterOperator.bind(this),this.handleDone=this.handleDone.bind(this),this.handleFilterChange=this.handleFilterChange.bind(this),this.handleFilterDelete=this.handleFilterDelete.bind(this),this.handleSelectValueChange=this.handleSelectValueChange.bind(this),this.handleReset=this.handleReset.bind(this),this.handleSortDown=this.handleSortDown.bind(this),this.handleSortUp=this.handleSortUp.bind(this),this.handleSubmit=this.handleSubmit.bind(this),this.handleFocusTrapStart=this.handleFocusTrapStart.bind(this),this.handleFocusTrapEnd=this.handleFocusTrapEnd.bind(this),this.handleUpdateTimeout=this.handleUpdateTimeout.bind(this),this.focusTrapContainer=de.createRef();const{options:t}=e;let{filterOperators:n,invertSelection:s,selectedValues:i}=t;const o=t.filterItems?.map(({selectedType:l,value:a})=>({selectedType:l,value:a,key:qe()}))??[];o.length===0&&o.push(us.makeFilterItem()),n==null&&(n=[]),s==null&&(s=!0),i==null&&(i=[]),this.state={filterItems:o,filterOperators:n,invertSelection:s,selectedValues:i,valuesTableError:null,valuesTable:void 0}}componentDidMount(){this.initValuesTable()}componentWillUnmount(){this.debounceTimeout!=null&&(clearTimeout(this.debounceTimeout),this.sendUpdate()),this.valuesTablePromise!=null&&this.valuesTablePromise.cancel()}focusTrapContainer;debounceTimeout;valuesTablePromise;getFilterChangeHandler(e){return this.handleFilterChange.bind(this,e)}getFilterDeleteHandler(e){return this.handleFilterDelete.bind(this,e)}getFilterTypes=ge(e=>F.getFilterTypes(e));initValuesTable(){const{model:e,column:t}=this.props;if(!e.isValuesTableAvailable){Bi.debug("No values table for this model, just ignore");return}this.valuesTablePromise=F.makeCancelableTablePromise(e.valuesTable(t)),this.valuesTablePromise.then(n=>{const s=n.columns[0].sort().asc();n.applySort([s]),this.setState({valuesTable:n})}).catch(n=>{ye.isCanceled(n)||(Bi.error("Unable to open values table",n),this.setState({valuesTableError:n}))})}handleFocusTrapEnd(){(this.focusTrapContainer?.current?.querySelector("button,select,input,textarea")).focus()}handleFocusTrapStart(){const e=this.focusTrapContainer?.current?.querySelectorAll("button,select,input,textarea");e&&e.length>0&&e[e.length-1].focus()}handleAddAnd(){let{filterItems:e,filterOperators:t}=this.state;e=e.concat(us.makeFilterItem()),t=t.concat(Bn.and),this.setState({filterItems:e,filterOperators:t})}handleAddOr(){let{filterItems:e,filterOperators:t}=this.state;e=e.concat(us.makeFilterItem()),t=t.concat(Bn.or),this.setState({filterItems:e,filterOperators:t})}handleChangeFilterOperator(e,t){let{filterOperators:n}=this.state;n=[...n],Am(t),n[e]=t,this.setState({filterOperators:n}),this.startUpdateTimer()}handleFilterChange(e,t,n){let{filterItems:s}=this.state;s=[...s];const{key:i}=s[e];s[e]={key:i,selectedType:t,value:n},this.setState({filterItems:s}),this.startUpdateTimer()}handleFilterDelete(e){let{filterItems:t,filterOperators:n}=this.state;t=[...t],n=[...n],e<t.length&&t.splice(e,1),e<n.length?n.splice(e,1):e===n.length&&n.splice(n.length-1,1),t.length===0&&t.push(us.makeFilterItem()),this.setState({filterItems:t,filterOperators:n}),this.startUpdateTimer()}handleSelectValueChange(e,t){this.setState({selectedValues:e,invertSelection:t}),this.startUpdateTimer()}handleReset(){Bi.debug("Resetting Advanced Filter"),this.setState({filterItems:[us.makeFilterItem()],filterOperators:[],selectedValues:[],invertSelection:!0}),this.startUpdateTimer()}handleSortDown(e){const t=Ts.isModifierKeyDown(e);this.sortTable(F.sortDirection.descending,t)}handleSortUp(e){const t=Ts.isModifierKeyDown(e);this.sortTable(F.sortDirection.ascending,t)}handleSubmit(e){Bi.debug("Submitting Advanced Filter"),this.stopUpdateTimer(),this.sendUpdate(),e.preventDefault()}handleDone(e){Bi.debug("Submitting and Closing Advanced Filter"),this.stopUpdateTimer(),this.sendUpdate();const{onDone:t}=this.props;t(),e.preventDefault()}handleUpdateTimeout(){this.debounceTimeout=void 0,this.sendUpdate()}shouldShowAddFilter(){const{filterItems:e}=this.state;if(e.length===0)return!1;const t=e[e.length-1],{selectedType:n,value:s}=t;return n!=null&&n.length>0&&s!=null&&s.length>0}sortTable(e,t=!1){const{column:n,onSortChange:s}=this.props;s(n,e,t)}startUpdateTimer(){this.stopUpdateTimer(),this.debounceTimeout=setTimeout(this.handleUpdateTimeout,us.debounceFilterUpdate)}stopUpdateTimer(){this.debounceTimeout!==void 0&&(clearTimeout(this.debounceTimeout),this.debounceTimeout=void 0)}sendUpdate(){const{filterItems:e,filterOperators:t,invertSelection:n,selectedValues:s}=this.state,{column:i,onFilterChange:o,model:l}=this.props,{formatter:a}=l,d=e.filter(({selectedType:g,value:p})=>g!=null&&p!=null&&p!==""),h=t.filter((g,p)=>g!=null&&e[p].selectedType!=null&&e[p].value!=null&&e[p].value!=="").slice(0,d.length-1),u={filterItems:d,filterOperators:h,invertSelection:n,selectedValues:s},m=F.makeAdvancedFilter(i,u,a.timeZone);o(i,m,u)}render(){const{column:e,model:t,sortDirection:n,formatter:s}=this.props,{filterItems:i,filterOperators:o,invertSelection:l,selectedValues:a,valuesTable:d,valuesTableError:h}=this.state,{isValuesTableAvailable:u}=t,m=F.isBooleanType(e.type),g=F.isDateType(e.type),p=this.getFilterTypes(e.type),C=e.type.substring(e.type.lastIndexOf(".")+1),f=[];if(!m&&p.length)for(let S=0;S<i.length;S+=1){const T=i[S],{key:y,selectedType:E,value:R}=T,x=r.jsx(rT,{column:e,filterTypes:p,onChange:this.getFilterChangeHandler(S),onDelete:this.getFilterDeleteHandler(S),selectedType:E,value:R,formatter:s},y);if(f.push(x),S<o.length){const M=o[S]===Bn.and,O=r.jsxs("div",{className:"form-row justify-content-end advanced-filter-creator-filter-operator",children:[r.jsx(B,{kind:"ghost",className:Y("filter-operator",{active:M}),onClick:()=>this.handleChangeFilterOperator(S,Bn.and),children:"AND"}),r.jsx(B,{kind:"ghost",className:Y("filter-operator",{active:!M}),onClick:()=>this.handleChangeFilterOperator(S,Bn.or),children:"OR"})]},`filterOperator${y}`);f.push(O)}}const b=this.shouldShowAddFilter(),w=r.jsxs("div",{className:Y("form-row justify-content-end add-filter-item",{hidden:!b}),children:[r.jsx("span",{className:"text-muted",children:r.jsx(ee,{icon:Es})}),r.jsx(B,{kind:"ghost",className:"btn-filter-item",onClick:this.handleAddAnd,disabled:!b,tooltip:"Add filter with AND",children:"AND"}),r.jsx(B,{kind:"ghost",className:"btn-filter-item",onClick:this.handleAddOr,disabled:!b,tooltip:"Add filter with OR",children:"OR"})]},"addFilterItem");return f.push(w),r.jsxs("div",{className:"advanced-filter-creator",role:"presentation",children:[r.jsx("div",{tabIndex:0,onFocus:this.handleFocusTrapStart}),r.jsxs("form",{onSubmit:this.handleSubmit,ref:this.focusTrapContainer,children:[r.jsxs("div",{className:"title-bar",children:[r.jsx("h6",{className:"advanced-filter-title",children:"Advanced Filters"}),r.jsxs("div",{className:"advanced-filter-menu-buttons",children:[r.jsx(B,{kind:"ghost",className:Y("sort-operator",{active:n===F.sortDirection.descending}),onClick:this.handleSortDown,icon:Sd,tooltip:`Sort ${e.name} Descending`}),r.jsx(B,{kind:"ghost",className:Y("sort-operator",{active:n===F.sortDirection.ascending}),onClick:this.handleSortUp,icon:r.jsx(ee,{icon:Sd,rotation:180}),tooltip:`Sort ${e.name} Ascending`})]})]}),r.jsx("hr",{}),r.jsxs("div",{className:"advanced-filter-column-name",children:[e.name," ",r.jsxs("span",{className:"column-type",children:["(",C,")"]})]}),f,u&&h==null&&r.jsxs(r.Fragment,{children:[!m&&r.jsx("hr",{}),r.jsx("div",{className:"form-group",children:r.jsx(cT,{table:d,onChange:this.handleSelectValueChange,invertSelection:l,selectedValues:a,formatter:s,showSearch:!g,timeZone:s.timeZone})})]}),r.jsxs("div",{className:"form-row justify-content-end",children:[r.jsx(B,{kind:"secondary",className:"mr-2",onClick:this.handleReset,children:"Reset"}),r.jsx(B,{kind:"primary",onClick:this.handleDone,children:"Done"})]})]}),r.jsx("div",{tabIndex:0,onFocus:this.handleFocusTrapEnd})]})}}const hT=us;const oc=ne.module("Aggregations");function uT({isRollup:c,settings:e,onChange:t,onEdit:n}){const{aggregations:s,showOnTop:i}=e,o=v.useMemo(()=>Qw.filter(D=>!s.some(M=>M.operation===D)),[s]),[l,a]=v.useState(o[0]),[d,h]=v.useState([]),u=v.useCallback(D=>{t({...e,...D})},[t,e]),m=v.useCallback(D=>{u({aggregations:D})},[u]),g=v.useCallback(D=>{u({showOnTop:D})},[u]),p=v.useCallback(()=>{oc.debug("handleDragStart"),hn.startDragging()},[]),C=v.useCallback(({destination:D,source:M})=>{if(oc.debug("handleDragEnd",D,M),hn.stopDragging(),D===null)return;let O=D.index;M.index<D.index&&(O+=1);const H=[...s],L=hn.reorder(H,d,H,O),V=hn.adjustDestinationIndex(O,d),U=[[V,V+L.length-1]];m(H),h(U)},[m,s,d,h]),f=v.useCallback(D=>{a(D)},[a]),b=v.useCallback(()=>{m([...s,{operation:l,selected:[],invert:!0}])},[s,l,m]),w=v.useCallback(D=>{m(s.filter((M,O)=>O!==D))},[s,m]),S=v.useCallback(D=>{h(D)},[h]),T=v.useCallback(D=>{const M=s[D];Cs.isRollupOperation(M.operation)||n(M)},[s,n]),y=v.useCallback(D=>{g(D.target.value==="true")},[g]);v.useEffect(function(){o.length>0&&!o.includes(l)&&a(o[0])},[o,l]);const E=v.useCallback(({item:D,itemIndex:M,isClone:O=!1,selectedCount:H})=>{const L=D.operation,V=O?`${H}`:void 0,U=O?"item-list-item-clone":void 0,j=Cs.isRollupOperation(D.operation),P=!O&&!j;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:Y("item-list-item-content","draggable-item-list-item-content",U),children:[r.jsxs("span",{className:"title",children:[L,!c&&j&&r.jsxs("span",{className:"small text-warning",children:[r.jsx(ee,{icon:eh})," Requires rollup"]})]}),rn.renderBadge({text:V}),rn.renderHandle()]}),!O&&r.jsxs(r.Fragment,{children:[r.jsx(B,{kind:"ghost",className:"btn-edit",icon:go,tooltip:"Edit Columns",onClick:()=>n(D),disabled:!P}),r.jsx(B,{kind:"ghost",className:"btn-delete",icon:Gt,tooltip:"Delete Aggregation",onClick:()=>w(M)})]})]})},[w,n,c]),R=o.length>0,x=s.length>0;return r.jsxs("div",{className:"aggregations",children:[R&&r.jsxs("div",{className:"form-inline",children:[r.jsx(_m,{onChange:f,value:l,children:o.map(D=>r.jsx(Pm,{value:D,children:D},D))}),r.jsxs("button",{type:"button",className:"btn btn-link btn-add",onClick:b,children:[r.jsx(ee,{icon:Es}),"Add Aggregation"]})]}),R&&x&&r.jsx("hr",{}),x&&r.jsxs(r.Fragment,{children:[!c&&r.jsxs("div",{className:"form-inline",children:[r.jsx("label",{children:"Placement: "}),r.jsxs(Ul,{onChange:y,value:`${i}`,children:[r.jsx(Wn,{value:"true",children:"Top"}),r.jsx(Wn,{value:"false",children:"Bottom"})]})]}),r.jsx(Pl,{onDragStart:p,onDragEnd:C,children:r.jsx(rn,{className:"selected-aggregations",itemCount:s.length,items:s,renderItem:E,offset:0,onSelectionChange:S,onSelect:T,selectedRanges:d,isMultiSelect:!0})})]})]})}const mT=30;function gT({aggregation:c,columns:e,onChange:t}){const[n,s]=v.useState(-1),[i,o]=v.useState(-1),[l,a]=v.useState(0),{invert:d,selected:h}=c,u=v.useRef(null),m=v.useCallback(y=>h.includes(y)?!d:d,[d,h]),g=v.useMemo(()=>{let y=jr(e,c.operation);return l!==0&&(y=F.sortColumns(y,l===1)),y},[e,c.operation,l]),p=v.useMemo(()=>n>=0?g.slice(n,i+1).map(y=>({value:y.name,displayValue:y.name,isSelected:m(y.name)})):[],[g,m,i,n]),C=v.useCallback(y=>{const{name:E}=g[y],R=h.indexOf(E);let x=[...h],D=d;R>=0?x.splice(R,1):(x.push(E),x.length===g.length&&(x=[],D=!d)),t({...c,selected:x,invert:D})},[c,d,g,h,t]),f=v.useCallback(()=>{a(0),t({...c,selected:[],invert:!0})},[c,t]),b=v.useCallback((y,E)=>{s(y),o(E)},[s,o]),w=v.useCallback(()=>{h.length===0?t({...c,invert:!d}):t({...c,selected:[],invert:!0})},[c,d,t,h]),S=h.length===0?d:null,T=h.length!==0||!d||l!==0;return r.jsxs("div",{role:"menu",className:"aggregation-edit",children:[r.jsx("div",{className:"top-menu",children:r.jsxs("div",{className:"form-inline",children:[r.jsx(nn,{checked:S,onChange:w,children:"Toggle All"}),r.jsx("div",{className:"spacer"}),r.jsx(Wt,{in:T,timeout:Je.transitionSlowMs,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx(B,{kind:"ghost",className:"btn-reset",onClick:f,children:"Reset"})}),r.jsx(B,{kind:"ghost",className:Y({active:l===1}),icon:ur,tooltip:"Sort ascending",onClick:()=>a(1)}),r.jsx(B,{kind:"ghost",className:Y({active:l===2}),icon:mr,tooltip:"Sort descending",onClick:()=>a(2)})]})}),r.jsx("div",{className:"aggregation-edit-item-list",children:r.jsx(yi,{itemCount:g.length,items:p,offset:n,renderItem:({item:y})=>r.jsx(nn,{checked:m(y.value),children:y.displayValue}),onSelect:C,onViewportChange:b,rowHeight:mT,focusSelector:"input",ref:u})})]})}function pT(c){return r.jsx("svg",{width:48,height:48,xmlns:"http://www.w3.org/2000/svg",...c,children:r.jsxs("g",{fill:"none",fillRule:"evenodd",children:[r.jsx("path",{fill:"#C1C0C0",d:"M44 43v1H4v-1z"}),r.jsx("path",{fill:"#7DA4FF",d:"M8 26h4v15H8zM15 17h4v24h-4zM22 21h4v20h-4zM29 17h4v24h-4zM36 11h4v30h-4z"})]})})}function fT(c){return r.jsx("svg",{width:48,height:48,xmlns:"http://www.w3.org/2000/svg",...c,children:r.jsxs("g",{fill:"none",fillRule:"evenodd",children:[r.jsx("path",{fill:"#C1C0C0",d:"M44 43v1H4v-1z"}),r.jsx("path",{fill:"#7DA4FF",d:"M7 34h4v8H7zM12 31h4v11h-4zM17 27h4v15h-4zM22 22h4v20h-4zM27 27h4v15h-4zM32 29h4v13h-4zM37 31h4v11h-4z"})]})})}function CT(c){return r.jsx("svg",{width:48,height:48,xmlns:"http://www.w3.org/2000/svg",...c,children:r.jsxs("g",{fill:"none",fillRule:"evenodd",children:[r.jsx("path",{fill:"#C1C0C0",d:"M4 4h1v40H4zM44 43v1H5v-1z"}),r.jsx("path",{stroke:"#7DA4FF",d:"M7.984 32.44l7.982-11.378 5.273 3.739 9.952-10.838 2.826 1.894 7.45-5.802"}),r.jsx("path",{stroke:"#BECDEF",d:"M8.244 37.926L17 33.496l5 .87 10.637-10.35 10.615-1.381"})]})})}function bT(c){return r.jsx("svg",{width:48,height:48,xmlns:"http://www.w3.org/2000/svg",...c,children:r.jsxs("g",{fill:"none",fillRule:"evenodd",children:[r.jsx("path",{d:"M24 10c7.732 0 14 6.268 14 14s-6.268 14-14 14-14-6.268-14-14h14V10z",fill:"#80A6FF"}),r.jsx("path",{d:"M10 24c0-7.732 6.268-14 14-14v14H10z",fill:"#C1C0C0"})]})})}function ST(c){return r.jsx("svg",{width:48,height:48,xmlns:"http://www.w3.org/2000/svg",...c,children:r.jsxs("g",{fill:"none",fillRule:"evenodd",children:[r.jsx("path",{fill:"#C1C0C0",d:"M44 43v1H4v-1z"}),r.jsx("path",{fill:"#939293",d:"M44 34v1H4v-1zM44 25v1H4v-1zM44 16v1H4v-1z"}),r.jsx("circle",{fill:"#7DA4FF",cx:9.5,cy:37.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:16.5,cy:30.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:22.5,cy:36.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:28.5,cy:30.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:15.5,cy:38.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:23.5,cy:25.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:19.5,cy:19.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:29.5,cy:19.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:32.5,cy:26.5,r:1.5}),r.jsx("circle",{fill:"#7DA4FF",cx:36.5,cy:13.5,r:1.5})]})})}function wT(c){return r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none",xmlns:"http://www.w3.org/2000/svg",...c,children:[r.jsx("rect",{width:"48",height:"48",fill:"none"}),r.jsx("rect",{x:"26",y:"10",width:"15",height:"4",fill:"#9FDE70"}),r.jsx("rect",{x:"26",y:"22",width:"15",height:"4",fill:"#9FDE70"}),r.jsx("rect",{x:"26",y:"28",width:"15",height:"4",fill:"#FFD95C"}),r.jsx("rect",{x:"26",y:"34",width:"15",height:"4",fill:"#9FDE70"})]})}function vT(c){return r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none",xmlns:"http://www.w3.org/2000/svg",...c,children:[r.jsx("rect",{width:"48",height:"48",fill:"none"}),r.jsx("rect",{x:"4",y:"16",width:"40",height:"4",fill:"#FFD95C"}),r.jsx("rect",{x:"4",y:"10",width:"40",height:"4",fill:"#78DCE8"}),r.jsx("rect",{x:"4",y:"34",width:"40",height:"4",fill:"#78DCE8"})]})}const lc=ne.module("ChartBuilder");class ut extends v.PureComponent{static types=[I.plot.SeriesPlotStyle.LINE,I.plot.SeriesPlotStyle.BAR,I.plot.SeriesPlotStyle.SCATTER,I.plot.SeriesPlotStyle.PIE];static getTypeName(e){switch(e){case I.plot.SeriesPlotStyle.LINE:return"Line";case I.plot.SeriesPlotStyle.BAR:return"Bar";case I.plot.SeriesPlotStyle.SCATTER:return"Scatter";case I.plot.SeriesPlotStyle.PIE:return"Pie";case I.plot.SeriesPlotStyle.HISTOGRAM:return"Histogram";default:return e}}static getTypeIcon(e){switch(e){case I.plot.SeriesPlotStyle.LINE:return r.jsx(CT,{});case I.plot.SeriesPlotStyle.BAR:return r.jsx(pT,{});case I.plot.SeriesPlotStyle.SCATTER:return r.jsx(ST,{});case I.plot.SeriesPlotStyle.PIE:return r.jsx(bT,{});case I.plot.SeriesPlotStyle.HISTOGRAM:return r.jsx(fT,{});default:return null}}static getMaxSeriesCount(e){switch(e){case I.plot.SeriesPlotStyle.PIE:return 1;case I.plot.SeriesPlotStyle.HISTOGRAM:return 0;default:return 100}}static getXAxisLabel(e){switch(e){case I.plot.SeriesPlotStyle.PIE:return"Labels";case I.plot.SeriesPlotStyle.HISTOGRAM:return"Data";default:return"X-Axis"}}static getSeriesLabel(e){switch(e){case I.plot.SeriesPlotStyle.PIE:return"Values";default:return"Series"}}static makeSeriesItem(e){return{id:qe.generate(),value:e}}static makeDefaultSeriesItems(e,t){if(ut.getMaxSeriesCount(e)===0||t==null||t.length===0)return[];const s=t.length>1?t[1].name:t[0].name;return[ut.makeSeriesItem(s)]}static getDefaultXAxis(e,t){return t!=null&&t.length>0?t[0].name:null}constructor(e){super(e),this.handleAddSeries=this.handleAddSeries.bind(this),this.handleLinkStateChange=this.handleLinkStateChange.bind(this),this.handleReset=this.handleReset.bind(this),this.handleSeriesChange=this.handleSeriesChange.bind(this),this.handleSeriesDeleteClick=this.handleSeriesDeleteClick.bind(this),this.handleSubmit=this.handleSubmit.bind(this),this.handleTypeClick=this.handleTypeClick.bind(this),this.handleXAxisChange=this.handleXAxisChange.bind(this),this.sendChange=this.sendChange.bind(this);const{model:t}=e,{columns:n}=t,s=ut.types[0],i=ut.getDefaultXAxis(s,n),o=ut.makeDefaultSeriesItems(s,n);this.state={type:s,seriesItems:o,xAxis:i,isLinked:!0}}handleAddSeries(){this.setState(e=>{const{seriesItems:t}=e,n=[...t],{model:s}=this.props,{columns:i}=s;return n.push({id:qe.generate(),value:i[0].name}),{seriesItems:n}},this.sendChange)}handleLinkStateChange(e){this.setState({isLinked:e.target.value==="true"},this.sendChange)}handleReset(){const{model:e}=this.props,{columns:t}=e,n=ut.types[0],s=ut.getDefaultXAxis(n,t),i=ut.makeDefaultSeriesItems(n,t),o=!0;this.setState({type:n,seriesItems:i,xAxis:s,isLinked:o},this.sendChange)}handleSeriesChange(e){const{value:t}=e.target,n=e.target.getAttribute("data-index"),s=parseInt(n,10);this.setState(i=>{let{seriesItems:o}=i;return o=[...o],o[s].value=t,{seriesItems:o}},this.sendChange)}handleSeriesDeleteClick(e){const n=e.target.getAttribute("data-index"),s=parseInt(n,10);this.setState(i=>{const{seriesItems:o}=i,l=[...o];return l.splice(s,1),{seriesItems:l}},this.sendChange)}handleSubmit(e){e.preventDefault();const{onSubmit:t}=this.props,{type:n,seriesItems:s,xAxis:i,isLinked:o}=this.state,l=s.map(a=>a.value);t({type:`${n}`,series:l,xAxis:i,isLinked:o})}handleTypeClick(e){const n=e.target.getAttribute("data-index"),s=parseInt(n,10),i=ut.types[s];lc.debug2("handleTypeSelect",i),this.setState(o=>{const l=ut.getMaxSeriesCount(i);let{seriesItems:a}=o;if(a=a.slice(0,l),a.length===0&&l>0){const{model:d}=this.props,{columns:h}=d;a=ut.makeDefaultSeriesItems(i,h)}return{type:i,seriesItems:a}},this.sendChange)}handleXAxisChange(e){const t=e.target.value;lc.debug2("x-axis change",t),this.setState({xAxis:t},this.sendChange)}sendChange(){const{onChange:e}=this.props,{isLinked:t,type:n,seriesItems:s,xAxis:i}=this.state,o=s.map(l=>l.value);e({type:n,series:o,xAxis:i,isLinked:t})}render(){const{model:e}=this.props,{columns:t}=e,{seriesItems:n,type:s,xAxis:i,isLinked:o}=this.state,l=ut.getMaxSeriesCount(s),a=ut.getXAxisLabel(s),d=ut.getSeriesLabel(s),h=n.length>0,u=n.length<l;return r.jsx("div",{className:"chart-builder",children:r.jsxs("form",{onSubmit:this.handleSubmit,children:[r.jsxs("div",{className:"form-row",children:[r.jsx("label",{children:"Select Chart Type"}),r.jsx("div",{className:"form-row",children:ut.types.map((m,g)=>{const p=m;return r.jsx("div",{className:"col col-chart-type",children:r.jsxs("button",{type:"button",className:Y("btn","btn-icon","btn-chart-type",{active:m===s}),"data-index":g,onClick:this.handleTypeClick,children:[ut.getTypeIcon(m),ut.getTypeName(m)]})},p)})})]}),r.jsx("hr",{}),r.jsxs("div",{className:"form-row form-inline",children:[r.jsx("label",{className:"col-2 label-left",children:a}),r.jsx("select",{className:"form-control custom-select select-x-axis col",value:i,onChange:this.handleXAxisChange,children:t.map(m=>r.jsx("option",{value:m.name,children:m.name},m.name))})]}),h&&r.jsx("hr",{}),n.map((m,g)=>r.jsxs("div",{className:"form-row form-inline form-series-item","data-testid":`form-series-item-${g}`,children:[r.jsx("label",{className:"col-2 label-left",children:g===0?d:""}),r.jsx("select",{className:"form-control custom-select select-series col",value:m.value,onChange:this.handleSeriesChange,"data-testid":`select-series-item-${g}`,"data-index":g,children:t.map(p=>r.jsx("option",{value:p.name,"data-index":g,children:p.name},p.name))}),n.length>1&&r.jsx(B,{kind:"ghost",className:"btn-delete-series ml-2 px-2","data-index":g,"data-testid":`delete-series-${g}`,onClick:this.handleSeriesDeleteClick,icon:Gt,tooltip:"Delete"})]},m.id)),u&&r.jsxs("div",{className:"form-row",children:[r.jsx("div",{className:"col-2"}),r.jsx(B,{kind:"ghost",className:"btn-add-series mt-1",onClick:this.handleAddSeries,icon:Es,children:"Add Series"})]}),r.jsxs("div",{className:"form-row chart-builder-link",children:[r.jsx("label",{className:"col-2 label-right",children:r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx(ee,{mask:rr,icon:Ri,transform:"right-5 down-5"}),r.jsx(ee,{icon:o?th:Cg,transform:"grow-2 right-8 down-6"})]})}),r.jsxs(Ul,{onChange:this.handleLinkStateChange,value:`${o}`,children:[r.jsx(Wn,{value:"true",children:"Sync State"}),r.jsx(Wn,{value:"false",children:"Freeze State"})]})]}),r.jsxs("div",{className:"form-row",children:[r.jsx("div",{className:"col-2 label-right"}),r.jsx("div",{className:"col chart-builder-link-info",children:o?"Charts with synced state will update to match any filters or user modifications applied to the parent table.":"Freeze State disconnects the chart state from the parent table. New filters or user modifications on the parent table will not be applied."})]}),r.jsxs("div",{className:Y("form-row","justify-content-end","my-3"),children:[r.jsx(B,{kind:"secondary",className:"btn-reset",onClick:this.handleReset,children:"Reset"}),r.jsx(B,{kind:"primary",type:"submit",className:"btn-submit",children:"Create"})]})]})})}}const TT=ut;class ET extends v.Component{static defaultProps={value:"",onContentChanged:()=>{},editorSettings:{},editorIndex:0,onTab:()=>{},invalid:!1};constructor(e){super(e),this.handleContentChanged=this.handleContentChanged.bind(this),this.handleEditorFocus=this.handleEditorFocus.bind(this),this.handleEditorBlur=this.handleEditorBlur.bind(this),this.handleContainerClick=this.handleContainerClick.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.state={isEditorFocused:!1,isEditorEmpty:!0},this.editorContainer=null}componentDidMount(){this.initEditor()}componentWillUnmount(){this.destroyEditor()}editorContainer;editor;initEditor(){const{value:e,editorSettings:t}=this.props,n={copyWithSyntaxHighlighting:"false",fixedOverflowWidgets:!0,folding:!1,fontFamily:"Fira Mono",glyphMargin:!1,language:"groovyDB",lineDecorationsWidth:8,lineNumbers:"off",minimap:{enabled:!1},renderLineHighlight:"none",scrollbar:{arrowSize:0,horizontal:"hidden",horizontalScrollbarSize:0},scrollBeyondLastLine:!1,padding:{top:6,bottom:6},tabCompletion:"off",useTabStops:!0,value:e,wordWrap:"on",automaticLayout:!0,...t};if(!this.editorContainer)throw new Error("editorContainer is null");this.editor=Gn.create(this.editorContainer,n),this.editor.layout(),this.editor.getModel()?.updateOptions({tabSize:0}),this.editor.onKeyDown(this.handleKeyDown),this.editor.onDidChangeModelContent(this.handleContentChanged),this.editor.onDidFocusEditorText(this.handleEditorFocus),this.editor.onDidBlurEditorText(this.handleEditorBlur)}destroyEditor(){this.editor?.dispose(),this.editor=void 0}handleContentChanged(){const{onContentChanged:e}=this.props,t=this.editor?.getModel()?.getValue();t!==void 0&&this.setState({isEditorEmpty:t.length===0}),e(t)}handleEditorFocus(){this.setState({isEditorFocused:!0})}handleEditorBlur(){const e=this.editor?.getModel()?.getValue()??"";this.setState({isEditorEmpty:e.length===0,isEditorFocused:!1})}handleContainerClick(){const{isEditorFocused:e}=this.state;e||this.editor?.focus()}handleKeyDown(e){const{onTab:t,editorIndex:n}=this.props;e.code==="Tab"&&(e.stopPropagation(),e.preventDefault(),t(n,e.shiftKey))}render(){const{value:e,invalid:t}=this.props,{isEditorFocused:n,isEditorEmpty:s}=this.state;return r.jsxs("div",{className:Y("input-editor-wrapper",{focused:n,invalid:t}),role:"presentation",onClick:this.handleContainerClick,children:[r.jsx("div",{className:"editor-container",ref:i=>{this.editorContainer=i}}),s&&!e&&r.jsx("div",{className:"editor-placeholder text-muted",children:"Column Formula"})]})}}const ac=Object.freeze({NAME:"name",FORMULA:"formula"}),yT=()=>{};function RT({eventKey:c,name:e,inputIndex:t,formula:n,onChange:s,onDeleteColumn:i,onTabInEditor:o,invalid:l,isDuplicate:a}){const d=e===""||Ii.isValidColumnName(e),h=v.useCallback(u=>{u!==void 0&&(u.replace(/(\r\n|\n|\r)/gm,""),s(c,ac.FORMULA,u))},[s,c]);return r.jsx(Uc,{draggableId:c,index:t,disableInteractiveElementBlocking:!0,children:(u,m)=>r.jsxs("div",{className:Y("draggable-container",{dragging:m.isDragging}),ref:u.innerRef,...u.draggableProps,children:[r.jsxs("div",{className:"custom-column-input-container",children:[r.jsxs("div",{className:"pb-3",children:[r.jsxs("div",{className:"d-flex flex-row custom-column-name",children:[r.jsx("input",{className:Y("form-control custom-column-input",{"is-invalid":l||!d||a}),placeholder:"Column Name",value:e,onChange:g=>{s(c,ac.NAME,g.target.value)}}),r.jsx(B,{kind:"ghost",className:"ml-1 px-2",onClick:()=>{i(c)},icon:Gt,tooltip:"Delete custom column"}),r.jsx(B,{kind:"ghost",className:"btn-drag-handle",onClick:yT,...u.dragHandleProps,icon:Wl,tooltip:"Drag column to re-order"})]}),(!d||a)&&r.jsx("p",{className:"validate-label-error text-danger mb-0 mt-2 pl-1",children:d?"Duplicate name":"Invalid name"})]}),r.jsx(ET,{editorSettings:{language:"deephavenDb"},editorIndex:t,value:n,onContentChanged:h,onTab:o,invalid:l})]}),r.jsx("hr",{})]})})}const xa=[];class xT extends Sw{static EVENT=Object.freeze({UPDATED:"UPDATED",FORMATTER_UPDATED:"FORMATTER_UPDATED",REQUEST_FAILED:"REQUEST_FAILED",COLUMNS_CHANGED:"COLUMNS_CHANGED",TABLE_CHANGED:"TABLE_CHANGED",FILTERS_CHANGED:"FILTERS_CHANGED",SORTS_CHANGED:"SORTS_CHANGED",DISCONNECT:"DISCONNECT",RECONNECT:"RECONNECT",TOTALS_UPDATED:"TOTALS_UPDATED",PENDING_DATA_UPDATED:"PENDING_DATA_UPDATED"});constructor(){super(),this.listenerCount=0}listenerCount;addEventListener(e,t,n){super.addEventListener(e,t,n),this.listenerCount+=1,this.listenerCount===1&&this.startListening()}removeEventListener(e,t,n){super.removeEventListener(e,t,n),this.listenerCount-=1,this.listenerCount===0&&this.stopListening()}startListening(){}stopListening(){}get originalColumns(){return this.columns}get layoutHints(){return null}get frontColumns(){return xa}get backColumns(){return xa}get frozenColumns(){return xa}isColumnFrozen(e){return!1}get isFilterRequired(){return!1}get isReversible(){return!0}get isColumnStatisticsAvailable(){return!1}get description(){return""}get isCustomColumnsAvailable(){return!1}get isFormatColumnsAvailable(){return!1}get isExportAvailable(){return!1}get isValuesTableAvailable(){return!1}get isChartBuilderAvailable(){return!1}get isRollupAvailable(){return!1}get isSelectDistinctAvailable(){return!1}get isTotalsAvailable(){return!1}isFilterable(e){return!1}close(){}isRowMovable(){return!1}get isSeekRowAvailable(){return!1}}const Ce=xT;class Us extends v.Component{static SUCCESS_SHOW_DURATION=750;static makeCustomColumnInputEventKey(){return qe.generate()}static createCustomColumnInput(){return{eventKey:qe.generate(),name:"",formula:""}}constructor(e){super(e),this.handleAddColumnClick=this.handleAddColumnClick.bind(this),this.handleSaveClick=this.handleSaveClick.bind(this),this.handleInputChange=this.handleInputChange.bind(this),this.handleDeleteColumn=this.handleDeleteColumn.bind(this),this.handleCustomColumnUpdated=this.handleCustomColumnUpdated.bind(this),this.handleRequestFailed=this.handleRequestFailed.bind(this),this.handleDragEnd=this.handleDragEnd.bind(this),this.resetRequestFailed=this.resetRequestFailed.bind(this),this.handleEditorTabNavigation=this.handleEditorTabNavigation.bind(this),this.state={inputs:[],isCustomColumnApplying:!1,errorMessage:null,hasRequestFailed:!1,isSuccessShowing:!1},this.container=null,this.successButtonTimer=null}componentDidMount(){const{customColumns:e}=this.props;this.parseCustomColumns(e),this.startListening()}componentWillUnmount(){this.stopListening(),this.successButtonTimer&&clearTimeout(this.successButtonTimer)}container;successButtonTimer;getInput=ge((e,t)=>e.find(n=>n.eventKey===t));getInputIndex=ge((e,t)=>e.findIndex(n=>n.eventKey===t));resetErrorMessage(){this.setState({errorMessage:null})}startListening(){const{model:e}=this.props;e.addEventListener(Ce.EVENT.COLUMNS_CHANGED,this.handleCustomColumnUpdated),e.addEventListener(Ce.EVENT.UPDATED,this.handleCustomColumnUpdated),e.addEventListener(Ce.EVENT.REQUEST_FAILED,this.handleRequestFailed)}stopListening(){const{model:e}=this.props;e.removeEventListener(Ce.EVENT.COLUMNS_CHANGED,this.handleCustomColumnUpdated),e.removeEventListener(Ce.EVENT.UPDATED,this.handleCustomColumnUpdated),e.removeEventListener(Ce.EVENT.REQUEST_FAILED,this.handleRequestFailed)}parseCustomColumns(e){if(e.length>0){const t=e.map(n=>{const s=n.split(/=(.+)/,2);return{eventKey:Us.makeCustomColumnInputEventKey(),name:s[0],formula:s[1]}});this.setState({inputs:t})}else this.setState({inputs:[Us.createCustomColumnInput()]})}handleAddColumnClick(){const{inputs:e}=this.state,t=[...e];t.push(Us.createCustomColumnInput()),this.setState({inputs:t})}handleDeleteColumn(e){const{inputs:t}=this.state,n=this.getInputIndex(t,e),s=[...t];s.splice(n,1),s.length===0&&s.push(Us.createCustomColumnInput()),this.setState({inputs:s})}handleInputChange(e,t,n){const{inputs:s}=this.state,i=this.getInputIndex(s,e),l={...this.getInput(s,e)};l[t]=n;const a=[...s];a.splice(i,1,l),this.setState({inputs:a})}handleCustomColumnUpdated(){const{isCustomColumnApplying:e}=this.state;e&&this.setState({isCustomColumnApplying:!1,isSuccessShowing:!0},()=>{this.successButtonTimer=setTimeout(()=>this.setState({isSuccessShowing:!1}),Us.SUCCESS_SHOW_DURATION)})}handleRequestFailed(e){const t=e,{isCustomColumnApplying:n}=this.state;n&&this.setState({isCustomColumnApplying:!1,errorMessage:r.jsxs(r.Fragment,{children:[r.jsxs("p",{children:[r.jsx(ee,{icon:ws})," Failed to apply custom columns."]}),r.jsxs("div",{className:"error-box",children:[t.detail.errorMessage,r.jsx("br",{}),"Table configuration:"," ",JSON.stringify(t.detail.configuration)]})]}),hasRequestFailed:!0})}handleDragEnd(e){if(hn.stopDragging(),!e.destination)return;const{inputs:t}=this.state,n=e.source.index,s=e.destination.index,i=[...t],o=t[n];i.splice(n,1),i.splice(s,0,o),this.setState({inputs:i})}handleEditorTabNavigation(e,t){const{inputs:n}=this.state;if(t){(this.container?.querySelectorAll(".btn-drag-handle")[e]).focus();return}if(e===n.length-1)this.container?.querySelector(".btn-add-column")?.focus();else{const s=e+1;(this.container?.querySelectorAll(".custom-column-input")[s]).focus()}}handleSaveClick(){const{onSave:e,customColumns:t}=this.props,{inputs:n,isCustomColumnApplying:s}=this.state;if(s)return;const i=[];n.forEach(o=>{const{name:l,formula:a}=o;l&&a&&i.push(`${l}=${a}`)}),this.resetErrorMessage(),this.setState({isCustomColumnApplying:i.length>0||t.length>0}),e(i)}resetRequestFailed(){this.setState(({hasRequestFailed:e})=>e?{hasRequestFailed:!1}:null)}renderInputs(){const{inputs:e,hasRequestFailed:t}=this.state,n=new Map;return e.forEach(({name:s})=>n.set(s,(n.get(s)??0)+1)),e.map((s,i)=>{const{eventKey:o,name:l,formula:a}=s,d=(n.get(l)??0)>1;return r.jsx(RT,{inputIndex:i,eventKey:o,name:l,formula:a,onChange:this.handleInputChange,onDeleteColumn:this.handleDeleteColumn,onTabInEditor:this.handleEditorTabNavigation,invalid:t,isDuplicate:d},o)})}renderSaveButton(){const{inputs:e,isCustomColumnApplying:t,isSuccessShowing:n}=this.state,s=e.length>1?"Save Columns":"Save Column",i=e.every(({name:a})=>a===""||Ii.isValidColumnName(a)),o=e.filter(({name:a})=>a!=="").map(({name:a})=>a),l=new Set(o).size===o.length;return r.jsxs(B,{kind:n?"success":"primary",className:Y("btn-apply",{"btn-spinner":t}),disabled:n||t||!i||!l,onClick:this.handleSaveClick,children:[t&&r.jsxs("span",{children:[r.jsx(In,{}),r.jsx("span",{className:"btn-normal-content",children:"Applying"})]}),!n&&!t&&s,n&&r.jsxs(r.Fragment,{children:[r.jsx(ee,{icon:dr})," Success"]})]})}render(){const{onCancel:e}=this.props,{errorMessage:t}=this.state;return r.jsxs("div",{role:"presentation",className:"custom-column-builder-container",ref:n=>{this.container=n},onClick:this.resetRequestFailed,onFocus:this.resetRequestFailed,children:[r.jsx("hr",{}),r.jsx(Pl,{onDragStart:hn.startDragging,onDragEnd:this.handleDragEnd,children:r.jsx(or,{droppableId:"droppable-custom-columns",children:(n,s)=>r.jsxs("div",{ref:n.innerRef,...n.droppableProps,className:Y("droppable-container",{dragging:s.draggingFromThisWith}),children:[this.renderInputs(),n.placeholder]})})}),r.jsx("div",{className:"pt-1 px-3",children:r.jsx(B,{kind:"ghost",className:"btn-add-column",onClick:this.handleAddColumnClick,icon:Es,children:"Add Another Column"})}),r.jsxs("div",{className:"custom-column-builder-footer",children:[t&&r.jsx("div",{className:"error-message",children:t}),r.jsxs("div",{className:"d-flex justify-content-end",children:[r.jsx(B,{kind:"secondary",className:"mr-2",onClick:e,children:"Cancel"}),this.renderSaveButton()]})]})]})}}const DT=Us;var Du=(c=>(c.ADVANCED_SETTINGS="ADVANCED_SETTINGS",c.AGGREGATIONS="AGGREGATIONS",c.AGGREGATION_EDIT="AGGREGATIONS_EDIT",c.CHART_BUILDER="CHART_BUILDER",c.CUSTOM_COLUMN_BUILDER="CUSTOM_COLUMN_BUILDER",c.QUICK_FILTERS="QUICK_FILTERS",c.ROLLUP_ROWS="ROLLUP_ROWS",c.SEARCH_BAR="SEARCH_BAR",c.SELECT_DISTINCT="SELECT_DISTINCT",c.TABLE_EXPORTER="TABLE_EXPORTER",c.VISIBILITY_ORDERING_BUILDER="VISIBILITY_ORDERING_BUILDER",c.CONDITIONAL_FORMATTING="CONDITIONAL_FORMATTING",c.CONDITIONAL_FORMATTING_EDIT="CONDITIONAL_FORMATTING_EDIT",c.GOTO="GOTO",c))(Du||{});const Ne=Du;const Ui=ne.module("RollupRows"),IT=150,Wo="grouped-rollup-rows",Go="ungrouped-rollup-rows";class Qt extends v.Component{static SORT=Object.freeze({ASCENDING:"ASC",DESCENDING:"DESC"});static defaultProps={config:null,onChange:()=>{}};static renderColumn({item:e,isClone:t,selectedCount:n}){const s=e?.name,i=t!==void 0&&t?`${n}`:void 0,o=t!==void 0&&t?"item-list-item-clone":"";return rn.renderTextItem({text:s,badgeText:i,className:o})}static addGroupings(e,t,n=e.length){if(t==null||t.length===0)return e;let s=n;const i=e.filter((o,l)=>t.includes(o)?(l<s&&(s-=1),!1):!0);return i.splice(s,0,...t),i}static isGroupable(e){return!F.isDecimalType(e.type)}constructor(e){super(e),this.handleDeleteClicked=this.handleDeleteClicked.bind(this),this.handleSearchChange=this.handleSearchChange.bind(this),this.handleUngroupedSelect=this.handleUngroupedSelect.bind(this),this.handleUngroupedSelectionChange=this.handleUngroupedSelectionChange.bind(this),this.handleDragStart=this.handleDragStart.bind(this),this.handleDragEnd=this.handleDragEnd.bind(this),this.handleGroupedSelectionChange=this.handleGroupedSelectionChange.bind(this),this.handleShowConstituentsChange=this.handleShowConstituentsChange.bind(this),this.handleShowNonAggregatedColumnsChange=this.handleShowNonAggregatedColumnsChange.bind(this),this.handleSortAscending=this.handleSortAscending.bind(this),this.handleSortDescending=this.handleSortDescending.bind(this),this.renderGroupedItem=this.renderGroupedItem.bind(this),this.ungroupedList=de.createRef(),this.groupedList=de.createRef();const{config:t}=e,{columns:n=[],showConstituents:s=!0,showNonAggregatedColumns:i=!0}=t??{};this.state={ungroupedSelectedRanges:[],columns:n,groupedSelectedRanges:[],searchFilter:"",showConstituents:s,showNonAggregatedColumns:i,dragSource:null,sort:null}}componentDidUpdate(e,t){const{config:n}=this.props,{columns:s,showConstituents:i,showNonAggregatedColumns:o}=this.state;n!==e.config?this.updateFromConfig():(s!==t.columns||i!==t.showConstituents||o!==t.showNonAggregatedColumns)&&(n==null||s!==n.columns||i!==n.showConstituents||o!==n.showNonAggregatedColumns)&&this.sendChange()}componentWillUnmount(){this.search.cancel()}ungroupedList;groupedList;handleSearchChange(e){const t=e.target.value;if(this.setState({searchFilter:t}),!t){this.search.cancel(),this.resetSelection();return}this.search(t)}handleSortAscending(){this.setState(({sort:e})=>({sort:e===Qt.SORT.ASCENDING?null:Qt.SORT.ASCENDING}))}handleSortDescending(){this.setState(({sort:e})=>({sort:e===Qt.SORT.DESCENDING?null:Qt.SORT.DESCENDING}))}resetSelection(){this.setState({ungroupedSelectedRanges:[],groupedSelectedRanges:[]})}search=Ye(e=>{const t=this.getSortedUngroupedColumns(),n=[];let s=null;for(let i=0;i<t.length;i+=1)t[i].name.toLowerCase().includes(e.toLowerCase())&&(s==null&&(s=i),n.push([i,i]));N(s),this.setState({ungroupedSelectedRanges:n}),n.length>0&&this.ungroupedList.current&&this.ungroupedList.current.scrollToItem(s)},IT);handleDragStart(e){Ui.debug("handleDragStart",e),document.documentElement.classList.add("drag-pointer-events-none"),this.setState({dragSource:e.source})}handleDragEnd(e){Ui.debug("handleDragEnd",e),document.documentElement.classList.remove("drag-pointer-events-none"),this.setState({dragSource:null});const{destination:t,source:n}=e;if(t==null||n==null)return;if(t.droppableId===Go){this.setState(({groupedSelectedRanges:o,columns:l})=>{const a=[...l];return hn.reorder(a,o,[],0),{columns:a,ungroupedSelectedRanges:[],groupedSelectedRanges:[]}});return}const s=n.droppableId===Wo;let i=t.index;s&&n.index<t.index&&(i+=1),this.setState(({columns:o,ungroupedSelectedRanges:l,groupedSelectedRanges:a})=>{const d=[...o],h=s?d:this.getSortedUngroupedColumns().map(C=>C.name),u=s?a:l,m=hn.reorder(h,u,d,i),g=s?hn.adjustDestinationIndex(i,a):i,p=[[g,g+m.length-1]];return{columns:d,ungroupedSelectedRanges:[],groupedSelectedRanges:p}}),this.resetSelection()}handleUngroupedSelect(e){Ui.debug("handleUngroupedSelect"),this.setState(({columns:t})=>({columns:Qt.addGroupings(t,[this.getSortedUngroupedColumns()[e].name]),ungroupedSelectedRanges:[],groupedSelectedRanges:[]}))}handleUngroupedSelectionChange(e){Ui.debug2("handleUngroupedSelectionChange",e),this.setState(({ungroupedSelectedRanges:t})=>e===t?null:{ungroupedSelectedRanges:e,groupedSelectedRanges:[]})}handleGroupedSelectionChange(e){Ui.debug2("handleGroupedSelectedRanges",e),this.setState(({groupedSelectedRanges:t})=>e===t?null:{groupedSelectedRanges:e,ungroupedSelectedRanges:[]})}handleDeleteClicked(e){this.setState(({columns:t})=>{const n=t.slice();return n.splice(e,1),{columns:n}})}handleShowConstituentsChange(){this.setState(({showConstituents:e})=>({showConstituents:!e}))}handleShowNonAggregatedColumnsChange(){this.setState(({showNonAggregatedColumns:e})=>({showNonAggregatedColumns:!e}))}updateFromConfig(){const{config:e}=this.props,{columns:t=[],showConstituents:n=!0,showNonAggregatedColumns:s=!0}=e??{};this.setState({columns:t,showConstituents:n,showNonAggregatedColumns:s})}sendChange(){const{onChange:e}=this.props,{columns:t,showConstituents:n,showNonAggregatedColumns:s}=this.state;e({columns:t,showConstituents:n,showNonAggregatedColumns:s})}getCachedUngroupedColumns=Re((e,t)=>e.filter(n=>Qt.isGroupable(n)&&t.find(s=>s===n.name)==null));getCachedSortedColumns=Re((e,t)=>t==null?[...e]:F.sortColumns(e,t===Qt.SORT.ASCENDING));getUngroupedColumns(){const{model:e}=this.props,{columns:t}=this.state,{originalColumns:n}=e;return this.getCachedUngroupedColumns(n,t)}getSortedUngroupedColumns(){const{sort:e}=this.state,t=this.getUngroupedColumns();return this.getCachedSortedColumns(t,e)}renderGroupedItem({item:e,itemIndex:t,isClone:n,selectedCount:s}){const o=`${n!==void 0&&n?"":"  ".repeat(t)}${e}`,l=n!==void 0&&n?`${s}`:void 0,a=n!==void 0&&n?"item-list-item-clone":"";return r.jsxs(r.Fragment,{children:[rn.renderTextItem({text:o,badgeText:l,className:a}),(n===void 0||!n)&&r.jsx(B,{kind:"ghost",className:"btn btn-link btn-link-icon btn-delete-grouping float-right",onClick:()=>this.handleDeleteClicked(t),children:r.jsx(ee,{icon:Gt})})]})}render(){const{columns:e,dragSource:t,searchFilter:n,groupedSelectedRanges:s,ungroupedSelectedRanges:i,showConstituents:o,showNonAggregatedColumns:l,sort:a}=this.state,d=this.getSortedUngroupedColumns();let h=e.length*rn.DEFAULT_ROW_HEIGHT;t?.droppableId===Go&&(h+=rn.DEFAULT_ROW_HEIGHT);const u=d.length*rn.DEFAULT_ROW_HEIGHT+10,m=Math.min(3*rn.DEFAULT_ROW_HEIGHT,u);return r.jsx("div",{role:"menu",className:Y("rollup-rows",{"is-dragging":t!=null}),tabIndex:0,children:r.jsxs(Pl,{onDragEnd:this.handleDragEnd,onDragStart:this.handleDragStart,children:[r.jsxs("div",{className:"rollup-rows-group-by",children:[r.jsx("div",{className:"section-title",children:"Group By"}),e.length===0&&r.jsx(or,{droppableId:"placeholder",children:(g,p)=>r.jsx("div",{className:Y("placeholder","text-muted",{"is-dragging-from-this":p.draggingFromThisWith,"is-dragging-over":p.isDraggingOver,"is-dropping":p.draggingOverWith}),ref:g.innerRef,...g.droppableProps,children:"To create a rollup, drag columns from the list below and drop them into this area."})}),e.length>0&&r.jsx(rn,{draggingItemClassName:"rollup-rows-dragging-grouped-item",draggablePrefix:Wo,droppableId:Wo,itemCount:e.length,items:e,offset:0,onSelectionChange:this.handleGroupedSelectionChange,ref:this.groupedList,renderItem:this.renderGroupedItem,selectedRanges:s,style:{height:h},isMultiSelect:!0})]}),r.jsxs("div",{className:"rollup-rows-available-columns",children:[r.jsx("div",{className:"section-title",children:"Available Grouping Columns"}),r.jsxs("div",{className:"top-menu",children:[r.jsx(Di,{className:"w-100",value:n,matchCount:n?i.length:void 0,placeholder:"Find column...",onChange:this.handleSearchChange}),r.jsxs(B,{kind:"ghost",className:Y("btn-link btn-link-icon",{active:a===Qt.SORT.ASCENDING}),onClick:this.handleSortAscending,children:[r.jsx(ee,{icon:ur}),r.jsx(ot,{children:"Sort ascending"})]}),r.jsxs(B,{kind:"ghost",className:Y("btn-link btn-link-icon",{active:a===Qt.SORT.DESCENDING}),onClick:this.handleSortDescending,children:[r.jsx(ee,{icon:mr}),r.jsx(ot,{children:"Sort descending"})]})]}),r.jsx(rn,{className:"rollup-available-grouping-columns",draggablePrefix:Go,droppableId:Go,itemCount:d.length,items:d,renderItem:Qt.renderColumn,offset:0,onSelect:this.handleUngroupedSelect,onSelectionChange:this.handleUngroupedSelectionChange,ref:this.ungroupedList,selectedRanges:i,style:{maxHeight:u,minHeight:m},isDropDisabled:t?.droppableId!==Wo,isMultiSelect:!0}),r.jsxs("div",{className:"bottom-menu",children:[r.jsx("div",{className:"label",children:"Show:"}),r.jsx(nn,{checked:o,onChange:this.handleShowConstituentsChange,children:"Constituents"}),r.jsx(nn,{checked:l,onChange:this.handleShowNonAggregatedColumnsChange,children:"Non-Aggregated Columns"})]})]})]})})}}const FT=Qt;const NT=ne.module("TableCsvExporter");class Be extends v.Component{static FILENAME_DATE_FORMAT="yyyy-MM-dd-HHmmss";static DOWNLOAD_STATUS={INITIATING:"INITIATING",DOWNLOADING:"DOWNLOADING",FINISHED:"FINISHED",CANCELED:"CANCELED"};static DOWNLOAD_ROW_OPTIONS={ALL_ROWS:"ALL_ROWS",SELECTED_ROWS:"SELECTED_ROWS",CUSTOMIZED_ROWS:"CUSTOMIZED_ROWS"};static CUSTOMIZED_ROWS_OPTIONS={FIRST:"FIRST",LAST:"LAST"};static DEFAULT_DOWNLOAD_ROWS=100;static defaultProps={onDownloadStart:()=>{},isDownloading:!1,tableDownloadStatus:"",tableDownloadProgress:0,tableDownloadEstimatedTime:null,selectedRanges:[]};static getDateString(){return I.i18n.DateTimeFormat.format(Be.FILENAME_DATE_FORMAT,new Date)}constructor(e){super(e),this.handleDownloadClick=this.handleDownloadClick.bind(this),this.handleDownloadRowOptionChanged=this.handleDownloadRowOptionChanged.bind(this),this.handleCustomizedDownloadRowOptionChanged=this.handleCustomizedDownloadRowOptionChanged.bind(this),this.handleCustomizedDownloadRowsChanged=this.handleCustomizedDownloadRowsChanged.bind(this),this.handleIncludeColumnHeadersChanged=this.handleIncludeColumnHeadersChanged.bind(this),this.handleIncludeHiddenColumnsChanged=this.handleIncludeHiddenColumnsChanged.bind(this),this.handleUseUnformattedValuesChanged=this.handleUseUnformattedValuesChanged.bind(this);const{name:t}=e;this.state={fileName:`${t}-${Be.getDateString()}.csv`,downloadRowOption:Be.DOWNLOAD_ROW_OPTIONS.ALL_ROWS,customizedDownloadRowOption:Be.CUSTOMIZED_ROWS_OPTIONS.FIRST,customizedDownloadRows:Be.DEFAULT_DOWNLOAD_ROWS,includeColumnHeaders:!0,includeHiddenColumns:!1,useUnformattedValues:!1,errorMessage:null,id:qe.generate()}}getSnapshotRanges(){const{model:e,selectedRanges:t}=this.props,{downloadRowOption:n,customizedDownloadRowOption:s,customizedDownloadRows:i}=this.state,{rowCount:o,columnCount:l}=e;let a=[];switch(n){case Be.DOWNLOAD_ROW_OPTIONS.ALL_ROWS:a.push(new te(0,0,l-1,o-1));break;case Be.DOWNLOAD_ROW_OPTIONS.SELECTED_ROWS:a=t.map(d=>({...d,startColumn:0,endColumn:l-1})).sort((d,h)=>d.startRow!=null&&h.startRow!=null?d.startRow-h.startRow:0);break;case Be.DOWNLOAD_ROW_OPTIONS.CUSTOMIZED_ROWS:switch(s){case Be.CUSTOMIZED_ROWS_OPTIONS.FIRST:a.push(new te(0,0,l-1,Math.min(i-1,o-1)));break;case Be.CUSTOMIZED_ROWS_OPTIONS.LAST:a.push(new te(0,Math.max(0,o-i),l-1,o-1));break}break}return a}getModelRanges(e){const{userColumnWidths:t,movedColumns:n}=this.props,{includeHiddenColumns:s}=this.state,i=Se.getHiddenColumns(t);let o=_.getModelRanges(e,n);if(!s&&i.length>0){const l=i.map(te.makeColumn);o=te.subtractRangesFromRanges(o,l)}return o}resetDownloadState(){this.setState({errorMessage:null})}async handleDownloadClick(){const{model:e,isDownloading:t,onDownloadStart:n,onDownload:s,onCancel:i}=this.props,{fileName:o,includeColumnHeaders:l,useUnformattedValues:a}=this.state;if(t){i();return}this.resetDownloadState();const d=this.getSnapshotRanges(),h=this.getModelRanges(d);if(this.validateOptionInput()){n();try{const u=await e.export(),m=u.setViewport(0,0);await m.getViewportData(),s(o,u,m,d,h,l,a)}catch(u){NT.error("CSV download failed",u),this.setState({errorMessage:r.jsxs("p",{children:[r.jsx(ee,{icon:ws})," ",`${u}`]})}),i()}}}handleDownloadRowOptionChanged(e){this.setState({downloadRowOption:e.target.value})}handleCustomizedDownloadRowOptionChanged(e){this.setState({customizedDownloadRowOption:e.target.value})}handleCustomizedDownloadRowsChanged(e){this.setState({customizedDownloadRows:parseInt(e.target.value,10)})}handleIncludeColumnHeadersChanged(){this.setState(({includeColumnHeaders:e})=>({includeColumnHeaders:!e}))}handleIncludeHiddenColumnsChanged(){this.setState(({includeHiddenColumns:e})=>({includeHiddenColumns:!e}))}handleUseUnformattedValuesChanged(){this.setState(({useUnformattedValues:e})=>({useUnformattedValues:!e}))}validateOptionInput(){const{selectedRanges:e}=this.props,{downloadRowOption:t,customizedDownloadRows:n}=this.state;return t===Be.DOWNLOAD_ROW_OPTIONS.SELECTED_ROWS&&e.length===0?(this.setState({errorMessage:r.jsxs("p",{children:[r.jsx(ee,{icon:ws})," No rows selected. Please select some rows in the table."]})}),!1):t===Be.DOWNLOAD_ROW_OPTIONS.CUSTOMIZED_ROWS&&n<=0?(this.setState({errorMessage:r.jsxs("p",{children:[r.jsx(ee,{icon:ws})," Number of rows to output must be greater than 0"]})}),!1):!0}render(){const{model:e,isDownloading:t,tableDownloadProgress:n,tableDownloadEstimatedTime:s,selectedRanges:i,tableDownloadStatus:o}=this.props,{fileName:l,downloadRowOption:a,customizedDownloadRowOption:d,customizedDownloadRows:h,includeColumnHeaders:u,includeHiddenColumns:m,useUnformattedValues:g,errorMessage:p,id:C}=this.state,{rowCount:f}=e;return r.jsxs("div",{className:"table-csv-exporter",children:[r.jsx("div",{className:"section-title",children:"Download Rows"}),r.jsx("div",{className:"form-group",children:r.jsxs(Ul,{onChange:this.handleDownloadRowOptionChanged,value:a,disabled:t,children:[r.jsxs(Wn,{value:Be.DOWNLOAD_ROW_OPTIONS.ALL_ROWS,"data-testid":"radio-csv-exporter-download-all",children:["All Rows",r.jsx("span",{className:"text-muted ml-2",children:`(${f.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1,")} rows)`})]}),r.jsxs(Wn,{value:Be.DOWNLOAD_ROW_OPTIONS.SELECTED_ROWS,"data-testid":"radio-csv-exporter-only-selected",children:["Only Selected Rows",r.jsx("span",{className:"text-muted ml-2",children:i.length>0?`(${te.rowCount(i).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1,")} rows)`:null})]}),r.jsx(Wn,{value:Be.DOWNLOAD_ROW_OPTIONS.CUSTOMIZED_ROWS,"data-testid":"radio-csv-exporter-customized-rows",children:r.jsxs("div",{className:"radio-input-row",role:"presentation",onClick:()=>{this.setState({downloadRowOption:Be.DOWNLOAD_ROW_OPTIONS.CUSTOMIZED_ROWS})},children:[r.jsxs("select",{value:d,"data-testid":"select-csv-exporter-customized-rows",className:"custom-select",disabled:t,onChange:this.handleCustomizedDownloadRowOptionChanged,children:[r.jsx("option",{value:"FIRST",children:"First"}),r.jsx("option",{value:"LAST",children:"Last"})]}),r.jsx("input",{type:"number",className:"form-control",id:`customizedRows-${C}`,"data-testid":"input-csv-exporter-customized-rows",name:`customizedRows-${C}`,placeholder:"100",value:h,disabled:t,onChange:this.handleCustomizedDownloadRowsChanged}),r.jsx("div",{children:"Rows"})]})})]})}),r.jsxs("div",{className:"form-group",children:[r.jsx("label",{htmlFor:`customizedRows-${C}`,children:"File Name"}),r.jsx("input",{type:"text",className:"form-control",id:`filename-${C}`,"data-testid":"input-csv-exporter-file-name",name:`filename-${C}`,value:l,onChange:b=>{this.setState({fileName:b.target.value})},disabled:t})]}),r.jsxs("div",{className:"checkbox-options",children:[r.jsx(nn,{checked:u,onChange:this.handleIncludeColumnHeadersChanged,children:"Include column headers"}),r.jsx(nn,{checked:m,onChange:this.handleIncludeHiddenColumnsChanged,children:"Include hidden columns"}),r.jsx(nn,{checked:g,onChange:this.handleUseUnformattedValuesChanged,children:"Use unformatted values"})]}),r.jsxs("div",{className:"section-footer flex-column",children:[p!=null&&r.jsx("div",{className:"error-message",children:p}),o&&r.jsxs("div",{className:"download-status",children:[(o===Be.DOWNLOAD_STATUS.DOWNLOADING||o===Be.DOWNLOAD_STATUS.INITIATING)&&r.jsxs(r.Fragment,{children:[o===Be.DOWNLOAD_STATUS.INITIATING&&r.jsx("div",{className:"text-muted",children:"Starting Download..."}),o===Be.DOWNLOAD_STATUS.DOWNLOADING&&r.jsxs("div",{className:"text-muted d-flex justify-content-between",children:[r.jsx("span",{children:s||s===0?`Estimated time: ${jl.formatElapsedTime(s)}`:null}),r.jsx("span",{children:`${n}%`})]})]}),o===Be.DOWNLOAD_STATUS.FINISHED&&r.jsx("div",{className:"text-muted text-right",children:"Download Completed"}),o===Be.DOWNLOAD_STATUS.CANCELED&&r.jsx("div",{className:"text-muted",children:"Download Canceled"}),(o===Be.DOWNLOAD_STATUS.DOWNLOADING||o===Be.DOWNLOAD_STATUS.INITIATING)&&r.jsx("div",{className:"progress",children:r.jsx("div",{className:"progress-bar progress-bar-striped progress-bar-animated",style:{width:`${n}%`}})}),o===Be.DOWNLOAD_STATUS.FINISHED&&r.jsx("div",{className:"progress",children:r.jsx("div",{className:"progress-bar bg-success",style:{width:`${n}%`}})})]}),r.jsxs(B,{kind:"primary","data-testid":"btn-csv-exporter-download",className:Y("btn-downloading",{"btn-spinner btn-cancelable":t}),onClick:this.handleDownloadClick,children:[t&&r.jsxs("span",{children:[r.jsx(In,{}),r.jsx("span",{className:"btn-normal-content",children:"Downloading"}),r.jsx("span",{className:"btn-hover-content",children:"Cancel"})]}),!t&&"Download"]})]})]})}}const Ms=Be,An=ne.module("TableSaver"),kT="yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS z";function MT(c){return c.added!==void 0}function LT(c){if(!MT(c))throw new Error("event is not UpdateEventData")}class jn extends v.PureComponent{static DOWNLOAD_CELL_CHUNK=6e3;static SNAPSHOT_BUFFER_SIZE=5;static STREAM_TIMEOUT=8e3;static SNAPSHOT_HANDLER_TIMEOUT=5;static defaultProps={getDownloadWorker:()=>Promise.reject(new Error("Download worker not provided")),isDownloading:!1,onDownloadCompleted:()=>{},onDownloadCanceled:()=>{},onDownloadProgressUpdate:()=>{}};static csvEscapeString(e){return`"${e.replace(/"/g,'""')}"`}constructor(e){super(e),this.handlePortMessage=this.handlePortMessage.bind(this),this.handleSnapshotResolved=this.handleSnapshotResolved.bind(this),this.handleDownloadTimeout=this.handleDownloadTimeout.bind(this),this.state={},this.gridRanges=[],this.gridRangeCounter=0,this.rangedSnapshotsTotal=[],this.rangedSnapshotCounter=0,this.includeColumnHeaders=!0,this.useUnformattedValues=!1,this.snapshotsTotal=0,this.snapshotCounter=0,this.snapshotsBuffer=new Map,this.currentSnapshotIndex=0,this.snapshotPending=0,this.cancelableSnapshots=[],this.iframes=[],this.useBlobFallback=!1}componentDidMount(){const{getDownloadWorker:e}=this.props;e().then(t=>{An.info("found active service worker"),this.sw=t,this.sw.postMessage("ping")}).catch(t=>{An.warn("Download csv is not optimized.",t),this.useBlobFallback=!0})}componentWillUnmount(){this.iframes.length>0&&this.iframes.forEach(e=>{e.remove()}),this.streamTimeout&&clearTimeout(this.streamTimeout),this.snapshotHandlerTimeout&&clearTimeout(this.snapshotHandlerTimeout)}sw;port;fileWriter;table;tableSubscription;columns;fileName;includeColumnHeaders;useUnformattedValues;chunkRows;gridRanges;gridRangeCounter;rangedSnapshotsTotal;rangedSnapshotCounter;snapshotsTotal;snapshotCounter;snapshotsBuffer;currentSnapshotIndex;snapshotPending;cancelableSnapshots;streamTimeout;snapshotHandlerTimeout;downloadStartTime;iframes;useBlobFallback;getCachedCustomColumnFormatFlag=pn($n.isCustomColumnFormatDefined,{max:1e4});createWriterStream(e){const t=this.useBlobFallback,n=[];let s=null;t&&(s=TextEncoder.prototype.encode.bind(new TextEncoder));const{fileName:i}=this,o={};return t?(o.write=l=>{N(s),l.header!==void 0&&n.push(s(l.header)),l.rows!==void 0&&n.push(s(l.rows))},o.close=()=>{N(i);const l=new Blob(n,{type:"application/octet-stream; charset=utf-8"}),a=document.createElement("a");a.href=URL.createObjectURL(l),a.download=i,a.click()},o.abort=()=>{e.postMessage({cancel:!0}),e.close()}):(o.write=l=>{e.postMessage(l)},o.close=()=>{e.postMessage({end:!0}),e.close()},o.abort=()=>{e.postMessage({cancel:!0}),e.close()}),new WritableStream(o)}startDownload(e,t,n,s,i,o,l){const{isDownloading:a}=this.props;if(a)return;this.downloadStartTime=Date.now(),An.info(`start downloading ${e}`),this.table=t,this.columns=Se.columnsFromRanges(i,t.columns),this.tableSubscription=n,this.gridRanges=s,this.includeColumnHeaders=o,this.useUnformattedValues=l;const d=encodeURIComponent(e.replace(/\//g,":")).replace(/['()]/g,escape).replace(/\*/g,"%2A"),h=new MessageChannel;if(this.port=h.port1,this.fileName=e,this.fileWriter=this.createWriterStream(this.port).getWriter(),this.useBlobFallback){this.writeCsvTable(o);return}this.sw&&this.sw.postMessage({encodedFileName:d},[h.port2]),this.port.onmessage=this.handlePortMessage}finishDownload(){this.table&&this.table.close(),this.tableSubscription&&this.tableSubscription.close(),this.fileWriter&&this.fileWriter.close();const{onDownloadCompleted:e}=this.props;e(),this.resetTableSaver(),this.downloadStartTime!==void 0&&An.info(`download finished, total elapsed time ${(Date.now()-this.downloadStartTime)/1e3} seconds`)}cancelDownload(){this.table&&this.table.close(),this.tableSubscription&&this.tableSubscription.close(),this.fileWriter&&this.fileWriter.abort(),this.cancelableSnapshots.forEach(t=>{t&&(t.catch(()=>null),t.cancel())});const{onDownloadCanceled:e}=this.props;e(),this.resetTableSaver()}resetTableSaver(){this.table=void 0,this.tableSubscription=void 0,this.columns=void 0,this.chunkRows=void 0,this.gridRanges=[],this.gridRangeCounter=0,this.rangedSnapshotsTotal=[],this.rangedSnapshotCounter=0,this.includeColumnHeaders=!0,this.useUnformattedValues=!1,this.snapshotsTotal=0,this.snapshotCounter=0,this.snapshotsBuffer=new Map,this.currentSnapshotIndex=0,this.snapshotPending=0,this.cancelableSnapshots=[],this.streamTimeout!=null&&clearTimeout(this.streamTimeout),this.snapshotHandlerTimeout!=null&&clearTimeout(this.snapshotHandlerTimeout),this.streamTimeout=void 0,this.snapshotHandlerTimeout=void 0}handleDownloadTimeout(){An.info("download canceled"),this.cancelDownload()}writeTableHeader(){let e="";if(this.columns)for(let t=0;t<this.columns.length;t+=1)e+=this.columns[t].name,e+=t===this.columns.length-1?`
21
21
  `:",";this.fileWriter?.write({header:e}).then(()=>null)}startWriteTableBody(){this.columns&&this.gridRanges!=null&&(this.chunkRows=Math.floor(jn.DOWNLOAD_CELL_CHUNK/this.columns.length),this.rangedSnapshotsTotal=this.gridRanges.map(e=>(N(e.endRow),N(e.startRow),N(this.chunkRows),Math.ceil((e.endRow-e.startRow+1)/this.chunkRows))),this.snapshotsTotal=this.rangedSnapshotsTotal.reduce((e,t)=>e+t),An.info("start writing table, total snapshots: ",this.snapshotsTotal),this.makeSnapshot(Math.min(jn.SNAPSHOT_BUFFER_SIZE,this.snapshotsTotal)))}writeCsvTable(e){e&&this.writeTableHeader(),this.startWriteTableBody()}writeSnapshot(e,t,n){if(this.currentSnapshotIndex===e&&this.fileWriter){for(;this.snapshotsBuffer.has(this.currentSnapshotIndex);){const s=this.snapshotsBuffer.get(this.currentSnapshotIndex);N(s),this.fileWriter.write({rows:this.convertSnapshotIntoCsv(s)}),this.snapshotsBuffer.delete(this.currentSnapshotIndex),this.currentSnapshotIndex+=1,this.updateDownloadProgress(e)}if(this.snapshotsTotal&&this.currentSnapshotIndex>=this.snapshotsTotal){this.finishDownload();return}}this.snapshotCounter&&this.snapshotsTotal&&this.snapshotCounter<this.snapshotsTotal&&(An.debug2(`
22
22
  current range index: ${this.gridRangeCounter},
23
23
  snapshotIndexCounter: ${this.snapshotCounter},
@@ -26,17 +26,17 @@ ${e}`):n.setValue(`${e}`);const i=n.getLineCount(),o=n.getLineLength(i)+1;this.e
26
26
  buffered ${this.snapshotsBuffer.size}
27
27
  making ${Math.min(jn.SNAPSHOT_BUFFER_SIZE-this.snapshotsBuffer.size-this.snapshotPending,this.snapshotsTotal-this.snapshotCounter)} more snapshots
28
28
  `),this.makeSnapshot(Math.min(jn.SNAPSHOT_BUFFER_SIZE-this.snapshotsBuffer.size-this.snapshotPending,this.snapshotsTotal-this.snapshotCounter)))}updateDownloadProgress(e){if(e!=null&&this.snapshotsTotal!=null&&this.downloadStartTime!=null){const{onDownloadProgressUpdate:t}=this.props,n=Math.floor(e*100/this.snapshotsTotal),s=e>1?Math.floor((Date.now()-this.downloadStartTime)*(this.snapshotsTotal-e)/e/1e3):null;t(n,s)}}convertSnapshotIntoCsv(e){let t="";const n=e.added.iterator(),{formatter:s}=this.props,i=[];for(;n.hasNext();)i.push(n.next().value);N(this.columns);const{useUnformattedValues:o}=this;for(let l=0;l<i.length;l+=1){const a=i[l];for(let d=0;d<this.columns.length;d+=1){const{type:h,name:u}=this.columns[d];let m=null;if(o){let g=e.getData(a,this.columns[d])??"";g!==""&&F.isDateType(h)&&(g=I.i18n.DateTimeFormat.format(kT,g,I.i18n.TimeZone.getTimeZone(s.timeZone))),m=g.toString()}else{const g=this.getCachedCustomColumnFormatFlag(s,u,h);let p=null;if(!g){const C=e.getFormat(a,this.columns[d]);p=C?.formatString!=null?C:null}p?m=s.getFormattedString(e.getData(a,this.columns[d]),h,u,p):m=s.getFormattedString(e.getData(a,this.columns[d]),h,u)}t+=jn.csvEscapeString(m),t+=d===this.columns.length-1?`
29
- `:","}}return t}makeSnapshot(e){if(e<=0)return;N(this.gridRangeCounter);let t=0,n=this.gridRanges[this.gridRangeCounter];for(N(this.tableSubscription),N(this.columns);t<e;){N(n),N(n.startRow),N(n.endRow),N(this.rangedSnapshotCounter),N(this.chunkRows);const s=n.startRow+this.rangedSnapshotCounter*this.chunkRows,i=Math.min(s+this.chunkRows-1,n.endRow),o=this.snapshotCounter;this.cancelableSnapshots.push(ye.makeCancelable(this.tableSubscription.snapshot(I.RangeSet.ofRange(s,i),this.columns).then(l=>(LT(l),this.handleSnapshotResolved(l,o,s,i),o)).catch(l=>{An.error(l)}),l=>{An.info(`snapshot ${l} has been canceled`)})),this.rangedSnapshotCounter+=1,this.snapshotCounter+=1,this.snapshotPending+=1,this.rangedSnapshotCounter>=this.rangedSnapshotsTotal[this.gridRangeCounter]&&(this.gridRangeCounter+=1,this.rangedSnapshotCounter=0,n=this.gridRanges[this.gridRangeCounter]),t+=1}}handlePortMessage({data:e}){const{download:t,readableStreamPulling:n}=e;if(!this.useBlobFallback){if(t!=null){const{includeColumnHeaders:s}=this;this.makeIframe(`${t}`),this.writeCsvTable(s)}n!=null&&(this.useBlobFallback||(this.streamTimeout!=null&&clearTimeout(this.streamTimeout),this.streamTimeout=setTimeout(this.handleDownloadTimeout,jn.STREAM_TIMEOUT)))}}handleSnapshotResolved(e,t,n,s){this.snapshotHandlerTimeout=setTimeout(()=>{this.snapshotsBuffer.set(t,e),this.snapshotPending-=1,this.writeSnapshot(t,n,s),this.cancelableSnapshots[t]=null},jn.SNAPSHOT_HANDLER_TIMEOUT)}makeIframe(e){const t=document.createElement("iframe");t.hidden=!0,t.src=`download/${e}`,t.name="iframe",document.body.appendChild(t),this.iframes.push(t)}render(){return null}}function OT(c){const{group:e,onDelete:t,onColorChange:n,onNameChange:s,validateName:i}=c,{isNew:o}=e,l=v.useRef(e),a=v.useRef(null),d=v.useRef(null),[h,u]=v.useState(!1),[m,g]=v.useState(o?"":e.name),[p,C]=v.useState(o),[f,b]=v.useState(!1),w=m!==e.name?i(m):"",S=o&&!f||w==="",T=v.useCallback(()=>{u(!1)},[]);v.useEffect(function(){p&&a.current&&(a.current.focus(),a.current.select())},[p]),v.useEffect(function(){return()=>{l.current.isNew&&t(l.current)}},[t]),v.useEffect(function(){return h&&(d.current?.click(),d.current?.focus(),window.addEventListener("click",T,!0)),()=>window.removeEventListener("click",T,!0)},[h,T]);const y=()=>{S&&(s(e,m),C(!1))},E=()=>{if(o){t(e);return}g(e.name),C(!1)},R=x=>{b(!0),x.key==="Enter"&&(x.stopPropagation(),y()),x.key===" "&&x.stopPropagation(),x.key==="Escape"&&E()};return p?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"editing-container",children:[r.jsx("input",{ref:a,className:Y("form-control",{"is-invalid":!S}),value:m,placeholder:"Group Name",onChange:x=>g(x.target.value),onKeyDown:R,onBlur:()=>b(!0)}),r.jsx(B,{kind:"ghost",icon:zn,tooltip:"Confirm",onClick:y}),r.jsx(B,{kind:"ghost",icon:bg,tooltip:"Cancel",onClick:E})]}),!S&&r.jsx("p",{className:"mb-0 validate-label-error text-danger",children:w})]}):r.jsxs("div",{className:"group-name-wrapper",children:[r.jsx("span",{className:"column-name",children:m}),r.jsx(B,{className:"p-1 mx-1",kind:"ghost",icon:go,tooltip:"Edit",onClick:()=>{C(!0)}}),r.jsxs("span",{className:"right-buttons",children:[r.jsx(B,{kind:"ghost",icon:Gt,tooltip:"Delete group",onClick:()=>t(e)}),r.jsx(B,{kind:"ghost",className:"color-swatch mr-1",icon:e.color!==void 0?r.jsxs("span",{className:"fa-layers",children:[r.jsx(ee,{className:"color-swatch",icon:cl,color:Je.white,transform:"down-1"}),r.jsx(ee,{className:"color-swatch",icon:cl,color:e.color,transform:"shrink-2 down-1"})]}):Sg,tooltip:"Set color",onClick:()=>u(x=>!x)}),h&&r.jsxs(r.Fragment,{children:[r.jsx("input",{"aria-label":"Color input",ref:d,type:"color",list:"presetColors",value:e.color??Je["content-bg"],style:{visibility:"hidden",width:0,height:0,padding:0,border:0},onChange:x=>{e.color=x.target.value,n(e,x.target.value)}}),r.jsxs("datalist",{id:"presetColors",children:[r.jsx("option",{children:Je["content-bg"]}),r.jsx("option",{children:Je.primary}),r.jsx("option",{children:Je.foreground}),r.jsx("option",{children:Je.green}),r.jsx("option",{children:Je.yellow}),r.jsx("option",{children:Je.orange}),r.jsx("option",{children:Je.red}),r.jsx("option",{children:Je.purple}),r.jsx("option",{children:Je.blue}),r.jsx("option",{children:Je["gray-400"]})]})]})]})]})}function AT(){}const _T=v.forwardRef(function(e,t){const{value:n,clone:s,childCount:i,item:o,onVisibilityChange:l,onClick:a,onGroupDelete:d,onGroupColorChange:h,onGroupNameChange:u,validateGroupName:m,handleProps:g}=e,{group:p,modelIndex:C,isVisible:f}=o.data,b=v.useRef(null),w=v.useCallback(T=>{T.buttons===1&&(l([C].flat(),!f),b.current?.focus())},[l,C,f]),S=v.useCallback(T=>{a(n,T)},[a,n]);return r.jsxs("div",{ref:t,className:Y("tree-item",{isSelected:o.selected,"two-dragged":i===2,"multiple-dragged":i>2}),onClick:S,...g,children:[r.jsx(B,{ref:b,kind:"ghost",className:"px-1",onClick:AT,onMouseDown:w,onMouseEnter:w,icon:f?gr:nh,tooltip:"Toggle visibility"}),r.jsx("span",{className:Y("column-name",p&&"column-group"),children:p&&!s?r.jsx(OT,{group:p,onDelete:d,onColorChange:h,onNameChange:u,validateName:m}):n}),r.jsxs("div",{children:[s&&i>1&&r.jsx("span",{className:"item-count",children:i}),r.jsx(ot,{children:"Drag to re-order"}),r.jsx(ee,{icon:Wl})]})]})}),PT=_T;function jT(c){return c.parentId!==void 0}function HT(c,e){return Math.round(c/e)}function Iu(c,e,t,n,s,i){const o=c.findIndex(l=>l.name===n);if(o===-1){const l=t.get(n);if(l==null)throw new Error(`Column or header group not found: ${n}`);const a=l.childIndexes.flat();return{id:n,selected:i.has(n),children:l.children.map(d=>Iu(c,e,t,d,s,i)).sort((d,h)=>{const u=Array.isArray(d.data.visibleIndex)?d.data.visibleIndex[0]:d.data.visibleIndex,m=Array.isArray(h.data.visibleIndex)?h.data.visibleIndex[0]:h.data.visibleIndex;return u-m}),data:{modelIndex:a,visibleIndex:l.getVisibleRange(e),group:l,isVisible:a.some(d=>!s.has(d))}}}return{id:n,children:[],selected:i.has(n),data:{modelIndex:o,visibleIndex:_.getVisibleIndex(o,e),isVisible:!s.has(o)}}}function BT(c,e,t,n,s){const i=[],o=new Set(s),l=new Map(t.map(h=>[h.name,h])),a=new Set(n);let d=0;for(;d<c.length;){const h=_.getModelIndex(d,e),u=c[h].name;let m=t.find(({children:p})=>p.includes(u));for(;m!==void 0&&m.parent!==void 0;)m=l.get(m.parent);const g=Iu(c,e,l,m?m.name:u,a,o);i.push(g),Array.isArray(g.data.visibleIndex)?d+=g.data.visibleIndex[1]-g.data.visibleIndex[0]+1:d+=1}return i}function Dl(c,e,t,n,s){const i=c.findIndex(({id:b})=>b===t),o=c.findIndex(({id:b})=>b===e),l=c[o],a=hm(c,o,i),d=a[i-1],h=a[i+1],u=HT(n,s),m=l.depth+u,g=UT({previousItem:d,nextItem:h}),p=VT({nextItem:h});let C=m;return m>=g?C=g:m<p&&(C=p),{depth:C,maxDepth:g,minDepth:p,parentId:f()};function f(){return C===0||!d?null:C===d.depth?d.parentId:C>d.depth?d.id:a.slice(0,i).reverse().find(w=>w.depth===C)?.parentId??null}}function UT({previousItem:c,nextItem:e}){return Math.max(c?.depth??0,e?.depth??0)}function VT({nextItem:c}){return c?c.depth:0}function Fu(c,e=null,t=0){return c.reduce((n,s,i)=>[...n,{...s,parentId:e,depth:t,index:i},...Fu(s.children,s.id,t+1)],[])}function Jt(c){return c.every(jT)?[...c]:Fu(c)}function Nu(c,e){for(let t=0;t<c.length;t+=1){const n=c[t],{id:s,children:i}=n;if(s===e)return n;if(i.length){const o=Nu(i,e);if(o)return o}}}function ku(c,e=0){return c.reduce((t,{children:n})=>n.length?ku(n,t+1):t+1,e)}function $T(c,e){const t=Nu(c,e);return t?ku(t.children):0}const WT=[Rn.Down,Rn.Right,Rn.Up,Rn.Left],GT=[Rn.Left,Rn.Right];function zT(c,e,t){return(n,{currentCoordinates:s,context:{active:i,over:o,collisionRect:l,droppableRects:a,droppableContainers:d}})=>{if(WT.includes(n.code)){if(!i||!l)return;n.preventDefault();const{current:{items:h,offset:u}}=c;if(GT.includes(n.code)&&o?.id!=null){const{depth:C,maxDepth:f,minDepth:b}=Dl(h,i.id,o.id,u,t);switch(n.code){case Rn.Left:if(C>b)return{...s,x:s.x-t};break;case Rn.Right:if(C<f)return{...s,x:s.x+t};break}return}const m=[];d.forEach(C=>{if(C?.disabled||C.id===o?.id)return;const f=a.get(C.id);if(f)switch(n.code){case Rn.Down:l.top<f.top&&m.push(C);break;case Rn.Up:l.top>f.top&&m.push(C);break}});const g=um({active:i,collisionRect:l,pointerCoordinates:null,droppableRects:a,droppableContainers:m});let p=mm(g,"id");if(p===o?.id&&g.length>1&&(p=g[1].id),p!=null&&o?.id!=null){const C=a.get(i.id),f=a.get(p),b=d.get(p);if(C&&f&&b){const w=h.findIndex(({id:E})=>E===p),S=h[w],T=h.findIndex(({id:E})=>E===i.id),y=h[T];if(S!=null&&y!=null){const{depth:E}=Dl(h,i.id,p,(S.depth-y.depth)*t,t),x=w>T?1:-1,D=e?(l.height-C.height)/2:0;return{x:f.left+E*t,y:f.top+x*D}}}}}}}class KT extends gm{static activators=[{eventName:"onPointerDown",handler:({nativeEvent:e})=>!(!e.isPrimary||e.button!==0||qT(e.target))}]}const YT=["button","input","textarea","select","option"];function qT(c){return!!(c?.tagName!=null&&YT.includes(c.tagName.toLowerCase()))}function Mu(c){const{clone:e=!1,depth:t,disableInteraction:n=!1,ghost:s=!1,handleProps:i,value:o,dragRef:l=null,wrapperRef:a=null,renderItem:d,item:h,childCount:u}=c,m=v.useMemo(()=>Array(t).fill(0).map((p,C)=>r.jsx("span",{className:"depth-line"},`depth-line-${C}`)),[t]),g=v.useMemo(()=>({ref:l,clone:e,value:o,item:h,childCount:u,handleProps:i}),[l,e,o,h,u,i]);return r.jsxs("li",{className:Y("item-wrapper",{clone:e,ghost:s,disableInteraction:n}),ref:a,children:[!e&&m,d(g)]},o)}Mu.displayName="TreeItem";const XT=({isSorting:c,wasDragging:e})=>!(c||e);function rc({id:c,depth:e,...t}){const{attributes:n,isDragging:s,isSorting:i,listeners:o,setDraggableNodeRef:l,setDroppableNodeRef:a,transform:d,transition:h}=pm({id:c,animateLayoutChanges:XT}),u=Ha.Translate.toString(d),m=v.useMemo(()=>({transform:u,transition:h}),[u,h]),g=v.useMemo(()=>({...n,...o,style:m}),[n,o,m]);return r.jsx(Mu,{dragRef:l,wrapperRef:a,depth:e,ghost:s,disableInteraction:i,handleProps:g,...t})}const ZT={keyframes({transform:c}){return[{opacity:1,transform:Ha.Transform.toString(c.initial)},{opacity:0,transform:Ha.Transform.toString({...c.final,x:c.final.x+5,y:c.final.y+5})}]},easing:"ease-out",sideEffects({active:c}){c.node.animate([{opacity:0},{opacity:1}],{duration:dd.duration,easing:dd.easing})}};let zo=null;function QT(c){return zo==null&&c.activeNodeRect&&c.activatorEvent instanceof PointerEvent&&(zo=Math.floor((c.activatorEvent.clientY-c.activeNodeRect.top)/c.activeNodeRect.height)*c.activeNodeRect.height),c.activeNodeRect||(zo=null),{...c.transform,y:c.transform.y+(zo??0)}}function JT({items:c,renderItem:e,indentationWidth:t=30,indicator:n=!1,activeId:s,overId:i,offsetLeft:o}){const l=fm(),a=v.useRef(l);v.useEffect(function(){a.current=l},[l]),v.useEffect(function(){a.current.measureDroppableContainers(c.map(({id:g})=>g))},[c]);const d=s!=null&&i!=null?Dl(c,s,i,o,t):null,h=v.useRef({items:c,offset:o}),u=s!=null?c.find(({id:m})=>m===s):null;return v.useEffect(()=>{h.current={items:c,offset:o}},[c,o]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:Y("tree-container",s!=null&&"marching-ants"),children:c.map(m=>{const{id:g,depth:p}=m;return r.jsx(rc,{id:g,value:g,depth:g===s&&d?d.depth:p,item:m,renderItem:e},g)})}),Cm.createPortal(r.jsx(bm,{dropAnimation:ZT,modifiers:[QT],className:"visibility-ordering-list",children:s!=null&&u?r.jsx(rc,{id:s,depth:u.depth,clone:!0,childCount:$T(c,s)+1,value:s.toString(),renderItem:e,item:u}):null}),document.body)]})}const eE={droppable:{strategy:ym.Always}},tE={activationConstraint:{distance:5}};function nE({items:c,indicator:e=!1,indentationWidth:t=30,onDragStart:n,onDragEnd:s,renderItem:i}){const[o,l]=v.useState(null),[a,d]=v.useState(null),[h,u]=v.useState(0),m=v.useMemo(()=>{const x=Jt(c);return o!=null?x.filter(({id:D,selected:M})=>D===o||!M):x},[o,c]),g=o!=null&&a!=null?Dl(m,o,a,h,t):null,p=v.useRef({items:m,offset:h}),C=v.useMemo(()=>({coordinateGetter:zT(p,e,t)}),[t,e]),f=Sm(cd(KT,tE),cd(Rm,C)),b=v.useMemo(()=>m.map(({id:x})=>x),[m]);v.useEffect(()=>{p.current={items:m,offset:h}},[m,h]);const w=v.useCallback(({active:{id:x}})=>{l(x),d(x),n?.(x),document.body.style.setProperty("cursor","grabbing")},[n]),S=v.useCallback(({delta:x})=>{u(x.x)},[]),T=v.useCallback(({over:x})=>{d(x?.id??null)},[]),y=v.useCallback(()=>{d(null),l(null),u(0),document.body.style.setProperty("cursor","")},[]),E=v.useCallback(({active:x,over:D})=>{if(y(),g&&D){const{depth:M,parentId:O}=g,H=JSON.parse(JSON.stringify(Jt(c))),L=H.findIndex(({id:j})=>j===D.id),V=H.findIndex(({id:j})=>j===x.id),U=H[V];H[V]={...U,depth:M,parentId:O},s?.(U,{...H[L],parentId:g.parentId})}},[c,s,g,y]),R=v.useCallback(()=>{y()},[y]);return r.jsx(wm,{sensors:f,collisionDetection:vm,measuring:eE,onDragStart:w,onDragMove:S,onDragOver:T,onDragEnd:E,onDragCancel:R,children:r.jsx(Tm,{items:b,strategy:Em,children:r.jsx(JT,{items:m,renderItem:i,indicator:e,indentationWidth:t,activeId:o,overId:a,offsetLeft:h})})})}function sE(c,e,t,n,s,i,o,l){const a=s.map((w,S)=>({...w,index:S}));let d=[],h=n;const u=i[0].data.visibleIndex,m=a.findIndex(({id:w})=>w===c.id),g=a.findIndex(({id:w})=>w===e.id);let p=Array.isArray(u)?u[1]+1:u+1;h=ms(i[0],e.parentId,h);for(let w=1;w<i.length;w+=1){const{data:{visibleIndex:S}}=i[w];d=_.moveItemOrRange(S,p,d,!0),p+=Array.isArray(S)?S[1]-S[0]+1:1,h=ms(i[w],e.parentId,h)}const C=[Array.isArray(u)?u[0]:u,p-1],f=Array.isArray(e.data.visibleIndex)?e.data.visibleIndex[0]:e.data.visibleIndex;let b=_.getVisibleIndex(f,d);return m>g&&b>f&&(b-=1),e.children.length>0&&(Array.isArray(u)?u[0]:u)<b&&(b-=1),C[0]<b&&(b-=C[1]-C[0]),d=_.moveItemOrRange(C,Oe(b,o,l),d),{groups:h,movedColumns:t.concat(d)}}function ms(c,e,t){if(c.parentId===e)return[...t];let n=t.map(a=>new dn(a));const s=new Map(n.map(a=>[a.name,a])),i=n.find(a=>a.name===c.parentId),o=n.find(a=>a.name===e),l=n.find(a=>a.name===c.id);if(i!=null&&(i.children=i.children.filter(a=>a!==c.id),i.children.length===0)){const a=new Set([i.name]),{parent:d=""}=i;let h=s.get(d);for(h?.removeChildren([i.name]);h&&h.children.length===0;){a.add(h.name);const u=h?.parent??"",m=s.get(u);m?.removeChildren([h.name]),h=m}n=n.filter(({name:u})=>!a.has(u))}return o?.addChildren([c.id]),l?.setParent(e??void 0),n}const iE=150;class pt extends v.Component{static SORTING_OPTIONS={DSC:"DSC",ASC:"ASC"};static MOVE_OPTIONS={TOP:"TOP",BOTTOM:"BOTTOM",UP:"UP",DOWN:"DOWN"};constructor(e){super(e),this.handleSearchInputChange=this.handleSearchInputChange.bind(this),this.searchColumns=this.searchColumns.bind(this),this.handleItemClick=this.handleItemClick.bind(this),this.handleDragEnd=this.handleDragEnd.bind(this),this.handleGroupDelete=this.handleGroupDelete.bind(this),this.handleGroupNameChange=this.handleGroupNameChange.bind(this),this.handleGroupCreate=this.handleGroupCreate.bind(this),this.validateGroupName=this.validateGroupName.bind(this),this.addColumnToSelected=this.addColumnToSelected.bind(this),this.handleDragStart=this.handleDragStart.bind(this),this.state={selectedColumns:new Set,lastSelectedColumn:"",searchFilter:""},this.list=null}componentWillUnmount(){this.debouncedSearchColumns.cancel()}list;debouncedSearchColumns=Ye(this.searchColumns,iE);resetVisibilityOrdering(){const{model:e,onReset:t,onMovedColumnsChanged:n,onColumnHeaderGroupChanged:s}=this.props;this.setState({selectedColumns:new Set,lastSelectedColumn:"",searchFilter:""}),t(),s(e.initialColumnHeaderGroups),n(e.initialMovedColumns)}resetSelection(){this.setState({selectedColumns:new Set,lastSelectedColumn:""})}handleSearchInputChange(e){const t=e.target.value;if(this.setState({searchFilter:t}),!t){this.debouncedSearchColumns.cancel(),this.resetSelection();return}this.debouncedSearchColumns(t)}searchColumns(e){const t=Jt(this.getTreeItems()),s=t.filter(({id:o,data:l})=>!(l.group?.isNew??!1)&&o.toLowerCase().includes(e.toLowerCase())).map(({id:o})=>o),i=t.findIndex(({id:o})=>o.toLowerCase().includes(e.toLowerCase()));this.addColumnToSelected(s,!1),s.length>0&&this.list?.querySelectorAll(".item-wrapper")[i]?.scrollIntoView({block:"center"})}moveSelectedColumns(e){const{columnHeaderGroups:t}=this.props,{selectedColumns:n}=this.state,s=Jt(this.getTreeItems());let i=this.getFirstMovableIndex(),o=this.getLastMovableIndex();N(i),N(o);const l=this.getSelectedParentItems();e===pt.MOVE_OPTIONS.UP||e===pt.MOVE_OPTIONS.TOP||l.reverse();let d=[],h=t;for(let u=0;u<l.length;u+=1){const{id:m,parentId:g,depth:p,data:{visibleIndex:C}}=l[u];switch(e){case pt.MOVE_OPTIONS.TOP:{d=_.moveItemOrRange(C,i,d,!0);const f=Array.isArray(C)?C[1]-C[0]+1:1;i+=f,h=ms(l[u],null,h);break}case pt.MOVE_OPTIONS.BOTTOM:{d=_.moveItemOrRange(C,o,d,!0);const f=Array.isArray(C)?C[1]-C[0]+1:1;o-=f,h=ms(l[u],null,h);break}case pt.MOVE_OPTIONS.UP:{const f=s.findIndex(S=>S.id===m),b=s.map((S,T)=>T<f&&!n.has(S.id)).lastIndexOf(!0),w=s[b];if(w!=null&&w.parentId!==g)if(Math.abs(w.depth-p)>1){const S=s.map((y,E)=>E<b&&y.depth===p).lastIndexOf(!0),T=s[S];h=ms(l[u],T.id,h)}else h=ms(l[u],w.parentId,h);else{const S=Oe(Array.isArray(C)?C[0]-1:C-1,i,o);d=_.moveItemOrRange(C,S,d,!1);const T=Array.isArray(C)?C[1]-C[0]+1:1;i+=T}break}case pt.MOVE_OPTIONS.DOWN:{const f=s.findIndex(T=>T.id===m),b=s.find((T,y)=>y>f&&!n.has(T.id));if(b?.parentId!==g){const T=s.find(y=>y.id===g);h=ms(l[u],T?.parentId??null,h);break}else if(b?.children.length>0){h=ms(l[u],b.id,h);break}const w=Oe(Array.isArray(C)?C[0]+1:C+1,i,o);d=_.moveItemOrRange(C,w,d,!1);const S=Array.isArray(C)?C[1]-C[0]+1:1;o-=S;break}}}return{newMoves:d,groups:h}}handleMoveColumns(e){const{onMovedColumnsChanged:t,movedColumns:n,onColumnHeaderGroupChanged:s}=this.props,{newMoves:i,groups:o}=this.moveSelectedColumns(e);let l;e===pt.MOVE_OPTIONS.TOP&&(l=()=>{this.list?.parentElement?.scroll({top:0})}),e===pt.MOVE_OPTIONS.BOTTOM&&(l=()=>{this.list?.parentElement?.scroll({top:this.list.parentElement.scrollHeight})}),s(o),i.length>0&&t(n.concat(i),l)}getSortMoves(e,t,n){const s=[...e],i=t===pt.SORTING_OPTIONS.ASC;s.sort((a,d)=>{const h=a.id.toUpperCase(),u=d.id.toUpperCase();return en.sort(h,u,i)});let o=[...n],l=Math.min(...s.flatMap(a=>{const{modelIndex:d}=a.data;return Array.isArray(d)?_.getVisibleIndexes(d,o):_.getVisibleIndex(d,o)}));for(let a=0;a<s.length;a+=1){const d=s[a],{modelIndex:h}=d.data,u=Array.isArray(h)?_.getVisibleIndexes(h,o):_.getVisibleIndex(h,o);o=Array.isArray(u)?_.moveRange([Math.min(...u),Math.max(...u)],l,o,!0):_.moveItem(u,l,o),Array.isArray(u)&&(o=this.getSortMoves(d.children,t,o)),l+=Array.isArray(h)?h.length:1}return o}handleSortColumns(e){const{model:t,onMovedColumnsChanged:n}=this.props,s=this.getSortMoves(this.getTreeItems(),e,t.initialMovedColumns);n(s)}handleItemClick(e,t){if(t.stopPropagation(),t.target instanceof HTMLElement&&(t.target.tagName==="BUTTON"||t.target.tagName==="INPUT"))return;t.currentTarget.focus();const{selectedColumns:n,lastSelectedColumn:s}=this.state,i=_.isModifierKeyDown(t),o=t.shiftKey,l=n.has(e),a=[e];if(l&&i){this.removeColumnFromSelected(e);return}const d=Jt(this.getTreeItems());if(l&&!o&&s===e){const h=d.find(({id:m})=>m===e);if(N(h),Jt(h.children).length+1===n.size){this.resetSelection();return}}if(o){const h=d.findIndex(m=>m.id===e),u=d.findIndex(m=>m.id===s);a.push(...d.slice(Math.min(u,h),Math.max(u,h)+1).map(m=>m.id))}this.addColumnToSelected(a,i||o),this.setState({lastSelectedColumn:e})}addColumnToSelected(e,t){const{selectedColumns:n}=this.state,s=new Set(t?[...n.values()].concat(e):e);Jt(this.getTreeItems()).forEach(({id:o,children:l})=>{s.has(o)&&l.forEach(a=>s.add(a.id))}),this.setState({selectedColumns:s})}removeColumnFromSelected(e){const{selectedColumns:t}=this.state,n=Jt(this.getTreeItems()),s=n.find(({id:o})=>o===e);N(s);let i=n.find(({id:o})=>o===s.parentId);for(Jt(s?.children).forEach(o=>t.delete(o.id));i!=null;){t.delete(i.id);const o=i.parentId;i=n.find(({id:l})=>l===o)}t.delete(e),this.setState({selectedColumns:new Set(t)})}handleDragStart(e){const{selectedColumns:t}=this.state;t.has(e)||this.addColumnToSelected([e],!1)}handleDragEnd(e,t){const{movedColumns:n,onMovedColumnsChanged:s,columnHeaderGroups:i,onColumnHeaderGroupChanged:o}=this.props,l=this.getSelectedParentItems(),a=Jt(this.getTreeItems()).map((g,p)=>({...g,index:p})),d=this.getFirstMovableIndex(),h=this.getLastMovableIndex();N(d),N(h);const{groups:u,movedColumns:m}=sE(e,t,n,i,a,l,d,h);o(u),s(m)}handleGroupNameChange(e,t){const{columnHeaderGroups:n,onColumnHeaderGroupChanged:s}=this.props,i=[...n],o=e.name,l=i.findIndex(({name:u})=>u===o),a=i[l];N(a);const d=new dn(a);d.name=t,i.splice(l,1,d);const h=i.findIndex(({name:u})=>u===d.parent);if(h>=0){const u=new dn(i[h]);u.removeChildren([o]),u.addChildren([t]),i.splice(h,1,u)}s(i)}handleGroupColorChange=vs((e,t)=>{const{columnHeaderGroups:n,onColumnHeaderGroupChanged:s}=this.props,i=[...n],o=new dn({...e,color:t});i.splice(i.findIndex(({name:l})=>l===e.name),1,o),s(i)},250);handleGroupDelete(e){const{columnHeaderGroups:t,onColumnHeaderGroupChanged:n}=this.props,s=t.filter(o=>o.name!==e.name),i=s.findIndex(o=>o.name===e.parent);if(i>=0){const o=new dn(s[i]);o.addChildren(e.children),o.removeChildren([e.name]),s.splice(i,1,o)}n(s)}handleGroupCreate(){const{movedColumns:e,onMovedColumnsChanged:t,onColumnHeaderGroupChanged:n}=this.props,{newMoves:s,groups:i}=this.moveSelectedColumns(pt.MOVE_OPTIONS.TOP),o=i.filter(u=>!u.isNew),l=this.getSelectedParentItems(),a=l.map(u=>u.data.modelIndex).flat().filter(u=>u>=0),d=`${dn.NEW_GROUP_PREFIX}-${Date.now()}`,h=new dn({name:d,children:l.map(({id:u})=>u),depth:0,childIndexes:[...new Set(a)]});t(e.concat(s),()=>{this.list?.parentElement?.scroll({top:0})}),n(o.concat([h])),this.resetSelection()}validateGroupName(e){const{model:t,columnHeaderGroups:n}=this.props,{columns:s}=t;return Ii.isValidColumnName(e)?s.some(({name:i})=>i===e)||n.some(({name:i})=>i===e)?"Duplicate name":"":"Invalid name"}renderItem=Re(({value:e,clone:t,item:n,ref:s,handleProps:i})=>{const{onColumnVisibilityChanged:o}=this.props,{selectedColumns:l}=this.state;let a=e;return t&&(a=this.getSelectedParentItems().map(({id:h})=>h).join(", ")),r.jsx(PT,{ref:s,value:a,clone:t,item:n,childCount:l.size,onVisibilityChange:o,onClick:this.handleItemClick,onGroupDelete:this.handleGroupDelete,onGroupColorChange:this.handleGroupColorChange,onGroupNameChange:this.handleGroupNameChange,validateGroupName:this.validateGroupName,handleProps:i})});getMemoizedFirstMovableIndex=Re((e,t,n)=>{for(let s=0;s<t.length;s+=1){const i=_.getModelIndex(s,n);if(e.isColumnMovable(i))return s}return null});getFirstMovableIndex(){const{model:e,movedColumns:t}=this.props;return this.getMemoizedFirstMovableIndex(e,e.columns,t)}getMemoizedLastMovableIndex=Re((e,t,n)=>{for(let s=t.length-1;s>=0;s-=1){const i=_.getModelIndex(s,n);if(e.isColumnMovable(i))return s}return null});getLastMovableIndex(){const{model:e,movedColumns:t}=this.props;return this.getMemoizedLastMovableIndex(e,e.columns,t)}memoizedGetTreeItems=Re((e,t,n,s,i)=>BT(e,t,n,s,[...i.values()]));getTreeItems(){const{model:e,movedColumns:t,hiddenColumns:n,columnHeaderGroups:s}=this.props,{selectedColumns:i}=this.state;return this.memoizedGetTreeItems(e.columns,t,s,n,i)}getSelectedParentItems(){const{selectedColumns:e}=this.state;return Jt(this.getTreeItems()).filter(({id:n,parentId:s})=>e.has(n)&&!e.has(s??""))}makeVisibilityOrderingList=Re((e,t)=>{const{movedColumns:n}=this.props,s=[],i=this.getFirstMovableIndex(),o=this.getLastMovableIndex(),l=t.findIndex(({data:h})=>Array.isArray(h.visibleIndex)?h.visibleIndex[0]===i:h.visibleIndex===i),a=t.findIndex(({data:h})=>Array.isArray(h.visibleIndex)?h.visibleIndex[1]===o:h.visibleIndex===o),d=t.slice(l,a+1);if(i==null||o===null){for(let h=0;h<e.length;h+=1){const u=_.getModelIndex(h,n),m=e[u];s.push(this.renderImmovableItem(m.name))}return s}for(let h=0;h<i;h+=1){const u=_.getModelIndex(h,n),m=e[u];s.push(this.renderImmovableItem(m.name))}i!==null&&i>0&&s.push(r.jsx("hr",{},"top-horizontal-divider")),s.push(r.jsx(nE,{items:d,renderItem:this.renderItem,onDragStart:this.handleDragStart,onDragEnd:this.handleDragEnd},"movable-items")),o!=null&&o<e.length-1&&s.push(r.jsx("hr",{},"bottom-horizontal-divider"));for(let h=o+1;h<e.length;h+=1){const u=_.getModelIndex(h,n),m=e[u];s.push(this.renderImmovableItem(m.name))}return s});renderImmovableItem=Re(e=>r.jsx("div",{className:"visibility-ordering-list-item immovable",children:r.jsx("div",{className:"column-item",children:r.jsx("span",{className:"column-name",children:e})})},e));render(){const{model:e,hiddenColumns:t,onColumnVisibilityChanged:n}=this.props,{selectedColumns:s,searchFilter:i}=this.state,o=s.size>0,l=this.getTreeItems(),a=new Map(Jt(l).map(C=>[C.id,C.data.modelIndex])),d=new Set(t),h=[...new Set(o?[...s.values()].map(C=>a.get(C)).filter(C=>C!=null).flat():l.map(C=>C.data.modelIndex).flat())],u=h.some(C=>!d.has(C)),m=u?"Hide All":"Show All",g=u?"Hide Selected":"Show Selected",p=this.makeVisibilityOrderingList(e.columns,l);return r.jsxs("div",{role:"menu",className:"visibility-ordering-builder",tabIndex:0,children:[r.jsxs("div",{className:"top-menu",children:[r.jsx(B,{kind:"ghost",className:"toggle-visibility-btn",onClick:()=>{n(h,!u)},icon:u?gr:nh,tooltip:"Toggle column visibility",children:o?g:m}),r.jsx(Di,{className:"visibility-search",value:i,matchCount:i?s.size:void 0,onChange:this.handleSearchInputChange})]}),r.jsxs("div",{className:"top-menu",children:[r.jsx(B,{kind:"ghost",icon:Ws,tooltip:"Reset to default",onClick:()=>{this.resetVisibilityOrdering()},children:"Reset"}),r.jsx("span",{className:"vertical-divider"}),r.jsx(B,{kind:"ghost",icon:ur,tooltip:"Sort ascending",onClick:()=>{this.handleSortColumns(pt.SORTING_OPTIONS.ASC)}}),r.jsx(B,{kind:"ghost",icon:mr,tooltip:"Sort descending",onClick:()=>{this.handleSortColumns(pt.SORTING_OPTIONS.DSC)}}),r.jsx("span",{className:"vertical-divider"}),r.jsxs(B,{kind:"ghost",tooltip:"Create group from selection",disabled:!o,onClick:this.handleGroupCreate,children:[r.jsxs("span",{className:"fa-layers",style:{marginRight:"0.75rem"},children:[r.jsx(ee,{mask:wg,icon:Ri,transform:"right-7 down-5 shrink-6"}),r.jsx(ee,{icon:vg,transform:"right-8 down-6 shrink-8"})]}),"Group"]}),r.jsx("span",{className:"vertical-divider"}),r.jsx(B,{kind:"ghost",icon:Tg,tooltip:"Move selection up",onClick:()=>{this.handleMoveColumns(pt.MOVE_OPTIONS.UP)},disabled:!o}),r.jsx(B,{kind:"ghost",icon:Eg,tooltip:"Move selection down",onClick:()=>{this.handleMoveColumns(pt.MOVE_OPTIONS.DOWN)},disabled:!o}),r.jsx(B,{kind:"ghost",icon:yg,tooltip:"Move selection to top",onClick:()=>{this.handleMoveColumns(pt.MOVE_OPTIONS.TOP)},disabled:!o}),r.jsx(B,{kind:"ghost",icon:Rg,tooltip:"Move selection to bottom",onClick:()=>{this.handleMoveColumns(pt.MOVE_OPTIONS.BOTTOM)},disabled:!o})]}),r.jsx("div",{role:"menu",className:Y("visibility-ordering-list"),children:r.jsx("div",{className:"column-list",ref:C=>{this.list=C},children:p})})]})}}const oE=pt;class lE extends v.PureComponent{static createSearchFilter(e,t,n,s){const i=s?n.filter(o=>!t.includes(o.name)).map(o=>o.name):t;if(e&&i.length>0){const o=I.FilterValue.ofString(e);return i.length===n.length?I.FilterCondition.search(o):I.FilterCondition.search(o,n.filter(a=>i.includes(a.name)).map(a=>a.filter()))}}constructor(e){super(e),this.handleSearchValueChange=this.handleSearchValueChange.bind(this),this.toggleColumn=this.toggleColumn.bind(this),this.selectAll=this.selectAll.bind(this),this.clear=this.clear.bind(this),this.selectNumbers=this.selectNumbers.bind(this),this.searchField=de.createRef(),this.state={isConfigureColumnsShown:!1}}searchField;focus(){this.searchField.current?.focus()}handleSearchValueChange(e){const{onChange:t,selectedColumns:n,invertSelection:s}=this.props;t(e.target.value,n,s)}sendColumnChange(e,t){const{onChange:n,value:s}=this.props;n(s,e,t)}setInvertSelection(e){const{onChange:t,value:n}=this.props;t(n,[],e)}toggleColumn(e){const{selectedColumns:t,invertSelection:n}=this.props;if(t.includes(e))this.sendColumnChange(t.filter(s=>s!==e),n);else{const s=t.slice();s.push(e),this.sendColumnChange(s,n)}}selectAll(){this.setInvertSelection(!0)}clear(){this.setInvertSelection(!1)}selectNumbers(){const{columns:e}=this.props;this.sendColumnChange(e.filter(t=>F.isNumberType(t.type)).map(t=>t.name),!1)}render(){const{value:e,selectedColumns:t,invertSelection:n,columns:s}=this.props,{isConfigureColumnsShown:i}=this.state,o=t.length===0&&n===!0||t.length===s.length&&n===!1,l=t.length===0&&n===!1||t.length===s.length&&n===!0;let a;return o?a=r.jsxs(r.Fragment,{children:[r.jsx(ee,{icon:cl,mask:pa,transform:"shrink-2 down-5 right-7"}),r.jsx(ee,{icon:xg,className:"text-primary",transform:"shrink-4 down-5 right-7"})]}):l?a=r.jsxs(r.Fragment,{children:[r.jsx(ee,{icon:Ri,mask:pa,transform:"shrink-1 down-5 right-7"}),r.jsx(ee,{icon:wd,className:"text-danger",transform:"shrink-4 down-5 right-7"})]}):a=r.jsxs(r.Fragment,{children:[r.jsx(ee,{icon:cl,mask:pa,transform:"shrink-2 down-5 right-7"}),r.jsx(ee,{icon:Dg,className:"text-primary",transform:"shrink-4 down-5 right-7"})]}),r.jsxs("div",{className:"cross-column-container",children:[r.jsx(Di,{className:"cross-column-search",placeholder:"Search Data...",value:e,onChange:this.handleSearchValueChange,ref:this.searchField}),r.jsxs("button",{type:"button",className:"btn btn-link btn-link-icon px-2",onClick:()=>{i?this.setState({isConfigureColumnsShown:!1}):this.setState({isConfigureColumnsShown:!0})},children:[r.jsx("div",{className:"fa-layers",children:a}),r.jsx(ot,{children:"Configure Columns"}),r.jsx(Vl,{isShown:i,className:"cross-column-popper",onExited:()=>{this.setState({isConfigureColumnsShown:!1})},closeOnBlur:!0,interactive:!0,children:r.jsxs("div",{className:"cross-column-popup",children:["Searched Columns",r.jsx("div",{className:"cross-column-scroll",children:s.map(d=>r.jsxs(de.Fragment,{children:[r.jsx(nn,{className:"cross-column-checkbox",checked:n?!t.includes(d.name):t.includes(d.name),onChange:()=>this.toggleColumn(d.name),children:d.name}),d.type.substring(d.type.lastIndexOf(".")+1)]},d.name))}),r.jsxs("div",{className:"cross-column-button-bar",children:[r.jsx("button",{type:"button",className:"btn btn-link",onClick:this.selectAll,children:"Select All"}),r.jsx("button",{type:"button",className:"btn btn-link",onClick:this.clear,children:"Clear"}),r.jsx("button",{type:"button",className:"btn btn-link",onClick:this.selectNumbers,children:"Numbers Only"})]}),l&&r.jsxs("p",{className:"text-danger",children:[r.jsx(ee,{icon:wd})," Select at least one column to search."]})]})})]})]})}}const Ko=lE;const ls=ne.module("PartitionSelectorSearch"),aE=150;class Vr extends v.Component{static MAX_VISIBLE_ITEMS=12;static defaultProps={initialPageSize:100,onSelect:()=>{},onListResized:()=>{}};static propTypes={getFormattedString:z.func.isRequired,table:z.shape({addEventListener:z.func.isRequired,removeEventListener:z.func.isRequired,columns:z.arrayOf(z.shape({name:z.string.isRequired,type:z.string.isRequired,filter:z.func.isRequired})),size:z.number.isRequired,applyFilter:z.func.isRequired,setViewport:z.func.isRequired}).isRequired,initialPageSize:z.number,onSelect:z.func,onListResized:z.func};static handleError(e){e instanceof Hl||ls.error(e)}constructor(e){super(e),this.handleFilterChange=this.handleFilterChange.bind(this),this.handleInputFocus=this.handleInputFocus.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleListKeydown=this.handleListKeydown.bind(this),this.handleSelect=this.handleSelect.bind(this),this.handleTableUpdate=this.handleTableUpdate.bind(this),this.handleTextChange=this.handleTextChange.bind(this),this.handleViewportChange=this.handleViewportChange.bind(this),this.itemList=null,this.searchInput=null,this.timer=null,this.state={offset:0,itemCount:0,items:[],text:"",isLoading:!0}}componentDidMount(){this.startListening()}componentDidUpdate(e,t){const{isLoading:n,itemCount:s}=this.state,{onListResized:i}=this.props;(s!==t.itemCount||n!==t.isLoading)&&i()}componentWillUnmount(){this.debounceUpdateFilter.cancel(),this.stopListening()}itemList;searchInput;timer;handleKeyDown(e){if(this.itemList==null)return!1;const{items:t,itemCount:n}=this.state;switch(e.key){case"Enter":{let s=null;if(t.length>0)s=t[0].value;else{const{text:i}=this.state;s=i.trim()}if(s.length>0){const{onSelect:i}=this.props;i(s)}return e.stopPropagation(),e.preventDefault(),!0}case"ArrowDown":return n>0&&this.itemList.focusItem(1),e.stopPropagation(),e.preventDefault(),!0;default:return!1}}handleListKeydown(e){switch(e.key){case"Escape":break;default:this.focus();break}}handleFilterChange(){ls.debug2("handleFilterChange");const{table:e}=this.props,t=e.size;this.setState({itemCount:t,isLoading:!0})}handleInputFocus(){this.itemList&&this.itemList.focusItem(0)}handleSelect(e){ls.debug2("handleSelect",e);const{onSelect:t}=this.props,{offset:n,items:s}=this.state,i=e-n;if(i<0||s.length<=i){ls.error("No data for item",e);return}const{value:o}=s[i];t(o)}handleTableUpdate(e){const t=e.detail,{offset:n}=t,s=[],{getFormattedString:i,table:o}=this.props,l=o.columns[0];for(let d=0;d<t.rows.length;d+=1){const u=t.rows[d].get(l),m=i(u,l.type,l.name);s.push({displayValue:m,value:u})}const a=o.size;ls.debug2("handleTableUpdate",a,n,s.length),this.setState({itemCount:a,items:s,offset:n,isLoading:!1})}handleTextChange(e){ls.debug2("handleTextChange");const{value:t}=e.target;this.setState({text:t}),this.debounceUpdateFilter()}handleViewportChange(e,t){ls.debug2("handleViewportChange",e,t);const n=Math.max(1,t-e),s=Math.max(0,e-n),i=t+n,{table:o}=this.props;o.setViewport(s,i)}debounceUpdateFilter=Ye(()=>{this.updateFilter()},aE);focus(){this.searchInput&&this.searchInput.focus()}startListening(){const{initialPageSize:e,table:t}=this.props;t.addEventListener(I.Table.EVENT_UPDATED,this.handleTableUpdate),t.addEventListener(I.Table.EVENT_FILTERCHANGED,this.handleFilterChange),t.setViewport(0,e)}stopListening(){const{table:e}=this.props;e.removeEventListener(I.Table.EVENT_UPDATED,this.handleTableUpdate),e.removeEventListener(I.Table.EVENT_FILTERCHANGED,this.handleFilterChange)}updateFilter(){const{initialPageSize:e,table:t}=this.props,{text:n}=this.state,s=n.trim(),i=[];if(s.length>0){const l=t.columns[0].filter().invoke("matches",I.FilterValue.ofString(`(?s)(?i).*\\Q${s}\\E.*`));i.push(l)}ls.debug2("updateFilter",i),t.applyFilter(i),t.setViewport(0,e)}render(){const{isLoading:e,itemCount:t,items:n,offset:s,text:i}=this.state,o=Math.min(t,Vr.MAX_VISIBLE_ITEMS)*yi.DEFAULT_ROW_HEIGHT+11;return r.jsxs("div",{className:"iris-grid-partition-selector-search",children:[r.jsx("div",{className:"search-container",children:r.jsx("input",{type:"text",ref:l=>{this.searchInput=l},value:i,placeholder:"Available Partitions",onChange:this.handleTextChange,onFocus:this.handleInputFocus,onKeyDown:this.handleKeyDown,className:"form-control input-partition"})}),!e&&t>0&&r.jsx("div",{className:"iris-grid-partition-selector-search-list",onKeyDown:this.handleListKeydown,role:"presentation",style:{height:o},children:r.jsx(yi,{ref:l=>{this.itemList=l},itemCount:t,items:n,offset:s,onSelect:this.handleSelect,onViewportChange:this.handleViewportChange})}),!e&&t===0&&r.jsx("div",{className:"iris-grid-partition-selector-search-empty",children:"No results"}),e&&r.jsxs("div",{className:"iris-grid-partition-selector-loading",children:[r.jsx(In,{})," Loading..."]})]})}}const rE=Vr;const di=ne.module("IrisGridPartitionSelector"),dE=250;class cE extends v.Component{static defaultProps={onAppend:()=>{},onChange:()=>{},onFetchAll:()=>{},onDone:()=>{},partition:""};constructor(e){super(e),this.handleAppendClick=this.handleAppendClick.bind(this),this.handleCloseClick=this.handleCloseClick.bind(this),this.handleIgnoreClick=this.handleIgnoreClick.bind(this),this.handlePartitionChange=this.handlePartitionChange.bind(this),this.handlePartitionSelect=this.handlePartitionSelect.bind(this),this.handlePartitionListResized=this.handlePartitionListResized.bind(this),this.handleSearchOpened=this.handleSearchOpened.bind(this),this.handleSearchClosed=this.handleSearchClosed.bind(this),this.searchMenu=null,this.selectorSearch=null;const{partition:t}=e;this.state={partition:t}}componentWillUnmount(){this.debounceUpdate.cancel()}searchMenu;selectorSearch;handleAppendClick(){di.debug2("handleAppendClick");const{onAppend:e}=this.props,{partition:t}=this.state;e(t)}handleCloseClick(){di.debug2("handleCloseClick"),this.sendDone()}handleIgnoreClick(){di.debug2("handleIgnoreClick"),this.sendFetchAll()}handlePartitionChange(e){di.debug2("handlePartitionChange");const{value:t}=e.target;this.setState({partition:t}),this.debounceUpdate()}handlePartitionSelect(e){this.searchMenu&&this.searchMenu.closeMenu(),this.setState({partition:e},()=>{this.sendUpdate()})}handlePartitionListResized(){this.searchMenu&&this.searchMenu.scheduleUpdate()}handleSearchClosed(){const{table:e}=this.props;e.applyFilter([])}handleSearchOpened(){this.selectorSearch&&this.selectorSearch.focus()}debounceUpdate=Ye(()=>{this.sendUpdate()},dE);sendDone(){this.debounceUpdate.flush();const{onDone:e}=this.props;e()}sendUpdate(){di.debug2("sendUpdate");const{onChange:e}=this.props,{partition:t}=this.state;e(t)}sendFetchAll(){di.debug2("sendFetchAll"),this.debounceUpdate.cancel();const{onFetchAll:e}=this.props;e()}render(){const{columnName:e,getFormattedString:t,onDone:n,table:s}=this.props,{partition:i}=this.state,o=r.jsx(rE,{getFormattedString:t,table:s,onSelect:this.handlePartitionSelect,onListResized:this.handlePartitionListResized,ref:l=>{this.selectorSearch=l}},"search");return r.jsxs("div",{className:"iris-grid-partition-selector",children:[r.jsx("div",{className:"status-message",children:r.jsxs("span",{children:['Filtering "',e,'" partition to']})}),r.jsxs("div",{className:"input-group",children:[r.jsx("input",{type:"text",value:i,onChange:this.handlePartitionChange,className:"form-control input-partition"}),r.jsx("div",{className:"input-group-append",children:r.jsxs("button",{type:"button",className:"btn btn-outline-primary",children:[r.jsx(ee,{icon:Un}),r.jsx(ot,{children:"Partitions"}),r.jsx(Vn,{ref:l=>{this.searchMenu=l},actions:[{menuElement:o}],onMenuOpened:this.handleSearchOpened,onMenuClosed:this.handleSearchClosed})]})})]}),r.jsx("div",{className:"iris-grid-partition-selector-spacer"}),r.jsx("button",{type:"button",className:"btn btn-outline-primary btn-ignore",onClick:this.handleIgnoreClick,children:"Ignore & Fetch All"}),r.jsx("button",{type:"button",className:"btn btn-outline-primary btn-append",onClick:this.handleAppendClick,children:"Append Command"}),r.jsx("button",{type:"button",className:"btn btn-link btn-link-icon btn-close",onClick:n,children:r.jsx(ee,{icon:uo})})]})}}const hE=cE;const uE=ne.module("SelectDistinctBuilder");class mE extends v.Component{static defaultProps={selectDistinctColumns:[],onChange:()=>{}};constructor(e){super(e),this.handleAddColumnClick=this.handleAddColumnClick.bind(this),this.handleDeleteColumn=this.handleDeleteColumn.bind(this),this.handleDropdownChanged=this.handleDropdownChanged.bind(this);const{model:t,selectDistinctColumns:n}=this.props;this.state={inputs:n.length>0?[...n]:[""],columns:t.originalColumns}}componentDidUpdate(e,t){const{inputs:n}=this.state,{onChange:s}=this.props;if(t.inputs!==n){const i=n.filter(o=>o!=="");st(t.inputs.filter(o=>o!==""),i)||s(i)}}handleAddColumnClick(){this.setState(({inputs:e})=>({inputs:[...e,""]}))}handleDeleteColumn(e){this.setState(({inputs:t})=>({inputs:t.length===1&&e===0?[""]:t.filter((n,s)=>e!==s)}))}handleDropdownChanged(e,t){uE.debug("handleDropdownChanged",e,t);const{value:n}=t.target;this.setState(({inputs:s})=>{const i=[...s];return i[e]=n,{inputs:i}})}renderInputs(){const{columns:e,inputs:t}=this.state;return t.map((n,s)=>{const i=e.filter(({name:o})=>o===n||!t.includes(o)).map(({name:o})=>r.jsx("option",{value:o,children:o},o));return r.jsxs("div",{className:"form-inline px-3 pb-3",children:[r.jsxs("select",{className:"form-control custom-select col",value:n,onChange:o=>this.handleDropdownChanged(s,o),children:[r.jsx("option",{value:"",children:"Select a column"}),i]}),(t.length>1||n!=="")&&r.jsx(B,{kind:"ghost",className:"ml-1 px-2",onClick:()=>{this.handleDeleteColumn(s)},icon:r.jsx(ee,{icon:Gt,transform:"grow-3"}),tooltip:"Delete column"})]},s)})}render(){const{columns:e,inputs:t}=this.state,n=t.length>=e.length;return r.jsxs("div",{role:"presentation",className:"select-distinct-builder-container h-100",children:[r.jsx("div",{className:"select-distinct-title",children:"Display Unique Values From"}),this.renderInputs(),r.jsx("hr",{}),r.jsx("div",{className:"pt-1 px-3",children:r.jsx(B,{kind:"ghost",className:"btn-add-column",onClick:this.handleAddColumnClick,disabled:n,icon:Es,children:"Add Additional Column"})}),r.jsx("div",{className:"select-distinct-builder-footer",children:r.jsx("div",{className:"select-distinct-builder-hint",children:"Display only unique values from the selected table columns. Note that this will reset any filters and display only the selected columns."})})]})}}const gE=mE;function $r({items:c,onChange:e=()=>{}}){return r.jsx(Gc,{items:Array.from(c.entries()).map(([t,n])=>({title:$r.getAdvancedSettingsTitleForKey(t),isOn:n,onChange:s=>e(t,s)}))})}$r.getAdvancedSettingsTitleForKey=c=>{switch(c){case xi.FILTER_CONTROL_CHANGE_CLEARS_ALL_FILTERS:return"Clear current table filters before applying new filters from a control";case xi.LINK_CHANGE_CLEARS_ALL_FILTERS:return"Clear current table filters before applying new filters from an incoming link filter"}};const dc=ne.module("ConditionalFormattingMenu"),Da=()=>{};function pE(c){const{column:{type:e}}=c;if(F.isNumberType(e))return c.condition===$e.IS_NULL||c.condition===$e.IS_NOT_NULL?"":`${c.value}`;if(F.isCharType(e))return c.condition===Ft.IS_NULL||c.condition===Ft.IS_NOT_NULL?"":`${c.value}`;if(F.isStringType(e))return c.condition===Bt.IS_NULL||c.condition===Bt.IS_NOT_NULL?"":`"${c.value}"`;if(F.isDateType(e))return c.condition===Ft.IS_NULL||c.condition===Ft.IS_NOT_NULL?"":`${c.value}`;if(F.isBooleanType(e))return"";throw new Error(`Invalid column type ${e} in getRuleValue`)}function fE(c){return F.isNumberType(c.column.type)&&c.condition===$e.IS_BETWEEN?`${c.start} < ${c.column.name} < ${c.end}`:`${c.column.name} ${Gw(c.column.type,c.condition)}
30
- ${pE(c)}`}function CE(c){const{rules:e=[],onChange:t=Da,onCreate:n=Da,onSelect:s=Da}=c,i=v.useCallback((d,h,u)=>{d.stopPropagation(),dc.debug("Rule clicked",h,u),s(u)},[s]),o=v.useCallback((d,h,u)=>{d.stopPropagation(),dc.debug("Delete button clicked",h,u);const m=[...e];m.splice(u,1),t(m)},[t,e]),l=v.useCallback(d=>{d.stopPropagation()},[]),a=v.useCallback(d=>{if(hn.stopDragging(),d.destination==null)return;const h=d.source.index,u=d.destination.index,m=[...e],g=e[h];m.splice(h,1),m.splice(u,0,g),t(m)},[t,e]);return r.jsxs("div",{className:"conditional-formatting-rules",children:[r.jsx(Pl,{onDragStart:hn.startDragging,onDragEnd:a,children:r.jsx(or,{droppableId:"droppable-custom-columns",children:(d,h)=>r.jsxs("div",{ref:d.innerRef,...d.droppableProps,className:Y("droppable-container",{dragging:h.draggingFromThisWith}),children:[e.length===0&&r.jsx("div",{className:"text-muted pl-2",children:"No formats defined"}),e.map((u,m)=>r.jsx(Uc,{draggableId:`${m}-${u.type}`,index:m,disableInteractiveElementBlocking:!0,children:(g,p)=>r.jsx("div",{role:"menuitem",tabIndex:0,onClick:C=>i(C,u,m),className:Y("draggable-container",{dragging:p.isDragging}),ref:g.innerRef,...g.draggableProps,children:r.jsx("div",{className:"conditional-formatting-list-item",children:r.jsxs("div",{className:"formatting-item",children:[r.jsx("div",{className:"rule-icon",children:r.jsx("span",{className:"rule-icon-bg",style:{backgroundColor:Tl(u.config.style),color:El(u.config.style)},children:u.type===Dn.ROWS?"row":"col"})}),r.jsx("div",{className:"rule-title",children:fE(u.config)}),r.jsx(B,{kind:"ghost",className:"ml-1 px-2",onClick:C=>o(C,u,m),icon:Gt,tooltip:"Delete rule"}),r.jsxs("button",{type:"button",className:"btn btn-link btn-link-icon px-2 btn-drag-handle",onClick:l,...g.dragHandleProps,children:[r.jsx(ot,{children:"Drag to re-order"}),r.jsx(ee,{icon:Wl})]})]})})})},`${m}-${u.type}`)),d.placeholder]})})}),r.jsx("hr",{}),r.jsx(B,{kind:"ghost",onClick:n,icon:Es,children:"Add New Rule"})]})}const Ls=ne.module("ConditionEditor"),bE=()=>{},SE=[$e.IS_EQUAL,$e.IS_NOT_EQUAL,$e.IS_BETWEEN,$e.GREATER_THAN,$e.GREATER_THAN_OR_EQUAL,$e.LESS_THAN,$e.LESS_THAN_OR_EQUAL,$e.IS_NULL,$e.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:Nw(c)},c)),wE=[Bt.IS_EXACTLY,Bt.IS_NOT_EXACTLY,Bt.CONTAINS,Bt.DOES_NOT_CONTAIN,Bt.STARTS_WITH,Bt.ENDS_WITH,Bt.IS_NULL,Bt.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:kw(c)},c)),vE=[Ft.IS_EXACTLY,Ft.IS_NOT_EXACTLY,Ft.IS_BEFORE,Ft.IS_BEFORE_OR_EQUAL,Ft.IS_AFTER,Ft.IS_AFTER_OR_EQUAL,Ft.IS_NULL,Ft.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:Mw(c)},c)),TE=[Xi.IS_TRUE,Xi.IS_FALSE,Xi.IS_NULL,Xi.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:Lw(c)},c)),EE=[zs.IS_EQUAL,zs.IS_NOT_EQUAL,zs.IS_NULL,zs.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:Ow(c)},c));function yE(c,e,t,n){return c===$e.IS_NULL||c===$e.IS_NOT_NULL||c===$e.IS_BETWEEN&&t!=null&&t!==""&&!Number.isNaN(Number.parseFloat(t))&&n!=null&&n!==""&&!Number.isNaN(Number.parseFloat(n))||c!==$e.IS_BETWEEN&&e!==void 0&&e!==""&&!Number.isNaN(Number.parseFloat(e))}function RE(c,e,t,n,s,i,o){switch(c){case $e.IS_EQUAL:case $e.IS_NOT_EQUAL:case $e.GREATER_THAN:case $e.GREATER_THAN_OR_EQUAL:case $e.LESS_THAN:case $e.LESS_THAN_OR_EQUAL:return r.jsx("input",{type:"number",className:"form-control",placeholder:"Enter value",value:s??"",onChange:e});case $e.IS_BETWEEN:return r.jsxs("div",{className:"d-flex flex-row",children:[r.jsx("input",{type:"number",className:"form-control d-flex mr-2",placeholder:"Start value",value:i??"",onChange:t}),r.jsx("input",{type:"number",className:"form-control d-flex",placeholder:"End value",value:o??"",onChange:n})]});case $e.IS_NULL:case $e.IS_NOT_NULL:return null}}function xE(c,e,t){switch(c){case Bt.IS_NULL:case Bt.IS_NOT_NULL:return null;default:return r.jsx("input",{type:"text",className:"form-control",placeholder:"Enter value",value:t??"",onChange:e})}}function DE(c,e,t){switch(c){case Ft.IS_NULL:case Ft.IS_NOT_NULL:return null;default:return r.jsx("input",{type:"text",className:"form-control",placeholder:"Enter value",value:t??"",onChange:e})}}function IE(){return null}function FE(c,e,t){switch(c){case zs.IS_NULL:case zs.IS_NOT_NULL:return null;default:return r.jsx("input",{type:"text",className:"form-control",maxLength:1,placeholder:"Enter value",value:t??"",onChange:e})}}function Lu(c){const{column:e,config:t,onChange:n=bE}=c,s=e.type,[i,o]=v.useState(s),[l,a]=v.useState(t.condition),[d,h]=v.useState(t.value),[u,m]=v.useState(t.start),[g,p]=v.useState(t.end);s!==i&&(a(bu(s)),h(Su(s)),m(void 0),p(void 0),o(s));const C=v.useMemo(()=>{if(s===void 0)return[];if(F.isNumberType(s))return SE;if(F.isCharType(s))return EE;if(F.isStringType(s))return wE;if(F.isDateType(s))return vE;if(F.isBooleanType(s))return TE},[s]),f=v.useCallback(y=>{const{value:E}=y.target;Ls.debug("handleConditionChange",E),a(E)},[]),b=v.useCallback(y=>{const{value:E}=y.target;Ls.debug("handleValueChange",E),h(E)},[]),w=v.useCallback(y=>{const{value:E}=y.target;Ls.debug("handleStartValueChange",E),m(E)},[]),S=v.useCallback(y=>{const{value:E}=y.target;Ls.debug("handleEndValueChange",E),p(E)},[]);v.useEffect(function(){let E=!0;l===void 0?(Ls.debug("Unable to create formatting rule. Condition is not selected."),E=!1):F.isNumberType(e.type)&&!yE(l,d,u,g)?(Ls.debug("Unable to create formatting rule. Invalid value",d),E=!1):F.isDateType(e.type)&&!Kw(l,d)&&(Ls.debug("Unable to create formatting rule. Invalid date condition",d),E=!1),n({condition:l,value:d,start:u,end:g},E)},[n,e.type,l,d,u,g]);const T=v.useMemo(()=>{if(s===void 0)return null;if(F.isNumberType(s))return RE(l,b,w,S,d,u,g);if(F.isCharType(s))return FE(l,b,d);if(F.isStringType(s))return xE(l,b,d);if(F.isDateType(s))return DE(l,b,d);if(F.isBooleanType(s))return IE()},[s,l,d,u,g,b,w,S]);return r.jsxs("div",{className:"condition-editor mb-2",children:[r.jsx("select",{value:l,id:"condition-select",className:"custom-select mb-2",onChange:f,children:C}),T]})}const NE=ne.module("StyleEditor"),kE="#fcfcfa",ME="#f0f0ee",LE="#1a171a",OE=200,AE=()=>{};function Ou(c){const{config:e,onChange:t=AE}=c,[n,s]=v.useState(e.type),[i,o]=v.useState(e.customConfig?.background??kE),[l,a]=v.useState(!1),[d,h]=v.useState(OE),u=v.useRef(null),m=v.useCallback(S=>{const{value:T}=S.target;NE.debug("handleBackgroundChange",T),o(T)},[]),g=v.useCallback(()=>{l&&a(!1)},[l]),p=v.useCallback(()=>{l||f(),a(!l)},[l]),C=v.useMemo(()=>[on.NO_FORMATTING,on.POSITIVE,on.NEGATIVE,on.WARN,on.NEUTRAL,on.ACCENT_1,on.ACCENT_2,on.CUSTOM],[]);function f(){u.current&&h(u.current.getBoundingClientRect().width)}v.useEffect(function(){t({type:n,customConfig:{color:lh.isDark(i)?ME:LE,background:i}})},[t,n,i]);const b=v.useCallback(()=>{const S=[];for(let T=0;T<C.length;T+=1){const y=C[T],E=`option-${T}-${y}`;S.push(r.jsxs(B,{kind:"inline",className:"style-option-btn",onClick:()=>{s(y),a(!1)},style:{color:El({type:y}),background:Tl({type:y})},children:[y===n&&r.jsx(ee,{icon:zn,className:"mr-2"}),y!==n&&r.jsx("span",{className:"mr-4"}),Jd(y)]},E))}return S},[C,n]),w=v.useCallback(()=>r.jsx("div",{className:"style-menu-container",role:"presentation",style:{width:d},children:r.jsx("div",{className:"style-options",children:b()})}),[d,b]);return r.jsxs("div",{className:"style-editor",children:[r.jsxs("div",{className:"mb-2",ref:u,children:[r.jsx("label",{className:"mb-0",children:"Style"}),r.jsxs(B,{kind:"inline",className:"cs-dropdown",style:{color:El({type:n}),background:Tl({type:n})},onClick:p,children:[Jd(n),r.jsx("span",{children:r.jsx(ee,{icon:Ig,className:"cs-caret"})}),r.jsx(Vn,{isShown:l,actions:{menuElement:w()},popperOptions:{placement:"bottom-start"},popperClassName:"style-dropdown-menu",onMenuClosed:g,menuStyle:{maxWidth:"100rem"}})]})]}),n===on.CUSTOM&&r.jsxs("div",{className:"mb-2",children:[r.jsx("label",{className:"mb-0",children:"Background"}),r.jsx("input",{type:"color",value:i,className:"custom-select color-select",onChange:m})]})]})}const Vi=ne.module("ColumnFormatEditor"),_E=()=>{};function PE(c){const{type:e,name:t}=c[0];return{column:{type:e,name:t},style:vu(),...na(e)}}function jE(c){const{columns:e,config:t=PE(e),onChange:n=_E}=c,[s,i]=v.useState(e.find(f=>f.name===t.column.name&&f.type===t.column.type)??e[0]),[o,l]=v.useState(wu(t)),[a,d]=v.useState(!1),[h,u]=v.useState(t.style),m=v.useCallback(f=>{const b=e.find(({name:w})=>w===f);b!==void 0?(i(b),s.type!==b.type&&(l(na(b.type)),d(!1))):Vi.error(`Column ${f} not found.`)},[e,s]),g=v.useCallback((f,b)=>{Vi.debug("handleConditionChange",f,b),l(f),d(b)},[]),p=v.useCallback(f=>{Vi.debug("handleStyleChange",f),u(f)},[]);v.useEffect(function(){let b=a;s===void 0&&(Vi.debug("Column is not selected, invalidating update."),b=!1),(h===void 0||h.type===on.NO_FORMATTING)&&(Vi.debug("Style is not selected, invalidating update."),b=!1);const{type:w,name:S}=s;n({column:{type:w,name:S},style:h,...o},b)},[n,s,h,o,a]);const C=e.map(({name:f})=>({title:f,value:f}));return r.jsxs("div",{className:"conditional-rule-editor form",children:[r.jsxs("div",{className:"mb-2",children:[r.jsx("label",{className:"mb-0",children:"Format Cell If"}),r.jsx(zc,{defaultValue:s?.name,options:C,inputPlaceholder:"Select a column",spellCheck:!1,onChange:m,searchPlaceholder:"Filter columns"})]}),s!==void 0&&r.jsxs(r.Fragment,{children:[r.jsx(Lu,{column:s,config:o,onChange:g}),r.jsx(Ou,{config:h,onChange:p})]})]})}const $i=ne.module("RowFormatEditor"),HE=()=>{};function BE(c){const{type:e,name:t}=c[0];return{column:{type:e,name:t},style:vu(),...na(e)}}function UE(c){const{columns:e,config:t=BE(e),onChange:n=HE}=c,[s,i]=v.useState(e.find(f=>f.name===t.column.name&&f.type===t.column.type)??e[0]),[o,l]=v.useState(wu(t)),[a,d]=v.useState(!1),[h,u]=v.useState(t.style),m=v.useCallback(f=>{const b=e.find(({name:w})=>w===f);b!==void 0?(i(b),s.type!==b.type&&(l(na(b.type)),d(!1))):$i.error(`Column ${f} not found.`)},[e,s]),g=v.useCallback((f,b)=>{$i.debug("handleConditionChange",f,b),l(f),d(b)},[]),p=v.useCallback(f=>{$i.debug("handleStyleChange",f),u(f)},[]);v.useEffect(function(){if(s===void 0){$i.debug("Column is not selected, skip update.");return}if(h===void 0){$i.debug("Style is not selected, skip update.");return}const{type:b,name:w}=s;n({column:{type:b,name:w},style:h,...o},a)},[n,s,h,o,a]);const C=e.map(({name:f})=>({title:f,value:f}));return r.jsxs("div",{className:"conditional-rule-editor form",children:[r.jsxs("div",{className:"mb-2",children:[r.jsx("label",{className:"mb-0",children:"Format Row If"}),r.jsx(zc,{defaultValue:s?.name,options:C,inputPlaceholder:"Select a column",spellCheck:!1,onChange:m,searchPlaceholder:"Filter columns"})]}),s!==void 0&&r.jsxs(r.Fragment,{children:[r.jsx(Lu,{column:s,config:o,onChange:g}),r.jsx(Ou,{config:h,onChange:p})]})]})}const Ia=ne.module("ConditionalFormatEditor"),Fa=()=>{};function VE(c){switch(c){case Dn.CONDITIONAL:return r.jsx(wT,{});case Dn.ROWS:return r.jsx(vT,{})}}function $E(c){switch(c){case Dn.CONDITIONAL:return"Conditional";case Dn.ROWS:return"Rows"}}const cc=[Dn.CONDITIONAL,Dn.ROWS];function WE(c){const{columns:e,onSave:t=Fa,onUpdate:n=Fa,onCancel:s=Fa,rule:i}=c,o=e.filter(Yw),[l,a]=v.useState(i?.type??cc[0]),[d,h]=v.useState(i),[u,m]=v.useState(!1),g=v.useCallback(()=>{s()},[s]),p=v.useCallback(()=>{if(d===void 0){Ia.error("Rule is not defined.");return}t(d)},[t,d]),C=v.useCallback(b=>{Ia.debug("handleFormatterChange",b),a(b)},[]),f=v.useCallback((b,w)=>{Ia.debug("handleRuleChange",b,w,l);const S={type:l,config:b};h(S),m(w),n(w?S:void 0)},[n,l]);return r.jsxs("div",{className:"conditional-format-editor form",children:[r.jsxs("div",{className:"mb-2",children:[r.jsx("label",{className:"mb-0",htmlFor:"formatter-select",children:"Select Formatter"}),r.jsx("div",{className:"formatter-list",children:cc.map((b,w)=>r.jsx("div",{className:"formatter-type",children:r.jsxs("button",{type:"button",className:Y("btn","btn-icon","btn-formatter-type",{active:b===l}),"data-index":w,onClick:()=>C(b),children:[VE(b),$E(b)]})},b))})]}),l===Dn.CONDITIONAL&&r.jsx(jE,{columns:o,config:d?.config,onChange:f}),l===Dn.ROWS&&r.jsx(UE,{columns:o,config:d?.config,onChange:f}),r.jsx("hr",{}),r.jsxs("div",{className:"d-flex justify-content-end my-3",children:[r.jsx(B,{kind:"secondary",onClick:g,className:"mr-2",children:"Cancel"}),r.jsx(B,{kind:"primary",onClick:p,disabled:d===void 0||!u,children:"Done"})]})]})}function GE({text:c,isOpen:e,onClose:t}){const[n,s]=v.useState(!1),[i,o]=v.useState(0),[l,a]=v.useState(!1),[d,h]=v.useState(!1),[u,m]=v.useState(!1),g=v.useRef();v.useEffect(function(){if(e){try{JSON.parse(c),m(!0)}catch{m(!1)}h(!1)}},[e,c]),v.useEffect(function(){g.current&&g.current.layout()},[i]),v.useEffect(function(){g.current&&g.current.updateOptions({lineNumbers:l?"on":"off"})},[l]);function p(){a(!l)}function C(){const S=g.current?.getModel();!u||!S||(d?(S.setValue(c),h(!1)):(S.setValue(JSON.stringify(JSON.parse(c),void 0,2)),h(!0)),f())}function f(){const S=g.current;S&&a((S.getModel()?.getLineCount()??0)>1)}function b(){n&&(g.current=void 0,t())}function w(S){g.current=S,o(S.getContentHeight()),S.onDidContentSizeChange(({contentHeight:T})=>o(T)),f()}return!e&&!n?null:r.jsxs(Gl,{isOpen:e,centered:!0,keyboard:!0,toggle:b,onOpened:()=>s(!0),onClosed:()=>{s(!1),o(0)},className:"theme-bg-dark cell-overflow-modal",size:"xl",children:[r.jsxs(zl,{toggle:t,children:[r.jsx("h5",{className:"overflow-modal-title",children:"Cell Contents"}),r.jsx(Bl,{kind:"inline",tooltip:"Copy cell contents",copy:g.current?.getValue()??c}),r.jsx(B,{kind:"inline",active:l,icon:Fg,tooltip:"Toggle line numbers",onClick:p}),u&&r.jsx(B,{kind:"inline",icon:Ng,active:d,tooltip:"Format as JSON",onClick:C})]}),r.jsx(Kl,{style:{height:i},children:r.jsx(br,{onEditorInitialized:w,settings:{value:c,readOnly:!0,wordWrap:"on",language:u?"typescript":"plaintext",folding:u,padding:{bottom:16},lineNumbers:l?"on":"off",overviewRulerLanes:0,renderLineHighlight:"none",find:{seedSearchStringFromSelection:"never"}}})})]})}function zE(c){return c.model!==void 0}const KE="###,##0";function YE({gotoRow:c,gotoRowError:e,gotoValueError:t,onGotoRowSubmit:n,isShown:s,onEntering:i,onEntered:o,onExiting:l,onExited:a,model:d,onGotoRowNumberChanged:h,onClose:u,gotoValueSelectedColumnName:m,gotoValue:g,gotoValueFilter:p,onGotoValueSelectedColumnNameChanged:C,onGotoValueSelectedFilterChanged:f,onGotoValueChanged:b,onGotoValueSubmit:w}){const S=v.useRef(null),T=v.useRef(null),[y,E]=v.useState(!1);let R=[];zE(d)&&d.table!==void 0&&({columns:R}=d.table);const x="Row number",{rowCount:D}=d,M=$=>{$.key==="Enter"?($.stopPropagation(),$.preventDefault(),w()):($.key==="Backspace"||$.key==="Delete")&&(g===`${Number.POSITIVE_INFINITY}`||g===`${Number.NEGATIVE_INFINITY}`)&&j("")},O=$=>{$.key==="Enter"&&($.stopPropagation(),$.preventDefault(),w($.shiftKey))},H=d.getColumnIndexByName(m),V=R[H??0]?.type,U=F.getNormalizedType(V),j=$=>{b($??"")},P=()=>{y&&document.activeElement!==S.current?S.current?.select():!y&&document.activeElement!==T.current&&T.current?.select()};v.useEffect(P,[y,c,g]);const Q=()=>{switch(U){case F.dataType.DECIMAL:case F.dataType.INT:return r.jsx("div",{className:"goto-row-input",children:r.jsx("input",{ref:T,className:Y("form-control",{"is-invalid":t!==""}),onKeyDown:M,placeholder:"value",onChange:$=>{const J=$.target.value.toLowerCase();/^-?[0-9]*\.?[0-9]*$/.test($.target.value)?j($.target.value):J==="-i"||J==="-infinity"?j(`${Number.NEGATIVE_INFINITY}`):(J==="i"||J==="infinity")&&j(`${Number.POSITIVE_INFINITY}`)},value:g})});case F.dataType.DATETIME:return r.jsx("div",{className:"goto-value-date-time-input",children:r.jsx(jm,{ref:T,className:Y("form-control","goto-value-date-time-input",{"is-invalid":t!==""}),defaultValue:g,onChange:j,onSubmit:O})});case F.dataType.STRING:return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"goto-row-input",children:r.jsxs("select",{className:"custom-select",onChange:$=>{f($.target.value)},value:p,children:[r.jsx("option",{value:be.eq,children:"Equals"},be.eq),r.jsx("option",{value:be.contains,children:"Contains"},be.contains),r.jsx("option",{value:be.eqIgnoreCase,children:"EqIgnoreCase"},be.eqIgnoreCase)]})}),r.jsx("div",{className:"goto-row-input",children:r.jsx("input",{ref:T,className:Y("form-control",{"is-invalid":t!==""}),onKeyDown:O,placeholder:"value",onChange:$=>j($.target.value),value:g})})]});case F.dataType.BOOLEAN:return r.jsx("div",{className:"goto-row-input",children:r.jsxs("select",{className:"custom-select",onChange:$=>{j($.target.value)},value:g,children:[r.jsx("option",{"aria-label":"null value",value:""},"null"),r.jsx("option",{value:"true",children:"true"},"true"),r.jsx("option",{value:"false",children:"false"},"false")]})});default:return r.jsx("div",{className:"goto-row-input",children:r.jsx("input",{ref:T,className:"form-control",onKeyDown:O,placeholder:"value",onChange:$=>j($.target.value),value:g})})}};return r.jsx(sa,{isShown:s,className:Y("goto-row"),onEntering:i,onEntered:()=>{o(),P()},onExiting:l,onExited:a,children:r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"goto-row-row",children:[r.jsxs("div",{className:Y("goto-row-wrapper",{"is-inactive":!y}),onClick:()=>E(!0),onFocus:()=>E(!0),role:"group",children:[r.jsx("div",{className:"goto-row-text",children:"Go to row"}),r.jsx("div",{className:"goto-row-input",children:r.jsx("input",{ref:S,type:"number",onKeyDown:$=>{$.key==="Enter"&&($.stopPropagation(),$.preventDefault(),n())},className:Y("form-control",{"is-invalid":e!==""}),placeholder:x,onChange:$=>{h($)},value:c})}),r.jsxs("div",{className:"goto-row-text",children:["of ",dh.i18n.NumberFormat.format(KE,D)]}),e&&r.jsx("div",{className:"text-danger",children:e})]}),r.jsx("div",{className:"goto-row-close",children:r.jsx(B,{kind:"ghost",onClick:u,children:r.jsx(ee,{icon:uo,style:{marginRight:"0"}})})})]}),d.isSeekRowAvailable&&r.jsx("div",{className:"goto-row-row",children:r.jsxs("div",{className:Y("goto-row-wrapper",{"is-inactive":y}),onClick:()=>E(!1),onFocus:()=>E(!1),role:"group",children:[r.jsx("div",{className:"goto-row-text",children:"Go to value"}),r.jsx("div",{className:"goto-row-input",children:r.jsx("select",{className:"custom-select",onChange:$=>{const J=$.target.value;C(J)},value:m,children:R.map($=>r.jsx("option",{value:$.name,children:$.name},$.name))})}),Q(),r.jsxs("div",{children:[r.jsx(B,{kind:"ghost",disabled:g==="",onClick:()=>{w(!0)},children:r.jsx(ee,{icon:sh})}),r.jsx(B,{kind:"ghost",disabled:g==="",onClick:()=>{w(!1)},children:r.jsx(ee,{icon:kg})})]}),t&&r.jsx("div",{className:"text-danger",children:t})]})})]})})}const me=ne.module("IrisGrid"),qE=500,XE=250,ZE=250,QE=250,hc=Object.freeze({aggregations:ke,showOnTop:!1}),JE="yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS z";function uc({advancedFilters:c,aggregationSettings:e,customColumns:t,quickFilters:n,reverseType:s,rollupConfig:i,searchFilter:o,selectDistinctColumns:l,sorts:a}){return c.size===0&&e.aggregations.length===0&&t.length===0&&n.size===0&&s===F.REVERSE_TYPE.NONE&&i==null&&o==null&&l.length===0&&a.length===0}class Hn extends v.Component{static minDebounce=150;static maxDebounce=500;static loadingSpinnerDelay=800;static defaultProps={children:null,advancedFilters:Pn,advancedSettings:Pn,alwaysFetchColumns:ke,conditionalFormats:ke,customColumnFormatMap:Pn,isFilterBarShown:!1,applyInputFiltersOnInit:!1,movedColumns:ke,movedRows:ke,inputFilters:ke,customFilters:ke,onCreateChart:void 0,onColumnSelected:()=>{},onDataSelected:()=>{},onError:()=>{},onStateChange:()=>{},onPartitionAppend:()=>{},onAdvancedSettingsChange:()=>{},partition:null,partitionColumn:null,quickFilters:Pn,selectDistinctColumns:ke,sorts:ke,reverseType:F.REVERSE_TYPE.NONE,customColumns:ke,aggregationSettings:hc,rollupConfig:void 0,userColumnWidths:Pn,userRowHeights:Pn,onSelectionChanged:()=>{},isSelectingColumn:!1,isSelectingPartition:!1,isStuckToBottom:!1,isStuckToRight:!1,columnSelectionValidator:null,columnAllowedCursor:null,columnNotAllowedCursor:null,name:"table",onlyFetchVisibleColumns:!0,showSearchBar:!1,searchValue:"",selectedSearchColumns:null,invertSearchColumns:!0,onContextMenu:()=>{},pendingDataMap:Pn,getDownloadWorker:void 0,settings:{timeZone:"America/New_York",defaultDateTimeFormat:Xs.FULL_DATE_FORMAT,showTimeZone:!1,showTSeparator:!0,truncateNumbersWithPound:!1,formatter:ke,decimalFormatOptions:z.shape({defaultFormatString:z.string}),integerFormatOptions:z.shape({defaultFormatString:z.string})},canCopy:!0,canDownloadCsv:!0,frozenColumns:null,theme:sc,canToggleSearch:!0};static makeQuickFilter(e,t,n){try{return F.makeQuickFilter(e,t,n)}catch(s){me.error("Error creating quick filter",s)}return null}constructor(e){super(e),this.handleAdvancedFilterChange=this.handleAdvancedFilterChange.bind(this),this.handleAdvancedFilterSortChange=this.handleAdvancedFilterSortChange.bind(this),this.handleAdvancedFilterDone=this.handleAdvancedFilterDone.bind(this),this.handleAdvancedMenuOpened=this.handleAdvancedMenuOpened.bind(this),this.handleGotoRowOpened=this.handleGotoRowOpened.bind(this),this.handleGotoRowClosed=this.handleGotoRowClosed.bind(this),this.handleAdvancedMenuClosed=this.handleAdvancedMenuClosed.bind(this),this.handleAggregationChange=this.handleAggregationChange.bind(this),this.handleAggregationsChange=this.handleAggregationsChange.bind(this),this.handleAggregationEdit=this.handleAggregationEdit.bind(this),this.handleAnimationLoop=this.handleAnimationLoop.bind(this),this.handleAnimationStart=this.handleAnimationStart.bind(this),this.handleAnimationEnd=this.handleAnimationEnd.bind(this),this.handleChartChange=this.handleChartChange.bind(this),this.handleChartCreate=this.handleChartCreate.bind(this),this.handleGridError=this.handleGridError.bind(this),this.handleFilterBarChange=this.handleFilterBarChange.bind(this),this.handleFilterBarDone=this.handleFilterBarDone.bind(this),this.handleFilterBarTab=this.handleFilterBarTab.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleMenu=this.handleMenu.bind(this),this.handleMenuClose=this.handleMenuClose.bind(this),this.handleMenuSelect=this.handleMenuSelect.bind(this),this.handleMenuBack=this.handleMenuBack.bind(this),this.handleRequestFailed=this.handleRequestFailed.bind(this),this.handleSelectionChanged=this.handleSelectionChanged.bind(this),this.handleMovedColumnsChanged=this.handleMovedColumnsChanged.bind(this),this.handleHeaderGroupsChanged=this.handleHeaderGroupsChanged.bind(this),this.handleUpdate=this.handleUpdate.bind(this),this.handleTooltipRef=this.handleTooltipRef.bind(this),this.handleViewChanged=this.handleViewChanged.bind(this),this.handleFormatSelection=this.handleFormatSelection.bind(this),this.handleConditionalFormatCreate=this.handleConditionalFormatCreate.bind(this),this.handleConditionalFormatEdit=this.handleConditionalFormatEdit.bind(this),this.handleConditionalFormatsChange=this.handleConditionalFormatsChange.bind(this),this.handleConditionalFormatEditorSave=this.handleConditionalFormatEditorSave.bind(this),this.handleConditionalFormatEditorCancel=this.handleConditionalFormatEditorCancel.bind(this),this.handleUpdateCustomColumns=this.handleUpdateCustomColumns.bind(this),this.handleCustomColumnsChanged=this.handleCustomColumnsChanged.bind(this),this.handleSelectDistinctChanged=this.handleSelectDistinctChanged.bind(this),this.handlePendingDataUpdated=this.handlePendingDataUpdated.bind(this),this.handlePendingCommitClicked=this.handlePendingCommitClicked.bind(this),this.handlePendingDiscardClicked=this.handlePendingDiscardClicked.bind(this),this.handleGotoRowSelectedRowNumberSubmit=this.handleGotoRowSelectedRowNumberSubmit.bind(this),this.focusRowInGrid=this.focusRowInGrid.bind(this),this.handleDownloadTable=this.handleDownloadTable.bind(this),this.handleDownloadTableStart=this.handleDownloadTableStart.bind(this),this.handleCancelDownloadTable=this.handleCancelDownloadTable.bind(this),this.handleDownloadCanceled=this.handleDownloadCanceled.bind(this),this.handleDownloadCompleted=this.handleDownloadCompleted.bind(this),this.handlePartitionAppend=this.handlePartitionAppend.bind(this),this.handlePartitionChange=this.handlePartitionChange.bind(this),this.handlePartitionFetchAll=this.handlePartitionFetchAll.bind(this),this.handlePartitionDone=this.handlePartitionDone.bind(this),this.handleColumnVisibilityChanged=this.handleColumnVisibilityChanged.bind(this),this.handleColumnVisibilityReset=this.handleColumnVisibilityReset.bind(this),this.handleCrossColumnSearch=this.handleCrossColumnSearch.bind(this),this.handleRollupChange=this.handleRollupChange.bind(this),this.handleOverflowClose=this.handleOverflowClose.bind(this),this.getColumnBoundingRect=this.getColumnBoundingRect.bind(this),this.handleGotoRowSelectedRowNumberChanged=this.handleGotoRowSelectedRowNumberChanged.bind(this),this.handleGotoValueSelectedColumnNameChanged=this.handleGotoValueSelectedColumnNameChanged.bind(this),this.handleGotoValueSelectedFilterChanged=this.handleGotoValueSelectedFilterChanged.bind(this),this.handleGotoValueChanged=this.handleGotoValueChanged.bind(this),this.handleGotoValueSubmitted=this.handleGotoValueSubmitted.bind(this),this.grid=null,this.gridWrapper=null,this.lastLoadedConfig=null,this.pending=new Yn,this.globalColumnFormats=ke,this.decimalFormatOptions={},this.integerFormatOptions={},this.truncateNumbersWithPound=!1,this.renderer=new tT,this.tableSaver=null,this.crossColumnRef=de.createRef(),this.isAnimating=!1,this.filterInputRef=de.createRef(),this.toggleFilterBarAction={action:()=>this.toggleFilterBar(),shortcut:Ut.TABLE.TOGGLE_QUICK_FILTER},this.toggleSearchBarAction={action:()=>this.toggleSearchBar(),shortcut:Ut.TABLE.TOGGLE_SEARCH},this.toggleGotoRowAction={action:()=>this.toggleGotoRow(),shortcut:Ut.TABLE.GOTO_ROW},this.discardAction={action:()=>{const{model:P}=this.props;Xe(P)&&P.isEditable&&P.pendingDataMap.size>0&&this.discardPending().catch(me.error)},shortcut:Ut.INPUT_TABLE.DISCARD},this.commitAction={action:()=>{const{model:P}=this.props;Xe(P)&&P.isEditable&&P.pendingDataMap.size>0&&P.pendingDataErrors.size===0&&this.commitPending().catch(me.error)},shortcut:Ut.INPUT_TABLE.COMMIT},this.contextActions=[this.toggleFilterBarAction,this.toggleSearchBarAction,this.toggleGotoRowAction,this.discardAction,this.commitAction];const{aggregationSettings:t,conditionalFormats:n,customColumnFormatMap:s,isFilterBarShown:i,isSelectingPartition:o,model:l,movedColumns:a,movedRows:d,partition:h,partitionColumn:u,rollupConfig:m,userColumnWidths:g,userRowHeights:p,showSearchBar:C,searchValue:f,selectedSearchColumns:b,invertSearchColumns:w,advancedFilters:S,quickFilters:T,selectDistinctColumns:y,pendingDataMap:E,canCopy:R,frozenColumns:x,columnHeaderGroups:D}=e,M=[new gv(this),new fv(this)];R&&M.push(new dv(this));const O=[new bv(this),new Av(this),new Uv(this),new wv(this),new Tv(this),new Pv(this),new Lv(this),new Fv(this),new kv(this),new Hv(this)],H=a.length>0?a:l.initialMovedColumns,L=d.length>0?d:l.initialMovedRows,V=new Gv({userColumnWidths:new Map(g),userRowHeights:new Map(p),movedColumns:H,initialColumnWidths:new Map(l?.layoutHints?.hiddenColumns?.map(P=>[l.getColumnIndexByName(P),0]))}),U=b??[],j=Ko.createSearchFilter(f,U,l.columns,w);this.state={isFilterBarShown:i,isSelectingPartition:o,focusedFilterBarColumn:null,metricCalculator:V,metrics:void 0,keyHandlers:M,mouseHandlers:O,partition:h,partitionColumn:u,partitionTable:null,partitionFilters:[],quickFilters:T?new Map(T):new Map,advancedFilters:new Map(S),shownAdvancedFilter:null,hoverAdvancedFilter:null,sorts:[],reverseType:F.REVERSE_TYPE.NONE,customColumns:[],selectDistinctColumns:y,selectedRanges:[],copyOperation:null,loadingText:null,loadingScrimProgress:null,loadingSpinnerShown:!1,movedColumns:H,movedRows:L,shownColumnTooltip:null,formatter:new gn,isMenuShown:!1,customColumnFormatMap:new Map(s),conditionalFormats:n,conditionalFormatEditIndex:null,conditionalFormatPreview:void 0,hoverSelectColumn:null,isTableDownloading:!1,isReady:!1,tableDownloadStatus:"",tableDownloadProgress:0,tableDownloadEstimatedTime:0,showSearchBar:C,searchFilter:j,searchValue:f,selectedSearchColumns:U,invertSearchColumns:w,rollupConfig:m,rollupSelectedColumns:[],aggregationSettings:t,selectedAggregation:null,openOptions:[],pendingRowCount:0,pendingDataMap:E??new Map,pendingDataErrors:new Map,pendingSavePromise:null,pendingSaveError:null,toastMessage:null,frozenColumns:x,showOverflowModal:!1,overflowText:"",overflowButtonTooltipProps:null,expandCellTooltipProps:null,expandTooltipDisplayValue:"expand",linkHoverTooltipProps:null,linkHoverDisplayValue:"",isGotoShown:!1,gotoRow:"",gotoRowError:"",gotoValueError:"",gotoValueSelectedColumnName:l.columns[0]?.name??"",gotoValueSelectedFilter:be.eq,gotoValue:"",columnHeaderGroups:D??l.initialColumnHeaderGroups}}componentDidMount(){const{partitionColumn:e,model:t}=this.props,n=e??t.columns.find(s=>s.isPartitionColumn);t.isFilterRequired&&t.isValuesTableAvailable&&n!=null?this.loadPartitionsTable(n):this.initState(),this.startListening(t)}componentDidUpdate(e){const{inputFilters:t,isSelectingColumn:n,settings:s,model:i,customFilters:o,sorts:l}=this.props;i!==e.model&&(this.stopListening(e.model),this.startListening(i));const a=t!==e.inputFilters?t.filter(u=>!e.inputFilters.includes(u)):[];if(a.length>0){const{advancedSettings:u}=this.props,m=u.get(xi.FILTER_CONTROL_CHANGE_CLEARS_ALL_FILTERS)??!1;m&&(this.clearGridInputField(),this.clearCrossColumSearch()),this.startLoading("Filtering...",!0),this.applyInputFilters(a,m)}n!==e.isSelectingColumn&&this.resetColumnSelection(),s!==e.settings&&this.updateFormatterSettings(s),o!==e.customFilters&&this.startLoading("Filtering...",!0),l!==e.sorts&&this.updateSorts(l);const{loadingScrimStartTime:d,loadingScrimFinishTime:h}=this;d!=null&&h!=null&&window.requestAnimationFrame(()=>{const u=Date.now(),m=u-d,g=h-d,p=Math.min(m/g,1);h<u&&(this.loadingScrimStartTime=void 0,this.loadingScrimFinishTime=void 0),this.setState(C=>C.loadingScrimProgress==null?(me.debug2("Ignoring scrim update because loading cancelled."),null):{loadingScrimProgress:p})}),this.sendStateChange()}componentWillUnmount(){const{model:e}=this.props;this.stopListening(e),this.pending.cancel(),this.updateSearchFilter.cancel(),this.loadingTimer&&clearTimeout(this.loadingTimer),this.handleDownloadProgressUpdate.cancel(),this.animationFrame!==void 0&&cancelAnimationFrame(this.animationFrame)}grid;gridWrapper;lastFocusedFilterBarColumn;lastLoadedConfig;tooltip;pending;globalColumnFormats;dateTimeFormatterOptions;decimalFormatOptions;integerFormatOptions;truncateNumbersWithPound;loadingScrimStartTime;loadingScrimFinishTime;animationFrame;loadingTimer;renderer;tableSaver;crossColumnRef;isAnimating;filterInputRef;toggleFilterBarAction;toggleSearchBarAction;toggleGotoRowAction;discardAction;commitAction;contextActions;getAdvancedMenuOpenedHandler=Re(e=>this.handleAdvancedMenuOpened.bind(this,e),{max:100});getCachedAdvancedFilterMenuActions=Re((e,t,n,s,i)=>r.jsx(hT,{model:e,column:t,onFilterChange:this.handleAdvancedFilterChange,onSortChange:this.handleAdvancedFilterSortChange,onDone:this.handleAdvancedFilterDone,options:n,sortDirection:s,formatter:i}),{max:50});getCachedOptionItems=Re((e,t,n,s,i,o,l,a,d,h,u,m,g,p,C,f)=>{const b=[];return e&&b.push({type:Ne.CHART_BUILDER,title:"Chart Builder",icon:Mg}),b.push({type:Ne.VISIBILITY_ORDERING_BUILDER,title:"Organize Columns",icon:gr}),n&&b.push({type:Ne.CONDITIONAL_FORMATTING,title:"Conditional Formatting",icon:go}),t&&b.push({type:Ne.CUSTOM_COLUMN_BUILDER,title:"Custom Columns",icon:Lg}),s&&b.push({type:Ne.ROLLUP_ROWS,title:"Rollup Rows",icon:ih}),i&&b.push({type:Ne.AGGREGATIONS,title:"Aggregate Columns",icon:Og}),o&&b.push({type:Ne.SELECT_DISTINCT,title:"Select Distinct Values",icon:Ag}),l&&g&&b.push({type:Ne.TABLE_EXPORTER,title:"Download CSV",icon:_g}),f&&b.push({type:Ne.ADVANCED_SETTINGS,title:"Advanced Settings",icon:Pg}),b.push({type:Ne.QUICK_FILTERS,title:"Quick Filters",subtitle:a.shortcut.getDisplayText(),icon:dl,isOn:u,onChange:a.action}),p&&b.push({type:Ne.SEARCH_BAR,title:"Search Bar",subtitle:d.shortcut.getDisplayText(),icon:jg,isOn:m,onChange:d.action}),b.push({type:Ne.GOTO,title:"Go to",subtitle:h.shortcut.getDisplayText(),icon:Hg,isOn:C,onChange:h.action}),Object.freeze(b)},{max:1});getCachedHiddenColumns=Re((e,t)=>Se.getHiddenColumns(new Map([...e.initialColumnWidths,...t])),{max:1});getAggregationMap=Re((e,t)=>{const n={};return t.forEach(({operation:s,selected:i,invert:o})=>{n[s]=Cs.getOperationColumnNames(e,s,i,o)}),n});getOperationMap=Re((e,t)=>{const n={};return t.filter(s=>!Cs.isRollupOperation(s.operation)).forEach(({operation:s,selected:i,invert:o})=>{Cs.getOperationColumnNames(e,s,i,o).forEach(l=>{const a=[...n[l]??[],s];n[l]=Object.freeze(a)})}),n});getOperationOrder=Re(e=>e.map(t=>t.operation).filter(t=>!Cs.isRollupOperation(t)));getCachedFormatColumns=Re((e,t)=>zw(e,t));getCachedPreviewFormatColumns=Re((e,t,n,s)=>{if(me.debug("getCachedPreviewFormatColumns",t,n,s),n!==void 0&&s!==void 0){const i=[...t];return i[s]=n,this.getCachedFormatColumns(e,i)}return this.getCachedFormatColumns(e,t)});getModelRollupConfig=Re((e,t,n)=>Se.getModelRollupConfig(e,t,n));getModelTotalsConfig=Re((e,t,n)=>{const{aggregations:s,showOnTop:i}=n;if((t?.columns?.length??0)>0||(s?.length??0)===0)return null;const o=this.getOperationMap(e,s),l=this.getOperationOrder(s);return{operationMap:o,operationOrder:l,showOnTop:i}});getCachedStateOverride=Re((e,t,n,s,i,o,l,a,d,h)=>({hoverSelectColumn:e,isFilterBarShown:t,isSelectingColumn:n,loadingScrimProgress:s,quickFilters:i,advancedFilters:o,sorts:l,reverseType:a,rollupConfig:d,isMenuShown:h}),{max:1});getCachedFilter=Re((e,t,n,s,i)=>[...e??[],...s??[],...Se.getFiltersFromFilterMap(t),...Se.getFiltersFromFilterMap(n),...i!==void 0?[i]:[]],{max:1});getCachedTheme=Re((e,t,n)=>({...sc,...e,autoSelectRow:!t,rowFooterWidth:n>0?e.rowFooterWidth:0}),{max:1});getValueForCell(e,t,n=!1){const{model:s}=this.props,i=this.getModelColumn(e),o=this.getModelRow(t);if(n&&i!=null&&o!=null){const l=s.valueForCell(i,o);if(F.isDateType(s.columns[i].type)){const{formatter:a}=s;return I.i18n.DateTimeFormat.format(JE,l,I.i18n.TimeZone.getTimeZone(a.timeZone))}return l}return n?null:i!=null&&o!=null?s.textForCell(i,o):""}getModelColumn(e){const{metrics:t}=this.state;N(t);const{modelColumns:n}=t;return n==null?null:e!=null?n.get(e):null}getModelRow(e){const{metrics:t}=this.state;N(t);const{modelRows:n}=t;return n==null?null:e!=null?n.get(e):null}getTheme(){const{model:e,theme:t}=this.props;return this.getCachedTheme(t,(Xe(e)&&e.isEditable)??!1,e.floatingTopRowCount+e.floatingBottomRowCount)}getVisibleColumn(e){const{movedColumns:t}=this.state;return _.getVisibleIndex(e,t)}applyInputFilters(e,t=!1){const{model:n}=this.props,{advancedFilters:s,quickFilters:i}=this.state,o=t?new Map:new Map(s),l=t?new Map:new Map(i);let a=t&&s.size>0;e.forEach(({name:d,type:h,value:u})=>{const m=n.columns.findIndex(({name:g,type:p})=>g===d&&p===h);m>=0?(a=o.delete(m)||a,a=this.applyQuickFilter(m,u,l)||a):me.error("Unable to find column for inputFilter",d,h,u)}),a&&this.setState({quickFilters:l,advancedFilters:o})}applyQuickFilter(e,t,n){const{model:s}=this.props,{formatter:i}=s,o=s.columns[e];if(t!=null&&`${t}`.trim().length>0){const l=n.get(e);if(l!=null){const{text:a}=l;if(a===t)return me.debug2("Ignoring change to existing filter"),!1}return n.set(e,{text:t,filter:Hn.makeQuickFilter(o,t,i.timeZone)}),!0}return n.delete(e)}setAdvancedFilterMap(e){this.setState({advancedFilters:e})}setAdvancedFilter(e,t,n){me.debug("Setting advanced filter",e,t),this.startLoading("Filtering...",!0),this.setState(({advancedFilters:s})=>{const i=new Map(s);return t==null?i.delete(e):i.set(e,{filter:t,options:n}),{advancedFilters:i}})}setQuickFilter(e,t,n){me.debug("Setting quick filter",e,t,n),this.startLoading("Filtering...",!0),this.setState(({quickFilters:s})=>{const i=new Map(s);return i.set(e,{filter:t,text:n}),{quickFilters:i}})}setFilterMap(e){me.debug("setFilterMap",e);const{advancedSettings:t}=this.props;(t.get(xi.LINK_CHANGE_CLEARS_ALL_FILTERS)??!1)&&this.clearAllFilters();const{model:s}=this.props;e.forEach(({columnType:i,filterList:o},l)=>{const a=s.columns.find(u=>u.name===l&&u.type===i);if(a==null)return;const d=s.getColumnIndexByName(a.name);N(d);const h=Se.combineFiltersFromList(i,o);if(h.length===0)this.removeQuickFilter(d);else{const{formatter:u}=s;this.setQuickFilter(d,Hn.makeQuickFilter(a,h,u.timeZone),`${h}`)}})}removeColumnFilter(e){this.startLoading("Filtering...",!0),this.setState(({advancedFilters:t,quickFilters:n})=>{const s=t?new Map(t):new Map,i=n?new Map(n):new Map;return i.delete(e),s.delete(e),{quickFilters:i,advancedFilters:s}})}removeQuickFilter(e){this.startLoading("Clearing Filter...",!0),this.setState(({quickFilters:t})=>{const n=new Map(t);return n.delete(e),{quickFilters:n}})}clearAllFilters(){me.debug("Clearing all filters");const{advancedFilters:e,quickFilters:t,searchFilter:n}=this.state;t.size===0&&e.size===0&&n===null||(this.clearGridInputField(),this.startLoading("Clearing Filters...",!0),this.setState({quickFilters:new Map,advancedFilters:new Map,searchValue:"",searchFilter:void 0}))}clearCrossColumSearch(){me.debug("Clearing cross-column search"),this.setState({searchValue:"",searchFilter:void 0})}clearGridInputField(){this.filterInputRef.current!=null&&this.filterInputRef.current.setValue("")}rebuildFilters(){me.debug("Rebuilding filters");const{model:e}=this.props,{advancedFilters:t,quickFilters:n}=this.state,{columns:s,formatter:i}=e,o=new Map,l=new Map;t.forEach((a,d)=>{const{options:h}=a,u=s[d],m=F.makeAdvancedFilter(u,h,i.timeZone);o.set(d,{options:h,filter:m})}),n.forEach((a,d)=>{const{text:h}=a,u=s[d];l.set(d,{text:h,filter:Hn.makeQuickFilter(u,h,i.timeZone)})}),this.startLoading("Rebuilding filters...",!0),this.setState({quickFilters:l,advancedFilters:o})}setFilters({quickFilters:e,advancedFilters:t}){this.setState({quickFilters:e,advancedFilters:t})}updateFormatterSettings(e,t=!0){const n=$n.getColumnFormats(e),s=$n.getDateTimeFormatterOptions(e),i=e?.defaultDecimalFormatOptions??{},o=e?.defaultIntegerFormatOptions??{},l=e?.truncateNumbersWithPound??!1,a=!st(this.globalColumnFormats,n),d=!st(this.dateTimeFormatterOptions,s),h=!st(this.decimalFormatOptions,e?.defaultDecimalFormatOptions),u=!st(this.integerFormatOptions,o),m=this.truncateNumbersWithPound!==l;(a||d||h||u||m)&&(this.globalColumnFormats=n,this.dateTimeFormatterOptions=s,this.decimalFormatOptions=i,this.integerFormatOptions=o,this.truncateNumbersWithPound=l,this.updateFormatter({},t),d&&t&&this.rebuildFilters())}getAlwaysFetchColumns=Re((e,t,n,s,i,o)=>{const l=[];for(let d=0;d<s;d+=1)l.push(t[_.getModelIndex(d,n)].name);for(let d=0;d<i;d+=1)l.push(t[_.getModelIndex(t.length-1-d,n)].name);if(o)for(let d=o[0];d<=o[1];d+=1)l.push(t[_.getModelIndex(d,n)].name);const a=new Set([...e,...l]);return Object.freeze([...a])});updateFormatter(e,t=!0){const{customColumnFormatMap:n}=this.state,s={customColumnFormatMap:n,...e},i=[...this.globalColumnFormats??[],...s.customColumnFormatMap.values()],o=new gn(i,this.dateTimeFormatterOptions,this.decimalFormatOptions,this.integerFormatOptions,this.truncateNumbersWithPound);me.debug("updateFormatter",this.globalColumnFormats,i),this.setState({...s,formatter:o},()=>{t&&this.grid&&this.grid.forceUpdate()})}initFormatter(){const{settings:e}=this.props;this.updateFormatterSettings(e)}initState(){const{applyInputFiltersOnInit:e,inputFilters:t,sorts:n,model:s,reverseType:i,customColumns:o,searchValue:l,selectedSearchColumns:a,invertSearchColumns:d}=this.props,h=a??[],u=Ko.createSearchFilter(l,h,s.columns,d);if(e){const m=t.filter(g=>g.value!=null);this.applyInputFilters(m)}this.setState({sorts:n,reverseType:i,customColumns:o,isReady:!0,searchFilter:u}),this.initFormatter()}async loadPartitionsTable(e){const{model:t}=this.props;this.setState({isSelectingPartition:!0});try{const n=await this.pending.add(t.valuesTable(e),l=>l.close()),s=n.columns[0],i=s.sort().desc();n.applySort([i]),n.setViewport(0,0,[s]);const o=await this.pending.add(n.getViewportData());if(o.rows.length>0){const a=o.rows[0].get(s);this.updatePartition(a,e),this.setState({isSelectingPartition:!0})}else me.info("Table does not have any data, just fetching all"),this.setState({isSelectingPartition:!1}),this.handlePartitionFetchAll();this.setState({partitionTable:n,partitionColumn:e},()=>{this.initState()})}catch(n){this.handleTableLoadError(n)}}updatePartition(e,t){const s=[t.filter().eq(I.FilterValue.ofString(e))];this.setState({partition:e,partitionFilters:s})}copyCell(e,t,n=!1){const{canCopy:s}=this.props;if(s){const i=String(this.getValueForCell(e,t,n));ho(i).catch(o=>me.error("Unable to copy cell",o))}else me.error("Attempted to copyCell for user without copy permission.")}copyRanges(e,t=!1,n=!0,s){const{model:i,canCopy:o}=this.props,{metricCalculator:l,movedColumns:a}=this.state,d=l.getUserColumnWidths();if(o){const h={ranges:te.boundedRanges(e,i.columnCount,i.rowCount),includeHeaders:t,formatValues:n,movedColumns:a,userColumnWidths:d,error:s};this.setState({copyOperation:h})}else me.error("Attempted copyRanges for user without copy permission.")}startLoading(e,t=!1){this.setState({loadingText:e});const n=this.getTheme();if(t&&this.grid&&(this.grid.clearSelectedRanges(),this.grid.setViewState({top:0},!0)),this.loadingScrimStartTime==null){const{minScrimTransitionTime:s,maxScrimTransitionTime:i}=n;N(s),N(i);const o=this.gridWrapper?.getBoundingClientRect().height??0,l=Math.max(s,Math.min(o/2,i));this.loadingScrimStartTime=Date.now(),this.loadingScrimFinishTime=this.loadingScrimStartTime+l,this.setState({loadingScrimProgress:0}),this.loadingTimer=setTimeout(()=>{this.setState({loadingSpinnerShown:!0})},Hn.loadingSpinnerDelay)}}stopLoading(){this.loadingScrimStartTime=void 0,this.loadingScrimFinishTime=void 0,this.setState({loadingText:null,loadingScrimProgress:null,loadingSpinnerShown:!1}),this.loadingTimer!=null&&(clearTimeout(this.loadingTimer),this.loadingTimer=void 0)}rollback(){if(this.lastLoadedConfig){me.debug("loading last loading config",this.lastLoadedConfig);const{advancedFilters:e,aggregationSettings:t,customColumns:n,quickFilters:s,reverseType:i,rollupConfig:o,searchFilter:l,selectDistinctColumns:a,sorts:d}=this.lastLoadedConfig;this.lastLoadedConfig=null,this.setState({advancedFilters:e,aggregationSettings:t,customColumns:n,quickFilters:s,reverseType:i,rollupConfig:o,searchFilter:l,selectDistinctColumns:a,sorts:d})}else me.debug("remove all sorts, filters, and custom columns"),this.setState({advancedFilters:new Map,aggregationSettings:hc,customColumns:[],quickFilters:new Map,reverseType:F.REVERSE_TYPE.NONE,rollupConfig:void 0,selectDistinctColumns:[],sorts:[]})}canRollback(){return this.lastLoadedConfig!=null||!uc(this.state)}startListening(e){e.addEventListener(Ce.EVENT.UPDATED,this.handleUpdate),e.addEventListener(Ce.EVENT.REQUEST_FAILED,this.handleRequestFailed),e.addEventListener(Ce.EVENT.COLUMNS_CHANGED,this.handleCustomColumnsChanged),e.addEventListener(Ce.EVENT.PENDING_DATA_UPDATED,this.handlePendingDataUpdated)}stopListening(e){e.removeEventListener(Ce.EVENT.UPDATED,this.handleUpdate),e.removeEventListener(Ce.EVENT.REQUEST_FAILED,this.handleRequestFailed),e.removeEventListener(Ce.EVENT.COLUMNS_CHANGED,this.handleCustomColumnsChanged),e.removeEventListener(Ce.EVENT.PENDING_DATA_UPDATED,this.handlePendingDataUpdated)}focus(){this.grid?.focus()}focusFilterBar(e){const{movedColumns:t}=this.state,{model:n}=this.props,{columnCount:s}=n,i=_.getModelIndex(e,t);if(e==null||e<0||s<=e||!n.isFilterable(i)){this.setState({focusedFilterBarColumn:null});return}const{metricCalculator:o,metrics:l}=this.state;N(l);const{left:a,rightVisible:d,lastLeft:h}=l;if(e<a)this.grid?.setViewState({left:e},!0);else if(d<e){const u=this.grid?.getMetricState();N(u);const m=o.getLastLeft(u,e,o.getVisibleWidth(u));this.grid?.setViewState({left:Math.min(m,h),leftOffset:0},!0)}this.lastFocusedFilterBarColumn=e,this.setState({focusedFilterBarColumn:e,isFilterBarShown:!0})}hideColumnByVisibleIndex(e){const{metricCalculator:t,movedColumns:n}=this.state;t.setColumnWidth(_.getModelIndex(e,n),0),this.grid?.forceUpdate()}freezeColumnByColumnName(e){const{frozenColumns:t,movedColumns:n}=this.state,{model:s}=this.props;me.debug2("freezing column",e);const i=t==null?new Set(s.frozenColumns):new Set(t);i.add(e);const o=s.getColumnIndexByName(e);N(o);const l=_.getVisibleIndex(o,n),a=_.moveItem(l,i.size-1,n);this.setState({frozenColumns:[...i],movedColumns:a})}unFreezeColumnByColumnName(e){const{frozenColumns:t,movedColumns:n}=this.state,{model:s}=this.props;me.debug2("unfreezing column",e);const i=t==null?new Set(s.frozenColumns):new Set(t);i.delete(e);const o=s.getColumnIndexByName(e);N(o);const l=_.getVisibleIndex(o,n),a=_.moveItem(l,i.size+s.frontColumns.length,n);this.setState({frozenColumns:[...i],movedColumns:a})}handleColumnVisibilityChanged(e,t){const{metricCalculator:n,metrics:s}=this.state;N(s),t?e.forEach(i=>{const o=n.initialColumnWidths.get(i),l=k(s.calculatedColumnWidths,i);o!==l?n.setColumnWidth(i,l):n.resetColumnWidth(i)}):e.forEach(i=>{n.setColumnWidth(i,0)}),this.grid?.forceUpdate()}handleColumnVisibilityReset(){const{metricCalculator:e,metrics:t}=this.state,{model:n}=this.props;N(t);for(let s=0;s<t.columnCount;s+=1)e.resetColumnWidth(s);this.handleMovedColumnsChanged(n.initialMovedColumns),this.handleHeaderGroupsChanged(n.initialColumnHeaderGroups),this.setState({frozenColumns:n.layoutHints?.frozenColumns??[]})}handleCrossColumnSearch(e,t,n){const{model:s}=this.props;this.updateSearchFilter(e,t,s.columns,n),this.setState({searchValue:e,selectedSearchColumns:t,invertSearchColumns:n})}updateSearchFilter=Ye((e,t,n,s)=>{const i=Ko.createSearchFilter(e,t,n,s);this.setState({searchFilter:i})},XE);handleAnimationLoop(){this.grid?.updateCanvas(),this.isAnimating&&(this.animationFrame=requestAnimationFrame(this.handleAnimationLoop))}handleAnimationStart(){me.debug2("handleAnimationStart"),this.isAnimating=!0,this.animationFrame=requestAnimationFrame(this.handleAnimationLoop)}handleAnimationEnd(){me.debug2("handleAnimationEnd"),this.isAnimating=!1}handlePartitionAppend(e){const{onPartitionAppend:t}=this.props,{partitionColumn:n}=this.state;n!=null&&t(n,e)}handlePartitionChange(e){const{partitionColumn:t}=this.state;t!=null&&this.updatePartition(e,t)}handlePartitionFetchAll(){this.setState({partitionFilters:[],isSelectingPartition:!1})}handlePartitionDone(){this.setState({isSelectingPartition:!1})}handleTableLoadError(e){if(ye.isCanceled(e))return;me.error(e);const{onError:t}=this.props;t(e)}showAllColumns(){const{metricCalculator:e}=this.state,n=[...e.getUserColumnWidths().entries()];for(let s=0;s<n.length;s+=1){const[i,o]=n[s];o===0&&e.resetColumnWidth(i)}this.grid?.forceUpdate()}toggleSort(e,t){me.info("Toggling sort for column",e);const{model:n}=this.props,{sorts:s}=this.state,i=this.getModelColumn(e);N(i);const o=F.toggleSortForColumn(s,n.columns,i,t);this.updateSorts(o)}updateSorts(e){this.startLoading("Sorting..."),this.setState({sorts:e}),this.grid?.forceUpdate()}sortColumn(e,t=F.sortDirection.none,n=!1,s=!1){N(e);const{model:i}=this.props,o=F.sortColumn(i.sort,i.columns,e,t,n,s);this.startLoading("Sorting..."),this.setState({sorts:o}),this.grid?.forceUpdate()}reverse(e){this.startLoading("Reversing..."),this.setState({reverseType:e}),this.grid?.forceUpdate()}isReversible(){const{model:e}=this.props;return e.isReversible}toggleFilterBar(e=this.lastFocusedFilterBarColumn){let{isFilterBarShown:t}=this.state;if(t=!t,this.setState({isFilterBarShown:t}),t)if(e!=null)this.focusFilterBar(e);else{let n=0;const{model:s}=this.props,{columnCount:i}=s;for(let o=0;o<i;o+=1){const l=this.getModelColumn(o);if(l!=null){const a=s.columns[l];if(a!=null&&F.isTextType(a.type)){n=o;break}}}this.focusFilterBar(n)}else this.grid?.focus()}isTableSearchAvailable(){const{model:e,canToggleSearch:t}=this.props,n=e?.layoutHints?.searchDisplayMode;return n===I.SearchDisplayMode?.SEARCH_DISPLAY_HIDE?!1:n===I.SearchDisplayMode?.SEARCH_DISPLAY_SHOW?!0:t}toggleSearchBar(){const{showSearchBar:e}=this.state;if(!this.isTableSearchAvailable())return;const t=!e;this.setState({showSearchBar:t},()=>{t&&this.crossColumnRef?.current?this.crossColumnRef?.current.focus():this.grid?.focus()})}toggleGotoRow(e="",t="",n=""){const{isGotoShown:s}=this.state;if(e||t){this.setState({isGotoShown:!0,gotoRow:e,gotoValue:t,gotoValueSelectedColumnName:n,gotoRowError:"",gotoValueError:""}),this.focusRowInGrid(e);return}const i=this.grid?.state.cursorRow,o=this.grid?.state.cursorColumn;if(i==null||o==null){this.setState({isGotoShown:!s,gotoRow:"",gotoValue:"",gotoRowError:"",gotoValueError:""});return}const{model:l}=this.props,{name:a,type:d}=l.columns[o],h=l.valueForCell(o,i),u=Se.convertValueToText(h,d);this.setState({isGotoShown:!s,gotoRow:`${i}`,gotoValue:u,gotoValueSelectedColumnName:a,gotoRowError:"",gotoValueError:""})}async commitPending(){const{model:e}=this.props;if(!Xe(e)||!e.isEditable)throw new Error("Cannot save, table is not editable");const{pendingSavePromise:t}=this.state;if(t!=null)throw new Error("Save already in progress");const n=document?.activeElement?.classList.contains("grid-cell-input-field");if(n!=null&&n){if(document.activeElement!=null&&document.activeElement.classList.contains("error"))throw new vi("Current input is invalid");this.grid?.focus()}const s=this.pending.add(e.commitPending()).then(()=>{this.setState({pendingSaveError:null,pendingSavePromise:null})}).catch(i=>{ye.isCanceled(i)||this.setState({pendingSaveError:i,pendingSavePromise:null})});return this.setState({pendingSavePromise:s}),s}async discardPending(){const{pendingSavePromise:e}=this.state;if(e!=null)throw new Error("Cannot cancel a save in progress");this.setState({pendingSavePromise:null,pendingSaveError:null,pendingDataMap:new Map,pendingDataErrors:new Map})}selectColumn(e){const{onColumnSelected:t}=this.props;t(e)}selectData(e,t){const{model:n}=this.props,{columns:s,groupedColumns:i}=n,o={};for(let a=0;a<s.length;a+=1){const d=s[a],{name:h,type:u}=d,m=n.valueForCell(a,t),g=n.textForCell(a,t),p=this.getVisibleColumn(a),C=je(n)&&n.isRowExpandable(t),f=i.find(b=>b.name===h)!=null;o[h]={value:m,text:g,type:u,isGrouped:f,isExpandable:C,visibleIndex:p}}const{onDataSelected:l}=this.props;l(t,o)}handleAdvancedFilterChange(e,t,n){const{model:s}=this.props,i=s.getColumnIndexByName(e.name);N(i),this.setAdvancedFilter(i,t,n)}handleAdvancedFilterSortChange(e,t,n=!1){const{model:s}=this.props,i=s.getColumnIndexByName(e.name);N(i);const o=s.columns[i].name,l=F.getSortForColumn(s.sort,o);let a=null;(l==null||l.direction!==t)&&(t===F.sortDirection.descending?a=e.sort().desc():a=e.sort().asc());const d=F.setSortForColumn(s.sort,o,a,n);me.info("Setting table sorts",d),this.startLoading("Sorting..."),this.setState({sorts:d}),this.grid?.forceUpdate()}handleAdvancedFilterDone(){this.grid?.focus()}handleAdvancedMenuOpened(e){this.setState({shownAdvancedFilter:e})}handleGotoRowOpened(){this.setState({isGotoShown:!0})}handleGotoRowClosed(){this.setState({isGotoShown:!1})}handleAdvancedMenuClosed(e){const{focusedFilterBarColumn:t,isFilterBarShown:n}=this.state;n&&t===e&&this.filterInputRef?.current!==null?(this.filterInputRef?.current.focus(),this.setState({shownAdvancedFilter:null})):this.setState({focusedFilterBarColumn:null,shownAdvancedFilter:null})}handleCancel(){this.rollback()}handleChartChange(){}handleChartCreate(e){const{model:t,onCreateChart:n}=this.props;n(e,t)}handleGridError(e){me.warn("Grid Error",e),this.setState({toastMessage:r.jsx("div",{className:"error-message",children:`${e}`})})}handleFilterBarChange(e){this.startLoading("Filtering...",!0),this.setState(({focusedFilterBarColumn:t,quickFilters:n})=>{const s=new Map(n);if(t!=null){const i=this.getModelColumn(t);N(i),this.applyQuickFilter(i,e,s)}return{quickFilters:s}})}handleFilterBarDone(e=!0,t=!0){e&&this.grid?.focus(),t&&this.setState({focusedFilterBarColumn:null})}handleFilterBarTab(e){const{focusedFilterBarColumn:t}=this.state;N(t),e?this.focusFilterBar(t-1):this.focusFilterBar(t+1)}handleFormatSelection(e,t){const{model:n}=this.props,s=n.columns[e],{customColumnFormatMap:i}=this.state,o=new Map(i);if(t!=null){const l=F.getNormalizedType(s.type);N(l);const a=gn.makeColumnFormattingRule(l,s.name,t);o.set(s.name,a)}else o.delete(s.name);this.updateFormatter({customColumnFormatMap:o})}handleMenu(e){e.stopPropagation(),this.setState({isMenuShown:!0})}handleMenuClose(){this.setState({isMenuShown:!1,openOptions:[]})}handleMenuBack(){this.setState(({openOptions:e})=>{const t=[...e];return t.pop(),{openOptions:t}})}handleMenuSelect(e){this.setState(({openOptions:t})=>({openOptions:[...t,e]}))}handleRequestFailed(e){const t=e;if(me.error("request failed:",t.detail),this.stopLoading(),this.canRollback())this.startLoading("Rolling back changes...",!0),this.rollback();else{me.error("Table failed and unable to rollback");const{onError:n}=this.props;n(new Error(`Error displaying table: ${t.detail}`))}}handleUpdate(){this.stopLoading(),me.debug2("Received model update");const{advancedFilters:e,aggregationSettings:t,customColumns:n,quickFilters:s,reverseType:i,rollupConfig:o,searchFilter:l,selectDistinctColumns:a,sorts:d}=this.state,h={advancedFilters:e,aggregationSettings:t,customColumns:n,quickFilters:s,reverseType:i,rollupConfig:o,searchFilter:l,selectDistinctColumns:a,sorts:d};uc(h)?this.lastLoadedConfig=null:this.lastLoadedConfig=h,this.grid?.forceUpdate()}handleViewChanged(e){const{model:t}=this.props,{selectionEndRow:n=0}=this.grid?.state??{};let s=0;if(Xe(t)&&t.isEditable){N(e);const{bottomViewport:i}=e,o=t.rowCount-t.floatingBottomRowCount;n===o-1?s=t.pendingRowCount+1:n===o-2?s=t.pendingRowCount:s=Math.max(0,i-(t.rowCount-t.pendingRowCount)-t.floatingTopRowCount-t.floatingBottomRowCount-1)}this.setState({metrics:e,pendingRowCount:s})}handleSelectionChanged(e){N(e);const{onSelectionChanged:t}=this.props,{copyOperation:n}=this.state;this.setState({selectedRanges:e}),n!=null&&this.setState({copyOperation:null}),t(e)}handleMovedColumnsChanged(e,t){this.setState({movedColumns:e},t)}handleHeaderGroupsChanged(e){const{model:t}=this.props;this.setState({columnHeaderGroups:Se.parseColumnHeaderGroups(t,e).groups},()=>this.grid?.forceUpdate())}handleTooltipRef(e){e?.startTimer(),this.tooltip=e}handleConditionalFormatsChange(e){me.debug("Updated conditional formats",e),this.setState({conditionalFormats:e})}handleConditionalFormatCreate(){me.debug("Create new conditional format");const{openOptions:e,conditionalFormats:t}=this.state;this.setState({openOptions:[...e,{type:Ne.CONDITIONAL_FORMATTING_EDIT,title:"Create Formatting Rule"}],conditionalFormatEditIndex:t.length,conditionalFormatPreview:void 0})}handleConditionalFormatEdit(e){me.debug("Edit conditional format",e);const{openOptions:t,conditionalFormats:n}=this.state;this.setState({openOptions:[...t,{type:Ne.CONDITIONAL_FORMATTING_EDIT,title:"Edit Formatting Rule"}],conditionalFormatEditIndex:e,conditionalFormatPreview:{...n[e]}})}handleConditionalFormatEditorUpdate=Ye(e=>{this.setState({conditionalFormatPreview:e})},QE);handleConditionalFormatEditorSave(e){me.debug("Save conditional format changes",e),this.setState(t=>{if(t.conditionalFormatEditIndex===null)return me.debug("Invalid format index"),null;const n=[...t.conditionalFormats];return n[t.conditionalFormatEditIndex]=e,{conditionalFormats:n}},()=>{this.handleMenuBack()})}handleConditionalFormatEditorCancel(){this.handleMenuBack(),this.setState({conditionalFormatEditIndex:null})}handleUpdateCustomColumns(e){me.info("handleUpdateCustomColumns:",e);const{model:t}=this.props,{movedColumns:n,sorts:s,quickFilters:i,advancedFilters:o,selectDistinctColumns:l}=this.state,{columns:a}=t,d=t.customColumns.map(u=>`${u}`),h=Se.getRemovedCustomColumnNames(d,e);if(h.length>0){const u=Se.removeSortsInColumns(s,h),m=Se.removeFiltersInColumns(a,i,h),g=Se.removeFiltersInColumns(a,o,h),p=Se.removeColumnFromMovedColumns(a,n,h),C=Se.removeColumnsFromSelectDistinctColumns(l,h);u.length!==s.length&&(me.debug("removing sorts from removed custom columns..."),this.setState({sorts:u})),(m.size!==i.size||g.size!==o.size)&&(me.debug("removing filters from removed custom columns..."),this.setState({quickFilters:m,advancedFilters:g})),st(n,p)||(me.debug("change moved columns for removed custom columns",p),this.setState({movedColumns:p})),st(l,C)||(me.debug("change selectDistinct columns for removed custom columns",p),this.setState({selectDistinctColumns:C}))}this.setState({customColumns:e}),e.length>0&&this.startLoading("Applying custom columns...")}handleCustomColumnsChanged(){me.debug("custom columns changed");const{isReady:e}=this.state;e?(this.stopLoading(),this.grid?.forceUpdate()):this.initState()}handlePendingCommitClicked(){return this.commitPending()}handlePendingDiscardClicked(){return this.discardPending()}handlePendingDataUpdated(){me.debug("pending data updated");const{model:e}=this.props,{pendingDataMap:t,pendingDataErrors:n}=e;this.setState({pendingDataMap:t,pendingDataErrors:n,pendingSaveError:null}),this.grid?.forceUpdate()}handleAggregationsChange(e){me.debug("handleAggregationsChange",e),this.startLoading(`Aggregating ${e.aggregations.map(t=>t.operation).join(", ")}...`),this.setState({aggregationSettings:e})}handleAggregationChange(e){me.debug("handleAggregationChange",e),this.startLoading(`Aggregating ${e.operation}...`),this.setState(({aggregationSettings:t})=>({selectedAggregation:e,aggregationSettings:{...t,aggregations:t.aggregations.map(n=>n.operation===e.operation?e:n)}}))}handleAggregationEdit(e){me.debug("handleAggregationEdit",e);const{openOptions:t}=this.state;this.setState({openOptions:[...t,{type:Ne.AGGREGATION_EDIT,title:`Edit Columns to ${e.operation}`}],selectedAggregation:e})}handleRollupChange(e){me.info("Rollup change",e),this.resetGridViewState(),this.showAllColumns(),this.clearAllFilters(),this.startLoading(`Grouping by columns ${e?.columns?.join(", ")??""}...`),this.setState({rollupConfig:e,movedColumns:[],frozenColumns:[],sorts:[],reverseType:F.REVERSE_TYPE.NONE,selectDistinctColumns:[]})}handleSelectDistinctChanged(e){me.debug("SelectDistinct change",e),this.resetGridViewState(),this.showAllColumns(),this.clearAllFilters(),this.startLoading(`Selecting distinct values in ${e.length>0?e.join(", "):""}...`),this.setState({selectDistinctColumns:e,movedColumns:[],sorts:[],reverseType:F.REVERSE_TYPE.NONE})}handleDownloadTableStart(){const{canDownloadCsv:e}=this.props;e?this.setState({isTableDownloading:!0,tableDownloadProgress:0,tableDownloadEstimatedTime:null,tableDownloadStatus:Ms.DOWNLOAD_STATUS.INITIATING}):me.error("Attempted to handleDownloadTableStart for user without download CSV permission.")}handleDownloadTable(e,t,n,s,i,o,l){const{canDownloadCsv:a}=this.props;a?(me.info("start table downloading",e,t,n,s,i,o,l),this.setState(()=>(this.tableSaver&&this.tableSaver.startDownload(e,t,n,s,i,o,l),{tableDownloadStatus:Ms.DOWNLOAD_STATUS.DOWNLOADING}))):me.error("Attempted to handleDownloadTable for user without download CSV permission.")}async seekRow(e,t=!1){const{gotoValueSelectedColumnName:n,gotoValueSelectedFilter:s}=this.state,{model:i}=this.props;if(!i.isSeekRowAvailable||e==="")return;const o=Se.getColumnByName(i.columns,n);if(o===void 0)return;let l=this.grid?.state.cursorRow;l==null&&(l=0);const a=s===be.contains,d=s===be.eq||s===be.eqIgnoreCase;try{const{formatter:h}=i,u=F.getNormalizedType(o.type);let m;switch(u){case F.dataType.CHAR:case F.dataType.STRING:{m=await i.seekRow(l,o,I.ValueType.STRING,e,d,a,t??!1);break}case F.dataType.DATETIME:{const[g]=Xs.parseDateRange(e,h.timeZone);m=await i.seekRow(l,o,I.ValueType.DATETIME,g,void 0,void 0,t??!1);break}case F.dataType.DECIMAL:case F.dataType.INT:{if(!F.isBigDecimalType(o.type)&&!F.isBigIntegerType(o.type)){let g=parseInt(e,10);e==="-Infinity"?g=Number.NEGATIVE_INFINITY:e==="Infinity"&&(g=Number.POSITIVE_INFINITY),m=await i.seekRow(l,o,I.ValueType.NUMBER,g,void 0,void 0,t??!1)}else m=await i.seekRow(l,o,I.ValueType.STRING,e,void 0,void 0,t??!1);break}default:m=await i.seekRow(l,o,I.ValueType.STRING,F.makeValue(o.type,e,h.timeZone),void 0,void 0,t??!1)}this.grid?.setFocusRow(m),this.setState({gotoValueError:""})}catch{this.setState({gotoValueError:"invalid input"})}}handleCancelDownloadTable(){this.tableSaver?.cancelDownload(),this.setState({isTableDownloading:!1})}handleDownloadProgressUpdate=vs((e,t)=>{const{tableDownloadStatus:n}=this.state;n===Ms.DOWNLOAD_STATUS.DOWNLOADING&&this.setState({tableDownloadProgress:e,tableDownloadEstimatedTime:t})},qE);handleDownloadCompleted(){this.setState({isTableDownloading:!1,tableDownloadProgress:100,tableDownloadStatus:Ms.DOWNLOAD_STATUS.FINISHED})}handleDownloadCanceled(){this.setState({isTableDownloading:!1,tableDownloadProgress:0,tableDownloadStatus:Ms.DOWNLOAD_STATUS.CANCELED})}deleteRanges(e){const{model:t}=this.props;this.pending.add(t.delete(e)).catch(n=>{ye.isCanceled(n)||me.error("Unable to delete ranges",e,n)})}resetColumnSelection(){if(this.grid==null)return;const{isSelectingColumn:e}=this.props;if(e){const{columnAllowedCursor:t}=this.props;this.grid.setState({cursor:t})}else this.grid.setState({cursor:null}),this.setState({hoverSelectColumn:null})}resetGridViewState(e=!0){this.grid&&(this.grid.clearSelectedRanges(),this.grid.setViewState({left:0,top:0,topOffset:0,leftOffset:0},e))}sendStateChange(){if(!this.grid)return;const{state:e}=this,{state:t}=this.grid,{onStateChange:n}=this.props;n(e,t)}handleOverflowClose(){this.setState({showOverflowModal:!1})}getColumnBoundingRect(){const{metrics:e,shownColumnTooltip:t}=this.state;N(e),N(t);const n=this.gridWrapper?.getBoundingClientRect(),s=20;N(n);const{columnHeaderHeight:i,allColumnXs:o,allColumnWidths:l,width:a,columnHeaderMaxDepth:d}=e,h=o.get(t),u=l.get(t);N(h),N(u);const m=n.left+Oe(h+u/2,s,a-s);return{top:n.top+(d-1)*i,left:n.left+Oe(h+u/2,s,a-s),bottom:n.top+d*i,right:n.left+Oe(h+u/2,s,a-s)+1,width:1,height:i,x:m,y:n.top,toJSON:()=>{throw new Error("not implemented")}}}getOverflowButtonTooltip=Re(e=>{if(e==null)return null;const t={position:"absolute",...e,pointerEvents:"none"},n={placement:"left",modifiers:{flip:{behavior:["left","right"]}}};return r.jsx("div",{style:t,children:r.jsx(ot,{options:n,ref:this.handleTooltipRef,children:"View full contents"},Date.now())})});getExpandCellTooltip=Re(e=>{if(e==null)return null;const{expandTooltipDisplayValue:t}=this.state,n={position:"absolute",...e,pointerEvents:"none"},s={placement:"bottom-start"};return r.jsx("div",{style:n,children:r.jsx(ot,{options:s,ref:this.handleTooltipRef,children:r.jsxs("div",{style:{textAlign:"left"},children:["Click to ",t," row",r.jsx("br",{}),Ts.isMacPlatform()?"⌘":"Ctrl+","Click to expand row and all children"]})},Date.now())})});getLinkHoverTooltip=Re(e=>{if(e==null)return null;const{linkHoverDisplayValue:t}=this.state,n={position:"absolute",...e,pointerEvents:"none"},s={placement:"bottom"};return r.jsx("div",{style:n,children:r.jsx(ot,{options:s,ref:this.handleTooltipRef,children:r.jsxs("div",{className:"link-hover-tooltip",children:[t," - Click once to follow.",r.jsx("br",{}),"Click and hold to select this cell."]})})})});handleGotoRowSelectedRowNumberSubmit(){const{gotoRow:e}=this.state;this.focusRowInGrid(e)}focusRowInGrid(e){const{model:t}=this.props,{rowCount:n}=t;if(this.setState({gotoRow:e}),e===""){this.setState({gotoRowError:"",gotoValueError:""});return}const s=parseInt(e,10);s>n||s<-n?this.setState({gotoRowError:"Invalid row index"}):s===0?(this.setState({gotoRowError:"",gotoValueError:""}),this.grid?.setFocusRow(0)):s<0?(this.setState({gotoRowError:"",gotoValueError:""}),this.grid?.setFocusRow(s+n)):(this.grid?.setFocusRow(s-1),this.setState({gotoRowError:"",gotoValueError:""}))}handleGotoRowSelectedRowNumberChanged(e){const t=e.target.value;this.focusRowInGrid(t)}getColumnTooltip(e,t,n){const{columnHeaderHeight:s,columnHeaderMaxDepth:i,allColumnXs:o,allColumnWidths:l,width:a}=t,d=o.get(e),h=l.get(e);if(d==null||h==null)return null;const u=Math.max(0,d);let m=h;d+h>a?m=a-d:d<0&&(m=h-Math.abs(d));const g={position:"absolute",top:(i-1)*s,left:u,width:m,height:s,pointerEvents:"none"},p={clientWidth:1,clientHeight:s,getBoundingClientRect:this.getColumnBoundingRect},C={placement:"bottom",modifiers:{flip:{behavior:["bottom","top"]}}},f=this.getModelColumn(e);if(f==null)return null;const b=n.columns[f];return b==null?null:r.jsx("div",{style:g,children:r.jsx(ot,{timeout:400,interactive:!0,options:C,ref:this.handleTooltipRef,referenceObject:p,onExited:()=>{this.setState({shownColumnTooltip:null})},children:r.jsx(aT,{model:n,column:b,onStatistics:()=>{this.tooltip?.update()}})},b.name)})}handleGotoValueSelectedColumnNameChanged(e){const{model:t}=this.props,n=this.grid?.state.cursorRow;if(n!=null){const s=t.getColumnIndexByName(e),i=Se.getColumnByName(t.columns,e);if(s==null||i==null)return;const o=t.valueForCell(s,n),l=Se.convertValueToText(o,i.type);this.setState({gotoValueSelectedColumnName:e,gotoValue:l,gotoValueError:""})}this.setState({gotoValueSelectedColumnName:e,gotoValueError:""})}handleGotoValueSelectedFilterChanged(e){this.setState({gotoValueSelectedFilter:e,gotoValueError:""})}handleGotoValueChanged=e=>{this.setState({gotoValue:e}),this.debouncedSeekRow(e)};debouncedSeekRow=Ye(e=>{this.seekRow(e)},ZE);handleGotoValueSubmitted(e){const{gotoValue:t}=this.state;this.seekRow(t,e)}render(){const{children:e,customFilters:t,getDownloadWorker:n,isSelectingColumn:s,isStuckToBottom:i,isStuckToRight:o,model:l,name:a,onlyFetchVisibleColumns:d,alwaysFetchColumns:h,advancedSettings:u,onAdvancedSettingsChange:m,canDownloadCsv:g,onCreateChart:p}=this.props,{metricCalculator:C,metrics:f,isFilterBarShown:b,isSelectingPartition:w,isMenuShown:S,isReady:T,copyOperation:y,focusedFilterBarColumn:E,loadingText:R,loadingScrimProgress:x,loadingSpinnerShown:D,keyHandlers:M,mouseHandlers:O,shownColumnTooltip:H,hoverAdvancedFilter:L,shownAdvancedFilter:V,hoverSelectColumn:U,quickFilters:j,advancedFilters:P,partition:Q,partitionFilters:$,partitionTable:J,partitionColumn:A,searchFilter:W,selectDistinctColumns:q,movedColumns:Z,movedRows:le,formatter:G,conditionalFormats:oe,conditionalFormatPreview:ue,conditionalFormatEditIndex:ae,sorts:ce,reverseType:we,customColumns:He,selectedRanges:Fe,isTableDownloading:mt,tableDownloadStatus:et,tableDownloadProgress:De,tableDownloadEstimatedTime:gt,showSearchBar:lt,searchValue:vt,selectedSearchColumns:kt,invertSearchColumns:Cn,aggregationSettings:zt,selectedAggregation:So,rollupConfig:Rs,openOptions:Kt,pendingSavePromise:Xn,pendingSaveError:ti,pendingRowCount:ki,pendingDataErrors:ni,pendingDataMap:si,toastMessage:wo,frozenColumns:vo,columnHeaderGroups:Zn,showOverflowModal:xs,overflowText:la,overflowButtonTooltipProps:To,expandCellTooltipProps:Mi,linkHoverTooltipProps:Li,isGotoShown:Oi,gotoRow:Eo,gotoRowError:aa,gotoValueError:ra,gotoValueSelectedColumnName:da,gotoValue:ca,gotoValueSelectedFilter:ha}=this.state;if(!T)return null;const Ds=this.getTheme(),yo=this.getCachedFilter(t,j,P,$,W),ii=C.getUserColumnWidths(),Ro=this.getCachedStateOverride(U,b,s,x,j,P,ce,we,Rs,S),Is=f?f.top:0,xo=f?f.bottomViewport:0;let Ai=null,_i=null;d&&(Ai=f?f.left:0,_i=f?f.right:0);const Do=f!=null&&f.width>0&&f.height>0,Io=(Rs?.columns?.length??0)>0;let Fo=null;const ua=f?Math.min(Math.max(Hn.minDebounce,Math.round(f.rowCount/200)),Hn.maxDebounce):Hn.maxDebounce;if(b&&E!=null&&f!=null){const{gridX:Ge,gridY:Ae,allColumnXs:Yt,allColumnWidths:Pi,width:oi}=f,Qn=Yt.get(E),Mt=Pi.get(E);if(Qn!=null&&Mt!=null){const xt=Ge+Qn,Nn=Ae-(Ds.filterBarHeight??0),Fs=Mt+1,Ns=(Ds.filterBarHeight??0)-1,_o={top:Nn,left:xt,minWidth:Math.min(Fs,oi-xt),height:Ns};let kn="",li=!0;const ks=this.getModelColumn(E);N(ks);const ai=j.get(ks),Jn=P.get(ks);ai!=null&&(kn=ai.text,li=ai.filter!=null);const ri=j.size!==0||P.size!==0;Fo=r.jsx(av,{ref:this.filterInputRef,style:_o,className:Y({error:!li,active:kn!==""||Jn!=null,"iris-grid-has-filter":ri}),isAdvancedFilterSet:Jn!=null,onAdvancedFiltersTriggered:()=>{this.setState({shownAdvancedFilter:E})},onChange:this.handleFilterBarChange,onDone:this.handleFilterBarDone,onTab:this.handleFilterBarTab,onContextMenu:this.grid?.handleContextMenu,debounceMs:ua,value:kn},E)}}let No=null;if(R!=null){const Ge=r.jsxs("div",{className:"iris-grid-loading-status",children:[r.jsx("div",{className:Y("iris-grid-loading-status-bar",{show:D}),children:R}),r.jsxs("button",{type:"button",onClick:this.handleCancel,className:Y("iris-grid-btn-cancel",{show:D}),children:[r.jsx(ee,{icon:uo,transform:"down-1"}),"Cancel"]})]}),Ae=f?f.gridY:0;No=r.jsx("div",{className:"iris-grid-loading",style:{top:Ae},children:Ge})}let ko=null;H!=null&&f&&(ko=this.getColumnTooltip(H,f,l),this.tooltip?.update());const Mo=[];if(f&&b){const{gridX:Ge,gridY:Ae,visibleColumns:Yt,allColumnXs:Pi,allColumnWidths:oi}=f,{filterBarHeight:Qn}=Ds;for(let Mt=0;Mt<Yt.length;Mt+=1){const xt=Yt[Mt],Nn=Pi.get(xt),Fs=oi.get(xt),Ns=this.getModelColumn(xt);if(Ns!=null&&l.isFilterable(Ns)&&Nn!=null&&Fs!=null&&Fs>0){const kn=Ge+Nn+Fs-24,ks={position:"absolute",top:Ae-(Qn??0)+2,left:kn},Jn=P.get(Ns)!=null,ri=xt===L||xt===E||Jn,ga=r.jsx("div",{className:Y("advanced-filter-button-container",{hidden:!ri}),style:ks,children:ri&&r.jsx(B,{kind:"ghost",className:Y("btn-link-icon advanced-filter-button",{"filter-set":Jn}),onClick:()=>{this.setState({shownAdvancedFilter:xt})},onContextMenu:nm=>{this.grid?.handleContextMenu(nm)},onMouseEnter:()=>{this.setState({hoverAdvancedFilter:xt})},onMouseLeave:()=>{this.setState({hoverAdvancedFilter:null})},children:r.jsxs("div",{className:"fa-layers",children:[r.jsx(ee,{icon:cr,className:"filter-solid"}),r.jsx(ee,{icon:dl,className:"filter-light"})]})})},xt);Mo.push(ga)}}}const Lo=[];if(f){const{gridX:Ge,visibleColumns:Ae,allColumnXs:Yt,allColumnWidths:Pi,columnHeaderHeight:oi}=f;for(let Qn=0;Qn<Ae.length;Qn+=1){const Mt=Ae[Qn],xt=Yt.get(Mt),Nn=Pi.get(Mt);if(xt!=null&&Nn!=null&&Nn>0){const Fs=Ge+xt,Ns=Ge+xt+Nn-20,_o=b?{position:"absolute",top:oi,left:Ns,width:20,height:Ds.filterBarHeight}:{position:"absolute",top:0,left:Fs,width:Nn,height:oi},kn=this.getModelColumn(Mt);if(kn!=null){const li=l.columns[kn],ks=P.get(kn),{options:ai}=ks||{},Jn=F.getSortForColumn(l.sort,li.name),ri=Jn?Jn.direction:null,ga=r.jsx("div",{className:"advanced-filter-menu-container",style:_o,children:r.jsx(Vl,{className:"advanced-filter-menu-popper",onEntered:this.getAdvancedMenuOpenedHandler(Mt),onExited:()=>{this.handleAdvancedMenuClosed(Mt)},isShown:V===Mt,interactive:!0,closeOnBlur:!0,options:{positionFixed:!0},children:this.getCachedAdvancedFilterMenuActions(l,li,ai,ri,G)})},Mt);Lo.push(ga)}}}}const Oo=this.getCachedOptionItems(p!==void 0&&l.isChartBuilderAvailable,l.isCustomColumnsAvailable,l.isFormatColumnsAvailable,l.isRollupAvailable,l.isTotalsAvailable||Io,l.isSelectDistinctAvailable,l.isExportAvailable,this.toggleFilterBarAction,this.toggleSearchBarAction,this.toggleGotoRowAction,b,lt,g,this.isTableSearchAvailable(),Oi,u.size>0),Ao=this.getCachedHiddenColumns(C,ii),ma=Kt.map(Ge=>{switch(Ge.type){case Ne.CHART_BUILDER:return r.jsx(TT,{model:l,onChange:this.handleChartChange,onSubmit:this.handleChartCreate},Ne.CHART_BUILDER);case Ne.VISIBILITY_ORDERING_BUILDER:return r.jsx(oE,{model:l,movedColumns:Z,hiddenColumns:Ao,columnHeaderGroups:Zn,onColumnVisibilityChanged:this.handleColumnVisibilityChanged,onReset:this.handleColumnVisibilityReset,onMovedColumnsChanged:this.handleMovedColumnsChanged,onColumnHeaderGroupChanged:this.handleHeaderGroupsChanged},Ne.VISIBILITY_ORDERING_BUILDER);case Ne.CONDITIONAL_FORMATTING:return r.jsx(CE,{rules:oe,onChange:this.handleConditionalFormatsChange,onCreate:this.handleConditionalFormatCreate,onSelect:this.handleConditionalFormatEdit});case Ne.CONDITIONAL_FORMATTING_EDIT:return N(l.columns),N(this.handleConditionalFormatEditorUpdate),r.jsx(WE,{columns:l.columns,rule:ue,onUpdate:this.handleConditionalFormatEditorUpdate,onSave:this.handleConditionalFormatEditorSave,onCancel:this.handleConditionalFormatEditorCancel});case Ne.CUSTOM_COLUMN_BUILDER:return r.jsx(DT,{model:l,customColumns:He,onSave:this.handleUpdateCustomColumns,onCancel:this.handleMenuBack},Ne.CUSTOM_COLUMN_BUILDER);case Ne.ROLLUP_ROWS:return r.jsx(FT,{model:l,onChange:this.handleRollupChange,config:Rs},Ne.ROLLUP_ROWS);case Ne.AGGREGATIONS:return r.jsx(uT,{settings:zt,isRollup:Io,onChange:this.handleAggregationsChange,onEdit:this.handleAggregationEdit});case Ne.AGGREGATION_EDIT:return So&&r.jsx(gT,{aggregation:So,columns:l.originalColumns,onChange:this.handleAggregationChange});case Ne.TABLE_EXPORTER:return r.jsx(Ms,{model:l,name:a,userColumnWidths:ii,movedColumns:Z,isDownloading:mt,tableDownloadStatus:et,tableDownloadProgress:De,tableDownloadEstimatedTime:gt??void 0,onDownload:this.handleDownloadTable,onDownloadStart:this.handleDownloadTableStart,onCancel:this.handleCancelDownloadTable,selectedRanges:Fe},Ne.TABLE_EXPORTER);case Ne.SELECT_DISTINCT:return r.jsx(gE,{model:l,selectDistinctColumns:q,onChange:this.handleSelectDistinctChanged});case Ne.ADVANCED_SETTINGS:return r.jsx($r,{items:u,onChange:m});default:throw Error(`Unexpected option type ${Ge.type}`)}});return r.jsxs("div",{className:"iris-grid",role:"presentation",children:[r.jsxs("div",{className:"iris-grid-column",children:[e!=null&&r.jsx("div",{className:"iris-grid-bar",children:e}),r.jsx(Wt,{in:w,timeout:Je.transitionSlowMs,classNames:"iris-grid-bar-horizontal",onEnter:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExit:this.handleAnimationStart,onExited:this.handleAnimationEnd,mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:"iris-grid-partition-selector-wrapper iris-grid-bar iris-grid-bar-primary",children:J&&A&&Q!=null&&r.jsx(hE,{table:J,getFormattedString:(Ge,Ae,Yt)=>l.displayString(Ge,Ae,Yt),columnName:A.name,partition:Q,onChange:this.handlePartitionChange,onFetchAll:this.handlePartitionFetchAll,onAppend:this.handlePartitionAppend,onDone:this.handlePartitionDone})})}),r.jsx(Wt,{in:lt,timeout:Je.transitionSlowMs,classNames:"iris-grid-bar-horizontal",onEnter:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExit:this.handleAnimationStart,onExited:this.handleAnimationEnd,mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:"iris-grid-bar",children:r.jsx(Ko,{value:vt,selectedColumns:kt,invertSelection:Cn,onChange:this.handleCrossColumnSearch,columns:l.columns,ref:this.crossColumnRef})})}),r.jsxs("div",{className:"grid-wrapper",ref:Ge=>{this.gridWrapper=Ge},children:[r.jsx(Cw,{ref:Ge=>{this.grid=Ge},isStickyBottom:!Xe(l)||!l.isEditable,isStuckToBottom:i,isStuckToRight:o,metricCalculator:C,model:l,keyHandlers:M,mouseHandlers:O,movedColumns:Z,movedRows:le,onError:this.handleGridError,onViewChanged:this.handleViewChanged,onSelectionChanged:this.handleSelectionChanged,onMovedColumnsChanged:this.handleMovedColumnsChanged,renderer:this.renderer,stateOverride:Ro,theme:Ds}),r.jsx(GE,{isOpen:xs,text:la,onClose:this.handleOverflowClose}),Do&&r.jsx(Kv,{model:l,modelColumns:l.columns,top:Is,bottom:xo,left:Ai,right:_i,filter:yo,formatter:G,sorts:ce,reverseType:we,movedColumns:Z,customColumns:He,hiddenColumns:Ao,alwaysFetchColumns:this.getAlwaysFetchColumns(h,l.columns,Z,l.floatingLeftColumnCount,l.floatingRightColumnCount,this.grid?.state.draggingColumn?.range),formatColumns:this.getCachedPreviewFormatColumns(l.columns,oe,ue,Kt[Kt.length-1]?.type===Ne.CONDITIONAL_FORMATTING_EDIT?ae??void 0:void 0),rollupConfig:this.getModelRollupConfig(l.originalColumns,Rs,zt),totalsConfig:this.getModelTotalsConfig(l.columns,Rs,zt),selectDistinctColumns:q,pendingRowCount:ki,pendingDataMap:si,frozenColumns:vo,columnHeaderGroups:Zn}),!S&&r.jsx("div",{className:"grid-settings-button",children:r.jsx(B,{kind:"ghost","data-testid":`btn-iris-grid-settings-button-${a}`,onClick:this.handleMenu,icon:r.jsx(ee,{icon:Bg,transform:"up-1"}),tooltip:"Table Options"})}),Fo,No,Mo,ko,Lo,To&&this.getOverflowButtonTooltip(To),Mi&&this.getExpandCellTooltip(Mi),Li&&this.getLinkHoverTooltip(Li)]}),r.jsx(YE,{model:l,isShown:Oi,gotoRow:Eo,gotoRowError:aa,gotoValueError:ra,onGotoRowSubmit:this.handleGotoRowSelectedRowNumberSubmit,onGotoRowNumberChanged:this.handleGotoRowSelectedRowNumberChanged,onClose:this.handleGotoRowClosed,onEntering:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExiting:()=>{this.handleAnimationStart(),this.focus()},onExited:this.handleAnimationEnd,gotoValueSelectedColumnName:da,gotoValue:ca,gotoValueFilter:ha,onGotoValueSelectedColumnNameChanged:this.handleGotoValueSelectedColumnNameChanged,onGotoValueSelectedFilterChanged:this.handleGotoValueSelectedFilterChanged,onGotoValueChanged:this.handleGotoValueChanged,onGotoValueSubmit:this.handleGotoValueSubmitted}),r.jsx(Zw,{error:ti,isSaving:Xn!=null,saveTooltip:`Commit (${this.commitAction.shortcut.getDisplayText()})`,discardTooltip:`Discard (${this.discardAction.shortcut.getDisplayText()})`,pendingDataErrors:ni,pendingDataMap:si,onEntering:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExiting:this.handleAnimationStart,onExited:this.handleAnimationEnd,onSave:this.handlePendingCommitClicked,onDiscard:this.handlePendingDiscardClicked}),r.jsx($v,{children:wo}),r.jsx(ov,{model:l,copyOperation:y??void 0,onEntering:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExiting:this.handleAnimationStart,onExited:this.handleAnimationEnd}),r.jsx(jn,{ref:Ge=>{this.tableSaver=Ge},getDownloadWorker:n,onDownloadCompleted:this.handleDownloadCompleted,onDownloadCanceled:this.handleDownloadCanceled,onDownloadProgressUpdate:this.handleDownloadProgressUpdate,isDownloading:et===Ms.DOWNLOAD_STATUS.DOWNLOADING,formatter:G})]}),r.jsx(Wt,{in:S,timeout:Je.transitionMidMs,classNames:"slide-left",onEntering:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExiting:this.handleAnimationStart,onExited:this.handleAnimationEnd,mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:"table-sidebar",children:r.jsxs(Hm,{children:[r.jsx(ud,{title:"Table Options",onClose:this.handleMenuClose,children:r.jsx(Gc,{onSelect:Ge=>this.handleMenuSelect(Oo[Ge]),items:Oo})}),ma.map((Ge,Ae)=>r.jsx(ud,{title:Kt[Ae].title,onBack:this.handleMenuBack,onClose:this.handleMenuClose,children:Ge},Kt[Ae].type))]})})}),r.jsx(ie,{actions:this.contextActions})]})}}const Au=Hn;class ey extends Error{isMissingKey=!0;rowIndex;columnName;constructor(e,t){super(`${t} can't be empty (on pending row ${e+1})`),this.rowIndex=e,this.columnName=t}}const ty=ey,tt=ne.module("IrisGridTableModel"),ny=150,sy=0,iy=[];function Ks(c){return c.table!==void 0}class ao extends Ce{static ROW_BUFFER_PAGES=1;seekRow(e,t,n,s,i,o,l){throw new Error("Method not implemented.")}export(){throw new Error("Method not implemented.")}columnStatistics(e){throw new Error("Method not implemented.")}get customColumns(){return[]}set customColumns(e){throw new Error("Method not implemented.")}get formatColumns(){return[]}set formatColumns(e){throw new Error("Method not implemented.")}updateFrozenColumns(e){throw new Error("Method not implemented.")}get rollupConfig(){throw new Error("Method not implemented.")}set rollupConfig(e){throw new Error("Method not implemented.")}get selectDistinctColumns(){throw new Error("Method not implemented.")}set selectDistinctColumns(e){throw new Error("Method not implemented.")}get columns(){return this.table.columns}irisFormatter;inputTable;subscription;table;viewport;viewportData;formattedStringData;pendingStringData;isSaveInProgress;totalsTable;totalsTablePromise;totals;totalsDataMap;pendingNewDataMap;pendingNewRowCount=0;_columnHeaderGroupMap=new Map;columnHeaderParentMap=new Map;_columnHeaderMaxDepth=null;_columnHeaderGroups=[];_movedColumns=null;constructor(e,t=new gn,n=null){super(),this.handleTableDisconnect=this.handleTableDisconnect.bind(this),this.handleTableReconnect=this.handleTableReconnect.bind(this),this.handleTableUpdate=this.handleTableUpdate.bind(this),this.handleTotalsUpdate=this.handleTotalsUpdate.bind(this),this.handleRequestFailed=this.handleRequestFailed.bind(this),this.handleCustomColumnsChanged=this.handleCustomColumnsChanged.bind(this),this.irisFormatter=t,this.inputTable=n,this.subscription=null,this.table=e,this.viewport=null,this.viewportData=null,this.formattedStringData=[],this.pendingStringData=[],this.isSaveInProgress=!1,this.totalsTable=null,this.totalsTablePromise=null,this.totals=null,this.totalsDataMap=null,this.pendingNewDataMap=new Map,this.pendingNewRowCount=0,this.columnHeaderGroups=Se.parseColumnHeaderGroups(this,this.layoutHints?.columnGroups??[]).groups}close(){this.table.close(),this.totalsTable!==null&&this.totalsTable.close(),this.totalsTablePromise!==null&&this.totalsTablePromise.cancel()}startListening(){super.startListening(),this.table.addEventListener(I.Table.EVENT_DISCONNECT,this.handleTableDisconnect),this.table.addEventListener(I.Table.EVENT_RECONNECT,this.handleTableReconnect),this.table.addEventListener(I.Table.EVENT_UPDATED,this.handleTableUpdate),this.table.addEventListener(I.Client.EVENT_REQUEST_FAILED,this.handleRequestFailed),this.table.addEventListener(I.Table.EVENT_CUSTOMCOLUMNSCHANGED,this.handleCustomColumnsChanged),this.totalsTable!=null&&this.addTotalsListeners(this.totalsTable),this.applyViewport()}stopListening(){super.stopListening(),this.table.removeEventListener(I.Table.EVENT_DISCONNECT,this.handleTableDisconnect),this.table.removeEventListener(I.Table.EVENT_RECONNECT,this.handleTableReconnect),this.table.removeEventListener(I.Table.EVENT_UPDATED,this.handleTableUpdate),this.table.removeEventListener(I.Client.EVENT_REQUEST_FAILED,this.handleRequestFailed),this.table.removeEventListener(I.Table.EVENT_CUSTOMCOLUMNSCHANGED,this.handleCustomColumnsChanged),this.totalsTable!=null&&this.removeTotalsListeners(this.totalsTable),this.closeSubscription()}addTotalsListeners(e){e.addEventListener(I.Table.EVENT_UPDATED,this.handleTotalsUpdate),e.setViewport(0,0)}removeTotalsListeners(e){e.removeEventListener(I.Table.EVENT_UPDATED,this.handleTotalsUpdate)}handleTableDisconnect(){this.dispatchEvent(new ze(Ce.EVENT.DISCONNECT))}handleTableReconnect(){this.dispatchEvent(new ze(Ce.EVENT.RECONNECT))}handleTableUpdate(e){this.copyViewportData(e.detail),this.dispatchEvent(new ze(Ce.EVENT.UPDATED))}handleTotalsUpdate(e){this.copyTotalsData(e.detail),this.dispatchEvent(new ze(Ce.EVENT.UPDATED))}handleRequestFailed(e){this.dispatchEvent(new ze(Ce.EVENT.REQUEST_FAILED,e))}handleCustomColumnsChanged(){this.dispatchEvent(new ze(Ce.EVENT.COLUMNS_CHANGED,{detail:this.columns}))}get rowCount(){return this.table.size+this.pendingNewRowCount+(this.totals?.operationOrder?.length??0)}get pendingDataErrors(){return this.getCachedPendingErrors(this.pendingNewDataMap,this.columns,this.inputTable?.keyColumns.length??0)}get pendingDataMap(){return this.pendingNewDataMap}set pendingDataMap(e){e!==this.pendingNewDataMap&&(e.forEach((t,n)=>{if(!Se.isValidIndex(n))throw new Error(`Invalid rowIndex ${n}`);const{data:s}=t;s.forEach((i,o)=>{if(!Se.isValidIndex(o))throw new Error(`Invalid columnIndex ${o}`)})}),this.pendingNewDataMap=e,this.pendingNewRowCount=Math.max(this.pendingNewRowCount,this.maxPendingDataRow),this.formattedStringData=[],this.dispatchEvent(new ze(Ce.EVENT.PENDING_DATA_UPDATED)))}get pendingRowCount(){return this.pendingNewRowCount}set pendingRowCount(e){e!==this.pendingNewRowCount&&(this.pendingNewRowCount=Math.max(0,e,this.maxPendingDataRow),this.dispatchEvent(new ze(Ce.EVENT.UPDATED)))}get maxPendingDataRow(){return this.pendingNewDataMap.size>0?Math.max(...this.pendingNewDataMap.keys())+1:0}get columnCount(){return this.columns.length}get floatingBottomRowCount(){return this.totals!=null&&this.totals.showOnTop?0:this.totals?.operationOrder?.length??0}get floatingTopRowCount(){return this.totals!=null&&this.totals.showOnTop?this.totals?.operationOrder?.length??0:0}get isChartBuilderAvailable(){return!0}get isTotalsAvailable(){return this.table.getTotalsTable!=null}get isEditable(){return!this.isSaveInProgress&&this.inputTable!=null}cacheFormattedValue(e,t,n){this.formattedStringData[e]==null&&(this.formattedStringData[e]=[]),this.formattedStringData[e][t]=n}cachePendingValue(e,t,n){this.pendingStringData[e]==null&&(this.pendingStringData[e]=[]),this.pendingStringData[e][t]=n}clearPendingValue(e,t){const n=this.pendingStringData[e];n!=null&&delete n[t]}textValueForCell(e,t){if(this.pendingStringData[e]?.[t]!==void 0)return this.pendingStringData[e][t];if(this.formattedStringData[e]?.[t]===void 0){const n=this.valueForCell(e,t);if(n==null)return null;const s=this.totalsColumn(e,t)??this.columns[e],i=this.getCachedCustomColumnFormatFlag(this.formatter,s.name,s.type);let o;if(!i){const a=this.formatForCell(e,t);a?.formatString!=null&&(o=a)}const l=this.displayString(n,s.type,s.name,o);this.cacheFormattedValue(e,t,l)}return this.formattedStringData[e][t]}textForCell(e,t){const n=this.textValueForCell(e,t);if(n==null&&this.isKeyColumn(e)){const s=this.pendingRow(t);if(s!=null&&this.pendingDataMap.has(s))return"*"}if(F.isTextType(this.columns[e]?.type)){if(n===null)return"null";if(n==="")return"empty"}return n??""}truncationCharForCell(e){const t=this.columns[e],{type:n}=t;if(F.isNumberType(n)&&this.formatter.truncateNumbersWithPound)return"#"}colorForCell(e,t,n){const s=this.dataForCell(e,t);if(s){const{format:i,value:o}=s;if(o==null||o==="")return N(n.nullStringColor),n.nullStringColor;if(i&&i.color)return i.color;if(this.isPendingRow(t))return N(n.pendingTextColor),n.pendingTextColor;if(o!=null){const l=this.totalsColumn(e,t)??this.columns[e];if(F.isDateType(l.type)||l.name==="Date")return N(n.dateColor),n.dateColor;if(F.isNumberType(l.type))return o>0?(N(n.positiveNumberColor),n.positiveNumberColor):o<0?(N(n.negativeNumberColor),n.negativeNumberColor):(N(n.zeroNumberColor),n.zeroNumberColor)}}else if(this.isPendingRow(t)&&this.isKeyColumn(e))return N(n.errorTextColor),n.errorTextColor;return n.textColor}backgroundColorForCell(e,t){return this.formatForCell(e,t)?.backgroundColor??null}textAlignForCell(e){const t=this.columns[e],{type:n}=t;return F.isNumberType(n)?"right":F.isDateType(n)||t.name==="Date"?"center":"left"}textForColumnHeader(e,t=0){const n=this.columnAtDepth(e,t);return Ea(n)?n.isNew?"":n.name:n?.name}colorForColumnHeader(e,t=0){const n=this.columnAtDepth(e,t);return Ea(n)?n.color??null:null}getColumnHeaderGroup(e,t){const n=this.columnAtDepth(e,t);if(Ea(n))return n}getColumnHeaderParentGroup(e,t){return this.columnHeaderParentMap.get(this.columnAtDepth(e,t)?.name??"")}columnAtDepth(e,t=0){if(t===0)return this.columns[e];const n=this.columns[e]?.name;let s=this.columnHeaderParentMap.get(n);if(!s)return;let i=s.depth;for(;i<t;){if(s=this.columnHeaderParentMap.get(s.name),!s)return;i=s.depth}if(s.depth===t)return s}textForRowFooter(e){const t=this.totalsRow(e);return t!=null&&this.totals?this.totals.operationOrder[t]:""}getMemoizedInitialMovedColumns=ge(e=>{if(!e)return[];let t=[];const{groupMap:n}=Se.parseColumnHeaderGroups(this,e?.columnGroups??[]),s=(h,u)=>{const m=this.getColumnIndexByName(h);if(m==null)throw new Error(`Unknown layout hint column: ${h}`);const g=_.getVisibleIndex(m,t);t=_.moveItem(g,u,t)},i=(h,u)=>{const m=n.get(h);if(m==null)throw new Error(`Unknown layout hint group: ${h}`);const g=m.getVisibleRange(t);t=_.moveRange(g,u,t)},{frontColumns:o=[],backColumns:l=[],frozenColumns:a=[]}=e;if(o.length||l.length||a.length){const h=new Set;let u=0;a.forEach(g=>{if(h.has(g))throw new Error(`Column specified in multiple layout hints: ${g}`);s(g,u),u+=1}),o.forEach(g=>{if(h.has(g))throw new Error(`Column specified in multiple layout hints: ${g}`);s(g,u),u+=1});let m=this.columnMap.size-1;l.forEach(g=>{if(h.has(g))throw new Error(`Column specified in multiple layout hints: ${g}`);s(g,m),m-=1})}if(e?.columnGroups){const h=[...n.values()];h.sort((u,m)=>u.depth-m.depth),h.forEach(u=>{const m=u.children[0],g=this.getColumnIndexByName(m);let p;if(g!=null)p=_.getVisibleIndex(g,t);else{const C=n.get(m);if(!C)throw new Error(`Unknown column ${m} in group ${u.name}`);[,p]=C.getVisibleRange(t)}for(let C=1;C<u.children.length;C+=1){const f=u.children[C],b=n.get(f),w=this.getColumnIndexByName(f);if(b){const T=b.getVisibleRange(t)[0]<p?p-b.childIndexes.length+1:p+1;i(f,T),p=T+b.childIndexes.length-1}else if(w!=null){const T=_.getVisibleIndex(w,t)<p?p:p+1;s(f,T),p=T}}})}return this._movedColumns=t,t});get initialMovedColumns(){return this.getMemoizedInitialMovedColumns(this.layoutHints??void 0)}get initialMovedRows(){return iy}getMemoizedInitialColumnHeaderGroups=ge(e=>Se.parseColumnHeaderGroups(this,e?.columnGroups??[]).groups);get initialColumnHeaderGroups(){return this.getMemoizedInitialColumnHeaderGroups(this.layoutHints??void 0)}getMemoizedColumnMap=ge(e=>{const t=new Map;return e.forEach(n=>t.set(n.name,n)),t});get columnMap(){return this.getMemoizedColumnMap(this.table.columns)}get columnHeaderMaxDepth(){return this._columnHeaderMaxDepth??1}set columnHeaderMaxDepth(e){this._columnHeaderMaxDepth=e}get columnHeaderGroupMap(){return this._columnHeaderGroupMap}get columnHeaderGroups(){return this._columnHeaderGroups}set columnHeaderGroups(e){if(e===this._columnHeaderGroups)return;const{groups:t,maxDepth:n,parentMap:s,groupMap:i}=Se.parseColumnHeaderGroups(this,e??this.initialColumnHeaderGroups);this._columnHeaderGroups=t,this.columnHeaderMaxDepth=n,this.columnHeaderParentMap=s,this._columnHeaderGroupMap=i}get groupedColumns(){return[]}row(e){const t=this.totals?.operationOrder?.length??0,n=this.totals?.showOnTop??!1,s=this.totalsRow(e);if(s!=null){const a=this.totals?.operationOrder[s];return N(a),this.totalsDataMap?.get(a)??null}const i=this.pendingRow(e);if(i!=null)return this.pendingNewDataMap.get(i)??null;const o=this.viewportData?.offset??0,l=(n?e-t:e)-o;return this.viewportData?.rows?.[l]??null}totalsColumn(e,t){const n=this.totalsRow(t);if(n==null)return null;const s=this.totals?.operationOrder[n],i=this.totals?.defaultOperation??Le.SUM,o=this.columns[e];return this.totalsTable?.columns.find(l=>l.name===`${o.name}__${s}`||(s===i||this.totals?.operationOrder.length===1)&&l.name===o.name)}totalsRow(e){const t=this.totals?.operationOrder?.length??0,s=this.totals?.showOnTop??!1?e:e-this.table.size;return s>=0&&s<t?s:null}pendingRow(e){const t=e-this.floatingTopRowCount-this.table.size;return t>=0&&t<this.pendingNewRowCount?t:null}isTotalsRow(e){return this.totalsRow(e)!=null}isPendingRow(e){return this.pendingRow(e)!=null}dataForCell(e,t){return this.row(t)?.data.get(e)}formatForCell(e,t){return this.dataForCell(e,t)?.format}valueForCell(e,t){const n=this.dataForCell(e,t);if(n)return n.value??null}copyViewportData(e){if(e==null){tt.warn("invalid data!");return}this.viewportData=this.extractViewportData(e),this.formattedStringData=[]}copyTotalsData(e){if(e==null){tt.warn("invalid data!");return}const{columns:t,rows:n}=e;if(n.length!==1){tt.error("Unexpected number of rows received for totals table, ignoring update");return}const s=new Map,i=n[0],o=this.totals?.defaultOperation??Le.SUM,l=this.totals?.operationMap;for(let a=0;a<t.length;a+=1){const d=t[a],[h,u=l?.[h]?.[0]??o]=d.name.split("__");s.has(u)||s.set(u,{data:new Map});const{data:m}=s.get(u),g=this.columns.findIndex(p=>p.name===h);m.set(g,{value:i.get(d),format:i.getFormat(d)})}tt.debug2("copyTotalsData",s),this.totalsDataMap=s,this.formattedStringData=[]}getColumnIndexByName(e){return this.getColumnIndicesByNameMap(this.columns).get(e)}getColumnIndicesByNameMap=ge(e=>{const t=new Map;return e.forEach(({name:n},s)=>t.set(n,s)),t});extractViewportData(e){const t={offset:e.offset,rows:[]},{columns:n}=e;for(let s=0;s<e.rows.length;s+=1){const i=e.rows[s],o=this.extractViewportRow(i,n);t.rows.push(o)}return t}extractViewportRow(e,t){const n=new Map;for(let s=0;s<t.length;s+=1){const i=t[s],o=this.getColumnIndexByName(i.name);N(o),n.set(o,{value:e.get(i),format:e.getFormat(i)})}return{data:n}}closeSubscription(){tt.debug2("closeSubscription",this.subscription),this.subscription&&(this.subscription.close(),this.subscription=null),this.setViewport.cancel(),this.applyViewport.cancel()}get filter(){return this.table.filter}set filter(e){this.closeSubscription(),this.table.applyFilter(e),this.applyViewport()}get formatter(){return this.irisFormatter}set formatter(e){this.irisFormatter=e,this.formattedStringData=[],this.dispatchEvent(new ze(Ce.EVENT.FORMATTER_UPDATED))}displayString(e,t,n="",s){return this.getCachedFormattedString(this.formatter,e,t,n,s)}get sort(){return this.table.sort}set sort(e){this.closeSubscription(),this.table.applySort(e),this.applyViewport()}set totalsConfig(e){if(tt.debug("set totalsConfig",e),e!==this.totals){if(this.totals=e,this.formattedStringData=[],this.totalsTablePromise!=null&&this.totalsTablePromise.cancel(),this.setTotalsTable(null),e==null){this.dispatchEvent(new ze(Ce.EVENT.UPDATED));return}this.totalsTablePromise=ye.makeCancelable(this.table.getTotalsTable(e),t=>t.close()),this.totalsTablePromise.then(t=>{this.totalsTablePromise=null,this.setTotalsTable(t)}).catch(t=>{ye.isCanceled(t)||(tt.error("Unable to set next totalsTable",t),this.totalsTablePromise=null,this.dispatchEvent(new ze(Ce.EVENT.REQUEST_FAILED,{detail:t})))})}}setTotalsTable(e){tt.debug("setTotalsTable",e),this.totalsTable!==null&&(this.listenerCount>0&&this.removeTotalsListeners(this.totalsTable),this.totalsTable.close()),this.totalsTable=e,this.totalsDataMap=null,this.listenerCount>0&&this.totalsTable!=null&&this.addTotalsListeners(this.totalsTable)}setViewport=vs((e,t,n)=>{if(t<e){tt.error("Invalid viewport",e,t);return}const{viewport:s}=this;if(s!=null&&s.top===e&&s.bottom===t&&s.columns===n){tt.debug2("Ignoring duplicate viewport",s);return}this.viewport={top:e,bottom:t,columns:n},tt.debug2("setViewport",this.viewport),this.applyViewport()},ny);applyViewport=vs(()=>{if(!this.viewport)return;tt.debug2("applyViewport",this.viewport);const{top:e,bottom:t,columns:n}=this.viewport,[s,i]=this.getCachedViewportRowRange(e,t);this.applyBufferedViewport(s,i,n)},sy,{leading:!1});applyBufferedViewport(e,t,n){tt.debug2("applyBufferedViewport",e,t,n),this.subscription==null?(tt.debug2("applyBufferedViewport creating new subscription"),this.subscription=this.table.setViewport(e,t,n)):(tt.debug2("applyBufferedViewport using existing subscription"),this.subscription.setViewport(e,t,n))}async snapshot(e,t=!1,n=i=>i,s=!0){if(this.subscription==null)throw new Error("No subscription available");const i=s?te.consolidate(e):e;if(!Se.isValidSnapshotRanges(i))throw new Error(`Invalid snapshot ranges ${e}`);const o=new Set,l=[],a=new Set;for(let g=0;g<i.length;g+=1){const p=i[g];N(p.endRow),N(p.startRow);for(let C=p.startRow;C<=p.endRow&&C<this.floatingTopRowCount;C+=1)o.add(C);p.endRow>=this.floatingTopRowCount&&p.startRow<=this.floatingTopRowCount+this.table.size&&l.push(new te(p.startColumn,Math.min(Math.max(0,p.startRow-this.floatingTopRowCount)),p.endColumn,Math.min(Math.max(0,p.endRow-this.floatingTopRowCount),this.table.size-this.floatingTopRowCount)));for(let C=Math.max(p.startRow,this.floatingTopRowCount+this.table.size);C<=p.endRow&&C<this.floatingTopRowCount+this.table.size+this.floatingBottomRowCount;C+=1)a.add(C)}const d=Se.columnsFromRanges(i,this.columns),h=[];t&&h.push(d.map(g=>g.name));const u=[...o].sort();for(let g=0;g<u.length;g+=1){const p=u[g],C=d.map(f=>{const b=this.getColumnIndexByName(f.name);return N(b),n(this.valueForCell(b,p),f)});t&&C.push(this.textForRowFooter(p)),h.push(C)}if(l.length>0){const g=Se.rangeSetFromRanges(l),p=await this.subscription.snapshot(g,d);h.push(...p.rows.map(C=>d.map(f=>n(C.get(f),f))))}const m=[...a].sort();for(let g=0;g<m.length;g+=1){const p=m[g],C=d.map(f=>{const b=this.getColumnIndexByName(f.name);return N(b),n(this.valueForCell(b,p),f)});t&&C.push(this.textForRowFooter(p)),h.push(C)}return h}async textSnapshot(e,t=!1,n=s=>`${s}`){return tt.debug2("textSnapshot",e,t),(await this.snapshot(e,t,n,!1)).map(i=>i.join(" ")).join(`
29
+ `:","}}return t}makeSnapshot(e){if(e<=0)return;N(this.gridRangeCounter);let t=0,n=this.gridRanges[this.gridRangeCounter];for(N(this.tableSubscription),N(this.columns);t<e;){N(n),N(n.startRow),N(n.endRow),N(this.rangedSnapshotCounter),N(this.chunkRows);const s=n.startRow+this.rangedSnapshotCounter*this.chunkRows,i=Math.min(s+this.chunkRows-1,n.endRow),o=this.snapshotCounter;this.cancelableSnapshots.push(ye.makeCancelable(this.tableSubscription.snapshot(I.RangeSet.ofRange(s,i),this.columns).then(l=>(LT(l),this.handleSnapshotResolved(l,o,s,i),o)).catch(l=>{An.error(l)}),l=>{An.info(`snapshot ${l} has been canceled`)})),this.rangedSnapshotCounter+=1,this.snapshotCounter+=1,this.snapshotPending+=1,this.rangedSnapshotCounter>=this.rangedSnapshotsTotal[this.gridRangeCounter]&&(this.gridRangeCounter+=1,this.rangedSnapshotCounter=0,n=this.gridRanges[this.gridRangeCounter]),t+=1}}handlePortMessage({data:e}){const{download:t,readableStreamPulling:n}=e;if(!this.useBlobFallback){if(t!=null){const{includeColumnHeaders:s}=this;this.makeIframe(`${t}`),this.writeCsvTable(s)}n!=null&&(this.useBlobFallback||(this.streamTimeout!=null&&clearTimeout(this.streamTimeout),this.streamTimeout=setTimeout(this.handleDownloadTimeout,jn.STREAM_TIMEOUT)))}}handleSnapshotResolved(e,t,n,s){this.snapshotHandlerTimeout=setTimeout(()=>{this.snapshotsBuffer.set(t,e),this.snapshotPending-=1,this.writeSnapshot(t,n,s),this.cancelableSnapshots[t]=null},jn.SNAPSHOT_HANDLER_TIMEOUT)}makeIframe(e){const t=document.createElement("iframe");t.hidden=!0,t.src=`download/${e}`,t.name="iframe",document.body.appendChild(t),this.iframes.push(t)}render(){return null}}function OT(c){const{group:e,onDelete:t,onColorChange:n,onNameChange:s,validateName:i}=c,{isNew:o}=e,l=v.useRef(e),a=v.useRef(null),d=v.useRef(null),[h,u]=v.useState(!1),[m,g]=v.useState(o?"":e.name),[p,C]=v.useState(o),[f,b]=v.useState(!1),w=m!==e.name?i(m):"",S=o&&!f||w==="",T=v.useCallback(()=>{u(!1)},[]);v.useEffect(function(){p&&a.current&&(a.current.focus(),a.current.select())},[p]),v.useEffect(function(){return()=>{l.current.isNew&&t(l.current)}},[t]),v.useEffect(function(){return h&&(d.current?.click(),d.current?.focus(),window.addEventListener("click",T,!0)),()=>window.removeEventListener("click",T,!0)},[h,T]);const y=()=>{S&&(s(e,m),C(!1))},E=()=>{if(o){t(e);return}g(e.name),C(!1)},R=x=>{b(!0),x.key==="Enter"&&(x.stopPropagation(),y()),x.key===" "&&x.stopPropagation(),x.key==="Escape"&&E()};return p?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"editing-container",children:[r.jsx("input",{ref:a,className:Y("form-control",{"is-invalid":!S}),value:m,placeholder:"Group Name",onChange:x=>g(x.target.value),onKeyDown:R,onBlur:()=>b(!0)}),r.jsx(B,{kind:"ghost",icon:zn,tooltip:"Confirm",onClick:y}),r.jsx(B,{kind:"ghost",icon:bg,tooltip:"Cancel",onClick:E})]}),!S&&r.jsx("p",{className:"mb-0 validate-label-error text-danger",children:w})]}):r.jsxs("div",{className:"group-name-wrapper",children:[r.jsx("span",{className:"column-name",children:m}),r.jsx(B,{className:"p-1 mx-1",kind:"ghost",icon:go,tooltip:"Edit",onClick:()=>{C(!0)}}),r.jsxs("span",{className:"right-buttons",children:[r.jsx(B,{kind:"ghost",icon:Gt,tooltip:"Delete group",onClick:()=>t(e)}),r.jsx(B,{kind:"ghost",className:"color-swatch mr-1",icon:e.color!==void 0?r.jsxs("span",{className:"fa-layers",children:[r.jsx(ee,{className:"color-swatch",icon:cl,color:Je.white,transform:"down-1"}),r.jsx(ee,{className:"color-swatch",icon:cl,color:e.color,transform:"shrink-2 down-1"})]}):Sg,tooltip:"Set color",onClick:()=>u(x=>!x)}),h&&r.jsxs(r.Fragment,{children:[r.jsx("input",{"aria-label":"Color input",ref:d,type:"color",list:"presetColors",value:e.color??Je["content-bg"],style:{visibility:"hidden",width:0,height:0,padding:0,border:0},onChange:x=>{e.color=x.target.value,n(e,x.target.value)}}),r.jsxs("datalist",{id:"presetColors",children:[r.jsx("option",{children:Je["content-bg"]}),r.jsx("option",{children:Je.primary}),r.jsx("option",{children:Je.foreground}),r.jsx("option",{children:Je.green}),r.jsx("option",{children:Je.yellow}),r.jsx("option",{children:Je.orange}),r.jsx("option",{children:Je.red}),r.jsx("option",{children:Je.purple}),r.jsx("option",{children:Je.blue}),r.jsx("option",{children:Je["gray-400"]})]})]})]})]})}function AT(){}const _T=v.forwardRef(function(e,t){const{value:n,clone:s,childCount:i,item:o,onVisibilityChange:l,onClick:a,onGroupDelete:d,onGroupColorChange:h,onGroupNameChange:u,validateGroupName:m,handleProps:g}=e,{group:p,modelIndex:C,isVisible:f}=o.data,b=v.useRef(null),w=v.useCallback(T=>{T.buttons===1&&(l([C].flat(),!f),b.current?.focus())},[l,C,f]),S=v.useCallback(T=>{a(n,T)},[a,n]);return r.jsxs("div",{ref:t,className:Y("tree-item",{isSelected:o.selected,"two-dragged":i===2,"multiple-dragged":i>2}),onClick:S,...g,children:[r.jsx(B,{ref:b,kind:"ghost",className:"px-1",onClick:AT,onMouseDown:w,onMouseEnter:w,icon:f?gr:nh,tooltip:"Toggle visibility"}),r.jsx("span",{className:Y("column-name",p&&"column-group"),children:p&&!s?r.jsx(OT,{group:p,onDelete:d,onColorChange:h,onNameChange:u,validateName:m}):n}),r.jsxs("div",{children:[s&&i>1&&r.jsx("span",{className:"item-count",children:i}),r.jsx(ot,{children:"Drag to re-order"}),r.jsx(ee,{icon:Wl})]})]})}),PT=_T;function jT(c){return c.parentId!==void 0}function HT(c,e){return Math.round(c/e)}function Iu(c,e,t,n,s,i){const o=c.findIndex(l=>l.name===n);if(o===-1){const l=t.get(n);if(l==null)throw new Error(`Column or header group not found: ${n}`);const a=l.childIndexes.flat();return{id:n,selected:i.has(n),children:l.children.map(d=>Iu(c,e,t,d,s,i)).sort((d,h)=>{const u=Array.isArray(d.data.visibleIndex)?d.data.visibleIndex[0]:d.data.visibleIndex,m=Array.isArray(h.data.visibleIndex)?h.data.visibleIndex[0]:h.data.visibleIndex;return u-m}),data:{modelIndex:a,visibleIndex:l.getVisibleRange(e),group:l,isVisible:a.some(d=>!s.has(d))}}}return{id:n,children:[],selected:i.has(n),data:{modelIndex:o,visibleIndex:_.getVisibleIndex(o,e),isVisible:!s.has(o)}}}function BT(c,e,t,n,s){const i=[],o=new Set(s),l=new Map(t.map(h=>[h.name,h])),a=new Set(n);let d=0;for(;d<c.length;){const h=_.getModelIndex(d,e),u=c[h].name;let m=t.find(({children:p})=>p.includes(u));for(;m!==void 0&&m.parent!==void 0;)m=l.get(m.parent);const g=Iu(c,e,l,m?m.name:u,a,o);i.push(g),Array.isArray(g.data.visibleIndex)?d+=g.data.visibleIndex[1]-g.data.visibleIndex[0]+1:d+=1}return i}function Dl(c,e,t,n,s){const i=c.findIndex(({id:b})=>b===t),o=c.findIndex(({id:b})=>b===e),l=c[o],a=hm(c,o,i),d=a[i-1],h=a[i+1],u=HT(n,s),m=l.depth+u,g=UT({previousItem:d,nextItem:h}),p=VT({nextItem:h});let C=m;return m>=g?C=g:m<p&&(C=p),{depth:C,maxDepth:g,minDepth:p,parentId:f()};function f(){return C===0||!d?null:C===d.depth?d.parentId:C>d.depth?d.id:a.slice(0,i).reverse().find(w=>w.depth===C)?.parentId??null}}function UT({previousItem:c,nextItem:e}){return Math.max(c?.depth??0,e?.depth??0)}function VT({nextItem:c}){return c?c.depth:0}function Fu(c,e=null,t=0){return c.reduce((n,s,i)=>[...n,{...s,parentId:e,depth:t,index:i},...Fu(s.children,s.id,t+1)],[])}function Jt(c){return c.every(jT)?[...c]:Fu(c)}function Nu(c,e){for(let t=0;t<c.length;t+=1){const n=c[t],{id:s,children:i}=n;if(s===e)return n;if(i.length){const o=Nu(i,e);if(o)return o}}}function ku(c,e=0){return c.reduce((t,{children:n})=>n.length?ku(n,t+1):t+1,e)}function $T(c,e){const t=Nu(c,e);return t?ku(t.children):0}const WT=[Rn.Down,Rn.Right,Rn.Up,Rn.Left],GT=[Rn.Left,Rn.Right];function zT(c,e,t){return(n,{currentCoordinates:s,context:{active:i,over:o,collisionRect:l,droppableRects:a,droppableContainers:d}})=>{if(WT.includes(n.code)){if(!i||!l)return;n.preventDefault();const{current:{items:h,offset:u}}=c;if(GT.includes(n.code)&&o?.id!=null){const{depth:C,maxDepth:f,minDepth:b}=Dl(h,i.id,o.id,u,t);switch(n.code){case Rn.Left:if(C>b)return{...s,x:s.x-t};break;case Rn.Right:if(C<f)return{...s,x:s.x+t};break}return}const m=[];d.forEach(C=>{if(C?.disabled||C.id===o?.id)return;const f=a.get(C.id);if(f)switch(n.code){case Rn.Down:l.top<f.top&&m.push(C);break;case Rn.Up:l.top>f.top&&m.push(C);break}});const g=um({active:i,collisionRect:l,pointerCoordinates:null,droppableRects:a,droppableContainers:m});let p=mm(g,"id");if(p===o?.id&&g.length>1&&(p=g[1].id),p!=null&&o?.id!=null){const C=a.get(i.id),f=a.get(p),b=d.get(p);if(C&&f&&b){const w=h.findIndex(({id:E})=>E===p),S=h[w],T=h.findIndex(({id:E})=>E===i.id),y=h[T];if(S!=null&&y!=null){const{depth:E}=Dl(h,i.id,p,(S.depth-y.depth)*t,t),x=w>T?1:-1,D=e?(l.height-C.height)/2:0;return{x:f.left+E*t,y:f.top+x*D}}}}}}}class KT extends gm{static activators=[{eventName:"onPointerDown",handler:({nativeEvent:e})=>!(!e.isPrimary||e.button!==0||qT(e.target))}]}const YT=["button","input","textarea","select","option"];function qT(c){return!!(c?.tagName!=null&&YT.includes(c.tagName.toLowerCase()))}function Mu(c){const{clone:e=!1,depth:t,disableInteraction:n=!1,ghost:s=!1,handleProps:i,value:o,dragRef:l=null,wrapperRef:a=null,renderItem:d,item:h,childCount:u}=c,m=v.useMemo(()=>Array(t).fill(0).map((p,C)=>r.jsx("span",{className:"depth-line"},`depth-line-${C}`)),[t]),g=v.useMemo(()=>({ref:l,clone:e,value:o,item:h,childCount:u,handleProps:i}),[l,e,o,h,u,i]);return r.jsxs("li",{className:Y("item-wrapper",{clone:e,ghost:s,disableInteraction:n}),ref:a,children:[!e&&m,d(g)]},o)}Mu.displayName="TreeItem";const XT=({isSorting:c,wasDragging:e})=>!(c||e);function rc({id:c,depth:e,...t}){const{attributes:n,isDragging:s,isSorting:i,listeners:o,setDraggableNodeRef:l,setDroppableNodeRef:a,transform:d,transition:h}=pm({id:c,animateLayoutChanges:XT}),u=Ha.Translate.toString(d),m=v.useMemo(()=>({transform:u,transition:h}),[u,h]),g=v.useMemo(()=>({...n,...o,style:m}),[n,o,m]);return r.jsx(Mu,{dragRef:l,wrapperRef:a,depth:e,ghost:s,disableInteraction:i,handleProps:g,...t})}const ZT={keyframes({transform:c}){return[{opacity:1,transform:Ha.Transform.toString(c.initial)},{opacity:0,transform:Ha.Transform.toString({...c.final,x:c.final.x+5,y:c.final.y+5})}]},easing:"ease-out",sideEffects({active:c}){c.node.animate([{opacity:0},{opacity:1}],{duration:dd.duration,easing:dd.easing})}};let zo=null;function QT(c){return zo==null&&c.activeNodeRect&&c.activatorEvent instanceof PointerEvent&&(zo=Math.floor((c.activatorEvent.clientY-c.activeNodeRect.top)/c.activeNodeRect.height)*c.activeNodeRect.height),c.activeNodeRect||(zo=null),{...c.transform,y:c.transform.y+(zo??0)}}function JT({items:c,renderItem:e,indentationWidth:t=30,indicator:n=!1,activeId:s,overId:i,offsetLeft:o}){const l=fm(),a=v.useRef(l);v.useEffect(function(){a.current=l},[l]),v.useEffect(function(){a.current.measureDroppableContainers(c.map(({id:g})=>g))},[c]);const d=s!=null&&i!=null?Dl(c,s,i,o,t):null,h=v.useRef({items:c,offset:o}),u=s!=null?c.find(({id:m})=>m===s):null;return v.useEffect(()=>{h.current={items:c,offset:o}},[c,o]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:Y("tree-container",s!=null&&"marching-ants"),children:c.map(m=>{const{id:g,depth:p}=m;return r.jsx(rc,{id:g,value:g,depth:g===s&&d?d.depth:p,item:m,renderItem:e},g)})}),Cm.createPortal(r.jsx(bm,{dropAnimation:ZT,modifiers:[QT],className:"visibility-ordering-list",children:s!=null&&u?r.jsx(rc,{id:s,depth:u.depth,clone:!0,childCount:$T(c,s)+1,value:s.toString(),renderItem:e,item:u}):null}),document.body)]})}const eE={droppable:{strategy:ym.Always}},tE={activationConstraint:{distance:5}};function nE({items:c,indicator:e=!1,indentationWidth:t=30,onDragStart:n,onDragEnd:s,renderItem:i}){const[o,l]=v.useState(null),[a,d]=v.useState(null),[h,u]=v.useState(0),m=v.useMemo(()=>{const x=Jt(c);return o!=null?x.filter(({id:D,selected:M})=>D===o||!M):x},[o,c]),g=o!=null&&a!=null?Dl(m,o,a,h,t):null,p=v.useRef({items:m,offset:h}),C=v.useMemo(()=>({coordinateGetter:zT(p,e,t)}),[t,e]),f=Sm(cd(KT,tE),cd(Rm,C)),b=v.useMemo(()=>m.map(({id:x})=>x),[m]);v.useEffect(()=>{p.current={items:m,offset:h}},[m,h]);const w=v.useCallback(({active:{id:x}})=>{l(x),d(x),n?.(x),document.body.style.setProperty("cursor","grabbing")},[n]),S=v.useCallback(({delta:x})=>{u(x.x)},[]),T=v.useCallback(({over:x})=>{d(x?.id??null)},[]),y=v.useCallback(()=>{d(null),l(null),u(0),document.body.style.setProperty("cursor","")},[]),E=v.useCallback(({active:x,over:D})=>{if(y(),g&&D){const{depth:M,parentId:O}=g,H=JSON.parse(JSON.stringify(Jt(c))),L=H.findIndex(({id:j})=>j===D.id),V=H.findIndex(({id:j})=>j===x.id),U=H[V];H[V]={...U,depth:M,parentId:O},s?.(U,{...H[L],parentId:g.parentId})}},[c,s,g,y]),R=v.useCallback(()=>{y()},[y]);return r.jsx(wm,{sensors:f,collisionDetection:vm,measuring:eE,onDragStart:w,onDragMove:S,onDragOver:T,onDragEnd:E,onDragCancel:R,children:r.jsx(Tm,{items:b,strategy:Em,children:r.jsx(JT,{items:m,renderItem:i,indicator:e,indentationWidth:t,activeId:o,overId:a,offsetLeft:h})})})}function sE(c,e,t,n,s,i,o,l){const a=s.map((w,S)=>({...w,index:S}));let d=[],h=n;const u=i[0].data.visibleIndex,m=a.findIndex(({id:w})=>w===c.id),g=a.findIndex(({id:w})=>w===e.id);let p=Array.isArray(u)?u[1]+1:u+1;h=ms(i[0],e.parentId,h);for(let w=1;w<i.length;w+=1){const{data:{visibleIndex:S}}=i[w];d=_.moveItemOrRange(S,p,d,!0),p+=Array.isArray(S)?S[1]-S[0]+1:1,h=ms(i[w],e.parentId,h)}const C=[Array.isArray(u)?u[0]:u,p-1],f=Array.isArray(e.data.visibleIndex)?e.data.visibleIndex[0]:e.data.visibleIndex;let b=_.getVisibleIndex(f,d);return m>g&&b>f&&(b-=1),e.children.length>0&&(Array.isArray(u)?u[0]:u)<b&&(b-=1),C[0]<b&&(b-=C[1]-C[0]),d=_.moveItemOrRange(C,Oe(b,o,l),d),{groups:h,movedColumns:t.concat(d)}}function ms(c,e,t){if(c.parentId===e)return[...t];let n=t.map(a=>new dn(a));const s=new Map(n.map(a=>[a.name,a])),i=n.find(a=>a.name===c.parentId),o=n.find(a=>a.name===e),l=n.find(a=>a.name===c.id);if(i!=null&&(i.children=i.children.filter(a=>a!==c.id),i.children.length===0)){const a=new Set([i.name]),{parent:d=""}=i;let h=s.get(d);for(h?.removeChildren([i.name]);h&&h.children.length===0;){a.add(h.name);const u=h?.parent??"",m=s.get(u);m?.removeChildren([h.name]),h=m}n=n.filter(({name:u})=>!a.has(u))}return o?.addChildren([c.id]),l?.setParent(e??void 0),n}const iE=150;class pt extends v.Component{static SORTING_OPTIONS={DSC:"DSC",ASC:"ASC"};static MOVE_OPTIONS={TOP:"TOP",BOTTOM:"BOTTOM",UP:"UP",DOWN:"DOWN"};constructor(e){super(e),this.handleSearchInputChange=this.handleSearchInputChange.bind(this),this.searchColumns=this.searchColumns.bind(this),this.handleItemClick=this.handleItemClick.bind(this),this.handleDragEnd=this.handleDragEnd.bind(this),this.handleGroupDelete=this.handleGroupDelete.bind(this),this.handleGroupNameChange=this.handleGroupNameChange.bind(this),this.handleGroupCreate=this.handleGroupCreate.bind(this),this.validateGroupName=this.validateGroupName.bind(this),this.addColumnToSelected=this.addColumnToSelected.bind(this),this.handleDragStart=this.handleDragStart.bind(this),this.state={selectedColumns:new Set,lastSelectedColumn:"",searchFilter:""},this.list=null}componentWillUnmount(){this.debouncedSearchColumns.cancel()}list;debouncedSearchColumns=Ye(this.searchColumns,iE);resetVisibilityOrdering(){const{model:e,onReset:t,onMovedColumnsChanged:n,onColumnHeaderGroupChanged:s}=this.props;this.setState({selectedColumns:new Set,lastSelectedColumn:"",searchFilter:""}),t(),s(e.initialColumnHeaderGroups),n(e.initialMovedColumns)}resetSelection(){this.setState({selectedColumns:new Set,lastSelectedColumn:""})}handleSearchInputChange(e){const t=e.target.value;if(this.setState({searchFilter:t}),!t){this.debouncedSearchColumns.cancel(),this.resetSelection();return}this.debouncedSearchColumns(t)}searchColumns(e){const t=Jt(this.getTreeItems()),s=t.filter(({id:o,data:l})=>!(l.group?.isNew??!1)&&o.toLowerCase().includes(e.toLowerCase())).map(({id:o})=>o),i=t.findIndex(({id:o})=>o.toLowerCase().includes(e.toLowerCase()));this.addColumnToSelected(s,!1),s.length>0&&this.list?.querySelectorAll(".item-wrapper")[i]?.scrollIntoView({block:"center"})}moveSelectedColumns(e){const{columnHeaderGroups:t}=this.props,{selectedColumns:n}=this.state,s=Jt(this.getTreeItems());let i=this.getFirstMovableIndex(),o=this.getLastMovableIndex();N(i),N(o);const l=this.getSelectedParentItems();e===pt.MOVE_OPTIONS.UP||e===pt.MOVE_OPTIONS.TOP||l.reverse();let d=[],h=t;for(let u=0;u<l.length;u+=1){const{id:m,parentId:g,depth:p,data:{visibleIndex:C}}=l[u];switch(e){case pt.MOVE_OPTIONS.TOP:{d=_.moveItemOrRange(C,i,d,!0);const f=Array.isArray(C)?C[1]-C[0]+1:1;i+=f,h=ms(l[u],null,h);break}case pt.MOVE_OPTIONS.BOTTOM:{d=_.moveItemOrRange(C,o,d,!0);const f=Array.isArray(C)?C[1]-C[0]+1:1;o-=f,h=ms(l[u],null,h);break}case pt.MOVE_OPTIONS.UP:{const f=s.findIndex(S=>S.id===m),b=s.map((S,T)=>T<f&&!n.has(S.id)).lastIndexOf(!0),w=s[b];if(w!=null&&w.parentId!==g)if(Math.abs(w.depth-p)>1){const S=s.map((y,E)=>E<b&&y.depth===p).lastIndexOf(!0),T=s[S];h=ms(l[u],T.id,h)}else h=ms(l[u],w.parentId,h);else{const S=Oe(Array.isArray(C)?C[0]-1:C-1,i,o);d=_.moveItemOrRange(C,S,d,!1);const T=Array.isArray(C)?C[1]-C[0]+1:1;i+=T}break}case pt.MOVE_OPTIONS.DOWN:{const f=s.findIndex(T=>T.id===m),b=s.find((T,y)=>y>f&&!n.has(T.id));if(b?.parentId!==g){const T=s.find(y=>y.id===g);h=ms(l[u],T?.parentId??null,h);break}else if(b?.children.length>0){h=ms(l[u],b.id,h);break}const w=Oe(Array.isArray(C)?C[0]+1:C+1,i,o);d=_.moveItemOrRange(C,w,d,!1);const S=Array.isArray(C)?C[1]-C[0]+1:1;o-=S;break}}}return{newMoves:d,groups:h}}handleMoveColumns(e){const{onMovedColumnsChanged:t,movedColumns:n,onColumnHeaderGroupChanged:s}=this.props,{newMoves:i,groups:o}=this.moveSelectedColumns(e);let l;e===pt.MOVE_OPTIONS.TOP&&(l=()=>{this.list?.parentElement?.scroll({top:0})}),e===pt.MOVE_OPTIONS.BOTTOM&&(l=()=>{this.list?.parentElement?.scroll({top:this.list.parentElement.scrollHeight})}),s(o),i.length>0&&t(n.concat(i),l)}getSortMoves(e,t,n){const s=[...e],i=t===pt.SORTING_OPTIONS.ASC;s.sort((a,d)=>{const h=a.id.toUpperCase(),u=d.id.toUpperCase();return en.sort(h,u,i)});let o=[...n],l=Math.min(...s.flatMap(a=>{const{modelIndex:d}=a.data;return Array.isArray(d)?_.getVisibleIndexes(d,o):_.getVisibleIndex(d,o)}));for(let a=0;a<s.length;a+=1){const d=s[a],{modelIndex:h}=d.data,u=Array.isArray(h)?_.getVisibleIndexes(h,o):_.getVisibleIndex(h,o);o=Array.isArray(u)?_.moveRange([Math.min(...u),Math.max(...u)],l,o,!0):_.moveItem(u,l,o),Array.isArray(u)&&(o=this.getSortMoves(d.children,t,o)),l+=Array.isArray(h)?h.length:1}return o}handleSortColumns(e){const{model:t,onMovedColumnsChanged:n}=this.props,s=this.getSortMoves(this.getTreeItems(),e,t.initialMovedColumns);n(s)}handleItemClick(e,t){if(t.stopPropagation(),t.target instanceof HTMLElement&&(t.target.tagName==="BUTTON"||t.target.tagName==="INPUT"))return;t.currentTarget.focus();const{selectedColumns:n,lastSelectedColumn:s}=this.state,i=_.isModifierKeyDown(t),o=t.shiftKey,l=n.has(e),a=[e];if(l&&i){this.removeColumnFromSelected(e);return}const d=Jt(this.getTreeItems());if(l&&!o&&s===e){const h=d.find(({id:m})=>m===e);if(N(h),Jt(h.children).length+1===n.size){this.resetSelection();return}}if(o){const h=d.findIndex(m=>m.id===e),u=d.findIndex(m=>m.id===s);a.push(...d.slice(Math.min(u,h),Math.max(u,h)+1).map(m=>m.id))}this.addColumnToSelected(a,i||o),this.setState({lastSelectedColumn:e})}addColumnToSelected(e,t){const{selectedColumns:n}=this.state,s=new Set(t?[...n.values()].concat(e):e);Jt(this.getTreeItems()).forEach(({id:o,children:l})=>{s.has(o)&&l.forEach(a=>s.add(a.id))}),this.setState({selectedColumns:s})}removeColumnFromSelected(e){const{selectedColumns:t}=this.state,n=Jt(this.getTreeItems()),s=n.find(({id:o})=>o===e);N(s);let i=n.find(({id:o})=>o===s.parentId);for(Jt(s?.children).forEach(o=>t.delete(o.id));i!=null;){t.delete(i.id);const o=i.parentId;i=n.find(({id:l})=>l===o)}t.delete(e),this.setState({selectedColumns:new Set(t)})}handleDragStart(e){const{selectedColumns:t}=this.state;t.has(e)||this.addColumnToSelected([e],!1)}handleDragEnd(e,t){const{movedColumns:n,onMovedColumnsChanged:s,columnHeaderGroups:i,onColumnHeaderGroupChanged:o}=this.props,l=this.getSelectedParentItems(),a=Jt(this.getTreeItems()).map((g,p)=>({...g,index:p})),d=this.getFirstMovableIndex(),h=this.getLastMovableIndex();N(d),N(h);const{groups:u,movedColumns:m}=sE(e,t,n,i,a,l,d,h);o(u),s(m)}handleGroupNameChange(e,t){const{columnHeaderGroups:n,onColumnHeaderGroupChanged:s}=this.props,i=[...n],o=e.name,l=i.findIndex(({name:u})=>u===o),a=i[l];N(a);const d=new dn(a);d.name=t,i.splice(l,1,d);const h=i.findIndex(({name:u})=>u===d.parent);if(h>=0){const u=new dn(i[h]);u.removeChildren([o]),u.addChildren([t]),i.splice(h,1,u)}s(i)}handleGroupColorChange=vs((e,t)=>{const{columnHeaderGroups:n,onColumnHeaderGroupChanged:s}=this.props,i=[...n],o=new dn({...e,color:t});i.splice(i.findIndex(({name:l})=>l===e.name),1,o),s(i)},250);handleGroupDelete(e){const{columnHeaderGroups:t,onColumnHeaderGroupChanged:n}=this.props,s=t.filter(o=>o.name!==e.name),i=s.findIndex(o=>o.name===e.parent);if(i>=0){const o=new dn(s[i]);o.addChildren(e.children),o.removeChildren([e.name]),s.splice(i,1,o)}n(s)}handleGroupCreate(){const{movedColumns:e,onMovedColumnsChanged:t,onColumnHeaderGroupChanged:n}=this.props,{newMoves:s,groups:i}=this.moveSelectedColumns(pt.MOVE_OPTIONS.TOP),o=i.filter(u=>!u.isNew),l=this.getSelectedParentItems(),a=l.map(u=>u.data.modelIndex).flat().filter(u=>u>=0),d=`${dn.NEW_GROUP_PREFIX}-${Date.now()}`,h=new dn({name:d,children:l.map(({id:u})=>u),depth:0,childIndexes:[...new Set(a)]});t(e.concat(s),()=>{this.list?.parentElement?.scroll({top:0})}),n(o.concat([h])),this.resetSelection()}validateGroupName(e){const{model:t,columnHeaderGroups:n}=this.props,{columns:s}=t;return Ii.isValidColumnName(e)?s.some(({name:i})=>i===e)||n.some(({name:i})=>i===e)?"Duplicate name":"":"Invalid name"}renderItem=Re(({value:e,clone:t,item:n,ref:s,handleProps:i})=>{const{onColumnVisibilityChanged:o}=this.props,{selectedColumns:l}=this.state;let a=e;return t&&(a=this.getSelectedParentItems().map(({id:h})=>h).join(", ")),r.jsx(PT,{ref:s,value:a,clone:t,item:n,childCount:l.size,onVisibilityChange:o,onClick:this.handleItemClick,onGroupDelete:this.handleGroupDelete,onGroupColorChange:this.handleGroupColorChange,onGroupNameChange:this.handleGroupNameChange,validateGroupName:this.validateGroupName,handleProps:i})});getMemoizedFirstMovableIndex=Re((e,t,n)=>{for(let s=0;s<t.length;s+=1){const i=_.getModelIndex(s,n);if(e.isColumnMovable(i))return s}return null});getFirstMovableIndex(){const{model:e,movedColumns:t}=this.props;return this.getMemoizedFirstMovableIndex(e,e.columns,t)}getMemoizedLastMovableIndex=Re((e,t,n)=>{for(let s=t.length-1;s>=0;s-=1){const i=_.getModelIndex(s,n);if(e.isColumnMovable(i))return s}return null});getLastMovableIndex(){const{model:e,movedColumns:t}=this.props;return this.getMemoizedLastMovableIndex(e,e.columns,t)}memoizedGetTreeItems=Re((e,t,n,s,i)=>BT(e,t,n,s,[...i.values()]));getTreeItems(){const{model:e,movedColumns:t,hiddenColumns:n,columnHeaderGroups:s}=this.props,{selectedColumns:i}=this.state;return this.memoizedGetTreeItems(e.columns,t,s,n,i)}getSelectedParentItems(){const{selectedColumns:e}=this.state;return Jt(this.getTreeItems()).filter(({id:n,parentId:s})=>e.has(n)&&!e.has(s??""))}makeVisibilityOrderingList=Re((e,t)=>{const{movedColumns:n}=this.props,s=[],i=this.getFirstMovableIndex(),o=this.getLastMovableIndex(),l=t.findIndex(({data:h})=>Array.isArray(h.visibleIndex)?h.visibleIndex[0]===i:h.visibleIndex===i),a=t.findIndex(({data:h})=>Array.isArray(h.visibleIndex)?h.visibleIndex[1]===o:h.visibleIndex===o),d=t.slice(l,a+1);if(i==null||o===null){for(let h=0;h<e.length;h+=1){const u=_.getModelIndex(h,n),m=e[u];s.push(this.renderImmovableItem(m.name))}return s}for(let h=0;h<i;h+=1){const u=_.getModelIndex(h,n),m=e[u];s.push(this.renderImmovableItem(m.name))}i!==null&&i>0&&s.push(r.jsx("hr",{},"top-horizontal-divider")),s.push(r.jsx(nE,{items:d,renderItem:this.renderItem,onDragStart:this.handleDragStart,onDragEnd:this.handleDragEnd},"movable-items")),o!=null&&o<e.length-1&&s.push(r.jsx("hr",{},"bottom-horizontal-divider"));for(let h=o+1;h<e.length;h+=1){const u=_.getModelIndex(h,n),m=e[u];s.push(this.renderImmovableItem(m.name))}return s});renderImmovableItem=Re(e=>r.jsx("div",{className:"visibility-ordering-list-item immovable",children:r.jsx("div",{className:"column-item",children:r.jsx("span",{className:"column-name",children:e})})},e));render(){const{model:e,hiddenColumns:t,onColumnVisibilityChanged:n}=this.props,{selectedColumns:s,searchFilter:i}=this.state,o=s.size>0,l=this.getTreeItems(),a=new Map(Jt(l).map(C=>[C.id,C.data.modelIndex])),d=new Set(t),h=[...new Set(o?[...s.values()].map(C=>a.get(C)).filter(C=>C!=null).flat():l.map(C=>C.data.modelIndex).flat())],u=h.some(C=>!d.has(C)),m=u?"Hide All":"Show All",g=u?"Hide Selected":"Show Selected",p=this.makeVisibilityOrderingList(e.columns,l);return r.jsxs("div",{role:"menu",className:"visibility-ordering-builder",tabIndex:0,children:[r.jsxs("div",{className:"top-menu",children:[r.jsx(B,{kind:"ghost",className:"toggle-visibility-btn",onClick:()=>{n(h,!u)},icon:u?gr:nh,tooltip:"Toggle column visibility",children:o?g:m}),r.jsx(Di,{className:"visibility-search",value:i,matchCount:i?s.size:void 0,onChange:this.handleSearchInputChange})]}),r.jsxs("div",{className:"top-menu",children:[r.jsx(B,{kind:"ghost",icon:Ws,tooltip:"Reset to default",onClick:()=>{this.resetVisibilityOrdering()},children:"Reset"}),r.jsx("span",{className:"vertical-divider"}),r.jsx(B,{kind:"ghost",icon:ur,tooltip:"Sort ascending",onClick:()=>{this.handleSortColumns(pt.SORTING_OPTIONS.ASC)}}),r.jsx(B,{kind:"ghost",icon:mr,tooltip:"Sort descending",onClick:()=>{this.handleSortColumns(pt.SORTING_OPTIONS.DSC)}}),r.jsx("span",{className:"vertical-divider"}),r.jsxs(B,{kind:"ghost",tooltip:"Create group from selection",disabled:!o,onClick:this.handleGroupCreate,children:[r.jsxs("span",{className:"fa-layers",style:{marginRight:"0.75rem"},children:[r.jsx(ee,{mask:wg,icon:Ri,transform:"right-7 down-5 shrink-6"}),r.jsx(ee,{icon:vg,transform:"right-8 down-6 shrink-8"})]}),"Group"]}),r.jsx("span",{className:"vertical-divider"}),r.jsx(B,{kind:"ghost",icon:Tg,tooltip:"Move selection up",onClick:()=>{this.handleMoveColumns(pt.MOVE_OPTIONS.UP)},disabled:!o}),r.jsx(B,{kind:"ghost",icon:Eg,tooltip:"Move selection down",onClick:()=>{this.handleMoveColumns(pt.MOVE_OPTIONS.DOWN)},disabled:!o}),r.jsx(B,{kind:"ghost",icon:yg,tooltip:"Move selection to top",onClick:()=>{this.handleMoveColumns(pt.MOVE_OPTIONS.TOP)},disabled:!o}),r.jsx(B,{kind:"ghost",icon:Rg,tooltip:"Move selection to bottom",onClick:()=>{this.handleMoveColumns(pt.MOVE_OPTIONS.BOTTOM)},disabled:!o})]}),r.jsx("div",{role:"menu",className:Y("visibility-ordering-list"),children:r.jsx("div",{className:"column-list",ref:C=>{this.list=C},children:p})})]})}}const oE=pt;class lE extends v.PureComponent{static createSearchFilter(e,t,n,s){const i=s?n.filter(o=>!t.includes(o.name)).map(o=>o.name):t;if(e&&i.length>0){const o=I.FilterValue.ofString(e);return i.length===n.length?I.FilterCondition.search(o):I.FilterCondition.search(o,n.filter(a=>i.includes(a.name)).map(a=>a.filter()))}}constructor(e){super(e),this.handleSearchValueChange=this.handleSearchValueChange.bind(this),this.toggleColumn=this.toggleColumn.bind(this),this.selectAll=this.selectAll.bind(this),this.clear=this.clear.bind(this),this.selectNumbers=this.selectNumbers.bind(this),this.searchField=de.createRef(),this.state={isConfigureColumnsShown:!1}}searchField;focus(){this.searchField.current?.focus()}handleSearchValueChange(e){const{onChange:t,selectedColumns:n,invertSelection:s}=this.props;t(e.target.value,n,s)}sendColumnChange(e,t){const{onChange:n,value:s}=this.props;n(s,e,t)}setInvertSelection(e){const{onChange:t,value:n}=this.props;t(n,[],e)}toggleColumn(e){const{selectedColumns:t,invertSelection:n}=this.props;if(t.includes(e))this.sendColumnChange(t.filter(s=>s!==e),n);else{const s=t.slice();s.push(e),this.sendColumnChange(s,n)}}selectAll(){this.setInvertSelection(!0)}clear(){this.setInvertSelection(!1)}selectNumbers(){const{columns:e}=this.props;this.sendColumnChange(e.filter(t=>F.isNumberType(t.type)).map(t=>t.name),!1)}render(){const{value:e,selectedColumns:t,invertSelection:n,columns:s}=this.props,{isConfigureColumnsShown:i}=this.state,o=t.length===0&&n===!0||t.length===s.length&&n===!1,l=t.length===0&&n===!1||t.length===s.length&&n===!0;let a;return o?a=r.jsxs(r.Fragment,{children:[r.jsx(ee,{icon:cl,mask:pa,transform:"shrink-2 down-5 right-7"}),r.jsx(ee,{icon:xg,className:"text-primary",transform:"shrink-4 down-5 right-7"})]}):l?a=r.jsxs(r.Fragment,{children:[r.jsx(ee,{icon:Ri,mask:pa,transform:"shrink-1 down-5 right-7"}),r.jsx(ee,{icon:wd,className:"text-danger",transform:"shrink-4 down-5 right-7"})]}):a=r.jsxs(r.Fragment,{children:[r.jsx(ee,{icon:cl,mask:pa,transform:"shrink-2 down-5 right-7"}),r.jsx(ee,{icon:Dg,className:"text-primary",transform:"shrink-4 down-5 right-7"})]}),r.jsxs("div",{className:"cross-column-container",children:[r.jsx(Di,{className:"cross-column-search",placeholder:"Search Data...",value:e,onChange:this.handleSearchValueChange,ref:this.searchField}),r.jsxs("button",{type:"button",className:"btn btn-link btn-link-icon px-2",onClick:()=>{i?this.setState({isConfigureColumnsShown:!1}):this.setState({isConfigureColumnsShown:!0})},children:[r.jsx("div",{className:"fa-layers",children:a}),r.jsx(ot,{children:"Configure Columns"}),r.jsx(Vl,{isShown:i,className:"cross-column-popper",onExited:()=>{this.setState({isConfigureColumnsShown:!1})},closeOnBlur:!0,interactive:!0,children:r.jsxs("div",{className:"cross-column-popup",children:["Searched Columns",r.jsx("div",{className:"cross-column-scroll",children:s.map(d=>r.jsxs(de.Fragment,{children:[r.jsx(nn,{className:"cross-column-checkbox",checked:n?!t.includes(d.name):t.includes(d.name),onChange:()=>this.toggleColumn(d.name),children:d.name}),d.type.substring(d.type.lastIndexOf(".")+1)]},d.name))}),r.jsxs("div",{className:"cross-column-button-bar",children:[r.jsx("button",{type:"button",className:"btn btn-link",onClick:this.selectAll,children:"Select All"}),r.jsx("button",{type:"button",className:"btn btn-link",onClick:this.clear,children:"Clear"}),r.jsx("button",{type:"button",className:"btn btn-link",onClick:this.selectNumbers,children:"Numbers Only"})]}),l&&r.jsxs("p",{className:"text-danger",children:[r.jsx(ee,{icon:wd})," Select at least one column to search."]})]})})]})]})}}const Ko=lE;const ls=ne.module("PartitionSelectorSearch"),aE=150;class Vr extends v.Component{static MAX_VISIBLE_ITEMS=12;static defaultProps={initialPageSize:100,onSelect:()=>{},onListResized:()=>{}};static propTypes={getFormattedString:z.func.isRequired,table:z.shape({addEventListener:z.func.isRequired,removeEventListener:z.func.isRequired,columns:z.arrayOf(z.shape({name:z.string.isRequired,type:z.string.isRequired,filter:z.func.isRequired})),size:z.number.isRequired,applyFilter:z.func.isRequired,setViewport:z.func.isRequired}).isRequired,initialPageSize:z.number,onSelect:z.func,onListResized:z.func};static handleError(e){e instanceof Hl||ls.error(e)}constructor(e){super(e),this.handleFilterChange=this.handleFilterChange.bind(this),this.handleInputFocus=this.handleInputFocus.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleListKeydown=this.handleListKeydown.bind(this),this.handleSelect=this.handleSelect.bind(this),this.handleTableUpdate=this.handleTableUpdate.bind(this),this.handleTextChange=this.handleTextChange.bind(this),this.handleViewportChange=this.handleViewportChange.bind(this),this.itemList=null,this.searchInput=null,this.timer=null,this.state={offset:0,itemCount:0,items:[],text:"",isLoading:!0}}componentDidMount(){this.startListening()}componentDidUpdate(e,t){const{isLoading:n,itemCount:s}=this.state,{onListResized:i}=this.props;(s!==t.itemCount||n!==t.isLoading)&&i()}componentWillUnmount(){this.debounceUpdateFilter.cancel(),this.stopListening()}itemList;searchInput;timer;handleKeyDown(e){if(this.itemList==null)return!1;const{items:t,itemCount:n}=this.state;switch(e.key){case"Enter":{let s=null;if(t.length>0)s=t[0].value;else{const{text:i}=this.state;s=i.trim()}if(s.length>0){const{onSelect:i}=this.props;i(s)}return e.stopPropagation(),e.preventDefault(),!0}case"ArrowDown":return n>0&&this.itemList.focusItem(1),e.stopPropagation(),e.preventDefault(),!0;default:return!1}}handleListKeydown(e){switch(e.key){case"Escape":break;default:this.focus();break}}handleFilterChange(){ls.debug2("handleFilterChange");const{table:e}=this.props,t=e.size;this.setState({itemCount:t,isLoading:!0})}handleInputFocus(){this.itemList&&this.itemList.focusItem(0)}handleSelect(e){ls.debug2("handleSelect",e);const{onSelect:t}=this.props,{offset:n,items:s}=this.state,i=e-n;if(i<0||s.length<=i){ls.error("No data for item",e);return}const{value:o}=s[i];t(o)}handleTableUpdate(e){const t=e.detail,{offset:n}=t,s=[],{getFormattedString:i,table:o}=this.props,l=o.columns[0];for(let d=0;d<t.rows.length;d+=1){const u=t.rows[d].get(l),m=i(u,l.type,l.name);s.push({displayValue:m,value:u})}const a=o.size;ls.debug2("handleTableUpdate",a,n,s.length),this.setState({itemCount:a,items:s,offset:n,isLoading:!1})}handleTextChange(e){ls.debug2("handleTextChange");const{value:t}=e.target;this.setState({text:t}),this.debounceUpdateFilter()}handleViewportChange(e,t){ls.debug2("handleViewportChange",e,t);const n=Math.max(1,t-e),s=Math.max(0,e-n),i=t+n,{table:o}=this.props;o.setViewport(s,i)}debounceUpdateFilter=Ye(()=>{this.updateFilter()},aE);focus(){this.searchInput&&this.searchInput.focus()}startListening(){const{initialPageSize:e,table:t}=this.props;t.addEventListener(I.Table.EVENT_UPDATED,this.handleTableUpdate),t.addEventListener(I.Table.EVENT_FILTERCHANGED,this.handleFilterChange),t.setViewport(0,e)}stopListening(){const{table:e}=this.props;e.removeEventListener(I.Table.EVENT_UPDATED,this.handleTableUpdate),e.removeEventListener(I.Table.EVENT_FILTERCHANGED,this.handleFilterChange)}updateFilter(){const{initialPageSize:e,table:t}=this.props,{text:n}=this.state,s=n.trim(),i=[];if(s.length>0){const l=t.columns[0].filter().invoke("matches",I.FilterValue.ofString(`(?s)(?i).*\\Q${s}\\E.*`));i.push(l)}ls.debug2("updateFilter",i),t.applyFilter(i),t.setViewport(0,e)}render(){const{isLoading:e,itemCount:t,items:n,offset:s,text:i}=this.state,o=Math.min(t,Vr.MAX_VISIBLE_ITEMS)*yi.DEFAULT_ROW_HEIGHT+11;return r.jsxs("div",{className:"iris-grid-partition-selector-search",children:[r.jsx("div",{className:"search-container",children:r.jsx("input",{type:"text",ref:l=>{this.searchInput=l},value:i,placeholder:"Available Partitions",onChange:this.handleTextChange,onFocus:this.handleInputFocus,onKeyDown:this.handleKeyDown,className:"form-control input-partition"})}),!e&&t>0&&r.jsx("div",{className:"iris-grid-partition-selector-search-list",onKeyDown:this.handleListKeydown,role:"presentation",style:{height:o},children:r.jsx(yi,{ref:l=>{this.itemList=l},itemCount:t,items:n,offset:s,onSelect:this.handleSelect,onViewportChange:this.handleViewportChange})}),!e&&t===0&&r.jsx("div",{className:"iris-grid-partition-selector-search-empty",children:"No results"}),e&&r.jsxs("div",{className:"iris-grid-partition-selector-loading",children:[r.jsx(In,{})," Loading..."]})]})}}const rE=Vr;const di=ne.module("IrisGridPartitionSelector"),dE=250;class cE extends v.Component{static defaultProps={onAppend:()=>{},onChange:()=>{},onFetchAll:()=>{},onDone:()=>{},partition:""};constructor(e){super(e),this.handleAppendClick=this.handleAppendClick.bind(this),this.handleCloseClick=this.handleCloseClick.bind(this),this.handleIgnoreClick=this.handleIgnoreClick.bind(this),this.handlePartitionChange=this.handlePartitionChange.bind(this),this.handlePartitionSelect=this.handlePartitionSelect.bind(this),this.handlePartitionListResized=this.handlePartitionListResized.bind(this),this.handleSearchOpened=this.handleSearchOpened.bind(this),this.handleSearchClosed=this.handleSearchClosed.bind(this),this.searchMenu=null,this.selectorSearch=null;const{partition:t}=e;this.state={partition:t}}componentWillUnmount(){this.debounceUpdate.cancel()}searchMenu;selectorSearch;handleAppendClick(){di.debug2("handleAppendClick");const{onAppend:e}=this.props,{partition:t}=this.state;e(t)}handleCloseClick(){di.debug2("handleCloseClick"),this.sendDone()}handleIgnoreClick(){di.debug2("handleIgnoreClick"),this.sendFetchAll()}handlePartitionChange(e){di.debug2("handlePartitionChange");const{value:t}=e.target;this.setState({partition:t}),this.debounceUpdate()}handlePartitionSelect(e){this.searchMenu&&this.searchMenu.closeMenu(),this.setState({partition:e},()=>{this.sendUpdate()})}handlePartitionListResized(){this.searchMenu&&this.searchMenu.scheduleUpdate()}handleSearchClosed(){const{table:e}=this.props;e.applyFilter([])}handleSearchOpened(){this.selectorSearch&&this.selectorSearch.focus()}debounceUpdate=Ye(()=>{this.sendUpdate()},dE);sendDone(){this.debounceUpdate.flush();const{onDone:e}=this.props;e()}sendUpdate(){di.debug2("sendUpdate");const{onChange:e}=this.props,{partition:t}=this.state;e(t)}sendFetchAll(){di.debug2("sendFetchAll"),this.debounceUpdate.cancel();const{onFetchAll:e}=this.props;e()}render(){const{columnName:e,getFormattedString:t,onDone:n,table:s}=this.props,{partition:i}=this.state,o=r.jsx(rE,{getFormattedString:t,table:s,onSelect:this.handlePartitionSelect,onListResized:this.handlePartitionListResized,ref:l=>{this.selectorSearch=l}},"search");return r.jsxs("div",{className:"iris-grid-partition-selector",children:[r.jsx("div",{className:"status-message",children:r.jsxs("span",{children:['Filtering "',e,'" partition to']})}),r.jsxs("div",{className:"input-group",children:[r.jsx("input",{type:"text",value:i,onChange:this.handlePartitionChange,className:"form-control input-partition"}),r.jsx("div",{className:"input-group-append",children:r.jsxs("button",{type:"button",className:"btn btn-outline-primary",children:[r.jsx(ee,{icon:Un}),r.jsx(ot,{children:"Partitions"}),r.jsx(Vn,{ref:l=>{this.searchMenu=l},actions:[{menuElement:o}],onMenuOpened:this.handleSearchOpened,onMenuClosed:this.handleSearchClosed})]})})]}),r.jsx("div",{className:"iris-grid-partition-selector-spacer"}),r.jsx("button",{type:"button",className:"btn btn-outline-primary btn-ignore",onClick:this.handleIgnoreClick,children:"Ignore & Fetch All"}),r.jsx("button",{type:"button",className:"btn btn-outline-primary btn-append",onClick:this.handleAppendClick,children:"Append Command"}),r.jsx("button",{type:"button",className:"btn btn-link btn-link-icon btn-close",onClick:n,children:r.jsx(ee,{icon:uo})})]})}}const hE=cE;const uE=ne.module("SelectDistinctBuilder");class mE extends v.Component{static defaultProps={selectDistinctColumns:[],onChange:()=>{}};constructor(e){super(e),this.handleAddColumnClick=this.handleAddColumnClick.bind(this),this.handleDeleteColumn=this.handleDeleteColumn.bind(this),this.handleDropdownChanged=this.handleDropdownChanged.bind(this);const{model:t,selectDistinctColumns:n}=this.props;this.state={inputs:n.length>0?[...n]:[""],columns:t.originalColumns}}componentDidUpdate(e,t){const{inputs:n}=this.state,{onChange:s}=this.props;if(t.inputs!==n){const i=n.filter(o=>o!=="");st(t.inputs.filter(o=>o!==""),i)||s(i)}}handleAddColumnClick(){this.setState(({inputs:e})=>({inputs:[...e,""]}))}handleDeleteColumn(e){this.setState(({inputs:t})=>({inputs:t.length===1&&e===0?[""]:t.filter((n,s)=>e!==s)}))}handleDropdownChanged(e,t){uE.debug("handleDropdownChanged",e,t);const{value:n}=t.target;this.setState(({inputs:s})=>{const i=[...s];return i[e]=n,{inputs:i}})}renderInputs(){const{columns:e,inputs:t}=this.state;return t.map((n,s)=>{const i=e.filter(({name:o})=>o===n||!t.includes(o)).map(({name:o})=>r.jsx("option",{value:o,children:o},o));return r.jsxs("div",{className:"form-inline px-3 pb-3",children:[r.jsxs("select",{className:"form-control custom-select col",value:n,onChange:o=>this.handleDropdownChanged(s,o),children:[r.jsx("option",{value:"",children:"Select a column"}),i]}),(t.length>1||n!=="")&&r.jsx(B,{kind:"ghost",className:"ml-1 px-2",onClick:()=>{this.handleDeleteColumn(s)},icon:r.jsx(ee,{icon:Gt,transform:"grow-3"}),tooltip:"Delete column"})]},s)})}render(){const{columns:e,inputs:t}=this.state,n=t.length>=e.length;return r.jsxs("div",{role:"presentation",className:"select-distinct-builder-container h-100",children:[r.jsx("div",{className:"select-distinct-title",children:"Display Unique Values From"}),this.renderInputs(),r.jsx("hr",{}),r.jsx("div",{className:"pt-1 px-3",children:r.jsx(B,{kind:"ghost",className:"btn-add-column",onClick:this.handleAddColumnClick,disabled:n,icon:Es,children:"Add Additional Column"})}),r.jsx("div",{className:"select-distinct-builder-footer",children:r.jsx("div",{className:"select-distinct-builder-hint",children:"Display only unique values from the selected table columns. Note that this will reset any filters and display only the selected columns."})})]})}}const gE=mE;function $r({items:c,onChange:e=()=>{}}){return r.jsx(Gc,{items:Array.from(c.entries()).map(([t,n])=>({title:$r.getAdvancedSettingsTitleForKey(t),isOn:n,onChange:s=>e(t,s)}))})}$r.getAdvancedSettingsTitleForKey=c=>{switch(c){case xi.FILTER_CONTROL_CHANGE_CLEARS_ALL_FILTERS:return"Clear current table filters before applying new filters from a control";case xi.LINK_CHANGE_CLEARS_ALL_FILTERS:return"Clear current table filters before applying new filters from an incoming link filter"}};const dc=ne.module("ConditionalFormattingMenu"),Da=()=>{};function pE(c){const{column:{type:e}}=c;if(F.isNumberType(e))return c.condition===$e.IS_NULL||c.condition===$e.IS_NOT_NULL?"":`${c.value}`;if(F.isCharType(e))return c.condition===Ft.IS_NULL||c.condition===Ft.IS_NOT_NULL?"":`${c.value}`;if(F.isStringType(e))return c.condition===Ht.IS_NULL||c.condition===Ht.IS_NOT_NULL?"":`"${c.value}"`;if(F.isDateType(e))return c.condition===Ft.IS_NULL||c.condition===Ft.IS_NOT_NULL?"":`${c.value}`;if(F.isBooleanType(e))return"";throw new Error(`Invalid column type ${e} in getRuleValue`)}function fE(c){return F.isNumberType(c.column.type)&&c.condition===$e.IS_BETWEEN?`${c.start} < ${c.column.name} < ${c.end}`:`${c.column.name} ${Gw(c.column.type,c.condition)}
30
+ ${pE(c)}`}function CE(c){const{rules:e=[],onChange:t=Da,onCreate:n=Da,onSelect:s=Da}=c,i=v.useCallback((d,h,u)=>{d.stopPropagation(),dc.debug("Rule clicked",h,u),s(u)},[s]),o=v.useCallback((d,h,u)=>{d.stopPropagation(),dc.debug("Delete button clicked",h,u);const m=[...e];m.splice(u,1),t(m)},[t,e]),l=v.useCallback(d=>{d.stopPropagation()},[]),a=v.useCallback(d=>{if(hn.stopDragging(),d.destination==null)return;const h=d.source.index,u=d.destination.index,m=[...e],g=e[h];m.splice(h,1),m.splice(u,0,g),t(m)},[t,e]);return r.jsxs("div",{className:"conditional-formatting-rules",children:[r.jsx(Pl,{onDragStart:hn.startDragging,onDragEnd:a,children:r.jsx(or,{droppableId:"droppable-custom-columns",children:(d,h)=>r.jsxs("div",{ref:d.innerRef,...d.droppableProps,className:Y("droppable-container",{dragging:h.draggingFromThisWith}),children:[e.length===0&&r.jsx("div",{className:"text-muted pl-2",children:"No formats defined"}),e.map((u,m)=>r.jsx(Uc,{draggableId:`${m}-${u.type}`,index:m,disableInteractiveElementBlocking:!0,children:(g,p)=>r.jsx("div",{role:"menuitem",tabIndex:0,onClick:C=>i(C,u,m),className:Y("draggable-container",{dragging:p.isDragging}),ref:g.innerRef,...g.draggableProps,children:r.jsx("div",{className:"conditional-formatting-list-item",children:r.jsxs("div",{className:"formatting-item",children:[r.jsx("div",{className:"rule-icon",children:r.jsx("span",{className:"rule-icon-bg",style:{backgroundColor:Tl(u.config.style),color:El(u.config.style)},children:u.type===Dn.ROWS?"row":"col"})}),r.jsx("div",{className:"rule-title",children:fE(u.config)}),r.jsx(B,{kind:"ghost",className:"ml-1 px-2",onClick:C=>o(C,u,m),icon:Gt,tooltip:"Delete rule"}),r.jsxs("button",{type:"button",className:"btn btn-link btn-link-icon px-2 btn-drag-handle",onClick:l,...g.dragHandleProps,children:[r.jsx(ot,{children:"Drag to re-order"}),r.jsx(ee,{icon:Wl})]})]})})})},`${m}-${u.type}`)),d.placeholder]})})}),r.jsx("hr",{}),r.jsx(B,{kind:"ghost",onClick:n,icon:Es,children:"Add New Rule"})]})}const Ls=ne.module("ConditionEditor"),bE=()=>{},SE=[$e.IS_EQUAL,$e.IS_NOT_EQUAL,$e.IS_BETWEEN,$e.GREATER_THAN,$e.GREATER_THAN_OR_EQUAL,$e.LESS_THAN,$e.LESS_THAN_OR_EQUAL,$e.IS_NULL,$e.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:Nw(c)},c)),wE=[Ht.IS_EXACTLY,Ht.IS_NOT_EXACTLY,Ht.CONTAINS,Ht.DOES_NOT_CONTAIN,Ht.STARTS_WITH,Ht.ENDS_WITH,Ht.IS_NULL,Ht.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:kw(c)},c)),vE=[Ft.IS_EXACTLY,Ft.IS_NOT_EXACTLY,Ft.IS_BEFORE,Ft.IS_BEFORE_OR_EQUAL,Ft.IS_AFTER,Ft.IS_AFTER_OR_EQUAL,Ft.IS_NULL,Ft.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:Mw(c)},c)),TE=[Xi.IS_TRUE,Xi.IS_FALSE,Xi.IS_NULL,Xi.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:Lw(c)},c)),EE=[zs.IS_EQUAL,zs.IS_NOT_EQUAL,zs.IS_NULL,zs.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:Ow(c)},c));function yE(c,e,t,n){return c===$e.IS_NULL||c===$e.IS_NOT_NULL||c===$e.IS_BETWEEN&&t!=null&&t!==""&&!Number.isNaN(Number.parseFloat(t))&&n!=null&&n!==""&&!Number.isNaN(Number.parseFloat(n))||c!==$e.IS_BETWEEN&&e!==void 0&&e!==""&&!Number.isNaN(Number.parseFloat(e))}function RE(c,e,t,n,s,i,o){switch(c){case $e.IS_EQUAL:case $e.IS_NOT_EQUAL:case $e.GREATER_THAN:case $e.GREATER_THAN_OR_EQUAL:case $e.LESS_THAN:case $e.LESS_THAN_OR_EQUAL:return r.jsx("input",{type:"number",className:"form-control",placeholder:"Enter value",value:s??"",onChange:e});case $e.IS_BETWEEN:return r.jsxs("div",{className:"d-flex flex-row",children:[r.jsx("input",{type:"number",className:"form-control d-flex mr-2",placeholder:"Start value",value:i??"",onChange:t}),r.jsx("input",{type:"number",className:"form-control d-flex",placeholder:"End value",value:o??"",onChange:n})]});case $e.IS_NULL:case $e.IS_NOT_NULL:return null}}function xE(c,e,t){switch(c){case Ht.IS_NULL:case Ht.IS_NOT_NULL:return null;default:return r.jsx("input",{type:"text",className:"form-control",placeholder:"Enter value",value:t??"",onChange:e})}}function DE(c,e,t){switch(c){case Ft.IS_NULL:case Ft.IS_NOT_NULL:return null;default:return r.jsx("input",{type:"text",className:"form-control",placeholder:"Enter value",value:t??"",onChange:e})}}function IE(){return null}function FE(c,e,t){switch(c){case zs.IS_NULL:case zs.IS_NOT_NULL:return null;default:return r.jsx("input",{type:"text",className:"form-control",maxLength:1,placeholder:"Enter value",value:t??"",onChange:e})}}function Lu(c){const{column:e,config:t,onChange:n=bE}=c,s=e.type,[i,o]=v.useState(s),[l,a]=v.useState(t.condition),[d,h]=v.useState(t.value),[u,m]=v.useState(t.start),[g,p]=v.useState(t.end);s!==i&&(a(bu(s)),h(Su(s)),m(void 0),p(void 0),o(s));const C=v.useMemo(()=>{if(s===void 0)return[];if(F.isNumberType(s))return SE;if(F.isCharType(s))return EE;if(F.isStringType(s))return wE;if(F.isDateType(s))return vE;if(F.isBooleanType(s))return TE},[s]),f=v.useCallback(y=>{const{value:E}=y.target;Ls.debug("handleConditionChange",E),a(E)},[]),b=v.useCallback(y=>{const{value:E}=y.target;Ls.debug("handleValueChange",E),h(E)},[]),w=v.useCallback(y=>{const{value:E}=y.target;Ls.debug("handleStartValueChange",E),m(E)},[]),S=v.useCallback(y=>{const{value:E}=y.target;Ls.debug("handleEndValueChange",E),p(E)},[]);v.useEffect(function(){let E=!0;l===void 0?(Ls.debug("Unable to create formatting rule. Condition is not selected."),E=!1):F.isNumberType(e.type)&&!yE(l,d,u,g)?(Ls.debug("Unable to create formatting rule. Invalid value",d),E=!1):F.isDateType(e.type)&&!Kw(l,d)&&(Ls.debug("Unable to create formatting rule. Invalid date condition",d),E=!1),n({condition:l,value:d,start:u,end:g},E)},[n,e.type,l,d,u,g]);const T=v.useMemo(()=>{if(s===void 0)return null;if(F.isNumberType(s))return RE(l,b,w,S,d,u,g);if(F.isCharType(s))return FE(l,b,d);if(F.isStringType(s))return xE(l,b,d);if(F.isDateType(s))return DE(l,b,d);if(F.isBooleanType(s))return IE()},[s,l,d,u,g,b,w,S]);return r.jsxs("div",{className:"condition-editor mb-2",children:[r.jsx("select",{value:l,id:"condition-select",className:"custom-select mb-2",onChange:f,children:C}),T]})}const NE=ne.module("StyleEditor"),kE="#fcfcfa",ME="#f0f0ee",LE="#1a171a",OE=200,AE=()=>{};function Ou(c){const{config:e,onChange:t=AE}=c,[n,s]=v.useState(e.type),[i,o]=v.useState(e.customConfig?.background??kE),[l,a]=v.useState(!1),[d,h]=v.useState(OE),u=v.useRef(null),m=v.useCallback(S=>{const{value:T}=S.target;NE.debug("handleBackgroundChange",T),o(T)},[]),g=v.useCallback(()=>{l&&a(!1)},[l]),p=v.useCallback(()=>{l||f(),a(!l)},[l]),C=v.useMemo(()=>[on.NO_FORMATTING,on.POSITIVE,on.NEGATIVE,on.WARN,on.NEUTRAL,on.ACCENT_1,on.ACCENT_2,on.CUSTOM],[]);function f(){u.current&&h(u.current.getBoundingClientRect().width)}v.useEffect(function(){t({type:n,customConfig:{color:lh.isDark(i)?ME:LE,background:i}})},[t,n,i]);const b=v.useCallback(()=>{const S=[];for(let T=0;T<C.length;T+=1){const y=C[T],E=`option-${T}-${y}`;S.push(r.jsxs(B,{kind:"inline",className:"style-option-btn",onClick:()=>{s(y),a(!1)},style:{color:El({type:y}),background:Tl({type:y})},children:[y===n&&r.jsx(ee,{icon:zn,className:"mr-2"}),y!==n&&r.jsx("span",{className:"mr-4"}),Jd(y)]},E))}return S},[C,n]),w=v.useCallback(()=>r.jsx("div",{className:"style-menu-container",role:"presentation",style:{width:d},children:r.jsx("div",{className:"style-options",children:b()})}),[d,b]);return r.jsxs("div",{className:"style-editor",children:[r.jsxs("div",{className:"mb-2",ref:u,children:[r.jsx("label",{className:"mb-0",children:"Style"}),r.jsxs(B,{kind:"inline",className:"cs-dropdown",style:{color:El({type:n}),background:Tl({type:n})},onClick:p,children:[Jd(n),r.jsx("span",{children:r.jsx(ee,{icon:Ig,className:"cs-caret"})}),r.jsx(Vn,{isShown:l,actions:{menuElement:w()},popperOptions:{placement:"bottom-start"},popperClassName:"style-dropdown-menu",onMenuClosed:g,menuStyle:{maxWidth:"100rem"}})]})]}),n===on.CUSTOM&&r.jsxs("div",{className:"mb-2",children:[r.jsx("label",{className:"mb-0",children:"Background"}),r.jsx("input",{type:"color",value:i,className:"custom-select color-select",onChange:m})]})]})}const Vi=ne.module("ColumnFormatEditor"),_E=()=>{};function PE(c){const{type:e,name:t}=c[0];return{column:{type:e,name:t},style:vu(),...na(e)}}function jE(c){const{columns:e,config:t=PE(e),onChange:n=_E}=c,[s,i]=v.useState(e.find(f=>f.name===t.column.name&&f.type===t.column.type)??e[0]),[o,l]=v.useState(wu(t)),[a,d]=v.useState(!1),[h,u]=v.useState(t.style),m=v.useCallback(f=>{const b=e.find(({name:w})=>w===f);b!==void 0?(i(b),s.type!==b.type&&(l(na(b.type)),d(!1))):Vi.error(`Column ${f} not found.`)},[e,s]),g=v.useCallback((f,b)=>{Vi.debug("handleConditionChange",f,b),l(f),d(b)},[]),p=v.useCallback(f=>{Vi.debug("handleStyleChange",f),u(f)},[]);v.useEffect(function(){let b=a;s===void 0&&(Vi.debug("Column is not selected, invalidating update."),b=!1),(h===void 0||h.type===on.NO_FORMATTING)&&(Vi.debug("Style is not selected, invalidating update."),b=!1);const{type:w,name:S}=s;n({column:{type:w,name:S},style:h,...o},b)},[n,s,h,o,a]);const C=e.map(({name:f})=>({title:f,value:f}));return r.jsxs("div",{className:"conditional-rule-editor form",children:[r.jsxs("div",{className:"mb-2",children:[r.jsx("label",{className:"mb-0",children:"Format Cell If"}),r.jsx(zc,{defaultValue:s?.name,options:C,inputPlaceholder:"Select a column",spellCheck:!1,onChange:m,searchPlaceholder:"Filter columns"})]}),s!==void 0&&r.jsxs(r.Fragment,{children:[r.jsx(Lu,{column:s,config:o,onChange:g}),r.jsx(Ou,{config:h,onChange:p})]})]})}const $i=ne.module("RowFormatEditor"),HE=()=>{};function BE(c){const{type:e,name:t}=c[0];return{column:{type:e,name:t},style:vu(),...na(e)}}function UE(c){const{columns:e,config:t=BE(e),onChange:n=HE}=c,[s,i]=v.useState(e.find(f=>f.name===t.column.name&&f.type===t.column.type)??e[0]),[o,l]=v.useState(wu(t)),[a,d]=v.useState(!1),[h,u]=v.useState(t.style),m=v.useCallback(f=>{const b=e.find(({name:w})=>w===f);b!==void 0?(i(b),s.type!==b.type&&(l(na(b.type)),d(!1))):$i.error(`Column ${f} not found.`)},[e,s]),g=v.useCallback((f,b)=>{$i.debug("handleConditionChange",f,b),l(f),d(b)},[]),p=v.useCallback(f=>{$i.debug("handleStyleChange",f),u(f)},[]);v.useEffect(function(){if(s===void 0){$i.debug("Column is not selected, skip update.");return}if(h===void 0){$i.debug("Style is not selected, skip update.");return}const{type:b,name:w}=s;n({column:{type:b,name:w},style:h,...o},a)},[n,s,h,o,a]);const C=e.map(({name:f})=>({title:f,value:f}));return r.jsxs("div",{className:"conditional-rule-editor form",children:[r.jsxs("div",{className:"mb-2",children:[r.jsx("label",{className:"mb-0",children:"Format Row If"}),r.jsx(zc,{defaultValue:s?.name,options:C,inputPlaceholder:"Select a column",spellCheck:!1,onChange:m,searchPlaceholder:"Filter columns"})]}),s!==void 0&&r.jsxs(r.Fragment,{children:[r.jsx(Lu,{column:s,config:o,onChange:g}),r.jsx(Ou,{config:h,onChange:p})]})]})}const Ia=ne.module("ConditionalFormatEditor"),Fa=()=>{};function VE(c){switch(c){case Dn.CONDITIONAL:return r.jsx(wT,{});case Dn.ROWS:return r.jsx(vT,{})}}function $E(c){switch(c){case Dn.CONDITIONAL:return"Conditional";case Dn.ROWS:return"Rows"}}const cc=[Dn.CONDITIONAL,Dn.ROWS];function WE(c){const{columns:e,onSave:t=Fa,onUpdate:n=Fa,onCancel:s=Fa,rule:i}=c,o=e.filter(Yw),[l,a]=v.useState(i?.type??cc[0]),[d,h]=v.useState(i),[u,m]=v.useState(!1),g=v.useCallback(()=>{s()},[s]),p=v.useCallback(()=>{if(d===void 0){Ia.error("Rule is not defined.");return}t(d)},[t,d]),C=v.useCallback(b=>{Ia.debug("handleFormatterChange",b),a(b)},[]),f=v.useCallback((b,w)=>{Ia.debug("handleRuleChange",b,w,l);const S={type:l,config:b};h(S),m(w),n(w?S:void 0)},[n,l]);return r.jsxs("div",{className:"conditional-format-editor form",children:[r.jsxs("div",{className:"mb-2",children:[r.jsx("label",{className:"mb-0",htmlFor:"formatter-select",children:"Select Formatter"}),r.jsx("div",{className:"formatter-list",children:cc.map((b,w)=>r.jsx("div",{className:"formatter-type",children:r.jsxs("button",{type:"button",className:Y("btn","btn-icon","btn-formatter-type",{active:b===l}),"data-index":w,onClick:()=>C(b),children:[VE(b),$E(b)]})},b))})]}),l===Dn.CONDITIONAL&&r.jsx(jE,{columns:o,config:d?.config,onChange:f}),l===Dn.ROWS&&r.jsx(UE,{columns:o,config:d?.config,onChange:f}),r.jsx("hr",{}),r.jsxs("div",{className:"d-flex justify-content-end my-3",children:[r.jsx(B,{kind:"secondary",onClick:g,className:"mr-2",children:"Cancel"}),r.jsx(B,{kind:"primary",onClick:p,disabled:d===void 0||!u,children:"Done"})]})]})}function GE({text:c,isOpen:e,onClose:t}){const[n,s]=v.useState(!1),[i,o]=v.useState(0),[l,a]=v.useState(!1),[d,h]=v.useState(!1),[u,m]=v.useState(!1),g=v.useRef();v.useEffect(function(){if(e){try{JSON.parse(c),m(!0)}catch{m(!1)}h(!1)}},[e,c]),v.useEffect(function(){g.current&&g.current.layout()},[i]),v.useEffect(function(){g.current&&g.current.updateOptions({lineNumbers:l?"on":"off"})},[l]);function p(){a(!l)}function C(){const S=g.current?.getModel();!u||!S||(d?(S.setValue(c),h(!1)):(S.setValue(JSON.stringify(JSON.parse(c),void 0,2)),h(!0)),f())}function f(){const S=g.current;S&&a((S.getModel()?.getLineCount()??0)>1)}function b(){n&&(g.current=void 0,t())}function w(S){g.current=S,o(S.getContentHeight()),S.onDidContentSizeChange(({contentHeight:T})=>o(T)),f()}return!e&&!n?null:r.jsxs(Gl,{isOpen:e,centered:!0,keyboard:!0,toggle:b,onOpened:()=>s(!0),onClosed:()=>{s(!1),o(0)},className:"theme-bg-dark cell-overflow-modal",size:"xl",children:[r.jsxs(zl,{toggle:t,children:[r.jsx("h5",{className:"overflow-modal-title",children:"Cell Contents"}),r.jsx(Bl,{kind:"inline",tooltip:"Copy cell contents",copy:g.current?.getValue()??c}),r.jsx(B,{kind:"inline",active:l,icon:Fg,tooltip:"Toggle line numbers",onClick:p}),u&&r.jsx(B,{kind:"inline",icon:Ng,active:d,tooltip:"Format as JSON",onClick:C})]}),r.jsx(Kl,{style:{height:i},children:r.jsx(br,{onEditorInitialized:w,settings:{value:c,readOnly:!0,wordWrap:"on",language:u?"typescript":"plaintext",folding:u,padding:{bottom:16},lineNumbers:l?"on":"off",overviewRulerLanes:0,renderLineHighlight:"none",find:{seedSearchStringFromSelection:"never"}}})})]})}function zE(c){return c.model!==void 0}const KE="###,##0";function YE({gotoRow:c,gotoRowError:e,gotoValueError:t,onGotoRowSubmit:n,isShown:s,onEntering:i,onEntered:o,onExiting:l,onExited:a,model:d,onGotoRowNumberChanged:h,onClose:u,gotoValueSelectedColumnName:m,gotoValue:g,gotoValueFilter:p,onGotoValueSelectedColumnNameChanged:C,onGotoValueSelectedFilterChanged:f,onGotoValueChanged:b,onGotoValueSubmit:w}){const S=v.useRef(null),T=v.useRef(null),[y,E]=v.useState(!1);let R=[];zE(d)&&d.table!==void 0&&({columns:R}=d.table);const x="Row number",{rowCount:D}=d,M=$=>{$.key==="Enter"?($.stopPropagation(),$.preventDefault(),w()):($.key==="Backspace"||$.key==="Delete")&&(g===`${Number.POSITIVE_INFINITY}`||g===`${Number.NEGATIVE_INFINITY}`)&&j("")},O=$=>{$.key==="Enter"&&($.stopPropagation(),$.preventDefault(),w($.shiftKey))},H=d.getColumnIndexByName(m),V=R[H??0]?.type,U=F.getNormalizedType(V),j=$=>{b($??"")},P=()=>{y&&document.activeElement!==S.current?S.current?.select():!y&&document.activeElement!==T.current&&T.current?.select()};v.useEffect(P,[y,c,g]);const Q=()=>{switch(U){case F.dataType.DECIMAL:case F.dataType.INT:return r.jsx("div",{className:"goto-row-input",children:r.jsx("input",{ref:T,className:Y("form-control",{"is-invalid":t!==""}),onKeyDown:M,placeholder:"value",onChange:$=>{const J=$.target.value.toLowerCase();/^-?[0-9]*\.?[0-9]*$/.test($.target.value)?j($.target.value):J==="-i"||J==="-infinity"?j(`${Number.NEGATIVE_INFINITY}`):(J==="i"||J==="infinity")&&j(`${Number.POSITIVE_INFINITY}`)},value:g})});case F.dataType.DATETIME:return r.jsx("div",{className:"goto-value-date-time-input",children:r.jsx(jm,{ref:T,className:Y("form-control","goto-value-date-time-input",{"is-invalid":t!==""}),defaultValue:g,onChange:j,onSubmit:O})});case F.dataType.STRING:return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"goto-row-input",children:r.jsxs("select",{className:"custom-select",onChange:$=>{f($.target.value)},value:p,children:[r.jsx("option",{value:be.eq,children:"Equals"},be.eq),r.jsx("option",{value:be.contains,children:"Contains"},be.contains),r.jsx("option",{value:be.eqIgnoreCase,children:"EqIgnoreCase"},be.eqIgnoreCase)]})}),r.jsx("div",{className:"goto-row-input",children:r.jsx("input",{ref:T,className:Y("form-control",{"is-invalid":t!==""}),onKeyDown:O,placeholder:"value",onChange:$=>j($.target.value),value:g})})]});case F.dataType.BOOLEAN:return r.jsx("div",{className:"goto-row-input",children:r.jsxs("select",{className:"custom-select",onChange:$=>{j($.target.value)},value:g,children:[r.jsx("option",{"aria-label":"null value",value:""},"null"),r.jsx("option",{value:"true",children:"true"},"true"),r.jsx("option",{value:"false",children:"false"},"false")]})});default:return r.jsx("div",{className:"goto-row-input",children:r.jsx("input",{ref:T,className:"form-control",onKeyDown:O,placeholder:"value",onChange:$=>j($.target.value),value:g})})}};return r.jsx(sa,{isShown:s,className:Y("goto-row"),onEntering:i,onEntered:()=>{o(),P()},onExiting:l,onExited:a,children:r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"goto-row-row",children:[r.jsxs("div",{className:Y("goto-row-wrapper",{"is-inactive":!y}),onClick:()=>E(!0),onFocus:()=>E(!0),role:"group",children:[r.jsx("div",{className:"goto-row-text",children:"Go to row"}),r.jsx("div",{className:"goto-row-input",children:r.jsx("input",{ref:S,type:"number",onKeyDown:$=>{$.key==="Enter"&&($.stopPropagation(),$.preventDefault(),n())},className:Y("form-control",{"is-invalid":e!==""}),placeholder:x,onChange:$=>{h($)},value:c})}),r.jsxs("div",{className:"goto-row-text",children:["of ",dh.i18n.NumberFormat.format(KE,D)]}),e&&r.jsx("div",{className:"text-danger",children:e})]}),r.jsx("div",{className:"goto-row-close",children:r.jsx(B,{kind:"ghost",onClick:u,children:r.jsx(ee,{icon:uo,style:{marginRight:"0"}})})})]}),d.isSeekRowAvailable&&r.jsx("div",{className:"goto-row-row",children:r.jsxs("div",{className:Y("goto-row-wrapper",{"is-inactive":y}),onClick:()=>E(!1),onFocus:()=>E(!1),role:"group",children:[r.jsx("div",{className:"goto-row-text",children:"Go to value"}),r.jsx("div",{className:"goto-row-input",children:r.jsx("select",{className:"custom-select",onChange:$=>{const J=$.target.value;C(J)},value:m,children:R.map($=>r.jsx("option",{value:$.name,children:$.name},$.name))})}),Q(),r.jsxs("div",{children:[r.jsx(B,{kind:"ghost",disabled:g==="",onClick:()=>{w(!0)},children:r.jsx(ee,{icon:sh})}),r.jsx(B,{kind:"ghost",disabled:g==="",onClick:()=>{w(!1)},children:r.jsx(ee,{icon:kg})})]}),t&&r.jsx("div",{className:"text-danger",children:t})]})})]})})}const me=ne.module("IrisGrid"),qE=500,XE=250,ZE=250,QE=250,hc=Object.freeze({aggregations:ke,showOnTop:!1}),JE="yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS z";function uc({advancedFilters:c,aggregationSettings:e,customColumns:t,quickFilters:n,reverseType:s,rollupConfig:i,searchFilter:o,selectDistinctColumns:l,sorts:a}){return c.size===0&&e.aggregations.length===0&&t.length===0&&n.size===0&&s===F.REVERSE_TYPE.NONE&&i==null&&o==null&&l.length===0&&a.length===0}class Hn extends v.Component{static minDebounce=150;static maxDebounce=500;static loadingSpinnerDelay=800;static defaultProps={children:null,advancedFilters:Pn,advancedSettings:Pn,alwaysFetchColumns:ke,conditionalFormats:ke,customColumnFormatMap:Pn,isFilterBarShown:!1,applyInputFiltersOnInit:!1,movedColumns:ke,movedRows:ke,inputFilters:ke,customFilters:ke,onCreateChart:void 0,onColumnSelected:()=>{},onDataSelected:()=>{},onError:()=>{},onStateChange:()=>{},onPartitionAppend:()=>{},onAdvancedSettingsChange:()=>{},partition:null,partitionColumn:null,quickFilters:Pn,selectDistinctColumns:ke,sorts:ke,reverseType:F.REVERSE_TYPE.NONE,customColumns:ke,aggregationSettings:hc,rollupConfig:void 0,userColumnWidths:Pn,userRowHeights:Pn,onSelectionChanged:()=>{},isSelectingColumn:!1,isSelectingPartition:!1,isStuckToBottom:!1,isStuckToRight:!1,columnSelectionValidator:null,columnAllowedCursor:null,columnNotAllowedCursor:null,name:"table",onlyFetchVisibleColumns:!0,showSearchBar:!1,searchValue:"",selectedSearchColumns:null,invertSearchColumns:!0,onContextMenu:()=>{},pendingDataMap:Pn,getDownloadWorker:void 0,settings:{timeZone:"America/New_York",defaultDateTimeFormat:Xs.FULL_DATE_FORMAT,showTimeZone:!1,showTSeparator:!0,truncateNumbersWithPound:!1,formatter:ke,decimalFormatOptions:z.shape({defaultFormatString:z.string}),integerFormatOptions:z.shape({defaultFormatString:z.string})},canCopy:!0,canDownloadCsv:!0,frozenColumns:null,theme:sc,canToggleSearch:!0};static makeQuickFilter(e,t,n){try{return F.makeQuickFilter(e,t,n)}catch(s){me.error("Error creating quick filter",s)}return null}constructor(e){super(e),this.handleAdvancedFilterChange=this.handleAdvancedFilterChange.bind(this),this.handleAdvancedFilterSortChange=this.handleAdvancedFilterSortChange.bind(this),this.handleAdvancedFilterDone=this.handleAdvancedFilterDone.bind(this),this.handleAdvancedMenuOpened=this.handleAdvancedMenuOpened.bind(this),this.handleGotoRowOpened=this.handleGotoRowOpened.bind(this),this.handleGotoRowClosed=this.handleGotoRowClosed.bind(this),this.handleAdvancedMenuClosed=this.handleAdvancedMenuClosed.bind(this),this.handleAggregationChange=this.handleAggregationChange.bind(this),this.handleAggregationsChange=this.handleAggregationsChange.bind(this),this.handleAggregationEdit=this.handleAggregationEdit.bind(this),this.handleAnimationLoop=this.handleAnimationLoop.bind(this),this.handleAnimationStart=this.handleAnimationStart.bind(this),this.handleAnimationEnd=this.handleAnimationEnd.bind(this),this.handleChartChange=this.handleChartChange.bind(this),this.handleChartCreate=this.handleChartCreate.bind(this),this.handleGridError=this.handleGridError.bind(this),this.handleFilterBarChange=this.handleFilterBarChange.bind(this),this.handleFilterBarDone=this.handleFilterBarDone.bind(this),this.handleFilterBarTab=this.handleFilterBarTab.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleMenu=this.handleMenu.bind(this),this.handleMenuClose=this.handleMenuClose.bind(this),this.handleMenuSelect=this.handleMenuSelect.bind(this),this.handleMenuBack=this.handleMenuBack.bind(this),this.handleRequestFailed=this.handleRequestFailed.bind(this),this.handleSelectionChanged=this.handleSelectionChanged.bind(this),this.handleMovedColumnsChanged=this.handleMovedColumnsChanged.bind(this),this.handleHeaderGroupsChanged=this.handleHeaderGroupsChanged.bind(this),this.handleUpdate=this.handleUpdate.bind(this),this.handleTooltipRef=this.handleTooltipRef.bind(this),this.handleViewChanged=this.handleViewChanged.bind(this),this.handleFormatSelection=this.handleFormatSelection.bind(this),this.handleConditionalFormatCreate=this.handleConditionalFormatCreate.bind(this),this.handleConditionalFormatEdit=this.handleConditionalFormatEdit.bind(this),this.handleConditionalFormatsChange=this.handleConditionalFormatsChange.bind(this),this.handleConditionalFormatEditorSave=this.handleConditionalFormatEditorSave.bind(this),this.handleConditionalFormatEditorCancel=this.handleConditionalFormatEditorCancel.bind(this),this.handleUpdateCustomColumns=this.handleUpdateCustomColumns.bind(this),this.handleCustomColumnsChanged=this.handleCustomColumnsChanged.bind(this),this.handleSelectDistinctChanged=this.handleSelectDistinctChanged.bind(this),this.handlePendingDataUpdated=this.handlePendingDataUpdated.bind(this),this.handlePendingCommitClicked=this.handlePendingCommitClicked.bind(this),this.handlePendingDiscardClicked=this.handlePendingDiscardClicked.bind(this),this.handleGotoRowSelectedRowNumberSubmit=this.handleGotoRowSelectedRowNumberSubmit.bind(this),this.focusRowInGrid=this.focusRowInGrid.bind(this),this.handleDownloadTable=this.handleDownloadTable.bind(this),this.handleDownloadTableStart=this.handleDownloadTableStart.bind(this),this.handleCancelDownloadTable=this.handleCancelDownloadTable.bind(this),this.handleDownloadCanceled=this.handleDownloadCanceled.bind(this),this.handleDownloadCompleted=this.handleDownloadCompleted.bind(this),this.handlePartitionAppend=this.handlePartitionAppend.bind(this),this.handlePartitionChange=this.handlePartitionChange.bind(this),this.handlePartitionFetchAll=this.handlePartitionFetchAll.bind(this),this.handlePartitionDone=this.handlePartitionDone.bind(this),this.handleColumnVisibilityChanged=this.handleColumnVisibilityChanged.bind(this),this.handleColumnVisibilityReset=this.handleColumnVisibilityReset.bind(this),this.handleCrossColumnSearch=this.handleCrossColumnSearch.bind(this),this.handleRollupChange=this.handleRollupChange.bind(this),this.handleOverflowClose=this.handleOverflowClose.bind(this),this.getColumnBoundingRect=this.getColumnBoundingRect.bind(this),this.handleGotoRowSelectedRowNumberChanged=this.handleGotoRowSelectedRowNumberChanged.bind(this),this.handleGotoValueSelectedColumnNameChanged=this.handleGotoValueSelectedColumnNameChanged.bind(this),this.handleGotoValueSelectedFilterChanged=this.handleGotoValueSelectedFilterChanged.bind(this),this.handleGotoValueChanged=this.handleGotoValueChanged.bind(this),this.handleGotoValueSubmitted=this.handleGotoValueSubmitted.bind(this),this.grid=null,this.gridWrapper=null,this.lastLoadedConfig=null,this.pending=new Yn,this.globalColumnFormats=ke,this.decimalFormatOptions={},this.integerFormatOptions={},this.truncateNumbersWithPound=!1,this.renderer=new tT,this.tableSaver=null,this.crossColumnRef=de.createRef(),this.isAnimating=!1,this.filterInputRef=de.createRef(),this.toggleFilterBarAction={action:()=>this.toggleFilterBar(),shortcut:Ut.TABLE.TOGGLE_QUICK_FILTER},this.toggleSearchBarAction={action:()=>this.toggleSearchBar(),shortcut:Ut.TABLE.TOGGLE_SEARCH},this.toggleGotoRowAction={action:()=>this.toggleGotoRow(),shortcut:Ut.TABLE.GOTO_ROW},this.discardAction={action:()=>{const{model:P}=this.props;Xe(P)&&P.isEditable&&P.pendingDataMap.size>0&&this.discardPending().catch(me.error)},shortcut:Ut.INPUT_TABLE.DISCARD},this.commitAction={action:()=>{const{model:P}=this.props;Xe(P)&&P.isEditable&&P.pendingDataMap.size>0&&P.pendingDataErrors.size===0&&this.commitPending().catch(me.error)},shortcut:Ut.INPUT_TABLE.COMMIT},this.contextActions=[this.toggleFilterBarAction,this.toggleSearchBarAction,this.toggleGotoRowAction,this.discardAction,this.commitAction];const{aggregationSettings:t,conditionalFormats:n,customColumnFormatMap:s,isFilterBarShown:i,isSelectingPartition:o,model:l,movedColumns:a,movedRows:d,partition:h,partitionColumn:u,rollupConfig:m,userColumnWidths:g,userRowHeights:p,showSearchBar:C,searchValue:f,selectedSearchColumns:b,invertSearchColumns:w,advancedFilters:S,quickFilters:T,selectDistinctColumns:y,pendingDataMap:E,canCopy:R,frozenColumns:x,columnHeaderGroups:D}=e,M=[new gv(this),new fv(this)];R&&M.push(new dv(this));const O=[new bv(this),new Av(this),new Uv(this),new wv(this),new Tv(this),new Pv(this),new Lv(this),new Fv(this),new kv(this),new Hv(this)],H=a.length>0?a:l.initialMovedColumns,L=d.length>0?d:l.initialMovedRows,V=new Gv({userColumnWidths:new Map(g),userRowHeights:new Map(p),movedColumns:H,initialColumnWidths:new Map(l?.layoutHints?.hiddenColumns?.map(P=>[l.getColumnIndexByName(P),0]))}),U=b??[],j=Ko.createSearchFilter(f,U,l.columns,w);this.state={isFilterBarShown:i,isSelectingPartition:o,focusedFilterBarColumn:null,metricCalculator:V,metrics:void 0,keyHandlers:M,mouseHandlers:O,partition:h,partitionColumn:u,partitionTable:null,partitionFilters:[],quickFilters:T?new Map(T):new Map,advancedFilters:new Map(S),shownAdvancedFilter:null,hoverAdvancedFilter:null,sorts:[],reverseType:F.REVERSE_TYPE.NONE,customColumns:[],selectDistinctColumns:y,selectedRanges:[],copyOperation:null,loadingText:null,loadingScrimProgress:null,loadingSpinnerShown:!1,movedColumns:H,movedRows:L,shownColumnTooltip:null,formatter:new gn,isMenuShown:!1,customColumnFormatMap:new Map(s),conditionalFormats:n,conditionalFormatEditIndex:null,conditionalFormatPreview:void 0,hoverSelectColumn:null,isTableDownloading:!1,isReady:!1,tableDownloadStatus:"",tableDownloadProgress:0,tableDownloadEstimatedTime:0,showSearchBar:C,searchFilter:j,searchValue:f,selectedSearchColumns:U,invertSearchColumns:w,rollupConfig:m,rollupSelectedColumns:[],aggregationSettings:t,selectedAggregation:null,openOptions:[],pendingRowCount:0,pendingDataMap:E??new Map,pendingDataErrors:new Map,pendingSavePromise:null,pendingSaveError:null,toastMessage:null,frozenColumns:x,showOverflowModal:!1,overflowText:"",overflowButtonTooltipProps:null,expandCellTooltipProps:null,expandTooltipDisplayValue:"expand",linkHoverTooltipProps:null,linkHoverDisplayValue:"",isGotoShown:!1,gotoRow:"",gotoRowError:"",gotoValueError:"",gotoValueSelectedColumnName:l.columns[0]?.name??"",gotoValueSelectedFilter:be.eq,gotoValue:"",columnHeaderGroups:D??l.initialColumnHeaderGroups}}componentDidMount(){const{partitionColumn:e,model:t}=this.props,n=e??t.columns.find(s=>s.isPartitionColumn);t.isFilterRequired&&t.isValuesTableAvailable&&n!=null?this.loadPartitionsTable(n):this.initState(),this.startListening(t)}componentDidUpdate(e){const{inputFilters:t,isSelectingColumn:n,settings:s,model:i,customFilters:o,sorts:l}=this.props;i!==e.model&&(this.stopListening(e.model),this.startListening(i));const a=t!==e.inputFilters?t.filter(u=>!e.inputFilters.includes(u)):[];if(a.length>0){const{advancedSettings:u}=this.props,m=u.get(xi.FILTER_CONTROL_CHANGE_CLEARS_ALL_FILTERS)??!1;m&&(this.clearGridInputField(),this.clearCrossColumSearch()),this.startLoading("Filtering...",!0),this.applyInputFilters(a,m)}n!==e.isSelectingColumn&&this.resetColumnSelection(),s!==e.settings&&this.updateFormatterSettings(s),o!==e.customFilters&&this.startLoading("Filtering...",!0),l!==e.sorts&&this.updateSorts(l);const{loadingScrimStartTime:d,loadingScrimFinishTime:h}=this;d!=null&&h!=null&&window.requestAnimationFrame(()=>{const u=Date.now(),m=u-d,g=h-d,p=Math.min(m/g,1);h<u&&(this.loadingScrimStartTime=void 0,this.loadingScrimFinishTime=void 0),this.setState(C=>C.loadingScrimProgress==null?(me.debug2("Ignoring scrim update because loading cancelled."),null):{loadingScrimProgress:p})}),this.sendStateChange()}componentWillUnmount(){const{model:e}=this.props;this.stopListening(e),this.pending.cancel(),this.updateSearchFilter.cancel(),this.loadingTimer&&clearTimeout(this.loadingTimer),this.handleDownloadProgressUpdate.cancel(),this.animationFrame!==void 0&&cancelAnimationFrame(this.animationFrame)}grid;gridWrapper;lastFocusedFilterBarColumn;lastLoadedConfig;tooltip;pending;globalColumnFormats;dateTimeFormatterOptions;decimalFormatOptions;integerFormatOptions;truncateNumbersWithPound;loadingScrimStartTime;loadingScrimFinishTime;animationFrame;loadingTimer;renderer;tableSaver;crossColumnRef;isAnimating;filterInputRef;toggleFilterBarAction;toggleSearchBarAction;toggleGotoRowAction;discardAction;commitAction;contextActions;getAdvancedMenuOpenedHandler=Re(e=>this.handleAdvancedMenuOpened.bind(this,e),{max:100});getCachedAdvancedFilterMenuActions=Re((e,t,n,s,i)=>r.jsx(hT,{model:e,column:t,onFilterChange:this.handleAdvancedFilterChange,onSortChange:this.handleAdvancedFilterSortChange,onDone:this.handleAdvancedFilterDone,options:n,sortDirection:s,formatter:i}),{max:50});getCachedOptionItems=Re((e,t,n,s,i,o,l,a,d,h,u,m,g,p,C,f)=>{const b=[];return e&&b.push({type:Ne.CHART_BUILDER,title:"Chart Builder",icon:Mg}),b.push({type:Ne.VISIBILITY_ORDERING_BUILDER,title:"Organize Columns",icon:gr}),n&&b.push({type:Ne.CONDITIONAL_FORMATTING,title:"Conditional Formatting",icon:go}),t&&b.push({type:Ne.CUSTOM_COLUMN_BUILDER,title:"Custom Columns",icon:Lg}),s&&b.push({type:Ne.ROLLUP_ROWS,title:"Rollup Rows",icon:ih}),i&&b.push({type:Ne.AGGREGATIONS,title:"Aggregate Columns",icon:Og}),o&&b.push({type:Ne.SELECT_DISTINCT,title:"Select Distinct Values",icon:Ag}),l&&g&&b.push({type:Ne.TABLE_EXPORTER,title:"Download CSV",icon:_g}),f&&b.push({type:Ne.ADVANCED_SETTINGS,title:"Advanced Settings",icon:Pg}),b.push({type:Ne.QUICK_FILTERS,title:"Quick Filters",subtitle:a.shortcut.getDisplayText(),icon:dl,isOn:u,onChange:a.action}),p&&b.push({type:Ne.SEARCH_BAR,title:"Search Bar",subtitle:d.shortcut.getDisplayText(),icon:jg,isOn:m,onChange:d.action}),b.push({type:Ne.GOTO,title:"Go to",subtitle:h.shortcut.getDisplayText(),icon:Hg,isOn:C,onChange:h.action}),Object.freeze(b)},{max:1});getCachedHiddenColumns=Re((e,t)=>Se.getHiddenColumns(new Map([...e.initialColumnWidths,...t])),{max:1});getAggregationMap=Re((e,t)=>{const n={};return t.forEach(({operation:s,selected:i,invert:o})=>{n[s]=Cs.getOperationColumnNames(e,s,i,o)}),n});getOperationMap=Re((e,t)=>{const n={};return t.filter(s=>!Cs.isRollupOperation(s.operation)).forEach(({operation:s,selected:i,invert:o})=>{Cs.getOperationColumnNames(e,s,i,o).forEach(l=>{const a=[...n[l]??[],s];n[l]=Object.freeze(a)})}),n});getOperationOrder=Re(e=>e.map(t=>t.operation).filter(t=>!Cs.isRollupOperation(t)));getCachedFormatColumns=Re((e,t)=>zw(e,t));getCachedPreviewFormatColumns=Re((e,t,n,s)=>{if(me.debug("getCachedPreviewFormatColumns",t,n,s),n!==void 0&&s!==void 0){const i=[...t];return i[s]=n,this.getCachedFormatColumns(e,i)}return this.getCachedFormatColumns(e,t)});getModelRollupConfig=Re((e,t,n)=>Se.getModelRollupConfig(e,t,n));getModelTotalsConfig=Re((e,t,n)=>{const{aggregations:s,showOnTop:i}=n;if((t?.columns?.length??0)>0||(s?.length??0)===0)return null;const o=this.getOperationMap(e,s),l=this.getOperationOrder(s);return{operationMap:o,operationOrder:l,showOnTop:i}});getCachedStateOverride=Re((e,t,n,s,i,o,l,a,d,h)=>({hoverSelectColumn:e,isFilterBarShown:t,isSelectingColumn:n,loadingScrimProgress:s,quickFilters:i,advancedFilters:o,sorts:l,reverseType:a,rollupConfig:d,isMenuShown:h}),{max:1});getCachedFilter=Re((e,t,n,s,i)=>[...e??[],...s??[],...Se.getFiltersFromFilterMap(t),...Se.getFiltersFromFilterMap(n),...i!==void 0?[i]:[]],{max:1});getCachedTheme=Re((e,t,n)=>({...sc,...e,autoSelectRow:!t,rowFooterWidth:n>0?e.rowFooterWidth:0}),{max:1});getValueForCell(e,t,n=!1){const{model:s}=this.props,i=this.getModelColumn(e),o=this.getModelRow(t);if(n&&i!=null&&o!=null){const l=s.valueForCell(i,o);if(F.isDateType(s.columns[i].type)){const{formatter:a}=s;return I.i18n.DateTimeFormat.format(JE,l,I.i18n.TimeZone.getTimeZone(a.timeZone))}return l}return n?null:i!=null&&o!=null?s.textForCell(i,o):""}getModelColumn(e){const{metrics:t}=this.state;N(t);const{modelColumns:n}=t;return n==null?null:e!=null?n.get(e):null}getModelRow(e){const{metrics:t}=this.state;N(t);const{modelRows:n}=t;return n==null?null:e!=null?n.get(e):null}getTheme(){const{model:e,theme:t}=this.props;return this.getCachedTheme(t,(Xe(e)&&e.isEditable)??!1,e.floatingTopRowCount+e.floatingBottomRowCount)}getVisibleColumn(e){const{movedColumns:t}=this.state;return _.getVisibleIndex(e,t)}applyInputFilters(e,t=!1){const{model:n}=this.props,{advancedFilters:s,quickFilters:i}=this.state,o=t?new Map:new Map(s),l=t?new Map:new Map(i);let a=t&&s.size>0;e.forEach(({name:d,type:h,value:u})=>{const m=n.columns.findIndex(({name:g,type:p})=>g===d&&p===h);m>=0?(a=o.delete(m)||a,a=this.applyQuickFilter(m,u,l)||a):me.error("Unable to find column for inputFilter",d,h,u)}),a&&this.setState({quickFilters:l,advancedFilters:o})}applyQuickFilter(e,t,n){const{model:s}=this.props,{formatter:i}=s,o=s.columns[e];if(t!=null&&`${t}`.trim().length>0){const l=n.get(e);if(l!=null){const{text:a}=l;if(a===t)return me.debug2("Ignoring change to existing filter"),!1}return n.set(e,{text:t,filter:Hn.makeQuickFilter(o,t,i.timeZone)}),!0}return n.delete(e)}setAdvancedFilterMap(e){this.setState({advancedFilters:e})}setAdvancedFilter(e,t,n){me.debug("Setting advanced filter",e,t),this.startLoading("Filtering...",!0),this.setState(({advancedFilters:s})=>{const i=new Map(s);return t==null?i.delete(e):i.set(e,{filter:t,options:n}),{advancedFilters:i}})}setQuickFilter(e,t,n){me.debug("Setting quick filter",e,t,n),this.startLoading("Filtering...",!0),this.setState(({quickFilters:s})=>{const i=new Map(s);return i.set(e,{filter:t,text:n}),{quickFilters:i}})}setFilterMap(e){me.debug("setFilterMap",e);const{advancedSettings:t}=this.props;(t.get(xi.LINK_CHANGE_CLEARS_ALL_FILTERS)??!1)&&this.clearAllFilters();const{model:s}=this.props;e.forEach(({columnType:i,filterList:o},l)=>{const a=s.columns.find(u=>u.name===l&&u.type===i);if(a==null)return;const d=s.getColumnIndexByName(a.name);N(d);const h=Se.combineFiltersFromList(i,o);if(h.length===0)this.removeQuickFilter(d);else{const{formatter:u}=s;this.setQuickFilter(d,Hn.makeQuickFilter(a,h,u.timeZone),`${h}`)}})}removeColumnFilter(e){this.startLoading("Filtering...",!0),this.setState(({advancedFilters:t,quickFilters:n})=>{const s=t?new Map(t):new Map,i=n?new Map(n):new Map;return i.delete(e),s.delete(e),{quickFilters:i,advancedFilters:s}})}removeQuickFilter(e){this.startLoading("Clearing Filter...",!0),this.setState(({quickFilters:t})=>{const n=new Map(t);return n.delete(e),{quickFilters:n}})}clearAllFilters(){me.debug("Clearing all filters");const{advancedFilters:e,quickFilters:t,searchFilter:n}=this.state;t.size===0&&e.size===0&&n===null||(this.clearGridInputField(),this.startLoading("Clearing Filters...",!0),this.setState({quickFilters:new Map,advancedFilters:new Map,searchValue:"",searchFilter:void 0}))}clearCrossColumSearch(){me.debug("Clearing cross-column search"),this.setState({searchValue:"",searchFilter:void 0})}clearGridInputField(){this.filterInputRef.current!=null&&this.filterInputRef.current.setValue("")}rebuildFilters(){me.debug("Rebuilding filters");const{model:e}=this.props,{advancedFilters:t,quickFilters:n}=this.state,{columns:s,formatter:i}=e,o=new Map,l=new Map;t.forEach((a,d)=>{const{options:h}=a,u=s[d],m=F.makeAdvancedFilter(u,h,i.timeZone);o.set(d,{options:h,filter:m})}),n.forEach((a,d)=>{const{text:h}=a,u=s[d];l.set(d,{text:h,filter:Hn.makeQuickFilter(u,h,i.timeZone)})}),this.startLoading("Rebuilding filters...",!0),this.setState({quickFilters:l,advancedFilters:o})}setFilters({quickFilters:e,advancedFilters:t}){this.setState({quickFilters:e,advancedFilters:t})}updateFormatterSettings(e,t=!0){const n=$n.getColumnFormats(e),s=$n.getDateTimeFormatterOptions(e),i=e?.defaultDecimalFormatOptions??{},o=e?.defaultIntegerFormatOptions??{},l=e?.truncateNumbersWithPound??!1,a=!st(this.globalColumnFormats,n),d=!st(this.dateTimeFormatterOptions,s),h=!st(this.decimalFormatOptions,e?.defaultDecimalFormatOptions),u=!st(this.integerFormatOptions,o),m=this.truncateNumbersWithPound!==l;(a||d||h||u||m)&&(this.globalColumnFormats=n,this.dateTimeFormatterOptions=s,this.decimalFormatOptions=i,this.integerFormatOptions=o,this.truncateNumbersWithPound=l,this.updateFormatter({},t),d&&t&&this.rebuildFilters())}getAlwaysFetchColumns=Re((e,t,n,s,i,o)=>{const l=[];for(let d=0;d<s;d+=1)l.push(t[_.getModelIndex(d,n)].name);for(let d=0;d<i;d+=1)l.push(t[_.getModelIndex(t.length-1-d,n)].name);if(o)for(let d=o[0];d<=o[1];d+=1)l.push(t[_.getModelIndex(d,n)].name);const a=new Set([...e,...l]);return Object.freeze([...a])});updateFormatter(e,t=!0){const{customColumnFormatMap:n}=this.state,s={customColumnFormatMap:n,...e},i=[...this.globalColumnFormats??[],...s.customColumnFormatMap.values()],o=new gn(i,this.dateTimeFormatterOptions,this.decimalFormatOptions,this.integerFormatOptions,this.truncateNumbersWithPound);me.debug("updateFormatter",this.globalColumnFormats,i),this.setState({...s,formatter:o},()=>{t&&this.grid&&this.grid.forceUpdate()})}initFormatter(){const{settings:e}=this.props;this.updateFormatterSettings(e)}initState(){const{applyInputFiltersOnInit:e,inputFilters:t,sorts:n,model:s,reverseType:i,customColumns:o,searchValue:l,selectedSearchColumns:a,invertSearchColumns:d}=this.props,h=a??[],u=Ko.createSearchFilter(l,h,s.columns,d);if(e){const m=t.filter(g=>g.value!=null);this.applyInputFilters(m)}this.setState({sorts:n,reverseType:i,customColumns:o,isReady:!0,searchFilter:u}),this.initFormatter()}async loadPartitionsTable(e){const{model:t}=this.props;this.setState({isSelectingPartition:!0});try{const n=await this.pending.add(t.valuesTable(e),l=>l.close()),s=n.columns[0],i=s.sort().desc();n.applySort([i]),n.setViewport(0,0,[s]);const o=await this.pending.add(n.getViewportData());if(o.rows.length>0){const a=o.rows[0].get(s);this.updatePartition(a,e),this.setState({isSelectingPartition:!0})}else me.info("Table does not have any data, just fetching all"),this.setState({isSelectingPartition:!1}),this.handlePartitionFetchAll();this.setState({partitionTable:n,partitionColumn:e},()=>{this.initState()})}catch(n){this.handleTableLoadError(n)}}updatePartition(e,t){const s=[t.filter().eq(I.FilterValue.ofString(e))];this.setState({partition:e,partitionFilters:s})}copyCell(e,t,n=!1){const{canCopy:s}=this.props;if(s){const i=String(this.getValueForCell(e,t,n));ho(i).catch(o=>me.error("Unable to copy cell",o))}else me.error("Attempted to copyCell for user without copy permission.")}copyRanges(e,t=!1,n=!0,s){const{model:i,canCopy:o}=this.props,{metricCalculator:l,movedColumns:a}=this.state,d=l.getUserColumnWidths();if(o){const h={ranges:te.boundedRanges(e,i.columnCount,i.rowCount),includeHeaders:t,formatValues:n,movedColumns:a,userColumnWidths:d,error:s};this.setState({copyOperation:h})}else me.error("Attempted copyRanges for user without copy permission.")}startLoading(e,t=!1){this.setState({loadingText:e});const n=this.getTheme();if(t&&this.grid&&(this.grid.clearSelectedRanges(),this.grid.setViewState({top:0},!0)),this.loadingScrimStartTime==null){const{minScrimTransitionTime:s,maxScrimTransitionTime:i}=n;N(s),N(i);const o=this.gridWrapper?.getBoundingClientRect().height??0,l=Math.max(s,Math.min(o/2,i));this.loadingScrimStartTime=Date.now(),this.loadingScrimFinishTime=this.loadingScrimStartTime+l,this.setState({loadingScrimProgress:0}),this.loadingTimer=setTimeout(()=>{this.setState({loadingSpinnerShown:!0})},Hn.loadingSpinnerDelay)}}stopLoading(){this.loadingScrimStartTime=void 0,this.loadingScrimFinishTime=void 0,this.setState({loadingText:null,loadingScrimProgress:null,loadingSpinnerShown:!1}),this.loadingTimer!=null&&(clearTimeout(this.loadingTimer),this.loadingTimer=void 0)}rollback(){if(this.lastLoadedConfig){me.debug("loading last loading config",this.lastLoadedConfig);const{advancedFilters:e,aggregationSettings:t,customColumns:n,quickFilters:s,reverseType:i,rollupConfig:o,searchFilter:l,selectDistinctColumns:a,sorts:d}=this.lastLoadedConfig;this.lastLoadedConfig=null,this.setState({advancedFilters:e,aggregationSettings:t,customColumns:n,quickFilters:s,reverseType:i,rollupConfig:o,searchFilter:l,selectDistinctColumns:a,sorts:d})}else me.debug("remove all sorts, filters, and custom columns"),this.setState({advancedFilters:new Map,aggregationSettings:hc,customColumns:[],quickFilters:new Map,reverseType:F.REVERSE_TYPE.NONE,rollupConfig:void 0,selectDistinctColumns:[],sorts:[]})}canRollback(){return this.lastLoadedConfig!=null||!uc(this.state)}startListening(e){e.addEventListener(Ce.EVENT.UPDATED,this.handleUpdate),e.addEventListener(Ce.EVENT.REQUEST_FAILED,this.handleRequestFailed),e.addEventListener(Ce.EVENT.COLUMNS_CHANGED,this.handleCustomColumnsChanged),e.addEventListener(Ce.EVENT.PENDING_DATA_UPDATED,this.handlePendingDataUpdated)}stopListening(e){e.removeEventListener(Ce.EVENT.UPDATED,this.handleUpdate),e.removeEventListener(Ce.EVENT.REQUEST_FAILED,this.handleRequestFailed),e.removeEventListener(Ce.EVENT.COLUMNS_CHANGED,this.handleCustomColumnsChanged),e.removeEventListener(Ce.EVENT.PENDING_DATA_UPDATED,this.handlePendingDataUpdated)}focus(){this.grid?.focus()}focusFilterBar(e){const{movedColumns:t}=this.state,{model:n}=this.props,{columnCount:s}=n,i=_.getModelIndex(e,t);if(e==null||e<0||s<=e||!n.isFilterable(i)){this.setState({focusedFilterBarColumn:null});return}const{metricCalculator:o,metrics:l}=this.state;N(l);const{left:a,rightVisible:d,lastLeft:h}=l;if(e<a)this.grid?.setViewState({left:e},!0);else if(d<e){const u=this.grid?.getMetricState();N(u);const m=o.getLastLeft(u,e,o.getVisibleWidth(u));this.grid?.setViewState({left:Math.min(m,h),leftOffset:0},!0)}this.lastFocusedFilterBarColumn=e,this.setState({focusedFilterBarColumn:e,isFilterBarShown:!0})}hideColumnByVisibleIndex(e){const{metricCalculator:t,movedColumns:n}=this.state;t.setColumnWidth(_.getModelIndex(e,n),0),this.grid?.forceUpdate()}freezeColumnByColumnName(e){const{frozenColumns:t,movedColumns:n}=this.state,{model:s}=this.props;me.debug2("freezing column",e);const i=t==null?new Set(s.frozenColumns):new Set(t);i.add(e);const o=s.getColumnIndexByName(e);N(o);const l=_.getVisibleIndex(o,n),a=_.moveItem(l,i.size-1,n);this.setState({frozenColumns:[...i],movedColumns:a})}unFreezeColumnByColumnName(e){const{frozenColumns:t,movedColumns:n}=this.state,{model:s}=this.props;me.debug2("unfreezing column",e);const i=t==null?new Set(s.frozenColumns):new Set(t);i.delete(e);const o=s.getColumnIndexByName(e);N(o);const l=_.getVisibleIndex(o,n),a=_.moveItem(l,i.size+s.frontColumns.length,n);this.setState({frozenColumns:[...i],movedColumns:a})}handleColumnVisibilityChanged(e,t){const{metricCalculator:n,metrics:s}=this.state;N(s),t?e.forEach(i=>{const o=n.initialColumnWidths.get(i),l=k(s.calculatedColumnWidths,i);o!==l?n.setColumnWidth(i,l):n.resetColumnWidth(i)}):e.forEach(i=>{n.setColumnWidth(i,0)}),this.grid?.forceUpdate()}handleColumnVisibilityReset(){const{metricCalculator:e,metrics:t}=this.state,{model:n}=this.props;N(t);for(let s=0;s<t.columnCount;s+=1)e.resetColumnWidth(s);this.handleMovedColumnsChanged(n.initialMovedColumns),this.handleHeaderGroupsChanged(n.initialColumnHeaderGroups),this.setState({frozenColumns:n.layoutHints?.frozenColumns??[]})}handleCrossColumnSearch(e,t,n){const{model:s}=this.props;this.updateSearchFilter(e,t,s.columns,n),this.setState({searchValue:e,selectedSearchColumns:t,invertSearchColumns:n})}updateSearchFilter=Ye((e,t,n,s)=>{const i=Ko.createSearchFilter(e,t,n,s);this.setState({searchFilter:i})},XE);handleAnimationLoop(){this.grid?.updateCanvas(),this.isAnimating&&(this.animationFrame=requestAnimationFrame(this.handleAnimationLoop))}handleAnimationStart(){me.debug2("handleAnimationStart"),this.isAnimating=!0,this.animationFrame=requestAnimationFrame(this.handleAnimationLoop)}handleAnimationEnd(){me.debug2("handleAnimationEnd"),this.isAnimating=!1}handlePartitionAppend(e){const{onPartitionAppend:t}=this.props,{partitionColumn:n}=this.state;n!=null&&t(n,e)}handlePartitionChange(e){const{partitionColumn:t}=this.state;t!=null&&this.updatePartition(e,t)}handlePartitionFetchAll(){this.setState({partitionFilters:[],isSelectingPartition:!1})}handlePartitionDone(){this.setState({isSelectingPartition:!1})}handleTableLoadError(e){if(ye.isCanceled(e))return;me.error(e);const{onError:t}=this.props;t(e)}showAllColumns(){const{metricCalculator:e}=this.state,n=[...e.getUserColumnWidths().entries()];for(let s=0;s<n.length;s+=1){const[i,o]=n[s];o===0&&e.resetColumnWidth(i)}this.grid?.forceUpdate()}toggleSort(e,t){me.info("Toggling sort for column",e);const{model:n}=this.props,{sorts:s}=this.state,i=this.getModelColumn(e);N(i);const o=F.toggleSortForColumn(s,n.columns,i,t);this.updateSorts(o)}updateSorts(e){this.startLoading("Sorting..."),this.setState({sorts:e}),this.grid?.forceUpdate()}sortColumn(e,t=F.sortDirection.none,n=!1,s=!1){N(e);const{model:i}=this.props,o=F.sortColumn(i.sort,i.columns,e,t,n,s);this.startLoading("Sorting..."),this.setState({sorts:o}),this.grid?.forceUpdate()}reverse(e){this.startLoading("Reversing..."),this.setState({reverseType:e}),this.grid?.forceUpdate()}isReversible(){const{model:e}=this.props;return e.isReversible}toggleFilterBar(e=this.lastFocusedFilterBarColumn){let{isFilterBarShown:t}=this.state;if(t=!t,this.setState({isFilterBarShown:t}),t)if(e!=null)this.focusFilterBar(e);else{let n=0;const{model:s}=this.props,{columnCount:i}=s;for(let o=0;o<i;o+=1){const l=this.getModelColumn(o);if(l!=null){const a=s.columns[l];if(a!=null&&F.isTextType(a.type)){n=o;break}}}this.focusFilterBar(n)}else this.grid?.focus()}isTableSearchAvailable(){const{model:e,canToggleSearch:t}=this.props,n=e?.layoutHints?.searchDisplayMode;return n===I.SearchDisplayMode?.SEARCH_DISPLAY_HIDE?!1:n===I.SearchDisplayMode?.SEARCH_DISPLAY_SHOW?!0:t}toggleSearchBar(){const{showSearchBar:e}=this.state;if(!this.isTableSearchAvailable())return;const t=!e;this.setState({showSearchBar:t},()=>{t&&this.crossColumnRef?.current?this.crossColumnRef?.current.focus():this.grid?.focus()})}toggleGotoRow(e="",t="",n=""){const{isGotoShown:s}=this.state;if(e||t){this.setState({isGotoShown:!0,gotoRow:e,gotoValue:t,gotoValueSelectedColumnName:n,gotoRowError:"",gotoValueError:""}),this.focusRowInGrid(e);return}const i=this.grid?.state.cursorRow,o=this.grid?.state.cursorColumn;if(i==null||o==null){this.setState({isGotoShown:!s,gotoRow:"",gotoValue:"",gotoRowError:"",gotoValueError:""});return}const{model:l}=this.props,{name:a,type:d}=l.columns[o],h=l.valueForCell(o,i),u=Se.convertValueToText(h,d);this.setState({isGotoShown:!s,gotoRow:`${i}`,gotoValue:u,gotoValueSelectedColumnName:a,gotoRowError:"",gotoValueError:""})}async commitPending(){const{model:e}=this.props;if(!Xe(e)||!e.isEditable)throw new Error("Cannot save, table is not editable");const{pendingSavePromise:t}=this.state;if(t!=null)throw new Error("Save already in progress");const n=document?.activeElement?.classList.contains("grid-cell-input-field");if(n!=null&&n){if(document.activeElement!=null&&document.activeElement.classList.contains("error"))throw new vi("Current input is invalid");this.grid?.focus()}const s=this.pending.add(e.commitPending()).then(()=>{this.setState({pendingSaveError:null,pendingSavePromise:null})}).catch(i=>{ye.isCanceled(i)||this.setState({pendingSaveError:i,pendingSavePromise:null})});return this.setState({pendingSavePromise:s}),s}async discardPending(){const{pendingSavePromise:e}=this.state;if(e!=null)throw new Error("Cannot cancel a save in progress");this.setState({pendingSavePromise:null,pendingSaveError:null,pendingDataMap:new Map,pendingDataErrors:new Map})}selectColumn(e){const{onColumnSelected:t}=this.props;t(e)}selectData(e,t){const{model:n}=this.props,{columns:s,groupedColumns:i}=n,o={};for(let a=0;a<s.length;a+=1){const d=s[a],{name:h,type:u}=d,m=n.valueForCell(a,t),g=n.textForCell(a,t),p=this.getVisibleColumn(a),C=je(n)&&n.isRowExpandable(t),f=i.find(b=>b.name===h)!=null;o[h]={value:m,text:g,type:u,isGrouped:f,isExpandable:C,visibleIndex:p}}const{onDataSelected:l}=this.props;l(t,o)}handleAdvancedFilterChange(e,t,n){const{model:s}=this.props,i=s.getColumnIndexByName(e.name);N(i),this.setAdvancedFilter(i,t,n)}handleAdvancedFilterSortChange(e,t,n=!1){const{model:s}=this.props,i=s.getColumnIndexByName(e.name);N(i);const o=s.columns[i].name,l=F.getSortForColumn(s.sort,o);let a=null;(l==null||l.direction!==t)&&(t===F.sortDirection.descending?a=e.sort().desc():a=e.sort().asc());const d=F.setSortForColumn(s.sort,o,a,n);me.info("Setting table sorts",d),this.startLoading("Sorting..."),this.setState({sorts:d}),this.grid?.forceUpdate()}handleAdvancedFilterDone(){this.grid?.focus()}handleAdvancedMenuOpened(e){this.setState({shownAdvancedFilter:e})}handleGotoRowOpened(){this.setState({isGotoShown:!0})}handleGotoRowClosed(){this.setState({isGotoShown:!1})}handleAdvancedMenuClosed(e){const{focusedFilterBarColumn:t,isFilterBarShown:n}=this.state;n&&t===e&&this.filterInputRef?.current!==null?(this.filterInputRef?.current.focus(),this.setState({shownAdvancedFilter:null})):this.setState({focusedFilterBarColumn:null,shownAdvancedFilter:null})}handleCancel(){this.rollback()}handleChartChange(){}handleChartCreate(e){const{model:t,onCreateChart:n}=this.props;n(e,t)}handleGridError(e){me.warn("Grid Error",e),this.setState({toastMessage:r.jsx("div",{className:"error-message",children:`${e}`})})}handleFilterBarChange(e){this.startLoading("Filtering...",!0),this.setState(({focusedFilterBarColumn:t,quickFilters:n})=>{const s=new Map(n);if(t!=null){const i=this.getModelColumn(t);N(i),this.applyQuickFilter(i,e,s)}return{quickFilters:s}})}handleFilterBarDone(e=!0,t=!0){e&&this.grid?.focus(),t&&this.setState({focusedFilterBarColumn:null})}handleFilterBarTab(e){const{focusedFilterBarColumn:t}=this.state;N(t),e?this.focusFilterBar(t-1):this.focusFilterBar(t+1)}handleFormatSelection(e,t){const{model:n}=this.props,s=n.columns[e],{customColumnFormatMap:i}=this.state,o=new Map(i);if(t!=null){const l=F.getNormalizedType(s.type);N(l);const a=gn.makeColumnFormattingRule(l,s.name,t);o.set(s.name,a)}else o.delete(s.name);this.updateFormatter({customColumnFormatMap:o})}handleMenu(e){e.stopPropagation(),this.setState({isMenuShown:!0})}handleMenuClose(){this.setState({isMenuShown:!1,openOptions:[]})}handleMenuBack(){this.setState(({openOptions:e})=>{const t=[...e];return t.pop(),{openOptions:t}})}handleMenuSelect(e){this.setState(({openOptions:t})=>({openOptions:[...t,e]}))}handleRequestFailed(e){const t=e;if(me.error("request failed:",t.detail),this.stopLoading(),this.canRollback())this.startLoading("Rolling back changes...",!0),this.rollback();else{me.error("Table failed and unable to rollback");const{onError:n}=this.props;n(new Error(`Error displaying table: ${t.detail}`))}}handleUpdate(){this.stopLoading(),me.debug2("Received model update");const{advancedFilters:e,aggregationSettings:t,customColumns:n,quickFilters:s,reverseType:i,rollupConfig:o,searchFilter:l,selectDistinctColumns:a,sorts:d}=this.state,h={advancedFilters:e,aggregationSettings:t,customColumns:n,quickFilters:s,reverseType:i,rollupConfig:o,searchFilter:l,selectDistinctColumns:a,sorts:d};uc(h)?this.lastLoadedConfig=null:this.lastLoadedConfig=h,this.grid?.forceUpdate()}handleViewChanged(e){const{model:t}=this.props,{selectionEndRow:n=0}=this.grid?.state??{};let s=0;if(Xe(t)&&t.isEditable){N(e);const{bottomViewport:i}=e,o=t.rowCount-t.floatingBottomRowCount;n===o-1?s=t.pendingRowCount+1:n===o-2?s=t.pendingRowCount:s=Math.max(0,i-(t.rowCount-t.pendingRowCount)-t.floatingTopRowCount-t.floatingBottomRowCount-1)}this.setState({metrics:e,pendingRowCount:s})}handleSelectionChanged(e){N(e);const{onSelectionChanged:t}=this.props,{copyOperation:n}=this.state;this.setState({selectedRanges:e}),n!=null&&this.setState({copyOperation:null}),t(e)}handleMovedColumnsChanged(e,t){this.setState({movedColumns:e},t)}handleHeaderGroupsChanged(e){const{model:t}=this.props;this.setState({columnHeaderGroups:Se.parseColumnHeaderGroups(t,e).groups},()=>this.grid?.forceUpdate())}handleTooltipRef(e){e?.startTimer(),this.tooltip=e}handleConditionalFormatsChange(e){me.debug("Updated conditional formats",e),this.setState({conditionalFormats:e})}handleConditionalFormatCreate(){me.debug("Create new conditional format");const{openOptions:e,conditionalFormats:t}=this.state;this.setState({openOptions:[...e,{type:Ne.CONDITIONAL_FORMATTING_EDIT,title:"Create Formatting Rule"}],conditionalFormatEditIndex:t.length,conditionalFormatPreview:void 0})}handleConditionalFormatEdit(e){me.debug("Edit conditional format",e);const{openOptions:t,conditionalFormats:n}=this.state;this.setState({openOptions:[...t,{type:Ne.CONDITIONAL_FORMATTING_EDIT,title:"Edit Formatting Rule"}],conditionalFormatEditIndex:e,conditionalFormatPreview:{...n[e]}})}handleConditionalFormatEditorUpdate=Ye(e=>{this.setState({conditionalFormatPreview:e})},QE);handleConditionalFormatEditorSave(e){me.debug("Save conditional format changes",e),this.setState(t=>{if(t.conditionalFormatEditIndex===null)return me.debug("Invalid format index"),null;const n=[...t.conditionalFormats];return n[t.conditionalFormatEditIndex]=e,{conditionalFormats:n}},()=>{this.handleMenuBack()})}handleConditionalFormatEditorCancel(){this.handleMenuBack(),this.setState({conditionalFormatEditIndex:null})}handleUpdateCustomColumns(e){me.info("handleUpdateCustomColumns:",e);const{model:t}=this.props,{movedColumns:n,sorts:s,quickFilters:i,advancedFilters:o,selectDistinctColumns:l}=this.state,{columns:a}=t,d=t.customColumns.map(u=>`${u}`),h=Se.getRemovedCustomColumnNames(d,e);if(h.length>0){const u=Se.removeSortsInColumns(s,h),m=Se.removeFiltersInColumns(a,i,h),g=Se.removeFiltersInColumns(a,o,h),p=Se.removeColumnFromMovedColumns(a,n,h),C=Se.removeColumnsFromSelectDistinctColumns(l,h);u.length!==s.length&&(me.debug("removing sorts from removed custom columns..."),this.setState({sorts:u})),(m.size!==i.size||g.size!==o.size)&&(me.debug("removing filters from removed custom columns..."),this.setState({quickFilters:m,advancedFilters:g})),st(n,p)||(me.debug("change moved columns for removed custom columns",p),this.setState({movedColumns:p})),st(l,C)||(me.debug("change selectDistinct columns for removed custom columns",p),this.setState({selectDistinctColumns:C}))}this.setState({customColumns:e}),e.length>0&&this.startLoading("Applying custom columns...")}handleCustomColumnsChanged(){me.debug("custom columns changed");const{isReady:e}=this.state;e?(this.stopLoading(),this.grid?.forceUpdate()):this.initState()}handlePendingCommitClicked(){return this.commitPending()}handlePendingDiscardClicked(){return this.discardPending()}handlePendingDataUpdated(){me.debug("pending data updated");const{model:e}=this.props,{pendingDataMap:t,pendingDataErrors:n}=e;this.setState({pendingDataMap:t,pendingDataErrors:n,pendingSaveError:null}),this.grid?.forceUpdate()}handleAggregationsChange(e){me.debug("handleAggregationsChange",e),this.startLoading(`Aggregating ${e.aggregations.map(t=>t.operation).join(", ")}...`),this.setState({aggregationSettings:e})}handleAggregationChange(e){me.debug("handleAggregationChange",e),this.startLoading(`Aggregating ${e.operation}...`),this.setState(({aggregationSettings:t})=>({selectedAggregation:e,aggregationSettings:{...t,aggregations:t.aggregations.map(n=>n.operation===e.operation?e:n)}}))}handleAggregationEdit(e){me.debug("handleAggregationEdit",e);const{openOptions:t}=this.state;this.setState({openOptions:[...t,{type:Ne.AGGREGATION_EDIT,title:`Edit Columns to ${e.operation}`}],selectedAggregation:e})}handleRollupChange(e){me.info("Rollup change",e),this.resetGridViewState(),this.showAllColumns(),this.clearAllFilters(),this.startLoading(`Grouping by columns ${e?.columns?.join(", ")??""}...`),this.setState({rollupConfig:e,movedColumns:[],frozenColumns:[],sorts:[],reverseType:F.REVERSE_TYPE.NONE,selectDistinctColumns:[]})}handleSelectDistinctChanged(e){me.debug("SelectDistinct change",e),this.resetGridViewState(),this.showAllColumns(),this.clearAllFilters(),this.startLoading(`Selecting distinct values in ${e.length>0?e.join(", "):""}...`),this.setState({selectDistinctColumns:e,movedColumns:[],sorts:[],reverseType:F.REVERSE_TYPE.NONE})}handleDownloadTableStart(){const{canDownloadCsv:e}=this.props;e?this.setState({isTableDownloading:!0,tableDownloadProgress:0,tableDownloadEstimatedTime:null,tableDownloadStatus:Ms.DOWNLOAD_STATUS.INITIATING}):me.error("Attempted to handleDownloadTableStart for user without download CSV permission.")}handleDownloadTable(e,t,n,s,i,o,l){const{canDownloadCsv:a}=this.props;a?(me.info("start table downloading",e,t,n,s,i,o,l),this.setState(()=>(this.tableSaver&&this.tableSaver.startDownload(e,t,n,s,i,o,l),{tableDownloadStatus:Ms.DOWNLOAD_STATUS.DOWNLOADING}))):me.error("Attempted to handleDownloadTable for user without download CSV permission.")}async seekRow(e,t=!1){const{gotoValueSelectedColumnName:n,gotoValueSelectedFilter:s}=this.state,{model:i}=this.props;if(!i.isSeekRowAvailable||e==="")return;const o=Se.getColumnByName(i.columns,n);if(o===void 0)return;let l=this.grid?.state.cursorRow;l==null&&(l=0);const a=s===be.contains,d=s===be.eq||s===be.eqIgnoreCase;try{const{formatter:h}=i,u=F.getNormalizedType(o.type);let m;switch(u){case F.dataType.CHAR:case F.dataType.STRING:{m=await i.seekRow(l,o,I.ValueType.STRING,e,d,a,t??!1);break}case F.dataType.DATETIME:{const[g]=Xs.parseDateRange(e,h.timeZone);m=await i.seekRow(l,o,I.ValueType.DATETIME,g,void 0,void 0,t??!1);break}case F.dataType.DECIMAL:case F.dataType.INT:{if(!F.isBigDecimalType(o.type)&&!F.isBigIntegerType(o.type)){let g=parseInt(e,10);e==="-Infinity"?g=Number.NEGATIVE_INFINITY:e==="Infinity"&&(g=Number.POSITIVE_INFINITY),m=await i.seekRow(l,o,I.ValueType.NUMBER,g,void 0,void 0,t??!1)}else m=await i.seekRow(l,o,I.ValueType.STRING,e,void 0,void 0,t??!1);break}default:m=await i.seekRow(l,o,I.ValueType.STRING,F.makeValue(o.type,e,h.timeZone),void 0,void 0,t??!1)}this.grid?.setFocusRow(m),this.setState({gotoValueError:""})}catch{this.setState({gotoValueError:"invalid input"})}}handleCancelDownloadTable(){this.tableSaver?.cancelDownload(),this.setState({isTableDownloading:!1})}handleDownloadProgressUpdate=vs((e,t)=>{const{tableDownloadStatus:n}=this.state;n===Ms.DOWNLOAD_STATUS.DOWNLOADING&&this.setState({tableDownloadProgress:e,tableDownloadEstimatedTime:t})},qE);handleDownloadCompleted(){this.setState({isTableDownloading:!1,tableDownloadProgress:100,tableDownloadStatus:Ms.DOWNLOAD_STATUS.FINISHED})}handleDownloadCanceled(){this.setState({isTableDownloading:!1,tableDownloadProgress:0,tableDownloadStatus:Ms.DOWNLOAD_STATUS.CANCELED})}deleteRanges(e){const{model:t}=this.props;this.pending.add(t.delete(e)).catch(n=>{ye.isCanceled(n)||me.error("Unable to delete ranges",e,n)})}resetColumnSelection(){if(this.grid==null)return;const{isSelectingColumn:e}=this.props;if(e){const{columnAllowedCursor:t}=this.props;this.grid.setState({cursor:t})}else this.grid.setState({cursor:null}),this.setState({hoverSelectColumn:null})}resetGridViewState(e=!0){this.grid&&(this.grid.clearSelectedRanges(),this.grid.setViewState({left:0,top:0,topOffset:0,leftOffset:0},e))}sendStateChange(){if(!this.grid)return;const{state:e}=this,{state:t}=this.grid,{onStateChange:n}=this.props;n(e,t)}handleOverflowClose(){this.setState({showOverflowModal:!1})}getColumnBoundingRect(){const{metrics:e,shownColumnTooltip:t}=this.state;N(e),N(t);const n=this.gridWrapper?.getBoundingClientRect(),s=20;N(n);const{columnHeaderHeight:i,allColumnXs:o,allColumnWidths:l,width:a,columnHeaderMaxDepth:d}=e,h=o.get(t),u=l.get(t);N(h),N(u);const m=n.left+Oe(h+u/2,s,a-s);return{top:n.top+(d-1)*i,left:n.left+Oe(h+u/2,s,a-s),bottom:n.top+d*i,right:n.left+Oe(h+u/2,s,a-s)+1,width:1,height:i,x:m,y:n.top,toJSON:()=>{throw new Error("not implemented")}}}getOverflowButtonTooltip=Re(e=>{if(e==null)return null;const t={position:"absolute",...e,pointerEvents:"none"},n={placement:"left",modifiers:{flip:{behavior:["left","right"]}}};return r.jsx("div",{style:t,children:r.jsx(ot,{options:n,ref:this.handleTooltipRef,children:"View full contents"},Date.now())})});getExpandCellTooltip=Re(e=>{if(e==null)return null;const{expandTooltipDisplayValue:t}=this.state,n={position:"absolute",...e,pointerEvents:"none"},s={placement:"bottom-start"};return r.jsx("div",{style:n,children:r.jsx(ot,{options:s,ref:this.handleTooltipRef,children:r.jsxs("div",{style:{textAlign:"left"},children:["Click to ",t," row",r.jsx("br",{}),Ts.isMacPlatform()?"⌘":"Ctrl+","Click to expand row and all children"]})},Date.now())})});getLinkHoverTooltip=Re(e=>{if(e==null)return null;const{linkHoverDisplayValue:t}=this.state,n={position:"absolute",...e,pointerEvents:"none"},s={placement:"bottom"};return r.jsx("div",{style:n,children:r.jsx(ot,{options:s,ref:this.handleTooltipRef,children:r.jsxs("div",{className:"link-hover-tooltip",children:[t," - Click once to follow.",r.jsx("br",{}),"Click and hold to select this cell."]})})})});handleGotoRowSelectedRowNumberSubmit(){const{gotoRow:e}=this.state;this.focusRowInGrid(e)}focusRowInGrid(e){const{model:t}=this.props,{rowCount:n}=t;if(this.setState({gotoRow:e}),e===""){this.setState({gotoRowError:"",gotoValueError:""});return}const s=parseInt(e,10);s>n||s<-n?this.setState({gotoRowError:"Invalid row index"}):s===0?(this.setState({gotoRowError:"",gotoValueError:""}),this.grid?.setFocusRow(0)):s<0?(this.setState({gotoRowError:"",gotoValueError:""}),this.grid?.setFocusRow(s+n)):(this.grid?.setFocusRow(s-1),this.setState({gotoRowError:"",gotoValueError:""}))}handleGotoRowSelectedRowNumberChanged(e){const t=e.target.value;this.focusRowInGrid(t)}getColumnTooltip(e,t,n){const{columnHeaderHeight:s,columnHeaderMaxDepth:i,allColumnXs:o,allColumnWidths:l,width:a}=t,d=o.get(e),h=l.get(e);if(d==null||h==null)return null;const u=Math.max(0,d);let m=h;d+h>a?m=a-d:d<0&&(m=h-Math.abs(d));const g={position:"absolute",top:(i-1)*s,left:u,width:m,height:s,pointerEvents:"none"},p={clientWidth:1,clientHeight:s,getBoundingClientRect:this.getColumnBoundingRect},C={placement:"bottom",modifiers:{flip:{behavior:["bottom","top"]}}},f=this.getModelColumn(e);if(f==null)return null;const b=n.columns[f];return b==null?null:r.jsx("div",{style:g,children:r.jsx(ot,{timeout:400,interactive:!0,options:C,ref:this.handleTooltipRef,referenceObject:p,onExited:()=>{this.setState({shownColumnTooltip:null})},children:r.jsx(aT,{model:n,column:b,onStatistics:()=>{this.tooltip?.update()}})},b.name)})}handleGotoValueSelectedColumnNameChanged(e){const{model:t}=this.props,n=this.grid?.state.cursorRow;if(n!=null){const s=t.getColumnIndexByName(e),i=Se.getColumnByName(t.columns,e);if(s==null||i==null)return;const o=t.valueForCell(s,n),l=Se.convertValueToText(o,i.type);this.setState({gotoValueSelectedColumnName:e,gotoValue:l,gotoValueError:""})}this.setState({gotoValueSelectedColumnName:e,gotoValueError:""})}handleGotoValueSelectedFilterChanged(e){this.setState({gotoValueSelectedFilter:e,gotoValueError:""})}handleGotoValueChanged=e=>{this.setState({gotoValue:e}),this.debouncedSeekRow(e)};debouncedSeekRow=Ye(e=>{this.seekRow(e)},ZE);handleGotoValueSubmitted(e){const{gotoValue:t}=this.state;this.seekRow(t,e)}render(){const{children:e,customFilters:t,getDownloadWorker:n,isSelectingColumn:s,isStuckToBottom:i,isStuckToRight:o,model:l,name:a,onlyFetchVisibleColumns:d,alwaysFetchColumns:h,advancedSettings:u,onAdvancedSettingsChange:m,canDownloadCsv:g,onCreateChart:p}=this.props,{metricCalculator:C,metrics:f,isFilterBarShown:b,isSelectingPartition:w,isMenuShown:S,isReady:T,copyOperation:y,focusedFilterBarColumn:E,loadingText:R,loadingScrimProgress:x,loadingSpinnerShown:D,keyHandlers:M,mouseHandlers:O,shownColumnTooltip:H,hoverAdvancedFilter:L,shownAdvancedFilter:V,hoverSelectColumn:U,quickFilters:j,advancedFilters:P,partition:Q,partitionFilters:$,partitionTable:J,partitionColumn:A,searchFilter:W,selectDistinctColumns:q,movedColumns:Z,movedRows:le,formatter:G,conditionalFormats:oe,conditionalFormatPreview:ue,conditionalFormatEditIndex:ae,sorts:he,reverseType:we,customColumns:He,selectedRanges:Fe,isTableDownloading:mt,tableDownloadStatus:et,tableDownloadProgress:De,tableDownloadEstimatedTime:gt,showSearchBar:lt,searchValue:vt,selectedSearchColumns:kt,invertSearchColumns:Cn,aggregationSettings:zt,selectedAggregation:So,rollupConfig:Rs,openOptions:Kt,pendingSavePromise:Xn,pendingSaveError:ti,pendingRowCount:ki,pendingDataErrors:ni,pendingDataMap:si,toastMessage:wo,frozenColumns:vo,columnHeaderGroups:Zn,showOverflowModal:xs,overflowText:la,overflowButtonTooltipProps:To,expandCellTooltipProps:Mi,linkHoverTooltipProps:Li,isGotoShown:Oi,gotoRow:Eo,gotoRowError:aa,gotoValueError:ra,gotoValueSelectedColumnName:da,gotoValue:ca,gotoValueSelectedFilter:ha}=this.state;if(!T)return null;const Ds=this.getTheme(),yo=this.getCachedFilter(t,j,P,$,W),ii=C.getUserColumnWidths(),Ro=this.getCachedStateOverride(U,b,s,x,j,P,he,we,Rs,S),Is=f?f.top:0,xo=f?f.bottomViewport:0;let Ai=null,_i=null;d&&(Ai=f?f.left:0,_i=f?f.right:0);const Do=f!=null&&f.width>0&&f.height>0,Io=(Rs?.columns?.length??0)>0;let Fo=null;const ua=f?Math.min(Math.max(Hn.minDebounce,Math.round(f.rowCount/200)),Hn.maxDebounce):Hn.maxDebounce;if(b&&E!=null&&f!=null){const{gridX:Ge,gridY:Ae,allColumnXs:Yt,allColumnWidths:Pi,width:oi}=f,Qn=Yt.get(E),Mt=Pi.get(E);if(Qn!=null&&Mt!=null){const xt=Ge+Qn,Nn=Ae-(Ds.filterBarHeight??0),Fs=Mt+1,Ns=(Ds.filterBarHeight??0)-1,_o={top:Nn,left:xt,minWidth:Math.min(Fs,oi-xt),height:Ns};let kn="",li=!0;const ks=this.getModelColumn(E);N(ks);const ai=j.get(ks),Jn=P.get(ks);ai!=null&&(kn=ai.text,li=ai.filter!=null);const ri=j.size!==0||P.size!==0;Fo=r.jsx(av,{ref:this.filterInputRef,style:_o,className:Y({error:!li,active:kn!==""||Jn!=null,"iris-grid-has-filter":ri}),isAdvancedFilterSet:Jn!=null,onAdvancedFiltersTriggered:()=>{this.setState({shownAdvancedFilter:E})},onChange:this.handleFilterBarChange,onDone:this.handleFilterBarDone,onTab:this.handleFilterBarTab,onContextMenu:this.grid?.handleContextMenu,debounceMs:ua,value:kn},E)}}let No=null;if(R!=null){const Ge=r.jsxs("div",{className:"iris-grid-loading-status",children:[r.jsx("div",{className:Y("iris-grid-loading-status-bar",{show:D}),children:R}),r.jsxs("button",{type:"button",onClick:this.handleCancel,className:Y("iris-grid-btn-cancel",{show:D}),children:[r.jsx(ee,{icon:uo,transform:"down-1"}),"Cancel"]})]}),Ae=f?f.gridY:0;No=r.jsx("div",{className:"iris-grid-loading",style:{top:Ae},children:Ge})}let ko=null;H!=null&&f&&(ko=this.getColumnTooltip(H,f,l),this.tooltip?.update());const Mo=[];if(f&&b){const{gridX:Ge,gridY:Ae,visibleColumns:Yt,allColumnXs:Pi,allColumnWidths:oi}=f,{filterBarHeight:Qn}=Ds;for(let Mt=0;Mt<Yt.length;Mt+=1){const xt=Yt[Mt],Nn=Pi.get(xt),Fs=oi.get(xt),Ns=this.getModelColumn(xt);if(Ns!=null&&l.isFilterable(Ns)&&Nn!=null&&Fs!=null&&Fs>0){const kn=Ge+Nn+Fs-24,ks={position:"absolute",top:Ae-(Qn??0)+2,left:kn},Jn=P.get(Ns)!=null,ri=xt===L||xt===E||Jn,ga=r.jsx("div",{className:Y("advanced-filter-button-container",{hidden:!ri}),style:ks,children:ri&&r.jsx(B,{kind:"ghost",className:Y("btn-link-icon advanced-filter-button",{"filter-set":Jn}),onClick:()=>{this.setState({shownAdvancedFilter:xt})},onContextMenu:nm=>{this.grid?.handleContextMenu(nm)},onMouseEnter:()=>{this.setState({hoverAdvancedFilter:xt})},onMouseLeave:()=>{this.setState({hoverAdvancedFilter:null})},children:r.jsxs("div",{className:"fa-layers",children:[r.jsx(ee,{icon:cr,className:"filter-solid"}),r.jsx(ee,{icon:dl,className:"filter-light"})]})})},xt);Mo.push(ga)}}}const Lo=[];if(f){const{gridX:Ge,visibleColumns:Ae,allColumnXs:Yt,allColumnWidths:Pi,columnHeaderHeight:oi}=f;for(let Qn=0;Qn<Ae.length;Qn+=1){const Mt=Ae[Qn],xt=Yt.get(Mt),Nn=Pi.get(Mt);if(xt!=null&&Nn!=null&&Nn>0){const Fs=Ge+xt,Ns=Ge+xt+Nn-20,_o=b?{position:"absolute",top:oi,left:Ns,width:20,height:Ds.filterBarHeight}:{position:"absolute",top:0,left:Fs,width:Nn,height:oi},kn=this.getModelColumn(Mt);if(kn!=null){const li=l.columns[kn],ks=P.get(kn),{options:ai}=ks||{},Jn=F.getSortForColumn(l.sort,li.name),ri=Jn?Jn.direction:null,ga=r.jsx("div",{className:"advanced-filter-menu-container",style:_o,children:r.jsx(Vl,{className:"advanced-filter-menu-popper",onEntered:this.getAdvancedMenuOpenedHandler(Mt),onExited:()=>{this.handleAdvancedMenuClosed(Mt)},isShown:V===Mt,interactive:!0,closeOnBlur:!0,options:{positionFixed:!0},children:this.getCachedAdvancedFilterMenuActions(l,li,ai,ri,G)})},Mt);Lo.push(ga)}}}}const Oo=this.getCachedOptionItems(p!==void 0&&l.isChartBuilderAvailable,l.isCustomColumnsAvailable,l.isFormatColumnsAvailable,l.isRollupAvailable,l.isTotalsAvailable||Io,l.isSelectDistinctAvailable,l.isExportAvailable,this.toggleFilterBarAction,this.toggleSearchBarAction,this.toggleGotoRowAction,b,lt,g,this.isTableSearchAvailable(),Oi,u.size>0),Ao=this.getCachedHiddenColumns(C,ii),ma=Kt.map(Ge=>{switch(Ge.type){case Ne.CHART_BUILDER:return r.jsx(TT,{model:l,onChange:this.handleChartChange,onSubmit:this.handleChartCreate},Ne.CHART_BUILDER);case Ne.VISIBILITY_ORDERING_BUILDER:return r.jsx(oE,{model:l,movedColumns:Z,hiddenColumns:Ao,columnHeaderGroups:Zn,onColumnVisibilityChanged:this.handleColumnVisibilityChanged,onReset:this.handleColumnVisibilityReset,onMovedColumnsChanged:this.handleMovedColumnsChanged,onColumnHeaderGroupChanged:this.handleHeaderGroupsChanged},Ne.VISIBILITY_ORDERING_BUILDER);case Ne.CONDITIONAL_FORMATTING:return r.jsx(CE,{rules:oe,onChange:this.handleConditionalFormatsChange,onCreate:this.handleConditionalFormatCreate,onSelect:this.handleConditionalFormatEdit});case Ne.CONDITIONAL_FORMATTING_EDIT:return N(l.columns),N(this.handleConditionalFormatEditorUpdate),r.jsx(WE,{columns:l.columns,rule:ue,onUpdate:this.handleConditionalFormatEditorUpdate,onSave:this.handleConditionalFormatEditorSave,onCancel:this.handleConditionalFormatEditorCancel});case Ne.CUSTOM_COLUMN_BUILDER:return r.jsx(DT,{model:l,customColumns:He,onSave:this.handleUpdateCustomColumns,onCancel:this.handleMenuBack},Ne.CUSTOM_COLUMN_BUILDER);case Ne.ROLLUP_ROWS:return r.jsx(FT,{model:l,onChange:this.handleRollupChange,config:Rs},Ne.ROLLUP_ROWS);case Ne.AGGREGATIONS:return r.jsx(uT,{settings:zt,isRollup:Io,onChange:this.handleAggregationsChange,onEdit:this.handleAggregationEdit});case Ne.AGGREGATION_EDIT:return So&&r.jsx(gT,{aggregation:So,columns:l.originalColumns,onChange:this.handleAggregationChange});case Ne.TABLE_EXPORTER:return r.jsx(Ms,{model:l,name:a,userColumnWidths:ii,movedColumns:Z,isDownloading:mt,tableDownloadStatus:et,tableDownloadProgress:De,tableDownloadEstimatedTime:gt??void 0,onDownload:this.handleDownloadTable,onDownloadStart:this.handleDownloadTableStart,onCancel:this.handleCancelDownloadTable,selectedRanges:Fe},Ne.TABLE_EXPORTER);case Ne.SELECT_DISTINCT:return r.jsx(gE,{model:l,selectDistinctColumns:q,onChange:this.handleSelectDistinctChanged});case Ne.ADVANCED_SETTINGS:return r.jsx($r,{items:u,onChange:m});default:throw Error(`Unexpected option type ${Ge.type}`)}});return r.jsxs("div",{className:"iris-grid",role:"presentation",children:[r.jsxs("div",{className:"iris-grid-column",children:[e!=null&&r.jsx("div",{className:"iris-grid-bar",children:e}),r.jsx(Wt,{in:w,timeout:Je.transitionSlowMs,classNames:"iris-grid-bar-horizontal",onEnter:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExit:this.handleAnimationStart,onExited:this.handleAnimationEnd,mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:"iris-grid-partition-selector-wrapper iris-grid-bar iris-grid-bar-primary",children:J&&A&&Q!=null&&r.jsx(hE,{table:J,getFormattedString:(Ge,Ae,Yt)=>l.displayString(Ge,Ae,Yt),columnName:A.name,partition:Q,onChange:this.handlePartitionChange,onFetchAll:this.handlePartitionFetchAll,onAppend:this.handlePartitionAppend,onDone:this.handlePartitionDone})})}),r.jsx(Wt,{in:lt,timeout:Je.transitionSlowMs,classNames:"iris-grid-bar-horizontal",onEnter:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExit:this.handleAnimationStart,onExited:this.handleAnimationEnd,mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:"iris-grid-bar",children:r.jsx(Ko,{value:vt,selectedColumns:kt,invertSelection:Cn,onChange:this.handleCrossColumnSearch,columns:l.columns,ref:this.crossColumnRef})})}),r.jsxs("div",{className:"grid-wrapper",ref:Ge=>{this.gridWrapper=Ge},children:[r.jsx(Cw,{ref:Ge=>{this.grid=Ge},isStickyBottom:!Xe(l)||!l.isEditable,isStuckToBottom:i,isStuckToRight:o,metricCalculator:C,model:l,keyHandlers:M,mouseHandlers:O,movedColumns:Z,movedRows:le,onError:this.handleGridError,onViewChanged:this.handleViewChanged,onSelectionChanged:this.handleSelectionChanged,onMovedColumnsChanged:this.handleMovedColumnsChanged,renderer:this.renderer,stateOverride:Ro,theme:Ds}),r.jsx(GE,{isOpen:xs,text:la,onClose:this.handleOverflowClose}),Do&&r.jsx(Kv,{model:l,modelColumns:l.columns,top:Is,bottom:xo,left:Ai,right:_i,filter:yo,formatter:G,sorts:he,reverseType:we,movedColumns:Z,customColumns:He,hiddenColumns:Ao,alwaysFetchColumns:this.getAlwaysFetchColumns(h,l.columns,Z,l.floatingLeftColumnCount,l.floatingRightColumnCount,this.grid?.state.draggingColumn?.range),formatColumns:this.getCachedPreviewFormatColumns(l.columns,oe,ue,Kt[Kt.length-1]?.type===Ne.CONDITIONAL_FORMATTING_EDIT?ae??void 0:void 0),rollupConfig:this.getModelRollupConfig(l.originalColumns,Rs,zt),totalsConfig:this.getModelTotalsConfig(l.columns,Rs,zt),selectDistinctColumns:q,pendingRowCount:ki,pendingDataMap:si,frozenColumns:vo,columnHeaderGroups:Zn}),!S&&r.jsx("div",{className:"grid-settings-button",children:r.jsx(B,{kind:"ghost","data-testid":`btn-iris-grid-settings-button-${a}`,onClick:this.handleMenu,icon:r.jsx(ee,{icon:Bg,transform:"up-1"}),tooltip:"Table Options"})}),Fo,No,Mo,ko,Lo,To&&this.getOverflowButtonTooltip(To),Mi&&this.getExpandCellTooltip(Mi),Li&&this.getLinkHoverTooltip(Li)]}),r.jsx(YE,{model:l,isShown:Oi,gotoRow:Eo,gotoRowError:aa,gotoValueError:ra,onGotoRowSubmit:this.handleGotoRowSelectedRowNumberSubmit,onGotoRowNumberChanged:this.handleGotoRowSelectedRowNumberChanged,onClose:this.handleGotoRowClosed,onEntering:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExiting:()=>{this.handleAnimationStart(),this.focus()},onExited:this.handleAnimationEnd,gotoValueSelectedColumnName:da,gotoValue:ca,gotoValueFilter:ha,onGotoValueSelectedColumnNameChanged:this.handleGotoValueSelectedColumnNameChanged,onGotoValueSelectedFilterChanged:this.handleGotoValueSelectedFilterChanged,onGotoValueChanged:this.handleGotoValueChanged,onGotoValueSubmit:this.handleGotoValueSubmitted}),r.jsx(Zw,{error:ti,isSaving:Xn!=null,saveTooltip:`Commit (${this.commitAction.shortcut.getDisplayText()})`,discardTooltip:`Discard (${this.discardAction.shortcut.getDisplayText()})`,pendingDataErrors:ni,pendingDataMap:si,onEntering:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExiting:this.handleAnimationStart,onExited:this.handleAnimationEnd,onSave:this.handlePendingCommitClicked,onDiscard:this.handlePendingDiscardClicked}),r.jsx($v,{children:wo}),r.jsx(ov,{model:l,copyOperation:y??void 0,onEntering:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExiting:this.handleAnimationStart,onExited:this.handleAnimationEnd}),r.jsx(jn,{ref:Ge=>{this.tableSaver=Ge},getDownloadWorker:n,onDownloadCompleted:this.handleDownloadCompleted,onDownloadCanceled:this.handleDownloadCanceled,onDownloadProgressUpdate:this.handleDownloadProgressUpdate,isDownloading:et===Ms.DOWNLOAD_STATUS.DOWNLOADING,formatter:G})]}),r.jsx(Wt,{in:S,timeout:Je.transitionMidMs,classNames:"slide-left",onEntering:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExiting:this.handleAnimationStart,onExited:this.handleAnimationEnd,mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:"table-sidebar",children:r.jsxs(Hm,{children:[r.jsx(ud,{title:"Table Options",onClose:this.handleMenuClose,children:r.jsx(Gc,{onSelect:Ge=>this.handleMenuSelect(Oo[Ge]),items:Oo})}),ma.map((Ge,Ae)=>r.jsx(ud,{title:Kt[Ae].title,onBack:this.handleMenuBack,onClose:this.handleMenuClose,children:Ge},Kt[Ae].type))]})})}),r.jsx(ie,{actions:this.contextActions})]})}}const Au=Hn;class ey extends Error{isMissingKey=!0;rowIndex;columnName;constructor(e,t){super(`${t} can't be empty (on pending row ${e+1})`),this.rowIndex=e,this.columnName=t}}const ty=ey,tt=ne.module("IrisGridTableModel"),ny=150,sy=0,iy=[];function Ks(c){return c.table!==void 0}class ao extends Ce{static ROW_BUFFER_PAGES=1;seekRow(e,t,n,s,i,o,l){throw new Error("Method not implemented.")}export(){throw new Error("Method not implemented.")}columnStatistics(e){throw new Error("Method not implemented.")}get customColumns(){return[]}set customColumns(e){throw new Error("Method not implemented.")}get formatColumns(){return[]}set formatColumns(e){throw new Error("Method not implemented.")}updateFrozenColumns(e){throw new Error("Method not implemented.")}get rollupConfig(){throw new Error("Method not implemented.")}set rollupConfig(e){throw new Error("Method not implemented.")}get selectDistinctColumns(){throw new Error("Method not implemented.")}set selectDistinctColumns(e){throw new Error("Method not implemented.")}get columns(){return this.table.columns}irisFormatter;inputTable;subscription;table;viewport;viewportData;formattedStringData;pendingStringData;isSaveInProgress;totalsTable;totalsTablePromise;totals;totalsDataMap;pendingNewDataMap;pendingNewRowCount=0;_columnHeaderGroupMap=new Map;columnHeaderParentMap=new Map;_columnHeaderMaxDepth=null;_columnHeaderGroups=[];_movedColumns=null;constructor(e,t=new gn,n=null){super(),this.handleTableDisconnect=this.handleTableDisconnect.bind(this),this.handleTableReconnect=this.handleTableReconnect.bind(this),this.handleTableUpdate=this.handleTableUpdate.bind(this),this.handleTotalsUpdate=this.handleTotalsUpdate.bind(this),this.handleRequestFailed=this.handleRequestFailed.bind(this),this.handleCustomColumnsChanged=this.handleCustomColumnsChanged.bind(this),this.irisFormatter=t,this.inputTable=n,this.subscription=null,this.table=e,this.viewport=null,this.viewportData=null,this.formattedStringData=[],this.pendingStringData=[],this.isSaveInProgress=!1,this.totalsTable=null,this.totalsTablePromise=null,this.totals=null,this.totalsDataMap=null,this.pendingNewDataMap=new Map,this.pendingNewRowCount=0,this.columnHeaderGroups=Se.parseColumnHeaderGroups(this,this.layoutHints?.columnGroups??[]).groups}close(){this.table.close(),this.totalsTable!==null&&this.totalsTable.close(),this.totalsTablePromise!==null&&this.totalsTablePromise.cancel()}startListening(){super.startListening(),this.table.addEventListener(I.Table.EVENT_DISCONNECT,this.handleTableDisconnect),this.table.addEventListener(I.Table.EVENT_RECONNECT,this.handleTableReconnect),this.table.addEventListener(I.Table.EVENT_UPDATED,this.handleTableUpdate),this.table.addEventListener(I.Client.EVENT_REQUEST_FAILED,this.handleRequestFailed),this.table.addEventListener(I.Table.EVENT_CUSTOMCOLUMNSCHANGED,this.handleCustomColumnsChanged),this.totalsTable!=null&&this.addTotalsListeners(this.totalsTable),this.applyViewport()}stopListening(){super.stopListening(),this.table.removeEventListener(I.Table.EVENT_DISCONNECT,this.handleTableDisconnect),this.table.removeEventListener(I.Table.EVENT_RECONNECT,this.handleTableReconnect),this.table.removeEventListener(I.Table.EVENT_UPDATED,this.handleTableUpdate),this.table.removeEventListener(I.Client.EVENT_REQUEST_FAILED,this.handleRequestFailed),this.table.removeEventListener(I.Table.EVENT_CUSTOMCOLUMNSCHANGED,this.handleCustomColumnsChanged),this.totalsTable!=null&&this.removeTotalsListeners(this.totalsTable),this.closeSubscription()}addTotalsListeners(e){e.addEventListener(I.Table.EVENT_UPDATED,this.handleTotalsUpdate),e.setViewport(0,0)}removeTotalsListeners(e){e.removeEventListener(I.Table.EVENT_UPDATED,this.handleTotalsUpdate)}handleTableDisconnect(){this.dispatchEvent(new ze(Ce.EVENT.DISCONNECT))}handleTableReconnect(){this.dispatchEvent(new ze(Ce.EVENT.RECONNECT))}handleTableUpdate(e){this.copyViewportData(e.detail),this.dispatchEvent(new ze(Ce.EVENT.UPDATED))}handleTotalsUpdate(e){this.copyTotalsData(e.detail),this.dispatchEvent(new ze(Ce.EVENT.UPDATED))}handleRequestFailed(e){this.dispatchEvent(new ze(Ce.EVENT.REQUEST_FAILED,e))}handleCustomColumnsChanged(){this.dispatchEvent(new ze(Ce.EVENT.COLUMNS_CHANGED,{detail:this.columns}))}get rowCount(){return this.table.size+this.pendingNewRowCount+(this.totals?.operationOrder?.length??0)}get pendingDataErrors(){return this.getCachedPendingErrors(this.pendingNewDataMap,this.columns,this.inputTable?.keyColumns.length??0)}get pendingDataMap(){return this.pendingNewDataMap}set pendingDataMap(e){e!==this.pendingNewDataMap&&(e.forEach((t,n)=>{if(!Se.isValidIndex(n))throw new Error(`Invalid rowIndex ${n}`);const{data:s}=t;s.forEach((i,o)=>{if(!Se.isValidIndex(o))throw new Error(`Invalid columnIndex ${o}`)})}),this.pendingNewDataMap=e,this.pendingNewRowCount=Math.max(this.pendingNewRowCount,this.maxPendingDataRow),this.formattedStringData=[],this.dispatchEvent(new ze(Ce.EVENT.PENDING_DATA_UPDATED)))}get pendingRowCount(){return this.pendingNewRowCount}set pendingRowCount(e){e!==this.pendingNewRowCount&&(this.pendingNewRowCount=Math.max(0,e,this.maxPendingDataRow),this.dispatchEvent(new ze(Ce.EVENT.UPDATED)))}get maxPendingDataRow(){return this.pendingNewDataMap.size>0?Math.max(...this.pendingNewDataMap.keys())+1:0}get columnCount(){return this.columns.length}get floatingBottomRowCount(){return this.totals!=null&&this.totals.showOnTop?0:this.totals?.operationOrder?.length??0}get floatingTopRowCount(){return this.totals!=null&&this.totals.showOnTop?this.totals?.operationOrder?.length??0:0}get isChartBuilderAvailable(){return!0}get isTotalsAvailable(){return this.table.getTotalsTable!=null}get isEditable(){return!this.isSaveInProgress&&this.inputTable!=null}cacheFormattedValue(e,t,n){this.formattedStringData[e]==null&&(this.formattedStringData[e]=[]),this.formattedStringData[e][t]=n}cachePendingValue(e,t,n){this.pendingStringData[e]==null&&(this.pendingStringData[e]=[]),this.pendingStringData[e][t]=n}clearPendingValue(e,t){const n=this.pendingStringData[e];n!=null&&delete n[t]}textValueForCell(e,t){if(this.pendingStringData[e]?.[t]!==void 0)return this.pendingStringData[e][t];if(this.formattedStringData[e]?.[t]===void 0){const n=this.valueForCell(e,t);if(n==null)return null;const s=this.totalsColumn(e,t)??this.columns[e],i=this.getCachedCustomColumnFormatFlag(this.formatter,s.name,s.type);let o;if(!i){const a=this.formatForCell(e,t);a?.formatString!=null&&(o=a)}const l=this.displayString(n,s.type,s.name,o);this.cacheFormattedValue(e,t,l)}return this.formattedStringData[e][t]}textForCell(e,t){const n=this.textValueForCell(e,t);if(n==null&&this.isKeyColumn(e)){const s=this.pendingRow(t);if(s!=null&&this.pendingDataMap.has(s))return"*"}if(F.isTextType(this.columns[e]?.type)){if(n===null)return"null";if(n==="")return"empty"}return n??""}truncationCharForCell(e){const t=this.columns[e],{type:n}=t;if(F.isNumberType(n)&&this.formatter.truncateNumbersWithPound)return"#"}colorForCell(e,t,n){const s=this.dataForCell(e,t);if(s){const{format:i,value:o}=s;if(o==null||o==="")return N(n.nullStringColor),n.nullStringColor;if(i&&i.color)return i.color;if(this.isPendingRow(t))return N(n.pendingTextColor),n.pendingTextColor;if(o!=null){const l=this.totalsColumn(e,t)??this.columns[e];if(F.isDateType(l.type)||l.name==="Date")return N(n.dateColor),n.dateColor;if(F.isNumberType(l.type))return o>0?(N(n.positiveNumberColor),n.positiveNumberColor):o<0?(N(n.negativeNumberColor),n.negativeNumberColor):(N(n.zeroNumberColor),n.zeroNumberColor)}}else if(this.isPendingRow(t)&&this.isKeyColumn(e))return N(n.errorTextColor),n.errorTextColor;return n.textColor}backgroundColorForCell(e,t){return this.formatForCell(e,t)?.backgroundColor??null}textAlignForCell(e){const t=this.columns[e],{type:n}=t;return F.isNumberType(n)?"right":F.isDateType(n)||t.name==="Date"?"center":"left"}textForColumnHeader(e,t=0){const n=this.columnAtDepth(e,t);return Ea(n)?n.isNew?"":n.name:n?.name}colorForColumnHeader(e,t=0){const n=this.columnAtDepth(e,t);return Ea(n)?n.color??null:null}getColumnHeaderGroup(e,t){const n=this.columnAtDepth(e,t);if(Ea(n))return n}getColumnHeaderParentGroup(e,t){return this.columnHeaderParentMap.get(this.columnAtDepth(e,t)?.name??"")}columnAtDepth(e,t=0){if(t===0)return this.columns[e];const n=this.columns[e]?.name;let s=this.columnHeaderParentMap.get(n);if(!s)return;let i=s.depth;for(;i<t;){if(s=this.columnHeaderParentMap.get(s.name),!s)return;i=s.depth}if(s.depth===t)return s}textForRowFooter(e){const t=this.totalsRow(e);return t!=null&&this.totals?this.totals.operationOrder[t]:""}getMemoizedInitialMovedColumns=ge(e=>{if(!e)return[];let t=[];const{groupMap:n}=Se.parseColumnHeaderGroups(this,e?.columnGroups??[]),s=(h,u)=>{const m=this.getColumnIndexByName(h);if(m==null)throw new Error(`Unknown layout hint column: ${h}`);const g=_.getVisibleIndex(m,t);t=_.moveItem(g,u,t)},i=(h,u)=>{const m=n.get(h);if(m==null)throw new Error(`Unknown layout hint group: ${h}`);const g=m.getVisibleRange(t);t=_.moveRange(g,u,t)},{frontColumns:o=[],backColumns:l=[],frozenColumns:a=[]}=e;if(o.length||l.length||a.length){const h=new Set;let u=0;a.forEach(g=>{if(h.has(g))throw new Error(`Column specified in multiple layout hints: ${g}`);s(g,u),u+=1}),o.forEach(g=>{if(h.has(g))throw new Error(`Column specified in multiple layout hints: ${g}`);s(g,u),u+=1});let m=this.columnMap.size-1;l.forEach(g=>{if(h.has(g))throw new Error(`Column specified in multiple layout hints: ${g}`);s(g,m),m-=1})}if(e?.columnGroups){const h=[...n.values()];h.sort((u,m)=>u.depth-m.depth),h.forEach(u=>{const m=u.children[0],g=this.getColumnIndexByName(m);let p;if(g!=null)p=_.getVisibleIndex(g,t);else{const C=n.get(m);if(!C)throw new Error(`Unknown column ${m} in group ${u.name}`);[,p]=C.getVisibleRange(t)}for(let C=1;C<u.children.length;C+=1){const f=u.children[C],b=n.get(f),w=this.getColumnIndexByName(f);if(b){const T=b.getVisibleRange(t)[0]<p?p-b.childIndexes.length+1:p+1;i(f,T),p=T+b.childIndexes.length-1}else if(w!=null){const T=_.getVisibleIndex(w,t)<p?p:p+1;s(f,T),p=T}}})}return this._movedColumns=t,t});get initialMovedColumns(){return this.getMemoizedInitialMovedColumns(this.layoutHints??void 0)}get initialMovedRows(){return iy}getMemoizedInitialColumnHeaderGroups=ge(e=>Se.parseColumnHeaderGroups(this,e?.columnGroups??[]).groups);get initialColumnHeaderGroups(){return this.getMemoizedInitialColumnHeaderGroups(this.layoutHints??void 0)}getMemoizedColumnMap=ge(e=>{const t=new Map;return e.forEach(n=>t.set(n.name,n)),t});get columnMap(){return this.getMemoizedColumnMap(this.table.columns)}get columnHeaderMaxDepth(){return this._columnHeaderMaxDepth??1}set columnHeaderMaxDepth(e){this._columnHeaderMaxDepth=e}get columnHeaderGroupMap(){return this._columnHeaderGroupMap}get columnHeaderGroups(){return this._columnHeaderGroups}set columnHeaderGroups(e){if(e===this._columnHeaderGroups)return;const{groups:t,maxDepth:n,parentMap:s,groupMap:i}=Se.parseColumnHeaderGroups(this,e??this.initialColumnHeaderGroups);this._columnHeaderGroups=t,this.columnHeaderMaxDepth=n,this.columnHeaderParentMap=s,this._columnHeaderGroupMap=i}get groupedColumns(){return[]}row(e){const t=this.totals?.operationOrder?.length??0,n=this.totals?.showOnTop??!1,s=this.totalsRow(e);if(s!=null){const a=this.totals?.operationOrder[s];return N(a),this.totalsDataMap?.get(a)??null}const i=this.pendingRow(e);if(i!=null)return this.pendingNewDataMap.get(i)??null;const o=this.viewportData?.offset??0,l=(n?e-t:e)-o;return this.viewportData?.rows?.[l]??null}totalsColumn(e,t){const n=this.totalsRow(t);if(n==null)return null;const s=this.totals?.operationOrder[n],i=this.totals?.defaultOperation??Le.SUM,o=this.columns[e];return this.totalsTable?.columns.find(l=>l.name===`${o.name}__${s}`||(s===i||this.totals?.operationOrder.length===1)&&l.name===o.name)}totalsRow(e){const t=this.totals?.operationOrder?.length??0,s=this.totals?.showOnTop??!1?e:e-this.table.size;return s>=0&&s<t?s:null}pendingRow(e){const t=e-this.floatingTopRowCount-this.table.size;return t>=0&&t<this.pendingNewRowCount?t:null}isTotalsRow(e){return this.totalsRow(e)!=null}isPendingRow(e){return this.pendingRow(e)!=null}dataForCell(e,t){return this.row(t)?.data.get(e)}formatForCell(e,t){return this.dataForCell(e,t)?.format}valueForCell(e,t){const n=this.dataForCell(e,t);if(n)return n.value??null}copyViewportData(e){if(e==null){tt.warn("invalid data!");return}this.viewportData=this.extractViewportData(e),this.formattedStringData=[]}copyTotalsData(e){if(e==null){tt.warn("invalid data!");return}const{columns:t,rows:n}=e;if(n.length!==1){tt.error("Unexpected number of rows received for totals table, ignoring update");return}const s=new Map,i=n[0],o=this.totals?.defaultOperation??Le.SUM,l=this.totals?.operationMap;for(let a=0;a<t.length;a+=1){const d=t[a],[h,u=l?.[h]?.[0]??o]=d.name.split("__");s.has(u)||s.set(u,{data:new Map});const{data:m}=s.get(u),g=this.columns.findIndex(p=>p.name===h);m.set(g,{value:i.get(d),format:i.getFormat(d)})}tt.debug2("copyTotalsData",s),this.totalsDataMap=s,this.formattedStringData=[]}getColumnIndexByName(e){return this.getColumnIndicesByNameMap(this.columns).get(e)}getColumnIndicesByNameMap=ge(e=>{const t=new Map;return e.forEach(({name:n},s)=>t.set(n,s)),t});extractViewportData(e){const t={offset:e.offset,rows:[]},{columns:n}=e;for(let s=0;s<e.rows.length;s+=1){const i=e.rows[s],o=this.extractViewportRow(i,n);t.rows.push(o)}return t}extractViewportRow(e,t){const n=new Map;for(let s=0;s<t.length;s+=1){const i=t[s],o=this.getColumnIndexByName(i.name);N(o),n.set(o,{value:e.get(i),format:e.getFormat(i)})}return{data:n}}closeSubscription(){tt.debug2("closeSubscription",this.subscription),this.subscription&&(this.subscription.close(),this.subscription=null),this.setViewport.cancel(),this.applyViewport.cancel()}get filter(){return this.table.filter}set filter(e){this.closeSubscription(),this.table.applyFilter(e),this.applyViewport()}get formatter(){return this.irisFormatter}set formatter(e){this.irisFormatter=e,this.formattedStringData=[],this.dispatchEvent(new ze(Ce.EVENT.FORMATTER_UPDATED))}displayString(e,t,n="",s){return this.getCachedFormattedString(this.formatter,e,t,n,s)}get sort(){return this.table.sort}set sort(e){this.closeSubscription(),this.table.applySort(e),this.applyViewport()}set totalsConfig(e){if(tt.debug("set totalsConfig",e),e!==this.totals){if(this.totals=e,this.formattedStringData=[],this.totalsTablePromise!=null&&this.totalsTablePromise.cancel(),this.setTotalsTable(null),e==null){this.dispatchEvent(new ze(Ce.EVENT.UPDATED));return}this.totalsTablePromise=ye.makeCancelable(this.table.getTotalsTable(e),t=>t.close()),this.totalsTablePromise.then(t=>{this.totalsTablePromise=null,this.setTotalsTable(t)}).catch(t=>{ye.isCanceled(t)||(tt.error("Unable to set next totalsTable",t),this.totalsTablePromise=null,this.dispatchEvent(new ze(Ce.EVENT.REQUEST_FAILED,{detail:t})))})}}setTotalsTable(e){tt.debug("setTotalsTable",e),this.totalsTable!==null&&(this.listenerCount>0&&this.removeTotalsListeners(this.totalsTable),this.totalsTable.close()),this.totalsTable=e,this.totalsDataMap=null,this.listenerCount>0&&this.totalsTable!=null&&this.addTotalsListeners(this.totalsTable)}setViewport=vs((e,t,n)=>{if(t<e){tt.error("Invalid viewport",e,t);return}const{viewport:s}=this;if(s!=null&&s.top===e&&s.bottom===t&&s.columns===n){tt.debug2("Ignoring duplicate viewport",s);return}this.viewport={top:e,bottom:t,columns:n},tt.debug2("setViewport",this.viewport),this.applyViewport()},ny);applyViewport=vs(()=>{if(!this.viewport)return;tt.debug2("applyViewport",this.viewport);const{top:e,bottom:t,columns:n}=this.viewport,[s,i]=this.getCachedViewportRowRange(e,t);this.applyBufferedViewport(s,i,n)},sy,{leading:!1});applyBufferedViewport(e,t,n){tt.debug2("applyBufferedViewport",e,t,n),this.subscription==null?(tt.debug2("applyBufferedViewport creating new subscription"),this.subscription=this.table.setViewport(e,t,n)):(tt.debug2("applyBufferedViewport using existing subscription"),this.subscription.setViewport(e,t,n))}async snapshot(e,t=!1,n=i=>i,s=!0){if(this.subscription==null)throw new Error("No subscription available");const i=s?te.consolidate(e):e;if(!Se.isValidSnapshotRanges(i))throw new Error(`Invalid snapshot ranges ${e}`);const o=new Set,l=[],a=new Set;for(let g=0;g<i.length;g+=1){const p=i[g];N(p.endRow),N(p.startRow);for(let C=p.startRow;C<=p.endRow&&C<this.floatingTopRowCount;C+=1)o.add(C);p.endRow>=this.floatingTopRowCount&&p.startRow<=this.floatingTopRowCount+this.table.size&&l.push(new te(p.startColumn,Math.min(Math.max(0,p.startRow-this.floatingTopRowCount)),p.endColumn,Math.min(Math.max(0,p.endRow-this.floatingTopRowCount),this.table.size-this.floatingTopRowCount)));for(let C=Math.max(p.startRow,this.floatingTopRowCount+this.table.size);C<=p.endRow&&C<this.floatingTopRowCount+this.table.size+this.floatingBottomRowCount;C+=1)a.add(C)}const d=Se.columnsFromRanges(i,this.columns),h=[];t&&h.push(d.map(g=>g.name));const u=[...o].sort();for(let g=0;g<u.length;g+=1){const p=u[g],C=d.map(f=>{const b=this.getColumnIndexByName(f.name);return N(b),n(this.valueForCell(b,p),f)});t&&C.push(this.textForRowFooter(p)),h.push(C)}if(l.length>0){const g=Se.rangeSetFromRanges(l),p=await this.subscription.snapshot(g,d);h.push(...p.rows.map(C=>d.map(f=>n(C.get(f),f))))}const m=[...a].sort();for(let g=0;g<m.length;g+=1){const p=m[g],C=d.map(f=>{const b=this.getColumnIndexByName(f.name);return N(b),n(this.valueForCell(b,p),f)});t&&C.push(this.textForRowFooter(p)),h.push(C)}return h}async textSnapshot(e,t=!1,n=s=>`${s}`){return tt.debug2("textSnapshot",e,t),(await this.snapshot(e,t,n,!1)).map(i=>i.join(" ")).join(`
31
31
  `)}async valuesTable(e){let t=null;try{return t=await this.table.copy(),t.applyFilter([]),t.applySort([]),t.selectDistinct([e])}finally{t?.close()}}getCachedFormattedString=pn((e,t,n,s,i)=>e.getFormattedString(t,n,s,i),{max:1e4});getCachedCustomColumnFormatFlag=pn($n.isCustomColumnFormatDefined,{max:1e4});getCachedViewportRowRange=ge((e,t)=>{const n=t-e,s=Math.max(0,e-n*ao.ROW_BUFFER_PAGES),i=t+n*ao.ROW_BUFFER_PAGES;return[s,i]});getCachedPendingErrors=ge((e,t,n)=>{const s=new Map;return e.forEach((i,o)=>{const{data:l}=i;for(let a=0;a<n;a+=1)l.has(a)||(s.has(o)||s.set(o,[]),s.get(o)?.push(new ty(o,t[a].name)))}),s});isColumnMovable(e,t){if(e<0||e>=this.columnCount)return!1;if(t>0)return!0;const n=this.columns[e].name;return this.frontColumns.includes(n)||this.backColumns.includes(n)||this.frozenColumns.includes(n)||!n?!1:!this.isKeyColumn(e)}isKeyColumn(e){return e<(this.inputTable?.keyColumns.length??0)}isRowMovable(){return!1}isEditableRange(e){return!(this.inputTable==null||!te.isBounded(e)||!(this.isPendingRow(e.startRow)&&this.isPendingRow(e.endRow)||this.inputTable.keyColumns.length!==0&&e.startColumn>=this.inputTable.keyColumns.length&&e.endColumn>=this.inputTable.keyColumns.length)||e.startRow<this.floatingTopRowCount||e.startRow>=this.floatingTopRowCount+this.table.size+this.pendingRowCount||e.endRow>=this.floatingTopRowCount+this.table.size+this.pendingRowCount)}isDeletableRange(e){return this.inputTable!=null&&e.startRow!=null&&e.endRow!=null&&e.startRow>=this.floatingTopRowCount&&e.startRow<this.floatingTopRowCount+this.table.size+this.pendingRowCount&&e.endRow<this.floatingTopRowCount+this.table.size+this.pendingRowCount}isEditableRanges(e){return e.every(t=>this.isEditableRange(t))}isDeletableRanges(e){return e.every(t=>this.isDeletableRange(t))}getTableAreaRange(){return new te(null,this.floatingTopRowCount,null,this.floatingTopRowCount+this.table.size-1)}getPendingAreaRange(){return new te(null,this.floatingTopRowCount+this.table.size,null,this.floatingTopRowCount+this.table.size+this.pendingNewRowCount-1)}async setValueForCell(e,t,n){return this.setValueForRanges([new te(e,t,e,t)],n)}async setValueForRanges(e,t){if(!this.isEditableRanges(e))throw new Error(`Uneditable ranges ${e}`);try{const n=new Set,s=[];te.forEachCell(e,(d,h)=>{const u=this.columns[d];if(n.add(u),s[d]===void 0){const m=F.makeValue(u.type,t,this.formatter.timeZone);s[d]=m!=null?this.displayString(m,u.type,u.name):null}this.cachePendingValue(d,h,s[d])});const i=this.getPendingAreaRange(),o=e.map(d=>te.intersection(i,d)).filter(d=>d!=null).map(d=>(N(d),te.offset(d,0,-(this.floatingTopRowCount+this.table.size))));if(o.length>0){const d=new Map(this.pendingNewDataMap);te.forEachCell(o,(h,u)=>{d.has(u)||d.set(u,{data:new Map});const m=this.columns[h],g=d.get(u);N(g);const{data:p}=g,C=new Map(p),f=F.makeValue(m.type,t,this.formatter.timeZone);f!=null?C.set(h,{value:f}):C.delete(h),C.size>0?d.set(u,{...g,data:C}):d.delete(u)}),this.pendingDataMap=d}this.dispatchEvent(new ze(Ce.EVENT.UPDATED));const l=this.getTableAreaRange(),a=e.map(d=>te.intersection(l,d)).filter(d=>d!=null);if(a.length>0){const h=(await this.snapshot(a.map(m=>new te(null,m?.startRow??null,null,m?.endRow??null)))).map(m=>{const g={};for(let p=0;p<this.columns.length;p+=1)g[this.columns[p].name]=m[p];return n.forEach(p=>{g[p.name]=F.makeValue(p.type,t,this.formatter.timeZone)}),g}),u=await this.inputTable?.addRows(h);tt.debug("setValueForRanges(",e,",",t,") set tableRanges",a,"result",u)}te.forEachCell(e,(d,h)=>{const u=s[d];N(u),this.cacheFormattedValue(d,h,u)})}catch(n){tt.error("Unable to set ranges",e,t,n)}finally{te.forEachCell(e,(n,s)=>{this.clearPendingValue(n,s)})}}async setValues(e=[]){if(tt.debug("setValues(",e,")"),!e.every(t=>this.isEditableRange(te.makeCell(t.column??t.x,t.row??t.y))))throw new Error(`Uneditable ranges ${e}`);try{const t=new Map(this.pendingNewDataMap);e.forEach(l=>{const{text:a}=l,d=l.column??l.x,h=l.row??l.y,u=this.columns[d],m=F.makeValue(u.type,a,this.formatter.timeZone),g=m!=null?this.displayString(m,u.type,u.name):null;this.cachePendingValue(d,h,g);const p=this.pendingRow(h);if(p!=null){t.has(p)||t.set(p,{data:new Map});const C=t.get(p);N(C);const{data:f}=C,b=new Map(f);m!=null?b.set(d,{value:m}):b.delete(d),b.size>0?t.set(p,{...C,data:b}):t.delete(p)}}),this.pendingDataMap=t,this.dispatchEvent(new ze(Ce.EVENT.UPDATED));const n=e.reduce((l,a)=>{const d=a.row??a.y;return l.has(d)||l.set(d,[]),l.get(d)?.push(a),l},new Map),s=te.consolidate(e.map(l=>te.makeCell(l.column??l.x,l.row??l.y))),i=this.getTableAreaRange(),o=s.map(l=>te.intersection(i,l)).filter(l=>l!=null);if(o.length>0){const a=(await this.snapshot(o.map(h=>(N(h),new te(null,h.startRow,null,h.endRow))))).map((h,u)=>{let m=null,g=u;for(let f=0;f<o.length;f+=1){const b=o[f];N(b);const w=te.rowCount([b]);if(g<w){N(b.startRow),m=b.startRow+g;break}g-=w}const p={};for(let f=0;f<this.columns.length;f+=1)p[this.columns[f].name]=h[f];N(m);const C=n.get(m);return C?.forEach(f=>{const b=this.columns[f.column??f.x];p[b.name]=F.makeValue(b.type,f.text,this.formatter.timeZone)}),p});tt.info("setValues setting tableRanges",o);const d=await this.inputTable?.addRows(a);tt.info("setValues set tableRanges",o,"SUCCESS",d)}e.forEach(l=>{const{text:a}=l,d=l.column??l.x,h=l.row??l.y,u=this.columns[d],m=F.makeValue(u.type,a,this.formatter.timeZone),g=m!=null?this.displayString(m,u.type,u.name):null;this.cacheFormattedValue(d,h,g)})}finally{e.forEach(t=>{this.clearPendingValue(t.column,t.row)})}}async commitPending(){if(this.pendingNewDataMap.size<=0)throw new Error("No pending changes to commit");try{this.isSaveInProgress=!0;const e=[];this.pendingNewDataMap.forEach(n=>{const s={};n.data.forEach(({value:i},o)=>{const l=this.columns[o];s[l.name]=i}),e.push(s)});const t=await this.inputTable?.addRows(e);tt.debug("commitPending()",this.pendingNewDataMap,"result",t),this.pendingNewDataMap=new Map,this.pendingNewRowCount=Math.max(0,(this.viewport?.bottom??0)-this.table.size),this.formattedStringData=[],this.dispatchEvent(new ze(Ce.EVENT.PENDING_DATA_UPDATED))}finally{this.isSaveInProgress=!1}}editValueForCell(e,t){return this.textValueForCell(e,t)}async delete(e){if(!this.isDeletableRanges(e))throw new Error(`Undeletable ranges ${e}`);N(this.inputTable);const{keyColumns:t}=this.inputTable;if(t.length===0)throw new Error("No key columns to allow deletion");const n=this.getPendingAreaRange(),s=e.map(u=>te.intersection(n,u)).filter(u=>u!=null).map(u=>(N(u),te.offset(u,0,-(this.floatingTopRowCount+this.table.size))));if(s.length>0){const u=new Map(this.pendingNewDataMap);for(let m=0;m<s.length;m+=1){const g=s[m];N(g.startRow),N(g.endRow);for(let p=g.startRow;p<=g.endRow;p+=1)u.delete(p)}this.pendingNewDataMap=u,this.formattedStringData=[],this.dispatchEvent(new ze(Ce.EVENT.PENDING_DATA_UPDATED)),this.dispatchEvent(new ze(Ce.EVENT.UPDATED))}const i=this.getTableAreaRange(),o=e.map(u=>te.intersection(i,u)).filter(u=>u!=null);if(o.length<=0)return;const[l,a]=await Promise.all([this.snapshot(o.map(u=>(N(u),new te(0,u.startRow,t.length-1,u.endRow)))),this.table.copy()]),h=l.map(u=>{const m=[];for(let g=0;g<t.length;g+=1){const p=t[g],C=u[g],f=F.makeFilterRawValue(p.type,C),b=p.filter().eq(f);m.push(b)}return m.reduce((g,p)=>g?.and(p)??p)}).reduce((u,m)=>u?.or(m)??m);a.applyFilter([h]),a.close()}isValidForCell(e,t,n){try{const s=this.columns[e];return F.makeValue(s.type,n,this.formatter.timeZone),!0}catch{return!1}}}const as=ne.module("IrisGridTableModel");class oy extends ao{userFrozenColumns;customColumnList;formatColumnList;constructor(e,t=new gn,n=null){super(e,t,n),this.customColumnList=[],this.formatColumnList=[]}get isExportAvailable(){return this.table.freeze!=null}get isColumnStatisticsAvailable(){return this.table.getColumnStatistics!=null}get isValuesTableAvailable(){return this.table.selectDistinct!=null&&this.table.copy!=null}get isRollupAvailable(){return this.table.rollup!=null}get isSelectDistinctAvailable(){return this.table.selectDistinct!=null}get isCustomColumnsAvailable(){return this.table.applyCustomColumns!=null}get isFormatColumnsAvailable(){return this.table.applyCustomColumns!=null}getMemoizedFrontColumns=ge(e=>e??[]);get frontColumns(){return this.getMemoizedFrontColumns(this.layoutHints?.frontColumns)}getMemoizedBackColumns=ge(e=>e??[]);get backColumns(){return this.getMemoizedBackColumns(this.layoutHints?.backColumns)}getMemoizedFrozenColumns=ge((e,t)=>t??e??[]);get frozenColumns(){return this.getMemoizedFrozenColumns(this.layoutHints?.frozenColumns,this.userFrozenColumns)}get layoutHints(){return this.table.layoutHints}get floatingLeftColumnCount(){return this.frozenColumns.length}get description(){return this.table.description}get customColumns(){return this.customColumnList}set customColumns(e){if(as.debug2("set customColumns",e,this.customColumnList,e===this.customColumnList),this.customColumnList.length===0&&e.length===0){as.debug("Ignore empty initial customColumns"),this.customColumnList=e;return}if(this.customColumnList===e){as.debug("Ignore same customColumns");return}this.closeSubscription(),this.customColumnList=e,this.table.applyCustomColumns([...e,...this.formatColumns]),this.applyViewport()}get formatColumns(){return this.formatColumnList}set formatColumns(e){if(as.debug2("set formatColumns",e,this.formatColumnList,e===this.formatColumnList),this.formatColumnList.length===0&&e.length===0){as.debug("Ignore empty initial formatColumns"),this.formatColumnList=e;return}if(this.formatColumnList===e){as.debug("Ignore same formatColumns");return}this.closeSubscription(),this.formatColumnList=e,this.table.applyCustomColumns([...this.customColumns,...e]),this.applyViewport()}updateFrozenColumns(e){this.userFrozenColumns=e,this.dispatchEvent(new ze(Ce.EVENT.TABLE_CHANGED,{detail:this.table}))}set totalsConfig(e){if(as.debug("set totalsConfig",e),e!==this.totals){if(this.totals=e,this.formattedStringData=[],this.totalsTablePromise!=null&&this.totalsTablePromise.cancel(),this.setTotalsTable(null),e==null){this.dispatchEvent(new ze(Ce.EVENT.UPDATED));return}this.totalsTablePromise=ye.makeCancelable(this.table.getTotalsTable(e),t=>t.close()),this.totalsTablePromise.then(t=>{this.totalsTablePromise=null,this.setTotalsTable(t)}).catch(t=>{ye.isCanceled(t)||(as.error("Unable to set next totalsTable",t),this.totalsTablePromise=null,this.dispatchEvent(new ze(Ce.EVENT.REQUEST_FAILED,{detail:t})))})}}get isFilterRequired(){return this.table.isUncoalesced}isFilterable(e){return this.getCachedFilterableColumnSet(this.columns).has(e)}async export(){return this.table.freeze()}columnStatistics(e){return this.table.getColumnStatistics(e)}getCachedFilterableColumnSet=ge(e=>new Set(e.map((t,n)=>n)));isColumnMovable(e){const t=this.columns[e].name;return this.frontColumns.includes(t)||this.backColumns.includes(t)||this.frozenColumns.includes(t)?!1:!this.isKeyColumn(e)}isColumnFrozen(e){return this.frozenColumns.includes(this.columns[e].name)}async delete(e){if(!this.isDeletableRanges(e))throw new Error(`Undeletable ranges ${e}`);N(this.inputTable);const{keyColumns:t}=this.inputTable;if(t.length===0)throw new Error("No key columns to allow deletion");const n=this.getPendingAreaRange(),s=e.map(u=>te.intersection(n,u)).filter(u=>u!=null).map(u=>(N(u),te.offset(u,0,-(this.floatingTopRowCount+this.table.size))));if(s.length>0){const u=new Map(super.pendingDataMap);for(let m=0;m<s.length;m+=1){const g=s[m];N(g.startRow),N(g.endRow);for(let p=g.startRow;p<=g.endRow;p+=1)u.delete(p)}super.pendingDataMap=u,this.formattedStringData=[],this.dispatchEvent(new ze(Ce.EVENT.PENDING_DATA_UPDATED)),this.dispatchEvent(new ze(Ce.EVENT.UPDATED))}const i=this.getTableAreaRange(),o=e.map(u=>te.intersection(i,u)).filter(u=>u!=null);if(o.length<=0)return;const[l,a]=await Promise.all([this.snapshot(o.map(u=>(N(u),new te(0,u.startRow,t.length-1,u.endRow)))),this.table.copy()]),h=l.map(u=>{const m=[];for(let g=0;g<t.length;g+=1){const p=t[g],C=u[g],f=F.makeFilterRawValue(p.type,C),b=p.filter().eq(f);m.push(b)}return m.reduce((g,p)=>g?.and(p)??p)}).reduce((u,m)=>u?.or(m)??m);a.applyFilter([h]),await this.inputTable?.deleteTable(a),a.close()}async seekRow(e,t,n,s,i,o,l){return this.table.seekRow(e,t,n,s,i,o,l)}get isSeekRowAvailable(){return this.table.seekRow!=null}}const _u=oy;class ly extends ao{applyBufferedViewport(e,t,n){this.table.setViewport(e,t,n)}textForCell(e,t){const n=this.columns[e],s=this.row(t);if(s!=null&&n!=null&&!s.hasChildren&&n.constituentType!=null){const i=this.valueForCell(e,t);return this.displayString(i,n.constituentType,n.name)}return super.textForCell(e,t)}extractViewportRow(e,t){const{isExpanded:n,hasChildren:s,depth:i}=e;return{...super.extractViewportRow(e,t),isExpanded:n,hasChildren:s,depth:i}}async snapshot(e,t,n){N(this.viewport),N(this.viewportData);const{columns:s}=this.viewport,i=[];t!=null&&t&&i.push(s.map(l=>l.name));const o=new te(0,this.viewportData?.offset,s.length,this.viewportData.offset+this.viewportData.rows.length);for(let l=0;l<e.length;l+=1){const a=te.intersection(o,e[l]);N(a),N(a.startRow),N(a.endRow);for(let d=a.startRow;d<=a.endRow;d+=1){const h=[],u=this.viewportData.rows[d-this.viewportData.offset];N(a.startColumn),N(a.endColumn);for(let m=a.startColumn;m<=a.endColumn;m+=1)N(n),h.push(n(u.data.get(m)?.value,this.columns[m]));i.push(h)}}return i}get groupedColumns(){return this.table.groupedColumns}get hasExpandableRows(){return!0}get isExpandAllAvailable(){return this.table.expandAll!==void 0}get isChartBuilderAvailable(){return!1}get isSelectDistinctAvailable(){return!1}get isReversible(){return!1}isFilterable(e){return this.getCachedFilterableColumnSet(this.columns,this.groupedColumns).has(e)}isColumnMovable(e){return e>=this.groupedColumns.length}isRowExpandable(e){return this.row(e)?.hasChildren??!1}isRowExpanded(e){return this.row(e)?.isExpanded??!1}setRowExpanded(e,t,n=!1){this.isExpandAllAvailable?this.table.setExpanded(e,t,n):this.table.setExpanded(e,t)}expandAll(){this.table.expandAll&&this.table.expandAll()}collapseAll(){this.table.collapseAll&&this.table.collapseAll()}depthForRow(e){return(this.row(e)?.depth??1)-1}getCachedFilterableColumnSet=ge((e,t)=>new Set((t?.length>0?t:e).map(n=>e.findIndex(s=>n.name===s.name))));updateFrozenColumns(e){if(e.length>0)throw new Error("Cannot freeze columns on a tree table")}}const ay=ly,rs=ne.module("IrisGridProxyModel");function Na(c,e,t){return F.isTreeTable(c)?new ay(c,e):new _u(c,e,t)}class ry extends Ce{originalModel;model;modelPromise;rollup;selectDistinct;constructor(e,t=new gn,n=null){super(),this.handleModelEvent=this.handleModelEvent.bind(this);const s=Na(e,t,n);this.originalModel=s,this.model=s,this.modelPromise=null,this.rollup=null,this.selectDistinct=[]}close(){this.originalModel.close(),this.model!==this.originalModel&&this.model.close(),this.modelPromise!=null&&this.modelPromise.cancel()}handleModelEvent(e){rs.debug2("handleModelEvent",e);const{detail:t,type:n}=e;this.dispatchEvent(new ze(n,{detail:t}))}setModel(e){rs.debug("setModel",e);const t=this.model;t!==this.originalModel&&t.close(),this.model=e,this.listenerCount>0&&this.addListeners(e),this.dispatchEvent(new ze(Ce.EVENT.COLUMNS_CHANGED,{detail:e.columns})),Ks(e)&&this.dispatchEvent(new ze(Ce.EVENT.TABLE_CHANGED,{detail:e.table}))}setNextModel(e){rs.debug2("setNextModel"),this.modelPromise&&this.modelPromise.cancel(),this.listenerCount>0&&this.removeListeners(this.model),this.modelPromise=ye.makeCancelable(e,t=>t.close()),this.modelPromise.then(t=>{this.modelPromise=null,this.setModel(t)}).catch(t=>{if(ye.isCanceled(t)){rs.debug2("setNextModel cancelled");return}rs.error("Unable to set next model",t),this.modelPromise=null,this.dispatchEvent(new ze(Ce.EVENT.REQUEST_FAILED,{detail:t}))})}startListening(){super.startListening(),this.addListeners(this.model)}stopListening(){super.stopListening(),this.removeListeners(this.model)}addListeners(e){const t=Object.keys(Ce.EVENT);for(let n=0;n<t.length;n+=1)e.addEventListener(t[n],this.handleModelEvent)}removeListeners(e){const t=Object.keys(Ce.EVENT);for(let n=0;n<t.length;n+=1)e.removeEventListener(t[n],this.handleModelEvent)}get rowCount(){return this.model.rowCount}get columnCount(){return this.model.columnCount}get floatingTopRowCount(){return this.model.floatingTopRowCount}get floatingBottomRowCount(){return this.model.floatingBottomRowCount}get floatingLeftColumnCount(){return this.model.floatingLeftColumnCount}get floatingRightColumnCount(){return this.model.floatingRightColumnCount}textForCell=(...e)=>this.model.textForCell(...e);truncationCharForCell=(...e)=>this.model.truncationCharForCell(...e);textAlignForCell=(...e)=>this.model.textAlignForCell(...e);colorForCell=(...e)=>this.model.colorForCell(...e);backgroundColorForCell=(...e)=>this.model.backgroundColorForCell(...e);textForColumnHeader=(...e)=>this.model.textForColumnHeader(...e);colorForColumnHeader=(...e)=>this.model.colorForColumnHeader(...e);textForRowHeader=(...e)=>this.model.textForRowHeader(...e);textForRowFooter=(...e)=>this.model.textForRowFooter(...e);isRowMovable=(...e)=>this.model.isRowMovable(...e);isColumnMovable=(...e)=>this.model.isColumnMovable(...e);isColumnFrozen(e){return this.model.isColumnFrozen(e)}get hasExpandableRows(){return je(this.model)?this.model.hasExpandableRows:!1}get isExpandAllAvailable(){return je(this.model)?this.model.isExpandAllAvailable??!1:!1}isRowExpandable=(...e)=>je(this.model)?this.model.isRowExpandable(...e):!1;isRowExpanded=(...e)=>je(this.model)?this.model.isRowExpanded(...e):!1;setRowExpanded=(...e)=>{if(je(this.model))return this.model.setRowExpanded(...e);throw Error("Function setRowExpanded does not exist on IrisGridTableModel")};expandAll=()=>{if(je(this.model))return this.model.expandAll();throw Error("Function expandAll does not exist on IrisGridTableModel")};collapseAll=()=>{if(je(this.model))return this.model.collapseAll();throw Error("Function collapseAll does not exist on IrisGridTableModel")};depthForRow=(...e)=>je(this.model)?this.model.depthForRow(...e):0;get isExportAvailable(){return this.model.isExportAvailable}get isColumnStatisticsAvailable(){return this.model.isColumnStatisticsAvailable}get isValuesTableAvailable(){return this.model.isValuesTableAvailable}get isCustomColumnsAvailable(){return this.model.isCustomColumnsAvailable&&!(this.isSelectDistinctAvailable&&this.selectDistinctColumns.length>0)}get isFormatColumnsAvailable(){return this.model.isFormatColumnsAvailable}get isChartBuilderAvailable(){return this.model.isChartBuilderAvailable}get isRollupAvailable(){return(this.originalModel.isRollupAvailable||this.rollup!=null)&&this.selectDistinct.length===0}get isSelectDistinctAvailable(){return(this.originalModel.isSelectDistinctAvailable||this.selectDistinct.length>0)&&this.rollup==null}get isTotalsAvailable(){return this.model.isTotalsAvailable}get isReversible(){return this.model.isReversible}get columns(){return this.model.columns}get initialMovedColumns(){return this.model.initialMovedColumns}get initialMovedRows(){return this.model.initialMovedRows}get layoutHints(){return this.model.layoutHints}get frontColumns(){return this.model.frontColumns}get backColumns(){return this.model.backColumns}get frozenColumns(){return this.model.frozenColumns}getColumnHeaderGroup=(...e)=>this.model.getColumnHeaderGroup(...e);get columnHeaderGroups(){return this.model.columnHeaderGroups}set columnHeaderGroups(e){this.model.columnHeaderGroups=e}get initialColumnHeaderGroups(){return this.model.initialColumnHeaderGroups}getColumnHeaderParentGroup=(...e)=>this.model.getColumnHeaderParentGroup(...e);get columnHeaderGroupMap(){return this.model.columnHeaderGroupMap}get columnHeaderMaxDepth(){return this.model.columnHeaderMaxDepth}updateFrozenColumns(e){return this.model.updateFrozenColumns(e)}get originalColumns(){return this.originalModel.columns}get groupedColumns(){return this.model.groupedColumns}get description(){return this.model.description}formatForCell=(...e)=>this.model.formatForCell(...e);valueForCell=(...e)=>this.model.valueForCell(...e);get filter(){return this.model.filter}set filter(e){this.model.filter=e}get formatter(){return this.model.formatter}set formatter(e){this.model.formatter=e}displayString=(...e)=>this.model.displayString(...e);get sort(){return this.model.sort}set sort(e){this.model.sort=e}get customColumns(){return this.model.customColumns}set customColumns(e){this.model.customColumns=e}get formatColumns(){return this.model.formatColumns}set formatColumns(e){this.model.formatColumns=e}get rollupConfig(){return this.rollup}set rollupConfig(e){if(rs.debug("set rollupConfig",e),!this.isRollupAvailable)throw new Error("Rollup Rows are not available");if(st(e,this.rollup))return;this.rollup=e;let t=Promise.resolve(this.originalModel);Ks(this.originalModel)&&e!=null&&(t=this.originalModel.table.rollup(e).then(n=>Na(n,this.formatter))),this.setNextModel(t)}get selectDistinctColumns(){return this.selectDistinct}set selectDistinctColumns(e){if(rs.debug("set selectDistinctColumns",e),!this.isSelectDistinctAvailable)throw new Error("Select distinct is not available");if(e===this.selectDistinctColumns||e.length===0&&this.selectDistinctColumns.length===0){rs.debug("Ignore same selectDistinctColumns",e);return}this.selectDistinct=e;const t=e.map(s=>this.originalColumns.find(i=>i.name===s)).filter(s=>s!=null);let n=Promise.resolve(this.originalModel);Ks(this.originalModel)&&t.length>0&&(n=this.originalModel.table.selectDistinct(t).then(s=>Na(s,this.formatter))),this.setNextModel(n)}get table(){if(Ks(this.model))return this.model.table}get totalsConfig(){return this.model.totalsConfig}set totalsConfig(e){this.model.totalsConfig=e}get isFilterRequired(){return this.model.isFilterRequired}get isEditable(){return Xe(this.model)&&this.model.isEditable}isEditableRange=(...e)=>Xe(this.model)?this.model.isEditableRange(...e):!1;isFilterable=(...e)=>this.model.isFilterable(...e);setViewport=(e,t,n)=>this.model.setViewport(e,t,n);snapshot=(...e)=>this.model.snapshot(...e);textSnapshot=(...e)=>this.model.textSnapshot(...e);export(){if(F.isTreeTable(this.model))throw new Error("TreeTable has no 'export' property");return this.model.export()}valuesTable=(...e)=>this.model.valuesTable(...e);columnStatistics(e){if(F.isTreeTable(this.model))throw new Error("TreeTable has no 'columnStatistics' function");return this.model.columnStatistics(e)}editValueForCell=(...e)=>Xe(this.model)?this.model.editValueForCell(...e):"";setValueForCell=(...e)=>Xe(this.model)?this.model.setValueForCell(...e):Promise.reject(new Error("Model is not editable"));setValueForRanges=(...e)=>Xe(this.model)?this.model.setValueForRanges(...e):Promise.reject(new Error("Model is not editable"));setValues=(...e)=>Xe(this.model)?this.model.setValues(...e):Promise.resolve();isValidForCell=(...e)=>Xe(this.model)?this.model.isValidForCell(...e):!1;delete=(...e)=>this.model.delete(...e);get pendingDataMap(){return this.model.pendingDataMap}set pendingDataMap(e){this.model.pendingDataMap=e}get pendingRowCount(){return this.model.pendingRowCount}set pendingRowCount(e){this.model.pendingRowCount=e}get pendingDataErrors(){return this.model.pendingDataErrors}commitPending=(...e)=>this.model.commitPending(...e);getColumnIndexByName(e){return this.model.getColumnIndexByName(e)}async seekRow(e,t,n,s,i,o,l){return this.model.seekRow(e,t,n,s,i,o,l)}get isSeekRowAvailable(){return this.model.isSeekRowAvailable}}const dy=ry;class cy{static async makeModel(e,t=new gn){let n=null;return!F.isTreeTable(e)&&e.hasInputTable&&(n=await e.inputTable()),new dy(e,t,n)}}const Wr=cy;class hy{static OPEN="ChartEvent.OPEN";static CLOSE="ChartEvent.CLOSE";static COLUMN_SELECTED="ChartEvent.COLUMN_SELECTED"}const Qa=hy;class uy{static SESSION_OPENED="ConsoleEvent.SESSION_OPENED";static SESSION_CLOSED="ConsoleEvent.SESSION_CLOSED";static FOCUS_HISTORY="ConsoleEvent.FOCUS_HISTORY";static SEND_COMMAND="ConsoleEvent.SEND_COMMAND";static SETTINGS_CHANGED="ConsoleEvent.SETTINGS_CHANGED"}const $t=uy;class my{static TABLE_CHANGED="InputFilterEvent.TABLE_CHANGED";static COLUMNS_CHANGED="InputFilterEvent.COLUMNS_CHANGED";static FILTERS_CHANGED="InputFilterEvent.FILTERS_CHANGED";static CLEAR_ALL_FILTERS="InputFilterEvent.CLEAR_ALL_FILTERS";static COLUMN_SELECTED="InputFilterEvent.COLUMN_SELECTED";static OPEN_DROPDOWN="InputFilterEvent.OPEN_DROPDOWN";static OPEN_INPUT="InputFilterEvent.OPEN_INPUT";static OPEN_FILTER_SET_MANAGER="InputFilterEvent.OPEN_FILTER_SET_MANAGER"}const Ze=my;class gy{static OPEN_GRID="IrisGridEvent.OPEN_GRID";static CLOSE_GRID="IrisGridEvent.CLOSE_GRID";static DATA_SELECTED="IrisGridEvent.DATA_SELECTED";static COLUMN_SELECTED="IrisGridEvent.COLUMN_SELECTED";static STATE_CHANGED="IrisGridEvent.STATE_CHANGED";static CREATE_CHART="IrisGridevent.CREATE_CHART"}const cn=gy,Pu=Object.freeze({OPEN:"MarkdownEvent.OPEN"});class py{static CREATE_NOTEBOOK="NotebookEvent.createNotebook";static SELECT_NOTEBOOK="NotebookEvent.selectNotebook";static CLOSE_FILE="NotebookEvent.closeFile";static RENAME="NotebookEvent.rename";static RENAME_FILE="NotebookEvent.renameFile";static REGISTER_FILE="NotebookEvent.registerFile";static SEND_TO_NOTEBOOK="NotebookEvent.sendToNotebook";static UNREGISTER_FILE="NotebookEvent.unregisterFile";static PROMOTE_FROM_PREVIEW="NotebookEvent.promoteFromPreview"}const Ue=py;class fy{static focus="TabEvent.focus";static blur="TabEvent.blur";static openPQObject="TabEvent.openPQObject";static openControl="TabEvent.openControl";static reload="TabEvent.reload";static clearAllFilters="TabEvent.clearAllFilters"}const Yo=fy;class Cy extends v.PureComponent{static defaultProps={additionalActions:[]};constructor(e){super(e),this.handleCloseTab=this.handleCloseTab.bind(this),this.handleCloseTabsRight=this.handleCloseTabsRight.bind(this),this.handleCloseTabsAll=this.handleCloseTabsAll.bind(this)}getAllTabs(){const{glContainer:e}=this.props;return[...e?.tab?.header?.tabs??[]]}handleCloseTab(){const{glContainer:e}=this.props;e.close()}handleCloseTabsAll(){this.getAllTabs().forEach(t=>(t?.contentItem).container?.close())}handleCloseTabsRight(){const{glContainer:e}=this.props,t=this.getAllTabs();for(let n=t.length-1;n>0&&t[n].contentItem?.config?.id!==e.tab?.contentItem?.config?.id;n-=1)(t[n]?.contentItem).container?.close()}canCloseTabsRight(){const{glContainer:e}=this.props,t=this.getAllTabs();let n=!0;for(let s=t.length-1;s>0&&t[s].contentItem?.config?.id!==e.tab?.contentItem?.config?.id;s-=1)if(Boolean(t[s]?.contentItem?.config?.isClosable)){n=!1;break}return n}canCloseAny(){const e=this.getAllTabs();let t=!0;for(let n=e.length-1;n>0;n-=1)if(Boolean(e[n]?.contentItem?.config?.isClosable)){t=!1;break}return t}render(){const{additionalActions:e,glContainer:t}=this.props,n=[...e],s=t.tab?.contentItem?.config?.isClosable;return n.push({title:"Close",order:10,group:ie.groups.low,action:this.handleCloseTab,disabled:s===void 0||!s}),n.push(()=>({title:"Close Tabs to Right",order:20,group:ie.groups.low,action:this.handleCloseTabsRight,disabled:this.canCloseTabsRight()})),n.push(()=>({title:"Close All",order:30,group:ie.groups.low,action:this.handleCloseTabsAll,disabled:this.canCloseAny()})),r.jsx(ie,{actions:n})}}const by=Cy;class Sy extends v.PureComponent{static defaultProps={isShared:!1,isOwner:!0,itemType:"Item",value:""};constructor(e){super(e),this.handleRenameDialogOpened=this.handleRenameDialogOpened.bind(this),this.handleRenameInputChange=this.handleRenameInputChange.bind(this),this.handleRenameCancel=this.handleRenameCancel.bind(this),this.handleRenameSubmit=this.handleRenameSubmit.bind(this),this.renameInputRef=de.createRef();const{value:t}=e;this.state={value:t,valueWasValidated:!1}}componentDidUpdate(e){const{isShown:t}=e,{isShown:n}=this.props;n&&!t&&this.resetState()}renameInputRef;resetState(){const{value:e}=this.props;this.setState({value:e,valueWasValidated:!1})}handleRenameDialogOpened(){this.renameInputRef?.current?.focus()}handleRenameInputChange(e){this.setState({value:e.target.value})}handleRenameCancel(){const{onCancel:e}=this.props;e()}handleRenameSubmit(e){e.stopPropagation(),e.preventDefault();const{value:t}=this.state,n=t?.trim();if(n!==void 0&&n!==""){const{onSubmit:s}=this.props;s(n)}else this.setState({value:n,valueWasValidated:!0})}renderRenameDialog(){const{isShared:e,isOwner:t,itemType:n}=this.props,{value:s,valueWasValidated:i}=this.state;return r.jsxs("form",{className:Y("p-3",{"was-validated":i}),onSubmit:this.handleRenameSubmit,noValidate:!0,role:"presentation",onMouseDown:o=>{o.stopPropagation()},onMouseUp:o=>{o.stopPropagation()},children:[r.jsxs("div",{className:"form-group",children:[r.jsxs("label",{htmlFor:`rename-dialog-${n}-input`,children:["Rename ",n]}),r.jsx("input",{type:"text",className:"form-control",id:`rename-dialog-${n}-input`,value:s??void 0,ref:this.renameInputRef,onChange:this.handleRenameInputChange,required:!0}),r.jsxs("div",{className:"invalid-feedback",children:[n," name cannot be empty"]}),(e||!t)&&r.jsxs("div",{className:"pt-2",children:["Renaming this ",n," will rename for all users."]})]}),r.jsxs("div",{className:"text-right",children:[r.jsx(B,{kind:"secondary",className:"mr-2",onClick:this.handleRenameCancel,children:"Cancel"}),r.jsx(B,{kind:"primary",type:"submit",children:"Rename"})]})]})}render(){const{isShown:e,onCancel:t}=this.props;return r.jsx(Vl,{isShown:e,onEntered:this.handleRenameDialogOpened,onExited:t,options:{placement:"bottom"},interactive:!0,closeOnBlur:!0,children:this.renderRenameDialog()})}}const wy=ne.module("Panel");class vy extends v.PureComponent{static defaultProps={className:"",onTab:()=>{},onTabClicked:()=>{},onClearAllFilters:()=>{},onFocus:()=>{},onBlur:()=>{},onHide:()=>{},onResize:()=>{},onSessionClose:()=>{},onSessionOpen:()=>{},onBeforeShow:()=>{},onShow:()=>{},onTabBlur:()=>{},onTabFocus:()=>{},renderTabTooltip:null,additionalActions:[],errorMessage:null,isLoading:!1,isLoaded:!0,isClonable:!1,isRenamable:!1};constructor(e){super(e),this.handleClearAllFilters=this.handleClearAllFilters.bind(this),this.handleCopyPanel=this.handleCopyPanel.bind(this),this.handleFocus=this.handleFocus.bind(this),this.handleBlur=this.handleBlur.bind(this),this.handleHide=this.handleHide.bind(this),this.handleResize=this.handleResize.bind(this),this.handleSessionClosed=this.handleSessionClosed.bind(this),this.handleSessionOpened=this.handleSessionOpened.bind(this),this.handleBeforeShow=this.handleBeforeShow.bind(this),this.handleShow=this.handleShow.bind(this),this.handleTabBlur=this.handleTabBlur.bind(this),this.handleTabFocus=this.handleTabFocus.bind(this),this.handleRenameCancel=this.handleRenameCancel.bind(this),this.handleRenameSubmit=this.handleRenameSubmit.bind(this),this.handleShowRenameDialog=this.handleShowRenameDialog.bind(this),this.handleTabClicked=this.handleTabClicked.bind(this),this.handleTab=this.handleTab.bind(this);const{glContainer:t}=this.props;this.state={title:K.getTitleFromContainer(t),showRenameDialog:!1}}componentDidMount(){const{componentPanel:e,glContainer:t,glEventHub:n}=this.props;t.on("resize",this.handleResize),t.on("show",this.handleBeforeShow),t.on("shown",this.handleShow),t.on("hide",this.handleHide),t.on("tab",this.handleTab),t.on("tabClicked",this.handleTabClicked),n.on($t.SESSION_CLOSED,this.handleSessionClosed),n.on($t.SESSION_OPENED,this.handleSessionOpened),n.on(Yo.focus,this.handleTabFocus),n.on(Yo.blur,this.handleTabBlur),n.on(Ze.CLEAR_ALL_FILTERS,this.handleClearAllFilters),n.emit(Ee.MOUNT,e)}componentWillUnmount(){const{componentPanel:e,glContainer:t,glEventHub:n}=this.props;t.off("resize",this.handleResize),t.off("show",this.handleBeforeShow),t.off("shown",this.handleShow),t.off("hide",this.handleHide),t.off("tab",this.handleTab),t.off("tabClicked",this.handleTabClicked),n.off($t.SESSION_CLOSED,this.handleSessionClosed),n.off($t.SESSION_OPENED,this.handleSessionOpened),n.off(Yo.focus,this.handleTabFocus),n.off(Yo.blur,this.handleTabBlur),n.off(Ze.CLEAR_ALL_FILTERS,this.handleClearAllFilters),n.emit(Ee.UNMOUNT,e)}handleTab(e){e!=null&&this.setState({title:K.getTitleFromTab(e)}),this.forceUpdate();const{onTab:t}=this.props;t(e)}handleTabClicked(e){const{onTabClicked:t}=this.props;t(e)}handleClearAllFilters(...e){const{onClearAllFilters:t}=this.props;t(...e)}handleFocus(e){const{componentPanel:t,glEventHub:n}=this.props;n.emit(Ee.FOCUS,t);const{onFocus:s}=this.props;s(e)}handleBlur(e){const{onBlur:t}=this.props;t(e)}handleHide(...e){const{onHide:t}=this.props;t(...e)}handleResize(...e){const{onResize:t}=this.props;t(...e)}handleSessionClosed(e){const{onSessionClose:t}=this.props;t(e)}handleSessionOpened(e,t){const{onSessionOpen:n}=this.props;n(e,t)}handleBeforeShow(...e){const{onBeforeShow:t}=this.props;t(...e)}handleShow(...e){const{onShow:t}=this.props;t(...e)}handleTabBlur(...e){const{onTabBlur:t}=this.props;t(...e)}handleTabFocus(...e){const{onTabFocus:t}=this.props;t(...e)}handleRenameCancel(){this.setState({showRenameDialog:!1})}handleShowRenameDialog(){this.setState({showRenameDialog:!0})}handleRenameSubmit(e){const{glContainer:t}=this.props;this.setState({showRenameDialog:!1,title:e});const n=K.getRootFromContainer(t),s=K.getComponentConfigFromContainer(t);N(s),K.renameComponent(n,s,e)}handleCopyPanel(){const{glContainer:e,glEventHub:t}=this.props,n=K.getRootFromContainer(e),s=K.getComponentConfigFromContainer(e);if(s==null){wy.error("Could not get component config from container",e);return}const i=K.cloneComponent(n,s);i!==null&&t.emit(Ee.CLONED,this,i)}getCloneAction(){return{title:"Copy Panel",order:10,group:ie.groups.high,action:this.handleCopyPanel}}getRenameAction(){return{title:"Rename",order:10,group:ie.groups.medium,action:this.handleShowRenameDialog}}getAdditionActions=ge((e,t,n)=>{const s=[];return t&&s.push(this.getCloneAction()),n&&s.push(this.getRenameAction()),[...s,...e]});render(){const{children:e,className:t,renderTabTooltip:n,glContainer:s,additionalActions:i,errorMessage:o,isLoaded:l,isLoading:a,isClonable:d,isRenamable:h}=this.props,{tab:u}=s,{showRenameDialog:m,title:g}=this.state;return r.jsxs("div",{className:Y("h-100 w-100 iris-panel",t),onFocusCapture:this.handleFocus,onBlurCapture:this.handleBlur,children:[e,r.jsx($l,{errorMessage:o,isLoaded:l,isLoading:a}),u!=null&&al.createPortal(r.jsxs(r.Fragment,{children:[r.jsx(by,{glContainer:s,additionalActions:this.getAdditionActions(i,d,h)}),h&&r.jsx(Sy,{isShown:m,value:g,itemType:"Panel",onCancel:this.handleRenameCancel,onSubmit:this.handleRenameSubmit}),n!=null&&r.jsx(ot,{interactive:!0,options:{placement:"bottom"},popperClassName:"panel-tab-popper",children:n()})]}),u.element[0])]})}}const qn=vy;function ia(c){const{widgetType:e,widgetName:t,glContainer:n,description:s,children:i}=c,o=K.getTitleFromContainer(n);return r.jsxs("div",{className:"tab-tooltip-container",children:[r.jsxs("div",{className:"row flex-nowrap align-items-start",children:[r.jsx("span",{className:"tab-tooltip-title",children:r.jsxs("b",{children:[e," Name "]})}),r.jsx("span",{className:"tab-tooltip-name",children:t}),r.jsx(Bl,{className:"tab-tooltip-copy",tooltip:"Copy name",copy:t})]}),t!==o&&r.jsxs("div",{className:"row",children:[r.jsx("span",{className:"tab-tooltip-title",children:r.jsx("b",{children:"Display Name"})}),r.jsx("span",{className:"tab-tooltip-name",children:o})]}),s&&r.jsx("div",{className:"row",children:r.jsx("span",{className:"tab-tooltip-description",children:s})}),i]})}ia.propTypes={glContainer:kr.Container.isRequired,widgetType:z.string,widgetName:z.string,description:z.string,children:z.node};ia.defaultProps={widgetType:"",widgetName:"",description:null,children:null};class Ty extends v.PureComponent{static defaultProps={className:"",errorMessage:null,isClonable:!0,isDisconnected:!1,isLoading:!1,isLoaded:!0,isRenamable:!0,showTabTooltip:!0,widgetName:"Widget",widgetType:"Widget",renderTabTooltip:null,description:"",onFocus:()=>{},onBlur:()=>{},onHide:()=>{},onClearAllFilters:()=>{},onResize:()=>{},onSessionClose:()=>{},onSessionOpen:()=>{},onShow:()=>{},onTabBlur:()=>{},onTabFocus:()=>{},onTabClicked:()=>{}};constructor(e){super(e),this.handleSessionClosed=this.handleSessionClosed.bind(this),this.handleSessionOpened=this.handleSessionOpened.bind(this),this.handleCopyName=this.handleCopyName.bind(this),this.state={isClientDisconnected:!1,isPanelDisconnected:!1,isWidgetDisconnected:!1,isWaitingForReconnect:!1,isPanelInactive:!1}}handleCopyName(){const{widgetName:e}=this.props;ho(e)}getErrorMessage(){const{errorMessage:e}=this.props,{isClientDisconnected:t,isPanelDisconnected:n,isWidgetDisconnected:s,isWaitingForReconnect:i}=this.state;if(e)return`${e}`;if(t&&n&&i)return`Disconnected from server.
32
32
  Check your internet connection.`;if(t&&n)return"Disconnected from server.";if(n){const{widgetName:o,widgetType:l}=this.props;return`Variable "${o}" not set.
33
- ${l} does not exist yet.`}if(s){const{widgetName:o}=this.props;return`${o} is unavailable.`}}getCachedRenderTabTooltip=ge((e,t,n,s,i)=>e?()=>r.jsx(ia,{glContainer:t,widgetType:n,widgetName:s,description:i}):null);handleSessionClosed(...e){const{onSessionClose:t}=this.props;this.setState({isPanelDisconnected:!0,isWaitingForReconnect:!1}),t(...e)}handleSessionOpened(...e){const{onSessionOpen:t}=this.props;t(...e)}render(){const{children:e,className:t,componentPanel:n,isLoaded:s,isLoading:i,glContainer:o,glEventHub:l,isDisconnected:a,isClonable:d,isRenamable:h,showTabTooltip:u,renderTabTooltip:m,widgetType:g,widgetName:p,description:C,onClearAllFilters:f,onHide:b,onFocus:w,onBlur:S,onResize:T,onShow:y,onTabBlur:E,onTabFocus:R,onTabClicked:x}=this.props,{isPanelDisconnected:D,isWidgetDisconnected:M,isPanelInactive:O}=this.state,H=this.getErrorMessage(),L=m??this.getCachedRenderTabTooltip(u,o,g,p,C),V=[{title:`Copy ${g} Name`,group:ie.groups.medium,order:20,action:this.handleCopyName}];return r.jsxs(qn,{className:Y(t,{disconnected:D||M||a,inactive:O}),componentPanel:n,glContainer:o,glEventHub:l,onClearAllFilters:f,onHide:b,onFocus:w,onBlur:S,onResize:T,onShow:y,onSessionClose:this.handleSessionClosed,onSessionOpen:this.handleSessionOpened,onTabBlur:E,onTabFocus:R,onTabClicked:x,renderTabTooltip:L,errorMessage:H,isLoaded:s,isLoading:i,isClonable:d,isRenamable:h,additionalActions:V,children:[e,O&&r.jsx("div",{className:"fill-parent-absolute"})]})}}const Gr=Ty,Pt=Object.freeze({DEFAULT:"DEFAULT",LINKER:"LINKER"}),Ey=new Map,oa=Object.freeze([]),ju=(c,e)=>jt(c,e).columns??oa,yy=(c,e)=>jt(c,e).filterSets??oa,zr=(c,e)=>jt(c,e).filters??oa,Kr=(c,e)=>jt(c,e).tableMap??Ey,Yr=(c,e)=>jt(c,e).isolatedLinkerPanelId,Ni=(c,e)=>jt(c,e).links??oa,qr=(c,e)=>jt(c,e).columnSelectionValidator,Ry=(c,e)=>jt(c,e).connection,Qs=(c,e)=>jt(c,e).sessionWrapper,xy=(c,e)=>t=>t(Fn(c,{connection:e})),Dy=(c,e)=>t=>t(Fn(c,{sessionWrapper:e})),Xr=(c,e)=>t=>t(Fn(c,{links:e})),Iy=(c,e)=>(t,n)=>{const s=Ni(n(),c),i=e.filter(o=>s.findIndex(l=>st(l.start,o.start)&&st(l.end,o.end))<0);return t(Xr(c,s.concat(i)))},Fy=(c,e)=>(t,n)=>{const i=Ni(n(),c).filter(o=>!e.includes(o.id));return t(Xr(c,i))},Hu=(c,e)=>t=>t(Fn(c,{isolatedLinkerPanelId:e})),Ny=(c,e)=>t=>t(Fn(c,{columnSelectionValidator:e})),ky=(c,e)=>t=>t(Fn(c,{consoleSettings:e})),My=(c,e)=>t=>t(Fn(c,{filterSets:e}));function Bu({columnMap:c,inputFilterMap:e,linkedColumnMap:t,onAdd:n,onOpenLinker:s,waitingFilterMap:i,waitingInputMap:o}){const l=v.useMemo(()=>{const g=Array.from(o.keys()),p=g.find(b=>e.get(b)!=null),C=g.find(b=>t.get(b)!=null),f=en.join(g.map(b=>`"${b}"`));return p!=null&&p&&C!=null&&C?`Use a filter control or linked table to set a value for ${f}`:p!=null&&p?`Set a filter control value for ${f}`:`Double click a row in a linked table to set a value for ${f}`},[e,t,o]),a=v.useMemo(()=>Array.from(c.values()),[c]),d=v.useCallback(g=>{g.stopPropagation(),g.preventDefault(),n(Array.from(i.values()))},[n,i]),h=v.useCallback(g=>{g.stopPropagation(),g.preventDefault(),s()},[s]),u=i.size>0,m=!u&&o.size>0;return r.jsx("div",{className:"chart-panel-overlay chart-filter-overlay",children:r.jsxs("div",{className:Y("chart-panel-overlay-content chart-filter-overlay-content",{"chart-filter-waiting-filter":u},{"chart-filter-waiting-input":m}),children:[u&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"info-message",children:"This plot requires a filter control to be added to the layout or a table link to be created on the following columns:"}),r.jsx("div",{className:"waiting-filter-list",children:a.map(g=>{const p=i.has(g.name),C=p?ws:dr;return r.jsxs("div",{className:Y("waiting-filter-item",{"is-invalid":p}),children:[r.jsx(ee,{icon:C}),g.name]},g.name)})}),r.jsxs("div",{children:[r.jsx(md,{onClick:d,className:"btn-primary",children:"Add Input Filters"}),r.jsx(md,{onClick:h,className:"btn-primary",children:"Open Linker Tool"})]})]}),m&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"info-message",children:"Waiting for User Input"}),r.jsx("div",{className:"",children:l})]})]})})}Bu.propTypes={columnMap:z.instanceOf(Map).isRequired,inputFilterMap:z.instanceOf(Map).isRequired,linkedColumnMap:z.instanceOf(Map).isRequired,onAdd:z.func.isRequired,onOpenLinker:z.func.isRequired,waitingFilterMap:z.instanceOf(Map).isRequired,waitingInputMap:z.instanceOf(Map).isRequired};function ro({columns:c,onColumnSelected:e,onMouseEnter:t,onMouseLeave:n}){return r.jsx("div",{className:"chart-panel-overlay chart-column-selector-overlay",children:r.jsxs("div",{className:Y("chart-panel-overlay-content"),children:[r.jsx("div",{className:"info-message",children:"This plot requires a filter control to be added to the layout or a table link to be created on the following columns:"}),r.jsx("div",{className:"waiting-column-select-list",children:c.map(s=>r.jsx(Kc,{className:Y("btn-chart-column-selector",ro.makeButtonClassName(s.name)),onClick:()=>e(s.name),onMouseEnter:()=>{t&&t(s)},onMouseLeave:n,disabled:!s.isValid,isLinked:s.isActive,children:s.name},s.name))})]})})}ro.makeButtonClassName=c=>`btn-chart-column-selector-${c}`;ro.defaultProps={onMouseEnter:()=>{},onMouseLeave:()=>{}};function il(c){return c.settings!==void 0}const Lt=ne.module("ChartPanel"),Ly=150;function Oy(c){return c.inputFilters!=null}function Ay(c){return c.panelState!=null}class _y extends v.Component{static defaultProps={columnSelectionValidator:null,isLinkerActive:!1,source:null,sourcePanel:null,panelState:null,settings:{}};static displayName="ChartPanel";static COMPONENT="ChartPanel";constructor(e){super(e),this.handleColumnSelected=this.handleColumnSelected.bind(this),this.handleColumnMouseEnter=this.handleColumnMouseEnter.bind(this),this.handleColumnMouseLeave=this.handleColumnMouseLeave.bind(this),this.handleDisconnect=this.handleDisconnect.bind(this),this.handleReconnect=this.handleReconnect.bind(this),this.handleFilterAdd=this.handleFilterAdd.bind(this),this.handleHide=this.handleHide.bind(this),this.handleError=this.handleError.bind(this),this.handleLoadError=this.handleLoadError.bind(this),this.handleLoadSuccess=this.handleLoadSuccess.bind(this),this.handleResize=this.handleResize.bind(this),this.handleSettingsChanged=this.handleSettingsChanged.bind(this),this.handleOpenLinker=this.handleOpenLinker.bind(this),this.handleShow=this.handleShow.bind(this),this.handleSourceColumnChange=this.handleSourceColumnChange.bind(this),this.handleSourceFilterChange=this.handleSourceFilterChange.bind(this),this.handleSourceSortChange=this.handleSourceSortChange.bind(this),this.handleTabBlur=this.handleTabBlur.bind(this),this.handleTabFocus=this.handleTabFocus.bind(this),this.handleUpdate=this.handleUpdate.bind(this),this.updateModelFromSource=Ye(this.updateModelFromSource.bind(this),Ly),this.handleClearAllFilters=this.handleClearAllFilters.bind(this),this.panelContainer=de.createRef(),this.chart=de.createRef(),this.pending=new Yn;const{metadata:t,panelState:n}=e,{filterValueMap:s=[],settings:i={}}=n??{};this.state={settings:i,error:void 0,isActive:!1,isDisconnected:!1,isLoading:!1,isLoaded:!1,isLinked:t!=null&&il(t)&&t.settings.isLinked,filterMap:new Map(s),filterValueMap:new Map(s),model:void 0,columnMap:new Map,panelState:n}}componentDidMount(){this.isHidden()||(this.setState({isActive:!0}),this.initModel())}componentDidUpdate(e,t){const{inputFilters:n,source:s}=this.props,{columnMap:i,model:o,filterMap:l,filterValueMap:a,isLinked:d,settings:h}=this.state;o&&(i!==t.columnMap&&this.pruneFilterMaps(),n!==e.inputFilters&&this.updateChangedInputFilters(n,e.inputFilters),l!==t.filterMap?this.updateFilters():a!==t.filterValueMap&&this.updatePanelState(),h!==t.settings&&Hd(o)&&(o.updateSettings(h),this.updatePanelState()),d!==t.isLinked?s&&(d?(this.startListeningToSource(s),this.updateModelFromSource()):this.stopListeningToSource(s)):d&&s!==e.source&&(e.source&&this.stopListeningToSource(e.source),s&&(this.startListeningToSource(s),this.updateModelFromSource())))}componentWillUnmount(){this.pending.cancel();const{source:e}=this.props;e&&this.stopListeningToSource(e)}panelContainer;chart;pending;initModel(){this.setState({isLoading:!0,isLoaded:!1,error:void 0});const{makeModel:e}=this.props;this.pending.add(e(),t=>{t.close()}).then(this.handleLoadSuccess,this.handleLoadError)}getWaitingInputMap=ge((e,t,n)=>{if(!e)return new Map;const s=new Map(t);return n.forEach((i,o)=>{s.delete(o)}),s});getWaitingFilterMap=ge((e,t,n,s,i)=>{if(!e)return new Map;const o=new Map(t);return n.forEach((l,a)=>{o.delete(a)}),i.forEach((l,a)=>{o.delete(a)}),s.forEach((l,a)=>{o.delete(a)}),o});getInputFilterColumnMap=ge((e,t)=>{const n=new Map;for(let s=0;s<t.length;s+=1){const i=t[s],{name:o,type:l}=i,a=e.get(o);a!=null&&a.type===l&&n.set(o,i)}return n});getLinkedColumnMap=ge((e,t)=>{const n=new Map,s=K.getIdFromPanel(this);for(let i=0;i<t.length;i+=1){const o=t[i];let l=null;if(o.start!=null&&o.start.panelId===s&&e.has(o.start.columnName)?l=o.start.columnName:o.end&&o.end.panelId===s&&e.has(o.end.columnName)&&(l=o.end.columnName),l!=null&&e.has(l)){const a=e.get(l);N(a),n.set(l,a)}}return n});getSelectorColumns=ge((e,t,n)=>Array.from(e.values()).map(s=>({name:s.name,type:s.type,isValid:n?n(this,s):!1,isActive:t.has(s.name)})));startListeningToSource(e){Lt.debug("startListeningToSource",e),e.addEventListener(I.Table.EVENT_CUSTOMCOLUMNSCHANGED,this.handleSourceColumnChange),e.addEventListener(I.Table.EVENT_FILTERCHANGED,this.handleSourceFilterChange),e.addEventListener(I.Table.EVENT_SORTCHANGED,this.handleSourceSortChange)}stopListeningToSource(e){Lt.debug("stopListeningToSource",e),e.removeEventListener(I.Table.EVENT_CUSTOMCOLUMNSCHANGED,this.handleSourceColumnChange),e.removeEventListener(I.Table.EVENT_FILTERCHANGED,this.handleSourceFilterChange),e.removeEventListener(I.Table.EVENT_SORTCHANGED,this.handleSourceSortChange)}loadModelIfNecessary(){const{isActive:e,isLoaded:t,isLoading:n}=this.state;e&&!t&&!n&&this.initModel()}isHidden(){const{glContainer:e}=this.props,{isHidden:t}=e;return t}handleColumnSelected(e){const{glEventHub:t}=this.props,{columnMap:n}=this.state;t.emit(Qa.COLUMN_SELECTED,this,n.get(e))}handleColumnMouseEnter({type:e,name:t}){const{columnSelectionValidator:n}=this.props;Lt.debug("handleColumnMouseEnter",n,e,t),n&&n(this,{type:e,name:t})}handleColumnMouseLeave(){const{columnSelectionValidator:e}=this.props;Lt.debug("handleColumnMouseLeave",e),e&&e(this,void 0)}handleDisconnect(){this.setState({error:new Error("Figure disconnected"),isDisconnected:!0})}handleFilterAdd(e){for(let t=0;t<e.length;t+=1)this.openInputFilter(e[t])}handleOpenLinker(){const{localDashboardId:e,setActiveTool:t,setDashboardIsolatedLinkerPanelId:n}=this.props;n(e,void 0),t(Pt.LINKER)}handleReconnect(){this.setState({isDisconnected:!1,error:void 0}),this.sendColumnChange(),this.updateColumnFilters()}handleLoadSuccess(e){Lt.debug("handleLoadSuccess");const{model:t}=this.state;this.setState({model:e,isLoaded:!0},()=>{const{inputFilters:n,source:s}=this.props,{filterMap:i,isLinked:o}=this.state;e!==t&&(this.sendColumnChange(),this.updateColumnFilters(),this.updateInputFilters(n,i.size>0||e.isFilterRequired()),s&&o&&(this.startListeningToSource(s),this.updateModelFromSource()))})}handleLoadError(e){ye.isCanceled(e)||(Lt.error("handleLoadError",e),this.setState({error:e,isLoading:!1}))}handleSourceColumnChange(){this.updateModelFromSource()}handleSourceFilterChange(){this.updateModelFromSource()}handleSourceSortChange(){this.updateModelFromSource()}updateModelFromSource(){const{metadata:e,source:t}=this.props,{isLinked:n,model:s}=this.state;if(!n||!s||!t){Lt.debug2("updateModelFromSource ignoring",n,s,t);return}if(this.pending.cancel(),il(e)){const{settings:i}=e;this.pending.add(I.plot.Figure.create(Qe.makeFigureSettings(i,t))).then(o=>{Hd(s)&&s.setFigure(o)}).catch(this.handleLoadError)}this.updatePanelState()}updatePanelState(){const{sourcePanel:e}=this.props,{panelState:t,filterValueMap:n,settings:s}=this.state;let{tableSettings:i}=t??{};if(e&&Oy(e.props)&&Ay(e.state)){const{inputFilters:o}=e.props,{panelState:l}=e.state;l!=null&&(i=Se.extractTableSettings(l,o))}this.setState({panelState:{settings:s,tableSettings:i,filterValueMap:Array.from(n)}})}handleError(){this.setState({isLoading:!1})}handleResize(){this.updateChart()}handleSettingsChanged(e){this.setState(({settings:t})=>{const n={...t,...e};return Lt.debug("Updated settings",n),{settings:n}})}handleHide(){this.setActive(!1)}handleShow(){this.setActive(!0)}handleTabBlur(){this.setActive(!1)}handleTabFocus(){const e=this.isHidden();this.setActive(!e)}handleUpdate(){this.setState({isLoading:!1})}handleClearAllFilters(){this.setState({filterValueMap:new Map,filterMap:new Map}),this.updatePanelState()}openInputFilter(e){const{glEventHub:t}=this.props,{name:n,type:s}=e;t.emit(Ze.OPEN_INPUT,{title:`${n} Filter`,panelState:{name:n,type:s,isValueShown:!0},createNewStack:!0,focusElement:"input"})}setActive(e){this.setState({isActive:e},()=>{e&&(this.loadModelIfNecessary(),this.updateChart())})}sendColumnChange(){const{model:e}=this.state;if(!e)return;const{glEventHub:t}=this.props;t.emit(Ze.COLUMNS_CHANGED,this,Array.from(e.getFilterColumnMap().values()))}getCoordinateForColumn(e){const t=ro.makeButtonClassName(e);if(!this.panelContainer.current)return null;const s=this.panelContainer.current.querySelector(`.${t}`)?.getBoundingClientRect()??null;if(s==null||s.width<=0||s.height<=0)return null;const i=s.left+s.width/2,o=s.bottom;return[i,o]}setFilterMap(e){Lt.debug("setFilterMap",e),this.setState(t=>{const{columnMap:n,filterMap:s}=t;let i=null;const o=new Map(t.filterValueMap);return e.forEach(({columnType:l,filterList:a},d)=>{const h=n.get(d);if(h==null||h.type!==l)return;if(a.length<1){Lt.debug("Ignoring empty filterList for column",d);return}const{value:u}=a[0];o.set(d,u),s.get(d)!==u&&(i===null&&(i=new Map(s)),i.set(d,u))}),{filterValueMap:o,filterMap:i??s}})}unsetFilterValue(e){this.setState(t=>{const{inputFilters:n}=this.props,{columnMap:s}=t;let{filterMap:i,filterValueMap:o}=t;if(!o.has(e))return null;o=new Map(t.filterValueMap),o.delete(e);const l=this.getInputFilterColumnMap(s,n);if(l.has(e)){const a=i.get(e),d=l.get(e)?.value;d!=null&&a!==d&&(i=new Map(t.filterMap),d.length>0?i.set(e,d):i.delete(e))}else i=new Map(t.filterMap),i.delete(e);return{filterMap:i,filterValueMap:o}})}updateChangedInputFilters(e,t){const n=t.filter(i=>e.find(o=>o.name===i.name&&o.type===i.type)===void 0);n.length>0&&this.deleteInputFilters(n);const s=e.filter(i=>!t.includes(i));s.length>0&&this.updateInputFilters(s)}updateInputFilters(e,t=!1){this.setState(n=>{const{columnMap:s}=n,i=new Map(n.filterValueMap),o=new Map(n.filterMap),l=t?{filterMap:o,filterValueMap:i}:{};for(let a=0;a<e.length;a+=1){const{name:d,type:h,value:u}=e[a],m=s.get(d);m!=null&&m.type===h&&(u!=null&&o.get(d)!==u&&(u===""?o.delete(d):o.set(d,u),l.filterMap=o),i.has(d)&&(i.delete(d),l.filterValueMap=i))}return Lt.debug("updateInputFilters",l),l})}deleteInputFilters(e,t=!1){this.setState(n=>{const{columnMap:s,filterValueMap:i}=n,o=new Map(n.filterMap);let l=t;for(let a=0;a<e.length;a+=1){const{name:d,type:h}=e[a],u=s.get(d);if(u!=null&&u.type===h&&o.has(d)){const m=o.get(d);if(i.has(d)){const g=i.get(d);g!==m&&g!=null&&(l=!0,o.set(d,g))}else l=!0,o.delete(d)}}return Lt.debug("deleteInputFilters",l),l?{filterMap:o}:null})}updateColumnFilters(){this.setState(({model:e})=>e?{columnMap:e.getFilterColumnMap()}:null)}updateFilters(){const{columnMap:e,filterMap:t,model:n}=this.state;N(n);const s=this.getWaitingInputMap(n.isFilterRequired(),e,t);if(n.setFilter(t),t.size>0&&s.size===0){const i=n.getDefaultTitle(),o=en.join(Array.from(t.entries()).map(([l,a])=>`${l}: ${a}`));i?n.setTitle(`${i}<br><span style="font-size: smaller">${o}</span>`):n.setTitle(o),Lt.debug2("updateFilters filters set",t),this.setState({isLoading:!0})}else Lt.debug2("updateFilters waiting on inputs",s),n.setTitle(n.getDefaultTitle()),this.setState({isLoading:!1});this.updatePanelState()}pruneFilterMaps(){this.setState(e=>{const{columnMap:t}=e,n=new Map(e.filterMap),s=new Map(e.filterValueMap),i={};return e.filterValueMap.forEach((o,l)=>{t.has(l)||(s.delete(l),i.filterValueMap=s)}),e.filterMap.forEach((o,l)=>{t.has(l)||(n.delete(l),i.filterMap=n)}),i})}updateChart(){this.chart.current&&this.chart.current.updateDimensions()}render(){const{columnSelectionValidator:e,glContainer:t,glEventHub:n,inputFilters:s,isLinkerActive:i,links:o,metadata:l,settings:a}=this.props,{columnMap:d,filterMap:h,error:u,model:m,isActive:g,isDisconnected:p,isLoaded:C,isLoading:f}=this.state;let b;il(l)?b=l.table:b=l.figure;const w=this.getInputFilterColumnMap(d,s),S=this.getLinkedColumnMap(d,o),T=m!=null?this.getWaitingInputMap(m.isFilterRequired(),d,h):new Map,y=m!=null?this.getWaitingFilterMap(m.isFilterRequired(),d,h,S,w):new Map,E=u!=null?`Unable to open chart. ${u}`:void 0,R=T.size>0,x=d.size>0&&i;return r.jsx(Gr,{className:Y("iris-chart-panel",{"input-required":R}),componentPanel:this,glContainer:t,glEventHub:n,onHide:this.handleHide,onClearAllFilters:this.handleClearAllFilters,onResize:this.handleResize,onShow:this.handleShow,onTabBlur:this.handleTabBlur,onTabFocus:this.handleTabFocus,errorMessage:E,isDisconnected:p,isLoading:f,isLoaded:C,widgetName:b,widgetType:"Chart",children:r.jsxs("div",{ref:this.panelContainer,className:"chart-panel-container h-100 w-100",children:[r.jsx("div",{className:"chart-container h-100 w-100",children:C&&m&&r.jsx(hC,{isActive:g,model:m,settings:a,ref:this.chart,onDisconnect:this.handleDisconnect,onReconnect:this.handleReconnect,onUpdate:this.handleUpdate,onError:this.handleError,onSettingsChanged:this.handleSettingsChanged})}),r.jsx(Wt,{in:R&&!x&&!f,timeout:Je.transitionMs,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx(Bu,{inputFilterMap:w,linkedColumnMap:S,onAdd:this.handleFilterAdd,onOpenLinker:this.handleOpenLinker,columnMap:d,waitingFilterMap:y,waitingInputMap:T})}),r.jsx(Wt,{in:x,timeout:Je.transitionMs,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx(ro,{columns:this.getSelectorColumns(d,S,e),onColumnSelected:this.handleColumnSelected,onMouseEnter:this.handleColumnMouseEnter,onMouseLeave:this.handleColumnMouseLeave})})]})})}}const Py=(c,e)=>{const{localDashboardId:t,metadata:n}=e;let s;n!=null&&(s=n.sourcePanelId);const i=Kr(c,t),o=au(c,t),l=Xl(c),a=Yr(c,t),d=l===Pt.LINKER&&a===void 0;return{columnSelectionValidator:qr(c,t),isLinkerActive:d,inputFilters:zr(c,t),links:Ni(c,t),source:s!=null?i.get(s):void 0,sourcePanel:s!=null?o.get(s):void 0,settings:wt(c)}},jy=St(Py,{setActiveTool:Ql,setDashboardIsolatedLinkerPanelId:Hu},null,{forwardRef:!0})(_y),Ei=jy;const qo=ne.module("CommandHistoryPanel");class Zr extends v.Component{static COMPONENT="CommandHistoryPanel";static TITLE="Command History";static handleError(e){qo.error(e)}constructor(e){super(e),this.handleFocusHistory=this.handleFocusHistory.bind(this),this.handleSessionOpened=this.handleSessionOpened.bind(this),this.handleSessionClosed=this.handleSessionClosed.bind(this),this.handleShow=this.handleShow.bind(this),this.handleSendToConsole=this.handleSendToConsole.bind(this),this.handleSendToNotebook=this.handleSendToNotebook.bind(this),this.container=de.createRef(),this.pending=new Yn;const{session:t,sessionId:n,language:s}=e;this.state={panelState:{},session:t,sessionId:n,language:s,contextActions:[{action:this.handleFocusHistory,shortcut:Nt.COMMAND_HISTORY.FOCUS_HISTORY}]}}componentDidMount(){const{glEventHub:e,session:t}=this.props;e.on($t.FOCUS_HISTORY,this.handleFocusHistory),t!=null&&this.loadTable()}componentWillUnmount(){const{glEventHub:e}=this.props;e.off($t.FOCUS_HISTORY,this.handleFocusHistory),this.pending.cancel()}container;pending;handleFocusHistory(){this.container.current&&this.container.current.focus()}handleShow(){this.container.current?.restoreScrollPosition()}handleSessionOpened(e,{language:t,sessionId:n}){this.setState({session:e,sessionId:n,language:t},()=>{this.loadTable()})}handleSessionClosed(){this.pending.cancel(),this.setState({session:void 0,language:void 0,table:void 0})}handleSendToNotebook(e,t=!1){const{session:n,language:s}=this.state;if(qo.debug("handleSendToNotebook",n,e),!n){qo.error("Session is not connected.");return}const{glEventHub:i}=this.props;i.emit(t?Ue.CREATE_NOTEBOOK:Ue.SEND_TO_NOTEBOOK,n,s,e)}handleSendToConsole(e,t=!0,n=!1){qo.debug("handleSendToConsole",e);const{glEventHub:s}=this.props;s.emit($t.SEND_COMMAND,e,t,n)}loadTable(){const{commandHistoryStorage:e}=this.props,{language:t,sessionId:n}=this.state;N(t),N(n),this.pending.add(e.getTable(t,n,Date.now()),s=>s.close()).then(s=>{this.setState({table:s})}).catch(Zr.handleError)}render(){const{glContainer:e,glEventHub:t,commandHistoryStorage:n}=this.props,{language:s,contextActions:i,table:o}=this.state;return r.jsxs(qn,{className:"command-history-pane",componentPanel:this,glContainer:e,glEventHub:t,onSessionOpen:this.handleSessionOpened,onSessionClose:this.handleSessionClosed,onShow:this.handleShow,children:[!o&&r.jsx("div",{className:"command-history-disconnected-message",children:"Waiting for console connection"}),o&&s!=null&&r.jsxs(r.Fragment,{children:[r.jsx(qf,{ref:this.container,language:s,sendToNotebook:this.handleSendToNotebook,sendToConsole:this.handleSendToConsole,table:o,commandHistoryStorage:n}),r.jsx(ie,{actions:i})]})]})}}const Hy=(c,e)=>{const t=wh(c),n=Qs(c,e.localDashboardId),{session:s,config:i}=n??{},{type:o,id:l}=i??{};return{commandHistoryStorage:t,language:o,session:s,sessionId:l}},By=St(Hy,null,null,{forwardRef:!0})(Zr),Il=By;const Xo=ne.module("ConsolePanel"),Uy=500,Vy=Object.freeze({consoleSettings:{},itemIds:[]});class $y extends v.PureComponent{static COMPONENT="ConsolePanel";static TITLE="Console";constructor(e){super(e),this.handleFocusCommandHistory=this.handleFocusCommandHistory.bind(this),this.handleOpenObject=this.handleOpenObject.bind(this),this.handleCloseObject=this.handleCloseObject.bind(this),this.handleResize=this.handleResize.bind(this),this.handleSettingsChange=this.handleSettingsChange.bind(this),this.handleShow=this.handleShow.bind(this),this.handlePanelMount=this.handlePanelMount.bind(this),this.consoleRef=de.createRef();const{panelState:t}=e,n={...Vy,...t||{}},{consoleSettings:s,itemIds:i}=n;this.state={consoleSettings:s,itemIds:new Map(i),objectMap:new Map,error:void 0,panelState:n}}componentDidMount(){const{glEventHub:e}=this.props;this.closeDisconnectedPanels(),e.on(Ee.MOUNT,this.handlePanelMount),this.subscribeToFieldUpdates()}componentDidUpdate(e,t){const{consoleSettings:n,itemIds:s}=this.state;(t.consoleSettings!==n||t.itemIds!==s)&&this.savePanelState()}componentWillUnmount(){const{glEventHub:e}=this.props;this.savePanelState.flush(),e.off(Ee.MOUNT,this.handlePanelMount),this.objectSubscriptionCleanup?.()}consoleRef;objectSubscriptionCleanup;subscribeToFieldUpdates(){const{sessionWrapper:e}=this.props,{session:t}=e;this.objectSubscriptionCleanup=t.subscribeToFieldUpdates(n=>{Xo.debug("Got updates",n),this.setState(({objectMap:s})=>{const{updated:i,created:o,removed:l}=n,a=[...i,...l],d=new Map(s);return a.forEach(u=>{const{title:m}=u;m!==void 0&&d.delete(m)}),[...i,...o].forEach(u=>{u.title!==void 0&&d.set(u.title,u)}),{objectMap:d}})})}setItemId(e,t){this.setState(({itemIds:n})=>{const s=new Map(n);return s.set(e,t),{itemIds:s}})}getItemId(e,t=!0){const{itemIds:n}=this.state;let s=n.get(e);return s==null&&t&&(s=qe.generate(),this.setItemId(e,s)),s}handleTabFocus(){this.consoleRef.current?.focus()}handlePanelMount(e){const{itemIds:t}=this.state,n=e?.props?.id,s=e?.props?.metadata?.sourcePanelId;n&&s&&new Set(t.values()).has(s)&&this.setItemId(n,n)}handleFocusCommandHistory(){const{glEventHub:e}=this.props;e.emit($t.FOCUS_HISTORY)}handleResize(){this.updateDimensions()}handleShow(){this.updateDimensions()}handleOpenObject(e){const{sessionWrapper:t}=this.props,{session:n}=t;this.openWidget(e,n)}handleCloseObject(e){const{title:t}=e;if(t!==void 0){const n=this.getItemId(t,!1),{glEventHub:s}=this.props;s.emit(Ee.CLOSE,n)}}handleSettingsChange(e){const{glEventHub:t}=this.props;Xo.debug("handleSettingsChange",e),this.setState({consoleSettings:e}),t.emit($t.SETTINGS_CHANGED,e)}openWidget(e,t){const{glEventHub:n}=this.props,{title:s}=e;N(s);const i=this.getItemId(s),o={fetch:()=>t.getObject(e),panelId:i,widget:e};Xo.debug("openWidget",o),n.emit(Ee.OPEN,o)}addCommand(e,t=!0,n=!1){this.consoleRef.current?.addCommand(e,t,n)}closeDisconnectedPanels(e=!1){const{consoleSettings:t,itemIds:n}=this.state,{isClosePanelsOnDisconnectEnabled:s=!0}=t;if(!s&&!e)return;const i=[...n.values()],{glEventHub:o}=this.props;i.forEach(l=>{o.emit(Ee.CLOSE,l)}),this.setState({itemIds:new Map})}savePanelState=Ye(()=>{const{consoleSettings:e,itemIds:t}=this.state,n={consoleSettings:e,itemIds:[...t]};Xo.debug("Saving panel state",n),this.setState({panelState:n})},Uy);updateDimensions(){this.consoleRef.current?.updateDimensions()}render(){const{commandHistoryStorage:e,glContainer:t,glEventHub:n,sessionWrapper:s,timeZone:i,unzip:o}=this.props,{consoleSettings:l,error:a,objectMap:d}=this.state,{config:h,session:u,connection:m,details:g={}}=s,{workerName:p,processInfoId:C}=g,{id:f,type:b}=h;return r.jsx(qn,{className:"iris-panel-console",componentPanel:this,glContainer:t,glEventHub:n,onResize:this.handleResize,onShow:this.handleShow,onTabFocus:this.handleTabFocus,errorMessage:a!=null?`${a}`:void 0,children:u!=null&&r.jsx(Af,{ref:this.consoleRef,settings:l,session:u,focusCommandHistory:this.handleFocusCommandHistory,openObject:this.handleOpenObject,closeObject:this.handleCloseObject,commandHistoryStorage:e,onSettingsChange:this.handleSettingsChange,language:b,statusBarChildren:r.jsxs(r.Fragment,{children:[r.jsx("div",{children:" "}),r.jsx("div",{children:rh.LANGUAGE_MAP.get(b)}),p!=null&&r.jsxs(r.Fragment,{children:[r.jsx("div",{children:" • "}),p]}),C!=null&&r.jsxs(r.Fragment,{children:[r.jsx("div",{children:" • "}),C,r.jsx("div",{children:" •"})]}),r.jsx("div",{children:" "}),r.jsx("div",{children:r.jsx(mC,{connection:m,defaultUpdateInterval:10*1e3,hoverUpdateInterval:3*1e3,monitorDuration:10*60*1e3})}),r.jsx("div",{children:" "})]}),scope:f,timeZone:i,objectMap:d,unzip:o})})}}const Wy=(c,e)=>({commandHistoryStorage:wh(c),sessionWrapper:Qs(c,e.localDashboardId),timeZone:po(c)}),Gy=St(Wy,null,null,{forwardRef:!0})($y),Ci=Gy;const Zo=ne.module("DropdownFilter"),zy=150;class eo extends v.Component{static defaultProps={column:null,disableLinking:!1,isLinkerActive:!1,isLoaded:!1,isValueShown:!1,settingsError:null,source:null,value:"",values:[],onColumnSelected:()=>{},onSourceMouseEnter:()=>{},onSourceMouseLeave:()=>{}};static PLACEHOLDER="Select a value...";static SOURCE_BUTTON_CLASS_NAME="btn-dropdown-filter-selector";static SOURCE_BUTTON_PLACEHOLDER="Select a column";constructor(e){super(e),this.handleColumnChange=this.handleColumnChange.bind(this),this.handleSettingsCancel=this.handleSettingsCancel.bind(this),this.handleSettingsClick=this.handleSettingsClick.bind(this),this.handleSettingsSave=this.handleSettingsSave.bind(this),this.handleBackgroundClick=this.handleBackgroundClick.bind(this),this.handleDropdownKeyPress=this.handleDropdownKeyPress.bind(this),this.handleValueChange=this.handleValueChange.bind(this),this.dropdownRef=de.createRef();const{column:t,isValueShown:n,value:s}=e;this.state={column:t,id:qe(),selectedColumn:t,disableCancel:!n,isValueShown:n,value:s}}componentDidUpdate(e,t){const{source:n,values:s,isLoaded:i}=this.props,{column:o,value:l,isValueShown:a}=this.state;i&&(n!==e.source&&this.sourceUpdated(),s!==e.values&&l!==""&&!s.includes(l)&&this.resetValue(),a!==t.isValueShown&&a&&this.focusInput(),(o!==t.column||l!==t.value||a!==t.isValueShown)&&this.sendUpdate())}componentWillUnmount(){this.sendUpdate.flush()}dropdownRef;getCompatibleColumns=ge((e,t)=>e!=null?t.filter(({type:n})=>n!==void 0&&F.isCompatibleType(n,e.columnType)):[]);getColumnOptions=ge((e,t)=>{let n=-1;const s=[];return s.push(r.jsx("option",{value:"-1",children:"Select a column"},"placeholder")),e.forEach((i,o)=>{s.push(r.jsx("option",{value:o,children:this.getItemLabel(e,o)},`${i.name}/${i.type}`)),t!==null&&i.name===t.name&&i.type===t.type&&(n=o)}),[s,n]});getSelectedOptionIndex=ge((e,t)=>e.indexOf(t));getValueOptions=ge(e=>[r.jsx("option",{value:"-1",children:eo.PLACEHOLDER},"-1"),...e.map((t,n)=>r.jsx("option",{value:n,children:t??"(null)"},`${n}/${t}`))]);getItemLabel=Re((e,t)=>{const{name:n,type:s}=e[t];if(t>0&&e[t-1].name===n||t<e.length-1&&e[t+1].name===n){const i=s.substring(s.lastIndexOf(".")+1);return`${n} (${i})`}return n});handleColumnChange(e){const{value:t}=e.target;if(Zo.debug2("handleColumnChange",t),t!=null&&parseInt(t,10)<0){this.setState({selectedColumn:null});return}const{columns:n,source:s}=this.props,i=this.getCompatibleColumns(s,n);this.setState({selectedColumn:i[parseInt(t,10)]})}handleDropdownKeyPress(e){e.key==="Enter"&&(e.preventDefault(),e.stopPropagation(),Zo.debug2("handleDropdownKeyPress"),this.sendUpdate(),this.sendUpdate.flush())}handleValueChange(e){const{value:t}=e.target,n=parseInt(t,10);let s="";const{values:i}=this.props;n>=0&&n<i.length?s=i[n]:Zo.debug2("Selected default item"),Zo.debug2("handleValueChange",s),this.setState({value:s})}handleSettingsCancel(){this.setState(({column:e})=>({selectedColumn:e,isValueShown:!0}))}handleSettingsSave(){this.setState(({column:e,selectedColumn:t,value:n})=>({column:t,value:e===t?n:"",isValueShown:!0,disableCancel:!1}))}handleSettingsClick(e){e.stopPropagation(),this.showSettings()}handleBackgroundClick(e){e.target!==this.dropdownRef.current&&this.focusInput()}sourceUpdated(){this.setState({column:null,selectedColumn:null,isValueShown:!1,disableCancel:!0,value:""})}showSettings(){const{column:e}=this.state;this.setState({selectedColumn:e,isValueShown:!1})}focusInput(){this.dropdownRef.current?.focus()}resetValue(){this.setState({value:""})}clearFilter(){this.resetValue()}setFilterState({name:e,type:t,value:n,isValueShown:s}){const i=e!=null&&t!=null?{name:e,type:t}:null;this.setState(({value:o,isValueShown:l})=>({column:i,value:n??o,isValueShown:s??l}))}sendUpdate=Ye(()=>{const{onChange:e}=this.props,{column:t,value:n,isValueShown:s}=this.state;e({column:t,isValueShown:s,value:n??void 0})},zy);render(){const{columns:e,disableLinking:t,isLinkerActive:n,isLoaded:s,source:i,onColumnSelected:o,onSourceMouseEnter:l,onSourceMouseLeave:a,values:d,settingsError:h}=this.props,{column:u,disableCancel:m,id:g,isValueShown:p,selectedColumn:C,value:f}=this.state,b=i===null,w=this.getCompatibleColumns(i,e),S=i!=null,T=i?.columnName??eo.SOURCE_BUTTON_PLACEHOLDER,y=u!=null?`${u.name} Filter`:null,[E,R]=this.getColumnOptions(w,C),x=this.getValueOptions(d),D=this.getSelectedOptionIndex(d,f),M=!S||C==null,O=p&&!n,H=`source-column-btn-${g}`,L=`filter-column-select-${g}`;return r.jsxs(ar,{className:"dropdown-filter fill-parent-absolute",isFlipped:O,children:[r.jsx("div",{className:"dropdown-filter-settings-card",children:r.jsxs("div",{className:"dropdown-filter-card-content",children:[r.jsxs("div",{className:"dropdown-filter-settings-grid",children:[r.jsx("label",{htmlFor:H,children:"Source Column"}),r.jsx(Kc,{id:H,isLinked:S,onClick:o,onMouseEnter:l,onMouseLeave:a,className:eo.SOURCE_BUTTON_CLASS_NAME,disabled:t,children:T}),r.jsx("div",{className:"text-muted small",children:"Select a source column for the list by linking to a table."}),r.jsx("label",{htmlFor:L,children:"Filter Column"}),r.jsx("select",{id:L,value:R,className:"custom-select",onChange:this.handleColumnChange,disabled:b,children:E}),r.jsx("div",{className:"text-muted small",children:"Dropdown filter control will apply its filter to all columns matching this name in this dashboard."})]}),h&&r.jsx("div",{className:"error-message text-center",children:h}),S&&r.jsxs("div",{className:"dropdown-filter-settings-buttons",children:[r.jsx(B,{kind:"secondary",type:"button",onClick:this.handleSettingsCancel,disabled:m||p||n,tooltip:n?"Cancel disabled while linker open":void 0,children:"Cancel"}),r.jsx(B,{kind:"primary",type:"button",className:"ml-2",onClick:this.handleSettingsSave,disabled:M||p||n,tooltip:n?"Save disabled while linker open":void 0,children:"Save"})]})]})}),r.jsx("div",{className:"dropdown-filter-value-card",onClick:this.handleBackgroundClick,"data-testid":"dropdown-filter-value-background",children:s&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"dropdown-filter-column",children:r.jsx("div",{className:"dropdown-filter-column-title",children:y})}),r.jsxs("div",{className:"dropdown-filter-card-content",children:[r.jsx("div",{className:"dropdown-filter-value-input d-flex flex-column justify-content-center",children:r.jsx("select",{className:"custom-select",value:D,ref:this.dropdownRef,onChange:this.handleValueChange,onKeyPress:this.handleDropdownKeyPress,title:"Select Value",children:x})}),h&&r.jsx("div",{className:"error-message mt-3 text-center",children:h})]}),r.jsx("div",{className:"dropdown-filter-menu",children:r.jsx(B,{kind:"ghost",className:"m-2 px-2",onClick:this.handleSettingsClick,icon:r.jsx(ee,{icon:mo,transform:"grow-4"}),tooltip:"Dropdown Filter Settings"})})]})})]})}}const mc=eo;const nt=ne.module("DropdownFilterPanel"),Ky=250,Yy=(c,e)=>{const{localDashboardId:t}=e,n=K.getIdFromPanel({props:e}),s=Kr(c,t),i=Ni(c,t),o=Xl(c),l=Yr(c,t),a=o===Pt.LINKER&&(l===void 0||l===n),d=o===Pt.LINKER&&l!==void 0&&l!==n;return{columns:ju(c,t),columnSelectionValidator:qr(c,t),isLinkerActive:a,disableLinking:d,settings:wt(c),panelTableMap:s,dashboardLinks:i}},qy=St(Yy,null,null,{forwardRef:!0});class gs extends v.Component{static displayName="DropdownFilterPanel";static COMPONENT="DropdownFilterPanel";static MAX_TABLE_SIZE=256;static DATETIME_FORMATTER=new ct({showTimeZone:!1,showTSeparator:!0,defaultDateTimeFormatString:"yyyy-MM-dd HH:mm:ss.SSSSSSSSS"});static SOURCE_COLUMN=Object.freeze({name:"FilterSource",type:null});constructor(e){super(e),this.handleChange=Ye(this.handleChange.bind(this),Ky),this.handleClearAllFilters=this.handleClearAllFilters.bind(this),this.handleDisconnect=this.handleDisconnect.bind(this),this.handleReconnect=this.handleReconnect.bind(this),this.handleColumnSelected=this.handleColumnSelected.bind(this),this.handleSourceFilterChange=this.handleSourceFilterChange.bind(this),this.handleSourceSortChange=this.handleSourceSortChange.bind(this),this.handleSourceSizeChange=this.handleSourceSizeChange.bind(this),this.handleSourceMouseEnter=this.handleSourceMouseEnter.bind(this),this.handleSourceMouseLeave=this.handleSourceMouseLeave.bind(this),this.handleValuesTableUpdate=this.handleValuesTableUpdate.bind(this),this.dropdownFilterRef=de.createRef(),this.panelContainer=de.createRef(),this.pending=new Yn;const{panelState:t,settings:n}=e;this.columnFormats=$n.getColumnFormats(n);const{value:s="",isValueShown:i=!1,name:o,type:l,timestamp:a}=t??{},d=o!=null&&l!=null?{name:o,type:l}:void 0;this.state={column:d,formatter:new gn(this.columnFormats),valuesTable:void 0,valuesColumn:void 0,sourceSize:0,value:s,timestamp:a,values:[],isValueShown:i,wasFlipped:!1,skipUpdate:!1,panelState:t,isDisconnected:!1,isLoading:!1,isLoaded:!1,error:null}}componentDidMount(){this.updateValuesTable();const{dashboardLinks:e,panelTableMap:t}=this.props,{column:n,value:s,timestamp:i}=this.state,o=this.getSourceTable(t,e);if(o!==null&&this.startListeningToSource(o),n!=null){const{name:l,type:a}=n;this.sendUpdate(l,a,s,i)}}componentDidUpdate(e,t){const{dashboardLinks:n,panelTableMap:s,settings:i}=this.props,{valuesTable:o}=this.state,l=this.getSource(n),a=this.getSourceTable(s,n),d=this.getSource(e.dashboardLinks),h=this.getSourceTable(e.panelTableMap,e.dashboardLinks);i!==e.settings&&i!==void 0&&this.updateFormatterSettings(i),o!==t.valuesTable&&t.valuesTable!=null&&(nt.debug("Table in state modified, closing the old table."),t.valuesTable.close()),(a!==h||l!==d)&&this.updateValuesTable(),a!==h&&(h!==null&&this.stopListeningToSource(h),a!==null&&this.startListeningToSource(a))}componentWillUnmount(){const{dashboardLinks:e,panelTableMap:t}=this.props,{valuesTable:n}=this.state,s=this.getSourceTable(t,e);this.pending.cancel(),s!==null&&this.stopListeningToSource(s),this.cleanup&&this.cleanup(),n?.close()}dropdownFilterRef;panelContainer;pending;cleanup;columnFormats;getCachedValues=Re((e,{type:t,name:n},s)=>t!==void 0&&F.isDateType(t)?e.map(i=>gs.DATETIME_FORMATTER.format(i)):e.map(i=>i!=null&&t!=null?s.getFormattedString(i,t,n):null));getCoordinateForColumn(){if(this.panelContainer.current==null)return null;const t=this.panelContainer.current.querySelector(`.${mc.SOURCE_BUTTON_CLASS_NAME}`)?.getBoundingClientRect()??null;if(t==null||t.width<=0||t.height<=0)return null;const n=t.left+t.width/2,s=t.bottom;return[n,s]}getSettingsErrorMessage(){const{sourceSize:e}=this.state;if(e>gs.MAX_TABLE_SIZE)return`Table too large, must have fewer than ${gs.MAX_TABLE_SIZE} options.`}getPanelErrorMessage(){const{error:e}=this.state;return e!=null?`${e}`:void 0}getCachedPanelLinks=Re((e,t)=>{const n=K.getIdFromPanel(t);return nt.debug("getCachedPanelLinks",e,n),e.filter(s=>s.end?.panelId===n)});getCachedSource=Re(e=>{nt.debug("getCachedSource",e);let t;if(e.length>0){const[n]=e;t=n.start,e.length>1&&nt.error("Filter has more that one link",e)}return t});getCachedSourceTable=Re((e,t)=>{if(nt.debug("getCachedSourceTable",e,t),t==null)return null;const{panelId:n}=t;return e.get(n)??null});getCachedSourceColumn=Re((e,t)=>(nt.debug("getCachedSourceColumn",e,t),e==null||t==null?null:e.columns.find(({name:n,type:s})=>n===t.columnName&&s===t.columnType)??null));getSource(e){const t=this.getCachedPanelLinks(e,this);return this.getCachedSource(t)}getSourceTable(e,t){const n=this.getSource(t);return this.getCachedSourceTable(e,n)}getValuesColumn(e,t){const n=this.getSource(t);return this.getCachedSourceColumn(e,n)}startListeningToSource(e){nt.debug("startListeningToSource"),e.addEventListener(I.Table.EVENT_FILTERCHANGED,this.handleSourceFilterChange),e.addEventListener(I.Table.EVENT_SORTCHANGED,this.handleSourceSortChange),e.addEventListener(I.Table.EVENT_SIZECHANGED,this.handleSourceSizeChange),e.addEventListener(I.Table.EVENT_DISCONNECT,this.handleDisconnect),e.addEventListener(I.Table.EVENT_RECONNECT,this.handleReconnect)}stopListeningToSource(e){nt.debug("stopListeningToSource"),e.removeEventListener(I.Table.EVENT_FILTERCHANGED,this.handleSourceFilterChange),e.removeEventListener(I.Table.EVENT_SORTCHANGED,this.handleSourceSortChange),e.removeEventListener(I.Table.EVENT_SIZECHANGED,this.handleSourceSizeChange),e.removeEventListener(I.Table.EVENT_DISCONNECT,this.handleDisconnect),e.removeEventListener(I.Table.EVENT_RECONNECT,this.handleReconnect)}handleChange({column:e,isValueShown:t=!1,value:n}){const{name:s=void 0,type:i=void 0}=e??{};let o=!0,l=Date.now();this.setState(({panelState:a,timestamp:d,wasFlipped:h,skipUpdate:u})=>{const m=a!=null&&t!==a.isValueShown&&s===a.name&&i===a.type&&n===a.value;return o=(!u&&t&&(!m||!h))??!1,o||(l=d),{panelState:{isValueShown:t,name:s,type:i,value:n,timestamp:l??void 0},timestamp:l,wasFlipped:m,skipUpdate:!1}},()=>{o&&this.sendUpdate(s??null,i,n,l)})}handleDisconnect(){this.setState({error:new Error("Table disconnected"),isDisconnected:!0,isLoading:!1})}handleReconnect(){this.setState({isDisconnected:!1,error:null})}handleSourceFilterChange(){this.applySourceFilters()}handleSourceSortChange(){this.applySourceSorts()}handleSourceSizeChange({detail:e}){this.setState({sourceSize:e})}handleColumnSelected(){nt.debug("handleColumnSelected");const{glEventHub:e}=this.props;e.emit(Ze.COLUMN_SELECTED,this,gs.SOURCE_COLUMN)}handleClearAllFilters(){this.dropdownFilterRef?.current?.clearFilter()}setPanelState(e,t=!1){const{dashboardLinks:n}=this.props;if(this.getSource(n)==null){nt.debug("Ignore state update for unlinked filter",e);return}this.setState({skipUpdate:!t}),this.dropdownFilterRef?.current?.setFilterState(e)}sendUpdate(e,t,n,s){const{dashboardLinks:i,glEventHub:o}=this.props,l=this.getSource(i)?.panelId,a=l===null?[]:[l];nt.debug("sendUpdate",{name:e,type:t,value:n,timestamp:s,excludePanelIds:a}),o.emit(Ze.FILTERS_CHANGED,this,{name:e,type:t,value:n??"=null",timestamp:s,excludePanelIds:a})}updateValuesTable(){const{dashboardLinks:e,panelTableMap:t}=this.props,n=this.getSource(e),s=this.getSourceTable(t,e);if(nt.debug("updateValuesTable",n,s),this.setState({values:[],valuesTable:void 0,error:null}),n==null){nt.debug("Filter unlinked."),this.setState({isLoading:!1,isLoaded:!0,isValueShown:!1,sourceSize:0});return}this.setState({isLoading:!0}),s!=null&&(this.setState({isLoaded:!1,sourceSize:s.size}),this.pending.add(s.copy(),i=>i.close()).then(i=>{this.updateViewportListener(i),this.setState({valuesTable:i})}).catch(i=>{ye.isCanceled(i)||(nt.error(i),this.setState({isLoading:!1,error:i}))}))}applySourceSorts(){const{dashboardLinks:e,panelTableMap:t}=this.props,{valuesTable:n}=this.state,s=this.getSourceTable(t,e);if(nt.debug("applySourceSorts",s?.sort),n==null||s==null){nt.debug("Table not initialized");return}const i=[...s.sort];n.applySort(i),this.setViewport(n)}applySourceFilters(){const{dashboardLinks:e,panelTableMap:t}=this.props,{valuesTable:n}=this.state,s=this.getSourceTable(t,e);if(nt.debug("applySourceFilters",s?.filter),n==null||s==null){nt.debug("Table not initialized");return}const i=[...s.filter];n.applyFilter(i),this.setViewport(n)}updateViewportListener(e){if(nt.debug("updateViewportListener",e?.size),this.cleanup&&this.cleanup(),e==null){this.cleanup=void 0;return}this.cleanup=e.addEventListener(I.Table.EVENT_UPDATED,this.handleValuesTableUpdate),this.setViewport(e)}setViewport(e){const{dashboardLinks:t}=this.props,n=this.getValuesColumn(e,t);if(!n){nt.error("values column is null");return}e.setViewport(0,gs.MAX_TABLE_SIZE-1,[n])}updateFormatterSettings(e){const t=$n.getColumnFormats(e);st(this.columnFormats,t)||(this.columnFormats=t,this.setState({formatter:new gn(t)}))}handleValuesTableUpdate({detail:e}){const{rows:t}=e,{dashboardLinks:n}=this.props,{valuesTable:s}=this.state;if(!s){nt.error("valuesTable is null");return}const i=this.getValuesColumn(s,n);if(!i){nt.error("Values column not found");return}const o=t.map(l=>l.get(i));this.setState({values:o,isLoading:!1,isLoaded:!0,valuesColumn:i})}handleSourceMouseEnter(){const{columnSelectionValidator:e}=this.props;e&&e(this,gs.SOURCE_COLUMN)}handleSourceMouseLeave(){const{columnSelectionValidator:e}=this.props;e&&e(this,void 0)}render(){const{columns:e,dashboardLinks:t,disableLinking:n,glContainer:s,glEventHub:i,isLinkerActive:o}=this.props,{column:l,formatter:a,isDisconnected:d,isValueShown:h,value:u,values:m,valuesColumn:g,isLoading:p,isLoaded:C}=this.state,f=this.getSource(t),b=this.getSettingsErrorMessage(),w=this.getPanelErrorMessage(),S=C&&g!=null?this.getCachedValues(m,g,a):[];return r.jsx(Gr,{errorMessage:w,isLoading:p,isLoaded:C,isDisconnected:d,className:"iris-dropdown-filter-panel",componentPanel:this,glContainer:s,glEventHub:i,onClearAllFilters:this.handleClearAllFilters,widgetName:"Dropdown Filter",widgetType:"DropdownFilter",children:r.jsx("div",{ref:this.panelContainer,className:"dropdown-filter-container h-100 w-100 container",children:r.jsx(mc,{ref:this.dropdownFilterRef,column:l,columns:e,isValueShown:h,isLinkerActive:o,disableLinking:n,isLoaded:C,settingsError:b,source:f,value:u,values:S,onChange:this.handleChange,onColumnSelected:this.handleColumnSelected,onSourceMouseEnter:this.handleSourceMouseEnter,onSourceMouseLeave:this.handleSourceMouseLeave})})})}}const Xy=qy(gs),Ys=Xy;function xn(c){return c.type==="directory"}var Uu=(c=>(c.GROOVY="text/x-groovy",c.PLAIN_TEXT="text/plain",c.PYTHON="text/x-python",c.PYTHON_COMPILED="application/x-python-code",c.SCALA="text/x-scala",c.UNKNOWN="",c))(Uu||{});class Vs{static fileExtensionToString(e=""){return e.length===0?"":`.${e}`}static getDepth(e){if(!Vs.hasPath(e))throw new Error(`Invalid path provided: ${e}`);return(e.match(/\//g)??[]).length-1}static getExtension(e){const t=this.getBaseName(e).split(".");return t.length>1?t.pop()??"":""}static getBaseName(e){return e.split("/").pop()??""}static getCopyFileName(e){const t=e.lastIndexOf(".");let n=null,s=null;t<0?s=e:(s=e.substring(0,t),n=e.substring(t+1));const i=s?`${s}-copy`:"Copy";return n!==null?`${i}.${n}`:i}static getMimeType(e){switch(this.getExtension(e).toLowerCase()){case"groovy":return"text/x-groovy";case"py":return"text/x-python";case"pyc":return"application/x-python-code";case"scala":return"text/x-scala";case"txt":return"text/plain";default:return""}}static getParent(e){if(!Vs.hasPath(e))throw new Error(`Invalid name provided: ${e}`);const t=e.split("/");for(;t.pop()==="";);if(t.length===0)throw new Error(`No parent for path provided: ${e}`);return`${t.join("/")}/`}static getPath(e){if(!Vs.hasPath(e))throw new Error(`Invalid filename provided: ${e}`);const t=e.split("/");return t.pop(),`${t.join("/")}/`}static hasPath(e){return e.startsWith("/")}static isPath(e){return e.startsWith("/")&&e.endsWith("/")}static makePath(e){return e.endsWith("/")?e:`${e}/`}static replaceExtension(e,t=""){const n=e.lastIndexOf("."),s=n>-1?e.substring(0,n):e,i=Vs.fileExtensionToString(t);return`${s}${i}`}static validateName(e){const t=[".",".."],n=/[\\/\0]/g,s=new Map([["\0","null"]]);if(!e)throw new vi("Name cannot be empty");if(t.includes(e))throw new vi(`"${e}" is a reserved name`);if(n.test(e))throw new vi(`Invalid characters in name: "${e.match(n)?.reduce((i,o)=>i.includes(o)?i:[...i,o],[]).map(i=>s.has(i)?s.get(i):i).join('", "')??""}"`)}static reducePaths(e){const t=e.filter(n=>Vs.isPath(n));return e.filter(n=>!t.some(s=>n!==s&&n.startsWith(s)))}static removeRoot(e,t){if(e.length===0)return t;if(!t.startsWith(e))throw new Error(`Filename ${t} does not start with expected root ${e}`);return t.substring(e.length)}static addRoot(e,t){return`${e}${t}`}}const fe=Vs,Qr=26;function Ja(c){return xn(c)?fe.makePath(c.filename):fe.getPath(c.filename)}function gc(c,e){if(c.length===0||e==null)throw new Error("No items to move");const t=Ja(e);if(c.some(({filename:n})=>fe.getPath(n)===t))throw new Error("File already in the destination folder");if(c.some(n=>xn(n)&&t.startsWith(fe.makePath(n.filename))))throw new Error("Destination folder cannot be a child of a dragged folder");return{files:c,targetPath:t}}function Zy(c){if(xn(c))return c.isExpanded?Ug:Vg;switch(fe.getMimeType(c.basename)){case Uu.PYTHON:return Wg;default:return $g}}function er(c){const{children:e,draggedItems:t,isDragInProgress:n,isDropTargetValid:s,isSelected:i,item:o,itemIndex:l,dropTargetItem:a,onDragStart:d,onDragOver:h,onDragEnd:u,onDrop:m}=c,g=t?.some(E=>E.id===o.id)??!1,p=Ja(o),C=n&&a?Ja(a):null,f=n&&s&&xn(o)&&C===p,b=n&&s&&C===p,w=n&&!s&&C===p,S=Zy(o),T=fe.getDepth(o.filename),y=Array(T).fill(null).map((E,R)=>r.jsx("span",{className:"file-list-depth-line"},R));return r.jsxs("div",{className:Y("d-flex w-100 align-items-center","file-list-item",{"is-dragged":g,"is-exact-drop-target":f,"is-in-drop-target":b,"is-invalid-drop-target":w,"is-selected":i}),onDragStart:E=>d(l,E),onDragOver:E=>h(l,E),onDragEnd:E=>u(l,E),onDrop:E=>m(l,E),draggable:!0,role:"presentation","aria-label":o.basename,children:[y," ",r.jsx(ee,{icon:S,className:"item-icon",fixedWidth:!0})," ",r.jsxs("span",{className:"truncation-wrapper",children:[e??o.basename,r.jsx(ot,{options:{placement:"left"},children:e??o.basename})]})]})}const It=ne.module("FileList"),Qy=500,pc="item-list-scroll-pane";function Jy(c){const{isMultiSelect:e=!1,table:t,onFocusChange:n=()=>{},onMove:s,onSelect:i,onSelectionChange:o=()=>{},renderItem:l=er,rowHeight:a=Qr,overscanCount:d=yi.DEFAULT_OVERSCAN}=c,[h,u]=v.useState(()=>({items:[],offset:0,itemCount:0})),[m,g]=v.useState({top:0,bottom:0}),[p,C]=v.useState(),[f,b]=v.useState(),[w,S]=v.useState(),[T,y]=v.useState([]),E=v.useRef(null),R=v.useRef(null),x=v.useCallback(G=>{if(G.length===0||h==null)return[];const oe=[];for(let ue=0;ue<G.length;ue+=1){const ae=G[ue];for(let ce=ae[0];ce<=ae[1];ce+=1)ce>=h.offset&&ce<h.offset+h.items.length&&oe.push(h.items[ce-h.offset])}return oe},[h]),D=v.useCallback(G=>{const oe=x([[G,G]]);if(oe.length>0)return oe[0]},[x]),M=v.useCallback(()=>{const G=gd.count(T);if(G===0)return null;if(G===1){const oe=T[0][0],ue=D(oe);if(ue!=null)return ue.filename}return`${G} items`},[D,T]),O=v.useCallback(G=>{if(!(!f||!p)){It.debug("dropItems",f,"to",G);try{const{files:oe,targetPath:ue}=gc(f,p);s?.(oe,ue),G!=null&&(y([[G,G]]),E.current?.focusItem(G))}catch(oe){It.error("Unable to complete move",oe)}}},[f,p,s]),H=v.useCallback((G,oe)=>{const ue=h.items[G-h.offset];ue!==void 0&&(It.debug("handleItemClick",ue),i(ue,oe),xn(ue)&&t?.setExpanded(ue.filename,!ue.isExpanded))},[h,i,t]),L=v.useCallback((G,oe)=>{It.debug2("handleItemDragStart",G,T);let ue=T;gd.isSelected(T,G)||(ue=[[G,G]],y(ue)),b(x(ue)),E.current?.resetMouseState();const ae=document.createElement("div");ae.innerHTML=`<div class="dnd-placeholder-content">${M()}</div>`,ae.className="file-list-dnd-placeholder",document.body.appendChild(ae),oe.dataTransfer.setDragImage(ae,0,0),oe.dataTransfer.effectAllowed="move",S(ae)},[M,x,T]),V=v.useCallback((G,oe)=>{oe.preventDefault(),It.debug2("handleItemDragOver",oe),C(D(G))},[D]),U=v.useCallback((G,oe)=>{It.debug("handleItemDragEnd",G),w?.remove(),b(void 0),C(void 0),S(void 0)},[w]),j=v.useCallback((G,oe)=>{O(G)},[O]),P=v.useCallback(()=>{It.debug2("handleItemDragExit"),C(void 0)},[]),Q=v.useCallback(G=>{G.target instanceof Element&&G.target.classList.contains(pc)&&(G.preventDefault(),It.debug2("handleListDragOver",G),C({type:"directory",filename:"/",basename:"/",id:"/"}))},[]),$=v.useCallback(G=>{G.target instanceof Element&&G.target.classList.contains(pc)&&(It.debug("handleListDrop"),O())},[O]),J=v.useCallback(G=>{if(It.debug2("handleSelectionChange",G),G!==T){y(G);const oe=x(G);o(oe)}},[x,o,T]),A=v.useCallback(G=>{if(It.debug2("handleFocusChange",G),G!=null){const[oe]=x([[G,G]]);n(oe)}else n()},[x,n]),W=v.useCallback((G,oe)=>{It.debug("handleViewportChange",G,oe),(G!==m.top||oe!==m.bottom)&&g({top:G,bottom:oe})},[m]),q=v.useMemo(()=>{if(!f||!p)return!1;try{return gc(f,p),It.debug("handleValidateDropTarget true"),!0}catch{return It.debug("handleValidateDropTarget false"),!1}},[f,p]),{focusedPath:Z}=c;v.useEffect(()=>{Z!==void 0&&(Z==="/"?t.collapseAll():(t.setExpanded(Z,!1),t.setExpanded(Z,!0)))},[t,Z]),v.useEffect(function(){It.debug("updating table viewport",m),t?.setViewport({top:Math.max(0,m.top-d),bottom:m.bottom+d})},[d,t,m]),v.useEffect(function(){const oe=t.onUpdate(ue=>{u({items:ue.items.map(ae=>({...ae,itemName:ae.basename})),offset:ue.offset,itemCount:t.size})});return()=>{oe()}},[t]),v.useEffect(function(){if(p!=null&&xn(p)&&p.filename!=="/"){const oe=setTimeout(()=>{p.isExpanded||t?.setExpanded(p.filename,!0)},Qy);return()=>clearTimeout(oe)}},[p,t]);const le=v.useCallback(G=>l({...G,isDragInProgress:f!=null,dropTargetItem:p,draggedItems:f,isDropTargetValid:q,onDragStart:L,onDragEnd:U,onDragOver:V,onDragExit:P,onDrop:j}),[U,P,V,L,j,f,p,q,l]);return r.jsx("div",{ref:R,className:Y("file-list",{"is-dragging":f!=null}),onDragOver:Q,onDrop:$,children:r.jsx(yi,{ref:E,items:h.items,itemCount:h.itemCount,offset:h.offset,onFocusChange:A,onSelect:H,onSelectionChange:J,onViewportChange:W,selectedRanges:T,renderItem:le,rowHeight:a,isMultiSelect:e,isDragSelect:!1,isDeselectOnClick:!1})})}const eR={name:"File Explorer",DELETE:We.createAndAdd({id:"FILE_EXPLORER.DELETE",name:"Delete",shortcut:[xe.DELETE],macShortcut:[ve.CMD,xe.BACKSPACE]}),RENAME:We.createAndAdd({id:"FILE_EXPLORER.RENAME",name:"Rename",shortcut:[xe.ENTER],macShortcut:[xe.ENTER]})},fc={FILE_EXPLORER:eR};const Cc=ne.module("FileListItemEditor"),tR=()=>Promise.resolve();function nR({item:c,onCancel:e,onSubmit:t,validate:n=tR}){const s=v.useRef(null),[i,o]=v.useState(c.basename),[l,a]=v.useState(),[d,h]=v.useState(Promise.resolve()),u=v.useCallback(()=>{s.current?.focus()},[s]),m=v.useCallback(b=>b.stopPropagation(),[]),g=v.useCallback(()=>{d.then(()=>{t(i)}).catch(b=>Cc.info("Unable to validate name",b))},[t,i,d]);v.useEffect(function(){const w=ye.makeCancelable(n(i));return w.then(()=>a(void 0)).catch(S=>{ye.isCanceled(S)||a(S)}),h(w),()=>w.cancel()},[n,i]),v.useEffect(function(){u()},[u]);const p=v.useCallback(()=>{Cc.debug2("handleBlur"),g()},[g]),C=v.useCallback(b=>{const{value:w}=b.target;o(w)},[]),f=v.useCallback(b=>{b.stopPropagation();const{key:w}=b;switch(w){case"Enter":{g();break}case"Escape":{e();break}}},[e,g]);return r.jsxs("div",{className:"file-list-item-editor",children:[r.jsx("input",{type:"text",className:Y("form-control file-list-item-editor-input",{"is-invalid":l}),value:i,ref:s,onBlur:p,onKeyDown:f,onChange:C,onClick:m,onDoubleClick:m,onMouseDown:m}),l&&r.jsx("div",{className:"invalid-feedback",children:`${l}`})]})}function Vu(c){const{isMultiSelect:e=!1,focusedPath:t,showContextMenu:n=!1,onCreateFile:s,onCreateFolder:i,onCopy:o,onDelete:l,onMove:a,onRename:d,onSelect:h,onSelectionChange:u,table:m,rowHeight:g=Qr,validateRename:p=()=>Promise.resolve()}=c,[C,f]=v.useState(),[b,w]=v.useState([]),[S,T]=v.useState(),y=v.useCallback(P=>{w(P),u?.(P)},[u]),E=v.useCallback(P=>{T(P)},[]),R=v.useCallback(()=>{S&&o?.(S)},[S,o]),x=v.useCallback(()=>{b.length>0&&l?.(b)},[l,b]),D=v.useCallback(()=>{s?.()},[s]),M=v.useCallback(()=>{S&&i?.(fe.getPath(S.filename))},[S,i]),O=v.useCallback(()=>{S&&f(S)},[S]),H=v.useCallback(()=>{f(void 0)},[]),L=v.useCallback(P=>{C&&(d?.(C,P),f(void 0))},[d,C]),V=v.useMemo(()=>{if(C)return[];const P=[];return s&&P.push({title:"New File",description:"Create new file",action:D,group:ie.groups.medium}),i&&P.push({title:"New Folder",description:"Create new folder",action:M,group:ie.groups.medium}),o&&P.push({title:"Copy",description:"Copy",action:R,group:ie.groups.low,disabled:S==null||xn(S)}),l&&b.length>0&&P.push({title:"Delete",description:"Delete",shortcut:fc.FILE_EXPLORER.DELETE,action:x,group:ie.groups.low}),d&&P.push({title:"Rename",description:"Rename",shortcut:fc.FILE_EXPLORER.RENAME,action:O,group:ie.groups.low,disabled:S==null}),P},[R,x,D,M,O,S,o,s,i,l,d,b,C]),U=v.useCallback(P=>(N(C),p(C,P)),[C,p]),j=v.useCallback(P=>{const{item:Q}=P;return C&&C.filename===Q.filename?r.jsx(er,{...P,children:r.jsx(nR,{item:Q,validate:U,onSubmit:L,onCancel:H})}):r.jsx(er,{...P})},[H,L,C,U]);return r.jsxs("div",{className:"file-list-container",children:[m!=null&&r.jsx(Jy,{onMove:a,onSelect:h,onSelectionChange:y,onFocusChange:E,renderItem:j,rowHeight:g,table:m,isMultiSelect:e,focusedPath:t}),n&&r.jsx(ie,{actions:V})]})}Vu.displayName="FileListContainer";class sR extends vi{isExistingFile=!0;info;constructor(e){super("Name already exists"),this.info=e}}const ol=sR;class iR extends Error{constructor(){super("No file exists at the path specified")}isFileNotFound=!0}const Jr=iR,Os=ne.module("FileExplorer");function ed(c){const{storage:e,isMultiSelect:t=!1,focusedPath:n,onDelete:s=()=>{},onRename:i=()=>{},onSelect:o,onSelectionChange:l,rowHeight:a=Qr}=c,[d,h]=v.useState([]),[u,m]=v.useState();v.useEffect(function(){let R;async function x(){Os.debug("initTable"),R=ye.makeCancelable(e.getTable(),D=>D.close());try{m(await R)}catch(D){ye.isCanceled(D)||Os.error("Unable to initialize table",D)}}return x(),()=>{R.cancel()}},[e]);const g=v.useCallback(E=>{ye.isCanceled(E)||Os.error(E)},[]),p=v.useCallback(E=>{Os.debug("handleDelete, pending confirmation",E),h(E)},[]),C=v.useCallback(()=>{Os.debug("handleDeleteConfirm",d),d.forEach(E=>e.deleteFile(xn(E)?fe.makePath(E.filename):E.filename)),s(d),h([])},[d,s,e]),f=v.useCallback(()=>{Os.debug("handleDeleteCancel"),h([])},[]),b=v.useCallback((E,R)=>{fe.reducePaths(E.map(D=>xn(D)?fe.makePath(D.filename):D.filename)).forEach(D=>{const M=fe.isPath(D)?`${R}${fe.getBaseName(D.substring(0,D.length-1))}/`:`${R}${fe.getBaseName(D)}`;e.moveFile(D,M).then(()=>{i(D,M)}).catch(g)})},[g,i,e]),w=v.useCallback((E,R)=>{let x=E.filename;const D=xn(E);D&&!x.endsWith("/")&&(x=`${x}/`);let M=`${fe.getParent(x)}${R}`;D&&!M.endsWith("/")&&(M=`${M}/`),Os.debug2("handleRename",x,M),e.moveFile(x,M).catch(g),i(x,M)},[g,i,e]),S=v.useCallback(async(E,R)=>{if(R===E.basename)return;fe.validateName(R);const x=`${fe.getPath(E.filename)}${R}`;try{const D=await e.info(x);throw new ol(D)}catch(D){if(!(D instanceof Jr))throw D}},[e]),T=d.length>0,y=v.useMemo(()=>d.length===1?`Are you sure you want to delete "${d[0].filename}"?`:"Are you sure you want to delete the selected files?",[d]);return r.jsxs("div",{className:"file-explorer",children:[u&&r.jsx(Vu,{isMultiSelect:t,focusedPath:n,showContextMenu:!0,onMove:b,onDelete:p,onRename:w,onSelect:o,onSelectionChange:l,rowHeight:a,table:u,validateRename:S}),r.jsx(oo,{isOpen:T,headerText:y,bodyText:"You cannot undo this action.",onCancel:f,onConfirm:C,confirmButtonText:"Delete"})]})}ed.displayName="FileExplorer";const As=ne.module("NewItemModal");class to extends v.PureComponent{static propTypes={isOpen:z.bool,title:z.string.isRequired,defaultValue:z.string,type:z.oneOf(["file","directory"]).isRequired,onSubmit:z.func,onCancel:z.func,placeholder:z.string,storage:z.shape({}).isRequired,notifyOnExtensionChange:z.bool};static defaultProps={isOpen:!1,defaultValue:"/",notifyOnExtensionChange:!1,placeholder:"",onSubmit:(e,t)=>{},onCancel:()=>{}};static getValidationMessage(e){return e instanceof ol&&e.info.type==="directory"?"Error: Cannot overwrite existing directory":`${e}`}static handleError(e){ye.isCanceled(e)||As.error(e)}constructor(e){super(e),this.handleModalSubmit=this.handleModalSubmit.bind(this),this.handleModalOpened=this.handleModalOpened.bind(this),this.handleSelect=this.handleSelect.bind(this),this.handleChange=this.handleChange.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleValidationError=this.handleValidationError.bind(this),this.handleOverwriteCancel=this.handleOverwriteCancel.bind(this),this.handleOverwriteConfirm=this.handleOverwriteConfirm.bind(this),this.handleExtensionChangeCancel=this.handleExtensionChangeCancel.bind(this),this.handleExtensionChangeConfirm=this.handleExtensionChangeConfirm.bind(this),this.handleBreadcrumbSelect=this.handleBreadcrumbSelect.bind(this);const{defaultValue:t}=e,n=fe.hasPath(t)?fe.getPath(t):"/";this.state={isSubmitting:!1,path:n,prevExtension:fe.getExtension(t),showExtensionChangeModal:!1,showOverwriteModal:!1,value:fe.getBaseName(t)}}componentDidUpdate(e,t){const{isOpen:n}=this.props,{isOpen:s}=e,{value:i,path:o}=this.state;!s&&n&&(this.resetValue(),this.isInitialLoad=!0),s&&n&&(!this.isInitialLoad&&(o!==t.path||i!==t.value)&&this.updateValidationStatus(o,i),this.isInitialLoad=!1)}componentWillUnmount(){this.pending.cancel(),this.cancelableValidatePromise&&this.cancelableValidatePromise.cancel(),this.cancelableExistingItemPromise&&this.cancelableExistingItemPromise.cancel()}inputRef=de.createRef();cancelableValidatePromise;cancelableExistingItemPromise;pending=new Yn;pathMap=new Map;isInitialLoad=!0;resetValue(){const{defaultValue:e}=this.props,t=fe.hasPath(e)?fe.getPath(e):"/";this.setState({path:t,value:fe.getBaseName(e),validationError:void 0,prevExtension:fe.getExtension(e),isSubmitting:!1})}getValidationPromise(e,t,n=!1){return this.cancelableValidatePromise&&this.cancelableValidatePromise.cancel(),this.cancelableValidatePromise=ye.makeCancelable(this.validateName(e,t,n)),this.cancelableValidatePromise}async validateName(e,t,n){fe.validateName(t);const{defaultValue:s,storage:i}=this.props;if(n){const o=`${e}${t}`;if(o!==s)try{const l=await i.info(o);throw new ol(l)}catch(l){if(!(l instanceof Jr))throw l}}return t}updateValidationStatus(e,t){this.getValidationPromise(e,t).then(()=>{this.setState({validationError:void 0})}).catch(this.handleValidationError).catch(to.handleError)}handleModalOpened(){this.focusRenameInput()}handleModalSubmit(){this.submitModal()}handleChange(e){const{value:t}=e.target;this.setState({value:t})}handleSelect(e){if(As.debug("handleSelect",e),e.type==="directory")this.setState({path:fe.makePath(e.filename)});else{const t=e.basename,n=fe.getPath(e.filename);this.setState({value:t,path:n},()=>{this.focusRenameInput()})}}handleKeyDown(e){const{key:t}=e;switch(e.stopPropagation(),t){case"Enter":{e.preventDefault(),this.submitModal();break}case"Escape":{e.preventDefault();const{onCancel:n}=this.props;n();break}}}handleValidationError(e){if(!(e instanceof vi))throw e;As.debug("Validation error",e),this.setState({validationError:e})}handleOverwriteCancel(){this.setState({showOverwriteModal:!1,isSubmitting:!1})}handleOverwriteConfirm(){this.setState({showOverwriteModal:!1});const{onSubmit:e}=this.props,{path:t,value:n}=this.state;As.debug("handleOverwriteConfirm",t,n),e(`${t}${n}`,!0)}handleExtensionChangeCancel(){As.debug("handleExtensionChangeCancel"),this.setState(({value:e,prevExtension:t})=>({showExtensionChangeModal:!1,value:fe.replaceExtension(e,t)})),this.submitModal(!0)}handleExtensionChangeConfirm(){As.debug("handleExtensionChangeConfirm"),this.setState({showExtensionChangeModal:!1}),this.submitModal(!0)}focusRenameInput(){const e=this.inputRef.current;if(e){const{type:t}=this.props,{value:n}=e,s=t==="directory"?n.length:n.lastIndexOf(".");e.focus(),e.setSelectionRange(0,s>0?s:n.length)}}submitModal(e=!1){this.setState(({prevExtension:t,value:n,path:s})=>{const{notifyOnExtensionChange:i,type:o}=this.props;As.debug("submitModal",t,n);const l=fe.getExtension(n);return i&&!e&&t!==null&&t!==l?{isSubmitting:!1,showExtensionChangeModal:!0,newExtension:l}:(this.getValidationPromise(s,n,!0).then(a=>{const{onSubmit:d}=this.props;d(`${s}${n}`)}).catch(a=>{if(a instanceof ol&&o!=="directory"&&a.info.type!=="directory"){this.setState({showOverwriteModal:!0});return}throw a}).catch(a=>{throw ye.isCanceled(a)&&this.setState({isSubmitting:!1}),a}).catch(this.handleValidationError).catch(to.handleError),{isSubmitting:!0,showExtensionChangeModal:!1,newExtension:void 0})})}handleBreadcrumbSelect(e){this.setState({path:e})}renderPathButtons(e){const t=e.split("/");return t.pop(),t.map((n,s)=>{let i="";for(let o=0;o<s;o+=1)i+=`${t[o]}/`;return i+=`${n}/`,r.jsxs(de.Fragment,{children:[r.jsx(B,{kind:"ghost",className:"directory-breadcrumbs",onClick:()=>this.handleBreadcrumbSelect(i),"aria-label":s===0?"Home":void 0,icon:s===0?r.jsx(ee,{icon:Gg,transform:"right-1.6"}):void 0,tooltip:s===0?"Home":void 0,children:n}),"/"]},i)})}render(){const{storage:e,isOpen:t,onCancel:n,placeholder:s,title:i,type:o}=this.props,{isSubmitting:l,path:a,showExtensionChangeModal:d,showOverwriteModal:h,validationError:u,value:m,prevExtension:g,newExtension:p}=this.state,C=o==="directory",f=fe.fileExtensionToString(g),b=fe.fileExtensionToString(p),w=C?"Create":"Save",S=C?"New folder name":"Save file as";return r.jsxs(r.Fragment,{children:[r.jsxs(Gl,{isOpen:t,toggle:n,onOpened:this.handleModalOpened,className:"modal-dialog-centered new-file-modal theme-bg-dark",children:[r.jsx(zl,{toggle:n,children:i}),r.jsx(Kl,{children:r.jsx("form",{children:r.jsxs("div",{className:"d-flex flex-column new-file-modal-content",children:[r.jsxs("div",{className:"flex-grow-0 mb-4",children:[r.jsx("label",{htmlFor:"file-name-input",children:S}),r.jsx("input",{id:"file-name-input",type:"text",autoComplete:"off",autoCapitalize:"none",autoCorrect:"off",spellCheck:"false",className:Y("form-control",{"is-invalid":u}),value:m,placeholder:s,ref:this.inputRef,onKeyDown:this.handleKeyDown,onChange:this.handleChange}),u&&r.jsx("div",{className:"invalid-feedback",children:to.getValidationMessage(u)})]}),r.jsxs("div",{className:"flex-grow-0",children:[r.jsx("label",{children:"Directory: /"}),this.renderPathButtons(a)]}),r.jsx("div",{className:"flex-grow-1 file-explorer-container",children:r.jsx(ed,{onSelect:this.handleSelect,storage:e,focusedPath:a})})]})})}),r.jsxs(Yc,{children:[r.jsx(B,{kind:"secondary",onClick:n,children:"Cancel"}),r.jsx(B,{kind:"primary",disabled:l,onClick:this.handleModalSubmit,children:w})]})]}),r.jsx(oo,{isOpen:h,headerText:"Confirm overwrite",bodyText:"File with this name already exists, are you sure you want to overwrite it?",onCancel:this.handleOverwriteCancel,onConfirm:this.handleOverwriteConfirm,cancelButtonText:"Cancel",confirmButtonText:"Overwrite"}),r.jsx(oo,{isOpen:d,headerText:"Confirm extension change",bodyText:`Are you sure you want to change extension from "${f}" to "${b}"?`,onCancel:this.handleExtensionChangeCancel,onConfirm:this.handleExtensionChangeConfirm,cancelButtonText:`Keep "${f}"`,confirmButtonText:`Use "${b}"`})]})}}const $u=to;function oR({createFile:c,createFolder:e,onSearchChange:t,defaultSearchText:n=""}){return r.jsxs("div",{className:"file-explorer-toolbar",children:[r.jsxs("div",{className:"file-explorer-toolbar-buttons",children:[r.jsx(B,{kind:"ghost",icon:Jc,tooltip:"New notebook",onClick:c,"aria-label":"New notebook"}),r.jsx(B,{kind:"ghost",icon:zg,tooltip:"New folder",onClick:e,"aria-label":"New folder"})]}),t&&r.jsx("div",{className:"file-explorer-toolbar-search",children:r.jsx(Bm,{value:n,onChange:t,placeholder:"Search by name"})})]})}const ci=ne.module("FileExplorerPanel"),lR=(c,e)=>{const t=vh(c),n=Qs(c,e.localDashboardId),{session:s,config:i}=n??{},o=i?.type;return{fileStorage:t,language:o,session:s}},aR=St(lR,null,null,{forwardRef:!0});function rR(c){const e=c;return e!=null&&typeof e.button=="number"}class Fl extends de.Component{static COMPONENT="FileExplorerPanel";static TITLE="File Explorer";static handleError(e){ci.error(e)}static isFocusEvent(e){return rR(e)?e.detail>=2:!0}constructor(e){super(e),this.handleFileSelect=this.handleFileSelect.bind(this),this.handleCreateFile=this.handleCreateFile.bind(this),this.handleCreateDirectory=this.handleCreateDirectory.bind(this),this.handleCreateDirectoryCancel=this.handleCreateDirectoryCancel.bind(this),this.handleCreateDirectorySubmit=this.handleCreateDirectorySubmit.bind(this),this.handleDelete=this.handleDelete.bind(this),this.handleRename=this.handleRename.bind(this),this.handleSessionOpened=this.handleSessionOpened.bind(this),this.handleSessionClosed=this.handleSessionClosed.bind(this),this.handleShow=this.handleShow.bind(this),this.handleSelectionChange=this.handleSelectionChange.bind(this);const{session:t,language:n}=e;this.state={isShown:!1,language:n,session:t,showCreateFolder:!1,focusedFilePath:"/"}}componentDidMount(){this.isHidden()||this.setState({isShown:!0})}handleCreateFile(){const{glEventHub:e}=this.props,{session:t,language:n}=this.state,s={language:n,value:""};ci.debug("handleCreateFile",t,n,s),e.emit(Ue.CREATE_NOTEBOOK,t,n,s)}handleCreateDirectory(e){this.setState({showCreateFolder:!0})}handleCreateDirectoryCancel(){ci.debug("handleCreateDirectoryCancel"),this.setState({showCreateFolder:!1})}handleCreateDirectorySubmit(e){ci.debug("handleCreateDirectorySubmit",e),this.setState({showCreateFolder:!1});const{fileStorage:t}=this.props;t.createDirectory(e).catch(Fl.handleError)}handleDelete(e){const{glEventHub:t}=this.props;e.forEach(n=>{t.emit(Ue.CLOSE_FILE,{id:n.filename,itemName:n.filename})})}handleSelectionChange(e){let t="/";e.length===1&&(e[0].type==="directory"?t=fe.makePath(e[0].filename):t=fe.getPath(e[0].filename)),this.setState({focusedFilePath:t})}handleFileSelect(e,t){if(ci.debug("fileSelect",e),e.type==="directory")return;const n=Fl.isFocusEvent(t),s={id:e.filename,itemName:e.filename},{glEventHub:i}=this.props,{session:o,language:l}=this.state,a={value:null,language:l};i.emit(Ue.SELECT_NOTEBOOK,o,l,a,s,n)}handleRename(e,t){const{glEventHub:n}=this.props;ci.debug("handleRename",e,t),n.emit(Ue.RENAME_FILE,e,t)}handleSessionOpened(e,{language:t}){this.setState({session:e,language:t})}handleSessionClosed(){this.setState({session:void 0,language:void 0})}handleShow(){this.setState({isShown:!0})}isHidden(){const{glContainer:e}=this.props,{isHidden:t}=e;return t}render(){const{fileStorage:e,glContainer:t,glEventHub:n}=this.props,{isShown:s,showCreateFolder:i,focusedFilePath:o}=this.state;return r.jsxs(qn,{className:"file-explorer-panel",componentPanel:this,glContainer:t,glEventHub:n,onSessionOpen:this.handleSessionOpened,onSessionClose:this.handleSessionClosed,onShow:this.handleShow,children:[r.jsx(oR,{createFile:this.handleCreateFile,createFolder:this.handleCreateDirectory}),s&&r.jsx(ed,{isMultiSelect:!0,storage:e,onDelete:this.handleDelete,onRename:this.handleRename,onSelect:this.handleFileSelect,onSelectionChange:this.handleSelectionChange}),r.jsx($u,{isOpen:i,type:"directory",title:"Create New Folder",storage:e,onSubmit:this.handleCreateDirectorySubmit,onCancel:this.handleCreateDirectoryCancel,defaultValue:o})]})}}const dR=aR(Fl),Nl=dR;const it=ne.module("FilterSetManager"),cR="Enter name...",bc="No Available Filter Sets";class kl extends v.Component{static animateScreenFlash(){const e=document.createElement("div");e.classList.add("screen-flash-overlay"),e.addEventListener("animationend",()=>{e.remove()}),document.querySelector("body")?.appendChild(e)}constructor(e){super(e),this.handleSettingsCancel=this.handleSettingsCancel.bind(this),this.handleSettingsClick=this.handleSettingsClick.bind(this),this.handleSettingsSave=this.handleSettingsSave.bind(this),this.handleBackgroundClick=this.handleBackgroundClick.bind(this),this.handleEditDropdownChange=this.handleEditDropdownChange.bind(this),this.handleFilterChange=this.handleFilterChange.bind(this),this.handleFilterApply=this.handleFilterApply.bind(this),this.handleCaptureNewSet=this.handleCaptureNewSet.bind(this),this.handleNameInputChange=this.handleNameInputChange.bind(this),this.handleNameInputKeyPress=this.handleNameInputKeyPress.bind(this),this.handleRenameConfirm=this.handleRenameConfirm.bind(this),this.handleRenameCancel=this.handleRenameCancel.bind(this),this.handleRestoreFullStateChange=this.handleRestoreFullStateChange.bind(this),this.handleSetDelete=this.handleSetDelete.bind(this),this.handleSetEdit=this.handleSetEdit.bind(this),this.handleSetUpdate=this.handleSetUpdate.bind(this),this.state={editId:void 0,renameSet:void 0,nameInputValue:"",nameInputError:void 0,modifiedFilterSets:[],restoreFullState:!1}}componentDidMount(){const{isValueShown:e}=this.props;e?this.updateSelectedId():this.initSettingsScreen()}componentDidUpdate(e,t){const{isValueShown:n,filterSets:s}=this.props,{modifiedFilterSets:i}=this.state;if(e.isValueShown&&!n&&this.initSettingsScreen(),this.isNameInputScreen()&&!this.isNameInputScreen(t)&&this.focusRenameInput(),s!==e.filterSets)if(!n&&s.length>0&&e.filterSets.length===0&&i.length===0){const{onChange:o}=this.props;o({isValueShown:!0,selectedId:s[0].id})}else this.updateSelectedId()}renameInputRef=de.createRef();dropdownRef=de.createRef();editDropdownRef=de.createRef();initSettingsScreen(){const{filterSets:e,selectedId:t}=this.props;it.debug("initSettingsScreen",e,t),this.setState({modifiedFilterSets:[...e],editId:t})}updateSelectedId(){const{isValueShown:e,filterSets:t,selectedId:n,onChange:s}=this.props;if(it.debug("updateSelectedId",t,n),!!e&&!t.some(({id:i})=>i===n)){const i=t.length===0;s({isValueShown:!i,selectedId:i?void 0:t[0].id})}}handleEditDropdownChange(e){const{value:t}=e.target;this.setState({editId:t})}handleFilterChange(e){const{value:t}=e.target,{isValueShown:n,onChange:s}=this.props;this.applyFilterSet(t),s({isValueShown:n,selectedId:t})}handleFilterApply(){const{selectedId:e}=this.props;this.applyFilterSet(e)}handleSettingsCancel(){const{onChange:e,selectedId:t,filterSets:n}=this.props;this.setState({modifiedFilterSets:[]}),n.length>0&&e({isValueShown:!0,selectedId:t})}handleSettingsSave(){const{onChange:e,onUpdateSets:t}=this.props,{modifiedFilterSets:n,editId:s}=this.state;this.setState({modifiedFilterSets:[]}),it.debug("Update sets",n,s),t(n),n.length>0&&e({isValueShown:!0,selectedId:s})}handleCaptureNewSet(){const{getFilterState:e}=this.props;kl.animateScreenFlash();const t=qe(),n=e(),s={id:t,title:"",panels:n};it.debug("handleSetCreate",s),this.setState({nameInputValue:"",nameInputError:void 0,renameSet:s})}handleRenameCancel(){this.setState({renameSet:void 0})}handleRestoreFullStateChange(e){this.setState({restoreFullState:e.target.value==="true"})}getNameError(e){const{renameSet:t,modifiedFilterSets:n}=this.state,s=e?.trim()??"";if(s.length===0)return it.debug("Name cannot be empty",s),"Name cannot be empty";if(t!==void 0&&n.some(({title:i,id:o})=>i===s&&o!==t.id))return it.debug("Set with this name already exists",s),"Set with this name already exists"}handleRenameConfirm(){const{nameInputValue:e,renameSet:t,modifiedFilterSets:n,restoreFullState:s}=this.state;if(t===void 0){it.error("Renamed set undefined.");return}const i=this.getNameError(e);if(it.debug("handleRenameConfirm",e,i),i!==void 0){this.setState({nameInputError:i});return}const o=e?.trim()??"",l={...t,title:o,restoreFullState:s},a=n.findIndex(({id:h})=>h===t.id),d=[...n];a>=0?(d[a]=l,it.debug("Renamed existing set",d)):(d.push(l),it.debug("Added new set to modified sets",d)),this.setState({editId:l.id,modifiedFilterSets:d,renameSet:void 0})}handleSetDelete(){this.setState(e=>{const{editId:t,modifiedFilterSets:n}=e,s=n.findIndex(({id:a})=>a===t);if(s<0)return it.error("Unable to find selected filterSet index",n,t),null;const i=n.filter(({id:a})=>a!==t),o=Math.max(0,Math.min(i.length-1,s-1)),l=i.length>0?i[o].id:void 0;return it.debug("Deleted selected set",t,n,i),it.debug("New selection",o,l),{modifiedFilterSets:i,editId:l}})}handleSetUpdate(){const{getFilterState:e}=this.props;kl.animateScreenFlash();const t=e();this.setState(({modifiedFilterSets:n,editId:s})=>{if(s===void 0)return it.error("Filter for update not selected."),null;const i=[...n],o=i.findIndex(({id:l})=>l===s);return o<0?(it.error("Selected set for update not found."),null):(i[o]={...i[o],panels:t},it.debug("Update set",i,t),{modifiedFilterSets:i})})}handleSetEdit(){this.setState(({editId:e,modifiedFilterSets:t})=>{const n=t.find(({id:o})=>o===e);if(n===void 0)return it.error("Could not find selected set",e,t),null;const{title:s,restoreFullState:i=!1}=n;return{nameInputValue:s,nameInputError:void 0,renameSet:n,restoreFullState:i}})}handleSettingsClick(e){e.stopPropagation();const{onChange:t,selectedId:n}=this.props;t({isValueShown:!1,selectedId:n})}handleBackgroundClick(e){it.debug("handleBackgroundClick"),e.target!==this.dropdownRef.current&&this.focusInput()}handleNameInputChange(e){const{value:t}=e.target,n=this.getNameError(t);this.setState({nameInputValue:t,nameInputError:n})}handleNameInputKeyPress(e){const{key:t}=e;t==="Enter"&&(e.preventDefault(),this.handleRenameConfirm())}isNameInputScreen(e=this.state){const{renameSet:t}=e;return t!==void 0}isRenamingExistingSet=ge((e,t)=>t!==void 0&&e.some(({id:n})=>n===t.id));applyFilterSet(e){const{onApply:t,filterSets:n}=this.props;if(e===void 0){it.debug("No filter selected");return}const s=n.find(({id:i})=>i===e);if(s===void 0){it.debug("Selected id not found in filterSets",e,n);return}it.debug("Apply filterSet",s),t(s)}focusInput(){this.dropdownRef.current?.focus()}focusRenameInput(){this.renameInputRef.current?.focus()}render(){const{nameInputValue:e,nameInputError:t,editId:n,renameSet:s,modifiedFilterSets:i,restoreFullState:o}=this.state,{isValueShown:l,filterSets:a,selectedId:d}=this.props,h=this.isNameInputScreen(),u=this.isRenamingExistingSet(i,s),m=i.length===0,g=!h&&m&&a.length===0,p=!h&&!g,C=r.jsxs("div",{className:"fa-layers mr-3",children:[r.jsx(ee,{icon:Ri,mask:Ua,transform:"shrink-1 down-5 right-7"}),r.jsx(ee,{icon:Es,className:"text-primary",transform:"shrink-6 down-5 right-7"})]}),f=r.jsxs("div",{className:"fa-layers",children:[r.jsx(ee,{icon:Ri,mask:Ua,transform:"shrink-1 down-5 right-7"}),r.jsx(ee,{icon:Va,transform:"shrink-1 down-5 right-7"})]});return r.jsx("div",{className:"filter-set-manager fill-parent-absolute",children:r.jsxs(ar,{className:"w-100 h-100",isFlipped:l,children:[r.jsx("div",{className:"filter-set-manager-settings-card fill-parent-absolute",children:r.jsxs("div",{className:"filter-set-manager-card-content",children:[g&&r.jsxs("div",{children:[r.jsx(B,{kind:"ghost",className:"btn btn-link no-underline",onClick:this.handleCaptureNewSet,icon:C,children:"Capture filter set"}),r.jsx("div",{className:"py-3 text-muted small",children:"Takes a snapshot of the currently applied filters on all panels, allowing you to restore saved filter sets later."})]}),h&&r.jsxs("div",{className:"d-flex flex-column justify-content-center","data-testid":"edit-filter-set-container",children:[r.jsxs("div",{className:"form-group",children:[r.jsx("label",{children:u?"Edit set":"Name captured set"}),r.jsxs("div",{className:"name-input-container",children:[r.jsx("input",{type:"text",className:"input-set-name form-control",placeholder:cR,value:e,ref:this.renameInputRef,onChange:this.handleNameInputChange,onKeyPress:this.handleNameInputKeyPress,spellCheck:"false"}),r.jsx(B,{"data-testid":"rename-confirm-button",kind:"ghost",className:"btn btn-link no-underline pt-2 pb-2",onClick:this.handleRenameConfirm,tooltip:"Save","test-id":"button-save",icon:oh}),r.jsx(B,{"data-testid":"rename-cancel-button",kind:"ghost",className:"btn btn-link no-underline pt-2 pb-2",onClick:this.handleRenameCancel,tooltip:"Cancel",icon:Kg})]}),t!==void 0&&r.jsx("div",{className:"error-message",children:t})]}),r.jsx("div",{className:"form-group",children:r.jsxs(Ul,{onChange:this.handleRestoreFullStateChange,value:`${o}`,children:[r.jsx(Wn,{value:"false",children:"Restore only filters"}),r.jsx(Wn,{value:"true",children:"Restore full table state"})]})})]}),p&&r.jsxs("div",{className:"filter-set-manager-settings-grid-1",children:[r.jsxs("div",{className:"form-group",children:[r.jsx("label",{children:"Edit filter sets"}),r.jsxs("div",{className:"filter-select-container",children:[r.jsxs("select",{"data-testid":"settings-card-filter-select",ref:this.editDropdownRef,value:n??"-1",className:"custom-select filter-value-select",onChange:this.handleEditDropdownChange,disabled:m,children:[m&&r.jsx("option",{value:"-1",disabled:!0,children:bc}),i.map(({id:b,title:w})=>r.jsx("option",{value:b,children:w},b))]}),r.jsx(B,{kind:"ghost",onClick:this.handleSetUpdate,disabled:m,icon:f,tooltip:"Update"}),r.jsx(B,{kind:"ghost",onClick:this.handleSetEdit,disabled:m,icon:go,tooltip:"Edit"}),r.jsx(B,{kind:"ghost",onClick:this.handleSetDelete,disabled:m,icon:Gt,tooltip:"Delete"})]})]}),r.jsx("div",{children:r.jsx(B,{kind:"ghost",className:"btn btn-link no-underline",onClick:this.handleCaptureNewSet,icon:C,children:"Capture new filter set"})}),r.jsxs("div",{className:"py-3 text-right",children:[r.jsx(B,{kind:"secondary",onClick:this.handleSettingsCancel,children:"Cancel"})," ",r.jsx(B,{kind:"primary",onClick:this.handleSettingsSave,children:"Save"})]})]})]})},"front"),r.jsxs("div",{className:"filter-set-manager-value-card fill-parent-absolute",onClick:this.handleBackgroundClick,children:[r.jsx("div",{className:"filter-set-manager-column",children:r.jsx("div",{className:"filter-set-manager-column-title",children:"Filter sets"})}),r.jsx("div",{className:"filter-set-manager-card-content",children:r.jsx("div",{className:"filter-set-manager-value-input",children:r.jsxs("div",{className:"filter-select-container",children:[r.jsxs("select",{"data-testid":"value-card-filter-select",ref:this.dropdownRef,value:d,className:"custom-select filter-value-select",onChange:this.handleFilterChange,children:[a.length===0&&r.jsx("option",{value:"-1",disabled:!0,children:bc}),a.map(({id:b,title:w})=>r.jsx("option",{value:b,children:w},b))]}),r.jsx(B,{"data-testid":"filter-apply-button",kind:"ghost",onClick:this.handleFilterApply,icon:hr,tooltip:"Apply Filter Set"})]})})}),r.jsx("div",{className:"filter-set-manager-menu",children:r.jsx(B,{kind:"ghost",className:"btn btn-link btn-link-icon m-2 px-2",onClick:this.handleSettingsClick,tooltip:"Settings",icon:r.jsx(ee,{icon:mo,transform:"grow-4"})})})]},"back")]})})}}const hR=kl;function td(c){const{model:e,widgetName:t,glContainer:n,description:s}=c,i=(e?.rowCount??0)-(e?.pendingRowCount??0),o=e?.displayString(i,"long");return r.jsx(ia,{widgetType:"Table",widgetName:t,glContainer:n,description:s,children:r.jsxs("div",{className:"column-statistics-grid",children:[r.jsx("span",{className:"column-statistic-operation",children:"Number of Rows"}),r.jsx("span",{className:"column-statistic-value",children:o})]})})}td.propTypes={glContainer:kr.Container.isRequired,widgetName:z.string.isRequired,description:z.string};td.defaultProps={description:null};const Sn=ne.module("IrisGridPanel"),uR=500,mR={IrisGrid:Au,IrisGridTableModel:_u,ContextMenuRoot:qc};class tr extends v.PureComponent{static defaultProps={onStateChange:()=>{},onPanelStateUpdate:()=>{}};static displayName="IrisGridPanel";static COMPONENT="IrisGridPanel";constructor(e){super(e),this.handleAdvancedSettingsChange=this.handleAdvancedSettingsChange.bind(this),this.handleColumnsChanged=this.handleColumnsChanged.bind(this),this.handleTableChanged=this.handleTableChanged.bind(this),this.handleColumnSelected=this.handleColumnSelected.bind(this),this.handleDataSelected=this.handleDataSelected.bind(this),this.handleError=this.handleError.bind(this),this.handleGridStateChange=this.handleGridStateChange.bind(this),this.handlePluginStateChange=this.handlePluginStateChange.bind(this),this.handlePartitionAppend=this.handlePartitionAppend.bind(this),this.handleCreateChart=this.handleCreateChart.bind(this),this.handleResize=this.handleResize.bind(this),this.handleShow=this.handleShow.bind(this),this.handleTabClicked=this.handleTabClicked.bind(this),this.handleDisconnect=this.handleDisconnect.bind(this),this.handleReconnect=this.handleReconnect.bind(this),this.handleLoadSuccess=this.handleLoadSuccess.bind(this),this.handleLoadError=this.handleLoadError.bind(this),this.isColumnSelectionValid=this.isColumnSelectionValid.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.handlePluginFilter=this.handlePluginFilter.bind(this),this.handlePluginFetchColumns=this.handlePluginFetchColumns.bind(this),this.handleClearAllFilters=this.handleClearAllFilters.bind(this),this.irisGrid=de.createRef(),this.pluginRef=de.createRef();const{panelState:t}=e;this.pluginState=null,this.state={error:null,isDisconnected:!1,isLoaded:!1,isLoading:!0,isModelReady:!1,model:void 0,advancedFilters:new Map,aggregationSettings:{aggregations:[],showOnTop:!1},advancedSettings:new Map(yu.DEFAULTS),customColumns:[],customColumnFormatMap:new Map,isFilterBarShown:!1,quickFilters:new Map,sorts:[],userColumnWidths:new Map,userRowHeights:new Map,reverseType:F.REVERSE_TYPE.NONE,movedColumns:[],movedRows:[],isSelectingPartition:!1,partition:void 0,partitionColumn:void 0,rollupConfig:void 0,showSearchBar:!1,searchValue:"",selectedSearchColumns:void 0,invertSearchColumns:!0,Plugin:void 0,pluginFilters:[],pluginFetchColumns:[],modelQueue:[],pendingDataMap:new Map,frozenColumns:void 0,panelState:t,irisGridStateOverrides:{},gridStateOverrides:{},isStuckToBottom:!1,isStuckToRight:!1,conditionalFormats:[],selectDistinctColumns:[]}}componentDidMount(){this.initModel()}componentDidUpdate(e,t){const{model:n}=this.state;n!==t.model&&(t.model!=null&&(this.stopModelListening(t.model),t.model.close()),n!=null&&this.startModelListening(n))}componentWillUnmount(){this.savePanelState.cancel(),this.modelPromise!=null&&(this.modelPromise.cancel(),this.modelPromise=void 0);const{model:e}=this.state;e&&(this.stopModelListening(e),e.close())}irisGrid;pluginRef;modelPromise;irisGridState;gridState;pluginState;getTableName(){const{metadata:e}=this.props;return e.table}getGridInputFilters=ge((e,t)=>Se.getInputFiltersForColumns(e,t.filter(({value:n,excludePanelIds:s})=>{const i=K.getIdFromPanel(this);return n!=null&&(s==null||i!=null&&!s.includes(i))})));getAlwaysFetchColumns=ge((e,t)=>{const n=K.getIdFromPanel(this),s=new Set(t);for(let i=0;i<e.length;i+=1){const{start:o}=e[i];o!=null&&o.panelId===n&&s.add(o.columnName)}return[...s]});getPluginContent=ge((e,t,n,s,i)=>!t||!Ks(t)||e==null||t.table==null?null:r.jsx("div",{className:"iris-grid-plugin",children:r.jsx(e,{ref:this.pluginRef,filter:this.handlePluginFilter,onFilter:this.handlePluginFilter,fetchColumns:this.handlePluginFetchColumns,onFetchColumns:this.handlePluginFetchColumns,table:t.table,user:n,panel:this,workspace:s,components:mR,onStateChange:this.handlePluginStateChange,pluginState:i})}));getDehydratedIrisGridPanelState=ge((e,t,n,s,i)=>Se.dehydrateIrisGridPanelState(e,{isSelectingPartition:t,partition:n,partitionColumn:s,advancedSettings:i}));getDehydratedIrisGridState=ge((e,t,n,s,i,o,l,a,d,h,u,m,g,p,C,f,b,w,S,T,y)=>Se.dehydrateIrisGridState(e,{advancedFilters:n,aggregationSettings:b,customColumnFormatMap:s,isFilterBarShown:i,metrics:{userColumnWidths:C,userRowHeights:f},quickFilters:o,customColumns:l,reverseType:a,rollupConfig:d,showSearchBar:h,searchValue:u,selectDistinctColumns:m,selectedSearchColumns:g,sorts:t,invertSearchColumns:p,pendingDataMap:w,frozenColumns:S,conditionalFormats:T,columnHeaderGroups:y}));getDehydratedGridState=ge((e,t,n,s,i)=>Se.dehydrateGridState(e,{isStuckToBottom:s,isStuckToRight:i,movedColumns:t,movedRows:n}));getCachedPanelState=ge((e,t,n,s)=>({irisGridPanelState:e,irisGridState:t,gridState:n,pluginState:s}));initModel(){this.setState({isModelReady:!1,isLoading:!0,error:null});const{makeModel:e}=this.props;this.modelPromise!=null&&this.modelPromise.cancel(),this.modelPromise=ye.makeCancelable(e(),t=>t.close()),this.modelPromise.then(this.handleLoadSuccess).catch(this.handleLoadError)}handleLoadSuccess(e){const t=e,{panelState:n,irisGridStateOverrides:s}=this.state,i=[];if(n!=null){const{irisGridState:o}=n,{aggregationSettings:l,customColumns:a,selectDistinctColumns:d=[],rollupConfig:h}={...o,...s};a.length>0&&i.push(u=>{u.customColumns=a}),h!=null&&h.columns.length>0&&i.push(u=>{u.rollupConfig=Se.getModelRollupConfig(u.originalColumns,h,l)}),d.length>0&&i.push(u=>{u.selectDistinctColumns=d})}this.setState({model:t,modelQueue:i}),this.initModelQueue(t,i)}initModelQueue(e,t){const n=e;if(t.length===0){this.modelInitialized(n);return}const s=t.shift();Sn.debug("initModelQueue",s),s&&s(n),this.setState({modelQueue:t})}handleAdvancedSettingsChange(e,t){Sn.debug("handleAdvancedSettingsChange",e,t),this.setState(({advancedSettings:n})=>n.get(e)===t?null:{advancedSettings:new Map(n).set(e,t)})}handlePluginFilter(e){const{model:t}=this.state;N(t);const{columns:n,formatter:s}=t,i=Se.getFiltersFromInputFilters(n,e,s.timeZone);this.setState({pluginFilters:i})}handlePluginFetchColumns(e){this.setState({pluginFetchColumns:e})}handleContextMenu(e){return this.pluginRef.current?.getMenu?.(e)??[]}isColumnSelectionValid(e){const{columnSelectionValidator:t}=this.props;return t&&e?t(this,e):!1}handleGridStateChange(e,t){this.irisGridState=e,this.gridState=t,this.setState({isLoaded:!0,isLoading:!1}),this.savePanelState();const{glEventHub:n,onStateChange:s}=this.props;n.emit(cn.STATE_CHANGED,this),s?.(e,t)}handlePluginStateChange(e){const{irisGridState:t,gridState:n}=this;this.pluginState=e,t!==null&&n!==null&&this.savePanelState()}handleColumnsChanged(e){const{isModelReady:t,model:n,modelQueue:s}=this.state;t?this.sendColumnsChange(e.detail):(N(n),this.initModelQueue(n,s))}handleTableChanged(e){Sn.debug("handleTableChanged",e);const{glEventHub:t}=this.props,{detail:n}=e;t.emit(Ze.TABLE_CHANGED,this,n)}handlePartitionAppend(e,t){const{glEventHub:n}=this.props,{name:s}=e,i=this.getTableName(),o=`${i} = ${i}.where("${s}=\`${t}\`")`;n.emit($t.SEND_COMMAND,o,!1,!0)}handleCreateChart(e,t){this.savePanelState.flush(),this.setState(()=>null,()=>{const{glEventHub:n,inputFilters:s,metadata:i}=this.props,{table:o}=i,{panelState:l}=this.state,a=K.getIdFromPanel(this);let d;l&&(d=Se.extractTableSettings(l,s)),n.emit(cn.CREATE_CHART,{metadata:{settings:e,sourcePanelId:a,table:o,tableSettings:d},table:Ks(t)?t.table:void 0})})}handleColumnSelected(e){const{glEventHub:t}=this.props;t.emit(cn.COLUMN_SELECTED,this,e)}handleDataSelected(e,t){const{glEventHub:n}=this.props;n.emit(cn.DATA_SELECTED,this,t)}handleResize(){this.updateGrid()}handleShow(){this.updateGrid()}handleTabClicked(){this.irisGrid.current&&this.irisGrid.current.focus()}handleError(e){Sn.error(e),this.setState({error:e,isLoading:!1})}handleDisconnect(){this.setState({error:new Error("Table disconnected"),isDisconnected:!0,isLoading:!1})}handleReconnect(){this.setState({isDisconnected:!1,error:null})}handleLoadError(e){ye.isCanceled(e)||this.handleError(e)}modelInitialized(e){const{glEventHub:t,loadPlugin:n}=this.props;if(this.modelPromise=void 0,this.loadPanelState(e),this.setState({isModelReady:!0}),Ks(e)){const{table:s}=e,{pluginName:i}=s;if(i!==""&&n!=null&&i!=null){const o=n(i);this.setState({Plugin:o})}t.emit(Ze.TABLE_CHANGED,this,s)}this.sendColumnsChange(e.columns)}handleClearAllFilters(){const e=this.irisGrid.current,{isDisconnected:t}=this.state;e!=null&&!t&&e.clearAllFilters()}sendColumnsChange(e){Sn.debug2("sendColumnsChange",e);const{glEventHub:t}=this.props;t.emit(Ze.COLUMNS_CHANGED,this,e)}startModelListening(e){e.addEventListener(Ce.EVENT.DISCONNECT,this.handleDisconnect),e.addEventListener(Ce.EVENT.RECONNECT,this.handleReconnect),e.addEventListener(Ce.EVENT.COLUMNS_CHANGED,this.handleColumnsChanged),e.addEventListener(Ce.EVENT.TABLE_CHANGED,this.handleTableChanged)}stopModelListening(e){e.removeEventListener(Ce.EVENT.DISCONNECT,this.handleDisconnect),e.removeEventListener(Ce.EVENT.RECONNECT,this.handleReconnect),e.removeEventListener(Ce.EVENT.COLUMNS_CHANGED,this.handleColumnsChanged),e.removeEventListener(Ce.EVENT.TABLE_CHANGED,this.handleTableChanged)}getCoordinateForColumn(e){const{model:t}=this.state;if(!t)return null;const n=this.irisGrid.current,{gridWrapper:s}=n||{},i=s?.getBoundingClientRect()??null;if(i==null||i.width<=0||i.height<=0)return null;N(n);const{metrics:o}=n.state;N(o);const{columnHeaderHeight:l,allColumnXs:a,allColumnWidths:d,right:h,columnHeaderMaxDepth:u}=o,m=t.getColumnIndexByName(e);N(m);const g=n.getVisibleColumn(m),p=a.get(g)??0,C=d.get(g)??0,f=Math.max(i.left,Math.min(g>h?i.right:i.left+p+C*.5,i.right)),b=i.top+l*u;return[f,b]}setFilterMap(e){const t=this.irisGrid.current;t?.setFilterMap(e)}setAdvancedFilterMap(e){const t=this.irisGrid.current;t?.setAdvancedFilterMap(e)}setFilters({quickFilters:e,advancedFilters:t}){Sn.debug("setFilters",e,t);const{model:n,isDisconnected:s}=this.state,i=this.irisGrid.current;if(i==null||s){Sn.debug("Ignore setFilters, model disconnected");return}N(n);const{columns:o,formatter:l}=n,a=Se.changeFilterColumnNamesToIndexes(n.columns,e).filter(([h])=>n.isFilterable(h)),d=Se.changeFilterColumnNamesToIndexes(n.columns,t).filter(([h])=>n.isFilterable(h));i.clearAllFilters(),i.setFilters({quickFilters:Se.hydrateQuickFilters(o,a,l.timeZone),advancedFilters:Se.hydrateAdvancedFilters(o,d,l.timeZone)})}setStateOverrides(e){Sn.debug("setStateOverrides",e);const{irisGridState:t,gridState:n}=e;this.setState({irisGridStateOverrides:t,gridStateOverrides:n},()=>{this.initModel()})}unsetFilterValue(){}loadPanelState(e){const{panelState:t,irisGridStateOverrides:n,gridStateOverrides:s}=this.state;if(t!=null)try{const{gridState:i,irisGridState:o,irisGridPanelState:l}=t,a={...n},{quickFilters:d,advancedFilters:h}=a;d&&(a.quickFilters=Se.changeFilterColumnNamesToIndexes(e.columns,d)),h&&(a.advancedFilters=Se.changeFilterColumnNamesToIndexes(e.columns,h));const{isSelectingPartition:u,partition:m,partitionColumn:g,advancedSettings:p}=Se.hydrateIrisGridPanelState(e,l),{advancedFilters:C,customColumns:f,customColumnFormatMap:b,isFilterBarShown:w,quickFilters:S,reverseType:T,rollupConfig:y,aggregationSettings:E,sorts:R,userColumnWidths:x,userRowHeights:D,showSearchBar:M,searchValue:O,selectDistinctColumns:H,selectedSearchColumns:L,invertSearchColumns:V,pendingDataMap:U,frozenColumns:j,conditionalFormats:P,columnHeaderGroups:Q}=Se.hydrateIrisGridState(e,{...o,...a}),{isStuckToBottom:$,isStuckToRight:J,movedColumns:A,movedRows:W}=Se.hydrateGridState(e,{...i,...s},o.customColumns);this.setState({advancedFilters:C,advancedSettings:p,conditionalFormats:P,customColumns:f,customColumnFormatMap:b,isFilterBarShown:w,isSelectingPartition:u,movedColumns:A,movedRows:W,partition:m,partitionColumn:g,quickFilters:S,reverseType:T,rollupConfig:y,aggregationSettings:E,sorts:R,userColumnWidths:x,userRowHeights:D,showSearchBar:M,searchValue:O,selectDistinctColumns:H,selectedSearchColumns:L,invertSearchColumns:V,pendingDataMap:U,frozenColumns:j,isStuckToBottom:$,isStuckToRight:J,columnHeaderGroups:Q})}catch(i){Sn.error("loadPanelState failed to load panelState",t,i)}}savePanelState=Ye(()=>{const{irisGridState:e,gridState:t,pluginState:n}=this;N(e);const{onPanelStateUpdate:s}=this.props,{model:i,panelState:o,isSelectingPartition:l,partition:a,partitionColumn:d,advancedSettings:h}=this.state,{advancedFilters:u,aggregationSettings:m,customColumnFormatMap:g,isFilterBarShown:p,quickFilters:C,customColumns:f,reverseType:b,rollupConfig:w,showSearchBar:S,searchValue:T,selectDistinctColumns:y,selectedSearchColumns:E,sorts:R,invertSearchColumns:x,metrics:D,pendingDataMap:M,frozenColumns:O,conditionalFormats:H,columnHeaderGroups:L}=e;N(i),N(D);const{userColumnWidths:V,userRowHeights:U}=D;N(t);const{isStuckToBottom:j,isStuckToRight:P,movedColumns:Q,movedRows:$}=t,J=this.getCachedPanelState(this.getDehydratedIrisGridPanelState(i,l,a,d,h),this.getDehydratedIrisGridState(i,R,u,g,p,C,f,b,w,S,T,y,E,x,V,U,m,M,O,H,L),this.getDehydratedGridState(i,Q,$,j,P),n);J!==o&&(Sn.debug("Saving panel state",this,J),this.setState({panelState:J}),s?.(J))},uR);updateGrid(){const e=this.irisGrid.current?.grid??null;e&&e.handleResize()}render(){const{children:e,glContainer:t,glEventHub:n,columnSelectionValidator:s,getDownloadWorker:i,inputFilters:o,links:l,metadata:a,panelState:d,user:h,workspace:u,settings:m,theme:g}=this.props,{advancedFilters:p,aggregationSettings:C,advancedSettings:f,conditionalFormats:b,customColumns:w,customColumnFormatMap:S,error:T,isDisconnected:y,isFilterBarShown:E,isSelectingPartition:R,isStuckToBottom:x,isStuckToRight:D,isLoaded:M,isLoading:O,isModelReady:H,model:L,movedColumns:V,movedRows:U,partition:j,partitionColumn:P,quickFilters:Q,reverseType:$,rollupConfig:J,sorts:A,userColumnWidths:W,userRowHeights:q,showSearchBar:Z,searchValue:le,selectDistinctColumns:G,selectedSearchColumns:oe,invertSearchColumns:ue,Plugin:ae,pluginFilters:ce,pluginFetchColumns:we,pendingDataMap:He,frozenColumns:Fe,columnHeaderGroups:mt}=this.state,et=T!=null?`Unable to open table. ${T}`:void 0,{table:De}=a,gt=L?.description??void 0,lt=d?.pluginState??null,vt=e??this.getPluginContent(ae,L,h,u,lt),{permissions:kt}=h,{canCopy:Cn,canDownloadCsv:zt}=kt;return r.jsx(Gr,{errorMessage:et,isDisconnected:y,isLoading:O,isLoaded:M,className:"iris-grid-panel",glContainer:t,glEventHub:n,onClearAllFilters:this.handleClearAllFilters,onResize:this.handleResize,onShow:this.handleShow,onTabFocus:this.handleShow,onTabClicked:this.handleTabClicked,widgetName:De,widgetType:"Table",description:gt,componentPanel:this,renderTabTooltip:()=>r.jsx(td,{model:L,widgetName:De,glContainer:t,description:gt}),children:H&&L&&r.jsx(Au,{advancedFilters:p,aggregationSettings:C,advancedSettings:f,alwaysFetchColumns:this.getAlwaysFetchColumns(l,we),columnAllowedCursor:"linker",columnNotAllowedCursor:"linker-not-allowed",customColumns:w,customColumnFormatMap:S,columnSelectionValidator:this.isColumnSelectionValid,conditionalFormats:b,inputFilters:this.getGridInputFilters(L.columns,o),applyInputFiltersOnInit:d==null,isFilterBarShown:E,isSelectingColumn:s!=null,isSelectingPartition:R,isStuckToBottom:x,isStuckToRight:D,movedColumns:V,movedRows:U,partition:j,partitionColumn:P,quickFilters:Q,reverseType:$,rollupConfig:J,settings:m,sorts:A,userColumnWidths:W,userRowHeights:q,model:L,showSearchBar:Z,searchValue:le,selectedSearchColumns:oe,selectDistinctColumns:G,invertSearchColumns:ue,onColumnSelected:this.handleColumnSelected,onCreateChart:this.handleCreateChart,onDataSelected:this.handleDataSelected,onError:this.handleError,onPartitionAppend:this.handlePartitionAppend,onStateChange:this.handleGridStateChange,onContextMenu:this.handleContextMenu,onAdvancedSettingsChange:this.handleAdvancedSettingsChange,customFilters:ce,pendingDataMap:He,canCopy:Cn,canDownloadCsv:zt,ref:this.irisGrid,getDownloadWorker:i,frozenColumns:Fe,theme:g,columnHeaderGroups:mt,children:vt})})}}const gR=(c,{localDashboardId:e=un})=>({inputFilters:zr(c,e),links:Ni(c,e),columnSelectionValidator:qr(c,e),user:Sh(c),workspace:ql(c),settings:wt(c)}),pR=St(gR,null,null,{forwardRef:!0})(tr),qs=pR;const Sc=ne.module("InputFilter"),fR=150;class Ml extends v.Component{static PLACEHOLDER="Enter value...";static defaultProps={column:null,isValueShown:!1,value:null};constructor(e){super(e),this.handleColumnChange=this.handleColumnChange.bind(this),this.handleInputKeyPress=this.handleInputKeyPress.bind(this),this.handleValueChange=this.handleValueChange.bind(this),this.handleSettingsCancel=this.handleSettingsCancel.bind(this),this.handleSettingsClick=this.handleSettingsClick.bind(this),this.handleSettingsSave=this.handleSettingsSave.bind(this),this.handleBackgroundClick=this.handleBackgroundClick.bind(this),this.inputRef=de.createRef();const{column:t,isValueShown:n,value:s}=e;this.state={column:t,selectedColumn:t,value:s,isValueShown:n}}componentDidUpdate(e,t){const{column:n}=this.props,{column:s,value:i,isValueShown:o}=this.state;n!==e.column&&this.setState({column:n,selectedColumn:n}),o!==void 0&&o&&o!==t.isValueShown&&this.focusInput(),(s!==t.column||i!==t.value||o!==t.isValueShown)&&this.sendUpdate()}componentWillUnmount(){this.sendUpdate.flush()}inputRef;getItemLabel=Re((e,t)=>{const{name:n,type:s}=e[t];if(t>0&&e[t-1].name===n||t<e.length-1&&e[t+1].name===n){const i=s.substring(s.lastIndexOf(".")+1);return`${n} (${i})`}return n});handleColumnChange(e){const{columns:t}=this.props,{value:n}=e.target,s=t[parseInt(n,10)];Sc.debug2("handleColumnChange",s),this.setState({selectedColumn:s,value:void 0})}handleInputKeyPress(e){e.key==="Enter"&&(e.preventDefault(),e.stopPropagation(),this.setState(({value:t})=>t==null?{value:""}:null,()=>{this.sendUpdate(),this.sendUpdate.flush()}))}handleValueChange(e){const{value:t}=e.target;Sc.debug2("handleValueChange",t),this.setState({value:t})}handleSettingsCancel(){const{column:e}=this.state;this.setState({selectedColumn:e,isValueShown:!0})}handleSettingsSave(){const{selectedColumn:e}=this.state;this.setState({column:e,isValueShown:!0})}handleSettingsClick(e){const{column:t}=this.state;this.setState({selectedColumn:t,isValueShown:!1}),e.stopPropagation()}handleBackgroundClick(e){e.target!==this.inputRef.current&&this.focusInput()}focusInput(){this.inputRef.current!==null&&(this.inputRef.current.select(),this.inputRef.current.focus())}clearFilter(){this.setState({value:""})}setFilterState({name:e,type:t,value:n,isValueShown:s}){const i=e!=null&&t!=null?{name:e,type:t}:void 0,o=s===void 0?{column:i,value:n}:{column:i,value:n,isValueShown:s};this.setState(o)}sendUpdate=Ye(()=>{const{onChange:e}=this.props,{column:t,value:n,isValueShown:s}=this.state;e({column:t,isValueShown:s,value:n})},fR);render(){const{columns:e}=this.props,{column:t,isValueShown:n,selectedColumn:s,value:i}=this.state,o=i==null||i.length===0?Ml.PLACEHOLDER.length:i.length;let l=null;if(t!=null){const a=e.findIndex(d=>d.name===t.name&&d.type===t.type);l=a>=0?this.getItemLabel(e,a):t.name}return r.jsxs(ar,{className:"input-filter fill-parent-absolute",isFlipped:n??!1,children:[r.jsx("div",{className:"input-filter-settings-card",children:r.jsxs("div",{className:"input-filter-settings-content",children:[r.jsxs("div",{className:"input-filter-settings-grid",children:[r.jsx("label",{children:"Filter Column"}),r.jsxs("select",{value:e.findIndex(a=>a.name===s?.name&&a.type===s?.type),className:"custom-select",onChange:this.handleColumnChange,children:[e.map((a,d)=>r.jsx("option",{value:d,children:this.getItemLabel(e,d)},`${a.name}/${a.type}`)),e.length===0&&r.jsx("option",{value:"-1",disabled:!0,children:"No Available Columns"})]}),r.jsx("div",{className:"text-muted small",children:"Input filter control will apply its filter to all columns matching this name in this dashboard."})]}),r.jsxs("div",{className:"input-filter-settings-buttons",children:[r.jsx(B,{kind:"secondary",onClick:this.handleSettingsCancel,disabled:t==null,children:"Cancel"}),r.jsx(B,{kind:"primary",className:"ml-2",onClick:this.handleSettingsSave,disabled:s==null,children:"Save"})]})]})}),r.jsxs("div",{className:"input-filter-value-card",onClick:this.handleBackgroundClick,children:[r.jsx("div",{className:"input-filter-column",children:r.jsxs("div",{className:"input-filter-column-title",children:[l," Filter"]})}),r.jsx("div",{className:"d-flex justify-content-center align-items-center h-100 w-100",children:r.jsx("div",{className:"input-filter-value-input d-flex flex-column justify-content-center",children:r.jsx("input",{type:"text",ref:this.inputRef,placeholder:Ml.PLACEHOLDER,value:i??"",onChange:this.handleValueChange,onKeyPress:this.handleInputKeyPress,style:{width:`${o+3}ch`},spellCheck:"false"})})}),r.jsx("div",{className:"input-filter-menu",children:r.jsx(B,{kind:"ghost",className:"m-2 px-2",onClick:this.handleSettingsClick,icon:r.jsx(ee,{icon:mo,transform:"grow-4"}),tooltip:"Input Filter Settings"})})]})]})}}const CR=Ml,bR=250;class SR extends v.Component{static defaultProps={panelState:null};static COMPONENT="InputFilterPanel";static displayName="InputFilterPanel";constructor(e){super(e),this.handleChange=Ye(this.handleChange.bind(this),bR),this.handleClearAllFilters=this.handleClearAllFilters.bind(this),this.inputFilterRef=de.createRef();const{panelState:t}=e,{value:n,isValueShown:s=!1,name:i,type:o,timestamp:l}=t??{};this.state={columns:[],column:i!=null&&o!=null?{name:i,type:o}:void 0,value:n,timestamp:l,isValueShown:s,wasFlipped:!1,skipUpdate:!1,panelState:t}}componentDidMount(){this.updateColumns();const{column:e,value:t,timestamp:n}=this.state;if(e!=null){const{name:s,type:i}=e;this.sendUpdate(s,i,t,n)}}componentDidUpdate(e){const{columns:t}=this.props;t!==e.columns&&this.updateColumns()}inputFilterRef;handleChange({column:e,isValueShown:t=!1,value:n}){let s,i;e!=null&&({name:s,type:i}=e);let o=!0,l=Date.now();this.setState(({panelState:a,timestamp:d,wasFlipped:h,skipUpdate:u})=>{const m=a!=null&&t!==a.isValueShown&&s===a.name&&i===a.type&&n===a.value;return o=(!u&&t&&(!m||!h))??!1,o||(l=d),{panelState:{isValueShown:t,name:s,type:i,value:n,timestamp:l},timestamp:l,wasFlipped:m,skipUpdate:!1}},()=>{o&&this.sendUpdate(s,i,n,l)})}handleClearAllFilters(){this.inputFilterRef.current?.clearFilter()}sendUpdate(e,t,n,s){const{glEventHub:i}=this.props;i.emit(Ze.FILTERS_CHANGED,this,{name:e,type:t,value:n,timestamp:s})}setPanelState(e,t=!1){this.setState({skipUpdate:!t}),this.inputFilterRef.current?.setFilterState(e)}updateColumns(){const{columns:e}=this.props;e!=null&&this.setState(t=>{const{column:n}=t;return n==null&&e.length>0?{columns:[...e],column:e[0]}:n!=null&&!e.find(({name:s,type:i})=>n.name===s&&n.type===i)?{columns:[...e,n]}:{columns:[...e]}})}render(){const{glContainer:e,glEventHub:t}=this.props,{column:n,columns:s,isValueShown:i,value:o}=this.state;return r.jsx(qn,{className:"iris-input-filter-panel",componentPanel:this,glContainer:e,glEventHub:t,onClearAllFilters:this.handleClearAllFilters,isClonable:!0,isRenamable:!0,children:r.jsx(CR,{ref:this.inputFilterRef,column:n,columns:s,onChange:this.handleChange,isValueShown:i,value:o})})}}const wR=(c,e)=>{const{localDashboardId:t}=e;return{columns:ju(c,t)}},vR=St(wR,null,null,{forwardRef:!0})(SR),no=vR;const Et=ne.module("FilterSetManagerPanel");function TR(c){return c.setPanelState!=null}class Ll extends v.Component{static defaultProps={panelState:null};static COMPONENT="FilterSetManagerPanel";static changeFilterIndexesToColumnNames(e,t){return t.map(([n,s])=>{if(n>=e.columns.length)return null;const{name:i}=e.columns[n];return{name:i,filter:s}}).filter(n=>n!=null)}constructor(e){super(e),this.handleChange=this.handleChange.bind(this),this.handleFilterApply=this.handleFilterApply.bind(this),this.handleSetsUpdate=this.handleSetsUpdate.bind(this),this.handleGetFilterState=this.handleGetFilterState.bind(this);const{panelState:t,filterSets:n}=e,{selectedId:s=n.length>0?n[0].id:void 0,isValueShown:i=!1}=t??{};this.state={selectedId:s,isValueShown:i,panelState:t}}getFilterState(){const{dashboardOpenedPanelMap:e}=this.props,t=[];return[...e.keys()].forEach(n=>{const s=e.get(n);if(s===void 0){Et.error("Could not get panel",s);return}const i=K.getComponentNameFromPanel(s),o=K.getIdFromPanel(s);Et.debug("Panel:",s,i);const{glContainer:l=null}=s.props;if(l==null){Et.error("Could not get panel container",s);return}const a=K.getComponentConfigFromContainer(l);if(a==null){Et.error("Could not get component config from container",l);return}const d=K.getPanelComponentState(a);if(d==null){Et.debug(`Panel state is null ${o}`);return}switch(i){case K.getComponentName(tr):{let h;o!=null&&(h=this.getIrisGridPanelFilters(o,d)),h!=null&&t.push({panelId:o,type:i,state:h});break}case K.getComponentName(no):case K.getComponentName(Ys):{const{isValueShown:h,name:u,type:m,value:g}=d;t.push({panelId:o,type:i,state:{isValueShown:h,name:u,type:m,value:g}});break}}}),t}getIrisGridPanelFilters(e,t){const{panelTableMap:n}=this.props,s=n.get(e);if(s==null)return Et.error(`Unable to get table for panel ${e}.`),null;const{irisGridState:i={advancedFilters:void 0,quickFilters:void 0},gridState:o={}}=t,{advancedFilters:l,quickFilters:a}=i;let d;l&&(d=Ll.changeFilterIndexesToColumnNames(s,l));let h;return a&&(h=Ll.changeFilterIndexesToColumnNames(s,a)),{irisGridState:{...i,advancedFilters:d,quickFilters:h},gridState:{...o}}}handleGetFilterState(){return this.getFilterState()}handleChange({isValueShown:e,selectedId:t}){Et.debug("handleChange",e,t),this.setState({isValueShown:e,selectedId:t}),this.updatePanelState()}handleFilterApply(e){const{dashboardOpenedPanelMap:t}=this.props,{panels:n,restoreFullState:s=!1}=e;Et.debug("Apply filters from filter set",e),n.forEach(({panelId:i,type:o,state:l})=>{if(i==null){Et.debug("panel is null",i);return}if(!t.has(i)){Et.debug("Ignore closed panel",i);return}Et.debug("Apply panel filters",i,o,l);const a=t.get(i);switch(o){case K.getComponentName(tr):this.restoreIrisGridFilters(a,l,s);break;case K.getComponentName(no):case K.getComponentName(Ys):this.restoreInputFilterState(a,l);break}})}handleSetsUpdate(e){const{setDashboardFilterSets:t,localDashboardId:n}=this.props;Et.debug("Saving updated sets",e),t(n,[...e])}updatePanelState(){this.setState(({selectedId:e,isValueShown:t})=>({panelState:{selectedId:e,isValueShown:t}}))}restoreIrisGridFilters(e,t,n){const{irisGridState:s={},advancedFilters:i=[],quickFilters:o=[]}=t,{advancedFilters:l=i,quickFilters:a=o}=s,{panelTableMap:d}=this.props,h=K.getIdFromPanel(e);if(h==null){Et.error("Panel Id is null.");return}if(d.get(h)==null){Et.error(`Unable to get table for panel ${h}.`);return}Et.debug("restoreIrisGridFilters",h,t,n),n?e.setStateOverrides(t):e.setFilters({quickFilters:a,advancedFilters:l})}restoreInputFilterState(e,t){const n={...t};delete n.isValueShown,Et.debug("restoreInputFilterState",e,n),e&&TR(e)&&e.setPanelState(n)}render(){const{glContainer:e,glEventHub:t,filterSets:n}=this.props,{isValueShown:s,selectedId:i}=this.state;return r.jsx(qn,{className:"filter-set-manager-panel",componentPanel:this,glContainer:e,glEventHub:t,isClonable:!0,isRenamable:!0,children:r.jsx("div",{className:"input-filter-container h-100 w-100 container",children:r.jsx(hR,{onChange:this.handleChange,onApply:this.handleFilterApply,onUpdateSets:this.handleSetsUpdate,isValueShown:s,filterSets:n,selectedId:i,getFilterState:this.handleGetFilterState})})})}}const ER=(c,e)=>{const{localDashboardId:t}=e;return{filterSets:yy(c,t),dashboardOpenedPanelMap:au(c,t),dashboardInputFilters:zr(c,t),panelTableMap:Kr(c,t)}},yR=St(ER,{setDashboardFilterSets:My},null,{forwardRef:!0})(Ll),ka=yR;const wc=ne.module("LogPanel");class RR extends v.PureComponent{static defaultProps={session:null};static COMPONENT="LogPanel";static TITLE="Log";constructor(e){super(e),this.handleResize=this.handleResize.bind(this),this.handleShow=this.handleShow.bind(this),this.handleHide=this.handleHide.bind(this),this.handleSessionOpened=this.handleSessionOpened.bind(this),this.handleSessionClosed=this.handleSessionClosed.bind(this),this.isBottomVisible=!0,this.logView=null;const{session:t}=this.props;this.state={session:t}}isBottomVisible;logView;handleResize(){this.updateDimensions()}handleShow(){this.updateDimensions(),this.logView&&(this.logView.triggerFindWidget(),this.isBottomVisible&&this.logView.scrollToBottom())}handleHide(){this.logView&&(this.isBottomVisible=this.logView.isBottomVisible())}handleSessionOpened(e){wc.debug("Session opened",[e]),this.setState({session:e})}handleSessionClosed(e){wc.debug("Session closed",e)}updateDimensions(){this.logView&&this.logView.updateDimensions()}render(){const{glContainer:e,glEventHub:t}=this.props,{session:n}=this.state;return r.jsxs(qn,{componentPanel:this,glContainer:e,glEventHub:t,onResize:this.handleResize,onHide:this.handleHide,onShow:this.handleShow,onSessionOpen:this.handleSessionOpened,onSessionClose:this.handleSessionClosed,children:[n==null&&r.jsx("div",{className:"log-panel-disconnected-message",children:"Waiting for session connection"}),n!=null&&r.jsx(Qf,{session:n,ref:s=>{this.logView=s}})]})}}const xR=(c,e)=>({session:Qs(c,e.localDashboardId)?.session}),DR=St(xR,null,null,{forwardRef:!0})(RR),Ol=DR;class IR extends v.PureComponent{static defaultProps={isEditing:!1};render(){const{isEditing:e,children:t,onDoubleClick:n}=this.props;return r.jsxs("div",{className:"markdown-editor-container h-100 w-100",onDoubleClick:n,children:[r.jsx("div",{className:Y("text-muted","edit-hint",{viewing:e===void 0||!e}),children:r.jsxs("span",{children:["double-click to edit ",r.jsx(ee,{icon:go})]})}),t]})}}const FR=ne.module("MarkdownStartPage");class NR extends v.PureComponent{static defaultProps={closedMarkdowns:[],onOpen:()=>{},onCreate:()=>{},onDelete:()=>{}};constructor(e){super(e),this.handleDeleteButtonClick=this.handleDeleteButtonClick.bind(this),this.handleDeleteModalClose=this.handleDeleteModalClose.bind(this),this.state={isDeleteModalShown:!1}}handleDeleteButtonClick(e){this.setState({isDeleteModalShown:!0,toBeDeleted:e})}handleDeleteModalClose(){this.setState({isDeleteModalShown:!1,toBeDeleted:void 0})}handleDeleteMarkdown(e){if(FR.debug("delete markdown: ",e),e!==void 0){const{onDelete:t}=this.props;t(e)}this.setState({isDeleteModalShown:!1,toBeDeleted:void 0})}render(){const{closedMarkdowns:e,onOpen:t,onCreate:n}=this.props,{isDeleteModalShown:s,toBeDeleted:i}=this.state;return r.jsx("div",{className:"markdown-panel-start-page h-100 w-100",children:r.jsxs("div",{className:"markdown-panel-start-page-container",children:[r.jsxs("div",{className:"markdown-panel-start-list",children:[r.jsx("h3",{className:"list-title",children:"Start"}),r.jsx("div",{className:"list-item",children:r.jsx(B,{kind:"ghost",className:"title",onClick:n,children:"New Markdown Note"})})]}),r.jsxs("div",{className:"markdown-panel-start-list",children:[r.jsx("h3",{className:"list-title",children:"Recently Closed from Dashboard"}),e.map(o=>r.jsxs("div",{className:"list-item",children:[r.jsx(B,{kind:"ghost",className:"title",onClick:()=>t(o),children:o.title}),r.jsx("button",{className:"btn-link icon",type:"button",onClick:()=>{this.handleDeleteButtonClick(o)},children:r.jsx(ee,{icon:Gt})})]},o.id)),r.jsxs(Gl,{isOpen:s,toggle:this.handleDeleteModalClose,className:"modal-dialog-centered markdown-delete-modal theme-bg-light",children:[r.jsx(zl,{children:"Are you sure you want to permanently delete this note?"}),r.jsx(Kl,{children:"You can't undo this action."}),r.jsxs(Yc,{children:[r.jsx(B,{kind:"secondary",onClick:this.handleDeleteModalClose,children:"Cancel"}),r.jsx(B,{kind:"danger",onClick:()=>{this.handleDeleteMarkdown(i)},children:"Delete"})]})]})]})]})})}}const kR=NR,MR=c=>{const{children:e,className:t}=c,n=t!==void 0&&t?.startsWith("language-")?t.substring(9):"plaintext";return r.jsx("pre",{children:r.jsx("code",{children:r.jsx(Yl,{language:n,children:de.Children.map(e,s=>typeof s=="string"?s.trim():s)})})})};class LR extends v.PureComponent{static defaultProps={isEditing:!1,content:""};constructor(e){super(e),this.container=null}container;render(){const{isEditing:e,content:t,onEditorInitialized:n}=this.props;return r.jsx("div",{className:"markdown-editor-container",ref:s=>{this.container=s},children:e?r.jsx(br,{settings:{language:"markdown",value:t,lineNumbers:"off"},onEditorInitialized:n}):r.jsx(Vc,{components:{code:MR},children:t})})}}const Qo=ne.module("MarkdownPanel");class OR extends v.Component{static defaultProps={panelState:null};static COMPONENT="MarkdownPanel";constructor(e){super(e),this.handleContainerDoubleClick=this.handleContainerDoubleClick.bind(this),this.handleCreateMarkdown=this.handleCreateMarkdown.bind(this),this.handleDeleteMarkdown=this.handleDeleteMarkdown.bind(this),this.handleOpenMarkdown=this.handleOpenMarkdown.bind(this),this.handleEditorInitialized=this.handleEditorInitialized.bind(this),this.handleEditorBlur=this.handleEditorBlur.bind(this),this.handleEditorResize=this.handleEditorResize.bind(this);const{panelState:t}=e;let n=null;t!=null&&t.content!=null&&({content:n}=t),this.state={isStartPageShown:n==null,isEditing:!1,content:n,panelState:t},this.markdownEditor=null}markdownEditor;editor;setEditorPosition(e){N(this.markdownEditor);const{container:t}=this.markdownEditor;if(this.editor&&t){const n=t.getBoundingClientRect().top,s=t.scrollTop,i=t.scrollHeight,o=this.editor.getModel()?.getLineCount()??0;let l=Math.round((s+e-n)/i*o);l>o&&(l=o),this.editor.revealLine(l),this.editor.setPosition({lineNumber:l,column:1}),this.editor.focus()}}getClosedMarkdowns=ge(e=>e.filter(t=>t.component==="MarkdownPanel").reverse());handleContainerDoubleClick(e){const{isEditing:t}=this.state,n=e.clientY;t||this.setState({isEditing:!0},()=>{this.setEditorPosition(n)})}handleEditorInitialized(e){Qo.debug("Markdown Editor Initialized..."),this.editor=e}handleCreateMarkdown(){Qo.debug("create markdown..."),this.setState({isStartPageShown:!1,content:"",isEditing:!0,panelState:{content:""}},()=>{this.editor!=null&&this.editor.focus!=null&&this.editor.focus()})}handleOpenMarkdown(e){Qo.debug("open markdown...",e);const{glContainer:t,glEventHub:n}=this.props,s=K.getComponentConfigFromContainer(t);n.emit(Ee.REOPEN,e,s)}handleDeleteMarkdown(e){const{glEventHub:t}=this.props;t.emit(Ee.DELETE,e)}handleEditorBlur(e){Qo.debug("markdown content changed, saving...");const{isEditing:t}=this.state;if(!t||this.markdownEditor!=null&&this.markdownEditor.container!=null&&this.markdownEditor.container.contains(e.relatedTarget))return;const n=this.editor?.getValue();this.setState({content:n,isEditing:!1,panelState:{content:n}})}handleEditorResize(){const{isEditing:e}=this.state;e&&this.editor&&this.editor.layout()}render(){const{glContainer:e,glEventHub:t,closedPanels:n}=this.props,{isEditing:s,isStartPageShown:i,content:o}=this.state,l=this.getClosedMarkdowns(n);return r.jsx(qn,{glContainer:e,glEventHub:t,className:"markdown-panel",componentPanel:this,onResize:this.handleEditorResize,onBlur:this.handleEditorBlur,isClonable:!0,isRenamable:!0,children:i?r.jsx(kR,{closedMarkdowns:l,onCreate:this.handleCreateMarkdown,onOpen:this.handleOpenMarkdown,onDelete:this.handleDeleteMarkdown}):r.jsx(IR,{isEditing:s,onDoubleClick:this.handleContainerDoubleClick,children:r.jsx(LR,{ref:a=>{this.markdownEditor=a},isEditing:s,content:o??void 0,onEditorInitialized:this.handleEditorInitialized})})})}}const AR=(c,e)=>{const{localDashboardId:t}=e;return{closedPanels:CS(c,t)}},_R=St(AR,null,null,{forwardRef:!0})(OR),Wi=_R;class PR extends v.PureComponent{static defaultProps={onRunCode:()=>{}};constructor(e){super(e),this.handleRunSelected=this.handleRunSelected.bind(this),this.renderCodeBlock=this.renderCodeBlock.bind(this),this.renderLink=this.renderLink.bind(this),this.commands=new Map,this.codeElements=new Map,this.editorScrollView=de.createRef(),this.state={hasCode:!1,hasRunCode:!1,nextStartLine:null}}componentDidMount(){this.updateHasCode()}componentDidUpdate(){this.updateHasCode()}commands;codeElements;editorScrollView;updateHasCode(){const{hasCode:e}=this.state;this.commands.size===0&&e?this.setState({hasCode:!1}):this.commands.size>0&&!e&&this.setState({hasCode:!0})}getNextStartLine(e){const t=[...this.commands.keys()],n=t.findIndex(s=>s===e)+1;return n>=t.length?null:t[n]}handleRunSelected(e){e.preventDefault(),e.stopPropagation();const{nextStartLine:t}=this.state,n=[...this.commands.keys()],s=n.findIndex(h=>h===t||t==null);if(s<0)return;const i=n[s],o=this.commands.get(i),l=this.getNextStartLine(i),d=this.codeElements.get(i)?.current?.parentElement?.nextElementSibling;if(d!=null){const{offsetTop:h}=d,u=h;this.editorScrollView.current?.scroll({top:u,left:0})}this.runCode(o),this.setState({nextStartLine:l})}runCode(e){const{onRunCode:t}=this.props;t(e),this.setState({hasRunCode:!0})}renderCodeBlock(e){const{children:t,className:n,inline:s,node:i}=e,{hasRunCode:o,nextStartLine:l}=this.state,{children:a,position:d}=i;N(d);const{start:h}=d,{line:u}=h,m=a[0].value,g=de.createRef(),p=this.commands.size===0,C=l===u||p&&l==null&&!o,f=n!==void 0&&n.startsWith("language-")?n.substring(9):"plaintext";return s!=null&&s?r.jsx("code",{className:n,children:t}):(this.commands.set(u,m),this.codeElements.set(u,g),r.jsxs("div",{className:Y("markdown-notebook-code-block",{"is-selected":C}),ref:g,onClick:()=>{this.setState({nextStartLine:u})},role:"presentation",children:[r.jsx(B,{kind:"ghost",icon:rl,className:"btn-play-block",onClick:b=>{b.stopPropagation(),b.preventDefault(),this.runCode(m),this.setState({nextStartLine:u})},tooltip:"Run code"}),r.jsx("code",{children:r.jsx(Yl,{language:f,children:de.Children.map(t,b=>typeof b=="string"?b.trim():b)})})]}))}renderLink(e){const{onLinkClick:t}=this.props,{href:n,children:s,target:i}=e;return r.jsx("a",{href:n,onClick:t,target:i,children:s})}render(){const{content:e,transformImageUri:t,transformLinkUri:n}=this.props,{hasCode:s,hasRunCode:i,nextStartLine:o}=this.state;return r.jsxs("div",{className:"markdown-notebook",children:[r.jsx("div",{className:"markdown-notebook-toolbar",children:r.jsx(B,{className:Y("btn-play-selected-cell",{flashing:s&&!i}),kind:"ghost",icon:rl,onClick:this.handleRunSelected,tooltip:"Run code and select next",disabled:i&&o==null||!s,children:"Run Selected Code"})}),r.jsx("div",{className:"markdown-notebook-content",ref:this.editorScrollView,children:r.jsx(Vc,{components:{code:this.renderCodeBlock,a:this.renderLink},linkTarget:"_blank",remarkPlugins:[xm],transformLinkUri:n,transformImageUri:t,includeElementIndex:!0,children:e})})]})}}const jR=PR;const Pe=ne.module("NotebookPanel"),vc=400;class $s extends v.Component{static COMPONENT="NotebookPanel";static POPPER_OPTIONS={placement:"bottom-end"};static DEFAULT_NAME="Untitled";static handleError(e){ye.isCanceled(e)||Pe.error(e)}static defaultProps={isDashboardActive:!0,isPreview:!1,session:null,sessionLanguage:null,defaultNotebookSettings:null};static languageFromFileName(e){switch(fe.getExtension(e).toLowerCase()){case"py":case"python":return"python";case"groovy":return"groovy";case"scala":return"scala";default:return null}}constructor(e){super(e),this.handleBlur=this.handleBlur.bind(this),this.handleCloseCancel=this.handleCloseCancel.bind(this),this.handleCloseDiscard=this.handleCloseDiscard.bind(this),this.handleCloseSave=this.handleCloseSave.bind(this),this.handleCopy=this.handleCopy.bind(this),this.handleEditorInitialized=this.handleEditorInitialized.bind(this),this.handleEditorWillDestroy=this.handleEditorWillDestroy.bind(this),this.handleEditorChange=this.handleEditorChange.bind(this),this.handleFind=this.handleFind.bind(this),this.handleMinimapChange=this.handleMinimapChange.bind(this),this.handleWordWrapChange=this.handleWordWrapChange.bind(this),this.handleFocus=this.handleFocus.bind(this),this.handleLinkClick=this.handleLinkClick.bind(this),this.handleLoadSuccess=this.handleLoadSuccess.bind(this),this.handleLoadError=this.handleLoadError.bind(this),this.handleTabClick=this.handleTabClick.bind(this),this.handleRenameFile=this.handleRenameFile.bind(this),this.handleResize=this.handleResize.bind(this),this.handleRunCommand=this.handleRunCommand.bind(this),this.handleRunAll=this.handleRunAll.bind(this),this.handleRunSelected=this.handleRunSelected.bind(this),this.handleSave=this.handleSave.bind(this),this.handleSaveAsCancel=this.handleSaveAsCancel.bind(this),this.handleSaveAsSubmit=this.handleSaveAsSubmit.bind(this),this.handleSaveError=this.handleSaveError.bind(this),this.handleSaveSuccess=this.handleSaveSuccess.bind(this),this.handleSessionOpened=this.handleSessionOpened.bind(this),this.handleSessionClosed=this.handleSessionClosed.bind(this),this.handleShow=this.handleShow.bind(this),this.handleShowRename=this.handleShowRename.bind(this),this.handleTab=this.handleTab.bind(this),this.handleTabFocus=this.handleTabFocus.bind(this),this.handleTabBlur=this.handleTabBlur.bind(this),this.handleTransformLinkUri=this.handleTransformLinkUri.bind(this),this.handleOverwrite=this.handleOverwrite.bind(this),this.handlePreviewPromotion=this.handlePreviewPromotion.bind(this),this.getDropdownOverflowActions=this.getDropdownOverflowActions.bind(this),this.pending=new Yn,this.debouncedSavePanelState=Ye(this.savePanelState.bind(this),vc),this.debouncedLoad=Ye(this.load.bind(this),vc),this.notebook=null,this.tabTitleElement=null,this.tabInitOnce=!1;const{isDashboardActive:t,session:n,sessionLanguage:s,panelState:i}=e;let o={value:"",language:"",wordWrap:"off"},l=null,{isPreview:a}=e;i!=null&&({fileMetadata:l=l,isPreview:a=a,settings:o=o}=i);const d=l!=null&&fe.hasPath(l.itemName),u=d===!0&&o.value!=null||!d&&o.value!=null&&o.value.length>0?1:0;this.state={error:void 0,isDashboardActive:t,isFocused:!1,isLoading:!0,isLoaded:!1,isPreview:a,savedChangeCount:0,changeCount:u,fileMetadata:l,settings:o,session:n,sessionLanguage:s,panelState:{fileMetadata:l,settings:o},showCloseModal:!1,showSaveAsModal:!1,scriptCode:""},Pe.debug("constructor",e,this.state)}componentDidMount(){const{glContainer:e,glEventHub:t}=this.props,{tab:n}=e;n!=null&&this.initTab(n),this.initNotebookContent(),t.on(Ue.RENAME_FILE,this.handleRenameFile),e.on(Ue.PROMOTE_FROM_PREVIEW,this.handlePreviewPromotion)}componentDidUpdate(e,t){const{isPreview:n,settings:s}=this.state,{wordWrap:i}=s,{defaultNotebookSettings:o}=this.props;n!==t.isPreview&&this.setPreviewStatus(),i!==t.settings.wordWrap&&(this.updateEditorWordWrap(),this.debouncedSavePanelState()),o.isMinimapEnabled!==e.defaultNotebookSettings.isMinimapEnabled&&this.updateEditorMinimap()}componentWillUnmount(){this.debouncedSavePanelState.flush(),this.pending.cancel();const{glEventHub:e,glContainer:t}=this.props,{fileMetadata:n,isPreview:s}=this.state;e.off(Ue.RENAME_FILE,this.handleRenameFile),t.off(Ue.PROMOTE_FROM_PREVIEW,this.handlePreviewPromotion),e.emit(Ue.UNREGISTER_FILE,n,s)}pending;debouncedSavePanelState;debouncedLoad;notebook;tabTitleElement;tabInitOnce;editor;initTab(e){this.tabInitOnce||(this.tabInitOnce=!0,this.initTabCloseOverride()),this.initTabClasses(e)}initTabCloseOverride(){const{glContainer:e}=this.props;e.beforeClose(t=>{if(t?.force===!0)return!0;const{changeCount:n,savedChangeCount:s}=this.state;return n!==s?(this.setState({showCloseModal:!0}),!1):!0})}initTabClasses(e){const t=e.element.get(0);N(t);const n=t.querySelector(".lm_title");this.tabTitleElement=n,n?.classList.add("notebook-title"),this.setPreviewStatus()}getNotebookValue(){const{changeCount:e,savedChangeCount:t,settings:n}=this.state,{value:s}=n;if(e!==t&&this.notebook){const i=this.notebook.getValue();return i??s}return s}initNotebookContent(){const{fileMetadata:e,settings:t,isPreview:n}=this.state;if(e&&e.id){Pe.debug("Init content from file"),this.registerFileMetadata(e,n),this.load();return}if(t.value!=null){Pe.debug("Use content passed in the settings prop"),this.handleLoadSuccess();return}this.handleLoadError(new Error("Missing file metadata"))}closeFileTabById(e){const{glEventHub:t}=this.props;t.emit(Ue.CLOSE_FILE,{id:e})}registerFileMetadata(e,t){const{glEventHub:n,metadata:s}=this.props,{id:i}=s;n.emit(Ue.REGISTER_FILE,i,e,t)}renameTab(e,t){const{glEventHub:n}=this.props;n.emit(Ue.RENAME,e,t)}load(){const{fileMetadata:e,settings:t}=this.state;N(e);const{id:n}=e,{fileStorage:s}=this.props;this.pending.add(s.loadFile(n)).then(i=>{Pe.debug("Loaded file",i);const{filename:o}=i,{itemName:l}=this.state;if(o!==l){const{metadata:d}=this.props,{id:h}=d;this.renameTab(h,fe.getBaseName(o))}const a={...t,language:$s.languageFromFileName(o)??""};t.value==null&&(a.value=i.content),t.wordWrap===void 0&&(t.wordWrap="off"),this.setState({fileMetadata:{id:o,itemName:o},settings:a}),this.debouncedSavePanelState()}).then(this.handleLoadSuccess).catch(this.handleLoadError)}save(){const{fileMetadata:e}=this.state;if(e&&fe.hasPath(e.itemName)){const t=this.getNotebookValue();return t!==void 0?(this.saveContent(e.itemName,t),!0):!1}return this.setState({showSaveAsModal:!0}),!1}saveContent(e,t){Pe.debug("saveContent",e,t),this.updateSavedChangeCount();const{fileStorage:n}=this.props;this.pending.add(n.saveFile({filename:e,content:t,basename:e})).then(this.handleSaveSuccess).catch(this.handleSaveError)}updateSavedChangeCount(){this.setState(({changeCount:e})=>({savedChangeCount:e}))}setPreviewStatus(){if(!this.tabTitleElement)return;const{isPreview:e}=this.state;Pe.debug("setPreviewStatus",this.tabTitleElement,e),e?this.tabTitleElement.classList.add("is-preview"):this.tabTitleElement.classList.remove("is-preview")}handlePreviewPromotion(){this.removePreviewStatus()}getSettings=ge((e,t)=>({...e,minimap:{enabled:t}}));getOverflowActions=ge((e,t)=>[{title:"Find",icon:Yg,action:this.handleFind,group:ie.groups.high,shortcut:Nt.NOTEBOOK.FIND,order:10},{title:"Show Minimap",icon:e?zn:void 0,action:this.handleMinimapChange,group:ie.groups.medium,shortcut:Nt.NOTEBOOK.MINIMAP,order:20},{title:"Word Wrap",icon:t?zn:void 0,action:this.handleWordWrapChange,group:ie.groups.medium,shortcut:Nt.NOTEBOOK.WORDWRAP,order:30}]);savePanelState(){this.setState(e=>{const{changeCount:t,savedChangeCount:n,fileMetadata:s,isPreview:i,settings:o}=e,l=this.getNotebookValue(),a=t!==n?l:void 0,d={...o,value:l},u={settings:{...o,value:a},fileMetadata:s,isPreview:i};return Pe.debug("Saving panel state",u),{settings:d,panelState:u}})}handleCloseDiscard(){this.setState({showCloseModal:!1});const{glContainer:e}=this.props;e.close({force:!0})}handleCloseSave(){if(this.setState({showCloseModal:!1}),this.save()){const{glContainer:e}=this.props;e.close({force:!0})}}handleCloseCancel(){this.setState({showCloseModal:!1})}handleOverwrite(e){const{glEventHub:t}=this.props;t.emit(Ue.CLOSE_FILE,{id:e,itemName:e},{force:!0}),this.focus()}handleCopy(){const{fileMetadata:e,settings:t}=this.state;N(e);const n=this.getNotebookValue(),{language:s}=t,{itemName:i}=e,o=fe.getCopyFileName(i);Pe.debug("handleCopy",e,i,o),this.createNotebook(o,s,n)}handleEditorInitialized(e){this.editor=e}handleEditorWillDestroy(){this.editor=void 0}handleEditorChange(e){Pe.debug2("handleEditorChanged",e),this.removePreviewStatus(),this.setState(t=>{const{changeCount:n,savedChangeCount:s}=t,{isUndoing:i,isRedoing:o}=e;return i?{changeCount:n-1,savedChangeCount:s}:!o&&n<s?{changeCount:n+1,savedChangeCount:0}:{changeCount:n+1,savedChangeCount:s}}),this.debouncedSavePanelState()}handleFind(){this.notebook&&this.notebook.toggleFind()}updateEditorMinimap(){if(this.editor){const{defaultNotebookSettings:e}=this.props;this.editor.updateOptions({minimap:{enabled:e.isMinimapEnabled}})}}handleMinimapChange(){const{settings:e,defaultNotebookSettings:t,saveSettings:n}=this.props,s={...e,defaultNotebookSettings:{isMinimapEnabled:!t.isMinimapEnabled}};n(s)}updateEditorWordWrap(){if(this.editor){const{settings:e}=this.state,{wordWrap:t}=e;this.editor.updateOptions({wordWrap:t})}}handleWordWrapChange(){this.editor&&this.setState(e=>{const{settings:t}=e,n=t.wordWrap==="on"?"off":"on";return{settings:{...t,wordWrap:n}}})}handleBlur(){Pe.debug("handleBlur"),this.setState({isFocused:!1})}handleFocus(){Pe.debug("handleFocus"),this.setState({isFocused:!0})}handleLinkClick(e){const{notebooksUrl:t,session:n,sessionLanguage:s}=this.props,{href:i}=e.currentTarget;if(!i||!i.startsWith(t))return;e.stopPropagation(),e.preventDefault();const o=`/${i.substring(t.length)}`.replace(/%20/g," ");if(o==="/"){Pe.debug("Ignoring invalid notebook link",o);return}Pe.debug("Notebook link clicked, opening",o);const{glEventHub:l}=this.props,a={value:null,language:s},d={id:o,itemName:o};l.emit(Ue.SELECT_NOTEBOOK,n,s,a,d)}handleLoadSuccess(){this.setState({error:void 0,isLoaded:!0,isLoading:!1})}handleLoadError(e){let t=e;ye.isCanceled(t)||(ye.isTimedOut(t)&&(t=new Error("File not found.")),Pe.error(t),this.setState({error:t,isLoading:!1}))}handleSave(){Pe.debug("handleSave"),this.save()}handleSaveSuccess(e){const{fileStorage:t}=this.props,n={id:e.filename,itemName:e.filename},s=$s.languageFromFileName(e.filename)??"";this.setState(i=>{const{fileMetadata:o}=i,l={...i.settings,language:s};return Pe.debug("handleSaveSuccess",n,o,l),o&&fe.hasPath(o.itemName)&&o.itemName!==n.itemName&&(Pe.debug("handleSaveSuccess deleting old file",o.itemName),t.deleteFile(o.itemName).catch($s.handleError)),{fileMetadata:n,settings:l,isPreview:!1}}),this.debouncedSavePanelState(),this.registerFileMetadata(n,!1)}handleSaveError(e){ye.isCanceled(e)||(this.setState({savedChangeCount:0}),Pe.error(e))}handleSaveAsCancel(){this.setState({showSaveAsModal:!1})}handleSaveAsSubmit(e,t=!1){t&&this.handleOverwrite(e),Pe.debug("handleSaveAsSubmit",e);const{fileMetadata:n}=this.state;if(!n)return;const{itemName:s}=n,i=this.getNotebookValue()??"";if(this.setState({showSaveAsModal:!1}),fe.getBaseName(s)!==fe.getBaseName(e)){const{metadata:o}=this.props,{id:l}=o;this.renameTab(l,fe.getBaseName(e))}this.saveContent(e,i)}handleRenameFile(e,t,n){const{fileMetadata:s,panelState:i}=this.state,{glContainer:o}=this.props;if(s?.itemName===`/${t}`&&n&&JSON.stringify(i)!==JSON.stringify(n)){o.close();return}s&&s.id===e&&(this.setState({fileMetadata:{id:t,itemName:t}}),this.debouncedSavePanelState())}handleResize(){this.notebook?.updateDimensions()}handleRunCommand(e){this.runCommand(e)}handleRunAll(){if(!this.notebook){Pe.error("Editor is not initialized.");return}this.runCommand(this.notebook.getValue()??void 0)}handleRunSelected(){if(!this.notebook){Pe.error("Editor is not initialized.");return}this.runCommand(this.notebook.getSelectedCommand())}handleSessionOpened(e,{language:t}){this.setState({session:e,sessionLanguage:t})}handleSessionClosed(){this.setState({session:void 0,sessionLanguage:void 0})}handleShow(){Pe.debug("handleShow"),this.notebook?.updateDimensions()}handleShowRename(){this.setState({showSaveAsModal:!0})}handleTab(e){Pe.debug("NotebookPanel tab event",e),this.initTab(e)}handleTabFocus(...e){Pe.debug("handleTabFocus",...e);const{glContainer:t}=this.props;this.setState({isDashboardActive:!0}),this.notebook&&!t.isHidden&&this.notebook.updateDimensions()}handleTabBlur(){Pe.debug("handleTabBlur"),this.setState({isDashboardActive:!1})}handleTabClick(e){Pe.debug("handle NotebookPanel tab click"),this.focus(),e.detail===2&&this.removePreviewStatus()}handleTransformLinkUri(e){const{notebooksUrl:t}=this.props,{fileMetadata:n}=this.state;if(e.endsWith("/"))return e;if(e.startsWith("/"))return`${t}${e.substring(1)}`;let s=n?.itemName;if(s===void 0)return e;s.charAt(0)==="/"&&(s=s.substring(1));const i=new URL(s,t);return new URL(e,i).href}focus(){requestAnimationFrame(()=>{this.notebook&&this.notebook.focus()})}createNotebook(e,t,n=""){const{glEventHub:s}=this.props,{session:i,sessionLanguage:o,settings:l}=this.state,a={...l,language:t,value:n},d={id:null,itemName:e};Pe.debug("handleCreateNotebook",i,o,a,d),s.emit(Ue.CREATE_NOTEBOOK,i,o,a,d)}runCommand(e){if(e===void 0||e===""){Pe.debug("Ignoring empty command.");return}this.removePreviewStatus();const{glEventHub:t}=this.props;t.emit($t.SEND_COMMAND,e,!1,!0)}removePreviewStatus(){this.setState(({isPreview:e})=>{if(e){const{fileMetadata:t}=this.state;return t&&this.registerFileMetadata(t,!1),{isPreview:!1}}return null})}getDropdownOverflowActions(){const{defaultNotebookSettings:e}=this.props,{settings:t}=this.state;return this.getOverflowActions(e.isMinimapEnabled,this.getSettings(t,e.isMinimapEnabled).wordWrap==="on")}render(){const{fileStorage:e,glContainer:t,glContainer:{tab:n},glEventHub:s,defaultNotebookSettings:i}=this.props,{changeCount:o,savedChangeCount:l,error:a,isDashboardActive:d,isLoaded:h,isLoading:u,isPreview:m,fileMetadata:g,session:p,sessionLanguage:C,settings:f,showCloseModal:b,showSaveAsModal:w}=this.state,S=d&&!t.isHidden&&!m,T=g?.itemName??$s.DEFAULT_NAME,y=T.endsWith(".md"),E=g?.id!=null,R=this.getSettings(f,i.isMinimapEnabled),x=p!=null,D=C===R.language,M=!h||!x||!D,O=!h,H=[{action:this.handleSave,shortcut:Kn.SAVE},{action:this.handleMinimapChange,shortcut:Nt.NOTEBOOK.MINIMAP},{action:this.handleWordWrapChange,shortcut:Nt.NOTEBOOK.WORDWRAP}],L=Ld.getDisabledRunTooltip(x,D,"Notebook extension","Run"),V=Ld.getDisabledRunTooltip(x,D,"Notebook extension","Run Selected"),U=[{title:E?"Rename":"Save As…",order:10,group:ie.groups.high,action:this.handleShowRename},{title:"Copy File",action:this.handleCopy,group:ie.groups.high,order:20}],j=n?.element.find(".lm_title_before").get(0);return r.jsxs(r.Fragment,{children:[j&&al.createPortal(r.jsx("span",{className:Y("editor-unsaved-indicator",{"is-unsaved":o!==l})}),j),r.jsxs(qn,{className:"notebook-container",componentPanel:this,glContainer:t,glEventHub:s,onTab:this.handleTab,onResize:this.handleResize,onShow:this.handleShow,onTabClicked:this.handleTabClick,onTabFocus:this.handleTabFocus,onTabBlur:this.handleTabBlur,onSessionOpen:this.handleSessionOpened,onSessionClose:this.handleSessionClosed,onFocus:this.handleFocus,onBlur:this.handleBlur,additionalActions:U,renderTabTooltip:()=>T,children:[!y&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"notebook-toolbar",children:[r.jsxs("span",{children:[r.jsx(B,{kind:"ghost",className:"btn-play",onClick:this.handleRunAll,disabled:M,icon:r.jsx(ee,{icon:rl,transform:"grow-4"}),tooltip:`Run ${Nt.NOTEBOOK.RUN.getDisplayText()}`,"aria-label":"Run"}),L!=null&&r.jsx(ot,{children:L})]}),r.jsxs("span",{children:[r.jsx(B,{kind:"ghost",className:"btn-play",onClick:this.handleRunSelected,disabled:M,icon:r.jsx(ee,{icon:qg,transform:"grow-4"}),tooltip:`Run Selected ${Nt.NOTEBOOK.RUN_SELECTED.getDisplayText()}`,"aria-label":"Run Selected"}),V!=null&&r.jsx(ot,{children:V})]}),r.jsx(B,{kind:"ghost",className:"mr-auto",disabled:O,onClick:this.handleSave,icon:oh,tooltip:`Save ${Kn.SAVE.getDisplayText()}`,"aria-label":"Save"}),r.jsx(B,{kind:"ghost",className:"btn-overflow btn-link-icon",disabled:O,icon:Qc,tooltip:"More Actions...",onClick:()=>{},children:r.jsx(Vn,{actions:this.getDropdownOverflowActions,popperOptions:$s.POPPER_OPTIONS})})]}),r.jsx(jf,{isLoaded:h,isLoading:u,error:a,onChange:this.handleEditorChange,onRunCommand:this.handleRunCommand,session:p,sessionLanguage:C,onEditorInitialized:this.handleEditorInitialized,onEditorWillDestroy:this.handleEditorWillDestroy,settings:R,focusOnMount:S,ref:P=>{this.notebook=P}})]}),y&&r.jsx(jR,{content:R.value??"",onLinkClick:this.handleLinkClick,onRunCode:this.handleRunCommand,transformImageUri:this.handleTransformLinkUri,transformLinkUri:this.handleTransformLinkUri}),r.jsx($u,{isOpen:w,type:"file",defaultValue:T,title:E?"Rename":"Save file as",onSubmit:this.handleSaveAsSubmit,onCancel:this.handleSaveAsCancel,notifyOnExtensionChange:!0,storage:e}),r.jsx(oo,{isOpen:b,headerText:`Do you want to save the changes you made to ${T}?`,bodyText:"Your changes will be lost if you don't save them.",onCancel:this.handleCloseCancel,onDiscard:this.handleCloseDiscard,onConfirm:this.handleCloseSave,discardButtonText:"Discard Changes",confirmButtonText:"Save"}),r.jsx(ie,{actions:H})]})]})}}const HR=(c,e)=>{const t=vh(c),n=wt(c),s=CC(c),i=Qs(c,e.localDashboardId),{session:o,config:l}=i??{},{type:a}=l??{};return{fileStorage:t,settings:n,defaultNotebookSettings:s,session:o,sessionLanguage:a}},BR=St(HR,{saveSettings:Zl},null,{forwardRef:!0})($s),ds=BR;class UR extends v.Component{static defaultProps={panelState:null};static COMPONENT="PandasPanel";constructor(e){super(e),this.irisGridRef=de.createRef(),this.buttonRef=de.createRef(),this.handleReload=this.handleReload.bind(this),this.handleGridStateChange=this.handleGridStateChange.bind(this),this.handlePanelStateUpdate=this.handlePanelStateUpdate.bind(this);const{panelState:t}=e;this.state={shouldFocusGrid:!1,panelState:t}}buttonRef;irisGridRef;handleReload(){this.irisGridRef.current?.initModel(),this.buttonRef.current?.blur(),this.setState({shouldFocusGrid:!0})}handleGridStateChange(){const{shouldFocusGrid:e}=this.state;e&&this.irisGridRef.current?.irisGrid?.current?.grid&&(this.irisGridRef.current.irisGrid.current.grid.focus(),this.setState({shouldFocusGrid:!1}))}handlePanelStateUpdate(e){this.setState({panelState:e})}render(){const{...e}=this.props;return r.jsx(qs,{ref:this.irisGridRef,onStateChange:this.handleGridStateChange,onPanelStateUpdate:this.handlePanelStateUpdate,...e,children:r.jsxs(B,{ref:this.buttonRef,kind:"primary",className:"btn-pandas",onClick:this.handleReload,tooltip:"Click to refresh pandas dataframe, updates do not occur automatically.",children:["pandas dataframe",r.jsxs("span",{children:[r.jsx(ee,{icon:hr,transform:"shrink-1",className:"mr-1"}),"Reload"]})]})})}}const Ma=UR;function VR(c){ys(c);const{id:e,layout:t,registerComponent:n,hydrate:s}=c,i=v.useCallback(({dragEvent:o,fetch:l,panelId:a=qe.generate(),widget:d})=>{const{name:h,type:u}=d;if(u!==dh.VariableType.FIGURE)return;const m={name:h,figure:h},g=()=>l().then(f=>fl.makeModel(void 0,f)),p={type:"react-component",component:Ei.COMPONENT,props:{localDashboardId:e,id:a,metadata:m,makeModel:g},title:h,id:a},{root:C}=t;K.openComponent({root:C,config:p,dragEvent:o})},[e,t]);return v.useEffect(function(){const l=[n(Ei.COMPONENT,Ei,s)];return()=>{l.forEach(a=>a())}},[s,n]),Ve(t.eventHub,Ee.OPEN,i),null}function $R(c){ys(c);const{id:e,layout:t}=c,n=v.useCallback(({metadata:s,panelId:i=qe.generate(),table:o})=>{const{settings:l}=s,a=()=>fl.makeModelFromSettings(l,o),d=Qe.titleFromSettings(l),h={type:"react-component",component:Ei.COMPONENT,props:{localDashboardId:e,id:i,metadata:s,makeModel:a},title:d,id:i},{root:u}=t;K.openComponent({root:u,config:h})},[e,t]);return Ve(t.eventHub,cn.CREATE_CHART,n),null}const at=ne.module("ConsolePlugin");function Tc(c){return c.notebook!==void 0}function WR(c){ys(c)}function GR(c){WR(c);const{id:e,hydrateConsole:t,layout:n,panelManager:s,registerComponent:i,notebooksUrl:o}=c,l=v.useRef(0),[a,d]=v.useState(new Map),[h,u]=v.useState(new Map),m=ir(),g=v.useCallback(()=>s.getLastUsedPanelOfType(Ci),[s]),p=v.useCallback((A,W)=>{d(q=>new Map(q.set(A,W)))},[d]),C=v.useCallback(A=>{d(W=>(W.delete(A),new Map(W)))},[d]),f=v.useCallback((A,W)=>{u(q=>new Map(q.set(A,W)))},[u]),b=v.useCallback(A=>{u(W=>(W.delete(A),new Map(W)))},[u]),w=v.useCallback((A,W=!0,q=!0)=>{if(!(A&&A.trim()))at.info("Ignoring empty code");else{const le=g();if(!le||!(le instanceof Ci.WrappedComponent)){at.error("Console panel not found");return}at.debug("Send command: ",A,W,q),le.addCommand(A,W,q)}},[g]),S=v.useCallback(A=>{m(ky(e,A))},[m,e]),T=v.useCallback(({language:A})=>{const W=A==="python"?"py":A;let q=null;return W==null?(at.debug("No extension for language",A),q=`Untitled-${l.current}`):q=`Untitled-${l.current}.${W}`,l.current+=1,q},[]),y=v.useCallback((A,W=!0)=>{const{id:q}=A;if(q!=null&&a.has(q))return a.get(q);if(q!=null&&h.has(q))return h.get(q);if(W)return qe.generate()},[a,h]),E=v.useCallback((A,W)=>{K.renameComponent(n.root,{id:A},W)},[n.root]),R=v.useCallback((A,W)=>{at.debug("Rename file panel",A,W);let q;if(a.has(A)&&(q=a.get(A),C(A),q!=null&&p(W,q)),h.has(A)&&(q=h.get(A),b(A),q!=null&&f(W,q)),q===void 0){at.debug2(`File ${A} isn't open, no need to rename the tab`);return}E(q,fe.getBaseName(W))},[a,h,E,p,f,C,b]),x=v.useCallback(A=>{const W=y(A,!1);if(W==null){at.error("Could not find panel id for file metadata",A);return}K.activateTab(n.root,{id:W})},[y,n.root]),D=v.useCallback((A,W,q)=>{if(at.debug("registerFilePanel",A,W,q),W==null||W.id==null){at.debug("Ignore empty file id",W);return}const{id:Z}=W;if(q){f(Z,A);return}if(a.has(Z)){const le=a.get(Z);if(A===le){at.debug(`Update tab title for file ${Z}`);const{itemName:G}=W;R(Z,G)}else at.error(`File ${Z} already associated with a different tab ${le}`);return}p(Z,A),h.has(Z)&&b(Z)},[a,h,R,p,f,b]),M=v.useCallback((A,W)=>{if(at.debug("unregisterFileTab",A,W),A==null||A.id==null){at.debug("Ignore empty file id",A);return}const{id:q}=A;if(W){b(q);return}C(q)},[C,b]),O=v.useCallback((A,W)=>{at.debug("closeFilePanel",A);const{id:q}=A;let Z=null,le=!1;if(a.has(q))Z=a.get(q);else if(h.has(q))Z=h.get(q),le=!0;else{at.debug(`File ${q} isn't open, ignore close event`);return}M(A,le),K.closeComponent(n.root,{id:Z},W)},[n.root,a,h,M]),H=v.useCallback(A=>{const{itemName:W}=A;return fe.getBaseName(W)},[]),L=v.useCallback(A=>{const{id:W}=A;return at.debug("fileIsOpen",A,W,a),W!=null&&a.has(W)},[a]),V=v.useCallback(A=>{const{id:W}=A;return at.debug("fileIsOpenAsPreview",A,W,h),W!=null&&h.has(W)},[h]),U=v.useCallback(A=>{if(A==null)return;const W=s.getOpenedPanelById(A);W&&Tc(W)&&W.focus()},[s]),j=v.useCallback(({id:A,settings:W,fileMetadata:q,session:Z,sessionLanguage:le,isPreview:G=!1})=>{const oe={settings:W,fileMetadata:q},ue=H(q);return{type:"react-component",component:ds.COMPONENT,isFocusOnShow:!1,props:{localDashboardId:e,metadata:{id:A},session:Z,sessionLanguage:le,panelState:oe,isPreview:G,notebooksUrl:o},title:ue,id:A}},[H,e,o]),P=v.useCallback((A,W,q,Z={id:null,itemName:T(q)})=>{const le=y(Z);if(L(Z)&&le!=null){at.debug("File is already open, focus panel"),x(Z),U(le);return}const G=K.getStackForComponentTypes(n.root,[ds.COMPONENT]),oe=j({id:le,settings:q,fileMetadata:Z,session:A,sessionLanguage:W});at.debug("createNotebook",oe,a),K.openComponentInStack(G,oe)},[L,U,T,y,n.root,j,a,x]),Q=v.useCallback((A,W,q,Z,le=!1)=>{at.debug("selectNotebook",Z,le);const G=L(Z),oe=V(Z),[ue]=[...h.values()],ae=!le,ce=ae&&ue?ue:y(Z);if(ce==null||ce==="")throw new Error("Unable to retrieve or create panelId for metadata",Z);if(G||oe)x(Z);else{const we=K.getStackForComponentTypes(n.root,[ds.COMPONENT]),He=j({id:ce,settings:q,fileMetadata:Z,session:A,sessionLanguage:W,isPreview:ae});K.openComponentInStack(we,He)}if(oe&&le){const we=Z.id,He=K.getStackForConfig(n.root,{component:ds.COMPONENT,id:ce}),Fe=K.getContentItemInStack(He,{component:ds.COMPONENT,id:ce});Fe&&Ot(Fe)&&(Fe.container.emit(Ue.PROMOTE_FROM_PREVIEW),b(we),p(we,ce))}le&&U(ce)},[x,L,V,U,y,n.root,j,h,b,p]),$=v.useCallback((A,W,q={},Z=!0)=>{const le=s.getLastUsedPanelOfType(ds);le&&Tc(le)?q!=null&&q.value!=null&&le.notebook!=null&&le.notebook.append(q.value):Z&&P(A,W,q)},[P,s]),J=v.useCallback((A,W)=>qa.hydrate({...A,notebooksUrl:o},W),[o]);return v.useEffect(function(){const W=[i(Ci.COMPONENT,Ci,t),i(Il.COMPONENT,Il),i(Nl.COMPONENT,Nl),i(Ol.COMPONENT,Ol),i(ds.COMPONENT,ds,J)];return()=>{W.forEach(q=>q())}},[i,t,J]),Ve(n.eventHub,$t.SEND_COMMAND,w),Ve(n.eventHub,$t.SETTINGS_CHANGED,S),Ve(n.eventHub,Ue.CLOSE_FILE,O),Ve(n.eventHub,Ue.CREATE_NOTEBOOK,P),Ve(n.eventHub,Ue.SELECT_NOTEBOOK,Q),Ve(n.eventHub,Ue.RENAME,E),Ve(n.eventHub,Ue.RENAME_FILE,R),Ve(n.eventHub,Ue.SEND_TO_NOTEBOOK,$),Ve(n.eventHub,Ue.REGISTER_FILE,D),Ve(n.eventHub,Ue.UNREGISTER_FILE,M),null}const Gi=ne.module("FilterPlugin");function Ec(c,e){return c.concat(e)}function zR(c){ys(c);const{id:e,layout:t,registerComponent:n}=c,s=ir(),[i]=v.useState(()=>new Map),[o]=v.useState(()=>new Map),[l]=v.useState(()=>new Map),a=v.useCallback(()=>{const f=Array.from(i.values()).reduce(Ec,[]).sort((S,T)=>{const y=en.toLower(S.name),E=en.toLower(T.name);if(y!==E)return y>E?1:-1;const R=en.toLower(S.type),x=en.toLower(T.type);return R!==x?R>x?1:-1:0}).reduce((S,T)=>((S.length===0||en.toLower(S[S.length-1].name)!==en.toLower(T.name)||en.toLower(S[S.length-1].type)!==en.toLower(T.type))&&S.push(T),S),[]),b=Array.from(o.values()).reduce(Ec,[]).sort((S,T)=>S.timestamp-T.timestamp),w=new Map(l);Gi.debug("sendUpdate",{columns:f,filters:b,tableMap:w}),s(Fn(e,{columns:f,filters:b,tableMap:w}))},[s,e,i,o,l]),d=v.useCallback((f,b)=>{Gi.debug2("handleColumnsChanged",f,b),i.set(f,[].concat(b)),a()},[i,a]),h=v.useCallback((f,b)=>{Gi.debug2("handleFiltersChanged",f,b),o.set(f,[].concat(b)),a()},[o,a]),u=v.useCallback((f,b)=>{Gi.debug2("handleTableChanged",f,b),l.set(K.getIdFromPanel(f),b),a()},[l,a]),m=v.useCallback(f=>{Gi.debug2("handlePanelUnmount",f),i.delete(f),o.delete(f),l.delete(K.getIdFromPanel(f)),a()},[i,o,l,a]),g=v.useCallback(({title:f="DropdownFilter",metadata:b={},panelState:w=null,id:S=qe.generate(),focusElement:T=K.DEFAULT_FOCUS_SELECTOR,createNewStack:y=!1,dragEvent:E=null})=>{const R={type:"react-component",component:Ys.COMPONENT,props:{id:S,metadata:b,panelState:w,localDashboardId:e},title:f,id:S},{root:x}=t;K.openComponent({root:x,config:R,focusElement:T,createNewStack:y,dragEvent:E})},[t,e]),p=v.useCallback(({title:f="InputFilter",metadata:b={},panelState:w=null,id:S=qe.generate(),focusElement:T=K.DEFAULT_FOCUS_SELECTOR,createNewStack:y=!1,dragEvent:E=null})=>{const R={type:"react-component",component:no.COMPONENT,props:{id:S,metadata:b,panelState:w,localDashboardId:e},title:f,id:S},{root:x}=t;K.openComponent({root:x,config:R,focusElement:T,createNewStack:y,dragEvent:E})},[t,e]),C=v.useCallback(({title:f="FilterSets",metadata:b={},panelState:w=null,id:S=qe.generate(),focusElement:T=K.DEFAULT_FOCUS_SELECTOR,createNewStack:y=!1,dragEvent:E=null})=>{const R={type:"react-component",component:ka.COMPONENT,props:{id:S,metadata:b,panelState:w,localDashboardId:e},title:f,id:S},{root:x}=t;K.openComponent({root:x,config:R,focusElement:T,createNewStack:y,dragEvent:E})},[t,e]);return v.useEffect(function(){const b=[n(Ys.COMPONENT,Ys),n(no.COMPONENT,no),n(ka.COMPONENT,ka)];return()=>{b.forEach(w=>w())}},[n]),Ve(t.eventHub,Ze.COLUMNS_CHANGED,d),Ve(t.eventHub,Ze.FILTERS_CHANGED,h),Ve(t.eventHub,Ze.TABLE_CHANGED,u),Ve(t.eventHub,Ze.OPEN_DROPDOWN,g),Ve(t.eventHub,Ze.OPEN_INPUT,p),Ve(t.eventHub,Ze.OPEN_FILTER_SET_MANAGER,C),Ve(t.eventHub,Ee.UNMOUNT,m),null}const KR=[dh.VariableType.TABLE,dh.VariableType.TREETABLE,dh.VariableType.HIERARCHICALTABLE];function YR(c){ys(c);const{getDownloadWorker:e,loadPlugin:t,id:n,layout:s,registerComponent:i,hydrate:o,theme:l}=c,a=v.useCallback(({dragEvent:d,fetch:h,panelId:u=qe.generate(),widget:m})=>{const{name:g,type:p}=m;if(!KR.includes(p))return;const C={name:g,table:g,type:m.type},f=()=>h().then(S=>Wr.makeModel(S)),b={type:"react-component",component:qs.COMPONENT,props:{getDownloadWorker:e,loadPlugin:t,localDashboardId:n,id:u,metadata:C,makeModel:f,theme:l},title:g,id:u},{root:w}=s;K.openComponent({root:w,config:b,dragEvent:d})},[e,n,s,t,l]);return v.useEffect(function(){const h=[i(qs.COMPONENT,qs,o)];return()=>{h.forEach(u=>u())}},[o,i]),Ve(s.eventHub,Ee.OPEN,a),null}function Wu(c){return typeof c.getCoordinateForColumn=="function"}function yc(c){const e=c;return Wu(c)&&typeof e.setFilterMap=="function"&&typeof e.unsetFilterValue=="function"}function Rc(c){return c.description===void 0||!c.description?.startsWith("Preview of type: ")}const zi=ne.module("LinkerUtils");class nd{static ALLOWED_LINKS=new Map([[K.getComponentName(qs),[K.getComponentName(qs),K.getComponentName(Ei),K.getComponentName(Ys)]]]);static getLinkType(e,t,n){if(e?.panelId==null||t?.panelId==null||e.panelId===t.panelId||n!=null&&n!==e.panelId&&n!==t.panelId)return zi.debug2("Incompatible panel ids",e,t,n),"invalid";if(e.panelComponent==null||t.panelComponent==null)return zi.error("PanelComponent should not be null",e,t),"invalid";const s=nd.ALLOWED_LINKS.get(e.panelComponent)?.includes(t.panelComponent);if(s===void 0||!s)return zi.debug2("Incompatible panel components",e,t),"invalid";const{columnType:i}=e,{columnType:o}=t;if(!(o===null||F.isCompatibleType(i,o)))return zi.debug2("Incompatible type",i,o),"invalid";switch(t.panelComponent){case K.getComponentName(Ei):return"chartLink";case K.getComponentName(qs):return"tableLink";case K.getComponentName(Ys):return"filterSource"}return zi.debug2("Incompatible target panel component",t.panelComponent),"invalid"}static findColumn(e,{columnName:t,columnType:n}){return e.find(({name:s,type:i})=>s===t&&i===n)}static cloneLinksForPanel(e,t,n){const s=[];return e.forEach(i=>{i.start.panelId===t&&i.type!=="filterSource"?s.push({...i,id:qe.generate(),start:{...i.start,panelId:n}}):i.end?.panelId===t&&s.push({...i,id:qe.generate(),end:{...i.end,panelId:n}})}),s}}const hi=nd;const qR=ne.module("LinkerLink"),xc=.015,Dc=1.5,Gu=12,zu=12,Ic=2,Jo=Math.sqrt((zu*.5)**2+Gu**2),Fc=Math.asin(zu*.5/Gu),Nc=15,cs=Math.PI*.5;class so extends v.Component{static defaultProps={className:"",isSelected:!1,onClick(){},onDelete(){}};static makeCirclePath(e,t,n){return`M ${e} ${t} m -${n},0 a ${n},${n} 0 1,0 ${n*2},0 a ${n},${n} 0 1,0 -${n*2},0 z`}static getLabelForLinkFilter(e,t){try{if(F.isNumberType(e)||F.isCharType(e))return fh(t);if(F.isTextType(e))return ph(t);if(F.isDateType(e))return Ch(t);if(F.isBooleanType(e)){if(t===be.eq)return"is equal to";if(t===be.notEq)return"is not equal to"}throw new Error(`Unrecognized column type: ${e}`)}catch(n){return qR.warn(n),""}}constructor(e){super(e),this.handleClick=this.handleClick.bind(this),this.handleMouseEnter=this.handleMouseEnter.bind(this),this.handleMouseLeave=this.handleMouseLeave.bind(this),this.handleDelete=this.handleDelete.bind(this),this.getDropdownActions=this.getDropdownActions.bind(this),this.state={isHovering:void 0}}getOperators=ge((e,t)=>{const{onOperatorChanged:n}=this.props;let s=F.getFilterTypes(t);return F.isBooleanType(t)&&(s=[be.eq,be.notEq]),s.flatMap((i,o)=>{if(i==="eqIgnoreCase"||i==="notEqIgnoreCase")return[];let l="";return i==="startsWith"?l="a*":i==="endsWith"?l="*z":l=F.getFilterOperatorString(i),[{title:so.getLabelForLinkFilter(t,i),icon:r.jsx("b",{children:l}),action:()=>n(e,i),order:o}]})});handleClick(e){e.stopPropagation(),e.preventDefault();const{id:t,onClick:n,onDelete:s}=this.props;e.altKey?s(t):n(t)}handleMouseEnter(){this.setState({isHovering:!0})}handleMouseLeave(){this.setState({isHovering:!1})}handleDelete(){const{id:e,onDelete:t}=this.props;t(e)}getDropdownActions(){const{id:e,startColumnType:t}=this.props;return t!=null?this.getOperators(e,t):[]}render(){const{className:e,operator:t,isSelected:n,x1:s,y1:i,x2:o,y2:l,id:a,startColumnType:d,type:h}=this.props,{isHovering:u}=this.state,m=Math.sqrt((s-o)**2+(i-l)**2),g=Math.atan2(l-i,o-s),p=Math.sin(g),C=Math.cos(g)+2,f=window.innerWidth,b=window.innerHeight,w=0,S=0,T=Math.max(w,Math.min(s+(o-s)/2+p*(m*xc)**Dc,f)),y=Math.max(S,Math.min(i+(l-i)/2+C*(m*xc)**Dc,b)),E=`M ${s} ${i} Q ${T} ${y} ${o} ${l}`,R=`M ${w} ${S} L ${w} ${b} L ${f} ${b} L ${f} ${S} z
33
+ ${l} does not exist yet.`}if(s){const{widgetName:o}=this.props;return`${o} is unavailable.`}}getCachedRenderTabTooltip=ge((e,t,n,s,i)=>e?()=>r.jsx(ia,{glContainer:t,widgetType:n,widgetName:s,description:i}):null);handleSessionClosed(...e){const{onSessionClose:t}=this.props;this.setState({isPanelDisconnected:!0,isWaitingForReconnect:!1}),t(...e)}handleSessionOpened(...e){const{onSessionOpen:t}=this.props;t(...e)}render(){const{children:e,className:t,componentPanel:n,isLoaded:s,isLoading:i,glContainer:o,glEventHub:l,isDisconnected:a,isClonable:d,isRenamable:h,showTabTooltip:u,renderTabTooltip:m,widgetType:g,widgetName:p,description:C,onClearAllFilters:f,onHide:b,onFocus:w,onBlur:S,onResize:T,onShow:y,onTabBlur:E,onTabFocus:R,onTabClicked:x}=this.props,{isPanelDisconnected:D,isWidgetDisconnected:M,isPanelInactive:O}=this.state,H=this.getErrorMessage(),L=m??this.getCachedRenderTabTooltip(u,o,g,p,C),V=[{title:`Copy ${g} Name`,group:ie.groups.medium,order:20,action:this.handleCopyName}];return r.jsxs(qn,{className:Y(t,{disconnected:D||M||a,inactive:O}),componentPanel:n,glContainer:o,glEventHub:l,onClearAllFilters:f,onHide:b,onFocus:w,onBlur:S,onResize:T,onShow:y,onSessionClose:this.handleSessionClosed,onSessionOpen:this.handleSessionOpened,onTabBlur:E,onTabFocus:R,onTabClicked:x,renderTabTooltip:L,errorMessage:H,isLoaded:s,isLoading:i,isClonable:d,isRenamable:h,additionalActions:V,children:[e,O&&r.jsx("div",{className:"fill-parent-absolute"})]})}}const Gr=Ty,_t=Object.freeze({DEFAULT:"DEFAULT",LINKER:"LINKER"}),Ey=new Map,oa=Object.freeze([]),ju=(c,e)=>Pt(c,e).columns??oa,yy=(c,e)=>Pt(c,e).filterSets??oa,zr=(c,e)=>Pt(c,e).filters??oa,Kr=(c,e)=>Pt(c,e).tableMap??Ey,Yr=(c,e)=>Pt(c,e).isolatedLinkerPanelId,Ni=(c,e)=>Pt(c,e).links??oa,qr=(c,e)=>Pt(c,e).columnSelectionValidator,Ry=(c,e)=>Pt(c,e).connection,Qs=(c,e)=>Pt(c,e).sessionWrapper,xy=(c,e)=>t=>t(Fn(c,{connection:e})),Dy=(c,e)=>t=>t(Fn(c,{sessionWrapper:e})),Xr=(c,e)=>t=>t(Fn(c,{links:e})),Iy=(c,e)=>(t,n)=>{const s=Ni(n(),c),i=e.filter(o=>s.findIndex(l=>st(l.start,o.start)&&st(l.end,o.end))<0);return t(Xr(c,s.concat(i)))},Fy=(c,e)=>(t,n)=>{const i=Ni(n(),c).filter(o=>!e.includes(o.id));return t(Xr(c,i))},Hu=(c,e)=>t=>t(Fn(c,{isolatedLinkerPanelId:e})),Ny=(c,e)=>t=>t(Fn(c,{columnSelectionValidator:e})),ky=(c,e)=>t=>t(Fn(c,{consoleSettings:e})),My=(c,e)=>t=>t(Fn(c,{filterSets:e}));function Bu({columnMap:c,inputFilterMap:e,linkedColumnMap:t,onAdd:n,onOpenLinker:s,waitingFilterMap:i,waitingInputMap:o}){const l=v.useMemo(()=>{const g=Array.from(o.keys()),p=g.find(b=>e.get(b)!=null),C=g.find(b=>t.get(b)!=null),f=en.join(g.map(b=>`"${b}"`));return p!=null&&p&&C!=null&&C?`Use a filter control or linked table to set a value for ${f}`:p!=null&&p?`Set a filter control value for ${f}`:`Double click a row in a linked table to set a value for ${f}`},[e,t,o]),a=v.useMemo(()=>Array.from(c.values()),[c]),d=v.useCallback(g=>{g.stopPropagation(),g.preventDefault(),n(Array.from(i.values()))},[n,i]),h=v.useCallback(g=>{g.stopPropagation(),g.preventDefault(),s()},[s]),u=i.size>0,m=!u&&o.size>0;return r.jsx("div",{className:"chart-panel-overlay chart-filter-overlay",children:r.jsxs("div",{className:Y("chart-panel-overlay-content chart-filter-overlay-content",{"chart-filter-waiting-filter":u},{"chart-filter-waiting-input":m}),children:[u&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"info-message",children:"This plot requires a filter control to be added to the layout or a table link to be created on the following columns:"}),r.jsx("div",{className:"waiting-filter-list",children:a.map(g=>{const p=i.has(g.name),C=p?ws:dr;return r.jsxs("div",{className:Y("waiting-filter-item",{"is-invalid":p}),children:[r.jsx(ee,{icon:C}),g.name]},g.name)})}),r.jsxs("div",{children:[r.jsx(md,{onClick:d,className:"btn-primary",children:"Add Input Filters"}),r.jsx(md,{onClick:h,className:"btn-primary",children:"Open Linker Tool"})]})]}),m&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"info-message",children:"Waiting for User Input"}),r.jsx("div",{className:"",children:l})]})]})})}Bu.propTypes={columnMap:z.instanceOf(Map).isRequired,inputFilterMap:z.instanceOf(Map).isRequired,linkedColumnMap:z.instanceOf(Map).isRequired,onAdd:z.func.isRequired,onOpenLinker:z.func.isRequired,waitingFilterMap:z.instanceOf(Map).isRequired,waitingInputMap:z.instanceOf(Map).isRequired};function ro({columns:c,onColumnSelected:e,onMouseEnter:t,onMouseLeave:n}){return r.jsx("div",{className:"chart-panel-overlay chart-column-selector-overlay",children:r.jsxs("div",{className:Y("chart-panel-overlay-content"),children:[r.jsx("div",{className:"info-message",children:"This plot requires a filter control to be added to the layout or a table link to be created on the following columns:"}),r.jsx("div",{className:"waiting-column-select-list",children:c.map(s=>r.jsx(Kc,{className:Y("btn-chart-column-selector",ro.makeButtonClassName(s.name)),onClick:()=>e(s.name),onMouseEnter:()=>{t&&t(s)},onMouseLeave:n,disabled:!s.isValid,isLinked:s.isActive,children:s.name},s.name))})]})})}ro.makeButtonClassName=c=>`btn-chart-column-selector-${c}`;ro.defaultProps={onMouseEnter:()=>{},onMouseLeave:()=>{}};function il(c){return c.settings!==void 0}const Lt=ne.module("ChartPanel"),Ly=150;function Oy(c){return c.inputFilters!=null}function Ay(c){return c.panelState!=null}class _y extends v.Component{static defaultProps={columnSelectionValidator:null,isLinkerActive:!1,source:null,sourcePanel:null,panelState:null,settings:{}};static displayName="ChartPanel";static COMPONENT="ChartPanel";constructor(e){super(e),this.handleColumnSelected=this.handleColumnSelected.bind(this),this.handleColumnMouseEnter=this.handleColumnMouseEnter.bind(this),this.handleColumnMouseLeave=this.handleColumnMouseLeave.bind(this),this.handleDisconnect=this.handleDisconnect.bind(this),this.handleReconnect=this.handleReconnect.bind(this),this.handleFilterAdd=this.handleFilterAdd.bind(this),this.handleHide=this.handleHide.bind(this),this.handleError=this.handleError.bind(this),this.handleLoadError=this.handleLoadError.bind(this),this.handleLoadSuccess=this.handleLoadSuccess.bind(this),this.handleResize=this.handleResize.bind(this),this.handleSettingsChanged=this.handleSettingsChanged.bind(this),this.handleOpenLinker=this.handleOpenLinker.bind(this),this.handleShow=this.handleShow.bind(this),this.handleSourceColumnChange=this.handleSourceColumnChange.bind(this),this.handleSourceFilterChange=this.handleSourceFilterChange.bind(this),this.handleSourceSortChange=this.handleSourceSortChange.bind(this),this.handleTabBlur=this.handleTabBlur.bind(this),this.handleTabFocus=this.handleTabFocus.bind(this),this.handleUpdate=this.handleUpdate.bind(this),this.updateModelFromSource=Ye(this.updateModelFromSource.bind(this),Ly),this.handleClearAllFilters=this.handleClearAllFilters.bind(this),this.panelContainer=de.createRef(),this.chart=de.createRef(),this.pending=new Yn;const{metadata:t,panelState:n}=e,{filterValueMap:s=[],settings:i={}}=n??{};this.state={settings:i,error:void 0,isActive:!1,isDisconnected:!1,isLoading:!1,isLoaded:!1,isLinked:t!=null&&il(t)&&t.settings.isLinked,filterMap:new Map(s),filterValueMap:new Map(s),model:void 0,columnMap:new Map,panelState:n}}componentDidMount(){this.isHidden()||(this.setState({isActive:!0}),this.initModel())}componentDidUpdate(e,t){const{inputFilters:n,source:s}=this.props,{columnMap:i,model:o,filterMap:l,filterValueMap:a,isLinked:d,settings:h}=this.state;o&&(i!==t.columnMap&&this.pruneFilterMaps(),n!==e.inputFilters&&this.updateChangedInputFilters(n,e.inputFilters),l!==t.filterMap?this.updateFilters():a!==t.filterValueMap&&this.updatePanelState(),h!==t.settings&&Hd(o)&&(o.updateSettings(h),this.updatePanelState()),d!==t.isLinked?s&&(d?(this.startListeningToSource(s),this.updateModelFromSource()):this.stopListeningToSource(s)):d&&s!==e.source&&(e.source&&this.stopListeningToSource(e.source),s&&(this.startListeningToSource(s),this.updateModelFromSource())))}componentWillUnmount(){this.pending.cancel();const{source:e}=this.props;e&&this.stopListeningToSource(e)}panelContainer;chart;pending;initModel(){this.setState({isLoading:!0,isLoaded:!1,error:void 0});const{makeModel:e}=this.props;this.pending.add(e(),t=>{t.close()}).then(this.handleLoadSuccess,this.handleLoadError)}getWaitingInputMap=ge((e,t,n)=>{if(!e)return new Map;const s=new Map(t);return n.forEach((i,o)=>{s.delete(o)}),s});getWaitingFilterMap=ge((e,t,n,s,i)=>{if(!e)return new Map;const o=new Map(t);return n.forEach((l,a)=>{o.delete(a)}),i.forEach((l,a)=>{o.delete(a)}),s.forEach((l,a)=>{o.delete(a)}),o});getInputFilterColumnMap=ge((e,t)=>{const n=new Map;for(let s=0;s<t.length;s+=1){const i=t[s],{name:o,type:l}=i,a=e.get(o);a!=null&&a.type===l&&n.set(o,i)}return n});getLinkedColumnMap=ge((e,t)=>{const n=new Map,s=K.getIdFromPanel(this);for(let i=0;i<t.length;i+=1){const o=t[i];let l=null;if(o.start!=null&&o.start.panelId===s&&e.has(o.start.columnName)?l=o.start.columnName:o.end&&o.end.panelId===s&&e.has(o.end.columnName)&&(l=o.end.columnName),l!=null&&e.has(l)){const a=e.get(l);N(a),n.set(l,a)}}return n});getSelectorColumns=ge((e,t,n)=>Array.from(e.values()).map(s=>({name:s.name,type:s.type,isValid:n?n(this,s):!1,isActive:t.has(s.name)})));startListeningToSource(e){Lt.debug("startListeningToSource",e),e.addEventListener(I.Table.EVENT_CUSTOMCOLUMNSCHANGED,this.handleSourceColumnChange),e.addEventListener(I.Table.EVENT_FILTERCHANGED,this.handleSourceFilterChange),e.addEventListener(I.Table.EVENT_SORTCHANGED,this.handleSourceSortChange)}stopListeningToSource(e){Lt.debug("stopListeningToSource",e),e.removeEventListener(I.Table.EVENT_CUSTOMCOLUMNSCHANGED,this.handleSourceColumnChange),e.removeEventListener(I.Table.EVENT_FILTERCHANGED,this.handleSourceFilterChange),e.removeEventListener(I.Table.EVENT_SORTCHANGED,this.handleSourceSortChange)}loadModelIfNecessary(){const{isActive:e,isLoaded:t,isLoading:n}=this.state;e&&!t&&!n&&this.initModel()}isHidden(){const{glContainer:e}=this.props,{isHidden:t}=e;return t}handleColumnSelected(e){const{glEventHub:t}=this.props,{columnMap:n}=this.state;t.emit(Qa.COLUMN_SELECTED,this,n.get(e))}handleColumnMouseEnter({type:e,name:t}){const{columnSelectionValidator:n}=this.props;Lt.debug("handleColumnMouseEnter",n,e,t),n&&n(this,{type:e,name:t})}handleColumnMouseLeave(){const{columnSelectionValidator:e}=this.props;Lt.debug("handleColumnMouseLeave",e),e&&e(this,void 0)}handleDisconnect(){this.setState({error:new Error("Figure disconnected"),isDisconnected:!0})}handleFilterAdd(e){for(let t=0;t<e.length;t+=1)this.openInputFilter(e[t])}handleOpenLinker(){const{localDashboardId:e,setActiveTool:t,setDashboardIsolatedLinkerPanelId:n}=this.props;n(e,void 0),t(_t.LINKER)}handleReconnect(){this.setState({isDisconnected:!1,error:void 0}),this.sendColumnChange(),this.updateColumnFilters()}handleLoadSuccess(e){Lt.debug("handleLoadSuccess");const{model:t}=this.state;this.setState({model:e,isLoaded:!0},()=>{const{inputFilters:n,source:s}=this.props,{filterMap:i,isLinked:o}=this.state;e!==t&&(this.sendColumnChange(),this.updateColumnFilters(),this.updateInputFilters(n,i.size>0||e.isFilterRequired()),s&&o&&(this.startListeningToSource(s),this.updateModelFromSource()))})}handleLoadError(e){ye.isCanceled(e)||(Lt.error("handleLoadError",e),this.setState({error:e,isLoading:!1}))}handleSourceColumnChange(){this.updateModelFromSource()}handleSourceFilterChange(){this.updateModelFromSource()}handleSourceSortChange(){this.updateModelFromSource()}updateModelFromSource(){const{metadata:e,source:t}=this.props,{isLinked:n,model:s}=this.state;if(!n||!s||!t){Lt.debug2("updateModelFromSource ignoring",n,s,t);return}if(this.pending.cancel(),il(e)){const{settings:i}=e;this.pending.add(I.plot.Figure.create(Qe.makeFigureSettings(i,t))).then(o=>{Hd(s)&&s.setFigure(o)}).catch(this.handleLoadError)}this.updatePanelState()}updatePanelState(){const{sourcePanel:e}=this.props,{panelState:t,filterValueMap:n,settings:s}=this.state;let{tableSettings:i}=t??{};if(e&&Oy(e.props)&&Ay(e.state)){const{inputFilters:o}=e.props,{panelState:l}=e.state;l!=null&&(i=Se.extractTableSettings(l,o))}this.setState({panelState:{settings:s,tableSettings:i,filterValueMap:Array.from(n)}})}handleError(){this.setState({isLoading:!1})}handleResize(){this.updateChart()}handleSettingsChanged(e){this.setState(({settings:t})=>{const n={...t,...e};return Lt.debug("Updated settings",n),{settings:n}})}handleHide(){this.setActive(!1)}handleShow(){this.setActive(!0)}handleTabBlur(){this.setActive(!1)}handleTabFocus(){const e=this.isHidden();this.setActive(!e)}handleUpdate(){this.setState({isLoading:!1})}handleClearAllFilters(){this.setState({filterValueMap:new Map,filterMap:new Map}),this.updatePanelState()}openInputFilter(e){const{glEventHub:t}=this.props,{name:n,type:s}=e;t.emit(Ze.OPEN_INPUT,{title:`${n} Filter`,panelState:{name:n,type:s,isValueShown:!0},createNewStack:!0,focusElement:"input"})}setActive(e){this.setState({isActive:e},()=>{e&&(this.loadModelIfNecessary(),this.updateChart())})}sendColumnChange(){const{model:e}=this.state;if(!e)return;const{glEventHub:t}=this.props;t.emit(Ze.COLUMNS_CHANGED,this,Array.from(e.getFilterColumnMap().values()))}getCoordinateForColumn(e){const t=ro.makeButtonClassName(e);if(!this.panelContainer.current)return null;const s=this.panelContainer.current.querySelector(`.${t}`)?.getBoundingClientRect()??null;if(s==null||s.width<=0||s.height<=0)return null;const i=s.left+s.width/2,o=s.bottom;return[i,o]}setFilterMap(e){Lt.debug("setFilterMap",e),this.setState(t=>{const{columnMap:n,filterMap:s}=t;let i=null;const o=new Map(t.filterValueMap);return e.forEach(({columnType:l,filterList:a},d)=>{const h=n.get(d);if(h==null||h.type!==l)return;if(a.length<1){Lt.debug("Ignoring empty filterList for column",d);return}const{value:u}=a[0];o.set(d,u),s.get(d)!==u&&(i===null&&(i=new Map(s)),i.set(d,u))}),{filterValueMap:o,filterMap:i??s}})}unsetFilterValue(e){this.setState(t=>{const{inputFilters:n}=this.props,{columnMap:s}=t;let{filterMap:i,filterValueMap:o}=t;if(!o.has(e))return null;o=new Map(t.filterValueMap),o.delete(e);const l=this.getInputFilterColumnMap(s,n);if(l.has(e)){const a=i.get(e),d=l.get(e)?.value;d!=null&&a!==d&&(i=new Map(t.filterMap),d.length>0?i.set(e,d):i.delete(e))}else i=new Map(t.filterMap),i.delete(e);return{filterMap:i,filterValueMap:o}})}updateChangedInputFilters(e,t){const n=t.filter(i=>e.find(o=>o.name===i.name&&o.type===i.type)===void 0);n.length>0&&this.deleteInputFilters(n);const s=e.filter(i=>!t.includes(i));s.length>0&&this.updateInputFilters(s)}updateInputFilters(e,t=!1){this.setState(n=>{const{columnMap:s}=n,i=new Map(n.filterValueMap),o=new Map(n.filterMap),l=t?{filterMap:o,filterValueMap:i}:{};for(let a=0;a<e.length;a+=1){const{name:d,type:h,value:u}=e[a],m=s.get(d);m!=null&&m.type===h&&(u!=null&&o.get(d)!==u&&(u===""?o.delete(d):o.set(d,u),l.filterMap=o),i.has(d)&&(i.delete(d),l.filterValueMap=i))}return Lt.debug("updateInputFilters",l),l})}deleteInputFilters(e,t=!1){this.setState(n=>{const{columnMap:s,filterValueMap:i}=n,o=new Map(n.filterMap);let l=t;for(let a=0;a<e.length;a+=1){const{name:d,type:h}=e[a],u=s.get(d);if(u!=null&&u.type===h&&o.has(d)){const m=o.get(d);if(i.has(d)){const g=i.get(d);g!==m&&g!=null&&(l=!0,o.set(d,g))}else l=!0,o.delete(d)}}return Lt.debug("deleteInputFilters",l),l?{filterMap:o}:null})}updateColumnFilters(){this.setState(({model:e})=>e?{columnMap:e.getFilterColumnMap()}:null)}updateFilters(){const{columnMap:e,filterMap:t,model:n}=this.state;N(n);const s=this.getWaitingInputMap(n.isFilterRequired(),e,t);if(n.setFilter(t),t.size>0&&s.size===0){const i=n.getDefaultTitle(),o=en.join(Array.from(t.entries()).map(([l,a])=>`${l}: ${a}`));i?n.setTitle(`${i}<br><span style="font-size: smaller">${o}</span>`):n.setTitle(o),Lt.debug2("updateFilters filters set",t),this.setState({isLoading:!0})}else Lt.debug2("updateFilters waiting on inputs",s),n.setTitle(n.getDefaultTitle()),this.setState({isLoading:!1});this.updatePanelState()}pruneFilterMaps(){this.setState(e=>{const{columnMap:t}=e,n=new Map(e.filterMap),s=new Map(e.filterValueMap),i={};return e.filterValueMap.forEach((o,l)=>{t.has(l)||(s.delete(l),i.filterValueMap=s)}),e.filterMap.forEach((o,l)=>{t.has(l)||(n.delete(l),i.filterMap=n)}),i})}updateChart(){this.chart.current&&this.chart.current.updateDimensions()}render(){const{columnSelectionValidator:e,glContainer:t,glEventHub:n,inputFilters:s,isLinkerActive:i,links:o,metadata:l,settings:a}=this.props,{columnMap:d,filterMap:h,error:u,model:m,isActive:g,isDisconnected:p,isLoaded:C,isLoading:f}=this.state;let b;il(l)?b=l.table:b=l.figure;const w=this.getInputFilterColumnMap(d,s),S=this.getLinkedColumnMap(d,o),T=m!=null?this.getWaitingInputMap(m.isFilterRequired(),d,h):new Map,y=m!=null?this.getWaitingFilterMap(m.isFilterRequired(),d,h,S,w):new Map,E=u!=null?`Unable to open chart. ${u}`:void 0,R=T.size>0,x=d.size>0&&i;return r.jsx(Gr,{className:Y("iris-chart-panel",{"input-required":R}),componentPanel:this,glContainer:t,glEventHub:n,onHide:this.handleHide,onClearAllFilters:this.handleClearAllFilters,onResize:this.handleResize,onShow:this.handleShow,onTabBlur:this.handleTabBlur,onTabFocus:this.handleTabFocus,errorMessage:E,isDisconnected:p,isLoading:f,isLoaded:C,widgetName:b,widgetType:"Chart",children:r.jsxs("div",{ref:this.panelContainer,className:"chart-panel-container h-100 w-100",children:[r.jsx("div",{className:"chart-container h-100 w-100",children:C&&m&&r.jsx(hC,{isActive:g,model:m,settings:a,ref:this.chart,onDisconnect:this.handleDisconnect,onReconnect:this.handleReconnect,onUpdate:this.handleUpdate,onError:this.handleError,onSettingsChanged:this.handleSettingsChanged})}),r.jsx(Wt,{in:R&&!x&&!f,timeout:Je.transitionMs,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx(Bu,{inputFilterMap:w,linkedColumnMap:S,onAdd:this.handleFilterAdd,onOpenLinker:this.handleOpenLinker,columnMap:d,waitingFilterMap:y,waitingInputMap:T})}),r.jsx(Wt,{in:x,timeout:Je.transitionMs,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx(ro,{columns:this.getSelectorColumns(d,S,e),onColumnSelected:this.handleColumnSelected,onMouseEnter:this.handleColumnMouseEnter,onMouseLeave:this.handleColumnMouseLeave})})]})})}}const Py=(c,e)=>{const{localDashboardId:t,metadata:n}=e;let s;n!=null&&(s=n.sourcePanelId);const i=Kr(c,t),o=au(c,t),l=Xl(c),a=Yr(c,t),d=l===_t.LINKER&&a===void 0;return{columnSelectionValidator:qr(c,t),isLinkerActive:d,inputFilters:zr(c,t),links:Ni(c,t),source:s!=null?i.get(s):void 0,sourcePanel:s!=null?o.get(s):void 0,settings:wt(c)}},jy=St(Py,{setActiveTool:Ql,setDashboardIsolatedLinkerPanelId:Hu},null,{forwardRef:!0})(_y),Ei=jy;const qo=ne.module("CommandHistoryPanel");class Zr extends v.Component{static COMPONENT="CommandHistoryPanel";static TITLE="Command History";static handleError(e){qo.error(e)}constructor(e){super(e),this.handleFocusHistory=this.handleFocusHistory.bind(this),this.handleSessionOpened=this.handleSessionOpened.bind(this),this.handleSessionClosed=this.handleSessionClosed.bind(this),this.handleShow=this.handleShow.bind(this),this.handleSendToConsole=this.handleSendToConsole.bind(this),this.handleSendToNotebook=this.handleSendToNotebook.bind(this),this.container=de.createRef(),this.pending=new Yn;const{session:t,sessionId:n,language:s}=e;this.state={panelState:{},session:t,sessionId:n,language:s,contextActions:[{action:this.handleFocusHistory,shortcut:Nt.COMMAND_HISTORY.FOCUS_HISTORY}]}}componentDidMount(){const{glEventHub:e,session:t}=this.props;e.on($t.FOCUS_HISTORY,this.handleFocusHistory),t!=null&&this.loadTable()}componentWillUnmount(){const{glEventHub:e}=this.props;e.off($t.FOCUS_HISTORY,this.handleFocusHistory),this.pending.cancel()}container;pending;handleFocusHistory(){this.container.current&&this.container.current.focus()}handleShow(){this.container.current?.restoreScrollPosition()}handleSessionOpened(e,{language:t,sessionId:n}){this.setState({session:e,sessionId:n,language:t},()=>{this.loadTable()})}handleSessionClosed(){this.pending.cancel(),this.setState({session:void 0,language:void 0,table:void 0})}handleSendToNotebook(e,t=!1){const{session:n,language:s}=this.state;if(qo.debug("handleSendToNotebook",n,e),!n){qo.error("Session is not connected.");return}const{glEventHub:i}=this.props;i.emit(t?Ue.CREATE_NOTEBOOK:Ue.SEND_TO_NOTEBOOK,n,s,e)}handleSendToConsole(e,t=!0,n=!1){qo.debug("handleSendToConsole",e);const{glEventHub:s}=this.props;s.emit($t.SEND_COMMAND,e,t,n)}loadTable(){const{commandHistoryStorage:e}=this.props,{language:t,sessionId:n}=this.state;N(t),N(n),this.pending.add(e.getTable(t,n,Date.now()),s=>s.close()).then(s=>{this.setState({table:s})}).catch(Zr.handleError)}render(){const{glContainer:e,glEventHub:t,commandHistoryStorage:n}=this.props,{language:s,contextActions:i,table:o}=this.state;return r.jsxs(qn,{className:"command-history-pane",componentPanel:this,glContainer:e,glEventHub:t,onSessionOpen:this.handleSessionOpened,onSessionClose:this.handleSessionClosed,onShow:this.handleShow,children:[!o&&r.jsx("div",{className:"command-history-disconnected-message",children:"Waiting for console connection"}),o&&s!=null&&r.jsxs(r.Fragment,{children:[r.jsx(qf,{ref:this.container,language:s,sendToNotebook:this.handleSendToNotebook,sendToConsole:this.handleSendToConsole,table:o,commandHistoryStorage:n}),r.jsx(ie,{actions:i})]})]})}}const Hy=(c,e)=>{const t=wh(c),n=Qs(c,e.localDashboardId),{session:s,config:i}=n??{},{type:o,id:l}=i??{};return{commandHistoryStorage:t,language:o,session:s,sessionId:l}},By=St(Hy,null,null,{forwardRef:!0})(Zr),Il=By;const Xo=ne.module("ConsolePanel"),Uy=500,Vy=Object.freeze({consoleSettings:{},itemIds:[]});class $y extends v.PureComponent{static COMPONENT="ConsolePanel";static TITLE="Console";constructor(e){super(e),this.handleFocusCommandHistory=this.handleFocusCommandHistory.bind(this),this.handleOpenObject=this.handleOpenObject.bind(this),this.handleCloseObject=this.handleCloseObject.bind(this),this.handleResize=this.handleResize.bind(this),this.handleSettingsChange=this.handleSettingsChange.bind(this),this.handleShow=this.handleShow.bind(this),this.handlePanelMount=this.handlePanelMount.bind(this),this.consoleRef=de.createRef();const{panelState:t}=e,n={...Vy,...t||{}},{consoleSettings:s,itemIds:i}=n;this.state={consoleSettings:s,itemIds:new Map(i),objectMap:new Map,error:void 0,panelState:n}}componentDidMount(){const{glEventHub:e}=this.props;this.closeDisconnectedPanels(),e.on(Ee.MOUNT,this.handlePanelMount),this.subscribeToFieldUpdates()}componentDidUpdate(e,t){const{consoleSettings:n,itemIds:s}=this.state;(t.consoleSettings!==n||t.itemIds!==s)&&this.savePanelState()}componentWillUnmount(){const{glEventHub:e}=this.props;this.savePanelState.flush(),e.off(Ee.MOUNT,this.handlePanelMount),this.objectSubscriptionCleanup?.()}consoleRef;objectSubscriptionCleanup;subscribeToFieldUpdates(){const{sessionWrapper:e}=this.props,{session:t}=e;this.objectSubscriptionCleanup=t.subscribeToFieldUpdates(n=>{Xo.debug("Got updates",n),this.setState(({objectMap:s})=>{const{updated:i,created:o,removed:l}=n,a=[...i,...l],d=new Map(s);return a.forEach(u=>{const{title:m}=u;m!==void 0&&d.delete(m)}),[...i,...o].forEach(u=>{u.title!==void 0&&d.set(u.title,u)}),{objectMap:d}})})}setItemId(e,t){this.setState(({itemIds:n})=>{const s=new Map(n);return s.set(e,t),{itemIds:s}})}getItemId(e,t=!0){const{itemIds:n}=this.state;let s=n.get(e);return s==null&&t&&(s=qe.generate(),this.setItemId(e,s)),s}handleTabFocus(){this.consoleRef.current?.focus()}handlePanelMount(e){const{itemIds:t}=this.state,n=e?.props?.id,s=e?.props?.metadata?.sourcePanelId;n&&s&&new Set(t.values()).has(s)&&this.setItemId(n,n)}handleFocusCommandHistory(){const{glEventHub:e}=this.props;e.emit($t.FOCUS_HISTORY)}handleResize(){this.updateDimensions()}handleShow(){this.updateDimensions()}handleOpenObject(e){const{sessionWrapper:t}=this.props,{session:n}=t;this.openWidget(e,n)}handleCloseObject(e){const{title:t}=e;if(t!==void 0){const n=this.getItemId(t,!1),{glEventHub:s}=this.props;s.emit(Ee.CLOSE,n)}}handleSettingsChange(e){const{glEventHub:t}=this.props;Xo.debug("handleSettingsChange",e),this.setState({consoleSettings:e}),t.emit($t.SETTINGS_CHANGED,e)}openWidget(e,t){const{glEventHub:n}=this.props,{title:s}=e;N(s);const i=this.getItemId(s),o={fetch:()=>t.getObject(e),panelId:i,widget:e};Xo.debug("openWidget",o),n.emit(Ee.OPEN,o)}addCommand(e,t=!0,n=!1){this.consoleRef.current?.addCommand(e,t,n)}closeDisconnectedPanels(e=!1){const{consoleSettings:t,itemIds:n}=this.state,{isClosePanelsOnDisconnectEnabled:s=!0}=t;if(!s&&!e)return;const i=[...n.values()],{glEventHub:o}=this.props;i.forEach(l=>{o.emit(Ee.CLOSE,l)}),this.setState({itemIds:new Map})}savePanelState=Ye(()=>{const{consoleSettings:e,itemIds:t}=this.state,n={consoleSettings:e,itemIds:[...t]};Xo.debug("Saving panel state",n),this.setState({panelState:n})},Uy);updateDimensions(){this.consoleRef.current?.updateDimensions()}render(){const{commandHistoryStorage:e,glContainer:t,glEventHub:n,sessionWrapper:s,timeZone:i,unzip:o}=this.props,{consoleSettings:l,error:a,objectMap:d}=this.state,{config:h,session:u,connection:m,details:g={}}=s,{workerName:p,processInfoId:C}=g,{id:f,type:b}=h;return r.jsx(qn,{className:"iris-panel-console",componentPanel:this,glContainer:t,glEventHub:n,onResize:this.handleResize,onShow:this.handleShow,onTabFocus:this.handleTabFocus,errorMessage:a!=null?`${a}`:void 0,children:u!=null&&r.jsx(Af,{ref:this.consoleRef,settings:l,session:u,focusCommandHistory:this.handleFocusCommandHistory,openObject:this.handleOpenObject,closeObject:this.handleCloseObject,commandHistoryStorage:e,onSettingsChange:this.handleSettingsChange,language:b,statusBarChildren:r.jsxs(r.Fragment,{children:[r.jsx("div",{children:" "}),r.jsx("div",{children:rh.LANGUAGE_MAP.get(b)}),p!=null&&r.jsxs(r.Fragment,{children:[r.jsx("div",{children:" • "}),p]}),C!=null&&r.jsxs(r.Fragment,{children:[r.jsx("div",{children:" • "}),C,r.jsx("div",{children:" •"})]}),r.jsx("div",{children:" "}),r.jsx("div",{children:r.jsx(mC,{connection:m,defaultUpdateInterval:10*1e3,hoverUpdateInterval:3*1e3,monitorDuration:10*60*1e3})}),r.jsx("div",{children:" "})]}),scope:f,timeZone:i,objectMap:d,unzip:o})})}}const Wy=(c,e)=>({commandHistoryStorage:wh(c),sessionWrapper:Qs(c,e.localDashboardId),timeZone:po(c)}),Gy=St(Wy,null,null,{forwardRef:!0})($y),Ci=Gy;const Zo=ne.module("DropdownFilter"),zy=150;class eo extends v.Component{static defaultProps={column:null,disableLinking:!1,isLinkerActive:!1,isLoaded:!1,isValueShown:!1,settingsError:null,source:null,value:"",values:[],onColumnSelected:()=>{},onSourceMouseEnter:()=>{},onSourceMouseLeave:()=>{}};static PLACEHOLDER="Select a value...";static SOURCE_BUTTON_CLASS_NAME="btn-dropdown-filter-selector";static SOURCE_BUTTON_PLACEHOLDER="Select a column";constructor(e){super(e),this.handleColumnChange=this.handleColumnChange.bind(this),this.handleSettingsCancel=this.handleSettingsCancel.bind(this),this.handleSettingsClick=this.handleSettingsClick.bind(this),this.handleSettingsSave=this.handleSettingsSave.bind(this),this.handleBackgroundClick=this.handleBackgroundClick.bind(this),this.handleDropdownKeyPress=this.handleDropdownKeyPress.bind(this),this.handleValueChange=this.handleValueChange.bind(this),this.dropdownRef=de.createRef();const{column:t,isValueShown:n,value:s}=e;this.state={column:t,id:qe(),selectedColumn:t,disableCancel:!n,isValueShown:n,value:s}}componentDidUpdate(e,t){const{source:n,values:s,isLoaded:i}=this.props,{column:o,value:l,isValueShown:a}=this.state;i&&(n!==e.source&&this.sourceUpdated(),s!==e.values&&l!==""&&!s.includes(l)&&this.resetValue(),a!==t.isValueShown&&a&&this.focusInput(),(o!==t.column||l!==t.value||a!==t.isValueShown)&&this.sendUpdate())}componentWillUnmount(){this.sendUpdate.flush()}dropdownRef;getCompatibleColumns=ge((e,t)=>e!=null?t.filter(({type:n})=>n!==void 0&&F.isCompatibleType(n,e.columnType)):[]);getColumnOptions=ge((e,t)=>{let n=-1;const s=[];return s.push(r.jsx("option",{value:"-1",children:"Select a column"},"placeholder")),e.forEach((i,o)=>{s.push(r.jsx("option",{value:o,children:this.getItemLabel(e,o)},`${i.name}/${i.type}`)),t!==null&&i.name===t.name&&i.type===t.type&&(n=o)}),[s,n]});getSelectedOptionIndex=ge((e,t)=>e.indexOf(t));getValueOptions=ge(e=>[r.jsx("option",{value:"-1",children:eo.PLACEHOLDER},"-1"),...e.map((t,n)=>r.jsx("option",{value:n,children:t??"(null)"},`${n}/${t}`))]);getItemLabel=Re((e,t)=>{const{name:n,type:s}=e[t];if(t>0&&e[t-1].name===n||t<e.length-1&&e[t+1].name===n){const i=s.substring(s.lastIndexOf(".")+1);return`${n} (${i})`}return n});handleColumnChange(e){const{value:t}=e.target;if(Zo.debug2("handleColumnChange",t),t!=null&&parseInt(t,10)<0){this.setState({selectedColumn:null});return}const{columns:n,source:s}=this.props,i=this.getCompatibleColumns(s,n);this.setState({selectedColumn:i[parseInt(t,10)]})}handleDropdownKeyPress(e){e.key==="Enter"&&(e.preventDefault(),e.stopPropagation(),Zo.debug2("handleDropdownKeyPress"),this.sendUpdate(),this.sendUpdate.flush())}handleValueChange(e){const{value:t}=e.target,n=parseInt(t,10);let s="";const{values:i}=this.props;n>=0&&n<i.length?s=i[n]:Zo.debug2("Selected default item"),Zo.debug2("handleValueChange",s),this.setState({value:s})}handleSettingsCancel(){this.setState(({column:e})=>({selectedColumn:e,isValueShown:!0}))}handleSettingsSave(){this.setState(({column:e,selectedColumn:t,value:n})=>({column:t,value:e===t?n:"",isValueShown:!0,disableCancel:!1}))}handleSettingsClick(e){e.stopPropagation(),this.showSettings()}handleBackgroundClick(e){e.target!==this.dropdownRef.current&&this.focusInput()}sourceUpdated(){this.setState({column:null,selectedColumn:null,isValueShown:!1,disableCancel:!0,value:""})}showSettings(){const{column:e}=this.state;this.setState({selectedColumn:e,isValueShown:!1})}focusInput(){this.dropdownRef.current?.focus()}resetValue(){this.setState({value:""})}clearFilter(){this.resetValue()}setFilterState({name:e,type:t,value:n,isValueShown:s}){const i=e!=null&&t!=null?{name:e,type:t}:null;this.setState(({value:o,isValueShown:l})=>({column:i,value:n??o,isValueShown:s??l}))}sendUpdate=Ye(()=>{const{onChange:e}=this.props,{column:t,value:n,isValueShown:s}=this.state;e({column:t,isValueShown:s,value:n??void 0})},zy);render(){const{columns:e,disableLinking:t,isLinkerActive:n,isLoaded:s,source:i,onColumnSelected:o,onSourceMouseEnter:l,onSourceMouseLeave:a,values:d,settingsError:h}=this.props,{column:u,disableCancel:m,id:g,isValueShown:p,selectedColumn:C,value:f}=this.state,b=i===null,w=this.getCompatibleColumns(i,e),S=i!=null,T=i?.columnName??eo.SOURCE_BUTTON_PLACEHOLDER,y=u!=null?`${u.name} Filter`:null,[E,R]=this.getColumnOptions(w,C),x=this.getValueOptions(d),D=this.getSelectedOptionIndex(d,f),M=!S||C==null,O=p&&!n,H=`source-column-btn-${g}`,L=`filter-column-select-${g}`;return r.jsxs(ar,{className:"dropdown-filter fill-parent-absolute",isFlipped:O,children:[r.jsx("div",{className:"dropdown-filter-settings-card",children:r.jsxs("div",{className:"dropdown-filter-card-content",children:[r.jsxs("div",{className:"dropdown-filter-settings-grid",children:[r.jsx("label",{htmlFor:H,children:"Source Column"}),r.jsx(Kc,{id:H,isLinked:S,onClick:o,onMouseEnter:l,onMouseLeave:a,className:eo.SOURCE_BUTTON_CLASS_NAME,disabled:t,children:T}),r.jsx("div",{className:"text-muted small",children:"Select a source column for the list by linking to a table."}),r.jsx("label",{htmlFor:L,children:"Filter Column"}),r.jsx("select",{id:L,value:R,className:"custom-select",onChange:this.handleColumnChange,disabled:b,children:E}),r.jsx("div",{className:"text-muted small",children:"Dropdown filter control will apply its filter to all columns matching this name in this dashboard."})]}),h&&r.jsx("div",{className:"error-message text-center",children:h}),S&&r.jsxs("div",{className:"dropdown-filter-settings-buttons",children:[r.jsx(B,{kind:"secondary",type:"button",onClick:this.handleSettingsCancel,disabled:m||p||n,tooltip:n?"Cancel disabled while linker open":void 0,children:"Cancel"}),r.jsx(B,{kind:"primary",type:"button",className:"ml-2",onClick:this.handleSettingsSave,disabled:M||p||n,tooltip:n?"Save disabled while linker open":void 0,children:"Save"})]})]})}),r.jsx("div",{className:"dropdown-filter-value-card",onClick:this.handleBackgroundClick,"data-testid":"dropdown-filter-value-background",children:s&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"dropdown-filter-column",children:r.jsx("div",{className:"dropdown-filter-column-title",children:y})}),r.jsxs("div",{className:"dropdown-filter-card-content",children:[r.jsx("div",{className:"dropdown-filter-value-input d-flex flex-column justify-content-center",children:r.jsx("select",{className:"custom-select",value:D,ref:this.dropdownRef,onChange:this.handleValueChange,onKeyPress:this.handleDropdownKeyPress,title:"Select Value",children:x})}),h&&r.jsx("div",{className:"error-message mt-3 text-center",children:h})]}),r.jsx("div",{className:"dropdown-filter-menu",children:r.jsx(B,{kind:"ghost",className:"m-2 px-2",onClick:this.handleSettingsClick,icon:r.jsx(ee,{icon:mo,transform:"grow-4"}),tooltip:"Dropdown Filter Settings"})})]})})]})}}const mc=eo;const nt=ne.module("DropdownFilterPanel"),Ky=250,Yy=(c,e)=>{const{localDashboardId:t}=e,n=K.getIdFromPanel({props:e}),s=Kr(c,t),i=Ni(c,t),o=Xl(c),l=Yr(c,t),a=o===_t.LINKER&&(l===void 0||l===n),d=o===_t.LINKER&&l!==void 0&&l!==n;return{columns:ju(c,t),columnSelectionValidator:qr(c,t),isLinkerActive:a,disableLinking:d,settings:wt(c),panelTableMap:s,dashboardLinks:i}},qy=St(Yy,null,null,{forwardRef:!0});class gs extends v.Component{static displayName="DropdownFilterPanel";static COMPONENT="DropdownFilterPanel";static MAX_TABLE_SIZE=256;static DATETIME_FORMATTER=new ct({showTimeZone:!1,showTSeparator:!0,defaultDateTimeFormatString:"yyyy-MM-dd HH:mm:ss.SSSSSSSSS"});static SOURCE_COLUMN=Object.freeze({name:"FilterSource",type:null});constructor(e){super(e),this.handleChange=Ye(this.handleChange.bind(this),Ky),this.handleClearAllFilters=this.handleClearAllFilters.bind(this),this.handleDisconnect=this.handleDisconnect.bind(this),this.handleReconnect=this.handleReconnect.bind(this),this.handleColumnSelected=this.handleColumnSelected.bind(this),this.handleSourceFilterChange=this.handleSourceFilterChange.bind(this),this.handleSourceSortChange=this.handleSourceSortChange.bind(this),this.handleSourceSizeChange=this.handleSourceSizeChange.bind(this),this.handleSourceMouseEnter=this.handleSourceMouseEnter.bind(this),this.handleSourceMouseLeave=this.handleSourceMouseLeave.bind(this),this.handleValuesTableUpdate=this.handleValuesTableUpdate.bind(this),this.dropdownFilterRef=de.createRef(),this.panelContainer=de.createRef(),this.pending=new Yn;const{panelState:t,settings:n}=e;this.columnFormats=$n.getColumnFormats(n);const{value:s="",isValueShown:i=!1,name:o,type:l,timestamp:a}=t??{},d=o!=null&&l!=null?{name:o,type:l}:void 0;this.state={column:d,formatter:new gn(this.columnFormats),valuesTable:void 0,valuesColumn:void 0,sourceSize:0,value:s,timestamp:a,values:[],isValueShown:i,wasFlipped:!1,skipUpdate:!1,panelState:t,isDisconnected:!1,isLoading:!1,isLoaded:!1,error:null}}componentDidMount(){this.updateValuesTable();const{dashboardLinks:e,panelTableMap:t}=this.props,{column:n,value:s,timestamp:i}=this.state,o=this.getSourceTable(t,e);if(o!==null&&this.startListeningToSource(o),n!=null){const{name:l,type:a}=n;this.sendUpdate(l,a,s,i)}}componentDidUpdate(e,t){const{dashboardLinks:n,panelTableMap:s,settings:i}=this.props,{valuesTable:o}=this.state,l=this.getSource(n),a=this.getSourceTable(s,n),d=this.getSource(e.dashboardLinks),h=this.getSourceTable(e.panelTableMap,e.dashboardLinks);i!==e.settings&&i!==void 0&&this.updateFormatterSettings(i),o!==t.valuesTable&&t.valuesTable!=null&&(nt.debug("Table in state modified, closing the old table."),t.valuesTable.close()),(a!==h||l!==d)&&this.updateValuesTable(),a!==h&&(h!==null&&this.stopListeningToSource(h),a!==null&&this.startListeningToSource(a))}componentWillUnmount(){const{dashboardLinks:e,panelTableMap:t}=this.props,{valuesTable:n}=this.state,s=this.getSourceTable(t,e);this.pending.cancel(),s!==null&&this.stopListeningToSource(s),this.cleanup&&this.cleanup(),n?.close()}dropdownFilterRef;panelContainer;pending;cleanup;columnFormats;getCachedValues=Re((e,{type:t,name:n},s)=>t!==void 0&&F.isDateType(t)?e.map(i=>gs.DATETIME_FORMATTER.format(i)):e.map(i=>i!=null&&t!=null?s.getFormattedString(i,t,n):null));getCoordinateForColumn(){if(this.panelContainer.current==null)return null;const t=this.panelContainer.current.querySelector(`.${mc.SOURCE_BUTTON_CLASS_NAME}`)?.getBoundingClientRect()??null;if(t==null||t.width<=0||t.height<=0)return null;const n=t.left+t.width/2,s=t.bottom;return[n,s]}getSettingsErrorMessage(){const{sourceSize:e}=this.state;if(e>gs.MAX_TABLE_SIZE)return`Table too large, must have fewer than ${gs.MAX_TABLE_SIZE} options.`}getPanelErrorMessage(){const{error:e}=this.state;return e!=null?`${e}`:void 0}getCachedPanelLinks=Re((e,t)=>{const n=K.getIdFromPanel(t);return nt.debug("getCachedPanelLinks",e,n),e.filter(s=>s.end?.panelId===n)});getCachedSource=Re(e=>{nt.debug("getCachedSource",e);let t;if(e.length>0){const[n]=e;t=n.start,e.length>1&&nt.error("Filter has more that one link",e)}return t});getCachedSourceTable=Re((e,t)=>{if(nt.debug("getCachedSourceTable",e,t),t==null)return null;const{panelId:n}=t;return e.get(n)??null});getCachedSourceColumn=Re((e,t)=>(nt.debug("getCachedSourceColumn",e,t),e==null||t==null?null:e.columns.find(({name:n,type:s})=>n===t.columnName&&s===t.columnType)??null));getSource(e){const t=this.getCachedPanelLinks(e,this);return this.getCachedSource(t)}getSourceTable(e,t){const n=this.getSource(t);return this.getCachedSourceTable(e,n)}getValuesColumn(e,t){const n=this.getSource(t);return this.getCachedSourceColumn(e,n)}startListeningToSource(e){nt.debug("startListeningToSource"),e.addEventListener(I.Table.EVENT_FILTERCHANGED,this.handleSourceFilterChange),e.addEventListener(I.Table.EVENT_SORTCHANGED,this.handleSourceSortChange),e.addEventListener(I.Table.EVENT_SIZECHANGED,this.handleSourceSizeChange),e.addEventListener(I.Table.EVENT_DISCONNECT,this.handleDisconnect),e.addEventListener(I.Table.EVENT_RECONNECT,this.handleReconnect)}stopListeningToSource(e){nt.debug("stopListeningToSource"),e.removeEventListener(I.Table.EVENT_FILTERCHANGED,this.handleSourceFilterChange),e.removeEventListener(I.Table.EVENT_SORTCHANGED,this.handleSourceSortChange),e.removeEventListener(I.Table.EVENT_SIZECHANGED,this.handleSourceSizeChange),e.removeEventListener(I.Table.EVENT_DISCONNECT,this.handleDisconnect),e.removeEventListener(I.Table.EVENT_RECONNECT,this.handleReconnect)}handleChange({column:e,isValueShown:t=!1,value:n}){const{name:s=void 0,type:i=void 0}=e??{};let o=!0,l=Date.now();this.setState(({panelState:a,timestamp:d,wasFlipped:h,skipUpdate:u})=>{const m=a!=null&&t!==a.isValueShown&&s===a.name&&i===a.type&&n===a.value;return o=(!u&&t&&(!m||!h))??!1,o||(l=d),{panelState:{isValueShown:t,name:s,type:i,value:n,timestamp:l??void 0},timestamp:l,wasFlipped:m,skipUpdate:!1}},()=>{o&&this.sendUpdate(s??null,i,n,l)})}handleDisconnect(){this.setState({error:new Error("Table disconnected"),isDisconnected:!0,isLoading:!1})}handleReconnect(){this.setState({isDisconnected:!1,error:null})}handleSourceFilterChange(){this.applySourceFilters()}handleSourceSortChange(){this.applySourceSorts()}handleSourceSizeChange({detail:e}){this.setState({sourceSize:e})}handleColumnSelected(){nt.debug("handleColumnSelected");const{glEventHub:e}=this.props;e.emit(Ze.COLUMN_SELECTED,this,gs.SOURCE_COLUMN)}handleClearAllFilters(){this.dropdownFilterRef?.current?.clearFilter()}setPanelState(e,t=!1){const{dashboardLinks:n}=this.props;if(this.getSource(n)==null){nt.debug("Ignore state update for unlinked filter",e);return}this.setState({skipUpdate:!t}),this.dropdownFilterRef?.current?.setFilterState(e)}sendUpdate(e,t,n,s){const{dashboardLinks:i,glEventHub:o}=this.props,l=this.getSource(i)?.panelId,a=l===null?[]:[l];nt.debug("sendUpdate",{name:e,type:t,value:n,timestamp:s,excludePanelIds:a}),o.emit(Ze.FILTERS_CHANGED,this,{name:e,type:t,value:n??"=null",timestamp:s,excludePanelIds:a})}updateValuesTable(){const{dashboardLinks:e,panelTableMap:t}=this.props,n=this.getSource(e),s=this.getSourceTable(t,e);if(nt.debug("updateValuesTable",n,s),this.setState({values:[],valuesTable:void 0,error:null}),n==null){nt.debug("Filter unlinked."),this.setState({isLoading:!1,isLoaded:!0,isValueShown:!1,sourceSize:0});return}this.setState({isLoading:!0}),s!=null&&(this.setState({isLoaded:!1,sourceSize:s.size}),this.pending.add(s.copy(),i=>i.close()).then(i=>{this.updateViewportListener(i),this.setState({valuesTable:i})}).catch(i=>{ye.isCanceled(i)||(nt.error(i),this.setState({isLoading:!1,error:i}))}))}applySourceSorts(){const{dashboardLinks:e,panelTableMap:t}=this.props,{valuesTable:n}=this.state,s=this.getSourceTable(t,e);if(nt.debug("applySourceSorts",s?.sort),n==null||s==null){nt.debug("Table not initialized");return}const i=[...s.sort];n.applySort(i),this.setViewport(n)}applySourceFilters(){const{dashboardLinks:e,panelTableMap:t}=this.props,{valuesTable:n}=this.state,s=this.getSourceTable(t,e);if(nt.debug("applySourceFilters",s?.filter),n==null||s==null){nt.debug("Table not initialized");return}const i=[...s.filter];n.applyFilter(i),this.setViewport(n)}updateViewportListener(e){if(nt.debug("updateViewportListener",e?.size),this.cleanup&&this.cleanup(),e==null){this.cleanup=void 0;return}this.cleanup=e.addEventListener(I.Table.EVENT_UPDATED,this.handleValuesTableUpdate),this.setViewport(e)}setViewport(e){const{dashboardLinks:t}=this.props,n=this.getValuesColumn(e,t);if(!n){nt.error("values column is null");return}e.setViewport(0,gs.MAX_TABLE_SIZE-1,[n])}updateFormatterSettings(e){const t=$n.getColumnFormats(e);st(this.columnFormats,t)||(this.columnFormats=t,this.setState({formatter:new gn(t)}))}handleValuesTableUpdate({detail:e}){const{rows:t}=e,{dashboardLinks:n}=this.props,{valuesTable:s}=this.state;if(!s){nt.error("valuesTable is null");return}const i=this.getValuesColumn(s,n);if(!i){nt.error("Values column not found");return}const o=t.map(l=>l.get(i));this.setState({values:o,isLoading:!1,isLoaded:!0,valuesColumn:i})}handleSourceMouseEnter(){const{columnSelectionValidator:e}=this.props;e&&e(this,gs.SOURCE_COLUMN)}handleSourceMouseLeave(){const{columnSelectionValidator:e}=this.props;e&&e(this,void 0)}render(){const{columns:e,dashboardLinks:t,disableLinking:n,glContainer:s,glEventHub:i,isLinkerActive:o}=this.props,{column:l,formatter:a,isDisconnected:d,isValueShown:h,value:u,values:m,valuesColumn:g,isLoading:p,isLoaded:C}=this.state,f=this.getSource(t),b=this.getSettingsErrorMessage(),w=this.getPanelErrorMessage(),S=C&&g!=null?this.getCachedValues(m,g,a):[];return r.jsx(Gr,{errorMessage:w,isLoading:p,isLoaded:C,isDisconnected:d,className:"iris-dropdown-filter-panel",componentPanel:this,glContainer:s,glEventHub:i,onClearAllFilters:this.handleClearAllFilters,widgetName:"Dropdown Filter",widgetType:"DropdownFilter",children:r.jsx("div",{ref:this.panelContainer,className:"dropdown-filter-container h-100 w-100 container",children:r.jsx(mc,{ref:this.dropdownFilterRef,column:l,columns:e,isValueShown:h,isLinkerActive:o,disableLinking:n,isLoaded:C,settingsError:b,source:f,value:u,values:S,onChange:this.handleChange,onColumnSelected:this.handleColumnSelected,onSourceMouseEnter:this.handleSourceMouseEnter,onSourceMouseLeave:this.handleSourceMouseLeave})})})}}const Xy=qy(gs),Ys=Xy;function xn(c){return c.type==="directory"}var Uu=(c=>(c.GROOVY="text/x-groovy",c.PLAIN_TEXT="text/plain",c.PYTHON="text/x-python",c.PYTHON_COMPILED="application/x-python-code",c.SCALA="text/x-scala",c.UNKNOWN="",c))(Uu||{});class Vs{static fileExtensionToString(e=""){return e.length===0?"":`.${e}`}static getDepth(e){if(!Vs.hasPath(e))throw new Error(`Invalid path provided: ${e}`);return(e.match(/\//g)??[]).length-1}static getExtension(e){const t=this.getBaseName(e).split(".");return t.length>1?t.pop()??"":""}static getBaseName(e){return e.split("/").pop()??""}static getCopyFileName(e){const t=e.lastIndexOf(".");let n=null,s=null;t<0?s=e:(s=e.substring(0,t),n=e.substring(t+1));const i=s?`${s}-copy`:"Copy";return n!==null?`${i}.${n}`:i}static getMimeType(e){switch(this.getExtension(e).toLowerCase()){case"groovy":return"text/x-groovy";case"py":return"text/x-python";case"pyc":return"application/x-python-code";case"scala":return"text/x-scala";case"txt":return"text/plain";default:return""}}static getParent(e){if(!Vs.hasPath(e))throw new Error(`Invalid name provided: ${e}`);const t=e.split("/");for(;t.pop()==="";);if(t.length===0)throw new Error(`No parent for path provided: ${e}`);return`${t.join("/")}/`}static getPath(e){if(!Vs.hasPath(e))throw new Error(`Invalid filename provided: ${e}`);const t=e.split("/");return t.pop(),`${t.join("/")}/`}static hasPath(e){return e.startsWith("/")}static isPath(e){return e.startsWith("/")&&e.endsWith("/")}static makePath(e){return e.endsWith("/")?e:`${e}/`}static replaceExtension(e,t=""){const n=e.lastIndexOf("."),s=n>-1?e.substring(0,n):e,i=Vs.fileExtensionToString(t);return`${s}${i}`}static validateName(e){const t=[".",".."],n=/[\\/\0]/g,s=new Map([["\0","null"]]);if(!e)throw new vi("Name cannot be empty");if(t.includes(e))throw new vi(`"${e}" is a reserved name`);if(n.test(e))throw new vi(`Invalid characters in name: "${e.match(n)?.reduce((i,o)=>i.includes(o)?i:[...i,o],[]).map(i=>s.has(i)?s.get(i):i).join('", "')??""}"`)}static reducePaths(e){const t=e.filter(n=>Vs.isPath(n));return e.filter(n=>!t.some(s=>n!==s&&n.startsWith(s)))}static removeRoot(e,t){if(e.length===0)return t;if(!t.startsWith(e))throw new Error(`Filename ${t} does not start with expected root ${e}`);return t.substring(e.length)}static addRoot(e,t){return`${e}${t}`}}const fe=Vs,Qr=26;function Ja(c){return xn(c)?fe.makePath(c.filename):fe.getPath(c.filename)}function gc(c,e){if(c.length===0||e==null)throw new Error("No items to move");const t=Ja(e);if(c.some(({filename:n})=>fe.getPath(n)===t))throw new Error("File already in the destination folder");if(c.some(n=>xn(n)&&t.startsWith(fe.makePath(n.filename))))throw new Error("Destination folder cannot be a child of a dragged folder");return{files:c,targetPath:t}}function Zy(c){if(xn(c))return c.isExpanded?Ug:Vg;switch(fe.getMimeType(c.basename)){case Uu.PYTHON:return Wg;default:return $g}}function er(c){const{children:e,draggedItems:t,isDragInProgress:n,isDropTargetValid:s,isSelected:i,item:o,itemIndex:l,dropTargetItem:a,onDragStart:d,onDragOver:h,onDragEnd:u,onDrop:m}=c,g=t?.some(E=>E.id===o.id)??!1,p=Ja(o),C=n&&a?Ja(a):null,f=n&&s&&xn(o)&&C===p,b=n&&s&&C===p,w=n&&!s&&C===p,S=Zy(o),T=fe.getDepth(o.filename),y=Array(T).fill(null).map((E,R)=>r.jsx("span",{className:"file-list-depth-line"},R));return r.jsxs("div",{className:Y("d-flex w-100 align-items-center","file-list-item",{"is-dragged":g,"is-exact-drop-target":f,"is-in-drop-target":b,"is-invalid-drop-target":w,"is-selected":i}),onDragStart:E=>d(l,E),onDragOver:E=>h(l,E),onDragEnd:E=>u(l,E),onDrop:E=>m(l,E),draggable:!0,role:"presentation","aria-label":o.basename,children:[y," ",r.jsx(ee,{icon:S,className:"item-icon",fixedWidth:!0})," ",r.jsxs("span",{className:"truncation-wrapper",children:[e??o.basename,r.jsx(ot,{options:{placement:"left"},children:e??o.basename})]})]})}const It=ne.module("FileList"),Qy=500,pc="item-list-scroll-pane";function Jy(c){const{isMultiSelect:e=!1,table:t,onFocusChange:n=()=>{},onMove:s,onSelect:i,onSelectionChange:o=()=>{},renderItem:l=er,rowHeight:a=Qr,overscanCount:d=yi.DEFAULT_OVERSCAN}=c,[h,u]=v.useState(()=>({items:[],offset:0,itemCount:0})),[m,g]=v.useState({top:0,bottom:0}),[p,C]=v.useState(),[f,b]=v.useState(),[w,S]=v.useState(),[T,y]=v.useState([]),E=v.useRef(null),R=v.useRef(null),x=v.useCallback(G=>{if(G.length===0||h==null)return[];const oe=[];for(let ue=0;ue<G.length;ue+=1){const ae=G[ue];for(let he=ae[0];he<=ae[1];he+=1)he>=h.offset&&he<h.offset+h.items.length&&oe.push(h.items[he-h.offset])}return oe},[h]),D=v.useCallback(G=>{const oe=x([[G,G]]);if(oe.length>0)return oe[0]},[x]),M=v.useCallback(()=>{const G=gd.count(T);if(G===0)return null;if(G===1){const oe=T[0][0],ue=D(oe);if(ue!=null)return ue.filename}return`${G} items`},[D,T]),O=v.useCallback(G=>{if(!(!f||!p)){It.debug("dropItems",f,"to",G);try{const{files:oe,targetPath:ue}=gc(f,p);s?.(oe,ue),G!=null&&(y([[G,G]]),E.current?.focusItem(G))}catch(oe){It.error("Unable to complete move",oe)}}},[f,p,s]),H=v.useCallback((G,oe)=>{const ue=h.items[G-h.offset];ue!==void 0&&(It.debug("handleItemClick",ue),i(ue,oe),xn(ue)&&t?.setExpanded(ue.filename,!ue.isExpanded))},[h,i,t]),L=v.useCallback((G,oe)=>{It.debug2("handleItemDragStart",G,T);let ue=T;gd.isSelected(T,G)||(ue=[[G,G]],y(ue)),b(x(ue)),E.current?.resetMouseState();const ae=document.createElement("div");ae.innerHTML=`<div class="dnd-placeholder-content">${M()}</div>`,ae.className="file-list-dnd-placeholder",document.body.appendChild(ae),oe.dataTransfer.setDragImage(ae,0,0),oe.dataTransfer.effectAllowed="move",S(ae)},[M,x,T]),V=v.useCallback((G,oe)=>{oe.preventDefault(),It.debug2("handleItemDragOver",oe),C(D(G))},[D]),U=v.useCallback((G,oe)=>{It.debug("handleItemDragEnd",G),w?.remove(),b(void 0),C(void 0),S(void 0)},[w]),j=v.useCallback((G,oe)=>{O(G)},[O]),P=v.useCallback(()=>{It.debug2("handleItemDragExit"),C(void 0)},[]),Q=v.useCallback(G=>{G.target instanceof Element&&G.target.classList.contains(pc)&&(G.preventDefault(),It.debug2("handleListDragOver",G),C({type:"directory",filename:"/",basename:"/",id:"/"}))},[]),$=v.useCallback(G=>{G.target instanceof Element&&G.target.classList.contains(pc)&&(It.debug("handleListDrop"),O())},[O]),J=v.useCallback(G=>{if(It.debug2("handleSelectionChange",G),G!==T){y(G);const oe=x(G);o(oe)}},[x,o,T]),A=v.useCallback(G=>{if(It.debug2("handleFocusChange",G),G!=null){const[oe]=x([[G,G]]);n(oe)}else n()},[x,n]),W=v.useCallback((G,oe)=>{It.debug("handleViewportChange",G,oe),(G!==m.top||oe!==m.bottom)&&g({top:G,bottom:oe})},[m]),q=v.useMemo(()=>{if(!f||!p)return!1;try{return gc(f,p),It.debug("handleValidateDropTarget true"),!0}catch{return It.debug("handleValidateDropTarget false"),!1}},[f,p]),{focusedPath:Z}=c;v.useEffect(()=>{Z!==void 0&&(Z==="/"?t.collapseAll():(t.setExpanded(Z,!1),t.setExpanded(Z,!0)))},[t,Z]),v.useEffect(function(){It.debug("updating table viewport",m),t?.setViewport({top:Math.max(0,m.top-d),bottom:m.bottom+d})},[d,t,m]),v.useEffect(function(){const oe=t.onUpdate(ue=>{u({items:ue.items.map(ae=>({...ae,itemName:ae.basename})),offset:ue.offset,itemCount:t.size})});return()=>{oe()}},[t]),v.useEffect(function(){if(p!=null&&xn(p)&&p.filename!=="/"){const oe=setTimeout(()=>{p.isExpanded||t?.setExpanded(p.filename,!0)},Qy);return()=>clearTimeout(oe)}},[p,t]);const le=v.useCallback(G=>l({...G,isDragInProgress:f!=null,dropTargetItem:p,draggedItems:f,isDropTargetValid:q,onDragStart:L,onDragEnd:U,onDragOver:V,onDragExit:P,onDrop:j}),[U,P,V,L,j,f,p,q,l]);return r.jsx("div",{ref:R,className:Y("file-list",{"is-dragging":f!=null}),onDragOver:Q,onDrop:$,children:r.jsx(yi,{ref:E,items:h.items,itemCount:h.itemCount,offset:h.offset,onFocusChange:A,onSelect:H,onSelectionChange:J,onViewportChange:W,selectedRanges:T,renderItem:le,rowHeight:a,isMultiSelect:e,isDragSelect:!1,isDeselectOnClick:!1})})}const eR={name:"File Explorer",DELETE:We.createAndAdd({id:"FILE_EXPLORER.DELETE",name:"Delete",shortcut:[xe.DELETE],macShortcut:[ve.CMD,xe.BACKSPACE]}),RENAME:We.createAndAdd({id:"FILE_EXPLORER.RENAME",name:"Rename",shortcut:[xe.ENTER],macShortcut:[xe.ENTER]})},fc={FILE_EXPLORER:eR};const Cc=ne.module("FileListItemEditor"),tR=()=>Promise.resolve();function nR({item:c,onCancel:e,onSubmit:t,validate:n=tR}){const s=v.useRef(null),[i,o]=v.useState(c.basename),[l,a]=v.useState(),[d,h]=v.useState(Promise.resolve()),u=v.useCallback(()=>{s.current?.focus()},[s]),m=v.useCallback(b=>b.stopPropagation(),[]),g=v.useCallback(()=>{d.then(()=>{t(i)}).catch(b=>Cc.info("Unable to validate name",b))},[t,i,d]);v.useEffect(function(){const w=ye.makeCancelable(n(i));return w.then(()=>a(void 0)).catch(S=>{ye.isCanceled(S)||a(S)}),h(w),()=>w.cancel()},[n,i]),v.useEffect(function(){u()},[u]);const p=v.useCallback(()=>{Cc.debug2("handleBlur"),g()},[g]),C=v.useCallback(b=>{const{value:w}=b.target;o(w)},[]),f=v.useCallback(b=>{b.stopPropagation();const{key:w}=b;switch(w){case"Enter":{g();break}case"Escape":{e();break}}},[e,g]);return r.jsxs("div",{className:"file-list-item-editor",children:[r.jsx("input",{type:"text",className:Y("form-control file-list-item-editor-input",{"is-invalid":l}),value:i,ref:s,onBlur:p,onKeyDown:f,onChange:C,onClick:m,onDoubleClick:m,onMouseDown:m}),l&&r.jsx("div",{className:"invalid-feedback",children:`${l}`})]})}function Vu(c){const{isMultiSelect:e=!1,focusedPath:t,showContextMenu:n=!1,onCreateFile:s,onCreateFolder:i,onCopy:o,onDelete:l,onMove:a,onRename:d,onSelect:h,onSelectionChange:u,table:m,rowHeight:g=Qr,validateRename:p=()=>Promise.resolve()}=c,[C,f]=v.useState(),[b,w]=v.useState([]),[S,T]=v.useState(),y=v.useCallback(P=>{w(P),u?.(P)},[u]),E=v.useCallback(P=>{T(P)},[]),R=v.useCallback(()=>{S&&o?.(S)},[S,o]),x=v.useCallback(()=>{b.length>0&&l?.(b)},[l,b]),D=v.useCallback(()=>{s?.()},[s]),M=v.useCallback(()=>{S&&i?.(fe.getPath(S.filename))},[S,i]),O=v.useCallback(()=>{S&&f(S)},[S]),H=v.useCallback(()=>{f(void 0)},[]),L=v.useCallback(P=>{C&&(d?.(C,P),f(void 0))},[d,C]),V=v.useMemo(()=>{if(C)return[];const P=[];return s&&P.push({title:"New File",description:"Create new file",action:D,group:ie.groups.medium}),i&&P.push({title:"New Folder",description:"Create new folder",action:M,group:ie.groups.medium}),o&&P.push({title:"Copy",description:"Copy",action:R,group:ie.groups.low,disabled:S==null||xn(S)}),l&&b.length>0&&P.push({title:"Delete",description:"Delete",shortcut:fc.FILE_EXPLORER.DELETE,action:x,group:ie.groups.low}),d&&P.push({title:"Rename",description:"Rename",shortcut:fc.FILE_EXPLORER.RENAME,action:O,group:ie.groups.low,disabled:S==null}),P},[R,x,D,M,O,S,o,s,i,l,d,b,C]),U=v.useCallback(P=>(N(C),p(C,P)),[C,p]),j=v.useCallback(P=>{const{item:Q}=P;return C&&C.filename===Q.filename?r.jsx(er,{...P,children:r.jsx(nR,{item:Q,validate:U,onSubmit:L,onCancel:H})}):r.jsx(er,{...P})},[H,L,C,U]);return r.jsxs("div",{className:"file-list-container",children:[m!=null&&r.jsx(Jy,{onMove:a,onSelect:h,onSelectionChange:y,onFocusChange:E,renderItem:j,rowHeight:g,table:m,isMultiSelect:e,focusedPath:t}),n&&r.jsx(ie,{actions:V})]})}Vu.displayName="FileListContainer";class sR extends vi{isExistingFile=!0;info;constructor(e){super("Name already exists"),this.info=e}}const ol=sR;class iR extends Error{constructor(){super("No file exists at the path specified")}isFileNotFound=!0}const Jr=iR,Os=ne.module("FileExplorer");function ed(c){const{storage:e,isMultiSelect:t=!1,focusedPath:n,onDelete:s=()=>{},onRename:i=()=>{},onSelect:o,onSelectionChange:l,rowHeight:a=Qr}=c,[d,h]=v.useState([]),[u,m]=v.useState();v.useEffect(function(){let R;async function x(){Os.debug("initTable"),R=ye.makeCancelable(e.getTable(),D=>D.close());try{m(await R)}catch(D){ye.isCanceled(D)||Os.error("Unable to initialize table",D)}}return x(),()=>{R.cancel()}},[e]);const g=v.useCallback(E=>{ye.isCanceled(E)||Os.error(E)},[]),p=v.useCallback(E=>{Os.debug("handleDelete, pending confirmation",E),h(E)},[]),C=v.useCallback(()=>{Os.debug("handleDeleteConfirm",d),d.forEach(E=>e.deleteFile(xn(E)?fe.makePath(E.filename):E.filename)),s(d),h([])},[d,s,e]),f=v.useCallback(()=>{Os.debug("handleDeleteCancel"),h([])},[]),b=v.useCallback((E,R)=>{fe.reducePaths(E.map(D=>xn(D)?fe.makePath(D.filename):D.filename)).forEach(D=>{const M=fe.isPath(D)?`${R}${fe.getBaseName(D.substring(0,D.length-1))}/`:`${R}${fe.getBaseName(D)}`;e.moveFile(D,M).then(()=>{i(D,M)}).catch(g)})},[g,i,e]),w=v.useCallback((E,R)=>{let x=E.filename;const D=xn(E);D&&!x.endsWith("/")&&(x=`${x}/`);let M=`${fe.getParent(x)}${R}`;D&&!M.endsWith("/")&&(M=`${M}/`),Os.debug2("handleRename",x,M),e.moveFile(x,M).catch(g),i(x,M)},[g,i,e]),S=v.useCallback(async(E,R)=>{if(R===E.basename)return;fe.validateName(R);const x=`${fe.getPath(E.filename)}${R}`;try{const D=await e.info(x);throw new ol(D)}catch(D){if(!(D instanceof Jr))throw D}},[e]),T=d.length>0,y=v.useMemo(()=>d.length===1?`Are you sure you want to delete "${d[0].filename}"?`:"Are you sure you want to delete the selected files?",[d]);return r.jsxs("div",{className:"file-explorer",children:[u&&r.jsx(Vu,{isMultiSelect:t,focusedPath:n,showContextMenu:!0,onMove:b,onDelete:p,onRename:w,onSelect:o,onSelectionChange:l,rowHeight:a,table:u,validateRename:S}),r.jsx(oo,{isOpen:T,headerText:y,bodyText:"You cannot undo this action.",onCancel:f,onConfirm:C,confirmButtonText:"Delete"})]})}ed.displayName="FileExplorer";const As=ne.module("NewItemModal");class to extends v.PureComponent{static propTypes={isOpen:z.bool,title:z.string.isRequired,defaultValue:z.string,type:z.oneOf(["file","directory"]).isRequired,onSubmit:z.func,onCancel:z.func,placeholder:z.string,storage:z.shape({}).isRequired,notifyOnExtensionChange:z.bool};static defaultProps={isOpen:!1,defaultValue:"/",notifyOnExtensionChange:!1,placeholder:"",onSubmit:(e,t)=>{},onCancel:()=>{}};static getValidationMessage(e){return e instanceof ol&&e.info.type==="directory"?"Error: Cannot overwrite existing directory":`${e}`}static handleError(e){ye.isCanceled(e)||As.error(e)}constructor(e){super(e),this.handleModalSubmit=this.handleModalSubmit.bind(this),this.handleModalOpened=this.handleModalOpened.bind(this),this.handleSelect=this.handleSelect.bind(this),this.handleChange=this.handleChange.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleValidationError=this.handleValidationError.bind(this),this.handleOverwriteCancel=this.handleOverwriteCancel.bind(this),this.handleOverwriteConfirm=this.handleOverwriteConfirm.bind(this),this.handleExtensionChangeCancel=this.handleExtensionChangeCancel.bind(this),this.handleExtensionChangeConfirm=this.handleExtensionChangeConfirm.bind(this),this.handleBreadcrumbSelect=this.handleBreadcrumbSelect.bind(this);const{defaultValue:t}=e,n=fe.hasPath(t)?fe.getPath(t):"/";this.state={isSubmitting:!1,path:n,prevExtension:fe.getExtension(t),showExtensionChangeModal:!1,showOverwriteModal:!1,value:fe.getBaseName(t)}}componentDidUpdate(e,t){const{isOpen:n}=this.props,{isOpen:s}=e,{value:i,path:o}=this.state;!s&&n&&(this.resetValue(),this.isInitialLoad=!0),s&&n&&(!this.isInitialLoad&&(o!==t.path||i!==t.value)&&this.updateValidationStatus(o,i),this.isInitialLoad=!1)}componentWillUnmount(){this.pending.cancel(),this.cancelableValidatePromise&&this.cancelableValidatePromise.cancel(),this.cancelableExistingItemPromise&&this.cancelableExistingItemPromise.cancel()}inputRef=de.createRef();cancelableValidatePromise;cancelableExistingItemPromise;pending=new Yn;pathMap=new Map;isInitialLoad=!0;resetValue(){const{defaultValue:e}=this.props,t=fe.hasPath(e)?fe.getPath(e):"/";this.setState({path:t,value:fe.getBaseName(e),validationError:void 0,prevExtension:fe.getExtension(e),isSubmitting:!1})}getValidationPromise(e,t,n=!1){return this.cancelableValidatePromise&&this.cancelableValidatePromise.cancel(),this.cancelableValidatePromise=ye.makeCancelable(this.validateName(e,t,n)),this.cancelableValidatePromise}async validateName(e,t,n){fe.validateName(t);const{defaultValue:s,storage:i}=this.props;if(n){const o=`${e}${t}`;if(o!==s)try{const l=await i.info(o);throw new ol(l)}catch(l){if(!(l instanceof Jr))throw l}}return t}updateValidationStatus(e,t){this.getValidationPromise(e,t).then(()=>{this.setState({validationError:void 0})}).catch(this.handleValidationError).catch(to.handleError)}handleModalOpened(){this.focusRenameInput()}handleModalSubmit(){this.submitModal()}handleChange(e){const{value:t}=e.target;this.setState({value:t})}handleSelect(e){if(As.debug("handleSelect",e),e.type==="directory")this.setState({path:fe.makePath(e.filename)});else{const t=e.basename,n=fe.getPath(e.filename);this.setState({value:t,path:n},()=>{this.focusRenameInput()})}}handleKeyDown(e){const{key:t}=e;switch(e.stopPropagation(),t){case"Enter":{e.preventDefault(),this.submitModal();break}case"Escape":{e.preventDefault();const{onCancel:n}=this.props;n();break}}}handleValidationError(e){if(!(e instanceof vi))throw e;As.debug("Validation error",e),this.setState({validationError:e})}handleOverwriteCancel(){this.setState({showOverwriteModal:!1,isSubmitting:!1})}handleOverwriteConfirm(){this.setState({showOverwriteModal:!1});const{onSubmit:e}=this.props,{path:t,value:n}=this.state;As.debug("handleOverwriteConfirm",t,n),e(`${t}${n}`,!0)}handleExtensionChangeCancel(){As.debug("handleExtensionChangeCancel"),this.setState(({value:e,prevExtension:t})=>({showExtensionChangeModal:!1,value:fe.replaceExtension(e,t)})),this.submitModal(!0)}handleExtensionChangeConfirm(){As.debug("handleExtensionChangeConfirm"),this.setState({showExtensionChangeModal:!1}),this.submitModal(!0)}focusRenameInput(){const e=this.inputRef.current;if(e){const{type:t}=this.props,{value:n}=e,s=t==="directory"?n.length:n.lastIndexOf(".");e.focus(),e.setSelectionRange(0,s>0?s:n.length)}}submitModal(e=!1){this.setState(({prevExtension:t,value:n,path:s})=>{const{notifyOnExtensionChange:i,type:o}=this.props;As.debug("submitModal",t,n);const l=fe.getExtension(n);return i&&!e&&t!==null&&t!==l?{isSubmitting:!1,showExtensionChangeModal:!0,newExtension:l}:(this.getValidationPromise(s,n,!0).then(a=>{const{onSubmit:d}=this.props;d(`${s}${n}`)}).catch(a=>{if(a instanceof ol&&o!=="directory"&&a.info.type!=="directory"){this.setState({showOverwriteModal:!0});return}throw a}).catch(a=>{throw ye.isCanceled(a)&&this.setState({isSubmitting:!1}),a}).catch(this.handleValidationError).catch(to.handleError),{isSubmitting:!0,showExtensionChangeModal:!1,newExtension:void 0})})}handleBreadcrumbSelect(e){this.setState({path:e})}renderPathButtons(e){const t=e.split("/");return t.pop(),t.map((n,s)=>{let i="";for(let o=0;o<s;o+=1)i+=`${t[o]}/`;return i+=`${n}/`,r.jsxs(de.Fragment,{children:[r.jsx(B,{kind:"ghost",className:"directory-breadcrumbs",onClick:()=>this.handleBreadcrumbSelect(i),"aria-label":s===0?"Home":void 0,icon:s===0?r.jsx(ee,{icon:Gg,transform:"right-1.6"}):void 0,tooltip:s===0?"Home":void 0,children:n}),"/"]},i)})}render(){const{storage:e,isOpen:t,onCancel:n,placeholder:s,title:i,type:o}=this.props,{isSubmitting:l,path:a,showExtensionChangeModal:d,showOverwriteModal:h,validationError:u,value:m,prevExtension:g,newExtension:p}=this.state,C=o==="directory",f=fe.fileExtensionToString(g),b=fe.fileExtensionToString(p),w=C?"Create":"Save",S=C?"New folder name":"Save file as";return r.jsxs(r.Fragment,{children:[r.jsxs(Gl,{isOpen:t,toggle:n,onOpened:this.handleModalOpened,className:"modal-dialog-centered new-file-modal theme-bg-dark",children:[r.jsx(zl,{toggle:n,children:i}),r.jsx(Kl,{children:r.jsx("form",{children:r.jsxs("div",{className:"d-flex flex-column new-file-modal-content",children:[r.jsxs("div",{className:"flex-grow-0 mb-4",children:[r.jsx("label",{htmlFor:"file-name-input",children:S}),r.jsx("input",{id:"file-name-input",type:"text",autoComplete:"off",autoCapitalize:"none",autoCorrect:"off",spellCheck:"false",className:Y("form-control",{"is-invalid":u}),value:m,placeholder:s,ref:this.inputRef,onKeyDown:this.handleKeyDown,onChange:this.handleChange}),u&&r.jsx("div",{className:"invalid-feedback",children:to.getValidationMessage(u)})]}),r.jsxs("div",{className:"flex-grow-0",children:[r.jsx("label",{children:"Directory: /"}),this.renderPathButtons(a)]}),r.jsx("div",{className:"flex-grow-1 file-explorer-container",children:r.jsx(ed,{onSelect:this.handleSelect,storage:e,focusedPath:a})})]})})}),r.jsxs(Yc,{children:[r.jsx(B,{kind:"secondary",onClick:n,children:"Cancel"}),r.jsx(B,{kind:"primary",disabled:l,onClick:this.handleModalSubmit,children:w})]})]}),r.jsx(oo,{isOpen:h,headerText:"Confirm overwrite",bodyText:"File with this name already exists, are you sure you want to overwrite it?",onCancel:this.handleOverwriteCancel,onConfirm:this.handleOverwriteConfirm,cancelButtonText:"Cancel",confirmButtonText:"Overwrite"}),r.jsx(oo,{isOpen:d,headerText:"Confirm extension change",bodyText:`Are you sure you want to change extension from "${f}" to "${b}"?`,onCancel:this.handleExtensionChangeCancel,onConfirm:this.handleExtensionChangeConfirm,cancelButtonText:`Keep "${f}"`,confirmButtonText:`Use "${b}"`})]})}}const $u=to;function oR({createFile:c,createFolder:e,onSearchChange:t,defaultSearchText:n=""}){return r.jsxs("div",{className:"file-explorer-toolbar",children:[r.jsxs("div",{className:"file-explorer-toolbar-buttons",children:[r.jsx(B,{kind:"ghost",icon:Jc,tooltip:"New notebook",onClick:c,"aria-label":"New notebook"}),r.jsx(B,{kind:"ghost",icon:zg,tooltip:"New folder",onClick:e,"aria-label":"New folder"})]}),t&&r.jsx("div",{className:"file-explorer-toolbar-search",children:r.jsx(Bm,{value:n,onChange:t,placeholder:"Search by name"})})]})}const ci=ne.module("FileExplorerPanel"),lR=(c,e)=>{const t=vh(c),n=Qs(c,e.localDashboardId),{session:s,config:i}=n??{},o=i?.type;return{fileStorage:t,language:o,session:s}},aR=St(lR,null,null,{forwardRef:!0});function rR(c){const e=c;return e!=null&&typeof e.button=="number"}class Fl extends de.Component{static COMPONENT="FileExplorerPanel";static TITLE="File Explorer";static handleError(e){ci.error(e)}static isFocusEvent(e){return rR(e)?e.detail>=2:!0}constructor(e){super(e),this.handleFileSelect=this.handleFileSelect.bind(this),this.handleCreateFile=this.handleCreateFile.bind(this),this.handleCreateDirectory=this.handleCreateDirectory.bind(this),this.handleCreateDirectoryCancel=this.handleCreateDirectoryCancel.bind(this),this.handleCreateDirectorySubmit=this.handleCreateDirectorySubmit.bind(this),this.handleDelete=this.handleDelete.bind(this),this.handleRename=this.handleRename.bind(this),this.handleSessionOpened=this.handleSessionOpened.bind(this),this.handleSessionClosed=this.handleSessionClosed.bind(this),this.handleShow=this.handleShow.bind(this),this.handleSelectionChange=this.handleSelectionChange.bind(this);const{session:t,language:n}=e;this.state={isShown:!1,language:n,session:t,showCreateFolder:!1,focusedFilePath:"/"}}componentDidMount(){this.isHidden()||this.setState({isShown:!0})}handleCreateFile(){const{glEventHub:e}=this.props,{session:t,language:n}=this.state,s={language:n,value:""};ci.debug("handleCreateFile",t,n,s),e.emit(Ue.CREATE_NOTEBOOK,t,n,s)}handleCreateDirectory(e){this.setState({showCreateFolder:!0})}handleCreateDirectoryCancel(){ci.debug("handleCreateDirectoryCancel"),this.setState({showCreateFolder:!1})}handleCreateDirectorySubmit(e){ci.debug("handleCreateDirectorySubmit",e),this.setState({showCreateFolder:!1});const{fileStorage:t}=this.props;t.createDirectory(e).catch(Fl.handleError)}handleDelete(e){const{glEventHub:t}=this.props;e.forEach(n=>{t.emit(Ue.CLOSE_FILE,{id:n.filename,itemName:n.filename})})}handleSelectionChange(e){let t="/";e.length===1&&(e[0].type==="directory"?t=fe.makePath(e[0].filename):t=fe.getPath(e[0].filename)),this.setState({focusedFilePath:t})}handleFileSelect(e,t){if(ci.debug("fileSelect",e),e.type==="directory")return;const n=Fl.isFocusEvent(t),s={id:e.filename,itemName:e.filename},{glEventHub:i}=this.props,{session:o,language:l}=this.state,a={value:null,language:l};i.emit(Ue.SELECT_NOTEBOOK,o,l,a,s,n)}handleRename(e,t){const{glEventHub:n}=this.props;ci.debug("handleRename",e,t),n.emit(Ue.RENAME_FILE,e,t)}handleSessionOpened(e,{language:t}){this.setState({session:e,language:t})}handleSessionClosed(){this.setState({session:void 0,language:void 0})}handleShow(){this.setState({isShown:!0})}isHidden(){const{glContainer:e}=this.props,{isHidden:t}=e;return t}render(){const{fileStorage:e,glContainer:t,glEventHub:n}=this.props,{isShown:s,showCreateFolder:i,focusedFilePath:o}=this.state;return r.jsxs(qn,{className:"file-explorer-panel",componentPanel:this,glContainer:t,glEventHub:n,onSessionOpen:this.handleSessionOpened,onSessionClose:this.handleSessionClosed,onShow:this.handleShow,children:[r.jsx(oR,{createFile:this.handleCreateFile,createFolder:this.handleCreateDirectory}),s&&r.jsx(ed,{isMultiSelect:!0,storage:e,onDelete:this.handleDelete,onRename:this.handleRename,onSelect:this.handleFileSelect,onSelectionChange:this.handleSelectionChange}),r.jsx($u,{isOpen:i,type:"directory",title:"Create New Folder",storage:e,onSubmit:this.handleCreateDirectorySubmit,onCancel:this.handleCreateDirectoryCancel,defaultValue:o})]})}}const dR=aR(Fl),Nl=dR;const it=ne.module("FilterSetManager"),cR="Enter name...",bc="No Available Filter Sets";class kl extends v.Component{static animateScreenFlash(){const e=document.createElement("div");e.classList.add("screen-flash-overlay"),e.addEventListener("animationend",()=>{e.remove()}),document.querySelector("body")?.appendChild(e)}constructor(e){super(e),this.handleSettingsCancel=this.handleSettingsCancel.bind(this),this.handleSettingsClick=this.handleSettingsClick.bind(this),this.handleSettingsSave=this.handleSettingsSave.bind(this),this.handleBackgroundClick=this.handleBackgroundClick.bind(this),this.handleEditDropdownChange=this.handleEditDropdownChange.bind(this),this.handleFilterChange=this.handleFilterChange.bind(this),this.handleFilterApply=this.handleFilterApply.bind(this),this.handleCaptureNewSet=this.handleCaptureNewSet.bind(this),this.handleNameInputChange=this.handleNameInputChange.bind(this),this.handleNameInputKeyPress=this.handleNameInputKeyPress.bind(this),this.handleRenameConfirm=this.handleRenameConfirm.bind(this),this.handleRenameCancel=this.handleRenameCancel.bind(this),this.handleRestoreFullStateChange=this.handleRestoreFullStateChange.bind(this),this.handleSetDelete=this.handleSetDelete.bind(this),this.handleSetEdit=this.handleSetEdit.bind(this),this.handleSetUpdate=this.handleSetUpdate.bind(this),this.state={editId:void 0,renameSet:void 0,nameInputValue:"",nameInputError:void 0,modifiedFilterSets:[],restoreFullState:!1}}componentDidMount(){const{isValueShown:e}=this.props;e?this.updateSelectedId():this.initSettingsScreen()}componentDidUpdate(e,t){const{isValueShown:n,filterSets:s}=this.props,{modifiedFilterSets:i}=this.state;if(e.isValueShown&&!n&&this.initSettingsScreen(),this.isNameInputScreen()&&!this.isNameInputScreen(t)&&this.focusRenameInput(),s!==e.filterSets)if(!n&&s.length>0&&e.filterSets.length===0&&i.length===0){const{onChange:o}=this.props;o({isValueShown:!0,selectedId:s[0].id})}else this.updateSelectedId()}renameInputRef=de.createRef();dropdownRef=de.createRef();editDropdownRef=de.createRef();initSettingsScreen(){const{filterSets:e,selectedId:t}=this.props;it.debug("initSettingsScreen",e,t),this.setState({modifiedFilterSets:[...e],editId:t})}updateSelectedId(){const{isValueShown:e,filterSets:t,selectedId:n,onChange:s}=this.props;if(it.debug("updateSelectedId",t,n),!!e&&!t.some(({id:i})=>i===n)){const i=t.length===0;s({isValueShown:!i,selectedId:i?void 0:t[0].id})}}handleEditDropdownChange(e){const{value:t}=e.target;this.setState({editId:t})}handleFilterChange(e){const{value:t}=e.target,{isValueShown:n,onChange:s}=this.props;this.applyFilterSet(t),s({isValueShown:n,selectedId:t})}handleFilterApply(){const{selectedId:e}=this.props;this.applyFilterSet(e)}handleSettingsCancel(){const{onChange:e,selectedId:t,filterSets:n}=this.props;this.setState({modifiedFilterSets:[]}),n.length>0&&e({isValueShown:!0,selectedId:t})}handleSettingsSave(){const{onChange:e,onUpdateSets:t}=this.props,{modifiedFilterSets:n,editId:s}=this.state;this.setState({modifiedFilterSets:[]}),it.debug("Update sets",n,s),t(n),n.length>0&&e({isValueShown:!0,selectedId:s})}handleCaptureNewSet(){const{getFilterState:e}=this.props;kl.animateScreenFlash();const t=qe(),n=e(),s={id:t,title:"",panels:n};it.debug("handleSetCreate",s),this.setState({nameInputValue:"",nameInputError:void 0,renameSet:s})}handleRenameCancel(){this.setState({renameSet:void 0})}handleRestoreFullStateChange(e){this.setState({restoreFullState:e.target.value==="true"})}getNameError(e){const{renameSet:t,modifiedFilterSets:n}=this.state,s=e?.trim()??"";if(s.length===0)return it.debug("Name cannot be empty",s),"Name cannot be empty";if(t!==void 0&&n.some(({title:i,id:o})=>i===s&&o!==t.id))return it.debug("Set with this name already exists",s),"Set with this name already exists"}handleRenameConfirm(){const{nameInputValue:e,renameSet:t,modifiedFilterSets:n,restoreFullState:s}=this.state;if(t===void 0){it.error("Renamed set undefined.");return}const i=this.getNameError(e);if(it.debug("handleRenameConfirm",e,i),i!==void 0){this.setState({nameInputError:i});return}const o=e?.trim()??"",l={...t,title:o,restoreFullState:s},a=n.findIndex(({id:h})=>h===t.id),d=[...n];a>=0?(d[a]=l,it.debug("Renamed existing set",d)):(d.push(l),it.debug("Added new set to modified sets",d)),this.setState({editId:l.id,modifiedFilterSets:d,renameSet:void 0})}handleSetDelete(){this.setState(e=>{const{editId:t,modifiedFilterSets:n}=e,s=n.findIndex(({id:a})=>a===t);if(s<0)return it.error("Unable to find selected filterSet index",n,t),null;const i=n.filter(({id:a})=>a!==t),o=Math.max(0,Math.min(i.length-1,s-1)),l=i.length>0?i[o].id:void 0;return it.debug("Deleted selected set",t,n,i),it.debug("New selection",o,l),{modifiedFilterSets:i,editId:l}})}handleSetUpdate(){const{getFilterState:e}=this.props;kl.animateScreenFlash();const t=e();this.setState(({modifiedFilterSets:n,editId:s})=>{if(s===void 0)return it.error("Filter for update not selected."),null;const i=[...n],o=i.findIndex(({id:l})=>l===s);return o<0?(it.error("Selected set for update not found."),null):(i[o]={...i[o],panels:t},it.debug("Update set",i,t),{modifiedFilterSets:i})})}handleSetEdit(){this.setState(({editId:e,modifiedFilterSets:t})=>{const n=t.find(({id:o})=>o===e);if(n===void 0)return it.error("Could not find selected set",e,t),null;const{title:s,restoreFullState:i=!1}=n;return{nameInputValue:s,nameInputError:void 0,renameSet:n,restoreFullState:i}})}handleSettingsClick(e){e.stopPropagation();const{onChange:t,selectedId:n}=this.props;t({isValueShown:!1,selectedId:n})}handleBackgroundClick(e){it.debug("handleBackgroundClick"),e.target!==this.dropdownRef.current&&this.focusInput()}handleNameInputChange(e){const{value:t}=e.target,n=this.getNameError(t);this.setState({nameInputValue:t,nameInputError:n})}handleNameInputKeyPress(e){const{key:t}=e;t==="Enter"&&(e.preventDefault(),this.handleRenameConfirm())}isNameInputScreen(e=this.state){const{renameSet:t}=e;return t!==void 0}isRenamingExistingSet=ge((e,t)=>t!==void 0&&e.some(({id:n})=>n===t.id));applyFilterSet(e){const{onApply:t,filterSets:n}=this.props;if(e===void 0){it.debug("No filter selected");return}const s=n.find(({id:i})=>i===e);if(s===void 0){it.debug("Selected id not found in filterSets",e,n);return}it.debug("Apply filterSet",s),t(s)}focusInput(){this.dropdownRef.current?.focus()}focusRenameInput(){this.renameInputRef.current?.focus()}render(){const{nameInputValue:e,nameInputError:t,editId:n,renameSet:s,modifiedFilterSets:i,restoreFullState:o}=this.state,{isValueShown:l,filterSets:a,selectedId:d}=this.props,h=this.isNameInputScreen(),u=this.isRenamingExistingSet(i,s),m=i.length===0,g=!h&&m&&a.length===0,p=!h&&!g,C=r.jsxs("div",{className:"fa-layers mr-3",children:[r.jsx(ee,{icon:Ri,mask:Ua,transform:"shrink-1 down-5 right-7"}),r.jsx(ee,{icon:Es,className:"text-primary",transform:"shrink-6 down-5 right-7"})]}),f=r.jsxs("div",{className:"fa-layers",children:[r.jsx(ee,{icon:Ri,mask:Ua,transform:"shrink-1 down-5 right-7"}),r.jsx(ee,{icon:Va,transform:"shrink-1 down-5 right-7"})]});return r.jsx("div",{className:"filter-set-manager fill-parent-absolute",children:r.jsxs(ar,{className:"w-100 h-100",isFlipped:l,children:[r.jsx("div",{className:"filter-set-manager-settings-card fill-parent-absolute",children:r.jsxs("div",{className:"filter-set-manager-card-content",children:[g&&r.jsxs("div",{children:[r.jsx(B,{kind:"ghost",className:"btn btn-link no-underline",onClick:this.handleCaptureNewSet,icon:C,children:"Capture filter set"}),r.jsx("div",{className:"py-3 text-muted small",children:"Takes a snapshot of the currently applied filters on all panels, allowing you to restore saved filter sets later."})]}),h&&r.jsxs("div",{className:"d-flex flex-column justify-content-center","data-testid":"edit-filter-set-container",children:[r.jsxs("div",{className:"form-group",children:[r.jsx("label",{children:u?"Edit set":"Name captured set"}),r.jsxs("div",{className:"name-input-container",children:[r.jsx("input",{type:"text",className:"input-set-name form-control",placeholder:cR,value:e,ref:this.renameInputRef,onChange:this.handleNameInputChange,onKeyPress:this.handleNameInputKeyPress,spellCheck:"false"}),r.jsx(B,{"data-testid":"rename-confirm-button",kind:"ghost",className:"btn btn-link no-underline pt-2 pb-2",onClick:this.handleRenameConfirm,tooltip:"Save","test-id":"button-save",icon:oh}),r.jsx(B,{"data-testid":"rename-cancel-button",kind:"ghost",className:"btn btn-link no-underline pt-2 pb-2",onClick:this.handleRenameCancel,tooltip:"Cancel",icon:Kg})]}),t!==void 0&&r.jsx("div",{className:"error-message",children:t})]}),r.jsx("div",{className:"form-group",children:r.jsxs(Ul,{onChange:this.handleRestoreFullStateChange,value:`${o}`,children:[r.jsx(Wn,{value:"false",children:"Restore only filters"}),r.jsx(Wn,{value:"true",children:"Restore full table state"})]})})]}),p&&r.jsxs("div",{className:"filter-set-manager-settings-grid-1",children:[r.jsxs("div",{className:"form-group",children:[r.jsx("label",{children:"Edit filter sets"}),r.jsxs("div",{className:"filter-select-container",children:[r.jsxs("select",{"data-testid":"settings-card-filter-select",ref:this.editDropdownRef,value:n??"-1",className:"custom-select filter-value-select",onChange:this.handleEditDropdownChange,disabled:m,children:[m&&r.jsx("option",{value:"-1",disabled:!0,children:bc}),i.map(({id:b,title:w})=>r.jsx("option",{value:b,children:w},b))]}),r.jsx(B,{kind:"ghost",onClick:this.handleSetUpdate,disabled:m,icon:f,tooltip:"Update"}),r.jsx(B,{kind:"ghost",onClick:this.handleSetEdit,disabled:m,icon:go,tooltip:"Edit"}),r.jsx(B,{kind:"ghost",onClick:this.handleSetDelete,disabled:m,icon:Gt,tooltip:"Delete"})]})]}),r.jsx("div",{children:r.jsx(B,{kind:"ghost",className:"btn btn-link no-underline",onClick:this.handleCaptureNewSet,icon:C,children:"Capture new filter set"})}),r.jsxs("div",{className:"py-3 text-right",children:[r.jsx(B,{kind:"secondary",onClick:this.handleSettingsCancel,children:"Cancel"})," ",r.jsx(B,{kind:"primary",onClick:this.handleSettingsSave,children:"Save"})]})]})]})},"front"),r.jsxs("div",{className:"filter-set-manager-value-card fill-parent-absolute",onClick:this.handleBackgroundClick,children:[r.jsx("div",{className:"filter-set-manager-column",children:r.jsx("div",{className:"filter-set-manager-column-title",children:"Filter sets"})}),r.jsx("div",{className:"filter-set-manager-card-content",children:r.jsx("div",{className:"filter-set-manager-value-input",children:r.jsxs("div",{className:"filter-select-container",children:[r.jsxs("select",{"data-testid":"value-card-filter-select",ref:this.dropdownRef,value:d,className:"custom-select filter-value-select",onChange:this.handleFilterChange,children:[a.length===0&&r.jsx("option",{value:"-1",disabled:!0,children:bc}),a.map(({id:b,title:w})=>r.jsx("option",{value:b,children:w},b))]}),r.jsx(B,{"data-testid":"filter-apply-button",kind:"ghost",onClick:this.handleFilterApply,icon:hr,tooltip:"Apply Filter Set"})]})})}),r.jsx("div",{className:"filter-set-manager-menu",children:r.jsx(B,{kind:"ghost",className:"btn btn-link btn-link-icon m-2 px-2",onClick:this.handleSettingsClick,tooltip:"Settings",icon:r.jsx(ee,{icon:mo,transform:"grow-4"})})})]},"back")]})})}}const hR=kl;function td(c){const{model:e,widgetName:t,glContainer:n,description:s}=c,i=(e?.rowCount??0)-(e?.pendingRowCount??0),o=e?.displayString(i,"long");return r.jsx(ia,{widgetType:"Table",widgetName:t,glContainer:n,description:s,children:r.jsxs("div",{className:"column-statistics-grid",children:[r.jsx("span",{className:"column-statistic-operation",children:"Number of Rows"}),r.jsx("span",{className:"column-statistic-value",children:o})]})})}td.propTypes={glContainer:kr.Container.isRequired,widgetName:z.string.isRequired,description:z.string};td.defaultProps={description:null};const Sn=ne.module("IrisGridPanel"),uR=500,mR={IrisGrid:Au,IrisGridTableModel:_u,ContextMenuRoot:qc};class tr extends v.PureComponent{static defaultProps={onStateChange:()=>{},onPanelStateUpdate:()=>{}};static displayName="IrisGridPanel";static COMPONENT="IrisGridPanel";constructor(e){super(e),this.handleAdvancedSettingsChange=this.handleAdvancedSettingsChange.bind(this),this.handleColumnsChanged=this.handleColumnsChanged.bind(this),this.handleTableChanged=this.handleTableChanged.bind(this),this.handleColumnSelected=this.handleColumnSelected.bind(this),this.handleDataSelected=this.handleDataSelected.bind(this),this.handleError=this.handleError.bind(this),this.handleGridStateChange=this.handleGridStateChange.bind(this),this.handlePluginStateChange=this.handlePluginStateChange.bind(this),this.handlePartitionAppend=this.handlePartitionAppend.bind(this),this.handleCreateChart=this.handleCreateChart.bind(this),this.handleResize=this.handleResize.bind(this),this.handleShow=this.handleShow.bind(this),this.handleTabClicked=this.handleTabClicked.bind(this),this.handleDisconnect=this.handleDisconnect.bind(this),this.handleReconnect=this.handleReconnect.bind(this),this.handleLoadSuccess=this.handleLoadSuccess.bind(this),this.handleLoadError=this.handleLoadError.bind(this),this.isColumnSelectionValid=this.isColumnSelectionValid.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.handlePluginFilter=this.handlePluginFilter.bind(this),this.handlePluginFetchColumns=this.handlePluginFetchColumns.bind(this),this.handleClearAllFilters=this.handleClearAllFilters.bind(this),this.irisGrid=de.createRef(),this.pluginRef=de.createRef();const{panelState:t}=e;this.pluginState=null,this.state={error:null,isDisconnected:!1,isLoaded:!1,isLoading:!0,isModelReady:!1,model:void 0,advancedFilters:new Map,aggregationSettings:{aggregations:[],showOnTop:!1},advancedSettings:new Map(yu.DEFAULTS),customColumns:[],customColumnFormatMap:new Map,isFilterBarShown:!1,quickFilters:new Map,sorts:[],userColumnWidths:new Map,userRowHeights:new Map,reverseType:F.REVERSE_TYPE.NONE,movedColumns:[],movedRows:[],isSelectingPartition:!1,partition:void 0,partitionColumn:void 0,rollupConfig:void 0,showSearchBar:!1,searchValue:"",selectedSearchColumns:void 0,invertSearchColumns:!0,Plugin:void 0,pluginFilters:[],pluginFetchColumns:[],modelQueue:[],pendingDataMap:new Map,frozenColumns:void 0,panelState:t,irisGridStateOverrides:{},gridStateOverrides:{},isStuckToBottom:!1,isStuckToRight:!1,conditionalFormats:[],selectDistinctColumns:[]}}componentDidMount(){this.initModel()}componentDidUpdate(e,t){const{model:n}=this.state;n!==t.model&&(t.model!=null&&(this.stopModelListening(t.model),t.model.close()),n!=null&&this.startModelListening(n))}componentWillUnmount(){this.savePanelState.cancel(),this.modelPromise!=null&&(this.modelPromise.cancel(),this.modelPromise=void 0);const{model:e}=this.state;e&&(this.stopModelListening(e),e.close())}irisGrid;pluginRef;modelPromise;irisGridState;gridState;pluginState;getTableName(){const{metadata:e}=this.props;return e.table}getGridInputFilters=ge((e,t)=>Se.getInputFiltersForColumns(e,t.filter(({value:n,excludePanelIds:s})=>{const i=K.getIdFromPanel(this);return n!=null&&(s==null||i!=null&&!s.includes(i))})));getAlwaysFetchColumns=ge((e,t)=>{const n=K.getIdFromPanel(this),s=new Set(t);for(let i=0;i<e.length;i+=1){const{start:o}=e[i];o!=null&&o.panelId===n&&s.add(o.columnName)}return[...s]});getPluginContent=ge((e,t,n,s,i)=>!t||!Ks(t)||e==null||t.table==null?null:r.jsx("div",{className:"iris-grid-plugin",children:r.jsx(e,{ref:this.pluginRef,filter:this.handlePluginFilter,onFilter:this.handlePluginFilter,fetchColumns:this.handlePluginFetchColumns,onFetchColumns:this.handlePluginFetchColumns,table:t.table,user:n,panel:this,workspace:s,components:mR,onStateChange:this.handlePluginStateChange,pluginState:i})}));getDehydratedIrisGridPanelState=ge((e,t,n,s,i)=>Se.dehydrateIrisGridPanelState(e,{isSelectingPartition:t,partition:n,partitionColumn:s,advancedSettings:i}));getDehydratedIrisGridState=ge((e,t,n,s,i,o,l,a,d,h,u,m,g,p,C,f,b,w,S,T,y)=>Se.dehydrateIrisGridState(e,{advancedFilters:n,aggregationSettings:b,customColumnFormatMap:s,isFilterBarShown:i,metrics:{userColumnWidths:C,userRowHeights:f},quickFilters:o,customColumns:l,reverseType:a,rollupConfig:d,showSearchBar:h,searchValue:u,selectDistinctColumns:m,selectedSearchColumns:g,sorts:t,invertSearchColumns:p,pendingDataMap:w,frozenColumns:S,conditionalFormats:T,columnHeaderGroups:y}));getDehydratedGridState=ge((e,t,n,s,i)=>Se.dehydrateGridState(e,{isStuckToBottom:s,isStuckToRight:i,movedColumns:t,movedRows:n}));getCachedPanelState=ge((e,t,n,s)=>({irisGridPanelState:e,irisGridState:t,gridState:n,pluginState:s}));initModel(){this.setState({isModelReady:!1,isLoading:!0,error:null});const{makeModel:e}=this.props;this.modelPromise!=null&&this.modelPromise.cancel(),this.modelPromise=ye.makeCancelable(e(),t=>t.close()),this.modelPromise.then(this.handleLoadSuccess).catch(this.handleLoadError)}handleLoadSuccess(e){const t=e,{panelState:n,irisGridStateOverrides:s}=this.state,i=[];if(n!=null){const{irisGridState:o}=n,{aggregationSettings:l,customColumns:a,selectDistinctColumns:d=[],rollupConfig:h}={...o,...s};a.length>0&&i.push(u=>{u.customColumns=a}),h!=null&&h.columns.length>0&&i.push(u=>{u.rollupConfig=Se.getModelRollupConfig(u.originalColumns,h,l)}),d.length>0&&i.push(u=>{u.selectDistinctColumns=d})}this.setState({model:t,modelQueue:i}),this.initModelQueue(t,i)}initModelQueue(e,t){const n=e;if(t.length===0){this.modelInitialized(n);return}const s=t.shift();Sn.debug("initModelQueue",s),s&&s(n),this.setState({modelQueue:t})}handleAdvancedSettingsChange(e,t){Sn.debug("handleAdvancedSettingsChange",e,t),this.setState(({advancedSettings:n})=>n.get(e)===t?null:{advancedSettings:new Map(n).set(e,t)})}handlePluginFilter(e){const{model:t}=this.state;N(t);const{columns:n,formatter:s}=t,i=Se.getFiltersFromInputFilters(n,e,s.timeZone);this.setState({pluginFilters:i})}handlePluginFetchColumns(e){this.setState({pluginFetchColumns:e})}handleContextMenu(e){return this.pluginRef.current?.getMenu?.(e)??[]}isColumnSelectionValid(e){const{columnSelectionValidator:t}=this.props;return t&&e?t(this,e):!1}handleGridStateChange(e,t){this.irisGridState=e,this.gridState=t,this.setState({isLoaded:!0,isLoading:!1}),this.savePanelState();const{glEventHub:n,onStateChange:s}=this.props;n.emit(cn.STATE_CHANGED,this),s?.(e,t)}handlePluginStateChange(e){const{irisGridState:t,gridState:n}=this;this.pluginState=e,t!==null&&n!==null&&this.savePanelState()}handleColumnsChanged(e){const{isModelReady:t,model:n,modelQueue:s}=this.state;t?this.sendColumnsChange(e.detail):(N(n),this.initModelQueue(n,s))}handleTableChanged(e){Sn.debug("handleTableChanged",e);const{glEventHub:t}=this.props,{detail:n}=e;t.emit(Ze.TABLE_CHANGED,this,n)}handlePartitionAppend(e,t){const{glEventHub:n}=this.props,{name:s}=e,i=this.getTableName(),o=`${i} = ${i}.where("${s}=\`${t}\`")`;n.emit($t.SEND_COMMAND,o,!1,!0)}handleCreateChart(e,t){this.savePanelState.flush(),this.setState(()=>null,()=>{const{glEventHub:n,inputFilters:s,metadata:i}=this.props,{table:o}=i,{panelState:l}=this.state,a=K.getIdFromPanel(this);let d;l&&(d=Se.extractTableSettings(l,s)),n.emit(cn.CREATE_CHART,{metadata:{settings:e,sourcePanelId:a,table:o,tableSettings:d},table:Ks(t)?t.table:void 0})})}handleColumnSelected(e){const{glEventHub:t}=this.props;t.emit(cn.COLUMN_SELECTED,this,e)}handleDataSelected(e,t){const{glEventHub:n}=this.props;n.emit(cn.DATA_SELECTED,this,t)}handleResize(){this.updateGrid()}handleShow(){this.updateGrid()}handleTabClicked(){this.irisGrid.current&&this.irisGrid.current.focus()}handleError(e){Sn.error(e),this.setState({error:e,isLoading:!1})}handleDisconnect(){this.setState({error:new Error("Table disconnected"),isDisconnected:!0,isLoading:!1})}handleReconnect(){this.setState({isDisconnected:!1,error:null})}handleLoadError(e){ye.isCanceled(e)||this.handleError(e)}modelInitialized(e){const{glEventHub:t,loadPlugin:n}=this.props;if(this.modelPromise=void 0,this.loadPanelState(e),this.setState({isModelReady:!0}),Ks(e)){const{table:s}=e,{pluginName:i}=s;if(i!==""&&n!=null&&i!=null){const o=n(i);this.setState({Plugin:o})}t.emit(Ze.TABLE_CHANGED,this,s)}this.sendColumnsChange(e.columns)}handleClearAllFilters(){const e=this.irisGrid.current,{isDisconnected:t}=this.state;e!=null&&!t&&e.clearAllFilters()}sendColumnsChange(e){Sn.debug2("sendColumnsChange",e);const{glEventHub:t}=this.props;t.emit(Ze.COLUMNS_CHANGED,this,e)}startModelListening(e){e.addEventListener(Ce.EVENT.DISCONNECT,this.handleDisconnect),e.addEventListener(Ce.EVENT.RECONNECT,this.handleReconnect),e.addEventListener(Ce.EVENT.COLUMNS_CHANGED,this.handleColumnsChanged),e.addEventListener(Ce.EVENT.TABLE_CHANGED,this.handleTableChanged)}stopModelListening(e){e.removeEventListener(Ce.EVENT.DISCONNECT,this.handleDisconnect),e.removeEventListener(Ce.EVENT.RECONNECT,this.handleReconnect),e.removeEventListener(Ce.EVENT.COLUMNS_CHANGED,this.handleColumnsChanged),e.removeEventListener(Ce.EVENT.TABLE_CHANGED,this.handleTableChanged)}getCoordinateForColumn(e){const{model:t}=this.state;if(!t)return null;const n=this.irisGrid.current,{gridWrapper:s}=n||{},i=s?.getBoundingClientRect()??null;if(i==null||i.width<=0||i.height<=0)return null;N(n);const{metrics:o}=n.state;N(o);const{columnHeaderHeight:l,allColumnXs:a,allColumnWidths:d,right:h,columnHeaderMaxDepth:u}=o,m=t.getColumnIndexByName(e);N(m);const g=n.getVisibleColumn(m),p=a.get(g)??0,C=d.get(g)??0,f=Math.max(i.left,Math.min(g>h?i.right:i.left+p+C*.5,i.right)),b=i.top+l*u;return[f,b]}setFilterMap(e){const t=this.irisGrid.current;t?.setFilterMap(e)}setAdvancedFilterMap(e){const t=this.irisGrid.current;t?.setAdvancedFilterMap(e)}setFilters({quickFilters:e,advancedFilters:t}){Sn.debug("setFilters",e,t);const{model:n,isDisconnected:s}=this.state,i=this.irisGrid.current;if(i==null||s){Sn.debug("Ignore setFilters, model disconnected");return}N(n);const{columns:o,formatter:l}=n,a=Se.changeFilterColumnNamesToIndexes(n.columns,e).filter(([h])=>n.isFilterable(h)),d=Se.changeFilterColumnNamesToIndexes(n.columns,t).filter(([h])=>n.isFilterable(h));i.clearAllFilters(),i.setFilters({quickFilters:Se.hydrateQuickFilters(o,a,l.timeZone),advancedFilters:Se.hydrateAdvancedFilters(o,d,l.timeZone)})}setStateOverrides(e){Sn.debug("setStateOverrides",e);const{irisGridState:t,gridState:n}=e;this.setState({irisGridStateOverrides:t,gridStateOverrides:n},()=>{this.initModel()})}unsetFilterValue(){}loadPanelState(e){const{panelState:t,irisGridStateOverrides:n,gridStateOverrides:s}=this.state;if(t!=null)try{const{gridState:i,irisGridState:o,irisGridPanelState:l}=t,a={...n},{quickFilters:d,advancedFilters:h}=a;d&&(a.quickFilters=Se.changeFilterColumnNamesToIndexes(e.columns,d)),h&&(a.advancedFilters=Se.changeFilterColumnNamesToIndexes(e.columns,h));const{isSelectingPartition:u,partition:m,partitionColumn:g,advancedSettings:p}=Se.hydrateIrisGridPanelState(e,l),{advancedFilters:C,customColumns:f,customColumnFormatMap:b,isFilterBarShown:w,quickFilters:S,reverseType:T,rollupConfig:y,aggregationSettings:E,sorts:R,userColumnWidths:x,userRowHeights:D,showSearchBar:M,searchValue:O,selectDistinctColumns:H,selectedSearchColumns:L,invertSearchColumns:V,pendingDataMap:U,frozenColumns:j,conditionalFormats:P,columnHeaderGroups:Q}=Se.hydrateIrisGridState(e,{...o,...a}),{isStuckToBottom:$,isStuckToRight:J,movedColumns:A,movedRows:W}=Se.hydrateGridState(e,{...i,...s},o.customColumns);this.setState({advancedFilters:C,advancedSettings:p,conditionalFormats:P,customColumns:f,customColumnFormatMap:b,isFilterBarShown:w,isSelectingPartition:u,movedColumns:A,movedRows:W,partition:m,partitionColumn:g,quickFilters:S,reverseType:T,rollupConfig:y,aggregationSettings:E,sorts:R,userColumnWidths:x,userRowHeights:D,showSearchBar:M,searchValue:O,selectDistinctColumns:H,selectedSearchColumns:L,invertSearchColumns:V,pendingDataMap:U,frozenColumns:j,isStuckToBottom:$,isStuckToRight:J,columnHeaderGroups:Q})}catch(i){Sn.error("loadPanelState failed to load panelState",t,i)}}savePanelState=Ye(()=>{const{irisGridState:e,gridState:t,pluginState:n}=this;N(e);const{onPanelStateUpdate:s}=this.props,{model:i,panelState:o,isSelectingPartition:l,partition:a,partitionColumn:d,advancedSettings:h}=this.state,{advancedFilters:u,aggregationSettings:m,customColumnFormatMap:g,isFilterBarShown:p,quickFilters:C,customColumns:f,reverseType:b,rollupConfig:w,showSearchBar:S,searchValue:T,selectDistinctColumns:y,selectedSearchColumns:E,sorts:R,invertSearchColumns:x,metrics:D,pendingDataMap:M,frozenColumns:O,conditionalFormats:H,columnHeaderGroups:L}=e;N(i),N(D);const{userColumnWidths:V,userRowHeights:U}=D;N(t);const{isStuckToBottom:j,isStuckToRight:P,movedColumns:Q,movedRows:$}=t,J=this.getCachedPanelState(this.getDehydratedIrisGridPanelState(i,l,a,d,h),this.getDehydratedIrisGridState(i,R,u,g,p,C,f,b,w,S,T,y,E,x,V,U,m,M,O,H,L),this.getDehydratedGridState(i,Q,$,j,P),n);J!==o&&(Sn.debug("Saving panel state",this,J),this.setState({panelState:J}),s?.(J))},uR);updateGrid(){const e=this.irisGrid.current?.grid??null;e&&e.handleResize()}render(){const{children:e,glContainer:t,glEventHub:n,columnSelectionValidator:s,getDownloadWorker:i,inputFilters:o,links:l,metadata:a,panelState:d,user:h,workspace:u,settings:m,theme:g}=this.props,{advancedFilters:p,aggregationSettings:C,advancedSettings:f,conditionalFormats:b,customColumns:w,customColumnFormatMap:S,error:T,isDisconnected:y,isFilterBarShown:E,isSelectingPartition:R,isStuckToBottom:x,isStuckToRight:D,isLoaded:M,isLoading:O,isModelReady:H,model:L,movedColumns:V,movedRows:U,partition:j,partitionColumn:P,quickFilters:Q,reverseType:$,rollupConfig:J,sorts:A,userColumnWidths:W,userRowHeights:q,showSearchBar:Z,searchValue:le,selectDistinctColumns:G,selectedSearchColumns:oe,invertSearchColumns:ue,Plugin:ae,pluginFilters:he,pluginFetchColumns:we,pendingDataMap:He,frozenColumns:Fe,columnHeaderGroups:mt}=this.state,et=T!=null?`Unable to open table. ${T}`:void 0,{table:De}=a,gt=L?.description??void 0,lt=d?.pluginState??null,vt=e??this.getPluginContent(ae,L,h,u,lt),{permissions:kt}=h,{canCopy:Cn,canDownloadCsv:zt}=kt;return r.jsx(Gr,{errorMessage:et,isDisconnected:y,isLoading:O,isLoaded:M,className:"iris-grid-panel",glContainer:t,glEventHub:n,onClearAllFilters:this.handleClearAllFilters,onResize:this.handleResize,onShow:this.handleShow,onTabFocus:this.handleShow,onTabClicked:this.handleTabClicked,widgetName:De,widgetType:"Table",description:gt,componentPanel:this,renderTabTooltip:()=>r.jsx(td,{model:L,widgetName:De,glContainer:t,description:gt}),children:H&&L&&r.jsx(Au,{advancedFilters:p,aggregationSettings:C,advancedSettings:f,alwaysFetchColumns:this.getAlwaysFetchColumns(l,we),columnAllowedCursor:"linker",columnNotAllowedCursor:"linker-not-allowed",customColumns:w,customColumnFormatMap:S,columnSelectionValidator:this.isColumnSelectionValid,conditionalFormats:b,inputFilters:this.getGridInputFilters(L.columns,o),applyInputFiltersOnInit:d==null,isFilterBarShown:E,isSelectingColumn:s!=null,isSelectingPartition:R,isStuckToBottom:x,isStuckToRight:D,movedColumns:V,movedRows:U,partition:j,partitionColumn:P,quickFilters:Q,reverseType:$,rollupConfig:J,settings:m,sorts:A,userColumnWidths:W,userRowHeights:q,model:L,showSearchBar:Z,searchValue:le,selectedSearchColumns:oe,selectDistinctColumns:G,invertSearchColumns:ue,onColumnSelected:this.handleColumnSelected,onCreateChart:this.handleCreateChart,onDataSelected:this.handleDataSelected,onError:this.handleError,onPartitionAppend:this.handlePartitionAppend,onStateChange:this.handleGridStateChange,onContextMenu:this.handleContextMenu,onAdvancedSettingsChange:this.handleAdvancedSettingsChange,customFilters:he,pendingDataMap:He,canCopy:Cn,canDownloadCsv:zt,ref:this.irisGrid,getDownloadWorker:i,frozenColumns:Fe,theme:g,columnHeaderGroups:mt,children:vt})})}}const gR=(c,{localDashboardId:e=un})=>({inputFilters:zr(c,e),links:Ni(c,e),columnSelectionValidator:qr(c,e),user:Sh(c),workspace:ql(c),settings:wt(c)}),pR=St(gR,null,null,{forwardRef:!0})(tr),qs=pR;const Sc=ne.module("InputFilter"),fR=150;class Ml extends v.Component{static PLACEHOLDER="Enter value...";static defaultProps={column:null,isValueShown:!1,value:null};constructor(e){super(e),this.handleColumnChange=this.handleColumnChange.bind(this),this.handleInputKeyPress=this.handleInputKeyPress.bind(this),this.handleValueChange=this.handleValueChange.bind(this),this.handleSettingsCancel=this.handleSettingsCancel.bind(this),this.handleSettingsClick=this.handleSettingsClick.bind(this),this.handleSettingsSave=this.handleSettingsSave.bind(this),this.handleBackgroundClick=this.handleBackgroundClick.bind(this),this.inputRef=de.createRef();const{column:t,isValueShown:n,value:s}=e;this.state={column:t,selectedColumn:t,value:s,isValueShown:n}}componentDidUpdate(e,t){const{column:n}=this.props,{column:s,value:i,isValueShown:o}=this.state;n!==e.column&&this.setState({column:n,selectedColumn:n}),o!==void 0&&o&&o!==t.isValueShown&&this.focusInput(),(s!==t.column||i!==t.value||o!==t.isValueShown)&&this.sendUpdate()}componentWillUnmount(){this.sendUpdate.flush()}inputRef;getItemLabel=Re((e,t)=>{const{name:n,type:s}=e[t];if(t>0&&e[t-1].name===n||t<e.length-1&&e[t+1].name===n){const i=s.substring(s.lastIndexOf(".")+1);return`${n} (${i})`}return n});handleColumnChange(e){const{columns:t}=this.props,{value:n}=e.target,s=t[parseInt(n,10)];Sc.debug2("handleColumnChange",s),this.setState({selectedColumn:s,value:void 0})}handleInputKeyPress(e){e.key==="Enter"&&(e.preventDefault(),e.stopPropagation(),this.setState(({value:t})=>t==null?{value:""}:null,()=>{this.sendUpdate(),this.sendUpdate.flush()}))}handleValueChange(e){const{value:t}=e.target;Sc.debug2("handleValueChange",t),this.setState({value:t})}handleSettingsCancel(){const{column:e}=this.state;this.setState({selectedColumn:e,isValueShown:!0})}handleSettingsSave(){const{selectedColumn:e}=this.state;this.setState({column:e,isValueShown:!0})}handleSettingsClick(e){const{column:t}=this.state;this.setState({selectedColumn:t,isValueShown:!1}),e.stopPropagation()}handleBackgroundClick(e){e.target!==this.inputRef.current&&this.focusInput()}focusInput(){this.inputRef.current!==null&&(this.inputRef.current.select(),this.inputRef.current.focus())}clearFilter(){this.setState({value:""})}setFilterState({name:e,type:t,value:n,isValueShown:s}){const i=e!=null&&t!=null?{name:e,type:t}:void 0,o=s===void 0?{column:i,value:n}:{column:i,value:n,isValueShown:s};this.setState(o)}sendUpdate=Ye(()=>{const{onChange:e}=this.props,{column:t,value:n,isValueShown:s}=this.state;e({column:t,isValueShown:s,value:n})},fR);render(){const{columns:e}=this.props,{column:t,isValueShown:n,selectedColumn:s,value:i}=this.state,o=i==null||i.length===0?Ml.PLACEHOLDER.length:i.length;let l=null;if(t!=null){const a=e.findIndex(d=>d.name===t.name&&d.type===t.type);l=a>=0?this.getItemLabel(e,a):t.name}return r.jsxs(ar,{className:"input-filter fill-parent-absolute",isFlipped:n??!1,children:[r.jsx("div",{className:"input-filter-settings-card",children:r.jsxs("div",{className:"input-filter-settings-content",children:[r.jsxs("div",{className:"input-filter-settings-grid",children:[r.jsx("label",{children:"Filter Column"}),r.jsxs("select",{value:e.findIndex(a=>a.name===s?.name&&a.type===s?.type),className:"custom-select",onChange:this.handleColumnChange,children:[e.map((a,d)=>r.jsx("option",{value:d,children:this.getItemLabel(e,d)},`${a.name}/${a.type}`)),e.length===0&&r.jsx("option",{value:"-1",disabled:!0,children:"No Available Columns"})]}),r.jsx("div",{className:"text-muted small",children:"Input filter control will apply its filter to all columns matching this name in this dashboard."})]}),r.jsxs("div",{className:"input-filter-settings-buttons",children:[r.jsx(B,{kind:"secondary",onClick:this.handleSettingsCancel,disabled:t==null,children:"Cancel"}),r.jsx(B,{kind:"primary",className:"ml-2",onClick:this.handleSettingsSave,disabled:s==null,children:"Save"})]})]})}),r.jsxs("div",{className:"input-filter-value-card",onClick:this.handleBackgroundClick,children:[r.jsx("div",{className:"input-filter-column",children:r.jsxs("div",{className:"input-filter-column-title",children:[l," Filter"]})}),r.jsx("div",{className:"d-flex justify-content-center align-items-center h-100 w-100",children:r.jsx("div",{className:"input-filter-value-input d-flex flex-column justify-content-center",children:r.jsx("input",{type:"text",ref:this.inputRef,placeholder:Ml.PLACEHOLDER,value:i??"",onChange:this.handleValueChange,onKeyPress:this.handleInputKeyPress,style:{width:`${o+3}ch`},spellCheck:"false"})})}),r.jsx("div",{className:"input-filter-menu",children:r.jsx(B,{kind:"ghost",className:"m-2 px-2",onClick:this.handleSettingsClick,icon:r.jsx(ee,{icon:mo,transform:"grow-4"}),tooltip:"Input Filter Settings"})})]})]})}}const CR=Ml,bR=250;class SR extends v.Component{static defaultProps={panelState:null};static COMPONENT="InputFilterPanel";static displayName="InputFilterPanel";constructor(e){super(e),this.handleChange=Ye(this.handleChange.bind(this),bR),this.handleClearAllFilters=this.handleClearAllFilters.bind(this),this.inputFilterRef=de.createRef();const{panelState:t}=e,{value:n,isValueShown:s=!1,name:i,type:o,timestamp:l}=t??{};this.state={columns:[],column:i!=null&&o!=null?{name:i,type:o}:void 0,value:n,timestamp:l,isValueShown:s,wasFlipped:!1,skipUpdate:!1,panelState:t}}componentDidMount(){this.updateColumns();const{column:e,value:t,timestamp:n}=this.state;if(e!=null){const{name:s,type:i}=e;this.sendUpdate(s,i,t,n)}}componentDidUpdate(e){const{columns:t}=this.props;t!==e.columns&&this.updateColumns()}inputFilterRef;handleChange({column:e,isValueShown:t=!1,value:n}){let s,i;e!=null&&({name:s,type:i}=e);let o=!0,l=Date.now();this.setState(({panelState:a,timestamp:d,wasFlipped:h,skipUpdate:u})=>{const m=a!=null&&t!==a.isValueShown&&s===a.name&&i===a.type&&n===a.value;return o=(!u&&t&&(!m||!h))??!1,o||(l=d),{panelState:{isValueShown:t,name:s,type:i,value:n,timestamp:l},timestamp:l,wasFlipped:m,skipUpdate:!1}},()=>{o&&this.sendUpdate(s,i,n,l)})}handleClearAllFilters(){this.inputFilterRef.current?.clearFilter()}sendUpdate(e,t,n,s){const{glEventHub:i}=this.props;i.emit(Ze.FILTERS_CHANGED,this,{name:e,type:t,value:n,timestamp:s})}setPanelState(e,t=!1){this.setState({skipUpdate:!t}),this.inputFilterRef.current?.setFilterState(e)}updateColumns(){const{columns:e}=this.props;e!=null&&this.setState(t=>{const{column:n}=t;return n==null&&e.length>0?{columns:[...e],column:e[0]}:n!=null&&!e.find(({name:s,type:i})=>n.name===s&&n.type===i)?{columns:[...e,n]}:{columns:[...e]}})}render(){const{glContainer:e,glEventHub:t}=this.props,{column:n,columns:s,isValueShown:i,value:o}=this.state;return r.jsx(qn,{className:"iris-input-filter-panel",componentPanel:this,glContainer:e,glEventHub:t,onClearAllFilters:this.handleClearAllFilters,isClonable:!0,isRenamable:!0,children:r.jsx(CR,{ref:this.inputFilterRef,column:n,columns:s,onChange:this.handleChange,isValueShown:i,value:o})})}}const wR=(c,e)=>{const{localDashboardId:t}=e;return{columns:ju(c,t)}},vR=St(wR,null,null,{forwardRef:!0})(SR),no=vR;const Et=ne.module("FilterSetManagerPanel");function TR(c){return c.setPanelState!=null}class Ll extends v.Component{static defaultProps={panelState:null};static COMPONENT="FilterSetManagerPanel";static changeFilterIndexesToColumnNames(e,t){return t.map(([n,s])=>{if(n>=e.columns.length)return null;const{name:i}=e.columns[n];return{name:i,filter:s}}).filter(n=>n!=null)}constructor(e){super(e),this.handleChange=this.handleChange.bind(this),this.handleFilterApply=this.handleFilterApply.bind(this),this.handleSetsUpdate=this.handleSetsUpdate.bind(this),this.handleGetFilterState=this.handleGetFilterState.bind(this);const{panelState:t,filterSets:n}=e,{selectedId:s=n.length>0?n[0].id:void 0,isValueShown:i=!1}=t??{};this.state={selectedId:s,isValueShown:i,panelState:t}}getFilterState(){const{dashboardOpenedPanelMap:e}=this.props,t=[];return[...e.keys()].forEach(n=>{const s=e.get(n);if(s===void 0){Et.error("Could not get panel",s);return}const i=K.getComponentNameFromPanel(s),o=K.getIdFromPanel(s);Et.debug("Panel:",s,i);const{glContainer:l=null}=s.props;if(l==null){Et.error("Could not get panel container",s);return}const a=K.getComponentConfigFromContainer(l);if(a==null){Et.error("Could not get component config from container",l);return}const d=K.getPanelComponentState(a);if(d==null){Et.debug(`Panel state is null ${o}`);return}switch(i){case K.getComponentName(tr):{let h;o!=null&&(h=this.getIrisGridPanelFilters(o,d)),h!=null&&t.push({panelId:o,type:i,state:h});break}case K.getComponentName(no):case K.getComponentName(Ys):{const{isValueShown:h,name:u,type:m,value:g}=d;t.push({panelId:o,type:i,state:{isValueShown:h,name:u,type:m,value:g}});break}}}),t}getIrisGridPanelFilters(e,t){const{panelTableMap:n}=this.props,s=n.get(e);if(s==null)return Et.error(`Unable to get table for panel ${e}.`),null;const{irisGridState:i={advancedFilters:void 0,quickFilters:void 0},gridState:o={}}=t,{advancedFilters:l,quickFilters:a}=i;let d;l&&(d=Ll.changeFilterIndexesToColumnNames(s,l));let h;return a&&(h=Ll.changeFilterIndexesToColumnNames(s,a)),{irisGridState:{...i,advancedFilters:d,quickFilters:h},gridState:{...o}}}handleGetFilterState(){return this.getFilterState()}handleChange({isValueShown:e,selectedId:t}){Et.debug("handleChange",e,t),this.setState({isValueShown:e,selectedId:t}),this.updatePanelState()}handleFilterApply(e){const{dashboardOpenedPanelMap:t}=this.props,{panels:n,restoreFullState:s=!1}=e;Et.debug("Apply filters from filter set",e),n.forEach(({panelId:i,type:o,state:l})=>{if(i==null){Et.debug("panel is null",i);return}if(!t.has(i)){Et.debug("Ignore closed panel",i);return}Et.debug("Apply panel filters",i,o,l);const a=t.get(i);switch(o){case K.getComponentName(tr):this.restoreIrisGridFilters(a,l,s);break;case K.getComponentName(no):case K.getComponentName(Ys):this.restoreInputFilterState(a,l);break}})}handleSetsUpdate(e){const{setDashboardFilterSets:t,localDashboardId:n}=this.props;Et.debug("Saving updated sets",e),t(n,[...e])}updatePanelState(){this.setState(({selectedId:e,isValueShown:t})=>({panelState:{selectedId:e,isValueShown:t}}))}restoreIrisGridFilters(e,t,n){const{irisGridState:s={},advancedFilters:i=[],quickFilters:o=[]}=t,{advancedFilters:l=i,quickFilters:a=o}=s,{panelTableMap:d}=this.props,h=K.getIdFromPanel(e);if(h==null){Et.error("Panel Id is null.");return}if(d.get(h)==null){Et.error(`Unable to get table for panel ${h}.`);return}Et.debug("restoreIrisGridFilters",h,t,n),n?e.setStateOverrides(t):e.setFilters({quickFilters:a,advancedFilters:l})}restoreInputFilterState(e,t){const n={...t};delete n.isValueShown,Et.debug("restoreInputFilterState",e,n),e&&TR(e)&&e.setPanelState(n)}render(){const{glContainer:e,glEventHub:t,filterSets:n}=this.props,{isValueShown:s,selectedId:i}=this.state;return r.jsx(qn,{className:"filter-set-manager-panel",componentPanel:this,glContainer:e,glEventHub:t,isClonable:!0,isRenamable:!0,children:r.jsx("div",{className:"input-filter-container h-100 w-100 container",children:r.jsx(hR,{onChange:this.handleChange,onApply:this.handleFilterApply,onUpdateSets:this.handleSetsUpdate,isValueShown:s,filterSets:n,selectedId:i,getFilterState:this.handleGetFilterState})})})}}const ER=(c,e)=>{const{localDashboardId:t}=e;return{filterSets:yy(c,t),dashboardOpenedPanelMap:au(c,t),dashboardInputFilters:zr(c,t),panelTableMap:Kr(c,t)}},yR=St(ER,{setDashboardFilterSets:My},null,{forwardRef:!0})(Ll),ka=yR;const wc=ne.module("LogPanel");class RR extends v.PureComponent{static defaultProps={session:null};static COMPONENT="LogPanel";static TITLE="Log";constructor(e){super(e),this.handleResize=this.handleResize.bind(this),this.handleShow=this.handleShow.bind(this),this.handleHide=this.handleHide.bind(this),this.handleSessionOpened=this.handleSessionOpened.bind(this),this.handleSessionClosed=this.handleSessionClosed.bind(this),this.isBottomVisible=!0,this.logView=null;const{session:t}=this.props;this.state={session:t}}isBottomVisible;logView;handleResize(){this.updateDimensions()}handleShow(){this.updateDimensions(),this.logView&&(this.logView.triggerFindWidget(),this.isBottomVisible&&this.logView.scrollToBottom())}handleHide(){this.logView&&(this.isBottomVisible=this.logView.isBottomVisible())}handleSessionOpened(e){wc.debug("Session opened",[e]),this.setState({session:e})}handleSessionClosed(e){wc.debug("Session closed",e)}updateDimensions(){this.logView&&this.logView.updateDimensions()}render(){const{glContainer:e,glEventHub:t}=this.props,{session:n}=this.state;return r.jsxs(qn,{componentPanel:this,glContainer:e,glEventHub:t,onResize:this.handleResize,onHide:this.handleHide,onShow:this.handleShow,onSessionOpen:this.handleSessionOpened,onSessionClose:this.handleSessionClosed,children:[n==null&&r.jsx("div",{className:"log-panel-disconnected-message",children:"Waiting for session connection"}),n!=null&&r.jsx(Qf,{session:n,ref:s=>{this.logView=s}})]})}}const xR=(c,e)=>({session:Qs(c,e.localDashboardId)?.session}),DR=St(xR,null,null,{forwardRef:!0})(RR),Ol=DR;class IR extends v.PureComponent{static defaultProps={isEditing:!1};render(){const{isEditing:e,children:t,onDoubleClick:n}=this.props;return r.jsxs("div",{className:"markdown-editor-container h-100 w-100",onDoubleClick:n,children:[r.jsx("div",{className:Y("text-muted","edit-hint",{viewing:e===void 0||!e}),children:r.jsxs("span",{children:["double-click to edit ",r.jsx(ee,{icon:go})]})}),t]})}}const FR=ne.module("MarkdownStartPage");class NR extends v.PureComponent{static defaultProps={closedMarkdowns:[],onOpen:()=>{},onCreate:()=>{},onDelete:()=>{}};constructor(e){super(e),this.handleDeleteButtonClick=this.handleDeleteButtonClick.bind(this),this.handleDeleteModalClose=this.handleDeleteModalClose.bind(this),this.state={isDeleteModalShown:!1}}handleDeleteButtonClick(e){this.setState({isDeleteModalShown:!0,toBeDeleted:e})}handleDeleteModalClose(){this.setState({isDeleteModalShown:!1,toBeDeleted:void 0})}handleDeleteMarkdown(e){if(FR.debug("delete markdown: ",e),e!==void 0){const{onDelete:t}=this.props;t(e)}this.setState({isDeleteModalShown:!1,toBeDeleted:void 0})}render(){const{closedMarkdowns:e,onOpen:t,onCreate:n}=this.props,{isDeleteModalShown:s,toBeDeleted:i}=this.state;return r.jsx("div",{className:"markdown-panel-start-page h-100 w-100",children:r.jsxs("div",{className:"markdown-panel-start-page-container",children:[r.jsxs("div",{className:"markdown-panel-start-list",children:[r.jsx("h3",{className:"list-title",children:"Start"}),r.jsx("div",{className:"list-item",children:r.jsx(B,{kind:"ghost",className:"title",onClick:n,children:"New Markdown Note"})})]}),r.jsxs("div",{className:"markdown-panel-start-list",children:[r.jsx("h3",{className:"list-title",children:"Recently Closed from Dashboard"}),e.map(o=>r.jsxs("div",{className:"list-item",children:[r.jsx(B,{kind:"ghost",className:"title",onClick:()=>t(o),children:o.title}),r.jsx("button",{className:"btn-link icon",type:"button",onClick:()=>{this.handleDeleteButtonClick(o)},children:r.jsx(ee,{icon:Gt})})]},o.id)),r.jsxs(Gl,{isOpen:s,toggle:this.handleDeleteModalClose,className:"modal-dialog-centered markdown-delete-modal theme-bg-light",children:[r.jsx(zl,{children:"Are you sure you want to permanently delete this note?"}),r.jsx(Kl,{children:"You can't undo this action."}),r.jsxs(Yc,{children:[r.jsx(B,{kind:"secondary",onClick:this.handleDeleteModalClose,children:"Cancel"}),r.jsx(B,{kind:"danger",onClick:()=>{this.handleDeleteMarkdown(i)},children:"Delete"})]})]})]})]})})}}const kR=NR,MR=c=>{const{children:e,className:t}=c,n=t!==void 0&&t?.startsWith("language-")?t.substring(9):"plaintext";return r.jsx("pre",{children:r.jsx("code",{children:r.jsx(Yl,{language:n,children:de.Children.map(e,s=>typeof s=="string"?s.trim():s)})})})};class LR extends v.PureComponent{static defaultProps={isEditing:!1,content:""};constructor(e){super(e),this.container=null}container;render(){const{isEditing:e,content:t,onEditorInitialized:n}=this.props;return r.jsx("div",{className:"markdown-editor-container",ref:s=>{this.container=s},children:e?r.jsx(br,{settings:{language:"markdown",value:t,lineNumbers:"off"},onEditorInitialized:n}):r.jsx(Vc,{components:{code:MR},children:t})})}}const Qo=ne.module("MarkdownPanel");class OR extends v.Component{static defaultProps={panelState:null};static COMPONENT="MarkdownPanel";constructor(e){super(e),this.handleContainerDoubleClick=this.handleContainerDoubleClick.bind(this),this.handleCreateMarkdown=this.handleCreateMarkdown.bind(this),this.handleDeleteMarkdown=this.handleDeleteMarkdown.bind(this),this.handleOpenMarkdown=this.handleOpenMarkdown.bind(this),this.handleEditorInitialized=this.handleEditorInitialized.bind(this),this.handleEditorBlur=this.handleEditorBlur.bind(this),this.handleEditorResize=this.handleEditorResize.bind(this);const{panelState:t}=e;let n=null;t!=null&&t.content!=null&&({content:n}=t),this.state={isStartPageShown:n==null,isEditing:!1,content:n,panelState:t},this.markdownEditor=null}markdownEditor;editor;setEditorPosition(e){N(this.markdownEditor);const{container:t}=this.markdownEditor;if(this.editor&&t){const n=t.getBoundingClientRect().top,s=t.scrollTop,i=t.scrollHeight,o=this.editor.getModel()?.getLineCount()??0;let l=Math.round((s+e-n)/i*o);l>o&&(l=o),this.editor.revealLine(l),this.editor.setPosition({lineNumber:l,column:1}),this.editor.focus()}}getClosedMarkdowns=ge(e=>e.filter(t=>t.component==="MarkdownPanel").reverse());handleContainerDoubleClick(e){const{isEditing:t}=this.state,n=e.clientY;t||this.setState({isEditing:!0},()=>{this.setEditorPosition(n)})}handleEditorInitialized(e){Qo.debug("Markdown Editor Initialized..."),this.editor=e}handleCreateMarkdown(){Qo.debug("create markdown..."),this.setState({isStartPageShown:!1,content:"",isEditing:!0,panelState:{content:""}},()=>{this.editor!=null&&this.editor.focus!=null&&this.editor.focus()})}handleOpenMarkdown(e){Qo.debug("open markdown...",e);const{glContainer:t,glEventHub:n}=this.props,s=K.getComponentConfigFromContainer(t);n.emit(Ee.REOPEN,e,s)}handleDeleteMarkdown(e){const{glEventHub:t}=this.props;t.emit(Ee.DELETE,e)}handleEditorBlur(e){Qo.debug("markdown content changed, saving...");const{isEditing:t}=this.state;if(!t||this.markdownEditor!=null&&this.markdownEditor.container!=null&&this.markdownEditor.container.contains(e.relatedTarget))return;const n=this.editor?.getValue();this.setState({content:n,isEditing:!1,panelState:{content:n}})}handleEditorResize(){const{isEditing:e}=this.state;e&&this.editor&&this.editor.layout()}render(){const{glContainer:e,glEventHub:t,closedPanels:n}=this.props,{isEditing:s,isStartPageShown:i,content:o}=this.state,l=this.getClosedMarkdowns(n);return r.jsx(qn,{glContainer:e,glEventHub:t,className:"markdown-panel",componentPanel:this,onResize:this.handleEditorResize,onBlur:this.handleEditorBlur,isClonable:!0,isRenamable:!0,children:i?r.jsx(kR,{closedMarkdowns:l,onCreate:this.handleCreateMarkdown,onOpen:this.handleOpenMarkdown,onDelete:this.handleDeleteMarkdown}):r.jsx(IR,{isEditing:s,onDoubleClick:this.handleContainerDoubleClick,children:r.jsx(LR,{ref:a=>{this.markdownEditor=a},isEditing:s,content:o??void 0,onEditorInitialized:this.handleEditorInitialized})})})}}const AR=(c,e)=>{const{localDashboardId:t}=e;return{closedPanels:CS(c,t)}},_R=St(AR,null,null,{forwardRef:!0})(OR),Wi=_R;class PR extends v.PureComponent{static defaultProps={onRunCode:()=>{}};constructor(e){super(e),this.handleRunSelected=this.handleRunSelected.bind(this),this.renderCodeBlock=this.renderCodeBlock.bind(this),this.renderLink=this.renderLink.bind(this),this.commands=new Map,this.codeElements=new Map,this.editorScrollView=de.createRef(),this.state={hasCode:!1,hasRunCode:!1,nextStartLine:null}}componentDidMount(){this.updateHasCode()}componentDidUpdate(){this.updateHasCode()}commands;codeElements;editorScrollView;updateHasCode(){const{hasCode:e}=this.state;this.commands.size===0&&e?this.setState({hasCode:!1}):this.commands.size>0&&!e&&this.setState({hasCode:!0})}getNextStartLine(e){const t=[...this.commands.keys()],n=t.findIndex(s=>s===e)+1;return n>=t.length?null:t[n]}handleRunSelected(e){e.preventDefault(),e.stopPropagation();const{nextStartLine:t}=this.state,n=[...this.commands.keys()],s=n.findIndex(h=>h===t||t==null);if(s<0)return;const i=n[s],o=this.commands.get(i),l=this.getNextStartLine(i),d=this.codeElements.get(i)?.current?.parentElement?.nextElementSibling;if(d!=null){const{offsetTop:h}=d,u=h;this.editorScrollView.current?.scroll({top:u,left:0})}this.runCode(o),this.setState({nextStartLine:l})}runCode(e){const{onRunCode:t}=this.props;t(e),this.setState({hasRunCode:!0})}renderCodeBlock(e){const{children:t,className:n,inline:s,node:i}=e,{hasRunCode:o,nextStartLine:l}=this.state,{children:a,position:d}=i;N(d);const{start:h}=d,{line:u}=h,m=a[0].value,g=de.createRef(),p=this.commands.size===0,C=l===u||p&&l==null&&!o,f=n!==void 0&&n.startsWith("language-")?n.substring(9):"plaintext";return s!=null&&s?r.jsx("code",{className:n,children:t}):(this.commands.set(u,m),this.codeElements.set(u,g),r.jsxs("div",{className:Y("markdown-notebook-code-block",{"is-selected":C}),ref:g,onClick:()=>{this.setState({nextStartLine:u})},role:"presentation",children:[r.jsx(B,{kind:"ghost",icon:rl,className:"btn-play-block",onClick:b=>{b.stopPropagation(),b.preventDefault(),this.runCode(m),this.setState({nextStartLine:u})},tooltip:"Run code"}),r.jsx("code",{children:r.jsx(Yl,{language:f,children:de.Children.map(t,b=>typeof b=="string"?b.trim():b)})})]}))}renderLink(e){const{onLinkClick:t}=this.props,{href:n,children:s,target:i}=e;return r.jsx("a",{href:n,onClick:t,target:i,children:s})}render(){const{content:e,transformImageUri:t,transformLinkUri:n}=this.props,{hasCode:s,hasRunCode:i,nextStartLine:o}=this.state;return r.jsxs("div",{className:"markdown-notebook",children:[r.jsx("div",{className:"markdown-notebook-toolbar",children:r.jsx(B,{className:Y("btn-play-selected-cell",{flashing:s&&!i}),kind:"ghost",icon:rl,onClick:this.handleRunSelected,tooltip:"Run code and select next",disabled:i&&o==null||!s,children:"Run Selected Code"})}),r.jsx("div",{className:"markdown-notebook-content",ref:this.editorScrollView,children:r.jsx(Vc,{components:{code:this.renderCodeBlock,a:this.renderLink},linkTarget:"_blank",remarkPlugins:[xm],transformLinkUri:n,transformImageUri:t,includeElementIndex:!0,children:e})})]})}}const jR=PR;const Pe=ne.module("NotebookPanel"),vc=400;class $s extends v.Component{static COMPONENT="NotebookPanel";static POPPER_OPTIONS={placement:"bottom-end"};static DEFAULT_NAME="Untitled";static handleError(e){ye.isCanceled(e)||Pe.error(e)}static defaultProps={isDashboardActive:!0,isPreview:!1,session:null,sessionLanguage:null,defaultNotebookSettings:null};static languageFromFileName(e){switch(fe.getExtension(e).toLowerCase()){case"py":case"python":return"python";case"groovy":return"groovy";case"scala":return"scala";default:return null}}constructor(e){super(e),this.handleBlur=this.handleBlur.bind(this),this.handleCloseCancel=this.handleCloseCancel.bind(this),this.handleCloseDiscard=this.handleCloseDiscard.bind(this),this.handleCloseSave=this.handleCloseSave.bind(this),this.handleCopy=this.handleCopy.bind(this),this.handleEditorInitialized=this.handleEditorInitialized.bind(this),this.handleEditorWillDestroy=this.handleEditorWillDestroy.bind(this),this.handleEditorChange=this.handleEditorChange.bind(this),this.handleFind=this.handleFind.bind(this),this.handleMinimapChange=this.handleMinimapChange.bind(this),this.handleWordWrapChange=this.handleWordWrapChange.bind(this),this.handleFocus=this.handleFocus.bind(this),this.handleLinkClick=this.handleLinkClick.bind(this),this.handleLoadSuccess=this.handleLoadSuccess.bind(this),this.handleLoadError=this.handleLoadError.bind(this),this.handleTabClick=this.handleTabClick.bind(this),this.handleRenameFile=this.handleRenameFile.bind(this),this.handleResize=this.handleResize.bind(this),this.handleRunCommand=this.handleRunCommand.bind(this),this.handleRunAll=this.handleRunAll.bind(this),this.handleRunSelected=this.handleRunSelected.bind(this),this.handleSave=this.handleSave.bind(this),this.handleSaveAsCancel=this.handleSaveAsCancel.bind(this),this.handleSaveAsSubmit=this.handleSaveAsSubmit.bind(this),this.handleSaveError=this.handleSaveError.bind(this),this.handleSaveSuccess=this.handleSaveSuccess.bind(this),this.handleSessionOpened=this.handleSessionOpened.bind(this),this.handleSessionClosed=this.handleSessionClosed.bind(this),this.handleShow=this.handleShow.bind(this),this.handleShowRename=this.handleShowRename.bind(this),this.handleTab=this.handleTab.bind(this),this.handleTabFocus=this.handleTabFocus.bind(this),this.handleTabBlur=this.handleTabBlur.bind(this),this.handleTransformLinkUri=this.handleTransformLinkUri.bind(this),this.handleOverwrite=this.handleOverwrite.bind(this),this.handlePreviewPromotion=this.handlePreviewPromotion.bind(this),this.getDropdownOverflowActions=this.getDropdownOverflowActions.bind(this),this.pending=new Yn,this.debouncedSavePanelState=Ye(this.savePanelState.bind(this),vc),this.debouncedLoad=Ye(this.load.bind(this),vc),this.notebook=null,this.tabTitleElement=null,this.tabInitOnce=!1;const{isDashboardActive:t,session:n,sessionLanguage:s,panelState:i}=e;let o={value:"",language:"",wordWrap:"off"},l=null,{isPreview:a}=e;i!=null&&({fileMetadata:l=l,isPreview:a=a,settings:o=o}=i);const d=l!=null&&fe.hasPath(l.itemName),u=d===!0&&o.value!=null||!d&&o.value!=null&&o.value.length>0?1:0;this.state={error:void 0,isDashboardActive:t,isFocused:!1,isLoading:!0,isLoaded:!1,isPreview:a,savedChangeCount:0,changeCount:u,fileMetadata:l,settings:o,session:n,sessionLanguage:s,panelState:{fileMetadata:l,settings:o},showCloseModal:!1,showSaveAsModal:!1,scriptCode:""},Pe.debug("constructor",e,this.state)}componentDidMount(){const{glContainer:e,glEventHub:t}=this.props,{tab:n}=e;n!=null&&this.initTab(n),this.initNotebookContent(),t.on(Ue.RENAME_FILE,this.handleRenameFile),e.on(Ue.PROMOTE_FROM_PREVIEW,this.handlePreviewPromotion)}componentDidUpdate(e,t){const{isPreview:n,settings:s}=this.state,{wordWrap:i}=s,{defaultNotebookSettings:o}=this.props;n!==t.isPreview&&this.setPreviewStatus(),i!==t.settings.wordWrap&&(this.updateEditorWordWrap(),this.debouncedSavePanelState()),o.isMinimapEnabled!==e.defaultNotebookSettings.isMinimapEnabled&&this.updateEditorMinimap()}componentWillUnmount(){this.debouncedSavePanelState.flush(),this.pending.cancel();const{glEventHub:e,glContainer:t}=this.props,{fileMetadata:n,isPreview:s}=this.state;e.off(Ue.RENAME_FILE,this.handleRenameFile),t.off(Ue.PROMOTE_FROM_PREVIEW,this.handlePreviewPromotion),e.emit(Ue.UNREGISTER_FILE,n,s)}pending;debouncedSavePanelState;debouncedLoad;notebook;tabTitleElement;tabInitOnce;editor;initTab(e){this.tabInitOnce||(this.tabInitOnce=!0,this.initTabCloseOverride()),this.initTabClasses(e)}initTabCloseOverride(){const{glContainer:e}=this.props;e.beforeClose(t=>{if(t?.force===!0)return!0;const{changeCount:n,savedChangeCount:s}=this.state;return n!==s?(this.setState({showCloseModal:!0}),!1):!0})}initTabClasses(e){const t=e.element.get(0);N(t);const n=t.querySelector(".lm_title");this.tabTitleElement=n,n?.classList.add("notebook-title"),this.setPreviewStatus()}getNotebookValue(){const{changeCount:e,savedChangeCount:t,settings:n}=this.state,{value:s}=n;if(e!==t&&this.notebook){const i=this.notebook.getValue();return i??s}return s}initNotebookContent(){const{fileMetadata:e,settings:t,isPreview:n}=this.state;if(e&&e.id){Pe.debug("Init content from file"),this.registerFileMetadata(e,n),this.load();return}if(t.value!=null){Pe.debug("Use content passed in the settings prop"),this.handleLoadSuccess();return}this.handleLoadError(new Error("Missing file metadata"))}closeFileTabById(e){const{glEventHub:t}=this.props;t.emit(Ue.CLOSE_FILE,{id:e})}registerFileMetadata(e,t){const{glEventHub:n,metadata:s}=this.props,{id:i}=s;n.emit(Ue.REGISTER_FILE,i,e,t)}renameTab(e,t){const{glEventHub:n}=this.props;n.emit(Ue.RENAME,e,t)}load(){const{fileMetadata:e,settings:t}=this.state;N(e);const{id:n}=e,{fileStorage:s}=this.props;this.pending.add(s.loadFile(n)).then(i=>{Pe.debug("Loaded file",i);const{filename:o}=i,{itemName:l}=this.state;if(o!==l){const{metadata:d}=this.props,{id:h}=d;this.renameTab(h,fe.getBaseName(o))}const a={...t,language:$s.languageFromFileName(o)??""};t.value==null&&(a.value=i.content),t.wordWrap===void 0&&(t.wordWrap="off"),this.setState({fileMetadata:{id:o,itemName:o},settings:a}),this.debouncedSavePanelState()}).then(this.handleLoadSuccess).catch(this.handleLoadError)}save(){const{fileMetadata:e}=this.state;if(e&&fe.hasPath(e.itemName)){const t=this.getNotebookValue();return t!==void 0?(this.saveContent(e.itemName,t),!0):!1}return this.setState({showSaveAsModal:!0}),!1}saveContent(e,t){Pe.debug("saveContent",e,t),this.updateSavedChangeCount();const{fileStorage:n}=this.props;this.pending.add(n.saveFile({filename:e,content:t,basename:e})).then(this.handleSaveSuccess).catch(this.handleSaveError)}updateSavedChangeCount(){this.setState(({changeCount:e})=>({savedChangeCount:e}))}setPreviewStatus(){if(!this.tabTitleElement)return;const{isPreview:e}=this.state;Pe.debug("setPreviewStatus",this.tabTitleElement,e),e?this.tabTitleElement.classList.add("is-preview"):this.tabTitleElement.classList.remove("is-preview")}handlePreviewPromotion(){this.removePreviewStatus()}getSettings=ge((e,t)=>({...e,minimap:{enabled:t}}));getOverflowActions=ge((e,t)=>[{title:"Find",icon:Yg,action:this.handleFind,group:ie.groups.high,shortcut:Nt.NOTEBOOK.FIND,order:10},{title:"Show Minimap",icon:e?zn:void 0,action:this.handleMinimapChange,group:ie.groups.medium,shortcut:Nt.NOTEBOOK.MINIMAP,order:20},{title:"Word Wrap",icon:t?zn:void 0,action:this.handleWordWrapChange,group:ie.groups.medium,shortcut:Nt.NOTEBOOK.WORDWRAP,order:30}]);savePanelState(){this.setState(e=>{const{changeCount:t,savedChangeCount:n,fileMetadata:s,isPreview:i,settings:o}=e,l=this.getNotebookValue(),a=t!==n?l:void 0,d={...o,value:l},u={settings:{...o,value:a},fileMetadata:s,isPreview:i};return Pe.debug("Saving panel state",u),{settings:d,panelState:u}})}handleCloseDiscard(){this.setState({showCloseModal:!1});const{glContainer:e}=this.props;e.close({force:!0})}handleCloseSave(){if(this.setState({showCloseModal:!1}),this.save()){const{glContainer:e}=this.props;e.close({force:!0})}}handleCloseCancel(){this.setState({showCloseModal:!1})}handleOverwrite(e){const{glEventHub:t}=this.props;t.emit(Ue.CLOSE_FILE,{id:e,itemName:e},{force:!0}),this.focus()}handleCopy(){const{fileMetadata:e,settings:t}=this.state;N(e);const n=this.getNotebookValue(),{language:s}=t,{itemName:i}=e,o=fe.getCopyFileName(i);Pe.debug("handleCopy",e,i,o),this.createNotebook(o,s,n)}handleEditorInitialized(e){this.editor=e}handleEditorWillDestroy(){this.editor=void 0}handleEditorChange(e){Pe.debug2("handleEditorChanged",e),this.removePreviewStatus(),this.setState(t=>{const{changeCount:n,savedChangeCount:s}=t,{isUndoing:i,isRedoing:o}=e;return i?{changeCount:n-1,savedChangeCount:s}:!o&&n<s?{changeCount:n+1,savedChangeCount:0}:{changeCount:n+1,savedChangeCount:s}}),this.debouncedSavePanelState()}handleFind(){this.notebook&&this.notebook.toggleFind()}updateEditorMinimap(){if(this.editor){const{defaultNotebookSettings:e}=this.props;this.editor.updateOptions({minimap:{enabled:e.isMinimapEnabled}})}}handleMinimapChange(){const{settings:e,defaultNotebookSettings:t,saveSettings:n}=this.props,s={...e,defaultNotebookSettings:{isMinimapEnabled:!t.isMinimapEnabled}};n(s)}updateEditorWordWrap(){if(this.editor){const{settings:e}=this.state,{wordWrap:t}=e;this.editor.updateOptions({wordWrap:t})}}handleWordWrapChange(){this.editor&&this.setState(e=>{const{settings:t}=e,n=t.wordWrap==="on"?"off":"on";return{settings:{...t,wordWrap:n}}})}handleBlur(){Pe.debug("handleBlur"),this.setState({isFocused:!1})}handleFocus(){Pe.debug("handleFocus"),this.setState({isFocused:!0})}handleLinkClick(e){const{notebooksUrl:t,session:n,sessionLanguage:s}=this.props,{href:i}=e.currentTarget;if(!i||!i.startsWith(t))return;e.stopPropagation(),e.preventDefault();const o=`/${i.substring(t.length)}`.replace(/%20/g," ");if(o==="/"){Pe.debug("Ignoring invalid notebook link",o);return}Pe.debug("Notebook link clicked, opening",o);const{glEventHub:l}=this.props,a={value:null,language:s},d={id:o,itemName:o};l.emit(Ue.SELECT_NOTEBOOK,n,s,a,d)}handleLoadSuccess(){this.setState({error:void 0,isLoaded:!0,isLoading:!1})}handleLoadError(e){let t=e;ye.isCanceled(t)||(ye.isTimedOut(t)&&(t=new Error("File not found.")),Pe.error(t),this.setState({error:t,isLoading:!1}))}handleSave(){Pe.debug("handleSave"),this.save()}handleSaveSuccess(e){const{fileStorage:t}=this.props,n={id:e.filename,itemName:e.filename},s=$s.languageFromFileName(e.filename)??"";this.setState(i=>{const{fileMetadata:o}=i,l={...i.settings,language:s};return Pe.debug("handleSaveSuccess",n,o,l),o&&fe.hasPath(o.itemName)&&o.itemName!==n.itemName&&(Pe.debug("handleSaveSuccess deleting old file",o.itemName),t.deleteFile(o.itemName).catch($s.handleError)),{fileMetadata:n,settings:l,isPreview:!1}}),this.debouncedSavePanelState(),this.registerFileMetadata(n,!1)}handleSaveError(e){ye.isCanceled(e)||(this.setState({savedChangeCount:0}),Pe.error(e))}handleSaveAsCancel(){this.setState({showSaveAsModal:!1})}handleSaveAsSubmit(e,t=!1){t&&this.handleOverwrite(e),Pe.debug("handleSaveAsSubmit",e);const{fileMetadata:n}=this.state;if(!n)return;const{itemName:s}=n,i=this.getNotebookValue()??"";if(this.setState({showSaveAsModal:!1}),fe.getBaseName(s)!==fe.getBaseName(e)){const{metadata:o}=this.props,{id:l}=o;this.renameTab(l,fe.getBaseName(e))}this.saveContent(e,i)}handleRenameFile(e,t,n){const{fileMetadata:s,panelState:i}=this.state,{glContainer:o}=this.props;if(s?.itemName===`/${t}`&&n&&JSON.stringify(i)!==JSON.stringify(n)){o.close();return}s&&s.id===e&&(this.setState({fileMetadata:{id:t,itemName:t}}),this.debouncedSavePanelState())}handleResize(){this.notebook?.updateDimensions()}handleRunCommand(e){this.runCommand(e)}handleRunAll(){if(!this.notebook){Pe.error("Editor is not initialized.");return}this.runCommand(this.notebook.getValue()??void 0)}handleRunSelected(){if(!this.notebook){Pe.error("Editor is not initialized.");return}this.runCommand(this.notebook.getSelectedCommand())}handleSessionOpened(e,{language:t}){this.setState({session:e,sessionLanguage:t})}handleSessionClosed(){this.setState({session:void 0,sessionLanguage:void 0})}handleShow(){Pe.debug("handleShow"),this.notebook?.updateDimensions()}handleShowRename(){this.setState({showSaveAsModal:!0})}handleTab(e){Pe.debug("NotebookPanel tab event",e),this.initTab(e)}handleTabFocus(...e){Pe.debug("handleTabFocus",...e);const{glContainer:t}=this.props;this.setState({isDashboardActive:!0}),this.notebook&&!t.isHidden&&this.notebook.updateDimensions()}handleTabBlur(){Pe.debug("handleTabBlur"),this.setState({isDashboardActive:!1})}handleTabClick(e){Pe.debug("handle NotebookPanel tab click"),this.focus(),e.detail===2&&this.removePreviewStatus()}handleTransformLinkUri(e){const{notebooksUrl:t}=this.props,{fileMetadata:n}=this.state;if(e.endsWith("/"))return e;if(e.startsWith("/"))return`${t}${e.substring(1)}`;let s=n?.itemName;if(s===void 0)return e;s.charAt(0)==="/"&&(s=s.substring(1));const i=new URL(s,t);return new URL(e,i).href}focus(){requestAnimationFrame(()=>{this.notebook&&this.notebook.focus()})}createNotebook(e,t,n=""){const{glEventHub:s}=this.props,{session:i,sessionLanguage:o,settings:l}=this.state,a={...l,language:t,value:n},d={id:null,itemName:e};Pe.debug("handleCreateNotebook",i,o,a,d),s.emit(Ue.CREATE_NOTEBOOK,i,o,a,d)}runCommand(e){if(e===void 0||e===""){Pe.debug("Ignoring empty command.");return}this.removePreviewStatus();const{glEventHub:t}=this.props;t.emit($t.SEND_COMMAND,e,!1,!0)}removePreviewStatus(){this.setState(({isPreview:e})=>{if(e){const{fileMetadata:t}=this.state;return t&&this.registerFileMetadata(t,!1),{isPreview:!1}}return null})}getDropdownOverflowActions(){const{defaultNotebookSettings:e}=this.props,{settings:t}=this.state;return this.getOverflowActions(e.isMinimapEnabled,this.getSettings(t,e.isMinimapEnabled).wordWrap==="on")}render(){const{fileStorage:e,glContainer:t,glContainer:{tab:n},glEventHub:s,defaultNotebookSettings:i}=this.props,{changeCount:o,savedChangeCount:l,error:a,isDashboardActive:d,isLoaded:h,isLoading:u,isPreview:m,fileMetadata:g,session:p,sessionLanguage:C,settings:f,showCloseModal:b,showSaveAsModal:w}=this.state,S=d&&!t.isHidden&&!m,T=g?.itemName??$s.DEFAULT_NAME,y=T.endsWith(".md"),E=g?.id!=null,R=this.getSettings(f,i.isMinimapEnabled),x=p!=null,D=C===R.language,M=!h||!x||!D,O=!h,H=[{action:this.handleSave,shortcut:Kn.SAVE},{action:this.handleMinimapChange,shortcut:Nt.NOTEBOOK.MINIMAP},{action:this.handleWordWrapChange,shortcut:Nt.NOTEBOOK.WORDWRAP}],L=Ld.getDisabledRunTooltip(x,D,"Notebook extension","Run"),V=Ld.getDisabledRunTooltip(x,D,"Notebook extension","Run Selected"),U=[{title:E?"Rename":"Save As…",order:10,group:ie.groups.high,action:this.handleShowRename},{title:"Copy File",action:this.handleCopy,group:ie.groups.high,order:20}],j=n?.element.find(".lm_title_before").get(0);return r.jsxs(r.Fragment,{children:[j&&al.createPortal(r.jsx("span",{className:Y("editor-unsaved-indicator",{"is-unsaved":o!==l})}),j),r.jsxs(qn,{className:"notebook-container",componentPanel:this,glContainer:t,glEventHub:s,onTab:this.handleTab,onResize:this.handleResize,onShow:this.handleShow,onTabClicked:this.handleTabClick,onTabFocus:this.handleTabFocus,onTabBlur:this.handleTabBlur,onSessionOpen:this.handleSessionOpened,onSessionClose:this.handleSessionClosed,onFocus:this.handleFocus,onBlur:this.handleBlur,additionalActions:U,renderTabTooltip:()=>T,children:[!y&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"notebook-toolbar",children:[r.jsxs("span",{children:[r.jsx(B,{kind:"ghost",className:"btn-play",onClick:this.handleRunAll,disabled:M,icon:r.jsx(ee,{icon:rl,transform:"grow-4"}),tooltip:`Run ${Nt.NOTEBOOK.RUN.getDisplayText()}`,"aria-label":"Run"}),L!=null&&r.jsx(ot,{children:L})]}),r.jsxs("span",{children:[r.jsx(B,{kind:"ghost",className:"btn-play",onClick:this.handleRunSelected,disabled:M,icon:r.jsx(ee,{icon:qg,transform:"grow-4"}),tooltip:`Run Selected ${Nt.NOTEBOOK.RUN_SELECTED.getDisplayText()}`,"aria-label":"Run Selected"}),V!=null&&r.jsx(ot,{children:V})]}),r.jsx(B,{kind:"ghost",className:"mr-auto",disabled:O,onClick:this.handleSave,icon:oh,tooltip:`Save ${Kn.SAVE.getDisplayText()}`,"aria-label":"Save"}),r.jsx(B,{kind:"ghost",className:"btn-overflow btn-link-icon",disabled:O,icon:Qc,tooltip:"More Actions...",onClick:()=>{},children:r.jsx(Vn,{actions:this.getDropdownOverflowActions,popperOptions:$s.POPPER_OPTIONS})})]}),r.jsx(jf,{isLoaded:h,isLoading:u,error:a,onChange:this.handleEditorChange,onRunCommand:this.handleRunCommand,session:p,sessionLanguage:C,onEditorInitialized:this.handleEditorInitialized,onEditorWillDestroy:this.handleEditorWillDestroy,settings:R,focusOnMount:S,ref:P=>{this.notebook=P}})]}),y&&r.jsx(jR,{content:R.value??"",onLinkClick:this.handleLinkClick,onRunCode:this.handleRunCommand,transformImageUri:this.handleTransformLinkUri,transformLinkUri:this.handleTransformLinkUri}),r.jsx($u,{isOpen:w,type:"file",defaultValue:T,title:E?"Rename":"Save file as",onSubmit:this.handleSaveAsSubmit,onCancel:this.handleSaveAsCancel,notifyOnExtensionChange:!0,storage:e}),r.jsx(oo,{isOpen:b,headerText:`Do you want to save the changes you made to ${T}?`,bodyText:"Your changes will be lost if you don't save them.",onCancel:this.handleCloseCancel,onDiscard:this.handleCloseDiscard,onConfirm:this.handleCloseSave,discardButtonText:"Discard Changes",confirmButtonText:"Save"}),r.jsx(ie,{actions:H})]})]})}}const HR=(c,e)=>{const t=vh(c),n=wt(c),s=CC(c),i=Qs(c,e.localDashboardId),{session:o,config:l}=i??{},{type:a}=l??{};return{fileStorage:t,settings:n,defaultNotebookSettings:s,session:o,sessionLanguage:a}},BR=St(HR,{saveSettings:Zl},null,{forwardRef:!0})($s),ds=BR;class UR extends v.Component{static defaultProps={panelState:null};static COMPONENT="PandasPanel";constructor(e){super(e),this.irisGridRef=de.createRef(),this.buttonRef=de.createRef(),this.handleReload=this.handleReload.bind(this),this.handleGridStateChange=this.handleGridStateChange.bind(this),this.handlePanelStateUpdate=this.handlePanelStateUpdate.bind(this);const{panelState:t}=e;this.state={shouldFocusGrid:!1,panelState:t}}buttonRef;irisGridRef;handleReload(){this.irisGridRef.current?.initModel(),this.buttonRef.current?.blur(),this.setState({shouldFocusGrid:!0})}handleGridStateChange(){const{shouldFocusGrid:e}=this.state;e&&this.irisGridRef.current?.irisGrid?.current?.grid&&(this.irisGridRef.current.irisGrid.current.grid.focus(),this.setState({shouldFocusGrid:!1}))}handlePanelStateUpdate(e){this.setState({panelState:e})}render(){const{...e}=this.props;return r.jsx(qs,{ref:this.irisGridRef,onStateChange:this.handleGridStateChange,onPanelStateUpdate:this.handlePanelStateUpdate,...e,children:r.jsxs(B,{ref:this.buttonRef,kind:"primary",className:"btn-pandas",onClick:this.handleReload,tooltip:"Click to refresh pandas dataframe, updates do not occur automatically.",children:["pandas dataframe",r.jsxs("span",{children:[r.jsx(ee,{icon:hr,transform:"shrink-1",className:"mr-1"}),"Reload"]})]})})}}const Ma=UR;function VR(c){ys(c);const{id:e,layout:t,registerComponent:n,hydrate:s}=c,i=v.useCallback(({dragEvent:o,fetch:l,panelId:a=qe.generate(),widget:d})=>{const{name:h,type:u}=d;if(u!==dh.VariableType.FIGURE)return;const m={name:h,figure:h},g=()=>l().then(f=>fl.makeModel(void 0,f)),p={type:"react-component",component:Ei.COMPONENT,props:{localDashboardId:e,id:a,metadata:m,makeModel:g},title:h,id:a},{root:C}=t;K.openComponent({root:C,config:p,dragEvent:o})},[e,t]);return v.useEffect(function(){const l=[n(Ei.COMPONENT,Ei,s)];return()=>{l.forEach(a=>a())}},[s,n]),Ve(t.eventHub,Ee.OPEN,i),null}function $R(c){ys(c);const{id:e,layout:t}=c,n=v.useCallback(({metadata:s,panelId:i=qe.generate(),table:o})=>{const{settings:l}=s,a=()=>fl.makeModelFromSettings(l,o),d=Qe.titleFromSettings(l),h={type:"react-component",component:Ei.COMPONENT,props:{localDashboardId:e,id:i,metadata:s,makeModel:a},title:d,id:i},{root:u}=t;K.openComponent({root:u,config:h})},[e,t]);return Ve(t.eventHub,cn.CREATE_CHART,n),null}const at=ne.module("ConsolePlugin");function Tc(c){return c.notebook!==void 0}function WR(c){ys(c)}function GR(c){WR(c);const{id:e,hydrateConsole:t,layout:n,panelManager:s,registerComponent:i,notebooksUrl:o}=c,l=v.useRef(0),[a,d]=v.useState(new Map),[h,u]=v.useState(new Map),m=ir(),g=v.useCallback(()=>s.getLastUsedPanelOfType(Ci),[s]),p=v.useCallback((A,W)=>{d(q=>new Map(q.set(A,W)))},[d]),C=v.useCallback(A=>{d(W=>(W.delete(A),new Map(W)))},[d]),f=v.useCallback((A,W)=>{u(q=>new Map(q.set(A,W)))},[u]),b=v.useCallback(A=>{u(W=>(W.delete(A),new Map(W)))},[u]),w=v.useCallback((A,W=!0,q=!0)=>{if(!(A&&A.trim()))at.info("Ignoring empty code");else{const le=g();if(!le||!(le instanceof Ci.WrappedComponent)){at.error("Console panel not found");return}at.debug("Send command: ",A,W,q),le.addCommand(A,W,q)}},[g]),S=v.useCallback(A=>{m(ky(e,A))},[m,e]),T=v.useCallback(({language:A})=>{const W=A==="python"?"py":A;let q=null;return W==null?(at.debug("No extension for language",A),q=`Untitled-${l.current}`):q=`Untitled-${l.current}.${W}`,l.current+=1,q},[]),y=v.useCallback((A,W=!0)=>{const{id:q}=A;if(q!=null&&a.has(q))return a.get(q);if(q!=null&&h.has(q))return h.get(q);if(W)return qe.generate()},[a,h]),E=v.useCallback((A,W)=>{K.renameComponent(n.root,{id:A},W)},[n.root]),R=v.useCallback((A,W)=>{at.debug("Rename file panel",A,W);let q;if(a.has(A)&&(q=a.get(A),C(A),q!=null&&p(W,q)),h.has(A)&&(q=h.get(A),b(A),q!=null&&f(W,q)),q===void 0){at.debug2(`File ${A} isn't open, no need to rename the tab`);return}E(q,fe.getBaseName(W))},[a,h,E,p,f,C,b]),x=v.useCallback(A=>{const W=y(A,!1);if(W==null){at.error("Could not find panel id for file metadata",A);return}K.activateTab(n.root,{id:W})},[y,n.root]),D=v.useCallback((A,W,q)=>{if(at.debug("registerFilePanel",A,W,q),W==null||W.id==null){at.debug("Ignore empty file id",W);return}const{id:Z}=W;if(q){f(Z,A);return}if(a.has(Z)){const le=a.get(Z);if(A===le){at.debug(`Update tab title for file ${Z}`);const{itemName:G}=W;R(Z,G)}else at.error(`File ${Z} already associated with a different tab ${le}`);return}p(Z,A),h.has(Z)&&b(Z)},[a,h,R,p,f,b]),M=v.useCallback((A,W)=>{if(at.debug("unregisterFileTab",A,W),A==null||A.id==null){at.debug("Ignore empty file id",A);return}const{id:q}=A;if(W){b(q);return}C(q)},[C,b]),O=v.useCallback((A,W)=>{at.debug("closeFilePanel",A);const{id:q}=A;let Z=null,le=!1;if(a.has(q))Z=a.get(q);else if(h.has(q))Z=h.get(q),le=!0;else{at.debug(`File ${q} isn't open, ignore close event`);return}M(A,le),K.closeComponent(n.root,{id:Z},W)},[n.root,a,h,M]),H=v.useCallback(A=>{const{itemName:W}=A;return fe.getBaseName(W)},[]),L=v.useCallback(A=>{const{id:W}=A;return at.debug("fileIsOpen",A,W,a),W!=null&&a.has(W)},[a]),V=v.useCallback(A=>{const{id:W}=A;return at.debug("fileIsOpenAsPreview",A,W,h),W!=null&&h.has(W)},[h]),U=v.useCallback(A=>{if(A==null)return;const W=s.getOpenedPanelById(A);W&&Tc(W)&&W.focus()},[s]),j=v.useCallback(({id:A,settings:W,fileMetadata:q,session:Z,sessionLanguage:le,isPreview:G=!1})=>{const oe={settings:W,fileMetadata:q},ue=H(q);return{type:"react-component",component:ds.COMPONENT,isFocusOnShow:!1,props:{localDashboardId:e,metadata:{id:A},session:Z,sessionLanguage:le,panelState:oe,isPreview:G,notebooksUrl:o},title:ue,id:A}},[H,e,o]),P=v.useCallback((A,W,q,Z={id:null,itemName:T(q)})=>{const le=y(Z);if(L(Z)&&le!=null){at.debug("File is already open, focus panel"),x(Z),U(le);return}const G=K.getStackForComponentTypes(n.root,[ds.COMPONENT]),oe=j({id:le,settings:q,fileMetadata:Z,session:A,sessionLanguage:W});at.debug("createNotebook",oe,a),K.openComponentInStack(G,oe)},[L,U,T,y,n.root,j,a,x]),Q=v.useCallback((A,W,q,Z,le=!1)=>{at.debug("selectNotebook",Z,le);const G=L(Z),oe=V(Z),[ue]=[...h.values()],ae=!le,he=ae&&ue?ue:y(Z);if(he==null||he==="")throw new Error("Unable to retrieve or create panelId for metadata",Z);if(G||oe)x(Z);else{const we=K.getStackForComponentTypes(n.root,[ds.COMPONENT]),He=j({id:he,settings:q,fileMetadata:Z,session:A,sessionLanguage:W,isPreview:ae});K.openComponentInStack(we,He)}if(oe&&le){const we=Z.id,He=K.getStackForConfig(n.root,{component:ds.COMPONENT,id:he}),Fe=K.getContentItemInStack(He,{component:ds.COMPONENT,id:he});Fe&&Bt(Fe)&&(Fe.container.emit(Ue.PROMOTE_FROM_PREVIEW),b(we),p(we,he))}le&&U(he)},[x,L,V,U,y,n.root,j,h,b,p]),$=v.useCallback((A,W,q={},Z=!0)=>{const le=s.getLastUsedPanelOfType(ds);le&&Tc(le)?q!=null&&q.value!=null&&le.notebook!=null&&le.notebook.append(q.value):Z&&P(A,W,q)},[P,s]),J=v.useCallback((A,W)=>qa.hydrate({...A,notebooksUrl:o},W),[o]);return v.useEffect(function(){const W=[i(Ci.COMPONENT,Ci,t),i(Il.COMPONENT,Il),i(Nl.COMPONENT,Nl),i(Ol.COMPONENT,Ol),i(ds.COMPONENT,ds,J)];return()=>{W.forEach(q=>q())}},[i,t,J]),Ve(n.eventHub,$t.SEND_COMMAND,w),Ve(n.eventHub,$t.SETTINGS_CHANGED,S),Ve(n.eventHub,Ue.CLOSE_FILE,O),Ve(n.eventHub,Ue.CREATE_NOTEBOOK,P),Ve(n.eventHub,Ue.SELECT_NOTEBOOK,Q),Ve(n.eventHub,Ue.RENAME,E),Ve(n.eventHub,Ue.RENAME_FILE,R),Ve(n.eventHub,Ue.SEND_TO_NOTEBOOK,$),Ve(n.eventHub,Ue.REGISTER_FILE,D),Ve(n.eventHub,Ue.UNREGISTER_FILE,M),null}const Gi=ne.module("FilterPlugin");function Ec(c,e){return c.concat(e)}function zR(c){ys(c);const{id:e,layout:t,registerComponent:n}=c,s=ir(),[i]=v.useState(()=>new Map),[o]=v.useState(()=>new Map),[l]=v.useState(()=>new Map),a=v.useCallback(()=>{const f=Array.from(i.values()).reduce(Ec,[]).sort((S,T)=>{const y=en.toLower(S.name),E=en.toLower(T.name);if(y!==E)return y>E?1:-1;const R=en.toLower(S.type),x=en.toLower(T.type);return R!==x?R>x?1:-1:0}).reduce((S,T)=>((S.length===0||en.toLower(S[S.length-1].name)!==en.toLower(T.name)||en.toLower(S[S.length-1].type)!==en.toLower(T.type))&&S.push(T),S),[]),b=Array.from(o.values()).reduce(Ec,[]).sort((S,T)=>S.timestamp-T.timestamp),w=new Map(l);Gi.debug("sendUpdate",{columns:f,filters:b,tableMap:w}),s(Fn(e,{columns:f,filters:b,tableMap:w}))},[s,e,i,o,l]),d=v.useCallback((f,b)=>{Gi.debug2("handleColumnsChanged",f,b),i.set(f,[].concat(b)),a()},[i,a]),h=v.useCallback((f,b)=>{Gi.debug2("handleFiltersChanged",f,b),o.set(f,[].concat(b)),a()},[o,a]),u=v.useCallback((f,b)=>{Gi.debug2("handleTableChanged",f,b),l.set(K.getIdFromPanel(f),b),a()},[l,a]),m=v.useCallback(f=>{Gi.debug2("handlePanelUnmount",f),i.delete(f),o.delete(f),l.delete(K.getIdFromPanel(f)),a()},[i,o,l,a]),g=v.useCallback(({title:f="DropdownFilter",metadata:b={},panelState:w=null,id:S=qe.generate(),focusElement:T=K.DEFAULT_FOCUS_SELECTOR,createNewStack:y=!1,dragEvent:E=null})=>{const R={type:"react-component",component:Ys.COMPONENT,props:{id:S,metadata:b,panelState:w,localDashboardId:e},title:f,id:S},{root:x}=t;K.openComponent({root:x,config:R,focusElement:T,createNewStack:y,dragEvent:E})},[t,e]),p=v.useCallback(({title:f="InputFilter",metadata:b={},panelState:w=null,id:S=qe.generate(),focusElement:T=K.DEFAULT_FOCUS_SELECTOR,createNewStack:y=!1,dragEvent:E=null})=>{const R={type:"react-component",component:no.COMPONENT,props:{id:S,metadata:b,panelState:w,localDashboardId:e},title:f,id:S},{root:x}=t;K.openComponent({root:x,config:R,focusElement:T,createNewStack:y,dragEvent:E})},[t,e]),C=v.useCallback(({title:f="FilterSets",metadata:b={},panelState:w=null,id:S=qe.generate(),focusElement:T=K.DEFAULT_FOCUS_SELECTOR,createNewStack:y=!1,dragEvent:E=null})=>{const R={type:"react-component",component:ka.COMPONENT,props:{id:S,metadata:b,panelState:w,localDashboardId:e},title:f,id:S},{root:x}=t;K.openComponent({root:x,config:R,focusElement:T,createNewStack:y,dragEvent:E})},[t,e]);return v.useEffect(function(){const b=[n(Ys.COMPONENT,Ys),n(no.COMPONENT,no),n(ka.COMPONENT,ka)];return()=>{b.forEach(w=>w())}},[n]),Ve(t.eventHub,Ze.COLUMNS_CHANGED,d),Ve(t.eventHub,Ze.FILTERS_CHANGED,h),Ve(t.eventHub,Ze.TABLE_CHANGED,u),Ve(t.eventHub,Ze.OPEN_DROPDOWN,g),Ve(t.eventHub,Ze.OPEN_INPUT,p),Ve(t.eventHub,Ze.OPEN_FILTER_SET_MANAGER,C),Ve(t.eventHub,Ee.UNMOUNT,m),null}const KR=[dh.VariableType.TABLE,dh.VariableType.TREETABLE,dh.VariableType.HIERARCHICALTABLE];function YR(c){ys(c);const{getDownloadWorker:e,loadPlugin:t,id:n,layout:s,registerComponent:i,hydrate:o,theme:l}=c,a=v.useCallback(({dragEvent:d,fetch:h,panelId:u=qe.generate(),widget:m})=>{const{name:g,type:p}=m;if(!KR.includes(p))return;const C={name:g,table:g,type:m.type},f=()=>h().then(S=>Wr.makeModel(S)),b={type:"react-component",component:qs.COMPONENT,props:{getDownloadWorker:e,loadPlugin:t,localDashboardId:n,id:u,metadata:C,makeModel:f,theme:l},title:g,id:u},{root:w}=s;K.openComponent({root:w,config:b,dragEvent:d})},[e,n,s,t,l]);return v.useEffect(function(){const h=[i(qs.COMPONENT,qs,o)];return()=>{h.forEach(u=>u())}},[o,i]),Ve(s.eventHub,Ee.OPEN,a),null}function Wu(c){return typeof c.getCoordinateForColumn=="function"}function yc(c){const e=c;return Wu(c)&&typeof e.setFilterMap=="function"&&typeof e.unsetFilterValue=="function"}function Rc(c){return c.description===void 0||!c.description?.startsWith("Preview of type: ")}const zi=ne.module("LinkerUtils");class nd{static ALLOWED_LINKS=new Map([[K.getComponentName(qs),[K.getComponentName(qs),K.getComponentName(Ei),K.getComponentName(Ys)]]]);static getLinkType(e,t,n){if(e?.panelId==null||t?.panelId==null||e.panelId===t.panelId||n!=null&&n!==e.panelId&&n!==t.panelId)return zi.debug2("Incompatible panel ids",e,t,n),"invalid";if(e.panelComponent==null||t.panelComponent==null)return zi.error("PanelComponent should not be null",e,t),"invalid";const s=nd.ALLOWED_LINKS.get(e.panelComponent)?.includes(t.panelComponent);if(s===void 0||!s)return zi.debug2("Incompatible panel components",e,t),"invalid";const{columnType:i}=e,{columnType:o}=t;if(!(o===null||F.isCompatibleType(i,o)))return zi.debug2("Incompatible type",i,o),"invalid";switch(t.panelComponent){case K.getComponentName(Ei):return"chartLink";case K.getComponentName(qs):return"tableLink";case K.getComponentName(Ys):return"filterSource"}return zi.debug2("Incompatible target panel component",t.panelComponent),"invalid"}static findColumn(e,{columnName:t,columnType:n}){return e.find(({name:s,type:i})=>s===t&&i===n)}static cloneLinksForPanel(e,t,n){const s=[];return e.forEach(i=>{i.start.panelId===t&&i.type!=="filterSource"?s.push({...i,id:qe.generate(),start:{...i.start,panelId:n}}):i.end?.panelId===t&&s.push({...i,id:qe.generate(),end:{...i.end,panelId:n}})}),s}}const hi=nd;const qR=ne.module("LinkerLink"),xc=.015,Dc=1.5,Gu=12,zu=12,Ic=2,Jo=Math.sqrt((zu*.5)**2+Gu**2),Fc=Math.asin(zu*.5/Gu),Nc=15,cs=Math.PI*.5;class so extends v.Component{static defaultProps={className:"",isSelected:!1,onClick(){},onDelete(){}};static makeCirclePath(e,t,n){return`M ${e} ${t} m -${n},0 a ${n},${n} 0 1,0 ${n*2},0 a ${n},${n} 0 1,0 -${n*2},0 z`}static getLabelForLinkFilter(e,t){try{if(F.isNumberType(e)||F.isCharType(e))return fh(t);if(F.isTextType(e))return ph(t);if(F.isDateType(e))return Ch(t);if(F.isBooleanType(e)){if(t===be.eq)return"is equal to";if(t===be.notEq)return"is not equal to"}throw new Error(`Unrecognized column type: ${e}`)}catch(n){return qR.warn(n),""}}constructor(e){super(e),this.handleClick=this.handleClick.bind(this),this.handleMouseEnter=this.handleMouseEnter.bind(this),this.handleMouseLeave=this.handleMouseLeave.bind(this),this.handleDelete=this.handleDelete.bind(this),this.getDropdownActions=this.getDropdownActions.bind(this),this.state={isHovering:void 0}}getOperators=ge((e,t)=>{const{onOperatorChanged:n}=this.props;let s=F.getFilterTypes(t);return F.isBooleanType(t)&&(s=[be.eq,be.notEq]),s.flatMap((i,o)=>{if(i==="eqIgnoreCase"||i==="notEqIgnoreCase")return[];let l="";return i==="startsWith"?l="a*":i==="endsWith"?l="*z":l=F.getFilterOperatorString(i),[{title:so.getLabelForLinkFilter(t,i),icon:r.jsx("b",{children:l}),action:()=>n(e,i),order:o}]})});handleClick(e){e.stopPropagation(),e.preventDefault();const{id:t,onClick:n,onDelete:s}=this.props;e.altKey?s(t):n(t)}handleMouseEnter(){this.setState({isHovering:!0})}handleMouseLeave(){this.setState({isHovering:!1})}handleDelete(){const{id:e,onDelete:t}=this.props;t(e)}getDropdownActions(){const{id:e,startColumnType:t}=this.props;return t!=null?this.getOperators(e,t):[]}render(){const{className:e,operator:t,isSelected:n,x1:s,y1:i,x2:o,y2:l,id:a,startColumnType:d,type:h}=this.props,{isHovering:u}=this.state,m=Math.sqrt((s-o)**2+(i-l)**2),g=Math.atan2(l-i,o-s),p=Math.sin(g),C=Math.cos(g)+2,f=window.innerWidth,b=window.innerHeight,w=0,S=0,T=Math.max(w,Math.min(s+(o-s)/2+p*(m*xc)**Dc,f)),y=Math.max(S,Math.min(i+(l-i)/2+C*(m*xc)**Dc,b)),E=`M ${s} ${i} Q ${T} ${y} ${o} ${l}`,R=`M ${w} ${S} L ${w} ${b} L ${f} ${b} L ${f} ${S} z
34
34
  ${so.makeCirclePath(s,i,Nc)}
35
- ${so.makeCirclePath(o,l,Nc)}`,x=`link-select-clip-${a}`,D=Math.atan2(l-y,o-T),M=D-Fc+Math.PI,O=D+Fc+Math.PI,H=o+Math.cos(D)*Ic,L=l+Math.sin(D)*Ic,V=H+Math.cos(M)*Jo,U=L+Math.sin(M)*Jo,j=H+Math.cos(O)*Jo,P=L+Math.sin(O)*Jo,Q=`${H},${L} ${V},${U} ${j},${P}`,$=.25*s+.5*T+.25*o,J=.25*i+.5*y+.25*l,A=T-s+(o-T),q=(y-i+(l-y))/A;let le=20/Math.sqrt(1+q**2),G=le*q,oe=le*-1,ue=G*-1;Number.isFinite(q)?q>0?(le*=-1,G*=-1,oe*=-1,ue*=-1,oe-=50-10*(Math.abs(g)%cs),ue+=10*(Math.abs(g)%cs),le-=50-10*(Math.abs(g)%cs),G+=10*(Math.abs(g)%cs)):q<0?(oe+=10*(Math.abs(g)%cs),ue+=10*(Math.abs(g)%cs),le+=10*(Math.abs(g)%cs),G+=10*(Math.abs(g)%cs)):(oe=15,ue=10,le=-25,G=10):(oe=10,ue=5,le=10,G=-35);let ae="";t!==void 0&&(t==="startsWith"?ae="a*":t==="endsWith"?ae="*z":ae=F.getFilterOperatorString(t));const ce=h!=="chartLink"&&h!=="filterSource";return r.jsxs(r.Fragment,{children:[r.jsxs("svg",{className:Y(e,{hovering:u}),children:[r.jsx("clipPath",{id:x,children:r.jsx("path",{d:R,clipRule:"evenodd"})}),r.jsx("path",{className:"link-select",d:E,onClick:this.handleClick,onMouseEnter:this.handleMouseEnter,onMouseLeave:this.handleMouseLeave,clipPath:`url(#${x})`,"data-testid":"link-select"}),r.jsx("path",{className:"link-background",d:E}),r.jsx("path",{className:"link-foreground",d:E}),r.jsx("circle",{className:"link-dot",cx:s,cy:i,r:"5"}),r.jsx("polygon",{className:"link-triangle",points:Q})]}),d!=null&&n&&r.jsxs(r.Fragment,{children:[ce&&r.jsx(B,{kind:"primary",className:"btn-fab btn-operator",style:{top:J+(q>=0?G:ue),left:$+(q>=0?le:oe)},onClick:()=>{},icon:r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx("b",{children:ae}),r.jsx(ee,{icon:Un,transform:"right-8 down-9 shrink-5"})]}),tooltip:"Change comparison operator",children:r.jsx(Vn,{actions:this.getDropdownActions,popperOptions:{placement:"bottom-start"}})}),r.jsx(B,{kind:"primary",className:"btn-fab btn-delete",style:{top:J+(q<0?G:ue),left:$+(q<0?le:oe)},onClick:this.handleDelete,icon:Gt,tooltip:"Delete"})]})]})}}const XR=so;const La=ne.module("LinkerOverlayContent");class ZR extends v.Component{static defaultProps={disabled:"false"};constructor(e){super(e),this.handleBlur=this.handleBlur.bind(this),this.handleResize=this.handleResize.bind(this),this.handleMouseMove=this.handleMouseMove.bind(this),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleKeyUp=this.handleKeyUp.bind(this),this.handleEscapePressed=this.handleEscapePressed.bind(this),this.handleOperatorChanged=this.handleOperatorChanged.bind(this),this.dialogRef=de.createRef(),this.state={mouse:void 0,dialog:void 0,offset:{x:0,y:0},isDragging:!1,mode:"select"}}componentDidMount(){window.addEventListener("blur",this.handleBlur,!0),window.addEventListener("mousemove",this.handleMouseMove,!0),window.addEventListener("mouseup",this.handleMouseUp,!0),window.addEventListener("keydown",this.handleKeyDown,!0),window.addEventListener("keyup",this.handleKeyUp,!0),window.addEventListener("resize",this.handleResize,!0)}componentDidCatch(e,t){La.error("componentDidCatch",e,t)}componentWillUnmount(){window.removeEventListener("blur",this.handleBlur,!0),window.removeEventListener("mousemove",this.handleMouseMove,!0),window.removeEventListener("mouseup",this.handleMouseUp,!0),window.removeEventListener("keydown",this.handleKeyDown,!0),window.removeEventListener("keyup",this.handleKeyUp,!0),window.removeEventListener("resize",this.handleResize,!0)}dialogRef;getPointFromLinkPoint(e){const{panelManager:t}=this.props,{panelId:n,columnName:s}=e,i=t.getOpenedPanelById(n);if(i!=null){if(!Wu(i))throw new Error(`Panel does not have getCoordinateForColumn method: ${n}`);try{const l=i.getCoordinateForColumn(s);if(l!=null)return l}catch{La.error("Could not get coordinate for column",s,i)}}const o=t.getContainerByPanelId(n);if(o==null)throw new Error(`Unable to find panel container for id: ${n}`);return K.getTabPoint(o)}handleOperatorChanged(e,t){const{links:n,onLinksUpdated:s}=this.props,i=n.map(o=>o.id===e?{...o,operator:t}:o);s(i)}handleBlur(){this.setState({mode:"select"})}handleResize(){const{dialog:e}=this.state;if(e&&this.dialogRef.current){const t=this.dialogRef.current.getBoundingClientRect(),n=Oe(e.x,0,window.innerWidth-t.width),s=Oe(e.y,0,window.innerHeight-t.height);this.setState({dialog:{x:n,y:s}})}}handleMouseMove(e){const{offset:t,isDragging:n}=this.state;if(this.setState({mouse:{x:e.clientX,y:e.clientY}}),n&&this.dialogRef.current){const s=this.dialogRef.current.getBoundingClientRect(),i=Oe(window.innerWidth-(e.clientX+s.width+t.x),0,window.innerWidth-s.width),o=Oe(window.innerHeight-(e.clientY+s.height+t.y),0,window.innerHeight-s.height);this.setState({dialog:{x:i,y:o}})}}handleMouseDown(e){const t={x:0,y:0};if(this.dialogRef.current){const n=this.dialogRef.current.getBoundingClientRect();t.x=n.right-(n.width+e.clientX),t.y=n.bottom-(n.height+e.clientY)}this.setState({isDragging:!0,offset:t})}handleMouseUp(){this.setState({isDragging:!1})}handleKeyDown(e){if(e.key==="Alt")e.preventDefault(),this.setState({mode:"delete"});else if(e.key==="Delete"||e.key==="Backspace"){const{selectedIds:t,onLinkDeleted:n}=this.props;e.preventDefault(),t.forEach(s=>n(s))}}handleKeyUp(e){e.key==="Alt"&&(e.preventDefault(),this.setState({mode:"select"}))}handleEscapePressed(){const{onCancel:e}=this.props;e()}render(){const{disabled:e,links:t,selectedIds:n,messageText:s,onLinkSelected:i,onLinkDeleted:o,onAllLinksDeleted:l,onDone:a}=this.props,{mouse:d,dialog:h,isDragging:u,mode:m}=this.state,g=t.map(p=>{try{const{id:C,type:f,isReversed:b,start:w,end:S,operator:T}=p,y=w.columnType;let[E,R]=this.getPointFromLinkPoint(w),x=d?.x??E,D=d?.y??R;if(S!=null&&([x,D]=this.getPointFromLinkPoint(S)),b!=null&&b){const[O,H]=[E,R];[E,R]=[x,D],[x,D]=[O,H]}const M=Y("linker-link",{disabled:e},{"link-filter-source":f==="filterSource"},{"link-invalid":f==="invalid"},{interactive:p.end==null},{"link-is-selected":n.has(C)},{"danger-delete":m==="delete"});return{x1:E,y1:R,x2:x,y2:D,id:C,className:M,operator:T,startColumnType:y,type:f}}catch(C){return La.warn("Unable to get point for link",p,C),null}}).filter(p=>p!=null);return r.jsxs("div",{className:Y("linker-overlay",{"danger-delete":m==="delete"}),children:[g.map(({x1:p,y1:C,x2:f,y2:b,id:w,className:S,operator:T,startColumnType:y,type:E})=>r.jsx(XR,{className:S,id:w,x1:p,y1:C,x2:f,y2:b,onClick:i,onDelete:o,isSelected:n.has(w),operator:T,startColumnType:y,type:E,onOperatorChanged:this.handleOperatorChanged},w)),r.jsxs("div",{className:Y("linker-toast-dialog",{dragging:u}),ref:this.dialogRef,style:{bottom:h?.y,right:h?.x},"data-testid":"linker-toast-dialog",children:[r.jsx(B,{draggable:!0,kind:"inline",className:"btn-drag-handle",icon:Wl,onClick:()=>{},onMouseDown:this.handleMouseDown,children:!u&&r.jsx(ot,{children:"Drag to reposition"})}),r.jsx("div",{className:"toast-body",children:s}),r.jsxs("div",{className:"toast-footer",children:[r.jsx(B,{kind:"secondary",onClick:l,children:"Clear All"}),r.jsx(B,{kind:"primary",onClick:a,children:"Done"})]})]}),r.jsx(ie,{actions:[{action:this.handleEscapePressed,shortcut:Kn.LINKER_CLOSE,isGlobal:!0}]})]})}}const QR=ZR,ft=ne.module("Linker"),JR=(c,e)=>({activeTool:Xl(c),isolatedLinkerPanelId:Yr(c,e.localDashboardId),links:Ni(c,e.localDashboardId),timeZone:po(c)}),ex=St(JR,{setActiveTool:Ql,setDashboardLinks:Xr,addDashboardLinks:Iy,deleteDashboardLinks:Fy,setDashboardIsolatedLinkerPanelId:Hu,setDashboardColumnSelectionValidator:Ny});class tx extends v.Component{constructor(e){super(e),this.handleCancel=this.handleCancel.bind(this),this.handleDone=this.handleDone.bind(this),this.handlePanelCloned=this.handlePanelCloned.bind(this),this.handleFilterColumnSelect=this.handleFilterColumnSelect.bind(this),this.handleColumnsChanged=this.handleColumnsChanged.bind(this),this.handlePanelClosed=this.handlePanelClosed.bind(this),this.handleLayoutStateChanged=this.handleLayoutStateChanged.bind(this),this.handleAllLinksDeleted=this.handleAllLinksDeleted.bind(this),this.handleLinkDeleted=this.handleLinkDeleted.bind(this),this.handleLinksUpdated=this.handleLinksUpdated.bind(this),this.handleChartColumnSelect=this.handleChartColumnSelect.bind(this),this.handleGridColumnSelect=this.handleGridColumnSelect.bind(this),this.handleUpdateValues=this.handleUpdateValues.bind(this),this.handleStateChange=this.handleStateChange.bind(this),this.handleExited=this.handleExited.bind(this),this.handleLinkSelected=this.handleLinkSelected.bind(this),this.handlePanelDragging=this.handlePanelDragging.bind(this),this.handlePanelDropped=this.handlePanelDropped.bind(this),this.isColumnSelectionValid=this.isColumnSelectionValid.bind(this),this.state={linkInProgress:void 0,selectedIds:new Set,isDraggingPanel:!1}}componentDidMount(){const{layout:e}=this.props;this.startListening(e),this.updateSelectionValidators()}componentDidUpdate(e){const{activeTool:t,layout:n}=this.props;n!==e.layout&&(this.stopListening(e.layout),this.startListening(n)),t!==e.activeTool&&(this.updateSelectionValidators(),t===Pt.DEFAULT&&this.reset())}componentDidCatch(e,t){ft.error("componentDidCatch",e,t)}componentWillUnmount(){const{layout:e}=this.props;this.stopListening(e)}startListening(e){e.on("stateChanged",this.handleLayoutStateChanged);const{eventHub:t}=e;t.on(cn.COLUMN_SELECTED,this.handleGridColumnSelect),t.on(cn.DATA_SELECTED,this.handleUpdateValues),t.on(cn.STATE_CHANGED,this.handleStateChange),t.on(Qa.COLUMN_SELECTED,this.handleChartColumnSelect),t.on(Ee.CLONED,this.handlePanelCloned),t.on(Ze.COLUMN_SELECTED,this.handleFilterColumnSelect),t.on(Ze.COLUMNS_CHANGED,this.handleColumnsChanged),t.on(Ee.CLOSE,this.handlePanelClosed),t.on(Ee.CLOSED,this.handlePanelClosed),t.on(Ee.DRAGGING,this.handlePanelDragging),t.on(Ee.DROPPED,this.handlePanelDropped)}stopListening(e){e.off("stateChanged",this.handleLayoutStateChanged);const{eventHub:t}=e;t.off(cn.COLUMN_SELECTED,this.handleGridColumnSelect),t.off(cn.DATA_SELECTED,this.handleUpdateValues),t.off(cn.STATE_CHANGED,this.handleStateChange),t.off(Qa.COLUMN_SELECTED,this.handleChartColumnSelect),t.off(Ee.CLONED,this.handlePanelCloned),t.off(Ze.COLUMN_SELECTED,this.handleFilterColumnSelect),t.off(Ze.COLUMNS_CHANGED,this.handleColumnsChanged),t.off(Ee.CLOSE,this.handlePanelClosed),t.off(Ee.CLOSED,this.handlePanelClosed),t.off(Ee.DRAGGING,this.handlePanelDragging),t.off(Ee.DROPPED,this.handlePanelDropped)}reset(){this.setState({linkInProgress:void 0,selectedIds:new Set})}handleCancel(){const{linkInProgress:e}=this.state;if(e==null){const{setActiveTool:t}=this.props;t(Pt.DEFAULT)}this.setState({linkInProgress:void 0})}handleDone(){const{setActiveTool:e}=this.props;e(Pt.DEFAULT)}handleChartColumnSelect(e,t){this.columnSelected(e,t,!0)}handleFilterColumnSelect(e,t){ft.debug("handleFilterColumnSelect",this.isOverlayShown());const{links:n,localDashboardId:s,setActiveTool:i,setDashboardIsolatedLinkerPanelId:o}=this.props,l=K.getIdFromPanel(e),a=n.filter(d=>d.start?.panelId===l||d.end?.panelId===l);if(!this.isOverlayShown()&&l!=null){i(Pt.LINKER),o(s,l),a.length===0&&this.columnSelected(e,t,!0,l);return}this.columnSelected(e,t,!0)}handleColumnsChanged(e,t){ft.debug("handleColumnsChanged",e,t);const{links:n}=this.props,s=K.getIdFromPanel(e);if(s==null){ft.error("Invalid panelId",e);return}const i=n.filter(({start:o,end:l})=>o.panelId===s&&hi.findColumn(t,o)==null||l!=null&&l.panelId===s&&hi.findColumn(t,l)==null);this.deleteLinks(i)}handleGridColumnSelect(e,t){if(!Rc(t)){ft.debug2("Column is not filterable");return}this.columnSelected(e,t)}columnSelected(e,t,n=!1,s){if(s===void 0&&!this.isOverlayShown())return;const{isolatedLinkerPanelId:i}=this.props,{linkInProgress:o}=this.state,l=K.getIdFromPanel(e);if(l==null)return;const a=K.getComponentNameFromPanel(e),{name:d,type:h}=t;if(o==null||o.start==null){const u={id:qe.generate(),start:{panelId:l,panelComponent:a,columnName:d,columnType:h},type:"invalid",isReversed:n};ft.debug("starting link",u),this.setState({linkInProgress:u})}else{const{links:u}=this.props,{start:m,id:g,isReversed:p}=o,C={panelId:l,panelComponent:a,columnName:d,columnType:h},f=hi.getLinkType(p!==void 0&&p?C:m,p!==void 0&&p?m:C,s??i);switch(f){case"invalid":ft.debug("Ignore invalid link connection",o,C);return;case"filterSource":{const w=p!==void 0&&p?m.panelId:C.panelId,S=u.filter(({end:T})=>T?.panelId===w);this.deleteLinks(S);break}case"chartLink":{const w=p===!0?m:C,S=p===!0?C:m;ft.debug("creating chartlink",{existingLinkEnd:w,start:m,end:C});const T=u.filter(({end:y,start:E})=>E?.panelId===S.panelId&&y?.panelId===w.panelId&&y?.columnName===w.columnName&&y?.columnType===w.columnType);this.deleteLinks(T);break}}const b={start:p!==void 0&&p?C:m,end:p!==void 0&&p?m:C,id:g,type:f,operator:be.eq};ft.info("creating link",b),this.setState({linkInProgress:void 0,selectedIds:new Set([g])},()=>{this.addLinks([b])})}}unsetFilterValueForLink(e){const{panelManager:t}=this.props;if(e.end){const{end:n}=e,{panelId:s,columnName:i,columnType:o}=n,l=t.getOpenedPanelById(s);l?yc(l)?l.unsetFilterValue(i,o):ft.debug("endPanel.unsetFilterValue not implemented",l):ft.debug("endPanel no longer exists, ignoring unsetFilterValue",s)}}setPanelFilterMap(e,t){ft.debug("Set filter data for panel:",e,t);const{panelManager:n}=this.props,s=n.getOpenedPanelById(e);s?yc(s)?s.setFilterMap(t):ft.debug("panel.setFilterMap not implemented",e,s):ft.debug("panel no longer exists, ignoring setFilterMap",e)}addLinks(e){const{addDashboardLinks:t,localDashboardId:n}=this.props;t(n,e)}deleteLinks(e,t=!1){const{localDashboardId:n}=this.props;if(e.forEach(s=>this.unsetFilterValueForLink(s)),t){const{setDashboardLinks:s}=this.props;s(n,[])}else if(e.length>0){const{deleteDashboardLinks:s}=this.props;s(n,e.map(({id:i})=>i))}}handleAllLinksDeleted(){const{links:e,isolatedLinkerPanelId:t}=this.props;if(t===void 0)this.deleteLinks(e,!0);else{const n=e.filter(s=>s?.start?.panelId===t||s?.end?.panelId===t);this.deleteLinks(n)}this.reset()}handleLinkDeleted(e){const{links:t}=this.props,n=t.find(s=>s.id===e);n?this.deleteLinks([n]):ft.error("Unable to find link to delete",e)}handleUpdateValues(e,t){const n=K.getIdFromPanel(e),{links:s,timeZone:i}=this.props,o=new Map;for(let l=0;l<s.length;l+=1){const{start:a,end:d,operator:h}=s[l];if(a.panelId===n&&d!=null){const{panelId:u,columnName:m,columnType:g}=d,p=o.has(u)?o.get(u):new Map,C=p.has(m)===!0?p.get(m).filterList:[],{visibleIndex:f,isExpandable:b,isGrouped:w}=t[a.columnName];let{value:S}=t[a.columnName],T=`${S}`;S===null&&b&&w&&(S=void 0),g!=null&&F.isDateType(g)&&(T=new ct({timeZone:i,showTimeZone:!1,showTSeparator:!0,defaultDateTimeFormatString:Xs.FULL_DATE_FORMAT}).format(S));const y={operator:h,text:T,value:S,startColumnIndex:f};C.push(y),p.set(m,{columnType:g,filterList:C}),o.set(u,p)}}o.forEach((l,a)=>{this.setPanelFilterMap(a,l)})}handlePanelCloned(e,t){const{links:n}=this.props,s=K.getIdFromPanel(e),i=t.id;if(s!=null){const o=hi.cloneLinksForPanel(n,s,i);this.addLinks(o)}}handlePanelDragging(e){const{links:t}=this.props;for(let n=0;n<t.length;n+=1){const s=t[n],{start:i,end:o}=s;if(i.panelId===e||o?.panelId===e){this.setState({isDraggingPanel:!0});return}}}handlePanelDropped(){this.setState({isDraggingPanel:!1})}handlePanelClosed(e){ft.debug(`Panel ${e} closed, deleting links.`),this.deleteLinksForPanelId(e)}handleLinkSelected(e){this.setState({selectedIds:new Set([e])})}handleLinksUpdated(e){const{localDashboardId:t,setDashboardLinks:n}=this.props;n(t,e)}handleLayoutStateChanged(){this.forceUpdate()}handleStateChange(){this.forceUpdate()}handleExited(){const{localDashboardId:e,setDashboardIsolatedLinkerPanelId:t}=this.props;t(e,void 0)}deleteLinksForPanelId(e){const{links:t}=this.props;for(let n=0;n<t.length;n+=1){const s=t[n],{start:i,end:o,id:l}=s;(i.panelId===e||o?.panelId===e)&&this.handleLinkDeleted(l)}}getCachedLinks=ge((e,t,n)=>{const s=[...e];return t!=null&&t.start!=null&&s.push(t),n!==void 0?s.filter(i=>i?.start?.panelId===n||i?.end?.panelId===n||i?.end==null):s});isOverlayShown(){const{activeTool:e}=this.props;return e===Pt.LINKER}updateSelectionValidators(){const{activeTool:e,setDashboardColumnSelectionValidator:t,localDashboardId:n}=this.props;switch(e){case Pt.LINKER:t(n,this.isColumnSelectionValid);break;default:t(n,void 0);break}}updateLinkInProgressType(e="invalid"){this.setState(({linkInProgress:t})=>t!==void 0?{linkInProgress:{...t,type:e}}:null)}isColumnSelectionValid(e,t){const{linkInProgress:n}=this.state,{isolatedLinkerPanelId:s}=this.props;if(t==null)return n?.start!=null&&this.updateLinkInProgressType(),!1;if(!Rc(t))return ft.debug2("Column is not filterable",t.description),n?.start!=null&&this.updateLinkInProgressType("invalid"),!1;if(n?.start==null)return!0;const{isReversed:i,start:o}=n,l=K.getIdFromPanel(e);if(l==null)return!1;const a={panelId:l,panelComponent:K.getComponentNameFromPanel(e),columnName:t.name,columnType:t.type},d=i!==void 0&&i?hi.getLinkType(a,o,s):hi.getLinkType(o,a,s);return this.updateLinkInProgressType(d),d!=="invalid"}render(){const{links:e,isolatedLinkerPanelId:t,panelManager:n}=this.props,{linkInProgress:s,selectedIds:i,isDraggingPanel:o}=this.state,l=this.isOverlayShown(),a=s!=null&&s.start!=null,d=t===void 0?"Click a column source, then click a column target to create a filter link. The filter comparison operator used by a selected link can be changed. Delete a filter link by clicking the delete button or with alt+click. Click done when finished.":"Create a link between the source column button and a table column by clicking on one, then the other. Delete a filter link by clicking the delete button or with alt+click. Click done when finished.";return o?null:r.jsx(Wt,{in:l,timeout:Je.transitionMs,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,onExited:this.handleExited,children:r.jsx(QR,{disabled:a,panelManager:n,links:this.getCachedLinks(e,s,t),selectedIds:i,messageText:d,onLinkSelected:this.handleLinkSelected,onLinkDeleted:this.handleLinkDeleted,onAllLinksDeleted:this.handleAllLinksDeleted,onLinksUpdated:this.handleLinksUpdated,onDone:this.handleDone,onCancel:this.handleCancel})})}}const nx=ex(tx),sx=nx;function ix(c){ys(c);const{id:e,layout:t,panelManager:n}=c;return r.jsx(sx,{layout:t,localDashboardId:e,panelManager:n})}class Al{static DEFAULT_TITLE="Note";static DEFAULT_CONTENT=`# Markdown Note
35
+ ${so.makeCirclePath(o,l,Nc)}`,x=`link-select-clip-${a}`,D=Math.atan2(l-y,o-T),M=D-Fc+Math.PI,O=D+Fc+Math.PI,H=o+Math.cos(D)*Ic,L=l+Math.sin(D)*Ic,V=H+Math.cos(M)*Jo,U=L+Math.sin(M)*Jo,j=H+Math.cos(O)*Jo,P=L+Math.sin(O)*Jo,Q=`${H},${L} ${V},${U} ${j},${P}`,$=.25*s+.5*T+.25*o,J=.25*i+.5*y+.25*l,A=T-s+(o-T),q=(y-i+(l-y))/A;let le=20/Math.sqrt(1+q**2),G=le*q,oe=le*-1,ue=G*-1;Number.isFinite(q)?q>0?(le*=-1,G*=-1,oe*=-1,ue*=-1,oe-=50-10*(Math.abs(g)%cs),ue+=10*(Math.abs(g)%cs),le-=50-10*(Math.abs(g)%cs),G+=10*(Math.abs(g)%cs)):q<0?(oe+=10*(Math.abs(g)%cs),ue+=10*(Math.abs(g)%cs),le+=10*(Math.abs(g)%cs),G+=10*(Math.abs(g)%cs)):(oe=15,ue=10,le=-25,G=10):(oe=10,ue=5,le=10,G=-35);let ae="";t!==void 0&&(t==="startsWith"?ae="a*":t==="endsWith"?ae="*z":ae=F.getFilterOperatorString(t));const he=h!=="chartLink"&&h!=="filterSource";return r.jsxs(r.Fragment,{children:[r.jsxs("svg",{className:Y(e,{hovering:u}),children:[r.jsx("clipPath",{id:x,children:r.jsx("path",{d:R,clipRule:"evenodd"})}),r.jsx("path",{className:"link-select",d:E,onClick:this.handleClick,onMouseEnter:this.handleMouseEnter,onMouseLeave:this.handleMouseLeave,clipPath:`url(#${x})`,"data-testid":"link-select"}),r.jsx("path",{className:"link-background",d:E}),r.jsx("path",{className:"link-foreground",d:E}),r.jsx("circle",{className:"link-dot",cx:s,cy:i,r:"5"}),r.jsx("polygon",{className:"link-triangle",points:Q})]}),d!=null&&n&&r.jsxs(r.Fragment,{children:[he&&r.jsx(B,{kind:"primary",className:"btn-fab btn-operator",style:{top:J+(q>=0?G:ue),left:$+(q>=0?le:oe)},onClick:()=>{},icon:r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx("b",{children:ae}),r.jsx(ee,{icon:Un,transform:"right-8 down-9 shrink-5"})]}),tooltip:"Change comparison operator",children:r.jsx(Vn,{actions:this.getDropdownActions,popperOptions:{placement:"bottom-start"}})}),r.jsx(B,{kind:"primary",className:"btn-fab btn-delete",style:{top:J+(q<0?G:ue),left:$+(q<0?le:oe)},onClick:this.handleDelete,icon:Gt,tooltip:"Delete"})]})]})}}const XR=so;const La=ne.module("LinkerOverlayContent");class ZR extends v.Component{static defaultProps={disabled:"false"};constructor(e){super(e),this.handleBlur=this.handleBlur.bind(this),this.handleResize=this.handleResize.bind(this),this.handleMouseMove=this.handleMouseMove.bind(this),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleKeyUp=this.handleKeyUp.bind(this),this.handleEscapePressed=this.handleEscapePressed.bind(this),this.handleOperatorChanged=this.handleOperatorChanged.bind(this),this.dialogRef=de.createRef(),this.state={mouse:void 0,dialog:void 0,offset:{x:0,y:0},isDragging:!1,mode:"select"}}componentDidMount(){window.addEventListener("blur",this.handleBlur,!0),window.addEventListener("mousemove",this.handleMouseMove,!0),window.addEventListener("mouseup",this.handleMouseUp,!0),window.addEventListener("keydown",this.handleKeyDown,!0),window.addEventListener("keyup",this.handleKeyUp,!0),window.addEventListener("resize",this.handleResize,!0)}componentDidCatch(e,t){La.error("componentDidCatch",e,t)}componentWillUnmount(){window.removeEventListener("blur",this.handleBlur,!0),window.removeEventListener("mousemove",this.handleMouseMove,!0),window.removeEventListener("mouseup",this.handleMouseUp,!0),window.removeEventListener("keydown",this.handleKeyDown,!0),window.removeEventListener("keyup",this.handleKeyUp,!0),window.removeEventListener("resize",this.handleResize,!0)}dialogRef;getPointFromLinkPoint(e){const{panelManager:t}=this.props,{panelId:n,columnName:s}=e,i=t.getOpenedPanelById(n);if(i!=null){if(!Wu(i))throw new Error(`Panel does not have getCoordinateForColumn method: ${n}`);try{const l=i.getCoordinateForColumn(s);if(l!=null)return l}catch{La.error("Could not get coordinate for column",s,i)}}const o=t.getContainerByPanelId(n);if(o==null)throw new Error(`Unable to find panel container for id: ${n}`);return K.getTabPoint(o)}handleOperatorChanged(e,t){const{links:n,onLinksUpdated:s}=this.props,i=n.map(o=>o.id===e?{...o,operator:t}:o);s(i)}handleBlur(){this.setState({mode:"select"})}handleResize(){const{dialog:e}=this.state;if(e&&this.dialogRef.current){const t=this.dialogRef.current.getBoundingClientRect(),n=Oe(e.x,0,window.innerWidth-t.width),s=Oe(e.y,0,window.innerHeight-t.height);this.setState({dialog:{x:n,y:s}})}}handleMouseMove(e){const{offset:t,isDragging:n}=this.state;if(this.setState({mouse:{x:e.clientX,y:e.clientY}}),n&&this.dialogRef.current){const s=this.dialogRef.current.getBoundingClientRect(),i=Oe(window.innerWidth-(e.clientX+s.width+t.x),0,window.innerWidth-s.width),o=Oe(window.innerHeight-(e.clientY+s.height+t.y),0,window.innerHeight-s.height);this.setState({dialog:{x:i,y:o}})}}handleMouseDown(e){const t={x:0,y:0};if(this.dialogRef.current){const n=this.dialogRef.current.getBoundingClientRect();t.x=n.right-(n.width+e.clientX),t.y=n.bottom-(n.height+e.clientY)}this.setState({isDragging:!0,offset:t})}handleMouseUp(){this.setState({isDragging:!1})}handleKeyDown(e){if(e.key==="Alt")e.preventDefault(),this.setState({mode:"delete"});else if(e.key==="Delete"||e.key==="Backspace"){const{selectedIds:t,onLinkDeleted:n}=this.props;e.preventDefault(),t.forEach(s=>n(s))}}handleKeyUp(e){e.key==="Alt"&&(e.preventDefault(),this.setState({mode:"select"}))}handleEscapePressed(){const{onCancel:e}=this.props;e()}render(){const{disabled:e,links:t,selectedIds:n,messageText:s,onLinkSelected:i,onLinkDeleted:o,onAllLinksDeleted:l,onDone:a}=this.props,{mouse:d,dialog:h,isDragging:u,mode:m}=this.state,g=t.map(p=>{try{const{id:C,type:f,isReversed:b,start:w,end:S,operator:T}=p,y=w.columnType;let[E,R]=this.getPointFromLinkPoint(w),x=d?.x??E,D=d?.y??R;if(S!=null&&([x,D]=this.getPointFromLinkPoint(S)),b!=null&&b){const[O,H]=[E,R];[E,R]=[x,D],[x,D]=[O,H]}const M=Y("linker-link",{disabled:e},{"link-filter-source":f==="filterSource"},{"link-invalid":f==="invalid"},{interactive:p.end==null},{"link-is-selected":n.has(C)},{"danger-delete":m==="delete"});return{x1:E,y1:R,x2:x,y2:D,id:C,className:M,operator:T,startColumnType:y,type:f}}catch(C){return La.warn("Unable to get point for link",p,C),null}}).filter(p=>p!=null);return r.jsxs("div",{className:Y("linker-overlay",{"danger-delete":m==="delete"}),children:[g.map(({x1:p,y1:C,x2:f,y2:b,id:w,className:S,operator:T,startColumnType:y,type:E})=>r.jsx(XR,{className:S,id:w,x1:p,y1:C,x2:f,y2:b,onClick:i,onDelete:o,isSelected:n.has(w),operator:T,startColumnType:y,type:E,onOperatorChanged:this.handleOperatorChanged},w)),r.jsxs("div",{className:Y("linker-toast-dialog",{dragging:u}),ref:this.dialogRef,style:{bottom:h?.y,right:h?.x},"data-testid":"linker-toast-dialog",children:[r.jsx(B,{draggable:!0,kind:"inline",className:"btn-drag-handle",icon:Wl,onClick:()=>{},onMouseDown:this.handleMouseDown,children:!u&&r.jsx(ot,{children:"Drag to reposition"})}),r.jsx("div",{className:"toast-body",children:s}),r.jsxs("div",{className:"toast-footer",children:[r.jsx(B,{kind:"secondary",onClick:l,children:"Clear All"}),r.jsx(B,{kind:"primary",onClick:a,children:"Done"})]})]}),r.jsx(ie,{actions:[{action:this.handleEscapePressed,shortcut:Kn.LINKER_CLOSE,isGlobal:!0}]})]})}}const QR=ZR,ft=ne.module("Linker"),JR=(c,e)=>({activeTool:Xl(c),isolatedLinkerPanelId:Yr(c,e.localDashboardId),links:Ni(c,e.localDashboardId),timeZone:po(c)}),ex=St(JR,{setActiveTool:Ql,setDashboardLinks:Xr,addDashboardLinks:Iy,deleteDashboardLinks:Fy,setDashboardIsolatedLinkerPanelId:Hu,setDashboardColumnSelectionValidator:Ny});class tx extends v.Component{constructor(e){super(e),this.handleCancel=this.handleCancel.bind(this),this.handleDone=this.handleDone.bind(this),this.handlePanelCloned=this.handlePanelCloned.bind(this),this.handleFilterColumnSelect=this.handleFilterColumnSelect.bind(this),this.handleColumnsChanged=this.handleColumnsChanged.bind(this),this.handlePanelClosed=this.handlePanelClosed.bind(this),this.handleLayoutStateChanged=this.handleLayoutStateChanged.bind(this),this.handleAllLinksDeleted=this.handleAllLinksDeleted.bind(this),this.handleLinkDeleted=this.handleLinkDeleted.bind(this),this.handleLinksUpdated=this.handleLinksUpdated.bind(this),this.handleChartColumnSelect=this.handleChartColumnSelect.bind(this),this.handleGridColumnSelect=this.handleGridColumnSelect.bind(this),this.handleUpdateValues=this.handleUpdateValues.bind(this),this.handleStateChange=this.handleStateChange.bind(this),this.handleExited=this.handleExited.bind(this),this.handleLinkSelected=this.handleLinkSelected.bind(this),this.handlePanelDragging=this.handlePanelDragging.bind(this),this.handlePanelDropped=this.handlePanelDropped.bind(this),this.isColumnSelectionValid=this.isColumnSelectionValid.bind(this),this.state={linkInProgress:void 0,selectedIds:new Set,isDraggingPanel:!1}}componentDidMount(){const{layout:e}=this.props;this.startListening(e),this.updateSelectionValidators()}componentDidUpdate(e){const{activeTool:t,layout:n}=this.props;n!==e.layout&&(this.stopListening(e.layout),this.startListening(n)),t!==e.activeTool&&(this.updateSelectionValidators(),t===_t.DEFAULT&&this.reset())}componentDidCatch(e,t){ft.error("componentDidCatch",e,t)}componentWillUnmount(){const{layout:e}=this.props;this.stopListening(e)}startListening(e){e.on("stateChanged",this.handleLayoutStateChanged);const{eventHub:t}=e;t.on(cn.COLUMN_SELECTED,this.handleGridColumnSelect),t.on(cn.DATA_SELECTED,this.handleUpdateValues),t.on(cn.STATE_CHANGED,this.handleStateChange),t.on(Qa.COLUMN_SELECTED,this.handleChartColumnSelect),t.on(Ee.CLONED,this.handlePanelCloned),t.on(Ze.COLUMN_SELECTED,this.handleFilterColumnSelect),t.on(Ze.COLUMNS_CHANGED,this.handleColumnsChanged),t.on(Ee.CLOSE,this.handlePanelClosed),t.on(Ee.CLOSED,this.handlePanelClosed),t.on(Ee.DRAGGING,this.handlePanelDragging),t.on(Ee.DROPPED,this.handlePanelDropped)}stopListening(e){e.off("stateChanged",this.handleLayoutStateChanged);const{eventHub:t}=e;t.off(cn.COLUMN_SELECTED,this.handleGridColumnSelect),t.off(cn.DATA_SELECTED,this.handleUpdateValues),t.off(cn.STATE_CHANGED,this.handleStateChange),t.off(Qa.COLUMN_SELECTED,this.handleChartColumnSelect),t.off(Ee.CLONED,this.handlePanelCloned),t.off(Ze.COLUMN_SELECTED,this.handleFilterColumnSelect),t.off(Ze.COLUMNS_CHANGED,this.handleColumnsChanged),t.off(Ee.CLOSE,this.handlePanelClosed),t.off(Ee.CLOSED,this.handlePanelClosed),t.off(Ee.DRAGGING,this.handlePanelDragging),t.off(Ee.DROPPED,this.handlePanelDropped)}reset(){this.setState({linkInProgress:void 0,selectedIds:new Set})}handleCancel(){const{linkInProgress:e}=this.state;if(e==null){const{setActiveTool:t}=this.props;t(_t.DEFAULT)}this.setState({linkInProgress:void 0})}handleDone(){const{setActiveTool:e}=this.props;e(_t.DEFAULT)}handleChartColumnSelect(e,t){this.columnSelected(e,t,!0)}handleFilterColumnSelect(e,t){ft.debug("handleFilterColumnSelect",this.isOverlayShown());const{links:n,localDashboardId:s,setActiveTool:i,setDashboardIsolatedLinkerPanelId:o}=this.props,l=K.getIdFromPanel(e),a=n.filter(d=>d.start?.panelId===l||d.end?.panelId===l);if(!this.isOverlayShown()&&l!=null){i(_t.LINKER),o(s,l),a.length===0&&this.columnSelected(e,t,!0,l);return}this.columnSelected(e,t,!0)}handleColumnsChanged(e,t){ft.debug("handleColumnsChanged",e,t);const{links:n}=this.props,s=K.getIdFromPanel(e);if(s==null){ft.error("Invalid panelId",e);return}const i=n.filter(({start:o,end:l})=>o.panelId===s&&hi.findColumn(t,o)==null||l!=null&&l.panelId===s&&hi.findColumn(t,l)==null);this.deleteLinks(i)}handleGridColumnSelect(e,t){if(!Rc(t)){ft.debug2("Column is not filterable");return}this.columnSelected(e,t)}columnSelected(e,t,n=!1,s){if(s===void 0&&!this.isOverlayShown())return;const{isolatedLinkerPanelId:i}=this.props,{linkInProgress:o}=this.state,l=K.getIdFromPanel(e);if(l==null)return;const a=K.getComponentNameFromPanel(e),{name:d,type:h}=t;if(o==null||o.start==null){const u={id:qe.generate(),start:{panelId:l,panelComponent:a,columnName:d,columnType:h},type:"invalid",isReversed:n};ft.debug("starting link",u),this.setState({linkInProgress:u})}else{const{links:u}=this.props,{start:m,id:g,isReversed:p}=o,C={panelId:l,panelComponent:a,columnName:d,columnType:h},f=hi.getLinkType(p!==void 0&&p?C:m,p!==void 0&&p?m:C,s??i);switch(f){case"invalid":ft.debug("Ignore invalid link connection",o,C);return;case"filterSource":{const w=p!==void 0&&p?m.panelId:C.panelId,S=u.filter(({end:T})=>T?.panelId===w);this.deleteLinks(S);break}case"chartLink":{const w=p===!0?m:C,S=p===!0?C:m;ft.debug("creating chartlink",{existingLinkEnd:w,start:m,end:C});const T=u.filter(({end:y,start:E})=>E?.panelId===S.panelId&&y?.panelId===w.panelId&&y?.columnName===w.columnName&&y?.columnType===w.columnType);this.deleteLinks(T);break}}const b={start:p!==void 0&&p?C:m,end:p!==void 0&&p?m:C,id:g,type:f,operator:be.eq};ft.info("creating link",b),this.setState({linkInProgress:void 0,selectedIds:new Set([g])},()=>{this.addLinks([b])})}}unsetFilterValueForLink(e){const{panelManager:t}=this.props;if(e.end){const{end:n}=e,{panelId:s,columnName:i,columnType:o}=n,l=t.getOpenedPanelById(s);l?yc(l)?l.unsetFilterValue(i,o):ft.debug("endPanel.unsetFilterValue not implemented",l):ft.debug("endPanel no longer exists, ignoring unsetFilterValue",s)}}setPanelFilterMap(e,t){ft.debug("Set filter data for panel:",e,t);const{panelManager:n}=this.props,s=n.getOpenedPanelById(e);s?yc(s)?s.setFilterMap(t):ft.debug("panel.setFilterMap not implemented",e,s):ft.debug("panel no longer exists, ignoring setFilterMap",e)}addLinks(e){const{addDashboardLinks:t,localDashboardId:n}=this.props;t(n,e)}deleteLinks(e,t=!1){const{localDashboardId:n}=this.props;if(e.forEach(s=>this.unsetFilterValueForLink(s)),t){const{setDashboardLinks:s}=this.props;s(n,[])}else if(e.length>0){const{deleteDashboardLinks:s}=this.props;s(n,e.map(({id:i})=>i))}}handleAllLinksDeleted(){const{links:e,isolatedLinkerPanelId:t}=this.props;if(t===void 0)this.deleteLinks(e,!0);else{const n=e.filter(s=>s?.start?.panelId===t||s?.end?.panelId===t);this.deleteLinks(n)}this.reset()}handleLinkDeleted(e){const{links:t}=this.props,n=t.find(s=>s.id===e);n?this.deleteLinks([n]):ft.error("Unable to find link to delete",e)}handleUpdateValues(e,t){const n=K.getIdFromPanel(e),{links:s,timeZone:i}=this.props,o=new Map;for(let l=0;l<s.length;l+=1){const{start:a,end:d,operator:h}=s[l];if(a.panelId===n&&d!=null){const{panelId:u,columnName:m,columnType:g}=d,p=o.has(u)?o.get(u):new Map,C=p.has(m)===!0?p.get(m).filterList:[],{visibleIndex:f,isExpandable:b,isGrouped:w}=t[a.columnName];let{value:S}=t[a.columnName],T=`${S}`;S===null&&b&&w&&(S=void 0),g!=null&&F.isDateType(g)&&(T=new ct({timeZone:i,showTimeZone:!1,showTSeparator:!0,defaultDateTimeFormatString:Xs.FULL_DATE_FORMAT}).format(S));const y={operator:h,text:T,value:S,startColumnIndex:f};C.push(y),p.set(m,{columnType:g,filterList:C}),o.set(u,p)}}o.forEach((l,a)=>{this.setPanelFilterMap(a,l)})}handlePanelCloned(e,t){const{links:n}=this.props,s=K.getIdFromPanel(e),i=t.id;if(s!=null){const o=hi.cloneLinksForPanel(n,s,i);this.addLinks(o)}}handlePanelDragging(e){const{links:t}=this.props;for(let n=0;n<t.length;n+=1){const s=t[n],{start:i,end:o}=s;if(i.panelId===e||o?.panelId===e){this.setState({isDraggingPanel:!0});return}}}handlePanelDropped(){this.setState({isDraggingPanel:!1})}handlePanelClosed(e){ft.debug(`Panel ${e} closed, deleting links.`),this.deleteLinksForPanelId(e)}handleLinkSelected(e){this.setState({selectedIds:new Set([e])})}handleLinksUpdated(e){const{localDashboardId:t,setDashboardLinks:n}=this.props;n(t,e)}handleLayoutStateChanged(){this.forceUpdate()}handleStateChange(){this.forceUpdate()}handleExited(){const{localDashboardId:e,setDashboardIsolatedLinkerPanelId:t}=this.props;t(e,void 0)}deleteLinksForPanelId(e){const{links:t}=this.props;for(let n=0;n<t.length;n+=1){const s=t[n],{start:i,end:o,id:l}=s;(i.panelId===e||o?.panelId===e)&&this.handleLinkDeleted(l)}}getCachedLinks=ge((e,t,n)=>{const s=[...e];return t!=null&&t.start!=null&&s.push(t),n!==void 0?s.filter(i=>i?.start?.panelId===n||i?.end?.panelId===n||i?.end==null):s});isOverlayShown(){const{activeTool:e}=this.props;return e===_t.LINKER}updateSelectionValidators(){const{activeTool:e,setDashboardColumnSelectionValidator:t,localDashboardId:n}=this.props;switch(e){case _t.LINKER:t(n,this.isColumnSelectionValid);break;default:t(n,void 0);break}}updateLinkInProgressType(e="invalid"){this.setState(({linkInProgress:t})=>t!==void 0?{linkInProgress:{...t,type:e}}:null)}isColumnSelectionValid(e,t){const{linkInProgress:n}=this.state,{isolatedLinkerPanelId:s}=this.props;if(t==null)return n?.start!=null&&this.updateLinkInProgressType(),!1;if(!Rc(t))return ft.debug2("Column is not filterable",t.description),n?.start!=null&&this.updateLinkInProgressType("invalid"),!1;if(n?.start==null)return!0;const{isReversed:i,start:o}=n,l=K.getIdFromPanel(e);if(l==null)return!1;const a={panelId:l,panelComponent:K.getComponentNameFromPanel(e),columnName:t.name,columnType:t.type},d=i!==void 0&&i?hi.getLinkType(a,o,s):hi.getLinkType(o,a,s);return this.updateLinkInProgressType(d),d!=="invalid"}render(){const{links:e,isolatedLinkerPanelId:t,panelManager:n}=this.props,{linkInProgress:s,selectedIds:i,isDraggingPanel:o}=this.state,l=this.isOverlayShown(),a=s!=null&&s.start!=null,d=t===void 0?"Click a column source, then click a column target to create a filter link. The filter comparison operator used by a selected link can be changed. Delete a filter link by clicking the delete button or with alt+click. Click done when finished.":"Create a link between the source column button and a table column by clicking on one, then the other. Delete a filter link by clicking the delete button or with alt+click. Click done when finished.";return o?null:r.jsx(Wt,{in:l,timeout:Je.transitionMs,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,onExited:this.handleExited,children:r.jsx(QR,{disabled:a,panelManager:n,links:this.getCachedLinks(e,s,t),selectedIds:i,messageText:d,onLinkSelected:this.handleLinkSelected,onLinkDeleted:this.handleLinkDeleted,onAllLinksDeleted:this.handleAllLinksDeleted,onLinksUpdated:this.handleLinksUpdated,onDone:this.handleDone,onCancel:this.handleCancel})})}}const nx=ex(tx),sx=nx;function ix(c){ys(c);const{id:e,layout:t,panelManager:n}=c;return r.jsx(sx,{layout:t,localDashboardId:e,panelManager:n})}class Al{static DEFAULT_TITLE="Note";static DEFAULT_CONTENT=`# Markdown Note
36
36
 
37
37
  This note can be edited using **markdown** for styling.`;static getNewMarkdownTitle(e){let t=`${Al.DEFAULT_TITLE}`,n=0;for(;e.indexOf(t)>=0;)n+=1,t=`${Al.DEFAULT_TITLE}-${n}`;return t}}const Oa=Al;function ox(c){ys(c);const{id:e,layout:t,panelManager:n,registerComponent:s}=c,i=v.useCallback(l=>{const{title:a,componentState:d,props:h}=l;let{panelState:u=null}=h;return d!=null&&({panelState:u=null}=d),a==null||u==null||u.content==null||u.content.length===0||u.content===Oa.DEFAULT_CONTENT?null:Fr(l)},[]),o=v.useCallback(({title:l="",metadata:a={},id:d=qe.generate(),focusElement:h=K.DEFAULT_FOCUS_SELECTOR,createNewStack:u=!1,dragEvent:m=null}={})=>{const g=n.getOpenedPanelConfigsOfType(Wi.COMPONENT),p=n.getClosedPanelConfigsOfType(Wi.COMPONENT),C=g.map(T=>T.title??""),f=l!=null&&l!==""?l:Oa.getNewMarkdownTitle(C),b=p.length>0?null:Oa.DEFAULT_CONTENT,w={type:"react-component",component:Wi.COMPONENT,props:{id:d,metadata:a,panelState:{content:b},localDashboardId:e},title:f,id:d},{root:S}=t;K.openComponent({root:S,config:w,focusElement:h,createNewStack:u,dragEvent:m})},[e,t,n]);return v.useEffect(function(){const a=[s(Wi.COMPONENT,Wi,Nr,i)];return()=>{a.forEach(d=>d())}},[i,s]),Ve(t.eventHub,Pu.OPEN,o),null}function lx(c){ys(c);const{hydrate:e,id:t,layout:n,registerComponent:s}=c,i=v.useCallback(({dragEvent:o,fetch:l,panelId:a=qe.generate(),widget:d})=>{const{name:h,type:u}=d;if(u!==dh.VariableType.PANDAS)return;const m={name:h,table:h},g=()=>l().then(f=>Wr.makeModel(f)),p={type:"react-component",component:Ma.COMPONENT,props:{localDashboardId:t,id:a,metadata:m,makeModel:g},title:h,id:a},{root:C}=n;K.openComponent({root:C,config:p,dragEvent:o})},[t,n]);return v.useEffect(function(){const l=[s(Ma.COMPONENT,Ma,e)];return()=>{l.forEach(a=>a())}},[e,s]),Ve(n.eventHub,Ee.OPEN,i),null}class ax{static DROPDOWN_FILTER="ControlType.DROPDOWN_FILTER";static INPUT_FILTER="ControlType.INPUT_FILTER";static MARKDOWN="ControlType.MARKDOWN";static FILTER_SET_MANAGER="ControlType.FILTER_SET_MANAGER"}const bs=ax;class kc{static makeSortConfig(e,t){return{column:e,direction:t}}static makeFilterConfig(e){const t=[],n=[];return e.forEach((s,i)=>{t.push(s),i>0&&n.push(Bn.and)}),{filterItems:t,filterOperators:n}}static combineFilterConfigs(e,t,n=Bn.and){return{filterItems:[...e.filterItems,...t.filterItems],filterOperators:[...e.filterOperators,n,...t.filterOperators]}}static makeFilterItem(e,t,n){return{columnName:e,type:t,value:n}}}function rx(c,e,t){if(c.length>e){const n=c.length-t;return{toKeep:c.slice(n),toPrune:c.slice(0,n)}}return{toKeep:c,toPrune:[]}}const Aa=ne.module("PouchStorageTable"),dx="Deephaven.";$c.plugin(Dm);function cx(c,e){switch(c){case be.in:case be.contains:return{$regex:new RegExp(`${e}`)};case be.inIgnoreCase:return{$regex:new RegExp(`${e}`,"i")};case be.eq:return{$eq:e};case be.notEq:return{$neq:e};case be.greaterThan:return{$gt:e};case be.greaterThanOrEqualTo:return{$gte:e};case be.lessThan:return{$lt:e};case be.lessThanOrEqualTo:return{$lte:e};case be.startsWith:return{$regex:new RegExp(`^(?${e}).*`)};default:throw new Error(`Unsupported type: ${c}`)}}function hx(c){const{filterItems:e,filterOperators:t}=c;let n=null;for(let s=0;s<e.length;s+=1){const i=e[s],{columnName:o,type:l,value:a}=i,d={[o]:cx(l,a)};if(s===0)n=d;else if(n!==null&&s-1<t.length){const h=t[s-1];if(h===Bn.and)n={$and:[n,d]};else if(h===Bn.or)n={$or:[n,d]};else throw new Error(`Unexpected filter operator ${h}, ${d}`)}}if(n==null)throw new Error(`Invalid filter config ${c}`);return n}function _a(c=[]){return{$and:[...c.map(e=>hx(e)),{name:{$gt:null}},{id:{$gt:null}}]}}function ux(c,e=!1){return[{id:e?"desc":"asc"},...c?.map(t=>({[t.column]:t.direction}))??[]]}class mx{db;changes;listeners=[];itemListeners=new Map;currentSize=0;currentViewport;currentReverse=!1;currentFilter=null;currentSort=null;infoUpdatePromise;viewportUpdatePromise;currentViewportData;constructor(e,t){this.db=new $c(`${dx}${e}`,t),this.db._remote=!1,this.listenForChanges(),this.db.createIndex({index:{fields:["id","name"]}}),this.refreshInfo()}listenForChanges(){this.changes=this.db.changes({live:!0,since:"now",include_docs:!0}).on("change",this.dbUpdate.bind(this))}onUpdate(e){return this.listeners=[...this.listeners,e],()=>{this.listeners=this.listeners.filter(t=>t!==e)}}onItemUpdate(e,t){return this.itemListeners.has(e)||this.itemListeners.set(e,[]),this.itemListeners.set(e,[...this.itemListeners.get(e),t]),this.refreshItem(e),()=>{this.itemListeners.set(e,this.itemListeners.get(e).filter(n=>n!==t))}}close(){this.listeners=[]}get size(){return this.currentSize}get viewport(){return this.currentViewport}setReversed(e){this.currentReverse=e,this.currentViewportData=void 0,this.refreshData()}setViewport(e){this.currentViewport=e,this.refreshInfo(),this.refreshData()}setSorts(e){this.currentSort=e,this.currentViewportData=void 0,this.refreshData()}setFilters(e){this.currentFilter=e,this.currentViewportData=void 0,this.refreshInfo(),this.refreshData()}get data(){return this.currentViewportData}async getViewportData(){return this.viewportUpdatePromise||this.refreshData(),this.viewportUpdatePromise??Promise.resolve({items:[],offset:0})}async put(e){const t={...e,_id:e.id};return await this.db.put(t),t}sendUpdate(){const{listeners:e}=this,t=this.currentViewportData??{items:[],offset:0};for(let n=0;n<e.length;n+=1)e[n](t)}sendItemUpdate(e){const t=this.itemListeners.get(e.id);if(t!==void 0)for(let n=0;n<t.length;n+=1)t[n](e)}dbUpdate(e){Aa.debug("Update received",e),this.refreshInfo(),e.doc!==void 0&&this.sendItemUpdate(e.doc),this.refreshData()}async fetchInfo(e){return this.db.find({selector:e,fields:[]})}async refreshInfo(){try{this.infoUpdatePromise?.cancel(),this.infoUpdatePromise=ye.makeCancelable(this.fetchInfo(_a(this.currentFilter??[])));const e=await this.infoUpdatePromise;this.currentSize=e.docs.length,this.sendUpdate()}catch(e){if(!ye.isCanceled(e))throw Aa.error("Unable to refreshInfo",e),e}}async fetchViewportData(e,t,n){return this.db.find({selector:t,skip:e.top,limit:e.bottom-e.top+1,sort:n,fields:["id","name"]}).then(s=>({items:s.docs,offset:e.top}))}async refreshData(){if(this.currentViewport)try{const e=_a(this.currentFilter??[]),t=ux(this.currentSort,this.currentReverse);this.viewportUpdatePromise?.cancel(),this.viewportUpdatePromise=ye.makeCancelable(this.fetchViewportData(this.currentViewport,e,t));const n=await this.viewportUpdatePromise;return this.currentViewportData=n,this.sendUpdate(),n}catch(e){if(!ye.isCanceled(e))throw Aa.error("Unable to refreshData",e),e}}async refreshItem(e){const n=(await this.db.find({selector:{id:e},limit:1})).docs[0];return n!==void 0&&this.sendItemUpdate(n),n}async getSnapshot(e){const t=new Map,n=[{id:this.currentReverse?"desc":"asc"}];return await Promise.all(e.map(async([s,i])=>{const o=i-s+1;return this.db.find({selector:_a(this.currentFilter??[]),skip:s,limit:o,sort:n,fields:["id","name"]}).then(l=>{for(let a=0;a<o;a+=1){const d=s+a;t.set(d,l.docs[a])}})})),t}}const gx=mx,px=2500,fx=2e3,Zt=ne.module("PouchCommandHistoryTable");class Cx extends gx{constructor(e,t){super(`CommandHistoryStorage.${e}`,{auto_compaction:!0,revs_limit:1}),this.cache=t,this.cache.tableRegistry.has(this.cacheKey)||this.cache.tableRegistry.set(this.cacheKey,new Set),Zt.debug("Adding table to registry",this.cacheKey),this.cache.tableRegistry.get(this.cacheKey)?.add(this)}searchText;get cacheKey(){return this.db.name}setSearch(e){Zt.debug("Setting search filters",e),this.searchText=e.trim().toLowerCase(),this.setFilters(e?[kc.makeFilterConfig([kc.makeFilterItem("name",be.contains,e)])]:[])}dbUpdate(e){Zt.debug("Clearing cache and refreshing data",e),this.cache.response.delete(this.cacheKey),super.dbUpdate(e)}async fetchData(e){return ye.withTimeout(0,async()=>{this.cache.response.has(this.cacheKey)?Zt.debug("Fetching from cache",this.searchText,this.viewport):(Zt.debug("Fetching from PouchDB",this.searchText,this.viewport),this.cache.response.set(this.cacheKey,this.db.allDocs({include_docs:!0}).then(n=>{const s=n.rows.map(l=>l.doc).filter(({name:l})=>l);Zt.debug(`Fetched ${s.length} command history items`);const{toKeep:i,toPrune:o}=rx(s,px,fx);return o.length&&this.pruneItems(o),{docs:i}})));const t=this.cache.response.get(this.cacheKey);return this.searchText==null||this.searchText===""?t:{...t,docs:(await t).docs.filter(({name:n})=>n.toLowerCase().includes(this.searchText))}})}async fetchInfo(e){return this.fetchData(e)}async fetchViewportData(e,t,n){const s=await this.fetchData(t);return Zt.debug("Fetching viewport data",e.top,e.bottom+1,n,s),{items:(typeof n[0]=="object"&&n[0].id==="desc"?s.docs.slice(0).reverse():s.docs).slice(e.top,e.bottom+1),offset:e.top}}async pruneItems(e){if(this.cache.isPruning.get(this.cacheKey)===!0){Zt.debug("Pruning already in progress. Skipping.");return}try{Zt.debug(`Pruning ${e.length} command history items`);const t=this.cache.pauseChangeListeners(this.cacheKey);this.cache.isPruning.set(this.cacheKey,!0),await this.db.bulkDocs(e.map(n=>({...n,_deleted:!0}))),this.cache.isPruning.set(this.cacheKey,!1),t(),Zt.debug("Finished pruning command history items")}catch(t){Zt.error("An error occurred while pruning db",t)}}close(){Zt.debug("Closing table",this,this.cache.tableRegistry.get(this.cacheKey)?.size),this.cache.tableRegistry.get(this.cacheKey)?.delete(this),this.changes?.cancel(),super.close()}}const Mc=Cx,Lc=ne.module("PouchCommandHistoryCache");class bx{constructor(){this.isPruning=new Map,this.response=new Map,this.tableRegistry=new Map}isPruning;response;tableRegistry;pauseChangeListeners(e){const t=[];return this.tableRegistry.get(e)?.forEach(n=>{n.changes&&(Lc.debug(`Pausing event listeners on '${e}' table`,n),n.changes.cancel(),t.push(n))}),()=>{t.forEach(n=>{(this.tableRegistry.get(e)?.has(n)??!1)&&(Lc.debug(`Resuming event listeners on '${e}' table`,n),n.listenForChanges())})}}}const Sx=bx,Oc=ne.module("PouchCommandHistoryStorage");class wx{cache=new Sx;updateTableMap=new Map;getUpdateTable(e){return this.updateTableMap.has(e)||this.updateTableMap.set(e,new Mc(e,this.cache)),this.updateTableMap.get(e)}async getTable(e){return new Mc(e,this.cache)}async addItem(e,t,n,s){return this.updateItem(e,{id:`${new Date().getTime()}`,name:n,data:s})}async updateItem(e,t){const n=this.getUpdateTable(e),i={...await n.refreshItem(t.id)??{},...t};return Oc.debug("Updating item",i),await n.put(i),Oc.debug("Update saved"),t}listenItem(e,t,n){return this.getUpdateTable(e).onItemUpdate(t,n)}}const Ku="SET_LAYOUT_STORAGE",vx=c=>({type:Ku,payload:c}),Yu=""+new URL("community-wordmark-app-d2c5c1eb.svg",import.meta.url).href;const Tx=ne.module("FormattingSectionContent");function Ex(c){return c.formatString!=null}function nr(c){const e=c?.querySelector("input, select, textarea");e&&e.focus()}function qu(c,e){return c.defaultFormatString===e.defaultFormatString}function yx(c,e){return qu(c,e)}function Rx(c,e){return qu(c,e)}function Xu(c){return c!==""&&Ii.isValidColumnName(c)}function Ss(c,e){if(!c||e.formatString==null||!Ex(e))return!1;switch(c){case"datetime":return ct.isValid(e);case"decimal":return Ke.isValid(e);case"int":return dt.isValid(e);default:return Tx.warn("Trying to validate format of unknown type"),!0}}function Zu(c){const{id:e,isNewRule:t,...n}=c;return n}function Qu(c){return Xu(c.columnName)&&Ss(c.columnType,c.format)}function Ju(c){const{timestamp:e,timeZone:t,showTimeZone:n,showTSeparator:s,isGlobalOptions:i,legacyGlobalFormat:o}=c,l=new gn([],{timeZone:t,showTimeZone:n,showTSeparator:s}),a=i?ct.getGlobalFormats(n,s):ct.getFormats(n,s);return o!=null&&!a.includes(o)&&a.unshift(o),r.jsx(r.Fragment,{children:a.map(d=>{const h=ct.makeFormat("",d,ct.TYPE_GLOBAL);return r.jsx("option",{value:d,"data-testid":"time-format",children:l.getFormattedString(e,F.dataType.DATETIME,"",h)},d)})})}function xx(){return r.jsx(r.Fragment,{children:jl.TIME_ZONES.map(c=>{const{label:e,value:t}=c;return r.jsx("option",{value:t,children:e},t)})})}const _s=ne.module("FormattingSectionContent");class sd extends v.PureComponent{static defaultProps={scrollTo:()=>{},defaults:{defaultDateTimeFormat:ct.DEFAULT_DATETIME_FORMAT_STRING,defaultDecimalFormatOptions:{defaultFormatString:Ke.DEFAULT_FORMAT_STRING},defaultIntegerFormatOptions:{defaultFormatString:dt.DEFAULT_FORMAT_STRING},showTimeZone:!1,showTSeparator:!0,timeZone:ct.DEFAULT_TIME_ZONE_ID}};static inputDebounceTime=250;constructor(e){super(e),this.debouncedCommitChanges=Ye(this.commitChanges.bind(this),sd.inputDebounceTime),this.handleDefaultDateTimeFormatChange=this.handleDefaultDateTimeFormatChange.bind(this),this.handleDefaultDecimalFormatChange=this.handleDefaultDecimalFormatChange.bind(this),this.handleDefaultIntegerFormatChange=this.handleDefaultIntegerFormatChange.bind(this),this.handleShowTimeZoneChange=this.handleShowTimeZoneChange.bind(this),this.handleShowTSeparatorChange=this.handleShowTSeparatorChange.bind(this),this.handleTimeZoneChange=this.handleTimeZoneChange.bind(this),this.handleResetDateTimeFormat=this.handleResetDateTimeFormat.bind(this),this.handleResetDecimalFormat=this.handleResetDecimalFormat.bind(this),this.handleResetIntegerFormat=this.handleResetIntegerFormat.bind(this),this.handleResetTimeZone=this.handleResetTimeZone.bind(this),this.handleTruncateNumbersWithPoundChange=this.handleTruncateNumbersWithPoundChange.bind(this);const{formatter:t,defaultDateTimeFormat:n,defaultDecimalFormatOptions:s,defaultIntegerFormatOptions:i,showTimeZone:o,showTSeparator:l,timeZone:a,truncateNumbersWithPound:d}=e,h=t.map((u,m)=>({...u,id:m}));this.containerRef=de.createRef(),this.state={formatSettings:h,showTimeZone:o,showTSeparator:l,timeZone:a,defaultDateTimeFormat:n,defaultDecimalFormatOptions:s,defaultIntegerFormatOptions:i,truncateNumbersWithPound:d,timestampAtMenuOpen:new Date}}componentDidMount(){nr(this.containerRef.current)}componentWillUnmount(){this.debouncedCommitChanges.flush()}debouncedCommitChanges;containerRef;getCachedDateTimeFormatOptions=Re((e,t,n,s=!1,i)=>{const{timestampAtMenuOpen:o}=this.state;return r.jsx(Ju,{timestamp:o,timeZone:e,showTimeZone:t,showTSeparator:n,isGlobalOptions:s,legacyGlobalFormat:i})});handleDefaultDateTimeFormatChange(e){_s.debug("handleDefaultDateTimeFormatChange",e.target.value),this.setState({defaultDateTimeFormat:e.target.value},()=>{this.debouncedCommitChanges()})}handleDefaultDecimalFormatChange(e){_s.debug("handleDefaultDecimalFormatChange",e.target.value),this.setState({defaultDecimalFormatOptions:{defaultFormatString:e.target.value}},()=>{this.debouncedCommitChanges()})}handleDefaultIntegerFormatChange(e){_s.debug("handleDefaultIntegerFormatChange",e.target.value),this.setState({defaultIntegerFormatOptions:{defaultFormatString:e.target.value}},()=>{this.debouncedCommitChanges()})}handleShowTimeZoneChange(){this.setState(e=>({showTimeZone:!e.showTimeZone}),()=>{this.debouncedCommitChanges()})}handleShowTSeparatorChange(){this.setState(e=>({showTSeparator:!e.showTSeparator}),()=>{this.debouncedCommitChanges()})}handleTimeZoneChange(e){this.setState({timeZone:e.target.value},()=>{this.debouncedCommitChanges()})}handleResetDateTimeFormat(){const{defaults:e}=this.props,{defaultDateTimeFormat:t,showTimeZone:n,showTSeparator:s}=e;_s.debug("handleResetDateTimeFormat"),this.setState({defaultDateTimeFormat:t,showTimeZone:n,showTSeparator:s},()=>{this.debouncedCommitChanges()})}handleResetTimeZone(){const{defaults:e}=this.props,{timeZone:t}=e;_s.debug("handleResetTimeZone"),this.setState({timeZone:t},()=>{this.debouncedCommitChanges()})}handleResetDecimalFormat(){const{defaults:e}=this.props,{defaultDecimalFormatOptions:t}=e;_s.debug("handleResetDecimalFormat"),this.setState({defaultDecimalFormatOptions:t},()=>{this.debouncedCommitChanges()})}handleResetIntegerFormat(){const{defaults:e}=this.props,{defaultIntegerFormatOptions:t}=e;_s.debug("handleResetIntegerFormat"),this.setState({defaultIntegerFormatOptions:t},()=>{this.debouncedCommitChanges()})}handleTruncateNumbersWithPoundChange(){this.setState(e=>({truncateNumbersWithPound:!e.truncateNumbersWithPound}),()=>{this.debouncedCommitChanges()})}commitChanges(){const{formatSettings:e,defaultDateTimeFormat:t,showTimeZone:n,showTSeparator:s,timeZone:i,defaultDecimalFormatOptions:o,defaultIntegerFormatOptions:l,truncateNumbersWithPound:a}=this.state,d=e.filter(Qu).map(Zu)??[],{settings:h,saveSettings:u}=this.props,m={...h,formatter:d,defaultDateTimeFormat:t,showTimeZone:n,showTSeparator:s,timeZone:i,truncateNumbersWithPound:a};Ss(F.dataType.DECIMAL,Ke.makeCustomFormat(o.defaultFormatString))&&(m.defaultDecimalFormatOptions=o),Ss(F.dataType.INT,dt.makeCustomFormat(l.defaultFormatString))&&(m.defaultIntegerFormatOptions=l),u(m)}render(){const{defaults:e}=this.props,{defaultDateTimeFormat:t,defaultDecimalFormatOptions:n,defaultIntegerFormatOptions:s,timeZone:i,showTimeZone:o,showTSeparator:l,truncateNumbersWithPound:a}=this.state,{defaultFormatString:d=Ke.DEFAULT_FORMAT_STRING}=n??{},{defaultFormatString:h=dt.DEFAULT_FORMAT_STRING}=s??{},u=i===e.timeZone,m=l===e.showTSeparator&&o===e.showTimeZone&&t===e.defaultDateTimeFormat,g=yx(n,e.defaultDecimalFormatOptions),p=Rx(s,e.defaultIntegerFormatOptions);return r.jsx("div",{className:"app-settings-formatting-section",ref:this.containerRef,children:r.jsxs("div",{className:"container-fluid p-0",children:[r.jsx("div",{className:"app-settings-menu-description mb-3",children:"Choose the default formatting rule to apply to all table columns based on their type."}),r.jsxs("div",{className:"form-row mb-2",children:[r.jsx("label",{className:"col-form-label col-3",htmlFor:"select-reset-timezone",children:"Time zone"}),r.jsx("div",{className:"col pr-0",children:r.jsx("select",{className:"custom-select",value:i,onChange:this.handleTimeZoneChange,id:"select-reset-timezone",children:r.jsx(xx,{})})}),r.jsx("div",{className:"col-1 btn-col",children:r.jsx(B,{kind:"ghost",icon:Ws,onClick:this.handleResetTimeZone,tooltip:"Reset Time Zone",className:Y("btn-reset","btn-reset-time-zone",{hidden:u})})})]}),r.jsxs("div",{className:"form-row mb-2",children:[r.jsx("label",{className:"col-form-label col-3",htmlFor:"select-default-time-format",children:"DateTime"}),r.jsx("div",{className:"col pr-0",children:r.jsx("select",{className:"custom-select",value:t,onChange:this.handleDefaultDateTimeFormatChange,id:"select-default-time-format",children:this.getCachedDateTimeFormatOptions(i,o,l,!0,t)})}),r.jsx("div",{className:"col-1 btn-col",children:r.jsx(B,{kind:"ghost",icon:Ws,onClick:this.handleResetDateTimeFormat,tooltip:"Reset DateTime Options",className:Y("btn-reset","btn-reset-date-time",{hidden:m})})})]}),r.jsx("div",{className:"form-row",children:r.jsx("div",{className:"offset-3 col-9",children:r.jsx(nn,{checked:o??null,onChange:this.handleShowTimeZoneChange,children:"Show time zone in dates"})})}),r.jsx("div",{className:"form-row mb-3",children:r.jsx("div",{className:"offset-3 col-9",children:r.jsx(nn,{checked:l??null,onChange:this.handleShowTSeparatorChange,children:"Show 'T' separator"})})}),r.jsxs("div",{className:"form-row mb-2",children:[r.jsx("label",{className:"col-form-label col-3",htmlFor:"default-decimal-format-input",children:"Decimal"}),r.jsx("div",{className:"col pr-0",children:r.jsx("input",{className:Y("form-control","flex-grow-1","default-decimal-format-input",{"is-invalid":!Ss(F.dataType.DECIMAL,Ke.makeCustomFormat(d))}),"data-lpignore":!0,placeholder:Ke.DEFAULT_FORMAT_STRING,type:"text",id:"default-decimal-format-input",value:d,onChange:this.handleDefaultDecimalFormatChange})}),r.jsx("div",{className:"col-1 btn-col",children:r.jsx(B,{kind:"ghost",icon:Ws,onClick:this.handleResetDecimalFormat,tooltip:"Reset Decimal Formatting",className:Y("btn-reset","btn-reset-decimal",{hidden:g}),"data-testid":"btn-reset-decimal"})})]}),r.jsxs("div",{className:"form-row mb-2",children:[r.jsx("label",{className:"col-form-label col-3",htmlFor:"default-integer-format-input",children:"Integer"}),r.jsx("div",{className:"col pr-0",children:r.jsx("input",{className:Y("form-control","flex-grow-1","default-integer-format-input",{"is-invalid":!Ss(F.dataType.INT,dt.makeCustomFormat(h))}),"data-lpignore":!0,placeholder:dt.DEFAULT_FORMAT_STRING,type:"text",id:"default-integer-format-input",value:h,onChange:this.handleDefaultIntegerFormatChange})}),r.jsx("div",{className:"col-1 btn-col",children:r.jsx(B,{kind:"ghost",icon:Ws,onClick:this.handleResetIntegerFormat,tooltip:"Reset Integer Formatting",className:Y("btn-reset","btn-reset-integer",{hidden:p}),"data-testid":"btn-reset-integer"})})]}),r.jsx("div",{className:"form-row mb-3",children:r.jsx("div",{className:"offset-3 col-9",children:r.jsx(nn,{checked:a??null,onChange:this.handleTruncateNumbersWithPoundChange,children:"Truncate numbers with #"})})})]})})}}const Dx=c=>({formatter:Rh(c),defaultDateTimeFormat:Th(c),defaultDecimalFormatOptions:Eh(c),defaultIntegerFormatOptions:yh(c),showTimeZone:xh(c),showTSeparator:Dh(c),truncateNumbersWithPound:Ih(c),timeZone:po(c),settings:wt(c)}),Ix=St(Dx,{saveSettings:Zl})(sd);function Fx(){const[c,e]=v.useState(!1),t=()=>{e(!c)};return r.jsxs(B,{kind:"ghost",onClick:t,icon:Xg,children:["Legal Notices",r.jsxs(Gl,{isOpen:c,toggle:t,className:"theme-bg-light",children:[r.jsx(zl,{toggle:t,children:"Legal Notice"}),r.jsxs(Kl,{children:[r.jsx("p",{children:"Deephaven software is protected by U.S. Patent Nos. 9,612,959; 9,613,018; 9,613,109; 9,619,210; 9,633,060; 9,639,570; 9,672,238; 9,679,006; 9,690,821; 9,710,511; 9,760,591; 9,805,084; 9,836,495; 9,836,494; 9,886,469; 9,898,496; 9,934,266; 10,002,153; 10,002,154; 10,002,155; 10,003,673; 10,019,138; 10,069,943; 10,176,211; 10,198,465; 10,198,466; 10,198,469; 10,212,257; 10,241,960; 10,241,965; 10,242,040; 10,242,041; 10,353,893; 10,346,394; 10,452,649; 10,496,639; 10,540,351; 10,552,412; 10,565,194; 10,565,206; 10,572,474; 10,621,168; 10,642,829; 10,657,184; 10,678,787; 10,691,686; and 10,783,191. Other patents pending."}),r.jsxs("p",{children:["© 2016-",new Date().getFullYear()," Deephaven Data Labs LLC. Patent Pending."]})]})]})]})}function io(c){const{children:e,isExpanded:t,sectionKey:n,title:s,onToggle:i}=c;return r.jsxs(r.Fragment,{children:[r.jsx("div",{children:r.jsxs(B,{kind:"ghost",className:"btn-collapse-trigger",onClick:()=>i(n),children:[r.jsx("div",{className:"flex-grow-1",children:s}),r.jsx("div",{className:"flex-shrink-0",children:r.jsx(ee,{transform:t?"flip-v":"",icon:Un})})]})}),r.jsx(Um,{in:t,autoFocusOnShow:!0,children:e})]})}io.propTypes={children:z.node,isExpanded:z.bool.isRequired,sectionKey:z.string.isRequired,title:z.node.isRequired,onToggle:z.func};io.defaultProps={children:null,onToggle:()=>{}};function Nx({shortcut:c,displayText:e,categoryName:t,onChange:n}){const[s,i]=v.useState(e),[o,l]=v.useState(c.getKeyState()),[a,d]=v.useState(!1),[h,u]=v.useState("");v.useEffect(function(){i(e),l(c.getKeyState())},[e,c]),v.useEffect(function(){i(sn.getDisplayText(o)),c.matchesKeyState(o)&&d(!1)},[o,c]),v.useEffect(function(){if(a){if(!sn.isValidKeyState(o)){sn.isAllowedKey(o.keyValue)?u("Must contain a modifier key"):u("Must contain an allowed action key");return}const T=We.getConflictingShortcuts(o).filter(y=>y.id.startsWith(t)&&y!==c).map(y=>y.name);if(T.length){u(`Conflicts with ${T.join(", ")}`);return}u("")}else u("")},[a,o,t,c]);function m(S){if(S.stopPropagation(),S.preventDefault(),c.isEditable&&!S.repeat){const T=sn.getKeyStateFromEvent(S),y=sn.createKeyState([xe.BACKSPACE]);sn.doKeyStatesMatch(T,y)?l(sn.NULL_KEY_STATE):l(T)}}function g(S){S.stopPropagation(),S.preventDefault(),c.matchesKeyState(o)||d(!0)}function p(){Ts.disableAllActions()}function C(){Ts.enableAllActions()}function f(){c.setKeyState(o),d(!1),n(c)}function b(){const S=c.getKeyState();l(S),d(!1)}function w(){d(!0),l(c.getDefaultKeyState())}return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"shortcut-item-container",children:[r.jsxs("label",{className:"shortcut-item-name",children:[c.name,c.tooltip!==void 0&&r.jsx(ot,{children:c.tooltip})]}),r.jsxs("div",{className:"shortcut-item-input-container",children:[r.jsx("input",{className:Y("form-control",{"is-invalid":h}),onKeyDown:m,onKeyUp:g,onFocus:p,onBlur:C,disabled:!c.isEditable,value:s,readOnly:!0}),!sn.doKeyStatesMatch(o,c.getDefaultKeyState())&&!h&&r.jsx(B,{className:"reset-to-default-button",kind:"ghost",icon:r.jsx(ee,{icon:Ws,transform:{rotate:90,flipX:!0}}),tooltip:"Reset to default",onClick:w})]})]}),a&&r.jsxs("div",{className:Y("shortcut-item-message-container",{"is-invalid":h}),children:[r.jsx("div",{className:"shortcut-item-message",children:h}),r.jsxs("div",{className:"shortcut-item-message-buttons",children:[sn.isValidKeyState(o)&&r.jsx(B,{kind:"ghost",onClick:f,children:"Confirm"}),r.jsx(B,{kind:"ghost",onClick:b,children:"Undo"})]})]})]})}function kx({shortcutOverrides:c={},settings:e,saveSettings:t}){const n=v.useCallback(l=>{const a=sn.isMacPlatform,d={mac:{...c.mac},windows:{...c.windows}},h=a?d.mac:d.windows;l.forEach(u=>{u.isDefault()?delete h[u.id]:h[u.id]=u.getKeyState()}),t({...e,shortcutOverrides:d})},[e,t,c]);let s=Array.from(We.shortcutsByCategory.entries()).map(([l,a])=>({name:l,shortcuts:a}));const i=s.findIndex(l=>l.name.toUpperCase()==="GLOBAL"),o=s.splice(i,1);return s=s.concat(o),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"app-settings-menu-description",children:"Customize shortcuts below. To prevent unexpected results, avoid conflicting shortcuts with the browser or IDE editor."}),s.map(l=>r.jsx(Mx,{name:l.name,shortcuts:l.shortcuts,saveShortcutOverrides:n},l.name))]})}function Mx({name:c,shortcuts:e,saveShortcutOverrides:t}){function n(a){return a.split("_").map(d=>`${d[0].toUpperCase()}${d.slice(1).toLowerCase()}`).join(" ")}const[s,i]=v.useState(e);function o(a){const d=s.filter(u=>u!==a&&!u.isNull()&&u.matchesKeyState(a.getKeyState()));d.forEach(u=>u.setToNull());const h=[a,...d];t(h),i(u=>[...u])}const l=v.useMemo(()=>s.map(a=>a.getDisplayText()),[s]);return r.jsxs("div",{className:"mt-3",children:[r.jsx("div",{className:"font-weight-bold",children:n(c)}),s.map((a,d)=>r.jsx(Nx,{shortcut:a,displayText:l[d],categoryName:c,onChange:o},a.id))]})}const Lx=c=>({settings:wt(c),shortcutOverrides:fC(c)}),Ox={saveSettings:Zl},Ax=St(Lx,Ox)(kx),_x="yyyy-MM-dd-HHmmss";function em(c,e="root",t=new Map([[c,""]])){const n={};return Object.entries(c).forEach(([s,i])=>{try{JSON.stringify(i),n[s]=i}catch{const l=i;if(typeof i=="bigint")n[s]=i.toString();else if(t.has(l))n[s]=`Circular ref to ${t.get(l)}`;else{const a=`${e}.${s}`;t.set(l,a),n[s]=em(i,a,t)}}}),n}function Px(){const c=yr.getState();return JSON.stringify(em(c),null,2)}function jx(c){const e={uiVersion:"0.38.0",userAgent:navigator.userAgent,...c};return JSON.stringify(e,null,2)}async function Hx(c=`${I.i18n.DateTimeFormat.format(_x,new Date)}_support_logs`,e){const t=new Wc,n=t.folder(c);n.file("console.txt",Zg.getFormattedHistory()),n.file("redux.json",Px()),n.file("metadata.json",jx(e));const s=await t.generateAsync({type:"blob"}),i=document.createElement("a");i.href=URL.createObjectURL(s),i.download=`${c}.zip`,i.click()}const Bx=[{value:F.dataType.DATETIME,label:"DateTime"},{value:F.dataType.DECIMAL,label:"Decimal"},{value:F.dataType.INT,label:"Integer"}];function Ux(){const c=Bx.map(e=>r.jsx("option",{value:e.value,children:e.label},`key-columnType-${e.value}`));return r.jsxs(r.Fragment,{children:[r.jsx("option",{disabled:!0,value:"",children:"Select Type"},"key-columnType-placeholder"),c]})}class id extends v.PureComponent{static defaultProps={scrollTo:()=>{},defaults:{defaultDateTimeFormat:ct.DEFAULT_DATETIME_FORMAT_STRING,defaultDecimalFormatOptions:{defaultFormatString:Ke.DEFAULT_FORMAT_STRING},defaultIntegerFormatOptions:{defaultFormatString:dt.DEFAULT_FORMAT_STRING},showTimeZone:!1,showTSeparator:!0,timeZone:ct.DEFAULT_TIME_ZONE_ID}};static inputDebounceTime=250;constructor(e){super(e),this.debouncedCommitChanges=Ye(this.commitChanges.bind(this),id.inputDebounceTime),this.handleFormatRuleEntered=this.handleFormatRuleEntered.bind(this),this.handleFormatRuleChange=this.handleFormatRuleChange.bind(this),this.handleFormatRuleCreate=this.handleFormatRuleCreate.bind(this),this.handleFormatRuleDelete=this.handleFormatRuleDelete.bind(this);const{formatter:t,defaultDateTimeFormat:n,defaultDecimalFormatOptions:s,defaultIntegerFormatOptions:i,showTimeZone:o,showTSeparator:l,timeZone:a,truncateNumbersWithPound:d}=e,h=t.map((u,m)=>({...u,id:m}));this.containerRef=de.createRef(),this.addFormatRuleButtonRef=de.createRef(),this.lastFormatRuleIndex=h.length,this.state={formatSettings:h,formatRulesChanged:!1,showTimeZone:o,showTSeparator:l,timeZone:a,defaultDateTimeFormat:n,defaultDecimalFormatOptions:s,defaultIntegerFormatOptions:i,truncateNumbersWithPound:d,timestampAtMenuOpen:new Date}}componentDidMount(){nr(this.containerRef.current)}componentWillUnmount(){this.debouncedCommitChanges.flush()}debouncedCommitChanges;containerRef;addFormatRuleButtonRef;lastFormatRuleIndex;isDuplicateRule(e){const{formatSettings:t}=this.state;return t.some(n=>n.id!==e.id&&n.columnName===e.columnName&&n.columnType===e.columnType)??!1}getAutoIncrementFormatRuleIndex(){const{lastFormatRuleIndex:e}=this;return this.lastFormatRuleIndex+=1,e}getCachedColumnTypeOptions=Re(()=>r.jsx(Ux,{}));getCachedDateTimeFormatOptions=Re((e,t,n,s=!1,i)=>{const{timestampAtMenuOpen:o}=this.state;return r.jsx(Ju,{timestamp:o,timeZone:e,showTimeZone:t,showTSeparator:n,isGlobalOptions:s,legacyGlobalFormat:i})});handleFormatRuleChange(e,t,n){this.setState(s=>{const{formatSettings:i}=s;N(i);const o=[...i];let l={};t==="columnType"&&(l={format:""});const a={...o[e],...l,[t]:n};return o[e]=a,{formatSettings:o}},()=>{this.debouncedCommitChanges()})}handleFormatRuleCreate(){this.setState(e=>{const{formatSettings:t}=e,n={columnType:F.dataType.DATETIME,columnName:"",format:{},id:this.getAutoIncrementFormatRuleIndex(),isNewRule:!0};return{formatSettings:[...t,n],formatRulesChanged:!0}})}handleFormatRuleDelete(e){this.setState(t=>{const{formatSettings:n}=t;return{formatSettings:n.filter((i,o)=>o!==e),formatRulesChanged:!0}},()=>{this.debouncedCommitChanges()})}handleFormatRuleEntered(e){this.scrollToFormatBlockBottom(),nr(e)}commitChanges(){const{formatSettings:e,defaultDateTimeFormat:t,showTimeZone:n,showTSeparator:s,timeZone:i,defaultDecimalFormatOptions:o,defaultIntegerFormatOptions:l,truncateNumbersWithPound:a}=this.state,d=e.filter(Qu).map(Zu)??[],{settings:h,saveSettings:u}=this.props,m={...h,formatter:d,defaultDateTimeFormat:t,showTimeZone:n,showTSeparator:s,timeZone:i,truncateNumbersWithPound:a};Ss(F.dataType.DECIMAL,Ke.makeCustomFormat(o.defaultFormatString))&&(m.defaultDecimalFormatOptions=o),Ss(F.dataType.INT,dt.makeCustomFormat(l.defaultFormatString))&&(m.defaultIntegerFormatOptions=l),u(m)}scrollToFormatBlockBottom(){const{scrollTo:e}=this.props;e(0,(this.addFormatRuleButtonRef.current?.offsetHeight??0)+(this.addFormatRuleButtonRef.current?.offsetTop??0))}getRuleError(e){const t={hasColumnNameError:!1,hasFormatError:!1,message:""},n=[];return e.isNewRule!==void 0&&e.isNewRule||(this.isDuplicateRule(e)&&(t.hasColumnNameError=!0,n.push("Duplicate column name/type combo.")),Xu(e.columnName)||(t.hasColumnNameError=!0,n.push("Column names must start with a letter or underscore and contain only alphanumeric characters or underscores.")),e.format.formatString!==void 0&&e.format.formatString.length===0?(t.hasFormatError=!0,n.push("Empty formatting rule.")):Ss(e.columnType,e.format)||(t.hasFormatError=!0,n.push("Invalid formatting rule.")),t.message=n.join(`
38
38
  `)),t}renderFormatRule(e,t){const n=`input-${e}-columnName`,s=`input-${e}-columnType`,i=`input-${e}-format`,o=this.getCachedColumnTypeOptions(),l=u=>this.handleFormatRuleChange(e,"columnName",u.target.value),a=()=>this.handleFormatRuleChange(e,"isNewRule",!1),d=u=>this.handleFormatRuleChange(e,"columnType",u.target.value),h=this.getRuleError(t);return r.jsxs("fieldset",{className:"container-fluid format-rule-container",children:[r.jsxs("div",{className:"form-row",children:[r.jsxs("div",{className:"form-group col-7 mb-2",children:[r.jsx("label",{htmlFor:n,children:"Column Name"}),r.jsx("input",{id:n,className:Y("form-control",{"is-invalid":h.hasColumnNameError}),"data-lpignore":!0,type:"text",value:t.columnName,onChange:l,onBlur:a})]}),r.jsxs("div",{className:"form-group col mb-2",children:[r.jsx(B,{kind:"ghost",className:"btn-delete-format-rule float-right",tabIndex:-1,onClick:()=>this.handleFormatRuleDelete(e),icon:Gt,tooltip:"Delete","aria-label":"Delete Format Rule"}),r.jsx("label",{htmlFor:s,children:"Column Type"}),r.jsx("select",{id:s,className:"custom-select",value:t.columnType,onChange:d,children:o})]})]}),r.jsx("div",{className:"form-row",children:r.jsxs("div",{className:"form-group col-12 d-flex mb-2",children:[r.jsx("label",{className:"flex-shrink-0 col-form-label mr-3",htmlFor:i,children:"Formatting Rule"}),this.renderFormatRuleInput(e,t.columnType,i,t.format,h.hasFormatError)]})}),r.jsx("div",{className:"form-row",children:r.jsx("div",{className:"form-group col-12 d-flex mb-2",children:h.message&&r.jsx("p",{className:"text-danger",children:h.message})})})]},e)}renderFormatRuleInput(e,t,n,s,i){switch(F.getNormalizedType(t)){case F.dataType.DATETIME:return this.renderDateTimeFormatRuleInput(e,n,s,i);case F.dataType.DECIMAL:return this.renderDecimalFormatRuleInput(e,n,s,i);case F.dataType.INT:return this.renderIntegerFormatRuleInput(e,n,s,i);default:throw new Error(`Unrecognized column type: ${t}`)}}renderDateTimeFormatRuleInput(e,t,n,s){const{showTimeZone:i,showTSeparator:o,timeZone:l}=this.state,a=n.formatString??"";return r.jsxs("select",{className:Y("custom-select",{"is-invalid":s}),value:a,id:t,onChange:d=>{const h=ct.makeFormat("",d.target.value,ct.TYPE_GLOBAL);this.handleFormatRuleChange(e,"format",h)},children:[r.jsx("option",{value:"",disabled:!0,children:"Select format"},"default"),this.getCachedDateTimeFormatOptions(l,i,o)]})}renderIntegerFormatRuleInput(e,t,n,s){const i=n.formatString??"";return r.jsx("input",{className:Y("form-control","flex-grow-1",{"is-invalid":s}),"data-lpignore":!0,id:t,placeholder:dt.DEFAULT_FORMAT_STRING,type:"text",value:i,onChange:o=>{const l=dt.makeFormat("",o.target.value,dt.TYPE_GLOBAL,void 0);this.handleFormatRuleChange(e,"format",l)}})}renderDecimalFormatRuleInput(e,t,n,s){const i=n.formatString??"";return r.jsx("input",{className:Y("form-control","flex-grow-1",{"is-invalid":s}),"data-lpignore":!0,id:t,placeholder:Ke.DEFAULT_FORMAT_STRING,type:"text",value:i,onChange:o=>{const l=Ke.makeFormat("",o.target.value,Ke.TYPE_GLOBAL,void 0);this.handleFormatRuleChange(e,"format",l)}})}render(){const{formatRulesChanged:e,formatSettings:t}=this.state,n=t.map((i,o)=>r.jsx(Wt,{classNames:"fade",timeout:Je.transitionMs,onEnter:this.handleFormatRuleEntered,children:this.renderFormatRule(o,i)},i.id)),s=r.jsx(B,{kind:"ghost",className:"mb-3",onClick:this.handleFormatRuleCreate,ref:this.addFormatRuleButtonRef,icon:Es,children:"Add New Rule"});return r.jsxs("div",{className:"app-settings-formatting-section",ref:this.containerRef,children:[r.jsx("div",{className:"app-settings-menu-description mb-3",children:"Customize the formatting of table columns by applying rules based on matching both a column name and column type."}),r.jsx(Im,{appear:e,enter:e,exit:e,children:n}),s]})}}const Vx=c=>({formatter:Rh(c),defaultDateTimeFormat:Th(c),defaultDecimalFormatOptions:Eh(c),defaultIntegerFormatOptions:yh(c),showTimeZone:xh(c),showTSeparator:Dh(c),truncateNumbersWithPound:Ih(c),timeZone:po(c),settings:wt(c)}),$x=St(Vx,{saveSettings:Zl})(id);class En extends v.Component{static defaultProps={onDone:()=>{}};static FORMATTING_SECTION_KEY="SettingsMenu.formatting";static COLUMN_SPECIFIC_SECTION_KEY="SettingsMenu.columnFormatting";static APPLICATION_SECTION_KEY="ApplicationMenu.settings";static SHORTCUT_SECTION_KEY="SettingsMenu.shortcuts";static focusFirstInputInContainer(e){const t=e?.querySelector("input, select, textarea");t&&t.focus()}constructor(e){super(e),this.handleClose=this.handleClose.bind(this),this.handleScrollTo=this.handleScrollTo.bind(this),this.handleSectionToggle=this.handleSectionToggle.bind(this),this.handleExportSupportLogs=this.handleExportSupportLogs.bind(this),this.handleLogout=this.handleLogout.bind(this),this.menuContentRef=de.createRef(),this.broadcastChannel=new BroadcastChannel(Vm),this.state={expandedSectionKey:En.FORMATTING_SECTION_KEY}}componentDidMount(){En.focusFirstInputInContainer(this.menuContentRef.current)}componentWillUnmount(){this.broadcastChannel.close()}menuContentRef;broadcastChannel;isSectionExpanded(e){const{expandedSectionKey:t}=this.state;return t===e}handleLogout(){this.broadcastChannel.postMessage($m(Wm))}handleScrollTo(e,t){this.menuContentRef.current?.scrollTo(e,t)}handleSectionToggle(e){this.setState(t=>({expandedSectionKey:t.expandedSectionKey===e?void 0:e}))}handleClose(){const{onDone:e}=this.props;e()}handleExportSupportLogs(){const{serverConfigValues:e}=this.props;Hx(void 0,Object.fromEntries(e))}render(){const e="0.38.0",t="https://github.com/deephaven/web-client-ui/",n="https://deephaven.io/core/docs/",{serverConfigValues:s,user:i}=this.props,o=s.get("barrage.version"),l=s.get("java.version"),a=s.get("deephaven.version"),d=(g,p)=>r.jsxs(r.Fragment,{children:[r.jsx("div",{children:g}),r.jsx("div",{children:p})]}),h=i.displayName??i.name,u=i.image!=null&&i.image!=="",m=h!=="";return r.jsxs("div",{className:"app-settings-menu",children:[r.jsxs("header",{className:"app-settings-menu-header",children:[r.jsxs("div",{className:"user-info",children:[r.jsxs("div",{className:"user-image",children:[!u&&r.jsx(ee,{icon:Qg,transform:"grow-8"}),u&&r.jsx("img",{src:i.image,alt:h})]}),r.jsxs("div",{className:"user-details",children:[m&&r.jsxs("div",{className:"user-name",children:[h,i.operateAs!=null&&i.name!==i.operateAs&&r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"font-weight-light font-italic",children:[" ","as"," "]}),r.jsxs("span",{className:"operating-as-user",children:[r.jsx(ee,{icon:Jg,className:"mr-1"}),i.operateAs]})]})]}),i.permissions.canLogout&&r.jsx("button",{type:"button",className:"btn btn-link",onClick:this.handleLogout,children:"logout"})]})]}),r.jsx(B,{kind:"ghost",className:"btn-close-settings-menu",onClick:this.handleClose,icon:r.jsx(ee,{icon:uo,transform:"grow-4"}),tooltip:"Close"})]}),r.jsxs("div",{className:"app-settings-menu-content",ref:this.menuContentRef,children:[r.jsx("h5",{children:"Settings"}),r.jsx("hr",{className:"my-0"}),r.jsx(io,{sectionKey:En.FORMATTING_SECTION_KEY,isExpanded:this.isSectionExpanded(En.FORMATTING_SECTION_KEY),title:r.jsxs(r.Fragment,{children:[r.jsx(ee,{icon:ep,transform:"grow-4",className:"mr-2"}),"Default Format & Time zone"]}),onToggle:this.handleSectionToggle,children:r.jsx(Ix,{})}),r.jsx(io,{sectionKey:En.COLUMN_SPECIFIC_SECTION_KEY,isExpanded:this.isSectionExpanded(En.COLUMN_SPECIFIC_SECTION_KEY),title:r.jsxs(r.Fragment,{children:[r.jsx(ee,{icon:tp,transform:"grow-4",className:"mr-2"}),"Format by Column Name & Type"]}),onToggle:this.handleSectionToggle,children:r.jsx($x,{scrollTo:this.handleScrollTo})}),r.jsx(io,{sectionKey:En.SHORTCUT_SECTION_KEY,isExpanded:this.isSectionExpanded(En.SHORTCUT_SECTION_KEY),title:r.jsxs(r.Fragment,{children:[r.jsx(ee,{icon:np,transform:"grow-2"})," ","Keyboard Shortcuts"]}),onToggle:this.handleSectionToggle,children:r.jsx(Ax,{})}),r.jsxs("div",{className:"app-settings-footer",children:[r.jsxs("div",{className:"app-settings-footer-section",children:[r.jsxs("div",{className:"app-settings-footer-item",children:[r.jsx("div",{className:"font-weight-bold",children:"Support"}),r.jsxs("div",{children:["GitHub: ",r.jsx("a",{href:t,className:"custom-link",target:"_blank",rel:"noopener noreferrer",children:t})]}),r.jsx(B,{kind:"tertiary",className:"mt-2 py-2",onClick:this.handleExportSupportLogs,children:"Export Logs"})]}),r.jsxs("div",{className:"app-settings-footer-item",children:[r.jsx("div",{className:"font-weight-bold",children:"Documentation"}),r.jsx("a",{target:"_blank",rel:"noreferrer noopener",href:n,className:"custom-link",children:n})]}),r.jsxs("div",{className:"app-settings-footer-item",children:[r.jsx("div",{className:"font-weight-bold",children:"Version"}),r.jsxs("span",{className:"d-inline-block text-muted",children:[a," ",r.jsx(ee,{icon:sp}),r.jsxs(ot,{interactive:!0,children:[r.jsxs("div",{className:"detailed-server-config",children:[d("Engine Version",a),d("Web UI Version",e),d("Java Version",l),d("Barrage Version",o)]}),r.jsx(Bl,{tooltip:"Copy version numbers",copy:`Engine Version: ${a}
39
39
  Web UI Version: ${e}
40
40
  Java Version: ${l}
41
- Barrage Version: ${o}`,children:"Copy Versions"})]})]})]}),r.jsx("div",{className:"app-settings-footer-item",children:r.jsx(Fx,{})})]}),r.jsx("div",{className:"app-settings-footer-section",children:r.jsx("div",{className:"logo",children:r.jsx("a",{target:"_blank",rel:"noreferrer noopener",href:"https://deephaven.io",className:"d-inline-block custom-link p-1",children:r.jsx("img",{src:Yu,alt:"Deephaven Data Labs",width:"230px"})})})})]})]})]})}}const Ac=10;function bi(c){const{forwardedProps:{menuItem:{action:e,title:t,disabled:n},iconElement:s,displayShortcut:i,isMouseSelected:o,isKeyboardSelected:l,closeMenu:a}}=c,d=v.useRef(),h=v.useRef(),u=v.useRef(null),[m,g]=v.useState(!1),p=v.useCallback(b=>{d.current!=null&&h.current!=null&&u.current&&(Math.abs(d.current-b.clientX)>=Ac||Math.abs(h.current-b.clientY)>=Ac)&&(g(!0),window.removeEventListener("mousemove",p),a(),e(b),u.current=null)},[e,a]);function C(b){d.current=b.clientX,h.current=b.clientY,u.current=b.target,window.addEventListener("mousemove",p)}function f(b){u.current===b.target&&(g(!0),a(),e(),window.removeEventListener("mousemove",p)),u.current=null}return v.useEffect(function(){return function(){return window.removeEventListener("mousemove",p)}},[p]),r.jsxs("button",{type:"button",className:Y("btn-context-menu",{disabled:n},{active:o&&!n},{"keyboard-active":l&&!n}),onMouseDown:C,onMouseUp:f,disabled:m,children:[r.jsx("span",{className:Y("icon"),children:s}),r.jsx("span",{className:"title",children:t}),r.jsx("span",{className:"shortcut",children:i})]})}function od(c){const{handleControlSelect:e,handleToolSelect:t,onClearFilter:n}=c,s=v.useMemo(()=>[{title:"Input Filter",icon:ip,menuElement:r.jsx(bi,{}),action:i=>{e(bs.INPUT_FILTER,i)},order:10},{title:"Dropdown Filter",icon:ih,menuElement:r.jsx(bi,{}),action:i=>{e(bs.DROPDOWN_FILTER,i)},order:15},{title:"Markdown Widget",icon:op,menuElement:r.jsx(bi,{}),action:i=>{e(bs.MARKDOWN,i)},order:20},{title:"Filter Sets",icon:Ua,menuElement:r.jsx(bi,{}),action:i=>{e(bs.FILTER_SET_MANAGER,i)},order:25},{disabled:!0,menuElement:r.jsx("div",{className:"context-menu-group-header",children:"Tools"}),order:30},{title:"Linker",icon:th,action:()=>{t(Pt.LINKER)},order:40,shortcut:Kn.LINKER},{disabled:!0,menuElement:r.jsx("div",{className:"context-menu-group-header",children:"Actions"}),order:50},{title:"Clear All Filters",icon:lp,action:()=>{n()},order:60,shortcut:Ut.TABLE.CLEAR_ALL_FILTERS}],[e,t,n]);return r.jsx(Vn,{popperClassName:"controls-menu-popper",actions:s})}od.propTypes={handleControlSelect:z.func,handleToolSelect:z.func,onClearFilter:z.func};od.defaultProps={handleControlSelect:()=>{},handleToolSelect:()=>{},onClearFilter:()=>{}};bi.propTypes={forwardedProps:z.shape({iconElement:z.node,displayShortcut:z.string,isMouseSelected:z.bool.isRequired,isKeyboardSelected:z.bool.isRequired,closeMenu:z.func.isRequired,menuItem:z.shape({action:z.func,title:z.string,disabled:z.bool}).isRequired})};bi.defaultProps={forwardedProps:null};const Wx=Js(Ku,null),Gx={layoutStorage:Wx},zx=c=>c.layoutStorage,Kx=c=>c.serverConfigValues;Object.entries(Gx).map(([c,e])=>fo.register(c,e));const _c=10;function Yx(c){const{onExportLayout:e,onImportLayout:t,onResetLayout:n,onSelect:s,widgets:i=[]}=c,[o,l]=v.useState(!1),[a,d]=v.useState(""),h=v.useRef(null),u=v.useRef(),m=v.useCallback((T,y)=>{T!=null&&s(T,y)},[s]),g=v.useCallback(T=>{d(T.target.value)},[]),p=v.useCallback(T=>{u.current!=null&&(Math.abs(u.current.x-T.clientX)>=_c||Math.abs(u.current.y-T.clientY)>=_c)&&(l(!0),window.removeEventListener("mousemove",p),m(u.current.widget,T),u.current=void 0)},[u,m]),C=v.useCallback((T,y)=>{u.current={x:T.clientX,y:T.clientY,widget:y},window.addEventListener("mousemove",p)},[p]),f=v.useCallback((T,y)=>{window.removeEventListener("mousemove",p),u.current?.widget===y&&(l(!0),m(y)),u.current=void 0},[p,u,m]),b=v.useMemo(()=>i.filter(T=>a?T.name?.toLowerCase().includes(a.toLowerCase()):!0),[a,i]).sort((T,y)=>T.name?.localeCompare(y.name??"")??0),w=v.useMemo(()=>b.map(T=>r.jsx("li",{children:r.jsxs(B,{kind:"ghost","data-testid":`panel-list-item-${T.name??""}-button`,onMouseDown:y=>{C(y,T)},onMouseUp:y=>{f(y,T)},onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&m(T)},disabled:o,onClick:()=>{},children:[r.jsx(ah,{type:T.type})," ",T.name??""]})},T.name)),[b,o,C,f,m]),S=v.useMemo(()=>w.length===0?r.jsx("span",{children:"No bound variables found."}):null,[w]);return r.jsxs("div",{className:"widget-list-container d-flex flex-column",children:[r.jsx("div",{className:"widget-list-header",children:r.jsx(Di,{value:a,placeholder:"Find Table, Plot or Widget",onChange:g,ref:h})}),r.jsxs("ul",{className:"widget-list flex-grow-1",children:[S&&r.jsx("li",{className:"widget-list-message",children:S}),!S&&w]}),r.jsx("div",{children:r.jsx("hr",{})}),r.jsxs("div",{className:"widget-list-footer",children:[r.jsxs(B,{kind:"ghost",onClick:e,children:[r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx(ee,{mask:Ba,icon:vd,transform:"right-5 down-5"}),r.jsx(ee,{icon:vd,transform:"right-8 down-6"})]}),"Export Layout"]}),r.jsxs(B,{kind:"ghost",onClick:t,children:[r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx(ee,{mask:Ba,icon:Va,transform:"right-5 down-5"}),r.jsx(ee,{icon:Va,transform:"right-8 down-6"})]}),"Import Layout"]}),r.jsx(B,{kind:"ghost",icon:Ws,onClick:n,tooltip:"Reset Layout"})]})]})}const qx=async(c,e,t)=>{let n,s,i,o;if(il(e)?(n=e.settings,s=e.table,i=void 0,o=e.tableSettings):(n={},s="",i=e.figure,o={}),t!==void 0&&(t.tableSettings!=null&&(o=t.tableSettings),t.table!=null&&(s=t.table),t.figure!=null&&(i=t.figure),t.settings!=null&&(n={...n,...t.settings})),i!==void 0){const d={title:i,name:i,type:I.VariableType.FIGURE},h=await c.getObject(d);return fl.makeModel(n,h)}const l={title:i,name:s,type:I.VariableType.TABLE},a=await c.getObject(l);return Se.applyTableSettings(a,o,po(yr.getState())),fl.makeModelFromSettings(n,a)},Xx=async(c,e,t=I.VariableType.TABLE)=>{const{table:n}=e,s={title:n,name:n,type:t},i=await c.getObject(s);return Wr.makeModel(i)};function Zx({onAutoFillClick:c=()=>{}}){return r.jsxs("div",{className:"empty-dashboard-container",children:[r.jsxs("div",{className:"hint-container",children:[r.jsx(ee,{icon:sh})," ",r.jsx("br",{}),"Use the panel list to add objects from a query."]}),r.jsxs("div",{className:"empty-dashboard",children:[r.jsx("div",{className:"add-panels-hint",children:"Drag Panels Here"}),r.jsx(B,{kind:"tertiary",onClick:c,children:"Auto fill objects"})]})]})}function Qx(c){return c.version===2}function Jx(c){return Array.isArray(c)}const el=ne.module("UserLayoutUtils"),e0={layoutConfig:[{type:"column",content:[{type:"row",height:40,content:[{type:"stack",content:[{type:"react-component",component:Ci.COMPONENT,title:Ci.TITLE,isClosable:!1},{type:"react-component",component:Ol.COMPONENT,title:Ol.TITLE,isClosable:!1}]},{type:"stack",width:25,content:[{type:"react-component",component:Il.COMPONENT,title:Il.TITLE,isClosable:!1},{type:"react-component",component:Nl.COMPONENT,title:Nl.TITLE,isClosable:!1}]}]},{type:"row",content:[{type:"stack",title:"Notebooks",content:[]}]}]}],links:[],filterSets:[],version:2},t0={layoutConfig:[],links:[],filterSets:[],version:2};function tm(c){if(Qx(c))return c;if(Jx(c))return{layoutConfig:c,links:[],filterSets:[],version:2};throw new Error(`Unexpected layout import format: ${c}`)}async function n0(c,e=!0){try{const t=await c.getLayouts();if(t.length>0)try{const n=await c.getLayout(t[0]);return tm(n)}catch(n){el.error("Unable to load layout",t[0],":",n),el.warn("No valid layouts found, falling back to default layout")}}catch(t){el.error("Unable to fetch layout list",t),el.warn("Falling back to default layout")}return e?e0:t0}function s0(c){const{filterSets:e,layoutConfig:t,links:n}=c;return{filterSets:e,layoutConfig:t,links:n,version:2}}const ll={exportLayout:s0,getDefaultLayout:n0,normalizeLayout:tm},tl=ne.module("DownloadServiceWorkerUtils");class co{static DOWNLOAD_PATH="/download/";static registerOnLoaded(){new URL("./",window.location.href).origin===window.location.origin&&("serviceWorker"in navigator?window.addEventListener("load",()=>{const t=new URL("./download/serviceWorker.js",window.location.href);navigator.serviceWorker.register(t).then(n=>{n.update(),tl.info("Registering service worker on ",t,n)}).catch(n=>{tl.error("Failed to register service worker",n)})}):tl.info("Service worker is not supported."))}static async getServiceWorker(){if("serviceWorker"in navigator){const t=(await navigator.serviceWorker.getRegistrations()).find(n=>n.scope.endsWith(co.DOWNLOAD_PATH));if(t&&t.active)return tl.info("Download service worker is active."),t.active;throw new Error("Can not find download service worker.")}throw new Error("Download service worker is not available.")}static unregisterSW(){}}const rt=ne.module("AppMainContainer");class Si extends v.Component{static handleWindowBeforeUnload(e){e.preventDefault(),e.returnValue=""}static hydrateConsole(e,t){return qa.hydrate({...e,unzip:n=>Wc.loadAsync(n).then(s=>Object.values(s.files))},t)}static handleRefresh(){rt.info("Refreshing application"),window.location.reload()}constructor(e){super(e),this.handleSettingsMenuHide=this.handleSettingsMenuHide.bind(this),this.handleSettingsMenuShow=this.handleSettingsMenuShow.bind(this),this.handleError=this.handleError.bind(this),this.handleControlSelect=this.handleControlSelect.bind(this),this.handleToolSelect=this.handleToolSelect.bind(this),this.handleClearFilter=this.handleClearFilter.bind(this),this.handleDataChange=this.handleDataChange.bind(this),this.handleAutoFillClick=this.handleAutoFillClick.bind(this),this.handleGoldenLayoutChange=this.handleGoldenLayoutChange.bind(this),this.handleLayoutConfigChange=this.handleLayoutConfigChange.bind(this),this.handleExportLayoutClick=this.handleExportLayoutClick.bind(this),this.handleImportLayoutClick=this.handleImportLayoutClick.bind(this),this.handleImportLayoutFiles=this.handleImportLayoutFiles.bind(this),this.handleLoadTablePlugin=this.handleLoadTablePlugin.bind(this),this.handleResetLayoutClick=this.handleResetLayoutClick.bind(this),this.handleWidgetMenuClick=this.handleWidgetMenuClick.bind(this),this.handleWidgetsMenuClose=this.handleWidgetsMenuClose.bind(this),this.handleWidgetSelect=this.handleWidgetSelect.bind(this),this.handlePaste=this.handlePaste.bind(this),this.hydrateChart=this.hydrateChart.bind(this),this.hydrateGrid=this.hydrateGrid.bind(this),this.hydratePandas=this.hydratePandas.bind(this),this.hydrateDefault=this.hydrateDefault.bind(this),this.openNotebookFromURL=this.openNotebookFromURL.bind(this),this.handleDisconnect=this.handleDisconnect.bind(this),this.handleReconnect=this.handleReconnect.bind(this),this.handleReconnectAuthFailed=this.handleReconnectAuthFailed.bind(this),this.importElement=de.createRef(),this.state={contextActions:[{action:()=>{this.handleToolSelect(Pt.LINKER)},shortcut:Kn.LINKER,isGlobal:!0},{action:()=>{this.sendClearFilter()},shortcut:Ut.TABLE.CLEAR_ALL_FILTERS,isGlobal:!0},{action:()=>{rt.debug("Consume unhandled save shortcut")},shortcut:Kn.SAVE,isGlobal:!0}],isAuthFailed:!1,isDisconnected:!1,isPanelsMenuShown:!1,isSettingsMenuShown:!1,widgets:[]}}componentDidMount(){this.initWidgets(),this.startListeningForDisconnect(),window.addEventListener("beforeunload",Si.handleWindowBeforeUnload)}componentDidUpdate(e){const{dashboardData:t}=this.props;e.dashboardData!==t&&this.handleDataChange(t)}componentWillUnmount(){this.deinitWidgets(),this.stopListeningForDisconnect(),window.removeEventListener("beforeunload",Si.handleWindowBeforeUnload)}goldenLayout;importElement;widgetListenerRemover;initWidgets(){const{connection:e}=this.props;if(e.subscribeToFieldUpdates==null){rt.warn("subscribeToFieldUpdates not supported, not initializing widgets");return}this.widgetListenerRemover=e.subscribeToFieldUpdates(t=>{rt.debug("Got updates",t),this.setState(({widgets:n})=>{const{updated:s,created:i,removed:o}=t,l=[...s,...o],a=n.filter(h=>!l.some(u=>u.name===h.name));return[...s,...i].forEach(h=>{h.name!=null&&h.name!==""&&a.push(h)}),{widgets:a}})})}deinitWidgets(){this.widgetListenerRemover?.()}openNotebookFromURL(){const{match:e}=this.props,{notebookPath:t}=e.params;if(t){const{session:n,sessionConfig:s}=this.props;if(n==null||s==null){rt.error("No session available to open notebook URL",t);return}const i={id:`/${t}`,itemName:`/${t}`},o=s.type,l={value:null,language:o};this.emitLayoutEvent(Ue.SELECT_NOTEBOOK,n,o,l,i,!0)}}sendClearFilter(){this.emitLayoutEvent(Ze.CLEAR_ALL_FILTERS)}emitLayoutEvent(e,...t){this.goldenLayout?.eventHub.emit(e,...t)}handleError(e){ye.isCanceled(e)||rt.error(e)}handleSettingsMenuHide(){this.setState({isSettingsMenuShown:!1})}handleSettingsMenuShow(){this.setState({isSettingsMenuShown:!0})}handleControlSelect(e,t=null){switch(rt.debug("handleControlSelect",e),e){case bs.DROPDOWN_FILTER:this.emitLayoutEvent(Ze.OPEN_DROPDOWN,{title:"DropdownFilter",type:e,createNewStack:!0,dragEvent:t});break;case bs.INPUT_FILTER:this.emitLayoutEvent(Ze.OPEN_INPUT,{title:"InputFilter",type:e,createNewStack:!0,dragEvent:t});break;case bs.MARKDOWN:this.emitLayoutEvent(Pu.OPEN,{title:"Markdown",type:e,dragEvent:t});break;case bs.FILTER_SET_MANAGER:this.emitLayoutEvent(Ze.OPEN_FILTER_SET_MANAGER,{title:"FilterSets",type:e,dragEvent:t});break;default:throw new Error(`Unrecognized control type ${e}`)}}handleToolSelect(e){rt.debug("handleToolSelect",e);const{activeTool:t,setActiveTool:n}=this.props;n(t===e?Pt.DEFAULT:e)}handleClearFilter(){this.sendClearFilter()}handleDataChange(e){const{updateWorkspaceData:t}=this.props,{closed:n,filterSets:s,links:i}=e;t({closed:n,filterSets:s,links:i})}handleGoldenLayoutChange(e){this.goldenLayout=e}handleLayoutConfigChange(e){const{updateWorkspaceData:t}=this.props;t({layoutConfig:e})}handleWidgetMenuClick(){this.setState(({isPanelsMenuShown:e})=>({isPanelsMenuShown:!e}))}handleWidgetSelect(e,t){this.setState({isPanelsMenuShown:!1}),rt.debug("handleWidgetSelect",e,t),this.openWidget(e,t)}handleWidgetsMenuClose(){this.setState({isPanelsMenuShown:!1})}handleAutoFillClick(){const{widgets:e}=this.state;rt.debug("handleAutoFillClick",e);const t=e.sort((n,s)=>n.title!=null&&s.title!=null?n.title.localeCompare(s.title):0);for(let n=0;n<t.length;n+=1)this.openWidget(t[n])}handleExportLayoutClick(){rt.info("handleExportLayoutClick"),this.setState({isPanelsMenuShown:!1});try{const{workspace:e}=this.props,{data:t}=e,n=ll.exportLayout(t);rt.info("handleExportLayoutClick exportedConfig",n);const s=new Blob([JSON.stringify(n)],{type:"application/json"}),i=I.i18n.DateTimeFormat.format("yyyy-MM-dd-HHmmss",new Date),o=document.createElement("a");o.href=URL.createObjectURL(s),o.download=`deephaven-app-layout-${i}.json`,o.click()}catch(e){rt.error("Unable to export layout",e)}}handleImportLayoutClick(){rt.info("handleImportLayoutClick"),this.setState({isPanelsMenuShown:!1}),this.importElement.current!=null&&(this.importElement.current.value="",this.importElement.current.click())}handleResetLayoutClick(){rt.info("handleResetLayoutClick"),this.setState({isPanelsMenuShown:!1}),this.resetLayout()}handleImportLayoutFiles(e){e.stopPropagation(),e.preventDefault(),e.target.files!=null&&this.importLayoutFile(e.target.files?.[0])}handleDisconnect(){rt.info("Disconnected from server"),this.setState({isDisconnected:!0})}handleReconnect(){rt.info("Reconnected to server"),this.setState({isDisconnected:!1})}handleReconnectAuthFailed(){rt.warn("Reconnect authentication failed"),this.setState({isAuthFailed:!0})}async importLayoutFile(e){try{const{updateDashboardData:t,updateWorkspaceData:n}=this.props,s=await e.text(),i=JSON.parse(s),{filterSets:o,layoutConfig:l,links:a}=ll.normalizeLayout(i);n({layoutConfig:l}),t(un,{filterSets:o,links:a})}catch(t){rt.error("Unable to import layout",t)}}async resetLayout(){const{layoutStorage:e,session:t}=this.props,{filterSets:n,layoutConfig:s,links:i}=await ll.getDefaultLayout(e,t!==void 0),{updateDashboardData:o,updateWorkspaceData:l}=this.props;l({layoutConfig:s}),o(un,{filterSets:n,links:i})}handlePaste(e){if(e.target instanceof HTMLElement&&e.target.closest(".monaco-editor"))return;const{clipboardData:t}=e,n=t.getData("Text"),s=/“|”/g;s.test(n)&&(e.preventDefault(),e.stopPropagation(),document.execCommand("insertText",!1,n.replace(s,'"')))}handleLoadTablePlugin(e){const{plugins:t}=this.props,n=t.get(e);if(n!=null&&n.TablePlugin!=null)return n.TablePlugin;const s=`Unable to find table plugin ${e}.`;return rt.error(s),r.jsx("div",{className:"error-message",children:`${s}`})}startListeningForDisconnect(){const{connection:e}=this.props;e.addEventListener(I.IdeConnection.EVENT_DISCONNECT,this.handleDisconnect),e.addEventListener(I.IdeConnection.EVENT_RECONNECT,this.handleReconnect),e.addEventListener(I.CoreClient.EVENT_RECONNECT_AUTH_FAILED,this.handleReconnectAuthFailed)}stopListeningForDisconnect(){const{connection:e}=this.props;e.removeEventListener(I.IdeConnection.EVENT_DISCONNECT,this.handleDisconnect),e.removeEventListener(I.IdeConnection.EVENT_RECONNECT,this.handleReconnect),e.removeEventListener(I.CoreClient.EVENT_RECONNECT_AUTH_FAILED,this.handleReconnectAuthFailed)}hydrateDefault(e,t){const{connection:n}=this.props,{metadata:s}=e;if(s?.type!=null&&(s?.id!=null||s?.name!=null)){const i=s.id!=null?{type:s.type,id:s.id}:{type:s.type,name:s.name,title:s.name};return{fetch:()=>n.getObject(i),localDashboardId:t,...e}}return qa.hydrate(e,t)}hydrateGrid(e,t){return this.hydrateTable(e,t,e.metadata.type??I.VariableType.TABLE)}hydratePandas(e,t){return this.hydrateTable(e,t,I.VariableType.PANDAS)}hydrateTable(e,t,n=I.VariableType.TABLE){const{connection:s}=this.props;return{...e,getDownloadWorker:co.getServiceWorker,loadPlugin:this.handleLoadTablePlugin,localDashboardId:t,makeModel:()=>Xx(s,e.metadata,n)}}hydrateChart(e,t){const{connection:n}=this.props;return{...e,localDashboardId:t,makeModel:()=>{const{metadata:s,panelState:i}=e;return qx(n,s,i)}}}openWidget(e,t){const{connection:n}=this.props;this.emitLayoutEvent(Ee.OPEN,{dragEvent:t,fetch:()=>n.getObject(e),widget:e})}getDashboardPlugins=ge(e=>[...e.entries()].filter(([,t])=>t.DashboardPlugin!=null).map(([t,{DashboardPlugin:n}])=>r.jsx(n,{},t)));render(){const{activeTool:e,plugins:t,user:n,workspace:s,serverConfigValues:i}=this.props,{data:o}=s,{layoutConfig:l}=o,{permissions:a}=n,{canUsePanels:d}=a,{contextActions:h,isAuthFailed:u,isDisconnected:m,isPanelsMenuShown:g,isSettingsMenuShown:p,widgets:C}=this.state,f=this.getDashboardPlugins(t);return r.jsxs("div",{className:Y("app-main-tabs","w-100","h-100","d-flex","flex-column",e?`active-tool-${e.toLowerCase()}`:""),onPaste:this.handlePaste,tabIndex:-1,children:[r.jsx("nav",{className:"nav-container",children:r.jsxs("div",{className:"app-main-top-nav-menus",children:[r.jsx("img",{src:Yu,alt:"Deephaven Data Labs",width:"115px",className:"ml-1"}),r.jsxs("div",{children:[r.jsxs(B,{kind:"ghost",className:"btn-panels-menu",icon:ap,onClick:()=>{},children:["Controls",r.jsx(od,{handleControlSelect:this.handleControlSelect,handleToolSelect:this.handleToolSelect,onClearFilter:this.handleClearFilter})]}),d&&r.jsxs(B,{kind:"ghost",className:"btn-panels-menu btn-show-panels","data-testid":"app-main-panels-button",onClick:this.handleWidgetMenuClick,icon:rp,children:["Panels",r.jsx(Vl,{isShown:g,className:"panels-menu-popper",onExited:this.handleWidgetsMenuClose,closeOnBlur:!0,interactive:!0,children:r.jsx(Yx,{widgets:C,onExportLayout:this.handleExportLayoutClick,onImportLayout:this.handleImportLayoutClick,onResetLayout:this.handleResetLayoutClick,onSelect:this.handleWidgetSelect})})]}),r.jsx(B,{kind:"ghost",className:Y("btn-settings-menu",{"text-warning":n.operateAs!=null&&n.operateAs!==n.name}),onClick:this.handleSettingsMenuShow,icon:r.jsx(ee,{icon:mo,transform:"grow-3 right-1 down-1"}),tooltip:"User Settings"})]})]})}),r.jsxs(TS,{emptyDashboard:r.jsx(Zx,{onAutoFillClick:this.handleAutoFillClick}),id:un,layoutConfig:l,onGoldenLayoutChange:this.handleGoldenLayoutChange,onLayoutConfigChange:this.handleLayoutConfigChange,onLayoutInitialized:this.openNotebookFromURL,hydrate:this.hydrateDefault,children:[r.jsx(YR,{hydrate:this.hydrateGrid,getDownloadWorker:co.getServiceWorker,loadPlugin:this.handleLoadTablePlugin}),r.jsx(VR,{hydrate:this.hydrateChart}),r.jsx($R,{}),r.jsx(GR,{hydrateConsole:Si.hydrateConsole,notebooksUrl:new URL("notebooks/",document.baseURI).href}),r.jsx(zR,{}),r.jsx(lx,{hydrate:this.hydratePandas}),r.jsx(ox,{}),r.jsx(ix,{}),f]}),r.jsx(Wt,{in:p,timeout:Je.transitionMidMs,classNames:"slide-left",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx(En,{serverConfigValues:i,onDone:this.handleSettingsMenuHide,user:n})}),r.jsx(ie,{actions:h}),r.jsx("input",{ref:this.importElement,type:"file",accept:".json",style:{display:"none"},onChange:this.handleImportLayoutFiles}),r.jsx(Gm,{isOpen:m&&!u,debounceMs:250,children:r.jsx(zm,{icon:dp,title:r.jsxs(r.Fragment,{children:[r.jsx(In,{})," Attempting to reconnect..."]}),subtitle:"Please check your network connection."})}),r.jsx(oo,{confirmButtonText:"Refresh",onConfirm:Si.handleRefresh,isOpen:u,headerText:"Authentication failed",bodyText:"Credentials are invalid. Please refresh your browser to try and reconnect."})]})}}const i0=c=>({activeTool:Xl(c),dashboardData:jt(c,un),layoutStorage:zx(c),plugins:bC(c),connection:Ry(c,un),session:Qs(c,un)?.session,sessionConfig:Qs(c,un)?.config,user:Sh(c),workspace:ql(c),serverConfigValues:Kx(c)}),o0=St(i0,{setActiveTool:Ql,updateDashboardData:Fn,updateWorkspaceData:jh})(Fm(Si));function l0(){return r.jsxs("div",{className:"app",children:[r.jsx(o0,{}),r.jsx(qc,{})]})}const a0=ne.module("LocalWorkspaceStorage");class wi{static STORAGE_KEY="deephaven.WorkspaceStorage";static async makeDefaultWorkspaceData(e,t){const{filterSets:n,links:s,layoutConfig:i}=await ll.getDefaultLayout(e,t?.isConsoleAvailable);return{settings:{defaultDateTimeFormat:ct.DEFAULT_DATETIME_FORMAT_STRING,formatter:[],timeZone:ct.DEFAULT_TIME_ZONE_ID,showTimeZone:!1,showTSeparator:!0,disableMoveConfirmation:!1,defaultDecimalFormatOptions:{defaultFormatString:Ke.DEFAULT_FORMAT_STRING},defaultIntegerFormatOptions:{defaultFormatString:dt.DEFAULT_FORMAT_STRING},truncateNumbersWithPound:!1,defaultNotebookSettings:{isMinimapEnabled:!1}},layoutConfig:i,closed:[{}],links:s,filterSets:n}}static async makeDefaultWorkspace(e,t){return{data:await wi.makeDefaultWorkspaceData(e,t)}}layoutStorage;constructor(e){this.layoutStorage=e}async load(e){try{return JSON.parse(localStorage.getItem(wi.STORAGE_KEY)??"")}catch{return a0.info("Unable to load workspace data, initializing to default data"),wi.makeDefaultWorkspace(this.layoutStorage,e)}}async save(e){return localStorage.setItem(wi.STORAGE_KEY,JSON.stringify(e)),e}}class r0{storageService;root;constructor(e,t=""){this.storageService=e,this.root=t}async getLayouts(){return(await this.storageService.listItems(this.root,"*.json")).map(t=>t.basename)}async getLayout(e){const n=await(await this.storageService.loadFile(`${this.root}/${e}`)).text();return JSON.parse(n)}}const Ki=ne.module("GrpcFileStorageTable");class _l{static REFRESH_DEBOUNCE=50;storageService;baseRoot;root;currentSize=0;currentViewport;listeners=[];viewportUpdatePromise;currentViewportData;childTables=new Map;constructor(e,t="",n=t){this.storageService=e,this.baseRoot=t,this.root=n,n===t&&(this.doRefresh=Ye(this.doRefresh.bind(this),_l.REFRESH_DEBOUNCE))}removeBaseRoot(e){return fe.removeRoot(this.baseRoot,e)}getViewportData(){return this.viewportUpdatePromise||this.refreshInternal(),this.viewportUpdatePromise??Promise.resolve({items:[],offset:0})}getSnapshot(e){throw new Error("Method not implemented.")}get size(){return this.currentSize}setExpanded(e,t){const n=e.split("/");let s=n.shift();if((s===void 0||s==="")&&(s=n.shift()),s===void 0||s==="")throw new Error(`Invalid path: ${e}`);const i=n.join("/");if(t){if(!this.childTables.has(s)){const o=new _l(this.storageService,this.baseRoot,`${this.root}/${s}`);this.childTables.set(s,o)}i&&this.childTables.get(s)?.setExpanded(i,t)}else this.childTables.has(s)&&(i?this.childTables.get(s)?.setExpanded(i,t):this.childTables.delete(s));this.currentViewport&&this.refreshInternal()}collapseAll(){this.childTables.clear(),this.currentViewport&&this.refreshInternal()}setSearch(e){throw new Error("Method not implemented.")}setViewport(e){this.currentViewport=e,this.refreshInternal()}setFilters(){throw new Error("Method not implemented.")}setSorts(){throw new Error("Method not implemented.")}setReversed(){throw new Error("Method not implemented.")}close(){this.listeners=[]}onUpdate(e){return this.listeners=[...this.listeners,e],()=>{this.listeners=this.listeners.filter(t=>t!==e)}}doRefresh(e){Ki.debug2("doRefresh",this.root),e(this.fetchData())}refresh(){Ki.debug2("refresh",this.root),this.viewportUpdatePromise?.cancel();const e=new Promise(n=>{this.doRefresh(n)}),t=ye.makeCancelable(e.then(n=>{if(this.viewportUpdatePromise!==t)throw new Hl;return this.currentViewportData=n,this.sendUpdate(),n}));t.catch(n=>{ye.isCanceled(n)||Ki.error("Error updating viewport",n)}),this.viewportUpdatePromise=t}refreshInternal(){try{this.refresh()}catch(e){ye.isCanceled(e)||Ki.error("Unable to refresh data",e)}}async fetchData(){const{currentViewport:e}=this;if(!e)throw new Error("No viewport set");let n=(await this.storageService.listItems(this.root)).map(s=>({type:s.type,filename:this.removeBaseRoot(s.filename),basename:s.basename,id:this.removeBaseRoot(s.filename),isExpanded:s.type==="directory"?this.childTables.has(s.basename):void 0})).sort((s,i)=>s.type!==i.type?s.type==="directory"?-1:1:s.basename.localeCompare(i.basename));for(let s=0;s<n.length;s+=1){const i=n[s],{basename:o,filename:l}=i;if(l===this.removeBaseRoot(`${this.root}/${o}`)&&i.type==="directory"){const a=this.childTables.get(o);if(a!=null){a.setViewport({top:0,bottom:e.bottom-s});const d=await a.getViewportData();n.splice(s+1,0,...d.items)}}}return this.currentSize=n.length,Ki.debug2(this.root,"items",n,e),n=n.slice(e.top,e.bottom),{items:n,offset:e.top}}sendUpdate(){const{listeners:e}=this,t=this.currentViewportData??{items:[],offset:0};for(let n=0;n<e.length;n+=1)e[n](t)}}const d0=ne.module("GrpcFileStorage");class ld{static REFRESH_THROTTLE=150;storageService;tables=[];root;constructor(e,t=""){this.storageService=e,this.root=t}removeRoot(e){return fe.removeRoot(this.root,e)}addRoot(e){return fe.addRoot(this.root,e)}async createDirectory(e){return await this.storageService.createDirectory(this.addRoot(e)),this.refreshTables(),{type:"directory",id:e,filename:e,basename:fe.getBaseName(e)}}async getTable(){const e=new _l(this.storageService,this.root);return this.tables.push(e),e}async saveFile(e){const t=dh.storage.FileContents.text(e.content);return await this.storageService.saveFile(this.addRoot(e.filename),t,!0),this.refreshTables(),e}async loadFile(e){const n=await(await this.storageService.loadFile(this.addRoot(e))).text();return{filename:e,basename:fe.getBaseName(e),content:n}}async deleteFile(e){await this.storageService.deleteItem(this.addRoot(e)),this.refreshTables()}async moveFile(e,t){await this.storageService.moveItem(this.addRoot(e),this.addRoot(t)),this.refreshTables()}async info(e){const t=await this.storageService.listItems(this.addRoot(fe.getPath(e)),fe.getBaseName(e));if(t.length===0)throw new Jr;if(t.length>1)throw d0.error("More than one matching file found, should never happen.",t),new Error("More than one matching file found");const n=t[0];return{filename:this.removeRoot(n.filename),basename:n.basename,id:this.removeRoot(n.filename),type:n.type}}refreshTables=vs(()=>{this.tables.forEach(e=>e.refresh())},ld.REFRESH_THROTTLE)}const c0=ne.module("AppInit");function ad(c){const{workspace:e,setActiveTool:t,setCommandHistoryStorage:n,setDashboardData:s,setFileStorage:i,setLayoutStorage:o,setDashboardConnection:l,setDashboardSessionWrapper:a,setPlugins:d,setUser:h,setWorkspace:u,setWorkspaceStorage:m,setServerConfigValues:g}=c,p=Km(),C=Ym(),f=qm(),b=v.useContext(Xm),w=v.useContext(Zm),[S,T]=v.useState();v.useEffect(function(){d(f)},[f,d]),v.useEffect(function(){async function D(){try{const M=await Qm(),O=await Jm(C,M),H=p.getStorageService(),L=new r0(H,"/layouts"),V=new ld(H,"/notebooks"),U=new wi(L),j=new wx,[P,Q]=await Promise.all([p.getServerConfigValues(),U.load({isConsoleAvailable:O!==void 0})]),{data:$}=Q,{settings:J}=$;J.defaultDecimalFormatOptions===void 0&&(J.defaultDecimalFormatOptions={defaultFormatString:Ke.DEFAULT_FORMAT_STRING}),J.defaultIntegerFormatOptions===void 0&&(J.defaultIntegerFormatOptions={defaultFormatString:dt.DEFAULT_FORMAT_STRING}),J.truncateNumbersWithPound===void 0&&(J.truncateNumbersWithPound=!1);const{shortcutOverrides:A={}}=J,q=sn.isMacPlatform?A.mac??{}:A.windows??{};Object.entries(q).forEach(([ue,ae])=>{We.get(ue)?.setKeyState(ae)});const Z={filterSets:$.filterSets,links:$.links},le=new Map(P),G="",oe={name:G,operateAs:G,groups:[],...b,permissions:{isACLEditor:!1,isSuperUser:!1,isQueryViewOnly:!1,isNonInteractive:!1,canUsePanels:!0,canCreateDashboard:!0,canCreateCodeStudio:!0,canCreateQueryMonitor:!0,canCopy:le.get("internal.webClient.appInit.canCopy")!=="false",canDownloadCsv:le.get("internal.webClient.appInit.canDownloadCsv")!=="false",canLogout:!0,...w}};t(Pt.DEFAULT),g(le),n(j),s(un,Z),i(V),o(L),l(un,C),O!==void 0&&a(un,O),h(oe),m(U),u(Q)}catch(M){c0.error(M),T(M)}}D()},[p,C,t,n,s,i,o,l,a,h,u,m,g,b,w]);const y=e==null&&S==null,E=!y&&S==null,R=S!=null?`${S}`:null;return r.jsxs(r.Fragment,{children:[E&&r.jsx(l0,{}),r.jsx($l,{isLoading:y&&R==null,isLoaded:E,errorMessage:R})]})}ad.propTypes={workspace:z.shape({}),workspaceStorage:z.shape({close:z.func}),setActiveTool:z.func.isRequired,setCommandHistoryStorage:z.func.isRequired,setDashboardData:z.func.isRequired,setFileStorage:z.func.isRequired,setLayoutStorage:z.func.isRequired,setDashboardConnection:z.func.isRequired,setDashboardSessionWrapper:z.func.isRequired,setPlugins:z.func.isRequired,setUser:z.func.isRequired,setWorkspace:z.func.isRequired,setWorkspaceStorage:z.func.isRequired};ad.defaultProps={workspace:null,workspaceStorage:null};const h0=c=>({workspace:ql(c),workspaceStorage:pC(c)}),Pc=St(h0,{setActiveTool:Ql,setCommandHistoryStorage:vC,setDashboardData:ru,setFileStorage:TC,setLayoutStorage:vx,setDashboardConnection:xy,setDashboardSessionWrapper:Dy,setPlugins:yC,setUser:SC,setWorkspace:Ph,setWorkspaceStorage:wC,setServerConfigValues:RC})(ad),u0=document.location.pathname;function m0(){return r.jsx(Nm,{basename:u0,children:r.jsxs(km,{children:[r.jsx(hd,{exact:!0,path:"/",component:Pc}),r.jsx(hd,{path:"/notebooks/:notebookPath+",component:Pc}),r.jsx(Mm,{from:"*",to:"/"})]})})}function v0(){return co.registerOnLoaded(),_t.init({getWorker:()=>new tg}),window["__react-beautiful-dnd-disable-dev-warnings"]=!0,r.jsx(Bc,{store:yr,children:r.jsx(m0,{})})}export{v0 as AppRoot,v0 as default};
42
- //# sourceMappingURL=AppRoot-7cfe096c.js.map
41
+ Barrage Version: ${o}`,children:"Copy Versions"})]})]})]}),r.jsx("div",{className:"app-settings-footer-item",children:r.jsx(Fx,{})})]}),r.jsx("div",{className:"app-settings-footer-section",children:r.jsx("div",{className:"logo",children:r.jsx("a",{target:"_blank",rel:"noreferrer noopener",href:"https://deephaven.io",className:"d-inline-block custom-link p-1",children:r.jsx("img",{src:Yu,alt:"Deephaven Data Labs",width:"230px"})})})})]})]})]})}}const Ac=10;function bi(c){const{forwardedProps:{menuItem:{action:e,title:t,disabled:n},iconElement:s,displayShortcut:i,isMouseSelected:o,isKeyboardSelected:l,closeMenu:a}}=c,d=v.useRef(),h=v.useRef(),u=v.useRef(null),[m,g]=v.useState(!1),p=v.useCallback(b=>{d.current!=null&&h.current!=null&&u.current&&(Math.abs(d.current-b.clientX)>=Ac||Math.abs(h.current-b.clientY)>=Ac)&&(g(!0),window.removeEventListener("mousemove",p),a(),e(b),u.current=null)},[e,a]);function C(b){d.current=b.clientX,h.current=b.clientY,u.current=b.target,window.addEventListener("mousemove",p)}function f(b){u.current===b.target&&(g(!0),a(),e(),window.removeEventListener("mousemove",p)),u.current=null}return v.useEffect(function(){return function(){return window.removeEventListener("mousemove",p)}},[p]),r.jsxs("button",{type:"button",className:Y("btn-context-menu",{disabled:n},{active:o&&!n},{"keyboard-active":l&&!n}),onMouseDown:C,onMouseUp:f,disabled:m,children:[r.jsx("span",{className:Y("icon"),children:s}),r.jsx("span",{className:"title",children:t}),r.jsx("span",{className:"shortcut",children:i})]})}function od(c){const{handleControlSelect:e,handleToolSelect:t,onClearFilter:n}=c,s=v.useMemo(()=>[{title:"Input Filter",icon:ip,menuElement:r.jsx(bi,{}),action:i=>{e(bs.INPUT_FILTER,i)},order:10},{title:"Dropdown Filter",icon:ih,menuElement:r.jsx(bi,{}),action:i=>{e(bs.DROPDOWN_FILTER,i)},order:15},{title:"Markdown Widget",icon:op,menuElement:r.jsx(bi,{}),action:i=>{e(bs.MARKDOWN,i)},order:20},{title:"Filter Sets",icon:Ua,menuElement:r.jsx(bi,{}),action:i=>{e(bs.FILTER_SET_MANAGER,i)},order:25},{disabled:!0,menuElement:r.jsx("div",{className:"context-menu-group-header",children:"Tools"}),order:30},{title:"Linker",icon:th,action:()=>{t(_t.LINKER)},order:40,shortcut:Kn.LINKER},{disabled:!0,menuElement:r.jsx("div",{className:"context-menu-group-header",children:"Actions"}),order:50},{title:"Clear All Filters",icon:lp,action:()=>{n()},order:60,shortcut:Ut.TABLE.CLEAR_ALL_FILTERS}],[e,t,n]);return r.jsx(Vn,{popperClassName:"controls-menu-popper",actions:s})}od.propTypes={handleControlSelect:z.func,handleToolSelect:z.func,onClearFilter:z.func};od.defaultProps={handleControlSelect:()=>{},handleToolSelect:()=>{},onClearFilter:()=>{}};bi.propTypes={forwardedProps:z.shape({iconElement:z.node,displayShortcut:z.string,isMouseSelected:z.bool.isRequired,isKeyboardSelected:z.bool.isRequired,closeMenu:z.func.isRequired,menuItem:z.shape({action:z.func,title:z.string,disabled:z.bool}).isRequired})};bi.defaultProps={forwardedProps:null};const Wx=Js(Ku,null),Gx={layoutStorage:Wx},zx=c=>c.layoutStorage,Kx=c=>c.serverConfigValues;Object.entries(Gx).map(([c,e])=>fo.register(c,e));const _c=10;function Yx(c){const{onExportLayout:e,onImportLayout:t,onResetLayout:n,onSelect:s,widgets:i=[]}=c,[o,l]=v.useState(!1),[a,d]=v.useState(""),h=v.useRef(null),u=v.useRef(),m=v.useCallback((T,y)=>{T!=null&&s(T,y)},[s]),g=v.useCallback(T=>{d(T.target.value)},[]),p=v.useCallback(T=>{u.current!=null&&(Math.abs(u.current.x-T.clientX)>=_c||Math.abs(u.current.y-T.clientY)>=_c)&&(l(!0),window.removeEventListener("mousemove",p),m(u.current.widget,T),u.current=void 0)},[u,m]),C=v.useCallback((T,y)=>{u.current={x:T.clientX,y:T.clientY,widget:y},window.addEventListener("mousemove",p)},[p]),f=v.useCallback((T,y)=>{window.removeEventListener("mousemove",p),u.current?.widget===y&&(l(!0),m(y)),u.current=void 0},[p,u,m]),b=v.useMemo(()=>i.filter(T=>a?T.name?.toLowerCase().includes(a.toLowerCase()):!0),[a,i]).sort((T,y)=>T.name?.localeCompare(y.name??"")??0),w=v.useMemo(()=>b.map(T=>r.jsx("li",{children:r.jsxs(B,{kind:"ghost","data-testid":`panel-list-item-${T.name??""}-button`,onMouseDown:y=>{C(y,T)},onMouseUp:y=>{f(y,T)},onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&m(T)},disabled:o,onClick:()=>{},children:[r.jsx(ah,{type:T.type})," ",T.name??""]})},T.name)),[b,o,C,f,m]),S=v.useMemo(()=>w.length===0?r.jsx("span",{children:"No bound variables found."}):null,[w]);return r.jsxs("div",{className:"widget-list-container d-flex flex-column",children:[r.jsx("div",{className:"widget-list-header",children:r.jsx(Di,{value:a,placeholder:"Find Table, Plot or Widget",onChange:g,ref:h})}),r.jsxs("ul",{className:"widget-list flex-grow-1",children:[S&&r.jsx("li",{className:"widget-list-message",children:S}),!S&&w]}),r.jsx("div",{children:r.jsx("hr",{})}),r.jsxs("div",{className:"widget-list-footer",children:[r.jsxs(B,{kind:"ghost",onClick:e,children:[r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx(ee,{mask:Ba,icon:vd,transform:"right-5 down-5"}),r.jsx(ee,{icon:vd,transform:"right-8 down-6"})]}),"Export Layout"]}),r.jsxs(B,{kind:"ghost",onClick:t,children:[r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx(ee,{mask:Ba,icon:Va,transform:"right-5 down-5"}),r.jsx(ee,{icon:Va,transform:"right-8 down-6"})]}),"Import Layout"]}),r.jsx(B,{kind:"ghost",icon:Ws,onClick:n,tooltip:"Reset Layout"})]})]})}const qx=async(c,e,t)=>{let n,s,i,o;if(il(e)?(n=e.settings,s=e.table,i=void 0,o=e.tableSettings):(n={},s="",i=e.figure,o={}),t!==void 0&&(t.tableSettings!=null&&(o=t.tableSettings),t.table!=null&&(s=t.table),t.figure!=null&&(i=t.figure),t.settings!=null&&(n={...n,...t.settings})),i!==void 0){const d={title:i,name:i,type:I.VariableType.FIGURE},h=await c.getObject(d);return fl.makeModel(n,h)}const l={title:i,name:s,type:I.VariableType.TABLE},a=await c.getObject(l);return Se.applyTableSettings(a,o,po(yr.getState())),fl.makeModelFromSettings(n,a)},Xx=async(c,e,t=I.VariableType.TABLE)=>{const{table:n}=e,s={title:n,name:n,type:t},i=await c.getObject(s);return Wr.makeModel(i)};function Zx({onAutoFillClick:c=()=>{}}){return r.jsxs("div",{className:"empty-dashboard-container",children:[r.jsxs("div",{className:"hint-container",children:[r.jsx(ee,{icon:sh})," ",r.jsx("br",{}),"Use the panel list to add objects from a query."]}),r.jsxs("div",{className:"empty-dashboard",children:[r.jsx("div",{className:"add-panels-hint",children:"Drag Panels Here"}),r.jsx(B,{kind:"tertiary",onClick:c,children:"Auto fill objects"})]})]})}function Qx(c){return c.version===2}function Jx(c){return Array.isArray(c)}const el=ne.module("UserLayoutUtils"),e0={layoutConfig:[{type:"column",content:[{type:"row",height:40,content:[{type:"stack",content:[{type:"react-component",component:Ci.COMPONENT,title:Ci.TITLE,isClosable:!1},{type:"react-component",component:Ol.COMPONENT,title:Ol.TITLE,isClosable:!1}]},{type:"stack",width:25,content:[{type:"react-component",component:Il.COMPONENT,title:Il.TITLE,isClosable:!1},{type:"react-component",component:Nl.COMPONENT,title:Nl.TITLE,isClosable:!1}]}]},{type:"row",content:[{type:"stack",title:"Notebooks",content:[]}]}]}],links:[],filterSets:[],version:2},t0={layoutConfig:[],links:[],filterSets:[],version:2};function tm(c){if(Qx(c))return c;if(Jx(c))return{layoutConfig:c,links:[],filterSets:[],version:2};throw new Error(`Unexpected layout import format: ${c}`)}async function n0(c,e=!0){try{const t=await c.getLayouts();if(t.length>0)try{const n=await c.getLayout(t[0]);return tm(n)}catch(n){el.error("Unable to load layout",t[0],":",n),el.warn("No valid layouts found, falling back to default layout")}}catch(t){el.error("Unable to fetch layout list",t),el.warn("Falling back to default layout")}return e?e0:t0}function s0(c){const{filterSets:e,layoutConfig:t,links:n}=c;return{filterSets:e,layoutConfig:t,links:n,version:2}}const ll={exportLayout:s0,getDefaultLayout:n0,normalizeLayout:tm},tl=ne.module("DownloadServiceWorkerUtils");class co{static DOWNLOAD_PATH="/download/";static registerOnLoaded(){new URL("./",window.location.href).origin===window.location.origin&&("serviceWorker"in navigator?window.addEventListener("load",()=>{const t=new URL("./download/serviceWorker.js",window.location.href);navigator.serviceWorker.register(t).then(n=>{n.update(),tl.info("Registering service worker on ",t,n)}).catch(n=>{tl.error("Failed to register service worker",n)})}):tl.info("Service worker is not supported."))}static async getServiceWorker(){if("serviceWorker"in navigator){const t=(await navigator.serviceWorker.getRegistrations()).find(n=>n.scope.endsWith(co.DOWNLOAD_PATH));if(t&&t.active)return tl.info("Download service worker is active."),t.active;throw new Error("Can not find download service worker.")}throw new Error("Download service worker is not available.")}static unregisterSW(){}}const rt=ne.module("AppMainContainer");class Si extends v.Component{static handleWindowBeforeUnload(e){e.preventDefault(),e.returnValue=""}static hydrateConsole(e,t){return qa.hydrate({...e,unzip:n=>Wc.loadAsync(n).then(s=>Object.values(s.files))},t)}static handleRefresh(){rt.info("Refreshing application"),window.location.reload()}constructor(e){super(e),this.handleSettingsMenuHide=this.handleSettingsMenuHide.bind(this),this.handleSettingsMenuShow=this.handleSettingsMenuShow.bind(this),this.handleError=this.handleError.bind(this),this.handleControlSelect=this.handleControlSelect.bind(this),this.handleToolSelect=this.handleToolSelect.bind(this),this.handleClearFilter=this.handleClearFilter.bind(this),this.handleDataChange=this.handleDataChange.bind(this),this.handleAutoFillClick=this.handleAutoFillClick.bind(this),this.handleGoldenLayoutChange=this.handleGoldenLayoutChange.bind(this),this.handleLayoutConfigChange=this.handleLayoutConfigChange.bind(this),this.handleExportLayoutClick=this.handleExportLayoutClick.bind(this),this.handleImportLayoutClick=this.handleImportLayoutClick.bind(this),this.handleImportLayoutFiles=this.handleImportLayoutFiles.bind(this),this.handleLoadTablePlugin=this.handleLoadTablePlugin.bind(this),this.handleResetLayoutClick=this.handleResetLayoutClick.bind(this),this.handleWidgetMenuClick=this.handleWidgetMenuClick.bind(this),this.handleWidgetsMenuClose=this.handleWidgetsMenuClose.bind(this),this.handleWidgetSelect=this.handleWidgetSelect.bind(this),this.handlePaste=this.handlePaste.bind(this),this.hydrateChart=this.hydrateChart.bind(this),this.hydrateGrid=this.hydrateGrid.bind(this),this.hydratePandas=this.hydratePandas.bind(this),this.hydrateDefault=this.hydrateDefault.bind(this),this.openNotebookFromURL=this.openNotebookFromURL.bind(this),this.handleDisconnect=this.handleDisconnect.bind(this),this.handleReconnect=this.handleReconnect.bind(this),this.handleReconnectAuthFailed=this.handleReconnectAuthFailed.bind(this),this.importElement=de.createRef(),this.state={contextActions:[{action:()=>{this.handleToolSelect(_t.LINKER)},shortcut:Kn.LINKER,isGlobal:!0},{action:()=>{this.sendClearFilter()},shortcut:Ut.TABLE.CLEAR_ALL_FILTERS,isGlobal:!0},{action:()=>{rt.debug("Consume unhandled save shortcut")},shortcut:Kn.SAVE,isGlobal:!0}],isAuthFailed:!1,isDisconnected:!1,isPanelsMenuShown:!1,isSettingsMenuShown:!1,widgets:[]}}componentDidMount(){this.initWidgets(),this.startListeningForDisconnect(),window.addEventListener("beforeunload",Si.handleWindowBeforeUnload)}componentDidUpdate(e){const{dashboardData:t}=this.props;e.dashboardData!==t&&this.handleDataChange(t)}componentWillUnmount(){this.deinitWidgets(),this.stopListeningForDisconnect(),window.removeEventListener("beforeunload",Si.handleWindowBeforeUnload)}goldenLayout;importElement;widgetListenerRemover;initWidgets(){const{connection:e}=this.props;if(e.subscribeToFieldUpdates==null){rt.warn("subscribeToFieldUpdates not supported, not initializing widgets");return}this.widgetListenerRemover=e.subscribeToFieldUpdates(t=>{rt.debug("Got updates",t),this.setState(({widgets:n})=>{const{updated:s,created:i,removed:o}=t,l=[...s,...o],a=n.filter(h=>!l.some(u=>u.name===h.name));return[...s,...i].forEach(h=>{h.name!=null&&h.name!==""&&a.push(h)}),{widgets:a}})})}deinitWidgets(){this.widgetListenerRemover?.()}openNotebookFromURL(){const{match:e}=this.props,{notebookPath:t}=e.params;if(t){const{session:n,sessionConfig:s}=this.props;if(n==null||s==null){rt.error("No session available to open notebook URL",t);return}const i={id:`/${t}`,itemName:`/${t}`},o=s.type,l={value:null,language:o};this.emitLayoutEvent(Ue.SELECT_NOTEBOOK,n,o,l,i,!0)}}sendClearFilter(){this.emitLayoutEvent(Ze.CLEAR_ALL_FILTERS)}emitLayoutEvent(e,...t){this.goldenLayout?.eventHub.emit(e,...t)}handleError(e){ye.isCanceled(e)||rt.error(e)}handleSettingsMenuHide(){this.setState({isSettingsMenuShown:!1})}handleSettingsMenuShow(){this.setState({isSettingsMenuShown:!0})}handleControlSelect(e,t=null){switch(rt.debug("handleControlSelect",e),e){case bs.DROPDOWN_FILTER:this.emitLayoutEvent(Ze.OPEN_DROPDOWN,{title:"DropdownFilter",type:e,createNewStack:!0,dragEvent:t});break;case bs.INPUT_FILTER:this.emitLayoutEvent(Ze.OPEN_INPUT,{title:"InputFilter",type:e,createNewStack:!0,dragEvent:t});break;case bs.MARKDOWN:this.emitLayoutEvent(Pu.OPEN,{title:"Markdown",type:e,dragEvent:t});break;case bs.FILTER_SET_MANAGER:this.emitLayoutEvent(Ze.OPEN_FILTER_SET_MANAGER,{title:"FilterSets",type:e,dragEvent:t});break;default:throw new Error(`Unrecognized control type ${e}`)}}handleToolSelect(e){rt.debug("handleToolSelect",e);const{activeTool:t,setActiveTool:n}=this.props;n(t===e?_t.DEFAULT:e)}handleClearFilter(){this.sendClearFilter()}handleDataChange(e){const{updateWorkspaceData:t}=this.props,{closed:n,filterSets:s,links:i}=e;t({closed:n,filterSets:s,links:i})}handleGoldenLayoutChange(e){this.goldenLayout=e}handleLayoutConfigChange(e){const{updateWorkspaceData:t}=this.props;t({layoutConfig:e})}handleWidgetMenuClick(){this.setState(({isPanelsMenuShown:e})=>({isPanelsMenuShown:!e}))}handleWidgetSelect(e,t){this.setState({isPanelsMenuShown:!1}),rt.debug("handleWidgetSelect",e,t),this.openWidget(e,t)}handleWidgetsMenuClose(){this.setState({isPanelsMenuShown:!1})}handleAutoFillClick(){const{widgets:e}=this.state;rt.debug("handleAutoFillClick",e);const t=e.sort((n,s)=>n.title!=null&&s.title!=null?n.title.localeCompare(s.title):0);for(let n=0;n<t.length;n+=1)this.openWidget(t[n])}handleExportLayoutClick(){rt.info("handleExportLayoutClick"),this.setState({isPanelsMenuShown:!1});try{const{workspace:e}=this.props,{data:t}=e,n=ll.exportLayout(t);rt.info("handleExportLayoutClick exportedConfig",n);const s=new Blob([JSON.stringify(n)],{type:"application/json"}),i=I.i18n.DateTimeFormat.format("yyyy-MM-dd-HHmmss",new Date),o=document.createElement("a");o.href=URL.createObjectURL(s),o.download=`deephaven-app-layout-${i}.json`,o.click()}catch(e){rt.error("Unable to export layout",e)}}handleImportLayoutClick(){rt.info("handleImportLayoutClick"),this.setState({isPanelsMenuShown:!1}),this.importElement.current!=null&&(this.importElement.current.value="",this.importElement.current.click())}handleResetLayoutClick(){rt.info("handleResetLayoutClick"),this.setState({isPanelsMenuShown:!1}),this.resetLayout()}handleImportLayoutFiles(e){e.stopPropagation(),e.preventDefault(),e.target.files!=null&&this.importLayoutFile(e.target.files?.[0])}handleDisconnect(){rt.info("Disconnected from server"),this.setState({isDisconnected:!0})}handleReconnect(){rt.info("Reconnected to server"),this.setState({isDisconnected:!1})}handleReconnectAuthFailed(){rt.warn("Reconnect authentication failed"),this.setState({isAuthFailed:!0})}async importLayoutFile(e){try{const{updateDashboardData:t,updateWorkspaceData:n}=this.props,s=await e.text(),i=JSON.parse(s),{filterSets:o,layoutConfig:l,links:a}=ll.normalizeLayout(i);n({layoutConfig:l}),t(un,{filterSets:o,links:a})}catch(t){rt.error("Unable to import layout",t)}}async resetLayout(){const{layoutStorage:e,session:t}=this.props,{filterSets:n,layoutConfig:s,links:i}=await ll.getDefaultLayout(e,t!==void 0),{updateDashboardData:o,updateWorkspaceData:l}=this.props;l({layoutConfig:s}),o(un,{filterSets:n,links:i})}handlePaste(e){if(e.target instanceof HTMLElement&&e.target.closest(".monaco-editor"))return;const{clipboardData:t}=e,n=t.getData("Text"),s=/“|”/g;s.test(n)&&(e.preventDefault(),e.stopPropagation(),document.execCommand("insertText",!1,n.replace(s,'"')))}handleLoadTablePlugin(e){const{plugins:t}=this.props,n=t.get(e);if(n!=null&&n.TablePlugin!=null)return n.TablePlugin;const s=`Unable to find table plugin ${e}.`;return rt.error(s),r.jsx("div",{className:"error-message",children:`${s}`})}startListeningForDisconnect(){const{connection:e}=this.props;e.addEventListener(I.IdeConnection.EVENT_DISCONNECT,this.handleDisconnect),e.addEventListener(I.IdeConnection.EVENT_RECONNECT,this.handleReconnect),e.addEventListener(I.CoreClient.EVENT_RECONNECT_AUTH_FAILED,this.handleReconnectAuthFailed)}stopListeningForDisconnect(){const{connection:e}=this.props;e.removeEventListener(I.IdeConnection.EVENT_DISCONNECT,this.handleDisconnect),e.removeEventListener(I.IdeConnection.EVENT_RECONNECT,this.handleReconnect),e.removeEventListener(I.CoreClient.EVENT_RECONNECT_AUTH_FAILED,this.handleReconnectAuthFailed)}hydrateDefault(e,t){const{connection:n}=this.props,{metadata:s}=e;if(s?.type!=null&&(s?.id!=null||s?.name!=null)){const i=s.id!=null?{type:s.type,id:s.id}:{type:s.type,name:s.name,title:s.name};return{fetch:()=>n.getObject(i),localDashboardId:t,...e}}return qa.hydrate(e,t)}hydrateGrid(e,t){return this.hydrateTable(e,t,e.metadata.type??I.VariableType.TABLE)}hydratePandas(e,t){return this.hydrateTable(e,t,I.VariableType.PANDAS)}hydrateTable(e,t,n=I.VariableType.TABLE){const{connection:s}=this.props;return{...e,getDownloadWorker:co.getServiceWorker,loadPlugin:this.handleLoadTablePlugin,localDashboardId:t,makeModel:()=>Xx(s,e.metadata,n)}}hydrateChart(e,t){const{connection:n}=this.props;return{...e,localDashboardId:t,makeModel:()=>{const{metadata:s,panelState:i}=e;return qx(n,s,i)}}}openWidget(e,t){const{connection:n}=this.props;this.emitLayoutEvent(Ee.OPEN,{dragEvent:t,fetch:()=>n.getObject(e),widget:e})}getDashboardPlugins=ge(e=>[...e.entries()].filter(([,t])=>t.DashboardPlugin!=null).map(([t,{DashboardPlugin:n}])=>r.jsx(n,{},t)));render(){const{activeTool:e,plugins:t,user:n,workspace:s,serverConfigValues:i}=this.props,{data:o}=s,{layoutConfig:l}=o,{permissions:a}=n,{canUsePanels:d}=a,{contextActions:h,isAuthFailed:u,isDisconnected:m,isPanelsMenuShown:g,isSettingsMenuShown:p,widgets:C}=this.state,f=this.getDashboardPlugins(t);return r.jsxs("div",{className:Y("app-main-tabs","w-100","h-100","d-flex","flex-column",e?`active-tool-${e.toLowerCase()}`:""),onPaste:this.handlePaste,tabIndex:-1,children:[r.jsx("nav",{className:"nav-container",children:r.jsxs("div",{className:"app-main-top-nav-menus",children:[r.jsx("img",{src:Yu,alt:"Deephaven Data Labs",width:"115px",className:"ml-1"}),r.jsxs("div",{children:[r.jsxs(B,{kind:"ghost",className:"btn-panels-menu",icon:ap,onClick:()=>{},children:["Controls",r.jsx(od,{handleControlSelect:this.handleControlSelect,handleToolSelect:this.handleToolSelect,onClearFilter:this.handleClearFilter})]}),d&&r.jsxs(B,{kind:"ghost",className:"btn-panels-menu btn-show-panels","data-testid":"app-main-panels-button",onClick:this.handleWidgetMenuClick,icon:rp,children:["Panels",r.jsx(Vl,{isShown:g,className:"panels-menu-popper",onExited:this.handleWidgetsMenuClose,closeOnBlur:!0,interactive:!0,children:r.jsx(Yx,{widgets:C,onExportLayout:this.handleExportLayoutClick,onImportLayout:this.handleImportLayoutClick,onResetLayout:this.handleResetLayoutClick,onSelect:this.handleWidgetSelect})})]}),r.jsx(B,{kind:"ghost",className:Y("btn-settings-menu",{"text-warning":n.operateAs!=null&&n.operateAs!==n.name}),onClick:this.handleSettingsMenuShow,icon:r.jsx(ee,{icon:mo,transform:"grow-3 right-1 down-1"}),tooltip:"User Settings"})]})]})}),r.jsxs(TS,{emptyDashboard:r.jsx(Zx,{onAutoFillClick:this.handleAutoFillClick}),id:un,layoutConfig:l,onGoldenLayoutChange:this.handleGoldenLayoutChange,onLayoutConfigChange:this.handleLayoutConfigChange,onLayoutInitialized:this.openNotebookFromURL,hydrate:this.hydrateDefault,children:[r.jsx(YR,{hydrate:this.hydrateGrid,getDownloadWorker:co.getServiceWorker,loadPlugin:this.handleLoadTablePlugin}),r.jsx(VR,{hydrate:this.hydrateChart}),r.jsx($R,{}),r.jsx(GR,{hydrateConsole:Si.hydrateConsole,notebooksUrl:new URL("notebooks/",document.baseURI).href}),r.jsx(zR,{}),r.jsx(lx,{hydrate:this.hydratePandas}),r.jsx(ox,{}),r.jsx(ix,{}),f]}),r.jsx(Wt,{in:p,timeout:Je.transitionMidMs,classNames:"slide-left",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx(En,{serverConfigValues:i,onDone:this.handleSettingsMenuHide,user:n})}),r.jsx(ie,{actions:h}),r.jsx("input",{ref:this.importElement,type:"file",accept:".json",style:{display:"none"},onChange:this.handleImportLayoutFiles}),r.jsx(Gm,{isOpen:m&&!u,debounceMs:250,children:r.jsx(zm,{icon:dp,title:r.jsxs(r.Fragment,{children:[r.jsx(In,{})," Attempting to reconnect..."]}),subtitle:"Please check your network connection."})}),r.jsx(oo,{confirmButtonText:"Refresh",onConfirm:Si.handleRefresh,isOpen:u,headerText:"Authentication failed",bodyText:"Credentials are invalid. Please refresh your browser to try and reconnect."})]})}}const i0=c=>({activeTool:Xl(c),dashboardData:Pt(c,un),layoutStorage:zx(c),plugins:bC(c),connection:Ry(c,un),session:Qs(c,un)?.session,sessionConfig:Qs(c,un)?.config,user:Sh(c),workspace:ql(c),serverConfigValues:Kx(c)}),o0=St(i0,{setActiveTool:Ql,updateDashboardData:Fn,updateWorkspaceData:jh})(Fm(Si));function l0(){return r.jsxs("div",{className:"app",children:[r.jsx(o0,{}),r.jsx(qc,{})]})}const a0=ne.module("LocalWorkspaceStorage");class wi{static STORAGE_KEY="deephaven.WorkspaceStorage";static async makeDefaultWorkspaceData(e,t){const{filterSets:n,links:s,layoutConfig:i}=await ll.getDefaultLayout(e,t?.isConsoleAvailable);return{settings:{defaultDateTimeFormat:ct.DEFAULT_DATETIME_FORMAT_STRING,formatter:[],timeZone:ct.DEFAULT_TIME_ZONE_ID,showTimeZone:!1,showTSeparator:!0,disableMoveConfirmation:!1,defaultDecimalFormatOptions:{defaultFormatString:Ke.DEFAULT_FORMAT_STRING},defaultIntegerFormatOptions:{defaultFormatString:dt.DEFAULT_FORMAT_STRING},truncateNumbersWithPound:!1,defaultNotebookSettings:{isMinimapEnabled:!1}},layoutConfig:i,closed:[{}],links:s,filterSets:n}}static async makeDefaultWorkspace(e,t){return{data:await wi.makeDefaultWorkspaceData(e,t)}}layoutStorage;constructor(e){this.layoutStorage=e}async load(e){try{return JSON.parse(localStorage.getItem(wi.STORAGE_KEY)??"")}catch{return a0.info("Unable to load workspace data, initializing to default data"),wi.makeDefaultWorkspace(this.layoutStorage,e)}}async save(e){return localStorage.setItem(wi.STORAGE_KEY,JSON.stringify(e)),e}}class r0{storageService;root;constructor(e,t=""){this.storageService=e,this.root=t}async getLayouts(){return(await this.storageService.listItems(this.root,"*.json")).map(t=>t.basename)}async getLayout(e){const n=await(await this.storageService.loadFile(`${this.root}/${e}`)).text();return JSON.parse(n)}}const Ki=ne.module("GrpcFileStorageTable");class _l{static REFRESH_DEBOUNCE=50;storageService;baseRoot;root;currentSize=0;currentViewport;listeners=[];viewportUpdatePromise;currentViewportData;childTables=new Map;constructor(e,t="",n=t){this.storageService=e,this.baseRoot=t,this.root=n,n===t&&(this.doRefresh=Ye(this.doRefresh.bind(this),_l.REFRESH_DEBOUNCE))}removeBaseRoot(e){return fe.removeRoot(this.baseRoot,e)}getViewportData(){return this.viewportUpdatePromise||this.refreshInternal(),this.viewportUpdatePromise??Promise.resolve({items:[],offset:0})}getSnapshot(e){throw new Error("Method not implemented.")}get size(){return this.currentSize}setExpanded(e,t){const n=e.split("/");let s=n.shift();if((s===void 0||s==="")&&(s=n.shift()),s===void 0||s==="")throw new Error(`Invalid path: ${e}`);const i=n.join("/");if(t){if(!this.childTables.has(s)){const o=new _l(this.storageService,this.baseRoot,`${this.root}/${s}`);this.childTables.set(s,o)}i&&this.childTables.get(s)?.setExpanded(i,t)}else this.childTables.has(s)&&(i?this.childTables.get(s)?.setExpanded(i,t):this.childTables.delete(s));this.currentViewport&&this.refreshInternal()}collapseAll(){this.childTables.clear(),this.currentViewport&&this.refreshInternal()}setSearch(e){throw new Error("Method not implemented.")}setViewport(e){this.currentViewport=e,this.refreshInternal()}setFilters(){throw new Error("Method not implemented.")}setSorts(){throw new Error("Method not implemented.")}setReversed(){throw new Error("Method not implemented.")}close(){this.listeners=[]}onUpdate(e){return this.listeners=[...this.listeners,e],()=>{this.listeners=this.listeners.filter(t=>t!==e)}}doRefresh(e){Ki.debug2("doRefresh",this.root),e(this.fetchData())}refresh(){Ki.debug2("refresh",this.root),this.viewportUpdatePromise?.cancel();const e=new Promise(n=>{this.doRefresh(n)}),t=ye.makeCancelable(e.then(n=>{if(this.viewportUpdatePromise!==t)throw new Hl;return this.currentViewportData=n,this.sendUpdate(),n}));t.catch(n=>{ye.isCanceled(n)||Ki.error("Error updating viewport",n)}),this.viewportUpdatePromise=t}refreshInternal(){try{this.refresh()}catch(e){ye.isCanceled(e)||Ki.error("Unable to refresh data",e)}}async fetchData(){const{currentViewport:e}=this;if(!e)throw new Error("No viewport set");let n=(await this.storageService.listItems(this.root)).map(s=>({type:s.type,filename:this.removeBaseRoot(s.filename),basename:s.basename,id:this.removeBaseRoot(s.filename),isExpanded:s.type==="directory"?this.childTables.has(s.basename):void 0})).sort((s,i)=>s.type!==i.type?s.type==="directory"?-1:1:s.basename.localeCompare(i.basename));for(let s=0;s<n.length;s+=1){const i=n[s],{basename:o,filename:l}=i;if(l===this.removeBaseRoot(`${this.root}/${o}`)&&i.type==="directory"){const a=this.childTables.get(o);if(a!=null){a.setViewport({top:0,bottom:e.bottom-s});const d=await a.getViewportData();n.splice(s+1,0,...d.items)}}}return this.currentSize=n.length,Ki.debug2(this.root,"items",n,e),n=n.slice(e.top,e.bottom),{items:n,offset:e.top}}sendUpdate(){const{listeners:e}=this,t=this.currentViewportData??{items:[],offset:0};for(let n=0;n<e.length;n+=1)e[n](t)}}const d0=ne.module("GrpcFileStorage");class ld{static REFRESH_THROTTLE=150;storageService;tables=[];root;constructor(e,t=""){this.storageService=e,this.root=t}removeRoot(e){return fe.removeRoot(this.root,e)}addRoot(e){return fe.addRoot(this.root,e)}async createDirectory(e){return await this.storageService.createDirectory(this.addRoot(e)),this.refreshTables(),{type:"directory",id:e,filename:e,basename:fe.getBaseName(e)}}async getTable(){const e=new _l(this.storageService,this.root);return this.tables.push(e),e}async saveFile(e){const t=dh.storage.FileContents.text(e.content);return await this.storageService.saveFile(this.addRoot(e.filename),t,!0),this.refreshTables(),e}async loadFile(e){const n=await(await this.storageService.loadFile(this.addRoot(e))).text();return{filename:e,basename:fe.getBaseName(e),content:n}}async deleteFile(e){await this.storageService.deleteItem(this.addRoot(e)),this.refreshTables()}async moveFile(e,t){await this.storageService.moveItem(this.addRoot(e),this.addRoot(t)),this.refreshTables()}async info(e){const t=await this.storageService.listItems(this.addRoot(fe.getPath(e)),fe.getBaseName(e));if(t.length===0)throw new Jr;if(t.length>1)throw d0.error("More than one matching file found, should never happen.",t),new Error("More than one matching file found");const n=t[0];return{filename:this.removeRoot(n.filename),basename:n.basename,id:this.removeRoot(n.filename),type:n.type}}refreshTables=vs(()=>{this.tables.forEach(e=>e.refresh())},ld.REFRESH_THROTTLE)}const c0=ne.module("AppInit");function ad(c){const{workspace:e,setActiveTool:t,setCommandHistoryStorage:n,setDashboardData:s,setFileStorage:i,setLayoutStorage:o,setDashboardConnection:l,setDashboardSessionWrapper:a,setPlugins:d,setUser:h,setWorkspace:u,setWorkspaceStorage:m,setServerConfigValues:g}=c,p=Km(),C=Ym(),f=qm(),b=v.useContext(Xm),w=v.useContext(Zm),[S,T]=v.useState();v.useEffect(function(){d(f)},[f,d]),v.useEffect(function(){async function D(){try{const M=await Qm(),O=await Jm(C,M),H=p.getStorageService(),L=new r0(H,"/layouts"),V=new ld(H,"/notebooks"),U=new wi(L),j=new wx,[P,Q]=await Promise.all([p.getServerConfigValues(),U.load({isConsoleAvailable:O!==void 0})]),{data:$}=Q,{settings:J}=$;J.defaultDecimalFormatOptions===void 0&&(J.defaultDecimalFormatOptions={defaultFormatString:Ke.DEFAULT_FORMAT_STRING}),J.defaultIntegerFormatOptions===void 0&&(J.defaultIntegerFormatOptions={defaultFormatString:dt.DEFAULT_FORMAT_STRING}),J.truncateNumbersWithPound===void 0&&(J.truncateNumbersWithPound=!1);const{shortcutOverrides:A={}}=J,q=sn.isMacPlatform?A.mac??{}:A.windows??{};Object.entries(q).forEach(([ue,ae])=>{We.get(ue)?.setKeyState(ae)});const Z={filterSets:$.filterSets,links:$.links},le=new Map(P),G="",oe={name:G,operateAs:G,groups:[],...b,permissions:{isACLEditor:!1,isSuperUser:!1,isQueryViewOnly:!1,isNonInteractive:!1,canUsePanels:!0,canCreateDashboard:!0,canCreateCodeStudio:!0,canCreateQueryMonitor:!0,canCopy:le.get("internal.webClient.appInit.canCopy")!=="false",canDownloadCsv:le.get("internal.webClient.appInit.canDownloadCsv")!=="false",canLogout:!0,...w}};t(_t.DEFAULT),g(le),n(j),s(un,Z),i(V),o(L),l(un,C),O!==void 0&&a(un,O),h(oe),m(U),u(Q)}catch(M){c0.error(M),T(M)}}D()},[p,C,t,n,s,i,o,l,a,h,u,m,g,b,w]);const y=e==null&&S==null,E=!y&&S==null,R=S!=null?`${S}`:null;return r.jsxs(r.Fragment,{children:[E&&r.jsx(l0,{}),r.jsx($l,{isLoading:y&&R==null,isLoaded:E,errorMessage:R})]})}ad.propTypes={workspace:z.shape({}),workspaceStorage:z.shape({close:z.func}),setActiveTool:z.func.isRequired,setCommandHistoryStorage:z.func.isRequired,setDashboardData:z.func.isRequired,setFileStorage:z.func.isRequired,setLayoutStorage:z.func.isRequired,setDashboardConnection:z.func.isRequired,setDashboardSessionWrapper:z.func.isRequired,setPlugins:z.func.isRequired,setUser:z.func.isRequired,setWorkspace:z.func.isRequired,setWorkspaceStorage:z.func.isRequired};ad.defaultProps={workspace:null,workspaceStorage:null};const h0=c=>({workspace:ql(c),workspaceStorage:pC(c)}),Pc=St(h0,{setActiveTool:Ql,setCommandHistoryStorage:vC,setDashboardData:ru,setFileStorage:TC,setLayoutStorage:vx,setDashboardConnection:xy,setDashboardSessionWrapper:Dy,setPlugins:yC,setUser:SC,setWorkspace:Ph,setWorkspaceStorage:wC,setServerConfigValues:RC})(ad),u0=document.location.pathname;function m0(){return r.jsx(Nm,{basename:u0,children:r.jsxs(km,{children:[r.jsx(hd,{exact:!0,path:"/",component:Pc}),r.jsx(hd,{path:"/notebooks/:notebookPath+",component:Pc}),r.jsx(Mm,{from:"*",to:"/"})]})})}function v0(){return co.registerOnLoaded(),At.init({getWorker:()=>new tg}),window["__react-beautiful-dnd-disable-dev-warnings"]=!0,r.jsx(Bc,{store:yr,children:r.jsx(m0,{})})}export{v0 as AppRoot,v0 as default};
42
+ //# sourceMappingURL=AppRoot-0af5d169.js.map