"use client"; import { type ColumnFiltersState, type FilterFn, getCoreRowModel, getExpandedRowModel, getFacetedRowModel, getFilteredRowModel, getPaginationRowModel, getSortedRowModel, type PaginationState, type SortingFn, type SortingState, useReactTable, type VisibilityState, } from "@tanstack/react-table"; import * as React from "react"; import { localeSortingFn } from "./faceted-filter-fn"; import type { DataTableProps } from "./types"; function getNestedValue(obj: TData, path: string): unknown { let current: unknown = obj; for (const key of path.split(".")) { if (current && typeof current === "object" && key in current) { current = (current as Record)[key]; } else { return undefined; } } return current; } let refSeq = 0; const refKeys = new WeakMap(); /** key สำหรับเทียบค่า: JSON ถ้าได้ ไม่งั้นใช้ตัวอ้างอิงของ object */ function stableKey(value: unknown): string | undefined { if (value === undefined) return undefined; try { return JSON.stringify(value); } catch { if (value && typeof value === "object") { let k = refKeys.get(value); if (!k) { k = `ref:${++refSeq}`; refKeys.set(value, k); } return k; } return String(value); } } function defaultRowId(row: T, index: number, parent?: { id: string }): string { const id = (row as { id?: unknown } | null)?.id; if (typeof id === "string" || typeof id === "number") return parent ? `${parent.id}.${id}` : String(id); return parent ? `${parent.id}.${index}` : String(index); } export function useDataTable({ columns, data, initialVisibility = {}, globalFilterFn, globalFilterKeys, getFacetedUniqueValues: getFacetedUniqueValuesProp, initialColumnFilters = [], columnFilters: columnFiltersProp, getSubRows, getRowId, initialPageSize = 25, meta, initialState, pageCount, rowCount, pagination: paginationProp, sorting: sortingProp, globalFilter: globalFilterProp, onGlobalFilterChange, manualPagination, manualSorting, manualFiltering, onPaginationChange, onSortingChange, onColumnFiltersChange, enableColumnResizing = false, enableRowSelection = true, }: DataTableProps) { const [rowSelection, setRowSelection] = React.useState({}); const [columnVisibility, setColumnVisibility] = React.useState(initialVisibility); const [columnFilters, setColumnFilters] = React.useState( columnFiltersProp ?? initialColumnFilters, ); // Sync with prop if provided — เทียบด้วยค่าเหมือน sorting/pagination: ผู้เรียกมักส่ง array literal ใหม่ทุก render // ถ้าผูกกับตัวอ้างอิง effect จะรันทุก render → render ซ้ำ + ล้าง memo ของ row model + ทับตัวกรองที่ผู้ใช้เพิ่งเลือก // ใช้ key แค่ตัดสินว่า "เปลี่ยนจริงไหม" แต่ตั้ง state เป็นค่าจริงจาก prop (Date/Set ฯลฯ ไม่กลายเป็น string) // ค่าที่ stringify ไม่ได้ (BigInt, วงอ้างอิง) ถอยไปเทียบด้วยตัวอ้างอิงแทน throw ตอน render const columnFiltersKey = stableKey(columnFiltersProp); const columnFiltersPropRef = React.useRef(columnFiltersProp); columnFiltersPropRef.current = columnFiltersProp; React.useEffect(() => { if (columnFiltersKey === undefined) return; const next = columnFiltersPropRef.current; if (next) setColumnFilters((current) => (stableKey(current) === columnFiltersKey ? current : next)); }, [columnFiltersKey]); const [sorting, setSorting] = React.useState( () => sortingProp ?? (initialState?.sorting as SortingState | undefined) ?? [], ); // Sync with prop if provided — เทียบด้วยค่าเหมือน pagination ด้วยเหตุผลเดียวกัน const sortingKey = sortingProp ? JSON.stringify(sortingProp) : undefined; React.useEffect(() => { if (sortingKey === undefined) return; setSorting((current) => JSON.stringify(current) === sortingKey ? current : JSON.parse(sortingKey), ); }, [sortingKey]); const [globalFilter, setGlobalFilter] = React.useState( globalFilterProp ?? (initialState?.globalFilter as string) ?? "", ); // Sync with prop if provided React.useEffect(() => { if (globalFilterProp !== undefined) { setGlobalFilter(globalFilterProp); } }, [globalFilterProp]); const [pagination, setPagination] = React.useState( paginationProp ?? { pageIndex: 0, pageSize: initialPageSize }, ); // Sync with prop if provided — กันเลขหน้าใน UI หลุดจาก state จริงที่อยู่ใน URL // // ต้องเทียบด้วยค่า ไม่ใช่ตัวอ้างอิง เพราะผู้เรียกมักส่ง object literal ใหม่ทุก render // ถ้าผูก effect ไว้กับตัว object มันจะรันทุกครั้งแล้วรีเซ็ต state ทับ // การกดเปลี่ยนหน้าที่เพิ่งเกิดขึ้นทิ้งไปก่อนที่ค่าใหม่จะกลับมาจาก server const pageIndexProp = paginationProp?.pageIndex; const pageSizeProp = paginationProp?.pageSize; React.useEffect(() => { if (pageIndexProp === undefined || pageSizeProp === undefined) return; setPagination((current) => current.pageIndex === pageIndexProp && current.pageSize === pageSizeProp ? current : { pageIndex: pageIndexProp, pageSize: pageSizeProp }, ); }, [pageIndexProp, pageSizeProp]); // Sync initialPageSize when it loads asynchronously (e.g. from user preferences) // เฉพาะตอน pagination ไม่ได้ถูกควบคุมจาก prop — ไม่งั้นจะทับ pageSize จาก URL ตอน mount const paginationControlled = paginationProp !== undefined; React.useEffect(() => { if (paginationControlled) return; setPagination((prev) => { // Only update if the size actually changed if (prev.pageSize !== initialPageSize) { return { ...prev, pageSize: initialPageSize }; } return prev; }); }, [initialPageSize, paginationControlled]); const finalGlobalFilterFn = React.useMemo(() => { if (globalFilterFn) { return globalFilterFn; } if (globalFilterKeys && globalFilterKeys.length > 0) { const generatedFn: FilterFn = (row, _columnId, filterValue) => { const search = String(filterValue).toLowerCase(); for (const key of globalFilterKeys) { const value = getNestedValue(row.original, key as string); if (value !== null && value !== undefined) { const valueAsString = String(value).toLowerCase(); if (valueAsString.includes(search)) { return true; } } } return false; }; return generatedFn; } return undefined; }, [globalFilterFn, globalFilterKeys]); // ผลกรอง/ค้น/เรียงเปลี่ยน → กลับหน้าแรก (เฉพาะแบ่งหน้าฝั่ง client — server แบ่งหน้า แอปคุมเอง) const resetPageIndex = () => { if (manualPagination) return; const updater = (prev: PaginationState) => prev.pageIndex === 0 ? prev : { ...prev, pageIndex: 0 }; setPagination(updater); onPaginationChange?.(updater); }; const table = useReactTable({ data, columns, // -1 = ไม่รู้จำนวนหน้า — ใช้เฉพาะเมื่อไม่มีทั้ง pageCount และ rowCount (มี rowCount → tanstack คำนวณเอง) pageCount: pageCount ?? (manualPagination && rowCount === undefined ? -1 : undefined), rowCount, manualPagination, // ไม่ให้ tanstack กลับหน้า 1 ทุกครั้งที่ data เปลี่ยน (แก้เซลล์/ลากเรียง/refresh) — กลับหน้า 1 เองเมื่อกรอง/ค้น/เรียง autoResetPageIndex: false, manualSorting, manualFiltering, state: { sorting, columnVisibility, rowSelection, columnFilters, globalFilter, pagination, }, enableColumnResizing, columnResizeMode: "onChange", defaultColumn: { minSize: 50, maxSize: 800, // เรียงข้อความไทยตามพจนานุกรม (เดิมเทียบรหัสอักขระ: คำขึ้นต้น เ แ โ ใ ไ ไปอยู่หลัง ฮ) — คอลัมน์ที่กำหนดเองยังทับได้ sortingFn: localeSortingFn as SortingFn, }, initialState: { pagination: { pageSize: initialPageSize, }, columnFilters: initialColumnFilters, ...initialState, }, meta, getSubRows: getSubRows, // ค่าเริ่มต้นใช้ `row.id` ถ้ามี — tanstack ใช้ลำดับแถว (index) ทำให้แถวที่เลือกไว้กลายเป็นแถวอื่นเมื่อข้อมูลเปลี่ยน // (DeleteManyButton ลบผิดรายการ) — ไม่มี id = ใช้ index เหมือนเดิม getRowId: getRowId ?? defaultRowId, getExpandedRowModel: getExpandedRowModel(), filterFromLeafRows: true, enableRowSelection, onRowSelectionChange: setRowSelection, onSortingChange: (updater) => { resetPageIndex(); setSorting(updater); if (onSortingChange) onSortingChange(updater); }, onColumnFiltersChange: (updater) => { resetPageIndex(); setColumnFilters(updater); if (onColumnFiltersChange) onColumnFiltersChange(updater); }, onColumnVisibilityChange: setColumnVisibility, onGlobalFilterChange: (updater) => { resetPageIndex(); setGlobalFilter(updater); if (onGlobalFilterChange) { // อ่านค่าปัจจุบันจาก table ไม่ใช่ closure ของ render ก่อน (พิมพ์เร็วสองตัวอักษรใน tick เดียวจะหายตัว) const current = table.getState().globalFilter as string; const next = typeof updater === "function" ? updater(current) : updater; onGlobalFilterChange((next as string) ?? ""); } }, onPaginationChange: (updater) => { setPagination(updater); if (onPaginationChange) onPaginationChange(updater); }, // Correction: To use `onPaginationChange`, we usually need to control state. // Let's create local pagination state to be robust. globalFilterFn: finalGlobalFilterFn, getCoreRowModel: getCoreRowModel(), getFilteredRowModel: getFilteredRowModel(), // server แบ่งหน้าให้แล้ว (manualPagination) → ไม่ต้องตัดซ้ำฝั่ง client getPaginationRowModel: manualPagination ? undefined : getPaginationRowModel(), getSortedRowModel: getSortedRowModel(), getFacetedRowModel: getFacetedRowModel(), getFacetedUniqueValues: getFacetedUniqueValuesProp, }); // ข้อมูลลดลงจนหน้าปัจจุบันเลยหน้าสุดท้าย (เช่น ลบรายการหน้าสุดท้ายหมด) → ไปหน้าสุดท้ายที่มี const lastPageIndex = Math.max(0, table.getPageCount() - 1); // biome-ignore lint/correctness/useExhaustiveDependencies: ตรวจเมื่อจำนวนหน้า/หน้าปัจจุบันเปลี่ยน React.useEffect(() => { // data ว่าง (ยังโหลดอยู่) ไม่ปรับ — ไม่งั้นหน้าจาก URL หายก่อนข้อมูลมา if (manualPagination || data.length === 0 || pagination.pageIndex <= lastPageIndex) return; const updater = (prev: PaginationState) => ({ ...prev, pageIndex: lastPageIndex }); setPagination(updater); onPaginationChange?.(updater); }, [lastPageIndex, pagination.pageIndex, manualPagination, data.length]); return { table, initialColumnFilters }; }