@cryptlex/web-components 6.6.6-alpha56 → 6.6.6-alpha57
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.
|
@@ -7,7 +7,6 @@ import { CtxIcon } from './icons';
|
|
|
7
7
|
import { ClientPathsWithMethod } from 'openapi-fetch';
|
|
8
8
|
import { PressEvent } from 'react-aria-components';
|
|
9
9
|
import { CtxClientType } from '../utilities/ctx-client';
|
|
10
|
-
import { ControlledDialogComponent } from './dialog';
|
|
11
10
|
export type DisplayType = 'string' | 'boolean' | 'date' | 'number' | 'enum' | 'badge' | 'country' | 'fileSize' | 'days';
|
|
12
11
|
declare module '@tanstack/react-table' {
|
|
13
12
|
interface ColumnMeta<TData extends RowData, TValue> {
|
|
@@ -98,36 +97,43 @@ export declare function DataTableProvider<T extends object, TOperation extends k
|
|
|
98
97
|
export type DataTableProps = React.ComponentProps<'section'>;
|
|
99
98
|
export declare function DataTable({ className, ...props }: DataTableProps): import("react/jsx-runtime").JSX.Element;
|
|
100
99
|
/** Base properties shared by all table actions */
|
|
101
|
-
type
|
|
100
|
+
type ActionBase = {
|
|
102
101
|
label: string;
|
|
103
102
|
icon: CtxIcon;
|
|
104
103
|
tooltip?: string;
|
|
105
|
-
/** Optional function to determine if the action is disabled. Receives the rows and returns a boolean. Defaults to false if not provided */
|
|
106
|
-
isDisabled?: (data: T | T[]) => boolean;
|
|
107
|
-
/** True for actions that can be applied for bulk operations */
|
|
108
|
-
bulk: boolean;
|
|
109
|
-
/** True for actions that can be row-level actions */
|
|
110
|
-
isRowCompatible: boolean;
|
|
111
104
|
/** Optional button variant to pass through to Button (defaults to neutral) */
|
|
112
105
|
variant?: React.ComponentProps<typeof Button>['variant'];
|
|
113
106
|
};
|
|
114
|
-
/**
|
|
115
|
-
type
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
107
|
+
/** Context provided to onPress functions in TableActions */
|
|
108
|
+
type ActionPressContext = {
|
|
109
|
+
event?: PressEvent;
|
|
110
|
+
openDialog: (c: React.ReactNode) => void;
|
|
111
|
+
closeDialog: () => void;
|
|
119
112
|
};
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
113
|
+
type NoResourceAction = ActionBase & {
|
|
114
|
+
resourceType: 'none';
|
|
115
|
+
isDisabled?: () => boolean;
|
|
116
|
+
onPress: (c: ActionPressContext) => void;
|
|
117
|
+
};
|
|
118
|
+
type SingleResourceAction<T> = ActionBase & {
|
|
119
|
+
resourceType: 'single';
|
|
120
|
+
isDisabled?: (data: T) => boolean;
|
|
121
|
+
onPress: (c: ActionPressContext & {
|
|
122
|
+
data: T;
|
|
123
|
+
}) => void;
|
|
124
|
+
};
|
|
125
|
+
type BulkResourceAction<T> = ActionBase & {
|
|
126
|
+
resourceType: 'multiple';
|
|
127
|
+
isDisabled?: (data: T[]) => boolean;
|
|
128
|
+
onPress: (c: ActionPressContext & {
|
|
129
|
+
data: T[];
|
|
130
|
+
}) => void;
|
|
125
131
|
};
|
|
126
132
|
/** Common table action type that works for both action and dialog types */
|
|
127
|
-
export type TableAction<T> =
|
|
133
|
+
export type TableAction<T> = NoResourceAction | SingleResourceAction<T> | BulkResourceAction<T>;
|
|
128
134
|
export type TableActionsProps<T> = {
|
|
129
135
|
/** Array of table actions to render */
|
|
130
|
-
readonly items:
|
|
136
|
+
readonly items: (NoResourceAction | BulkResourceAction<T>)[];
|
|
131
137
|
/** Whether the table is currently fetching data */
|
|
132
138
|
readonly isFetching?: boolean;
|
|
133
139
|
};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{jsx as t,Fragment as C,jsxs as u}from"react/jsx-runtime";import{createContext as de,useState as I,useMemo as me,useEffect as ge,useContext as pe,useRef as fe}from"react";import{Button as y}from"./button.js";import{useSensors as be,useSensor as V,PointerSensor as he,KeyboardSensor as Se,DndContext as ye,closestCenter as ve,DragOverlay as Ce}from"@dnd-kit/core";import{sortableKeyboardCoordinates as we,SortableContext as xe,verticalListSortingStrategy as Ne,arrayMove as Te,useSortable as Ie}from"@dnd-kit/sortable";import{CSS as Fe}from"@dnd-kit/utilities";import{useQuery as Ae}from"@tanstack/react-query";import{createColumnHelper as X,useReactTable as De,getCoreRowModel as Pe,flexRender as O}from"@tanstack/react-table";import{useLocalStorage as k}from"@uidotdev/usehooks";import{merge as Re}from"lodash-es";import{Badge as ze}from"./badge.js";import{TfDatePicker as Oe}from"./date-picker.js";import{EasyMenu as P,MenuItem as F}from"./menu.js";import{PopoverTrigger as Me,Popover as _e}from"./popover.js";import{useAppForm as Le}from"../utilities/form-hook.js";import{useResourceFormatter as L}from"../utilities/resources.js";import{classNames as v}from"../utilities/theme.js";import{IcInfo as $e,IcMoreVertical as je,IcRefresh as Ee,IcColumns as qe,IcGrip as Ve,IcFirst as ke,IcLeft as He,IcRight as Ue,IcLast as Be,IcSortAsc as Ke,IcSortDesc as Qe,IcSortNone as Ge,IcFilter as Xe,IcRemove as H,IcCheck as U,IcMinus as Ze,IcAccount as Je,IcLicense as We,IcDate as Ye,IcFile as et}from"./icons.js";import{TfMultipleIdSearchInput as tt}from"./id-search.js";import{Loader as nt}from"./loader.js";import{SearchField as rt}from"./searchfield.js";import{Table as ot,TableHeader as at,TableRow as B,TableHead as it,TableBody as lt,TableCell as st}from"./table.js";import{CountryName as ct}from"../utilities/countries.js";import{formatDate as ut}from"../utilities/date.js";import{formatDays as dt,formatFilesize as mt,formatNumber as gt}from"../utilities/numbers.js";import{Checkbox as K}from"./checkbox.js";import{useCtxClient as pt}from"../utilities/ctx-client.js";import{ControlledDialogProvider as ft,useControlledDialog as Z}from"./dialog.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"../utilities/empty-option.js";import"./select-options.js";import"zod";import"../utilities/duration.js";function bt(e){return e?e.desc?`-${e.id}`:`+${e.id}`:"-createdAt"}const J=X(),ht=[J.accessor("checkbox",{header:({table:e})=>t(K,{isIndeterminate:e.getIsSomeRowsSelected()&&!e.getIsAllPageRowsSelected(),isSelected:e.getIsAllPageRowsSelected()||e.getIsSomePageRowsSelected(),onChange:()=>e.toggleAllPageRowsSelected(),"aria-label":"Select all"}),cell:({row:e})=>t(K,{isSelected:e.getIsSelected(),onChange:()=>e.toggleSelected(),"aria-label":"Select row"}),enableSorting:!1,enableHiding:!1})],x="TableActions";function St(e){return e.length===0?[]:[J.accessor(x,{header:"Actions",id:x,enableHiding:!1,cell:({row:r})=>t(It,{label:t(je,{}),data:r.original,items:e}),enableSorting:!1})]}function In(){return X()}function Fn({path:e,pathParameters:r,columns:n,filterConfig:l,columnsToHideByDefault:i={},allowSelection:s=!1,initialFilters:o=[],tableActions:c}){const[f,g]=I({pagination:{pageIndex:0,pageSize:20},sorting:[]}),{sorting:S,pagination:m}=f,[d,b]=I(""),[p,h]=I({}),[A,re]=I(o),oe=me(()=>A.map(a=>Array.isArray(a.value)?{[a.property]:{[a.operator]:a.value.join(",")}}:{[a.property]:{[a.operator]:a.value}}).reduce((a,T)=>Re(a,T),{}),[A]),ae={...A,page:m.pageIndex+1,limit:m.pageSize,sort:bt(S[0]),search:d},ie=pt(),R=["get",e],[$,j]=k(`${R.join("")}_ctx_column_order_preference`,[]),[E,le]=k(`${R.join("")}_ctx_column_visibility_preference`,{id:!1,...i}),z=a=>{g(T=>({...T,...a}))},D=Ae({queryKey:R,queryFn:async()=>{const a=await ie.GET(e,{params:{query:ae,path:r}});return{data:a.data??[],total:Number.parseInt(a.response.headers.get("Pagination-Count")||"0")}}}),se=c.filter(a=>a.isRowCompatible),ce=[...s?ht:[],...n,...St(se??[])];function ue(a){return typeof a=="function"}function N(a,T){return ue(a)?a(T):a}const q=De({data:D.data?.data??[],columns:ce,getCoreRowModel:Pe(),rowCount:D.data?.total??0,manualPagination:!0,onPaginationChange:a=>{z({pagination:N(a,m)})},manualSorting:!0,onSortingChange:a=>{h({}),z({sorting:[...N(a,S)]})},manualFiltering:!0,onColumnVisibilityChange:a=>{le(N(a,E))},onRowSelectionChange:a=>{h(N(a,p))},onColumnOrderChange:a=>{j(N(a,$))},state:{sorting:S,columnVisibility:E,pagination:m,rowSelection:p,columnOrder:$},meta:{refetch:D.refetch}});return ge(()=>{j([...q.getAllLeafColumns().map(a=>a.id)])},[]),{tableState:f,updateTableState:z,query:D,setSearchQuery:b,searchQuery:d,tanTable:q,mergedFilters:oe,filters:A,setFilters:re,filterConfig:l,tableActions:c}}const W=de(null);function w(){const e=pe(W);if(!e)throw Error("DataTable should be used within DataTableProvider.");return e}function An({children:e,...r}){return t(W.Provider,{value:r,children:e})}function Dn({className:e,...r}){const{query:n,tanTable:l}=w();return t(C,{children:t(ft,{children:u("section",{...r,className:v("flex flex-col bg-elevation-1",e),children:[t(wt,{}),u("div",{className:"w-full overflow-auto border-x h-table relative",tabIndex:0,children:[n.isLoading&&t(Q,{className:"cursor-wait",children:t(nt,{})}),!n.isLoading&&l.getRowModel().rows.length===0&&t(Q,{className:"cursor-not-allowed",children:!n.isFetching&&(n.isError?u("span",{className:"flex gap-3 justify-center items-center",children:[t($e,{}),t("span",{children:n.error.message})]}):n.data?.data?.length===0?t(C,{children:"No results found."}):t(C,{children:"Unknown error. Please contact customer support."}))}),!n.isLoading&&l.getRowModel().rows.length!==0&&t(Nt,{className:"w-full"})]}),u("div",{className:"flex w-full justify-between border gap-icon p-icon overflow-x-auto",children:[u("div",{className:"flex gap-icon",children:[t(yt,{}),t(Ct,{})]}),t(vt,{})]})]})})})}function Q({children:e,className:r}){return u(C,{children:[t("span",{className:v(r,"absolute top-0 bg-elevation-1 text-foreground z-20 size-full body-sm flex items-center justify-center"),children:e}),t("span",{className:"relative h-full w-0 block"})]})}function yt(){const{tanTable:e}=w(),[r,n]=I(null),l=L(),i=be(V(he),V(Se,{coordinateGetter:we}));return t(ye,{sensors:i,collisionDetection:ve,onDragStart:o=>{const{active:c}=o;n(c.id.toString())},onDragEnd:o=>{const{active:c,over:f}=o;if(f&&c.id!==f.id){const g=e.getState().columnOrder,S=g.indexOf(c.id.toString()),m=g.indexOf(f.id.toString());e.setColumnOrder([...Te(g,S,m)])}n(null)},children:u(xe,{items:e.getState().columnOrder,strategy:Ne,children:[u(P,{label:u(C,{children:[t(qe,{className:"inline align-bottom me-1"}),"Columns"]}),selectionMode:"multiple",items:e.getAllFlatColumns(),selectedKeys:e.getVisibleFlatColumns().map(o=>o.id),children:[t(F,{onAction:()=>e.toggleAllColumnsVisible(),className:"italic",children:"(select all)"}),e.getState().columnOrder.map(o=>{const c=e.getAllFlatColumns().find(f=>f.id===o);return!c||c.id==="checkbox"||c.id===x?null:t(s,{column:c},c.id)})]}),t(Ce,{children:r?t("div",{className:"opacity-70 border-2 border-primary",children:l(r)}):null})]})});function s({column:o}){const{attributes:c,listeners:f,setNodeRef:g,transform:S,transition:m}=Ie({id:o.id}),d={transform:Fe.Transform.toString(S),transition:m,zIndex:"999"};return u(F,{ref:g,style:d,...c,id:o.id,onAction:()=>o.toggleVisibility(),isDisabled:!o.getCanHide(),className:"flex items-center",children:[t(Ve,{...f,className:"size-icon cursor-grab"}),M(o),o.getIsSorted()&&t(Y,{className:"size-icon",direction:o.getIsSorted()})]})}}function vt(){const{tanTable:e}=w(),r=e.getRowCount();return u("div",{className:"flex items-center gap-2",children:[t("span",{className:"whitespace-nowrap body-sm text-muted",children:`${e.getState().pagination.pageIndex*e.getState().pagination.pageSize+1} - ${Math.min((e.getState().pagination.pageIndex+1)*e.getState().pagination.pageSize,r)} of ${r?.toLocaleString()}`}),t(y,{"aria-label":"First page",onPress:()=>e.firstPage(),isDisabled:!e.getCanPreviousPage(),variant:"neutral",size:"icon",children:t(ke,{})}),t(y,{"aria-label":"Previous page",onPress:()=>e.previousPage(),isDisabled:!e.getCanPreviousPage(),variant:"neutral",size:"icon",children:t(He,{})}),t(y,{"aria-label":"Next page",onPress:()=>e.nextPage(),isDisabled:!e.getCanNextPage(),variant:"neutral",size:"icon",children:t(Ue,{})}),t(y,{"aria-label":"Last page",onClick:()=>e.lastPage(),isDisabled:!e.getCanNextPage(),variant:"neutral",size:"icon",children:t(Be,{})})]})}function Ct(){const{tanTable:e}=w(),r=[10,20,30,40,50];return t(P,{label:e.getState().pagination.pageSize.toString(),selectionMode:"single",selectedKeys:[e.getState().pagination.pageSize.toString()],items:r.map(n=>({id:n.toString(),value:n})),children:n=>t(F,{onAction:()=>e.setPageSize(n.value),children:n.value})})}function wt(){const{query:e,tanTable:r,searchQuery:n,setSearchQuery:l,tableActions:i}=w(),s=r.getSelectedRowModel().rows.length>0,o=i.filter(c=>!(c.isRowCompatible&&!c.bulk)).filter(c=>c.bulk===s);return u("section",{className:"flex bg-elevation-1 justify-between my-0 p-icon border gap-icon overflow-auto",children:[u("div",{className:"flex gap-icon",children:[t(y,{"aria-label":"Refresh",isPending:e.isFetching,onClick:()=>e.refetch(),variant:"neutral",size:"icon",children:t(Ee,{})}),t(Tt,{items:o,isFetching:e.isFetching})]}),u("div",{className:"flex gap-icon",children:[t(Dt,{}),t(rt,{value:n,onChange:l})]})]})}function Y({direction:e,...r}){return e==="asc"?t(Ke,{className:"size-3.5",...r}):e==="desc"?t(Qe,{className:"size-3.5",...r}):t(Ge,{className:"size-3.5",...r})}function M(e){const r=L(),n=e.columnDef.header;return typeof n=="string"?n:r(e.id)}function xt(e){const r=e.column.columnDef.meta?.displayType,n=e.getValue();if(n==null)return null;switch(r){case"date":return ut(n);case"number":return gt(n);case"boolean":case"badge":return t(ze,{className:"uppercase w-full",children:String(n)});case"country":return t(ct,{value:n});case"enum":return t("span",{className:"uppercase w-full",children:String(n)});case"fileSize":return mt(n);case"days":return dt(n);default:return String(n)}}function G({header:e}){const r=e.column.columnDef.header;return typeof r=="string"||!r?M(e.column):typeof r=="function"?typeof r(e.getContext())=="string"?M(e.column):O(r,e.getContext()):O(r,e.getContext())}function Nt({className:e}){const{tanTable:r}=w(),n=(l,i,s="z-50")=>v("px-icon py-2 text-left body-sm font-medium whitespace-nowrap",l&&`bg-elevation-1 sticky right-0 ${s} text-center justify-center`,i);return u(ot,{className:v("table-auto",e),children:[t(at,{className:"sticky top-0 z-10",children:r.getHeaderGroups().map(l=>t(B,{children:l.headers.map(i=>u(it,{scope:"col",colSpan:i.colSpan,className:n(i.id===x,"bg-elevation-1"),children:[!i.column.getCanSort()&&!i.isPlaceholder&&t("div",{className:v("w-full py-1 inline-flex items-center gap-1 body-sm",i.id===x?"justify-center":"justify-start"),children:t(G,{header:i})}),i.column.getCanSort()&&u(y,{variant:"ghost",className:v("w-full p-1",i.id===x?"justify-center":"justify-start"),onPress:i.column.getToggleSortingHandler(),children:[t("span",{children:t(G,{header:i})}),t(Y,{direction:i.column.getIsSorted()})]})]},i.id))},l.id))}),t(lt,{children:r.getRowModel().rows.map(l=>t(B,{className:v("transition-colors data-[selected=true]:bg-primary/10 hover:bg-muted-foreground/20"),"data-selected":l.getIsSelected(),children:l.getVisibleCells().map(i=>{const s=i.column.id===x,o=i.column.columnDef.meta?.displayType?xt(i):O(i.column.columnDef.cell,i.getContext());return t(st,{className:v(n(s,void 0,"z-1"),s&&"flex justify-center items-center"),children:o},i.id)})},l.id))})]})}function ee(e){return e.type==="action"}function _(e){return e.type==="dialog"}function te(e,r){return e.isDisabled?e.isDisabled(r):!1}function Tt({items:e,isFetching:r}){const{openDialog:n,closeDialog:l}=Z(),{tanTable:i}=w(),s=i.getSelectedRowModel().rows.map(o=>o.original);return t(C,{children:e.map((o,c)=>{const f=o.icon,g=te(o,s)||r;return _(o)&&console.log(o.component,typeof o.component),u(y,{"aria-label":o.label,type:"button",isDisabled:g,className:"animate-in fade-in slide-in-from-left-15 duration-300 transition-transform",onPress:S=>{if(ee(o))o.onPress(S,s);else if(_(o)){const m=o.component;n(t(m,{close:l,data:s}))}},variant:o.variant??"neutral",children:[f&&t(f,{"aria-hidden":!0}),t("span",{children:o.label})]},`${o.label}-${c}`)})})}function It({label:e,items:r,data:n}){const{openDialog:l,closeDialog:i}=Z();return t(P,{"aria-label":"Actions",label:e,size:"icon",children:r.map(s=>{const o=s.icon,c=te(s,[n]);return u(F,{id:s.label,isDisabled:c,onAction:()=>{if(ee(s))s.onPress(void 0,n);else if(_(s)){const f=s.component;l(t(f,{close:i,data:n}))}},children:[t(o,{className:"size-icon"}),s.label]},s.label)})})}const Pn=["eq","ne","cn","nc","sw","ew","in","nin","gt","gte","lt","lte"],Ft={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 At(e,r){const n=`${r}-${Date.now()}`,l=ne[e][0];switch(e){case"bool":return{id:n,type:e,property:r,operator:l,value:!0};case"string":return{id:n,type:e,property:r,operator:l,value:""};case"date":return{id:n,type:e,property:r,operator:l,value:new Date().toISOString()};case"id":return{id:n,type:e,property:r,operator:l,value:""};case"id-search":return{id:n,type:e,property:r,operator:l,value:[]};case"enum":return{id:n,type:e,property:r,operator:l,value:new Set};case"number":return{id:n,type:e,property:r,operator:l,value:0}}}const ne={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 Dt({className:e,...r}){const{filters:n,query:l,setFilters:i,filterConfig:s}=w(),o=fe(null),c=L(),g=Le({defaultValues:{filters:n},onSubmit:({value:m})=>{i(m.filters)}}),S=Object.keys(s).sort();return t("section",{...r,className:v("flex gap-icon items-center",e),children:u(Me,{onOpenChange:m=>{m?o.current?.focus():g.handleSubmit()},children:[u("div",{className:"relative",children:[n.length>0&&t("div",{className:"size-2 rounded-full absolute bg-primary/90 z-20 top-0 right-0 translate-x-0.5 -translate-y-0.5"}),t(y,{"aria-label":"Filter",isDisabled:l.isPending||S.length===0,type:"button",size:"icon",variant:"neutral",children:t(Xe,{})})]}),t(_e,{className:"w-full p-icon",children:t("form",{onSubmit:m=>{m.preventDefault()},className:"flex flex-col gap-icon max-h-table overflow-auto ",children:t(g.Field,{mode:"array",name:"filters",children:m=>u(C,{children:[m.state.value.map((d,b)=>u("div",{className:"flex gap-icon items-center justify-normal",children:[t("span",{className:"body-sm",children:c(d.property)}),t(g.AppField,{name:`filters[${b}].operator`,children:p=>t(p.TfSingleSelect,{items:ne[d.type].map(h=>({id:h,label:t(C,{children:Ft[h]})}))})},d.id),d.type==="bool"&&t(g.AppField,{name:`filters[${b}].value`,children:p=>t(p.TfCheckbox,{autoFocus:!0})}),d.type==="date"&&t(g.AppField,{name:`filters[${b}].value`,children:p=>t(Oe,{autoFocus:!0})}),d.type==="id"&&t(g.AppField,{name:`filters[${b}].value`,children:p=>t(p.TfTextField,{autoFocus:!0})}),d.type==="string"&&t(g.AppField,{name:`filters[${b}].value`,children:p=>t(p.TfTextField,{autoFocus:!0})}),d.type==="number"&&t(g.AppField,{name:`filters[${b}].value`,children:p=>t(p.TfNumberField,{autoFocus:!0})}),d.type==="enum"&&t(g.AppField,{name:`filters[${b}].value`,children:p=>{const h=s[d.property];return h.type!=="enum"?null:t(p.TfMultiSelect,{items:h.options})}}),d.type==="id-search"&&t(g.AppField,{name:`filters[${b}].value`,children:p=>{const h=s[d.property];return h.type!=="id-search"?null:t(tt,{path:h.path,accessor:h.accessor})}}),t(y,{type:"button",variant:"neutral",size:"icon",onPress:()=>m.removeValue(b),children:t(H,{})})]},d.id)),u("div",{className:"flex w-full items-center justify-end gap-2 not-first:mt-icon",children:[t(P,{label:"Add filter",autoFocus:!0,children:S.sort().map(d=>{const b=s[d].type,p=Pt[b];return u(F,{onAction:()=>{const h=At(b,d);m.pushValue(h)},children:[c(d),t(p,{})]},d)})}),m.state.value.length>0?u(y,{type:"button",variant:"neutral",onPress:()=>{m.setValue([])},children:[t(H,{}),"Reset"]}):null]})]})})})})]})})}const Pt={"id-search":et,bool:U,date:Ye,enum:We,id:Je,number:Ze,string:U};export{Ft as C,Dt as D,Dn as DataTable,W as DataTableContext,An as DataTableProvider,Pn as F,In as getColumnHelper,w as useDataTable,Fn as useDataTableState};
|
|
1
|
+
"use client";import{jsx as t,Fragment as C,jsxs as u}from"react/jsx-runtime";import{createContext as de,useState as I,useMemo as me,useEffect as ge,useContext as fe,useRef as pe}from"react";import{Button as y}from"./button.js";import{useSensors as be,useSensor as q,PointerSensor as he,KeyboardSensor as Se,DndContext as ye,closestCenter as ve,DragOverlay as Ce}from"@dnd-kit/core";import{sortableKeyboardCoordinates as xe,SortableContext as we,verticalListSortingStrategy as Te,arrayMove as Ne,useSortable as Ie}from"@dnd-kit/sortable";import{CSS as Fe}from"@dnd-kit/utilities";import{useQuery as Ae}from"@tanstack/react-query";import{createColumnHelper as Z,useReactTable as De,getCoreRowModel as Pe,flexRender as O}from"@tanstack/react-table";import{useLocalStorage as V}from"@uidotdev/usehooks";import{merge as Re}from"lodash-es";import{Badge as ze}from"./badge.js";import{TfDatePicker as Oe}from"./date-picker.js";import{EasyMenu as P,MenuItem as F}from"./menu.js";import{PopoverTrigger as Me,Popover as _e}from"./popover.js";import{useAppForm as Le}from"../utilities/form-hook.js";import{useResourceFormatter as _}from"../utilities/resources.js";import{classNames as v}from"../utilities/theme.js";import{IcInfo as $e,IcMoreVertical as je,IcRefresh as Ee,IcColumns as qe,IcGrip as Ve,IcFirst as He,IcLeft as ke,IcRight as Be,IcLast as Ue,IcSortAsc as Ke,IcSortDesc as Qe,IcSortNone as Ge,IcFilter as Xe,IcRemove as H,IcCheck as k,IcMinus as Ze,IcAccount as Je,IcLicense as We,IcDate as Ye,IcFile as et}from"./icons.js";import{TfMultipleIdSearchInput as tt}from"./id-search.js";import{Loader as nt}from"./loader.js";import{SearchField as rt}from"./searchfield.js";import{Table as ot,TableHeader as at,TableRow as B,TableHead as it,TableBody as lt,TableCell as st}from"./table.js";import{CountryName as ct}from"../utilities/countries.js";import{formatDate as ut}from"../utilities/date.js";import{formatDays as dt,formatFilesize as mt,formatNumber as gt}from"../utilities/numbers.js";import{Checkbox as U}from"./checkbox.js";import{useCtxClient as ft}from"../utilities/ctx-client.js";import{ControlledDialogProvider as pt,useControlledDialog as J}from"./dialog.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"../utilities/empty-option.js";import"./select-options.js";import"zod";import"../utilities/duration.js";function bt(e){return e?e.desc?`-${e.id}`:`+${e.id}`:"-createdAt"}const W=Z(),ht=[W.accessor("checkbox",{header:({table:e})=>t(U,{isIndeterminate:e.getIsSomeRowsSelected()&&!e.getIsAllPageRowsSelected(),isSelected:e.getIsAllPageRowsSelected()||e.getIsSomePageRowsSelected(),onChange:()=>e.toggleAllPageRowsSelected(),"aria-label":"Select all"}),cell:({row:e})=>t(U,{isSelected:e.getIsSelected(),onChange:()=>e.toggleSelected(),"aria-label":"Select row"}),enableSorting:!1,enableHiding:!1})],w="TableActions";function St(e){return e.length===0?[]:[W.accessor(w,{header:"Actions",id:w,enableHiding:!1,cell:({row:r})=>t(It,{label:t(je,{}),data:r.original,items:e}),enableSorting:!1})]}function In(){return Z()}function Fn({path:e,pathParameters:r,columns:n,filterConfig:l,columnsToHideByDefault:a={},allowSelection:d=!1,initialFilters:s=[],tableActions:o}){const[p,g]=I({pagination:{pageIndex:0,pageSize:20},sorting:[]}),{sorting:S,pagination:m}=p,[c,b]=I(""),[f,h]=I({}),[A,re]=I(s),oe=me(()=>A.map(i=>Array.isArray(i.value)?{[i.property]:{[i.operator]:i.value.join(",")}}:{[i.property]:{[i.operator]:i.value}}).reduce((i,N)=>Re(i,N),{}),[A]),ae={...A,page:m.pageIndex+1,limit:m.pageSize,sort:bt(S[0]),search:c},ie=ft(),R=["get",e],[L,$]=V(`${R.join("")}_ctx_column_order_preference`,[]),[j,le]=V(`${R.join("")}_ctx_column_visibility_preference`,{id:!1,...a}),z=i=>{g(N=>({...N,...i}))},D=Ae({queryKey:R,queryFn:async()=>{const i=await ie.GET(e,{params:{query:ae,path:r}});return{data:i.data??[],total:Number.parseInt(i.response.headers.get("Pagination-Count")||"0")}}}),se=o.filter(te),ce=[...d?ht:[],...n,...St(se??[])];function ue(i){return typeof i=="function"}function T(i,N){return ue(i)?i(N):i}const E=De({data:D.data?.data??[],columns:ce,getCoreRowModel:Pe(),rowCount:D.data?.total??0,manualPagination:!0,onPaginationChange:i=>{z({pagination:T(i,m)})},manualSorting:!0,onSortingChange:i=>{h({}),z({sorting:[...T(i,S)]})},manualFiltering:!0,onColumnVisibilityChange:i=>{le(T(i,j))},onRowSelectionChange:i=>{h(T(i,f))},onColumnOrderChange:i=>{$(T(i,L))},state:{sorting:S,columnVisibility:j,pagination:m,rowSelection:f,columnOrder:L},meta:{refetch:D.refetch}});return ge(()=>{$([...E.getAllLeafColumns().map(i=>i.id)])},[]),{tableState:p,updateTableState:z,query:D,setSearchQuery:b,searchQuery:c,tanTable:E,mergedFilters:oe,filters:A,setFilters:re,filterConfig:l,tableActions:o}}const Y=de(null);function x(){const e=fe(Y);if(!e)throw Error("DataTable should be used within DataTableProvider.");return e}function An({children:e,...r}){return t(Y.Provider,{value:r,children:e})}function Dn({className:e,...r}){const{query:n,tanTable:l}=x();return t(C,{children:t(pt,{children:u("section",{...r,className:v("flex flex-col bg-elevation-1",e),children:[t(xt,{}),u("div",{className:"w-full overflow-auto border-x h-table relative",tabIndex:0,children:[n.isLoading&&t(K,{className:"cursor-wait",children:t(nt,{})}),!n.isLoading&&l.getRowModel().rows.length===0&&t(K,{className:"cursor-not-allowed",children:!n.isFetching&&(n.isError?u("span",{className:"flex gap-3 justify-center items-center",children:[t($e,{}),t("span",{children:n.error.message})]}):n.data?.data?.length===0?t(C,{children:"No results found."}):t(C,{children:"Unknown error. Please contact customer support."}))}),!n.isLoading&&l.getRowModel().rows.length!==0&&t(Tt,{className:"w-full"})]}),u("div",{className:"flex w-full justify-between border gap-icon p-icon overflow-x-auto",children:[u("div",{className:"flex gap-icon",children:[t(yt,{}),t(Ct,{})]}),t(vt,{})]})]})})})}function K({children:e,className:r}){return u(C,{children:[t("span",{className:v(r,"absolute top-0 bg-elevation-1 text-foreground z-20 size-full body-sm flex items-center justify-center"),children:e}),t("span",{className:"relative h-full w-0 block"})]})}function yt(){const{tanTable:e}=x(),[r,n]=I(null),l=_(),a=be(q(he),q(Se,{coordinateGetter:xe}));return t(ye,{sensors:a,collisionDetection:ve,onDragStart:s=>{const{active:o}=s;n(o.id.toString())},onDragEnd:s=>{const{active:o,over:p}=s;if(p&&o.id!==p.id){const g=e.getState().columnOrder,S=g.indexOf(o.id.toString()),m=g.indexOf(p.id.toString());e.setColumnOrder([...Ne(g,S,m)])}n(null)},children:u(we,{items:e.getState().columnOrder,strategy:Te,children:[u(P,{label:u(C,{children:[t(qe,{className:"inline align-bottom me-1"}),"Columns"]}),selectionMode:"multiple",items:e.getAllFlatColumns(),selectedKeys:e.getVisibleFlatColumns().map(s=>s.id),children:[t(F,{onAction:()=>e.toggleAllColumnsVisible(),className:"italic",children:"(select all)"}),e.getState().columnOrder.map(s=>{const o=e.getAllFlatColumns().find(p=>p.id===s);return!o||o.id==="checkbox"||o.id===w?null:t(d,{column:o},o.id)})]}),t(Ce,{children:r?t("div",{className:"opacity-70 border-2 border-primary",children:l(r)}):null})]})});function d({column:s}){const{attributes:o,listeners:p,setNodeRef:g,transform:S,transition:m}=Ie({id:s.id}),c={transform:Fe.Transform.toString(S),transition:m,zIndex:"999"};return u(F,{ref:g,style:c,...o,id:s.id,onAction:()=>s.toggleVisibility(),isDisabled:!s.getCanHide(),className:"flex items-center",children:[t(Ve,{...p,className:"size-icon cursor-grab"}),M(s),s.getIsSorted()&&t(ee,{className:"size-icon",direction:s.getIsSorted()})]})}}function vt(){const{tanTable:e}=x(),r=e.getRowCount();return u("div",{className:"flex items-center gap-2",children:[t("span",{className:"whitespace-nowrap body-sm text-muted",children:`${e.getState().pagination.pageIndex*e.getState().pagination.pageSize+1} - ${Math.min((e.getState().pagination.pageIndex+1)*e.getState().pagination.pageSize,r)} of ${r?.toLocaleString()}`}),t(y,{"aria-label":"First page",onPress:()=>e.firstPage(),isDisabled:!e.getCanPreviousPage(),variant:"neutral",size:"icon",children:t(He,{})}),t(y,{"aria-label":"Previous page",onPress:()=>e.previousPage(),isDisabled:!e.getCanPreviousPage(),variant:"neutral",size:"icon",children:t(ke,{})}),t(y,{"aria-label":"Next page",onPress:()=>e.nextPage(),isDisabled:!e.getCanNextPage(),variant:"neutral",size:"icon",children:t(Be,{})}),t(y,{"aria-label":"Last page",onClick:()=>e.lastPage(),isDisabled:!e.getCanNextPage(),variant:"neutral",size:"icon",children:t(Ue,{})})]})}function Ct(){const{tanTable:e}=x(),r=[10,20,30,40,50];return t(P,{label:e.getState().pagination.pageSize.toString(),selectionMode:"single",selectedKeys:[e.getState().pagination.pageSize.toString()],items:r.map(n=>({id:n.toString(),value:n})),children:n=>t(F,{onAction:()=>e.setPageSize(n.value),children:n.value})})}function xt(){const{query:e,tanTable:r,searchQuery:n,setSearchQuery:l,tableActions:a}=x(),d=r.getSelectedRowModel().rows.length>0,s=a.filter(o=>o.resourceType!=="single").filter(o=>o.resourceType==="multiple"===d);return u("section",{className:"flex bg-elevation-1 justify-between my-0 p-icon border gap-icon overflow-auto",children:[u("div",{className:"flex gap-icon",children:[t(y,{"aria-label":"Refresh",isPending:e.isFetching,onClick:()=>e.refetch(),variant:"neutral",size:"icon",children:t(Ee,{})}),t(Nt,{items:s,isFetching:e.isFetching})]}),u("div",{className:"flex gap-icon",children:[t(Dt,{}),t(rt,{value:n,onChange:l})]})]})}function ee({direction:e,...r}){return e==="asc"?t(Ke,{className:"size-3.5",...r}):e==="desc"?t(Qe,{className:"size-3.5",...r}):t(Ge,{className:"size-3.5",...r})}function M(e){const r=_(),n=e.columnDef.header;return typeof n=="string"?n:r(e.id)}function wt(e){const r=e.column.columnDef.meta?.displayType,n=e.getValue();if(n==null)return null;switch(r){case"date":return ut(n);case"number":return gt(n);case"boolean":case"badge":return t(ze,{className:"uppercase w-full",children:String(n)});case"country":return t(ct,{value:n});case"enum":return t("span",{className:"uppercase w-full",children:String(n)});case"fileSize":return mt(n);case"days":return dt(n);default:return String(n)}}function Q({header:e}){const r=e.column.columnDef.header;return typeof r=="string"||!r?M(e.column):typeof r=="function"?typeof r(e.getContext())=="string"?M(e.column):O(r,e.getContext()):O(r,e.getContext())}function Tt({className:e}){const{tanTable:r}=x(),n=(l,a,d="z-50")=>v("px-icon py-2 text-left body-sm font-medium whitespace-nowrap",l&&`bg-elevation-1 sticky right-0 ${d} text-center justify-center`,a);return u(ot,{className:v("table-auto",e),children:[t(at,{className:"sticky top-0 z-10",children:r.getHeaderGroups().map(l=>t(B,{children:l.headers.map(a=>u(it,{scope:"col",colSpan:a.colSpan,className:n(a.id===w,"bg-elevation-1"),children:[!a.column.getCanSort()&&!a.isPlaceholder&&t("div",{className:v("w-full py-1 inline-flex items-center gap-1 body-sm",a.id===w?"justify-center":"justify-start"),children:t(Q,{header:a})}),a.column.getCanSort()&&u(y,{variant:"ghost",className:v("w-full p-1",a.id===w?"justify-center":"justify-start"),onPress:a.column.getToggleSortingHandler(),children:[t("span",{children:t(Q,{header:a})}),t(ee,{direction:a.column.getIsSorted()})]})]},a.id))},l.id))}),t(lt,{children:r.getRowModel().rows.map(l=>t(B,{className:v("transition-colors data-[selected=true]:bg-primary/10 hover:bg-muted-foreground/20"),"data-selected":l.getIsSelected(),children:l.getVisibleCells().map(a=>{const d=a.column.id===w,s=a.column.columnDef.meta?.displayType?wt(a):O(a.column.columnDef.cell,a.getContext());return t(st,{className:v(n(d,void 0,"z-1"),d&&"flex justify-center items-center"),children:s},a.id)})},l.id))})]})}function G(e){return e.resourceType==="none"}function te(e){return e.resourceType==="single"}function X(e){return e.resourceType==="multiple"}function Nt({items:e,isFetching:r}){const{openDialog:n,closeDialog:l}=J(),{tanTable:a}=x();function d(o,p){return o.isDisabled?G(o)?o.isDisabled():X(o)?o.isDisabled(p):!1:!1}const s=a.getSelectedRowModel().rows.map(o=>o.original);return t(C,{children:e.map((o,p)=>{const g=o.icon,S=d(o,s)||r;return u(y,{"aria-label":o.label,type:"button",isDisabled:S,className:"animate-in fade-in slide-in-from-left-15 duration-300 transition-transform",onPress:m=>{const c={event:m,openDialog:n,closeDialog:l};G(o)?o.onPress(c):X(o)&&o.onPress({...c,data:s})},variant:o.variant??"neutral",children:[g&&t(g,{"aria-hidden":!0}),t("span",{children:o.label})]},`${o.label}-${p}`)})})}function It({label:e,items:r,data:n}){const{openDialog:l,closeDialog:a}=J();return t(P,{"aria-label":"Actions",label:e,size:"icon",children:r.map(d=>{const s=d.icon;return u(F,{id:d.label,isDisabled:d.isDisabled?.(n)??!1,onAction:()=>{const o={openDialog:l,closeDialog:a};te(d)&&d.onPress({...o,data:n})},children:[t(s,{className:"size-icon"}),d.label]},d.label)})})}const Pn=["eq","ne","cn","nc","sw","ew","in","nin","gt","gte","lt","lte"],Ft={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 At(e,r){const n=`${r}-${Date.now()}`,l=ne[e][0];switch(e){case"bool":return{id:n,type:e,property:r,operator:l,value:!0};case"string":return{id:n,type:e,property:r,operator:l,value:""};case"date":return{id:n,type:e,property:r,operator:l,value:new Date().toISOString()};case"id":return{id:n,type:e,property:r,operator:l,value:""};case"id-search":return{id:n,type:e,property:r,operator:l,value:[]};case"enum":return{id:n,type:e,property:r,operator:l,value:new Set};case"number":return{id:n,type:e,property:r,operator:l,value:0}}}const ne={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 Dt({className:e,...r}){const{filters:n,query:l,setFilters:a,filterConfig:d}=x(),s=pe(null),o=_(),g=Le({defaultValues:{filters:n},onSubmit:({value:m})=>{a(m.filters)}}),S=Object.keys(d).sort();return t("section",{...r,className:v("flex gap-icon items-center",e),children:u(Me,{onOpenChange:m=>{m?s.current?.focus():g.handleSubmit()},children:[u("div",{className:"relative",children:[n.length>0&&t("div",{className:"size-2 rounded-full absolute bg-primary/90 z-20 top-0 right-0 translate-x-0.5 -translate-y-0.5"}),t(y,{"aria-label":"Filter",isDisabled:l.isPending||S.length===0,type:"button",size:"icon",variant:"neutral",children:t(Xe,{})})]}),t(_e,{className:"w-full p-icon",children:t("form",{onSubmit:m=>{m.preventDefault()},className:"flex flex-col gap-icon max-h-table overflow-auto ",children:t(g.Field,{mode:"array",name:"filters",children:m=>u(C,{children:[m.state.value.map((c,b)=>u("div",{className:"flex gap-icon items-center justify-normal",children:[t("span",{className:"body-sm",children:o(c.property)}),t(g.AppField,{name:`filters[${b}].operator`,children:f=>t(f.TfSingleSelect,{items:ne[c.type].map(h=>({id:h,label:t(C,{children:Ft[h]})}))})},c.id),c.type==="bool"&&t(g.AppField,{name:`filters[${b}].value`,children:f=>t(f.TfCheckbox,{autoFocus:!0})}),c.type==="date"&&t(g.AppField,{name:`filters[${b}].value`,children:f=>t(Oe,{autoFocus:!0})}),c.type==="id"&&t(g.AppField,{name:`filters[${b}].value`,children:f=>t(f.TfTextField,{autoFocus:!0})}),c.type==="string"&&t(g.AppField,{name:`filters[${b}].value`,children:f=>t(f.TfTextField,{autoFocus:!0})}),c.type==="number"&&t(g.AppField,{name:`filters[${b}].value`,children:f=>t(f.TfNumberField,{autoFocus:!0})}),c.type==="enum"&&t(g.AppField,{name:`filters[${b}].value`,children:f=>{const h=d[c.property];return h.type!=="enum"?null:t(f.TfMultiSelect,{items:h.options})}}),c.type==="id-search"&&t(g.AppField,{name:`filters[${b}].value`,children:f=>{const h=d[c.property];return h.type!=="id-search"?null:t(tt,{path:h.path,accessor:h.accessor})}}),t(y,{type:"button",variant:"neutral",size:"icon",onPress:()=>m.removeValue(b),children:t(H,{})})]},c.id)),u("div",{className:"flex w-full items-center justify-end gap-2 not-first:mt-icon",children:[t(P,{label:"Add filter",autoFocus:!0,children:S.sort().map(c=>{const b=d[c].type,f=Pt[b];return u(F,{onAction:()=>{const h=At(b,c);m.pushValue(h)},children:[o(c),t(f,{})]},c)})}),m.state.value.length>0?u(y,{type:"button",variant:"neutral",onPress:()=>{m.setValue([])},children:[t(H,{}),"Reset"]}):null]})]})})})})]})})}const Pt={"id-search":et,bool:k,date:Ye,enum:We,id:Je,number:Ze,string:k};export{Ft as C,Dt as D,Dn as DataTable,Y as DataTableContext,An as DataTableProvider,Pn as F,In as getColumnHelper,x as useDataTable,Fn 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 { 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 {\n type CtxIcon,\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 { PressEvent } from 'react-aria-components';\nimport { type CtxClientType, useCtxClient } from '../utilities/ctx-client';\nimport { type ControlledDialogComponent, ControlledDialogProvider, useControlledDialog } from './dialog';\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';\nfunction getActionsColumn<T extends object>(rowActions: TableAction<T>[]) {\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 }) => (\n <TableActionsRowMenu label={<IcMoreVertical />} data={row.original} items={rowActions} />\n ),\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};\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}: 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 const rowActions = tableActions.filter(a => a.isRowCompatible);\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 ...getActionsColumn<T>(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 <ControlledDialogProvider>\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 </ControlledDialogProvider>\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\n const filteredActions = tableActions\n .filter(ta => !(ta.isRowCompatible && !ta.bulk))\n .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} 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\n/** Base properties shared by all table actions */\ntype TableActionBase<T> = {\n label: string;\n icon: CtxIcon;\n tooltip?: string;\n /** Optional function to determine if the action is disabled. Receives the rows and returns a boolean. Defaults to false if not provided */\n isDisabled?: (data: T | T[]) => boolean;\n /** True for actions that can be applied for bulk operations */\n bulk: boolean;\n /** True for actions that can be row-level actions */\n isRowCompatible: boolean;\n /** Optional button variant to pass through to Button (defaults to neutral) */\n variant?: React.ComponentProps<typeof Button>['variant'];\n};\n\n/** Action that triggers a callback */\ntype TableActionAction<T> = TableActionBase<T> & {\n type: 'action';\n /** Callback triggered when the action is pressed. Receives the press event and selected rows as parameters */\n onPress: (e: PressEvent, data: T | T[]) => void;\n};\n\n/** Action that opens a dialog */\ntype TableActionDialog<T> = TableActionBase<T> & {\n type: 'dialog';\n /** Component to render in the dialog */\n component: ControlledDialogComponent<T>;\n};\n\n/** Common table action type that works for both action and dialog types */\nexport type TableAction<T> = TableActionAction<T> | TableActionDialog<T>;\n\nfunction isTableActionAction<T>(item: TableAction<T>): item is TableActionAction<T> {\n return item.type === 'action';\n}\n\nfunction isTableActionDialog<T>(item: TableAction<T>): item is TableActionDialog<T> {\n return item.type === 'dialog';\n}\n\nfunction getTableActionIsDisabled<T>(item: TableAction<T>, rows: T[]): boolean {\n return item.isDisabled ? item.isDisabled(rows) : false;\n}\n\nexport type TableActionsProps<T> = {\n /** Array of table actions to render */\n readonly items: TableAction<T>[];\n /** Whether the table is currently fetching data */\n readonly isFetching?: boolean;\n};\n\nfunction TableActions<T>({ items, isFetching }: TableActionsProps<T>) {\n const { openDialog, closeDialog } = useControlledDialog();\n const { tanTable } = useDataTable();\n const selectedRows = tanTable.getSelectedRowModel().rows.map(r => r.original);\n return (\n <>\n {items.map((item, i) => {\n const Icon = item.icon;\n const isDisabled = getTableActionIsDisabled(item, selectedRows) || isFetching;\n\n if (isTableActionDialog(item)) {\n console.log(item.component, typeof item.component);\n }\n\n return (\n <Button\n key={`${item.label}-${i}`}\n aria-label={item.label}\n type=\"button\"\n isDisabled={isDisabled}\n className=\"animate-in fade-in slide-in-from-left-15 duration-300 transition-transform\"\n onPress={e => {\n if (isTableActionAction(item)) {\n item.onPress(e, selectedRows);\n } else if (isTableActionDialog(item)) {\n const Component = item.component;\n openDialog(<Component close={closeDialog} data={selectedRows} />);\n }\n }}\n variant={item.variant ?? 'neutral'}\n >\n {Icon && <Icon aria-hidden />}\n <span>{item.label}</span>\n </Button>\n );\n })}\n </>\n );\n}\n\nfunction TableActionsRowMenu<T>({\n label,\n items,\n data,\n}: {\n readonly label: React.ReactNode;\n readonly items: TableAction<T>[];\n readonly data: T;\n}) {\n const { openDialog, closeDialog } = useControlledDialog();\n\n return (\n <EasyMenu aria-label=\"Actions\" label={label} size={'icon'}>\n {items.map(it => {\n const Icon = it.icon;\n const isDisabled = getTableActionIsDisabled(it, [data]);\n return (\n <MenuItem\n key={it.label}\n id={it.label}\n isDisabled={isDisabled}\n onAction={() => {\n if (isTableActionAction(it)) {\n it.onPress(undefined as any, data);\n } else if (isTableActionDialog(it)) {\n const Component = it.component;\n openDialog(<Component close={closeDialog} data={data} />);\n }\n }}\n >\n <Icon className=\"size-icon\" />\n {it.label}\n </MenuItem>\n );\n })}\n </EasyMenu>\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","getActionsColumn","rowActions","TableActionsRowMenu","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","ControlledDialogProvider","jsxs","classNames","Actions","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","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","isTableActionAction","item","isTableActionDialog","getTableActionIsDisabled","rows","isFetching","openDialog","closeDialog","useControlledDialog","selectedRows","r","i","Icon","isDisabled","e","Component","label","data","it","FILTER_COMPARISON_OPERATORS","COMPARISON_OPERATOR_LABELS","createNewFilter","type","property","id","operator","FilterOperations","addFilterButtonRef","useRef","form","useAppForm","filterKeys","PopoverTrigger","o","IcFilter","Popover","field","lf","sf","op","_","TfDatePicker","config","TfMultipleIdSearchInput","IcRemove","k","FilterIcon","newFilter","IcFile","IcCheck","IcDate","IcLicense","IcAccount","IcMinus"],"mappings":"koFAmFA,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,eAC1B,SAASC,GAAmCC,EAA8B,CACtE,OAAIA,EAAW,SAAW,EAAU,CAAA,EAE7B,CACHT,EAAG,SAASO,EAAmB,CAC3B,OAAQ,UACR,GAAIA,EACJ,aAAc,GACd,KAAM,CAA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AA,EAAO,IAAIc,GAAK,CACxB,MAAMvB,EAAOhL,EAAauM,CAAC,EAAE,KACvBjC,EAAOkC,GAAWxB,CAAI,EAC5B,OACIrH,EAACgC,EAAA,CAEG,SAAU,IAAM,CACZ,MAAM8G,EAAY1B,GAAgBC,EAAMuB,CAAC,EACzCT,EAAM,UAAUW,CAAS,CAC7B,EAEC,SAAA,CAAAlI,EAAkBgI,CAAC,IACnBjC,EAAA,CAAA,CAAK,CAAA,CAAA,EAPDiC,CAAA,CAUjB,CAAC,CAAA,CACL,EACCT,EAAM,MAAM,MAAM,OAAS,EACxBnI,EAACkD,EAAA,CACG,KAAK,SACL,QAAQ,UACR,QAAS,IAAM,CACXiF,EAAM,SAAS,EAAE,CACrB,EAEA,SAAA,CAAA3M,EAACmN,EAAA,EAAS,EAAE,OAAA,CAAA,CAAA,EAGhB,IAAA,CAAA,CACR,CAAA,EACJ,CAER,CACJ,CAAA,CAAA,CACJ,CACJ,CAAA,CAAA,CAAA,EAER,CAER,CAEA,MAAME,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 { 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 {\n type CtxIcon,\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 { PressEvent } from 'react-aria-components';\nimport { type CtxClientType, useCtxClient } from '../utilities/ctx-client';\nimport { ControlledDialogProvider, useControlledDialog } from './dialog';\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';\nfunction getActionsColumn<T extends object>(rowActions: SingleResourceAction<T>[]) {\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 }) => (\n <TableActionsRowMenu label={<IcMoreVertical />} data={row.original} items={rowActions} />\n ),\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};\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}: 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 const rowActions = tableActions.filter(isSingleResourceAction);\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 ...getActionsColumn<T>(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 <ControlledDialogProvider>\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 </ControlledDialogProvider>\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\n const filteredActions = tableActions\n .filter(ta => ta.resourceType !== 'single')\n .filter(ta => (ta.resourceType === 'multiple') === 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} 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\n/** Base properties shared by all table actions */\ntype ActionBase = {\n label: string;\n icon: CtxIcon;\n tooltip?: string;\n /** Optional button variant to pass through to Button (defaults to neutral) */\n variant?: React.ComponentProps<typeof Button>['variant'];\n};\n\n/** Context provided to onPress functions in TableActions */\ntype ActionPressContext = {\n event?: PressEvent;\n openDialog: (c: React.ReactNode) => void;\n closeDialog: () => void;\n};\n\ntype NoResourceAction = ActionBase & {\n resourceType: 'none';\n isDisabled?: () => boolean;\n onPress: (c: ActionPressContext) => void;\n};\n\ntype SingleResourceAction<T> = ActionBase & {\n resourceType: 'single';\n isDisabled?: (data: T) => boolean;\n onPress: (c: ActionPressContext & { data: T }) => void;\n};\n\ntype BulkResourceAction<T> = ActionBase & {\n resourceType: 'multiple';\n isDisabled?: (data: T[]) => boolean;\n onPress: (c: ActionPressContext & { data: T[] }) => void;\n};\n\n/** Common table action type that works for both action and dialog types */\nexport type TableAction<T> = NoResourceAction | SingleResourceAction<T> | BulkResourceAction<T>;\n\nfunction isNoResourceAction<T>(item: TableAction<T>): item is NoResourceAction {\n return item.resourceType === 'none';\n}\n\nfunction isSingleResourceAction<T>(item: TableAction<T>): item is SingleResourceAction<T> {\n return item.resourceType === 'single';\n}\n\nfunction isBulkResourceAction<T>(item: TableAction<T>): item is BulkResourceAction<T> {\n return item.resourceType === 'multiple';\n}\n\nexport type TableActionsProps<T> = {\n /** Array of table actions to render */\n readonly items: (NoResourceAction | BulkResourceAction<T>)[];\n /** Whether the table is currently fetching data */\n readonly isFetching?: boolean;\n};\n\nfunction TableActions<T>({ items, isFetching }: TableActionsProps<T>) {\n const { openDialog, closeDialog } = useControlledDialog();\n const { tanTable } = useDataTable();\n\n function getTableActionIsDisabled<T>(item: TableAction<T>, rows: T[]): boolean {\n if (!item.isDisabled) return false;\n\n if (isNoResourceAction(item)) {\n return item.isDisabled();\n } else if (isBulkResourceAction(item)) {\n return item.isDisabled(rows);\n }\n return false;\n }\n\n const selectedRows = tanTable.getSelectedRowModel().rows.map(r => r.original);\n return (\n <>\n {items.map((item, i) => {\n const Icon = item.icon;\n const isDisabled = getTableActionIsDisabled(item, selectedRows) || isFetching;\n\n return (\n <Button\n key={`${item.label}-${i}`}\n aria-label={item.label}\n type=\"button\"\n isDisabled={isDisabled}\n className=\"animate-in fade-in slide-in-from-left-15 duration-300 transition-transform\"\n onPress={e => {\n const context = { event: e, openDialog, closeDialog };\n if (isNoResourceAction(item)) {\n item.onPress(context);\n } else if (isBulkResourceAction(item)) {\n item.onPress({ ...context, data: selectedRows as T[] });\n }\n }}\n variant={item.variant ?? 'neutral'}\n >\n {Icon && <Icon aria-hidden />}\n <span>{item.label}</span>\n </Button>\n );\n })}\n </>\n );\n}\n\nfunction TableActionsRowMenu<T>({\n label,\n items,\n data,\n}: {\n readonly label: React.ReactNode;\n readonly items: SingleResourceAction<T>[];\n readonly data: T;\n}) {\n const { openDialog, closeDialog } = useControlledDialog();\n\n return (\n <EasyMenu aria-label=\"Actions\" label={label} size={'icon'}>\n {items.map(it => {\n const Icon = it.icon;\n return (\n <MenuItem\n key={it.label}\n id={it.label}\n isDisabled={it.isDisabled?.(data) ?? false}\n onAction={() => {\n const context = { openDialog, closeDialog };\n if (isSingleResourceAction(it)) {\n it.onPress({ ...context, data });\n }\n }}\n >\n <Icon className=\"size-icon\" />\n {it.label}\n </MenuItem>\n );\n })}\n </EasyMenu>\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","getActionsColumn","rowActions","TableActionsRowMenu","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","isSingleResourceAction","cols","isUpdaterFunction","updater","resolveUpdater","currentValue","tanTable","useReactTable","getCoreRowModel","useEffect","c","DataTableContext","createContext","useDataTable","ctx","useContext","DataTableProvider","children","props","DataTable","className","Fragment","ControlledDialogProvider","jsxs","classNames","Actions","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","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","isNoResourceAction","item","isBulkResourceAction","isFetching","openDialog","closeDialog","useControlledDialog","getTableActionIsDisabled","rows","selectedRows","r","i","Icon","isDisabled","e","context","label","data","it","FILTER_COMPARISON_OPERATORS","COMPARISON_OPERATOR_LABELS","createNewFilter","type","property","id","operator","FilterOperations","addFilterButtonRef","useRef","form","useAppForm","filterKeys","PopoverTrigger","o","IcFilter","Popover","field","lf","sf","op","_","TfDatePicker","config","TfMultipleIdSearchInput","IcRemove","k","FilterIcon","newFilter","IcFile","IcCheck","IcDate","IcLicense","IcAccount","IcMinus"],"mappings":"koFAmFA,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,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C,EAElC,WAACiC,EAAA,CAAA,CAAS,CAAA,CAAA,CACd,CAAA,EAvEMP,EAAG,EAwEb,CAEP,EACDpI,EAAC,MAAA,CAAI,UAAU,+DACX,SAAA,CAAAzE,EAACuG,EAAA,CAAS,MAAM,aAAa,UAAS,GACjC,SAAAgG,EAAW,KAAA,EAAO,IAAIc,GAAK,CACxB,MAAMvB,EAAOjL,EAAawM,CAAC,EAAE,KACvBjC,EAAOkC,GAAWxB,CAAI,EAC5B,OACIrH,EAACgC,EAAA,CAEG,SAAU,IAAM,CACZ,MAAM8G,EAAY1B,GAAgBC,EAAMuB,CAAC,EACzCT,EAAM,UAAUW,CAAS,CAC7B,EAEC,SAAA,CAAAlI,EAAkBgI,CAAC,IACnBjC,EAAA,CAAA,CAAK,CAAA,CAAA,EAPDiC,CAAA,CAUjB,CAAC,CAAA,CACL,EACCT,EAAM,MAAM,MAAM,OAAS,EACxBnI,EAACkD,EAAA,CACG,KAAK,SACL,QAAQ,UACR,QAAS,IAAM,CACXiF,EAAM,SAAS,EAAE,CACrB,EAEA,SAAA,CAAA5M,EAACoN,EAAA,EAAS,EAAE,OAAA,CAAA,CAAA,EAGhB,IAAA,CAAA,CACR,CAAA,EACJ,CAER,CACJ,CAAA,CAAA,CACJ,CACJ,CAAA,CAAA,CAAA,EAER,CAER,CAEA,MAAME,GAAoD,CACtD,YAAaE,GACb,KAAMC,EACN,KAAMC,GACN,KAAMC,GACN,GAAIC,GACJ,OAAQC,GACR,OAAQJ,CACZ"}
|
|
@@ -166,15 +166,4 @@ export declare function ControlledDialogProvider({ children }: {
|
|
|
166
166
|
* ```
|
|
167
167
|
*/
|
|
168
168
|
export declare function useControlledDialog(): ControlledDialogContextType;
|
|
169
|
-
export type ControlledDialogProps<T> = {
|
|
170
|
-
/** Callback to close the dialog */
|
|
171
|
-
close: () => void;
|
|
172
|
-
/** The data passed to the dialog - array of selected rows */
|
|
173
|
-
data: T | T[];
|
|
174
|
-
};
|
|
175
|
-
/**
|
|
176
|
-
* Component type that accepts ControlledDialogProps.
|
|
177
|
-
* Use this for components that will be rendered in a controlled dialog.
|
|
178
|
-
*/
|
|
179
|
-
export type ControlledDialogComponent<T> = React.ComponentType<ControlledDialogProps<T>>;
|
|
180
169
|
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{jsx as i,jsxs as g,Fragment as f}from"react/jsx-runtime";import{cva as x}from"class-variance-authority";import{createContext as p,useState as c,useContext as h}from"react";import{DialogTrigger as b,ModalOverlay as D,composeRenderProps as m,Modal as v,Dialog as C,Heading as w}from"react-aria-components";import{Button as N}from"./button.js";import{classNames as a}from"../utilities/theme.js";import{IcClose as y}from"./icons.js";import"./loader.js";import"clsx";const z=x(["fixed z-50 gap-icon bg-elevation-1 transition ease-in-out","data-[entering]:duration-200 data-[entering]:animate-in data-[entering]:fade-in-0 data-[exiting]:duration-200 data-[exiting]:animate-out data-[exiting]:fade-out-0"],{variants:{side:{top:"inset-x-0 top-0 border-b data-[entering]:slide-in-from-top data-[exiting]:slide-out-to-top max-h-table",bottom:"inset-x-0 bottom-0 border-t data-[entering]:slide-in-from-bottom data-[exiting]:slide-out-to-bottom max-h-table",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[entering]:slide-in-from-left data-[exiting]:slide-out-to-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[entering]:slide-in-from-right data-[exiting]:slide-out-to-right sm:max-w-sm"}}}),O=b,P=({className:t,isDismissable:e=!0,...n})=>i(D,{isDismissable:e,className:m(t,o=>a("fixed inset-0 z-50 bg-background/
|
|
1
|
+
"use client";import{jsx as i,jsxs as g,Fragment as f}from"react/jsx-runtime";import{cva as x}from"class-variance-authority";import{createContext as p,useState as c,useContext as h}from"react";import{DialogTrigger as b,ModalOverlay as D,composeRenderProps as m,Modal as v,Dialog as C,Heading as w}from"react-aria-components";import{Button as N}from"./button.js";import{classNames as a}from"../utilities/theme.js";import{IcClose as y}from"./icons.js";import"./loader.js";import"clsx";const z=x(["fixed z-50 gap-icon bg-elevation-1 transition ease-in-out","data-[entering]:duration-200 data-[entering]:animate-in data-[entering]:fade-in-0 data-[exiting]:duration-200 data-[exiting]:animate-out data-[exiting]:fade-out-0"],{variants:{side:{top:"inset-x-0 top-0 border-b data-[entering]:slide-in-from-top data-[exiting]:slide-out-to-top max-h-table",bottom:"inset-x-0 bottom-0 border-t data-[entering]:slide-in-from-bottom data-[exiting]:slide-out-to-bottom max-h-table",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[entering]:slide-in-from-left data-[exiting]:slide-out-to-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[entering]:slide-in-from-right data-[exiting]:slide-out-to-right sm:max-w-sm"}}}),O=b,P=({className:t,isDismissable:e=!0,...n})=>i(D,{isDismissable:e,className:m(t,o=>a("fixed inset-0 z-50 bg-background/80","data-[exiting]:duration-100 data-[exiting]:animate-out","data-[entering]:animate-in",o)),...n});function T({className:t,children:e,side:n,role:o,closeButton:l=!0,...s}){return i(v,{className:m(t,r=>a(n?z({side:n,className:"h-full p-6"}):["fixed left-[50vw] top-1/2 z-50 w-full max-w-lg -translate-x-1/2 -translate-y-1/2 border bg-elevation-1 p-icon duration-100 data-[exiting]:duration-100 data-[entering]:animate-in data-[exiting]:animate-out data-[entering]:fade-in-0 data-[exiting]:fade-out-0 data-[entering]:zoom-in-95 data-[exiting]:zoom-out-95 md:w-full"],r)),...s,children:i(C,{role:o,className:a(!n&&"grid h-full gap-icon relative","h-full outline-none"),children:m(e,(r,d)=>g(f,{children:[r,l&&i("div",{className:"absolute right-2 top-1",children:g(N,{size:"icon",variant:"neutral",onPress:d.close,className:"rounded-full",children:[i(y,{}),i("span",{className:"sr-only",children:"Close"})]})})]}))})})}function S({className:t,...e}){return i("div",{className:a("flex flex-col gap-y-2 text-center sm:text-left",t),...e})}function V({className:t,...e}){return i("div",{className:a("flex flex-col-reverse sm:flex-row sm:justify-end sm:gap-x-2",t),...e})}function $({className:t,...e}){return i(w,{slot:"title",className:a("heading-3 font-semibold leading-none tracking-tight",t),...e})}function q({className:t,...e}){return i("p",{className:a("flex flex-col gap-y-1 text-center sm:text-left",t),...e})}const u=p(null);function A({children:t}){const[e,n]=c(!1),[o,l]=c(null),s=d=>{l(d),n(!0)},r=()=>{n(!1)};return g(u.Provider,{value:{openDialog:s,closeDialog:r,isOpen:e},children:[t,i(O,{isOpen:e,onOpenChange:n,children:i(P,{isDismissable:!0,children:i(T,{children:o})})})]})}function G(){const t=h(u);if(!t)throw new Error("useControlledDialog must be used within ControlledDialogProvider");return t}export{A as ControlledDialogProvider,T as DialogContent,q as DialogDescription,V as DialogFooter,S as DialogHeader,P as DialogOverlay,$ as DialogTitle,O as DialogTrigger,G as useControlledDialog};
|
|
2
2
|
//# sourceMappingURL=dialog.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dialog.js","sources":["../../lib/components/dialog.tsx"],"sourcesContent":["'use client';\nimport { cva, type VariantProps } from 'class-variance-authority';\nimport type { ReactNode } from 'react';\nimport { createContext, useContext, useState } from 'react';\nimport {\n Dialog as AriaDialog,\n DialogProps as AriaDialogProps,\n DialogTrigger as AriaDialogTrigger,\n Heading as AriaHeading,\n HeadingProps as AriaHeadingProps,\n Modal as AriaModal,\n ModalOverlay as AriaModalOverlay,\n ModalOverlayProps as AriaModalOverlayProps,\n composeRenderProps,\n} from 'react-aria-components';\n\nimport { Button } from '../components/button';\nimport { classNames } from '../utilities/theme';\nimport { IcClose } from './icons';\n\n/**\n * Visual variants for the sheet-style dialog (slide in from an edge).\n *\n * @remarks\n * Internally used to style `<DialogContent side=\"...\">`.\n */\nconst sheetVariants = cva(\n [\n 'fixed z-50 gap-icon bg-elevation-1 transition ease-in-out',\n 'data-[entering]:duration-200 data-[entering]:animate-in data-[entering]:fade-in-0 data-[exiting]:duration-200 data-[exiting]:animate-out data-[exiting]:fade-out-0',\n ],\n {\n variants: {\n side: {\n top: 'inset-x-0 top-0 border-b data-[entering]:slide-in-from-top data-[exiting]:slide-out-to-top max-h-table',\n bottom: 'inset-x-0 bottom-0 border-t data-[entering]:slide-in-from-bottom data-[exiting]:slide-out-to-bottom max-h-table',\n left: 'inset-y-0 left-0 h-full w-3/4 border-r data-[entering]:slide-in-from-left data-[exiting]:slide-out-to-left sm:max-w-sm',\n right: 'inset-y-0 right-0 h-full w-3/4 border-l data-[entering]:slide-in-from-right data-[exiting]:slide-out-to-right sm:max-w-sm',\n },\n },\n }\n);\n\n/**\n * Opens the dialog when interacted with (click/press).\n *\n * @remarks\n * Compose this around any control that should open the dialog.\n *\n * @example\n * ```tsx\n * <DialogTrigger>\n * <Button>Open</Button>\n * <DialogOverlay>\n * <DialogContent>...</DialogContent>\n * </DialogOverlay>\n * </DialogTrigger>\n * ```\n */\nexport const DialogTrigger = AriaDialogTrigger;\n\nexport const DialogOverlay = ({ className, isDismissable = true, ...props }: AriaModalOverlayProps) => (\n <AriaModalOverlay\n isDismissable={isDismissable}\n className={composeRenderProps(className, className =>\n classNames(\n 'fixed inset-0 z-50 bg-background/10',\n /* Exiting */\n 'data-[exiting]:duration-100 data-[exiting]:animate-out',\n /* Entering */\n 'data-[entering]:animate-in',\n className\n )\n )}\n {...props}\n />\n);\n\n/** Props for {@link DialogContent}. */\nexport interface DialogContentProps\n extends Omit<React.ComponentProps<typeof AriaModal>, 'children'>,\n VariantProps<typeof sheetVariants> {\n /**\n * Render function or nodes for the dialog panel contents.\n */\n children?: AriaDialogProps['children'];\n\n /**\n * ARIA role of the dialog.\n *\n * Use `\"alertdialog\"` for destructive/confirmation flows that require\n * explicit acknowledgement.\n * @defaultValue \"dialog\"\n */\n role?: AriaDialogProps['role'];\n\n /**\n * Show a built-in close button in the top-right corner.\n * @defaultValue true\n */\n closeButton?: boolean;\n}\n\n/**\n * Dialog panel container. Renders either a centered modal or a sheet\n * from an edge when `side` is provided.\n *\n * @example Basic\n * ```tsx\n * <DialogTrigger>\n * <Button>Open</Button>\n * <DialogOverlay>\n * <DialogContent>\n * <DialogHeader>\n * <DialogTitle>Sign up</DialogTitle>\n * </DialogHeader>\n * ...\n * </DialogContent>\n * </DialogOverlay>\n * </DialogTrigger>\n * ```\n */\nexport function DialogContent({ className, children, side, role, closeButton = true, ...props }: DialogContentProps) {\n return (\n <AriaModal\n className={composeRenderProps(className, className =>\n classNames(\n side\n ? sheetVariants({ side, className: 'h-full p-6' })\n : [\n 'fixed left-[50vw] top-1/2 z-50 w-full max-w-lg -translate-x-1/2 -translate-y-1/2 border bg-elevation-1 p-icon duration-100 data-[exiting]:duration-100 data-[entering]:animate-in data-[exiting]:animate-out data-[entering]:fade-in-0 data-[exiting]:fade-out-0 data-[entering]:zoom-in-95 data-[exiting]:zoom-out-95 md:w-full',\n ],\n className\n )\n )}\n {...props}\n >\n <AriaDialog\n role={role}\n className={classNames(!side && 'grid h-full gap-icon relative', 'h-full outline-none')}\n >\n {composeRenderProps(children, (children, renderProps) => (\n <>\n {children}\n {closeButton && (\n <div className=\"absolute right-2 top-1\">\n <Button\n size={'icon'}\n variant={'neutral'}\n onPress={renderProps.close}\n className=\"rounded-full\"\n >\n <IcClose />\n <span className=\"sr-only\">Close</span>\n </Button>\n </div>\n )}\n </>\n ))}\n </AriaDialog>\n </AriaModal>\n );\n}\n\n/**\n * Header region for the dialog panel.\n *\n * @example\n * ```tsx\n * <DialogHeader>\n * <DialogTitle>Settings</DialogTitle>\n * </DialogHeader>\n * ```\n */\nexport function DialogHeader({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {\n return <div className={classNames('flex flex-col gap-y-2 text-center sm:text-left', className)} {...props} />;\n}\n\n/**\n * Footer region that aligns action buttons.\n *\n * @example\n * ```tsx\n * <DialogFooter>\n * <Button variant=\"outline\">Cancel</Button>\n * <Button>Save</Button>\n * </DialogFooter>\n * ```\n */\nexport function DialogFooter({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {\n return (\n <div\n className={classNames('flex flex-col-reverse sm:flex-row sm:justify-end sm:gap-x-2', className)}\n {...props}\n />\n );\n}\n\n/**\n * Heading element mapped to the dialog title (announced by screen readers).\n *\n * @remarks\n * Sets `slot=\"title\"` so RAC wires it to the dialog.\n */\nexport function DialogTitle({ className, ...props }: AriaHeadingProps) {\n return (\n <AriaHeading\n slot=\"title\"\n className={classNames('heading-3 font-semibold leading-none tracking-tight', className)}\n {...props}\n />\n );\n}\n\n/**\n * Short explanatory text under the title.\n *\n * @example\n * ```tsx\n * <DialogDescription>\n * This action cannot be undone.\n * </DialogDescription>\n * ```\n */\nexport function DialogDescription({ className, ...props }: React.HTMLAttributes<HTMLParagraphElement>) {\n return <p className={classNames('flex flex-col gap-y-1 text-center sm:text-left', className)} {...props} />;\n}\n\n/**\n * Context type for controlled dialog state and actions.\n */\ntype ControlledDialogContextType = {\n /** Opens the dialog with the provided content */\n openDialog: (content: ReactNode) => void;\n /** Closes the dialog */\n closeDialog: () => void;\n /** Whether the dialog is currently open */\n isOpen: boolean;\n};\n\nconst ControlledDialogContext = createContext<ControlledDialogContextType | null>(null);\n\n/**\n * Provider that manages a scoped dialog controlled via hooks.\n *\n * @example\n * ```tsx\n * <ControlledDialogProvider>\n * <MyComponent />\n * </ControlledDialogProvider>\n *\n * // Inside MyComponent:\n * function MyComponent() {\n * const { openDialog } = useControlledDialog();\n * return (\n * <Button onPress={() => openDialog(<div>Dialog content</div>)}>\n * Open Dialog\n * </Button>\n * );\n * }\n * ```\n */\nexport function ControlledDialogProvider({ children }: { children: ReactNode }) {\n const [isOpen, setIsOpen] = useState(false);\n const [content, setContent] = useState<ReactNode>(null);\n\n const openDialog = (dialogContent: ReactNode) => {\n setContent(dialogContent);\n setIsOpen(true);\n };\n\n const closeDialog = () => {\n setIsOpen(false);\n };\n\n return (\n <ControlledDialogContext.Provider value={{ openDialog, closeDialog, isOpen }}>\n {children}\n <DialogTrigger isOpen={isOpen} onOpenChange={setIsOpen}>\n <DialogOverlay isDismissable>\n <DialogContent>{content}</DialogContent>\n </DialogOverlay>\n </DialogTrigger>\n </ControlledDialogContext.Provider>\n );\n}\n\n/**\n * Hook to access the controlled dialog from within a ControlledDialogProvider.\n *\n * @throws Error if used outside of ControlledDialogProvider\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const { openDialog, closeDialog, isOpen } = useControlledDialog();\n *\n * return (\n * <Button onPress={() => openDialog(\n * <DialogHeader>\n * <DialogTitle>Confirm</DialogTitle>\n * </DialogHeader>\n * )}>\n * Open\n * </Button>\n * );\n * }\n * ```\n */\nexport function useControlledDialog() {\n const context = useContext(ControlledDialogContext);\n if (!context) {\n throw new Error('useControlledDialog must be used within ControlledDialogProvider');\n }\n return context;\n}\n\nexport type ControlledDialogProps<T> = {\n /** Callback to close the dialog */\n close: () => void;\n /** The data passed to the dialog - array of selected rows */\n data: T | T[];\n};\n\n/**\n * Component type that accepts ControlledDialogProps.\n * Use this for components that will be rendered in a controlled dialog.\n */\nexport type ControlledDialogComponent<T> = React.ComponentType<ControlledDialogProps<T>>;\n"],"names":["sheetVariants","cva","DialogTrigger","AriaDialogTrigger","DialogOverlay","className","isDismissable","props","jsx","AriaModalOverlay","composeRenderProps","classNames","DialogContent","children","side","role","closeButton","AriaModal","AriaDialog","renderProps","jsxs","Fragment","Button","IcClose","DialogHeader","DialogFooter","DialogTitle","AriaHeading","DialogDescription","ControlledDialogContext","createContext","ControlledDialogProvider","isOpen","setIsOpen","useState","content","setContent","openDialog","dialogContent","closeDialog","useControlledDialog","context","useContext"],"mappings":"keA0BA,MAAMA,EAAgBC,EAClB,CACI,4DACA,qKAAA,EAEJ,CACI,SAAU,CACN,KAAM,CACF,IAAK,yGACL,OAAQ,kHACR,KAAM,yHACN,MAAO,4HAAA,CACX,CACJ,CAER,EAkBaC,EAAgBC,EAEhBC,EAAgB,CAAC,CAAE,UAAAC,EAAW,cAAAC,EAAgB,GAAM,GAAGC,KAChEC,EAACC,EAAA,CACG,cAAAH,EACA,UAAWI,EAAmBL,EAAWA,GACrCM,EACI,sCAEA,yDAEA,6BACAN,CAAA,C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W,GAAGE,GAAqD,CACnG,OAAOC,EAAC,KAAE,UAAWG,EAAW,iDAAkDN,CAAS,EAAI,GAAGE,EAAO,CAC7G,CAcA,MAAMsB,EAA0BC,EAAkD,IAAI,EAsB/E,SAASC,EAAyB,CAAE,SAAAlB,GAAqC,CAC5E,KAAM,CAACmB,EAAQC,CAAS,EAAIC,EAAS,EAAK,EACpC,CAACC,EAASC,CAAU,EAAIF,EAAoB,IAAI,EAEhDG,EAAcC,GAA6B,CAC7CF,EAAWE,CAAa,EACxBL,EAAU,EAAI,CAClB,EAEMM,EAAc,IAAM,CACtBN,EAAU,EAAK,CACnB,EAEA,OACIb,EAACS,EAAwB,SAAxB,CAAiC,MAAO,CAAE,WAAAQ,EAAY,YAAAE,EAAa,OAAAP,CAAA,EAC/D,SAAA,CAAAnB,EACDL,EAACN,EAAA,CAAc,OAAA8B,EAAgB,aAAcC,EACzC,SAAAzB,EAACJ,EAAA,CAAc,cAAa,GACxB,SAAAI,EAACI,EAAA,CAAe,SAAAuB,CAAA,CAAQ,EAC5B,CAAA,CACJ,CAAA,EACJ,CAER,CAwBO,SAASK,GAAsB,CAClC,MAAMC,EAAUC,EAAWb,CAAuB,EAClD,GAAI,CAACY,EACD,MAAM,IAAI,MAAM,kEAAkE,EAEtF,OAAOA,CACX"}
|
|
1
|
+
{"version":3,"file":"dialog.js","sources":["../../lib/components/dialog.tsx"],"sourcesContent":["'use client';\nimport { cva, type VariantProps } from 'class-variance-authority';\nimport type { ReactNode } from 'react';\nimport { createContext, useContext, useState } from 'react';\nimport {\n Dialog as AriaDialog,\n DialogProps as AriaDialogProps,\n DialogTrigger as AriaDialogTrigger,\n Heading as AriaHeading,\n HeadingProps as AriaHeadingProps,\n Modal as AriaModal,\n ModalOverlay as AriaModalOverlay,\n ModalOverlayProps as AriaModalOverlayProps,\n composeRenderProps,\n} from 'react-aria-components';\n\nimport { Button } from '../components/button';\nimport { classNames } from '../utilities/theme';\nimport { IcClose } from './icons';\n\n/**\n * Visual variants for the sheet-style dialog (slide in from an edge).\n *\n * @remarks\n * Internally used to style `<DialogContent side=\"...\">`.\n */\nconst sheetVariants = cva(\n [\n 'fixed z-50 gap-icon bg-elevation-1 transition ease-in-out',\n 'data-[entering]:duration-200 data-[entering]:animate-in data-[entering]:fade-in-0 data-[exiting]:duration-200 data-[exiting]:animate-out data-[exiting]:fade-out-0',\n ],\n {\n variants: {\n side: {\n top: 'inset-x-0 top-0 border-b data-[entering]:slide-in-from-top data-[exiting]:slide-out-to-top max-h-table',\n bottom: 'inset-x-0 bottom-0 border-t data-[entering]:slide-in-from-bottom data-[exiting]:slide-out-to-bottom max-h-table',\n left: 'inset-y-0 left-0 h-full w-3/4 border-r data-[entering]:slide-in-from-left data-[exiting]:slide-out-to-left sm:max-w-sm',\n right: 'inset-y-0 right-0 h-full w-3/4 border-l data-[entering]:slide-in-from-right data-[exiting]:slide-out-to-right sm:max-w-sm',\n },\n },\n }\n);\n\n/**\n * Opens the dialog when interacted with (click/press).\n *\n * @remarks\n * Compose this around any control that should open the dialog.\n *\n * @example\n * ```tsx\n * <DialogTrigger>\n * <Button>Open</Button>\n * <DialogOverlay>\n * <DialogContent>...</DialogContent>\n * </DialogOverlay>\n * </DialogTrigger>\n * ```\n */\nexport const DialogTrigger = AriaDialogTrigger;\n\nexport const DialogOverlay = ({ className, isDismissable = true, ...props }: AriaModalOverlayProps) => (\n <AriaModalOverlay\n isDismissable={isDismissable}\n className={composeRenderProps(className, className =>\n classNames(\n 'fixed inset-0 z-50 bg-background/80',\n /* Exiting */\n 'data-[exiting]:duration-100 data-[exiting]:animate-out',\n /* Entering */\n 'data-[entering]:animate-in',\n className\n )\n )}\n {...props}\n />\n);\n\n/** Props for {@link DialogContent}. */\nexport interface DialogContentProps\n extends Omit<React.ComponentProps<typeof AriaModal>, 'children'>,\n VariantProps<typeof sheetVariants> {\n /**\n * Render function or nodes for the dialog panel contents.\n */\n children?: AriaDialogProps['children'];\n\n /**\n * ARIA role of the dialog.\n *\n * Use `\"alertdialog\"` for destructive/confirmation flows that require\n * explicit acknowledgement.\n * @defaultValue \"dialog\"\n */\n role?: AriaDialogProps['role'];\n\n /**\n * Show a built-in close button in the top-right corner.\n * @defaultValue true\n */\n closeButton?: boolean;\n}\n\n/**\n * Dialog panel container. Renders either a centered modal or a sheet\n * from an edge when `side` is provided.\n *\n * @example Basic\n * ```tsx\n * <DialogTrigger>\n * <Button>Open</Button>\n * <DialogOverlay>\n * <DialogContent>\n * <DialogHeader>\n * <DialogTitle>Sign up</DialogTitle>\n * </DialogHeader>\n * ...\n * </DialogContent>\n * </DialogOverlay>\n * </DialogTrigger>\n * ```\n */\nexport function DialogContent({ className, children, side, role, closeButton = true, ...props }: DialogContentProps) {\n return (\n <AriaModal\n className={composeRenderProps(className, className =>\n classNames(\n side\n ? sheetVariants({ side, className: 'h-full p-6' })\n : [\n 'fixed left-[50vw] top-1/2 z-50 w-full max-w-lg -translate-x-1/2 -translate-y-1/2 border bg-elevation-1 p-icon duration-100 data-[exiting]:duration-100 data-[entering]:animate-in data-[exiting]:animate-out data-[entering]:fade-in-0 data-[exiting]:fade-out-0 data-[entering]:zoom-in-95 data-[exiting]:zoom-out-95 md:w-full',\n ],\n className\n )\n )}\n {...props}\n >\n <AriaDialog\n role={role}\n className={classNames(!side && 'grid h-full gap-icon relative', 'h-full outline-none')}\n >\n {composeRenderProps(children, (children, renderProps) => (\n <>\n {children}\n {closeButton && (\n <div className=\"absolute right-2 top-1\">\n <Button\n size={'icon'}\n variant={'neutral'}\n onPress={renderProps.close}\n className=\"rounded-full\"\n >\n <IcClose />\n <span className=\"sr-only\">Close</span>\n </Button>\n </div>\n )}\n </>\n ))}\n </AriaDialog>\n </AriaModal>\n );\n}\n\n/**\n * Header region for the dialog panel.\n *\n * @example\n * ```tsx\n * <DialogHeader>\n * <DialogTitle>Settings</DialogTitle>\n * </DialogHeader>\n * ```\n */\nexport function DialogHeader({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {\n return <div className={classNames('flex flex-col gap-y-2 text-center sm:text-left', className)} {...props} />;\n}\n\n/**\n * Footer region that aligns action buttons.\n *\n * @example\n * ```tsx\n * <DialogFooter>\n * <Button variant=\"outline\">Cancel</Button>\n * <Button>Save</Button>\n * </DialogFooter>\n * ```\n */\nexport function DialogFooter({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {\n return (\n <div\n className={classNames('flex flex-col-reverse sm:flex-row sm:justify-end sm:gap-x-2', className)}\n {...props}\n />\n );\n}\n\n/**\n * Heading element mapped to the dialog title (announced by screen readers).\n *\n * @remarks\n * Sets `slot=\"title\"` so RAC wires it to the dialog.\n */\nexport function DialogTitle({ className, ...props }: AriaHeadingProps) {\n return (\n <AriaHeading\n slot=\"title\"\n className={classNames('heading-3 font-semibold leading-none tracking-tight', className)}\n {...props}\n />\n );\n}\n\n/**\n * Short explanatory text under the title.\n *\n * @example\n * ```tsx\n * <DialogDescription>\n * This action cannot be undone.\n * </DialogDescription>\n * ```\n */\nexport function DialogDescription({ className, ...props }: React.HTMLAttributes<HTMLParagraphElement>) {\n return <p className={classNames('flex flex-col gap-y-1 text-center sm:text-left', className)} {...props} />;\n}\n\n/**\n * Context type for controlled dialog state and actions.\n */\ntype ControlledDialogContextType = {\n /** Opens the dialog with the provided content */\n openDialog: (content: ReactNode) => void;\n /** Closes the dialog */\n closeDialog: () => void;\n /** Whether the dialog is currently open */\n isOpen: boolean;\n};\n\nconst ControlledDialogContext = createContext<ControlledDialogContextType | null>(null);\n\n/**\n * Provider that manages a scoped dialog controlled via hooks.\n *\n * @example\n * ```tsx\n * <ControlledDialogProvider>\n * <MyComponent />\n * </ControlledDialogProvider>\n *\n * // Inside MyComponent:\n * function MyComponent() {\n * const { openDialog } = useControlledDialog();\n * return (\n * <Button onPress={() => openDialog(<div>Dialog content</div>)}>\n * Open Dialog\n * </Button>\n * );\n * }\n * ```\n */\nexport function ControlledDialogProvider({ children }: { children: ReactNode }) {\n const [isOpen, setIsOpen] = useState(false);\n const [content, setContent] = useState<ReactNode>(null);\n\n const openDialog = (dialogContent: ReactNode) => {\n setContent(dialogContent);\n setIsOpen(true);\n };\n\n const closeDialog = () => {\n setIsOpen(false);\n };\n\n return (\n <ControlledDialogContext.Provider value={{ openDialog, closeDialog, isOpen }}>\n {children}\n <DialogTrigger isOpen={isOpen} onOpenChange={setIsOpen}>\n <DialogOverlay isDismissable>\n <DialogContent>{content}</DialogContent>\n </DialogOverlay>\n </DialogTrigger>\n </ControlledDialogContext.Provider>\n );\n}\n\n/**\n * Hook to access the controlled dialog from within a ControlledDialogProvider.\n *\n * @throws Error if used outside of ControlledDialogProvider\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const { openDialog, closeDialog, isOpen } = useControlledDialog();\n *\n * return (\n * <Button onPress={() => openDialog(\n * <DialogHeader>\n * <DialogTitle>Confirm</DialogTitle>\n * </DialogHeader>\n * )}>\n * Open\n * </Button>\n * );\n * }\n * ```\n */\nexport function useControlledDialog() {\n const context = useContext(ControlledDialogContext);\n if (!context) {\n throw new Error('useControlledDialog must be used within ControlledDialogProvider');\n }\n return context;\n}\n"],"names":["sheetVariants","cva","DialogTrigger","AriaDialogTrigger","DialogOverlay","className","isDismissable","props","jsx","AriaModalOverlay","composeRenderProps","classNames","DialogContent","children","side","role","closeButton","AriaModal","AriaDialog","renderProps","jsxs","Fragment","Button","IcClose","DialogHeader","DialogFooter","DialogTitle","AriaHeading","DialogDescription","ControlledDialogContext","createContext","ControlledDialogProvider","isOpen","setIsOpen","useState","content","setContent","openDialog","dialogContent","closeDialog","useControlledDialog","context","useContext"],"mappings":"keA0BA,MAAMA,EAAgBC,EAClB,CACI,4DACA,qKAAA,EAEJ,CACI,SAAU,CACN,KAAM,CACF,IAAK,yGACL,OAAQ,kHACR,KAAM,yHACN,MAAO,4HAAA,CACX,CACJ,CAER,EAkBaC,EAAgBC,EAEhBC,EAAgB,CAAC,CAAE,UAAAC,EAAW,cAAAC,EAAgB,GAAM,GAAGC,KAChEC,EAACC,EAAA,CACG,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