|
1
|
import { |
|
2
|
DataTable as UiDataTable, |
|
3
|
useDataTable, |
|
4
|
DataTableColumnDef, |
|
5
|
DataTableCommand, |
|
6
|
DataTableEmptyStateProps, |
|
7
|
DataTableFilter, |
|
8
|
DataTableRow, |
|
9
|
DataTableRowSelectionState, |
|
10
|
Heading, |
|
11
|
Text, |
|
12
|
Button, |
|
13
|
DataTableFilteringState, |
|
14
|
DataTablePaginationState, |
|
15
|
DataTableSortingState, |
|
16
|
Tooltip, |
|
17
|
} from "@medusajs/ui" |
|
18
|
import React, { ReactNode, useCallback, useMemo } from "react" |
|
19
|
import { useTranslation } from "react-i18next" |
|
20
|
import { Link, useNavigate, useSearchParams } from "react-router-dom" |
|
21
|
|
|
22
|
import { useQueryParams } from "../../hooks/use-query-params" |
|
23
|
import { ActionMenu } from "../common/action-menu" |
|
24
|
import { ViewPills } from "../table/view-selector" |
|
25
|
import { useFeatureFlag } from "../../providers/feature-flag-provider" |
|
26
|
|
|
27
|
// Types for column visibility and ordering |
|
28
|
type VisibilityState = Record<string, boolean> |
|
29
|
type ColumnOrderState = string[] |
|
30
|
|
|
31
|
type DataTableActionProps = { |
|
32
|
label: string |
|
33
|
disabled?: boolean |
|
34
|
tooltip?: ReactNode |
|
35
|
} & ( |
|
36
|
| { |
|
37
|
to: string |
|
38
|
} |
|
39
|
| { |
|
40
|
onClick: () => void |
|
41
|
} |
|
42
|
) |
|
43
|
|
|
44
|
type DataTableActionMenuActionProps = { |
|
45
|
label: string |
|
46
|
icon: ReactNode |
|
47
|
disabled?: boolean |
|
48
|
} & ( |
|
49
|
| { |
|
50
|
to: string |
|
51
|
} |
|
52
|
| { |
|
53
|
onClick: () => void |
|
54
|
} |
|
55
|
) |
|
56
|
|
|
57
|
type DataTableActionMenuGroupProps = { |
|
58
|
actions: DataTableActionMenuActionProps[] |
|
59
|
} |
|
60
|
|
|
61
|
type DataTableActionMenuProps = { |
|
62
|
groups: DataTableActionMenuGroupProps[] |
|
63
|
} |
|
64
|
|
|
65
|
export interface DataTableProps<TData> { |
|
66
|
data?: TData[] |
|
67
|
columns: DataTableColumnDef<TData, any>[] |
|
68
|
filters?: DataTableFilter[] |
|
69
|
commands?: DataTableCommand[] |
|
70
|
action?: DataTableActionProps |
|
71
|
actions?: DataTableActionProps[] |
|
72
|
actionMenu?: DataTableActionMenuProps |
|
73
|
rowCount?: number |
|
74
|
getRowId: (row: TData) => string |
|
75
|
enablePagination?: boolean |
|
76
|
enableSearch?: boolean |
|
77
|
autoFocusSearch?: boolean |
|
78
|
rowHref?: (row: TData) => string |
|
79
|
emptyState?: DataTableEmptyStateProps |
|
80
|
heading?: string |
|
81
|
headingLevel?: "h1" | "h2" | "h3" |
|
82
|
subHeading?: string |
|
83
|
prefix?: string |
|
84
|
pageSize?: number |
|
85
|
isLoading?: boolean |
|
86
|
rowSelection?: { |
|
87
|
state: DataTableRowSelectionState |
|
88
|
onRowSelectionChange: (value: DataTableRowSelectionState) => void |
|
89
|
enableRowSelection?: boolean | ((row: DataTableRow<TData>) => boolean) |
|
90
|
} |
|
91
|
layout?: "fill" | "auto" |
|
92
|
enableColumnVisibility?: boolean |
|
93
|
initialColumnVisibility?: VisibilityState |
|
94
|
onColumnVisibilityChange?: (visibility: VisibilityState) => void |
|
95
|
columnOrder?: ColumnOrderState |
|
96
|
onColumnOrderChange?: (order: ColumnOrderState) => void |
|
97
|
enableViewSelector?: boolean |
|
98
|
entity?: string |
|
99
|
currentColumns?: { |
|
100
|
visible: string[] |
|
101
|
order: string[] |
|
102
|
} |
|
103
|
filterBarContent?: React.ReactNode |
|
104
|
} |
|
105
|
|
|
106
|
export const DataTable = <TData,>({ |
|
107
|
data = [], |
|
108
|
columns, |
|
109
|
filters, |
|
110
|
commands, |
|
111
|
action, |
|
112
|
actions, |
|
113
|
actionMenu, |
|
114
|
getRowId, |
|
115
|
rowCount = 0, |
|
116
|
enablePagination = true, |
|
117
|
enableSearch = true, |
|
118
|
autoFocusSearch = false, |
|
119
|
rowHref, |
|
120
|
heading, |
|
121
|
headingLevel = "h1", |
|
122
|
subHeading, |
|
123
|
prefix, |
|
124
|
pageSize = 10, |
|
125
|
emptyState, |
|
126
|
rowSelection, |
|
127
|
isLoading = false, |
|
128
|
layout = "auto", |
|
129
|
enableColumnVisibility = false, |
|
130
|
initialColumnVisibility = {}, |
|
131
|
onColumnVisibilityChange, |
|
132
|
columnOrder, |
|
133
|
onColumnOrderChange, |
|
134
|
enableViewSelector = false, |
|
135
|
entity, |
|
136
|
currentColumns, |
|
137
|
filterBarContent, |
|
138
|
}: DataTableProps<TData>) => { |
|
139
|
const { t } = useTranslation() |
|
140
|
const isViewConfigEnabled = useFeatureFlag("view_configurations") |
|
141
|
|
|
142
|
// If view config is disabled, don't use column visibility features |
|
143
|
const effectiveEnableColumnVisibility = |
|
144
|
isViewConfigEnabled && enableColumnVisibility |
|
145
|
const effectiveEnableViewSelector = isViewConfigEnabled && enableViewSelector |
|
146
|
|
|
147
|
const enableFiltering = filters && filters.length > 0 |
|
148
|
const enableCommands = commands && commands.length > 0 |
|
149
|
const enableSorting = columns.some((column) => column.enableSorting) |
|
150
|
|
|
151
|
// Reserve the filter bar row whenever it can gain content — active filter |
|
152
|
// chips, or the view-config save controls that appear on sort/column changes |
|
153
|
// — so toggling those doesn't shift the layout. |
|
154
|
const alwaysShowFilterBar = Boolean( |
|
155
|
enableFiltering || effectiveEnableColumnVisibility |
|
156
|
) |
|
157
|
|
|
158
|
const [columnVisibility, setColumnVisibility] = |
|
159
|
React.useState<VisibilityState>(initialColumnVisibility) |
|
160
|
|
|
161
|
// Update column visibility when initial visibility changes |
|
162
|
React.useEffect(() => { |
|
163
|
// Deep compare to check if the visibility has actually changed |
|
164
|
const currentKeys = Object.keys(columnVisibility).sort() |
|
165
|
const newKeys = Object.keys(initialColumnVisibility).sort() |
|
166
|
|
|
167
|
const hasChanged = |
|
168
|
currentKeys.length !== newKeys.length || |
|
169
|
currentKeys.some((key, index) => key !== newKeys[index]) || |
|
170
|
Object.entries(initialColumnVisibility).some( |
|
171
|
([key, value]) => columnVisibility[key] !== value |
|
172
|
) |
|
173
|
|
|
174
|
if (hasChanged) { |
|
175
|
setColumnVisibility(initialColumnVisibility) |
|
176
|
} |
|
177
|
}, [initialColumnVisibility]) |
|
178
|
|
|
179
|
// Wrapper function to handle column visibility changes |
|
180
|
const handleColumnVisibilityChange = React.useCallback( |
|
181
|
(visibility: VisibilityState) => { |
|
182
|
setColumnVisibility(visibility) |
|
183
|
onColumnVisibilityChange?.(visibility) |
|
184
|
}, |
|
185
|
[onColumnVisibilityChange] |
|
186
|
) |
|
187
|
|
|
188
|
// Extract filter IDs for query param management |
|
189
|
const filterIds = useMemo(() => filters?.map((f) => f.id) ?? [], [filters]) |
|
190
|
const prefixedFilterIds = filterIds.map((id) => getQueryParamKey(id, prefix)) |
|
191
|
|
|
192
|
const { offset, order, q, ...filterParams } = useQueryParams( |
|
193
|
[ |
|
194
|
...filterIds, |
|
195
|
...(enableSorting ? ["order"] : []), |
|
196
|
...(enableSearch ? ["q"] : []), |
|
197
|
...(enablePagination ? ["offset"] : []), |
|
198
|
], |
|
199
|
prefix |
|
200
|
) |
|
201
|
const [_, setSearchParams] = useSearchParams() |
|
202
|
|
|
203
|
const search = useMemo(() => { |
|
204
|
return q ?? "" |
|
205
|
}, [q]) |
|
206
|
|
|
207
|
const handleSearchChange = (value: string) => { |
|
208
|
setSearchParams((prev) => { |
|
209
|
if (value) { |
|
210
|
prev.set(getQueryParamKey("q", prefix), value) |
|
211
|
} else { |
|
212
|
prev.delete(getQueryParamKey("q", prefix)) |
|
213
|
} |
|
214
|
|
|
215
|
return prev |
|
216
|
}) |
|
217
|
} |
|
218
|
|
|
219
|
const pagination: DataTablePaginationState = useMemo(() => { |
|
220
|
return offset |
|
221
|
? parsePaginationState(offset, pageSize) |
|
222
|
: { pageIndex: 0, pageSize } |
|
223
|
}, [offset, pageSize]) |
|
224
|
|
|
225
|
const handlePaginationChange = (value: DataTablePaginationState) => { |
|
226
|
setSearchParams((prev) => { |
|
227
|
if (value.pageIndex === 0) { |
|
228
|
prev.delete(getQueryParamKey("offset", prefix)) |
|
229
|
} else { |
|
230
|
prev.set( |
|
231
|
getQueryParamKey("offset", prefix), |
|
232
|
transformPaginationState(value).toString() |
|
233
|
) |
|
234
|
} |
|
235
|
return prev |
|
236
|
}) |
|
237
|
} |
|
238
|
|
|
239
|
const filtering: DataTableFilteringState = useMemo( |
|
240
|
() => parseFilterState(filterIds, filterParams), |
|
241
|
[filterIds, filterParams] |
|
242
|
) |
|
243
|
|
|
244
|
const handleFilteringChange = (value: DataTableFilteringState) => { |
|
245
|
setSearchParams((prev) => { |
|
246
|
// Remove filters that are no longer in the state |
|
247
|
Array.from(prev.keys()).forEach((key) => { |
|
248
|
if (prefixedFilterIds.includes(key)) { |
|
249
|
// Extract the unprefixed key |
|
250
|
const unprefixedKey = prefix ? key.replace(`${prefix}_`, "") : key |
|
251
|
if (!(unprefixedKey in value)) { |
|
252
|
prev.delete(key) |
|
253
|
} |
|
254
|
} |
|
255
|
}) |
|
256
|
|
|
257
|
// Add or update filters in the state |
|
258
|
Object.entries(value).forEach(([key, filter]) => { |
|
259
|
const prefixedKey = getQueryParamKey(key, prefix) |
|
260
|
if (filter !== undefined) { |
|
261
|
prev.set(prefixedKey, JSON.stringify(filter)) |
|
262
|
} else { |
|
263
|
prev.delete(prefixedKey) |
|
264
|
} |
|
265
|
}) |
|
266
|
|
|
267
|
return prev |
|
268
|
}) |
|
269
|
} |
|
270
|
|
|
271
|
const sorting: DataTableSortingState | null = useMemo(() => { |
|
272
|
return order ? parseSortingState(order) : null |
|
273
|
}, [order]) |
|
274
|
|
|
275
|
// Memoize current configuration to prevent infinite loops |
|
276
|
const currentConfiguration = useMemo( |
|
277
|
() => ({ |
|
278
|
filters: filtering, |
|
279
|
sorting: sorting, |
|
280
|
search: search, |
|
281
|
}), |
|
282
|
[filtering, sorting, search] |
|
283
|
) |
|
284
|
|
|
285
|
const handleSortingChange = (value: DataTableSortingState) => { |
|
286
|
setSearchParams((prev) => { |
|
287
|
if (value) { |
|
288
|
const valueToStore = transformSortingState(value) |
|
289
|
|
|
290
|
prev.set(getQueryParamKey("order", prefix), valueToStore) |
|
291
|
} else { |
|
292
|
prev.delete(getQueryParamKey("order", prefix)) |
|
293
|
} |
|
294
|
|
|
295
|
return prev |
|
296
|
}) |
|
297
|
} |
|
298
|
|
|
299
|
const { pagination: paginationTranslations, toolbar: toolbarTranslations } = |
|
300
|
useDataTableTranslations() |
|
301
|
|
|
302
|
const navigate = useNavigate() |
|
303
|
|
|
304
|
const onRowClick = useCallback( |
|
305
|
(event: React.MouseEvent<HTMLTableRowElement, MouseEvent>, row: TData) => { |
|
306
|
if (!rowHref) { |
|
307
|
return |
|
308
|
} |
|
309
|
|
|
310
|
const href = rowHref(row) |
|
311
|
const basePath = __BASE__ || "/" |
|
312
|
const hrefWithBasePath = `${basePath === "/" ? "" : basePath}${href}` |
|
313
|
|
|
314
|
if (event.metaKey || event.ctrlKey || event.button === 1) { |
|
315
|
window.open(hrefWithBasePath, "_blank", "noreferrer") |
|
316
|
return |
|
317
|
} |
|
318
|
|
|
319
|
if (event.shiftKey) { |
|
320
|
window.open(hrefWithBasePath, undefined, "noreferrer") |
|
321
|
return |
|
322
|
} |
|
323
|
|
|
324
|
navigate(href) |
|
325
|
}, |
|
326
|
[navigate, rowHref] |
|
327
|
) |
|
328
|
|
|
329
|
const instance = useDataTable({ |
|
330
|
data, |
|
331
|
columns, |
|
332
|
filters, |
|
333
|
commands, |
|
334
|
rowCount, |
|
335
|
getRowId, |
|
336
|
onRowClick: rowHref ? onRowClick : undefined, |
|
337
|
pagination: enablePagination |
|
338
|
? { |
|
339
|
state: pagination, |
|
340
|
onPaginationChange: handlePaginationChange, |
|
341
|
} |
|
342
|
: undefined, |
|
343
|
filtering: enableFiltering |
|
344
|
? { |
|
345
|
state: filtering, |
|
346
|
onFilteringChange: handleFilteringChange, |
|
347
|
} |
|
348
|
: undefined, |
|
349
|
sorting: enableSorting |
|
350
|
? { |
|
351
|
state: sorting, |
|
352
|
onSortingChange: handleSortingChange, |
|
353
|
} |
|
354
|
: undefined, |
|
355
|
search: enableSearch |
|
356
|
? { |
|
357
|
state: search, |
|
358
|
onSearchChange: handleSearchChange, |
|
359
|
} |
|
360
|
: undefined, |
|
361
|
rowSelection, |
|
362
|
isLoading, |
|
363
|
columnVisibility: effectiveEnableColumnVisibility |
|
364
|
? { |
|
365
|
state: columnVisibility, |
|
366
|
onColumnVisibilityChange: handleColumnVisibilityChange, |
|
367
|
} |
|
368
|
: undefined, |
|
369
|
columnOrder: |
|
370
|
effectiveEnableColumnVisibility && columnOrder && onColumnOrderChange |
|
371
|
? { |
|
372
|
state: columnOrder, |
|
373
|
onColumnOrderChange: onColumnOrderChange, |
|
374
|
} |
|
375
|
: undefined, |
|
376
|
}) |
|
377
|
|
|
378
|
const shouldRenderHeading = heading || subHeading |
|
379
|
|
|
380
|
return ( |
|
381
|
<UiDataTable |
|
382
|
instance={instance} |
|
383
|
className={ |
|
384
|
layout === "fill" ? "h-full [&_tr]:last-of-type:!border-b" : undefined |
|
385
|
} |
|
386
|
> |
|
387
|
<UiDataTable.Toolbar |
|
388
|
className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center" |
|
389
|
translations={toolbarTranslations} |
|
390
|
filterBarContent={filterBarContent} |
|
391
|
alwaysShowFilterBar={alwaysShowFilterBar} |
|
392
|
> |
|
393
|
<div className="flex w-full items-center justify-between gap-2"> |
|
394
|
<div className="flex items-center gap-x-4"> |
|
395
|
{shouldRenderHeading && ( |
|
396
|
<div> |
|
397
|
{heading && <Heading level={headingLevel}>{heading}</Heading>} |
|
398
|
{subHeading && ( |
|
399
|
<Text size="small" className="text-ui-fg-subtle"> |
|
400
|
{subHeading} |
|
401
|
</Text> |
|
402
|
)} |
|
403
|
</div> |
|
404
|
)} |
|
405
|
{effectiveEnableViewSelector && entity && ( |
|
406
|
<ViewPills |
|
407
|
entity={entity} |
|
408
|
currentColumns={currentColumns} |
|
409
|
currentConfiguration={currentConfiguration} |
|
410
|
/> |
|
411
|
)} |
|
412
|
</div> |
|
413
|
<div className="flex items-center gap-x-2"> |
|
414
|
{enableFiltering && ( |
|
415
|
<UiDataTable.FilterMenu tooltip={toolbarTranslations.filter} /> |
|
416
|
)} |
|
417
|
{enableSorting && ( |
|
418
|
<UiDataTable.SortingMenu tooltip={toolbarTranslations.sort} /> |
|
419
|
)} |
|
420
|
{effectiveEnableColumnVisibility && ( |
|
421
|
<UiDataTable.ColumnVisibilityMenu |
|
422
|
tooltip={toolbarTranslations.columns} |
|
423
|
/> |
|
424
|
)} |
|
425
|
{enableSearch && ( |
|
426
|
<div className="w-full md:w-auto"> |
|
427
|
<UiDataTable.Search |
|
428
|
placeholder={t("filters.searchLabel")} |
|
429
|
autoFocus={autoFocusSearch} |
|
430
|
/> |
|
431
|
</div> |
|
432
|
)} |
|
433
|
{actionMenu && <ActionMenu variant="primary" {...actionMenu} />} |
|
434
|
{actions && actions.length > 0 && ( |
|
435
|
<DataTableActions actions={actions} /> |
|
436
|
)} |
|
437
|
{!actions && action && <DataTableAction {...action} />} |
|
438
|
</div> |
|
439
|
</div> |
|
440
|
</UiDataTable.Toolbar> |
|
441
|
<UiDataTable.Table emptyState={emptyState} /> |
|
442
|
{enablePagination && ( |
|
443
|
<UiDataTable.Pagination translations={paginationTranslations} /> |
|
444
|
)} |
|
445
|
{enableCommands && ( |
|
446
|
<UiDataTable.CommandBar |
|
447
|
selectedLabel={(count) => `${count} selected`} |
|
448
|
/> |
|
449
|
)} |
|
450
|
</UiDataTable> |
|
451
|
) |
|
452
|
} |
|
453
|
|
|
454
|
function transformSortingState(value: DataTableSortingState) { |
|
455
|
return value.desc ? `-${value.id}` : value.id |
|
456
|
} |
|
457
|
|
|
458
|
function parseSortingState(value: string) { |
|
459
|
return value.startsWith("-") |
|
460
|
? { id: value.slice(1), desc: true } |
|
461
|
: { id: value, desc: false } |
|
462
|
} |
|
463
|
|
|
464
|
function transformPaginationState(value: DataTablePaginationState) { |
|
465
|
return value.pageIndex * value.pageSize |
|
466
|
} |
|
467
|
|
|
468
|
function parsePaginationState(value: string, pageSize: number) { |
|
469
|
const offset = parseInt(value) |
|
470
|
|
|
471
|
return { |
|
472
|
pageIndex: Math.floor(offset / pageSize), |
|
473
|
pageSize, |
|
474
|
} |
|
475
|
} |
|
476
|
|
|
477
|
function parseFilterState( |
|
478
|
filterIds: string[], |
|
479
|
value: Record<string, string | undefined> |
|
480
|
) { |
|
481
|
if (!value) { |
|
482
|
return {} |
|
483
|
} |
|
484
|
|
|
485
|
const filters: DataTableFilteringState = {} |
|
486
|
|
|
487
|
for (const id of filterIds) { |
|
488
|
const filterValue = value[id] |
|
489
|
|
|
490
|
if (filterValue !== undefined) { |
|
491
|
filters[id] = parseFilterValue(filterValue) |
|
492
|
} |
|
493
|
} |
|
494
|
|
|
495
|
return filters |
|
496
|
} |
|
497
|
|
|
498
|
// Radio/select filters use string option values, but a URL written by hand |
|
499
|
// (e.g. `?is_exclusive=false`) JSON-parses to a boolean and no longer matches |
|
500
|
// those values, leaving the filter chip unhighlighted. Fall back to the raw |
|
501
|
// string in that case so manual URLs still highlight correctly. |
|
502
|
function parseFilterValue(raw: string): unknown { |
|
503
|
try { |
|
504
|
const parsed = JSON.parse(raw) |
|
505
|
return typeof parsed === "boolean" ? raw : parsed |
|
506
|
} catch { |
|
507
|
return raw |
|
508
|
} |
|
509
|
} |
|
510
|
|
|
511
|
function getQueryParamKey(key: string, prefix?: string) { |
|
512
|
return prefix ? `${prefix}_${key}` : key |
|
513
|
} |
|
514
|
|
|
515
|
const useDataTableTranslations = () => { |
|
516
|
const { t } = useTranslation() |
|
517
|
|
|
518
|
const paginationTranslations = { |
|
519
|
of: t("general.of"), |
|
520
|
results: t("general.results"), |
|
521
|
pages: t("general.pages"), |
|
522
|
prev: t("general.prev"), |
|
523
|
next: t("general.next"), |
|
524
|
} |
|
525
|
|
|
526
|
const toolbarTranslations = { |
|
527
|
clearAll: t("actions.clearAll"), |
|
528
|
sort: t("filters.sortLabel"), |
|
529
|
filter: t("filters.filterLabel"), |
|
530
|
columns: t("filters.columnsLabel"), |
|
531
|
} |
|
532
|
|
|
533
|
return { |
|
534
|
pagination: paginationTranslations, |
|
535
|
toolbar: toolbarTranslations, |
|
536
|
} |
|
537
|
} |
|
538
|
|
|
539
|
const DataTableAction = ({ |
|
540
|
label, |
|
541
|
disabled, |
|
542
|
tooltip, |
|
543
|
...props |
|
544
|
}: DataTableActionProps) => { |
|
545
|
const buttonProps = { |
|
546
|
size: "small" as const, |
|
547
|
disabled: disabled ?? false, |
|
548
|
type: "button" as const, |
|
549
|
variant: "secondary" as const, |
|
550
|
} |
|
551
|
|
|
552
|
if ("to" in props) { |
|
553
|
const linkButton = disabled ? ( |
|
554
|
<Button {...buttonProps}>{label}</Button> |
|
555
|
) : ( |
|
556
|
<Button {...buttonProps} asChild> |
|
557
|
<Link to={props.to}>{label}</Link> |
|
558
|
</Button> |
|
559
|
) |
|
560
|
|
|
561
|
return tooltip ? ( |
|
562
|
<Tooltip content={tooltip}>{linkButton}</Tooltip> |
|
563
|
) : ( |
|
564
|
linkButton |
|
565
|
) |
|
566
|
} |
|
567
|
|
|
568
|
return tooltip ? ( |
|
569
|
<Tooltip content={tooltip}> |
|
570
|
<Button {...buttonProps} onClick={props.onClick}> |
|
571
|
{label} |
|
572
|
</Button> |
|
573
|
</Tooltip> |
|
574
|
) : ( |
|
575
|
<Button {...buttonProps} onClick={props.onClick}> |
|
576
|
{label} |
|
577
|
</Button> |
|
578
|
) |
|
579
|
} |
|
580
|
|
|
581
|
const DataTableActions = ({ actions }: { actions: DataTableActionProps[] }) => { |
|
582
|
return ( |
|
583
|
<div className="flex items-center gap-x-2"> |
|
584
|
{actions.map((action, index) => ( |
|
585
|
<DataTableAction key={index} {...action} /> |
|
586
|
))} |
|
587
|
</div> |
|
588
|
) |
|
589
|
} |