@cryptlex/web-components 6.6.6-alpha27 → 6.6.6-alpha29
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/checkbox.js +1 -1
- package/dist/components/checkbox.js.map +1 -1
- package/dist/components/data-table-filter.d.ts +1 -1
- package/dist/components/data-table.js +1 -1
- package/dist/components/data-table.js.map +1 -1
- package/dist/components/form.js +1 -1
- package/dist/components/form.js.map +1 -1
- package/dist/components/id-search.js +1 -1
- package/dist/components/id-search.js.map +1 -1
- package/dist/components/multi-select.js +1 -1
- package/dist/components/multi-select.js.map +1 -1
- package/dist/components/numberfield.d.ts +3 -2
- package/dist/components/numberfield.js +1 -1
- package/dist/components/numberfield.js.map +1 -1
- package/dist/utilities/numbers.d.ts +7 -0
- package/dist/utilities/numbers.js +1 -1
- package/dist/utilities/numbers.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsx as e,Fragment as
|
|
1
|
+
import{jsx as e,Fragment as d}from"react/jsx-runtime";import{useId as h}from"react";import{Checkbox as p,composeRenderProps as n,CheckboxGroup as g}from"react-aria-components";import{useFieldContext as x}from"../utilities/form-context.js";import{classNames as s}from"../utilities/theme.js";import{FormField as f,labelVariants as k}from"./form.js";import{IcMinus as v,IcCheck as C}from"./icons.js";import"@tanstack/react-form";import"clsx";import"class-variance-authority";const w=g;function y({className:r,label:o,description:l,errorMessage:u,requiredIndicator:m,...t}){const b=h(),i=t.id||b;return e("div",{className:"group form-field",children:e(f,{label:o,description:l,errorMessage:u,requiredIndicator:m,htmlFor:i,children:e(p,{className:n(r,c=>s("group/checkbox cursor-pointer relative focus-ring flex items-center gap-x-2","disabled-muted",k,c)),id:i,...t,children:n(e(d,{}),(c,a)=>e(d,{children:e("div",{className:s("flex size-input shrink-0 items-center bg-elevation-2 justify-center border border-input text-current ring-offset-background","group-data-[indeterminate]/checkbox:bg-primary group-data-[selected]/checkbox:bg-primary group-data-[indeterminate]/checkbox:text-primary-foreground group-data-[selected]/checkbox:text-primary-foreground","group-data-[disabled]/checkbox:cursor-not-allowed group-data-[disabled]/checkbox:opacity-50","group-data-[invalid]/checkbox:border-destructive group-data-[invalid]/checkbox:group-data-[selected]/checkbox:bg-destructive group-data-[invalid]/checkbox:group-data-[selected]/checkbox:text-destructive-foreground","focus:outline-none focus-visible:outline-none"),children:a.isIndeterminate?e(v,{className:"size-icon"}):a.isSelected?e(C,{className:"size-icon"}):null})}))})})})}function M({...r}){const o=x({disabled:r.isDisabled});return e(y,{isSelected:o.state.value,isDisabled:o.form.state.isSubmitting||r.isDisabled,onChange:()=>o.handleChange(!o.state.value),onBlur:o.handleBlur,...r})}export{y as Checkbox,w as CheckboxGroup,M as TfCheckbox};
|
|
2
2
|
//# sourceMappingURL=checkbox.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkbox.js","sources":["../../lib/components/checkbox.tsx"],"sourcesContent":["import {\n Checkbox as AriaCheckbox,\n CheckboxGroup as AriaCheckboxGroup,\n composeRenderProps,\n type CheckboxProps as AriaCheckboxProps,\n} from 'react-aria-components';\n\nimport { useFieldContext } from '../utilities/form-context';\nimport { classNames } from '../utilities/theme';\nimport { FormField, labelVariants, type FormFieldProps } from './form';\nimport { IcCheck, IcMinus } from './icons';\n\nexport const CheckboxGroup = AriaCheckboxGroup;\ntype CheckboxProps = AriaCheckboxProps & FormFieldProps;\nexport function Checkbox({\n className,\n label,\n description,\n errorMessage,\n requiredIndicator,\n ...props\n}: Omit<CheckboxProps, 'children'>) {\n return (\n <div className=\"group form-field\">\n <FormField {...{ label, description, errorMessage, requiredIndicator }}>\n <AriaCheckbox\n className={composeRenderProps(className, className =>\n classNames(\n 'group/checkbox cursor-pointer relative focus-ring flex items-center gap-x-2',\n /* Disabled */\n 'disabled-muted',\n labelVariants,\n className\n )\n )}\n {...props}\n >\n {composeRenderProps(<></>, (_, renderProps) => (\n <>\n <div\n className={classNames(\n 'flex size-input shrink-0 items-center bg-elevation-2 justify-center border border-input text-current ring-offset-background',\n /* Selected */\n 'group-data-[indeterminate]/checkbox:bg-primary group-data-[selected]/checkbox:bg-primary group-data-[indeterminate]/checkbox:text-primary-foreground group-data-[selected]/checkbox:text-primary-foreground',\n /* Disabled */\n 'group-data-[disabled]/checkbox:cursor-not-allowed group-data-[disabled]/checkbox:opacity-50',\n /* Invalid */\n 'group-data-[invalid]/checkbox:border-destructive group-data-[invalid]/checkbox:group-data-[selected]/checkbox:bg-destructive group-data-[invalid]/checkbox:group-data-[selected]/checkbox:text-destructive-foreground',\n /* Resets */\n 'focus:outline-none focus-visible:outline-none'\n )}\n >\n {renderProps.isIndeterminate ? (\n <IcMinus className=\"size-icon\" />\n ) : renderProps.isSelected ? (\n <IcCheck className=\"size-icon\" />\n ) : null}\n </div>\n </>\n ))}\n </AriaCheckbox>\n </FormField>\n </div>\n );\n}\n\nexport type TfCheckboxProps = Omit<React.ComponentProps<typeof Checkbox>, 'onChange' | 'onBlur' | 'isChecked'>;\nexport function TfCheckbox({ ...props }: TfCheckboxProps) {\n const field = useFieldContext<boolean>({ disabled: props.isDisabled });\n return (\n <Checkbox\n isSelected={field.state.value}\n isDisabled={field.form.state.isSubmitting || props.isDisabled}\n onChange={() => field.handleChange(!field.state.value)}\n onBlur={field.handleBlur}\n {...props}\n />\n );\n}\n"],"names":["CheckboxGroup","AriaCheckboxGroup","Checkbox","className","label","description","errorMessage","requiredIndicator","props","jsx","FormField","AriaCheckbox","composeRenderProps","classNames","labelVariants","Fragment","_","renderProps","IcMinus","IcCheck","TfCheckbox","field","useFieldContext"],"mappings":"
|
|
1
|
+
{"version":3,"file":"checkbox.js","sources":["../../lib/components/checkbox.tsx"],"sourcesContent":["import { useId } from 'react';\nimport {\n Checkbox as AriaCheckbox,\n CheckboxGroup as AriaCheckboxGroup,\n composeRenderProps,\n type CheckboxProps as AriaCheckboxProps,\n} from 'react-aria-components';\n\nimport { useFieldContext } from '../utilities/form-context';\nimport { classNames } from '../utilities/theme';\nimport { FormField, labelVariants, type FormFieldProps } from './form';\nimport { IcCheck, IcMinus } from './icons';\n\nexport const CheckboxGroup = AriaCheckboxGroup;\ntype CheckboxProps = AriaCheckboxProps & FormFieldProps;\nexport function Checkbox({\n className,\n label,\n description,\n errorMessage,\n requiredIndicator,\n ...props\n}: Omit<CheckboxProps, 'children'>) {\n const generatedId = useId();\n const fieldId = props.id || generatedId;\n return (\n <div className=\"group form-field\">\n <FormField {...{ label, description, errorMessage, requiredIndicator, htmlFor: fieldId }}>\n <AriaCheckbox\n className={composeRenderProps(className, className =>\n classNames(\n 'group/checkbox cursor-pointer relative focus-ring flex items-center gap-x-2',\n /* Disabled */\n 'disabled-muted',\n labelVariants,\n className\n )\n )}\n id={fieldId}\n {...props}\n >\n {composeRenderProps(<></>, (_, renderProps) => (\n <>\n <div\n className={classNames(\n 'flex size-input shrink-0 items-center bg-elevation-2 justify-center border border-input text-current ring-offset-background',\n /* Selected */\n 'group-data-[indeterminate]/checkbox:bg-primary group-data-[selected]/checkbox:bg-primary group-data-[indeterminate]/checkbox:text-primary-foreground group-data-[selected]/checkbox:text-primary-foreground',\n /* Disabled */\n 'group-data-[disabled]/checkbox:cursor-not-allowed group-data-[disabled]/checkbox:opacity-50',\n /* Invalid */\n 'group-data-[invalid]/checkbox:border-destructive group-data-[invalid]/checkbox:group-data-[selected]/checkbox:bg-destructive group-data-[invalid]/checkbox:group-data-[selected]/checkbox:text-destructive-foreground',\n /* Resets */\n 'focus:outline-none focus-visible:outline-none'\n )}\n >\n {renderProps.isIndeterminate ? (\n <IcMinus className=\"size-icon\" />\n ) : renderProps.isSelected ? (\n <IcCheck className=\"size-icon\" />\n ) : null}\n </div>\n </>\n ))}\n </AriaCheckbox>\n </FormField>\n </div>\n );\n}\n\nexport type TfCheckboxProps = Omit<React.ComponentProps<typeof Checkbox>, 'onChange' | 'onBlur' | 'isChecked'>;\nexport function TfCheckbox({ ...props }: TfCheckboxProps) {\n const field = useFieldContext<boolean>({ disabled: props.isDisabled });\n return (\n <Checkbox\n isSelected={field.state.value}\n isDisabled={field.form.state.isSubmitting || props.isDisabled}\n onChange={() => field.handleChange(!field.state.value)}\n onBlur={field.handleBlur}\n {...props}\n />\n );\n}\n"],"names":["CheckboxGroup","AriaCheckboxGroup","Checkbox","className","label","description","errorMessage","requiredIndicator","props","generatedId","useId","fieldId","jsx","FormField","AriaCheckbox","composeRenderProps","classNames","labelVariants","Fragment","_","renderProps","IcMinus","IcCheck","TfCheckbox","field","useFieldContext"],"mappings":"wdAaO,MAAMA,EAAgBC,EAEtB,SAASC,EAAS,CACrB,UAAAC,EACA,MAAAC,EACA,YAAAC,EACA,aAAAC,EACA,kBAAAC,EACA,GAAGC,CACP,EAAoC,CAChC,MAAMC,EAAcC,EAAA,EACdC,EAAUH,EAAM,IAAMC,EAC5B,OACIG,EAAC,MAAA,CAAI,UAAU,mBACX,WAACC,EAAA,CAAgB,MAAAT,EAAO,YAAAC,EAAa,aAAAC,EAAc,kBAAAC,EAAmB,QAASI,EAC3E,SAAAC,EAACE,EAAA,CACG,UAAWC,EAAmBZ,EAAWA,GACrCa,EACI,8EAEA,iBACAC,EACAd,CAAA,CACJ,EAEJ,GAAIQ,EACH,GAAGH,EAEH,WAAmBI,EAAAM,EAAA,CAAA,CAAE,EAAK,CAACC,EAAGC,IAC3BR,EAAAM,EAAA,CACI,SAAAN,EAAC,MAAA,CACG,UAAWI,EACP,8HAEA,+MAEA,8FAEA,wNAEA,+CAAA,EAGH,SAAAI,EAAY,gBACTR,EAACS,EAAA,CAAQ,UAAU,WAAA,CAAY,EAC/BD,EAAY,WACZR,EAACU,EAAA,CAAQ,UAAU,YAAY,EAC/B,IAAA,CAAA,EAEZ,CACH,CAAA,CAAA,EAET,CAAA,CACJ,CAER,CAGO,SAASC,EAAW,CAAE,GAAGf,GAA0B,CACtD,MAAMgB,EAAQC,EAAyB,CAAE,SAAUjB,EAAM,WAAY,EACrE,OACII,EAACV,EAAA,CACG,WAAYsB,EAAM,MAAM,MACxB,WAAYA,EAAM,KAAK,MAAM,cAAgBhB,EAAM,WACnD,SAAU,IAAMgB,EAAM,aAAa,CAACA,EAAM,MAAM,KAAK,EACrD,OAAQA,EAAM,WACb,GAAGhB,CAAA,CAAA,CAGhB"}
|
|
@@ -19,7 +19,7 @@ type BoolLocalFilter = BaseLocalFilter<'bool', boolean>;
|
|
|
19
19
|
type StringLocalFilter = BaseLocalFilter<'string', string>;
|
|
20
20
|
type NumberLocalFilter = BaseLocalFilter<'number', number>;
|
|
21
21
|
type DateLocalFilter = BaseLocalFilter<'date', string>;
|
|
22
|
-
type IdSearchLocalFilter = BaseLocalFilter<'id-search',
|
|
22
|
+
type IdSearchLocalFilter = BaseLocalFilter<'id-search', string[]>;
|
|
23
23
|
export type TableFilter = EnumLocalFilter | IdLocalFilter | BoolLocalFilter | StringLocalFilter | DateLocalFilter | IdSearchLocalFilter | NumberLocalFilter;
|
|
24
24
|
export type FilterConfig = {
|
|
25
25
|
type: 'enum';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{jsx as e,Fragment as C,jsxs as l}from"react/jsx-runtime";import{createContext as re,useState as F,useMemo as ae,useEffect as ie,useContext as oe,useRef as le}from"react";import{Button as S}from"./button.js";import{useSensors as se,useSensor as k,PointerSensor as ce,KeyboardSensor as ue,DndContext as de,closestCenter as me,DragOverlay as ge}from"@dnd-kit/core";import{sortableKeyboardCoordinates as pe,SortableContext as fe,verticalListSortingStrategy as he,arrayMove as be,useSortable as Se}from"@dnd-kit/sortable";import{CSS as ve}from"@dnd-kit/utilities";import{useQuery as Ce,keepPreviousData as ye}from"@tanstack/react-query";import{createColumnHelper as W,useReactTable as we,getCoreRowModel as Ie,flexRender as V}from"@tanstack/react-table";import{useLocalStorage as H}from"@uidotdev/usehooks";import{merge as xe}from"lodash-es";import{TfDatePicker as Fe}from"./date-picker.js";import{EasyMenu as R,MenuItem as N}from"./menu.js";import{PopoverTrigger as Ne,Popover as Te}from"./popover.js";import{useAppForm as Ae}from"../utilities/form-hook.js";import{useResourceFormatter as M}from"../utilities/resources.js";import{classNames as w}from"../utilities/theme.js";import{IcInfo as Pe,IcMoreVertical as De,IcRefresh as Re,IcColumns as Oe,IcGrip as ze,IcFirst as _e,IcLeft as Le,IcRight as Me,IcLast as Ee,IcSortAsc as $e,IcSortDesc as qe,IcSortNone as ke,IcFilter as Ve,IcRemove as U,IcCheck as j,IcMinus as He,IcAccount as Ue,IcLicense as je,IcDate as Be,IcFile as Ke}from"./icons.js";import{TfMultipleIdSearchInput as Qe}from"./id-search.js";import{Loader as Ge}from"./loader.js";import{SearchField as We}from"./searchfield.js";import{Table as Xe,TableHeader as Ze,TableRow as B,TableHead as Je,TableBody as Ye,TableCell as et}from"./table.js";import{formatDate as K}from"../utilities/date.js";import{Checkbox as Q}from"./checkbox.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";function en(t){const n=async(o,m,a,s)=>{const d={...s,page:o.pageIndex+1,limit:o.pageSize,sort:tt(m[0]),search:a},h=await t(d);return{total:Number.parseInt(h.response.headers.get("Pagination-Count")||"0"),data:h.data}},r=W();return{callback:n,columnHelper:r}}function tt(t){return t?t.desc?`-${t.id}`:`+${t.id}`:"-createdAt"}const T=W(),nt=[T.accessor("checkbox",{header:({table:t})=>e(Q,{isIndeterminate:t.getIsSomeRowsSelected()&&!t.getIsAllPageRowsSelected(),isSelected:t.getIsAllPageRowsSelected()||t.getIsSomePageRowsSelected(),onChange:()=>t.toggleAllPageRowsSelected(),"aria-label":"Select all"}),cell:({row:t})=>e(Q,{isSelected:t.getIsSelected(),onChange:()=>t.toggleSelected(),"aria-label":"Select row"}),enableSorting:!1,enableHiding:!1})],rt=[T.accessor("id",{header:()=>"ID"})],at=[T.accessor("createdAt",{header:()=>"Creation Date",cell:({row:t})=>{const n=t.getValue("createdAt");return K(n)},enableHiding:!1}),T.accessor("updatedAt",{header:()=>"Last Updated",cell:({row:t})=>{const n=t.getValue("updatedAt");return K(n)},enableHiding:!1})],L="TableActions",it=t=>t.length===0?[]:[T.accessor(L,{header:"",id:L,enableHiding:!1,cell:({row:n})=>e(R,{label:e(De,{}),size:"icon",children:t.map(r=>e(N,{isDisabled:r.disabled(n.original),onPress:()=>r.onPress(n.original),children:r.label}))})})];function tn({resourceName:t,columns:n,callback:r,filterConfig:o,columnsToHideByDefault:m={},allowSelection:a=!1,initialFilters:s=[],tableActions:d,rowActions:h}){const[u,v]=F({pagination:{pageIndex:0,pageSize:20},sorting:[]}),[g,c]=F({}),[f,p]=F(""),[b,E]=H(`${t}_ctx_column_order_preference`,[]),[$,Y]=H(`${t}_ctx_column_visibility_preference`,{id:!1,...m}),[O,ee]=F(s),z=ae(()=>O.map(i=>Array.isArray(i.value)?{[i.property]:{[i.operator]:i.value.join(",")}}:{[i.property]:{[i.operator]:i.value}}).reduce((i,x)=>xe(i,x),{}),[O]),_=i=>{v(x=>({...x,...i}))},{sorting:A,pagination:P}=u,D=Ce({queryKey:[t,P,A,f,z],queryFn:()=>r(P,A,f,z),placeholderData:ye,retry:0,refetchOnWindowFocus:!1}),te=[...a?nt:[],...rt,...n,...at,...it(h??[])];function ne(i){return typeof i=="function"}function I(i,x){return ne(i)?i(x):i}const q=we({data:D.data?.data??[],columns:te,getCoreRowModel:Ie(),rowCount:D.data?.total,manualPagination:!0,onPaginationChange:i=>{_({pagination:I(i,P)})},manualSorting:!0,onSortingChange:i=>{c({}),_({sorting:[...I(i,A)]})},manualFiltering:!0,onColumnVisibilityChange:i=>{Y(I(i,$))},onRowSelectionChange:i=>{c(I(i,g))},onColumnOrderChange:i=>{E(I(i,b))},state:{sorting:A,columnVisibility:$,pagination:P,rowSelection:g,columnOrder:b},meta:{refetch:D.refetch}});return ie(()=>{E([...q.getAllLeafColumns().map(i=>i.id)])},[]),{tableState:u,updateTableState:_,query:D,setSearchQuery:p,searchQuery:f,tanTable:q,mergedFilters:z,filters:O,setFilters:ee,filterConfig:o,tableActions:d}}const X=re(null);function y(){const t=oe(X);if(!t)throw Error("DataTable should be used within DataTableProvider.");return t}function nn({children:t,...n}){return e(X.Provider,{value:n,children:t})}function rn({className:t,...n}){const{query:r,tanTable:o}=y();return e(C,{children:l("section",{...n,className:w("flex flex-col bg-elevation-1",t),children:[e(ct,{}),l("div",{className:"w-full overflow-auto border-x h-table relative",tabIndex:0,children:[r.isLoading&&e(G,{className:"cursor-wait",children:e(Ge,{})}),!r.isLoading&&o.getRowModel().rows.length===0&&e(G,{className:"cursor-not-allowed",children:!r.isFetching&&(r.isError?l("span",{className:"flex gap-3 justify-center items-center",children:[e(Pe,{}),e("span",{children:r.error.message})]}):r.data?.data?.length===0?e(C,{children:"No results found."}):e(C,{children:"Unknown error. Please contact customer support."}))}),!r.isLoading&&o.getRowModel().rows.length!==0&&e(ut,{className:"w-full"})]}),l("div",{className:"flex w-full justify-between border gap-icon p-icon overflow-x-auto",children:[l("div",{className:"flex gap-icon",children:[e(ot,{}),e(st,{})]}),e(lt,{})]})]})})}function G({children:t,className:n}){return l(C,{children:[e("span",{className:w(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 ot(){const{tanTable:t}=y(),[n,r]=F(null),o=M(),m=se(k(ce),k(ue,{coordinateGetter:pe}));return e(de,{sensors:m,collisionDetection:me,onDragStart:s=>{const{active:d}=s;r(d.id.toString())},onDragEnd:s=>{const{active:d,over:h}=s;if(h&&d.id!==h.id){const u=t.getState().columnOrder,v=u.indexOf(d.id.toString()),g=u.indexOf(h.id.toString());t.setColumnOrder([...be(u,v,g)])}r(null)},children:l(fe,{items:t.getState().columnOrder,strategy:he,children:[l(R,{label:l(C,{children:[e(Oe,{className:"inline align-bottom me-1"}),"Columns"]}),selectionMode:"multiple",items:t.getAllFlatColumns(),selectedKeys:t.getVisibleFlatColumns().map(s=>s.id),children:[e(N,{onAction:()=>t.toggleAllColumnsVisible(),className:"italic",children:"(select all)"}),t.getState().columnOrder.map(s=>{const d=t.getAllFlatColumns().find(h=>h.id===s);return d?e(a,{column:d},d.id):null})]}),e(ge,{children:n?e("div",{className:"opacity-70 border-2 border-primary",children:o(n)}):null})]})});function a({column:s}){const{attributes:d,listeners:h,setNodeRef:u,transform:v,transition:g}=Se({id:s.id}),c={transform:ve.Transform.toString(v),transition:g,zIndex:"999"};return l(N,{ref:u,style:c,...d,id:s.id,onAction:()=>s.toggleVisibility(),isDisabled:!s.getCanHide(),className:"flex items-center",children:[e(ze,{...h,className:"size-icon cursor-grab"}),o(s.id),s.getIsSorted()&&e(Z,{className:"size-icon",direction:s.getIsSorted()})]})}}function lt(){const{tanTable:t,query:n}=y(),r=n.data?.total??0;return l("div",{className:"flex items-center gap-2",children:[e("span",{className:"whitespace-nowrap body-sm text-muted",children:`${t.getState().pagination.pageIndex*t.getState().pagination.pageSize+1} - ${Math.min((t.getState().pagination.pageIndex+1)*t.getState().pagination.pageSize,r)} of ${r?.toLocaleString()}`}),e(S,{"aria-label":"First page",onPress:()=>t.firstPage(),isDisabled:!t.getCanPreviousPage(),variant:"neutral",size:"icon",children:e(_e,{})}),e(S,{"aria-label":"Previous page",onPress:()=>t.previousPage(),isDisabled:!t.getCanPreviousPage(),variant:"neutral",size:"icon",children:e(Le,{})}),e(S,{"aria-label":"Next page",onPress:()=>t.nextPage(),isDisabled:!t.getCanNextPage(),variant:"neutral",size:"icon",children:e(Me,{})}),e(S,{"aria-label":"Last page",onClick:()=>t.lastPage(),isDisabled:!t.getCanNextPage(),variant:"neutral",size:"icon",children:e(Ee,{})})]})}function st(){const{tanTable:t}=y(),n=[10,20,30,40,50];return e(R,{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(N,{onAction:()=>t.setPageSize(r.value),children:r.value})})}function ct(){const{query:t,tanTable:n,searchQuery:r,setSearchQuery:o,tableActions:m}=y();return l("section",{className:"flex bg-elevation-1 justify-between my-0 p-icon border gap-icon overflow-auto",children:[l("div",{className:"flex gap-icon",children:[e(S,{"aria-label":"Refresh",isPending:t.isFetching,onClick:()=>t.refetch(),variant:"neutral",size:"icon",children:e(Re,{})}),m.filter(a=>a.bulk===n.getSelectedRowModel().rows.length>0).map((a,s)=>{const d=a.icon;return e(S,{"aria-label":a.label,type:"button",isDisabled:t.isFetching,className:"animate-in fade-in slide-in-from-left-15 duration-300 transition-transform",onPress:h=>{a.onClick(h,n.getSelectedRowModel().rows.map(u=>u.original))},size:"icon",children:e(d,{})},`${s}-${a.bulk}`)})]}),l("div",{className:"flex gap-icon",children:[e(gt,{}),e(We,{value:r,onChange:o})]})]})}function Z({direction:t,...n}){return t==="asc"?e($e,{className:"size-3.5",...n}):t==="desc"?e(qe,{className:"size-3.5",...n}):e(ke,{className:"size-3.5",...n})}function ut({className:t}){const{tanTable:n}=y(),r=M(),o=(m,a)=>w("px-icon py-2 text-left body-sm font-medium whitespace-nowrap",m&&"bg-elevation-1 sticky right-0 z-50 text-center",a);return l(Xe,{className:w("table-auto",t),children:[e(Ze,{className:"sticky top-0 z-10",children:n.getHeaderGroups().map(m=>e(B,{children:m.headers.map(a=>l(Je,{scope:"col",colSpan:a.colSpan,className:o(!1,"bg-elevation-1"),children:[!a.column.getCanSort()&&!a.isPlaceholder&&V(a.column.columnDef.header,a.getContext()),a.column.getCanSort()&&l(S,{variant:"ghost",className:"w-full justify-start p-1",onPress:a.column.getToggleSortingHandler(),children:[e("span",{children:r(a.id)}),e(Z,{direction:a.column.getIsSorted()})]})]},a.id))},m.id))}),e(Ye,{children:n.getRowModel().rows.map(m=>e(B,{className:w("transition-colors data-[selected=true]:bg-primary/10 hover:bg-muted-foreground/20"),"data-selected":m.getIsSelected(),children:m.getVisibleCells().map(a=>e(et,{className:o(a.column.id===L),children:V(a.column.columnDef.cell,a.getContext())},a.id))},m.id))})]})}const an=["eq","ne","cn","nc","sw","ew","in","nin","gt","gte","lt","lte"],dt={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 mt(t,n){const r=`${n}-${Date.now()}`,o=J[t][0];switch(t){case"bool":return{id:r,type:t,property:n,operator:o,value:!0};case"string":return{id:r,type:t,property:n,operator:o,value:""};case"date":return{id:r,type:t,property:n,operator:o,value:new Date().toISOString()};case"id":return{id:r,type:t,property:n,operator:o,value:""};case"id-search":return{id:r,type:t,property:n,operator:o,value:new Set};case"enum":return{id:r,type:t,property:n,operator:o,value:new Set};case"number":return{id:r,type:t,property:n,operator:o,value:0}}}const J={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 gt({className:t,...n}){const{filters:r,query:o,setFilters:m,filterConfig:a}=y(),s=le(null),d=M(),u=Ae({defaultValues:{filters:r},onSubmit:({value:g})=>{m(g.filters)}}),v=Object.keys(a).sort();return e("section",{...n,className:w("flex gap-icon items-center",t),children:l(Ne,{onOpenChange:g=>{g?s.current?.focus():u.handleSubmit()},children:[l("div",{className:"relative",children:[r.length>0&&e("div",{className:"size-2 rounded-full absolute bg-primary/90 z-20 top-0 right-0 translate-x-0.5 -translate-y-0.5"}),e(S,{"aria-label":"Filter",isDisabled:o.isPending||v.length===0,type:"button",size:"icon",variant:"neutral",children:e(Ve,{})})]}),e(Te,{className:"w-full p-icon",children:e("form",{onSubmit:g=>{g.preventDefault()},className:"flex flex-col gap-icon max-h-table overflow-auto ",children:e(u.Field,{mode:"array",name:"filters",children:g=>l(C,{children:[g.state.value.map((c,f)=>l("div",{className:"flex gap-icon items-center justify-normal",children:[e("span",{className:"body-sm",children:d(c.property)}),e(u.AppField,{name:`filters[${f}].operator`,children:p=>e(p.TfSingleSelect,{items:J[c.type].map(b=>({id:b,label:e(C,{children:dt[b]})}))})},c.id),c.type==="bool"&&e(u.AppField,{name:`filters[${f}].value`,children:p=>e(p.TfCheckbox,{autoFocus:!0})}),c.type==="date"&&e(u.AppField,{name:`filters[${f}].value`,children:p=>e(Fe,{autoFocus:!0})}),c.type==="id"&&e(u.AppField,{name:`filters[${f}].value`,children:p=>e(p.TfTextField,{autoFocus:!0})}),c.type==="string"&&e(u.AppField,{name:`filters[${f}].value`,children:p=>e(p.TfTextField,{autoFocus:!0})}),c.type==="number"&&e(u.AppField,{name:`filters[${f}].value`,children:p=>e(p.TfNumberField,{autoFocus:!0})}),c.type==="enum"&&e(u.AppField,{name:`filters[${f}].value`,children:p=>{const b=a[c.property];return b.type!=="enum"?null:e(p.TfMultiSelect,{items:b.options})}}),c.type==="id-search"&&e(u.AppField,{name:`filters[${f}].value`,children:p=>{const b=a[c.property];return b.type!=="id-search"?null:e(Qe,{resource:b.resource,accessor:b.accessor,searchFn:b.searchFn})}}),e(S,{type:"button",variant:"neutral",size:"icon",onPress:()=>g.removeValue(f),children:e(U,{})})]},c.id)),l("div",{className:"flex w-full items-center justify-end gap-2 not-first:mt-icon",children:[e(R,{label:"Add filter",autoFocus:!0,children:v.sort().map(c=>{const f=a[c].type,p=pt[f];return l(N,{onAction:()=>{const b=mt(f,c);g.pushValue(b)},children:[d(c),e(p,{})]},c)})}),g.state.value.length>0?l(S,{type:"button",variant:"neutral",onPress:()=>{g.setValue([])},children:[e(U,{}),"Reset"]}):null]})]})})})})]})})}const pt={"id-search":Ke,bool:j,date:Be,enum:je,id:Ue,number:He,string:j};export{dt as C,gt as D,rn as DataTable,X as DataTableContext,nn as DataTableProvider,an as F,en as getTableCallback,y as useDataTable,tn as useDataTableState};
|
|
1
|
+
"use client";import{jsx as e,Fragment as C,jsxs as l}from"react/jsx-runtime";import{createContext as re,useState as F,useMemo as ae,useEffect as ie,useContext as oe,useRef as le}from"react";import{Button as S}from"./button.js";import{useSensors as se,useSensor as k,PointerSensor as ce,KeyboardSensor as ue,DndContext as de,closestCenter as me,DragOverlay as ge}from"@dnd-kit/core";import{sortableKeyboardCoordinates as pe,SortableContext as fe,verticalListSortingStrategy as he,arrayMove as be,useSortable as Se}from"@dnd-kit/sortable";import{CSS as ve}from"@dnd-kit/utilities";import{useQuery as Ce,keepPreviousData as ye}from"@tanstack/react-query";import{createColumnHelper as W,useReactTable as Ie,getCoreRowModel as we,flexRender as V}from"@tanstack/react-table";import{useLocalStorage as H}from"@uidotdev/usehooks";import{merge as xe}from"lodash-es";import{TfDatePicker as Fe}from"./date-picker.js";import{EasyMenu as R,MenuItem as N}from"./menu.js";import{PopoverTrigger as Ne,Popover as Te}from"./popover.js";import{useAppForm as Ae}from"../utilities/form-hook.js";import{useResourceFormatter as M}from"../utilities/resources.js";import{classNames as I}from"../utilities/theme.js";import{IcInfo as Pe,IcMoreVertical as De,IcRefresh as Re,IcColumns as Oe,IcGrip as ze,IcFirst as _e,IcLeft as Le,IcRight as Me,IcLast as Ee,IcSortAsc as $e,IcSortDesc as qe,IcSortNone as ke,IcFilter as Ve,IcRemove as U,IcCheck as j,IcMinus as He,IcAccount as Ue,IcLicense as je,IcDate as Be,IcFile as Ke}from"./icons.js";import{TfMultipleIdSearchInput as Qe}from"./id-search.js";import{Loader as Ge}from"./loader.js";import{SearchField as We}from"./searchfield.js";import{Table as Xe,TableHeader as Ze,TableRow as B,TableHead as Je,TableBody as Ye,TableCell as et}from"./table.js";import{formatDate as K}from"../utilities/date.js";import{Checkbox as Q}from"./checkbox.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";function en(t){const n=async(o,m,a,s)=>{const d={...s,page:o.pageIndex+1,limit:o.pageSize,sort:tt(m[0]),search:a},h=await t(d);return{total:Number.parseInt(h.response.headers.get("Pagination-Count")||"0"),data:h.data}},r=W();return{callback:n,columnHelper:r}}function tt(t){return t?t.desc?`-${t.id}`:`+${t.id}`:"-createdAt"}const T=W(),nt=[T.accessor("checkbox",{header:({table:t})=>e(Q,{isIndeterminate:t.getIsSomeRowsSelected()&&!t.getIsAllPageRowsSelected(),isSelected:t.getIsAllPageRowsSelected()||t.getIsSomePageRowsSelected(),onChange:()=>t.toggleAllPageRowsSelected(),"aria-label":"Select all"}),cell:({row:t})=>e(Q,{isSelected:t.getIsSelected(),onChange:()=>t.toggleSelected(),"aria-label":"Select row"}),enableSorting:!1,enableHiding:!1})],rt=[T.accessor("id",{header:()=>"ID"})],at=[T.accessor("createdAt",{header:()=>"Creation Date",cell:({row:t})=>{const n=t.getValue("createdAt");return K(n)},enableHiding:!1}),T.accessor("updatedAt",{header:()=>"Last Updated",cell:({row:t})=>{const n=t.getValue("updatedAt");return K(n)},enableHiding:!1})],L="TableActions",it=t=>t.length===0?[]:[T.accessor(L,{header:"",id:L,enableHiding:!1,cell:({row:n})=>e(R,{label:e(De,{}),size:"icon",children:t.map(r=>e(N,{isDisabled:r.disabled(n.original),onPress:()=>r.onPress(n.original),children:r.label}))})})];function tn({resourceName:t,columns:n,callback:r,filterConfig:o,columnsToHideByDefault:m={},allowSelection:a=!1,initialFilters:s=[],tableActions:d,rowActions:h}){const[u,v]=F({pagination:{pageIndex:0,pageSize:20},sorting:[]}),[g,c]=F({}),[f,p]=F(""),[b,E]=H(`${t}_ctx_column_order_preference`,[]),[$,Y]=H(`${t}_ctx_column_visibility_preference`,{id:!1,...m}),[O,ee]=F(s),z=ae(()=>O.map(i=>Array.isArray(i.value)?{[i.property]:{[i.operator]:i.value.join(",")}}:{[i.property]:{[i.operator]:i.value}}).reduce((i,x)=>xe(i,x),{}),[O]),_=i=>{v(x=>({...x,...i}))},{sorting:A,pagination:P}=u,D=Ce({queryKey:[t,P,A,f,z],queryFn:()=>r(P,A,f,z),placeholderData:ye,retry:0,refetchOnWindowFocus:!1}),te=[...a?nt:[],...rt,...n,...at,...it(h??[])];function ne(i){return typeof i=="function"}function w(i,x){return ne(i)?i(x):i}const q=Ie({data:D.data?.data??[],columns:te,getCoreRowModel:we(),rowCount:D.data?.total,manualPagination:!0,onPaginationChange:i=>{_({pagination:w(i,P)})},manualSorting:!0,onSortingChange:i=>{c({}),_({sorting:[...w(i,A)]})},manualFiltering:!0,onColumnVisibilityChange:i=>{Y(w(i,$))},onRowSelectionChange:i=>{c(w(i,g))},onColumnOrderChange:i=>{E(w(i,b))},state:{sorting:A,columnVisibility:$,pagination:P,rowSelection:g,columnOrder:b},meta:{refetch:D.refetch}});return ie(()=>{E([...q.getAllLeafColumns().map(i=>i.id)])},[]),{tableState:u,updateTableState:_,query:D,setSearchQuery:p,searchQuery:f,tanTable:q,mergedFilters:z,filters:O,setFilters:ee,filterConfig:o,tableActions:d}}const X=re(null);function y(){const t=oe(X);if(!t)throw Error("DataTable should be used within DataTableProvider.");return t}function nn({children:t,...n}){return e(X.Provider,{value:n,children:t})}function rn({className:t,...n}){const{query:r,tanTable:o}=y();return e(C,{children:l("section",{...n,className:I("flex flex-col bg-elevation-1",t),children:[e(ct,{}),l("div",{className:"w-full overflow-auto border-x h-table relative",tabIndex:0,children:[r.isLoading&&e(G,{className:"cursor-wait",children:e(Ge,{})}),!r.isLoading&&o.getRowModel().rows.length===0&&e(G,{className:"cursor-not-allowed",children:!r.isFetching&&(r.isError?l("span",{className:"flex gap-3 justify-center items-center",children:[e(Pe,{}),e("span",{children:r.error.message})]}):r.data?.data?.length===0?e(C,{children:"No results found."}):e(C,{children:"Unknown error. Please contact customer support."}))}),!r.isLoading&&o.getRowModel().rows.length!==0&&e(ut,{className:"w-full"})]}),l("div",{className:"flex w-full justify-between border gap-icon p-icon overflow-x-auto",children:[l("div",{className:"flex gap-icon",children:[e(ot,{}),e(st,{})]}),e(lt,{})]})]})})}function G({children:t,className:n}){return l(C,{children:[e("span",{className:I(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 ot(){const{tanTable:t}=y(),[n,r]=F(null),o=M(),m=se(k(ce),k(ue,{coordinateGetter:pe}));return e(de,{sensors:m,collisionDetection:me,onDragStart:s=>{const{active:d}=s;r(d.id.toString())},onDragEnd:s=>{const{active:d,over:h}=s;if(h&&d.id!==h.id){const u=t.getState().columnOrder,v=u.indexOf(d.id.toString()),g=u.indexOf(h.id.toString());t.setColumnOrder([...be(u,v,g)])}r(null)},children:l(fe,{items:t.getState().columnOrder,strategy:he,children:[l(R,{label:l(C,{children:[e(Oe,{className:"inline align-bottom me-1"}),"Columns"]}),selectionMode:"multiple",items:t.getAllFlatColumns(),selectedKeys:t.getVisibleFlatColumns().map(s=>s.id),children:[e(N,{onAction:()=>t.toggleAllColumnsVisible(),className:"italic",children:"(select all)"}),t.getState().columnOrder.map(s=>{const d=t.getAllFlatColumns().find(h=>h.id===s);return d?e(a,{column:d},d.id):null})]}),e(ge,{children:n?e("div",{className:"opacity-70 border-2 border-primary",children:o(n)}):null})]})});function a({column:s}){const{attributes:d,listeners:h,setNodeRef:u,transform:v,transition:g}=Se({id:s.id}),c={transform:ve.Transform.toString(v),transition:g,zIndex:"999"};return l(N,{ref:u,style:c,...d,id:s.id,onAction:()=>s.toggleVisibility(),isDisabled:!s.getCanHide(),className:"flex items-center",children:[e(ze,{...h,className:"size-icon cursor-grab"}),o(s.id),s.getIsSorted()&&e(Z,{className:"size-icon",direction:s.getIsSorted()})]})}}function lt(){const{tanTable:t,query:n}=y(),r=n.data?.total??0;return l("div",{className:"flex items-center gap-2",children:[e("span",{className:"whitespace-nowrap body-sm text-muted",children:`${t.getState().pagination.pageIndex*t.getState().pagination.pageSize+1} - ${Math.min((t.getState().pagination.pageIndex+1)*t.getState().pagination.pageSize,r)} of ${r?.toLocaleString()}`}),e(S,{"aria-label":"First page",onPress:()=>t.firstPage(),isDisabled:!t.getCanPreviousPage(),variant:"neutral",size:"icon",children:e(_e,{})}),e(S,{"aria-label":"Previous page",onPress:()=>t.previousPage(),isDisabled:!t.getCanPreviousPage(),variant:"neutral",size:"icon",children:e(Le,{})}),e(S,{"aria-label":"Next page",onPress:()=>t.nextPage(),isDisabled:!t.getCanNextPage(),variant:"neutral",size:"icon",children:e(Me,{})}),e(S,{"aria-label":"Last page",onClick:()=>t.lastPage(),isDisabled:!t.getCanNextPage(),variant:"neutral",size:"icon",children:e(Ee,{})})]})}function st(){const{tanTable:t}=y(),n=[10,20,30,40,50];return e(R,{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(N,{onAction:()=>t.setPageSize(r.value),children:r.value})})}function ct(){const{query:t,tanTable:n,searchQuery:r,setSearchQuery:o,tableActions:m}=y();return l("section",{className:"flex bg-elevation-1 justify-between my-0 p-icon border gap-icon overflow-auto",children:[l("div",{className:"flex gap-icon",children:[e(S,{"aria-label":"Refresh",isPending:t.isFetching,onClick:()=>t.refetch(),variant:"neutral",size:"icon",children:e(Re,{})}),m.filter(a=>a.bulk===n.getSelectedRowModel().rows.length>0).map((a,s)=>{const d=a.icon;return e(S,{"aria-label":a.label,type:"button",isDisabled:t.isFetching,className:"animate-in fade-in slide-in-from-left-15 duration-300 transition-transform",onPress:h=>{a.onClick(h,n.getSelectedRowModel().rows.map(u=>u.original))},size:"icon",children:e(d,{})},`${s}-${a.bulk}`)})]}),l("div",{className:"flex gap-icon",children:[e(gt,{}),e(We,{value:r,onChange:o})]})]})}function Z({direction:t,...n}){return t==="asc"?e($e,{className:"size-3.5",...n}):t==="desc"?e(qe,{className:"size-3.5",...n}):e(ke,{className:"size-3.5",...n})}function ut({className:t}){const{tanTable:n}=y(),r=M(),o=(m,a)=>I("px-icon py-2 text-left body-sm font-medium whitespace-nowrap",m&&"bg-elevation-1 sticky right-0 z-50 text-center",a);return l(Xe,{className:I("table-auto",t),children:[e(Ze,{className:"sticky top-0 z-10",children:n.getHeaderGroups().map(m=>e(B,{children:m.headers.map(a=>l(Je,{scope:"col",colSpan:a.colSpan,className:o(!1,"bg-elevation-1"),children:[!a.column.getCanSort()&&!a.isPlaceholder&&V(a.column.columnDef.header,a.getContext()),a.column.getCanSort()&&l(S,{variant:"ghost",className:"w-full justify-start p-1",onPress:a.column.getToggleSortingHandler(),children:[e("span",{children:r(a.id)}),e(Z,{direction:a.column.getIsSorted()})]})]},a.id))},m.id))}),e(Ye,{children:n.getRowModel().rows.map(m=>e(B,{className:I("transition-colors data-[selected=true]:bg-primary/10 hover:bg-muted-foreground/20"),"data-selected":m.getIsSelected(),children:m.getVisibleCells().map(a=>e(et,{className:o(a.column.id===L),children:V(a.column.columnDef.cell,a.getContext())},a.id))},m.id))})]})}const an=["eq","ne","cn","nc","sw","ew","in","nin","gt","gte","lt","lte"],dt={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 mt(t,n){const r=`${n}-${Date.now()}`,o=J[t][0];switch(t){case"bool":return{id:r,type:t,property:n,operator:o,value:!0};case"string":return{id:r,type:t,property:n,operator:o,value:""};case"date":return{id:r,type:t,property:n,operator:o,value:new Date().toISOString()};case"id":return{id:r,type:t,property:n,operator:o,value:""};case"id-search":return{id:r,type:t,property:n,operator:o,value:[]};case"enum":return{id:r,type:t,property:n,operator:o,value:new Set};case"number":return{id:r,type:t,property:n,operator:o,value:0}}}const J={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 gt({className:t,...n}){const{filters:r,query:o,setFilters:m,filterConfig:a}=y(),s=le(null),d=M(),u=Ae({defaultValues:{filters:r},onSubmit:({value:g})=>{m(g.filters)}}),v=Object.keys(a).sort();return e("section",{...n,className:I("flex gap-icon items-center",t),children:l(Ne,{onOpenChange:g=>{g?s.current?.focus():u.handleSubmit()},children:[l("div",{className:"relative",children:[r.length>0&&e("div",{className:"size-2 rounded-full absolute bg-primary/90 z-20 top-0 right-0 translate-x-0.5 -translate-y-0.5"}),e(S,{"aria-label":"Filter",isDisabled:o.isPending||v.length===0,type:"button",size:"icon",variant:"neutral",children:e(Ve,{})})]}),e(Te,{className:"w-full p-icon",children:e("form",{onSubmit:g=>{g.preventDefault()},className:"flex flex-col gap-icon max-h-table overflow-auto ",children:e(u.Field,{mode:"array",name:"filters",children:g=>l(C,{children:[g.state.value.map((c,f)=>l("div",{className:"flex gap-icon items-center justify-normal",children:[e("span",{className:"body-sm",children:d(c.property)}),e(u.AppField,{name:`filters[${f}].operator`,children:p=>e(p.TfSingleSelect,{items:J[c.type].map(b=>({id:b,label:e(C,{children:dt[b]})}))})},c.id),c.type==="bool"&&e(u.AppField,{name:`filters[${f}].value`,children:p=>e(p.TfCheckbox,{autoFocus:!0})}),c.type==="date"&&e(u.AppField,{name:`filters[${f}].value`,children:p=>e(Fe,{autoFocus:!0})}),c.type==="id"&&e(u.AppField,{name:`filters[${f}].value`,children:p=>e(p.TfTextField,{autoFocus:!0})}),c.type==="string"&&e(u.AppField,{name:`filters[${f}].value`,children:p=>e(p.TfTextField,{autoFocus:!0})}),c.type==="number"&&e(u.AppField,{name:`filters[${f}].value`,children:p=>e(p.TfNumberField,{autoFocus:!0})}),c.type==="enum"&&e(u.AppField,{name:`filters[${f}].value`,children:p=>{const b=a[c.property];return b.type!=="enum"?null:e(p.TfMultiSelect,{items:b.options})}}),c.type==="id-search"&&e(u.AppField,{name:`filters[${f}].value`,children:p=>{const b=a[c.property];return b.type!=="id-search"?null:e(Qe,{resource:b.resource,accessor:b.accessor,searchFn:b.searchFn})}}),e(S,{type:"button",variant:"neutral",size:"icon",onPress:()=>g.removeValue(f),children:e(U,{})})]},c.id)),l("div",{className:"flex w-full items-center justify-end gap-2 not-first:mt-icon",children:[e(R,{label:"Add filter",autoFocus:!0,children:v.sort().map(c=>{const f=a[c].type,p=pt[f];return l(N,{onAction:()=>{const b=mt(f,c);g.pushValue(b)},children:[d(c),e(p,{})]},c)})}),g.state.value.length>0?l(S,{type:"button",variant:"neutral",onPress:()=>{g.setValue([])},children:[e(U,{}),"Reset"]}):null]})]})})})})]})})}const pt={"id-search":Ke,bool:j,date:Be,enum:je,id:Ue,number:He,string:j};export{dt as C,gt as D,rn as DataTable,X as DataTableContext,nn as DataTableProvider,an as F,en as getTableCallback,y as useDataTable,tn 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 { keepPreviousData, useQuery } from '@tanstack/react-query';\nimport {\n type Column,\n type ColumnDef,\n type ColumnHelper,\n type ColumnOrderState,\n createColumnHelper,\n flexRender,\n getCoreRowModel,\n type PaginationState,\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 type { PressEvent } from 'react-aria-components';\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 { formatDate } from '../utilities/date';\nimport type { CtxResourceName } from '../utilities/resources';\nimport { 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\n/** Reserved name for actions column */\n// export const ACTIONS_COLUMN_ID = 'tableActions';\n\nexport type TableAction<in TActionData> = {\n label: string;\n onClick: (e: PressEvent, t: TActionData[]) => void;\n bulk: boolean;\n icon: CtxIcon;\n tooltip?: string;\n};\n\nexport type TableFetchFn<in out TData extends object> = (\n p: PaginationState,\n s: SortingState,\n q: string,\n f: Record<string, any>\n) => Promise<{\n total: number;\n data: TData[] | undefined;\n}>;\nexport function getTableCallback<T extends object>(\n getter: (\n q: Record<string, any>\n ) => Promise<{ data?: T[]; error?: { code?: string | null; message: string }; response: Response }>\n): { callback: TableFetchFn<T>; columnHelper: ColumnHelper<T> } {\n const callback: TableFetchFn<T> = async (pagination, sorting, searching, filters) => {\n const query = {\n ...filters,\n page: pagination.pageIndex + 1,\n limit: pagination.pageSize,\n sort: generateSortParam(sorting[0]),\n search: searching,\n };\n\n const _f = await getter(query);\n\n return {\n total: Number.parseInt(_f.response.headers.get('Pagination-Count') || '0'),\n data: _f.data,\n };\n };\n\n const columnHelper = createColumnHelper<T>();\n\n return { callback, columnHelper };\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 TABLE_ID_COLUMN = [\n cH.accessor('id', {\n header: () => 'ID',\n }),\n];\nconst TABLE_DEFAULT_DATE_COLUMNS = [\n cH.accessor('createdAt', {\n header: () => 'Creation Date',\n cell: ({ row }) => {\n const date = row.getValue('createdAt') satisfies string | null | undefined;\n return formatDate(date);\n },\n enableHiding: false,\n }),\n cH.accessor('updatedAt', {\n header: () => 'Last Updated',\n cell: ({ row }) => {\n const date = row.getValue('updatedAt') satisfies string | null | undefined;\n return formatDate(date);\n },\n enableHiding: false,\n }),\n];\n\nconst ACTIONS_COLUMN_ID = 'TableActions';\nconst getActionColumn = (rowActions: RowAction<any>[]) => {\n if (rowActions.length === 0) return [];\n\n return [\n cH.accessor(ACTIONS_COLUMN_ID, {\n header: '',\n id: ACTIONS_COLUMN_ID,\n enableHiding: false,\n cell: ({ row }) => (\n <EasyMenu label={<IcMoreVertical />} size={'icon'}>\n {rowActions.map(ra => (\n <MenuItem isDisabled={ra.disabled(row.original)} onPress={() => ra.onPress(row.original)}>\n {ra.label}\n </MenuItem>\n ))}\n </EasyMenu>\n ),\n }),\n ];\n};\n\ntype RowAction<T> = {\n onPress: (t: T) => void;\n label: React.ReactElement;\n disabled: (t: T) => boolean;\n};\n\ntype DataTableFactory<T extends object, TOperation extends keyof operations> = {\n resourceName: CtxResourceName;\n callback: TableFetchFn<T>;\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?: RowAction<T>[];\n};\n\ntype DataTableState = {\n sorting: SortingState;\n pagination: PaginationState;\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 resourceName,\n columns,\n callback,\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 [rowSelection, setRowSelection] = useState<RowSelectionState>({});\n\n /** Reflect in URL in host application */\n const [searchQuery, setSearchQuery] = useState('');\n\n const [columnOrder, setColumnOrder] = useLocalStorage<ColumnOrderState>(\n `${resourceName}_ctx_column_order_preference`,\n []\n );\n const [columnVisibility, setColumnVisibility] = useLocalStorage<VisibilityState>(\n `${resourceName}_ctx_column_visibility_preference`,\n {\n id: false,\n ...columnsToHideByDefault,\n }\n );\n\n const [filters, setFilters] = useState(initialFilters);\n\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 // Update table state with new values\n const updateTableState = (updates: Partial<DataTableState>) => {\n _setTableState(prev => ({ ...prev, ...updates }));\n };\n\n const { sorting, pagination } = tableState;\n\n const query = useQuery({\n queryKey: [resourceName, pagination, sorting, searchQuery, mergedFilters],\n queryFn: () => callback(pagination, sorting, searchQuery, mergedFilters),\n placeholderData: keepPreviousData, // Keep previous data while loading new data\n retry: 0,\n refetchOnWindowFocus: false,\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 ...TABLE_ID_COLUMN,\n ...columns,\n ...TABLE_DEFAULT_DATE_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,\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 if (!col) 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 {resourceFormatter(column.id)}\n {column.getIsSorted() && <SortIcon className=\"size-icon\" direction={column.getIsSorted()} />}\n </MenuItem>\n );\n }\n}\n\nfunction Paginator() {\n const { tanTable, query } = useDataTable();\n const rowCount = query.data?.total ?? 0;\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\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\n .filter(ta => ta.bulk === tanTable.getSelectedRowModel().rows.length > 0)\n .map((ta, i) => {\n const Icon = ta.icon;\n return (\n <Button\n aria-label={ta.label}\n key={`${i}-${ta.bulk}`}\n type=\"button\"\n isDisabled={query.isFetching}\n className=\"animate-in fade-in slide-in-from-left-15 duration-300 transition-transform\"\n onPress={e => {\n ta.onClick(\n e,\n tanTable.getSelectedRowModel().rows.map(r => r.original)\n );\n }}\n size={'icon'}\n >\n <Icon />\n </Button>\n );\n })}\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\n// TODO, automate checking valid HTML\nfunction TableContent({ className }: React.ComponentProps<typeof TableComponent>) {\n const { tanTable } = useDataTable();\n const resourceFormatter = useResourceFormatter();\n const tableCellStyle = (isSticky: boolean, className?: string) =>\n classNames(\n 'px-icon py-2 text-left body-sm font-medium whitespace-nowrap',\n isSticky && 'bg-elevation-1 sticky right-0 z-50 text-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(false, 'bg-elevation-1')}\n >\n {/* TODO, custom headers should be supported */}\n {/* TODO, styling breaks if enableSorting:false */}\n {!header.column.getCanSort() &&\n !header.isPlaceholder &&\n flexRender(header.column.columnDef.header, header.getContext())}\n {header.column.getCanSort() && (\n <Button\n variant=\"ghost\"\n className=\"w-full justify-start p-1\"\n onPress={header.column.getToggleSortingHandler()}\n >\n <span>{resourceFormatter(header.id)}</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 <TableCell key={cell.id} className={tableCellStyle(cell.column.id === ACTIONS_COLUMN_ID)}>\n {flexRender(cell.column.columnDef.cell, cell.getContext())}\n </TableCell>\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', Set<string | number>>;\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: new Set<string | number>() };\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<\n React.ComponentProps<typeof TfMultipleIdSearchInput>,\n 'accessor' | 'searchFn' | 'resource'\n >)\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 resource={config.resource}\n accessor={config.accessor}\n searchFn={config.searchFn}\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":["getTableCallback","getter","callback","pagination","sorting","searching","filters","query","generateSortParam","_f","columnHelper","createColumnHelper","sort","cH","TABLE_CHECK_BOX_COLUMN","table","jsx","Checkbox","row","TABLE_ID_COLUMN","TABLE_DEFAULT_DATE_COLUMNS","date","formatDate","ACTIONS_COLUMN_ID","getActionColumn","rowActions","EasyMenu","IcMoreVertical","ra","MenuItem","useDataTableState","resourceName","columns","filterConfig","columnsToHideByDefault","allowSelection","initialFilters","tableActions","tableState","_setTableState","useState","rowSelection","setRowSelection","searchQuery","setSearchQuery","columnOrder","setColumnOrder","useLocalStorage","columnVisibility","setColumnVisibility","setFilters","mergedFilters","useMemo","tf","acc","current","merge","updateTableState","updates","prev","useQuery","keepPreviousData","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","IcColumns","colId","col","SortableItem","DragOverlay","column","attributes","listeners","setNodeRef","transform","transition","useSortable","style","CSS","IcGrip","SortIcon","rowCount","Button","IcFirst","IcLeft","IcRight","IcLast","PAGE_SIZES","s","items","IcRefresh","ta","i","Icon","e","r","DataTableFilter","SearchField","direction","IcSortAsc","IcSortDesc","IcSortNone","tableCellStyle","isSticky","TableComponent","TableHeader","headerGroup","TableRow","header","TableHead","flexRender","TableBody","cell","TableCell","FILTER_COMPARISON_OPERATORS","COMPARISON_OPERATOR_LABELS","createNewFilter","type","property","id","operator","FilterOperations","addFilterButtonRef","useRef","form","useAppForm","value","filterKeys","PopoverTrigger","o","IcFilter","Popover","field","lf","sf","op","_","TfDatePicker","config","TfMultipleIdSearchInput","IcRemove","k","FilterIcon","newFilter","IcFile","IcCheck","IcDate","IcLicense","IcAccount","IcMinus"],"mappings":"muEAsFO,SAASA,GACZC,EAG4D,CAC5D,MAAMC,EAA4B,MAAOC,EAAYC,EAASC,EAAWC,IAAY,CACjF,MAAMC,EAAQ,CACV,GAAGD,EACH,KAAMH,EAAW,UAAY,EAC7B,MAAOA,EAAW,SAClB,KAAMK,GAAkBJ,EAAQ,CAAC,CAAC,EAClC,OAAQC,CAAA,EAGNI,EAAK,MAAMR,EAAOM,CAAK,EAE7B,MAAO,CACH,MAAO,OAAO,SAASE,EAAG,SAAS,QAAQ,IAAI,kBAAkB,GAAK,GAAG,EACzE,KAAMA,EAAG,IAAA,CAEjB,EAEMC,EAAeC,EAAA,EAErB,MAAO,CAAE,SAAAT,EAAU,aAAAQ,CAAA,CACvB,CAEA,SAASF,GAAkBI,EAAyD,CAChF,OAAIA,EACIA,EAAK,KACE,IAAIA,EAAK,EAAE,GAEX,IAAIA,EAAK,EAAE,GAGf,YAEf,CAEA,MAAMC,EAAKF,EAAA,EACLG,GAAyB,CAC3BD,EAAG,SAAS,WAAY,CACpB,OAAQ,CAAC,CAAE,MAAAE,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,GAAkB,CACpBN,EAAG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S,EACxB/F,EAAC6C,EAAA,CACG,KAAK,SACL,QAAQ,UACR,QAAS,IAAM,CACXkD,EAAM,SAAS,EAAE,CACrB,EAEA,SAAA,CAAApK,EAAC4K,EAAA,EAAS,EAAE,OAAA,CAAA,CAAA,EAGhB,IAAA,CAAA,CACR,CAAA,EACJ,CAER,CACJ,CAAA,CAAA,CACJ,CACJ,CAAA,CAAA,CAAA,EAER,CAER,CAEA,MAAME,GAAoD,CACtD,YAAaE,GACb,KAAMC,EACN,KAAMC,GACN,KAAMC,GACN,GAAIC,GACJ,OAAQC,GACR,OAAQJ,CACZ"}
|
|
1
|
+
{"version":3,"file":"data-table.js","sources":["../../lib/components/data-table.tsx","../../lib/components/data-table-filter.tsx"],"sourcesContent":["'use client';\nimport type { operations } from '@cryptlex/web-api-types/develop';\nimport {\n closestCenter,\n DndContext,\n DragOverlay,\n KeyboardSensor,\n PointerSensor,\n useSensor,\n useSensors,\n} from '@dnd-kit/core';\nimport {\n arrayMove,\n SortableContext,\n sortableKeyboardCoordinates,\n useSortable,\n verticalListSortingStrategy,\n} from '@dnd-kit/sortable';\nimport { CSS } from '@dnd-kit/utilities';\nimport { keepPreviousData, useQuery } from '@tanstack/react-query';\nimport {\n type Column,\n type ColumnDef,\n type ColumnHelper,\n type ColumnOrderState,\n createColumnHelper,\n flexRender,\n getCoreRowModel,\n type PaginationState,\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 type { PressEvent } from 'react-aria-components';\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 { formatDate } from '../utilities/date';\nimport type { CtxResourceName } from '../utilities/resources';\nimport { 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\n/** Reserved name for actions column */\n// export const ACTIONS_COLUMN_ID = 'tableActions';\n\nexport type TableAction<in TActionData> = {\n label: string;\n onClick: (e: PressEvent, t: TActionData[]) => void;\n bulk: boolean;\n icon: CtxIcon;\n tooltip?: string;\n};\n\nexport type TableFetchFn<in out TData extends object> = (\n p: PaginationState,\n s: SortingState,\n q: string,\n f: Record<string, any>\n) => Promise<{\n total: number;\n data: TData[] | undefined;\n}>;\nexport function getTableCallback<T extends object>(\n getter: (\n q: Record<string, any>\n ) => Promise<{ data?: T[]; error?: { code?: string | null; message: string }; response: Response }>\n): { callback: TableFetchFn<T>; columnHelper: ColumnHelper<T> } {\n const callback: TableFetchFn<T> = async (pagination, sorting, searching, filters) => {\n const query = {\n ...filters,\n page: pagination.pageIndex + 1,\n limit: pagination.pageSize,\n sort: generateSortParam(sorting[0]),\n search: searching,\n };\n\n const _f = await getter(query);\n\n return {\n total: Number.parseInt(_f.response.headers.get('Pagination-Count') || '0'),\n data: _f.data,\n };\n };\n\n const columnHelper = createColumnHelper<T>();\n\n return { callback, columnHelper };\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 TABLE_ID_COLUMN = [\n cH.accessor('id', {\n header: () => 'ID',\n }),\n];\nconst TABLE_DEFAULT_DATE_COLUMNS = [\n cH.accessor('createdAt', {\n header: () => 'Creation Date',\n cell: ({ row }) => {\n const date = row.getValue('createdAt') satisfies string | null | undefined;\n return formatDate(date);\n },\n enableHiding: false,\n }),\n cH.accessor('updatedAt', {\n header: () => 'Last Updated',\n cell: ({ row }) => {\n const date = row.getValue('updatedAt') satisfies string | null | undefined;\n return formatDate(date);\n },\n enableHiding: false,\n }),\n];\n\nconst ACTIONS_COLUMN_ID = 'TableActions';\nconst getActionColumn = (rowActions: RowAction<any>[]) => {\n if (rowActions.length === 0) return [];\n\n return [\n cH.accessor(ACTIONS_COLUMN_ID, {\n header: '',\n id: ACTIONS_COLUMN_ID,\n enableHiding: false,\n cell: ({ row }) => (\n <EasyMenu label={<IcMoreVertical />} size={'icon'}>\n {rowActions.map(ra => (\n <MenuItem isDisabled={ra.disabled(row.original)} onPress={() => ra.onPress(row.original)}>\n {ra.label}\n </MenuItem>\n ))}\n </EasyMenu>\n ),\n }),\n ];\n};\n\ntype RowAction<T> = {\n onPress: (t: T) => void;\n label: React.ReactElement;\n disabled: (t: T) => boolean;\n};\n\ntype DataTableFactory<T extends object, TOperation extends keyof operations> = {\n resourceName: CtxResourceName;\n callback: TableFetchFn<T>;\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?: RowAction<T>[];\n};\n\ntype DataTableState = {\n sorting: SortingState;\n pagination: PaginationState;\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 resourceName,\n columns,\n callback,\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 [rowSelection, setRowSelection] = useState<RowSelectionState>({});\n\n /** Reflect in URL in host application */\n const [searchQuery, setSearchQuery] = useState('');\n\n const [columnOrder, setColumnOrder] = useLocalStorage<ColumnOrderState>(\n `${resourceName}_ctx_column_order_preference`,\n []\n );\n const [columnVisibility, setColumnVisibility] = useLocalStorage<VisibilityState>(\n `${resourceName}_ctx_column_visibility_preference`,\n {\n id: false,\n ...columnsToHideByDefault,\n }\n );\n\n const [filters, setFilters] = useState(initialFilters);\n\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 // Update table state with new values\n const updateTableState = (updates: Partial<DataTableState>) => {\n _setTableState(prev => ({ ...prev, ...updates }));\n };\n\n const { sorting, pagination } = tableState;\n\n const query = useQuery({\n queryKey: [resourceName, pagination, sorting, searchQuery, mergedFilters],\n queryFn: () => callback(pagination, sorting, searchQuery, mergedFilters),\n placeholderData: keepPreviousData, // Keep previous data while loading new data\n retry: 0,\n refetchOnWindowFocus: false,\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 ...TABLE_ID_COLUMN,\n ...columns,\n ...TABLE_DEFAULT_DATE_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,\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 if (!col) 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 {resourceFormatter(column.id)}\n {column.getIsSorted() && <SortIcon className=\"size-icon\" direction={column.getIsSorted()} />}\n </MenuItem>\n );\n }\n}\n\nfunction Paginator() {\n const { tanTable, query } = useDataTable();\n const rowCount = query.data?.total ?? 0;\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\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\n .filter(ta => ta.bulk === tanTable.getSelectedRowModel().rows.length > 0)\n .map((ta, i) => {\n const Icon = ta.icon;\n return (\n <Button\n aria-label={ta.label}\n key={`${i}-${ta.bulk}`}\n type=\"button\"\n isDisabled={query.isFetching}\n className=\"animate-in fade-in slide-in-from-left-15 duration-300 transition-transform\"\n onPress={e => {\n ta.onClick(\n e,\n tanTable.getSelectedRowModel().rows.map(r => r.original)\n );\n }}\n size={'icon'}\n >\n <Icon />\n </Button>\n );\n })}\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\n// TODO, automate checking valid HTML\nfunction TableContent({ className }: React.ComponentProps<typeof TableComponent>) {\n const { tanTable } = useDataTable();\n const resourceFormatter = useResourceFormatter();\n const tableCellStyle = (isSticky: boolean, className?: string) =>\n classNames(\n 'px-icon py-2 text-left body-sm font-medium whitespace-nowrap',\n isSticky && 'bg-elevation-1 sticky right-0 z-50 text-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(false, 'bg-elevation-1')}\n >\n {/* TODO, custom headers should be supported */}\n {/* TODO, styling breaks if enableSorting:false */}\n {!header.column.getCanSort() &&\n !header.isPlaceholder &&\n flexRender(header.column.columnDef.header, header.getContext())}\n {header.column.getCanSort() && (\n <Button\n variant=\"ghost\"\n className=\"w-full justify-start p-1\"\n onPress={header.column.getToggleSortingHandler()}\n >\n <span>{resourceFormatter(header.id)}</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 <TableCell key={cell.id} className={tableCellStyle(cell.column.id === ACTIONS_COLUMN_ID)}>\n {flexRender(cell.column.columnDef.cell, cell.getContext())}\n </TableCell>\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<\n React.ComponentProps<typeof TfMultipleIdSearchInput>,\n 'accessor' | 'searchFn' | 'resource'\n >)\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 resource={config.resource}\n accessor={config.accessor}\n searchFn={config.searchFn}\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":["getTableCallback","getter","callback","pagination","sorting","searching","filters","query","generateSortParam","_f","columnHelper","createColumnHelper","sort","cH","TABLE_CHECK_BOX_COLUMN","table","jsx","Checkbox","row","TABLE_ID_COLUMN","TABLE_DEFAULT_DATE_COLUMNS","date","formatDate","ACTIONS_COLUMN_ID","getActionColumn","rowActions","EasyMenu","IcMoreVertical","ra","MenuItem","useDataTableState","resourceName","columns","filterConfig","columnsToHideByDefault","allowSelection","initialFilters","tableActions","tableState","_setTableState","useState","rowSelection","setRowSelection","searchQuery","setSearchQuery","columnOrder","setColumnOrder","useLocalStorage","columnVisibility","setColumnVisibility","setFilters","mergedFilters","useMemo","tf","acc","current","merge","updateTableState","updates","prev","useQuery","keepPreviousData","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","IcColumns","colId","col","SortableItem","DragOverlay","column","attributes","listeners","setNodeRef","transform","transition","useSortable","style","CSS","IcGrip","SortIcon","rowCount","Button","IcFirst","IcLeft","IcRight","IcLast","PAGE_SIZES","s","items","IcRefresh","ta","i","Icon","e","r","DataTableFilter","SearchField","direction","IcSortAsc","IcSortDesc","IcSortNone","tableCellStyle","isSticky","TableComponent","TableHeader","headerGroup","TableRow","header","TableHead","flexRender","TableBody","cell","TableCell","FILTER_COMPARISON_OPERATORS","COMPARISON_OPERATOR_LABELS","createNewFilter","type","property","id","operator","FilterOperations","addFilterButtonRef","useRef","form","useAppForm","value","filterKeys","PopoverTrigger","o","IcFilter","Popover","field","lf","sf","op","_","TfDatePicker","config","TfMultipleIdSearchInput","IcRemove","k","FilterIcon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,EAGhB,IAAA,CAAA,CACR,CAAA,EACJ,CAER,CACJ,CAAA,CAAA,CACJ,CACJ,CAAA,CAAA,CAAA,EAER,CAER,CAEA,MAAME,GAAoD,CACtD,YAAaE,GACb,KAAMC,EACN,KAAMC,GACN,KAAMC,GACN,GAAIC,GACJ,OAAQC,GACR,OAAQJ,CACZ"}
|
package/dist/components/form.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{jsxs as a,Fragment as d,jsx as n}from"react/jsx-runtime";import{cva as l}from"class-variance-authority";import{Group as u,composeRenderProps as c,Label as f,Text as p,Button as g}from"react-aria-components";import{classNames as i}from"../utilities/theme.js";import{IcInfo as b,IcError as h}from"./icons.js";import"clsx";import"react";const x=l(["select-none body-sm font-medium leading-none","disabled-muted","group-data-[invalid]:text-destructive"]);function F({className:t,...e}){return n(f,{className:i(x(),t),...e})}function N({className:t,children:e,...r}){return a(p,{className:i("body-sm text-muted leading-tight",t),...r,slot:"description",children:[e,n(b,{className:"inline size-2 align-text-top ms-0.5"})]})}function v({className:t,children:e,...r}){return a("label",{role:"alert",className:i("body-sm leading-tight text-destructive duration-150 animate-in transition-transform slide-in-from-top-5 fade-in",t),...r,children:[e,n(h,{className:"inline size-2 align-text-top ms-0.5"})]})}const y=l("",{variants:{variant:{default:["relative flex w-full items-center overflow-hidden border border-input bg-elevation-2 input-dim ring-offset-background placeholder:text-muted-foreground","focus-ring","disabled-muted"],ghost:""}},defaultVariants:{variant:"default"}});function k({className:t,variant:e,...r}){return n(u,{className:c(t,o=>i(y({variant:e}),o)),...r})}function w({label:t,description:e,errorMessage:r,children:o,requiredIndicator:m,htmlFor:s}){return a(d,{children:[t&&a(F,{htmlFor:s,children:[t,m&&n("sup",{className:"text-destructive",children:"*"})]}),o,e&&n(N,{children:e}),r&&n(v,{htmlFor:s,children:r})]})}function B({className:t,...e}){return n(g,{className:c(t,r=>i("btn btn-ghost h-input px-2 -me-2",r)),...e})}function D({className:t,onSubmit:e,...r}){return n("form",{className:i(t),onSubmit:o=>{o.preventDefault(),e?.(o)},...r})}function E({className:t,...e}){return n("section",{className:i("flex flex-col gap-input border-
|
|
1
|
+
"use client";import{jsxs as a,Fragment as d,jsx as n}from"react/jsx-runtime";import{cva as l}from"class-variance-authority";import{Group as u,composeRenderProps as c,Label as f,Text as p,Button as g}from"react-aria-components";import{classNames as i}from"../utilities/theme.js";import{IcInfo as b,IcError as h}from"./icons.js";import"clsx";import"react";const x=l(["select-none body-sm font-medium leading-none","disabled-muted","group-data-[invalid]:text-destructive"]);function F({className:t,...e}){return n(f,{className:i(x(),t),...e})}function N({className:t,children:e,...r}){return a(p,{className:i("body-sm text-muted leading-tight",t),...r,slot:"description",children:[e,n(b,{className:"inline size-2 align-text-top ms-0.5"})]})}function v({className:t,children:e,...r}){return a("label",{role:"alert",className:i("body-sm leading-tight text-destructive duration-150 animate-in transition-transform slide-in-from-top-5 fade-in",t),...r,children:[e,n(h,{className:"inline size-2 align-text-top ms-0.5"})]})}const y=l("",{variants:{variant:{default:["relative flex w-full items-center overflow-hidden border border-input bg-elevation-2 input-dim ring-offset-background placeholder:text-muted-foreground","focus-ring","disabled-muted"],ghost:""}},defaultVariants:{variant:"default"}});function k({className:t,variant:e,...r}){return n(u,{className:c(t,o=>i(y({variant:e}),o)),...r})}function w({label:t,description:e,errorMessage:r,children:o,requiredIndicator:m,htmlFor:s}){return a(d,{children:[t&&a(F,{htmlFor:s,children:[t,m&&n("sup",{className:"text-destructive",children:"*"})]}),o,e&&n(N,{children:e}),r&&n(v,{htmlFor:s,children:r})]})}function B({className:t,...e}){return n(g,{className:c(t,r=>i("btn btn-ghost h-input px-2 -me-2",r)),...e})}function D({className:t,onSubmit:e,...r}){return n("form",{className:i(t),onSubmit:o=>{o.preventDefault(),e?.(o)},...r})}function E({className:t,...e}){return n("section",{className:i("flex flex-col gap-input border-b py-icon pb-input",t),...e})}function T({className:t,...e}){return n("h2",{className:i("heading-4",t),...e})}function A({className:t,...e}){return n("nav",{className:i("flex items-center justify-end h-header bg-glass-1 sticky bottom-0 z-50 py-icon px-input border-t",t),...e})}function P({className:t,...e}){return n("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-input mt-icon my-header",...e})}export{k as FieldGroup,D as Form,A as FormActionFooter,w as FormField,B as FormFieldButton,N as FormFieldDescription,v as FormFieldError,F as FormFieldLabel,P as FormLayout,E as FormSection,T as FormSectionTitle,y as fieldGroupVariants,x as labelVariants};
|
|
2
2
|
//# sourceMappingURL=form.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"form.js","sources":["../../lib/components/form.tsx"],"sourcesContent":["'use client';\n\nimport { cva, type VariantProps } from 'class-variance-authority';\nimport {\n Button as AriaButton,\n ButtonProps as AriaButtonProps,\n Group as AriaGroup,\n GroupProps as AriaGroupProps,\n Label as AriaLabel,\n LabelProps as AriaLabelProps,\n Text as AriaText,\n TextProps as AriaTextProps,\n composeRenderProps,\n} from 'react-aria-components';\n\nimport { classNames } from '../utilities/theme';\nimport { IcError, IcInfo } from './icons';\n\n/**\n * Class variance authority variants for form field labels.\n * Provides styling for different states including disabled and invalid.\n */\nexport const labelVariants = cva([\n 'select-none body-sm font-medium leading-none',\n /* Disabled */\n 'disabled-muted',\n /* Invalid */\n 'group-data-[invalid]:text-destructive',\n]);\n\n/**\n * A form field label component that extends React Aria's Label component.\n * Applies consistent styling for form labels including disabled and invalid states.\n *\n * @param className - Optional additional CSS classes to apply\n * @param props - All other props from AriaLabelProps\n * @returns A styled label element\n */\nexport function FormFieldLabel({ className, ...props }: AriaLabelProps) {\n return <AriaLabel className={classNames(labelVariants(), className)} {...props} />;\n}\n\n/**\n * A form field description component that provides additional context or help text.\n * Automatically includes an info icon and uses the \"description\" slot for accessibility.\n */\nexport function FormFieldDescription({ className, children, ...props }: AriaTextProps) {\n return (\n <AriaText className={classNames('body-sm text-muted leading-tight', className)} {...props} slot=\"description\">\n {children}\n <IcInfo className=\"inline size-2 align-text-top ms-0.5\" />\n </AriaText>\n );\n}\n/**\n * A form field error component that displays validation error messages.\n *\n * @remarks\n * Currently uses a div instead of AriaFieldError to avoid overlap with Tanstack Form.\n * This approach needs further discussion and exploration.\n *\n */\nexport function FormFieldError({ className, children, ...props }: React.ComponentPropsWithRef<'label'>) {\n return (\n <label\n role=\"alert\"\n className={classNames(\n 'body-sm leading-tight text-destructive duration-150 animate-in transition-transform slide-in-from-top-5 fade-in',\n className\n )}\n {...props}\n >\n {children}\n <IcError className=\"inline size-2 align-text-top ms-0.5\" />\n </label>\n );\n}\n\n/**\n * Class variance authority variants for field groups.\n * Provides styling variants for different types of form field containers.\n */\nexport const fieldGroupVariants = cva('', {\n variants: {\n variant: {\n default: [\n 'relative flex w-full items-center overflow-hidden border border-input bg-elevation-2 input-dim ring-offset-background placeholder:text-muted-foreground',\n /* Focus Within */\n 'focus-ring',\n /* Disabled */\n 'disabled-muted',\n ],\n ghost: '',\n },\n },\n defaultVariants: {\n variant: 'default',\n },\n});\n\n/**\n * Props interface for FieldGroup component.\n * Extends AriaGroupProps with variant styling options.\n */\nexport interface GroupProps extends AriaGroupProps, VariantProps<typeof fieldGroupVariants> {}\n\n/**\n * A field group component that wraps form inputs with consistent styling.\n * Supports different variants for various use cases.\n */\nexport function FieldGroup({ className, variant, ...props }: GroupProps) {\n return (\n <AriaGroup\n className={composeRenderProps(className, className =>\n classNames(fieldGroupVariants({ variant }), className)\n )}\n {...props}\n />\n );\n}\n\n/**\n * Props for the FormField component.\n * Defines the structure for form field configuration.\n */\nexport type FormFieldProps = {\n /** Optional label text for the form field */\n label?: React.ReactNode;\n /** Optional description or help text */\n description?: React.ReactNode;\n /** Optional error message to display */\n errorMessage?: string;\n /** Show required indicator on field label */\n requiredIndicator?: boolean;\n /** Not defining the htmlFor on labels will lead to accessibilty warnings */\n htmlFor?: string;\n};\n\n/**\n * A wrapper component for form fields that provides consistent layout and styling.\n * Automatically renders label, children, description, and error message in the correct order.\n * @returns A complete form field with all associated elements\n */\nexport function FormField({\n label,\n description,\n errorMessage,\n children,\n requiredIndicator,\n htmlFor,\n}: FormFieldProps & {\n children: React.ReactNode;\n}) {\n return (\n <>\n {label && (\n <FormFieldLabel htmlFor={htmlFor}>\n {label}\n {requiredIndicator && <sup className=\"text-destructive\">*</sup>}\n </FormFieldLabel>\n )}\n {children}\n {description && <FormFieldDescription>{description}</FormFieldDescription>}\n {errorMessage && <FormFieldError htmlFor={htmlFor}>{errorMessage}</FormFieldError>}\n </>\n );\n}\n\n/**\n * A button component designed to be used within form fields.\n * Styled to fit nicely alongside form inputs with ghost styling.\n */\nexport function FormFieldButton({ className, ...props }: AriaButtonProps) {\n return (\n <AriaButton\n className={composeRenderProps(className, className =>\n classNames('btn btn-ghost h-input px-2 -me-2', className)\n )}\n {...props}\n />\n );\n}\n\n/**\n * A form component that prevents default form submission and handles submit events.\n * All forms in this application are controlled components, not pure HTML forms.\n */\nexport function Form({ className, onSubmit, ...props }: React.ComponentProps<'form'>) {\n return (\n <form\n className={classNames(className)}\n onSubmit={e => {\n // None of the forms in our applications are pure HTML forms.\n e.preventDefault();\n // If onSubmit is provided, call it.\n onSubmit?.(e);\n }}\n {...props}\n />\n );\n}\n\n/**\n * A section component for organizing form content into logical groups.\n * Provides consistent spacing and visual separation between form sections.\n */\nexport function FormSection({ className, ...props }: React.ComponentProps<'section'>) {\n return <section className={classNames('flex flex-col gap-input border-x p-icon', className)} {...props} />;\n}\n\n/**\n * A title component for form sections.\n */\nexport function FormSectionTitle({ className, ...props }: React.ComponentProps<'h2'>) {\n return <h2 className={classNames('heading-4', className)} {...props} />;\n}\n\nexport function FormActionFooter({ className, ...props }: React.ComponentProps<'nav'>) {\n return (\n <nav\n className={classNames(\n 'flex items-center justify-end h-header bg-glass-1 sticky bottom-0 z-50 py-icon px-input border-t',\n className\n )}\n {...props}\n />\n );\n}\n\nexport function FormLayout({ className, ...props }: React.ComponentProps<'div'>) {\n return <div className={'grid grid-cols-1 lg:grid-cols-2 gap-input mt-icon my-header'} {...props} />;\n}\n"],"names":["labelVariants","cva","FormFieldLabel","className","props","jsx","AriaLabel","classNames","FormFieldDescription","children","jsxs","AriaText","IcInfo","FormFieldError","IcError","fieldGroupVariants","FieldGroup","variant","AriaGroup","composeRenderProps","FormField","label","description","errorMessage","requiredIndicator","htmlFor","Fragment","FormFieldButton","AriaButton","Form","onSubmit","e","FormSection","FormSectionTitle","FormActionFooter","FormLayout"],"mappings":"kWAsBO,MAAMA,EAAgBC,EAAI,CAC7B,+CAEA,iBAEA,uCACJ,CAAC,EAUM,SAASC,EAAe,CAAE,UAAAC,EAAW,GAAGC,GAAyB,CACpE,OAAOC,EAACC,GAAU,UAAWC,EAAWP,IAAiBG,CAAS,EAAI,GAAGC,EAAO,CACpF,CAMO,SAASI,EAAqB,CAAE,UAAAL,EAAW,SAAAM,EAAU,GAAGL,GAAwB,CACnF,OACIM,EAACC,EAAA,CAAS,UAAWJ,EAAW,mCAAoCJ,CAAS,EAAI,GAAGC,EAAO,KAAK,cAC3F,SAAA,CAAAK,EACDJ,EAACO,EAAA,CAAO,UAAU,qCAAA,CAAsC,CAAA,EAC5D,CAER,CASO,SAASC,EAAe,CAAE,UAAAV,EAAW,SAAAM,EAAU,GAAGL,GAA+C,CACpG,OACIM,EAAC,QAAA,CACG,KAAK,QACL,UAAWH,EACP,mHACAJ,CAAA,EAEH,GAAGC,EAEH,SAAA,CAAAK,EACDJ,EAACS,EAAA,CAAQ,UAAU,qCAAA,CAAsC,CAAA,CAAA,CAAA,CAGrE,CAMO,MAAMC,EAAqBd,EAAI,GAAI,CACtC,SAAU,CACN,QAAS,CACL,QAAS,CACL,0JAEA,aAEA,gBAAA,EAEJ,MAAO,EAAA,CACX,EAEJ,gBAAiB,CACb,QAAS,SAAA,CAEjB,CAAC,EAYM,SAASe,EAAW,CAAE,UAAAb,EAAW,QAAAc,EAAS,GAAGb,GAAqB,CACrE,OACIC,EAACa,EAAA,CACG,UAAWC,EAAmBhB,EAAWA,GACrCI,EAAWQ,EAAmB,CAA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C,EAAC,MAAA,CACG,UAAWE,EACP,mGACAJ,CAAA,EAEH,GAAGC,CAAA,CAAA,CAGhB,CAEO,SAAS+B,EAAW,CAAE,UAAAhC,EAAW,GAAGC,GAAsC,CAC7E,OAAOC,EAAC,MAAA,CAAI,UAAW,8DAAgE,GAAGD,EAAO,CACrG"}
|
|
1
|
+
{"version":3,"file":"form.js","sources":["../../lib/components/form.tsx"],"sourcesContent":["'use client';\n\nimport { cva, type VariantProps } from 'class-variance-authority';\nimport {\n Button as AriaButton,\n ButtonProps as AriaButtonProps,\n Group as AriaGroup,\n GroupProps as AriaGroupProps,\n Label as AriaLabel,\n LabelProps as AriaLabelProps,\n Text as AriaText,\n TextProps as AriaTextProps,\n composeRenderProps,\n} from 'react-aria-components';\n\nimport { classNames } from '../utilities/theme';\nimport { IcError, IcInfo } from './icons';\n\n/**\n * Class variance authority variants for form field labels.\n * Provides styling for different states including disabled and invalid.\n */\nexport const labelVariants = cva([\n 'select-none body-sm font-medium leading-none',\n /* Disabled */\n 'disabled-muted',\n /* Invalid */\n 'group-data-[invalid]:text-destructive',\n]);\n\n/**\n * A form field label component that extends React Aria's Label component.\n * Applies consistent styling for form labels including disabled and invalid states.\n *\n * @param className - Optional additional CSS classes to apply\n * @param props - All other props from AriaLabelProps\n * @returns A styled label element\n */\nexport function FormFieldLabel({ className, ...props }: AriaLabelProps) {\n return <AriaLabel className={classNames(labelVariants(), className)} {...props} />;\n}\n\n/**\n * A form field description component that provides additional context or help text.\n * Automatically includes an info icon and uses the \"description\" slot for accessibility.\n */\nexport function FormFieldDescription({ className, children, ...props }: AriaTextProps) {\n return (\n <AriaText className={classNames('body-sm text-muted leading-tight', className)} {...props} slot=\"description\">\n {children}\n <IcInfo className=\"inline size-2 align-text-top ms-0.5\" />\n </AriaText>\n );\n}\n/**\n * A form field error component that displays validation error messages.\n *\n * @remarks\n * Currently uses a div instead of AriaFieldError to avoid overlap with Tanstack Form.\n * This approach needs further discussion and exploration.\n *\n */\nexport function FormFieldError({ className, children, ...props }: React.ComponentPropsWithRef<'label'>) {\n return (\n <label\n role=\"alert\"\n className={classNames(\n 'body-sm leading-tight text-destructive duration-150 animate-in transition-transform slide-in-from-top-5 fade-in',\n className\n )}\n {...props}\n >\n {children}\n <IcError className=\"inline size-2 align-text-top ms-0.5\" />\n </label>\n );\n}\n\n/**\n * Class variance authority variants for field groups.\n * Provides styling variants for different types of form field containers.\n */\nexport const fieldGroupVariants = cva('', {\n variants: {\n variant: {\n default: [\n 'relative flex w-full items-center overflow-hidden border border-input bg-elevation-2 input-dim ring-offset-background placeholder:text-muted-foreground',\n /* Focus Within */\n 'focus-ring',\n /* Disabled */\n 'disabled-muted',\n ],\n ghost: '',\n },\n },\n defaultVariants: {\n variant: 'default',\n },\n});\n\n/**\n * Props interface for FieldGroup component.\n * Extends AriaGroupProps with variant styling options.\n */\nexport interface GroupProps extends AriaGroupProps, VariantProps<typeof fieldGroupVariants> {}\n\n/**\n * A field group component that wraps form inputs with consistent styling.\n * Supports different variants for various use cases.\n */\nexport function FieldGroup({ className, variant, ...props }: GroupProps) {\n return (\n <AriaGroup\n className={composeRenderProps(className, className =>\n classNames(fieldGroupVariants({ variant }), className)\n )}\n {...props}\n />\n );\n}\n\n/**\n * Props for the FormField component.\n * Defines the structure for form field configuration.\n */\nexport type FormFieldProps = {\n /** Optional label text for the form field */\n label?: React.ReactNode;\n /** Optional description or help text */\n description?: React.ReactNode;\n /** Optional error message to display */\n errorMessage?: string;\n /** Show required indicator on field label */\n requiredIndicator?: boolean;\n /** Not defining the htmlFor on labels will lead to accessibilty warnings */\n htmlFor?: string;\n};\n\n/**\n * A wrapper component for form fields that provides consistent layout and styling.\n * Automatically renders label, children, description, and error message in the correct order.\n * @returns A complete form field with all associated elements\n */\nexport function FormField({\n label,\n description,\n errorMessage,\n children,\n requiredIndicator,\n htmlFor,\n}: FormFieldProps & {\n children: React.ReactNode;\n}) {\n return (\n <>\n {label && (\n <FormFieldLabel htmlFor={htmlFor}>\n {label}\n {requiredIndicator && <sup className=\"text-destructive\">*</sup>}\n </FormFieldLabel>\n )}\n {children}\n {description && <FormFieldDescription>{description}</FormFieldDescription>}\n {errorMessage && <FormFieldError htmlFor={htmlFor}>{errorMessage}</FormFieldError>}\n </>\n );\n}\n\n/**\n * A button component designed to be used within form fields.\n * Styled to fit nicely alongside form inputs with ghost styling.\n */\nexport function FormFieldButton({ className, ...props }: AriaButtonProps) {\n return (\n <AriaButton\n className={composeRenderProps(className, className =>\n classNames('btn btn-ghost h-input px-2 -me-2', className)\n )}\n {...props}\n />\n );\n}\n\n/**\n * A form component that prevents default form submission and handles submit events.\n * All forms in this application are controlled components, not pure HTML forms.\n */\nexport function Form({ className, onSubmit, ...props }: React.ComponentProps<'form'>) {\n return (\n <form\n className={classNames(className)}\n onSubmit={e => {\n // None of the forms in our applications are pure HTML forms.\n e.preventDefault();\n // If onSubmit is provided, call it.\n onSubmit?.(e);\n }}\n {...props}\n />\n );\n}\n\n/**\n * A section component for organizing form content into logical groups.\n * Provides consistent spacing and visual separation between form sections.\n */\nexport function FormSection({ className, ...props }: React.ComponentProps<'section'>) {\n return (\n <section className={classNames('flex flex-col gap-input border-b py-icon pb-input', className)} {...props} />\n );\n}\n\n/**\n * A title component for form sections.\n */\nexport function FormSectionTitle({ className, ...props }: React.ComponentProps<'h2'>) {\n return <h2 className={classNames('heading-4', className)} {...props} />;\n}\n\nexport function FormActionFooter({ className, ...props }: React.ComponentProps<'nav'>) {\n return (\n <nav\n className={classNames(\n 'flex items-center justify-end h-header bg-glass-1 sticky bottom-0 z-50 py-icon px-input border-t',\n className\n )}\n {...props}\n />\n );\n}\n\nexport function FormLayout({ className, ...props }: React.ComponentProps<'div'>) {\n return <div className={'grid grid-cols-1 xl:grid-cols-2 gap-input mt-icon my-header'} {...props} />;\n}\n"],"names":["labelVariants","cva","FormFieldLabel","className","props","jsx","AriaLabel","classNames","FormFieldDescription","children","jsxs","AriaText","IcInfo","FormFieldError","IcError","fieldGroupVariants","FieldGroup","variant","AriaGroup","composeRenderProps","FormField","label","description","errorMessage","requiredIndicator","htmlFor","Fragment","FormFieldButton","AriaButton","Form","onSubmit","e","FormSection","FormSectionTitle","FormActionFooter","FormLayout"],"mappings":"kWAsBO,MAAMA,EAAgBC,EAAI,CAC7B,+CAEA,iBAEA,uCACJ,CAAC,EAUM,SAASC,EAAe,CAAE,UAAAC,EAAW,GAAGC,GAAyB,CACpE,OAAOC,EAACC,GAAU,UAAWC,EAAWP,IAAiBG,CAAS,EAAI,GAAGC,EAAO,CACpF,CAMO,SAASI,EAAqB,CAAE,UAAAL,EAAW,SAAAM,EAAU,GAAGL,GAAwB,CACnF,OACIM,EAACC,EAAA,CAAS,UAAWJ,EAAW,mCAAoCJ,CAAS,EAAI,GAAGC,EAAO,KAAK,cAC3F,SAAA,CAAAK,EACDJ,EAACO,EAAA,CAAO,UAAU,qCAAA,CAAsC,CAAA,EAC5D,CAER,CASO,SAASC,EAAe,CAAE,UAAAV,EAAW,SAAAM,EAAU,GAAGL,GAA+C,CACpG,OACIM,EAAC,QAAA,CACG,KAAK,QACL,UAAWH,EACP,mHACAJ,CAAA,EAEH,GAAGC,EAEH,SAAA,CAAAK,EACDJ,EAACS,EAAA,CAAQ,UAAU,qCAAA,CAAsC,CAAA,CAAA,CAAA,CAGrE,CAMO,MAAMC,EAAqBd,EAAI,GAAI,CACtC,SAAU,CACN,QAAS,CACL,QAAS,CACL,0JAEA,aAEA,gBAAA,EAEJ,MAAO,EAAA,CACX,EAEJ,gBAAiB,CACb,QAAS,SAAA,CAEjB,CAAC,EAYM,SAASe,EAAW,CAAE,UAAAb,EAAW,QAAAc,EAAS,GAAGb,GAAqB,CACrE,OACIC,EAACa,EAAA,CACG,UAAWC,EAAmBhB,EAAWA,GACrCI,EAAWQ,EAAmB,CAAE,QAAAE,CAAA,CAAS,EAAGd,CAAS,CAAA,EAExD,GAAGC,CAAA,CAAA,CAGhB,CAwBO,SAASgB,EAAU,CACtB,MAAAC,EACA,YAAAC,E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AGC,GAAsC,CAC7E,OAAOC,EAAC,MAAA,CAAI,UAAW,8DAAgE,GAAGD,EAAO,CACrG"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsx as t,jsxs as
|
|
1
|
+
import{jsx as t,jsxs as f}from"react/jsx-runtime";import{useQuery as N}from"@tanstack/react-query";import{useId as x,useState as B}from"react";import{Autocomplete as T}from"react-aria-components";import{Loader as j}from"./loader.js";import{Menu as A,MenuItem as E}from"./menu.js";import{PopoverTrigger as K}from"./popover.js";import{SearchField as L}from"./searchfield.js";import{getFieldErrorMessage as p}from"../utilities/form.js";import{useFieldContext as g}from"../utilities/form-context.js";import{FormField as _}from"./form.js";import{SelectTrigger as q,SelectPopover as P}from"./select.js";import"../utilities/theme.js";import"clsx";import"./icons.js";import"./list-box.js";import"@tanstack/react-form";import"class-variance-authority";import"./button.js";function S({label:r,description:n,errorMessage:e,requiredIndicator:o,searchFn:a,isDisabled:I,onBlur:y,resource:C,onChange:V,value:d,renderLabel:v,...m}){const b=x(),s=m.id||b,[l,F]=B(""),{data:c,isError:u,isFetching:h,error:M}=N({queryKey:[C,"id",l],queryFn:()=>a(l)});return t("div",{className:"group form-field",children:t(_,{label:r,description:n,errorMessage:e,requiredIndicator:o,htmlFor:s,children:f(K,{onOpenChange:i=>{i||y?.(d)},children:[t(q,{id:s,isDisabled:I,children:v(d,c)}),t(P,{placement:"bottom start",children:f(T,{inputValue:l,onInputChange:F,children:[t(L,{className:"p-2",autoFocus:!0}),h&&t("div",{className:"p-input",children:t(j,{className:"mx-auto"})}),!h&&!u&&t(A,{...m,className:"max-h-48",items:c,renderEmptyState:()=>t("div",{className:"body-sm p-2",children:"No results found."}),children:i=>t(E,{id:i.id,children:i.name},i.id)}),u&&t("div",{className:"text-destructive p-icon body-sm",children:M.message})]})})]})})})}function O({...r}){return t(S,{selectedKeys:[r.value],onSelectionChange:n=>r.onChange(Array.from(n).filter(e=>typeof e=="string")[0]),renderLabel:(n,e)=>e?.find(o=>o.id===n)?.name??n,selectionMode:"single",...r})}function Q({...r}){return t(S,{selectedKeys:r.value,onSelectionChange:n=>r.onChange(Array.from(n).filter(e=>typeof e=="string")),selectionMode:"multiple",renderLabel:(n,e)=>n?.map(o=>e?.find(a=>a.id===o)?.name??o).join(","),...r})}function ie({isDisabled:r,...n}){const e=g({disabled:r});return t(O,{...n,isDisabled:r||e.form.state.isSubmitting,value:e.state.value,onBlur:o=>e.handleBlur(),onChange:o=>e.handleChange(o),errorMessage:p(e)})}function ae({isDisabled:r,...n}){const e=g({disabled:r});return t(Q,{...n,isDisabled:r||e.form.state.isSubmitting,value:e.state.value,onBlur:o=>e.handleBlur(),onChange:o=>e.handleChange(o),errorMessage:p(e)})}export{Q as MultipleIdSearchInput,O as SingleIdSearchInput,ae as TfMultipleIdSearchInput,ie 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":["import { useQuery } from '@tanstack/react-query';\nimport { useState } from 'react';\nimport { Autocomplete } from 'react-aria-components';\nimport { Loader } from '../components/loader';\nimport { Menu, MenuItem } from '../components/menu';\nimport { PopoverTrigger } from '../components/popover';\nimport { SearchField } from '../components/searchfield';\nimport { getFieldErrorMessage } from '../utilities/form';\nimport { useFieldContext } from '../utilities/form-context';\nimport type { CtxResourceName } from '../utilities/resources';\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 * - 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 * - Clear separation of concerns: this component only handles UI search/display; callers provide `searchFn`\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 * - `searchFn` should return `Promise<T[] | undefined>`. Returning `undefined` indicates no results / handled error.\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 *\n * @example\n * <BaseIdSearchInput\n * label=\"Owner\"\n * searchFn={q => api.searchUsers(q)}\n * value={ownerId}\n * onChange={setOwnerId}\n * renderLabel={(v, data) => data?.find(d => d.id === v)?.name ?? v}\n * />\n *\n * @testing\n * - Mock `searchFn` in unit tests; 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 searchFn,\n isDisabled,\n onBlur,\n resource,\n onChange,\n value,\n renderLabel,\n ...props\n}: FormFieldProps & {\n resource: CtxResourceName;\n /** Function that returns matching resources for the current query. */\n searchFn: (q: string) => Promise<T[] | undefined>;\n /** Disable interactions. */\n isDisabled?: 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} & Omit<React.ComponentProps<typeof Menu>, 'items' | 'className'>) {\n const [search, _setSearch] = useState('');\n const { data, isError, isFetching, error } = useQuery({\n queryKey: [resource, 'id', search],\n queryFn: () => searchFn(search),\n });\n\n return (\n <div className=\"group form-field\">\n <FormField {...{ label, description, errorMessage, requiredIndicator }}>\n <PopoverTrigger\n onOpenChange={o => {\n if (!o) {\n // searchInputRef.current?.focus();\n onBlur?.(value);\n }\n }}\n >\n <SelectTrigger isDisabled={isDisabled}>{renderLabel(value, data)}</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['id']} id={item['id']}>\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 </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 * searchFn={q => api.searchUsers(q)}\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 * searchFn={q => api.searchUsers(q)}\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\" searchFn={q => api.searchUsers(q)} />\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 {...props}\n isDisabled={isDisabled || field.form.state.isSubmitting}\n value={field.state.value}\n onBlur={_ => field.handleBlur()}\n onChange={e => field.handleChange(e)}\n errorMessage={getFieldErrorMessage(field)}\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\" searchFn={q => api.searchUsers(q)} />\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 {...props}\n isDisabled={isDisabled || field.form.state.isSubmitting}\n value={field.state.value}\n onBlur={_ => field.handleBlur()}\n onChange={e => field.handleChange(e)}\n errorMessage={getFieldErrorMessage(field)}\n />\n );\n}\n"],"names":["BaseIdSearchInput","label","description","errorMessage","requiredIndicator","searchFn","isDisabled","onBlur","resource","onChange","value","renderLabel","props","search","_setSearch","useState","data","isError","isFetching","error","useQuery","jsx","FormField","jsxs","PopoverTrigger","o","SelectTrigger","SelectPopover","Autocomplete","SearchField","Loader","Menu","item","MenuItem","SingleIdSearchInput","e","v","d","di","MultipleIdSearchInput","vi","TfSingleIdSearchInput","field","useFieldContext","_","getFieldErrorMessage","TfMultipleIdSearchInput"],"mappings":"gvBAwDA,SAASA,EAAuD,CAC5D,MAAAC,EACA,YAAAC,EACA,aAAAC,EACA,kBAAAC,EACA,SAAAC,EACA,WAAAC,EACA,OAAAC,EACA,SAAAC,EACA,SAAAC,EACA,MAAAC,EACA,YAAAC,EACA,GAAGC,CACP,EAgBoE,CAChE,KAAM,CAACC,EAAQC,CAAU,EAAIC,EAAS,EAAE,EAClC,CAAE,KAAAC,EAAM,QAAAC,EAAS,WAAAC,EAAY,MAAAC,CAAA,EAAUC,EAAS,CAClD,SAAU,CAACZ,EAAU,KAAMK,CAAM,EACjC,QAAS,IAAMR,EAASQ,CAAM,CAAA,CACjC,EAED,OACIQ,EAAC,MAAA,CAAI,UAAU,mBACX,SAAAA,EAACC,EAAA,CAAgB,MAAArB,EAAO,YAAAC,EAAa,aAAAC,EAAc,kBAAAC,EAC/C,SAAAmB,EAACC,EAAA,CACG,aAAcC,GAAK,CACVA,GAEDlB,IAASG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AM,QAAQ,CAAC,EACvF,cAAc,WACd,YAAa,CAACA,EAAGC,IAAMD,EAAE,OAAUC,GAAG,KAAKC,GAAMA,EAAG,KAAOE,CAAE,GAAG,MAAQA,CAAE,EAAE,KAAK,GAAG,EACnF,GAAG5B,CAAA,CAAA,CAGhB,CAcO,SAAS6B,GAAsB,CAClC,WAAAnC,EACA,GAAGM,CACP,EAA4F,CACxF,MAAM8B,EAAQC,EAAwB,CAAE,SAAUrC,EAAY,EAC9D,OACIe,EAACa,EAAA,CACI,GAAGtB,EACJ,WAAYN,GAAcoC,EAAM,KAAK,MAAM,aAC3C,MAAOA,EAAM,MAAM,MACnB,OAAQE,GAAKF,EAAM,WAAA,EACnB,SAAUP,GAAKO,EAAM,aAAaP,CAAC,EACnC,aAAcU,EAAqBH,CAAK,CAAA,CAAA,CAGpD,CAcO,SAASI,GAAwB,CACpC,WAAAxC,EACA,GAAGM,CACP,EAAmF,CAC/E,MAAM8B,EAAQC,EAA0B,CAAE,SAAUrC,EAAY,EAChE,OACIe,EAACkB,EAAA,CACI,GAAG3B,EACJ,WAAYN,GAAcoC,EAAM,KAAK,MAAM,aAC3C,MAAOA,EAAM,MAAM,MACnB,OAAQE,GAAKF,EAAM,WAAA,EACnB,SAAUP,GAAKO,EAAM,aAAaP,CAAC,EACnC,aAAcU,EAAqBH,CAAK,CAAA,CAAA,CAGpD"}
|
|
1
|
+
{"version":3,"file":"id-search.js","sources":["../../lib/components/id-search.tsx"],"sourcesContent":["import { useQuery } from '@tanstack/react-query';\nimport { useId, useState } from 'react';\nimport { Autocomplete } from 'react-aria-components';\nimport { Loader } from '../components/loader';\nimport { Menu, MenuItem } from '../components/menu';\nimport { PopoverTrigger } from '../components/popover';\nimport { SearchField } from '../components/searchfield';\nimport { getFieldErrorMessage } from '../utilities/form';\nimport { useFieldContext } from '../utilities/form-context';\nimport type { CtxResourceName } from '../utilities/resources';\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 * - 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 * - Clear separation of concerns: this component only handles UI search/display; callers provide `searchFn`\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 * - `searchFn` should return `Promise<T[] | undefined>`. Returning `undefined` indicates no results / handled error.\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 *\n * @example\n * <BaseIdSearchInput\n * label=\"Owner\"\n * searchFn={q => api.searchUsers(q)}\n * value={ownerId}\n * onChange={setOwnerId}\n * renderLabel={(v, data) => data?.find(d => d.id === v)?.name ?? v}\n * />\n *\n * @testing\n * - Mock `searchFn` in unit tests; 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 searchFn,\n isDisabled,\n onBlur,\n resource,\n onChange,\n value,\n renderLabel,\n ...props\n}: FormFieldProps & {\n resource: CtxResourceName;\n /** Function that returns matching resources for the current query. */\n searchFn: (q: string) => Promise<T[] | undefined>;\n /** Disable interactions. */\n isDisabled?: 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} & Omit<React.ComponentProps<typeof Menu>, 'items' | 'className'>) {\n const generatedId = useId();\n const fieldId = props.id || generatedId;\n\n const [search, _setSearch] = useState('');\n const { data, isError, isFetching, error } = useQuery({\n queryKey: [resource, 'id', search],\n queryFn: () => searchFn(search),\n });\n\n return (\n <div className=\"group form-field\">\n <FormField {...{ label, description, errorMessage, requiredIndicator, htmlFor: fieldId }}>\n <PopoverTrigger\n onOpenChange={o => {\n if (!o) {\n // searchInputRef.current?.focus();\n onBlur?.(value);\n }\n }}\n >\n <SelectTrigger id={fieldId} isDisabled={isDisabled}>\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['id']} id={item['id']}>\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 </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 * searchFn={q => api.searchUsers(q)}\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 * searchFn={q => api.searchUsers(q)}\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\" searchFn={q => api.searchUsers(q)} />\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 {...props}\n isDisabled={isDisabled || field.form.state.isSubmitting}\n value={field.state.value}\n onBlur={_ => field.handleBlur()}\n onChange={e => field.handleChange(e)}\n errorMessage={getFieldErrorMessage(field)}\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\" searchFn={q => api.searchUsers(q)} />\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 {...props}\n isDisabled={isDisabled || field.form.state.isSubmitting}\n value={field.state.value}\n onBlur={_ => field.handleBlur()}\n onChange={e => field.handleChange(e)}\n errorMessage={getFieldErrorMessage(field)}\n />\n );\n}\n"],"names":["BaseIdSearchInput","label","description","errorMessage","requiredIndicator","searchFn","isDisabled","onBlur","resource","onChange","value","renderLabel","props","generatedId","useId","fieldId","search","_setSearch","useState","data","isError","isFetching","error","useQuery","jsx","FormField","jsxs","PopoverTrigger","o","SelectTrigger","SelectPopover","Autocomplete","SearchField","Loader","Menu","item","MenuItem","SingleIdSearchInput","e","v","d","di","MultipleIdSearchInput","vi","TfSingleIdSearchInput","field","useFieldContext","_","getFieldErrorMessage","TfMultipleIdSearchInput"],"mappings":"2vBAwDA,SAASA,EAAuD,CAC5D,MAAAC,EACA,YAAAC,EACA,aAAAC,EACA,kBAAAC,EACA,SAAAC,EACA,WAAAC,EACA,OAAAC,EACA,SAAAC,EACA,SAAAC,EACA,MAAAC,EACA,YAAAC,EACA,GAAGC,CACP,EAgBoE,CAChE,MAAMC,EAAcC,EAAA,EACdC,EAA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EAAqBH,CAAK,CAAA,CAAA,CAGpD"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsx as i}from"react/jsx-runtime";import{EasyMenu as
|
|
1
|
+
import{jsx as i}from"react/jsx-runtime";import{EasyMenu as d,MenuItem as p}from"./menu.js";import{getFieldErrorMessage as u}from"../utilities/form.js";import{useFieldContext as c}from"../utilities/form-context.js";import{FormField as f}from"./form.js";import"react-aria-components";import"../utilities/theme.js";import"clsx";import"./icons.js";import"react";import"./list-box.js";import"./select.js";import"./button.js";import"class-variance-authority";import"./loader.js";import"./popover.js";import"@tanstack/react-form";function g({items:o,value:e,onChange:t,label:n,errorMessage:s,description:a,requiredIndicator:m,...l}){return i("div",{className:"group form-field",children:i(f,{label:n,description:a,errorMessage:s,requiredIndicator:m,children:i(d,{isNonModal:!1,selectionMode:"multiple",selectedKeys:e,onSelectionChange:r=>{typeof r!="string"&&t(r)},items:o,label:l.triggerLabel??i("span",{className:"tabular-nums",children:e.size}),...l,children:r=>i(p,{id:r.id,isDisabled:r?.disabled,children:r.label},r.id)})})})}function I({...o}){const e=c({disabled:o.isDisabled});return i(g,{value:new Set(e.state.value),onChange:t=>e.setValue(Array.from(t)),onClose:e.handleBlur,errorMessage:u(e),...o})}export{g as MultiSelect,I as TfMultiSelect};
|
|
2
2
|
//# sourceMappingURL=multi-select.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multi-select.js","sources":["../../lib/components/multi-select.tsx"],"sourcesContent":["import React 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';\n\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 return (\n <div className=\"group form-field\">\n <FormField {...{ label, description, errorMessage, requiredIndicator }}>\n <EasyMenu\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 ?? value.size}\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 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","jsx","FormField","EasyMenu","v","item","MenuItem","TfMultiSelect","field","useFieldContext","e","getFieldErrorMessage"],"mappings":"2gBAqBO,SAASA,EAAY,CACxB,MAAAC,EACA,MAAAC,EACA,SAAUC,EACV,MAAAC,EACA,aAAAC,EACA,YAAAC,EACA,kBAAAC,EACA,GAAGC,CACP,EAAqB,CACjB,OACIC,EAAC,MAAA,CAAI,UAAU,mBACX,SAAAA,EAACC,EAAA,CAAgB,MAAAN,EAAO,YAAAE,EAAa,aAAAD,EAAc,kBAAAE,EAC/C,SAAAE,EAACE,EAAA,CACG,WAAY,GACZ,cAAc,WACd,aAAcT,EACd,kBAAmBU,GAAK,CAChB,OAAOA,GAAM,UACjBT,EAASS,CAAC,CACd,EACA,MAAAX,EACA,MAAOO,EAAM,
|
|
1
|
+
{"version":3,"file":"multi-select.js","sources":["../../lib/components/multi-select.tsx"],"sourcesContent":["import React 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';\n\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 return (\n <div className=\"group form-field\">\n <FormField {...{ label, description, errorMessage, requiredIndicator }}>\n <EasyMenu\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 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","jsx","FormField","EasyMenu","v","item","MenuItem","TfMultiSelect","field","useFieldContext","e","getFieldErrorMessage"],"mappings":"2gBAqBO,SAASA,EAAY,CACxB,MAAAC,EACA,MAAAC,EACA,SAAUC,EACV,MAAAC,EACA,aAAAC,EACA,YAAAC,EACA,kBAAAC,EACA,GAAGC,CACP,EAAqB,CACjB,OACIC,EAAC,MAAA,CAAI,UAAU,mBACX,SAAAA,EAACC,EAAA,CAAgB,MAAAN,EAAO,YAAAE,EAAa,aAAAD,EAAc,kBAAAE,EAC/C,SAAAE,EAACE,EAAA,CACG,WAAY,GACZ,cAAc,WACd,aAAcT,EACd,kBAAmBU,GAAK,CAChB,OAAOA,GAAM,UACjBT,EAASS,CAAC,CACd,EACA,MAAAX,EACA,MAAOO,EAAM,cAAgBC,EAAC,QAAK,UAAU,eAAgB,WAAM,IAAA,CAAK,EACvE,GAAGD,EAEH,SAAAK,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,GAAGP,GAA6B,CAC5D,MAAMQ,EAAQC,EAA0B,CACpC,SAAUT,EAAM,UAAA,CACnB,EAED,OACIC,EAACT,EAAA,CACG,MAAO,IAAI,IAAIgB,EAAM,MAAM,KAAK,EAEhC,SAAUE,GAAKF,EAAM,SAAS,MAAM,KAAKE,CAAC,CAAC,EAC3C,QAASF,EAAM,WACf,aAAcG,EAAqBH,CAAK,EACvC,GAAGR,CAAA,CAAA,CAGhB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { NumberFieldProps as AriaNumberFieldProps } from 'react-aria-components';
|
|
2
2
|
import { FormFieldProps } from './form';
|
|
3
|
-
type NumberFieldProps = AriaNumberFieldProps & FormFieldProps;
|
|
3
|
+
export type NumberFieldProps = AriaNumberFieldProps & FormFieldProps;
|
|
4
4
|
export declare function NumberField({ label, description, errorMessage, requiredIndicator, className, ...props }: NumberFieldProps): import("react/jsx-runtime").JSX.Element;
|
|
5
5
|
export declare function TfNumberField({ isDisabled, ...props }: Omit<React.ComponentProps<typeof NumberField>, 'value' | 'id' | 'onChange' | 'onBlur'>): import("react/jsx-runtime").JSX.Element;
|
|
6
|
-
export {};
|
|
6
|
+
export declare function DaysField({ label, description, errorMessage, requiredIndicator, className, ...props }: NumberFieldProps): import("react/jsx-runtime").JSX.Element;
|
|
7
|
+
export declare function TfDaysField({ isDisabled, ...props }: Omit<React.ComponentProps<typeof DaysField>, 'value' | 'id' | 'onChange' | 'onBlur'>): import("react/jsx-runtime").JSX.Element;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsx as r,jsxs as
|
|
1
|
+
import{jsx as r,jsxs as u}from"react/jsx-runtime";import{NumberField as F,composeRenderProps as m,Input as v}from"react-aria-components";import{Button as x}from"./button.js";import{getFieldErrorMessage as d}from"../utilities/form.js";import{useFieldContext as p}from"../utilities/form-context.js";import{classNames as s}from"../utilities/theme.js";import{FormField as f,FieldGroup as h}from"./form.js";import{IcUp as C,IcDown as w}from"./icons.js";import"class-variance-authority";import"./loader.js";import"clsx";import"react";import"@tanstack/react-form";const b=F;function N({className:t,...n}){return r(v,{className:m(t,e=>s("w-fit min-w-0 flex-1 border-r border-transparent bg-elevation-2 outline-0 placeholder:text-muted-foreground [&::-webkit-search-cancel-button]:hidden",e)),...n})}function D({className:t,...n}){return u("div",{className:s("absolute right-0 flex h-full flex-col border-l",t),...n,children:[r(c,{slot:"increment",children:r(C,{"aria-hidden":!0,className:"size-icon"})}),r("div",{className:"border-b"}),r(c,{slot:"decrement",children:r(w,{"aria-hidden":!0,className:"size-icon"})})]})}function c({className:t,...n}){return r(x,{className:m(t,e=>s("w-auto grow h-3 px-0.5 text-muted-foreground",e)),variant:"ghost",size:"none",...n})}function I({label:t,description:n,errorMessage:e,requiredIndicator:i,className:o,...l}){return r(b,{className:m(o,a=>s("group form-field",a)),...l,children:r(f,{label:t,description:n,errorMessage:e,requiredIndicator:i,children:u(h,{children:[r(N,{className:"pr-input"}),r(D,{})]})})})}function O({isDisabled:t,...n}){const e=p({disabled:t});return r(I,{isInvalid:!!d(e),isDisabled:t||e.form.state.isSubmitting,value:e.state.value,id:e.name,onChange:e.handleChange,onBlur:e.handleBlur,errorMessage:d(e),...n})}function S({label:t,description:n,errorMessage:e,requiredIndicator:i,className:o,...l}){return r(b,{className:m(o,a=>s("group form-field",a)),...l,children:r(f,{label:t,description:n,errorMessage:e,requiredIndicator:i,children:u(h,{children:[r(N,{className:"pr-input"}),r("div",{className:"absolute right-1 select-none text-muted",children:"days"})]})})})}function U({isDisabled:t,...n}){const e=p({disabled:t}),i=86400,o=e.state.value!=null?e.state.value/i:void 0,l=a=>{const g=a*i;e.handleChange(g)};return r(S,{isInvalid:!!d(e),isDisabled:t||e.form.state.isSubmitting,value:o,id:e.name,onChange:l,onBlur:e.handleBlur,errorMessage:d(e),...n})}export{S as DaysField,I as NumberField,U as TfDaysField,O as TfNumberField};
|
|
2
2
|
//# sourceMappingURL=numberfield.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"numberfield.js","sources":["../../lib/components/numberfield.tsx"],"sourcesContent":["import {\n ButtonProps as AriaButtonProps,\n Input as AriaInput,\n InputProps as AriaInputProps,\n NumberField as AriaNumberField,\n NumberFieldProps as AriaNumberFieldProps,\n composeRenderProps,\n} from 'react-aria-components';\n\nimport { Button } from '../components/button';\nimport { getFieldErrorMessage } from '../utilities/form';\nimport { useFieldContext } from '../utilities/form-context';\nimport { classNames } from '../utilities/theme';\nimport { FieldGroup, FormField, type FormFieldProps } from './form';\nimport { IcDown, IcUp } from './icons';\n\nconst ANumberField = AriaNumberField;\n\nfunction NumberFieldInput({ className, ...props }: AriaInputProps) {\n return (\n <AriaInput\n className={composeRenderProps(className, className =>\n classNames(\n 'w-fit min-w-0 flex-1 border-r border-transparent bg-elevation-2
|
|
1
|
+
{"version":3,"file":"numberfield.js","sources":["../../lib/components/numberfield.tsx"],"sourcesContent":["import {\n ButtonProps as AriaButtonProps,\n Input as AriaInput,\n InputProps as AriaInputProps,\n NumberField as AriaNumberField,\n NumberFieldProps as AriaNumberFieldProps,\n composeRenderProps,\n} from 'react-aria-components';\n\nimport { Button } from '../components/button';\nimport { getFieldErrorMessage } from '../utilities/form';\nimport { useFieldContext } from '../utilities/form-context';\nimport { classNames } from '../utilities/theme';\nimport { FieldGroup, FormField, type FormFieldProps } from './form';\nimport { IcDown, IcUp } from './icons';\n\nconst ANumberField = AriaNumberField;\n\nfunction NumberFieldInput({ className, ...props }: AriaInputProps) {\n return (\n <AriaInput\n className={composeRenderProps(className, className =>\n classNames(\n 'w-fit min-w-0 flex-1 border-r border-transparent bg-elevation-2 outline-0 placeholder:text-muted-foreground [&::-webkit-search-cancel-button]:hidden',\n className\n )\n )}\n {...props}\n />\n );\n}\n\nfunction NumberFieldSteppers({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div className={classNames('absolute right-0 flex h-full flex-col border-l', className)} {...props}>\n <NumberFieldStepper slot=\"increment\">\n <IcUp aria-hidden className=\"size-icon\" />\n </NumberFieldStepper>\n <div className=\"border-b\" />\n <NumberFieldStepper slot=\"decrement\">\n <IcDown aria-hidden className=\"size-icon\" />\n </NumberFieldStepper>\n </div>\n );\n}\n\nfunction NumberFieldStepper({ className, ...props }: AriaButtonProps) {\n return (\n <Button\n className={composeRenderProps(className, className =>\n classNames('w-auto grow h-3 px-0.5 text-muted-foreground', className)\n )}\n variant={'ghost'}\n size={'none'}\n {...props}\n />\n );\n}\n\nexport type NumberFieldProps = AriaNumberFieldProps & FormFieldProps;\nexport function NumberField({\n label,\n description,\n errorMessage,\n requiredIndicator,\n className,\n ...props\n}: NumberFieldProps) {\n return (\n <ANumberField\n className={composeRenderProps(className, className => classNames('group form-field', className))}\n {...props}\n >\n <FormField {...{ label, description, errorMessage, requiredIndicator }}>\n <FieldGroup>\n <NumberFieldInput className={'pr-input'} />\n <NumberFieldSteppers />\n </FieldGroup>\n </FormField>\n </ANumberField>\n );\n}\n\nexport function TfNumberField({\n isDisabled,\n ...props\n}: Omit<React.ComponentProps<typeof NumberField>, 'value' | 'id' | 'onChange' | 'onBlur'>) {\n const field = useFieldContext<number>({ disabled: isDisabled });\n\n return (\n <NumberField\n isInvalid={!!getFieldErrorMessage(field)}\n isDisabled={isDisabled || field.form.state.isSubmitting}\n value={field.state.value}\n id={field.name}\n onChange={field.handleChange}\n onBlur={field.handleBlur}\n errorMessage={getFieldErrorMessage(field)}\n {...props}\n />\n );\n}\n\nexport function DaysField({\n label,\n description,\n errorMessage,\n requiredIndicator,\n className,\n ...props\n}: NumberFieldProps) {\n return (\n <ANumberField\n className={composeRenderProps(className, className => classNames('group form-field', className))}\n {...props}\n >\n <FormField {...{ label, description, errorMessage, requiredIndicator }}>\n <FieldGroup>\n <NumberFieldInput className={'pr-input'} />\n <div className=\"absolute right-1 select-none text-muted\">days</div>\n </FieldGroup>\n </FormField>\n </ANumberField>\n );\n}\n\nexport function TfDaysField({\n isDisabled,\n ...props\n}: Omit<React.ComponentProps<typeof DaysField>, 'value' | 'id' | 'onChange' | 'onBlur'>) {\n const field = useFieldContext<number>({ disabled: isDisabled });\n\n const SECONDS_PER_DAY = 86400; // 24 * 60 * 60\n\n // Convert seconds to days for display\n const daysValue = field.state.value != null ? field.state.value / SECONDS_PER_DAY : undefined;\n\n // Convert days to seconds when value changes\n const handleDaysChange = (days: number) => {\n const seconds = days * SECONDS_PER_DAY;\n field.handleChange(seconds);\n };\n\n return (\n <DaysField\n isInvalid={!!getFieldErrorMessage(field)}\n isDisabled={isDisabled || field.form.state.isSubmitting}\n value={daysValue}\n id={field.name}\n onChange={handleDaysChange}\n onBlur={field.handleBlur}\n errorMessage={getFieldErrorMessage(field)}\n {...props}\n />\n );\n}\n"],"names":["ANumberField","AriaNumberField","NumberFieldInput","className","props","jsx","AriaInput","composeRenderProps","classNames","NumberFieldSteppers","jsxs","NumberFieldStepper","IcUp","IcDown","Button","NumberField","label","description","errorMessage","requiredIndicator","FormField","FieldGroup","TfNumberField","isDisabled","field","useFieldContext","getFieldErrorMessage","DaysField","TfDaysField","SECONDS_PER_DAY","daysValue","handleDaysChange","days","seconds"],"mappings":"6iBAgBA,MAAMA,EAAeC,EAErB,SAASC,EAAiB,CAAE,UAAAC,EAAW,GAAGC,GAAyB,CAC/D,OACIC,EAACC,EAAA,CACG,UAAWC,EAAmBJ,EAAWA,GACrCK,EACI,uJACAL,CAAA,CACJ,EAEH,GAAGC,CAAA,CAAA,CAGhB,CAEA,SAASK,EAAoB,CAAE,UAAAN,EAAW,GAAGC,GAAsC,CAC/E,OACIM,EAAC,OAAI,UAAWF,EAAW,iDAAkDL,CAAS,EAAI,GAAGC,EACzF,SAAA,CAAAC,EAACM,EAAA,CAAmB,KAAK,YACrB,SAAAN,EAACO,GAAK,cAAW,GAAC,UAAU,WAAA,CAAY,CAAA,CAC5C,EACAP,EAAC,MAAA,CAAI,UAAU,UAAA,CAAW,EAC1BA,EAACM,EAAA,CAAmB,KAAK,YACrB,SAAAN,EAACQ,GAAO,cAAW,GAAC,UAAU,WAAA,CAAY,CAAA,CAC9C,CAAA,EACJ,CAER,CAEA,SAASF,EAAmB,CAAE,UAAAR,EAAW,GAAGC,GAA0B,CAClE,OACIC,EAACS,EAAA,CACG,UAAWP,EAAmBJ,EAAWA,GACrCK,EAAW,+CAAgDL,CAAS,CAAA,EAExE,QAAS,QACT,KAAM,OACL,GAAGC,CAAA,CAAA,CAGhB,CAGO,SAASW,EAAY,CACxB,MAAAC,EACA,YAAAC,EACA,aAAAC,EACA,kBAAAC,EACA,UAAAhB,EACA,GAAGC,CACP,EAAqB,CACjB,OACIC,EAACL,EAAA,CACG,UAAWO,EAAmBJ,EAAWA,GAAaK,EAAW,mBAAoBL,CAAS,CAAC,EAC9F,GAAGC,EAEJ,SAAAC,EAACe,EAAA,CAAgB,MAAAJ,EAAO,YAAAC,EAAa,aAAAC,EAA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UD,EAAOH,EACvBL,EAAM,aAAaS,CAAO,CAC9B,EAEA,OACI5B,EAACsB,EAAA,CACG,UAAW,CAAC,CAACD,EAAqBF,CAAK,EACvC,WAAYD,GAAcC,EAAM,KAAK,MAAM,aAC3C,MAAOM,EACP,GAAIN,EAAM,KACV,SAAUO,EACV,OAAQP,EAAM,WACd,aAAcE,EAAqBF,CAAK,EACvC,GAAGpB,CAAA,CAAA,CAGhB"}
|
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
import { default as z } from 'zod';
|
|
2
|
+
export declare const MAX_INT32 = 2147483647;
|
|
3
|
+
export declare const MAX_INT32_DAYS: number;
|
|
4
|
+
export declare const MIN_INT32 = -2147483648;
|
|
5
|
+
export declare const MIN_INT32_DAYS: number;
|
|
6
|
+
export declare function getNumberValidator(min: number, max: number): z.ZodNumber;
|
|
7
|
+
export declare function getDaysValidator(min: number): z.ZodNumber;
|
|
1
8
|
export declare function formatNumber(num: number | bigint): string;
|
|
2
9
|
/**
|
|
3
10
|
* @returns A formatted string for the number of bytes
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(r){return Intl.NumberFormat(navigator.language).format(r)}function
|
|
1
|
+
import n from"zod";const u=2147483647,i=Math.floor(u/86400),a=-2147483648,l=Math.ceil(a/86400);function m(r,e){return n.number().min(r,{error:t=>{if(t.code==="too_small")return`The number must be at least ${o(r)}.`}}).max(e,{error:t=>{if(t.code==="too_big")return`The number must be at most ${o(e)}.`}})}function c(r){return m(r,i)}function o(r){return Intl.NumberFormat(navigator.language).format(r)}function N(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:r<1024*1024*1024?`${(r/(1024*1024)).toFixed(2)} MB`:`${(r/(1024*1024*1024)).toFixed(2)} GB`}export{u as MAX_INT32,i as MAX_INT32_DAYS,a as MIN_INT32,l as MIN_INT32_DAYS,N as formatFilesize,o as formatNumber,c as getDaysValidator,m as getNumberValidator};
|
|
2
2
|
//# sourceMappingURL=numbers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"numbers.js","sources":["../../lib/utilities/numbers.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"numbers.js","sources":["../../lib/utilities/numbers.ts"],"sourcesContent":["import z from 'zod';\n\nexport const MAX_INT32 = 2147483647;\nexport const MAX_INT32_DAYS = Math.floor(MAX_INT32 / 86400);\nexport const MIN_INT32 = -2147483648;\nexport const MIN_INT32_DAYS = Math.ceil(MIN_INT32 / 86400);\n\nexport function getNumberValidator(min: number, max: number) {\n return z\n .number()\n .min(min, {\n error: issue => {\n if (issue.code === 'too_small') return `The number must be at least ${formatNumber(min)}.`;\n },\n })\n .max(max, {\n error: issue => {\n if (issue.code === 'too_big') return `The number must be at most ${formatNumber(max)}.`;\n },\n });\n}\n\nexport function getDaysValidator(min: number) {\n return getNumberValidator(min, MAX_INT32_DAYS);\n}\n\nexport function formatNumber(num: number | bigint) {\n return Intl.NumberFormat(navigator.language).format(num);\n}\n\n/**\n * @returns A formatted string for the number of bytes\n */\nexport function formatFilesize(bytes: number): string {\n if (bytes < 1024) {\n return `${bytes} B`;\n } else if (bytes < 1024 * 1024) {\n return `${(bytes / 1024).toFixed(1)} KB`;\n } else if (bytes < 1024 * 1024 * 1024) {\n return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;\n } else {\n return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;\n }\n}\n"],"names":["MAX_INT32","MAX_INT32_DAYS","MIN_INT32","MIN_INT32_DAYS","getNumberValidator","min","max","z","issue","formatNumber","getDaysValidator","num","formatFilesize","bytes"],"mappings":"mBAEO,MAAMA,EAAY,WACZC,EAAiB,KAAK,MAAMD,EAAY,KAAK,EAC7CE,EAAY,YACZC,EAAiB,KAAK,KAAKD,EAAY,KAAK,EAElD,SAASE,EAAmBC,EAAaC,EAAa,CACzD,OAAOC,EACF,SACA,IAAIF,EAAK,CACN,MAAOG,GAAS,CACZ,GAAIA,EAAM,OAAS,kBAAoB,+BAA+BC,EAAaJ,CAAG,CAAC,GAC3F,CAAA,CACH,EACA,IAAIC,EAAK,CACN,MAAOE,GAAS,CACZ,GAAIA,EAAM,OAAS,gBAAkB,8BAA8BC,EAAaH,CAAG,CAAC,GACxF,CAAA,CACH,CACT,CAEO,SAASI,EAAiBL,EAAa,CAC1C,OAAOD,EAAmBC,EAAKJ,CAAc,CACjD,CAEO,SAASQ,EAAaE,EAAsB,CAC/C,OAAO,KAAK,aAAa,UAAU,QAAQ,EAAE,OAAOA,CAAG,CAC3D,CAKO,SAASC,EAAeC,EAAuB,CAClD,OAAIA,EAAQ,KACD,GAAGA,CAAK,KACRA,EAAQ,KAAO,KACf,IAAIA,EAAQ,MAAM,QAAQ,CAAC,CAAC,MAC5BA,EAAQ,KAAO,KAAO,KACtB,IAAIA,GAAS,KAAO,OAAO,QAAQ,CAAC,CAAC,MAErC,IAAIA,GAAS,KAAO,KAAO,OAAO,QAAQ,CAAC,CAAC,KAE3D"}
|