use-generated-columns.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. import { useAllBulkActions } from '@/vdb/components/data-table/use-all-bulk-actions.js';
  2. import { DisplayComponent } from '@/vdb/framework/component-registry/display-component.js';
  3. import {
  4. FieldInfo,
  5. getOperationVariablesFields,
  6. getTypeFieldInfo,
  7. } from '@/vdb/framework/document-introspection/get-document-structure.js';
  8. import { BulkAction } from '@/vdb/framework/extension-api/types/index.js';
  9. import { api } from '@/vdb/graphql/api.js';
  10. import { Trans, useLingui } from '@/vdb/lib/trans.js';
  11. import { TypedDocumentNode } from '@graphql-typed-document-node/core';
  12. import { useMutation } from '@tanstack/react-query';
  13. import { AccessorKeyColumnDef, createColumnHelper, Row } from '@tanstack/react-table';
  14. import { EllipsisIcon, TrashIcon } from 'lucide-react';
  15. import { useMemo } from 'react';
  16. import { toast } from 'sonner';
  17. import {
  18. AdditionalColumns,
  19. AllItemFieldKeys,
  20. CustomizeColumnConfig,
  21. FacetedFilterConfig,
  22. PaginatedListItemFields,
  23. RowAction,
  24. usePaginatedList,
  25. } from '../shared/paginated-list-data-table.js';
  26. import {
  27. AlertDialog,
  28. AlertDialogAction,
  29. AlertDialogCancel,
  30. AlertDialogContent,
  31. AlertDialogDescription,
  32. AlertDialogFooter,
  33. AlertDialogHeader,
  34. AlertDialogTitle,
  35. AlertDialogTrigger,
  36. } from '../ui/alert-dialog.js';
  37. import { Button } from '../ui/button.js';
  38. import { Checkbox } from '../ui/checkbox.js';
  39. import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '../ui/dropdown-menu.js';
  40. import { DataTableColumnHeader } from './data-table-column-header.js';
  41. /**
  42. * @description
  43. * This hook is used to generate the columns for a data table, combining the fields
  44. * from the query with the additional columns and the custom fields.
  45. *
  46. * It also
  47. * - adds the row actions and the delete mutation.
  48. * - adds the row selection column.
  49. * - adds the custom field columns.
  50. */
  51. export function useGeneratedColumns<T extends TypedDocumentNode<any, any>>({
  52. fields,
  53. customizeColumns,
  54. rowActions,
  55. bulkActions,
  56. deleteMutation,
  57. additionalColumns,
  58. defaultColumnOrder,
  59. facetedFilters,
  60. includeSelectionColumn = true,
  61. includeActionsColumn = true,
  62. enableSorting = true,
  63. }: Readonly<{
  64. fields: FieldInfo[];
  65. customizeColumns?: CustomizeColumnConfig<T>;
  66. rowActions?: RowAction<PaginatedListItemFields<T>>[];
  67. bulkActions?: BulkAction[];
  68. deleteMutation?: TypedDocumentNode<any, any>;
  69. additionalColumns?: AdditionalColumns<T>;
  70. defaultColumnOrder?: Array<string | number | symbol>;
  71. facetedFilters?: FacetedFilterConfig<T>;
  72. includeSelectionColumn?: boolean;
  73. includeActionsColumn?: boolean;
  74. enableSorting?: boolean;
  75. }>) {
  76. const columnHelper = createColumnHelper<PaginatedListItemFields<T>>();
  77. const allBulkActions = useAllBulkActions(bulkActions ?? []);
  78. const { columns, customFieldColumnNames } = useMemo(() => {
  79. const columnConfigs: Array<{ fieldInfo: FieldInfo; isCustomField: boolean }> = [];
  80. const customFieldColumnNames: string[] = [];
  81. columnConfigs.push(
  82. ...fields // Filter out custom fields
  83. .filter(field => field.name !== 'customFields' && !field.type.endsWith('CustomFields'))
  84. .map(field => ({ fieldInfo: field, isCustomField: false })),
  85. );
  86. const customFieldColumn = fields.find(field => field.name === 'customFields');
  87. if (customFieldColumn && customFieldColumn.type !== 'JSON') {
  88. const customFieldFields = getTypeFieldInfo(customFieldColumn.type);
  89. columnConfigs.push(
  90. ...customFieldFields.map(field => ({ fieldInfo: field, isCustomField: true })),
  91. );
  92. customFieldColumnNames.push(...customFieldFields.map(field => field.name));
  93. }
  94. const queryBasedColumns = columnConfigs.map(({ fieldInfo, isCustomField }) => {
  95. const customConfig = customizeColumns?.[fieldInfo.name as unknown as AllItemFieldKeys<T>] ?? {};
  96. const { header, ...customConfigRest } = customConfig;
  97. const enableColumnFilter = fieldInfo.isScalar && !facetedFilters?.[fieldInfo.name];
  98. return columnHelper.accessor(fieldInfo.name as any, {
  99. id: fieldInfo.name,
  100. meta: { fieldInfo, isCustomField },
  101. enableColumnFilter,
  102. enableSorting: fieldInfo.isScalar && enableSorting,
  103. // Filtering is done on the server side, but we set this to 'equalsString' because
  104. // otherwise the TanStack Table with apply an "auto" function which somehow
  105. // prevents certain filters from working.
  106. filterFn: 'equalsString',
  107. cell: ({ cell, row }) => {
  108. const cellValue = cell.getValue();
  109. const value =
  110. cellValue ??
  111. (isCustomField ? row.original?.customFields?.[fieldInfo.name] : undefined);
  112. if (fieldInfo.list && Array.isArray(value)) {
  113. return value.join(', ');
  114. }
  115. if (
  116. (fieldInfo.type === 'DateTime' && typeof value === 'string') ||
  117. value instanceof Date
  118. ) {
  119. return <DisplayComponent id="vendure:dateTime" value={value} />;
  120. }
  121. if (fieldInfo.type === 'Boolean') {
  122. if (cell.column.id === 'enabled') {
  123. return <DisplayComponent id="vendure:booleanBadge" value={value} />;
  124. } else {
  125. return <DisplayComponent id="vendure:booleanCheckbox" value={value} />;
  126. }
  127. }
  128. if (fieldInfo.type === 'Asset') {
  129. return <DisplayComponent id="vendure:asset" value={value} />;
  130. }
  131. if (value !== null && typeof value === 'object') {
  132. return JSON.stringify(value);
  133. }
  134. return value;
  135. },
  136. header: headerContext => {
  137. return (
  138. <DataTableColumnHeader headerContext={headerContext} customConfig={customConfig} />
  139. );
  140. },
  141. ...customConfigRest,
  142. });
  143. });
  144. let finalColumns = [...queryBasedColumns];
  145. for (const [id, column] of Object.entries(additionalColumns ?? {})) {
  146. if (!id) {
  147. throw new Error('Column id is required');
  148. }
  149. finalColumns.push(columnHelper.accessor(id as any, { ...column, id }));
  150. }
  151. if (defaultColumnOrder) {
  152. // ensure the columns with ids matching the items in defaultColumnOrder
  153. // appear as the first columns in sequence, and leave the remainder in the
  154. // existing order
  155. const orderedColumns = finalColumns
  156. .filter(column => column.id && defaultColumnOrder.includes(column.id as any))
  157. .sort(
  158. (a, b) =>
  159. defaultColumnOrder.indexOf(a.id as any) - defaultColumnOrder.indexOf(b.id as any),
  160. );
  161. const remainingColumns = finalColumns.filter(
  162. column => !column.id || !defaultColumnOrder.includes(column.id as any),
  163. );
  164. finalColumns = [...orderedColumns, ...remainingColumns];
  165. }
  166. if (includeActionsColumn && (rowActions || deleteMutation || bulkActions)) {
  167. const rowActionColumn = getRowActions(rowActions, deleteMutation, allBulkActions);
  168. if (rowActionColumn) {
  169. finalColumns.push(rowActionColumn);
  170. }
  171. }
  172. if (includeSelectionColumn) {
  173. // Add the row selection column
  174. finalColumns.unshift({
  175. id: 'selection',
  176. accessorKey: 'selection',
  177. header: ({ table }) => (
  178. <Checkbox
  179. className="mx-1"
  180. checked={table.getIsAllRowsSelected()}
  181. onCheckedChange={checked =>
  182. table.toggleAllRowsSelected(checked === 'indeterminate' ? undefined : checked)
  183. }
  184. />
  185. ),
  186. enableColumnFilter: false,
  187. cell: ({ row }) => {
  188. return (
  189. <Checkbox
  190. className="mx-1"
  191. checked={row.getIsSelected()}
  192. onCheckedChange={row.getToggleSelectedHandler()}
  193. />
  194. );
  195. },
  196. });
  197. }
  198. return { columns: finalColumns, customFieldColumnNames };
  199. }, [fields, customizeColumns, rowActions, deleteMutation, additionalColumns, defaultColumnOrder]);
  200. return { columns, customFieldColumnNames };
  201. }
  202. function getRowActions(
  203. rowActions?: RowAction<any>[],
  204. deleteMutation?: TypedDocumentNode<any, any>,
  205. bulkActions?: BulkAction[],
  206. ): AccessorKeyColumnDef<any> | undefined {
  207. return {
  208. id: 'actions',
  209. accessorKey: 'actions',
  210. header: () => <Trans>Actions</Trans>,
  211. enableColumnFilter: false,
  212. cell: ({ row, table }) => {
  213. return (
  214. <DropdownMenu>
  215. <DropdownMenuTrigger asChild>
  216. <Button variant="ghost" size="icon">
  217. <EllipsisIcon />
  218. </Button>
  219. </DropdownMenuTrigger>
  220. <DropdownMenuContent>
  221. {rowActions?.map((action, index) => (
  222. <DropdownMenuItem
  223. onClick={() => action.onClick?.(row)}
  224. key={`${action.label}-${index}`}
  225. >
  226. {action.label}
  227. </DropdownMenuItem>
  228. ))}
  229. {bulkActions?.map((action, index) => (
  230. <action.component key={`bulk-action-${index}`} selection={[row]} table={table} />
  231. ))}
  232. {deleteMutation && (
  233. <DeleteMutationRowAction deleteMutation={deleteMutation} row={row} />
  234. )}
  235. </DropdownMenuContent>
  236. </DropdownMenu>
  237. );
  238. },
  239. };
  240. }
  241. function DeleteMutationRowAction({
  242. deleteMutation,
  243. row,
  244. }: Readonly<{
  245. deleteMutation: TypedDocumentNode<any, any>;
  246. row: Row<{ id: string }>;
  247. }>) {
  248. const { refetchPaginatedList } = usePaginatedList();
  249. const { i18n } = useLingui();
  250. // Inspect the mutation variables to determine if it expects 'id' or 'ids'
  251. const mutationVariables = getOperationVariablesFields(deleteMutation);
  252. const hasIdsParameter = mutationVariables.some(field => field.name === 'ids');
  253. const { mutate: deleteMutationFn } = useMutation({
  254. mutationFn: api.mutate(deleteMutation),
  255. onSuccess: (result: {
  256. [key: string]:
  257. | { result: 'DELETED' | 'NOT_DELETED'; message: string }
  258. | {
  259. result: 'DELETED' | 'NOT_DELETED';
  260. message: string;
  261. }[];
  262. }) => {
  263. const unwrappedResult = Object.values(result)[0];
  264. // Handle both single result and array of results
  265. const resultToCheck = Array.isArray(unwrappedResult) ? unwrappedResult[0] : unwrappedResult;
  266. if (resultToCheck.result === 'DELETED') {
  267. refetchPaginatedList();
  268. toast.success(i18n.t('Deleted successfully'));
  269. } else {
  270. toast.error(i18n.t('Failed to delete'), {
  271. description: resultToCheck.message,
  272. });
  273. }
  274. },
  275. onError: (err: Error) => {
  276. toast.error(i18n.t('Failed to delete'), {
  277. description: err.message,
  278. });
  279. },
  280. });
  281. return (
  282. <AlertDialog>
  283. <AlertDialogTrigger asChild>
  284. <DropdownMenuItem onSelect={e => e.preventDefault()}>
  285. <div className="flex items-center gap-2 text-destructive">
  286. <TrashIcon className="w-4 h-4 text-destructive" />
  287. <Trans>Delete</Trans>
  288. </div>
  289. </DropdownMenuItem>
  290. </AlertDialogTrigger>
  291. <AlertDialogContent>
  292. <AlertDialogHeader>
  293. <AlertDialogTitle>
  294. <Trans>Confirm deletion</Trans>
  295. </AlertDialogTitle>
  296. <AlertDialogDescription>
  297. <Trans>
  298. Are you sure you want to delete this item? This action cannot be undone.
  299. </Trans>
  300. </AlertDialogDescription>
  301. </AlertDialogHeader>
  302. <AlertDialogFooter>
  303. <AlertDialogCancel>
  304. <Trans>Cancel</Trans>
  305. </AlertDialogCancel>
  306. <AlertDialogAction
  307. onClick={() => {
  308. // Pass variables based on what the mutation expects
  309. if (hasIdsParameter) {
  310. deleteMutationFn({ ids: [row.original.id] });
  311. } else {
  312. // Fallback to single id if we can't determine the format
  313. deleteMutationFn({ id: row.original.id });
  314. }
  315. }}
  316. className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
  317. >
  318. <Trans>Delete</Trans>
  319. </AlertDialogAction>
  320. </AlertDialogFooter>
  321. </AlertDialogContent>
  322. </AlertDialog>
  323. );
  324. }