@deephaven/code-studio 0.38.1-deglobalized-jsapi.22 → 0.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/assets/AppRoot-1a29b8a5.js +42 -0
- package/build/assets/AppRoot-1a29b8a5.js.map +1 -0
- package/build/assets/AppRoot-44d1b9c4.css +1 -0
- package/build/assets/{index-bf790340.js → index-9a42370c.js} +5 -5
- package/build/assets/index-9a42370c.js.map +1 -0
- package/build/assets/{index-ad337f58.js → index-a8ae5175.js} +2 -2
- package/build/assets/{index-ad337f58.js.map → index-a8ae5175.js.map} +1 -1
- package/build/assets/{useConnection-342d64b1.js → useConnection-fb76a373.js} +2 -2
- package/build/assets/{useConnection-342d64b1.js.map → useConnection-fb76a373.js.map} +1 -1
- package/build/index.html +2 -2
- package/package.json +31 -31
- package/build/assets/AppRoot-0312ece9.css +0 -1
- package/build/assets/AppRoot-d3c11490.js +0 -42
- package/build/assets/AppRoot-d3c11490.js.map +0 -1
- package/build/assets/index-bf790340.js.map +0 -1
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import{C as r,G as X,A as v,I as Xu,B as U,F as z,J as _c,H as oe,K as ce,L as _a,M as bs,N as We,O as we,P as Pc,Q as Ze,S as tr,T as Zu,U as Qu,V as Ju,W as em,X as le,R as ll,Y as ld,Z as Ge,_ as nr,$ as tm,a0 as nm,a1 as jc,a2 as Oe,a3 as Pa,E as sm,D as Vt,a4 as Ll,a5 as Hc,a6 as sr,a7 as im,a8 as In,a9 as om,aa as lm,ab as am,ac as rm,ad as ja,ae as dm,af as cm,ag as hm,ah as ad,ai as um,aj as rd,ak as mm,al as gm,am as pm,an as fm,ao as Cm,ap as Sm,aq as mt,ar as Uc,as as bm,at as Bc,au as wm,av as Vc,aw as vm,ax as Tm,ay as Em,az as ym,aA as dd,aB as Rm}from"./vendor-4a7e2c7c.js";import{P as be,u as vs,T as _l,B as P,a as D,S as He,M as fe,K as ve,G as Yn,b as Jt,C as te,c as tn,D as $n,d as xi,e as Pl,f as Je,g as co,I as Ei,U as xm,h as pe,i as F,j as Zs,F as Wn,k as gn,l as ir,E as Ie,m as N,n as jn,o as ws,p as tl,q as it,r as $e,s as st,t as jl,v as Im,O as Un,w as Dm,x as hn,y as rn,z as Fm,A as Nm,R as Hl,H as Gn,J as Ul,L as $c,N as Wc,Q as km,V as Mm,W as cd,X as Ve,Y as hd,Z as Gc,_ as or,$ as ud,a0 as io,a1 as zc,a2 as Om,a3 as Kc,a4 as Am,a5 as nn,a6 as Lm,a7 as _m,a8 as Pm,a9 as jm,aa as Hm,ab as Um,ac as Bm,ad as Vm,ae as $m,af as Wm,ag as Gm,ah as zm}from"./useConnection-fb76a373.js";import{e as zn,l as xn,K as en,a as md,R as Km,b as gs,W as Ym}from"./monaco-6eaf53f7.js";import{v as Ha,d as qm,a as Yc,b as lr,L as Nn,c as ho,e as Vn,f as qc,g as J,h as gd,i as Xm,j as Zm,k as Qm,l as Jm,m as $t,n as Ss,o as Xc,p as Kn,q as Bl,r as yi,s as eg,t as tg,u as pd,w as al,x as fd,y as Zc,z as ng,A as uo,B as Qc,C as sg,D as ig,E as og,T as Ye,F as ar,G as rr,H as rl,I as On,J as lg,K as ag,M as rg,N as dg,O as cg,P as dr,Q as Ts,R as Cd,S as mo,U as cr,V as hr,W as Jc,X as hg,Y as Vl,Z as ug,_ as dl,$ as mg,a0 as ur,a1 as eh,a2 as Gs,a3 as gg,a4 as pg,a5 as fg,a6 as Cg,a7 as Sg,a8 as bg,a9 as Sd,aa as ga,ab as wg,ac as vg,ad as Tg,ae as $l,af as Wl,ag as Eg,ah as yg,ai as Gl,aj as th,ak as Rg,al as xg,am as Ig,an as nh,ao as Dg,ap as Fg,aq as Ng,ar as kg,as as Mg,at as Og,au as Ag,av as Lg,aw as _g,ax as Pg,ay as jg,az as Hg,aA as Ug,aB as sh,aC as Bg,aD as Ua,aE as Ba,aF as Vg,aG as $g,aH as Wg,aI as Gg,aJ as zg,aK as Kg,aL as Yg,aM as qg,aN as Xg,aO as Zg,aP as Qg,aQ as Jg,aR as ep,aS as bd,aT as tp,aU as np,aV as sp}from"./index-9a42370c.js";import{P as cl,b as ip,h as op,p as lp,o as ap,s as rp,t as dp,c as pa}from"./plotly-788bff8c.js";import"./helpers-042e6b4d.js";class mr{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),mr.getBrightness(i)<125}static getBrightness(e){return Math.round((e[0]*299+e[1]*587+e[2]*114)/1e3)}}const ih=mr,cp="table_",wd="column_",hp=new Set(["in","not","i","ii","k"]),up=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"]),mp=/[^a-zA-Z0-9_$+@-]/g,gp=/[^A-Za-z0-9_$]/g;class js{static legalize=(e,t,n,s,i)=>{let o=e.trim().replace(/[- ]/g,"_");return s&&(hp.has(o)||up.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=>js.legalize(e,cp,mp,!1,0);static legalizeColumnNames=e=>{const t=[];return e.forEach((n,s)=>{let i=js.legalizeColumnName(n,s);t.includes(i)&&(i=wd+s),t.push(i)}),t};static legalizeColumnName=(e,t=0)=>js.legalize(e,wd,gp,!0,t);static isValidTableName=e=>js.legalizeTableName(e)===e;static isValidColumnName=e=>js.legalizeColumnName(e)===e}const Ii=js;function pp(c,e){return c?c.closest(`.${e}`):null}const fp={getClosestByClassName:pp};class Cp{pending=[];resolved=[];add(e,t){const n=be.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 qn=Cp;class Sp extends Error{isInvalid=!0}const wi=Sp;function oh({type:c}){const e=vs();switch(c){case e.VariableType.TABLE:case e.VariableType.TABLEMAP:case e.VariableType.TREETABLE:case e.VariableType.HIERARCHICALTABLE:return r.jsx(X,{icon:lr});case e.VariableType.FIGURE:return r.jsx(X,{icon:Yc});case e.VariableType.PANDAS:return r.jsx(X,{icon:qm});default:return r.jsx(X,{icon:Ha})}}class bp extends v.Component{constructor(e){super(e),this.container=null}componentDidMount(){this.colorize()}container;colorize(){const{children:e}=this.props;this.container&&e!=null&&zn.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 zl=bp;class wp{static get LANGUAGE_MAP(){return new Map([["python","Python"],["groovy","Groovy"],["scala","Scala"]])}}const lh=wp;class hl{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)?[]:Xu.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,t){return t===e.VariableType.TABLE||t===e.VariableType.TREETABLE||t===e.VariableType.HIERARCHICALTABLE}static isWidgetType(e,t){return t===e.VariableType.FIGURE||t===e.VariableType.OTHERWIDGET||t===e.VariableType.PANDAS}static isOpenableType(e,t){return hl.isTableType(e,t)||hl.isWidgetType(e,t)}static isFigureType(e,t){return t===e.VariableType.FIGURE}static isPandas(e,t){return t===e.VariableType.PANDAS}}const Va=hl;function ah({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})]})}ah.propTypes={children:U.node.isRequired};class vp 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:z("console-history-result-in-progress",{disabled:e}),children:r.jsxs("span",{className:"badge",children:[r.jsx(Nn,{})," Running... ",_l.formatElapsedTime(n)," ",r.jsx(P,{className:"console-history-result-in-progress-cancel",kind:"ghost",icon:ho,tooltip:"Cancel",onClick:t,disabled:e})]})})}}const Tp=vp;class ul 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)>=ul.mouseDragThreshold||Math.abs(e.clientY-this.mouseY)>=ul.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;D(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:z("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(X,{icon:e?Vn:qc,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 Ep=ul;const vd=J.module("ConsoleHistoryItem");class yp 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){vd.debug("handleObjectClick",e);const{openObject:t}=this.props;t(e)}handleCancelClick(){const{item:e}=this.props;e!=null&&e.cancelResult&&(vd.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(zl,{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(f=>{a=!0;const{title:C}=f,S=`${C}`,b=e===void 0||e||(s??[]).indexOf(S)>=0,w=r.jsx(P,{kind:"primary",onClick:()=>this.handleObjectClick(f),className:"btn-console-object",disabled:b,icon:r.jsx(oh,{type:f.type}),children:C},S);l.push(w)})}if(h!=null&&t.command==null){let g=`${h.message??h}`;g||(g=h);const p=r.jsx(Ep,{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(Tp,{onCancelClick:this.handleCancelClick,disabled:e},"in_progress");l.push(h)}let d=null;return l.length>0&&(d=r.jsx(ah,{children:l})),r.jsxs("div",{className:z("console-command-result",{"console-result-buttons":a}),children:[o,d]})}}const Rp=yp;class gr 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(Rp,{disabled:e,item:l,openObject:s,language:n},gr.itemKey(o,l));i.push(a)}return r.jsx("div",{className:"container-fluid console-history",children:i})}}const xp=gr,Ip={name:"Console",CLEAR:He.createAndAdd({id:"CONSOLE.CLEAR",name:"Clear",shortcut:[fe.CTRL,ve.L],macShortcut:[fe.CTRL,ve.C]}),FOCUS_HISTORY:He.createAndAdd({id:"CONSOLE.FOCUS_HISTORY",name:"Focus History",shortcut:[fe.CTRL,ve.H],macShortcut:[fe.CTRL,fe.OPTION,ve.H]})},Dp={name:"Command History",FOCUS_HISTORY:He.createAndAdd({id:"COMMAND_HISTORY.FOCUS_HISTORY",name:"Focus History Search",shortcut:[fe.CTRL,ve.H],macShortcut:[fe.CTRL,fe.OPTION,ve.H]}),SEND_TO_CONSOLE:He.createAndAdd({id:"COMMAND_HISTORY.SEND_TO_CONSOLE",name:"Send to Console",shortcut:[ve.ENTER],macShortcut:[ve.ENTER]}),SEND_TO_NOTEBOOK:He.createAndAdd({id:"COMMAND_HISTORY.SEND_TO_NOTEBOOK",name:"Send to Notebook",shortcut:[fe.CTRL,ve.ENTER],macShortcut:[fe.CMD,ve.ENTER]}),RUN:He.createAndAdd({id:"COMMAND_HISTORY.RUN",name:"Run",shortcut:[fe.ALT,ve.R],macShortcut:[fe.OPTION,ve.R]})},Fp={name:"Notebook",RUN:He.createAndAdd({id:"NOTEBOOK.RUN",name:"Run",shortcut:[fe.ALT,ve.R],macShortcut:[fe.OPTION,ve.R]}),RUN_SELECTED:He.createAndAdd({id:"NOTEBOOK.RUN_SELECTED",name:"Run Selected",shortcut:[fe.ALT,fe.SHIFT,ve.R],macShortcut:[fe.OPTION,fe.SHIFT,ve.R]}),FIND:He.createAndAdd({id:"NOTEBOOK.FIND",name:"Find",shortcut:[fe.CTRL,ve.F],macShortcut:[fe.CMD,ve.F],isEditable:!1}),MINIMAP:He.createAndAdd({id:"NOTEBOOK.MINIMAP",name:"Show Minimap",shortcut:[fe.ALT,ve.M],macShortcut:[fe.OPTION,ve.M]}),WORDWRAP:He.createAndAdd({id:"NOTEBOOK.WORDWRAP",name:"Word Wrap",shortcut:[fe.ALT,ve.Z],macShortcut:[fe.OPTION,ve.Z]})},Np={CONSOLE:Ip,COMMAND_HISTORY:Dp,NOTEBOOK:Fp},Rt=Np,ct=Object.freeze({FATAL:"FATAL",STDERR:"STDERR",ERROR:"ERROR",WARN:"WARN",STDOUT:"STDOUT",INFO:"INFO",DEBUG:"DEBUG",TRACE:"TRACE"}),kp="#2d2a2e",Mp="#fcfcfa",Op="#fcd65b",Ap="#b2b1b2",Lp="#9edc6f",_p="#76d9e4",Pp="#f95d84",jp="#aa9af4",Hp="#f95d84",Up="#fcfcfa",Bp="#7c7b7c",ue={"error-foreground":"#f95d84",background:kp,foreground:Mp,"line-height":"19px",string:Op,"string-delim":"#929192",delimiter:Ap,predefined:Lp,keyword:_p,storage:Pp,number:jp,operator:Hp,identifier:Up,"namespace-identifier":"#f95d84","identifier-js":"#fcd65b",comment:Bp,"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"},Vp="python",$p={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/}}},Wp={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"]]}},Gp={id:Vp,conf:$p,language:Wp},zp=Gp,Kp="groovy",Yp={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/}}},qp={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"]]}},Xp={id:Kp,conf:Yp,language:qp},Zp=Xp,Qp="scala",Jp={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>))/}}},ef={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"]]}},tf={id:Qp,conf:Jp,language:ef},nf=tf,sf="deephavenDb",of={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/}}},lf={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"]]}},af={id:sf,conf:of,language:lf},rf=af,df="log",cf={},hf={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"}]]}},uf={id:df,conf:cf,language:hf},mf=uf,bn=J.module("MonacoUtils");class Tn{static init({getWorker:e}={}){bn.debug("Initializing Monaco..."),e!==void 0&&Tn.registerGetWorker(e);const{registerLanguages:t,removeHashtag:n}=Tn,s=[{token:"",foreground:n(ue.foreground)},{token:"string",foreground:n(ue.string)},{token:"string.delim",foreground:n(ue["string-delim"])},{token:"keyword",foreground:n(ue.keyword)},{token:"identifier.js",foreground:n(ue["identifier-js"])},{token:"delimiter",foreground:n(ue.delimiter)},{token:"comment",foreground:n(ue.comment)},{token:"number",foreground:n(ue.number)},{token:"storage",foreground:n(ue.storage)},{token:"identifier",foreground:n(ue.identifier)},{token:"namespace.identifier",foreground:n(ue["namespace-identifier"])},{token:"operator",foreground:n(ue.operator)},{token:"predefined",foreground:n(ue.predefined)},{token:"error.log",foreground:ue["log-error"].substring(1)},{token:"warn.log",foreground:n(ue["log-warn"])},{token:"info.log",foreground:n(ue["log-info"])},{token:"stdout.log",foreground:n(ue["log-stdout"])},{token:"trace.log",foreground:n(ue["log-trace"])},{token:"debug.log",foreground:n(ue["log-debug"])},{token:"date.log",foreground:n(ue["log-date"])}],i={errorForeground:ue["error-foreground"],"inputOption.activeBorder":ue["input-option-active-border"],"editor.background":ue.background,"editor.foreground":ue.foreground,"editor.lineHighlightBackground":ue["editor-line-highlight-bg"],"editorLineNumber.foreground":ue["editor-line-number-foreground"],"editor.selectionBackground":ue["editor-selection-background"],"editor.findMatchBackground":ue["editor-find-match-background"],"editor.findMatchHighlightBackground":ue["editor-find-match-highlight-background"],"editorSuggestWidget.background":ue["editor-suggest-widget-background"],"editorSuggestWidget.border":ue["editor-suggest-widget-border"],"editorSuggestWidget.foreground":ue["editor-suggest-widget-foreground"],"editorSuggestWidget.selectedBackground":ue["editor-suggest-widget-selected-background"],"editorSuggestWidget.highlightForeground":ue["editor-suggest-widget-highlightForeground"],"list.hoverBackground":ue["list-hover-background"],"dropdown.background":ue["context-menu-background"],"dropdown.foreground":ue["context-menu-foreground"],"menu.selectionBackground":ue["menu-selection-background"],"list.focusBackground":ue["menu-selection-background"],"editorWidget.background":ue["editor-widget-background"],"inputOption.activeBackground":ue["input-option-active-background"],"inputOption.activeForeground":ue["input-option-active-foreground"],focusBorder:ue["focus-border"],"input.background":ue["input-background"],"input.foreground":ue["input-foreground"],"input.border":ue["input-border"],"textLink.foreground":ue["text-link-foreground"],"textLink.activeForeground":ue["text-link-active-foreground"],"editorLink.activeForeground":ue["editor-link-active-foreground"]};zn.defineTheme("dh-dark",{base:"vs-dark",inherit:!0,rules:s,colors:i}),bn.debug2("monaco theme: ",ue),zn.setTheme("dh-dark"),t([rf,zp,Zp,mf,nf]),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);xn.getLanguages().filter(({id:n})=>t.includes(n)).forEach(n=>{const s=n;bn.debug2("Overriding default language loader:",s.id)}),e.forEach(n=>{Tn.registerLanguage(n)})}static registerLanguage(e){bn.debug2("Registering language: ",e.id),xn.register(e),xn.onLanguage(e.id,()=>{xn.setLanguageConfiguration(e.id,e.conf),xn.setMonarchTokensProvider(e.id,e.language)})}static setEOL(e,t=zn.EndOfLineSequence.LF){e.getModel()?.setEOL(t)}static openDocument(e,t){const n=e.getModel();D(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,f={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(f)}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();D(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();D(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=>{Tn.isMacPlatform()&&n.mac===""||!Tn.isMacPlatform()&&n.windows===""||Tn.removeKeybinding(e,Tn.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:Tn.isMacPlatform()?(t.metaKey?en.CtrlCmd:0)|(t.shiftKey?en.Shift:0)|(t.altKey?en.Alt:0)|(t.ctrlKey?en.WinCtrl:0)|md.fromString(n):(t.ctrlKey?en.CtrlCmd:0)|(t.shiftKey?en.Shift:0)|(t.altKey?en.Alt:0)|(t.metaKey?en.WinCtrl:0)|md.fromString(n)}static provideLinks(e){const t=[];for(let n=1;n<=e.getLineCount();n+=1){const s=e.getLineContent(n);_c(s).filter(l=>l.type==="url"?/^https?:\/\//.test(l.value):!0).forEach(l=>{t.push({url:l.href,range:new Km(n,l.start+1,n,l.end+1)})})}return{links:t}}}const Mt=Tn,An=J.module("MonacoCompletionProvider");class Hs extends v.PureComponent{static lspToMonacoKind(e){const t=xn.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=xn.registerCompletionItemProvider(e,{provideCompletionItems:this.handleCompletionRequest,triggerCharacters:[".",'"',"'"]}),t.getSignatureHelp&&(this.registeredSignatureProvider=xn.registerSignatureHelpProvider(e,{provideSignatureHelp:this.handleSignatureRequest,signatureHelpTriggerCharacters:["(",","]})),t.getHover&&(this.registeredHoverProvider=xn.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:Hs.monacoToLspPosition(t),context:n},l=i.getCompletionItems(o);return An.debug("Requested completion items",o),l.then(d=>(An.debug("Completion items received: ",o,d),{incomplete:!0,suggestions:d.map(u=>{const{label:m,kind:g,detail:p,documentation:f,sortText:C,filterText:S,textEdit:b,insertTextFormat:w}=u;return{label:m,kind:Hs.lspToMonacoKind(g),detail:p,documentation:f?.kind==="markdown"?f:f?.value,sortText:C,filterText:S,insertText:b.text,insertTextRules:w===2?4:w,range:Hs.lspToMonacoRange(b.range)}})})).catch(d=>(An.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:Hs.monacoToLspPosition(t),context:s},d=l.getSignatureHelp(a);return An.debug("Requested signature help",a),d.then(u=>{An.debug("Signatures received: ",a,d);const m=u.map(p=>{const{label:f,documentation:C,parameters:S}=p;return{documentation:C?.kind==="markdown"?C:C?.value,label:f,parameters:S??[]}});if(m.length===0)return i;const g=0;return{value:{signatures:m,activeSignature:g,activeParameter:u[g].activeParameter},dispose:()=>{}}}).catch(u=>(An.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:Hs.monacoToLspPosition(t)},o=s.getHover(i);return An.debug("Requested hover",i),o.then(a=>{An.debug("Hover received: ",i,a);const{contents:d}=a;return{contents:d?[d]:[]}}).catch(a=>(An.error("There was an error retrieving hover",a),{contents:[]}))}render(){return null}}const rh=Hs;const fa=J.module("ConsoleInput"),nl=parseInt(ue["line-height"],10),ch=6,hh=6,gf=nl+ch+hh,Ca=100;class pr extends v.PureComponent{static defaultProps={maxHeight:nl*10,scope:null,disabled:!1};static INPUT_CLASS_NAME="console-input";constructor(e){super(e),this.handleWindowResize=this.handleWindowResize.bind(this),this.commandContainer=oe.createRef(),this.commandHistoryIndex=null,this.timestamp=Date.now(),this.bufferIndex=0,this.history=[],this.modifiedCommands=new Map,this.state={commandEditorHeight:nl,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&&(fa.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:nl,lineDecorationsWidth:3,lineNumbers:"off",minimap:{enabled:!1},renderLineHighlight:"none",scrollBeyondLastLine:!1,scrollbar:{arrowSize:0,horizontal:"hidden",horizontalScrollbarSize:0},padding:{top:ch,bottom:hh},tabCompletion:"on",value:"",wordWrap:"on"},s=this.commandContainer.current;D(s),this.commandEditor=zn.create(s,n),Mt.setEOL(this.commandEditor),Mt.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();D(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===gs.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===gs.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(en.CtrlCmd|gs.KeyF,()=>{}),Mt.removeConflictingKeybindings(this.commandEditor),Mt.registerPasteHandler(this.commandEditor),this.commandEditor.focus(),this.updateDimensions(),this.setState({model:this.commandEditor.getModel()})}destroyCommandEditor(){const{session:e}=this.props;this.commandEditor&&(Mt.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();D(e);const t=e.getLineLength(1)+1,n=this.commandEditor?.getTopForPosition(1,t);D(n),this.commandEditor?.setPosition({lineNumber:1,column:t}),this.commandEditor?.setScrollTop(n),this.commandEditor?.focus()}focusEnd(){const e=this.commandEditor?.getModel();D(e);const t=e.getLineCount(),n=e.getLineLength(t)+1,s=this.commandEditor?.getTopForPosition(t,n);D(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-Ca&&this.loadMoreHistory()}async loadMoreHistory(){try{if(this.loadingPromise!=null||this.bufferIndex==null)return;const{commandHistoryStorage:e,language:t,scope:n}=this.props;this.loadingPromise=be.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+Ca-1}),this.loadingPromise=be.makeCancelable(s.getViewportData(),()=>s.close());const i=await this.loadingPromise;this.bufferIndex+=Ca,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,be.isCanceled(e)){fa.debug2("Promise canceled, not loading history");return}fa.error("Error fetching history",e)}}processCommand(e){this.commandHistoryIndex=null,this.modifiedCommands.clear(),D(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;D(e);const t=this.commandEditor.getContentHeight(),n=Math.max(Math.min(t,e),gf),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:z("console-input-wrapper",{disabled:e}),children:r.jsxs("div",{className:z("console-input-inner-wrapper",{focus:i}),children:[r.jsx("div",{className:pr.INPUT_CLASS_NAME,ref:this.commandContainer,style:{height:s}}),o&&r.jsx(rh,{model:o,language:t,session:n})]})})}}const Td=pr;const Ed="pasted values",pf=[/^audio.*/,/^font.*/,/^image.*/,/^video.*/],Sa=[".csv",".tsv",".tab",".psv",".dsv",".txt"],yd=[".zip"];class Us 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"&&!pf.find(t=>t.test(e.type))}static isValidExtension(e,t=!1){return Sa.some(n=>e.endsWith(n))||t&&yd.some(n=>e.endsWith(n))}static handleDragOver(e){e.preventDefault(),e.stopPropagation()}static getIcon(e){return e===Ed?gd:e.endsWith(".csv")?Xm:e.endsWith(".zip")?Zm:Qm}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=oe.createRef(),this.divElem=oe.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();D(i),Us.isValidExtension(i.name,t)?this.handleFile(i):this.setState({dropError:Us.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:Ed,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:gd,action:this.handleMenuPaste,shortcut:Yn.PASTE,disabled:e}]}getValidExtensions=ce(e=>e?[...Sa,...yd]:[...Sa]);getAcceptString=ce(e=>this.getValidExtensions(e).join(", "));getFileTypeErrorString=ce(e=>Jt.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:Us.handleDragOver,onDrop:this.handleDrop,tabIndex:-1,children:[r.jsx(te,{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(X,{icon:Jm})}),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(P,{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(X,{icon:Us.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(P,{kind:"ghost",className:"ml-2",onClick:this.unstageFile,icon:$t,tooltip:"Remove"})]})]})]}),Boolean(o)&&r.jsxs("div",{className:"message-content",children:[r.jsx("div",{className:"message-icon",children:r.jsx(X,{icon:Ss})}),r.jsx("label",{children:o}),o===Us.FILE_TYPE_ERROR&&r.jsx("div",{className:"message-small",children:r.jsx("label",{children:this.getFileTypeErrorString(e)})})]})]})}}const ci=Us;class ff{static INTEGER="int";static LONG="long";static DOUBLE="double";static BOOLEAN="bool";static STRING="string";static DATE_TIME="datetime";static LOCAL_TIME="localtime"}const ke=ff,Rd="unknown",Cf=2147483647,Sf=-2147483648,xd=/^[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]+)?$/,Id=/^([0-9]+T)?([0-9]+):([0-9]+)(:[0-9]+)?(?:\.[0-9]{1,9})?$/;class St{static determineType(e,t,n){if(!e||e===n)return t;switch(t){case ke.STRING:return ke.STRING;case ke.INTEGER:return St.checkInteger(e);case ke.LONG:return St.checkLong(e);case ke.DOUBLE:return St.checkDouble(e);case ke.BOOLEAN:return St.checkBoolean(e);case ke.DATE_TIME:return St.checkDateTime(e);case ke.LOCAL_TIME:return St.checkLocalTime(e);default:return St.getTypeFromUnknown(e)}}static isNotParsableNumber(e){return isNaN(e)||e==="Infinity"||e==="-Infinity"}static checkInteger(e){const t=e.replace(/,/g,"");return St.isNotParsableNumber(t)?ke.STRING:St.getNumberType(t)}static checkLong(e){const t=e.replace(/,/g,"");return St.isNotParsableNumber(t)?ke.STRING:t.includes(".")?ke.DOUBLE:ke.LONG}static checkDouble(e){const t=e.replace(/,/g,"");return St.isNotParsableNumber(t)?ke.STRING:ke.DOUBLE}static checkBoolean(e){const t=e.toLowerCase();return t==="true"||t==="false"?ke.BOOLEAN:ke.STRING}static checkDateTime(e){return xd.test(e)?ke.DATE_TIME:ke.STRING}static checkLocalTime(e){return Id.test(e)?ke.LOCAL_TIME:ke.STRING}static getTypeFromUnknown(e){const t=e.replace(/,/g,"");if(St.isNotParsableNumber(t)){const n=e.toLowerCase();return n==="true"||n==="false"?ke.BOOLEAN:xd.test(e)&&e.includes(":")?ke.DATE_TIME:Id.test(e)?ke.LOCAL_TIME:ke.STRING}return St.getNumberType(t)}static getNumberType(e){if(e.includes("."))return ke.DOUBLE;const t=e.startsWith("-")?11:10;if(e.length>t)return ke.LONG;const n=parseInt(e,10);return n>Cf||n<Sf?ke.LONG:ke.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;_a.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(Rd),this.readHeaders&&(n=n.slice(1))}D(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]=St.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
|
+
Expected length ${s.length} but found ${l.length}.
|
|
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;D(t),(e==null||!e.meta.aborted)&&n(t.map(s=>s===Rd?ke.STRING:s))}handleError(e){const{onError:t}=this;t(e)}handleNodeUpdate(e){this.zipProgress=e.percent}}const bf=St,_o=J.module("CsvParser"),wf=650;class Xi{static generateHeaders=e=>{const t=[];for(let n=0;n<e;n+=1)t.push(Xi.generateHeaderRecursive(n));return t};static generateHeaderRecursive(e){let t="",n=e;return e>=26&&(t=t.concat(Xi.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/_a.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
|
+
${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,_a.parse(s,this.config)};new bf(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){_o.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=Xi.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>=wf||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,D(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(),D(this.headers),D(a),s.newTable(this.headers,a,t,this.timeZone).then(u=>{if(this.isCancelled){_o.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),_o.debug2(`CSV parser progress ${m}`),d(m),this.isComplete&&i.length===this.chunks&&(_o.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 vf=Xi;class Tf{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
|
+
`,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!0,nullString:null},EXCEL_CSV:{name:"Excel csv (strict)",delimiter:",",newline:`\r
|
|
7
|
+
`,escapeChar:'"',shouldTrim:!0,skipEmptyLines:!1,nullString:null},MY_SQL_CSV:{name:"MySQL csv",delimiter:" ",newline:`
|
|
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 Ki=Tf;const Dd=J.module("CsvInputBar"),Ef=Object.entries(Ki.TYPES).map(([c,e])=>r.jsx("option",{value:c,children:e.name},c));class yf 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=oe.createRef(),this.state={tableName:"",tableNameSet:!1,isFirstRowHeaders:!0,showProgress:!1,progressValue:0,type:Ki.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:Ki.fromExtension(t.name)}):n!=null&&n!==""&&(e.paste===void 0||e.paste==="")&&this.setState({type:Ki.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;Dd.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){Dd.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 vf({onFileCompleted:d,session:n,file:e,type:Ki.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(ci.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:z("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:Ef})]}),r.jsx(tn,{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(P,{kind:"secondary",onClick:this.handleCancel,children:"Cancel"}),r.jsx(P,{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(P,{kind:"primary",onClick:this.handleCancelInProgress,children:"Cancel"})]})]})}}const Rf=yf;const Fd=J.module("ConsoleMenu");class ml extends v.PureComponent{static makeItemActions(e,t,n,s,i){if(e.length===0)return[];const o={menuElement:r.jsx(xi,{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=ce((e,t,n)=>{const{dh:s}=this.props,i=e.filter(o=>Va.isTableType(s,o.type));return ml.makeItemActions(i,t,o=>{this.tableSearchField=o},this.handleTableFilterChange,n)});makeWidgetActions=ce((e,t,n)=>{const{dh:s}=this.props,i=e.filter(o=>Va.isWidgetType(s,o.type));return ml.makeItemActions(i,t,o=>{this.widgetSearchField=o},this.handleWidgetFilterChange,n)});handleTableFilterChange(e){Fd.debug("filtering tables..."),this.setState({tableFilterText:e.target.value})}handleTableMenuClosed(){this.setState({tableFilterText:""})}handleTableMenuOpened(){this.tableSearchField?.focus()}handleWidgetFilterChange(e){Fd.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(P,{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(X,{mask:lr,icon:Vn,transform:"right-5 down-5"}),r.jsx(X,{icon:Vn,transform:"right-8 down-6"})]}),r.jsx($n,{actions:o,onMenuOpened:this.handleTableMenuOpened,onMenuClosed:this.handleTableMenuClosed,options:{initialKeyboardIndex:1},popperOptions:a},"table-actions ")]}),r.jsxs(P,{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(X,{mask:Yc,icon:Vn,transform:"right-5 down-5"}),r.jsx(X,{icon:Vn,transform:"right-8 down-6"})]}),r.jsx($n,{actions:l,onMenuOpened:this.handleWidgetMenuOpened,onMenuClosed:this.handleWidgetMenuClosed,options:{initialKeyboardIndex:1},popperOptions:a},"table-actions")]}),r.jsx(P,{kind:"ghost",className:"btn-overflow btn-link-icon",icon:Xc,tooltip:"More Actions...",onClick:()=>{},children:r.jsx($n,{actions:e,popperOptions:a})})]})}}const xf=ml;class If 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 qn,this.state={isDisconnected:!1,isCommandRunning:!1}}componentDidMount(){this.startListening()}componentWillUnmount(){this.stopListening(),this.cancelPendingPromises()}pending;startListening(){const{dh:e,session:t}=this.props;t.addEventListener(e.IdeSession.EVENT_COMMANDSTARTED,this.handleCommandStarted)}stopListening(){const{dh:e,session:t}=this.props;t.removeEventListener(e.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 Pl||this.setState({isCommandRunning:this.pending.pending.length>0})}render(){const{children:e,dh:t,openObject:n,overflowActions:s,objects:i}=this.props,{isDisconnected:o,isCommandRunning:l}=this.state;let a=null,d=null;return o?(a="console-status-icon-disconnected",d="Worker is disconnected"):l?(a="console-status-icon-pending",d="Worker is busy"):(a="console-status-icon-idle",d="Worker is idle"),r.jsxs("div",{className:"console-pane-status-bar",children:[r.jsxs("div",{children:[r.jsx("div",{className:z("console-status-icon",a)}),r.jsx(Je,{children:d})]}),e,r.jsx(xf,{dh:t,overflowActions:s,openObject:n,objects:i})]})}}const Df=If,Ln=J.module("Console"),Nd={isAutoLaunchPanelsEnabled:!0,isPrintStdOutEnabled:!0,isClosePanelsOnDisconnectEnabled:!0};class hi 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||hi.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=oe.createRef(),this.consoleInput=oe.createRef(),this.consoleHistoryScrollPane=oe.createRef(),this.pending=new qn,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,...Nd,...n}}componentDidMount(){this.initConsoleLogging();const{dh:e,session:t}=this.props;t.addEventListener(e.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{dh:e,session:t}=this.props;t.removeEventListener(e.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=>{Ln.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 Ln.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(be.isCanceled(e)){Ln.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&&hi.isOutputLevel(e.logLevel)&&this.queueLogMessage(e.message,e.logLevel)}queueLogMessage(e,t){const n={};hi.isErrorLevel(t)?n.error=e:n.message=e;const s={command:void 0,result:n};this.queuedLogMessages.push(s),this.processLogMessageQueue()}processLogMessageQueue=bs(()=>{this.scrollConsoleHistoryToBottom(),this.setState(e=>{Ln.debug2("processLogMessageQueue",this.queuedLogMessages.length," items");let{consoleHistory:t}=e;return t=t.concat(this.queuedLogMessages),this.queuedLogMessages=[],{consoleHistory:t}})},hi.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)){Ln.debug2("updateKnownObjects no changes");return}this.setState(n=>{let{consoleHistory:s}=n;const i=s.lastIndexOf(e);if(i<0)return Ln.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;D(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;D(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=>{Ln.warn("Error updating command history storage",d)})}).catch(i=>{Ln.debug("Error updating workspace history item",i)})}scrollConsoleHistoryToBottom(e=!1){const t=this.consoleHistoryScrollPane.current;D(t),!(!e&&t.scrollTop<t.scrollHeight-t.offsetHeight)&&window.requestAnimationFrame(()=>{t.scrollTop=t.scrollHeight})}handleScrollPaneScroll(){const e=this.consoleHistoryScrollPane.current;D(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:ci.MULTIPLE_FILE_ERROR});return}const n=t[0];ci.isValidDropItem(n)?this.setState({dragError:null}):this.setState({dragError:ci.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{dh:t,openObject:n,commandHistoryStorage:s,language:i,scope:o}=this.props,{consoleHistory:l,objectMap:a}=this.state,d={name:e,title:e,type:t.VariableType.TABLE},h=a.has(e),u={startTime:Date.now(),endTime:Date.now(),disabledObjects:[],result:{changes:{created:[],updated:[],removed:[],[h?"updated":"created"]:[d]}}},m=l.concat(u);this.setState({consoleHistory:m}),this.scrollConsoleHistoryToBottom(!0),this.updateKnownObjects(u),n({name:e,title:e,type:t.VariableType.TABLE}),s.addItem(i,o,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:te.groups.high,icon:n?Kn:void 0,order:10},{title:"Auto Launch Panels",action:this.handleToggleAutoLaunchPanels,group:te.groups.high,icon:e?Kn:void 0,order:20},{title:"Close Panels on Disconnect",action:this.handleToggleClosePanelsOnDisconnect,group:te.groups.high,icon:t?Kn:void 0,order:30},{title:"Upload Table from File",action:this.handleUploadCsv,group:te.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=>{Ln.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=ce(e=>[...e.values()]);getContextActions=ce(e=>[...e,{action:this.handleClearShortcut,shortcut:Rt.CONSOLE.CLEAR},{action:this.handleFocusHistory,shortcut:Rt.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(Nd),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,dh:t,historyChildren:n,language:s,statusBarChildren:i,openObject:o,session:l,scope:a,commandHistoryStorage:d,timeZone:h,disabled:u,unzip:m}=this.props,{consoleHeight:g,consoleHistory:p,isScrollDecorationShown:f,objectMap:C,showCsvOverlay:S,csvFile:b,csvPaste:w,dragError:T,csvUploadInProgress:E}=this.state,y=this.getObjects(C),R=Math.round(g*.7),I=this.getContextActions(e);return r.jsxs("div",{role:"presentation",className:z("iris-console","h-100","w-100",{disabled:u}),children:[r.jsxs("div",{className:"console-pane",ref:this.consolePane,children:[r.jsx(Df,{dh:t,session:l,overflowActions:this.handleOverflowActions,openObject:o,objects:y,children:i}),r.jsxs("div",{className:"console-csv-container",onDragOver:ci.handleDragOver,onDragEnter:this.handleDragEnter,onDragLeave:this.handleDragLeave,children:[S&&r.jsx(ci,{onCancel:this.handleCsvFileCanceled,onFileOpened:this.handleCsvFileOpened,onPaste:this.handleCsvPaste,clearDragError:this.handleClearDragError,dragError:T,onError:this.handleCsvError,uploadInProgress:E,allowZip:m!=null}),r.jsxs("div",{role:"presentation",className:z("scroll-pane no-scroll-x",{"scroll-decoration":f}),onScroll:this.handleScrollPaneScroll,ref:this.consoleHistoryScrollPane,children:[r.jsx(xp,{items:p,openObject:o,language:s,disabled:u}),n]})]}),!S&&r.jsx(Td,{ref:this.consoleInput,session:l,language:s,scope:a,onSubmit:this.handleCommandSubmit,maxHeight:R,commandHistoryStorage:d}),S&&r.jsx(Rf,{session:l,onOpenTable:this.handleOpenCsvTable,onClose:this.handleHideCsv,onUpdate:this.handleCsvUpdate,onError:this.handleCsvError,file:b??void 0,paste:w??void 0,onInProgress:this.handleCsvInProgress,timeZone:h,unzip:m})]}),r.jsx(te,{actions:I,ignoreClassNames:[Td.INPUT_CLASS_NAME]})]})}}const Ff=hi;class Nf 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();D(t),zn.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},D(this.container),this.editor=zn.create(this.container,t),this.editor.addAction({id:"find",label:"Find",keybindings:[en.CtrlCmd|gs.KeyF],precondition:void 0,keybindingContext:void 0,contextMenuGroupId:"navigation",contextMenuOrder:1,run:()=>{this.toggleFind()}}),this.editor.layout(),Mt.removeConflictingKeybindings(this.editor),xn.registerLinkProvider("plaintext",{provideLinks:Mt.provideLinks}),e(this.editor)}destroyEditor(){const{onEditorWillDestroy:e}=this.props;D(this.editor),e(this.editor),this.editor.dispose(),this.editor=void 0}render(){const{className:e}=this.props;return r.jsx("div",{className:z("editor-container",e),ref:t=>{this.container=t}})}}const fr=Nf;const Yt=J.module("ScriptEditor");class kf 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=oe.createRef(),this.state={model:null}}componentDidMount(){He.addEventListener("onUpdate",this.updateShortcuts)}componentDidUpdate(e){const{sessionLanguage:t,settings:n}=this.props,s=n?.language;s!==e.settings?.language&&(Yt.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)&&(Yt.debug("De-init completion and context actions"),this.deInitContextActions(),this.deInitCodeCompletion()),(t!=null&&e.sessionLanguage==null&&l||t!==void 0&&!a&&l)&&(Yt.debug("Init completion and context actions"),this.initContextActions(),this.initCodeCompletion())}componentWillUnmount(){He.removeEventListener("onUpdate",this.updateShortcuts)}contextActionCleanups;completionCleanup;editor;editorComponent;getValue(){return this.editor?this.editor.getValue():(Yt.error("Editor not initialized"),null)}getSelectedCommand(){const e=this.editor?.getSelection();D(e);const t=this.editor?.getModel();D(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;Yt.debug("handleEditorInitialized",l,o,i),this.editor=e,this.setState({model:this.editor.getModel()}),Mt.setEOL(e),Mt.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){Yt.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){Yt.error("Context actions already initialized.");return}if(!this.editor)return;const e=[];e.push(this.editor.addAction({id:"run-code",label:"Run",keybindings:[Mt.getMonacoKeyCodeFromShortcut(Rt.NOTEBOOK.RUN)],contextMenuGroupId:"navigation",contextMenuOrder:1.5,run:()=>{this.handleRun()}})),e.push(this.editor.addAction({id:"run-selected-code",label:"Run Selected",keybindings:[Mt.getMonacoKeyCodeFromShortcut(Rt.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){Yt.error("Code completion already initialized.");return}const{session:e}=this.props;Yt.debug("initCodeCompletion",this.editor,e),this.editor&&e!=null&&(this.completionCleanup=Mt.openDocument(this.editor,e))}deInitCodeCompletion(){const{session:e}=this.props;Yt.debug("deInitCodeCompletion",this.editor,e),this.completionCleanup&&(this.completionCleanup.dispose(),this.completionCleanup=void 0,this.editor&&e!=null&&Mt.closeDocument(this.editor,e))}append(e,t=!0){D(this.editor);const n=this.editor.getModel();D(n);const s=n.getValue();s?n.setValue(`${s}
|
|
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(){Yt.debug("updateDimensions"),this.editor&&this.editor.layout()}focus(){Yt.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(Bl,{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(fr,{ref:this.editorComponent,settings:o,onEditorInitialized:this.handleEditorInitialized,onEditorWillDestroy:this.handleEditorWillDestroy}),h!=null&&h&&r.jsx(rh,{model:l,language:d,session:s})]})})]})}}const Mf=kf,Of={groovy:"Groovy",python:"Python",scala:"Scala"};class Af{static normalizeScriptLanguage(e){return Of[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 kd=Af;const Lf=250,_f=2500;class Cr 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":_l.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=We(()=>{const{commandHistoryStorage:e,item:t,language:n}=this.props,{id:s}=t;this.cleanup=e.listenItem(n,s,this.handleUpdate,this.handleError)},Lf);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=we(e=>e.split(`
|
|
11
|
+
`,_f).join(`
|
|
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=Cr.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(zl,{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(X,{icon:Ss})," Executed with errors"]}),r.jsxs("div",{className:"time-wrapper",children:["Elapsed time:"," ",m?r.jsx("span",{className:"time-string",children:h}):r.jsx(Nn,{})]})]}),Boolean(d)&&r.jsx("div",{className:"error-message",children:d})]})]})}}const Pf=Cr,jf=512;function uh(c){const{item:e,language:t,isSelected:n,commandHistoryStorage:s}=c,i=e.name.substring(0,jf),o=v.useRef(null),l=v.useCallback(()=>{o.current?.update()},[o]);return r.jsxs("div",{className:z("command-history-item",{selected:n}),children:[i,r.jsx(Je,{ref:o,interactive:!0,options:{placement:"left",modifiers:{preventOverflow:{enabled:!0,boundariesElement:"viewport",order:825}}},popperClassName:"command-history-item-popper",children:r.jsx(Pf,{item:e,language:t,onUpdate:l,commandHistoryStorage:s})})]})}uh.defaultProps={isSelected:!1};class gl 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(X,{icon:yi,mask:e.icon,transform:"right-5 down-5 shrink-4"}),r.jsx(X,{icon:eg,transform:"shrink-3 right-7 down-6"})]}):r.jsx(X,{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(P,{kind:"inline",className:z(n.className),onClick:n.action,tooltip:n.description,disabled:n.selectionRequired!==void 0&&n.selectionRequired&&!t,icon:gl.renderContent(n)},gl.itemKey(s,n)))})}}const Hf=gl;const Uf=150,Bf=150,Md=3,Od=J.module("CommandHistoryViewportUpdater");function Vf({table:c,columns:e,top:t=0,bottom:n=0,search:s,isReversed:i=!1,onUpdate:o}){const l=v.useMemo(()=>We(d=>{c.setSearch(d??"")},Uf),[c]),a=v.useMemo(()=>bs(d=>{const h=d.bottom-d.top,u=Math.max(0,d.top-h*Md),m=d.bottom+h*Md;c.setViewport({top:u,bottom:m,columns:d.columns})},Bf),[c]);return v.useEffect(function(){const h=c.onUpdate(u=>{o({items:u.items??[],offset:u.offset??0})});return()=>{Od.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(()=>()=>{Od.debug2("Cancel throttledUpdateViewport"),a.cancel()},[a]),null}const ts=J.module("CommandHistory");class En extends v.Component{static ITEM_HEIGHT=29;static MAX_SELECTION_COUNT=1e4;static menuGroups={send:te.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:tg,shortcut:Yn.COPY,action:this.copySelectedCommands,group:te.groups.edit},{title:"Send to Console",description:"Open selected commands in the console",icon:pd,shortcut:Rt.COMMAND_HISTORY.SEND_TO_CONSOLE,action:this.sendToConsole,group:En.menuGroups.send,order:10},{title:"Run in Console",description:"Run selected commands in the console",icon:al,shortcut:Rt.COMMAND_HISTORY.RUN,action:this.runInConsole,group:En.menuGroups.send,order:10},{title:"Send to Active Notebook",description:"Open selected commands in a notebook",icon:fd,shortcut:Rt.COMMAND_HISTORY.SEND_TO_NOTEBOOK,action:this.sendToNotebook,group:En.menuGroups.send,order:20},{title:"Send to New Notebook",description:"Open selected commands in a new notebook",icon:Zc,action:this.createNotebook,group:En.menuGroups.send,order:30}],this.historyActions=[{title:"Send to Console",icon:pd,selectionRequired:!0,description:"Open selected commands in the console",action:this.sendToConsole},{title:"Send to Notebook",icon:fd,selectionRequired:!0,description:"Open selected commands in a notebook",action:this.sendToNotebook}],this.pending=new qn,this.searchInputRef=oe.createRef(),this.itemListRef=oe.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 En.getCommandsFromViewport(e,t,s);const{table:i}=this.props;return this.pending.add(En.getCommandsFromSnapshot(i,s))}getSelectedCommandText(){return this.getSelectedCommands().then(e=>e.join(`
|
|
13
|
+
`))}updateActions(){this.setState(e=>{const{selectedRanges:t}=e,n=t.reduce((s,i)=>s+i[1]-i[0]+1,0);return n>0&&n<En.MAX_SELECTION_COUNT?(ts.debug("Updating actions",this.itemActions),{actions:this.itemActions}):(ts.debug("Disabling actions",n),{actions:[]})})}copySelectedCommands(){this.getSelectedCommandText().then(co).catch(ts.error)}createNotebook(){this.getSelectedCommandText().then(e=>{const{language:t,sendToNotebook:n}=this.props;n({value:e,language:t},!0)}).catch(ts.error)}sendToNotebook(){this.getSelectedCommandText().then(e=>{const{language:t,sendToNotebook:n}=this.props;n({value:e,language:t})}).catch(ts.error)}sendToConsole(){const{sendToConsole:e}=this.props;this.getSelectedCommandText().then(e).catch(ts.error)}runInConsole(){this.getSelectedCommandText().then(e=>{const{sendToConsole:t}=this.props;t(e,!0,!0)}).catch(ts.error)}handleSelect(e){const{sendToConsole:t}=this.props,{items:n,offset:s}=this.state;if(e<s||e>=s+n.length){ts.error("Invalid index!",e);return}const{name:i}=n[e-s];t(i)}handleSelectionChange(e){this.setState({selectedRanges:e}),this.updateActions()}handleViewportChange(e,t){this.setState({top:e,bottom:t})}handleSearchChange(e){this.setState({searchText:e.target.value,selectedRanges:[]})}handleViewportUpdate({items:e,offset:t}){const{table:n}=this.props,s=n.size;this.setState({items:e,itemCount:s,offset:t})}renderItem({item:e,itemIndex:t,isSelected:n}){const{language:s,commandHistoryStorage:i}=this.props;return r.jsx(uh,{isSelected:n,item:e,language:s,commandHistoryStorage:i})}focus(){this.searchInputRef.current&&this.searchInputRef.current.focus()}restoreScrollPosition(){this.itemListRef.current?.restoreScrollPosition()}render(){const{language:e,table:t}=this.props,{actions:n,historyActions:s,searchText:i,top:o,bottom:l,items:a,itemCount:d,offset:h,selectedRanges:u}=this.state,m=lh.LANGUAGE_MAP.get(e)??"";return r.jsxs("div",{className:"command-history",children:[r.jsxs("div",{className:"command-history-search-bar",children:[r.jsx(xi,{ref:this.searchInputRef,value:i,placeholder:`${m} Command History`,onChange:this.handleSearchChange}),r.jsx(Hf,{actions:s,hasSelection:u.length>0})]}),r.jsxs("div",{className:"command-history-list",children:[r.jsx(Ei,{ref:this.itemListRef,itemCount:d,items:a,offset:h,selectedRanges:u,onSelect:this.handleSelect,onSelectionChange:this.handleSelectionChange,onViewportChange:this.handleViewportChange,renderItem:this.renderItem,rowHeight:En.ITEM_HEIGHT,isDoubleClickSelect:!0,isMultiSelect:!0,isStickyBottom:!0}),r.jsx(Vf,{table:t,top:o,bottom:l,search:i,onUpdate:this.handleViewportUpdate}),r.jsx(te,{actions:n})]})]})}}const $f=En;class Wf extends v.PureComponent{constructor(e){super(e),this.handleSwitchClick=this.handleSwitchClick.bind(this)}handleSwitchClick(){const{logLevel:e,onClick:t}=this.props;t(e)}render(){const{logLevel:e,on:t}=this.props;return r.jsxs("div",{className:z("log-level-menu-item",e),children:[r.jsx(xm,{on:t,onClick:this.handleSwitchClick}),e]})}}const Gf=Wf;class bt extends v.PureComponent{static DefaultLogLevels=[ct.STDOUT,ct.ERROR,ct.FATAL,ct.STDERR,ct.WARN];static AllLogLevels=[ct.INFO,ct.STDOUT,ct.ERROR,ct.FATAL,ct.STDERR,ct.WARN,ct.DEBUG,ct.TRACE];static bufferTimeout=16;static maxLogSize=131072;static truncateSize=65536;static getLogText(e){const t=new Date(e.micros/1e3);return`${Va.formatTimestamp(t)} ${e.logLevel} ${e.message}`}constructor(e){super(e),this.handleClearClick=this.handleClearClick.bind(this),this.handleFlushTimeout=this.handleFlushTimeout.bind(this),this.handleLogMessage=this.handleLogMessage.bind(this),this.handleMenuItemClick=this.handleMenuItemClick.bind(this),this.handleResetClick=this.handleResetClick.bind(this),this.handleResize=this.handleResize.bind(this),this.handleToggleAllClick=this.handleToggleAllClick.bind(this),this.logLevelMenuItems={},this.editorContainer=null,this.bufferedMessages=[],this.messages=[],this.state={shownLogLevels:{}}}componentDidMount(){this.resetLogLevels(),this.initMonaco(),this.startListening(),window.addEventListener("resize",this.handleResize)}componentDidUpdate(e,t){this.updateDimensions();const{shownLogLevels:n}=this.state;t.shownLogLevels!==n&&this.refreshLogText();const{session:s}=this.props;e.session!==s&&(this.stopListening(),this.startListening(),this.clearLogs())}componentWillUnmount(){this.stopFlushTimer(),this.stopListening(),this.destroyMonaco(),window.removeEventListener("resize",this.handleResize)}cancelListener;editor;editorContainer;logLevelMenuItems;flushTimer;bufferedMessages;messages;getMenuActions(e){const t=[];t.push({menuElement:r.jsx("div",{className:"log-level-menu-title",children:"Display Log Levels"}),group:1,order:10});for(let n=0;n<bt.AllLogLevels.length;n+=1){const s=bt.AllLogLevels[n],i=e[s]!=null?e[s]:!1;t.push({title:s,group:1,order:n+100,menuElement:r.jsx(Gf,{logLevel:s,on:i,onClick:this.handleMenuItemClick,ref:o=>{o!=null&&(this.logLevelMenuItems[s]=o)}})})}return t.push({group:1,order:1e3,menuElement:r.jsxs("div",{className:"log-level-menu-controls",children:[r.jsx(P,{kind:"ghost",className:"log-level-toggle-all",onClick:this.handleToggleAllClick,children:"Toggle All"}),r.jsx(P,{kind:"ghost",onClick:this.handleResetClick,children:"Reset"})]})}),t}resetLogLevels(){const e={};for(let t=0;t<bt.AllLogLevels.length;t+=1){const n=bt.AllLogLevels[t],s=bt.DefaultLogLevels.some(i=>i===n);e[n]=s}this.setState({shownLogLevels:e})}startListening(){const{session:e}=this.props;this.cancelListener=e.onLogMessage(this.handleLogMessage)}stopListening(){this.cancelListener!=null&&(this.cancelListener(),this.cancelListener=void 0)}initMonaco(){D(this.editorContainer),this.editor=zn.create(this.editorContainer,{copyWithSyntaxHighlighting:!1,fixedOverflowWidgets:!0,folding:!1,fontFamily:"Fira Mono",glyphMargin:!1,language:"log",lineDecorationsWidth:0,lineNumbers:"off",lineNumbersMinChars:0,minimap:{enabled:!1},readOnly:!0,renderLineHighlight:"none",scrollBeyondLastLine:!1,value:"",wordWrap:"on"}),this.editor.addCommand(gs.Escape,()=>{}),this.editor.addCommand(en.Shift|gs.Escape,()=>{}),this.editor.addCommand(gs.Escape,()=>{const e=this.editor?.getPosition();D(e),this.editor?.setPosition(e)},"findWidgetVisible && editorTextFocus"),this.editor.addCommand(en.Shift|gs.Escape,()=>{const e=this.editor?.getPosition();D(e),this.editor?.setPosition(e)},"findWidgetVisible && editorTextFocus")}destroyMonaco(){this.editor&&(this.editor.dispose(),this.editor=void 0)}triggerFindWidget(){this.editor?.focus(),this.editor?.trigger("keyboard","actions.find",void 0)}toggleAll(){const{shownLogLevels:e}=this.state;let t=!0;for(let n=0;n<bt.AllLogLevels.length;n+=1){const s=bt.AllLogLevels[n];if(!e[s]){t=!1;break}}if(t)this.setState({shownLogLevels:{}});else{const n={};for(let s=0;s<bt.AllLogLevels.length;s+=1){const i=bt.AllLogLevels[s];n[i]=!0}this.setState({shownLogLevels:n})}}toggleLogLevel(e){const{shownLogLevels:t}=this.state,n=t[e],s={};s[e]=!n,this.updateLogLevels(s)}updateLogLevels(e){let{shownLogLevels:t}=this.state;t={...t,...e},this.setState({shownLogLevels:t})}appendLogText(e){if(!this.editor)return;const t=this.editor.getModel();let n=t?.getLineCount();D(n);let s=t?.getLineLength(n);D(s);const i=this.isBottomVisible(),o=[];if(s>0&&(o.push({range:{startLineNumber:n,startColumn:s+1,endLineNumber:n,endColumn:s+1},text:`
|
|
14
|
+
`,forceMoveMarkers:!0}),n+=1,s=0),o.push({range:{startLineNumber:n,startColumn:s,endLineNumber:n,endColumn:s},text:e,forceMoveMarkers:!0}),t?.applyEdits(o),i){const l=t?.getLineCount();D(l),this.editor.revealLine(l,1)}}refreshLogText(){if(!this.editor)return;this.truncateLogIfNecessary();const{shownLogLevels:e}=this.state,t=this.isBottomVisible();let n="";for(let s=0;s<this.messages.length;s+=1){const i=this.messages[s];if(e[i.logLevel]){const o=bt.getLogText(i);o.length>0&&(n+=o,o.charAt(o.length-1)!==`
|
|
15
|
+
`&&(n+=`
|
|
16
|
+
`))}}if(n=n.trimRight(),this.editor.setValue(n),t){const s=this.editor.getModel()?.getLineCount();D(s),this.editor.revealLine(s,1)}this.stopFlushTimer(),this.bufferedMessages=[]}truncateLogIfNecessary(){this.messages.length>bt.maxLogSize&&(this.messages=this.messages.splice(this.messages.length-bt.truncateSize))}scrollToBottom(){if(!this.editor)return;const e=this.editor?.getModel?.()?.getLineCount();D(e),this.editor.revealLine(e,1)}isBottomVisible(){if(!this.editor)return!0;const t=this.editor.getModel()?.getLineCount();return D(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=bt.getLogText(n);e+=s,s.charAt(s.length-1)!==`
|
|
17
|
+
`&&(e+=`
|
|
18
|
+
`)}this.bufferedMessages=[],this.appendLogText(e)}queue(e){this.bufferedMessages.push(e),this.bufferedMessages.length===1&&(this.flushTimer=setTimeout(this.handleFlushTimeout,bt.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(P,{kind:"ghost",className:"btn-clear-logs",onClick:this.handleClearClick,icon:ng,tooltip:"Clear log"}),r.jsx(P,{kind:"ghost",className:"btn-link-icon btn-overflow",icon:uo,tooltip:"Log Settings",onClick:()=>{},children:r.jsx($n,{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 zf=bt;function mh(c){switch(c){case pe.eq:return"is exactly";case pe.eqIgnoreCase:return"is exactly (ignore case)";case pe.notEq:return"is not exactly";case pe.notEqIgnoreCase:return"is not exactly (ignore case)";case pe.contains:return"contains";case pe.notContains:return"does not contain";case pe.startsWith:return"starts with";case pe.endsWith:return"ends with";default:throw new Error(`Unrecognized text filter type ${c}`)}}function gh(c){switch(c){case pe.eq:return"is equal to";case pe.notEq:return"is not equal to";case pe.greaterThan:return"greater than";case pe.greaterThanOrEqualTo:return"greater than or equal to";case pe.lessThan:return"less than";case pe.lessThanOrEqualTo:return"less than or equal to";default:throw new Error(`Unrecognized number filter type ${c}`)}}function ph(c){switch(c){case pe.eq:return"date is";case pe.notEq:return"date is not";case pe.notEqIgnoreCase:case pe.greaterThan:return"date is after";case pe.greaterThanOrEqualTo:return"date is after or equal";case pe.lessThan:return"date is before";case pe.lessThanOrEqualTo:return"date is before or equal";default:throw new Error(`Unrecognized date filter type ${c}`)}}function Kf(c){switch(c){case pe.isTrue:return"Is True";case pe.isFalse:return"Is False";case pe.isNull:return"Is Null";default:throw new Error(`Unrecognized boolean filter type ${c}`)}}cl.register([ip,op,lp,ap,rp,dp]);const fh=typeof pa=="function"?pa(cl):pa.default(cl);class yn{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(e){this.dh=e,this.listeners=[],this.isDownsamplingDisabled=!1}dh;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(yn.EVENT_UPDATED,{detail:e}))}fireDisconnect(){this.fireEvent(new CustomEvent(yn.EVENT_DISCONNECT))}fireReconnect(){this.fireEvent(new CustomEvent(yn.EVENT_RECONNECT))}fireDownsampleStart(e){this.fireEvent(new CustomEvent(yn.EVENT_DOWNSAMPLESTARTED,{detail:e}))}fireDownsampleFinish(e){this.fireEvent(new CustomEvent(yn.EVENT_DOWNSAMPLEFINISHED,{detail:e}))}fireDownsampleFail(e){this.fireEvent(new CustomEvent(yn.EVENT_DOWNSAMPLEFAILED,{detail:e}))}fireDownsampleNeeded(e){this.fireEvent(new CustomEvent(yn.EVENT_DOWNSAMPLENEEDED,{detail:e}))}fireLoadFinished(){this.fireEvent(new CustomEvent(yn.EVENT_LOADFINISHED))}}const Pn=yn,Yf="#76d9e4 #9edc6f #fcd65b #aa9af4 #f37e3f #f95d84 #f0f0ee",qf="#403e41",Xf="#5b5a5c",Zf="#c0bfbf",Qf="#4878ea",Jf="rgba(91, 90, 92, 0.7)",ft={"paper-bgcolor":"#2d2a2e","plot-bgcolor":"#322f33","title-color":"#f0f0ee",colorway:Yf,gridcolor:qf,linecolor:Xf,zerolinecolor:Zf,activecolor:Qf,rangebgcolor:Jf,"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"},kt=Object.freeze({paper_bgcolor:ft["paper-bgcolor"],plot_bgcolor:ft["plot-bgcolor"],title_color:ft["title-color"],colorway:ft.colorway,gridcolor:ft.gridcolor,linecolor:ft.linecolor,zerolinecolor:ft.zerolinecolor,activecolor:ft.activecolor,rangebgcolor:ft.rangebgcolor,area_color:ft["area-color"],trend_color:ft["trend-color"],line_color:ft["line-color"],error_band_line_color:ft["error-band-line-color"],error_band_fill_color:ft["error-band-fill-color"],ohlc_increasing:ft["ohlc-increasing"],ohlc_decreasing:ft["ohlc-decreasing"]}),Pi=J.module("ChartUtils"),Ad="io.deephaven.time.DateTime",eC=36e5,tC=1e6;function nC(c){return c.asDate!==void 0}function sC(c){return c.asNumber!==void 0}function Ld(c){return c.dhTimeZone!==void 0}function iC(c){return c!=null&&c.range!=null&&(c.autorange===!1||c.autorange===void 0)}class de{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 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 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*)(%?)(.*)/);D(i);const[,o,l,a,,d,h,u,m,g]=i,p=a.replace(",","").length,C=l.indexOf(",")>=0||a.indexOf(",")>=0?",":"",S=u!=null&&u!==""?"e":"f",b=m!==""?m:S,w=d.length+h.length,E=`0${p}${C}.${w}${b}`,y=de.convertNumberPrefix(o),R=de.convertNumberPrefix(g);return{tickformat:E,tickprefix:y,ticksuffix:R,automargin:!0}}static addTickSpacing(e,t,n){const{gapBetweenMajorTicks:s}=t;if(s>0){const i=e||{};let o=s;return n&&(o=s/tC),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=de.ORIENTATION.VERTICAL){return{type:e,mode:t,name:n,orientation:i,showlegend:s??void 0}}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 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];iC(o)&&(t[i]=[...o.range])}return t}static getAxisLayoutProperty(e,t){const n=t>0?`${t+1}`:"";return`${e??""}axis${n}`}static periodToDecimal(e){const t=e.split(":");return Number(t[0])+Number(t[1])/60}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 getColorwayFromTheme(e=kt){let t=[];return e.colorway&&(Array.isArray(e.colorway)?t=e.colorway:typeof e.colorway=="string"?t=e.colorway.split(" "):Pi.warn(`Unable to handle colorway property: ${e.colorway}`)),t}static titleFromSettings(e){const{series:t,xAxis:n,title:s=`${(t??[]).join(", ")} by ${n}`}=e;return s}dh;daysOfWeek;constructor(e){this.dh=e,this.daysOfWeek=Object.freeze(e.calendar.DayOfWeek.values())}getAxisFormats(e,t){const n=new Map,s={tickformat:null,ticksuffix:null},i=de.getAllAxes(e),o=de.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 f=g[p],{axis:C}=f,{type:S}=C,b=o.get(S);D(b);const w=b.indexOf(C),T=this.getAxisPropertyName(S);if(T!=null){const E=de.getAxisLayoutProperty(T,w);if(n.has(E))Pi.debug(`${E} already added.`);else{Pi.debug(`Adding ${E} to axisFormats.`);const y=this.getPlotlyAxisFormat(f,t);if(y===null)n.set(E,s);else{n.set(E,y);const{businessCalendar:R}=C;if(R!=null){const I=[],{businessPeriods:x,businessDays:A,holidays:k,timeZone:_}=R,M=t?.getColumnTypeFormatter(Ad);let $;Ld(M)&&($=M.dhTimeZone);const H=$?(_.standardOffset-$.standardOffset)/60:0;k.length>0&&I.push(...this.createRangeBreakValuesFromHolidays(k,_,$)),x.forEach(K=>I.push({pattern:"hour",bounds:[de.periodToDecimal(K.close)+H,de.periodToDecimal(K.open)+H]})),A.length<this.daysOfWeek.length&&this.createBoundsFromDays(A).forEach(K=>I.push({pattern:"day of week",bounds:K})),y.rangebreaks=I}if(n.size===d.axes.length)return n}}}}}}return n}getPlotlyChartType(e,t){const{dh:n}=this;switch(e){case n.plot.SeriesPlotStyle.SCATTER:return t?"scatter":"scattergl";case n.plot.SeriesPlotStyle.LINE:return"scatter";case n.plot.SeriesPlotStyle.BAR:case n.plot.SeriesPlotStyle.STACKED_BAR:return"bar";case n.plot.SeriesPlotStyle.PIE:return"pie";case n.plot.SeriesPlotStyle.TREEMAP:return"treemap";case n.plot.SeriesPlotStyle.HISTOGRAM:return"histogram";case n.plot.SeriesPlotStyle.OHLC:return"ohlc";default:return}}getPlotlyChartMode(e,t,n){const{dh:s}=this,i=new Set;switch(e){case s.plot.SeriesPlotStyle.SCATTER:(t??!1)&&i.add(de.MODE_LINES),(n??!0)&&i.add(de.MODE_MARKERS);break;case s.plot.SeriesPlotStyle.LINE:(t??!0)&&i.add(de.MODE_LINES),(n??!1)&&i.add(de.MODE_MARKERS);break}return i.size>0?[...i].join("+"):void 0}getPlotlyProperty(e,t){const{dh:n}=this;switch(e){case n.plot.SeriesPlotStyle.PIE:switch(t){case n.plot.SourceType.X:return"labels";case n.plot.SourceType.Y:return"values"}break;case n.plot.SeriesPlotStyle.OHLC:switch(t){case n.plot.SourceType.TIME:return"x"}break;case n.plot.SeriesPlotStyle.TREEMAP:switch(t){case n.plot.SourceType.X:return"ids";case n.plot.SourceType.Y:return"values";case n.plot.SourceType.LABEL:return"labels";case n.plot.SourceType.PARENT:return"parents";case n.plot.SourceType.COLOR:return"marker.colors"}break}switch(t){case n.plot.SourceType.X:return"x";case n.plot.SourceType.Y:return"y";case n.plot.SourceType.Z:return"z";case n.plot.SourceType.X_LOW:return"xLow";case n.plot.SourceType.X_HIGH:return"xHigh";case n.plot.SourceType.Y_LOW:return"yLow";case n.plot.SourceType.Y_HIGH:return"yHigh";case n.plot.SourceType.TIME:return"time";case n.plot.SourceType.OPEN:return"open";case n.plot.SourceType.HIGH:return"high";case n.plot.SourceType.LOW:return"low";case n.plot.SourceType.CLOSE:return"close";case n.plot.SourceType.SHAPE:return"shape";case n.plot.SourceType.SIZE:return"size";case n.plot.SourceType.LABEL:return"label";case n.plot.SourceType.COLOR:return"color";case n.plot.SourceType.PARENT:return"parent";case n.plot.SourceType.HOVER_TEXT:return"hovertext";case n.plot.SourceType.TEXT:return"text";default:throw new Error(`Unrecognized source type: ${t}`)}}getPlotlySeriesOrientation(e){const{dh:t}=this,{sources:n}=e;return n.length===2&&n[0]?.axis?.type===t.plot.AxisType.Y?de.ORIENTATION.HORIZONTAL:de.ORIENTATION.VERTICAL}makeSeriesDataFromSeries(e,t,n,s=null,i=kt){const{name:o,isLinesVisible:l,isShapesVisible:a,plotStyle:d,lineColor:h,shapeColor:u,sources:m,shape:g,shapeSize:p}=e,f=m.some(T=>T.axis?.businessCalendar),C=this.getChartType(d,f),S=this.getPlotlyChartMode(d,l??void 0,a??void 0),b=this.getPlotlySeriesOrientation(e),w=de.makeSeriesData(C,S,o,s,b);return this.addSourcesToSeriesData(w,d,m,t),this.addStylingToSeriesData(w,d,i,h,u,g,p,n),w}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=this.getPlotlyProperty(t,d);Pc(i,h,[]);const u=a!=null?this.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}`}}}}addStylingToSeriesData(e,t,n=kt,s=null,i=null,o=null,l=null,a=null){const{dh:d}=this,h=e;if(h.marker={line:{}},h.line={width:1},t===d.plot.SeriesPlotStyle.AREA?h.fill="tozeroy":t===d.plot.SeriesPlotStyle.STACKED_AREA?h.stackgroup="stack":t===d.plot.SeriesPlotStyle.STEP?h.line.shape="hv":t===d.plot.SeriesPlotStyle.HISTOGRAM?(h.width=[],h.marker.line!==void 0&&Object.assign(h.marker.line,{color:n.paper_bgcolor,width:1})):t===d.plot.SeriesPlotStyle.OHLC?(h.increasing={line:{color:n.ohlc_increasing}},h.decreasing={line:{color:n.ohlc_decreasing}}):t===d.plot.SeriesPlotStyle.PIE?(h.textinfo="label+percent",h.outsidetextfont={color:n.title_color}):t===d.plot.SeriesPlotStyle.TREEMAP&&(h.hoverinfo="text",h.textinfo="label+text",h.tiling={packing:"squarify",pad:0},h.textposition="middle center",h.outsidetextfont={color:n.title_color}),s!=null&&(t===d.plot.SeriesPlotStyle.BAR?h.marker.color=s:h.line.color=s),i!=null&&(h.marker.color=i),o!=null&&o.length>0)try{h.marker.symbol=de.getMarkerSymbol(o)}catch(u){Pi.warn("Unable to handle shape",o,":",u)}l!=null&&(h.marker.size=l*de.DEFAULT_MARKER_SIZE),a!=null&&t!==d.plot.SeriesPlotStyle.PIE&&(h.visible=a)}getChartType(e,t){const{dh:n}=this;switch(e){case n.plot.SeriesPlotStyle.HISTOGRAM:return"bar";default:return this.getPlotlyChartType(e,t)}}getAxisPropertyName(e){const{dh:t}=this;switch(e){case t.plot.AxisType.X:return"x";case t.plot.AxisType.Y:return"y";default:return null}}getAxisSide(e){const{dh:t}=this;switch(e){case t.plot.AxisPosition.BOTTOM:return"bottom";case t.plot.AxisPosition.TOP:return"top";case t.plot.AxisPosition.LEFT:return"left";case t.plot.AxisPosition.RIGHT:return"right";default:return}}updateFigureAxes(e,t,n,s=0,i=0,o=kt){const l=e,a=de.getAllAxes(t);for(let d=0;d<t.charts.length;d+=1){const h=t.charts[d],u=n?.(h),m=this.getChartBounds(t,h,s,i);this.updateLayoutAxes(l,h.axes,a,s,i,m,u,o)}this.removeStaleAxes(l,a)}getChartBounds(e,t,n,s){const{dh:i}=this,{cols:o,rows:l}=e,{column:a,colspan:d,row:h,rowspan:u}=t,m=a+d,g=h+u,p=1/o,f=1/l,C=de.AXIS_SIZE_PX/n,S=de.AXIS_SIZE_PX/s,b={bottom:(l-g)*f+(g<l?S/2:0),top:(l-h)*f-(h>0?S/2:0),left:a*p+(a>0?C/2:0),right:m*p-(m<o?C/2:0)};return(de.groupArray(t.axes,"position").get(i.plot.AxisPosition.RIGHT)??[]).length>0&&(n>0?b.right-=(b.right-b.left)*Math.max(0,Math.min(de.LEGEND_WIDTH_PX/n,de.MAX_LEGEND_SIZE)):b.right-=(b.right-b.left)*de.DEFAULT_AXIS_SIZE),b}getPlotlyDateFormat(e,t,n){const{dh:s}=this,i=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 o;const l=e?.getColumnTypeFormatter(t);return l!=null&&Ld(l)&&l.dhTimeZone!=null&&l.showTimeZone&&(o=s.i18n.DateTimeFormat.format(" z",new Date,l.dhTimeZone)),{tickformat:i,ticksuffix:o,automargin:!0}}getPlotlyAxisFormat(e,t=null){const{dh:n}=this,{axis:s,columnType:i}=e,{formatPattern:o}=s;let l=null;return F.isDateType(i)?(l=this.getPlotlyDateFormat(t,i,o),l=de.addTickSpacing(l,s,!0)):F.isNumberType(i)&&(l=de.getPlotlyNumberFormat(t,i,o),l=de.addTickSpacing(l,s,!1)),s.formatType===n.plot.AxisFormatType.CATEGORY&&(l?l.type="category":l={type:"category",tickformat:void 0,ticksuffix:void 0}),l}updateLayoutAxes(e,t,n,s=0,i=0,o={left:0,top:0,right:1,bottom:1},l,a=kt){const{dh:d}=this,h=s>0?Math.max(de.MIN_AXIS_SIZE,Math.min(de.AXIS_SIZE_PX/i,de.MAX_AXIS_SIZE)):de.DEFAULT_AXIS_SIZE,u=i>0?Math.max(de.MIN_AXIS_SIZE,Math.min(de.AXIS_SIZE_PX/s,de.MAX_AXIS_SIZE)):de.DEFAULT_AXIS_SIZE,m=e,g=de.groupArray(t,"position"),p=de.groupArray(t,"type"),f=[...p.keys()],C=de.groupArray(n,"type");for(let S=0;S<f.length;S+=1){const b=f[S],w=this.getAxisPropertyName(b);if(w!=null){const T=p.get(b),E=C.get(b),R=b===d.plot.AxisType.Y?i:s;D(T),D(E);for(let I=0;I<T.length;I+=1){const x=T[I],A=E.indexOf(x),k=de.getAxisLayoutProperty(w,A);m[k]==null&&(m[k]=this.makeLayoutAxis(b,a));const _=m[k];if(_!=null){this.updateLayoutAxis(_,x,I,g,h,u,o);const{range:M,autorange:$}=_;if(l!=null&&M!==void 0&&($===void 0||$===!1)){const H=l(x),[K,L]=H(M);Pi.debug("Setting downsample range",R,K,L),x.range(R,K,L)}else x.range(R)}}}}}removeStaleAxes(e,t){const n=e,s=de.groupArray(t,"type"),i=[...s.keys()];for(let o=0;o<i.length;o+=1){const l=i[o],a=s.get(l);D(a);let d=a.length;const h=this.getAxisPropertyName(l);if(h!=null){let u=de.getAxisLayoutProperty(h,d);for(;n[u]!=null;)delete n[u],d+=1,u=de.getAxisLayoutProperty(h,d)}}}updateLayoutAxis(e,t,n,s,i,o,l){const{dh:a}=this,h=t.type===a.plot.AxisType.Y?o:i,u=e,m=t.label??"";if(u.title!==void 0&&typeof u.title!="string"?u.title.text=m:u.title={text:m},t.log&&(u.type="log"),u.side=this.getAxisSide(t.position),n>0){u.overlaying=this.getAxisPropertyName(t.type)??void 0;const g=s.get(t.position)??[],p=g.indexOf(t);p>0&&(u.anchor="free",t.position===a.plot.AxisPosition.RIGHT?u.position=l.right+(p-g.length+1)*h:t.position===a.plot.AxisPosition.TOP?u.position=l.top+(p-g.length+1)*h:t.position===a.plot.AxisPosition.BOTTOM?u.position=l.bottom+(g.length-p+1)*h:t.position===a.plot.AxisPosition.LEFT&&(u.position=l.left+(g.length-p+1)*h))}else if(t.type===a.plot.AxisType.X){const g=s.get(a.plot.AxisPosition.LEFT)||[],p=s.get(a.plot.AxisPosition.RIGHT)||[],f=Math.max(l.left,l.left+(g.length-1)*o),C=Math.min(l.right-(p.length-1)*o,l.right);u.domain=[f,C]}else if(t.type===a.plot.AxisType.Y){const g=s.get(a.plot.AxisPosition.BOTTOM)||[],p=s.get(a.plot.AxisPosition.TOP)||[],f=Math.max(l.bottom,l.bottom+(g.length-1)*i),C=Math.min(l.top-(p.length-1)*i,l.top);u.domain=[f,C]}}createBoundsFromDays(e){const t=e.map(o=>this.daysOfWeek.indexOf(o)),n=this.daysOfWeek.filter(o=>!e.includes(o)).map(o=>this.daysOfWeek.indexOf(o)),s=new Set;n.forEach(o=>{for(let l=o+1;l<o+this.daysOfWeek.length;l+=1){const a=l%this.daysOfWeek.length;if(t.includes(a)){s.add(a);break}}});const i=[];return s.forEach(o=>{for(let l=o-1;l>o-this.daysOfWeek.length;l-=1){const a=l<0?l+this.daysOfWeek.length:l;if(t.includes(a)){const d=(a+1)%7;i.push([d,o]);break}}}),i}createRangeBreakValuesFromHolidays(e,t,n){const s=[],i=[];return e.forEach(o=>{o.businessPeriods.length>0?i.push(...this.createPartialHoliday(o,t,n)):s.push(this.createFullHoliday(o,t,n))}),[{values:s},...i]}createFullHoliday(e,t,n){return this.adjustDateForTimeZone(`${e.date.toString()} 00:00:00.000000`,t,n)}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=[this.adjustDateForTimeZone(`${s} ${a}:00.000000`,t,n)],u=eC*(de.periodToDecimal(d)-de.periodToDecimal(a));o.push({values:h,dvalue:u})}}return o}adjustDateForTimeZone(e,t,n){return n&&n.standardOffset!==t.standardOffset?this.unwrapValue(this.wrapValue(e,Ad,t),n):e}makeFigureSettings(e,t){const{dh:n}=this,{series:s,xAxis:i,type:o}=e,l=de.titleFromSettings(e),a={formatType:`${n.plot.AxisFormatType.NUMBER}`,type:`${n.plot.AxisType.X}`,position:`${n.plot.AxisPosition.BOTTOM}`},d={formatType:`${n.plot.AxisFormatType.NUMBER}`,type:`${n.plot.AxisType.Y}`,position:`${n.plot.AxisPosition.LEFT}`};return{charts:[{chartType:`${n.plot.ChartType.XY}`,axes:[a,d],series:(s??[]).map(h=>({plotStyle:`${o}`,name:h,dataSources:[{type:`${n.plot.SourceType.X}`,columnName:i??"",axis:a,table:t},{type:`${n.plot.SourceType.Y}`,columnName:h,axis:d,table:t}]}))}],title:l}}unwrapValue(e,t){const{dh:n}=this;if(e!=null){if(nC(e))return n.i18n.DateTimeFormat.format(de.DATE_FORMAT,e,t);if(sC(e))return e.asNumber()}return e}wrapValue(e,t,n=null){const{dh:s}=this;if(F.isDateType(t)&&typeof e=="string"){const i=e,o=de.DATE_FORMAT.substr(0,e.length),l=s.i18n.DateTimeFormat.parse(o,i);if(!n)return l;const a=`${o} Z`,d=s.i18n.DateTimeFormat.format("Z",l,n),h=s.i18n.DateTimeFormat.parse(a,`${i} ${d}`),u=s.i18n.DateTimeFormat.format("Z",h,n);return s.i18n.DateTimeFormat.parse(a,`${i} ${u}`)}return e}makeLayoutAxis(e,t=kt){const{dh:n}=this,s={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===n.plot.AxisType.X?Object.assign(s,{showgrid:!0}):e===n.plot.AxisType.Y&&Object.assign(s,{zerolinecolor:t.zerolinecolor,zerolinewidth:2}),s}makeDefaultLayout(e=kt){const{dh:t}=this,n={...e,autosize:!0,colorway:de.getColorwayFromTheme(e),font:{family:"'Fira Sans', sans-serif"},title:{font:{color:e.title_color},yanchor:"top",pad:{...de.DEFAULT_TITLE_PADDING},y:1},legend:{font:{color:e.title_color}},margin:{...de.DEFAULT_MARGIN},xaxis:this.makeLayoutAxis(t.plot.AxisType.X,e),yaxis:this.makeLayoutAxis(t.plot.AxisType.Y,e)};return n.datarevision=0,n}hydrateSettings(e){const{dh:t}=this;return{...e,type:e.type!=null?t.plot.SeriesPlotStyle[e.type]:void 0}}}const ht=de;const ns=J.module("Chart");class ui extends v.Component{static defaultProps={isActive:!0,settings:{timeZone:"America/New_York",defaultDateTimeFormat:Zs.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=oe.createRef(),this.plotWrapper=oe.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=ce((e,t,n,s)=>{const i=[],o=Boolean(e);if(o&&i.push({name:`Downsampling failed: ${e}`,click:()=>{},icon:ui.convertIcon(Qc),attr:"fill-warning"}),t||n||s||o){const l=ui.downsampleButtonTitle(n,s),a=ui.downsampleButtonAttr(n,s),d=n?sg:ig;i.push({name:l,icon:ui.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 Pn.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 Pn.EVENT_LOADFINISHED:{const{onUpdate:s}=this.props;this.isLoadedFired=!0,s({isLoading:!1});break}case Pn.EVENT_DISCONNECT:{const{onDisconnect:s}=this.props;s();break}case Pn.EVENT_RECONNECT:{const{onReconnect:s}=this.props;s();break}case Pn.EVENT_DOWNSAMPLESTARTED:{this.setState({isDownsampleFinished:!1,isDownsampleInProgress:!0,downsamplingError:null});break}case Pn.EVENT_DOWNSAMPLEFINISHED:{this.setState({isDownsampleFinished:!0,isDownsampleInProgress:!1,downsamplingError:null});break}case Pn.EVENT_DOWNSAMPLENEEDED:case Pn.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=ht.getLayoutRanges(t);!Ze(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=Wn.getColumnFormats(e),n=Wn.getDateTimeFormatterOptions(e),{decimalFormatOptions:s={},integerFormatOptions:i={}}=e;(!Ze(this.columnFormats,t)||!Ze(this.dateTimeFormatterOptions,n)||!Ze(this.decimalFormatOptions,s)||!Ze(this.integerFormatOptions,i))&&(this.columnFormats=Wn.getColumnFormats(e),this.dateTimeFormatterOptions=n,this.decimalFormatOptions=s,this.integerFormatOptions=i,this.updateFormatter())}updateFormatter(){const{model:e}=this.props,t=new gn(e.dh,this.columnFormats,this.dateTimeFormatterOptions,this.decimalFormatOptions,this.integerFormatOptions);e.setFormatter(t)}updateDimensions(){const e=this.getPlotRect();this.plot.current!=null&&e!=null&&e.width>0&&e.height>0&&cl.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(fh,{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 oC=ui,Tt=J.module("FigureChartModel");class Sr extends Pn{static ADD_SERIES_DEBOUNCE=50;constructor(e,t,n={},s=kt){super(e),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.dh=e,this.chartUtils=new ht(e),this.figure=t,this.settings=n,this.theme=s,this.data=[];const i={data:{},layout:this.chartUtils.makeDefaultLayout(s)};this.layout={grid:{rows:t.rows,columns:t.cols,pattern:"independent"},template:i},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()}chartUtils;dh;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=ht.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{dh:s}=this,i=ht.groupArray(t,"type"),o=this.chartUtils.makeSeriesDataFromSeries(e,i,ht.getSeriesVisibility(e.name,this.settings),n,this.theme);if(this.seriesDataMap.set(e.name,o),this.data=[...this.seriesDataMap.values()],e.plotStyle===s.plot.SeriesPlotStyle.STACKED_BAR?this.layout.barmode="stack":e.plotStyle===s.plot.SeriesPlotStyle.PIE&&(this.layout.hiddenlabels=ht.getHiddenLabels(this.settings)),this.layout.showlegend=this.data.length>1||e.plotStyle===s.plot.SeriesPlotStyle.PIE?n??void 0:!1,e.oneClick!=null){const{oneClick:l}=e,{columns:a}=l;for(let d=0;d<a.length;d+=1)this.filterColumnMap.set(a[d].name,a[d]);this.oneClicks.push(l)}this.updateLayoutFormats()}addPendingSeries=We(()=>{const e=ht.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=[]},Sr.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){Tt.debug("Ignoring subscribe when figure in disconnected state");return}this.figure.subscribe(this.isDownsamplingDisabled?this.dh.plot.DownsampleOptions.DISABLE:this.dh.plot.DownsampleOptions.DEFAULT)}unsubscribeFigure(){this.figure.unsubscribe()}startListeningFigure(){const{dh:e}=this;this.figure.addEventListener(e.plot.Figure.EVENT_UPDATED,this.handleFigureUpdated),this.figure.addEventListener(e.plot.Figure.EVENT_SERIES_ADDED,this.handleFigureSeriesAdded),this.figure.addEventListener(e.plot.Figure.EVENT_DISCONNECT,this.handleFigureDisconnected),this.figure.addEventListener(e.plot.Figure.EVENT_RECONNECT,this.handleFigureReconnected),this.figure.addEventListener(e.plot.Figure.EVENT_DOWNSAMPLESTARTED,this.handleDownsampleStart),this.figure.addEventListener(e.plot.Figure.EVENT_DOWNSAMPLEFINISHED,this.handleDownsampleFinish),this.figure.addEventListener(e.plot.Figure.EVENT_DOWNSAMPLEFAILED,this.handleDownsampleFail),this.figure.addEventListener(e.plot.Figure.EVENT_DOWNSAMPLENEEDED,this.handleDownsampleNeeded),this.figure.addEventListener(e.Client.EVENT_REQUEST_FAILED,this.handleRequestFailed)}stopListeningFigure(){const{dh:e}=this;this.figure.removeEventListener(e.plot.Figure.EVENT_UPDATED,this.handleFigureUpdated),this.figure.removeEventListener(e.plot.Figure.EVENT_SERIES_ADDED,this.handleFigureSeriesAdded),this.figure.removeEventListener(e.plot.Figure.EVENT_DISCONNECT,this.handleFigureDisconnected),this.figure.removeEventListener(e.plot.Figure.EVENT_RECONNECT,this.handleFigureReconnected),this.figure.removeEventListener(e.plot.Figure.EVENT_DOWNSAMPLESTARTED,this.handleDownsampleStart),this.figure.removeEventListener(e.plot.Figure.EVENT_DOWNSAMPLEFINISHED,this.handleDownsampleFinish),this.figure.removeEventListener(e.plot.Figure.EVENT_DOWNSAMPLEFAILED,this.handleDownsampleFail),this.figure.removeEventListener(e.plot.Figure.EVENT_DOWNSAMPLENEEDED,this.handleDownsampleNeeded),this.figure.removeEventListener(e.Client.EVENT_REQUEST_FAILED,this.handleRequestFailed)}getTimeZone=we((e,t)=>{if(t!=null){const n=t.getColumnTypeFormatter(e);if(n!=null)return n.dhTimeZone}});getValueTranslator=we((e,t)=>{const n=this.getTimeZone(e,t);return s=>this.chartUtils.unwrapValue(s,n)});getValueParser=we((e,t)=>{const n=this.getTimeZone(e,t);return s=>this.chartUtils.wrapValue(s,e,n)});getRangeParser=we((e,t)=>n=>{let[s,i]=n;const o=this.getValueParser(e,t);return s=o(s),i=o(i),[s,i]});getAxisRangeParser=we((e,t)=>n=>{const s=ht.getSourceForAxis(e,n);return s?this.getRangeParser(s.columnType,t):i=>i});handleDownsampleStart(e){Tt.debug("Downsample started",e),this.fireDownsampleStart(e.detail)}handleDownsampleFinish(e){Tt.debug("Downsample finished",e),this.fireDownsampleFinish(e.detail)}handleDownsampleFail(e){Tt.error("Downsample failed",e),this.fireDownsampleFail(e.detail)}handleDownsampleNeeded(e){Tt.info("Downsample needed",e),this.fireDownsampleNeeded(e.detail)}handleFigureUpdated(e){const{detail:t}=e,{series:n}=t;Tt.debug2("handleFigureUpdated",n);for(let i=0;i<n.length;i+=1){const o=n[i];Tt.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){Tt.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){Tt.debug("Figure disconnected",e),this.isConnected=!1,this.listeners.length>0&&this.unsubscribeFigure(),this.fireDisconnect()}handleFigureReconnected(e){Tt.debug("Figure reconnected",e),this.isConnected=!0,this.initAllSeries(),this.fireReconnect(),this.listeners.length>0&&this.subscribeFigure()}handleFigureSeriesAdded(e){const{detail:t}=e;Tt.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=ht.DEFAULT_MARGIN.t+t*ht.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=ht.DEFAULT_TITLE_PADDING.t+t*ht.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();this.chartUtils.updateFigureAxes(this.layout,this.figure,n=>this.getAxisRangeParser(n,this.formatter),e,t,this.theme)}updateLayoutFormats(){if(!this.formatter)return;this.chartUtils.getAxisFormats(this.figure,this.formatter).forEach((t,n)=>{Tt.debug(`Assigning ${n}`,this.layout[n],t);const s=this.layout[n];s!=null?Object.assign(s,t):Tt.debug(`Ignoring null layout.${n}`)})}setDataArrayForSeries(e,t,n){const{name:s,plotStyle:i}=e,o=this.seriesDataMap.get(s),l=this.chartUtils.getPlotlyProperty(i,t);o&&Pc(o,l,n)}cleanSeries(e){const{dh:t}=this,{name:n,plotStyle:s}=e,i=this.seriesDataMap.get(n);if(i!=null){if(s===t.plot.SeriesPlotStyle.HISTOGRAM){const{xLow:o,xHigh:l}=i;if(o&&l&&o.length===l.length){const a=[];for(let d=0;d<o.length;d+=1)a.push(l[d]-o[d]);i.width=a}}else if(s===t.plot.SeriesPlotStyle.LINE){const{x:o,xLow:l,xHigh:a,y:d,yLow:h,yHigh:u}=i;l&&a&&l!==o&&(i.error_x=ht.getPlotlyErrorBars(o,l,a)),h&&u&&h!==d&&(i.error_y=ht.getPlotlyErrorBars(d,h,u))}else if(s===t.plot.SeriesPlotStyle.TREEMAP){const{ids:o,labels:l}=i;o!==void 0&&l===void 0&&(i.labels=o)}}}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){Tt.warn("Trying to set a filter, but no one click!");return}Tt.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 _d=Sr;class br{static async makeModelFromSettings(e,t,n,s=kt){const i=await br.makeFigureFromSettings(e,t,n);return new _d(e,i,t,s)}static async makeFigureFromSettings(e,t,n){const s=await n.copy();return s.applyCustomColumns(n.customColumns),s.applyFilter(n.filter),s.applySort(n.sort),e.plot.Figure.create(new ht(e).makeFigureSettings(t,s))}static async makeModel(e,t,n,s=kt){return new _d(e,n,t,s)}}const pl=br;function Pd(c){return c.setFigure!==void 0}const lC=J.module("HeapUsage");function aC({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 k=async()=>{try{const M=await c.getWorkerHeapInfo();if(o(M),n||l){const $=(M.totalHeapSize-M.freeMemory)/M.maximumHeapSize,H=Date.now(),{timestamps:K,usages:L}=d.current;for(;K.length!==0&&H-K[0]>s*1.5;)K.shift(),L.shift();K.push(H),L.push($)}else d.current={timestamps:[],usages:[]}}catch(M){lC.warn("Unable to get heap usage",M)}};k();const _=setInterval(k,l?t:e);return()=>{clearInterval(_)}},[l,t,c,e,s,n]);const h=(A,k)=>Math.round(A*10**k)/10**k,u=2,m=1024**3,{freeMemory:g,totalHeapSize:p,maximumHeapSize:f}=i,C=h(g/m,u),S=h(p/m,u),b=h(f/m,u),w=S-C,T=(A,k,_=!1)=>r.jsxs("div",{className:z("heap-usage-info-row",{"heading-bottom-border":_}),children:[r.jsx("div",{className:"font-weight-bold",children:A}),r.jsx("div",{children:k})]}),{timestamps:E,usages:y}=d.current,R=E[E.length-1]??0,I=p/f,x=(p-g)/f;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"max-memory",children:[r.jsx("div",{className:"total-memory",style:{width:`calc(${I*100}% - ${I*2}px`}}),r.jsx("div",{className:z("used-memory",{"heap-overflow":(p-g)/f>.95}),style:{width:`calc(${x*100}% - ${x*2}px`}}),r.jsxs("div",{className:"memory-text",children:[b.toFixed(1)," GB"]})]}),r.jsx(Je,{onEntered:()=>a(!0),onExited:()=>a(!1),interactive:!0,children:r.jsxs("div",{className:"heap-tooltip",children:[T("In use:",`${w.toFixed(u)} of ${b.toFixed(u)} GB`,!0),T("Free:",`${C.toFixed(u)} GB`),T("Total:",`${S.toFixed(u)} GB`),T("Max:",`${b.toFixed(u)} GB`),r.jsx("div",{className:"heap-plot",children:r.jsx(fh,{data:[{x:[...E],y:[...y],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:kt.linecolor,range:[R-s,R],linecolor:kt.linecolor,linewidth:2,mirror:!0},yaxis:{dtick:.2,gridcolor:kt.linecolor,range:[0,1],linecolor:kt.linecolor,linewidth:2,mirror:!0}}})}),r.jsxs("div",{className:"heap-utilisation-text",children:["% utilization over ",Math.round(s/1e3/60)," min."]})]})})]})}const wr=Object.freeze({}),rC=new Map,Kl=c=>c.api,Ch=c=>c.user,vr=c=>c.storage,Sh=c=>vr(c).commandHistoryStorage,bh=c=>vr(c).fileStorage,dC=c=>vr(c).workspaceStorage,Yl=c=>c.workspace,gt=c=>Yl(c).data.settings,wh=c=>gt(c).defaultDateTimeFormat,vh=c=>gt(c).defaultDecimalFormatOptions??wr,Th=c=>gt(c).defaultIntegerFormatOptions??wr,Eh=c=>gt(c).formatter,go=c=>gt(c).timeZone,yh=c=>gt(c).showTimeZone,Rh=c=>gt(c).showTSeparator,xh=c=>gt(c).truncateNumbersWithPound,cC=c=>gt(c).shortcutOverrides,hC=c=>gt(c).defaultNotebookSettings??wr,ql=c=>c.activeTool,uC=c=>c.plugins??rC,Ih="SET_ACTIVE_TOOL",Dh="SET_API",Fh="SET_COMMAND_HISTORY_STORAGE",Nh="SET_FILE_STORAGE",kh="SET_PLUGINS",Mh="SET_USER",Oh="SET_WORKSPACE",Ah="SET_WORKSPACE_STORAGE",Lh="SET_SERVER_CONFIG_VALUES",mC=c=>({type:Mh,payload:c}),gC=c=>({type:Dh,payload:c}),_h=c=>({type:Oh,payload:c}),pC=c=>({type:Ah,payload:c}),fC=c=>({type:Fh,payload:c}),CC=c=>({type:Nh,payload:c}),SC=c=>(e,t)=>{e(_h(c));const{storage:n}=t(),{workspaceStorage:s}=n;return s.save(c)},Ph=c=>(e,t)=>{const{workspace:n}=t(),{data:s}=n,i={...n,data:{...s,...c}};return e(SC(i))},Xl=c=>e=>e(Ph({settings:c})),Zl=c=>({type:Ih,payload:c}),bC=c=>({type:kh,payload:c}),wC=c=>({type:Lh,payload:c});function jh(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 vC(c,e={},t=!0){return(n=e,s)=>{switch(s.type){case c:{const{id:i,payload:o}=s;return t&&Ze({payload:o},{payload:n[i]})?n:{...n,[i]:o}}default:return n}}}function Es(c,e){return(t=e,n)=>{switch(n.type){case c:return n.payload;default:return t}}}const TC=Es(Dh,null),EC=Es(Ih,null),yC=Es(kh,null),RC=Es(Fh,null),xC=Es(Nh,null),IC=Es(Ah,null),DC=tr({commandHistoryStorage:RC,fileStorage:xC,workspaceStorage:IC}),FC=jh(Mh,null),NC=jh(Oh,null),kC=Es(Lh,null),MC={activeTool:EC,api:TC,plugins:yC,storage:DC,user:FC,workspace:NC,serverConfigValues:kC},OC=MC;class AC{reducers={};listener=null;register(e,t){this.reducers={...this.reducers,[e]:t},this.listener?.(this.reducers)}setListener(e){this.listener=e}}const LC=new AC,po=LC,jd=J.module("redux-logger"),_C=c=>e=>t=>{jd.debug("dispatching",t);const n=e(t);return jd.debug("next state",c.getState()),n},PC=_C,jC=J.module("redux-crashReporter"),HC=c=>e=>t=>{try{return e(t)}catch(n){throw jC.error("Error executing",t," with state ",c.getState(),":",n),n}},UC=HC,BC=[PC,UC,Zu];Object.entries(OC).map(([c,e])=>po.register(c,e));const VC=window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__??em,Hh=Qu(tr(po.reducers),VC(Ju(...BC)));po.setListener(c=>{Hh.replaceReducer(tr(c))});const Tr=Hh,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 Bh(c){return c.componentName!==void 0}function $C(c){return c.component!==void 0}const Vh=Object.freeze({type:"default",isClosable:!0,isFocusOnShow:!0,reorderEnabled:!0,title:""}),WC=Object.freeze(Object.defineProperty({__proto__:null,defaultConfig:Uh,isGLComponentConfig:Bh,isReactComponentConfig:$C,itemDefaultConfig:Vh},Symbol.toStringTag,{value:"Module"}));class fl{static ALL_EVENT="__all";_mSubscriptions;constructor(){this._mSubscriptions={},this._mSubscriptions[fl.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[fl.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 pn=fl;class $a extends pn{width;height;title;parent;layoutManager;tab;_config;isHidden=!1;beforeCloseHandler;_element=le(['<div class="lm_item_container">','<div class="lm_content" tabindex="-1"></div>',"</div>"].join(""));_contentElement;constructor(e,t,n){super(),this.title=Bh(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(le.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 GC=Object.freeze(Object.defineProperty({__proto__:null,Container:$a,ItemContainer:$a},Symbol.toStringTag,{value:"Module"}));function $h(c){var e=location.hash.match(new RegExp(c+"=([^&]*)"));return e?e[1]:null}function Wh(c){if(window.location.hash)return $h(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 Ql(c){return window.requestAnimationFrame(c)}function zC(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 Er(){return(Math.random()*1e15).toString(36).replace(".","")}function KC(c,e){var t=c.replace(/javascript/gi,"javascript").replace(/expression/gi,"expression").replace(/onload/gi,"onload").replace(/script/gi,"script").replace(/onerror/gi,"onerror");return e===!0?t:t.replace(/>/g,">").replace(/</g,"<")}function yr(c){return le.trim(c.replace(/(<([^>]+)>)/gi,""))}class YC extends pn{_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=le(document),this._eBody=le(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 fo=YC;class Gh{_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(){ll.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(){ll.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=le.extend(e,this._container._config.props);return oe.createElement(this._reactClass,t)}}const Cl=["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"],qC=[!0,!1,"row","column","stack","component","close","maximise","minimise","open in new window"];function Rr(c){if(Cl.length>36)throw new Error("Too many keys in config minifier map");const e={};return xr(c,e,"_min"),e}function Wa(c){if(Cl.length>36)throw new Error("Too many keys in config minifier map");const e={};return xr(c,e,"_max"),e}function xr(c,e,t){const n=t==="_min"?XC:ZC;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,Cl);e[l]=o}xr(i,o,t)}else{const o=n(i,qC);if(Array.isArray(e))e[Number.parseInt(s,10)]=o;else{const l=n(s,Cl);e[l]=o}}}}function XC(c,e){if(typeof c=="string"&&c.length===1)return"___"+c;var t=e.indexOf(c);return t===-1?c:t.toString(36)}function ZC(c,e){return typeof c=="string"&&c.length===1?e[parseInt(c,36)]:typeof c=="string"&&c.substr(0,3)==="___"?c[3]:c}class Ga{name;origin;isPropagationStopped;constructor(e,t){this.name=e,this.origin=t,this.isPropagationStopped=!1}stopPropagation(){this.isPropagationStopped=!0}}let QC=class extends pn{_layoutManager;_dontPropagateToParent;_childEventSource;_boundOnEventFromChild;constructor(e){super(),this._layoutManager=e,this._dontPropagateToParent=null,this._childEventSource=null,this.on(pn.ALL_EVENT,this._onEventFromThis.bind(this)),this._boundOnEventFromChild=this._onEventFromChild.bind(this),le(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(){le(window).off("gl_child_event",this._boundOnEventFromChild)}};const zh=QC,JC=Object.freeze(Object.defineProperty({__proto__:null,BubblingEvent:Ga,DragListener:fo,EventEmitter:pn,EventHub:zh,ReactComponentHandler:Gh,animFrame:Ql,filterXss:KC,getHashValue:$h,getQueryStringParam:Wh,getUniqueId:Er,minifyConfig:Rr,removeFromArray:zC,stripTags:yr,unminifyConfig:Wa},Symbol.toStringTag,{value:"Module"}));class Kh extends pn{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=le.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;le(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-"+Er();e=Rr(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 Di extends pn{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=le(Di._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",yr(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(),le(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 Yh{_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 fo(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(le.extend(!0,{},n)),i=new Di(e,t,this._dragListener,this._layoutManager,s,null);this._layoutManager.transitionIndicator?.transitionElements(this._element,i.element)}}class qh{_element=le(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 fo(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(le.extend(!0,{},n));new Di(e,t,this._dragListener,this._layoutManager,s,null)}}}class Jl{static _template='<div class="lm_dropTargetIndicator"><div class="lm_inner"></div></div>';element=le(Jl._template);constructor(){le(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 Yi{element;_header;_action;constructor(e,t,n,s){this._header=e,this.element=le('<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 eS extends Error{node;constructor(e,t){super(),this.name="Configuration Error",this.message=e,this.node=t}}const zs=eS,tS=Object.freeze(Object.defineProperty({__proto__:null,ConfigurationError:zs},Symbol.toStringTag,{value:"Module"}));function oo(c){return c.isStack}function jt(c){return c.isComponent}function Xh(c){return c.isRoot}class ut extends pn{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(pn.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,oo(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&&jt(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 Ga(e,this);this.emit(e,t)}_createContentItems(e){var t;if(!(e.content instanceof Array))throw new zs("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(Vh)){const s=t;e[s]===void 0&&(e[s]=n)}return e}_propagateEvent(e,t){t instanceof Ga&&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,Ql(this._propagateEventToLayoutManager.bind(this,e,t)))}_propagateEventToLayoutManager(e,t){this._pendingEventPropagations[e]=!1,this.layoutManager.emit(e,t)}}class Zh extends ut{config;componentName;container;parent;instance;constructor(e,t,n){super(e,t,n,le()),this.config=t,this.parent=n;const s=e.getComponent(this.config.componentName)||e.getFallbackComponent(),i=le.extend(!0,{},this.config.componentState||{});if(s==null)throw new zs('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 $a(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(){ut.prototype._$init.call(this),this.container.emit("open")}_$hide(){this.container.hide(),ut.prototype._$hide.call(this)}_$show(){this.container.show(),this.container._config.isFocusOnShow&&this.container._contentElement[0].focus({preventScroll:!0}),ut.prototype._$show.call(this)}_$destroy(){this.container.emit("destroy",this),ut.prototype._$destroy.call(this)}_$getArea(){return null}}class Sl extends ut{isRow;isColumn;childElementContainer;parent;_splitter=[];_splitterSize;_splitterGrabSize;_isColumn;_dimension;_splitterPosition=null;_splitterMinPosition=null;_splitterMaxPosition=null;constructor(e,t,n,s){super(t,n,s,le('<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),ut.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));ut.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(ut.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 Qh(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}),Ql(this.callDownwards.bind(this,"setSize",void 0,void 0,void 0))}}class za extends ut{childElementContainer;_containerElement;constructor(e,t,n){super(e,{...t,type:"root"},null,le('<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(jt(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 Ka extends ut{_activeContentItem=null;_header;childElementContainer=le('<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,le('<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 vi(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(){ut.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(jt(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 nS=Object.freeze(Object.defineProperty({__proto__:null,AbstractContentItem:ut,Component:Zh,ContentItem:ut,Root:za,RowOrColumn:Sl,Stack:Ka,isComponent:jt,isRoot:Xh,isStack:oo},Symbol.toStringTag,{value:"Module"}));class ea{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=le(ea._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 fo(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),jt(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),jt(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 Di(e,t,this._dragListener,this._layoutManager,this.contentItem,this.header.parent)}_onTabContentFocusIn(){le(".lm_focusin",this._layoutManager.root.element).removeClass("lm_focusin"),this.element.addClass("lm_focusin")}_onTabContentFocusOut(){jt(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&&jt(this.contentItem)?this.header.parent.setActiveContentItem(this.contentItem):jt(this.contentItem)&&!this.contentItem.container._contentElement[0].contains(document.activeElement)&&this.contentItem.container._contentElement.focus(),jt(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(),jt(this.contentItem)?this.contentItem.container.close():this.header.parent.removeChild(this.contentItem)}_onCloseMousedown(e){e.stopPropagation()}}class vi extends pn{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=le(vi._template);tabsContainer;tabDropdownContainer;tabDropdownSearch;tabDropdownList=null;controlsContainer;parent;tabs=[];activeContentItem=null;closeButton=null;tabDropdownButton=null;tabNextButton=le(vi._nextButtonTemplate);tabPreviousButton=le(vi._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 ea(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(),le(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 Yi(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 Yi(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 Yi(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 Yi(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"),le(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(),le(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)-(le(window).scrollTop()??0);t+e>(le(window).height()??0)&&this.tabDropdownContainer.css("max-height",(le(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 Qh{_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 fo(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=le('<div class="lm_drag_handle"></div>'),t=le('<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 Jh{_element=le('<div class="lm_transition_indicator"></div>');_toElement=null;_fromDimensions={};_totalAnimationDuration=200;_animationStartTime=null;constructor(){le(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),Ql(this._nextAnimationFrame.bind(this))}_measure(e){const t=e.offset();return{left:t?.left,top:t?.top,width:e.outerWidth(),height:e.outerHeight()}}}const sS=Object.freeze(Object.defineProperty({__proto__:null,BrowserPopout:Kh,DragProxy:Di,DragSource:Yh,DragSourceFromEvent:qh,DropTargetIndicator:Jl,Header:vi,HeaderButton:Yi,Splitter:Qh,Tab:ea,TransitionIndicator:Jh},Symbol.toStringTag,{value:"Module"})),iS={config:WC,container:GC,controls:sS,errors:tS,items:nS,utils:JC},oS=iS;class eu extends pn{static __lm=oS;static minifyConfig(e){return Rr(e)}static unminifyConfig(e){return Wa(e)}isInitialised=!1;_isFullPage=!1;_resizeTimeoutId;_components={"lm-react-component":Gh};_fallbackComponent;_itemAreas=[];_maximisedItem=null;_maximisePlaceholder=le('<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 zh(this);config;container;_originalContainer;dropTargetIndicator=null;transitionIndicator=null;tabDropPlaceholder=le('<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&&le("body").css("visibility","hidden"),this._typeToItem={column:Sl.bind(this,!0),row:Sl.bind(this,!1),stack:Ka,component:Zh}}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 ut))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){le(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 Jl,this.transitionIndicator=new Jh,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(),le(window).off("resize",this._onResize),le(window).off("unload beforeunload",this._onUnload),le(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 zs("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 zs(n);return e.type==="component"&&!(t instanceof Ka)&&t&&!(this.isSubWindow===!0&&t instanceof za)&&(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 ut,l=this;if(o){i=this.toConfig(e).content,n=Er();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 Kh(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 Yh(e,t,this);return this._dragSources.push(n),n}createDragSourceFromEvent(e,t){return this.config.settings.constrainDragToContainer=!1,new qh(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(!oo(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 ut)return e;if(le.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&&le(window).resize(this._onResize),le(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=Wh("gl-window");t&&(this.isSubWindow=!0,e=JSON.parse(localStorage.getItem(t)||"{}"),e=Wa(e),localStorage.removeItem(t)),e=le.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=le('<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=yr(this.config.content[0].title??""),le("head").append(le("body link, body style, template, .gl_keep")),this.container=le("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?le(this._originalContainer):le("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,le("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 zs(t,e);if(e.content.length>1)throw t="Top level content can't contain more then one element.",new zs(t,e);this.root=new za(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=>{oo(n)?e.push(n):n.isComponent||this._findAllStackContainersRecursive(e,n)})}}const lS="_lm_root_15d73_3",aS="_lm_row_15d73_7",rS="_lm_item_15d73_7",dS="_lm_content_15d73_11",cS="_lm_dragging_15d73_17",hS="_lm_maximised_15d73_23",uS="_lm_maximise_placeholder_15d73_30",mS="_lm_splitter_15d73_34",gS="_lm_vertical_15d73_41",pS="_lm_drag_handle_15d73_41",fS="_lm_horizontal_15d73_46",CS="_lm_header_15d73_56",SS="_lm_dropdown_open_15d73_63",bS="_lm_controls_15d73_69",wS="_lm_tabs_15d73_89",vS="_lm_tab_15d73_89",TS="_lm_title_15d73_104",ES="_lm_close_tab_15d73_111",yS="_lm_stack_15d73_120",RS="_lm_left_15d73_120",xS="_lm_right_15d73_121",IS="_lm_dragProxy_15d73_125",DS="_lm_items_15d73_148",FS="_lm_tabdropdown_list_15d73_165",NS="_lm_bottom_15d73_192",kS="_lm_drop_tab_placeholder_15d73_207",MS="_lm_tabdropdown_15d73_165",OS="_lm_dropTargetIndicator_15d73_258",AS="_lm_inner_15d73_264",LS="_lm_transition_indicator_15d73_272",_S="_lm_popin_15d73_282",PS="_lm_bg_15d73_297",jS="_lm_icon_15d73_300",HS="_lm_goldenlayout_15d73_304",US="_lm_selectable_15d73_340",BS="_lm_active_15d73_370",VS="_lm_selected_15d73_388",$S="_lm_keyboard_active_15d73_397",WS="_lm_popout_15d73_416",GS="_lm_maximise_15d73_23",zS="_lm_close_15d73_111",KS="_lm_tabnextbutton_15d73_425",YS="_lm_tabpreviousbutton_15d73_428",qS="_lm_title_before_15d73_544",XS="_lm_focusin_15d73_568",ZS="_lm_window_blur_15d73_573",QS="_lm_tabdropdown_search_15d73_631",JS="_march_15d73_1",eb="_app_15d73_712",tb="_plotly_15d73_721",Hd={"tab-height":"28px","drag-border-width":"5px",lm_root:lS,lm_row:aS,lm_item:rS,lm_content:dS,lm_dragging:cS,lm_maximised:hS,lm_maximise_placeholder:uS,lm_splitter:mS,lm_vertical:gS,lm_drag_handle:pS,lm_horizontal:fS,lm_header:CS,lm_dropdown_open:SS,lm_controls:bS,lm_tabs:wS,lm_tab:vS,lm_title:TS,lm_close_tab:ES,lm_stack:yS,lm_left:RS,lm_right:xS,lm_dragProxy:IS,lm_items:DS,lm_tabdropdown_list:FS,lm_bottom:NS,lm_drop_tab_placeholder:kS,lm_tabdropdown:MS,lm_dropTargetIndicator:OS,lm_inner:AS,lm_transition_indicator:LS,lm_popin:_S,lm_bg:PS,lm_icon:jS,lm_goldenlayout:HS,lm_selectable:US,lm_active:BS,lm_selected:VS,lm_keyboard_active:$S,lm_popout:WS,lm_maximise:GS,lm_close:zS,lm_tabnextbutton:KS,lm_tabpreviousbutton:YS,lm_title_before:qS,"editor-unsaved-indicator":"_editor-unsaved-indicator_15d73_548","is-unsaved":"_is-unsaved_15d73_556",lm_focusin:XS,lm_window_blur:ZS,lm_tabdropdown_search:QS,march:JS,app:eb,"js-plotly-plot":"_js-plotly-plot_15d73_721",plotly:tb},Ud=Object.freeze({tabHeight:parseInt(Hd["tab-height"],10),dragBorderWidth:parseInt(Hd["drag-border-width"],10)}),ss=J.module("LayoutUtils");function tu(c){return c.componentName!==void 0}function mi(c){const e=c;return(tu(c)&&c.componentName==="lm-react-component"||c.type==="react-component")&&e.component!==void 0}function Po(c){return c.focus!==void 0}function Bd(c){return c.type==="stack"}class V{static DEFAULT_FOCUS_SELECTOR="input, select, textarea, button";static activateTab(e,t){const n=V.getStackForRoot(e,t,!1);if(!n){ss.error("Could not find stack for config",t);return}const s=V.getContentItemInStack(n,t);s&&n.setActiveContentItem(s)}static isActiveTab(e,t){const n=V.getStackForRoot(e,t,!1);if(!n)return ss.error("Could not find stack for config",t),!1;const s=V.getContentItemInStack(n,t);return n.getActiveContentItem()===s}static addStack(e,t=!0){const n=t?"column":"row";if(Xh(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&&oo(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&&ld(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=V.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&&ld(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:V.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?(Bd(n)&&delete n.activeItemIndex,V.dropLayoutMinorChange(s)):mi(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=V.cloneLayout(e),i=V.cloneLayout(t);return V.dropLayoutMinorChange(s),V.dropLayoutMinorChange(i),Ze(s,i)}return Ze(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(mi(i)){const{component:o,props:l={}}=i;n.push({...i,id:i?.id??Ge(),props:t(o,l)})}else if(i.content!==void 0){const o=V.hydrateLayoutConfig(i.content,t);Bd(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=Ge.generate()),l){e?.layoutManager.createDragSourceFromEvent(d,l);return}const h=s||{id:d.id,component:d.component};D(e);const u=i?V.addStack(e):V.getStackForRoot(e,h);D(u);const m=V.getContentItemInStack(u,h);if(o!=null){const g=p=>{ss.debug("Component created, focusing element",o),u.off("componentCreated",g);const{element:f}=p.origin;requestAnimationFrame(()=>{V.focusElement(f[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&&Po(a)&&a.focus()}static openComponentInStack(e,t,n=!0){const s=document.activeElement,i={id:t.id},o=V.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&&Po(s)&&s.focus()}static closeComponent(e,t,n){const s=V.getStackForRoot(e,t,!1,!1,!1);if(!s){ss.warn("Cannot find stack for component, ignoring close",t);return}const i=V.getContentItemInStack(s,t),o=document.activeElement;i&&(jt(i)?i.container.close(n):s.removeChild(i)),o&&document.contains(o)&&Po(o)&&o.focus()}static renameComponent(e,t,n){const s=V.getStackForRoot(e,t,!1);if(!s){ss.error("Could not find stack for config",t);return}const i=V.getContentItemInStack(s,t);i&&i.setTitle(n)}static cloneComponent(e,t){const n=V.getStackForRoot(e,t,!1);if(!n)return ss.error("Could not find stack for config",t),null;const{props:s={}}=t,i=V.getPanelComponentState(t),o={type:"react-component",component:t.component,props:{...s,panelState:i},title:`${t.title} Copy`,id:Ge.generate()};return V.openComponentInStack(n,o),o}static getPanelComponentState(e){return tu(e)?e.componentState?.panelState:mi(e)?e.props?.panelState:null}static makeDefaultLayout(){return{dimensions:{headerHeight:Ud.tabHeight,borderWidth:Ud.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=V.getComponentConfigFromContainer(e);return t?t.id:null}static getIdFromPanel(e){const{glContainer:t}=e.props;return V.getIdFromContainer(t)}static getComponentNameFromPanel(e){const{glContainer:t}=e.props,n=V.getComponentConfigFromContainer(t);return n&&mi(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=V.DEFAULT_FOCUS_SELECTOR){if(e==null)return null;const n=e.querySelector(t);return n==null?null:(Po(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 nu=oe.forwardRef((c,e)=>{const t=V.getComponentNameFromPanel({props:c});return r.jsxs("div",{ref:e,className:"panel-placeholder",children:['Component "',t,'" is not registered.']})});nu.displayName="PanelPlaceholder";const Se=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 Vd(c){return c?.WrappedComponent!==void 0}function nb(c){return typeof c.id=="string"&&c.layout instanceof eu&&c.panelManager instanceof su&&typeof c.registerComponent=="function"}function ys(c){if(!nb(c))throw new Error(`Expected dashboard plugin props, but instead received ${c}`)}const qt=J.module("PanelManager");class su{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(Se.FOCUS,this.handleFocus),e.on(Se.MOUNT,this.handleMount),e.on(Se.UNMOUNT,this.handleUnmount),e.on(Se.REOPEN,this.handleReopen),e.on(Se.DELETE,this.handleDeleted),e.on(Se.CLOSED,this.handleClosed),e.on(Se.CLOSE,this.handleControlClose)}stopListening(){const{eventHub:e}=this.layout;e.off(Se.FOCUS,this.handleFocus),e.off(Se.MOUNT,this.handleMount),e.off(Se.UNMOUNT,this.handleUnmount),e.off(Se.REOPEN,this.handleReopen),e.off(Se.DELETE,this.handleDeleted),e.off(Se.CLOSED,this.handleClosed),e.off(Se.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 V.getComponentConfigFromContainer(t)})}getOpenedPanelConfigsOfType(e){return this.getOpenedPanelConfigs().filter(t=>t!=null&&mi(t)&&t.component===e)}getOpenedPanelById(e){return this.openedMap.get(e)}getContainerByPanelId(e){const t=V.getStackForConfig(this.layout.root,{id:e});return(t&&V.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=>Vd(n)&&t instanceof n.WrappedComponent||!Vd(n)&&t instanceof n))}updatePanel(e){const t=V.getIdFromPanel(e);if(t==null){qt.error("updatePanel Panel did not have an ID",e);return}qt.debug2(`Updating panel ID ${t} in open panels map`),this.openedMap.delete(t),this.openedMap.set(t,e)}removePanel(e){const t=V.getIdFromPanel(e);if(t==null){qt.error("removePanel Panel did not have an ID",e);return}if(!this.openedMap.has(t)){qt.error(`Missing panel ID ${t} in open panels map`);return}if(this.openedMap.get(t)!==e){qt.debug(`Panel argument doesn't match the open panels map entry for ${t}, removePanel ignored`);return}qt.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){qt.debug2("Focus: ",e),this.updatePanel(e)}handleMount(e){qt.debug2("Mount: ",e),this.updatePanel(e),this.sendUpdate()}handleUnmount(e){qt.debug2("Unmount: ",e),this.removePanel(e),this.sendUpdate()}handleReopen(e,t){qt.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;V.openComponent({root:o,config:i,replaceConfig:t})}handleDeleted(e){qt.debug2("Deleted:",e),this.removeClosedPanelConfig(e),this.sendUpdate()}handleClosed(e,t){qt.debug2("Closed: ",e),this.addClosedPanel(t),this.sendUpdate()}handleControlClose(e){const t={id:e},{root:n}=this.layout;V.closeComponent(n,t)}addClosedPanel(e){const t=V.getComponentConfigFromContainer(e);if(t&&mi(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 sb=J.module("PanelErrorBoundary");class ib 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=V.getIdFromContainer(e);sb.debug("componentWillUnmount",n),t.emit(Se.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(Bl,{errorMessage:`${t}`,isLoading:!1,isLoaded:!1})}):e}}function Ir(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 Dr(c,e=""){return{metadata:{},...c,localDashboardId:e}}const Ya={dehydrate:Ir,hydrate:Dr},ob=U.shape({on:U.func,off:U.func,isHidden:U.bool,tab:U.shape({header:U.shape({tabs:U.arrayOf(U.shape({contentItem:U.shape({})}))})}),title:U.string,setTitle:U.func,close:U.func}),iu=U.shape({on:U.func,off:U.func,emit:U.func}),lb=U.shape({registerComponent:U.func,root:U.shape({addChild:U.func}),on:U.func,off:U.func,eventHub:iu}),Fr=Object.freeze({Container:ob,EventHub:iu,Layout:lb}),_e=(c,e,t)=>v.useEffect(function(){return c.on(e,t),()=>{c.off(e,t)}},[c,e,t]),ou="SET_DASHBOARD_DATA",ab=vC(ou,{},!1),rb={dashboardData:ab},db=new Map,cb=Object.freeze({}),hb=Object.freeze([]),ub=c=>c.dashboardData,At=(c,e)=>ub(c)[e]??cb,mb=(c,e)=>At(c,e).closed??hb,lu=(c,e)=>At(c,e).openedMap??db,au=(c,e)=>({type:ou,id:c,payload:e}),kn=(c,e)=>(t,n)=>t(au(c,{...At(n(),c),...e}));Object.entries(rb).map(([c,e])=>po.register(c,e));const jo=J.module("DashboardLayout"),gb=Object.freeze({}),pb=[],$d=()=>{},Wd=c=>c;function ru({id:c,children:e,emptyDashboard:t=r.jsx("div",{children:"Dashboard is empty."}),layout:n,layoutConfig:s=pb,onLayoutChange:i=$d,onLayoutInitialized:o=$d,hydrate:l=Dr,dehydrate:a=Ir}){const d=vs(),h=nr(),u=tm(L=>At(L,c))??gb,[m,g]=v.useState(!1),[p,f]=v.useState(!1),[C,S]=v.useState(),[b]=v.useState(u?.closed??[]),[w,T]=v.useState(!1),E=v.useMemo(()=>new Map,[]),y=v.useMemo(()=>new Map,[]),R=nm(),I=v.useCallback((L,G,ee=l,W=a)=>{jo.debug2("registerComponent",L,G,ee,W);function j(se,ae){const q=G,{dh:ne,glContainer:he,glEventHub:Te}=se;return r.jsx(og.Provider,{value:ne??d,children:r.jsx(jc,{store:R,children:r.jsx(ib,{glContainer:he,glEventHub:Te,children:r.jsx(q,{...se,ref:ae})})})})}const B=oe.forwardRef(j),Z=n.registerComponent(L,B);return E.set(L,ee),y.set(L,W),Z},[d,l,a,E,y,n,R]),x=v.useCallback((L,G)=>(E.get(L)??Wd)(G,c),[E,c]),A=v.useCallback((L,G)=>(y.get(L)??Wd)(G,c),[y,c]),k=v.useMemo(()=>new su(n,x,A,new Map,b,({closed:L,openedMap:G})=>{h(kn(c,{closed:L,openedMap:G}))}),[A,h,x,c,b,n]),_=v.useCallback(()=>{if(p)return;w||(o(),T(!0));const G=n.toConfig().content,ee=V.dehydrateLayoutConfig(G,A),W=C==null||!V.isEqual(C,ee);jo.debug("handleLayoutStateChanged",W,G,ee),W&&(g(n.root.contentItems.length===0),S(ee),i(ee))},[A,w,p,C,n,i,o]),M=v.useCallback(L=>{const G=V.getIdFromContainer(L);n.eventHub.emit(Se.DRAGGING,G),f(!0)},[n.eventHub]),$=v.useCallback(L=>{const G=V.getIdFromContainer(L);n.eventHub.emit(Se.DROPPED,G),f(!1)},[n.eventHub]),H=v.useCallback(L=>{if(jo.debug2("handleComponentCreated",L),L==null||L.config==null||L.config.component==null||L.element==null)return;const ee=`${L.config.component.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}-component`;L.element.addClass(ee)},[]);_e(n,"stateChanged",_),_e(n,"itemPickedUp",M),_e(n,"itemDropped",$),_e(n,"componentCreated",H),_e(n.eventHub,Se.TITLE_CHANGED,_);const K=ir(s);return v.useEffect(function(){if(K!==s&&s!==C){jo.debug("Setting new layout content...");const G=V.hydrateLayoutConfig(s,x);for(;n.root.contentItems.length>0;)n.root.contentItems[0].remove();for(let ee=0;ee<G.length;ee+=1)n.root.addChild(G[ee]);g(n.root.contentItems.length===0)}},[x,n,s,C,k,K]),r.jsxs(r.Fragment,{children:[m&&t,oe.Children.map(e,L=>L!=null?oe.cloneElement(L,{id:c,layout:n,panelManager:k,registerComponent:I}):null)]})}ru.propTypes={id:U.string.isRequired,children:U.node,data:U.shape({}),emptyDashboard:U.node,layout:Fr.Layout.isRequired,layoutConfig:U.arrayOf(U.shape({})),onLayoutChange:U.func,onLayoutInitialized:U.func};const fb=100,ba=()=>{},Cb=Object.freeze({});function Sb({id:c="default",children:e,emptyDashboard:t,layoutConfig:n,layoutSettings:s=Cb,onLayoutConfigChange:i=ba,onGoldenLayoutChange:o=ba,onLayoutInitialized:l=ba,fallbackComponent:a=nu,hydrate:d,dehydrate:h}){const u=v.useRef(null),[m,g]=v.useState(!1),[p,f]=v.useState();v.useEffect(function(){if(!u.current){f(void 0);return}const b={...V.makeDefaultLayout()};b.settings===void 0&&(b.settings={}),Object.assign(b.settings,s),b.content=[];const w=new eu(b,u.current),T=()=>{w.off("initialised",T),g(!0)};return w.on("initialised",T),a!=null&&w.setFallbackComponent(a),w.init(),f(w),o(w),()=>{w.destroy()}},[s,a,o,g,f]);const C=v.useMemo(()=>bs(()=>{p!=null&&p.isInitialised&&p?.updateSize()},fb),[p]);return v.useEffect(function(){return window.addEventListener("resize",C),()=>{window.removeEventListener("resize",C)}},[C]),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(ru,{emptyDashboard:t,id:c,layout:p,layoutConfig:n,onLayoutChange:i,onLayoutInitialized:l,hydrate:d,dehydrate:h,children:e})]})}const un="default";class bb extends Error{isAssertionFailed=!0}const du=bb;function Gd(c){if(c==null)throw new du(`Expected 'val' to be defined, but received ${c}`)}class wb extends Error{isPasteError=!0}const wa=wb;function ze(c){return c?.isEditable!==void 0}function zd(c){if(!ze(c))throw new du(`Expected 'model' to be editable, but received ${c}`)}function Pe(c){return c?.hasExpandableRows!==void 0}var mn=(c=>(c.DOWN="DOWN",c.UP="UP",c.LEFT="LEFT",c.RIGHT="RIGHT",c))(mn||{});class Q{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 Q(...Q.normalize(e,t,n,s))}static makeCell(e,t){return new Q(e,t,e,t)}static makeColumn(e){return new Q(e,null,e,null)}static makeRow(e){return new Q(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=Q.minOrNull(i.startColumn,l.startColumn),u=Q.maxOrNull(i.endColumn,l.endColumn);n=!0,t[s]=new Q(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=Q.minOrNull(i.startRow,l.startRow),u=Q.maxOrNull(i.endRow,l.endRow);n=!0,t[s]=new Q(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 Q(n,s,i,o)}static subtractFromRange(e,t){const n=[],s=Q.intersection(e,t);return s==null?[e]:(s.startRow!=null&&(e.startRow==null||e.startRow<s.startRow)&&n.push(new Q(e.startColumn,e.startRow,e.endColumn,s.startRow-1)),s.startColumn!=null&&(e.startColumn==null||e.startColumn<s.startColumn)&&n.push(new Q(e.startColumn,s.startRow,s.startColumn-1,s.endRow)),s.endColumn!=null&&(e.endColumn==null||e.endColumn>s.endColumn)&&n.push(new Q(s.endColumn+1,s.startRow,e.endColumn,s.endRow)),s.endRow!=null&&(e.endRow==null||e.endRow>s.endRow)&&n.push(new Q(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(...Q.subtractFromRange(e[s],t));return n}static subtractRangesFromRanges(e,t){let n=[...e];for(let s=0;s<t.length;s+=1)n=Q.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 Q.isBounded(e)?e:new Q(e.startColumn??0,e.startRow??0,e.endColumn??t-1,e.endRow??n-1)}static boundedRanges(e,t,n){return e.map(s=>Q.boundedRange(s,t,n))}static offset(e,t,n){return new Q(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=Q.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 Q.SELECTION_DIRECTION.DOWN:case Q.SELECTION_DIRECTION.RIGHT:{const o=i<e.length-1?i+1:0;return e[o].startCell(s)}case Q.SELECTION_DIRECTION.LEFT:case Q.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=Q.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 Q.isAxisRangeTouching(this.startRow,this.endRow,e.startRow,e.endRow)&&Q.isAxisRangeTouching(this.startColumn,this.endColumn,e.startColumn,e.endColumn)}subtract(e){return Q.subtractFromRange(this,e)}startCell(e=Q.SELECTION_DIRECTION.DOWN){if(!Q.isBounded(this))throw new Error("Cannot get the startCell of an unbounded range");switch(e){case Q.SELECTION_DIRECTION.DOWN:case Q.SELECTION_DIRECTION.RIGHT:return{column:this.startColumn,row:this.startRow};case Q.SELECTION_DIRECTION.LEFT:case Q.SELECTION_DIRECTION.UP:return{column:this.endColumn,row:this.endRow};default:throw new Error(`Invalid direction: ${e}`)}}nextCell(e,t,n){if(!Q.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 Q.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 Q.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 Q.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 Q.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=Q.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 Re=Q;function vb(c){return Array.isArray(c)&&c.length===2&&(c[0]===null||typeof c[0]=="number")&&(c[1]===null||typeof c[1]=="number")}function Ho(c){return vb(c)&&c[0]!=null&&c[1]!=null}function bl(c){return c?.href!==void 0}class O{static PIXELS_PER_LINE=100/3;static getGridPointFromXY(e,t,n){const s=O.getColumnAtX(e,n),i=O.getRowAtY(t,n),o=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}=O.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,f=s!==null?d.get(s):null,C=i!==null?o.get(i):null,S=s!==null?l.get(s):null;return{row:s,column:i,modelRow:m??null,modelColumn:g??null,left:p??null,top:f??null,columnWidth:C??null,rowHeight:S??null}}static getColumnHeaderDepthAtY(e,t){const n=O.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=O.iterateFloatingStart(e,n,s);return i!==void 0?i:O.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=O.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:O.iterateFloating(n,s,t,h=>{if(O.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(O.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 O.getNextShownItem(e,n,s,i)}static getNextShownRow(e,t){const{modelRows:n,visibleRows:s,userRowHeights:i}=t;return O.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 f=e-i,C=p*.5;let S=!1;for(let b=l.length-1;b>=0;b-=1){const w=l[b],T=h.get(w)??0,E=u.get(w)??0,y=E===0;if(!S||!y){let R=T+E;y?R+=C:S&&(R-=C);const I=R-C,x=R+C;if(I<=f&&f<=x)return w;S=y}}S=!1;for(let b=d.length-1;b>=0;b-=1){const w=d[b],T=h.get(w)??0,E=u.get(w)??0,y=E===0;if(T<a-E)return null;if(!S||!y){let R=T+E;y?R+=C:S&&(R-=C);const I=R-C,x=R+C;if(I<=f&&f<=x)return w;S=y}}return null}static isItemHidden(e,t){return t.get(e)===0}static isColumnHidden(e,t){const{allColumnWidths:n}=t;return O.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(!O.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(!O.isItemHidden(l,t))break;s.push(l)}return s}static getHiddenColumns(e,t){const{visibleColumns:n,allColumnWidths:s}=t;return O.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 f=l.length-1;f>=0;f-=1){const C=l[f],S=a.get(C)??0,b=d.get(C)??0,w=b===0;if(!p||!w){let T=S+b;w?T+=g:p&&(T-=g);const E=T-g,y=T+g;if(E<=m&&m<=y)return C;p=w}}return null}static isRowHidden(e,t){const{allRowHeights:n}=t;return O.isItemHidden(e,n)}static getHiddenRows(e,t){const{visibleRows:n,allRowHeights:s}=t;return O.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&&!Ho(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 O.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&&Ho(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 Ho(a.from)&&a.from[0]===a.to&&o.pop(),o}static moveItemOrRange(e,t,n,s=!1){return Array.isArray(e)?O.moveRange(e,t,n,s):O.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;Ho(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,f=[];for(let C=0;C<i.length;C+=1){const S=i[C][0]??Number.NEGATIVE_INFINITY,b=i[C][1]??Number.POSITIVE_INFINITY;let w;const T=[[S,u-1],[u,m],[m+1,b]].map(([E,y])=>[Math.max(E,S),Math.min(y,b)]).filter(([E,y])=>E<=y).map(E=>{const[y,R]=E;return u<=y&&m>=R?(w=[y+p,R+p],w):m<y?[y-d,R-d]:E}).map(E=>{const[y,R]=E;return g>y&&g<=R?[[y,g-1],[g+d,R+d]]:E===w?[E]:g<=y?[[y+d,R+d]]:[E]}).flat();f.push(...T)}i=f.map(([C,S])=>[Number.isFinite(C)?C:null,Number.isFinite(S)?S:null])}return i}static translateRange(e,t,n,s){const i=O.applyItemMoves(e.startColumn,e.endColumn,t,s),o=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 Re(d[0],u[0],d[1],u[1]))}}return l}static getModelIndex(e,t){return O.applyItemMoves(e,e,t,!0)[0][0]}static getModelIndexes(e,t){return e.map(n=>O.getModelIndex(n,t))}static getModelRangeIndexes(e,t,n){return O.applyItemMoves(e,t,n,!0)}static getModelRange(e,t=Ie,n=Ie){return O.translateRange(e,t,n,!0)}static getModelRanges(e,t=Ie,n=Ie){const s=[];for(let i=0;i<e.length;i+=1)s.push(...O.getModelRange(e[i],t,n));return s}static getVisibleRangeIndexes(e,t,n){return O.applyItemMoves(e,t,n,!1)}static getVisibleRange(e,t=Ie,n=Ie){return this.translateRange(e,t,n,!1)}static getVisibleRanges(e,t=Ie,n=Ie){const s=[];for(let i=0;i<e.length;i+=1)s.push(...O.getVisibleRange(e[i],t,n));return s}static getVisibleIndex(e,t){return O.applyItemMoves(e,e,t)[0][0]}static getVisibleIndexes(e,t){return e.map(n=>O.getVisibleIndex(n,t))}static isMacPlatform(){const{platform:e}=window.navigator;return e.startsWith("Mac")}static getModifierKey(){return O.isMacPlatform()?"metaKey":"ctrlKey"}static isModifierKeyDown(e){const t=O.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:f,columnCount:C,rowCount:S}=e;let b=s,w=i,T=o,E=l;return n!=null&&(n>h&&(b+=m),n<C-u&&(T-=g)),t!=null&&(t>a&&(w+=p),t<S-d&&(E-=f)),{x1:b,y1:w,x2:T,y2:E}}static getScrollDelta(e,t=1024,n=768,s=20,i=20){let{deltaX:o,deltaY:l}=e;return!O.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&&(O.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),f=Oe(a+s,a,h-m),C=Oe(a+o,a,h-m);return{x1:g,y1:f,x2:p,y2:C,token:e.token}}static findTokensWithProtocolInText(e){return _c(e).filter(n=>n.type==="url"?/^https?:\/\//.test(n.value):!0)}}function Uo(c,e=Co.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 Kd(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+=N(s,l);o=n;for(let l=0;l<e&&t-l-1>=0;l+=1)o-=N(s,t-l-1),i.set(t-l-1,o);return i}class Co{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:f,columnWidth:C,columnHeaderHeight:S,minScrollHandleSize:b,scrollBarSize:w}=a;h!==this.movedRows&&(this.movedRows=h,this.modelRows.clear()),u!==this.movedColumns&&(this.movedColumns=u,this.modelColumns.clear());const{columnCount:T,rowCount:E,floatingTopRowCount:y,floatingBottomRowCount:R,floatingLeftColumnCount:I,floatingRightColumnCount:x,columnHeaderMaxDepth:A}=d,k=this.getFirstRow(e),_=this.getFirstColumn(e),M=this.getGridX(e),$=this.getGridY(e),H=Pe(d)&&d.hasExpandableRows?this.calculateTreePaddingX(e):0,K=0,L=this.getVisibleRowHeights(e),G=this.getVisibleColumnWidths(e,_,H),ee=Array.from(L.keys()),W=Array.from(G.keys()),j=new Map([...L,...this.getFloatingRowHeights(e)]),B=new Map([...G,...this.getFloatingColumnWidths(e)]),Z=this.getVisibleColumnXs(B,W,s),se=this.getVisibleRowYs(j,ee,i),ae=ee.length>0?ee[ee.length-1]:n,q=W.length>0?W[W.length-1]:t,ne=this.getBottomViewport(e,ee,se,j),he=this.getRightViewport(e,W,Z,B),Te=this.getFloatingTopHeight(e,j),ye=this.getFloatingBottomHeight(e,j),rt=this.getFloatingLeftWidth(e,B),wt=this.getFloatingRightWidth(e,B),Wt=Array.from(B.values()),fn=Array.from(j.values()),xt=Wt.reduce((Ne,Kt)=>Ne+Kt,0)-s,Ee=fn.reduce((Ne,Kt)=>Ne+Kt,0)-i,lt=s+xt+f,et=i+Ee,pt=o-M,It=l-$,Cn=this.getLastLeft(e,null,pt-f),Gt=this.getLastLeft(e,null,pt-f-w),So=this.getLastTop(e,null,It-ye),Rs=this.getLastTop(e,null,It-ye-w);let zt=Gt,Zn=Rs;Cn===0&&So===0&&(zt=0,Zn=0);const ei=zt>0,Ni=ei?w:0,ti=Zn>0,ni=ti?w:0,bo=M,wo=A*S,Qn=o-bo-ni,xs=l-wo-Ni,oa=T===1?Qn/lt:(T-zt)/T,vo=E===1?xs/et:(E-Zn)/E,ki=ei?Oe(Qn*oa,b,Qn-1):0,Mi=ti?Oe(xs*vo,b,xs-1):0,Oi=N(B,t,0),To=N(j,n,0),la=Oi>0?s/Oi:0,aa=To>0?i/To:0,ra=T===1?s/(lt-pt):(t+la)/zt,da=E===1?i/(et-It):(n+aa)/Zn,ca=ei?ra*(Qn-ki):0,Is=ti?da*(xs-Mi):0,Eo=[...Array(y).keys(),...[...Array(R).keys()].map(Ne=>E-Ne-1)],si=new Map([...se,...this.getFloatingRowYs(e,j,Math.floor(l-$-Ni))]),yo=[...Array(I).keys(),...[...Array(x).keys()].map(Ne=>T-Ne-1)],Ds=new Map([...Z,...this.getFloatingColumnXs(e,B,Math.floor(o-M-ni))]),Ro=[];if(m)for(let Ne=m.range[0];Ne<=m.range[1];Ne+=1)Ro.push(Ne),B.has(Ne)||B.set(Ne,this.getVisibleColumnWidth(Ne,e)),Ds.has(Ne)||Ds.set(Ne,0);const Ai=ee.concat(Eo),Li=W.concat(yo).concat(Ro),xo=this.getModelRows(Ai,e),Io=this.getModelColumns(Li,e),Do=this.getVisibleRowTreeBoxes(j,xo,e),ha=this.getTopVisible(e,si,j,ee),Fo=this.getLeftVisible(e,Ds,B,W),No=Zn>0?this.getBottomVisible(e,si,j,ee,$):ae,ko=zt>0?this.getRightVisible(e,Ds,B,W,M):q,{fontWidths:Mo,userColumnWidths:Oo,userRowHeights:Ao,calculatedRowHeights:ua,calculatedColumnWidths:Ue}=this;return{rowHeight:g,rowHeaderWidth:p,rowFooterWidth:f,rowCount:E,columnWidth:C,columnCount:T,columnHeaderHeight:S,floatingTopRowCount:y,floatingBottomRowCount:R,floatingLeftColumnCount:I,floatingRightColumnCount:x,gridX:M,gridY:$,firstRow:k,firstColumn:_,treePaddingX:H,treePaddingY:K,left:t,top:n,bottom:ae,right:q,topOffset:i,leftOffset:s,topVisible:ha,leftVisible:Fo,bottomVisible:No,rightVisible:ko,bottomViewport:ne,rightViewport:he,width:o,height:l,maxX:xt,maxY:Ee,lastLeft:zt,lastTop:Zn,barHeight:xs,barTop:wo,barWidth:Qn,barLeft:bo,handleHeight:Mi,handleWidth:ki,hasHorizontalBar:ei,hasVerticalBar:ti,verticalBarWidth:ni,horizontalBarHeight:Ni,scrollX:ca,scrollY:Is,scrollableContentWidth:lt,scrollableContentHeight:et,scrollableViewportWidth:pt,scrollableViewportHeight:It,visibleRows:ee,visibleColumns:W,visibleRowHeights:L,visibleColumnWidths:G,floatingRows:Eo,floatingColumns:yo,allRows:Ai,allColumns:Li,allRowHeights:j,allColumnWidths:B,floatingTopHeight:Te,floatingBottomHeight:ye,floatingLeftWidth:rt,floatingRightWidth:wt,visibleRowYs:se,visibleColumnXs:Z,allRowYs:si,allColumnXs:Ds,visibleRowTreeBoxes:Do,modelRows:xo,modelColumns:Io,movedRows:h,movedColumns:u,fontWidths:Mo,userColumnWidths:Oo,userRowHeights:Ao,calculatedRowHeights:ua,calculatedColumnWidths:Ue,columnHeaderMaxDepth:A}}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 Kd(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=N(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 Kd(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=N(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 Pe(i)&&i.hasExpandableRows&&e.forEach((d,h)=>{const u=N(t,h);if(i.isRowExpandable(u)){const m=i.depthForRow(u),g=m*l+a,p=(m+1)*l+a,f=0,C=d;s.set(h,{x1:g,y1:f,x2:p,y2:C})}}),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+=N(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+=N(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+=N(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+=N(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(N(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(N(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=N(t,m),p=N(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=N(t,m),p=N(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=N(t,o)+N(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 N(this.modelRows,e);const{movedRows:n}=t,s=O.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 N(this.modelColumns,e);const{movedColumns:s}=t,i=O.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:f,scrollBarSize:C}=l;let S=0;const b=this.getWidthForFont(u,t),w=s/g,T=Math.ceil(n+w);return O.iterateAllItems(n,T,a,d,h,E=>{const y=this.getModelRow(E,t),R=o.textForCell(e,y);if(R){const I=m*2;S=Math.max(S,R.length*b+I)}}),S=Math.max(Math.min(S,(i-p-C-f)*Co.MAX_COLUMN_WIDTH),m*2),S}calculateTreePaddingX(e){const{top:t,height:n,model:s,theme:i}=e,{rowHeight:o,treeDepthIndent:l}=i;if(!Pe(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 N(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 Tb=Co,Eb=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"}),yb=Eb,Rb=(c,e)=>{let t=!1;const n=we(c,{...e,dispose:()=>{t||(t=!0,n.clear(),t=!1)}});return n},Bn=Rb;function xb(c,e,t=6){const n=Pa.hex.lab.raw(c);return n[0]=Math.max(n[0]-n[0]/t*e,0),`#${Pa.lab.hex(n)}`}function Ib(c,e){const[t,n,s]=Pa.hex.rgb(c);return`rgba(${t}, ${n}, ${s}, ${e})`}const Yd={colorWithAlpha:Ib,darkenForDepth:xb};class ot{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 Db extends ot{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 f=N(l,p),C=n-a-f-this.dragOffset,S=N(h,p),b=this.targetSizes.get(S),w=this.resizingItems.length>1,T=this.hiddenItems.indexOf(p);let E=N(d,S);p===u&&(E+=m);let y=C;Math.abs(C-E)<=o.headerResizeSnapThreshold?y=E:b!==void 0&&C>b&&(w&&T!==0||T>0)?y=b:C<=o.headerResizeHiddenSnapThreshold&&(y=0),g.set(S,y),C<-o.headerResizeSnapThreshold&&y===0?T>=0&&w?(this.resizingItems.pop(),this.removeTargetSize(i,p),p=this.resizingItems[this.resizingItems.length-1],this.dragOffset-=this.targetSizes.get(N(h,p))??0):(p=this.getNextShownItem(p,i),p!==null&&(this.resizingItems.push(p),this.addTargetSize(i,p))):b!==void 0&&C>b+o.headerResizeSnapThreshold&&y===b?T>0?(this.dragOffset+=y,p=this.hiddenItems[T-1],this.resizingItems.push(p),this.addTargetSize(i,p)):w?(this.resizingItems.pop(),this.removeTargetSize(i,p),p=this.resizingItems[this.resizingItems.length-1]):p=null:p=null}return g.forEach((f,C)=>{const S=s[this.initialSizesProperty].get(C)??d.get(C);f===S?this.resetSize(s,C):this.setSize(s,C,f)}),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=N(a,l.index),h=N(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];N(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=N(n,t);let a=s.get(l);(a==null||a===0)&&(a=N(i,l)+o),this.targetSizes.set(l,a)}removeTargetSize(e,t){const n=e[this.modelIndexesProperty],s=N(n,t);this.targetSizes.delete(s)}}const cu=Db;class Nr extends cu{static getColumnSeparator(e,t,n,s){if(!s.allowColumnResize)return null;const{x:i,y:o,columnHeaderDepth:l}=e,{modelColumns:a}=t,d=O.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=O.getHiddenColumns;getNextShownItem=O.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=Nr.getColumnSeparator}const hu=Nr;class Nt{static DEFAULT_FONT_WIDTH=10;static DEFAULT_EDGE_RADIUS=2;static ACTIVE_CELL_BORDER_WIDTH=2;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=Nt.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=Nt.DEFAULT_FONT_WIDTH,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 Nt.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:N(m,l-1)+N(g,l-1)-.5}),a>0&&this.drawSelectedRanges(e,t,{top:h-a-1,bottom:h-1,minY:N(m,h-a)+.5,maxY:N(m,h-1)+N(g,h-1)-.5});for(let p=0;p<u.length;p+=1){const f=u[p];for(let C=0;C<d.length;C+=1){const S=d[C];this.drawCellContent(e,t,f,S)}}}}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:f,allColumnXs:C,allColumnWidths:S,width:b,height:w}=i;if(u.length!==0){o.floatingRowBackgroundColors&&(this.drawRowStripesForRows(e,t,f,o.floatingRowBackgroundColors,0,d),this.drawRowStripesForRows(e,t,f,o.floatingRowBackgroundColors,b-m-h,g)),n==null&&s==null&&this.drawFloatingMouseRowHover(e,t),e.save(),e.beginPath(),e.rect(0,0,d,w),e.clip(),this.drawGridLinesForItems(e,t,u,f,o.floatingGridColumnColor,o.floatingGridRowColor),e.restore(),this.drawCellBackgroundsForItems(e,t,u,f),this.drawFloatingBorders(e,t),l>0&&this.drawSelectedRanges(e,t,{left:0,maxX:N(C,l-1)+N(S,l-1)}),a>0&&this.drawSelectedRanges(e,t,{left:p-a,right:p-1,minX:N(C,p-a)+.5,maxX:N(C,p-1)+N(S,p-1)});for(let T=0;T<u.length;T+=1){const E=u[T];for(let y=0;y<f.length;y+=1){const R=f[y];this.drawCellContent(e,t,E,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:f,maxY:C}=n,{floatingDividerOuterColor:S,floatingDividerInnerColor:b}=s;if(e.lineWidth=3,e.beginPath(),e.strokeStyle=S,i>0){const w=N(u,i-1)+N(g,i-1)+.5;e.moveTo(0,w),e.lineTo(f,w)}if(o>0){const w=N(u,d-o)-.5;e.moveTo(0,w),e.lineTo(f,w)}if(l>0){const w=N(m,l-1)+N(p,l-1)+.5;e.moveTo(w,0),e.lineTo(w,C)}if(a>0){const w=N(m,h-a)-.5;e.moveTo(w,0),e.lineTo(w,C)}if(e.stroke(),e.beginPath(),e.lineWidth=1,e.strokeStyle=b,i>0){const w=N(u,i-1)+N(g,i-1)+.5;e.moveTo(0,w),e.lineTo(f,w)}if(o>0){const w=N(u,d-o)-.5;e.moveTo(0,w),e.lineTo(f,w)}if(l>0){const w=N(m,l-1)+N(p,l-1)+.5;e.moveTo(w,0),e.lineTo(w,C)}if(a>0){const w=N(m,h-a)-.5;e.moveTo(w,0),e.lineTo(w,C)}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:f,allColumnWidths:C,width:S,height:b}=s;this.drawSelectedRanges(e,t,{bottom:Math.min(i,m-l-1),right:Math.min(o,u-d-1),minX:a>0&&f.has(a+1)?N(f,a+1):-10,minY:h>0&&p.has(h+1)?N(p,h+1):-10,maxX:d>0&&f.has(u-d-1)?N(f,u-d-1)+N(C,u-d-1)-.5:S+10,maxY:l>0&&p.has(m-l-1)?N(p,m-l-1)+N(g,m-l-1)-.5:b+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:f}=a,C=new Map,S=[],b=[],w=(T,E)=>{const y=Pe(d)?d.depthForRow(T):0,R=g[T%g.length],I=R[Math.min(y,R.length-1)];if(C.has(I)||C.set(I,[]),C.get(I).push(T),E!=null){const x=Pe(d)?d.depthForRow(E):0;x<y?S.push(T):x>y&&b.push(E)}};for(let T=0;T<n.length;T+=1){const E=n[T],y=T>0?n[T-1]:void 0;w(E,y)}if(C.forEach((T,E)=>{e.fillStyle=E,e.beginPath();for(let y=0;y<T.length;y+=1){const R=T[y],I=N(p,R),x=N(f,R);e.rect(i,I,o,x)}e.fill()}),S.length>0){e.save();const T=this.getCachedColorWithAlpha(m,.15),E=this.getCachedColorWithAlpha(m,0),y=e.createLinearGradient(0,0,0,u);y.addColorStop(0,T),y.addColorStop(1,E),e.fillStyle=y;for(let R=0;R<S.length;R+=1){const I=S[R],x=N(p,I);e.translate(0,x),e.fillRect(i,0,o,u),e.translate(0,-x)}e.restore()}if(b.length>0){e.save();const T=this.getCachedColorWithAlpha(m,0),E=this.getCachedColorWithAlpha(m,.15),y=e.createLinearGradient(0,0,0,u);y.addColorStop(0,T),y.addColorStop(1,E),e.fillStyle=y;for(let R=0;R<b.length;R+=1){const I=b[R],x=N(p,I),A=N(f,I),k=x+A-u;e.translate(0,k),e.fillRect(i,0,o,u),e.translate(0,-k)}e.restore()}}drawMouseColumnHover(e,t){const{mouseX:n,mouseY:s,theme:i,metrics:o}=t;if(n==null||s==null)return;const l=O.getColumnAtX(n,o);if(l==null||i.columnHoverBackgroundColor==null)return;const{allColumnWidths:a,allColumnXs:d,maxY:h}=o;if(s>h)return;const u=N(d,l),m=N(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=O.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=O.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=N(a,n),u=N(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=N(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=N(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:f}=o,C=N(u,s),S=N(h,n),b=l.backgroundColorForCell(S,C,a),w=n===d,T=Pe(l)&&l.hasExpandableRows;if(b!=null){const E=N(m,n)+1,y=N(p,s)+1,R=N(g,n)-1,I=N(f,s)-1;e.fillStyle=b,e.fillRect(E,y,R,I)}w&&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=N(i,n),h=N(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()}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:f,treeHorizontalPadding:C}=o,S=N(m,n),b=N(g,t),w=i.textAlignForCell(b,S),T=N(a,t),E=N(h,n),y=N(d,t),R=N(u,n),I=t===l;let x=0;Pe(i)&&i.hasExpandableRows&&I&&(x=f*(i.depthForRow(n)+1)+C);const A=y-x;let k=T+p;const _=E+R*.5;return w==="right"?k=T+A-p:w==="center"&&(k=T+A*.5),k+=x,{width:A-p*2,x:k,y:_}}drawCellContent(e,t,n,s,i){const{metrics:o,model:l,theme:a}=t,{firstColumn:d,fontWidths:h,modelColumns:u,modelRows:m,allRowHeights:g}=o,{textColor:p}=a,f=N(g,s),C=N(m,s),S=N(u,n),b=i??l.textForCell(S,C),w=l.truncationCharForCell(S,C),T=n===d;if(b&&f>0){const E=l.textAlignForCell(S,C)||"left";e.textAlign=E;const y=l.colorForCell(S,C,a)||p;e.fillStyle=y,e.save();const{width:R,x:I,y:x}=this.getTextRenderMetrics(t,n,s),A=h.get(e.font)??Nt.DEFAULT_FONT_WIDTH,k=this.getCachedTruncatedString(e,b,R,A,w),_=l.tokensForCell(S,C,k.length);if(k){let M=0,$=0,H=I;const{actualBoundingBoxDescent:K}=e.measureText(k);for(;$<k.length;){const L=_[M],G=$===L?.start?L:null,ee=G?.end??L?.start??k.length,W=k.substring($,ee),{width:j}=e.measureText(W),B=W.endsWith("…")?e.measureText(W.substring(0,W.length-1)).width:j;G!=null?(e.fillStyle=a.hyperlinkColor,e.fillText(W,H,x),e.fillRect(H,x+K,B,1)):(e.fillStyle=y,e.fillText(W,H,x)),H+=j,$=ee,G!=null&&(M+=1)}}e.restore()}T&&Pe(l)&&l.hasExpandableRows&&this.drawCellRowTreeMarker(e,t,s)}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:f,visibleRowTreeBoxes:C}=s,{treeMarkerColor:S,treeMarkerHoverColor:b}=a,w=N(m,d),T=N(g,d),E=N(p,n),y=N(f,n);if(!Pe(i)||!i.isRowExpandable(n))return;const R=N(C,n),I=o!=null&&l!=null&&o>=h+w&&o<=h+w+T&&l>=u+E&&l<=u+E+y?b:S;this.drawTreeMarker(e,t,w,E,R,I,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)}drawCellRowTreeDepthLines(e,t,n,s){const{metrics:i,model:o,theme:l}=t;if(!Pe(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:f}=l,C=N(h,d),S=N(u,n),b=N(m,n),w=s!==void 0?o.depthForRow(s):0,T=a>w?a-w:0;if(e.strokeStyle=f,e.lineWidth=1,a-T>0){e.beginPath();for(let E=0;E<a-T;E+=1){const y=C+E*g+g*.5+p+.5;e.moveTo(y,S),e.lineTo(y,S+b)}e.stroke()}if(T>0){e.beginPath();for(let E=a-T;E<a;E+=1){const y=C+E*g+g*.5+p+.5;e.moveTo(y,S),e.lineTo(y,S+Math.ceil(b/2)),e.moveTo(y-.5,S+Math.ceil(b/2)+.5),e.lineTo(y+g-.5,S+Math.ceil(b/2)+.5)}e.stroke()}}getCachedTruncatedString=Bn((e,t,n,s,i)=>Nt.truncateToWidth(e,t,n,s,i),{max:1e4});getCachedBackgroundColors=Bn((e,t)=>e.split(" ").map(n=>{const s=[];for(let i=0;i<t;i+=1)s.push(Yd.darkenForDepth(n,i,t));return s}),{max:1e3});getCachedColorWithAlpha=Bn((e,t)=>Yd.colorWithAlpha(e,t),{max:1e3});getCachedColorIsDark=Bn(e=>ih.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:f,allColumnXs:C,floatingLeftColumnCount:S,floatingLeftWidth:b,floatingRightWidth:w,modelColumns:T,columnHeaderMaxDepth:E}=o;if(h<=0)return;const{headerHiddenSeparatorSize:y,headerHiddenSeparatorHoverColor:R,headerSeparatorColor:I,headerSeparatorHoverColor:x}=i,A=h*.5,k=h*(E-1)+h*.5-A*.5,_=S>0;if(e.save(),this.drawColumnHeadersForRange(e,t,[p[0],p[p.length-1]],{minX:m+b,maxX:g-w}),_&&this.drawColumnHeadersForRange(e,t,[u[0],u[u.length-1]],{minX:m,maxX:m+b}),I){e.strokeStyle=I;const M=[...f.entries()].filter(([$,H])=>H===0).map(([$])=>$);e.beginPath(),e.fillStyle=I;for(let $=0;$<M.length;$+=1){const H=M[$],K=N(C,H),L=N(f,H),G=m+K+L+.5-y*.5;e.rect(G,k,y,A)}e.fill()}if(x){let{index:M,depth:$}=l??{};if(M==null&&n!=null&&s!=null){const K=hu.getColumnSeparator(O.getGridPointFromXY(n,s,o),o,d,i);M=K?.index,$=K?.depth}let H;if(M==null)H=!1;else{const K=T.get(M),L=T.get(M+1);K==null||L==null?H=!1:H=d.textForColumnHeader(K,$)!==d.textForColumnHeader(L,$)}if(H&&M!=null&&$!=null&&(!a||l!=null)){e.strokeStyle=x;const K=N(C,M),L=N(f,M),G=m+K+L+.5,ee=p.indexOf(M),W=ee<p.length-1?p[ee+1]:null,j=W!=null?f.get(W):null,B=L===0,Z=j!=null&&j===0;B?(e.strokeStyle=R,e.fillStyle=R,e.fillRect(G,k,y*.5,A)):Z&&(e.fillStyle=x,e.fillRect(G-y*.5,k,y*.5,A)),e.beginPath(),e.moveTo(G,(E-$-1)*h),e.lineTo(G,(E-$)*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:f,columnWidth:C}=a,{columnHeaderMaxDepth:S}=l,{minX:b,maxX:w}=s,T=w-b;if(S===0)return;const E=n[0],y=n[1];if(e.save(),e.translate(0,(S-i-1)*f),i===0){this.drawColumnHeader(e,t,"",b,w);for(let R=E;R<=y;R+=1)this.drawColumnHeaderAtIndex(e,t,R,s)}if(i>0){let R=E;for(;R<=y;){const{columnCount:I}=o,x=N(d,R),A=l.textForColumnHeader(x,i),k=l.colorForColumnHeader(x,i);let _=N(h,R)+u,M=_+N(g,R);if(A!=null){let $=R-1;for(;$>=0&&(M-_<T||_>b);){const G=d.get($)??O.getModelIndex($,p);if(G==null||l.textForColumnHeader(G,i)!==A)break;const ee=m.get(G)??g.get($)??C;_-=ee,$-=1}let H=R+1;for(;H<I&&(M-_<T||M<w);){const G=d.get(H)??O.getModelIndex(H,p);if(l.textForColumnHeader(G,i)!==A)break;const ee=m.get(G)??g.get(H)??C;M+=ee,H+=1}R=H-1;const K=M-_>=T;let L=_;K&&(M<w?L=M-T:_<b&&(L=b)),this.drawColumnHeader(e,t,A,L,Math.min(M-_,T),{backgroundColor:k??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=N(a,n),m=N(d,n)+h,g=N(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:f,white:C}=d,{fontWidths:S,width:b}=a,w=S.get(e.font)??Nt.DEFAULT_FONT_WIDTH,E=(i-h*2)/w,{backgroundColor:y=m,separatorColor:R=p}=o??{};let{textColor:I=g}=o??{};try{const B=this.getCachedColorIsDark(y),Z=this.getCachedColorIsDark(I);B&&Z?I=C:!B&&!Z&&(I=f)}catch{}let{minX:x=0,maxX:A=b}=l??{};e.save(),e.rect(x,0,A-x,u),e.clip(),y!=null&&(e.fillStyle=y,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=I;let k=n;E<=0?k="":k.length>E&&(k=`${k.substring(0,E-1)}…`);const _=k.length*w;let M=s+i*.5;const $=u*.5;x+=h,A-=h;const H=s+h,K=Oe(H,x,A),L=s+i-h,ee=Oe(L,x,A)-K,W=M-_*.5<x,j=M+_*.5>A;W?_<ee?M=x+_*.5:M=L-_*.5:j&&(_<ee?M=A-_*.5:M=H+_*.5),e.textAlign="center",e.fillText(k,M,$),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:f,headerHiddenSeparatorSize:C,headerHiddenSeparatorHoverColor:S,headerSeparatorColor:b,headerSeparatorHoverColor:w}=o,T=d*.5,E=d*.5-T*.5;if(e.save(),e.beginPath(),e.fillStyle=p,e.fillRect(0,0,d,h),b){e.strokeStyle=b,e.beginPath(),e.moveTo(0,a+.5),e.lineTo(d,a+.5);const y=[];let R=!1;for(let I=0;I<u.length;I+=1){const x=u[I],A=N(g,x),k=N(m,x);if(k>0){const _=a+A+k+.5;e.moveTo(0,_),e.lineTo(d,_),R=!1}else R||(R=!0,y.push(x))}e.moveTo(d-.5,0),e.lineTo(d-.5,h),e.stroke(),e.beginPath(),e.fillStyle=b;for(let I=0;I<y.length;I+=1){const x=y[I],A=N(g,x),k=N(m,x),_=a+A+k+.5-C*.5;e.rect(E,_,T,C)}e.fill()}if(w){let{index:y=null}=l??{};if(y==null&&n!=null&&s!=null&&(y=O.getRowSeparatorIndex(n,s,i,o)),y!=null){e.strokeStyle=w;const R=N(g,y),I=N(m,y),x=a+R+I+.5,A=u.indexOf(y),k=A<u.length-1?u[A+1]:null,_=k!=null?m.get(k):null,M=I===0,$=_!=null&&_===0;M?(e.strokeStyle=S,e.fillStyle=S,e.fillRect(E,x,T,C*.5)):$&&(e.fillStyle=w,e.fillRect(E,x-C*.5,T,C*.5)),e.beginPath(),e.moveTo(.5,x),e.lineTo(d+.5,x),e.stroke()}}e.beginPath(),e.rect(0,a,d,h),e.clip(),e.fillStyle=f,e.textAlign="right";for(let y=0;y<u.length;y+=1){const R=u[y],I=N(m,R),x=N(g,R)+a;this.drawRowHeader(e,t,R,x,I)}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=N(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:f,visibleRows:C,allRowHeights:S,allRowYs:b,width:w}=i;if(g<=0)return;const{cellHorizontalPadding:T,headerBackgroundColor:E,headerColor:y,headerHiddenSeparatorSize:R,headerHiddenSeparatorHoverColor:I,headerSeparatorColor:x,headerSeparatorHoverColor:A}=l,k=g*.5,_=g*.5-k*.5,M=Math.min(h+u,w-g-f);if(e.save(),e.beginPath(),e.fillStyle=E,e.fillRect(M,d,g,p),x){e.strokeStyle=x,e.beginPath(),e.moveTo(M,d+.5),e.lineTo(g,d+.5);const H=[];let K=!1;for(let L=0;L<C.length;L+=1){const G=C[L],ee=N(b,G),W=N(S,G);if(W>0){const j=d+ee+W+.5;e.moveTo(M+.5,j),e.lineTo(M+g-.5,j),K=!1}else K||(K=!0,H.push(G))}e.moveTo(M+.5,d),e.lineTo(M+.5,p),e.stroke(),e.beginPath(),e.fillStyle=x;for(let L=0;L<H.length;L+=1){const G=H[L],ee=N(b,G),W=N(S,G),j=d+ee+W+.5-R*.5;e.rect(M+_,j,k,R)}e.fill()}if(A){let{index:H=null}=a??{};if(H==null&&n!=null&&s!=null&&(H=O.getRowSeparatorIndex(n,s,i,l)),H!=null){e.strokeStyle=A;const K=N(b,H),L=N(S,H),G=d+K+L+.5,ee=C.indexOf(H),W=ee<C.length-1?C[ee+1]:null,j=W!=null?S.get(W):null,B=L===0,Z=j!=null&&j===0;B?(e.strokeStyle=I,e.fillStyle=I,e.fillRect(_,G,k,R*.5)):Z&&(e.fillStyle=A,e.fillRect(_,G-R*.5,k,R*.5)),e.beginPath(),e.moveTo(M+.5,G),e.lineTo(M+g+.5,G),e.stroke()}}e.beginPath(),e.rect(M,d,g,p),e.clip(),e.fillStyle=y,e.textAlign="left";const $=M+T;for(let H=0;H<C.length;H+=1){const K=C[H],L=N(S,K);if(L>0){const G=N(b,K)+d,ee=N(m,K),W=G+L*.5;e.fillText(o.textForRowFooter(ee),$,W)}}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:f,allRowYs:C,width:S,height:b}=d,{left:w=d.left,top:T=d.top,right:E=d.right,bottom:y=d.bottom,minY:R=-10,maxY:I=b+10,minX:x=-10,maxX:A=S+10}=n;if(u.length===0)return;const k=ze(h)&&h.isEditable&&a==null&&o==null&&l==null&&s!=null&&i!=null&&p.has(s)&&C.has(i);if(k){const _=N(p,s),M=N(C,i),$=N(g,s),H=N(f,i);e.save(),e.beginPath(),e.rect(0,0,S,b),e.rect(_,M,$,H),e.clip("evenodd")}e.beginPath();for(let _=0;_<u.length;_+=1){const M=u[_],$=M.startColumn!==null?M.startColumn:w,H=M.startRow!==null?M.startRow:T,K=M.endColumn!==null?M.endColumn:E,L=M.endRow!==null?M.endRow:y;if(L>=T&&y>=H&&K>=w&&E>=$){const G=$>=w&&p.has($)?Math.round(N(p,$))+.5:x,ee=H>=T&&C.has(H)?Math.max(Math.round(N(C,H))+.5,.5):R,W=K<=E&&p.has(K)?Math.round(N(p,K)+N(g,K))-.5:A,j=L<=y&&C.has(L)?Math.round(N(C,L)+N(f,L))-.5:I;e.rect(G,ee,W-G,j-ee)}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()}k&&s!=null&&i!=null&&(e.restore(),this.drawActiveCell(e,t,s,i))}drawActiveCell(e,t,n,s,i=Nt.ACTIVE_CELL_BORDER_WIDTH){const{metrics:o,theme:l}=t,{allColumnWidths:a,allColumnXs:d,allRowHeights:h,allRowYs:u}=o,m=N(d,n),g=N(u,s),p=N(a,n),f=N(h,s);let C=m-i*.5,S=g-i*.5,b=p+i,w=f+i;C<=0&&(b+=C-1,C=1),S<=0&&(w+=S-1,S=1);const{lineWidth:T}=e;e.beginPath(),e.lineWidth=i,e.strokeStyle=l.selectionOutlineColor,this.drawRoundedRect(e,C,S,b,w),e.stroke(),e.lineWidth=T}drawRoundedRect(e,t,n,s,i,o=Nt.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:f,columnHeaderMaxDepth:C,columnHeaderHeight:S,movedColumns:b,modelColumns:w,floatingLeftWidth:T}=s,E=w.get(a[0])??O.getModelIndex(a[0],b),y=l.getColumnHeaderGroup(E,d);if(d>0&&!y)return;const[R,I]=a,x=N(m,R),k=N(m,I)+N(g,I)-x,_=n.left,{backgroundColor:M,font:$,headerFont:H,reorderOffset:K,shadowBlur:L,shadowColor:G}=o,ee=(C-d-1)*S;e.save(),e.translate(h,0),e.save(),e.beginPath(),e.rect(T,0,f,p),e.clip(),e.fillStyle=M,e.fillRect(x,ee,k,p),e.restore(),e.translate(0,K),e.save(),e.shadowColor=G,e.shadowBlur=L,e.fillStyle=M,e.fillRect(n.left,ee+K,n.width,p),e.restore(),e.beginPath(),e.rect(n.left,ee,n.width+1,p),e.clip(),e.translate(_-x,0),e.font=H;const W=[];for(let j=n.range[0];j<=n.range[1];j+=1)W.push(j);this.drawColumnHeaders(e,t),this.drawColumnHeadersForRange(e,t,[W[0],W[W.length-1]],{minX:x,maxX:f}),e.translate(0,u),e.font=$,this.drawGridBackground(e,t);for(let j=R;j<=I;j+=1)this.drawColumnCellContents(e,t,j);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=N(h,n),p=N(u,n)+1,{backgroundColor:f,font:C,headerFont:S,reorderOffset:b,shadowBlur:w,shadowColor:T}=l;e.save(),e.translate(0,d),e.fillStyle=f,e.fillRect(0,g,m,p),e.translate(a+b,o-g-d-(s??0)),e.save(),e.shadowColor=T,e.shadowBlur=w,e.fillStyle=f,e.fillRect(-a,g,m,p),e.restore(),e.beginPath(),e.rect(-a,g,m,p),e.clip(),e.font=C,this.drawGridBackground(e,t),this.drawCellContents(e,t),e.translate(-a,-d),e.font=S,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:f,hasHorizontalBar:C,hasVerticalBar:S,barWidth:b,barHeight:w,barLeft:T,barTop:E}=o,{scrollBarBackgroundColor:y,scrollBarHoverBackgroundColor:R,scrollBarCasingColor:I,scrollBarCornerColor:x,scrollBarColor:A,scrollBarHoverColor:k,scrollBarActiveColor:_,scrollBarSize:M,scrollBarHoverSize:$,scrollBarCasingWidth:H,scrollBarSelectionTick:K,scrollBarSelectionTickColor:L,scrollBarActiveSelectionTickColor:G,autoSelectRow:ee,autoSelectColumn:W}=d,j=l!=null&&a!=null&&l<=h&&a<=u,B=s||S&&!n&&!i&&l!=null&&a!=null&&l>=h-$&&a>=E&&j,Z=n||C&&!s&&!i&&!B&&l!=null&&a!=null&&a>=u-$&&l>=T&&j,se=Z?$:M,ae=B?$:M;if(e.translate(T,E),C&&S&&(e.fillStyle=I,e.fillRect(h-T-M,u-E-M,M,M),e.fillStyle=x,e.fillRect(h-T-M+H,u-E-M+H,M-H,M-H)),C){const q=p,ne=u-E-se;if(e.fillStyle=I,e.fillRect(0,ne,b,se-H),e.fillStyle=Z?R:y,e.fillRect(0,ne+H,b,se-H),n?e.fillStyle=_:Z?e.fillStyle=k:e.fillStyle=A,e.fillRect(q,ne+H,g,se-H),!ee&&K&&L!=null&&G!=null){e.fillStyle=L;const{selectedRanges:he,cursorColumn:Te}=t,{lastLeft:ye,columnCount:rt}=o,Wt=[...he].filter(Ee=>Ee.startColumn!=null&&Ee.endColumn!=null).map(Ee=>[Ee.startColumn,Ee.endColumn]).sort(O.compareRanges),fn=O.mergeSortedRanges(Wt),xt=Ee=>Ee<=ye?Ee/ye*(b-g):b-g+(Ee-ye)/(rt-ye)*g;for(let Ee=0;Ee<fn.length;Ee+=1){const lt=fn[Ee],et=lt[0],pt=lt[1];if(et!=null&&pt!=null&&(et!==Te||pt!==Te)){const It=xt(et),Cn=Math.max(1,Math.round(xt(pt+1)-It)),Gt=se-H;e.fillRect(It,ne+H+Math.round(Gt/3),Cn,Math.round(Gt/3))}}if(Te!=null){const Ee=xt(Te),lt=2,et=se-H;e.fillStyle=G,e.fillRect(Ee,ne+H,lt,et)}}}if(S){const q=h-T-ae,ne=f;if(e.fillStyle=I,e.fillRect(q,0,ae-H,w),e.fillStyle=B?R:y,e.fillRect(q+H,0,ae-H,w),s?e.fillStyle=_:B?e.fillStyle=k:e.fillStyle=A,e.fillRect(q+H,ne,ae-H,m),!W&&K&&L!=null&&G!=null){const{selectedRanges:he,cursorRow:Te}=t,{lastTop:ye,rowCount:rt}=o,wt=Ee=>Ee<=ye?Ee/ye*(w-m):w-m+(Ee-ye)/(rt-ye)*m;e.fillStyle=L;const fn=[...he].filter(Ee=>Ee.startRow!=null&&Ee.endRow!=null).map(Ee=>[Ee.startRow,Ee.endRow]).sort(O.compareRanges),xt=O.mergeSortedRanges(fn);for(let Ee=0;Ee<xt.length;Ee+=1){const lt=xt[Ee],et=lt[0],pt=lt[1];if(et!=null&&pt!=null&&(et!==Te||pt!==Te)){const It=wt(et),Cn=ae-H,Gt=Math.max(1,Math.round(wt(pt+1)-It));e.fillRect(q+H+Math.round(Cn/3),It,Math.round(Cn/3),Gt)}}if(Te!=null){const Ee=Math.round(wt(Te)),lt=ae-H,et=2;e.fillStyle=G,e.fillRect(q+H,Ee,lt,et)}}}e.translate(-T,-E)}getTokenBoxesForVisibleCell(e,t,n){const{metrics:s,context:i,model:o,theme:l}=n;if(i==null||s==null)return Ie;const{modelRows:a,modelColumns:d}=s,h=N(a,t),u=N(d,e),m=o.textForCell(u,h),{width:g,x:p,y:f}=this.getTextRenderMetrics(n,e,t),{fontWidths:C}=s;i.save(),this.configureContext(i,n);const S=C?.get(i.font)??Nt.DEFAULT_FONT_WIDTH,b=o.truncationCharForCell(u,h),w=this.getCachedTruncatedString(i,m,g,S,b),{actualBoundingBoxAscent:T,actualBoundingBoxDescent:E}=i.measureText(w),y=T+E,R=o.tokensForCell(u,h,w.length);if(R.length===0)return i.restore(),Ie;const I=this.getCachedTokenBoxesForVisibleCell(w,R,l.font,"middle",y,i).map(x=>({x1:x.x1+p,y1:x.y1+(f-T),x2:x.x2+p,y2:x.y2+(f-T),token:x.token}));return i.restore(),I}getCachedTokenBoxesForVisibleCell=Bn((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:f}=g,C=f>e.length?e.substring(p):g.value;u+=o.measureText(e.substring(h,p)).width;const S=o.measureText(C).width,b=u,w=b+S,T={x1:b,y1:0,x2:w,y2:a,token:g};d.push(T),h=f,u+=S}return d},{max:1e4})}const Fb=Nt,qd=100;class Nb extends ot{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 f=O.isModifierKeyDown(n),C=n.shiftKey;f||(C?t.trimSelectedRanges():t.clearSelectedRanges());const S=t.getTheme(),{autoSelectRow:b,autoSelectColumn:w}=S;return(o!==null||!w)&&(l!==null||!b)&&(t.focus(),t.moveCursorToPosition(o,l,C,!1,C&&f)),this.startPoint=e,this.hasExtendedFloating=!1,this.dragBounds=O.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:f}=d,C=O.getScrollDragBounds(d,n,s);let S=0,b=0;if(h<u&&(i<C.x1?S=i-C.x1:i>C.x2&&(S=i-C.x2)),m<g&&(o<C.y1?b=o-C.y1:o>C.y2&&(b=o-C.y2)),S!==0||b!==0)this.startTimer(t,e,S>0?Math.ceil(S/p):Math.floor(S/p),b>0?Math.ceil(b/f):Math.floor(b/f));else if(l!=null&&a!=null){const{floatingTopRowCount:w,floatingBottomRowCount:T,floatingLeftColumnCount:E,floatingRightColumnCount:y,columnCount:R,rowCount:I,bottom:x,right:A,topVisible:k,bottomVisible:_,leftVisible:M,rightVisible:$}=d;this.hasExtendedFloating||(n!==null&&n<w&&l>=w?(l=w,this.hasExtendedFloating=!0):n!==null&&n>=I-T&&l<I-T&&(l=I-T-1,this.hasExtendedFloating=!0),s!==null&&s<E&&a>=E?(a=E,this.hasExtendedFloating=!0):s!==null&&s>=R-y&&a<R-y&&(a=R-y-1,this.hasExtendedFloating=!0)),n!==null&&!O.isFloatingRow(n,d)&&O.isFloatingRow(l,d)&&(n>l&&l<m?l=k-1:n<l&&l>x&&(l=_+1)),s!==null&&!O.isFloatingColumn(s,d)&&O.isFloatingColumn(a,d)&&(s>a&&a<h?a=M-1:s<a&&a>A&&(a=$+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,f=s>0&&i!=null?i:h-1;e.moveCursorToPosition(Math.min(Math.max(m,d+n),g),Math.min(Math.max(p,a+s),f),!0),this.lastTriggerTime=Date.now()}startTimer(e,t,n,s){this.stopTimer();const i=this.lastTriggerTime!=null?qd-Math.min(qd,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 kb=Nb,Xd=5,Mb=1e3/60,Bo=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)??O.getModelIndex(c,i),p=n.getColumnHeaderGroup(g,e),f=p!=null;let C,S,b;if(p!=null){const[w,T]=p.getVisibleRange(i);C=o.get(w)??u,S=(o.get(T)??m)+(a.get(T)??0),b=[w,T]}else{const w=o.get(c);if(w==null)return null;C=w,S=C+(a.get(c)??d.get(g)??h.get(g)??0),b=[c,c]}return{visibleIndex:c,modelIndex:g,left:C,right:S,width:S-C,isColumnGroup:f,range:b,depth:e}}class Ob extends ot{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-=Bo;m<0;){u-=1;const f=O.getModelIndex(s-1,d),C=l.get(f)??a.get(f);C===void 0?m=0:m+=C,u<0&&(m=0,u=0)}else{m+=Bo;let f=h.get(s);for(;f!==void 0&&m>f;){u+=1,m-=f;const C=O.getModelIndex(s+1,d);f=l.get(C)??a.get(C),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"?-Bo:Bo),e.setState({left:u,leftOffset:m}),(t==="left"&&u===0&&o===0||t==="right"&&u===i)&&this.clearScrollInterval())},Mb))}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)<Xd&&Math.abs(this.initialGridPoint.y-i)<Xd)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,f=p+g.width;this.draggingColumn={...this.draggingColumn,left:p},t.setState({draggingColumn:this.draggingColumn});const C=is(O.getColumnAtX(Oe(m?p:f,a,d),l,!0),s,l,i),S=i.getColumnHeaderParentGroup(g.modelIndex,g.depth);if(!C)return;if(S!==void 0){const R=S.getVisibleRange(o);if(C.visibleIndex<R[0]){const I=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:I});return}if(C.visibleIndex>R[1]){const I=this.moveColumn(g,R[1]-(g.range[1]-g.range[0]),o),{right:x=0}=is(R[1],0,l,i)??{};this.draggingOffset=e-(x-g.width),this.draggingColumn={...this.draggingColumn,left:e-this.draggingOffset},this.clearScrollInterval(),t.setState({draggingColumn:this.draggingColumn,movedColumns:I});return}}if(!i.isColumnMovable(C.modelIndex)){let R=C.visibleIndex;if(m)for(R+=1;R<g.visibleIndex&&!i.isColumnMovable(O.getModelIndex(R,o));)R+=1;else for(R-=1;R>g.visibleIndex&&!i.isColumnMovable(O.getModelIndex(R,o));)R-=1;if(R!==g.visibleIndex){m||(R-=g.range[1]-g.range[0]);const x=this.moveColumn(g,R,o);t.setState({movedColumns:x,draggingColumn:this.draggingColumn})}const I=is(R,0,l,i);m?this.draggingOffset=e-(I?.left??0):this.draggingOffset=e-((I?.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"):f>d?this.setScrollInterval(t,"right"):this.clearScrollInterval(),C.visibleIndex===g.visibleIndex||m&&g.visibleIndex<C.visibleIndex||!m&&g.visibleIndex>C.visibleIndex)return;const b=C.left+C.width*.5,w=i.getColumnHeaderParentGroup(g.modelIndex,g.depth);let T,E=(w?.depth??h)-1;for(;E>=0&&T===void 0;)T=i.getColumnHeaderGroup(C.modelIndex,E),E-=1;let y;m&&p<b&&(!T||C.visibleIndex===T.getVisibleRange(o)[0])&&(y=this.moveColumn(g,C.range[0],o)),!m&&f>b&&(!T||C.visibleIndex===T.getVisibleRange(o)[1])&&(y=this.moveColumn(g,C.range[1]-(g.range[1]-g.range[0]),o)),y&&(this.draggingColumn={...this.draggingColumn,left:p},t.setState({movedColumns:y,draggingColumn:this.draggingColumn}))}moveColumn(e,t,n){const s=e.isColumnGroup?O.moveRange(e.range,t,n):O.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 Ab=Ob;class kr extends ot{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 kr.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 Lb=kr;class _b extends ot{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=N(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:y}=t.getGridPointFromXY(i,o);if(y!=null&&!n.isRowMovable(y)||(s=y,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:f,height:C}=l;let S=g;if(a<s){const y=s-1;S=N(f,y)+N(p,y)*.5+g}let b=C;if(s<h){const y=s+1;b=N(f,y)+N(p,y)*.5+g}let{movedRows:w}=t.state;o<S&&s>0&&n.isRowMovable(s-1)?(w=O.moveItem(s,s-1,w),s-=1):b<o&&s<m-1&&n.isRowMovable(s+1)&&(w=O.moveItem(s,s+1,w),s+=1),t.setState({movedRows:w,draggingRow:s});const T=g+N(p,a)*.5,E=g+N(f,u)+N(p,u)*.5;return o<T&&a>0?t.setState({top:a-1}):o>E&&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 Pb=_b;class Mr extends cu{static getRowSeparator(e,t,n,s){if(!s.allowRowResize)return null;const{x:i,y:o}=e,l=O.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=O.getHiddenRows;getNextShownItem=O.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=Mr.getRowSeparator}const jb=Mr;class wl extends ot{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:f}=l;if(n===h&&s!=null&&f.get(s)!=null&&i>a&&o>d){const C=N(u,n),S=N(m,n),b=N(p,s),w=N(g,s);if(i>=a+C&&i<=a+C+S&&o>=d+b&&o<=d+b+w)return!0}return!1}onDown(e,t){return wl.isInTreeBox(e,t)}onClick(e,t,n){if(wl.isInTreeBox(e,t)){const{row:s}=e;if(s!==null)return t.toggleRowExpanded(s,O.isModifierKeyDown(n)),!0}return!1}}const qa=wl;class Hb extends ot{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 Ub=Hb;class Or extends ot{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 Or.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 Bb=Or;class Vb extends ot{onDoubleClick({column:e,row:t},n){const{model:s}=n.props;return ze(s)&&e!=null&&t!=null&&s.isEditableRange(Re.makeCell(e,t))?(n.startEditing(e,t),!0):!1}}const $b=Vb;class Ar extends ot{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}=t;if(n==null||s==null||a==null)return this.currentLinkBox=void 0,!1;if(this.currentLinkBox!=null){const{x1:u,y1:m,x2:g,y2:p}=this.currentLinkBox;if(i>=u&&i<=g&&o>=m&&o<=p)return!0}const d=t.updateRenderState(),h=l.getTokenBoxesForVisibleCell(n,s,d);for(let u=0;u<h.length;u+=1)if(bl(h[u].token)){const m=O.translateTokenBox(h[u],a),{x1:g,x2:p,y1:f,y2:C}=m;if(i>=g&&i<=p&&o>=f&&o<=C)return this.currentLinkBox=m,!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 O.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),ze(l)&&i!=null&&o!=null&&l.isEditableRange(Re.makeCell(i,o))&&t.startEditing(i,o)},Ar.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 Wb=Ar;class Gb{order;constructor(e=5e3){this.order=e}onDown(e,t){return!1}}const Js=Gb;class zb extends Js{onDown(e,t){switch(e.key){case"a":if(O.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 O.isModifierKeyDown(e)?!1:this.handlePageUp(e,t);case"j":case"J":return O.isModifierKeyDown(e)?!1:this.handlePageDown(e,t);case"h":case"H":return O.isModifierKeyDown(e)?!1:(e.shiftKey||t.clearSelectedRanges(),t.moveCursorToPosition(0,t.state.cursorRow,e.shiftKey),!0);case"l":case"L":{if(O.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(O.isModifierKeyDown(e)?t.state.cursorColumn:0,O.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(O.isModifierKeyDown(e)?t.state.cursorColumn:s-1,O.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?Re.SELECTION_DIRECTION.UP:Re.SELECTION_DIRECTION.DOWN),!0;break;case"Tab":if(t.state.selectedRanges.length>0)return t.moveCursorInDirection(e.shiftKey?Re.SELECTION_DIRECTION.LEFT:Re.SELECTION_DIRECTION.RIGHT),!0;break}return!1}handleArrowMove(e,t,n,s){const i=n.shiftKey,o=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:f}=g,C=o&&i;let S=null,b=null;e<0?(S=0,b=m):e>0?(S=p-1,b=m):t<0?(S=u,b=0):t>0&&(S=u,b=f-1),S!=null&&b!=null&&s.moveCursorToPosition(S,b,i,!0,C)}else{if(!s.metrics)throw new Error("grid.metrics are not set");const{theme:g}=s.props,{autoSelectRow:p=!1,autoSelectColumn:f=!1}=g;if(p&&e!==0){const{lastLeft:C}=s.metrics;let{left:S}=s.state;S=Oe(S+e,0,C),s.moveCursorToPosition(S,l,i,!1),s.setViewState({left:S})}else if(f&&t!==0){const{lastTop:C}=s.metrics;let{top:S}=s.state;S=Oe(S+t,0,C),s.moveCursorToPosition(S,a,i,!1),s.setViewState({top:S})}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),f=g-1;let C=h-u+o;C+=m?0:1,C=Math.min(C,f);const S=Math.min(p,C-(o-u));return t.moveCursorToPosition(l,C,n,!1),t.setViewState({top:S}),!0}}const Kb=zb;class Yb extends Js{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)&&Pe(i)&&i.isRowExpandable(a))return t.toggleRowExpanded(o),!0}}}return!1}}const qb=Yb;class Xb extends Js{onDown(e,t){if(O.isModifierKeyDown(e))return!1;const{model:n}=t.props,{cursorColumn:s,cursorRow:i}=t.state;if(s==null||i==null||!ze(n)||!n.isEditableRange(Re.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 Zb=Xb;function Qb(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 Jb(c){const e=[];return c.forEach(t=>{const n=t.textContent??"";n.length>0&&e.push(n.split(/\t|\u00a0\u00a0 \u00a0/))}),e}function ew(c){const e=c.querySelector("table");if(e!=null)return Qb(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
|
+
`).map(o=>o.split(" ")):n.length>1||i?Jb(c.childNodes):t}return null}class tw extends Js{onDown(e,t){switch(e.key){case"v":if(O.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=ew(n);i!=null&&t.pasteValue(i)};return n.addEventListener("input",s),n.focus(),{preventDefault:!1,stopPropagation:!0}}break}return!1}}const nw=tw;const sw=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 Lr({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),[f,C]=v.useState(s),[S,b]=v.useState(n);v.useEffect(function(){const{current:_}=h;_!=null&&(_.focus(),c?_.setSelectionRange(c[0],c[1]):_.setSelectionRange(_.value.length,_.value.length))},[c]);const w=v.useCallback(k=>{i(k)},[i]),T=v.useCallback(k=>{const{value:_}=k.target;b(_),p(!0),w(_)},[w,b,p]),E=v.useCallback(()=>{u.current=!0,g&&w(m),p(!1),o()},[m,g,o,w]),y=v.useCallback(()=>{C(!1)},[C]),R=v.useCallback((k,_=!1)=>{l(S,{direction:k,fillRange:_})},[l,S]),I=v.useCallback(()=>{u.current||R(null)},[u,R]),x=v.useCallback(k=>{switch(k.stopPropagation(),k.key){case"Escape":k.preventDefault(),E();break;case"Enter":if(k.preventDefault(),O.isModifierKeyDown(k))R(void 0,!0);else if(k.altKey){const _=`${S}
|
|
20
|
+
`;b(_),p(!0),w(_)}else R(k.shiftKey?mn.UP:mn.DOWN);break;case"Tab":k.preventDefault(),R(k.shiftKey?mn.LEFT:mn.RIGHT);break;case"ArrowDown":case"ArrowUp":case"ArrowLeft":case"ArrowRight":f&&(k.preventDefault(),R(sw(k.key)));break}},[E,R,f,b,p,w,S]),A=v.useCallback(k=>{a(k)},[a]);return r.jsx("textarea",{ref:h,className:z("grid-cell-input-field",e),value:S,onBlur:I,onChange:T,onKeyDown:x,onContextMenu:A,onClick:y,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false",disabled:t,style:d})}Lr.propTypes={selectionRange:U.arrayOf(U.number),className:U.string,disabled:U.bool,isQuickEdit:U.bool,value:U.string,onChange:U.func,onCancel:U.func,onDone:U.func,onContextMenu:U.func,style:U.shape({})};Lr.defaultProps={selectionRange:null,className:"",disabled:!1,value:"",isQuickEdit:!0,onChange:()=>{},onCancel:()=>{},onDone:()=>{},onContextMenu:()=>{},style:{}};const iw=oe.createContext({}),ow=iw;class hs extends v.PureComponent{static contextType=ow;static defaultProps={canvasOptions:{alpha:!1},isStickyBottom:!1,isStickyRight:!1,isStuckToBottom:!1,isStuckToRight:!1,keyHandlers:Ie,mouseHandlers:Ie,movedColumns:Ie,movedRows:Ie,onError:()=>{},onSelectionChanged:()=>{},onMovedColumnsChanged:e=>{},onMoveColumnComplete:()=>{},onMovedRowsChanged:()=>{},onMoveRowComplete:()=>{},onViewChanged:()=>{},onTokenClicked:e=>{bl(e)&&window.open(e.href,"_blank","noopener,noreferrer")},stateOverride:{},theme:{autoSelectColumn:!1,autoSelectRow:!1}};static pixelsPerLine=100/3;static dragTimeout=1e3;static getTheme=ce((e,t)=>({...yb,...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 Fb,this.metricCalculator=s||new Tb,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 Zb(400),new nw(450),new Kb(500),new qb(900)],this.mouseHandlers=[new jb(100),new hu(200),new Pb(300),new Ab(400),new $b(450),new Bb(500),new Lb(600),new Ub(700),new qa(800),new Wb(825),new kb(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:Ie,lastSelectedRanges:Ie,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:f,movedRows:C}=t,{draggingColumn:S,draggingRow:b,movedColumns:w,movedRows:T}=this.state;g!==i&&this.setState({movedColumns:i}),p!==o&&this.setState({movedRows:o}),f!==w&&l(w),t.draggingColumn!=null&&S==null&&a(w),C!==T&&d(T),t.draggingRow!=null&&b==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){Gd(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 O.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:f,draggingColumn:C}=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:f,draggingColumn:C,...s}}getCachedKeyHandlers=ce(e=>[...e,...this.keyHandlers].sort((t,n)=>t.order-n.order));getKeyHandlers(){const{keyHandlers:e}=this.props;return this.getCachedKeyHandlers(e)}getCachedMouseHandlers=ce(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;Pe(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=Re.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;D(e),D(t),D(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 f=o[o.length-1];let C=null,S=null,b=null,w=null;s?(C=h!==void 0&&h?null:Math.min(e??0,f.startColumn??0),S=u!==void 0&&u?null:Math.min(t??0,f.startRow??0),b=h!==void 0&&h?null:Math.max(e??0,f.endColumn??0),w=u!==void 0&&u?null:Math.max(t??0,f.endRow??0)):(C=f.startColumn,S=f.startRow,(a!=null||l!=null)&&((h===void 0||!h)&&(C=a),(u===void 0||!u)&&(S=l)),b=h!==void 0&&h?null:e,w=u!==void 0&&u?null:t);const T=Re.makeNormalized(C,S,b,w);if(f.equals(T))return null;const E=[...o];return E[E.length-1]=T,{selectedRanges:E,selectionEndColumn:e,selectionEndRow:t}}const m=[...o],g=h!==void 0&&h?null:e,p=u!==void 0&&u?null:t;return m.push(Re.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?Re.rowCount(s)===1:Re.cellCount(s)===1)&&Re.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=Re.consolidate(a)}let d=l,h=o;if(!Re.containsCell(a,l,o)){const{model:u}=this.props,{columnCount:m,rowCount:g}=u,p=Re.nextCell(Re.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 Re(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 Re(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=Re.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:[Re.makeCell(o,i)];let d=null;if(a.length===1&&Re.cellCount(a)===1){const h=new Re(0,0,n-1,s-1);d=h.nextCell(o,i,e)??h.startCell(e)}else d=Re.nextCell(Re.boundedRanges(a,n,s),o,i,e);if(d!=null){const{column:h,row:u}=d;this.setState({cursorColumn:h,cursorRow:u}),Re.containsCell(l,h,u)||this.setState({selectedRanges:[Re.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&&!O.isFloatingRow(t,this.metrics)&&(t<o?(d=n.getTopForTopVisible(a,t),u=0):t>s&&(d=n.getTopForBottomVisible(a,t),u=0)),e!=null&&!O.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(!ze(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 ze(s)&&s.isValidForCell(i,o,n)}async pasteValue(e){const{model:t}=this.props,{movedColumns:n,movedRows:s,selectedRanges:i}=this.state;try{if(zd(t),!t.isEditable||!i.every(m=>t.isEditableRange(m)))throw new wa("Can't paste in to read-only area.");if(i.length<=0)throw new wa("Select an area to paste to.");if(typeof e=="string"){const m=[],g=O.getModelRanges(i,n,s);Re.forEachCell(g,(p,f)=>{m.push({column:p,row:f,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=>Re.cellCount([m])===1&&(m.startColumn??0)+l<=a&&(m.startRow??0)+o<=d)&&(h=h.map(m=>new Re(m.startColumn,m.startRow,(m.startColumn??0)+l-1,(m.startRow??0)+o-1)),this.setSelectedRanges(h)),!h.every(m=>Re.rowCount([m])===o&&Re.columnCount([m])===l))throw new wa("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;zd(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=O.getModelRanges(e,s,i);ze(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:f,left:C,topOffset:S,leftOffset:b}=n;const w=this.getTheme();let{deltaX:T,deltaY:E}=O.getScrollDelta(e,n.barWidth,n.barHeight,n.rowHeight,n.rowHeight);for(;g&&T!==0;){if(b+=T,T=0,l>1){if(b>0&&C>=o||b<0&&C<=0){b=0;break}}else{if(b<=0){b=0;break}const y=d-h;if(b>=y){b=y;break}}if(b>0){const y=n.allColumnWidths.get(C)??t.getVisibleColumnWidth(C,s);b>=y?(T=b-y,b=0,C+=1):w.scrollSnapToColumn&&l>1&&(b=0,C+=1)}else if(b<0){const y=n.allColumnWidths.get(C-1)??t.getVisibleColumnWidth(C-1,s);Math.abs(b)<=y&&w.scrollSnapToColumn&&l>1?(b=0,C-=1):(T=b+y,b=0,C-=1)}}for(;p&&E!==0;){if(S+=E,E=0,a>1){if(S>0&&f>=i||S<0&&f<=0){S=0;break}}else{if(S<=0){S=0;break}const y=u-m;if(S>=y){S=y;break}}if(S>0){const y=n.allRowHeights.get(f)??t.getVisibleRowHeight(f,s);S>=y?(E=S-y,S=0,f+=1):w.scrollSnapToRow&&a>1&&(S=0,f+=1)}else if(S<0){const y=n.allRowHeights.get(f-1)??t.getVisibleRowHeight(f-1,s);Math.abs(S)<=y&&w.scrollSnapToRow&&a>1?(S=0,f-=1):(E=S+y,S=0,f-=1)}}this.setViewState({top:f,left:C,leftOffset:b,topOffset:S}),e.stopPropagation(),e.preventDefault()}handleEditCellCancel(){this.setState({editingCell:null}),this.focus()}handleEditCellChange(e){this.setState(({editingCell:t})=>{try{return Gd(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||!ze(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,f=u.get(l),C=m.get(a),S=g.get(l),b=p.get(a),w=f!=null&&C!=null&&S!=null&&b!=null?{position:"absolute",left:d+f,top:h+C,width:S,height:b}:{opacity:0},T=this.getModelColumn(l),E=this.getModelRow(a),y=T!=null&&E!=null?{textAlign:e.textAlignForCell(T,E)}:void 0,R=e.isValidForCell(T,E,i);return r.jsx("div",{style:w,children:r.jsx(Lr,{selectionRange:s,className:z({error:!R}),onCancel:this.handleEditCellCancel,onChange:this.handleEditCellChange,onDone:this.handleEditCellCommit,isQuickEdit:o,style:y,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:f,stateOverride:C}=this.props,{metrics:S}=this,b=this.canvasContext,w=this.getTheme(),T=this.canvas.clientWidth,E=this.canvas.clientHeight;return D(S),this.renderState={width:T,height:E,context:b,theme:w,model:f,metrics:S,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,...C},this.renderState}render(){const{cursor:e}=this.state;return r.jsxs(r.Fragment,{children:[r.jsx("canvas",{className:z("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 lw=hs,va=5e3;class aw extends sm{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=va){const s=this.textForCell(e,t);return this.getCachedTokensInText(s,n)}getCachedTokensInText=Bn((e,t)=>{if(t>=e.length)return O.findTokensWithProtocolInText(e);const n=e.slice(t-1,va).search(/\s/);let s=t+n;n===-1&&(s=Math.min(va,e.length));const i=e.substring(0,s);return O.findTokensWithProtocolInText(i)})}const rw=aw;function dw(c,e){const t=uw(c);return t===void 0?void 0:`${Sw(c)} ? ${t} : ${e}`}function cw(c,e){return c.Column.formatRowColor(e)}function hw(c,e){return c.formatColor(e)}const Zi=J.module("ConditionalFormattingUtils");var Fn=(c=>(c.CONDITIONAL="conditional",c.ROWS="rows",c))(Fn||{}),je=(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))(je||{}),Pt=(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))(Pt||{}),yt=(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))(yt||{}),qi=(c=>(c.IS_TRUE="is-true",c.IS_FALSE="is-false",c.IS_NULL="is-null",c.IS_NOT_NULL="is-not-null",c))(qi||{}),Ks=(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))(Ks||{}),sn=(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))(sn||{});function Zd(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 vl(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 Tl(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 uw(c){const e=Tl(c.style),t=vl(c.style);if(!(e===void 0||t===void 0))return`bgfg(\`${t}\`, \`${e}\`)`}function mw(c){const{column:e,value:t,start:n,end:s}=c;return Fw(e.name,c.condition,t,n,s)}function gw(c){const{column:e,value:t}=c;return Nw(e.name,c.condition,t)}function pw(c){const{column:e,value:t}=c;return kw(e.name,c.condition,t)}function fw(c){const{column:e}=c;return Mw(e.name,c.condition)}function Cw(c){const{column:e,value:t}=c;return Ow(e.name,c.condition,t)}function Sw(c){const{column:e}=c;if(F.isNumberType(e.type))return mw(c);if(F.isCharType(e.type))return Cw(c);if(F.isStringType(e.type))return gw(c);if(F.isDateType(e.type))return pw(c);if(F.isBooleanType(e.type))return fw(c);throw new Error("Invalid column type")}function bw(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 ww(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 vw(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 Tw(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 Ew(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 uu(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 mu(c){if(F.isCharType(c)||F.isStringType(c))return""}function gu(c){const{condition:e,value:t,start:n,end:s}=c;return{condition:e,value:t,start:n,end:s}}function ta(c){return{condition:uu(c),value:mu(c),start:void 0,end:void 0}}function pu(){return{type:"no-formatting"}}function yw(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 Rw(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 xw(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 Iw(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 Dw(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 Fw(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 Nw(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 kw(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 Mw(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 Ow(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 Aw(c,e){if(F.isNumberType(c))return Dw(e);if(F.isCharType(c))return Iw(e);if(F.isStringType(c))return yw(e);if(F.isDateType(c))return Rw(e);if(F.isBooleanType(c))return xw(e);throw new Error("Invalid column type")}function Lw(c,e,t){if(t===void 0)return Zi.debug("no rules passed."),[];const n=[];let s;const i=new Map;return t.forEach(({config:o,type:l})=>{const{column:a}=o,d=e.find(({name:f,type:C})=>f===a.name&&C===a.type);if(d===void 0){Zi.debug(`Column ${a.name}:${a.type} not found. Ignoring format rule.`,o);return}const[h,u]=(l==="conditional"?i.get(d.name):s)??["null",void 0],m=dw(o,h);if(m===void 0){Zi.debug("Ignoring format rule.",o);return}const g=u===void 0?-1:n.indexOf(u);g>-1&&n.splice(g,1);const p=l==="conditional"?hw(d,m):cw(c,m);n.push(p),l==="conditional"?i.set(d.name,[m,p]):s=[m,p]}),n}function _w(c,e,t){switch(e){case"is-null":case"is-not-null":return!0;default:{const[n,...s]=(t??"").split(" "),i=s.join(" ");try{Zs.parseDateTimeString(n)}catch{return Zi.debug("Invalid datetime string",n),!1}try{c.i18n.TimeZone.getTimeZone(i)}catch{return Zi.debug("Invalid timezone string",i),!1}return!0}}}function Pw({type:c}){return F.isNumberType(c)||F.isCharType(c)||F.isStringType(c)||F.isDateType(c)||F.isBooleanType(c)}function na({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(Vt,{in:n,timeout:Ye.transitionMs,classNames:c,onEntering:i,onEntered:o,onExiting:l,onExited:a,mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:z("iris-grid-bottom-bar",t),role:"presentation",onClick:s,onKeyPress:s,children:e})})}const jw=3e3,Hw=5;function Uw({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,f]=v.useState(!1),C=v.useRef(),S=ir(c),b=v.useMemo(()=>o.size===0?i:o.size<=Hw?`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(){S!=null&&S&&!c&&b==null&&(g(!0),f(!0),C.current=setTimeout(()=>{g(!1)},jw))},[b,c,S]),v.useEffect(function(){C.current&&l.size>0&&(clearTimeout(C.current),g(!1),f(!1))},[l]),v.useEffect(function(){return()=>C.current?clearTimeout(C.current):void 0},[]);const w=l.size;let T;return c?T=r.jsx(Nn,{}):p&&(T=ar),r.jsxs(na,{className:"pending-data-bottom-bar",isShown:w>0||m||b!=null,onEntering:a,onEntered:d,onExiting:h,onExited:()=>{f(!1),u&&u()},children:[b!=null&&b!==""&&r.jsxs("div",{className:"error-message",children:[r.jsx(X,{icon:Ss}),r.jsx("span",{children:`${b}`})]}),(b==null||b==="")&&r.jsx("div",{className:"status-message",children:w>0&&r.jsx("span",{children:`${w} row${w>1?"s":""} pending`})}),r.jsxs("div",{className:"buttons-container",children:[!c&&!p&&r.jsx(P,{kind:"secondary",onClick:t,tooltip:n,children:"Discard"}),r.jsxs(P,{kind:p?"success":"primary",onClick:e,icon:T,disabled:c||p||b!=null,tooltip:s,children:[c&&"Committing...",!c&&p&&"Success",!c&&!p&&"Commit"]})]})]})}var fu=(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))(fu||{});const Fe=fu,Bw=[Fe.SUM,Fe.ABS_SUM,Fe.MIN,Fe.MAX,Fe.VAR,Fe.AVG,Fe.STD,Fe.FIRST,Fe.LAST,Fe.COUNT_DISTINCT,Fe.DISTINCT,Fe.COUNT,Fe.UNIQUE],Vw=c=>{switch(c){default:return!1}},$w=(c,e)=>{switch(c){case Fe.COUNT:case Fe.FIRST:case Fe.LAST:case Fe.COUNT_DISTINCT:case Fe.DISTINCT:case Fe.UNIQUE:return!0;case Fe.MIN:case Fe.MAX:return F.isNumberType(e)||F.isDateType(e)||F.isTextType(e);case Fe.SUM:case Fe.ABS_SUM:case Fe.VAR:case Fe.AVG:case Fe.STD:return F.isNumberType(e);case Fe.SKIP:return!1}},_r=(c,e)=>c.filter(t=>$w(e,t.type)),Ww=(c,e,t,n)=>_r(c,e).map(({name:s})=>s).filter(s=>t.includes(s)?!n:n),ps={isRollupOperation:Vw,filterValidColumns:_r,getOperationColumnNames:Ww};var Cu=(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))(Cu||{});const Ri=Cu,Gw=Object.freeze([[Ri.FILTER_CONTROL_CHANGE_CLEARS_ALL_FILTERS,!1],[Ri.LINK_CHANGE_CLEARS_ALL_FILTERS,!1]]),Su={DEFAULTS:Gw},zw=J.module("ColumnHeaderGroup");function Ta(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=ce(e=>{const t=this.childIndexes.flat(),n=O.getVisibleIndexes(t,e),s=Math.min(...n),i=Math.max(...n);return i-s!==t.length-1&&zw.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 ji=J.module("IrisGridUtils");function os(c,e){return c>=0&&c<e.length}function Kw(c){return c.asDate!=null}class Be{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=Be.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(f=>f===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 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?Be.getColumnByName(l,i):void 0,advancedSettings:new Map([...Su.DEFAULTS,...o])}}static dehydrateQuickFilters(e){return[...e].map(([t,n])=>{const{text:s}=n;return[t,{text:s}]})}static dehydrateLong(e){return e!=null?`${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 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 getInputFiltersForColumns(e,t=[]){return t.filter(({name:n,type:s})=>e.find(({name:i,type:o})=>i===n&&o===s))}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=Be.parseCustomColumnNames(e),s=Be.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=O.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=O.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=O.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=O.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=Be.getVisibleColumnsInRange(e,t,n,s,i),d=a.length*l,h=Be.getPrevVisibleColumns(e,t-1,d,s,i),u=Be.getNextVisibleColumns(e,n+1,d,s,i),m=[...h,...a,...u];return Be.getColumnsToFetch(e,m,o)}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];D(i.startColumn),D(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})=>ps.isRollupOperation(u)?[]:ps.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[Fe.FIRST]??[];h[Fe.FIRST]=[...m,...u]}}return{groupingColumns:s,includeConstituents:i,includeDescriptions:l,aggregations:h}}static getPendingErrors(e){e.forEach((t,n)=>{if(!Be.isValidIndex(n))throw new Error(`Invalid rowIndex ${n}`);const{data:s}=t;s.forEach((i,o)=>{if(!Be.isValidIndex(o))throw new Error(`Invalid columnIndex ${o}`)})})}static getColumn(e,t){return t<e.length?e[t]:(ji.error("Unable to retrieve column",t,">=",e.length),null)}static getColumnByName(e,t){const n=e.find(({name:s})=>s===t);return n==null&&ji.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 f=1;u.children.forEach(S=>{if(a.has(S))throw new Error(`Column group child ${S} specified in multiple groups`);a.add(S);const b=l.get(S),w=e.getColumnIndexByName(S);if(b){const T=d(b);p.push(...T.childIndexes),f=Math.max(f,T.depth+1)}else if(w!=null)p.push(w),f=Math.max(f,1);else throw new Error(`Unknown child ${S} in group ${m}`)});const C=new dn({...u,depth:f,childIndexes:p.flat()});return i.set(m,C),u.children.forEach(S=>s.set(S,C)),n=Math.max(n,C.depth+1),C},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)&&Kw(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}`}dh;tableUtils;constructor(e){this.dh=e,this.tableUtils=new F(e)}dehydrateIrisGridState(e,t){const{aggregationSettings:n={aggregations:Ie,showOnTop:!1},advancedFilters:s,customColumnFormatMap:i,isFilterBarShown:o,metrics:l,quickFilters:a,customColumns:d,conditionalFormats:h=Ie,reverseType:u,rollupConfig:m=void 0,showSearchBar:g,searchValue:p,selectDistinctColumns:f=Ie,selectedSearchColumns:C,sorts:S,invertSearchColumns:b,pendingDataMap:w=jn,frozenColumns:T,columnHeaderGroups:E}=t;D(l);const{userColumnWidths:y,userRowHeights:R}=l,{columns:I}=e;return{advancedFilters:this.dehydrateAdvancedFilters(I,s),aggregationSettings:n,customColumnFormatMap:[...i],isFilterBarShown:o,quickFilters:Be.dehydrateQuickFilters(a),sorts:Be.dehydrateSort(S),userColumnWidths:[...y].filter(([x])=>x!=null&&x>=0&&x<I.length).map(([x,A])=>[I[x].name,A]),userRowHeights:[...R],customColumns:[...d],conditionalFormats:[...h],reverseType:u,rollupConfig:m,showSearchBar:g,searchValue:p,selectDistinctColumns:[...f],selectedSearchColumns:C,invertSearchColumns:b,pendingDataMap:this.dehydratePendingDataMap(I,w),frozenColumns:T,columnHeaderGroups:E?.map(x=>({name:x.name,children:x.children,color:x.color}))}}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:f,searchValue:C,selectDistinctColumns:S,selectedSearchColumns:b,invertSearchColumns:w=!0,pendingDataMap:T=[],frozenColumns:E,columnHeaderGroups:y}=t,{columns:R,formatter:I}=e;return{advancedFilters:this.hydrateAdvancedFilters(R,n,I.timeZone),aggregationSettings:s,customColumnFormatMap:new Map(i),isFilterBarShown:o,quickFilters:this.hydrateQuickFilters(R,l,I.timeZone),sorts:this.hydrateSort(R,a),userColumnWidths:new Map(u.map(([x,A])=>typeof x=="string"||x instanceof String?[R.findIndex(({name:k})=>k===x),A]:[x,A]).filter(([x])=>x!=null&&x>=0&&x<R.length)),customColumns:d,conditionalFormats:h,userRowHeights:new Map(m),reverseType:g,rollupConfig:p,showSearchBar:f,searchValue:C,selectDistinctColumns:S,selectedSearchColumns:b,invertSearchColumns:w,pendingDataMap:this.hydratePendingDataMap(R,T),frozenColumns:E,columnHeaderGroups:Be.parseColumnHeaderGroups(e,y??e.layoutHints?.columnGroups??[]).groups}}hydrateQuickFilters(e,t,n){const s=t.map(([i,o])=>{const{text:l}=o;let a=null;try{const d=Be.getColumn(e,i);d!=null&&(a=this.tableUtils.makeQuickFilter(d,l,n))}catch(d){ji.error("hydrateQuickFilters error with",l,d)}return[i,{text:l,filter:a}]});return new Map(s)}dehydrateAdvancedFilters(e,t){return[...t].map(([n,s])=>{const i=Be.getColumn(e,n);D(i);const o=this.dehydrateAdvancedFilterOptions(i,s.options);return[n,{options:o}]})}hydrateAdvancedFilters(e,t,n){const s=t.map(([i,o])=>{const l=Be.getColumn(e,i);D(l);const a=this.hydrateAdvancedFilterOptions(l,o.options);let d=null;try{Be.getColumn(e,i)!=null&&(d=this.tableUtils.makeAdvancedFilter(l,a,n))}catch(h){ji.error("hydrateAdvancedFilters error with",a,h)}return[i,{options:a,filter:d}]});return new Map(s)}dehydrateAdvancedFilterOptions(e,t){const{selectedValues:n,...s}=t;return{selectedValues:n?.map(i=>this.dehydrateValue(i,e?.type)),...s}}hydrateAdvancedFilterOptions(e,t){const{selectedValues:n,...s}=t;return{selectedValues:n?.map(i=>this.hydrateValue(i,e?.type)),...s}}dehydratePendingDataMap(e,t){return[...t].map(([n,{data:s}])=>[n,{data:[...s].map(([i,o])=>[e[i].name,this.dehydrateValue(o,e[i].type)])}])}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 D(d),[s(l)??null,this.hydrateValue(a,e[d].type)]}))}]))}dehydrateValue(e,t){return F.isDateType(t)?this.dehydrateDateTime(e):F.isLongType(t)?Be.dehydrateLong(e):e}hydrateValue(e,t){return F.isDateType(t)?this.hydrateDateTime(e):F.isLongType(t)?this.hydrateLong(e):e}dehydrateDateTime(e){return e!=null?this.dh.i18n.DateTimeFormat.format(Zs.FULL_DATE_FORMAT,e):null}hydrateDateTime(e){return e!=null?this.dh.i18n.DateTimeFormat.parse(Zs.FULL_DATE_FORMAT,e):null}hydrateLong(e){return e!=null?this.dh.LongWrapper.ofString(e):null}hydrateSort(e,t){const{dh:n}=this;return t.map(s=>{const{column:i,isAbs:o,direction:l}=s;if(l===F.sortDirection.reverse)return n.Table.reverse();const a=typeof i=="string"?Be.getColumnByName(e,i):Be.getColumn(e,i);if(a!=null){let d=a.sort();return o&&(d=d.abs()),l===F.sortDirection.descending?d=d.desc():d=d.asc(),d}return null}).filter(s=>s!=null&&s.direction!==F.sortDirection.reverse)}applyTableSettings(e,t,n){const{columns:s}=e;let i=[];t.quickFilters&&(i=Be.getFiltersFromFilterMap(this.hydrateQuickFilters(s,t.quickFilters,n)));let o=[];t.advancedFilters&&(o=Be.getFiltersFromFilterMap(this.hydrateAdvancedFilters(s,t.advancedFilters,n)));const l=this.getFiltersFromInputFilters(s,t.inputFilters,n);let a=[];t.sorts&&(a=this.hydrateSort(s,t.sorts));let d=[...i,...o];const{partition:h,partitionColumn:u}=t;if(h!=null&&u!=null){const m=Be.getColumnByName(s,u);m&&(d=[m.filter().eq(this.dh.FilterValue.ofString(h)),...d])}d=[...l,...d],e.applyFilter(d),e.applySort(a)}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 this.tableUtils.makeQuickFilter(l,o,n)}catch(a){ji.debug("Unable to create input filter",a)}return null}).filter(s=>s!=null)}rangeSetFromRanges(e){const{dh:t}=this,n=e.slice().sort((s,i)=>(D(s.startRow),D(i.startRow),s.startRow-i.startRow)).map(s=>{const{startRow:i,endRow:o}=s;return D(i),D(o),t.RangeSet.ofRange(i,o)});return t.RangeSet.ofRanges(n)}}const Ce=Be;const Lt=J.module("IrisGridCopyHandler");class De 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 De.COPY_STATES.CONFIRMATION_REQUIRED:return`Are you sure you want to copy ${t.toLocaleString()} rows to your clipboard?`;case De.COPY_STATES.CLICK_REQUIRED:return`Fetched ${t.toLocaleString()} rows!`;case De.COPY_STATES.FETCH_ERROR:return"Unable to copy data.";case De.COPY_STATES.FETCH_IN_PROGRESS:return`Fetching ${t.toLocaleString()} rows for clipboard...`;case De.COPY_STATES.DONE:return"Copied to Clipboard!";default:return""}}static getCopyButtonText(e){switch(e){case De.BUTTON_STATES.FETCH_IN_PROGRESS:return"Fetching";case De.BUTTON_STATES.CLICK_TO_COPY:return"Click to Copy";case De.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:De.COPY_STATES.IDLE,buttonState:De.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(){Lt.debug2("startCopy"),this.stopCopy();const{copyOperation:e}=this.props;if(e==null){Lt.debug2("No copy operation set, cancelling out"),this.setState({isShown:!1});return}const{ranges:t,error:n}=e;if(n!=null){Lt.debug("Showing copy error",n),this.setState({isShown:!0,copyState:De.COPY_STATES.DONE,error:n}),this.startHideTimer();return}const s=Q.rowCount(t);this.setState({rowCount:s,isShown:!0,error:void 0}),s>De.NO_PROMPT_THRESHOLD?this.setState({buttonState:De.BUTTON_STATES.COPY,copyState:De.COPY_STATES.CONFIRMATION_REQUIRED}):this.startFetch()}stopCopy(){this.textData=void 0,this.stopFetch(),this.stopHideTimer()}handleBackgroundClick(){Lt.debug2("handleBackgroundClick");const{copyState:e}=this.state;e===De.COPY_STATES.DONE&&this.setState({isShown:!1})}handleCancelClick(){Lt.debug2("handleCancelClick"),this.stopFetch(),this.setState({isShown:!1})}handleCopyClick(){Lt.debug2("handleCopyClick"),this.textData!=null?this.copyText(this.textData):this.startFetch()}handleHideTimeout(){Lt.debug2("handleHideTimeout"),this.stopHideTimer(),this.setState({isShown:!1})}copyText(e){Lt.debug2("copyText",e),this.textData=e,co(e).then(()=>{this.setState({copyState:De.COPY_STATES.DONE}),this.startHideTimer()},t=>{Lt.error("copyText error",t),this.setState({buttonState:De.BUTTON_STATES.CLICK_TO_COPY,copyState:De.COPY_STATES.CLICK_REQUIRED})})}startFetch(){this.stopFetch(),this.setState({buttonState:De.BUTTON_STATES.FETCH_IN_PROGRESS,copyState:De.COPY_STATES.FETCH_IN_PROGRESS});const{model:e,copyOperation:t}=this.props,{ranges:n,includeHeaders:s,userColumnWidths:i,movedColumns:o,formatValues:l}=t;Lt.debug("startFetch",n);const a=Ce.getHiddenColumns(i);let d=O.getModelRanges(n,o);if(a.length>0){const u=a.map(Q.makeColumn);d=Q.subtractRangesFromRanges(d,u)}const h=l!=null&&l?(u,m)=>e.displayString(u,m.type,m.name):u=>`${u}`;this.fetchPromise=be.makeCancelable(e.textSnapshot(d,s,h)),this.fetchPromise.then(u=>{this.fetchPromise=void 0,this.copyText(u)}).catch(u=>{u instanceof Pl?Lt.debug("User cancelled copy."):(Lt.error("Error fetching contents",u),this.fetchPromise=void 0,this.setState({buttonState:De.BUTTON_STATES.RETRY,copyState:De.COPY_STATES.FETCH_ERROR}))})}stopFetch(){this.fetchPromise&&(Lt.debug2("stopFetch"),this.fetchPromise.cancel(),this.fetchPromise=void 0)}startHideTimer(){this.stopHideTimer(),this.hideTimer=setTimeout(this.handleHideTimeout,De.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===De.COPY_STATES.DONE?"fade":"copy-slide-up",u=De.getCopyButtonText(i),m=d??De.getStatusMessageText(o,a),g=o!==De.COPY_STATES.DONE,p=i===De.BUTTON_STATES.FETCH_IN_PROGRESS,f=o===De.COPY_STATES.DONE;return r.jsxs(na,{animation:h,isShown:l,className:z("iris-grid-copy-handler",{"copy-done":f}),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(Vt,{in:g,timeout:Ye.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(P,{kind:p?"tertiary":"primary",className:z("btn-copy",{"btn-spinner":p}),onClick:this.handleCopyClick,disabled:p,children:[p&&r.jsx(Nn,{}),u]})]})})]})}}const Yw=De;class qw 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=We(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=We(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:z("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(P,{kind:"ghost",className:z("btn-link-icon advanced-filter-button",{"filter-set":n}),onClick:s,onContextMenu:this.handleContextMenu,children:r.jsxs("div",{className:"fa-layers ",children:[r.jsx(X,{icon:rr,className:"filter-solid"}),r.jsx(X,{icon:rl,className:"filter-light"})]})})})]})}}const Xw=qw;class Zw extends Js{irisGrid;constructor(e){super(),this.irisGrid=e}onDown(e){const{selectedRanges:t}=this.irisGrid.state;return e.key==="c"&&ws.isModifierKeyDown(e)?(Ce.isValidSnapshotRanges(t)?this.irisGrid.copyRanges(t):this.irisGrid.copyRanges(t,!1,!1,"Invalid copy ranges"),!0):!1}}const Qw=Zw,Jw={TOGGLE_QUICK_FILTER:He.createAndAdd({id:"TABLE.TOGGLE_QUICK_FILTER",name:"Toggle Quick Filter",shortcut:[fe.CTRL,ve.F],macShortcut:[fe.CMD,ve.F]}),CLEAR_ALL_FILTERS:He.createAndAdd({id:"TABLE.CLEAR_ALL_FILTERS",name:"Clear All Table Filters",shortcut:[fe.CTRL,ve.E],macShortcut:[fe.CMD,ve.E]}),CLEAR_FILTERS:He.createAndAdd({id:"TABLE.CLEAR_FILTERS",name:"Clear Active Table Filters",shortcut:[fe.CTRL,fe.SHIFT,ve.E],macShortcut:[fe.CMD,fe.SHIFT,ve.E]}),REVERSE:He.createAndAdd({id:"TABLE.REVERSE",name:"Reverse",shortcut:[fe.CTRL,ve.I],macShortcut:[fe.CMD,ve.I]}),TOGGLE_SEARCH:He.createAndAdd({id:"TABLE.TOGGLE_SEARCH",name:"Toggle Search",shortcut:[fe.CTRL,fe.SHIFT,ve.F],macShortcut:[fe.CMD,fe.SHIFT,ve.F]}),GOTO_ROW:He.createAndAdd({id:"TABLE.GOTO_ROW",name:"Go to Row",shortcut:[fe.CTRL,ve.G],macShortcut:[fe.CMD,ve.G]})},ev={COMMIT:He.createAndAdd({id:"INPUT_TABLE.COMMIT",name:"Commit",shortcut:[fe.CTRL,ve.S],macShortcut:[fe.CMD,ve.S]}),DISCARD:He.createAndAdd({id:"INPUT_TABLE.DISCARD",name:"Discard",shortcut:[fe.CTRL,fe.ALT,ve.S],macShortcut:[fe.CMD,fe.OPTION,ve.S]})},tv={TABLE:Jw,INPUT_TABLE:ev},Ht=tv;class nv extends Js{irisGrid;constructor(e){super(),this.irisGrid=e}onDown(e){if(Ht.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 sv=nv;class iv extends Js{irisGrid;constructor(e){super(),this.irisGrid=e}onDown(e){return Ht.TABLE.CLEAR_FILTERS.matchesEvent(e)?(this.irisGrid.clearAllFilters(),!0):!1}}const ov=iv;class lv extends ot{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:f,width:C,height:S}=i.getCellOverflowButtonPosition(g);return p==null||C==null||f==null||S==null?null:{left:p,top:f,width:C,height:S}}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,f=d.getTheme(),C={context:p,mouseX:t,mouseY:n,metrics:m,model:g,theme:f};return a.shouldRenderOverflowButton(C)&&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);Ze(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 av=lv;class rv extends ot{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 dv=rv;class cv extends ot{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 hv=cv;class Pr extends v.Component{static defaultProps={formatString:"",forwardedProps:{menuItem:{},closeMenu(e){},iconElement:null},placeholder:"",title:"",onChange(e){}};constructor(e=Pr.defaultProps){super(e),this.handleInputChange=this.handleInputChange.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.inputRef=oe.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=fp.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(Je,{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 uv=Pr;class mv{static isDefaultSelected(e){return!e||![tl.TYPE_CONTEXT_CUSTOM,tl.TYPE_CONTEXT_PRESET].includes(e.type)}static isCustomSelected(e){return e!=null&&e.type===tl.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(uv,{formatString:e.formatString,title:e.label,placeholder:n,onChange:i})}}}const Ut=mv;class on{static dateGroup=10;static timeGroup=20;static dateTimeGroup=30;static getOptions(e,t){const n=new Date,i=[{group:on.dateGroup,formatString:"yyyy-MM-dd"},{group:on.dateGroup,formatString:"MM-dd-yyyy"},{group:on.timeGroup,formatString:"HH:mm:ss"},{group:on.timeGroup,formatString:"HH:mm:ss.SSS"},{group:on.timeGroup,formatString:"HH:mm:ss.SSSSSSSSS"},{group:on.dateTimeGroup,formatString:"yyyy-MM-dd HH:mm:ss"},{group:on.dateTimeGroup,formatString:"yyyy-MM-dd HH:mm:ss.SSS"},{group:on.dateTimeGroup,formatString:"yyyy-MM-dd HH:mm:ss.SSSSSSSSS"}].map(l=>{const a=it.makeFormat("",l.formatString,it.TYPE_CONTEXT_PRESET),d=e.getFormattedString(n,F.dataType.DATETIME,"",a);return Ut.makeOption(d,a,l.group,it.isSameFormat(a,t))});return[Ut.makeOption("Default",null,on.dateGroup,Ut.isDefaultSelected(t)),...i]}}const gv=on;class ln{static defaultGroup=10;static presetGroup=20;static presetRoundGroup=30;static customGroup=40;static getOptions(e,t,n){const s=[{format:$e.FORMAT_PERCENT,group:ln.presetGroup},{format:$e.FORMAT_BASIS_POINTS,group:ln.presetGroup},{format:$e.FORMAT_MILLIONS,group:ln.presetGroup},{format:$e.FORMAT_SCIENTIFIC_NOTATION,group:ln.presetGroup},{format:$e.FORMAT_ROUND,group:ln.presetRoundGroup},{format:$e.FORMAT_ROUND_TWO_DECIMALS,group:ln.presetRoundGroup},{format:$e.FORMAT_ROUND_FOUR_DECIMALS,group:ln.presetRoundGroup}],i=Ut.makeOption("Default",null,ln.defaultGroup,Ut.isDefaultSelected(t)),o=s.map(h=>Ut.makeOption(h.format.label,h.format,h.group,$e.isSameFormat(h.format,t))),l=Ut.isCustomSelected(t),a=l?t:$e.makeCustomFormat(),d=Ut.makeCustomFormatOption(a,ln.customGroup,$e.DEFAULT_FORMAT_STRING,l,h=>{if(h!=null){const u=$e.makeCustomFormat(h);$e.isValid(e,u)&&n(u)}else n(null)});return[i,...o,d]}}const pv=ln;class gi{static defaultGroup=10;static presetGroup=20;static customGroup=30;static getOptions(e,t,n){const s=[{format:st.FORMAT_MILLIONS,group:gi.presetGroup},{format:st.FORMAT_SCIENTIFIC_NOTATION,group:gi.presetGroup}],i=Ut.makeOption("Default",null,gi.defaultGroup,Ut.isDefaultSelected(t)),o=s.map(h=>Ut.makeOption(h.format.label,h.format,h.group,st.isSameFormat(h.format,t))),l=Ut.isCustomSelected(t),a=l?t:st.makeCustomFormat(),d=Ut.makeCustomFormatOption(a,gi.customGroup,st.DEFAULT_FORMAT_STRING,l,h=>{if(h!=null){const u=st.makeCustomFormat(h);st.isValid(e,u)&&n(u)}else n(null)});return[i,...o,d]}}const fv=gi;const Qd=J.module("IrisGridContextMenuHandler"),Cv=150,Jd="yyyy-MM-dd HH:mm:ss.SSSSSSSSS";class Y extends ot{static GROUP_EDIT=te.groups.high+10;static GROUP_HIDE_COLUMNS=te.groups.high+25;static GROUP_FILTER=te.groups.high+50;static GROUP_EXPAND_COLLAPSE=te.groups.high+55;static GROUP_GOTO=te.groups.high+60;static GROUP_SORT=te.groups.high+75;static GROUP_COPY=te.groups.high+100;static GROUP_FORMAT=te.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 getRowOptionFormatted(e,t,n=30){return`${e} "${Nt.truncate(t,n-e.length-3)}"`}irisGrid;debouncedUpdateCustomFormat;constructor(e,t){super(),this.debouncedUpdateCustomFormat=We(e.handleFormatSelection,Cv),this.dh=t,this.irisGrid=e}componentWillUnmount(){this.debouncedUpdateCustomFormat.flush()}dh;getHeaderActions(e,t){const{irisGrid:n}=this,{column:s}=t;D(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();D(d);const{filterIconColor:f,filterBarActiveColor:C,contextMenuSortIconColor:S,contextMenuReverseIconColor:b}=p,w=i.sort,T=F.getSortForColumn(w,l.name),E=h!==F.REVERSE_TYPE.NONE,{userColumnWidths:y}=d,R=[...y.values()].some(A=>A===0),I=i.getColumnHeaderParentGroup(e,0)===void 0&&!(Pe(i)&&i.hasExpandableRows),x=i.isColumnFrozen(e);return a.push({title:"Hide Column",group:Y.GROUP_HIDE_COLUMNS,action:()=>{this.irisGrid.hideColumnByVisibleIndex(s)}}),a.push({title:x?"Unfreeze Column":"Freeze Column",group:Y.GROUP_HIDE_COLUMNS,disabled:!I,action:()=>{x?this.irisGrid.unFreezeColumnByColumnName(l.name):this.irisGrid.freezeColumnByColumnName(l.name)},order:10}),a.push({title:"Show All Columns",group:Y.GROUP_HIDE_COLUMNS,action:()=>{this.irisGrid.showAllColumns()},disabled:!R}),a.push({title:"Quick Filters",icon:On,iconColor:C,shortcut:Ht.TABLE.TOGGLE_QUICK_FILTER,group:Y.GROUP_FILTER,order:10,action:()=>{this.irisGrid.toggleFilterBar(s)}}),a.push({title:"Advanced Filters",icon:m.get(e)?rr:rl,iconColor:f,group:Y.GROUP_FILTER,order:20,action:()=>{this.irisGrid.handleAdvancedMenuOpened(s)}}),a.push({title:"Clear Table Filters",group:Y.GROUP_FILTER,order:40,shortcut:Ht.TABLE.CLEAR_FILTERS,action:()=>{this.irisGrid.clearAllFilters()},disabled:!(u.size>0||m.size>0||g!=null)}),a.push({title:"Sort by",icon:On,iconColor:S,group:Y.GROUP_SORT,order:10,actions:this.sortByActions(l,e,T)}),a.push({title:"Add Additional Sort",disabled:T&&w.length===1||E&&w.length===1||T&&E&&w.length===2||w.length===0,group:Y.GROUP_SORT,order:20,actions:this.additionalSortActions(l,e)}),a.push({title:"Clear Table Sorting",disabled:w.length===0||E&&w.length===1,group:Y.GROUP_SORT,action:()=>{this.irisGrid.sortColumn(s,Y.COLUMN_SORT_DIRECTION.none)},order:30}),a.push({title:h===F.REVERSE_TYPE.NONE?"Reverse Table":"Clear Reverse Table",icon:On,iconColor:b,group:Y.GROUP_SORT,order:40,disabled:!i.isReversible,shortcut:Ht.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:Y.GROUP_COPY,action:()=>{co(i.textForColumnHeader(e)??"").catch(A=>Qd.error("Unable to copy header",A))}}),F.isDateType(l.type)?a.push({title:"Date/Time Format",group:Y.GROUP_FORMAT,actions:this.dateFormatActions(l)}):F.isNumberType(l.type)&&a.push({title:"Number Format",group:Y.GROUP_FORMAT,actions:this.numberFormatActions(l)??void 0}),a}getCellActions(e,t,n){D(e);const{dh:s,irisGrid:i}=this,{column:o,row:l}=n,{model:a,canCopy:d}=i.props,{columns:h}=a,u=i.getModelRow(l);D(u);const m=a.valueForCell(e,u),g=a.textForCell(e,u),p=h[e],f=[],{quickFilters:C}=i.state,S=i.getTheme(),{filterIconColor:b}=S,{settings:w}=i.props,T=new it(s,{timeZone:w?.timeZone,showTimeZone:!1,showTSeparator:!0,defaultDateTimeFormatString:Jd}),E=new it(s,{timeZone:w?.timeZone,showTimeZone:w?.showTimeZone,showTSeparator:w?.showTSeparator,defaultDateTimeFormatString:Jd});if(p==null||l==null)return f;if(a.isFilterable(e)){const R={title:"Filter by Value",icon:On,iconColor:b,group:Y.GROUP_FILTER,order:10,actions:[]};if(m==null)C.get(e)&&R.actions.push({title:"And",actions:this.nullFilterActions(p,C.get(e),"&&"),order:2,group:te.groups.high}),R.actions.push(...this.nullFilterActions(p));else if(F.isBooleanType(p.type))C.get(e)&&R.actions.push({title:"Or",actions:this.booleanFilterActions(p,g,C.get(e),"||"),order:2,group:te.groups.high}),R.actions.push(...this.booleanFilterActions(p,g));else if(F.isNumberType(p.type)||F.isCharType(p.type)){D(e);const I=F.isCharType(p.type)?String.fromCharCode(m):`${m}`;C.get(e)&&R.actions.push({title:"And",actions:this.numberFilterActions(p,I,m,C.get(e),"&&"),order:2,group:te.groups.high}),R.actions.push(...this.numberFilterActions(p,I,m,C.get(e)))}else if(F.isDateType(p.type)){const I=T.format(m),x=E.format(m);C.get(e)&&R.actions.push({title:"And",actions:this.dateFilterActions(p,I,x,m,C.get(e),"&&"),order:2,group:te.groups.high}),R.actions.push(...this.dateFilterActions(p,I,x,m,C.get(e)))}else C.get(e)&&R.actions.push({title:"And",actions:this.stringFilterActions(p,g,m,C.get(e),"&&"),order:2,group:te.groups.high}),R.actions.push(...this.stringFilterActions(p,g,m));R.actions!=null&&R.actions.length>0&&f.push(R)}if(Pe(a)&&a.isRowExpandable(u)){const R=a.groupedColumns.length>0?a.depthForRow(u)-1:0,x=a.valueForCell(R,u)==null?"null":a.textForCell(R,u);f.push({title:Y.getRowOptionFormatted(a.isRowExpanded(u)?"Collapse":"Expand",x),group:Y.GROUP_EXPAND_COLLAPSE,order:10,action:()=>{a.setRowExpanded(u,!a.isRowExpanded(u))}}),a.isExpandAllAvailable===!0&&f.push({title:Y.getRowOptionFormatted("Expand All in",x),group:Y.GROUP_EXPAND_COLLAPSE,order:20,action:()=>{a.setRowExpanded(u,!0,!0)}})}Pe(a)&&a.hasExpandableRows&&a.isExpandAllAvailable===!0&&(f.push({title:"Expand Entire Table",group:Y.GROUP_EXPAND_COLLAPSE,order:30,action:()=>{a.expandAll()}}),f.push({title:"Collapse Entire Table",group:Y.GROUP_EXPAND_COLLAPSE,order:40,action:()=>{a.collapseAll()}}));const y={title:"Go to",iconColor:b,shortcut:Ht.TABLE.GOTO_ROW,group:Y.GROUP_GOTO,order:10,action:()=>this.irisGrid.toggleGotoRow(`${l+1}`,`${m}`,p.name)};return f.push(y),d&&(f.push({title:"Copy Cell",group:Y.GROUP_COPY,order:10,action:()=>{i.copyCell(o,l)}}),f.push({title:"Copy Cell Unformatted",group:Y.GROUP_COPY,order:20,action:()=>{i.copyCell(o,l,!0)}})),f}getNumberValueEqualsFilter(e,t){const{dh:n}=this,s=e.filter();if(t===Number.POSITIVE_INFINITY)return n.FilterCondition.invoke("isInf",s).and(s.greaterThan(n.FilterValue.ofNumber(0)));if(t===Number.NEGATIVE_INFINITY)return n.FilterCondition.invoke("isInf",s).and(s.lessThan(n.FilterValue.ofNumber(0)));if(Number.isNaN(t))return n.FilterCondition.invoke("isNaN",s);const i=this.getFilterValueForNumberOrChar(e.type,t);return s.eq(i)}getFilterValueForNumberOrChar(e,t){const{dh:n}=this;return F.isCharType(e)?n.FilterValue.ofString(String.fromCharCode(t)):n.FilterValue.ofNumber(t)}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:f,quickFilters:C,advancedFilters:S,selectedRanges:b}=s.state;D(p);const{columnHeaderHeight:w,gridY:T,columnHeaderMaxDepth:E}=p,y=[];if(d!=null&&h!=null){const R=u.valueForCell(d,h),I=u.textForCell(d,h),x=g[d],{onContextMenu:A}=s.props;x!=null&&y.push(A({model:u,value:R,valueText:I,column:x,rowIndex:l,columnIndex:o,modelRow:h,modelColumn:d}))}return d!=null&&u.isFilterable(d)&&y.push({title:"Clear Column Filter",group:Y.GROUP_FILTER,order:30,action:()=>{this.irisGrid.removeColumnFilter(d)},disabled:!(C.has(d)||S.has(d))}),(f?i<=T:i<=w*E&&a===0)?d!=null&&y.push(...this.getHeaderActions(d,e)):(d!=null&&h!=null&&y.push(...this.getCellActions(d,t,e)),m&&b.length>0&&(y.push({title:"Copy Selection",shortcut:Yn.COPY,group:Y.GROUP_COPY,order:30,action:()=>{s.copyRanges(b)}}),y.push({title:"Copy Selection w/ Headers",group:Y.GROUP_COPY,order:40,action:()=>{s.copyRanges(b,!0)}})),ze(u)&&u.isEditable&&b.length>0&&y.push({title:"Delete Selected Rows",group:Y.GROUP_EDIT,order:50,action:()=>{this.irisGrid.deleteRanges(b)}})),y.length===0?!1:(D(s.gridWrapper),te.triggerMenu(s.gridWrapper,n.clientX,n.clientY,y),!0)}dateFormatActions(e){const{model:t}=this.irisGrid.props,{formatter:n}=t,s=n.getColumnFormat(e.type,e.name),i=gv.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?Kn:void 0,group:h,order:l,action:()=>{const g=t.getColumnIndexByName(e.name);D(g),this.irisGrid.handleFormatSelection(g,d)}})}return o}numberFormatActions(e){const{model:t}=this.irisGrid.props,{formatter:n}=t,{dh:s}=this,i=n.getColumnFormat(e.type,e.name);let o;const l=t.getColumnIndexByName(e.name);if(F.isDecimalType(e.type))o=pv.getOptions(s,i,d=>{D(l),this.debouncedUpdateCustomFormat(l,d)});else if(F.isIntegerType(e.type))o=fv.getOptions(s,i,d=>{D(l),this.debouncedUpdateCustomFormat(l,d)});else return Qd.error("Invalid column type in numberFormatActions"),null;const a=[];for(let d=0;d<o.length;d+=1){const{format:h,isSelected:u}=o[d];a.push({...o[d],icon:u?Kn:void 0,order:d,action:()=>{l===void 0&&h&&h.type===tl.TYPE_CONTEXT_CUSTOM||(D(l),this.irisGrid.handleFormatSelection(l,h))}})}return a}stringFilterActions(e,t,n,s,i){const{dh:o}=this,l=o.FilterValue.ofString(n);let a=s;a||(a={filter:null,text:null});const{filter:d,text:h}=a,u=[],{model:m}=this.irisGrid.props,g=m.getColumnIndexByName(e.name);return D(g),u.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[i?Y.getOperatorAsText(i):""," ",'"',t,'"']}),order:1,group:te.groups.high}),u.push({title:"text is exactly",description:`Show only rows where ${e.name} is ${n} (case sensitive)`,action:()=>{this.irisGrid.setQuickFilter(g,Y.getQuickFilterCondition(d,e.filter().eq(l),i),Y.getQuickFilterText(h,`=${t}`,i))},order:10,group:te.groups.low}),u.push({title:"text is not exactly",description:`Show only rows where ${e.name} is not ${t} (case sensitive)`,action:()=>{this.irisGrid.setQuickFilter(g,Y.getQuickFilterCondition(d,e.filter().notEq(l),i),Y.getQuickFilterText(h,`!=${t}`,i))},order:20,group:te.groups.low}),u.push({title:"text contains",description:`Show only rows where ${e.name} contains ${t}`,action:()=>{this.irisGrid.setQuickFilter(g,Y.getQuickFilterCondition(d,e.filter().contains(l),i),Y.getQuickFilterText(h,`~${t}`,i))},order:30,group:te.groups.low}),u.push({title:"text does not contain",description:`Show only rows where ${e.name} does not contain ${n}`,action:()=>{this.irisGrid.setQuickFilter(g,Y.getQuickFilterCondition(d,e.filter().contains(l).not(),i),Y.getQuickFilterText(h,`!~${t}`,i))},order:40,group:te.groups.low}),u.push({title:"text starts with",description:`Show only rows where ${e.name} starts with ${t}`,action:()=>{this.irisGrid.setQuickFilter(g,Y.getQuickFilterCondition(d,e.filter().invoke("startsWith",l),i),Y.getQuickFilterText(h,`${t}*`,i))},order:50,group:te.groups.low}),u.push({title:"text ends with",description:`Show only rows where ${e.name} ends with ${t}`,action:()=>{this.irisGrid.setQuickFilter(g,Y.getQuickFilterCondition(d,e.filter().invoke("endsWith",l),i),Y.getQuickFilterText(h,`*${t}`,i))},order:60,group:te.groups.low}),u}numberFilterActions(e,t,n,s,i){const o=this.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 D(m),d.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[i?Y.getOperatorAsText(i):""," ",'"',t,'"']}),order:1,group:te.groups.high}),d.push({title:"is equal to",description:`Show only rows where ${e.name} is ${t}`,action:()=>{const g=this.getNumberValueEqualsFilter(e,n);this.irisGrid.setQuickFilter(m,Y.getQuickFilterCondition(l,g,i),Y.getQuickFilterText(a,`=${t}`,i))},order:10,group:te.groups.low}),d.push({title:"is not equal to",description:`Show only rows where ${e.name} is not ${t}`,action:()=>{const g=this.getNumberValueEqualsFilter(e,n).not();this.irisGrid.setQuickFilter(m,Y.getQuickFilterCondition(l,g,i),Y.getQuickFilterText(a,`!=${t}`,i))},order:20,group:te.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,Y.getQuickFilterCondition(l,e.filter().greaterThan(o),i),Y.getQuickFilterText(a,`>${t}`,i))},order:30,group:te.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,Y.getQuickFilterCondition(l,e.filter().greaterThanOrEqualTo(o),i),Y.getQuickFilterText(a,`>=${t}`,i))},order:40,group:te.groups.low}),d.push({title:"less than",description:`Show only rows where ${e.name} is less than ${t}`,action:()=>{this.irisGrid.setQuickFilter(m,Y.getQuickFilterCondition(l,e.filter().lessThan(o),i),Y.getQuickFilterText(a,`<${t}`,i))},order:50,group:te.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,Y.getQuickFilterCondition(l,e.filter().lessThanOrEqualTo(o),i),Y.getQuickFilterText(a,`<=${t}`,i))},order:60,group:te.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 D(d),i.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[s?Y.getOperatorAsText(s):""," ",'"',t??"null",'"']}),order:1,group:te.groups.high}),i.push({title:"true",description:`Show only rows where ${e.name} is true`,action:()=>{this.irisGrid.setQuickFilter(d,Y.getQuickFilterCondition(l,e.filter().isTrue(),s),Y.getQuickFilterText(a,"true",s))},order:10,group:te.groups.low}),i.push({title:"false",description:`Show only rows where ${e.name} is false`,action:()=>{this.irisGrid.setQuickFilter(d,Y.getQuickFilterCondition(l,e.filter().isFalse(),s),Y.getQuickFilterText(a,"false",s))},order:20,group:te.groups.low}),i.push({title:"is null",description:`Show only rows where ${e.name} is null`,action:()=>{this.irisGrid.setQuickFilter(d,Y.getQuickFilterCondition(l,e.filter().isNull(),s),Y.getQuickFilterText(a,"null",s))},order:30,group:te.groups.low}),i.push({title:"is not null",description:`Show only rows where ${e.name} is not null`,action:()=>{this.irisGrid.setQuickFilter(d,Y.getQuickFilterCondition(l,e.filter().isNull().not(),s),Y.getQuickFilterText(a,"!null",s))},order:40,group:te.groups.low}),i}dateFilterActions(e,t,n,s,i,o){const{dh:l}=this,a=l.FilterValue.ofNumber(s);let d=null,h=null;i&&(d=i.filter,h=i.text);const{model:u}=this.irisGrid.props,m=u.getColumnIndexByName(e.name);D(m);const g=[];return g.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[o?Y.getOperatorAsText(o):""," ",'"',n,'"']}),order:1,group:te.groups.high}),g.push({title:"date is",description:`Show only rows where ${e.name} is ${n}`,action:()=>{this.irisGrid.setQuickFilter(m,Y.getQuickFilterCondition(d,e.filter().eq(a),o),Y.getQuickFilterText(h,`=${t}`,o))},order:10,group:te.groups.low}),g.push({title:"date is not",description:`Show only rows where ${e.name} is not ${n}`,action:()=>{this.irisGrid.setQuickFilter(m,Y.getQuickFilterCondition(d,e.filter().notEq(a),o),Y.getQuickFilterText(h,`!=${t}`,o))},order:20,group:te.groups.low}),g.push({title:"date is before",description:`Show only rows where ${e.name} is before ${n}`,action:()=>{this.irisGrid.setQuickFilter(m,Y.getQuickFilterCondition(d,e.filter().lessThan(a),o),Y.getQuickFilterText(h,`<${t}`,o))},order:30,group:te.groups.low}),g.push({title:"date is before or equal",description:`Show only rows where ${e.name} is before or equal to ${n}`,action:()=>{this.irisGrid.setQuickFilter(m,Y.getQuickFilterCondition(d,e.filter().lessThanOrEqualTo(a),o),Y.getQuickFilterText(h,`<=${t}`,o))},order:40,group:te.groups.low}),g.push({title:"date is after",description:`Show only rows where ${e.name} is greater than ${n}`,action:()=>{this.irisGrid.setQuickFilter(m,Y.getQuickFilterCondition(d,e.filter().greaterThan(a),o),Y.getQuickFilterText(h,`>${t}`,o))},order:50,group:te.groups.low}),g.push({title:"date is after or equal",description:`Show only rows where ${e.name} is after or equal to ${n}`,action:()=>{this.irisGrid.setQuickFilter(m,Y.getQuickFilterCondition(d,e.filter().greaterThanOrEqualTo(a),o),Y.getQuickFilterText(h,`>=${t}`,o))},order:60,group:te.groups.low}),g}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 D(a),o.push({menuElement:r.jsxs("div",{className:"iris-grid-filter-menu-item-value",children:[n?Y.getOperatorAsText(n):""," ",'"null"']}),order:1,group:te.groups.high}),o.push({title:"is null",description:`Show only rows where ${e.name} is null`,action:()=>{this.irisGrid.setQuickFilter(a,Y.getQuickFilterCondition(s,e.filter().isNull(),n),Y.getQuickFilterText(i,"null",n))},order:10,group:te.groups.low}),o.push({title:"is not null",description:`Show only rows where ${e.name} is not null`,action:()=>{this.irisGrid.setQuickFilter(a,Y.getQuickFilterCondition(s,e.filter().isNull().not(),n),Y.getQuickFilterText(i,"!null",n))},order:20,group:te.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,Y.COLUMN_SORT_DIRECTION.ascending)},icon:this.checkColumnSort(n,Y.COLUMN_SORT_DIRECTION.ascending)?On:void 0,iconColor:i},{title:`${e.name} Descending`,order:20,action:()=>{this.irisGrid.sortColumn(t,Y.COLUMN_SORT_DIRECTION.descending)},icon:this.checkColumnSort(n,Y.COLUMN_SORT_DIRECTION.descending)?On:void 0,iconColor:i},{title:"Remove Sort",order:50,action:()=>{this.irisGrid.sortColumn(t,Y.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,Y.COLUMN_SORT_DIRECTION.ascending,!0)},icon:this.checkColumnSort(n,Y.COLUMN_SORT_DIRECTION.ascending,!0)?On:void 0,iconColor:i}),o.push({title:`ABS(${e.name}) Descending`,order:40,action:()=>{this.irisGrid.sortColumn(t,Y.COLUMN_SORT_DIRECTION.descending,!0)},icon:this.checkColumnSort(n,Y.COLUMN_SORT_DIRECTION.descending,!0)?On: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(X,{icon:On,style:{color:s??void 0}})}),r.jsx("span",{className:"title",children:"Add Additional Sort"}),r.jsx("span",{className:"shortcut",children:ws.isMacPlatform()?"⌘Click":"Ctrl+Click"})]}),order:1},{title:`${e.name} Ascending`,order:10,action:()=>{this.irisGrid.sortColumn(t,Y.COLUMN_SORT_DIRECTION.ascending,!1,!0)}},{title:`${e.name} Descending`,order:20,action:()=>{this.irisGrid.sortColumn(t,Y.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,Y.COLUMN_SORT_DIRECTION.ascending,!0,!0)}}),i.push({title:`ABS(${e.name}) Descending`,order:40,action:()=>{this.irisGrid.sortColumn(t,Y.COLUMN_SORT_DIRECTION.descending,!0,!0)}})),i}checkColumnSort(e,t=null,n=!1){return e?e.direction===t&&e.isAbs===n:!1}}const Sv=Y;class bv extends ot{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 wv=bv;class vv extends ot{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 Tv=vv;class Ev extends ot{irisGrid;constructor(e){super(750),this.irisGrid=e}destroyTooltip(){this.irisGrid.setState({expandCellTooltipProps:null})}setCursor(e,t){return qa.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=Pe(h)?h.depthForRow(s):null,{left:f,top:C,width:S,height:b}=i.getExpandButtonPosition(g,p);return f==null||S==null||C==null||b==null?null:{left:f,top:C,width:S,height:b}}onMove(e,t){if(qa.isInTreeBox(e,t)){const{expandCellTooltipProps:n}=this.irisGrid.state,{model:s}=this.irisGrid.props,i=this.getButtonPosition(e),{row:o}=e;D(o);const l=Pe(s)&&s.isRowExpanded(o);Ze(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 yv=Ev;class Rv extends ot{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=ws.isModifierKeyDown(n);return this.irisGrid.toggleSort(s,i),!0}return!1}}const xv=Rv;class Iv extends ot{constructor(e){super(),this.irisGrid=e}onWheel(e,t,n){const{irisGrid:s}=this,{model:i}=s.props,{metrics:o,pendingRowCount:l}=s.state;D(o);const{bottom:a,rowCount:d,rowHeight:h}=o,{deltaY:u}=O.getScrollDelta(n);return ze(i)&&i.isEditable&&a>=d-1&&u>0&&s.setState({pendingRowCount:l+Math.ceil(u/h)}),!1}}const Dv=Iv;class Fv extends ot{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}=t;if(n==null||s==null||a==null)return this.currentLinkBox=void 0,!1;if(this.currentLinkBox!=null){const{x1:u,y1:m,x2:g,y2:p}=this.currentLinkBox;if(i>=u&&i<=g&&o>=m&&o<=p)return!0}const d=t.updateRenderState(),h=l.getTokenBoxesForVisibleCell(n,s,d);for(let u=0;u<h.length;u+=1)if(bl(h[u].token)){const m=O.translateTokenBox(h[u],a),{x1:g,x2:p,y1:f,y2:C}=m;if(i>=g&&i<=p&&o>=f&&o<=C)return this.currentLinkBox=m,!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&&bl(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};Ze(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 Nv=Fv,kv=3e3;function Mv({children:c=null,onEntering:e,onEntered:t,onExiting:n,onExited:s}){const[i,o]=v.useState(!1),l=v.useRef(),a=ir(c),d=v.useCallback(()=>{o(!0),l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{o(!1)},kv)},[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(na,{className:"toast-bottom-bar",isShown:i,onEntering:e,onEntered:t,onExiting:n,onExited:s,children:c})}class Ov extends Co{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 Av=Ov,Lv=1,bu=oe.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:f=null,selectDistinctColumns:C=Ie,pendingRowCount:S=0,pendingDataMap:b=jn,frozenColumns:w,formatColumns:T,columnHeaderGroups:E})=>{const y=v.useMemo(()=>Ce.getModelViewportColumns(e,s,i,u,m,g,Lv),[e,s,i,u,m,g]);return v.useEffect(function(){c.filter=o},[c,o]),v.useEffect(function(){const I=[...d];a!==F.REVERSE_TYPE.NONE&&I.push(c.dh.Table.reverse()),c.sort=I},[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,y)},[c,t,n,y]),v.useEffect(function(){c.isRollupAvailable&&(c.rollupConfig=p)},[c,c.isRollupAvailable,p]),v.useEffect(function(){c.isSelectDistinctAvailable&&(c.selectDistinctColumns=C)},[c,C]),v.useEffect(function(){c.isTotalsAvailable&&(c.totalsConfig=f)},[c,c.isTotalsAvailable,f]),v.useEffect(function(){c.pendingRowCount=S},[c,S]),v.useEffect(function(){c.pendingDataMap=b},[c,b]),v.useEffect(function(){w&&c.updateFrozenColumns(w)},[c,w]),v.useEffect(function(){c.columnHeaderGroups=E},[c,E]),null});bu.displayName="IrisGridModelUpdater";const _v=bu,wn=Object.freeze({SORT_UP:"sortUp",SORT_DOWN:"sortDown",CARET_DOWN:"caretDown",CARET_RIGHT:"caretRight",CELL_OVERFLOW:"cellOverflow"}),ec=10,Ea=16;class Qi extends Nt{static isFilterValid(e,t){const n=e==null||e.filter!=null,s=t==null||t.filter!=null;return n&&s}constructor(){super(),this.icons={},this.initIcons()}icons;initIcons(){this.setIcon(wn.SORT_UP,lg),this.setIcon(wn.SORT_DOWN,ag),this.setIcon(wn.CARET_DOWN,Vn),this.setIcon(wn.CARET_RIGHT,qc),this.setIcon(wn.CELL_OVERFLOW,rg)}setIcon(e,t){const n=Array.isArray(t.icon[4])?t.icon[4][0]:t.icon[4],s=new Path2D(n),i=new Path2D,o={a:Ea/t.icon[0],d:Ea/t.icon[1]};i.addPath(s,o),this.icons[e]=i}getIcon(e){return this.icons[e]}getSortIcon(e){return e?e.direction===F.sortDirection.ascending?this.getIcon(wn.SORT_UP):e.direction===F.sortDirection.descending?this.getIcon(wn.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=N(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}`;const g=u===null?"null":"empty";super.drawCellContent(e,t,n,s,g),e.font=m;return}super.drawCellContent(e,t,n,s)}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=N(l,i),h=N(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,f=N(d,n,0),C=N(h,n)+u,S=a.get(n);if(S==null)return;const b=o.columns[S]?.name;if(b==null)return;const w=F.getSortForColumn(o.sort,b);if(!w)return;const T=this.getSortIcon(w);if(!T)return;const E=o.textForColumnHeader(S);if(E===void 0)return;const y=g.get(e.font)??Nt.DEFAULT_FONT_WIDTH;D(y);const R=E.length*y,I=u+C+R+p;let{maxX:x}=s;x-=p;const A=u+C+f-p-1,k=I>x?I+1:Math.min(x,A),_=w.direction===F.sortDirection.ascending?-6:-12,M=m*.5+_;e.save(),e.beginPath(),e.rect(C,0,f,m),e.clip(),e.fillStyle=l.headerSortBarColor,e.translate(k,M),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:f}=n,C=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,C,u,a-1),e.fillStyle=i.headerBarCasingColor,e.fillRect(d,C+a-1,u,1);const S=C;e.strokeStyle=i.filterBarSeparatorColor,e.beginPath();for(let b=0;b<g.length;b+=1){const w=g[b],T=N(m,w),E=N(f,w),y=N(p,w);if(s.isFilterable(T)&&y>0){const R=d+(E??0);e.rect(R+.5,S+.5,y,a-2)}}e.stroke();for(let b=0;b<g.length;b+=1){const w=g[b],T=N(p,w),y=N(f,w)+d;this.drawExpandedFilterHeader(e,t,w,y,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:f,headerColor:C}=l,S=u-m,b=h.get(n);if(b===void 0)return;const w=a.get(b),T=d.get(b);if(w==null&&T==null)return;let E=null;if(w!=null){const{text:R}=w;if(E=R,E||(E=F.getFilterText(w.filter)),E!=null){const{fontWidths:I}=o;let x=I.get(e.font);(x==null||x===0)&&(x=e.measureText("8").width,x||(x=10));const A=(i-f*2)/x;A<=0?E="":E.length>A&&(E=`${E.substring(0,A-1)}…`)}}if(e.save(),Qi.isFilterValid(T,w)&&g!=null)e.fillStyle=g,e.fillRect(s+1,S+1,i-1,m-3);else if(p!=null){e.fillStyle=p,e.lineWidth=2,e.strokeStyle=p;const R=s+2,I=S+2,x=i-3,A=m-5;e.strokeRect(R,I,x,A)}if(E!=null&&E!==""){const R=s+f,I=S+m*.5+1;e.fillStyle=C,e.fillText(E,R,I)}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 f=h[p],C=u.get(f),S=m.get(f);if(S!=null&&C!=null){const b=S+l;this.drawCollapsedFilterHeader(e,t,f,b,C)}}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:f,filterBarActiveColor:C,filterBarActiveBackgroundColor:S,filterBarErrorColor:b}=l;e.save();const w=Qi.isFilterValid(p,g);S!=null&&g==null&&p==null?e.fillStyle=S:C!=null&&w?e.fillStyle=C:b!=null&&(e.fillStyle=b);const T=s+1,E=u-f,y=i-1,R=f-1;e.fillRect(T,E,y,R),e.restore()}drawTreeMarker(e,t,n,s,i,o,l){e.save();const{x1:a,y1:d}=i,h=l?this.getIcon(wn.CARET_DOWN):this.getIcon(wn.CARET_RIGHT),u=n+a-2,m=s+d+2.5;e.fillStyle=o,e.textAlign="center",e.translate(u,m),e.fill(h),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:f,height:C,horizontalBarHeight:S,verticalBarWidth:b,allRowHeights:w,allRowYs:T,width:E}=n;if(f<=0||p.length===0)return;const{cellHorizontalPadding:y,floatingGridRowColor:R,floatingRowBackgroundColors:I,headerColor:x,rowHoverBackgroundColor:A}=l;e.translate(d,a),e.beginPath();const k=Math.min(h,E-f-b-d);e.fillStyle=I,m>0&&e.rect(k,0,f,m),g>0&&e.rect(k,C-a-S-g,f,g),e.fill();const _=i!=null&&o!=null&&i>=d&&i<=h+f?O.getRowAtY(o,n):null;if(A!=null&&_!==null&&p.includes(_)){e.fillStyle=A;const $=T.get(_),H=w.get(_);D($),D(H),e.fillRect(k,$,f,H)}if(e.beginPath(),R!=null&&(e.strokeStyle=R),m>0&&(e.moveTo(k+.5,.5),e.lineTo(k+.5,m-.5)),g>0){const $=C-a-S-g;e.moveTo(k-.5,$+.5),e.lineTo(k-.5,$+g-.5)}e.stroke(),e.fillStyle=x,e.textAlign="left";const M=k+y;for(let $=0;$<p.length;$+=1){const H=p[$],K=w.get(H),L=T.get(H),G=u.get(H);if(L!=null&&K!=null&&G!=null){const ee=L+K*.5;e.fillText(s.textForRowFooter(G),M,ee)}}e.translate(-d,-a)}getTextRenderMetrics(e,t,n){const s=super.getTextRenderMetrics(e,t,n),{mouseX:i,mouseY:o,metrics:l}=e;if(i==null||o==null)return s;const{column:a,row:d}=O.getGridPointFromXY(i,o,l);if(t===a&&n===d){const{left:h}=this.getCellOverflowButtonPosition(e);this.shouldRenderOverflowButton(e)&&h!=null&&(s.width=h-l.gridX-s.x)}return s}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}=O.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}=super.getTextRenderMetrics(e,d,a),p=i.fontWidths.get(l.font)??Qi.DEFAULT_FONT_WIDTH;t.save(),t.font=l.font;const f=this.getCachedTruncatedString(t,m,g,p,o.truncationCharForCell(u,h));return t.restore(),m!==""&&f!==m}getCellOverflowButtonPosition({mouseX:e,mouseY:t,metrics:n,theme: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}=O.getCellInfoFromXY(e,t,n);if(a==null||l==null||d==null)return i;const{width:h,verticalBarWidth:u}=n,{cellHorizontalPadding:m}=s,g=Ea+2*m,p=o,C=Math.min(n.gridX+a+l,h-u)-g,S=n.gridY+d;return{left:C,top:S,width:g,height:p}}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=this.getIcon(wn.CELL_OVERFLOW);o!=null&&l!=null&&t.translate(o+h,l+2),t.fill(g),t.restore()}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}=O.getCellInfoFromXY(e,t,n);D(a),D(l),D(d);const{cellHorizontalPadding:h}=s,u=ec+2*h,m=Math.max(a+ec*i,n.gridX),g=n.gridY+d;return{left:m,top:g,width:u,height:l}}}const Pv=Qi,jv="12px Fira Sans, sans-serif",Hv="#f0f0ee",Uv="#1a171a",ie={"grid-bg":"#211f22",font:jv,white:Hv,black:Uv,"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"},Bv=Object.freeze({backgroundColor:ie["grid-bg"],white:ie.white,black:ie.black,font:ie.font,headerBackgroundColor:ie["header-bg"],headerColor:ie["header-color"],headerSeparatorColor:ie["header-separator-color"],headerSeparatorHoverColor:ie["header-separator-hover-color"],headerHiddenSeparatorHoverColor:ie["header-hidden-separator-hover-color"],headerSortBarColor:ie["header-sort-bar-color"],headerReverseBarColor:ie["header-reverse-bar-color"],headerBarCasingColor:ie["header-bar-casing-color"],headerFont:ie["header-font"],rowBackgroundColors:ie["row-background-colors"],rowHoverBackgroundColor:ie["row-hover-bg"],selectionColor:ie["selection-color"],selectionOutlineColor:ie["selection-outline-color"],selectionOutlineCasingColor:ie["selection-outline-casing-color"],selectedRowHoverBackgroundColor:ie["selected-row-hover-bg"],scrollBarBackgroundColor:ie["scroll-bar-bg"],scrollBarHoverBackgroundColor:ie["scroll-bar-hover-bg"],scrollBarCasingColor:ie["scroll-bar-casing-color"],scrollBarCornerColor:ie["scroll-bar-corner-color"],scrollBarColor:ie["scroll-bar-color"],scrollBarHoverColor:ie["scroll-bar-hover-color"],scrollBarActiveColor:ie["scroll-bar-active-color"],scrollBarSelectionTickColor:ie["selected-row-hover-bg"],scrollBarActiveSelectionTickColor:ie["scroll-bar-active-selection-tick-color"],textColor:ie["text-color"],hyperlinkColor:ie["hyperlink-color"],positiveNumberColor:ie["positive-number-color"],negativeNumberColor:ie["negative-number-color"],zeroNumberColor:ie["zero-number-color"],dateColor:ie["date-color"],pendingTextColor:ie["pending-text-color"],errorTextColor:ie["error-text-color"],nullStringColor:ie["null-string-color"],filterBarActiveBackgroundColor:ie["filter-bar-active-bg"],filterBarExpandedBackgroundColor:ie["filter-bar-expanded-bg"],filterBarExpandedActiveBackgroundColor:ie["filter-bar-expanded-active-bg"],filterBarExpandedActiveCellBackgroundColor:ie["filter-bar-expanded-active-cell-bg"],filterBarSeparatorColor:ie["filter-bar-separator-color"],filterBarActiveColor:ie["filter-bar-active-color"],filterBarErrorColor:ie["filter-bar-error-color"],filterIconColor:ie["filter-icon-color"],scrimColor:ie["scrim-color"],contextMenuSortIconColor:ie["context-menu-sort-icon-color"],contextMenuReverseIconColor:ie["context-menu-reverse-icon-color"],allowRowResize:!1,autoSelectRow:!0,gridColumnColor:null,gridRowColor:null,groupedColumnDividerColor:ie["grouped-column-divider-color"],columnHoverBackgroundColor:null,headerHorizontalPadding:12,scrollBarSize:13,scrollBarHoverSize:16,minScrollHandleSize:24,rowHeight:parseInt(ie["row-height"],10)||19,columnWidth:100,rowHeaderWidth:0,rowFooterWidth:60,columnHeaderHeight:parseInt(ie["header-height"],10)||30,filterBarHeight:30,filterBarCollapsedHeight:5,sortHeaderBarHeight:2,reverseHeaderBarHeight:4,filterBarHorizontalPadding:4,scrimBlurSize:25,minScrimTransitionTime:150,maxScrimTransitionTime:350,scrollSnapToRow:!0,linkerColumnHoverBackgroundColor:ie["linker-column-hover-bg"],treeLineColor:ie["tree-line-color"],treeMarkerColor:ie["tree-marker-color"],treeMarkerHoverColor:ie["tree-marker-hover-color"],floatingGridColumnColor:null,floatingGridRowColor:ie["floating-grid-row-color"],floatingRowBackgroundColors:ie["floating-row-background-colors"],floatingDividerInnerColor:ie["floating-divider-inner-color"],floatingDividerOuterColor:ie["floating-divider-outer-color"],overflowButtonColor:ie["overflow-button-color"],overflowButtonHoverColor:ie["overflow-button-hover-color"]}),tc=Bv;const ya=J.module("ColumnStatistics"),Vv={SIZE:"Number of Rows"};class El extends v.Component{static AUTO_GENERATE_LIMIT=1e5;static getStatsLabel(e){return Vv[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<El.AUTO_GENERATE_LIMIT&&this.handleGenerateStatistics():this.setState({loading:!1})}handleGenerateStatistics(){this.setState({loading:!0});const{column:e,model:t}=this.props;this.cancelablePromise=be.makeCancelable(t.columnStatistics(e)),this.cancelablePromise.then(this.handleStatistics).catch(this.handleError)}handleStatistics(e){ya.debug("Received statistics",e);const{model:t,onStatistics:n}=this.props,s=[];e.statisticsMap.forEach((i,o)=>{s.push({operation:El.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&&be.isCanceled(e)){ya.debug("Called handleError on a cancelled promise result");return}ya.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:f,className:C,value:S,type:b}=i[p],w=b?t.displayString(S,b):t.displayString(S,e.type,e.name),T=r.jsxs(oe.Fragment,{children:[r.jsx("div",{className:z("column-statistic-operation",C),children:f}),r.jsx("div",{className:"column-statistic-value",children:w})]},f);a.push(T)}const u=Pe(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(jl,{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(X,{icon:t.isColumnFrozen(g)?dg:cg,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(P,{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(P,{kind:"ghost",className:"px-0",onClick:this.handleGenerateStatistics,icon:r.jsx(X,{icon:dr,className:"mr-1"}),children:"Refresh"}),s&&r.jsxs("div",{className:"column-statistics-loading",children:[r.jsx(Nn,{className:"mr-2"}),"Calculating Stats..."]})]})}}const $v=El;const Vo=J.module("AdvancedFilterCreatorFilterItem");class jr extends v.PureComponent{static getLabelForFilter(e,t){try{if(F.isNumberType(e)||F.isCharType(e))return gh(t);if(F.isTextType(e))return mh(t);if(F.isDateType(e))return ph(t);if(F.isBooleanType(e))return Kf(t);throw new Error(`Unrecognized column type: ${e}`)}catch(n){return Vo.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;Vo.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){Vo.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(){Vo.debug("delete");const{onDelete:e}=this.props;e()}getCachedIsValid=ce((e,t,n,s,i)=>{try{return!n||i.makeAdvancedValueFilter(e,t,n,s)!=null}catch{return!1}});render(){const{column:e,filterTypes:t,formatter:n,tableUtils:s}=this.props,{selectedType:i,value:o}=this.state,l=!F.isBooleanType(e.type),a=[],d=this.getCachedIsValid(e,i,o,n.timeZone,s);for(let h=0;h<t.length;h+=1){const u=t[h],m=jr.getLabelForFilter(e.type,u),g=r.jsx("option",{value:u,children:m},u);a.push(g)}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:i,onChange:this.handleTypeChange,ref:h=>{this.typeDropdown=h},children:a})}),l&&r.jsx("div",{className:"form-group col",children:r.jsx("div",{className:"input-group",children:r.jsx("input",{type:"text",className:z("form-control",{error:!d}),placeholder:"Enter value",value:o,onChange:this.handleValueChange})})}),r.jsx("div",{className:"form-group col-1 px-0",children:r.jsx(P,{kind:"ghost",className:"w-100 h-100 p-0 m-0",onClick:this.handleDelete,icon:$t,tooltip:"Remove Filter"})})]})})}}const Wv=jr,nc=J.module("AdvancedFilterCreatorSelectValueList");class yl 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);const{selectedValues:t,dh:n}=this.props;this.dh=n,this.list=null,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)}dh;list;handleSelect(e,t){const{invertSelection:n}=this.props;let{selectedValues:s}=this.state;s=[...s];const i=yl.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})}nc.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=yl.indexOf(e,n);return t?s<0:s>=0}startListening(e){e.addEventListener(this.dh.Table.EVENT_UPDATED,this.handleTableUpdate)}stopListening(e){e.removeEventListener(this.dh.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);nc.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(Im,{itemCount:s,items:n,offset:e,onSelect:this.handleSelect,onViewportChange:this.handleViewportChange,ref:i=>{this.list=i}}),r.jsx(Vt,{in:t,timeout:250,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:"loading-list",children:r.jsx(Nn,{className:"loading-spinner-large"})})})]})}}const Gv=yl;class Hr 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{dh:t,invertSelection:n,selectedValues:s}=e;this.tableUtils=new F(t),this.state={filters:[],invertSelection:n,selectedValues:s,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;tableUtils;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,Hr.searchDebounceTime)}stopUpdateFilterTimer(){this.updateFilterTimer!=null&&(clearTimeout(this.updateFilterTimer),this.updateFilterTimer=void 0)}updateTableFilter(){const{table:e,searchText:t}=this.state,{timeZone:n}=this.props,{tableUtils:s}=this,i=e?.columns[0],o=[];if(i==null)return;let l;if(t.length>0){let a=null;F.isCharType(i.type)?a=s.makeQuickFilter(i,t):F.isTextType(i.type)?a=s.makeQuickFilter(i,`~${t}`,n):a=s.makeQuickFilter(i,`>=${t}`,n),a!=null?o.push(a):l="Invalid search text"}this.setState({filters:o,error:l})}render(){const{error:e,filters:t,invertSelection:n,selectedValues:s,searchText:i,table:o}=this.state,{dh:l,formatter:a,showSearch:d}=this.props,h=this.getColumnName(),u=this.getDisplayedValueText(),m=h?`Find ${h}...`:"";return r.jsxs("div",{className:"advanced-filter-creator-select-value",children:[r.jsxs("div",{className:d?"form-group":"",children:[r.jsx("label",{htmlFor:"advanced-filter-creator-select-value-input",children:"Select Values"}),d&&r.jsx("input",{type:"text",className:z("form-control",{"is-invalid":e!=null}),id:"advanced-filter-creator-select-value-input",placeholder:m,value:i,onChange:this.handleSearchChange})]}),r.jsx(Gv,{dh:l,table:o,filters:t,invertSelection:n,selectedValues:s,formatter:a,onChange:this.handleListChange}),r.jsxs("div",{className:"advanced-filter-creator-select-meta-row",children:[r.jsxs("div",{children:[r.jsx(P,{kind:"ghost",onClick:this.handleSelectAllClick,children:"Select All"}),r.jsx(P,{kind:"ghost",onClick:this.handleClearAllClick,children:"Clear"})]}),r.jsx(Vt,{in:u!=null,timeout:250,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx("div",{className:"row-count-info",children:u})})]})]})}}const zv=Hr;const Hi=J.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:Ge()}}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=oe.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:Ge()}))??[];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=ce(e=>F.getFilterTypes(e));initValuesTable(){const{model:e,column:t}=this.props;if(!e.isValuesTableAvailable){Hi.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=>{be.isCanceled(n)||(Hi.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(Un.and),this.setState({filterItems:e,filterOperators:t})}handleAddOr(){let{filterItems:e,filterOperators:t}=this.state;e=e.concat(us.makeFilterItem()),t=t.concat(Un.or),this.setState({filterItems:e,filterOperators:t})}handleChangeFilterOperator(e,t){let{filterOperators:n}=this.state;n=[...n],Dm(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(){Hi.debug("Resetting Advanced Filter"),this.setState({filterItems:[us.makeFilterItem()],filterOperators:[],selectedValues:[],invertSelection:!0}),this.startUpdateTimer()}handleSortDown(e){const t=ws.isModifierKeyDown(e);this.sortTable(F.sortDirection.descending,t)}handleSortUp(e){const t=ws.isModifierKeyDown(e);this.sortTable(F.sortDirection.ascending,t)}handleSubmit(e){Hi.debug("Submitting Advanced Filter"),this.stopUpdateTimer(),this.sendUpdate(),e.preventDefault()}handleDone(e){Hi.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,tableUtils:a}=this.props,{formatter:d}=l,h=e.filter(({selectedType:p,value:f})=>p!=null&&f!=null&&f!==""),u=t.filter((p,f)=>p!=null&&e[f].selectedType!=null&&e[f].value!=null&&e[f].value!=="").slice(0,h.length-1),m={filterItems:h,filterOperators:u,invertSelection:n,selectedValues:s},g=a.makeAdvancedFilter(i,m,d.timeZone);o(i,g,m)}render(){const{column:e,model:t,sortDirection:n,formatter:s,tableUtils:i}=this.props,{filterItems:o,filterOperators:l,invertSelection:a,selectedValues:d,valuesTable:h,valuesTableError:u}=this.state,{dh:m,isValuesTableAvailable:g}=t,p=F.isBooleanType(e.type),f=F.isDateType(e.type),C=this.getFilterTypes(e.type),S=e.type.substring(e.type.lastIndexOf(".")+1),b=[];if(!p&&C.length)for(let E=0;E<o.length;E+=1){const y=o[E],{key:R,selectedType:I,value:x}=y,A=r.jsx(Wv,{column:e,filterTypes:C,onChange:this.getFilterChangeHandler(E),onDelete:this.getFilterDeleteHandler(E),selectedType:I,value:x,formatter:s,tableUtils:i},R);if(b.push(A),E<l.length){const _=l[E]===Un.and,M=r.jsxs("div",{className:"form-row justify-content-end advanced-filter-creator-filter-operator",children:[r.jsx(P,{kind:"ghost",className:z("filter-operator",{active:_}),onClick:()=>this.handleChangeFilterOperator(E,Un.and),children:"AND"}),r.jsx(P,{kind:"ghost",className:z("filter-operator",{active:!_}),onClick:()=>this.handleChangeFilterOperator(E,Un.or),children:"OR"})]},`filterOperator${R}`);b.push(M)}}const w=this.shouldShowAddFilter(),T=r.jsxs("div",{className:z("form-row justify-content-end add-filter-item",{hidden:!w}),children:[r.jsx("span",{className:"text-muted",children:r.jsx(X,{icon:Ts})}),r.jsx(P,{kind:"ghost",className:"btn-filter-item",onClick:this.handleAddAnd,disabled:!w,tooltip:"Add filter with AND",children:"AND"}),r.jsx(P,{kind:"ghost",className:"btn-filter-item",onClick:this.handleAddOr,disabled:!w,tooltip:"Add filter with OR",children:"OR"})]},"addFilterItem");return b.push(T),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(P,{kind:"ghost",className:z("sort-operator",{active:n===F.sortDirection.descending}),onClick:this.handleSortDown,icon:Cd,tooltip:`Sort ${e.name} Descending`}),r.jsx(P,{kind:"ghost",className:z("sort-operator",{active:n===F.sortDirection.ascending}),onClick:this.handleSortUp,icon:r.jsx(X,{icon:Cd,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:["(",S,")"]})]}),b,g&&u==null&&r.jsxs(r.Fragment,{children:[!p&&r.jsx("hr",{}),r.jsx("div",{className:"form-group",children:r.jsx(zv,{dh:m,table:h,onChange:this.handleSelectValueChange,invertSelection:a,selectedValues:d,formatter:s,showSearch:!f,timeZone:s.timeZone})})]}),r.jsxs("div",{className:"form-row justify-content-end",children:[r.jsx(P,{kind:"secondary",className:"mr-2",onClick:this.handleReset,children:"Reset"}),r.jsx(P,{kind:"primary",onClick:this.handleDone,children:"Done"})]})]}),r.jsx("div",{tabIndex:0,onFocus:this.handleFocusTrapEnd})]})}}const Kv=us;const sc=J.module("Aggregations");function Yv({isRollup:c,settings:e,onChange:t,onEdit:n}){const{aggregations:s,showOnTop:i}=e,o=v.useMemo(()=>Bw.filter(x=>!s.some(A=>A.operation===x)),[s]),[l,a]=v.useState(o[0]),[d,h]=v.useState([]),u=v.useCallback(x=>{t({...e,...x})},[t,e]),m=v.useCallback(x=>{u({aggregations:x})},[u]),g=v.useCallback(x=>{u({showOnTop:x})},[u]),p=v.useCallback(()=>{sc.debug("handleDragStart"),hn.startDragging()},[]),f=v.useCallback(({destination:x,source:A})=>{if(sc.debug("handleDragEnd",x,A),hn.stopDragging(),x===null)return;let k=x.index;A.index<x.index&&(k+=1);const _=[...s],M=hn.reorder(_,d,_,k),$=hn.adjustDestinationIndex(k,d),H=[[$,$+M.length-1]];m(_),h(H)},[m,s,d,h]),C=v.useCallback(x=>{a(x)},[a]),S=v.useCallback(()=>{m([...s,{operation:l,selected:[],invert:!0}])},[s,l,m]),b=v.useCallback(x=>{m(s.filter((A,k)=>k!==x))},[s,m]),w=v.useCallback(x=>{h(x)},[h]),T=v.useCallback(x=>{const A=s[x];ps.isRollupOperation(A.operation)||n(A)},[s,n]),E=v.useCallback(x=>{g(x.target.value==="true")},[g]);v.useEffect(function(){o.length>0&&!o.includes(l)&&a(o[0])},[o,l]);const y=v.useCallback(({item:x,itemIndex:A,isClone:k=!1,selectedCount:_})=>{const M=x.operation,$=k?`${_}`:void 0,H=k?"item-list-item-clone":void 0,K=ps.isRollupOperation(x.operation),L=!k&&!K;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:z("item-list-item-content","draggable-item-list-item-content",H),children:[r.jsxs("span",{className:"title",children:[M,!c&&K&&r.jsxs("span",{className:"small text-warning",children:[r.jsx(X,{icon:Qc})," Requires rollup"]})]}),rn.renderBadge({text:$}),rn.renderHandle()]}),!k&&r.jsxs(r.Fragment,{children:[r.jsx(P,{kind:"ghost",className:"btn-edit",icon:mo,tooltip:"Edit Columns",onClick:()=>n(x),disabled:!L}),r.jsx(P,{kind:"ghost",className:"btn-delete",icon:$t,tooltip:"Delete Aggregation",onClick:()=>b(A)})]})]})},[b,n,c]),R=o.length>0,I=s.length>0;return r.jsxs("div",{className:"aggregations",children:[R&&r.jsxs("div",{className:"form-inline",children:[r.jsx(Fm,{onChange:C,value:l,children:o.map(x=>r.jsx(Nm,{value:x,children:x},x))}),r.jsxs("button",{type:"button",className:"btn btn-link btn-add",onClick:S,children:[r.jsx(X,{icon:Ts}),"Add Aggregation"]})]}),R&&I&&r.jsx("hr",{}),I&&r.jsxs(r.Fragment,{children:[!c&&r.jsxs("div",{className:"form-inline",children:[r.jsx("label",{children:"Placement: "}),r.jsxs(Hl,{onChange:E,value:`${i}`,children:[r.jsx(Gn,{value:"true",children:"Top"}),r.jsx(Gn,{value:"false",children:"Bottom"})]})]}),r.jsx(Ll,{onDragStart:p,onDragEnd:f,children:r.jsx(rn,{className:"selected-aggregations",itemCount:s.length,items:s,renderItem:y,offset:0,onSelectionChange:w,onSelect:T,selectedRanges:d,isMultiSelect:!0})})]})]})}const qv=30;function Xv({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(E=>h.includes(E)?!d:d,[d,h]),g=v.useMemo(()=>{let E=_r(e,c.operation);return l!==0&&(E=F.sortColumns(E,l===1)),E},[e,c.operation,l]),p=v.useMemo(()=>n>=0?g.slice(n,i+1).map(E=>({value:E.name,displayValue:E.name,isSelected:m(E.name)})):[],[g,m,i,n]),f=v.useCallback(E=>{const{name:y}=g[E],R=h.indexOf(y);let I=[...h],x=d;R>=0?I.splice(R,1):(I.push(y),I.length===g.length&&(I=[],x=!d)),t({...c,selected:I,invert:x})},[c,d,g,h,t]),C=v.useCallback(()=>{a(0),t({...c,selected:[],invert:!0})},[c,t]),S=v.useCallback((E,y)=>{s(E),o(y)},[s,o]),b=v.useCallback(()=>{h.length===0?t({...c,invert:!d}):t({...c,selected:[],invert:!0})},[c,d,t,h]),w=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(tn,{checked:w,onChange:b,children:"Toggle All"}),r.jsx("div",{className:"spacer"}),r.jsx(Vt,{in:T,timeout:Ye.transitionSlowMs,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx(P,{kind:"ghost",className:"btn-reset",onClick:C,children:"Reset"})}),r.jsx(P,{kind:"ghost",className:z({active:l===1}),icon:cr,tooltip:"Sort ascending",onClick:()=>a(1)}),r.jsx(P,{kind:"ghost",className:z({active:l===2}),icon:hr,tooltip:"Sort descending",onClick:()=>a(2)})]})}),r.jsx("div",{className:"aggregation-edit-item-list",children:r.jsx(Ei,{itemCount:g.length,items:p,offset:n,renderItem:({item:E})=>r.jsx(tn,{checked:m(E.value),children:E.displayValue}),onSelect:f,onViewportChange:S,rowHeight:qv,focusSelector:"input",ref:u})})]})}function Zv(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 Qv(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 Jv(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 eT(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 tT(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 nT(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 sT(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 ic=J.module("ChartBuilder");class an extends v.PureComponent{static getMaxSeriesCount(e,t){switch(t){case e.plot.SeriesPlotStyle.PIE:return 1;case e.plot.SeriesPlotStyle.HISTOGRAM:return 0;default:return 100}}static makeSeriesItem(e){return{id:Ge.generate(),value:e}}static makeDefaultSeriesItems(e,t,n){if(an.getMaxSeriesCount(e,t)===0||n==null||n.length===0)return[];const i=n.length>1?n[1].name:n[0].name;return[an.makeSeriesItem(i)]}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,dh:s}=t,i=this.getTypes()[0],o=an.getDefaultXAxis(i,n),l=an.makeDefaultSeriesItems(s,i,n);this.state={type:i,seriesItems:l,xAxis:o,isLinked:!0}}getTypes(){const{model:e}=this.props,{dh:t}=e;return[t.plot.SeriesPlotStyle.LINE,t.plot.SeriesPlotStyle.BAR,t.plot.SeriesPlotStyle.SCATTER,t.plot.SeriesPlotStyle.PIE]}getTypeName(e){const{model:t}=this.props,{dh:n}=t;switch(e){case n.plot.SeriesPlotStyle.LINE:return"Line";case n.plot.SeriesPlotStyle.BAR:return"Bar";case n.plot.SeriesPlotStyle.SCATTER:return"Scatter";case n.plot.SeriesPlotStyle.PIE:return"Pie";case n.plot.SeriesPlotStyle.HISTOGRAM:return"Histogram";default:return e}}getTypeIcon(e){const{model:t}=this.props,{dh:n}=t;switch(e){case n.plot.SeriesPlotStyle.LINE:return r.jsx(Jv,{});case n.plot.SeriesPlotStyle.BAR:return r.jsx(Zv,{});case n.plot.SeriesPlotStyle.SCATTER:return r.jsx(tT,{});case n.plot.SeriesPlotStyle.PIE:return r.jsx(eT,{});case n.plot.SeriesPlotStyle.HISTOGRAM:return r.jsx(Qv,{});default:return null}}getXAxisLabel(e){const{model:t}=this.props,{dh:n}=t;switch(e){case n.plot.SeriesPlotStyle.PIE:return"Labels";case n.plot.SeriesPlotStyle.HISTOGRAM:return"Data";default:return"X-Axis"}}getSeriesLabel(e){const{model:t}=this.props,{dh:n}=t;switch(e){case n.plot.SeriesPlotStyle.PIE:return"Values";default:return"Series"}}handleAddSeries(){this.setState(e=>{const{seriesItems:t}=e,n=[...t],{model:s}=this.props,{columns:i}=s;return n.push({id:Ge.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,dh:n}=e,s=this.getTypes()[0],i=an.getDefaultXAxis(s,t),o=an.makeDefaultSeriesItems(n,s,t),l=!0;this.setState({type:s,seriesItems:o,xAxis:i,isLinked:l},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=this.getTypes()[s];ic.debug2("handleTypeSelect",i),this.setState(o=>{const{model:l}=this.props,{dh:a}=l,d=an.getMaxSeriesCount(a,i);let{seriesItems:h}=o;if(h=h.slice(0,d),h.length===0&&d>0){const{columns:u}=l;h=an.makeDefaultSeriesItems(a,i,u)}return{type:i,seriesItems:h}},this.sendChange)}handleXAxisChange(e){const t=e.target.value;ic.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,dh:n}=e,{seriesItems:s,type:i,xAxis:o,isLinked:l}=this.state,a=an.getMaxSeriesCount(n,i),d=this.getXAxisLabel(i),h=this.getSeriesLabel(i),u=s.length>0,m=s.length<a;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:this.getTypes().map((g,p)=>{const f=g;return r.jsx("div",{className:"col col-chart-type",children:r.jsxs("button",{type:"button",className:z("btn","btn-icon","btn-chart-type",{active:g===i}),"data-index":p,onClick:this.handleTypeClick,children:[this.getTypeIcon(g),this.getTypeName(g)]})},f)})})]}),r.jsx("hr",{}),r.jsxs("div",{className:"form-row form-inline",children:[r.jsx("label",{className:"col-2 label-left",children:d}),r.jsx("select",{className:"form-control custom-select select-x-axis col",value:o,onChange:this.handleXAxisChange,children:t.map(g=>r.jsx("option",{value:g.name,children:g.name},g.name))})]}),u&&r.jsx("hr",{}),s.map((g,p)=>r.jsxs("div",{className:"form-row form-inline form-series-item","data-testid":`form-series-item-${p}`,children:[r.jsx("label",{className:"col-2 label-left",children:p===0?h:""}),r.jsx("select",{className:"form-control custom-select select-series col",value:g.value,onChange:this.handleSeriesChange,"data-testid":`select-series-item-${p}`,"data-index":p,children:t.map(f=>r.jsx("option",{value:f.name,"data-index":p,children:f.name},f.name))}),s.length>1&&r.jsx(P,{kind:"ghost",className:"btn-delete-series ml-2 px-2","data-index":p,"data-testid":`delete-series-${p}`,onClick:this.handleSeriesDeleteClick,icon:$t,tooltip:"Delete"})]},g.id)),m&&r.jsxs("div",{className:"form-row",children:[r.jsx("div",{className:"col-2"}),r.jsx(P,{kind:"ghost",className:"btn-add-series mt-1",onClick:this.handleAddSeries,icon:Ts,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(X,{mask:lr,icon:yi,transform:"right-5 down-5"}),r.jsx(X,{icon:l?Jc:hg,transform:"grow-2 right-8 down-6"})]})}),r.jsxs(Hl,{onChange:this.handleLinkStateChange,value:`${l}`,children:[r.jsx(Gn,{value:"true",children:"Sync State"}),r.jsx(Gn,{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:l?"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:z("form-row","justify-content-end","my-3"),children:[r.jsx(P,{kind:"secondary",className:"btn-reset",onClick:this.handleReset,children:"Reset"}),r.jsx(P,{kind:"primary",type:"submit",className:"btn-submit",children:"Create"})]})]})})}}const iT=an;class oT 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=zn.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:z("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 oc=Object.freeze({NAME:"name",FORMULA:"formula"}),lT=()=>{};function aT({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,oc.FORMULA,u))},[s,c]);return r.jsx(Hc,{draggableId:c,index:t,disableInteractiveElementBlocking:!0,children:(u,m)=>r.jsxs("div",{className:z("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:z("form-control custom-column-input",{"is-invalid":l||!d||a}),placeholder:"Column Name",value:e,onChange:g=>{s(c,oc.NAME,g.target.value)}}),r.jsx(P,{kind:"ghost",className:"ml-1 px-2",onClick:()=>{i(c)},icon:$t,tooltip:"Delete custom column"}),r.jsx(P,{kind:"ghost",className:"btn-drag-handle",onClick:lT,...u.dragHandleProps,icon:Vl,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(oT,{editorSettings:{language:"deephavenDb"},editorIndex:t,value:n,onContentChanged:h,onTab:o,invalid:l})]}),r.jsx("hr",{})]})})}const Ra=[];class rT extends rw{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(e){super(),this.dh=e,this.listenerCount=0}dh;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 Ra}get backColumns(){return Ra}get frozenColumns(){return Ra}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 ge=rT;class Bs extends v.Component{static SUCCESS_SHOW_DURATION=750;static makeCustomColumnInputEventKey(){return Ge.generate()}static createCustomColumnInput(){return{eventKey:Ge.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=ce((e,t)=>e.find(n=>n.eventKey===t));getInputIndex=ce((e,t)=>e.findIndex(n=>n.eventKey===t));resetErrorMessage(){this.setState({errorMessage:null})}startListening(){const{model:e}=this.props;e.addEventListener(ge.EVENT.COLUMNS_CHANGED,this.handleCustomColumnUpdated),e.addEventListener(ge.EVENT.UPDATED,this.handleCustomColumnUpdated),e.addEventListener(ge.EVENT.REQUEST_FAILED,this.handleRequestFailed)}stopListening(){const{model:e}=this.props;e.removeEventListener(ge.EVENT.COLUMNS_CHANGED,this.handleCustomColumnUpdated),e.removeEventListener(ge.EVENT.UPDATED,this.handleCustomColumnUpdated),e.removeEventListener(ge.EVENT.REQUEST_FAILED,this.handleRequestFailed)}parseCustomColumns(e){if(e.length>0){const t=e.map(n=>{const s=n.split(/=(.+)/,2);return{eventKey:Bs.makeCustomColumnInputEventKey(),name:s[0],formula:s[1]}});this.setState({inputs:t})}else this.setState({inputs:[Bs.createCustomColumnInput()]})}handleAddColumnClick(){const{inputs:e}=this.state,t=[...e];t.push(Bs.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(Bs.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}),Bs.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(X,{icon:Ss})," 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(aT,{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(P,{kind:n?"success":"primary",className:z("btn-apply",{"btn-spinner":t}),disabled:n||t||!i||!l,onClick:this.handleSaveClick,children:[t&&r.jsxs("span",{children:[r.jsx(Nn,{}),r.jsx("span",{className:"btn-normal-content",children:"Applying"})]}),!n&&!t&&s,n&&r.jsxs(r.Fragment,{children:[r.jsx(X,{icon:ar})," 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(Ll,{onDragStart:hn.startDragging,onDragEnd:this.handleDragEnd,children:r.jsx(sr,{droppableId:"droppable-custom-columns",children:(n,s)=>r.jsxs("div",{ref:n.innerRef,...n.droppableProps,className:z("droppable-container",{dragging:s.draggingFromThisWith}),children:[this.renderInputs(),n.placeholder]})})}),r.jsx("div",{className:"pt-1 px-3",children:r.jsx(P,{kind:"ghost",className:"btn-add-column",onClick:this.handleAddColumnClick,icon:Ts,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(P,{kind:"secondary",className:"mr-2",onClick:e,children:"Cancel"}),this.renderSaveButton()]})]})]})}}const dT=Bs;var wu=(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))(wu||{});const xe=wu;const Ui=J.module("RollupRows"),cT=150,$o="grouped-rollup-rows",Wo="ungrouped-rollup-rows";class Zt 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=oe.createRef(),this.groupedList=oe.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===Zt.SORT.ASCENDING?null:Zt.SORT.ASCENDING}))}handleSortDescending(){this.setState(({sort:e})=>({sort:e===Zt.SORT.DESCENDING?null:Zt.SORT.DESCENDING}))}resetSelection(){this.setState({ungroupedSelectedRanges:[],groupedSelectedRanges:[]})}search=We(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]));D(s),this.setState({ungroupedSelectedRanges:n}),n.length>0&&this.ungroupedList.current&&this.ungroupedList.current.scrollToItem(s)},cT);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===Wo){this.setState(({groupedSelectedRanges:o,columns:l})=>{const a=[...l];return hn.reorder(a,o,[],0),{columns:a,ungroupedSelectedRanges:[],groupedSelectedRanges:[]}});return}const s=n.droppableId===$o;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(f=>f.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:Zt.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=we((e,t)=>e.filter(n=>Zt.isGroupable(n)&&t.find(s=>s===n.name)==null));getCachedSortedColumns=we((e,t)=>t==null?[...e]:F.sortColumns(e,t===Zt.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(P,{kind:"ghost",className:"btn btn-link btn-link-icon btn-delete-grouping float-right",onClick:()=>this.handleDeleteClicked(t),children:r.jsx(X,{icon:$t})})]})}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===Wo&&(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:z("rollup-rows",{"is-dragging":t!=null}),tabIndex:0,children:r.jsxs(Ll,{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(sr,{droppableId:"placeholder",children:(g,p)=>r.jsx("div",{className:z("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:$o,droppableId:$o,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(xi,{className:"w-100",value:n,matchCount:n?i.length:void 0,placeholder:"Find column...",onChange:this.handleSearchChange}),r.jsxs(P,{kind:"ghost",className:z("btn-link btn-link-icon",{active:a===Zt.SORT.ASCENDING}),onClick:this.handleSortAscending,children:[r.jsx(X,{icon:cr}),r.jsx(Je,{children:"Sort ascending"})]}),r.jsxs(P,{kind:"ghost",className:z("btn-link btn-link-icon",{active:a===Zt.SORT.DESCENDING}),onClick:this.handleSortDescending,children:[r.jsx(X,{icon:hr}),r.jsx(Je,{children:"Sort descending"})]})]}),r.jsx(rn,{className:"rollup-available-grouping-columns",draggablePrefix:Wo,droppableId:Wo,itemCount:d.length,items:d,renderItem:Zt.renderColumn,offset:0,onSelect:this.handleUngroupedSelect,onSelectionChange:this.handleUngroupedSelectionChange,ref:this.ungroupedList,selectedRanges:i,style:{maxHeight:u,minHeight:m},isDropDisabled:t?.droppableId!==$o,isMultiSelect:!0}),r.jsxs("div",{className:"bottom-menu",children:[r.jsx("div",{className:"label",children:"Show:"}),r.jsx(tn,{checked:o,onChange:this.handleShowConstituentsChange,children:"Constituents"}),r.jsx(tn,{checked:l,onChange:this.handleShowNonAggregatedColumnsChange,children:"Non-Aggregated Columns"})]})]})]})})}}const hT=Zt;const uT=J.module("TableCsvExporter");class Ae 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(e){return e.i18n.DateTimeFormat.format(Ae.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{model:t,name:n}=e;this.state={fileName:`${n}-${Ae.getDateString(t.dh)}.csv`,downloadRowOption:Ae.DOWNLOAD_ROW_OPTIONS.ALL_ROWS,customizedDownloadRowOption:Ae.CUSTOMIZED_ROWS_OPTIONS.FIRST,customizedDownloadRows:Ae.DEFAULT_DOWNLOAD_ROWS,includeColumnHeaders:!0,includeHiddenColumns:!1,useUnformattedValues:!1,errorMessage:null,id:Ge.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 Ae.DOWNLOAD_ROW_OPTIONS.ALL_ROWS:a.push(new Q(0,0,l-1,o-1));break;case Ae.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 Ae.DOWNLOAD_ROW_OPTIONS.CUSTOMIZED_ROWS:switch(s){case Ae.CUSTOMIZED_ROWS_OPTIONS.FIRST:a.push(new Q(0,0,l-1,Math.min(i-1,o-1)));break;case Ae.CUSTOMIZED_ROWS_OPTIONS.LAST:a.push(new Q(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=Ce.getHiddenColumns(t);let o=O.getModelRanges(e,n);if(!s&&i.length>0){const l=i.map(Q.makeColumn);o=Q.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){uT.error("CSV download failed",u),this.setState({errorMessage:r.jsxs("p",{children:[r.jsx(X,{icon:Ss})," ",`${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===Ae.DOWNLOAD_ROW_OPTIONS.SELECTED_ROWS&&e.length===0?(this.setState({errorMessage:r.jsxs("p",{children:[r.jsx(X,{icon:Ss})," No rows selected. Please select some rows in the table."]})}),!1):t===Ae.DOWNLOAD_ROW_OPTIONS.CUSTOMIZED_ROWS&&n<=0?(this.setState({errorMessage:r.jsxs("p",{children:[r.jsx(X,{icon:Ss})," 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:f}=this.state,{rowCount:C}=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(Hl,{onChange:this.handleDownloadRowOptionChanged,value:a,disabled:t,children:[r.jsxs(Gn,{value:Ae.DOWNLOAD_ROW_OPTIONS.ALL_ROWS,"data-testid":"radio-csv-exporter-download-all",children:["All Rows",r.jsx("span",{className:"text-muted ml-2",children:`(${C.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1,")} rows)`})]}),r.jsxs(Gn,{value:Ae.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?`(${Q.rowCount(i).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1,")} rows)`:null})]}),r.jsx(Gn,{value:Ae.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:Ae.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-${f}`,"data-testid":"input-csv-exporter-customized-rows",name:`customizedRows-${f}`,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-${f}`,children:"File Name"}),r.jsx("input",{type:"text",className:"form-control",id:`filename-${f}`,"data-testid":"input-csv-exporter-file-name",name:`filename-${f}`,value:l,onChange:S=>{this.setState({fileName:S.target.value})},disabled:t})]}),r.jsxs("div",{className:"checkbox-options",children:[r.jsx(tn,{checked:u,onChange:this.handleIncludeColumnHeadersChanged,children:"Include column headers"}),r.jsx(tn,{checked:m,onChange:this.handleIncludeHiddenColumnsChanged,children:"Include hidden columns"}),r.jsx(tn,{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===Ae.DOWNLOAD_STATUS.DOWNLOADING||o===Ae.DOWNLOAD_STATUS.INITIATING)&&r.jsxs(r.Fragment,{children:[o===Ae.DOWNLOAD_STATUS.INITIATING&&r.jsx("div",{className:"text-muted",children:"Starting Download..."}),o===Ae.DOWNLOAD_STATUS.DOWNLOADING&&r.jsxs("div",{className:"text-muted d-flex justify-content-between",children:[r.jsx("span",{children:s||s===0?`Estimated time: ${_l.formatElapsedTime(s)}`:null}),r.jsx("span",{children:`${n}%`})]})]}),o===Ae.DOWNLOAD_STATUS.FINISHED&&r.jsx("div",{className:"text-muted text-right",children:"Download Completed"}),o===Ae.DOWNLOAD_STATUS.CANCELED&&r.jsx("div",{className:"text-muted",children:"Download Canceled"}),(o===Ae.DOWNLOAD_STATUS.DOWNLOADING||o===Ae.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===Ae.DOWNLOAD_STATUS.FINISHED&&r.jsx("div",{className:"progress",children:r.jsx("div",{className:"progress-bar bg-success",style:{width:`${n}%`}})})]}),r.jsxs(P,{kind:"primary","data-testid":"btn-csv-exporter-download",className:z("btn-downloading",{"btn-spinner btn-cancelable":t}),onClick:this.handleDownloadClick,children:[t&&r.jsxs("span",{children:[r.jsx(Nn,{}),r.jsx("span",{className:"btn-normal-content",children:"Downloading"}),r.jsx("span",{className:"btn-hover-content",children:"Cancel"})]}),!t&&"Download"]})]})]})}}const Os=Ae,_n=J.module("TableSaver"),mT="yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS z";function gT(c){return c.added!==void 0}function pT(c){if(!gT(c))throw new Error("event is not UpdateEventData")}class Hn 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=>{_n.info("found active service worker"),this.sw=t,this.sw.postMessage("ping")}).catch(t=>{_n.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=Bn(Wn.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=>{D(s),l.header!==void 0&&n.push(s(l.header)),l.rows!==void 0&&n.push(s(l.rows))},o.close=()=>{D(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(),_n.info(`start downloading ${e}`),this.table=t,this.columns=Ce.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&&_n.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(){_n.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
|
+
`:",";this.fileWriter?.write({header:e}).then(()=>null)}startWriteTableBody(){this.columns&&this.gridRanges!=null&&(this.chunkRows=Math.floor(Hn.DOWNLOAD_CELL_CHUNK/this.columns.length),this.rangedSnapshotsTotal=this.gridRanges.map(e=>(D(e.endRow),D(e.startRow),D(this.chunkRows),Math.ceil((e.endRow-e.startRow+1)/this.chunkRows))),this.snapshotsTotal=this.rangedSnapshotsTotal.reduce((e,t)=>e+t),_n.info("start writing table, total snapshots: ",this.snapshotsTotal),this.makeSnapshot(Math.min(Hn.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);D(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&&(_n.debug2(`
|
|
22
|
+
current range index: ${this.gridRangeCounter},
|
|
23
|
+
snapshotIndexCounter: ${this.snapshotCounter},
|
|
24
|
+
currentRangedSnapshotIndex : ${this.rangedSnapshotCounter},
|
|
25
|
+
snapshotpending: ${this.snapshotPending},
|
|
26
|
+
buffered ${this.snapshotsBuffer.size}
|
|
27
|
+
making ${Math.min(Hn.SNAPSHOT_BUFFER_SIZE-this.snapshotsBuffer.size-this.snapshotPending,this.snapshotsTotal-this.snapshotCounter)} more snapshots
|
|
28
|
+
`),this.makeSnapshot(Math.min(Hn.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(),{dh:s,formatter:i}=this.props,o=[];for(;n.hasNext();)o.push(n.next().value);D(this.columns);const{useUnformattedValues:l}=this;for(let a=0;a<o.length;a+=1){const d=o[a];for(let h=0;h<this.columns.length;h+=1){const{type:u,name:m}=this.columns[h];let g=null;if(l){let p=e.getData(d,this.columns[h])??"";p!==""&&F.isDateType(u)&&(p=s.i18n.DateTimeFormat.format(mT,p,s.i18n.TimeZone.getTimeZone(i.timeZone))),g=p.toString()}else{const p=this.getCachedCustomColumnFormatFlag(i,m,u);let f=null;if(!p){const C=e.getFormat(d,this.columns[h]);f=C?.formatString!=null?C:null}f?g=i.getFormattedString(e.getData(d,this.columns[h]),u,m,f):g=i.getFormattedString(e.getData(d,this.columns[h]),u,m)}t+=Hn.csvEscapeString(g),t+=h===this.columns.length-1?`
|
|
29
|
+
`:","}}return t}makeSnapshot(e){if(e<=0)return;const{dh:t}=this.props;D(this.gridRangeCounter);let n=0,s=this.gridRanges[this.gridRangeCounter];for(D(this.tableSubscription),D(this.columns);n<e;){D(s),D(s.startRow),D(s.endRow),D(this.rangedSnapshotCounter),D(this.chunkRows);const i=s.startRow+this.rangedSnapshotCounter*this.chunkRows,o=Math.min(i+this.chunkRows-1,s.endRow),l=this.snapshotCounter;this.cancelableSnapshots.push(be.makeCancelable(this.tableSubscription.snapshot(t.RangeSet.ofRange(i,o),this.columns).then(a=>(pT(a),this.handleSnapshotResolved(a,l,i,o),l)).catch(a=>{_n.error(a)}),a=>{_n.info(`snapshot ${a} has been canceled`)})),this.rangedSnapshotCounter+=1,this.snapshotCounter+=1,this.snapshotPending+=1,this.rangedSnapshotCounter>=this.rangedSnapshotsTotal[this.gridRangeCounter]&&(this.gridRangeCounter+=1,this.rangedSnapshotCounter=0,s=this.gridRanges[this.gridRangeCounter]),n+=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,Hn.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},Hn.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 fT(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,f]=v.useState(o),[C,S]=v.useState(!1),b=m!==e.name?i(m):"",w=o&&!C||b==="",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 E=()=>{w&&(s(e,m),f(!1))},y=()=>{if(o){t(e);return}g(e.name),f(!1)},R=I=>{S(!0),I.key==="Enter"&&(I.stopPropagation(),E()),I.key===" "&&I.stopPropagation(),I.key==="Escape"&&y()};return p?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"editing-container",children:[r.jsx("input",{ref:a,className:z("form-control",{"is-invalid":!w}),value:m,placeholder:"Group Name",onChange:I=>g(I.target.value),onKeyDown:R,onBlur:()=>S(!0)}),r.jsx(P,{kind:"ghost",icon:Kn,tooltip:"Confirm",onClick:E}),r.jsx(P,{kind:"ghost",icon:ug,tooltip:"Cancel",onClick:y})]}),!w&&r.jsx("p",{className:"mb-0 validate-label-error text-danger",children:b})]}):r.jsxs("div",{className:"group-name-wrapper",children:[r.jsx("span",{className:"column-name",children:m}),r.jsx(P,{className:"p-1 mx-1",kind:"ghost",icon:mo,tooltip:"Edit",onClick:()=>{f(!0)}}),r.jsxs("span",{className:"right-buttons",children:[r.jsx(P,{kind:"ghost",icon:$t,tooltip:"Delete group",onClick:()=>t(e)}),r.jsx(P,{kind:"ghost",className:"color-swatch mr-1",icon:e.color!==void 0?r.jsxs("span",{className:"fa-layers",children:[r.jsx(X,{className:"color-swatch",icon:dl,color:Ye.white,transform:"down-1"}),r.jsx(X,{className:"color-swatch",icon:dl,color:e.color,transform:"shrink-2 down-1"})]}):mg,tooltip:"Set color",onClick:()=>u(I=>!I)}),h&&r.jsxs(r.Fragment,{children:[r.jsx("input",{"aria-label":"Color input",ref:d,type:"color",list:"presetColors",value:e.color??Ye["content-bg"],style:{visibility:"hidden",width:0,height:0,padding:0,border:0},onChange:I=>{e.color=I.target.value,n(e,I.target.value)}}),r.jsxs("datalist",{id:"presetColors",children:[r.jsx("option",{children:Ye["content-bg"]}),r.jsx("option",{children:Ye.primary}),r.jsx("option",{children:Ye.foreground}),r.jsx("option",{children:Ye.green}),r.jsx("option",{children:Ye.yellow}),r.jsx("option",{children:Ye.orange}),r.jsx("option",{children:Ye.red}),r.jsx("option",{children:Ye.purple}),r.jsx("option",{children:Ye.blue}),r.jsx("option",{children:Ye["gray-400"]})]})]})]})]})}function CT(){}const ST=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:f,isVisible:C}=o.data,S=v.useRef(null),b=v.useCallback(T=>{T.buttons===1&&(l([f].flat(),!C),S.current?.focus())},[l,f,C]),w=v.useCallback(T=>{a(n,T)},[a,n]);return r.jsxs("div",{ref:t,className:z("tree-item",{isSelected:o.selected,"two-dragged":i===2,"multiple-dragged":i>2}),onClick:w,...g,children:[r.jsx(P,{ref:S,kind:"ghost",className:"px-1",onClick:CT,onMouseDown:b,onMouseEnter:b,icon:C?ur:eh,tooltip:"Toggle visibility"}),r.jsx("span",{className:z("column-name",p&&"column-group"),children:p&&!s?r.jsx(fT,{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(Je,{children:"Drag to re-order"}),r.jsx(X,{icon:Vl})]})]})}),bT=ST;function wT(c){return c.parentId!==void 0}function vT(c,e){return Math.round(c/e)}function vu(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=>vu(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:O.getVisibleIndex(o,e),isVisible:!s.has(o)}}}function TT(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=O.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=vu(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 Rl(c,e,t,n,s){const i=c.findIndex(({id:S})=>S===t),o=c.findIndex(({id:S})=>S===e),l=c[o],a=im(c,o,i),d=a[i-1],h=a[i+1],u=vT(n,s),m=l.depth+u,g=ET({previousItem:d,nextItem:h}),p=yT({nextItem:h});let f=m;return m>=g?f=g:m<p&&(f=p),{depth:f,maxDepth:g,minDepth:p,parentId:C()};function C(){return f===0||!d?null:f===d.depth?d.parentId:f>d.depth?d.id:a.slice(0,i).reverse().find(b=>b.depth===f)?.parentId??null}}function ET({previousItem:c,nextItem:e}){return Math.max(c?.depth??0,e?.depth??0)}function yT({nextItem:c}){return c?c.depth:0}function Tu(c,e=null,t=0){return c.reduce((n,s,i)=>[...n,{...s,parentId:e,depth:t,index:i},...Tu(s.children,s.id,t+1)],[])}function Qt(c){return c.every(wT)?[...c]:Tu(c)}function Eu(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=Eu(i,e);if(o)return o}}}function yu(c,e=0){return c.reduce((t,{children:n})=>n.length?yu(n,t+1):t+1,e)}function RT(c,e){const t=Eu(c,e);return t?yu(t.children):0}const xT=[In.Down,In.Right,In.Up,In.Left],IT=[In.Left,In.Right];function DT(c,e,t){return(n,{currentCoordinates:s,context:{active:i,over:o,collisionRect:l,droppableRects:a,droppableContainers:d}})=>{if(xT.includes(n.code)){if(!i||!l)return;n.preventDefault();const{current:{items:h,offset:u}}=c;if(IT.includes(n.code)&&o?.id!=null){const{depth:f,maxDepth:C,minDepth:S}=Rl(h,i.id,o.id,u,t);switch(n.code){case In.Left:if(f>S)return{...s,x:s.x-t};break;case In.Right:if(f<C)return{...s,x:s.x+t};break}return}const m=[];d.forEach(f=>{if(f?.disabled||f.id===o?.id)return;const C=a.get(f.id);if(C)switch(n.code){case In.Down:l.top<C.top&&m.push(f);break;case In.Up:l.top>C.top&&m.push(f);break}});const g=om({active:i,collisionRect:l,pointerCoordinates:null,droppableRects:a,droppableContainers:m});let p=lm(g,"id");if(p===o?.id&&g.length>1&&(p=g[1].id),p!=null&&o?.id!=null){const f=a.get(i.id),C=a.get(p),S=d.get(p);if(f&&C&&S){const b=h.findIndex(({id:y})=>y===p),w=h[b],T=h.findIndex(({id:y})=>y===i.id),E=h[T];if(w!=null&&E!=null){const{depth:y}=Rl(h,i.id,p,(w.depth-E.depth)*t,t),I=b>T?1:-1,x=e?(l.height-f.height)/2:0;return{x:C.left+y*t,y:C.top+I*x}}}}}}}class FT extends am{static activators=[{eventName:"onPointerDown",handler:({nativeEvent:e})=>!(!e.isPrimary||e.button!==0||kT(e.target))}]}const NT=["button","input","textarea","select","option"];function kT(c){return!!(c?.tagName!=null&&NT.includes(c.tagName.toLowerCase()))}function Ru(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,f)=>r.jsx("span",{className:"depth-line"},`depth-line-${f}`)),[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:z("item-wrapper",{clone:e,ghost:s,disableInteraction:n}),ref:a,children:[!e&&m,d(g)]},o)}Ru.displayName="TreeItem";const MT=({isSorting:c,wasDragging:e})=>!(c||e);function lc({id:c,depth:e,...t}){const{attributes:n,isDragging:s,isSorting:i,listeners:o,setDraggableNodeRef:l,setDroppableNodeRef:a,transform:d,transition:h}=rm({id:c,animateLayoutChanges:MT}),u=ja.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(Ru,{dragRef:l,wrapperRef:a,depth:e,ghost:s,disableInteraction:i,handleProps:g,...t})}const OT={keyframes({transform:c}){return[{opacity:1,transform:ja.Transform.toString(c.initial)},{opacity:0,transform:ja.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:ad.duration,easing:ad.easing})}};let Go=null;function AT(c){return Go==null&&c.activeNodeRect&&c.activatorEvent instanceof PointerEvent&&(Go=Math.floor((c.activatorEvent.clientY-c.activeNodeRect.top)/c.activeNodeRect.height)*c.activeNodeRect.height),c.activeNodeRect||(Go=null),{...c.transform,y:c.transform.y+(Go??0)}}function LT({items:c,renderItem:e,indentationWidth:t=30,indicator:n=!1,activeId:s,overId:i,offsetLeft:o}){const l=dm(),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?Rl(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:z("tree-container",s!=null&&"marching-ants"),children:c.map(m=>{const{id:g,depth:p}=m;return r.jsx(lc,{id:g,value:g,depth:g===s&&d?d.depth:p,item:m,renderItem:e},g)})}),cm.createPortal(r.jsx(hm,{dropAnimation:OT,modifiers:[AT],className:"visibility-ordering-list",children:s!=null&&u?r.jsx(lc,{id:s,depth:u.depth,clone:!0,childCount:RT(c,s)+1,value:s.toString(),renderItem:e,item:u}):null}),document.body)]})}const _T={droppable:{strategy:Cm.Always}},PT={activationConstraint:{distance:5}};function jT({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 I=Qt(c);return o!=null?I.filter(({id:x,selected:A})=>x===o||!A):I},[o,c]),g=o!=null&&a!=null?Rl(m,o,a,h,t):null,p=v.useRef({items:m,offset:h}),f=v.useMemo(()=>({coordinateGetter:DT(p,e,t)}),[t,e]),C=um(rd(FT,PT),rd(Sm,f)),S=v.useMemo(()=>m.map(({id:I})=>I),[m]);v.useEffect(()=>{p.current={items:m,offset:h}},[m,h]);const b=v.useCallback(({active:{id:I}})=>{l(I),d(I),n?.(I),document.body.style.setProperty("cursor","grabbing")},[n]),w=v.useCallback(({delta:I})=>{u(I.x)},[]),T=v.useCallback(({over:I})=>{d(I?.id??null)},[]),E=v.useCallback(()=>{d(null),l(null),u(0),document.body.style.setProperty("cursor","")},[]),y=v.useCallback(({active:I,over:x})=>{if(E(),g&&x){const{depth:A,parentId:k}=g,_=JSON.parse(JSON.stringify(Qt(c))),M=_.findIndex(({id:K})=>K===x.id),$=_.findIndex(({id:K})=>K===I.id),H=_[$];_[$]={...H,depth:A,parentId:k},s?.(H,{..._[M],parentId:g.parentId})}},[c,s,g,E]),R=v.useCallback(()=>{E()},[E]);return r.jsx(mm,{sensors:C,collisionDetection:gm,measuring:_T,onDragStart:b,onDragMove:w,onDragOver:T,onDragEnd:y,onDragCancel:R,children:r.jsx(pm,{items:S,strategy:fm,children:r.jsx(LT,{items:m,renderItem:i,indicator:e,indentationWidth:t,activeId:o,overId:a,offsetLeft:h})})})}function HT(c,e,t,n,s,i,o,l){const a=s.map((b,w)=>({...b,index:w}));let d=[],h=n;const u=i[0].data.visibleIndex,m=a.findIndex(({id:b})=>b===c.id),g=a.findIndex(({id:b})=>b===e.id);let p=Array.isArray(u)?u[1]+1:u+1;h=ms(i[0],e.parentId,h);for(let b=1;b<i.length;b+=1){const{data:{visibleIndex:w}}=i[b];d=O.moveItemOrRange(w,p,d,!0),p+=Array.isArray(w)?w[1]-w[0]+1:1,h=ms(i[b],e.parentId,h)}const f=[Array.isArray(u)?u[0]:u,p-1],C=Array.isArray(e.data.visibleIndex)?e.data.visibleIndex[0]:e.data.visibleIndex;let S=O.getVisibleIndex(C,d);return m>g&&S>C&&(S-=1),e.children.length>0&&(Array.isArray(u)?u[0]:u)<S&&(S-=1),f[0]<S&&(S-=f[1]-f[0]),d=O.moveItemOrRange(f,Oe(S,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 UT=150;class at 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=We(this.searchColumns,UT);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=Qt(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=Qt(this.getTreeItems());let i=this.getFirstMovableIndex(),o=this.getLastMovableIndex();D(i),D(o);const l=this.getSelectedParentItems();e===at.MOVE_OPTIONS.UP||e===at.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:f}}=l[u];switch(e){case at.MOVE_OPTIONS.TOP:{d=O.moveItemOrRange(f,i,d,!0);const C=Array.isArray(f)?f[1]-f[0]+1:1;i+=C,h=ms(l[u],null,h);break}case at.MOVE_OPTIONS.BOTTOM:{d=O.moveItemOrRange(f,o,d,!0);const C=Array.isArray(f)?f[1]-f[0]+1:1;o-=C,h=ms(l[u],null,h);break}case at.MOVE_OPTIONS.UP:{const C=s.findIndex(w=>w.id===m),S=s.map((w,T)=>T<C&&!n.has(w.id)).lastIndexOf(!0),b=s[S];if(b!=null&&b.parentId!==g)if(Math.abs(b.depth-p)>1){const w=s.map((E,y)=>y<S&&E.depth===p).lastIndexOf(!0),T=s[w];h=ms(l[u],T.id,h)}else h=ms(l[u],b.parentId,h);else{const w=Oe(Array.isArray(f)?f[0]-1:f-1,i,o);d=O.moveItemOrRange(f,w,d,!1);const T=Array.isArray(f)?f[1]-f[0]+1:1;i+=T}break}case at.MOVE_OPTIONS.DOWN:{const C=s.findIndex(T=>T.id===m),S=s.find((T,E)=>E>C&&!n.has(T.id));if(S?.parentId!==g){const T=s.find(E=>E.id===g);h=ms(l[u],T?.parentId??null,h);break}else if(S?.children.length>0){h=ms(l[u],S.id,h);break}const b=Oe(Array.isArray(f)?f[0]+1:f+1,i,o);d=O.moveItemOrRange(f,b,d,!1);const w=Array.isArray(f)?f[1]-f[0]+1:1;o-=w;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===at.MOVE_OPTIONS.TOP&&(l=()=>{this.list?.parentElement?.scroll({top:0})}),e===at.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===at.SORTING_OPTIONS.ASC;s.sort((a,d)=>{const h=a.id.toUpperCase(),u=d.id.toUpperCase();return Jt.sort(h,u,i)});let o=[...n],l=Math.min(...s.flatMap(a=>{const{modelIndex:d}=a.data;return Array.isArray(d)?O.getVisibleIndexes(d,o):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)?O.getVisibleIndexes(h,o):O.getVisibleIndex(h,o);o=Array.isArray(u)?O.moveRange([Math.min(...u),Math.max(...u)],l,o,!0):O.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=O.isModifierKeyDown(t),o=t.shiftKey,l=n.has(e),a=[e];if(l&&i){this.removeColumnFromSelected(e);return}const d=Qt(this.getTreeItems());if(l&&!o&&s===e){const h=d.find(({id:m})=>m===e);if(D(h),Qt(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);Qt(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=Qt(this.getTreeItems()),s=n.find(({id:o})=>o===e);D(s);let i=n.find(({id:o})=>o===s.parentId);for(Qt(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=Qt(this.getTreeItems()).map((g,p)=>({...g,index:p})),d=this.getFirstMovableIndex(),h=this.getLastMovableIndex();D(d),D(h);const{groups:u,movedColumns:m}=HT(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];D(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=bs((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(at.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=we(({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(bT,{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=we((e,t,n)=>{for(let s=0;s<t.length;s+=1){const i=O.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=we((e,t,n)=>{for(let s=t.length-1;s>=0;s-=1){const i=O.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=we((e,t,n,s,i)=>TT(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 Qt(this.getTreeItems()).filter(({id:n,parentId:s})=>e.has(n)&&!e.has(s??""))}makeVisibilityOrderingList=we((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=O.getModelIndex(h,n),m=e[u];s.push(this.renderImmovableItem(m.name))}return s}for(let h=0;h<i;h+=1){const u=O.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(jT,{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=O.getModelIndex(h,n),m=e[u];s.push(this.renderImmovableItem(m.name))}return s});renderImmovableItem=we(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(Qt(l).map(f=>[f.id,f.data.modelIndex])),d=new Set(t),h=[...new Set(o?[...s.values()].map(f=>a.get(f)).filter(f=>f!=null).flat():l.map(f=>f.data.modelIndex).flat())],u=h.some(f=>!d.has(f)),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(P,{kind:"ghost",className:"toggle-visibility-btn",onClick:()=>{n(h,!u)},icon:u?ur:eh,tooltip:"Toggle column visibility",children:o?g:m}),r.jsx(xi,{className:"visibility-search",value:i,matchCount:i?s.size:void 0,onChange:this.handleSearchInputChange})]}),r.jsxs("div",{className:"top-menu",children:[r.jsx(P,{kind:"ghost",icon:Gs,tooltip:"Reset to default",onClick:()=>{this.resetVisibilityOrdering()},children:"Reset"}),r.jsx("span",{className:"vertical-divider"}),r.jsx(P,{kind:"ghost",icon:cr,tooltip:"Sort ascending",onClick:()=>{this.handleSortColumns(at.SORTING_OPTIONS.ASC)}}),r.jsx(P,{kind:"ghost",icon:hr,tooltip:"Sort descending",onClick:()=>{this.handleSortColumns(at.SORTING_OPTIONS.DSC)}}),r.jsx("span",{className:"vertical-divider"}),r.jsxs(P,{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(X,{mask:gg,icon:yi,transform:"right-7 down-5 shrink-6"}),r.jsx(X,{icon:pg,transform:"right-8 down-6 shrink-8"})]}),"Group"]}),r.jsx("span",{className:"vertical-divider"}),r.jsx(P,{kind:"ghost",icon:fg,tooltip:"Move selection up",onClick:()=>{this.handleMoveColumns(at.MOVE_OPTIONS.UP)},disabled:!o}),r.jsx(P,{kind:"ghost",icon:Cg,tooltip:"Move selection down",onClick:()=>{this.handleMoveColumns(at.MOVE_OPTIONS.DOWN)},disabled:!o}),r.jsx(P,{kind:"ghost",icon:Sg,tooltip:"Move selection to top",onClick:()=>{this.handleMoveColumns(at.MOVE_OPTIONS.TOP)},disabled:!o}),r.jsx(P,{kind:"ghost",icon:bg,tooltip:"Move selection to bottom",onClick:()=>{this.handleMoveColumns(at.MOVE_OPTIONS.BOTTOM)},disabled:!o})]}),r.jsx("div",{role:"menu",className:z("visibility-ordering-list"),children:r.jsx("div",{className:"column-list",ref:f=>{this.list=f},children:p})})]})}}const BT=at;class VT extends v.PureComponent{static createSearchFilter(e,t,n,s,i){const o=i?s.filter(l=>!n.includes(l.name)).map(l=>l.name):n;if(t&&o.length>0){const l=e.FilterValue.ofString(t);return o.length===s.length?e.FilterCondition.search(l):e.FilterCondition.search(l,s.filter(d=>o.includes(d.name)).map(d=>d.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=oe.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(X,{icon:dl,mask:ga,transform:"shrink-2 down-5 right-7"}),r.jsx(X,{icon:wg,className:"text-primary",transform:"shrink-4 down-5 right-7"})]}):l?a=r.jsxs(r.Fragment,{children:[r.jsx(X,{icon:yi,mask:ga,transform:"shrink-1 down-5 right-7"}),r.jsx(X,{icon:Sd,className:"text-danger",transform:"shrink-4 down-5 right-7"})]}):a=r.jsxs(r.Fragment,{children:[r.jsx(X,{icon:dl,mask:ga,transform:"shrink-2 down-5 right-7"}),r.jsx(X,{icon:vg,className:"text-primary",transform:"shrink-4 down-5 right-7"})]}),r.jsxs("div",{className:"cross-column-container",children:[r.jsx(xi,{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(Je,{children:"Configure Columns"}),r.jsx(Ul,{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(oe.Fragment,{children:[r.jsx(tn,{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(X,{icon:Sd})," Select at least one column to search."]})]})})]})]})}}const zo=VT;const ls=J.module("PartitionSelectorSearch"),$T=150;class Ur extends v.Component{static MAX_VISIBLE_ITEMS=12;static defaultProps={initialPageSize:100,onSelect:()=>{},onListResized:()=>{}};static propTypes={getFormattedString:U.func.isRequired,table:U.shape({addEventListener:U.func.isRequired,removeEventListener:U.func.isRequired,columns:U.arrayOf(U.shape({name:U.string.isRequired,type:U.string.isRequired,filter:U.func.isRequired})),size:U.number.isRequired,applyFilter:U.func.isRequired,setViewport:U.func.isRequired}).isRequired,initialPageSize:U.number,onSelect:U.func,onListResized:U.func};static handleError(e){e instanceof Pl||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=We(()=>{this.updateFilter()},$T);focus(){this.searchInput&&this.searchInput.focus()}startListening(){const{dh:e,initialPageSize:t,table:n}=this.props;n.addEventListener(e.Table.EVENT_UPDATED,this.handleTableUpdate),n.addEventListener(e.Table.EVENT_FILTERCHANGED,this.handleFilterChange),n.setViewport(0,t)}stopListening(){const{dh:e,table:t}=this.props;t.removeEventListener(e.Table.EVENT_UPDATED,this.handleTableUpdate),t.removeEventListener(e.Table.EVENT_FILTERCHANGED,this.handleFilterChange)}updateFilter(){const{dh:e,initialPageSize:t,table:n}=this.props,{text:s}=this.state,i=s.trim(),o=[];if(i.length>0){const a=n.columns[0].filter().invoke("matches",e.FilterValue.ofString(`(?s)(?i).*\\Q${i}\\E.*`));o.push(a)}ls.debug2("updateFilter",o),n.applyFilter(o),n.setViewport(0,t)}render(){const{isLoading:e,itemCount:t,items:n,offset:s,text:i}=this.state,o=Math.min(t,Ur.MAX_VISIBLE_ITEMS)*Ei.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(Ei,{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(Nn,{})," Loading..."]})]})}}const WT=Ur;const ai=J.module("IrisGridPartitionSelector"),GT=250;class zT 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(){ai.debug2("handleAppendClick");const{onAppend:e}=this.props,{partition:t}=this.state;e(t)}handleCloseClick(){ai.debug2("handleCloseClick"),this.sendDone()}handleIgnoreClick(){ai.debug2("handleIgnoreClick"),this.sendFetchAll()}handlePartitionChange(e){ai.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=We(()=>{this.sendUpdate()},GT);sendDone(){this.debounceUpdate.flush();const{onDone:e}=this.props;e()}sendUpdate(){ai.debug2("sendUpdate");const{onChange:e}=this.props,{partition:t}=this.state;e(t)}sendFetchAll(){ai.debug2("sendFetchAll"),this.debounceUpdate.cancel();const{onFetchAll:e}=this.props;e()}render(){const{columnName:e,dh:t,getFormattedString:n,onDone:s,table:i}=this.props,{partition:o}=this.state,l=r.jsx(WT,{dh:t,getFormattedString:n,table:i,onSelect:this.handlePartitionSelect,onListResized:this.handlePartitionListResized,ref:a=>{this.selectorSearch=a}},"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:o,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(X,{icon:Vn}),r.jsx(Je,{children:"Partitions"}),r.jsx($n,{ref:a=>{this.searchMenu=a},actions:[{menuElement:l}],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:s,children:r.jsx(X,{icon:ho})})]})}}const KT=zT;const YT=J.module("SelectDistinctBuilder");class qT 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!=="");Ze(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){YT.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(P,{kind:"ghost",className:"ml-1 px-2",onClick:()=>{this.handleDeleteColumn(s)},icon:r.jsx(X,{icon:$t,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(P,{kind:"ghost",className:"btn-add-column",onClick:this.handleAddColumnClick,disabled:n,icon:Ts,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 XT=qT;function Br({items:c,onChange:e=()=>{}}){return r.jsx($c,{items:Array.from(c.entries()).map(([t,n])=>({title:Br.getAdvancedSettingsTitleForKey(t),isOn:n,onChange:s=>e(t,s)}))})}Br.getAdvancedSettingsTitleForKey=c=>{switch(c){case Ri.FILTER_CONTROL_CHANGE_CLEARS_ALL_FILTERS:return"Clear current table filters before applying new filters from a control";case Ri.LINK_CHANGE_CLEARS_ALL_FILTERS:return"Clear current table filters before applying new filters from an incoming link filter"}};const ac=J.module("ConditionalFormattingMenu"),xa=()=>{};function ZT(c){const{column:{type:e}}=c;if(F.isNumberType(e))return c.condition===je.IS_NULL||c.condition===je.IS_NOT_NULL?"":`${c.value}`;if(F.isCharType(e))return c.condition===yt.IS_NULL||c.condition===yt.IS_NOT_NULL?"":`${c.value}`;if(F.isStringType(e))return c.condition===Pt.IS_NULL||c.condition===Pt.IS_NOT_NULL?"":`"${c.value}"`;if(F.isDateType(e))return c.condition===yt.IS_NULL||c.condition===yt.IS_NOT_NULL?"":`${c.value}`;if(F.isBooleanType(e))return"";throw new Error(`Invalid column type ${e} in getRuleValue`)}function QT(c){return F.isNumberType(c.column.type)&&c.condition===je.IS_BETWEEN?`${c.start} < ${c.column.name} < ${c.end}`:`${c.column.name} ${Aw(c.column.type,c.condition)}
|
|
30
|
+
${ZT(c)}`}function JT(c){const{rules:e=[],onChange:t=xa,onCreate:n=xa,onSelect:s=xa}=c,i=v.useCallback((d,h,u)=>{d.stopPropagation(),ac.debug("Rule clicked",h,u),s(u)},[s]),o=v.useCallback((d,h,u)=>{d.stopPropagation(),ac.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(Ll,{onDragStart:hn.startDragging,onDragEnd:a,children:r.jsx(sr,{droppableId:"droppable-custom-columns",children:(d,h)=>r.jsxs("div",{ref:d.innerRef,...d.droppableProps,className:z("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(Hc,{draggableId:`${m}-${u.type}`,index:m,disableInteractiveElementBlocking:!0,children:(g,p)=>r.jsx("div",{role:"menuitem",tabIndex:0,onClick:f=>i(f,u,m),className:z("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:vl(u.config.style),color:Tl(u.config.style)},children:u.type===Fn.ROWS?"row":"col"})}),r.jsx("div",{className:"rule-title",children:QT(u.config)}),r.jsx(P,{kind:"ghost",className:"ml-1 px-2",onClick:f=>o(f,u,m),icon:$t,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(Je,{children:"Drag to re-order"}),r.jsx(X,{icon:Vl})]})]})})})},`${m}-${u.type}`)),d.placeholder]})})}),r.jsx("hr",{}),r.jsx(P,{kind:"ghost",onClick:n,icon:Ts,children:"Add New Rule"})]})}const As=J.module("ConditionEditor"),eE=()=>{},tE=[je.IS_EQUAL,je.IS_NOT_EQUAL,je.IS_BETWEEN,je.GREATER_THAN,je.GREATER_THAN_OR_EQUAL,je.LESS_THAN,je.LESS_THAN_OR_EQUAL,je.IS_NULL,je.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:bw(c)},c)),nE=[Pt.IS_EXACTLY,Pt.IS_NOT_EXACTLY,Pt.CONTAINS,Pt.DOES_NOT_CONTAIN,Pt.STARTS_WITH,Pt.ENDS_WITH,Pt.IS_NULL,Pt.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:ww(c)},c)),sE=[yt.IS_EXACTLY,yt.IS_NOT_EXACTLY,yt.IS_BEFORE,yt.IS_BEFORE_OR_EQUAL,yt.IS_AFTER,yt.IS_AFTER_OR_EQUAL,yt.IS_NULL,yt.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:vw(c)},c)),iE=[qi.IS_TRUE,qi.IS_FALSE,qi.IS_NULL,qi.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:Tw(c)},c)),oE=[Ks.IS_EQUAL,Ks.IS_NOT_EQUAL,Ks.IS_NULL,Ks.IS_NOT_NULL].map(c=>r.jsx("option",{value:c,children:Ew(c)},c));function lE(c,e,t,n){return c===je.IS_NULL||c===je.IS_NOT_NULL||c===je.IS_BETWEEN&&t!=null&&t!==""&&!Number.isNaN(Number.parseFloat(t))&&n!=null&&n!==""&&!Number.isNaN(Number.parseFloat(n))||c!==je.IS_BETWEEN&&e!==void 0&&e!==""&&!Number.isNaN(Number.parseFloat(e))}function aE(c,e,t,n,s,i,o){switch(c){case je.IS_EQUAL:case je.IS_NOT_EQUAL:case je.GREATER_THAN:case je.GREATER_THAN_OR_EQUAL:case je.LESS_THAN:case je.LESS_THAN_OR_EQUAL:return r.jsx("input",{type:"number",className:"form-control",placeholder:"Enter value",value:s??"",onChange:e});case je.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 je.IS_NULL:case je.IS_NOT_NULL:return null}}function rE(c,e,t){switch(c){case Pt.IS_NULL:case Pt.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 yt.IS_NULL:case yt.IS_NOT_NULL:return null;default:return r.jsx("input",{type:"text",className:"form-control",placeholder:"Enter value",value:t??"",onChange:e})}}function cE(){return null}function hE(c,e,t){switch(c){case Ks.IS_NULL:case Ks.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 xu(c){const{column:e,config:t,dh:n,onChange:s=eE}=c,i=e.type,[o,l]=v.useState(i),[a,d]=v.useState(t.condition),[h,u]=v.useState(t.value),[m,g]=v.useState(t.start),[p,f]=v.useState(t.end);i!==o&&(d(uu(i)),u(mu(i)),g(void 0),f(void 0),l(i));const C=v.useMemo(()=>{if(i===void 0)return[];if(F.isNumberType(i))return tE;if(F.isCharType(i))return oE;if(F.isStringType(i))return nE;if(F.isDateType(i))return sE;if(F.isBooleanType(i))return iE},[i]),S=v.useCallback(y=>{const{value:R}=y.target;As.debug("handleConditionChange",R),d(R)},[]),b=v.useCallback(y=>{const{value:R}=y.target;As.debug("handleValueChange",R),u(R)},[]),w=v.useCallback(y=>{const{value:R}=y.target;As.debug("handleStartValueChange",R),g(R)},[]),T=v.useCallback(y=>{const{value:R}=y.target;As.debug("handleEndValueChange",R),f(R)},[]);v.useEffect(function(){let R=!0;a===void 0?(As.debug("Unable to create formatting rule. Condition is not selected."),R=!1):F.isNumberType(e.type)&&!lE(a,h,m,p)?(As.debug("Unable to create formatting rule. Invalid value",h),R=!1):F.isDateType(e.type)&&!_w(n,a,h)&&(As.debug("Unable to create formatting rule. Invalid date condition",h),R=!1),s({condition:a,value:h,start:m,end:p},R)},[s,e.type,n,a,h,m,p]);const E=v.useMemo(()=>{if(i===void 0)return null;if(F.isNumberType(i))return aE(a,b,w,T,h,m,p);if(F.isCharType(i))return hE(a,b,h);if(F.isStringType(i))return rE(a,b,h);if(F.isDateType(i))return dE(a,b,h);if(F.isBooleanType(i))return cE()},[i,a,h,m,p,b,w,T]);return r.jsxs("div",{className:"condition-editor mb-2",children:[r.jsx("select",{value:a,id:"condition-select",className:"custom-select mb-2",onChange:S,children:C}),E]})}const uE=J.module("StyleEditor"),mE="#fcfcfa",gE="#f0f0ee",pE="#1a171a",fE=200,CE=()=>{};function Iu(c){const{config:e,onChange:t=CE}=c,[n,s]=v.useState(e.type),[i,o]=v.useState(e.customConfig?.background??mE),[l,a]=v.useState(!1),[d,h]=v.useState(fE),u=v.useRef(null),m=v.useCallback(w=>{const{value:T}=w.target;uE.debug("handleBackgroundChange",T),o(T)},[]),g=v.useCallback(()=>{l&&a(!1)},[l]),p=v.useCallback(()=>{l||C(),a(!l)},[l]),f=v.useMemo(()=>[sn.NO_FORMATTING,sn.POSITIVE,sn.NEGATIVE,sn.WARN,sn.NEUTRAL,sn.ACCENT_1,sn.ACCENT_2,sn.CUSTOM],[]);function C(){u.current&&h(u.current.getBoundingClientRect().width)}v.useEffect(function(){t({type:n,customConfig:{color:ih.isDark(i)?gE:pE,background:i}})},[t,n,i]);const S=v.useCallback(()=>{const w=[];for(let T=0;T<f.length;T+=1){const E=f[T],y=`option-${T}-${E}`;w.push(r.jsxs(P,{kind:"inline",className:"style-option-btn",onClick:()=>{s(E),a(!1)},style:{color:Tl({type:E}),background:vl({type:E})},children:[E===n&&r.jsx(X,{icon:Kn,className:"mr-2"}),E!==n&&r.jsx("span",{className:"mr-4"}),Zd(E)]},y))}return w},[f,n]),b=v.useCallback(()=>r.jsx("div",{className:"style-menu-container",role:"presentation",style:{width:d},children:r.jsx("div",{className:"style-options",children:S()})}),[d,S]);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(P,{kind:"inline",className:"cs-dropdown",style:{color:Tl({type:n}),background:vl({type:n})},onClick:p,children:[Zd(n),r.jsx("span",{children:r.jsx(X,{icon:Tg,className:"cs-caret"})}),r.jsx($n,{isShown:l,actions:{menuElement:b()},popperOptions:{placement:"bottom-start"},popperClassName:"style-dropdown-menu",onMenuClosed:g,menuStyle:{maxWidth:"100rem"}})]})]}),n===sn.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 Bi=J.module("ColumnFormatEditor"),SE=()=>{};function bE(c){const{type:e,name:t}=c[0];return{column:{type:e,name:t},style:pu(),...ta(e)}}function wE(c){const{columns:e,config:t=bE(e),dh:n,onChange:s=SE}=c,[i,o]=v.useState(e.find(S=>S.name===t.column.name&&S.type===t.column.type)??e[0]),[l,a]=v.useState(gu(t)),[d,h]=v.useState(!1),[u,m]=v.useState(t.style),g=v.useCallback(S=>{const b=e.find(({name:w})=>w===S);b!==void 0?(o(b),i.type!==b.type&&(a(ta(b.type)),h(!1))):Bi.error(`Column ${S} not found.`)},[e,i]),p=v.useCallback((S,b)=>{Bi.debug("handleConditionChange",S,b),a(S),h(b)},[]),f=v.useCallback(S=>{Bi.debug("handleStyleChange",S),m(S)},[]);v.useEffect(function(){let b=d;i===void 0&&(Bi.debug("Column is not selected, invalidating update."),b=!1),(u===void 0||u.type===sn.NO_FORMATTING)&&(Bi.debug("Style is not selected, invalidating update."),b=!1);const{type:w,name:T}=i;s({column:{type:w,name:T},style:u,...l},b)},[s,i,u,l,d]);const C=e.map(({name:S})=>({title:S,value:S}));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(Wc,{defaultValue:i?.name,options:C,inputPlaceholder:"Select a column",spellCheck:!1,onChange:g,searchPlaceholder:"Filter columns"})]}),i!==void 0&&r.jsxs(r.Fragment,{children:[r.jsx(xu,{dh:n,column:i,config:l,onChange:p}),r.jsx(Iu,{config:u,onChange:f})]})]})}const Vi=J.module("RowFormatEditor"),vE=()=>{};function TE(c){const{type:e,name:t}=c[0];return{column:{type:e,name:t},style:pu(),...ta(e)}}function EE(c){const{columns:e,config:t=TE(e),dh:n,onChange:s=vE}=c,[i,o]=v.useState(e.find(S=>S.name===t.column.name&&S.type===t.column.type)??e[0]),[l,a]=v.useState(gu(t)),[d,h]=v.useState(!1),[u,m]=v.useState(t.style),g=v.useCallback(S=>{const b=e.find(({name:w})=>w===S);b!==void 0?(o(b),i.type!==b.type&&(a(ta(b.type)),h(!1))):Vi.error(`Column ${S} not found.`)},[e,i]),p=v.useCallback((S,b)=>{Vi.debug("handleConditionChange",S,b),a(S),h(b)},[]),f=v.useCallback(S=>{Vi.debug("handleStyleChange",S),m(S)},[]);v.useEffect(function(){if(i===void 0){Vi.debug("Column is not selected, skip update.");return}if(u===void 0){Vi.debug("Style is not selected, skip update.");return}const{type:b,name:w}=i;s({column:{type:b,name:w},style:u,...l},d)},[s,i,u,l,d]);const C=e.map(({name:S})=>({title:S,value:S}));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(Wc,{defaultValue:i?.name,options:C,inputPlaceholder:"Select a column",spellCheck:!1,onChange:g,searchPlaceholder:"Filter columns"})]}),i!==void 0&&r.jsxs(r.Fragment,{children:[r.jsx(xu,{column:i,config:l,dh:n,onChange:p}),r.jsx(Iu,{config:u,onChange:f})]})]})}const Ia=J.module("ConditionalFormatEditor"),Da=()=>{};function yE(c){switch(c){case Fn.CONDITIONAL:return r.jsx(nT,{});case Fn.ROWS:return r.jsx(sT,{})}}function RE(c){switch(c){case Fn.CONDITIONAL:return"Conditional";case Fn.ROWS:return"Rows"}}const rc=[Fn.CONDITIONAL,Fn.ROWS];function xE(c){const{columns:e,dh:t,onSave:n=Da,onUpdate:s=Da,onCancel:i=Da,rule:o}=c,l=e.filter(Pw),[a,d]=v.useState(o?.type??rc[0]),[h,u]=v.useState(o),[m,g]=v.useState(!1),p=v.useCallback(()=>{i()},[i]),f=v.useCallback(()=>{if(h===void 0){Ia.error("Rule is not defined.");return}n(h)},[n,h]),C=v.useCallback(b=>{Ia.debug("handleFormatterChange",b),d(b)},[]),S=v.useCallback((b,w)=>{Ia.debug("handleRuleChange",b,w,a);const T={type:a,config:b};u(T),g(w),s(w?T:void 0)},[s,a]);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:rc.map((b,w)=>r.jsx("div",{className:"formatter-type",children:r.jsxs("button",{type:"button",className:z("btn","btn-icon","btn-formatter-type",{active:b===a}),"data-index":w,onClick:()=>C(b),children:[yE(b),RE(b)]})},b))})]}),a===Fn.CONDITIONAL&&r.jsx(wE,{columns:l,dh:t,config:h?.config,onChange:S}),a===Fn.ROWS&&r.jsx(EE,{columns:l,config:h?.config,dh:t,onChange:S}),r.jsx("hr",{}),r.jsxs("div",{className:"d-flex justify-content-end my-3",children:[r.jsx(P,{kind:"secondary",onClick:p,className:"mr-2",children:"Cancel"}),r.jsx(P,{kind:"primary",onClick:f,disabled:h===void 0||!m,children:"Done"})]})]})}function IE({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 f(){const w=g.current?.getModel();!u||!w||(d?(w.setValue(c),h(!1)):(w.setValue(JSON.stringify(JSON.parse(c),void 0,2)),h(!0)),C())}function C(){const w=g.current;w&&a((w.getModel()?.getLineCount()??0)>1)}function S(){n&&(g.current=void 0,t())}function b(w){g.current=w,o(w.getContentHeight()),w.onDidContentSizeChange(({contentHeight:T})=>o(T)),C()}return!e&&!n?null:r.jsxs($l,{isOpen:e,centered:!0,keyboard:!0,toggle:S,onOpened:()=>s(!0),onClosed:()=>{s(!1),o(0)},className:"theme-bg-dark cell-overflow-modal",size:"xl",children:[r.jsxs(Wl,{toggle:t,children:[r.jsx("h5",{className:"overflow-modal-title",children:"Cell Contents"}),r.jsx(jl,{kind:"inline",tooltip:"Copy cell contents",copy:g.current?.getValue()??c}),r.jsx(P,{kind:"inline",active:l,icon:Eg,tooltip:"Toggle line numbers",onClick:p}),u&&r.jsx(P,{kind:"inline",icon:yg,active:d,tooltip:"Format as JSON",onClick:f})]}),r.jsx(Gl,{style:{height:i},children:r.jsx(fr,{onEditorInitialized:b,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 DE(c){return c.model!==void 0}const FE="###,##0";function NE({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:f,onGotoValueSelectedFilterChanged:C,onGotoValueChanged:S,onGotoValueSubmit:b}){const w=v.useRef(null),T=v.useRef(null),[E,y]=v.useState(!1);let R=[];DE(d)&&d.table!==void 0&&({columns:R}=d.table);const I="Row number",{dh:x,rowCount:A}=d,k=W=>{W.key==="Enter"?(W.stopPropagation(),W.preventDefault(),b()):(W.key==="Backspace"||W.key==="Delete")&&(g===`${Number.POSITIVE_INFINITY}`||g===`${Number.NEGATIVE_INFINITY}`)&&L("")},_=W=>{W.key==="Enter"&&(W.stopPropagation(),W.preventDefault(),b(W.shiftKey))},M=d.getColumnIndexByName(m),H=R[M??0]?.type,K=F.getNormalizedType(H),L=W=>{S(W??"")},G=()=>{E&&document.activeElement!==w.current?w.current?.select():!E&&document.activeElement!==T.current&&T.current?.select()};v.useEffect(G,[E,c,g]);const ee=()=>{switch(K){case F.dataType.DECIMAL:case F.dataType.INT:return r.jsx("div",{className:"goto-row-input",children:r.jsx("input",{ref:T,className:z("form-control",{"is-invalid":t!==""}),onKeyDown:k,placeholder:"value",onChange:W=>{const j=W.target.value.toLowerCase();/^-?[0-9]*\.?[0-9]*$/.test(W.target.value)?L(W.target.value):j==="-i"||j==="-infinity"?L(`${Number.NEGATIVE_INFINITY}`):(j==="i"||j==="infinity")&&L(`${Number.POSITIVE_INFINITY}`)},value:g})});case F.dataType.DATETIME:return r.jsx("div",{className:"goto-value-date-time-input",children:r.jsx(km,{ref:T,className:z("form-control","goto-value-date-time-input",{"is-invalid":t!==""}),defaultValue:g,onChange:L,onSubmit:_})});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:W=>{C(W.target.value)},value:p,children:[r.jsx("option",{value:pe.eq,children:"Equals"},pe.eq),r.jsx("option",{value:pe.contains,children:"Contains"},pe.contains),r.jsx("option",{value:pe.eqIgnoreCase,children:"EqIgnoreCase"},pe.eqIgnoreCase)]})}),r.jsx("div",{className:"goto-row-input",children:r.jsx("input",{ref:T,className:z("form-control",{"is-invalid":t!==""}),onKeyDown:_,placeholder:"value",onChange:W=>L(W.target.value),value:g})})]});case F.dataType.BOOLEAN:return r.jsx("div",{className:"goto-row-input",children:r.jsxs("select",{className:"custom-select",onChange:W=>{L(W.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:_,placeholder:"value",onChange:W=>L(W.target.value),value:g})})}};return r.jsx(na,{isShown:s,className:z("goto-row"),onEntering:i,onEntered:()=>{o(),G()},onExiting:l,onExited:a,children:r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"goto-row-row",children:[r.jsxs("div",{className:z("goto-row-wrapper",{"is-inactive":!E}),onClick:()=>y(!0),onFocus:()=>y(!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:w,type:"number",onKeyDown:W=>{W.key==="Enter"&&(W.stopPropagation(),W.preventDefault(),n())},className:z("form-control",{"is-invalid":e!==""}),placeholder:I,onChange:W=>{h(W)},value:c})}),r.jsxs("div",{className:"goto-row-text",children:["of ",x.i18n.NumberFormat.format(FE,A)]}),e&&r.jsx("div",{className:"text-danger",children:e})]}),r.jsx("div",{className:"goto-row-close",children:r.jsx(P,{kind:"ghost",onClick:u,children:r.jsx(X,{icon:ho,style:{marginRight:"0"}})})})]}),d.isSeekRowAvailable&&r.jsx("div",{className:"goto-row-row",children:r.jsxs("div",{className:z("goto-row-wrapper",{"is-inactive":E}),onClick:()=>y(!1),onFocus:()=>y(!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:W=>{const j=W.target.value;f(j)},value:m,children:R.map(W=>r.jsx("option",{value:W.name,children:W.name},W.name))})}),ee(),r.jsxs("div",{children:[r.jsx(P,{kind:"ghost",disabled:g==="",onClick:()=>{b(!0)},children:r.jsx(X,{icon:th})}),r.jsx(P,{kind:"ghost",disabled:g==="",onClick:()=>{b(!1)},children:r.jsx(X,{icon:Rg})})]}),t&&r.jsx("div",{className:"text-danger",children:t})]})})]})})}const re=J.module("IrisGrid"),kE=500,ME=250,OE=250,AE=250,dc=Object.freeze({aggregations:Ie,showOnTop:!1}),LE="yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS z";function cc({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 pi extends v.Component{static minDebounce=150;static maxDebounce=500;static loadingSpinnerDelay=800;static defaultProps={children:null,advancedFilters:jn,advancedSettings:jn,alwaysFetchColumns:Ie,conditionalFormats:Ie,customColumnFormatMap:jn,isFilterBarShown:!1,applyInputFiltersOnInit:!1,movedColumns:Ie,movedRows:Ie,inputFilters:Ie,customFilters:Ie,onCreateChart:void 0,onColumnSelected:()=>{},onDataSelected:()=>{},onError:()=>{},onStateChange:()=>{},onPartitionAppend:()=>{},onAdvancedSettingsChange:()=>{},partition:null,partitionColumn:null,quickFilters:jn,selectDistinctColumns:Ie,sorts:Ie,reverseType:F.REVERSE_TYPE.NONE,customColumns:Ie,aggregationSettings:dc,rollupConfig:void 0,userColumnWidths:jn,userRowHeights:jn,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:jn,getDownloadWorker:void 0,settings:{timeZone:"America/New_York",defaultDateTimeFormat:Zs.FULL_DATE_FORMAT,showTimeZone:!1,showTSeparator:!0,truncateNumbersWithPound:!1,formatter:Ie,decimalFormatOptions:U.shape({defaultFormatString:U.string}),integerFormatOptions:U.shape({defaultFormatString:U.string})},canCopy:!0,canDownloadCsv:!0,frozenColumns:null,theme:tc,canToggleSearch:!0};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 qn,this.globalColumnFormats=Ie,this.decimalFormatOptions={},this.integerFormatOptions={},this.truncateNumbersWithPound=!1,this.renderer=new Pv,this.tableSaver=null,this.crossColumnRef=oe.createRef(),this.isAnimating=!1,this.filterInputRef=oe.createRef(),this.toggleFilterBarAction={action:()=>this.toggleFilterBar(),shortcut:Ht.TABLE.TOGGLE_QUICK_FILTER},this.toggleSearchBarAction={action:()=>this.toggleSearchBar(),shortcut:Ht.TABLE.TOGGLE_SEARCH},this.toggleGotoRowAction={action:()=>this.toggleGotoRow(),shortcut:Ht.TABLE.GOTO_ROW},this.discardAction={action:()=>{const{model:G}=this.props;ze(G)&&G.isEditable&&G.pendingDataMap.size>0&&this.discardPending().catch(re.error)},shortcut:Ht.INPUT_TABLE.DISCARD},this.commitAction={action:()=>{const{model:G}=this.props;ze(G)&&G.isEditable&&G.pendingDataMap.size>0&&G.pendingDataErrors.size===0&&this.commitPending().catch(re.error)},shortcut:Ht.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:f,searchValue:C,selectedSearchColumns:S,invertSearchColumns:b,advancedFilters:w,quickFilters:T,selectDistinctColumns:E,pendingDataMap:y,canCopy:R,frozenColumns:I,columnHeaderGroups:x}=e,A=[new sv(this),new ov(this)];R&&A.push(new Qw(this));const{dh:k}=l,_=[new av(this),new yv(this),new Nv(this),new dv(this),new hv(this),new xv(this),new Tv(this),new Sv(this,k),new wv(this),new Dv(this)],M=a.length>0?a:l.initialMovedColumns,$=d.length>0?d:l.initialMovedRows,H=new Av({userColumnWidths:new Map(g),userRowHeights:new Map(p),movedColumns:M,initialColumnWidths:new Map(l?.layoutHints?.hiddenColumns?.map(G=>[l.getColumnIndexByName(G),0]))}),K=S??[],L=zo.createSearchFilter(k,C,K,l.columns,b);this.tableUtils=new F(k),this.state={isFilterBarShown:i,isSelectingPartition:o,focusedFilterBarColumn:null,metricCalculator:H,metrics:void 0,keyHandlers:A,mouseHandlers:_,partition:h,partitionColumn:u,partitionTable:null,partitionFilters:[],quickFilters:T?new Map(T):new Map,advancedFilters:new Map(w),shownAdvancedFilter:null,hoverAdvancedFilter:null,sorts:[],reverseType:F.REVERSE_TYPE.NONE,customColumns:[],selectDistinctColumns:E,selectedRanges:[],copyOperation:null,loadingText:null,loadingScrimProgress:null,loadingSpinnerShown:!1,movedColumns:M,movedRows:$,shownColumnTooltip:null,formatter:new gn(k),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:f,searchFilter:L,searchValue:C,selectedSearchColumns:K,invertSearchColumns:b,rollupConfig:m,rollupSelectedColumns:[],aggregationSettings:t,selectedAggregation:null,openOptions:[],pendingRowCount:0,pendingDataMap:y??new Map,pendingDataErrors:new Map,pendingSavePromise:null,pendingSaveError:null,toastMessage:null,frozenColumns:I,showOverflowModal:!1,overflowText:"",overflowButtonTooltipProps:null,expandCellTooltipProps:null,expandTooltipDisplayValue:"expand",linkHoverTooltipProps:null,linkHoverDisplayValue:"",isGotoShown:!1,gotoRow:"",gotoRowError:"",gotoValueError:"",gotoValueSelectedColumnName:l.columns[0]?.name??"",gotoValueSelectedFilter:pe.eq,gotoValue:"",columnHeaderGroups:x??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(Ri.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(f=>f.loadingScrimProgress==null?(re.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;tableUtils;getAdvancedMenuOpenedHandler=we(e=>this.handleAdvancedMenuOpened.bind(this,e),{max:100});getCachedAdvancedFilterMenuActions=we((e,t,n,s,i)=>r.jsx(Kv,{model:e,column:t,onFilterChange:this.handleAdvancedFilterChange,onSortChange:this.handleAdvancedFilterSortChange,onDone:this.handleAdvancedFilterDone,options:n,sortDirection:s,formatter:i,tableUtils:this.tableUtils}),{max:50});getCachedOptionItems=we((e,t,n,s,i,o,l,a,d,h,u,m,g,p,f,C)=>{const S=[];return e&&S.push({type:xe.CHART_BUILDER,title:"Chart Builder",icon:xg}),S.push({type:xe.VISIBILITY_ORDERING_BUILDER,title:"Organize Columns",icon:ur}),n&&S.push({type:xe.CONDITIONAL_FORMATTING,title:"Conditional Formatting",icon:mo}),t&&S.push({type:xe.CUSTOM_COLUMN_BUILDER,title:"Custom Columns",icon:Ig}),s&&S.push({type:xe.ROLLUP_ROWS,title:"Rollup Rows",icon:nh}),i&&S.push({type:xe.AGGREGATIONS,title:"Aggregate Columns",icon:Dg}),o&&S.push({type:xe.SELECT_DISTINCT,title:"Select Distinct Values",icon:Fg}),l&&g&&S.push({type:xe.TABLE_EXPORTER,title:"Download CSV",icon:Ng}),C&&S.push({type:xe.ADVANCED_SETTINGS,title:"Advanced Settings",icon:kg}),S.push({type:xe.QUICK_FILTERS,title:"Quick Filters",subtitle:a.shortcut.getDisplayText(),icon:rl,isOn:u,onChange:a.action}),p&&S.push({type:xe.SEARCH_BAR,title:"Search Bar",subtitle:d.shortcut.getDisplayText(),icon:Mg,isOn:m,onChange:d.action}),S.push({type:xe.GOTO,title:"Go to",subtitle:h.shortcut.getDisplayText(),icon:Og,isOn:f,onChange:h.action}),Object.freeze(S)},{max:1});getCachedHiddenColumns=we((e,t)=>Ce.getHiddenColumns(new Map([...e.initialColumnWidths,...t])),{max:1});getAggregationMap=we((e,t)=>{const n={};return t.forEach(({operation:s,selected:i,invert:o})=>{n[s]=ps.getOperationColumnNames(e,s,i,o)}),n});getOperationMap=we((e,t)=>{const n={};return t.filter(s=>!ps.isRollupOperation(s.operation)).forEach(({operation:s,selected:i,invert:o})=>{ps.getOperationColumnNames(e,s,i,o).forEach(l=>{const a=[...n[l]??[],s];n[l]=Object.freeze(a)})}),n});getOperationOrder=we(e=>e.map(t=>t.operation).filter(t=>!ps.isRollupOperation(t)));getCachedFormatColumns=we((e,t,n)=>Lw(e,t,n));getCachedPreviewFormatColumns=we((e,t,n,s,i)=>{if(re.debug("getCachedPreviewFormatColumns",n,s,i),s!==void 0&&i!==void 0){const o=[...n];return o[i]=s,this.getCachedFormatColumns(e,t,o)}return this.getCachedFormatColumns(e,t,n)});getModelRollupConfig=we((e,t,n)=>Ce.getModelRollupConfig(e,t,n));getModelTotalsConfig=we((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=we((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=we((e,t,n,s,i)=>[...e??[],...s??[],...Ce.getFiltersFromFilterMap(t),...Ce.getFiltersFromFilterMap(n),...i!==void 0?[i]:[]],{max:1});getCachedTheme=we((e,t,n)=>({...tc,...e,autoSelectRow:!t,rowFooterWidth:n>0?e.rowFooterWidth:0}),{max:1});getValueForCell(e,t,n=!1){const{model:s}=this.props,{dh:i}=s,o=this.getModelColumn(e),l=this.getModelRow(t);if(n&&o!=null&&l!=null){const a=s.valueForCell(o,l);if(F.isDateType(s.columns[o].type)){const{formatter:d}=s;return i.i18n.DateTimeFormat.format(LE,a,i.i18n.TimeZone.getTimeZone(d.timeZone))}return a}return n?null:o!=null&&l!=null?s.textForCell(o,l):""}getModelColumn(e){const{metrics:t}=this.state;D(t);const{modelColumns:n}=t;return n==null?null:e!=null?n.get(e):null}getModelRow(e){const{metrics:t}=this.state;D(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,(ze(e)&&e.isEditable)??!1,e.floatingTopRowCount+e.floatingBottomRowCount)}getVisibleColumn(e){const{movedColumns:t}=this.state;return O.getVisibleIndex(e,t)}makeQuickFilter(e,t,n){try{return this.tableUtils.makeQuickFilter(e,t,n)}catch(s){re.error("Error creating quick filter",s)}return null}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):re.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 re.debug2("Ignoring change to existing filter"),!1}return n.set(e,{text:t,filter:this.makeQuickFilter(o,t,i.timeZone)}),!0}return n.delete(e)}setAdvancedFilterMap(e){this.setState({advancedFilters:e})}setAdvancedFilter(e,t,n){re.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){re.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){re.debug("setFilterMap",e);const{advancedSettings:t}=this.props;(t.get(Ri.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);D(d);const h=Ce.combineFiltersFromList(i,o);if(h.length===0)this.removeQuickFilter(d);else{const{formatter:u}=s;this.setQuickFilter(d,this.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(){re.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(){re.debug("Clearing cross-column search"),this.setState({searchValue:"",searchFilter:void 0})}clearGridInputField(){this.filterInputRef.current!=null&&this.filterInputRef.current.setValue("")}rebuildFilters(){re.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=this.tableUtils.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:this.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=Wn.getColumnFormats(e),s=Wn.getDateTimeFormatterOptions(e),i=e?.defaultDecimalFormatOptions??{},o=e?.defaultIntegerFormatOptions??{},l=e?.truncateNumbersWithPound??!1,a=!Ze(this.globalColumnFormats,n),d=!Ze(this.dateTimeFormatterOptions,s),h=!Ze(this.decimalFormatOptions,e?.defaultDecimalFormatOptions),u=!Ze(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=we((e,t,n,s,i,o)=>{const l=[];for(let d=0;d<s;d+=1)l.push(t[O.getModelIndex(d,n)].name);for(let d=0;d<i;d+=1)l.push(t[O.getModelIndex(t.length-1-d,n)].name);if(o)for(let d=o[0];d<=o[1];d+=1)l.push(t[O.getModelIndex(d,n)].name);const a=new Set([...e,...l]);return Object.freeze([...a])});updateFormatter(e,t=!0){const{customColumnFormatMap:n}=this.state,{model:s}=this.props,i={customColumnFormatMap:n,...e},o=[...this.globalColumnFormats??[],...i.customColumnFormatMap.values()],l=new gn(s.dh,o,this.dateTimeFormatterOptions,this.decimalFormatOptions,this.integerFormatOptions,this.truncateNumbersWithPound);re.debug("updateFormatter",this.globalColumnFormats,o),this.setState({...i,formatter:l},()=>{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=zo.createSearchFilter(s.dh,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 re.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{model:n}=this.props,i=[t.filter().eq(n.dh.FilterValue.ofString(e))];this.setState({partition:e,partitionFilters:i})}copyCell(e,t,n=!1){const{canCopy:s}=this.props;if(s){const i=String(this.getValueForCell(e,t,n));co(i).catch(o=>re.error("Unable to copy cell",o))}else re.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:Q.boundedRanges(e,i.columnCount,i.rowCount),includeHeaders:t,formatValues:n,movedColumns:a,userColumnWidths:d,error:s};this.setState({copyOperation:h})}else re.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;D(s),D(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})},pi.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){re.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 re.debug("remove all sorts, filters, and custom columns"),this.setState({advancedFilters:new Map,aggregationSettings:dc,customColumns:[],quickFilters:new Map,reverseType:F.REVERSE_TYPE.NONE,rollupConfig:void 0,selectDistinctColumns:[],sorts:[]})}canRollback(){return this.lastLoadedConfig!=null||!cc(this.state)}startListening(e){e.addEventListener(ge.EVENT.UPDATED,this.handleUpdate),e.addEventListener(ge.EVENT.REQUEST_FAILED,this.handleRequestFailed),e.addEventListener(ge.EVENT.COLUMNS_CHANGED,this.handleCustomColumnsChanged),e.addEventListener(ge.EVENT.PENDING_DATA_UPDATED,this.handlePendingDataUpdated)}stopListening(e){e.removeEventListener(ge.EVENT.UPDATED,this.handleUpdate),e.removeEventListener(ge.EVENT.REQUEST_FAILED,this.handleRequestFailed),e.removeEventListener(ge.EVENT.COLUMNS_CHANGED,this.handleCustomColumnsChanged),e.removeEventListener(ge.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=O.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;D(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();D(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(O.getModelIndex(e,n),0),this.grid?.forceUpdate()}freezeColumnByColumnName(e){const{frozenColumns:t,movedColumns:n}=this.state,{model:s}=this.props;re.debug2("freezing column",e);const i=t==null?new Set(s.frozenColumns):new Set(t);i.add(e);const o=s.getColumnIndexByName(e);D(o);const l=O.getVisibleIndex(o,n),a=O.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;re.debug2("unfreezing column",e);const i=t==null?new Set(s.frozenColumns):new Set(t);i.delete(e);const o=s.getColumnIndexByName(e);D(o);const l=O.getVisibleIndex(o,n),a=O.moveItem(l,i.size+s.frontColumns.length,n);this.setState({frozenColumns:[...i],movedColumns:a})}handleColumnVisibilityChanged(e,t){const{metricCalculator:n,metrics:s}=this.state;D(s),t?e.forEach(i=>{const o=n.initialColumnWidths.get(i),l=N(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;D(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=We((e,t,n,s)=>{const{model:i}=this.props,o=zo.createSearchFilter(i.dh,e,t,n,s);this.setState({searchFilter:o})},ME);handleAnimationLoop(){this.grid?.updateCanvas(),this.isAnimating&&(this.animationFrame=requestAnimationFrame(this.handleAnimationLoop))}handleAnimationStart(){re.debug2("handleAnimationStart"),this.isAnimating=!0,this.animationFrame=requestAnimationFrame(this.handleAnimationLoop)}handleAnimationEnd(){re.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(be.isCanceled(e))return;re.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){re.info("Toggling sort for column",e);const{model:n}=this.props,{sorts:s}=this.state,i=this.getModelColumn(e);D(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){D(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,{dh:n}=e,s=e?.layoutHints?.searchDisplayMode;return s===n.SearchDisplayMode?.SEARCH_DISPLAY_HIDE?!1:s===n.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=Ce.convertValueToText(h,d);this.setState({isGotoShown:!s,gotoRow:`${i}`,gotoValue:u,gotoValueSelectedColumnName:a,gotoRowError:"",gotoValueError:""})}async commitPending(){const{model:e}=this.props;if(!ze(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 wi("Current input is invalid");this.grid?.focus()}const s=this.pending.add(e.commitPending()).then(()=>{this.setState({pendingSaveError:null,pendingSavePromise:null})}).catch(i=>{be.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),f=Pe(n)&&n.isRowExpandable(t),C=i.find(S=>S.name===h)!=null;o[h]={value:m,text:g,type:u,isGrouped:C,isExpandable:f,visibleIndex:p}}const{onDataSelected:l}=this.props;l(t,o)}handleAdvancedFilterChange(e,t,n){const{model:s}=this.props,i=s.getColumnIndexByName(e.name);D(i),this.setAdvancedFilter(i,t,n)}handleAdvancedFilterSortChange(e,t,n=!1){const{model:s}=this.props,i=s.getColumnIndexByName(e.name);D(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);re.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){re.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);D(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;D(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);D(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(re.error("request failed:",t.detail),this.stopLoading(),this.canRollback())this.startLoading("Rolling back changes...",!0),this.rollback();else{re.error("Table failed and unable to rollback");const{onError:n}=this.props;n(new Error(`Error displaying table: ${t.detail}`))}}handleUpdate(){this.stopLoading(),re.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};cc(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(ze(t)&&t.isEditable){D(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){D(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:Ce.parseColumnHeaderGroups(t,e).groups},()=>this.grid?.forceUpdate())}handleTooltipRef(e){e?.startTimer(),this.tooltip=e}handleConditionalFormatsChange(e){re.debug("Updated conditional formats",e),this.setState({conditionalFormats:e})}handleConditionalFormatCreate(){re.debug("Create new conditional format");const{openOptions:e,conditionalFormats:t}=this.state;this.setState({openOptions:[...e,{type:xe.CONDITIONAL_FORMATTING_EDIT,title:"Create Formatting Rule"}],conditionalFormatEditIndex:t.length,conditionalFormatPreview:void 0})}handleConditionalFormatEdit(e){re.debug("Edit conditional format",e);const{openOptions:t,conditionalFormats:n}=this.state;this.setState({openOptions:[...t,{type:xe.CONDITIONAL_FORMATTING_EDIT,title:"Edit Formatting Rule"}],conditionalFormatEditIndex:e,conditionalFormatPreview:{...n[e]}})}handleConditionalFormatEditorUpdate=We(e=>{this.setState({conditionalFormatPreview:e})},AE);handleConditionalFormatEditorSave(e){re.debug("Save conditional format changes",e),this.setState(t=>{if(t.conditionalFormatEditIndex===null)return re.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){re.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=Ce.getRemovedCustomColumnNames(d,e);if(h.length>0){const u=Ce.removeSortsInColumns(s,h),m=Ce.removeFiltersInColumns(a,i,h),g=Ce.removeFiltersInColumns(a,o,h),p=Ce.removeColumnFromMovedColumns(a,n,h),f=Ce.removeColumnsFromSelectDistinctColumns(l,h);u.length!==s.length&&(re.debug("removing sorts from removed custom columns..."),this.setState({sorts:u})),(m.size!==i.size||g.size!==o.size)&&(re.debug("removing filters from removed custom columns..."),this.setState({quickFilters:m,advancedFilters:g})),Ze(n,p)||(re.debug("change moved columns for removed custom columns",p),this.setState({movedColumns:p})),Ze(l,f)||(re.debug("change selectDistinct columns for removed custom columns",p),this.setState({selectDistinctColumns:f}))}this.setState({customColumns:e}),e.length>0&&this.startLoading("Applying custom columns...")}handleCustomColumnsChanged(){re.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(){re.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){re.debug("handleAggregationsChange",e),this.startLoading(`Aggregating ${e.aggregations.map(t=>t.operation).join(", ")}...`),this.setState({aggregationSettings:e})}handleAggregationChange(e){re.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){re.debug("handleAggregationEdit",e);const{openOptions:t}=this.state;this.setState({openOptions:[...t,{type:xe.AGGREGATION_EDIT,title:`Edit Columns to ${e.operation}`}],selectedAggregation:e})}handleRollupChange(e){re.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){re.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:Os.DOWNLOAD_STATUS.INITIATING}):re.error("Attempted to handleDownloadTableStart for user without download CSV permission.")}handleDownloadTable(e,t,n,s,i,o,l){const{canDownloadCsv:a}=this.props;a?(re.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:Os.DOWNLOAD_STATUS.DOWNLOADING}))):re.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,{dh:o}=i;if(!i.isSeekRowAvailable||e==="")return;const l=Ce.getColumnByName(i.columns,n);if(l===void 0)return;let a=this.grid?.state.cursorRow;a==null&&(a=0);const d=s===pe.contains,h=s===pe.eq||s===pe.eqIgnoreCase;try{const{formatter:u}=i,m=F.getNormalizedType(l.type);let g;switch(m){case F.dataType.CHAR:case F.dataType.STRING:{g=await i.seekRow(a,l,o.ValueType.STRING,e,h,d,t??!1);break}case F.dataType.DATETIME:{const[p]=Zs.parseDateRange(o,e,u.timeZone);g=await i.seekRow(a,l,o.ValueType.DATETIME,p,void 0,void 0,t??!1);break}case F.dataType.DECIMAL:case F.dataType.INT:{if(!F.isBigDecimalType(l.type)&&!F.isBigIntegerType(l.type)){let p=parseInt(e,10);e==="-Infinity"?p=Number.NEGATIVE_INFINITY:e==="Infinity"&&(p=Number.POSITIVE_INFINITY),g=await i.seekRow(a,l,o.ValueType.NUMBER,p,void 0,void 0,t??!1)}else g=await i.seekRow(a,l,o.ValueType.STRING,e,void 0,void 0,t??!1);break}default:g=await i.seekRow(a,l,o.ValueType.STRING,this.tableUtils.makeValue(l.type,e,u.timeZone),void 0,void 0,t??!1)}this.grid?.setFocusRow(g),this.setState({gotoValueError:""})}catch{this.setState({gotoValueError:"invalid input"})}}handleCancelDownloadTable(){this.tableSaver?.cancelDownload(),this.setState({isTableDownloading:!1})}handleDownloadProgressUpdate=bs((e,t)=>{const{tableDownloadStatus:n}=this.state;n===Os.DOWNLOAD_STATUS.DOWNLOADING&&this.setState({tableDownloadProgress:e,tableDownloadEstimatedTime:t})},kE);handleDownloadCompleted(){this.setState({isTableDownloading:!1,tableDownloadProgress:100,tableDownloadStatus:Os.DOWNLOAD_STATUS.FINISHED})}handleDownloadCanceled(){this.setState({isTableDownloading:!1,tableDownloadProgress:0,tableDownloadStatus:Os.DOWNLOAD_STATUS.CANCELED})}deleteRanges(e){const{model:t}=this.props;this.pending.add(t.delete(e)).catch(n=>{be.isCanceled(n)||re.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;D(e),D(t);const n=this.gridWrapper?.getBoundingClientRect(),s=20;D(n);const{columnHeaderHeight:i,allColumnXs:o,allColumnWidths:l,width:a,columnHeaderMaxDepth:d}=e,h=o.get(t),u=l.get(t);D(h),D(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=we(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(Je,{options:n,ref:this.handleTooltipRef,children:"View full contents"},Date.now())})});getExpandCellTooltip=we(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(Je,{options:s,ref:this.handleTooltipRef,children:r.jsxs("div",{style:{textAlign:"left"},children:["Click to ",t," row",r.jsx("br",{}),ws.isMacPlatform()?"⌘":"Ctrl+","Click to expand row and all children"]})},Date.now())})});getLinkHoverTooltip=we(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(Je,{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},f={placement:"bottom",modifiers:{flip:{behavior:["bottom","top"]}}},C=this.getModelColumn(e);if(C==null)return null;const S=n.columns[C];return S==null?null:r.jsx("div",{style:g,children:r.jsx(Je,{timeout:400,interactive:!0,options:f,ref:this.handleTooltipRef,referenceObject:p,onExited:()=>{this.setState({shownColumnTooltip:null})},children:r.jsx($v,{model:n,column:S,onStatistics:()=>{this.tooltip?.update()}})},S.name)})}handleGotoValueSelectedColumnNameChanged(e){const{model:t}=this.props,n=this.grid?.state.cursorRow;if(n!=null){const s=t.getColumnIndexByName(e),i=Ce.getColumnByName(t.columns,e);if(s==null||i==null)return;const o=t.valueForCell(s,n),l=Ce.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=We(e=>{this.seekRow(e)},OE);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:f,metrics:C,isFilterBarShown:S,isSelectingPartition:b,isMenuShown:w,isReady:T,copyOperation:E,focusedFilterBarColumn:y,loadingText:R,loadingScrimProgress:I,loadingSpinnerShown:x,keyHandlers:A,mouseHandlers:k,shownColumnTooltip:_,hoverAdvancedFilter:M,shownAdvancedFilter:$,hoverSelectColumn:H,quickFilters:K,advancedFilters:L,partition:G,partitionFilters:ee,partitionTable:W,partitionColumn:j,searchFilter:B,selectDistinctColumns:Z,movedColumns:se,movedRows:ae,formatter:q,conditionalFormats:ne,conditionalFormatPreview:he,conditionalFormatEditIndex:Te,sorts:ye,reverseType:rt,customColumns:wt,selectedRanges:Wt,isTableDownloading:fn,tableDownloadStatus:xt,tableDownloadProgress:Ee,tableDownloadEstimatedTime:lt,showSearchBar:et,searchValue:pt,selectedSearchColumns:It,invertSearchColumns:Cn,aggregationSettings:Gt,selectedAggregation:So,rollupConfig:Rs,openOptions:zt,pendingSavePromise:Zn,pendingSaveError:ei,pendingRowCount:Ni,pendingDataErrors:ti,pendingDataMap:ni,toastMessage:bo,frozenColumns:wo,columnHeaderGroups:Qn,showOverflowModal:xs,overflowText:oa,overflowButtonTooltipProps:vo,expandCellTooltipProps:ki,linkHoverTooltipProps:Mi,isGotoShown:Oi,gotoRow:To,gotoRowError:la,gotoValueError:aa,gotoValueSelectedColumnName:ra,gotoValue:da,gotoValueSelectedFilter:ca}=this.state;if(!T)return null;const Is=this.getTheme(),Eo=this.getCachedFilter(t,K,L,ee,B),si=f.getUserColumnWidths(),yo=this.getCachedStateOverride(H,S,s,I,K,L,ye,rt,Rs,w),Ds=C?C.top:0,Ro=C?C.bottomViewport:0;let Ai=null,Li=null;d&&(Ai=C?C.left:0,Li=C?C.right:0);const xo=C!=null&&C.width>0&&C.height>0,Io=(Rs?.columns?.length??0)>0;let Do=null;const ha=C?Math.min(Math.max(pi.minDebounce,Math.round(C.rowCount/200)),pi.maxDebounce):pi.maxDebounce;if(S&&y!=null&&C!=null){const{gridX:Ue,gridY:Ne,allColumnXs:Kt,allColumnWidths:_i,width:ii}=C,Jn=Kt.get(y),Dt=_i.get(y);if(Jn!=null&&Dt!=null){const vt=Ue+Jn,Mn=Ne-(Is.filterBarHeight??0),Fs=Dt+1,Ns=(Is.filterBarHeight??0)-1,Lo={top:Mn,left:vt,minWidth:Math.min(Fs,ii-vt),height:Ns};let Sn="",ks=!0;const Ms=this.getModelColumn(y);D(Ms);const oi=K.get(Ms),es=L.get(Ms);oi!=null&&(Sn=oi.text,ks=oi.filter!=null);const li=K.size!==0||L.size!==0;Do=r.jsx(Xw,{ref:this.filterInputRef,style:Lo,className:z({error:!ks,active:Sn!==""||es!=null,"iris-grid-has-filter":li}),isAdvancedFilterSet:es!=null,onAdvancedFiltersTriggered:()=>{this.setState({shownAdvancedFilter:y})},onChange:this.handleFilterBarChange,onDone:this.handleFilterBarDone,onTab:this.handleFilterBarTab,onContextMenu:this.grid?.handleContextMenu,debounceMs:ha,value:Sn},y)}}let Fo=null;if(R!=null){const Ue=r.jsxs("div",{className:"iris-grid-loading-status",children:[r.jsx("div",{className:z("iris-grid-loading-status-bar",{show:x}),children:R}),r.jsxs("button",{type:"button",onClick:this.handleCancel,className:z("iris-grid-btn-cancel",{show:x}),children:[r.jsx(X,{icon:ho,transform:"down-1"}),"Cancel"]})]}),Ne=C?C.gridY:0;Fo=r.jsx("div",{className:"iris-grid-loading",style:{top:Ne},children:Ue})}let No=null;_!=null&&C&&(No=this.getColumnTooltip(_,C,l),this.tooltip?.update());const ko=[];if(C&&S){const{gridX:Ue,gridY:Ne,visibleColumns:Kt,allColumnXs:_i,allColumnWidths:ii}=C,{filterBarHeight:Jn}=Is;for(let Dt=0;Dt<Kt.length;Dt+=1){const vt=Kt[Dt],Mn=_i.get(vt),Fs=ii.get(vt),Ns=this.getModelColumn(vt);if(Ns!=null&&l.isFilterable(Ns)&&Mn!=null&&Fs!=null&&Fs>0){const Sn=Ue+Mn+Fs-24,Ms={position:"absolute",top:Ne-(Jn??0)+2,left:Sn},es=L.get(Ns)!=null,li=vt===M||vt===y||es,ma=r.jsx("div",{className:z("advanced-filter-button-container",{hidden:!li}),style:Ms,children:li&&r.jsx(P,{kind:"ghost",className:z("btn-link-icon advanced-filter-button",{"filter-set":es}),onClick:()=>{this.setState({shownAdvancedFilter:vt})},onContextMenu:qu=>{this.grid?.handleContextMenu(qu)},onMouseEnter:()=>{this.setState({hoverAdvancedFilter:vt})},onMouseLeave:()=>{this.setState({hoverAdvancedFilter:null})},children:r.jsxs("div",{className:"fa-layers",children:[r.jsx(X,{icon:rr,className:"filter-solid"}),r.jsx(X,{icon:rl,className:"filter-light"})]})})},vt);ko.push(ma)}}}const Mo=[];if(C){const{gridX:Ue,visibleColumns:Ne,allColumnXs:Kt,allColumnWidths:_i,columnHeaderHeight:ii}=C;for(let Jn=0;Jn<Ne.length;Jn+=1){const Dt=Ne[Jn],vt=Kt.get(Dt),Mn=_i.get(Dt);if(vt!=null&&Mn!=null&&Mn>0){const Fs=Ue+vt,Ns=Ue+vt+Mn-20,Lo=S?{position:"absolute",top:ii,left:Ns,width:20,height:Is.filterBarHeight}:{position:"absolute",top:0,left:Fs,width:Mn,height:ii},Sn=this.getModelColumn(Dt);if(Sn!=null){const ks=l.columns[Sn];if(ks==null){re.warn(`Column does not exist at index ${Sn} for column array of length ${l.columns.length}`);continue}const Ms=L.get(Sn),{options:oi}=Ms||{},es=F.getSortForColumn(l.sort,ks.name),li=es?es.direction:null,ma=r.jsx("div",{className:"advanced-filter-menu-container",style:Lo,children:r.jsx(Ul,{className:"advanced-filter-menu-popper",onEntered:this.getAdvancedMenuOpenedHandler(Dt),onExited:()=>{this.handleAdvancedMenuClosed(Dt)},isShown:$===Dt,interactive:!0,closeOnBlur:!0,options:{positionFixed:!0},children:this.getCachedAdvancedFilterMenuActions(l,ks,oi,li,q)})},Dt);Mo.push(ma)}}}}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,S,et,g,this.isTableSearchAvailable(),Oi,u.size>0),Ao=this.getCachedHiddenColumns(f,si),ua=zt.map(Ue=>{switch(Ue.type){case xe.CHART_BUILDER:return r.jsx(iT,{model:l,onChange:this.handleChartChange,onSubmit:this.handleChartCreate},xe.CHART_BUILDER);case xe.VISIBILITY_ORDERING_BUILDER:return r.jsx(BT,{model:l,movedColumns:se,hiddenColumns:Ao,columnHeaderGroups:Qn,onColumnVisibilityChanged:this.handleColumnVisibilityChanged,onReset:this.handleColumnVisibilityReset,onMovedColumnsChanged:this.handleMovedColumnsChanged,onColumnHeaderGroupChanged:this.handleHeaderGroupsChanged},xe.VISIBILITY_ORDERING_BUILDER);case xe.CONDITIONAL_FORMATTING:return r.jsx(JT,{rules:ne,onChange:this.handleConditionalFormatsChange,onCreate:this.handleConditionalFormatCreate,onSelect:this.handleConditionalFormatEdit});case xe.CONDITIONAL_FORMATTING_EDIT:return D(l.columns),D(this.handleConditionalFormatEditorUpdate),r.jsx(xE,{dh:l.dh,columns:l.columns,rule:he,onUpdate:this.handleConditionalFormatEditorUpdate,onSave:this.handleConditionalFormatEditorSave,onCancel:this.handleConditionalFormatEditorCancel});case xe.CUSTOM_COLUMN_BUILDER:return r.jsx(dT,{model:l,customColumns:wt,onSave:this.handleUpdateCustomColumns,onCancel:this.handleMenuBack},xe.CUSTOM_COLUMN_BUILDER);case xe.ROLLUP_ROWS:return r.jsx(hT,{model:l,onChange:this.handleRollupChange,config:Rs},xe.ROLLUP_ROWS);case xe.AGGREGATIONS:return r.jsx(Yv,{settings:Gt,isRollup:Io,onChange:this.handleAggregationsChange,onEdit:this.handleAggregationEdit});case xe.AGGREGATION_EDIT:return So&&r.jsx(Xv,{aggregation:So,columns:l.originalColumns,onChange:this.handleAggregationChange});case xe.TABLE_EXPORTER:return r.jsx(Os,{model:l,name:a,userColumnWidths:si,movedColumns:se,isDownloading:fn,tableDownloadStatus:xt,tableDownloadProgress:Ee,tableDownloadEstimatedTime:lt??void 0,onDownload:this.handleDownloadTable,onDownloadStart:this.handleDownloadTableStart,onCancel:this.handleCancelDownloadTable,selectedRanges:Wt},xe.TABLE_EXPORTER);case xe.SELECT_DISTINCT:return r.jsx(XT,{model:l,selectDistinctColumns:Z,onChange:this.handleSelectDistinctChanged});case xe.ADVANCED_SETTINGS:return r.jsx(Br,{items:u,onChange:m});default:throw Error(`Unexpected option type ${Ue.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(Vt,{in:b,timeout:Ye.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:W&&j&&G!=null&&r.jsx(KT,{dh:l.dh,table:W,getFormattedString:(Ue,Ne,Kt)=>l.displayString(Ue,Ne,Kt),columnName:j.name,partition:G,onChange:this.handlePartitionChange,onFetchAll:this.handlePartitionFetchAll,onAppend:this.handlePartitionAppend,onDone:this.handlePartitionDone})})}),r.jsx(Vt,{in:et,timeout:Ye.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(zo,{value:pt,selectedColumns:It,invertSelection:Cn,onChange:this.handleCrossColumnSearch,columns:l.columns,ref:this.crossColumnRef})})}),r.jsxs("div",{className:"grid-wrapper",ref:Ue=>{this.gridWrapper=Ue},children:[r.jsx(lw,{ref:Ue=>{this.grid=Ue},isStickyBottom:!ze(l)||!l.isEditable,isStuckToBottom:i,isStuckToRight:o,metricCalculator:f,model:l,keyHandlers:A,mouseHandlers:k,movedColumns:se,movedRows:ae,onError:this.handleGridError,onViewChanged:this.handleViewChanged,onSelectionChanged:this.handleSelectionChanged,onMovedColumnsChanged:this.handleMovedColumnsChanged,renderer:this.renderer,stateOverride:yo,theme:Is}),r.jsx(IE,{isOpen:xs,text:oa,onClose:this.handleOverflowClose}),xo&&r.jsx(_v,{model:l,modelColumns:l.columns,top:Ds,bottom:Ro,left:Ai,right:Li,filter:Eo,formatter:q,sorts:ye,reverseType:rt,movedColumns:se,customColumns:wt,hiddenColumns:Ao,alwaysFetchColumns:this.getAlwaysFetchColumns(h,l.columns,se,l.floatingLeftColumnCount,l.floatingRightColumnCount,this.grid?.state.draggingColumn?.range),formatColumns:this.getCachedPreviewFormatColumns(l.dh,l.columns,ne,he,zt[zt.length-1]?.type===xe.CONDITIONAL_FORMATTING_EDIT?Te??void 0:void 0),rollupConfig:this.getModelRollupConfig(l.originalColumns,Rs,Gt),totalsConfig:this.getModelTotalsConfig(l.columns,Rs,Gt),selectDistinctColumns:Z,pendingRowCount:Ni,pendingDataMap:ni,frozenColumns:wo,columnHeaderGroups:Qn}),!w&&r.jsx("div",{className:"grid-settings-button",children:r.jsx(P,{kind:"ghost","data-testid":`btn-iris-grid-settings-button-${a}`,onClick:this.handleMenu,icon:r.jsx(X,{icon:Ag,transform:"up-1"}),tooltip:"Table Options"})}),Do,Fo,ko,No,Mo,vo&&this.getOverflowButtonTooltip(vo),ki&&this.getExpandCellTooltip(ki),Mi&&this.getLinkHoverTooltip(Mi)]}),r.jsx(NE,{model:l,isShown:Oi,gotoRow:To,gotoRowError:la,gotoValueError:aa,onGotoRowSubmit:this.handleGotoRowSelectedRowNumberSubmit,onGotoRowNumberChanged:this.handleGotoRowSelectedRowNumberChanged,onClose:this.handleGotoRowClosed,onEntering:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExiting:()=>{this.handleAnimationStart(),this.focus()},onExited:this.handleAnimationEnd,gotoValueSelectedColumnName:ra,gotoValue:da,gotoValueFilter:ca,onGotoValueSelectedColumnNameChanged:this.handleGotoValueSelectedColumnNameChanged,onGotoValueSelectedFilterChanged:this.handleGotoValueSelectedFilterChanged,onGotoValueChanged:this.handleGotoValueChanged,onGotoValueSubmit:this.handleGotoValueSubmitted}),r.jsx(Uw,{error:ei,isSaving:Zn!=null,saveTooltip:`Commit (${this.commitAction.shortcut.getDisplayText()})`,discardTooltip:`Discard (${this.discardAction.shortcut.getDisplayText()})`,pendingDataErrors:ti,pendingDataMap:ni,onEntering:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExiting:this.handleAnimationStart,onExited:this.handleAnimationEnd,onSave:this.handlePendingCommitClicked,onDiscard:this.handlePendingDiscardClicked}),r.jsx(Mv,{children:bo}),r.jsx(Yw,{model:l,copyOperation:E??void 0,onEntering:this.handleAnimationStart,onEntered:this.handleAnimationEnd,onExiting:this.handleAnimationStart,onExited:this.handleAnimationEnd}),r.jsx(Hn,{dh:l.dh,ref:Ue=>{this.tableSaver=Ue},getDownloadWorker:n,onDownloadCompleted:this.handleDownloadCompleted,onDownloadCanceled:this.handleDownloadCanceled,onDownloadProgressUpdate:this.handleDownloadProgressUpdate,isDownloading:xt===Os.DOWNLOAD_STATUS.DOWNLOADING,formatter:q})]}),r.jsx(Vt,{in:w,timeout:Ye.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(Mm,{children:[r.jsx(cd,{title:"Table Options",onClose:this.handleMenuClose,children:r.jsx($c,{onSelect:Ue=>this.handleMenuSelect(Oo[Ue]),items:Oo})}),ua.map((Ue,Ne)=>r.jsx(cd,{title:zt[Ne].title,onBack:this.handleMenuBack,onClose:this.handleMenuClose,children:Ue},zt[Ne].type))]})})}),r.jsx(te,{actions:this.contextActions})]})}}const Du=pi;class _E 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 PE=_E,qe=J.module("IrisGridTableModel"),jE=150,HE=0,UE=[];function Ys(c){return c.table!==void 0}class lo extends ge{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}dh;irisGridUtils;tableUtils;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,n=new gn(e),s=null){super(e),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.dh=e,this.irisFormatter=n,this.irisGridUtils=new Ce(e),this.inputTable=s,this.subscription=null,this.table=t,this.tableUtils=new F(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=Ce.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();const{dh:e}=this;this.table.addEventListener(e.Table.EVENT_DISCONNECT,this.handleTableDisconnect),this.table.addEventListener(e.Table.EVENT_RECONNECT,this.handleTableReconnect),this.table.addEventListener(e.Table.EVENT_UPDATED,this.handleTableUpdate),this.table.addEventListener(e.Client.EVENT_REQUEST_FAILED,this.handleRequestFailed),this.table.addEventListener(e.Table.EVENT_CUSTOMCOLUMNSCHANGED,this.handleCustomColumnsChanged),this.totalsTable!=null&&this.addTotalsListeners(this.totalsTable),this.applyViewport()}stopListening(){super.stopListening();const{dh:e}=this;this.table.removeEventListener(e.Table.EVENT_DISCONNECT,this.handleTableDisconnect),this.table.removeEventListener(e.Table.EVENT_RECONNECT,this.handleTableReconnect),this.table.removeEventListener(e.Table.EVENT_UPDATED,this.handleTableUpdate),this.table.removeEventListener(e.Client.EVENT_REQUEST_FAILED,this.handleRequestFailed),this.table.removeEventListener(e.Table.EVENT_CUSTOMCOLUMNSCHANGED,this.handleCustomColumnsChanged),this.totalsTable!=null&&this.removeTotalsListeners(this.totalsTable),this.closeSubscription()}addTotalsListeners(e){const{dh:t}=this;e.addEventListener(t.Table.EVENT_UPDATED,this.handleTotalsUpdate),e.setViewport(0,0)}removeTotalsListeners(e){const{dh:t}=this;e.removeEventListener(t.Table.EVENT_UPDATED,this.handleTotalsUpdate)}handleTableDisconnect(){this.dispatchEvent(new Ve(ge.EVENT.DISCONNECT))}handleTableReconnect(){this.dispatchEvent(new Ve(ge.EVENT.RECONNECT))}handleTableUpdate(e){this.copyViewportData(e.detail),this.dispatchEvent(new Ve(ge.EVENT.UPDATED))}handleTotalsUpdate(e){this.copyTotalsData(e.detail),this.dispatchEvent(new Ve(ge.EVENT.UPDATED))}handleRequestFailed(e){this.dispatchEvent(new Ve(ge.EVENT.REQUEST_FAILED,e))}handleCustomColumnsChanged(){this.dispatchEvent(new Ve(ge.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(!Ce.isValidIndex(n))throw new Error(`Invalid rowIndex ${n}`);const{data:s}=t;s.forEach((i,o)=>{if(!Ce.isValidIndex(o))throw new Error(`Invalid columnIndex ${o}`)})}),this.pendingNewDataMap=e,this.pendingNewRowCount=Math.max(this.pendingNewRowCount,this.maxPendingDataRow),this.formattedStringData=[],this.dispatchEvent(new Ve(ge.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 Ve(ge.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"*"}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 D(n.nullStringColor),n.nullStringColor;if(i&&i.color)return i.color;if(this.isPendingRow(t))return D(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 D(n.dateColor),n.dateColor;if(F.isNumberType(l.type))return o>0?(D(n.positiveNumberColor),n.positiveNumberColor):o<0?(D(n.negativeNumberColor),n.negativeNumberColor):(D(n.zeroNumberColor),n.zeroNumberColor)}}else if(this.isPendingRow(t)&&this.isKeyColumn(e))return D(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 Ta(n)?n.isNew?"":n.name:n?.name}colorForColumnHeader(e,t=0){const n=this.columnAtDepth(e,t);return Ta(n)?n.color??null:null}getColumnHeaderGroup(e,t){const n=this.columnAtDepth(e,t);if(Ta(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=ce(e=>{if(!e)return[];let t=[];const{groupMap:n}=Ce.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=O.getVisibleIndex(m,t);t=O.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=O.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=O.getVisibleIndex(g,t);else{const f=n.get(m);if(!f)throw new Error(`Unknown column ${m} in group ${u.name}`);[,p]=f.getVisibleRange(t)}for(let f=1;f<u.children.length;f+=1){const C=u.children[f],S=n.get(C),b=this.getColumnIndexByName(C);if(S){const T=S.getVisibleRange(t)[0]<p?p-S.childIndexes.length+1:p+1;i(C,T),p=T+S.childIndexes.length-1}else if(b!=null){const T=O.getVisibleIndex(b,t)<p?p:p+1;s(C,T),p=T}}})}return this._movedColumns=t,t});get initialMovedColumns(){return this.getMemoizedInitialMovedColumns(this.layoutHints??void 0)}get initialMovedRows(){return UE}getMemoizedInitialColumnHeaderGroups=ce(e=>Ce.parseColumnHeaderGroups(this,e?.columnGroups??[]).groups);get initialColumnHeaderGroups(){return this.getMemoizedInitialColumnHeaderGroups(this.layoutHints??void 0)}getMemoizedColumnMap=ce(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}=Ce.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 D(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??Fe.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){qe.warn("invalid data!");return}this.viewportData=this.extractViewportData(e),this.formattedStringData=[]}copyTotalsData(e){if(e==null){qe.warn("invalid data!");return}const{columns:t,rows:n}=e;if(n.length!==1){qe.error("Unexpected number of rows received for totals table, ignoring update");return}const s=new Map,i=n[0],o=this.totals?.defaultOperation??Fe.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)})}qe.debug2("copyTotalsData",s),this.totalsDataMap=s,this.formattedStringData=[]}getColumnIndexByName(e){return this.getColumnIndicesByNameMap(this.columns).get(e)}getColumnIndicesByNameMap=ce(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);D(o),n.set(o,{value:e.get(i),format:e.getFormat(i)})}return{data:n}}closeSubscription(){qe.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 Ve(ge.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(qe.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 Ve(ge.EVENT.UPDATED));return}this.totalsTablePromise=be.makeCancelable(this.table.getTotalsTable(e),t=>t.close()),this.totalsTablePromise.then(t=>{this.totalsTablePromise=null,this.setTotalsTable(t)}).catch(t=>{be.isCanceled(t)||(qe.error("Unable to set next totalsTable",t),this.totalsTablePromise=null,this.dispatchEvent(new Ve(ge.EVENT.REQUEST_FAILED,{detail:t})))})}}setTotalsTable(e){qe.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=bs((e,t,n)=>{if(t<e){qe.error("Invalid viewport",e,t);return}const{viewport:s}=this;if(s!=null&&s.top===e&&s.bottom===t&&s.columns===n){qe.debug2("Ignoring duplicate viewport",s);return}this.viewport={top:e,bottom:t,columns:n},qe.debug2("setViewport",this.viewport),this.applyViewport()},jE);applyViewport=bs(()=>{if(!this.viewport)return;qe.debug2("applyViewport",this.viewport);const{top:e,bottom:t,columns:n}=this.viewport,[s,i]=this.getCachedViewportRowRange(e,t);this.applyBufferedViewport(s,i,n)},HE,{leading:!1});applyBufferedViewport(e,t,n){qe.debug2("applyBufferedViewport",e,t,n),this.subscription==null?(qe.debug2("applyBufferedViewport creating new subscription"),this.subscription=this.table.setViewport(e,t,n)):(qe.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?Q.consolidate(e):e;if(!Ce.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];D(p.endRow),D(p.startRow);for(let f=p.startRow;f<=p.endRow&&f<this.floatingTopRowCount;f+=1)o.add(f);p.endRow>=this.floatingTopRowCount&&p.startRow<=this.floatingTopRowCount+this.table.size&&l.push(new Q(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 f=Math.max(p.startRow,this.floatingTopRowCount+this.table.size);f<=p.endRow&&f<this.floatingTopRowCount+this.table.size+this.floatingBottomRowCount;f+=1)a.add(f)}const d=Ce.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],f=d.map(C=>{const S=this.getColumnIndexByName(C.name);return D(S),n(this.valueForCell(S,p),C)});t&&f.push(this.textForRowFooter(p)),h.push(f)}if(l.length>0){const g=this.irisGridUtils.rangeSetFromRanges(l),p=await this.subscription.snapshot(g,d);h.push(...p.rows.map(f=>d.map(C=>n(f.get(C),C))))}const m=[...a].sort();for(let g=0;g<m.length;g+=1){const p=m[g],f=d.map(C=>{const S=this.getColumnIndexByName(C.name);return D(S),n(this.valueForCell(S,p),C)});t&&f.push(this.textForRowFooter(p)),h.push(f)}return h}async textSnapshot(e,t=!1,n=s=>`${s}`){return qe.debug2("textSnapshot",e,t),(await this.snapshot(e,t,n,!1)).map(i=>i.join(" ")).join(`
|
|
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=Bn((e,t,n,s,i)=>e.getFormattedString(t,n,s,i),{max:1e4});getCachedCustomColumnFormatFlag=Bn(Wn.isCustomColumnFormatDefined,{max:1e4});getCachedViewportRowRange=ce((e,t)=>{const n=t-e,s=Math.max(0,e-n*lo.ROW_BUFFER_PAGES),i=t+n*lo.ROW_BUFFER_PAGES;return[s,i]});getCachedPendingErrors=ce((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 PE(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||!Q.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 Q(null,this.floatingTopRowCount,null,this.floatingTopRowCount+this.table.size-1)}getPendingAreaRange(){return new Q(null,this.floatingTopRowCount+this.table.size,null,this.floatingTopRowCount+this.table.size+this.pendingNewRowCount-1)}async setValueForCell(e,t,n){return this.setValueForRanges([new Q(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=[];Q.forEachCell(e,(d,h)=>{const u=this.columns[d];if(n.add(u),s[d]===void 0){const m=this.tableUtils.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=>Q.intersection(i,d)).filter(d=>d!=null).map(d=>(D(d),Q.offset(d,0,-(this.floatingTopRowCount+this.table.size))));if(o.length>0){const d=new Map(this.pendingNewDataMap);Q.forEachCell(o,(h,u)=>{d.has(u)||d.set(u,{data:new Map});const m=this.columns[h],g=d.get(u);D(g);const{data:p}=g,f=new Map(p),C=this.tableUtils.makeValue(m.type,t,this.formatter.timeZone);C!=null?f.set(h,{value:C}):f.delete(h),f.size>0?d.set(u,{...g,data:f}):d.delete(u)}),this.pendingDataMap=d}this.dispatchEvent(new Ve(ge.EVENT.UPDATED));const l=this.getTableAreaRange(),a=e.map(d=>Q.intersection(l,d)).filter(d=>d!=null);if(a.length>0){const h=(await this.snapshot(a.map(m=>new Q(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]=this.tableUtils.makeValue(p.type,t,this.formatter.timeZone)}),g}),u=await this.inputTable?.addRows(h);qe.debug("setValueForRanges(",e,",",t,") set tableRanges",a,"result",u)}Q.forEachCell(e,(d,h)=>{const u=s[d];D(u),this.cacheFormattedValue(d,h,u)})}catch(n){qe.error("Unable to set ranges",e,t,n)}finally{Q.forEachCell(e,(n,s)=>{this.clearPendingValue(n,s)})}}async setValues(e=[]){if(qe.debug("setValues(",e,")"),!e.every(t=>this.isEditableRange(Q.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=this.tableUtils.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 f=t.get(p);D(f);const{data:C}=f,S=new Map(C);m!=null?S.set(d,{value:m}):S.delete(d),S.size>0?t.set(p,{...f,data:S}):t.delete(p)}}),this.pendingDataMap=t,this.dispatchEvent(new Ve(ge.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=Q.consolidate(e.map(l=>Q.makeCell(l.column??l.x,l.row??l.y))),i=this.getTableAreaRange(),o=s.map(l=>Q.intersection(i,l)).filter(l=>l!=null);if(o.length>0){const a=(await this.snapshot(o.map(h=>(D(h),new Q(null,h.startRow,null,h.endRow))))).map((h,u)=>{let m=null,g=u;for(let C=0;C<o.length;C+=1){const S=o[C];D(S);const b=Q.rowCount([S]);if(g<b){D(S.startRow),m=S.startRow+g;break}g-=b}const p={};for(let C=0;C<this.columns.length;C+=1)p[this.columns[C].name]=h[C];D(m);const f=n.get(m);return f?.forEach(C=>{const S=this.columns[C.column??C.x];p[S.name]=this.tableUtils.makeValue(S.type,C.text,this.formatter.timeZone)}),p});qe.info("setValues setting tableRanges",o);const d=await this.inputTable?.addRows(a);qe.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=this.tableUtils.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);qe.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 Ve(ge.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}`);D(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=>Q.intersection(n,u)).filter(u=>u!=null).map(u=>(D(u),Q.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];D(g.startRow),D(g.endRow);for(let p=g.startRow;p<=g.endRow;p+=1)u.delete(p)}this.pendingNewDataMap=u,this.formattedStringData=[],this.dispatchEvent(new Ve(ge.EVENT.PENDING_DATA_UPDATED)),this.dispatchEvent(new Ve(ge.EVENT.UPDATED))}const i=this.getTableAreaRange(),o=e.map(u=>Q.intersection(i,u)).filter(u=>u!=null);if(o.length<=0)return;const[l,a]=await Promise.all([this.snapshot(o.map(u=>(D(u),new Q(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],f=u[g],C=this.tableUtils.makeFilterRawValue(p.type,f),S=p.filter().eq(C);m.push(S)}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 this.tableUtils.makeValue(s.type,n,this.formatter.timeZone),!0}catch{return!1}}}const as=J.module("IrisGridTableModel");class BE extends lo{userFrozenColumns;customColumnList;formatColumnList;constructor(e,t,n=new gn(e),s=null){super(e,t,n,s),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=ce(e=>e??[]);get frontColumns(){return this.getMemoizedFrontColumns(this.layoutHints?.frontColumns)}getMemoizedBackColumns=ce(e=>e??[]);get backColumns(){return this.getMemoizedBackColumns(this.layoutHints?.backColumns)}getMemoizedFrozenColumns=ce((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 Ve(ge.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 Ve(ge.EVENT.UPDATED));return}this.totalsTablePromise=be.makeCancelable(this.table.getTotalsTable(e),t=>t.close()),this.totalsTablePromise.then(t=>{this.totalsTablePromise=null,this.setTotalsTable(t)}).catch(t=>{be.isCanceled(t)||(as.error("Unable to set next totalsTable",t),this.totalsTablePromise=null,this.dispatchEvent(new Ve(ge.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=ce(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}`);D(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=>Q.intersection(n,u)).filter(u=>u!=null).map(u=>(D(u),Q.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];D(g.startRow),D(g.endRow);for(let p=g.startRow;p<=g.endRow;p+=1)u.delete(p)}super.pendingDataMap=u,this.formattedStringData=[],this.dispatchEvent(new Ve(ge.EVENT.PENDING_DATA_UPDATED)),this.dispatchEvent(new Ve(ge.EVENT.UPDATED))}const i=this.getTableAreaRange(),o=e.map(u=>Q.intersection(i,u)).filter(u=>u!=null);if(o.length<=0)return;const[l,a]=await Promise.all([this.snapshot(o.map(u=>(D(u),new Q(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],f=u[g],C=this.tableUtils.makeFilterRawValue(p.type,f),S=p.filter().eq(C);m.push(S)}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 Fu=BE;class VE extends lo{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){D(this.viewport),D(this.viewportData);const{columns:s}=this.viewport,i=[];t!=null&&t&&i.push(s.map(l=>l.name));const o=new Q(0,this.viewportData?.offset,s.length,this.viewportData.offset+this.viewportData.rows.length);for(let l=0;l<e.length;l+=1){const a=Q.intersection(o,e[l]);D(a),D(a.startRow),D(a.endRow);for(let d=a.startRow;d<=a.endRow;d+=1){const h=[],u=this.viewportData.rows[d-this.viewportData.offset];D(a.startColumn),D(a.endColumn);for(let m=a.startColumn;m<=a.endColumn;m+=1)D(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=ce((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 $E=VE,rs=J.module("IrisGridProxyModel");function Fa(c,e,t,n){return F.isTreeTable(e)?new $E(c,e,t):new Fu(c,e,t,n)}class WE extends ge{dh;originalModel;model;modelPromise;rollup;selectDistinct;constructor(e,t,n=new gn(e),s=null){super(e),this.handleModelEvent=this.handleModelEvent.bind(this);const i=Fa(e,t,n,s);this.dh=e,this.originalModel=i,this.model=i,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 Ve(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 Ve(ge.EVENT.COLUMNS_CHANGED,{detail:e.columns})),Ys(e)&&this.dispatchEvent(new Ve(ge.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=be.makeCancelable(e,t=>t.close()),this.modelPromise.then(t=>{this.modelPromise=null,this.setModel(t)}).catch(t=>{if(be.isCanceled(t)){rs.debug2("setNextModel cancelled");return}rs.error("Unable to set next model",t),this.modelPromise=null,this.dispatchEvent(new Ve(ge.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(ge.EVENT);for(let n=0;n<t.length;n+=1)e.addEventListener(t[n],this.handleModelEvent)}removeListeners(e){const t=Object.keys(ge.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 Pe(this.model)?this.model.hasExpandableRows:!1}get isExpandAllAvailable(){return Pe(this.model)?this.model.isExpandAllAvailable??!1:!1}isRowExpandable=(...e)=>Pe(this.model)?this.model.isRowExpandable(...e):!1;isRowExpanded=(...e)=>Pe(this.model)?this.model.isRowExpanded(...e):!1;setRowExpanded=(...e)=>{if(Pe(this.model))return this.model.setRowExpanded(...e);throw Error("Function setRowExpanded does not exist on IrisGridTableModel")};expandAll=()=>{if(Pe(this.model))return this.model.expandAll();throw Error("Function expandAll does not exist on IrisGridTableModel")};collapseAll=()=>{if(Pe(this.model))return this.model.collapseAll();throw Error("Function collapseAll does not exist on IrisGridTableModel")};depthForRow=(...e)=>Pe(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(Ze(e,this.rollup))return;this.rollup=e;let t=Promise.resolve(this.originalModel);Ys(this.originalModel)&&e!=null&&(t=this.originalModel.table.rollup(e).then(n=>Fa(this.dh,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);Ys(this.originalModel)&&t.length>0&&(n=this.originalModel.table.selectDistinct(t).then(s=>Fa(this.dh,s,this.formatter))),this.setNextModel(n)}get table(){if(Ys(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 ze(this.model)&&this.model.isEditable}isEditableRange=(...e)=>ze(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)=>ze(this.model)?this.model.editValueForCell(...e):"";setValueForCell=(...e)=>ze(this.model)?this.model.setValueForCell(...e):Promise.reject(new Error("Model is not editable"));setValueForRanges=(...e)=>ze(this.model)?this.model.setValueForRanges(...e):Promise.reject(new Error("Model is not editable"));setValues=(...e)=>ze(this.model)?this.model.setValues(...e):Promise.resolve();isValidForCell=(...e)=>ze(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 GE=WE;class zE{static async makeModel(e,t,n=new gn(e)){let s=null;return!F.isTreeTable(t)&&t.hasInputTable&&(s=await t.inputTable()),new GE(e,t,n,s)}}const Vr=zE;class KE{static OPEN="ChartEvent.OPEN";static CLOSE="ChartEvent.CLOSE";static COLUMN_SELECTED="ChartEvent.COLUMN_SELECTED"}const Xa=KE;class YE{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 Bt=YE;class qE{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 Ke=qE;class XE{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=XE,Nu=Object.freeze({OPEN:"MarkdownEvent.OPEN"});class ZE{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 Le=ZE;class QE{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 Ko=QE;class JE 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:te.groups.low,action:this.handleCloseTab,disabled:s===void 0||!s}),n.push(()=>({title:"Close Tabs to Right",order:20,group:te.groups.low,action:this.handleCloseTabsRight,disabled:this.canCloseTabsRight()})),n.push(()=>({title:"Close All",order:30,group:te.groups.low,action:this.handleCloseTabsAll,disabled:this.canCloseAny()})),r.jsx(te,{actions:n})}}const ey=JE;class ty 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=oe.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:z("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(P,{kind:"secondary",className:"mr-2",onClick:this.handleRenameCancel,children:"Cancel"}),r.jsx(P,{kind:"primary",type:"submit",children:"Rename"})]})]})}render(){const{isShown:e,onCancel:t}=this.props;return r.jsx(Ul,{isShown:e,onEntered:this.handleRenameDialogOpened,onExited:t,options:{placement:"bottom"},interactive:!0,closeOnBlur:!0,children:this.renderRenameDialog()})}}const ny=J.module("Panel");class sy 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:V.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(Bt.SESSION_CLOSED,this.handleSessionClosed),n.on(Bt.SESSION_OPENED,this.handleSessionOpened),n.on(Ko.focus,this.handleTabFocus),n.on(Ko.blur,this.handleTabBlur),n.on(Ke.CLEAR_ALL_FILTERS,this.handleClearAllFilters),n.emit(Se.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(Bt.SESSION_CLOSED,this.handleSessionClosed),n.off(Bt.SESSION_OPENED,this.handleSessionOpened),n.off(Ko.focus,this.handleTabFocus),n.off(Ko.blur,this.handleTabBlur),n.off(Ke.CLEAR_ALL_FILTERS,this.handleClearAllFilters),n.emit(Se.UNMOUNT,e)}handleTab(e){e!=null&&this.setState({title:V.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(Se.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=V.getRootFromContainer(t),s=V.getComponentConfigFromContainer(t);D(s),V.renameComponent(n,s,e)}handleCopyPanel(){const{glContainer:e,glEventHub:t}=this.props,n=V.getRootFromContainer(e),s=V.getComponentConfigFromContainer(e);if(s==null){ny.error("Could not get component config from container",e);return}const i=V.cloneComponent(n,s);i!==null&&t.emit(Se.CLONED,this,i)}getCloneAction(){return{title:"Copy Panel",order:10,group:te.groups.high,action:this.handleCopyPanel}}getRenameAction(){return{title:"Rename",order:10,group:te.groups.medium,action:this.handleShowRenameDialog}}getAdditionActions=ce((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:z("h-100 w-100 iris-panel",t),onFocusCapture:this.handleFocus,onBlurCapture:this.handleBlur,children:[e,r.jsx(Bl,{errorMessage:o,isLoaded:l,isLoading:a}),u!=null&&ll.createPortal(r.jsxs(r.Fragment,{children:[r.jsx(ey,{glContainer:s,additionalActions:this.getAdditionActions(i,d,h)}),h&&r.jsx(ty,{isShown:m,value:g,itemType:"Panel",onCancel:this.handleRenameCancel,onSubmit:this.handleRenameSubmit}),n!=null&&r.jsx(Je,{interactive:!0,options:{placement:"bottom"},popperClassName:"panel-tab-popper",children:n()})]}),u.element[0])]})}}const Xn=sy;function sa(c){const{widgetType:e,widgetName:t,glContainer:n,description:s,children:i}=c,o=V.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(jl,{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]})}sa.propTypes={glContainer:Fr.Container.isRequired,widgetType:U.string,widgetName:U.string,description:U.string,children:U.node};sa.defaultProps={widgetType:"",widgetName:"",description:null,children:null};class iy 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;co(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
|
+
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=ce((e,t,n,s,i)=>e?()=>r.jsx(sa,{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:f,onClearAllFilters:C,onHide:S,onFocus:b,onBlur:w,onResize:T,onShow:E,onTabBlur:y,onTabFocus:R,onTabClicked:I}=this.props,{isPanelDisconnected:x,isWidgetDisconnected:A,isPanelInactive:k}=this.state,_=this.getErrorMessage(),M=m??this.getCachedRenderTabTooltip(u,o,g,p,f),$=[{title:`Copy ${g} Name`,group:te.groups.medium,order:20,action:this.handleCopyName}];return r.jsxs(Xn,{className:z(t,{disconnected:x||A||a,inactive:k}),componentPanel:n,glContainer:o,glEventHub:l,onClearAllFilters:C,onHide:S,onFocus:b,onBlur:w,onResize:T,onShow:E,onSessionClose:this.handleSessionClosed,onSessionOpen:this.handleSessionOpened,onTabBlur:y,onTabFocus:R,onTabClicked:I,renderTabTooltip:M,errorMessage:_,isLoaded:s,isLoading:i,isClonable:d,isRenamable:h,additionalActions:$,children:[e,k&&r.jsx("div",{className:"fill-parent-absolute"})]})}}const $r=iy,Ot=Object.freeze({DEFAULT:"DEFAULT",LINKER:"LINKER"}),oy=new Map,ia=Object.freeze([]),ku=(c,e)=>At(c,e).columns??ia,ly=(c,e)=>At(c,e).filterSets??ia,Wr=(c,e)=>At(c,e).filters??ia,Gr=(c,e)=>At(c,e).tableMap??oy,zr=(c,e)=>At(c,e).isolatedLinkerPanelId,Fi=(c,e)=>At(c,e).links??ia,Kr=(c,e)=>At(c,e).columnSelectionValidator,ay=(c,e)=>At(c,e).connection,Qs=(c,e)=>At(c,e).sessionWrapper,ry=(c,e)=>t=>t(kn(c,{connection:e})),dy=(c,e)=>t=>t(kn(c,{sessionWrapper:e})),Yr=(c,e)=>t=>t(kn(c,{links:e})),cy=(c,e)=>(t,n)=>{const s=Fi(n(),c),i=e.filter(o=>s.findIndex(l=>Ze(l.start,o.start)&&Ze(l.end,o.end))<0);return t(Yr(c,s.concat(i)))},hy=(c,e)=>(t,n)=>{const i=Fi(n(),c).filter(o=>!e.includes(o.id));return t(Yr(c,i))},Mu=(c,e)=>t=>t(kn(c,{isolatedLinkerPanelId:e})),uy=(c,e)=>t=>t(kn(c,{columnSelectionValidator:e})),my=(c,e)=>t=>t(kn(c,{consoleSettings:e})),gy=(c,e)=>t=>t(kn(c,{filterSets:e}));function Ou({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(S=>e.get(S)!=null),f=g.find(S=>t.get(S)!=null),C=Jt.join(g.map(S=>`"${S}"`));return p!=null&&p&&f!=null&&f?`Use a filter control or linked table to set a value for ${C}`:p!=null&&p?`Set a filter control value for ${C}`:`Double click a row in a linked table to set a value for ${C}`},[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:z("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),f=p?Ss:ar;return r.jsxs("div",{className:z("waiting-filter-item",{"is-invalid":p}),children:[r.jsx(X,{icon:f}),g.name]},g.name)})}),r.jsxs("div",{children:[r.jsx(hd,{onClick:d,className:"btn-primary",children:"Add Input Filters"}),r.jsx(hd,{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})]})]})})}Ou.propTypes={columnMap:U.instanceOf(Map).isRequired,inputFilterMap:U.instanceOf(Map).isRequired,linkedColumnMap:U.instanceOf(Map).isRequired,onAdd:U.func.isRequired,onOpenLinker:U.func.isRequired,waitingFilterMap:U.instanceOf(Map).isRequired,waitingInputMap:U.instanceOf(Map).isRequired};function ao({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:z("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(Gc,{className:z("btn-chart-column-selector",ao.makeButtonClassName(s.name)),onClick:()=>e(s.name),onMouseEnter:()=>{t&&t(s)},onMouseLeave:n,disabled:!s.isValid,isLinked:s.isActive,children:s.name},s.name))})]})})}ao.makeButtonClassName=c=>`btn-chart-column-selector-${c}`;ao.defaultProps={onMouseEnter:()=>{},onMouseLeave:()=>{}};function sl(c){return c.settings!==void 0}const Ft=J.module("ChartPanel"),py=150;function fy(c){return c.inputFilters!=null}function Cy(c){return c.panelState!=null}class Sy 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=We(this.updateModelFromSource.bind(this),py),this.handleClearAllFilters=this.handleClearAllFilters.bind(this),this.panelContainer=oe.createRef(),this.chart=oe.createRef(),this.pending=new qn;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&&sl(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&&Pd(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{model:e}=this.state,{source:t}=this.props;e!=null&&t&&this.stopListeningToSource(t)}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=ce((e,t,n)=>{if(!e)return new Map;const s=new Map(t);return n.forEach((i,o)=>{s.delete(o)}),s});getWaitingFilterMap=ce((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=ce((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=ce((e,t)=>{const n=new Map,s=V.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);D(a),n.set(l,a)}}return n});getSelectorColumns=ce((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){Ft.debug("startListeningToSource",e);const{model:t}=this.state;D(t);const{dh:n}=t;e.addEventListener(n.Table.EVENT_CUSTOMCOLUMNSCHANGED,this.handleSourceColumnChange),e.addEventListener(n.Table.EVENT_FILTERCHANGED,this.handleSourceFilterChange),e.addEventListener(n.Table.EVENT_SORTCHANGED,this.handleSourceSortChange)}stopListeningToSource(e){Ft.debug("stopListeningToSource",e);const{model:t}=this.state;D(t);const{dh:n}=t;e.removeEventListener(n.Table.EVENT_CUSTOMCOLUMNSCHANGED,this.handleSourceColumnChange),e.removeEventListener(n.Table.EVENT_FILTERCHANGED,this.handleSourceFilterChange),e.removeEventListener(n.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(Xa.COLUMN_SELECTED,this,n.get(e))}handleColumnMouseEnter({type:e,name:t}){const{columnSelectionValidator:n}=this.props;Ft.debug("handleColumnMouseEnter",n,e,t),n&&n(this,{type:e,name:t})}handleColumnMouseLeave(){const{columnSelectionValidator:e}=this.props;Ft.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(Ot.LINKER)}handleReconnect(){this.setState({isDisconnected:!1,error:void 0}),this.sendColumnChange(),this.updateColumnFilters()}handleLoadSuccess(e){Ft.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){be.isCanceled(e)||(Ft.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){Ft.debug2("updateModelFromSource ignoring",n,s,t);return}const{dh:i}=s;if(this.pending.cancel(),sl(e)){const{settings:o}=e;this.pending.add(i.plot.Figure.create(new ht(i).makeFigureSettings(o,t))).then(l=>{Pd(s)&&s.setFigure(l)}).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&&fy(e.props)&&Cy(e.state)){const{inputFilters:o}=e.props,{panelState:l}=e.state;l!=null&&(i=Ce.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 Ft.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(Ke.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(Ke.COLUMNS_CHANGED,this,Array.from(e.getFilterColumnMap().values()))}getCoordinateForColumn(e){const t=ao.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){Ft.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){Ft.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 Ft.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 Ft.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;D(n);const s=this.getWaitingInputMap(n.isFilterRequired(),e,t);if(n.setFilter(t),t.size>0&&s.size===0){const i=n.getDefaultTitle(),o=Jt.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),Ft.debug2("updateFilters filters set",t),this.setState({isLoading:!0})}else Ft.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:f,isLoading:C}=this.state;let S;sl(l)?S=l.table:S=l.figure;const b=this.getInputFilterColumnMap(d,s),w=this.getLinkedColumnMap(d,o),T=m!=null?this.getWaitingInputMap(m.isFilterRequired(),d,h):new Map,E=m!=null?this.getWaitingFilterMap(m.isFilterRequired(),d,h,w,b):new Map,y=u!=null?`Unable to open chart. ${u}`:void 0,R=T.size>0,I=d.size>0&&i;return r.jsx($r,{className:z("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:y,isDisconnected:p,isLoading:C,isLoaded:f,widgetName:S,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:f&&m&&r.jsx(oC,{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(Vt,{in:R&&!I&&!C,timeout:Ye.transitionMs,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx(Ou,{inputFilterMap:b,linkedColumnMap:w,onAdd:this.handleFilterAdd,onOpenLinker:this.handleOpenLinker,columnMap:d,waitingFilterMap:E,waitingInputMap:T})}),r.jsx(Vt,{in:I,timeout:Ye.transitionMs,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx(ao,{columns:this.getSelectorColumns(d,w,e),onColumnSelected:this.handleColumnSelected,onMouseEnter:this.handleColumnMouseEnter,onMouseLeave:this.handleColumnMouseLeave})})]})})}}const by=(c,e)=>{const{localDashboardId:t,metadata:n}=e;let s;n!=null&&(s=n.sourcePanelId);const i=Gr(c,t),o=lu(c,t),l=ql(c),a=zr(c,t),d=l===Ot.LINKER&&a===void 0;return{columnSelectionValidator:Kr(c,t),isLinkerActive:d,inputFilters:Wr(c,t),links:Fi(c,t),source:s!=null?i.get(s):void 0,sourcePanel:s!=null?o.get(s):void 0,settings:gt(c)}},wy=mt(by,{setActiveTool:Zl,setDashboardIsolatedLinkerPanelId:Mu},null,{forwardRef:!0})(Sy),Ti=wy;const Yo=J.module("CommandHistoryPanel");class qr extends v.Component{static COMPONENT="CommandHistoryPanel";static TITLE="Command History";static handleError(e){Yo.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=oe.createRef(),this.pending=new qn;const{session:t,sessionId:n,language:s}=e;this.state={panelState:{},session:t,sessionId:n,language:s,contextActions:[{action:this.handleFocusHistory,shortcut:Rt.COMMAND_HISTORY.FOCUS_HISTORY}]}}componentDidMount(){const{glEventHub:e,session:t}=this.props;e.on(Bt.FOCUS_HISTORY,this.handleFocusHistory),t!=null&&this.loadTable()}componentWillUnmount(){const{glEventHub:e}=this.props;e.off(Bt.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(Yo.debug("handleSendToNotebook",n,e),!n){Yo.error("Session is not connected.");return}const{glEventHub:i}=this.props;i.emit(t?Le.CREATE_NOTEBOOK:Le.SEND_TO_NOTEBOOK,n,s,e)}handleSendToConsole(e,t=!0,n=!1){Yo.debug("handleSendToConsole",e);const{glEventHub:s}=this.props;s.emit(Bt.SEND_COMMAND,e,t,n)}loadTable(){const{commandHistoryStorage:e}=this.props,{language:t,sessionId:n}=this.state;D(t),D(n),this.pending.add(e.getTable(t,n,Date.now()),s=>s.close()).then(s=>{this.setState({table:s})}).catch(qr.handleError)}render(){const{glContainer:e,glEventHub:t,commandHistoryStorage:n}=this.props,{language:s,contextActions:i,table:o}=this.state;return r.jsxs(Xn,{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($f,{ref:this.container,language:s,sendToNotebook:this.handleSendToNotebook,sendToConsole:this.handleSendToConsole,table:o,commandHistoryStorage:n}),r.jsx(te,{actions:i})]})]})}}const vy=(c,e)=>{const t=Sh(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}},Ty=mt(vy,null,null,{forwardRef:!0})(qr),xl=Ty;const qo=J.module("ConsolePanel"),Ey=500,yy=Object.freeze({consoleSettings:{},itemIds:[]});class Ry 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=oe.createRef();const{panelState:t}=e,n={...yy,...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(Se.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(Se.MOUNT,this.handlePanelMount),this.objectSubscriptionCleanup?.()}consoleRef;objectSubscriptionCleanup;subscribeToFieldUpdates(){const{sessionWrapper:e}=this.props,{session:t}=e;this.objectSubscriptionCleanup=t.subscribeToFieldUpdates(n=>{qo.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=Ge.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(Bt.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(Se.CLOSE,n)}}handleSettingsChange(e){const{glEventHub:t}=this.props;qo.debug("handleSettingsChange",e),this.setState({consoleSettings:e}),t.emit(Bt.SETTINGS_CHANGED,e)}openWidget(e,t){const{glEventHub:n}=this.props,{title:s}=e;D(s);const i=this.getItemId(s),o={fetch:()=>t.getObject(e),panelId:i,widget:e};qo.debug("openWidget",o),n.emit(Se.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(Se.CLOSE,l)}),this.setState({itemIds:new Map})}savePanelState=We(()=>{const{consoleSettings:e,itemIds:t}=this.state,n={consoleSettings:e,itemIds:[...t]};qo.debug("Saving panel state",n),this.setState({panelState:n})},Ey);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={},dh:p}=s,{workerName:f,processInfoId:C}=g,{id:S,type:b}=h;return r.jsx(Xn,{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(Ff,{dh:p,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:lh.LANGUAGE_MAP.get(b)}),f!=null&&r.jsxs(r.Fragment,{children:[r.jsx("div",{children:" • "}),f]}),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(aC,{connection:m,defaultUpdateInterval:10*1e3,hoverUpdateInterval:3*1e3,monitorDuration:10*60*1e3})}),r.jsx("div",{children:" "})]}),scope:S,timeZone:i,objectMap:d,unzip:o})})}}const xy=(c,e)=>({commandHistoryStorage:Sh(c),sessionWrapper:Qs(c,e.localDashboardId),timeZone:go(c)}),Iy=mt(xy,null,null,{forwardRef:!0})(Ry),fi=Iy;const Xo=J.module("DropdownFilter"),Dy=150;class Ji 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=oe.createRef();const{column:t,isValueShown:n,value:s}=e;this.state={column:t,id:Ge(),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=ce((e,t)=>e!=null?t.filter(({type:n})=>n!==void 0&&F.isCompatibleType(n,e.columnType)):[]);getColumnOptions=ce((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=ce((e,t)=>e.indexOf(t));getValueOptions=ce(e=>[r.jsx("option",{value:"-1",children:Ji.PLACEHOLDER},"-1"),...e.map((t,n)=>r.jsx("option",{value:n,children:t??"(null)"},`${n}/${t}`))]);getItemLabel=we((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(Xo.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(),Xo.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]:Xo.debug2("Selected default item"),Xo.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=We(()=>{const{onChange:e}=this.props,{column:t,value:n,isValueShown:s}=this.state;e({column:t,isValueShown:s,value:n??void 0})},Dy);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:f,value:C}=this.state,S=i===null,b=this.getCompatibleColumns(i,e),w=i!=null,T=i?.columnName??Ji.SOURCE_BUTTON_PLACEHOLDER,E=u!=null?`${u.name} Filter`:null,[y,R]=this.getColumnOptions(b,f),I=this.getValueOptions(d),x=this.getSelectedOptionIndex(d,C),A=!w||f==null,k=p&&!n,_=`source-column-btn-${g}`,M=`filter-column-select-${g}`;return r.jsxs(or,{className:"dropdown-filter fill-parent-absolute",isFlipped:k,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:_,children:"Source Column"}),r.jsx(Gc,{id:_,isLinked:w,onClick:o,onMouseEnter:l,onMouseLeave:a,className:Ji.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:M,children:"Filter Column"}),r.jsx("select",{id:M,value:R,className:"custom-select",onChange:this.handleColumnChange,disabled:S,children:y}),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}),w&&r.jsxs("div",{className:"dropdown-filter-settings-buttons",children:[r.jsx(P,{kind:"secondary",type:"button",onClick:this.handleSettingsCancel,disabled:m||p||n,tooltip:n?"Cancel disabled while linker open":void 0,children:"Cancel"}),r.jsx(P,{kind:"primary",type:"button",className:"ml-2",onClick:this.handleSettingsSave,disabled:A||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:E})}),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:x,ref:this.dropdownRef,onChange:this.handleValueChange,onKeyPress:this.handleDropdownKeyPress,title:"Select Value",children:I})}),h&&r.jsx("div",{className:"error-message mt-3 text-center",children:h})]}),r.jsx("div",{className:"dropdown-filter-menu",children:r.jsx(P,{kind:"ghost",className:"m-2 px-2",onClick:this.handleSettingsClick,icon:r.jsx(X,{icon:uo,transform:"grow-4"}),tooltip:"Dropdown Filter Settings"})})]})})]})}}const hc=Ji;const Xe=J.module("DropdownFilterPanel"),Fy=250,Ny=(c,e)=>{const{localDashboardId:t}=e,n=V.getIdFromPanel({props:e}),s=Gr(c,t),i=Fi(c,t),o=ql(c),l=zr(c,t),a=o===Ot.LINKER&&(l===void 0||l===n),d=o===Ot.LINKER&&l!==void 0&&l!==n;return{columns:ku(c,t),columnSelectionValidator:Kr(c,t),dh:Kl(c),isLinkerActive:a,disableLinking:d,settings:gt(c),panelTableMap:s,dashboardLinks:i}},ky=mt(Ny,null,null,{forwardRef:!0});class Vs extends v.Component{static displayName="DropdownFilterPanel";static COMPONENT="DropdownFilterPanel";static MAX_TABLE_SIZE=256;static SOURCE_COLUMN=Object.freeze({name:"FilterSource",type:null});constructor(e){super(e),this.handleChange=We(this.handleChange.bind(this),Fy),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=oe.createRef(),this.panelContainer=oe.createRef(),this.pending=new qn;const{dh:t,panelState:n,settings:s}=e;this.columnFormats=Wn.getColumnFormats(s),this.dateTimeFormatter=new it(t,{showTimeZone:!1,showTSeparator:!0,defaultDateTimeFormatString:"yyyy-MM-dd HH:mm:ss.SSSSSSSSS"});const{value:i="",isValueShown:o=!1,name:l,type:a,timestamp:d}=n??{},h=l!=null&&a!=null?{name:l,type:a}:void 0;this.state={column:h,formatter:new gn(t,this.columnFormats),valuesTable:void 0,valuesColumn:void 0,sourceSize:0,value:i,timestamp:d,values:[],isValueShown:o,wasFlipped:!1,skipUpdate:!1,panelState:n,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&&(Xe.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()}dateTimeFormatter;dropdownFilterRef;panelContainer;pending;cleanup;columnFormats;getCachedValues=we((e,{type:t,name:n},s)=>t!==void 0&&F.isDateType(t)?e.map(i=>this.dateTimeFormatter.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(`.${hc.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>Vs.MAX_TABLE_SIZE)return`Table too large, must have fewer than ${Vs.MAX_TABLE_SIZE} options.`}getPanelErrorMessage(){const{error:e}=this.state;return e!=null?`${e}`:void 0}getCachedPanelLinks=we((e,t)=>{const n=V.getIdFromPanel(t);return Xe.debug("getCachedPanelLinks",e,n),e.filter(s=>s.end?.panelId===n)});getCachedSource=we(e=>{Xe.debug("getCachedSource",e);let t;if(e.length>0){const[n]=e;t=n.start,e.length>1&&Xe.error("Filter has more that one link",e)}return t});getCachedSourceTable=we((e,t)=>{if(Xe.debug("getCachedSourceTable",e,t),t==null)return null;const{panelId:n}=t;return e.get(n)??null});getCachedSourceColumn=we((e,t)=>(Xe.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){const{dh:t}=this.props;Xe.debug("startListeningToSource"),e.addEventListener(t.Table.EVENT_FILTERCHANGED,this.handleSourceFilterChange),e.addEventListener(t.Table.EVENT_SORTCHANGED,this.handleSourceSortChange),e.addEventListener(t.Table.EVENT_SIZECHANGED,this.handleSourceSizeChange),e.addEventListener(t.Table.EVENT_DISCONNECT,this.handleDisconnect),e.addEventListener(t.Table.EVENT_RECONNECT,this.handleReconnect)}stopListeningToSource(e){const{dh:t}=this.props;Xe.debug("stopListeningToSource"),e.removeEventListener(t.Table.EVENT_FILTERCHANGED,this.handleSourceFilterChange),e.removeEventListener(t.Table.EVENT_SORTCHANGED,this.handleSourceSortChange),e.removeEventListener(t.Table.EVENT_SIZECHANGED,this.handleSourceSizeChange),e.removeEventListener(t.Table.EVENT_DISCONNECT,this.handleDisconnect),e.removeEventListener(t.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(){Xe.debug("handleColumnSelected");const{glEventHub:e}=this.props;e.emit(Ke.COLUMN_SELECTED,this,Vs.SOURCE_COLUMN)}handleClearAllFilters(){this.dropdownFilterRef?.current?.clearFilter()}setPanelState(e,t=!1){const{dashboardLinks:n}=this.props;if(this.getSource(n)==null){Xe.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];Xe.debug("sendUpdate",{name:e,type:t,value:n,timestamp:s,excludePanelIds:a}),o.emit(Ke.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(Xe.debug("updateValuesTable",n,s),this.setState({values:[],valuesTable:void 0,error:null}),n==null){Xe.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=>{be.isCanceled(i)||(Xe.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(Xe.debug("applySourceSorts",s?.sort),n==null||s==null){Xe.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(Xe.debug("applySourceFilters",s?.filter),n==null||s==null){Xe.debug("Table not initialized");return}const i=[...s.filter];n.applyFilter(i),this.setViewport(n)}updateViewportListener(e){const{dh:t}=this.props;if(Xe.debug("updateViewportListener",e?.size),this.cleanup&&this.cleanup(),e==null){this.cleanup=void 0;return}this.cleanup=e.addEventListener(t.Table.EVENT_UPDATED,this.handleValuesTableUpdate),this.setViewport(e)}setViewport(e){const{dashboardLinks:t}=this.props,n=this.getValuesColumn(e,t);if(!n){Xe.error("values column is null");return}e.setViewport(0,Vs.MAX_TABLE_SIZE-1,[n])}updateFormatterSettings(e){const{dh:t}=this.props,n=Wn.getColumnFormats(e);Ze(this.columnFormats,n)||(this.columnFormats=n,this.setState({formatter:new gn(t,n)}))}handleValuesTableUpdate({detail:e}){const{rows:t}=e,{dashboardLinks:n}=this.props,{valuesTable:s}=this.state;if(!s){Xe.error("valuesTable is null");return}const i=this.getValuesColumn(s,n);if(!i){Xe.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,Vs.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:f}=this.state,C=this.getSource(t),S=this.getSettingsErrorMessage(),b=this.getPanelErrorMessage(),w=f&&g!=null?this.getCachedValues(m,g,a):[];return r.jsx($r,{errorMessage:b,isLoading:p,isLoaded:f,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(hc,{ref:this.dropdownFilterRef,column:l,columns:e,isValueShown:h,isLinkerActive:o,disableLinking:n,isLoaded:f,settingsError:S,source:C,value:u,values:w,onChange:this.handleChange,onColumnSelected:this.handleColumnSelected,onSourceMouseEnter:this.handleSourceMouseEnter,onSourceMouseLeave:this.handleSourceMouseLeave})})})}}const My=ky(Vs),qs=My;function Dn(c){return c.type==="directory"}var Au=(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))(Au||{});class $s{static fileExtensionToString(e=""){return e.length===0?"":`.${e}`}static getDepth(e){if(!$s.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(!$s.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(!$s.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=$s.fileExtensionToString(t);return`${s}${i}`}static validateName(e){const t=[".",".."],n=/[\\/\0]/g,s=new Map([["\0","null"]]);if(!e)throw new wi("Name cannot be empty");if(t.includes(e))throw new wi(`"${e}" is a reserved name`);if(n.test(e))throw new wi(`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=>$s.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 me=$s,Xr=26;function Za(c){return Dn(c)?me.makePath(c.filename):me.getPath(c.filename)}function uc(c,e){if(c.length===0||e==null)throw new Error("No items to move");const t=Za(e);if(c.some(({filename:n})=>me.getPath(n)===t))throw new Error("File already in the destination folder");if(c.some(n=>Dn(n)&&t.startsWith(me.makePath(n.filename))))throw new Error("Destination folder cannot be a child of a dragged folder");return{files:c,targetPath:t}}function Oy(c){if(Dn(c))return c.isExpanded?Lg:_g;switch(me.getMimeType(c.basename)){case Au.PYTHON:return jg;default:return Pg}}function Qa(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(y=>y.id===o.id)??!1,p=Za(o),f=n&&a?Za(a):null,C=n&&s&&Dn(o)&&f===p,S=n&&s&&f===p,b=n&&!s&&f===p,w=Oy(o),T=me.getDepth(o.filename),E=Array(T).fill(null).map((y,R)=>r.jsx("span",{className:"file-list-depth-line"},R));return r.jsxs("div",{className:z("d-flex w-100 align-items-center","file-list-item",{"is-dragged":g,"is-exact-drop-target":C,"is-in-drop-target":S,"is-invalid-drop-target":b,"is-selected":i}),onDragStart:y=>d(l,y),onDragOver:y=>h(l,y),onDragEnd:y=>u(l,y),onDrop:y=>m(l,y),draggable:!0,role:"presentation","aria-label":o.basename,children:[E," ",r.jsx(X,{icon:w,className:"item-icon",fixedWidth:!0})," ",r.jsxs("span",{className:"truncation-wrapper",children:[e??o.basename,r.jsx(Je,{options:{placement:"left"},children:e??o.basename})]})]})}const Et=J.module("FileList"),Ay=500,mc="item-list-scroll-pane";function Ly(c){const{isMultiSelect:e=!1,table:t,onFocusChange:n=()=>{},onMove:s,onSelect:i,onSelectionChange:o=()=>{},renderItem:l=Qa,rowHeight:a=Xr,overscanCount:d=Ei.DEFAULT_OVERSCAN}=c,[h,u]=v.useState(()=>({items:[],offset:0,itemCount:0})),[m,g]=v.useState({top:0,bottom:0}),[p,f]=v.useState(),[C,S]=v.useState(),[b,w]=v.useState(),[T,E]=v.useState([]),y=v.useRef(null),R=v.useRef(null),I=v.useCallback(q=>{if(q.length===0||h==null)return[];const ne=[];for(let he=0;he<q.length;he+=1){const Te=q[he];for(let ye=Te[0];ye<=Te[1];ye+=1)ye>=h.offset&&ye<h.offset+h.items.length&&ne.push(h.items[ye-h.offset])}return ne},[h]),x=v.useCallback(q=>{const ne=I([[q,q]]);if(ne.length>0)return ne[0]},[I]),A=v.useCallback(()=>{const q=ud.count(T);if(q===0)return null;if(q===1){const ne=T[0][0],he=x(ne);if(he!=null)return he.filename}return`${q} items`},[x,T]),k=v.useCallback(q=>{if(!(!C||!p)){Et.debug("dropItems",C,"to",q);try{const{files:ne,targetPath:he}=uc(C,p);s?.(ne,he),q!=null&&(E([[q,q]]),y.current?.focusItem(q))}catch(ne){Et.error("Unable to complete move",ne)}}},[C,p,s]),_=v.useCallback((q,ne)=>{const he=h.items[q-h.offset];he!==void 0&&(Et.debug("handleItemClick",he),i(he,ne),Dn(he)&&t?.setExpanded(he.filename,!he.isExpanded))},[h,i,t]),M=v.useCallback((q,ne)=>{Et.debug2("handleItemDragStart",q,T);let he=T;ud.isSelected(T,q)||(he=[[q,q]],E(he)),S(I(he)),y.current?.resetMouseState();const Te=document.createElement("div");Te.innerHTML=`<div class="dnd-placeholder-content">${A()}</div>`,Te.className="file-list-dnd-placeholder",document.body.appendChild(Te),ne.dataTransfer.setDragImage(Te,0,0),ne.dataTransfer.effectAllowed="move",w(Te)},[A,I,T]),$=v.useCallback((q,ne)=>{ne.preventDefault(),Et.debug2("handleItemDragOver",ne),f(x(q))},[x]),H=v.useCallback((q,ne)=>{Et.debug("handleItemDragEnd",q),b?.remove(),S(void 0),f(void 0),w(void 0)},[b]),K=v.useCallback((q,ne)=>{k(q)},[k]),L=v.useCallback(()=>{Et.debug2("handleItemDragExit"),f(void 0)},[]),G=v.useCallback(q=>{q.target instanceof Element&&q.target.classList.contains(mc)&&(q.preventDefault(),Et.debug2("handleListDragOver",q),f({type:"directory",filename:"/",basename:"/",id:"/"}))},[]),ee=v.useCallback(q=>{q.target instanceof Element&&q.target.classList.contains(mc)&&(Et.debug("handleListDrop"),k())},[k]),W=v.useCallback(q=>{if(Et.debug2("handleSelectionChange",q),q!==T){E(q);const ne=I(q);o(ne)}},[I,o,T]),j=v.useCallback(q=>{if(Et.debug2("handleFocusChange",q),q!=null){const[ne]=I([[q,q]]);n(ne)}else n()},[I,n]),B=v.useCallback((q,ne)=>{Et.debug("handleViewportChange",q,ne),(q!==m.top||ne!==m.bottom)&&g({top:q,bottom:ne})},[m]),Z=v.useMemo(()=>{if(!C||!p)return!1;try{return uc(C,p),Et.debug("handleValidateDropTarget true"),!0}catch{return Et.debug("handleValidateDropTarget false"),!1}},[C,p]),{focusedPath:se}=c;v.useEffect(()=>{se!==void 0&&(se==="/"?t.collapseAll():(t.setExpanded(se,!1),t.setExpanded(se,!0)))},[t,se]),v.useEffect(function(){Et.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 ne=t.onUpdate(he=>{u({items:he.items.map(Te=>({...Te,itemName:Te.basename})),offset:he.offset,itemCount:t.size})});return()=>{ne()}},[t]),v.useEffect(function(){if(p!=null&&Dn(p)&&p.filename!=="/"){const ne=setTimeout(()=>{p.isExpanded||t?.setExpanded(p.filename,!0)},Ay);return()=>clearTimeout(ne)}},[p,t]);const ae=v.useCallback(q=>l({...q,isDragInProgress:C!=null,dropTargetItem:p,draggedItems:C,isDropTargetValid:Z,onDragStart:M,onDragEnd:H,onDragOver:$,onDragExit:L,onDrop:K}),[H,L,$,M,K,C,p,Z,l]);return r.jsx("div",{ref:R,className:z("file-list",{"is-dragging":C!=null}),onDragOver:G,onDrop:ee,children:r.jsx(Ei,{ref:y,items:h.items,itemCount:h.itemCount,offset:h.offset,onFocusChange:j,onSelect:_,onSelectionChange:W,onViewportChange:B,selectedRanges:T,renderItem:ae,rowHeight:a,isMultiSelect:e,isDragSelect:!1,isDeselectOnClick:!1})})}const _y={name:"File Explorer",DELETE:He.createAndAdd({id:"FILE_EXPLORER.DELETE",name:"Delete",shortcut:[ve.DELETE],macShortcut:[fe.CMD,ve.BACKSPACE]}),RENAME:He.createAndAdd({id:"FILE_EXPLORER.RENAME",name:"Rename",shortcut:[ve.ENTER],macShortcut:[ve.ENTER]})},gc={FILE_EXPLORER:_y};const pc=J.module("FileListItemEditor"),Py=()=>Promise.resolve();function jy({item:c,onCancel:e,onSubmit:t,validate:n=Py}){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(S=>S.stopPropagation(),[]),g=v.useCallback(()=>{d.then(()=>{t(i)}).catch(S=>pc.info("Unable to validate name",S))},[t,i,d]);v.useEffect(function(){const b=be.makeCancelable(n(i));return b.then(()=>a(void 0)).catch(w=>{be.isCanceled(w)||a(w)}),h(b),()=>b.cancel()},[n,i]),v.useEffect(function(){u()},[u]);const p=v.useCallback(()=>{pc.debug2("handleBlur"),g()},[g]),f=v.useCallback(S=>{const{value:b}=S.target;o(b)},[]),C=v.useCallback(S=>{S.stopPropagation();const{key:b}=S;switch(b){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:z("form-control file-list-item-editor-input",{"is-invalid":l}),value:i,ref:s,onBlur:p,onKeyDown:C,onChange:f,onClick:m,onDoubleClick:m,onMouseDown:m}),l&&r.jsx("div",{className:"invalid-feedback",children:`${l}`})]})}function Lu(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=Xr,validateRename:p=()=>Promise.resolve()}=c,[f,C]=v.useState(),[S,b]=v.useState([]),[w,T]=v.useState(),E=v.useCallback(L=>{b(L),u?.(L)},[u]),y=v.useCallback(L=>{T(L)},[]),R=v.useCallback(()=>{w&&o?.(w)},[w,o]),I=v.useCallback(()=>{S.length>0&&l?.(S)},[l,S]),x=v.useCallback(()=>{s?.()},[s]),A=v.useCallback(()=>{w&&i?.(me.getPath(w.filename))},[w,i]),k=v.useCallback(()=>{w&&C(w)},[w]),_=v.useCallback(()=>{C(void 0)},[]),M=v.useCallback(L=>{f&&(d?.(f,L),C(void 0))},[d,f]),$=v.useMemo(()=>{if(f)return[];const L=[];return s&&L.push({title:"New File",description:"Create new file",action:x,group:te.groups.medium}),i&&L.push({title:"New Folder",description:"Create new folder",action:A,group:te.groups.medium}),o&&L.push({title:"Copy",description:"Copy",action:R,group:te.groups.low,disabled:w==null||Dn(w)}),l&&S.length>0&&L.push({title:"Delete",description:"Delete",shortcut:gc.FILE_EXPLORER.DELETE,action:I,group:te.groups.low}),d&&L.push({title:"Rename",description:"Rename",shortcut:gc.FILE_EXPLORER.RENAME,action:k,group:te.groups.low,disabled:w==null}),L},[R,I,x,A,k,w,o,s,i,l,d,S,f]),H=v.useCallback(L=>(D(f),p(f,L)),[f,p]),K=v.useCallback(L=>{const{item:G}=L;return f&&f.filename===G.filename?r.jsx(Qa,{...L,children:r.jsx(jy,{item:G,validate:H,onSubmit:M,onCancel:_})}):r.jsx(Qa,{...L})},[_,M,f,H]);return r.jsxs("div",{className:"file-list-container",children:[m!=null&&r.jsx(Ly,{onMove:a,onSelect:h,onSelectionChange:E,onFocusChange:y,renderItem:K,rowHeight:g,table:m,isMultiSelect:e,focusedPath:t}),n&&r.jsx(te,{actions:$})]})}Lu.displayName="FileListContainer";class Hy extends wi{isExistingFile=!0;info;constructor(e){super("Name already exists"),this.info=e}}const il=Hy;class Uy extends Error{constructor(){super("No file exists at the path specified")}isFileNotFound=!0}const Zr=Uy,Ls=J.module("FileExplorer");function Qr(c){const{storage:e,isMultiSelect:t=!1,focusedPath:n,onDelete:s=()=>{},onRename:i=()=>{},onSelect:o,onSelectionChange:l,rowHeight:a=Xr}=c,[d,h]=v.useState([]),[u,m]=v.useState();v.useEffect(function(){let R;async function I(){Ls.debug("initTable"),R=be.makeCancelable(e.getTable(),x=>x.close());try{m(await R)}catch(x){be.isCanceled(x)||Ls.error("Unable to initialize table",x)}}return I(),()=>{R.cancel()}},[e]);const g=v.useCallback(y=>{be.isCanceled(y)||Ls.error(y)},[]),p=v.useCallback(y=>{Ls.debug("handleDelete, pending confirmation",y),h(y)},[]),f=v.useCallback(()=>{Ls.debug("handleDeleteConfirm",d),d.forEach(y=>e.deleteFile(Dn(y)?me.makePath(y.filename):y.filename)),s(d),h([])},[d,s,e]),C=v.useCallback(()=>{Ls.debug("handleDeleteCancel"),h([])},[]),S=v.useCallback((y,R)=>{me.reducePaths(y.map(x=>Dn(x)?me.makePath(x.filename):x.filename)).forEach(x=>{const A=me.isPath(x)?`${R}${me.getBaseName(x.substring(0,x.length-1))}/`:`${R}${me.getBaseName(x)}`;e.moveFile(x,A).then(()=>{i(x,A)}).catch(g)})},[g,i,e]),b=v.useCallback((y,R)=>{let I=y.filename;const x=Dn(y);x&&!I.endsWith("/")&&(I=`${I}/`);let A=`${me.getParent(I)}${R}`;x&&!A.endsWith("/")&&(A=`${A}/`),Ls.debug2("handleRename",I,A),e.moveFile(I,A).catch(g),i(I,A)},[g,i,e]),w=v.useCallback(async(y,R)=>{if(R===y.basename)return;me.validateName(R);const I=`${me.getPath(y.filename)}${R}`;try{const x=await e.info(I);throw new il(x)}catch(x){if(!(x instanceof Zr))throw x}},[e]),T=d.length>0,E=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(Lu,{isMultiSelect:t,focusedPath:n,showContextMenu:!0,onMove:S,onDelete:p,onRename:b,onSelect:o,onSelectionChange:l,rowHeight:a,table:u,validateRename:w}),r.jsx(io,{isOpen:T,headerText:E,bodyText:"You cannot undo this action.",onCancel:C,onConfirm:f,confirmButtonText:"Delete"})]})}Qr.displayName="FileExplorer";const _s=J.module("NewItemModal");class eo extends v.PureComponent{static propTypes={isOpen:U.bool,title:U.string.isRequired,defaultValue:U.string,type:U.oneOf(["file","directory"]).isRequired,onSubmit:U.func,onCancel:U.func,placeholder:U.string,storage:U.shape({}).isRequired,notifyOnExtensionChange:U.bool};static defaultProps={isOpen:!1,defaultValue:"/",notifyOnExtensionChange:!1,placeholder:"",onSubmit:(e,t)=>{},onCancel:()=>{}};static getValidationMessage(e){return e instanceof il&&e.info.type==="directory"?"Error: Cannot overwrite existing directory":`${e}`}static handleError(e){be.isCanceled(e)||_s.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=me.hasPath(t)?me.getPath(t):"/";this.state={isSubmitting:!1,path:n,prevExtension:me.getExtension(t),showExtensionChangeModal:!1,showOverwriteModal:!1,value:me.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=oe.createRef();cancelableValidatePromise;cancelableExistingItemPromise;pending=new qn;pathMap=new Map;isInitialLoad=!0;resetValue(){const{defaultValue:e}=this.props,t=me.hasPath(e)?me.getPath(e):"/";this.setState({path:t,value:me.getBaseName(e),validationError:void 0,prevExtension:me.getExtension(e),isSubmitting:!1})}getValidationPromise(e,t,n=!1){return this.cancelableValidatePromise&&this.cancelableValidatePromise.cancel(),this.cancelableValidatePromise=be.makeCancelable(this.validateName(e,t,n)),this.cancelableValidatePromise}async validateName(e,t,n){me.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 il(l)}catch(l){if(!(l instanceof Zr))throw l}}return t}updateValidationStatus(e,t){this.getValidationPromise(e,t).then(()=>{this.setState({validationError:void 0})}).catch(this.handleValidationError).catch(eo.handleError)}handleModalOpened(){this.focusRenameInput()}handleModalSubmit(){this.submitModal()}handleChange(e){const{value:t}=e.target;this.setState({value:t})}handleSelect(e){if(_s.debug("handleSelect",e),e.type==="directory")this.setState({path:me.makePath(e.filename)});else{const t=e.basename,n=me.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 wi))throw e;_s.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;_s.debug("handleOverwriteConfirm",t,n),e(`${t}${n}`,!0)}handleExtensionChangeCancel(){_s.debug("handleExtensionChangeCancel"),this.setState(({value:e,prevExtension:t})=>({showExtensionChangeModal:!1,value:me.replaceExtension(e,t)})),this.submitModal(!0)}handleExtensionChangeConfirm(){_s.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;_s.debug("submitModal",t,n);const l=me.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 il&&o!=="directory"&&a.info.type!=="directory"){this.setState({showOverwriteModal:!0});return}throw a}).catch(a=>{throw be.isCanceled(a)&&this.setState({isSubmitting:!1}),a}).catch(this.handleValidationError).catch(eo.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(oe.Fragment,{children:[r.jsx(P,{kind:"ghost",className:"directory-breadcrumbs",onClick:()=>this.handleBreadcrumbSelect(i),"aria-label":s===0?"Home":void 0,icon:s===0?r.jsx(X,{icon:Hg,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,f=o==="directory",C=me.fileExtensionToString(g),S=me.fileExtensionToString(p),b=f?"Create":"Save",w=f?"New folder name":"Save file as";return r.jsxs(r.Fragment,{children:[r.jsxs($l,{isOpen:t,toggle:n,onOpened:this.handleModalOpened,className:"modal-dialog-centered new-file-modal theme-bg-dark",children:[r.jsx(Wl,{toggle:n,children:i}),r.jsx(Gl,{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:w}),r.jsx("input",{id:"file-name-input",type:"text",autoComplete:"off",autoCapitalize:"none",autoCorrect:"off",spellCheck:"false",className:z("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:eo.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(Qr,{onSelect:this.handleSelect,storage:e,focusedPath:a})})]})})}),r.jsxs(zc,{children:[r.jsx(P,{kind:"secondary",onClick:n,children:"Cancel"}),r.jsx(P,{kind:"primary",disabled:l,onClick:this.handleModalSubmit,children:b})]})]}),r.jsx(io,{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(io,{isOpen:d,headerText:"Confirm extension change",bodyText:`Are you sure you want to change extension from "${C}" to "${S}"?`,onCancel:this.handleExtensionChangeCancel,onConfirm:this.handleExtensionChangeConfirm,cancelButtonText:`Keep "${C}"`,confirmButtonText:`Use "${S}"`})]})}}const _u=eo;function By({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(P,{kind:"ghost",icon:Zc,tooltip:"New notebook",onClick:c,"aria-label":"New notebook"}),r.jsx(P,{kind:"ghost",icon:Ug,tooltip:"New folder",onClick:e,"aria-label":"New folder"})]}),t&&r.jsx("div",{className:"file-explorer-toolbar-search",children:r.jsx(Om,{value:n,onChange:t,placeholder:"Search by name"})})]})}const ri=J.module("FileExplorerPanel"),Vy=(c,e)=>{const t=bh(c),n=Qs(c,e.localDashboardId),{session:s,config:i}=n??{},o=i?.type;return{fileStorage:t,language:o,session:s}},$y=mt(Vy,null,null,{forwardRef:!0});function Wy(c){const e=c;return e!=null&&typeof e.button=="number"}class Il extends oe.Component{static COMPONENT="FileExplorerPanel";static TITLE="File Explorer";static handleError(e){ri.error(e)}static isFocusEvent(e){return Wy(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:""};ri.debug("handleCreateFile",t,n,s),e.emit(Le.CREATE_NOTEBOOK,t,n,s)}handleCreateDirectory(e){this.setState({showCreateFolder:!0})}handleCreateDirectoryCancel(){ri.debug("handleCreateDirectoryCancel"),this.setState({showCreateFolder:!1})}handleCreateDirectorySubmit(e){ri.debug("handleCreateDirectorySubmit",e),this.setState({showCreateFolder:!1});const{fileStorage:t}=this.props;t.createDirectory(e).catch(Il.handleError)}handleDelete(e){const{glEventHub:t}=this.props;e.forEach(n=>{t.emit(Le.CLOSE_FILE,{id:n.filename,itemName:n.filename})})}handleSelectionChange(e){let t="/";e.length===1&&(e[0].type==="directory"?t=me.makePath(e[0].filename):t=me.getPath(e[0].filename)),this.setState({focusedFilePath:t})}handleFileSelect(e,t){if(ri.debug("fileSelect",e),e.type==="directory")return;const n=Il.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(Le.SELECT_NOTEBOOK,o,l,a,s,n)}handleRename(e,t){const{glEventHub:n}=this.props;ri.debug("handleRename",e,t),n.emit(Le.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(Xn,{className:"file-explorer-panel",componentPanel:this,glContainer:t,glEventHub:n,onSessionOpen:this.handleSessionOpened,onSessionClose:this.handleSessionClosed,onShow:this.handleShow,children:[r.jsx(By,{createFile:this.handleCreateFile,createFolder:this.handleCreateDirectory}),s&&r.jsx(Qr,{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 Gy=$y(Il),Dl=Gy;const Qe=J.module("FilterSetManager"),zy="Enter name...",fc="No Available Filter Sets";class Fl 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=oe.createRef();dropdownRef=oe.createRef();editDropdownRef=oe.createRef();initSettingsScreen(){const{filterSets:e,selectedId:t}=this.props;Qe.debug("initSettingsScreen",e,t),this.setState({modifiedFilterSets:[...e],editId:t})}updateSelectedId(){const{isValueShown:e,filterSets:t,selectedId:n,onChange:s}=this.props;if(Qe.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:[]}),Qe.debug("Update sets",n,s),t(n),n.length>0&&e({isValueShown:!0,selectedId:s})}handleCaptureNewSet(){const{getFilterState:e}=this.props;Fl.animateScreenFlash();const t=Ge(),n=e(),s={id:t,title:"",panels:n};Qe.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 Qe.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 Qe.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){Qe.error("Renamed set undefined.");return}const i=this.getNameError(e);if(Qe.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,Qe.debug("Renamed existing set",d)):(d.push(l),Qe.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 Qe.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 Qe.debug("Deleted selected set",t,n,i),Qe.debug("New selection",o,l),{modifiedFilterSets:i,editId:l}})}handleSetUpdate(){const{getFilterState:e}=this.props;Fl.animateScreenFlash();const t=e();this.setState(({modifiedFilterSets:n,editId:s})=>{if(s===void 0)return Qe.error("Filter for update not selected."),null;const i=[...n],o=i.findIndex(({id:l})=>l===s);return o<0?(Qe.error("Selected set for update not found."),null):(i[o]={...i[o],panels:t},Qe.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 Qe.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){Qe.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=ce((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){Qe.debug("No filter selected");return}const s=n.find(({id:i})=>i===e);if(s===void 0){Qe.debug("Selected id not found in filterSets",e,n);return}Qe.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,f=r.jsxs("div",{className:"fa-layers mr-3",children:[r.jsx(X,{icon:yi,mask:Ua,transform:"shrink-1 down-5 right-7"}),r.jsx(X,{icon:Ts,className:"text-primary",transform:"shrink-6 down-5 right-7"})]}),C=r.jsxs("div",{className:"fa-layers",children:[r.jsx(X,{icon:yi,mask:Ua,transform:"shrink-1 down-5 right-7"}),r.jsx(X,{icon:Ba,transform:"shrink-1 down-5 right-7"})]});return r.jsx("div",{className:"filter-set-manager fill-parent-absolute",children:r.jsxs(or,{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(P,{kind:"ghost",className:"btn btn-link no-underline",onClick:this.handleCaptureNewSet,icon:f,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:zy,value:e,ref:this.renameInputRef,onChange:this.handleNameInputChange,onKeyPress:this.handleNameInputKeyPress,spellCheck:"false"}),r.jsx(P,{"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:sh}),r.jsx(P,{"data-testid":"rename-cancel-button",kind:"ghost",className:"btn btn-link no-underline pt-2 pb-2",onClick:this.handleRenameCancel,tooltip:"Cancel",icon:Bg})]}),t!==void 0&&r.jsx("div",{className:"error-message",children:t})]}),r.jsx("div",{className:"form-group",children:r.jsxs(Hl,{onChange:this.handleRestoreFullStateChange,value:`${o}`,children:[r.jsx(Gn,{value:"false",children:"Restore only filters"}),r.jsx(Gn,{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:fc}),i.map(({id:S,title:b})=>r.jsx("option",{value:S,children:b},S))]}),r.jsx(P,{kind:"ghost",onClick:this.handleSetUpdate,disabled:m,icon:C,tooltip:"Update"}),r.jsx(P,{kind:"ghost",onClick:this.handleSetEdit,disabled:m,icon:mo,tooltip:"Edit"}),r.jsx(P,{kind:"ghost",onClick:this.handleSetDelete,disabled:m,icon:$t,tooltip:"Delete"})]})]}),r.jsx("div",{children:r.jsx(P,{kind:"ghost",className:"btn btn-link no-underline",onClick:this.handleCaptureNewSet,icon:f,children:"Capture new filter set"})}),r.jsxs("div",{className:"py-3 text-right",children:[r.jsx(P,{kind:"secondary",onClick:this.handleSettingsCancel,children:"Cancel"})," ",r.jsx(P,{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:fc}),a.map(({id:S,title:b})=>r.jsx("option",{value:S,children:b},S))]}),r.jsx(P,{"data-testid":"filter-apply-button",kind:"ghost",onClick:this.handleFilterApply,icon:dr,tooltip:"Apply Filter Set"})]})})}),r.jsx("div",{className:"filter-set-manager-menu",children:r.jsx(P,{kind:"ghost",className:"btn btn-link btn-link-icon m-2 px-2",onClick:this.handleSettingsClick,tooltip:"Settings",icon:r.jsx(X,{icon:uo,transform:"grow-4"})})})]},"back")]})})}}const Ky=Fl;function Jr(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(sa,{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})]})})}Jr.propTypes={glContainer:Fr.Container.isRequired,widgetName:U.string.isRequired,description:U.string};Jr.defaultProps={description:null};const vn=J.module("IrisGridPanel"),Yy=500,qy={IrisGrid:Du,IrisGridTableModel:Fu,ContextMenuRoot:Kc};class Ja 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=oe.createRef(),this.pluginRef=oe.createRef();const{panelState:t}=e;this.pluginState=null,this.irisGridUtils=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(Su.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;irisGridUtils;getTableName(){const{metadata:e}=this.props;return e.table}getGridInputFilters=ce((e,t)=>Ce.getInputFiltersForColumns(e,t.filter(({value:n,excludePanelIds:s})=>{const i=V.getIdFromPanel(this);return n!=null&&(s==null||i!=null&&!s.includes(i))})));getAlwaysFetchColumns=ce((e,t)=>{const n=V.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=ce((e,t,n,s,i)=>!t||!Ys(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:qy,onStateChange:this.handlePluginStateChange,pluginState:i})}));getDehydratedIrisGridPanelState=ce((e,t,n,s,i)=>Ce.dehydrateIrisGridPanelState(e,{isSelectingPartition:t,partition:n,partitionColumn:s,advancedSettings:i}));getDehydratedIrisGridState=ce((e,t,n,s,i,o,l,a,d,h,u,m,g,p,f,C,S,b,w,T,E)=>(D(this.irisGridUtils),this.irisGridUtils.dehydrateIrisGridState(e,{advancedFilters:n,aggregationSettings:S,customColumnFormatMap:s,isFilterBarShown:i,metrics:{userColumnWidths:f,userRowHeights:C},quickFilters:o,customColumns:l,reverseType:a,rollupConfig:d,showSearchBar:h,searchValue:u,selectDistinctColumns:m,selectedSearchColumns:g,sorts:t,invertSearchColumns:p,pendingDataMap:b,frozenColumns:w,conditionalFormats:T,columnHeaderGroups:E})));getDehydratedGridState=ce((e,t,n,s,i)=>Ce.dehydrateGridState(e,{isStuckToBottom:s,isStuckToRight:i,movedColumns:t,movedRows:n}));getCachedPanelState=ce((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=be.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(this.irisGridUtils=new Ce(t.dh),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=Ce.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();vn.debug("initModelQueue",s),s&&s(n),this.setState({modelQueue:t})}handleAdvancedSettingsChange(e,t){vn.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;D(t);const{columns:n,formatter:s}=t,i=this.irisGridUtils?.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):(D(n),this.initModelQueue(n,s))}handleTableChanged(e){vn.debug("handleTableChanged",e);const{glEventHub:t}=this.props,{detail:n}=e;t.emit(Ke.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(Bt.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=V.getIdFromPanel(this);let d;l&&(d=Ce.extractTableSettings(l,s)),n.emit(cn.CREATE_CHART,{metadata:{settings:e,sourcePanelId:a,table:o,tableSettings:d},table:Ys(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){vn.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){be.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}),Ys(e)){const{table:s}=e,{pluginName:i}=s;if(i!==""&&n!=null&&i!=null){const o=n(i);this.setState({Plugin:o})}t.emit(Ke.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){vn.debug2("sendColumnsChange",e);const{glEventHub:t}=this.props;t.emit(Ke.COLUMNS_CHANGED,this,e)}startModelListening(e){e.addEventListener(ge.EVENT.DISCONNECT,this.handleDisconnect),e.addEventListener(ge.EVENT.RECONNECT,this.handleReconnect),e.addEventListener(ge.EVENT.COLUMNS_CHANGED,this.handleColumnsChanged),e.addEventListener(ge.EVENT.TABLE_CHANGED,this.handleTableChanged)}stopModelListening(e){e.removeEventListener(ge.EVENT.DISCONNECT,this.handleDisconnect),e.removeEventListener(ge.EVENT.RECONNECT,this.handleReconnect),e.removeEventListener(ge.EVENT.COLUMNS_CHANGED,this.handleColumnsChanged),e.removeEventListener(ge.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;D(n);const{metrics:o}=n.state;D(o);const{columnHeaderHeight:l,allColumnXs:a,allColumnWidths:d,right:h,columnHeaderMaxDepth:u}=o,m=t.getColumnIndexByName(e);D(m);const g=n.getVisibleColumn(m),p=a.get(g)??0,f=d.get(g)??0,C=Math.max(i.left,Math.min(g>h?i.right:i.left+p+f*.5,i.right)),S=i.top+l*u;return[C,S]}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}){vn.debug("setFilters",e,t);const{model:n,isDisconnected:s}=this.state,i=this.irisGrid.current;if(i==null||s){vn.debug("Ignore setFilters, model disconnected");return}D(n);const{columns:o,formatter:l}=n,a=Ce.changeFilterColumnNamesToIndexes(n.columns,e).filter(([h])=>n.isFilterable(h)),d=Ce.changeFilterColumnNamesToIndexes(n.columns,t).filter(([h])=>n.isFilterable(h));D(this.irisGridUtils),i.clearAllFilters(),i.setFilters({quickFilters:this.irisGridUtils.hydrateQuickFilters(o,a,l.timeZone),advancedFilters:this.irisGridUtils.hydrateAdvancedFilters(o,d,l.timeZone)})}setStateOverrides(e){vn.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=Ce.changeFilterColumnNamesToIndexes(e.columns,d)),h&&(a.advancedFilters=Ce.changeFilterColumnNamesToIndexes(e.columns,h));const{isSelectingPartition:u,partition:m,partitionColumn:g,advancedSettings:p}=Ce.hydrateIrisGridPanelState(e,l);D(this.irisGridUtils);const{advancedFilters:f,customColumns:C,customColumnFormatMap:S,isFilterBarShown:b,quickFilters:w,reverseType:T,rollupConfig:E,aggregationSettings:y,sorts:R,userColumnWidths:I,userRowHeights:x,showSearchBar:A,searchValue:k,selectDistinctColumns:_,selectedSearchColumns:M,invertSearchColumns:$,pendingDataMap:H,frozenColumns:K,conditionalFormats:L,columnHeaderGroups:G}=this.irisGridUtils.hydrateIrisGridState(e,{...o,...a}),{isStuckToBottom:ee,isStuckToRight:W,movedColumns:j,movedRows:B}=Ce.hydrateGridState(e,{...i,...s},o.customColumns);this.setState({advancedFilters:f,advancedSettings:p,conditionalFormats:L,customColumns:C,customColumnFormatMap:S,isFilterBarShown:b,isSelectingPartition:u,movedColumns:j,movedRows:B,partition:m,partitionColumn:g,quickFilters:w,reverseType:T,rollupConfig:E,aggregationSettings:y,sorts:R,userColumnWidths:I,userRowHeights:x,showSearchBar:A,searchValue:k,selectDistinctColumns:_,selectedSearchColumns:M,invertSearchColumns:$,pendingDataMap:H,frozenColumns:K,isStuckToBottom:ee,isStuckToRight:W,columnHeaderGroups:G})}catch(i){vn.error("loadPanelState failed to load panelState",t,i)}}savePanelState=We(()=>{const{irisGridState:e,gridState:t,pluginState:n}=this;D(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:f,customColumns:C,reverseType:S,rollupConfig:b,showSearchBar:w,searchValue:T,selectDistinctColumns:E,selectedSearchColumns:y,sorts:R,invertSearchColumns:I,metrics:x,pendingDataMap:A,frozenColumns:k,conditionalFormats:_,columnHeaderGroups:M}=e;D(i),D(x);const{userColumnWidths:$,userRowHeights:H}=x;D(t);const{isStuckToBottom:K,isStuckToRight:L,movedColumns:G,movedRows:ee}=t,W=this.getCachedPanelState(this.getDehydratedIrisGridPanelState(i,l,a,d,h),this.getDehydratedIrisGridState(i,R,u,g,p,f,C,S,b,w,T,E,y,I,$,H,m,A,k,_,M),this.getDehydratedGridState(i,G,ee,K,L),n);W!==o&&(vn.debug("Saving panel state",this,W),this.setState({panelState:W}),s?.(W))},Yy);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:f,advancedSettings:C,conditionalFormats:S,customColumns:b,customColumnFormatMap:w,error:T,isDisconnected:E,isFilterBarShown:y,isSelectingPartition:R,isStuckToBottom:I,isStuckToRight:x,isLoaded:A,isLoading:k,isModelReady:_,model:M,movedColumns:$,movedRows:H,partition:K,partitionColumn:L,quickFilters:G,reverseType:ee,rollupConfig:W,sorts:j,userColumnWidths:B,userRowHeights:Z,showSearchBar:se,searchValue:ae,selectDistinctColumns:q,selectedSearchColumns:ne,invertSearchColumns:he,Plugin:Te,pluginFilters:ye,pluginFetchColumns:rt,pendingDataMap:wt,frozenColumns:Wt,columnHeaderGroups:fn}=this.state,xt=T!=null?`Unable to open table. ${T}`:void 0,{table:Ee}=a,lt=M?.description??void 0,et=d?.pluginState??null,pt=e??this.getPluginContent(Te,M,h,u,et),{permissions:It}=h,{canCopy:Cn,canDownloadCsv:Gt}=It;return r.jsx($r,{errorMessage:xt,isDisconnected:E,isLoading:k,isLoaded:A,className:"iris-grid-panel",glContainer:t,glEventHub:n,onClearAllFilters:this.handleClearAllFilters,onResize:this.handleResize,onShow:this.handleShow,onTabFocus:this.handleShow,onTabClicked:this.handleTabClicked,widgetName:Ee,widgetType:"Table",description:lt,componentPanel:this,renderTabTooltip:()=>r.jsx(Jr,{model:M,widgetName:Ee,glContainer:t,description:lt}),children:_&&M&&r.jsx(Du,{advancedFilters:p,aggregationSettings:f,advancedSettings:C,alwaysFetchColumns:this.getAlwaysFetchColumns(l,rt),columnAllowedCursor:"linker",columnNotAllowedCursor:"linker-not-allowed",customColumns:b,customColumnFormatMap:w,columnSelectionValidator:this.isColumnSelectionValid,conditionalFormats:S,inputFilters:this.getGridInputFilters(M.columns,o),applyInputFiltersOnInit:d==null,isFilterBarShown:y,isSelectingColumn:s!=null,isSelectingPartition:R,isStuckToBottom:I,isStuckToRight:x,movedColumns:$,movedRows:H,partition:K,partitionColumn:L,quickFilters:G,reverseType:ee,rollupConfig:W,settings:m,sorts:j,userColumnWidths:B,userRowHeights:Z,model:M,showSearchBar:se,searchValue:ae,selectedSearchColumns:ne,selectDistinctColumns:q,invertSearchColumns:he,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:ye,pendingDataMap:wt,canCopy:Cn,canDownloadCsv:Gt,ref:this.irisGrid,getDownloadWorker:i,frozenColumns:Wt,theme:g,columnHeaderGroups:fn,children:pt})})}}const Xy=(c,{localDashboardId:e=un})=>({inputFilters:Wr(c,e),links:Fi(c,e),columnSelectionValidator:Kr(c,e),user:Ch(c),workspace:Yl(c),settings:gt(c)}),Zy=mt(Xy,null,null,{forwardRef:!0})(Ja),Xs=Zy;const Cc=J.module("InputFilter"),Qy=150;class Nl 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=oe.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=we((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)];Cc.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;Cc.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=We(()=>{const{onChange:e}=this.props,{column:t,value:n,isValueShown:s}=this.state;e({column:t,isValueShown:s,value:n})},Qy);render(){const{columns:e}=this.props,{column:t,isValueShown:n,selectedColumn:s,value:i}=this.state,o=i==null||i.length===0?Nl.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(or,{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(P,{kind:"secondary",onClick:this.handleSettingsCancel,disabled:t==null,children:"Cancel"}),r.jsx(P,{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:Nl.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(P,{kind:"ghost",className:"m-2 px-2",onClick:this.handleSettingsClick,icon:r.jsx(X,{icon:uo,transform:"grow-4"}),tooltip:"Input Filter Settings"})})]})]})}}const Jy=Nl,eR=250;class tR extends v.Component{static defaultProps={panelState:null};static COMPONENT="InputFilterPanel";static displayName="InputFilterPanel";constructor(e){super(e),this.handleChange=We(this.handleChange.bind(this),eR),this.handleClearAllFilters=this.handleClearAllFilters.bind(this),this.inputFilterRef=oe.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(Ke.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(Xn,{className:"iris-input-filter-panel",componentPanel:this,glContainer:e,glEventHub:t,onClearAllFilters:this.handleClearAllFilters,isClonable:!0,isRenamable:!0,children:r.jsx(Jy,{ref:this.inputFilterRef,column:n,columns:s,onChange:this.handleChange,isValueShown:i,value:o})})}}const nR=(c,e)=>{const{localDashboardId:t}=e;return{columns:ku(c,t)}},sR=mt(nR,null,null,{forwardRef:!0})(tR),to=sR;const Ct=J.module("FilterSetManagerPanel");function iR(c){return c.setPanelState!=null}class kl 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){Ct.error("Could not get panel",s);return}const i=V.getComponentNameFromPanel(s),o=V.getIdFromPanel(s);Ct.debug("Panel:",s,i);const{glContainer:l=null}=s.props;if(l==null){Ct.error("Could not get panel container",s);return}const a=V.getComponentConfigFromContainer(l);if(a==null){Ct.error("Could not get component config from container",l);return}const d=V.getPanelComponentState(a);if(d==null){Ct.debug(`Panel state is null ${o}`);return}switch(i){case V.getComponentName(Ja):{let h;o!=null&&(h=this.getIrisGridPanelFilters(o,d)),h!=null&&t.push({panelId:o,type:i,state:h});break}case V.getComponentName(to):case V.getComponentName(qs):{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 Ct.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=kl.changeFilterIndexesToColumnNames(s,l));let h;return a&&(h=kl.changeFilterIndexesToColumnNames(s,a)),{irisGridState:{...i,advancedFilters:d,quickFilters:h},gridState:{...o}}}handleGetFilterState(){return this.getFilterState()}handleChange({isValueShown:e,selectedId:t}){Ct.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;Ct.debug("Apply filters from filter set",e),n.forEach(({panelId:i,type:o,state:l})=>{if(i==null){Ct.debug("panel is null",i);return}if(!t.has(i)){Ct.debug("Ignore closed panel",i);return}Ct.debug("Apply panel filters",i,o,l);const a=t.get(i);switch(o){case V.getComponentName(Ja):this.restoreIrisGridFilters(a,l,s);break;case V.getComponentName(to):case V.getComponentName(qs):this.restoreInputFilterState(a,l);break}})}handleSetsUpdate(e){const{setDashboardFilterSets:t,localDashboardId:n}=this.props;Ct.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=V.getIdFromPanel(e);if(h==null){Ct.error("Panel Id is null.");return}if(d.get(h)==null){Ct.error(`Unable to get table for panel ${h}.`);return}Ct.debug("restoreIrisGridFilters",h,t,n),n?e.setStateOverrides(t):e.setFilters({quickFilters:a,advancedFilters:l})}restoreInputFilterState(e,t){const n={...t};delete n.isValueShown,Ct.debug("restoreInputFilterState",e,n),e&&iR(e)&&e.setPanelState(n)}render(){const{glContainer:e,glEventHub:t,filterSets:n}=this.props,{isValueShown:s,selectedId:i}=this.state;return r.jsx(Xn,{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(Ky,{onChange:this.handleChange,onApply:this.handleFilterApply,onUpdateSets:this.handleSetsUpdate,isValueShown:s,filterSets:n,selectedId:i,getFilterState:this.handleGetFilterState})})})}}const oR=(c,e)=>{const{localDashboardId:t}=e;return{filterSets:ly(c,t),dashboardOpenedPanelMap:lu(c,t),dashboardInputFilters:Wr(c,t),panelTableMap:Gr(c,t)}},lR=mt(oR,{setDashboardFilterSets:gy},null,{forwardRef:!0})(kl),Na=lR;const Sc=J.module("LogPanel");class aR 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){Sc.debug("Session opened",[e]),this.setState({session:e})}handleSessionClosed(e){Sc.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(Xn,{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(zf,{session:n,ref:s=>{this.logView=s}})]})}}const rR=(c,e)=>({session:Qs(c,e.localDashboardId)?.session}),dR=mt(rR,null,null,{forwardRef:!0})(aR),Ml=dR;class cR 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:z("text-muted","edit-hint",{viewing:e===void 0||!e}),children:r.jsxs("span",{children:["double-click to edit ",r.jsx(X,{icon:mo})]})}),t]})}}const hR=J.module("MarkdownStartPage");class uR 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(hR.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(P,{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(P,{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(X,{icon:$t})})]},o.id)),r.jsxs($l,{isOpen:s,toggle:this.handleDeleteModalClose,className:"modal-dialog-centered markdown-delete-modal theme-bg-light",children:[r.jsx(Wl,{children:"Are you sure you want to permanently delete this note?"}),r.jsx(Gl,{children:"You can't undo this action."}),r.jsxs(zc,{children:[r.jsx(P,{kind:"secondary",onClick:this.handleDeleteModalClose,children:"Cancel"}),r.jsx(P,{kind:"danger",onClick:()=>{this.handleDeleteMarkdown(i)},children:"Delete"})]})]})]})]})})}}const mR=uR,gR=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(zl,{language:n,children:oe.Children.map(e,s=>typeof s=="string"?s.trim():s)})})})};class pR 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(fr,{settings:{language:"markdown",value:t,lineNumbers:"off"},onEditorInitialized:n}):r.jsx(Uc,{components:{code:gR},children:t})})}}const Zo=J.module("MarkdownPanel");class fR 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){D(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=ce(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){Zo.debug("Markdown Editor Initialized..."),this.editor=e}handleCreateMarkdown(){Zo.debug("create markdown..."),this.setState({isStartPageShown:!1,content:"",isEditing:!0,panelState:{content:""}},()=>{this.editor!=null&&this.editor.focus!=null&&this.editor.focus()})}handleOpenMarkdown(e){Zo.debug("open markdown...",e);const{glContainer:t,glEventHub:n}=this.props,s=V.getComponentConfigFromContainer(t);n.emit(Se.REOPEN,e,s)}handleDeleteMarkdown(e){const{glEventHub:t}=this.props;t.emit(Se.DELETE,e)}handleEditorBlur(e){Zo.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(Xn,{glContainer:e,glEventHub:t,className:"markdown-panel",componentPanel:this,onResize:this.handleEditorResize,onBlur:this.handleEditorBlur,isClonable:!0,isRenamable:!0,children:i?r.jsx(mR,{closedMarkdowns:l,onCreate:this.handleCreateMarkdown,onOpen:this.handleOpenMarkdown,onDelete:this.handleDeleteMarkdown}):r.jsx(cR,{isEditing:s,onDoubleClick:this.handleContainerDoubleClick,children:r.jsx(pR,{ref:a=>{this.markdownEditor=a},isEditing:s,content:o??void 0,onEditorInitialized:this.handleEditorInitialized})})})}}const CR=(c,e)=>{const{localDashboardId:t}=e;return{closedPanels:mb(c,t)}},SR=mt(CR,null,null,{forwardRef:!0})(fR),$i=SR;class bR 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=oe.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;D(d);const{start:h}=d,{line:u}=h,m=a[0].value,g=oe.createRef(),p=this.commands.size===0,f=l===u||p&&l==null&&!o,C=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:z("markdown-notebook-code-block",{"is-selected":f}),ref:g,onClick:()=>{this.setState({nextStartLine:u})},role:"presentation",children:[r.jsx(P,{kind:"ghost",icon:al,className:"btn-play-block",onClick:S=>{S.stopPropagation(),S.preventDefault(),this.runCode(m),this.setState({nextStartLine:u})},tooltip:"Run code"}),r.jsx("code",{children:r.jsx(zl,{language:C,children:oe.Children.map(t,S=>typeof S=="string"?S.trim():S)})})]}))}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(P,{className:z("btn-play-selected-cell",{flashing:s&&!i}),kind:"ghost",icon:al,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(Uc,{components:{code:this.renderCodeBlock,a:this.renderLink},linkTarget:"_blank",remarkPlugins:[bm],transformLinkUri:n,transformImageUri:t,includeElementIndex:!0,children:e})})]})}}const wR=bR;const Me=J.module("NotebookPanel"),bc=400;class Ws extends v.Component{static COMPONENT="NotebookPanel";static POPPER_OPTIONS={placement:"bottom-end"};static DEFAULT_NAME="Untitled";static handleError(e){be.isCanceled(e)||Me.error(e)}static defaultProps={isDashboardActive:!0,isPreview:!1,session:null,sessionLanguage:null,defaultNotebookSettings:null};static languageFromFileName(e){switch(me.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 qn,this.debouncedSavePanelState=We(this.savePanelState.bind(this),bc),this.debouncedLoad=We(this.load.bind(this),bc),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&&me.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:""},Me.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(Le.RENAME_FILE,this.handleRenameFile),e.on(Le.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(Le.RENAME_FILE,this.handleRenameFile),t.off(Le.PROMOTE_FROM_PREVIEW,this.handlePreviewPromotion),e.emit(Le.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);D(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){Me.debug("Init content from file"),this.registerFileMetadata(e,n),this.load();return}if(t.value!=null){Me.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(Le.CLOSE_FILE,{id:e})}registerFileMetadata(e,t){const{glEventHub:n,metadata:s}=this.props,{id:i}=s;n.emit(Le.REGISTER_FILE,i,e,t)}renameTab(e,t){const{glEventHub:n}=this.props;n.emit(Le.RENAME,e,t)}load(){const{fileMetadata:e,settings:t}=this.state;D(e);const{id:n}=e,{fileStorage:s}=this.props;this.pending.add(s.loadFile(n)).then(i=>{Me.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,me.getBaseName(o))}const a={...t,language:Ws.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&&me.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){Me.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;Me.debug("setPreviewStatus",this.tabTitleElement,e),e?this.tabTitleElement.classList.add("is-preview"):this.tabTitleElement.classList.remove("is-preview")}handlePreviewPromotion(){this.removePreviewStatus()}getSettings=ce((e,t)=>({...e,minimap:{enabled:t}}));getOverflowActions=ce((e,t)=>[{title:"Find",icon:Vg,action:this.handleFind,group:te.groups.high,shortcut:Rt.NOTEBOOK.FIND,order:10},{title:"Show Minimap",icon:e?Kn:void 0,action:this.handleMinimapChange,group:te.groups.medium,shortcut:Rt.NOTEBOOK.MINIMAP,order:20},{title:"Word Wrap",icon:t?Kn:void 0,action:this.handleWordWrapChange,group:te.groups.medium,shortcut:Rt.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 Me.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(Le.CLOSE_FILE,{id:e,itemName:e},{force:!0}),this.focus()}handleCopy(){const{fileMetadata:e,settings:t}=this.state;D(e);const n=this.getNotebookValue(),{language:s}=t,{itemName:i}=e,o=me.getCopyFileName(i);Me.debug("handleCopy",e,i,o),this.createNotebook(o,s,n)}handleEditorInitialized(e){this.editor=e}handleEditorWillDestroy(){this.editor=void 0}handleEditorChange(e){Me.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(){Me.debug("handleBlur"),this.setState({isFocused:!1})}handleFocus(){Me.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==="/"){Me.debug("Ignoring invalid notebook link",o);return}Me.debug("Notebook link clicked, opening",o);const{glEventHub:l}=this.props,a={value:null,language:s},d={id:o,itemName:o};l.emit(Le.SELECT_NOTEBOOK,n,s,a,d)}handleLoadSuccess(){this.setState({error:void 0,isLoaded:!0,isLoading:!1})}handleLoadError(e){let t=e;be.isCanceled(t)||(be.isTimedOut(t)&&(t=new Error("File not found.")),Me.error(t),this.setState({error:t,isLoading:!1}))}handleSave(){Me.debug("handleSave"),this.save()}handleSaveSuccess(e){const{fileStorage:t}=this.props,n={id:e.filename,itemName:e.filename},s=Ws.languageFromFileName(e.filename)??"";this.setState(i=>{const{fileMetadata:o}=i,l={...i.settings,language:s};return Me.debug("handleSaveSuccess",n,o,l),o&&me.hasPath(o.itemName)&&o.itemName!==n.itemName&&(Me.debug("handleSaveSuccess deleting old file",o.itemName),t.deleteFile(o.itemName).catch(Ws.handleError)),{fileMetadata:n,settings:l,isPreview:!1}}),this.debouncedSavePanelState(),this.registerFileMetadata(n,!1)}handleSaveError(e){be.isCanceled(e)||(this.setState({savedChangeCount:0}),Me.error(e))}handleSaveAsCancel(){this.setState({showSaveAsModal:!1})}handleSaveAsSubmit(e,t=!1){t&&this.handleOverwrite(e),Me.debug("handleSaveAsSubmit",e);const{fileMetadata:n}=this.state;if(!n)return;const{itemName:s}=n,i=this.getNotebookValue()??"";if(this.setState({showSaveAsModal:!1}),me.getBaseName(s)!==me.getBaseName(e)){const{metadata:o}=this.props,{id:l}=o;this.renameTab(l,me.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){Me.error("Editor is not initialized.");return}this.runCommand(this.notebook.getValue()??void 0)}handleRunSelected(){if(!this.notebook){Me.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(){Me.debug("handleShow"),this.notebook?.updateDimensions()}handleShowRename(){this.setState({showSaveAsModal:!0})}handleTab(e){Me.debug("NotebookPanel tab event",e),this.initTab(e)}handleTabFocus(...e){Me.debug("handleTabFocus",...e);const{glContainer:t}=this.props;this.setState({isDashboardActive:!0}),this.notebook&&!t.isHidden&&this.notebook.updateDimensions()}handleTabBlur(){Me.debug("handleTabBlur"),this.setState({isDashboardActive:!1})}handleTabClick(e){Me.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};Me.debug("handleCreateNotebook",i,o,a,d),s.emit(Le.CREATE_NOTEBOOK,i,o,a,d)}runCommand(e){if(e===void 0||e===""){Me.debug("Ignoring empty command.");return}this.removePreviewStatus();const{glEventHub:t}=this.props;t.emit(Bt.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:f,settings:C,showCloseModal:S,showSaveAsModal:b}=this.state,w=d&&!t.isHidden&&!m,T=g?.itemName??Ws.DEFAULT_NAME,E=T.endsWith(".md"),y=g?.id!=null,R=this.getSettings(C,i.isMinimapEnabled),I=p!=null,x=f===R.language,A=!h||!I||!x,k=!h,_=[{action:this.handleSave,shortcut:Yn.SAVE},{action:this.handleMinimapChange,shortcut:Rt.NOTEBOOK.MINIMAP},{action:this.handleWordWrapChange,shortcut:Rt.NOTEBOOK.WORDWRAP}],M=kd.getDisabledRunTooltip(I,x,"Notebook extension","Run"),$=kd.getDisabledRunTooltip(I,x,"Notebook extension","Run Selected"),H=[{title:y?"Rename":"Save As…",order:10,group:te.groups.high,action:this.handleShowRename},{title:"Copy File",action:this.handleCopy,group:te.groups.high,order:20}],K=n?.element.find(".lm_title_before").get(0);return r.jsxs(r.Fragment,{children:[K&&ll.createPortal(r.jsx("span",{className:z("editor-unsaved-indicator",{"is-unsaved":o!==l})}),K),r.jsxs(Xn,{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:H,renderTabTooltip:()=>T,children:[!E&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"notebook-toolbar",children:[r.jsxs("span",{children:[r.jsx(P,{kind:"ghost",className:"btn-play",onClick:this.handleRunAll,disabled:A,icon:r.jsx(X,{icon:al,transform:"grow-4"}),tooltip:`Run ${Rt.NOTEBOOK.RUN.getDisplayText()}`,"aria-label":"Run"}),M!=null&&r.jsx(Je,{children:M})]}),r.jsxs("span",{children:[r.jsx(P,{kind:"ghost",className:"btn-play",onClick:this.handleRunSelected,disabled:A,icon:r.jsx(X,{icon:$g,transform:"grow-4"}),tooltip:`Run Selected ${Rt.NOTEBOOK.RUN_SELECTED.getDisplayText()}`,"aria-label":"Run Selected"}),$!=null&&r.jsx(Je,{children:$})]}),r.jsx(P,{kind:"ghost",className:"mr-auto",disabled:k,onClick:this.handleSave,icon:sh,tooltip:`Save ${Yn.SAVE.getDisplayText()}`,"aria-label":"Save"}),r.jsx(P,{kind:"ghost",className:"btn-overflow btn-link-icon",disabled:k,icon:Xc,tooltip:"More Actions...",onClick:()=>{},children:r.jsx($n,{actions:this.getDropdownOverflowActions,popperOptions:Ws.POPPER_OPTIONS})})]}),r.jsx(Mf,{isLoaded:h,isLoading:u,error:a,onChange:this.handleEditorChange,onRunCommand:this.handleRunCommand,session:p,sessionLanguage:f,onEditorInitialized:this.handleEditorInitialized,onEditorWillDestroy:this.handleEditorWillDestroy,settings:R,focusOnMount:w,ref:L=>{this.notebook=L}})]}),E&&r.jsx(wR,{content:R.value??"",onLinkClick:this.handleLinkClick,onRunCode:this.handleRunCommand,transformImageUri:this.handleTransformLinkUri,transformLinkUri:this.handleTransformLinkUri}),r.jsx(_u,{isOpen:b,type:"file",defaultValue:T,title:y?"Rename":"Save file as",onSubmit:this.handleSaveAsSubmit,onCancel:this.handleSaveAsCancel,notifyOnExtensionChange:!0,storage:e}),r.jsx(io,{isOpen:S,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(te,{actions:_})]})]})}}const vR=(c,e)=>{const t=bh(c),n=gt(c),s=hC(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}},TR=mt(vR,{saveSettings:Xl},null,{forwardRef:!0})(Ws),ds=TR;class ER extends v.Component{static defaultProps={panelState:null};static COMPONENT="PandasPanel";constructor(e){super(e),this.irisGridRef=oe.createRef(),this.buttonRef=oe.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(Xs,{ref:this.irisGridRef,onStateChange:this.handleGridStateChange,onPanelStateUpdate:this.handlePanelStateUpdate,...e,children:r.jsxs(P,{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(X,{icon:dr,transform:"shrink-1",className:"mr-1"}),"Reload"]})]})})}}const ka=ER;function yR(c){ys(c);const{id:e,layout:t,registerComponent:n,hydrate:s}=c,i=vs(),o=v.useCallback(({dragEvent:l,fetch:a,panelId:d=Ge.generate(),widget:h})=>{const{name:u,type:m}=h;if(m!==i.VariableType.FIGURE)return;const g={name:u,figure:u},p=()=>a().then(S=>pl.makeModel(i,void 0,S)),f={type:"react-component",component:Ti.COMPONENT,props:{localDashboardId:e,id:d,metadata:g,makeModel:p},title:u,id:d},{root:C}=t;V.openComponent({root:C,config:f,dragEvent:l})},[i,e,t]);return v.useEffect(function(){const a=[n(Ti.COMPONENT,Ti,s)];return()=>{a.forEach(d=>d())}},[s,n]),_e(t.eventHub,Se.OPEN,o),null}function RR(c){ys(c);const{id:e,layout:t}=c,n=vs(),s=v.useCallback(({metadata:i,panelId:o=Ge.generate(),table:l})=>{const{settings:a}=i,d=()=>pl.makeModelFromSettings(n,a,l),h=ht.titleFromSettings(a),u={type:"react-component",component:Ti.COMPONENT,props:{localDashboardId:e,id:o,metadata:i,makeModel:d},title:h,id:o},{root:m}=t;V.openComponent({root:m,config:u})},[n,e,t]);return _e(t.eventHub,cn.CREATE_CHART,s),null}const tt=J.module("ConsolePlugin");function wc(c){return c.notebook!==void 0}function xR(c){ys(c)}function IR(c){xR(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=nr(),g=v.useCallback(()=>s.getLastUsedPanelOfType(fi),[s]),p=v.useCallback((j,B)=>{d(Z=>new Map(Z.set(j,B)))},[d]),f=v.useCallback(j=>{d(B=>(B.delete(j),new Map(B)))},[d]),C=v.useCallback((j,B)=>{u(Z=>new Map(Z.set(j,B)))},[u]),S=v.useCallback(j=>{u(B=>(B.delete(j),new Map(B)))},[u]),b=v.useCallback((j,B=!0,Z=!0)=>{if(!(j&&j.trim()))tt.info("Ignoring empty code");else{const ae=g();if(!ae||!(ae instanceof fi.WrappedComponent)){tt.error("Console panel not found");return}tt.debug("Send command: ",j,B,Z),ae.addCommand(j,B,Z)}},[g]),w=v.useCallback(j=>{m(my(e,j))},[m,e]),T=v.useCallback(({language:j})=>{const B=j==="python"?"py":j;let Z=null;return B==null?(tt.debug("No extension for language",j),Z=`Untitled-${l.current}`):Z=`Untitled-${l.current}.${B}`,l.current+=1,Z},[]),E=v.useCallback((j,B=!0)=>{const{id:Z}=j;if(Z!=null&&a.has(Z))return a.get(Z);if(Z!=null&&h.has(Z))return h.get(Z);if(B)return Ge.generate()},[a,h]),y=v.useCallback((j,B)=>{V.renameComponent(n.root,{id:j},B)},[n.root]),R=v.useCallback((j,B)=>{tt.debug("Rename file panel",j,B);let Z;if(a.has(j)&&(Z=a.get(j),f(j),Z!=null&&p(B,Z)),h.has(j)&&(Z=h.get(j),S(j),Z!=null&&C(B,Z)),Z===void 0){tt.debug2(`File ${j} isn't open, no need to rename the tab`);return}y(Z,me.getBaseName(B))},[a,h,y,p,C,f,S]),I=v.useCallback(j=>{const B=E(j,!1);if(B==null){tt.error("Could not find panel id for file metadata",j);return}V.activateTab(n.root,{id:B})},[E,n.root]),x=v.useCallback((j,B,Z)=>{if(tt.debug("registerFilePanel",j,B,Z),B==null||B.id==null){tt.debug("Ignore empty file id",B);return}const{id:se}=B;if(Z){C(se,j);return}if(a.has(se)){const ae=a.get(se);if(j===ae){tt.debug(`Update tab title for file ${se}`);const{itemName:q}=B;R(se,q)}else tt.error(`File ${se} already associated with a different tab ${ae}`);return}p(se,j),h.has(se)&&S(se)},[a,h,R,p,C,S]),A=v.useCallback((j,B)=>{if(tt.debug("unregisterFileTab",j,B),j==null||j.id==null){tt.debug("Ignore empty file id",j);return}const{id:Z}=j;if(B){S(Z);return}f(Z)},[f,S]),k=v.useCallback((j,B)=>{tt.debug("closeFilePanel",j);const{id:Z}=j;let se=null,ae=!1;if(a.has(Z))se=a.get(Z);else if(h.has(Z))se=h.get(Z),ae=!0;else{tt.debug(`File ${Z} isn't open, ignore close event`);return}A(j,ae),V.closeComponent(n.root,{id:se},B)},[n.root,a,h,A]),_=v.useCallback(j=>{const{itemName:B}=j;return me.getBaseName(B)},[]),M=v.useCallback(j=>{const{id:B}=j;return tt.debug("fileIsOpen",j,B,a),B!=null&&a.has(B)},[a]),$=v.useCallback(j=>{const{id:B}=j;return tt.debug("fileIsOpenAsPreview",j,B,h),B!=null&&h.has(B)},[h]),H=v.useCallback(j=>{if(j==null)return;const B=s.getOpenedPanelById(j);B&&wc(B)&&B.focus()},[s]),K=v.useCallback(({id:j,settings:B,fileMetadata:Z,session:se,sessionLanguage:ae,isPreview:q=!1})=>{const ne={settings:B,fileMetadata:Z},he=_(Z);return{type:"react-component",component:ds.COMPONENT,isFocusOnShow:!1,props:{localDashboardId:e,metadata:{id:j},session:se,sessionLanguage:ae,panelState:ne,isPreview:q,notebooksUrl:o},title:he,id:j}},[_,e,o]),L=v.useCallback((j,B,Z,se={id:null,itemName:T(Z)})=>{const ae=E(se);if(M(se)&&ae!=null){tt.debug("File is already open, focus panel"),I(se),H(ae);return}const q=V.getStackForComponentTypes(n.root,[ds.COMPONENT]),ne=K({id:ae,settings:Z,fileMetadata:se,session:j,sessionLanguage:B});tt.debug("createNotebook",ne,a),V.openComponentInStack(q,ne)},[M,H,T,E,n.root,K,a,I]),G=v.useCallback((j,B,Z,se,ae=!1)=>{tt.debug("selectNotebook",se,ae);const q=M(se),ne=$(se),[he]=[...h.values()],Te=!ae,ye=Te&&he?he:E(se);if(ye==null||ye==="")throw new Error("Unable to retrieve or create panelId for metadata",se);if(q||ne)I(se);else{const rt=V.getStackForComponentTypes(n.root,[ds.COMPONENT]),wt=K({id:ye,settings:Z,fileMetadata:se,session:j,sessionLanguage:B,isPreview:Te});V.openComponentInStack(rt,wt)}if(ne&&ae){const rt=se.id,wt=V.getStackForConfig(n.root,{component:ds.COMPONENT,id:ye}),Wt=V.getContentItemInStack(wt,{component:ds.COMPONENT,id:ye});Wt&&jt(Wt)&&(Wt.container.emit(Le.PROMOTE_FROM_PREVIEW),S(rt),p(rt,ye))}ae&&H(ye)},[I,M,$,H,E,n.root,K,h,S,p]),ee=v.useCallback((j,B,Z={},se=!0)=>{const ae=s.getLastUsedPanelOfType(ds);ae&&wc(ae)?Z!=null&&Z.value!=null&&ae.notebook!=null&&ae.notebook.append(Z.value):se&&L(j,B,Z)},[L,s]),W=v.useCallback((j,B)=>Ya.hydrate({...j,notebooksUrl:o},B),[o]);return v.useEffect(function(){const B=[i(fi.COMPONENT,fi,t),i(xl.COMPONENT,xl),i(Dl.COMPONENT,Dl),i(Ml.COMPONENT,Ml),i(ds.COMPONENT,ds,W)];return()=>{B.forEach(Z=>Z())}},[i,t,W]),_e(n.eventHub,Bt.SEND_COMMAND,b),_e(n.eventHub,Bt.SETTINGS_CHANGED,w),_e(n.eventHub,Le.CLOSE_FILE,k),_e(n.eventHub,Le.CREATE_NOTEBOOK,L),_e(n.eventHub,Le.SELECT_NOTEBOOK,G),_e(n.eventHub,Le.RENAME,y),_e(n.eventHub,Le.RENAME_FILE,R),_e(n.eventHub,Le.SEND_TO_NOTEBOOK,ee),_e(n.eventHub,Le.REGISTER_FILE,x),_e(n.eventHub,Le.UNREGISTER_FILE,A),null}const Wi=J.module("FilterPlugin");function vc(c,e){return c.concat(e)}function DR(c){ys(c);const{id:e,layout:t,registerComponent:n}=c,s=nr(),[i]=v.useState(()=>new Map),[o]=v.useState(()=>new Map),[l]=v.useState(()=>new Map),a=v.useCallback(()=>{const C=Array.from(i.values()).reduce(vc,[]).sort((w,T)=>{const E=Jt.toLower(w.name),y=Jt.toLower(T.name);if(E!==y)return E>y?1:-1;const R=Jt.toLower(w.type),I=Jt.toLower(T.type);return R!==I?R>I?1:-1:0}).reduce((w,T)=>((w.length===0||Jt.toLower(w[w.length-1].name)!==Jt.toLower(T.name)||Jt.toLower(w[w.length-1].type)!==Jt.toLower(T.type))&&w.push(T),w),[]),S=Array.from(o.values()).reduce(vc,[]).sort((w,T)=>w.timestamp-T.timestamp),b=new Map(l);Wi.debug("sendUpdate",{columns:C,filters:S,tableMap:b}),s(kn(e,{columns:C,filters:S,tableMap:b}))},[s,e,i,o,l]),d=v.useCallback((C,S)=>{Wi.debug2("handleColumnsChanged",C,S),i.set(C,[].concat(S)),a()},[i,a]),h=v.useCallback((C,S)=>{Wi.debug2("handleFiltersChanged",C,S),o.set(C,[].concat(S)),a()},[o,a]),u=v.useCallback((C,S)=>{Wi.debug2("handleTableChanged",C,S),l.set(V.getIdFromPanel(C),S),a()},[l,a]),m=v.useCallback(C=>{Wi.debug2("handlePanelUnmount",C),i.delete(C),o.delete(C),l.delete(V.getIdFromPanel(C)),a()},[i,o,l,a]),g=v.useCallback(({title:C="DropdownFilter",metadata:S={},panelState:b=null,id:w=Ge.generate(),focusElement:T=V.DEFAULT_FOCUS_SELECTOR,createNewStack:E=!1,dragEvent:y=null})=>{const R={type:"react-component",component:qs.COMPONENT,props:{id:w,metadata:S,panelState:b,localDashboardId:e},title:C,id:w},{root:I}=t;V.openComponent({root:I,config:R,focusElement:T,createNewStack:E,dragEvent:y})},[t,e]),p=v.useCallback(({title:C="InputFilter",metadata:S={},panelState:b=null,id:w=Ge.generate(),focusElement:T=V.DEFAULT_FOCUS_SELECTOR,createNewStack:E=!1,dragEvent:y=null})=>{const R={type:"react-component",component:to.COMPONENT,props:{id:w,metadata:S,panelState:b,localDashboardId:e},title:C,id:w},{root:I}=t;V.openComponent({root:I,config:R,focusElement:T,createNewStack:E,dragEvent:y})},[t,e]),f=v.useCallback(({title:C="FilterSets",metadata:S={},panelState:b=null,id:w=Ge.generate(),focusElement:T=V.DEFAULT_FOCUS_SELECTOR,createNewStack:E=!1,dragEvent:y=null})=>{const R={type:"react-component",component:Na.COMPONENT,props:{id:w,metadata:S,panelState:b,localDashboardId:e},title:C,id:w},{root:I}=t;V.openComponent({root:I,config:R,focusElement:T,createNewStack:E,dragEvent:y})},[t,e]);return v.useEffect(function(){const S=[n(qs.COMPONENT,qs),n(to.COMPONENT,to),n(Na.COMPONENT,Na)];return()=>{S.forEach(b=>b())}},[n]),_e(t.eventHub,Ke.COLUMNS_CHANGED,d),_e(t.eventHub,Ke.FILTERS_CHANGED,h),_e(t.eventHub,Ke.TABLE_CHANGED,u),_e(t.eventHub,Ke.OPEN_DROPDOWN,g),_e(t.eventHub,Ke.OPEN_INPUT,p),_e(t.eventHub,Ke.OPEN_FILTER_SET_MANAGER,f),_e(t.eventHub,Se.UNMOUNT,m),null}function FR(c){ys(c);const{getDownloadWorker:e,loadPlugin:t,id:n,layout:s,registerComponent:i,hydrate:o,theme:l}=c,a=vs(),d=v.useMemo(()=>[a.VariableType.TABLE,a.VariableType.TREETABLE,a.VariableType.HIERARCHICALTABLE],[a]),h=v.useCallback(({dragEvent:u,fetch:m,panelId:g=Ge.generate(),widget:p})=>{const{name:f,type:C}=p;if(!d.includes(C))return;const S={name:f,table:f,type:p.type},b=()=>m().then(E=>Vr.makeModel(a,E)),w={type:"react-component",component:Xs.COMPONENT,props:{getDownloadWorker:e,loadPlugin:t,localDashboardId:n,id:g,metadata:S,makeModel:b,theme:l},title:f,id:g},{root:T}=s;V.openComponent({root:T,config:w,dragEvent:u})},[a,e,n,s,t,d,l]);return v.useEffect(function(){const m=[i(Xs.COMPONENT,Xs,o)];return()=>{m.forEach(g=>g())}},[o,i]),_e(s.eventHub,Se.OPEN,h),null}function Pu(c){return typeof c.getCoordinateForColumn=="function"}function Tc(c){const e=c;return Pu(c)&&typeof e.setFilterMap=="function"&&typeof e.unsetFilterValue=="function"}function Ec(c){return c.description===void 0||!c.description?.startsWith("Preview of type: ")}const Gi=J.module("LinkerUtils");class ed{static ALLOWED_LINKS=new Map([[V.getComponentName(Xs),[V.getComponentName(Xs),V.getComponentName(Ti),V.getComponentName(qs)]]]);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 Gi.debug2("Incompatible panel ids",e,t,n),"invalid";if(e.panelComponent==null||t.panelComponent==null)return Gi.error("PanelComponent should not be null",e,t),"invalid";const s=ed.ALLOWED_LINKS.get(e.panelComponent)?.includes(t.panelComponent);if(s===void 0||!s)return Gi.debug2("Incompatible panel components",e,t),"invalid";const{columnType:i}=e,{columnType:o}=t;if(!(o===null||F.isCompatibleType(i,o)))return Gi.debug2("Incompatible type",i,o),"invalid";switch(t.panelComponent){case V.getComponentName(Ti):return"chartLink";case V.getComponentName(Xs):return"tableLink";case V.getComponentName(qs):return"filterSource"}return Gi.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:Ge.generate(),start:{...i.start,panelId:n}}):i.end?.panelId===t&&s.push({...i,id:Ge.generate(),end:{...i.end,panelId:n}})}),s}}const di=ed;const NR=J.module("LinkerLink"),yc=.015,Rc=1.5,ju=12,Hu=12,xc=2,Qo=Math.sqrt((Hu*.5)**2+ju**2),Ic=Math.asin(Hu*.5/ju),Dc=15,cs=Math.PI*.5;class no 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 gh(t);if(F.isTextType(e))return mh(t);if(F.isDateType(e))return ph(t);if(F.isBooleanType(e)){if(t===pe.eq)return"is equal to";if(t===pe.notEq)return"is not equal to"}throw new Error(`Unrecognized column type: ${e}`)}catch(n){return NR.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=ce((e,t)=>{const{onOperatorChanged:n}=this.props;let s=F.getFilterTypes(t);return F.isBooleanType(t)&&(s=[pe.eq,pe.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:no.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),f=Math.cos(g)+2,C=window.innerWidth,S=window.innerHeight,b=0,w=0,T=Math.max(b,Math.min(s+(o-s)/2+p*(m*yc)**Rc,C)),E=Math.max(w,Math.min(i+(l-i)/2+f*(m*yc)**Rc,S)),y=`M ${s} ${i} Q ${T} ${E} ${o} ${l}`,R=`M ${b} ${w} L ${b} ${S} L ${C} ${S} L ${C} ${w} z
|
|
34
|
+
${no.makeCirclePath(s,i,Dc)}
|
|
35
|
+
${no.makeCirclePath(o,l,Dc)}`,I=`link-select-clip-${a}`,x=Math.atan2(l-E,o-T),A=x-Ic+Math.PI,k=x+Ic+Math.PI,_=o+Math.cos(x)*xc,M=l+Math.sin(x)*xc,$=_+Math.cos(A)*Qo,H=M+Math.sin(A)*Qo,K=_+Math.cos(k)*Qo,L=M+Math.sin(k)*Qo,G=`${_},${M} ${$},${H} ${K},${L}`,ee=.25*s+.5*T+.25*o,W=.25*i+.5*E+.25*l,j=T-s+(o-T),Z=(E-i+(l-E))/j;let ae=20/Math.sqrt(1+Z**2),q=ae*Z,ne=ae*-1,he=q*-1;Number.isFinite(Z)?Z>0?(ae*=-1,q*=-1,ne*=-1,he*=-1,ne-=50-10*(Math.abs(g)%cs),he+=10*(Math.abs(g)%cs),ae-=50-10*(Math.abs(g)%cs),q+=10*(Math.abs(g)%cs)):Z<0?(ne+=10*(Math.abs(g)%cs),he+=10*(Math.abs(g)%cs),ae+=10*(Math.abs(g)%cs),q+=10*(Math.abs(g)%cs)):(ne=15,he=10,ae=-25,q=10):(ne=10,he=5,ae=10,q=-35);let Te="";t!==void 0&&(t==="startsWith"?Te="a*":t==="endsWith"?Te="*z":Te=F.getFilterOperatorString(t));const ye=h!=="chartLink"&&h!=="filterSource";return r.jsxs(r.Fragment,{children:[r.jsxs("svg",{className:z(e,{hovering:u}),children:[r.jsx("clipPath",{id:I,children:r.jsx("path",{d:R,clipRule:"evenodd"})}),r.jsx("path",{className:"link-select",d:y,onClick:this.handleClick,onMouseEnter:this.handleMouseEnter,onMouseLeave:this.handleMouseLeave,clipPath:`url(#${I})`,"data-testid":"link-select"}),r.jsx("path",{className:"link-background",d:y}),r.jsx("path",{className:"link-foreground",d:y}),r.jsx("circle",{className:"link-dot",cx:s,cy:i,r:"5"}),r.jsx("polygon",{className:"link-triangle",points:G})]}),d!=null&&n&&r.jsxs(r.Fragment,{children:[ye&&r.jsx(P,{kind:"primary",className:"btn-fab btn-operator",style:{top:W+(Z>=0?q:he),left:ee+(Z>=0?ae:ne)},onClick:()=>{},icon:r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx("b",{children:Te}),r.jsx(X,{icon:Vn,transform:"right-8 down-9 shrink-5"})]}),tooltip:"Change comparison operator",children:r.jsx($n,{actions:this.getDropdownActions,popperOptions:{placement:"bottom-start"}})}),r.jsx(P,{kind:"primary",className:"btn-fab btn-delete",style:{top:W+(Z<0?q:he),left:ee+(Z<0?ae:ne)},onClick:this.handleDelete,icon:$t,tooltip:"Delete"})]})]})}}const kR=no;const Ma=J.module("LinkerOverlayContent");class MR 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=oe.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){Ma.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(!Pu(i))throw new Error(`Panel does not have getCoordinateForColumn method: ${n}`);try{const l=i.getCoordinateForColumn(s);if(l!=null)return l}catch{Ma.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 V.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:f,type:C,isReversed:S,start:b,end:w,operator:T}=p,E=b.columnType;let[y,R]=this.getPointFromLinkPoint(b),I=d?.x??y,x=d?.y??R;if(w!=null&&([I,x]=this.getPointFromLinkPoint(w)),S!=null&&S){const[k,_]=[y,R];[y,R]=[I,x],[I,x]=[k,_]}const A=z("linker-link",{disabled:e},{"link-filter-source":C==="filterSource"},{"link-invalid":C==="invalid"},{interactive:p.end==null},{"link-is-selected":n.has(f)},{"danger-delete":m==="delete"});return{x1:y,y1:R,x2:I,y2:x,id:f,className:A,operator:T,startColumnType:E,type:C}}catch(f){return Ma.warn("Unable to get point for link",p,f),null}}).filter(p=>p!=null);return r.jsxs("div",{className:z("linker-overlay",{"danger-delete":m==="delete"}),children:[g.map(({x1:p,y1:f,x2:C,y2:S,id:b,className:w,operator:T,startColumnType:E,type:y})=>r.jsx(kR,{className:w,id:b,x1:p,y1:f,x2:C,y2:S,onClick:i,onDelete:o,isSelected:n.has(b),operator:T,startColumnType:E,type:y,onOperatorChanged:this.handleOperatorChanged},b)),r.jsxs("div",{className:z("linker-toast-dialog",{dragging:u}),ref:this.dialogRef,style:{bottom:h?.y,right:h?.x},"data-testid":"linker-toast-dialog",children:[r.jsx(P,{draggable:!0,kind:"inline",className:"btn-drag-handle",icon:Vl,onClick:()=>{},onMouseDown:this.handleMouseDown,children:!u&&r.jsx(Je,{children:"Drag to reposition"})}),r.jsx("div",{className:"toast-body",children:s}),r.jsxs("div",{className:"toast-footer",children:[r.jsx(P,{kind:"secondary",onClick:l,children:"Clear All"}),r.jsx(P,{kind:"primary",onClick:a,children:"Done"})]})]}),r.jsx(te,{actions:[{action:this.handleEscapePressed,shortcut:Yn.LINKER_CLOSE,isGlobal:!0}]})]})}}const OR=MR,dt=J.module("Linker"),AR=(c,e)=>({activeTool:ql(c),dh:Kl(c),isolatedLinkerPanelId:zr(c,e.localDashboardId),links:Fi(c,e.localDashboardId),timeZone:go(c)}),LR=mt(AR,{setActiveTool:Zl,setDashboardLinks:Yr,addDashboardLinks:cy,deleteDashboardLinks:hy,setDashboardIsolatedLinkerPanelId:Mu,setDashboardColumnSelectionValidator:uy});class _R 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===Ot.DEFAULT&&this.reset())}componentDidCatch(e,t){dt.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(Xa.COLUMN_SELECTED,this.handleChartColumnSelect),t.on(Se.CLONED,this.handlePanelCloned),t.on(Ke.COLUMN_SELECTED,this.handleFilterColumnSelect),t.on(Ke.COLUMNS_CHANGED,this.handleColumnsChanged),t.on(Se.CLOSE,this.handlePanelClosed),t.on(Se.CLOSED,this.handlePanelClosed),t.on(Se.DRAGGING,this.handlePanelDragging),t.on(Se.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(Xa.COLUMN_SELECTED,this.handleChartColumnSelect),t.off(Se.CLONED,this.handlePanelCloned),t.off(Ke.COLUMN_SELECTED,this.handleFilterColumnSelect),t.off(Ke.COLUMNS_CHANGED,this.handleColumnsChanged),t.off(Se.CLOSE,this.handlePanelClosed),t.off(Se.CLOSED,this.handlePanelClosed),t.off(Se.DRAGGING,this.handlePanelDragging),t.off(Se.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(Ot.DEFAULT)}this.setState({linkInProgress:void 0})}handleDone(){const{setActiveTool:e}=this.props;e(Ot.DEFAULT)}handleChartColumnSelect(e,t){this.columnSelected(e,t,!0)}handleFilterColumnSelect(e,t){dt.debug("handleFilterColumnSelect",this.isOverlayShown());const{links:n,localDashboardId:s,setActiveTool:i,setDashboardIsolatedLinkerPanelId:o}=this.props,l=V.getIdFromPanel(e),a=n.filter(d=>d.start?.panelId===l||d.end?.panelId===l);if(!this.isOverlayShown()&&l!=null){i(Ot.LINKER),o(s,l),a.length===0&&this.columnSelected(e,t,!0,l);return}this.columnSelected(e,t,!0)}handleColumnsChanged(e,t){dt.debug("handleColumnsChanged",e,t);const{links:n}=this.props,s=V.getIdFromPanel(e);if(s==null){dt.error("Invalid panelId",e);return}const i=n.filter(({start:o,end:l})=>o.panelId===s&&di.findColumn(t,o)==null||l!=null&&l.panelId===s&&di.findColumn(t,l)==null);this.deleteLinks(i)}handleGridColumnSelect(e,t){if(!Ec(t)){dt.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=V.getIdFromPanel(e);if(l==null)return;const a=V.getComponentNameFromPanel(e),{name:d,type:h}=t;if(o==null||o.start==null){const u={id:Ge.generate(),start:{panelId:l,panelComponent:a,columnName:d,columnType:h},type:"invalid",isReversed:n};dt.debug("starting link",u),this.setState({linkInProgress:u})}else{const{links:u}=this.props,{start:m,id:g,isReversed:p}=o,f={panelId:l,panelComponent:a,columnName:d,columnType:h},C=di.getLinkType(p!==void 0&&p?f:m,p!==void 0&&p?m:f,s??i);switch(C){case"invalid":dt.debug("Ignore invalid link connection",o,f);return;case"filterSource":{const b=p!==void 0&&p?m.panelId:f.panelId,w=u.filter(({end:T})=>T?.panelId===b);this.deleteLinks(w);break}case"chartLink":{const b=p===!0?m:f,w=p===!0?f:m;dt.debug("creating chartlink",{existingLinkEnd:b,start:m,end:f});const T=u.filter(({end:E,start:y})=>y?.panelId===w.panelId&&E?.panelId===b.panelId&&E?.columnName===b.columnName&&E?.columnType===b.columnType);this.deleteLinks(T);break}}const S={start:p!==void 0&&p?f:m,end:p!==void 0&&p?m:f,id:g,type:C,operator:pe.eq};dt.info("creating link",S),this.setState({linkInProgress:void 0,selectedIds:new Set([g])},()=>{this.addLinks([S])})}}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?Tc(l)?l.unsetFilterValue(i,o):dt.debug("endPanel.unsetFilterValue not implemented",l):dt.debug("endPanel no longer exists, ignoring unsetFilterValue",s)}}setPanelFilterMap(e,t){dt.debug("Set filter data for panel:",e,t);const{panelManager:n}=this.props,s=n.getOpenedPanelById(e);s?Tc(s)?s.setFilterMap(t):dt.debug("panel.setFilterMap not implemented",e,s):dt.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]):dt.error("Unable to find link to delete",e)}handleUpdateValues(e,t){const n=V.getIdFromPanel(e),{dh:s,links:i,timeZone:o}=this.props,l=new Map;for(let a=0;a<i.length;a+=1){const{start:d,end:h,operator:u}=i[a];if(d.panelId===n&&h!=null){const{panelId:m,columnName:g,columnType:p}=h,f=l.has(m)?l.get(m):new Map,C=f.has(g)===!0?f.get(g).filterList:[],{visibleIndex:S,isExpandable:b,isGrouped:w}=t[d.columnName];let{value:T}=t[d.columnName],E=`${T}`;T===null&&b&&w&&(T=void 0),p!=null&&F.isDateType(p)&&(E=new it(s,{timeZone:o,showTimeZone:!1,showTSeparator:!0,defaultDateTimeFormatString:Zs.FULL_DATE_FORMAT}).format(T));const y={operator:u,text:E,value:T,startColumnIndex:S};C.push(y),f.set(g,{columnType:p,filterList:C}),l.set(m,f)}}l.forEach((a,d)=>{this.setPanelFilterMap(d,a)})}handlePanelCloned(e,t){const{links:n}=this.props,s=V.getIdFromPanel(e),i=t.id;if(s!=null){const o=di.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){dt.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=ce((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===Ot.LINKER}updateSelectionValidators(){const{activeTool:e,setDashboardColumnSelectionValidator:t,localDashboardId:n}=this.props;switch(e){case Ot.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(!Ec(t))return dt.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=V.getIdFromPanel(e);if(l==null)return!1;const a={panelId:l,panelComponent:V.getComponentNameFromPanel(e),columnName:t.name,columnType:t.type},d=i!==void 0&&i?di.getLinkType(a,o,s):di.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(Vt,{in:l,timeout:Ye.transitionMs,classNames:"fade",mountOnEnter:!0,unmountOnExit:!0,onExited:this.handleExited,children:r.jsx(OR,{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 PR=LR(_R),jR=PR;function HR(c){ys(c);const{id:e,layout:t,panelManager:n}=c;return r.jsx(jR,{layout:t,localDashboardId:e,panelManager:n})}class Ol{static DEFAULT_TITLE="Note";static DEFAULT_CONTENT=`# Markdown Note
|
|
36
|
+
|
|
37
|
+
This note can be edited using **markdown** for styling.`;static getNewMarkdownTitle(e){let t=`${Ol.DEFAULT_TITLE}`,n=0;for(;e.indexOf(t)>=0;)n+=1,t=`${Ol.DEFAULT_TITLE}-${n}`;return t}}const Oa=Ol;function UR(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:Ir(l)},[]),o=v.useCallback(({title:l="",metadata:a={},id:d=Ge.generate(),focusElement:h=V.DEFAULT_FOCUS_SELECTOR,createNewStack:u=!1,dragEvent:m=null}={})=>{const g=n.getOpenedPanelConfigsOfType($i.COMPONENT),p=n.getClosedPanelConfigsOfType($i.COMPONENT),f=g.map(T=>T.title??""),C=l!=null&&l!==""?l:Oa.getNewMarkdownTitle(f),S=p.length>0?null:Oa.DEFAULT_CONTENT,b={type:"react-component",component:$i.COMPONENT,props:{id:d,metadata:a,panelState:{content:S},localDashboardId:e},title:C,id:d},{root:w}=t;V.openComponent({root:w,config:b,focusElement:h,createNewStack:u,dragEvent:m})},[e,t,n]);return v.useEffect(function(){const a=[s($i.COMPONENT,$i,Dr,i)];return()=>{a.forEach(d=>d())}},[i,s]),_e(t.eventHub,Nu.OPEN,o),null}function BR(c){ys(c);const{hydrate:e,id:t,layout:n,registerComponent:s}=c,i=vs(),o=v.useCallback(({dragEvent:l,fetch:a,panelId:d=Ge.generate(),widget:h})=>{const{name:u,type:m}=h;if(m!==i.VariableType.PANDAS)return;const g={name:u,table:u},p=()=>a().then(S=>Vr.makeModel(i,S)),f={type:"react-component",component:ka.COMPONENT,props:{localDashboardId:t,id:d,metadata:g,makeModel:p},title:u,id:d},{root:C}=n;V.openComponent({root:C,config:f,dragEvent:l})},[i,t,n]);return v.useEffect(function(){const a=[s(ka.COMPONENT,ka,e)];return()=>{a.forEach(d=>d())}},[e,s]),_e(n.eventHub,Se.OPEN,o),null}class VR{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 fs=VR;class Fc{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(Un.and)}),{filterItems:t,filterOperators:n}}static combineFilterConfigs(e,t,n=Un.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 $R(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=J.module("PouchStorageTable"),WR="Deephaven.";Bc.plugin(wm);function GR(c,e){switch(c){case pe.in:case pe.contains:return{$regex:new RegExp(`${e}`)};case pe.inIgnoreCase:return{$regex:new RegExp(`${e}`,"i")};case pe.eq:return{$eq:e};case pe.notEq:return{$neq:e};case pe.greaterThan:return{$gt:e};case pe.greaterThanOrEqualTo:return{$gte:e};case pe.lessThan:return{$lt:e};case pe.lessThanOrEqualTo:return{$lte:e};case pe.startsWith:return{$regex:new RegExp(`^(?${e}).*`)};default:throw new Error(`Unsupported type: ${c}`)}}function zR(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]:GR(l,a)};if(s===0)n=d;else if(n!==null&&s-1<t.length){const h=t[s-1];if(h===Un.and)n={$and:[n,d]};else if(h===Un.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 La(c=[]){return{$and:[...c.map(e=>zR(e)),{name:{$gt:null}},{id:{$gt:null}}]}}function KR(c,e=!1){return[{id:e?"desc":"asc"},...c?.map(t=>({[t.column]:t.direction}))??[]]}class YR{db;changes;listeners=[];itemListeners=new Map;currentSize=0;currentViewport;currentReverse=!1;currentFilter=null;currentSort=null;infoUpdatePromise;viewportUpdatePromise;currentViewportData;constructor(e,t){this.db=new Bc(`${WR}${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=be.makeCancelable(this.fetchInfo(La(this.currentFilter??[])));const e=await this.infoUpdatePromise;this.currentSize=e.docs.length,this.sendUpdate()}catch(e){if(!be.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=La(this.currentFilter??[]),t=KR(this.currentSort,this.currentReverse);this.viewportUpdatePromise?.cancel(),this.viewportUpdatePromise=be.makeCancelable(this.fetchViewportData(this.currentViewport,e,t));const n=await this.viewportUpdatePromise;return this.currentViewportData=n,this.sendUpdate(),n}catch(e){if(!be.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:La(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 qR=YR,XR=2500,ZR=2e3,Xt=J.module("PouchCommandHistoryTable");class QR extends qR{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),Xt.debug("Adding table to registry",this.cacheKey),this.cache.tableRegistry.get(this.cacheKey)?.add(this)}searchText;get cacheKey(){return this.db.name}setSearch(e){Xt.debug("Setting search filters",e),this.searchText=e.trim().toLowerCase(),this.setFilters(e?[Fc.makeFilterConfig([Fc.makeFilterItem("name",pe.contains,e)])]:[])}dbUpdate(e){Xt.debug("Clearing cache and refreshing data",e),this.cache.response.delete(this.cacheKey),super.dbUpdate(e)}async fetchData(e){return be.withTimeout(0,async()=>{this.cache.response.has(this.cacheKey)?Xt.debug("Fetching from cache",this.searchText,this.viewport):(Xt.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);Xt.debug(`Fetched ${s.length} command history items`);const{toKeep:i,toPrune:o}=$R(s,XR,ZR);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 Xt.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){Xt.debug("Pruning already in progress. Skipping.");return}try{Xt.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(),Xt.debug("Finished pruning command history items")}catch(t){Xt.error("An error occurred while pruning db",t)}}close(){Xt.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 Nc=QR,kc=J.module("PouchCommandHistoryCache");class JR{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&&(kc.debug(`Pausing event listeners on '${e}' table`,n),n.changes.cancel(),t.push(n))}),()=>{t.forEach(n=>{(this.tableRegistry.get(e)?.has(n)??!1)&&(kc.debug(`Resuming event listeners on '${e}' table`,n),n.listenForChanges())})}}}const ex=JR,Mc=J.module("PouchCommandHistoryStorage");class tx{cache=new ex;updateTableMap=new Map;getUpdateTable(e){return this.updateTableMap.has(e)||this.updateTableMap.set(e,new Nc(e,this.cache)),this.updateTableMap.get(e)}async getTable(e){return new Nc(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 Mc.debug("Updating item",i),await n.put(i),Mc.debug("Update saved"),t}listenItem(e,t,n){return this.getUpdateTable(e).onItemUpdate(t,n)}}const Uu="SET_LAYOUT_STORAGE",nx=c=>({type:Uu,payload:c}),{dh:sx}=globalThis,_t=sx,Bu=""+new URL("community-wordmark-app-d2c5c1eb.svg",import.meta.url).href;const ix=J.module("SettingsUtils");function ox(c){return c.formatString!=null}function er(c){const e=c?.querySelector("input, select, textarea");e&&e.focus()}function Vu(c,e){return c.defaultFormatString===e.defaultFormatString}function lx(c,e){return Vu(c,e)}function ax(c,e){return Vu(c,e)}function $u(c){return c!==""&&Ii.isValidColumnName(c)}function Cs(c,e,t){if(!e||t.formatString==null||!ox(t))return!1;switch(e){case"datetime":return it.isValid(c,t);case"decimal":return $e.isValid(c,t);case"int":return st.isValid(c,t);default:return ix.warn("Trying to validate format of unknown type"),!0}}function Wu(c){const{id:e,isNewRule:t,...n}=c;return n}function Gu(c,e){return $u(e.columnName)&&Cs(c,e.columnType,e.format)}function zu(c){const{timestamp:e,timeZone:t,showTimeZone:n,showTSeparator:s,isGlobalOptions:i,legacyGlobalFormat:o}=c,l=vs(),a=v.useMemo(()=>new gn(l,[],{timeZone:t,showTimeZone:n,showTSeparator:s}),[l,n,s,t]),d=i?it.getGlobalFormats(n,s):it.getFormats(n,s);return o!=null&&!d.includes(o)&&d.unshift(o),r.jsx(r.Fragment,{children:d.map(h=>{const u=it.makeFormat("",h,it.TYPE_GLOBAL);return r.jsx("option",{value:h,"data-testid":"time-format",children:a.getFormattedString(e,F.dataType.DATETIME,"",u)},h)})})}function rx(){return r.jsx(r.Fragment,{children:_l.TIME_ZONES.map(c=>{const{label:e,value:t}=c;return r.jsx("option",{value:t,children:e},t)})})}const Ps=J.module("FormattingSectionContent");class td extends v.PureComponent{static defaultProps={scrollTo:()=>{},defaults:{defaultDateTimeFormat:it.DEFAULT_DATETIME_FORMAT_STRING,defaultDecimalFormatOptions:{defaultFormatString:$e.DEFAULT_FORMAT_STRING},defaultIntegerFormatOptions:{defaultFormatString:st.DEFAULT_FORMAT_STRING},showTimeZone:!1,showTSeparator:!0,timeZone:it.DEFAULT_TIME_ZONE_ID}};static inputDebounceTime=250;constructor(e){super(e),this.debouncedCommitChanges=We(this.commitChanges.bind(this),td.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=oe.createRef(),this.state={formatSettings:h,showTimeZone:o,showTSeparator:l,timeZone:a,defaultDateTimeFormat:n,defaultDecimalFormatOptions:s,defaultIntegerFormatOptions:i,truncateNumbersWithPound:d,timestampAtMenuOpen:new Date}}componentDidMount(){er(this.containerRef.current)}componentWillUnmount(){this.debouncedCommitChanges.flush()}debouncedCommitChanges;containerRef;getCachedDateTimeFormatOptions=we((e,t,n,s=!1,i)=>{const{timestampAtMenuOpen:o}=this.state;return r.jsx(zu,{timestamp:o,timeZone:e,showTimeZone:t,showTSeparator:n,isGlobalOptions:s,legacyGlobalFormat:i})});handleDefaultDateTimeFormatChange(e){Ps.debug("handleDefaultDateTimeFormatChange",e.target.value),this.setState({defaultDateTimeFormat:e.target.value},()=>{this.debouncedCommitChanges()})}handleDefaultDecimalFormatChange(e){Ps.debug("handleDefaultDecimalFormatChange",e.target.value),this.setState({defaultDecimalFormatOptions:{defaultFormatString:e.target.value}},()=>{this.debouncedCommitChanges()})}handleDefaultIntegerFormatChange(e){Ps.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;Ps.debug("handleResetDateTimeFormat"),this.setState({defaultDateTimeFormat:t,showTimeZone:n,showTSeparator:s},()=>{this.debouncedCommitChanges()})}handleResetTimeZone(){const{defaults:e}=this.props,{timeZone:t}=e;Ps.debug("handleResetTimeZone"),this.setState({timeZone:t},()=>{this.debouncedCommitChanges()})}handleResetDecimalFormat(){const{defaults:e}=this.props,{defaultDecimalFormatOptions:t}=e;Ps.debug("handleResetDecimalFormat"),this.setState({defaultDecimalFormatOptions:t},()=>{this.debouncedCommitChanges()})}handleResetIntegerFormat(){const{defaults:e}=this.props,{defaultIntegerFormatOptions:t}=e;Ps.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,{dh:d}=this.props,h=e.filter(p=>Gu(d,p)).map(Wu)??[],{settings:u,saveSettings:m}=this.props,g={...u,formatter:h,defaultDateTimeFormat:t,showTimeZone:n,showTSeparator:s,timeZone:i,truncateNumbersWithPound:a};Cs(d,F.dataType.DECIMAL,$e.makeCustomFormat(o.defaultFormatString))&&(g.defaultDecimalFormatOptions=o),Cs(d,F.dataType.INT,st.makeCustomFormat(l.defaultFormatString))&&(g.defaultIntegerFormatOptions=l),m(g)}render(){const{defaults:e,dh:t}=this.props,{defaultDateTimeFormat:n,defaultDecimalFormatOptions:s,defaultIntegerFormatOptions:i,timeZone:o,showTimeZone:l,showTSeparator:a,truncateNumbersWithPound:d}=this.state,{defaultFormatString:h=$e.DEFAULT_FORMAT_STRING}=s??{},{defaultFormatString:u=st.DEFAULT_FORMAT_STRING}=i??{},m=o===e.timeZone,g=a===e.showTSeparator&&l===e.showTimeZone&&n===e.defaultDateTimeFormat,p=lx(s,e.defaultDecimalFormatOptions),f=ax(i,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:o,onChange:this.handleTimeZoneChange,id:"select-reset-timezone",children:r.jsx(rx,{})})}),r.jsx("div",{className:"col-1 btn-col",children:r.jsx(P,{kind:"ghost",icon:Gs,onClick:this.handleResetTimeZone,tooltip:"Reset Time Zone",className:z("btn-reset","btn-reset-time-zone",{hidden:m})})})]}),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:n,onChange:this.handleDefaultDateTimeFormatChange,id:"select-default-time-format",children:this.getCachedDateTimeFormatOptions(o,l,a,!0,n)})}),r.jsx("div",{className:"col-1 btn-col",children:r.jsx(P,{kind:"ghost",icon:Gs,onClick:this.handleResetDateTimeFormat,tooltip:"Reset DateTime Options",className:z("btn-reset","btn-reset-date-time",{hidden:g})})})]}),r.jsx("div",{className:"form-row",children:r.jsx("div",{className:"offset-3 col-9",children:r.jsx(tn,{checked:l??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(tn,{checked:a??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:z("form-control","flex-grow-1","default-decimal-format-input",{"is-invalid":!Cs(t,F.dataType.DECIMAL,$e.makeCustomFormat(h))}),"data-lpignore":!0,placeholder:$e.DEFAULT_FORMAT_STRING,type:"text",id:"default-decimal-format-input",value:h,onChange:this.handleDefaultDecimalFormatChange})}),r.jsx("div",{className:"col-1 btn-col",children:r.jsx(P,{kind:"ghost",icon:Gs,onClick:this.handleResetDecimalFormat,tooltip:"Reset Decimal Formatting",className:z("btn-reset","btn-reset-decimal",{hidden:p}),"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:z("form-control","flex-grow-1","default-integer-format-input",{"is-invalid":!Cs(t,F.dataType.INT,st.makeCustomFormat(u))}),"data-lpignore":!0,placeholder:st.DEFAULT_FORMAT_STRING,type:"text",id:"default-integer-format-input",value:u,onChange:this.handleDefaultIntegerFormatChange})}),r.jsx("div",{className:"col-1 btn-col",children:r.jsx(P,{kind:"ghost",icon:Gs,onClick:this.handleResetIntegerFormat,tooltip:"Reset Integer Formatting",className:z("btn-reset","btn-reset-integer",{hidden:f}),"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(tn,{checked:d??null,onChange:this.handleTruncateNumbersWithPoundChange,children:"Truncate numbers with #"})})})]})})}}const dx=c=>({formatter:Eh(c),defaultDateTimeFormat:wh(c),defaultDecimalFormatOptions:vh(c),defaultIntegerFormatOptions:Th(c),dh:Kl(c),showTimeZone:yh(c),showTSeparator:Rh(c),truncateNumbersWithPound:xh(c),timeZone:go(c),settings:gt(c)}),cx=mt(dx,{saveSettings:Xl})(td);function hx(){const[c,e]=v.useState(!1),t=()=>{e(!c)};return r.jsxs(P,{kind:"ghost",onClick:t,icon:Wg,children:["Legal Notices",r.jsxs($l,{isOpen:c,toggle:t,className:"theme-bg-light",children:[r.jsx(Wl,{toggle:t,children:"Legal Notice"}),r.jsxs(Gl,{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 so(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(P,{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(X,{transform:t?"flip-v":"",icon:Vn})})]})}),r.jsx(Am,{in:t,autoFocusOnShow:!0,children:e})]})}so.propTypes={children:U.node,isExpanded:U.bool.isRequired,sectionKey:U.string.isRequired,title:U.node.isRequired,onToggle:U.func};so.defaultProps={children:null,onToggle:()=>{}};function ux({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(nn.getDisplayText(o)),c.matchesKeyState(o)&&d(!1)},[o,c]),v.useEffect(function(){if(a){if(!nn.isValidKeyState(o)){nn.isAllowedKey(o.keyValue)?u("Must contain a modifier key"):u("Must contain an allowed action key");return}const T=He.getConflictingShortcuts(o).filter(E=>E.id.startsWith(t)&&E!==c).map(E=>E.name);if(T.length){u(`Conflicts with ${T.join(", ")}`);return}u("")}else u("")},[a,o,t,c]);function m(w){if(w.stopPropagation(),w.preventDefault(),c.isEditable&&!w.repeat){const T=nn.getKeyStateFromEvent(w),E=nn.createKeyState([ve.BACKSPACE]);nn.doKeyStatesMatch(T,E)?l(nn.NULL_KEY_STATE):l(T)}}function g(w){w.stopPropagation(),w.preventDefault(),c.matchesKeyState(o)||d(!0)}function p(){ws.disableAllActions()}function f(){ws.enableAllActions()}function C(){c.setKeyState(o),d(!1),n(c)}function S(){const w=c.getKeyState();l(w),d(!1)}function b(){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(Je,{children:c.tooltip})]}),r.jsxs("div",{className:"shortcut-item-input-container",children:[r.jsx("input",{className:z("form-control",{"is-invalid":h}),onKeyDown:m,onKeyUp:g,onFocus:p,onBlur:f,disabled:!c.isEditable,value:s,readOnly:!0}),!nn.doKeyStatesMatch(o,c.getDefaultKeyState())&&!h&&r.jsx(P,{className:"reset-to-default-button",kind:"ghost",icon:r.jsx(X,{icon:Gs,transform:{rotate:90,flipX:!0}}),tooltip:"Reset to default",onClick:b})]})]}),a&&r.jsxs("div",{className:z("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:[nn.isValidKeyState(o)&&r.jsx(P,{kind:"ghost",onClick:C,children:"Confirm"}),r.jsx(P,{kind:"ghost",onClick:S,children:"Undo"})]})]})]})}function mx({shortcutOverrides:c={},settings:e,saveSettings:t}){const n=v.useCallback(l=>{const a=nn.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(He.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(gx,{name:l.name,shortcuts:l.shortcuts,saveShortcutOverrides:n},l.name))]})}function gx({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(ux,{shortcut:a,displayText:l[d],categoryName:c,onChange:o},a.id))]})}const px=c=>({settings:gt(c),shortcutOverrides:cC(c)}),fx={saveSettings:Xl},Cx=mt(px,fx)(mx),Sx="yyyy-MM-dd-HHmmss";function Ku(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]=Ku(i,a,t)}}}),n}function bx(){const c=Tr.getState();return JSON.stringify(Ku(c),null,2)}function wx(c){const e={uiVersion:"0.39.0",userAgent:navigator.userAgent,...c};return JSON.stringify(e,null,2)}async function vx(c=`${_t.i18n.DateTimeFormat.format(Sx,new Date)}_support_logs`,e){const t=new Vc,n=t.folder(c);n.file("console.txt",Gg.getFormattedHistory()),n.file("redux.json",bx()),n.file("metadata.json",wx(e));const s=await t.generateAsync({type:"blob"}),i=document.createElement("a");i.href=URL.createObjectURL(s),i.download=`${c}.zip`,i.click()}const Tx=[{value:F.dataType.DATETIME,label:"DateTime"},{value:F.dataType.DECIMAL,label:"Decimal"},{value:F.dataType.INT,label:"Integer"}];function Ex(){const c=Tx.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 nd extends v.PureComponent{static defaultProps={scrollTo:()=>{},defaults:{defaultDateTimeFormat:it.DEFAULT_DATETIME_FORMAT_STRING,defaultDecimalFormatOptions:{defaultFormatString:$e.DEFAULT_FORMAT_STRING},defaultIntegerFormatOptions:{defaultFormatString:st.DEFAULT_FORMAT_STRING},showTimeZone:!1,showTSeparator:!0,timeZone:it.DEFAULT_TIME_ZONE_ID}};static inputDebounceTime=250;constructor(e){super(e),this.debouncedCommitChanges=We(this.commitChanges.bind(this),nd.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=oe.createRef(),this.addFormatRuleButtonRef=oe.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(){er(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=we(()=>r.jsx(Ex,{}));getCachedDateTimeFormatOptions=we((e,t,n,s=!1,i)=>{const{timestampAtMenuOpen:o}=this.state;return r.jsx(zu,{timestamp:o,timeZone:e,showTimeZone:t,showTSeparator:n,isGlobalOptions:s,legacyGlobalFormat:i})});handleFormatRuleChange(e,t,n){this.setState(s=>{const{formatSettings:i}=s;D(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(),er(e)}commitChanges(){const{formatSettings:e,defaultDateTimeFormat:t,showTimeZone:n,showTSeparator:s,timeZone:i,defaultDecimalFormatOptions:o,defaultIntegerFormatOptions:l,truncateNumbersWithPound:a}=this.state,{dh:d}=this.props,h=e.filter(p=>Gu(d,p)).map(Wu)??[],{settings:u,saveSettings:m}=this.props,g={...u,formatter:h,defaultDateTimeFormat:t,showTimeZone:n,showTSeparator:s,timeZone:i,truncateNumbersWithPound:a};Cs(d,F.dataType.DECIMAL,$e.makeCustomFormat(o.defaultFormatString))&&(g.defaultDecimalFormatOptions=o),Cs(d,F.dataType.INT,st.makeCustomFormat(l.defaultFormatString))&&(g.defaultIntegerFormatOptions=l),m(g)}scrollToFormatBlockBottom(){const{scrollTo:e}=this.props;e(0,(this.addFormatRuleButtonRef.current?.offsetHeight??0)+(this.addFormatRuleButtonRef.current?.offsetTop??0))}getRuleError(e){const{dh:t}=this.props,n={hasColumnNameError:!1,hasFormatError:!1,message:""},s=[];return e.isNewRule!==void 0&&e.isNewRule||(this.isDuplicateRule(e)&&(n.hasColumnNameError=!0,s.push("Duplicate column name/type combo.")),$u(e.columnName)||(n.hasColumnNameError=!0,s.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?(n.hasFormatError=!0,s.push("Empty formatting rule.")):Cs(t,e.columnType,e.format)||(n.hasFormatError=!0,s.push("Invalid formatting rule.")),n.message=s.join(`
|
|
38
|
+
`)),n}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:z("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(P,{kind:"ghost",className:"btn-delete-format-rule float-right",tabIndex:-1,onClick:()=>this.handleFormatRuleDelete(e),icon:$t,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:z("custom-select",{"is-invalid":s}),value:a,id:t,onChange:d=>{const h=it.makeFormat("",d.target.value,it.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:z("form-control","flex-grow-1",{"is-invalid":s}),"data-lpignore":!0,id:t,placeholder:st.DEFAULT_FORMAT_STRING,type:"text",value:i,onChange:o=>{const l=st.makeFormat("",o.target.value,st.TYPE_GLOBAL,void 0);this.handleFormatRuleChange(e,"format",l)}})}renderDecimalFormatRuleInput(e,t,n,s){const i=n.formatString??"";return r.jsx("input",{className:z("form-control","flex-grow-1",{"is-invalid":s}),"data-lpignore":!0,id:t,placeholder:$e.DEFAULT_FORMAT_STRING,type:"text",value:i,onChange:o=>{const l=$e.makeFormat("",o.target.value,$e.TYPE_GLOBAL,void 0);this.handleFormatRuleChange(e,"format",l)}})}render(){const{formatRulesChanged:e,formatSettings:t}=this.state,n=t.map((i,o)=>r.jsx(Vt,{classNames:"fade",timeout:Ye.transitionMs,onEnter:this.handleFormatRuleEntered,children:this.renderFormatRule(o,i)},i.id)),s=r.jsx(P,{kind:"ghost",className:"mb-3",onClick:this.handleFormatRuleCreate,ref:this.addFormatRuleButtonRef,icon:Ts,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(vm,{appear:e,enter:e,exit:e,children:n}),s]})}}const yx=c=>({formatter:Eh(c),defaultDateTimeFormat:wh(c),defaultDecimalFormatOptions:vh(c),defaultIntegerFormatOptions:Th(c),dh:Kl(c),showTimeZone:yh(c),showTSeparator:Rh(c),truncateNumbersWithPound:xh(c),timeZone:go(c),settings:gt(c)}),Rx=mt(yx,{saveSettings:Xl})(nd);class Rn 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=oe.createRef(),this.broadcastChannel=new BroadcastChannel(Lm),this.state={expandedSectionKey:Rn.FORMATTING_SECTION_KEY}}componentDidMount(){Rn.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(Pm))}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;vx(void 0,Object.fromEntries(e))}render(){const e="0.39.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(X,{icon:zg,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(X,{icon:Kg,className:"mr-1"}),i.operateAs]})]})]}),i.permissions.canLogout&&r.jsx("button",{type:"button",className:"btn btn-link",onClick:this.handleLogout,children:"logout"})]})]}),r.jsx(P,{kind:"ghost",className:"btn-close-settings-menu",onClick:this.handleClose,icon:r.jsx(X,{icon:ho,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(so,{sectionKey:Rn.FORMATTING_SECTION_KEY,isExpanded:this.isSectionExpanded(Rn.FORMATTING_SECTION_KEY),title:r.jsxs(r.Fragment,{children:[r.jsx(X,{icon:Yg,transform:"grow-4",className:"mr-2"}),"Default Format & Time zone"]}),onToggle:this.handleSectionToggle,children:r.jsx(cx,{})}),r.jsx(so,{sectionKey:Rn.COLUMN_SPECIFIC_SECTION_KEY,isExpanded:this.isSectionExpanded(Rn.COLUMN_SPECIFIC_SECTION_KEY),title:r.jsxs(r.Fragment,{children:[r.jsx(X,{icon:qg,transform:"grow-4",className:"mr-2"}),"Format by Column Name & Type"]}),onToggle:this.handleSectionToggle,children:r.jsx(Rx,{scrollTo:this.handleScrollTo})}),r.jsx(so,{sectionKey:Rn.SHORTCUT_SECTION_KEY,isExpanded:this.isSectionExpanded(Rn.SHORTCUT_SECTION_KEY),title:r.jsxs(r.Fragment,{children:[r.jsx(X,{icon:Xg,transform:"grow-2"})," ","Keyboard Shortcuts"]}),onToggle:this.handleSectionToggle,children:r.jsx(Cx,{})}),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(P,{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(X,{icon:Zg}),r.jsxs(Je,{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(jl,{tooltip:"Copy version numbers",copy:`Engine Version: ${a}
|
|
39
|
+
Web UI Version: ${e}
|
|
40
|
+
Java Version: ${l}
|
|
41
|
+
Barrage Version: ${o}`,children:"Copy Versions"})]})]})]}),r.jsx("div",{className:"app-settings-footer-item",children:r.jsx(hx,{})})]}),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:Bu,alt:"Deephaven Data Labs",width:"230px"})})})})]})]})]})}}const Oc=10;function Ci(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(S=>{d.current!=null&&h.current!=null&&u.current&&(Math.abs(d.current-S.clientX)>=Oc||Math.abs(h.current-S.clientY)>=Oc)&&(g(!0),window.removeEventListener("mousemove",p),a(),e(S),u.current=null)},[e,a]);function f(S){d.current=S.clientX,h.current=S.clientY,u.current=S.target,window.addEventListener("mousemove",p)}function C(S){u.current===S.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:z("btn-context-menu",{disabled:n},{active:o&&!n},{"keyboard-active":l&&!n}),onMouseDown:f,onMouseUp:C,disabled:m,children:[r.jsx("span",{className:z("icon"),children:s}),r.jsx("span",{className:"title",children:t}),r.jsx("span",{className:"shortcut",children:i})]})}function sd(c){const{handleControlSelect:e,handleToolSelect:t,onClearFilter:n}=c,s=v.useMemo(()=>[{title:"Input Filter",icon:Qg,menuElement:r.jsx(Ci,{}),action:i=>{e(fs.INPUT_FILTER,i)},order:10},{title:"Dropdown Filter",icon:nh,menuElement:r.jsx(Ci,{}),action:i=>{e(fs.DROPDOWN_FILTER,i)},order:15},{title:"Markdown Widget",icon:Jg,menuElement:r.jsx(Ci,{}),action:i=>{e(fs.MARKDOWN,i)},order:20},{title:"Filter Sets",icon:Ua,menuElement:r.jsx(Ci,{}),action:i=>{e(fs.FILTER_SET_MANAGER,i)},order:25},{disabled:!0,menuElement:r.jsx("div",{className:"context-menu-group-header",children:"Tools"}),order:30},{title:"Linker",icon:Jc,action:()=>{t(Ot.LINKER)},order:40,shortcut:Yn.LINKER},{disabled:!0,menuElement:r.jsx("div",{className:"context-menu-group-header",children:"Actions"}),order:50},{title:"Clear All Filters",icon:ep,action:()=>{n()},order:60,shortcut:Ht.TABLE.CLEAR_ALL_FILTERS}],[e,t,n]);return r.jsx($n,{popperClassName:"controls-menu-popper",actions:s})}sd.propTypes={handleControlSelect:U.func,handleToolSelect:U.func,onClearFilter:U.func};sd.defaultProps={handleControlSelect:()=>{},handleToolSelect:()=>{},onClearFilter:()=>{}};Ci.propTypes={forwardedProps:U.shape({iconElement:U.node,displayShortcut:U.string,isMouseSelected:U.bool.isRequired,isKeyboardSelected:U.bool.isRequired,closeMenu:U.func.isRequired,menuItem:U.shape({action:U.func,title:U.string,disabled:U.bool}).isRequired})};Ci.defaultProps={forwardedProps:null};const xx=Es(Uu,null),Ix={layoutStorage:xx},Dx=c=>c.layoutStorage,Fx=c=>c.serverConfigValues;Object.entries(Ix).map(([c,e])=>po.register(c,e));const Ac=10;function Nx(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,E)=>{T!=null&&s(T,E)},[s]),g=v.useCallback(T=>{d(T.target.value)},[]),p=v.useCallback(T=>{u.current!=null&&(Math.abs(u.current.x-T.clientX)>=Ac||Math.abs(u.current.y-T.clientY)>=Ac)&&(l(!0),window.removeEventListener("mousemove",p),m(u.current.widget,T),u.current=void 0)},[u,m]),f=v.useCallback((T,E)=>{u.current={x:T.clientX,y:T.clientY,widget:E},window.addEventListener("mousemove",p)},[p]),C=v.useCallback((T,E)=>{window.removeEventListener("mousemove",p),u.current?.widget===E&&(l(!0),m(E)),u.current=void 0},[p,u,m]),S=v.useMemo(()=>i.filter(T=>a?T.name?.toLowerCase().includes(a.toLowerCase()):!0),[a,i]).sort((T,E)=>T.name?.localeCompare(E.name??"")??0),b=v.useMemo(()=>S.map(T=>r.jsx("li",{children:r.jsxs(P,{kind:"ghost","data-testid":`panel-list-item-${T.name??""}-button`,onMouseDown:E=>{f(E,T)},onMouseUp:E=>{C(E,T)},onKeyDown:E=>{(E.key==="Enter"||E.key===" ")&&m(T)},disabled:o,onClick:()=>{},children:[r.jsx(oh,{type:T.type})," ",T.name??""]})},T.name)),[S,o,f,C,m]),w=v.useMemo(()=>b.length===0?r.jsx("span",{children:"No bound variables found."}):null,[b]);return r.jsxs("div",{className:"widget-list-container d-flex flex-column",children:[r.jsx("div",{className:"widget-list-header",children:r.jsx(xi,{value:a,placeholder:"Find Table, Plot or Widget",onChange:g,ref:h})}),r.jsxs("ul",{className:"widget-list flex-grow-1",children:[w&&r.jsx("li",{className:"widget-list-message",children:w}),!w&&b]}),r.jsx("div",{children:r.jsx("hr",{})}),r.jsxs("div",{className:"widget-list-footer",children:[r.jsxs(P,{kind:"ghost",onClick:e,children:[r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx(X,{mask:Ha,icon:bd,transform:"right-5 down-5"}),r.jsx(X,{icon:bd,transform:"right-8 down-6"})]}),"Export Layout"]}),r.jsxs(P,{kind:"ghost",onClick:t,children:[r.jsxs("div",{className:"fa-md fa-layers",children:[r.jsx(X,{mask:Ha,icon:Ba,transform:"right-5 down-5"}),r.jsx(X,{icon:Ba,transform:"right-8 down-6"})]}),"Import Layout"]}),r.jsx(P,{kind:"ghost",icon:Gs,onClick:n,tooltip:"Reset Layout"})]})]})}const kx=async(c,e,t,n)=>{let s,i,o,l;if(sl(t)?(s=t.settings,i=t.table,o=void 0,l=t.tableSettings):(s={},i="",o=t.figure,l={}),n!==void 0&&(n.tableSettings!=null&&(l=n.tableSettings),n.table!=null&&(i=n.table),n.figure!=null&&(o=n.figure),n.settings!=null&&(s={...s,...n.settings})),o!==void 0){const h={title:o,name:o,type:c.VariableType.FIGURE},u=await e.getObject(h);return pl.makeModel(c,s,u)}const a={title:o,name:i,type:c.VariableType.TABLE},d=await e.getObject(a);return new Ce(c).applyTableSettings(d,l,go(Tr.getState())),pl.makeModelFromSettings(c,s,d)},Mx=async(c,e,t,n=c.VariableType.TABLE)=>{const{table:s}=t,i={title:s,name:s,type:n},o=await e.getObject(i);return Vr.makeModel(c,o)};function Ox({onAutoFillClick:c=()=>{}}){return r.jsxs("div",{className:"empty-dashboard-container",children:[r.jsxs("div",{className:"hint-container",children:[r.jsx(X,{icon:th})," ",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(P,{kind:"tertiary",onClick:c,children:"Auto fill objects"})]})]})}function Ax(c){return c.version===2}function Lx(c){return Array.isArray(c)}const Jo=J.module("UserLayoutUtils"),_x={layoutConfig:[{type:"column",content:[{type:"row",height:40,content:[{type:"stack",content:[{type:"react-component",component:fi.COMPONENT,title:fi.TITLE,isClosable:!1},{type:"react-component",component:Ml.COMPONENT,title:Ml.TITLE,isClosable:!1}]},{type:"stack",width:25,content:[{type:"react-component",component:xl.COMPONENT,title:xl.TITLE,isClosable:!1},{type:"react-component",component:Dl.COMPONENT,title:Dl.TITLE,isClosable:!1}]}]},{type:"row",content:[{type:"stack",title:"Notebooks",content:[]}]}]}],links:[],filterSets:[],version:2},Px={layoutConfig:[],links:[],filterSets:[],version:2};function Yu(c){if(Ax(c))return c;if(Lx(c))return{layoutConfig:c,links:[],filterSets:[],version:2};throw new Error(`Unexpected layout import format: ${c}`)}async function jx(c,e=!0){try{const t=await c.getLayouts();if(t.length>0)try{const n=await c.getLayout(t[0]);return Yu(n)}catch(n){Jo.error("Unable to load layout",t[0],":",n),Jo.warn("No valid layouts found, falling back to default layout")}}catch(t){Jo.error("Unable to fetch layout list",t),Jo.warn("Falling back to default layout")}return e?_x:Px}function Hx(c){const{filterSets:e,layoutConfig:t,links:n}=c;return{filterSets:e,layoutConfig:t,links:n,version:2}}const ol={exportLayout:Hx,getDefaultLayout:jx,normalizeLayout:Yu},el=J.module("DownloadServiceWorkerUtils");class ro{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(),el.info("Registering service worker on ",t,n)}).catch(n=>{el.error("Failed to register service worker",n)})}):el.info("Service worker is not supported."))}static async getServiceWorker(){if("serviceWorker"in navigator){const t=(await navigator.serviceWorker.getRegistrations()).find(n=>n.scope.endsWith(ro.DOWNLOAD_PATH));if(t&&t.active)return el.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 nt=J.module("AppMainContainer");class Si extends v.Component{static handleWindowBeforeUnload(e){e.preventDefault(),e.returnValue=""}static hydrateConsole(e,t){return Ya.hydrate({...e,unzip:n=>Vc.loadAsync(n).then(s=>Object.values(s.files))},t)}static handleRefresh(){nt.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=oe.createRef(),this.state={contextActions:[{action:()=>{this.handleToolSelect(Ot.LINKER)},shortcut:Yn.LINKER,isGlobal:!0},{action:()=>{this.sendClearFilter()},shortcut:Ht.TABLE.CLEAR_ALL_FILTERS,isGlobal:!0},{action:()=>{nt.debug("Consume unhandled save shortcut")},shortcut:Yn.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){nt.warn("subscribeToFieldUpdates not supported, not initializing widgets");return}this.widgetListenerRemover=e.subscribeToFieldUpdates(t=>{nt.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){nt.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(Le.SELECT_NOTEBOOK,n,o,l,i,!0)}}sendClearFilter(){this.emitLayoutEvent(Ke.CLEAR_ALL_FILTERS)}emitLayoutEvent(e,...t){this.goldenLayout?.eventHub.emit(e,...t)}handleError(e){be.isCanceled(e)||nt.error(e)}handleSettingsMenuHide(){this.setState({isSettingsMenuShown:!1})}handleSettingsMenuShow(){this.setState({isSettingsMenuShown:!0})}handleControlSelect(e,t=null){switch(nt.debug("handleControlSelect",e),e){case fs.DROPDOWN_FILTER:this.emitLayoutEvent(Ke.OPEN_DROPDOWN,{title:"DropdownFilter",type:e,createNewStack:!0,dragEvent:t});break;case fs.INPUT_FILTER:this.emitLayoutEvent(Ke.OPEN_INPUT,{title:"InputFilter",type:e,createNewStack:!0,dragEvent:t});break;case fs.MARKDOWN:this.emitLayoutEvent(Nu.OPEN,{title:"Markdown",type:e,dragEvent:t});break;case fs.FILTER_SET_MANAGER:this.emitLayoutEvent(Ke.OPEN_FILTER_SET_MANAGER,{title:"FilterSets",type:e,dragEvent:t});break;default:throw new Error(`Unrecognized control type ${e}`)}}handleToolSelect(e){nt.debug("handleToolSelect",e);const{activeTool:t,setActiveTool:n}=this.props;n(t===e?Ot.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}),nt.debug("handleWidgetSelect",e,t),this.openWidget(e,t)}handleWidgetsMenuClose(){this.setState({isPanelsMenuShown:!1})}handleAutoFillClick(){const{widgets:e}=this.state;nt.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(){nt.info("handleExportLayoutClick"),this.setState({isPanelsMenuShown:!1});try{const{workspace:e}=this.props,{data:t}=e,n=ol.exportLayout(t);nt.info("handleExportLayoutClick exportedConfig",n);const s=new Blob([JSON.stringify(n)],{type:"application/json"}),i=_t.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){nt.error("Unable to export layout",e)}}handleImportLayoutClick(){nt.info("handleImportLayoutClick"),this.setState({isPanelsMenuShown:!1}),this.importElement.current!=null&&(this.importElement.current.value="",this.importElement.current.click())}handleResetLayoutClick(){nt.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(){nt.info("Disconnected from server"),this.setState({isDisconnected:!0})}handleReconnect(){nt.info("Reconnected to server"),this.setState({isDisconnected:!1})}handleReconnectAuthFailed(){nt.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}=ol.normalizeLayout(i);n({layoutConfig:l}),t(un,{filterSets:o,links:a})}catch(t){nt.error("Unable to import layout",t)}}async resetLayout(){const{layoutStorage:e,session:t}=this.props,{filterSets:n,layoutConfig:s,links:i}=await ol.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 nt.error(s),r.jsx("div",{className:"error-message",children:`${s}`})}startListeningForDisconnect(){const{connection:e}=this.props;e.addEventListener(_t.IdeConnection.EVENT_DISCONNECT,this.handleDisconnect),e.addEventListener(_t.IdeConnection.EVENT_RECONNECT,this.handleReconnect),e.addEventListener(_t.CoreClient.EVENT_RECONNECT_AUTH_FAILED,this.handleReconnectAuthFailed)}stopListeningForDisconnect(){const{connection:e}=this.props;e.removeEventListener(_t.IdeConnection.EVENT_DISCONNECT,this.handleDisconnect),e.removeEventListener(_t.IdeConnection.EVENT_RECONNECT,this.handleReconnect),e.removeEventListener(_t.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 Ya.hydrate(e,t)}hydrateGrid(e,t){return this.hydrateTable(e,t,e.metadata.type??_t.VariableType.TABLE)}hydratePandas(e,t){return this.hydrateTable(e,t,_t.VariableType.PANDAS)}hydrateTable(e,t,n=_t.VariableType.TABLE){const{connection:s}=this.props;return{...e,getDownloadWorker:ro.getServiceWorker,loadPlugin:this.handleLoadTablePlugin,localDashboardId:t,makeModel:()=>Mx(_t,s,e.metadata,n)}}hydrateChart(e,t){const{connection:n}=this.props;return{...e,localDashboardId:t,makeModel:()=>{const{metadata:s,panelState:i}=e;return kx(_t,n,s,i)}}}openWidget(e,t){const{connection:n}=this.props;this.emitLayoutEvent(Se.OPEN,{dragEvent:t,fetch:()=>n.getObject(e),widget:e})}getDashboardPlugins=ce(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:f}=this.state,C=this.getDashboardPlugins(t);return r.jsxs("div",{className:z("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:Bu,alt:"Deephaven Data Labs",width:"115px",className:"ml-1"}),r.jsxs("div",{children:[r.jsxs(P,{kind:"ghost",className:"btn-panels-menu",icon:tp,onClick:()=>{},children:["Controls",r.jsx(sd,{handleControlSelect:this.handleControlSelect,handleToolSelect:this.handleToolSelect,onClearFilter:this.handleClearFilter})]}),d&&r.jsxs(P,{kind:"ghost",className:"btn-panels-menu btn-show-panels","data-testid":"app-main-panels-button",onClick:this.handleWidgetMenuClick,icon:np,children:["Panels",r.jsx(Ul,{isShown:g,className:"panels-menu-popper",onExited:this.handleWidgetsMenuClose,closeOnBlur:!0,interactive:!0,children:r.jsx(Nx,{widgets:f,onExportLayout:this.handleExportLayoutClick,onImportLayout:this.handleImportLayoutClick,onResetLayout:this.handleResetLayoutClick,onSelect:this.handleWidgetSelect})})]}),r.jsx(P,{kind:"ghost",className:z("btn-settings-menu",{"text-warning":n.operateAs!=null&&n.operateAs!==n.name}),onClick:this.handleSettingsMenuShow,icon:r.jsx(X,{icon:uo,transform:"grow-3 right-1 down-1"}),tooltip:"User Settings"})]})]})}),r.jsxs(Sb,{emptyDashboard:r.jsx(Ox,{onAutoFillClick:this.handleAutoFillClick}),id:un,layoutConfig:l,onGoldenLayoutChange:this.handleGoldenLayoutChange,onLayoutConfigChange:this.handleLayoutConfigChange,onLayoutInitialized:this.openNotebookFromURL,hydrate:this.hydrateDefault,children:[r.jsx(FR,{hydrate:this.hydrateGrid,getDownloadWorker:ro.getServiceWorker,loadPlugin:this.handleLoadTablePlugin}),r.jsx(yR,{hydrate:this.hydrateChart}),r.jsx(RR,{}),r.jsx(IR,{hydrateConsole:Si.hydrateConsole,notebooksUrl:new URL("notebooks/",document.baseURI).href}),r.jsx(DR,{}),r.jsx(BR,{hydrate:this.hydratePandas}),r.jsx(UR,{}),r.jsx(HR,{}),C]}),r.jsx(Vt,{in:p,timeout:Ye.transitionMidMs,classNames:"slide-left",mountOnEnter:!0,unmountOnExit:!0,children:r.jsx(Rn,{serverConfigValues:i,onDone:this.handleSettingsMenuHide,user:n})}),r.jsx(te,{actions:h}),r.jsx("input",{ref:this.importElement,type:"file",accept:".json",style:{display:"none"},onChange:this.handleImportLayoutFiles}),r.jsx(jm,{isOpen:m&&!u,debounceMs:250,children:r.jsx(Hm,{icon:sp,title:r.jsxs(r.Fragment,{children:[r.jsx(Nn,{})," Attempting to reconnect..."]}),subtitle:"Please check your network connection."})}),r.jsx(io,{confirmButtonText:"Refresh",onConfirm:Si.handleRefresh,isOpen:u,headerText:"Authentication failed",bodyText:"Credentials are invalid. Please refresh your browser to try and reconnect."})]})}}const Ux=c=>({activeTool:ql(c),dashboardData:At(c,un),layoutStorage:Dx(c),plugins:uC(c),connection:ay(c,un),session:Qs(c,un)?.session,sessionConfig:Qs(c,un)?.config,user:Ch(c),workspace:Yl(c),serverConfigValues:Fx(c)}),Bx=mt(Ux,{setActiveTool:Zl,updateDashboardData:kn,updateWorkspaceData:Ph})(Tm(Si));function Vx(){return r.jsxs("div",{className:"app",children:[r.jsx(Bx,{}),r.jsx(Kc,{})]})}const $x=J.module("LocalWorkspaceStorage");class bi{static STORAGE_KEY="deephaven.WorkspaceStorage";static async makeDefaultWorkspaceData(e,t){const{filterSets:n,links:s,layoutConfig:i}=await ol.getDefaultLayout(e,t?.isConsoleAvailable);return{settings:{defaultDateTimeFormat:it.DEFAULT_DATETIME_FORMAT_STRING,formatter:[],timeZone:it.DEFAULT_TIME_ZONE_ID,showTimeZone:!1,showTSeparator:!0,disableMoveConfirmation:!1,defaultDecimalFormatOptions:{defaultFormatString:$e.DEFAULT_FORMAT_STRING},defaultIntegerFormatOptions:{defaultFormatString:st.DEFAULT_FORMAT_STRING},truncateNumbersWithPound:!1,defaultNotebookSettings:{isMinimapEnabled:!1}},layoutConfig:i,closed:[{}],links:s,filterSets:n}}static async makeDefaultWorkspace(e,t){return{data:await bi.makeDefaultWorkspaceData(e,t)}}layoutStorage;constructor(e){this.layoutStorage=e}async load(e){try{return JSON.parse(localStorage.getItem(bi.STORAGE_KEY)??"")}catch{return $x.info("Unable to load workspace data, initializing to default data"),bi.makeDefaultWorkspace(this.layoutStorage,e)}}async save(e){return localStorage.setItem(bi.STORAGE_KEY,JSON.stringify(e)),e}}class Wx{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 zi=J.module("GrpcFileStorageTable");class Al{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=We(this.doRefresh.bind(this),Al.REFRESH_DEBOUNCE))}removeBaseRoot(e){return me.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 Al(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){zi.debug2("doRefresh",this.root),e(this.fetchData())}refresh(){zi.debug2("refresh",this.root),this.viewportUpdatePromise?.cancel();const e=new Promise(n=>{this.doRefresh(n)}),t=be.makeCancelable(e.then(n=>{if(this.viewportUpdatePromise!==t)throw new Pl;return this.currentViewportData=n,this.sendUpdate(),n}));t.catch(n=>{be.isCanceled(n)||zi.error("Error updating viewport",n)}),this.viewportUpdatePromise=t}refreshInternal(){try{this.refresh()}catch(e){be.isCanceled(e)||zi.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,zi.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 Gx=J.module("GrpcFileStorage");class id{static REFRESH_THROTTLE=150;storageService;tables=[];root;constructor(e,t=""){this.storageService=e,this.root=t}removeRoot(e){return me.removeRoot(this.root,e)}addRoot(e){return me.addRoot(this.root,e)}async createDirectory(e){return await this.storageService.createDirectory(this.addRoot(e)),this.refreshTables(),{type:"directory",id:e,filename:e,basename:me.getBaseName(e)}}async getTable(){const e=new Al(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:me.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(me.getPath(e)),me.getBaseName(e));if(t.length===0)throw new Zr;if(t.length>1)throw Gx.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=bs(()=>{this.tables.forEach(e=>e.refresh())},id.REFRESH_THROTTLE)}const zx=J.module("AppInit");function od(c){const{workspace:e,setActiveTool:t,setApi:n,setCommandHistoryStorage:s,setDashboardData:i,setFileStorage:o,setLayoutStorage:l,setDashboardConnection:a,setDashboardSessionWrapper:d,setPlugins:h,setUser:u,setWorkspace:m,setWorkspaceStorage:g,setServerConfigValues:p}=c,f=vs(),C=Um(),S=Bm(),b=Vm(),w=v.useContext($m),T=v.useContext(Wm),[E,y]=v.useState();v.useEffect(function(){h(b)},[b,h]),v.useEffect(function(){async function k(){try{const _=await Gm(),M=await zm(f,S,_),$=C.getStorageService(),H=new Wx($,"/layouts"),K=new id($,"/notebooks"),L=new bi(H),G=new tx,[ee,W]=await Promise.all([C.getServerConfigValues(),L.load({isConsoleAvailable:M!==void 0})]),{data:j}=W,{settings:B}=j;B.defaultDecimalFormatOptions===void 0&&(B.defaultDecimalFormatOptions={defaultFormatString:$e.DEFAULT_FORMAT_STRING}),B.defaultIntegerFormatOptions===void 0&&(B.defaultIntegerFormatOptions={defaultFormatString:st.DEFAULT_FORMAT_STRING}),B.truncateNumbersWithPound===void 0&&(B.truncateNumbersWithPound=!1);const{shortcutOverrides:Z={}}=B,ae=nn.isMacPlatform?Z.mac??{}:Z.windows??{};Object.entries(ae).forEach(([ye,rt])=>{He.get(ye)?.setKeyState(rt)});const q={filterSets:j.filterSets,links:j.links},ne=new Map(ee),he="",Te={name:he,operateAs:he,groups:[],...w,permissions:{isACLEditor:!1,isSuperUser:!1,isQueryViewOnly:!1,isNonInteractive:!1,canUsePanels:!0,canCreateDashboard:!0,canCreateCodeStudio:!0,canCreateQueryMonitor:!0,canCopy:ne.get("internal.webClient.appInit.canCopy")!=="false",canDownloadCsv:ne.get("internal.webClient.appInit.canDownloadCsv")!=="false",canLogout:!0,...T}};n(f),t(Ot.DEFAULT),p(ne),s(G),i(un,q),o(K),l(H),a(un,S),M!==void 0&&d(un,M),u(Te),g(L),m(W)}catch(_){zx.error(_),y(_)}}k()},[f,C,S,t,n,s,i,o,l,a,d,u,m,g,p,w,T]);const R=e==null&&E==null,I=!R&&E==null,x=E!=null?`${E}`:null;return r.jsxs(r.Fragment,{children:[I&&r.jsx(Vx,{}),r.jsx(Bl,{isLoading:R&&x==null,isLoaded:I,errorMessage:x})]})}od.propTypes={workspace:U.shape({}),workspaceStorage:U.shape({close:U.func}),setActiveTool:U.func.isRequired,setApi:U.func.isRequired,setCommandHistoryStorage:U.func.isRequired,setDashboardData:U.func.isRequired,setFileStorage:U.func.isRequired,setLayoutStorage:U.func.isRequired,setDashboardConnection:U.func.isRequired,setDashboardSessionWrapper:U.func.isRequired,setPlugins:U.func.isRequired,setUser:U.func.isRequired,setWorkspace:U.func.isRequired,setWorkspaceStorage:U.func.isRequired};od.defaultProps={workspace:null,workspaceStorage:null};const Kx=c=>({workspace:Yl(c),workspaceStorage:dC(c)}),Lc=mt(Kx,{setActiveTool:Zl,setApi:gC,setCommandHistoryStorage:fC,setDashboardData:au,setFileStorage:CC,setLayoutStorage:nx,setDashboardConnection:ry,setDashboardSessionWrapper:dy,setPlugins:bC,setUser:mC,setWorkspace:_h,setWorkspaceStorage:pC,setServerConfigValues:wC})(od),Yx=document.location.pathname;function qx(){return r.jsx(Em,{basename:Yx,children:r.jsxs(ym,{children:[r.jsx(dd,{exact:!0,path:"/",component:Lc}),r.jsx(dd,{path:"/notebooks/:notebookPath+",component:Lc}),r.jsx(Rm,{from:"*",to:"/"})]})})}function sI(){return ro.registerOnLoaded(),Mt.init({getWorker:()=>new Ym}),window["__react-beautiful-dnd-disable-dev-warnings"]=!0,r.jsx(jc,{store:Tr,children:r.jsx(qx,{})})}export{sI as AppRoot,sI as default};
|
|
42
|
+
//# sourceMappingURL=AppRoot-1a29b8a5.js.map
|