hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits
| 1 | import { For, Show, createEffect, createSignal, onCleanup } from "solid-js"; |
| 2 | import type { JSX, ParentProps } from "solid-js"; |
| 3 | import { |
| 4 | type Column, |
| 5 | type ColumnDef, |
| 6 | type ColumnFiltersState, |
| 7 | type PaginationState, |
| 8 | type SortingState, |
| 9 | type Updater, |
| 10 | createSolidTable, |
| 11 | flexRender, |
| 12 | getCoreRowModel, |
| 13 | getFilteredRowModel, |
| 14 | getPaginationRowModel, |
| 15 | getSortedRowModel, |
| 16 | } from "@tanstack/solid-table"; |
| 17 | import { Illustration } from "@/components/ui/illustration"; |
| 18 | import type { IllustrationName } from "@/lib/illustrations"; |
| 19 | import { Button } from "@/components/ui/button"; |
| 20 | import { DataTableSearch } from "@/components/ui/data-table-search"; |
| 21 | import { DataTableViewMenu, type ViewMenuColumn } from "@/components/ui/data-table-view-menu"; |
| 22 | import { TablePagination } from "@/components/ui/table-pagination"; |
| 23 | import { IconArrowDown, IconArrowUp, IconChevronsUpDown } from "@/components/ui/icons"; |
| 24 | import { cn } from "@/lib/cn"; |
| 25 | import { createMediaQuery } from "@/lib/create-media-query"; |
| 26 | import { createTablePreferences } from "@/lib/table-preferences"; |
| 27 | import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; |
| 28 | import { useT } from "@/stores/preferences-context"; |
| 29 | |
| 30 | declare module "@tanstack/solid-table" { |
| 31 | interface ColumnMeta<TData, TValue> { |
| 32 | headerClass?: string; |
| 33 | cellClass?: string; |
| 34 | label?: string; |
| 35 | /** Header + cell horizontal alignment. Applied to both so they never drift apart. */ |
| 36 | align?: "left" | "center" | "right"; |
| 37 | /** Freeze this column to the left edge on horizontal scroll. */ |
| 38 | stickyLeft?: boolean; |
| 39 | /** Vertical divider on the given edge — separates frozen label from metric columns. */ |
| 40 | divider?: "left" | "right"; |
| 41 | /** Leave this column out of the phone card layout (e.g. a "yakında" placeholder). */ |
| 42 | hideInCards?: boolean; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | export type DataTableProps<TData, TValue = unknown> = { |
| 47 | columns: ColumnDef<TData, TValue>[]; |
| 48 | data: TData[]; |
| 49 | empty?: JSX.Element; |
| 50 | /** Scene shown above `empty`; defaults to a generic empty / no-results one. */ |
| 51 | emptyIllustration?: IllustrationName; |
| 52 | class?: string; |
| 53 | tableClass?: string; |
| 54 | enableColumnVisibility?: boolean; |
| 55 | enablePagination?: boolean; |
| 56 | enableSorting?: boolean; |
| 57 | filters?: JSX.Element; |
| 58 | filterColumn?: string; |
| 59 | filterPlaceholder?: string; |
| 60 | /** On-focus hint under the search box naming the fields it matches. */ |
| 61 | filterHint?: string; |
| 62 | title?: string; |
| 63 | description?: string; |
| 64 | actions?: JSX.Element; |
| 65 | manualPagination?: { |
| 66 | pageIndex: number; |
| 67 | pageSize: number; |
| 68 | total: number; |
| 69 | onPageChange: (pageIndex: number) => void; |
| 70 | }; |
| 71 | /** |
| 72 | * Below the `sm` breakpoint rows render as cards (first column as the |
| 73 | * title, actions top-right, the rest as label/value pairs) instead of a |
| 74 | * table that scrolls sideways. "scroll" keeps the table on phones too. |
| 75 | */ |
| 76 | mobileLayout?: "cards" | "scroll"; |
| 77 | onRowClick?: (row: TData) => void; |
| 78 | onSearchInput?: (value: string) => void; |
| 79 | pageSize?: number; |
| 80 | searchPredicate?: (row: TData, query: string) => boolean; |
| 81 | searchValue?: string; |
| 82 | /** |
| 83 | * When set, column widths / visibility / row density persist to localStorage. |
| 84 | * Without a key the same controls remain available for the current mount. |
| 85 | */ |
| 86 | storageKey?: string; |
| 87 | /** Split the title/toolbar and table into the same inner surfaces as detail pages. */ |
| 88 | surfaceSections?: boolean; |
| 89 | }; |
| 90 | |
| 91 | const resolveUpdater = <T,>(updater: Updater<T>, old: T): T => |
| 92 | typeof updater === "function" ? (updater as (value: T) => T)(old) : updater; |
| 93 | |
| 94 | const alignClass = { left: "text-left", center: "text-center", right: "text-right" } as const; |
| 95 | |
| 96 | export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, TValue>) { |
| 97 | const t = useT(); |
| 98 | const paginationEnabled = props.enablePagination ?? true; |
| 99 | const prefs = createTablePreferences(props.storageKey); |
| 100 | const [sorting, setSorting] = createSignal<SortingState>([]); |
| 101 | const [columnFilters, setColumnFilters] = createSignal<ColumnFiltersState>([]); |
| 102 | const [pagination, setPagination] = createSignal<PaginationState>({ |
| 103 | pageIndex: 0, |
| 104 | pageSize: props.pageSize ?? 10, |
| 105 | }); |
| 106 | const [search, setSearch] = createSignal(""); |
| 107 | const searchValue = () => props.searchValue ?? search(); |
| 108 | // Sorting is client-side only, and the backend takes no sort parameter: on |
| 109 | // a server-paged table it would reorder the visible page alone while the |
| 110 | // header claimed the whole list. Off there unless a caller opts in. |
| 111 | const sortingEnabled = () => props.enableSorting ?? !props.manualPagination; |
| 112 | const tableData = () => { |
| 113 | const query = searchValue().trim(); |
| 114 | if (!query || !props.searchPredicate) return props.data; |
| 115 | return props.data.filter((row) => props.searchPredicate?.(row, query)); |
| 116 | }; |
| 117 | const table = createSolidTable({ |
| 118 | defaultColumn: { |
| 119 | size: 120, |
| 120 | minSize: 72, |
| 121 | maxSize: 360, |
| 122 | }, |
| 123 | get data() { |
| 124 | return tableData(); |
| 125 | }, |
| 126 | get columns() { |
| 127 | return props.columns; |
| 128 | }, |
| 129 | enableSorting: sortingEnabled(), |
| 130 | getCoreRowModel: getCoreRowModel(), |
| 131 | getSortedRowModel: getSortedRowModel(), |
| 132 | getFilteredRowModel: getFilteredRowModel(), |
| 133 | ...(paginationEnabled && !props.manualPagination ? { getPaginationRowModel: getPaginationRowModel() } : {}), |
| 134 | onSortingChange: setSorting, |
| 135 | onColumnFiltersChange: setColumnFilters, |
| 136 | onColumnVisibilityChange: (updater) => |
| 137 | prefs.setVisibility(resolveUpdater(updater, prefs.preferences().visibility)), |
| 138 | onPaginationChange: setPagination, |
| 139 | state: { |
| 140 | get sorting() { |
| 141 | return sorting(); |
| 142 | }, |
| 143 | get columnFilters() { |
| 144 | return columnFilters(); |
| 145 | }, |
| 146 | get columnVisibility() { |
| 147 | return prefs.preferences().visibility; |
| 148 | }, |
| 149 | get pagination() { |
| 150 | return props.manualPagination |
| 151 | ? { pageIndex: props.manualPagination.pageIndex, pageSize: props.manualPagination.pageSize } |
| 152 | : pagination(); |
| 153 | }, |
| 154 | }, |
| 155 | }); |
| 156 | const hiddenLocked = (columnId: string) => columnId === "actions" || columnId === "update"; |
| 157 | const stickyRightLocked = (columnId: string) => |
| 158 | columnId === "actions" || (columnId === "update" && table.getColumn("actions") == null); |
| 159 | const isStickyLeft = (column: Column<TData, unknown>) => column.columnDef.meta?.stickyLeft === true; |
| 160 | const alignOf = (_column: Column<TData, unknown>) => "center" as const; |
| 161 | const dividerClass = (column: Column<TData, unknown>) => { |
| 162 | const divider = column.columnDef.meta?.divider; |
| 163 | return divider === "left" ? "border-l border-border/70" : divider === "right" ? "border-r border-border/70" : undefined; |
| 164 | }; |
| 165 | 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; |
| 166 | const stickyHeadClass = (column: Column<TData, unknown>) => |
| 167 | isStickyLeft(column) |
| 168 | ? "table-sticky-head-left sticky left-0 z-30" |
| 169 | : stickyRightLocked(column.id) |
| 170 | ? "table-sticky-head-right sticky right-0 z-30" |
| 171 | : undefined; |
| 172 | const stickyCellClass = (column: Column<TData, unknown>) => |
| 173 | isStickyLeft(column) |
| 174 | ? "table-sticky-left sticky left-0 z-10" |
| 175 | : stickyRightLocked(column.id) |
| 176 | ? "table-sticky-right sticky right-0 z-10" |
| 177 | : undefined; |
| 178 | const hideableColumns = () => table.getAllColumns().filter((column) => column.getCanHide() && !hiddenLocked(column.id)); |
| 179 | const columnLabel = (column: Column<TData, unknown>) => { |
| 180 | const header = column.columnDef.header; |
| 181 | return column.columnDef.meta?.label ?? (typeof header === "string" ? header : column.id); |
| 182 | }; |
| 183 | const viewMenuColumns = (): ViewMenuColumn[] => |
| 184 | hideableColumns().map((column) => ({ |
| 185 | id: column.id, |
| 186 | label: columnLabel(column), |
| 187 | visible: column.getIsVisible(), |
| 188 | toggle: (visible: boolean) => column.toggleVisibility(visible), |
| 189 | })); |
| 190 | const colSpan = () => Math.max(1, table.getVisibleLeafColumns().length); |
| 191 | const dataColumnsWidth = () => |
| 192 | table.getVisibleLeafColumns().reduce( |
| 193 | (total, column) => total + (stickyRightLocked(column.id) ? 0 : column.getSize()), |
| 194 | 0, |
| 195 | ); |
| 196 | const actionColumnsWidth = () => |
| 197 | table.getVisibleLeafColumns().reduce( |
| 198 | (total, column) => total + (stickyRightLocked(column.id) ? 110 : 0), |
| 199 | 0, |
| 200 | ); |
| 201 | const tableWidth = () => dataColumnsWidth() + actionColumnsWidth(); |
| 202 | const columnWidth = (column: Column<TData, unknown>) => { |
| 203 | if (stickyRightLocked(column.id)) return "110px"; |
| 204 | const total = dataColumnsWidth(); |
| 205 | if (total === 0) return `${column.getSize()}px`; |
| 206 | const share = column.getSize() / total; |
| 207 | return `calc(${share * 100}% - ${share * actionColumnsWidth()}px)`; |
| 208 | }; |
| 209 | const showColumnMenu = () => (props.enableColumnVisibility ?? true) && hideableColumns().length > 0; |
| 210 | const showSearch = () => props.searchPredicate != null || props.filterColumn != null || props.onSearchInput != null; |
| 211 | const sectioned = () => props.surfaceSections !== false; |
| 212 | const showHeader = () => false; |
| 213 | const showToolbar = () => showSearch() || props.filters != null || showColumnMenu() || props.actions != null; |
| 214 | const pageCount = () => props.manualPagination ? Math.max(1, Math.ceil(props.manualPagination.total / props.manualPagination.pageSize)) : table.getPageCount(); |
| 215 | const pageIndex = () => props.manualPagination?.pageIndex ?? table.getState().pagination.pageIndex; |
| 216 | const pageSize = () => props.manualPagination?.pageSize ?? table.getState().pagination.pageSize; |
| 217 | const totalRows = () => props.manualPagination?.total ?? table.getFilteredRowModel().rows.length; |
| 218 | const setPageIndex = (next: number) => { |
| 219 | if (props.manualPagination) props.manualPagination.onPageChange(next); |
| 220 | else table.setPageIndex(next); |
| 221 | }; |
| 222 | const searchFieldValue = () => { |
| 223 | if (props.onSearchInput || props.searchPredicate) return searchValue(); |
| 224 | if (props.filterColumn) return (table.getColumn(props.filterColumn)?.getFilterValue() as string) ?? ""; |
| 225 | return ""; |
| 226 | }; |
| 227 | const handleSearch = (value: string) => { |
| 228 | if (props.onSearchInput) props.onSearchInput(value); |
| 229 | else if (props.searchPredicate) setSearch(value); |
| 230 | else if (props.filterColumn) table.getColumn(props.filterColumn)?.setFilterValue(value); |
| 231 | setPageIndex(0); |
| 232 | }; |
| 233 | const isInteractiveTarget = (target: EventTarget | null, row: EventTarget | null) => { |
| 234 | if (!(target instanceof Element)) return false; |
| 235 | const interactive = target.closest("button,a,input,select,textarea,[role='button']"); |
| 236 | return interactive != null && interactive !== row; |
| 237 | }; |
| 238 | // A search that matches nothing is not an empty list: say so and offer the way back. |
| 239 | const emptyContent = () => ( |
| 240 | <Show |
| 241 | when={searchFieldValue().trim()} |
| 242 | fallback={ |
| 243 | <div class="flex flex-col items-center gap-3"> |
| 244 | <Illustration name={props.emptyIllustration ?? "empty"} class="h-20 w-32" /> |
| 245 | <span>{props.empty ?? t("common.noResults")}</span> |
| 246 | </div> |
| 247 | } |
| 248 | > |
| 249 | <div class="flex flex-col items-center gap-3"> |
| 250 | <Illustration name="no-results" class="h-20 w-32" /> |
| 251 | <span>{t("common.noMatches")}</span> |
| 252 | <Button type="button" size="sm" variant="outline" onClick={() => handleSearch("")}> |
| 253 | {t("common.clearSearch")} |
| 254 | </Button> |
| 255 | </div> |
| 256 | </Show> |
| 257 | ); |
| 258 | const compactScreen = createMediaQuery("(max-width: 639px)"); |
| 259 | const useCards = () => (props.mobileLayout ?? "cards") === "cards" && compactScreen(); |
| 260 | const headerLabel = (columnId: string) => { |
| 261 | const header = table.getFlatHeaders().find((candidate) => candidate.column.id === columnId); |
| 262 | return header ? flexRender(header.column.columnDef.header, header.getContext()) : columnId; |
| 263 | }; |
| 264 | const renderHeader = (header: ReturnType<typeof table.getHeaderGroups>[number]["headers"][number]) => { |
| 265 | const content = flexRender(header.column.columnDef.header, header.getContext()); |
| 266 | if (!sortingEnabled() || !header.column.getCanSort()) { |
| 267 | return <span class="block truncate whitespace-nowrap text-center">{content}</span>; |
| 268 | } |
| 269 | const sorted = () => header.column.getIsSorted(); |
| 270 | return ( |
| 271 | <Button |
| 272 | type="button" |
| 273 | variant="ghost" |
| 274 | size="sm" |
| 275 | class={cn("mx-auto h-8 min-w-0 max-w-full justify-center px-2 text-center font-medium tracking-normal normal-case", sorted() && "text-foreground")} |
| 276 | onClick={() => header.column.toggleSorting(sorted() === "asc")} |
| 277 | > |
| 278 | <span class="truncate">{content}</span> |
| 279 | <Show |
| 280 | when={sorted() !== false} |
| 281 | fallback={ |
| 282 | <IconChevronsUpDown class="h-3.5 w-3.5 opacity-0 transition-opacity group-hover/head:opacity-50 group-focus-within/head:opacity-50" /> |
| 283 | } |
| 284 | > |
| 285 | <Show |
| 286 | when={sorted() === "asc"} |
| 287 | fallback={<IconArrowDown class="h-3.5 w-3.5" />} |
| 288 | > |
| 289 | <IconArrowUp class="h-3.5 w-3.5" /> |
| 290 | </Show> |
| 291 | </Show> |
| 292 | </Button> |
| 293 | ); |
| 294 | }; |
| 295 | |
| 296 | return ( |
| 297 | <div class={cn("space-y-3", props.class)}> |
| 298 | <Show when={showHeader()}> |
| 299 | <div class={cn("flex flex-wrap items-start justify-between gap-3", sectioned() && "rounded-xl border border-border-line bg-surface-base p-3 shadow-xs sm:p-4")}> |
| 300 | <div class="min-w-0"> |
| 301 | <Show when={props.title}> |
| 302 | <h2 class="truncate text-lg font-semibold tracking-tight text-foreground">{props.title}</h2> |
| 303 | </Show> |
| 304 | <Show when={props.description}> |
| 305 | <p class="mt-1 text-sm text-muted-foreground">{props.description}</p> |
| 306 | </Show> |
| 307 | </div> |
| 308 | <Show when={props.actions}> |
| 309 | <div class="flex min-w-0 flex-wrap items-center gap-2 [&_button]:rounded-md">{props.actions}</div> |
| 310 | </Show> |
| 311 | </div> |
| 312 | </Show> |
| 313 | <Show when={showToolbar()}> |
| 314 | <div class={cn("flex flex-col gap-2 lg:flex-row lg:items-center lg:justify-between", sectioned() && "rounded-xl border border-border-line bg-surface-base p-3 shadow-xs")}> |
| 315 | <div class="flex flex-1 flex-wrap items-center gap-2"> |
| 316 | <Show when={showSearch()}> |
| 317 | <DataTableSearch |
| 318 | value={searchFieldValue()} |
| 319 | onChange={handleSearch} |
| 320 | placeholder={props.filterPlaceholder ?? t("common.searchPlaceholder")} |
| 321 | hint={props.filterHint} |
| 322 | /> |
| 323 | </Show> |
| 324 | <Show when={props.filters}> |
| 325 | <div class="flex flex-wrap items-center gap-2 [&_button]:h-8 [&_button]:rounded-lg [&_button]:text-[13px] [&_select]:h-8 [&_select]:rounded-lg [&_select]:text-[13px]">{props.filters}</div> |
| 326 | </Show> |
| 327 | </div> |
| 328 | <div class="flex shrink-0 flex-wrap items-center justify-end gap-2"> |
| 329 | <Show when={props.actions}> |
| 330 | <div class="flex min-w-0 flex-wrap items-center gap-2 [&_button]:rounded-md">{props.actions}</div> |
| 331 | </Show> |
| 332 | <Show when={showColumnMenu()}> |
| 333 | <DataTableViewMenu columns={viewMenuColumns()} /> |
| 334 | </Show> |
| 335 | </div> |
| 336 | </div> |
| 337 | </Show> |
| 338 | <Show when={useCards()}> |
| 339 | <ul class="space-y-2" aria-label={props.title}> |
| 340 | <Show |
| 341 | when={table.getRowModel().rows.length > 0} |
| 342 | fallback={<li class="rounded-lg border border-border-line bg-surface-base px-4 py-8 text-center text-sm text-muted-foreground">{emptyContent()}</li>} |
| 343 | > |
| 344 | <For each={table.getRowModel().rows}> |
| 345 | {(row) => { |
| 346 | const cells = () => |
| 347 | row.getVisibleCells().filter((cell) => cell.column.id !== "select" && !cell.column.columnDef.meta?.hideInCards); |
| 348 | const action = () => cells().find((cell) => cell.column.id === "actions"); |
| 349 | const body = () => cells().filter((cell) => cell.column.id !== "actions"); |
| 350 | return ( |
| 351 | <li> |
| 352 | <div |
| 353 | role={props.onRowClick ? "button" : undefined} |
| 354 | tabIndex={props.onRowClick ? 0 : undefined} |
| 355 | class={cn( |
| 356 | "rounded-lg border border-border-line bg-surface-base p-3 text-sm", |
| 357 | props.onRowClick && "cursor-pointer outline-hidden focus-visible:ring-2 focus-visible:ring-ring active:bg-primary/6", |
| 358 | )} |
| 359 | onClick={(event) => { |
| 360 | if (!props.onRowClick || isInteractiveTarget(event.target, event.currentTarget)) return; |
| 361 | props.onRowClick(row.original); |
| 362 | }} |
| 363 | onKeyDown={(event) => { |
| 364 | if (!props.onRowClick || isInteractiveTarget(event.target, event.currentTarget) || (event.key !== "Enter" && event.key !== " ")) return; |
| 365 | event.preventDefault(); |
| 366 | props.onRowClick(row.original); |
| 367 | }} |
| 368 | > |
| 369 | <div class="flex items-start gap-2"> |
| 370 | <div class="min-w-0 flex-1 font-medium"> |
| 371 | <Show when={body()[0]}>{(first) => flexRender(first().column.columnDef.cell, first().getContext())}</Show> |
| 372 | </div> |
| 373 | <Show when={action()}>{(cell) => <div class="-my-1 shrink-0">{flexRender(cell().column.columnDef.cell, cell().getContext())}</div>}</Show> |
| 374 | </div> |
| 375 | <Show when={body().length > 1}> |
| 376 | <dl class="mt-2 grid grid-cols-[minmax(6rem,auto)_minmax(0,1fr)] gap-x-3 gap-y-1.5"> |
| 377 | <For each={body().slice(1)}> |
| 378 | {(cell) => ( |
| 379 | <> |
| 380 | <dt class="truncate text-xs text-muted-foreground">{headerLabel(cell.column.id)}</dt> |
| 381 | <dd class="min-w-0 break-words text-foreground"> |
| 382 | <Show |
| 383 | when={cell.column.accessorFn == null || (cell.getValue() != null && cell.getValue() !== "")} |
| 384 | fallback={<span class="text-muted-foreground/60">-</span>} |
| 385 | > |
| 386 | {flexRender(cell.column.columnDef.cell, cell.getContext())} |
| 387 | </Show> |
| 388 | </dd> |
| 389 | </> |
| 390 | )} |
| 391 | </For> |
| 392 | </dl> |
| 393 | </Show> |
| 394 | </div> |
| 395 | </li> |
| 396 | ); |
| 397 | }} |
| 398 | </For> |
| 399 | </Show> |
| 400 | </ul> |
| 401 | </Show> |
| 402 | <Show when={!useCards()}> |
| 403 | {/* No inner padding: the header row sits flush on the card's top edge. |
| 404 | A padded frame left it floating inside the card, and the sticky |
| 405 | header then pinned below that padding while rows scrolled through |
| 406 | the gap above it. */} |
| 407 | <DataTableFrame class={sectioned() ? "shadow-xs" : undefined}> |
| 408 | <Table |
| 409 | class={cn("data-table table-fixed", props.tableClass)} |
| 410 | style={{ width: `max(100%, ${tableWidth()}px)` }} |
| 411 | > |
| 412 | <colgroup> |
| 413 | <For each={table.getVisibleLeafColumns()}> |
| 414 | {(column) => <col style={{ width: columnWidth(column) }} />} |
| 415 | </For> |
| 416 | </colgroup> |
| 417 | <TableHeader> |
| 418 | <For each={table.getHeaderGroups()}> |
| 419 | {(headerGroup) => ( |
| 420 | <TableRow class="hover:bg-transparent"> |
| 421 | <For each={headerGroup.headers}> |
| 422 | {(header) => ( |
| 423 | <TableHead |
| 424 | colSpan={header.colSpan} |
| 425 | class={cn( |
| 426 | "group/head relative overflow-hidden", |
| 427 | dividerClass(header.column), |
| 428 | stickyHeadClass(header.column), |
| 429 | header.column.columnDef.meta?.headerClass, |
| 430 | actionColumnClass(header.column.id), |
| 431 | )} |
| 432 | style={{ width: columnWidth(header.column) }} |
| 433 | > |
| 434 | <Show when={!header.isPlaceholder}>{renderHeader(header)}</Show> |
| 435 | </TableHead> |
| 436 | )} |
| 437 | </For> |
| 438 | </TableRow> |
| 439 | )} |
| 440 | </For> |
| 441 | </TableHeader> |
| 442 | <TableBody> |
| 443 | <Show |
| 444 | when={table.getRowModel().rows.length > 0} |
| 445 | fallback={ |
| 446 | <TableRow> |
| 447 | <TableCell colSpan={colSpan()} class="py-8 text-center text-muted-foreground"> |
| 448 | {emptyContent()} |
| 449 | </TableCell> |
| 450 | </TableRow> |
| 451 | } |
| 452 | > |
| 453 | <For each={table.getRowModel().rows}> |
| 454 | {(row) => ( |
| 455 | <TableRow |
| 456 | data-state={row.getIsSelected() ? "selected" : undefined} |
| 457 | role={props.onRowClick ? "button" : undefined} |
| 458 | tabIndex={props.onRowClick ? 0 : undefined} |
| 459 | class={cn( |
| 460 | "group/row", |
| 461 | props.onRowClick && "cursor-pointer outline-hidden focus-visible:bg-primary/6 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring active:bg-primary/8", |
| 462 | )} |
| 463 | onClick={(event) => { |
| 464 | if (!props.onRowClick || isInteractiveTarget(event.target, event.currentTarget)) return; |
| 465 | props.onRowClick(row.original); |
| 466 | }} |
| 467 | onKeyDown={(event) => { |
| 468 | if (!props.onRowClick || isInteractiveTarget(event.target, event.currentTarget) || (event.key !== "Enter" && event.key !== " ")) return; |
| 469 | event.preventDefault(); |
| 470 | props.onRowClick(row.original); |
| 471 | }} |
| 472 | > |
| 473 | <For each={row.getVisibleCells()}> |
| 474 | {(cell) => { |
| 475 | const val = cell.getValue(); |
| 476 | const isText = typeof val === "string" || typeof val === "number"; |
| 477 | const isSystemColumn = ["actions", "update", "select"].includes(cell.column.id); |
| 478 | // A display column (no accessorFn/accessorKey) has no |
| 479 | // value to be empty — getValue() is always undefined — |
| 480 | // so it must render its own `cell`, or a column that |
| 481 | // draws itself from row.original silently shows "-". |
| 482 | const isDisplayColumn = cell.column.accessorFn == null; |
| 483 | const isEmpty = |
| 484 | !isSystemColumn && !isDisplayColumn && (val == null || val === ""); |
| 485 | |
| 486 | return ( |
| 487 | <TableCell |
| 488 | class={cn( |
| 489 | alignClass[alignOf(cell.column)], |
| 490 | dividerClass(cell.column), |
| 491 | stickyCellClass(cell.column), |
| 492 | cell.column.columnDef.meta?.cellClass, |
| 493 | actionColumnClass(cell.column.id), |
| 494 | )} |
| 495 | style={{ width: columnWidth(cell.column) }} |
| 496 | title={isText && !isEmpty ? String(val) : undefined} |
| 497 | > |
| 498 | <Show when={!isEmpty} fallback={<span class="text-muted-foreground/40">-</span>}> |
| 499 | {flexRender(cell.column.columnDef.cell, cell.getContext())} |
| 500 | </Show> |
| 501 | </TableCell> |
| 502 | ); |
| 503 | }} |
| 504 | </For> |
| 505 | </TableRow> |
| 506 | )} |
| 507 | </For> |
| 508 | </Show> |
| 509 | </TableBody> |
| 510 | </Table> |
| 511 | </DataTableFrame> |
| 512 | </Show> |
| 513 | <Show when={paginationEnabled && totalRows() > 0}> |
| 514 | <TablePagination |
| 515 | pageIndex={pageIndex()} |
| 516 | pageCount={pageCount()} |
| 517 | pageSize={pageSize()} |
| 518 | total={totalRows()} |
| 519 | onPageChange={setPageIndex} |
| 520 | /> |
| 521 | </Show> |
| 522 | </div> |
| 523 | ); |
| 524 | } |
| 525 | |
| 526 | export function DataTableFrame(props: ParentProps<{ class?: string }>) { |
| 527 | const t = useT(); |
| 528 | let frame: HTMLDivElement | undefined; |
| 529 | const [scrollable, setScrollable] = createSignal(false); |
| 530 | const checkOverflow = () => setScrollable(!!frame && frame.scrollWidth > frame.clientWidth + 2); |
| 531 | createEffect(() => { |
| 532 | queueMicrotask(checkOverflow); |
| 533 | if (typeof ResizeObserver === "undefined" || !frame) return; |
| 534 | const observer = new ResizeObserver(checkOverflow); |
| 535 | observer.observe(frame); |
| 536 | onCleanup(() => observer.disconnect()); |
| 537 | }); |
| 538 | return ( |
| 539 | <div ref={frame} class={cn("data-table-wrap relative", props.class)}> |
| 540 | {props.children} |
| 541 | <Show when={scrollable()}> |
| 542 | <span class="pointer-events-none sticky bottom-2 left-[calc(100%-6rem)] z-30 ml-[calc(100%-6.5rem)] inline-flex w-fit items-center gap-1 rounded-full border border-border/70 bg-surface-base/95 px-2 py-1 text-xs font-medium text-muted-foreground shadow-sm backdrop-blur" aria-hidden="true"> |
| 543 | ↔ {t("common.scrollHint")} |
| 544 | </span> |
| 545 | </Show> |
| 546 | </div> |
| 547 | ); |
| 548 | } |
| 549 | |
| 550 | export function DataTableEmpty(props: ParentProps<{ class?: string }>) { |
| 551 | return ( |
| 552 | <div class={cn("rounded-xl border border-dashed border-border-line bg-surface-overlay px-6 py-10 text-center text-sm leading-6 text-text-subtle", props.class)}> |
| 553 | {props.children} |
| 554 | </div> |
| 555 | ); |
| 556 | } |
| 557 | |
| 558 | export function DataTableSkeleton(props: { rows?: number; columns?: number }) { |
| 559 | const rows = () => Array.from({ length: props.rows ?? 6 }); |
| 560 | const columns = () => Array.from({ length: props.columns ?? 5 }); |
| 561 | return ( |
| 562 | <DataTableFrame class="animate-pulse"> |
| 563 | <table class="data-table"> |
| 564 | <thead> |
| 565 | <tr> |
| 566 | <For each={columns()}> |
| 567 | {() => ( |
| 568 | <th> |
| 569 | <div class="h-2.5 w-20 rounded-full bg-muted" /> |
| 570 | </th> |
| 571 | )} |
| 572 | </For> |
| 573 | </tr> |
| 574 | </thead> |
| 575 | <tbody> |
| 576 | <For each={rows()}> |
| 577 | {() => ( |
| 578 | <tr> |
| 579 | <For each={columns()}> |
| 580 | {() => ( |
| 581 | <td> |
| 582 | <div class="h-3 w-full max-w-32 rounded-full bg-muted/80" /> |
| 583 | </td> |
| 584 | )} |
| 585 | </For> |
| 586 | </tr> |
| 587 | )} |
| 588 | </For> |
| 589 | </tbody> |
| 590 | </table> |
| 591 | </DataTableFrame> |
| 592 | ); |
| 593 | } |