import { For, Show, createEffect, createSignal, onCleanup } from "solid-js"; import type { JSX, ParentProps } from "solid-js"; import { type Column, type ColumnDef, type ColumnFiltersState, type PaginationState, type SortingState, type Updater, createSolidTable, flexRender, getCoreRowModel, getFilteredRowModel, getPaginationRowModel, getSortedRowModel, } from "@tanstack/solid-table"; import { Illustration } from "@/components/ui/illustration"; import type { IllustrationName } from "@/lib/illustrations"; import { Button } from "@/components/ui/button"; import { DataTableSearch } from "@/components/ui/data-table-search"; import { DataTableViewMenu, type ViewMenuColumn } from "@/components/ui/data-table-view-menu"; import { TablePagination } from "@/components/ui/table-pagination"; import { IconArrowDown, IconArrowUp, IconChevronsUpDown } from "@/components/ui/icons"; import { cn } from "@/lib/cn"; import { createMediaQuery } from "@/lib/create-media-query"; import { createTablePreferences } from "@/lib/table-preferences"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { useT } from "@/stores/preferences-context"; declare module "@tanstack/solid-table" { interface ColumnMeta { headerClass?: string; cellClass?: string; label?: string; /** Header + cell horizontal alignment. Applied to both so they never drift apart. */ align?: "left" | "center" | "right"; /** Freeze this column to the left edge on horizontal scroll. */ stickyLeft?: boolean; /** Vertical divider on the given edge — separates frozen label from metric columns. */ divider?: "left" | "right"; /** Leave this column out of the phone card layout (e.g. a "yakında" placeholder). */ hideInCards?: boolean; } } export type DataTableProps = { columns: ColumnDef[]; data: TData[]; empty?: JSX.Element; /** Scene shown above `empty`; defaults to a generic empty / no-results one. */ emptyIllustration?: IllustrationName; class?: string; tableClass?: string; enableColumnVisibility?: boolean; enablePagination?: boolean; enableSorting?: boolean; filters?: JSX.Element; filterColumn?: string; filterPlaceholder?: string; /** On-focus hint under the search box naming the fields it matches. */ filterHint?: string; title?: string; description?: string; actions?: JSX.Element; manualPagination?: { pageIndex: number; pageSize: number; total: number; onPageChange: (pageIndex: number) => void; }; /** * Below the `sm` breakpoint rows render as cards (first column as the * title, actions top-right, the rest as label/value pairs) instead of a * table that scrolls sideways. "scroll" keeps the table on phones too. */ mobileLayout?: "cards" | "scroll"; onRowClick?: (row: TData) => void; onSearchInput?: (value: string) => void; pageSize?: number; searchPredicate?: (row: TData, query: string) => boolean; searchValue?: string; /** * When set, column widths / visibility / row density persist to localStorage. * Without a key the same controls remain available for the current mount. */ storageKey?: string; /** Split the title/toolbar and table into the same inner surfaces as detail pages. */ surfaceSections?: boolean; }; const resolveUpdater = (updater: Updater, old: T): T => typeof updater === "function" ? (updater as (value: T) => T)(old) : updater; const alignClass = { left: "text-left", center: "text-center", right: "text-right" } as const; export function DataTable(props: DataTableProps) { const t = useT(); const paginationEnabled = props.enablePagination ?? true; const prefs = createTablePreferences(props.storageKey); const [sorting, setSorting] = createSignal([]); const [columnFilters, setColumnFilters] = createSignal([]); const [pagination, setPagination] = createSignal({ pageIndex: 0, pageSize: props.pageSize ?? 10, }); const [search, setSearch] = createSignal(""); const searchValue = () => props.searchValue ?? search(); // Sorting is client-side only, and the backend takes no sort parameter: on // a server-paged table it would reorder the visible page alone while the // header claimed the whole list. Off there unless a caller opts in. const sortingEnabled = () => props.enableSorting ?? !props.manualPagination; const tableData = () => { const query = searchValue().trim(); if (!query || !props.searchPredicate) return props.data; return props.data.filter((row) => props.searchPredicate?.(row, query)); }; const table = createSolidTable({ defaultColumn: { size: 120, minSize: 72, maxSize: 360, }, get data() { return tableData(); }, get columns() { return props.columns; }, enableSorting: sortingEnabled(), getCoreRowModel: getCoreRowModel(), getSortedRowModel: getSortedRowModel(), getFilteredRowModel: getFilteredRowModel(), ...(paginationEnabled && !props.manualPagination ? { getPaginationRowModel: getPaginationRowModel() } : {}), onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: (updater) => prefs.setVisibility(resolveUpdater(updater, prefs.preferences().visibility)), onPaginationChange: setPagination, state: { get sorting() { return sorting(); }, get columnFilters() { return columnFilters(); }, get columnVisibility() { return prefs.preferences().visibility; }, get pagination() { return props.manualPagination ? { pageIndex: props.manualPagination.pageIndex, pageSize: props.manualPagination.pageSize } : pagination(); }, }, }); const hiddenLocked = (columnId: string) => columnId === "actions" || columnId === "update"; const stickyRightLocked = (columnId: string) => columnId === "actions" || (columnId === "update" && table.getColumn("actions") == null); const isStickyLeft = (column: Column) => column.columnDef.meta?.stickyLeft === true; const alignOf = (_column: Column) => "center" as const; const dividerClass = (column: Column) => { const divider = column.columnDef.meta?.divider; return divider === "left" ? "border-l border-border/70" : divider === "right" ? "border-r border-border/70" : undefined; }; const actionColumnClass = (columnId: string) => stickyRightLocked(columnId) ? "table-action-cell h-[45px] w-[110px] min-w-[110px] max-w-[110px] px-2 py-0 text-center whitespace-nowrap" : undefined; const stickyHeadClass = (column: Column) => isStickyLeft(column) ? "table-sticky-head-left sticky left-0 z-30" : stickyRightLocked(column.id) ? "table-sticky-head-right sticky right-0 z-30" : undefined; const stickyCellClass = (column: Column) => isStickyLeft(column) ? "table-sticky-left sticky left-0 z-10" : stickyRightLocked(column.id) ? "table-sticky-right sticky right-0 z-10" : undefined; const hideableColumns = () => table.getAllColumns().filter((column) => column.getCanHide() && !hiddenLocked(column.id)); const columnLabel = (column: Column) => { const header = column.columnDef.header; return column.columnDef.meta?.label ?? (typeof header === "string" ? header : column.id); }; const viewMenuColumns = (): ViewMenuColumn[] => hideableColumns().map((column) => ({ id: column.id, label: columnLabel(column), visible: column.getIsVisible(), toggle: (visible: boolean) => column.toggleVisibility(visible), })); const colSpan = () => Math.max(1, table.getVisibleLeafColumns().length); const dataColumnsWidth = () => table.getVisibleLeafColumns().reduce( (total, column) => total + (stickyRightLocked(column.id) ? 0 : column.getSize()), 0, ); const actionColumnsWidth = () => table.getVisibleLeafColumns().reduce( (total, column) => total + (stickyRightLocked(column.id) ? 110 : 0), 0, ); const tableWidth = () => dataColumnsWidth() + actionColumnsWidth(); const columnWidth = (column: Column) => { if (stickyRightLocked(column.id)) return "110px"; const total = dataColumnsWidth(); if (total === 0) return `${column.getSize()}px`; const share = column.getSize() / total; return `calc(${share * 100}% - ${share * actionColumnsWidth()}px)`; }; const showColumnMenu = () => (props.enableColumnVisibility ?? true) && hideableColumns().length > 0; const showSearch = () => props.searchPredicate != null || props.filterColumn != null || props.onSearchInput != null; const sectioned = () => props.surfaceSections !== false; const showHeader = () => false; const showToolbar = () => showSearch() || props.filters != null || showColumnMenu() || props.actions != null; const pageCount = () => props.manualPagination ? Math.max(1, Math.ceil(props.manualPagination.total / props.manualPagination.pageSize)) : table.getPageCount(); const pageIndex = () => props.manualPagination?.pageIndex ?? table.getState().pagination.pageIndex; const pageSize = () => props.manualPagination?.pageSize ?? table.getState().pagination.pageSize; const totalRows = () => props.manualPagination?.total ?? table.getFilteredRowModel().rows.length; const setPageIndex = (next: number) => { if (props.manualPagination) props.manualPagination.onPageChange(next); else table.setPageIndex(next); }; const searchFieldValue = () => { if (props.onSearchInput || props.searchPredicate) return searchValue(); if (props.filterColumn) return (table.getColumn(props.filterColumn)?.getFilterValue() as string) ?? ""; return ""; }; const handleSearch = (value: string) => { if (props.onSearchInput) props.onSearchInput(value); else if (props.searchPredicate) setSearch(value); else if (props.filterColumn) table.getColumn(props.filterColumn)?.setFilterValue(value); setPageIndex(0); }; const isInteractiveTarget = (target: EventTarget | null, row: EventTarget | null) => { if (!(target instanceof Element)) return false; const interactive = target.closest("button,a,input,select,textarea,[role='button']"); return interactive != null && interactive !== row; }; // A search that matches nothing is not an empty list: say so and offer the way back. const emptyContent = () => ( {props.empty ?? t("common.noResults")} } >
{t("common.noMatches")}
); const compactScreen = createMediaQuery("(max-width: 639px)"); const useCards = () => (props.mobileLayout ?? "cards") === "cards" && compactScreen(); const headerLabel = (columnId: string) => { const header = table.getFlatHeaders().find((candidate) => candidate.column.id === columnId); return header ? flexRender(header.column.columnDef.header, header.getContext()) : columnId; }; const renderHeader = (header: ReturnType[number]["headers"][number]) => { const content = flexRender(header.column.columnDef.header, header.getContext()); if (!sortingEnabled() || !header.column.getCanSort()) { return {content}; } const sorted = () => header.column.getIsSorted(); return ( ); }; return (

{props.title}

{props.description}

{props.actions}
{props.filters}
{props.actions}
    0} fallback={
  • {emptyContent()}
  • } > {(row) => { const cells = () => row.getVisibleCells().filter((cell) => cell.column.id !== "select" && !cell.column.columnDef.meta?.hideInCards); const action = () => cells().find((cell) => cell.column.id === "actions"); const body = () => cells().filter((cell) => cell.column.id !== "actions"); return (
  • { if (!props.onRowClick || isInteractiveTarget(event.target, event.currentTarget)) return; props.onRowClick(row.original); }} onKeyDown={(event) => { if (!props.onRowClick || isInteractiveTarget(event.target, event.currentTarget) || (event.key !== "Enter" && event.key !== " ")) return; event.preventDefault(); props.onRowClick(row.original); }} >
    {(first) => flexRender(first().column.columnDef.cell, first().getContext())}
    {(cell) =>
    {flexRender(cell().column.columnDef.cell, cell().getContext())}
    }
    1}>
    {(cell) => ( <>
    {headerLabel(cell.column.id)}
    -} > {flexRender(cell.column.columnDef.cell, cell.getContext())}
    )}
  • ); }}
{/* No inner padding: the header row sits flush on the card's top edge. A padded frame left it floating inside the card, and the sticky header then pinned below that padding while rows scrolled through the gap above it. */} {(column) => } {(headerGroup) => ( {(header) => ( {renderHeader(header)} )} )} 0} fallback={ {emptyContent()} } > {(row) => ( { if (!props.onRowClick || isInteractiveTarget(event.target, event.currentTarget)) return; props.onRowClick(row.original); }} onKeyDown={(event) => { if (!props.onRowClick || isInteractiveTarget(event.target, event.currentTarget) || (event.key !== "Enter" && event.key !== " ")) return; event.preventDefault(); props.onRowClick(row.original); }} > {(cell) => { const val = cell.getValue(); const isText = typeof val === "string" || typeof val === "number"; const isSystemColumn = ["actions", "update", "select"].includes(cell.column.id); // A display column (no accessorFn/accessorKey) has no // value to be empty — getValue() is always undefined — // so it must render its own `cell`, or a column that // draws itself from row.original silently shows "-". const isDisplayColumn = cell.column.accessorFn == null; const isEmpty = !isSystemColumn && !isDisplayColumn && (val == null || val === ""); return ( -}> {flexRender(cell.column.columnDef.cell, cell.getContext())} ); }} )}
0}>
); } export function DataTableFrame(props: ParentProps<{ class?: string }>) { const t = useT(); let frame: HTMLDivElement | undefined; const [scrollable, setScrollable] = createSignal(false); const checkOverflow = () => setScrollable(!!frame && frame.scrollWidth > frame.clientWidth + 2); createEffect(() => { queueMicrotask(checkOverflow); if (typeof ResizeObserver === "undefined" || !frame) return; const observer = new ResizeObserver(checkOverflow); observer.observe(frame); onCleanup(() => observer.disconnect()); }); return (
{props.children}
); } export function DataTableEmpty(props: ParentProps<{ class?: string }>) { return (
{props.children}
); } export function DataTableSkeleton(props: { rows?: number; columns?: number }) { const rows = () => Array.from({ length: props.rows ?? 6 }); const columns = () => Array.from({ length: props.columns ?? 5 }); return ( {() => ( )} {() => ( {() => ( )} )}
); }