1 import { useState, useMemo, useCallback, useEffect } from "react"
2 import { useSearchParams } from "react-router-dom"
3 import { HttpTypes } from "@medusajs/types"
4 import { DataTableFilter } from "@medusajs/ui"
5 import {
6 useViewConfigurations,
7 useViewConfiguration,
8 } from "../use-view-configurations"
9 import { useEntityColumns } from "../api/views"
10 import { useFeatureFlag } from "../../providers/feature-flag-provider"
11 import { useColumnState } from "./columns/use-column-state"
12 import { useQueryParams } from "../use-query-params"
13 import { calculateRequiredFields } from "../../lib/table/field-utils"
14 import {
15 generateFiltersFromColumns,
16 getRelationshipFilterConfigs,
17 } from "../../lib/table/filter-utils"
18 import {
19 RelationshipFilterConfig,
20 useRelationshipFilterOptions,
21 } from "./use-relationship-filter-options"
22 import { TableAdapter } from "../../lib/table/table-adapters"
23
24 export interface TableConfiguration {
25 filters: Record<string, any>
26 sorting: { id: string; desc: boolean } | null
27 search: string
28 visible_columns?: string[]
29 column_order?: string[]
30 }
31
32 export interface UseTableConfigurationOptions {
33 entity: string
34 pageSize?: number
35 queryPrefix?: string
36 transformColumns?: TableAdapter<unknown>["transformColumns"]
37 /**
38 * Extra client-side columns to append to the API columns (e.g. the virtual
39 * actions column). They participate in column state like any other column.
40 */
41 extraColumns?: HttpTypes.AdminColumn[]
42 /**
43 * Default filters (filter id -> value) applied only when there is no saved
44 * view configuration active. Once a view is active, its filters are used
45 * instead. Acts as the baseline for "unsaved changes" detection.
46 */
47 defaultFilters?: Record<string, any>
48 /**
49 * Key under which saved view configurations are stored/looked up. Columns
50 * always come from the real `entity`, but views are keyed independently so
51 * that multiple tables of the SAME entity each get their own views without
52 * clobbering each other. Defaults to `entity`.
53 */
54 viewConfigurationKey?: string
55 }
56
57 export interface UseTableConfigurationReturn {
58 activeView: any
59 createView: any
60 updateView: any
61 isViewConfigEnabled: boolean
62 visibleColumns: Record<string, boolean>
63 columnOrder: string[]
64 currentColumns: {
65 visible: string[]
66 order: string[]
67 }
68 setColumnOrder: (order: string[]) => void
69 handleColumnVisibilityChange: (visibility: Record<string, boolean>) => void
70 currentConfiguration: TableConfiguration
71 hasConfigurationChanged: boolean
72 handleClearConfiguration: () => void
73 apiColumns: HttpTypes.AdminColumn[] | undefined
74 filters: DataTableFilter[]
75 isLoadingColumns: boolean
76 isLoadingFilterOptions: boolean
77 queryParams: Record<string, any>
78 requiredFields: string
79 }
80
81 function parseSortingState(value: string) {
82 return value.startsWith("-")
83 ? { id: value.slice(1), desc: true }
84 : { id: value, desc: false }
85 }
86
87 export function useTableConfiguration({
88 entity,
89 queryPrefix = "",
90 transformColumns,
91 extraColumns,
92 defaultFilters,
93 viewConfigurationKey,
94 }: UseTableConfigurationOptions): UseTableConfigurationReturn {
95 const isViewConfigEnabled = useFeatureFlag("view_configurations")
96 const [_, setSearchParams] = useSearchParams()
97
98 const viewConfigKey = viewConfigurationKey ?? entity
99
100 // Seed the adapter's default filters into the URL params. Used when no saved
101 // view is active, both on initial sync and when clearing.
102 const applyDefaultFilters = useCallback(
103 (params: URLSearchParams) => {
104 if (!defaultFilters) {
105 return
106 }
107 Object.entries(defaultFilters).forEach(([key, value]) => {
108 params.set(`${queryPrefix}_${key}`, JSON.stringify(value))
109 })
110 },
111 [defaultFilters, queryPrefix]
112 )
113
114 const { activeView, createView } = useViewConfigurations(viewConfigKey)
115 const currentActiveView = activeView?.view_configuration || null
116 const { updateView } = useViewConfiguration(
117 viewConfigKey,
118 currentActiveView?.id || ""
119 )
120
121 const { columns: rawApiColumns, isLoading: isLoadingColumns } =
122 useEntityColumns(entity, {
123 enabled: isViewConfigEnabled,
124 })
125
126 const apiColumns = useMemo(() => {
127 if (!rawApiColumns) {
128 return undefined
129 }
130 const transformed = transformColumns
131 ? transformColumns(rawApiColumns)
132 : rawApiColumns
133 return extraColumns?.length
134 ? [...transformed, ...extraColumns]
135 : transformed
136 }, [rawApiColumns, transformColumns, extraColumns])
137
138 // Extract relationship filter configs from filterable columns only
139 const relationshipFilterConfigs = useMemo(() => {
140 if (!apiColumns) {
141 return []
142 }
143
144 const filterableColumns = apiColumns.filter(
145 (column) => column.filter?.enabled
146 )
147 return getRelationshipFilterConfigs(filterableColumns)
148 }, [apiColumns])
149
150 const { options: relationshipOptions, isLoading: isLoadingFilterOptions } =
151 useRelationshipFilterOptions(
152 relationshipFilterConfigs as RelationshipFilterConfig[]
153 )
154
155 const resolvedFilters = useMemo(() => {
156 if (!apiColumns) {
157 return []
158 }
159 const filterableColumns = apiColumns.filter(
160 (column) => column.filter?.enabled
161 )
162 return generateFiltersFromColumns(filterableColumns, relationshipOptions)
163 }, [apiColumns, relationshipOptions])
164
165 const queryParams = useQueryParams(
166 ["q", "order", "offset", "limit", ...resolvedFilters.map((f) => f.id)],
167 queryPrefix
168 )
169
170 const columnsToRender = useMemo(() => {
171 return apiColumns?.filter((column) => column.context !== "filter")
172 }, [apiColumns])
173
174 // Column state
175 const {
176 visibleColumns,
177 columnOrder,
178 currentColumns,
179 setColumnOrder,
180 handleColumnVisibilityChange,
181 handleViewChange: originalHandleViewChange,
182 } = useColumnState(columnsToRender, currentActiveView)
183
184 // Re-sync only when the content of the active view or the column set changes
185 const activeViewSignature = currentActiveView
186 ? `${currentActiveView.id}:${JSON.stringify(
187 currentActiveView.configuration
188 )}`
189 : ""
190 const columnsSignature = columnsToRender
191 ? columnsToRender
192 .map((column) => column.field)
193 .sort()
194 .join(",")
195 : ""
196
197 // Sync view configuration with URL and column state
198 useEffect(() => {
199 if (!columnsToRender) {
200 return
201 }
202 originalHandleViewChange(currentActiveView, columnsToRender)
203 setSearchParams((prev) => {
204 // Clear existing query params
205 const keysToDelete = Array.from(prev.keys()).filter(
206 (key) =>
207 key.startsWith(queryPrefix + "_") ||
208 key === queryPrefix + "_q" ||
209 key === queryPrefix + "_order"
210 )
211 keysToDelete.forEach((key) => prev.delete(key))
212
213 // Apply view configuration
214 if (currentActiveView) {
215 const viewConfig = currentActiveView.configuration
216
217 if (viewConfig.filters) {
218 Object.entries(viewConfig.filters).forEach(([key, value]) => {
219 prev.set(`${queryPrefix}_${key}`, JSON.stringify(value))
220 })
221 }
222
223 if (viewConfig.sorting) {
224 const sortValue = viewConfig.sorting.desc
225 ? `-${viewConfig.sorting.id}`
226 : viewConfig.sorting.id
227 prev.set(`${queryPrefix}_order`, sortValue)
228 }
229
230 if (viewConfig.search) {
231 prev.set(`${queryPrefix}_q`, viewConfig.search)
232 }
233 } else {
234 // No saved view: fall back to the adapter's default filters.
235 applyDefaultFilters(prev)
236 }
237
238 return prev
239 })
240 // Intentionally keyed on value signatures, not object identity: re-sync
241 // only when the active view or the column set actually changes. Must NOT
242 // depend on setSearchParams (its identity changes on every URL change) or
243 // on the raw columnsToRender/currentActiveView objects (their identity can
244 // churn every render), or it re-runs on each render and clears the
245 // just-applied filter. applyDefaultFilters is stable.
246 // eslint-disable-next-line react-hooks/exhaustive-deps
247 }, [activeViewSignature, columnsSignature])
248
249 // Current configuration from URL
250 const currentConfiguration = useMemo(() => {
251 const currentFilters: Record<string, any> = {}
252 resolvedFilters.forEach((filter) => {
253 if (queryParams[filter.id] !== undefined) {
254 currentFilters[filter.id] = JSON.parse(queryParams[filter.id] || "")
255 }
256 })
257
258 return {
259 filters: currentFilters,
260 sorting: queryParams.order ? parseSortingState(queryParams.order) : null,
261 search: queryParams.q || "",
262 }
263 }, [resolvedFilters, queryParams])
264
265 // Check if configuration has changed from view
266 const [debouncedHasConfigChanged, setDebouncedHasConfigChanged] =
267 useState(false)
268
269 const hasConfigurationChanged = useMemo(() => {
270 const currentFilters = currentConfiguration.filters
271 const currentSorting = currentConfiguration.sorting
272 const currentSearch = currentConfiguration.search
273 const currentVisibleColumns = Object.entries(visibleColumns)
274 .filter(([_, isVisible]) => isVisible)
275 .map(([field]) => field)
276 .sort()
277
278 if (currentActiveView) {
279 const viewFilters = currentActiveView.configuration.filters || {}
280 const viewSorting = currentActiveView.configuration.sorting
281 const viewSearch = currentActiveView.configuration.search || ""
282 const viewVisibleColumns = [
283 ...(currentActiveView.configuration.visible_columns || []),
284 ].sort()
285 const viewColumnOrder = currentActiveView.configuration.column_order || []
286
287 // Check filters
288 const filterKeys = new Set([
289 ...Object.keys(currentFilters),
290 ...Object.keys(viewFilters),
291 ])
292 for (const key of filterKeys) {
293 if (
294 JSON.stringify(currentFilters[key]) !==
295 JSON.stringify(viewFilters[key])
296 ) {
297 return true
298 }
299 }
300
301 // Check sorting
302 const normalizedCurrentSorting = currentSorting || undefined
303 const normalizedViewSorting = viewSorting || undefined
304 if (
305 JSON.stringify(normalizedCurrentSorting) !==
306 JSON.stringify(normalizedViewSorting)
307 ) {
308 return true
309 }
310
311 // Check search
312 if (currentSearch !== viewSearch) {
313 return true
314 }
315
316 // Check visible columns
317 if (
318 JSON.stringify(currentVisibleColumns) !==
319 JSON.stringify(viewVisibleColumns)
320 ) {
321 return true
322 }
323
324 // Check column order
325 if (JSON.stringify(columnOrder) !== JSON.stringify(viewColumnOrder)) {
326 return true
327 }
328 } else {
329 // Check filters against the adapter's default filters (the baseline when
330 // no view is saved), not against "no filters".
331 const baselineFilters = defaultFilters ?? {}
332 const filterKeys = new Set([
333 ...Object.keys(currentFilters),
334 ...Object.keys(baselineFilters),
335 ])
336 for (const key of filterKeys) {
337 if (
338 JSON.stringify(currentFilters[key]) !==
339 JSON.stringify(baselineFilters[key])
340 ) {
341 return true
342 }
343 }
344 if (currentSorting !== null) {
345 return true
346 }
347 if (currentSearch !== "") {
348 return true
349 }
350
351 if (columnsToRender) {
352 const currentVisibleSet = new Set(currentVisibleColumns)
353 const defaultVisibleSet = new Set(
354 columnsToRender
355 .filter((col) => col.default_visible)
356 .map((col) => col.field)
357 )
358
359 if (
360 currentVisibleSet.size !== defaultVisibleSet.size ||
361 [...currentVisibleSet].some((field) => !defaultVisibleSet.has(field))
362 ) {
363 return true
364 }
365
366 const defaultOrder = [...columnsToRender]
367 .sort((a, b) => (a.default_order ?? 500) - (b.default_order ?? 500))
368 .map((col) => col.field)
369
370 if (JSON.stringify(columnOrder) !== JSON.stringify(defaultOrder)) {
371 return true
372 }
373 }
374 }
375
376 return false
377 }, [
378 currentActiveView,
379 visibleColumns,
380 columnOrder,
381 currentConfiguration,
382 columnsToRender,
383 defaultFilters,
384 ])
385
386 // Debounce configuration change detection
387 useEffect(() => {
388 const timer = setTimeout(() => {
389 setDebouncedHasConfigChanged(hasConfigurationChanged)
390 }, 50)
391
392 return () => clearTimeout(timer)
393 }, [hasConfigurationChanged])
394
395 // Clear configuration handler
396 const handleClearConfiguration = useCallback(() => {
397 if (columnsToRender) {
398 originalHandleViewChange(currentActiveView, columnsToRender)
399 }
400
401 setSearchParams((prev) => {
402 const keysToDelete = Array.from(prev.keys()).filter(
403 (key) =>
404 key.startsWith(queryPrefix + "_") ||
405 key === queryPrefix + "_q" ||
406 key === queryPrefix + "_order"
407 )
408 keysToDelete.forEach((key) => prev.delete(key))
409
410 if (currentActiveView?.configuration) {
411 const viewConfig = currentActiveView.configuration
412
413 if (viewConfig.filters) {
414 Object.entries(viewConfig.filters).forEach(([key, value]) => {
415 prev.set(`${queryPrefix}_${key}`, JSON.stringify(value))
416 })
417 }
418
419 if (viewConfig.sorting) {
420 const sortValue = viewConfig.sorting.desc
421 ? `-${viewConfig.sorting.id}`
422 : viewConfig.sorting.id
423 prev.set(`${queryPrefix}_order`, sortValue)
424 }
425
426 if (viewConfig.search) {
427 prev.set(`${queryPrefix}_q`, viewConfig.search)
428 }
429 } else {
430 // No saved view: clear back to the adapter's default filters.
431 applyDefaultFilters(prev)
432 }
433
434 return prev
435 })
436 // eslint-disable-next-line react-hooks/exhaustive-deps
437 }, [currentActiveView, columnsToRender, queryPrefix])
438
439 // Calculate required fields based on visible columns
440 const requiredFields = useMemo(() => {
441 return calculateRequiredFields(columnsToRender || [], visibleColumns)
442 }, [columnsToRender, visibleColumns])
443
444 return {
445 activeView: currentActiveView,
446 createView,
447 updateView,
448 isViewConfigEnabled,
449 visibleColumns,
450 columnOrder,
451 currentColumns,
452 setColumnOrder,
453 handleColumnVisibilityChange,
454 currentConfiguration,
455 hasConfigurationChanged: debouncedHasConfigChanged,
456 handleClearConfiguration,
457 apiColumns: columnsToRender,
458 filters: resolvedFilters,
459 isLoadingColumns,
460 isLoadingFilterOptions,
461 queryParams,
462 requiredFields,
463 }
464 }