@vuu-ui/vuu-table 0.6.18 → 0.6.19-debug

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/cjs/index.js CHANGED
@@ -1,11 +1,2761 @@
1
- "use strict";var Dp=Object.create;var Wr=Object.defineProperty;var Ap=Object.getOwnPropertyDescriptor;var Pp=Object.getOwnPropertyNames;var Ep=Object.getPrototypeOf,Op=Object.prototype.hasOwnProperty;var Ip=(n,e)=>{for(var t in e)Wr(n,t,{get:e[t],enumerable:!0})},ja=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Pp(e))!Op.call(n,r)&&r!==t&&Wr(n,r,{get:()=>e[r],enumerable:!(i=Ap(e,r))||i.enumerable});return n};var ue=(n,e,t)=>(t=n!=null?Dp(Ep(n)):{},ja(e||!n||!n.__esModule?Wr(t,"default",{value:n,enumerable:!0}):t,n)),Vp=n=>ja(Wr({},"__esModule",{value:!0}),n);var Ja=(n,e,t)=>{if(!e.has(n))throw TypeError("Cannot "+t)};var k=(n,e,t)=>(Ja(n,e,"read from private field"),t?t.call(n):e.get(n)),W=(n,e,t)=>{if(e.has(n))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(n):e.set(n,t)},P=(n,e,t,i)=>(Ja(n,e,"write to private field"),i?i.call(n,t):e.set(n,t),t),Qa=(n,e,t,i)=>({set _(r){P(n,e,r,t)},get _(){return k(n,e,i)}});var Nw={};Ip(Nw,{Table:()=>Ew,useMeasuredContainer:()=>za});module.exports=Vp(Nw);var ho=require("@heswell/salt-lab"),Fp=require("@salt-ds/core"),Hp=ue(require("classnames")),co=require("react");var Gn=require("react"),tu=ue(require("react-dom"));var Xa=ue(require("react-dom")),Ya=require("@salt-ds/core"),eu=require("react/jsx-runtime"),Lp=1,Np=(n=0,e=0,t=window)=>{let i=t.document.createElement("div");return i.className="vuuPopup "+Lp++,i.style.cssText=`left:${n}px; top:${e}px;`,t.document.body.appendChild(i),i},Bp=(n,e)=>Np(n,e),_r=(n,e,t,i,r)=>{e.style.cssText=`left:${t}px; top:${i}px;position: absolute;`,Xa.render((0,eu.jsx)(Ya.SaltProvider,{applyClassesTo:"child",children:n}),e,r)},Za=Bp;var uo=function({children:e,x:t=0,y:i=0,onRender:r}){let s=(0,Gn.useMemo)(()=>Za(),[]);return(0,Gn.useLayoutEffect)(()=>{_r(e,s,t,i,r)},[e,r,s,t,i]),(0,Gn.useLayoutEffect)(()=>()=>{var o;s&&(tu.unmountComponentAtNode(s),s.classList.contains("vuuPopup")&&((o=s.parentElement)==null||o.removeChild(s)))},[s]),null};var iu=require("react/jsx-runtime");var vu=require("@salt-ds/core"),Di=require("react");var Jt=ue(require("react")),po=ue(require("classnames")),fu=require("@salt-ds/core");var Le=require("react");var nu=n=>n.closest("[data-root='true']")!==null,ru=(n,e)=>{var t;return n.ariaHasPopup==="true"&&((t=n.dataset)==null?void 0:t.idx)===`${e}`||n.querySelector(`:scope > [data-idx='${e}'][aria-haspopup='true']`)!==null};function Wp(n,...e){let t=new Set(n);for(let i of e)for(let r of i)t.add(r);return t}var _p="Enter";var zp="Delete",Up=new Set([_p,zp]),$p=new Set(["Tab"]),Kp=new Set(["ArrowRight","ArrowLeft"]),su=new Set(["Home","End","ArrowDown","ArrowUp"]),ou=new Set(["Home","End","ArrowRight","ArrowLeft"]),qp=new Set(["F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12"]),iv=Wp(Up,ou,su,Kp,qp,$p);var lu=({key:n},e="vertical")=>(e==="vertical"?su:ou).has(n);var au=({autoHighlightFirstItem:n=!1,count:e,highlightedIndex:t,onActivate:i,onHighlight:r,onCloseMenu:s,onOpenMenu:o})=>{let l=(0,Le.useRef)((t!=null?t:n)?0:-1),[,a]=(0,Le.useState)(null),u=t!==void 0,h=(0,Le.useCallback)(y=>{l.current=y,r==null||r(y),a({})},[r]),c=(0,Le.useCallback)(y=>{y!==l.current&&(u||h(y))},[u,h]),f=(0,Le.useRef)(!0),d=(0,Le.useRef)(!1),p=y=>d.current=y,m=u?t:l.current,g=(0,Le.useCallback)(y=>{let x=Gp(e,y.key,l.current);x!==l.current&&c(x)},[e,c]),b=(0,Le.useCallback)(y=>{lu(y)?(y.preventDefault(),y.stopPropagation(),f.current=!0,g(y)):(y.key==="ArrowRight"||y.key==="Enter")&&ru(y.target,m)?o(m):y.key==="ArrowLeft"&&!nu(y.target)?s(m):y.key==="Enter"&&i&&i(m)},[m,g,i,s,o]),C=(0,Le.useMemo)(()=>({onFocus:()=>{m===-1&&h(0)},onKeyDown:b,onMouseDownCapture:()=>{f.current=!1,p(!0)},onMouseMove:()=>{f.current&&(f.current=!1)},onMouseLeave:()=>{f.current=!0,p(!1),c(-1)}}),[m,c,g,i,s,o,h]);return{focusVisible:f.current?m:-1,controlledHighlighting:u,highlightedIndex:m,setHighlightedIndex:c,listProps:C,setIgnoreFocus:p}};function Gp(n,e,t){return e==="ArrowUp"?t>0?t-1:t:t===null?0:t===n-1?t:t+1}var Ri=ue(require("react"));var fo=n=>n.type===zr||!!n.props["data-group"],uu=n=>{let e=(0,Ri.useCallback)(()=>{let r=(o,l="root",a={},u={})=>{let h=a[l]=[],c=0,f=!1;return Ri.default.Children.forEach(o,d=>{if(d.type===hu)f=!0;else{let p=fo(d),m=l==="root"?`${c}`:`${l}.${c}`,{props:{action:g,options:b}}=d,{childWithId:C,grandChildren:y}=s(d,m,p,f);h.push(C),y?r(y,m,a,u):u[m]={action:g,options:b},c+=1,f=!1}}),[a,u]},s=(o,l,a,u=!1)=>{let{props:{children:h}}=o;return{childWithId:Ri.default.cloneElement(o,{hasSeparator:u,id:`${l}`,key:l,children:a?void 0:h}),grandChildren:a?h:void 0}};return r(n)},[n]),[t,i]=(0,Ri.useMemo)(()=>e(),[e]);return[t,i]};var Xi=require("react/jsx-runtime"),cu="vuuMenuList",hu=()=>(0,Xi.jsx)("li",{className:"vuuMenuItem-divider"}),zr=()=>null,mo=({children:n,idx:e,...t})=>(0,Xi.jsx)("div",{...t,children:n}),jp=n=>n.props["data-icon"],du=({activatedByKeyboard:n,childMenuShowing:e=-1,children:t,className:i,highlightedIdx:r,id:s,isRoot:o,listItemProps:l,menuId:a,onHighlightMenuItem:u,onActivate:h,onCloseMenu:c,onOpenMenu:f,...d})=>{let p=(0,fu.useIdMemo)(s),m=(0,Jt.useRef)(null),g=(0,Jt.useMemo)(()=>new Map,[]),b=E=>{var R;let S=(R=m.current)==null?void 0:R.querySelector(`:scope > [data-idx='${E}']`);S!=null&&S.id&&(f==null||f(S.id))},C=E=>{var R;let S=(R=m.current)==null?void 0:R.querySelector(`:scope > [data-idx='${E}']`);S!=null&&S.id&&(h==null||h(S.id))},{focusVisible:y,highlightedIndex:x,listProps:v}=au({count:Jt.default.Children.count(t),highlightedIndex:r,onActivate:C,onHighlight:u,onOpenMenu:b,onCloseMenu:c}),w=e==-1?y:-1;return(0,Jt.useLayoutEffect)(()=>{var E;e===-1&&n&&((E=m.current)==null||E.focus())},[n,e]),(0,Xi.jsx)("div",{...d,...v,"aria-activedescendant":(()=>x===void 0||x===-1?void 0:g.get(x))(),className:(0,po.default)(cu,i,{[`${cu}-childMenuShowing`]:e!==-1}),"data-root":o||void 0,id:`${p}-${a}`,ref:m,role:"menu",tabIndex:0,children:L()});function L(){let E={...l,role:"menuitem"},S=(I,z,B)=>z?[(0,Xi.jsx)("span",{className:"vuuIconContainer","data-icon":B},"icon")].concat(I):I;function R(I,z,B,Y){var Hr;let{children:ke,className:ae,"data-icon":q,id:j,hasSeparator:et,label:ft,...jt}=z.props,At=fo(z),Fr=At&&e===B,ao=Fr?`${p}-${j}`:void 0;I.push((0,Xi.jsx)(mo,{...jt,...E,...Jp(`${p}-${a}`,j,B,(Hr=z.key)!=null?Hr:j,x,w,ae,et),"aria-controls":ao,"aria-haspopup":At||void 0,"aria-expanded":Fr||void 0,children:S(At?ft:ke,Y,q)}))}let O=[];if(t.length>0){let I=t.some(jp);t.forEach((z,B)=>{R(O,z,B,I)})}return O}},Jp=(n,e,t,i,r,s,o,l)=>({id:`${n}-${e}`,key:i!=null?i:t,"data-idx":t,"data-highlighted":t===r||void 0,className:(0,po.default)("vuuMenuItem",o,{"vuuMenuItem-separator":l,focusVisible:s===t})});du.displayName="MenuList";var pu=du;var ye=require("react");function mu(n){if(n){let e=n.dataset.idx;if(e)return parseInt(e,10);if(n.ariaPosInSet)return parseInt(n.ariaPosInSet,10)-1}}var go=n=>n==null?void 0:n.closest("[data-idx],[aria-posinset]");var gu=(n,e,t)=>n.map((i,r)=>r===n.length-1?{...i,[t]:i[t]-e}:i),Qp=(n,e)=>gu(n,e,"left"),Xp=(n,e)=>gu(n,e,"top"),Yp=(n,e)=>{let[t,i]=e.slice(-2),r=document.getElementById(`${n}-${i.id}`);if(r===null)throw Error(`useCascade.flipSides element with id ${i.id} not found`);let{width:s}=r.getBoundingClientRect();return e.map(o=>o===i?{...o,left:t.left-(s-2)}:o)},Zp=(n,e)=>{let[{left:t,top:i}]=e.slice(-1),{offsetWidth:r,offsetTop:s}=n;return{left:t+r,top:s+i}},jn=n=>{let e=n.lastIndexOf("-");return e===-1?n:n.slice(e+1)},Ur=n=>{let e=jn(n),t=e.lastIndexOf(".");return t>-1?e.slice(0,t):"root"},em=n=>{let e=0,t=n.indexOf(".",0);for(;t!==-1;)e+=1,t=n.indexOf(".",t+1);return e},tm=n=>({menuId:Ur(n.id),itemId:jn(n.id),isGroup:n.ariaHasPopup==="true",isOpen:n.ariaExpanded==="true",level:em(n.id)}),bu=({id:n,onActivate:e,onMouseEnterItem:t,position:{x:i,y:r}})=>{let[,s]=(0,ye.useState)({}),o=(0,ye.useRef)([{id:"root",left:i,top:r}]),l=(0,ye.useCallback)(y=>{o.current=y,s({})},[]),a=(0,ye.useRef)(),u=(0,ye.useRef)(),h=(0,ye.useRef)({root:"no-popup"}),c=(0,ye.useRef)(0),f=(0,ye.useCallback)((y="root",x=null,v=null)=>{if(y==="root"&&x===null)l([{id:"root",left:i,top:r}]);else{h.current[y]="popup-open";let M=(v?v.ownerDocument:document).getElementById(`${n}-${y}-${x}`),{left:L,top:E}=Zp(M,o.current);l(o.current.concat({id:x,left:L,top:E}))}},[n,i,r,l]),d=(0,ye.useCallback)(y=>{l(y==="root"?[]:o.current.slice(0,-1))},[l]),p=(0,ye.useCallback)((y,x)=>{let v=o.current.slice(),{id:w}=v[v.length-1];for(;v.length>1&&!x.startsWith(w);){let M=Ur(w);v.pop(),h.current[w]="no-popup",h.current[M]="no-popup",{id:w}=v[v.length-1]}v.length<o.current.length&&l(v)},[l]),m=(0,ye.useCallback)((y,x,v)=>{a.current&&clearTimeout(a.current),a.current=window.setTimeout(()=>{console.log(`scheduleOpen timed out opening ${x}`),p(y,x),h.current[y]="popup-open",h.current[x]="no-popup",f(y,x,v)},400)},[p,f]),g=(0,ye.useCallback)((y,x,v)=>{console.log(`scheduleClose openMenuId ${y} menuId ${x} itemId ${v}`),h.current[y]="pending-close",u.current=window.setTimeout(()=>{p(x,v)},400)},[p]),b=(0,ye.useCallback)(()=>{let{current:y}=o,[x]=y.slice(-1),v=document.getElementById(`${n}-${x.id}`);if(v){let{right:w,bottom:M}=v.getBoundingClientRect(),{clientHeight:L,clientWidth:E}=document.body;if(w>E){let S=y.length>1?Yp(n,y):Qp(y,w-E);l(S)}else if(M>L){let S=Xp(y,M-L);l(S)}}},[n,l]),C=(0,ye.useMemo)(()=>({onMouseEnter:y=>{let x=go(y.target),{menuId:v,itemId:w,isGroup:M,isOpen:L,level:E}=tm(x),S=c.current===E,{current:{[v]:R}}=h;if(c.current=E,R==="no-popup"&&M)h.current[v]="popup-pending",m(v,w,x);else if(R==="popup-pending"&&!M)h.current[v]="no-popup",clearTimeout(a.current),a.current=void 0;else if(R==="popup-pending"&&M)clearTimeout(a.current),m(v,w,x);else if(R==="popup-open"){let[{id:O},{id:I}]=o.current.slice(-2);O===v&&h.current[I]!=="pending-close"&&S?(g(I,v,w),M&&!L&&m(v,w,x)):O===v&&M&&w!==I&&h.current[I]==="pending-close"?m(v,w,x):M?(p(v,w),m(v,w,x)):h.current[I]==="pending-close"&&S||p(v,w)}R==="pending-close"&&(a.current&&(clearTimeout(a.current),a.current=void 0),clearTimeout(u.current),u.current=void 0,h.current[v]="popup-open"),t(y,w)},onClick:y=>{let x=y.target,v=go(x),w=mu(v);console.log(`list item click [${w}] hasPopup ${v.ariaHasPopup}`),v.ariaHasPopup==="true"?v.ariaExpanded!=="true"&&f(w):e(jn(v.id))}}),[p,e,t,f,g,m]);return{closeMenu:d,handleRender:b,listItemProps:C,openMenu:f,openMenus:o.current}};var yu=require("react"),wu=({containerClassName:n,isOpen:e,onClose:t})=>{(0,yu.useEffect)(()=>{let i;return e&&(i=r=>{r.target.closest(`.${n}`)===null&&(t==null||t("root"))},document.body.addEventListener("click",i,!0)),()=>{i&&document.body.removeEventListener("click",i,!0)}},[n,e,t])};var Jn=require("react/jsx-runtime"),Cu=require("react"),im=()=>{},bo=({activatedByKeyboard:n,children:e,className:t,id:i,onClose:r=()=>{},position:s={x:0,y:0},style:o,...l})=>{let a=(0,vu.useIdMemo)(i),u=(0,Di.useRef)(im),[h,c]=uu(e),f=(0,Di.useRef)(n),d=(0,Di.useCallback)(()=>{f.current=!1},[]),p=(0,Di.useCallback)(S=>{let{action:R,options:O}=c[S];u.current("root"),r(R,O)},[c,r]),{closeMenu:m,listItemProps:g,openMenu:b,openMenus:C,handleRender:y}=bu({id:a,onActivate:p,onMouseEnterItem:d,position:s});u.current=m,console.log({openMenus:C});let x=(0,Di.useCallback)(()=>{m(),r()},[m,r]);wu({containerClassName:"vuuMenuList",onClose:x,isOpen:C.length>0});let v=S=>{let R=jn(S),O=Ur(R);f.current=!0,b(O,R)},w=()=>{f.current=!0,m()},M=()=>{},L=C.length-1,E=S=>{if(S>=L)return-1;{let{id:R}=C[S+1],O=R.lastIndexOf(".");return parseInt(O===-1?R:R.slice(-O),10)}};return(0,Jn.jsx)(Jn.Fragment,{children:C.map(({id:S,left:R,top:O},I)=>{let z=E(I);return(0,Jn.jsx)(uo,{x:R,y:O,onRender:y,children:(0,Cu.createElement)(pu,{...l,activatedByKeyboard:f.current,childMenuShowing:z,className:t,id:a,menuId:S,isRoot:I===0,key:I,listItemProps:g,onActivate:p,onHighlightMenuItem:M,onCloseMenu:w,onOpenMenu:v,style:o},h[S])},I)})})};bo.displayName="ContextMenu";var Yi=require("react"),$r=require("react/jsx-runtime"),Kr=(0,Yi.createContext)(null),yo=n=>n!==void 0&&"children"in n,nm=({children:n,context:e,menuActionHandler:t,menuBuilder:i})=>{let r=(0,Yi.useMemo)(()=>e!=null&&e.menuBuilders&&i?e.menuBuilders.concat(i):i?[i]:(e==null?void 0:e.menuBuilders)||[],[e,i]),s=(0,Yi.useCallback)((o,l)=>{var a;if(t!=null&&t(o,l)||(a=e==null?void 0:e.menuActionHandler)!=null&&a.call(e,o,l))return!0},[e,t]);return(0,$r.jsx)(Kr.Provider,{value:{menuActionHandler:s,menuBuilders:r},children:n})},Su=({children:n,label:e,menuActionHandler:t,menuBuilder:i})=>(0,$r.jsx)(Kr.Consumer,{children:r=>(0,$r.jsx)(nm,{context:r,label:e,menuActionHandler:t,menuBuilder:i,children:n})});var Qn=require("react");var xu=ue(require("classnames")),Zi=ue(require("react")),qr=ue(require("react-dom"));var wo=!1,tt=[];function ku(n){if(n.key==="Esc"){if(tt.length)Tu();else if(wo){let e=document.body.querySelector(".vuuDialog");e&&qr.default.unmountComponentAtNode(e)}}}function Mu(n){if(tt.length){let e=document.body.querySelectorAll(".vuuPopup");for(let t=0;t<e.length;t++)if(e[t].contains(n.target))return;Tu()}}function Tu(){if(tt.length){let n=document.body.querySelectorAll(".vuuPopup");for(let e=0;e<n.length;e++)qr.default.unmountComponentAtNode(n[e]);Ru("*")}}function rm(n){tt.indexOf(n)===-1&&(tt.push(n),wo===!1&&(window.addEventListener("keydown",ku,!0),window.addEventListener("click",Mu,!0)))}function Ru(n){if(tt.length){if(n==="*")tt.length=0;else{let e=tt.indexOf(n);e!==-1&&tt.splice(e,1)}tt.length===0&&wo===!1&&(window.removeEventListener("keydown",ku,!0),window.removeEventListener("click",Mu,!0))}}var sm=({children:n,position:e,style:t})=>{let i=(0,xu.default)("hwPopup","hwPopupContainer",e);return(0,Zi.createElement)("div",{className:i,style:t},n)},om=1,Ai=class{static showPopup({name:e="anon",group:t="all",position:i="",left:r=0,right:s="auto",top:o=0,width:l="auto",component:a}){if(!a)throw Error("PopupService showPopup, no component supplied");rm(e);let u=document.body.querySelector(".vuuPopup."+t);u===null&&(u=document.createElement("div"),u.className="vuuPopup "+t,document.body.appendChild(u));let h={width:l};_r((0,Zi.createElement)(sm,{key:om++,position:i,style:h},a),u,r,o,()=>{Ai.keepWithinThePage(u,s)})}static hidePopup(e="anon",t="all"){if(tt.indexOf(e)!==-1){Ru(e);let i=document.body.querySelector(`.vuuPopup.${t}`);i&&qr.default.unmountComponentAtNode(i)}}static keepWithinThePage(e,t="auto"){let i=e.querySelector(".vuuPopupContainer > *");if(i){let{top:r,left:s,width:o,height:l,right:a}=i.getBoundingClientRect(),u=window.innerWidth,c=window.innerHeight-(r+l);c<0&&(i.style.top=Math.round(r)+c+"px");let f=u-(s+o);if(f<0&&(i.style.left=Math.round(s)+f+"px"),typeof t=="number"&&t!==a){let d=t-a;i.style.left=s+d+"px"}}}};var Gr=require("react/jsx-runtime"),en=()=>{let n=(0,Qn.useContext)(Kr),e=(0,Qn.useCallback)((i,r,s)=>{let o=[];for(let l of i)o=o.concat(l(r,s));return o},[]);return(0,Qn.useCallback)((i,r,s)=>{var a;i.stopPropagation(),i.preventDefault();let o=(a=n==null?void 0:n.menuBuilders)!=null?a:[],l=e(o,r,s);console.log({menuItemDescriptors:l}),l.length&&(n!=null&&n.menuActionHandler)&&(console.log(`showContextMenu ${r}`,{options:s}),lm(i,l,n.menuActionHandler))},[e,n])},lm=(n,e,t)=>{let{clientX:i,clientY:r}=n,l=(0,Gr.jsx)(bo,{onClose:(a,u)=>{a&&(t(a,u),Ai.hidePopup())},position:{x:i,y:r},children:(a=>{let u=(h,c)=>yo(h)?(0,Gr.jsx)(zr,{label:h.label,children:h.children.map(u)},c):(0,Gr.jsx)(mo,{action:h.action,"data-icon":h.icon,options:h.options,children:h.label},c);return a.map(u)})(e)});Ai.showPopup({left:0,top:0,component:l})};var lo=require("@salt-ds/core");var qu=require("@vuu-ui/vuu-utils"),Gu=require("react"),ju=ue(require("classnames"));var it=require("@vuu-ui/vuu-utils"),Lu=ue(require("classnames")),Yn=require("react");var jr=require("@vuu-ui/vuu-utils"),Au=require("@heswell/salt-lab"),Pu=ue(require("classnames")),Ot=require("react");var Xn=require("react/jsx-runtime"),{KEY:Du}=jr.metadataKeys,vo=(0,Ot.memo)(({className:n,column:e,onClick:t,row:i})=>{let r=(0,Ot.useRef)(null),{align:s,CellRenderer:o,key:l,pin:a,editable:u,resizing:h,valueFormatter:c}=e,[f,d]=(0,Ot.useState)(!1),p=c(i[l]),[m,g]=(0,Ot.useState)(p),b=()=>{var L;(L=r.current)==null||L.focus()},C=L=>{L.key==="Enter"&&d(!0)},y=(0,Ot.useCallback)(()=>{t==null||t(e)},[e,t]),x=()=>{d(!0)},v=(L="",E="",S=!0,R=!1)=>{var O;d(!1),R?g(L):E!==L&&g(E),S===!1&&((O=r.current)==null||O.focus())},w=(0,Pu.default)(n,{vuuAlignRight:s==="right",vuuPinFloating:a==="floating",vuuPinLeft:a==="left",vuuPinRight:a==="right","vuuTableCell-resizing":h})||void 0,M=(0,jr.getColumnPinStyle)(e);return u?(0,Xn.jsx)("td",{className:w,"data-editable":!0,style:M,onKeyDown:C,children:(0,Xn.jsx)(Au.EditableLabel,{editing:f,value:m,onChange:g,onMouseDownCapture:b,onEnterEditMode:x,onExitEditMode:v,onKeyDown:C,ref:r,tabIndex:0},"title")}):(0,Xn.jsx)("td",{className:w,style:M,onClick:y,children:o?(0,Xn.jsx)(o,{column:e,row:i}):p})},am);vo.displayName="TableCell";function am(n,e){return n.column===e.column&&n.onClick===e.onClick&&n.row[Du]===e.row[Du]&&n.row[n.column.key]===e.row[e.column.key]}var Eu=require("@vuu-ui/vuu-utils"),Ou=require("react");var tn=require("react/jsx-runtime"),{DEPTH:um,IS_LEAF:Iu}=Eu.metadataKeys,hm=(n,e)=>{let{[um]:t,[Iu]:i}=e;if(i||t>n.length)return[null,t===null?0:t-1];if(t===0)return["$root",0];{let r=n[t-1];return[e[r.key],t-1]}},Vu=({column:n,onClick:e,row:t})=>{let{columns:i}=n,[r,s]=hm(i,t),o=(0,Ou.useCallback)(()=>{e==null||e(n)},[n,e]),l={left:n.pin=="left"?n.pinnedOffset:void 0},a=t[Iu],u=Array(s).fill(0).map((h,c)=>(0,tn.jsx)("span",{className:"vuuTableGroupCell-spacer"},c));return(0,tn.jsxs)("td",{className:"vuuTableGroupCell vuuPinLeft",onClick:a?void 0:o,style:l,children:[u,a?null:(0,tn.jsx)("span",{className:"vuuTableGroupCell-toggle","data-icon":"triangle-right"}),(0,tn.jsx)("span",{children:r})]})};var Zn=require("react/jsx-runtime"),{IDX:cm,IS_EXPANDED:fm,SELECTED:dm}=it.metadataKeys,Jr="vuuTableRow",Qr=(0,Yn.memo)(function({columns:e,height:t,index:i,onClick:r,onToggleGroup:s,virtualColSpan:o=0,row:l}){let{[cm]:a,[fm]:u,[dm]:h}=l,c=(0,Lu.default)(Jr,{[`${Jr}-even`]:a%2===0,[`${Jr}-expanded`]:u,[`${Jr}-preSelected`]:h===2}),f=a-i,d=(0,Yn.useCallback)(m=>{let g=m.shiftKey,b=m.ctrlKey||m.metaKey;r==null||r(l,g,b)},[r,l]),p=(0,Yn.useCallback)(m=>{((0,it.isGroupColumn)(m)||(0,it.isJsonGroup)(m,l))&&(s==null||s(l,m))},[s,l]);return(0,Zn.jsxs)("tr",{"aria-selected":h===1?!0:void 0,"aria-rowindex":a,className:c,onClick:d,style:{transform:`translate(0px, ${f*t}px)`},children:[o>0?(0,Zn.jsx)("td",{colSpan:o}):null,e.filter(it.notHidden).map(m=>{let g=(0,it.isGroupColumn)(m),b=(0,it.isJsonColumn)(m);return(0,Zn.jsx)(g?Vu:vo,{column:m,onClick:g||b?p:void 0,row:l},m.name)})]})});var $u=ue(require("classnames")),Oi=require("react");var nn=require("react");var Bu=require("react/jsx-runtime"),Nu=()=>{},pm="vuuColumnResizer",Xr=({onDrag:n,onDragEnd:e=Nu,onDragStart:t=Nu})=>{let i=(0,nn.useRef)(0),r=(0,nn.useCallback)(l=>{l.stopPropagation&&l.stopPropagation(),l.preventDefault&&l.preventDefault();let a=Math.round(l.clientX),u=a-i.current;i.current=a,u!==0&&n(l,u)},[n]),s=(0,nn.useCallback)(l=>{window.removeEventListener("mouseup",s),window.removeEventListener("mousemove",r),e(l)},[e,r]),o=(0,nn.useCallback)(l=>{t(l),i.current=Math.round(l.clientX),window.addEventListener("mouseup",s),window.addEventListener("mousemove",r),l.stopPropagation&&l.stopPropagation(),l.preventDefault&&l.preventDefault()},[t,r,s]);return(0,Bu.jsx)("div",{className:pm,onMouseDown:o})};var Co=ue(require("classnames"));var Pi=require("react/jsx-runtime"),Fu="vuuSortIndicator",Hu=({sorted:n})=>{if(!n)return null;let e=typeof n=="number"?n<0?"dsc":"asc":n==="A"?"asc":"dsc";return typeof n=="number"?(0,Pi.jsxs)("div",{className:(0,Co.default)(Fu,"multi-col",e),children:[(0,Pi.jsx)("span",{"data-icon":`sorted-${e}`}),(0,Pi.jsx)("span",{className:"vuuSortPosition",children:Math.abs(n)})]}):(0,Pi.jsx)("div",{className:(0,Co.default)(Fu,"single-col"),children:(0,Pi.jsx)("span",{"data-icon":`sorted-${e}`})})};var Ei=require("react"),Yr=({column:n,onResize:e,rootRef:t})=>{let i=(0,Ei.useRef)(0),r=(0,Ei.useRef)(!1),{name:s}=n,o=(0,Ei.useCallback)(()=>{if(e&&t.current){let{width:u}=t.current.getBoundingClientRect();i.current=Math.round(u),r.current=!0,e==null||e("begin",s)}},[s,e,t]),l=(0,Ei.useCallback)((u,h)=>{if(t.current&&e){let{width:c}=t.current.getBoundingClientRect(),f=Math.round(c)+h;f!==i.current&&f>0&&(e("resize",s,f),i.current=f)}},[s,e,t]),a=(0,Ei.useCallback)(()=>{e&&(e("end",s,i.current),setTimeout(()=>{r.current=!1},100))},[s,e]);return{isResizing:r.current,onDrag:l,onDragStart:o,onDragEnd:a}};var Wu=ue(require("classnames")),_u=require("react");var Uu=require("react/jsx-runtime");var zu=({column:n,filter:e})=>{let t=en(),i=(0,_u.useCallback)(r=>{r.stopPropagation(),t(r,"filter",{column:n,filter:e})},[n,e,t]);return n.filter?(0,Uu.jsx)("div",{className:(0,Wu.default)("vuuFilterIndicator"),"data-icon":"filter",onClick:i}):null};var Qt=require("react/jsx-runtime"),er="vuuTable-headerCell",Zr=({column:n,className:e,onClick:t,onDragStart:i,onResize:r,...s})=>{let o=(0,Oi.useRef)(null),{isResizing:l,...a}=Yr({column:n,onResize:r,rootRef:o}),u=en(),h=(0,Oi.useRef)(null),c=g=>{u(g,"header",{column:n})},f=(0,Oi.useCallback)(g=>!l&&(t==null?void 0:t(g)),[l,t]),d=(0,Oi.useCallback)(g=>{h.current=window.setTimeout(()=>{i==null||i(g),h.current=null},250)},[i]),p=(0,Oi.useCallback)(()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null)},[]),m=(0,$u.default)(er,e,{vuuPinFloating:n.pin==="floating",vuuPinLeft:n.pin==="left",vuuPinRight:n.pin==="right",vuuEndPin:n.endPin,[`${er}-resizing`]:n.resizing,[`${er}-right`]:n.align==="right"});return(0,Qt.jsx)("th",{className:m,...s,onClick:f,onContextMenu:c,onMouseDown:d,onMouseUp:p,ref:o,children:(0,Qt.jsxs)("div",{className:`${er}-inner`,children:[(0,Qt.jsx)(zu,{column:n}),(0,Qt.jsx)("div",{className:`${er}-label`,children:n.label}),(0,Qt.jsx)(Hu,{sorted:n.sorted}),n.resizeable!==!1?(0,Qt.jsx)(Xr,{...a}):null]})})};var nt=require("react/jsx-runtime"),Ku="vuuTable",{RENDER_IDX:mm}=qu.metadataKeys,Ju=({columns:n,data:e,headerHeight:t,onHeaderCellDragEnd:i,rowHeight:r})=>{let s=(0,Gu.useCallback)(()=>{i==null||i()},[i]);return console.log("ColumnBasedTable render"),(0,nt.jsx)(nt.Fragment,{children:n.map((o,l)=>(0,nt.jsx)("table",{className:(0,ju.default)(`${Ku}-table`,`${Ku}-columnBased`,{vuuPinLeft:o.pin==="left"}),"data-idx":l,id:`col-${l}`,style:{width:o.width,left:o.pinnedOffset,"--vuuTableHeaderHeight":`${t}px`,"--row-height":`${r}px`},children:(0,nt.jsxs)("tbody",{children:[(0,nt.jsx)("tr",{children:(0,nt.jsx)(Zr,{column:o,"data-idx":l,onDragEnd:s},l)},"header"),e.map((a,u)=>(0,nt.jsx)(Qr,{columns:[o],height:r,index:u,row:a},a[mm])),(0,nt.jsx)("tr",{className:"vuuTable-filler"})]})},o.name))})};var Qu=require("@vuu-ui/vuu-utils"),Xu=n=>(e,t)=>{let i=[];if(n===void 0)return i;if(e==="header")i.push(...gm(t,n)),i.push(...wm(t,n)),i.push(...bm(t,n)),i.push(...ym(t));else if(e==="filter"){let{column:r,filter:s}=t,o=(s==null?void 0:s.column)===(r==null?void 0:r.name);i.push({label:"Edit filter",action:"filter-edit",options:t}),i.push({label:"Remove filter",action:"filter-remove-column",options:t}),r&&!o&&i.push({label:"Remove all filters",action:"remove-filters",options:t})}return i};function gm(n,{sort:{sortDefs:e}}){let{column:t}=n,i=[];if(t===void 0)return i;let r=e.length>0;return t.sorted==="A"?i.push({label:"Reverse Sort (DSC)",action:"sort-dsc",options:n}):t.sorted==="D"?i.push({label:"Reverse Sort (ASC)",action:"sort-asc",options:n}):typeof t.sorted=="number"?(t.sorted>0?i.push({label:"Reverse Sort (DSC)",action:"sort-add-dsc",options:n}):i.push({label:"Reverse Sort (ASC)",action:"sort-add-asc",options:n}),r&&Math.abs(t.sorted)<e.length&&i.push({label:"Remove from sort",action:"sort-remove",options:n}),i.push({label:"New Sort",children:[{label:"Ascending",action:"sort-asc",options:n},{label:"Descending",action:"sort-dsc",options:n}]})):r?(i.push({label:"Add to sort",children:[{label:"Ascending",action:"sort-add-asc",options:n},{label:"Descending",action:"sort-add-dsc",options:n}]}),i.push({label:"New Sort",children:[{label:"Ascending",action:"sort-asc",options:n},{label:"Descending",action:"sort-dsc",options:n}]})):i.push({label:"Sort",children:[{label:"Ascending",action:"sort-asc",options:n},{label:"Descending",action:"sort-dsc",options:n}]}),i}function bm(n,e){let{column:t}=n;if(t===void 0||e.groupBy.length===0)return[];let{name:i,label:r=i}=t;return[{label:`Aggregate ${r}`,children:[{label:"Count",action:"agg-count",options:n}].concat((0,Qu.isNumericColumn)(t)?[{label:"Sum",action:"agg-sum",options:n},{label:"Avg",action:"agg-avg",options:n},{label:"High",action:"agg-high",options:n},{label:"Low",action:"agg-low",options:n}]:[])}]}var Mo=(n,e)=>({label:`Pin ${e}`,action:`column-pin-${e}`,options:n}),So=n=>Mo(n,"left"),xo=n=>Mo(n,"floating"),ko=n=>Mo(n,"right");function ym(n){let{column:e}=n;if(e===void 0)return[];let{pin:t}=e,i=[{label:"Hide column",action:"column-hide",options:n},{label:"Remove column",action:"column-remove",options:n}];return t===void 0?i.push({label:"Pin column",children:[So(n),xo(n),ko(n)]}):t==="left"?i.push({label:"Unpin column",action:"column-unpin",options:n},{label:"Pin column",children:[xo(n),ko(n)]}):t==="right"?i.push({label:"Unpin column",action:"column-unpin",options:n},{label:"Pin column",children:[So(n),xo(n)]}):t==="floating"&&i.push({label:"Unpin column",action:"column-unpin",options:n},{label:"Pin column",children:[So(n),ko(n)]}),i}function wm(n,{groupBy:e}){let{column:t}=n,i=[];if(t===void 0)return i;let{name:r,label:s=r}=t;return e.length===0?i.push({label:`Group by ${s}`,action:"group",options:n}):i.push({label:`Add ${s} to group by`,action:"group-add",options:n}),i}var iy=require("@salt-ds/core");var _=class{constructor(){}lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),Ue.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){let i=[];return this.decompose(e,t,i,0),Ue.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new Li(this),s=new Li(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new Li(this,e)}iterRange(e,t=this.length){return new ns(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new rs(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?_.empty:e.length<=32?new ie(e):Ue.from(ie.split(e,[]))}},ie=class extends _{constructor(e,t=vm(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new Ro(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ie(Yu(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=is(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new ie(l,o.length+s.length));else{let a=l.length>>1;i.push(new ie(l.slice(0,a)),new ie(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ie))return super.replace(e,t,i);let r=is(this.text,is(i.text,Yu(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ie(r,s):Ue.from(ie.split(r,[]),s)}sliceString(e,t=this.length,i=`
2
- `){let r="";for(let s=0,o=0;s<=t&&o<this.text.length;o++){let l=this.text[o],a=s+l.length;s>e&&o&&(r+=i),e<a&&t>s&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ie(i,r)),i=[],r=-1);return r>-1&&t.push(new ie(i,r)),t}},Ue=class extends _{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s<this.children.length;s++){let l=this.children[s],a=o+l.length;if(e<=a&&t>=o){let u=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!u?i.push(l):l.decompose(e-o,t-o,i,u)}o=a+1}}replace(e,t,i){if(i.lines<this.lines)for(let r=0,s=0;r<this.children.length;r++){let o=this.children[r],l=s+o.length;if(e>=s&&t<=l){let a=o.replace(e-s,t-s,i),u=this.lines-o.lines+a.lines;if(a.lines<u>>5-1&&a.lines>u>>5+1){let h=this.children.slice();return h[r]=a,new Ue(h,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=`
3
- `){let r="";for(let s=0,o=0;s<this.children.length&&o<=t;s++){let l=this.children[s],a=o+l.length;o>e&&s&&(r+=i),e<a&&t>o&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof Ue))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],u=e.children[s];if(a!=u)return i+a.scanIdentical(u,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let d of e)i+=d.lines;if(i<32){let d=[];for(let p of e)p.flatten(d);return new ie(d,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,u=-1,h=[];function c(d){let p;if(d.lines>s&&d instanceof Ue)for(let m of d.children)c(m);else d.lines>o&&(a>o||!a)?(f(),l.push(d)):d instanceof ie&&a&&(p=h[h.length-1])instanceof ie&&d.lines+p.lines<=32?(a+=d.lines,u+=d.length+1,h[h.length-1]=new ie(p.text.concat(d.text),p.length+1+d.length)):(a+d.lines>r&&f(),a+=d.lines,u+=d.length+1,h.push(d))}function f(){a!=0&&(l.push(h.length==1?h[0]:Ue.from(h,u)),u=-1,a=h.length=0)}for(let d of e)c(d);return f(),l.length==1?l[0]:new Ue(l,t)}};_.empty=new ie([""],0);function vm(n){let e=-1;for(let t of n)e+=t.length+1;return e}function is(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s<n.length&&r<=i;s++){let l=n[s],a=r+l.length;a>=t&&(a>i&&(l=l.slice(0,i-r)),r<t&&(l=l.slice(t-r)),o?(e[e.length-1]+=l,o=!1):e.push(l)),r=a+1}return e}function Yu(n,e,t){return is(n,[""],e,t)}var Li=class{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[e],this.offsets=[t>0?1:(e instanceof ie?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof ie?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=`
4
- `,this;e--}else if(r instanceof ie){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ie?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},ns=class{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new Li(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}},rs=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(_.prototype[Symbol.iterator]=function(){return this.iter()},Li.prototype[Symbol.iterator]=ns.prototype[Symbol.iterator]=rs.prototype[Symbol.iterator]=function(){return this});var Ro=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}},rn="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(n=>n?parseInt(n,36):1);for(let n=1;n<rn.length;n++)rn[n]+=rn[n-1];function Cm(n){for(let e=1;e<rn.length;e+=2)if(rn[e]>n)return rn[e-1]<=n;return!1}function Zu(n){return n>=127462&&n<=127487}var eh=8205;function De(n,e,t=!0,i=!0){return(t?oh:Sm)(n,e,i)}function oh(n,e,t){if(e==n.length)return e;e&&lh(n.charCodeAt(e))&&ah(n.charCodeAt(e-1))&&e--;let i=sn(n,e);for(e+=ss(i);e<n.length;){let r=sn(n,e);if(i==eh||r==eh||t&&Cm(r))e+=ss(r),i=r;else if(Zu(r)){let s=0,o=e-2;for(;o>=0&&Zu(sn(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function Sm(n,e,t){for(;e>0;){let i=oh(n,e-2,t);if(i<e)return i;e--}return 0}function lh(n){return n>=56320&&n<57344}function ah(n){return n>=55296&&n<56320}function sn(n,e){let t=n.charCodeAt(e);if(!ah(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return lh(i)?(t-55296<<10)+(i-56320)+65536:t}function ss(n){return n<65536?1:2}var Do=/\r\n?|\n/,Pe=function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n}(Pe||(Pe={})),Ne=class{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let i=this.sections[t+1];e+=i<0?this.sections[t]:i}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,i=0,r=0;t<this.sections.length;){let s=this.sections[t++],o=this.sections[t++];o<0?(e(i,r,s),r+=s):r+=o,i+=s}}iterChangedRanges(e,t=!1){Ao(this,e,t)}get invertedDesc(){let e=[];for(let t=0;t<this.sections.length;){let i=this.sections[t++],r=this.sections[t++];r<0?e.push(i,r):e.push(r,i)}return new Ne(e)}composeDesc(e){return this.empty?e:e.empty?this:uh(this,e)}mapDesc(e,t=!1){return e.empty?this:Po(this,e,t)}mapPos(e,t=-1,i=Pe.Simple){let r=0,s=0;for(let o=0;o<this.sections.length;){let l=this.sections[o++],a=this.sections[o++],u=r+l;if(a<0){if(u>e)return s+(e-r);s+=l}else{if(i!=Pe.Simple&&u>=e&&(i==Pe.TrackDel&&r<e&&u>e||i==Pe.TrackBefore&&r<e||i==Pe.TrackAfter&&u>e))return null;if(u>e||u==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=u}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i<this.sections.length&&r<=t;){let s=this.sections[i++],o=this.sections[i++],l=r+s;if(o>=0&&r<=t&&l>=e)return r<e&&l>t?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t<this.sections.length;){let i=this.sections[t++],r=this.sections[t++];e+=(e?" ":"")+i+(r>=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new Ne(e)}static create(e){return new Ne(e)}},ne=class extends Ne{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ao(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Po(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r<t.length;r+=2){let o=t[r],l=t[r+1];if(l>=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length<a;)i.push(_.empty);i.push(o?e.slice(s,s+o):_.empty)}s+=o}return new ne(t,i)}compose(e){return this.empty?e:e.empty?this:uh(this,e,!0)}map(e,t=!1){return e.empty?this:Po(this,e,t,!0)}iterChanges(e,t=!1){Ao(this,e,t)}get desc(){return Ne.create(this.sections)}filter(e){let t=[],i=[],r=[],s=new Ni(this);e:for(let o=0,l=0;;){let a=o==e.length?1e9:e[o++];for(;l<a||l==a&&s.len==0;){if(s.done)break e;let h=Math.min(s.len,a-l);Me(r,h,-1);let c=s.ins==-1?-1:s.off==0?s.ins:0;Me(t,h,c),c>0&&Xt(i,t,s.text),s.forward(h),l+=h}let u=e[o++];for(;l<u;){if(s.done)break e;let h=Math.min(s.len,u-l);Me(t,h,-1),Me(r,h,s.ins==-1?-1:s.off==0?s.ins:0),s.forward(h),l+=h}}return{changes:new ne(t,i),filtered:Ne.create(r)}}toJSON(){let e=[];for(let t=0;t<this.sections.length;t+=2){let i=this.sections[t],r=this.sections[t+1];r<0?e.push(i):r==0?e.push([i]):e.push([i].concat(this.inserted[t>>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,l=null;function a(h=!1){if(!h&&!r.length)return;o<t&&Me(r,t-o,-1);let c=new ne(r,s);l=l?l.compose(c.map(l)):c,r=[],s=[],o=0}function u(h){if(Array.isArray(h))for(let c of h)u(c);else if(h instanceof ne){if(h.length!=t)throw new RangeError(`Mismatched change set length (got ${h.length}, expected ${t})`);a(),l=l?l.compose(h.map(l)):h}else{let{from:c,to:f=c,insert:d}=h;if(c>f||c<0||f>t)throw new RangeError(`Invalid change range ${c} to ${f} (in doc of length ${t})`);let p=d?typeof d=="string"?_.of(d.split(i||Do)):d:_.empty,m=p.length;if(c==f&&m==0)return;c<o&&a(),c>o&&Me(r,c-o,-1),Me(r,f-c,m),Xt(s,r,p),o=f}}return u(e),a(!l),l}static empty(e){return new ne(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;r<e.length;r++){let s=e[r];if(typeof s=="number")t.push(s,-1);else{if(!Array.isArray(s)||typeof s[0]!="number"||s.some((o,l)=>l&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length<r;)i.push(_.empty);i[r]=_.of(s.slice(1)),t.push(s[0],i[r].length)}}}return new ne(t,i)}static createSet(e,t){return new ne(e,t)}};function Me(n,e,t,i=!1){if(e==0&&t<=0)return;let r=n.length-2;r>=0&&t<=0&&t==n[r+1]?n[r]+=e:e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function Xt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i<n.length)n[n.length-1]=n[n.length-1].append(t);else{for(;n.length<i;)n.push(_.empty);n.push(t)}}function Ao(n,e,t){let i=n.inserted;for(let r=0,s=0,o=0;o<n.sections.length;){let l=n.sections[o++],a=n.sections[o++];if(a<0)r+=l,s+=l;else{let u=r,h=s,c=_.empty;for(;u+=l,h+=a,a&&i&&(c=c.append(i[o-2>>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(r,u,s,h,c),r=u,s=h}}}function Po(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Ni(n),l=new Ni(e);for(let a=-1;;)if(o.ins==-1&&l.ins==-1){let u=Math.min(o.len,l.len);Me(r,u,-1),o.forward(u),l.forward(u)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len<o.len||l.len==o.len&&!t))){let u=l.len;for(Me(r,l.ins,-1);u;){let h=Math.min(o.len,u);o.ins>=0&&a<o.i&&o.len<=h&&(Me(r,0,o.ins),s&&Xt(s,r,o.text),a=o.i),o.forward(h),u-=h}l.next()}else if(o.ins>=0){let u=0,h=o.len;for(;h;)if(l.ins==-1){let c=Math.min(h,l.len);u+=c,h-=c,l.forward(c)}else if(l.ins==0&&l.len<h)h-=l.len,l.next();else break;Me(r,u,a<o.i?o.ins:0),s&&a<o.i&&Xt(s,r,o.text),a=o.i,o.forward(o.len-h)}else{if(o.done&&l.done)return s?ne.createSet(r,s):Ne.create(r);throw new Error("Mismatched change set lengths")}}function uh(n,e,t=!1){let i=[],r=t?[]:null,s=new Ni(n),o=new Ni(e);for(let l=!1;;){if(s.done&&o.done)return r?ne.createSet(i,r):Ne.create(i);if(s.ins==0)Me(i,s.len,0,l),s.next();else if(o.len==0&&!o.done)Me(i,0,o.ins,l),r&&Xt(r,i,o.text),o.next();else{if(s.done||o.done)throw new Error("Mismatched change set lengths");{let a=Math.min(s.len2,o.len),u=i.length;if(s.ins==-1){let h=o.ins==-1?-1:o.off?0:o.ins;Me(i,a,h,l),r&&h&&Xt(r,i,o.text)}else o.ins==-1?(Me(i,s.off?0:s.len,a,l),r&&Xt(r,i,s.textBit(a))):(Me(i,s.off?0:s.len,o.off?0:o.ins,l),r&&!o.off&&Xt(r,i,o.text));l=(s.ins>a||o.ins>=0&&o.len>a)&&(l||i.length>u),s.forward2(a),o.forward(a)}}}}var Ni=class{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i<e.length?(this.len=e[this.i++],this.ins=e[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return this.ins==-2}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted:e}=this.set,t=this.i-2>>1;return t>=e.length?_.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?_.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}},It=class{constructor(e,t,i){this.from=e,this.to=t,this.flags=i}get anchor(){return this.flags&16?this.to:this.from}get head(){return this.flags&16?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&4?-1:this.flags&8?1:0}get bidiLevel(){let e=this.flags&3;return e==3?null:e}get goalColumn(){let e=this.flags>>5;return e==33554431?void 0:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new It(i,r,this.flags)}extend(e,t=e){if(e<=this.anchor&&t>=this.anchor)return T.range(e,t);let i=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return T.range(this.anchor,i)}eq(e){return this.anchor==e.anchor&&this.head==e.head}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return T.range(e.anchor,e.head)}static create(e,t,i){return new It(e,t,i)}},T=class{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:T.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let t=0;t<this.ranges.length;t++)if(!this.ranges[t].eq(e.ranges[t]))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return this.ranges.length==1?this:new T([this.main],0)}addRange(e,t=!0){return T.create([e].concat(this.ranges),t?0:this.mainIndex+1)}replaceRange(e,t=this.mainIndex){let i=this.ranges.slice();return i[t]=e,T.create(i,this.mainIndex)}toJSON(){return{ranges:this.ranges.map(e=>e.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new T(e.ranges.map(t=>It.fromJSON(t)),e.main)}static single(e,t=e){return new T([T.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;r<e.length;r++){let s=e[r];if(s.empty?s.from<=i:s.from<i)return T.normalized(e.slice(),t);i=s.to}return new T(e,t)}static cursor(e,t=0,i,r){return It.create(e,e,(t==0?0:t<0?4:8)|(i==null?3:Math.min(2,i))|(r!=null?r:33554431)<<5)}static range(e,t,i,r){let s=(i!=null?i:33554431)<<5|(r==null?3:Math.min(2,r));return t<e?It.create(t,e,24|s):It.create(e,t,(t>e?4:0)|s)}static normalized(e,t=0){let i=e[t];e.sort((r,s)=>r.from-s.from),t=e.indexOf(i);for(let r=1;r<e.length;r++){let s=e[r],o=e[r-1];if(s.empty?s.from<=o.to:s.from<o.to){let l=o.from,a=Math.max(s.to,o.to);r<=t&&t--,e.splice(--r,2,s.anchor>s.head?T.range(a,l):T.range(l,a))}}return new T(e,t)}};function hh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}var Fo=0,N=class{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=Fo++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}static define(e={}){return new N(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Ho),!!e.static,e.enables)}of(e){return new on([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new on(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new on(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}};function Ho(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}var on=class{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=Fo++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,l=this.type==2,a=!1,u=!1,h=[];for(let c of this.dependencies)c=="doc"?a=!0:c=="selection"?u=!0:((t=e[c.id])!==null&&t!==void 0?t:1)&1||h.push(e[c.id]);return{create(c){return c.values[o]=i(c),1},update(c,f){if(a&&f.docChanged||u&&(f.docChanged||f.selection)||Eo(c,h)){let d=i(c);if(l?!th(d,c.values[o],r):!r(d,c.values[o]))return c.values[o]=d,1}return 0},reconfigure:(c,f)=>{let d,p=f.config.address[s];if(p!=null){let m=ls(f,p);if(this.dependencies.every(g=>g instanceof N?f.facet(g)===c.facet(g):g instanceof Be?f.field(g,!1)==c.field(g,!1):!0)||(l?th(d=i(c),m,r):r(d=i(c),m)))return c.values[o]=m,0}else d=i(c);return c.values[o]=d,1}}}};function th(n,e,t){if(n.length!=e.length)return!1;for(let i=0;i<n.length;i++)if(!t(n[i],e[i]))return!1;return!0}function Eo(n,e){let t=!1;for(let i of e)ir(n,i)&1&&(t=!0);return t}function xm(n,e,t){let i=t.map(a=>n[a.id]),r=t.map(a=>a.type),s=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let u=[];for(let h=0;h<i.length;h++){let c=ls(a,i[h]);if(r[h]==2)for(let f of c)u.push(f);else u.push(c)}return e.combine(u)}return{create(a){for(let u of i)ir(a,u);return a.values[o]=l(a),1},update(a,u){if(!Eo(a,s))return 0;let h=l(a);return e.compare(h,a.values[o])?0:(a.values[o]=h,1)},reconfigure(a,u){let h=Eo(a,i),c=u.config.facets[e.id],f=u.facet(e);if(c&&!h&&Ho(t,c))return a.values[o]=f,0;let d=l(a);return e.compare(d,f)?(a.values[o]=f,0):(a.values[o]=d,1)}}}var ih=N.define({static:!0}),Be=class{constructor(e,t,i,r,s){this.id=e,this.createF=t,this.updateF=i,this.compareF=r,this.spec=s,this.provides=void 0}static define(e){let t=new Be(Fo++,e.create,e.update,e.compare||((i,r)=>i===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(ih).find(i=>i.field==this);return((t==null?void 0:t.create)||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}init(e){return[this,ih.of({field:this,create:e})]}get extension(){return this}},Ii={lowest:4,low:3,default:2,high:1,highest:0};function tr(n){return e=>new os(e,n)}var hn={highest:tr(Ii.highest),high:tr(Ii.high),default:tr(Ii.default),low:tr(Ii.low),lowest:tr(Ii.lowest)},os=class{constructor(e,t){this.inner=e,this.prec=t}},an=class{of(e){return new nr(this,e)}reconfigure(e){return an.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}},nr=class{constructor(e,t){this.compartment=e,this.inner=t}},un=class{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length<i.length;)this.statusTemplate.push(0)}staticFacet(e){let t=this.address[e.id];return t==null?e.default:this.staticValues[t>>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let f of km(e,t,o))f instanceof Be?r.push(f):(s[f.facet.id]||(s[f.facet.id]=[])).push(f);let l=Object.create(null),a=[],u=[];for(let f of r)l[f.id]=u.length<<1,u.push(d=>f.slot(d));let h=i==null?void 0:i.config.facets;for(let f in s){let d=s[f],p=d[0].facet,m=h&&h[f]||[];if(d.every(g=>g.type==0))if(l[p.id]=a.length<<1|1,Ho(m,d))a.push(i.facet(p));else{let g=p.combine(d.map(b=>b.value));a.push(i&&p.compare(g,i.facet(p))?i.facet(p):g)}else{for(let g of d)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=u.length<<1,u.push(b=>g.dynamicSlot(b)));l[p.id]=u.length<<1,u.push(g=>xm(g,p,d))}}let c=u.map(f=>f(l));return new un(e,o,c,l,a,s)}};function km(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,l){let a=r.get(o);if(a!=null){if(a<=l)return;let u=i[a].indexOf(o);u>-1&&i[a].splice(u,1),o instanceof nr&&t.delete(o.compartment)}if(r.set(o,l),Array.isArray(o))for(let u of o)s(u,l);else if(o instanceof nr){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let u=e.get(o.compartment)||o.inner;t.set(o.compartment,u),s(u,l)}else if(o instanceof os)s(o.inner,o.prec);else if(o instanceof Be)i[l].push(o),o.provides&&s(o.provides,l);else if(o instanceof on)i[l].push(o),o.facet.extensions&&s(o.facet.extensions,Ii.default);else{let u=o.extension;if(!u)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(u,l)}}return s(n,Ii.default),i.reduce((o,l)=>o.concat(l))}function ir(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function ls(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}var ch=N.define(),fh=N.define({combine:n=>n.some(e=>e),static:!0}),dh=N.define({combine:n=>n.length?n[0]:void 0,static:!0}),ph=N.define(),mh=N.define(),gh=N.define(),bh=N.define({combine:n=>n.length?n[0]:!1}),$e=class{constructor(e,t){this.type=e,this.value=t}static define(){return new Oo}},Oo=class{of(e){return new $e(this,e)}},Io=class{constructor(e){this.map=e}of(e){return new ee(this,e)}},ee=class{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new ee(this.type,t)}is(e){return this.type==e}static define(e={}){return new Io(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}};ee.reconfigure=ee.define();ee.appendConfig=ee.define();var re=class{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&hh(i,t.newLength),s.some(l=>l.type==re.time)||(this.annotations=s.concat(re.time.of(Date.now())))}static create(e,t,i,r,s,o){return new re(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(re.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}};re.time=$e.define();re.userEvent=$e.define();re.addToHistory=$e.define();re.remote=$e.define();function Mm(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i<n.length&&(r==e.length||e[r]>=n[i]))s=n[i++],o=n[i++];else if(r<e.length)s=e[r++],o=e[r++];else return t;!t.length||t[t.length-1]<s?t.push(s,o):t[t.length-1]<o&&(t[t.length-1]=o)}}function yh(n,e,t){var i;let r,s,o;return t?(r=e.changes,s=ne.empty(e.changes.length),o=n.changes.compose(e.changes)):(r=e.changes.map(n.changes),s=n.changes.mapDesc(e.changes,!0),o=n.changes.compose(r)),{changes:o,selection:e.selection?e.selection.map(s):(i=n.selection)===null||i===void 0?void 0:i.map(r),effects:ee.mapEffects(n.effects,r).concat(ee.mapEffects(e.effects,s)),annotations:n.annotations.length?n.annotations.concat(e.annotations):e.annotations,scrollIntoView:n.scrollIntoView||e.scrollIntoView}}function Vo(n,e,t){let i=e.selection,r=ln(e.annotations);return e.userEvent&&(r=r.concat(re.userEvent.of(e.userEvent))),{changes:e.changes instanceof ne?e.changes:ne.of(e.changes||[],t,n.facet(dh)),selection:i&&(i instanceof T?i:T.single(i.anchor,i.head)),effects:ln(e.effects),annotations:r,scrollIntoView:!!e.scrollIntoView}}function wh(n,e,t){let i=Vo(n,e.length?e[0]:{},n.doc.length);e.length&&e[0].filter===!1&&(t=!1);for(let s=1;s<e.length;s++){e[s].filter===!1&&(t=!1);let o=!!e[s].sequential;i=yh(i,Vo(n,e[s],o?i.changes.newLength:n.doc.length),o)}let r=re.create(n,i.changes,i.selection,i.effects,i.annotations,i.scrollIntoView);return Rm(t?Tm(r):r)}function Tm(n){let e=n.startState,t=!0;for(let r of e.facet(ph)){let s=r(n);if(s===!1){t=!1;break}Array.isArray(s)&&(t=t===!0?s:Mm(t,s))}if(t!==!0){let r,s;if(t===!1)s=n.changes.invertedDesc,r=ne.empty(e.doc.length);else{let o=n.changes.filter(t);r=o.changes,s=o.filtered.mapDesc(o.changes).invertedDesc}n=re.create(e,r,n.selection&&n.selection.map(s),ee.mapEffects(n.effects,s),n.annotations,n.scrollIntoView)}let i=e.facet(mh);for(let r=i.length-1;r>=0;r--){let s=i[r](n);s instanceof re?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof re?n=s[0]:n=wh(e,ln(s),!1)}return n}function Rm(n){let e=n.startState,t=e.facet(gh),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=yh(i,Vo(e,s,n.changes.newLength),!0))}return i==n?n:re.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}var Dm=[];function ln(n){return n==null?Dm:Array.isArray(n)?n:[n]}var rt=function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n}(rt||(rt={})),Am=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Lo;try{Lo=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function Pm(n){if(Lo)return Lo.test(n);for(let e=0;e<n.length;e++){let t=n[e];if(/\w/.test(t)||t>"\x80"&&(t.toUpperCase()!=t.toLowerCase()||Am.test(t)))return!0}return!1}function Em(n){return e=>{if(!/\S/.test(e))return rt.Space;if(Pm(e))return rt.Word;for(let t=0;t<n.length;t++)if(e.indexOf(n[t])>-1)return rt.Word;return rt.Other}}var U=class{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let l=0;l<this.config.dynamicSlots.length;l++)ir(this,l<<1);this.computeSlot=null}field(e,t=!0){let i=this.config.address[e.id];if(i==null){if(t)throw new RangeError("Field is not present in this state");return}return ir(this,i),ls(this,i)}update(...e){return wh(this,e,!0)}applyTransaction(e){let t=this.config,{base:i,compartments:r}=t;for(let o of e.effects)o.is(an.reconfigure)?(t&&(r=new Map,t.compartments.forEach((l,a)=>r.set(a,l)),t=null),r.set(o.value.compartment,o.value.extension)):o.is(ee.reconfigure)?(t=null,i=o.value):o.is(ee.appendConfig)&&(t=null,i=ln(i).concat(o.value));let s;t?s=e.startState.values.slice():(t=un.resolve(i,r,this),s=new U(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,a)=>a.reconfigure(l,this),null).values),new U(t,e.newDoc,e.newSelection,s,(o,l)=>l.update(o,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:T.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ln(i.effects);for(let l=1;l<t.ranges.length;l++){let a=e(t.ranges[l]),u=this.changes(a.changes),h=u.map(r);for(let f=0;f<l;f++)s[f]=s[f].map(h);let c=r.mapDesc(u,!0);s.push(a.range.map(c)),r=r.compose(h),o=ee.mapEffects(o,h).concat(ee.mapEffects(ln(a.effects),c))}return{changes:r,selection:T.create(s,t.mainIndex),effects:o}}changes(e=[]){return e instanceof ne?e:ne.of(e,this.doc.length,this.facet(U.lineSeparator))}toText(e){return _.of(e.split(this.facet(U.lineSeparator)||Do))}sliceDoc(e=0,t=this.doc.length){return this.doc.sliceString(e,t,this.lineBreak)}facet(e){let t=this.config.address[e.id];return t==null?e.default:(ir(this,t),ls(this,t))}toJSON(e){let t={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(e)for(let i in e){let r=e[i];r instanceof Be&&this.config.address[r.id]!=null&&(t[i]=r.spec.toJSON(this.field(e[i]),this))}return t}static fromJSON(e,t={},i){if(!e||typeof e.doc!="string")throw new RangeError("Invalid JSON representation for EditorState");let r=[];if(i){for(let s in i)if(Object.prototype.hasOwnProperty.call(e,s)){let o=i[s],l=e[s];r.push(o.init(a=>o.spec.fromJSON(l,a)))}}return U.create({doc:e.doc,selection:T.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=un.resolve(e.extensions||[],new Map),i=e.doc instanceof _?e.doc:_.of((e.doc||"").split(t.staticFacet(U.lineSeparator)||Do)),r=e.selection?e.selection instanceof T?e.selection:T.single(e.selection.anchor,e.selection.head):T.single(0);return hh(r,i.length),t.staticFacet(fh)||(r=r.asSingle()),new U(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(U.tabSize)}get lineBreak(){return this.facet(U.lineSeparator)||`
5
- `}get readOnly(){return this.facet(bh)}phrase(e,...t){for(let i of this.facet(U.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,r)=>{if(r=="$")return"$";let s=+(r||1);return!s||s>t.length?i:t[s-1]})),e}languageDataAt(e,t,i=-1){let r=[];for(let s of this.facet(ch))for(let o of s(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&r.push(o[e]);return r}charCategorizer(e){return Em(this.languageDataAt("wordChars",e).join(""))}wordAt(e){let{text:t,from:i,length:r}=this.doc.lineAt(e),s=this.charCategorizer(e),o=e-i,l=e-i;for(;o>0;){let a=De(t,o,!1);if(s(t.slice(a,o))!=rt.Word)break;o=a}for(;l<r;){let a=De(t,l);if(s(t.slice(l,a))!=rt.Word)break;l=a}return o==l?null:T.range(o+i,l+i)}};U.allowMultipleSelections=fh;U.tabSize=N.define({combine:n=>n.length?n[0]:4});U.lineSeparator=dh;U.readOnly=bh;U.phrases=N.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(r=>n[r]==e[r])}});U.languageData=ch;U.changeFilter=ph;U.transactionFilter=mh;U.transactionExtender=gh;an.reconfigure=ee.define();function cn(n,e,t={}){let i={};for(let r of n)for(let s of Object.keys(r)){let o=r[s],l=i[s];if(l===void 0)i[s]=o;else if(!(l===o||o===void 0))if(Object.hasOwnProperty.call(t,s))i[s]=t[s](l,o);else throw new Error("Config merge conflict for field "+s)}for(let r in e)i[r]===void 0&&(i[r]=e[r]);return i}var Vt=class{eq(e){return this==e}range(e,t=e){return Bi.create(e,t,this)}};Vt.prototype.startSide=Vt.prototype.endSide=0;Vt.prototype.point=!1;Vt.prototype.mapMode=Pe.TrackDel;var Bi=class{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new Bi(e,t,i)}};function No(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}var rr=class{constructor(e,t,i,r){this.from=e,this.to=t,this.value=i,this.maxPoint=r}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,r=0){let s=i?this.to:this.from;for(let o=r,l=s.length;;){if(o==l)return o;let a=o+l>>1,u=s[a]-e||(i?this.value[a].endSide:this.value[a].startSide)-t;if(a==o)return u>=0?o:l;u>=0?l=a:o=a+1}}between(e,t,i,r){for(let s=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,s);s<o;s++)if(r(this.from[s]+e,this.to[s]+e,this.value[s])===!1)return!1}map(e,t){let i=[],r=[],s=[],o=-1,l=-1;for(let a=0;a<this.value.length;a++){let u=this.value[a],h=this.from[a]+e,c=this.to[a]+e,f,d;if(h==c){let p=t.mapPos(h,u.startSide,u.mapMode);if(p==null||(f=d=p,u.startSide!=u.endSide&&(d=t.mapPos(h,u.endSide),d<f)))continue}else if(f=t.mapPos(h,u.startSide),d=t.mapPos(c,u.endSide),f>d||f==d&&u.startSide>0&&u.endSide<=0)continue;(d-f||u.endSide-u.startSide)<0||(o<0&&(o=f),u.point&&(l=Math.max(l,d-f)),i.push(u),r.push(f-o),s.push(d-o))}return{mapped:i.length?new rr(r,s,i,l):null,pos:o}}},Z=class{constructor(e,t,i,r){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=r}static create(e,t,i,r){return new Z(e,t,i,r)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:r=0,filterTo:s=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(No)),this.isEmpty)return t.length?Z.of(t):this;let l=new as(this,null,-1).goto(0),a=0,u=[],h=new dt;for(;l.value||a<t.length;)if(a<t.length&&(l.from-t[a].from||l.startSide-t[a].value.startSide)>=0){let c=t[a++];h.addInner(c.from,c.to,c.value)||u.push(c)}else l.rangeIndex==1&&l.chunkIndex<this.chunk.length&&(a==t.length||this.chunkEnd(l.chunkIndex)<t[a].from)&&(!o||r>this.chunkEnd(l.chunkIndex)||s<this.chunkPos[l.chunkIndex])&&h.addChunk(this.chunkPos[l.chunkIndex],this.chunk[l.chunkIndex])?l.nextChunk():((!o||r>l.to||s<l.from||o(l.from,l.to,l.value))&&(h.addInner(l.from,l.to,l.value)||u.push(Bi.create(l.from,l.to,l.value))),l.next());return h.finishInner(this.nextLayer.isEmpty&&!u.length?Z.empty:this.nextLayer.update({add:u,filter:o,filterFrom:r,filterTo:s}))}map(e){if(e.empty||this.isEmpty)return this;let t=[],i=[],r=-1;for(let o=0;o<this.chunk.length;o++){let l=this.chunkPos[o],a=this.chunk[o],u=e.touchesRange(l,l+a.length);if(u===!1)r=Math.max(r,a.maxPoint),t.push(a),i.push(e.mapPos(l));else if(u===!0){let{mapped:h,pos:c}=a.map(l,e);h&&(r=Math.max(r,h.maxPoint),t.push(h),i.push(c))}}let s=this.nextLayer.map(e);return t.length==0?s:new Z(i,t,s||Z.empty,r)}between(e,t,i){if(!this.isEmpty){for(let r=0;r<this.chunk.length;r++){let s=this.chunkPos[r],o=this.chunk[r];if(t>=s&&e<=s+o.length&&o.between(s,e-s,t-s,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return Fi.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return Fi.from(e).goto(t)}static compare(e,t,i,r,s=-1){let o=e.filter(c=>c.maxPoint>0||!c.isEmpty&&c.maxPoint>=s),l=t.filter(c=>c.maxPoint>0||!c.isEmpty&&c.maxPoint>=s),a=nh(o,l,i),u=new Vi(o,a,s),h=new Vi(l,a,s);i.iterGaps((c,f,d)=>rh(u,c,h,f,d,r)),i.empty&&i.length==0&&rh(u,0,h,0,0,r)}static eq(e,t,i=0,r){r==null&&(r=1e9-1);let s=e.filter(h=>!h.isEmpty&&t.indexOf(h)<0),o=t.filter(h=>!h.isEmpty&&e.indexOf(h)<0);if(s.length!=o.length)return!1;if(!s.length)return!0;let l=nh(s,o),a=new Vi(s,l,0).goto(i),u=new Vi(o,l,0).goto(i);for(;;){if(a.to!=u.to||!Bo(a.active,u.active)||a.point&&(!u.point||!a.point.eq(u.point)))return!1;if(a.to>r)return!0;a.next(),u.next()}}static spans(e,t,i,r,s=-1){let o=new Vi(e,null,s).goto(t),l=t,a=o.openStart;for(;;){let u=Math.min(o.to,i);if(o.point){let h=o.activeForPoint(o.to),c=o.pointFrom<t?h.length+1:Math.min(h.length,a);r.point(l,u,o.point,h,c,o.pointRank),a=Math.min(o.openEnd(u),h.length)}else u>l&&(r.span(l,u,o.active,a),a=o.openEnd(u));if(o.to>i)return a+(o.point&&o.to>i?1:0);l=o.to,o.next()}}static of(e,t=!1){let i=new dt;for(let r of e instanceof Bi?[e]:t?Om(e):e)i.add(r.from,r.to,r.value);return i.finish()}};Z.empty=new Z([],[],null,-1);function Om(n){if(n.length>1)for(let e=n[0],t=1;t<n.length;t++){let i=n[t];if(No(e,i)>0)return n.slice().sort(No);e=i}return n}Z.empty.nextLayer=Z.empty;var dt=class{constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}finishChunk(e){this.chunks.push(new rr(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}add(e,t,i){this.addInner(e,t,i)||(this.nextLayer||(this.nextLayer=new dt)).add(e,t,i)}addInner(e,t,i){let r=e-this.lastTo||i.startSide-this.last.endSide;if(r<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return r<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(Z.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=Z.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}};function nh(n,e,t){let i=new Map;for(let s of n)for(let o=0;o<s.chunk.length;o++)s.chunk[o].maxPoint<=0&&i.set(s.chunk[o],s.chunkPos[o]);let r=new Set;for(let s of e)for(let o=0;o<s.chunk.length;o++){let l=i.get(s.chunk[o]);l!=null&&(t?t.mapPos(l):l)==s.chunkPos[o]&&!(t!=null&&t.touchesRange(l,l+s.chunk[o].length))&&r.add(s.chunk[o])}return r}var as=class{constructor(e,t,i,r=0){this.layer=e,this.skip=t,this.minPoint=i,this.rank=r}get startSide(){return this.value?this.value.startSide:0}get endSide(){return this.value?this.value.endSide:0}goto(e,t=-1e9){return this.chunkIndex=this.rangeIndex=0,this.gotoInner(e,t,!1),this}gotoInner(e,t,i){for(;this.chunkIndex<this.layer.chunk.length;){let r=this.layer.chunk[this.chunkIndex];if(!(this.skip&&this.skip.has(r)||this.layer.chunkEnd(this.chunkIndex)<e||r.maxPoint<this.minPoint))break;this.chunkIndex++,i=!1}if(this.chunkIndex<this.layer.chunk.length){let r=this.layer.chunk[this.chunkIndex].findIndex(e-this.layer.chunkPos[this.chunkIndex],t,!0);(!i||this.rangeIndex<r)&&this.setRangeIndex(r)}this.next()}forward(e,t){(this.to-e||this.endSide-t)<0&&this.gotoInner(e,t,!0)}next(){for(;;)if(this.chunkIndex==this.layer.chunk.length){this.from=this.to=1e9,this.value=null;break}else{let e=this.layer.chunkPos[this.chunkIndex],t=this.layer.chunk[this.chunkIndex],i=e+t.from[this.rangeIndex];if(this.from=i,this.to=e+t.to[this.rangeIndex],this.value=t.value[this.rangeIndex],this.setRangeIndex(this.rangeIndex+1),this.minPoint<0||this.value.point&&this.to-this.from>=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex<this.layer.chunk.length&&this.skip.has(this.layer.chunk[this.chunkIndex]);)this.chunkIndex++;this.rangeIndex=0}else this.rangeIndex=e}nextChunk(){this.chunkIndex++,this.rangeIndex=0,this.next()}compare(e){return this.from-e.from||this.startSide-e.startSide||this.rank-e.rank||this.to-e.to||this.endSide-e.endSide}},Fi=class{constructor(e){this.heap=e}static from(e,t=null,i=-1){let r=[];for(let s=0;s<e.length;s++)for(let o=e[s];!o.isEmpty;o=o.nextLayer)o.maxPoint>=i&&r.push(new as(o,t,i,s));return r.length==1?r[0]:new Fi(r)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)To(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)To(this.heap,i);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),To(this.heap,0)}}};function To(n,e){for(let t=n[e];;){let i=(e<<1)+1;if(i>=n.length)break;let r=n[i];if(i+1<n.length&&r.compare(n[i+1])>=0&&(r=n[i+1],i++),t.compare(r)<0)break;n[i]=t,n[e]=r,e=i}}var Vi=class{constructor(e,t,i){this.minPoint=i,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=Fi.from(e,t,i)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){es(this.active,e),es(this.activeTo,e),es(this.activeRank,e),this.minActive=sh(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:r,rank:s}=this.cursor;for(;t<this.activeRank.length&&this.activeRank[t]<=s;)t++;ts(this.active,t,i),ts(this.activeTo,t,r),ts(this.activeRank,t,s),e&&ts(e,t,this.cursor.from),this.minActive=sh(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let r=this.minActive;if(r>-1&&(this.activeTo[r]-this.cursor.from||this.active[r].endSide-this.cursor.startSide)<0){if(this.activeTo[r]>e){this.to=this.activeTo[r],this.endSide=this.active[r].endSide;break}this.removeActive(r),i&&es(i,r)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let s=this.cursor.value;if(!s.point)this.addActive(i),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from<this.cursor.to)this.cursor.next();else{this.point=s,this.pointFrom=this.cursor.from,this.pointRank=this.cursor.rank,this.to=this.cursor.to,this.endSide=s.endSide,this.cursor.next(),this.forward(this.to,this.endSide);break}}else{this.to=this.endSide=1e9;break}}if(i){this.openStart=0;for(let r=i.length-1;r>=0&&i[r]<e;r--)this.openStart++}}activeForPoint(e){if(!this.active.length)return this.active;let t=[];for(let i=this.active.length-1;i>=0&&!(this.activeRank[i]<this.pointRank);i--)(this.activeTo[i]>e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}};function rh(n,e,t,i,r,s){n.goto(e),t.goto(i);let o=i+r,l=i,a=i-e;for(;;){let u=n.to+a-t.to||n.endSide-t.endSide,h=u<0?n.to+a:t.to,c=Math.min(h,o);if(n.point||t.point?n.point&&t.point&&(n.point==t.point||n.point.eq(t.point))&&Bo(n.activeForPoint(n.to+a),t.activeForPoint(t.to))||s.comparePoint(l,c,n.point,t.point):c>l&&!Bo(n.active,t.active)&&s.compareRange(l,c,n.active,t.active),h>o)break;l=h,u<=0&&n.next(),u>=0&&t.next()}}function Bo(n,e){if(n.length!=e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!=e[t]&&!n[t].eq(e[t]))return!1;return!0}function es(n,e){for(let t=e,i=n.length-1;t<i;t++)n[t]=n[t+1];n.pop()}function ts(n,e,t){for(let i=n.length-1;i>=e;i--)n[i+1]=n[i];n[e]=t}function sh(n,e){let t=-1,i=1e9;for(let r=0;r<e.length;r++)(e[r]-i||n[r].endSide-n[t].endSide)<0&&(t=r,i=e[r]);return t}function Hi(n,e,t=n.length){let i=0;for(let r=0;r<t;)n.charCodeAt(r)==9?(i+=e-i%e,r++):(i++,r=De(n,r));return i}function vh(n,e,t,i){for(let r=0,s=0;;){if(s>=e)return r;if(r==n.length)break;s+=n.charCodeAt(r)==9?t-s%t:1,r=De(n,r)}return i===!0?-1:n.length}var Wo="\u037C",Ch=typeof Symbol>"u"?"__"+Wo:Symbol.for(Wo),_o=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),Sh=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},Ke=class{constructor(e,t){this.rules=[];let{finish:i}=t||{};function r(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function s(o,l,a,u){let h=[],c=/^@(\w+)\b/.exec(o[0]),f=c&&c[1]=="keyframes";if(c&&l==null)return a.push(o[0]+";");for(let d in l){let p=l[d];if(/&/.test(d))s(d.split(/,\s*/).map(m=>o.map(g=>m.replace(/&/,g))).reduce((m,g)=>m.concat(g)),p,a);else if(p&&typeof p=="object"){if(!c)throw new RangeError("The value of a property ("+d+") should be a primitive value.");s(r(d),p,h,f)}else p!=null&&h.push(d.replace(/_.*/,"").replace(/[A-Z]/g,m=>"-"+m.toLowerCase())+": "+p+";")}(h.length||f)&&a.push((i&&!c&&!u?o.map(i):o).join(", ")+" {"+h.join(" ")+"}")}for(let o in e)s(r(o),e[o],this.rules)}getRules(){return this.rules.join(`
6
- `)}static newName(){let e=Sh[Ch]||1;return Sh[Ch]=e+1,Wo+e.toString(36)}static mount(e,t){(e[_o]||new zo(e)).mount(Array.isArray(t)?t:[t])}},us=null,zo=class{constructor(e){if(!e.head&&e.adoptedStyleSheets&&typeof CSSStyleSheet<"u"){if(us)return e.adoptedStyleSheets=[us.sheet,...e.adoptedStyleSheets],e[_o]=us;this.sheet=new CSSStyleSheet,e.adoptedStyleSheets=[this.sheet,...e.adoptedStyleSheets],us=this}else{this.styleTag=(e.ownerDocument||e).createElement("style");let t=e.head||e;t.insertBefore(this.styleTag,t.firstChild)}this.modules=[],e[_o]=this}mount(e){let t=this.sheet,i=0,r=0;for(let s=0;s<e.length;s++){let o=e[s],l=this.modules.indexOf(o);if(l<r&&l>-1&&(this.modules.splice(l,1),r--,l=-1),l==-1){if(this.modules.splice(r++,0,o),t)for(let a=0;a<o.rules.length;a++)t.insertRule(o.rules[a],i++)}else{for(;r<l;)i+=this.modules[r++].rules.length;i+=o.rules.length,r++}}if(!t){let s="";for(let o=0;o<this.modules.length;o++)s+=this.modules[o].getRules()+`
7
- `;this.styleTag.textContent=s}}};var Lt={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},fn={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},xh=typeof navigator<"u"&&/Chrome\/(\d+)/.exec(navigator.userAgent),aS=typeof navigator<"u"&&/Gecko\/\d+/.test(navigator.userAgent),Im=typeof navigator<"u"&&/Mac/.test(navigator.platform),Vm=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),Lm=Im||xh&&+xh[1]<57;for(he=0;he<10;he++)Lt[48+he]=Lt[96+he]=String(he);var he;for(he=1;he<=24;he++)Lt[he+111]="F"+he;var he;for(he=65;he<=90;he++)Lt[he]=String.fromCharCode(he+32),fn[he]=String.fromCharCode(he);var he;for(hs in Lt)fn.hasOwnProperty(hs)||(fn[hs]=Lt[hs]);var hs;function kh(n){var e=Lm&&(n.ctrlKey||n.altKey||n.metaKey)||Vm&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?fn:Lt)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function Cs(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function gn(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function Nm(n){let e=n.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function bs(n,e){if(!e.anchorNode)return!1;try{return gn(n,e.anchorNode)}catch{return!1}}function hr(n){return n.nodeType==3?bn(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function Ss(n,e,t,i){return t?Mh(n,e,t,i,-1)||Mh(n,e,t,i,1):!1}function xs(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function Mh(n,e,t,i,r){for(;;){if(n==t&&e==i)return!0;if(e==(r<0?0:cr(n))){if(n.nodeName=="DIV")return!1;let s=n.parentNode;if(!s||s.nodeType!=1)return!1;e=xs(n)+(r<0?0:1),n=s}else if(n.nodeType==1){if(n=n.childNodes[e+(r<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=r<0?cr(n):0}else return!1}}function cr(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}var rc={left:0,right:0,top:0,bottom:0};function Al(n,e){let t=e?n.left:n.right;return{left:t,right:t,top:n.top,bottom:n.bottom}}function Bm(n){return{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function Fm(n,e,t,i,r,s,o,l){let a=n.ownerDocument,u=a.defaultView||window;for(let h=n;h;)if(h.nodeType==1){let c,f=h==a.body;if(f)c=Bm(u);else{if(h.scrollHeight<=h.clientHeight&&h.scrollWidth<=h.clientWidth){h=h.assignedSlot||h.parentNode;continue}let m=h.getBoundingClientRect();c={left:m.left,right:m.left+h.clientWidth,top:m.top,bottom:m.top+h.clientHeight}}let d=0,p=0;if(r=="nearest")e.top<c.top?(p=-(c.top-e.top+o),t>0&&e.bottom>c.bottom+p&&(p=e.bottom-c.bottom+p+o)):e.bottom>c.bottom&&(p=e.bottom-c.bottom+o,t<0&&e.top-p<c.top&&(p=-(c.top+p-e.top+o)));else{let m=e.bottom-e.top,g=c.bottom-c.top;p=(r=="center"&&m<=g?e.top+m/2-g/2:r=="start"||r=="center"&&t<0?e.top-o:e.bottom-g+o)-c.top}if(i=="nearest"?e.left<c.left?(d=-(c.left-e.left+s),t>0&&e.right>c.right+d&&(d=e.right-c.right+d+s)):e.right>c.right&&(d=e.right-c.right+s,t<0&&e.left<c.left+d&&(d=-(c.left+d-e.left+s))):d=(i=="center"?e.left+(e.right-e.left)/2-(c.right-c.left)/2:i=="start"==l?e.left-s:e.right-(c.right-c.left)+s)-c.left,d||p)if(f)u.scrollBy(d,p);else{let m=0,g=0;if(p){let b=h.scrollTop;h.scrollTop+=p,g=h.scrollTop-b}if(d){let b=h.scrollLeft;h.scrollLeft+=d,m=h.scrollLeft-b}e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g},m&&Math.abs(m-d)<1&&(i="nearest"),g&&Math.abs(g-p)<1&&(r="nearest")}if(f)break;h=h.assignedSlot||h.parentNode}else if(h.nodeType==11)h=h.host;else break}function Hm(n){let e=n.ownerDocument;for(let t=n.parentNode;t&&t!=e.body;)if(t.nodeType==1){if(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth)return t;t=t.assignedSlot||t.parentNode}else if(t.nodeType==11)t=t.host;else break;return null}var jo=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){this.set(e.anchorNode,e.anchorOffset,e.focusNode,e.focusOffset)}set(e,t,i,r){this.anchorNode=e,this.anchorOffset=t,this.focusNode=i,this.focusOffset=r}},dn=null;function sc(n){if(n.setActive)return n.setActive();if(dn)return n.focus(dn);let e=[];for(let t=n;t&&(e.push(t,t.scrollTop,t.scrollLeft),t!=t.ownerDocument);t=t.parentNode);if(n.focus(dn==null?{get preventScroll(){return dn={preventScroll:!0},!0}}:void 0),!dn){dn=!1;for(let t=0;t<e.length;){let i=e[t++],r=e[t++],s=e[t++];i.scrollTop!=r&&(i.scrollTop=r),i.scrollLeft!=s&&(i.scrollLeft=s)}}}var Th;function bn(n,e,t=e){let i=Th||(Th=document.createRange());return i.setEnd(n,t),i.setStart(n,e),i}function mn(n,e,t){let i={key:e,code:e,keyCode:t,which:t,cancelable:!0},r=new KeyboardEvent("keydown",i);r.synthetic=!0,n.dispatchEvent(r);let s=new KeyboardEvent("keyup",i);return s.synthetic=!0,n.dispatchEvent(s),r.defaultPrevented||s.defaultPrevented}function Wm(n){for(;n;){if(n&&(n.nodeType==9||n.nodeType==11&&n.host))return n;n=n.assignedSlot||n.parentNode}return null}function oc(n){for(;n.attributes.length;)n.removeAttributeNode(n.attributes[0])}function _m(n,e){let t=e.focusNode,i=e.focusOffset;if(!t||e.anchorNode!=t||e.anchorOffset!=i)return!1;for(;;)if(i){if(t.nodeType!=1)return!1;let r=t.childNodes[i-1];r.contentEditable=="false"?i--:(t=r,i=cr(t))}else{if(t==n)return!0;i=xs(t),t=t.parentNode}}var me=class{constructor(e,t,i=!0){this.node=e,this.offset=t,this.precise=i}static before(e,t){return new me(e.parentNode,xs(e),t)}static after(e,t){return new me(e.parentNode,xs(e)+1,t)}},Pl=[],G=class{constructor(){this.parent=null,this.dom=null,this.dirty=2}get overrideDOMText(){return null}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e){let t=this.posAtStart;for(let i of this.children){if(i==e)return t;t+=i.length+i.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}coordsAt(e,t){return null}sync(e,t){if(this.dirty&2){let i=this.dom,r=null,s;for(let o of this.children){if(o.dirty){if(!o.dom&&(s=r?r.nextSibling:i.firstChild)){let l=G.get(s);(!l||!l.parent&&l.canReuseDOM(o))&&o.reuseDOM(s)}o.sync(e,t),o.dirty=0}if(s=r?r.nextSibling:i.firstChild,t&&!t.written&&t.node==i&&s!=o.dom&&(t.written=!0),o.dom.parentNode==i)for(;s&&s!=o.dom;)s=Rh(s);else i.insertBefore(o.dom,s);r=o.dom}for(s=r?r.nextSibling:i.firstChild,s&&t&&t.node==i&&(t.written=!0);s;)s=Rh(s)}else if(this.dirty&1)for(let i of this.children)i.dirty&&(i.sync(e,t),i.dirty=0)}reuseDOM(e){}localPosFromDOM(e,t){let i;if(e==this.dom)i=this.dom.childNodes[t];else{let r=cr(e)==0?0:t==0?-1:1;for(;;){let s=e.parentNode;if(s==this.dom)break;r==0&&s.firstChild!=s.lastChild&&(e==s.firstChild?r=-1:r=1),e=s}r<0?i=e:i=e.nextSibling}if(i==this.dom.firstChild)return 0;for(;i&&!G.get(i);)i=i.nextSibling;if(!i)return this.length;for(let r=0,s=0;;r++){let o=this.children[r];if(o.dom==i)return s;s+=o.length+o.breakAfter}}domBoundsAround(e,t,i=0){let r=-1,s=-1,o=-1,l=-1;for(let a=0,u=i,h=i;a<this.children.length;a++){let c=this.children[a],f=u+c.length;if(u<e&&f>t)return c.domBoundsAround(e,t,u);if(f>=e&&r==-1&&(r=a,s=u),u>t&&c.dom.parentNode==this.dom){o=a,l=h;break}h=f,u=f+c.breakAfter}return{from:s,to:l<0?i+this.length:l,startDOM:(r?this.children[r-1].dom.nextSibling:null)||this.dom.firstChild,endDOM:o<this.children.length&&o>=0?this.children[o].dom:null}}markDirty(e=!1){this.dirty|=2,this.markParentsDirty(e)}markParentsDirty(e){for(let t=this.parent;t;t=t.parent){if(e&&(t.dirty|=2),t.dirty&1)return;t.dirty|=1,e=!1}}setParent(e){this.parent!=e&&(this.parent=e,this.dirty&&this.markParentsDirty(!0))}setDOM(e){this.dom&&(this.dom.cmView=null),this.dom=e,e.cmView=this}get rootView(){for(let e=this;;){let t=e.parent;if(!t)return e;e=t}}replaceChildren(e,t,i=Pl){this.markDirty();for(let r=e;r<t;r++){let s=this.children[r];s.parent==this&&s.destroy()}this.children.splice(e,t-e,...i);for(let r=0;r<i.length;r++)i[r].setParent(this)}ignoreMutation(e){return!1}ignoreEvent(e){return!1}childCursor(e=this.length){return new ks(this.children,e,this.children.length)}childPos(e,t=1){return this.childCursor().findPos(e,t)}toString(){let e=this.constructor.name.replace("View","");return e+(this.children.length?"("+this.children.join()+")":this.length?"["+(e=="Text"?this.text:this.length)+"]":"")+(this.breakAfter?"#":"")}static get(e){return e.cmView}get isEditable(){return!0}get isWidget(){return!1}merge(e,t,i,r,s,o){return!1}become(e){return!1}canReuseDOM(e){return e.constructor==this.constructor}getSide(){return 0}destroy(){this.parent=null}};G.prototype.breakAfter=0;function Rh(n){let e=n.nextSibling;return n.parentNode.removeChild(n),e}var ks=class{constructor(e,t,i){this.children=e,this.pos=t,this.i=i,this.off=0}findPos(e,t=1){for(;;){if(e>this.pos||e==this.pos&&(t>0||this.i==0||this.children[this.i-1].breakAfter))return this.off=e-this.pos,this;let i=this.children[--this.i];this.pos-=i.length+i.breakAfter}}};function lc(n,e,t,i,r,s,o,l,a){let{children:u}=n,h=u.length?u[e]:null,c=s.length?s[s.length-1]:null,f=c?c.breakAfter:o;if(!(e==i&&h&&!o&&!f&&s.length<2&&h.merge(t,r,s.length?c:null,t==0,l,a))){if(i<u.length){let d=u[i];d&&r<d.length?(e==i&&(d=d.split(r),r=0),!f&&c&&d.merge(0,r,c,!0,0,a)?s[s.length-1]=d:(r&&d.merge(0,r,null,!1,0,a),s.push(d))):d!=null&&d.breakAfter&&(c?c.breakAfter=1:o=1),i++}for(h&&(h.breakAfter=o,t>0&&(!o&&s.length&&h.merge(t,h.length,s[0],!1,l,0)?h.breakAfter=s.shift().breakAfter:(t<h.length||h.children.length&&h.children[h.children.length-1].length==0)&&h.merge(t,h.length,null,!1,l,0),e++));e<i&&s.length;)if(u[i-1].become(s[s.length-1]))i--,s.pop(),a=s.length?0:l;else if(u[e].become(s[0]))e++,s.shift(),l=s.length?0:a;else break;!s.length&&e&&i<u.length&&!u[e-1].breakAfter&&u[i].merge(0,0,u[e-1],!1,l,a)&&e--,(e<i||s.length)&&n.replaceChildren(e,i,s)}}function ac(n,e,t,i,r,s){let o=n.childCursor(),{i:l,off:a}=o.findPos(t,1),{i:u,off:h}=o.findPos(e,-1),c=e-t;for(let f of i)c+=f.length;n.length+=c,lc(n,u,h,l,a,i,0,r,s)}var Fe=typeof navigator<"u"?navigator:{userAgent:"",vendor:"",platform:""},Jo=typeof document<"u"?document:{documentElement:{style:{}}},Qo=/Edge\/(\d+)/.exec(Fe.userAgent),uc=/MSIE \d/.test(Fe.userAgent),Xo=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(Fe.userAgent),Is=!!(uc||Xo||Qo),Dh=!Is&&/gecko\/(\d+)/i.test(Fe.userAgent),Uo=!Is&&/Chrome\/(\d+)/.exec(Fe.userAgent),Ah="webkitFontSmoothing"in Jo.documentElement.style,hc=!Is&&/Apple Computer/.test(Fe.vendor),Ph=hc&&(/Mobile\/\w+/.test(Fe.userAgent)||Fe.maxTouchPoints>2),V={mac:Ph||/Mac/.test(Fe.platform),windows:/Win/.test(Fe.platform),linux:/Linux|X11/.test(Fe.platform),ie:Is,ie_version:uc?Jo.documentMode||6:Xo?+Xo[1]:Qo?+Qo[1]:0,gecko:Dh,gecko_version:Dh?+(/Firefox\/(\d+)/.exec(Fe.userAgent)||[0,0])[1]:0,chrome:!!Uo,chrome_version:Uo?+Uo[1]:0,ios:Ph,android:/Android\b/.test(Fe.userAgent),webkit:Ah,safari:hc,webkit_version:Ah?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0,tabSize:Jo.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"},zm=256,gt=class extends G{constructor(e){super(),this.text=e}get length(){return this.text.length}createDOM(e){this.setDOM(e||document.createTextNode(this.text))}sync(e,t){this.dom||this.createDOM(),this.dom.nodeValue!=this.text&&(t&&t.node==this.dom&&(t.written=!0),this.dom.nodeValue=this.text)}reuseDOM(e){e.nodeType==3&&this.createDOM(e)}merge(e,t,i){return i&&(!(i instanceof gt)||this.length-(t-e)+i.length>zm)?!1:(this.text=this.text.slice(0,e)+(i?i.text:"")+this.text.slice(t),this.markDirty(),!0)}split(e){let t=new gt(this.text.slice(e));return this.text=this.text.slice(0,e),this.markDirty(),t}localPosFromDOM(e,t){return e==this.dom?t:t?this.text.length:0}domAtPos(e){return new me(this.dom,e)}domBoundsAround(e,t,i){return{from:i,to:i+this.length,startDOM:this.dom,endDOM:this.dom.nextSibling}}coordsAt(e,t){return Yo(this.dom,e,t)}},Ge=class extends G{constructor(e,t=[],i=0){super(),this.mark=e,this.children=t,this.length=i;for(let r of t)r.setParent(this)}setAttrs(e){if(oc(e),this.mark.class&&(e.className=this.mark.class),this.mark.attrs)for(let t in this.mark.attrs)e.setAttribute(t,this.mark.attrs[t]);return e}reuseDOM(e){e.nodeName==this.mark.tagName.toUpperCase()&&(this.setDOM(e),this.dirty|=6)}sync(e,t){this.dom?this.dirty&4&&this.setAttrs(this.dom):this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))),super.sync(e,t)}merge(e,t,i,r,s,o){return i&&(!(i instanceof Ge&&i.mark.eq(this.mark))||e&&s<=0||t<this.length&&o<=0)?!1:(ac(this,e,t,i?i.children:[],s-1,o-1),this.markDirty(),!0)}split(e){let t=[],i=0,r=-1,s=0;for(let l of this.children){let a=i+l.length;a>e&&t.push(i<e?l.split(e-i):l),r<0&&i>=e&&(r=s),i=a,s++}let o=this.length-e;return this.length=e,r>-1&&(this.children.length=r,this.markDirty()),new Ge(this.mark,t,o)}domAtPos(e){return fc(this,e)}coordsAt(e,t){return pc(this,e,t)}};function Yo(n,e,t){let i=n.nodeValue.length;e>i&&(e=i);let r=e,s=e,o=0;e==0&&t<0||e==i&&t>=0?V.chrome||V.gecko||(e?(r--,o=1):s<i&&(s++,o=-1)):t<0?r--:s<i&&s++;let l=bn(n,r,s).getClientRects();if(!l.length)return rc;let a=l[(o?o<0:t>=0)?0:l.length-1];return V.safari&&!o&&a.width==0&&(a=Array.prototype.find.call(l,u=>u.width)||a),o?Al(a,o<0):a||null}var mt=class extends G{constructor(e,t,i){super(),this.widget=e,this.length=t,this.side=i,this.prevWidget=null}static create(e,t,i){return new(e.customView||mt)(e,t,i)}split(e){let t=mt.create(this.widget,this.length-e,this.side);return this.length-=e,t}sync(e){(!this.dom||!this.widget.updateDOM(this.dom,e))&&(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(e)),this.dom.contentEditable="false")}getSide(){return this.side}merge(e,t,i,r,s,o){return i&&(!(i instanceof mt)||!this.widget.compare(i.widget)||e>0&&s<=0||t<this.length&&o<=0)?!1:(this.length=e+(i?i.length:0)+(this.length-t),!0)}become(e){return e.length==this.length&&e instanceof mt&&e.side==this.side&&this.widget.constructor==e.widget.constructor?(this.widget.eq(e.widget)||this.markDirty(!0),this.dom&&!this.prevWidget&&(this.prevWidget=this.widget),this.widget=e.widget,!0):!1}ignoreMutation(){return!0}ignoreEvent(e){return this.widget.ignoreEvent(e)}get overrideDOMText(){if(this.length==0)return _.empty;let e=this;for(;e.parent;)e=e.parent;let{view:t}=e,i=t&&t.state.doc,r=this.posAtStart;return i?i.slice(r,r+this.length):_.empty}domAtPos(e){return e==0?me.before(this.dom):me.after(this.dom,e==this.length)}domBoundsAround(){return null}coordsAt(e,t){let i=this.dom.getClientRects(),r=null;if(!i.length)return rc;for(let s=e>0?i.length-1:0;r=i[s],!(e>0?s==0:s==i.length-1||r.top<r.bottom);s+=e>0?-1:1);return this.length?r:Al(r,this.side>0)}get isEditable(){return!1}get isWidget(){return!0}destroy(){super.destroy(),this.dom&&this.widget.destroy(this.dom)}},Ms=class extends mt{domAtPos(e){let{topView:t,text:i}=this.widget;return t?Zo(e,0,t,i,(r,s)=>r.domAtPos(s),r=>new me(i,Math.min(r,i.nodeValue.length))):new me(i,Math.min(e,i.nodeValue.length))}sync(){this.setDOM(this.widget.toDOM())}localPosFromDOM(e,t){let{topView:i,text:r}=this.widget;return i?cc(e,t,i,r):Math.min(t,this.length)}ignoreMutation(){return!1}get overrideDOMText(){return null}coordsAt(e,t){let{topView:i,text:r}=this.widget;return i?Zo(e,t,i,r,(s,o,l)=>s.coordsAt(o,l),(s,o)=>Yo(r,s,o)):Yo(r,e,t)}destroy(){var e;super.destroy(),(e=this.widget.topView)===null||e===void 0||e.destroy()}get isEditable(){return!0}canReuseDOM(){return!0}};function Zo(n,e,t,i,r,s){if(t instanceof Ge){for(let o=t.dom.firstChild;o;o=o.nextSibling){let l=G.get(o);if(!l)return s(n,e);let a=gn(o,i),u=l.length+(a?i.nodeValue.length:0);if(n<u||n==u&&l.getSide()<=0)return a?Zo(n,e,l,i,r,s):r(l,n,e);n-=u}return r(t,t.length,-1)}else return t.dom==i?s(n,e):r(t,n,e)}function cc(n,e,t,i){if(t instanceof Ge){let r=0;for(let s of t.children){let o=gn(s.dom,i);if(gn(s.dom,n))return r+(o?cc(n,e,s,i):s.localPosFromDOM(n,e));r+=o?i.nodeValue.length:s.length}}else if(t.dom==i)return Math.min(e,i.nodeValue.length);return t.localPosFromDOM(n,e)}var ti=class extends G{constructor(e){super(),this.side=e}get length(){return 0}merge(){return!1}become(e){return e instanceof ti&&e.side==this.side}split(){return new ti(this.side)}sync(){if(!this.dom){let e=document.createElement("img");e.className="cm-widgetBuffer",e.setAttribute("aria-hidden","true"),this.setDOM(e)}}getSide(){return this.side}domAtPos(e){return this.side>0?me.before(this.dom):me.after(this.dom)}localPosFromDOM(){return 0}domBoundsAround(){return null}coordsAt(e){let t=this.dom.getBoundingClientRect(),i=Um(this,this.side>0?-1:1);return i&&i.top<t.bottom&&i.bottom>t.top?{left:t.left,right:t.right,top:i.top,bottom:i.bottom}:t}get overrideDOMText(){return _.empty}};gt.prototype.children=mt.prototype.children=ti.prototype.children=Pl;function Um(n,e){let t=n.parent,i=t?t.children.indexOf(n):-1;for(;t&&i>=0;)if(e<0?i>0:i<t.children.length){let r=t.children[i+e];if(r instanceof gt){let s=r.coordsAt(e<0?r.length:0,e);if(s)return s}i+=e}else if(t instanceof Ge&&t.parent)i=t.parent.children.indexOf(t)+(e<0?0:1),t=t.parent;else{let r=t.dom.lastChild;if(r&&r.nodeName=="BR")return r.getClientRects()[0];break}}function fc(n,e){let t=n.dom,{children:i}=n,r=0;for(let s=0;r<i.length;r++){let o=i[r],l=s+o.length;if(!(l==s&&o.getSide()<=0)){if(e>s&&e<l&&o.dom.parentNode==t)return o.domAtPos(e-s);if(e<=s)break;s=l}}for(let s=r;s>0;s--){let o=i[s-1];if(o.dom.parentNode==t)return o.domAtPos(o.length)}for(let s=r;s<i.length;s++){let o=i[s];if(o.dom.parentNode==t)return o.domAtPos(0)}return new me(t,0)}function dc(n,e,t){let i,{children:r}=n;t>0&&e instanceof Ge&&r.length&&(i=r[r.length-1])instanceof Ge&&i.mark.eq(e.mark)?dc(i,e.children[0],t-1):(r.push(e),e.setParent(n)),n.length+=e.length}function pc(n,e,t){let i=null,r=-1,s=null,o=-1;function l(u,h){for(let c=0,f=0;c<u.children.length&&f<=h;c++){let d=u.children[c],p=f+d.length;p>=h&&(d.children.length?l(d,h-f):!s&&(p>h||f==p&&d.getSide()>0)?(s=d,o=h-f):(f<h||f==p&&d.getSide()<0)&&(i=d,r=h-f)),f=p}}l(n,e);let a=(t<0?i:s)||i||s;return a?a.coordsAt(Math.max(0,a==i?r:o),t):$m(n)}function $m(n){let e=n.dom.lastChild;if(!e)return n.dom.getBoundingClientRect();let t=hr(e);return t[t.length-1]||null}function el(n,e){for(let t in n)t=="class"&&e.class?e.class+=" "+n.class:t=="style"&&e.style?e.style+=";"+n.style:e[t]=n[t];return e}function El(n,e){if(n==e)return!0;if(!n||!e)return!1;let t=Object.keys(n),i=Object.keys(e);if(t.length!=i.length)return!1;for(let r of t)if(i.indexOf(r)==-1||n[r]!==e[r])return!1;return!0}function tl(n,e,t){let i=null;if(e)for(let r in e)t&&r in t||n.removeAttribute(i=r);if(t)for(let r in t)e&&e[r]==t[r]||n.setAttribute(i=r,t[r]);return!!i}var Ft=class{eq(e){return!1}updateDOM(e,t){return!1}compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}get estimatedHeight(){return-1}ignoreEvent(e){return!0}get customView(){return null}destroy(e){}},Q=function(n){return n[n.Text=0]="Text",n[n.WidgetBefore=1]="WidgetBefore",n[n.WidgetAfter=2]="WidgetAfter",n[n.WidgetRange=3]="WidgetRange",n}(Q||(Q={})),X=class extends Vt{constructor(e,t,i,r){super(),this.startSide=e,this.endSide=t,this.widget=i,this.spec=r}get heightRelevant(){return!1}static mark(e){return new yn(e)}static widget(e){let t=e.side||0,i=!!e.block;return t+=i?t>0?3e8:-4e8:t>0?1e8:-1e8,new Ht(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,r;if(e.isBlockGap)i=-5e8,r=4e8;else{let{start:s,end:o}=mc(e,t);i=(s?t?-3e8:-1:5e8)-1,r=(o?t?2e8:1:-6e8)+1}return new Ht(e,i,r,t,e.widget||null,!0)}static line(e){return new Wi(e)}static set(e,t=!1){return Z.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}};X.none=Z.empty;var yn=class extends X{constructor(e){let{start:t,end:i}=mc(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.class=e.class||"",this.attrs=e.attributes||null}eq(e){return this==e||e instanceof yn&&this.tagName==e.tagName&&this.class==e.class&&El(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}};yn.prototype.point=!1;var Wi=class extends X{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof Wi&&this.spec.class==e.spec.class&&El(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}};Wi.prototype.mapMode=Pe.TrackBefore;Wi.prototype.point=!0;var Ht=class extends X{constructor(e,t,i,r,s,o){super(t,i,s,e),this.block=r,this.isReplace=o,this.mapMode=r?t<=0?Pe.TrackBefore:Pe.TrackAfter:Pe.TrackDel}get type(){return this.startSide<this.endSide?Q.WidgetRange:this.startSide<=0?Q.WidgetBefore:Q.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&this.widget.estimatedHeight>=5}eq(e){return e instanceof Ht&&Km(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}};Ht.prototype.point=!0;function mc(n,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=n;return t==null&&(t=n.inclusive),i==null&&(i=n.inclusive),{start:t!=null?t:e,end:i!=null?i:e}}function Km(n,e){return n==e||!!(n&&e&&n.compare(e))}function il(n,e,t,i=0){let r=t.length-1;r>=0&&t[r]+i>=n?t[r]=Math.max(t[r],e):t.push(n,e)}var Ce=class extends G{constructor(){super(...arguments),this.children=[],this.length=0,this.prevAttrs=void 0,this.attrs=null,this.breakAfter=0}merge(e,t,i,r,s,o){if(i){if(!(i instanceof Ce))return!1;this.dom||i.transferDOM(this)}return r&&this.setDeco(i?i.attrs:null),ac(this,e,t,i?i.children:[],s,o),!0}split(e){let t=new Ce;if(t.breakAfter=this.breakAfter,this.length==0)return t;let{i,off:r}=this.childPos(e);r&&(t.append(this.children[i].split(r),0),this.children[i].merge(r,this.children[i].length,null,!1,0,0),i++);for(let s=i;s<this.children.length;s++)t.append(this.children[s],0);for(;i>0&&this.children[i-1].length==0;)this.children[--i].destroy();return this.children.length=i,this.markDirty(),this.length=e,t}transferDOM(e){this.dom&&(this.markDirty(),e.setDOM(this.dom),e.prevAttrs=this.prevAttrs===void 0?this.attrs:this.prevAttrs,this.prevAttrs=void 0,this.dom=null)}setDeco(e){El(this.attrs,e)||(this.dom&&(this.prevAttrs=this.attrs,this.markDirty()),this.attrs=e)}append(e,t){dc(this,e,t)}addLineDeco(e){let t=e.spec.attributes,i=e.spec.class;t&&(this.attrs=el(t,this.attrs||{})),i&&(this.attrs=el({class:i},this.attrs||{}))}domAtPos(e){return fc(this,e)}reuseDOM(e){e.nodeName=="DIV"&&(this.setDOM(e),this.dirty|=6)}sync(e,t){var i;this.dom?this.dirty&4&&(oc(this.dom),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0):(this.setDOM(document.createElement("div")),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0),this.prevAttrs!==void 0&&(tl(this.dom,this.prevAttrs,this.attrs),this.dom.classList.add("cm-line"),this.prevAttrs=void 0),super.sync(e,t);let r=this.dom.lastChild;for(;r&&G.get(r)instanceof Ge;)r=r.lastChild;if(!r||!this.length||r.nodeName!="BR"&&((i=G.get(r))===null||i===void 0?void 0:i.isEditable)==!1&&(!V.ios||!this.children.some(s=>s instanceof gt))){let s=document.createElement("BR");s.cmIgnore=!0,this.dom.appendChild(s)}}measureTextSize(){if(this.children.length==0||this.length>20)return null;let e=0,t;for(let i of this.children){if(!(i instanceof gt)||/[^ -~]/.test(i.text))return null;let r=hr(i.dom);if(r.length!=1)return null;e+=r[0].width,t=r[0].height}return e?{lineHeight:this.dom.getBoundingClientRect().height,charWidth:e/this.length,textHeight:t}:null}coordsAt(e,t){let i=pc(this,e,t);if(!this.children.length&&i&&this.parent){let{heightOracle:r}=this.parent.view.viewState,s=i.bottom-i.top;if(Math.abs(s-r.lineHeight)<2&&r.textHeight<s){let o=(s-r.textHeight)/2;return{top:i.top+o,bottom:i.bottom-o,left:i.left,right:i.left}}}return i}become(e){return!1}get type(){return Q.Text}static find(e,t){for(let i=0,r=0;i<e.children.length;i++){let s=e.children[i],o=r+s.length;if(o>=t){if(s instanceof Ce)return s;if(o>t)break}r=o+s.breakAfter}return null}},Nt=class extends G{constructor(e,t,i){super(),this.widget=e,this.length=t,this.type=i,this.breakAfter=0,this.prevWidget=null}merge(e,t,i,r,s,o){return i&&(!(i instanceof Nt)||!this.widget.compare(i.widget)||e>0&&s<=0||t<this.length&&o<=0)?!1:(this.length=e+(i?i.length:0)+(this.length-t),!0)}domAtPos(e){return e==0?me.before(this.dom):me.after(this.dom,e==this.length)}split(e){let t=this.length-e;this.length=e;let i=new Nt(this.widget,t,this.type);return i.breakAfter=this.breakAfter,i}get children(){return Pl}sync(e){(!this.dom||!this.widget.updateDOM(this.dom,e))&&(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(e)),this.dom.contentEditable="false")}get overrideDOMText(){return this.parent?this.parent.view.state.doc.slice(this.posAtStart,this.posAtEnd):_.empty}domBoundsAround(){return null}become(e){return e instanceof Nt&&e.type==this.type&&e.widget.constructor==this.widget.constructor?(e.widget.eq(this.widget)||this.markDirty(!0),this.dom&&!this.prevWidget&&(this.prevWidget=this.widget),this.widget=e.widget,this.length=e.length,this.breakAfter=e.breakAfter,!0):!1}ignoreMutation(){return!0}ignoreEvent(e){return this.widget.ignoreEvent(e)}get isEditable(){return!1}get isWidget(){return!0}destroy(){super.destroy(),this.dom&&this.widget.destroy(this.dom)}},fr=class{constructor(e,t,i,r){this.doc=e,this.pos=t,this.end=i,this.disallowBlockEffectsFor=r,this.content=[],this.curLine=null,this.breakAtStart=0,this.pendingBuffer=0,this.bufferMarks=[],this.atCursorPos=!0,this.openStart=-1,this.openEnd=-1,this.text="",this.textOff=0,this.cursor=e.iter(),this.skip=t}posCovered(){if(this.content.length==0)return!this.breakAtStart&&this.doc.lineAt(this.pos).from!=this.pos;let e=this.content[this.content.length-1];return!e.breakAfter&&!(e instanceof Nt&&e.type==Q.WidgetBefore)}getLine(){return this.curLine||(this.content.push(this.curLine=new Ce),this.atCursorPos=!0),this.curLine}flushBuffer(e=this.bufferMarks){this.pendingBuffer&&(this.curLine.append(cs(new ti(-1),e),e.length),this.pendingBuffer=0)}addBlockWidget(e){this.flushBuffer(),this.curLine=null,this.content.push(e)}finish(e){this.pendingBuffer&&e<=this.bufferMarks.length?this.flushBuffer():this.pendingBuffer=0,this.posCovered()||this.getLine()}buildText(e,t,i){for(;e>0;){if(this.textOff==this.text.length){let{value:s,lineBreak:o,done:l}=this.cursor.next(this.skip);if(this.skip=0,l)throw new Error("Ran out of text content when drawing inline views");if(o){this.posCovered()||this.getLine(),this.content.length?this.content[this.content.length-1].breakAfter=1:this.breakAtStart=1,this.flushBuffer(),this.curLine=null,this.atCursorPos=!0,e--;continue}else this.text=s,this.textOff=0}let r=Math.min(this.text.length-this.textOff,e,512);this.flushBuffer(t.slice(t.length-i)),this.getLine().append(cs(new gt(this.text.slice(this.textOff,this.textOff+r)),t),i),this.atCursorPos=!0,this.textOff+=r,e-=r,i=0}}span(e,t,i,r){this.buildText(t-e,i,r),this.pos=t,this.openStart<0&&(this.openStart=r)}point(e,t,i,r,s,o){if(this.disallowBlockEffectsFor[o]&&i instanceof Ht){if(i.block)throw new RangeError("Block decorations may not be specified via plugins");if(t>this.doc.lineAt(this.pos).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}let l=t-e;if(i instanceof Ht)if(i.block){let{type:a}=i;a==Q.WidgetAfter&&!this.posCovered()&&this.getLine(),this.addBlockWidget(new Nt(i.widget||new Ts("div"),l,a))}else{let a=mt.create(i.widget||new Ts("span"),l,l?0:i.startSide),u=this.atCursorPos&&!a.isEditable&&s<=r.length&&(e<t||i.startSide>0),h=!a.isEditable&&(e<t||s>r.length||i.startSide<=0),c=this.getLine();this.pendingBuffer==2&&!u&&(this.pendingBuffer=0),this.flushBuffer(r),u&&(c.append(cs(new ti(1),r),s),s=r.length+Math.max(0,s-r.length)),c.append(cs(a,r),s),this.atCursorPos=h,this.pendingBuffer=h?e<t||s>r.length?1:2:0,this.pendingBuffer&&(this.bufferMarks=r.slice())}else this.doc.lineAt(this.pos).from==this.pos&&this.getLine().addLineDeco(i);l&&(this.textOff+l<=this.text.length?this.textOff+=l:(this.skip+=l-(this.text.length-this.textOff),this.text="",this.textOff=0),this.pos=t),this.openStart<0&&(this.openStart=s)}static build(e,t,i,r,s){let o=new fr(e,t,i,s);return o.openEnd=Z.spans(r,t,i,o),o.openStart<0&&(o.openStart=o.openEnd),o.finish(o.openEnd),o}};function cs(n,e){for(let t of e)n=new Ge(t,[n],n.length);return n}var Ts=class extends Ft{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}},gc=N.define(),bc=N.define(),yc=N.define(),wc=N.define(),nl=N.define(),vc=N.define(),Cc=N.define(),Sc=N.define({combine:n=>n.some(e=>e)}),xc=N.define({combine:n=>n.some(e=>e)}),wn=class{constructor(e,t="nearest",i="nearest",r=5,s=5){this.range=e,this.y=t,this.x=i,this.yMargin=r,this.xMargin=s}map(e){return e.empty?this:new wn(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin)}},Eh=ee.define({map:(n,e)=>n.map(e)});function Bt(n,e,t){let i=n.facet(wc);i.length?i[0](e):window.onerror?window.onerror(String(e),t,void 0,void 0,e):t?console.error(t+":",e):console.error(e)}var Vs=N.define({combine:n=>n.length?n[0]:!0}),qm=0,sr=N.define(),ot=class{constructor(e,t,i,r){this.id=e,this.create=t,this.domEventHandlers=i,this.extension=r(this)}static define(e,t){let{eventHandlers:i,provide:r,decorations:s}=t||{};return new ot(qm++,e,i,o=>{let l=[sr.of(o)];return s&&l.push(dr.of(a=>{let u=a.plugin(o);return u?s(u):X.none})),r&&l.push(r(o)),l})}static fromClass(e,t){return ot.define(i=>new e(i),t)}},ar=class{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(i){if(Bt(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.create(e)}catch(t){Bt(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(i){Bt(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}},kc=N.define(),Ol=N.define(),dr=N.define(),Mc=N.define(),Tc=N.define(),or=N.define(),qe=class{constructor(e,t,i,r){this.fromA=e,this.toA=t,this.fromB=i,this.toB=r}join(e){return new qe(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,i=this;for(;t>0;t--){let r=e[t-1];if(!(r.fromA>i.toA)){if(r.toA<i.fromA)break;i=i.join(r),e.splice(t-1,1)}}return e.splice(t,0,i),e}static extendWithRanges(e,t){if(t.length==0)return e;let i=[];for(let r=0,s=0,o=0,l=0;;r++){let a=r==e.length?null:e[r],u=o-l,h=a?a.fromB:1e9;for(;s<t.length&&t[s]<h;){let c=t[s],f=t[s+1],d=Math.max(l,c),p=Math.min(h,f);if(d<=p&&new qe(d+u,p+u,d,p).addToSet(i),f>h)break;s+=2}if(!a)return i;new qe(a.fromA,a.toA,a.fromB,a.toB).addToSet(i),o=a.toA,l=a.toB}}},vn=class{constructor(e,t,i){this.view=e,this.state=t,this.transactions=i,this.flags=0,this.startState=e.state,this.changes=ne.empty(this.startState.doc.length);for(let s of i)this.changes=this.changes.compose(s.changes);let r=[];this.changes.iterChangedRanges((s,o,l,a)=>r.push(new qe(s,o,l,a))),this.changedRanges=r}static create(e,t,i){return new vn(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&10)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}},ce=function(n){return n[n.LTR=0]="LTR",n[n.RTL=1]="RTL",n}(ce||(ce={})),rl=ce.LTR,Gm=ce.RTL;function Rc(n){let e=[];for(let t=0;t<n.length;t++)e.push(1<<+n[t]);return e}var jm=Rc("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"),Jm=Rc("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"),sl=Object.create(null),pt=[];for(let n of["()","[]","{}"]){let e=n.charCodeAt(0),t=n.charCodeAt(1);sl[e]=t,sl[t]=-e}function Qm(n){return n<=247?jm[n]:1424<=n&&n<=1524?2:1536<=n&&n<=1785?Jm[n-1536]:1774<=n&&n<=2220?4:8192<=n&&n<=8203?256:64336<=n&&n<=65023?4:n==8204?256:1}var Xm=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/,ei=class{constructor(e,t,i){this.from=e,this.to=t,this.level=i}get dir(){return this.level%2?Gm:rl}side(e,t){return this.dir==t==e?this.to:this.from}static find(e,t,i,r){let s=-1;for(let o=0;o<e.length;o++){let l=e[o];if(l.from<=t&&l.to>=t){if(l.level==i)return o;(s<0||(r!=0?r<0?l.from<t:l.to>t:e[s].level>l.level))&&(s=o)}}if(s<0)throw new RangeError("Index out of range");return s}},se=[];function Ym(n,e){let t=n.length,i=e==rl?1:2,r=e==rl?2:1;if(!n||i==1&&!Xm.test(n))return Dc(t);for(let o=0,l=i,a=i;o<t;o++){let u=Qm(n.charCodeAt(o));u==512?u=l:u==8&&a==4&&(u=16),se[o]=u==4?2:u,u&7&&(a=u),l=u}for(let o=0,l=i,a=i;o<t;o++){let u=se[o];if(u==128)o<t-1&&l==se[o+1]&&l&24?u=se[o]=l:se[o]=256;else if(u==64){let h=o+1;for(;h<t&&se[h]==64;)h++;let c=o&&l==8||h<t&&se[h]==8?a==1?1:8:256;for(let f=o;f<h;f++)se[f]=c;o=h-1}else u==8&&a==1&&(se[o]=1);l=u,u&7&&(a=u)}for(let o=0,l=0,a=0,u,h,c;o<t;o++)if(h=sl[u=n.charCodeAt(o)])if(h<0){for(let f=l-3;f>=0;f-=3)if(pt[f+1]==-h){let d=pt[f+2],p=d&2?i:d&4?d&1?r:i:0;p&&(se[o]=se[pt[f]]=p),l=f;break}}else{if(pt.length==189)break;pt[l++]=o,pt[l++]=u,pt[l++]=a}else if((c=se[o])==2||c==1){let f=c==i;a=f?0:1;for(let d=l-3;d>=0;d-=3){let p=pt[d+2];if(p&2)break;if(f)pt[d+2]|=2;else{if(p&4)break;pt[d+2]|=4}}}for(let o=0;o<t;o++)if(se[o]==256){let l=o+1;for(;l<t&&se[l]==256;)l++;let a=(o?se[o-1]:i)==1,u=(l<t?se[l]:i)==1,h=a==u?a?1:2:i;for(let c=o;c<l;c++)se[c]=h;o=l-1}let s=[];if(i==1)for(let o=0;o<t;){let l=o,a=se[o++]!=1;for(;o<t&&a==(se[o]!=1);)o++;if(a)for(let u=o;u>l;){let h=u,c=se[--u]!=2;for(;u>l&&c==(se[u-1]!=2);)u--;s.push(new ei(u,h,c?2:1))}else s.push(new ei(l,o,0))}else for(let o=0;o<t;){let l=o,a=se[o++]==2;for(;o<t&&a==(se[o]==2);)o++;s.push(new ei(l,o,a?1:2))}return s}function Dc(n){return[new ei(0,n,0)]}var Ac="";function Zm(n,e,t,i,r){var s;let o=i.head-n.from,l=-1;if(o==0){if(!r||!n.length)return null;e[0].level!=t&&(o=e[0].side(!1,t),l=0)}else if(o==n.length){if(r)return null;let f=e[e.length-1];f.level!=t&&(o=f.side(!0,t),l=e.length-1)}l<0&&(l=ei.find(e,o,(s=i.bidiLevel)!==null&&s!==void 0?s:-1,i.assoc));let a=e[l];o==a.side(r,t)&&(a=e[l+=r?1:-1],o=a.side(!r,t));let u=r==(a.dir==t),h=De(n.text,o,u);if(Ac=n.text.slice(Math.min(o,h),Math.max(o,h)),h!=a.side(r,t))return T.cursor(h+n.from,u?-1:1,a.level);let c=l==(r?e.length-1:0)?null:e[l+(r?1:-1)];return!c&&a.level!=t?T.cursor(r?n.to:n.from,r?-1:1,t):c&&c.level<a.level?T.cursor(c.side(!r,t)+n.from,r?1:-1,c.level):T.cursor(h+n.from,r?-1:1,a.level)}var Zt="\uFFFF",Rs=class{constructor(e,t){this.points=e,this.text="",this.lineSeparator=t.facet(U.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=Zt}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let r=e;;){this.findPointBefore(i,r),this.readNode(r);let s=r.nextSibling;if(s==t)break;let o=G.get(r),l=G.get(s);(o&&l?o.breakAfter:(o?o.breakAfter:Oh(r))||Oh(s)&&(r.nodeName!="BR"||r.cmIgnore))&&this.lineBreak(),r=s}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,r=this.lineSeparator?null:/\r\n?|\n/g;;){let s=-1,o=1,l;if(this.lineSeparator?(s=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(l=r.exec(t))&&(s=l.index,o=l[0].length),this.append(t.slice(i,s<0?t.length:s)),s<0)break;if(this.lineBreak(),o>1)for(let a of this.points)a.node==e&&a.pos>this.text.length&&(a.pos-=o-1);i=s+o}}readNode(e){if(e.cmIgnore)return;let t=G.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let r=i.iter();!r.next().done;)r.lineBreak?this.lineBreak():this.append(r.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+Math.min(t,i.offset))}};function Oh(n){return n.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(n.nodeName)}var Ds=class{constructor(e,t){this.node=e,this.offset=t,this.pos=-1}},As=class extends G{constructor(e){super(),this.view=e,this.compositionDeco=X.none,this.decorations=[],this.dynamicDecorationMap=[],this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.setDOM(e.contentDOM),this.children=[new Ce],this.children[0].setParent(this),this.updateDeco(),this.updateInner([new qe(0,0,0,e.state.doc.length)],0)}get length(){return this.view.state.doc.length}update(e){let t=e.changedRanges;this.minWidth>0&&t.length&&(t.every(({fromA:o,toA:l})=>l<this.minWidthFrom||o>this.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.view.inputState.composing<0?this.compositionDeco=X.none:(e.transactions.length||this.dirty)&&(this.compositionDeco=tg(this.view,e.changes)),(V.ie||V.chrome)&&!this.compositionDeco.size&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let i=this.decorations,r=this.updateDeco(),s=ng(i,r,e.changes);return t=qe.extendWithRanges(t,s),this.dirty==0&&t.length==0?!1:(this.updateInner(t,e.startState.doc.length),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0,this.updateChildren(e,t);let{observer:i}=this.view;i.ignore(()=>{this.dom.style.height=this.view.viewState.contentHeight+"px",this.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let s=V.chrome||V.ios?{node:i.selectionRange.focusNode,written:!1}:void 0;this.sync(this.view,s),this.dirty=0,s&&(s.written||i.selectionRange.focusNode!=s.node)&&(this.forceSelection=!0),this.dom.style.height=""});let r=[];if(this.view.viewport.from||this.view.viewport.to<this.view.state.doc.length)for(let s of this.children)s instanceof Nt&&s.widget instanceof Ps&&r.push(s.dom);i.updateGaps(r)}updateChildren(e,t){let i=this.childCursor(t);for(let r=e.length-1;;r--){let s=r>=0?e[r]:null;if(!s)break;let{fromA:o,toA:l,fromB:a,toB:u}=s,{content:h,breakAtStart:c,openStart:f,openEnd:d}=fr.build(this.view.state.doc,a,u,this.decorations,this.dynamicDecorationMap),{i:p,off:m}=i.findPos(l,1),{i:g,off:b}=i.findPos(o,-1);lc(this,g,b,p,m,h,c,f,d)}}updateSelection(e=!1,t=!1){if((e||!this.view.observer.selectionRange.focusNode)&&this.view.observer.readSelectionRange(),!(t||this.mayControlSelection()))return;let i=this.forceSelection;this.forceSelection=!1;let r=this.view.state.selection.main,s=this.domAtPos(r.anchor),o=r.empty?s:this.domAtPos(r.head);if(V.gecko&&r.empty&&eg(s)){let a=document.createTextNode("");this.view.observer.ignore(()=>s.node.insertBefore(a,s.node.childNodes[s.offset]||null)),s=o=new me(a,0),i=!0}let l=this.view.observer.selectionRange;(i||!l.focusNode||!Ss(s.node,s.offset,l.anchorNode,l.anchorOffset)||!Ss(o.node,o.offset,l.focusNode,l.focusOffset))&&(this.view.observer.ignore(()=>{V.android&&V.chrome&&this.dom.contains(l.focusNode)&&rg(l.focusNode,this.dom)&&(this.dom.blur(),this.dom.focus({preventScroll:!0}));let a=Cs(this.view.root);if(a)if(r.empty){if(V.gecko){let u=ig(s.node,s.offset);if(u&&u!=3){let h=Ec(s.node,s.offset,u==1?1:-1);h&&(s=new me(h,u==1?0:h.nodeValue.length))}}a.collapse(s.node,s.offset),r.bidiLevel!=null&&l.cursorBidiLevel!=null&&(l.cursorBidiLevel=r.bidiLevel)}else if(a.extend){a.collapse(s.node,s.offset);try{a.extend(o.node,o.offset)}catch{}}else{let u=document.createRange();r.anchor>r.head&&([s,o]=[o,s]),u.setEnd(o.node,o.offset),u.setStart(s.node,s.offset),a.removeAllRanges(),a.addRange(u)}}),this.view.observer.setSelectionRange(s,o)),this.impreciseAnchor=s.precise?null:new me(l.anchorNode,l.anchorOffset),this.impreciseHead=o.precise?null:new me(l.focusNode,l.focusOffset)}enforceCursorAssoc(){if(this.compositionDeco.size)return;let{view:e}=this,t=e.state.selection.main,i=Cs(e.root),{anchorNode:r,anchorOffset:s}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=Ce.find(this,t.head);if(!o)return;let l=o.posAtStart;if(t.head==l||t.head==l+o.length)return;let a=this.coordsAt(t.head,-1),u=this.coordsAt(t.head,1);if(!a||!u||a.bottom>u.top)return;let h=this.domAtPos(t.head+t.assoc);i.collapse(h.node,h.offset),i.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let c=e.observer.selectionRange;e.docView.posFromDOM(c.anchorNode,c.anchorOffset)!=t.from&&i.collapse(r,s)}mayControlSelection(){let e=this.view.root.activeElement;return e==this.dom||bs(this.dom,this.view.observer.selectionRange)&&!(e&&this.dom.contains(e))}nearest(e){for(let t=e;t;){let i=G.get(t);if(i&&i.rootView==this)return i;t=t.parentNode}return null}posFromDOM(e,t){let i=this.nearest(e);if(!i)throw new RangeError("Trying to find position for a DOM position outside of the document");return i.localPosFromDOM(e,t)+i.posAtStart}domAtPos(e){let{i:t,off:i}=this.childCursor().findPos(e,-1);for(;t<this.children.length-1;){let r=this.children[t];if(i<r.length||r instanceof Ce)break;t++,i=0}return this.children[t].domAtPos(i)}coordsAt(e,t){for(let i=this.length,r=this.children.length-1;;r--){let s=this.children[r],o=i-s.breakAfter-s.length;if(e>o||e==o&&s.type!=Q.WidgetBefore&&s.type!=Q.WidgetAfter&&(!r||t==2||this.children[r-1].breakAfter||this.children[r-1].type==Q.WidgetBefore&&t>-2))return s.coordsAt(e-o,t);i=o}}measureVisibleLineHeights(e){let t=[],{from:i,to:r}=e,s=this.view.contentDOM.clientWidth,o=s>Math.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,l=-1,a=this.view.textDirection==ce.LTR;for(let u=0,h=0;h<this.children.length;h++){let c=this.children[h],f=u+c.length;if(f>r)break;if(u>=i){let d=c.dom.getBoundingClientRect();if(t.push(d.height),o){let p=c.dom.lastChild,m=p?hr(p):[];if(m.length){let g=m[m.length-1],b=a?g.right-d.left:d.right-g.left;b>l&&(l=b,this.minWidth=s,this.minWidthFrom=u,this.minWidthTo=f)}}}u=f+c.breakAfter}return t}textDirectionAt(e){let{i:t}=this.childPos(e,1);return getComputedStyle(this.children[t].dom).direction=="rtl"?ce.RTL:ce.LTR}measureTextSize(){for(let s of this.children)if(s instanceof Ce){let o=s.measureTextSize();if(o)return o}let e=document.createElement("div"),t,i,r;return e.className="cm-line",e.style.width="99999px",e.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.dom.appendChild(e);let s=hr(e.firstChild)[0];t=e.getBoundingClientRect().height,i=s?s.width/27:7,r=s?s.height:t,e.remove()}),{lineHeight:t,charWidth:i,textHeight:r}}childCursor(e=this.length){let t=this.children.length;return t&&(e-=this.children[--t].length),new ks(this.children,e,t)}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,r=0;;r++){let s=r==t.viewports.length?null:t.viewports[r],o=s?s.from-1:this.length;if(o>i){let l=t.lineBlockAt(o).bottom-t.lineBlockAt(i).top;e.push(X.replace({widget:new Ps(l),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!s)break;i=s.to+1}return X.set(e)}updateDeco(){let e=this.view.state.facet(dr).map((t,i)=>(this.dynamicDecorationMap[i]=typeof t=="function")?t(this.view):t);for(let t=e.length;t<e.length+3;t++)this.dynamicDecorationMap[t]=!1;return this.decorations=[...e,this.compositionDeco,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco]}scrollIntoView(e){let{range:t}=e,i=this.coordsAt(t.head,t.empty?t.assoc:t.head>t.anchor?-1:1),r;if(!i)return;!t.empty&&(r=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(i={left:Math.min(i.left,r.left),top:Math.min(i.top,r.top),right:Math.max(i.right,r.right),bottom:Math.max(i.bottom,r.bottom)});let s=0,o=0,l=0,a=0;for(let h of this.view.state.facet(Tc).map(c=>c(this.view)))if(h){let{left:c,right:f,top:d,bottom:p}=h;c!=null&&(s=Math.max(s,c)),f!=null&&(o=Math.max(o,f)),d!=null&&(l=Math.max(l,d)),p!=null&&(a=Math.max(a,p))}let u={left:i.left-s,top:i.top-l,right:i.right+o,bottom:i.bottom+a};Fm(this.view.scrollDOM,u,t.head<t.anchor?-1:1,e.x,e.y,e.xMargin,e.yMargin,this.view.textDirection==ce.LTR)}};function eg(n){return n.node.nodeType==1&&n.node.firstChild&&(n.offset==0||n.node.childNodes[n.offset-1].contentEditable=="false")&&(n.offset==n.node.childNodes.length||n.node.childNodes[n.offset].contentEditable=="false")}var Ps=class extends Ft{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get estimatedHeight(){return this.height}};function Pc(n){let e=n.observer.selectionRange,t=e.focusNode&&Ec(e.focusNode,e.focusOffset,0);if(!t)return null;let i=n.docView.nearest(t);if(!i)return null;if(i instanceof Ce){let r=t;for(;r.parentNode!=i.dom;)r=r.parentNode;let s=r.previousSibling;for(;s&&!G.get(s);)s=s.previousSibling;let o=s?G.get(s).posAtEnd:i.posAtStart;return{from:o,to:o,node:r,text:t}}else{for(;;){let{parent:s}=i;if(!s)return null;if(s instanceof Ce)break;i=s}let r=i.posAtStart;return{from:r,to:r+i.length,node:i.dom,text:t}}}function tg(n,e){let t=Pc(n);if(!t)return X.none;let{from:i,to:r,node:s,text:o}=t,l=e.mapPos(i,1),a=Math.max(l,e.mapPos(r,-1)),{state:u}=n,h=s.nodeType==3?s.nodeValue:new Rs([],u).readRange(s.firstChild,null).text;if(a-l<h.length)if(u.doc.sliceString(l,Math.min(u.doc.length,l+h.length),Zt)==h)a=l+h.length;else if(u.doc.sliceString(Math.max(0,a-h.length),a,Zt)==h)l=a-h.length;else return X.none;else if(u.doc.sliceString(l,a,Zt)!=h)return X.none;let c=G.get(s);return c instanceof Ms?c=c.widget.topView:c&&(c.parent=null),X.set(X.replace({widget:new ol(s,o,c),inclusive:!0}).range(l,a))}var ol=class extends Ft{constructor(e,t,i){super(),this.top=e,this.text=t,this.topView=i}eq(e){return this.top==e.top&&this.text==e.text}toDOM(){return this.top}ignoreEvent(){return!1}get customView(){return Ms}};function Ec(n,e,t){if(t<=0)for(let i=n,r=e;;){if(i.nodeType==3)return i;if(i.nodeType==1&&r>0)i=i.childNodes[r-1],r=cr(i);else break}if(t>=0)for(let i=n,r=e;;){if(i.nodeType==3)return i;if(i.nodeType==1&&r<i.childNodes.length&&t>=0)i=i.childNodes[r],r=0;else break}return null}function ig(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e<n.childNodes.length&&n.childNodes[e].contentEditable=="false"?2:0)}var ll=class{constructor(){this.changes=[]}compareRange(e,t){il(e,t,this.changes)}comparePoint(e,t){il(e,t,this.changes)}};function ng(n,e,t){let i=new ll;return Z.compare(n,e,t,i),i.changes}function rg(n,e){for(let t=n;t&&t!=e;t=t.assignedSlot||t.parentNode)if(t.nodeType==1&&t.contentEditable=="false")return!0;return!1}function sg(n,e,t=1){let i=n.charCategorizer(e),r=n.doc.lineAt(e),s=e-r.from;if(r.length==0)return T.cursor(e);s==0?t=1:s==r.length&&(t=-1);let o=s,l=s;t<0?o=De(r.text,s,!1):l=De(r.text,s);let a=i(r.text.slice(o,l));for(;o>0;){let u=De(r.text,o,!1);if(i(r.text.slice(u,o))!=a)break;o=u}for(;l<r.length;){let u=De(r.text,l);if(i(r.text.slice(l,u))!=a)break;l=u}return T.range(o+r.from,l+r.from)}function og(n,e){return e.left>n?e.left-n:Math.max(0,n-e.right)}function lg(n,e){return e.top>n?e.top-n:Math.max(0,n-e.bottom)}function $o(n,e){return n.top<e.bottom-1&&n.bottom>e.top+1}function Ih(n,e){return e<n.top?{top:e,left:n.left,right:n.right,bottom:n.bottom}:n}function Vh(n,e){return e>n.bottom?{top:n.top,left:n.left,right:n.right,bottom:e}:n}function al(n,e,t){let i,r,s,o,l=!1,a,u,h,c;for(let p=n.firstChild;p;p=p.nextSibling){let m=hr(p);for(let g=0;g<m.length;g++){let b=m[g];r&&$o(r,b)&&(b=Ih(Vh(b,r.bottom),r.top));let C=og(e,b),y=lg(t,b);if(C==0&&y==0)return p.nodeType==3?Lh(p,e,t):al(p,e,t);if(!i||o>y||o==y&&s>C){i=p,r=b,s=C,o=y;let x=y?t<b.top?-1:1:C?e<b.left?-1:1:0;l=!x||(x>0?g<m.length-1:g>0)}C==0?t>b.bottom&&(!h||h.bottom<b.bottom)?(a=p,h=b):t<b.top&&(!c||c.top>b.top)&&(u=p,c=b):h&&$o(h,b)?h=Vh(h,b.bottom):c&&$o(c,b)&&(c=Ih(c,b.top))}}if(h&&h.bottom>=t?(i=a,r=h):c&&c.top<=t&&(i=u,r=c),!i)return{node:n,offset:0};let f=Math.max(r.left,Math.min(r.right,e));if(i.nodeType==3)return Lh(i,f,t);if(l&&i.contentEditable!="false")return al(i,f,t);let d=Array.prototype.indexOf.call(n.childNodes,i)+(e>=(r.left+r.right)/2?1:0);return{node:n,offset:d}}function Lh(n,e,t){let i=n.nodeValue.length,r=-1,s=1e9,o=0;for(let l=0;l<i;l++){let a=bn(n,l,l+1).getClientRects();for(let u=0;u<a.length;u++){let h=a[u];if(h.top==h.bottom)continue;o||(o=e-h.left);let c=(h.top>t?h.top-t:t-h.bottom)-1;if(h.left-1<=e&&h.right+1>=e&&c<s){let f=e>=(h.left+h.right)/2,d=f;if((V.chrome||V.gecko)&&bn(n,l).getBoundingClientRect().left==h.right&&(d=!f),c<=0)return{node:n,offset:l+(d?1:0)};r=l+(d?1:0),s=c}}}return{node:n,offset:r>-1?r:o>0?n.nodeValue.length:0}}function Oc(n,e,t,i=-1){var r,s;let o=n.contentDOM.getBoundingClientRect(),l=o.top+n.viewState.paddingTop,a,{docHeight:u}=n.viewState,{x:h,y:c}=e,f=c-l;if(f<0)return 0;if(f>u)return n.state.doc.length;for(let x=n.defaultLineHeight/2,v=!1;a=n.elementAtHeight(f),a.type!=Q.Text;)for(;f=i>0?a.bottom+x:a.top-x,!(f>=0&&f<=u);){if(v)return t?null:0;v=!0,i=-i}c=l+f;let d=a.from;if(d<n.viewport.from)return n.viewport.from==0?0:t?null:Nh(n,o,a,h,c);if(d>n.viewport.to)return n.viewport.to==n.state.doc.length?n.state.doc.length:t?null:Nh(n,o,a,h,c);let p=n.dom.ownerDocument,m=n.root.elementFromPoint?n.root:p,g=m.elementFromPoint(h,c);g&&!n.contentDOM.contains(g)&&(g=null),g||(h=Math.max(o.left+1,Math.min(o.right-1,h)),g=m.elementFromPoint(h,c),g&&!n.contentDOM.contains(g)&&(g=null));let b,C=-1;if(g&&((r=n.docView.nearest(g))===null||r===void 0?void 0:r.isEditable)!=!1){if(p.caretPositionFromPoint){let x=p.caretPositionFromPoint(h,c);x&&({offsetNode:b,offset:C}=x)}else if(p.caretRangeFromPoint){let x=p.caretRangeFromPoint(h,c);x&&({startContainer:b,startOffset:C}=x,(!n.contentDOM.contains(b)||V.safari&&ag(b,C,h)||V.chrome&&ug(b,C,h))&&(b=void 0))}}if(!b||!n.docView.dom.contains(b)){let x=Ce.find(n.docView,d);if(!x)return f>a.top+a.height/2?a.to:a.from;({node:b,offset:C}=al(x.dom,h,c))}let y=n.docView.nearest(b);if(!y)return null;if(y.isWidget&&((s=y.dom)===null||s===void 0?void 0:s.nodeType)==1){let x=y.dom.getBoundingClientRect();return e.y<x.top||e.y<=x.bottom&&e.x<=(x.left+x.right)/2?y.posAtStart:y.posAtEnd}else return y.localPosFromDOM(b,C)+y.posAtStart}function Nh(n,e,t,i,r){let s=Math.round((i-e.left)*n.defaultCharacterWidth);if(n.lineWrapping&&t.height>n.defaultLineHeight*1.5){let l=Math.floor((r-t.top)/n.defaultLineHeight);s+=l*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+vh(o,s,n.state.tabSize)}function ag(n,e,t){let i;if(n.nodeType!=3||e!=(i=n.nodeValue.length))return!1;for(let r=n.nextSibling;r;r=r.nextSibling)if(r.nodeType!=1||r.nodeName!="BR")return!1;return bn(n,i-1,i).getBoundingClientRect().left>t}function ug(n,e,t){if(e!=0)return!1;for(let r=n;;){let s=r.parentNode;if(!s||s.nodeType!=1||s.firstChild!=r)return!1;if(s.classList.contains("cm-line"))break;r=s}let i=n.nodeType==1?n.getBoundingClientRect():bn(n,0,Math.max(n.nodeValue.length,1)).getBoundingClientRect();return t-i.left>5}function hg(n,e,t,i){let r=n.state.doc.lineAt(e.head),s=!i||!n.lineWrapping?null:n.coordsAtPos(e.assoc<0&&e.head>r.from?e.head-1:e.head);if(s){let a=n.dom.getBoundingClientRect(),u=n.textDirectionAt(r.from),h=n.posAtCoords({x:t==(u==ce.LTR)?a.right-1:a.left+1,y:(s.top+s.bottom)/2});if(h!=null)return T.cursor(h,t?-1:1)}let o=Ce.find(n.docView,e.head),l=o?t?o.posAtEnd:o.posAtStart:t?r.to:r.from;return T.cursor(l,t?-1:1)}function Bh(n,e,t,i){let r=n.state.doc.lineAt(e.head),s=n.bidiSpans(r),o=n.textDirectionAt(r.from);for(let l=e,a=null;;){let u=Zm(r,s,o,l,t),h=Ac;if(!u){if(r.number==(t?n.state.doc.lines:1))return l;h=`
8
- `,r=n.state.doc.line(r.number+(t?1:-1)),s=n.bidiSpans(r),u=T.cursor(t?r.from:r.to)}if(a){if(!a(h))return l}else{if(!i)return u;a=i(h)}l=u}}function cg(n,e,t){let i=n.state.charCategorizer(e),r=i(t);return s=>{let o=i(s);return r==rt.Space&&(r=o),r==o}}function fg(n,e,t,i){let r=e.head,s=t?1:-1;if(r==(t?n.state.doc.length:0))return T.cursor(r,e.assoc);let o=e.goalColumn,l,a=n.contentDOM.getBoundingClientRect(),u=n.coordsAtPos(r),h=n.documentTop;if(u)o==null&&(o=u.left-a.left),l=s<0?u.top:u.bottom;else{let d=n.viewState.lineBlockAt(r);o==null&&(o=Math.min(a.right-a.left,n.defaultCharacterWidth*(r-d.from))),l=(s<0?d.top:d.bottom)+h}let c=a.left+o,f=i!=null?i:n.defaultLineHeight>>1;for(let d=0;;d+=10){let p=l+(f+d)*s,m=Oc(n,{x:c,y:p},!1,s);if(p<a.top||p>a.bottom||(s<0?m<r:m>r))return T.cursor(m,e.assoc,void 0,o)}}function Ko(n,e,t){let i=n.state.facet(Mc).map(r=>r(n));for(;;){let r=!1;for(let s of i)s.between(t.from-1,t.from+1,(o,l,a)=>{t.from>o&&t.from<l&&(t=e.head>t.from?T.cursor(o,1):T.cursor(l,-1),r=!0)});if(!r)return t}}var ul=class{constructor(e){this.lastKeyCode=0,this.lastKeyTime=0,this.lastTouchTime=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.chromeScrollHack=-1,this.pendingIOSKey=void 0,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastEscPress=0,this.lastContextMenu=0,this.scrollHandlers=[],this.registeredEvents=[],this.customHandlers=[],this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.mouseSelection=null;let t=(i,r)=>{this.ignoreDuringComposition(r)||r.type=="keydown"&&this.keydown(e,r)||(this.mustFlushObserver(r)&&e.observer.forceFlush(),this.runCustomHandlers(r.type,e,r)?r.preventDefault():i(e,r))};for(let i in ge){let r=ge[i];e.contentDOM.addEventListener(i,s=>{Fh(e,s)&&t(r,s)},cl[i]),this.registeredEvents.push(i)}e.scrollDOM.addEventListener("mousedown",i=>{if(i.target==e.scrollDOM&&i.clientY>e.contentDOM.getBoundingClientRect().bottom&&(t(ge.mousedown,i),!i.defaultPrevented&&i.button==2)){let r=e.contentDOM.style.minHeight;e.contentDOM.style.minHeight="100%",setTimeout(()=>e.contentDOM.style.minHeight=r,200)}}),V.chrome&&V.chrome_version==102&&e.scrollDOM.addEventListener("wheel",()=>{this.chromeScrollHack<0?e.contentDOM.style.pointerEvents="none":window.clearTimeout(this.chromeScrollHack),this.chromeScrollHack=setTimeout(()=>{this.chromeScrollHack=-1,e.contentDOM.style.pointerEvents=""},100)},{passive:!0}),this.notifiedFocused=e.hasFocus,V.safari&&e.contentDOM.addEventListener("input",()=>null)}setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}ensureHandlers(e,t){var i;let r;this.customHandlers=[];for(let s of t)if(r=(i=s.update(e).spec)===null||i===void 0?void 0:i.domEventHandlers){this.customHandlers.push({plugin:s.value,handlers:r});for(let o in r)this.registeredEvents.indexOf(o)<0&&o!="scroll"&&(this.registeredEvents.push(o),e.contentDOM.addEventListener(o,l=>{Fh(e,l)&&this.runCustomHandlers(o,e,l)&&l.preventDefault()}))}}runCustomHandlers(e,t,i){for(let r of this.customHandlers){let s=r.handlers[e];if(s)try{if(s.call(r.plugin,i,t)||i.defaultPrevented)return!0}catch(o){Bt(t.state,o)}}return!1}runScrollHandlers(e,t){this.lastScrollTop=e.scrollDOM.scrollTop,this.lastScrollLeft=e.scrollDOM.scrollLeft;for(let i of this.customHandlers){let r=i.handlers.scroll;if(r)try{r.call(i.plugin,t,e)}catch(s){Bt(e.state,s)}}}keydown(e,t){if(this.lastKeyCode=t.keyCode,this.lastKeyTime=Date.now(),t.keyCode==9&&Date.now()<this.lastEscPress+2e3)return!0;if(V.android&&V.chrome&&!t.synthetic&&(t.keyCode==13||t.keyCode==8))return e.observer.delayAndroidKey(t.key,t.keyCode),!0;let i;return V.ios&&!t.synthetic&&!t.altKey&&!t.metaKey&&((i=Ic.find(r=>r.keyCode==t.keyCode))&&!t.ctrlKey||dg.indexOf(t.key)>-1&&t.ctrlKey&&!t.shiftKey)?(this.pendingIOSKey=i||t,setTimeout(()=>this.flushIOSKey(e),250),!0):!1}flushIOSKey(e){let t=this.pendingIOSKey;return t?(this.pendingIOSKey=void 0,mn(e.contentDOM,t.key,t.keyCode)):!1}ignoreDuringComposition(e){return/^key/.test(e.type)?this.composing>0?!0:V.safari&&!V.ios&&Date.now()-this.compositionEndedAt<100?(this.compositionEndedAt=0,!0):!1:!1}mustFlushObserver(e){return e.type=="keydown"&&e.keyCode!=229}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.mouseSelection&&this.mouseSelection.update(e),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}},Ic=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],dg="dthko",Vc=[16,17,18,20,91,92,224,225];function fs(n){return n*.7+8}var hl=class{constructor(e,t,i,r){this.view=e,this.style=i,this.mustSelect=r,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParent=Hm(e.contentDOM);let s=e.contentDOM.ownerDocument;s.addEventListener("mousemove",this.move=this.move.bind(this)),s.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(U.allowMultipleSelections)&&pg(e,t),this.dragMove=mg(e,t),this.dragging=gg(e,t)&&Fc(t)==1?null:!1}start(e){this.dragging===!1&&(e.preventDefault(),this.select(e))}move(e){var t;if(e.buttons==0)return this.destroy();if(this.dragging!==!1)return;this.select(this.lastEvent=e);let i=0,r=0,s=((t=this.scrollParent)===null||t===void 0?void 0:t.getBoundingClientRect())||{left:0,top:0,right:this.view.win.innerWidth,bottom:this.view.win.innerHeight};e.clientX<=s.left?i=-fs(s.left-e.clientX):e.clientX>=s.right&&(i=fs(e.clientX-s.right)),e.clientY<=s.top?r=-fs(s.top-e.clientY):e.clientY>=s.bottom&&(r=fs(e.clientY-s.bottom)),this.setScrollSpeed(i,r)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){this.scrollParent?(this.scrollParent.scrollLeft+=this.scrollSpeed.x,this.scrollParent.scrollTop+=this.scrollSpeed.y):this.view.win.scrollBy(this.scrollSpeed.x,this.scrollSpeed.y),this.dragging===!1&&this.select(this.lastEvent)}select(e){let t=this.style.get(e,this.extend,this.multiple);(this.mustSelect||!t.eq(this.view.state.selection)||t.main.assoc!=this.view.state.selection.main.assoc)&&this.view.dispatch({selection:t,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.docChanged&&this.dragging&&(this.dragging=this.dragging.map(e.changes)),this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}};function pg(n,e){let t=n.state.facet(gc);return t.length?t[0](e):V.mac?e.metaKey:e.ctrlKey}function mg(n,e){let t=n.state.facet(bc);return t.length?t[0](e):V.mac?!e.altKey:!e.ctrlKey}function gg(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let i=Cs(n.root);if(!i||i.rangeCount==0)return!0;let r=i.getRangeAt(0).getClientRects();for(let s=0;s<r.length;s++){let o=r[s];if(o.left<=e.clientX&&o.right>=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function Fh(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=G.get(t))&&i.ignoreEvent(e))return!1;return!0}var ge=Object.create(null),cl=Object.create(null),Lc=V.ie&&V.ie_version<15||V.ios&&V.webkit_version<604;function bg(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),Nc(n,t.value)},50)}function Nc(n,e){let{state:t}=n,i,r=1,s=t.toText(e),o=s.lines==t.selection.ranges.length;if(fl!=null&&t.selection.ranges.every(a=>a.empty)&&fl==s.toString()){let a=-1;i=t.changeByRange(u=>{let h=t.doc.lineAt(u.from);if(h.from==a)return{range:u};a=h.from;let c=t.toText((o?s.line(r++).text:e)+t.lineBreak);return{changes:{from:h.from,insert:c},range:T.cursor(u.from+c.length)}})}else o?i=t.changeByRange(a=>{let u=s.line(r++);return{changes:{from:a.from,to:a.to,insert:u.text},range:T.cursor(a.from+u.length)}}):i=t.replaceSelection(s);n.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}ge.keydown=(n,e)=>{n.inputState.setSelectionOrigin("select"),e.keyCode==27?n.inputState.lastEscPress=Date.now():Vc.indexOf(e.keyCode)<0&&(n.inputState.lastEscPress=0)};ge.touchstart=(n,e)=>{n.inputState.lastTouchTime=Date.now(),n.inputState.setSelectionOrigin("select.pointer")};ge.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};cl.touchstart=cl.touchmove={passive:!0};ge.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return;let t=null;for(let i of n.state.facet(yc))if(t=i(n,e),t)break;if(!t&&e.button==0&&(t=vg(n,e)),t){let i=n.root.activeElement!=n.contentDOM;n.inputState.startMouseSelection(new hl(n,e,t,i)),i&&n.observer.ignore(()=>sc(n.contentDOM)),n.inputState.mouseSelection&&n.inputState.mouseSelection.start(e)}};function Hh(n,e,t,i){if(i==1)return T.cursor(e,t);if(i==2)return sg(n.state,e,t);{let r=Ce.find(n.docView,e),s=n.state.doc.lineAt(r?r.posAtEnd:e),o=r?r.posAtStart:s.from,l=r?r.posAtEnd:s.to;return l<n.state.doc.length&&l==s.to&&l++,T.range(o,l)}}var Bc=(n,e)=>n>=e.top&&n<=e.bottom,Wh=(n,e,t)=>Bc(e,t)&&n>=t.left&&n<=t.right;function yg(n,e,t,i){let r=Ce.find(n.docView,e);if(!r)return 1;let s=e-r.posAtStart;if(s==0)return 1;if(s==r.length)return-1;let o=r.coordsAt(s,-1);if(o&&Wh(t,i,o))return-1;let l=r.coordsAt(s,1);return l&&Wh(t,i,l)?1:o&&Bc(i,o)?-1:1}function _h(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1);return{pos:t,bias:yg(n,t,e.clientX,e.clientY)}}var wg=V.ie&&V.ie_version<=11,zh=null,Uh=0,$h=0;function Fc(n){if(!wg)return n.detail;let e=zh,t=$h;return zh=n,$h=Date.now(),Uh=!e||t>Date.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(Uh+1)%3:1}function vg(n,e){let t=_h(n,e),i=Fc(e),r=n.state.selection;return{update(s){s.docChanged&&(t.pos=s.changes.mapPos(t.pos),r=r.map(s.changes))},get(s,o,l){let a=_h(n,s),u=Hh(n,a.pos,a.bias,i);if(t.pos!=a.pos&&!o){let h=Hh(n,t.pos,t.bias,i),c=Math.min(h.from,u.from),f=Math.max(h.to,u.to);u=c<u.from?T.range(c,f):T.range(f,c)}return o?r.replaceRange(r.main.extend(u.from,u.to)):l&&r.ranges.length>1&&r.ranges.some(h=>h.eq(u))?Cg(r,u):l?r.addRange(u):T.create([u])}}}function Cg(n,e){for(let t=0;;t++)if(n.ranges[t].eq(e))return T.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}ge.dragstart=(n,e)=>{let{selection:{main:t}}=n.state,{mouseSelection:i}=n.inputState;i&&(i.dragging=t),e.dataTransfer&&(e.dataTransfer.setData("Text",n.state.sliceDoc(t.from,t.to)),e.dataTransfer.effectAllowed="copyMove")};function Kh(n,e,t,i){if(!t)return;let r=n.posAtCoords({x:e.clientX,y:e.clientY},!1);e.preventDefault();let{mouseSelection:s}=n.inputState,o=i&&s&&s.dragging&&s.dragMove?{from:s.dragging.from,to:s.dragging.to}:null,l={from:r,insert:t},a=n.state.changes(o?[o,l]:l);n.focus(),n.dispatch({changes:a,selection:{anchor:a.mapPos(r,-1),head:a.mapPos(r,1)},userEvent:o?"move.drop":"input.drop"})}ge.drop=(n,e)=>{if(!e.dataTransfer)return;if(n.state.readOnly)return e.preventDefault();let t=e.dataTransfer.files;if(t&&t.length){e.preventDefault();let i=Array(t.length),r=0,s=()=>{++r==t.length&&Kh(n,e,i.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o<t.length;o++){let l=new FileReader;l.onerror=s,l.onload=()=>{/[\x00-\x08\x0e-\x1f]{2}/.test(l.result)||(i[o]=l.result),s()},l.readAsText(t[o])}}else Kh(n,e,e.dataTransfer.getData("Text"),!0)};ge.paste=(n,e)=>{if(n.state.readOnly)return e.preventDefault();n.observer.flush();let t=Lc?null:e.clipboardData;t?(Nc(n,t.getData("text/plain")||t.getData("text/uri-text")),e.preventDefault()):bg(n)};function Sg(n,e){let t=n.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),n.focus()},50)}function xg(n){let e=[],t=[],i=!1;for(let r of n.selection.ranges)r.empty||(e.push(n.sliceDoc(r.from,r.to)),t.push(r));if(!e.length){let r=-1;for(let{from:s}of n.selection.ranges){let o=n.doc.lineAt(s);o.number>r&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),r=o.number}i=!0}return{text:e.join(n.lineBreak),ranges:t,linewise:i}}var fl=null;ge.copy=ge.cut=(n,e)=>{let{text:t,ranges:i,linewise:r}=xg(n.state);if(!t&&!r)return;fl=r?t:null;let s=Lc?null:e.clipboardData;s?(e.preventDefault(),s.clearData(),s.setData("text/plain",t)):Sg(n,t),e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"})};var Hc=$e.define();function Wc(n,e){let t=[];for(let i of n.facet(Cc)){let r=i(n,e);r&&t.push(r)}return t?n.update({effects:t,annotations:Hc.of(!0)}):null}function _c(n){setTimeout(()=>{let e=n.hasFocus;if(e!=n.inputState.notifiedFocused){let t=Wc(n.state,e);t?n.dispatch(t):n.update([])}},10)}ge.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),_c(n)};ge.blur=n=>{n.observer.clearSelectionRange(),_c(n)};ge.compositionstart=ge.compositionupdate=n=>{n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0&&(n.inputState.composing=0)};ge.compositionend=n=>{n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionFirstChange=null,V.chrome&&V.android&&n.observer.flushSoon(),setTimeout(()=>{n.inputState.composing<0&&n.docView.compositionDeco.size&&n.update([])},50)};ge.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};ge.beforeinput=(n,e)=>{var t;let i;if(V.chrome&&V.android&&(i=Ic.find(r=>r.inputType==e.inputType))&&(n.observer.delayAndroidKey(i.key,i.keyCode),i.key=="Backspace"||i.key=="Delete")){let r=((t=window.visualViewport)===null||t===void 0?void 0:t.height)||0;setTimeout(()=>{var s;(((s=window.visualViewport)===null||s===void 0?void 0:s.height)||0)>r+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}};var qh=["pre-wrap","normal","pre-line","break-spaces"],dl=class{constructor(e){this.lineWrapping=e,this.doc=_.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30,this.heightChanged=!1}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/(this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return qh.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i<e.length;i++){let r=e[i];r<0?i++:this.heightSamples[Math.floor(r*10)]||(t=!0,this.heightSamples[Math.floor(r*10)]=!0)}return t}refresh(e,t,i,r,s,o){let l=qh.indexOf(e)>-1,a=Math.round(t)!=Math.round(this.lineHeight)||this.lineWrapping!=l;if(this.lineWrapping=l,this.lineHeight=t,this.charWidth=i,this.textHeight=r,this.lineLength=s,a){this.heightSamples={};for(let u=0;u<o.length;u++){let h=o[u];h<0?u++:this.heightSamples[Math.floor(h*10)]=!0}}return a}},pl=class{constructor(e,t){this.from=e,this.heights=t,this.index=0}get more(){return this.index<this.heights.length}},st=class{constructor(e,t,i,r,s){this.from=e,this.length=t,this.top=i,this.height=r,this.type=s}get to(){return this.from+this.length}get bottom(){return this.top+this.height}join(e){let t=(Array.isArray(this.type)?this.type:[this]).concat(Array.isArray(e.type)?e.type:[e]);return new st(this.from,this.length+e.length,this.top,this.height+e.height,t)}},J=function(n){return n[n.ByPos=0]="ByPos",n[n.ByHeight=1]="ByHeight",n[n.ByPosNoHeight=2]="ByPosNoHeight",n}(J||(J={})),ys=.001,Se=class{constructor(e,t,i=2){this.length=e,this.height=t,this.flags=i}get outdated(){return(this.flags&2)>0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e,t){this.height!=t&&(Math.abs(this.height-t)>ys&&(e.heightChanged=!0),this.height=t)}replace(e,t,i){return Se.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,r){let s=this,o=i.doc;for(let l=r.length-1;l>=0;l--){let{fromA:a,toA:u,fromB:h,toB:c}=r[l],f=s.lineAt(a,J.ByPosNoHeight,i.setDoc(t),0,0),d=f.to>=u?f:s.lineAt(u,J.ByPosNoHeight,i,0,0);for(c+=d.to-u,u=d.to;l>0&&f.from<=r[l-1].toA;)a=r[l-1].fromA,h=r[l-1].fromB,l--,a<f.from&&(f=s.lineAt(a,J.ByPosNoHeight,i,0,0));h+=f.from-a,a=f.from;let p=pr.build(i.setDoc(o),e,h,c);s=s.replace(a,u,p)}return s.updateHeight(i,0)}static empty(){return new Ae(0,0)}static of(e){if(e.length==1)return e[0];let t=0,i=e.length,r=0,s=0;for(;;)if(t==i)if(r>s*2){let l=e[t-1];l.break?e.splice(--t,1,l.left,null,l.right):e.splice(--t,1,l.left,l.right),i+=1+l.break,r-=l.size}else if(s>r*2){let l=e[i];l.break?e.splice(i,1,l.left,null,l.right):e.splice(i,1,l.left,l.right),i+=2+l.break,s-=l.size}else break;else if(r<s){let l=e[t++];l&&(r+=l.size)}else{let l=e[--i];l&&(s+=l.size)}let o=0;return e[t-1]==null?(o=1,t--):e[t]==null&&(o=1,i++),new ml(Se.of(e.slice(0,t)),o,Se.of(e.slice(i)))}};Se.prototype.size=1;var Es=class extends Se{constructor(e,t,i){super(e,t),this.type=i}blockAt(e,t,i,r){return new st(r,this.length,i,this.height,this.type)}lineAt(e,t,i,r,s){return this.blockAt(0,i,r,s)}forEachLine(e,t,i,r,s,o){e<=s+this.length&&t>=s&&o(this.blockAt(0,i,r,s))}updateHeight(e,t=0,i=!1,r){return r&&r.from<=t&&r.more&&this.setHeight(e,r.heights[r.index++]),this.outdated=!1,this}toString(){return`block(${this.length})`}},Ae=class extends Es{constructor(e,t){super(e,t,Q.Text),this.collapsed=0,this.widgetHeight=0}replace(e,t,i){let r=i[0];return i.length==1&&(r instanceof Ae||r instanceof pe&&r.flags&4)&&Math.abs(this.length-r.length)<10?(r instanceof pe?r=new Ae(r.length,this.height):r.height=this.height,this.outdated||(r.outdated=!1),r):Se.of(i)}updateHeight(e,t=0,i=!1,r){return r&&r.from<=t&&r.more?this.setHeight(e,r.heights[r.index++]):(i||this.outdated)&&this.setHeight(e,Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}},pe=class extends Se{constructor(e){super(e,0)}heightMetrics(e,t){let i=e.doc.lineAt(t).number,r=e.doc.lineAt(t+this.length).number,s=r-i+1,o,l=0;if(e.lineWrapping){let a=Math.min(this.height,e.lineHeight*s);o=a/s,l=(this.height-a)/(this.length-s-1)}else o=this.height/s;return{firstLine:i,lastLine:r,perLine:o,perChar:l}}blockAt(e,t,i,r){let{firstLine:s,lastLine:o,perLine:l,perChar:a}=this.heightMetrics(t,r);if(t.lineWrapping){let u=r+Math.round(Math.max(0,Math.min(1,(e-i)/this.height))*this.length),h=t.doc.lineAt(u),c=l+h.length*a,f=Math.max(i,e-c/2);return new st(h.from,h.length,f,c,Q.Text)}else{let u=Math.max(0,Math.min(o-s,Math.floor((e-i)/l))),{from:h,length:c}=t.doc.line(s+u);return new st(h,c,i+l*u,l,Q.Text)}}lineAt(e,t,i,r,s){if(t==J.ByHeight)return this.blockAt(e,i,r,s);if(t==J.ByPosNoHeight){let{from:d,to:p}=i.doc.lineAt(e);return new st(d,p-d,0,0,Q.Text)}let{firstLine:o,perLine:l,perChar:a}=this.heightMetrics(i,s),u=i.doc.lineAt(e),h=l+u.length*a,c=u.number-o,f=r+l*c+a*(u.from-s-c);return new st(u.from,u.length,Math.max(r,Math.min(f,r+this.height-h)),h,Q.Text)}forEachLine(e,t,i,r,s,o){e=Math.max(e,s),t=Math.min(t,s+this.length);let{firstLine:l,perLine:a,perChar:u}=this.heightMetrics(i,s);for(let h=e,c=r;h<=t;){let f=i.doc.lineAt(h);if(h==e){let p=f.number-l;c+=a*p+u*(e-s-p)}let d=a+u*f.length;o(new st(f.from,f.length,c,d,Q.Text)),c+=d,h=f.to+1}}replace(e,t,i){let r=this.length-t;if(r>0){let s=i[i.length-1];s instanceof pe?i[i.length-1]=new pe(s.length+r):i.push(null,new pe(r-1))}if(e>0){let s=i[0];s instanceof pe?i[0]=new pe(e+s.length):i.unshift(new pe(e-1),null)}return Se.of(i)}decomposeLeft(e,t){t.push(new pe(e-1),null)}decomposeRight(e,t){t.push(null,new pe(this.length-e-1))}updateHeight(e,t=0,i=!1,r){let s=t+this.length;if(r&&r.from<=t+this.length&&r.more){let o=[],l=Math.max(t,r.from),a=-1;for(r.from>t&&o.push(new pe(r.from-t-1).updateHeight(e,t));l<=s&&r.more;){let h=e.doc.lineAt(l).length;o.length&&o.push(null);let c=r.heights[r.index++];a==-1?a=c:Math.abs(c-a)>=ys&&(a=-2);let f=new Ae(h,c);f.outdated=!1,o.push(f),l+=h+1}l<=s&&o.push(null,new pe(s-l).updateHeight(e,l));let u=Se.of(o);return(a<0||Math.abs(u.height-this.height)>=ys||Math.abs(a-this.heightMetrics(e,t).perLine)>=ys)&&(e.heightChanged=!0),u}else(i||this.outdated)&&(this.setHeight(e,e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}},ml=class extends Se{constructor(e,t,i){super(e.length+t+i.length,e.height+i.height,t|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,r){let s=i+this.left.height;return e<s?this.left.blockAt(e,t,i,r):this.right.blockAt(e,t,s,r+this.left.length+this.break)}lineAt(e,t,i,r,s){let o=r+this.left.height,l=s+this.left.length+this.break,a=t==J.ByHeight?e<o:e<l,u=a?this.left.lineAt(e,t,i,r,s):this.right.lineAt(e,t,i,o,l);if(this.break||(a?u.to<l:u.from>l))return u;let h=t==J.ByPosNoHeight?J.ByPosNoHeight:J.ByPos;return a?u.join(this.right.lineAt(l,h,i,o,l)):this.left.lineAt(l,h,i,r,s).join(u)}forEachLine(e,t,i,r,s,o){let l=r+this.left.height,a=s+this.left.length+this.break;if(this.break)e<a&&this.left.forEachLine(e,t,i,r,s,o),t>=a&&this.right.forEachLine(e,t,i,l,a,o);else{let u=this.lineAt(a,J.ByPos,i,r,s);e<u.from&&this.left.forEachLine(e,u.from-1,i,r,s,o),u.to>=e&&u.from<=t&&o(u),t>u.to&&this.right.forEachLine(u.to+1,t,i,l,a,o)}}replace(e,t,i){let r=this.left.length+this.break;if(t<r)return this.balanced(this.left.replace(e,t,i),this.right);if(e>this.left.length)return this.balanced(this.left,this.right.replace(e-r,t-r,i));let s=[];e>0&&this.decomposeLeft(e,s);let o=s.length;for(let l of i)s.push(l);if(e>0&&Gh(s,o-1),t<this.length){let l=s.length;this.decomposeRight(t,s),Gh(s,l)}return Se.of(s)}decomposeLeft(e,t){let i=this.left.length;if(e<=i)return this.left.decomposeLeft(e,t);t.push(this.left),this.break&&(i++,e>=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,r=i+this.break;if(e>=r)return this.right.decomposeRight(e-r,t);e<i&&this.left.decomposeRight(e,t),this.break&&e<r&&t.push(null),t.push(this.right)}balanced(e,t){return e.size>2*t.size||t.size>2*e.size?Se.of(this.break?[e,null,t]:[e,t]):(this.left=e,this.right=t,this.height=e.height+t.height,this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,i=!1,r){let{left:s,right:o}=this,l=t+s.length+this.break,a=null;return r&&r.from<=t+s.length&&r.more?a=s=s.updateHeight(e,t,i,r):s.updateHeight(e,t,i),r&&r.from<=l+o.length&&r.more?a=o=o.updateHeight(e,l,i,r):o.updateHeight(e,l,i),a?this.balanced(s,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}};function Gh(n,e){let t,i;n[e]==null&&(t=n[e-1])instanceof pe&&(i=n[e+1])instanceof pe&&n.splice(e-1,3,new pe(t.length+1+i.length))}var kg=5,pr=class{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let i=Math.min(t,this.lineEnd),r=this.nodes[this.nodes.length-1];r instanceof Ae?r.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new Ae(i-this.pos,-1)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e<t||i.heightRelevant){let r=i.widget?i.widget.estimatedHeight:0;r<0&&(r=this.oracle.lineHeight);let s=t-e;i.block?this.addBlock(new Es(s,r,i.type)):(s||r>=kg)&&this.addLineDeco(r,s)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd<this.pos&&(this.lineEnd=this.oracle.doc.lineAt(this.pos).to)}enterLine(){if(this.lineStart>-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenTo<e&&((this.writtenTo<e-1||this.nodes[this.nodes.length-1]==null)&&this.nodes.push(this.blankContent(this.writtenTo,e-1)),this.nodes.push(null)),this.pos>e&&this.nodes.push(new Ae(this.pos-e,-1)),this.writtenTo=this.pos}blankContent(e,t){let i=new pe(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof Ae)return e;let t=new Ae(0,-1);return this.nodes.push(t),t}addBlock(e){this.enterLine(),e.type==Q.WidgetAfter&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,e.type!=Q.WidgetBefore&&(this.covering=e)}addLineDeco(e,t){let i=this.ensureLine();i.length+=t,i.collapsed+=t,i.widgetHeight=Math.max(i.widgetHeight,e),this.writtenTo=this.pos=this.pos+t}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof Ae)&&!this.isCovered?this.nodes.push(new Ae(0,-1)):(this.writtenTo<this.pos||t==null)&&this.nodes.push(this.blankContent(this.writtenTo,this.pos));let i=e;for(let r of this.nodes)r instanceof Ae&&r.updateHeight(this.oracle,i),i+=r?r.length:1;return this.nodes}static build(e,t,i,r){let s=new pr(i,e);return Z.spans(t,i,r,s,0),s.finish(i)}};function Mg(n,e,t){let i=new gl;return Z.compare(n,e,t,i,0),i.changes}var gl=class{constructor(){this.changes=[]}compareRange(){}comparePoint(e,t,i,r){(e<t||i&&i.heightRelevant||r&&r.heightRelevant)&&il(e,t,this.changes,5)}};function Tg(n,e){let t=n.getBoundingClientRect(),i=n.ownerDocument,r=i.defaultView||window,s=Math.max(0,t.left),o=Math.min(r.innerWidth,t.right),l=Math.max(0,t.top),a=Math.min(r.innerHeight,t.bottom);for(let u=n.parentNode;u&&u!=i.body;)if(u.nodeType==1){let h=u,c=window.getComputedStyle(h);if((h.scrollHeight>h.clientHeight||h.scrollWidth>h.clientWidth)&&c.overflow!="visible"){let f=h.getBoundingClientRect();s=Math.max(s,f.left),o=Math.min(o,f.right),l=Math.max(l,f.top),a=u==n.parentNode?f.bottom:Math.min(a,f.bottom)}u=c.position=="absolute"||c.position=="fixed"?h.offsetParent:h.parentNode}else if(u.nodeType==11)u=u.host;else break;return{left:s-t.left,right:Math.max(s,o)-t.left,top:l-(t.top+e),bottom:Math.max(l,a)-(t.top+e)}}function Rg(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}var ur=class{constructor(e,t,i){this.from=e,this.to=t,this.size=i}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;i<e.length;i++){let r=e[i],s=t[i];if(r.from!=s.from||r.to!=s.to||r.size!=s.size)return!1}return!0}draw(e){return X.replace({widget:new bl(this.size,e)}).range(this.from,this.to)}},bl=class extends Ft{constructor(e,t){super(),this.size=e,this.vertical=t}eq(e){return e.size==this.size&&e.vertical==this.vertical}toDOM(){let e=document.createElement("div");return this.vertical?e.style.height=this.size+"px":(e.style.width=this.size+"px",e.style.height="2px",e.style.display="inline-block"),e}get estimatedHeight(){return this.vertical?this.size:-1}},Os=class{constructor(e){this.state=e,this.pixelViewport={left:0,right:window.innerWidth,top:0,bottom:0},this.inView=!0,this.paddingTop=0,this.paddingBottom=0,this.contentDOMWidth=0,this.contentDOMHeight=0,this.editorHeight=0,this.editorWidth=0,this.scaler=jh,this.scrollTarget=null,this.printing=!1,this.mustMeasureContent=!0,this.defaultTextDirection=ce.LTR,this.visibleRanges=[],this.mustEnforceCursorAssoc=!1;let t=e.facet(Ol).some(i=>typeof i!="function"&&i.class=="cm-lineWrapping");this.heightOracle=new dl(t),this.stateDeco=e.facet(dr).filter(i=>typeof i!="function"),this.heightMap=Se.empty().applyChanges(this.stateDeco,_.empty,this.heightOracle.setDoc(e.doc),[new qe(0,0,0,e.doc.length)]),this.viewport=this.getViewport(0,null),this.updateViewportLines(),this.updateForViewport(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=X.set(this.lineGaps.map(i=>i.draw(!1))),this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let r=i?t.head:t.anchor;if(!e.some(({from:s,to:o})=>r>=s&&r<=o)){let{from:s,to:o}=this.lineBlockAt(r);e.push(new pn(s,o))}}this.viewports=e.sort((i,r)=>i.from-r.from),this.scaler=this.heightMap.height<=7e6?jh:new yl(this.heightOracle,this.heightMap,this.viewports)}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(this.scaler.scale==1?e:lr(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=this.state.facet(dr).filter(u=>typeof u!="function");let r=e.changedRanges,s=qe.extendWithRanges(r,Mg(i,this.stateDeco,e?e.changes:ne.empty(this.state.doc.length))),o=this.heightMap.height;this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),s),this.heightMap.height!=o&&(e.flags|=2);let l=s.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.head<l.from||t.range.head>l.to)||!this.viewportIsAppropriate(l))&&(l=this.getViewport(0,t));let a=!e.changes.empty||e.flags&2||l.from!=this.viewport.from||l.to!=this.viewport.to;this.viewport=l,this.updateForViewport(),a&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>2e3<<1)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&e.selectionSet&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(xc)&&(this.mustEnforceCursorAssoc=!0)}measure(e){let t=e.contentDOM,i=window.getComputedStyle(t),r=this.heightOracle,s=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?ce.RTL:ce.LTR;let o=this.heightOracle.mustRefreshForWrapping(s),l=t.getBoundingClientRect(),a=o||this.mustMeasureContent||this.contentDOMHeight!=l.height;this.contentDOMHeight=l.height,this.mustMeasureContent=!1;let u=0,h=0,c=parseInt(i.paddingTop)||0,f=parseInt(i.paddingBottom)||0;(this.paddingTop!=c||this.paddingBottom!=f)&&(this.paddingTop=c,this.paddingBottom=f,u|=10),this.editorWidth!=e.scrollDOM.clientWidth&&(r.lineWrapping&&(a=!0),this.editorWidth=e.scrollDOM.clientWidth,u|=8);let d=(this.printing?Rg:Tg)(t,this.paddingTop),p=d.top-this.pixelViewport.top,m=d.bottom-this.pixelViewport.bottom;this.pixelViewport=d;let g=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(g!=this.inView&&(this.inView=g,g&&(a=!0)),!this.inView&&!this.scrollTarget)return 0;let b=l.width;if((this.contentDOMWidth!=b||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=l.width,this.editorHeight=e.scrollDOM.clientHeight,u|=8),a){let y=e.docView.measureVisibleLineHeights(this.viewport);if(r.mustRefreshForHeights(y)&&(o=!0),o||r.lineWrapping&&Math.abs(b-this.contentDOMWidth)>r.charWidth){let{lineHeight:x,charWidth:v,textHeight:w}=e.docView.measureTextSize();o=x>0&&r.refresh(s,x,v,w,b/v,y),o&&(e.docView.minWidth=0,u|=8)}p>0&&m>0?h=Math.max(p,m):p<0&&m<0&&(h=Math.min(p,m)),r.heightChanged=!1;for(let x of this.viewports){let v=x.from==this.viewport.from?y:e.docView.measureVisibleLineHeights(x);this.heightMap=(o?Se.empty().applyChanges(this.stateDeco,_.empty,this.heightOracle,[new qe(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(r,0,o,new pl(x.from,v))}r.heightChanged&&(u|=2)}let C=!this.viewportIsAppropriate(this.viewport,h)||this.scrollTarget&&(this.scrollTarget.range.head<this.viewport.from||this.scrollTarget.range.head>this.viewport.to);return C&&(this.viewport=this.getViewport(h,this.scrollTarget)),this.updateForViewport(),(u&2||C)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>2e3<<1)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),u|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),u}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),r=this.heightMap,s=this.heightOracle,{visibleTop:o,visibleBottom:l}=this,a=new pn(r.lineAt(o-i*1e3,J.ByHeight,s,0,0).from,r.lineAt(l+(1-i)*1e3,J.ByHeight,s,0,0).to);if(t){let{head:u}=t.range;if(u<a.from||u>a.to){let h=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),c=r.lineAt(u,J.ByPos,s,0,0),f;t.y=="center"?f=(c.top+c.bottom)/2-h/2:t.y=="start"||t.y=="nearest"&&u<a.from?f=c.top:f=c.bottom-h,a=new pn(r.lineAt(f-1e3/2,J.ByHeight,s,0,0).from,r.lineAt(f+h+1e3/2,J.ByHeight,s,0,0).to)}}return a}mapViewport(e,t){let i=t.mapPos(e.from,-1),r=t.mapPos(e.to,1);return new pn(this.heightMap.lineAt(i,J.ByPos,this.heightOracle,0,0).from,this.heightMap.lineAt(r,J.ByPos,this.heightOracle,0,0).to)}viewportIsAppropriate({from:e,to:t},i=0){if(!this.inView)return!0;let{top:r}=this.heightMap.lineAt(e,J.ByPos,this.heightOracle,0,0),{bottom:s}=this.heightMap.lineAt(t,J.ByPos,this.heightOracle,0,0),{visibleTop:o,visibleBottom:l}=this;return(e==0||r<=o-Math.max(10,Math.min(-i,250)))&&(t==this.state.doc.length||s>=l+Math.max(10,Math.min(i,250)))&&r>o-2*1e3&&s<l+2*1e3}mapLineGaps(e,t){if(!e.length||t.empty)return e;let i=[];for(let r of e)t.touchesRange(r.from,r.to)||i.push(new ur(t.mapPos(r.from),t.mapPos(r.to),r.size));return i}ensureLineGaps(e,t){let i=this.heightOracle.lineWrapping,r=i?1e4:2e3,s=r>>1,o=r<<1;if(this.defaultTextDirection!=ce.LTR&&!i)return[];let l=[],a=(u,h,c,f)=>{if(h-u<s)return;let d=this.state.selection.main,p=[d.from];d.empty||p.push(d.to);for(let g of p)if(g>u&&g<h){a(u,g-10,c,f),a(g+10,h,c,f);return}let m=Ag(e,g=>g.from>=c.from&&g.to<=c.to&&Math.abs(g.from-u)<s&&Math.abs(g.to-h)<s&&!p.some(b=>g.from<b&&g.to>b));if(!m){if(h<c.to&&t&&i&&t.visibleRanges.some(g=>g.from<=h&&g.to>=h)){let g=t.moveToLineBoundary(T.cursor(h),!1,!0).head;g>u&&(h=g)}m=new ur(u,h,this.gapSize(c,u,h,f))}l.push(m)};for(let u of this.viewportLines){if(u.length<o)continue;let h=Dg(u.from,u.to,this.stateDeco);if(h.total<o)continue;let c=this.scrollTarget?this.scrollTarget.range.head:null,f,d;if(i){let p=r/this.heightOracle.lineLength*this.heightOracle.lineHeight,m,g;if(c!=null){let b=ps(h,c),C=((this.visibleBottom-this.visibleTop)/2+p)/u.height;m=b-C,g=b+C}else m=(this.visibleTop-u.top-p)/u.height,g=(this.visibleBottom-u.top+p)/u.height;f=ds(h,m),d=ds(h,g)}else{let p=h.total*this.heightOracle.charWidth,m=r*this.heightOracle.charWidth,g,b;if(c!=null){let C=ps(h,c),y=((this.pixelViewport.right-this.pixelViewport.left)/2+m)/p;g=C-y,b=C+y}else g=(this.pixelViewport.left-m)/p,b=(this.pixelViewport.right+m)/p;f=ds(h,g),d=ds(h,b)}f>u.from&&a(u.from,f,u,h),d<u.to&&a(d,u.to,u,h)}return l}gapSize(e,t,i,r){let s=ps(r,i)-ps(r,t);return this.heightOracle.lineWrapping?e.height*s:r.total*this.heightOracle.charWidth*s}updateLineGaps(e){ur.same(e,this.lineGaps)||(this.lineGaps=e,this.lineGapDeco=X.set(e.map(t=>t.draw(this.heightOracle.lineWrapping))))}computeVisibleRanges(){let e=this.stateDeco;this.lineGaps.length&&(e=e.concat(this.lineGapDeco));let t=[];Z.spans(e,this.viewport.from,this.viewport.to,{span(r,s){t.push({from:r,to:s})},point(){}},20);let i=t.length!=this.visibleRanges.length||this.visibleRanges.some((r,s)=>r.from!=t[s].from||r.to!=t[s].to);return this.visibleRanges=t,i?4:0}lineBlockAt(e){return e>=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||lr(this.heightMap.lineAt(e,J.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return lr(this.heightMap.lineAt(this.scaler.fromDOM(e),J.ByHeight,this.heightOracle,0,0),this.scaler)}elementAtHeight(e){return lr(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}},pn=class{constructor(e,t){this.from=e,this.to=t}};function Dg(n,e,t){let i=[],r=n,s=0;return Z.spans(t,n,e,{span(){},point(o,l){o>r&&(i.push({from:r,to:o}),s+=o-r),r=l}},20),r<e&&(i.push({from:r,to:e}),s+=e-r),{total:s,ranges:i}}function ds({total:n,ranges:e},t){if(t<=0)return e[0].from;if(t>=1)return e[e.length-1].to;let i=Math.floor(n*t);for(let r=0;;r++){let{from:s,to:o}=e[r],l=o-s;if(i<=l)return s+i;i-=l}}function ps(n,e){let t=0;for(let{from:i,to:r}of n.ranges){if(e<=r){t+=e-i;break}t+=r-i}return t/n.total}function Ag(n,e){for(let t of n)if(e(t))return t}var jh={toDOM(n){return n},fromDOM(n){return n},scale:1},yl=class{constructor(e,t,i){let r=0,s=0,o=0;this.viewports=i.map(({from:l,to:a})=>{let u=t.lineAt(l,J.ByPos,e,0,0).top,h=t.lineAt(a,J.ByPos,e,0,0).bottom;return r+=h-u,{from:l,to:a,top:u,bottom:h,domTop:0,domBottom:0}}),this.scale=(7e6-r)/(t.height-r);for(let l of this.viewports)l.domTop=o+(l.top-s)*this.scale,o=l.domBottom=l.domTop+(l.bottom-l.top),s=l.bottom}toDOM(e){for(let t=0,i=0,r=0;;t++){let s=t<this.viewports.length?this.viewports[t]:null;if(!s||e<s.top)return r+(e-i)*this.scale;if(e<=s.bottom)return s.domTop+(e-s.top);i=s.bottom,r=s.domBottom}}fromDOM(e){for(let t=0,i=0,r=0;;t++){let s=t<this.viewports.length?this.viewports[t]:null;if(!s||e<s.domTop)return i+(e-r)/this.scale;if(e<=s.domBottom)return s.top+(e-s.domTop);i=s.bottom,r=s.domBottom}}};function lr(n,e){if(e.scale==1)return n;let t=e.toDOM(n.top),i=e.toDOM(n.bottom);return new st(n.from,n.length,t,i-t,Array.isArray(n.type)?n.type.map(r=>lr(r,e)):n.type)}var ms=N.define({combine:n=>n.join(" ")}),wl=N.define({combine:n=>n.indexOf(!0)>-1}),vl=Ke.newName(),zc=Ke.newName(),Uc=Ke.newName(),$c={"&light":"."+zc,"&dark":"."+Uc};function Cl(n,e,t){return new Ke(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,r=>{if(r=="&")return n;if(!t||!t[r])throw new RangeError(`Unsupported selector: ${r}`);return t[r]}):n+" "+i}})}var Pg=Cl("."+vl,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#444"},".cm-dropCursor":{position:"absolute"},"&.cm-focused .cm-cursor":{display:"block"},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",left:0,zIndex:200},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",borderRight:"1px solid #ddd"},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top"},".cm-highlightSpace:before":{content:"attr(data-display)",position:"absolute",pointerEvents:"none",color:"#888"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},$c),Sl=class{constructor(e,t,i,r){this.typeOver=r,this.bounds=null,this.text="";let{impreciseHead:s,impreciseAnchor:o}=e.docView;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=e.docView.domBoundsAround(t,i,0))){let l=s||o?[]:Og(e),a=new Rs(l,e.state);a.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=a.text,this.newSel=Ig(l,this.bounds.from)}else{let l=e.observer.selectionRange,a=s&&s.node==l.focusNode&&s.offset==l.focusOffset||!gn(e.contentDOM,l.focusNode)?e.state.selection.main.head:e.docView.posFromDOM(l.focusNode,l.focusOffset),u=o&&o.node==l.anchorNode&&o.offset==l.anchorOffset||!gn(e.contentDOM,l.anchorNode)?e.state.selection.main.anchor:e.docView.posFromDOM(l.anchorNode,l.anchorOffset);this.newSel=T.single(u,a)}}};function Kc(n,e){let t,{newSel:i}=e,r=n.state.selection.main;if(e.bounds){let{from:s,to:o}=e.bounds,l=r.from,a=null;(n.inputState.lastKeyCode===8&&n.inputState.lastKeyTime>Date.now()-100||V.android&&e.text.length<o-s)&&(l=r.to,a="end");let u=Eg(n.state.doc.sliceString(s,o,Zt),e.text,l-s,a);u&&(V.chrome&&n.inputState.lastKeyCode==13&&u.toB==u.from+2&&e.text.slice(u.from,u.toB)==Zt+Zt&&u.toB--,t={from:s+u.from,to:s+u.toA,insert:_.of(e.text.slice(u.from,u.toB).split(Zt))})}else i&&(!n.hasFocus&&n.state.facet(Vs)||i.main.eq(r))&&(i=null);if(!t&&!i)return!1;if(!t&&e.typeOver&&!r.empty&&i&&i.main.empty?t={from:r.from,to:r.to,insert:n.state.doc.slice(r.from,r.to)}:t&&t.from>=r.from&&t.to<=r.to&&(t.from!=r.from||t.to!=r.to)&&r.to-r.from-(t.to-t.from)<=4?t={from:r.from,to:r.to,insert:n.state.doc.slice(r.from,t.from).append(t.insert).append(n.state.doc.slice(t.to,r.to))}:(V.mac||V.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&n.contentDOM.getAttribute("autocorrect")=="off"?(i&&t.insert.length==2&&(i=T.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:_.of([" "])}):V.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==`
9
- `&&n.lineWrapping&&(i&&(i=T.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:_.of([" "])}),t){let s=n.state;if(V.ios&&n.inputState.flushIOSKey(n)||V.android&&(t.from==r.from&&t.to==r.to&&t.insert.length==1&&t.insert.lines==2&&mn(n.contentDOM,"Enter",13)||t.from==r.from-1&&t.to==r.to&&t.insert.length==0&&mn(n.contentDOM,"Backspace",8)||t.from==r.from&&t.to==r.to+1&&t.insert.length==0&&mn(n.contentDOM,"Delete",46)))return!0;let o=t.insert.toString();if(n.state.facet(vc).some(u=>u(n,t.from,t.to,o)))return!0;n.inputState.composing>=0&&n.inputState.composing++;let l;if(t.from>=r.from&&t.to<=r.to&&t.to-t.from>=(r.to-r.from)/3&&(!i||i.main.empty&&i.main.from==t.from+t.insert.length)&&n.inputState.composing<0){let u=r.from<t.from?s.sliceDoc(r.from,t.from):"",h=r.to>t.to?s.sliceDoc(t.to,r.to):"";l=s.replaceSelection(n.state.toText(u+t.insert.sliceString(0,void 0,n.state.lineBreak)+h))}else{let u=s.changes(t),h=i&&!s.selection.main.eq(i.main)&&i.main.to<=u.newLength?i.main:void 0;if(s.selection.ranges.length>1&&n.inputState.composing>=0&&t.to<=r.to&&t.to>=r.to-10){let c=n.state.sliceDoc(t.from,t.to),f=Pc(n)||n.state.doc.lineAt(r.head),d=r.to-t.to,p=r.to-r.from;l=s.changeByRange(m=>{if(m.from==r.from&&m.to==r.to)return{changes:u,range:h||m.map(u)};let g=m.to-d,b=g-c.length;if(m.to-m.from!=p||n.state.sliceDoc(b,g)!=c||f&&m.to>=f.from&&m.from<=f.to)return{range:m};let C=s.changes({from:b,to:g,insert:t.insert}),y=m.to-r.to;return{changes:C,range:h?T.range(Math.max(0,h.anchor+y),Math.max(0,h.head+y)):m.map(C)}})}else l={changes:u,selection:h&&s.selection.replaceRange(h)}}let a="input.type";return n.composing&&(a+=".compose",n.inputState.compositionFirstChange&&(a+=".start",n.inputState.compositionFirstChange=!1)),n.dispatch(l,{scrollIntoView:!0,userEvent:a}),!0}else if(i&&!i.main.eq(r)){let s=!1,o="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(s=!0),o=n.inputState.lastSelectionOrigin),n.dispatch({selection:i,scrollIntoView:s,userEvent:o}),!0}else return!1}function Eg(n,e,t,i){let r=Math.min(n.length,e.length),s=0;for(;s<r&&n.charCodeAt(s)==e.charCodeAt(s);)s++;if(s==r&&n.length==e.length)return null;let o=n.length,l=e.length;for(;o>0&&l>0&&n.charCodeAt(o-1)==e.charCodeAt(l-1);)o--,l--;if(i=="end"){let a=Math.max(0,s-Math.min(o,l));t-=o+a-s}if(o<s&&n.length<e.length){let a=t<=s&&t>=o?s-t:0;s-=a,l=s+(l-o),o=s}else if(l<s){let a=t<=s&&t>=l?s-t:0;s-=a,o=s+(o-l),l=s}return{from:s,toA:o,toB:l}}function Og(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:r,focusOffset:s}=n.observer.selectionRange;return t&&(e.push(new Ds(t,i)),(r!=t||s!=i)&&e.push(new Ds(r,s))),e}function Ig(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t>-1&&i>-1?T.single(t+e,i+e):null}var Vg={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},qo=V.ie&&V.ie_version<=11,xl=class{constructor(e){this.view=e,this.active=!1,this.selectionRange=new jo,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.resizeContent=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);(V.ie&&V.ie_version<=11||V.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),qo&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate)<Date.now()-75&&this.onResize()}),this.resizeScroll.observe(e.scrollDOM),this.resizeContent=new ResizeObserver(()=>this.view.requestMeasure()),this.resizeContent.observe(e.contentDOM)),this.addWindowListeners(this.win=e.win),this.start(),typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(t=>{this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runScrollHandlers(this.view,e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(){this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500)}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,i)=>t!=e[i]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:i}=this,r=this.selectionRange;if(i.state.facet(Vs)?i.root.activeElement!=this.dom:!bs(i.dom,r))return;let s=r.anchorNode&&i.docView.nearest(r.anchorNode);if(s&&s.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(V.ie&&V.ie_version<=11||V.android&&V.chrome)&&!i.state.selection.main.empty&&r.focusNode&&Ss(r.focusNode,r.focusOffset,r.anchorNode,r.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=V.safari&&e.root.nodeType==11&&Nm(this.dom.ownerDocument)==this.dom&&Lg(this.view)||Cs(e.root);if(!t||this.selectionRange.eq(t))return!1;let i=bs(this.dom,t);return i&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime<Date.now()-300&&_m(this.dom,t)?(this.view.inputState.lastFocusTime=0,e.docView.updateSelection(),!1):(this.selectionRange.setRange(t),i&&(this.selectionChanged=!0),!0)}setSelectionRange(e,t){this.selectionRange.set(e.node,e.offset,t.node,t.offset),this.selectionChanged=!1}clearSelectionRange(){this.selectionRange.set(null,0,null,0)}listenForScroll(){this.parentCheck=-1;let e=0,t=null;for(let i=this.dom;i;)if(i.nodeType==1)!t&&e<this.scrollTargets.length&&this.scrollTargets[e]==i?e++:t||(t=this.scrollTargets.slice(0,e)),t&&t.push(i),i=i.assignedSlot||i.parentNode;else if(i.nodeType==11)i=i.host;else break;if(e<this.scrollTargets.length&&!t&&(t=this.scrollTargets.slice(0,e)),t){for(let i of this.scrollTargets)i.removeEventListener("scroll",this.onScroll);for(let i of this.scrollTargets=t)i.addEventListener("scroll",this.onScroll)}}ignore(e){if(!this.active)return e();try{return this.stop(),e()}finally{this.start(),this.clear()}}start(){this.active||(this.observer.observe(this.dom,Vg),qo&&this.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.active=!0)}stop(){this.active&&(this.active=!1,this.observer.disconnect(),qo&&this.dom.removeEventListener("DOMCharacterDataModified",this.onCharData))}clear(){this.processRecords(),this.queue.length=0,this.selectionChanged=!1}delayAndroidKey(e,t){var i;if(!this.delayedAndroidKey){let r=()=>{let s=this.delayedAndroidKey;s&&(this.clearDelayedAndroidKey(),!this.flush()&&s.force&&mn(this.dom,s.key,s.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(r)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange<Date.now()-50||!!(!((i=this.delayedAndroidKey)===null||i===void 0)&&i.force)})}clearDelayedAndroidKey(){this.win.cancelAnimationFrame(this.flushingAndroidKey),this.delayedAndroidKey=null,this.flushingAndroidKey=-1}flushSoon(){this.delayedFlush<0&&(this.delayedFlush=this.view.win.requestAnimationFrame(()=>{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}processRecords(){let e=this.queue;for(let s of this.observer.takeRecords())e.push(s);e.length&&(this.queue=[]);let t=-1,i=-1,r=!1;for(let s of e){let o=this.readMutation(s);o&&(o.typeOver&&(r=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:r}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),r=this.selectionChanged&&bs(this.dom,this.selectionRange);return e<0&&!r?null:(e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1,new Sl(this.view,e,t,i))}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return!1;let i=this.view.state,r=Kc(this.view,t);return this.view.state==i&&this.view.update([]),r}readMutation(e){let t=this.view.docView.nearest(e.target);if(!t||t.ignoreMutation(e))return null;if(t.markDirty(e.type=="attributes"),e.type=="attributes"&&(t.dirty|=4),e.type=="childList"){let i=Jh(t,e.previousSibling||e.target.previousSibling,-1),r=Jh(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:r?t.posBefore(r):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}destroy(){var e,t,i,r;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resizeScroll)===null||i===void 0||i.disconnect(),(r=this.resizeContent)===null||r===void 0||r.disconnect();for(let s of this.scrollTargets)s.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey)}};function Jh(n,e,t){for(;e;){let i=G.get(e);if(i&&i.parent==n)return i;let r=e.parentNode;e=r!=n.dom?r:t>0?e.nextSibling:e.previousSibling}return null}function Lg(n){let e=null;function t(a){a.preventDefault(),a.stopImmediatePropagation(),e=a.getTargetRanges()[0]}if(n.contentDOM.addEventListener("beforeinput",t,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",t,!0),!e)return null;let i=e.startContainer,r=e.startOffset,s=e.endContainer,o=e.endOffset,l=n.docView.domAtPos(n.state.selection.main.anchor);return Ss(l.node,l.offset,s,o)&&([i,r,s,o]=[s,o,i,r]),{anchorNode:i,anchorOffset:r,focusNode:s,focusOffset:o}}var H=class{constructor(e={}){this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.style.cssText="position: fixed; top: -10000px",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),this._dispatch=e.dispatch||(t=>this.update([t])),this.dispatch=this.dispatch.bind(this),this._root=e.root||Wm(e.parent)||document,this.viewState=new Os(e.state||U.create(e)),this.plugins=this.state.facet(sr).map(t=>new ar(t));for(let t of this.plugins)t.update(this);this.observer=new xl(this),this.inputState=new ul(this),this.inputState.ensureHandlers(this,this.plugins),this.docView=new As(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),e.parent&&e.parent.appendChild(this.dom)}get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return this.inputState.composing>0}get compositionStarted(){return this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}dispatch(...e){this._dispatch(e.length==1&&e[0]instanceof re?e[0]:this.state.update(...e))}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,i=!1,r,s=this.state;for(let f of e){if(f.startState!=s)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");s=f.state}if(this.destroyed){this.viewState.state=s;return}let o=this.hasFocus,l=0,a=null;e.some(f=>f.annotation(Hc))?(this.inputState.notifiedFocused=o,l=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,a=Wc(s,o),a||(l=1));let u=this.observer.delayedAndroidKey,h=null;if(u?(this.observer.clearDelayedAndroidKey(),h=this.observer.readChange(),(h&&!this.state.doc.eq(s.doc)||!this.state.selection.eq(s.selection))&&(h=null)):this.observer.clear(),s.facet(U.phrases)!=this.state.facet(U.phrases))return this.setState(s);r=vn.create(this,s,e),r.flags|=l;let c=this.viewState.scrollTarget;try{this.updateState=2;for(let f of e){if(c&&(c=c.map(f.changes)),f.scrollIntoView){let{main:d}=f.state.selection;c=new wn(d.empty?d:T.cursor(d.head,d.head>d.anchor?-1:1))}for(let d of f.effects)d.is(Eh)&&(c=d.value)}this.viewState.update(r,c),this.bidiCache=Cn.update(this.bidiCache,r.changes),r.empty||(this.updatePlugins(r),this.inputState.update(r)),t=this.docView.update(r),this.state.facet(or)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(f=>f.isUserEvent("select.pointer")))}finally{this.updateState=0}if(r.startState.facet(ms)!=r.state.facet(ms)&&(this.viewState.mustMeasureContent=!0),(t||i||c||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),!r.empty)for(let f of this.state.facet(nl))f(r);(a||h)&&Promise.resolve().then(()=>{a&&this.state==a.startState&&this.dispatch(a),h&&!Kc(this,h)&&u.force&&mn(this.contentDOM,u.key,u.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let i of this.plugins)i.destroy(this);this.viewState=new Os(e),this.plugins=e.facet(sr).map(i=>new ar(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView=new As(this),this.inputState.ensureHandlers(this,this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(sr),i=e.state.facet(sr);if(t!=i){let r=[];for(let s of i){let o=t.indexOf(s);if(o<0)r.push(new ar(s));else{let l=this.plugins[o];l.mustUpdate=e,r.push(l)}}for(let s of this.plugins)s.mustUpdate!=e&&s.destroy(this);this.plugins=r,this.pluginMap.clear(),this.inputState.ensureHandlers(this,this.plugins)}else for(let r of this.plugins)r.mustUpdate=e;for(let r=0;r<this.plugins.length;r++)this.plugins[r].update(this)}measure(e=!0){if(this.destroyed)return;this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,{scrollHeight:i,scrollTop:r,clientHeight:s}=this.scrollDOM,o=r>i-s-4?i:r;try{for(let l=0;;l++){this.updateState=1;let a=this.viewport,u=this.viewState.lineBlockAtHeight(o),h=this.viewState.measure(this);if(!h&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(l>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let c=[];h&4||([this.measureRequests,c]=[c,this.measureRequests]);let f=c.map(g=>{try{return g.read(this)}catch(b){return Bt(this.state,b),Qh}}),d=vn.create(this,this.state,[]),p=!1,m=!1;d.flags|=h,t?t.flags|=h:t=d,this.updateState=2,d.empty||(this.updatePlugins(d),this.inputState.update(d),this.updateAttrs(),p=this.docView.update(d));for(let g=0;g<c.length;g++)if(f[g]!=Qh)try{let b=c[g];b.write&&b.write(f[g],this)}catch(b){Bt(this.state,b)}if(this.viewState.editorHeight)if(this.viewState.scrollTarget)this.docView.scrollIntoView(this.viewState.scrollTarget),this.viewState.scrollTarget=null,m=!0;else{let g=this.viewState.lineBlockAt(u.from).top-u.top;(g>1||g<-1)&&(this.scrollDOM.scrollTop+=g,m=!0)}if(p&&this.docView.updateSelection(!0),this.viewport.from==a.from&&this.viewport.to==a.to&&!m&&this.measureRequests.length==0)break}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let l of this.state.facet(nl))l(t)}get themeClasses(){return vl+" "+(this.state.facet(wl)?Uc:zc)+" "+this.state.facet(ms)}updateAttrs(){let e=Xh(this,kc,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",translate:"no",contenteditable:this.state.facet(Vs)?"true":"false",class:"cm-content",style:`${V.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),Xh(this,Ol,t);let i=this.observer.ignore(()=>{let r=tl(this.contentDOM,this.contentAttrs,t),s=tl(this.dom,this.editorAttrs,e);return r||s});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let r of i.effects)if(r.is(H.announce)){t&&(this.announceDOM.textContent=""),t=!1;let s=this.announceDOM.appendChild(document.createElement("div"));s.textContent=r.value}}mountStyles(){this.styleModules=this.state.facet(or),Ke.mount(this.root,this.styleModules.concat(Pg).reverse())}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;t<this.measureRequests.length;t++)if(this.measureRequests[t].key===e.key){this.measureRequests[t]=e;return}}this.measureRequests.push(e)}}plugin(e){let t=this.pluginMap.get(e);return(t===void 0||t&&t.spec!=e)&&this.pluginMap.set(e,t=this.plugins.find(i=>i.spec==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,i){return Ko(this,e,Bh(this,e,t,i))}moveByGroup(e,t){return Ko(this,e,Bh(this,e,t,i=>cg(this,e.head,i)))}moveToLineBoundary(e,t,i=!0){return hg(this,e,t,i)}moveVertically(e,t,i){return Ko(this,e,fg(this,e,t,i))}domAtPos(e){return this.docView.domAtPos(e)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){return this.readMeasured(),Oc(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.docView.coordsAt(e,t);if(!i||i.left==i.right)return i;let r=this.state.doc.lineAt(e),s=this.bidiSpans(r),o=s[ei.find(s,e-r.from,-1,t)];return Al(i,o.dir==ce.LTR==t>0)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(Sc)||e<this.viewport.from||e>this.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>Ng)return Dc(e.length);let t=this.textDirectionAt(e.from);for(let r of this.bidiCache)if(r.from==e.from&&r.dir==t)return r.order;let i=Ym(e.text,t);return this.bidiCache.push(new Cn(e.from,e.to,t,i)),i}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||V.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{sc(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){return Eh.of(new wn(typeof e=="number"?T.cursor(e):e,t.y,t.x,t.yMargin,t.xMargin))}static domEventHandlers(e){return ot.define(()=>({}),{eventHandlers:e})}static theme(e,t){let i=Ke.newName(),r=[ms.of(i),or.of(Cl(`.${i}`,e))];return t&&t.dark&&r.push(wl.of(!0)),r}static baseTheme(e){return hn.lowest(or.of(Cl("."+vl,e,$c)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),r=i&&G.get(i)||G.get(e);return((t=r==null?void 0:r.rootView)===null||t===void 0?void 0:t.view)||null}};H.styleModule=or;H.inputHandler=vc;H.focusChangeEffect=Cc;H.perLineTextDirection=Sc;H.exceptionSink=wc;H.updateListener=nl;H.editable=Vs;H.mouseSelectionStyle=yc;H.dragMovesSelection=bc;H.clickAddsSelectionRange=gc;H.decorations=dr;H.atomicRanges=Mc;H.scrollMargins=Tc;H.darkTheme=wl;H.contentAttributes=Ol;H.editorAttributes=kc;H.lineWrapping=H.contentAttributes.of({class:"cm-lineWrapping"});H.announce=ee.define();var Ng=4096,Qh={},Cn=class{constructor(e,t,i,r){this.from=e,this.to=t,this.dir=i,this.order=r}static update(e,t){if(t.empty)return e;let i=[],r=e.length?e[e.length-1].dir:ce.LTR;for(let s=Math.max(0,e.length-10);s<e.length;s++){let o=e[s];o.dir==r&&!t.touchesRange(o.from,o.to)&&i.push(new Cn(t.mapPos(o.from,1),t.mapPos(o.to,-1),o.dir,o.order))}return i}};function Xh(n,e,t){for(let i=n.state.facet(e),r=i.length-1;r>=0;r--){let s=i[r],o=typeof s=="function"?s(n):s;o&&el(o,t)}return t}var Bg=V.mac?"mac":V.windows?"win":V.linux?"linux":"key";function Fg(n,e){let t=n.split(/-(?!$)/),i=t[t.length-1];i=="Space"&&(i=" ");let r,s,o,l;for(let a=0;a<t.length-1;++a){let u=t[a];if(/^(cmd|meta|m)$/i.test(u))l=!0;else if(/^a(lt)?$/i.test(u))r=!0;else if(/^(c|ctrl|control)$/i.test(u))s=!0;else if(/^s(hift)?$/i.test(u))o=!0;else if(/^mod$/i.test(u))e=="mac"?l=!0:s=!0;else throw new Error("Unrecognized modifier name: "+u)}return r&&(i="Alt-"+i),s&&(i="Ctrl-"+i),l&&(i="Meta-"+i),o&&(i="Shift-"+i),i}function gs(n,e,t){return e.altKey&&(n="Alt-"+n),e.ctrlKey&&(n="Ctrl-"+n),e.metaKey&&(n="Meta-"+n),t!==!1&&e.shiftKey&&(n="Shift-"+n),n}var Hg=hn.default(H.domEventHandlers({keydown(n,e){return Ug(Wg(e.state),n,e,"editor")}})),gr=N.define({enables:Hg}),Yh=new WeakMap;function Wg(n){let e=n.facet(gr),t=Yh.get(e);return t||Yh.set(e,t=zg(e.reduce((i,r)=>i.concat(r),[]))),t}var Yt=null,_g=4e3;function zg(n,e=Bg){let t=Object.create(null),i=Object.create(null),r=(o,l)=>{let a=i[o];if(a==null)i[o]=l;else if(a!=l)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},s=(o,l,a,u)=>{var h,c;let f=t[o]||(t[o]=Object.create(null)),d=l.split(/ (?!$)/).map(g=>Fg(g,e));for(let g=1;g<d.length;g++){let b=d.slice(0,g).join(" ");r(b,!0),f[b]||(f[b]={preventDefault:!0,run:[C=>{let y=Yt={view:C,prefix:b,scope:o};return setTimeout(()=>{Yt==y&&(Yt=null)},_g),!0}]})}let p=d.join(" ");r(p,!1);let m=f[p]||(f[p]={preventDefault:!1,run:((c=(h=f._any)===null||h===void 0?void 0:h.run)===null||c===void 0?void 0:c.slice())||[]});a&&m.run.push(a),u&&(m.preventDefault=!0)};for(let o of n){let l=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let u of l){let h=t[u]||(t[u]=Object.create(null));h._any||(h._any={preventDefault:!1,run:[]});for(let c in h)h[c].run.push(o.any)}let a=o[e]||o.key;if(a)for(let u of l)s(u,a,o.run,o.preventDefault),o.shift&&s(u,"Shift-"+a,o.shift,o.preventDefault)}return t}function Ug(n,e,t,i){let r=kh(e),s=sn(r,0),o=ss(s)==r.length&&r!=" ",l="",a=!1;Yt&&Yt.view==t&&Yt.scope==i&&(l=Yt.prefix+" ",(a=Vc.indexOf(e.keyCode)<0)&&(Yt=null));let u=new Set,h=p=>{if(p){for(let m of p.run)if(!u.has(m)&&(u.add(m),m(t,e)))return!0;p.preventDefault&&(a=!0)}return!1},c=n[i],f,d;if(c){if(h(c[l+gs(r,e,!o)]))return!0;if(o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(V.windows&&e.ctrlKey&&e.altKey)&&(f=Lt[e.keyCode])&&f!=r){if(h(c[l+gs(f,e,!0)]))return!0;if(e.shiftKey&&(d=fn[e.keyCode])!=r&&d!=f&&h(c[l+gs(d,e,!1)]))return!0}else if(o&&e.shiftKey&&h(c[l+gs(r,e,!0)]))return!0;if(h(c._any))return!0}return a}var _i=class{constructor(e,t,i,r,s){this.className=e,this.left=t,this.top=i,this.width=r,this.height=s}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,t){return t.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,t,i){if(i.empty){let r=e.coordsAtPos(i.head,i.assoc||1);if(!r)return[];let s=qc(e);return[new _i(t,r.left-s.left,r.top-s.top,null,r.bottom-r.top)]}else return $g(e,t,i)}};function qc(n){let e=n.scrollDOM.getBoundingClientRect();return{left:(n.textDirection==ce.LTR?e.left:e.right-n.scrollDOM.clientWidth)-n.scrollDOM.scrollLeft,top:e.top-n.scrollDOM.scrollTop}}function Zh(n,e,t){let i=T.cursor(e);return{from:Math.max(t.from,n.moveToLineBoundary(i,!1,!0).from),to:Math.min(t.to,n.moveToLineBoundary(i,!0,!0).from),type:Q.Text}}function ec(n,e){let t=n.lineBlockAt(e);if(Array.isArray(t.type)){for(let i of t.type)if(i.to>e||i.to==e&&(i.to==t.to||i.type==Q.Text))return i}return t}function $g(n,e,t){if(t.to<=n.viewport.from||t.from>=n.viewport.to)return[];let i=Math.max(t.from,n.viewport.from),r=Math.min(t.to,n.viewport.to),s=n.textDirection==ce.LTR,o=n.contentDOM,l=o.getBoundingClientRect(),a=qc(n),u=o.querySelector(".cm-line"),h=u&&window.getComputedStyle(u),c=l.left+(h?parseInt(h.paddingLeft)+Math.min(0,parseInt(h.textIndent)):0),f=l.right-(h?parseInt(h.paddingRight):0),d=ec(n,i),p=ec(n,r),m=d.type==Q.Text?d:null,g=p.type==Q.Text?p:null;if(n.lineWrapping&&(m&&(m=Zh(n,i,m)),g&&(g=Zh(n,r,g))),m&&g&&m.from==g.from)return C(y(t.from,t.to,m));{let v=m?y(t.from,null,m):x(d,!1),w=g?y(null,t.to,g):x(p,!0),M=[];return(m||d).to<(g||p).from-1?M.push(b(c,v.bottom,f,w.top)):v.bottom<w.top&&n.elementAtHeight((v.bottom+w.top)/2).type==Q.Text&&(v.bottom=w.top=(v.bottom+w.top)/2),C(v).concat(M).concat(C(w))}function b(v,w,M,L){return new _i(e,v-a.left,w-a.top-.01,M-v,L-w+.01)}function C({top:v,bottom:w,horizontal:M}){let L=[];for(let E=0;E<M.length;E+=2)L.push(b(M[E],v,M[E+1],w));return L}function y(v,w,M){let L=1e9,E=-1e9,S=[];function R(z,B,Y,ke,ae){let q=n.coordsAtPos(z,z==M.to?-2:2),j=n.coordsAtPos(Y,Y==M.from?2:-2);L=Math.min(q.top,j.top,L),E=Math.max(q.bottom,j.bottom,E),ae==ce.LTR?S.push(s&&B?c:q.left,s&&ke?f:j.right):S.push(!s&&ke?c:j.left,!s&&B?f:q.right)}let O=v!=null?v:M.from,I=w!=null?w:M.to;for(let z of n.visibleRanges)if(z.to>O&&z.from<I)for(let B=Math.max(z.from,O),Y=Math.min(z.to,I);;){let ke=n.state.doc.lineAt(B);for(let ae of n.bidiSpans(ke)){let q=ae.from+ke.from,j=ae.to+ke.from;if(q>=Y)break;j>B&&R(Math.max(q,B),v==null&&q<=O,Math.min(j,Y),w==null&&j>=I,ae.dir)}if(B=ke.to+1,B>=Y)break}return S.length==0&&R(O,v==null,I,w==null,n.textDirection),{top:L,bottom:E,horizontal:S}}function x(v,w){let M=l.top+(w?v.top:v.bottom);return{top:M,bottom:M,horizontal:[]}}}function Kg(n,e){return n.constructor==e.constructor&&n.eq(e)}var kl=class{constructor(e,t){this.view=e,this.layer=t,this.drawn=[],this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),t.above&&this.dom.classList.add("cm-layer-above"),t.class&&this.dom.classList.add(t.class),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(ws)!=e.state.facet(ws)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&e.view.requestMeasure(this.measureReq)}setOrder(e){let t=0,i=e.facet(ws);for(;t<i.length&&i[t]!=this.layer;)t++;this.dom.style.zIndex=String((this.layer.above?150:-1)-t)}measure(){return this.layer.markers(this.view)}draw(e){if(e.length!=this.drawn.length||e.some((t,i)=>!Kg(t,this.drawn[i]))){let t=this.dom.firstChild,i=0;for(let r of e)r.update&&t&&r.constructor&&this.drawn[i].constructor&&r.update(t,this.drawn[i])?(t=t.nextSibling,i++):this.dom.insertBefore(r.draw(),t);for(;t;){let r=t.nextSibling;t.remove(),t=r}this.drawn=e}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}},ws=N.define();function Gc(n){return[ot.define(e=>new kl(e,n)),ws.of(n)]}var jc=!V.ios,mr=N.define({combine(n){return cn(n,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function Il(n={}){return[mr.of(n),qg,Gg,jg,xc.of(!0)]}function Jc(n){return n.startState.facet(mr)!=n.state.facet(mr)}var qg=Gc({above:!0,markers(n){let{state:e}=n,t=e.facet(mr),i=[];for(let r of e.selection.ranges){let s=r==e.selection.main;if(r.empty?!s||jc:t.drawRangeCursor){let o=s?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",l=r.empty?r:T.cursor(r.head,r.head>r.anchor?-1:1);for(let a of _i.forRange(n,o,l))i.push(a)}}return i},update(n,e){n.transactions.some(i=>i.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=Jc(n);return t&&tc(n.state,e),n.docChanged||n.selectionSet||t},mount(n,e){tc(e.state,n)},class:"cm-cursorLayer"});function tc(n,e){e.style.animationDuration=n.facet(mr).cursorBlinkRate+"ms"}var Gg=Gc({above:!1,markers(n){return n.state.selection.ranges.map(e=>e.empty?[]:_i.forRange(n,"cm-selectionBackground",e)).reduce((e,t)=>e.concat(t))},update(n,e){return n.docChanged||n.selectionSet||n.viewportChanged||Jc(n)},class:"cm-selectionLayer"}),Qc={".cm-line":{"& ::selection":{backgroundColor:"transparent !important"},"&::selection":{backgroundColor:"transparent !important"}}};jc&&(Qc[".cm-line"].caretColor="transparent !important");var jg=hn.highest(H.theme(Qc));function ic(n,e,t,i,r){e.lastIndex=0;for(let s=n.iterRange(t,i),o=t,l;!s.next().done;o+=s.value.length)if(!s.lineBreak)for(;l=e.exec(s.value);)r(o+l.index,l)}function Jg(n,e){let t=n.visibleRanges;if(t.length==1&&t[0].from==n.viewport.from&&t[0].to==n.viewport.to)return t;let i=[];for(let{from:r,to:s}of t)r=Math.max(n.state.doc.lineAt(r).from,r-e),s=Math.min(n.state.doc.lineAt(s).to,s+e),i.length&&i[i.length-1].to>=r?i[i.length-1].to=s:i.push({from:r,to:s});return i}var Ml=class{constructor(e){let{regexp:t,decoration:i,decorate:r,boundary:s,maxLength:o=1e3}=e;if(!t.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=t,r)this.addMatch=(l,a,u,h)=>r(h,u,u+l[0].length,l,a);else if(typeof i=="function")this.addMatch=(l,a,u,h)=>{let c=i(l,a,u);c&&h(u,u+l[0].length,c)};else if(i)this.addMatch=(l,a,u,h)=>h(u,u+l[0].length,i);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=s,this.maxLength=o}createDeco(e){let t=new dt,i=t.add.bind(t);for(let{from:r,to:s}of Jg(e,this.maxLength))ic(e.state.doc,this.regexp,r,s,(o,l)=>this.addMatch(l,e,o,i));return t.finish()}updateDeco(e,t){let i=1e9,r=-1;return e.docChanged&&e.changes.iterChanges((s,o,l,a)=>{a>e.view.viewport.from&&l<e.view.viewport.to&&(i=Math.min(l,i),r=Math.max(a,r))}),e.viewportChanged||r-i>1e3?this.createDeco(e.view):r>-1?this.updateRange(e.view,t.map(e.changes),i,r):t}updateRange(e,t,i,r){for(let s of e.visibleRanges){let o=Math.max(s.from,i),l=Math.min(s.to,r);if(l>o){let a=e.state.doc.lineAt(o),u=a.to<l?e.state.doc.lineAt(l):a,h=Math.max(s.from,a.from),c=Math.min(s.to,u.to);if(this.boundary){for(;o>a.from;o--)if(this.boundary.test(a.text[o-1-a.from])){h=o;break}for(;l<u.to;l++)if(this.boundary.test(u.text[l-u.from])){c=l;break}}let f=[],d,p=(m,g,b)=>f.push(b.range(m,g));if(a==u)for(this.regexp.lastIndex=h-a.from;(d=this.regexp.exec(a.text))&&d.index<c-a.from;)this.addMatch(d,e,d.index+a.from,p);else ic(e.state.doc,this.regexp,h,c,(m,g)=>this.addMatch(g,e,m,p));t=t.update({filterFrom:h,filterTo:c,filter:(m,g)=>m<h||g>c,add:f})}}return t}},Tl=/x/.unicode!=null?"gu":"g",Qg=new RegExp(`[\0-\b
10
- -\x7F-\x9F\xAD\u061C\u200B\u200E\u200F\u2028\u2029\u202D\u202E\u2066\u2067\u2069\uFEFF\uFFF9-\uFFFC]`,Tl),Xg={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"},Go=null;function Yg(){var n;if(Go==null&&typeof document<"u"&&document.body){let e=document.body.style;Go=((n=e.tabSize)!==null&&n!==void 0?n:e.MozTabSize)!=null}return Go||!1}var vs=N.define({combine(n){let e=cn(n,{render:null,specialChars:Qg,addSpecialChars:null});return(e.replaceTabs=!Yg())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,Tl)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,Tl)),e}});function Vl(n={}){return[vs.of(n),Zg()]}var nc=null;function Zg(){return nc||(nc=ot.fromClass(class{constructor(n){this.view=n,this.decorations=X.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(n.state.facet(vs)),this.decorations=this.decorator.createDeco(n)}makeDecorator(n){return new Ml({regexp:n.specialChars,decoration:(e,t,i)=>{let{doc:r}=t.state,s=sn(e[0],0);if(s==9){let o=r.lineAt(i),l=t.state.tabSize,a=Hi(o.text,l,i-o.from);return X.replace({widget:new Dl((l-a%l)*this.view.defaultCharacterWidth)})}return this.decorationCache[s]||(this.decorationCache[s]=X.replace({widget:new Rl(n,s)}))},boundary:n.replaceTabs?void 0:/[^]/})}update(n){let e=n.state.facet(vs);n.startState.facet(vs)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(n.view)):this.decorations=this.decorator.updateDeco(n,this.decorations)}},{decorations:n=>n.decorations}))}var eb="\u2022";function tb(n){return n>=32?eb:n==10?"\u2424":String.fromCharCode(9216+n)}var Rl=class extends Ft{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=tb(this.code),i=e.state.phrase("Control character")+" "+(Xg[this.code]||"0x"+this.code.toString(16)),r=this.options.render&&this.options.render(this.code,i,t);if(r)return r;let s=document.createElement("span");return s.textContent=t,s.title=i,s.setAttribute("aria-label",i),s.className="cm-specialChar",s}ignoreEvent(){return!1}},Dl=class extends Ft{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement("span");return e.textContent=" ",e.className="cm-tab",e.style.width=this.width+"px",e}ignoreEvent(){return!1}};var dS=H.baseTheme({".cm-tooltip":{zIndex:100,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:`${7*2}px`,position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}});var Wt=class extends Vt{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}};Wt.prototype.elementClass="";Wt.prototype.toDOM=void 0;Wt.prototype.mapMode=Pe.TrackBefore;Wt.prototype.startSide=Wt.prototype.endSide=-1;Wt.prototype.point=!0;var ib=0,br=class{constructor(e,t){this.from=e,this.to=t}},F=class{constructor(e={}){this.id=ib++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=we.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}};F.closedBy=new F({deserialize:n=>n.split(" ")});F.openedBy=new F({deserialize:n=>n.split(" ")});F.group=new F({deserialize:n=>n.split(" ")});F.contextHash=new F({perNode:!0});F.lookAhead=new F({perNode:!0});F.mounted=new F({perNode:!0});var nb=Object.create(null),we=class{constructor(e,t,i,r=0){this.name=e,this.props=t,this.id=i,this.flags=r}static define(e){let t=e.props&&e.props.length?Object.create(null):nb,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),r=new we(e.name||"",t,e.id,i);if(e.props){for(let s of e.props)if(Array.isArray(s)||(s=s(r)),s){if(s[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[s[0].id]=s[1]}}return r}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(F.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let r of i.split(" "))t[r]=e[i];return i=>{for(let r=i.prop(F.group),s=-1;s<(r?r.length:0);s++){let o=t[s<0?i.name:r[s]];if(o)return o}}}};we.none=new we("",Object.create(null),0,8);var zi=class{constructor(e){this.types=e;for(let t=0;t<e.length;t++)if(e[t].id!=t)throw new RangeError("Node type ids should correspond to array positions when creating a node set")}extend(...e){let t=[];for(let i of this.types){let r=null;for(let s of e){let o=s(i);o&&(r||(r=Object.assign({},i.props)),r[o[0].id]=o[1])}t.push(r?new we(i.name,r,i.id,i.flags):i)}return new zi(t)}},Ls=new WeakMap,Xc=new WeakMap,be;(function(n){n[n.ExcludeBuffers=1]="ExcludeBuffers",n[n.IncludeAnonymous=2]="IncludeAnonymous",n[n.IgnoreMounts=4]="IgnoreMounts",n[n.IgnoreOverlays=8]="IgnoreOverlays"})(be||(be={}));var te=class{constructor(e,t,i,r,s){if(this.type=e,this.children=t,this.positions=i,this.length=r,this.props=null,s&&s.length){this.props=Object.create(null);for(let[o,l]of s)this.props[typeof o=="number"?o:o.id]=l}}toString(){let e=this.prop(F.mounted);if(e&&!e.overlay)return e.tree.toString();let t="";for(let i of this.children){let r=i.toString();r&&(t&&(t+=","),t+=r)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(t.length?"("+t+")":""):t}cursor(e=0){return new xn(this.topNode,e)}cursorAt(e,t=0,i=0){let r=Ls.get(this)||this.topNode,s=new xn(r);return s.moveTo(e,t),Ls.set(this,s._tree),s}get topNode(){return new lt(this,0,0,null)}resolve(e,t=0){let i=Sn(Ls.get(this)||this.topNode,e,t,!1);return Ls.set(this,i),i}resolveInner(e,t=0){let i=Sn(Xc.get(this)||this.topNode,e,t,!0);return Xc.set(this,i),i}iterate(e){let{enter:t,leave:i,from:r=0,to:s=this.length}=e;for(let o=this.cursor((e.mode||0)|be.IncludeAnonymous);;){let l=!1;if(o.from<=s&&o.to>=r&&(o.type.isAnonymous||t(o)!==!1)){if(o.firstChild())continue;l=!0}for(;l&&i&&!o.type.isAnonymous&&i(o),!o.nextSibling();){if(!o.parent())return;l=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:Fl(we.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,r)=>new te(this.type,t,i,r,this.propValues),e.makeTree||((t,i,r)=>new te(we.none,t,i,r)))}static build(e){return rb(e)}};te.empty=new te(we.none,[],[],0);var yr=class{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new yr(this.buffer,this.index)}},_t=class{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return we.none}toString(){let e=[];for(let t=0;t<this.buffer.length;)e.push(this.childString(t)),t=this.buffer[t+3];return e.join(",")}childString(e){let t=this.buffer[e],i=this.buffer[e+3],r=this.set.types[t],s=r.name;if(/\W/.test(s)&&!r.isError&&(s=JSON.stringify(s)),e+=4,i==e)return s;let o=[];for(;e<i;)o.push(this.childString(e)),e=this.buffer[e+3];return s+"("+o.join(",")+")"}findChild(e,t,i,r,s){let{buffer:o}=this,l=-1;for(let a=e;a!=t&&!(Zc(s,r,o[a+1],o[a+2])&&(l=a,i>0));a=o[a+3]);return l}slice(e,t,i){let r=this.buffer,s=new Uint16Array(t-e),o=0;for(let l=e,a=0;l<t;){s[a++]=r[l++],s[a++]=r[l++]-i;let u=s[a++]=r[l++]-i;s[a++]=r[l++]-e,o=Math.max(o,u)}return new _t(s,o,this.set)}};function Zc(n,e,t,i){switch(n){case-2:return t<e;case-1:return i>=e&&t<e;case 0:return t<e&&i>e;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function ef(n,e){let t=n.childBefore(e);for(;t;){let i=t.lastChild;if(!i||i.to!=t.to)break;i.type.isError&&i.from==i.to?(n=t,t=i.prevSibling):t=i}return n}function Sn(n,e,t,i){for(var r;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to<e);){let o=!i&&n instanceof lt&&n.index<0?null:n.parent;if(!o)return n;n=o}let s=i?0:be.IgnoreOverlays;if(i)for(let o=n,l=o.parent;l;o=l,l=o.parent)o instanceof lt&&o.index<0&&((r=l.enter(e,t,s))===null||r===void 0?void 0:r.from)!=o.from&&(n=l);for(;;){let o=n.enter(e,t,s);if(!o)return n;n=o}}var lt=class{constructor(e,t,i,r){this._tree=e,this.from=t,this.index=i,this._parent=r}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(e,t,i,r,s=0){for(let o=this;;){for(let{children:l,positions:a}=o._tree,u=t>0?l.length:-1;e!=u;e+=t){let h=l[e],c=a[e]+o.from;if(Zc(r,i,c,c+h.length)){if(h instanceof _t){if(s&be.ExcludeBuffers)continue;let f=h.findChild(0,h.buffer.length,t,i-c,r);if(f>-1)return new bt(new Ll(o,h,e,c),null,f)}else if(s&be.IncludeAnonymous||!h.type.isAnonymous||Bl(h)){let f;if(!(s&be.IgnoreMounts)&&h.props&&(f=h.prop(F.mounted))&&!f.overlay)return new lt(f.tree,c,e,o);let d=new lt(h,c,e,o);return s&be.IncludeAnonymous||!d.type.isAnonymous?d:d.nextChild(t<0?h.children.length-1:0,t,i,r)}}}if(s&be.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}enter(e,t,i=0){let r;if(!(i&be.IgnoreOverlays)&&(r=this._tree.prop(F.mounted))&&r.overlay){let s=e-this.from;for(let{from:o,to:l}of r.overlay)if((t>0?o<=s:o<s)&&(t<0?l>=s:l>s))return new lt(r.tree,r.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}cursor(e=0){return new xn(this,e)}get tree(){return this._tree}toTree(){return this._tree}resolve(e,t=0){return Sn(this,e,t,!1)}resolveInner(e,t=0){return Sn(this,e,t,!0)}enterUnfinishedNodesBefore(e){return ef(this,e)}getChild(e,t=null,i=null){let r=Bs(this,e,t,i);return r.length?r[0]:null}getChildren(e,t=null,i=null){return Bs(this,e,t,i)}toString(){return this._tree.toString()}get node(){return this}matchContext(e){return Fs(this,e)}};function Bs(n,e,t,i){let r=n.cursor(),s=[];if(!r.firstChild())return s;if(t!=null){for(;!r.type.is(t);)if(!r.nextSibling())return s}for(;;){if(i!=null&&r.type.is(i))return s;if(r.type.is(e)&&s.push(r.node),!r.nextSibling())return i==null?s:[]}}function Fs(n,e,t=e.length-1){for(let i=n.parent;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}var Ll=class{constructor(e,t,i,r){this.parent=e,this.buffer=t,this.index=i,this.start=r}},bt=class{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,i){this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:r}=this.context,s=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.context.start,i);return s<0?null:new bt(this.context,this,s)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,i=0){if(i&be.ExcludeBuffers)return null;let{buffer:r}=this.context,s=r.findChild(this.index+4,r.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return s<0?null:new bt(this.context,this,s)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new bt(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new bt(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}cursor(e=0){return new xn(this,e)}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,r=this.index+4,s=i.buffer[this.index+3];if(s>r){let o=i.buffer[this.index+1];e.push(i.slice(r,s,o)),t.push(0)}return new te(this.type,e,t,this.to-this.from)}resolve(e,t=0){return Sn(this,e,t,!1)}resolveInner(e,t=0){return Sn(this,e,t,!0)}enterUnfinishedNodesBefore(e){return ef(this,e)}toString(){return this.context.buffer.childString(this.index)}getChild(e,t=null,i=null){let r=Bs(this,e,t,i);return r.length?r[0]:null}getChildren(e,t=null,i=null){return Bs(this,e,t,i)}get node(){return this}matchContext(e){return Fs(this,e)}},xn=class{get name(){return this.type.name}constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof lt)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:i,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=i+r.buffer[e+1],this.to=i+r.buffer[e+2],!0}yield(e){return e?e instanceof lt?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:r}=this.buffer,s=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,i);return s<0?!1:(this.stack.push(this.index),this.yieldBuf(s))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,i=this.mode){return this.buffer?i&be.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&be.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&be.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,i=this.stack.length-1;if(e<0){let r=i<0?0:this.stack[i]+4;if(this.index!=r)return this.yieldBuf(t.findChild(r,this.index,-1,0,4))}else{let r=t.buffer[this.index+3];if(r<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(r)}return i<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,i,{buffer:r}=this;if(r){if(e>0){if(this.index<r.buffer.buffer.length)return!1}else for(let s=0;s<this.index;s++)if(r.buffer.buffer[s+3]<this.index)return!1;({index:t,parent:i}=r)}else({index:t,_parent:i}=this._tree);for(;i;{index:t,_parent:i}=i)if(t>-1)for(let s=t+e,o=e<0?-1:i._tree.children.length;s!=o;s+=e){let l=i._tree.children[s];if(this.mode&be.IncludeAnonymous||l instanceof _t||!l.type.isAnonymous||Bl(l))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to<e))&&this.parent(););for(;this.enterChild(1,e,t););return this}get node(){if(!this.buffer)return this._tree;let e=this.bufferNode,t=null,i=0;if(e&&e.context==this.buffer)e:for(let r=this.index,s=this.stack.length;s>=0;){for(let o=e;o;o=o._parent)if(o.index==r){if(r==this.index)return o;t=o,i=s+1;break e}r=this.stack[--s]}for(let r=i;r<this.stack.length;r++)t=new bt(this.buffer,t,this.stack[r]);return this.bufferNode=new bt(this.buffer,t,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(e,t){for(let i=0;;){let r=!1;if(this.type.isAnonymous||e(this)!==!1){if(this.firstChild()){i++;continue}this.type.isAnonymous||(r=!0)}for(;r&&t&&t(this),r=this.type.isAnonymous,!this.nextSibling();){if(!i)return;this.parent(),i--,r=!0}}}matchContext(e){if(!this.buffer)return Fs(this.node,e);let{buffer:t}=this.buffer,{types:i}=t.set;for(let r=e.length-1,s=this.stack.length-1;r>=0;s--){if(s<0)return Fs(this.node,e,r);let o=i[t.buffer[this.stack[s]]];if(!o.isAnonymous){if(e[r]&&e[r]!=o.name)return!1;r--}}return!0}};function Bl(n){return n.children.some(e=>e instanceof _t||!e.type.isAnonymous||Bl(e))}function rb(n){var e;let{buffer:t,nodeSet:i,maxBufferLength:r=1024,reused:s=[],minRepeatType:o=i.types.length}=n,l=Array.isArray(t)?new yr(t,t.length):t,a=i.types,u=0,h=0;function c(x,v,w,M,L){let{id:E,start:S,end:R,size:O}=l,I=h;for(;O<0;)if(l.next(),O==-1){let ae=s[E];w.push(ae),M.push(S-x);return}else if(O==-3){u=E;return}else if(O==-4){h=E;return}else throw new RangeError(`Unrecognized record size: ${O}`);let z=a[E],B,Y,ke=S-x;if(R-S<=r&&(Y=m(l.pos-v,L))){let ae=new Uint16Array(Y.size-Y.skip),q=l.pos-Y.size,j=ae.length;for(;l.pos>q;)j=g(Y.start,ae,j);B=new _t(ae,R-Y.start,i),ke=Y.start-x}else{let ae=l.pos-O;l.next();let q=[],j=[],et=E>=o?E:-1,ft=0,jt=R;for(;l.pos>ae;)et>=0&&l.id==et&&l.size>=0?(l.end<=jt-r&&(d(q,j,S,ft,l.end,jt,et,I),ft=q.length,jt=l.end),l.next()):c(S,ae,q,j,et);if(et>=0&&ft>0&&ft<q.length&&d(q,j,S,ft,S,jt,et,I),q.reverse(),j.reverse(),et>-1&&ft>0){let At=f(z);B=Fl(z,q,j,0,q.length,0,R-S,At,At)}else B=p(z,q,j,R-S,I-R)}w.push(B),M.push(ke)}function f(x){return(v,w,M)=>{let L=0,E=v.length-1,S,R;if(E>=0&&(S=v[E])instanceof te){if(!E&&S.type==x&&S.length==M)return S;(R=S.prop(F.lookAhead))&&(L=w[E]+S.length+R)}return p(x,v,w,M,L)}}function d(x,v,w,M,L,E,S,R){let O=[],I=[];for(;x.length>M;)O.push(x.pop()),I.push(v.pop()+w-L);x.push(p(i.types[S],O,I,E-L,R-E)),v.push(L-w)}function p(x,v,w,M,L=0,E){if(u){let S=[F.contextHash,u];E=E?[S].concat(E):[S]}if(L>25){let S=[F.lookAhead,L];E=E?[S].concat(E):[S]}return new te(x,v,w,M,E)}function m(x,v){let w=l.fork(),M=0,L=0,E=0,S=w.end-r,R={size:0,start:0,skip:0};e:for(let O=w.pos-x;w.pos>O;){let I=w.size;if(w.id==v&&I>=0){R.size=M,R.start=L,R.skip=E,E+=4,M+=4,w.next();continue}let z=w.pos-I;if(I<0||z<O||w.start<S)break;let B=w.id>=o?4:0,Y=w.start;for(w.next();w.pos>z;){if(w.size<0)if(w.size==-3)B+=4;else break e;else w.id>=o&&(B+=4);w.next()}L=Y,M+=I,E+=B}return(v<0||M==x)&&(R.size=M,R.start=L,R.skip=E),R.size>4?R:void 0}function g(x,v,w){let{id:M,start:L,end:E,size:S}=l;if(l.next(),S>=0&&M<o){let R=w;if(S>4){let O=l.pos-(S-4);for(;l.pos>O;)w=g(x,v,w)}v[--w]=R,v[--w]=E-x,v[--w]=L-x,v[--w]=M}else S==-3?u=M:S==-4&&(h=M);return w}let b=[],C=[];for(;l.pos>0;)c(n.start||0,n.bufferStart||0,b,C,-1);let y=(e=n.length)!==null&&e!==void 0?e:b.length?C[0]+b[0].length:0;return new te(a[n.topID],b.reverse(),C.reverse(),y)}var Yc=new WeakMap;function Ns(n,e){if(!n.isAnonymous||e instanceof _t||e.type!=n)return 1;let t=Yc.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=n||!(i instanceof te)){t=1;break}t+=Ns(n,i)}Yc.set(e,t)}return t}function Fl(n,e,t,i,r,s,o,l,a){let u=0;for(let p=i;p<r;p++)u+=Ns(n,e[p]);let h=Math.ceil(u*1.5/8),c=[],f=[];function d(p,m,g,b,C){for(let y=g;y<b;){let x=y,v=m[y],w=Ns(n,p[y]);for(y++;y<b;y++){let M=Ns(n,p[y]);if(w+M>=h)break;w+=M}if(y==x+1){if(w>h){let M=p[x];d(M.children,M.positions,0,M.children.length,m[x]+C);continue}c.push(p[x])}else{let M=m[y-1]+p[y-1].length-v;c.push(Fl(n,p,m,x,y,v,M,null,a))}f.push(v+C-s)}}return d(e,t,i,r,0),(l||a)(c,f,o)}var yt=class{constructor(e,t,i,r,s=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=r,this.open=(s?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let r=[new yt(0,e.length,e,0,!1,i)];for(let s of t)s.to>e.length&&r.push(s);return r}static applyChanges(e,t,i=128){if(!t.length)return e;let r=[],s=1,o=e.length?e[0]:null;for(let l=0,a=0,u=0;;l++){let h=l<t.length?t[l]:null,c=h?h.fromA:1e9;if(c-a>=i)for(;o&&o.from<c;){let f=o;if(a>=f.from||c<=f.to||u){let d=Math.max(f.from,a)-u,p=Math.min(f.to,c)-u;f=d>=p?null:new yt(d,p,f.tree,f.offset+u,l>0,!!h)}if(f&&r.push(f),o.to>c)break;o=s<e.length?e[s++]:null}if(!h)break;a=h.toA,u=h.toA-h.toB}return r}},kn=class{startParse(e,t,i){return typeof e=="string"&&(e=new Nl(e)),i=i?i.length?i.map(r=>new br(r.from,r.to)):[new br(0,0)]:[new br(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let r=this.startParse(e,t,i);for(;;){let s=r.advance();if(s)return s}}},Nl=class{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}};var gS=new F({perNode:!0});var sb=0,je=class{constructor(e,t,i){this.set=e,this.base=t,this.modified=i,this.id=sb++}static define(e){if(e!=null&&e.base)throw new Error("Can not derive from a modified tag");let t=new je([],null,[]);if(t.set.push(t),e)for(let i of e.set)t.set.push(i);return t}static defineModifier(){let e=new Mn;return t=>t.modified.indexOf(e)>-1?t:Mn.get(t.base||t,t.modified.concat(e).sort((i,r)=>i.id-r.id))}},ob=0,Mn=class{constructor(){this.instances=[],this.id=ob++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(l=>l.base==e&&lb(t,l.modified));if(i)return i;let r=[],s=new je(r,e,t);for(let l of t)l.instances.push(s);let o=ab(t);for(let l of e.set)if(!l.modified.length)for(let a of o)r.push(Mn.get(l,a));return s}};function lb(n,e){return n.length==e.length&&n.every((t,i)=>t==e[i])}function ab(n){let e=[[]];for(let t=0;t<n.length;t++)for(let i=0,r=e.length;i<r;i++)e.push(e[i].concat(n[t]));return e.sort((t,i)=>i.length-t.length)}function vr(n){let e=Object.create(null);for(let t in n){let i=n[t];Array.isArray(i)||(i=[i]);for(let r of t.split(" "))if(r){let s=[],o=2,l=r;for(let c=0;;){if(l=="..."&&c>0&&c+3==r.length){o=1;break}let f=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(l);if(!f)throw new RangeError("Invalid path: "+r);if(s.push(f[0]=="*"?"":f[0][0]=='"'?JSON.parse(f[0]):f[0]),c+=f[0].length,c==r.length)break;let d=r[c++];if(c==r.length&&d=="!"){o=0;break}if(d!="/")throw new RangeError("Invalid path: "+r);l=r.slice(c)}let a=s.length-1,u=s[a];if(!u)throw new RangeError("Invalid path: "+r);let h=new Tn(i,o,a>0?s.slice(0,a):null);e[u]=h.sort(e[u])}}return rf.add(e)}var rf=new F,Tn=class{constructor(e,t,i,r){this.tags=e,this.mode=t,this.context=i,this.next=r}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth<this.depth?(this.next=e,this):(e.next=this.sort(e.next),e)}get depth(){return this.context?this.context.length:0}};Tn.empty=new Tn([],2,null);function zl(n,e){let t=Object.create(null);for(let s of n)if(!Array.isArray(s.tag))t[s.tag.id]=s.class;else for(let o of s.tag)t[o.id]=s.class;let{scope:i,all:r=null}=e||{};return{style:s=>{let o=r;for(let l of s)for(let a of l.set){let u=t[a.id];if(u){o=o?o+" "+u:u;break}}return o},scope:i}}function ub(n,e){let t=null;for(let i of n){let r=i.style(e);r&&(t=t?t+" "+r:r)}return t}function sf(n,e,t,i=0,r=n.length){let s=new Wl(i,Array.isArray(e)?e:[e],t);s.highlightRange(n.cursor(),i,r,"",s.highlighters),s.flush(r)}var Wl=class{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,i,r,s){let{type:o,from:l,to:a}=e;if(l>=i||a<=t)return;o.isTop&&(s=this.highlighters.filter(d=>!d.scope||d.scope(o)));let u=r,h=hb(e)||Tn.empty,c=ub(s,h.tags);if(c&&(u&&(u+=" "),u+=c,h.mode==1&&(r+=(r?" ":"")+c)),this.startSpan(e.from,u),h.opaque)return;let f=e.tree&&e.tree.prop(F.mounted);if(f&&f.overlay){let d=e.node.enter(f.overlay[0].from+l,1),p=this.highlighters.filter(g=>!g.scope||g.scope(f.tree.type)),m=e.firstChild();for(let g=0,b=l;;g++){let C=g<f.overlay.length?f.overlay[g]:null,y=C?C.from+l:a,x=Math.max(t,b),v=Math.min(i,y);if(x<v&&m)for(;e.from<v&&(this.highlightRange(e,x,v,r,s),this.startSpan(Math.min(v,e.to),u),!(e.to>=y||!e.nextSibling())););if(!C||y>i)break;b=C.to+l,b>t&&(this.highlightRange(d.cursor(),Math.max(t,C.from+l),Math.min(i,b),r,p),this.startSpan(b,u))}m&&e.parent()}else if(e.firstChild()){do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,r,s),this.startSpan(Math.min(i,e.to),u)}while(e.nextSibling());e.parent()}}};function hb(n){let e=n.type.prop(rf);for(;e&&e.context&&!n.matchContext(e.context);)e=e.next;return e||null}var A=je.define,Hs=A(),ii=A(),tf=A(ii),nf=A(ii),ni=A(),Ws=A(ni),Hl=A(ni),Ct=A(),Ui=A(Ct),wt=A(),vt=A(),_l=A(),wr=A(_l),_s=A(),D={comment:Hs,lineComment:A(Hs),blockComment:A(Hs),docComment:A(Hs),name:ii,variableName:A(ii),typeName:tf,tagName:A(tf),propertyName:nf,attributeName:A(nf),className:A(ii),labelName:A(ii),namespace:A(ii),macroName:A(ii),literal:ni,string:Ws,docString:A(Ws),character:A(Ws),attributeValue:A(Ws),number:Hl,integer:A(Hl),float:A(Hl),bool:A(ni),regexp:A(ni),escape:A(ni),color:A(ni),url:A(ni),keyword:wt,self:A(wt),null:A(wt),atom:A(wt),unit:A(wt),modifier:A(wt),operatorKeyword:A(wt),controlKeyword:A(wt),definitionKeyword:A(wt),moduleKeyword:A(wt),operator:vt,derefOperator:A(vt),arithmeticOperator:A(vt),logicOperator:A(vt),bitwiseOperator:A(vt),compareOperator:A(vt),updateOperator:A(vt),definitionOperator:A(vt),typeOperator:A(vt),controlOperator:A(vt),punctuation:_l,separator:A(_l),bracket:wr,angleBracket:A(wr),squareBracket:A(wr),paren:A(wr),brace:A(wr),content:Ct,heading:Ui,heading1:A(Ui),heading2:A(Ui),heading3:A(Ui),heading4:A(Ui),heading5:A(Ui),heading6:A(Ui),contentSeparator:A(Ct),list:A(Ct),quote:A(Ct),emphasis:A(Ct),strong:A(Ct),link:A(Ct),monospace:A(Ct),strikethrough:A(Ct),inserted:A(),deleted:A(),changed:A(),invalid:A(),meta:_s,documentMeta:A(_s),annotation:A(_s),processingInstruction:A(_s),definition:je.defineModifier(),constant:je.defineModifier(),function:je.defineModifier(),standard:je.defineModifier(),local:je.defineModifier(),special:je.defineModifier()},wS=zl([{tag:D.link,class:"tok-link"},{tag:D.heading,class:"tok-heading"},{tag:D.emphasis,class:"tok-emphasis"},{tag:D.strong,class:"tok-strong"},{tag:D.keyword,class:"tok-keyword"},{tag:D.atom,class:"tok-atom"},{tag:D.bool,class:"tok-bool"},{tag:D.url,class:"tok-url"},{tag:D.labelName,class:"tok-labelName"},{tag:D.inserted,class:"tok-inserted"},{tag:D.deleted,class:"tok-deleted"},{tag:D.literal,class:"tok-literal"},{tag:D.string,class:"tok-string"},{tag:D.number,class:"tok-number"},{tag:[D.regexp,D.escape,D.special(D.string)],class:"tok-string2"},{tag:D.variableName,class:"tok-variableName"},{tag:D.local(D.variableName),class:"tok-variableName tok-local"},{tag:D.definition(D.variableName),class:"tok-variableName tok-definition"},{tag:D.special(D.variableName),class:"tok-variableName2"},{tag:D.definition(D.propertyName),class:"tok-propertyName tok-definition"},{tag:D.typeName,class:"tok-typeName"},{tag:D.namespace,class:"tok-namespace"},{tag:D.className,class:"tok-className"},{tag:D.macroName,class:"tok-macroName"},{tag:D.propertyName,class:"tok-propertyName"},{tag:D.operator,class:"tok-operator"},{tag:D.comment,class:"tok-comment"},{tag:D.meta,class:"tok-meta"},{tag:D.invalid,class:"tok-invalid"},{tag:D.punctuation,class:"tok-punctuation"}]);var Ul,Rn=new F;function cb(n){return N.define({combine:n?e=>e.concat(n):void 0})}var fb=new F,He=class{constructor(e,t,i=[],r=""){this.data=e,this.name=r,U.prototype.hasOwnProperty("tree")||Object.defineProperty(U.prototype,"tree",{get(){return We(this)}}),this.parser=t,this.extension=[An.of(this),U.languageData.of((s,o,l)=>{let a=of(s,o,l),u=a.type.prop(Rn);if(!u)return[];let h=s.facet(u),c=a.type.prop(fb);if(c){let f=a.resolve(o-a.from,l);for(let d of c)if(d.test(f,s)){let p=s.facet(d.facet);return d.type=="replace"?p:p.concat(h)}}return h})].concat(i)}isActiveAt(e,t,i=-1){return of(e,t,i).type.prop(Rn)==this.data}findRegions(e){let t=e.facet(An);if((t==null?void 0:t.data)==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let i=[],r=(s,o)=>{if(s.prop(Rn)==this.data){i.push({from:o,to:o+s.length});return}let l=s.prop(F.mounted);if(l){if(l.tree.prop(Rn)==this.data){if(l.overlay)for(let a of l.overlay)i.push({from:a.from+o,to:a.to+o});else i.push({from:o,to:o+s.length});return}else if(l.overlay){let a=i.length;if(r(l.tree,l.overlay[0].from+o),i.length>a)return}}for(let a=0;a<s.children.length;a++){let u=s.children[a];u instanceof te&&r(u,s.positions[a]+o)}};return r(We(e),0),i}get allowsNesting(){return!0}};He.setState=ee.define();function of(n,e,t){let i=n.facet(An),r=We(n).topNode;if(!i||i.allowsNesting)for(let s=r;s;s=s.enter(e,t,be.ExcludeBuffers))s.type.isTop&&(r=s);return r}var ri=class extends He{constructor(e,t,i){super(e,t,[],i),this.parser=t}static define(e){let t=cb(e.languageData);return new ri(t,e.parser.configure({props:[Rn.add(i=>i.isTop?t:void 0)]}),e.name)}configure(e,t){return new ri(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}};function We(n){let e=n.field(He.state,!1);return e?e.tree:te.empty}var Gl=class{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let i=this.cursorPos-this.string.length;return e<i||t>=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-i,t-i)}},Cr=null,Dn=class{constructor(e,t,i=[],r,s,o,l,a){this.parser=e,this.state=t,this.fragments=i,this.tree=r,this.treeLen=s,this.viewport=o,this.skipped=l,this.scheduleOn=a,this.parse=null,this.tempSkipped=[]}static create(e,t,i){return new Dn(e,t,[],te.empty,0,i,[],null)}startParse(){return this.parser.startParse(new Gl(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=te.empty&&this.isDone(t!=null?t:this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var i;if(typeof e=="number"){let r=Date.now()+e;e=()=>Date.now()>r}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t<this.state.doc.length&&this.parse.stopAt(t);;){let r=this.parse.advance();if(r)if(this.fragments=this.withoutTempSkipped(yt.addTree(r,this.fragments,this.parse.stoppedAt!=null)),this.treeLen=(i=this.parse.stoppedAt)!==null&&i!==void 0?i:this.state.doc.length,this.tree=r,this.parse=null,this.treeLen<(t!=null?t:this.state.doc.length))this.parse=this.startParse();else return!0;if(e())return!1}})}takeTree(){let e,t;this.parse&&(e=this.parse.parsedPos)>=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(yt.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=Cr;Cr=this;try{return e()}finally{Cr=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=lf(e,t.from,t.to);return e}changes(e,t){let{fragments:i,tree:r,treeLen:s,viewport:o,skipped:l}=this;if(this.takeTree(),!e.empty){let a=[];if(e.iterChangedRanges((u,h,c,f)=>a.push({fromA:u,toA:h,fromB:c,toB:f})),i=yt.applyChanges(i,a),r=te.empty,s=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){l=[];for(let u of this.skipped){let h=e.mapPos(u.from,1),c=e.mapPos(u.to,-1);h<c&&l.push({from:h,to:c})}}}return new Dn(this.parser,t,i,r,s,o,l,this.scheduleOn)}updateViewport(e){if(this.viewport.from==e.from&&this.viewport.to==e.to)return!1;this.viewport=e;let t=this.skipped.length;for(let i=0;i<this.skipped.length;i++){let{from:r,to:s}=this.skipped[i];r<e.to&&s>e.from&&(this.fragments=lf(this.fragments,r,s),this.skipped.splice(i--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends kn{createParse(t,i,r){let s=r[0].from,o=r[r.length-1].to;return{parsedPos:s,advance(){let a=Cr;if(a){for(let u of r)a.tempSkipped.push(u);e&&(a.scheduleOn=a.scheduleOn?Promise.all([a.scheduleOn,e]):e)}return this.parsedPos=o,new te(we.none,[],[],o-s)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return Cr}};function lf(n,e,t){return yt.applyChanges(n,[{fromA:e,toA:t,fromB:e,toB:t}])}var si=class{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),i=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,i)||t.takeTree(),new si(t)}static init(e){let t=Math.min(3e3,e.doc.length),i=Dn.create(e.facet(An).parser,e,{from:0,to:t});return i.work(20,t)||i.takeTree(),new si(i)}};He.state=Be.define({create:si.init,update(n,e){for(let t of e.effects)if(t.is(He.setState))return t.value;return e.startState.facet(An)!=e.state.facet(An)?si.init(e.state):n.apply(e)}});var hf=n=>{let e=setTimeout(()=>n(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(hf=n=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(n,{timeout:500-100})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});var $l=typeof navigator<"u"&&(!((Ul=navigator.scheduling)===null||Ul===void 0)&&Ul.isInputPending)?()=>navigator.scheduling.isInputPending():null,db=ot.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(He.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),e.docChanged&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(He.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=hf(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnd<t&&(this.chunkEnd<0||this.view.hasFocus)&&(this.chunkEnd=t+3e4,this.chunkBudget=3e3),this.chunkBudget<=0)return;let{state:i,viewport:{to:r}}=this.view,s=i.field(He.state);if(s.tree==s.context.tree&&s.context.isDone(r+1e5))return;let o=Date.now()+Math.min(this.chunkBudget,100,e&&!$l?Math.max(25,e.timeRemaining()-5):1e9),l=s.context.treeLen<r&&i.doc.length>r+1e3,a=s.context.work(()=>$l&&$l()||Date.now()>o,r+(l?0:1e5));this.chunkBudget-=Date.now()-t,(a||this.chunkBudget<=0)&&(s.context.takeTree(),this.view.dispatch({effects:He.setState.of(new si(s.context))})),this.chunkBudget>0&&!(a&&!l)&&this.scheduleWork(),this.checkAsyncSchedule(s.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>Bt(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),An=N.define({combine(n){return n.length?n[0]:null},enables:n=>[He.state,db,H.contentAttributes.compute([n],e=>{let t=e.facet(n);return t&&t.name?{"data-language":t.name}:{}})]});var pb=N.define(),zs=N.define({combine:n=>{if(!n.length)return" ";let e=n[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(n[0]));return e}});function xr(n){let e=n.facet(zs);return e.charCodeAt(0)==9?n.tabSize*e.length:e.length}function kr(n,e){let t="",i=n.tabSize,r=n.facet(zs)[0];if(r==" "){for(;e>=i;)t+=" ",e-=i;r=" "}for(let s=0;s<e;s++)t+=r;return t}function Yl(n,e){n instanceof U&&(n=new $i(n));for(let i of n.state.facet(pb)){let r=i(n,e);if(r!==void 0)return r}let t=We(n.state);return t?gb(n,t,e):null}var $i=class{constructor(e,t={}){this.state=e,this.options=t,this.unit=xr(e)}lineAt(e,t=1){let i=this.state.doc.lineAt(e),{simulateBreak:r,simulateDoubleBreak:s}=this.options;return r!=null&&r>=i.from&&r<=i.to?s&&r==e?{text:"",from:e}:(t<0?r<e:r<=e)?{text:i.text.slice(r-i.from),from:r}:{text:i.text.slice(0,r-i.from),from:i.from}:i}textAfterPos(e,t=1){if(this.options.simulateDoubleBreak&&e==this.options.simulateBreak)return"";let{text:i,from:r}=this.lineAt(e,t);return i.slice(e-r,Math.min(i.length,e+100-r))}column(e,t=1){let{text:i,from:r}=this.lineAt(e,t),s=this.countColumn(i,e-r),o=this.options.overrideIndentation?this.options.overrideIndentation(r):-1;return o>-1&&(s+=o-this.countColumn(i,i.search(/\S|$/))),s}countColumn(e,t=e.length){return Hi(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:i,from:r}=this.lineAt(e,t),s=this.options.overrideIndentation;if(s){let o=s(r);if(o>-1)return o}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}},mb=new F;function gb(n,e,t){return cf(e.resolveInner(t).enterUnfinishedNodesBefore(t),t,n)}function bb(n){return n.pos==n.options.simulateBreak&&n.options.simulateDoubleBreak}function yb(n){let e=n.type.prop(mb);if(e)return e;let t=n.firstChild,i;if(t&&(i=t.type.prop(F.closedBy))){let r=n.lastChild,s=r&&i.indexOf(r.name)>-1;return o=>Sb(o,!0,1,void 0,s&&!bb(o)?r.from:void 0)}return n.parent==null?wb:null}function cf(n,e,t){for(;n;n=n.parent){let i=yb(n);if(i)return i(Sr.create(t,e,n))}return null}function wb(){return 0}var Sr=class extends $i{constructor(e,t,i){super(e.state,e.options),this.base=e,this.pos=t,this.node=i}static create(e,t,i){return new Sr(e,t,i)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){let e=this.state.doc.lineAt(this.node.from);for(;;){let t=this.node.resolve(e.from);for(;t.parent&&t.parent.from==t.from;)t=t.parent;if(vb(t,this.node))break;e=this.state.doc.lineAt(t.from)}return this.lineIndent(e.from)}continue(){let e=this.node.parent;return e?cf(e,this.pos,this.base):0}};function vb(n,e){for(let t=e;t;t=t.parent)if(n==t)return!0;return!1}function Cb(n){let e=n.node,t=e.childAfter(e.from),i=e.lastChild;if(!t)return null;let r=n.options.simulateBreak,s=n.state.doc.lineAt(t.from),o=r==null||r<=s.from?s.to:Math.min(s.to,r);for(let l=t.to;;){let a=e.childAfter(l);if(!a||a==i)return null;if(!a.type.isSkipped)return a.from<o?t:null;l=a.to}}function Sb(n,e,t,i,r){let s=n.textAfter,o=s.match(/^\s*/)[0].length,l=i&&s.slice(o,o+i.length)==i||r==n.pos+o,a=e?Cb(n):null;return a?l?n.column(a.from):n.column(a.to):n.baseIndent+(l?0:n.unit*t)}var zt=class{constructor(e,t){this.specs=e;let i;function r(l){let a=Ke.newName();return(i||(i=Object.create(null)))["."+a]=l,a}let s=typeof t.all=="string"?t.all:t.all?r(t.all):void 0,o=t.scope;this.scope=o instanceof He?l=>l.prop(Rn)==o.data:o?l=>l==o:void 0,this.style=zl(e.map(l=>({tag:l.tag,class:l.class||r(Object.assign({},l,{tag:null}))})),{all:s}).style,this.module=i?new Ke(i):null,this.themeType=t.themeType}static define(e,t){return new zt(e,t||{})}},jl=N.define(),ff=N.define({combine(n){return n.length?[n[0]]:null}});function Kl(n){let e=n.facet(jl);return e.length?e:n.facet(ff)}function Mr(n,e){let t=[xb],i;return n instanceof zt&&(n.module&&t.push(H.styleModule.of(n.module)),i=n.themeType),e!=null&&e.fallback?t.push(ff.of(n)):i?t.push(jl.computeN([H.darkTheme],r=>r.facet(H.darkTheme)==(i=="dark")?[n]:[])):t.push(jl.of(n)),t}var Jl=class{constructor(e){this.markCache=Object.create(null),this.tree=We(e.state),this.decorations=this.buildDeco(e,Kl(e.state))}update(e){let t=We(e.state),i=Kl(e.state),r=i!=Kl(e.startState);t.length<e.view.viewport.to&&!r&&t.type==this.tree.type?this.decorations=this.decorations.map(e.changes):(t!=this.tree||e.viewportChanged||r)&&(this.tree=t,this.decorations=this.buildDeco(e.view,i))}buildDeco(e,t){if(!t||!this.tree.length)return X.none;let i=new dt;for(let{from:r,to:s}of e.visibleRanges)sf(this.tree,t,(o,l,a)=>{i.add(o,l,this.markCache[a]||(this.markCache[a]=X.mark({class:a})))},r,s);return i.finish()}},xb=hn.high(ot.fromClass(Jl,{decorations:n=>n.decorations})),Zl=zt.define([{tag:D.meta,color:"#404740"},{tag:D.link,textDecoration:"underline"},{tag:D.heading,textDecoration:"underline",fontWeight:"bold"},{tag:D.emphasis,fontStyle:"italic"},{tag:D.strong,fontWeight:"bold"},{tag:D.strikethrough,textDecoration:"line-through"},{tag:D.keyword,color:"#708"},{tag:[D.atom,D.bool,D.url,D.contentSeparator,D.labelName],color:"#219"},{tag:[D.literal,D.inserted],color:"#164"},{tag:[D.string,D.deleted],color:"#a11"},{tag:[D.regexp,D.escape,D.special(D.string)],color:"#e40"},{tag:D.definition(D.variableName),color:"#00f"},{tag:D.local(D.variableName),color:"#30a"},{tag:[D.typeName,D.namespace],color:"#085"},{tag:D.className,color:"#167"},{tag:[D.special(D.variableName),D.macroName],color:"#256"},{tag:D.definition(D.propertyName),color:"#00c"},{tag:D.comment,color:"#940"},{tag:D.invalid,color:"#f00"}]);var kb=1e4,Mb="()[]{}";var Tb=new F;function Ql(n,e,t){let i=n.prop(e<0?F.openedBy:F.closedBy);if(i)return i;if(n.name.length==1){let r=t.indexOf(n.name);if(r>-1&&r%2==(e<0?1:0))return[t[r+e]]}return null}function Xl(n){let e=n.type.prop(Tb);return e?e(n.node):n}function Ki(n,e,t,i={}){let r=i.maxScanDistance||kb,s=i.brackets||Mb,o=We(n),l=o.resolveInner(e,t);for(let a=l;a;a=a.parent){let u=Ql(a.type,t,s);if(u&&a.from<a.to){let h=Xl(a);if(h&&(t>0?e>=h.from&&e<h.to:e>h.from&&e<=h.to))return Rb(n,e,t,a,h,u,s)}}return Db(n,e,t,o,l.type,r,s)}function Rb(n,e,t,i,r,s,o){let l=i.parent,a={from:r.from,to:r.to},u=0,h=l==null?void 0:l.cursor();if(h&&(t<0?h.childBefore(i.from):h.childAfter(i.to)))do if(t<0?h.to<=i.from:h.from>=i.to){if(u==0&&s.indexOf(h.type.name)>-1&&h.from<h.to){let c=Xl(h);return{start:a,end:c?{from:c.from,to:c.to}:void 0,matched:!0}}else if(Ql(h.type,t,o))u++;else if(Ql(h.type,-t,o)){if(u==0){let c=Xl(h);return{start:a,end:c&&c.from<c.to?{from:c.from,to:c.to}:void 0,matched:!1}}u--}}while(t<0?h.prevSibling():h.nextSibling());return{start:a,matched:!1}}function Db(n,e,t,i,r,s,o){let l=t<0?n.sliceDoc(e-1,e):n.sliceDoc(e,e+1),a=o.indexOf(l);if(a<0||a%2==0!=t>0)return null;let u={from:t<0?e-1:e,to:t>0?e+1:e},h=n.doc.iterRange(e,t>0?n.doc.length:0),c=0;for(let f=0;!h.next().done&&f<=s;){let d=h.value;t<0&&(f+=d.length);let p=e+f*t;for(let m=t>0?0:d.length-1,g=t>0?d.length:-1;m!=g;m+=t){let b=o.indexOf(d[m]);if(!(b<0||i.resolveInner(p+m,1).type!=r))if(b%2==0==t>0)c++;else{if(c==1)return{start:u,end:{from:p+m,to:p+m+1},matched:b>>1==a>>1};c--}}t>0&&(f+=d.length)}return h.done?{start:u,matched:!1}:null}var Ab=Object.create(null),af=[we.none];var uf=[],Pb=Object.create(null);for(let[n,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])Pb[n]=Eb(Ab,e);function ql(n,e){uf.indexOf(n)>-1||(uf.push(n),console.warn(e))}function Eb(n,e){let t=null;for(let s of e.split(".")){let o=n[s]||D[s];o?typeof o=="function"?t?t=o(t):ql(s,`Modifier ${s} used at start of tag`):t?ql(s,`Tag ${s} used as modifier`):t=o:ql(s,`Unknown highlighting tag ${s}`)}if(!t)return 0;let i=e.replace(/ /g,"_"),r=we.define({id:af.length,name:i,props:[vr({[i]:t})]});return af.push(r),r.id}var Ob=n=>{let{state:e}=n,t=e.doc.lineAt(e.selection.main.head),i=oa(n.state,t.from);return i.line?Ib(n):i.block?Lb(n):!1};function sa(n,e){return({state:t,dispatch:i})=>{if(t.readOnly)return!1;let r=n(e,t);return r?(i(t.update(r)),!0):!1}}var Ib=sa(Fb,0);var Vb=sa(vf,0);var Lb=sa((n,e)=>vf(n,e,Bb(e)),0);function oa(n,e){let t=n.languageDataAt("commentTokens",e);return t.length?t[0]:{}}var Tr=50;function Nb(n,{open:e,close:t},i,r){let s=n.sliceDoc(i-Tr,i),o=n.sliceDoc(r,r+Tr),l=/\s*$/.exec(s)[0].length,a=/^\s*/.exec(o)[0].length,u=s.length-l;if(s.slice(u-e.length,u)==e&&o.slice(a,a+t.length)==t)return{open:{pos:i-l,margin:l&&1},close:{pos:r+a,margin:a&&1}};let h,c;r-i<=2*Tr?h=c=n.sliceDoc(i,r):(h=n.sliceDoc(i,i+Tr),c=n.sliceDoc(r-Tr,r));let f=/^\s*/.exec(h)[0].length,d=/\s*$/.exec(c)[0].length,p=c.length-d-t.length;return h.slice(f,f+e.length)==e&&c.slice(p,p+t.length)==t?{open:{pos:i+f+e.length,margin:/\s/.test(h.charAt(f+e.length))?1:0},close:{pos:r-d-t.length,margin:/\s/.test(c.charAt(p-1))?1:0}}:null}function Bb(n){let e=[];for(let t of n.selection.ranges){let i=n.doc.lineAt(t.from),r=t.to<=i.to?i:n.doc.lineAt(t.to),s=e.length-1;s>=0&&e[s].to>i.from?e[s].to=r.to:e.push({from:i.from,to:r.to})}return e}function vf(n,e,t=e.selection.ranges){let i=t.map(s=>oa(e,s.from).block);if(!i.every(s=>s))return null;let r=t.map((s,o)=>Nb(e,i[o],s.from,s.to));if(n!=2&&!r.every(s=>s))return{changes:e.changes(t.map((s,o)=>r[o]?[]:[{from:s.from,insert:i[o].open+" "},{from:s.to,insert:" "+i[o].close}]))};if(n!=1&&r.some(s=>s)){let s=[];for(let o=0,l;o<r.length;o++)if(l=r[o]){let a=i[o],{open:u,close:h}=l;s.push({from:u.pos-a.open.length,to:u.pos+u.margin},{from:h.pos-h.margin,to:h.pos+a.close.length})}return{changes:s}}return null}function Fb(n,e,t=e.selection.ranges){let i=[],r=-1;for(let{from:s,to:o}of t){let l=i.length,a=1e9;for(let u=s;u<=o;){let h=e.doc.lineAt(u);if(h.from>r&&(s==o||o>h.from)){r=h.from;let c=oa(e,h.from).line;if(!c)continue;let f=/^\s*/.exec(h.text)[0].length,d=f==h.length,p=h.text.slice(f,f+c.length)==c?f:-1;f<h.text.length&&f<a&&(a=f),i.push({line:h,comment:p,token:c,indent:f,empty:d,single:!1})}u=h.to+1}if(a<1e9)for(let u=l;u<i.length;u++)i[u].indent<i[u].line.text.length&&(i[u].indent=a);i.length==l+1&&(i[l].single=!0)}if(n!=2&&i.some(s=>s.comment<0&&(!s.empty||s.single))){let s=[];for(let{line:l,token:a,indent:u,empty:h,single:c}of i)(c||!h)&&s.push({from:l.from+u,insert:a+" "});let o=e.changes(s);return{changes:o,selection:e.selection.map(o,1)}}else if(n!=1&&i.some(s=>s.comment>=0)){let s=[];for(let{line:o,comment:l,token:a}of i)if(l>=0){let u=o.from+l,h=u+a.length;o.text[h-o.from]==" "&&h++,s.push({from:u,to:h})}return{changes:s}}return null}var ta=$e.define(),Hb=$e.define(),Wb=N.define(),Cf=N.define({combine(n){return cn(n,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(i,r)=>e(i,r)||t(i,r)})}});function _b(n){let e=0;return n.iterChangedRanges((t,i)=>e=i),e}var Sf=Be.define({create(){return Qe.empty},update(n,e){let t=e.state.facet(Cf),i=e.annotation(ta);if(i){let a=e.docChanged?T.single(_b(e.changes)):void 0,u=Te.fromTransaction(e,a),h=i.side,c=h==0?n.undone:n.done;return u?c=$s(c,c.length,t.minDepth,u):c=Mf(c,e.startState.selection),new Qe(h==0?i.rest:c,h==0?c:i.rest)}let r=e.annotation(Hb);if((r=="full"||r=="before")&&(n=n.isolate()),e.annotation(re.addToHistory)===!1)return e.changes.empty?n:n.addMapping(e.changes.desc);let s=Te.fromTransaction(e),o=e.annotation(re.time),l=e.annotation(re.userEvent);return s?n=n.addChanges(s,o,l,t,e):e.selection&&(n=n.addSelection(e.startState.selection,o,l,t.newGroupDelay)),(r=="full"||r=="after")&&(n=n.isolate()),n},toJSON(n){return{done:n.done.map(e=>e.toJSON()),undone:n.undone.map(e=>e.toJSON())}},fromJSON(n){return new Qe(n.done.map(Te.fromJSON),n.undone.map(Te.fromJSON))}});function la(n={}){return[Sf,Cf.of(n),H.domEventHandlers({beforeinput(e,t){let i=e.inputType=="historyUndo"?xf:e.inputType=="historyRedo"?ia:null;return i?(e.preventDefault(),i(t)):!1}})]}function Ks(n,e){return function({state:t,dispatch:i}){if(!e&&t.readOnly)return!1;let r=t.field(Sf,!1);if(!r)return!1;let s=r.pop(n,t,e);return s?(i(s),!0):!1}}var xf=Ks(0,!1),ia=Ks(1,!1),zb=Ks(0,!0),Ub=Ks(1,!0);var Te=class{constructor(e,t,i,r,s){this.changes=e,this.effects=t,this.mapped=i,this.startSelection=r,this.selectionsAfter=s}setSelAfter(e){return new Te(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,i;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(i=this.startSelection)===null||i===void 0?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map(r=>r.toJSON())}}static fromJSON(e){return new Te(e.changes&&ne.fromJSON(e.changes),[],e.mapped&&Ne.fromJSON(e.mapped),e.startSelection&&T.fromJSON(e.startSelection),e.selectionsAfter.map(T.fromJSON))}static fromTransaction(e,t){let i=Je;for(let r of e.startState.facet(Wb)){let s=r(e);s.length&&(i=i.concat(s))}return!i.length&&e.changes.empty?null:new Te(e.changes.invert(e.startState.doc),i,void 0,t||e.startState.selection,Je)}static selection(e){return new Te(void 0,Je,void 0,void 0,e)}};function $s(n,e,t,i){let r=e+1>t+20?e-t-1:0,s=n.slice(r,e);return s.push(i),s}function $b(n,e){let t=[],i=!1;return n.iterChangedRanges((r,s)=>t.push(r,s)),e.iterChangedRanges((r,s,o,l)=>{for(let a=0;a<t.length;){let u=t[a++],h=t[a++];l>=u&&o<=h&&(i=!0)}}),i}function Kb(n,e){return n.ranges.length==e.ranges.length&&n.ranges.filter((t,i)=>t.empty!=e.ranges[i].empty).length===0}function kf(n,e){return n.length?e.length?n.concat(e):n:e}var Je=[],qb=200;function Mf(n,e){if(n.length){let t=n[n.length-1],i=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-qb));return i.length&&i[i.length-1].eq(e)?n:(i.push(e),$s(n,n.length-1,1e9,t.setSelAfter(i)))}else return[Te.selection([e])]}function Gb(n){let e=n[n.length-1],t=n.slice();return t[n.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function ea(n,e){if(!n.length)return n;let t=n.length,i=Je;for(;t;){let r=jb(n[t-1],e,i);if(r.changes&&!r.changes.empty||r.effects.length){let s=n.slice(0,t);return s[t-1]=r,s}else e=r.mapped,t--,i=r.selectionsAfter}return i.length?[Te.selection(i)]:Je}function jb(n,e,t){let i=kf(n.selectionsAfter.length?n.selectionsAfter.map(l=>l.map(e)):Je,t);if(!n.changes)return Te.selection(i);let r=n.changes.map(e),s=e.mapDesc(n.changes,!0),o=n.mapped?n.mapped.composeDesc(s):s;return new Te(r,ee.mapEffects(n.effects,e),o,n.startSelection.map(s),i)}var Jb=/^(input\.type|delete)($|\.)/,Qe=class{constructor(e,t,i=0,r=void 0){this.done=e,this.undone=t,this.prevTime=i,this.prevUserEvent=r}isolate(){return this.prevTime?new Qe(this.done,this.undone):this}addChanges(e,t,i,r,s){let o=this.done,l=o[o.length-1];return l&&l.changes&&!l.changes.empty&&e.changes&&(!i||Jb.test(i))&&(!l.selectionsAfter.length&&t-this.prevTime<r.newGroupDelay&&r.joinToEvent(s,$b(l.changes,e.changes))||i=="input.type.compose")?o=$s(o,o.length-1,r.minDepth,new Te(e.changes.compose(l.changes),kf(e.effects,l.effects),l.mapped,l.startSelection,Je)):o=$s(o,o.length,r.minDepth,e),new Qe(o,Je,t,i)}addSelection(e,t,i,r){let s=this.done.length?this.done[this.done.length-1].selectionsAfter:Je;return s.length>0&&t-this.prevTime<r&&i==this.prevUserEvent&&i&&/^select($|\.)/.test(i)&&Kb(s[s.length-1],e)?this:new Qe(Mf(this.done,e),this.undone,t,i)}addMapping(e){return new Qe(ea(this.done,e),ea(this.undone,e),this.prevTime,this.prevUserEvent)}pop(e,t,i){let r=e==0?this.done:this.undone;if(r.length==0)return null;let s=r[r.length-1];if(i&&s.selectionsAfter.length)return t.update({selection:s.selectionsAfter[s.selectionsAfter.length-1],annotations:ta.of({side:e,rest:Gb(r)}),userEvent:e==0?"select.undo":"select.redo",scrollIntoView:!0});if(s.changes){let o=r.length==1?Je:r.slice(0,r.length-1);return s.mapped&&(o=ea(o,s.mapped)),t.update({changes:s.changes,selection:s.startSelection,effects:s.effects,annotations:ta.of({side:e,rest:o}),filter:!1,userEvent:e==0?"undo":"redo",scrollIntoView:!0})}else return null}};Qe.empty=new Qe(Je,Je);var aa=[{key:"Mod-z",run:xf,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:ia,preventDefault:!0},{linux:"Ctrl-Shift-z",run:ia,preventDefault:!0},{key:"Mod-u",run:zb,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:Ub,preventDefault:!0}];function Pn(n,e){return T.create(n.ranges.map(e),n.mainIndex)}function St(n,e){return n.update({selection:e,scrollIntoView:!0,userEvent:"select"})}function at({state:n,dispatch:e},t){let i=Pn(n.selection,t);return i.eq(n.selection)?!1:(e(St(n,i)),!0)}function qs(n,e){return T.cursor(e?n.to:n.from)}function Tf(n,e){return at(n,t=>t.empty?n.moveByChar(t,e):qs(t,e))}function Re(n){return n.textDirectionAt(n.state.selection.main.head)==ce.LTR}var Rf=n=>Tf(n,!Re(n)),Df=n=>Tf(n,Re(n));function Af(n,e){return at(n,t=>t.empty?n.moveByGroup(t,e):qs(t,e))}var Qb=n=>Af(n,!Re(n)),Xb=n=>Af(n,Re(n));function Yb(n,e,t){if(e.type.prop(t))return!0;let i=e.to-e.from;return i&&(i>2||/[^\s,.;:]/.test(n.sliceDoc(e.from,e.to)))||e.firstChild}function Gs(n,e,t){let i=We(n).resolveInner(e.head),r=t?F.closedBy:F.openedBy;for(let a=e.head;;){let u=t?i.childAfter(a):i.childBefore(a);if(!u)break;Yb(n,u,r)?i=u:a=t?u.to:u.from}let s=i.type.prop(r),o,l;return s&&(o=t?Ki(n,i.from,1):Ki(n,i.to,-1))&&o.matched?l=t?o.end.to:o.end.from:l=t?i.to:i.from,T.cursor(l,t?-1:1)}var Zb=n=>at(n,e=>Gs(n.state,e,!Re(n))),e0=n=>at(n,e=>Gs(n.state,e,Re(n)));function Pf(n,e){return at(n,t=>{if(!t.empty)return qs(t,e);let i=n.moveVertically(t,e);return i.head!=t.head?i:n.moveToLineBoundary(t,e)})}var Ef=n=>Pf(n,!1),Of=n=>Pf(n,!0);function If(n){let e=n.scrollDOM.clientHeight<n.scrollDOM.scrollHeight-2,t=0,i=0,r;if(e){for(let s of n.state.facet(H.scrollMargins)){let o=s(n);o!=null&&o.top&&(t=Math.max(o==null?void 0:o.top,t)),o!=null&&o.bottom&&(i=Math.max(o==null?void 0:o.bottom,i))}r=n.scrollDOM.clientHeight-t-i}else r=(n.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:t,marginBottom:i,selfScroll:e,height:Math.max(n.defaultLineHeight,r-5)}}function Vf(n,e){let t=If(n),{state:i}=n,r=Pn(i.selection,o=>o.empty?n.moveVertically(o,e,t.height):qs(o,e));if(r.eq(i.selection))return!1;let s;if(t.selfScroll){let o=n.coordsAtPos(i.selection.main.head),l=n.scrollDOM.getBoundingClientRect(),a=l.top+t.marginTop,u=l.bottom-t.marginBottom;o&&o.top>a&&o.bottom<u&&(s=H.scrollIntoView(r.main.head,{y:"start",yMargin:o.top-a}))}return n.dispatch(St(i,r),{effects:s}),!0}var df=n=>Vf(n,!1),na=n=>Vf(n,!0);function oi(n,e,t){let i=n.lineBlockAt(e.head),r=n.moveToLineBoundary(e,t);if(r.head==e.head&&r.head!=(t?i.to:i.from)&&(r=n.moveToLineBoundary(e,t,!1)),!t&&r.head==i.from&&i.length){let s=/^\s*/.exec(n.state.sliceDoc(i.from,Math.min(i.from+100,i.to)))[0].length;s&&e.head!=i.from+s&&(r=T.cursor(i.from+s))}return r}var t0=n=>at(n,e=>oi(n,e,!0)),i0=n=>at(n,e=>oi(n,e,!1)),n0=n=>at(n,e=>oi(n,e,!Re(n))),r0=n=>at(n,e=>oi(n,e,Re(n))),s0=n=>at(n,e=>T.cursor(n.lineBlockAt(e.head).from,1)),o0=n=>at(n,e=>T.cursor(n.lineBlockAt(e.head).to,-1));function l0(n,e,t){let i=!1,r=Pn(n.selection,s=>{let o=Ki(n,s.head,-1)||Ki(n,s.head,1)||s.head>0&&Ki(n,s.head-1,1)||s.head<n.doc.length&&Ki(n,s.head+1,-1);if(!o||!o.end)return s;i=!0;let l=o.start.from==s.head?o.end.to:o.end.from;return t?T.range(s.anchor,l):T.cursor(l)});return i?(e(St(n,r)),!0):!1}var a0=({state:n,dispatch:e})=>l0(n,e,!1);function Xe(n,e){let t=Pn(n.state.selection,i=>{let r=e(i);return T.range(i.anchor,r.head,r.goalColumn,r.bidiLevel||void 0)});return t.eq(n.state.selection)?!1:(n.dispatch(St(n.state,t)),!0)}function Lf(n,e){return Xe(n,t=>n.moveByChar(t,e))}var Nf=n=>Lf(n,!Re(n)),Bf=n=>Lf(n,Re(n));function Ff(n,e){return Xe(n,t=>n.moveByGroup(t,e))}var u0=n=>Ff(n,!Re(n)),h0=n=>Ff(n,Re(n));var c0=n=>Xe(n,e=>Gs(n.state,e,!Re(n))),f0=n=>Xe(n,e=>Gs(n.state,e,Re(n)));function Hf(n,e){return Xe(n,t=>n.moveVertically(t,e))}var Wf=n=>Hf(n,!1),_f=n=>Hf(n,!0);function zf(n,e){return Xe(n,t=>n.moveVertically(t,e,If(n).height))}var pf=n=>zf(n,!1),mf=n=>zf(n,!0),d0=n=>Xe(n,e=>oi(n,e,!0)),p0=n=>Xe(n,e=>oi(n,e,!1)),m0=n=>Xe(n,e=>oi(n,e,!Re(n))),g0=n=>Xe(n,e=>oi(n,e,Re(n))),b0=n=>Xe(n,e=>T.cursor(n.lineBlockAt(e.head).from)),y0=n=>Xe(n,e=>T.cursor(n.lineBlockAt(e.head).to)),gf=({state:n,dispatch:e})=>(e(St(n,{anchor:0})),!0),bf=({state:n,dispatch:e})=>(e(St(n,{anchor:n.doc.length})),!0),yf=({state:n,dispatch:e})=>(e(St(n,{anchor:n.selection.main.anchor,head:0})),!0),wf=({state:n,dispatch:e})=>(e(St(n,{anchor:n.selection.main.anchor,head:n.doc.length})),!0),w0=({state:n,dispatch:e})=>(e(n.update({selection:{anchor:0,head:n.doc.length},userEvent:"select"})),!0),v0=({state:n,dispatch:e})=>{let t=Js(n).map(({from:i,to:r})=>T.range(i,Math.min(r+1,n.doc.length)));return e(n.update({selection:T.create(t),userEvent:"select"})),!0},C0=({state:n,dispatch:e})=>{let t=Pn(n.selection,i=>{var r;let s=We(n).resolveInner(i.head,1);for(;!(s.from<i.from&&s.to>=i.to||s.to>i.to&&s.from<=i.from||!(!((r=s.parent)===null||r===void 0)&&r.parent));)s=s.parent;return T.range(s.to,s.from)});return e(St(n,t)),!0},S0=({state:n,dispatch:e})=>{let t=n.selection,i=null;return t.ranges.length>1?i=T.create([t.main]):t.main.empty||(i=T.create([T.cursor(t.main.head)])),i?(e(St(n,i)),!0):!1};function js(n,e){if(n.state.readOnly)return!1;let t="delete.selection",{state:i}=n,r=i.changeByRange(s=>{let{from:o,to:l}=s;if(o==l){let a=e(o);a<o?(t="delete.backward",a=Us(n,a,!1)):a>o&&(t="delete.forward",a=Us(n,a,!0)),o=Math.min(o,a),l=Math.max(l,a)}else o=Us(n,o,!1),l=Us(n,l,!0);return o==l?{range:s}:{changes:{from:o,to:l},range:T.cursor(o)}});return r.changes.empty?!1:(n.dispatch(i.update(r,{scrollIntoView:!0,userEvent:t,effects:t=="delete.selection"?H.announce.of(i.phrase("Selection deleted")):void 0})),!0)}function Us(n,e,t){if(n instanceof H)for(let i of n.state.facet(H.atomicRanges).map(r=>r(n)))i.between(e,e,(r,s)=>{r<e&&s>e&&(e=t?s:r)});return e}var Uf=(n,e)=>js(n,t=>{let{state:i}=n,r=i.doc.lineAt(t),s,o;if(!e&&t>r.from&&t<r.from+200&&!/[^ \t]/.test(s=r.text.slice(0,t-r.from))){if(s[s.length-1]==" ")return t-1;let l=Hi(s,i.tabSize),a=l%xr(i)||xr(i);for(let u=0;u<a&&s[s.length-1-u]==" ";u++)t--;o=t}else o=De(r.text,t-r.from,e,e)+r.from,o==t&&r.number!=(e?i.doc.lines:1)&&(o+=e?1:-1);return o}),ra=n=>Uf(n,!1),$f=n=>Uf(n,!0),Kf=(n,e)=>js(n,t=>{let i=t,{state:r}=n,s=r.doc.lineAt(i),o=r.charCategorizer(i);for(let l=null;;){if(i==(e?s.to:s.from)){i==t&&s.number!=(e?r.doc.lines:1)&&(i+=e?1:-1);break}let a=De(s.text,i-s.from,e)+s.from,u=s.text.slice(Math.min(i,a)-s.from,Math.max(i,a)-s.from),h=o(u);if(l!=null&&h!=l)break;(u!=" "||i!=t)&&(l=h),i=a}return i}),qf=n=>Kf(n,!1),x0=n=>Kf(n,!0),Gf=n=>js(n,e=>{let t=n.lineBlockAt(e).to;return e<t?t:Math.min(n.state.doc.length,e+1)}),k0=n=>js(n,e=>{let t=n.lineBlockAt(e).from;return e>t?t:Math.max(0,e-1)});var M0=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>({changes:{from:i.from,to:i.to,insert:_.of(["",""])},range:T.cursor(i.from)}));return e(n.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},T0=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>{if(!i.empty||i.from==0||i.from==n.doc.length)return{range:i};let r=i.from,s=n.doc.lineAt(r),o=r==s.from?r-1:De(s.text,r-s.from,!1)+s.from,l=r==s.to?r+1:De(s.text,r-s.from,!0)+s.from;return{changes:{from:o,to:l,insert:n.doc.slice(r,l).append(n.doc.slice(o,r))},range:T.cursor(l)}});return t.changes.empty?!1:(e(n.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function Js(n){let e=[],t=-1;for(let i of n.selection.ranges){let r=n.doc.lineAt(i.from),s=n.doc.lineAt(i.to);if(!i.empty&&i.to==s.from&&(s=n.doc.lineAt(i.to-1)),t>=r.number){let o=e[e.length-1];o.to=s.to,o.ranges.push(i)}else e.push({from:r.from,to:s.to,ranges:[i]});t=s.number+1}return e}function jf(n,e,t){if(n.readOnly)return!1;let i=[],r=[];for(let s of Js(n)){if(t?s.to==n.doc.length:s.from==0)continue;let o=n.doc.lineAt(t?s.to+1:s.from-1),l=o.length+1;if(t){i.push({from:s.to,to:o.to},{from:s.from,insert:o.text+n.lineBreak});for(let a of s.ranges)r.push(T.range(Math.min(n.doc.length,a.anchor+l),Math.min(n.doc.length,a.head+l)))}else{i.push({from:o.from,to:s.from},{from:s.to,insert:n.lineBreak+o.text});for(let a of s.ranges)r.push(T.range(a.anchor-l,a.head-l))}}return i.length?(e(n.update({changes:i,scrollIntoView:!0,selection:T.create(r,n.selection.mainIndex),userEvent:"move.line"})),!0):!1}var R0=({state:n,dispatch:e})=>jf(n,e,!1),D0=({state:n,dispatch:e})=>jf(n,e,!0);function Jf(n,e,t){if(n.readOnly)return!1;let i=[];for(let r of Js(n))t?i.push({from:r.from,insert:n.doc.slice(r.from,r.to)+n.lineBreak}):i.push({from:r.to,insert:n.lineBreak+n.doc.slice(r.from,r.to)});return e(n.update({changes:i,scrollIntoView:!0,userEvent:"input.copyline"})),!0}var A0=({state:n,dispatch:e})=>Jf(n,e,!1),P0=({state:n,dispatch:e})=>Jf(n,e,!0),E0=n=>{if(n.state.readOnly)return!1;let{state:e}=n,t=e.changes(Js(e).map(({from:r,to:s})=>(r>0?r--:s<e.doc.length&&s++,{from:r,to:s}))),i=Pn(e.selection,r=>n.moveVertically(r,!0)).map(t);return n.dispatch({changes:t,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0};function O0(n,e){if(/\(\)|\[\]|\{\}/.test(n.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=We(n).resolveInner(e),i=t.childBefore(e),r=t.childAfter(e),s;return i&&r&&i.to<=e&&r.from>=e&&(s=i.type.prop(F.closedBy))&&s.indexOf(r.name)>-1&&n.doc.lineAt(i.to).from==n.doc.lineAt(r.from).from?{from:i.to,to:r.from}:null}var I0=Qf(!1),V0=Qf(!0);function Qf(n){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let i=e.changeByRange(r=>{let{from:s,to:o}=r,l=e.doc.lineAt(s),a=!n&&s==o&&O0(e,s);n&&(s=o=(o<=l.to?l:e.doc.lineAt(o)).to);let u=new $i(e,{simulateBreak:s,simulateDoubleBreak:!!a}),h=Yl(u,s);for(h==null&&(h=/^\s*/.exec(e.doc.lineAt(s).text)[0].length);o<l.to&&/\s/.test(l.text[o-l.from]);)o++;a?{from:s,to:o}=a:s>l.from&&s<l.from+100&&!/\S/.test(l.text.slice(0,s))&&(s=l.from);let c=["",kr(e,h)];return a&&c.push(kr(e,u.lineIndent(l.from,-1))),{changes:{from:s,to:o,insert:_.of(c)},range:T.cursor(s+1+c[1].length)}});return t(e.update(i,{scrollIntoView:!0,userEvent:"input"})),!0}}function ua(n,e){let t=-1;return n.changeByRange(i=>{let r=[];for(let o=i.from;o<=i.to;){let l=n.doc.lineAt(o);l.number>t&&(i.empty||i.to>l.from)&&(e(l,r,i),t=l.number),o=l.to+1}let s=n.changes(r);return{changes:r,range:T.range(s.mapPos(i.anchor,1),s.mapPos(i.head,1))}})}var L0=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=Object.create(null),i=new $i(n,{overrideIndentation:s=>{let o=t[s];return o==null?-1:o}}),r=ua(n,(s,o,l)=>{let a=Yl(i,s.from);if(a==null)return;/\S/.test(s.text)||(a=0);let u=/^\s*/.exec(s.text)[0],h=kr(n,a);(u!=h||l.from<s.from+u.length)&&(t[s.from]=a,o.push({from:s.from,to:s.from+u.length,insert:h}))});return r.changes.empty||e(n.update(r,{userEvent:"indent"})),!0},N0=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(ua(n,(t,i)=>{i.push({from:t.from,insert:n.facet(zs)})}),{userEvent:"input.indent"})),!0),B0=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(ua(n,(t,i)=>{let r=/^\s*/.exec(t.text)[0];if(!r)return;let s=Hi(r,n.tabSize),o=0,l=kr(n,Math.max(0,s-xr(n)));for(;o<r.length&&o<l.length&&r.charCodeAt(o)==l.charCodeAt(o);)o++;i.push({from:t.from+o,to:t.from+r.length,insert:l.slice(o)})}),{userEvent:"delete.dedent"})),!0);var F0=[{key:"Ctrl-b",run:Rf,shift:Nf,preventDefault:!0},{key:"Ctrl-f",run:Df,shift:Bf},{key:"Ctrl-p",run:Ef,shift:Wf},{key:"Ctrl-n",run:Of,shift:_f},{key:"Ctrl-a",run:s0,shift:b0},{key:"Ctrl-e",run:o0,shift:y0},{key:"Ctrl-d",run:$f},{key:"Ctrl-h",run:ra},{key:"Ctrl-k",run:Gf},{key:"Ctrl-Alt-h",run:qf},{key:"Ctrl-o",run:M0},{key:"Ctrl-t",run:T0},{key:"Ctrl-v",run:na}],H0=[{key:"ArrowLeft",run:Rf,shift:Nf,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:Qb,shift:u0,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:n0,shift:m0,preventDefault:!0},{key:"ArrowRight",run:Df,shift:Bf,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:Xb,shift:h0,preventDefault:!0},{mac:"Cmd-ArrowRight",run:r0,shift:g0,preventDefault:!0},{key:"ArrowUp",run:Ef,shift:Wf,preventDefault:!0},{mac:"Cmd-ArrowUp",run:gf,shift:yf},{mac:"Ctrl-ArrowUp",run:df,shift:pf},{key:"ArrowDown",run:Of,shift:_f,preventDefault:!0},{mac:"Cmd-ArrowDown",run:bf,shift:wf},{mac:"Ctrl-ArrowDown",run:na,shift:mf},{key:"PageUp",run:df,shift:pf},{key:"PageDown",run:na,shift:mf},{key:"Home",run:i0,shift:p0,preventDefault:!0},{key:"Mod-Home",run:gf,shift:yf},{key:"End",run:t0,shift:d0,preventDefault:!0},{key:"Mod-End",run:bf,shift:wf},{key:"Enter",run:I0},{key:"Mod-a",run:w0},{key:"Backspace",run:ra,shift:ra},{key:"Delete",run:$f},{key:"Mod-Backspace",mac:"Alt-Backspace",run:qf},{key:"Mod-Delete",mac:"Alt-Delete",run:x0},{mac:"Mod-Backspace",run:k0},{mac:"Mod-Delete",run:Gf}].concat(F0.map(n=>({mac:n.key,run:n.run,shift:n.shift}))),Qs=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:Zb,shift:c0},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:e0,shift:f0},{key:"Alt-ArrowUp",run:R0},{key:"Shift-Alt-ArrowUp",run:A0},{key:"Alt-ArrowDown",run:D0},{key:"Shift-Alt-ArrowDown",run:P0},{key:"Escape",run:S0},{key:"Mod-Enter",run:V0},{key:"Alt-l",mac:"Ctrl-l",run:v0},{key:"Mod-i",run:C0,preventDefault:!0},{key:"Mod-[",run:B0},{key:"Mod-]",run:N0},{key:"Mod-Alt-\\",run:L0},{key:"Shift-Mod-k",run:E0},{key:"Shift-Mod-\\",run:a0},{key:"Mod-/",run:Ob},{key:"Alt-A",run:Vb}].concat(H0);var On=class{constructor(e,t,i,r,s,o,l,a,u,h=0,c){this.p=e,this.stack=t,this.state=i,this.reducePos=r,this.pos=s,this.score=o,this.buffer=l,this.bufferBase=a,this.curContext=u,this.lookAhead=h,this.parent=c}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,i=0){let r=e.parser.context;return new On(e,[],t,i,i,0,[],0,r?new Xs(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let i=e>>19,r=e&65535,{parser:s}=this.p,o=s.dynamicPrecedence(r);if(o&&(this.score+=o),i==0){this.pushState(s.getGoto(this.state,r,!0),this.reducePos),r<s.minRepeatTerm&&this.storeNode(r,this.reducePos,this.reducePos,4,!0),this.reduceContext(r,this.reducePos);return}let l=this.stack.length-(i-1)*3-(e&262144?6:0),a=l?this.stack[l-2]:this.p.ranges[0].from,u=this.reducePos-a;u>=2e3&&!(!((t=this.p.parser.nodeSet.types[r])===null||t===void 0)&&t.isAnonymous)&&(a==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=u):this.p.lastBigReductionSize<u&&(this.p.bigReductionCount=1,this.p.lastBigReductionStart=a,this.p.lastBigReductionSize=u));let h=l?this.stack[l-1]:0,c=this.bufferBase+this.buffer.length-h;if(r<s.minRepeatTerm||e&131072){let f=s.stateFlag(this.state,1)?this.pos:this.reducePos;this.storeNode(r,a,f,c+4,!0)}if(e&262144)this.state=this.stack[l];else{let f=this.stack[l-3];this.state=s.getGoto(f,r,!0)}for(;this.stack.length>l;)this.stack.pop();this.reduceContext(r,a)}storeNode(e,t,i,r=4,s=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){let o=this,l=this.buffer.length;if(l==0&&o.parent&&(l=o.bufferBase-o.parent.bufferBase,o=o.parent),l>0&&o.buffer[l-4]==0&&o.buffer[l-1]>-1){if(t==i)return;if(o.buffer[l-2]>=t){o.buffer[l-2]=i;return}}}if(!s||this.pos==i)this.buffer.push(e,t,i,r);else{let o=this.buffer.length;if(o>0&&this.buffer[o-4]!=0)for(;o>0&&this.buffer[o-2]>i;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,r>4&&(r-=4);this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=r}}shift(e,t,i){let r=this.pos;if(e&131072)this.pushState(e&65535,this.pos);else if(e&262144)this.pos=i,this.shiftContext(t,r),t<=this.p.parser.maxNode&&this.buffer.push(t,r,i,4);else{let s=e,{parser:o}=this.p;(i>this.pos||t<=o.maxNode)&&(this.pos=i,o.stateFlag(s,1)||(this.reducePos=i)),this.pushState(s,r),this.shiftContext(t,r),t<=o.maxNode&&this.buffer.push(t,r,i,4)}}apply(e,t,i){e&65536?this.reduce(e):this.shift(e,t,i)}useNode(e,t){let i=this.p.reused.length-1;(i<0||this.p.reused[i]!=e)&&(this.p.reused.push(e),i++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(i,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),r=e.bufferBase+t;for(;e&&r==e.bufferBase;)e=e.parent;return new On(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,r,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new ca(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if(!(i&65536))return!0;t.reduce(i)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>4<<1||this.stack.length>=120){let r=[];for(let s=0,o;s<t.length;s+=2)(o=t[s+1])!=this.state&&this.p.parser.hasAction(o,e)&&r.push(t[s],o);if(this.stack.length<120)for(let s=0;r.length<4<<1&&s<t.length;s+=2){let o=t[s+1];r.some((l,a)=>a&1&&l==o)||r.push(t[s],o)}t=r}let i=[];for(let r=0;r<t.length&&i.length<4;r+=2){let s=t[r+1];if(s==this.state)continue;let o=this.split();o.pushState(s,this.pos),o.storeNode(0,o.pos,o.pos,4,!0),o.shiftContext(t[r],this.pos),o.score-=200,i.push(o)}return i}forceReduce(){let e=this.p.parser.stateSlot(this.state,5);if(!(e&65536))return!1;let{parser:t}=this.p;if(!t.validAction(this.state,e)){let i=e>>19,r=e&65535,s=this.stack.length-i*3;if(s<0||t.getGoto(this.stack[s],r,!1)<0)return!1;this.storeNode(0,this.reducePos,this.reducePos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(e),!0}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t<this.stack.length;t+=3)if(this.stack[t]!=e.stack[t])return!1;return!0}get parser(){return this.p.parser}dialectEnabled(e){return this.p.parser.dialect.flags[e]}shiftContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.shift(this.curContext.context,e,this,this.p.stream.reset(t)))}reduceContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.reduce(this.curContext.context,e,this,this.p.stream.reset(t)))}emitContext(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-3)&&this.buffer.push(this.curContext.hash,this.reducePos,this.reducePos,-3)}emitLookAhead(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-4)&&this.buffer.push(this.lookAhead,this.reducePos,this.reducePos,-4)}updateContext(e){if(e!=this.curContext.context){let t=new Xs(this.curContext.tracker,e);t.hash!=this.curContext.hash&&this.emitContext(),this.curContext=t}}setLookAhead(e){e>this.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}},Xs=class{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}},Xf;(function(n){n[n.Insert=200]="Insert",n[n.Delete=190]="Delete",n[n.Reduce=100]="Reduce",n[n.MaxNext=4]="MaxNext",n[n.MaxInsertStackDepth=300]="MaxInsertStackDepth",n[n.DampenInsertStackDepth=120]="DampenInsertStackDepth",n[n.MinBigReduction=2e3]="MinBigReduction"})(Xf||(Xf={}));var ca=class{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}},In=class{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new In(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new In(this.stack,this.pos,this.index)}};function Rr(n,e=Uint16Array){if(typeof n!="string")return n;let t=null;for(let i=0,r=0;i<n.length;){let s=0;for(;;){let o=n.charCodeAt(i++),l=!1;if(o==126){s=65535;break}o>=92&&o--,o>=34&&o--;let a=o-32;if(a>=46&&(a-=46,l=!0),s+=a,l)break;s*=46}t?t[r++]=s:t=new e(s)}return t}var En=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}},Yf=new En,fa=class{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=Yf,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let i=this.range,r=this.rangeIndex,s=this.pos+e;for(;s<i.from;){if(!r)return null;let o=this.ranges[--r];s-=i.from-o.to,i=o}for(;t<0?s>i.to:s>=i.to;){if(r==this.ranges.length-1)return null;let o=this.ranges[++r];s+=o.from-i.to,i=o}return s}clipPos(e){if(e>=this.range.from&&e<this.range.to)return e;for(let t of this.ranges)if(t.to>e)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,r;if(t>=0&&t<this.chunk.length)i=this.pos+e,r=this.chunk.charCodeAt(t);else{let s=this.resolveOffset(e,1);if(s==null)return-1;if(i=s,i>=this.chunk2Pos&&i<this.chunk2Pos+this.chunk2.length)r=this.chunk2.charCodeAt(i-this.chunk2Pos);else{let o=this.rangeIndex,l=this.range;for(;l.to<=i;)l=this.ranges[++o];this.chunk2=this.input.chunk(this.chunk2Pos=i),i+this.chunk2.length>l.to&&(this.chunk2=this.chunk2.slice(0,l.to-i)),r=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),r}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i<this.token.start)throw new RangeError("Token end out of bounds");this.token.value=e,this.token.end=i}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk:e,chunkPos:t}=this;this.chunk=this.chunk2,this.chunkPos=this.chunk2Pos,this.chunk2=e,this.chunk2Pos=t,this.chunkOff=this.pos-this.chunkPos}else{this.chunk2=this.chunk,this.chunk2Pos=this.chunkPos;let e=this.input.chunk(this.pos),t=this.pos+e.length;this.chunk=t>this.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=Yf,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e<this.range.from;)this.range=this.ranges[--this.rangeIndex];for(;e>=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e<this.chunkPos+this.chunk.length?this.chunkOff=e-this.chunkPos:(this.chunk="",this.chunkOff=0),this.readNext()}return this}read(e,t){if(e>=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let i="";for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(i+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return i}},li=class{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:i}=t.p;sd(this.data,e,t,this.id,i.data,i.tokenPrecTable)}};li.prototype.contextual=li.prototype.fallback=li.prototype.extend=!1;var da=class{constructor(e,t,i){this.precTable=t,this.elseToken=i,this.data=typeof e=="string"?Rr(e):e}token(e,t){let i=e.pos,r;for(;r=e.pos,sd(this.data,e,t,0,this.data,this.precTable),!(e.token.value>-1);){if(this.elseToken==null)return;if(e.next<0)break;e.advance(),e.reset(r+1,e.token)}r>i&&(e.reset(i,e.token),e.acceptToken(this.elseToken,r-i))}};da.prototype.contextual=li.prototype.fallback=li.prototype.extend=!1;function sd(n,e,t,i,r,s){let o=0,l=1<<i,{dialect:a}=t.p.parser;e:for(;l&n[o];){let u=n[o+1];for(let d=o+3;d<u;d+=2)if((n[d+1]&l)>0){let p=n[d];if(a.allows(p)&&(e.token.value==-1||e.token.value==p||_0(p,e.token.value,r,s))){e.acceptToken(p);break}}let h=e.next,c=0,f=n[o+2];if(e.next<0&&f>c&&n[u+f*3-3]==65535&&n[u+f*3-3]==65535){o=n[u+f*3-1];continue e}for(;c<f;){let d=c+f>>1,p=u+d+(d<<1),m=n[p],g=n[p+1]||65536;if(h<m)f=d;else if(h>=g)c=d+1;else{o=n[p+2],e.advance();continue e}}break}}function Zf(n,e,t){for(let i=e,r;(r=n[i])!=65535;i++)if(r==t)return i-e;return-1}function _0(n,e,t,i){let r=Zf(t,i,e);return r<0||Zf(t,i,n)<r}var ut=typeof process<"u"&&process.env&&/\bparse\b/.test(process.env.LOG),ha=null,ed;(function(n){n[n.Margin=25]="Margin"})(ed||(ed={}));function td(n,e,t){let i=n.cursor(be.IncludeAnonymous);for(i.moveTo(e);;)if(!(t<0?i.childBefore(e):i.childAfter(e)))for(;;){if((t<0?i.to<e:i.from>e)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(n.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:n.length}}var pa=class{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?td(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?td(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(e<this.nextStart)return null;for(;this.fragment&&this.safeTo<=e;)this.nextFragment();if(!this.fragment)return null;for(;;){let t=this.trees.length-1;if(t<0)return this.nextFragment(),null;let i=this.trees[t],r=this.index[t];if(r==i.children.length){this.trees.pop(),this.start.pop(),this.index.pop();continue}let s=i.children[r],o=this.start[t]+i.positions[r];if(o>e)return this.nextStart=o,null;if(s instanceof te){if(o==e){if(o<this.safeFrom)return null;let l=o+s.length;if(l<=this.safeTo){let a=s.prop(F.lookAhead);if(!a||l+a<this.fragment.to)return s}}this.index[t]++,o+s.length>=Math.max(this.safeFrom,e)&&(this.trees.push(s),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+s.length}}},ma=class{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new En)}getActions(e){let t=0,i=null,{parser:r}=e.p,{tokenizers:s}=r,o=r.stateSlot(e.state,3),l=e.curContext?e.curContext.hash:0,a=0;for(let u=0;u<s.length;u++){if(!(1<<u&o))continue;let h=s[u],c=this.tokens[u];if(!(i&&!h.fallback)&&((h.contextual||c.start!=e.pos||c.mask!=o||c.context!=l)&&(this.updateCachedToken(c,h,e),c.mask=o,c.context=l),c.lookAhead>c.end+25&&(a=Math.max(c.lookAhead,a)),c.value!=0)){let f=t;if(c.extended>-1&&(t=this.addActions(e,c.extended,c.end,t)),t=this.addActions(e,c.value,c.end,t),!h.extend&&(i=c,t>f))break}}for(;this.actions.length>t;)this.actions.pop();return a&&e.setLookAhead(a),!i&&e.pos==this.stream.end&&(i=new En,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new En,{pos:i,p:r}=e;return t.start=i,t.end=Math.min(i+1,r.stream.end),t.value=i==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,i){let r=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(r,e),i),e.value>-1){let{parser:s}=i.p;for(let o=0;o<s.specialized.length;o++)if(s.specialized[o]==e.value){let l=s.specializers[o](this.stream.read(e.start,e.end),i);if(l>=0&&i.p.parser.dialect.allows(l>>1)){l&1?e.extended=l>>1:e.value=l>>1;break}}}else e.value=0,e.end=this.stream.clipPos(r+1)}putAction(e,t,i,r){for(let s=0;s<r;s+=3)if(this.actions[s]==e)return r;return this.actions[r++]=e,this.actions[r++]=t,this.actions[r++]=i,r}addActions(e,t,i,r){let{state:s}=e,{parser:o}=e.p,{data:l}=o;for(let a=0;a<2;a++)for(let u=o.stateSlot(s,a?2:1);;u+=3){if(l[u]==65535)if(l[u+1]==1)u=Ut(l,u+2);else{r==0&&l[u+1]==2&&(r=this.putAction(Ut(l,u+2),t,i,r));break}l[u]==t&&(r=this.putAction(Ut(l,u+1),t,i,r))}return r}},id;(function(n){n[n.Distance=5]="Distance",n[n.MaxRemainingPerStep=3]="MaxRemainingPerStep",n[n.MinBufferLengthPrune=500]="MinBufferLengthPrune",n[n.ForceReduceLimit=10]="ForceReduceLimit",n[n.CutDepth=15e3]="CutDepth",n[n.CutTo=9e3]="CutTo",n[n.MaxLeftAssociativeReductionCount=300]="MaxLeftAssociativeReductionCount",n[n.MaxStackCount=12]="MaxStackCount"})(id||(id={}));var ga=class{constructor(e,t,i,r){this.parser=e,this.input=t,this.ranges=r,this.recovering=0,this.nextStackID=9812,this.minStackPos=0,this.reused=[],this.stoppedAt=null,this.lastBigReductionStart=-1,this.lastBigReductionSize=0,this.bigReductionCount=0,this.stream=new fa(t,r),this.tokens=new ma(e,this.stream),this.topTerm=e.top[1];let{from:s}=r[0];this.stacks=[On.start(this,e.top[0],s)],this.fragments=i.length&&this.stream.end-s>e.bufferLength*4?new pa(i,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],r,s;if(this.bigReductionCount>300&&e.length==1){let[o]=e;for(;o.forceReduce()&&o.stack.length&&o.stack[o.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let o=0;o<e.length;o++){let l=e[o];for(;;){if(this.tokens.mainToken=null,l.pos>t)i.push(l);else{if(this.advanceStack(l,i,e))continue;{r||(r=[],s=[]),r.push(l);let a=this.tokens.getMainToken(l);s.push(a.value,a.end)}}break}}if(!i.length){let o=r&&z0(r);if(o)return this.stackToTree(o);if(this.parser.strict)throw ut&&r&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&r){let o=this.stoppedAt!=null&&r[0].pos>this.stoppedAt?r[0]:this.runRecovery(r,s,i);if(o)return this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((l,a)=>a.score-l.score);i.length>o;)i.pop();i.some(l=>l.reducePos>t)&&this.recovering--}else if(i.length>1){e:for(let o=0;o<i.length-1;o++){let l=i[o];for(let a=o+1;a<i.length;a++){let u=i[a];if(l.sameState(u)||l.buffer.length>500&&u.buffer.length>500)if((l.score-u.score||l.buffer.length-u.buffer.length)>0)i.splice(a--,1);else{i.splice(o--,1);continue e}}}i.length>12&&i.splice(12,i.length-12)}this.minStackPos=i[0].pos;for(let o=1;o<i.length;o++)i[o].pos<this.minStackPos&&(this.minStackPos=i[o].pos);return null}stopAt(e){if(this.stoppedAt!=null&&this.stoppedAt<e)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=e}advanceStack(e,t,i){let r=e.pos,{parser:s}=this,o=ut?this.stackID(e)+" -> ":"";if(this.stoppedAt!=null&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let u=e.curContext&&e.curContext.tracker.strict,h=u?e.curContext.hash:0;for(let c=this.fragments.nodeAt(r);c;){let f=this.parser.nodeSet.types[c.type.id]==c.type?s.getGoto(e.state,c.type.id):-1;if(f>-1&&c.length&&(!u||(c.prop(F.contextHash)||0)==h))return e.useNode(c,f),ut&&console.log(o+this.stackID(e)+` (via reuse of ${s.getName(c.type.id)})`),!0;if(!(c instanceof te)||c.children.length==0||c.positions[0]>0)break;let d=c.children[0];if(d instanceof te&&c.positions[0]==0)c=d;else break}}let l=s.stateSlot(e.state,4);if(l>0)return e.reduce(l),ut&&console.log(o+this.stackID(e)+` (via always-reduce ${s.getName(l&65535)})`),!0;if(e.stack.length>=15e3)for(;e.stack.length>9e3&&e.forceReduce(););let a=this.tokens.getActions(e);for(let u=0;u<a.length;){let h=a[u++],c=a[u++],f=a[u++],d=u==a.length||!i,p=d?e:e.split();if(p.apply(h,c,f),ut&&console.log(o+this.stackID(p)+` (via ${h&65536?`reduce of ${s.getName(h&65535)}`:"shift"} for ${s.getName(c)} @ ${r}${p==e?"":", split"})`),d)return!0;p.pos>r?t.push(p):i.push(p)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return nd(e,t),!0}}runRecovery(e,t,i){let r=null,s=!1;for(let o=0;o<e.length;o++){let l=e[o],a=t[o<<1],u=t[(o<<1)+1],h=ut?this.stackID(l)+" -> ":"";if(l.deadEnd&&(s||(s=!0,l.restart(),ut&&console.log(h+this.stackID(l)+" (restarted)"),this.advanceFully(l,i))))continue;let c=l.split(),f=h;for(let d=0;c.forceReduce()&&d<10&&(ut&&console.log(f+this.stackID(c)+" (via force-reduce)"),!this.advanceFully(c,i));d++)ut&&(f=this.stackID(c)+" -> ");for(let d of l.recoverByInsert(a))ut&&console.log(h+this.stackID(d)+" (via recover-insert)"),this.advanceFully(d,i);this.stream.end>l.pos?(u==l.pos&&(u++,a=0),l.recoverByDelete(a,u),ut&&console.log(h+this.stackID(l)+` (via recover-delete ${this.parser.getName(a)})`),nd(l,i)):(!r||r.score<l.score)&&(r=l)}return r}stackToTree(e){return e.close(),te.build({buffer:In.create(e),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:e.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm})}stackID(e){let t=(ha||(ha=new WeakMap)).get(e);return t||ha.set(e,t=String.fromCodePoint(this.nextStackID++)),t+e}};function nd(n,e){for(let t=0;t<e.length;t++){let i=e[t];if(i.pos==n.pos&&i.sameState(n)){e[t].score<n.score&&(e[t]=n);return}}e.push(n)}var ba=class{constructor(e,t,i){this.source=e,this.flags=t,this.disabled=i}allows(e){return!this.disabled||this.disabled[e]==0}};var ai=class extends kn{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let l=0;l<e.repeatNodeCount;l++)t.push("");let i=Object.keys(e.topRules).map(l=>e.topRules[l][1]),r=[];for(let l=0;l<t.length;l++)r.push([]);function s(l,a,u){r[l].push([a,a.deserialize(String(u))])}if(e.nodeProps)for(let l of e.nodeProps){let a=l[0];typeof a=="string"&&(a=F[a]);for(let u=1;u<l.length;){let h=l[u++];if(h>=0)s(h,a,l[u++]);else{let c=l[u+-h];for(let f=-h;f>0;f--)s(l[u++],a,c);u++}}}this.nodeSet=new zi(t.map((l,a)=>we.define({name:a>=this.minRepeatTerm?void 0:l,id:a,props:r[a],top:i.indexOf(a)>-1,error:a==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=1024;let o=Rr(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let l=0;l<this.specializerSpecs.length;l++)this.specialized[l]=this.specializerSpecs[l].term;this.specializers=this.specializerSpecs.map(rd),this.states=Rr(e.states,Uint32Array),this.data=Rr(e.stateData),this.goto=Rr(e.goto),this.maxTerm=e.maxTerm,this.tokenizers=e.tokenizers.map(l=>typeof l=="number"?new li(o,l):l),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,i){let r=new ga(this,e,t,i);for(let s of this.wrappers)r=s(r,e,t,i);return r}getGoto(e,t,i=!1){let r=this.goto;if(t>=r[0])return-1;for(let s=r[t+1];;){let o=r[s++],l=o&1,a=r[s++];if(l&&i)return a;for(let u=s+(o>>1);s<u;s++)if(r[s]==e)return a;if(l)return-1}}hasAction(e,t){let i=this.data;for(let r=0;r<2;r++)for(let s=this.stateSlot(e,r?2:1),o;;s+=3){if((o=i[s])==65535)if(i[s+1]==1)o=i[s=Ut(i,s+2)];else{if(i[s+1]==2)return Ut(i,s+2);break}if(o==t||o==0)return Ut(i,s+1)}return 0}stateSlot(e,t){return this.states[e*6+t]}stateFlag(e,t){return(this.stateSlot(e,0)&t)>0}validAction(e,t){if(t==this.stateSlot(e,4))return!0;for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=Ut(this.data,i+2);else return!1;if(t==Ut(this.data,i+1))return!0}}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=Ut(this.data,i+2);else break;if(!(this.data[i+2]&1)){let r=this.data[i+1];t.some((s,o)=>o&1&&s==r)||t.push(this.data[i],r)}}return t}configure(e){let t=Object.assign(Object.create(ai.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let i=this.topRules[e.top];if(!i)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=i}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(i=>{let r=e.tokenizers.find(s=>s.from==i);return r?r.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,r)=>{let s=e.specializers.find(l=>l.from==i.external);if(!s)return i;let o=Object.assign(Object.assign({},i),{external:s.to});return t.specializers[r]=rd(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),i=t.map(()=>!1);if(e)for(let s of e.split(" ")){let o=t.indexOf(s);o>=0&&(i[o]=!0)}let r=null;for(let s=0;s<t.length;s++)if(!i[s])for(let o=this.dialects[t[s]],l;(l=this.data[o++])!=65535;)(r||(r=new Uint8Array(this.maxTerm+1)))[l]=1;return new ba(e,i,r)}static deserialize(e){return new ai(e)}};function Ut(n,e){return n[e]|n[e+1]<<16}function z0(n){let e=null;for(let t of n){let i=t.p.stoppedAt;(t.pos==t.p.stream.end||i!=null&&t.pos>i)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.score<t.score)&&(e=t)}return e}function rd(n){if(n.external){let e=n.extend?1:0;return(t,i)=>n.external(t,i)<<1|e}return n.get}var U0=[...Qs,...aa],$0=(()=>[Vl(),la(),Il(),Mr(Zl,{fallback:!0}),gr.of(U0)])();var K0=require("@vuu-ui/vuu-utils");var od=[{label:"=",boost:10,type:"operator"},{label:"!=",boost:9,type:"operator"}],q0=[...od,{label:"in",boost:6,type:"operator"},{label:"starts",boost:5,type:"operator"},{label:"ends",boost:4,type:"operator"}],G0=[...od,{label:">",boost:8,type:"operator"},{label:"<",boost:7,type:"operator"}];var ty=ue(require("classnames"),1),va=require("react");var Ys=ai.deserialize({version:14,states:"%QOVQPOOOOQO'#C_'#C_O_QQO'#C^OOQO'#DO'#DOOvQQO'#C|OOQO'#DR'#DROVQPO'#CuOOQO'#C}'#C}QOQPOOOOQO'#C`'#C`O!UQQO,58xO!dQPO,59VOVQPO,59]OVQPO,59_O!iQPO,59hO!nQQO,59aOOQO'#DQ'#DQOOQO1G.d1G.dO!UQQO1G.qO!yQQO1G.wOOQO1G.y1G.yOOQO'#Cw'#CwOOQO1G/S1G/SOOQO1G.{1G.{O#[QPO'#CnO#dQPO7+$]O!UQQO'#CxO#iQPO,59YOOQO<<Gw<<GwOOQO,59d,59dOOQO-E6v-E6v",stateData:"#q~OoOS~OsPOvUO~OTXOUXOVXOWXOXXOYXO`ZO~Of[Oh]Oj^OmpX~OZ`O[`O]`O^`O~OabO~OseO~Of[Oh]OwgO~Oh]Ofeijeimeiwei~OcjOdbX~OdlO~OcjOdba~O",goto:"#YvPPw}!TPPPPPPPPPPwPP!WPP!ZP!ZP!aP!g!jPPP!p!s!aP#P!aXROU[]XQOU[]RYQRibXTOU[]XVOU[]Rf^QkhRnkRWOQSOQ_UQc[Rd]QaYQhbRmj",nodeNames:"\u26A0 Filter ColumnValueExpression Column Operator Eq NotEq Gt Lt Starts Ends Number String True False ColumnSetExpression In LBrack Values Comma RBrack AndExpression And OrExpression Or ParenthesizedExpression As FilterName",maxTerm:39,skippedNodes:[0],repeatNodeCount:1,tokenData:"6p~RnXY#PYZ#P]^#Ppq#Pqr#brs#mxy$eyz$j|}$o!O!P$t!Q![%S!^!_%_!_!`%d!`!a%i!c!}%n!}#O&V#P#Q&[#R#S%n#T#U&a#U#X%n#X#Y(w#Y#Z+]#Z#]%n#]#^.]#^#c%n#c#d/e#d#g%n#g#h0m#h#i4[#i#o%n~#USo~XY#PYZ#P]^#Ppq#P~#eP!_!`#h~#mOU~~#pWOX#mZ]#m^r#mrs$Ys#O#m#P;'S#m;'S;=`$_<%lO#m~$_O[~~$bP;=`<%l#m~$jOv~~$oOw~~$tOc~~$wP!Q![$z~%PPZ~!Q![$z~%XQZ~!O!P$t!Q![%S~%dOW~~%iOT~~%nOV~P%sUsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n~&[Oa~~&aOd~R&fYsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c'U#c#g%n#g#h(^#h#o%nR'ZWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X's#X#o%nR'zUfQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(eUjQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c)f#c#o%nR)kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X*T#X#o%nR*YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h*r#h#o%nR*yUYQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR+bVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U+w#U#o%nR+|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#`%n#`#a,f#a#o%nR,kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h-T#h#o%nR-YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y-r#Y#o%nR-yU^QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR.bWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c.z#c#o%nR/RU`QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR/jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g0S#g#o%nR0ZUhQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR0rWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i1[#i#o%nR1aVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U1v#U#o%nR1{WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g2e#g#o%nR2jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i3S#i#o%nR3XWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h3q#h#o%nR3xUXQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR4aWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g4y#g#o%nR5OWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#i%n#i#j5h#j#o%nR5mWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y6V#Y#o%nR6^U]QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n",tokenizers:[0,1],topRules:{Filter:[0,1]},tokenPrec:0});var tx=ri.define({name:"VuuFilterQuery",parser:Ys.configure({props:[vr({Identifier:D.variableName,String:D.string,Or:D.emphasis,Operator:D.operator})]})});var xt=require("@vuu-ui/vuu-utils");var Ee,ya=class{constructor(){W(this,Ee,void 0)}setFilterCombinatorOp(e,t=k(this,Ee)){(0,xt.isMultiClauseFilter)(t)&&t.op===e||P(this,Ee,{op:e,filters:[k(this,Ee)]})}add(e){if(k(this,Ee)===void 0)P(this,Ee,e);else if((0,xt.isMultiClauseFilter)(k(this,Ee)))k(this,Ee).filters.push(e);else throw Error("Invalid filter passed to FilterExpression")}setColumn(e,t=k(this,Ee)){if((0,xt.isMultiClauseFilter)(t)){let i=t.filters.at(-1);i&&this.setColumn(e,i)}else t&&(t.column=e)}setOp(e,t=k(this,Ee)){if((0,xt.isMultiClauseFilter)(t)){let i=t.filters.at(-1);i&&this.setOp(e,i)}else t&&(t.op=e)}setValue(e,t=k(this,Ee)){var i;if((0,xt.isMultiClauseFilter)(t)){let r=t.filters.at(-1);r&&this.setValue(e,r)}else(0,xt.isMultiValueFilter)(t)?((i=t.values)!=null||(t.values=[]),t.values.push(e)):(0,xt.isSingleValueFilter)(t)&&(t.value=e)}toJSON(e=k(this,Ee)){return this.name?{...e,name:this.name}:e}};Ee=new WeakMap;var wa=(n,e)=>{let t=new ya,i=n.cursor();do{let{name:r,from:s,to:o}=i;switch(r){case"ColumnValueExpression":t.add({});break;case"ColumnSetExpression":t.add({op:"in"});break;case"Or":case"And":t.setFilterCombinatorOp(e.substring(s,o));break;case"Column":t.setColumn(e.substring(s,o));break;case"Operator":t.setOp(e.substring(s,o));break;case"String":t.setValue(e.substring(s+1,o-1));break;case"Number":t.setValue(parseFloat(e.substring(s,o)));break;case"True":t.setValue(!0);break;case"False":t.setValue(!1);break;case"FilterName":t.name=e.substring(s,o);break;default:}}while(i.next());return t.toJSON()};var Q0=Ys.configure({strict:!0}),Dr=n=>{let e=Q0.parse(n);return wa(e,n)};var X0=zt.define([{tag:D.variableName,color:"var(--vuuFilterEditor-variableColor)"},{tag:D.comment,color:"green",fontStyle:"italic"}]),Y0=Mr(X0);var Z0=H.theme({"&":{color:"var(--vuuFilterEditor-color)",backgroundColor:"var(--vuuFilterEditor-background)",fontSize:"var(--vuuFilterEditor-fontSize)"},".cm-content":{caretColor:"var(--vuuFilterEditor-cursorColor)",padding:0},".cm-line":{lineHeight:"var(--vuuFilterEditor-lineHeight)"},"&.cm-focused .cm-cursor":{borderLeftColor:"var(--vuuFilterEditor-cursorColor)"},"&.cm-focused .cm-selectionBackground, ::selection":{backgroundColor:"var(--vuuFilterEditor-selectionBackground)"},".cm-selectionBackground, ::selection":{backgroundColor:"var(--vuuFilterEditor-selectionBackground)"},".cm-scroller":{fontFamily:"var(--vuuFilterEditor-fontFamily)"},".cm-tooltip":{background:"var(--vuuFilterEditor-tooltipBackground)",border:"var(--vuuFilterEditor-tooltipBorder)",boxShadow:"var(--vuuFilterEditor-tooltipElevation)","&.cm-tooltip-autocomplete > ul":{fontFamily:"var(--vuuFilterEditor-fontFamily)",fontSize:"var(--vuuFilterEditor-fontSize)",maxHeight:"240px"},"&.cm-tooltip-autocomplete > ul > li":{alignItems:"center",display:"flex",height:"var(--vuuFilterEditor-suggestion-height)",padding:"0 3px",lineHeight:"var(--vuuFilterEditor-suggestion-height)"},"&.cm-tooltip-autocomplete li[aria-selected]":{background:"var(--vuuFilterEditor-suggestion-selectedBackground)",color:"var(--vuuFilterEditor-suggestion-selectedColor)"}},".cm-completionIcon":{height:"18px",flex:"0 0 16px"},".cm-completionLabel":{flex:"1 1 auto"},".cm-completionIcon-filter":{position:"relative","&:after":{background:"var(--salt-text-secondary-foreground)",content:"''","-webkit-mask":"var(--svg-filter) center center/13px 13px","-webkit-mask-repeat":"no-repeat",position:"absolute",height:"18px",left:"0px",top:"0px",width:"16px"}}},{dark:!1});var ey=require("react");var ld=require("react/jsx-runtime");var Ln=require("@vuu-ui/vuu-utils");var ad=n=>n.type==="viewport-update"&&n.mode==="size-only";var Ar=(n,e)=>n===e?!0:n===void 0&&e===void 0,ny=({filter:n},{filter:e})=>n===void 0&&(e==null?void 0:e.filter)===""||e===void 0&&(n==null?void 0:n.filter)==="",ry=(n,e)=>{var t,i;return ny(n,e)?!1:((t=n.filter)==null?void 0:t.filter)!==((i=e.filter)==null?void 0:i.filter)},sy=({sort:n},{sort:e})=>n===void 0&&(e==null?void 0:e.sortDefs.length)===0||e===void 0&&(n==null?void 0:n.sortDefs.length)===0,oy=(n,e)=>{let{sort:t}=n,{sort:i}=e;return Ar(t,i)||sy(n,e)?!1:t===void 0||i===void 0||(t==null?void 0:t.sortDefs.length)!==(i==null?void 0:i.sortDefs.length)?!0:t.sortDefs.some(({column:r,sortType:s},o)=>r!==i.sortDefs[o].column||s!==i.sortDefs[o].sortType)};var ly=({groupBy:n},{groupBy:e})=>n===void 0&&(e==null?void 0:e.length)===0||e===void 0&&(n==null?void 0:n.length)===0,ay=(n,e)=>{let{groupBy:t}=n,{groupBy:i}=e;return Ar(t,i)||ly(n,e)?!1:t===void 0||i===void 0||(t==null?void 0:t.length)!==(i==null?void 0:i.length)?!0:t.some((r,s)=>r!==(i==null?void 0:i[s]))},uy=({columns:n},{columns:e})=>n===void 0&&(e==null?void 0:e.length)===0||e===void 0&&(n==null?void 0:n.length)===0,hy=(n,e)=>{let{columns:t}=n,{columns:i}=e;return Ar(t,i)||uy(n,e)?!1:t===void 0||i===void 0||(t==null?void 0:t.length)!==(i==null?void 0:i.length)?!0:t.some((r,s)=>r!==(i==null?void 0:i[s]))},cy=({aggregations:n},{aggregations:e})=>n===void 0&&(e==null?void 0:e.length)===0||e===void 0&&(n==null?void 0:n.length)===0,fy=(n,e)=>{let{aggregations:t}=n,{aggregations:i}=e;return Ar(t,i)||cy(n,e)?!1:t===void 0||i===void 0||t.length!==i.length?!0:t.some(({column:r,aggType:s},o)=>r!==i[o].column||s!==i[o].aggType)},dy=()=>!1,ud=(n,e)=>Ar(n,e)?!1:n===void 0||e===void 0?!0:hy(n,e)||ry(n,e)||oy(n,e)||ay(n,e)||fy(n,e)||dy(n,e),py=["config","aggregate","viewport-update","columns","debounce-begin","disabled","enabled","filter","groupBy","vuu-link-created","vuu-link-removed","vuu-links","vuu-menu","sort","subscribed"],hd=n=>{let e=n.type;return py.includes(e)},cd=n=>["config","aggregate","columns","filter","groupBy","sort"].includes(n.type),fd=n=>{if(n.aggregations&&n.columns&&n.filter&&n.groupBy&&n.sort)return n;{let{aggregations:e=[],columns:t=[],filter:i={filter:""},groupBy:r=[],sort:s={sortDefs:[]},visualLink:o}=n;return{aggregations:e,columns:t,filter:i,groupBy:r,sort:s,visualLink:o}}};var dd="GET_TABLE_LIST",pd="GET_TABLE_META";var Ca=n=>n.type==="connection-status",md=n=>typeof n.result<"u";var gd='\nvar le=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)};var c=(o,e,t)=>(le(o,e,"read from private field"),t?t.call(o):e.get(o)),U=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},ce=(o,e,t,r)=>(le(o,e,"write to private field"),r?r.call(o,t):e.set(o,t),t);function pe(o,e,t=[],r=[]){for(let s=0,n=o.length;s<n;s++)(e(o[s],s)?t:r).push(o[s]);return[t,r]}var N={IDX:0,RENDER_IDX:1,IS_LEAF:2,IS_EXPANDED:3,DEPTH:4,COUNT:5,KEY:6,SELECTED:7,count:8,PARENT_IDX:"parent_idx",IDX_POINTER:"idx_pointer",FILTER_COUNT:"filter_count",NEXT_FILTER_IDX:"next_filter_idx"};function j({from:o,to:e},t=0,r=Number.MAX_SAFE_INTEGER){if(t===0)return r<o?{from:0,to:0}:{from:o,to:Math.min(e,r)};if(o===0)return{from:o,to:Math.min(e+t,r)};{let s=e-o,n=Math.round(t/2),i=o-n<0,l=r-(e+n)<0;return i&&l?{from:0,to:r}:i?{from:0,to:s+t}:l?{from:Math.max(0,r-(s+t)),to:r}:{from:o-n,to:e+n}}}var je=(o,{from:e,to:t})=>o>=e&&o<t,w=class{constructor(e,t){this.from=e,this.to=t}isWithin(e){return je(e,this)}overlap(e,t){return e>=this.to||t<this.from?[0,0]:[Math.max(e,this.from),Math.min(t,this.to)]}copy(){return new w(this.from,this.to)}};var{KEY:Ot}=N;var F=()=>{},Ye="error",{loggingLevel:W=Ye}=typeof loggingSettings<"u"?loggingSettings:{},V=o=>{let e=W==="debug",t=e||W==="info",r=t||W==="warn",s=r||W==="error",n=t?a=>console.info(`[${o}] ${a}`):F,i=r?a=>console.warn(`[${o}] ${a}`):F,l=e?a=>console.debug(`[${o}] ${a}`):F;return{errorEnabled:s,error:s?a=>console.error(`[${o}] ${a}`):F}};var{debug:Xe,debugEnabled:Ze}=V("range-monitor"),q=class{constructor(e){this.source=e;this.range={from:0,to:0};this.timestamp=0}isSet(){return this.timestamp!==0}set({from:e,to:t}){let{timestamp:r}=this;if(this.range.from=e,this.range.to=t,this.timestamp=performance.now(),r)Ze&&Xe(`<${this.source}> [${e}-${t}], ${(this.timestamp-r).toFixed(0)} ms elapsed`);else return 0}};function ge(o){return Array.isArray(o)}function Qe(o){return!Array.isArray(o)}var y,de=class{constructor(){U(this,y,new Map)}addListener(e,t){let r=c(this,y).get(e);r?ge(r)?r.push(t):Qe(r)&&c(this,y).set(e,[r,t]):c(this,y).set(e,t)}removeListener(e,t){if(!c(this,y).has(e))return;let r=c(this,y).get(e),s=-1;if(r===t)c(this,y).delete(e);else if(Array.isArray(r)){for(let n=length;n-- >0;)if(r[n]===t){s=n;break}if(s<0)return;r.length===1?(r.length=0,c(this,y).delete(e)):r.splice(s,1)}}removeAllListeners(e){e&&c(this,y).has(e)?c(this,y).delete(e):e===void 0&&c(this,y).clear()}emit(e,...t){if(c(this,y)){let r=c(this,y).get(e);r&&this.invokeHandler(r,t)}}once(e,t){let r=(...s)=>{this.removeListener(e,r),t(...s)};this.on(e,r)}on(e,t){this.addListener(e,t)}invokeHandler(e,t){if(ge(e))e.slice().forEach(r=>this.invokeHandler(r,t));else switch(t.length){case 0:e();break;case 1:e(t[0]);break;case 2:e(t[0],t[1]);break;default:e.call(null,...t)}}};y=new WeakMap;var B=String.fromCharCode(8200),d=String.fromCharCode(8199);var Ht={DIGIT:d,TWO_DIGITS:d+d,THREE_DIGITS:d+d+d,FULL_PADDING:[null,B+d,B+d+d,B+d+d+d,B+d+d+d+d]};var Jt=d+d+d+d+d+d+d+d+d;var et={Enter:"Enter",Delete:"Delete"},tt={Home:"Home",End:"End",ArrowRight:"ArrowRight",ArrowLeft:"ArrowLeft",ArrowDown:"ArrowDown",ArrowUp:"ArrowUp",Tab:"Tab"},rt={F1:"F1",F2:"F2",F3:"F3",F4:"F4",F5:"F5",F6:"F6",F7:"F7",F8:"F8",F9:"F9",F10:"F10",F11:"F11",F12:"F12"},er={...et,...tt,...rt};var{COUNT:nr}=N;var G=class{constructor(e){this.keys=new Map,this.free=[],this.nextKeyValue=0,this.reset(e)}next(){return this.free.length>0?this.free.pop():this.nextKeyValue++}reset({from:e,to:t}){this.keys.forEach((s,n)=>{(n<e||n>=t)&&(this.free.push(s),this.keys.delete(n))});let r=t-e;this.keys.size+this.free.length>r&&(this.free.length=r-this.keys.size);for(let s=e;s<t;s++)if(!this.keys.has(s)){let n=this.next();this.keys.set(s,n)}}keyFor(e){let t=this.keys.get(e);if(t===void 0)throw console.log(`key not found\n keys: ${this.toDebugString()}\n free : ${this.free.join(",")} \n `),Error(`KeySet, no key found for rowIndex ${e}`);return t}toDebugString(){return Array.from(this.keys.entries()).map((e,t)=>`${e}=>${t}`).join(",")}};var fe=o=>{if(o.every(t=>typeof t=="number"))return o;let e=[];for(let t of o)if(typeof t=="number")e.push(t);else for(let r=t[0];r<=t[1];r++)e.push(r);return e};var{debug:Wr,debugEnabled:qr,error:st,info:T,warn:x}=V("websocket-connection"),he="ws",nt=o=>o.startsWith(he+"://")||o.startsWith(he+"s://"),me={},X=Symbol("setWebsocket"),$=Symbol("connectionCallback");async function Se(o,e){return Q(o,e)}async function Y(o){Q(o.url,o[$],o)}async function Q(o,e,t){let r=me[o]||(me[o]={attemptsRemaining:5,status:"disconnected"});try{e({type:"connection-status",status:"connecting"});let s=typeof t<"u",n=await it(o);console.info("%c\u26A1 %cconnected","font-size: 24px;color: green;font-weight: bold;","color:green; font-size: 14px;"),t!==void 0&&t[X](n);let i=t!=null?t:new Z(n,o,e),l=s?"reconnected":"connected";return e({type:"connection-status",status:l}),i.status=l,i}catch{let n=--r.attemptsRemaining>0;if(e({type:"connection-status",status:"disconnected",reason:"failed to connect",retry:n}),n)return ot(o,e,t,1e4);throw Error("Failed to establish connection")}}var ot=(o,e,t,r)=>new Promise(s=>{setTimeout(()=>{s(Q(o,e,t))},r)}),it=o=>new Promise((e,t)=>{let r=nt(o)?o:`wss://${o}`,s=new WebSocket(r);s.onopen=()=>e(s),s.onerror=n=>t(n)}),Ce=()=>{x==null||x("Connection cannot be closed, socket not yet opened")},be=o=>{x==null||x(`Message cannot be sent, socket closed ${o.body.type}`)},at=o=>{try{return JSON.parse(o)}catch{throw Error(`Error parsing JSON response from server ${o}`)}},Z=class{constructor(e,t,r){this.close=Ce;this.requiresLogin=!0;this.send=be;this.status="ready";this.url=t,this[$]=r,this[X](e)}reconnect(){Y(this)}[($,X)](e){let t=this[$];e.onmessage=n=>{let i=at(n.data);t(i)},e.onerror=()=>{st("\u26A1 connection error"),t({type:"connection-status",status:"disconnected",reason:"error"}),this.status!=="closed"&&(Y(this),this.send=s)},e.onclose=()=>{T==null||T("\u26A1 connection close"),t({type:"connection-status",status:"disconnected",reason:"close"}),this.status!=="closed"&&(Y(this),this.send=s)};let r=n=>{e.send(JSON.stringify(n))},s=n=>{T==null||T(`TODO queue message until websocket reconnected ${n.body.type}`)};this.send=r,this.close=()=>{this.status="closed",e.close(),this.close=Ce,this.send=be,T==null||T("close websocket")}}};var ut=["VIEW_PORT_MENUS_SELECT_RPC","VIEW_PORT_MENU_TABLE_RPC","VIEW_PORT_MENU_ROW_RPC","VIEW_PORT_MENU_CELL_RPC"],ye=o=>ut.includes(o.type),ee=({requestId:o,...e})=>[o,e];var Ve=o=>o.type==="connection-status";var Re=o=>"viewport"in o;var Me="CHANGE_VP_SUCCESS",Te="CHANGE_VP_RANGE_SUCCESS",we="CLOSE_TREE_NODE",Ee="CLOSE_TREE_SUCCESS";var Ie="CREATE_VP",ve="CREATE_VP_SUCCESS",De="DISABLE_VP",xe="DISABLE_VP_SUCCESS";var _e="ENABLE_VP",Le="ENABLE_VP_SUCCESS";var te="GET_VP_VISUAL_LINKS",Oe="GET_VIEW_PORT_MENUS";var ke="HB",Pe="HB_RESP",Ae="LOGIN",Ue="LOGIN_SUCCESS",Ne="OPEN_TREE_NODE",Fe="OPEN_TREE_SUCCESS";var We="REMOVE_VP";var re="RPC_RESP";var qe="SET_SELECTION_SUCCESS",se="TABLE_META_RESP",ne="TABLE_LIST_RESP",Be="TABLE_ROW";var $e=o=>{switch(o){case"TypeAheadRpcHandler":return"TYPEAHEAD";default:return"SIMUL"}};var Ke=[],R=V("array-backed-moving-window"),h,K=class{constructor({from:e,to:t},{from:r,to:s},n){U(this,h,void 0);this.setRowCount=e=>{var t;if((t=R.info)==null||t.call(R,`setRowCount ${e}`),e<this.internalData.length&&(this.internalData.length=e),e<this.rowCount){this.rowsWithinRange=0;let r=Math.min(e,this.clientRange.to);for(let s=this.clientRange.from;s<r;s++){let n=s-c(this,h).from;this.internalData[n]!==void 0&&(this.rowsWithinRange+=1)}}this.rowCount=e};this.bufferBreakout=(e,t)=>{let r=this.bufferSize*.25;return c(this,h).to-t<r?!0:c(this,h).from>0&&e-c(this,h).from<r};this.bufferSize=n,this.clientRange=new w(e,t),ce(this,h,new w(r,s)),this.internalData=new Array(n),this.rowsWithinRange=0,this.rowCount=0}get range(){return c(this,h)}get hasAllRowsWithinRange(){return this.rowsWithinRange===this.clientRange.to-this.clientRange.from||this.rowCount>0&&this.clientRange.from+this.rowsWithinRange===this.rowCount}outOfRange(e,t){let{from:r,to:s}=this.range;if(t<r||e>=s)return!0}setAtIndex(e){let{rowIndex:t}=e,r=this.isWithinClientRange(t);if(r||this.isWithinRange(t)){let s=t-c(this,h).from;!this.internalData[s]&&r&&(this.rowsWithinRange+=1),this.internalData[s]=e}return r}getAtIndex(e){return c(this,h).isWithin(e)&&this.internalData[e-c(this,h).from]!=null?this.internalData[e-c(this,h).from]:void 0}isWithinRange(e){return c(this,h).isWithin(e)}isWithinClientRange(e){return this.clientRange.isWithin(e)}setClientRange(e,t){var a;(a=R.debug)==null||a.call(R,`setClientRange ${e} - ${t}`);let r=this.clientRange.from,s=Math.min(this.clientRange.to,this.rowCount);if(e===r&&t===s)return[!1,Ke];let n=this.clientRange.copy();this.clientRange.from=e,this.clientRange.to=t,this.rowsWithinRange=0;for(let u=e;u<t;u++){let g=u-c(this,h).from;this.internalData[g]&&(this.rowsWithinRange+=1)}let i=Ke,l=c(this,h).from;if(this.hasAllRowsWithinRange)if(t>n.to){let u=Math.max(e,n.to);i=this.internalData.slice(u-l,t-l)}else{let u=Math.min(n.from,t);i=this.internalData.slice(e-l,u-l)}return[this.bufferBreakout(e,t),i]}setRange(e,t){var i;(i=R.debug)==null||i.call(R,`setRange ${e} - ${t}`);let[r,s]=c(this,h).overlap(e,t),n=new Array(t-e+this.bufferSize);this.rowsWithinRange=0;for(let l=r;l<s;l++){let f=this.getAtIndex(l);if(f){let a=l-e;n[a]=f,this.isWithinClientRange(l)&&(this.rowsWithinRange+=1)}}this.internalData=n,c(this,h).from=e,c(this,h).to=t}getData(){var l;let{from:e,to:t}=c(this,h),{from:r,to:s}=this.clientRange,n=Math.max(0,r-e),i=Math.min(t-e,t,s-e,(l=this.rowCount)!=null?l:t);return this.internalData.slice(n,i)}clear(){var e;(e=R.debug)==null||e.call(R,"clear"),this.internalData.length=0,this.rowsWithinRange=0,this.setRowCount(0)}getCurrentDataRange(){let e=this.internalData,t=e.length,[r]=this.internalData,s=this.internalData[t-1];if(r&&s)return[r.rowIndex,s.rowIndex];for(let n=0;n<t;n++)if(e[n]!==void 0){r=e[n];break}for(let n=t-1;n>=0;n--)if(e[n]!==void 0){s=e[n];break}return r&&s?[r.rowIndex,s.rowIndex]:[-1,-1]}};h=new WeakMap;var He=o=>o!==void 0&&o.groupBy!==void 0&&o.groupBy.length>0;var lt=[],{debug:C,debugEnabled:H,error:ct,info:p,infoEnabled:pt,warn:_}=V("viewport"),gt=({rowKey:o,updateType:e})=>e==="U"&&!o.startsWith("$root"),J=class{constructor({aggregations:e,bufferSize:t=50,columns:r,filter:s,groupBy:n=[],table:i,range:l,sort:f,title:a,viewport:u,visualLink:g}){this.dataWindow=void 0;this.hasUpdates=!1;this.pendingUpdates=[];this.pendingOperations=new Map;this.pendingRangeRequests=[];this.rowCountChanged=!1;this.serverTableMeta=null;this.batchMode=!0;this.useBatchMode=!0;this.rangeMonitor=new q("ViewPort");this.disabled=!1;this.isTree=!1;this.status="";this.suspended=!1;this.rangeRequestAlreadyPending=e=>{let{bufferSize:t}=this,r=t*.25,{from:s}=e;for(let{from:n,to:i}of this.pendingRangeRequests)if(s>=n&&s<i){if(e.to+r<=i)return!0;s=i}return!1};this.getNewRowCount=()=>{if(this.rowCountChanged&&this.dataWindow)return this.rowCountChanged=!1,this.dataWindow.rowCount};this.aggregations=e,this.bufferSize=t,this.clientRange=l,this.clientViewportId=u,this.columns=r,this.filter=s,this.groupBy=n,this.keys=new G(l),this.pendingLinkedParent=g,this.table=i,this.sort=f,this.title=a,pt&&(p==null||p(`constructor #${u} ${i.table} bufferSize=${t}`))}get hasUpdatesToProcess(){return this.suspended?!1:this.rowCountChanged||this.hasUpdates}get size(){var e,t;return(t=(e=this.dataWindow)==null?void 0:e.rowCount)!=null?t:0}subscribe(){let{filter:e}=this.filter;return this.status=this.status==="subscribed"?"resubscribing":"subscribing",{type:Ie,table:this.table,range:j(this.clientRange,this.bufferSize),aggregations:this.aggregations,columns:this.columns,sort:this.sort,groupBy:this.groupBy,filterSpec:{filter:e}}}handleSubscribed({viewPortId:e,aggregations:t,columns:r,filterSpec:s,range:n,sort:i,groupBy:l}){return this.serverViewportId=e,this.status="subscribed",this.aggregations=t,this.columns=r,this.groupBy=l,this.isTree=l&&l.length>0,this.dataWindow=new K(this.clientRange,n,this.bufferSize),{aggregations:t,type:"subscribed",clientViewportId:this.clientViewportId,columns:r,filter:s,groupBy:l,range:n,sort:i,tableMeta:this.serverTableMeta}}awaitOperation(e,t){this.pendingOperations.set(e,t)}completeOperation(e,...t){var l;let{clientViewportId:r,pendingOperations:s}=this,n=s.get(e);if(!n){ct("no matching operation found to complete");return}let{type:i}=n;if(p==null||p(`completeOperation ${i}`),s.delete(e),i==="CHANGE_VP_RANGE"){let[f,a]=t;(l=this.dataWindow)==null||l.setRange(f,a);for(let u=this.pendingRangeRequests.length-1;u>=0;u--){let g=this.pendingRangeRequests[u];if(g.requestId===e){g.acked=!0;break}else _==null||_("range requests sent faster than they are being ACKed")}}else{if(i==="config")return He(n.data)?(this.isTree=!0,this.groupBy=n.data.groupBy):this.isTree&&(this.isTree=!1,this.groupBy=[]),C==null||C(`config change confirmed, isTree : ${this.isTree}`),{clientViewportId:r,type:i,config:n.data};if(i==="groupBy")return this.isTree=n.data.length>0,this.groupBy=n.data,C==null||C(`groupBy change confirmed, isTree : ${this.isTree}`),{clientViewportId:r,type:i,groupBy:n.data};if(i==="columns")return this.columns=n.data,{clientViewportId:r,type:i,columns:n.data};if(i==="filter")return this.filter=n.data,{clientViewportId:r,type:i,filter:n.data};if(i==="aggregate")return this.aggregations=n.data,{clientViewportId:r,type:"aggregate",aggregations:this.aggregations};if(i==="sort")return this.sort=n.data,{clientViewportId:r,type:i,sort:this.sort};if(i!=="selection"){if(i==="disable")return this.disabled=!0,{type:"disabled",clientViewportId:r};if(i==="enable")return this.disabled=!1,{type:"enabled",clientViewportId:r};if(i==="CREATE_VISUAL_LINK"){let[f,a,u]=t;return this.linkedParent={colName:f,parentViewportId:a,parentColName:u},this.pendingLinkedParent=void 0,{type:"vuu-link-created",clientViewportId:r,colName:f,parentViewportId:a,parentColName:u}}else if(i==="REMOVE_VISUAL_LINK")return this.linkedParent=void 0,{type:"vuu-link-removed",clientViewportId:r}}}}rangeRequest(e,t){H&&this.rangeMonitor.set(t);let r="CHANGE_VP_RANGE";if(this.dataWindow){let[s,n]=this.dataWindow.setClientRange(t.from,t.to),i,l=this.dataWindow.rowCount||void 0,f=s&&!this.rangeRequestAlreadyPending(t)?{type:r,viewPortId:this.serverViewportId,...j(t,this.bufferSize,l)}:null;if(f){H&&(C==null||C(`create CHANGE_VP_RANGE: [${f.from} - ${f.to}]`)),this.awaitOperation(e,{type:r});let u=this.pendingRangeRequests.at(-1);if(u)if(u.acked)console.warn("Range Request before previous request is filled");else{let{from:g,to:m}=u;this.dataWindow.outOfRange(g,m)?i={clientViewportId:this.clientViewportId,type:"debounce-begin"}:_==null||_("Range Request before previous request is acked")}this.pendingRangeRequests.push({...f,requestId:e}),this.useBatchMode&&(this.batchMode=!0)}else n.length>0&&(this.batchMode=!1);this.keys.reset(this.dataWindow.clientRange);let a=this.isTree?ie:oe;return n.length?[f,n.map(u=>a(u,this.keys))]:i?[f,void 0,i]:[f]}else return[null]}setLinks(e){return this.links=e,[{type:"vuu-links",links:e,clientViewportId:this.clientViewportId},this.pendingLinkedParent]}setMenu(e){return{type:"vuu-menu",menu:e,clientViewportId:this.clientViewportId}}setTableMeta(e,t){this.serverTableMeta={columns:e,dataTypes:t}}openTreeNode(e,t){return this.useBatchMode&&(this.batchMode=!0),{type:Ne,vpId:this.serverViewportId,treeKey:t.key}}closeTreeNode(e,t){return this.useBatchMode&&(this.batchMode=!0),{type:we,vpId:this.serverViewportId,treeKey:t.key}}createLink(e,t,r,s){let n={type:"CREATE_VISUAL_LINK",parentVpId:r,childVpId:this.serverViewportId,parentColumnName:s,childColumnName:t};return this.awaitOperation(e,n),this.useBatchMode&&(this.batchMode=!0),n}removeLink(e){let t={type:"REMOVE_VISUAL_LINK",childVpId:this.serverViewportId};return this.awaitOperation(e,t),t}suspend(){this.suspended=!0,p==null||p("suspend")}resume(){return this.suspended=!1,H&&(C==null||C(`resume: ${this.currentData()}`)),this.currentData()}currentData(){let e=[];if(this.dataWindow){let t=this.dataWindow.getData(),{keys:r}=this,s=this.isTree?ie:oe;for(let n of t)n&&e.push(s(n,r))}return e}enable(e){return this.awaitOperation(e,{type:"enable"}),p==null||p(`enable: ${this.serverViewportId}`),{type:_e,viewPortId:this.serverViewportId}}disable(e){return this.awaitOperation(e,{type:"disable"}),p==null||p(`disable: ${this.serverViewportId}`),{type:De,viewPortId:this.serverViewportId}}columnRequest(e,t){return this.awaitOperation(e,{type:"columns",data:t}),C==null||C(`columnRequest: ${t}`),this.createRequest({columns:t})}filterRequest(e,t){this.awaitOperation(e,{type:"filter",data:t});let{filter:r}=t;return p==null||p(`filterRequest: ${r}`),this.createRequest({filterSpec:{filter:r}})}setConfig(e,t){this.awaitOperation(e,{type:"config",data:t});let{filter:r,...s}=t;return H?C==null||C(`setConfig ${JSON.stringify(t)}`):p==null||p("setConfig"),this.createRequest({...s,filterSpec:typeof(r==null?void 0:r.filter)=="string"?{filter:r.filter}:{filter:""}},!0)}aggregateRequest(e,t){return this.awaitOperation(e,{type:"aggregate",data:t}),p==null||p(`aggregateRequest: ${t}`),this.createRequest({aggregations:t})}sortRequest(e,t){return this.awaitOperation(e,{type:"sort",data:t}),p==null||p(`sortRequest: ${JSON.stringify(t.sortDefs)}`),this.createRequest({sort:t})}groupByRequest(e,t=lt){var r;return this.awaitOperation(e,{type:"groupBy",data:t}),this.useBatchMode&&(this.batchMode=!0),this.isTree||(r=this.dataWindow)==null||r.clear(),this.createRequest({groupBy:t})}selectRequest(e,t){return this.awaitOperation(e,{type:"selection",data:t}),p==null||p(`selectRequest: ${t}`),{type:"SET_SELECTION",vpId:this.serverViewportId,selection:fe(t)}}removePendingRangeRequest(e,t){for(let r=this.pendingRangeRequests.length-1;r>=0;r--){let{from:s,to:n}=this.pendingRangeRequests[r],i=!0;if(e>=s&&e<n||t>s&&t<n){i||console.warn("removePendingRangeRequest TABLE_ROWS are not for latest request"),this.pendingRangeRequests.splice(r,1);break}else i=!1}}updateRows(e){var s,n,i;let[{rowIndex:t}]=e,{rowIndex:r}=e.at(-1);this.removePendingRangeRequest(t,r);for(let l of e)this.isTree&&gt(l)||((l.updateType==="SIZE"||((s=this.dataWindow)==null?void 0:s.rowCount)!==l.vpSize)&&((n=this.dataWindow)==null||n.setRowCount(l.vpSize),this.rowCountChanged=!0),l.updateType==="U"&&(i=this.dataWindow)!=null&&i.setAtIndex(l)&&(this.hasUpdates=!0,this.batchMode||this.pendingUpdates.push(l)))}getClientRows(){let e,t="size-only";if(this.hasUpdates&&this.dataWindow){let{keys:r}=this,s=this.isTree?ie:oe;if(this.pendingUpdates.length>0){e=[],t="update";for(let n of this.pendingUpdates)e.push(s(n,r));this.pendingUpdates.length=0}else{let n=this.dataWindow.getData();if(this.dataWindow.hasAllRowsWithinRange){e=[],t="batch";for(let i of n)e.push(s(i,r));this.batchMode=!1}}this.hasUpdates=!1}return[e,t]}createRequest(e,t=!1){return t?{type:"CHANGE_VP",viewPortId:this.serverViewportId,...e}:{type:"CHANGE_VP",viewPortId:this.serverViewportId,aggregations:this.aggregations,columns:this.columns,sort:this.sort,groupBy:this.groupBy,filterSpec:{filter:this.filter.filter},...e}}},oe=({rowIndex:o,rowKey:e,sel:t,data:r},s)=>[o,s.keyFor(o),!0,null,null,0,e,t].concat(r),ie=({rowIndex:o,rowKey:e,sel:t,data:r},s)=>{let[n,i,,l,,f,...a]=r;return[o,s.keyFor(o),l,i,n,f,e,t].concat(a)};var Je=1;var{debug:E,debugEnabled:P,error:L,info:I,infoEnabled:dt,warn:O}=V("server-proxy"),S=()=>`${Je++}`,ft={},ht=o=>o.disabled!==!0&&o.suspended!==!0,mt=(o,e,t)=>o.map(r=>r.parentVpId===e?{...r,label:t}:r);function Ct(o,e){return o.map(t=>{let{parentVpId:r}=t,s=e.get(r);if(s)return{...t,parentClientVpId:s.clientViewportId,label:s.title};throw Error("addLabelsToLinks viewport not found")})}var bt=(o,e)=>o.viewPortId===e.viewPortId?o.rowIndex===e.rowIndex?o.ts>e.ts?1:-1:o.rowIndex>e.rowIndex?1:-1:o.viewPortId>e.viewPortId?1:-1,z=class{constructor(e,t){this.authToken="";this.pendingTableMetaRequests=new Map;this.queuedRequests=[];this.cachedTableMeta=new Map;this.connection=e,this.postMessageToClient=t,this.viewports=new Map,this.mapClientToServerViewport=new Map}async reconnect(){await this.login(this.authToken);let[e,t]=pe(Array.from(this.viewports.values()),ht);this.viewports.clear(),this.mapClientToServerViewport.clear();let r=s=>{s.forEach(n=>{let{clientViewportId:i}=n;this.viewports.set(i,n),this.sendMessageToServer(n.subscribe(),i)})};r(e),setTimeout(()=>{r(t)},2e3)}async login(e){if(e)return this.authToken=e,new Promise((t,r)=>{this.sendMessageToServer({type:Ae,token:this.authToken,user:"user"},""),this.pendingLogin={resolve:t,reject:r}});this.authToken===""&&L("login, cannot login until auth token has been obtained")}subscribe(e){if(this.mapClientToServerViewport.has(e.viewport))L(`spurious subscribe call ${e.viewport}`);else{if(!this.hasMetaDataFor(e.table)){I==null||I(`subscribe to ${e.table.table}, no metadata yet, request metadata`);let r=S();this.sendMessageToServer({type:"GET_TABLE_META",table:e.table},r),this.pendingTableMetaRequests.set(r,e.viewport)}let t=new J(e);this.viewports.set(e.viewport,t),this.sendIfReady(t.subscribe(),e.viewport,this.sessionId!=="")}}unsubscribe(e){let t=this.mapClientToServerViewport.get(e);t?(I==null||I(`Unsubscribe Message (Client to Server):\n ${t}`),this.sendMessageToServer({type:We,viewPortId:t})):L(`failed to unsubscribe client viewport ${e}, viewport not found`)}getViewportForClient(e,t=!0){let r=this.mapClientToServerViewport.get(e);if(r){let s=this.viewports.get(r);if(s)return s;if(t)throw Error(`Viewport not found for client viewport ${e}`);return null}else{if(this.viewports.has(e))return this.viewports.get(e);if(t)throw Error(`Viewport server id not found for client viewport ${e}`);return null}}setViewRange(e,t){let r=S(),[s,n,i]=e.rangeRequest(r,t.range);s&&this.sendIfReady(s,r,e.status==="subscribed"),n?this.postMessageToClient({mode:"batch",type:"viewport-update",clientViewportId:e.clientViewportId,rows:n}):i&&this.postMessageToClient(i)}setConfig(e,t){let r=S(),s=e.setConfig(r,t.config);this.sendIfReady(s,r,e.status==="subscribed")}aggregate(e,t){let r=S(),s=e.aggregateRequest(r,t.aggregations);this.sendIfReady(s,r,e.status==="subscribed")}sort(e,t){let r=S(),s=e.sortRequest(r,t.sort);this.sendIfReady(s,r,e.status==="subscribed")}groupBy(e,t){let r=S(),s=e.groupByRequest(r,t.groupBy);this.sendIfReady(s,r,e.status==="subscribed")}filter(e,t){let r=S(),{filter:s}=t,n=e.filterRequest(r,s);this.sendIfReady(n,r,e.status==="subscribed")}setColumns(e,t){let r=S(),{columns:s}=t,n=e.columnRequest(r,s);this.sendIfReady(n,r,e.status==="subscribed")}setTitle(e,t){e&&(e.title=t.title,this.updateTitleOnVisualLinks(e))}select(e,t){let r=S(),{selected:s}=t,n=e.selectRequest(r,s);this.sendIfReady(n,r,e.status==="subscribed")}disableViewport(e){let t=S(),r=e.disable(t);this.sendIfReady(r,t,e.status==="subscribed")}enableViewport(e){let t=S(),r=e.enable(t);this.sendIfReady(r,t,e.status==="subscribed")}resumeViewport(e){let t=e.resume();this.postMessageToClient({clientViewportId:e.clientViewportId,rows:t,type:"viewport-update"})}openTreeNode(e,t){if(e.serverViewportId){let r=S();this.sendIfReady(e.openTreeNode(r,t),r,e.status==="subscribed")}}closeTreeNode(e,t){if(e.serverViewportId){let r=S();this.sendIfReady(e.closeTreeNode(r,t),r,e.status==="subscribed")}}createLink(e,t){let{parentClientVpId:r,parentColumnName:s,childColumnName:n}=t,i=S(),l=this.mapClientToServerViewport.get(r);if(l){let f=e.createLink(i,n,l,s);this.sendMessageToServer(f,i)}else L("ServerProxy unable to create link, viewport not found")}removeLink(e){let t=S(),r=e.removeLink(t);this.sendMessageToServer(r,t)}updateTitleOnVisualLinks(e){var s;let{serverViewportId:t,title:r}=e;for(let n of this.viewports.values())if(n!==e&&n.links&&t&&r&&(s=n.links)!=null&&s.some(i=>i.parentVpId===t)){let[i]=n.setLinks(mt(n.links,t,r));this.postMessageToClient(i)}}removeViewportFromVisualLinks(e){var t;for(let r of this.viewports.values())if((t=r.links)!=null&&t.some(({parentVpId:s})=>s===e)){let[s]=r.setLinks(r.links.filter(({parentVpId:n})=>n!==e));this.postMessageToClient(s)}}menuRpcCall(e){let t=this.getViewportForClient(e.vpId,!1);if(t!=null&&t.serverViewportId){let[r,s]=ee(e);this.sendMessageToServer({...s,vpId:t.serverViewportId},r)}}rpcCall(e){let[t,r]=ee(e),s=$e(r.service);this.sendMessageToServer(r,t,{module:s})}handleMessageFromClient(e){if(E==null||E(`handleMessageFromClient: ${e.type}`),Re(e))if(e.type==="disable"){let t=this.getViewportForClient(e.viewport,!1);return t!==null?this.disableViewport(t):void 0}else{let t=this.getViewportForClient(e.viewport);switch(e.type){case"setViewRange":return this.setViewRange(t,e);case"config":return this.setConfig(t,e);case"aggregate":return this.aggregate(t,e);case"sort":return this.sort(t,e);case"groupBy":return this.groupBy(t,e);case"filter":return this.filter(t,e);case"select":return this.select(t,e);case"suspend":return t.suspend();case"resume":return this.resumeViewport(t);case"enable":return this.enableViewport(t);case"openTreeNode":return this.openTreeNode(t,e);case"closeTreeNode":return this.closeTreeNode(t,e);case"createLink":return this.createLink(t,e);case"removeLink":return this.removeLink(t);case"setColumns":return this.setColumns(t,e);case"setTitle":return this.setTitle(t,e);default:}}else{if(ye(e))return this.menuRpcCall(e);{let{type:t,requestId:r}=e;switch(t){case"GET_TABLE_LIST":return this.sendMessageToServer({type:t},r);case"GET_TABLE_META":return this.sendMessageToServer({type:t,table:e.table},r);case"RPC_CALL":return this.rpcCall(e);default:}}}L(`Vuu ServerProxy Unexpected message from client ${JSON.stringify(e)}`)}sendIfReady(e,t,r=!0){return r?this.sendMessageToServer(e,t):this.queuedRequests.push(e),r}sendMessageToServer(e,t=`${Je++}`,r=ft){let{module:s="CORE"}=r;this.authToken&&this.connection.send({requestId:t,sessionId:this.sessionId,token:this.authToken,user:"user",module:s,body:e})}handleMessageFromServer(e){var i;let{body:t,requestId:r,sessionId:s}=e,{viewports:n}=this;switch(t.type){case ke:this.sendMessageToServer({type:Pe,ts:+new Date},"NA");break;case Ue:if(s)this.sessionId=s,(i=this.pendingLogin)==null||i.resolve(s),this.pendingLogin=void 0;else throw Error("LOGIN_SUCCESS did not provide sessionId");break;case ve:{let a=n.get(r);if(a){let{status:u}=a,{viewPortId:g}=t;r!==g&&(n.delete(r),n.set(g,a)),this.mapClientToServerViewport.set(r,g);let m=a.handleSubscribed(t);m&&(this.postMessageToClient(m),P&&E(`post DataSourceSubscribedMessage to client: ${JSON.stringify(m)}`)),a.disabled&&this.disableViewport(a),u==="subscribing"&&(this.sendMessageToServer({type:te,vpId:g}),this.sendMessageToServer({type:Oe,vpId:g}),Array.from(n.entries()).filter(([b,{disabled:M}])=>b!==g&&!M).forEach(([b])=>{this.sendMessageToServer({type:te,vpId:b})}))}}break;case"REMOVE_VP_SUCCESS":{let a=this.viewports.get(t.viewPortId);a&&(this.mapClientToServerViewport.delete(a.clientViewportId),n.delete(t.viewPortId),this.removeViewportFromVisualLinks(t.viewPortId))}break;case qe:{let a=this.viewports.get(t.vpId);a&&a.completeOperation(r)}break;case Me:case xe:if(n.has(t.viewPortId)){let a=this.viewports.get(t.viewPortId);if(a){let u=a.completeOperation(r);u!==void 0&&(this.postMessageToClient(u),P&&E(`postMessageToClient ${JSON.stringify(u)}`))}}break;case Le:{let a=this.viewports.get(t.viewPortId);if(a){let u=a.completeOperation(r);if(u){this.postMessageToClient(u);let g=a.currentData();P&&E(`Enable Response (ServerProxy to Client):\n ${JSON.stringify(u)}`),this.postMessageToClient({clientViewportId:a.clientViewportId,mode:"batch",rows:g,size:a.size,type:"viewport-update"}),P&&E(`Enable Response (ServerProxy to Client): ${JSON.stringify(u)}`)}}}break;case Be:{t.rows.sort(bt);let a="",u,g=0;for(let m=0,b=t.rows.length,M=m===b-1;m<b;m++,M=m===b-1){let k=t.rows[m];if(k.viewPortId!==a||M){let D=b===1?k.viewPortId:a;if(D!=="")if(u=n.get(D),u)if(g===0&&M)u.updateRows(t.rows);else{let A=M?b:m;u.updateRows(t.rows.slice(g,A)),g=m}else O==null||O(`TABLE_ROW message received for non registered viewport ${D}`);a=k.viewPortId}}this.processUpdates()}break;case Te:{let a=this.viewports.get(t.viewPortId);if(a){let{from:u,to:g}=t;a.completeOperation(r,u,g)}}break;case Fe:case Ee:break;case"CREATE_VISUAL_LINK_SUCCESS":{let a=this.viewports.get(t.childVpId),u=this.viewports.get(t.parentVpId);if(a&&u){let{childColumnName:g,parentColumnName:m}=t,b=a.completeOperation(r,g,u.clientViewportId,m);b&&this.postMessageToClient(b)}}break;case"REMOVE_VISUAL_LINK_SUCCESS":{let a=this.viewports.get(t.childVpId);if(a){let u=a.completeOperation(r);u&&this.postMessageToClient(u)}}break;case ne:this.postMessageToClient({type:ne,tables:t.tables,requestId:r});break;case se:{this.cacheTableMeta(t.table,t.columns,t.dataTypes);let a=this.pendingTableMetaRequests.get(r);if(a){this.pendingTableMetaRequests.delete(r);let u=this.viewports.get(a);u?u.setTableMeta(t.columns,t.dataTypes):O==null||O("Message has come back AFTER CREATE_VP_SUCCESS, what do we do now")}else this.postMessageToClient({type:se,table:t.table,columns:t.columns,dataTypes:t.dataTypes,requestId:r})}break;case"VP_VISUAL_LINKS_RESP":{let a=this.getActiveLinks(t.links),u=this.viewports.get(t.vpId);if(a.length&&u){let g=Ct(a,this.viewports),[m,b]=u.setLinks(g);if(this.postMessageToClient(m),b){let{link:M,parentClientVpId:k}=b,D=S(),A=this.mapClientToServerViewport.get(k);if(A){let ze=u.createLink(D,M.fromColumn,A,M.toColumn);this.sendMessageToServer(ze,D)}}}}break;case"VIEW_PORT_MENUS_RESP":if(t.menu.name){let a=this.viewports.get(t.vpId);if(a){let u=a.setMenu(t.menu);this.postMessageToClient(u)}}break;case"VIEW_PORT_MENU_RESP":{let{action:a}=t;this.postMessageToClient({type:"VIEW_PORT_MENU_RESP",action:a,tableAlreadyOpen:this.isTableOpen(a.table),requestId:r})}break;case re:{let{method:a,result:u}=t;this.postMessageToClient({type:re,method:a,result:u,requestId:r})}break;case"ERROR":L(t.msg);break;default:dt&&I(`handleMessageFromServer ${t.type}.`)}}hasMetaDataFor(e){return this.cachedTableMeta.has(`${e.module}:${e.table}`)}cacheTableMeta(e,t,r){this.hasMetaDataFor(e)||this.cachedTableMeta.set(`${e.module}:${e.table}`,{columns:t,serverDataTypes:r})}isTableOpen(e){if(e){let t=e.table;for(let r of this.viewports.values())if(!r.suspended&&r.table.table===t)return!0}}getActiveLinks(e){return e.filter(t=>{let r=this.viewports.get(t.parentVpId);return r&&!r.suspended})}processUpdates(){this.viewports.forEach(e=>{var t;if(e.hasUpdatesToProcess){let[r,s]=e.getClientRows(),n=e.getNewRowCount();(n!==void 0||r&&r.length>0)&&(P&&E(`postMessageToClient #${e.clientViewportId} viewport-update ${s}, ${(t=r==null?void 0:r.length)!=null?t:"no"} rows, size ${n}`),this.postMessageToClient({clientViewportId:e.clientViewportId,mode:s,rows:r,size:n,type:"viewport-update"}))}})}};var v,{info:ae,infoEnabled:ue}=V("worker");async function St(o,e,t){let r=await Se(o,s=>{Ve(s)?(t(s),s.status==="reconnected"&&v.reconnect()):v.handleMessageFromServer(s)});v=new z(r,s=>yt(s)),r.requiresLogin&&await v.login(e)}function yt(o){postMessage(o)}var Vt=async({data:o})=>{switch(o.type){case"connect":await St(o.url,o.token,postMessage),postMessage({type:"connected"});break;case"subscribe":ue&&ae(`client subscribe: ${JSON.stringify(o)}`),v.subscribe(o);break;case"unsubscribe":ue&&ae(`client unsubscribe: ${JSON.stringify(o)}`),v.unsubscribe(o.viewport);break;default:ue&&ae(`client message: ${JSON.stringify(o)}`),v.handleMessageFromClient(o)}};self.addEventListener("message",Vt);postMessage({type:"ready"});\n\n';var gy=new Blob([(0,Ln.getLoggingConfig)()+gd],{type:"text/javascript"}),by=URL.createObjectURL(gy),Vn,Sa,xa=[],yy,wy,vy=new Promise((n,e)=>{yy=n,wy=e}),to=()=>vy,Zs=new Map,eo=new Map,Cy=async(n,e="",t)=>e===""&&Sa===void 0?new Promise(i=>{xa.push({resolve:i})}):Sa||(Sa=new Promise(i=>{let r=new Worker(by),s=window.setTimeout(()=>{console.error("timed out waiting for worker to load")},1e3);r.onmessage=o=>{let{data:l}=o;if(l.type==="ready")window.clearTimeout(s),r.postMessage({type:"connect",url:n,token:e});else if(l.type==="connected"){r.onmessage=bd,i(r);for(let a of xa)a.resolve(r);xa.length=0}else Ca(l)?t(o):console.warn("ConnectionManager: Unexpected message from the worker")}}));function bd({data:n}){if(Ca(n))yd.emit("connection-status",n);else if(hd(n)){let e=Zs.get(n.clientViewportId);e?e.postMessageToClientDataSource(n):console.error(`[ConnectionManager] ${n.type} message received, viewport not found`)}else{let e=n.requestId;if(eo.has(e)){let{resolve:t}=eo.get(e);eo.delete(e);let{type:i,requestId:r,...s}=n;md(n)?t(n.result):t(s)}else console.warn("%cConnectionManager Unexpected message from the worker","color:red;font-weight:bold;")}}var ka=n=>{let e=(0,Ln.uuid)();return Vn.postMessage({requestId:e,...n}),new Promise((t,i)=>{eo.set(e,{resolve:t,reject:i})})},Sy={subscribe:(n,e)=>{Zs.set(n.viewport,{status:"subscribing",request:n,postMessageToClientDataSource:e}),Vn.postMessage({type:"subscribe",...n})},unsubscribe:n=>{Vn.postMessage({type:"unsubscribe",viewport:n})},send:n=>{Vn.postMessage(n)},destroy:n=>{n&&Zs.has(n)&&Zs.delete(n)},rpcCall:async n=>ka(n),getTableList:async()=>ka({type:dd}),getTableMeta:async n=>ka({type:pd,table:n})},Ma=class extends Ln.EventEmitter{async connect(e,t){return Vn=await Cy(e,t,bd),Sy}destroy(){Vn.terminate()}},yd=new Ma;var io=require("@vuu-ui/vuu-utils"),Pr=require("react"),{SELECTED:dk}=io.metadataKeys;var Ta=require("react");var ky=require("react");var Ra=require("@vuu-ui/vuu-utils");var My=require("react");var{KEY:kk}=Ra.metadataKeys;var Ty=n=>n.type==="vuu-links";var Ry=n=>n.type==="vuu-menu",wd=n=>Ry(n)||Ty(n),vd=n=>n.type==="vuu-link-created"||n.type==="vuu-link-removed";var Da=require("react");var ht=require("@vuu-ui/vuu-utils");var{IDX:Dy,SELECTED:Cd}=ht.metadataKeys,Ay=(n,e)=>[e,e,!0,!1,1,0,n[0],0,...n],Py=n=>{let e={columns:[],dataTypes:[]};return n.forEach(t=>{var i;e.columns.push(t.name),e.dataTypes.push((i=t.serverDataType)!=null?i:"string")}),e},Ey=(n,e)=>{let[t]=n,i=n.slice();return i[1]=e.keyFor(t),i},ui,hi,$t,ci,fi,di,no,ro,pi,Nn,Sd=class extends ht.EventEmitter{constructor({aggregations:t,columnDescriptors:i,columns:r,data:s,filter:o,groupBy:l,sort:a,title:u,viewport:h}){super();this.status="initialising";this.disabled=!1;this.suspended=!1;W(this,ui,[]);W(this,hi,[]);W(this,$t,void 0);W(this,ci,{filter:""});W(this,fi,[]);W(this,di,{from:0,to:0});W(this,no,0);W(this,ro,0);W(this,pi,{sortDefs:[]});W(this,Nn,void 0);this.keys=new ht.KeySet(k(this,di));if(!s||!i)throw Error("ArrayDataSource constructor called without data");this.columnDescriptors=i,this.tableMeta=Py(i),P(this,$t,s.map(Ay)),this.viewport=h||(0,ht.uuid)(),t&&P(this,ui,t),r&&P(this,hi,r),o&&P(this,ci,o),l&&P(this,fi,l),a&&P(this,pi,a),P(this,Nn,u)}async subscribe({viewport:t=(h=>(h=this.viewport)!=null?h:(0,ht.uuid)())(),columns:i,aggregations:r,range:s,sort:o,groupBy:l,filter:a},u){var c;this.clientCallback=u,console.log(`subscribe range ${s==null?void 0:s.from} ${s==null?void 0:s.to}`),r&&P(this,ui,r),i&&P(this,hi,i),a&&P(this,ci,a),l&&P(this,fi,l),s&&P(this,di,s),o&&P(this,pi,o),this.status==="initialising"&&(this.viewport=t,this.status="subscribed",(c=this.clientCallback)==null||c.call(this,{aggregations:k(this,ui),type:"subscribed",clientViewportId:this.viewport,columns:k(this,hi),filter:k(this,ci),groupBy:k(this,fi),range:k(this,di),sort:k(this,pi),tableMeta:this.tableMeta}),this.clientCallback({clientViewportId:this.viewport,type:"viewport-update",size:k(this,$t).length}))}unsubscribe(){console.log("noop")}suspend(){return console.log("noop"),this}resume(){return console.log("noop"),this}disable(){return console.log("noop"),this}enable(){return console.log("noop"),this}select(t){var r;let i=[];for(let s of k(this,$t)){let{[Dy]:o,[Cd]:l}=s,a=l===1,u=(0,ht.isSelected)(t,o);if(u!==a){let h=s.slice();h[Cd]=u?1:0,k(this,$t)[o]=h,i.push(h)}}i.length>0&&((r=this.clientCallback)==null||r.call(this,{clientViewportId:this.viewport,mode:"update",type:"viewport-update",rows:i}))}openTreeNode(t){console.log("TODO: open tree node",{key:t})}closeTreeNode(t){console.log("TODO: close tree node",{key:t})}get config(){}get selectedRowsCount(){return k(this,no)}get size(){return k(this,ro)}get range(){return k(this,di)}set range(t){P(this,di,t),this.keys.reset(t),requestAnimationFrame(()=>{var i;(i=this.clientCallback)==null||i.call(this,{clientViewportId:this.viewport,rows:k(this,$t).slice(t.from,t.to).map(r=>Ey(r,this.keys)),size:k(this,$t).length,type:"viewport-update"})})}get columns(){return k(this,hi)}set columns(t){P(this,hi,t),console.log(`ArrayDataSource setColumns ${t.join(",")}`)}get aggregations(){return k(this,ui)}set aggregations(t){P(this,ui,t)}get sort(){return k(this,pi)}set sort(t){P(this,pi,t)}get filter(){return k(this,ci)}set filter(t){P(this,ci,t),console.log(`RemoteDataSource ${JSON.stringify(t)}`)}get groupBy(){return k(this,fi)}set groupBy(t){P(this,fi,t)}get title(){return k(this,Nn)}set title(t){P(this,Nn,t)}createLink({parentVpId:t,link:{fromColumn:i,toColumn:r}}){console.log("create link",{parentVpId:t,fromColumn:i,toColumn:r})}removeLink(){console.log("remove link")}async menuRpcCall(t){console.log("rmenuRpcCall",{rpcRequest:t})}};ui=new WeakMap,hi=new WeakMap,$t=new WeakMap,ci=new WeakMap,fi=new WeakMap,di=new WeakMap,no=new WeakMap,ro=new WeakMap,pi=new WeakMap,Nn=new WeakMap;var _e=require("@vuu-ui/vuu-utils");var{DEPTH:Bn,IDX:xd,IS_EXPANDED:Oy,IS_LEAF:Iy,KEY:Dd,SELECTED:kd}=_e.metadataKeys,Md=(n,e)=>{let[t]=n,i=n.slice();return i[1]=e.keyFor(t),i},mi,gi,Oe,bi,yi,kt,so,oo,wi,Fn,Td=class extends _e.EventEmitter{constructor({aggregations:t,data:i,filter:r,groupBy:s,sort:o,title:l,viewport:a}){super();this.status="initialising";this.expandedRows=new Set;this.visibleRows=[];W(this,mi,[]);W(this,gi,[]);W(this,Oe,void 0);W(this,bi,{filter:""});W(this,yi,[]);W(this,kt,{from:0,to:0});W(this,so,0);W(this,oo,0);W(this,wi,{sortDefs:[]});W(this,Fn,void 0);this.keys=new _e.KeySet(k(this,kt));if(!i)throw Error("JsonDataSource constructor called without data");[this.columnDescriptors,Qa(this,Oe)._]=(0,_e.jsonToDataSourceRows)(i),this.visibleRows=k(this,Oe).filter(u=>u[Bn]===0).map((u,h)=>[h,h].concat(u.slice(2))),this.viewport=a||(0,_e.uuid)(),t&&P(this,mi,t),this.columnDescriptors&&P(this,gi,this.columnDescriptors.map(u=>u.name)),r&&P(this,bi,r),s&&P(this,yi,s),o&&P(this,wi,o),P(this,Fn,l)}async subscribe({viewport:t=(h=>(h=this.viewport)!=null?h:(0,_e.uuid)())(),columns:i,aggregations:r,range:s,sort:o,groupBy:l,filter:a},u){var c;this.clientCallback=u,console.log(`subscribe range ${s==null?void 0:s.from} ${s==null?void 0:s.to}`),r&&P(this,mi,r),i&&P(this,gi,i),a&&P(this,bi,a),l&&P(this,yi,l),s&&P(this,kt,s),o&&P(this,wi,o),this.status==="initialising"&&(this.viewport=t,this.status="subscribed",(c=this.clientCallback)==null||c.call(this,{aggregations:k(this,mi),type:"subscribed",clientViewportId:this.viewport,columns:k(this,gi),filter:k(this,bi),groupBy:k(this,yi),range:k(this,kt),sort:k(this,wi),tableMeta:{columns:[],dataTypes:[]}}),this.clientCallback({clientViewportId:this.viewport,type:"viewport-update",size:this.visibleRows.length}))}unsubscribe(){console.log("noop")}suspend(){return console.log("noop"),this}resume(){return console.log("noop"),this}disable(){return console.log("noop"),this}enable(){return console.log("noop"),this}select(t){var r;let i=[];for(let s of k(this,Oe)){let{[xd]:o,[kd]:l}=s,a=l===1,u=(0,_e.isSelected)(t,o);if(u!==a){let h=s.slice();h[kd]=u?1:0,k(this,Oe)[o]=h,i.push(h)}}i.length>0&&((r=this.clientCallback)==null||r.call(this,{clientViewportId:this.viewport,mode:"update",type:"viewport-update",rows:i}))}openTreeNode(t){var s;this.expandedRows.add(t),this.visibleRows=Rd(k(this,Oe),this.expandedRows);let{from:i,to:r}=k(this,kt);(s=this.clientCallback)==null||s.call(this,{clientViewportId:this.viewport,rows:this.visibleRows.slice(i,r).map(o=>Md(o,this.keys)),size:this.visibleRows.length,type:"viewport-update"}),console.log(this.expandedRows)}closeTreeNode(t,i=!1){if(this.expandedRows.delete(t),i)for(let r of this.expandedRows.keys())r.startsWith(t)&&this.expandedRows.delete(r);this.visibleRows=Rd(k(this,Oe),this.expandedRows),this.sendRowsToClient()}get config(){}get selectedRowsCount(){return k(this,so)}get size(){return k(this,oo)}get range(){return k(this,kt)}set range(t){P(this,kt,t),this.keys.reset(t),requestAnimationFrame(()=>{this.sendRowsToClient()})}sendRowsToClient(){var r;let{from:t,to:i}=k(this,kt);(r=this.clientCallback)==null||r.call(this,{clientViewportId:this.viewport,rows:this.visibleRows.slice(t,i).map(s=>Md(s,this.keys)),size:this.visibleRows.length,type:"viewport-update"})}get columns(){return k(this,gi)}set columns(t){P(this,gi,t),console.log(`ArrayDataSource setColumns ${t.join(",")}`)}get aggregations(){return k(this,mi)}set aggregations(t){P(this,mi,t)}get sort(){return k(this,wi)}set sort(t){P(this,wi,t)}get filter(){return k(this,bi)}set filter(t){P(this,bi,t),console.log(`RemoteDataSource ${JSON.stringify(t)}`)}get groupBy(){return k(this,yi)}set groupBy(t){P(this,yi,t)}get title(){return k(this,Fn)}set title(t){P(this,Fn,t)}createLink({parentVpId:t,link:{fromColumn:i,toColumn:r}}){console.log("create link",{parentVpId:t,fromColumn:i,toColumn:r})}removeLink(){console.log("remove link")}async menuRpcCall(t){console.log("rmenuRpcCall",{rpcRequest:t})}getChildRows(t){let i=k(this,Oe).find(s=>s[Dd]===t);if(i){let{[xd]:s,[Bn]:o}=i,l=s+1,a=[];do{let{[Bn]:u}=k(this,Oe)[l];if(u===o+1)a.push(k(this,Oe)[l]);else if(u<=o)break;l+=1}while(l<k(this,Oe).length);return a}else console.warn(`JsonDataSource getChildRows row not found for key ${t}`);let r=t.split("|").slice(1);return console.log({sections:r,parentRow:i}),[]}getRowsAtDepth(t,i=!0){return(i?this.visibleRows:k(this,Oe)).filter(s=>s[Bn]===t)}};mi=new WeakMap,gi=new WeakMap,Oe=new WeakMap,bi=new WeakMap,yi=new WeakMap,kt=new WeakMap,so=new WeakMap,oo=new WeakMap,wi=new WeakMap,Fn=new WeakMap;function Rd(n,e){let t=[],i={value:0};for(let r=0;r<n.length;r++){let s=n[r],{[Bn]:o,[Dd]:l,[Iy]:a}=s,u=e.has(l);if(t.push(Vy(s,i,u)),!a&&!u)do r+=1;while(r<n.length-1&&n[r+1][Bn]>o)}return t}var Vy=(n,e,t)=>{let i=n.slice();return i[0]=e.value,i[1]=e.value,t&&(i[Oy]=!0),e.value+=1,i};var Tt=require("@vuu-ui/vuu-utils");var vi,Ci,Ye,Si,Mt,Hn,qi,Er,Wn,xi,Gi,_n,Ad=class extends Tt.EventEmitter{constructor({bufferSize:t=100,aggregations:i,columns:r,filter:s,groupBy:o,sort:l,table:a,title:u,viewport:h,visualLink:c}){super();this.server=null;this.status="initialising";this.disabled=!1;this.suspended=!1;W(this,vi,[]);W(this,Ci,[]);W(this,Ye,void 0);W(this,Si,{filter:""});W(this,Mt,[]);W(this,Hn,"throttle");W(this,qi,{from:0,to:0});W(this,Er,0);W(this,Wn,0);W(this,xi,{sortDefs:[]});W(this,Gi,void 0);W(this,_n,void 0);this.handleMessageFromServer=t=>{var i,r;if(t.type==="subscribed")this.status="subscribed",(i=this.clientCallback)==null||i.call(this,t);else if(t.type==="disabled")this.status="disabled";else if(t.type==="enabled")this.status="enabled";else{if(cd(t))return;t.type==="debounce-begin"?this.optimize="debounce":(t.type==="viewport-update"&&t.size!==void 0&&t.size!==k(this,Wn)&&(P(this,Wn,t.size),this.emit("resize",t.size)),this.configChangePending&&this.setConfigPending(),ad(t)?this.throttleSizeCallback(t):((r=this.clientCallback)==null||r.call(this,t),this.optimize==="debounce"&&this.revertDebounce()))}};this.revertDebounce=(0,Tt.debounce)(()=>{this.optimize="throttle"},500);this.throttleSizeCallback=(0,Tt.throttle)(t=>{var i;(i=this.clientCallback)==null||i.call(this,t)},2e3);this.rawRangeRequest=t=>{this.viewport&&this.server&&this.server.send({viewport:this.viewport,type:"setViewRange",range:t})};this.debounceRangeRequest=(0,Tt.debounce)(t=>{this.viewport&&this.server&&this.server.send({viewport:this.viewport,type:"setViewRange",range:t})},50);this.throttleRangeRequest=(0,Tt.throttle)(t=>{this.viewport&&this.server&&this.server.send({viewport:this.viewport,type:"setViewRange",range:t})},100);if(!a)throw Error("RemoteDataSource constructor called without table");this.bufferSize=t,this.table=a,this.viewport=h,i&&P(this,vi,i),r&&P(this,Ci,r),s&&P(this,Si,s),o&&P(this,Mt,o),l&&P(this,xi,l),P(this,Gi,u),P(this,_n,c),this.refreshConfig(),this.rangeRequest=this.throttleRangeRequest}async subscribe({viewport:t=(h=>(h=this.viewport)!=null?h:(0,Tt.uuid)())(),columns:i,aggregations:r,range:s,sort:o,groupBy:l,filter:a},u){var f;if(this.clientCallback=u,r&&P(this,vi,r),i&&P(this,Ci,i),a&&P(this,Si,a),l&&P(this,Mt,l),s&&P(this,qi,s),o&&P(this,xi,o),this.status!=="initialising")return;this.status="subscribing",this.viewport=t,this.server=await to();let{bufferSize:c}=this;(f=this.server)==null||f.subscribe({aggregations:k(this,vi),bufferSize:c,columns:k(this,Ci),filter:k(this,Si),groupBy:k(this,Mt),viewport:t,table:this.table,range:k(this,qi),sort:k(this,xi),title:k(this,Gi),visualLink:this.visualLink},this.handleMessageFromServer)}unsubscribe(){var t,i;this.viewport&&((t=this.server)==null||t.unsubscribe(this.viewport)),(i=this.server)==null||i.destroy(this.viewport),this.removeAllListeners()}suspend(){var t;return this.viewport&&(this.suspended=!0,(t=this.server)==null||t.send({type:"suspend",viewport:this.viewport})),this}resume(){var t;return this.viewport&&this.suspended&&((t=this.server)==null||t.send({type:"resume",viewport:this.viewport}),this.suspended=!1),this}disable(){var t;return this.viewport&&(this.status="disabling",this.disabled=!0,(t=this.server)==null||t.send({viewport:this.viewport,type:"disable"})),this}enable(){var t;return this.viewport&&this.disabled&&(this.status="enabling",(t=this.server)==null||t.send({viewport:this.viewport,type:"enable"}),this.disabled=!1),this}select(t){var i;P(this,Er,t.length),this.viewport&&((i=this.server)==null||i.send({viewport:this.viewport,type:"select",selected:t}))}openTreeNode(t){var i;this.viewport&&((i=this.server)==null||i.send({viewport:this.viewport,type:"openTreeNode",key:t}))}closeTreeNode(t){var i;this.viewport&&((i=this.server)==null||i.send({viewport:this.viewport,type:"closeTreeNode",key:t}))}refreshConfig(t){let{aggregations:i,columns:r,filter:s,groupBy:o,sort:l,visualLink:a}=this,u=i.length>0,h=r.length>0,c=s.filter!=="",f=o.length>0,d=l.sortDefs.length>0,p=a!==void 0;if(u||h||c||f||d){let m={};u&&(m.aggregations=i),h&&(m.columns=r),c&&(m.filter=s),f&&(m.groupBy=o),d&&(m.sort=l),p&&(m.visualLink=a),P(this,Ye,m)}else P(this,Ye,void 0);this.emit("config",k(this,Ye),t)}get config(){return k(this,Ye)}set config(t){var i;if(ud(k(this,Ye),t)&&t){let r=t!=null&&t.filter&&(t==null?void 0:t.filter.filterStruct)===void 0?{...t,filter:{filter:t.filter.filter,filterStruct:Dr(t.filter.filter)}}:t;P(this,Ye,fd(r)),k(this,Ye)&&this.viewport&&this.server&&t&&((i=this.server)==null||i.send({viewport:this.viewport,type:"config",config:k(this,Ye)})),this.emit("config",k(this,Ye))}}get optimize(){return k(this,Hn)}set optimize(t){if(t!==k(this,Hn)){switch(P(this,Hn,t),t){case"none":this.rangeRequest=this.rawRangeRequest;break;case"debounce":this.rangeRequest=this.debounceRangeRequest;break;case"throttle":this.rangeRequest=this.throttleRangeRequest;break}this.emit("optimize",t)}}get selectedRowsCount(){return k(this,Er)}get size(){return k(this,Wn)}get range(){return k(this,qi)}set range(t){P(this,qi,t),this.rangeRequest(t)}get columns(){return k(this,Ci)}set columns(t){if(P(this,Ci,t),this.viewport){let i={viewport:this.viewport,type:"setColumns",columns:t};this.server&&this.server.send(i)}this.refreshConfig()}get aggregations(){return k(this,vi)}set aggregations(t){var i;P(this,vi,t),this.viewport&&((i=this.server)==null||i.send({viewport:this.viewport,type:"aggregate",aggregations:t})),this.refreshConfig()}get sort(){return k(this,xi)}set sort(t){if(P(this,xi,t),this.viewport){let i={viewport:this.viewport,type:"sort",sort:t};this.server&&this.server.send(i)}this.refreshConfig()}get filter(){return k(this,Si)}set filter(t){if(P(this,Si,t),this.viewport){let i={viewport:this.viewport,type:"filter",filter:t};this.server&&this.server.send(i)}this.refreshConfig()}get groupBy(){return k(this,Mt)}set groupBy(t){var r;let i=k(this,Mt).length>0;if(P(this,Mt,t!=null?t:[]),this.viewport){let s={viewport:this.viewport,type:"groupBy",groupBy:k(this,Mt)};this.server&&this.server.send(s)}!i&&t.length>0&&this.viewport&&((r=this.clientCallback)==null||r.call(this,{clientViewportId:this.viewport,type:"viewport-update",size:0,rows:[]})),this.refreshConfig(),this.setConfigPending({groupBy:t})}get title(){return k(this,Gi)}set title(t){var i;P(this,Gi,t),this.viewport&&t&&((i=this.server)==null||i.send({type:"setTitle",title:t,viewport:this.viewport}))}get visualLink(){return k(this,_n)}set visualLink(t){var i,r;if(P(this,_n,t),t){let{parentClientVpId:s,link:{fromColumn:o,toColumn:l}}=t;this.viewport&&((i=this.server)==null||i.send({viewport:this.viewport,type:"createLink",parentClientVpId:s,parentColumnName:l,childColumnName:o}))}else this.viewport&&((r=this.server)==null||r.send({type:"removeLink",viewport:this.viewport}));this.refreshConfig()}setConfigPending(t){let i=this.configChangePending;this.configChangePending=t,t!==void 0?this.emit("config",t,!1):this.emit("config",i,!0)}async menuRpcCall(t){var i;if(this.viewport)return(i=this.server)==null?void 0:i.rpcCall({vpId:this.viewport,...t})}};vi=new WeakMap,Ci=new WeakMap,Ye=new WeakMap,Si=new WeakMap,Mt=new WeakMap,Hn=new WeakMap,qi=new WeakMap,Er=new WeakMap,Wn=new WeakMap,xi=new WeakMap,Gi=new WeakMap,_n=new WeakMap;var Pd=require("react");var Ly=require("@vuu-ui/vuu-utils");var zy=require("@heswell/salt-lab"),Uy=ue(require("classnames"),1);var Id=require("@heswell/salt-lab");var Ny=require("@heswell/salt-lab"),Ed=require("react"),By=require("react/jsx-runtime");var Fy=require("@heswell/salt-lab"),Od=require("react"),Hy=require("react/jsx-runtime");var Wy=require("react/jsx-runtime");var $y=require("react/jsx-runtime");var Vd=require("@vuu-ui/vuu-utils");var Aa=n=>n!==void 0&&n.op==="in";function Pa(n){return n!==void 0&&(n.op==="and"||n.op==="or")}var Ky=n=>typeof n=="string"?`"${n}"`:n,Ea=n=>Pa(n)?n.filters.map(e=>Ea(e)).join(` ${n.op} `):Aa(n)?`${n.column} ${n.op} [${n.values.join(",")}]`:`${n.column} ${n.op} ${Ky(n.value)}`;var Ld=(n,e)=>{if(Pa(e)){let[t,i]=e.filters;if(t.column===n.name)return[i,Ea(i)];if(i.column===n.name)return[t,Ea(t)]}return[void 0,""]};var xe=require("@vuu-ui/vuu-utils"),qy=(n,e)=>{if(n.filterStruct&&e){let[t,i]=Ld(e,n.filterStruct);return{filter:i,filterStruct:t}}else return n},{Average:Gy,Count:jy,High:Jy,Low:Qy,Sum:Xy}=xe.AggregationType,Nd=({dataSource:n,onPersistentColumnOperation:e})=>(i,r)=>{let s=r;if(s.column&&n){let{column:o}=s;switch(i){case"sort-asc":return n.sort=(0,xe.setSortColumn)(n.sort,o,"A"),!0;case"sort-dsc":return n.sort=(0,xe.setSortColumn)(n.sort,o,"D"),!0;case"sort-add-asc":return n.sort=(0,xe.addSortColumn)(n.sort,o,"A"),!0;case"sort-add-dsc":return n.sort=(0,xe.addSortColumn)(n.sort,o,"D"),!0;case"group":return n.groupBy=(0,xe.addGroupColumn)(n.groupBy,o),!0;case"group-add":return n.groupBy=(0,xe.addGroupColumn)(n.groupBy,o),!0;case"column-hide":return e({type:"hideColumns",columns:[o]}),!0;case"column-remove":return n.columns=n.columns.filter(l=>l!==o.name),!0;case"filter-remove-column":return n.filter=qy(n.filter,o),!0;case"remove-filters":return n.filter={filter:""},!0;case"agg-avg":return n.aggregations=(0,xe.setAggregations)(n.aggregations,o,Gy),!0;case"agg-high":return n.aggregations=(0,xe.setAggregations)(n.aggregations,o,Jy),!0;case"agg-low":return n.aggregations=(0,xe.setAggregations)(n.aggregations,o,Qy),!0;case"agg-count":return n.aggregations=(0,xe.setAggregations)(n.aggregations,o,jy),!0;case"agg-sum":return n.aggregations=(0,xe.setAggregations)(n.aggregations,o,Xy),!0;case"column-pin-floating":return e({type:"pinColumn",column:o,pin:"floating"}),!0;case"column-pin-left":return e({type:"pinColumn",column:o,pin:"left"}),!0;case"column-pin-right":return e({type:"pinColumn",column:o,pin:"right"}),!0;case"column-unpin":return e({type:"pinColumn",column:o,pin:void 0}),!0;default:}}return!1};var Rt=require("@vuu-ui/vuu-utils"),Or=require("react");var Oa=ue(require("classnames")),Bd=require("react");var Kt=require("react/jsx-runtime"),ki="vuuTable-groupHeaderCell",Yy=n=>{let{column:e,className:t,onRemoveColumn:i}=n;return(0,Kt.jsxs)("div",{className:(0,Oa.default)(`${ki}-col`,t),role:"columnheader",children:[(0,Kt.jsx)("span",{className:`${ki}-label`,children:e.name}),(0,Kt.jsx)("span",{className:`${ki}-close`,"data-icon":"close-circle",onClick:()=>i==null?void 0:i(e)})]})},Fd=({column:n,className:e,onRemoveColumn:t,onResize:i,...r})=>{let s=(0,Bd.useRef)(null),{isResizing:o,...l}=Yr({column:n,onResize:i,rootRef:s}),a=(0,Oa.default)(ki,e,{vuuPinLeft:n.pin==="left",[`${ki}-right`]:n.align==="right",[`${ki}-resizing`]:n.resizing,[`${ki}-pending`]:n.groupConfirmed===!1}),{columns:u}=n;return(0,Kt.jsx)("th",{className:a,ref:s,...r,children:(0,Kt.jsxs)("div",{className:`${ki}-inner`,children:[u.map(h=>(0,Kt.jsx)(Yy,{column:h,onRemoveColumn:t},h.key)),n.resizeable!==!1?(0,Kt.jsx)(Xr,{...l}):null]})})};var Ie=require("react/jsx-runtime"),Hd="vuuTable",{RENDER_IDX:Zy}=Rt.metadataKeys,Wd=({columns:n,columnsWithinViewport:e,data:t,headings:i,onColumnResize:r,onHeaderCellDragStart:s,onContextMenu:o,onRemoveColumnFromGroupBy:l,onRowClick:a,onSort:u,onToggleGroup:h,virtualColSpan:c=0,rowCount:f,rowHeight:d})=>{let p=(0,Or.useCallback)(b=>{s==null||s(b)},[s]),m=(0,Or.useMemo)(()=>n.filter(Rt.notHidden),[n]),g=(0,Or.useCallback)(b=>{var M;let y=b.target.closest(".vuuTable-headerCell"),x=parseInt((M=y==null?void 0:y.dataset.idx)!=null?M:"-1"),v=(0,Rt.visibleColumnAtIndex)(n,x),w=b.shiftKey;v&&u(v,w)},[n,u]);return(0,Ie.jsxs)("table",{"aria-rowcount":f,className:`${Hd}-table`,children:[(0,Ie.jsx)("colgroup",{children:m.map((b,C)=>(0,Ie.jsx)("col",{width:`${b.width}px`},C))}),(0,Ie.jsxs)("thead",{children:[i.map((b,C)=>(0,Ie.jsx)("tr",{className:"vuuTable-heading",children:b.map(({label:y,span:x},v)=>(0,Ie.jsx)("th",{colSpan:x,className:"vuuTable-headingCell",children:y},v))},C)),(0,Ie.jsx)("tr",{children:m.map((b,C)=>{let y=(0,Rt.getColumnPinStyle)(b);return(0,Rt.isGroupColumn)(b)?(0,Ie.jsx)(Fd,{column:b,"data-idx":C,onRemoveColumn:l,onResize:r,style:y},C):(0,Ie.jsx)(Zr,{column:b,"data-idx":C,onClick:g,onDragStart:p,onResize:r,style:y},C)})})]}),(0,Ie.jsxs)("tbody",{onContextMenu:o,children:[t==null?void 0:t.map((b,C)=>(0,Ie.jsx)(Qr,{columns:e,height:d,index:C,onClick:a,virtualColSpan:c,onToggleGroup:h,row:b},b[Zy])),(0,Ie.jsx)("tr",{className:`${Hd}-filler`})]})]})};var Dt=require("@vuu-ui/vuu-utils"),le=require("react");var Mi=require("@vuu-ui/vuu-utils"),oe=require("react"),{SELECTED:Ir}=Mi.metadataKeys;function _d({dataSource:n,onConfigChange:e,onFeatureEnabled:t,onFeatureInvocation:i,onSizeChange:r,onSubscribed:s,range:o={from:0,to:0},renderBufferSize:l=0,viewportRowCount:a}){let[,u]=(0,oe.useState)(null),h=(0,oe.useRef)(!0),c=(0,oe.useRef)(!1),f=(0,oe.useRef)({from:0,to:0}),d=(0,oe.useRef)(null),p=(0,oe.useRef)([]),m=(0,oe.useMemo)(()=>new Ia((0,Mi.getFullRange)(o)),[]),g=(0,oe.useCallback)(w=>{for(let M of w)m.add(M);p.current=m.data,c.current=!0},[m]),b=(0,oe.useCallback)(w=>{w.type==="subscribed"?s==null||s(w):w.type==="viewport-update"?(typeof w.size=="number"&&(r==null||r(w.size),m.setRowCount(w.size)),w.rows?g(w.rows):typeof w.size=="number"&&(p.current=m.data,c.current=!0)):wd(w)?t==null||t(w):vd(w)?i==null||i(w):console.log(`useDataSource unexpected message ${w.type}`)},[m,t,i,r,s,g]);(0,oe.useEffect)(()=>()=>{d.current&&(cancelAnimationFrame(d.current),d.current=null),h.current=!1},[]);let C=(0,oe.useCallback)(()=>{h.current&&(c.current&&(u({}),c.current=!1),d.current=requestAnimationFrame(C))},[u]);(0,oe.useEffect)(()=>{d.current=requestAnimationFrame(C)},[C]);let y=(0,oe.useCallback)(w=>{let{from:M}=n.range,L={from:M,to:M+w},E=(0,Mi.getFullRange)(L,l);n.range=f.current=E,n.emit("range",L),m.setRange(E)},[n,m,l]),x=(0,oe.useCallback)(w=>{let M=(0,Mi.getFullRange)(w,l);n.range=f.current=M,m.setRange(M),n.emit("range",w)},[n,m,l]),v=(0,oe.useCallback)(()=>m.getSelectedRows(),[m]);return(0,oe.useEffect)(()=>{n==null||n.subscribe({range:f.current},b)},[n,b,e]),(0,oe.useEffect)(()=>{y(a)},[y,a]),{data:p.current,getSelectedRows:v,range:f.current,setRange:x,dataSource:n}}var Ia=class{constructor({from:e,to:t}){this.rowCount=0;this.setRowCount=e=>{e<this.data.length&&(this.data.length=e),this.rowCount=e};this.range=new Mi.WindowRange(e,t),this.data=new Array(t-e),this.rowCount=0}add(e){var i;let[t]=e;if(this.isWithinRange(t)){let r=t-this.range.from;this.data[r]=e;let s=e[Ir],o=(i=this.data[r-1])==null?void 0:i[Ir];o===0&&s?this.data[r-1][Ir]=2:o===2&&!s&&(this.data[r-1][Ir]=0)}}getAtIndex(e){return this.range.isWithin(e)&&this.data[e-this.range.from]!=null?this.data[e-this.range.from]:void 0}isWithinRange(e){return this.range.isWithin(e)}setRange({from:e,to:t}){if(e!==this.range.from||t!==this.range.to){let[i,r]=this.range.overlap(e,t),s=new Array(t-e);for(let o=i;o<r;o++){let l=this.getAtIndex(o);if(l){let a=o-e;s[a]=l}}this.data=s,this.range.from=e,this.range.to=t}}getSelectedRows(){return this.data.filter(e=>e[Ir]===1)}};var zd=require("@heswell/salt-lab"),qt=require("react"),Ud=({onDrop:n,tableContainerRef:e,tableLayout:t})=>{let[i,r]=(0,qt.useState)(t),s=(0,qt.useRef)(),o=(0,qt.useCallback)(()=>{console.log("handleDropSettle"),s.current=void 0,r("row")},[]),{draggable:l,draggedItemIndex:a,onMouseDown:u}=(0,zd.useDragDrop)({allowDragDrop:!0,draggableClassName:"table-column",orientation:"horizontal",containerRef:e,itemQuery:".vuuTable-table",onDrop:n,onDropSettle:o}),h=(0,qt.useCallback)(c=>{let{clientX:f,clientY:d}=c;console.log("useDraggableColumn handleHeaderCellDragStart means mouseDown fired on a column in RowBasedTable");let m=c.target.closest(".vuuTable-headerCell"),{dataset:{idx:g="-1"}}=m;s.current={clientX:f,clientY:d,idx:g},r("column")},[]);return(0,qt.useLayoutEffect)(()=>{var c;if(i==="column"&&s.current&&!l){let{clientX:f,clientY:d,idx:p}=s.current,m=(c=e.current)==null?void 0:c.querySelector(`.vuuTable-table[data-idx="${p}"]`);if(m){let g={persist:()=>{},nativeEvent:{clientX:f,clientY:d,target:m}};u==null||u(g)}}},[l,u,e,i]),{draggable:l,draggedItemIndex:a,tableLayout:i,onHeaderCellDragStart:i==="row"?h:void 0}};var jd=require("@vuu-ui/vuu-utils"),fe=require("react");function ew(n,...e){let t=new Set(n);for(let i of e)for(let r of i)t.add(r);return t}var Va="ArrowUp",La="ArrowDown",Na="ArrowLeft",Ba="ArrowRight";var Fa="Home",Ha="End",Wa="PageUp",_a="PageDown";var tw=new Set(["Enter","Delete"," "]),iw=new Set(["Tab"]),nw=new Set(["ArrowRight","ArrowLeft"]),$d=new Set([Fa,Ha,Wa,_a,La,Na,Ba,Va]),rw=new Set(["F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12"]),F1=ew(tw,$d,nw,rw,iw);var sw=["Home","End","PageUp","PageDown"],Kd=n=>sw.includes(n),qd=n=>$d.has(n);var Gd=n=>`thead th:nth-child(${n+1})`,ow=(n,e)=>`tbody > tr[aria-rowindex='${n}'] > td:nth-child(${e+1})`,lw=[-1,-1];function aw(n,[e,t],i,r){return n===Va?e>-1?[e-1,t]:[e,t]:n===La?e===-1?[0,t]:e===r-1?[e,t]:[e+1,t]:n===Ba?t<i-1?[e,t+1]:[e,t]:n===Na?t>0?[e,t-1]:[e,t]:[e,t]}var Jd=({columnCount:n=0,containerRef:e,disableHighlightOnFocus:t,data:i,requestScroll:r,rowCount:s=0,viewportRange:o})=>{var E;let{from:l,to:a}=o,u=(0,fe.useRef)([-1,-1]),h=(0,fe.useRef)(),c=(0,fe.useRef)([-1,0]),f=(0,fe.useCallback)(([S,R])=>{var I;let O=S===-1?Gd(R):ow(S,R);return(I=e.current)==null?void 0:I.querySelector(O)},[e]),d=S=>S==null?void 0:S.closest("th,td"),p=S=>{var R,O;if(S.tagName==="TH")return[-1,parseInt((R=S.dataset.idx)!=null?R:"-1",10)];{let I=S.closest("tr");if(I){let z=parseInt((O=I.ariaRowIndex)!=null?O:"-1",10),B=Array.from(I.childNodes).indexOf(S);return[z,B]}}return lw},m=(0,fe.useCallback)(S=>{var R;if(e.current){let O=f(S);O?(O!==h.current&&((R=h.current)==null||R.setAttribute("tabindex",""),h.current=O,O.setAttribute("tabindex","0")),O.focus()):(0,jd.withinRange)(S[0],o)||(h.current=void 0,r==null||r({type:"scroll-page",direction:"up"}))}},[e,f,r,o]),g=(0,fe.useCallback)((S,R,O=!1)=>{let I=[S,R];c.current=I,m(I),O&&(u.current=I)},[m]),b=(0,fe.useCallback)(()=>{var S;(S=h.current)==null||S.setAttribute("tabindex",""),h.current=void 0},[]),C=(0,fe.useCallback)(async(S,R)=>{switch(S){case _a:r==null||r({type:"scroll-page",direction:"down"});break;case Wa:r==null||r({type:"scroll-page",direction:"up"});break;case Fa:r==null||r({type:"scroll-end",direction:"home"});break;case Ha:r==null||r({type:"scroll-end",direction:"end"});break}return R},[r]),y=(0,fe.useCallback)(()=>{var S;if(t!==!0&&(S=e.current)!=null&&S.contains(document.activeElement)){let R=d(document.activeElement);R&&(u.current=p(R))}},[t,e]),x=(0,fe.useCallback)(async S=>{let[R,O]=Kd(S)?await C(S,c.current):aw(S,c.current,n,s),[I,z]=c.current;(R!==I||O!==z)&&g(R,O,!0)},[n,C,s,g]),v=(0,fe.useCallback)(S=>{i.length>0&&qd(S.key)&&(S.preventDefault(),S.stopPropagation(),x(S.key))},[i,x]),w=(0,fe.useCallback)(S=>{let R=S.target,O=d(R);if(O){let[I,z]=p(O);g(I,z)}},[g]),M=(0,fe.useMemo)(()=>({onClick:w,onFocus:y,onKeyDown:v}),[w,y,v]);(0,fe.useLayoutEffect)(()=>{let{current:S}=c,R=S[0]>=l&&S[0]<=a;h.current&&!R?b():!h.current&&R&&m(S)},[m,l,a,b]);let L=((E=e.current)==null?void 0:E.firstChild)!=null;return(0,fe.useEffect)(()=>{var S;if(L&&h.current===void 0){let R=(S=e.current)==null?void 0:S.querySelector(Gd(0));R&&(R.setAttribute("tabindex","0"),h.current=R)}},[e,L]),M};var zn=require("react");var Ji=require("react");var ji=new Map,Xd=(n,e,t)=>{switch(t){case"height":return e.height;case"clientHeight":return n.clientHeight;case"clientWidth":return n.clientWidth;case"contentHeight":return e.contentHeight;case"contentWidth":return e.contentWidth;case"scrollHeight":return Math.ceil(n.scrollHeight);case"scrollWidth":return Math.ceil(n.scrollWidth);case"width":return e.width;default:return 0}},Qd=new ResizeObserver(n=>{for(let e of n){let{target:t,borderBoxSize:i,contentBoxSize:r}=e,s=ji.get(t);if(s){let[{blockSize:o,inlineSize:l}]=i,[{blockSize:a,inlineSize:u}]=r,{onResize:h,measurements:c}=s,f=!1;for(let[d,p]of Object.entries(c)){let m=Xd(t,{height:o,width:l,contentHeight:a,contentWidth:u},d);m!==p&&(f=!0,c[d]=m)}f&&h&&h(c)}}});function Yd(n,e,t,i=!1){let r=(0,Ji.useRef)(e),s=(0,Ji.useCallback)(o=>{let{width:l,height:a}=o.getBoundingClientRect(),{clientWidth:u,clientHeight:h}=o;return r.current.reduce((c,f)=>(c[f]=Xd(o,{width:l,height:a,contentHeight:h,contentWidth:u},f),c),{})},[]);(0,Ji.useEffect)(()=>{let o=n.current;async function l(){ji.set(o,{measurements:{}}),await document.fonts.ready;let a=ji.get(o);if(a){let u=s(o);a.measurements=u,Qd.observe(o),i&&t(u)}else console.log("%cuseResizeObserver an target expected to be under observation wa snot found. This warrants investigation","font-weight:bold; color:red;")}if(o){if(ji.has(o))throw Error("useResizeObserver attemping to observe same element twice");l()}return()=>{o&&ji.has(o)&&(Qd.unobserve(o),ji.delete(o))}},[s,n]),(0,Ji.useEffect)(()=>{let o=n.current,l=ji.get(o);if(l){if(r.current!==e){r.current=e;let a=s(o);l.measurements=a}l.onResize=t}},[e,s,n,t])}var uw=["clientHeight","clientWidth"],Zd=n=>Number.isFinite(n),za=({defaultHeight:n=0,defaultWidth:e=0,height:t,width:i})=>{let r=(0,zn.useRef)(null),[s,o]=(0,zn.useState)({outer:{height:t!=null?t:"100%",width:i!=null?i:"100%"}}),l=(0,zn.useCallback)(({clientWidth:a,clientHeight:u})=>{o(h=>{let{inner:c,outer:f}=h;return Zd(u)&&Zd(a)&&(a!==(c==null?void 0:c.width)||u!==(c==null?void 0:c.height))?{outer:f,inner:{width:Math.floor(a)||e,height:Math.floor(u)||n}}:h})},[n,e]);return Yd(r,uw,l,!0),{containerRef:r,outerSize:s.outer,innerSize:s.inner}};var Un=require("@vuu-ui/vuu-utils"),Vr=require("react"),{IDX:hw,SELECTED:cw}=Un.metadataKeys,fw=[],ep=({selectionModel:n,onSelectionChange:e})=>{let t=(0,Vr.useRef)(-1),i=(0,Vr.useRef)(fw);return(0,Vr.useCallback)((s,o,l)=>{let{[hw]:a,[cw]:u}=s,{current:h}=t,{current:c}=i,d=(u?Un.deselectItem:Un.selectItem)(n,c,a,o,l,h);i.current=d,t.current=a,e&&e(d)},[e,n])};var tp=require("@heswell/salt-lab"),$=require("@vuu-ui/vuu-utils"),ip=require("react"),{info:Ua}=(0,$.logger)("useTableModel"),dw=100,np=$.metadataKeys.count,pw=({serverDataType:n})=>n===void 0,mw=n=>{var e,t;if((0,$.isTypeDescriptor)(n.type))return(0,$.getCellRenderer)((t=(e=n.type)==null?void 0:e.renderer)==null?void 0:t.name)},gw=(n,e,t)=>{var r;let i=e.indexOf(n.name);return i!==-1&&t[i]?t[i]:(r=n.serverDataType)!=null?r:"string"},bw=["int","long","double"],rp=n=>n===void 0?void 0:bw.includes(n)?"right":"left",yw=(n,e)=>{switch(Ua==null||Ua(`GridModelReducer ${e.type}`),e.type){case"init":return op(e);case"moveColumn":return vw(n,e);case"resizeColumn":return xw(n,e);case"setTypes":return kw(n,e);case"hideColumns":return Cw(n,e);case"showColumns":return Sw(n,e);case"pinColumn":return Mw(n,e);case"updateColumnProp":return Lr(n,e);case"tableConfig":return ap(n,e);default:return console.log(`unhandled action ${e.type}`),n}},sp=(n,e)=>{let[t,i]=(0,ip.useReducer)(yw,{tableConfig:n,dataSourceConfig:e},op);return{columns:t.columns,dispatchColumnAction:i,headings:t.headings}};function op({dataSourceConfig:n,tableConfig:e}){let t=e.columns.map(lp(e)),i=t.some($.isPinned)?(0,$.sortPinnedColumns)(t):t,r={columns:i,headings:(0,$.getTableHeadings)(i)};if(n){let{columns:s,...o}=n;return ap(r,{type:"tableConfig",...o})}else return r}var ww=(n,e)=>e==="uppercase"?n.toUpperCase():e==="capitalize"?n[0].toUpperCase()+n.slice(1).toLowerCase():n,lp=n=>(e,t)=>{let{columnDefaultWidth:i=dw,columnFormatHeader:r}=n,{align:s=rp(e.serverDataType),key:o,name:l,label:a=l,width:u=i,...h}=e,c={...h,align:s,CellRenderer:mw(e),label:ww(a,r),key:o!=null?o:t+np,name:l,originalIdx:t,valueFormatter:(0,$.getValueFormatter)(e),width:u};return(0,$.isGroupColumn)(c)&&(c.columns=c.columns.map(f=>lp(n)(f,f.key))),c};function vw(n,{column:e,moveBy:t,moveTo:i}){let{columns:r}=n;if(typeof t=="number"){let s=r.indexOf(e),o=r.slice(),[l]=o.splice(s,1);return o.splice(s+t,0,l),{...n,columns:o}}else if(typeof i=="number"){let s=r.indexOf(e);return{...n,columns:(0,tp.moveItem)(r,s,i)}}return n}function Cw(n,{columns:e}){return e.some(t=>t.hidden!==!0)?e.reduce((t,i)=>i.hidden!==!0?Lr(t,{type:"updateColumnProp",column:i,hidden:!0}):t,n):n}function Sw(n,{columns:e}){return e.some(t=>t.hidden)?e.reduce((t,i)=>i.hidden?Lr(t,{type:"updateColumnProp",column:i,hidden:!1}):t,n):n}function xw(n,{column:e,phase:t,width:i}){let r="updateColumnProp",s=t!=="end";switch(t){case"begin":case"end":return Lr(n,{type:r,column:e,resizing:s});case"resize":return Lr(n,{type:r,column:e,width:i});default:throw Error(`useTableModel.resizeColumn, invalid resizePhase ${t}`)}}function kw(n,{columnNames:e,serverDataTypes:t}){let{columns:i}=n;if(i.some(pw)){let r=i.map(s=>{var l;let o=gw(s,e,t);return{...s,align:(l=s.align)!=null?l:rp(o),serverDataType:o}});return{...n,columns:r}}else return n}function Mw(n,e){let{columns:t}=n,{column:i,pin:r}=e,s=t.find(o=>o.name===i.name);return s?(t=$n(t,{...s,pin:r}),t=(0,$.sortPinnedColumns)(t),{...n,columns:t}):n}function Lr(n,e){let{columns:t}=n,{align:i,column:r,hidden:s,label:o,resizing:l,width:a}=e,u=t.find(h=>h.name===r.name);return u&&((i==="left"||i==="right")&&(t=$n(t,{...u,align:i})),typeof o=="string"&&(t=$n(t,{...u,label:o})),typeof l=="boolean"&&(t=$n(t,{...u,resizing:l})),typeof s=="boolean"&&(t=$n(t,{...u,hidden:s})),typeof a=="number"&&(t=$n(t,{...u,width:a}))),{...n,columns:t}}function ap(n,{columns:e,confirmed:t,filter:i,groupBy:r,sort:s}){let o=e&&e.length>0,l=r!==void 0,a=typeof(i==null?void 0:i.filter)=="string",u=s&&s.sortDefs.length>0,h=n;return o&&(h={...n,columns:e.map((c,f)=>{let d=(0,$.getColumnName)(c),p=f+np,m=(0,$.findColumn)(h.columns,d);if(m)return m.key===p?m:{...m,key:p};throw Error(`useTableModel column ${c} not found`)})}),l&&(h={...n,columns:(0,$.applyGroupByToColumns)(h.columns,r,t)}),u&&(h={...n,columns:(0,$.applySortToColumns)(h.columns,s)}),a?h={...n,columns:(0,$.applyFilterToColumns)(h.columns,i)}:h.columns.some($.isFilteredColumn)&&(h={...n,columns:(0,$.stripFilterFromColumns)(h.columns)}),h}function $n(n,e){return n.map(t=>t.name===e.name?e:t)}var Ze=require("react"),up=n=>{let{scrollLeft:e,scrollTop:t}=n,{clientHeight:i,clientWidth:r,scrollHeight:s,scrollWidth:o}=n,l=e/(o-r),a=t/(s-i);return[l,a,e,t]},Tw=n=>{let{clientHeight:e,clientWidth:t,scrollHeight:i,scrollWidth:r}=n;return[r-t,i-e]},hp=({onHorizontalScroll:n,onVerticalScroll:e,viewport:t})=>{let i=(0,Ze.useRef)({scrollTop:0,scrollLeft:0}),r=(0,Ze.useRef)(null),s=(0,Ze.useRef)(null),o=(0,Ze.useRef)(null),l=(0,Ze.useRef)(!1),{maxScrollContainerScrollHorizontal:a,maxScrollContainerScrollVertical:u}=t,h=(0,Ze.useCallback)((m,g)=>{let{current:b}=o;b&&b.scrollTo({top:g,left:m,behavior:"auto"})},[o]),c=(0,Ze.useCallback)(()=>{let{current:m}=o;if(m){let{current:g}=i,{scrollLeft:b,scrollTop:C}=m;g.scrollTop!==C&&(g.scrollTop=C,e==null||e(C)),g.scrollLeft!==b&&(g.scrollLeft=b,n==null||n(b))}},[n,e]),f=(0,Ze.useCallback)(()=>{let{current:m}=s,{current:g}=r;if(m&&g){let[b,C,y,x]=up(m);l.current=!0,g.scrollLeft=Math.round(b*a),g.scrollTop=Math.round(C*u),h(y,x)}},[a,u,s,r,h]),d=(0,Ze.useCallback)(()=>{let{current:m}=s,{current:g}=r,{current:b}=l;if(b)l.current=!1;else if(m&&g){let[C,y]=up(g),[x,v]=Tw(m),w=Math.round(C*x),M=Math.round(y*v);m.scrollTo({left:w,top:M,behavior:"auto"}),h(w,M)}},[s,r,h]),p=(0,Ze.useCallback)(m=>{let{current:g}=r;if(g){if(l.current=!1,m.type==="scroll-page"){let{clientHeight:b,scrollLeft:C,scrollTop:y}=g,{direction:x}=m,v=x==="down"?b:-b,w=Math.min(Math.max(0,y+v),t.maxScrollContainerScrollVertical);g.scrollTo({top:w,left:C,behavior:"auto"})}else if(m.type==="scroll-end"){let{direction:b}=m,C=b==="end"?t.maxScrollContainerScrollVertical:0;g.scrollTo({top:C,left:g.scrollLeft,behavior:"auto"})}}},[t.maxScrollContainerScrollVertical]);return{scrollbarContainerRef:r,onScrollbarContainerScroll:d,contentContainerRef:s,onContentContainerScroll:f,tableContainerRef:o,onTableContainerScroll:c,requestScroll:p}};var $a=require("react"),Rw={fillerHeight:0,maxScrollContainerScrollHorizontal:0,maxScrollContainerScrollVertical:0,pinnedWidthLeft:0,pinnedWidthRight:0,rowCount:0,scrollContentHeight:0,scrollbarSize:0,scrollContentWidth:0,totalHeaderHeight:0},Dw=n=>{let e=0,t=0,i=0;for(let r of n){let{hidden:s,pin:o,width:l}=r,a=s?0:l;o==="left"?e+=a:o==="right"?t+=a:i+=a}return{pinnedWidthLeft:e,pinnedWidthRight:t,unpinnedWidth:i}},cp=({columns:n,headerHeight:e,headings:t,rowCount:i,rowHeight:r,size:s})=>{let{pinnedWidthLeft:o,pinnedWidthRight:l,unpinnedWidth:a}=(0,$a.useMemo)(()=>Dw(n),[n]);return(0,$a.useMemo)(()=>{var h;if(s){let c=t.length,f=15,d=i*r,p=o+a+l,m=d+e-(((h=s==null?void 0:s.height)!=null?h:0)-e-f),g=p-s.width+o,b=(s.height-e)/r,C=Number.isInteger(b)?b+1:Math.ceil(b);return{fillerHeight:(i-C)*r,maxScrollContainerScrollHorizontal:g,maxScrollContainerScrollVertical:m,pinnedWidthLeft:o,pinnedWidthRight:l,rowCount:C,scrollContentHeight:e+d+f,scrollbarSize:f,scrollContentWidth:p,totalHeaderHeight:e*(1+c)}}else return Rw},[e,t.length,o,l,i,r,s,a])};var Nr=require("@vuu-ui/vuu-utils"),ze=require("react"),fp=({columns:n,rowHeight:e,setRange:t,viewportMeasurements:i})=>{let r=(0,ze.useRef)(-1),{rowCount:s,scrollContentWidth:o,maxScrollContainerScrollHorizontal:l}=i,a=o-l,u=(0,ze.useRef)(0),[h,c]=(0,ze.useMemo)(()=>(0,Nr.getColumnsInViewport)(n,u.current,u.current+a),[a,n]),f=(0,ze.useRef)(c);(0,ze.useEffect)(()=>{p(h)},[h]);let[d,p]=(0,ze.useState)(h),m=(0,ze.useCallback)(b=>{u.current=b;let[C,y]=(0,Nr.getColumnsInViewport)(n,b,b+a);(0,Nr.itemsChanged)(d,C)&&(f.current=y,p(C))},[a,n,d]),g=(0,ze.useCallback)(b=>{let C=Math.floor(b/e);C!==r.current&&(r.current=C,t({from:C,to:C+s}))},[e,t,s]);return{columnsWithinViewport:d,onHorizontalScroll:m,onVerticalScroll:g,virtualColSpan:f.current}};var Aw=[],{KEY:Pw,IS_EXPANDED:dp,IS_LEAF:pp}=Dt.metadataKeys,mp=({config:n,dataSource:e,headerHeight:t,onConfigChange:i,onFeatureEnabled:r,onFeatureInvocation:s,onSelectionChange:o,renderBufferSize:l=0,rowHeight:a,selectionModel:u,tableLayout:h,...c})=>{var qa,Ga;let[f,d]=(0,le.useState)(0),p=(0,le.useRef)(!1),m=(0,le.useRef)();if(m.current=e,e===void 0)throw Error("no data source provided to DataTable");let g=za(c),b=(0,le.useCallback)(K=>{d(K)},[]),{columns:C,dispatchColumnAction:y,headings:x}=sp(n,e.config),v=(0,le.useCallback)(K=>{p.current=!0,y(K)},[y]),w=Nd({dataSource:e,onPersistentColumnOperation:v}),M=cp({columns:C,headerHeight:t,headings:x,rowCount:f,rowHeight:a,size:g.innerSize}),L=(0,le.useCallback)(K=>{if(K.tableMeta){let{columns:de,dataTypes:Ve}=K.tableMeta;p.current=!0,y({type:"setTypes",columnNames:de,serverDataTypes:Ve})}},[y]),E=(0,le.useCallback)(K=>{e.select(K),o==null||o(K)},[e,o]),S=ep({onSelectionChange:E,selectionModel:u}),{data:R,getSelectedRows:O,range:I,setRange:z}=_d({dataSource:e,onFeatureEnabled:r,onFeatureInvocation:s,onSubscribed:L,onSizeChange:b,renderBufferSize:l,viewportRowCount:M.rowCount}),B=(0,le.useRef)();B.current=R;let Y=(0,le.useCallback)((K,de=!1,Ve)=>{e&&(e.sort=(0,Dt.applySort)(e.sort,K,de,Ve))},[e]),ke=(0,le.useCallback)((K,de,Ve)=>{let ve=C.find(Pt=>Pt.name===de);if(ve)K==="end"&&(p.current=!0),y({type:"resizeColumn",phase:K,column:ve,width:Ve});else throw Error(`useDataTable.handleColumnResize, column ${de} not found`)},[C,y]),ae=(0,le.useCallback)((K,de)=>{let Ve=(0,Dt.isJsonGroup)(de,K),ve=K[Pw];if(K[dp]){if(e.closeTreeNode(ve,!0),Ve){let Pt=C.indexOf(de);e.getRowsAtDepth(Pt+1).some(Et=>Et[dp]||Et[pp])||y({type:"hideColumns",columns:C.slice(Pt+2)})}}else if(e.openTreeNode(ve),Ve){let Pt=e.getChildRows(ve),Ti=C.indexOf(de)+1,Et=[C[Ti]];Pt.some(Qi=>Qi[pp])&&Et.push(C[Ti+1]),Et.some(Qi=>Qi.hidden)&&y({type:"showColumns",columns:Et})}},[C,e,y]),{onVerticalScroll:q,onHorizontalScroll:j,columnsWithinViewport:et,virtualColSpan:ft}=fp({columns:C,rowHeight:a,setRange:z,viewportMeasurements:M}),{requestScroll:jt,...At}=hp({onHorizontalScroll:j,onVerticalScroll:q,viewport:M,viewportHeight:((Ga=(qa=g.innerSize)==null?void 0:qa.height)!=null?Ga:0)-t}),Fr=Jd({columnCount:C.length,containerRef:g.containerRef,data:R,requestScroll:jt,rowCount:e==null?void 0:e.size,viewportRange:I}),ao=(0,le.useCallback)(K=>{e&&e.groupBy.includes(K.name)&&(e.groupBy=e.groupBy.filter(de=>de!==K.name))},[e]),Hr=(0,le.useCallback)((K,de)=>{let Ve=e.columns[K],ve=(0,Dt.moveItem)(e.columns,Ve,de);ve!==e.columns&&(e.columns=ve,y({type:"tableConfig",columns:ve}))},[e,y]),wp=Ud({onDrop:Hr,tableContainerRef:At.tableContainerRef,tableLayout:h});(0,le.useEffect)(()=>{m.current&&(p.current=!0,y({type:"init",tableConfig:n,dataSourceConfig:m.current.config}))},[n,y]),(0,le.useEffect)(()=>{e.on("config",(K,de)=>{p.current=!0,y({type:"tableConfig",...K,confirmed:de})})},[e,y]),(0,le.useMemo)(()=>{p.current&&(i==null||i({...n,columns:C}),p.current=!1)},[C,n,i]);let Ka=en(),vp=(0,le.useCallback)(K=>{var Et;let{current:de}=B,{current:Ve}=m,ve=K.target,Pt=ve==null?void 0:ve.closest("td"),Ti=ve==null?void 0:ve.closest("tr");if(Pt&&Ti&&de&&Ve){let{columns:Qi,selectedRowsCount:Cp}=Ve,Sp=(0,Dt.buildColumnMap)(Qi),xp=parseInt((Et=Ti.ariaRowIndex)!=null?Et:"-1"),kp=Array.from(Ti.childNodes).indexOf(Pt),Mp=de.find(([Rp])=>Rp===xp),Tp=Qi[kp];Ka(K,"grid",{columnMap:Sp,columnName:Tp,row:Mp,selectedRows:Cp===0?Aw:O(),viewport:e==null?void 0:e.viewport})}},[e==null?void 0:e.viewport,O,Ka]);return{containerMeasurements:g,containerProps:Fr,columns:C,columnsWithinViewport:et,data:R,dispatchColumnAction:y,handleContextMenuAction:w,headings:x,onColumnResize:ke,onContextMenu:vp,onRemoveColumnFromGroupBy:ao,onRowClick:S,onSort:Y,onToggleGroup:ae,virtualColSpan:ft,scrollProps:At,rowCount:f,viewportMeasurements:M,...wp}};var gp=ue(require("classnames"));var bp=require("@vuu-ui/vuu-utils"),ct=require("react/jsx-runtime"),Gt="vuuTable",Ew=({allowConfigEditing:n=!1,className:e,config:t,dataSource:i,headerHeight:r=25,height:s,id:o,onConfigChange:l,onFeatureEnabled:a,onFeatureInvocation:u,onSelectionChange:h,onShowConfigEditor:c,renderBufferSize:f=0,rowHeight:d=20,selectionModel:p="extended",style:m,tableLayout:g="row",width:b,zebraStripes:C=!1,...y})=>{let x=(0,lo.useIdMemo)(o),{containerMeasurements:{containerRef:v,innerSize:w,outerSize:M},containerProps:L,dispatchColumnAction:E,draggable:S,draggedItemIndex:R,handleContextMenuAction:O,scrollProps:I,tableLayout:z,viewportMeasurements:B,...Y}=mp({config:t,dataSource:i,renderBufferSize:f,headerHeight:r,height:s,onConfigChange:l,onFeatureEnabled:a,onFeatureInvocation:u,onSelectionChange:h,rowHeight:d,selectionModel:p,tableLayout:g,width:b}),ke={...M,"--content-height":`${B.scrollContentHeight}px`,"--content-width":`${B.scrollContentWidth}px`,"--filler-height":`${B.fillerHeight}px`,"--pinned-width-left":`${B.pinnedWidthLeft}px`,"--pinned-width-right":`${B.pinnedWidthRight}px`,"--header-height":`${r}px`,"--row-height":`${d}px`,"--scrollbar-size":`${B.scrollbarSize}px`,"--table-height":`${w==null?void 0:w.height}px`,"--table-width":`${w==null?void 0:w.width}px`,"--total-header-height":`${B==null?void 0:B.totalHeaderHeight}px`},ae={left:B.pinnedWidthLeft-1,top:(B==null?void 0:B.totalHeaderHeight)-1},q=z==="column"?Ju:Wd,j=(0,gp.default)(Gt,e,{[`${Gt}-zebra`]:C,[`${Gt}-loading`]:(0,bp.isDataLoading)(Y.columns)});return(0,ct.jsx)(Su,{menuActionHandler:O,menuBuilder:Xu(i),children:(0,ct.jsxs)("div",{...L,className:j,id:x,ref:v,style:ke,tabIndex:-1,children:[w?(0,ct.jsx)("div",{className:`${Gt}-scrollbarContainer`,onScroll:I.onScrollbarContainerScroll,ref:I.scrollbarContainerRef,style:ae,children:(0,ct.jsx)("div",{className:`${Gt}-scrollContent`})}):null,w?(0,ct.jsxs)("div",{className:`${Gt}-contentContainer`,onScroll:I.onContentContainerScroll,ref:I.contentContainerRef,...y,children:[(0,ct.jsx)("div",{className:`${Gt}-scrollContent`}),(0,ct.jsx)("div",{className:`${Gt}-tableContainer`,onScroll:I.onTableContainerScroll,ref:I.tableContainerRef,children:(0,ct.jsx)(q,{...Y,headerHeight:r,rowHeight:d})}),S]}):null,n&&w?(0,ct.jsx)(lo.Button,{className:`${Gt}-settings`,"data-icon":"settings",onClick:c,variant:"secondary"}):null]})})};var yp=ue(require("classnames")),qn=require("@vuu-ui/vuu-utils");var Kn=require("react/jsx-runtime"),Br="vuuJsonCell",{IS_EXPANDED:Ow,KEY:Iw}=qn.metadataKeys,Vw=n=>{let e=n.lastIndexOf("|");return e===-1?"":n.slice(e+1)},Lw=({column:n,row:e})=>{let{key:t}=n,i=e[t],r=!1;(0,qn.isJsonAttribute)(i)&&(i=i.slice(0,-1),r=!0);let s=Vw(e[Iw]),o=(0,yp.default)({[`${Br}-name`]:s===i,[`${Br}-value`]:s!==i,[`${Br}-group`]:r});if(r){let l=e[Ow]?"minus-box":"plus-box";return(0,Kn.jsxs)("span",{className:o,children:[(0,Kn.jsx)("span",{className:`${Br}-value`,children:i}),(0,Kn.jsx)("span",{className:`${Br}-toggle`,"data-icon":l})]})}else return i?(0,Kn.jsx)("span",{className:o,children:i}):null};(0,qn.registerComponent)("json",Lw,"cell-renderer",{});
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ Table: () => Table,
34
+ useMeasuredContainer: () => useMeasuredContainer
35
+ });
36
+ module.exports = __toCommonJS(src_exports);
37
+
38
+ // src/Table.tsx
39
+ var import_vuu_popups4 = require("@vuu-ui/vuu-popups");
40
+ var import_core = require("@salt-ds/core");
41
+
42
+ // src/ColumnBasedTable.tsx
43
+ var import_vuu_utils4 = require("@vuu-ui/vuu-utils");
44
+ var import_react8 = require("react");
45
+ var import_classnames6 = __toESM(require("classnames"));
46
+
47
+ // src/TableRow.tsx
48
+ var import_vuu_utils3 = require("@vuu-ui/vuu-utils");
49
+ var import_classnames2 = __toESM(require("classnames"));
50
+ var import_react3 = require("react");
51
+
52
+ // src/TableCell.tsx
53
+ var import_vuu_utils = require("@vuu-ui/vuu-utils");
54
+ var import_salt_lab = require("@heswell/salt-lab");
55
+ var import_classnames = __toESM(require("classnames"));
56
+ var import_react = require("react");
57
+ var import_jsx_runtime = require("react/jsx-runtime");
58
+ var { KEY } = import_vuu_utils.metadataKeys;
59
+ var TableCell = (0, import_react.memo)(
60
+ ({ className: classNameProp, column, onClick, row }) => {
61
+ const labelFieldRef = (0, import_react.useRef)(null);
62
+ const {
63
+ align,
64
+ CellRenderer,
65
+ key,
66
+ pin,
67
+ editable,
68
+ resizing,
69
+ valueFormatter
70
+ } = column;
71
+ const [editing, setEditing] = (0, import_react.useState)(false);
72
+ const value = valueFormatter(row[key]);
73
+ const [editableValue, setEditableValue] = (0, import_react.useState)(value);
74
+ const handleTitleMouseDown = () => {
75
+ var _a;
76
+ (_a = labelFieldRef.current) == null ? void 0 : _a.focus();
77
+ };
78
+ const handleTitleKeyDown = (evt) => {
79
+ if (evt.key === "Enter") {
80
+ setEditing(true);
81
+ }
82
+ };
83
+ const handleClick = (0, import_react.useCallback)(() => {
84
+ onClick == null ? void 0 : onClick(column);
85
+ }, [column, onClick]);
86
+ const handleEnterEditMode = () => {
87
+ setEditing(true);
88
+ };
89
+ const handleExitEditMode = (originalValue = "", finalValue = "", allowDeactivation = true, editCancelled = false) => {
90
+ var _a;
91
+ setEditing(false);
92
+ if (editCancelled) {
93
+ setEditableValue(originalValue);
94
+ } else if (finalValue !== originalValue) {
95
+ setEditableValue(finalValue);
96
+ }
97
+ if (allowDeactivation === false) {
98
+ (_a = labelFieldRef.current) == null ? void 0 : _a.focus();
99
+ }
100
+ };
101
+ const className = (0, import_classnames.default)(classNameProp, {
102
+ vuuAlignRight: align === "right",
103
+ vuuPinFloating: pin === "floating",
104
+ vuuPinLeft: pin === "left",
105
+ vuuPinRight: pin === "right",
106
+ "vuuTableCell-resizing": resizing
107
+ }) || void 0;
108
+ const pinnedStyle = (0, import_vuu_utils.getColumnPinStyle)(column);
109
+ return editable ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
110
+ "td",
111
+ {
112
+ className,
113
+ "data-editable": true,
114
+ style: pinnedStyle,
115
+ onKeyDown: handleTitleKeyDown,
116
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
117
+ import_salt_lab.EditableLabel,
118
+ {
119
+ editing,
120
+ value: editableValue,
121
+ onChange: setEditableValue,
122
+ onMouseDownCapture: handleTitleMouseDown,
123
+ onEnterEditMode: handleEnterEditMode,
124
+ onExitEditMode: handleExitEditMode,
125
+ onKeyDown: handleTitleKeyDown,
126
+ ref: labelFieldRef,
127
+ tabIndex: 0
128
+ },
129
+ "title"
130
+ )
131
+ }
132
+ ) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("td", { className, style: pinnedStyle, onClick: handleClick, children: CellRenderer ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CellRenderer, { column, row }) : value });
133
+ },
134
+ cellValuesAreEqual
135
+ );
136
+ TableCell.displayName = "TableCell";
137
+ function cellValuesAreEqual(prev, next) {
138
+ return prev.column === next.column && prev.onClick === next.onClick && prev.row[KEY] === next.row[KEY] && prev.row[prev.column.key] === next.row[next.column.key];
139
+ }
140
+
141
+ // src/TableGroupCell.tsx
142
+ var import_vuu_utils2 = require("@vuu-ui/vuu-utils");
143
+ var import_react2 = require("react");
144
+ var import_jsx_runtime2 = require("react/jsx-runtime");
145
+ var { DEPTH, IS_LEAF } = import_vuu_utils2.metadataKeys;
146
+ var getGroupValueAndOffset = (columns, row) => {
147
+ const { [DEPTH]: depth, [IS_LEAF]: isLeaf } = row;
148
+ if (isLeaf || depth > columns.length) {
149
+ return [null, depth === null ? 0 : depth - 1];
150
+ } else if (depth === 0) {
151
+ return ["$root", 0];
152
+ } else {
153
+ const column = columns[depth - 1];
154
+ return [row[column.key], depth - 1];
155
+ }
156
+ };
157
+ var TableGroupCell = ({ column, onClick, row }) => {
158
+ const { columns } = column;
159
+ const [value, offset] = getGroupValueAndOffset(columns, row);
160
+ const handleClick = (0, import_react2.useCallback)(() => {
161
+ onClick == null ? void 0 : onClick(column);
162
+ }, [column, onClick]);
163
+ const style = {
164
+ left: column.pin == "left" ? column.pinnedOffset : void 0
165
+ };
166
+ const isLeaf = row[IS_LEAF];
167
+ const spacers = Array(offset).fill(0).map((n, i) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "vuuTableGroupCell-spacer" }, i));
168
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
169
+ "td",
170
+ {
171
+ className: "vuuTableGroupCell vuuPinLeft",
172
+ onClick: isLeaf ? void 0 : handleClick,
173
+ style,
174
+ children: [
175
+ spacers,
176
+ isLeaf ? null : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "vuuTableGroupCell-toggle", "data-icon": "triangle-right" }),
177
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: value })
178
+ ]
179
+ }
180
+ );
181
+ };
182
+
183
+ // src/TableRow.tsx
184
+ var import_jsx_runtime3 = require("react/jsx-runtime");
185
+ var { IDX, IS_EXPANDED, SELECTED } = import_vuu_utils3.metadataKeys;
186
+ var classBase = "vuuTableRow";
187
+ var TableRow = (0, import_react3.memo)(function Row({
188
+ columns,
189
+ height,
190
+ index,
191
+ onClick,
192
+ onToggleGroup,
193
+ virtualColSpan = 0,
194
+ row
195
+ }) {
196
+ const {
197
+ [IDX]: rowIndex,
198
+ [IS_EXPANDED]: isExpanded,
199
+ [SELECTED]: isSelected
200
+ } = row;
201
+ const className = (0, import_classnames2.default)(classBase, {
202
+ [`${classBase}-even`]: rowIndex % 2 === 0,
203
+ [`${classBase}-expanded`]: isExpanded,
204
+ [`${classBase}-preSelected`]: isSelected === 2
205
+ });
206
+ const offset = rowIndex - index;
207
+ const handleRowClick = (0, import_react3.useCallback)(
208
+ (evt) => {
209
+ const rangeSelect = evt.shiftKey;
210
+ const keepExistingSelection = evt.ctrlKey || evt.metaKey;
211
+ onClick == null ? void 0 : onClick(row, rangeSelect, keepExistingSelection);
212
+ },
213
+ [onClick, row]
214
+ );
215
+ const handleGroupCellClick = (0, import_react3.useCallback)(
216
+ (column) => {
217
+ if ((0, import_vuu_utils3.isGroupColumn)(column) || (0, import_vuu_utils3.isJsonGroup)(column, row)) {
218
+ onToggleGroup == null ? void 0 : onToggleGroup(row, column);
219
+ }
220
+ },
221
+ [onToggleGroup, row]
222
+ );
223
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
224
+ "tr",
225
+ {
226
+ "aria-selected": isSelected === 1 ? true : void 0,
227
+ "aria-rowindex": rowIndex,
228
+ className,
229
+ onClick: handleRowClick,
230
+ style: {
231
+ transform: `translate(0px, ${offset * height}px)`
232
+ },
233
+ children: [
234
+ virtualColSpan > 0 ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("td", { colSpan: virtualColSpan }) : null,
235
+ columns.filter(import_vuu_utils3.notHidden).map((column) => {
236
+ const isGroup = (0, import_vuu_utils3.isGroupColumn)(column);
237
+ const isJsonCell = (0, import_vuu_utils3.isJsonColumn)(column);
238
+ const Cell = isGroup ? TableGroupCell : TableCell;
239
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
240
+ Cell,
241
+ {
242
+ column,
243
+ onClick: isGroup || isJsonCell ? handleGroupCellClick : void 0,
244
+ row
245
+ },
246
+ column.name
247
+ );
248
+ })
249
+ ]
250
+ }
251
+ );
252
+ });
253
+
254
+ // src/TableHeaderCell.tsx
255
+ var import_classnames5 = __toESM(require("classnames"));
256
+ var import_react7 = require("react");
257
+
258
+ // src/ColumnResizer.tsx
259
+ var import_react4 = require("react");
260
+ var import_jsx_runtime4 = require("react/jsx-runtime");
261
+ var NOOP = () => void 0;
262
+ var baseClass = "vuuColumnResizer";
263
+ var ColumnResizer = ({
264
+ onDrag,
265
+ onDragEnd = NOOP,
266
+ onDragStart = NOOP
267
+ }) => {
268
+ const position = (0, import_react4.useRef)(0);
269
+ const onMouseMove = (0, import_react4.useCallback)(
270
+ (e) => {
271
+ if (e.stopPropagation) {
272
+ e.stopPropagation();
273
+ }
274
+ if (e.preventDefault) {
275
+ e.preventDefault();
276
+ }
277
+ const x = Math.round(e.clientX);
278
+ const moveBy = x - position.current;
279
+ position.current = x;
280
+ if (moveBy !== 0) {
281
+ onDrag(e, moveBy);
282
+ }
283
+ },
284
+ [onDrag]
285
+ );
286
+ const onMouseUp = (0, import_react4.useCallback)(
287
+ (e) => {
288
+ window.removeEventListener("mouseup", onMouseUp);
289
+ window.removeEventListener("mousemove", onMouseMove);
290
+ onDragEnd(e);
291
+ },
292
+ [onDragEnd, onMouseMove]
293
+ );
294
+ const handleMouseDown = (0, import_react4.useCallback)(
295
+ (e) => {
296
+ onDragStart(e);
297
+ position.current = Math.round(e.clientX);
298
+ window.addEventListener("mouseup", onMouseUp);
299
+ window.addEventListener("mousemove", onMouseMove);
300
+ if (e.stopPropagation) {
301
+ e.stopPropagation();
302
+ }
303
+ if (e.preventDefault) {
304
+ e.preventDefault();
305
+ }
306
+ },
307
+ [onDragStart, onMouseMove, onMouseUp]
308
+ );
309
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: baseClass, onMouseDown: handleMouseDown });
310
+ };
311
+
312
+ // src/SortIndicator.tsx
313
+ var import_classnames3 = __toESM(require("classnames"));
314
+ var import_jsx_runtime5 = require("react/jsx-runtime");
315
+ var classBase2 = "vuuSortIndicator";
316
+ var SortIndicator = ({ sorted }) => {
317
+ if (!sorted) {
318
+ return null;
319
+ }
320
+ const direction = typeof sorted === "number" ? sorted < 0 ? "dsc" : "asc" : sorted === "A" ? "asc" : "dsc";
321
+ return typeof sorted === "number" ? /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: (0, import_classnames3.default)(classBase2, "multi-col", direction), children: [
322
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { "data-icon": `sorted-${direction}` }),
323
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "vuuSortPosition", children: Math.abs(sorted) })
324
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: (0, import_classnames3.default)(classBase2, "single-col"), children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { "data-icon": `sorted-${direction}` }) });
325
+ };
326
+
327
+ // src/useTableColumnResize.tsx
328
+ var import_react5 = require("react");
329
+ var useTableColumnResize = ({
330
+ column,
331
+ onResize,
332
+ rootRef
333
+ }) => {
334
+ const widthRef = (0, import_react5.useRef)(0);
335
+ const isResizing = (0, import_react5.useRef)(false);
336
+ const { name } = column;
337
+ const handleResizeStart = (0, import_react5.useCallback)(() => {
338
+ if (onResize && rootRef.current) {
339
+ const { width } = rootRef.current.getBoundingClientRect();
340
+ widthRef.current = Math.round(width);
341
+ isResizing.current = true;
342
+ onResize == null ? void 0 : onResize("begin", name);
343
+ }
344
+ }, [name, onResize, rootRef]);
345
+ const handleResize = (0, import_react5.useCallback)(
346
+ (_evt, moveBy) => {
347
+ if (rootRef.current) {
348
+ if (onResize) {
349
+ const { width } = rootRef.current.getBoundingClientRect();
350
+ const newWidth = Math.round(width) + moveBy;
351
+ if (newWidth !== widthRef.current && newWidth > 0) {
352
+ onResize("resize", name, newWidth);
353
+ widthRef.current = newWidth;
354
+ }
355
+ }
356
+ }
357
+ },
358
+ [name, onResize, rootRef]
359
+ );
360
+ const handleResizeEnd = (0, import_react5.useCallback)(() => {
361
+ if (onResize) {
362
+ onResize("end", name, widthRef.current);
363
+ setTimeout(() => {
364
+ isResizing.current = false;
365
+ }, 100);
366
+ }
367
+ }, [name, onResize]);
368
+ return {
369
+ isResizing: isResizing.current,
370
+ onDrag: handleResize,
371
+ onDragStart: handleResizeStart,
372
+ onDragEnd: handleResizeEnd
373
+ };
374
+ };
375
+
376
+ // src/TableHeaderCell.tsx
377
+ var import_vuu_popups2 = require("@vuu-ui/vuu-popups");
378
+
379
+ // src/filter-indicator.tsx
380
+ var import_vuu_popups = require("@vuu-ui/vuu-popups");
381
+ var import_classnames4 = __toESM(require("classnames"));
382
+ var import_react6 = require("react");
383
+ var import_jsx_runtime6 = require("react/jsx-runtime");
384
+ var FilterIndicator = ({ column, filter }) => {
385
+ const showContextMenu = (0, import_vuu_popups.useContextMenu)();
386
+ const handleClick = (0, import_react6.useCallback)(
387
+ (evt) => {
388
+ evt.stopPropagation();
389
+ showContextMenu(evt, "filter", { column, filter });
390
+ },
391
+ [column, filter, showContextMenu]
392
+ );
393
+ if (!column.filter) {
394
+ return null;
395
+ }
396
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
397
+ "div",
398
+ {
399
+ className: (0, import_classnames4.default)("vuuFilterIndicator"),
400
+ "data-icon": "filter",
401
+ onClick: handleClick
402
+ }
403
+ );
404
+ };
405
+
406
+ // src/TableHeaderCell.tsx
407
+ var import_jsx_runtime7 = require("react/jsx-runtime");
408
+ var classBase3 = "vuuTable-headerCell";
409
+ var TableHeaderCell = ({
410
+ column,
411
+ className: classNameProp,
412
+ onClick,
413
+ onDragStart,
414
+ onResize,
415
+ ...props
416
+ }) => {
417
+ const rootRef = (0, import_react7.useRef)(null);
418
+ const { isResizing, ...resizeProps } = useTableColumnResize({
419
+ column,
420
+ onResize,
421
+ rootRef
422
+ });
423
+ const showContextMenu = (0, import_vuu_popups2.useContextMenu)();
424
+ const dragTimerRef = (0, import_react7.useRef)(null);
425
+ const handleContextMenu = (e) => {
426
+ showContextMenu(e, "header", { column });
427
+ };
428
+ const handleClick = (0, import_react7.useCallback)(
429
+ (evt) => !isResizing && (onClick == null ? void 0 : onClick(evt)),
430
+ [isResizing, onClick]
431
+ );
432
+ const handleMouseDown = (0, import_react7.useCallback)(
433
+ (evt) => {
434
+ dragTimerRef.current = window.setTimeout(() => {
435
+ onDragStart == null ? void 0 : onDragStart(evt);
436
+ dragTimerRef.current = null;
437
+ }, 250);
438
+ },
439
+ [onDragStart]
440
+ );
441
+ const handleMouseUp = (0, import_react7.useCallback)(() => {
442
+ if (dragTimerRef.current !== null) {
443
+ window.clearTimeout(dragTimerRef.current);
444
+ dragTimerRef.current = null;
445
+ }
446
+ }, []);
447
+ const className = (0, import_classnames5.default)(classBase3, classNameProp, {
448
+ vuuPinFloating: column.pin === "floating",
449
+ vuuPinLeft: column.pin === "left",
450
+ vuuPinRight: column.pin === "right",
451
+ vuuEndPin: column.endPin,
452
+ [`${classBase3}-resizing`]: column.resizing,
453
+ [`${classBase3}-right`]: column.align === "right"
454
+ });
455
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
456
+ "th",
457
+ {
458
+ className,
459
+ ...props,
460
+ onClick: handleClick,
461
+ onContextMenu: handleContextMenu,
462
+ onMouseDown: handleMouseDown,
463
+ onMouseUp: handleMouseUp,
464
+ ref: rootRef,
465
+ children: /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: `${classBase3}-inner`, children: [
466
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(FilterIndicator, { column }),
467
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { className: `${classBase3}-label`, children: column.label }),
468
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(SortIndicator, { sorted: column.sorted }),
469
+ column.resizeable !== false ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(ColumnResizer, { ...resizeProps }) : null
470
+ ] })
471
+ }
472
+ );
473
+ };
474
+
475
+ // src/ColumnBasedTable.tsx
476
+ var import_jsx_runtime8 = require("react/jsx-runtime");
477
+ var classBase4 = "vuuTable";
478
+ var { RENDER_IDX } = import_vuu_utils4.metadataKeys;
479
+ var ColumnBasedTable = ({
480
+ columns,
481
+ data,
482
+ headerHeight,
483
+ onHeaderCellDragEnd,
484
+ rowHeight
485
+ }) => {
486
+ const handleDragEnd = (0, import_react8.useCallback)(() => {
487
+ onHeaderCellDragEnd == null ? void 0 : onHeaderCellDragEnd();
488
+ }, [onHeaderCellDragEnd]);
489
+ console.log(`ColumnBasedTable render`);
490
+ return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_jsx_runtime8.Fragment, { children: columns.map((column, i) => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
491
+ "table",
492
+ {
493
+ className: (0, import_classnames6.default)(`${classBase4}-table`, `${classBase4}-columnBased`, {
494
+ vuuPinLeft: column.pin === "left"
495
+ }),
496
+ "data-idx": i,
497
+ id: `col-${i}`,
498
+ style: {
499
+ width: column.width,
500
+ left: column.pinnedOffset,
501
+ "--vuuTableHeaderHeight": `${headerHeight}px`,
502
+ "--row-height": `${rowHeight}px`
503
+ },
504
+ children: /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("tbody", { children: [
505
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("tr", { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
506
+ TableHeaderCell,
507
+ {
508
+ column,
509
+ "data-idx": i,
510
+ onDragEnd: handleDragEnd
511
+ },
512
+ i
513
+ ) }, "header"),
514
+ data.map((row, j) => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
515
+ TableRow,
516
+ {
517
+ columns: [column],
518
+ height: rowHeight,
519
+ index: j,
520
+ row
521
+ },
522
+ row[RENDER_IDX]
523
+ )),
524
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("tr", { className: "vuuTable-filler" })
525
+ ] })
526
+ },
527
+ column.name
528
+ )) });
529
+ };
530
+
531
+ // src/context-menu/buildContextMenuDescriptors.ts
532
+ var import_vuu_utils5 = require("@vuu-ui/vuu-utils");
533
+ var buildContextMenuDescriptors = (dataSource) => (location, options) => {
534
+ const descriptors = [];
535
+ if (dataSource === void 0) {
536
+ return descriptors;
537
+ }
538
+ if (location === "header") {
539
+ descriptors.push(
540
+ ...buildSortMenuItems(options, dataSource)
541
+ );
542
+ descriptors.push(
543
+ ...buildGroupMenuItems(options, dataSource)
544
+ );
545
+ descriptors.push(
546
+ ...buildAggregationMenuItems(options, dataSource)
547
+ );
548
+ descriptors.push(...buildColumnDisplayMenuItems(options));
549
+ } else if (location === "filter") {
550
+ const { column, filter } = options;
551
+ const colIsOnlyFilter = (filter == null ? void 0 : filter.column) === (column == null ? void 0 : column.name);
552
+ descriptors.push({
553
+ label: "Edit filter",
554
+ action: "filter-edit",
555
+ options
556
+ });
557
+ descriptors.push({
558
+ label: "Remove filter",
559
+ action: "filter-remove-column",
560
+ options
561
+ });
562
+ if (column && !colIsOnlyFilter) {
563
+ descriptors.push({
564
+ label: `Remove all filters`,
565
+ action: "remove-filters",
566
+ options
567
+ });
568
+ }
569
+ }
570
+ return descriptors;
571
+ };
572
+ function buildSortMenuItems(options, { sort: { sortDefs } }) {
573
+ const { column } = options;
574
+ const menuItems = [];
575
+ if (column === void 0) {
576
+ return menuItems;
577
+ }
578
+ const hasSort = sortDefs.length > 0;
579
+ if (column.sorted === "A") {
580
+ menuItems.push({
581
+ label: "Reverse Sort (DSC)",
582
+ action: "sort-dsc",
583
+ options
584
+ });
585
+ } else if (column.sorted === "D") {
586
+ menuItems.push({
587
+ label: "Reverse Sort (ASC)",
588
+ action: "sort-asc",
589
+ options
590
+ });
591
+ } else if (typeof column.sorted === "number") {
592
+ if (column.sorted > 0) {
593
+ menuItems.push({
594
+ label: "Reverse Sort (DSC)",
595
+ action: "sort-add-dsc",
596
+ options
597
+ });
598
+ } else {
599
+ menuItems.push({
600
+ label: "Reverse Sort (ASC)",
601
+ action: "sort-add-asc",
602
+ options
603
+ });
604
+ }
605
+ if (hasSort && Math.abs(column.sorted) < sortDefs.length) {
606
+ menuItems.push({
607
+ label: "Remove from sort",
608
+ action: "sort-remove",
609
+ options
610
+ });
611
+ }
612
+ menuItems.push({
613
+ label: "New Sort",
614
+ children: [
615
+ { label: "Ascending", action: "sort-asc", options },
616
+ { label: "Descending", action: "sort-dsc", options }
617
+ ]
618
+ });
619
+ } else if (hasSort) {
620
+ menuItems.push({
621
+ label: "Add to sort",
622
+ children: [
623
+ { label: "Ascending", action: "sort-add-asc", options },
624
+ { label: "Descending", action: "sort-add-dsc", options }
625
+ ]
626
+ });
627
+ menuItems.push({
628
+ label: "New Sort",
629
+ children: [
630
+ { label: "Ascending", action: "sort-asc", options },
631
+ { label: "Descending", action: "sort-dsc", options }
632
+ ]
633
+ });
634
+ } else {
635
+ menuItems.push({
636
+ label: "Sort",
637
+ children: [
638
+ { label: "Ascending", action: "sort-asc", options },
639
+ { label: "Descending", action: "sort-dsc", options }
640
+ ]
641
+ });
642
+ }
643
+ return menuItems;
644
+ }
645
+ function buildAggregationMenuItems(options, dataSource) {
646
+ const { column } = options;
647
+ if (column === void 0 || dataSource.groupBy.length === 0) {
648
+ return [];
649
+ }
650
+ const { name, label = name } = column;
651
+ return [
652
+ {
653
+ label: `Aggregate ${label}`,
654
+ children: [{ label: "Count", action: "agg-count", options }].concat(
655
+ (0, import_vuu_utils5.isNumericColumn)(column) ? [
656
+ { label: "Sum", action: "agg-sum", options },
657
+ { label: "Avg", action: "agg-avg", options },
658
+ { label: "High", action: "agg-high", options },
659
+ { label: "Low", action: "agg-low", options }
660
+ ] : []
661
+ )
662
+ }
663
+ ];
664
+ }
665
+ var pinColumn = (options, pinLocation) => ({
666
+ label: `Pin ${pinLocation}`,
667
+ action: `column-pin-${pinLocation}`,
668
+ options
669
+ });
670
+ var pinLeft = (options) => pinColumn(options, "left");
671
+ var pinFloating = (options) => pinColumn(options, "floating");
672
+ var pinRight = (options) => pinColumn(options, "right");
673
+ function buildColumnDisplayMenuItems(options) {
674
+ const { column } = options;
675
+ if (column === void 0) {
676
+ return [];
677
+ }
678
+ const { pin } = column;
679
+ const menuItems = [
680
+ {
681
+ label: `Hide column`,
682
+ action: "column-hide",
683
+ options
684
+ },
685
+ {
686
+ label: `Remove column`,
687
+ action: "column-remove",
688
+ options
689
+ }
690
+ ];
691
+ if (pin === void 0) {
692
+ menuItems.push({
693
+ label: `Pin column`,
694
+ children: [pinLeft(options), pinFloating(options), pinRight(options)]
695
+ });
696
+ } else if (pin === "left") {
697
+ menuItems.push(
698
+ { label: "Unpin column", action: "column-unpin", options },
699
+ {
700
+ label: `Pin column`,
701
+ children: [pinFloating(options), pinRight(options)]
702
+ }
703
+ );
704
+ } else if (pin === "right") {
705
+ menuItems.push(
706
+ { label: "Unpin column", action: "column-unpin", options },
707
+ {
708
+ label: `Pin column`,
709
+ children: [pinLeft(options), pinFloating(options)]
710
+ }
711
+ );
712
+ } else if (pin === "floating") {
713
+ menuItems.push(
714
+ { label: "Unpin column", action: "column-unpin", options },
715
+ {
716
+ label: `Pin column`,
717
+ children: [pinLeft(options), pinRight(options)]
718
+ }
719
+ );
720
+ }
721
+ return menuItems;
722
+ }
723
+ function buildGroupMenuItems(options, { groupBy }) {
724
+ const { column } = options;
725
+ const menuItems = [];
726
+ if (column === void 0) {
727
+ return menuItems;
728
+ }
729
+ const { name, label = name } = column;
730
+ if (groupBy.length === 0) {
731
+ menuItems.push({
732
+ label: `Group by ${label}`,
733
+ action: "group",
734
+ options
735
+ });
736
+ } else {
737
+ menuItems.push({
738
+ label: `Add ${label} to group by`,
739
+ action: "group-add",
740
+ options
741
+ });
742
+ }
743
+ return menuItems;
744
+ }
745
+
746
+ // src/context-menu/useContextMenu.ts
747
+ var import_vuu_filters = require("@vuu-ui/vuu-filters");
748
+ var import_vuu_utils6 = require("@vuu-ui/vuu-utils");
749
+ var removeFilterColumn = (dataSourceFilter, column) => {
750
+ if (dataSourceFilter.filterStruct && column) {
751
+ const [filterStruct, filter] = (0, import_vuu_filters.removeColumnFromFilter)(
752
+ column,
753
+ dataSourceFilter.filterStruct
754
+ );
755
+ return {
756
+ filter,
757
+ filterStruct
758
+ };
759
+ } else {
760
+ return dataSourceFilter;
761
+ }
762
+ };
763
+ var { Average, Count, High, Low, Sum } = import_vuu_utils6.AggregationType;
764
+ var useContextMenu3 = ({
765
+ dataSource,
766
+ onPersistentColumnOperation
767
+ }) => {
768
+ const handleContextMenuAction = (type, options) => {
769
+ const gridOptions = options;
770
+ if (gridOptions.column && dataSource) {
771
+ const { column } = gridOptions;
772
+ switch (type) {
773
+ case "sort-asc":
774
+ return dataSource.sort = (0, import_vuu_utils6.setSortColumn)(dataSource.sort, column, "A"), true;
775
+ case "sort-dsc":
776
+ return dataSource.sort = (0, import_vuu_utils6.setSortColumn)(dataSource.sort, column, "D"), true;
777
+ case "sort-add-asc":
778
+ return dataSource.sort = (0, import_vuu_utils6.addSortColumn)(dataSource.sort, column, "A"), true;
779
+ case "sort-add-dsc":
780
+ return dataSource.sort = (0, import_vuu_utils6.addSortColumn)(dataSource.sort, column, "D"), true;
781
+ case "group":
782
+ return dataSource.groupBy = (0, import_vuu_utils6.addGroupColumn)(dataSource.groupBy, column), true;
783
+ case "group-add":
784
+ return dataSource.groupBy = (0, import_vuu_utils6.addGroupColumn)(dataSource.groupBy, column), true;
785
+ case "column-hide":
786
+ return onPersistentColumnOperation({ type: "hideColumns", columns: [column] }), true;
787
+ case "column-remove":
788
+ return dataSource.columns = dataSource.columns.filter((name) => name !== column.name), true;
789
+ case "filter-remove-column":
790
+ return dataSource.filter = removeFilterColumn(dataSource.filter, column), true;
791
+ case "remove-filters":
792
+ return dataSource.filter = { filter: "" }, true;
793
+ case "agg-avg":
794
+ return dataSource.aggregations = (0, import_vuu_utils6.setAggregations)(dataSource.aggregations, column, Average), true;
795
+ case "agg-high":
796
+ return dataSource.aggregations = (0, import_vuu_utils6.setAggregations)(dataSource.aggregations, column, High), true;
797
+ case "agg-low":
798
+ return dataSource.aggregations = (0, import_vuu_utils6.setAggregations)(dataSource.aggregations, column, Low), true;
799
+ case "agg-count":
800
+ return dataSource.aggregations = (0, import_vuu_utils6.setAggregations)(dataSource.aggregations, column, Count), true;
801
+ case "agg-sum":
802
+ return dataSource.aggregations = (0, import_vuu_utils6.setAggregations)(dataSource.aggregations, column, Sum), true;
803
+ case "column-pin-floating":
804
+ return onPersistentColumnOperation({ type: "pinColumn", column, pin: "floating" }), true;
805
+ case "column-pin-left":
806
+ return onPersistentColumnOperation({ type: "pinColumn", column, pin: "left" }), true;
807
+ case "column-pin-right":
808
+ return onPersistentColumnOperation({ type: "pinColumn", column, pin: "right" }), true;
809
+ case "column-unpin":
810
+ return onPersistentColumnOperation({ type: "pinColumn", column, pin: void 0 }), true;
811
+ default:
812
+ }
813
+ }
814
+ return false;
815
+ };
816
+ return handleContextMenuAction;
817
+ };
818
+
819
+ // src/RowBasedTable.tsx
820
+ var import_vuu_utils7 = require("@vuu-ui/vuu-utils");
821
+ var import_react10 = require("react");
822
+
823
+ // src/TableGroupHeaderCell.tsx
824
+ var import_classnames7 = __toESM(require("classnames"));
825
+ var import_react9 = require("react");
826
+ var import_jsx_runtime9 = require("react/jsx-runtime");
827
+ var classBase5 = "vuuTable-groupHeaderCell";
828
+ var ColHeader = (props) => {
829
+ const { column, className, onRemoveColumn } = props;
830
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)("div", { className: (0, import_classnames7.default)(`${classBase5}-col`, className), role: "columnheader", children: [
831
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("span", { className: `${classBase5}-label`, children: column.name }),
832
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
833
+ "span",
834
+ {
835
+ className: `${classBase5}-close`,
836
+ "data-icon": "close-circle",
837
+ onClick: () => onRemoveColumn == null ? void 0 : onRemoveColumn(column)
838
+ }
839
+ )
840
+ ] });
841
+ };
842
+ var TableGroupHeaderCell = ({
843
+ column: groupColumn,
844
+ className: classNameProp,
845
+ onRemoveColumn,
846
+ onResize,
847
+ ...props
848
+ }) => {
849
+ const rootRef = (0, import_react9.useRef)(null);
850
+ const { isResizing, ...resizeProps } = useTableColumnResize({
851
+ column: groupColumn,
852
+ onResize,
853
+ rootRef
854
+ });
855
+ const className = (0, import_classnames7.default)(classBase5, classNameProp, {
856
+ vuuPinLeft: groupColumn.pin === "left",
857
+ [`${classBase5}-right`]: groupColumn.align === "right",
858
+ [`${classBase5}-resizing`]: groupColumn.resizing,
859
+ [`${classBase5}-pending`]: groupColumn.groupConfirmed === false
860
+ });
861
+ const { columns } = groupColumn;
862
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("th", { className, ref: rootRef, ...props, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)("div", { className: `${classBase5}-inner`, children: [
863
+ columns.map((column) => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
864
+ ColHeader,
865
+ {
866
+ column,
867
+ onRemoveColumn
868
+ },
869
+ column.key
870
+ )),
871
+ groupColumn.resizeable !== false ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(ColumnResizer, { ...resizeProps }) : null
872
+ ] }) });
873
+ };
874
+
875
+ // src/RowBasedTable.tsx
876
+ var import_jsx_runtime10 = require("react/jsx-runtime");
877
+ var classBase6 = "vuuTable";
878
+ var { RENDER_IDX: RENDER_IDX2 } = import_vuu_utils7.metadataKeys;
879
+ var RowBasedTable = ({
880
+ columns,
881
+ columnsWithinViewport,
882
+ data,
883
+ headings,
884
+ onColumnResize,
885
+ onHeaderCellDragStart,
886
+ onContextMenu,
887
+ onRemoveColumnFromGroupBy,
888
+ onRowClick,
889
+ onSort,
890
+ onToggleGroup,
891
+ virtualColSpan = 0,
892
+ rowCount,
893
+ rowHeight
894
+ }) => {
895
+ const handleDragStart = (0, import_react10.useCallback)(
896
+ (evt) => {
897
+ onHeaderCellDragStart == null ? void 0 : onHeaderCellDragStart(evt);
898
+ },
899
+ [onHeaderCellDragStart]
900
+ );
901
+ const visibleColumns = (0, import_react10.useMemo)(() => {
902
+ return columns.filter(import_vuu_utils7.notHidden);
903
+ }, [columns]);
904
+ const handleHeaderClick = (0, import_react10.useCallback)(
905
+ (evt) => {
906
+ var _a;
907
+ const targetElement = evt.target;
908
+ const headerCell = targetElement.closest(
909
+ ".vuuTable-headerCell"
910
+ );
911
+ const colIdx = parseInt((_a = headerCell == null ? void 0 : headerCell.dataset.idx) != null ? _a : "-1");
912
+ const column = (0, import_vuu_utils7.visibleColumnAtIndex)(columns, colIdx);
913
+ const isAdditive = evt.shiftKey;
914
+ column && onSort(column, isAdditive);
915
+ },
916
+ [columns, onSort]
917
+ );
918
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("table", { "aria-rowcount": rowCount, className: `${classBase6}-table`, children: [
919
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("colgroup", { children: visibleColumns.map((column, i) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("col", { width: `${column.width}px` }, i)) }),
920
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("thead", { children: [
921
+ headings.map((colHeaders, i) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("tr", { className: "vuuTable-heading", children: colHeaders.map(({ label, span }, j) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("th", { colSpan: span, className: "vuuTable-headingCell", children: label }, j)) }, i)),
922
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("tr", { children: visibleColumns.map((column, i) => {
923
+ const style = (0, import_vuu_utils7.getColumnPinStyle)(column);
924
+ return (0, import_vuu_utils7.isGroupColumn)(column) ? /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
925
+ TableGroupHeaderCell,
926
+ {
927
+ column,
928
+ "data-idx": i,
929
+ onRemoveColumn: onRemoveColumnFromGroupBy,
930
+ onResize: onColumnResize,
931
+ style
932
+ },
933
+ i
934
+ ) : /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
935
+ TableHeaderCell,
936
+ {
937
+ column,
938
+ "data-idx": i,
939
+ onClick: handleHeaderClick,
940
+ onDragStart: handleDragStart,
941
+ onResize: onColumnResize,
942
+ style
943
+ },
944
+ i
945
+ );
946
+ }) })
947
+ ] }),
948
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("tbody", { onContextMenu, children: [
949
+ data == null ? void 0 : data.map((row, i) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
950
+ TableRow,
951
+ {
952
+ columns: columnsWithinViewport,
953
+ height: rowHeight,
954
+ index: i,
955
+ onClick: onRowClick,
956
+ virtualColSpan,
957
+ onToggleGroup,
958
+ row
959
+ },
960
+ row[RENDER_IDX2]
961
+ )),
962
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("tr", { className: `${classBase6}-filler` })
963
+ ] })
964
+ ] });
965
+ };
966
+
967
+ // src/useDataTable.ts
968
+ var import_vuu_popups3 = require("@vuu-ui/vuu-popups");
969
+ var import_vuu_utils13 = require("@vuu-ui/vuu-utils");
970
+ var import_react21 = require("react");
971
+
972
+ // src/useDataSource.ts
973
+ var import_vuu_data = require("@vuu-ui/vuu-data");
974
+ var import_vuu_utils8 = require("@vuu-ui/vuu-utils");
975
+ var import_react11 = require("react");
976
+ var { SELECTED: SELECTED2 } = import_vuu_utils8.metadataKeys;
977
+ function useDataSource({
978
+ dataSource,
979
+ onConfigChange,
980
+ onFeatureEnabled,
981
+ onFeatureInvocation,
982
+ onSizeChange,
983
+ onSubscribed,
984
+ range = { from: 0, to: 0 },
985
+ renderBufferSize = 0,
986
+ viewportRowCount
987
+ }) {
988
+ const [, forceUpdate] = (0, import_react11.useState)(null);
989
+ const isMounted = (0, import_react11.useRef)(true);
990
+ const hasUpdated = (0, import_react11.useRef)(false);
991
+ const rangeRef = (0, import_react11.useRef)({ from: 0, to: 0 });
992
+ const rafHandle = (0, import_react11.useRef)(null);
993
+ const data = (0, import_react11.useRef)([]);
994
+ const dataWindow = (0, import_react11.useMemo)(
995
+ () => new MovingWindow((0, import_vuu_utils8.getFullRange)(range)),
996
+ // eslint-disable-next-line react-hooks/exhaustive-deps
997
+ []
998
+ );
999
+ const setData = (0, import_react11.useCallback)(
1000
+ (updates) => {
1001
+ for (const row of updates) {
1002
+ dataWindow.add(row);
1003
+ }
1004
+ data.current = dataWindow.data;
1005
+ hasUpdated.current = true;
1006
+ },
1007
+ [dataWindow]
1008
+ );
1009
+ const datasourceMessageHandler = (0, import_react11.useCallback)(
1010
+ (message) => {
1011
+ if (message.type === "subscribed") {
1012
+ onSubscribed == null ? void 0 : onSubscribed(message);
1013
+ } else if (message.type === "viewport-update") {
1014
+ if (typeof message.size === "number") {
1015
+ onSizeChange == null ? void 0 : onSizeChange(message.size);
1016
+ dataWindow.setRowCount(message.size);
1017
+ }
1018
+ if (message.rows) {
1019
+ setData(message.rows);
1020
+ } else if (typeof message.size === "number") {
1021
+ data.current = dataWindow.data;
1022
+ hasUpdated.current = true;
1023
+ }
1024
+ } else if ((0, import_vuu_data.isVuuFeatureAction)(message)) {
1025
+ onFeatureEnabled == null ? void 0 : onFeatureEnabled(message);
1026
+ } else if ((0, import_vuu_data.isVuuFeatureInvocation)(message)) {
1027
+ onFeatureInvocation == null ? void 0 : onFeatureInvocation(message);
1028
+ } else {
1029
+ console.log(`useDataSource unexpected message ${message.type}`);
1030
+ }
1031
+ },
1032
+ [
1033
+ dataWindow,
1034
+ onFeatureEnabled,
1035
+ onFeatureInvocation,
1036
+ onSizeChange,
1037
+ onSubscribed,
1038
+ setData
1039
+ ]
1040
+ );
1041
+ (0, import_react11.useEffect)(
1042
+ () => () => {
1043
+ if (rafHandle.current) {
1044
+ cancelAnimationFrame(rafHandle.current);
1045
+ rafHandle.current = null;
1046
+ }
1047
+ isMounted.current = false;
1048
+ },
1049
+ []
1050
+ );
1051
+ const refreshIfUpdated = (0, import_react11.useCallback)(() => {
1052
+ if (isMounted.current) {
1053
+ if (hasUpdated.current) {
1054
+ forceUpdate({});
1055
+ hasUpdated.current = false;
1056
+ }
1057
+ rafHandle.current = requestAnimationFrame(refreshIfUpdated);
1058
+ }
1059
+ }, [forceUpdate]);
1060
+ (0, import_react11.useEffect)(() => {
1061
+ rafHandle.current = requestAnimationFrame(refreshIfUpdated);
1062
+ }, [refreshIfUpdated]);
1063
+ const adjustRange = (0, import_react11.useCallback)(
1064
+ (rowCount) => {
1065
+ const { from } = dataSource.range;
1066
+ const rowRange = { from, to: from + rowCount };
1067
+ const fullRange = (0, import_vuu_utils8.getFullRange)(rowRange, renderBufferSize);
1068
+ dataSource.range = rangeRef.current = fullRange;
1069
+ dataSource.emit("range", rowRange);
1070
+ dataWindow.setRange(fullRange);
1071
+ },
1072
+ [dataSource, dataWindow, renderBufferSize]
1073
+ );
1074
+ const setRange = (0, import_react11.useCallback)(
1075
+ (range2) => {
1076
+ const fullRange = (0, import_vuu_utils8.getFullRange)(range2, renderBufferSize);
1077
+ dataSource.range = rangeRef.current = fullRange;
1078
+ dataWindow.setRange(fullRange);
1079
+ dataSource.emit("range", range2);
1080
+ },
1081
+ [dataSource, dataWindow, renderBufferSize]
1082
+ );
1083
+ const getSelectedRows = (0, import_react11.useCallback)(() => {
1084
+ return dataWindow.getSelectedRows();
1085
+ }, [dataWindow]);
1086
+ (0, import_react11.useEffect)(() => {
1087
+ dataSource == null ? void 0 : dataSource.subscribe(
1088
+ {
1089
+ range: rangeRef.current
1090
+ },
1091
+ datasourceMessageHandler
1092
+ );
1093
+ }, [dataSource, datasourceMessageHandler, onConfigChange]);
1094
+ (0, import_react11.useEffect)(() => {
1095
+ adjustRange(viewportRowCount);
1096
+ }, [adjustRange, viewportRowCount]);
1097
+ return {
1098
+ data: data.current,
1099
+ getSelectedRows,
1100
+ range: rangeRef.current,
1101
+ setRange,
1102
+ dataSource
1103
+ };
1104
+ }
1105
+ var MovingWindow = class {
1106
+ constructor({ from, to }) {
1107
+ this.rowCount = 0;
1108
+ this.setRowCount = (rowCount) => {
1109
+ if (rowCount < this.data.length) {
1110
+ this.data.length = rowCount;
1111
+ }
1112
+ this.rowCount = rowCount;
1113
+ };
1114
+ this.range = new import_vuu_utils8.WindowRange(from, to);
1115
+ this.data = new Array(to - from);
1116
+ this.rowCount = 0;
1117
+ }
1118
+ add(data) {
1119
+ var _a;
1120
+ const [index] = data;
1121
+ if (this.isWithinRange(index)) {
1122
+ const internalIndex = index - this.range.from;
1123
+ this.data[internalIndex] = data;
1124
+ const isSelected = data[SELECTED2];
1125
+ const preSelected = (_a = this.data[internalIndex - 1]) == null ? void 0 : _a[SELECTED2];
1126
+ if (preSelected === 0 && isSelected) {
1127
+ this.data[internalIndex - 1][SELECTED2] = 2;
1128
+ } else if (preSelected === 2 && !isSelected) {
1129
+ this.data[internalIndex - 1][SELECTED2] = 0;
1130
+ }
1131
+ }
1132
+ }
1133
+ getAtIndex(index) {
1134
+ return this.range.isWithin(index) && this.data[index - this.range.from] != null ? this.data[index - this.range.from] : void 0;
1135
+ }
1136
+ isWithinRange(index) {
1137
+ return this.range.isWithin(index);
1138
+ }
1139
+ setRange({ from, to }) {
1140
+ if (from !== this.range.from || to !== this.range.to) {
1141
+ const [overlapFrom, overlapTo] = this.range.overlap(from, to);
1142
+ const newData = new Array(to - from);
1143
+ for (let i = overlapFrom; i < overlapTo; i++) {
1144
+ const data = this.getAtIndex(i);
1145
+ if (data) {
1146
+ const index = i - from;
1147
+ newData[index] = data;
1148
+ }
1149
+ }
1150
+ this.data = newData;
1151
+ this.range.from = from;
1152
+ this.range.to = to;
1153
+ }
1154
+ }
1155
+ getSelectedRows() {
1156
+ return this.data.filter((row) => row[SELECTED2] === 1);
1157
+ }
1158
+ };
1159
+
1160
+ // src/useDraggableColumn.ts
1161
+ var import_salt_lab2 = require("@heswell/salt-lab");
1162
+ var import_react12 = require("react");
1163
+ var useDraggableColumn = ({
1164
+ onDrop,
1165
+ tableContainerRef,
1166
+ tableLayout: tableLayoutProp
1167
+ }) => {
1168
+ const [tableLayout, setTableLayout] = (0, import_react12.useState)(tableLayoutProp);
1169
+ const mousePosRef = (0, import_react12.useRef)();
1170
+ const handleDropSettle = (0, import_react12.useCallback)(() => {
1171
+ console.log(`handleDropSettle`);
1172
+ mousePosRef.current = void 0;
1173
+ setTableLayout("row");
1174
+ }, []);
1175
+ const { draggable, draggedItemIndex, onMouseDown } = (0, import_salt_lab2.useDragDrop)({
1176
+ allowDragDrop: true,
1177
+ draggableClassName: "table-column",
1178
+ orientation: "horizontal",
1179
+ containerRef: tableContainerRef,
1180
+ itemQuery: ".vuuTable-table",
1181
+ onDrop,
1182
+ onDropSettle: handleDropSettle
1183
+ });
1184
+ const handleHeaderCellDragStart = (0, import_react12.useCallback)((evt) => {
1185
+ const { clientX, clientY } = evt;
1186
+ console.log(
1187
+ `useDraggableColumn handleHeaderCellDragStart means mouseDown fired on a column in RowBasedTable`
1188
+ );
1189
+ const sourceElement = evt.target;
1190
+ const thElement = sourceElement.closest(".vuuTable-headerCell");
1191
+ const {
1192
+ dataset: { idx = "-1" }
1193
+ } = thElement;
1194
+ mousePosRef.current = {
1195
+ clientX,
1196
+ clientY,
1197
+ idx
1198
+ };
1199
+ setTableLayout("column");
1200
+ }, []);
1201
+ (0, import_react12.useLayoutEffect)(() => {
1202
+ var _a;
1203
+ if (tableLayout === "column" && mousePosRef.current && !draggable) {
1204
+ const { clientX, clientY, idx } = mousePosRef.current;
1205
+ const target = (_a = tableContainerRef.current) == null ? void 0 : _a.querySelector(
1206
+ `.vuuTable-table[data-idx="${idx}"]`
1207
+ );
1208
+ if (target) {
1209
+ const evt = {
1210
+ persist: () => void 0,
1211
+ nativeEvent: {
1212
+ clientX,
1213
+ clientY,
1214
+ target
1215
+ }
1216
+ };
1217
+ onMouseDown == null ? void 0 : onMouseDown(evt);
1218
+ }
1219
+ }
1220
+ }, [draggable, onMouseDown, tableContainerRef, tableLayout]);
1221
+ return {
1222
+ draggable,
1223
+ draggedItemIndex,
1224
+ tableLayout,
1225
+ onHeaderCellDragStart: tableLayout === "row" ? handleHeaderCellDragStart : void 0
1226
+ };
1227
+ };
1228
+
1229
+ // src/useKeyboardNavigation.ts
1230
+ var import_vuu_utils9 = require("@vuu-ui/vuu-utils");
1231
+ var import_react13 = require("react");
1232
+
1233
+ // src/keyUtils.ts
1234
+ function union(set1, ...sets) {
1235
+ const result = new Set(set1);
1236
+ for (let set of sets) {
1237
+ for (let element of set) {
1238
+ result.add(element);
1239
+ }
1240
+ }
1241
+ return result;
1242
+ }
1243
+ var ArrowUp = "ArrowUp";
1244
+ var ArrowDown = "ArrowDown";
1245
+ var ArrowLeft = "ArrowLeft";
1246
+ var ArrowRight = "ArrowRight";
1247
+ var Home = "Home";
1248
+ var End = "End";
1249
+ var PageUp = "PageUp";
1250
+ var PageDown = "PageDown";
1251
+ var actionKeys = /* @__PURE__ */ new Set(["Enter", "Delete", " "]);
1252
+ var focusKeys = /* @__PURE__ */ new Set(["Tab"]);
1253
+ var arrowLeftRightKeys = /* @__PURE__ */ new Set(["ArrowRight", "ArrowLeft"]);
1254
+ var navigationKeys = /* @__PURE__ */ new Set([
1255
+ Home,
1256
+ End,
1257
+ PageUp,
1258
+ PageDown,
1259
+ ArrowDown,
1260
+ ArrowLeft,
1261
+ ArrowRight,
1262
+ ArrowUp
1263
+ ]);
1264
+ var functionKeys = /* @__PURE__ */ new Set([
1265
+ "F1",
1266
+ "F2",
1267
+ "F3",
1268
+ "F4",
1269
+ "F5",
1270
+ "F6",
1271
+ "F7",
1272
+ "F8",
1273
+ "F9",
1274
+ "F10",
1275
+ "F11",
1276
+ "F12"
1277
+ ]);
1278
+ var specialKeys = union(
1279
+ actionKeys,
1280
+ navigationKeys,
1281
+ arrowLeftRightKeys,
1282
+ functionKeys,
1283
+ focusKeys
1284
+ );
1285
+ var PageKeys = ["Home", "End", "PageUp", "PageDown"];
1286
+ var isPagingKey = (key) => PageKeys.includes(key);
1287
+ var isNavigationKey = (key) => {
1288
+ return navigationKeys.has(key);
1289
+ };
1290
+
1291
+ // src/useKeyboardNavigation.ts
1292
+ var headerCellQuery = (colIdx) => `thead th:nth-child(${colIdx + 1})`;
1293
+ var dataCellQuery = (rowIdx, colIdx) => `tbody > tr[aria-rowindex='${rowIdx}'] > td:nth-child(${colIdx + 1})`;
1294
+ var NULL_CELL_POS = [-1, -1];
1295
+ function nextCellPos(key, [rowIdx, colIdx], columnCount, rowCount) {
1296
+ if (key === ArrowUp) {
1297
+ if (rowIdx > -1) {
1298
+ return [rowIdx - 1, colIdx];
1299
+ } else {
1300
+ return [rowIdx, colIdx];
1301
+ }
1302
+ } else if (key === ArrowDown) {
1303
+ if (rowIdx === -1) {
1304
+ return [0, colIdx];
1305
+ } else if (rowIdx === rowCount - 1) {
1306
+ return [rowIdx, colIdx];
1307
+ } else {
1308
+ return [rowIdx + 1, colIdx];
1309
+ }
1310
+ } else if (key === ArrowRight) {
1311
+ if (colIdx < columnCount - 1) {
1312
+ return [rowIdx, colIdx + 1];
1313
+ } else {
1314
+ return [rowIdx, colIdx];
1315
+ }
1316
+ } else if (key === ArrowLeft) {
1317
+ if (colIdx > 0) {
1318
+ return [rowIdx, colIdx - 1];
1319
+ } else {
1320
+ return [rowIdx, colIdx];
1321
+ }
1322
+ }
1323
+ return [rowIdx, colIdx];
1324
+ }
1325
+ var useKeyboardNavigation = ({
1326
+ columnCount = 0,
1327
+ containerRef,
1328
+ disableHighlightOnFocus,
1329
+ data,
1330
+ requestScroll,
1331
+ rowCount = 0,
1332
+ viewportRange
1333
+ }) => {
1334
+ var _a;
1335
+ const { from: viewportFirstRow, to: viewportLastRow } = viewportRange;
1336
+ const focusedCellPos = (0, import_react13.useRef)([-1, -1]);
1337
+ const focusableCell = (0, import_react13.useRef)();
1338
+ const activeCellPos = (0, import_react13.useRef)([-1, 0]);
1339
+ const getTableCell = (0, import_react13.useCallback)(
1340
+ ([rowIdx, colIdx]) => {
1341
+ var _a2;
1342
+ const cssQuery = rowIdx === -1 ? headerCellQuery(colIdx) : dataCellQuery(rowIdx, colIdx);
1343
+ return (_a2 = containerRef.current) == null ? void 0 : _a2.querySelector(
1344
+ cssQuery
1345
+ );
1346
+ },
1347
+ [containerRef]
1348
+ );
1349
+ const getFocusedCell = (element) => element == null ? void 0 : element.closest("th,td");
1350
+ const getTableCellPos = (tableCell) => {
1351
+ var _a2, _b;
1352
+ if (tableCell.tagName === "TH") {
1353
+ const colIdx = parseInt((_a2 = tableCell.dataset.idx) != null ? _a2 : "-1", 10);
1354
+ return [-1, colIdx];
1355
+ } else {
1356
+ const focusedRow = tableCell.closest("tr");
1357
+ if (focusedRow) {
1358
+ const rowIdx = parseInt((_b = focusedRow.ariaRowIndex) != null ? _b : "-1", 10);
1359
+ const colIdx = Array.from(focusedRow.childNodes).indexOf(tableCell);
1360
+ return [rowIdx, colIdx];
1361
+ }
1362
+ }
1363
+ return NULL_CELL_POS;
1364
+ };
1365
+ const focusCell = (0, import_react13.useCallback)(
1366
+ (cellPos) => {
1367
+ var _a2;
1368
+ if (containerRef.current) {
1369
+ const activeCell = getTableCell(cellPos);
1370
+ if (activeCell) {
1371
+ if (activeCell !== focusableCell.current) {
1372
+ (_a2 = focusableCell.current) == null ? void 0 : _a2.setAttribute("tabindex", "");
1373
+ focusableCell.current = activeCell;
1374
+ activeCell.setAttribute("tabindex", "0");
1375
+ }
1376
+ activeCell.focus();
1377
+ } else if (!(0, import_vuu_utils9.withinRange)(cellPos[0], viewportRange)) {
1378
+ focusableCell.current = void 0;
1379
+ requestScroll == null ? void 0 : requestScroll({ type: "scroll-page", direction: "up" });
1380
+ }
1381
+ }
1382
+ },
1383
+ // TODO we recreate this function whenever viewportRange changes, which will
1384
+ // be often whilst scrolling - store range in a a ref ?
1385
+ [containerRef, getTableCell, requestScroll, viewportRange]
1386
+ );
1387
+ const setActiveCell = (0, import_react13.useCallback)(
1388
+ (rowIdx, colIdx, fromKeyboard = false) => {
1389
+ const pos = [rowIdx, colIdx];
1390
+ activeCellPos.current = pos;
1391
+ focusCell(pos);
1392
+ if (fromKeyboard) {
1393
+ focusedCellPos.current = pos;
1394
+ }
1395
+ },
1396
+ [focusCell]
1397
+ );
1398
+ const virtualizeActiveCell = (0, import_react13.useCallback)(() => {
1399
+ var _a2;
1400
+ (_a2 = focusableCell.current) == null ? void 0 : _a2.setAttribute("tabindex", "");
1401
+ focusableCell.current = void 0;
1402
+ }, []);
1403
+ const nextPageItemIdx = (0, import_react13.useCallback)(
1404
+ async (key, cellPos) => {
1405
+ switch (key) {
1406
+ case PageDown:
1407
+ requestScroll == null ? void 0 : requestScroll({ type: "scroll-page", direction: "down" });
1408
+ break;
1409
+ case PageUp:
1410
+ requestScroll == null ? void 0 : requestScroll({ type: "scroll-page", direction: "up" });
1411
+ break;
1412
+ case Home:
1413
+ requestScroll == null ? void 0 : requestScroll({ type: "scroll-end", direction: "home" });
1414
+ break;
1415
+ case End:
1416
+ requestScroll == null ? void 0 : requestScroll({ type: "scroll-end", direction: "end" });
1417
+ break;
1418
+ }
1419
+ return cellPos;
1420
+ },
1421
+ [requestScroll]
1422
+ );
1423
+ const handleFocus = (0, import_react13.useCallback)(() => {
1424
+ var _a2;
1425
+ if (disableHighlightOnFocus !== true) {
1426
+ if ((_a2 = containerRef.current) == null ? void 0 : _a2.contains(document.activeElement)) {
1427
+ const focusedCell = getFocusedCell(document.activeElement);
1428
+ if (focusedCell) {
1429
+ focusedCellPos.current = getTableCellPos(focusedCell);
1430
+ }
1431
+ }
1432
+ }
1433
+ }, [disableHighlightOnFocus, containerRef]);
1434
+ const navigateChildItems = (0, import_react13.useCallback)(
1435
+ async (key) => {
1436
+ const [nextRowIdx, nextColIdx] = isPagingKey(key) ? await nextPageItemIdx(key, activeCellPos.current) : nextCellPos(key, activeCellPos.current, columnCount, rowCount);
1437
+ const [rowIdx, colIdx] = activeCellPos.current;
1438
+ if (nextRowIdx !== rowIdx || nextColIdx !== colIdx) {
1439
+ setActiveCell(nextRowIdx, nextColIdx, true);
1440
+ }
1441
+ },
1442
+ [columnCount, nextPageItemIdx, rowCount, setActiveCell]
1443
+ );
1444
+ const handleKeyDown = (0, import_react13.useCallback)(
1445
+ (e) => {
1446
+ if (data.length > 0 && isNavigationKey(e.key)) {
1447
+ e.preventDefault();
1448
+ e.stopPropagation();
1449
+ void navigateChildItems(e.key);
1450
+ }
1451
+ },
1452
+ [data, navigateChildItems]
1453
+ );
1454
+ const handleClick = (0, import_react13.useCallback)(
1455
+ // Might not be a cell e.g the Settings button
1456
+ (evt) => {
1457
+ const target = evt.target;
1458
+ const focusedCell = getFocusedCell(target);
1459
+ if (focusedCell) {
1460
+ const [rowIdx, colIdx] = getTableCellPos(focusedCell);
1461
+ setActiveCell(rowIdx, colIdx);
1462
+ }
1463
+ },
1464
+ [setActiveCell]
1465
+ );
1466
+ const containerProps = (0, import_react13.useMemo)(() => {
1467
+ return {
1468
+ onClick: handleClick,
1469
+ onFocus: handleFocus,
1470
+ onKeyDown: handleKeyDown
1471
+ };
1472
+ }, [handleClick, handleFocus, handleKeyDown]);
1473
+ (0, import_react13.useLayoutEffect)(() => {
1474
+ const { current: cellPos } = activeCellPos;
1475
+ const withinViewport = cellPos[0] >= viewportFirstRow && cellPos[0] <= viewportLastRow;
1476
+ if (focusableCell.current && !withinViewport) {
1477
+ virtualizeActiveCell();
1478
+ } else if (!focusableCell.current && withinViewport) {
1479
+ focusCell(cellPos);
1480
+ }
1481
+ }, [focusCell, viewportFirstRow, viewportLastRow, virtualizeActiveCell]);
1482
+ const fullyRendered = ((_a = containerRef.current) == null ? void 0 : _a.firstChild) != null;
1483
+ (0, import_react13.useEffect)(() => {
1484
+ var _a2;
1485
+ if (fullyRendered && focusableCell.current === void 0) {
1486
+ const headerCell = (_a2 = containerRef.current) == null ? void 0 : _a2.querySelector(
1487
+ headerCellQuery(0)
1488
+ );
1489
+ if (headerCell) {
1490
+ headerCell.setAttribute("tabindex", "0");
1491
+ focusableCell.current = headerCell;
1492
+ }
1493
+ }
1494
+ }, [containerRef, fullyRendered]);
1495
+ return containerProps;
1496
+ };
1497
+
1498
+ // src/useMeasuredContainer.ts
1499
+ var import_react15 = require("react");
1500
+
1501
+ // src/useResizeObserver.ts
1502
+ var import_react14 = require("react");
1503
+ var observedMap = /* @__PURE__ */ new Map();
1504
+ var getTargetSize = (element, size, dimension) => {
1505
+ switch (dimension) {
1506
+ case "height":
1507
+ return size.height;
1508
+ case "clientHeight":
1509
+ return element.clientHeight;
1510
+ case "clientWidth":
1511
+ return element.clientWidth;
1512
+ case "contentHeight":
1513
+ return size.contentHeight;
1514
+ case "contentWidth":
1515
+ return size.contentWidth;
1516
+ case "scrollHeight":
1517
+ return Math.ceil(element.scrollHeight);
1518
+ case "scrollWidth":
1519
+ return Math.ceil(element.scrollWidth);
1520
+ case "width":
1521
+ return size.width;
1522
+ default:
1523
+ return 0;
1524
+ }
1525
+ };
1526
+ var resizeObserver = new ResizeObserver((entries) => {
1527
+ for (const entry of entries) {
1528
+ const { target, borderBoxSize, contentBoxSize } = entry;
1529
+ const observedTarget = observedMap.get(target);
1530
+ if (observedTarget) {
1531
+ const [{ blockSize: height, inlineSize: width }] = borderBoxSize;
1532
+ const [{ blockSize: contentHeight, inlineSize: contentWidth }] = contentBoxSize;
1533
+ const { onResize, measurements } = observedTarget;
1534
+ let sizeChanged = false;
1535
+ for (const [dimension, size] of Object.entries(measurements)) {
1536
+ const newSize = getTargetSize(
1537
+ target,
1538
+ { height, width, contentHeight, contentWidth },
1539
+ dimension
1540
+ );
1541
+ if (newSize !== size) {
1542
+ sizeChanged = true;
1543
+ measurements[dimension] = newSize;
1544
+ }
1545
+ }
1546
+ if (sizeChanged) {
1547
+ onResize && onResize(measurements);
1548
+ }
1549
+ }
1550
+ }
1551
+ });
1552
+ function useResizeObserver(ref, dimensions, onResize, reportInitialSize = false) {
1553
+ const dimensionsRef = (0, import_react14.useRef)(dimensions);
1554
+ const measure = (0, import_react14.useCallback)((target) => {
1555
+ const { width, height } = target.getBoundingClientRect();
1556
+ const { clientWidth: contentWidth, clientHeight: contentHeight } = target;
1557
+ return dimensionsRef.current.reduce(
1558
+ (map, dim) => {
1559
+ map[dim] = getTargetSize(
1560
+ target,
1561
+ { width, height, contentHeight, contentWidth },
1562
+ dim
1563
+ );
1564
+ return map;
1565
+ },
1566
+ {}
1567
+ );
1568
+ }, []);
1569
+ (0, import_react14.useEffect)(() => {
1570
+ const target = ref.current;
1571
+ async function registerObserver() {
1572
+ observedMap.set(target, { measurements: {} });
1573
+ await document.fonts.ready;
1574
+ const observedTarget = observedMap.get(target);
1575
+ if (observedTarget) {
1576
+ const measurements = measure(target);
1577
+ observedTarget.measurements = measurements;
1578
+ resizeObserver.observe(target);
1579
+ if (reportInitialSize) {
1580
+ onResize(measurements);
1581
+ }
1582
+ } else {
1583
+ console.log(
1584
+ `%cuseResizeObserver an target expected to be under observation wa snot found. This warrants investigation`,
1585
+ "font-weight:bold; color:red;"
1586
+ );
1587
+ }
1588
+ }
1589
+ if (target) {
1590
+ if (observedMap.has(target)) {
1591
+ throw Error(
1592
+ "useResizeObserver attemping to observe same element twice"
1593
+ );
1594
+ }
1595
+ registerObserver();
1596
+ }
1597
+ return () => {
1598
+ if (target && observedMap.has(target)) {
1599
+ resizeObserver.unobserve(target);
1600
+ observedMap.delete(target);
1601
+ }
1602
+ };
1603
+ }, [measure, ref]);
1604
+ (0, import_react14.useEffect)(() => {
1605
+ const target = ref.current;
1606
+ const record = observedMap.get(target);
1607
+ if (record) {
1608
+ if (dimensionsRef.current !== dimensions) {
1609
+ dimensionsRef.current = dimensions;
1610
+ const measurements = measure(target);
1611
+ record.measurements = measurements;
1612
+ }
1613
+ record.onResize = onResize;
1614
+ }
1615
+ }, [dimensions, measure, ref, onResize]);
1616
+ }
1617
+
1618
+ // src/useMeasuredContainer.ts
1619
+ var ClientWidthHeight = ["clientHeight", "clientWidth"];
1620
+ var isNumber = (val) => Number.isFinite(val);
1621
+ var useMeasuredContainer = ({
1622
+ defaultHeight = 0,
1623
+ defaultWidth = 0,
1624
+ height,
1625
+ width
1626
+ }) => {
1627
+ const containerRef = (0, import_react15.useRef)(null);
1628
+ const [size, setSize] = (0, import_react15.useState)({
1629
+ outer: {
1630
+ height: height != null ? height : "100%",
1631
+ width: width != null ? width : "100%"
1632
+ }
1633
+ });
1634
+ const onResize = (0, import_react15.useCallback)(
1635
+ ({ clientWidth, clientHeight }) => {
1636
+ setSize((currentSize) => {
1637
+ const { inner, outer } = currentSize;
1638
+ return isNumber(clientHeight) && isNumber(clientWidth) && (clientWidth !== (inner == null ? void 0 : inner.width) || clientHeight !== (inner == null ? void 0 : inner.height)) ? {
1639
+ outer,
1640
+ inner: {
1641
+ width: Math.floor(clientWidth) || defaultWidth,
1642
+ height: Math.floor(clientHeight) || defaultHeight
1643
+ }
1644
+ } : currentSize;
1645
+ });
1646
+ },
1647
+ [defaultHeight, defaultWidth]
1648
+ );
1649
+ useResizeObserver(containerRef, ClientWidthHeight, onResize, true);
1650
+ return {
1651
+ containerRef,
1652
+ outerSize: size.outer,
1653
+ innerSize: size.inner
1654
+ };
1655
+ };
1656
+
1657
+ // src/useSelection.ts
1658
+ var import_vuu_utils10 = require("@vuu-ui/vuu-utils");
1659
+ var import_react16 = require("react");
1660
+ var { IDX: IDX2, SELECTED: SELECTED3 } = import_vuu_utils10.metadataKeys;
1661
+ var NO_SELECTION = [];
1662
+ var useSelection = ({
1663
+ selectionModel,
1664
+ onSelectionChange
1665
+ }) => {
1666
+ selectionModel === "extended" || selectionModel === "checkbox";
1667
+ const lastActiveRef = (0, import_react16.useRef)(-1);
1668
+ const selectedRef = (0, import_react16.useRef)(NO_SELECTION);
1669
+ const handleSelectionChange = (0, import_react16.useCallback)(
1670
+ (row, rangeSelect, keepExistingSelection) => {
1671
+ const { [IDX2]: idx, [SELECTED3]: isSelected } = row;
1672
+ const { current: active } = lastActiveRef;
1673
+ const { current: selected } = selectedRef;
1674
+ const selectOperation = isSelected ? import_vuu_utils10.deselectItem : import_vuu_utils10.selectItem;
1675
+ const newSelected = selectOperation(
1676
+ selectionModel,
1677
+ selected,
1678
+ idx,
1679
+ rangeSelect,
1680
+ keepExistingSelection,
1681
+ active
1682
+ );
1683
+ selectedRef.current = newSelected;
1684
+ lastActiveRef.current = idx;
1685
+ if (onSelectionChange) {
1686
+ onSelectionChange(newSelected);
1687
+ }
1688
+ },
1689
+ [onSelectionChange, selectionModel]
1690
+ );
1691
+ return handleSelectionChange;
1692
+ };
1693
+
1694
+ // src/useTableModel.ts
1695
+ var import_salt_lab3 = require("@heswell/salt-lab");
1696
+ var import_vuu_utils11 = require("@vuu-ui/vuu-utils");
1697
+ var import_react17 = require("react");
1698
+ var { info } = (0, import_vuu_utils11.logger)("useTableModel");
1699
+ var DEFAULT_COLUMN_WIDTH = 100;
1700
+ var KEY_OFFSET = import_vuu_utils11.metadataKeys.count;
1701
+ var columnWithoutDataType = ({ serverDataType }) => serverDataType === void 0;
1702
+ var getCellRendererForColumn = (column) => {
1703
+ var _a, _b;
1704
+ if ((0, import_vuu_utils11.isTypeDescriptor)(column.type)) {
1705
+ return (0, import_vuu_utils11.getCellRenderer)((_b = (_a = column.type) == null ? void 0 : _a.renderer) == null ? void 0 : _b.name);
1706
+ }
1707
+ };
1708
+ var getDataType = (column, columnNames, dataTypes) => {
1709
+ var _a;
1710
+ const index = columnNames.indexOf(column.name);
1711
+ if (index !== -1 && dataTypes[index]) {
1712
+ return dataTypes[index];
1713
+ } else {
1714
+ return (_a = column.serverDataType) != null ? _a : "string";
1715
+ }
1716
+ };
1717
+ var numericTypes = ["int", "long", "double"];
1718
+ var getDefaultAlignment = (serverDataType) => serverDataType === void 0 ? void 0 : numericTypes.includes(serverDataType) ? "right" : "left";
1719
+ var columnReducer = (state, action) => {
1720
+ info == null ? void 0 : info(`GridModelReducer ${action.type}`);
1721
+ switch (action.type) {
1722
+ case "init":
1723
+ return init(action);
1724
+ case "moveColumn":
1725
+ return moveColumn(state, action);
1726
+ case "resizeColumn":
1727
+ return resizeColumn(state, action);
1728
+ case "setTypes":
1729
+ return setTypes(state, action);
1730
+ case "hideColumns":
1731
+ return hideColumns(state, action);
1732
+ case "showColumns":
1733
+ return showColumns(state, action);
1734
+ case "pinColumn":
1735
+ return pinColumn2(state, action);
1736
+ case "updateColumnProp":
1737
+ return updateColumnProp(state, action);
1738
+ case "tableConfig":
1739
+ return updateTableConfig(state, action);
1740
+ default:
1741
+ console.log(`unhandled action ${action.type}`);
1742
+ return state;
1743
+ }
1744
+ };
1745
+ var useTableModel = (tableConfig, dataSourceConfig) => {
1746
+ const [state, dispatchColumnAction] = (0, import_react17.useReducer)(columnReducer, { tableConfig, dataSourceConfig }, init);
1747
+ return {
1748
+ columns: state.columns,
1749
+ dispatchColumnAction,
1750
+ headings: state.headings
1751
+ };
1752
+ };
1753
+ function init({ dataSourceConfig, tableConfig }) {
1754
+ const columns = tableConfig.columns.map(
1755
+ toKeyedColumWithDefaults(tableConfig)
1756
+ );
1757
+ const maybePinnedColumns = columns.some(import_vuu_utils11.isPinned) ? (0, import_vuu_utils11.sortPinnedColumns)(columns) : columns;
1758
+ const state = {
1759
+ columns: maybePinnedColumns,
1760
+ headings: (0, import_vuu_utils11.getTableHeadings)(maybePinnedColumns)
1761
+ };
1762
+ if (dataSourceConfig) {
1763
+ const { columns: columns2, ...rest } = dataSourceConfig;
1764
+ return updateTableConfig(state, {
1765
+ type: "tableConfig",
1766
+ ...rest
1767
+ });
1768
+ } else {
1769
+ return state;
1770
+ }
1771
+ }
1772
+ var getLabel = (label, columnFormatHeader) => {
1773
+ if (columnFormatHeader === "uppercase") {
1774
+ return label.toUpperCase();
1775
+ } else if (columnFormatHeader === "capitalize") {
1776
+ return label[0].toUpperCase() + label.slice(1).toLowerCase();
1777
+ }
1778
+ return label;
1779
+ };
1780
+ var toKeyedColumWithDefaults = (options) => (column, index) => {
1781
+ const { columnDefaultWidth = DEFAULT_COLUMN_WIDTH, columnFormatHeader } = options;
1782
+ const {
1783
+ align = getDefaultAlignment(column.serverDataType),
1784
+ key,
1785
+ name,
1786
+ label = name,
1787
+ width = columnDefaultWidth,
1788
+ ...rest
1789
+ } = column;
1790
+ const keyedColumnWithDefaults = {
1791
+ ...rest,
1792
+ align,
1793
+ CellRenderer: getCellRendererForColumn(column),
1794
+ label: getLabel(label, columnFormatHeader),
1795
+ key: key != null ? key : index + KEY_OFFSET,
1796
+ name,
1797
+ originalIdx: index,
1798
+ valueFormatter: (0, import_vuu_utils11.getValueFormatter)(column),
1799
+ width
1800
+ };
1801
+ if ((0, import_vuu_utils11.isGroupColumn)(keyedColumnWithDefaults)) {
1802
+ keyedColumnWithDefaults.columns = keyedColumnWithDefaults.columns.map(
1803
+ (col) => toKeyedColumWithDefaults(options)(col, col.key)
1804
+ );
1805
+ }
1806
+ return keyedColumnWithDefaults;
1807
+ };
1808
+ function moveColumn(state, { column, moveBy, moveTo }) {
1809
+ const { columns } = state;
1810
+ if (typeof moveBy === "number") {
1811
+ const idx = columns.indexOf(column);
1812
+ const newColumns = columns.slice();
1813
+ const [movedColumns] = newColumns.splice(idx, 1);
1814
+ newColumns.splice(idx + moveBy, 0, movedColumns);
1815
+ return {
1816
+ ...state,
1817
+ columns: newColumns
1818
+ };
1819
+ } else if (typeof moveTo === "number") {
1820
+ const index = columns.indexOf(column);
1821
+ return {
1822
+ ...state,
1823
+ columns: (0, import_salt_lab3.moveItem)(columns, index, moveTo)
1824
+ };
1825
+ }
1826
+ return state;
1827
+ }
1828
+ function hideColumns(state, { columns }) {
1829
+ if (columns.some((col) => col.hidden !== true)) {
1830
+ return columns.reduce((s, c) => {
1831
+ if (c.hidden !== true) {
1832
+ return updateColumnProp(s, {
1833
+ type: "updateColumnProp",
1834
+ column: c,
1835
+ hidden: true
1836
+ });
1837
+ } else {
1838
+ return s;
1839
+ }
1840
+ }, state);
1841
+ } else {
1842
+ return state;
1843
+ }
1844
+ }
1845
+ function showColumns(state, { columns }) {
1846
+ if (columns.some((col) => col.hidden)) {
1847
+ return columns.reduce((s, c) => {
1848
+ if (c.hidden) {
1849
+ return updateColumnProp(s, {
1850
+ type: "updateColumnProp",
1851
+ column: c,
1852
+ hidden: false
1853
+ });
1854
+ } else {
1855
+ return s;
1856
+ }
1857
+ }, state);
1858
+ } else {
1859
+ return state;
1860
+ }
1861
+ }
1862
+ function resizeColumn(state, { column, phase, width }) {
1863
+ const type = "updateColumnProp";
1864
+ const resizing = phase !== "end";
1865
+ switch (phase) {
1866
+ case "begin":
1867
+ case "end":
1868
+ return updateColumnProp(state, { type, column, resizing });
1869
+ case "resize":
1870
+ return updateColumnProp(state, { type, column, width });
1871
+ default:
1872
+ throw Error(`useTableModel.resizeColumn, invalid resizePhase ${phase}`);
1873
+ }
1874
+ }
1875
+ function setTypes(state, { columnNames, serverDataTypes }) {
1876
+ const { columns } = state;
1877
+ if (columns.some(columnWithoutDataType)) {
1878
+ const cols = columns.map((column) => {
1879
+ var _a;
1880
+ const serverDataType = getDataType(column, columnNames, serverDataTypes);
1881
+ return {
1882
+ ...column,
1883
+ align: (_a = column.align) != null ? _a : getDefaultAlignment(serverDataType),
1884
+ serverDataType
1885
+ };
1886
+ });
1887
+ return {
1888
+ ...state,
1889
+ columns: cols
1890
+ };
1891
+ } else {
1892
+ return state;
1893
+ }
1894
+ }
1895
+ function pinColumn2(state, action) {
1896
+ let { columns } = state;
1897
+ const { column, pin } = action;
1898
+ const targetColumn = columns.find((col) => col.name === column.name);
1899
+ if (targetColumn) {
1900
+ columns = replaceColumn(columns, { ...targetColumn, pin });
1901
+ columns = (0, import_vuu_utils11.sortPinnedColumns)(columns);
1902
+ return {
1903
+ ...state,
1904
+ columns
1905
+ };
1906
+ } else {
1907
+ return state;
1908
+ }
1909
+ }
1910
+ function updateColumnProp(state, action) {
1911
+ let { columns } = state;
1912
+ const { align, column, hidden, label, resizing, width } = action;
1913
+ const targetColumn = columns.find((col) => col.name === column.name);
1914
+ if (targetColumn) {
1915
+ if (align === "left" || align === "right") {
1916
+ columns = replaceColumn(columns, { ...targetColumn, align });
1917
+ }
1918
+ if (typeof label === "string") {
1919
+ columns = replaceColumn(columns, { ...targetColumn, label });
1920
+ }
1921
+ if (typeof resizing === "boolean") {
1922
+ columns = replaceColumn(columns, { ...targetColumn, resizing });
1923
+ }
1924
+ if (typeof hidden === "boolean") {
1925
+ columns = replaceColumn(columns, { ...targetColumn, hidden });
1926
+ }
1927
+ if (typeof width === "number") {
1928
+ columns = replaceColumn(columns, { ...targetColumn, width });
1929
+ }
1930
+ }
1931
+ return {
1932
+ ...state,
1933
+ columns
1934
+ };
1935
+ }
1936
+ function updateTableConfig(state, { columns, confirmed, filter, groupBy, sort }) {
1937
+ const hasColumns = columns && columns.length > 0;
1938
+ const hasGroupBy = groupBy !== void 0;
1939
+ const hasFilter = typeof (filter == null ? void 0 : filter.filter) === "string";
1940
+ const hasSort = sort && sort.sortDefs.length > 0;
1941
+ let result = state;
1942
+ if (hasColumns) {
1943
+ result = {
1944
+ ...state,
1945
+ columns: columns.map((colName, index) => {
1946
+ const columnName = (0, import_vuu_utils11.getColumnName)(colName);
1947
+ const key = index + KEY_OFFSET;
1948
+ const col = (0, import_vuu_utils11.findColumn)(result.columns, columnName);
1949
+ if (col) {
1950
+ if (col.key === key) {
1951
+ return col;
1952
+ } else {
1953
+ return {
1954
+ ...col,
1955
+ key
1956
+ };
1957
+ }
1958
+ }
1959
+ throw Error(`useTableModel column ${colName} not found`);
1960
+ })
1961
+ };
1962
+ }
1963
+ if (hasGroupBy) {
1964
+ result = {
1965
+ ...state,
1966
+ columns: (0, import_vuu_utils11.applyGroupByToColumns)(result.columns, groupBy, confirmed)
1967
+ };
1968
+ }
1969
+ if (hasSort) {
1970
+ result = {
1971
+ ...state,
1972
+ columns: (0, import_vuu_utils11.applySortToColumns)(result.columns, sort)
1973
+ };
1974
+ }
1975
+ if (hasFilter) {
1976
+ result = {
1977
+ ...state,
1978
+ columns: (0, import_vuu_utils11.applyFilterToColumns)(result.columns, filter)
1979
+ };
1980
+ } else if (result.columns.some(import_vuu_utils11.isFilteredColumn)) {
1981
+ result = {
1982
+ ...state,
1983
+ columns: (0, import_vuu_utils11.stripFilterFromColumns)(result.columns)
1984
+ };
1985
+ }
1986
+ return result;
1987
+ }
1988
+ function replaceColumn(state, column) {
1989
+ return state.map((col) => col.name === column.name ? column : col);
1990
+ }
1991
+
1992
+ // src/useTableScroll.ts
1993
+ var import_react18 = require("react");
1994
+ var getPctScroll = (container) => {
1995
+ const { scrollLeft, scrollTop } = container;
1996
+ const { clientHeight, clientWidth, scrollHeight, scrollWidth } = container;
1997
+ const pctScrollLeft = scrollLeft / (scrollWidth - clientWidth);
1998
+ const pctScrollTop = scrollTop / (scrollHeight - clientHeight);
1999
+ return [pctScrollLeft, pctScrollTop, scrollLeft, scrollTop];
2000
+ };
2001
+ var getMaxScroll = (container) => {
2002
+ const { clientHeight, clientWidth, scrollHeight, scrollWidth } = container;
2003
+ return [scrollWidth - clientWidth, scrollHeight - clientHeight];
2004
+ };
2005
+ var useTableScroll = ({
2006
+ onHorizontalScroll,
2007
+ onVerticalScroll,
2008
+ viewport
2009
+ }) => {
2010
+ const scrollPosRef = (0, import_react18.useRef)({ scrollTop: 0, scrollLeft: 0 });
2011
+ const scrollbarContainerRef = (0, import_react18.useRef)(null);
2012
+ const contentContainerRef = (0, import_react18.useRef)(null);
2013
+ const tableContainerRef = (0, import_react18.useRef)(null);
2014
+ const contentContainerScrolledRef = (0, import_react18.useRef)(false);
2015
+ const {
2016
+ maxScrollContainerScrollHorizontal: maxScrollLeft,
2017
+ maxScrollContainerScrollVertical: maxScrollTop
2018
+ } = viewport;
2019
+ const scrollTable = (0, import_react18.useCallback)(
2020
+ (scrollLeft, scrollTop) => {
2021
+ const { current: tableContainer } = tableContainerRef;
2022
+ if (tableContainer) {
2023
+ tableContainer.scrollTo({
2024
+ top: scrollTop,
2025
+ left: scrollLeft,
2026
+ behavior: "auto"
2027
+ });
2028
+ }
2029
+ },
2030
+ [tableContainerRef]
2031
+ );
2032
+ const handleTableContainerScroll = (0, import_react18.useCallback)(() => {
2033
+ const { current: tableContainer } = tableContainerRef;
2034
+ if (tableContainer) {
2035
+ const { current: scrollPos } = scrollPosRef;
2036
+ const { scrollLeft, scrollTop } = tableContainer;
2037
+ if (scrollPos.scrollTop !== scrollTop) {
2038
+ scrollPos.scrollTop = scrollTop;
2039
+ onVerticalScroll == null ? void 0 : onVerticalScroll(scrollTop);
2040
+ }
2041
+ if (scrollPos.scrollLeft !== scrollLeft) {
2042
+ scrollPos.scrollLeft = scrollLeft;
2043
+ onHorizontalScroll == null ? void 0 : onHorizontalScroll(scrollLeft);
2044
+ }
2045
+ }
2046
+ }, [onHorizontalScroll, onVerticalScroll]);
2047
+ const handleContentContainerScroll = (0, import_react18.useCallback)(() => {
2048
+ const { current: rootContainer } = contentContainerRef;
2049
+ const { current: scrollContainer } = scrollbarContainerRef;
2050
+ if (rootContainer && scrollContainer) {
2051
+ const [pctScrollLeft, pctScrollTop, scrollLeft, scrollTop] = getPctScroll(rootContainer);
2052
+ contentContainerScrolledRef.current = true;
2053
+ scrollContainer.scrollLeft = Math.round(pctScrollLeft * maxScrollLeft);
2054
+ scrollContainer.scrollTop = Math.round(pctScrollTop * maxScrollTop);
2055
+ scrollTable(scrollLeft, scrollTop);
2056
+ }
2057
+ }, [
2058
+ maxScrollLeft,
2059
+ maxScrollTop,
2060
+ contentContainerRef,
2061
+ scrollbarContainerRef,
2062
+ scrollTable
2063
+ ]);
2064
+ const handleScrollbarContainerScroll = (0, import_react18.useCallback)(() => {
2065
+ const { current: contentContainer } = contentContainerRef;
2066
+ const { current: scrollbarContainer } = scrollbarContainerRef;
2067
+ const { current: contentContainerScrolled } = contentContainerScrolledRef;
2068
+ if (contentContainerScrolled) {
2069
+ contentContainerScrolledRef.current = false;
2070
+ } else if (contentContainer && scrollbarContainer) {
2071
+ const [pctScrollLeft, pctScrollTop] = getPctScroll(scrollbarContainer);
2072
+ const [maxScrollLeft2, maxScrollTop2] = getMaxScroll(contentContainer);
2073
+ const rootScrollLeft = Math.round(pctScrollLeft * maxScrollLeft2);
2074
+ const rootScrollTop = Math.round(pctScrollTop * maxScrollTop2);
2075
+ contentContainer.scrollTo({
2076
+ left: rootScrollLeft,
2077
+ top: rootScrollTop,
2078
+ behavior: "auto"
2079
+ });
2080
+ scrollTable(rootScrollLeft, rootScrollTop);
2081
+ }
2082
+ }, [contentContainerRef, scrollbarContainerRef, scrollTable]);
2083
+ const requestScroll = (0, import_react18.useCallback)(
2084
+ (scrollRequest) => {
2085
+ const { current: scrollbarContainer } = scrollbarContainerRef;
2086
+ if (scrollbarContainer) {
2087
+ contentContainerScrolledRef.current = false;
2088
+ if (scrollRequest.type === "scroll-page") {
2089
+ const { clientHeight, scrollLeft, scrollTop } = scrollbarContainer;
2090
+ const { direction } = scrollRequest;
2091
+ const scrollBy = direction === "down" ? clientHeight : -clientHeight;
2092
+ const newScrollTop = Math.min(
2093
+ Math.max(0, scrollTop + scrollBy),
2094
+ viewport.maxScrollContainerScrollVertical
2095
+ );
2096
+ scrollbarContainer.scrollTo({
2097
+ top: newScrollTop,
2098
+ left: scrollLeft,
2099
+ behavior: "auto"
2100
+ });
2101
+ } else if (scrollRequest.type === "scroll-end") {
2102
+ const { direction } = scrollRequest;
2103
+ const scrollTo = direction === "end" ? viewport.maxScrollContainerScrollVertical : 0;
2104
+ scrollbarContainer.scrollTo({
2105
+ top: scrollTo,
2106
+ left: scrollbarContainer.scrollLeft,
2107
+ behavior: "auto"
2108
+ });
2109
+ }
2110
+ }
2111
+ },
2112
+ [viewport.maxScrollContainerScrollVertical]
2113
+ );
2114
+ return {
2115
+ /** Ref to be assigned to ScrollbarContainer */
2116
+ scrollbarContainerRef,
2117
+ /** Scroll handler to be attached to ScrollbarContainer */
2118
+ onScrollbarContainerScroll: handleScrollbarContainerScroll,
2119
+ /** Ref to be assigned to ContentContainer */
2120
+ contentContainerRef,
2121
+ /** Scroll handler to be attached to ContentContainer */
2122
+ onContentContainerScroll: handleContentContainerScroll,
2123
+ /** Ref to be assigned to TableContainer */
2124
+ tableContainerRef,
2125
+ /** Scroll handler to be attached to TableContainer */
2126
+ onTableContainerScroll: handleTableContainerScroll,
2127
+ /** Scroll the table */
2128
+ requestScroll
2129
+ };
2130
+ };
2131
+
2132
+ // src/useTableViewport.ts
2133
+ var import_react19 = require("react");
2134
+ var UNMEASURED_VIEWPORT = {
2135
+ fillerHeight: 0,
2136
+ maxScrollContainerScrollHorizontal: 0,
2137
+ maxScrollContainerScrollVertical: 0,
2138
+ pinnedWidthLeft: 0,
2139
+ pinnedWidthRight: 0,
2140
+ rowCount: 0,
2141
+ scrollContentHeight: 0,
2142
+ scrollbarSize: 0,
2143
+ scrollContentWidth: 0,
2144
+ totalHeaderHeight: 0
2145
+ };
2146
+ var measurePinnedColumns = (columns) => {
2147
+ let pinnedWidthLeft = 0;
2148
+ let pinnedWidthRight = 0;
2149
+ let unpinnedWidth = 0;
2150
+ for (const column of columns) {
2151
+ const { hidden, pin, width } = column;
2152
+ const visibleWidth = hidden ? 0 : width;
2153
+ if (pin === "left") {
2154
+ pinnedWidthLeft += visibleWidth;
2155
+ } else if (pin === "right") {
2156
+ pinnedWidthRight += visibleWidth;
2157
+ } else {
2158
+ unpinnedWidth += visibleWidth;
2159
+ }
2160
+ }
2161
+ return { pinnedWidthLeft, pinnedWidthRight, unpinnedWidth };
2162
+ };
2163
+ var useTableViewport = ({
2164
+ columns,
2165
+ headerHeight,
2166
+ headings,
2167
+ rowCount,
2168
+ rowHeight,
2169
+ size
2170
+ }) => {
2171
+ const { pinnedWidthLeft, pinnedWidthRight, unpinnedWidth } = (0, import_react19.useMemo)(
2172
+ () => measurePinnedColumns(columns),
2173
+ [columns]
2174
+ );
2175
+ const viewportMeasurements = (0, import_react19.useMemo)(() => {
2176
+ var _a;
2177
+ if (size) {
2178
+ const headingsDepth = headings.length;
2179
+ const scrollbarSize = 15;
2180
+ const contentHeight = rowCount * rowHeight;
2181
+ const scrollContentWidth = pinnedWidthLeft + unpinnedWidth + pinnedWidthRight;
2182
+ const maxScrollContainerScrollVertical = contentHeight + headerHeight - (((_a = size == null ? void 0 : size.height) != null ? _a : 0) - headerHeight - scrollbarSize);
2183
+ const maxScrollContainerScrollHorizontal = scrollContentWidth - size.width + pinnedWidthLeft;
2184
+ const visibleRows = (size.height - headerHeight) / rowHeight;
2185
+ const count = Number.isInteger(visibleRows) ? visibleRows + 1 : Math.ceil(visibleRows);
2186
+ return {
2187
+ fillerHeight: (rowCount - count) * rowHeight,
2188
+ maxScrollContainerScrollHorizontal,
2189
+ maxScrollContainerScrollVertical,
2190
+ pinnedWidthLeft,
2191
+ pinnedWidthRight,
2192
+ rowCount: count,
2193
+ scrollContentHeight: headerHeight + contentHeight + scrollbarSize,
2194
+ scrollbarSize,
2195
+ scrollContentWidth,
2196
+ totalHeaderHeight: headerHeight * (1 + headingsDepth)
2197
+ };
2198
+ } else {
2199
+ return UNMEASURED_VIEWPORT;
2200
+ }
2201
+ }, [
2202
+ headerHeight,
2203
+ headings.length,
2204
+ pinnedWidthLeft,
2205
+ pinnedWidthRight,
2206
+ rowCount,
2207
+ rowHeight,
2208
+ size,
2209
+ unpinnedWidth
2210
+ ]);
2211
+ return viewportMeasurements;
2212
+ };
2213
+
2214
+ // src/useVirtualViewport.ts
2215
+ var import_vuu_utils12 = require("@vuu-ui/vuu-utils");
2216
+ var import_react20 = require("react");
2217
+ var useVirtualViewport = ({
2218
+ columns,
2219
+ rowHeight,
2220
+ setRange,
2221
+ viewportMeasurements
2222
+ }) => {
2223
+ const firstRowRef = (0, import_react20.useRef)(-1);
2224
+ const {
2225
+ rowCount: viewportRowCount,
2226
+ scrollContentWidth: contentWidth,
2227
+ maxScrollContainerScrollHorizontal
2228
+ } = viewportMeasurements;
2229
+ const availableWidth = contentWidth - maxScrollContainerScrollHorizontal;
2230
+ const scrollLeftRef = (0, import_react20.useRef)(0);
2231
+ const [visibleColumns, preSpan] = (0, import_react20.useMemo)(
2232
+ () => (0, import_vuu_utils12.getColumnsInViewport)(
2233
+ columns,
2234
+ scrollLeftRef.current,
2235
+ scrollLeftRef.current + availableWidth
2236
+ ),
2237
+ [availableWidth, columns]
2238
+ );
2239
+ const preSpanRef = (0, import_react20.useRef)(preSpan);
2240
+ (0, import_react20.useEffect)(() => {
2241
+ setColumnsWithinViewport(visibleColumns);
2242
+ }, [visibleColumns]);
2243
+ const [columnsWithinViewport, setColumnsWithinViewport] = (0, import_react20.useState)(visibleColumns);
2244
+ const handleHorizontalScroll = (0, import_react20.useCallback)(
2245
+ (scrollLeft) => {
2246
+ scrollLeftRef.current = scrollLeft;
2247
+ const [visibleColumns2, pre] = (0, import_vuu_utils12.getColumnsInViewport)(
2248
+ columns,
2249
+ scrollLeft,
2250
+ scrollLeft + availableWidth
2251
+ );
2252
+ if ((0, import_vuu_utils12.itemsChanged)(columnsWithinViewport, visibleColumns2)) {
2253
+ preSpanRef.current = pre;
2254
+ setColumnsWithinViewport(visibleColumns2);
2255
+ }
2256
+ },
2257
+ [availableWidth, columns, columnsWithinViewport]
2258
+ );
2259
+ const handleVerticalScroll = (0, import_react20.useCallback)(
2260
+ (scrollTop) => {
2261
+ const firstRow = Math.floor(scrollTop / rowHeight);
2262
+ if (firstRow !== firstRowRef.current) {
2263
+ firstRowRef.current = firstRow;
2264
+ setRange({ from: firstRow, to: firstRow + viewportRowCount });
2265
+ }
2266
+ },
2267
+ [rowHeight, setRange, viewportRowCount]
2268
+ );
2269
+ return {
2270
+ columnsWithinViewport,
2271
+ onHorizontalScroll: handleHorizontalScroll,
2272
+ onVerticalScroll: handleVerticalScroll,
2273
+ /** number of leading columns not rendered because of virtualization */
2274
+ virtualColSpan: preSpanRef.current
2275
+ };
2276
+ };
2277
+
2278
+ // src/useDataTable.ts
2279
+ var NO_ROWS = [];
2280
+ var { KEY: KEY2, IS_EXPANDED: IS_EXPANDED2, IS_LEAF: IS_LEAF2 } = import_vuu_utils13.metadataKeys;
2281
+ var useDataTable = ({
2282
+ config,
2283
+ dataSource,
2284
+ headerHeight,
2285
+ onConfigChange,
2286
+ onFeatureEnabled,
2287
+ onFeatureInvocation,
2288
+ onSelectionChange,
2289
+ renderBufferSize = 0,
2290
+ rowHeight,
2291
+ selectionModel,
2292
+ tableLayout,
2293
+ ...measuredProps
2294
+ }) => {
2295
+ var _a, _b;
2296
+ const [rowCount, setRowCount] = (0, import_react21.useState)(0);
2297
+ const expectConfigChangeRef = (0, import_react21.useRef)(false);
2298
+ const dataSourceRef = (0, import_react21.useRef)();
2299
+ dataSourceRef.current = dataSource;
2300
+ if (dataSource === void 0) {
2301
+ throw Error("no data source provided to DataTable");
2302
+ }
2303
+ const containerMeasurements = useMeasuredContainer(measuredProps);
2304
+ const onDataRowcountChange = (0, import_react21.useCallback)((size) => {
2305
+ setRowCount(size);
2306
+ }, []);
2307
+ const { columns, dispatchColumnAction, headings } = useTableModel(
2308
+ config,
2309
+ dataSource.config
2310
+ );
2311
+ const handlePersistentColumnOperation = (0, import_react21.useCallback)(
2312
+ (action) => {
2313
+ expectConfigChangeRef.current = true;
2314
+ dispatchColumnAction(action);
2315
+ },
2316
+ [dispatchColumnAction]
2317
+ );
2318
+ const handleContextMenuAction = useContextMenu3({
2319
+ dataSource,
2320
+ onPersistentColumnOperation: handlePersistentColumnOperation
2321
+ });
2322
+ const viewportMeasurements = useTableViewport({
2323
+ columns,
2324
+ headerHeight,
2325
+ headings,
2326
+ rowCount,
2327
+ rowHeight,
2328
+ size: containerMeasurements.innerSize
2329
+ });
2330
+ const onSubscribed = (0, import_react21.useCallback)(
2331
+ (subscription) => {
2332
+ if (subscription.tableMeta) {
2333
+ const { columns: columnNames, dataTypes: serverDataTypes } = subscription.tableMeta;
2334
+ expectConfigChangeRef.current = true;
2335
+ dispatchColumnAction({
2336
+ type: "setTypes",
2337
+ columnNames,
2338
+ serverDataTypes
2339
+ });
2340
+ }
2341
+ },
2342
+ [dispatchColumnAction]
2343
+ );
2344
+ const handleSelectionChange = (0, import_react21.useCallback)(
2345
+ (selected) => {
2346
+ dataSource.select(selected);
2347
+ onSelectionChange == null ? void 0 : onSelectionChange(selected);
2348
+ },
2349
+ [dataSource, onSelectionChange]
2350
+ );
2351
+ const handleRowClick = useSelection({
2352
+ onSelectionChange: handleSelectionChange,
2353
+ selectionModel
2354
+ });
2355
+ const { data, getSelectedRows, range, setRange } = useDataSource({
2356
+ dataSource,
2357
+ onFeatureEnabled,
2358
+ onFeatureInvocation,
2359
+ onSubscribed,
2360
+ onSizeChange: onDataRowcountChange,
2361
+ renderBufferSize,
2362
+ viewportRowCount: viewportMeasurements.rowCount
2363
+ });
2364
+ const dataRef = (0, import_react21.useRef)();
2365
+ dataRef.current = data;
2366
+ const handleSort = (0, import_react21.useCallback)(
2367
+ (column, extendSort = false, sortType) => {
2368
+ if (dataSource) {
2369
+ dataSource.sort = (0, import_vuu_utils13.applySort)(
2370
+ dataSource.sort,
2371
+ column,
2372
+ extendSort,
2373
+ sortType
2374
+ );
2375
+ }
2376
+ },
2377
+ [dataSource]
2378
+ );
2379
+ const handleColumnResize = (0, import_react21.useCallback)(
2380
+ (phase, columnName, width) => {
2381
+ const column = columns.find((column2) => column2.name === columnName);
2382
+ if (column) {
2383
+ if (phase === "end") {
2384
+ expectConfigChangeRef.current = true;
2385
+ }
2386
+ dispatchColumnAction({
2387
+ type: "resizeColumn",
2388
+ phase,
2389
+ column,
2390
+ width
2391
+ });
2392
+ } else {
2393
+ throw Error(
2394
+ `useDataTable.handleColumnResize, column ${columnName} not found`
2395
+ );
2396
+ }
2397
+ },
2398
+ [columns, dispatchColumnAction]
2399
+ );
2400
+ const handleToggleGroup = (0, import_react21.useCallback)(
2401
+ (row, column) => {
2402
+ const isJson = (0, import_vuu_utils13.isJsonGroup)(column, row);
2403
+ const key = row[KEY2];
2404
+ if (row[IS_EXPANDED2]) {
2405
+ dataSource.closeTreeNode(key, true);
2406
+ if (isJson) {
2407
+ const idx = columns.indexOf(column);
2408
+ const rows = dataSource.getRowsAtDepth(idx + 1);
2409
+ if (!rows.some((row2) => row2[IS_EXPANDED2] || row2[IS_LEAF2])) {
2410
+ dispatchColumnAction({
2411
+ type: "hideColumns",
2412
+ columns: columns.slice(idx + 2)
2413
+ });
2414
+ }
2415
+ }
2416
+ } else {
2417
+ dataSource.openTreeNode(key);
2418
+ if (isJson) {
2419
+ const childRows = dataSource.getChildRows(key);
2420
+ const idx = columns.indexOf(column) + 1;
2421
+ const columnsToShow = [columns[idx]];
2422
+ if (childRows.some((row2) => row2[IS_LEAF2])) {
2423
+ columnsToShow.push(columns[idx + 1]);
2424
+ }
2425
+ if (columnsToShow.some((col) => col.hidden)) {
2426
+ dispatchColumnAction({
2427
+ type: "showColumns",
2428
+ columns: columnsToShow
2429
+ });
2430
+ }
2431
+ }
2432
+ }
2433
+ },
2434
+ [columns, dataSource, dispatchColumnAction]
2435
+ );
2436
+ const {
2437
+ onVerticalScroll,
2438
+ onHorizontalScroll,
2439
+ columnsWithinViewport,
2440
+ virtualColSpan
2441
+ } = useVirtualViewport({
2442
+ columns,
2443
+ rowHeight,
2444
+ setRange,
2445
+ viewportMeasurements
2446
+ });
2447
+ const { requestScroll, ...scrollProps } = useTableScroll({
2448
+ onHorizontalScroll,
2449
+ // onRangeChange: setRange,
2450
+ onVerticalScroll,
2451
+ viewport: viewportMeasurements,
2452
+ viewportHeight: ((_b = (_a = containerMeasurements.innerSize) == null ? void 0 : _a.height) != null ? _b : 0) - headerHeight
2453
+ });
2454
+ const containerProps = useKeyboardNavigation({
2455
+ columnCount: columns.length,
2456
+ containerRef: containerMeasurements.containerRef,
2457
+ data,
2458
+ requestScroll,
2459
+ rowCount: dataSource == null ? void 0 : dataSource.size,
2460
+ viewportRange: range
2461
+ });
2462
+ const handleRemoveColumnFromGroupBy = (0, import_react21.useCallback)(
2463
+ (column) => {
2464
+ if (dataSource && dataSource.groupBy.includes(column.name)) {
2465
+ dataSource.groupBy = dataSource.groupBy.filter(
2466
+ (columnName) => columnName !== column.name
2467
+ );
2468
+ }
2469
+ },
2470
+ [dataSource]
2471
+ );
2472
+ const handleDropColumn = (0, import_react21.useCallback)(
2473
+ (fromIndex, toIndex) => {
2474
+ const column = dataSource.columns[fromIndex];
2475
+ const columns2 = (0, import_vuu_utils13.moveItem)(dataSource.columns, column, toIndex);
2476
+ if (columns2 !== dataSource.columns) {
2477
+ dataSource.columns = columns2;
2478
+ dispatchColumnAction({ type: "tableConfig", columns: columns2 });
2479
+ }
2480
+ },
2481
+ [dataSource, dispatchColumnAction]
2482
+ );
2483
+ const draggableHook = useDraggableColumn({
2484
+ onDrop: handleDropColumn,
2485
+ tableContainerRef: scrollProps.tableContainerRef,
2486
+ tableLayout
2487
+ });
2488
+ (0, import_react21.useEffect)(() => {
2489
+ if (dataSourceRef.current) {
2490
+ expectConfigChangeRef.current = true;
2491
+ dispatchColumnAction({
2492
+ type: "init",
2493
+ tableConfig: config,
2494
+ dataSourceConfig: dataSourceRef.current.config
2495
+ });
2496
+ }
2497
+ }, [config, dispatchColumnAction]);
2498
+ (0, import_react21.useEffect)(() => {
2499
+ dataSource.on("config", (config2, confirmed) => {
2500
+ expectConfigChangeRef.current = true;
2501
+ dispatchColumnAction({
2502
+ type: "tableConfig",
2503
+ ...config2,
2504
+ confirmed
2505
+ });
2506
+ });
2507
+ }, [dataSource, dispatchColumnAction]);
2508
+ (0, import_react21.useMemo)(() => {
2509
+ if (expectConfigChangeRef.current) {
2510
+ onConfigChange == null ? void 0 : onConfigChange({
2511
+ ...config,
2512
+ columns
2513
+ });
2514
+ expectConfigChangeRef.current = false;
2515
+ }
2516
+ }, [columns, config, onConfigChange]);
2517
+ const showContextMenu = (0, import_vuu_popups3.useContextMenu)();
2518
+ const onContextMenu = (0, import_react21.useCallback)(
2519
+ (evt) => {
2520
+ var _a2;
2521
+ const { current: currentData } = dataRef;
2522
+ const { current: currentDataSource } = dataSourceRef;
2523
+ const target = evt.target;
2524
+ const cellEl = target == null ? void 0 : target.closest("td");
2525
+ const rowEl = target == null ? void 0 : target.closest("tr");
2526
+ if (cellEl && rowEl && currentData && currentDataSource) {
2527
+ const { columns: columns2, selectedRowsCount } = currentDataSource;
2528
+ const columnMap = (0, import_vuu_utils13.buildColumnMap)(columns2);
2529
+ const rowIndex = parseInt((_a2 = rowEl.ariaRowIndex) != null ? _a2 : "-1");
2530
+ const cellIndex = Array.from(rowEl.childNodes).indexOf(cellEl);
2531
+ const row = currentData.find(([idx]) => idx === rowIndex);
2532
+ const columnName = columns2[cellIndex];
2533
+ showContextMenu(evt, "grid", {
2534
+ columnMap,
2535
+ columnName,
2536
+ row,
2537
+ selectedRows: selectedRowsCount === 0 ? NO_ROWS : getSelectedRows(),
2538
+ viewport: dataSource == null ? void 0 : dataSource.viewport
2539
+ });
2540
+ }
2541
+ },
2542
+ [dataSource == null ? void 0 : dataSource.viewport, getSelectedRows, showContextMenu]
2543
+ );
2544
+ return {
2545
+ containerMeasurements,
2546
+ containerProps,
2547
+ columns,
2548
+ columnsWithinViewport,
2549
+ data,
2550
+ dispatchColumnAction,
2551
+ handleContextMenuAction,
2552
+ headings,
2553
+ onColumnResize: handleColumnResize,
2554
+ onContextMenu,
2555
+ onRemoveColumnFromGroupBy: handleRemoveColumnFromGroupBy,
2556
+ onRowClick: handleRowClick,
2557
+ onSort: handleSort,
2558
+ onToggleGroup: handleToggleGroup,
2559
+ virtualColSpan,
2560
+ scrollProps,
2561
+ rowCount,
2562
+ viewportMeasurements,
2563
+ ...draggableHook
2564
+ };
2565
+ };
2566
+
2567
+ // src/Table.tsx
2568
+ var import_classnames8 = __toESM(require("classnames"));
2569
+ var import_vuu_utils14 = require("@vuu-ui/vuu-utils");
2570
+ var import_jsx_runtime11 = require("react/jsx-runtime");
2571
+ var classBase7 = "vuuTable";
2572
+ var Table = ({
2573
+ allowConfigEditing: showSettings = false,
2574
+ className: classNameProp,
2575
+ config,
2576
+ dataSource,
2577
+ headerHeight = 25,
2578
+ height,
2579
+ id: idProp,
2580
+ onConfigChange,
2581
+ onFeatureEnabled,
2582
+ onFeatureInvocation,
2583
+ onSelectionChange,
2584
+ onShowConfigEditor: onShowSettings,
2585
+ renderBufferSize = 0,
2586
+ rowHeight = 20,
2587
+ selectionModel = "extended",
2588
+ style: styleProp,
2589
+ tableLayout: tableLayoutProp = "row",
2590
+ width,
2591
+ zebraStripes = false,
2592
+ ...props
2593
+ }) => {
2594
+ const id = (0, import_core.useIdMemo)(idProp);
2595
+ const {
2596
+ containerMeasurements: { containerRef, innerSize, outerSize },
2597
+ containerProps,
2598
+ dispatchColumnAction,
2599
+ draggable,
2600
+ draggedItemIndex,
2601
+ handleContextMenuAction,
2602
+ scrollProps,
2603
+ tableLayout,
2604
+ viewportMeasurements,
2605
+ ...tableProps
2606
+ } = useDataTable({
2607
+ config,
2608
+ dataSource,
2609
+ renderBufferSize,
2610
+ headerHeight,
2611
+ height,
2612
+ onConfigChange,
2613
+ onFeatureEnabled,
2614
+ onFeatureInvocation,
2615
+ onSelectionChange,
2616
+ rowHeight,
2617
+ selectionModel,
2618
+ tableLayout: tableLayoutProp,
2619
+ width
2620
+ });
2621
+ const style = {
2622
+ ...outerSize,
2623
+ "--content-height": `${viewportMeasurements.scrollContentHeight}px`,
2624
+ "--content-width": `${viewportMeasurements.scrollContentWidth}px`,
2625
+ "--filler-height": `${viewportMeasurements.fillerHeight}px`,
2626
+ "--pinned-width-left": `${viewportMeasurements.pinnedWidthLeft}px`,
2627
+ "--pinned-width-right": `${viewportMeasurements.pinnedWidthRight}px`,
2628
+ "--header-height": `${headerHeight}px`,
2629
+ "--row-height": `${rowHeight}px`,
2630
+ "--scrollbar-size": `${viewportMeasurements.scrollbarSize}px`,
2631
+ "--table-height": `${innerSize == null ? void 0 : innerSize.height}px`,
2632
+ "--table-width": `${innerSize == null ? void 0 : innerSize.width}px`,
2633
+ "--total-header-height": `${viewportMeasurements == null ? void 0 : viewportMeasurements.totalHeaderHeight}px`
2634
+ };
2635
+ const scrollbarContainerStyle = {
2636
+ left: viewportMeasurements.pinnedWidthLeft - 1,
2637
+ // The -1 is to align the top border, might cause innaccuracy
2638
+ // It is compensated by a hardcoded adjustment in css
2639
+ // top: measurements.top - 1 + headerHeight,
2640
+ top: (viewportMeasurements == null ? void 0 : viewportMeasurements.totalHeaderHeight) - 1
2641
+ };
2642
+ const Table2 = tableLayout === "column" ? ColumnBasedTable : RowBasedTable;
2643
+ const className = (0, import_classnames8.default)(classBase7, classNameProp, {
2644
+ [`${classBase7}-zebra`]: zebraStripes,
2645
+ [`${classBase7}-loading`]: (0, import_vuu_utils14.isDataLoading)(tableProps.columns)
2646
+ });
2647
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
2648
+ import_vuu_popups4.ContextMenuProvider,
2649
+ {
2650
+ menuActionHandler: handleContextMenuAction,
2651
+ menuBuilder: buildContextMenuDescriptors(dataSource),
2652
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
2653
+ "div",
2654
+ {
2655
+ ...containerProps,
2656
+ className,
2657
+ id,
2658
+ ref: containerRef,
2659
+ style,
2660
+ tabIndex: -1,
2661
+ children: [
2662
+ innerSize ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
2663
+ "div",
2664
+ {
2665
+ className: `${classBase7}-scrollbarContainer`,
2666
+ onScroll: scrollProps.onScrollbarContainerScroll,
2667
+ ref: scrollProps.scrollbarContainerRef,
2668
+ style: scrollbarContainerStyle,
2669
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: `${classBase7}-scrollContent` })
2670
+ }
2671
+ ) : null,
2672
+ innerSize ? /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
2673
+ "div",
2674
+ {
2675
+ className: `${classBase7}-contentContainer`,
2676
+ onScroll: scrollProps.onContentContainerScroll,
2677
+ ref: scrollProps.contentContainerRef,
2678
+ ...props,
2679
+ children: [
2680
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: `${classBase7}-scrollContent` }),
2681
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
2682
+ "div",
2683
+ {
2684
+ className: `${classBase7}-tableContainer`,
2685
+ onScroll: scrollProps.onTableContainerScroll,
2686
+ ref: scrollProps.tableContainerRef,
2687
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
2688
+ Table2,
2689
+ {
2690
+ ...tableProps,
2691
+ headerHeight,
2692
+ rowHeight
2693
+ }
2694
+ )
2695
+ }
2696
+ ),
2697
+ draggable
2698
+ ]
2699
+ }
2700
+ ) : null,
2701
+ showSettings && innerSize ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
2702
+ import_core.Button,
2703
+ {
2704
+ className: `${classBase7}-settings`,
2705
+ "data-icon": "settings",
2706
+ onClick: onShowSettings,
2707
+ variant: "secondary"
2708
+ }
2709
+ ) : null
2710
+ ]
2711
+ }
2712
+ )
2713
+ }
2714
+ );
2715
+ };
2716
+
2717
+ // src/cell-renderers/json-cell/JsonCell.tsx
2718
+ var import_classnames9 = __toESM(require("classnames"));
2719
+ var import_vuu_utils15 = require("@vuu-ui/vuu-utils");
2720
+ var import_jsx_runtime12 = require("react/jsx-runtime");
2721
+ var classBase8 = "vuuJsonCell";
2722
+ var { IS_EXPANDED: IS_EXPANDED3, KEY: KEY3 } = import_vuu_utils15.metadataKeys;
2723
+ var localKey = (key) => {
2724
+ const pos = key.lastIndexOf("|");
2725
+ if (pos === -1) {
2726
+ return "";
2727
+ } else {
2728
+ return key.slice(pos + 1);
2729
+ }
2730
+ };
2731
+ var JsonCell = ({ column, row }) => {
2732
+ const {
2733
+ key: columnKey
2734
+ /*, type, valueFormatter */
2735
+ } = column;
2736
+ let value = row[columnKey];
2737
+ let isToggle = false;
2738
+ if ((0, import_vuu_utils15.isJsonAttribute)(value)) {
2739
+ value = value.slice(0, -1);
2740
+ isToggle = true;
2741
+ }
2742
+ const rowKey = localKey(row[KEY3]);
2743
+ const className = (0, import_classnames9.default)({
2744
+ [`${classBase8}-name`]: rowKey === value,
2745
+ [`${classBase8}-value`]: rowKey !== value,
2746
+ [`${classBase8}-group`]: isToggle
2747
+ });
2748
+ if (isToggle) {
2749
+ const toggleIcon = row[IS_EXPANDED3] ? "minus-box" : "plus-box";
2750
+ return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("span", { className, children: [
2751
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("span", { className: `${classBase8}-value`, children: value }),
2752
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("span", { className: `${classBase8}-toggle`, "data-icon": toggleIcon })
2753
+ ] });
2754
+ } else if (value) {
2755
+ return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("span", { className, children: value });
2756
+ } else {
2757
+ return null;
2758
+ }
2759
+ };
2760
+ (0, import_vuu_utils15.registerComponent)("json", JsonCell, "cell-renderer", {});
11
2761
  //# sourceMappingURL=index.js.map