import { For, Show, createEffect, createSignal, on, 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 { InfoTip } from "@/components/ui/info-tip"; import { cn } from "@/lib/cn"; import { createMediaQuery } from "@/lib/create-media-query"; import { COMPACT_SCREEN_QUERY, createResponsivePageSize } from "@/lib/create-page-size"; import { createScrollRestore } from "@/lib/scroll-restore"; import { createTablePreferences } from "@/lib/table-preferences"; import { createUrlPageIndex, createUrlParam, createUrlString, decodeSort, encodeSort, listParamKeys } from "@/lib/url-state"; 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 column that only matters on a wide table). */ hideInCards?: boolean; /** * A note that explains this column (what fills it, a limit behind it). * Renders a circled "i" after the header label that shows the text on * hover, focus and tap — instead of a line kept on screen above the table. */ headerInfo?: string; } } 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; /** The size the caller actually fetched — pass a `createResponsivePageSize` accessor's value. */ pageSize: number; total: number; onPageChange: (pageIndex: number) => void; }; /** * Fetch-as-you-scroll: `data` holds the rows loaded so far and the table * asks for the next page (`onLoadMore`) as the reader nears its end. Pair * with `createInfiniteList` (lib/infinite-list); search must reach the * server through `onSearchInput`, and sorting is off (the backend takes no * sort parameter, so a header sort would order the loaded rows alone). */ infinite?: { hasMore: boolean; loading: boolean; total: number; onLoadMore: () => 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; /** Reports the rows on the rendered page after paging, search, or sorting changes. */ onPageRowsChange?: (rows: TData[]) => void; onSearchInput?: (value: string) => void; /** Rows per page on a wide screen; client tables use fewer on phones. */ 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; /** * Keep search, page and sort in the URL (`?q=`, `?page=`, `?sort=`) so Back * and a reload restore them. A string prefixes the keys (`?roster.q=`) for * a page with more than one list. Needs a router; only the search the table * owns (`searchPredicate` / `filterColumn`) is stored — a caller passing * `searchValue` / `onSearchInput` keeps its own. */ urlState?: boolean | string; /** Back to the top of the list whenever this changes — pass the caller's own filters. */ pageResetKey?: unknown; /** * The caller's own filters narrow the list. An empty result then offers * `onClearFilters` instead of the "nothing here yet" message. */ filtersActive?: boolean; onClearFilters?: () => void; }; 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; /** Start fetching the next server page this far before the list's end comes into view. */ const REVEAL_MARGIN_PX = 600; export function DataTable(props: DataTableProps) { const t = useT(); const paginationEnabled = props.enablePagination ?? true; const prefs = createTablePreferences(props.storageKey); // Read once: a table either keeps its state in the URL or it does not. const urlKeys = props.urlState ? listParamKeys(typeof props.urlState === "string" ? props.urlState : undefined) : null; const [sorting, setSortingState] = urlKeys ? createUrlParam(urlKeys.sort, { parse: decodeSort, serialize: encodeSort }) : createSignal([]); const [otherColumnFilters, setOtherColumnFilters] = createSignal([]); const clientPageSize = createResponsivePageSize(props.pageSize ?? 10); const [clientPageIndex, setClientPageIndex] = urlKeys && !props.manualPagination && !props.infinite ? createUrlPageIndex(urlKeys.page) : createSignal(0); const pagination = (): PaginationState => ({ pageIndex: clientPageIndex(), pageSize: clientPageSize() }); createEffect(on(clientPageSize, () => setClientPageIndex(0), { defer: true })); createEffect(on(() => props.pageResetKey, () => setClientPageIndex(0), { defer: true })); // The search box's text when the table owns it — the `searchPredicate` // query, or the `filterColumn` filter value. const [search, setSearch] = urlKeys && props.searchValue === undefined && !props.onSearchInput ? createUrlString(urlKeys.q) : createSignal(""); const searchValue = () => props.searchValue ?? search(); // The filterColumn filter is the search signal; any other column filter // stays local. const columnFilters = (): ColumnFiltersState => { const column = props.filterColumn; const query = search(); if (!column || props.searchPredicate || props.onSearchInput || !query) return otherColumnFilters(); return [...otherColumnFilters().filter((filter) => filter.id !== column), { id: column, value: query }]; }; const setColumnFilters = (next: ColumnFiltersState) => { const column = props.filterColumn; if (!column || props.searchPredicate || props.onSearchInput) { setOtherColumnFilters(next); return; } const own = next.find((filter) => filter.id === column); setSearch(typeof own?.value === "string" ? own.value : ""); setOtherColumnFilters(next.filter((filter) => filter.id !== column)); setClientPageIndex(0); }; // A new sort order is a new list: start again from its top. const setSorting = (next: SortingState) => { setSortingState(next); setClientPageIndex(0); }; // 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 || props.infinite); 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 && !props.infinite ? { getPaginationRowModel: getPaginationRowModel() } : {}), autoResetPageIndex: false, onSortingChange: (updater) => setSorting(resolveUpdater(updater, sorting())), onColumnFiltersChange: (updater) => setColumnFilters(resolveUpdater(updater, columnFilters())), onColumnVisibilityChange: (updater) => prefs.setVisibility(resolveUpdater(updater, prefs.preferences().visibility)), onPaginationChange: (updater) => setClientPageIndex(resolveUpdater(updater, pagination()).pageIndex), state: { get sorting() { return sorting(); }, get columnFilters() { return columnFilters(); }, get columnVisibility() { return prefs.preferences().visibility; }, get pagination(): PaginationState { return props.manualPagination ? { pageIndex: props.manualPagination.pageIndex, pageSize: props.manualPagination.pageSize } : props.infinite ? { pageIndex: 0, pageSize: Number.MAX_SAFE_INTEGER } : 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; // Headers stay centred; body cells read from the left edge. System columns // (row actions, checkboxes) keep their controls centred under the header. const isSystemColumnId = (columnId: string) => ["actions", "update", "select"].includes(columnId); const alignOf = (column: Column) => isSystemColumnId(column.id) ? "center" as const : "left" as const; // Cell renderers written for the old centred layout carry their own // mx-auto / justify-center / text-center on their root; pull those to the // start. Direct children only: deeper centring (avatar initials, icon // buttons) is the widget's own layout, not the column's. const leftCellClass = (column: Column) => isSystemColumnId(column.id) ? undefined : "[&>.mx-auto]:mx-0 [&>.justify-center]:justify-start [&>.text-center]:text-left"; 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, ); // The table scrolls sideways only once the frame is narrower than every // column at its floor: a column that declares `minSize` may shrink to it, // one that does not keeps its `size`. Sizing the table by `size` alone // made a tablet scroll a table that fit, and slid the last data column // under the sticky action column. const minTableWidth = () => table.getVisibleLeafColumns().reduce( (total, column) => total + (stickyRightLocked(column.id) ? 110 : Math.min(column.getSize(), column.columnDef.minSize ?? column.getSize())), 0, ); const columnWidth = (column: Column) => { if (stickyRightLocked(column.id)) return "110px"; const total = dataColumnsWidth(); if (total === 0) return `${column.getSize()}px`; // A plain percentage: Chrome treats a calc() that mixes % and px on a // table column as auto, which split every table into equal columns and // ignored each column's size. The shares sum to 100% beside the fixed // 110px action column; the fixed layout scales them into what is left. return `${(column.getSize() / total) * 100}%`; }; const compactScreen = createMediaQuery(COMPACT_SCREEN_QUERY); const useCards = () => (props.mobileLayout ?? "cards") === "cards" && compactScreen(); // Cards print every visible column as a label/value pair, so a column picker // there only hides lines; on phones it is one more control for nothing. const showColumnMenu = () => (props.enableColumnVisibility ?? true) && hideableColumns().length > 0 && !useCards(); 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; // Toolbar controls — search, filters, actions, "Sütunlar" — are one pill // shape and one height on every page: touch-sized (h-10) below `sm` and on touch screens, h-8 // above. Page actions arrive as plain Buttons (size="sm" is 26px), so the // slot sizes them rather than trusting each page to. const TOOLBAR_ACTIONS = "[&_button]:h-10 [&_button]:rounded-full [&_button]:px-3.5 [&_button]:text-[13px] sm:[&_button]:h-8 touch:[&_button]:h-10 [&_a]:h-10 [&_a]:rounded-full [&_a]:px-3.5 [&_a]:text-[13px] sm:[&_a]:h-8 touch:[&_a]:h-10"; const pageCount = () => props.manualPagination ? Math.max(1, Math.ceil(props.manualPagination.total / props.manualPagination.pageSize)) : table.getPageCount(); const pageIndex = () => props.manualPagination?.pageIndex ?? clientPageIndex(); const pageSize = () => props.manualPagination?.pageSize ?? clientPageSize(); const totalRows = () => props.manualPagination?.total ?? props.infinite?.total ?? table.getFilteredRowModel().rows.length; const setPageIndex = (next: number) => { if (props.manualPagination) props.manualPagination.onPageChange(next); else setClientPageIndex(next); }; createEffect(() => { if (props.manualPagination || props.infinite || !paginationEnabled) return; const rows = table.getFilteredRowModel().rows.length; if (rows === 0) return; const last = Math.max(0, Math.ceil(rows / clientPageSize()) - 1); if (clientPageIndex() > last) setClientPageIndex(last); }); const visibleRows = () => table.getRowModel().rows; createEffect(on(visibleRows, (rows) => props.onPageRowsChange?.(rows.map((row) => row.original)))); let sentinel: HTMLDivElement | undefined; const observing = typeof IntersectionObserver !== "undefined"; const nearEnd = () => !!sentinel && sentinel.getBoundingClientRect().top < window.innerHeight + REVEAL_MARGIN_PX; const loadMore = () => { if (!nearEnd()) return; const infinite = props.infinite; if (infinite?.hasMore && !infinite.loading) infinite.onLoadMore(); }; createEffect(() => { if (!props.infinite || !observing) return; const node = sentinel; if (!node) return; const observer = new IntersectionObserver((entries) => { if (entries.some((entry) => entry.isIntersecting)) loadMore(); }, { rootMargin: `0px 0px ${REVEAL_MARGIN_PX}px 0px` }); observer.observe(node); onCleanup(() => observer.disconnect()); }); // Same for a fetched page: once it lands, a short page may leave the end // in view, so ask for the next one straight away. createEffect(on(() => props.infinite?.loading, (busy) => { if (busy === false && observing) queueMicrotask(loadMore); }, { defer: true })); const scrollKey = typeof window === "undefined" || props.infinite || props.manualPagination ? null : `${window.location.pathname}:${props.storageKey ?? props.title ?? ""}:${urlKeys?.page ?? "page"}`; createScrollRestore(scrollKey, () => visibleRows().length > 0); const searchFieldValue = () => { if (props.onSearchInput || props.searchPredicate || props.filterColumn) return searchValue(); return ""; }; const handleSearch = (value: string) => { if (props.onSearchInput) props.onSearchInput(value); else setSearch(value); setPageIndex(0); }; const isInteractiveTarget = (target: EventTarget | null, row: EventTarget | null) => { if (!(target instanceof Element)) return false; // Solid bubbles a portalled element's events through its owner, so a pick // in a row's action menu (rendered in a portal) reaches the row too; it is // not a click on the row. if (row instanceof Node && !row.contains(target)) return true; const interactive = target.closest("button,a,input,select,textarea,[role='button']"); return interactive != null && interactive !== row; }; // A search or filter that matches nothing is not an empty list: say what // was asked for and offer the way back, instead of "nothing here yet". const activeQuery = () => searchFieldValue().trim(); const narrowed = () => activeQuery() !== "" || props.filtersActive === true; const clearNarrowing = () => { if (activeQuery()) handleSearch(""); if (props.filtersActive) props.onClearFilters?.(); }; const emptyContent = () => ( {props.empty ?? t("common.noResults")} } >
{activeQuery() ? t("common.noMatchesFor", { query: activeQuery() }) : t("common.noFilterMatches")}
); const headerLabel = (columnId: string) => { const header = table.getFlatHeaders().find((candidate) => candidate.column.id === columnId); return header ? flexRender(header.column.columnDef.header, header.getContext()) : columnId; }; // Screen readers hear the order only through aria-sort on the header cell. const ariaSort = (column: Column) => { if (!sortingEnabled() || !column.getCanSort()) return undefined; const sorted = column.getIsSorted(); return sorted === "asc" ? "ascending" : sorted === "desc" ? "descending" : "none"; }; // The info icon sits beside the label, never inside the sort button: a // button in a button is invalid, and opening the note must not sort. const headerInfoTip = (column: Column) => ( {(text) => } ); const renderHeader = (header: ReturnType[number]["headers"][number]) => { const content = flexRender(header.column.columnDef.header, header.getContext()); if (!sortingEnabled() || !header.column.getCanSort()) { return ( {content}}> {content} {headerInfoTip(header.column)} ); } const sorted = () => header.column.getIsSorted(); const sortButton = () => ( ); return ( {sortButton()} {headerInfoTip(header.column)} ); }; return (

{props.title}

{props.description}

{props.actions}
{/* One wrapping row, ordered by width. Phones: search and actions share the first line, filters get a line of their own that scrolls sideways instead of stacking one control per line. From `lg`: search, filters, then actions pushed to the right edge. Controls are touch-sized (h-10) below `sm` and compact (h-8) above it. */} {/* Always a card when sectioned, even when "Sütunlar" is its only control, so every list page's toolbar reads the same. */}
{props.filters}
{/* Beside the search the actions keep their own width (the search out-grows them 100:1). A label too long to fit there wraps to a line of its own, where the sole grower takes the full row and the button stretches instead of hanging off the right edge. */}
{props.actions}
    0} fallback={
  • {emptyContent()}
  • } > {(row, rowIndex) => { 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"); // A "-" line only makes a phone card taller: leave out fields // with no value. Display columns draw themselves from // row.original, so they have no value to test and always stay. const details = () => body().slice(1).filter((cell) => cell.column.accessorFn == null || (cell.getValue() != null && cell.getValue() !== "")); 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())}
    {/* The row menu shrinks to its ⋮ glyph here — the word beside it cost the title a third of the card width. */} {(cell) =>
    {flexRender(cell().column.columnDef.cell, cell().getContext())}
    }
    0}> {/* Two fields per line, label over value: a label/value row per field made every card as tall as its column count. Cells are written for a centred table column, so the card pulls their content back to the left, and a status pill sized for that column's width shrinks back to its own label. */}
    {(cell) => (
    {/* A column note shows on the first card only: once per list, like the table header it stands in for. */}
    {headerLabel(cell.column.id)} {headerInfoTip(cell.column)}
    {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 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 ( { if (isSystemColumn) return; const el = event.currentTarget; const clipped = [el, ...el.querySelectorAll("*")].some((node) => node.scrollWidth > node.clientWidth + 1); const text = el.textContent?.trim() ?? ""; if (clipped && text) el.title = text; else el.removeAttribute("title"); }} > —}> {flexRender(cell.column.columnDef.cell, cell.getContext())} ); }} )}
0}> 0}> {/* One block, so the parent's space-y gap is paid once: the sentinel and the count as siblings put two gaps under the scroll hint. */}
); } 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()); }); // The hint sits under the frame, not floated inside it: pinned to the // frame's bottom edge it covered the last row's action button. 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 ( {() => ( )} {() => ( {() => ( )} )}
); }