summaryrefslogtreecommitdiff
path: root/hooks/use-data-table.ts
blob: 1cbae9de714b4efd0d3797748990c4921959f5f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
// ====================== hooks/use-data-table.ts ======================
"use client";

import * as React from "react";
import type {
  DataTableFilterField,
  ExtendedSortingState,
} from "@/types/table";
import {
  getCoreRowModel,
  getFacetedRowModel,
  getFacetedUniqueValues,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  getGroupedRowModel,
  getExpandedRowModel,
  useReactTable,
  type ColumnFiltersState,
  type PaginationState,
  type RowSelectionState,
  type SortingState,
  type TableOptions,
  type TableState,
  type Updater,
  type VisibilityState,
  type ExpandedState,
} from "@tanstack/react-table";
import {
  parseAsArrayOf,
  parseAsInteger,
  parseAsString,
  useQueryState,
  useQueryStates,
  type Parser,
  type UseQueryStateOptions,
} from "nuqs";
import useSWRInfinite from "swr/infinite";

import { getSortingStateParser } from "@/lib/parsers";
import { useDebouncedCallback } from "@/hooks/use-debounced-callback";
import isEqual from "fast-deep-equal";
import deepEqual from "fast-deep-equal";

// ───────────────────────────────────────────────────────────────────────
// 무한 스크롤 관련 상수 및 타입
// ───────────────────────────────────────────────────────────────────────
const INFINITE_SCROLL_THRESHOLD = 1_000_000;

interface InfiniteScrollConfig {
  apiEndpoint: string;
  tableName: string;
  maxPageSize?: number;
}

interface InfiniteScrollResponse<TData> {
  mode: "infinite";
  data: TData[];
  hasNextPage: boolean;
  nextCursor: string | null;
  total?: number | null;
}

// ───────────────────────────────────────────────────────────────────────
// Hook props
// ───────────────────────────────────────────────────────────────────────
export interface UseDataTableProps<TData>
  extends Omit<
      TableOptions<TData>,
      | "state"
      | "pageCount"
      | "getCoreRowModel"
      | "manualFiltering"
      | "manualPagination"
      | "manualSorting"
      | "onGroupingChange"
      | "onExpandedChange"
      | "getExpandedRowModel"
      | "data"
    >,
    Required<Pick<TableOptions<TData>, "pageCount">> {
  filterFields?: DataTableFilterField<TData>[];
  enableAdvancedFilter?: boolean;
  history?: "push" | "replace";
  scroll?: boolean;
  shallow?: boolean;
  throttleMs?: number;
  debounceMs?: number;
  startTransition?: React.TransitionStartFunction;
  clearOnDefault?: boolean;
  initialState?: Omit<Partial<TableState>, "sorting"> & {
    sorting?: ExtendedSortingState<TData>;
    grouping?: string[];
    expanded?: Record<string, boolean>;
  };
  data?: TData[]; // 페이지네이션 모드 초기 데이터
  infiniteScrollConfig?: InfiniteScrollConfig;
  /** Table state가 변경되어 URL을 동기화할 때 호출됩니다. 이미 같은 문자열이면 호출되지 않습니다. */
  onStateToUrl?: (queryString: string) => void;
}

// ───────────────────────────────────────────────────────────────────────
// useDataTable
// ───────────────────────────────────────────────────────────────────────
export function useDataTable<TData>({
  pageCount = -1,
  filterFields = [],
  enableAdvancedFilter = false,
  history = "replace",
  scroll = false,
  shallow = true,
  throttleMs = 50,
  debounceMs = 300,
  clearOnDefault = false,
  startTransition,
  initialState,
  data: initialData = [],
  infiniteScrollConfig,
  onStateToUrl,
  ...props
}: UseDataTableProps<TData>) {
  // ───────────────────────── 공통 QueryState 옵션 ───────────────────────
  const queryStateOptions = React.useMemo<
    Omit<UseQueryStateOptions<string>, "parse">
  >(
    () => ({
      history,
      scroll,
      shallow,
      throttleMs,
      debounceMs,
      clearOnDefault,
      startTransition,
    }),
    [history, scroll, shallow, throttleMs, debounceMs, clearOnDefault, startTransition],
  );

  // ───────────────────────── 로컬 상태들 ────────────────────────────────
  const [rowSelection, setRowSelection] = React.useState<RowSelectionState>(
    initialState?.rowSelection ?? {},
  );
  const [columnVisibility, setColumnVisibility] =
    React.useState<VisibilityState>(initialState?.columnVisibility ?? {});
  const [expanded, setExpanded] = React.useState<ExpandedState>({});

  // ───────────────────────── URL ↔️ Pagination 동기화 ───────────────────
  const [page, setPage] = useQueryState(
    "page",
    parseAsInteger.withOptions(queryStateOptions).withDefault(1),
  );
  const [perPage, setPerPage] = useQueryState(
    "perPage",
    parseAsInteger
      .withOptions(queryStateOptions)
      .withDefault(initialState?.pagination?.pageSize ?? 10),
  );

  const isInfiniteMode = !!(
    infiniteScrollConfig && perPage >= INFINITE_SCROLL_THRESHOLD
  );

  // ───────────────────────── URL ↔️ Sorting 동기화 ─────────────────────
  const [sorting, setSorting] = useQueryState(
    "sort",
    getSortingStateParser<TData>()
      .withOptions(queryStateOptions)
      .withDefault(initialState?.sorting ?? []),
  );

  // ───────────────────────── URL ↔️ 기타 파라미터 ──────────────────────
  const [filters, setFilters] = useQueryState(
    "filters",
    parseAsString.withOptions(queryStateOptions).withDefault("[]"),
  );
  const [joinOperator, setJoinOperator] = useQueryState(
    "joinOperator",
    parseAsString.withOptions(queryStateOptions).withDefault("and"),
  );
  const [search, setSearch] = useQueryState(
    "search",
    parseAsString.withOptions(queryStateOptions).withDefault(""),
  );
  const [grouping, setGrouping] = useQueryState(
    "group",
    parseAsArrayOf(parseAsString, ",")
      .withOptions(queryStateOptions)
      .withDefault(initialState?.grouping ?? []),
  );

  // ───────────────────────── Pagination helper ─────────────────────────
  const pagination: PaginationState = {
    pageIndex: page - 1,
    pageSize: perPage,
  };

  // ───────────────────────── Table → URL 직렬화 ────────────────────────
  const toQueryString = React.useCallback(
    (pg: PaginationState, sort: SortingState) => {
      const p = new URLSearchParams();
      if (pg.pageIndex > 0) p.set("page", String(pg.pageIndex + 1));
      if (pg.pageSize !== perPage) p.set("perPage", String(pg.pageSize));
      if (sort.length) p.set("sort", JSON.stringify(sort));
      return p.toString();
    },
    [perPage],
  );

  // ───────────────────────── 페이징 변경 ───────────────────────────────
  const handlePageSizeChange = React.useCallback(
    (newPageSize: number) => {
      void setPerPage(newPageSize);
      const wasInfinite = perPage >= INFINITE_SCROLL_THRESHOLD;
      const willBeInfinite = newPageSize >= INFINITE_SCROLL_THRESHOLD;
      if (wasInfinite !== willBeInfinite) {
        void setPage(1);
      }
    },
    [perPage, setPerPage, setPage],
  );

  function onPaginationChange(updater: Updater<PaginationState>) {
    if (isInfiniteMode) return;
    const next = typeof updater === "function" ? updater(pagination) : updater;

    // URL 동기화 (diff)
    if (onStateToUrl) {
      const qs = toQueryString(next, sorting);
      if (qs !== window.location.search.slice(1)) onStateToUrl(qs);
    }

    void setPage(next.pageIndex + 1);
    if (next.pageSize !== perPage) handlePageSizeChange(next.pageSize);
  }

  // ───────────────────────── Sorting 변경 ──────────────────────────────
  function onSortingChange(updater: Updater<SortingState>) {
    const next = typeof updater === "function" ? updater(sorting) : updater;

    if (onStateToUrl) {
      const qs = toQueryString(pagination, next);
      if (qs !== window.location.search.slice(1)) onStateToUrl(qs);
    }

    if (!isEqual(next, sorting)) {
      void setSorting(next as ExtendedSortingState<TData>);
    }
  }

  // -------- 무한 스크롤 SWR 설정 --------
  const parsedFilters = React.useMemo(() => {
    try {
      return JSON.parse(filters)
    } catch {
      return []
    }
  }, [filters])

  const sortForSWR = React.useMemo(() => {
    return sorting.map(sort => ({
      id: sort.id,
      desc: sort.desc
    }))
  }, [sorting])

  // 실제 페이지 크기 계산 (무한 스크롤 시)
  const effectivePageSize = React.useMemo(() => {
    if (!isInfiniteMode) return perPage
    
    // 무한 스크롤 모드에서는 적절한 청크 크기 사용
    const maxSize = infiniteScrollConfig?.maxPageSize || 100
    return Math.min(50, maxSize) // 기본 50개씩 로드
  }, [isInfiniteMode, perPage, infiniteScrollConfig?.maxPageSize])

  // SWR 키 생성 함수 - 안정화를 위해 useCallback 사용
  const getKey = React.useCallback(
    (pageIndex: number, previousPageData: InfiniteScrollResponse<TData> | null) => {
      if (!isInfiniteMode || !infiniteScrollConfig) return null
      
      const params = new URLSearchParams()
      
      if (pageIndex === 0) {
        // 첫 페이지
        params.set("limit", String(effectivePageSize))
        if (search) params.set("search", search)
        if (parsedFilters.length) params.set("filters", JSON.stringify(parsedFilters))
        if (joinOperator !== "and") params.set("joinOperator", joinOperator)
        if (sortForSWR.length) params.set("sort", JSON.stringify(sortForSWR))
        
        return `${infiniteScrollConfig.apiEndpoint}?${params.toString()}`
      }

      // 다음 페이지
      if (!previousPageData || !previousPageData.hasNextPage) return null

      params.set("cursor", previousPageData.nextCursor || "")
      params.set("limit", String(effectivePageSize))
      if (search) params.set("search", search)
      if (parsedFilters.length) params.set("filters", JSON.stringify(parsedFilters))
      if (joinOperator !== "and") params.set("joinOperator", joinOperator)
      if (sortForSWR.length) params.set("sort", JSON.stringify(sortForSWR))

      return `${infiniteScrollConfig.apiEndpoint}?${params.toString()}`
    },
    [isInfiniteMode, infiniteScrollConfig, effectivePageSize, search, parsedFilters, joinOperator, sortForSWR]
  )

  // SWR Infinite 사용
  const {
    data: swrData,
    error: swrError,
    isLoading: swrIsLoading,
    isValidating: swrIsValidating,
    mutate: swrMutate,
    size: swrSize,
    setSize: swrSetSize,
  } = useSWRInfinite<InfiniteScrollResponse<TData>>(
    getKey,
    async (url: string) => {
      const response = await fetch(url)
      if (!response.ok) throw new Error(`HTTP ${response.status}`)
      return response.json()
    },
    {
      revalidateFirstPage: false,
      revalidateOnFocus: false,
      revalidateOnReconnect: true,
    }
  )

  // 무한 스크롤 데이터 병합
  const infiniteData = React.useMemo(() => {
    if (!isInfiniteMode || !swrData) return []
    return swrData.flatMap(page => page.data)
  }, [swrData, isInfiniteMode])

  // 무한 스크롤 메타 정보 - 안정화를 위해 useCallback 사용
  const infiniteScrollActions = React.useMemo(() => ({
    loadMore: () => {
      if (swrData && swrData[swrData.length - 1]?.hasNextPage && !swrIsValidating) {
        swrSetSize(prev => prev + 1)
      }
    },
    reset: () => {
      swrSetSize(1)
      swrMutate()
    },
    refresh: () => swrMutate(),
  }), [swrData, swrIsValidating, swrSetSize, swrMutate])

  const infiniteMeta = React.useMemo(() => {
    if (!isInfiniteMode || !infiniteScrollConfig) return null
    
    const totalCount = swrData?.[0]?.total ?? null
    const hasNextPage = swrData?.[swrData.length - 1]?.hasNextPage ?? false
    const isLoadingMore = swrIsValidating && swrData && typeof swrData[swrSize - 1] !== "undefined"
    
    return {
      enabled: true,
      totalCount,
      hasNextPage,
      isLoadingMore,
      onLoadMore: infiniteScrollActions.loadMore,
      reset: infiniteScrollActions.reset,
      refresh: infiniteScrollActions.refresh,
      error: swrError,
      isLoading: swrIsLoading,
      isEmpty: swrData?.[0]?.data.length === 0,
    }
  }, [
    isInfiniteMode, 
    infiniteScrollConfig, 
    swrData, 
    swrIsValidating, 
    swrSize, 
    swrError, 
    swrIsLoading, 
    infiniteScrollActions
  ])

  // 검색어나 필터 변경 시 무한 스크롤 리셋 - infiniteMeta 의존성 제거
  const resetInfiniteScroll = React.useCallback(() => {
    if (isInfiniteMode && infiniteScrollActions) {
      infiniteScrollActions.reset()
    }
  }, [isInfiniteMode, infiniteScrollActions])

  // 필터 변경 시 리셋 - useEffect dependency 최소화
  React.useEffect(() => {
    resetInfiniteScroll()
  }, [search, filters, joinOperator])

  // 최종 데이터 결정
  const finalData = isInfiniteMode ? infiniteData : initialData

  function onGroupingChange(updaterOrValue: Updater<string[]>) {
    if (typeof updaterOrValue === "function") {
      const newGrouping = updaterOrValue(grouping)
      void setGrouping(newGrouping)
    } else {
      void setGrouping(updaterOrValue)
    }
  }

  function onExpandedChange(updater: Updater<ExpandedState>) {
    setExpanded((old) => (typeof updater === "function" ? updater(old) : updater))
  }



  // 기존 필터 로직들... (동일)
  const filterParsers = React.useMemo(() => {
    return filterFields.reduce<
      Record<string, Parser<string> | Parser<string[]>>
    >((acc, field) => {
      if (field.options) {
        acc[field.id] = parseAsArrayOf(parseAsString, ",").withOptions(
          queryStateOptions
        )
      } else {
        acc[field.id] = parseAsString.withOptions(queryStateOptions)
      }
      return acc
    }, {})
  }, [filterFields, queryStateOptions])

  const [filterValues, setFilterValues] = useQueryStates(filterParsers)
  const debouncedSetFilterValues = useDebouncedCallback(
    setFilterValues,
    debounceMs
  )

  const initialColumnFilters: ColumnFiltersState = React.useMemo(() => {
    return enableAdvancedFilter
      ? []
      : Object.entries(filterValues).reduce<ColumnFiltersState>(
          (filters, [key, value]) => {
            if (value !== null) {
              filters.push({
                id: key,
                value: Array.isArray(value) ? value : [value],
              })
            }
            return filters
          },
          []
        )
  }, [filterValues, enableAdvancedFilter])

  const [columnFilters, setColumnFilters] =
    React.useState<ColumnFiltersState>(initialColumnFilters)

  const { searchableColumns, filterableColumns } = React.useMemo(() => {
    return enableAdvancedFilter
      ? { searchableColumns: [], filterableColumns: [] }
      : {
          searchableColumns: filterFields.filter((field) => !field.options),
          filterableColumns: filterFields.filter((field) => field.options),
        }
  }, [filterFields, enableAdvancedFilter])

// -------- column-filters 변경 핸들러 (루프 차단 버전) --------
const onColumnFiltersChange = React.useCallback(
  (updater: Updater<ColumnFiltersState>) => {
    setColumnFilters(prev => {
      const next =
        typeof updater === "function" ? updater(prev) : updater

      /* 변동이 없으면 바로 종료 */
      if (deepEqual(prev, next)) return prev

      /* ---------- URL 동기화: 고급필터 OFF 때만 ---------- */
      if (!enableAdvancedFilter) {
        const updates: Record<string, string | string[] | null> = {}

        next.forEach(f => {
          if (searchableColumns.some(c => c.id === f.id))
            updates[f.id] = f.value as string
          else if (filterableColumns.some(c => c.id === f.id))
            updates[f.id] = f.value as string[]
        })
        prev.forEach(pf => {
          if (!next.some(nf => nf.id === pf.id)) updates[pf.id] = null
        })

        void setPage(1)
        debouncedSetFilterValues(updates)
      }

      return next        // ★ 항상 state 를 반영
    })
  },
  [
    enableAdvancedFilter,
    searchableColumns,
    filterableColumns,
    deepEqual,               // fast-deep-equal
    debouncedSetFilterValues,
    setPage,
  ]
)

  // -------- TanStack Table 인스턴스 생성 --------
  const table = useReactTable({
    ...props,
    data: finalData,
    initialState,
    pageCount: isInfiniteMode ? -1 : pageCount,
    state: {
      pagination,
      sorting,
      columnVisibility,
      rowSelection,
      columnFilters: enableAdvancedFilter ? [] : columnFilters,
      grouping,
      expanded,
    },

    onRowSelectionChange: setRowSelection,
    onPaginationChange,
    onSortingChange,
    onColumnFiltersChange,
    onColumnVisibilityChange: setColumnVisibility,
    onGroupingChange,
    onExpandedChange,

    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: enableAdvancedFilter ? undefined : getFilteredRowModel(),
    getPaginationRowModel: isInfiniteMode ? undefined : getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getGroupedRowModel: getGroupedRowModel(),
    getExpandedRowModel: getExpandedRowModel(),

    getFacetedRowModel: enableAdvancedFilter ? undefined : getFacetedRowModel(),
    getFacetedUniqueValues: enableAdvancedFilter ? undefined : getFacetedUniqueValues(),

    manualPagination: true,
    manualSorting: true,
    manualFiltering: true,
  })

  return { 
    table,
    // 무한 스크롤 정보
    infiniteScroll: infiniteMeta,
    // 모드 정보
    isInfiniteMode,
    effectivePageSize,
    // 페이지 크기 변경 핸들러
    handlePageSizeChange,
    // URL 상태 관리 함수들
    urlState: {
      search,
      setSearch,
      filters: parsedFilters,
      setFilters: (newFilters: any[]) => setFilters(JSON.stringify(newFilters)),
      joinOperator,
      setJoinOperator,
    }
  }
}