Files
co-lite/solvway-admin-portal/app/components/ui/data-table.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

273 lines
11 KiB
TypeScript

'use client'
import {
flexRender,
getCoreRowModel,
useReactTable,
type ColumnDef,
type RowData,
type SortingState,
type VisibilityState,
} from '@tanstack/react-table'
import { Settings2 } from 'lucide-react'
import { SortButton, ariaSort } from '@/app/components/ui/sortable-head'
import { Button } from '@/app/components/ui/button'
import { Skeleton } from '@/app/components/ui/skeleton'
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuLabel,
DropdownMenuTrigger,
} from '@/app/components/ui/dropdown-menu'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/app/components/ui/table'
import { cn } from '@/app/lib/utils'
import { TablePager } from '@/app/components/ui/table-pager'
import { useT } from '@/app/lib/i18n/MessagesProvider'
declare module '@tanstack/react-table' {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface ColumnMeta<TData extends RowData, TValue> {
/** Right-aligns the column and renders it with tabular numerals (§2, §7). */
numeric?: boolean
}
}
// The first column stays visible while a wide table scrolls sideways. Its cells need an opaque
// background that follows the row's hover/focus/selected state, or scrolled cells show through.
const PINNED_HEAD = 'sticky left-0 z-[1] bg-table-head'
// Clicks on these inside a row act on the control, not the row.
const ROW_CONTROLS = 'a, button, input, select, textarea, label, [role="checkbox"]'
const PINNED_CELL =
'sticky left-0 z-[1] bg-card group-hover:bg-muted group-focus-visible:bg-muted group-aria-selected:bg-accent'
/**
* Data table for server-paginated, server-sorted result sets — which is what
* every `src/services/*` list function returns. Pagination and sorting state are
* owned by the caller (usually synced to the URL), so a filtered view is
* shareable and survives reload, per DASHBOARD-STANDARD.md §7.
*/
export interface DataTableProps<TData> {
columns: ColumnDef<TData, unknown>[]
data: TData[]
/** Total rows across all pages, from the service's `Page<T>.total`. */
total: number
page: number
pageSize: number
onPageChange: (page: number) => void
sorting?: SortingState
onSortingChange?: (sorting: SortingState) => void
columnVisibility?: VisibilityState
onColumnVisibilityChange?: (visibility: VisibilityState) => void
isLoading?: boolean
/** Rendered in place of rows when `data` is empty and not loading. */
empty?: React.ReactNode
/** Accessible name for the table. */
label: string
rowKey: (row: TData) => string
/** Makes rows clickable (and Enter/Space-activatable) — e.g. to open a detail drawer. */
onRowClick?: (row: TData) => void
/** rowKey of the row to highlight as selected (only meaningful with onRowClick). */
selectedKey?: string
/** Receives the table's root element, so useFitPageSize can measure where the table starts. */
tableRef?: (el: HTMLElement | null) => void
}
export function DataTable<TData>({
columns,
data,
total,
page,
pageSize,
onPageChange,
sorting = [],
onSortingChange,
columnVisibility,
onColumnVisibilityChange,
isLoading = false,
empty,
label,
rowKey,
onRowClick,
selectedKey,
tableRef,
}: DataTableProps<TData>) {
const t = useT()
const pageCount = Math.max(1, Math.ceil(total / pageSize))
const table = useReactTable({
data,
columns,
state: { sorting, columnVisibility: columnVisibility ?? {} },
// The service already sorted and paginated; never re-do it client-side or
// the table would only sort the rows on the current page.
manualSorting: true,
// First click is always ascending; tanstack would otherwise start numeric columns descending.
sortDescFirst: false,
manualPagination: true,
pageCount,
onSortingChange: updater => {
onSortingChange?.(typeof updater === 'function' ? updater(sorting) : updater)
},
onColumnVisibilityChange: updater => {
if (!onColumnVisibilityChange) return
onColumnVisibilityChange(
typeof updater === 'function' ? updater(columnVisibility ?? {}) : updater,
)
},
getCoreRowModel: getCoreRowModel(),
})
const visibleColumnCount = table.getVisibleLeafColumns().length
const hideableColumns = table.getAllLeafColumns().filter(c => c.getCanHide())
return (
<div ref={tableRef} className="space-y-3">
{onColumnVisibilityChange && hideableColumns.length > 0 && (
<div className="flex justify-end">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" className="h-9">
<Settings2 aria-hidden="true" className="size-4" />
{t("UiColumns")}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>{t("UiVisibleColumns")}</DropdownMenuLabel>
{hideableColumns.map(column => (
<DropdownMenuCheckboxItem
key={column.id}
checked={column.getIsVisible()}
onCheckedChange={value => column.toggleVisibility(!!value)}
>
{typeof column.columnDef.header === 'string'
? column.columnDef.header
: column.id}
</DropdownMenuCheckboxItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</div>
)}
<div className="overflow-hidden rounded-table border bg-card">
<div className="overflow-x-auto">
<Table aria-label={label}>
<TableHeader className="sticky top-0 z-10">
{table.getHeaderGroups().map(headerGroup => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header, index) => {
const sortDirection = header.column.getIsSorted()
const canSort = header.column.getCanSort() && Boolean(onSortingChange)
const numeric = header.column.columnDef.meta?.numeric
return (
<TableHead
key={header.id}
aria-sort={canSort ? ariaSort(sortDirection) : undefined}
className={cn(numeric && 'text-right', index === 0 && PINNED_HEAD)}
>
{canSort ? (
<SortButton
direction={sortDirection}
numeric={numeric}
onClick={header.column.getToggleSortingHandler()}
>
{flexRender(header.column.columnDef.header, header.getContext())}
</SortButton>
) : (
flexRender(header.column.columnDef.header, header.getContext())
)}
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{isLoading ? (
Array.from({ length: Math.min(pageSize, 8) }).map((_, rowIndex) => (
<TableRow key={`skeleton-${rowIndex}`} data-testid="table-skeleton-row">
{Array.from({ length: visibleColumnCount }).map((__, cellIndex) => (
<TableCell key={cellIndex} className="h-9">
<Skeleton className="h-4 w-full" />
</TableCell>
))}
</TableRow>
))
) : (
table.getRowModel().rows.map((row, i, rows) => {
const key = rowKey(row.original)
// Callers' keys can repeat (wallet ledger refNo); duplicate React keys leave stale rows on refetch.
// ponytail: O(n²) over one page (≤100 rows); switch to a Map counter if pages grow large.
const seen = rows.slice(0, i).filter(r => rowKey(r.original) === key).length
const interactive = Boolean(onRowClick)
return (
<TableRow
key={seen ? `${key}~${seen}` : key}
className={cn(
'group h-9 transition-colors hover:bg-muted',
interactive && 'cursor-pointer focus-visible:bg-muted focus-visible:outline-none',
interactive && key === selectedKey && 'bg-accent text-accent-foreground hover:bg-accent',
)}
{...(interactive
? {
tabIndex: 0,
'aria-selected': key === selectedKey,
onClick: (e: React.MouseEvent<HTMLElement>) => {
// DOM containment keeps out clicks bubbling (via React) from portalled dialogs/menus.
const target = e.target as Element
if (!e.currentTarget.contains(target)) return
const control = target.closest(ROW_CONTROLS)
if (control && e.currentTarget.contains(control)) return
onRowClick!(row.original)
},
onKeyDown: (e: React.KeyboardEvent) => {
// Only the focused row itself: Enter/Space on a control in the row belongs to that control.
if (e.target !== e.currentTarget) return
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
onRowClick!(row.original)
}
},
}
: {})}
>
{row.getVisibleCells().map((cell, index) => (
<TableCell
key={cell.id}
className={cn(
'py-1.5',
cell.column.columnDef.meta?.numeric && 'text-right tabular',
index === 0 && PINNED_CELL,
)}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
)
})
)}
</TableBody>
</Table>
</div>
{!isLoading && data.length === 0 && (
<div role="status" className="flex h-32 items-center justify-center p-2 text-center text-sm">
{empty ?? <span className="text-muted-foreground">{t("UiNoResults")}</span>}
</div>
)}
</div>
<TablePager page={page} pageSize={pageSize} total={total} onPageChange={onPageChange} isLoading={isLoading} />
</div>
)
}