1 import { HttpTypes } from "@medusajs/types"
2 import {
3 DataTableColumnAlignment,
4 DataTableColumnDef,
5 DataTableCommand,
6 DataTableEmptyStateProps,
7 DataTableFilter,
8 } from "@medusajs/ui"
9 import { ReactNode } from "react"
10
11 /**
12 * Adapter interface for configurable tables.
13 * Defines how to fetch and display data for a specific entity type.
14 */
15 export interface TableAdapter<TData> {
16 /**
17 * The entity type (e.g., "orders", "products", "customers")
18 */
19 entity: string
20
21 /**
22 * Hook to fetch data with the calculated required fields.
23 * Called inside ConfigurableDataTable with the fields and search params.
24 */
25 useData: (
26 fields: string,
27 params: any
28 ) => {
29 data: TData[] | undefined
30 count: number | undefined
31 isLoading: boolean
32 isError: boolean
33 error: any
34 }
35
36 /**
37 * Extract unique ID from a row. Defaults to row.id if not provided.
38 */
39 getRowId?: (row: TData) => string
40
41 /**
42 * Generate href for row navigation. Return undefined for non-clickable rows.
43 */
44 getRowHref?: (row: TData) => string | undefined
45
46 /**
47 * Explicit table filters configuration. If not provided, filters will be reolved dynamically from the API columns.
48 */
49 filters?: DataTableFilter[]
50
51 /**
52 * Transform API columns before use (e.g., disable sorting, exclude filters).
53 * Applied immediately after fetching columns from API.
54 * Returns a new array of columns with desired modifications.
55 *
56 * @param columns - The API columns to transform
57 * @returns Transformed columns
58 *
59 * @example
60 * transformColumns: (columns) => columns.map(col => ({
61 * ...col,
62 * sortable: col.field === 'status' ? false : col.sortable,
63 * filter: { ...col.filter, enabled: false }
64 * }))
65 */
66 transformColumns?: (
67 columns: HttpTypes.AdminColumn[]
68 ) => HttpTypes.AdminColumn[]
69
70 /**
71 * Transform API columns to table columns.
72 * If not provided, will use default column generation.
73 */
74 getColumns?: (apiColumns: any[]) => DataTableColumnDef<TData, any>[]
75
76 /**
77 * Override the alignment of a column's header and cell content.
78 * Return undefined to fall back to the render mode's declared alignment,
79 * and to the DataTable default when the render mode declares none.
80 */
81 getColumnAlignment?: (
82 column: HttpTypes.AdminColumn
83 ) => DataTableColumnAlignment | undefined
84
85 /**
86 * Empty state configuration
87 */
88 emptyState?: DataTableEmptyStateProps
89
90 /**
91 * Default page size
92 */
93 pageSize?: number
94
95 /**
96 * Query parameter prefix for URL state management
97 */
98 queryPrefix?: string
99
100 /**
101 * Key under which saved view configurations are stored, decoupled from
102 * `entity` (which drives columns). Set this when more than one table renders
103 * the SAME entity (e.g. publishable vs secret api keys) so each table keeps
104 * its own views instead of sharing them. Defaults to `entity`.
105 */
106 viewConfigurationKey?: string
107
108 /**
109 * Optional entity display name for headings
110 */
111 entityName?: string
112
113 /**
114 * Domain-specific row actions. When provided, a trailing, toggleable
115 * "actions" column is injected that renders this per row — typically the
116 * domain's existing action-menu component (icon trigger + menu), which can
117 * own its permissions, prompts and mutations.
118 */
119 renderRowActions?: (row: TData) => ReactNode
120
121 /**
122 * Default filters (filter id -> value) applied only when no saved view
123 * configuration is active. Once a view is active, its filters win. Values
124 * use the same shape as the filter's option value (e.g. `"false"` for a
125 * boolean filter). Also used as the baseline for "unsaved changes".
126 */
127 defaultFilters?: Record<string, any>
128
129 /**
130 * Override the outgoing query-param key for a resolved filter id when issuing
131 * the data request. The columns endpoint exposes filter ids by schema field
132 * path (e.g. `"sales_channels.id"`), which may not match the key the target
133 * list endpoint accepts (e.g. `"sales_channel_id"`). Map filter id -> param
134 * key; only the request key is rewritten — the filter id stays the same for
135 * the UI, URL and saved views. Unmapped filters pass through unchanged.
136 */
137 filterParamMap?: Record<string, string>
138
139 /**
140 * Enable per-row selection. When true, a leading checkbox "select" column is
141 * injected and selection state is managed by the table. Required for
142 * `commands` (bulk actions) to be usable.
143 */
144 enableRowSelection?: boolean
145
146 /**
147 * Bulk command-bar actions operating on the current row selection. Each
148 * command's `action` receives the selection state (row id -> boolean).
149 */
150 commands?: DataTableCommand[]
151 }
152
153 /**
154 * Field/id used for the injected virtual selection column. Must be "select" —
155 * the ui DataTable special-cases that id (sticky, non-draggable checkbox cell).
156 */
157 export const SELECT_COLUMN_FIELD = "select"
158
159 /**
160 * Build the synthetic selection column. Injected as an API-shaped column (like
161 * the actions column) so it participates in column ordering/visibility state;
162 * its very low `default_order` keeps it first. Rendered as the ui select column
163 * by `useConfigurableTableColumns`.
164 */
165 export function createSelectColumn(): HttpTypes.AdminColumn {
166 return {
167 id: SELECT_COLUMN_FIELD,
168 name: "",
169 field: SELECT_COLUMN_FIELD,
170 sortable: false,
171 hideable: false,
172 default_visible: true,
173 data_type: "string",
174 semantic_type: "select",
175 context: "display",
176 render_mode: "select",
177 // Always first.
178 default_order: 0,
179 filter: { enabled: false },
180 category: "computed",
181 }
182 }
183
184 /**
185 * Field/id used for the injected virtual actions column.
186 */
187 export const ACTIONS_COLUMN_FIELD = "action"
188
189 /**
190 * Build the synthetic column definition for the row actions column. It is
191 * injected client-side (it does not come from the API) but is shaped like an
192 * API column so it participates in column visibility, ordering and view
193 * persistence like any other column. Rendered specially by
194 * `useConfigurableTableColumns` via the adapter's `getRowActions`.
195 */
196 export function createActionsColumn(name: string): HttpTypes.AdminColumn {
197 return {
198 id: ACTIONS_COLUMN_FIELD,
199 name,
200 field: ACTIONS_COLUMN_FIELD,
201 sortable: false,
202 hideable: true,
203 default_visible: true,
204 data_type: "string",
205 semantic_type: "actions",
206 context: "display",
207 render_mode: "actions",
208 // Keep the actions column last by default.
209 default_order: 100000,
210 filter: { enabled: false },
211 category: "computed",
212 }
213 }
214
215 /**
216 * Helper to create a type-safe table adapter
217 */
218 export function createTableAdapter<TData>(
219 adapter: TableAdapter<TData>
220 ): TableAdapter<TData> {
221 return {
222 // Provide smart defaults
223 getRowId: (row: any) => row.id,
224 pageSize: 20,
225 queryPrefix: "",
226 ...adapter,
227 }
228 }