@vuu-ui/vuu-table 0.8.21 → 0.8.22-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/esm/index.js CHANGED
@@ -1,3 +1,3590 @@
1
- import{OverflowContainer as hn}from"@vuu-ui/vuu-layout";import{useLayoutEffectSkipFirst as xn}from"@vuu-ui/vuu-utils";import wn from"clsx";import{useCallback as Tn,useRef as Rn,useState as yn}from"react";import rn from"clsx";import{useCallback as ln}from"react";import{jsx as an,jsxs as sn}from"react/jsx-runtime";var Co="vuuColumnHeaderPill",le=({children:e,className:o,column:t,onRemove:r,removable:n,...l})=>{if(n&&typeof r!="function")throw Error("ColumnHeaderPill onRemove prop must be provided if Pill is removable");let s=ln(i=>{i.preventDefault(),i.stopPropagation(),r==null||r(t)},[t,r]);return sn("div",{...l,className:rn(Co,o),children:[e,n?an("span",{className:`${Co}-removeButton`,role:"button","data-icon":"cross",onClick:s}):null]})};import{jsx as Ie,jsxs as un}from"react/jsx-runtime";var vo=({column:e,...o})=>{let{name:t,sorted:r}=e,n=typeof r=="number"?r<0?"arrow-down":"arrow-up":r==="A"?"arrow-up":r==="D"?"arrow-down":void 0;return un(le,{...o,column:e,children:[Ie("span",{className:"vuuGroupColumnPill-label",children:t}),n!==void 0?Ie("span",{"data-icon":n}):null,typeof r=="number"?Ie("span",{className:"vuuSortPosition",children:Math.abs(r)}):null]})};import{jsx as ho,jsxs as cn}from"react/jsx-runtime";var xo=({column:e})=>{if(!e.sorted)return null;let o=typeof e.sorted=="number"?e.sorted<0?"arrow-down":"arrow-up":e.sorted==="A"?"arrow-up":"arrow-down";return cn(le,{column:e,children:[ho("span",{"data-icon":o}),typeof e.sorted=="number"?ho("span",{className:"vuuSortPosition",children:Math.abs(e.sorted)}):null]})};import{useCallback as ze,useRef as mn}from"react";import{jsx as pn}from"react/jsx-runtime";var wo=()=>{},dn="vuuColumnResizerNext",ge=({onDrag:e,onDragEnd:o=wo,onDragStart:t=wo})=>{let r=mn(0),n=ze(i=>{i.stopPropagation&&i.stopPropagation(),i.preventDefault&&i.preventDefault();let a=Math.round(i.clientX),u=a-r.current;r.current=a,u!==0&&e(i,u)},[e]),l=ze(i=>{window.removeEventListener("mouseup",l),window.removeEventListener("mousemove",n),o(i)},[o,n]),s=ze(i=>{t(i),r.current=Math.round(i.clientX),window.addEventListener("mouseup",l),window.addEventListener("mousemove",n),i.stopPropagation&&i.stopPropagation(),i.preventDefault&&i.preventDefault()},[t,n,l]);return pn("div",{className:dn,onMouseDown:s})};import{useCallback as Ne,useRef as bn,useState as fn}from"react";var Ce=({column:e,onResize:o,rootRef:t})=>{let r=bn(0),[n,l]=fn(!1),{name:s}=e,i=Ne(()=>{if(o&&t.current){let{width:c}=t.current.getBoundingClientRect();r.current=Math.round(c),l(!0),o==null||o("begin",s)}},[s,o,t]),a=Ne((c,d)=>{if(t.current&&o){let{width:g}=t.current.getBoundingClientRect(),b=Math.round(g)+d;b!==r.current&&b>0&&(o("resize",s,b),r.current=b)}},[s,o,t]),u=Ne(()=>{o&&(o("end",s,r.current),setTimeout(()=>{l(!1)},80))},[s,o]);return{isResizing:n,onDrag:a,onDragStart:i,onDragEnd:u}};import{getColumnStyle as gn}from"@vuu-ui/vuu-utils";import Cn from"clsx";import{useMemo as vn}from"react";var Y=(e,o,t)=>vn(()=>{let r=Cn(o,{vuuPinFloating:e.pin==="floating",vuuPinLeft:e.pin==="left",vuuPinRight:e.pin==="right",vuuEndPin:t&&e.endPin,[`${o}-editable`]:e.editable,[`${o}-right`]:e.align==="right"}),n=gn(e);return{className:r,style:n}},[e,o,t]);import{jsx as Ke,jsxs as Hn}from"react/jsx-runtime";import{createElement as Mn}from"react";var Fe="vuuTableGroupHeaderCell",Dn=(e,o)=>e===o?e:o,Ve=({column:e,className:o,onMoveColumn:t,onRemoveColumn:r,onResize:n,...l})=>{let s=Rn(null),{isResizing:i,...a}=Ce({column:e,onResize:n,rootRef:s}),[u,c]=yn(e.columns),{className:d,style:g}=Y(e,Fe,!0),b=u.length>1?{removable:!0,onRemove:r}:void 0,C=Tn((h,m)=>{c(v=>{let R=v.slice(),[P]=R.splice(h,1);if(m===-1){let I=R.concat(P);return t==null||t(I),I}else return R.splice(m,0,P),t==null||t(R),R})},[t]);return xn(()=>{c(h=>Dn(h,e.columns))},[e.columns]),Hn("div",{...l,className:wn(d,o,{[`${Fe}-pending`]:e.groupConfirmed===!1}),ref:s,role:"columnheader",style:g,children:[Ke(hn,{allowDragDrop:!0,className:`${Fe}-inner`,height:24,onMoveItem:C,overflowPosition:"start",children:u.map(h=>Mn(vo,{...b,column:h,key:h.key}))}),Ke(le,{column:e,removable:!0,onRemove:r}),e.resizeable!==!1?Ke(ge,{...a}):null]})};import In from"clsx";import{useCallback as zn,useRef as Nn}from"react";import{useContextMenu as Pn}from"@vuu-ui/vuu-popups";import En from"clsx";import{useCallback as To,useRef as Sn,useState as kn}from"react";import{jsx as An}from"react/jsx-runtime";var Ln=e=>{if(e){let{bottom:o,left:t}=e.getBoundingClientRect();return{x:t,y:o+6}}},Ro=({className:e,column:o,...t})=>{let r=Sn(null),[n,l]=kn(!1),[s]=Pn(),i=To(()=>{l(!1)},[]),a=To(u=>{l(!0),s(u,"column-menu",{column:o,ContextMenuProps:{onClose:i,position:Ln(r.current)}})},[o,i,s]);return An("span",{...t,className:En("vuuTable-columnMenu",e,{"vuuTable-columnMenu-open":n}),"data-icon":"more-vert",onClick:a,ref:r})};import{jsx as ie,jsxs as Fn}from"react/jsx-runtime";var ve="vuuTableHeaderCell",yo=({className:e,column:o,onClick:t,onResize:r,...n})=>{var R;let{HeaderCellContentRenderer:l,HeaderCellLabelRenderer:s}=o,i=Nn(null),{isResizing:a,...u}=Ce({column:o,onResize:r,rootRef:i}),c=zn(P=>{!a&&(t==null||t(P))},[a,t]),{className:d,style:g}=Y(o,ve,!0),b=ie(Ro,{column:o}),C=s?ie(s,{className:`${ve}-label`,column:o}):ie("div",{className:`${ve}-label`,children:(R=o.label)!=null?R:o.name}),h=l?[ie(l,{column:o},"content")]:[],m=ie(xo,{column:o}),v=o.align==="right"?[m,C].concat(h).concat(b):[b,C,m].concat(h);return Fn("div",{...n,className:In(d,e,{[`${ve}-resizing`]:a}),onClick:c,ref:i,role:"columnheader",style:g,children:[...v,o.resizeable!==!1?ie(ge,{...u}):null]})};import{MeasuredContainer as li}from"@vuu-ui/vuu-layout";import{ContextMenuProvider as ii}from"@vuu-ui/vuu-popups";import{metadataKeys as ai,useId as si}from"@vuu-ui/vuu-utils";import{useForkRef as ui}from"@salt-ds/core";import Mt from"clsx";import{forwardRef as ci,useRef as mi,useState as di}from"react";import{isGroupColumn as Eo,isJsonColumn as _n,isJsonGroup as Xn,metadataKeys as Qn,isNotHidden as Jn,RowSelected as Yn}from"@vuu-ui/vuu-utils";import Zn from"clsx";import{memo as jn,useCallback as So}from"react";import{isNumericColumn as Kn}from"@vuu-ui/vuu-utils";import{useCallback as Do}from"react";import{jsx as Mo}from"react/jsx-runtime";var Vn="vuuTableCell",Ho=({column:e,columnMap:o,onClick:t,onDataEdited:r,row:n})=>{let{className:l,style:s}=Y(e,Vn),{CellRenderer:i,name:a,valueFormatter:u}=e,c=o[a],d=Do(b=>{if(r){let C=b;return Kn(e)&&typeof b=="string"&&(C=e.serverDataType==="double"?parseFloat(b):parseInt(b)),r==null?void 0:r(n,a,C)}else throw Error("TableCell onDataEdited prop not supplied for an editable cell")},[e,a,r,n]),g=Do(b=>{t==null||t(b,e)},[e,t]);return Mo("div",{className:l,onClick:t?g:void 0,role:"cell",style:s,children:i?Mo(i,{column:e,columnMap:o,onCommit:d,row:n}):u(n[c])})};import{getGroupValueAndOffset as $n,metadataKeys as Gn}from"@vuu-ui/vuu-utils";import{useCallback as Bn}from"react";import On from"clsx";import{jsx as Ge,jsxs as Un}from"react/jsx-runtime";var{IS_LEAF:Wn}=Gn,$e="vuuTableGroupCell",Po=({column:e,onClick:o,row:t})=>{let{columns:r}=e,[n,l]=$n(r,t),{className:s,style:i}=Y(e,$e),a=Bn(d=>{o==null||o(d,e)},[e,o]),u=t[Wn],c=Array(l).fill(0).map((d,g)=>Ge("span",{className:`${$e}-spacer`},g));return Un("div",{className:On(s,"vuuTableCell"),role:"cell",style:i,onClick:u?void 0:a,children:[c,u?null:Ge("span",{className:`${$e}-toggle`,"data-icon":"triangle-right"}),Ge("span",{children:n})]})};import{jsx as Be}from"react/jsx-runtime";import{createElement as tr}from"react";var{IDX:qn,IS_EXPANDED:er,SELECTED:or}=Qn,X="vuuTableRow",Oe=jn(({className:e,columnMap:o,columns:t,highlighted:r,row:n,offset:l,onClick:s,onDataEdited:i,onToggleGroup:a,zebraStripes:u=!1,...c})=>{let{[qn]:d,[er]:g,[or]:b}=n,C=So(E=>{let k=E.shiftKey,F=E.ctrlKey||E.metaKey;s==null||s(n,k,F)},[s,n]),{True:h,First:m,Last:v}=Yn,R=Zn(X,e,{[`${X}-even`]:u&&d%2===0,[`${X}-expanded`]:g,[`${X}-highlighted`]:r,[`${X}-selected`]:b&h,[`${X}-selectedStart`]:b&m,[`${X}-selectedEnd`]:b&v}),P={transform:`translate3d(0px, ${l}px, 0px)`},I=So((E,k)=>{(Eo(k)||Xn(k,n))&&(E.stopPropagation(),a==null||a(n,k))},[a,n]);return tr("div",{...c,key:`row-${n[0]}`,role:"row",className:R,onClick:C,style:P},Be("span",{className:`${X}-selectionDecorator vuuStickyLeft`}),t.filter(Jn).map(E=>{let k=Eo(E),F=_n(E);return Be(k?Po:Ho,{column:E,columnMap:o,onClick:k||F?I:void 0,onDataEdited:i,row:n},E.key)}),Be("span",{className:`${X}-selectionDecorator vuuStickyRight`}))});Oe.displayName="Row";import{useDragDrop as Gl}from"@vuu-ui/vuu-ui-controls";import{applySort as Bl,buildColumnMap as Ol,getIndexFromRowElement as Wl,isGroupColumn as Ul,isJsonGroup as _l,isValidNumber as bt,metadataKeys as Xl,updateColumn as ft,useLayoutEffectSkipFirst as gt}from"@vuu-ui/vuu-utils";import{useCallback as L,useEffect as Ql,useMemo as oo,useState as Ct}from"react";import{isNumericColumn as nr}from"@vuu-ui/vuu-utils";var ko=e=>(o,t)=>{let r=[];return e===void 0||(o==="header"||o==="column-menu")&&(r.push(...rr(t,e)),r.push(...ar(t,e)),r.push(...lr(t,e)),r.push(...ir(t)),r.push({action:"column-settings",icon:"cog",label:"Column Settings",options:t}),r.push({action:"table-settings",icon:"cog",label:"DataGrid Settings",options:t})),r};function rr(e,{sort:{sortDefs:o}}){let{column:t}=e,r=[];if(t===void 0)return r;let n=o.length>0;return t.sorted==="A"?r.push({label:"Reverse Sort (DSC)",action:"sort-dsc",options:e}):t.sorted==="D"?r.push({label:"Reverse Sort (ASC)",action:"sort-asc",options:e}):typeof t.sorted=="number"?(t.sorted>0?r.push({label:"Reverse Sort (DSC)",action:"sort-add-dsc",options:e}):r.push({label:"Reverse Sort (ASC)",action:"sort-add-asc",options:e}),n&&Math.abs(t.sorted)<o.length&&r.push({label:"Remove from sort",action:"sort-remove",options:e}),r.push({label:"New Sort",children:[{label:"Ascending",action:"sort-asc",options:e},{label:"Descending",action:"sort-dsc",options:e}]})):n?(r.push({label:"Add to sort",children:[{label:"Ascending",action:"sort-add-asc",options:e},{label:"Descending",action:"sort-add-dsc",options:e}]}),r.push({label:"New Sort",children:[{label:"Ascending",action:"sort-asc",options:e},{label:"Descending",action:"sort-dsc",options:e}]})):r.push({label:"Sort",children:[{label:"Ascending",action:"sort-asc",options:e},{label:"Descending",action:"sort-dsc",options:e}]}),r}function lr(e,o){let{column:t}=e;if(t===void 0||o.groupBy.length===0)return[];let{name:r,label:n=r}=t;return[{label:`Aggregate ${n}`,children:[{label:"Count",action:"agg-count",options:e},{label:"Distinct",action:"agg-distinct",options:e}].concat(nr(t)?[{label:"Sum",action:"agg-sum",options:e},{label:"Avg",action:"agg-avg",options:e},{label:"High",action:"agg-high",options:e},{label:"Low",action:"agg-low",options:e}]:[])}]}var Xe=(e,o)=>({label:`Pin ${o}`,action:`column-pin-${o}`,options:e}),We=e=>Xe(e,"left"),Ue=e=>Xe(e,"floating"),_e=e=>Xe(e,"right");function ir(e){let{column:o}=e;if(o===void 0)return[];let{pin:t}=o,r=[{label:"Hide column",action:"column-hide",options:e},{label:"Remove column",action:"column-remove",options:e}];return t===void 0?r.push({label:"Pin column",children:[We(e),Ue(e),_e(e)]}):t==="left"?r.push({label:"Unpin column",action:"column-unpin",options:e},{label:"Pin column",children:[Ue(e),_e(e)]}):t==="right"?r.push({label:"Unpin column",action:"column-unpin",options:e},{label:"Pin column",children:[We(e),Ue(e)]}):t==="floating"&&r.push({label:"Unpin column",action:"column-unpin",options:e},{label:"Pin column",children:[We(e),_e(e)]}),r}function ar(e,{groupBy:o}){let{column:t}=e,r=[];if(t===void 0)return r;let{name:n,label:l=n}=t;return o.length===0?r.push({label:`Group by ${l}`,action:"group",options:e}):r.push({label:`Add ${l} to group by`,action:"group-add",options:e}),r}import{removeColumnFromFilter as sr}from"@vuu-ui/vuu-utils";import{addGroupColumn as Lo,addSortColumn as Ao,AggregationType as ur,setAggregations as ae,setSortColumn as Io}from"@vuu-ui/vuu-utils";var cr=(e,o)=>{if(e.filterStruct&&o){let[t,r]=sr(o,e.filterStruct);return{filter:r,filterStruct:t}}else return e},{Average:mr,Count:dr,Distinct:pr,High:br,Low:fr,Sum:gr}=ur,zo=({dataSource:e,onPersistentColumnOperation:o})=>r=>{let n=r.options;if(n.column&&e){let{column:l}=n;switch(r.menuId){case"sort-asc":return e.sort=Io(e.sort,l,"A"),!0;case"sort-dsc":return e.sort=Io(e.sort,l,"D"),!0;case"sort-add-asc":return e.sort=Ao(e.sort,l,"A"),!0;case"sort-add-dsc":return e.sort=Ao(e.sort,l,"D"),!0;case"group":return e.groupBy=Lo(e.groupBy,l),!0;case"group-add":return e.groupBy=Lo(e.groupBy,l),!0;case"column-hide":return o({type:"hideColumns",columns:[l]}),!0;case"column-remove":return e.columns=e.columns.filter(s=>s!==l.name),!0;case"filter-remove-column":return e.filter=cr(e.filter,l),!0;case"remove-filters":return e.filter={filter:""},!0;case"agg-avg":return e.aggregations=ae(e.aggregations,l,mr),!0;case"agg-high":return e.aggregations=ae(e.aggregations,l,br),!0;case"agg-low":return e.aggregations=ae(e.aggregations,l,fr),!0;case"agg-count":return e.aggregations=ae(e.aggregations,l,dr),!0;case"agg-distinct":return e.aggregations=ae(e.aggregations,l,pr),!0;case"agg-sum":return e.aggregations=ae(e.aggregations,l,gr),!0;case"column-pin-floating":return o({type:"pinColumn",column:l,pin:"floating"}),!0;case"column-pin-left":return o({type:"pinColumn",column:l,pin:"left"}),!0;case"column-pin-right":return o({type:"pinColumn",column:l,pin:"right"}),!0;case"column-unpin":return o({type:"pinColumn",column:l,pin:void 0}),!0;case"column-settings":return o({type:"columnSettings",column:l}),!0;case"table-settings":return o({type:"tableSettings"}),!0;default:}}return!1};var No=(e,o)=>{switch(o.type){case"col-size":return{...e,columns:e.columns.map(t=>t.name===o.column.name?{...t,width:o.width}:t)};case"column-prop":return{...e,columns:e.columns.map(t=>t.name===o.column.name?{...t,[o.property]:o.value}:t)};default:return e}};import{isCharacterKey as xr}from"@vuu-ui/vuu-utils";import{useCallback as ee}from"react";var Qe=e=>`.vuuTable-col-headers .vuuTableHeaderCell:nth-child(${e})`,Je=(e,o)=>`.vuuTable-body > [aria-rowindex='${e+1}'] > [role='cell']:nth-child(${o+1})`,Fo=(e,[o,t])=>{var l;let r=o===-1?Qe(t):Je(o,t),n=(l=e.current)==null?void 0:l.querySelector(r);return Cr(n)&&n.querySelector("button")||n},Cr=e=>e.classList.contains("vuuTableCell-editable"),Ko=e=>e.querySelector(".vuuTableInputCell")!==null;function vr(e){if(e){let o=e.ariaRowIndex;if(o!==null)return parseInt(o,10)-1}return-1}var hr=e=>e.closest('[role="row"]'),Vo=e=>vr(hr(e));var $o=({navigate:e})=>{let o=ee(()=>{e()},[e]),t=ee(a=>{let u=a.target,c=u.matches("input")?u:u.querySelector("input");c&&(c.focus(),c.select())},[]),r=ee(a=>{let c=a.target.querySelector("input");c&&(c.focus(),c.select())},[]),n=ee(a=>{let u=a.target;Ko(u)&&(xr(a.key)?t(a):a.key==="Enter"&&r(a))},[t,r]),l=ee(a=>{let u=a.target;(u.matches("input")||u.querySelector("input"))&&(t(a),a.stopPropagation())},[t]),s=ee(a=>{a.target.removeEventListener("vuu-commit",o,!0)},[o]),i=ee(a=>{a.target.addEventListener("vuu-commit",o,!0)},[o]);return{onBlur:s,onDoubleClick:l,onFocus:i,onKeyDown:n}};import{getFullRange as Ze,NULL_RANGE as Go}from"@vuu-ui/vuu-utils";import{useCallback as xe,useEffect as Bo,useMemo as yr,useRef as we,useState as Dr}from"react";import{isRowSelectedLast as wr,metadataKeys as Tr,WindowRange as Rr}from"@vuu-ui/vuu-utils";var{SELECTED:Ye}=Tr,he=class{constructor({from:o,to:t}){this.rowCount=0;this.setRowCount=o=>{o<this.data.length&&(this.data.length=o),this.rowCount=o};this.range=new Rr(o,t),this.data=new Array(Math.max(0,t-o)),this.rowCount=0}add(o){let[t]=o;if(this.isWithinRange(t)){let r=t-this.range.from;if(this.data[r]=o,o[Ye]){let n=this.data[r-1];wr(n)&&(this.data[r-1]=n.slice(),this.data[r-1][Ye]-=4)}}}getAtIndex(o){return this.range.isWithin(o)&&this.data[o-this.range.from]!=null?this.data[o-this.range.from]:void 0}isWithinRange(o){return this.range.isWithin(o)}setRange({from:o,to:t}){if(o!==this.range.from||t!==this.range.to){let[r,n]=this.range.overlap(o,t),l=new Array(Math.max(0,t-o));for(let s=r;s<n;s++){let i=this.getAtIndex(s);if(i){let a=s-o;l[a]=i}}this.data=l,this.range.from=o,this.range.to=t}}getSelectedRows(){return this.data.filter(o=>o[Ye]!==0)}};var Mr=e=>e.type==="vuu-link-created"||e.type==="vuu-link-removed",Oo=({dataSource:e,onFeatureInvocation:o,onSizeChange:t,onSubscribed:r,range:n=Go,renderBufferSize:l=0})=>{let[,s]=Dr(null),i=we([]),a=we(!0),u=we(!1),c=we(Go),d=yr(()=>new he(Ze(n,l)),[]),g=xe(m=>{for(let v of m)d.add(v);i.current=d.data,a.current?s({}):console.log("ignore update as we're not mounted")},[d]),b=xe(m=>{m.type==="subscribed"?r==null||r(m):m.type==="viewport-update"?(typeof m.size=="number"&&(t==null||t(m.size),d.setRowCount(m.size)),m.rows?g(m.rows):typeof m.size=="number"&&(i.current=d.data,u.current=!0)):Mr(m)?o==null||o(m):console.log(`useDataSource unexpected message ${m.type}`)},[d,o,t,r,g]),C=xe(()=>d.getSelectedRows(),[d]);Bo(()=>{var m;return a.current=!0,(m=e.resume)==null||m.call(e),()=>{var v;a.current=!1,(v=e.suspend)==null||v.call(e)}},[e]),Bo(()=>{var m;e.status==="disabled"?(m=e.enable)==null||m.call(e,b):e==null||e.subscribe({range:Ze(n,l)},b)},[e,b,n,l]);let h=xe(m=>{let v=Ze(m,l);d.setRange(v),e.range=c.current=v,e.emit("range",m)},[e,d,l]);return{data:i.current,dataRef:i,getSelectedRows:C,range:c.current,setRange:h}};import{useMemo as Hr,useRef as Pr}from"react";var Wo=e=>{let o=Pr(e);return Hr(()=>o.current,[])};import{getIndexFromRowElement as Er}from"@vuu-ui/vuu-utils";import{useControlled as Sr}from"@salt-ds/core";import{useCallback as W,useEffect as Uo,useRef as Te}from"react";var Qo=new Set(["Home","End","PageUp","PageDown","ArrowDown","ArrowUp"]),je=new Set(Qo);je.add("ArrowLeft");je.add("ArrowRight");var kr=(e,o)=>{switch(o){case"cell":return je.has(e);case"row":return Qo.has(e);default:return!1}},Lr=["Home","End","PageUp","PageDown"],_o=e=>Lr.includes(e),Ar=[-1,-1];function Xo(e,[o,t],r,n){return e==="ArrowUp"?o>-1?[o-1,t]:[o,t]:e==="ArrowDown"?o===-1?[0,t]:o===n-1?[o,t]:[o+1,t]:e==="ArrowRight"?t<r?[o,t+1]:[o,t]:e==="ArrowLeft"?t>1?[o,t-1]:[o,t]:[o,t]}var Jo=({columnCount:e=0,containerRef:o,disableFocus:t=!1,defaultHighlightedIndex:r,disableHighlightOnFocus:n,highlightedIndex:l,navigationStyle:s,requestScroll:i,onHighlight:a,rowCount:u=0,viewportRowCount:c})=>{var y;let d=Te([-1,-1]),g=Te(),b=Te([-1,0]),C=Te(),[h,m]=Sr({controlled:l,default:r,name:"UseKeyboardNavigation"});C.current=h;let v=W((f,x=!1)=>{a==null||a(f),m(f)},[a,m]),R=f=>f==null?void 0:f.closest("[role='columnHeader'],[role='cell']"),P=f=>{var x;if(f.role==="columnHeader")return[-1,parseInt((x=f.dataset.idx)!=null?x:"-1",10)];{let D=f.closest("[role='row']");if(D){let S=Er(D),$=Array.from(D.childNodes).indexOf(f);return[S,$]}}return Ar},I=W(f=>{var x;if(o.current){let D=Fo(o,f);D&&(D!==g.current&&((x=g.current)==null||x.removeAttribute("tabindex"),g.current=D,D.setAttribute("tabindex","0")),console.log(`scroll row ${f[0]}`),i==null||i({type:"scroll-row",rowIndex:f[0]}),D.focus({preventScroll:!0}))}},[o,i]),E=W((f,x,D=!1)=>{let S=[f,x];b.current=S,s==="row"?m(f):I(S),D&&(d.current=S)},[I,s,m]),k=W((f,[x,D])=>new Promise(S=>{let $=x;switch(f){case"PageDown":$=Math.min(u-1,x+c),i==null||i({type:"scroll-page",direction:"down"});break;case"PageUp":$=Math.max(0,x-c),i==null||i({type:"scroll-page",direction:"up"});break;case"Home":$=0,i==null||i({type:"scroll-end",direction:"home"});break;case"End":$=u-1,i==null||i({type:"scroll-end",direction:"end"});break}setTimeout(()=>{S([$,D])},90)}),[i,u,c]),F=W(()=>{var f;if(n!==!0&&(f=o.current)!=null&&f.contains(document.activeElement)){let x=R(document.activeElement);x&&(d.current=P(x),s==="row"&&m(d.current[0]))}},[n,o,s,m]),K=W(async f=>{let[x,D]=_o(f)?await k(f,b.current):Xo(f,b.current,e,u),[S,$]=b.current;(x!==S||D!==$)&&E(x,D,!0)},[e,k,u,E]),V=W(f=>{i==null||i({type:"scroll-row",rowIndex:f})},[i]),B=W(async f=>{let{current:x}=C,[D]=_o(f)?await k(f,[x!=null?x:-1,0]):Xo(f,[x!=null?x:-1,0],e,u);D!==x&&(v(D),V(D))},[e,k,u,V,v]);Uo(()=>{l!==void 0&&l!==-1&&V(l)},[l,V]);let O=W(f=>{u>0&&kr(f.key,s)&&(f.preventDefault(),f.stopPropagation(),s==="row"?B(f.key):K(f.key))},[u,s,B,K]),T=W(f=>{let x=f.target,D=R(x);if(D){let[S,$]=P(D);E(S,$)}},[E]),M=W(()=>{v(-1)},[v]),w=W(f=>{let x=Vo(f.target);x!==-1&&x!==C.current&&v(x)},[v]),N=W(()=>{K("ArrowDown")},[K]),z=((y=o.current)==null?void 0:y.firstChild)!=null;return Uo(()=>{if(z&&g.current===void 0&&!t){let{current:f}=o,x=(f==null?void 0:f.querySelector(Qe(0)))||(f==null?void 0:f.querySelector(Je(0,0)));x&&(x.setAttribute("tabindex","0"),g.current=x)}},[o,t,z]),{highlightedIndexRef:C,navigate:N,onClick:T,onFocus:F,onKeyDown:O,onMouseLeave:s==="row"?M:void 0,onMouseMove:s==="row"?w:void 0}};import{deselectItem as Ir,dispatchMouseEvent as zr,isRowSelected as Nr,metadataKeys as Fr,selectItem as Kr}from"@vuu-ui/vuu-utils";import{useCallback as qe,useRef as Yo}from"react";var{IDX:Vr}=Fr,$r=[],Gr=["Enter"," "],Zo=({highlightedIndexRef:e,selectionKeys:o=Gr,selectionModel:t,onSelect:r,onSelectionChange:n})=>{let l=Yo(-1),s=Yo($r),i=qe(c=>o.includes(c.key),[o]),a=qe((c,d,g)=>{let{[Vr]:b}=c,{current:C}=l,{current:h}=s,v=(Nr(c)?Ir:Kr)(t,h,b,d,g,C);s.current=v,l.current=b,r==null||r(c),n==null||n(v)},[r,n,t]);return{onKeyDown:qe(c=>{if(i(c)){let{current:d}=e;if(d!==void 0&&d!==-1){let g=c.target.querySelector(`[aria-rowindex="${d}"]`);g&&zr(g,"click")}}},[e,i]),onRowClick:a}};import{useContextMenu as Br}from"@vuu-ui/vuu-popups";import{buildColumnMap as Or,getIndexFromRowElement as Wr}from"@vuu-ui/vuu-utils";import{useCallback as Ur}from"react";var _r=[],jo=({columns:e,data:o,dataSource:t,getSelectedRows:r})=>{let[n]=Br();return Ur(s=>{let i=s.target,a=i==null?void 0:i.closest("div[role='cell']"),u=i==null?void 0:i.closest("div[role='row']");if(a&&u){let{selectedRowsCount:c}=t,d=Or(e),g=Wr(u),b=Array.from(u.childNodes).indexOf(a),C=o.find(([m])=>m===g),h=e[b];n(s,"grid",{columnMap:d,columnName:h,row:C,selectedRows:c===0?_r:r(),viewport:t.viewport})}},[e,o,t,r,n])};import{applyFilterToColumns as Xr,applyGroupByToColumns as Qr,applySortToColumns as Jr,getCellRenderer as Yr,getColumnHeaderContentRenderer as Zr,getColumnHeaderLabelRenderer as jr,getColumnLabel as qr,getTableHeadings as el,getValueFormatter as ol,hasValidationRules as tl,isFilteredColumn as nl,isGroupColumn as rl,isPinned as ll,logger as il,metadataKeys as al,replaceColumn as oe,sortPinnedColumns as qo,stripFilterFromColumns as sl,subscribedOnly as ul}from"@vuu-ui/vuu-utils";import{buildValidationChecker as cl}from"@vuu-ui/vuu-ui-controls";import{useReducer as ml}from"react";var{info:eo}=il("useTableModel"),dl=100,pl=al.count,bl=({serverDataType:e})=>e===void 0,et=(e,o)=>{let t=o==null?void 0:o.columns.find(({name:r})=>r===e.name);return t?t.serverDataType:e.serverDataType},fl=["int","long","double"],ot=e=>e===void 0?void 0:fl.includes(e)?"right":"left",tt=e=>e.type==="columnSettings",nt=e=>e.type==="tableSettings",gl=(e,o)=>{switch(eo==null||eo(`TableModelReducer ${o.type}`),o.type){case"init":return lt(o);case"moveColumn":return vl(e,o);case"resizeColumn":return wl(e,o);case"setTableSchema":return Tl(e,o);case"hideColumns":return hl(e,o);case"showColumns":return xl(e,o);case"pinColumn":return Rl(e,o);case"updateColumnProp":return se(e,o);case"tableConfig":return at(e,o);default:return console.log(`unhandled action ${o.type}`),e}},rt=(e,o)=>{let[t,r]=ml(gl,{tableConfig:e,dataSource:o},lt),{columns:n,headings:l,tableConfig:s,...i}=t;return{columns:n,dispatchColumnAction:r,headings:l,tableAttributes:i,tableConfig:s}};function lt({dataSource:e,tableConfig:o}){let{columns:t,...r}=o,{config:n,tableSchema:l}=e,s=t.filter(ul(n==null?void 0:n.columns)).map(it(r,l)),i=s.some(ll)?qo(s):s,a={columns:i,headings:el(i),tableConfig:o,...r};if(n){let{columns:u,...c}=n;a=at(a,{type:"tableConfig",...c})}return a}var Cl=(e,o)=>o==="uppercase"?e.toUpperCase():o==="capitalize"?e[0].toUpperCase()+e.slice(1).toLowerCase():e,it=(e,o)=>(t,r)=>{let{columnDefaultWidth:n=dl,columnFormatHeader:l}=e,s=et(t,o),{align:i=ot(s),key:a,name:u,label:c=qr(t),width:d=n,...g}=t,b={...g,align:i,CellRenderer:Yr(t),HeaderCellContentRenderer:Zr(t),HeaderCellLabelRenderer:jr(t),clientSideEditValidationCheck:tl(t.type)?cl(t.type.renderer.rules):void 0,label:Cl(c,l),key:a!=null?a:r+pl,name:u,originalIdx:r,serverDataType:s,valueFormatter:ol(t,s),width:d};return rl(b)&&(b.columns=b.columns.map(C=>it(e)(C,C.key))),b};function vl(e,{column:o,moveBy:t}){let{columns:r}=e;if(typeof t=="number"){let n=r.indexOf(o),l=r.slice(),[s]=l.splice(n,1);return l.splice(n+t,0,s),{...e,columns:l}}return e}function hl(e,{columns:o}){return o.some(t=>t.hidden!==!0)?o.reduce((t,r)=>r.hidden!==!0?se(t,{type:"updateColumnProp",column:r,hidden:!0}):t,e):e}function xl(e,{columns:o}){return o.some(t=>t.hidden)?o.reduce((t,r)=>r.hidden?se(t,{type:"updateColumnProp",column:r,hidden:!1}):t,e):e}function wl(e,{column:o,phase:t,width:r}){let n="updateColumnProp",l=t!=="end";switch(t){case"begin":return se(e,{type:n,column:o,resizing:l});case"end":return se(e,{type:n,column:o,resizing:l,width:r});case"resize":return se(e,{type:n,column:o,width:r});default:throw Error(`useTableModel.resizeColumn, invalid resizePhase ${t}`)}}function Tl(e,{tableSchema:o}){let{columns:t}=e;if(t.some(bl)){let r=t.map(n=>{var s;let l=et(n,o);return{...n,align:(s=n.align)!=null?s:ot(l),serverDataType:l}});return{...e,columns:r}}else return e}function Rl(e,o){let{columns:t}=e,{column:r,pin:n}=o,l=t.find(s=>s.name===r.name);return l?(t=oe(t,{...l,pin:n}),t=qo(t),{...e,columns:t}):e}function se(e,o){let{columns:t,tableConfig:r}=e,{align:n,column:l,hidden:s,label:i,resizing:a,width:u}=o,c=t.find(d=>d.name===l.name);if(c&&((n==="left"||n==="right")&&(t=oe(t,{...c,align:n})),typeof i=="string"&&(t=oe(t,{...c,label:i})),typeof a=="boolean"&&(t=oe(t,{...c,resizing:a})),typeof s=="boolean"&&(t=oe(t,{...c,hidden:s})),typeof u=="number")){t=oe(t,{...c,width:u});let d=r.columns.find(g=>g.name===l.name);d&&(r={...r,columns:oe(r.columns,{...d,width:u})})}return{...e,columns:t,tableConfig:r}}function at(e,{confirmed:o,filter:t,groupBy:r,sort:n}){let l=r!==void 0,s=typeof(t==null?void 0:t.filter)=="string",i=n&&n.sortDefs.length>0,a=e;return l&&(a={...e,columns:Qr(a.columns,r,o)}),i&&(a={...e,columns:Jr(a.columns,n)}),s?a={...e,columns:Xr(a.columns,t)}:a.columns.some(nl)&&(a={...e,columns:sl(a.columns)}),a}import{getRowElementAtIndex as yl}from"@vuu-ui/vuu-utils";import{useCallback as Q,useEffect as Dl,useImperativeHandle as Ml,useMemo as Hl,useRef as ue}from"react";var st=e=>{let{scrollLeft:o,scrollTop:t}=e,{clientHeight:r,clientWidth:n,scrollHeight:l,scrollWidth:s}=e,i=o/(s-n),a=t/(l-r);return[i,a]},Pl={scrollToIndex:()=>{},scrollToKey:()=>{}},El=[void 0,void 0],Sl=(e,o,t=e.closest(".vuuTable-contentContainer"))=>{if(t){let r=t==null?void 0:t.getBoundingClientRect(),n=r.top+o,l=e.getBoundingClientRect();if(l)return l.bottom>r.bottom?["down",l.bottom-r.bottom]:l.top<n?["up",l.top-n]:El;throw Error("Whats going on, row not found")}else throw Error("Whats going on, scrollbar container not found")},ut=({onAttach:e,onDetach:o})=>{let t=ue(null);return Q(n=>{if(n)t.current=n,e==null||e(n);else if(t.current){let{current:l}=t;t.current=n,o==null||o(l)}},[e,o])},ct=({getRowAtPosition:e,onHorizontalScroll:o,onVerticalScroll:t,scrollingApiRef:r,setRange:n,viewportMeasurements:l})=>{let s=ue(0),i=ue(!1),a=ue({scrollTop:0,scrollLeft:0}),u=ue(null),c=ue(null),{appliedPageSize:d,isVirtualScroll:g,maxScrollContainerScrollHorizontal:b,maxScrollContainerScrollVertical:C,rowCount:h,totalHeaderHeight:m}=l,v=Q((T,M)=>{t==null||t(T,M);let w=e(T);w!==s.current&&(s.current=w,n({from:w,to:w+h+1}))},[e,t,n,h]),R=Q(()=>{let{current:T}=c,{current:M}=u,{current:w}=i;if(w)i.current=!1;else if(T&&M){let[N,z]=st(M),y=Math.round(N*b),f=z*C;T.scrollTo({left:y,top:f,behavior:"auto"})}},[b,C]),P=Q(()=>{let{current:T}=c,{current:M}=u,{current:w}=a;if(T&&M){let{scrollLeft:N,scrollTop:z}=T,[y,f]=st(T);i.current=!0,M.scrollLeft=Math.round(y*b),M.scrollTop=f*C,w.scrollTop!==z&&(w.scrollTop=z,v(z,f)),w.scrollLeft!==N&&(w.scrollLeft=N,o==null||o(N))}},[v,b,C,o]),I=Q(T=>{u.current=T,T.addEventListener("scroll",R,{passive:!0})},[R]),E=Q(T=>{u.current=null,T.removeEventListener("scroll",R)},[R]),k=Q(T=>{c.current=T,T.addEventListener("scroll",P,{passive:!0})},[P]),F=Q(T=>{c.current=null,T.removeEventListener("scroll",P)},[P]),K=ut({onAttach:k,onDetach:F}),V=ut({onAttach:I,onDetach:E}),B=Q(T=>{let{current:M}=c;if(M){let{scrollLeft:w,scrollTop:N}=M;if(i.current=!1,T.type==="scroll-row"){let z=yl(M,T.rowIndex);if(z!==null){let[y,f]=Sl(z,m);if(y&&f)if(g)console.log(`virtual scroll row required ${y} ${f}
2
- first Row ${s.current}`);else{let x=w,D=N;y==="up"||y==="down"?D=Math.min(Math.max(0,N+f),C):x=Math.min(Math.max(0,w+f),b),M.scrollTo({top:D,left:x,behavior:"smooth"})}}}else if(T.type==="scroll-page"){let{direction:z}=T;if(g)console.log("need a virtual page scroll");else{let y=z==="down"?d:-d,f=Math.min(Math.max(0,N+y),C);M.scrollTo({top:f,left:w,behavior:"auto"})}}else if(T.type==="scroll-end"){let{direction:z}=T,y=z==="end"?C:0;M.scrollTo({top:y,left:M.scrollLeft,behavior:"auto"})}}},[d,g,b,C,n,m,h]),O=Hl(()=>({scrollToIndex:T=>{if(u.current){let M=(T-30)*20;u.current.scrollTop=M}},scrollToKey:T=>{console.log(`scrollToKey ${T}`)}}),[]);return Ml(r,()=>u.current?O:Pl,[O]),Dl(()=>{let{current:T}=s,M={from:T,to:T+h+1};n(M)},[n,h]),{scrollbarContainerRef:V,contentContainerRef:K,requestScroll:B}};import{useCallback as kl,useMemo as Re,useRef as mt}from"react";import{actualRowPositioning as Ll,virtualRowPositioning as Al}from"@vuu-ui/vuu-utils";var Il=1e5,zl={appliedPageSize:0,contentHeight:0,contentWidth:0,getRowAtPosition:()=>-1,getRowOffset:()=>-1,horizontalScrollbarHeight:0,isVirtualScroll:!1,maxScrollContainerScrollHorizontal:0,maxScrollContainerScrollVertical:0,pinnedWidthLeft:0,pinnedWidthRight:0,rowCount:0,setPctScrollTop:()=>{},totalHeaderHeight:0,verticalScrollbarWidth:0,viewportBodyHeight:0},Nl=e=>{let o=0,t=0,r=0;for(let n of e){let{hidden:l,pin:s,width:i}=n,a=l?0:i;s==="left"?o+=a:s==="right"?t+=a:r+=a}return{pinnedWidthLeft:o+4,pinnedWidthRight:t+4,unpinnedWidth:r}},dt=({columns:e,headerHeight:o,headings:t,rowCount:r,rowHeight:n,size:l})=>{let s=mt(0),i=n*Math.min(r,Il),a=r*n,u=a-i,{pinnedWidthLeft:c,pinnedWidthRight:d,unpinnedWidth:g}=Re(()=>Nl(e),[e]),b=mt(o);Re(()=>{b.current=o*(1+t.length)},[o,t.length]);let[C,h,m]=Re(()=>u?Al(n,u,s):Ll(n),[u,n]),v=kl(R=>{s.current=R},[]);return Re(()=>{var R;if(l){let{current:P}=b,I=15,E=c+g+d,k=E>l.width?I:0,F=i-(((R=l==null?void 0:l.height)!=null?R:0)-k)+P,K=E-l.width+c,V=(l.height-o)/n,B=Number.isInteger(V)?V:Math.ceil(V),O=l.height-P,T=i>O?I:0;return{appliedPageSize:B*n*(i/a),contentHeight:i,contentWidth:E,getRowAtPosition:h,getRowOffset:C,isVirtualScroll:m,horizontalScrollbarHeight:k,maxScrollContainerScrollHorizontal:K,maxScrollContainerScrollVertical:F,pinnedWidthLeft:c,pinnedWidthRight:d,rowCount:B,setPctScrollTop:v,totalHeaderHeight:P,verticalScrollbarWidth:T,viewportBodyHeight:O}}else return zl},[h,C,o,m,c,g,d,i,n,v,l,a])};import{useLayoutProviderDispatch as Fl}from"@vuu-ui/vuu-layout";import{getCalculatedColumnType as Kl}from"@vuu-ui/vuu-utils";import{useCallback as te,useRef as Vl,useState as $l}from"react";var pt=({availableColumns:e,onAvailableColumnsChange:o,onConfigChange:t,onCreateCalculatedColumn:r,onDataSourceConfigChange:n,tableConfig:l})=>{let s=Fl(),i=Vl(),[a,u]=$l(e),c=te((m,v,R)=>{s({type:"set-props",path:"#context-panel",props:{expanded:!0,content:{type:m,props:R},title:v}})},[s]),d=te(()=>{requestAnimationFrame(()=>{var m;(m=i.current)==null||m.call(i)})},[]),g=te(m=>{let v=a.concat({name:m.name,serverDataType:Kl(m)});u(v),o==null||o(v),requestAnimationFrame(()=>{var R;(R=i.current)==null||R.call(i)}),r(m)},[a,o,r]),b=te(m=>{c("ColumnSettings","Column Settings",{column:m.column,onCancelCreateColumn:d,onConfigChange:t,onCreateCalculatedColumn:g,tableConfig:l,vuuTable:m.vuuTable})},[d,g,t,c,l]),C=te(()=>{b({column:{name:"::",serverDataType:"string"},type:"columnSettings",vuuTable:{module:"SIMUL",table:"instruments"}})},[b]),h=te(m=>{let v=l.columns.find(R=>R.name===m);v&&b({type:"columnSettings",column:v,vuuTable:{module:"SIMUL",table:"instruments"}})},[b,l.columns]);return i.current=te(()=>{c("TableSettings","DataGrid Settings",{availableColumns:a!=null?a:l.columns.map(({name:m,serverDataType:v})=>({name:m,serverDataType:v})),onAddCalculatedColumn:C,onConfigChange:t,onDataSourceConfigChange:n,onNavigateToColumn:h,tableConfig:l})},[a,C,h,t,n,c,l]),{showColumnSettingsPanel:b,showTableSettingsPanel:i.current}};var ye=e=>e,{KEY:Jl,IS_EXPANDED:vt,IS_LEAF:ht}=Xl,Yl={draggable:void 0,onMouseDown:void 0},Zl=()=>Yl,jl=(e,o)=>({...e,columns:e.columns.concat(o)}),xt=({allowDragDrop:e=!1,availableColumns:o,config:t,containerRef:r,dataSource:n,disableFocus:l,headerHeight:s=25,highlightedIndex:i,id:a,navigationStyle:u="cell",onAvailableColumnsChange:c,onConfigChange:d,onDragStart:g,onDrop:b,onFeatureInvocation:C,onHighlight:h,onRowClick:m,onSelect:v,onSelectionChange:R,renderBufferSize:P=0,rowHeight:I=20,scrollingApiRef:E,selectionModel:k,size:F})=>{let[K,V]=Ct(n.size);if(n===void 0)throw Error("no data source provided to Vuu Table");let B=e?Gl:Zl,O=oo(()=>ko(n),[n]),T=L(p=>{V(p)},[]),{columns:M,dispatchColumnAction:w,headings:N,tableAttributes:z,tableConfig:y}=rt(t,n);gt(()=>{w({type:"init",dataSource:n,tableConfig:y})},[y,n,w]);let f=L(p=>{w({type:"init",tableConfig:p,dataSource:n}),d==null||d(ye(p))},[n,w,d]),[x,D]=Ct(),[S,$]=oo(()=>{let p=(H,A)=>{let G=ft(M,H,{width:A});D(G)};return[x!=null?x:M,p]},[M,x]),Pe=oo(()=>Ol(n.columns),[n.columns]),{getRowAtPosition:Ee,getRowOffset:Se,setPctScrollTop:de,...j}=dt({columns:S,headerHeight:s,headings:N,rowCount:K,rowHeight:I,size:F}),pe=Wo({from:0,to:j.rowCount===0?0:j.rowCount+1}),ne=L(({tableSchema:p})=>{p?w({type:"setTableSchema",tableSchema:p}):console.log("subscription message with no schema")},[w]),{data:be,dataRef:_,getSelectedRows:ke,range:Le,setRange:fe}=Oo({dataSource:n,onFeatureInvocation:C,renderBufferSize:P,onSizeChange:T,onSubscribed:ne,range:pe}),q=L(p=>{w({type:"init",tableConfig:p,dataSource:n}),d==null||d(ye(p))},[n,w,d]),kt=L(p=>{n.config={...n.config,...p}},[n]);Ql(()=>{n.on("config",(p,H)=>{w({type:"tableConfig",...p,confirmed:H})})},[n,w]);let Lt=L(p=>{n.columns=n.columns.concat(p.name),f(jl(y,p))},[n,y,f]),ro=L(p=>{let{columns:H}=p,A=H.map(U=>U.name),G={...y,columns:y.columns.map(U=>A.includes(U.name)?{...U,hidden:!0}:U)};f(G)},[y,f]),lo=L(p=>{f({...y,columns:ft(y.columns,{...p.column,pin:p.pin})})},[y,f]),{showColumnSettingsPanel:io,showTableSettingsPanel:ao}=pt({availableColumns:o!=null?o:y.columns.map(({name:p,serverDataType:H="string"})=>({name:p,serverDataType:H})),onAvailableColumnsChange:c,onConfigChange:q,onCreateCalculatedColumn:Lt,onDataSourceConfigChange:kt,tableConfig:y}),At=L(p=>{if(tt(p))io(p);else if(nt(p))ao();else switch(p.type){case"hideColumns":return ro(p);case"pinColumn":return lo(p);default:w(p)}},[w,ro,lo,io,ao]),It=zo({dataSource:n,onPersistentColumnOperation:At}),zt=L((p,H=!1,A)=>{n&&(n.sort=Bl(n.sort,p,H,A))},[n]),Nt=L((p,H,A)=>{let G=S.find(U=>U.name===H);if(G)p==="resize"?bt(A)&&$(H,A):p==="end"?bt(A)&&(w({type:"resizeColumn",phase:p,column:G,width:A}),D(void 0),d==null||d(ye(No(y,{type:"col-size",column:G,width:A})))):(D(void 0),w({type:"resizeColumn",phase:p,column:G,width:A}));else throw Error(`useDataTable.handleColumnResize, column ${H} not found`)},[S,y,w,d,$]),Ft=L((p,H)=>{var U,go;let A=_l(H,p),G=p[Jl];if(p[vt]){if(n.closeTreeNode(G,!0),A){let ce=S.indexOf(H),me=(U=n.getRowsAtDepth)==null?void 0:U.call(n,ce+1);me&&!me.some(re=>re[vt]||re[ht])&&w({type:"hideColumns",columns:S.slice(ce+2)})}}else if(n.openTreeNode(G),A){let ce=(go=n.getChildRows)==null?void 0:go.call(n,G),me=S.indexOf(H)+1,re=[S[me]];ce&&ce.some(Ae=>Ae[ht])&&re.push(S[me+1]),re.some(Ae=>Ae.hidden)&&w({type:"showColumns",columns:re})}},[S,n,w]),Kt=L((p,H)=>{de(H)},[de]),{requestScroll:Vt,...$t}=ct({getRowAtPosition:Ee,rowHeight:I,scrollingApiRef:E,setRange:fe,onVerticalScroll:Kt,viewportMeasurements:j}),{highlightedIndexRef:so,navigate:Gt,onFocus:uo,onKeyDown:co,...Bt}=Jo({columnCount:S.filter(p=>p.hidden!==!0).length,containerRef:r,disableFocus:l,highlightedIndex:i,navigationStyle:u,requestScroll:Vt,rowCount:n==null?void 0:n.size,onHighlight:h,viewportRange:Le,viewportRowCount:j.rowCount}),{onBlur:Ot,onDoubleClick:Wt,onKeyDown:mo,onFocus:po}=$o({navigate:Gt}),Ut=L(p=>{uo(),p.defaultPrevented||po(p)},[po,uo]),_t=jo({columns:S,data:be,dataSource:n,getSelectedRows:ke}),Xt=L(p=>{n.groupBy=p.map(H=>H.name)},[n]),Qt=L(p=>{Ul(p)?n.groupBy=[]:n&&n.groupBy.includes(p.name)&&(n.groupBy=n.groupBy.filter(H=>H!==p.name))},[n]),Jt=L(p=>{n.select(p),R==null||R(p)},[n,R]),{onKeyDown:bo,onRowClick:fo}=Zo({highlightedIndexRef:so,onSelect:v,onSelectionChange:Jt,selectionModel:k}),Yt=L(p=>{co(p),p.defaultPrevented||mo(p),p.defaultPrevented||bo(p)},[co,mo,bo]),Zt=L((p,H,A)=>{fo(p,H,A),m==null||m(p)},[m,fo]);gt(()=>{w({type:"init",tableConfig:t,dataSource:n})},[t,n,w]);let jt=L(p=>{console.log("useTable onMoveColumn",{columns:p});let H={...y,columns:p};w({type:"init",tableConfig:H,dataSource:n}),d==null||d(ye(H))},[n,w,d,y]),qt=L(p=>{b==null||b(p)},[b]),en=L(async(p,H,A)=>n.applyEdit(p,H,A),[n]),on=L(p=>{let{initialDragElement:H}=p,A=Wl(H),G=_.current.find(U=>U[0]===A);G&&p.setPayload(G),g==null||g(p)},[_,g]),{onMouseDown:tn,draggable:nn}=B({allowDragDrop:e,containerRef:r,draggableClassName:"vuuTable",id:a,onDragStart:on,onDrop:qt,orientation:"vertical",itemQuery:".vuuTableRow"});return{...Bt,"aria-rowcount":n.size,draggableRow:nn,onBlur:Ot,onDoubleClick:Wt,onFocus:Ut,onKeyDown:Yt,onMouseDown:tn,columnMap:Pe,columns:S,data:be,getRowOffset:Se,handleContextMenuAction:It,headings:N,highlightedIndex:so.current,menuBuilder:O,onContextMenu:_t,onDataEdited:en,onMoveColumn:jt,onMoveGroupColumn:Xt,onRemoveGroupColumn:Qt,onRowClick:Zt,onSortColumn:zt,onResizeColumn:Nt,onToggleGroup:Ft,scrollProps:$t,tableAttributes:z,tableConfig:y,viewportMeasurements:j}};import{isGroupColumn as ti,isNotHidden as ni}from"@vuu-ui/vuu-utils";import ri from"clsx";import{useDragDrop as ql}from"@vuu-ui/vuu-ui-controls";import{moveColumnTo as to,visibleColumnAtIndex as ei}from"@vuu-ui/vuu-utils";import{useCallback as wt,useRef as oi}from"react";var Tt=({columns:e,onMoveColumn:o,onSortColumn:t,tableConfig:r})=>{let n=oi(null),l=wt((c,d)=>{let g=e[c],b=to(e,g,d),C=({name:R})=>P=>P.name===R,h=b.findIndex(C(g)),m=b[h+1],v=m?r.columns.findIndex(C(m)):-1;d>c&&v!==-1?o(to(r.columns,g,v-1)):o(to(r.columns,g,v))},[e,o,r.columns]),s=wt(c=>{var m;let g=c.target.closest(".vuuTableHeaderCell"),b=parseInt((m=g==null?void 0:g.dataset.index)!=null?m:"-1"),C=ei(e,b),h=c.shiftKey;C&&t(C,h)},[e,t]),{onMouseDown:i,draggable:a,...u}=ql({allowDragDrop:!0,containerRef:n,draggableClassName:"vuuTable",onDrop:l,orientation:"horizontal",itemQuery:".vuuTableHeaderCell"});return{containerRef:n,draggableColumn:a,draggedColumnIndex:u.draggedItemIndex,onClick:s,onMouseDown:i}};import{jsx as De,jsxs as Rt}from"react/jsx-runtime";var yt=({classBase:e="vuuTable",columns:o,headings:t,onMoveColumn:r,onMoveGroupColumn:n,onRemoveGroupColumn:l,onResizeColumn:s,onSortColumn:i,tableConfig:a,tableId:u})=>{let{containerRef:c,draggableColumn:d,draggedColumnIndex:g,onClick:b,onMouseDown:C}=Tt({columns:o,onMoveColumn:r,onSortColumn:i,tableConfig:a});return Rt("div",{className:`${e}-col-headings`,ref:c,children:[t.map((h,m)=>De("div",{className:"vuuTable-heading",children:h.map(({label:v,width:R},P)=>De("div",{className:"vuuTable-headingCell",style:{width:R},children:v},P))},m)),Rt("div",{className:`${e}-col-headers`,role:"row",children:[o.filter(ni).map((h,m)=>ti(h)?De(Ve,{column:h,"data-index":m,onMoveColumn:n,onRemoveColumn:l,onResize:s},h.name):De(yo,{className:ri({"vuuDraggable-dragAway":m===g}),column:h,"data-index":m,id:`${u}-col-${m}`,onClick:b,onMouseDown:C,onResize:s},h.name)),d]})]})};import{jsx as Z,jsxs as Dt}from"react/jsx-runtime";var J="vuuTable",{IDX:pi,RENDER_IDX:bi}=ai,fi=({Row:e=Oe,allowDragDrop:o,availableColumns:t,config:r,containerRef:n,dataSource:l,disableFocus:s=!1,highlightedIndex:i,id:a,navigationStyle:u="cell",onAvailableColumnsChange:c,onConfigChange:d,onDragStart:g,onDrop:b,onFeatureInvocation:C,onHighlight:h,onRowClick:m,onSelect:v,onSelectionChange:R,renderBufferSize:P=5,rowHeight:I=20,scrollingApiRef:E,selectionModel:k="extended",showColumnHeaders:F=!0,headerHeight:K=F?25:0,size:V})=>{let B=si(a),{columnMap:O,columns:T,data:M,draggableRow:w,getRowOffset:N,handleContextMenuAction:z,headings:y,highlightedIndex:f,onDataEdited:x,onMoveColumn:D,onMoveGroupColumn:S,onRemoveGroupColumn:$,onResizeColumn:Pe,onRowClick:Ee,onSortColumn:Se,onToggleGroup:de,menuBuilder:j,scrollProps:pe,tableAttributes:ne,tableConfig:be,viewportMeasurements:_,...ke}=xt({allowDragDrop:o,availableColumns:t,config:r,containerRef:n,dataSource:l,disableFocus:s,headerHeight:K,highlightedIndex:i,id:B,navigationStyle:u,onAvailableColumnsChange:c,onConfigChange:d,onDragStart:g,onDrop:b,onFeatureInvocation:C,onHighlight:h,onRowClick:m,onSelect:v,onSelectionChange:R,renderBufferSize:P,rowHeight:I,scrollingApiRef:E,selectionModel:k,size:V}),Le=Mt(`${J}-contentContainer`,{[`${J}-colLines`]:ne.columnSeparators,[`${J}-rowLines`]:ne.rowSeparators,[`${J}-zebra`]:ne.zebraStripes}),fe={"--content-height":`${_.contentHeight}px`,"--content-width":`${_.contentWidth}px`,"--horizontal-scrollbar-height":`${_.horizontalScrollbarHeight}px`,"--pinned-width-left":`${_.pinnedWidthLeft}px`,"--pinned-width-right":`${_.pinnedWidthRight}px`,"--header-height":`${K}px`,"--row-height":`${I}px`,"--total-header-height":`${_.totalHeaderHeight}px`,"--vertical-scrollbar-width":`${_.verticalScrollbarWidth}px`,"--viewport-body-height":`${_.viewportBodyHeight}px`};return Dt(ii,{menuActionHandler:z,menuBuilder:j,children:[Z("div",{className:`${J}-scrollbarContainer`,ref:pe.scrollbarContainerRef,style:fe,children:Z("div",{className:`${J}-scrollbarContent`})}),Z("div",{className:Le,ref:pe.contentContainerRef,style:fe,children:Dt("div",{...ke,className:`${J}-table`,role:"table",tabIndex:s?void 0:-1,children:[F?Z(yt,{columns:T,headings:y,onMoveColumn:D,onMoveGroupColumn:S,onRemoveGroupColumn:$,onResizeColumn:Pe,onSortColumn:Se,tableConfig:be,tableId:B}):null,Z("div",{className:`${J}-body`,children:M.map(q=>Z(e,{"aria-rowindex":q[0]+1,columnMap:O,columns:T,highlighted:f===q[pi],onClick:Ee,onDataEdited:x,row:q,offset:N(q),onToggleGroup:de,zebraStripes:ne.zebraStripes},q[bi]))})]})}),w]})},um=ci(function({Row:o,allowDragDrop:t,availableColumns:r,className:n,config:l,dataSource:s,disableFocus:i,highlightedIndex:a,id:u,navigationStyle:c,onAvailableColumnsChange:d,onConfigChange:g,onDragStart:b,onDrop:C,onFeatureInvocation:h,onHighlight:m,onRowClick:v,onSelect:R,onSelectionChange:P,renderBufferSize:I,rowHeight:E,scrollingApiRef:k,selectionModel:F,showColumnHeaders:K,headerHeight:V,style:B,...O},T){let M=mi(null),[w,N]=di();if(l===void 0)throw Error("vuu Table requires config prop. Minimum config is list of Column Descriptors");if(s===void 0)throw Error("vuu Table requires dataSource prop");return Z(li,{...O,className:Mt(J,n),id:u,onResize:N,ref:ui(M,T),children:w?Z(fi,{Row:o,allowDragDrop:t,availableColumns:r,config:l,containerRef:M,dataSource:s,disableFocus:i,headerHeight:V,highlightedIndex:a,id:u,navigationStyle:c,onAvailableColumnsChange:d,onConfigChange:g,onDragStart:b,onDrop:C,onFeatureInvocation:h,onHighlight:m,onRowClick:v,onSelect:R,onSelectionChange:P,renderBufferSize:I,rowHeight:E,scrollingApiRef:k,selectionModel:F,showColumnHeaders:K,size:w}):null})});import{memo as gi,useCallback as Ci}from"react";import{CheckboxIcon as vi,WarnCommit as hi}from"@vuu-ui/vuu-ui-controls";import{Checkbox as xi}from"@salt-ds/core";var Me=(e,o)=>e.column===o.column&&e.column.valueFormatter(e.row[e.columnMap[e.column.name]])===o.column.valueFormatter(o.row[o.columnMap[o.column.name]]);import{dispatchCustomEvent as wi,registerComponent as Ti}from"@vuu-ui/vuu-utils";import{jsx as Ht}from"react/jsx-runtime";var Pt=gi(({column:e,columnMap:o,onCommit:t=hi,row:r})=>{let n=o[e.name],l=r[n],s=Ci(i=>async a=>{let u=await t(i);return u===!0&&wi(a.target,"vuu-commit"),u},[t]);return e.editable?Ht(xi,{checked:l,onClick:s(!l)}):Ht(vi,{checked:l,disabled:!0})},Me);Pt.displayName="CheckboxCell";Ti("checkbox-cell",Pt,"cell-renderer",{serverDataType:"boolean"});import{registerComponent as Ri}from"@vuu-ui/vuu-utils";import{Input as yi}from"@salt-ds/core";import{useEditableText as Di}from"@vuu-ui/vuu-ui-controls";import Mi from"clsx";import{jsx as no}from"react/jsx-runtime";var He="vuuTableInputCell",Hi=()=>(console.warn("onCommit handler has not been provided to InputCell cell renderer"),Promise.resolve(!0)),Pi=({column:e,columnMap:o,onCommit:t=Hi,row:r})=>{let n=o[e.name],{align:l="left",clientSideEditValidationCheck:s}=e,{warningMessage:i,...a}=Di({initialValue:r[n],onCommit:t,clientSideEditValidationCheck:s}),u=i&&l==="left"?no("span",{className:`${He}-icon`,"data-icon":"error"}):void 0,c=i&&l==="right"?no("span",{className:`${He}-icon`,"data-icon":"error"}):void 0;return no(yi,{...a,className:Mi(He,{[`${He}-error`]:i!==void 0}),endAdornment:u,startAdornment:c})};Ri("input-cell",Pi,"cell-renderer",{});import{WarnCommit as Ei}from"@vuu-ui/vuu-ui-controls";import{dispatchCustomEvent as Si,isTypeDescriptor as ki,isValueListRenderer as Li,registerComponent as Ai}from"@vuu-ui/vuu-utils";import Ii from"clsx";import{memo as zi,useCallback as Ni}from"react";import{CycleStateButton as Fi}from"@vuu-ui/vuu-ui-controls";import{jsx as $i}from"react/jsx-runtime";var Et="vuuTableToggleCell",Ki=({name:e,type:o})=>{if(ki(o)&&Li(o.renderer))return o.renderer.values;throw Error(`useLookupValues column ${e} has not been configured with a values list`)},Vi=zi(function({column:o,columnMap:t,onCommit:r=Ei,row:n}){let l=Ki(o),s=t[o.name],i=n[s],a=Ni((u,c)=>r(c).then(d=>(d===!0&&Si(u.target,"vuu-commit"),d)),[r]);return $i(Fi,{className:Ii(Et,`${Et}-${o.name}`),onCommit:a,value:i,values:l,variant:"cta",children:i})},Me);Ai("toggle-cell",Vi,"cell-renderer",{});import{useStateRef as Gi}from"@vuu-ui/vuu-ui-controls";import{dispatchMouseEvent as Bi}from"@vuu-ui/vuu-utils";import{useCallback as St,useRef as Oi}from"react";var nd=(e,o)=>{let t=Oi(null),[r,n]=Gi(e),l=St(i=>{var a;if(i.key==="ArrowDown")n((u=-1)=>Math.min(o-1,u+1));else if(i.key==="ArrowUp")n((u=-1)=>Math.max(0,u-1));else if(i.key==="Enter"||i.key===" "){let{current:u}=r,c=(a=t.current)==null?void 0:a.querySelector(`[aria-rowindex="${u}"]`);c&&Bi(c,"click")}},[r,o,n]),s=St(i=>{n(i)},[n]);return{highlightedIndexRef:r,onHighlight:s,onKeyDown:l,tableRef:t}};export{Pt as CheckboxCell,Ve as GroupHeaderCellNext,yo as HeaderCell,Pi as InputCell,um as Table,Ho as TableCell,Po as TableGroupCell,Vi as ToggleCell,Me as dataAndColumnUnchanged,Sl as howFarIsRowOutsideViewport,tt as isShowColumnSettings,nt as isShowTableSettings,Pl as noScrolling,No as updateTableConfig,nd as useControlledTableNavigation,rt as useTableModel,ct as useTableScroll,dt as useTableViewport};
1
+ // src/header-cell/GroupHeaderCellNext.tsx
2
+ import { OverflowContainer } from "@vuu-ui/vuu-layout";
3
+ import { useLayoutEffectSkipFirst } from "@vuu-ui/vuu-utils";
4
+ import cx3 from "clsx";
5
+ import { useCallback as useCallback4, useRef as useRef3, useState as useState2 } from "react";
6
+
7
+ // src/column-header-pill/ColumnHeaderPill.tsx
8
+ import cx from "clsx";
9
+ import { useCallback } from "react";
10
+ import { jsx, jsxs } from "react/jsx-runtime";
11
+ var classBase = "vuuColumnHeaderPill";
12
+ var ColumnHeaderPill = ({
13
+ children,
14
+ className,
15
+ column,
16
+ onRemove,
17
+ removable,
18
+ ...htmlAttributes
19
+ }) => {
20
+ if (removable && typeof onRemove !== "function") {
21
+ throw Error(
22
+ "ColumnHeaderPill onRemove prop must be provided if Pill is removable"
23
+ );
24
+ }
25
+ const handleClickRemove = useCallback(
26
+ (evt) => {
27
+ evt.preventDefault();
28
+ evt.stopPropagation();
29
+ onRemove == null ? void 0 : onRemove(column);
30
+ },
31
+ [column, onRemove]
32
+ );
33
+ return /* @__PURE__ */ jsxs("div", { ...htmlAttributes, className: cx(classBase, className), children: [
34
+ children,
35
+ removable ? /* @__PURE__ */ jsx(
36
+ "span",
37
+ {
38
+ className: `${classBase}-removeButton`,
39
+ role: "button",
40
+ "data-icon": "cross",
41
+ onClick: handleClickRemove
42
+ }
43
+ ) : null
44
+ ] });
45
+ };
46
+
47
+ // src/column-header-pill/GroupColumnPill.tsx
48
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
49
+ var GroupColumnPill = ({
50
+ column,
51
+ ...columnHeaderProps
52
+ }) => {
53
+ const { name, sorted } = column;
54
+ const icon = typeof sorted === "number" ? sorted < 0 ? "arrow-down" : "arrow-up" : sorted === "A" ? "arrow-up" : sorted === "D" ? "arrow-down" : void 0;
55
+ return /* @__PURE__ */ jsxs2(ColumnHeaderPill, { ...columnHeaderProps, column, children: [
56
+ /* @__PURE__ */ jsx2("span", { className: "vuuGroupColumnPill-label", children: name }),
57
+ icon !== void 0 ? /* @__PURE__ */ jsx2("span", { "data-icon": icon }) : null,
58
+ typeof sorted === "number" ? /* @__PURE__ */ jsx2("span", { className: "vuuSortPosition", children: Math.abs(sorted) }) : null
59
+ ] });
60
+ };
61
+
62
+ // src/column-header-pill/SortIndicator.tsx
63
+ import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
64
+ var SortIndicator = ({ column }) => {
65
+ if (!column.sorted) {
66
+ return null;
67
+ }
68
+ const icon = typeof column.sorted === "number" ? column.sorted < 0 ? "arrow-down" : "arrow-up" : column.sorted === "A" ? "arrow-up" : "arrow-down";
69
+ return /* @__PURE__ */ jsxs3(ColumnHeaderPill, { column, children: [
70
+ /* @__PURE__ */ jsx3("span", { "data-icon": icon }),
71
+ typeof column.sorted === "number" ? /* @__PURE__ */ jsx3("span", { className: "vuuSortPosition", children: Math.abs(column.sorted) }) : null
72
+ ] });
73
+ };
74
+
75
+ // src/column-resizing/ColumnResizer.tsx
76
+ import { useCallback as useCallback2, useRef } from "react";
77
+ import { jsx as jsx4 } from "react/jsx-runtime";
78
+ var NOOP = () => void 0;
79
+ var baseClass = "vuuColumnResizerNext";
80
+ var ColumnResizer = ({
81
+ onDrag,
82
+ onDragEnd = NOOP,
83
+ onDragStart = NOOP
84
+ }) => {
85
+ const position = useRef(0);
86
+ const onMouseMove = useCallback2(
87
+ (e) => {
88
+ if (e.stopPropagation) {
89
+ e.stopPropagation();
90
+ }
91
+ if (e.preventDefault) {
92
+ e.preventDefault();
93
+ }
94
+ const x = Math.round(e.clientX);
95
+ const moveBy = x - position.current;
96
+ position.current = x;
97
+ if (moveBy !== 0) {
98
+ onDrag(e, moveBy);
99
+ }
100
+ },
101
+ [onDrag]
102
+ );
103
+ const onMouseUp = useCallback2(
104
+ (e) => {
105
+ window.removeEventListener("mouseup", onMouseUp);
106
+ window.removeEventListener("mousemove", onMouseMove);
107
+ onDragEnd(e);
108
+ },
109
+ [onDragEnd, onMouseMove]
110
+ );
111
+ const handleMouseDown = useCallback2(
112
+ (e) => {
113
+ onDragStart(e);
114
+ position.current = Math.round(e.clientX);
115
+ window.addEventListener("mouseup", onMouseUp);
116
+ window.addEventListener("mousemove", onMouseMove);
117
+ if (e.stopPropagation) {
118
+ e.stopPropagation();
119
+ }
120
+ if (e.preventDefault) {
121
+ e.preventDefault();
122
+ }
123
+ },
124
+ [onDragStart, onMouseMove, onMouseUp]
125
+ );
126
+ return /* @__PURE__ */ jsx4("div", { className: baseClass, onMouseDown: handleMouseDown });
127
+ };
128
+
129
+ // src/column-resizing/useTableColumnResize.tsx
130
+ import { useCallback as useCallback3, useRef as useRef2, useState } from "react";
131
+ var useTableColumnResize = ({
132
+ column,
133
+ onResize,
134
+ rootRef
135
+ }) => {
136
+ const widthRef = useRef2(0);
137
+ const [isResizing, setResizing] = useState(false);
138
+ const { name } = column;
139
+ const handleResizeStart = useCallback3(() => {
140
+ if (onResize && rootRef.current) {
141
+ const { width } = rootRef.current.getBoundingClientRect();
142
+ widthRef.current = Math.round(width);
143
+ setResizing(true);
144
+ onResize == null ? void 0 : onResize("begin", name);
145
+ }
146
+ }, [name, onResize, rootRef]);
147
+ const handleResize = useCallback3(
148
+ (_evt, moveBy) => {
149
+ if (rootRef.current) {
150
+ if (onResize) {
151
+ const { width } = rootRef.current.getBoundingClientRect();
152
+ const newWidth = Math.round(width) + moveBy;
153
+ if (newWidth !== widthRef.current && newWidth > 0) {
154
+ onResize("resize", name, newWidth);
155
+ widthRef.current = newWidth;
156
+ }
157
+ }
158
+ }
159
+ },
160
+ [name, onResize, rootRef]
161
+ );
162
+ const handleResizeEnd = useCallback3(() => {
163
+ if (onResize) {
164
+ onResize("end", name, widthRef.current);
165
+ setTimeout(() => {
166
+ setResizing(false);
167
+ }, 80);
168
+ }
169
+ }, [name, onResize]);
170
+ return {
171
+ isResizing,
172
+ onDrag: handleResize,
173
+ onDragStart: handleResizeStart,
174
+ onDragEnd: handleResizeEnd
175
+ };
176
+ };
177
+
178
+ // src/useCell.ts
179
+ import { getColumnStyle } from "@vuu-ui/vuu-utils";
180
+ import cx2 from "clsx";
181
+ import { useMemo } from "react";
182
+ var useCell = (column, classBase10, isHeader) => (
183
+ // TODO measure perf without the memo, might not be worth the cost
184
+ useMemo(() => {
185
+ const className = cx2(classBase10, {
186
+ vuuPinFloating: column.pin === "floating",
187
+ vuuPinLeft: column.pin === "left",
188
+ vuuPinRight: column.pin === "right",
189
+ vuuEndPin: isHeader && column.endPin,
190
+ // [`${classBase}-resizing`]: column.resizing,
191
+ [`${classBase10}-editable`]: column.editable,
192
+ [`${classBase10}-right`]: column.align === "right"
193
+ });
194
+ const style = getColumnStyle(column);
195
+ return {
196
+ className,
197
+ style
198
+ };
199
+ }, [column, classBase10, isHeader])
200
+ );
201
+
202
+ // src/header-cell/GroupHeaderCellNext.tsx
203
+ import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
204
+ import { createElement } from "react";
205
+ var classBase2 = "vuuTableGroupHeaderCell";
206
+ var switchIfChanged = (columns, newColumns) => {
207
+ if (columns === newColumns) {
208
+ return columns;
209
+ } else {
210
+ return newColumns;
211
+ }
212
+ };
213
+ var GroupHeaderCellNext = ({
214
+ column: groupColumn,
215
+ className: classNameProp,
216
+ onMoveColumn,
217
+ onRemoveColumn,
218
+ onResize,
219
+ ...htmlAttributes
220
+ }) => {
221
+ const rootRef = useRef3(null);
222
+ const { isResizing, ...resizeProps } = useTableColumnResize({
223
+ column: groupColumn,
224
+ onResize,
225
+ rootRef
226
+ });
227
+ const [columns, setColumns] = useState2(groupColumn.columns);
228
+ const { className, style } = useCell(groupColumn, classBase2, true);
229
+ const columnPillProps = columns.length > 1 ? {
230
+ removable: true,
231
+ onRemove: onRemoveColumn
232
+ } : void 0;
233
+ const handleMoveItem = useCallback4(
234
+ (fromIndex, toIndex) => {
235
+ setColumns((cols) => {
236
+ const newCols = cols.slice();
237
+ const [tab] = newCols.splice(fromIndex, 1);
238
+ if (toIndex === -1) {
239
+ const result = newCols.concat(tab);
240
+ onMoveColumn == null ? void 0 : onMoveColumn(result);
241
+ return result;
242
+ } else {
243
+ newCols.splice(toIndex, 0, tab);
244
+ onMoveColumn == null ? void 0 : onMoveColumn(newCols);
245
+ return newCols;
246
+ }
247
+ });
248
+ },
249
+ [onMoveColumn]
250
+ );
251
+ useLayoutEffectSkipFirst(() => {
252
+ setColumns((cols) => switchIfChanged(cols, groupColumn.columns));
253
+ }, [groupColumn.columns]);
254
+ return /* @__PURE__ */ jsxs4(
255
+ "div",
256
+ {
257
+ ...htmlAttributes,
258
+ className: cx3(className, classNameProp, {
259
+ [`${classBase2}-pending`]: groupColumn.groupConfirmed === false
260
+ }),
261
+ ref: rootRef,
262
+ role: "columnheader",
263
+ style,
264
+ children: [
265
+ /* @__PURE__ */ jsx5(
266
+ OverflowContainer,
267
+ {
268
+ allowDragDrop: true,
269
+ className: `${classBase2}-inner`,
270
+ height: 24,
271
+ onMoveItem: handleMoveItem,
272
+ overflowPosition: "start",
273
+ children: columns.map((column) => {
274
+ return /* @__PURE__ */ createElement(
275
+ GroupColumnPill,
276
+ {
277
+ ...columnPillProps,
278
+ column,
279
+ key: column.key
280
+ }
281
+ );
282
+ })
283
+ }
284
+ ),
285
+ /* @__PURE__ */ jsx5(
286
+ ColumnHeaderPill,
287
+ {
288
+ column: groupColumn,
289
+ removable: true,
290
+ onRemove: onRemoveColumn
291
+ }
292
+ ),
293
+ groupColumn.resizeable !== false ? /* @__PURE__ */ jsx5(ColumnResizer, { ...resizeProps }) : null
294
+ ]
295
+ }
296
+ );
297
+ };
298
+
299
+ // src/header-cell/HeaderCell.tsx
300
+ import cx5 from "clsx";
301
+ import { useCallback as useCallback6, useRef as useRef5 } from "react";
302
+
303
+ // src/column-menu/ColumnMenu.tsx
304
+ import { useContextMenu } from "@vuu-ui/vuu-popups";
305
+ import cx4 from "clsx";
306
+ import {
307
+ useCallback as useCallback5,
308
+ useRef as useRef4,
309
+ useState as useState3
310
+ } from "react";
311
+ import { jsx as jsx6 } from "react/jsx-runtime";
312
+ var getPosition = (element) => {
313
+ if (element) {
314
+ const { bottom, left } = element.getBoundingClientRect();
315
+ return { x: left, y: bottom + 6 };
316
+ }
317
+ };
318
+ var ColumnMenu = ({
319
+ className,
320
+ column,
321
+ ...props
322
+ }) => {
323
+ const rootRef = useRef4(null);
324
+ const [menuOpen, setMenuOpen] = useState3(false);
325
+ const [showContextMenu] = useContextMenu();
326
+ const handleMenuClose = useCallback5(() => {
327
+ setMenuOpen(false);
328
+ }, []);
329
+ const showColumnMenu = useCallback5(
330
+ (e) => {
331
+ setMenuOpen(true);
332
+ showContextMenu(e, "column-menu", {
333
+ column,
334
+ ContextMenuProps: {
335
+ onClose: handleMenuClose,
336
+ position: getPosition(rootRef.current)
337
+ }
338
+ });
339
+ },
340
+ [column, handleMenuClose, showContextMenu]
341
+ );
342
+ return /* @__PURE__ */ jsx6(
343
+ "span",
344
+ {
345
+ ...props,
346
+ className: cx4("vuuTable-columnMenu", className, {
347
+ "vuuTable-columnMenu-open": menuOpen
348
+ }),
349
+ "data-icon": "more-vert",
350
+ onClick: showColumnMenu,
351
+ ref: rootRef
352
+ }
353
+ );
354
+ };
355
+
356
+ // src/header-cell/HeaderCell.tsx
357
+ import { jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
358
+ var classBase3 = "vuuTableHeaderCell";
359
+ var HeaderCell = ({
360
+ className: classNameProp,
361
+ column,
362
+ onClick,
363
+ onResize,
364
+ ...htmlAttributes
365
+ }) => {
366
+ var _a;
367
+ const { HeaderCellContentRenderer, HeaderCellLabelRenderer } = column;
368
+ const rootRef = useRef5(null);
369
+ const { isResizing, ...resizeProps } = useTableColumnResize({
370
+ column,
371
+ onResize,
372
+ rootRef
373
+ });
374
+ const handleClick = useCallback6(
375
+ (evt) => {
376
+ !isResizing && (onClick == null ? void 0 : onClick(evt));
377
+ },
378
+ [isResizing, onClick]
379
+ );
380
+ const { className, style } = useCell(column, classBase3, true);
381
+ const columnMenu = /* @__PURE__ */ jsx7(ColumnMenu, { column });
382
+ const columnLabel = HeaderCellLabelRenderer ? /* @__PURE__ */ jsx7(HeaderCellLabelRenderer, { className: `${classBase3}-label`, column }) : /* @__PURE__ */ jsx7("div", { className: `${classBase3}-label`, children: (_a = column.label) != null ? _a : column.name });
383
+ const columnContent = HeaderCellContentRenderer ? [/* @__PURE__ */ jsx7(HeaderCellContentRenderer, { column }, "content")] : [];
384
+ const sortIndicator = /* @__PURE__ */ jsx7(SortIndicator, { column });
385
+ const headerItems = column.align === "right" ? [sortIndicator, columnLabel].concat(columnContent).concat(columnMenu) : [columnMenu, columnLabel, sortIndicator].concat(columnContent);
386
+ return /* @__PURE__ */ jsxs5(
387
+ "div",
388
+ {
389
+ ...htmlAttributes,
390
+ className: cx5(className, classNameProp, {
391
+ [`${classBase3}-resizing`]: isResizing
392
+ }),
393
+ onClick: handleClick,
394
+ ref: rootRef,
395
+ role: "columnheader",
396
+ style,
397
+ children: [
398
+ ...headerItems,
399
+ column.resizeable !== false ? /* @__PURE__ */ jsx7(ColumnResizer, { ...resizeProps }) : null
400
+ ]
401
+ }
402
+ );
403
+ };
404
+
405
+ // src/Table.tsx
406
+ import {
407
+ MeasuredContainer
408
+ } from "@vuu-ui/vuu-layout";
409
+ import { ContextMenuProvider } from "@vuu-ui/vuu-popups";
410
+ import { metadataKeys as metadataKeys7, useId } from "@vuu-ui/vuu-utils";
411
+ import { useForkRef } from "@salt-ds/core";
412
+ import cx9 from "clsx";
413
+ import {
414
+ forwardRef,
415
+ useRef as useRef14,
416
+ useState as useState7
417
+ } from "react";
418
+
419
+ // src/Row.tsx
420
+ import {
421
+ isGroupColumn,
422
+ isJsonColumn,
423
+ isJsonGroup,
424
+ metadataKeys as metadataKeys2,
425
+ isNotHidden,
426
+ RowSelected
427
+ } from "@vuu-ui/vuu-utils";
428
+ import cx7 from "clsx";
429
+ import { memo, useCallback as useCallback9 } from "react";
430
+
431
+ // src/table-cell/TableCell.tsx
432
+ import { isNumericColumn } from "@vuu-ui/vuu-utils";
433
+ import { useCallback as useCallback7 } from "react";
434
+ import { jsx as jsx8 } from "react/jsx-runtime";
435
+ var classBase4 = "vuuTableCell";
436
+ var TableCell = ({
437
+ column,
438
+ columnMap,
439
+ onClick,
440
+ onDataEdited,
441
+ row
442
+ }) => {
443
+ const { className, style } = useCell(column, classBase4);
444
+ const { CellRenderer, name, valueFormatter } = column;
445
+ const dataIdx = columnMap[name];
446
+ const handleDataItemEdited = useCallback7(
447
+ (value) => {
448
+ if (onDataEdited) {
449
+ let typedValue = value;
450
+ if (isNumericColumn(column) && typeof value === "string") {
451
+ typedValue = column.serverDataType === "double" ? parseFloat(value) : parseInt(value);
452
+ }
453
+ return onDataEdited == null ? void 0 : onDataEdited(row, name, typedValue);
454
+ } else {
455
+ throw Error(
456
+ "TableCell onDataEdited prop not supplied for an editable cell"
457
+ );
458
+ }
459
+ },
460
+ [column, name, onDataEdited, row]
461
+ );
462
+ const handleClick = useCallback7(
463
+ (evt) => {
464
+ onClick == null ? void 0 : onClick(evt, column);
465
+ },
466
+ [column, onClick]
467
+ );
468
+ return /* @__PURE__ */ jsx8(
469
+ "div",
470
+ {
471
+ className,
472
+ onClick: onClick ? handleClick : void 0,
473
+ role: "cell",
474
+ style,
475
+ children: CellRenderer ? /* @__PURE__ */ jsx8(
476
+ CellRenderer,
477
+ {
478
+ column,
479
+ columnMap,
480
+ onCommit: handleDataItemEdited,
481
+ row
482
+ }
483
+ ) : valueFormatter(row[dataIdx])
484
+ }
485
+ );
486
+ };
487
+
488
+ // src/table-cell/TableGroupCell.tsx
489
+ import { getGroupValueAndOffset, metadataKeys } from "@vuu-ui/vuu-utils";
490
+ import { useCallback as useCallback8 } from "react";
491
+ import cx6 from "clsx";
492
+ import { jsx as jsx9, jsxs as jsxs6 } from "react/jsx-runtime";
493
+ var { IS_LEAF } = metadataKeys;
494
+ var classBase5 = "vuuTableGroupCell";
495
+ var TableGroupCell = ({ column, onClick, row }) => {
496
+ const { columns } = column;
497
+ const [value, offset] = getGroupValueAndOffset(columns, row);
498
+ const { className, style } = useCell(column, classBase5);
499
+ const handleClick = useCallback8(
500
+ (evt) => {
501
+ onClick == null ? void 0 : onClick(evt, column);
502
+ },
503
+ [column, onClick]
504
+ );
505
+ const isLeaf = row[IS_LEAF];
506
+ const spacers = Array(offset).fill(0).map((n, i) => /* @__PURE__ */ jsx9("span", { className: `${classBase5}-spacer` }, i));
507
+ return /* @__PURE__ */ jsxs6(
508
+ "div",
509
+ {
510
+ className: cx6(className, "vuuTableCell"),
511
+ role: "cell",
512
+ style,
513
+ onClick: isLeaf ? void 0 : handleClick,
514
+ children: [
515
+ spacers,
516
+ isLeaf ? null : /* @__PURE__ */ jsx9("span", { className: `${classBase5}-toggle`, "data-icon": "triangle-right" }),
517
+ /* @__PURE__ */ jsx9("span", { children: value })
518
+ ]
519
+ }
520
+ );
521
+ };
522
+
523
+ // src/Row.tsx
524
+ import { jsx as jsx10 } from "react/jsx-runtime";
525
+ import { createElement as createElement2 } from "react";
526
+ var { IDX, IS_EXPANDED, SELECTED } = metadataKeys2;
527
+ var classBase6 = "vuuTableRow";
528
+ var Row = memo(
529
+ ({
530
+ className: classNameProp,
531
+ columnMap,
532
+ columns,
533
+ highlighted,
534
+ row,
535
+ offset,
536
+ onClick,
537
+ onDataEdited,
538
+ onToggleGroup,
539
+ zebraStripes = false,
540
+ ...htmlAttributes
541
+ }) => {
542
+ const {
543
+ [IDX]: rowIndex,
544
+ [IS_EXPANDED]: isExpanded,
545
+ [SELECTED]: selectionStatus
546
+ } = row;
547
+ const handleRowClick = useCallback9(
548
+ (evt) => {
549
+ const rangeSelect = evt.shiftKey;
550
+ const keepExistingSelection = evt.ctrlKey || evt.metaKey;
551
+ onClick == null ? void 0 : onClick(row, rangeSelect, keepExistingSelection);
552
+ },
553
+ [onClick, row]
554
+ );
555
+ const { True, First, Last } = RowSelected;
556
+ const className = cx7(classBase6, classNameProp, {
557
+ [`${classBase6}-even`]: zebraStripes && rowIndex % 2 === 0,
558
+ [`${classBase6}-expanded`]: isExpanded,
559
+ [`${classBase6}-highlighted`]: highlighted,
560
+ [`${classBase6}-selected`]: selectionStatus & True,
561
+ [`${classBase6}-selectedStart`]: selectionStatus & First,
562
+ [`${classBase6}-selectedEnd`]: selectionStatus & Last
563
+ });
564
+ const style = { transform: `translate3d(0px, ${offset}px, 0px)` };
565
+ const handleGroupCellClick = useCallback9(
566
+ (evt, column) => {
567
+ if (isGroupColumn(column) || isJsonGroup(column, row)) {
568
+ evt.stopPropagation();
569
+ onToggleGroup == null ? void 0 : onToggleGroup(row, column);
570
+ }
571
+ },
572
+ [onToggleGroup, row]
573
+ );
574
+ return /* @__PURE__ */ createElement2(
575
+ "div",
576
+ {
577
+ ...htmlAttributes,
578
+ key: `row-${row[0]}`,
579
+ role: "row",
580
+ className,
581
+ onClick: handleRowClick,
582
+ style
583
+ },
584
+ /* @__PURE__ */ jsx10("span", { className: `${classBase6}-selectionDecorator vuuStickyLeft` }),
585
+ columns.filter(isNotHidden).map((column) => {
586
+ const isGroup = isGroupColumn(column);
587
+ const isJsonCell = isJsonColumn(column);
588
+ const Cell = isGroup ? TableGroupCell : TableCell;
589
+ return /* @__PURE__ */ jsx10(
590
+ Cell,
591
+ {
592
+ column,
593
+ columnMap,
594
+ onClick: isGroup || isJsonCell ? handleGroupCellClick : void 0,
595
+ onDataEdited,
596
+ row
597
+ },
598
+ column.key
599
+ );
600
+ }),
601
+ /* @__PURE__ */ jsx10("span", { className: `${classBase6}-selectionDecorator vuuStickyRight` })
602
+ );
603
+ }
604
+ );
605
+ Row.displayName = "Row";
606
+
607
+ // src/useTable.ts
608
+ import {
609
+ useDragDrop
610
+ } from "@vuu-ui/vuu-ui-controls";
611
+ import {
612
+ applySort,
613
+ buildColumnMap as buildColumnMap2,
614
+ getIndexFromRowElement as getIndexFromRowElement3,
615
+ isGroupColumn as isGroupColumn3,
616
+ isJsonGroup as isJsonGroup2,
617
+ isValidNumber,
618
+ metadataKeys as metadataKeys6,
619
+ updateColumn,
620
+ useLayoutEffectSkipFirst as useLayoutEffectSkipFirst2
621
+ } from "@vuu-ui/vuu-utils";
622
+ import {
623
+ useCallback as useCallback18,
624
+ useEffect as useEffect4,
625
+ useMemo as useMemo6,
626
+ useState as useState6
627
+ } from "react";
628
+
629
+ // src/context-menu/buildContextMenuDescriptors.ts
630
+ import { isNumericColumn as isNumericColumn2 } from "@vuu-ui/vuu-utils";
631
+ var buildContextMenuDescriptors = (dataSource) => (location, options) => {
632
+ const descriptors = [];
633
+ if (dataSource === void 0) {
634
+ return descriptors;
635
+ }
636
+ if (location === "header" || location === "column-menu") {
637
+ descriptors.push(
638
+ ...buildSortMenuItems(options, dataSource)
639
+ );
640
+ descriptors.push(
641
+ ...buildGroupMenuItems(options, dataSource)
642
+ );
643
+ descriptors.push(
644
+ ...buildAggregationMenuItems(options, dataSource)
645
+ );
646
+ descriptors.push(...buildColumnDisplayMenuItems(options));
647
+ descriptors.push({
648
+ action: "column-settings",
649
+ icon: "cog",
650
+ label: `Column Settings`,
651
+ options
652
+ });
653
+ descriptors.push({
654
+ action: "table-settings",
655
+ icon: "cog",
656
+ label: `DataGrid Settings`,
657
+ options
658
+ });
659
+ }
660
+ return descriptors;
661
+ };
662
+ function buildSortMenuItems(options, { sort: { sortDefs } }) {
663
+ const { column } = options;
664
+ const menuItems = [];
665
+ if (column === void 0) {
666
+ return menuItems;
667
+ }
668
+ const hasSort = sortDefs.length > 0;
669
+ if (column.sorted === "A") {
670
+ menuItems.push({
671
+ label: "Reverse Sort (DSC)",
672
+ action: "sort-dsc",
673
+ options
674
+ });
675
+ } else if (column.sorted === "D") {
676
+ menuItems.push({
677
+ label: "Reverse Sort (ASC)",
678
+ action: "sort-asc",
679
+ options
680
+ });
681
+ } else if (typeof column.sorted === "number") {
682
+ if (column.sorted > 0) {
683
+ menuItems.push({
684
+ label: "Reverse Sort (DSC)",
685
+ action: "sort-add-dsc",
686
+ options
687
+ });
688
+ } else {
689
+ menuItems.push({
690
+ label: "Reverse Sort (ASC)",
691
+ action: "sort-add-asc",
692
+ options
693
+ });
694
+ }
695
+ if (hasSort && Math.abs(column.sorted) < sortDefs.length) {
696
+ menuItems.push({
697
+ label: "Remove from sort",
698
+ action: "sort-remove",
699
+ options
700
+ });
701
+ }
702
+ menuItems.push({
703
+ label: "New Sort",
704
+ children: [
705
+ { label: "Ascending", action: "sort-asc", options },
706
+ { label: "Descending", action: "sort-dsc", options }
707
+ ]
708
+ });
709
+ } else if (hasSort) {
710
+ menuItems.push({
711
+ label: "Add to sort",
712
+ children: [
713
+ { label: "Ascending", action: "sort-add-asc", options },
714
+ { label: "Descending", action: "sort-add-dsc", options }
715
+ ]
716
+ });
717
+ menuItems.push({
718
+ label: "New Sort",
719
+ children: [
720
+ { label: "Ascending", action: "sort-asc", options },
721
+ { label: "Descending", action: "sort-dsc", options }
722
+ ]
723
+ });
724
+ } else {
725
+ menuItems.push({
726
+ label: "Sort",
727
+ children: [
728
+ { label: "Ascending", action: "sort-asc", options },
729
+ { label: "Descending", action: "sort-dsc", options }
730
+ ]
731
+ });
732
+ }
733
+ return menuItems;
734
+ }
735
+ function buildAggregationMenuItems(options, dataSource) {
736
+ const { column } = options;
737
+ if (column === void 0 || dataSource.groupBy.length === 0) {
738
+ return [];
739
+ }
740
+ const { name, label = name } = column;
741
+ return [
742
+ {
743
+ label: `Aggregate ${label}`,
744
+ children: [
745
+ { label: "Count", action: "agg-count", options },
746
+ { label: "Distinct", action: "agg-distinct", options }
747
+ ].concat(
748
+ isNumericColumn2(column) ? [
749
+ { label: "Sum", action: "agg-sum", options },
750
+ { label: "Avg", action: "agg-avg", options },
751
+ { label: "High", action: "agg-high", options },
752
+ { label: "Low", action: "agg-low", options }
753
+ ] : []
754
+ )
755
+ }
756
+ ];
757
+ }
758
+ var pinColumn = (options, pinLocation) => ({
759
+ label: `Pin ${pinLocation}`,
760
+ action: `column-pin-${pinLocation}`,
761
+ options
762
+ });
763
+ var pinLeft = (options) => pinColumn(options, "left");
764
+ var pinFloating = (options) => pinColumn(options, "floating");
765
+ var pinRight = (options) => pinColumn(options, "right");
766
+ function buildColumnDisplayMenuItems(options) {
767
+ const { column } = options;
768
+ if (column === void 0) {
769
+ return [];
770
+ }
771
+ const { pin } = column;
772
+ const menuItems = [
773
+ {
774
+ label: `Hide column`,
775
+ action: "column-hide",
776
+ options
777
+ },
778
+ {
779
+ label: `Remove column`,
780
+ action: "column-remove",
781
+ options
782
+ }
783
+ ];
784
+ if (pin === void 0) {
785
+ menuItems.push({
786
+ label: `Pin column`,
787
+ children: [pinLeft(options), pinFloating(options), pinRight(options)]
788
+ });
789
+ } else if (pin === "left") {
790
+ menuItems.push(
791
+ { label: "Unpin column", action: "column-unpin", options },
792
+ {
793
+ label: `Pin column`,
794
+ children: [pinFloating(options), pinRight(options)]
795
+ }
796
+ );
797
+ } else if (pin === "right") {
798
+ menuItems.push(
799
+ { label: "Unpin column", action: "column-unpin", options },
800
+ {
801
+ label: `Pin column`,
802
+ children: [pinLeft(options), pinFloating(options)]
803
+ }
804
+ );
805
+ } else if (pin === "floating") {
806
+ menuItems.push(
807
+ { label: "Unpin column", action: "column-unpin", options },
808
+ {
809
+ label: `Pin column`,
810
+ children: [pinLeft(options), pinRight(options)]
811
+ }
812
+ );
813
+ }
814
+ return menuItems;
815
+ }
816
+ function buildGroupMenuItems(options, { groupBy }) {
817
+ const { column } = options;
818
+ const menuItems = [];
819
+ if (column === void 0) {
820
+ return menuItems;
821
+ }
822
+ const { name, label = name } = column;
823
+ if (groupBy.length === 0) {
824
+ menuItems.push({
825
+ label: `Group by ${label}`,
826
+ action: "group",
827
+ options
828
+ });
829
+ } else {
830
+ menuItems.push({
831
+ label: `Add ${label} to group by`,
832
+ action: "group-add",
833
+ options
834
+ });
835
+ }
836
+ return menuItems;
837
+ }
838
+
839
+ // src/context-menu/useHandleTableContextMenu.ts
840
+ import { removeColumnFromFilter } from "@vuu-ui/vuu-utils";
841
+ import {
842
+ addGroupColumn,
843
+ addSortColumn,
844
+ AggregationType,
845
+ setAggregations,
846
+ setSortColumn
847
+ } from "@vuu-ui/vuu-utils";
848
+ var removeFilterColumn = (dataSourceFilter, column) => {
849
+ if (dataSourceFilter.filterStruct && column) {
850
+ const [filterStruct, filter] = removeColumnFromFilter(
851
+ column,
852
+ dataSourceFilter.filterStruct
853
+ );
854
+ return {
855
+ filter,
856
+ filterStruct
857
+ };
858
+ } else {
859
+ return dataSourceFilter;
860
+ }
861
+ };
862
+ var { Average, Count, Distinct, High, Low, Sum } = AggregationType;
863
+ var useHandleTableContextMenu = ({
864
+ dataSource,
865
+ onPersistentColumnOperation
866
+ }) => {
867
+ const handleContextMenuAction = (action) => {
868
+ const gridOptions = action.options;
869
+ if (gridOptions.column && dataSource) {
870
+ const { column } = gridOptions;
871
+ switch (action.menuId) {
872
+ case "sort-asc":
873
+ return dataSource.sort = setSortColumn(dataSource.sort, column, "A"), true;
874
+ case "sort-dsc":
875
+ return dataSource.sort = setSortColumn(dataSource.sort, column, "D"), true;
876
+ case "sort-add-asc":
877
+ return dataSource.sort = addSortColumn(dataSource.sort, column, "A"), true;
878
+ case "sort-add-dsc":
879
+ return dataSource.sort = addSortColumn(dataSource.sort, column, "D"), true;
880
+ case "group":
881
+ return dataSource.groupBy = addGroupColumn(dataSource.groupBy, column), true;
882
+ case "group-add":
883
+ return dataSource.groupBy = addGroupColumn(dataSource.groupBy, column), true;
884
+ case "column-hide":
885
+ return onPersistentColumnOperation({ type: "hideColumns", columns: [column] }), true;
886
+ case "column-remove":
887
+ return dataSource.columns = dataSource.columns.filter((name) => name !== column.name), true;
888
+ case "filter-remove-column":
889
+ return dataSource.filter = removeFilterColumn(dataSource.filter, column), true;
890
+ case "remove-filters":
891
+ return dataSource.filter = { filter: "" }, true;
892
+ case "agg-avg":
893
+ return dataSource.aggregations = setAggregations(dataSource.aggregations, column, Average), true;
894
+ case "agg-high":
895
+ return dataSource.aggregations = setAggregations(dataSource.aggregations, column, High), true;
896
+ case "agg-low":
897
+ return dataSource.aggregations = setAggregations(dataSource.aggregations, column, Low), true;
898
+ case "agg-count":
899
+ return dataSource.aggregations = setAggregations(dataSource.aggregations, column, Count), true;
900
+ case "agg-distinct":
901
+ return dataSource.aggregations = setAggregations(dataSource.aggregations, column, Distinct), true;
902
+ case "agg-sum":
903
+ return dataSource.aggregations = setAggregations(dataSource.aggregations, column, Sum), true;
904
+ case "column-pin-floating":
905
+ return onPersistentColumnOperation({ type: "pinColumn", column, pin: "floating" }), true;
906
+ case "column-pin-left":
907
+ return onPersistentColumnOperation({ type: "pinColumn", column, pin: "left" }), true;
908
+ case "column-pin-right":
909
+ return onPersistentColumnOperation({ type: "pinColumn", column, pin: "right" }), true;
910
+ case "column-unpin":
911
+ return onPersistentColumnOperation({ type: "pinColumn", column, pin: void 0 }), true;
912
+ case "column-settings":
913
+ return onPersistentColumnOperation({ type: "columnSettings", column }), true;
914
+ case "table-settings":
915
+ return onPersistentColumnOperation({ type: "tableSettings" }), true;
916
+ default:
917
+ }
918
+ }
919
+ return false;
920
+ };
921
+ return handleContextMenuAction;
922
+ };
923
+
924
+ // src/table-config.ts
925
+ var updateTableConfig = (config, action) => {
926
+ switch (action.type) {
927
+ case "col-size":
928
+ return {
929
+ ...config,
930
+ columns: config.columns.map(
931
+ (col) => col.name === action.column.name ? { ...col, width: action.width } : col
932
+ )
933
+ };
934
+ case "column-prop":
935
+ return {
936
+ ...config,
937
+ columns: config.columns.map(
938
+ (col) => col.name === action.column.name ? { ...col, [action.property]: action.value } : col
939
+ )
940
+ };
941
+ default:
942
+ return config;
943
+ }
944
+ };
945
+
946
+ // src/useCellEditing.ts
947
+ import { isCharacterKey } from "@vuu-ui/vuu-utils";
948
+ import {
949
+ useCallback as useCallback10
950
+ } from "react";
951
+
952
+ // src/table-dom-utils.ts
953
+ var headerCellQuery = (colIdx) => `.vuuTable-col-headers .vuuTableHeaderCell:nth-child(${colIdx})`;
954
+ var dataCellQuery = (rowIdx, colIdx) => `.vuuTable-body > [aria-rowindex='${rowIdx + 1}'] > [role='cell']:nth-child(${colIdx + 1})`;
955
+ var getTableCell = (containerRef, [rowIdx, colIdx]) => {
956
+ var _a;
957
+ const cssQuery = rowIdx === -1 ? headerCellQuery(colIdx) : dataCellQuery(rowIdx, colIdx);
958
+ const cell = (_a = containerRef.current) == null ? void 0 : _a.querySelector(
959
+ cssQuery
960
+ );
961
+ if (cellIsEditable(cell)) {
962
+ const focusableContent = cell.querySelector("button");
963
+ return focusableContent || cell;
964
+ } else {
965
+ return cell;
966
+ }
967
+ };
968
+ var cellIsEditable = (cell) => cell.classList.contains("vuuTableCell-editable");
969
+ var cellIsTextInput = (cell) => cell.querySelector(".vuuTableInputCell") !== null;
970
+ function getRowIndex(rowEl) {
971
+ if (rowEl) {
972
+ const idx = rowEl.ariaRowIndex;
973
+ if (idx !== null) {
974
+ return parseInt(idx, 10) - 1;
975
+ }
976
+ }
977
+ return -1;
978
+ }
979
+ var closestRow = (el) => el.closest('[role="row"]');
980
+ var closestRowIndex = (el) => getRowIndex(closestRow(el));
981
+
982
+ // src/useCellEditing.ts
983
+ var useCellEditing = ({ navigate }) => {
984
+ const commitHandler = useCallback10(() => {
985
+ navigate();
986
+ }, [navigate]);
987
+ const editInput = useCallback10(
988
+ (evt) => {
989
+ const cellEl = evt.target;
990
+ const input = cellEl.matches("input") ? cellEl : cellEl.querySelector("input");
991
+ if (input) {
992
+ input.focus();
993
+ input.select();
994
+ }
995
+ },
996
+ []
997
+ );
998
+ const focusInput = useCallback10(
999
+ (evt) => {
1000
+ const cellEl = evt.target;
1001
+ const input = cellEl.querySelector("input");
1002
+ if (input) {
1003
+ input.focus();
1004
+ input.select();
1005
+ }
1006
+ },
1007
+ []
1008
+ );
1009
+ const handleKeyDown = useCallback10(
1010
+ (e) => {
1011
+ const el = e.target;
1012
+ if (cellIsTextInput(el)) {
1013
+ if (isCharacterKey(e.key)) {
1014
+ editInput(e);
1015
+ } else if (e.key === "Enter") {
1016
+ focusInput(e);
1017
+ }
1018
+ }
1019
+ },
1020
+ [editInput, focusInput]
1021
+ );
1022
+ const handleDoubleClick = useCallback10(
1023
+ (e) => {
1024
+ const el = e.target;
1025
+ if (el.matches("input") || el.querySelector("input")) {
1026
+ editInput(e);
1027
+ e.stopPropagation();
1028
+ }
1029
+ },
1030
+ [editInput]
1031
+ );
1032
+ const handleBlur = useCallback10(
1033
+ (e) => {
1034
+ const el = e.target;
1035
+ el.removeEventListener("vuu-commit", commitHandler, true);
1036
+ },
1037
+ [commitHandler]
1038
+ );
1039
+ const handleFocus = useCallback10(
1040
+ (e) => {
1041
+ const el = e.target;
1042
+ el.addEventListener("vuu-commit", commitHandler, true);
1043
+ },
1044
+ [commitHandler]
1045
+ );
1046
+ return {
1047
+ onBlur: handleBlur,
1048
+ onDoubleClick: handleDoubleClick,
1049
+ onFocus: handleFocus,
1050
+ onKeyDown: handleKeyDown
1051
+ };
1052
+ };
1053
+
1054
+ // src/useDataSource.ts
1055
+ import { getFullRange, NULL_RANGE } from "@vuu-ui/vuu-utils";
1056
+ import { useCallback as useCallback11, useEffect, useMemo as useMemo2, useRef as useRef6, useState as useState4 } from "react";
1057
+
1058
+ // src/moving-window.ts
1059
+ import {
1060
+ isRowSelectedLast,
1061
+ metadataKeys as metadataKeys3,
1062
+ WindowRange
1063
+ } from "@vuu-ui/vuu-utils";
1064
+ var { SELECTED: SELECTED2 } = metadataKeys3;
1065
+ var MovingWindow = class {
1066
+ constructor({ from, to }) {
1067
+ this.rowCount = 0;
1068
+ this.setRowCount = (rowCount) => {
1069
+ if (rowCount < this.data.length) {
1070
+ this.data.length = rowCount;
1071
+ }
1072
+ this.rowCount = rowCount;
1073
+ };
1074
+ this.range = new WindowRange(from, to);
1075
+ this.data = new Array(Math.max(0, to - from));
1076
+ this.rowCount = 0;
1077
+ }
1078
+ add(data) {
1079
+ const [index] = data;
1080
+ if (this.isWithinRange(index)) {
1081
+ const internalIndex = index - this.range.from;
1082
+ this.data[internalIndex] = data;
1083
+ if (data[SELECTED2]) {
1084
+ const previousRow = this.data[internalIndex - 1];
1085
+ if (isRowSelectedLast(previousRow)) {
1086
+ this.data[internalIndex - 1] = previousRow.slice();
1087
+ this.data[internalIndex - 1][SELECTED2] -= 4;
1088
+ }
1089
+ }
1090
+ }
1091
+ }
1092
+ getAtIndex(index) {
1093
+ return this.range.isWithin(index) && this.data[index - this.range.from] != null ? this.data[index - this.range.from] : void 0;
1094
+ }
1095
+ isWithinRange(index) {
1096
+ return this.range.isWithin(index);
1097
+ }
1098
+ setRange({ from, to }) {
1099
+ if (from !== this.range.from || to !== this.range.to) {
1100
+ const [overlapFrom, overlapTo] = this.range.overlap(from, to);
1101
+ const newData = new Array(Math.max(0, to - from));
1102
+ for (let i = overlapFrom; i < overlapTo; i++) {
1103
+ const data = this.getAtIndex(i);
1104
+ if (data) {
1105
+ const index = i - from;
1106
+ newData[index] = data;
1107
+ }
1108
+ }
1109
+ this.data = newData;
1110
+ this.range.from = from;
1111
+ this.range.to = to;
1112
+ }
1113
+ }
1114
+ getSelectedRows() {
1115
+ return this.data.filter((row) => row[SELECTED2] !== 0);
1116
+ }
1117
+ };
1118
+
1119
+ // src/useDataSource.ts
1120
+ var isVuuFeatureInvocation = (action) => action.type === "vuu-link-created" || action.type === "vuu-link-removed";
1121
+ var useDataSource = ({
1122
+ dataSource,
1123
+ onFeatureInvocation,
1124
+ onSizeChange,
1125
+ onSubscribed,
1126
+ range = NULL_RANGE,
1127
+ renderBufferSize = 0
1128
+ }) => {
1129
+ const [, forceUpdate] = useState4(null);
1130
+ const data = useRef6([]);
1131
+ const isMounted = useRef6(true);
1132
+ const hasUpdated = useRef6(false);
1133
+ const rangeRef = useRef6(NULL_RANGE);
1134
+ const dataWindow = useMemo2(
1135
+ () => new MovingWindow(getFullRange(range, renderBufferSize)),
1136
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1137
+ []
1138
+ );
1139
+ const setData = useCallback11(
1140
+ (updates) => {
1141
+ for (const row of updates) {
1142
+ dataWindow.add(row);
1143
+ }
1144
+ data.current = dataWindow.data;
1145
+ if (isMounted.current) {
1146
+ forceUpdate({});
1147
+ } else {
1148
+ console.log(`ignore update as we're not mounted`);
1149
+ }
1150
+ },
1151
+ [dataWindow]
1152
+ );
1153
+ const datasourceMessageHandler = useCallback11(
1154
+ (message) => {
1155
+ if (message.type === "subscribed") {
1156
+ onSubscribed == null ? void 0 : onSubscribed(message);
1157
+ } else if (message.type === "viewport-update") {
1158
+ if (typeof message.size === "number") {
1159
+ onSizeChange == null ? void 0 : onSizeChange(message.size);
1160
+ dataWindow.setRowCount(message.size);
1161
+ }
1162
+ if (message.rows) {
1163
+ setData(message.rows);
1164
+ } else if (typeof message.size === "number") {
1165
+ data.current = dataWindow.data;
1166
+ hasUpdated.current = true;
1167
+ }
1168
+ } else if (isVuuFeatureInvocation(message)) {
1169
+ onFeatureInvocation == null ? void 0 : onFeatureInvocation(message);
1170
+ } else {
1171
+ console.log(`useDataSource unexpected message ${message.type}`);
1172
+ }
1173
+ },
1174
+ [dataWindow, onFeatureInvocation, onSizeChange, onSubscribed, setData]
1175
+ );
1176
+ const getSelectedRows = useCallback11(() => {
1177
+ return dataWindow.getSelectedRows();
1178
+ }, [dataWindow]);
1179
+ useEffect(() => {
1180
+ var _a;
1181
+ isMounted.current = true;
1182
+ (_a = dataSource.resume) == null ? void 0 : _a.call(dataSource);
1183
+ return () => {
1184
+ var _a2;
1185
+ isMounted.current = false;
1186
+ (_a2 = dataSource.suspend) == null ? void 0 : _a2.call(dataSource);
1187
+ };
1188
+ }, [dataSource]);
1189
+ useEffect(() => {
1190
+ var _a;
1191
+ if (dataSource.status === "disabled") {
1192
+ (_a = dataSource.enable) == null ? void 0 : _a.call(dataSource, datasourceMessageHandler);
1193
+ } else {
1194
+ dataSource == null ? void 0 : dataSource.subscribe(
1195
+ { range: getFullRange(range, renderBufferSize) },
1196
+ datasourceMessageHandler
1197
+ );
1198
+ }
1199
+ }, [dataSource, datasourceMessageHandler, range, renderBufferSize]);
1200
+ const setRange = useCallback11(
1201
+ (range2) => {
1202
+ const fullRange = getFullRange(range2, renderBufferSize);
1203
+ dataWindow.setRange(fullRange);
1204
+ dataSource.range = rangeRef.current = fullRange;
1205
+ dataSource.emit("range", range2);
1206
+ },
1207
+ [dataSource, dataWindow, renderBufferSize]
1208
+ );
1209
+ return {
1210
+ data: data.current,
1211
+ dataRef: data,
1212
+ getSelectedRows,
1213
+ range: rangeRef.current,
1214
+ setRange
1215
+ };
1216
+ };
1217
+
1218
+ // src/useInitialValue.ts
1219
+ import { useMemo as useMemo3, useRef as useRef7 } from "react";
1220
+ var useInitialValue = (value) => {
1221
+ const ref = useRef7(value);
1222
+ return useMemo3(() => ref.current, []);
1223
+ };
1224
+
1225
+ // src/useKeyboardNavigation.ts
1226
+ import { getIndexFromRowElement } from "@vuu-ui/vuu-utils";
1227
+ import { useControlled } from "@salt-ds/core";
1228
+ import {
1229
+ useCallback as useCallback12,
1230
+ useEffect as useEffect2,
1231
+ useRef as useRef8
1232
+ } from "react";
1233
+ var rowNavigationKeys = /* @__PURE__ */ new Set([
1234
+ "Home",
1235
+ "End",
1236
+ "PageUp",
1237
+ "PageDown",
1238
+ "ArrowDown",
1239
+ "ArrowUp"
1240
+ ]);
1241
+ var cellNavigationKeys = new Set(rowNavigationKeys);
1242
+ cellNavigationKeys.add("ArrowLeft");
1243
+ cellNavigationKeys.add("ArrowRight");
1244
+ var isNavigationKey = (key, navigationStyle) => {
1245
+ switch (navigationStyle) {
1246
+ case "cell":
1247
+ return cellNavigationKeys.has(key);
1248
+ case "row":
1249
+ return rowNavigationKeys.has(key);
1250
+ default:
1251
+ return false;
1252
+ }
1253
+ };
1254
+ var PageKeys = ["Home", "End", "PageUp", "PageDown"];
1255
+ var isPagingKey = (key) => PageKeys.includes(key);
1256
+ var NULL_CELL_POS = [-1, -1];
1257
+ function nextCellPos(key, [rowIdx, colIdx], columnCount, rowCount) {
1258
+ if (key === "ArrowUp") {
1259
+ if (rowIdx > -1) {
1260
+ return [rowIdx - 1, colIdx];
1261
+ } else {
1262
+ return [rowIdx, colIdx];
1263
+ }
1264
+ } else if (key === "ArrowDown") {
1265
+ if (rowIdx === -1) {
1266
+ return [0, colIdx];
1267
+ } else if (rowIdx === rowCount - 1) {
1268
+ return [rowIdx, colIdx];
1269
+ } else {
1270
+ return [rowIdx + 1, colIdx];
1271
+ }
1272
+ } else if (key === "ArrowRight") {
1273
+ if (colIdx < columnCount) {
1274
+ return [rowIdx, colIdx + 1];
1275
+ } else {
1276
+ return [rowIdx, colIdx];
1277
+ }
1278
+ } else if (key === "ArrowLeft") {
1279
+ if (colIdx > 1) {
1280
+ return [rowIdx, colIdx - 1];
1281
+ } else {
1282
+ return [rowIdx, colIdx];
1283
+ }
1284
+ }
1285
+ return [rowIdx, colIdx];
1286
+ }
1287
+ var useKeyboardNavigation = ({
1288
+ columnCount = 0,
1289
+ containerRef,
1290
+ disableFocus = false,
1291
+ defaultHighlightedIndex,
1292
+ disableHighlightOnFocus,
1293
+ highlightedIndex: highlightedIndexProp,
1294
+ navigationStyle,
1295
+ requestScroll,
1296
+ onHighlight,
1297
+ rowCount = 0,
1298
+ viewportRowCount
1299
+ }) => {
1300
+ var _a;
1301
+ const focusedCellPos = useRef8([-1, -1]);
1302
+ const focusableCell = useRef8();
1303
+ const activeCellPos = useRef8([-1, 0]);
1304
+ const highlightedIndexRef = useRef8();
1305
+ const [highlightedIndex, setHighlightedIdx] = useControlled({
1306
+ controlled: highlightedIndexProp,
1307
+ default: defaultHighlightedIndex,
1308
+ name: "UseKeyboardNavigation"
1309
+ });
1310
+ highlightedIndexRef.current = highlightedIndex;
1311
+ const setHighlightedIndex = useCallback12(
1312
+ (idx, fromKeyboard = false) => {
1313
+ onHighlight == null ? void 0 : onHighlight(idx);
1314
+ setHighlightedIdx(idx);
1315
+ if (fromKeyboard) {
1316
+ }
1317
+ },
1318
+ [onHighlight, setHighlightedIdx]
1319
+ );
1320
+ const getFocusedCell = (element) => element == null ? void 0 : element.closest(
1321
+ "[role='columnHeader'],[role='cell']"
1322
+ );
1323
+ const getTableCellPos = (tableCell) => {
1324
+ var _a2;
1325
+ if (tableCell.role === "columnHeader") {
1326
+ const colIdx = parseInt((_a2 = tableCell.dataset.idx) != null ? _a2 : "-1", 10);
1327
+ return [-1, colIdx];
1328
+ } else {
1329
+ const focusedRow = tableCell.closest("[role='row']");
1330
+ if (focusedRow) {
1331
+ const rowIdx = getIndexFromRowElement(focusedRow);
1332
+ const colIdx = Array.from(focusedRow.childNodes).indexOf(tableCell);
1333
+ return [rowIdx, colIdx];
1334
+ }
1335
+ }
1336
+ return NULL_CELL_POS;
1337
+ };
1338
+ const focusCell = useCallback12(
1339
+ (cellPos) => {
1340
+ var _a2;
1341
+ if (containerRef.current) {
1342
+ const activeCell = getTableCell(containerRef, cellPos);
1343
+ if (activeCell) {
1344
+ if (activeCell !== focusableCell.current) {
1345
+ (_a2 = focusableCell.current) == null ? void 0 : _a2.removeAttribute("tabindex");
1346
+ focusableCell.current = activeCell;
1347
+ activeCell.setAttribute("tabindex", "0");
1348
+ }
1349
+ console.log(`scroll row ${cellPos[0]}`);
1350
+ requestScroll == null ? void 0 : requestScroll({ type: "scroll-row", rowIndex: cellPos[0] });
1351
+ activeCell.focus({ preventScroll: true });
1352
+ }
1353
+ }
1354
+ },
1355
+ // TODO we recreate this function whenever viewportRange changes, which will
1356
+ // be often whilst scrolling - store range in a a ref ?
1357
+ [containerRef, requestScroll]
1358
+ );
1359
+ const setActiveCell = useCallback12(
1360
+ (rowIdx, colIdx, fromKeyboard = false) => {
1361
+ const pos = [rowIdx, colIdx];
1362
+ activeCellPos.current = pos;
1363
+ if (navigationStyle === "row") {
1364
+ setHighlightedIdx(rowIdx);
1365
+ } else {
1366
+ focusCell(pos);
1367
+ }
1368
+ if (fromKeyboard) {
1369
+ focusedCellPos.current = pos;
1370
+ }
1371
+ },
1372
+ [focusCell, navigationStyle, setHighlightedIdx]
1373
+ );
1374
+ const nextPageItemIdx = useCallback12(
1375
+ (key, [rowIdx, colIdx]) => new Promise((resolve) => {
1376
+ let newRowIdx = rowIdx;
1377
+ switch (key) {
1378
+ case "PageDown":
1379
+ newRowIdx = Math.min(rowCount - 1, rowIdx + viewportRowCount);
1380
+ requestScroll == null ? void 0 : requestScroll({ type: "scroll-page", direction: "down" });
1381
+ break;
1382
+ case "PageUp":
1383
+ newRowIdx = Math.max(0, rowIdx - viewportRowCount);
1384
+ requestScroll == null ? void 0 : requestScroll({ type: "scroll-page", direction: "up" });
1385
+ break;
1386
+ case "Home":
1387
+ newRowIdx = 0;
1388
+ requestScroll == null ? void 0 : requestScroll({ type: "scroll-end", direction: "home" });
1389
+ break;
1390
+ case "End":
1391
+ newRowIdx = rowCount - 1;
1392
+ requestScroll == null ? void 0 : requestScroll({ type: "scroll-end", direction: "end" });
1393
+ break;
1394
+ }
1395
+ setTimeout(() => {
1396
+ resolve([newRowIdx, colIdx]);
1397
+ }, 90);
1398
+ }),
1399
+ [requestScroll, rowCount, viewportRowCount]
1400
+ );
1401
+ const handleFocus = useCallback12(() => {
1402
+ var _a2;
1403
+ if (disableHighlightOnFocus !== true) {
1404
+ if ((_a2 = containerRef.current) == null ? void 0 : _a2.contains(document.activeElement)) {
1405
+ const focusedCell = getFocusedCell(document.activeElement);
1406
+ if (focusedCell) {
1407
+ focusedCellPos.current = getTableCellPos(focusedCell);
1408
+ if (navigationStyle === "row") {
1409
+ setHighlightedIdx(focusedCellPos.current[0]);
1410
+ }
1411
+ }
1412
+ }
1413
+ }
1414
+ }, [
1415
+ disableHighlightOnFocus,
1416
+ containerRef,
1417
+ navigationStyle,
1418
+ setHighlightedIdx
1419
+ ]);
1420
+ const navigateChildItems = useCallback12(
1421
+ async (key) => {
1422
+ const [nextRowIdx, nextColIdx] = isPagingKey(key) ? await nextPageItemIdx(key, activeCellPos.current) : nextCellPos(key, activeCellPos.current, columnCount, rowCount);
1423
+ const [rowIdx, colIdx] = activeCellPos.current;
1424
+ if (nextRowIdx !== rowIdx || nextColIdx !== colIdx) {
1425
+ setActiveCell(nextRowIdx, nextColIdx, true);
1426
+ }
1427
+ },
1428
+ [columnCount, nextPageItemIdx, rowCount, setActiveCell]
1429
+ );
1430
+ const scrollRowIntoViewIfNecessary = useCallback12(
1431
+ (rowIndex) => {
1432
+ requestScroll == null ? void 0 : requestScroll({ type: "scroll-row", rowIndex });
1433
+ },
1434
+ [requestScroll]
1435
+ );
1436
+ const moveHighlightedRow = useCallback12(
1437
+ async (key) => {
1438
+ const { current: highlighted } = highlightedIndexRef;
1439
+ const [nextRowIdx] = isPagingKey(key) ? await nextPageItemIdx(key, [highlighted != null ? highlighted : -1, 0]) : nextCellPos(key, [highlighted != null ? highlighted : -1, 0], columnCount, rowCount);
1440
+ if (nextRowIdx !== highlighted) {
1441
+ setHighlightedIndex(nextRowIdx);
1442
+ scrollRowIntoViewIfNecessary(nextRowIdx);
1443
+ }
1444
+ },
1445
+ [
1446
+ columnCount,
1447
+ nextPageItemIdx,
1448
+ rowCount,
1449
+ scrollRowIntoViewIfNecessary,
1450
+ setHighlightedIndex
1451
+ ]
1452
+ );
1453
+ useEffect2(() => {
1454
+ if (highlightedIndexProp !== void 0 && highlightedIndexProp !== -1) {
1455
+ scrollRowIntoViewIfNecessary(highlightedIndexProp);
1456
+ }
1457
+ }, [highlightedIndexProp, scrollRowIntoViewIfNecessary]);
1458
+ const handleKeyDown = useCallback12(
1459
+ (e) => {
1460
+ if (rowCount > 0 && isNavigationKey(e.key, navigationStyle)) {
1461
+ e.preventDefault();
1462
+ e.stopPropagation();
1463
+ if (navigationStyle === "row") {
1464
+ moveHighlightedRow(e.key);
1465
+ } else {
1466
+ void navigateChildItems(e.key);
1467
+ }
1468
+ }
1469
+ },
1470
+ [rowCount, navigationStyle, moveHighlightedRow, navigateChildItems]
1471
+ );
1472
+ const handleClick = useCallback12(
1473
+ // Might not be a cell e.g the Settings button
1474
+ (evt) => {
1475
+ const target = evt.target;
1476
+ const focusedCell = getFocusedCell(target);
1477
+ if (focusedCell) {
1478
+ const [rowIdx, colIdx] = getTableCellPos(focusedCell);
1479
+ setActiveCell(rowIdx, colIdx);
1480
+ }
1481
+ },
1482
+ [setActiveCell]
1483
+ );
1484
+ const handleMouseLeave = useCallback12(() => {
1485
+ setHighlightedIndex(-1);
1486
+ }, [setHighlightedIndex]);
1487
+ const handleMouseMove = useCallback12(
1488
+ (evt) => {
1489
+ const idx = closestRowIndex(evt.target);
1490
+ if (idx !== -1 && idx !== highlightedIndexRef.current) {
1491
+ setHighlightedIndex(idx);
1492
+ }
1493
+ },
1494
+ [setHighlightedIndex]
1495
+ );
1496
+ const navigate = useCallback12(() => {
1497
+ navigateChildItems("ArrowDown");
1498
+ }, [navigateChildItems]);
1499
+ const fullyRendered = ((_a = containerRef.current) == null ? void 0 : _a.firstChild) != null;
1500
+ useEffect2(() => {
1501
+ if (fullyRendered && focusableCell.current === void 0 && !disableFocus) {
1502
+ const { current: container } = containerRef;
1503
+ const cell = (container == null ? void 0 : container.querySelector(headerCellQuery(0))) || (container == null ? void 0 : container.querySelector(dataCellQuery(0, 0)));
1504
+ if (cell) {
1505
+ cell.setAttribute("tabindex", "0");
1506
+ focusableCell.current = cell;
1507
+ }
1508
+ }
1509
+ }, [containerRef, disableFocus, fullyRendered]);
1510
+ return {
1511
+ highlightedIndexRef,
1512
+ navigate,
1513
+ onClick: handleClick,
1514
+ onFocus: handleFocus,
1515
+ onKeyDown: handleKeyDown,
1516
+ onMouseLeave: navigationStyle === "row" ? handleMouseLeave : void 0,
1517
+ onMouseMove: navigationStyle === "row" ? handleMouseMove : void 0
1518
+ };
1519
+ };
1520
+
1521
+ // src/useSelection.ts
1522
+ import {
1523
+ deselectItem,
1524
+ dispatchMouseEvent,
1525
+ isRowSelected,
1526
+ metadataKeys as metadataKeys4,
1527
+ selectItem
1528
+ } from "@vuu-ui/vuu-utils";
1529
+ import {
1530
+ useCallback as useCallback13,
1531
+ useRef as useRef9
1532
+ } from "react";
1533
+ var { IDX: IDX2 } = metadataKeys4;
1534
+ var NO_SELECTION = [];
1535
+ var defaultSelectionKeys = ["Enter", " "];
1536
+ var useSelection = ({
1537
+ highlightedIndexRef,
1538
+ selectionKeys = defaultSelectionKeys,
1539
+ selectionModel,
1540
+ onSelect,
1541
+ onSelectionChange
1542
+ }) => {
1543
+ selectionModel === "extended" || selectionModel === "checkbox";
1544
+ const lastActiveRef = useRef9(-1);
1545
+ const selectedRef = useRef9(NO_SELECTION);
1546
+ const isSelectionEvent = useCallback13(
1547
+ (evt) => selectionKeys.includes(evt.key),
1548
+ [selectionKeys]
1549
+ );
1550
+ const handleRowClick = useCallback13(
1551
+ (row, rangeSelect, keepExistingSelection) => {
1552
+ const { [IDX2]: idx } = row;
1553
+ const { current: active } = lastActiveRef;
1554
+ const { current: selected } = selectedRef;
1555
+ const selectOperation = isRowSelected(row) ? deselectItem : selectItem;
1556
+ const newSelected = selectOperation(
1557
+ selectionModel,
1558
+ selected,
1559
+ idx,
1560
+ rangeSelect,
1561
+ keepExistingSelection,
1562
+ active
1563
+ );
1564
+ selectedRef.current = newSelected;
1565
+ lastActiveRef.current = idx;
1566
+ onSelect == null ? void 0 : onSelect(row);
1567
+ onSelectionChange == null ? void 0 : onSelectionChange(newSelected);
1568
+ },
1569
+ [onSelect, onSelectionChange, selectionModel]
1570
+ );
1571
+ const handleKeyDown = useCallback13(
1572
+ (e) => {
1573
+ if (isSelectionEvent(e)) {
1574
+ const { current: rowIndex } = highlightedIndexRef;
1575
+ if (rowIndex !== void 0 && rowIndex !== -1) {
1576
+ const rowEl = e.target.querySelector(
1577
+ `[aria-rowindex="${rowIndex}"]`
1578
+ );
1579
+ if (rowEl) {
1580
+ dispatchMouseEvent(rowEl, "click");
1581
+ }
1582
+ }
1583
+ }
1584
+ },
1585
+ [highlightedIndexRef, isSelectionEvent]
1586
+ );
1587
+ return {
1588
+ onKeyDown: handleKeyDown,
1589
+ onRowClick: handleRowClick
1590
+ };
1591
+ };
1592
+
1593
+ // src/useTableContextMenu.ts
1594
+ import { useContextMenu as usePopupContextMenu } from "@vuu-ui/vuu-popups";
1595
+ import { buildColumnMap, getIndexFromRowElement as getIndexFromRowElement2 } from "@vuu-ui/vuu-utils";
1596
+ import { useCallback as useCallback14 } from "react";
1597
+ var NO_ROWS = [];
1598
+ var useTableContextMenu = ({
1599
+ columns,
1600
+ data,
1601
+ dataSource,
1602
+ getSelectedRows
1603
+ }) => {
1604
+ const [showContextMenu] = usePopupContextMenu();
1605
+ const onContextMenu = useCallback14(
1606
+ (evt) => {
1607
+ const target = evt.target;
1608
+ const cellEl = target == null ? void 0 : target.closest("div[role='cell']");
1609
+ const rowEl = target == null ? void 0 : target.closest("div[role='row']");
1610
+ if (cellEl && rowEl) {
1611
+ const { selectedRowsCount } = dataSource;
1612
+ const columnMap = buildColumnMap(columns);
1613
+ const rowIndex = getIndexFromRowElement2(rowEl);
1614
+ const cellIndex = Array.from(rowEl.childNodes).indexOf(cellEl);
1615
+ const row = data.find(([idx]) => idx === rowIndex);
1616
+ const columnName = columns[cellIndex];
1617
+ showContextMenu(evt, "grid", {
1618
+ columnMap,
1619
+ columnName,
1620
+ row,
1621
+ selectedRows: selectedRowsCount === 0 ? NO_ROWS : getSelectedRows(),
1622
+ viewport: dataSource.viewport
1623
+ });
1624
+ }
1625
+ },
1626
+ [columns, data, dataSource, getSelectedRows, showContextMenu]
1627
+ );
1628
+ return onContextMenu;
1629
+ };
1630
+
1631
+ // src/useTableModel.ts
1632
+ import {
1633
+ applyFilterToColumns,
1634
+ applyGroupByToColumns,
1635
+ applySortToColumns,
1636
+ getCellRenderer,
1637
+ getColumnHeaderContentRenderer,
1638
+ getColumnHeaderLabelRenderer,
1639
+ getColumnLabel,
1640
+ getTableHeadings,
1641
+ getValueFormatter,
1642
+ hasValidationRules,
1643
+ isFilteredColumn,
1644
+ isGroupColumn as isGroupColumn2,
1645
+ isPinned,
1646
+ logger,
1647
+ metadataKeys as metadataKeys5,
1648
+ replaceColumn,
1649
+ sortPinnedColumns,
1650
+ stripFilterFromColumns,
1651
+ subscribedOnly
1652
+ } from "@vuu-ui/vuu-utils";
1653
+ import { buildValidationChecker } from "@vuu-ui/vuu-ui-controls";
1654
+ import { useReducer } from "react";
1655
+ var { info } = logger("useTableModel");
1656
+ var DEFAULT_COLUMN_WIDTH = 100;
1657
+ var KEY_OFFSET = metadataKeys5.count;
1658
+ var columnWithoutDataType = ({ serverDataType }) => serverDataType === void 0;
1659
+ var getDataType = (column, tableSchema) => {
1660
+ const schemaColumn = tableSchema == null ? void 0 : tableSchema.columns.find(
1661
+ ({ name }) => name === column.name
1662
+ );
1663
+ if (schemaColumn) {
1664
+ return schemaColumn.serverDataType;
1665
+ } else {
1666
+ return column.serverDataType;
1667
+ }
1668
+ };
1669
+ var numericTypes = ["int", "long", "double"];
1670
+ var getDefaultAlignment = (serverDataType) => serverDataType === void 0 ? void 0 : numericTypes.includes(serverDataType) ? "right" : "left";
1671
+ var isShowColumnSettings = (action) => action.type === "columnSettings";
1672
+ var isShowTableSettings = (action) => action.type === "tableSettings";
1673
+ var columnReducer = (state, action) => {
1674
+ info == null ? void 0 : info(`TableModelReducer ${action.type}`);
1675
+ switch (action.type) {
1676
+ case "init":
1677
+ return init(action);
1678
+ case "moveColumn":
1679
+ return moveColumn(state, action);
1680
+ case "resizeColumn":
1681
+ return resizeColumn(state, action);
1682
+ case "setTableSchema":
1683
+ return setTableSchema(state, action);
1684
+ case "hideColumns":
1685
+ return hideColumns(state, action);
1686
+ case "showColumns":
1687
+ return showColumns(state, action);
1688
+ case "pinColumn":
1689
+ return pinColumn2(state, action);
1690
+ case "updateColumnProp":
1691
+ return updateColumnProp(state, action);
1692
+ case "tableConfig":
1693
+ return updateTableConfig2(state, action);
1694
+ default:
1695
+ console.log(`unhandled action ${action.type}`);
1696
+ return state;
1697
+ }
1698
+ };
1699
+ var useTableModel = (tableConfigProp, dataSource) => {
1700
+ const [state, dispatchColumnAction] = useReducer(columnReducer, { tableConfig: tableConfigProp, dataSource }, init);
1701
+ const { columns, headings, tableConfig, ...tableAttributes } = state;
1702
+ return {
1703
+ columns,
1704
+ dispatchColumnAction,
1705
+ headings,
1706
+ tableAttributes,
1707
+ tableConfig
1708
+ };
1709
+ };
1710
+ function init({ dataSource, tableConfig }) {
1711
+ const { columns, ...tableAttributes } = tableConfig;
1712
+ const { config: dataSourceConfig, tableSchema } = dataSource;
1713
+ const runtimeColumns = columns.filter(subscribedOnly(dataSourceConfig == null ? void 0 : dataSourceConfig.columns)).map(
1714
+ columnDescriptorToRuntimeColumDescriptor(tableAttributes, tableSchema)
1715
+ );
1716
+ const maybePinnedColumns = runtimeColumns.some(isPinned) ? sortPinnedColumns(runtimeColumns) : runtimeColumns;
1717
+ let state = {
1718
+ columns: maybePinnedColumns,
1719
+ headings: getTableHeadings(maybePinnedColumns),
1720
+ tableConfig,
1721
+ ...tableAttributes
1722
+ };
1723
+ if (dataSourceConfig) {
1724
+ const { columns: _, ...rest } = dataSourceConfig;
1725
+ state = updateTableConfig2(state, {
1726
+ type: "tableConfig",
1727
+ ...rest
1728
+ });
1729
+ }
1730
+ return state;
1731
+ }
1732
+ var getLabel = (label, columnFormatHeader) => {
1733
+ if (columnFormatHeader === "uppercase") {
1734
+ return label.toUpperCase();
1735
+ } else if (columnFormatHeader === "capitalize") {
1736
+ return label[0].toUpperCase() + label.slice(1).toLowerCase();
1737
+ }
1738
+ return label;
1739
+ };
1740
+ var columnDescriptorToRuntimeColumDescriptor = (tableAttributes, tableSchema) => (column, index) => {
1741
+ const { columnDefaultWidth = DEFAULT_COLUMN_WIDTH, columnFormatHeader } = tableAttributes;
1742
+ const serverDataType = getDataType(column, tableSchema);
1743
+ const {
1744
+ align = getDefaultAlignment(serverDataType),
1745
+ key,
1746
+ name,
1747
+ label = getColumnLabel(column),
1748
+ width = columnDefaultWidth,
1749
+ ...rest
1750
+ } = column;
1751
+ const runtimeColumnWithDefaults = {
1752
+ ...rest,
1753
+ align,
1754
+ CellRenderer: getCellRenderer(column),
1755
+ HeaderCellContentRenderer: getColumnHeaderContentRenderer(column),
1756
+ HeaderCellLabelRenderer: getColumnHeaderLabelRenderer(column),
1757
+ clientSideEditValidationCheck: hasValidationRules(column.type) ? buildValidationChecker(column.type.renderer.rules) : void 0,
1758
+ label: getLabel(label, columnFormatHeader),
1759
+ key: key != null ? key : index + KEY_OFFSET,
1760
+ name,
1761
+ originalIdx: index,
1762
+ serverDataType,
1763
+ valueFormatter: getValueFormatter(column, serverDataType),
1764
+ width
1765
+ };
1766
+ if (isGroupColumn2(runtimeColumnWithDefaults)) {
1767
+ runtimeColumnWithDefaults.columns = runtimeColumnWithDefaults.columns.map(
1768
+ (col) => columnDescriptorToRuntimeColumDescriptor(tableAttributes)(
1769
+ col,
1770
+ col.key
1771
+ )
1772
+ );
1773
+ }
1774
+ return runtimeColumnWithDefaults;
1775
+ };
1776
+ function moveColumn(state, { column, moveBy }) {
1777
+ const { columns } = state;
1778
+ if (typeof moveBy === "number") {
1779
+ const idx = columns.indexOf(column);
1780
+ const newColumns = columns.slice();
1781
+ const [movedColumns] = newColumns.splice(idx, 1);
1782
+ newColumns.splice(idx + moveBy, 0, movedColumns);
1783
+ return {
1784
+ ...state,
1785
+ columns: newColumns
1786
+ };
1787
+ }
1788
+ return state;
1789
+ }
1790
+ function hideColumns(state, { columns }) {
1791
+ if (columns.some((col) => col.hidden !== true)) {
1792
+ return columns.reduce((s, c) => {
1793
+ if (c.hidden !== true) {
1794
+ return updateColumnProp(s, {
1795
+ type: "updateColumnProp",
1796
+ column: c,
1797
+ hidden: true
1798
+ });
1799
+ } else {
1800
+ return s;
1801
+ }
1802
+ }, state);
1803
+ } else {
1804
+ return state;
1805
+ }
1806
+ }
1807
+ function showColumns(state, { columns }) {
1808
+ if (columns.some((col) => col.hidden)) {
1809
+ return columns.reduce((s, c) => {
1810
+ if (c.hidden) {
1811
+ return updateColumnProp(s, {
1812
+ type: "updateColumnProp",
1813
+ column: c,
1814
+ hidden: false
1815
+ });
1816
+ } else {
1817
+ return s;
1818
+ }
1819
+ }, state);
1820
+ } else {
1821
+ return state;
1822
+ }
1823
+ }
1824
+ function resizeColumn(state, { column, phase, width }) {
1825
+ const type = "updateColumnProp";
1826
+ const resizing = phase !== "end";
1827
+ switch (phase) {
1828
+ case "begin":
1829
+ return updateColumnProp(state, { type, column, resizing });
1830
+ case "end":
1831
+ return updateColumnProp(state, { type, column, resizing, width });
1832
+ case "resize":
1833
+ return updateColumnProp(state, { type, column, width });
1834
+ default:
1835
+ throw Error(`useTableModel.resizeColumn, invalid resizePhase ${phase}`);
1836
+ }
1837
+ }
1838
+ function setTableSchema(state, { tableSchema }) {
1839
+ const { columns } = state;
1840
+ if (columns.some(columnWithoutDataType)) {
1841
+ const cols = columns.map((column) => {
1842
+ var _a;
1843
+ const serverDataType = getDataType(column, tableSchema);
1844
+ return {
1845
+ ...column,
1846
+ align: (_a = column.align) != null ? _a : getDefaultAlignment(serverDataType),
1847
+ serverDataType
1848
+ };
1849
+ });
1850
+ return {
1851
+ ...state,
1852
+ columns: cols
1853
+ };
1854
+ } else {
1855
+ return state;
1856
+ }
1857
+ }
1858
+ function pinColumn2(state, action) {
1859
+ let { columns } = state;
1860
+ const { column, pin } = action;
1861
+ const targetColumn = columns.find((col) => col.name === column.name);
1862
+ if (targetColumn) {
1863
+ columns = replaceColumn(columns, { ...targetColumn, pin });
1864
+ columns = sortPinnedColumns(columns);
1865
+ return {
1866
+ ...state,
1867
+ columns
1868
+ };
1869
+ } else {
1870
+ return state;
1871
+ }
1872
+ }
1873
+ function updateColumnProp(state, action) {
1874
+ let { columns, tableConfig } = state;
1875
+ const { align, column, hidden, label, resizing, width } = action;
1876
+ const targetColumn = columns.find((col) => col.name === column.name);
1877
+ if (targetColumn) {
1878
+ if (align === "left" || align === "right") {
1879
+ columns = replaceColumn(columns, { ...targetColumn, align });
1880
+ }
1881
+ if (typeof label === "string") {
1882
+ columns = replaceColumn(columns, { ...targetColumn, label });
1883
+ }
1884
+ if (typeof resizing === "boolean") {
1885
+ columns = replaceColumn(columns, { ...targetColumn, resizing });
1886
+ }
1887
+ if (typeof hidden === "boolean") {
1888
+ columns = replaceColumn(columns, { ...targetColumn, hidden });
1889
+ }
1890
+ if (typeof width === "number") {
1891
+ columns = replaceColumn(columns, { ...targetColumn, width });
1892
+ const targetConfigColumn = tableConfig.columns.find(
1893
+ (col) => col.name === column.name
1894
+ );
1895
+ if (targetConfigColumn) {
1896
+ tableConfig = {
1897
+ ...tableConfig,
1898
+ columns: replaceColumn(tableConfig.columns, {
1899
+ ...targetConfigColumn,
1900
+ width
1901
+ })
1902
+ };
1903
+ }
1904
+ }
1905
+ }
1906
+ return {
1907
+ ...state,
1908
+ columns,
1909
+ tableConfig
1910
+ };
1911
+ }
1912
+ function updateTableConfig2(state, { confirmed, filter, groupBy, sort }) {
1913
+ const hasGroupBy = groupBy !== void 0;
1914
+ const hasFilter = typeof (filter == null ? void 0 : filter.filter) === "string";
1915
+ const hasSort = sort && sort.sortDefs.length > 0;
1916
+ let result = state;
1917
+ if (hasGroupBy) {
1918
+ result = {
1919
+ ...state,
1920
+ columns: applyGroupByToColumns(result.columns, groupBy, confirmed)
1921
+ };
1922
+ }
1923
+ if (hasSort) {
1924
+ result = {
1925
+ ...state,
1926
+ columns: applySortToColumns(result.columns, sort)
1927
+ };
1928
+ }
1929
+ if (hasFilter) {
1930
+ result = {
1931
+ ...state,
1932
+ columns: applyFilterToColumns(result.columns, filter)
1933
+ };
1934
+ } else if (result.columns.some(isFilteredColumn)) {
1935
+ result = {
1936
+ ...state,
1937
+ columns: stripFilterFromColumns(result.columns)
1938
+ };
1939
+ }
1940
+ return result;
1941
+ }
1942
+
1943
+ // src/useTableScroll.ts
1944
+ import { getRowElementAtIndex } from "@vuu-ui/vuu-utils";
1945
+ import {
1946
+ useCallback as useCallback15,
1947
+ useEffect as useEffect3,
1948
+ useImperativeHandle,
1949
+ useMemo as useMemo4,
1950
+ useRef as useRef10
1951
+ } from "react";
1952
+ var getPctScroll = (container) => {
1953
+ const { scrollLeft, scrollTop } = container;
1954
+ const { clientHeight, clientWidth, scrollHeight, scrollWidth } = container;
1955
+ const pctScrollLeft = scrollLeft / (scrollWidth - clientWidth);
1956
+ const pctScrollTop = scrollTop / (scrollHeight - clientHeight);
1957
+ return [pctScrollLeft, pctScrollTop];
1958
+ };
1959
+ var noScrolling = {
1960
+ scrollToIndex: () => void 0,
1961
+ scrollToKey: () => void 0
1962
+ };
1963
+ var NO_SCROLL_NECESSARY = [void 0, void 0];
1964
+ var howFarIsRowOutsideViewport = (rowEl, totalHeaderHeight, contentContainer = rowEl.closest(".vuuTable-contentContainer")) => {
1965
+ if (contentContainer) {
1966
+ const viewport = contentContainer == null ? void 0 : contentContainer.getBoundingClientRect();
1967
+ const upperBoundary = viewport.top + totalHeaderHeight;
1968
+ const row = rowEl.getBoundingClientRect();
1969
+ if (row) {
1970
+ if (row.bottom > viewport.bottom) {
1971
+ return ["down", row.bottom - viewport.bottom];
1972
+ } else if (row.top < upperBoundary) {
1973
+ return ["up", row.top - upperBoundary];
1974
+ } else {
1975
+ return NO_SCROLL_NECESSARY;
1976
+ }
1977
+ } else {
1978
+ throw Error("Whats going on, row not found");
1979
+ }
1980
+ } else {
1981
+ throw Error("Whats going on, scrollbar container not found");
1982
+ }
1983
+ };
1984
+ var useCallbackRef = ({
1985
+ onAttach,
1986
+ onDetach
1987
+ }) => {
1988
+ const ref = useRef10(null);
1989
+ const callbackRef = useCallback15(
1990
+ (el) => {
1991
+ if (el) {
1992
+ ref.current = el;
1993
+ onAttach == null ? void 0 : onAttach(el);
1994
+ } else if (ref.current) {
1995
+ const { current: originalRef } = ref;
1996
+ ref.current = el;
1997
+ onDetach == null ? void 0 : onDetach(originalRef);
1998
+ }
1999
+ },
2000
+ [onAttach, onDetach]
2001
+ );
2002
+ return callbackRef;
2003
+ };
2004
+ var useTableScroll = ({
2005
+ getRowAtPosition,
2006
+ onHorizontalScroll,
2007
+ onVerticalScroll,
2008
+ scrollingApiRef,
2009
+ setRange,
2010
+ viewportMeasurements
2011
+ }) => {
2012
+ const firstRowRef = useRef10(0);
2013
+ const contentContainerScrolledRef = useRef10(false);
2014
+ const scrollPosRef = useRef10({ scrollTop: 0, scrollLeft: 0 });
2015
+ const scrollbarContainerRef = useRef10(null);
2016
+ const contentContainerRef = useRef10(null);
2017
+ const {
2018
+ appliedPageSize,
2019
+ isVirtualScroll,
2020
+ maxScrollContainerScrollHorizontal: maxScrollLeft,
2021
+ maxScrollContainerScrollVertical: maxScrollTop,
2022
+ rowCount: viewportRowCount,
2023
+ totalHeaderHeight
2024
+ } = viewportMeasurements;
2025
+ const handleVerticalScroll = useCallback15(
2026
+ (scrollTop, pctScrollTop) => {
2027
+ onVerticalScroll == null ? void 0 : onVerticalScroll(scrollTop, pctScrollTop);
2028
+ const firstRow = getRowAtPosition(scrollTop);
2029
+ if (firstRow !== firstRowRef.current) {
2030
+ firstRowRef.current = firstRow;
2031
+ setRange({ from: firstRow, to: firstRow + viewportRowCount + 1 });
2032
+ }
2033
+ },
2034
+ [getRowAtPosition, onVerticalScroll, setRange, viewportRowCount]
2035
+ );
2036
+ const handleScrollbarContainerScroll = useCallback15(() => {
2037
+ const { current: contentContainer } = contentContainerRef;
2038
+ const { current: scrollbarContainer } = scrollbarContainerRef;
2039
+ const { current: contentContainerScrolled } = contentContainerScrolledRef;
2040
+ if (contentContainerScrolled) {
2041
+ contentContainerScrolledRef.current = false;
2042
+ } else if (contentContainer && scrollbarContainer) {
2043
+ const [pctScrollLeft, pctScrollTop] = getPctScroll(scrollbarContainer);
2044
+ const rootScrollLeft = Math.round(pctScrollLeft * maxScrollLeft);
2045
+ const rootScrollTop = pctScrollTop * maxScrollTop;
2046
+ contentContainer.scrollTo({
2047
+ left: rootScrollLeft,
2048
+ top: rootScrollTop,
2049
+ behavior: "auto"
2050
+ });
2051
+ }
2052
+ }, [maxScrollLeft, maxScrollTop]);
2053
+ const handleContentContainerScroll = useCallback15(() => {
2054
+ const { current: contentContainer } = contentContainerRef;
2055
+ const { current: scrollbarContainer } = scrollbarContainerRef;
2056
+ const { current: scrollPos } = scrollPosRef;
2057
+ if (contentContainer && scrollbarContainer) {
2058
+ const { scrollLeft, scrollTop } = contentContainer;
2059
+ const [pctScrollLeft, pctScrollTop] = getPctScroll(contentContainer);
2060
+ contentContainerScrolledRef.current = true;
2061
+ scrollbarContainer.scrollLeft = Math.round(pctScrollLeft * maxScrollLeft);
2062
+ scrollbarContainer.scrollTop = pctScrollTop * maxScrollTop;
2063
+ if (scrollPos.scrollTop !== scrollTop) {
2064
+ scrollPos.scrollTop = scrollTop;
2065
+ handleVerticalScroll(scrollTop, pctScrollTop);
2066
+ }
2067
+ if (scrollPos.scrollLeft !== scrollLeft) {
2068
+ scrollPos.scrollLeft = scrollLeft;
2069
+ onHorizontalScroll == null ? void 0 : onHorizontalScroll(scrollLeft);
2070
+ }
2071
+ }
2072
+ }, [handleVerticalScroll, maxScrollLeft, maxScrollTop, onHorizontalScroll]);
2073
+ const handleAttachScrollbarContainer = useCallback15(
2074
+ (el) => {
2075
+ scrollbarContainerRef.current = el;
2076
+ el.addEventListener("scroll", handleScrollbarContainerScroll, {
2077
+ passive: true
2078
+ });
2079
+ },
2080
+ [handleScrollbarContainerScroll]
2081
+ );
2082
+ const handleDetachScrollbarContainer = useCallback15(
2083
+ (el) => {
2084
+ scrollbarContainerRef.current = null;
2085
+ el.removeEventListener("scroll", handleScrollbarContainerScroll);
2086
+ },
2087
+ [handleScrollbarContainerScroll]
2088
+ );
2089
+ const handleAttachContentContainer = useCallback15(
2090
+ (el) => {
2091
+ contentContainerRef.current = el;
2092
+ el.addEventListener("scroll", handleContentContainerScroll, {
2093
+ passive: true
2094
+ });
2095
+ },
2096
+ [handleContentContainerScroll]
2097
+ );
2098
+ const handleDetachContentContainer = useCallback15(
2099
+ (el) => {
2100
+ contentContainerRef.current = null;
2101
+ el.removeEventListener("scroll", handleContentContainerScroll);
2102
+ },
2103
+ [handleContentContainerScroll]
2104
+ );
2105
+ const contentContainerCallbackRef = useCallbackRef({
2106
+ onAttach: handleAttachContentContainer,
2107
+ onDetach: handleDetachContentContainer
2108
+ });
2109
+ const scrollbarContainerCallbackRef = useCallbackRef({
2110
+ onAttach: handleAttachScrollbarContainer,
2111
+ onDetach: handleDetachScrollbarContainer
2112
+ });
2113
+ const requestScroll = useCallback15(
2114
+ (scrollRequest) => {
2115
+ const { current: scrollbarContainer } = contentContainerRef;
2116
+ if (scrollbarContainer) {
2117
+ const { scrollLeft, scrollTop } = scrollbarContainer;
2118
+ contentContainerScrolledRef.current = false;
2119
+ if (scrollRequest.type === "scroll-row") {
2120
+ const activeRow = getRowElementAtIndex(
2121
+ scrollbarContainer,
2122
+ scrollRequest.rowIndex
2123
+ );
2124
+ if (activeRow !== null) {
2125
+ const [direction, distance] = howFarIsRowOutsideViewport(
2126
+ activeRow,
2127
+ totalHeaderHeight
2128
+ );
2129
+ if (direction && distance) {
2130
+ if (isVirtualScroll) {
2131
+ console.log(
2132
+ `virtual scroll row required ${direction} ${distance}
2133
+ first Row ${firstRowRef.current}`
2134
+ );
2135
+ } else {
2136
+ let newScrollLeft = scrollLeft;
2137
+ let newScrollTop = scrollTop;
2138
+ if (direction === "up" || direction === "down") {
2139
+ newScrollTop = Math.min(
2140
+ Math.max(0, scrollTop + distance),
2141
+ maxScrollTop
2142
+ );
2143
+ } else {
2144
+ newScrollLeft = Math.min(
2145
+ Math.max(0, scrollLeft + distance),
2146
+ maxScrollLeft
2147
+ );
2148
+ }
2149
+ scrollbarContainer.scrollTo({
2150
+ top: newScrollTop,
2151
+ left: newScrollLeft,
2152
+ behavior: "smooth"
2153
+ });
2154
+ }
2155
+ }
2156
+ }
2157
+ } else if (scrollRequest.type === "scroll-page") {
2158
+ const { direction } = scrollRequest;
2159
+ if (isVirtualScroll) {
2160
+ console.log(`need a virtual page scroll`);
2161
+ } else {
2162
+ const scrollBy = direction === "down" ? appliedPageSize : -appliedPageSize;
2163
+ const newScrollTop = Math.min(
2164
+ Math.max(0, scrollTop + scrollBy),
2165
+ maxScrollTop
2166
+ );
2167
+ scrollbarContainer.scrollTo({
2168
+ top: newScrollTop,
2169
+ left: scrollLeft,
2170
+ behavior: "auto"
2171
+ });
2172
+ }
2173
+ } else if (scrollRequest.type === "scroll-end") {
2174
+ const { direction } = scrollRequest;
2175
+ const scrollTo = direction === "end" ? maxScrollTop : 0;
2176
+ scrollbarContainer.scrollTo({
2177
+ top: scrollTo,
2178
+ left: scrollbarContainer.scrollLeft,
2179
+ behavior: "auto"
2180
+ });
2181
+ }
2182
+ }
2183
+ },
2184
+ [
2185
+ appliedPageSize,
2186
+ isVirtualScroll,
2187
+ maxScrollLeft,
2188
+ maxScrollTop,
2189
+ setRange,
2190
+ totalHeaderHeight,
2191
+ viewportRowCount
2192
+ ]
2193
+ );
2194
+ const scrollHandles = useMemo4(
2195
+ () => ({
2196
+ scrollToIndex: (rowIndex) => {
2197
+ if (scrollbarContainerRef.current) {
2198
+ const scrollPos = (rowIndex - 30) * 20;
2199
+ scrollbarContainerRef.current.scrollTop = scrollPos;
2200
+ }
2201
+ },
2202
+ scrollToKey: (rowKey) => {
2203
+ console.log(`scrollToKey ${rowKey}`);
2204
+ }
2205
+ }),
2206
+ []
2207
+ );
2208
+ useImperativeHandle(
2209
+ scrollingApiRef,
2210
+ () => {
2211
+ if (scrollbarContainerRef.current) {
2212
+ return scrollHandles;
2213
+ } else {
2214
+ return noScrolling;
2215
+ }
2216
+ },
2217
+ [scrollHandles]
2218
+ );
2219
+ useEffect3(() => {
2220
+ const { current: from } = firstRowRef;
2221
+ const rowRange = { from, to: from + viewportRowCount + 1 };
2222
+ setRange(rowRange);
2223
+ }, [setRange, viewportRowCount]);
2224
+ return {
2225
+ /** Ref to be assigned to ScrollbarContainer */
2226
+ scrollbarContainerRef: scrollbarContainerCallbackRef,
2227
+ /** Ref to be assigned to ContentContainer */
2228
+ contentContainerRef: contentContainerCallbackRef,
2229
+ /** Scroll the table */
2230
+ requestScroll
2231
+ };
2232
+ };
2233
+
2234
+ // src/useTableViewport.ts
2235
+ import { useCallback as useCallback16, useMemo as useMemo5, useRef as useRef11 } from "react";
2236
+ import {
2237
+ actualRowPositioning,
2238
+ virtualRowPositioning
2239
+ } from "@vuu-ui/vuu-utils";
2240
+ var MAX_RAW_ROWS = 1e5;
2241
+ var UNMEASURED_VIEWPORT = {
2242
+ appliedPageSize: 0,
2243
+ contentHeight: 0,
2244
+ contentWidth: 0,
2245
+ getRowAtPosition: () => -1,
2246
+ getRowOffset: () => -1,
2247
+ horizontalScrollbarHeight: 0,
2248
+ isVirtualScroll: false,
2249
+ maxScrollContainerScrollHorizontal: 0,
2250
+ maxScrollContainerScrollVertical: 0,
2251
+ pinnedWidthLeft: 0,
2252
+ pinnedWidthRight: 0,
2253
+ rowCount: 0,
2254
+ setPctScrollTop: () => void 0,
2255
+ totalHeaderHeight: 0,
2256
+ verticalScrollbarWidth: 0,
2257
+ viewportBodyHeight: 0
2258
+ };
2259
+ var measurePinnedColumns = (columns) => {
2260
+ let pinnedWidthLeft = 0;
2261
+ let pinnedWidthRight = 0;
2262
+ let unpinnedWidth = 0;
2263
+ for (const column of columns) {
2264
+ const { hidden, pin, width } = column;
2265
+ const visibleWidth = hidden ? 0 : width;
2266
+ if (pin === "left") {
2267
+ pinnedWidthLeft += visibleWidth;
2268
+ } else if (pin === "right") {
2269
+ pinnedWidthRight += visibleWidth;
2270
+ } else {
2271
+ unpinnedWidth += visibleWidth;
2272
+ }
2273
+ }
2274
+ return {
2275
+ pinnedWidthLeft: pinnedWidthLeft + 4,
2276
+ pinnedWidthRight: pinnedWidthRight + 4,
2277
+ unpinnedWidth
2278
+ };
2279
+ };
2280
+ var useTableViewport = ({
2281
+ columns,
2282
+ headerHeight,
2283
+ headings,
2284
+ rowCount,
2285
+ rowHeight,
2286
+ size
2287
+ }) => {
2288
+ const pctScrollTopRef = useRef11(0);
2289
+ const pixelContentHeight = rowHeight * Math.min(rowCount, MAX_RAW_ROWS);
2290
+ const virtualContentHeight = rowCount * rowHeight;
2291
+ const virtualisedExtent = virtualContentHeight - pixelContentHeight;
2292
+ const { pinnedWidthLeft, pinnedWidthRight, unpinnedWidth } = useMemo5(
2293
+ () => measurePinnedColumns(columns),
2294
+ [columns]
2295
+ );
2296
+ const totalHeaderHeightRef = useRef11(headerHeight);
2297
+ useMemo5(() => {
2298
+ totalHeaderHeightRef.current = headerHeight * (1 + headings.length);
2299
+ }, [headerHeight, headings.length]);
2300
+ const [getRowOffset, getRowAtPosition, isVirtualScroll] = useMemo5(() => {
2301
+ if (virtualisedExtent) {
2302
+ return virtualRowPositioning(
2303
+ rowHeight,
2304
+ virtualisedExtent,
2305
+ pctScrollTopRef
2306
+ );
2307
+ } else {
2308
+ return actualRowPositioning(rowHeight);
2309
+ }
2310
+ }, [virtualisedExtent, rowHeight]);
2311
+ const setPctScrollTop = useCallback16((scrollPct) => {
2312
+ pctScrollTopRef.current = scrollPct;
2313
+ }, []);
2314
+ return useMemo5(() => {
2315
+ var _a;
2316
+ if (size) {
2317
+ const { current: totalHeaderHeight } = totalHeaderHeightRef;
2318
+ const scrollbarSize = 15;
2319
+ const contentWidth = pinnedWidthLeft + unpinnedWidth + pinnedWidthRight;
2320
+ const horizontalScrollbarHeight = contentWidth > size.width ? scrollbarSize : 0;
2321
+ const maxScrollContainerScrollVertical = pixelContentHeight - (((_a = size == null ? void 0 : size.height) != null ? _a : 0) - horizontalScrollbarHeight) + totalHeaderHeight;
2322
+ const maxScrollContainerScrollHorizontal = contentWidth - size.width + pinnedWidthLeft;
2323
+ const visibleRows = (size.height - headerHeight) / rowHeight;
2324
+ const count = Number.isInteger(visibleRows) ? visibleRows : Math.ceil(visibleRows);
2325
+ const viewportBodyHeight = size.height - totalHeaderHeight;
2326
+ const verticalScrollbarWidth = pixelContentHeight > viewportBodyHeight ? scrollbarSize : 0;
2327
+ const appliedPageSize = count * rowHeight * (pixelContentHeight / virtualContentHeight);
2328
+ return {
2329
+ appliedPageSize,
2330
+ contentHeight: pixelContentHeight,
2331
+ contentWidth,
2332
+ getRowAtPosition,
2333
+ getRowOffset,
2334
+ isVirtualScroll,
2335
+ horizontalScrollbarHeight,
2336
+ maxScrollContainerScrollHorizontal,
2337
+ maxScrollContainerScrollVertical,
2338
+ pinnedWidthLeft,
2339
+ pinnedWidthRight,
2340
+ rowCount: count,
2341
+ setPctScrollTop,
2342
+ totalHeaderHeight,
2343
+ verticalScrollbarWidth,
2344
+ viewportBodyHeight
2345
+ };
2346
+ } else {
2347
+ return UNMEASURED_VIEWPORT;
2348
+ }
2349
+ }, [
2350
+ getRowAtPosition,
2351
+ getRowOffset,
2352
+ headerHeight,
2353
+ isVirtualScroll,
2354
+ pinnedWidthLeft,
2355
+ unpinnedWidth,
2356
+ pinnedWidthRight,
2357
+ pixelContentHeight,
2358
+ rowHeight,
2359
+ setPctScrollTop,
2360
+ size,
2361
+ virtualContentHeight
2362
+ ]);
2363
+ };
2364
+
2365
+ // src/useTableAndColumnSettings.ts
2366
+ import { useLayoutProviderDispatch } from "@vuu-ui/vuu-layout";
2367
+ import { getCalculatedColumnType } from "@vuu-ui/vuu-utils";
2368
+ import { useCallback as useCallback17, useRef as useRef12, useState as useState5 } from "react";
2369
+ var useTableAndColumnSettings = ({
2370
+ availableColumns: availableColumnsProps,
2371
+ onAvailableColumnsChange,
2372
+ onConfigChange,
2373
+ onCreateCalculatedColumn,
2374
+ onDataSourceConfigChange,
2375
+ tableConfig
2376
+ }) => {
2377
+ const dispatchLayoutAction = useLayoutProviderDispatch();
2378
+ const showTableSettingsRef = useRef12();
2379
+ const [availableColumns, setAvailableColumns] = useState5(
2380
+ availableColumnsProps
2381
+ );
2382
+ const showContextPanel = useCallback17(
2383
+ (componentType, title, props) => {
2384
+ dispatchLayoutAction({
2385
+ type: "set-props",
2386
+ path: "#context-panel",
2387
+ props: {
2388
+ expanded: true,
2389
+ content: {
2390
+ type: componentType,
2391
+ props
2392
+ },
2393
+ title
2394
+ }
2395
+ });
2396
+ },
2397
+ [dispatchLayoutAction]
2398
+ );
2399
+ const handleCancelCreateColumn = useCallback17(() => {
2400
+ requestAnimationFrame(() => {
2401
+ var _a;
2402
+ (_a = showTableSettingsRef.current) == null ? void 0 : _a.call(showTableSettingsRef);
2403
+ });
2404
+ }, []);
2405
+ const handleCreateCalculatedColumn = useCallback17(
2406
+ (column) => {
2407
+ const newAvailableColumns = availableColumns.concat({
2408
+ name: column.name,
2409
+ serverDataType: getCalculatedColumnType(column)
2410
+ });
2411
+ setAvailableColumns(newAvailableColumns);
2412
+ onAvailableColumnsChange == null ? void 0 : onAvailableColumnsChange(newAvailableColumns);
2413
+ requestAnimationFrame(() => {
2414
+ var _a;
2415
+ (_a = showTableSettingsRef.current) == null ? void 0 : _a.call(showTableSettingsRef);
2416
+ });
2417
+ onCreateCalculatedColumn(column);
2418
+ },
2419
+ [availableColumns, onAvailableColumnsChange, onCreateCalculatedColumn]
2420
+ );
2421
+ const showColumnSettingsPanel = useCallback17(
2422
+ (action) => {
2423
+ showContextPanel("ColumnSettings", "Column Settings", {
2424
+ column: action.column,
2425
+ onCancelCreateColumn: handleCancelCreateColumn,
2426
+ onConfigChange,
2427
+ onCreateCalculatedColumn: handleCreateCalculatedColumn,
2428
+ tableConfig,
2429
+ vuuTable: action.vuuTable
2430
+ });
2431
+ },
2432
+ [
2433
+ handleCancelCreateColumn,
2434
+ handleCreateCalculatedColumn,
2435
+ onConfigChange,
2436
+ showContextPanel,
2437
+ tableConfig
2438
+ ]
2439
+ );
2440
+ const handleAddCalculatedColumn = useCallback17(() => {
2441
+ showColumnSettingsPanel({
2442
+ column: {
2443
+ name: "::",
2444
+ serverDataType: "string"
2445
+ },
2446
+ type: "columnSettings",
2447
+ vuuTable: { module: "SIMUL", table: "instruments" }
2448
+ });
2449
+ }, [showColumnSettingsPanel]);
2450
+ const handleNavigateToColumn = useCallback17(
2451
+ (columnName) => {
2452
+ const column = tableConfig.columns.find((c) => c.name === columnName);
2453
+ if (column) {
2454
+ showColumnSettingsPanel({
2455
+ type: "columnSettings",
2456
+ column,
2457
+ //TODO where do we get this from
2458
+ vuuTable: { module: "SIMUL", table: "instruments" }
2459
+ });
2460
+ }
2461
+ },
2462
+ [showColumnSettingsPanel, tableConfig.columns]
2463
+ );
2464
+ showTableSettingsRef.current = useCallback17(() => {
2465
+ showContextPanel("TableSettings", "DataGrid Settings", {
2466
+ availableColumns: availableColumns != null ? availableColumns : tableConfig.columns.map(({ name, serverDataType }) => ({
2467
+ name,
2468
+ serverDataType
2469
+ })),
2470
+ onAddCalculatedColumn: handleAddCalculatedColumn,
2471
+ onConfigChange,
2472
+ onDataSourceConfigChange,
2473
+ onNavigateToColumn: handleNavigateToColumn,
2474
+ tableConfig
2475
+ });
2476
+ }, [
2477
+ availableColumns,
2478
+ handleAddCalculatedColumn,
2479
+ handleNavigateToColumn,
2480
+ onConfigChange,
2481
+ onDataSourceConfigChange,
2482
+ showContextPanel,
2483
+ tableConfig
2484
+ ]);
2485
+ return {
2486
+ showColumnSettingsPanel,
2487
+ showTableSettingsPanel: showTableSettingsRef.current
2488
+ };
2489
+ };
2490
+
2491
+ // src/useTable.ts
2492
+ var stripInternalProperties = (tableConfig) => {
2493
+ return tableConfig;
2494
+ };
2495
+ var { KEY, IS_EXPANDED: IS_EXPANDED2, IS_LEAF: IS_LEAF2 } = metadataKeys6;
2496
+ var NULL_DRAG_DROP = {
2497
+ draggable: void 0,
2498
+ onMouseDown: void 0
2499
+ };
2500
+ var useNullDragDrop = () => NULL_DRAG_DROP;
2501
+ var addColumn = (tableConfig, column) => ({
2502
+ ...tableConfig,
2503
+ columns: tableConfig.columns.concat(column)
2504
+ });
2505
+ var useTable = ({
2506
+ allowDragDrop = false,
2507
+ availableColumns,
2508
+ config,
2509
+ containerRef,
2510
+ dataSource,
2511
+ disableFocus,
2512
+ headerHeight = 25,
2513
+ highlightedIndex: highlightedIndexProp,
2514
+ id,
2515
+ navigationStyle = "cell",
2516
+ onAvailableColumnsChange,
2517
+ onConfigChange,
2518
+ onDragStart,
2519
+ onDrop,
2520
+ onFeatureInvocation,
2521
+ onHighlight,
2522
+ onRowClick: onRowClickProp,
2523
+ onSelect,
2524
+ onSelectionChange,
2525
+ renderBufferSize = 0,
2526
+ rowHeight = 20,
2527
+ scrollingApiRef,
2528
+ selectionModel,
2529
+ size
2530
+ }) => {
2531
+ const [rowCount, setRowCount] = useState6(dataSource.size);
2532
+ if (dataSource === void 0) {
2533
+ throw Error("no data source provided to Vuu Table");
2534
+ }
2535
+ const useRowDragDrop = allowDragDrop ? useDragDrop : useNullDragDrop;
2536
+ const menuBuilder = useMemo6(
2537
+ () => buildContextMenuDescriptors(dataSource),
2538
+ [dataSource]
2539
+ );
2540
+ const onDataRowcountChange = useCallback18((size2) => {
2541
+ setRowCount(size2);
2542
+ }, []);
2543
+ const {
2544
+ columns: runtimeColumns,
2545
+ dispatchColumnAction,
2546
+ headings,
2547
+ tableAttributes,
2548
+ tableConfig
2549
+ } = useTableModel(config, dataSource);
2550
+ useLayoutEffectSkipFirst2(() => {
2551
+ dispatchColumnAction({
2552
+ type: "init",
2553
+ dataSource,
2554
+ tableConfig
2555
+ });
2556
+ }, [tableConfig, dataSource, dispatchColumnAction]);
2557
+ const applyTableConfigChange = useCallback18(
2558
+ (config2) => {
2559
+ dispatchColumnAction({
2560
+ type: "init",
2561
+ tableConfig: config2,
2562
+ dataSource
2563
+ });
2564
+ onConfigChange == null ? void 0 : onConfigChange(stripInternalProperties(config2));
2565
+ },
2566
+ [dataSource, dispatchColumnAction, onConfigChange]
2567
+ );
2568
+ const [stateColumns, setStateColumns] = useState6();
2569
+ const [columns, setColumnSize] = useMemo6(() => {
2570
+ const setSize = (columnName, width) => {
2571
+ const cols = updateColumn(runtimeColumns, columnName, { width });
2572
+ setStateColumns(cols);
2573
+ };
2574
+ return [stateColumns != null ? stateColumns : runtimeColumns, setSize];
2575
+ }, [runtimeColumns, stateColumns]);
2576
+ const columnMap = useMemo6(
2577
+ () => buildColumnMap2(dataSource.columns),
2578
+ [dataSource.columns]
2579
+ );
2580
+ const {
2581
+ getRowAtPosition,
2582
+ getRowOffset,
2583
+ setPctScrollTop,
2584
+ ...viewportMeasurements
2585
+ } = useTableViewport({
2586
+ columns,
2587
+ headerHeight,
2588
+ headings,
2589
+ rowCount,
2590
+ rowHeight,
2591
+ size
2592
+ });
2593
+ const initialRange = useInitialValue({
2594
+ from: 0,
2595
+ to: viewportMeasurements.rowCount === 0 ? 0 : viewportMeasurements.rowCount + 1
2596
+ });
2597
+ const onSubscribed = useCallback18(
2598
+ ({ tableSchema }) => {
2599
+ if (tableSchema) {
2600
+ dispatchColumnAction({
2601
+ type: "setTableSchema",
2602
+ tableSchema
2603
+ });
2604
+ } else {
2605
+ console.log("subscription message with no schema");
2606
+ }
2607
+ },
2608
+ [dispatchColumnAction]
2609
+ );
2610
+ const { data, dataRef, getSelectedRows, range, setRange } = useDataSource({
2611
+ dataSource,
2612
+ // We need to factor this out of Table
2613
+ onFeatureInvocation,
2614
+ renderBufferSize,
2615
+ onSizeChange: onDataRowcountChange,
2616
+ onSubscribed,
2617
+ range: initialRange
2618
+ });
2619
+ const handleConfigEditedInSettingsPanel = useCallback18(
2620
+ (tableConfig2) => {
2621
+ dispatchColumnAction({
2622
+ type: "init",
2623
+ tableConfig: tableConfig2,
2624
+ dataSource
2625
+ });
2626
+ onConfigChange == null ? void 0 : onConfigChange(stripInternalProperties(tableConfig2));
2627
+ },
2628
+ [dataSource, dispatchColumnAction, onConfigChange]
2629
+ );
2630
+ const handleDataSourceConfigChanged = useCallback18(
2631
+ (dataSourceConfig) => {
2632
+ dataSource.config = {
2633
+ ...dataSource.config,
2634
+ ...dataSourceConfig
2635
+ };
2636
+ },
2637
+ [dataSource]
2638
+ );
2639
+ useEffect4(() => {
2640
+ dataSource.on("config", (config2, confirmed) => {
2641
+ dispatchColumnAction({
2642
+ type: "tableConfig",
2643
+ ...config2,
2644
+ confirmed
2645
+ });
2646
+ });
2647
+ }, [dataSource, dispatchColumnAction]);
2648
+ const handleCreateCalculatedColumn = useCallback18(
2649
+ (column) => {
2650
+ dataSource.columns = dataSource.columns.concat(column.name);
2651
+ applyTableConfigChange(addColumn(tableConfig, column));
2652
+ },
2653
+ [dataSource, tableConfig, applyTableConfigChange]
2654
+ );
2655
+ const hideColumns2 = useCallback18(
2656
+ (action) => {
2657
+ const { columns: columns2 } = action;
2658
+ const hiddenColumns = columns2.map((c) => c.name);
2659
+ const newTableConfig = {
2660
+ ...tableConfig,
2661
+ columns: tableConfig.columns.map(
2662
+ (col) => hiddenColumns.includes(col.name) ? { ...col, hidden: true } : col
2663
+ )
2664
+ };
2665
+ applyTableConfigChange(newTableConfig);
2666
+ },
2667
+ [tableConfig, applyTableConfigChange]
2668
+ );
2669
+ const pinColumn3 = useCallback18(
2670
+ (action) => {
2671
+ applyTableConfigChange({
2672
+ ...tableConfig,
2673
+ columns: updateColumn(tableConfig.columns, {
2674
+ ...action.column,
2675
+ pin: action.pin
2676
+ })
2677
+ });
2678
+ },
2679
+ [tableConfig, applyTableConfigChange]
2680
+ );
2681
+ const { showColumnSettingsPanel, showTableSettingsPanel } = useTableAndColumnSettings({
2682
+ availableColumns: availableColumns != null ? availableColumns : tableConfig.columns.map(({ name, serverDataType = "string" }) => ({
2683
+ name,
2684
+ serverDataType
2685
+ })),
2686
+ onAvailableColumnsChange,
2687
+ onConfigChange: handleConfigEditedInSettingsPanel,
2688
+ onCreateCalculatedColumn: handleCreateCalculatedColumn,
2689
+ onDataSourceConfigChange: handleDataSourceConfigChanged,
2690
+ tableConfig
2691
+ });
2692
+ const onPersistentColumnOperation = useCallback18(
2693
+ (action) => {
2694
+ if (isShowColumnSettings(action)) {
2695
+ showColumnSettingsPanel(action);
2696
+ } else if (isShowTableSettings(action)) {
2697
+ showTableSettingsPanel();
2698
+ } else {
2699
+ switch (action.type) {
2700
+ case "hideColumns":
2701
+ return hideColumns2(action);
2702
+ case "pinColumn":
2703
+ return pinColumn3(action);
2704
+ default:
2705
+ dispatchColumnAction(action);
2706
+ }
2707
+ }
2708
+ },
2709
+ [
2710
+ dispatchColumnAction,
2711
+ hideColumns2,
2712
+ pinColumn3,
2713
+ showColumnSettingsPanel,
2714
+ showTableSettingsPanel
2715
+ ]
2716
+ );
2717
+ const handleContextMenuAction = useHandleTableContextMenu({
2718
+ dataSource,
2719
+ onPersistentColumnOperation
2720
+ });
2721
+ const handleSort = useCallback18(
2722
+ (column, extendSort = false, sortType) => {
2723
+ if (dataSource) {
2724
+ dataSource.sort = applySort(
2725
+ dataSource.sort,
2726
+ column,
2727
+ extendSort,
2728
+ sortType
2729
+ );
2730
+ }
2731
+ },
2732
+ [dataSource]
2733
+ );
2734
+ const onResizeColumn = useCallback18(
2735
+ (phase, columnName, width) => {
2736
+ const column = columns.find((column2) => column2.name === columnName);
2737
+ if (column) {
2738
+ if (phase === "resize") {
2739
+ if (isValidNumber(width)) {
2740
+ setColumnSize(columnName, width);
2741
+ }
2742
+ } else if (phase === "end") {
2743
+ if (isValidNumber(width)) {
2744
+ dispatchColumnAction({
2745
+ type: "resizeColumn",
2746
+ phase,
2747
+ column,
2748
+ width
2749
+ });
2750
+ setStateColumns(void 0);
2751
+ onConfigChange == null ? void 0 : onConfigChange(
2752
+ stripInternalProperties(
2753
+ updateTableConfig(tableConfig, {
2754
+ type: "col-size",
2755
+ column,
2756
+ width
2757
+ })
2758
+ )
2759
+ );
2760
+ }
2761
+ } else {
2762
+ setStateColumns(void 0);
2763
+ dispatchColumnAction({
2764
+ type: "resizeColumn",
2765
+ phase,
2766
+ column,
2767
+ width
2768
+ });
2769
+ }
2770
+ } else {
2771
+ throw Error(
2772
+ `useDataTable.handleColumnResize, column ${columnName} not found`
2773
+ );
2774
+ }
2775
+ },
2776
+ [columns, tableConfig, dispatchColumnAction, onConfigChange, setColumnSize]
2777
+ );
2778
+ const onToggleGroup = useCallback18(
2779
+ (row, column) => {
2780
+ var _a, _b;
2781
+ const isJson = isJsonGroup2(column, row);
2782
+ const key = row[KEY];
2783
+ if (row[IS_EXPANDED2]) {
2784
+ dataSource.closeTreeNode(key, true);
2785
+ if (isJson) {
2786
+ const idx = columns.indexOf(column);
2787
+ const rows = (_a = dataSource.getRowsAtDepth) == null ? void 0 : _a.call(dataSource, idx + 1);
2788
+ if (rows && !rows.some((row2) => row2[IS_EXPANDED2] || row2[IS_LEAF2])) {
2789
+ dispatchColumnAction({
2790
+ type: "hideColumns",
2791
+ columns: columns.slice(idx + 2)
2792
+ });
2793
+ }
2794
+ }
2795
+ } else {
2796
+ dataSource.openTreeNode(key);
2797
+ if (isJson) {
2798
+ const childRows = (_b = dataSource.getChildRows) == null ? void 0 : _b.call(dataSource, key);
2799
+ const idx = columns.indexOf(column) + 1;
2800
+ const columnsToShow = [columns[idx]];
2801
+ if (childRows && childRows.some((row2) => row2[IS_LEAF2])) {
2802
+ columnsToShow.push(columns[idx + 1]);
2803
+ }
2804
+ if (columnsToShow.some((col) => col.hidden)) {
2805
+ dispatchColumnAction({
2806
+ type: "showColumns",
2807
+ columns: columnsToShow
2808
+ });
2809
+ }
2810
+ }
2811
+ }
2812
+ },
2813
+ [columns, dataSource, dispatchColumnAction]
2814
+ );
2815
+ const handleVerticalScroll = useCallback18(
2816
+ (_, pctScrollTop) => {
2817
+ setPctScrollTop(pctScrollTop);
2818
+ },
2819
+ [setPctScrollTop]
2820
+ );
2821
+ const { requestScroll, ...scrollProps } = useTableScroll({
2822
+ getRowAtPosition,
2823
+ rowHeight,
2824
+ scrollingApiRef,
2825
+ setRange,
2826
+ onVerticalScroll: handleVerticalScroll,
2827
+ viewportMeasurements
2828
+ });
2829
+ const {
2830
+ highlightedIndexRef,
2831
+ navigate,
2832
+ onFocus: navigationFocus,
2833
+ onKeyDown: navigationKeyDown,
2834
+ ...containerProps
2835
+ } = useKeyboardNavigation({
2836
+ columnCount: columns.filter((c) => c.hidden !== true).length,
2837
+ containerRef,
2838
+ disableFocus,
2839
+ highlightedIndex: highlightedIndexProp,
2840
+ navigationStyle,
2841
+ requestScroll,
2842
+ rowCount: dataSource == null ? void 0 : dataSource.size,
2843
+ onHighlight,
2844
+ viewportRange: range,
2845
+ viewportRowCount: viewportMeasurements.rowCount
2846
+ });
2847
+ const {
2848
+ onBlur: editingBlur,
2849
+ onDoubleClick: editingDoubleClick,
2850
+ onKeyDown: editingKeyDown,
2851
+ onFocus: editingFocus
2852
+ } = useCellEditing({
2853
+ navigate
2854
+ });
2855
+ const handleFocus = useCallback18(
2856
+ (e) => {
2857
+ navigationFocus();
2858
+ if (!e.defaultPrevented) {
2859
+ editingFocus(e);
2860
+ }
2861
+ },
2862
+ [editingFocus, navigationFocus]
2863
+ );
2864
+ const onContextMenu = useTableContextMenu({
2865
+ columns,
2866
+ data,
2867
+ dataSource,
2868
+ getSelectedRows
2869
+ });
2870
+ const onMoveGroupColumn = useCallback18(
2871
+ (columns2) => {
2872
+ dataSource.groupBy = columns2.map((col) => col.name);
2873
+ },
2874
+ [dataSource]
2875
+ );
2876
+ const onRemoveGroupColumn = useCallback18(
2877
+ (column) => {
2878
+ if (isGroupColumn3(column)) {
2879
+ dataSource.groupBy = [];
2880
+ } else {
2881
+ if (dataSource && dataSource.groupBy.includes(column.name)) {
2882
+ dataSource.groupBy = dataSource.groupBy.filter(
2883
+ (columnName) => columnName !== column.name
2884
+ );
2885
+ }
2886
+ }
2887
+ },
2888
+ [dataSource]
2889
+ );
2890
+ const handleSelectionChange = useCallback18(
2891
+ (selected) => {
2892
+ dataSource.select(selected);
2893
+ onSelectionChange == null ? void 0 : onSelectionChange(selected);
2894
+ },
2895
+ [dataSource, onSelectionChange]
2896
+ );
2897
+ const {
2898
+ onKeyDown: selectionHookKeyDown,
2899
+ onRowClick: selectionHookOnRowClick
2900
+ } = useSelection({
2901
+ highlightedIndexRef,
2902
+ onSelect,
2903
+ onSelectionChange: handleSelectionChange,
2904
+ selectionModel
2905
+ });
2906
+ const handleKeyDown = useCallback18(
2907
+ (e) => {
2908
+ navigationKeyDown(e);
2909
+ if (!e.defaultPrevented) {
2910
+ editingKeyDown(e);
2911
+ }
2912
+ if (!e.defaultPrevented) {
2913
+ selectionHookKeyDown(e);
2914
+ }
2915
+ },
2916
+ [navigationKeyDown, editingKeyDown, selectionHookKeyDown]
2917
+ );
2918
+ const handleRowClick = useCallback18(
2919
+ (row, rangeSelect, keepExistingSelection) => {
2920
+ selectionHookOnRowClick(row, rangeSelect, keepExistingSelection);
2921
+ onRowClickProp == null ? void 0 : onRowClickProp(row);
2922
+ },
2923
+ [onRowClickProp, selectionHookOnRowClick]
2924
+ );
2925
+ useLayoutEffectSkipFirst2(() => {
2926
+ dispatchColumnAction({
2927
+ type: "init",
2928
+ tableConfig: config,
2929
+ dataSource
2930
+ });
2931
+ }, [config, dataSource, dispatchColumnAction]);
2932
+ const onMoveColumn = useCallback18(
2933
+ (columns2) => {
2934
+ console.log(`useTable onMoveColumn`, {
2935
+ columns: columns2
2936
+ });
2937
+ const newTableConfig = {
2938
+ ...tableConfig,
2939
+ columns: columns2
2940
+ };
2941
+ dispatchColumnAction({
2942
+ type: "init",
2943
+ tableConfig: newTableConfig,
2944
+ dataSource
2945
+ });
2946
+ onConfigChange == null ? void 0 : onConfigChange(stripInternalProperties(newTableConfig));
2947
+ },
2948
+ [dataSource, dispatchColumnAction, onConfigChange, tableConfig]
2949
+ );
2950
+ const handleDropRow = useCallback18(
2951
+ (dragDropState) => {
2952
+ onDrop == null ? void 0 : onDrop(dragDropState);
2953
+ },
2954
+ [onDrop]
2955
+ );
2956
+ const handleDataEdited = useCallback18(
2957
+ async (row, columnName, value) => dataSource.applyEdit(row, columnName, value),
2958
+ [dataSource]
2959
+ );
2960
+ const handleDragStartRow = useCallback18(
2961
+ (dragDropState) => {
2962
+ const { initialDragElement } = dragDropState;
2963
+ const rowIndex = getIndexFromRowElement3(initialDragElement);
2964
+ const row = dataRef.current.find((row2) => row2[0] === rowIndex);
2965
+ if (row) {
2966
+ dragDropState.setPayload(row);
2967
+ } else {
2968
+ }
2969
+ onDragStart == null ? void 0 : onDragStart(dragDropState);
2970
+ },
2971
+ [dataRef, onDragStart]
2972
+ );
2973
+ const { onMouseDown: rowDragMouseDown, draggable: draggableRow } = useRowDragDrop({
2974
+ allowDragDrop,
2975
+ containerRef,
2976
+ draggableClassName: `vuuTable`,
2977
+ id,
2978
+ onDragStart: handleDragStartRow,
2979
+ onDrop: handleDropRow,
2980
+ orientation: "vertical",
2981
+ itemQuery: ".vuuTableRow"
2982
+ });
2983
+ return {
2984
+ ...containerProps,
2985
+ "aria-rowcount": dataSource.size,
2986
+ draggableRow,
2987
+ onBlur: editingBlur,
2988
+ onDoubleClick: editingDoubleClick,
2989
+ onFocus: handleFocus,
2990
+ onKeyDown: handleKeyDown,
2991
+ onMouseDown: rowDragMouseDown,
2992
+ columnMap,
2993
+ columns,
2994
+ data,
2995
+ getRowOffset,
2996
+ handleContextMenuAction,
2997
+ headings,
2998
+ highlightedIndex: highlightedIndexRef.current,
2999
+ menuBuilder,
3000
+ onContextMenu,
3001
+ onDataEdited: handleDataEdited,
3002
+ onMoveColumn,
3003
+ onMoveGroupColumn,
3004
+ onRemoveGroupColumn,
3005
+ onRowClick: handleRowClick,
3006
+ onSortColumn: handleSort,
3007
+ onResizeColumn,
3008
+ onToggleGroup,
3009
+ scrollProps,
3010
+ // TODO don't think we need these ...
3011
+ tableAttributes,
3012
+ tableConfig,
3013
+ viewportMeasurements
3014
+ };
3015
+ };
3016
+
3017
+ // src/table-header/TableHeader.tsx
3018
+ import { isGroupColumn as isGroupColumn4, isNotHidden as isNotHidden2 } from "@vuu-ui/vuu-utils";
3019
+ import cx8 from "clsx";
3020
+
3021
+ // src/table-header/useTableHeader.ts
3022
+ import { useDragDrop as useDragDrop2 } from "@vuu-ui/vuu-ui-controls";
3023
+ import { moveColumnTo, visibleColumnAtIndex } from "@vuu-ui/vuu-utils";
3024
+ import { useCallback as useCallback19, useRef as useRef13 } from "react";
3025
+ var useTableHeader = ({
3026
+ columns,
3027
+ onMoveColumn,
3028
+ onSortColumn,
3029
+ tableConfig
3030
+ }) => {
3031
+ const containerRef = useRef13(null);
3032
+ const handleDropColumnHeader = useCallback19(
3033
+ (moveFrom, moveTo) => {
3034
+ const column = columns[moveFrom];
3035
+ const orderedColumns = moveColumnTo(columns, column, moveTo);
3036
+ const ofColumn = ({ name }) => (col) => col.name === name;
3037
+ const targetIndex = orderedColumns.findIndex(ofColumn(column));
3038
+ const nextColumn = orderedColumns[targetIndex + 1];
3039
+ const insertPos = nextColumn ? tableConfig.columns.findIndex(ofColumn(nextColumn)) : -1;
3040
+ if (moveTo > moveFrom && insertPos !== -1) {
3041
+ onMoveColumn(moveColumnTo(tableConfig.columns, column, insertPos - 1));
3042
+ } else {
3043
+ onMoveColumn(moveColumnTo(tableConfig.columns, column, insertPos));
3044
+ }
3045
+ },
3046
+ [columns, onMoveColumn, tableConfig.columns]
3047
+ );
3048
+ const handleColumnHeaderClick = useCallback19(
3049
+ (evt) => {
3050
+ var _a;
3051
+ const targetElement = evt.target;
3052
+ const headerCell = targetElement.closest(
3053
+ ".vuuTableHeaderCell"
3054
+ );
3055
+ const colIdx = parseInt((_a = headerCell == null ? void 0 : headerCell.dataset.index) != null ? _a : "-1");
3056
+ const column = visibleColumnAtIndex(columns, colIdx);
3057
+ const isAdditive = evt.shiftKey;
3058
+ column && onSortColumn(column, isAdditive);
3059
+ },
3060
+ [columns, onSortColumn]
3061
+ );
3062
+ const {
3063
+ onMouseDown: columnHeaderDragMouseDown,
3064
+ draggable: draggableColumn,
3065
+ ...dragDropHook
3066
+ } = useDragDrop2({
3067
+ allowDragDrop: true,
3068
+ containerRef,
3069
+ draggableClassName: `vuuTable`,
3070
+ onDrop: handleDropColumnHeader,
3071
+ orientation: "horizontal",
3072
+ itemQuery: ".vuuTableHeaderCell"
3073
+ });
3074
+ return {
3075
+ containerRef,
3076
+ draggableColumn,
3077
+ draggedColumnIndex: dragDropHook.draggedItemIndex,
3078
+ onClick: handleColumnHeaderClick,
3079
+ onMouseDown: columnHeaderDragMouseDown
3080
+ };
3081
+ };
3082
+
3083
+ // src/table-header/TableHeader.tsx
3084
+ import { jsx as jsx11, jsxs as jsxs7 } from "react/jsx-runtime";
3085
+ var TableHeader = ({
3086
+ classBase: classBase10 = "vuuTable",
3087
+ columns,
3088
+ headings,
3089
+ onMoveColumn,
3090
+ onMoveGroupColumn,
3091
+ onRemoveGroupColumn,
3092
+ onResizeColumn,
3093
+ onSortColumn,
3094
+ tableConfig,
3095
+ tableId
3096
+ }) => {
3097
+ const {
3098
+ containerRef,
3099
+ draggableColumn,
3100
+ draggedColumnIndex,
3101
+ onClick,
3102
+ onMouseDown
3103
+ } = useTableHeader({
3104
+ columns,
3105
+ onMoveColumn,
3106
+ onSortColumn,
3107
+ tableConfig
3108
+ });
3109
+ return /* @__PURE__ */ jsxs7("div", { className: `${classBase10}-col-headings`, ref: containerRef, children: [
3110
+ headings.map((colHeaders, i) => /* @__PURE__ */ jsx11("div", { className: "vuuTable-heading", children: colHeaders.map(({ label, width }, j) => /* @__PURE__ */ jsx11("div", { className: "vuuTable-headingCell", style: { width }, children: label }, j)) }, i)),
3111
+ /* @__PURE__ */ jsxs7("div", { className: `${classBase10}-col-headers`, role: "row", children: [
3112
+ columns.filter(isNotHidden2).map(
3113
+ (col, i) => isGroupColumn4(col) ? /* @__PURE__ */ jsx11(
3114
+ GroupHeaderCellNext,
3115
+ {
3116
+ column: col,
3117
+ "data-index": i,
3118
+ onMoveColumn: onMoveGroupColumn,
3119
+ onRemoveColumn: onRemoveGroupColumn,
3120
+ onResize: onResizeColumn
3121
+ },
3122
+ col.name
3123
+ ) : /* @__PURE__ */ jsx11(
3124
+ HeaderCell,
3125
+ {
3126
+ className: cx8({
3127
+ "vuuDraggable-dragAway": i === draggedColumnIndex
3128
+ }),
3129
+ column: col,
3130
+ "data-index": i,
3131
+ id: `${tableId}-col-${i}`,
3132
+ onClick,
3133
+ onMouseDown,
3134
+ onResize: onResizeColumn
3135
+ },
3136
+ col.name
3137
+ )
3138
+ ),
3139
+ draggableColumn
3140
+ ] })
3141
+ ] });
3142
+ };
3143
+
3144
+ // src/Table.tsx
3145
+ import { jsx as jsx12, jsxs as jsxs8 } from "react/jsx-runtime";
3146
+ var classBase7 = "vuuTable";
3147
+ var { IDX: IDX3, RENDER_IDX } = metadataKeys7;
3148
+ var TableCore = ({
3149
+ Row: Row2 = Row,
3150
+ allowDragDrop,
3151
+ availableColumns,
3152
+ config,
3153
+ containerRef,
3154
+ dataSource,
3155
+ disableFocus = false,
3156
+ highlightedIndex: highlightedIndexProp,
3157
+ id: idProp,
3158
+ navigationStyle = "cell",
3159
+ onAvailableColumnsChange,
3160
+ onConfigChange,
3161
+ onDragStart,
3162
+ onDrop,
3163
+ onFeatureInvocation,
3164
+ onHighlight,
3165
+ onRowClick: onRowClickProp,
3166
+ onSelect,
3167
+ onSelectionChange,
3168
+ renderBufferSize = 5,
3169
+ rowHeight = 20,
3170
+ scrollingApiRef,
3171
+ selectionModel = "extended",
3172
+ showColumnHeaders = true,
3173
+ headerHeight = showColumnHeaders ? 25 : 0,
3174
+ size
3175
+ }) => {
3176
+ const id = useId(idProp);
3177
+ const {
3178
+ columnMap,
3179
+ columns,
3180
+ data,
3181
+ draggableRow,
3182
+ getRowOffset,
3183
+ handleContextMenuAction,
3184
+ headings,
3185
+ highlightedIndex,
3186
+ onDataEdited,
3187
+ onMoveColumn,
3188
+ onMoveGroupColumn,
3189
+ onRemoveGroupColumn,
3190
+ onResizeColumn,
3191
+ onRowClick,
3192
+ onSortColumn,
3193
+ onToggleGroup,
3194
+ menuBuilder,
3195
+ scrollProps,
3196
+ tableAttributes,
3197
+ tableConfig,
3198
+ viewportMeasurements,
3199
+ ...tableProps
3200
+ } = useTable({
3201
+ allowDragDrop,
3202
+ availableColumns,
3203
+ config,
3204
+ containerRef,
3205
+ dataSource,
3206
+ disableFocus,
3207
+ headerHeight,
3208
+ highlightedIndex: highlightedIndexProp,
3209
+ id,
3210
+ navigationStyle,
3211
+ onAvailableColumnsChange,
3212
+ onConfigChange,
3213
+ onDragStart,
3214
+ onDrop,
3215
+ onFeatureInvocation,
3216
+ onHighlight,
3217
+ onRowClick: onRowClickProp,
3218
+ onSelect,
3219
+ onSelectionChange,
3220
+ renderBufferSize,
3221
+ rowHeight,
3222
+ scrollingApiRef,
3223
+ selectionModel,
3224
+ size
3225
+ });
3226
+ const contentContainerClassName = cx9(`${classBase7}-contentContainer`, {
3227
+ [`${classBase7}-colLines`]: tableAttributes.columnSeparators,
3228
+ [`${classBase7}-rowLines`]: tableAttributes.rowSeparators,
3229
+ // [`${classBase}-highlight`]: tableAttributes.showHighlightedRow,
3230
+ [`${classBase7}-zebra`]: tableAttributes.zebraStripes
3231
+ // [`${classBase}-loading`]: isDataLoading(tableProps.columns),
3232
+ });
3233
+ const cssVariables = {
3234
+ "--content-height": `${viewportMeasurements.contentHeight}px`,
3235
+ "--content-width": `${viewportMeasurements.contentWidth}px`,
3236
+ "--horizontal-scrollbar-height": `${viewportMeasurements.horizontalScrollbarHeight}px`,
3237
+ "--pinned-width-left": `${viewportMeasurements.pinnedWidthLeft}px`,
3238
+ "--pinned-width-right": `${viewportMeasurements.pinnedWidthRight}px`,
3239
+ "--header-height": `${headerHeight}px`,
3240
+ "--row-height": `${rowHeight}px`,
3241
+ "--total-header-height": `${viewportMeasurements.totalHeaderHeight}px`,
3242
+ "--vertical-scrollbar-width": `${viewportMeasurements.verticalScrollbarWidth}px`,
3243
+ "--viewport-body-height": `${viewportMeasurements.viewportBodyHeight}px`
3244
+ };
3245
+ return /* @__PURE__ */ jsxs8(
3246
+ ContextMenuProvider,
3247
+ {
3248
+ menuActionHandler: handleContextMenuAction,
3249
+ menuBuilder,
3250
+ children: [
3251
+ /* @__PURE__ */ jsx12(
3252
+ "div",
3253
+ {
3254
+ className: `${classBase7}-scrollbarContainer`,
3255
+ ref: scrollProps.scrollbarContainerRef,
3256
+ style: cssVariables,
3257
+ children: /* @__PURE__ */ jsx12("div", { className: `${classBase7}-scrollbarContent` })
3258
+ }
3259
+ ),
3260
+ /* @__PURE__ */ jsx12(
3261
+ "div",
3262
+ {
3263
+ className: contentContainerClassName,
3264
+ ref: scrollProps.contentContainerRef,
3265
+ style: cssVariables,
3266
+ children: /* @__PURE__ */ jsxs8(
3267
+ "div",
3268
+ {
3269
+ ...tableProps,
3270
+ className: `${classBase7}-table`,
3271
+ role: "table",
3272
+ tabIndex: disableFocus ? void 0 : -1,
3273
+ children: [
3274
+ showColumnHeaders ? /* @__PURE__ */ jsx12(
3275
+ TableHeader,
3276
+ {
3277
+ columns,
3278
+ headings,
3279
+ onMoveColumn,
3280
+ onMoveGroupColumn,
3281
+ onRemoveGroupColumn,
3282
+ onResizeColumn,
3283
+ onSortColumn,
3284
+ tableConfig,
3285
+ tableId: id
3286
+ }
3287
+ ) : null,
3288
+ /* @__PURE__ */ jsx12("div", { className: `${classBase7}-body`, children: data.map((data2) => /* @__PURE__ */ jsx12(
3289
+ Row2,
3290
+ {
3291
+ "aria-rowindex": data2[0] + 1,
3292
+ columnMap,
3293
+ columns,
3294
+ highlighted: highlightedIndex === data2[IDX3],
3295
+ onClick: onRowClick,
3296
+ onDataEdited,
3297
+ row: data2,
3298
+ offset: getRowOffset(data2),
3299
+ onToggleGroup,
3300
+ zebraStripes: tableAttributes.zebraStripes
3301
+ },
3302
+ data2[RENDER_IDX]
3303
+ )) })
3304
+ ]
3305
+ }
3306
+ )
3307
+ }
3308
+ ),
3309
+ draggableRow
3310
+ ]
3311
+ }
3312
+ );
3313
+ };
3314
+ var Table = forwardRef(function TableNext({
3315
+ Row: Row2,
3316
+ allowDragDrop,
3317
+ availableColumns,
3318
+ className: classNameProp,
3319
+ config,
3320
+ dataSource,
3321
+ disableFocus,
3322
+ highlightedIndex,
3323
+ id,
3324
+ navigationStyle,
3325
+ onAvailableColumnsChange,
3326
+ onConfigChange,
3327
+ onDragStart,
3328
+ onDrop,
3329
+ onFeatureInvocation,
3330
+ onHighlight,
3331
+ onRowClick,
3332
+ onSelect,
3333
+ onSelectionChange,
3334
+ renderBufferSize,
3335
+ rowHeight,
3336
+ scrollingApiRef,
3337
+ selectionModel,
3338
+ showColumnHeaders,
3339
+ headerHeight,
3340
+ style: styleProp,
3341
+ ...htmlAttributes
3342
+ }, forwardedRef) {
3343
+ const containerRef = useRef14(null);
3344
+ const [size, setSize] = useState7();
3345
+ if (config === void 0) {
3346
+ throw Error(
3347
+ "vuu Table requires config prop. Minimum config is list of Column Descriptors"
3348
+ );
3349
+ }
3350
+ if (dataSource === void 0) {
3351
+ throw Error("vuu Table requires dataSource prop");
3352
+ }
3353
+ return /* @__PURE__ */ jsx12(
3354
+ MeasuredContainer,
3355
+ {
3356
+ ...htmlAttributes,
3357
+ className: cx9(classBase7, classNameProp),
3358
+ id,
3359
+ onResize: setSize,
3360
+ ref: useForkRef(containerRef, forwardedRef),
3361
+ children: size ? /* @__PURE__ */ jsx12(
3362
+ TableCore,
3363
+ {
3364
+ Row: Row2,
3365
+ allowDragDrop,
3366
+ availableColumns,
3367
+ config,
3368
+ containerRef,
3369
+ dataSource,
3370
+ disableFocus,
3371
+ headerHeight,
3372
+ highlightedIndex,
3373
+ id,
3374
+ navigationStyle,
3375
+ onAvailableColumnsChange,
3376
+ onConfigChange,
3377
+ onDragStart,
3378
+ onDrop,
3379
+ onFeatureInvocation,
3380
+ onHighlight,
3381
+ onRowClick,
3382
+ onSelect,
3383
+ onSelectionChange,
3384
+ renderBufferSize,
3385
+ rowHeight,
3386
+ scrollingApiRef,
3387
+ selectionModel,
3388
+ showColumnHeaders,
3389
+ size
3390
+ }
3391
+ ) : null
3392
+ }
3393
+ );
3394
+ });
3395
+
3396
+ // src/cell-renderers/checkbox-cell/CheckboxCell.tsx
3397
+ import { memo as memo2, useCallback as useCallback20 } from "react";
3398
+ import { CheckboxIcon, WarnCommit } from "@vuu-ui/vuu-ui-controls";
3399
+ import { Checkbox } from "@salt-ds/core";
3400
+
3401
+ // src/cell-renderers/cell-utils.ts
3402
+ var dataAndColumnUnchanged = (p, p1) => p.column === p1.column && p.column.valueFormatter(p.row[p.columnMap[p.column.name]]) === p1.column.valueFormatter(p1.row[p1.columnMap[p1.column.name]]);
3403
+
3404
+ // src/cell-renderers/checkbox-cell/CheckboxCell.tsx
3405
+ import { dispatchCustomEvent, registerComponent } from "@vuu-ui/vuu-utils";
3406
+ import { jsx as jsx13 } from "react/jsx-runtime";
3407
+ var CheckboxCell = memo2(
3408
+ ({ column, columnMap, onCommit = WarnCommit, row }) => {
3409
+ const dataIdx = columnMap[column.name];
3410
+ const isChecked = row[dataIdx];
3411
+ const handleCommit = useCallback20(
3412
+ (value) => async (evt) => {
3413
+ const res = await onCommit(value);
3414
+ if (res === true) {
3415
+ dispatchCustomEvent(evt.target, "vuu-commit");
3416
+ }
3417
+ return res;
3418
+ },
3419
+ [onCommit]
3420
+ );
3421
+ return column.editable ? /* @__PURE__ */ jsx13(Checkbox, { checked: isChecked, onClick: handleCommit(!isChecked) }) : /* @__PURE__ */ jsx13(CheckboxIcon, { checked: isChecked, disabled: true });
3422
+ },
3423
+ dataAndColumnUnchanged
3424
+ );
3425
+ CheckboxCell.displayName = "CheckboxCell";
3426
+ registerComponent("checkbox-cell", CheckboxCell, "cell-renderer", {
3427
+ serverDataType: "boolean"
3428
+ });
3429
+
3430
+ // src/cell-renderers/input-cell/InputCell.tsx
3431
+ import { registerComponent as registerComponent2 } from "@vuu-ui/vuu-utils";
3432
+ import { Input } from "@salt-ds/core";
3433
+ import { useEditableText } from "@vuu-ui/vuu-ui-controls";
3434
+ import cx10 from "clsx";
3435
+ import { jsx as jsx14 } from "react/jsx-runtime";
3436
+ var classBase8 = "vuuTableInputCell";
3437
+ var WarnCommit2 = () => {
3438
+ console.warn(
3439
+ "onCommit handler has not been provided to InputCell cell renderer"
3440
+ );
3441
+ return Promise.resolve(true);
3442
+ };
3443
+ var InputCell = ({
3444
+ column,
3445
+ columnMap,
3446
+ onCommit = WarnCommit2,
3447
+ row
3448
+ }) => {
3449
+ const dataIdx = columnMap[column.name];
3450
+ const { align = "left", clientSideEditValidationCheck } = column;
3451
+ const { warningMessage, ...editProps } = useEditableText({
3452
+ initialValue: row[dataIdx],
3453
+ onCommit,
3454
+ clientSideEditValidationCheck
3455
+ });
3456
+ const endAdornment = warningMessage && align === "left" ? /* @__PURE__ */ jsx14("span", { className: `${classBase8}-icon`, "data-icon": "error" }) : void 0;
3457
+ const startAdornment = warningMessage && align === "right" ? /* @__PURE__ */ jsx14("span", { className: `${classBase8}-icon`, "data-icon": "error" }) : void 0;
3458
+ return /* @__PURE__ */ jsx14(
3459
+ Input,
3460
+ {
3461
+ ...editProps,
3462
+ className: cx10(classBase8, {
3463
+ [`${classBase8}-error`]: warningMessage !== void 0
3464
+ }),
3465
+ endAdornment,
3466
+ startAdornment
3467
+ }
3468
+ );
3469
+ };
3470
+ registerComponent2("input-cell", InputCell, "cell-renderer", {});
3471
+
3472
+ // src/cell-renderers/toggle-cell/ToggleCell.tsx
3473
+ import { WarnCommit as WarnCommit3 } from "@vuu-ui/vuu-ui-controls";
3474
+ import {
3475
+ dispatchCustomEvent as dispatchCustomEvent2,
3476
+ isTypeDescriptor,
3477
+ isValueListRenderer,
3478
+ registerComponent as registerComponent3
3479
+ } from "@vuu-ui/vuu-utils";
3480
+ import cx11 from "clsx";
3481
+ import { memo as memo3, useCallback as useCallback21 } from "react";
3482
+ import { CycleStateButton } from "@vuu-ui/vuu-ui-controls";
3483
+ import { jsx as jsx15 } from "react/jsx-runtime";
3484
+ var classBase9 = "vuuTableToggleCell";
3485
+ var getValueList = ({ name, type }) => {
3486
+ if (isTypeDescriptor(type) && isValueListRenderer(type.renderer)) {
3487
+ return type.renderer.values;
3488
+ } else {
3489
+ throw Error(
3490
+ `useLookupValues column ${name} has not been configured with a values list`
3491
+ );
3492
+ }
3493
+ };
3494
+ var ToggleCell = memo3(
3495
+ function ToggleCell2({
3496
+ column,
3497
+ columnMap,
3498
+ onCommit = WarnCommit3,
3499
+ row
3500
+ }) {
3501
+ const values = getValueList(column);
3502
+ const dataIdx = columnMap[column.name];
3503
+ const value = row[dataIdx];
3504
+ const handleCommit = useCallback21(
3505
+ (evt, value2) => {
3506
+ return onCommit(value2).then((response) => {
3507
+ if (response === true) {
3508
+ dispatchCustomEvent2(evt.target, "vuu-commit");
3509
+ }
3510
+ return response;
3511
+ });
3512
+ },
3513
+ [onCommit]
3514
+ );
3515
+ return /* @__PURE__ */ jsx15(
3516
+ CycleStateButton,
3517
+ {
3518
+ className: cx11(classBase9, `${classBase9}-${column.name}`),
3519
+ onCommit: handleCommit,
3520
+ value,
3521
+ values,
3522
+ variant: "cta",
3523
+ children: value
3524
+ }
3525
+ );
3526
+ },
3527
+ dataAndColumnUnchanged
3528
+ );
3529
+ registerComponent3("toggle-cell", ToggleCell, "cell-renderer", {});
3530
+
3531
+ // src/useControlledTableNavigation.ts
3532
+ import { useStateRef } from "@vuu-ui/vuu-ui-controls";
3533
+ import { dispatchMouseEvent as dispatchMouseEvent2 } from "@vuu-ui/vuu-utils";
3534
+ import { useCallback as useCallback22, useRef as useRef15 } from "react";
3535
+ var useControlledTableNavigation = (initialValue, rowCount) => {
3536
+ const tableRef = useRef15(null);
3537
+ const [highlightedIndexRef, setHighlightedIndex] = useStateRef(initialValue);
3538
+ const handleKeyDown = useCallback22(
3539
+ (e) => {
3540
+ var _a;
3541
+ if (e.key === "ArrowDown") {
3542
+ setHighlightedIndex((index = -1) => Math.min(rowCount - 1, index + 1));
3543
+ } else if (e.key === "ArrowUp") {
3544
+ setHighlightedIndex((index = -1) => Math.max(0, index - 1));
3545
+ } else if (e.key === "Enter" || e.key === " ") {
3546
+ const { current: rowIdx } = highlightedIndexRef;
3547
+ const rowEl = (_a = tableRef.current) == null ? void 0 : _a.querySelector(
3548
+ `[aria-rowindex="${rowIdx}"]`
3549
+ );
3550
+ if (rowEl) {
3551
+ dispatchMouseEvent2(rowEl, "click");
3552
+ }
3553
+ }
3554
+ },
3555
+ [highlightedIndexRef, rowCount, setHighlightedIndex]
3556
+ );
3557
+ const handleHighlight = useCallback22(
3558
+ (idx) => {
3559
+ setHighlightedIndex(idx);
3560
+ },
3561
+ [setHighlightedIndex]
3562
+ );
3563
+ return {
3564
+ highlightedIndexRef,
3565
+ onHighlight: handleHighlight,
3566
+ onKeyDown: handleKeyDown,
3567
+ tableRef
3568
+ };
3569
+ };
3570
+ export {
3571
+ CheckboxCell,
3572
+ GroupHeaderCellNext,
3573
+ HeaderCell,
3574
+ InputCell,
3575
+ Table,
3576
+ TableCell,
3577
+ TableGroupCell,
3578
+ ToggleCell,
3579
+ dataAndColumnUnchanged,
3580
+ howFarIsRowOutsideViewport,
3581
+ isShowColumnSettings,
3582
+ isShowTableSettings,
3583
+ noScrolling,
3584
+ updateTableConfig,
3585
+ useControlledTableNavigation,
3586
+ useTableModel,
3587
+ useTableScroll,
3588
+ useTableViewport
3589
+ };
3
3590
  //# sourceMappingURL=index.js.map