@cryptlex/web-components 6.6.6-alpha54 → 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.
- package/dist/components/button.d.ts +1 -1
- package/dist/components/data-table-filter.js +1 -1
- package/dist/components/data-table.d.ts +45 -4
- package/dist/components/data-table.js +1 -1
- package/dist/components/data-table.js.map +1 -1
- package/dist/components/dialog.d.ts +58 -0
- package/dist/components/dialog.js +1 -1
- package/dist/components/dialog.js.map +1 -1
- package/dist/components/id-search.d.ts +5 -3
- package/dist/components/id-search.js +1 -1
- package/dist/components/id-search.js.map +1 -1
- package/dist/components/multi-select.js.map +1 -1
- package/dist/utilities/empty-option.d.ts +3 -0
- package/dist/utilities/empty-option.js +2 -0
- package/dist/utilities/empty-option.js.map +1 -0
- package/dist/utilities/string.d.ts +0 -5
- package/dist/utilities/string.js +1 -1
- package/dist/utilities/string.js.map +1 -1
- package/lib/index.css +2 -2
- package/package.json +1 -1
- package/dist/components/data-table-actions.d.ts +0 -46
- package/dist/components/data-table-actions.js +0 -2
- package/dist/components/data-table-actions.js.map +0 -1
- package/dist/components/dialog-action-utils.d.ts +0 -38
- package/dist/components/dialog-action-utils.js +0 -2
- package/dist/components/dialog-action-utils.js.map +0 -1
- package/dist/components/dialog-menu.d.ts +0 -34
- package/dist/components/dialog-menu.js +0 -2
- package/dist/components/dialog-menu.js.map +0 -1
|
@@ -2,7 +2,7 @@ import { VariantProps } from 'class-variance-authority';
|
|
|
2
2
|
import { ButtonProps as AriaButtonProps } from 'react-aria-components';
|
|
3
3
|
export declare const buttonVariants: (props?: ({
|
|
4
4
|
variant?: "link" | "primary" | "secondary" | "destructive" | "neutral" | "ghost" | null | undefined;
|
|
5
|
-
size?: "
|
|
5
|
+
size?: "none" | "default" | "icon" | null | undefined;
|
|
6
6
|
} & import('class-variance-authority/types').ClassProp) | undefined) => string;
|
|
7
7
|
export type ButtonProps = AriaButtonProps & VariantProps<typeof buttonVariants> & {
|
|
8
8
|
ref?: React.Ref<HTMLButtonElement>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"react/jsx-runtime";import"react";import"./button.js";import{C as
|
|
1
|
+
import"react/jsx-runtime";import"react";import"./button.js";import{C as X,D as Y,F as Z}from"./data-table.js";import"./date-picker.js";import"./menu.js";import"./popover.js";import"../utilities/form-hook.js";import"../utilities/resources.js";import"../utilities/theme.js";import"./icons.js";import"./id-search.js";import"class-variance-authority";import"react-aria-components";import"./loader.js";import"clsx";import"@dnd-kit/core";import"@dnd-kit/sortable";import"@dnd-kit/utilities";import"@tanstack/react-query";import"@tanstack/react-table";import"@uidotdev/usehooks";import"lodash-es";import"./badge.js";import"./searchfield.js";import"./form.js";import"./table.js";import"../utilities/countries.js";import"./select-options.js";import"../utilities/date.js";import"../utilities/numbers.js";import"zod";import"../utilities/duration.js";import"./checkbox.js";import"../utilities/form-context.js";import"@tanstack/react-form";import"../utilities/ctx-client.js";import"./dialog.js";import"@internationalized/date";import"./calendar.js";import"./datefield.js";import"../utilities/form.js";import"./list-box.js";import"./select.js";import"./multi-select.js";import"./numberfield.js";import"./textfield.js";import"../utilities/string.js";import"../utilities/empty-option.js";export{X as COMPARISON_OPERATOR_LABELS,Y as DataTableFilter,Z as FILTER_COMPARISON_OPERATORS};
|
|
2
2
|
//# sourceMappingURL=data-table-filter.js.map
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { operations } from '@cryptlex/web-api-types/develop';
|
|
2
2
|
import { ColumnDef, PaginationState, RowData, SortingState, ColumnHelper } from '@tanstack/react-table';
|
|
3
|
+
import { Button } from '../components/button';
|
|
3
4
|
import { FiltersConfig, TableFilter } from '../components/data-table-filter';
|
|
4
|
-
import { DialogMenuAction } from '../components/dialog-menu';
|
|
5
5
|
import { ApiPathParameters, ApiResponseBody } from '../utilities/resources';
|
|
6
|
-
import {
|
|
6
|
+
import { CtxIcon } from './icons';
|
|
7
7
|
import { ClientPathsWithMethod } from 'openapi-fetch';
|
|
8
|
+
import { PressEvent } from 'react-aria-components';
|
|
8
9
|
import { CtxClientType } from '../utilities/ctx-client';
|
|
9
10
|
export type DisplayType = 'string' | 'boolean' | 'date' | 'number' | 'enum' | 'badge' | 'country' | 'fileSize' | 'days';
|
|
10
11
|
declare module '@tanstack/react-table' {
|
|
@@ -21,7 +22,6 @@ type DataTableFactory<T extends object, TOperation extends keyof operations> = {
|
|
|
21
22
|
allowSelection?: boolean;
|
|
22
23
|
filterConfig: FiltersConfig<TOperation>;
|
|
23
24
|
initialFilters: TableFilter[];
|
|
24
|
-
rowActions?: DialogMenuAction<T>[];
|
|
25
25
|
};
|
|
26
26
|
type DataTableState = {
|
|
27
27
|
sorting: SortingState;
|
|
@@ -31,7 +31,7 @@ export declare function getColumnHelper<O extends keyof operations>(): ColumnHel
|
|
|
31
31
|
/**
|
|
32
32
|
* Hook for handling all data-table state. Used in DataTableContext
|
|
33
33
|
*/
|
|
34
|
-
export declare function useDataTableState<T extends object, TOperation extends keyof operations>({ path, pathParameters, columns, filterConfig, columnsToHideByDefault, allowSelection, initialFilters, tableActions,
|
|
34
|
+
export declare function useDataTableState<T extends object, TOperation extends keyof operations>({ path, pathParameters, columns, filterConfig, columnsToHideByDefault, allowSelection, initialFilters, tableActions, }: DataTableFactory<T, TOperation>): {
|
|
35
35
|
readonly tableState: DataTableState;
|
|
36
36
|
readonly updateTableState: (updates: Partial<DataTableState>) => void;
|
|
37
37
|
readonly query: import('@tanstack/react-query').UseQueryResult<{
|
|
@@ -96,4 +96,45 @@ export declare function DataTableProvider<T extends object, TOperation extends k
|
|
|
96
96
|
} & ReturnType<typeof useDataTableState<T, TOperation>>): import("react/jsx-runtime").JSX.Element;
|
|
97
97
|
export type DataTableProps = React.ComponentProps<'section'>;
|
|
98
98
|
export declare function DataTable({ className, ...props }: DataTableProps): import("react/jsx-runtime").JSX.Element;
|
|
99
|
+
/** Base properties shared by all table actions */
|
|
100
|
+
type ActionBase = {
|
|
101
|
+
label: string;
|
|
102
|
+
icon: CtxIcon;
|
|
103
|
+
tooltip?: string;
|
|
104
|
+
/** Optional button variant to pass through to Button (defaults to neutral) */
|
|
105
|
+
variant?: React.ComponentProps<typeof Button>['variant'];
|
|
106
|
+
};
|
|
107
|
+
/** Context provided to onPress functions in TableActions */
|
|
108
|
+
type ActionPressContext = {
|
|
109
|
+
event?: PressEvent;
|
|
110
|
+
openDialog: (c: React.ReactNode) => void;
|
|
111
|
+
closeDialog: () => void;
|
|
112
|
+
};
|
|
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;
|
|
131
|
+
};
|
|
132
|
+
/** Common table action type that works for both action and dialog types */
|
|
133
|
+
export type TableAction<T> = NoResourceAction | SingleResourceAction<T> | BulkResourceAction<T>;
|
|
134
|
+
export type TableActionsProps<T> = {
|
|
135
|
+
/** Array of table actions to render */
|
|
136
|
+
readonly items: (NoResourceAction | BulkResourceAction<T>)[];
|
|
137
|
+
/** Whether the table is currently fetching data */
|
|
138
|
+
readonly isFetching?: boolean;
|
|
139
|
+
};
|
|
99
140
|
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{jsx as e,Fragment as w,jsxs as s}from"react/jsx-runtime";import{createContext as le,useState as T,useMemo as se,useEffect as ce,useContext as ue,useRef as de}from"react";import{Button as y}from"./button.js";import{useSensors as me,useSensor as V,PointerSensor as ge,KeyboardSensor as pe,DndContext as fe,closestCenter as he,DragOverlay as be}from"@dnd-kit/core";import{sortableKeyboardCoordinates as Se,SortableContext as ye,verticalListSortingStrategy as ve,arrayMove as Ce,useSortable as we}from"@dnd-kit/sortable";import{CSS as xe}from"@dnd-kit/utilities";import{useQuery as Ne}from"@tanstack/react-query";import{createColumnHelper as X,useReactTable as Ie,getCoreRowModel as Te,flexRender as z}from"@tanstack/react-table";import{useLocalStorage as H}from"@uidotdev/usehooks";import{merge as Fe}from"lodash-es";import{Badge as Ae}from"./badge.js";import{TfDatePicker as Pe}from"./date-picker.js";import{EasyMenu as M,MenuItem as P}from"./menu.js";import{PopoverTrigger as De,Popover as Re}from"./popover.js";import{useAppForm as ze}from"../utilities/form-hook.js";import{useResourceFormatter as _}from"../utilities/resources.js";import{classNames as S}from"../utilities/theme.js";import{IcInfo as Oe,IcMoreVertical as Me,IcRefresh as _e,IcColumns as Le,IcGrip as je,IcFirst as Ee,IcLeft as $e,IcRight as qe,IcLast as Ve,IcSortAsc as He,IcSortDesc as ke,IcSortNone as Ue,IcFilter as Be,IcRemove as k,IcCheck as U,IcMinus as Ke,IcAccount as Qe,IcLicense as Ge,IcDate as Xe,IcFile as Ze}from"./icons.js";import{TfMultipleIdSearchInput as Je}from"./id-search.js";import{DialogMenu as We}from"./dialog-menu.js";import{Loader as Ye}from"./loader.js";import{SearchField as et}from"./searchfield.js";import{Table as tt,TableHeader as nt,TableRow as B,TableHead as rt,TableBody as at,TableCell as ot}from"./table.js";import{CountryName as it}from"../utilities/countries.js";import{formatDate as lt}from"../utilities/date.js";import{formatDays as st,formatFilesize as ct,formatNumber as ut}from"../utilities/numbers.js";import{Checkbox as K}from"./checkbox.js";import{TableActions as dt}from"./data-table-actions.js";import{useCtxClient as mt}from"../utilities/ctx-client.js";import"class-variance-authority";import"react-aria-components";import"@internationalized/date";import"./calendar.js";import"./form.js";import"./datefield.js";import"../utilities/form.js";import"../utilities/form-context.js";import"@tanstack/react-form";import"./list-box.js";import"./select.js";import"./multi-select.js";import"./numberfield.js";import"./textfield.js";import"../utilities/string.js";import"clsx";import"./dialog-action-utils.js";import"./dialog.js";import"./select-options.js";import"zod";import"../utilities/duration.js";function gt(t){return t?t.desc?`-${t.id}`:`+${t.id}`:"-createdAt"}const Z=X(),pt=[Z.accessor("checkbox",{header:({table:t})=>e(K,{isIndeterminate:t.getIsSomeRowsSelected()&&!t.getIsAllPageRowsSelected(),isSelected:t.getIsAllPageRowsSelected()||t.getIsSomePageRowsSelected(),onChange:()=>t.toggleAllPageRowsSelected(),"aria-label":"Select all"}),cell:({row:t})=>e(K,{isSelected:t.getIsSelected(),onChange:()=>t.toggleSelected(),"aria-label":"Select row"}),enableSorting:!1,enableHiding:!1})],C="TableActions",ft=t=>t.length===0?[]:[Z.accessor(C,{header:"Actions",id:C,enableHiding:!1,cell:({row:n})=>e(We,{label:e(Me,{}),data:n.original,items:t}),enableSorting:!1})];function xn(){return X()}function Nn({path:t,pathParameters:n,columns:r,filterConfig:i,columnsToHideByDefault:o={},allowSelection:p=!1,initialFilters:c=[],tableActions:u,rowActions:h}){const[d,v]=T({pagination:{pageIndex:0,pageSize:20},sorting:[]}),{sorting:m,pagination:l}=d,[f,g]=T(""),[b,L]=T({}),[F,ee]=T(c),te=se(()=>F.map(a=>Array.isArray(a.value)?{[a.property]:{[a.operator]:a.value.join(",")}}:{[a.property]:{[a.operator]:a.value}}).reduce((a,I)=>Fe(a,I),{}),[F]),ne={...F,page:l.pageIndex+1,limit:l.pageSize,sort:gt(m[0]),search:f},re=mt(),D=["get",t],[j,E]=H(`${D.join("")}_ctx_column_order_preference`,[]),[$,ae]=H(`${D.join("")}_ctx_column_visibility_preference`,{id:!1,...o}),R=a=>{v(I=>({...I,...a}))},A=Ne({queryKey:D,queryFn:async()=>{const a=await re.GET(t,{params:{query:ne,path:n}});return{data:a.data??[],total:Number.parseInt(a.response.headers.get("Pagination-Count")||"0")}}}),oe=[...p?pt:[],...r,...ft(h??[])];function ie(a){return typeof a=="function"}function N(a,I){return ie(a)?a(I):a}const q=Ie({data:A.data?.data??[],columns:oe,getCoreRowModel:Te(),rowCount:A.data?.total??0,manualPagination:!0,onPaginationChange:a=>{R({pagination:N(a,l)})},manualSorting:!0,onSortingChange:a=>{L({}),R({sorting:[...N(a,m)]})},manualFiltering:!0,onColumnVisibilityChange:a=>{ae(N(a,$))},onRowSelectionChange:a=>{L(N(a,b))},onColumnOrderChange:a=>{E(N(a,j))},state:{sorting:m,columnVisibility:$,pagination:l,rowSelection:b,columnOrder:j},meta:{refetch:A.refetch}});return ce(()=>{E([...q.getAllLeafColumns().map(a=>a.id)])},[]),{tableState:d,updateTableState:R,query:A,setSearchQuery:g,searchQuery:f,tanTable:q,mergedFilters:te,filters:F,setFilters:ee,filterConfig:i,tableActions:u}}const J=le(null);function x(){const t=ue(J);if(!t)throw Error("DataTable should be used within DataTableProvider.");return t}function In({children:t,...n}){return e(J.Provider,{value:n,children:t})}function Tn({className:t,...n}){const{query:r,tanTable:i}=x();return e(w,{children:s("section",{...n,className:S("flex flex-col bg-elevation-1",t),children:[e(yt,{}),s("div",{className:"w-full overflow-auto border-x h-table relative",tabIndex:0,children:[r.isLoading&&e(Q,{className:"cursor-wait",children:e(Ye,{})}),!r.isLoading&&i.getRowModel().rows.length===0&&e(Q,{className:"cursor-not-allowed",children:!r.isFetching&&(r.isError?s("span",{className:"flex gap-3 justify-center items-center",children:[e(Oe,{}),e("span",{children:r.error.message})]}):r.data?.data?.length===0?e(w,{children:"No results found."}):e(w,{children:"Unknown error. Please contact customer support."}))}),!r.isLoading&&i.getRowModel().rows.length!==0&&e(Ct,{className:"w-full"})]}),s("div",{className:"flex w-full justify-between border gap-icon p-icon overflow-x-auto",children:[s("div",{className:"flex gap-icon",children:[e(ht,{}),e(St,{})]}),e(bt,{})]})]})})}function Q({children:t,className:n}){return s(w,{children:[e("span",{className:S(n,"absolute top-0 bg-elevation-1 text-foreground z-20 size-full body-sm flex items-center justify-center"),children:t}),e("span",{className:"relative h-full w-0 block"})]})}function ht(){const{tanTable:t}=x(),[n,r]=T(null),i=_(),o=me(V(ge),V(pe,{coordinateGetter:Se}));return e(fe,{sensors:o,collisionDetection:he,onDragStart:c=>{const{active:u}=c;r(u.id.toString())},onDragEnd:c=>{const{active:u,over:h}=c;if(h&&u.id!==h.id){const d=t.getState().columnOrder,v=d.indexOf(u.id.toString()),m=d.indexOf(h.id.toString());t.setColumnOrder([...Ce(d,v,m)])}r(null)},children:s(ye,{items:t.getState().columnOrder,strategy:ve,children:[s(M,{label:s(w,{children:[e(Le,{className:"inline align-bottom me-1"}),"Columns"]}),selectionMode:"multiple",items:t.getAllFlatColumns(),selectedKeys:t.getVisibleFlatColumns().map(c=>c.id),children:[e(P,{onAction:()=>t.toggleAllColumnsVisible(),className:"italic",children:"(select all)"}),t.getState().columnOrder.map(c=>{const u=t.getAllFlatColumns().find(h=>h.id===c);return!u||u.id==="checkbox"||u.id===C?null:e(p,{column:u},u.id)})]}),e(be,{children:n?e("div",{className:"opacity-70 border-2 border-primary",children:i(n)}):null})]})});function p({column:c}){const{attributes:u,listeners:h,setNodeRef:d,transform:v,transition:m}=we({id:c.id}),l={transform:xe.Transform.toString(v),transition:m,zIndex:"999"};return s(P,{ref:d,style:l,...u,id:c.id,onAction:()=>c.toggleVisibility(),isDisabled:!c.getCanHide(),className:"flex items-center",children:[e(je,{...h,className:"size-icon cursor-grab"}),O(c),c.getIsSorted()&&e(W,{className:"size-icon",direction:c.getIsSorted()})]})}}function bt(){const{tanTable:t}=x(),n=t.getRowCount();return s("div",{className:"flex items-center gap-2",children:[e("span",{className:"whitespace-nowrap body-sm text-muted",children:`${t.getState().pagination.pageIndex*t.getState().pagination.pageSize+1} - ${Math.min((t.getState().pagination.pageIndex+1)*t.getState().pagination.pageSize,n)} of ${n?.toLocaleString()}`}),e(y,{"aria-label":"First page",onPress:()=>t.firstPage(),isDisabled:!t.getCanPreviousPage(),variant:"neutral",size:"icon",children:e(Ee,{})}),e(y,{"aria-label":"Previous page",onPress:()=>t.previousPage(),isDisabled:!t.getCanPreviousPage(),variant:"neutral",size:"icon",children:e($e,{})}),e(y,{"aria-label":"Next page",onPress:()=>t.nextPage(),isDisabled:!t.getCanNextPage(),variant:"neutral",size:"icon",children:e(qe,{})}),e(y,{"aria-label":"Last page",onClick:()=>t.lastPage(),isDisabled:!t.getCanNextPage(),variant:"neutral",size:"icon",children:e(Ve,{})})]})}function St(){const{tanTable:t}=x(),n=[10,20,30,40,50];return e(M,{label:t.getState().pagination.pageSize.toString(),selectionMode:"single",selectedKeys:[t.getState().pagination.pageSize.toString()],items:n.map(r=>({id:r.toString(),value:r})),children:r=>e(P,{onAction:()=>t.setPageSize(r.value),children:r.value})})}function yt(){const{query:t,tanTable:n,searchQuery:r,setSearchQuery:i,tableActions:o}=x(),p=n.getSelectedRowModel().rows.length>0,c=n.getSelectedRowModel().rows.map(h=>h.original),u=o.filter(h=>h.bulk===p);return s("section",{className:"flex bg-elevation-1 justify-between my-0 p-icon border gap-icon overflow-auto",children:[s("div",{className:"flex gap-icon",children:[e(y,{"aria-label":"Refresh",isPending:t.isFetching,onClick:()=>t.refetch(),variant:"neutral",size:"icon",children:e(_e,{})}),e(dt,{items:u,rowsSelected:c,isFetching:t.isFetching})]}),s("div",{className:"flex gap-icon",children:[e(Nt,{}),e(et,{value:r,onChange:i})]})]})}function W({direction:t,...n}){return t==="asc"?e(He,{className:"size-3.5",...n}):t==="desc"?e(ke,{className:"size-3.5",...n}):e(Ue,{className:"size-3.5",...n})}function O(t){const n=_(),r=t.columnDef.header;return typeof r=="string"?r:n(t.id)}function vt(t){const n=t.column.columnDef.meta?.displayType,r=t.getValue();if(r==null)return null;switch(n){case"date":return lt(r);case"number":return ut(r);case"boolean":case"badge":return e(Ae,{className:"uppercase w-full",children:String(r)});case"country":return e(it,{value:r});case"enum":return e("span",{className:"uppercase w-full",children:String(r)});case"fileSize":return ct(r);case"days":return st(r);default:return String(r)}}function G({header:t}){const n=t.column.columnDef.header;return typeof n=="string"||!n?O(t.column):typeof n=="function"?typeof n(t.getContext())=="string"?O(t.column):z(n,t.getContext()):z(n,t.getContext())}function Ct({className:t}){const{tanTable:n}=x(),r=(i,o,p="z-50")=>S("px-icon py-2 text-left body-sm font-medium whitespace-nowrap",i&&`bg-elevation-1 sticky right-0 ${p} text-center justify-center`,o);return s(tt,{className:S("table-auto",t),children:[e(nt,{className:"sticky top-0 z-10",children:n.getHeaderGroups().map(i=>e(B,{children:i.headers.map(o=>s(rt,{scope:"col",colSpan:o.colSpan,className:r(o.id===C,"bg-elevation-1"),children:[!o.column.getCanSort()&&!o.isPlaceholder&&e("div",{className:S("w-full py-1 inline-flex items-center gap-1 body-sm",o.id===C?"justify-center":"justify-start"),children:e(G,{header:o})}),o.column.getCanSort()&&s(y,{variant:"ghost",className:S("w-full p-1",o.id===C?"justify-center":"justify-start"),onPress:o.column.getToggleSortingHandler(),children:[e("span",{children:e(G,{header:o})}),e(W,{direction:o.column.getIsSorted()})]})]},o.id))},i.id))}),e(at,{children:n.getRowModel().rows.map(i=>e(B,{className:S("transition-colors data-[selected=true]:bg-primary/10 hover:bg-muted-foreground/20"),"data-selected":i.getIsSelected(),children:i.getVisibleCells().map(o=>{const p=o.column.id===C,c=o.column.columnDef.meta?.displayType?vt(o):z(o.column.columnDef.cell,o.getContext());return e(ot,{className:S(r(p,void 0,"z-1"),p&&"flex justify-center items-center"),children:c},o.id)})},i.id))})]})}const Fn=["eq","ne","cn","nc","sw","ew","in","nin","gt","gte","lt","lte"],wt={eq:"equal to",ne:"not equal to",cn:"contains",nc:"does not contain",sw:"starts with",ew:"ends with",in:"includes",nin:"does not include",gt:"greater than",gte:"greater than or equal to",lt:"less than",lte:"less than or equal to"};function xt(t,n){const r=`${n}-${Date.now()}`,i=Y[t][0];switch(t){case"bool":return{id:r,type:t,property:n,operator:i,value:!0};case"string":return{id:r,type:t,property:n,operator:i,value:""};case"date":return{id:r,type:t,property:n,operator:i,value:new Date().toISOString()};case"id":return{id:r,type:t,property:n,operator:i,value:""};case"id-search":return{id:r,type:t,property:n,operator:i,value:[]};case"enum":return{id:r,type:t,property:n,operator:i,value:new Set};case"number":return{id:r,type:t,property:n,operator:i,value:0}}}const Y={bool:["eq"],enum:["in","nin"],id:["in","nin"],"id-search":["in","nin"],string:["eq","ne","cn","nc","sw","ew","in","nin"],date:["lt","gt"],number:["eq","ne","gt","gte","lt","lte"]};function Nt({className:t,...n}){const{filters:r,query:i,setFilters:o,filterConfig:p}=x(),c=de(null),u=_(),d=ze({defaultValues:{filters:r},onSubmit:({value:m})=>{o(m.filters)}}),v=Object.keys(p).sort();return e("section",{...n,className:S("flex gap-icon items-center",t),children:s(De,{onOpenChange:m=>{m?c.current?.focus():d.handleSubmit()},children:[s("div",{className:"relative",children:[r.length>0&&e("div",{className:"size-2 rounded-full absolute bg-primary/90 z-20 top-0 right-0 translate-x-0.5 -translate-y-0.5"}),e(y,{"aria-label":"Filter",isDisabled:i.isPending||v.length===0,type:"button",size:"icon",variant:"neutral",children:e(Be,{})})]}),e(Re,{className:"w-full p-icon",children:e("form",{onSubmit:m=>{m.preventDefault()},className:"flex flex-col gap-icon max-h-table overflow-auto ",children:e(d.Field,{mode:"array",name:"filters",children:m=>s(w,{children:[m.state.value.map((l,f)=>s("div",{className:"flex gap-icon items-center justify-normal",children:[e("span",{className:"body-sm",children:u(l.property)}),e(d.AppField,{name:`filters[${f}].operator`,children:g=>e(g.TfSingleSelect,{items:Y[l.type].map(b=>({id:b,label:e(w,{children:wt[b]})}))})},l.id),l.type==="bool"&&e(d.AppField,{name:`filters[${f}].value`,children:g=>e(g.TfCheckbox,{autoFocus:!0})}),l.type==="date"&&e(d.AppField,{name:`filters[${f}].value`,children:g=>e(Pe,{autoFocus:!0})}),l.type==="id"&&e(d.AppField,{name:`filters[${f}].value`,children:g=>e(g.TfTextField,{autoFocus:!0})}),l.type==="string"&&e(d.AppField,{name:`filters[${f}].value`,children:g=>e(g.TfTextField,{autoFocus:!0})}),l.type==="number"&&e(d.AppField,{name:`filters[${f}].value`,children:g=>e(g.TfNumberField,{autoFocus:!0})}),l.type==="enum"&&e(d.AppField,{name:`filters[${f}].value`,children:g=>{const b=p[l.property];return b.type!=="enum"?null:e(g.TfMultiSelect,{items:b.options})}}),l.type==="id-search"&&e(d.AppField,{name:`filters[${f}].value`,children:g=>{const b=p[l.property];return b.type!=="id-search"?null:e(Je,{path:b.path,accessor:b.accessor})}}),e(y,{type:"button",variant:"neutral",size:"icon",onPress:()=>m.removeValue(f),children:e(k,{})})]},l.id)),s("div",{className:"flex w-full items-center justify-end gap-2 not-first:mt-icon",children:[e(M,{label:"Add filter",autoFocus:!0,children:v.sort().map(l=>{const f=p[l].type,g=It[f];return s(P,{onAction:()=>{const b=xt(f,l);m.pushValue(b)},children:[u(l),e(g,{})]},l)})}),m.state.value.length>0?s(y,{type:"button",variant:"neutral",onPress:()=>{m.setValue([])},children:[e(k,{}),"Reset"]}):null]})]})})})})]})})}const It={"id-search":Ze,bool:U,date:Xe,enum:Ge,id:Qe,number:Ke,string:U};export{wt as C,Nt as D,Tn as DataTable,J as DataTableContext,In as DataTableProvider,Fn as F,xn as getColumnHelper,x as useDataTable,Nn as useDataTableState};
|
|
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 { DialogMenu, type DialogMenuAction } from '../components/dialog-menu';\nimport { Loader } from '../components/loader';\nimport { EasyMenu, MenuItem } from '../components/menu';\nimport { SearchField } from '../components/searchfield';\nimport { TableBody, TableCell, Table as TableComponent, TableHead, TableHeader, TableRow } from '../components/table';\nimport { CountryName } from '../utilities/countries';\nimport { formatDate } from '../utilities/date';\nimport { formatDays, formatFilesize, formatNumber } from '../utilities/numbers';\nimport { type ApiPathParameters, type ApiResponseBody, useResourceFormatter } from '../utilities/resources';\nimport { classNames } from '../utilities/theme';\nimport { Checkbox } from './checkbox';\nimport { type TableAction, TableActions } from './data-table-actions';\nimport {\n IcColumns,\n IcFirst,\n IcGrip,\n IcInfo,\n IcLast,\n IcLeft,\n IcMoreVertical,\n IcRefresh,\n IcRight,\n IcSortAsc,\n IcSortDesc,\n IcSortNone,\n} from './icons';\n\nimport type { Cell, ColumnHelper } from '@tanstack/react-table';\nimport type { ClientPathsWithMethod } from 'openapi-fetch';\nimport { type CtxClientType, useCtxClient } from '../utilities/ctx-client';\nexport type DisplayType = 'string' | 'boolean' | 'date' | 'number' | 'enum' | 'badge' | 'country' | 'fileSize' | 'days';\n\ndeclare module '@tanstack/react-table' {\n interface ColumnMeta<TData extends RowData, TValue> {\n displayType: DisplayType;\n }\n}\n\nfunction generateSortParam(sort: { id: string; desc: boolean } | undefined): string {\n if (sort) {\n if (sort.desc) {\n return `-${sort.id}`;\n } else {\n return `+${sort.id}`;\n }\n } else {\n return '-createdAt';\n }\n}\n\nconst cH = createColumnHelper<any>();\nconst TABLE_CHECK_BOX_COLUMN = [\n cH.accessor('checkbox', {\n header: ({ table }) => (\n <Checkbox\n isIndeterminate={table.getIsSomeRowsSelected() && !table.getIsAllPageRowsSelected()}\n isSelected={table.getIsAllPageRowsSelected() || table.getIsSomePageRowsSelected()}\n onChange={() => table.toggleAllPageRowsSelected()}\n aria-label=\"Select all\"\n />\n ),\n\n cell: ({ row }) => (\n <Checkbox isSelected={row.getIsSelected()} onChange={() => row.toggleSelected()} aria-label=\"Select row\" />\n ),\n enableSorting: false,\n enableHiding: false,\n }),\n];\n\nconst ACTIONS_COLUMN_ID = 'TableActions';\nconst getActionColumn = (rowActions: DialogMenuAction<any>[]) => {\n if (rowActions.length === 0) return [];\n\n return [\n cH.accessor(ACTIONS_COLUMN_ID, {\n header: 'Actions',\n id: ACTIONS_COLUMN_ID,\n enableHiding: false,\n cell: ({ row }) => <DialogMenu label={<IcMoreVertical />} data={row.original} items={rowActions} />,\n enableSorting: false,\n }),\n ];\n};\n\ntype DataTableFactory<T extends object, TOperation extends keyof operations> = {\n path: NoInfer<ClientPathsWithMethod<CtxClientType, 'get'>>;\n pathParameters?: NoInfer<ApiPathParameters<TOperation>>;\n columns: ColumnDef<T, any>[];\n tableActions: TableAction<T>[];\n columnsToHideByDefault?: Partial<Record<keyof T, boolean>>; // Columns that are hidden by default\n allowSelection?: boolean;\n filterConfig: FiltersConfig<TOperation>;\n initialFilters: TableFilter[];\n rowActions?: DialogMenuAction<T>[];\n};\n\ntype DataTableState = {\n sorting: SortingState;\n pagination: PaginationState;\n};\n\nexport function getColumnHelper<O extends keyof operations>(): ColumnHelper<ApiResponseBody<O>> {\n return createColumnHelper<ApiResponseBody<O>>();\n}\n/**\n * Hook for handling all data-table state. Used in DataTableContext\n */\nexport function useDataTableState<T extends object, TOperation extends keyof operations>({\n path,\n pathParameters,\n columns,\n filterConfig,\n columnsToHideByDefault = {},\n allowSelection = false,\n initialFilters = [],\n tableActions,\n rowActions,\n}: DataTableFactory<T, TOperation>) {\n const [tableState, _setTableState] = useState<DataTableState>({\n /** Reflect in URL in host application */\n pagination: { pageIndex: 0, pageSize: 20 }, // Pagination state\n sorting: [], // Sorting state\n });\n\n const { sorting, pagination } = tableState;\n\n const [searchQuery, setSearchQuery] = useState('');\n\n const [rowSelection, setRowSelection] = useState<RowSelectionState>({});\n\n /** Reflect in URL in host application */\n const [filters, setFilters] = useState(initialFilters);\n const mergedFilters = useMemo(() => {\n // TODO, generic transform fn\n return filters\n .map(tf => {\n if (Array.isArray(tf.value)) {\n return {\n [tf.property]: {\n [tf.operator]: tf.value.join(','),\n },\n };\n }\n return {\n [tf.property]: {\n [tf.operator]: tf.value,\n },\n };\n })\n .reduce((acc, current) => {\n return merge(acc, current);\n }, {});\n }, [filters]);\n\n const queryParameters = {\n ...filters,\n page: pagination.pageIndex + 1,\n limit: pagination.pageSize,\n sort: generateSortParam(sorting[0]),\n search: searchQuery,\n };\n\n const client = useCtxClient();\n // TODO, this seems incorrect, verify\n const queryKey = ['get', path];\n\n const [columnOrder, setColumnOrder] = useLocalStorage<ColumnOrderState>(\n `${queryKey.join('')}_ctx_column_order_preference`,\n []\n );\n const [columnVisibility, setColumnVisibility] = useLocalStorage<VisibilityState>(\n `${queryKey.join('')}_ctx_column_visibility_preference`,\n {\n id: false,\n ...columnsToHideByDefault,\n }\n );\n\n // Update table state with new values\n const updateTableState = (updates: Partial<DataTableState>) => {\n _setTableState(prev => ({ ...prev, ...updates }));\n };\n\n const query = useQuery({\n queryKey,\n queryFn: async () => {\n // Hoping the above type catches the correct path parameter.\n const res = await client.GET(path, { params: { query: queryParameters, path: pathParameters as any } });\n return {\n data: (res.data ?? []) as T[],\n total: Number.parseInt(res.response.headers.get('Pagination-Count') || '0'),\n };\n },\n });\n /**\n * ID,createdAt and updatedAt will be added by default for all tables\n * If selection is allowed, checkbox will be added\n * If the dto has metadata, dynamics columns for all the metadata key-value will be added(particular for a view)\n * If there are actions for the table, they will be placed fixed at the right side of table.\n */\n const cols: ColumnDef<any, any>[] = [\n ...(allowSelection ? TABLE_CHECK_BOX_COLUMN : []),\n ...columns,\n ...getActionColumn(rowActions ?? []),\n ];\n\n // Type-guard for updater\n function isUpdaterFunction<T>(updater: Updater<T>): updater is (old: T) => T {\n return typeof updater === 'function';\n }\n // Utility function to resolve updater\n function resolveUpdater<T>(updater: Updater<T>, currentValue: T) {\n if (isUpdaterFunction(updater)) {\n return updater(currentValue);\n }\n return updater;\n }\n\n // Use react-table's hook to create the table instance\n const tanTable = useReactTable({\n data: query.data?.data ?? [],\n columns: cols,\n getCoreRowModel: getCoreRowModel(),\n rowCount: query.data?.total ?? 0,\n manualPagination: true, // Handle pagination manually since pagination is done server side for data tables\n onPaginationChange: updater => {\n updateTableState({ pagination: resolveUpdater(updater, pagination) });\n },\n manualSorting: true, // Handle sorting manually since sorting is done server side for data tables\n onSortingChange: updater => {\n setRowSelection({});\n updateTableState({ sorting: [...resolveUpdater(updater, sorting)] }); // Reset selection when sorting.\n },\n manualFiltering: true, // Handle filtering manually since filtering is done server side for data tables\n onColumnVisibilityChange: updater => {\n setColumnVisibility(resolveUpdater(updater, columnVisibility));\n },\n onRowSelectionChange: updater => {\n setRowSelection(resolveUpdater(updater, rowSelection));\n },\n onColumnOrderChange: updater => {\n setColumnOrder(resolveUpdater(updater, columnOrder));\n },\n state: {\n sorting: sorting,\n columnVisibility: columnVisibility,\n pagination: pagination,\n rowSelection: rowSelection,\n columnOrder: columnOrder,\n },\n meta: {\n refetch: query.refetch,\n },\n });\n\n // By default, ColumnDef does not give guarantees of column.id existing. Once useReactTable is called, all columns are assigned IDs.\n // This populates the columnIds in the columnOrder state\n useEffect(() => {\n setColumnOrder([...tanTable.getAllLeafColumns().map(c => c.id)]);\n }, []);\n\n return {\n tableState,\n updateTableState,\n query,\n setSearchQuery,\n searchQuery,\n tanTable,\n mergedFilters,\n filters,\n setFilters,\n filterConfig,\n tableActions,\n } as const;\n}\n\nexport const DataTableContext = createContext<ReturnType<typeof useDataTableState> | null>(null);\n// TODO, don't export this\nexport function useDataTable() {\n const ctx = useContext(DataTableContext);\n if (!ctx) {\n throw Error('DataTable should be used within DataTableProvider.');\n }\n return ctx;\n}\n\nexport function DataTableProvider<T extends object, TOperation extends keyof operations>({\n children,\n ...props\n}: { children: React.ReactNode } & ReturnType<typeof useDataTableState<T, TOperation>>) {\n // @ts-expect-error, propogating the generic type further will be more complex. Since this is a tightly coupled type, it should be okay but reviewed whenever useDataTableState changes.\n return <DataTableContext.Provider value={props}>{children}</DataTableContext.Provider>;\n}\n\nexport type DataTableProps = React.ComponentProps<'section'>;\nexport function DataTable({ className, ...props }: DataTableProps) {\n const { query, tanTable } = useDataTable();\n\n return (\n <>\n {/* Table Actions Section */}\n <section {...props} className={classNames('flex flex-col bg-elevation-1', className)}>\n <Actions />\n {/* The div here is necessary because TableContent is internally a <table> tag and does not respect width, height CSS */}\n <div className=\"w-full overflow-auto border-x h-table relative\" tabIndex={0}>\n {/* Table overlay with loader */}\n {query.isLoading && (\n <TableOverlay className=\"cursor-wait\">\n <Loader />\n </TableOverlay>\n )}\n {/* Table overlay for empty table */}\n {!query.isLoading && tanTable.getRowModel().rows.length === 0 && (\n // Empty table\n <TableOverlay className=\"cursor-not-allowed\">\n {!query.isFetching &&\n (query.isError ? (\n <span className=\"flex gap-3 justify-center items-center\">\n {/* TODO (mudasir-pandith) Check for 403 explicitly!! */}\n {/* <span>{query.error}</span> */}\n <IcInfo />\n <span>{query.error.message}</span>\n </span>\n ) : query.data?.data?.length === 0 ? (\n <>No results found.</>\n ) : (\n <>Unknown error. Please contact customer support.</>\n ))}\n </TableOverlay>\n )}\n {!query.isLoading && tanTable.getRowModel().rows.length !== 0 && (\n <TableContent className=\"w-full\" />\n )}\n </div>\n\n {/* Table Footer Section with Pagination and Column Picker */}\n <div className=\"flex w-full justify-between border gap-icon p-icon overflow-x-auto\">\n <div className=\"flex gap-icon\">\n <ColumnPicker />\n <PageSize />\n </div>\n <Paginator />\n </div>\n </section>\n </>\n );\n}\n/** Table overlay to be shown for loaders or other messages */\nfunction TableOverlay({ children, className }: { children: React.ReactNode; className?: string }) {\n return (\n <>\n <span\n className={classNames(\n className,\n 'absolute top-0 bg-elevation-1 text-foreground z-20 size-full body-sm flex items-center justify-center'\n )}\n >\n {children}\n </span>\n {/* Keep something in document flow with the correct height */}\n <span className=\"relative h-full w-0 block\" />\n </>\n );\n}\n\n// TODO, ?include query param on Licenses, Activations and other future resources that need this\nfunction ColumnPicker() {\n const { tanTable } = useDataTable();\n const [activeId, setActiveId] = useState<string | null>(null);\n\n const resourceFormatter = useResourceFormatter();\n\n const sensors = useSensors(\n useSensor(PointerSensor),\n useSensor(KeyboardSensor, {\n coordinateGetter: sortableKeyboardCoordinates,\n })\n );\n return (\n <DndContext\n sensors={sensors}\n collisionDetection={closestCenter}\n onDragStart={event => {\n const { active } = event;\n setActiveId(active.id.toString());\n }}\n onDragEnd={event => {\n const { active, over } = event;\n\n if (over && active.id !== over.id) {\n const columnOrder = tanTable.getState().columnOrder;\n const oldIndex = columnOrder.indexOf(active.id.toString());\n const newIndex = columnOrder.indexOf(over.id.toString());\n tanTable.setColumnOrder([...arrayMove(columnOrder, oldIndex, newIndex)]);\n }\n\n setActiveId(null);\n }}\n >\n <SortableContext items={tanTable.getState().columnOrder} strategy={verticalListSortingStrategy}>\n <EasyMenu\n label={\n <>\n <IcColumns className=\"inline align-bottom me-1\" />\n Columns\n </>\n }\n selectionMode=\"multiple\"\n items={tanTable.getAllFlatColumns()}\n // Using selectedKeys = 'all' does not mark MenuItems with isDisabled=true as selected. This is not the intended behaviour in this use-case.\n selectedKeys={tanTable.getVisibleFlatColumns().map(c => c.id)}\n >\n <MenuItem onAction={() => tanTable.toggleAllColumnsVisible()} className={'italic'}>\n (select all)\n </MenuItem>\n {tanTable.getState().columnOrder.map(colId => {\n const col = tanTable.getAllFlatColumns().find(c => c.id === colId);\n // Don't show checkbox and actions columns in picker\n if (!col || col.id === 'checkbox' || col.id === ACTIONS_COLUMN_ID) return null;\n return <SortableItem key={col.id} column={col} />;\n })}\n </EasyMenu>\n <DragOverlay>\n {activeId ? (\n <div className=\"opacity-70 border-2 border-primary\">{resourceFormatter(activeId)}</div>\n ) : null}\n </DragOverlay>\n </SortableContext>\n </DndContext>\n );\n\n function SortableItem({ column }: { column: Column<any, unknown> }) {\n const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: column.id });\n const style = {\n transform: CSS.Transform.toString(transform),\n transition,\n zIndex: '999',\n };\n return (\n <MenuItem\n ref={setNodeRef}\n style={style}\n {...attributes}\n id={column.id}\n onAction={() => column.toggleVisibility()}\n isDisabled={!column.getCanHide()}\n className=\"flex items-center\"\n >\n <IcGrip {...listeners} className=\"size-icon cursor-grab\" />\n {getColumnHeaderText(column)}\n {column.getIsSorted() && <SortIcon className=\"size-icon\" direction={column.getIsSorted()} />}\n </MenuItem>\n );\n }\n}\n\nfunction Paginator() {\n const { tanTable } = useDataTable();\n const rowCount = tanTable.getRowCount();\n return (\n <div className=\"flex items-center gap-2\">\n <span className=\"whitespace-nowrap body-sm text-muted\">\n {`${tanTable.getState().pagination.pageIndex * tanTable.getState().pagination.pageSize + 1} - ${Math.min(\n (tanTable.getState().pagination.pageIndex + 1) * tanTable.getState().pagination.pageSize,\n rowCount\n )} of ${rowCount?.toLocaleString()}`}\n </span>\n\n <Button\n aria-label=\"First page\"\n onPress={() => tanTable.firstPage()}\n isDisabled={!tanTable.getCanPreviousPage()}\n variant=\"neutral\"\n size={'icon'}\n >\n <IcFirst />\n </Button>\n <Button\n aria-label=\"Previous page\"\n onPress={() => tanTable.previousPage()}\n isDisabled={!tanTable.getCanPreviousPage()}\n variant=\"neutral\"\n size={'icon'}\n >\n <IcLeft />\n </Button>\n <Button\n aria-label=\"Next page\"\n onPress={() => tanTable.nextPage()}\n isDisabled={!tanTable.getCanNextPage()}\n variant=\"neutral\"\n size={'icon'}\n >\n <IcRight />\n </Button>\n <Button\n aria-label=\"Last page\"\n onClick={() => tanTable.lastPage()}\n isDisabled={!tanTable.getCanNextPage()}\n variant=\"neutral\"\n size={'icon'}\n >\n <IcLast />\n </Button>\n </div>\n );\n}\n\nfunction PageSize() {\n const { tanTable } = useDataTable();\n const PAGE_SIZES = [10, 20, 30, 40, 50];\n\n return (\n <EasyMenu\n label={tanTable.getState().pagination.pageSize.toString()}\n selectionMode=\"single\"\n selectedKeys={[tanTable.getState().pagination.pageSize.toString()]}\n items={PAGE_SIZES.map(s => ({ id: s.toString(), value: s }))}\n >\n {items => <MenuItem onAction={() => tanTable.setPageSize(items.value)}>{items.value}</MenuItem>}\n </EasyMenu>\n );\n}\n\nfunction Actions() {\n const { query, tanTable, searchQuery, setSearchQuery, tableActions } = useDataTable();\n const hasSelectedRows = tanTable.getSelectedRowModel().rows.length > 0;\n const selectedRows = tanTable.getSelectedRowModel().rows.map(r => r.original);\n\n const filteredActions = tableActions.filter(ta => ta.bulk === hasSelectedRows);\n\n return (\n <section className=\"flex bg-elevation-1 justify-between my-0 p-icon border gap-icon overflow-auto\">\n <div className=\"flex gap-icon\">\n <Button\n aria-label=\"Refresh\"\n isPending={query.isFetching}\n onClick={() => query.refetch()}\n variant={'neutral'}\n size={'icon'}\n >\n <IcRefresh />\n </Button>\n\n <TableActions items={filteredActions} rowsSelected={selectedRows} isFetching={query.isFetching} />\n </div>\n <div className=\"flex gap-icon\">\n <DataTableFilter />\n {<SearchField value={searchQuery} onChange={setSearchQuery} />}\n </div>\n </section>\n );\n}\n\nfunction SortIcon({\n direction,\n ...props\n}: { direction: 'asc' | 'desc' | false } & Omit<React.ComponentProps<'svg'>, 'direction'>) {\n if (direction === 'asc') return <IcSortAsc className=\"size-3.5\" {...props} />;\n else if (direction === 'desc') return <IcSortDesc className=\"size-3.5\" {...props} />;\n else return <IcSortNone className=\"size-3.5\" {...props} />;\n}\n\nfunction getColumnHeaderText(column: Column<any, unknown>): string {\n const resourceFormatter = useResourceFormatter();\n const headerDef = column.columnDef.header;\n return typeof headerDef === 'string' ? headerDef : resourceFormatter(column.id);\n}\n\n/**\n * Renders a cell value based on the displayType metadata\n * @param cell - The cell to render\n * @returns The formatted value as a React node\n */\nfunction renderCellByDisplayType(cell: Cell<any, any>): React.ReactNode {\n const displayType = cell.column.columnDef.meta?.displayType;\n const value = cell.getValue();\n\n if (value === null || value === undefined) {\n return null;\n }\n\n switch (displayType) {\n case 'date':\n return formatDate(value);\n\n case 'number':\n return formatNumber(value);\n case 'boolean':\n case 'badge':\n return <Badge className=\"uppercase w-full\">{String(value)}</Badge>;\n case 'country':\n return <CountryName value={value} />;\n case 'enum':\n return <span className=\"uppercase w-full\">{String(value)}</span>;\n case 'fileSize':\n return formatFilesize(value);\n case 'days':\n return formatDays(value);\n default:\n return String(value);\n }\n}\n\nfunction HeaderText({ header }: { header: Header<any, unknown> }) {\n const headerDef = header.column.columnDef.header;\n\n if (typeof headerDef === 'string' || !headerDef) {\n return getColumnHeaderText(header.column);\n }\n\n if (typeof headerDef === 'function') {\n const result = headerDef(header.getContext());\n if (typeof result === 'string') {\n return getColumnHeaderText(header.column);\n }\n return flexRender(headerDef, header.getContext());\n }\n\n return flexRender(headerDef, header.getContext());\n}\n\n// TODO, automate checking valid HTML\nfunction TableContent({ className }: React.ComponentProps<typeof TableComponent>) {\n const { tanTable } = useDataTable();\n const tableCellStyle = (isSticky: boolean, className?: string, zIndex: string = 'z-50') =>\n classNames(\n 'px-icon py-2 text-left body-sm font-medium whitespace-nowrap',\n isSticky && `bg-elevation-1 sticky right-0 ${zIndex} text-center justify-center`,\n className\n );\n return (\n <TableComponent className={classNames('table-auto', className)}>\n <TableHeader className=\"sticky top-0 z-10\">\n {tanTable.getHeaderGroups().map(headerGroup => (\n <TableRow key={headerGroup.id}>\n {headerGroup.headers.map(header => (\n <TableHead\n scope=\"col\"\n key={header.id}\n colSpan={header.colSpan}\n className={tableCellStyle(header.id === ACTIONS_COLUMN_ID, 'bg-elevation-1')}\n >\n {!header.column.getCanSort() && !header.isPlaceholder && (\n <div\n className={classNames(\n 'w-full py-1 inline-flex items-center gap-1 body-sm',\n header.id === ACTIONS_COLUMN_ID ? 'justify-center' : 'justify-start'\n )}\n >\n <HeaderText header={header} />\n </div>\n )}\n {header.column.getCanSort() && (\n <Button\n variant=\"ghost\"\n className={classNames(\n 'w-full p-1',\n header.id === ACTIONS_COLUMN_ID ? 'justify-center' : 'justify-start'\n )}\n onPress={header.column.getToggleSortingHandler()}\n >\n <span>\n <HeaderText header={header} />\n </span>\n <SortIcon direction={header.column.getIsSorted()} />\n </Button>\n )}\n </TableHead>\n ))}\n </TableRow>\n ))}\n </TableHeader>\n <TableBody>\n {tanTable.getRowModel().rows.map(row => (\n <TableRow\n className={classNames(\n 'transition-colors data-[selected=true]:bg-primary/10 hover:bg-muted-foreground/20'\n )}\n key={row.id}\n data-selected={row.getIsSelected()}\n >\n {row.getVisibleCells().map(cell => {\n const isActionsColumn = cell.column.id === ACTIONS_COLUMN_ID;\n const cellContent = cell.column.columnDef.meta?.displayType\n ? renderCellByDisplayType(cell)\n : flexRender(cell.column.columnDef.cell, cell.getContext());\n\n return (\n <TableCell\n key={cell.id}\n className={classNames(\n tableCellStyle(isActionsColumn, undefined, 'z-1'),\n isActionsColumn && 'flex justify-center items-center'\n )}\n >\n {cellContent}\n </TableCell>\n );\n })}\n </TableRow>\n ))}\n </TableBody>\n </TableComponent>\n );\n}\n","'use client';\nimport type { operations } from '@cryptlex/web-api-types/develop';\nimport { useRef } from 'react';\nimport { Button } from '../components/button';\nimport { useDataTable } from '../components/data-table';\nimport { TfDatePicker } from '../components/date-picker';\nimport { EasyMenu, MenuItem } from '../components/menu';\nimport type { MultiSelectProps } from '../components/multi-select';\nimport { Popover, PopoverTrigger } from '../components/popover';\nimport { useAppForm } from '../utilities/form-hook';\nimport { useResourceFormatter, type ApiFilters } from '../utilities/resources';\nimport { classNames } from '../utilities/theme';\nimport { IcAccount, IcCheck, IcDate, IcFile, IcFilter, IcLicense, IcMinus, IcRemove, type CtxIcon } from './icons';\nimport { TfMultipleIdSearchInput } from './id-search';\n\nexport const FILTER_COMPARISON_OPERATORS = [\n 'eq',\n 'ne',\n 'cn',\n 'nc',\n 'sw',\n 'ew',\n 'in',\n 'nin',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n] as const;\nexport type FilterComparisonOperator = (typeof FILTER_COMPARISON_OPERATORS)[number];\n\nexport const COMPARISON_OPERATOR_LABELS: Record<FilterComparisonOperator, string> = {\n eq: 'equal to',\n ne: 'not equal to',\n cn: 'contains',\n nc: 'does not contain',\n sw: 'starts with',\n ew: 'ends with',\n in: 'includes',\n nin: 'does not include',\n gt: 'greater than',\n gte: 'greater than or equal to',\n lt: 'less than',\n lte: 'less than or equal to',\n};\n\ntype BaseLocalFilter<T extends FilterType, V> = {\n id: string;\n type: T;\n property: string;\n operator: FilterComparisonOperator;\n value: V | undefined;\n displayValue?: string;\n};\ntype EnumLocalFilter = BaseLocalFilter<'enum', Set<string | number>>;\ntype IdLocalFilter = BaseLocalFilter<'id', string>;\ntype BoolLocalFilter = BaseLocalFilter<'bool', boolean>;\ntype StringLocalFilter = BaseLocalFilter<'string', string>;\ntype NumberLocalFilter = BaseLocalFilter<'number', number>;\n// DatePicker accepts a string,and converts it to a ZonedDateTime\ntype DateLocalFilter = BaseLocalFilter<'date', string>;\ntype IdSearchLocalFilter = BaseLocalFilter<'id-search', string[]>;\n// TODO, entitlementSets.productIds\nfunction createNewFilter(type: FilterType, property: string): TableFilter {\n const id = `${property}-${Date.now()}`;\n const operator = FilterOperations[type][0];\n\n switch (type) {\n case 'bool':\n return { id, type, property, operator, value: true };\n case 'string':\n return { id, type, property, operator, value: '' };\n case 'date':\n return { id, type, property, operator, value: new Date().toISOString() };\n case 'id':\n return { id, type, property, operator, value: '' };\n case 'id-search':\n return { id, type, property, operator, value: [] };\n case 'enum':\n return { id, type, property, operator, value: new Set<string | number>() };\n case 'number':\n return { id, type, property, operator, value: 0 };\n }\n}\n\nexport type TableFilter =\n | EnumLocalFilter\n | IdLocalFilter\n | BoolLocalFilter\n | StringLocalFilter\n | DateLocalFilter\n | IdSearchLocalFilter\n | NumberLocalFilter;\n\nexport type FilterConfig =\n | { type: 'enum'; options: MultiSelectProps['items'] }\n | ({ type: 'id-search' } & Pick<React.ComponentProps<typeof TfMultipleIdSearchInput>, 'accessor' | 'path'>)\n | { type: 'id' }\n | { type: 'bool' }\n | { type: 'string' }\n | { type: 'date' }\n | { type: 'number' };\n\nexport type FilterType = FilterConfig['type'];\n\nconst FilterOperations: Record<FilterType, FilterComparisonOperator[]> = {\n bool: ['eq'],\n enum: ['in', 'nin'],\n id: ['in', 'nin'],\n 'id-search': ['in', 'nin'],\n string: ['eq', 'ne', 'cn', 'nc', 'sw', 'ew', 'in', 'nin'],\n date: ['lt', 'gt'],\n number: ['eq', 'ne', 'gt', 'gte', 'lt', 'lte'],\n};\n\n// TS workaround to get rid of filterConfig: Required<Record<never, FilterConfig>>\nexport type FiltersConfig<TOperation extends keyof operations> = [keyof ApiFilters<TOperation>] extends [never]\n ? Record<string, FilterConfig>\n : Required<Record<keyof ApiFilters<TOperation>, FilterConfig>>;\n\nexport function DataTableFilter({ className, ...props }: React.ComponentProps<'section'>) {\n const { filters, query, setFilters, filterConfig } = useDataTable();\n\n const addFilterButtonRef = useRef<HTMLButtonElement>(null);\n\n const resourceFormatter = useResourceFormatter();\n\n const DEFAULT_VALUES: { filters: TableFilter[] } = {\n filters,\n };\n const form = useAppForm({\n defaultValues: DEFAULT_VALUES,\n onSubmit: ({ value }) => {\n setFilters(value.filters);\n },\n });\n\n // More reason to hate TS https://github.com/Microsoft/TypeScript/issues/12870\n const filterKeys = Object.keys(filterConfig).sort();\n\n return (\n <section {...props} className={classNames('flex gap-icon items-center', className)}>\n <PopoverTrigger\n onOpenChange={o => {\n // Set filters when the popover closes\n if (!o) {\n form.handleSubmit();\n } else {\n addFilterButtonRef.current?.focus();\n }\n }}\n >\n <div className=\"relative\">\n {filters.length > 0 && (\n <div className=\"size-2 rounded-full absolute bg-primary/90 z-20 top-0 right-0 translate-x-0.5 -translate-y-0.5\"></div>\n )}\n <Button\n aria-label=\"Filter\"\n isDisabled={query.isPending || filterKeys.length === 0}\n type=\"button\"\n size={'icon'}\n variant={'neutral'}\n >\n <IcFilter />\n </Button>\n </div>\n {/* TODO, icon maps with dynamic imports? */}\n {/* TODO open popover with form for property specific filter */}\n {/* TODO, icons here??? */}\n <Popover className=\"w-full p-icon\">\n <form\n onSubmit={e => {\n e.preventDefault();\n }}\n className=\"flex flex-col gap-icon max-h-table overflow-auto \"\n >\n <form.Field mode=\"array\" name={'filters'}>\n {field => {\n return (\n <>\n {field.state.value.map((lf, i) => {\n return (\n <div key={lf.id} className=\"flex gap-icon items-center justify-normal\">\n <span className=\"body-sm\">{resourceFormatter(lf.property)}</span>\n <form.AppField key={lf.id} name={`filters[${i}].operator`}>\n {sf => (\n <sf.TfSingleSelect\n items={FilterOperations[lf.type].map(op => ({\n id: op,\n label: <>{COMPARISON_OPERATOR_LABELS[op]}</>,\n }))}\n />\n )}\n </form.AppField>\n\n {lf.type === 'bool' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => <sf.TfCheckbox autoFocus />}\n </form.AppField>\n )}\n {lf.type === 'date' && (\n <form.AppField name={`filters[${i}].value`}>\n {_ => <TfDatePicker autoFocus />}\n </form.AppField>\n )}\n {lf.type === 'id' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => <sf.TfTextField autoFocus />}\n </form.AppField>\n )}\n {lf.type === 'string' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => <sf.TfTextField autoFocus />}\n </form.AppField>\n )}\n {lf.type === 'number' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => <sf.TfNumberField autoFocus />}\n </form.AppField>\n )}\n\n {lf.type === 'enum' && (\n <form.AppField name={`filters[${i}].value`}>\n {sf => {\n const config = filterConfig[lf.property];\n if (config.type !== 'enum') return null;\n return <sf.TfMultiSelect items={config.options} />;\n }}\n </form.AppField>\n )}\n\n {lf.type === 'id-search' && (\n <form.AppField name={`filters[${i}].value`}>\n {_ => {\n const config = filterConfig[lf.property];\n if (config.type !== 'id-search') return null;\n return (\n <TfMultipleIdSearchInput\n path={config.path}\n accessor={config.accessor}\n />\n );\n }}\n </form.AppField>\n )}\n\n <Button\n type=\"button\"\n variant=\"neutral\"\n size=\"icon\"\n onPress={() => field.removeValue(i)}\n >\n <IcRemove />\n </Button>\n </div>\n );\n })}\n <div className=\"flex w-full items-center justify-end gap-2 not-first:mt-icon\">\n <EasyMenu label=\"Add filter\" autoFocus>\n {filterKeys.sort().map(k => {\n const type = filterConfig[k].type;\n const Icon = FilterIcon[type];\n return (\n <MenuItem\n key={k}\n onAction={() => {\n const newFilter = createNewFilter(type, k);\n field.pushValue(newFilter);\n }}\n >\n {resourceFormatter(k)}\n <Icon />\n </MenuItem>\n );\n })}\n </EasyMenu>\n {field.state.value.length > 0 ? (\n <Button\n type=\"button\"\n variant=\"neutral\"\n onPress={() => {\n field.setValue([]);\n }}\n >\n <IcRemove />\n Reset\n </Button>\n ) : null}\n </div>\n </>\n );\n }}\n </form.Field>\n </form>\n </Popover>\n </PopoverTrigger>\n </section>\n );\n}\n\nconst FilterIcon: Record<FilterConfig['type'], CtxIcon> = {\n 'id-search': IcFile,\n bool: IcCheck,\n date: IcDate,\n enum: IcLicense,\n id: IcAccount,\n number: IcMinus,\n string: IcCheck,\n};\n"],"names":["generateSortParam","sort","cH","createColumnHelper","TABLE_CHECK_BOX_COLUMN","table","jsx","Checkbox","row","ACTIONS_COLUMN_ID","getActionColumn","rowActions","DialogMenu","IcMoreVertical","getColumnHelper","useDataTableState","path","pathParameters","columns","filterConfig","columnsToHideByDefault","allowSelection","initialFilters","tableActions","tableState","_setTableState","useState","sorting","pagination","searchQuery","setSearchQuery","rowSelection","setRowSelection","filters","setFilters","mergedFilters","useMemo","tf","acc","current","merge","queryParameters","client","useCtxClient","queryKey","columnOrder","setColumnOrder","useLocalStorage","columnVisibility","setColumnVisibility","updateTableState","updates","prev","query","useQuery","res","cols","isUpdaterFunction","updater","resolveUpdater","currentValue","tanTable","useReactTable","getCoreRowModel","useEffect","c","DataTableContext","createContext","useDataTable","ctx","useContext","DataTableProvider","children","props","DataTable","className","Fragment","classNames","Actions","jsxs","TableOverlay","Loader","IcInfo","TableContent","ColumnPicker","PageSize","Paginator","activeId","setActiveId","resourceFormatter","useResourceFormatter","sensors","useSensors","useSensor","PointerSensor","KeyboardSensor","sortableKeyboardCoordinates","DndContext","closestCenter","event","active","over","oldIndex","newIndex","arrayMove","SortableContext","verticalListSortingStrategy","EasyMenu","IcColumns","MenuItem","colId","col","SortableItem","DragOverlay","column","attributes","listeners","setNodeRef","transform","transition","useSortable","style","CSS","IcGrip","getColumnHeaderText","SortIcon","rowCount","Button","IcFirst","IcLeft","IcRight","IcLast","PAGE_SIZES","s","items","hasSelectedRows","selectedRows","r","filteredActions","ta","IcRefresh","TableActions","DataTableFilter","SearchField","direction","IcSortAsc","IcSortDesc","IcSortNone","headerDef","renderCellByDisplayType","cell","displayType","value","formatDate","formatNumber","Badge","CountryName","formatFilesize","formatDays","HeaderText","header","flexRender","tableCellStyle","isSticky","zIndex","TableComponent","TableHeader","headerGroup","TableRow","TableHead","TableBody","isActionsColumn","cellContent","TableCell","FILTER_COMPARISON_OPERATORS","COMPARISON_OPERATOR_LABELS","createNewFilter","type","property","id","operator","FilterOperations","addFilterButtonRef","useRef","form","useAppForm","filterKeys","PopoverTrigger","o","IcFilter","Popover","e","field","lf","i","sf","op","_","TfDatePicker","config","TfMultipleIdSearchInput","IcRemove","k","Icon","FilterIcon","newFilter","IcFile","IcCheck","IcDate","IcLicense","IcAccount","IcMinus"],"mappings":"wqFAkFA,SAASA,GAAkBC,EAAyD,CAChF,OAAIA,EACIA,EAAK,KACE,IAAIA,EAAK,EAAE,GAEX,IAAIA,EAAK,EAAE,GAGf,YAEf,CAEA,MAAMC,EAAKC,EAAA,EACLC,GAAyB,CAC3BF,EAAG,SAAS,WAAY,CACpB,OAAQ,CAAC,CAAE,MAAAG,CAAA,IACPC,EAACC,EAAA,CACG,gBAAiBF,EAAM,sBAAA,GAA2B,CAACA,EAAM,yBAAA,EACzD,WAAYA,EAAM,4BAA8BA,EAAM,0BAAA,EACtD,SAAU,IAAMA,EAAM,0BAAA,EACtB,aAAW,YAAA,CAAA,EAInB,KAAM,CAAC,CAAE,IAAAG,CAAA,MACJD,EAAA,CAAS,WAAYC,EAAI,cAAA,EAAiB,SAAU,IAAMA,EAAI,eAAA,EAAkB,aAAW,aAAa,EAE7G,cAAe,GACf,aAAc,EAAA,CACjB,CACL,EAEMC,EAAoB,eACpBC,GAAmBC,GACjBA,EAAW,SAAW,EAAU,CAAA,EAE7B,CACHT,EAAG,SAASO,EAAmB,CAC3B,OAAQ,UACR,GAAIA,EACJ,aAAc,GACd,KAAM,CAAC,CAAE,IAAAD,CAAA,IAAUF,EAACM,GAAA,CAAW,MAAON,EAACO,KAAe,EAAI,KAAML,EAAI,SAAU,MAAOG,EAAY,EACjG,cAAe,EAAA,CAClB,CAAA,EAqBF,SAASG,IAAgF,CAC5F,OAAOX,EAAA,CACX,CAIO,SAASY,GAAyE,CACrF,KAAAC,EACA,eAAAC,EACA,QAAAC,EACA,aAAAC,EACA,uBAAAC,EAAyB,CAAA,EACzB,eAAAC,EAAi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AYE,CAAC,EAElC,WAACO,EAAA,CAAA,CAAS,CAAA,CAAA,CACd,CAAA,EAvEMR,EAAG,EAwEb,CAEP,EACDlH,EAAC,MAAA,CAAI,UAAU,+DACX,SAAA,CAAAzE,EAACqG,EAAA,CAAS,MAAM,aAAa,UAAS,GACjC,SAAA+E,EAAW,KAAA,EAAO,IAAIgB,GAAK,CACxB,MAAMzB,EAAO9J,EAAauL,CAAC,EAAE,KACvBC,EAAOC,GAAW3B,CAAI,EAC5B,OACIlG,EAAC8B,EAAA,CAEG,SAAU,IAAM,CACZ,MAAMgG,EAAY7B,GAAgBC,EAAMyB,CAAC,EACzCV,EAAM,UAAUa,CAAS,CAC7B,EAEC,SAAA,CAAApH,EAAkBiH,CAAC,IACnBC,EAAA,CAAA,CAAK,CAAA,CAAA,EAPDD,CAAA,CAUjB,CAAC,CAAA,CACL,EACCV,EAAM,MAAM,MAAM,OAAS,EACxBjH,EAACgD,EAAA,CACG,KAAK,SACL,QAAQ,UACR,QAAS,IAAM,CACXiE,EAAM,SAAS,EAAE,CACrB,EAEA,SAAA,CAAA1L,EAACmM,EAAA,EAAS,EAAE,OAAA,CAAA,CAAA,EAGhB,IAAA,CAAA,CACR,CAAA,EACJ,CAER,CACJ,CAAA,CAAA,CACJ,CACJ,CAAA,CAAA,CAAA,EAER,CAER,CAEA,MAAMG,GAAoD,CACtD,YAAaE,GACb,KAAMC,EACN,KAAMC,GACN,KAAMC,GACN,GAAIC,GACJ,OAAQC,GACR,OAAQJ,CACZ"}
|
|
1
|
+
{"version":3,"file":"data-table.js","sources":["../../lib/components/data-table.tsx","../../lib/components/data-table-filter.tsx"],"sourcesContent":["'use client';\nimport type { operations } from '@cryptlex/web-api-types/develop';\nimport {\n closestCenter,\n DndContext,\n DragOverlay,\n KeyboardSensor,\n PointerSensor,\n useSensor,\n useSensors,\n} from '@dnd-kit/core';\nimport {\n arrayMove,\n SortableContext,\n sortableKeyboardCoordinates,\n useSortable,\n verticalListSortingStrategy,\n} from '@dnd-kit/sortable';\nimport { CSS } from '@dnd-kit/utilities';\nimport { useQuery } from '@tanstack/react-query';\n\nimport {\n type Column,\n type ColumnDef,\n type ColumnOrderState,\n createColumnHelper,\n flexRender,\n getCoreRowModel,\n type Header,\n type PaginationState,\n type RowData,\n type RowSelectionState,\n type SortingState,\n type Updater,\n useReactTable,\n type VisibilityState,\n} from '@tanstack/react-table';\nimport { useLocalStorage } from '@uidotdev/usehooks';\nimport { merge } from 'lodash-es';\nimport { createContext, useContext, useEffect, useMemo, useState } from 'react';\nimport { Badge } from '../components/badge';\n\nimport { Button } from '../components/button';\nimport { DataTableFilter, type FiltersConfig, type TableFilter } from '../components/data-table-filter';\nimport { 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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
|
import { DialogProps as AriaDialogProps, DialogTrigger as AriaDialogTrigger, HeadingProps as AriaHeadingProps, Modal as AriaModal, ModalOverlayProps as AriaModalOverlayProps } from 'react-aria-components';
|
|
3
4
|
/**
|
|
4
5
|
* Visual variants for the sheet-style dialog (slide in from an edge).
|
|
@@ -108,4 +109,61 @@ export declare function DialogTitle({ className, ...props }: AriaHeadingProps):
|
|
|
108
109
|
* ```
|
|
109
110
|
*/
|
|
110
111
|
export declare function DialogDescription({ className, ...props }: React.HTMLAttributes<HTMLParagraphElement>): import("react/jsx-runtime").JSX.Element;
|
|
112
|
+
/**
|
|
113
|
+
* Context type for controlled dialog state and actions.
|
|
114
|
+
*/
|
|
115
|
+
type ControlledDialogContextType = {
|
|
116
|
+
/** Opens the dialog with the provided content */
|
|
117
|
+
openDialog: (content: ReactNode) => void;
|
|
118
|
+
/** Closes the dialog */
|
|
119
|
+
closeDialog: () => void;
|
|
120
|
+
/** Whether the dialog is currently open */
|
|
121
|
+
isOpen: boolean;
|
|
122
|
+
};
|
|
123
|
+
/**
|
|
124
|
+
* Provider that manages a scoped dialog controlled via hooks.
|
|
125
|
+
*
|
|
126
|
+
* @example
|
|
127
|
+
* ```tsx
|
|
128
|
+
* <ControlledDialogProvider>
|
|
129
|
+
* <MyComponent />
|
|
130
|
+
* </ControlledDialogProvider>
|
|
131
|
+
*
|
|
132
|
+
* // Inside MyComponent:
|
|
133
|
+
* function MyComponent() {
|
|
134
|
+
* const { openDialog } = useControlledDialog();
|
|
135
|
+
* return (
|
|
136
|
+
* <Button onPress={() => openDialog(<div>Dialog content</div>)}>
|
|
137
|
+
* Open Dialog
|
|
138
|
+
* </Button>
|
|
139
|
+
* );
|
|
140
|
+
* }
|
|
141
|
+
* ```
|
|
142
|
+
*/
|
|
143
|
+
export declare function ControlledDialogProvider({ children }: {
|
|
144
|
+
children: ReactNode;
|
|
145
|
+
}): import("react/jsx-runtime").JSX.Element;
|
|
146
|
+
/**
|
|
147
|
+
* Hook to access the controlled dialog from within a ControlledDialogProvider.
|
|
148
|
+
*
|
|
149
|
+
* @throws Error if used outside of ControlledDialogProvider
|
|
150
|
+
*
|
|
151
|
+
* @example
|
|
152
|
+
* ```tsx
|
|
153
|
+
* function MyComponent() {
|
|
154
|
+
* const { openDialog, closeDialog, isOpen } = useControlledDialog();
|
|
155
|
+
*
|
|
156
|
+
* return (
|
|
157
|
+
* <Button onPress={() => openDialog(
|
|
158
|
+
* <DialogHeader>
|
|
159
|
+
* <DialogTitle>Confirm</DialogTitle>
|
|
160
|
+
* </DialogHeader>
|
|
161
|
+
* )}>
|
|
162
|
+
* Open
|
|
163
|
+
* </Button>
|
|
164
|
+
* );
|
|
165
|
+
* }
|
|
166
|
+
* ```
|
|
167
|
+
*/
|
|
168
|
+
export declare function useControlledDialog(): ControlledDialogContextType;
|
|
111
169
|
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{jsx as
|
|
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 {\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"],"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"],"mappings":"4aAwBA,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,CACJ,EAEH,GAAGE,CAAA,CACR,EA+CG,SAASK,EAAc,CAAE,UAAAP,EAAW,SAAAQ,EAAU,KAAAC,EAAM,KAAAC,EAAM,YAAAC,EAAc,GAAM,GAAGT,GAA6B,CACjH,OACIC,EAACS,EAAA,CACG,UAAWP,EAAmBL,EAAWA,GACrCM,EACIG,EACMd,EAAc,CAAE,KAAAc,EAAM,UAAW,YAAA,CAAc,EAC/C,CACI,kUAAA,EAEVT,CAAA,CACJ,EAEH,GAAGE,EAEJ,SAAAC,EAACU,EAAA,CACG,KAAAH,EACA,UAAWJ,EAAW,CAACG,GAAQ,gCAAiC,qBAAqB,EAEpF,SAAAJ,EAAmBG,EAAU,CAACA,EAAUM,IACrCC,EAAAC,EAAA,CACK,SAAA,CAAAR,EACAG,GACGR,EAAC,MAAA,CAAI,UAAU,yBACX,SAAAY,EAACE,EAAA,CACG,KAAM,OACN,QAAS,UACT,QAASH,EAAY,MACrB,UAAU,eAEV,SAAA,CAAAX,EAACe,EAAA,EAAQ,EACTf,EAAC,OAAA,CAAK,UAAU,UAAU,SAAA,OAAA,CAAK,CAAA,CAAA,CAAA,CACnC,CACJ,CAAA,EAER,CACH,CAAA,CAAA,CACL,CAAA,CAGZ,CAYO,SAASgB,EAAa,CAAE,UAAAnB,EAAW,GAAGE,GAA+C,CACxF,OAAOC,EAAC,OAAI,UAAWG,EAAW,iDAAkDN,CAAS,EAAI,GAAGE,EAAO,CAC/G,CAaO,SAASkB,EAAa,CAAE,UAAApB,EAAW,GAAGE,GAA+C,CACxF,OACIC,EAAC,MAAA,CACG,UAAWG,EAAW,8DAA+DN,CAAS,EAC7F,GAAGE,CAAA,CAAA,CAGhB,CAQO,SAASmB,EAAY,CAAE,UAAArB,EAAW,GAAGE,GAA2B,CACnE,OACIC,EAACmB,EAAA,CACG,KAAK,QACL,UAAWhB,EAAW,sDAAuDN,CAAS,EACrF,GAAGE,CAAA,CAAA,CAGhB,CAYO,SAASqB,EAAkB,CAAE,UAAAvB,EAAW,GAAGE,GAAqD,CACnG,OAAOC,EAAC,KAAE,UAAWG,EAAW,iDAAkDN,CAAS,EAAI,GAAGE,EAAO,CAC7G"}
|
|
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,cAAAH,EACA,UAAWI,EAAmBL,EAAWA,GACrCM,EACI,sCAEA,yDAEA,6BACAN,CAAA,CACJ,EAEH,GAAGE,CAAA,CACR,EA+CG,SAASK,EAAc,CAAE,UAAAP,EAAW,SAAAQ,EAAU,KAAAC,EAAM,KAAAC,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,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,6 +1,7 @@
|
|
|
1
1
|
import { ClientPathsWithMethod } from 'openapi-fetch';
|
|
2
2
|
import { Menu } from '../components/menu';
|
|
3
3
|
import { CtxClientType } from '../utilities/ctx-client';
|
|
4
|
+
import { EmptyOption } from '../utilities/empty-option';
|
|
4
5
|
import { FormFieldProps } from './form';
|
|
5
6
|
/**
|
|
6
7
|
* Minimal resource shape used by the ID search inputs.
|
|
@@ -44,7 +45,7 @@ type BaseSearchableResource = {
|
|
|
44
45
|
* @testing
|
|
45
46
|
* - Ensure API client is provided via context; assert keyboard navigation, open/close behavior, and `onBlur` call on popover close.
|
|
46
47
|
*/
|
|
47
|
-
declare function BaseIdSearchInput<T extends BaseSearchableResource, V>({ label, description, errorMessage, requiredIndicator, isDisabled, isInvalid, onBlur, path, onChange, value, renderLabel, accessor, defaultParams, className, ...props }: FormFieldProps & {
|
|
48
|
+
declare function BaseIdSearchInput<T extends BaseSearchableResource, V>({ label, description, errorMessage, requiredIndicator, isDisabled, isInvalid, onBlur, path, onChange, value, renderLabel, accessor, defaultParams, className, emptyOption, ...props }: FormFieldProps & {
|
|
48
49
|
path: ClientPathsWithMethod<CtxClientType, 'get'>;
|
|
49
50
|
/** Disable interactions. */
|
|
50
51
|
isDisabled?: boolean;
|
|
@@ -59,11 +60,12 @@ declare function BaseIdSearchInput<T extends BaseSearchableResource, V>({ label,
|
|
|
59
60
|
/** Controlled change handler. */
|
|
60
61
|
onChange: (v: V) => void;
|
|
61
62
|
/** Render a human-readable label for the current value using the latest data. */
|
|
62
|
-
renderLabel: (v: V, data: T[] | undefined) => string;
|
|
63
|
+
renderLabel: (v: V, data: T[] | undefined, emptyOption?: EmptyOption) => string;
|
|
63
64
|
/** Default parameters to include in the request. This is useful when using /v3/users?role='admin' or /v3/organizations/ID/user-groups */
|
|
64
65
|
defaultParams?: Record<'path' | 'query', any>;
|
|
65
66
|
/** Optional className to customize the trigger button styling. */
|
|
66
67
|
className?: string;
|
|
68
|
+
emptyOption?: EmptyOption;
|
|
67
69
|
} & Omit<React.ComponentProps<typeof Menu>, 'items' | 'className'>): import("react/jsx-runtime").JSX.Element;
|
|
68
70
|
/**
|
|
69
71
|
* Single-selection ID search input.
|
|
@@ -83,7 +85,7 @@ declare function BaseIdSearchInput<T extends BaseSearchableResource, V>({ label,
|
|
|
83
85
|
* />
|
|
84
86
|
*
|
|
85
87
|
*/
|
|
86
|
-
export declare function SingleIdSearchInput<T extends BaseSearchableResource>({ ...props }: Omit<React.ComponentProps<typeof BaseIdSearchInput<T, string>>, 'onSelectionChange' | 'selectionMode' | 'selectedKeys' | 'renderLabel'>): import("react/jsx-runtime").JSX.Element;
|
|
88
|
+
export declare function SingleIdSearchInput<T extends BaseSearchableResource>({ ...props }: Omit<React.ComponentProps<typeof BaseIdSearchInput<T, string | null>>, 'onSelectionChange' | 'selectionMode' | 'selectedKeys' | 'renderLabel'>): import("react/jsx-runtime").JSX.Element;
|
|
87
89
|
/**
|
|
88
90
|
* Multi-selection ID search input.
|
|
89
91
|
*
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{jsx as n,jsxs as
|
|
1
|
+
"use client";import{jsx as n,jsxs as C}from"react/jsx-runtime";import{useQuery as w}from"@tanstack/react-query";import{useId as L,useState as K}from"react";import{Select as R,Autocomplete as _}from"react-aria-components";import{Loader as P}from"./loader.js";import{Menu as V,MenuItem as D}from"./menu.js";import{PopoverTrigger as G}from"./popover.js";import{SearchField as Q}from"./searchfield.js";import{useCtxClient as k}from"../utilities/ctx-client.js";import{isEmptyValue as z,getEmptyLabel as F}from"../utilities/empty-option.js";import{getFieldErrorMessage as c}from"../utilities/form.js";import{useFieldContext as M}from"../utilities/form-context.js";import{FormField as H}from"./form.js";import{SelectTrigger as J,SelectPopover as U}from"./select.js";import"../utilities/theme.js";import"clsx";import"./icons.js";import"./list-box.js";import"./button.js";import"class-variance-authority";import"@tanstack/react-form";function W(r){return Array.isArray(r)&&r.every(i=>i&&typeof i=="object"&&"id"in i&&"name"in i)}function N({label:r,description:i,errorMessage:e,requiredIndicator:t,isDisabled:o,isInvalid:l,onBlur:u,path:a,onChange:m,value:h,renderLabel:q,accessor:f,defaultParams:p,className:x,emptyOption:E,...g}){if(a==="/v3/me")throw Error('Path "/v3/me" is not supported with IdSearch since it is not a searchable resource.');const A=L(),y=g.id||A,B=k(),[S,T]=K(""),{data:I,isError:v,isFetching:b,error:j}=w({queryKey:["get",a],queryFn:async()=>{const d=(await B.GET(a,{params:{query:{search:S,...p?.query},path:{...p?.path}}})).data;return d&&W(d)?d:[]}});return n("div",{className:"group form-field","data-invalid":l?"":void 0,children:n(H,{label:r,description:i,errorMessage:e,requiredIndicator:t,htmlFor:y,children:n(R,{isInvalid:l,children:C(G,{onOpenChange:s=>{s||u?.(h)},children:[n(J,{id:y,isDisabled:o,className:x??"w-full",children:q(h,I,E)}),n(U,{placement:"bottom start",children:C(_,{inputValue:S,onInputChange:T,children:[n(Q,{className:"p-2",autoFocus:!0}),b&&n("div",{className:"p-input",children:n(P,{className:"mx-auto"})}),!b&&!v&&n(V,{...g,className:"max-h-48",items:I,renderEmptyState:()=>n("div",{className:"body-sm p-2",children:"No results found."}),children:s=>n(D,{id:s[f],children:s.name},s[f])}),v&&n("div",{className:"text-destructive p-icon body-sm",children:j.message})]})})]})})})})}function X({...r}){const i=r.value?[r.value]:[];return n(N,{selectedKeys:i,onSelectionChange:e=>{const t=Array.from(e).filter(o=>typeof o=="string")[0];r.onChange(t)},renderLabel:(e,t,o)=>o&&z(e)?F(o):t?.find(l=>l.id===e)?.name??"",selectionMode:"single",...r})}function Y({...r}){const i=r.value;return n(N,{selectedKeys:i,onSelectionChange:e=>{const t=Array.from(e).filter(o=>typeof o=="string");r.onChange(t.length>0?t:[])},selectionMode:"multiple",renderLabel:(e,t,o)=>{if(o&&(!e||e.length===0))return F(o);const u=(e??[]).map(a=>t?.find(m=>m.id===a)?.name??a);return u.length>0?u.join(","):""},...r})}function Se({isDisabled:r,...i}){const e=M({disabled:r});return n(X,{requiredIndicator:e.isRequired,isDisabled:r||e.form.state.isSubmitting,value:e.state.value,onBlur:t=>e.handleBlur(),onChange:t=>e.handleChange(t),isInvalid:!!c(e),errorMessage:c(e),...i})}function Ie({isDisabled:r,...i}){const e=M({disabled:r});return n(Y,{requiredIndicator:e.isRequired,isDisabled:r||e.form.state.isSubmitting,value:e.state.value,onBlur:t=>e.handleBlur(),onChange:t=>e.handleChange(t),isInvalid:!!c(e),errorMessage:c(e),...i})}export{Y as MultipleIdSearchInput,X as SingleIdSearchInput,Ie as TfMultipleIdSearchInput,Se as TfSingleIdSearchInput};
|
|
2
2
|
//# sourceMappingURL=id-search.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"id-search.js","sources":["../../lib/components/id-search.tsx"],"sourcesContent":["'use client';\nimport { useQuery } from '@tanstack/react-query';\nimport { useId, useState } from 'react';\nimport { Select as AriaSelect, Autocomplete } from 'react-aria-components';\n\nimport type { ClientPathsWithMethod } from 'openapi-fetch';\nimport { Loader } from '../components/loader';\nimport { Menu, MenuItem } from '../components/menu';\nimport { PopoverTrigger } from '../components/popover';\nimport { SearchField } from '../components/searchfield';\nimport { useCtxClient, type CtxClientType } from '../utilities/ctx-client';\nimport { getFieldErrorMessage } from '../utilities/form';\nimport { useFieldContext } from '../utilities/form-context';\nimport { FormField, type FormFieldProps } from './form';\nimport { SelectPopover, SelectTrigger } from './select';\n\n/**\n * Minimal resource shape used by the ID search inputs.\n * Only `id` and `name` are required.\n *\n * @example\n * const user: BaseSearchableResource = { id: 'u_123', name: 'Nabeel Farooq' };\n */\ntype BaseSearchableResource = {\n /** Unique identifier used as the input value. */\n id: string;\n /** Human-readable label shown to users. */\n name: string;\n};\n\n/**\n * Type guard to check if a value is an array of searchable resources\n */\nfunction isSearchableResourceArray<T extends BaseSearchableResource>(value: unknown): value is T[] {\n return (\n Array.isArray(value) && value.every(item => item && typeof item === 'object' && 'id' in item && 'name' in item)\n );\n}\n\n/**\n * - Generic, accessible ID-search building block.\n * - Search (powered by react-query)\n * - Renders an accessible Autocomplete + Menu listbox\n * - Exposes a controlled `value`/`onChange` contract so callers (and wrappers) can manage state\n *\n * @template T - resource type extending `BaseSearchableResource` (must have `id` and `name`)\n * @template V - controlled value type (e.g. `string` for single-select or `string[]` for multi-select)\n *\n * @param props - props object (see inline property JSDoc for the most important fields)\n *\n * @remarks\n * - Search is automatically handled based on the `resource` prop using the API client from context\n * - When the popover closes, `onBlur` (if provided) is called with the current `value`.\n * - `renderLabel` must convert `value` to a readable string for the control button.\n * - `defaultParams` can be used to pass additional query parameters to the search endpoint\n *\n * @example\n * <BaseIdSearchInput\n * label=\"Owner\"\n * resource=\"user\"\n * value={ownerId}\n * onChange={setOwnerId}\n * renderLabel={(v, data) => data?.find(d => d.id === v)?.name ?? v}\n * />\n *\n * @testing\n * - Ensure API client is provided via context; assert keyboard navigation, open/close behavior, and `onBlur` call on popover close.\n */\nfunction BaseIdSearchInput<T extends BaseSearchableResource, V>({\n label,\n description,\n errorMessage,\n requiredIndicator,\n isDisabled,\n isInvalid,\n onBlur,\n path,\n onChange,\n value,\n renderLabel,\n accessor,\n defaultParams,\n className,\n ...props\n}: FormFieldProps & {\n path: ClientPathsWithMethod<CtxClientType, 'get'>;\n /** Disable interactions. */\n isDisabled?: boolean;\n /** Whether the field is invalid. */\n isInvalid?: boolean;\n /** Key used to access an alternate display accessor on item (kept for compatibility). */\n accessor: keyof BaseSearchableResource;\n /** Controlled value. */\n value: V;\n /** Called when popover closes or the field blurs with the current value. */\n onBlur?: (v: V) => void;\n /** Controlled change handler. */\n onChange: (v: V) => void;\n /** Render a human-readable label for the current value using the latest data. */\n renderLabel: (v: V, data: T[] | undefined) => string;\n /** Default parameters to include in the request. This is useful when using /v3/users?role='admin' or /v3/organizations/ID/user-groups */\n defaultParams?: Record<'path' | 'query', any>;\n /** Optional className to customize the trigger button styling. */\n className?: string;\n} & Omit<React.ComponentProps<typeof Menu>, 'items' | 'className'>) {\n if (path === '/v3/me') {\n throw Error('Path \"/v3/me\" is not supported with IdSearch since it is not a searchable resource.');\n }\n\n const generatedId = useId();\n const fieldId = props.id || generatedId;\n const client = useCtxClient();\n\n const [search, _setSearch] = useState('');\n const { data, isError, isFetching, error } = useQuery({\n // This is the schema that openapi-react-query follows as of 0.5.1\n queryKey: ['get', path],\n queryFn: async (): Promise<T[]> => {\n const result = await client.GET(path, {\n params: {\n query: {\n search,\n ...defaultParams?.query,\n },\n path: {\n ...defaultParams?.path,\n },\n },\n });\n\n // Type narrowing: result.data is inferred as never due to complex union types\n // We use unknown to bypass this and then validate with our type guard\n const responseData: unknown = result.data;\n if (responseData && isSearchableResourceArray<T>(responseData)) {\n return responseData;\n }\n return [];\n },\n });\n\n return (\n <div className=\"group form-field\" data-invalid={isInvalid ? '' : undefined}>\n <FormField {...{ label, description, errorMessage, requiredIndicator, htmlFor: fieldId }}>\n <AriaSelect isInvalid={isInvalid}>\n <PopoverTrigger\n onOpenChange={o => {\n if (!o) {\n // searchInputRef.current?.focus();\n onBlur?.(value);\n }\n }}\n >\n <SelectTrigger id={fieldId} isDisabled={isDisabled} className={className ?? 'w-full'}>\n {renderLabel(value, data)}\n </SelectTrigger>\n <SelectPopover placement=\"bottom start\">\n <Autocomplete inputValue={search} onInputChange={_setSearch}>\n <SearchField className={'p-2'} autoFocus />\n {isFetching && (\n <div className=\"p-input\">\n <Loader className=\"mx-auto\" />\n </div>\n )}\n {!isFetching && !isError && (\n <Menu\n {...props}\n className={'max-h-48'}\n items={data}\n renderEmptyState={() => <div className=\"body-sm p-2\">No results found.</div>}\n >\n {item => (\n <MenuItem key={item[accessor]} id={item[accessor]}>\n {item.name}\n </MenuItem>\n )}\n </Menu>\n )}\n {isError && <div className=\"text-destructive p-icon body-sm\">{error.message}</div>}\n </Autocomplete>\n </SelectPopover>\n </PopoverTrigger>\n </AriaSelect>\n </FormField>\n </div>\n );\n}\n\n/**\n * Single-selection ID search input.\n *\n * Thin, typed wrapper around `BaseIdSearchInput` specialized for the very common single-ID case.\n * Adapts the internal selection events into `onChange(id?: string)` and renders the selected label.\n *\n * @template T - resource type (extends BaseSearchableResource)\n *\n * @param props - Inherits `BaseIdSearchInput` props but uses `string[]` value type.\n *\n * @example\n * <SingleIdSearchInput\n * label=\"Reporter\"\n * value={reporterId}\n * onChange={setReporterId}\n * />\n *\n */\nexport function SingleIdSearchInput<T extends BaseSearchableResource>({\n ...props\n}: Omit<\n React.ComponentProps<typeof BaseIdSearchInput<T, string>>,\n 'onSelectionChange' | 'selectionMode' | 'selectedKeys' | 'renderLabel'\n>) {\n return (\n <BaseIdSearchInput\n selectedKeys={[props.value]}\n onSelectionChange={e => props.onChange(Array.from(e).filter(v => typeof v === 'string')[0])}\n renderLabel={(v, d) => d?.find(di => di.id === v)?.name ?? v}\n selectionMode=\"single\"\n {...props}\n />\n );\n}\n\n/**\n * Multi-selection ID search input.\n *\n * Thin wrapper around `BaseIdSearchInput` for the multiple-ID (`string[]`) case.\n * Adapts internal selection events into `onChange(ids: string[])`.\n *\n * @template T - resource type (extends BaseSearchableResource)\n *\n * @param props - Inherits `BaseIdSearchInput` props but uses `string[]` value type.\n *\n * @example\n * <MultipleIdSearchInput\n * label=\"Reviewers\"\n * value={reviewerIds}\n * onChange={setReviewerIds}\n * />\n *\n * @remarks\n * - The `renderLabel` joins selected item names with commas for compact display.\n */\nexport function MultipleIdSearchInput<T extends BaseSearchableResource>({\n ...props\n}: Omit<\n React.ComponentProps<typeof BaseIdSearchInput<T, string[]>>,\n 'renderLabel' | 'onSelectionChange' | 'selectionMode' | 'selectedKeys'\n>) {\n return (\n <BaseIdSearchInput\n selectedKeys={props.value}\n onSelectionChange={e => props.onChange(Array.from(e).filter(v => typeof v === 'string'))}\n selectionMode=\"multiple\"\n renderLabel={(v, d) => v?.map(vi => d?.find(di => di.id === vi)?.name ?? vi).join(',')}\n {...props}\n />\n );\n}\n\n/**\n * Form-integrated single-select ID input (field wrapper).\n *\n * Integrates `SingleIdSearchInput` into the form system using `useFieldContext`.\n * - wires `value`, `onChange`, and `onBlur`\n * - disables the control while the form is submitting\n * - surfaces field-level error messages\n *\n * @example\n * <TfSingleIdSearchInput name=\"ownerId\" label=\"Owner\" />\n \n */\nexport function TfSingleIdSearchInput({\n isDisabled,\n ...props\n}: Omit<React.ComponentProps<typeof SingleIdSearchInput>, 'value' | 'onChange' | 'onBlur'>) {\n const field = useFieldContext<string>({ disabled: isDisabled });\n return (\n <SingleIdSearchInput\n requiredIndicator={field.isRequired}\n isDisabled={isDisabled || field.form.state.isSubmitting}\n value={field.state.value}\n onBlur={_ => field.handleBlur()}\n onChange={e => field.handleChange(e)}\n isInvalid={!!getFieldErrorMessage(field)}\n errorMessage={getFieldErrorMessage(field)}\n {...props}\n />\n );\n}\n\n/**\n * Form-integrated multi-select ID input (field wrapper).\n *\n * Integrates `MultipleIdSearchInput` into the form system using `useFieldContext`.\n * - wires `value`, `onChange`, and `onBlur`\n * - disables the control while the form is submitting\n * - surfaces field-level error messages\n *\n * @example\n * <TfMultipleIdSearchInput name=\"reviewerIds\" label=\"Reviewers\" />\n *\n */\nexport function TfMultipleIdSearchInput({\n isDisabled,\n ...props\n}: Omit<React.ComponentProps<typeof MultipleIdSearchInput>, 'value' | 'onChange'>) {\n const field = useFieldContext<string[]>({ disabled: isDisabled });\n return (\n <MultipleIdSearchInput\n requiredIndicator={field.isRequired}\n isDisabled={isDisabled || field.form.state.isSubmitting}\n value={field.state.value}\n onBlur={_ => field.handleBlur()}\n onChange={e => field.handleChange(e)}\n isInvalid={!!getFieldErrorMessage(field)}\n errorMessage={getFieldErrorMessage(field)}\n {...props}\n />\n );\n}\n"],"names":["isSearchableResourceArray","value","item","BaseIdSearchInput","label","description","errorMessage","requiredIndicator","isDisabled","isInvalid","onBlur","path","onChange","renderLabel","accessor","defaultParams","className","props","generatedId","useId","fieldId","client","useCtxClient","search","_setSearch","useState","data","isError","isFetching","error","useQuery","responseData","jsx","FormField","AriaSelect","jsxs","PopoverTrigger","SelectTrigger","SelectPopover","Autocomplete","SearchField","Loader","Menu","MenuItem","SingleIdSearchInput","e","v","d","di","MultipleIdSearchInput","vi","TfSingleIdSearchInput","field","useFieldContext","_","getFieldErrorMessage","TfMultipleIdSearchInput"],"mappings":"80BAiCA,SAASA,EAA4DC,EAA8B,CAC/F,OACI,MAAM,QAAQA,CAAK,GAAKA,EAAM,MAAMC,GAAQA,GAAQ,OAAOA,GAAS,UAAY,OAAQA,GAAQ,SAAUA,CAAI,CAEtH,CA+BA,SAASC,EAAuD,CAC5D,MAAAC,EACA,YAAAC,EACA,aAAAC,EACA,kBAAAC,EACA,WAAAC,EACA,UAAAC,EACA,OAAAC,EACA,KAAAC,EACA,SAAAC,EACA,MAAAX,EACA,YAAAY,EACA,SAAAC,EACA,cAAAC,EACA,UAAAC,EACA,GAAGC,CACP,EAoBoE,CAChE,GAA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KAAK,MAAM,aAC3C,MAAOA,EAAM,MAAM,MACnB,OAAQE,GAAKF,EAAM,WAAA,EACnB,SAAUP,GAAKO,EAAM,aAAaP,CAAC,EACnC,UAAW,CAAC,CAACU,EAAqBH,CAAK,EACvC,aAAcG,EAAqBH,CAAK,EACvC,GAAGnC,CAAA,CAAA,CAGhB,CAcO,SAASuC,GAAwB,CACpC,WAAAhD,EACA,GAAGS,CACP,EAAmF,CAC/E,MAAMmC,EAAQC,EAA0B,CAAE,SAAU7C,EAAY,EAChE,OACIwB,EAACiB,EAAA,CACG,kBAAmBG,EAAM,WACzB,WAAY5C,GAAc4C,EAAM,KAAK,MAAM,aAC3C,MAAOA,EAAM,MAAM,MACnB,OAAQE,GAAKF,EAAM,WAAA,EACnB,SAAUP,GAAKO,EAAM,aAAaP,CAAC,EACnC,UAAW,CAAC,CAACU,EAAqBH,CAAK,EACvC,aAAcG,EAAqBH,CAAK,EACvC,GAAGnC,CAAA,CAAA,CAGhB"}
|
|
1
|
+
{"version":3,"file":"id-search.js","sources":["../../lib/components/id-search.tsx"],"sourcesContent":["'use client';\nimport { useQuery } from '@tanstack/react-query';\nimport { useId, useState } from 'react';\nimport { Select as AriaSelect, Autocomplete } from 'react-aria-components';\n\nimport type { ClientPathsWithMethod } from 'openapi-fetch';\nimport { Loader } from '../components/loader';\nimport { Menu, MenuItem } from '../components/menu';\nimport { PopoverTrigger } from '../components/popover';\nimport { SearchField } from '../components/searchfield';\nimport { useCtxClient, type CtxClientType } from '../utilities/ctx-client';\nimport { getEmptyLabel, isEmptyValue, type EmptyOption } from '../utilities/empty-option';\nimport { getFieldErrorMessage } from '../utilities/form';\nimport { useFieldContext } from '../utilities/form-context';\nimport { FormField, type FormFieldProps } from './form';\nimport { SelectPopover, SelectTrigger } from './select';\n\n/**\n * Minimal resource shape used by the ID search inputs.\n * Only `id` and `name` are required.\n *\n * @example\n * const user: BaseSearchableResource = { id: 'u_123', name: 'Nabeel Farooq' };\n */\ntype BaseSearchableResource = {\n /** Unique identifier used as the input value. */\n id: string;\n /** Human-readable label shown to users. */\n name: string;\n};\n\n/**\n * Type guard to check if a value is an array of searchable resources\n */\nfunction isSearchableResourceArray<T extends BaseSearchableResource>(value: unknown): value is T[] {\n return (\n Array.isArray(value) && value.every(item => item && typeof item === 'object' && 'id' in item && 'name' in item)\n );\n}\n\n/**\n * - Generic, accessible ID-search building block.\n * - Search (powered by react-query)\n * - Renders an accessible Autocomplete + Menu listbox\n * - Exposes a controlled `value`/`onChange` contract so callers (and wrappers) can manage state\n *\n * @template T - resource type extending `BaseSearchableResource` (must have `id` and `name`)\n * @template V - controlled value type (e.g. `string` for single-select or `string[]` for multi-select)\n *\n * @param props - props object (see inline property JSDoc for the most important fields)\n *\n * @remarks\n * - Search is automatically handled based on the `resource` prop using the API client from context\n * - When the popover closes, `onBlur` (if provided) is called with the current `value`.\n * - `renderLabel` must convert `value` to a readable string for the control button.\n * - `defaultParams` can be used to pass additional query parameters to the search endpoint\n *\n * @example\n * <BaseIdSearchInput\n * label=\"Owner\"\n * resource=\"user\"\n * value={ownerId}\n * onChange={setOwnerId}\n * renderLabel={(v, data) => data?.find(d => d.id === v)?.name ?? v}\n * />\n *\n * @testing\n * - Ensure API client is provided via context; assert keyboard navigation, open/close behavior, and `onBlur` call on popover close.\n */\nfunction BaseIdSearchInput<T extends BaseSearchableResource, V>({\n label,\n description,\n errorMessage,\n requiredIndicator,\n isDisabled,\n isInvalid,\n onBlur,\n path,\n onChange,\n value,\n renderLabel,\n accessor,\n defaultParams,\n className,\n emptyOption,\n ...props\n}: FormFieldProps & {\n path: ClientPathsWithMethod<CtxClientType, 'get'>;\n /** Disable interactions. */\n isDisabled?: boolean;\n /** Whether the field is invalid. */\n isInvalid?: boolean;\n /** Key used to access an alternate display accessor on item (kept for compatibility). */\n accessor: keyof BaseSearchableResource;\n /** Controlled value. */\n value: V;\n /** Called when popover closes or the field blurs with the current value. */\n onBlur?: (v: V) => void;\n /** Controlled change handler. */\n onChange: (v: V) => void;\n /** Render a human-readable label for the current value using the latest data. */\n renderLabel: (v: V, data: T[] | undefined, emptyOption?: EmptyOption) => string;\n /** Default parameters to include in the request. This is useful when using /v3/users?role='admin' or /v3/organizations/ID/user-groups */\n defaultParams?: Record<'path' | 'query', any>;\n /** Optional className to customize the trigger button styling. */\n className?: string;\n /* Optional empty option to show when value is empty. */\n emptyOption?: EmptyOption;\n} & Omit<React.ComponentProps<typeof Menu>, 'items' | 'className'>) {\n if (path === '/v3/me') {\n throw Error('Path \"/v3/me\" is not supported with IdSearch since it is not a searchable resource.');\n }\n\n const generatedId = useId();\n const fieldId = props.id || generatedId;\n const client = useCtxClient();\n\n const [search, _setSearch] = useState('');\n const { data, isError, isFetching, error } = useQuery({\n // This is the schema that openapi-react-query follows as of 0.5.1\n queryKey: ['get', path],\n queryFn: async (): Promise<T[]> => {\n const result = await client.GET(path, {\n params: {\n query: {\n search,\n ...defaultParams?.query,\n },\n path: {\n ...defaultParams?.path,\n },\n },\n });\n\n // Type narrowing: result.data is inferred as never due to complex union types\n // We use unknown to bypass this and then validate with our type guard\n const responseData: unknown = result.data;\n if (responseData && isSearchableResourceArray<T>(responseData)) {\n return responseData;\n }\n return [];\n },\n });\n\n return (\n <div className=\"group form-field\" data-invalid={isInvalid ? '' : undefined}>\n <FormField {...{ label, description, errorMessage, requiredIndicator, htmlFor: fieldId }}>\n <AriaSelect isInvalid={isInvalid}>\n <PopoverTrigger\n onOpenChange={o => {\n if (!o) {\n // searchInputRef.current?.focus();\n onBlur?.(value);\n }\n }}\n >\n <SelectTrigger id={fieldId} isDisabled={isDisabled} className={className ?? 'w-full'}>\n {renderLabel(value, data, emptyOption)}\n </SelectTrigger>\n <SelectPopover placement=\"bottom start\">\n <Autocomplete inputValue={search} onInputChange={_setSearch}>\n <SearchField className={'p-2'} autoFocus />\n {isFetching && (\n <div className=\"p-input\">\n <Loader className=\"mx-auto\" />\n </div>\n )}\n {!isFetching && !isError && (\n <Menu\n {...props}\n className={'max-h-48'}\n items={data}\n renderEmptyState={() => <div className=\"body-sm p-2\">No results found.</div>}\n >\n {item => (\n <MenuItem key={item[accessor]} id={item[accessor]}>\n {item.name}\n </MenuItem>\n )}\n </Menu>\n )}\n {isError && <div className=\"text-destructive p-icon body-sm\">{error.message}</div>}\n </Autocomplete>\n </SelectPopover>\n </PopoverTrigger>\n </AriaSelect>\n </FormField>\n </div>\n );\n}\n\n/**\n * Single-selection ID search input.\n *\n * Thin, typed wrapper around `BaseIdSearchInput` specialized for the very common single-ID case.\n * Adapts the internal selection events into `onChange(id?: string)` and renders the selected label.\n *\n * @template T - resource type (extends BaseSearchableResource)\n *\n * @param props - Inherits `BaseIdSearchInput` props but uses `string[]` value type.\n *\n * @example\n * <SingleIdSearchInput\n * label=\"Reporter\"\n * value={reporterId}\n * onChange={setReporterId}\n * />\n *\n */\nexport function SingleIdSearchInput<T extends BaseSearchableResource>({\n ...props\n}: Omit<\n React.ComponentProps<typeof BaseIdSearchInput<T, string | null>>,\n 'onSelectionChange' | 'selectionMode' | 'selectedKeys' | 'renderLabel'\n>) {\n const selectedKeys = props.value ? [props.value] : [];\n\n return (\n <BaseIdSearchInput\n selectedKeys={selectedKeys}\n onSelectionChange={e => {\n const val = Array.from(e).filter(v => typeof v === 'string')[0];\n props.onChange(val);\n }}\n renderLabel={(v, d, emptyOption) => {\n // If value is empty and emptyOption is set, show the empty label\n if (emptyOption && isEmptyValue(v)) {\n return getEmptyLabel(emptyOption);\n }\n return d?.find(di => di.id === v)?.name ?? '';\n }}\n selectionMode=\"single\"\n {...props}\n />\n );\n}\n\n/**\n * Multi-selection ID search input.\n *\n * Thin wrapper around `BaseIdSearchInput` for the multiple-ID (`string[]`) case.\n * Adapts internal selection events into `onChange(ids: string[])`.\n *\n * @template T - resource type (extends BaseSearchableResource)\n *\n * @param props - Inherits `BaseIdSearchInput` props but uses `string[]` value type.\n *\n * @example\n * <MultipleIdSearchInput\n * label=\"Reviewers\"\n * value={reviewerIds}\n * onChange={setReviewerIds}\n * />\n *\n * @remarks\n * - The `renderLabel` joins selected item names with commas for compact display.\n */\nexport function MultipleIdSearchInput<T extends BaseSearchableResource>({\n ...props\n}: Omit<\n React.ComponentProps<typeof BaseIdSearchInput<T, string[]>>,\n 'renderLabel' | 'onSelectionChange' | 'selectionMode' | 'selectedKeys'\n>) {\n const selectedKeys = props.value;\n\n return (\n <BaseIdSearchInput\n selectedKeys={selectedKeys}\n onSelectionChange={e => {\n const vals = Array.from(e).filter(v => typeof v === 'string');\n props.onChange(vals.length > 0 ? vals : []);\n }}\n selectionMode=\"multiple\"\n renderLabel={(v, d, emptyOption) => {\n // If array is empty and emptyOption is set, show the empty label\n if (emptyOption && (!v || v.length === 0)) {\n return getEmptyLabel(emptyOption);\n }\n\n const values = v ?? [];\n const labels = values.map(vi => {\n return d?.find(di => di.id === vi)?.name ?? vi;\n });\n return labels.length > 0 ? labels.join(',') : '';\n }}\n {...props}\n />\n );\n}\n\n/**\n * Form-integrated single-select ID input (field wrapper).\n *\n * Integrates `SingleIdSearchInput` into the form system using `useFieldContext`.\n * - wires `value`, `onChange`, and `onBlur`\n * - disables the control while the form is submitting\n * - surfaces field-level error messages\n *\n * @example\n * <TfSingleIdSearchInput name=\"ownerId\" label=\"Owner\" />\n \n */\nexport function TfSingleIdSearchInput({\n isDisabled,\n ...props\n}: Omit<React.ComponentProps<typeof SingleIdSearchInput>, 'value' | 'onChange' | 'onBlur'>) {\n const field = useFieldContext<string | null>({ disabled: isDisabled });\n return (\n <SingleIdSearchInput\n requiredIndicator={field.isRequired}\n isDisabled={isDisabled || field.form.state.isSubmitting}\n value={field.state.value}\n onBlur={_ => field.handleBlur()}\n onChange={e => field.handleChange(e)}\n isInvalid={!!getFieldErrorMessage(field)}\n errorMessage={getFieldErrorMessage(field)}\n {...props}\n />\n );\n}\n\n/**\n * Form-integrated multi-select ID input (field wrapper).\n *\n * Integrates `MultipleIdSearchInput` into the form system using `useFieldContext`.\n * - wires `value`, `onChange`, and `onBlur`\n * - disables the control while the form is submitting\n * - surfaces field-level error messages\n *\n * @example\n * <TfMultipleIdSearchInput name=\"reviewerIds\" label=\"Reviewers\" />\n *\n */\nexport function TfMultipleIdSearchInput({\n isDisabled,\n ...props\n}: Omit<React.ComponentProps<typeof MultipleIdSearchInput>, 'value' | 'onChange'>) {\n const field = useFieldContext<string[]>({ disabled: isDisabled });\n return (\n <MultipleIdSearchInput\n requiredIndicator={field.isRequired}\n isDisabled={isDisabled || field.form.state.isSubmitting}\n value={field.state.value}\n onBlur={_ => field.handleBlur()}\n onChange={e => field.handleChange(e)}\n isInvalid={!!getFieldErrorMessage(field)}\n errorMessage={getFieldErrorMessage(field)}\n {...props}\n />\n );\n}\n"],"names":["isSearchableResourceArray","value","item","BaseIdSearchInput","label","description","errorMessage","requiredIndicator","isDisabled","isInvalid","onBlur","path","onChange","renderLabel","accessor","defaultParams","className","emptyOption","props","generatedId","useId","fieldId","client","useCtxClient","search","_setSearch","useState","data","isError","isFetching","error","useQuery","responseData","jsx","FormField","AriaSelect","jsxs","PopoverTrigger","o","SelectTrigger","SelectPopover","Autocomplete","SearchField","Loader","Menu","MenuItem","SingleIdSearchInput","selectedKeys","val","v","d","isEmptyValue","getEmptyLabel","di","MultipleIdSearchInput","vals","labels","vi","TfSingleIdSearchInput","field","useFieldContext","_","e","getFieldErrorMessage","TfMultipleIdSearchInput"],"mappings":"65BAkCA,SAASA,EAA4DC,EAA8B,CAC/F,OACI,MAAM,QAAQA,CAAK,GAAKA,EAAM,MAAMC,GAAQA,GAAQ,OAAOA,GAAS,UAAY,OAAQA,GAAQ,SAAUA,CAAI,CAEtH,CA+BA,SAASC,EAAuD,CAC5D,MAAAC,EACA,YAAAC,EACA,aAAAC,EACA,kBAAAC,EACA,WAAAC,EACA,UAAAC,EACA,OAAAC,EACA,KAAAC,EACA,SAAAC,EACA,MAAAX,EACA,YAAAY,EACA,SAAAC,EACA,cAAAC,EACA,UAAAC,EACA,YAAAC,EACA,GAAGC,CACP,EAsBoE,CAChE,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nC,CAAW,EAIpC,MAAMuC,GADSP,GAAK,CAAA,GACE,IAAIQ,GACfP,GAAG,KAAKG,GAAMA,EAAG,KAAOI,CAAE,GAAG,MAAQA,CAC/C,EACD,OAAOD,EAAO,OAAS,EAAIA,EAAO,KAAK,GAAG,EAAI,EAClD,EACC,GAAGtC,CAAA,CAAA,CAGhB,CAcO,SAASwC,GAAsB,CAClC,WAAAlD,EACA,GAAGU,CACP,EAA4F,CACxF,MAAMyC,EAAQC,EAA+B,CAAE,SAAUpD,EAAY,EACrE,OACIyB,EAACa,EAAA,CACG,kBAAmBa,EAAM,WACzB,WAAYnD,GAAcmD,EAAM,KAAK,MAAM,aAC3C,MAAOA,EAAM,MAAM,MACnB,OAAQE,GAAKF,EAAM,WAAA,EACnB,SAAUG,GAAKH,EAAM,aAAaG,CAAC,EACnC,UAAW,CAAC,CAACC,EAAqBJ,CAAK,EACvC,aAAcI,EAAqBJ,CAAK,EACvC,GAAGzC,CAAA,CAAA,CAGhB,CAcO,SAAS8C,GAAwB,CACpC,WAAAxD,EACA,GAAGU,CACP,EAAmF,CAC/E,MAAMyC,EAAQC,EAA0B,CAAE,SAAUpD,EAAY,EAChE,OACIyB,EAACqB,EAAA,CACG,kBAAmBK,EAAM,WACzB,WAAYnD,GAAcmD,EAAM,KAAK,MAAM,aAC3C,MAAOA,EAAM,MAAM,MACnB,OAAQE,GAAKF,EAAM,WAAA,EACnB,SAAUG,GAAKH,EAAM,aAAaG,CAAC,EACnC,UAAW,CAAC,CAACC,EAAqBJ,CAAK,EACvC,aAAcI,EAAqBJ,CAAK,EACvC,GAAGzC,CAAA,CAAA,CAGhB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multi-select.js","sources":["../../lib/components/multi-select.tsx"],"sourcesContent":["'use client';\nimport React, { useId } from 'react';\nimport { EasyMenu, MenuItem } from '../components/menu';\nimport type { SelectOption } from '../components/select-options';\nimport { getFieldErrorMessage } from '../utilities/form';\nimport { useFieldContext } from '../utilities/form-context';\nimport { FormField, type FormFieldProps } from './form';\
|
|
1
|
+
{"version":3,"file":"multi-select.js","sources":["../../lib/components/multi-select.tsx"],"sourcesContent":["'use client';\nimport React, { useId } from 'react';\nimport { EasyMenu, MenuItem } from '../components/menu';\nimport type { SelectOption } from '../components/select-options';\nimport { getFieldErrorMessage } from '../utilities/form';\nimport { useFieldContext } from '../utilities/form-context';\nimport { FormField, type FormFieldProps } from './form';\ninterface MultipleSelectionProps {\n value: Set<string | number>;\n onChange: (v: Set<string | number>) => void;\n buttonLabel?: React.ReactNode;\n items: SelectOption[];\n}\n\nexport interface MultiSelectProps\n extends MultipleSelectionProps,\n FormFieldProps,\n Omit<React.ComponentProps<typeof EasyMenu>, 'label' | 'items'> {\n triggerLabel?: React.ReactNode;\n}\n\nexport function MultiSelect({\n items,\n value,\n onChange: setValue,\n label,\n errorMessage,\n description,\n requiredIndicator,\n ...props\n}: MultiSelectProps) {\n const generatedId = useId();\n const fieldId = props.id || generatedId;\n\n return (\n <div className=\"group form-field\">\n <FormField {...{ label, description, errorMessage, requiredIndicator, htmlFor: fieldId }}>\n <EasyMenu\n id={fieldId}\n isNonModal={false}\n selectionMode=\"multiple\"\n selectedKeys={value}\n onSelectionChange={v => {\n if (typeof v === 'string') return;\n setValue(v);\n }}\n items={items}\n label={props.triggerLabel ?? <span className=\"tabular-nums\">{value.size}</span>}\n {...props}\n >\n {item => (\n <MenuItem id={item.id} key={item.id} isDisabled={item?.disabled}>\n {item.label}\n </MenuItem>\n )}\n </EasyMenu>\n </FormField>\n </div>\n );\n}\n\nexport interface TfMultiSelectProps extends Omit<MultiSelectProps, 'value' | 'onChange'> {}\nexport function TfMultiSelect({ ...props }: TfMultiSelectProps) {\n const field = useFieldContext<string[]>({\n disabled: props.isDisabled,\n });\n\n return (\n <MultiSelect\n requiredIndicator={field.isRequired}\n value={new Set(field.state.value)}\n // @ts-expect-error\n onChange={e => field.setValue(Array.from(e))}\n onClose={field.handleBlur}\n errorMessage={getFieldErrorMessage(field)}\n {...props}\n />\n );\n}\n"],"names":["MultiSelect","items","value","setValue","label","errorMessage","description","requiredIndicator","props","generatedId","useId","fieldId","jsx","FormField","EasyMenu","v","item","MenuItem","TfMultiSelect","field","useFieldContext","e","getFieldErrorMessage"],"mappings":"wiBAqBO,SAASA,EAAY,CACxB,MAAAC,EACA,MAAAC,EACA,SAAUC,EACV,MAAAC,EACA,aAAAC,EACA,YAAAC,EACA,kBAAAC,EACA,GAAGC,CACP,EAAqB,CACjB,MAAMC,EAAcC,EAAA,EACdC,EAAUH,EAAM,IAAMC,EAE5B,OACIG,EAAC,MAAA,CAAI,UAAU,mBACX,WAACC,EAAA,CAAgB,MAAAT,EAAO,YAAAE,EAAa,aAAAD,EAAc,kBAAAE,EAAmB,QAASI,EAC3E,SAAAC,EAACE,EAAA,CACG,GAAIH,EACJ,WAAY,GACZ,cAAc,WACd,aAAcT,EACd,kBAAmBa,GAAK,CAChB,OAAOA,GAAM,UACjBZ,EAASY,CAAC,CACd,EACA,MAAAd,EACA,MAAOO,EAAM,cAAgBI,EAAC,QAAK,UAAU,eAAgB,WAAM,IAAA,CAAK,EACvE,GAAGJ,EAEH,SAAAQ,GACGJ,EAACK,EAAA,CAAS,GAAID,EAAK,GAAkB,WAAYA,GAAM,SAClD,SAAAA,EAAK,KAAA,EADkBA,EAAK,EAEjC,CAAA,CAAA,EAGZ,CAAA,CACJ,CAER,CAGO,SAASE,EAAc,CAAE,GAAGV,GAA6B,CAC5D,MAAMW,EAAQC,EAA0B,CACpC,SAAUZ,EAAM,UAAA,CACnB,EAED,OACII,EAACZ,EAAA,CACG,kBAAmBmB,EAAM,WACzB,MAAO,IAAI,IAAIA,EAAM,MAAM,KAAK,EAEhC,SAAUE,GAAKF,EAAM,SAAS,MAAM,KAAKE,CAAC,CAAC,EAC3C,QAASF,EAAM,WACf,aAAcG,EAAqBH,CAAK,EACvC,GAAGX,CAAA,CAAA,CAGhB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"empty-option.js","sources":["../../lib/utilities/empty-option.ts"],"sourcesContent":["export type EmptyOption = 'none' | 'all' | 'empty';\n\nexport function getEmptyLabel(option: EmptyOption): string {\n switch (option) {\n case 'all':\n return 'All';\n case 'none':\n return 'None';\n case 'empty':\n return 'Empty';\n }\n}\n\nexport function isEmptyValue(value: unknown): boolean {\n return value === null || value === undefined || value === '' || (Array.isArray(value) && value.length === 0);\n}\n"],"names":["getEmptyLabel","option","isEmptyValue","value"],"mappings":"AAEO,SAASA,EAAcC,EAA6B,CACvD,OAAQA,EAAA,CACJ,IAAK,MACD,MAAO,MACX,IAAK,OACD,MAAO,OACX,IAAK,QACD,MAAO,OAAA,CAEnB,CAEO,SAASC,EAAaC,EAAyB,CAClD,OAAOA,GAAU,MAA+BA,IAAU,IAAO,MAAM,QAAQA,CAAK,GAAKA,EAAM,SAAW,CAC9G"}
|
|
@@ -3,8 +3,3 @@
|
|
|
3
3
|
*/
|
|
4
4
|
export declare function toTitleCase(input?: string): string;
|
|
5
5
|
export declare function pluralizeTimes(resourceName: string, count: number): string;
|
|
6
|
-
/**
|
|
7
|
-
* Normalizes a label string by trimming, lowercasing, and replacing whitespace with hyphens.
|
|
8
|
-
* Used for generating consistent IDs from user-facing labels.
|
|
9
|
-
*/
|
|
10
|
-
export declare function normalizeLabel(label: string): string;
|
package/dist/utilities/string.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{startCase as
|
|
1
|
+
import{startCase as n}from"lodash-es";function f(t){return n(t)}function a(t,i){return i>1?/y$/.test(t)?t==="Day"?"Days":t.replace(/y$/,"ies"):t.concat("s"):t}export{a as pluralizeTimes,f as toTitleCase};
|
|
2
2
|
//# sourceMappingURL=string.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string.js","sources":["../../lib/utilities/string.ts"],"sourcesContent":["import { startCase } from 'lodash-es';\n\n/**\n *\n */\nexport function toTitleCase(input?: string): string {\n return startCase(input);\n}\n\nexport function pluralizeTimes(resourceName: string, count: number) {\n if (count > 1) {\n if (/y$/.test(resourceName)) {\n if (resourceName === 'Day') return 'Days';\n return resourceName.replace(/y$/, 'ies');\n }\n return resourceName.concat('s');\n }\n return resourceName;\n}\n
|
|
1
|
+
{"version":3,"file":"string.js","sources":["../../lib/utilities/string.ts"],"sourcesContent":["import { startCase } from 'lodash-es';\n\n/**\n *\n */\nexport function toTitleCase(input?: string): string {\n return startCase(input);\n}\n\nexport function pluralizeTimes(resourceName: string, count: number) {\n if (count > 1) {\n if (/y$/.test(resourceName)) {\n if (resourceName === 'Day') return 'Days';\n return resourceName.replace(/y$/, 'ies');\n }\n return resourceName.concat('s');\n }\n return resourceName;\n}\n"],"names":["toTitleCase","input","startCase","pluralizeTimes","resourceName","count"],"mappings":"sCAKO,SAASA,EAAYC,EAAwB,CAChD,OAAOC,EAAUD,CAAK,CAC1B,CAEO,SAASE,EAAeC,EAAsBC,EAAe,CAChE,OAAIA,EAAQ,EACJ,KAAK,KAAKD,CAAY,EAClBA,IAAiB,MAAc,OAC5BA,EAAa,QAAQ,KAAM,KAAK,EAEpCA,EAAa,OAAO,GAAG,EAE3BA,CACX"}
|
package/lib/index.css
CHANGED
|
@@ -144,7 +144,7 @@
|
|
|
144
144
|
|
|
145
145
|
/* A base set of classes for elements that can be clicked */
|
|
146
146
|
@utility btn {
|
|
147
|
-
@apply inline-flex body-sm gap-1 disabled:pointer-events-none text-ellipsis overflow-hidden items-center justify-center font-medium transition-colors cursor-pointer ring-offset-background [&_svg:not([class*='size-'])]:size-icon shrink-0 [&_svg]:shrink-0 [&_svg]:opacity-70 leading-
|
|
147
|
+
@apply inline-flex body-sm gap-1 disabled:pointer-events-none text-ellipsis overflow-hidden items-center justify-center font-medium transition-colors cursor-pointer ring-offset-background [&_svg:not([class*='size-'])]:size-icon shrink-0 [&_svg]:shrink-0 [&_svg]:opacity-70 leading-tight outline-none no-underline whitespace-nowrap select-none disabled-muted focus-ring;
|
|
148
148
|
}
|
|
149
149
|
|
|
150
150
|
@utility btn-link {
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
}
|
|
171
171
|
/* Dimensions for a standard input */
|
|
172
172
|
@utility input-dim {
|
|
173
|
-
@apply h-input px-2 py-2 body-sm leading-
|
|
173
|
+
@apply h-input px-2 py-2 body-sm leading-tight;
|
|
174
174
|
}
|
|
175
175
|
|
|
176
176
|
@utility form-field {
|
package/package.json
CHANGED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { default as React } from 'react';
|
|
2
|
-
import { PressEvent } from 'react-aria-components';
|
|
3
|
-
import { Button } from './button';
|
|
4
|
-
import { CtxIcon } from './icons';
|
|
5
|
-
export type TableActionDialogContentProps<T> = {
|
|
6
|
-
/** Callback to close the dialog */
|
|
7
|
-
close: () => void;
|
|
8
|
-
/** The data passed to the dialog - array of selected rows */
|
|
9
|
-
data: T[];
|
|
10
|
-
/** Flag to identify table action dialogs */
|
|
11
|
-
tableAction: true;
|
|
12
|
-
};
|
|
13
|
-
/** Base properties shared by all table actions */
|
|
14
|
-
export type TableActionBase<T> = {
|
|
15
|
-
label: string;
|
|
16
|
-
/** Optional function to determine if the action is disabled. Receives the rows and returns a boolean. Defaults to false if not provided */
|
|
17
|
-
isDisabled?: (rows: T[]) => boolean;
|
|
18
|
-
icon: CtxIcon;
|
|
19
|
-
bulk: boolean;
|
|
20
|
-
tooltip?: string;
|
|
21
|
-
/** Optional button variant to pass through to Button (defaults to neutral) */
|
|
22
|
-
variant?: React.ComponentProps<typeof Button>['variant'];
|
|
23
|
-
};
|
|
24
|
-
/** Action that triggers a callback */
|
|
25
|
-
export type TableActionAction<T> = TableActionBase<T> & {
|
|
26
|
-
type: 'action';
|
|
27
|
-
/** Callback triggered when the action is pressed. Receives the press event and selected rows as parameters */
|
|
28
|
-
onClick: (e: PressEvent, rows: T[]) => void;
|
|
29
|
-
};
|
|
30
|
-
/** Action that opens a dialog */
|
|
31
|
-
export type TableActionDialog<T> = TableActionBase<T> & {
|
|
32
|
-
type: 'dialog';
|
|
33
|
-
/** Component to render in the dialog */
|
|
34
|
-
component: React.ComponentType<TableActionDialogContentProps<T>>;
|
|
35
|
-
};
|
|
36
|
-
/** Common table action type that works for both action and dialog types */
|
|
37
|
-
export type TableAction<T> = TableActionAction<T> | TableActionDialog<T>;
|
|
38
|
-
export type TableActionsProps<T> = {
|
|
39
|
-
/** Array of table actions to render */
|
|
40
|
-
readonly items: TableAction<T>[];
|
|
41
|
-
/** Array of selected rows */
|
|
42
|
-
readonly rowsSelected: T[];
|
|
43
|
-
/** Whether the table is currently fetching data */
|
|
44
|
-
readonly isFetching?: boolean;
|
|
45
|
-
};
|
|
46
|
-
export declare function TableActions<T>({ items, rowsSelected, isFetching }: TableActionsProps<T>): import("react/jsx-runtime").JSX.Element;
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use client";import{jsxs as s,Fragment as b,jsx as r}from"react/jsx-runtime";import{normalizeLabel as d}from"../utilities/string.js";import{Button as g}from"./button.js";import{useDialogState as D,DialogActionRenderer as A,findItemByNormalizedLabel as y}from"./dialog-action-utils.js";import"lodash-es";import"class-variance-authority";import"react-aria-components";import"../utilities/theme.js";import"clsx";import"./loader.js";import"./icons.js";import"react";import"./dialog.js";function h(t){return t.type==="action"}function c(t){return t.type==="dialog"}function I(t,i){return t.isDisabled?t.isDisabled(i):!1}function k({items:t,rowsSelected:i,isFetching:p}){const{openKey:u,setOpenKey:e}=D();return s(b,{children:[t.map((n,o)=>{const a=d(n.label),f=n.icon,l=I(n,i)||p;return s(g,{"aria-label":n.label,type:"button",isDisabled:l,className:"animate-in fade-in slide-in-from-left-15 duration-300 transition-transform",onPress:m=>{l||(h(n)?n.onClick(m,i):c(n)&&e(a))},variant:n.variant??"neutral",children:[r(f,{}),r("span",{children:n.label})]},`${a}-${o}`)}),r(A,{openKey:u,onOpenChange:n=>{n||e(null)},findItem:n=>{const o=y(t,n);return!o||!c(o)?null:{component:o.component}},getDialogProps:n=>({data:i,tableAction:!0,close:n})})]})}export{k as TableActions};
|
|
2
|
-
//# sourceMappingURL=data-table-actions.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"data-table-actions.js","sources":["../../lib/components/data-table-actions.tsx"],"sourcesContent":["'use client';\nimport type React from 'react';\nimport type { PressEvent } from 'react-aria-components';\nimport { normalizeLabel } from '../utilities/string';\nimport { Button } from './button';\nimport { DialogActionRenderer, findItemByNormalizedLabel, useDialogState } from './dialog-action-utils';\nimport type { CtxIcon } from './icons';\n\nexport type TableActionDialogContentProps<T> = {\n /** Callback to close the dialog */\n close: () => void;\n /** The data passed to the dialog - array of selected rows */\n data: T[];\n /** Flag to identify table action dialogs */\n tableAction: true;\n};\n\n/** Base properties shared by all table actions */\nexport type TableActionBase<T> = {\n label: 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?: (rows: T[]) => boolean;\n icon: CtxIcon;\n bulk: boolean;\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/** Action that triggers a callback */\nexport type 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 onClick: (e: PressEvent, rows: T[]) => void;\n};\n\n/** Action that opens a dialog */\nexport type TableActionDialog<T> = TableActionBase<T> & {\n type: 'dialog';\n /** Component to render in the dialog */\n component: React.ComponentType<TableActionDialogContentProps<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 /** Array of selected rows */\n readonly rowsSelected: T[];\n /** Whether the table is currently fetching data */\n readonly isFetching?: boolean;\n};\n\nexport function TableActions<T>({ items, rowsSelected, isFetching }: TableActionsProps<T>) {\n const { openKey, setOpenKey } = useDialogState();\n\n return (\n <>\n {items.map((item, i) => {\n const id = normalizeLabel(item.label);\n const Icon = item.icon;\n const isDisabled = getTableActionIsDisabled(item, rowsSelected) || isFetching;\n\n return (\n <Button\n key={`${id}-${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 (isDisabled) return;\n\n if (isTableActionAction(item)) {\n item.onClick(e, rowsSelected);\n } else if (isTableActionDialog(item)) {\n setOpenKey(id);\n }\n }}\n variant={item.variant ?? 'neutral'}\n >\n <Icon />\n <span>{item.label}</span>\n </Button>\n );\n })}\n\n <DialogActionRenderer<TableActionDialogContentProps<T>>\n openKey={openKey}\n onOpenChange={open => {\n if (!open) setOpenKey(null);\n }}\n findItem={key => {\n const item = findItemByNormalizedLabel(items, key);\n if (!item || !isTableActionDialog(item)) return null;\n return { component: item.component };\n }}\n getDialogProps={close => ({ data: rowsSelected, tableAction: true, close })}\n />\n </>\n );\n}\n"],"names":["isTableActionAction","item","isTableActionDialog","getTableActionIsDisabled","rows","TableActions","items","rowsSelected","isFetching","openKey","setOpenKey","useDialogState","jsxs","Fragment","i","id","normalizeLabel","Icon","isDisabled","Button","e","jsx","DialogActionRenderer","open","key","findItemByNormalizedLabel","close"],"mappings":"keA8CA,SAASA,EAAuBC,EAAoD,CAChF,OAAOA,EAAK,OAAS,QACzB,CAEA,SAASC,EAAuBD,EAAoD,CAChF,OAAOA,EAAK,OAAS,QACzB,CAEA,SAASE,EAA4BF,EAAsBG,EAAoB,CAC3E,OAAOH,EAAK,WAAaA,EAAK,WAAWG,CAAI,EAAI,EACrD,CAWO,SAASC,EAAgB,CAAE,MAAAC,EAAO,aAAAC,EAAc,WAAAC,GAAoC,CACvF,KAAM,CAAE,QAAAC,EAAS,WAAAC,CAAA,EAAeC,EAAA,EAEhC,OACIC,EAAAC,EAAA,CACK,SAAA,CAAAP,EAAM,IAAI,CAACL,EAAMa,IAAM,CACpB,MAAMC,EAAKC,EAAef,EAAK,KAAK,EAC9BgB,EAAOhB,EAAK,KACZiB,EAAaf,EAAyBF,EAAMM,CAAY,GAAKC,EAEnE,OACII,EAACO,EAAA,CAEG,aAAYlB,EAAK,MACjB,KAAK,SACL,WAAAiB,EACA,UAAU,6EACV,QAASE,GAAK,CACNF,IAEAlB,EAAoBC,CAAI,EACxBA,EAAK,QAAQmB,EAAGb,CAAY,EACrBL,EAAoBD,CAAI,GAC/BS,EAAWK,CAAE,EAErB,EACA,QAASd,EAAK,SAAW,UAEzB,SAAA,CAAAoB,EAACJ,EAAA,EAAK,EACNI,EAAC,OAAA,CAAM,SAAApB,EAAK,KAAA,CAAM,CAAA,CAAA,EAjBb,GAAGc,CAAE,IAAID,CAAC,EAAA,CAoB3B,CAAC,EAEDO,EAACC,EAAA,CACG,QAAAb,EACA,aAAcc,GAAQ,CACbA,GAAMb,EAAW,IAAI,CAC9B,EACA,SAAUc,GAAO,CACb,MAAMvB,EAAOwB,EAA0BnB,EAAOkB,CAAG,EACjD,MAAI,CAACvB,GAAQ,CAACC,EAAoBD,CAAI,EAAU,KACzC,CAAE,UAAWA,EAAK,SAAA,CAC7B,EACA,eAAgByB,IAAU,CAAE,KAAMnB,EAAc,YAAa,GAAM,MAAAmB,CAAA,EAAM,CAAA,CAC7E,EACJ,CAER"}
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Hook for managing dialog state in action components.
|
|
3
|
-
* Returns the open key and setter function.
|
|
4
|
-
*/
|
|
5
|
-
export declare function useDialogState(): {
|
|
6
|
-
openKey: string | null;
|
|
7
|
-
setOpenKey: import('react').Dispatch<import('react').SetStateAction<string | null>>;
|
|
8
|
-
};
|
|
9
|
-
/**
|
|
10
|
-
* Props for rendering a dialog action.
|
|
11
|
-
*/
|
|
12
|
-
export type DialogActionRendererProps<TDialogProps extends {
|
|
13
|
-
close: () => void;
|
|
14
|
-
}> = {
|
|
15
|
-
/** The key of the currently open dialog */
|
|
16
|
-
readonly openKey: string | null;
|
|
17
|
-
/** Callback when dialog open state changes */
|
|
18
|
-
readonly onOpenChange: (open: boolean) => void;
|
|
19
|
-
/** Function to find the dialog item by normalized label key */
|
|
20
|
-
readonly findItem: (key: string) => {
|
|
21
|
-
component: React.ComponentType<TDialogProps>;
|
|
22
|
-
} | null;
|
|
23
|
-
/** Function to get dialog props, receives close function and returns full dialog props */
|
|
24
|
-
readonly getDialogProps: (close: () => void) => TDialogProps;
|
|
25
|
-
};
|
|
26
|
-
/**
|
|
27
|
-
* Renders a dialog for action components.
|
|
28
|
-
* Handles the DialogTrigger, DialogOverlay, and DialogContent wrapper.
|
|
29
|
-
*/
|
|
30
|
-
export declare function DialogActionRenderer<TDialogProps extends {
|
|
31
|
-
close: () => void;
|
|
32
|
-
}>({ openKey, onOpenChange, findItem, getDialogProps, }: DialogActionRendererProps<TDialogProps>): import("react/jsx-runtime").JSX.Element;
|
|
33
|
-
/**
|
|
34
|
-
* Helper function to find an item by normalized label.
|
|
35
|
-
*/
|
|
36
|
-
export declare function findItemByNormalizedLabel<T extends {
|
|
37
|
-
label: string;
|
|
38
|
-
}>(items: T[], normalizedKey: string): T | undefined;
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use client";import{jsx as o}from"react/jsx-runtime";import{useState as p}from"react";import{normalizeLabel as u}from"../utilities/string.js";import{DialogTrigger as a,DialogOverlay as c,DialogContent as f}from"./dialog.js";import"lodash-es";import"class-variance-authority";import"react-aria-components";import"./button.js";import"../utilities/theme.js";import"clsx";import"./loader.js";import"./icons.js";function S(){const[r,t]=p(null);return{openKey:r,setOpenKey:t}}function j({openKey:r,onOpenChange:t,findItem:n,getDialogProps:e}){return o(a,{isOpen:r!==null,onOpenChange:t,children:r!==null&&(()=>{const i=n(r);if(!i)return null;const l=i.component;return o(c,{children:o(f,{children:({close:m})=>o(l,{...e(m)})})})})()})}function v(r,t){return r.find(n=>u(n.label)===t)}export{j as DialogActionRenderer,v as findItemByNormalizedLabel,S as useDialogState};
|
|
2
|
-
//# sourceMappingURL=dialog-action-utils.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dialog-action-utils.js","sources":["../../lib/components/dialog-action-utils.tsx"],"sourcesContent":["'use client';\nimport { useState } from 'react';\nimport { normalizeLabel } from '../utilities/string';\nimport { DialogContent, DialogOverlay, DialogTrigger } from './dialog';\n\n/**\n * Hook for managing dialog state in action components.\n * Returns the open key and setter function.\n */\nexport function useDialogState() {\n const [openKey, setOpenKey] = useState<string | null>(null);\n return { openKey, setOpenKey };\n}\n\n/**\n * Props for rendering a dialog action.\n */\nexport type DialogActionRendererProps<TDialogProps extends { close: () => void }> = {\n /** The key of the currently open dialog */\n readonly openKey: string | null;\n /** Callback when dialog open state changes */\n readonly onOpenChange: (open: boolean) => void;\n /** Function to find the dialog item by normalized label key */\n readonly findItem: (key: string) => { component: React.ComponentType<TDialogProps> } | null;\n /** Function to get dialog props, receives close function and returns full dialog props */\n readonly getDialogProps: (close: () => void) => TDialogProps;\n};\n\n/**\n * Renders a dialog for action components.\n * Handles the DialogTrigger, DialogOverlay, and DialogContent wrapper.\n */\nexport function DialogActionRenderer<TDialogProps extends { close: () => void }>({\n openKey,\n onOpenChange,\n findItem,\n getDialogProps,\n}: DialogActionRendererProps<TDialogProps>) {\n return (\n <DialogTrigger isOpen={openKey !== null} onOpenChange={onOpenChange}>\n {openKey !== null &&\n (() => {\n const item = findItem(openKey);\n if (!item) return null;\n\n const Component = item.component;\n\n return (\n <DialogOverlay>\n <DialogContent>{({ close }) => <Component {...getDialogProps(close)} />}</DialogContent>\n </DialogOverlay>\n );\n })()}\n </DialogTrigger>\n );\n}\n\n/**\n * Helper function to find an item by normalized label.\n */\nexport function findItemByNormalizedLabel<T extends { label: string }>(\n items: T[],\n normalizedKey: string\n): T | undefined {\n return items.find(it => normalizeLabel(it.label) === normalizedKey);\n}\n"],"names":["useDialogState","openKey","setOpenKey","useState","DialogActionRenderer","onOpenChange","findItem","getDialogProps","jsx","DialogTrigger","item","Component","DialogOverlay","DialogContent","close","findItemByNormalizedLabel","items","normalizedKey","it","normalizeLabel"],"mappings":"uZASO,SAASA,GAAiB,CAC7B,KAAM,CAACC,EAASC,CAAU,EAAIC,EAAwB,IAAI,EAC1D,MAAO,CAAE,QAAAF,EAAS,WAAAC,CAAA,CACtB,CAoBO,SAASE,EAAiE,CAC7E,QAAAH,EACA,aAAAI,EACA,SAAAC,EACA,eAAAC,CACJ,EAA4C,CACxC,OACIC,EAACC,GAAc,OAAQR,IAAY,KAAM,aAAAI,EACpC,SAAAJ,IAAY,OACR,IAAM,CACH,MAAMS,EAAOJ,EAASL,CAAO,EAC7B,GAAI,CAACS,EAAM,OAAO,KAElB,MAAMC,EAAYD,EAAK,UAEvB,OACIF,EAACI,EAAA,CACG,SAAAJ,EAACK,EAAA,CAAe,UAAC,CAAE,MAAAC,CAAA,IAAYN,EAACG,GAAW,GAAGJ,EAAeO,CAAK,CAAA,CAAG,EAAG,EAC5E,CAER,IAAG,CACX,CAER,CAKO,SAASC,EACZC,EACAC,EACa,CACb,OAAOD,EAAM,KAAKE,GAAMC,EAAeD,EAAG,KAAK,IAAMD,CAAa,CACtE"}
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { CtxIcon } from './icons';
|
|
2
|
-
export type DialogMenuContentProps<T> = {
|
|
3
|
-
/** Callback to close the dialog */
|
|
4
|
-
close: () => void;
|
|
5
|
-
/** The data passed to the dialog */
|
|
6
|
-
data: T;
|
|
7
|
-
};
|
|
8
|
-
/** Base properties shared by all menu actions */
|
|
9
|
-
export type MenuActionBase<T> = {
|
|
10
|
-
label: string;
|
|
11
|
-
/** Optional function to determine if the action is disabled. Receives the data and returns a boolean. Defaults to false if not provided */
|
|
12
|
-
isDisabled?: (data: T) => boolean;
|
|
13
|
-
icon: CtxIcon;
|
|
14
|
-
};
|
|
15
|
-
/** Action that triggers a callback */
|
|
16
|
-
export type MenuActionAction<T> = MenuActionBase<T> & {
|
|
17
|
-
type: 'action';
|
|
18
|
-
/** Callback triggered when the action is pressed. Receives the data as parameter */
|
|
19
|
-
onPress: (data: T) => void;
|
|
20
|
-
};
|
|
21
|
-
/** Action that opens a dialog */
|
|
22
|
-
export type MenuActionDialog<T> = MenuActionBase<T> & {
|
|
23
|
-
type: 'dialog';
|
|
24
|
-
/** Component to render in the dialog */
|
|
25
|
-
component: React.ComponentType<DialogMenuContentProps<T>>;
|
|
26
|
-
};
|
|
27
|
-
/** Common menu action type that works for both DialogMenu and table row actions */
|
|
28
|
-
export type DialogMenuAction<T> = MenuActionAction<T> | MenuActionDialog<T>;
|
|
29
|
-
export type DialogMenuProps<T> = {
|
|
30
|
-
readonly label: React.ReactNode;
|
|
31
|
-
readonly items: DialogMenuAction<T>[];
|
|
32
|
-
readonly data: T;
|
|
33
|
-
};
|
|
34
|
-
export declare function DialogMenu<T>({ label, items, data }: DialogMenuProps<T>): import("react/jsx-runtime").JSX.Element;
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use client";import{jsxs as m,Fragment as d,jsx as t}from"react/jsx-runtime";import{normalizeLabel as b}from"../utilities/string.js";import{useDialogState as g,findItemByNormalizedLabel as p,DialogActionRenderer as D}from"./dialog-action-utils.js";import{EasyMenu as A,MenuItem as y}from"./menu.js";import"lodash-es";import"react";import"./dialog.js";import"class-variance-authority";import"react-aria-components";import"./button.js";import"../utilities/theme.js";import"clsx";import"./loader.js";import"./icons.js";import"./list-box.js";import"./select.js";import"../utilities/form.js";import"../utilities/form-context.js";import"@tanstack/react-form";import"./form.js";import"./popover.js";function I(n){return n.type==="action"}function c(n){return n.type==="dialog"}function a(n,e){return n.isDisabled?n.isDisabled(e):!1}function J({label:n,items:e,data:r}){const{openKey:u,setOpenKey:s}=g();return m(d,{children:[t(A,{"aria-label":"Actions",label:n,size:"icon",onAction:i=>{if(typeof i!="string")return;const o=p(e,i);!o||a(o,r)||(I(o)?o.onPress(r):c(o)&&s(i))},children:e.map(i=>{const o=b(i.label),l=i.icon,f=a(i,r);return m(y,{id:o,isDisabled:f,children:[t(l,{className:"size-icon"})," ",i.label]},o)})}),t(D,{openKey:u,onOpenChange:i=>{i||s(null)},findItem:i=>{const o=p(e,i);return!o||!c(o)?null:{component:o.component}},getDialogProps:i=>({data:r,close:i})})]})}export{J as DialogMenu};
|
|
2
|
-
//# sourceMappingURL=dialog-menu.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dialog-menu.js","sources":["../../lib/components/dialog-menu.tsx"],"sourcesContent":["'use client';\nimport { normalizeLabel } from '../utilities/string';\nimport { DialogActionRenderer, findItemByNormalizedLabel, useDialogState } from './dialog-action-utils';\nimport type { CtxIcon } from './icons';\nimport { EasyMenu, MenuItem } from './menu';\n\nexport type DialogMenuContentProps<T> = {\n /** Callback to close the dialog */\n close: () => void;\n /** The data passed to the dialog */\n data: T;\n};\n\n/** Base properties shared by all menu actions */\nexport type MenuActionBase<T> = {\n label: string;\n /** Optional function to determine if the action is disabled. Receives the data and returns a boolean. Defaults to false if not provided */\n isDisabled?: (data: T) => boolean;\n icon: CtxIcon;\n};\n\n/** Action that triggers a callback */\nexport type MenuActionAction<T> = MenuActionBase<T> & {\n type: 'action';\n /** Callback triggered when the action is pressed. Receives the data as parameter */\n onPress: (data: T) => void;\n};\n\n/** Action that opens a dialog */\nexport type MenuActionDialog<T> = MenuActionBase<T> & {\n type: 'dialog';\n /** Component to render in the dialog */\n component: React.ComponentType<DialogMenuContentProps<T>>;\n};\n\n/** Common menu action type that works for both DialogMenu and table row actions */\nexport type DialogMenuAction<T> = MenuActionAction<T> | MenuActionDialog<T>;\n\nfunction isMenuActionAction<T>(item: DialogMenuAction<T>): item is MenuActionAction<T> {\n return item.type === 'action';\n}\n\nfunction isMenuActionDialog<T>(item: DialogMenuAction<T>): item is MenuActionDialog<T> {\n return item.type === 'dialog';\n}\n\nfunction getIsDisabled<T>(item: DialogMenuAction<T>, data: T): boolean {\n return item.isDisabled ? item.isDisabled(data) : false;\n}\n\nexport type DialogMenuProps<T> = {\n readonly label: React.ReactNode;\n readonly items: DialogMenuAction<T>[];\n readonly data: T;\n};\n\nexport function DialogMenu<T>({ label, items, data }: DialogMenuProps<T>) {\n const { openKey, setOpenKey } = useDialogState();\n\n return (\n <>\n <EasyMenu\n aria-label=\"Actions\"\n label={label}\n size={'icon'}\n onAction={key => {\n if (typeof key !== 'string') return;\n const found = findItemByNormalizedLabel(items, key);\n if (!found) return;\n\n const isDisabled = getIsDisabled(found, data);\n if (isDisabled) return;\n\n if (isMenuActionAction(found)) {\n found.onPress(data);\n } else if (isMenuActionDialog(found)) {\n setOpenKey(key);\n }\n }}\n >\n {items.map(it => {\n const id = normalizeLabel(it.label);\n const Icon = it.icon;\n const isDisabled = getIsDisabled(it, data);\n return (\n <MenuItem key={id} id={id} isDisabled={isDisabled}>\n {<Icon className=\"size-icon\" />} {it.label}\n </MenuItem>\n );\n })}\n </EasyMenu>\n\n <DialogActionRenderer<DialogMenuContentProps<T>>\n openKey={openKey}\n onOpenChange={open => {\n if (!open) setOpenKey(null);\n }}\n findItem={key => {\n const item = findItemByNormalizedLabel(items, key);\n if (!item || !isMenuActionDialog(item)) return null;\n return { component: item.component };\n }}\n getDialogProps={close => ({ data, close })}\n />\n </>\n );\n}\n"],"names":["isMenuActionAction","item","isMenuActionDialog","getIsDisabled","data","DialogMenu","label","items","openKey","setOpenKey","useDialogState","jsxs","Fragment","jsx","EasyMenu","key","found","findItemByNormalizedLabel","it","id","normalizeLabel","Icon","isDisabled","MenuItem","DialogActionRenderer","open","close"],"mappings":"orBAsCA,SAASA,EAAsBC,EAAwD,CACnF,OAAOA,EAAK,OAA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