hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiBc35a83aBurak Boduroğlu4 months ago440 commits
| 1 | import { For, Show, createSignal } 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 { Button } from "@/components/ui/button"; |
| 18 | import { DataTableSearch } from "@/components/ui/data-table-search"; |
| 19 | import { DataTableViewMenu, type ViewMenuColumn } from "@/components/ui/data-table-view-menu"; |
| 20 | import { TablePagination } from "@/components/ui/table-pagination"; |
| 21 | import { IconArrowDown, IconArrowUp, IconChevronsUpDown } from "@/components/ui/icons"; |
| 22 | import { cn } from "@/lib/cn"; |
| 23 | import { createTablePreferences } from "@/lib/table-preferences"; |
| 24 | import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; |
| 25 | import { useT } from "@/stores/preferences-context"; |
| 26 | |
| 27 | declare module "@tanstack/solid-table" { |
| 28 | interface ColumnMeta<TData, TValue> { |
| 29 | headerClass?: string; |
| 30 | cellClass?: string; |
| 31 | label?: string; |
| 32 | /** Header + cell horizontal alignment. Applied to both so they never drift apart. */ |
| 33 | align?: "left" | "center" | "right"; |
| 34 | /** Freeze this column to the left edge on horizontal scroll. */ |
| 35 | stickyLeft?: boolean; |
| 36 | /** Vertical divider on the given edge — separates frozen label from metric columns. */ |
| 37 | divider?: "left" | "right"; |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | export type DataTableProps<TData, TValue = unknown> = { |
| 42 | columns: ColumnDef<TData, TValue>[]; |
| 43 | data: TData[]; |
| 44 | empty?: JSX.Element; |
| 45 | class?: string; |
| 46 | tableClass?: string; |
| 47 | enableColumnVisibility?: boolean; |
| 48 | enablePagination?: boolean; |
| 49 | enableSorting?: boolean; |
| 50 | filters?: JSX.Element; |
| 51 | filterColumn?: string; |
| 52 | filterPlaceholder?: string; |
| 53 | title?: string; |
| 54 | description?: string; |
| 55 | actions?: JSX.Element; |
| 56 | manualPagination?: { |
| 57 | pageIndex: number; |
| 58 | pageSize: number; |
| 59 | total: number; |
| 60 | onPageChange: (pageIndex: number) => void; |
| 61 | onPageSizeChange?: (pageSize: number) => void; |
| 62 | }; |
| 63 | onRowClick?: (row: TData) => void; |
| 64 | onSearchInput?: (value: string) => void; |
| 65 | pageSize?: number; |
| 66 | searchPredicate?: (row: TData, query: string) => boolean; |
| 67 | searchValue?: string; |
| 68 | /** |
| 69 | * When set, column widths / visibility / row density persist to localStorage. |
| 70 | * Without a key the same controls remain available for the current mount. |
| 71 | */ |
| 72 | storageKey?: string; |
| 73 | }; |
| 74 | |
| 75 | const resolveUpdater = <T,>(updater: Updater<T>, old: T): T => |
| 76 | typeof updater === "function" ? (updater as (value: T) => T)(old) : updater; |
| 77 | |
| 78 | const alignClass = { left: "text-left", center: "text-center", right: "text-right" } as const; |
| 79 | |
| 80 | export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, TValue>) { |
| 81 | const t = useT(); |
| 82 | const paginationEnabled = props.enablePagination ?? true; |
| 83 | const prefs = createTablePreferences(props.storageKey); |
| 84 | const [sorting, setSorting] = createSignal<SortingState>([]); |
| 85 | const [columnFilters, setColumnFilters] = createSignal<ColumnFiltersState>([]); |
| 86 | const [pagination, setPagination] = createSignal<PaginationState>({ |
| 87 | pageIndex: 0, |
| 88 | pageSize: props.pageSize ?? 10, |
| 89 | }); |
| 90 | const [search, setSearch] = createSignal(""); |
| 91 | const searchValue = () => props.searchValue ?? search(); |
| 92 | const tableData = () => { |
| 93 | const query = searchValue().trim(); |
| 94 | if (!query || !props.searchPredicate) return props.data; |
| 95 | return props.data.filter((row) => props.searchPredicate?.(row, query)); |
| 96 | }; |
| 97 | const table = createSolidTable({ |
| 98 | get data() { |
| 99 | return tableData(); |
| 100 | }, |
| 101 | get columns() { |
| 102 | return props.columns; |
| 103 | }, |
| 104 | enableSorting: props.enableSorting ?? true, |
| 105 | getCoreRowModel: getCoreRowModel(), |
| 106 | getSortedRowModel: getSortedRowModel(), |
| 107 | getFilteredRowModel: getFilteredRowModel(), |
| 108 | ...(paginationEnabled && !props.manualPagination ? { getPaginationRowModel: getPaginationRowModel() } : {}), |
| 109 | onSortingChange: setSorting, |
| 110 | onColumnFiltersChange: setColumnFilters, |
| 111 | onColumnVisibilityChange: (updater) => |
| 112 | prefs.setVisibility(resolveUpdater(updater, prefs.preferences().visibility)), |
| 113 | onPaginationChange: setPagination, |
| 114 | state: { |
| 115 | get sorting() { |
| 116 | return sorting(); |
| 117 | }, |
| 118 | get columnFilters() { |
| 119 | return columnFilters(); |
| 120 | }, |
| 121 | get columnVisibility() { |
| 122 | return prefs.preferences().visibility; |
| 123 | }, |
| 124 | get pagination() { |
| 125 | return props.manualPagination |
| 126 | ? { pageIndex: props.manualPagination.pageIndex, pageSize: props.manualPagination.pageSize } |
| 127 | : pagination(); |
| 128 | }, |
| 129 | }, |
| 130 | }); |
| 131 | const hiddenLocked = (columnId: string) => columnId === "actions" || columnId === "update"; |
| 132 | const stickyRightLocked = (columnId: string) => |
| 133 | columnId === "actions" || (columnId === "update" && table.getColumn("actions") == null); |
| 134 | const isStickyLeft = (column: Column<TData, unknown>) => column.columnDef.meta?.stickyLeft === true; |
| 135 | const alignOf = (column: Column<TData, unknown>) => column.columnDef.meta?.align ?? "left"; |
| 136 | const dividerClass = (column: Column<TData, unknown>) => { |
| 137 | const divider = column.columnDef.meta?.divider; |
| 138 | return divider === "left" ? "border-l border-border/70" : divider === "right" ? "border-r border-border/70" : undefined; |
| 139 | }; |
| 140 | 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; |
| 141 | const stickyHeadClass = (column: Column<TData, unknown>) => |
| 142 | isStickyLeft(column) |
| 143 | ? "table-sticky-head-left sticky left-0 z-30" |
| 144 | : stickyRightLocked(column.id) |
| 145 | ? "table-sticky-head-right sticky right-0 z-30" |
| 146 | : undefined; |
| 147 | const stickyCellClass = (column: Column<TData, unknown>) => |
| 148 | isStickyLeft(column) |
| 149 | ? "table-sticky-left sticky left-0 z-10" |
| 150 | : stickyRightLocked(column.id) |
| 151 | ? "table-sticky-right sticky right-0 z-10" |
| 152 | : undefined; |
| 153 | const hideableColumns = () => table.getAllColumns().filter((column) => column.getCanHide() && !hiddenLocked(column.id)); |
| 154 | const columnLabel = (column: Column<TData, unknown>) => { |
| 155 | const header = column.columnDef.header; |
| 156 | return column.columnDef.meta?.label ?? (typeof header === "string" ? header : column.id); |
| 157 | }; |
| 158 | const viewMenuColumns = (): ViewMenuColumn[] => |
| 159 | hideableColumns().map((column) => ({ |
| 160 | id: column.id, |
| 161 | label: columnLabel(column), |
| 162 | visible: column.getIsVisible(), |
| 163 | toggle: (visible: boolean) => column.toggleVisibility(visible), |
| 164 | })); |
| 165 | const colSpan = () => Math.max(1, table.getVisibleLeafColumns().length); |
| 166 | const dataColumnsWidth = () => |
| 167 | table.getVisibleLeafColumns().reduce( |
| 168 | (total, column) => total + (stickyRightLocked(column.id) ? 0 : column.getSize()), |
| 169 | 0, |
| 170 | ); |
| 171 | const actionColumnsWidth = () => |
| 172 | table.getVisibleLeafColumns().reduce( |
| 173 | (total, column) => total + (stickyRightLocked(column.id) ? 110 : 0), |
| 174 | 0, |
| 175 | ); |
| 176 | const tableWidth = () => dataColumnsWidth() + actionColumnsWidth(); |
| 177 | const columnWidth = (column: Column<TData, unknown>) => { |
| 178 | if (stickyRightLocked(column.id)) return "110px"; |
| 179 | const total = dataColumnsWidth(); |
| 180 | if (total === 0) return `${column.getSize()}px`; |
| 181 | const share = column.getSize() / total; |
| 182 | return `calc(${share * 100}% - ${share * actionColumnsWidth()}px)`; |
| 183 | }; |
| 184 | const showColumnMenu = () => (props.enableColumnVisibility ?? true) && hideableColumns().length > 0; |
| 185 | const showSearch = () => props.searchPredicate != null || props.filterColumn != null || props.onSearchInput != null; |
| 186 | const showHeader = () => props.title != null || props.description != null || props.actions != null; |
| 187 | const showToolbar = () => showSearch() || props.filters != null || showColumnMenu(); |
| 188 | const pageCount = () => props.manualPagination ? Math.max(1, Math.ceil(props.manualPagination.total / props.manualPagination.pageSize)) : table.getPageCount(); |
| 189 | const pageIndex = () => props.manualPagination?.pageIndex ?? table.getState().pagination.pageIndex; |
| 190 | const pageSize = () => props.manualPagination?.pageSize ?? table.getState().pagination.pageSize; |
| 191 | const totalRows = () => props.manualPagination?.total ?? table.getFilteredRowModel().rows.length; |
| 192 | const setPageIndex = (next: number) => { |
| 193 | if (props.manualPagination) props.manualPagination.onPageChange(next); |
| 194 | else table.setPageIndex(next); |
| 195 | }; |
| 196 | const searchFieldValue = () => { |
| 197 | if (props.onSearchInput || props.searchPredicate) return searchValue(); |
| 198 | if (props.filterColumn) return (table.getColumn(props.filterColumn)?.getFilterValue() as string) ?? ""; |
| 199 | return ""; |
| 200 | }; |
| 201 | const handleSearch = (value: string) => { |
| 202 | if (props.onSearchInput) props.onSearchInput(value); |
| 203 | else if (props.searchPredicate) setSearch(value); |
| 204 | else if (props.filterColumn) table.getColumn(props.filterColumn)?.setFilterValue(value); |
| 205 | setPageIndex(0); |
| 206 | }; |
| 207 | const isInteractiveTarget = (target: EventTarget | null, row: EventTarget | null) => { |
| 208 | if (!(target instanceof Element)) return false; |
| 209 | const interactive = target.closest("button,a,input,select,textarea,[role='button']"); |
| 210 | return interactive != null && interactive !== row; |
| 211 | }; |
| 212 | const renderHeader = (header: ReturnType<typeof table.getHeaderGroups>[number]["headers"][number]) => { |
| 213 | const content = flexRender(header.column.columnDef.header, header.getContext()); |
| 214 | const align = alignOf(header.column); |
| 215 | if (!(props.enableSorting ?? true) || !header.column.getCanSort()) { |
| 216 | // The th already carries alignClass; the block span makes text-align resolve. |
| 217 | return <span class="block truncate whitespace-nowrap">{content}</span>; |
| 218 | } |
| 219 | const sorted = () => header.column.getIsSorted(); |
| 220 | return ( |
| 221 | <Button |
| 222 | type="button" |
| 223 | variant="ghost" |
| 224 | size="sm" |
| 225 | // th text-align positions this inline-flex button; -ml-2 cancels the button's |
| 226 | // px-2 so header text starts at the same gutter as the cell text below it. |
| 227 | class={cn("h-8 min-w-0 max-w-full px-2 font-medium tracking-normal normal-case", align === "left" && "-ml-2", sorted() && "text-foreground")} |
| 228 | onClick={() => header.column.toggleSorting(sorted() === "asc")} |
| 229 | > |
| 230 | <span class="truncate">{content}</span> |
| 231 | <Show |
| 232 | when={sorted() !== false} |
| 233 | fallback={ |
| 234 | <IconChevronsUpDown class="h-3.5 w-3.5 opacity-0 transition-opacity group-hover/head:opacity-50 group-focus-within/head:opacity-50" /> |
| 235 | } |
| 236 | > |
| 237 | <Show |
| 238 | when={sorted() === "asc"} |
| 239 | fallback={<IconArrowDown class="h-3.5 w-3.5" />} |
| 240 | > |
| 241 | <IconArrowUp class="h-3.5 w-3.5" /> |
| 242 | </Show> |
| 243 | </Show> |
| 244 | </Button> |
| 245 | ); |
| 246 | }; |
| 247 | |
| 248 | return ( |
| 249 | <div class={cn("space-y-3", props.class)}> |
| 250 | <Show when={showHeader()}> |
| 251 | <div class="flex flex-wrap items-start justify-between gap-3"> |
| 252 | <div class="min-w-0"> |
| 253 | <Show when={props.title}> |
| 254 | <h2 class="truncate text-lg font-semibold tracking-tight text-foreground">{props.title}</h2> |
| 255 | </Show> |
| 256 | <Show when={props.description}> |
| 257 | <p class="mt-1 text-sm text-muted-foreground">{props.description}</p> |
| 258 | </Show> |
| 259 | </div> |
| 260 | <Show when={props.actions}> |
| 261 | <div class="flex shrink-0 flex-wrap items-center gap-2 [&_button]:h-9 [&_button]:rounded-md">{props.actions}</div> |
| 262 | </Show> |
| 263 | </div> |
| 264 | </Show> |
| 265 | <Show when={showToolbar()}> |
| 266 | <div class="flex flex-col gap-2 lg:flex-row lg:items-center lg:justify-between"> |
| 267 | <div class="flex flex-1 flex-wrap items-center gap-2"> |
| 268 | <Show when={showSearch()}> |
| 269 | <DataTableSearch |
| 270 | value={searchFieldValue()} |
| 271 | onChange={handleSearch} |
| 272 | placeholder={props.filterPlaceholder ?? t("common.searchPlaceholder")} |
| 273 | /> |
| 274 | </Show> |
| 275 | <Show when={props.filters}> |
| 276 | <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> |
| 277 | </Show> |
| 278 | </div> |
| 279 | <Show when={showColumnMenu()}> |
| 280 | <div class="flex justify-end"> |
| 281 | <DataTableViewMenu columns={viewMenuColumns()} /> |
| 282 | </div> |
| 283 | </Show> |
| 284 | </div> |
| 285 | </Show> |
| 286 | <DataTableFrame> |
| 287 | <Table |
| 288 | class={cn("data-table table-fixed", props.tableClass)} |
| 289 | style={{ width: `max(100%, ${tableWidth()}px)` }} |
| 290 | > |
| 291 | <colgroup> |
| 292 | <For each={table.getVisibleLeafColumns()}> |
| 293 | {(column) => <col style={{ width: columnWidth(column) }} />} |
| 294 | </For> |
| 295 | </colgroup> |
| 296 | <TableHeader> |
| 297 | <For each={table.getHeaderGroups()}> |
| 298 | {(headerGroup) => ( |
| 299 | <TableRow class="hover:bg-transparent"> |
| 300 | <For each={headerGroup.headers}> |
| 301 | {(header) => ( |
| 302 | <TableHead |
| 303 | colSpan={header.colSpan} |
| 304 | class={cn( |
| 305 | "group/head relative overflow-hidden", |
| 306 | alignClass[alignOf(header.column)], |
| 307 | dividerClass(header.column), |
| 308 | stickyHeadClass(header.column), |
| 309 | header.column.columnDef.meta?.headerClass, |
| 310 | actionColumnClass(header.column.id), |
| 311 | )} |
| 312 | style={{ width: columnWidth(header.column) }} |
| 313 | > |
| 314 | <Show when={!header.isPlaceholder}>{renderHeader(header)}</Show> |
| 315 | </TableHead> |
| 316 | )} |
| 317 | </For> |
| 318 | </TableRow> |
| 319 | )} |
| 320 | </For> |
| 321 | </TableHeader> |
| 322 | <TableBody> |
| 323 | <Show |
| 324 | when={table.getRowModel().rows.length > 0} |
| 325 | fallback={ |
| 326 | <TableRow> |
| 327 | <TableCell colSpan={colSpan()} class="py-8 text-center text-muted-foreground"> |
| 328 | {props.empty ?? t("common.noResults")} |
| 329 | </TableCell> |
| 330 | </TableRow> |
| 331 | } |
| 332 | > |
| 333 | <For each={table.getRowModel().rows}> |
| 334 | {(row) => ( |
| 335 | <TableRow |
| 336 | data-state={row.getIsSelected() ? "selected" : undefined} |
| 337 | role={props.onRowClick ? "button" : undefined} |
| 338 | tabIndex={props.onRowClick ? 0 : undefined} |
| 339 | class={cn( |
| 340 | "group/row", |
| 341 | 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", |
| 342 | )} |
| 343 | onClick={(event) => { |
| 344 | if (!props.onRowClick || isInteractiveTarget(event.target, event.currentTarget)) return; |
| 345 | props.onRowClick(row.original); |
| 346 | }} |
| 347 | onKeyDown={(event) => { |
| 348 | if (!props.onRowClick || isInteractiveTarget(event.target, event.currentTarget) || (event.key !== "Enter" && event.key !== " ")) return; |
| 349 | event.preventDefault(); |
| 350 | props.onRowClick(row.original); |
| 351 | }} |
| 352 | > |
| 353 | <For each={row.getVisibleCells()}> |
| 354 | {(cell) => { |
| 355 | const val = cell.getValue(); |
| 356 | const isText = typeof val === "string" || typeof val === "number"; |
| 357 | const isSystemColumn = ["actions", "update", "select"].includes(cell.column.id); |
| 358 | const isEmpty = !isSystemColumn && (val == null || val === ""); |
| 359 | |
| 360 | return ( |
| 361 | <TableCell |
| 362 | class={cn( |
| 363 | alignClass[alignOf(cell.column)], |
| 364 | dividerClass(cell.column), |
| 365 | stickyCellClass(cell.column), |
| 366 | cell.column.columnDef.meta?.cellClass, |
| 367 | actionColumnClass(cell.column.id), |
| 368 | )} |
| 369 | style={{ width: columnWidth(cell.column) }} |
| 370 | title={isText && !isEmpty ? String(val) : undefined} |
| 371 | > |
| 372 | <Show when={!isEmpty} fallback={<span class="text-muted-foreground/40">-</span>}> |
| 373 | {flexRender(cell.column.columnDef.cell, cell.getContext())} |
| 374 | </Show> |
| 375 | </TableCell> |
| 376 | ); |
| 377 | }} |
| 378 | </For> |
| 379 | </TableRow> |
| 380 | )} |
| 381 | </For> |
| 382 | </Show> |
| 383 | </TableBody> |
| 384 | </Table> |
| 385 | </DataTableFrame> |
| 386 | <Show when={paginationEnabled && totalRows() > 0}> |
| 387 | <TablePagination |
| 388 | pageIndex={pageIndex()} |
| 389 | pageCount={pageCount()} |
| 390 | pageSize={pageSize()} |
| 391 | total={totalRows()} |
| 392 | onPageChange={setPageIndex} |
| 393 | onPageSizeChange={ |
| 394 | props.manualPagination |
| 395 | ? props.manualPagination.onPageSizeChange |
| 396 | : (size) => { table.setPageSize(size); setPageIndex(0); } |
| 397 | } |
| 398 | /> |
| 399 | </Show> |
| 400 | </div> |
| 401 | ); |
| 402 | } |
| 403 | |
| 404 | export function DataTableFrame(props: ParentProps<{ class?: string }>) { |
| 405 | return <div class={cn("data-table-wrap", props.class)}>{props.children}</div>; |
| 406 | } |
| 407 | |
| 408 | export function DataTableEmpty(props: ParentProps<{ class?: string }>) { |
| 409 | return ( |
| 410 | <div class={cn("rounded-lg border border-dashed border-border/70 bg-muted/15 px-6 py-10 text-center text-sm leading-6 text-muted-foreground", props.class)}> |
| 411 | {props.children} |
| 412 | </div> |
| 413 | ); |
| 414 | } |
| 415 | |
| 416 | export function DataTableSkeleton(props: { rows?: number; columns?: number }) { |
| 417 | const rows = () => Array.from({ length: props.rows ?? 6 }); |
| 418 | const columns = () => Array.from({ length: props.columns ?? 5 }); |
| 419 | return ( |
| 420 | <DataTableFrame class="animate-pulse"> |
| 421 | <table class="data-table"> |
| 422 | <thead> |
| 423 | <tr> |
| 424 | <For each={columns()}> |
| 425 | {() => ( |
| 426 | <th> |
| 427 | <div class="h-2.5 w-20 rounded-full bg-muted" /> |
| 428 | </th> |
| 429 | )} |
| 430 | </For> |
| 431 | </tr> |
| 432 | </thead> |
| 433 | <tbody> |
| 434 | <For each={rows()}> |
| 435 | {() => ( |
| 436 | <tr> |
| 437 | <For each={columns()}> |
| 438 | {() => ( |
| 439 | <td> |
| 440 | <div class="h-3 w-full max-w-32 rounded-full bg-muted/80" /> |
| 441 | </td> |
| 442 | )} |
| 443 | </For> |
| 444 | </tr> |
| 445 | )} |
| 446 | </For> |
| 447 | </tbody> |
| 448 | </table> |
| 449 | </DataTableFrame> |
| 450 | ); |
| 451 | } |