@cryptlex/web-components 6.6.6-alpha53 → 6.6.6-alpha54
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.
|
@@ -2,7 +2,7 @@ import { operations } from '@cryptlex/web-api-types/develop';
|
|
|
2
2
|
import { ColumnDef, PaginationState, RowData, SortingState, ColumnHelper } from '@tanstack/react-table';
|
|
3
3
|
import { FiltersConfig, TableFilter } from '../components/data-table-filter';
|
|
4
4
|
import { DialogMenuAction } from '../components/dialog-menu';
|
|
5
|
-
import { ApiResponseBody } from '../utilities/resources';
|
|
5
|
+
import { ApiPathParameters, ApiResponseBody } from '../utilities/resources';
|
|
6
6
|
import { TableAction } from './data-table-actions';
|
|
7
7
|
import { ClientPathsWithMethod } from 'openapi-fetch';
|
|
8
8
|
import { CtxClientType } from '../utilities/ctx-client';
|
|
@@ -14,6 +14,7 @@ declare module '@tanstack/react-table' {
|
|
|
14
14
|
}
|
|
15
15
|
type DataTableFactory<T extends object, TOperation extends keyof operations> = {
|
|
16
16
|
path: NoInfer<ClientPathsWithMethod<CtxClientType, 'get'>>;
|
|
17
|
+
pathParameters?: NoInfer<ApiPathParameters<TOperation>>;
|
|
17
18
|
columns: ColumnDef<T, any>[];
|
|
18
19
|
tableActions: TableAction<T>[];
|
|
19
20
|
columnsToHideByDefault?: Partial<Record<keyof T, boolean>>;
|
|
@@ -30,7 +31,7 @@ export declare function getColumnHelper<O extends keyof operations>(): ColumnHel
|
|
|
30
31
|
/**
|
|
31
32
|
* Hook for handling all data-table state. Used in DataTableContext
|
|
32
33
|
*/
|
|
33
|
-
export declare function useDataTableState<T extends object, TOperation extends keyof operations>({ path, columns, filterConfig, columnsToHideByDefault, allowSelection, initialFilters, tableActions, rowActions, }: DataTableFactory<T, TOperation>): {
|
|
34
|
+
export declare function useDataTableState<T extends object, TOperation extends keyof operations>({ path, pathParameters, columns, filterConfig, columnsToHideByDefault, allowSelection, initialFilters, tableActions, rowActions, }: DataTableFactory<T, TOperation>): {
|
|
34
35
|
readonly tableState: DataTableState;
|
|
35
36
|
readonly updateTableState: (updates: Partial<DataTableState>) => void;
|
|
36
37
|
readonly query: import('@tanstack/react-query').UseQueryResult<{
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{jsx as e,Fragment as w,jsxs as l}from"react/jsx-runtime";import{createContext as ie,useState as T,useMemo as le,useEffect as se,useContext as ce,useRef as ue}from"react";import{Button as v}from"./button.js";import{useSensors as de,useSensor as q,PointerSensor as me,KeyboardSensor as ge,DndContext as pe,closestCenter as fe,DragOverlay as he}from"@dnd-kit/core";import{sortableKeyboardCoordinates as be,SortableContext as Se,verticalListSortingStrategy as ye,arrayMove as ve,useSortable as Ce}from"@dnd-kit/sortable";import{CSS as we}from"@dnd-kit/utilities";import{useQuery as xe}from"@tanstack/react-query";import{createColumnHelper as G,useReactTable as Ne,getCoreRowModel as Ie,flexRender as z}from"@tanstack/react-table";import{useLocalStorage as V}from"@uidotdev/usehooks";import{merge as Te}from"lodash-es";import{Badge as Fe}from"./badge.js";import{TfDatePicker as Ae}from"./date-picker.js";import{EasyMenu as M,MenuItem as P}from"./menu.js";import{PopoverTrigger as Pe,Popover as De}from"./popover.js";import{useAppForm as Re}from"../utilities/form-hook.js";import{useResourceFormatter as _}from"../utilities/resources.js";import{classNames as y}from"../utilities/theme.js";import{IcInfo as ze,IcMoreVertical as Oe,IcRefresh as Me,IcColumns as _e,IcGrip as Le,IcFirst as je,IcLeft as Ee,IcRight as $e,IcLast as qe,IcSortAsc as Ve,IcSortDesc as He,IcSortNone as ke,IcFilter as Ue,IcRemove as H,IcCheck as k,IcMinus as Be,IcAccount as Ke,IcLicense as Qe,IcDate as Ge,IcFile as Xe}from"./icons.js";import{TfMultipleIdSearchInput as Ze}from"./id-search.js";import{DialogMenu as Je}from"./dialog-menu.js";import{Loader as We}from"./loader.js";import{SearchField as Ye}from"./searchfield.js";import{Table as et,TableHeader as tt,TableRow as U,TableHead as nt,TableBody as rt,TableCell as at}from"./table.js";import{CountryName as ot}from"../utilities/countries.js";import{formatDate as it}from"../utilities/date.js";import{formatDays as lt,formatFilesize as st,formatNumber as ct}from"../utilities/numbers.js";import{Checkbox as B}from"./checkbox.js";import{TableActions as ut}from"./data-table-actions.js";import{useCtxClient as dt}from"../utilities/ctx-client.js";import"class-variance-authority";import"react-aria-components";import"@internationalized/date";import"./calendar.js";import"./form.js";import"./datefield.js";import"../utilities/form.js";import"../utilities/form-context.js";import"@tanstack/react-form";import"./list-box.js";import"./select.js";import"./multi-select.js";import"./numberfield.js";import"./textfield.js";import"../utilities/string.js";import"clsx";import"./dialog-action-utils.js";import"./dialog.js";import"./select-options.js";import"zod";import"../utilities/duration.js";function mt(t){return t?t.desc?`-${t.id}`:`+${t.id}`:"-createdAt"}const X=G(),gt=[X.accessor("checkbox",{header:({table:t})=>e(B,{isIndeterminate:t.getIsSomeRowsSelected()&&!t.getIsAllPageRowsSelected(),isSelected:t.getIsAllPageRowsSelected()||t.getIsSomePageRowsSelected(),onChange:()=>t.toggleAllPageRowsSelected(),"aria-label":"Select all"}),cell:({row:t})=>e(B,{isSelected:t.getIsSelected(),onChange:()=>t.toggleSelected(),"aria-label":"Select row"}),enableSorting:!1,enableHiding:!1})],C="TableActions",pt=t=>t.length===0?[]:[X.accessor(C,{header:"Actions",id:C,enableHiding:!1,cell:({row:n})=>e(Je,{label:e(Oe,{}),data:n.original,items:t}),enableSorting:!1})];function wn(){return G()}function xn({path:t,columns:n,filterConfig:r,columnsToHideByDefault:i={},allowSelection:o=!1,initialFilters:p=[],tableActions:s,rowActions:d}){const[f,m]=T({pagination:{pageIndex:0,pageSize:20},sorting:[]}),{sorting:S,pagination:u}=f,[c,h]=T(""),[g,b]=T({}),[F,Y]=T(p),ee=le(()=>F.map(a=>Array.isArray(a.value)?{[a.property]:{[a.operator]:a.value.join(",")}}:{[a.property]:{[a.operator]:a.value}}).reduce((a,I)=>Te(a,I),{}),[F]),te={...F,page:u.pageIndex+1,limit:u.pageSize,sort:mt(S[0]),search:c},ne=dt(),D=["get",t],[L,j]=V(`${D.join("")}_ctx_column_order_preference`,[]),[E,re]=V(`${D.join("")}_ctx_column_visibility_preference`,{id:!1,...i}),R=a=>{m(I=>({...I,...a}))},A=xe({queryKey:D,queryFn:async()=>{const a=await ne.GET(t,{params:{query:te}});return{data:a.data??[],total:Number.parseInt(a.response.headers.get("Pagination-Count")||"0")}}}),ae=[...o?gt:[],...n,...pt(d??[])];function oe(a){return typeof a=="function"}function N(a,I){return oe(a)?a(I):a}const $=Ne({data:A.data?.data??[],columns:ae,getCoreRowModel:Ie(),rowCount:A.data?.total??0,manualPagination:!0,onPaginationChange:a=>{R({pagination:N(a,u)})},manualSorting:!0,onSortingChange:a=>{b({}),R({sorting:[...N(a,S)]})},manualFiltering:!0,onColumnVisibilityChange:a=>{re(N(a,E))},onRowSelectionChange:a=>{b(N(a,g))},onColumnOrderChange:a=>{j(N(a,L))},state:{sorting:S,columnVisibility:E,pagination:u,rowSelection:g,columnOrder:L},meta:{refetch:A.refetch}});return se(()=>{j([...$.getAllLeafColumns().map(a=>a.id)])},[]),{tableState:f,updateTableState:R,query:A,setSearchQuery:h,searchQuery:c,tanTable:$,mergedFilters:ee,filters:F,setFilters:Y,filterConfig:r,tableActions:s}}const Z=ie(null);function x(){const t=ce(Z);if(!t)throw Error("DataTable should be used within DataTableProvider.");return t}function Nn({children:t,...n}){return e(Z.Provider,{value:n,children:t})}function In({className:t,...n}){const{query:r,tanTable:i}=x();return e(w,{children:l("section",{...n,className:y("flex flex-col bg-elevation-1",t),children:[e(St,{}),l("div",{className:"w-full overflow-auto border-x h-table relative",tabIndex:0,children:[r.isLoading&&e(K,{className:"cursor-wait",children:e(We,{})}),!r.isLoading&&i.getRowModel().rows.length===0&&e(K,{className:"cursor-not-allowed",children:!r.isFetching&&(r.isError?l("span",{className:"flex gap-3 justify-center items-center",children:[e(ze,{}),e("span",{children:r.error.message})]}):r.data?.data?.length===0?e(w,{children:"No results found."}):e(w,{children:"Unknown error. Please contact customer support."}))}),!r.isLoading&&i.getRowModel().rows.length!==0&&e(vt,{className:"w-full"})]}),l("div",{className:"flex w-full justify-between border gap-icon p-icon overflow-x-auto",children:[l("div",{className:"flex gap-icon",children:[e(ft,{}),e(bt,{})]}),e(ht,{})]})]})})}function K({children:t,className:n}){return l(w,{children:[e("span",{className:y(n,"absolute top-0 bg-elevation-1 text-foreground z-20 size-full body-sm flex items-center justify-center"),children:t}),e("span",{className:"relative h-full w-0 block"})]})}function ft(){const{tanTable:t}=x(),[n,r]=T(null),i=_(),o=de(q(me),q(ge,{coordinateGetter:be}));return e(pe,{sensors:o,collisionDetection:fe,onDragStart:s=>{const{active:d}=s;r(d.id.toString())},onDragEnd:s=>{const{active:d,over:f}=s;if(f&&d.id!==f.id){const m=t.getState().columnOrder,S=m.indexOf(d.id.toString()),u=m.indexOf(f.id.toString());t.setColumnOrder([...ve(m,S,u)])}r(null)},children:l(Se,{items:t.getState().columnOrder,strategy:ye,children:[l(M,{label:l(w,{children:[e(_e,{className:"inline align-bottom me-1"}),"Columns"]}),selectionMode:"multiple",items:t.getAllFlatColumns(),selectedKeys:t.getVisibleFlatColumns().map(s=>s.id),children:[e(P,{onAction:()=>t.toggleAllColumnsVisible(),className:"italic",children:"(select all)"}),t.getState().columnOrder.map(s=>{const d=t.getAllFlatColumns().find(f=>f.id===s);return!d||d.id==="checkbox"||d.id===C?null:e(p,{column:d},d.id)})]}),e(he,{children:n?e("div",{className:"opacity-70 border-2 border-primary",children:i(n)}):null})]})});function p({column:s}){const{attributes:d,listeners:f,setNodeRef:m,transform:S,transition:u}=Ce({id:s.id}),c={transform:we.Transform.toString(S),transition:u,zIndex:"999"};return l(P,{ref:m,style:c,...d,id:s.id,onAction:()=>s.toggleVisibility(),isDisabled:!s.getCanHide(),className:"flex items-center",children:[e(Le,{...f,className:"size-icon cursor-grab"}),O(s),s.getIsSorted()&&e(J,{className:"size-icon",direction:s.getIsSorted()})]})}}function ht(){const{tanTable:t}=x(),n=t.getRowCount();return l("div",{className:"flex items-center gap-2",children:[e("span",{className:"whitespace-nowrap body-sm text-muted",children:`${t.getState().pagination.pageIndex*t.getState().pagination.pageSize+1} - ${Math.min((t.getState().pagination.pageIndex+1)*t.getState().pagination.pageSize,n)} of ${n?.toLocaleString()}`}),e(v,{"aria-label":"First page",onPress:()=>t.firstPage(),isDisabled:!t.getCanPreviousPage(),variant:"neutral",size:"icon",children:e(je,{})}),e(v,{"aria-label":"Previous page",onPress:()=>t.previousPage(),isDisabled:!t.getCanPreviousPage(),variant:"neutral",size:"icon",children:e(Ee,{})}),e(v,{"aria-label":"Next page",onPress:()=>t.nextPage(),isDisabled:!t.getCanNextPage(),variant:"neutral",size:"icon",children:e($e,{})}),e(v,{"aria-label":"Last page",onClick:()=>t.lastPage(),isDisabled:!t.getCanNextPage(),variant:"neutral",size:"icon",children:e(qe,{})})]})}function bt(){const{tanTable:t}=x(),n=[10,20,30,40,50];return e(M,{label:t.getState().pagination.pageSize.toString(),selectionMode:"single",selectedKeys:[t.getState().pagination.pageSize.toString()],items:n.map(r=>({id:r.toString(),value:r})),children:r=>e(P,{onAction:()=>t.setPageSize(r.value),children:r.value})})}function St(){const{query:t,tanTable:n,searchQuery:r,setSearchQuery:i,tableActions:o}=x(),p=n.getSelectedRowModel().rows.length>0,s=n.getSelectedRowModel().rows.map(f=>f.original),d=o.filter(f=>f.bulk===p);return l("section",{className:"flex bg-elevation-1 justify-between my-0 p-icon border gap-icon overflow-auto",children:[l("div",{className:"flex gap-icon",children:[e(v,{"aria-label":"Refresh",isPending:t.isFetching,onClick:()=>t.refetch(),variant:"neutral",size:"icon",children:e(Me,{})}),e(ut,{items:d,rowsSelected:s,isFetching:t.isFetching})]}),l("div",{className:"flex gap-icon",children:[e(xt,{}),e(Ye,{value:r,onChange:i})]})]})}function J({direction:t,...n}){return t==="asc"?e(Ve,{className:"size-3.5",...n}):t==="desc"?e(He,{className:"size-3.5",...n}):e(ke,{className:"size-3.5",...n})}function O(t){const n=_(),r=t.columnDef.header;return typeof r=="string"?r:n(t.id)}function yt(t){const n=t.column.columnDef.meta?.displayType,r=t.getValue();if(r==null)return null;switch(n){case"date":return it(r);case"number":return ct(r);case"boolean":case"badge":return e(Fe,{className:"uppercase w-full",children:String(r)});case"country":return e(ot,{value:r});case"enum":return e("span",{className:"uppercase w-full",children:String(r)});case"fileSize":return st(r);case"days":return lt(r);default:return String(r)}}function Q({header:t}){const n=t.column.columnDef.header;return typeof n=="string"||!n?O(t.column):typeof n=="function"?typeof n(t.getContext())=="string"?O(t.column):z(n,t.getContext()):z(n,t.getContext())}function vt({className:t}){const{tanTable:n}=x(),r=(i,o,p="z-50")=>y("px-icon py-2 text-left body-sm font-medium whitespace-nowrap",i&&`bg-elevation-1 sticky right-0 ${p} text-center justify-center`,o);return l(et,{className:y("table-auto",t),children:[e(tt,{className:"sticky top-0 z-10",children:n.getHeaderGroups().map(i=>e(U,{children:i.headers.map(o=>l(nt,{scope:"col",colSpan:o.colSpan,className:r(o.id===C,"bg-elevation-1"),children:[!o.column.getCanSort()&&!o.isPlaceholder&&e("div",{className:y("w-full py-1 inline-flex items-center gap-1 body-sm",o.id===C?"justify-center":"justify-start"),children:e(Q,{header:o})}),o.column.getCanSort()&&l(v,{variant:"ghost",className:y("w-full p-1",o.id===C?"justify-center":"justify-start"),onPress:o.column.getToggleSortingHandler(),children:[e("span",{children:e(Q,{header:o})}),e(J,{direction:o.column.getIsSorted()})]})]},o.id))},i.id))}),e(rt,{children:n.getRowModel().rows.map(i=>e(U,{className:y("transition-colors data-[selected=true]:bg-primary/10 hover:bg-muted-foreground/20"),"data-selected":i.getIsSelected(),children:i.getVisibleCells().map(o=>{const p=o.column.id===C,s=o.column.columnDef.meta?.displayType?yt(o):z(o.column.columnDef.cell,o.getContext());return e(at,{className:y(r(p,void 0,"z-1"),p&&"flex justify-center items-center"),children:s},o.id)})},i.id))})]})}const Tn=["eq","ne","cn","nc","sw","ew","in","nin","gt","gte","lt","lte"],Ct={eq:"equal to",ne:"not equal to",cn:"contains",nc:"does not contain",sw:"starts with",ew:"ends with",in:"includes",nin:"does not include",gt:"greater than",gte:"greater than or equal to",lt:"less than",lte:"less than or equal to"};function wt(t,n){const r=`${n}-${Date.now()}`,i=W[t][0];switch(t){case"bool":return{id:r,type:t,property:n,operator:i,value:!0};case"string":return{id:r,type:t,property:n,operator:i,value:""};case"date":return{id:r,type:t,property:n,operator:i,value:new Date().toISOString()};case"id":return{id:r,type:t,property:n,operator:i,value:""};case"id-search":return{id:r,type:t,property:n,operator:i,value:[]};case"enum":return{id:r,type:t,property:n,operator:i,value:new Set};case"number":return{id:r,type:t,property:n,operator:i,value:0}}}const W={bool:["eq"],enum:["in","nin"],id:["in","nin"],"id-search":["in","nin"],string:["eq","ne","cn","nc","sw","ew","in","nin"],date:["lt","gt"],number:["eq","ne","gt","gte","lt","lte"]};function xt({className:t,...n}){const{filters:r,query:i,setFilters:o,filterConfig:p}=x(),s=ue(null),d=_(),m=Re({defaultValues:{filters:r},onSubmit:({value:u})=>{o(u.filters)}}),S=Object.keys(p).sort();return e("section",{...n,className:y("flex gap-icon items-center",t),children:l(Pe,{onOpenChange:u=>{u?s.current?.focus():m.handleSubmit()},children:[l("div",{className:"relative",children:[r.length>0&&e("div",{className:"size-2 rounded-full absolute bg-primary/90 z-20 top-0 right-0 translate-x-0.5 -translate-y-0.5"}),e(v,{"aria-label":"Filter",isDisabled:i.isPending||S.length===0,type:"button",size:"icon",variant:"neutral",children:e(Ue,{})})]}),e(De,{className:"w-full p-icon",children:e("form",{onSubmit:u=>{u.preventDefault()},className:"flex flex-col gap-icon max-h-table overflow-auto ",children:e(m.Field,{mode:"array",name:"filters",children:u=>l(w,{children:[u.state.value.map((c,h)=>l("div",{className:"flex gap-icon items-center justify-normal",children:[e("span",{className:"body-sm",children:d(c.property)}),e(m.AppField,{name:`filters[${h}].operator`,children:g=>e(g.TfSingleSelect,{items:W[c.type].map(b=>({id:b,label:e(w,{children:Ct[b]})}))})},c.id),c.type==="bool"&&e(m.AppField,{name:`filters[${h}].value`,children:g=>e(g.TfCheckbox,{autoFocus:!0})}),c.type==="date"&&e(m.AppField,{name:`filters[${h}].value`,children:g=>e(Ae,{autoFocus:!0})}),c.type==="id"&&e(m.AppField,{name:`filters[${h}].value`,children:g=>e(g.TfTextField,{autoFocus:!0})}),c.type==="string"&&e(m.AppField,{name:`filters[${h}].value`,children:g=>e(g.TfTextField,{autoFocus:!0})}),c.type==="number"&&e(m.AppField,{name:`filters[${h}].value`,children:g=>e(g.TfNumberField,{autoFocus:!0})}),c.type==="enum"&&e(m.AppField,{name:`filters[${h}].value`,children:g=>{const b=p[c.property];return b.type!=="enum"?null:e(g.TfMultiSelect,{items:b.options})}}),c.type==="id-search"&&e(m.AppField,{name:`filters[${h}].value`,children:g=>{const b=p[c.property];return b.type!=="id-search"?null:e(Ze,{path:b.path,accessor:b.accessor})}}),e(v,{type:"button",variant:"neutral",size:"icon",onPress:()=>u.removeValue(h),children:e(H,{})})]},c.id)),l("div",{className:"flex w-full items-center justify-end gap-2 not-first:mt-icon",children:[e(M,{label:"Add filter",autoFocus:!0,children:S.sort().map(c=>{const h=p[c].type,g=Nt[h];return l(P,{onAction:()=>{const b=wt(h,c);u.pushValue(b)},children:[d(c),e(g,{})]},c)})}),u.state.value.length>0?l(v,{type:"button",variant:"neutral",onPress:()=>{u.setValue([])},children:[e(H,{}),"Reset"]}):null]})]})})})})]})})}const Nt={"id-search":Xe,bool:k,date:Ge,enum:Qe,id:Ke,number:Be,string:k};export{Ct as C,xt as D,In as DataTable,Z as DataTableContext,Nn as DataTableProvider,Tn as F,wn as getColumnHelper,x as useDataTable,xn as useDataTableState};
|
|
1
|
+
"use client";import{jsx as e,Fragment as w,jsxs as s}from"react/jsx-runtime";import{createContext as le,useState as T,useMemo as se,useEffect as ce,useContext as ue,useRef as de}from"react";import{Button as y}from"./button.js";import{useSensors as me,useSensor as V,PointerSensor as ge,KeyboardSensor as pe,DndContext as fe,closestCenter as he,DragOverlay as be}from"@dnd-kit/core";import{sortableKeyboardCoordinates as Se,SortableContext as ye,verticalListSortingStrategy as ve,arrayMove as Ce,useSortable as we}from"@dnd-kit/sortable";import{CSS as xe}from"@dnd-kit/utilities";import{useQuery as Ne}from"@tanstack/react-query";import{createColumnHelper as X,useReactTable as Ie,getCoreRowModel as Te,flexRender as z}from"@tanstack/react-table";import{useLocalStorage as H}from"@uidotdev/usehooks";import{merge as Fe}from"lodash-es";import{Badge as Ae}from"./badge.js";import{TfDatePicker as Pe}from"./date-picker.js";import{EasyMenu as M,MenuItem as P}from"./menu.js";import{PopoverTrigger as De,Popover as Re}from"./popover.js";import{useAppForm as ze}from"../utilities/form-hook.js";import{useResourceFormatter as _}from"../utilities/resources.js";import{classNames as S}from"../utilities/theme.js";import{IcInfo as Oe,IcMoreVertical as Me,IcRefresh as _e,IcColumns as Le,IcGrip as je,IcFirst as Ee,IcLeft as $e,IcRight as qe,IcLast as Ve,IcSortAsc as He,IcSortDesc as ke,IcSortNone as Ue,IcFilter as Be,IcRemove as k,IcCheck as U,IcMinus as Ke,IcAccount as Qe,IcLicense as Ge,IcDate as Xe,IcFile as Ze}from"./icons.js";import{TfMultipleIdSearchInput as Je}from"./id-search.js";import{DialogMenu as We}from"./dialog-menu.js";import{Loader as Ye}from"./loader.js";import{SearchField as et}from"./searchfield.js";import{Table as tt,TableHeader as nt,TableRow as B,TableHead as rt,TableBody as at,TableCell as ot}from"./table.js";import{CountryName as it}from"../utilities/countries.js";import{formatDate as lt}from"../utilities/date.js";import{formatDays as st,formatFilesize as ct,formatNumber as ut}from"../utilities/numbers.js";import{Checkbox as K}from"./checkbox.js";import{TableActions as dt}from"./data-table-actions.js";import{useCtxClient as mt}from"../utilities/ctx-client.js";import"class-variance-authority";import"react-aria-components";import"@internationalized/date";import"./calendar.js";import"./form.js";import"./datefield.js";import"../utilities/form.js";import"../utilities/form-context.js";import"@tanstack/react-form";import"./list-box.js";import"./select.js";import"./multi-select.js";import"./numberfield.js";import"./textfield.js";import"../utilities/string.js";import"clsx";import"./dialog-action-utils.js";import"./dialog.js";import"./select-options.js";import"zod";import"../utilities/duration.js";function gt(t){return t?t.desc?`-${t.id}`:`+${t.id}`:"-createdAt"}const Z=X(),pt=[Z.accessor("checkbox",{header:({table:t})=>e(K,{isIndeterminate:t.getIsSomeRowsSelected()&&!t.getIsAllPageRowsSelected(),isSelected:t.getIsAllPageRowsSelected()||t.getIsSomePageRowsSelected(),onChange:()=>t.toggleAllPageRowsSelected(),"aria-label":"Select all"}),cell:({row:t})=>e(K,{isSelected:t.getIsSelected(),onChange:()=>t.toggleSelected(),"aria-label":"Select row"}),enableSorting:!1,enableHiding:!1})],C="TableActions",ft=t=>t.length===0?[]:[Z.accessor(C,{header:"Actions",id:C,enableHiding:!1,cell:({row:n})=>e(We,{label:e(Me,{}),data:n.original,items:t}),enableSorting:!1})];function xn(){return X()}function Nn({path:t,pathParameters:n,columns:r,filterConfig:i,columnsToHideByDefault:o={},allowSelection:p=!1,initialFilters:c=[],tableActions:u,rowActions:h}){const[d,v]=T({pagination:{pageIndex:0,pageSize:20},sorting:[]}),{sorting:m,pagination:l}=d,[f,g]=T(""),[b,L]=T({}),[F,ee]=T(c),te=se(()=>F.map(a=>Array.isArray(a.value)?{[a.property]:{[a.operator]:a.value.join(",")}}:{[a.property]:{[a.operator]:a.value}}).reduce((a,I)=>Fe(a,I),{}),[F]),ne={...F,page:l.pageIndex+1,limit:l.pageSize,sort:gt(m[0]),search:f},re=mt(),D=["get",t],[j,E]=H(`${D.join("")}_ctx_column_order_preference`,[]),[$,ae]=H(`${D.join("")}_ctx_column_visibility_preference`,{id:!1,...o}),R=a=>{v(I=>({...I,...a}))},A=Ne({queryKey:D,queryFn:async()=>{const a=await re.GET(t,{params:{query:ne,path:n}});return{data:a.data??[],total:Number.parseInt(a.response.headers.get("Pagination-Count")||"0")}}}),oe=[...p?pt:[],...r,...ft(h??[])];function ie(a){return typeof a=="function"}function N(a,I){return ie(a)?a(I):a}const q=Ie({data:A.data?.data??[],columns:oe,getCoreRowModel:Te(),rowCount:A.data?.total??0,manualPagination:!0,onPaginationChange:a=>{R({pagination:N(a,l)})},manualSorting:!0,onSortingChange:a=>{L({}),R({sorting:[...N(a,m)]})},manualFiltering:!0,onColumnVisibilityChange:a=>{ae(N(a,$))},onRowSelectionChange:a=>{L(N(a,b))},onColumnOrderChange:a=>{E(N(a,j))},state:{sorting:m,columnVisibility:$,pagination:l,rowSelection:b,columnOrder:j},meta:{refetch:A.refetch}});return ce(()=>{E([...q.getAllLeafColumns().map(a=>a.id)])},[]),{tableState:d,updateTableState:R,query:A,setSearchQuery:g,searchQuery:f,tanTable:q,mergedFilters:te,filters:F,setFilters:ee,filterConfig:i,tableActions:u}}const J=le(null);function x(){const t=ue(J);if(!t)throw Error("DataTable should be used within DataTableProvider.");return t}function In({children:t,...n}){return e(J.Provider,{value:n,children:t})}function Tn({className:t,...n}){const{query:r,tanTable:i}=x();return e(w,{children:s("section",{...n,className:S("flex flex-col bg-elevation-1",t),children:[e(yt,{}),s("div",{className:"w-full overflow-auto border-x h-table relative",tabIndex:0,children:[r.isLoading&&e(Q,{className:"cursor-wait",children:e(Ye,{})}),!r.isLoading&&i.getRowModel().rows.length===0&&e(Q,{className:"cursor-not-allowed",children:!r.isFetching&&(r.isError?s("span",{className:"flex gap-3 justify-center items-center",children:[e(Oe,{}),e("span",{children:r.error.message})]}):r.data?.data?.length===0?e(w,{children:"No results found."}):e(w,{children:"Unknown error. Please contact customer support."}))}),!r.isLoading&&i.getRowModel().rows.length!==0&&e(Ct,{className:"w-full"})]}),s("div",{className:"flex w-full justify-between border gap-icon p-icon overflow-x-auto",children:[s("div",{className:"flex gap-icon",children:[e(ht,{}),e(St,{})]}),e(bt,{})]})]})})}function Q({children:t,className:n}){return s(w,{children:[e("span",{className:S(n,"absolute top-0 bg-elevation-1 text-foreground z-20 size-full body-sm flex items-center justify-center"),children:t}),e("span",{className:"relative h-full w-0 block"})]})}function ht(){const{tanTable:t}=x(),[n,r]=T(null),i=_(),o=me(V(ge),V(pe,{coordinateGetter:Se}));return e(fe,{sensors:o,collisionDetection:he,onDragStart:c=>{const{active:u}=c;r(u.id.toString())},onDragEnd:c=>{const{active:u,over:h}=c;if(h&&u.id!==h.id){const d=t.getState().columnOrder,v=d.indexOf(u.id.toString()),m=d.indexOf(h.id.toString());t.setColumnOrder([...Ce(d,v,m)])}r(null)},children:s(ye,{items:t.getState().columnOrder,strategy:ve,children:[s(M,{label:s(w,{children:[e(Le,{className:"inline align-bottom me-1"}),"Columns"]}),selectionMode:"multiple",items:t.getAllFlatColumns(),selectedKeys:t.getVisibleFlatColumns().map(c=>c.id),children:[e(P,{onAction:()=>t.toggleAllColumnsVisible(),className:"italic",children:"(select all)"}),t.getState().columnOrder.map(c=>{const u=t.getAllFlatColumns().find(h=>h.id===c);return!u||u.id==="checkbox"||u.id===C?null:e(p,{column:u},u.id)})]}),e(be,{children:n?e("div",{className:"opacity-70 border-2 border-primary",children:i(n)}):null})]})});function p({column:c}){const{attributes:u,listeners:h,setNodeRef:d,transform:v,transition:m}=we({id:c.id}),l={transform:xe.Transform.toString(v),transition:m,zIndex:"999"};return s(P,{ref:d,style:l,...u,id:c.id,onAction:()=>c.toggleVisibility(),isDisabled:!c.getCanHide(),className:"flex items-center",children:[e(je,{...h,className:"size-icon cursor-grab"}),O(c),c.getIsSorted()&&e(W,{className:"size-icon",direction:c.getIsSorted()})]})}}function bt(){const{tanTable:t}=x(),n=t.getRowCount();return s("div",{className:"flex items-center gap-2",children:[e("span",{className:"whitespace-nowrap body-sm text-muted",children:`${t.getState().pagination.pageIndex*t.getState().pagination.pageSize+1} - ${Math.min((t.getState().pagination.pageIndex+1)*t.getState().pagination.pageSize,n)} of ${n?.toLocaleString()}`}),e(y,{"aria-label":"First page",onPress:()=>t.firstPage(),isDisabled:!t.getCanPreviousPage(),variant:"neutral",size:"icon",children:e(Ee,{})}),e(y,{"aria-label":"Previous page",onPress:()=>t.previousPage(),isDisabled:!t.getCanPreviousPage(),variant:"neutral",size:"icon",children:e($e,{})}),e(y,{"aria-label":"Next page",onPress:()=>t.nextPage(),isDisabled:!t.getCanNextPage(),variant:"neutral",size:"icon",children:e(qe,{})}),e(y,{"aria-label":"Last page",onClick:()=>t.lastPage(),isDisabled:!t.getCanNextPage(),variant:"neutral",size:"icon",children:e(Ve,{})})]})}function St(){const{tanTable:t}=x(),n=[10,20,30,40,50];return e(M,{label:t.getState().pagination.pageSize.toString(),selectionMode:"single",selectedKeys:[t.getState().pagination.pageSize.toString()],items:n.map(r=>({id:r.toString(),value:r})),children:r=>e(P,{onAction:()=>t.setPageSize(r.value),children:r.value})})}function yt(){const{query:t,tanTable:n,searchQuery:r,setSearchQuery:i,tableActions:o}=x(),p=n.getSelectedRowModel().rows.length>0,c=n.getSelectedRowModel().rows.map(h=>h.original),u=o.filter(h=>h.bulk===p);return s("section",{className:"flex bg-elevation-1 justify-between my-0 p-icon border gap-icon overflow-auto",children:[s("div",{className:"flex gap-icon",children:[e(y,{"aria-label":"Refresh",isPending:t.isFetching,onClick:()=>t.refetch(),variant:"neutral",size:"icon",children:e(_e,{})}),e(dt,{items:u,rowsSelected:c,isFetching:t.isFetching})]}),s("div",{className:"flex gap-icon",children:[e(Nt,{}),e(et,{value:r,onChange:i})]})]})}function W({direction:t,...n}){return t==="asc"?e(He,{className:"size-3.5",...n}):t==="desc"?e(ke,{className:"size-3.5",...n}):e(Ue,{className:"size-3.5",...n})}function O(t){const n=_(),r=t.columnDef.header;return typeof r=="string"?r:n(t.id)}function vt(t){const n=t.column.columnDef.meta?.displayType,r=t.getValue();if(r==null)return null;switch(n){case"date":return lt(r);case"number":return ut(r);case"boolean":case"badge":return e(Ae,{className:"uppercase w-full",children:String(r)});case"country":return e(it,{value:r});case"enum":return e("span",{className:"uppercase w-full",children:String(r)});case"fileSize":return ct(r);case"days":return st(r);default:return String(r)}}function G({header:t}){const n=t.column.columnDef.header;return typeof n=="string"||!n?O(t.column):typeof n=="function"?typeof n(t.getContext())=="string"?O(t.column):z(n,t.getContext()):z(n,t.getContext())}function Ct({className:t}){const{tanTable:n}=x(),r=(i,o,p="z-50")=>S("px-icon py-2 text-left body-sm font-medium whitespace-nowrap",i&&`bg-elevation-1 sticky right-0 ${p} text-center justify-center`,o);return s(tt,{className:S("table-auto",t),children:[e(nt,{className:"sticky top-0 z-10",children:n.getHeaderGroups().map(i=>e(B,{children:i.headers.map(o=>s(rt,{scope:"col",colSpan:o.colSpan,className:r(o.id===C,"bg-elevation-1"),children:[!o.column.getCanSort()&&!o.isPlaceholder&&e("div",{className:S("w-full py-1 inline-flex items-center gap-1 body-sm",o.id===C?"justify-center":"justify-start"),children:e(G,{header:o})}),o.column.getCanSort()&&s(y,{variant:"ghost",className:S("w-full p-1",o.id===C?"justify-center":"justify-start"),onPress:o.column.getToggleSortingHandler(),children:[e("span",{children:e(G,{header:o})}),e(W,{direction:o.column.getIsSorted()})]})]},o.id))},i.id))}),e(at,{children:n.getRowModel().rows.map(i=>e(B,{className:S("transition-colors data-[selected=true]:bg-primary/10 hover:bg-muted-foreground/20"),"data-selected":i.getIsSelected(),children:i.getVisibleCells().map(o=>{const p=o.column.id===C,c=o.column.columnDef.meta?.displayType?vt(o):z(o.column.columnDef.cell,o.getContext());return e(ot,{className:S(r(p,void 0,"z-1"),p&&"flex justify-center items-center"),children:c},o.id)})},i.id))})]})}const Fn=["eq","ne","cn","nc","sw","ew","in","nin","gt","gte","lt","lte"],wt={eq:"equal to",ne:"not equal to",cn:"contains",nc:"does not contain",sw:"starts with",ew:"ends with",in:"includes",nin:"does not include",gt:"greater than",gte:"greater than or equal to",lt:"less than",lte:"less than or equal to"};function xt(t,n){const r=`${n}-${Date.now()}`,i=Y[t][0];switch(t){case"bool":return{id:r,type:t,property:n,operator:i,value:!0};case"string":return{id:r,type:t,property:n,operator:i,value:""};case"date":return{id:r,type:t,property:n,operator:i,value:new Date().toISOString()};case"id":return{id:r,type:t,property:n,operator:i,value:""};case"id-search":return{id:r,type:t,property:n,operator:i,value:[]};case"enum":return{id:r,type:t,property:n,operator:i,value:new Set};case"number":return{id:r,type:t,property:n,operator:i,value:0}}}const Y={bool:["eq"],enum:["in","nin"],id:["in","nin"],"id-search":["in","nin"],string:["eq","ne","cn","nc","sw","ew","in","nin"],date:["lt","gt"],number:["eq","ne","gt","gte","lt","lte"]};function Nt({className:t,...n}){const{filters:r,query:i,setFilters:o,filterConfig:p}=x(),c=de(null),u=_(),d=ze({defaultValues:{filters:r},onSubmit:({value:m})=>{o(m.filters)}}),v=Object.keys(p).sort();return e("section",{...n,className:S("flex gap-icon items-center",t),children:s(De,{onOpenChange:m=>{m?c.current?.focus():d.handleSubmit()},children:[s("div",{className:"relative",children:[r.length>0&&e("div",{className:"size-2 rounded-full absolute bg-primary/90 z-20 top-0 right-0 translate-x-0.5 -translate-y-0.5"}),e(y,{"aria-label":"Filter",isDisabled:i.isPending||v.length===0,type:"button",size:"icon",variant:"neutral",children:e(Be,{})})]}),e(Re,{className:"w-full p-icon",children:e("form",{onSubmit:m=>{m.preventDefault()},className:"flex flex-col gap-icon max-h-table overflow-auto ",children:e(d.Field,{mode:"array",name:"filters",children:m=>s(w,{children:[m.state.value.map((l,f)=>s("div",{className:"flex gap-icon items-center justify-normal",children:[e("span",{className:"body-sm",children:u(l.property)}),e(d.AppField,{name:`filters[${f}].operator`,children:g=>e(g.TfSingleSelect,{items:Y[l.type].map(b=>({id:b,label:e(w,{children:wt[b]})}))})},l.id),l.type==="bool"&&e(d.AppField,{name:`filters[${f}].value`,children:g=>e(g.TfCheckbox,{autoFocus:!0})}),l.type==="date"&&e(d.AppField,{name:`filters[${f}].value`,children:g=>e(Pe,{autoFocus:!0})}),l.type==="id"&&e(d.AppField,{name:`filters[${f}].value`,children:g=>e(g.TfTextField,{autoFocus:!0})}),l.type==="string"&&e(d.AppField,{name:`filters[${f}].value`,children:g=>e(g.TfTextField,{autoFocus:!0})}),l.type==="number"&&e(d.AppField,{name:`filters[${f}].value`,children:g=>e(g.TfNumberField,{autoFocus:!0})}),l.type==="enum"&&e(d.AppField,{name:`filters[${f}].value`,children:g=>{const b=p[l.property];return b.type!=="enum"?null:e(g.TfMultiSelect,{items:b.options})}}),l.type==="id-search"&&e(d.AppField,{name:`filters[${f}].value`,children:g=>{const b=p[l.property];return b.type!=="id-search"?null:e(Je,{path:b.path,accessor:b.accessor})}}),e(y,{type:"button",variant:"neutral",size:"icon",onPress:()=>m.removeValue(f),children:e(k,{})})]},l.id)),s("div",{className:"flex w-full items-center justify-end gap-2 not-first:mt-icon",children:[e(M,{label:"Add filter",autoFocus:!0,children:v.sort().map(l=>{const f=p[l].type,g=It[f];return s(P,{onAction:()=>{const b=xt(f,l);m.pushValue(b)},children:[u(l),e(g,{})]},l)})}),m.state.value.length>0?s(y,{type:"button",variant:"neutral",onPress:()=>{m.setValue([])},children:[e(k,{}),"Reset"]}):null]})]})})})})]})})}const It={"id-search":Ze,bool:U,date:Xe,enum:Ge,id:Qe,number:Ke,string:U};export{wt as C,Nt as D,Tn as DataTable,J as DataTableContext,In as DataTableProvider,Fn as F,xn as getColumnHelper,x as useDataTable,Nn as useDataTableState};
|
|
2
2
|
//# sourceMappingURL=data-table.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-table.js","sources":["../../lib/components/data-table.tsx","../../lib/components/data-table-filter.tsx"],"sourcesContent":["'use client';\nimport type { operations } from '@cryptlex/web-api-types/develop';\nimport {\n closestCenter,\n DndContext,\n DragOverlay,\n KeyboardSensor,\n PointerSensor,\n useSensor,\n useSensors,\n} from '@dnd-kit/core';\nimport {\n arrayMove,\n SortableContext,\n sortableKeyboardCoordinates,\n useSortable,\n verticalListSortingStrategy,\n} from '@dnd-kit/sortable';\nimport { CSS } from '@dnd-kit/utilities';\nimport { useQuery } from '@tanstack/react-query';\n\nimport {\n type Column,\n type ColumnDef,\n type ColumnOrderState,\n createColumnHelper,\n flexRender,\n getCoreRowModel,\n type Header,\n type PaginationState,\n type RowData,\n type RowSelectionState,\n type SortingState,\n type Updater,\n useReactTable,\n type VisibilityState,\n} from '@tanstack/react-table';\nimport { useLocalStorage } from '@uidotdev/usehooks';\nimport { merge } from 'lodash-es';\nimport { createContext, useContext, useEffect, useMemo, useState } from 'react';\nimport { Badge } from '../components/badge';\n\nimport { Button } from '../components/button';\nimport { DataTableFilter, type FiltersConfig, type TableFilter } from '../components/data-table-filter';\nimport { DialogMenu, type DialogMenuAction } from '../components/dialog-menu';\nimport { Loader } from '../components/loader';\nimport { EasyMenu, MenuItem } from '../components/menu';\nimport { SearchField } from '../components/searchfield';\nimport { TableBody, TableCell, Table as TableComponent, TableHead, TableHeader, TableRow } from '../components/table';\nimport { CountryName } from '../utilities/countries';\nimport { formatDate } from '../utilities/date';\nimport { formatDays, formatFilesize, formatNumber } from '../utilities/numbers';\nimport { type ApiResponseBody, useResourceFormatter } from '../utilities/resources';\nimport { classNames } from '../utilities/theme';\nimport { Checkbox } from './checkbox';\nimport { type TableAction, TableActions } from './data-table-actions';\nimport {\n IcColumns,\n IcFirst,\n IcGrip,\n IcInfo,\n IcLast,\n IcLeft,\n IcMoreVertical,\n IcRefresh,\n IcRight,\n IcSortAsc,\n IcSortDesc,\n IcSortNone,\n} from './icons';\n\nimport type { Cell, ColumnHelper } from '@tanstack/react-table';\nimport type { ClientPathsWithMethod } from 'openapi-fetch';\nimport { type CtxClientType, useCtxClient } from '../utilities/ctx-client';\nexport type DisplayType = 'string' | 'boolean' | 'date' | 'number' | 'enum' | 'badge' | 'country' | 'fileSize' | 'days';\n\ndeclare module '@tanstack/react-table' {\n interface ColumnMeta<TData extends RowData, TValue> {\n displayType: DisplayType;\n }\n}\n\nfunction generateSortParam(sort: { id: string; desc: boolean } | undefined): string {\n if (sort) {\n if (sort.desc) {\n return `-${sort.id}`;\n } else {\n return `+${sort.id}`;\n }\n } else {\n return '-createdAt';\n }\n}\n\nconst cH = createColumnHelper<any>();\nconst TABLE_CHECK_BOX_COLUMN = [\n cH.accessor('checkbox', {\n header: ({ table }) => (\n <Checkbox\n isIndeterminate={table.getIsSomeRowsSelected() && !table.getIsAllPageRowsSelected()}\n isSelected={table.getIsAllPageRowsSelected() || table.getIsSomePageRowsSelected()}\n onChange={() => table.toggleAllPageRowsSelected()}\n aria-label=\"Select all\"\n />\n ),\n\n cell: ({ row }) => (\n <Checkbox isSelected={row.getIsSelected()} onChange={() => row.toggleSelected()} aria-label=\"Select row\" />\n ),\n enableSorting: false,\n enableHiding: false,\n }),\n];\n\nconst ACTIONS_COLUMN_ID = 'TableActions';\nconst getActionColumn = (rowActions: DialogMenuAction<any>[]) => {\n if (rowActions.length === 0) return [];\n\n return [\n cH.accessor(ACTIONS_COLUMN_ID, {\n header: 'Actions',\n id: ACTIONS_COLUMN_ID,\n enableHiding: false,\n cell: ({ row }) => <DialogMenu label={<IcMoreVertical />} data={row.original} items={rowActions} />,\n enableSorting: false,\n }),\n ];\n};\n\ntype DataTableFactory<T extends object, TOperation extends keyof operations> = {\n path: NoInfer<ClientPathsWithMethod<CtxClientType, 'get'>>;\n columns: ColumnDef<T, any>[];\n tableActions: TableAction<T>[];\n columnsToHideByDefault?: Partial<Record<keyof T, boolean>>; // Columns that are hidden by default\n allowSelection?: boolean;\n filterConfig: FiltersConfig<TOperation>;\n initialFilters: TableFilter[];\n rowActions?: DialogMenuAction<T>[];\n};\n\ntype DataTableState = {\n sorting: SortingState;\n pagination: PaginationState;\n};\n\nexport function getColumnHelper<O extends keyof operations>(): ColumnHelper<ApiResponseBody<O>> {\n return createColumnHelper<ApiResponseBody<O>>();\n}\n/**\n * Hook for handling all data-table state. Used in DataTableContext\n */\nexport function useDataTableState<T extends object, TOperation extends keyof operations>({\n path,\n columns,\n filterConfig,\n columnsToHideByDefault = {},\n allowSelection = false,\n initialFilters = [],\n tableActions,\n rowActions,\n}: DataTableFactory<T, TOperation>) {\n const [tableState, _setTableState] = useState<DataTableState>({\n /** Reflect in URL in host application */\n pagination: { pageIndex: 0, pageSize: 20 }, // Pagination state\n sorting: [], // Sorting state\n });\n\n const { sorting, pagination } = tableState;\n\n const [searchQuery, setSearchQuery] = useState('');\n\n const [rowSelection, setRowSelection] = useState<RowSelectionState>({});\n\n /** Reflect in URL in host application */\n const [filters, setFilters] = useState(initialFilters);\n const mergedFilters = useMemo(() => {\n // TODO, generic transform fn\n return filters\n .map(tf => {\n if (Array.isArray(tf.value)) {\n return {\n [tf.property]: {\n [tf.operator]: tf.value.join(','),\n },\n };\n }\n return {\n [tf.property]: {\n [tf.operator]: tf.value,\n },\n };\n })\n .reduce((acc, current) => {\n return merge(acc, current);\n }, {});\n }, [filters]);\n\n const queryParameters = {\n ...filters,\n page: pagination.pageIndex + 1,\n limit: pagination.pageSize,\n sort: generateSortParam(sorting[0]),\n search: searchQuery,\n };\n\n const client = useCtxClient();\n // TODO, this seems incorrect, verify\n const queryKey = ['get', path];\n\n const [columnOrder, setColumnOrder] = useLocalStorage<ColumnOrderState>(\n `${queryKey.join('')}_ctx_column_order_preference`,\n []\n );\n const [columnVisibility, setColumnVisibility] = useLocalStorage<VisibilityState>(\n `${queryKey.join('')}_ctx_column_visibility_preference`,\n {\n id: false,\n ...columnsToHideByDefault,\n }\n );\n\n // Update table state with new values\n const updateTableState = (updates: Partial<DataTableState>) => {\n _setTableState(prev => ({ ...prev, ...updates }));\n };\n\n const query = useQuery({\n queryKey,\n queryFn: async () => {\n const res = await client.GET(path, { params: { query: queryParameters } });\n return {\n data: (res.data ?? []) as T[],\n total: Number.parseInt(res.response.headers.get('Pagination-Count') || '0'),\n };\n },\n });\n /**\n * ID,createdAt and updatedAt will be added by default for all tables\n * If selection is allowed, checkbox will be added\n * If the dto has metadata, dynamics columns for all the metadata key-value will be added(particular for a view)\n * If there are actions for the table, they will be placed fixed at the right side of table.\n */\n const cols: ColumnDef<any, any>[] = [\n ...(allowSelection ? TABLE_CHECK_BOX_COLUMN : []),\n ...columns,\n ...getActionColumn(rowActions ?? []),\n ];\n\n // Type-guard for updater\n function isUpdaterFunction<T>(updater: Updater<T>): updater is (old: T) => T {\n return typeof updater === 'function';\n }\n // Utility function to resolve updater\n function resolveUpdater<T>(updater: Updater<T>, currentValue: T) {\n if (isUpdaterFunction(updater)) {\n return updater(currentValue);\n }\n return updater;\n }\n\n // Use react-table's hook to create the table instance\n const tanTable = useReactTable({\n data: query.data?.data ?? [],\n columns: cols,\n getCoreRowModel: getCoreRowModel(),\n rowCount: query.data?.total ?? 0,\n manualPagination: true, // Handle pagination manually since pagination is done server side for data tables\n onPaginationChange: updater => {\n updateTableState({ pagination: resolveUpdater(updater, pagination) });\n },\n manualSorting: true, // Handle sorting manually since sorting is done server side for data tables\n onSortingChange: updater => {\n setRowSelection({});\n updateTableState({ sorting: [...resolveUpdater(updater, sorting)] }); // Reset selection when sorting.\n },\n manualFiltering: true, // Handle filtering manually since filtering is done server side for data tables\n onColumnVisibilityChange: updater => {\n setColumnVisibility(resolveUpdater(updater, columnVisibility));\n },\n onRowSelectionChange: updater => {\n setRowSelection(resolveUpdater(updater, rowSelection));\n },\n onColumnOrderChange: updater => {\n setColumnOrder(resolveUpdater(updater, columnOrder));\n },\n state: {\n sorting: sorting,\n columnVisibility: columnVisibility,\n pagination: pagination,\n rowSelection: rowSelection,\n columnOrder: columnOrder,\n },\n meta: {\n refetch: query.refetch,\n },\n });\n\n // By default, ColumnDef does not give guarantees of column.id existing. Once useReactTable is called, all columns are assigned IDs.\n // This populates the columnIds in the columnOrder state\n useEffect(() => {\n setColumnOrder([...tanTable.getAllLeafColumns().map(c => c.id)]);\n }, []);\n\n return {\n tableState,\n updateTableState,\n query,\n setSearchQuery,\n searchQuery,\n tanTable,\n mergedFilters,\n filters,\n setFilters,\n filterConfig,\n tableActions,\n } as const;\n}\n\nexport const DataTableContext = createContext<ReturnType<typeof useDataTableState> | null>(null);\n// TODO, don't export this\nexport function useDataTable() {\n const ctx = useContext(DataTableContext);\n if (!ctx) {\n throw Error('DataTable should be used within DataTableProvider.');\n }\n return ctx;\n}\n\nexport function DataTableProvider<T extends object, TOperation extends keyof operations>({\n children,\n ...props\n}: { children: React.ReactNode } & ReturnType<typeof useDataTableState<T, TOperation>>) {\n // @ts-expect-error, propogating the generic type further will be more complex. Since this is a tightly coupled type, it should be okay but reviewed whenever useDataTableState changes.\n return <DataTableContext.Provider value={props}>{children}</DataTableContext.Provider>;\n}\n\nexport type DataTableProps = React.ComponentProps<'section'>;\nexport function DataTable({ className, ...props }: DataTableProps) {\n const { query, tanTable } = useDataTable();\n\n return (\n <>\n {/* Table Actions Section */}\n <section {...props} className={classNames('flex flex-col bg-elevation-1', className)}>\n <Actions />\n {/* The div here is necessary because TableContent is internally a <table> tag and does not respect width, height CSS */}\n <div className=\"w-full overflow-auto border-x h-table relative\" tabIndex={0}>\n {/* Table overlay with loader */}\n {query.isLoading && (\n <TableOverlay className=\"cursor-wait\">\n <Loader />\n </TableOverlay>\n )}\n {/* Table overlay for empty table */}\n {!query.isLoading && tanTable.getRowModel().rows.length === 0 && (\n // Empty table\n <TableOverlay className=\"cursor-not-allowed\">\n {!query.isFetching &&\n (query.isError ? (\n <span className=\"flex gap-3 justify-center items-center\">\n {/* TODO (mudasir-pandith) Check for 403 explicitly!! */}\n {/* <span>{query.error}</span> */}\n <IcInfo />\n <span>{query.error.message}</span>\n </span>\n ) : query.data?.data?.length === 0 ? (\n <>No results found.</>\n ) : (\n <>Unknown error. Please contact customer support.</>\n ))}\n </TableOverlay>\n )}\n {!query.isLoading && tanTable.getRowModel().rows.length !== 0 && (\n <TableContent className=\"w-full\" />\n )}\n </div>\n\n {/* Table Footer Section with Pagination and Column Picker */}\n <div className=\"flex w-full justify-between border gap-icon p-icon overflow-x-auto\">\n <div className=\"flex gap-icon\">\n <ColumnPicker />\n <PageSize />\n </div>\n <Paginator />\n </div>\n </section>\n </>\n );\n}\n/** Table overlay to be shown for loaders or other messages */\nfunction TableOverlay({ children, className }: { children: React.ReactNode; className?: string }) {\n return (\n <>\n <span\n className={classNames(\n className,\n 'absolute top-0 bg-elevation-1 text-foreground z-20 size-full body-sm flex items-center justify-center'\n )}\n >\n {children}\n </span>\n {/* Keep something in document flow with the correct height */}\n <span className=\"relative h-full w-0 block\" />\n </>\n );\n}\n\n// TODO, ?include query param on Licenses, Activations and other future resources that need this\nfunction ColumnPicker() {\n const { tanTable } = useDataTable();\n const [activeId, setActiveId] = useState<string | null>(null);\n\n const resourceFormatter = useResourceFormatter();\n\n const sensors = useSensors(\n useSensor(PointerSensor),\n useSensor(KeyboardSensor, {\n coordinateGetter: sortableKeyboardCoordinates,\n })\n );\n return (\n <DndContext\n sensors={sensors}\n collisionDetection={closestCenter}\n onDragStart={event => {\n const { active } = event;\n setActiveId(active.id.toString());\n }}\n onDragEnd={event => {\n const { active, over } = event;\n\n if (over && active.id !== over.id) {\n const columnOrder = tanTable.getState().columnOrder;\n const oldIndex = columnOrder.indexOf(active.id.toString());\n const newIndex = columnOrder.indexOf(over.id.toString());\n tanTable.setColumnOrder([...arrayMove(columnOrder, oldIndex, newIndex)]);\n }\n\n setActiveId(null);\n }}\n >\n <SortableContext items={tanTable.getState().columnOrder} strategy={verticalListSortingStrategy}>\n <EasyMenu\n label={\n <>\n <IcColumns className=\"inline align-bottom me-1\" />\n Columns\n </>\n }\n selectionMode=\"multiple\"\n items={tanTable.getAllFlatColumns()}\n // Using selectedKeys = 'all' does not mark MenuItems with isDisabled=true as selected. This is not the intended behaviour in this use-case.\n selectedKeys={tanTable.getVisibleFlatColumns().map(c => c.id)}\n >\n <MenuItem onAction={() => tanTable.toggleAllColumnsVisible()} className={'italic'}>\n (select all)\n </MenuItem>\n {tanTable.getState().columnOrder.map(colId => {\n const col = tanTable.getAllFlatColumns().find(c => c.id === colId);\n // Don't show checkbox and actions columns in picker\n if (!col || col.id === 'checkbox' || col.id === ACTIONS_COLUMN_ID) return null;\n return <SortableItem key={col.id} column={col} />;\n })}\n </EasyMenu>\n <DragOverlay>\n {activeId ? (\n <div className=\"opacity-70 border-2 border-primary\">{resourceFormatter(activeId)}</div>\n ) : null}\n </DragOverlay>\n </SortableContext>\n </DndContext>\n );\n\n function SortableItem({ column }: { column: Column<any, unknown> }) {\n const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: column.id });\n const style = {\n transform: CSS.Transform.toString(transform),\n transition,\n zIndex: '999',\n };\n return (\n <MenuItem\n ref={setNodeRef}\n style={style}\n {...attributes}\n id={column.id}\n onAction={() => column.toggleVisibility()}\n isDisabled={!column.getCanHide()}\n className=\"flex items-center\"\n >\n <IcGrip {...listeners} className=\"size-icon cursor-grab\" />\n {getColumnHeaderText(column)}\n {column.getIsSorted() && <SortIcon className=\"size-icon\" direction={column.getIsSorted()} />}\n </MenuItem>\n );\n }\n}\n\nfunction Paginator() {\n const { tanTable } = useDataTable();\n const rowCount = tanTable.getRowCount();\n return (\n <div className=\"flex items-center gap-2\">\n <span className=\"whitespace-nowrap body-sm text-muted\">\n {`${tanTable.getState().pagination.pageIndex * tanTable.getState().pagination.pageSize + 1} - ${Math.min(\n (tanTable.getState().pagination.pageIndex + 1) * tanTable.getState().pagination.pageSize,\n rowCount\n )} of ${rowCount?.toLocaleString()}`}\n </span>\n\n <Button\n aria-label=\"First page\"\n onPress={() => tanTable.firstPage()}\n isDisabled={!tanTable.getCanPreviousPage()}\n variant=\"neutral\"\n size={'icon'}\n >\n <IcFirst />\n </Button>\n <Button\n aria-label=\"Previous page\"\n onPress={() => tanTable.previousPage()}\n isDisabled={!tanTable.getCanPreviousPage()}\n variant=\"neutral\"\n size={'icon'}\n >\n <IcLeft />\n </Button>\n <Button\n aria-label=\"Next page\"\n onPress={() => tanTable.nextPage()}\n isDisabled={!tanTable.getCanNextPage()}\n variant=\"neutral\"\n size={'icon'}\n >\n <IcRight />\n </Button>\n <Button\n aria-label=\"Last page\"\n onClick={() => tanTable.lastPage()}\n isDisabled={!tanTable.getCanNextPage()}\n variant=\"neutral\"\n size={'icon'}\n >\n <IcLast />\n </Button>\n </div>\n );\n}\n\nfunction PageSize() {\n const { tanTable } = useDataTable();\n const PAGE_SIZES = [10, 20, 30, 40, 50];\n\n return (\n <EasyMenu\n label={tanTable.getState().pagination.pageSize.toString()}\n selectionMode=\"single\"\n selectedKeys={[tanTable.getState().pagination.pageSize.toString()]}\n items={PAGE_SIZES.map(s => ({ id: s.toString(), value: s }))}\n >\n {items => <MenuItem onAction={() => tanTable.setPageSize(items.value)}>{items.value}</MenuItem>}\n </EasyMenu>\n );\n}\n\nfunction Actions() {\n const { query, tanTable, searchQuery, setSearchQuery, tableActions } = useDataTable();\n const hasSelectedRows = tanTable.getSelectedRowModel().rows.length > 0;\n const selectedRows = tanTable.getSelectedRowModel().rows.map(r => r.original);\n\n const filteredActions = tableActions.filter(ta => ta.bulk === hasSelectedRows);\n\n return (\n <section className=\"flex bg-elevation-1 justify-between my-0 p-icon border gap-icon overflow-auto\">\n <div className=\"flex gap-icon\">\n <Button\n aria-label=\"Refresh\"\n isPending={query.isFetching}\n onClick={() => query.refetch()}\n variant={'neutral'}\n size={'icon'}\n >\n <IcRefresh />\n </Button>\n\n <TableActions items={filteredActions} rowsSelected={selectedRows} isFetching={query.isFetching} />\n </div>\n <div className=\"flex gap-icon\">\n <DataTableFilter />\n {<SearchField value={searchQuery} onChange={setSearchQuery} />}\n </div>\n </section>\n );\n}\n\nfunction SortIcon({\n direction,\n ...props\n}: { direction: 'asc' | 'desc' | false } & Omit<React.ComponentProps<'svg'>, 'direction'>) {\n if (direction === 'asc') return <IcSortAsc className=\"size-3.5\" {...props} />;\n else if (direction === 'desc') return <IcSortDesc className=\"size-3.5\" {...props} />;\n else return <IcSortNone className=\"size-3.5\" {...props} />;\n}\n\nfunction getColumnHeaderText(column: Column<any, unknown>): string {\n const resourceFormatter = useResourceFormatter();\n const headerDef = column.columnDef.header;\n return typeof headerDef === 'string' ? headerDef : resourceFormatter(column.id);\n}\n\n/**\n * Renders a cell value based on the displayType metadata\n * @param cell - The cell to render\n * @returns The formatted value as a React node\n */\nfunction renderCellByDisplayType(cell: Cell<any, any>): React.ReactNode {\n const displayType = cell.column.columnDef.meta?.displayType;\n const value = cell.getValue();\n\n if (value === null || value === undefined) {\n return null;\n }\n\n switch (displayType) {\n case 'date':\n return formatDate(value);\n\n case 'number':\n return formatNumber(value);\n case 'boolean':\n case 'badge':\n return <Badge className=\"uppercase w-full\">{String(value)}</Badge>;\n case 'country':\n return <CountryName value={value} />;\n case 'enum':\n return <span className=\"uppercase w-full\">{String(value)}</span>;\n case 'fileSize':\n return formatFilesize(value);\n case 'days':\n return formatDays(value);\n default:\n return String(value);\n }\n}\n\nfunction HeaderText({ header }: { header: Header<any, unknown> }) {\n const headerDef = header.column.columnDef.header;\n\n if (typeof headerDef === 'string' || !headerDef) {\n return getColumnHeaderText(header.column);\n }\n\n if (typeof headerDef === 'function') {\n const result = headerDef(header.getContext());\n if (typeof result === 'string') {\n return getColumnHeaderText(header.column);\n }\n return flexRender(headerDef, header.getContext());\n }\n\n return flexRender(headerDef, header.getContext());\n}\n\n// TODO, automate checking valid HTML\nfunction TableContent({ className }: React.ComponentProps<typeof TableComponent>) {\n const { tanTable } = useDataTable();\n const tableCellStyle = (isSticky: boolean, className?: string, zIndex: string = 'z-50') =>\n classNames(\n 'px-icon py-2 text-left body-sm font-medium whitespace-nowrap',\n isSticky && `bg-elevation-1 sticky right-0 ${zIndex} text-center justify-center`,\n className\n );\n return (\n <TableComponent className={classNames('table-auto', className)}>\n <TableHeader className=\"sticky top-0 z-10\">\n {tanTable.getHeaderGroups().map(headerGroup => (\n <TableRow key={headerGroup.id}>\n {headerGroup.headers.map(header => (\n <TableHead\n scope=\"col\"\n key={header.id}\n colSpan={header.colSpan}\n className={tableCellStyle(header.id === ACTIONS_COLUMN_ID, 'bg-elevation-1')}\n >\n {!header.column.getCanSort() && !header.isPlaceholder && (\n <div\n className={classNames(\n 'w-full py-1 inline-flex items-center gap-1 body-sm',\n header.id === ACTIONS_COLUMN_ID ? 'justify-center' : 'justify-start'\n )}\n >\n <HeaderText header={header} />\n </div>\n )}\n {header.column.getCanSort() && (\n <Button\n variant=\"ghost\"\n className={classNames(\n 'w-full p-1',\n header.id === ACTIONS_COLUMN_ID ? 'justify-center' : 'justify-start'\n )}\n onPress={header.column.getToggleSortingHandler()}\n >\n <span>\n <HeaderText header={header} />\n </span>\n <SortIcon direction={header.column.getIsSorted()} />\n </Button>\n )}\n </TableHead>\n ))}\n </TableRow>\n ))}\n </TableHeader>\n <TableBody>\n {tanTable.getRowModel().rows.map(row => (\n <TableRow\n className={classNames(\n 'transition-colors data-[selected=true]:bg-primary/10 hover:bg-muted-foreground/20'\n )}\n key={row.id}\n data-selected={row.getIsSelected()}\n >\n {row.getVisibleCells().map(cell => {\n const isActionsColumn = cell.column.id === ACTIONS_COLUMN_ID;\n const cellContent = cell.column.columnDef.meta?.displayType\n ? renderCellByDisplayType(cell)\n : flexRender(cell.column.columnDef.cell, cell.getContext());\n\n return (\n <TableCell\n key={cell.id}\n className={classNames(\n tableCellStyle(isActionsColumn, undefined, 'z-1'),\n isActionsColumn && 'flex justify-center items-center'\n )}\n >\n {cellContent}\n </TableCell>\n );\n })}\n </TableRow>\n ))}\n </TableBody>\n </TableComponent>\n );\n}\n","'use client';\nimport type { operations } from '@cryptlex/web-api-types/develop';\nimport { useRef } from 'react';\nimport { Button } from '../components/button';\nimport { useDataTable } from '../components/data-table';\nimport { TfDatePicker } from '../components/date-picker';\nimport { EasyMenu, MenuItem } from '../components/menu';\nimport type { MultiSelectProps } from '../components/multi-select';\nimport { Popover, PopoverTrigger } from '../components/popover';\nimport { useAppForm } from '../utilities/form-hook';\nimport { useResourceFormatter, type ApiFilters } from '../utilities/resources';\nimport { classNames } from '../utilities/theme';\nimport { IcAccount, IcCheck, IcDate, IcFile, IcFilter, IcLicense, IcMinus, IcRemove, type CtxIcon } from './icons';\nimport { TfMultipleIdSearchInput } from './id-search';\n\nexport const FILTER_COMPARISON_OPERATORS = [\n 'eq',\n 'ne',\n 'cn',\n 'nc',\n 'sw',\n 'ew',\n 'in',\n 'nin',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n] as const;\nexport type FilterComparisonOperator = (typeof FILTER_COMPARISON_OPERATORS)[number];\n\nexport const COMPARISON_OPERATOR_LABELS: Record<FilterComparisonOperator, string> = {\n eq: 'equal to',\n ne: 'not equal to',\n cn: 'contains',\n nc: 'does not contain',\n sw: 'starts with',\n ew: 'ends with',\n in: 'includes',\n nin: 'does not include',\n gt: 'greater than',\n gte: 'greater than or equal to',\n lt: 'less than',\n lte: 'less than or equal to',\n};\n\ntype BaseLocalFilter<T extends FilterType, V> = {\n id: string;\n type: T;\n property: string;\n operator: FilterComparisonOperator;\n value: V | undefined;\n displayValue?: string;\n};\ntype EnumLocalFilter = BaseLocalFilter<'enum', Set<string | number>>;\ntype IdLocalFilter = BaseLocalFilter<'id', string>;\ntype BoolLocalFilter = BaseLocalFilter<'bool', boolean>;\ntype StringLocalFilter = BaseLocalFilter<'string', string>;\ntype NumberLocalFilter = BaseLocalFilter<'number', number>;\n// DatePicker accepts a string,and converts it to a ZonedDateTime\ntype DateLocalFilter = BaseLocalFilter<'date', string>;\ntype IdSearchLocalFilter = BaseLocalFilter<'id-search', string[]>;\n// TODO, entitlementSets.productIds\nfunction createNewFilter(type: FilterType, property: string): TableFilter {\n const id = `${property}-${Date.now()}`;\n const operator = FilterOperations[type][0];\n\n switch (type) {\n case 'bool':\n return { id, type, property, operator, value: true };\n case 'string':\n return { id, type, property, operator, value: '' };\n case 'date':\n return { id, type, property, operator, value: new Date().toISOString() };\n case 'id':\n return { id, type, property, operator, value: '' };\n case 'id-search':\n return { id, type, property, operator, value: [] };\n case 'enum':\n return { id, type, property, operator, value: new Set<string | number>() };\n case 'number':\n return { id, type, property, operator, value: 0 };\n }\n}\n\nexport type TableFilter =\n | EnumLocalFilter\n | IdLocalFilter\n | BoolLocalFilter\n | StringLocalFilter\n | DateLocalFilter\n | IdSearchLocalFilter\n | NumberLocalFilter;\n\nexport type FilterConfig =\n | { type: 'enum'; options: MultiSelectProps['items'] }\n | ({ type: 'id-search' } & Pick<React.ComponentProps<typeof TfMultipleIdSearchInput>, 'accessor' | 'path'>)\n | { type: 'id' }\n | { type: 'bool' }\n | { type: 'string' }\n | { type: 'date' }\n | { type: 'number' };\n\nexport type FilterType = FilterConfig['type'];\n\nconst FilterOperations: Record<FilterType, FilterComparisonOperator[]> = {\n bool: ['eq'],\n enum: ['in', 'nin'],\n id: ['in', 'nin'],\n 'id-search': ['in', 'nin'],\n string: ['eq', 'ne', 'cn', 'nc', 'sw', 'ew', 'in', 'nin'],\n date: ['lt', 'gt'],\n number: ['eq', 'ne', 'gt', 'gte', 'lt', 'lte'],\n};\n\n// TS workaround to get rid of filterConfig: Required<Record<never, FilterConfig>>\nexport type FiltersConfig<TOperation extends keyof operations> = [keyof ApiFilters<TOperation>] extends [never]\n ? Record<string, FilterConfig>\n : Required<Record<keyof ApiFilters<TOperation>, FilterConfig>>;\n\nexport function DataTableFilter({ className, ...props }: React.ComponentProps<'section'>) {\n const { filters, query, setFilters, filterConfig } = useDataTable();\n\n const addFilterButtonRef = useRef<HTMLButtonElement>(null);\n\n const resourceFormatter = useResourceFormatter();\n\n const DEFAULT_VALUES: { filters: TableFilter[] } = {\n filters,\n };\n const form = useAppForm({\n defaultValues: DEFAULT_VALUES,\n onSubmit: ({ value }) => {\n setFilters(value.filters);\n },\n });\n\n // More reason to hate TS https://github.com/Microsoft/TypeScript/issues/12870\n const filterKeys = Object.keys(filterConfig).sort();\n\n return (\n <section {...props} className={classNames('flex gap-icon items-center', className)}>\n <PopoverTrigger\n onOpenChange={o => {\n // Set filters when the popover closes\n if (!o) {\n form.handleSubmit();\n } else {\n addFilterButtonRef.current?.focus();\n }\n }}\n >\n <div className=\"relative\">\n {filters.length > 0 && (\n <div className=\"size-2 rounded-full absolute bg-primary/90 z-20 top-0 right-0 translate-x-0.5 -translate-y-0.5\"></div>\n )}\n <Button\n aria-label=\"Filter\"\n isDisabled={query.isPending || filterKeys.length === 0}\n type=\"button\"\n size={'icon'}\n variant={'neutral'}\n >\n <IcFilter />\n </Button>\n </div>\n {/* TODO, icon maps with dynamic imports? */}\n {/* TODO open popover with form for property specific filter */}\n {/* TODO, icons here??? */}\n <Popover className=\"w-full p-icon\">\n <form\n onSubmit={e => {\n e.preventDefault();\n }}\n className=\"flex flex-col gap-icon max-h-table overflow-auto \"\n >\n <form.Field mode=\"array\" name={'filters'}>\n {field => {\n return (\n <>\n {field.state.value.map((lf, i) => {\n return (\n <div key={lf.id} className=\"flex gap-icon items-center justify-normal\">\n <span className=\"body-sm\">{resourceFormatter(lf.property)}</span>\n <form.AppField key={lf.id} name={`filters[${i}].operator`}>\n {sf => (\n <sf.TfSingleSelect\n items={FilterOperations[lf.type].map(op => ({\n id: op,\n label: <>{COMPARISON_OPERATOR_LABELS[op]}</>,\n }))}\n />\n )}\n </form.AppField>\n\n {lf.type === 'bool' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => <sf.TfCheckbox autoFocus />}\n </form.AppField>\n )}\n {lf.type === 'date' && (\n <form.AppField name={`filters[${i}].value`}>\n {_ => <TfDatePicker autoFocus />}\n </form.AppField>\n )}\n {lf.type === 'id' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => <sf.TfTextField autoFocus />}\n </form.AppField>\n )}\n {lf.type === 'string' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => <sf.TfTextField autoFocus />}\n </form.AppField>\n )}\n {lf.type === 'number' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => <sf.TfNumberField autoFocus />}\n </form.AppField>\n )}\n\n {lf.type === 'enum' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => {\n const config = filterConfig[lf.property];\n if (config.type !== 'enum') return null;\n return <sf.TfMultiSelect items={config.options} />;\n }}\n </form.AppField>\n )}\n\n {lf.type === 'id-search' && (\n <form.AppField name={`filters[${i}].value`}>\n {_ => {\n const config = filterConfig[lf.property];\n if (config.type !== 'id-search') return null;\n return (\n <TfMultipleIdSearchInput\n path={config.path}\n accessor={config.accessor}\n />\n );\n }}\n </form.AppField>\n )}\n\n <Button\n type=\"button\"\n variant=\"neutral\"\n size=\"icon\"\n onPress={() => field.removeValue(i)}\n >\n <IcRemove />\n </Button>\n </div>\n );\n })}\n <div className=\"flex w-full items-center justify-end gap-2 not-first:mt-icon\">\n <EasyMenu label=\"Add filter\" autoFocus>\n {filterKeys.sort().map(k => {\n const type = filterConfig[k].type;\n const Icon = FilterIcon[type];\n return (\n <MenuItem\n key={k}\n onAction={() => {\n const newFilter = createNewFilter(type, k);\n field.pushValue(newFilter);\n }}\n >\n {resourceFormatter(k)}\n <Icon />\n </MenuItem>\n );\n })}\n </EasyMenu>\n {field.state.value.length > 0 ? (\n <Button\n type=\"button\"\n variant=\"neutral\"\n onPress={() => {\n field.setValue([]);\n }}\n >\n <IcRemove />\n Reset\n </Button>\n ) : null}\n </div>\n </>\n );\n }}\n </form.Field>\n </form>\n </Popover>\n </PopoverTrigger>\n </section>\n );\n}\n\nconst FilterIcon: Record<FilterConfig['type'], CtxIcon> = {\n 'id-search': IcFile,\n bool: IcCheck,\n date: IcDate,\n enum: IcLicense,\n id: IcAccount,\n number: IcMinus,\n string: IcCheck,\n};\n"],"names":["generateSortParam","sort","cH","createColumnHelper","TABLE_CHECK_BOX_COLUMN","table","jsx","Checkbox","row","ACTIONS_COLUMN_ID","getActionColumn","rowActions","DialogMenu","IcMoreVertical","getColumnHelper","useDataTableState","path","columns","filterConfig","columnsToHideByDefault","allowSelection","initialFilters","tableActions","tableState","_setTableState","useState","sorting","pagination","searchQuery","setSearchQuery","rowSelection","setRowSelection","filters","setFilters","mergedFilters","useMemo","tf","acc","current","merge","queryParameters","client","useCtxClient","queryKey","columnOrder","setColumnOrder","useLocalStorage","columnVisibility","setColumnVisibility","updateTableState","updates","prev","query","useQuery","res","cols","isUpdaterFunction","updater","resolveUpdater","currentValue","tanTable","useReactTable","getCoreRowModel","useEffect","c","DataTableContext","createContext","useDataTable","ctx","useContext","DataTableProvider","children","props","DataTable","className","Fragment","classNames","Actions","jsxs","TableOverlay","Loader","IcInfo","TableContent","ColumnPicker","PageSize","Paginator","activeId","setActiveId","resourceFormatter","useResourceFormatter","sensors","useSensors","useSensor","PointerSensor","KeyboardSensor","sortableKeyboardCoordinates","DndContext","closestCenter","event","active","over","oldIndex","newIndex","arrayMove","SortableContext","verticalListSortingStrategy","EasyMenu","IcColumns","MenuItem","colId","col","SortableItem","DragOverlay","column","attributes","listeners","setNodeRef","transform","transition","useSortable","style","CSS","IcGrip","getColumnHeaderText","SortIcon","rowCount","Button","IcFirst","IcLeft","IcRight","IcLast","PAGE_SIZES","s","items","hasSelectedRows","selectedRows","r","filteredActions","ta","IcRefresh","TableActions","DataTableFilter","SearchField","direction","IcSortAsc","IcSortDesc","IcSortNone","headerDef","renderCellByDisplayType","cell","displayType","value","formatDate","formatNumber","Badge","CountryName","formatFilesize","formatDays","HeaderText","header","flexRender","tableCellStyle","isSticky","zIndex","TableComponent","TableHeader","headerGroup","TableRow","TableHead","TableBody","isActionsColumn","cellContent","TableCell","FILTER_COMPARISON_OPERATORS","COMPARISON_OPERATOR_LABELS","createNewFilter","type","property","id","operator","FilterOperations","addFilterButtonRef","useRef","form","useAppForm","filterKeys","PopoverTrigger","o","IcFilter","Popover","e","field","lf","i","sf","op","_","TfDatePicker","config","TfMultipleIdSearchInput","IcRemove","k","Icon","FilterIcon","newFilter","IcFile","IcCheck","IcDate","IcLicense","IcAccount","IcMinus"],"mappings":"wqFAkFA,SAASA,GAAkBC,EAAyD,CAChF,OAAIA,EACIA,EAAK,KACE,IAAIA,EAAK,EAAE,GAEX,IAAIA,EAAK,EAAE,GAGf,YAEf,CAEA,MAAMC,EAAKC,EAAA,EACLC,GAAyB,CAC3BF,EAAG,SAAS,WAAY,CACpB,OAAQ,CAAC,CAAE,MAAAG,CAAA,IACPC,EAACC,EAAA,CACG,gBAAiBF,EAAM,sBAAA,GAA2B,CAACA,EAAM,yBAAA,EACzD,WAAYA,EAAM,4BAA8BA,EAAM,0BA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,QAAQ,UACR,QAAS,IAAM,CACXiE,EAAM,SAAS,EAAE,CACrB,EAEA,SAAA,CAAAzL,EAACkM,EAAA,EAAS,EAAE,OAAA,CAAA,CAAA,EAGhB,IAAA,CAAA,CACR,CAAA,EACJ,CAER,CACJ,CAAA,CAAA,CACJ,CACJ,CAAA,CAAA,CAAA,EAER,CAER,CAEA,MAAMG,GAAoD,CACtD,YAAaE,GACb,KAAMC,EACN,KAAMC,GACN,KAAMC,GACN,GAAIC,GACJ,OAAQC,GACR,OAAQJ,CACZ"}
|
|
1
|
+
{"version":3,"file":"data-table.js","sources":["../../lib/components/data-table.tsx","../../lib/components/data-table-filter.tsx"],"sourcesContent":["'use client';\nimport type { operations } from '@cryptlex/web-api-types/develop';\nimport {\n closestCenter,\n DndContext,\n DragOverlay,\n KeyboardSensor,\n PointerSensor,\n useSensor,\n useSensors,\n} from '@dnd-kit/core';\nimport {\n arrayMove,\n SortableContext,\n sortableKeyboardCoordinates,\n useSortable,\n verticalListSortingStrategy,\n} from '@dnd-kit/sortable';\nimport { CSS } from '@dnd-kit/utilities';\nimport { useQuery } from '@tanstack/react-query';\n\nimport {\n type Column,\n type ColumnDef,\n type ColumnOrderState,\n createColumnHelper,\n flexRender,\n getCoreRowModel,\n type Header,\n type PaginationState,\n type RowData,\n type RowSelectionState,\n type SortingState,\n type Updater,\n useReactTable,\n type VisibilityState,\n} from '@tanstack/react-table';\nimport { useLocalStorage } from '@uidotdev/usehooks';\nimport { merge } from 'lodash-es';\nimport { createContext, useContext, useEffect, useMemo, useState } from 'react';\nimport { Badge } from '../components/badge';\n\nimport { Button } from '../components/button';\nimport { DataTableFilter, type FiltersConfig, type TableFilter } from '../components/data-table-filter';\nimport { DialogMenu, type DialogMenuAction } from '../components/dialog-menu';\nimport { Loader } from '../components/loader';\nimport { EasyMenu, MenuItem } from '../components/menu';\nimport { SearchField } from '../components/searchfield';\nimport { TableBody, TableCell, Table as TableComponent, TableHead, TableHeader, TableRow } from '../components/table';\nimport { CountryName } from '../utilities/countries';\nimport { formatDate } from '../utilities/date';\nimport { formatDays, formatFilesize, formatNumber } from '../utilities/numbers';\nimport { type ApiPathParameters, type ApiResponseBody, useResourceFormatter } from '../utilities/resources';\nimport { classNames } from '../utilities/theme';\nimport { Checkbox } from './checkbox';\nimport { type TableAction, TableActions } from './data-table-actions';\nimport {\n IcColumns,\n IcFirst,\n IcGrip,\n IcInfo,\n IcLast,\n IcLeft,\n IcMoreVertical,\n IcRefresh,\n IcRight,\n IcSortAsc,\n IcSortDesc,\n IcSortNone,\n} from './icons';\n\nimport type { Cell, ColumnHelper } from '@tanstack/react-table';\nimport type { ClientPathsWithMethod } from 'openapi-fetch';\nimport { type CtxClientType, useCtxClient } from '../utilities/ctx-client';\nexport type DisplayType = 'string' | 'boolean' | 'date' | 'number' | 'enum' | 'badge' | 'country' | 'fileSize' | 'days';\n\ndeclare module '@tanstack/react-table' {\n interface ColumnMeta<TData extends RowData, TValue> {\n displayType: DisplayType;\n }\n}\n\nfunction generateSortParam(sort: { id: string; desc: boolean } | undefined): string {\n if (sort) {\n if (sort.desc) {\n return `-${sort.id}`;\n } else {\n return `+${sort.id}`;\n }\n } else {\n return '-createdAt';\n }\n}\n\nconst cH = createColumnHelper<any>();\nconst TABLE_CHECK_BOX_COLUMN = [\n cH.accessor('checkbox', {\n header: ({ table }) => (\n <Checkbox\n isIndeterminate={table.getIsSomeRowsSelected() && !table.getIsAllPageRowsSelected()}\n isSelected={table.getIsAllPageRowsSelected() || table.getIsSomePageRowsSelected()}\n onChange={() => table.toggleAllPageRowsSelected()}\n aria-label=\"Select all\"\n />\n ),\n\n cell: ({ row }) => (\n <Checkbox isSelected={row.getIsSelected()} onChange={() => row.toggleSelected()} aria-label=\"Select row\" />\n ),\n enableSorting: false,\n enableHiding: false,\n }),\n];\n\nconst ACTIONS_COLUMN_ID = 'TableActions';\nconst getActionColumn = (rowActions: DialogMenuAction<any>[]) => {\n if (rowActions.length === 0) return [];\n\n return [\n cH.accessor(ACTIONS_COLUMN_ID, {\n header: 'Actions',\n id: ACTIONS_COLUMN_ID,\n enableHiding: false,\n cell: ({ row }) => <DialogMenu label={<IcMoreVertical />} data={row.original} items={rowActions} />,\n enableSorting: false,\n }),\n ];\n};\n\ntype DataTableFactory<T extends object, TOperation extends keyof operations> = {\n path: NoInfer<ClientPathsWithMethod<CtxClientType, 'get'>>;\n pathParameters?: NoInfer<ApiPathParameters<TOperation>>;\n columns: ColumnDef<T, any>[];\n tableActions: TableAction<T>[];\n columnsToHideByDefault?: Partial<Record<keyof T, boolean>>; // Columns that are hidden by default\n allowSelection?: boolean;\n filterConfig: FiltersConfig<TOperation>;\n initialFilters: TableFilter[];\n rowActions?: DialogMenuAction<T>[];\n};\n\ntype DataTableState = {\n sorting: SortingState;\n pagination: PaginationState;\n};\n\nexport function getColumnHelper<O extends keyof operations>(): ColumnHelper<ApiResponseBody<O>> {\n return createColumnHelper<ApiResponseBody<O>>();\n}\n/**\n * Hook for handling all data-table state. Used in DataTableContext\n */\nexport function useDataTableState<T extends object, TOperation extends keyof operations>({\n path,\n pathParameters,\n columns,\n filterConfig,\n columnsToHideByDefault = {},\n allowSelection = false,\n initialFilters = [],\n tableActions,\n rowActions,\n}: DataTableFactory<T, TOperation>) {\n const [tableState, _setTableState] = useState<DataTableState>({\n /** Reflect in URL in host application */\n pagination: { pageIndex: 0, pageSize: 20 }, // Pagination state\n sorting: [], // Sorting state\n });\n\n const { sorting, pagination } = tableState;\n\n const [searchQuery, setSearchQuery] = useState('');\n\n const [rowSelection, setRowSelection] = useState<RowSelectionState>({});\n\n /** Reflect in URL in host application */\n const [filters, setFilters] = useState(initialFilters);\n const mergedFilters = useMemo(() => {\n // TODO, generic transform fn\n return filters\n .map(tf => {\n if (Array.isArray(tf.value)) {\n return {\n [tf.property]: {\n [tf.operator]: tf.value.join(','),\n },\n };\n }\n return {\n [tf.property]: {\n [tf.operator]: tf.value,\n },\n };\n })\n .reduce((acc, current) => {\n return merge(acc, current);\n }, {});\n }, [filters]);\n\n const queryParameters = {\n ...filters,\n page: pagination.pageIndex + 1,\n limit: pagination.pageSize,\n sort: generateSortParam(sorting[0]),\n search: searchQuery,\n };\n\n const client = useCtxClient();\n // TODO, this seems incorrect, verify\n const queryKey = ['get', path];\n\n const [columnOrder, setColumnOrder] = useLocalStorage<ColumnOrderState>(\n `${queryKey.join('')}_ctx_column_order_preference`,\n []\n );\n const [columnVisibility, setColumnVisibility] = useLocalStorage<VisibilityState>(\n `${queryKey.join('')}_ctx_column_visibility_preference`,\n {\n id: false,\n ...columnsToHideByDefault,\n }\n );\n\n // Update table state with new values\n const updateTableState = (updates: Partial<DataTableState>) => {\n _setTableState(prev => ({ ...prev, ...updates }));\n };\n\n const query = useQuery({\n queryKey,\n queryFn: async () => {\n // Hoping the above type catches the correct path parameter.\n const res = await client.GET(path, { params: { query: queryParameters, path: pathParameters as any } });\n return {\n data: (res.data ?? []) as T[],\n total: Number.parseInt(res.response.headers.get('Pagination-Count') || '0'),\n };\n },\n });\n /**\n * ID,createdAt and updatedAt will be added by default for all tables\n * If selection is allowed, checkbox will be added\n * If the dto has metadata, dynamics columns for all the metadata key-value will be added(particular for a view)\n * If there are actions for the table, they will be placed fixed at the right side of table.\n */\n const cols: ColumnDef<any, any>[] = [\n ...(allowSelection ? TABLE_CHECK_BOX_COLUMN : []),\n ...columns,\n ...getActionColumn(rowActions ?? []),\n ];\n\n // Type-guard for updater\n function isUpdaterFunction<T>(updater: Updater<T>): updater is (old: T) => T {\n return typeof updater === 'function';\n }\n // Utility function to resolve updater\n function resolveUpdater<T>(updater: Updater<T>, currentValue: T) {\n if (isUpdaterFunction(updater)) {\n return updater(currentValue);\n }\n return updater;\n }\n\n // Use react-table's hook to create the table instance\n const tanTable = useReactTable({\n data: query.data?.data ?? [],\n columns: cols,\n getCoreRowModel: getCoreRowModel(),\n rowCount: query.data?.total ?? 0,\n manualPagination: true, // Handle pagination manually since pagination is done server side for data tables\n onPaginationChange: updater => {\n updateTableState({ pagination: resolveUpdater(updater, pagination) });\n },\n manualSorting: true, // Handle sorting manually since sorting is done server side for data tables\n onSortingChange: updater => {\n setRowSelection({});\n updateTableState({ sorting: [...resolveUpdater(updater, sorting)] }); // Reset selection when sorting.\n },\n manualFiltering: true, // Handle filtering manually since filtering is done server side for data tables\n onColumnVisibilityChange: updater => {\n setColumnVisibility(resolveUpdater(updater, columnVisibility));\n },\n onRowSelectionChange: updater => {\n setRowSelection(resolveUpdater(updater, rowSelection));\n },\n onColumnOrderChange: updater => {\n setColumnOrder(resolveUpdater(updater, columnOrder));\n },\n state: {\n sorting: sorting,\n columnVisibility: columnVisibility,\n pagination: pagination,\n rowSelection: rowSelection,\n columnOrder: columnOrder,\n },\n meta: {\n refetch: query.refetch,\n },\n });\n\n // By default, ColumnDef does not give guarantees of column.id existing. Once useReactTable is called, all columns are assigned IDs.\n // This populates the columnIds in the columnOrder state\n useEffect(() => {\n setColumnOrder([...tanTable.getAllLeafColumns().map(c => c.id)]);\n }, []);\n\n return {\n tableState,\n updateTableState,\n query,\n setSearchQuery,\n searchQuery,\n tanTable,\n mergedFilters,\n filters,\n setFilters,\n filterConfig,\n tableActions,\n } as const;\n}\n\nexport const DataTableContext = createContext<ReturnType<typeof useDataTableState> | null>(null);\n// TODO, don't export this\nexport function useDataTable() {\n const ctx = useContext(DataTableContext);\n if (!ctx) {\n throw Error('DataTable should be used within DataTableProvider.');\n }\n return ctx;\n}\n\nexport function DataTableProvider<T extends object, TOperation extends keyof operations>({\n children,\n ...props\n}: { children: React.ReactNode } & ReturnType<typeof useDataTableState<T, TOperation>>) {\n // @ts-expect-error, propogating the generic type further will be more complex. Since this is a tightly coupled type, it should be okay but reviewed whenever useDataTableState changes.\n return <DataTableContext.Provider value={props}>{children}</DataTableContext.Provider>;\n}\n\nexport type DataTableProps = React.ComponentProps<'section'>;\nexport function DataTable({ className, ...props }: DataTableProps) {\n const { query, tanTable } = useDataTable();\n\n return (\n <>\n {/* Table Actions Section */}\n <section {...props} className={classNames('flex flex-col bg-elevation-1', className)}>\n <Actions />\n {/* The div here is necessary because TableContent is internally a <table> tag and does not respect width, height CSS */}\n <div className=\"w-full overflow-auto border-x h-table relative\" tabIndex={0}>\n {/* Table overlay with loader */}\n {query.isLoading && (\n <TableOverlay className=\"cursor-wait\">\n <Loader />\n </TableOverlay>\n )}\n {/* Table overlay for empty table */}\n {!query.isLoading && tanTable.getRowModel().rows.length === 0 && (\n // Empty table\n <TableOverlay className=\"cursor-not-allowed\">\n {!query.isFetching &&\n (query.isError ? (\n <span className=\"flex gap-3 justify-center items-center\">\n {/* TODO (mudasir-pandith) Check for 403 explicitly!! */}\n {/* <span>{query.error}</span> */}\n <IcInfo />\n <span>{query.error.message}</span>\n </span>\n ) : query.data?.data?.length === 0 ? (\n <>No results found.</>\n ) : (\n <>Unknown error. Please contact customer support.</>\n ))}\n </TableOverlay>\n )}\n {!query.isLoading && tanTable.getRowModel().rows.length !== 0 && (\n <TableContent className=\"w-full\" />\n )}\n </div>\n\n {/* Table Footer Section with Pagination and Column Picker */}\n <div className=\"flex w-full justify-between border gap-icon p-icon overflow-x-auto\">\n <div className=\"flex gap-icon\">\n <ColumnPicker />\n <PageSize />\n </div>\n <Paginator />\n </div>\n </section>\n </>\n );\n}\n/** Table overlay to be shown for loaders or other messages */\nfunction TableOverlay({ children, className }: { children: React.ReactNode; className?: string }) {\n return (\n <>\n <span\n className={classNames(\n className,\n 'absolute top-0 bg-elevation-1 text-foreground z-20 size-full body-sm flex items-center justify-center'\n )}\n >\n {children}\n </span>\n {/* Keep something in document flow with the correct height */}\n <span className=\"relative h-full w-0 block\" />\n </>\n );\n}\n\n// TODO, ?include query param on Licenses, Activations and other future resources that need this\nfunction ColumnPicker() {\n const { tanTable } = useDataTable();\n const [activeId, setActiveId] = useState<string | null>(null);\n\n const resourceFormatter = useResourceFormatter();\n\n const sensors = useSensors(\n useSensor(PointerSensor),\n useSensor(KeyboardSensor, {\n coordinateGetter: sortableKeyboardCoordinates,\n })\n );\n return (\n <DndContext\n sensors={sensors}\n collisionDetection={closestCenter}\n onDragStart={event => {\n const { active } = event;\n setActiveId(active.id.toString());\n }}\n onDragEnd={event => {\n const { active, over } = event;\n\n if (over && active.id !== over.id) {\n const columnOrder = tanTable.getState().columnOrder;\n const oldIndex = columnOrder.indexOf(active.id.toString());\n const newIndex = columnOrder.indexOf(over.id.toString());\n tanTable.setColumnOrder([...arrayMove(columnOrder, oldIndex, newIndex)]);\n }\n\n setActiveId(null);\n }}\n >\n <SortableContext items={tanTable.getState().columnOrder} strategy={verticalListSortingStrategy}>\n <EasyMenu\n label={\n <>\n <IcColumns className=\"inline align-bottom me-1\" />\n Columns\n </>\n }\n selectionMode=\"multiple\"\n items={tanTable.getAllFlatColumns()}\n // Using selectedKeys = 'all' does not mark MenuItems with isDisabled=true as selected. This is not the intended behaviour in this use-case.\n selectedKeys={tanTable.getVisibleFlatColumns().map(c => c.id)}\n >\n <MenuItem onAction={() => tanTable.toggleAllColumnsVisible()} className={'italic'}>\n (select all)\n </MenuItem>\n {tanTable.getState().columnOrder.map(colId => {\n const col = tanTable.getAllFlatColumns().find(c => c.id === colId);\n // Don't show checkbox and actions columns in picker\n if (!col || col.id === 'checkbox' || col.id === ACTIONS_COLUMN_ID) return null;\n return <SortableItem key={col.id} column={col} />;\n })}\n </EasyMenu>\n <DragOverlay>\n {activeId ? (\n <div className=\"opacity-70 border-2 border-primary\">{resourceFormatter(activeId)}</div>\n ) : null}\n </DragOverlay>\n </SortableContext>\n </DndContext>\n );\n\n function SortableItem({ column }: { column: Column<any, unknown> }) {\n const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: column.id });\n const style = {\n transform: CSS.Transform.toString(transform),\n transition,\n zIndex: '999',\n };\n return (\n <MenuItem\n ref={setNodeRef}\n style={style}\n {...attributes}\n id={column.id}\n onAction={() => column.toggleVisibility()}\n isDisabled={!column.getCanHide()}\n className=\"flex items-center\"\n >\n <IcGrip {...listeners} className=\"size-icon cursor-grab\" />\n {getColumnHeaderText(column)}\n {column.getIsSorted() && <SortIcon className=\"size-icon\" direction={column.getIsSorted()} />}\n </MenuItem>\n );\n }\n}\n\nfunction Paginator() {\n const { tanTable } = useDataTable();\n const rowCount = tanTable.getRowCount();\n return (\n <div className=\"flex items-center gap-2\">\n <span className=\"whitespace-nowrap body-sm text-muted\">\n {`${tanTable.getState().pagination.pageIndex * tanTable.getState().pagination.pageSize + 1} - ${Math.min(\n (tanTable.getState().pagination.pageIndex + 1) * tanTable.getState().pagination.pageSize,\n rowCount\n )} of ${rowCount?.toLocaleString()}`}\n </span>\n\n <Button\n aria-label=\"First page\"\n onPress={() => tanTable.firstPage()}\n isDisabled={!tanTable.getCanPreviousPage()}\n variant=\"neutral\"\n size={'icon'}\n >\n <IcFirst />\n </Button>\n <Button\n aria-label=\"Previous page\"\n onPress={() => tanTable.previousPage()}\n isDisabled={!tanTable.getCanPreviousPage()}\n variant=\"neutral\"\n size={'icon'}\n >\n <IcLeft />\n </Button>\n <Button\n aria-label=\"Next page\"\n onPress={() => tanTable.nextPage()}\n isDisabled={!tanTable.getCanNextPage()}\n variant=\"neutral\"\n size={'icon'}\n >\n <IcRight />\n </Button>\n <Button\n aria-label=\"Last page\"\n onClick={() => tanTable.lastPage()}\n isDisabled={!tanTable.getCanNextPage()}\n variant=\"neutral\"\n size={'icon'}\n >\n <IcLast />\n </Button>\n </div>\n );\n}\n\nfunction PageSize() {\n const { tanTable } = useDataTable();\n const PAGE_SIZES = [10, 20, 30, 40, 50];\n\n return (\n <EasyMenu\n label={tanTable.getState().pagination.pageSize.toString()}\n selectionMode=\"single\"\n selectedKeys={[tanTable.getState().pagination.pageSize.toString()]}\n items={PAGE_SIZES.map(s => ({ id: s.toString(), value: s }))}\n >\n {items => <MenuItem onAction={() => tanTable.setPageSize(items.value)}>{items.value}</MenuItem>}\n </EasyMenu>\n );\n}\n\nfunction Actions() {\n const { query, tanTable, searchQuery, setSearchQuery, tableActions } = useDataTable();\n const hasSelectedRows = tanTable.getSelectedRowModel().rows.length > 0;\n const selectedRows = tanTable.getSelectedRowModel().rows.map(r => r.original);\n\n const filteredActions = tableActions.filter(ta => ta.bulk === hasSelectedRows);\n\n return (\n <section className=\"flex bg-elevation-1 justify-between my-0 p-icon border gap-icon overflow-auto\">\n <div className=\"flex gap-icon\">\n <Button\n aria-label=\"Refresh\"\n isPending={query.isFetching}\n onClick={() => query.refetch()}\n variant={'neutral'}\n size={'icon'}\n >\n <IcRefresh />\n </Button>\n\n <TableActions items={filteredActions} rowsSelected={selectedRows} isFetching={query.isFetching} />\n </div>\n <div className=\"flex gap-icon\">\n <DataTableFilter />\n {<SearchField value={searchQuery} onChange={setSearchQuery} />}\n </div>\n </section>\n );\n}\n\nfunction SortIcon({\n direction,\n ...props\n}: { direction: 'asc' | 'desc' | false } & Omit<React.ComponentProps<'svg'>, 'direction'>) {\n if (direction === 'asc') return <IcSortAsc className=\"size-3.5\" {...props} />;\n else if (direction === 'desc') return <IcSortDesc className=\"size-3.5\" {...props} />;\n else return <IcSortNone className=\"size-3.5\" {...props} />;\n}\n\nfunction getColumnHeaderText(column: Column<any, unknown>): string {\n const resourceFormatter = useResourceFormatter();\n const headerDef = column.columnDef.header;\n return typeof headerDef === 'string' ? headerDef : resourceFormatter(column.id);\n}\n\n/**\n * Renders a cell value based on the displayType metadata\n * @param cell - The cell to render\n * @returns The formatted value as a React node\n */\nfunction renderCellByDisplayType(cell: Cell<any, any>): React.ReactNode {\n const displayType = cell.column.columnDef.meta?.displayType;\n const value = cell.getValue();\n\n if (value === null || value === undefined) {\n return null;\n }\n\n switch (displayType) {\n case 'date':\n return formatDate(value);\n\n case 'number':\n return formatNumber(value);\n case 'boolean':\n case 'badge':\n return <Badge className=\"uppercase w-full\">{String(value)}</Badge>;\n case 'country':\n return <CountryName value={value} />;\n case 'enum':\n return <span className=\"uppercase w-full\">{String(value)}</span>;\n case 'fileSize':\n return formatFilesize(value);\n case 'days':\n return formatDays(value);\n default:\n return String(value);\n }\n}\n\nfunction HeaderText({ header }: { header: Header<any, unknown> }) {\n const headerDef = header.column.columnDef.header;\n\n if (typeof headerDef === 'string' || !headerDef) {\n return getColumnHeaderText(header.column);\n }\n\n if (typeof headerDef === 'function') {\n const result = headerDef(header.getContext());\n if (typeof result === 'string') {\n return getColumnHeaderText(header.column);\n }\n return flexRender(headerDef, header.getContext());\n }\n\n return flexRender(headerDef, header.getContext());\n}\n\n// TODO, automate checking valid HTML\nfunction TableContent({ className }: React.ComponentProps<typeof TableComponent>) {\n const { tanTable } = useDataTable();\n const tableCellStyle = (isSticky: boolean, className?: string, zIndex: string = 'z-50') =>\n classNames(\n 'px-icon py-2 text-left body-sm font-medium whitespace-nowrap',\n isSticky && `bg-elevation-1 sticky right-0 ${zIndex} text-center justify-center`,\n className\n );\n return (\n <TableComponent className={classNames('table-auto', className)}>\n <TableHeader className=\"sticky top-0 z-10\">\n {tanTable.getHeaderGroups().map(headerGroup => (\n <TableRow key={headerGroup.id}>\n {headerGroup.headers.map(header => (\n <TableHead\n scope=\"col\"\n key={header.id}\n colSpan={header.colSpan}\n className={tableCellStyle(header.id === ACTIONS_COLUMN_ID, 'bg-elevation-1')}\n >\n {!header.column.getCanSort() && !header.isPlaceholder && (\n <div\n className={classNames(\n 'w-full py-1 inline-flex items-center gap-1 body-sm',\n header.id === ACTIONS_COLUMN_ID ? 'justify-center' : 'justify-start'\n )}\n >\n <HeaderText header={header} />\n </div>\n )}\n {header.column.getCanSort() && (\n <Button\n variant=\"ghost\"\n className={classNames(\n 'w-full p-1',\n header.id === ACTIONS_COLUMN_ID ? 'justify-center' : 'justify-start'\n )}\n onPress={header.column.getToggleSortingHandler()}\n >\n <span>\n <HeaderText header={header} />\n </span>\n <SortIcon direction={header.column.getIsSorted()} />\n </Button>\n )}\n </TableHead>\n ))}\n </TableRow>\n ))}\n </TableHeader>\n <TableBody>\n {tanTable.getRowModel().rows.map(row => (\n <TableRow\n className={classNames(\n 'transition-colors data-[selected=true]:bg-primary/10 hover:bg-muted-foreground/20'\n )}\n key={row.id}\n data-selected={row.getIsSelected()}\n >\n {row.getVisibleCells().map(cell => {\n const isActionsColumn = cell.column.id === ACTIONS_COLUMN_ID;\n const cellContent = cell.column.columnDef.meta?.displayType\n ? renderCellByDisplayType(cell)\n : flexRender(cell.column.columnDef.cell, cell.getContext());\n\n return (\n <TableCell\n key={cell.id}\n className={classNames(\n tableCellStyle(isActionsColumn, undefined, 'z-1'),\n isActionsColumn && 'flex justify-center items-center'\n )}\n >\n {cellContent}\n </TableCell>\n );\n })}\n </TableRow>\n ))}\n </TableBody>\n </TableComponent>\n );\n}\n","'use client';\nimport type { operations } from '@cryptlex/web-api-types/develop';\nimport { useRef } from 'react';\nimport { Button } from '../components/button';\nimport { useDataTable } from '../components/data-table';\nimport { TfDatePicker } from '../components/date-picker';\nimport { EasyMenu, MenuItem } from '../components/menu';\nimport type { MultiSelectProps } from '../components/multi-select';\nimport { Popover, PopoverTrigger } from '../components/popover';\nimport { useAppForm } from '../utilities/form-hook';\nimport { useResourceFormatter, type ApiFilters } from '../utilities/resources';\nimport { classNames } from '../utilities/theme';\nimport { IcAccount, IcCheck, IcDate, IcFile, IcFilter, IcLicense, IcMinus, IcRemove, type CtxIcon } from './icons';\nimport { TfMultipleIdSearchInput } from './id-search';\n\nexport const FILTER_COMPARISON_OPERATORS = [\n 'eq',\n 'ne',\n 'cn',\n 'nc',\n 'sw',\n 'ew',\n 'in',\n 'nin',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n] as const;\nexport type FilterComparisonOperator = (typeof FILTER_COMPARISON_OPERATORS)[number];\n\nexport const COMPARISON_OPERATOR_LABELS: Record<FilterComparisonOperator, string> = {\n eq: 'equal to',\n ne: 'not equal to',\n cn: 'contains',\n nc: 'does not contain',\n sw: 'starts with',\n ew: 'ends with',\n in: 'includes',\n nin: 'does not include',\n gt: 'greater than',\n gte: 'greater than or equal to',\n lt: 'less than',\n lte: 'less than or equal to',\n};\n\ntype BaseLocalFilter<T extends FilterType, V> = {\n id: string;\n type: T;\n property: string;\n operator: FilterComparisonOperator;\n value: V | undefined;\n displayValue?: string;\n};\ntype EnumLocalFilter = BaseLocalFilter<'enum', Set<string | number>>;\ntype IdLocalFilter = BaseLocalFilter<'id', string>;\ntype BoolLocalFilter = BaseLocalFilter<'bool', boolean>;\ntype StringLocalFilter = BaseLocalFilter<'string', string>;\ntype NumberLocalFilter = BaseLocalFilter<'number', number>;\n// DatePicker accepts a string,and converts it to a ZonedDateTime\ntype DateLocalFilter = BaseLocalFilter<'date', string>;\ntype IdSearchLocalFilter = BaseLocalFilter<'id-search', string[]>;\n// TODO, entitlementSets.productIds\nfunction createNewFilter(type: FilterType, property: string): TableFilter {\n const id = `${property}-${Date.now()}`;\n const operator = FilterOperations[type][0];\n\n switch (type) {\n case 'bool':\n return { id, type, property, operator, value: true };\n case 'string':\n return { id, type, property, operator, value: '' };\n case 'date':\n return { id, type, property, operator, value: new Date().toISOString() };\n case 'id':\n return { id, type, property, operator, value: '' };\n case 'id-search':\n return { id, type, property, operator, value: [] };\n case 'enum':\n return { id, type, property, operator, value: new Set<string | number>() };\n case 'number':\n return { id, type, property, operator, value: 0 };\n }\n}\n\nexport type TableFilter =\n | EnumLocalFilter\n | IdLocalFilter\n | BoolLocalFilter\n | StringLocalFilter\n | DateLocalFilter\n | IdSearchLocalFilter\n | NumberLocalFilter;\n\nexport type FilterConfig =\n | { type: 'enum'; options: MultiSelectProps['items'] }\n | ({ type: 'id-search' } & Pick<React.ComponentProps<typeof TfMultipleIdSearchInput>, 'accessor' | 'path'>)\n | { type: 'id' }\n | { type: 'bool' }\n | { type: 'string' }\n | { type: 'date' }\n | { type: 'number' };\n\nexport type FilterType = FilterConfig['type'];\n\nconst FilterOperations: Record<FilterType, FilterComparisonOperator[]> = {\n bool: ['eq'],\n enum: ['in', 'nin'],\n id: ['in', 'nin'],\n 'id-search': ['in', 'nin'],\n string: ['eq', 'ne', 'cn', 'nc', 'sw', 'ew', 'in', 'nin'],\n date: ['lt', 'gt'],\n number: ['eq', 'ne', 'gt', 'gte', 'lt', 'lte'],\n};\n\n// TS workaround to get rid of filterConfig: Required<Record<never, FilterConfig>>\nexport type FiltersConfig<TOperation extends keyof operations> = [keyof ApiFilters<TOperation>] extends [never]\n ? Record<string, FilterConfig>\n : Required<Record<keyof ApiFilters<TOperation>, FilterConfig>>;\n\nexport function DataTableFilter({ className, ...props }: React.ComponentProps<'section'>) {\n const { filters, query, setFilters, filterConfig } = useDataTable();\n\n const addFilterButtonRef = useRef<HTMLButtonElement>(null);\n\n const resourceFormatter = useResourceFormatter();\n\n const DEFAULT_VALUES: { filters: TableFilter[] } = {\n filters,\n };\n const form = useAppForm({\n defaultValues: DEFAULT_VALUES,\n onSubmit: ({ value }) => {\n setFilters(value.filters);\n },\n });\n\n // More reason to hate TS https://github.com/Microsoft/TypeScript/issues/12870\n const filterKeys = Object.keys(filterConfig).sort();\n\n return (\n <section {...props} className={classNames('flex gap-icon items-center', className)}>\n <PopoverTrigger\n onOpenChange={o => {\n // Set filters when the popover closes\n if (!o) {\n form.handleSubmit();\n } else {\n addFilterButtonRef.current?.focus();\n }\n }}\n >\n <div className=\"relative\">\n {filters.length > 0 && (\n <div className=\"size-2 rounded-full absolute bg-primary/90 z-20 top-0 right-0 translate-x-0.5 -translate-y-0.5\"></div>\n )}\n <Button\n aria-label=\"Filter\"\n isDisabled={query.isPending || filterKeys.length === 0}\n type=\"button\"\n size={'icon'}\n variant={'neutral'}\n >\n <IcFilter />\n </Button>\n </div>\n {/* TODO, icon maps with dynamic imports? */}\n {/* TODO open popover with form for property specific filter */}\n {/* TODO, icons here??? */}\n <Popover className=\"w-full p-icon\">\n <form\n onSubmit={e => {\n e.preventDefault();\n }}\n className=\"flex flex-col gap-icon max-h-table overflow-auto \"\n >\n <form.Field mode=\"array\" name={'filters'}>\n {field => {\n return (\n <>\n {field.state.value.map((lf, i) => {\n return (\n <div key={lf.id} className=\"flex gap-icon items-center justify-normal\">\n <span className=\"body-sm\">{resourceFormatter(lf.property)}</span>\n <form.AppField key={lf.id} name={`filters[${i}].operator`}>\n {sf => (\n <sf.TfSingleSelect\n items={FilterOperations[lf.type].map(op => ({\n id: op,\n label: <>{COMPARISON_OPERATOR_LABELS[op]}</>,\n }))}\n />\n )}\n </form.AppField>\n\n {lf.type === 'bool' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => <sf.TfCheckbox autoFocus />}\n </form.AppField>\n )}\n {lf.type === 'date' && (\n <form.AppField name={`filters[${i}].value`}>\n {_ => <TfDatePicker autoFocus />}\n </form.AppField>\n )}\n {lf.type === 'id' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => <sf.TfTextField autoFocus />}\n </form.AppField>\n )}\n {lf.type === 'string' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => <sf.TfTextField autoFocus />}\n </form.AppField>\n )}\n {lf.type === 'number' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => <sf.TfNumberField autoFocus />}\n </form.AppField>\n )}\n\n {lf.type === 'enum' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => {\n const config = filterConfig[lf.property];\n if (config.type !== 'enum') return null;\n return <sf.TfMultiSelect items={config.options} />;\n }}\n </form.AppField>\n )}\n\n {lf.type === 'id-search' && (\n <form.AppField name={`filters[${i}].value`}>\n {_ => {\n const config = filterConfig[lf.property];\n if (config.type !== 'id-search') return null;\n return (\n <TfMultipleIdSearchInput\n path={config.path}\n accessor={config.accessor}\n />\n );\n }}\n </form.AppField>\n )}\n\n <Button\n type=\"button\"\n variant=\"neutral\"\n size=\"icon\"\n onPress={() => field.removeValue(i)}\n >\n <IcRemove />\n </Button>\n </div>\n );\n })}\n <div className=\"flex w-full items-center justify-end gap-2 not-first:mt-icon\">\n <EasyMenu label=\"Add filter\" autoFocus>\n {filterKeys.sort().map(k => {\n const type = filterConfig[k].type;\n const Icon = FilterIcon[type];\n return (\n <MenuItem\n key={k}\n onAction={() => {\n const newFilter = createNewFilter(type, k);\n field.pushValue(newFilter);\n }}\n >\n {resourceFormatter(k)}\n <Icon />\n </MenuItem>\n );\n })}\n </EasyMenu>\n {field.state.value.length > 0 ? (\n <Button\n type=\"button\"\n variant=\"neutral\"\n onPress={() => {\n field.setValue([]);\n }}\n >\n <IcRemove />\n Reset\n </Button>\n ) : null}\n </div>\n </>\n );\n }}\n </form.Field>\n </form>\n </Popover>\n </PopoverTrigger>\n </section>\n );\n}\n\nconst FilterIcon: Record<FilterConfig['type'], CtxIcon> = {\n 'id-search': IcFile,\n bool: IcCheck,\n date: IcDate,\n enum: IcLicense,\n id: IcAccount,\n number: IcMinus,\n string: IcCheck,\n};\n"],"names":["generateSortParam","sort","cH","createColumnHelper","TABLE_CHECK_BOX_COLUMN","table","jsx","Checkbox","row","ACTIONS_COLUMN_ID","getActionColumn","rowActions","DialogMenu","IcMoreVertical","getColumnHelper","useDataTableState","path","pathParameters","columns","filterConfig","columnsToHideByDefault","allowSelection","initialFilters","tableActions","tableState","_setTableState","useState","sorting","pagination","searchQuery","setSearchQuery","rowSelection","setRowSelection","filters","setFilters","mergedFilters","useMemo","tf","acc","current","merge","queryParameters","client","useCtxClient","queryKey","columnOrder","setColumnOrder","useLocalStorage","columnVisibility","setColumnVisibility","updateTableState","updates","prev","query","useQuery","res","cols","isUpdaterFunction","updater","resolveUpdater","currentValue","tanTable","useReactTable","getCoreRowModel","useEffect","c","DataTableContext","createContext","useDataTable","ctx","useContext","DataTableProvider","children","props","DataTable","className","Fragment","classNames","Actions","jsxs","TableOverlay","Loader","IcInfo","TableContent","ColumnPicker","PageSize","Paginator","activeId","setActiveId","resourceFormatter","useResourceFormatter","sensors","useSensors","useSensor","PointerSensor","KeyboardSensor","sortableKeyboardCoordinates","DndContext","closestCenter","event","active","over","oldIndex","newIndex","arrayMove","SortableContext","verticalListSortingStrategy","EasyMenu","IcColumns","MenuItem","colId","col","SortableItem","DragOverlay","column","attributes","listeners","setNodeRef","transform","transition","useSortable","style","CSS","IcGrip","getColumnHeaderText","SortIcon","rowCount","Button","IcFirst","IcLeft","IcRight","IcLast","PAGE_SIZES","s","items","hasSelectedRows","selectedRows","r","filteredActions","ta","IcRefresh","TableActions","DataTableFilter","SearchField","direction","IcSortAsc","IcSortDesc","IcSortNone","headerDef","renderCellByDisplayType","cell","displayType","value","formatDate","formatNumber","Badge","CountryName","formatFilesize","formatDays","HeaderText","header","flexRender","tableCellStyle","isSticky","zIndex","TableComponent","TableHeader","headerGroup","TableRow","TableHead","TableBody","isActionsColumn","cellContent","TableCell","FILTER_COMPARISON_OPERATORS","COMPARISON_OPERATOR_LABELS","createNewFilter","type","property","id","operator","FilterOperations","addFilterButtonRef","useRef","form","useAppForm","filterKeys","PopoverTrigger","o","IcFilter","Popover","e","field","lf","i","sf","op","_","TfDatePicker","config","TfMultipleIdSearchInput","IcRemove","k","Icon","FilterIcon","newFilter","IcFile","IcCheck","IcDate","IcLicense","IcAccount","IcMinus"],"mappings":"wqFAkFA,SAASA,GAAkBC,EAAyD,CAChF,OAAIA,EACIA,EAAK,KACE,IAAIA,EAAK,EAAE,GAEX,IAAIA,EAAK,EAAE,GAGf,YAEf,CAEA,MAAMC,EAAKC,EAAA,EACLC,GAAyB,CAC3BF,EAAG,SAAS,WAAY,CACpB,OAAQ,CAAC,CAAE,MAAAG,CAAA,IACPC,EAACC,EAAA,CACG,gBAAiBF,EAAM,sBAAA,GAA2B,CAACA,EAAM,yBAAA,EACzD,WAAYA,EAAM,4BAA8BA,EAAM,0BAAA,EACtD,SAAU,IAAMA,EAAM,0BAAA,EACtB,aAAW,YAAA,CAAA,EAInB,KAAM,CAAC,CAAE,IAAAG,CAAA,MACJD,EAAA,CAAS,WAAYC,EAAI,cAAA,EAAiB,SAAU,IAAMA,EAAI,eAAA,EAAkB,aAAW,aAAa,EAE7G,cAAe,GACf,aAAc,EAAA,CACjB,CACL,EAEMC,EAAoB,eACpBC,GAAmBC,GACjBA,EAAW,SAAW,EAAU,CAAA,EAE7B,CACHT,EAAG,SAASO,EAAmB,CAC3B,OAAQ,UACR,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OAAQC,GACR,OAAQJ,CACZ"}
|
|
@@ -10,6 +10,7 @@ export type ApiResponseBody<T extends keyof operations> = operations[T] extends
|
|
|
10
10
|
};
|
|
11
11
|
} ? R extends Array<infer U> ? U : R : never;
|
|
12
12
|
export type ApiQuery<T extends keyof operations> = NonNullable<operations[T]['parameters']['query']>;
|
|
13
|
+
export type ApiPathParameters<T extends keyof operations> = operations[T]['parameters']['path'];
|
|
13
14
|
export type ApiFilter<T extends keyof operations> = Omit<ApiQuery<T>, 'page' | 'limit' | 'sort' | 'search'>;
|
|
14
15
|
export type ApiFilters<T extends keyof operations> = NonNullable<ApiFilter<T>>;
|
|
15
16
|
export type CtxPortals = 'customer-portal' | 'system-portal' | 'reseller-portal' | 'admin-portal';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resources.js","sources":["../../lib/utilities/resources.tsx"],"sourcesContent":["import type { components, operations } from '@cryptlex/web-api-types/develop';\nimport { createContext, use } from 'react';\nimport { toTitleCase } from './string';\n\nexport type ApiSchema<T extends keyof components['schemas']> = components['schemas'][T];\nexport type ApiResponseBody<T extends keyof operations> = operations[T] extends {\n responses: { 200: { content: { 'application/json': infer R } } };\n}\n ? R extends Array<infer U>\n ? U\n : R\n : never;\nexport type ApiQuery<T extends keyof operations> = NonNullable<operations[T]['parameters']['query']>;\nexport type ApiFilter<T extends keyof operations> = Omit<ApiQuery<T>, 'page' | 'limit' | 'sort' | 'search'>;\nexport type ApiFilters<T extends keyof operations> = NonNullable<ApiFilter<T>>;\nexport type CtxPortals = 'customer-portal' | 'system-portal' | 'reseller-portal' | 'admin-portal';\n// Display names specific to customer and reseller portal\nconst OTHER_PORTALS_DISPLAY_NAME: Record<string, string> = {\n 'product.displayName': 'Product',\n // TanStack Table converts . -> _ TODO\n product_displayName: 'Product',\n};\n\n// TODO, delegate to openapi.json\n// TODO, this drifts quite a lot from the API, should be updated\n/** Resource Name should ALWAYS be in singular form */\nexport const RESOURCE_NAMES = [\n 'access-token',\n 'account',\n 'activation',\n 'activation-log',\n 'admin-role',\n 'audit-log',\n 'automated-email',\n 'automated-email-event-log',\n 'card',\n 'entitlement-set',\n 'feature-flag',\n 'feature',\n 'invoice',\n 'license',\n 'license-template',\n 'maintenance-policy',\n 'organization',\n 'plan',\n 'product',\n 'product-version',\n 'profile',\n 'release',\n 'release-channel',\n 'release-file',\n 'release-platform',\n 'role',\n 'role-claim',\n 'saml-configuration',\n 'segment',\n 'sending-domain',\n 'tag',\n 'trial',\n 'trial-policy',\n 'user',\n 'user-group',\n 'webhook',\n 'webhook-event-log',\n 'webhook-event',\n 'reseller',\n 'oidc-configuration',\n 'tenant-database-cluster',\n] as const;\nexport type CtxResourceName = (typeof RESOURCE_NAMES)[number];\n\n// TODO, use OpenAPI spec for resource definitions\n\nconst RESOURCE_DISPLAY_NAMES: Record<string, string> = {\n id: 'ID',\n createdAt: 'Creation Date',\n scopes: 'Permissions',\n updatedAt: 'Last Updated',\n expiresAt: 'Expiration Date',\n lastSeenAt: 'Last Seen',\n os: 'OS',\n osVersion: 'OS Version',\n key: 'License Key',\n vmName: 'VM Name',\n container: 'Container',\n allowedIpRange: 'Allowed IP Range',\n allowedIpRanges: 'Allowed IP Ranges',\n allowedIpAddresses: 'Allowed IP Addresses',\n disallowedIpAddresses: 'Disallowed IP Addresses',\n allowVmActivation: 'Allow VM Activation',\n disableGeoLocation: 'Disable Geolocation',\n 'user.id': 'User ID',\n userId: 'User',\n productId: 'Product',\n downloads: 'Total Downloads',\n claims: 'Permissions',\n googleSsoEnabled: 'Google Login Enabled',\n lastAttemptedAt: 'Last Attempt Date',\n url: 'URL',\n 'trialPolicy.name': 'Trial Policy Name',\n 'licensePolicy.name': 'License Template Name',\n licensePolicy: 'License Template',\n eventLog: 'Audit Log',\n cc: 'CC Recepients',\n bcc: 'BCC Recepients',\n ipAddress: 'IP Address',\n resellerId: 'Reseller',\n productVersionId: 'Product Version',\n releaseId: 'Release',\n maintenancePolicyId: 'Maintenance Policy',\n webhookId: 'Webhook',\n automatedEmailId: 'Automated Email',\n 'location.countryName': 'Country',\n 'location.ipAddress': 'IP Address',\n 'location.countryCode': 'Country',\n organizationId: 'Organization',\n 'address.country': 'Country',\n 'address.addressLine1': 'Address Line 1',\n 'address.addressLine2': 'Address Line 2',\n responseStatusCode: 'HTTP Status Code',\n resourceId: 'Resource ID',\n Sso: 'SAML SSO 2.0',\n 'reseller.name': 'Reseller',\n sendingDomain: 'Email Sending Domain',\n};\n\nfunction getResourceDisplayName(resourceName: string, portal: CtxPortals) {\n if (portal !== 'admin-portal' && resourceName in OTHER_PORTALS_DISPLAY_NAME) {\n return OTHER_PORTALS_DISPLAY_NAME[resourceName];\n } else if (resourceName in RESOURCE_DISPLAY_NAMES) {\n return RESOURCE_DISPLAY_NAMES[resourceName];\n } else {\n return toTitleCase(resourceName);\n }\n}\n\nconst ProjectContext = createContext<CtxPortals>('admin-portal');\n\nexport function ProjectProvider({ projectName, children }: { projectName: CtxPortals; children: React.ReactNode }) {\n return <ProjectContext.Provider value={projectName}>{children}</ProjectContext.Provider>;\n}\n\nexport function useProjectName(): CtxPortals {\n const projectName = use(ProjectContext);\n return projectName;\n}\n\nexport function useResourceFormatter(): (resourceName: string) => string {\n const portal = useProjectName();\n return (resourceName: string) => getResourceDisplayName(resourceName, portal);\n}\n\n/**\n * Format multiple license parameters (expired, suspended, revoked) into a single status\n */\nexport function getLicenseStatus(license: any): string {\n const licenseExpired = license.expiresAt && new Date(license.expiresAt) < new Date();\n // Status Column\n switch (true) {\n case license.revoked && license.suspended && licenseExpired:\n return 'Revoked, Suspended, Expired';\n case license.revoked && license.suspended:\n return 'Revoked, Suspended';\n case license.revoked && licenseExpired:\n return 'Revoked, Expired';\n case license.suspended && licenseExpired:\n return 'Suspended, Expired';\n case license.suspended:\n return 'Suspended';\n case license.revoked:\n return 'Revoked';\n case licenseExpired:\n return 'Expired';\n default:\n return 'Active';\n }\n}\ntype OsType = ApiSchema<'ActivationCreateRequestModel'>['os'];\nexport const ALL_OS: Record<OsType, string> = {\n windows: 'Windows',\n macos: 'macOS',\n linux: 'Linux',\n ios: 'iOS',\n android: 'Android',\n};\n"],"names":["OTHER_PORTALS_DISPLAY_NAME","RESOURCE_NAMES","RESOURCE_DISPLAY_NAMES","getResourceDisplayName","resourceName","portal","toTitleCase","ProjectContext","createContext","ProjectProvider","projectName","children","useProjectName","use","useResourceFormatter","getLicenseStatus","license","licenseExpired","ALL_OS"],"mappings":"
|
|
1
|
+
{"version":3,"file":"resources.js","sources":["../../lib/utilities/resources.tsx"],"sourcesContent":["import type { components, operations } from '@cryptlex/web-api-types/develop';\nimport { createContext, use } from 'react';\nimport { toTitleCase } from './string';\n\nexport type ApiSchema<T extends keyof components['schemas']> = components['schemas'][T];\nexport type ApiResponseBody<T extends keyof operations> = operations[T] extends {\n responses: { 200: { content: { 'application/json': infer R } } };\n}\n ? R extends Array<infer U>\n ? U\n : R\n : never;\nexport type ApiQuery<T extends keyof operations> = NonNullable<operations[T]['parameters']['query']>;\nexport type ApiPathParameters<T extends keyof operations> = operations[T]['parameters']['path'];\nexport type ApiFilter<T extends keyof operations> = Omit<ApiQuery<T>, 'page' | 'limit' | 'sort' | 'search'>;\nexport type ApiFilters<T extends keyof operations> = NonNullable<ApiFilter<T>>;\nexport type CtxPortals = 'customer-portal' | 'system-portal' | 'reseller-portal' | 'admin-portal';\n// Display names specific to customer and reseller portal\nconst OTHER_PORTALS_DISPLAY_NAME: Record<string, string> = {\n 'product.displayName': 'Product',\n // TanStack Table converts . -> _ TODO\n product_displayName: 'Product',\n};\n\n// TODO, delegate to openapi.json\n// TODO, this drifts quite a lot from the API, should be updated\n/** Resource Name should ALWAYS be in singular form */\nexport const RESOURCE_NAMES = [\n 'access-token',\n 'account',\n 'activation',\n 'activation-log',\n 'admin-role',\n 'audit-log',\n 'automated-email',\n 'automated-email-event-log',\n 'card',\n 'entitlement-set',\n 'feature-flag',\n 'feature',\n 'invoice',\n 'license',\n 'license-template',\n 'maintenance-policy',\n 'organization',\n 'plan',\n 'product',\n 'product-version',\n 'profile',\n 'release',\n 'release-channel',\n 'release-file',\n 'release-platform',\n 'role',\n 'role-claim',\n 'saml-configuration',\n 'segment',\n 'sending-domain',\n 'tag',\n 'trial',\n 'trial-policy',\n 'user',\n 'user-group',\n 'webhook',\n 'webhook-event-log',\n 'webhook-event',\n 'reseller',\n 'oidc-configuration',\n 'tenant-database-cluster',\n] as const;\nexport type CtxResourceName = (typeof RESOURCE_NAMES)[number];\n\n// TODO, use OpenAPI spec for resource definitions\n\nconst RESOURCE_DISPLAY_NAMES: Record<string, string> = {\n id: 'ID',\n createdAt: 'Creation Date',\n scopes: 'Permissions',\n updatedAt: 'Last Updated',\n expiresAt: 'Expiration Date',\n lastSeenAt: 'Last Seen',\n os: 'OS',\n osVersion: 'OS Version',\n key: 'License Key',\n vmName: 'VM Name',\n container: 'Container',\n allowedIpRange: 'Allowed IP Range',\n allowedIpRanges: 'Allowed IP Ranges',\n allowedIpAddresses: 'Allowed IP Addresses',\n disallowedIpAddresses: 'Disallowed IP Addresses',\n allowVmActivation: 'Allow VM Activation',\n disableGeoLocation: 'Disable Geolocation',\n 'user.id': 'User ID',\n userId: 'User',\n productId: 'Product',\n downloads: 'Total Downloads',\n claims: 'Permissions',\n googleSsoEnabled: 'Google Login Enabled',\n lastAttemptedAt: 'Last Attempt Date',\n url: 'URL',\n 'trialPolicy.name': 'Trial Policy Name',\n 'licensePolicy.name': 'License Template Name',\n licensePolicy: 'License Template',\n eventLog: 'Audit Log',\n cc: 'CC Recepients',\n bcc: 'BCC Recepients',\n ipAddress: 'IP Address',\n resellerId: 'Reseller',\n productVersionId: 'Product Version',\n releaseId: 'Release',\n maintenancePolicyId: 'Maintenance Policy',\n webhookId: 'Webhook',\n automatedEmailId: 'Automated Email',\n 'location.countryName': 'Country',\n 'location.ipAddress': 'IP Address',\n 'location.countryCode': 'Country',\n organizationId: 'Organization',\n 'address.country': 'Country',\n 'address.addressLine1': 'Address Line 1',\n 'address.addressLine2': 'Address Line 2',\n responseStatusCode: 'HTTP Status Code',\n resourceId: 'Resource ID',\n Sso: 'SAML SSO 2.0',\n 'reseller.name': 'Reseller',\n sendingDomain: 'Email Sending Domain',\n};\n\nfunction getResourceDisplayName(resourceName: string, portal: CtxPortals) {\n if (portal !== 'admin-portal' && resourceName in OTHER_PORTALS_DISPLAY_NAME) {\n return OTHER_PORTALS_DISPLAY_NAME[resourceName];\n } else if (resourceName in RESOURCE_DISPLAY_NAMES) {\n return RESOURCE_DISPLAY_NAMES[resourceName];\n } else {\n return toTitleCase(resourceName);\n }\n}\n\nconst ProjectContext = createContext<CtxPortals>('admin-portal');\n\nexport function ProjectProvider({ projectName, children }: { projectName: CtxPortals; children: React.ReactNode }) {\n return <ProjectContext.Provider value={projectName}>{children}</ProjectContext.Provider>;\n}\n\nexport function useProjectName(): CtxPortals {\n const projectName = use(ProjectContext);\n return projectName;\n}\n\nexport function useResourceFormatter(): (resourceName: string) => string {\n const portal = useProjectName();\n return (resourceName: string) => getResourceDisplayName(resourceName, portal);\n}\n\n/**\n * Format multiple license parameters (expired, suspended, revoked) into a single status\n */\nexport function getLicenseStatus(license: any): string {\n const licenseExpired = license.expiresAt && new Date(license.expiresAt) < new Date();\n // Status Column\n switch (true) {\n case license.revoked && license.suspended && licenseExpired:\n return 'Revoked, Suspended, Expired';\n case license.revoked && license.suspended:\n return 'Revoked, Suspended';\n case license.revoked && licenseExpired:\n return 'Revoked, Expired';\n case license.suspended && licenseExpired:\n return 'Suspended, Expired';\n case license.suspended:\n return 'Suspended';\n case license.revoked:\n return 'Revoked';\n case licenseExpired:\n return 'Expired';\n default:\n return 'Active';\n }\n}\ntype OsType = ApiSchema<'ActivationCreateRequestModel'>['os'];\nexport const ALL_OS: Record<OsType, string> = {\n windows: 'Windows',\n macos: 'macOS',\n linux: 'Linux',\n ios: 'iOS',\n android: 'Android',\n};\n"],"names":["OTHER_PORTALS_DISPLAY_NAME","RESOURCE_NAMES","RESOURCE_DISPLAY_NAMES","getResourceDisplayName","resourceName","portal","toTitleCase","ProjectContext","createContext","ProjectProvider","projectName","children","useProjectName","use","useResourceFormatter","getLicenseStatus","license","licenseExpired","ALL_OS"],"mappings":"mJAkBA,MAAMA,EAAqD,CACvD,sBAAuB,UAEvB,oBAAqB,SACzB,EAKaC,EAAiB,CAC1B,eACA,UACA,aACA,iBACA,aACA,YACA,kBACA,4BACA,OACA,kBACA,eACA,UACA,UACA,UACA,mBACA,qBACA,eACA,OACA,UACA,kBACA,UACA,UACA,kBACA,eACA,mBACA,OACA,aACA,qBACA,UACA,iBACA,MACA,QACA,eACA,OACA,aACA,UACA,oBACA,gBACA,WACA,qBACA,yBACJ,EAKMC,EAAiD,CACnD,GAAI,KACJ,UAAW,gBACX,OAAQ,cACR,UAAW,eACX,UAAW,kBACX,WAAY,YACZ,GAAI,KACJ,UAAW,aACX,IAAK,cACL,OAAQ,UACR,UAAW,YACX,eAAgB,mBAChB,gBAAiB,oBACjB,mBAAoB,uBACpB,sBAAuB,0BACvB,kBAAmB,sBACnB,mBAAoB,sBACpB,UAAW,UACX,OAAQ,OACR,UAAW,UACX,UAAW,kBACX,OAAQ,cACR,iBAAkB,uBAClB,gBAAiB,oBACjB,IAAK,MACL,mBAAoB,oBACpB,qBAAsB,wBACtB,cAAe,mBACf,SAAU,YACV,GAAI,gBACJ,IAAK,iBACL,UAAW,aACX,WAAY,WACZ,iBAAkB,kBAClB,UAAW,UACX,oBAAqB,qBACrB,UAAW,UACX,iBAAkB,kBAClB,uBAAwB,UACxB,qBAAsB,aACtB,uBAAwB,UACxB,eAAgB,eAChB,kBAAmB,UACnB,uBAAwB,iBACxB,uBAAwB,iBACxB,mBAAoB,mBACpB,WAAY,cACZ,IAAK,eACL,gBAAiB,WACjB,cAAe,sBACnB,EAEA,SAASC,EAAuBC,EAAsBC,EAAoB,CACtE,OAAIA,IAAW,gBAAkBD,KAAgBJ,EACtCA,EAA2BI,CAAY,EACvCA,KAAgBF,EAChBA,EAAuBE,CAAY,E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