Lightweight server monitoring with historical data, docker stats, and alerts.
feat(site): paginate data tables with a shared rows-per-page setting (#2444)
Sven van Ginkel237f9641960f
diff --git a/internal/site/bun.lock b/internal/site/bun.lockindex 724845a36..8bf7b92cd 100644--- a/internal/site/bun.lock+++ b/internal/site/bun.lock@@ -27,7 +27,6 @@"@radix-ui/react-toast": "^1.2.15","@radix-ui/react-tooltip": "^1.2.8","@tanstack/react-table": "^8.21.3",- "@tanstack/react-virtual": "^3.13.12","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",@@ -444,12 +443,8 @@"@tanstack/react-table": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/table-core": "8.21.3" }, "peerDependencies": { "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww=="],- "@tanstack/react-virtual": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/virtual-core": "3.13.12" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Gd13QdxPSukP8ZrkbgS2RwoZseTTbQPLnQEn7HY/rqtM+8Zt95f7xKC7N0EsKs7aoz0WzZ+fditZux+F8EzYxA=="],-"@tanstack/table-core": ["@tanstack/[email protected]", "", {}, "sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg=="],- "@tanstack/virtual-core": ["@tanstack/[email protected]", "", {}, "sha512-1YBOJfRHV4sXUmWsFSf5rQor4Ss82G8dQWLRbnk3GA4jeP8hQt1hxXh0tmflpC0dz3VgEv/1+qwPyLeWkQuPFA=="],-"@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.2.20" } }, "sha512-dX3RGzQ8+KgmMw7CsW4xT5ITBSCrSbfHc36SNT31EOUg/LA9JWq0VDdEXDRSe1InVWpd2yLUM1FUF/kEOyTzYA=="],"@types/d3-array": ["@types/[email protected]", "", {}, "sha512-Y2Jn2idRrLzUfAKV2LyRImR+y4oa2AntrgID95SHJxuMUrkNXmanDSed71sRNZysveJVt1hLLemQZIady0FpEg=="],diff --git a/internal/site/package-lock.json b/internal/site/package-lock.jsonindex 63de0f1a8..03a2ad907 100644--- a/internal/site/package-lock.json+++ b/internal/site/package-lock.json@@ -7,7 +7,7 @@"": {"name": "beszel","version": "0.21.0",- "dependencies": {+ "dependencies": {"@henrygd/queue": "^1.0.7","@henrygd/semaphore": "^0.0.2","@lingui/detect-locale": "^5.4.1",@@ -30,7 +30,6 @@"@radix-ui/react-toast": "^1.2.15","@radix-ui/react-tooltip": "^1.2.8","@tanstack/react-table": "^8.21.3",- "@tanstack/react-virtual": "^3.13.12","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",@@ -3468,23 +3467,6 @@"react-dom": ">=16.8"}},- "node_modules/@tanstack/react-virtual": {- "version": "3.13.12",- "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.13.12.tgz",- "integrity": "sha512-Gd13QdxPSukP8ZrkbgS2RwoZseTTbQPLnQEn7HY/rqtM+8Zt95f7xKC7N0EsKs7aoz0WzZ+fditZux+F8EzYxA==",- "license": "MIT",- "dependencies": {- "@tanstack/virtual-core": "3.13.12"- },- "funding": {- "type": "github",- "url": "https://github.com/sponsors/tannerlinsley"- },- "peerDependencies": {- "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",- "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"- }- },"node_modules/@tanstack/table-core": {"version": "8.21.3","resolved": "https://registry.npmjs.org/@tanstack/table-core/-/table-core-8.21.3.tgz",@@ -3498,16 +3480,6 @@"url": "https://github.com/sponsors/tannerlinsley"}},- "node_modules/@tanstack/virtual-core": {- "version": "3.13.12",- "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.13.12.tgz",- "integrity": "sha512-1YBOJfRHV4sXUmWsFSf5rQor4Ss82G8dQWLRbnk3GA4jeP8hQt1hxXh0tmflpC0dz3VgEv/1+qwPyLeWkQuPFA==",- "license": "MIT",- "funding": {- "type": "github",- "url": "https://github.com/sponsors/tannerlinsley"- }- },"node_modules/@types/bun": {"version": "1.2.20","resolved": "https://registry.npmjs.org/@types/bun/-/bun-1.2.20.tgz",diff --git a/internal/site/package.json b/internal/site/package.jsonindex d1b955b00..dd60a3d7d 100644--- a/internal/site/package.json+++ b/internal/site/package.json@@ -34,7 +34,6 @@"@radix-ui/react-toast": "^1.2.15","@radix-ui/react-tooltip": "^1.2.8","@tanstack/react-table": "^8.21.3",- "@tanstack/react-virtual": "^3.13.12","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",diff --git a/internal/site/src/components/containers-table/containers-table-columns.tsx b/internal/site/src/components/containers-table/containers-table-columns.tsxindex 2bec38b70..600ea7244 100644--- a/internal/site/src/components/containers-table/containers-table-columns.tsx+++ b/internal/site/src/components/containers-table/containers-table-columns.tsx@@ -16,7 +16,7 @@ import {import { EthernetIcon, HourglassIcon, SquareArrowRightEnterIcon } from "../ui/icons"import { Badge } from "../ui/badge"import { t } from "@lingui/core/macro"-import { $allSystemsById, $longestSystemName } from "@/lib/stores"+import { $allSystemsById } from "@/lib/stores"import { useStore } from "@nanostores/react"import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"@@ -68,15 +68,7 @@ export const containerChartCols: ColumnDef<ContainerRecord>[] = [header: ({ column }) => <HeaderButton column={column} name={t`System`} Icon={ServerIcon} />,cell: ({ getValue }) => {const allSystems = useStore($allSystemsById)- const longestName = useStore($longestSystemName)- return (- <div className="ms-1 relative w-fit max-w-40">- <span className="invisible block whitespace-nowrap" aria-hidden="true">- {longestName}- </span>- <span className="absolute inset-0 truncate">{allSystems[getValue() as string]?.name ?? ""}</span>- </div>- )+ return <div className="ms-1 max-w-40 truncate">{allSystems[getValue() as string]?.name ?? ""}</div>},},// {diff --git a/internal/site/src/components/containers-table/containers-table.tsx b/internal/site/src/components/containers-table/containers-table.tsxindex a8f8b21f8..ece3995e2 100644--- a/internal/site/src/components/containers-table/containers-table.tsx+++ b/internal/site/src/components/containers-table/containers-table.tsx@@ -6,6 +6,7 @@ import {flexRender,getCoreRowModel,getFilteredRowModel,+ getPaginationRowModel,getSortedRowModel,type Row,type SortingState,@@ -13,8 +14,8 @@ import {useReactTable,type VisibilityState,} from "@tanstack/react-table"-import { useVirtualizer, type VirtualItem } from "@tanstack/react-virtual"import { memo, type RefObject, useEffect, useRef, useState } from "react"+import { DataTablePagination, usePagination } from "@/components/ui/data-table-pagination"import { Input } from "@/components/ui/input"import { TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"import { pb } from "@/lib/api"@@ -63,6 +64,7 @@ export default function ContainersTable({ systemId }: { systemId?: string }) {const [rowSelection, setRowSelection] = useState({})const [globalFilter, setGlobalFilter] = useState("")+ const { pagination, onPaginationChange, resetPageIndex } = usePagination()useEffect(() => {function fetchData(systemId?: string) {@@ -126,7 +128,13 @@ export default function ContainersTable({ systemId }: { systemId?: string }) {getCoreRowModel: getCoreRowModel(),getSortedRowModel: getSortedRowModel(),getFilteredRowModel: getFilteredRowModel(),- onSortingChange: setSorting,+ getPaginationRowModel: getPaginationRowModel(),+ autoResetPageIndex: false,+ onPaginationChange,+ onSortingChange: (updater) => {+ setSorting(updater)+ resetPageIndex()+ },onColumnFiltersChange: setColumnFilters,onColumnVisibilityChange: setColumnVisibility,onRowSelectionChange: setRowSelection,@@ -141,8 +149,12 @@ export default function ContainersTable({ systemId }: { systemId?: string }) {columnVisibility,rowSelection,globalFilter,+ pagination,+ },+ onGlobalFilterChange: (value) => {+ setGlobalFilter(value)+ resetPageIndex()},- onGlobalFilterChange: setGlobalFilter,globalFilterFn: (row, _columnId, filterValue) => {const container = row.originalconst systemName = $allSystemsById.get()[container.system]?.name ?? ""@@ -180,7 +192,7 @@ export default function ContainersTable({ systemId }: { systemId?: string }) {<Inputplaceholder={t`Filter...`}value={globalFilter}- onChange={(e) => setGlobalFilter(e.target.value)}+ onChange={(e) => table.setGlobalFilter(e.target.value)}className="ps-4 pe-10 w-full"/>{globalFilter && (@@ -190,7 +202,7 @@ export default function ContainersTable({ systemId }: { systemId?: string }) {size="icon"aria-label={t`Clear`}className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7 text-muted-foreground"- onClick={() => setGlobalFilter("")}+ onClick={() => table.setGlobalFilter("")}><XIcon className="h-4 w-4" /></Button>@@ -201,6 +213,7 @@ export default function ContainersTable({ systemId }: { systemId?: string }) {<div className="rounded-md"><AllContainersTable table={table} rows={rows} colLength={visibleColumns.length} data={data} /></div>+ <DataTablePagination table={table} showSelected={false} /></Card>)}@@ -216,8 +229,6 @@ const AllContainersTable = memo(function AllContainersTable({colLength: numberdata: ContainerRecord[] | undefined}) {- // The virtualizer will need a reference to the scrollable container element- const scrollRef = useRef<HTMLDivElement>(null)const activeContainer = useRef<ContainerRecord | null>(null)const [sheetOpen, setSheetOpen] = useState(false)const openSheet = (container: ContainerRecord) => {@@ -225,50 +236,26 @@ const AllContainersTable = memo(function AllContainersTable({setSheetOpen(true)}- const virtualizer = useVirtualizer<HTMLDivElement, HTMLTableRowElement>({- count: rows.length,- estimateSize: () => 54,- getScrollElement: () => scrollRef.current,- overscan: 5,- })- const virtualRows = virtualizer.getVirtualItems()-- const paddingTop = Math.max(0, virtualRows[0]?.start ?? 0 - virtualizer.options.scrollMargin)- const paddingBottom = Math.max(0, virtualizer.getTotalSize() - (virtualRows[virtualRows.length - 1]?.end ?? 0))-return (- <div- className={cn(- "h-min max-h-[calc(100dvh-17rem)] max-w-full relative overflow-auto border rounded-md",- // don't set min height if there are less than 2 rows, do set if we need to display the empty state- (!rows.length || rows.length > 2) && "min-h-50"- )}- ref={scrollRef}- >- {/* add header height to table size */}- <div style={{ height: `${virtualizer.getTotalSize() + 48}px`, paddingTop, paddingBottom }}>- <table className="text-sm w-full h-full text-nowrap">- <ContainersTableHead table={table} />- <TableBody>- {rows.length ? (- virtualRows.map((virtualRow) => {- const row = rows[virtualRow.index]- return <ContainerTableRow key={row.id} row={row} virtualRow={virtualRow} openSheet={openSheet} />- })- ) : (- <TableRow>- <TableCell colSpan={colLength} className="h-37 text-center pointer-events-none">- {data ? (- <Trans>No results.</Trans>- ) : (- <LoaderCircleIcon className="animate-spin size-10 opacity-60 mx-auto" />- )}- </TableCell>- </TableRow>- )}- </TableBody>- </table>- </div>+ <div className="max-w-full relative overflow-auto border rounded-md">+ <table className="text-sm w-full h-full text-nowrap">+ <ContainersTableHead table={table} />+ <TableBody>+ {rows.length ? (+ rows.map((row) => <ContainerTableRow key={row.id} row={row} openSheet={openSheet} />)+ ) : (+ <TableRow>+ <TableCell colSpan={colLength} className="h-37 text-center pointer-events-none">+ {data ? (+ <Trans>No results.</Trans>+ ) : (+ <LoaderCircleIcon className="animate-spin size-10 opacity-60 mx-auto" />+ )}+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </table><ContainerSheet sheetOpen={sheetOpen} setSheetOpen={setSheetOpen} activeContainer={activeContainer} /></div>)@@ -474,11 +461,9 @@ function ContainersTableHead({ table }: { table: TableType<ContainerRecord> }) {const ContainerTableRow = memo(function ContainerTableRow({row,- virtualRow,openSheet,}: {row: Row<ContainerRecord>- virtualRow: VirtualItemopenSheet: (container: ContainerRecord) => void}) {return (@@ -492,7 +477,7 @@ const ContainerTableRow = memo(function ContainerTableRow({key={cell.id}className="py-0 ps-4.5"style={{- height: virtualRow.size,+ height: 54,width: cell.column.getSize(),}}>diff --git a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsxindex ece7ea62e..a09b6fea0 100644--- a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx+++ b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx@@ -29,7 +29,6 @@ import {} from "@/components/ui/dropdown-menu"import { Plural, Trans } from "@lingui/react/macro"import { $allSystemsById } from "@/lib/stores"-import type { ReadableAtom } from "nanostores"import { useStore } from "@nanostores/react"import { SystemStatus } from "@/lib/enums"import { Checkbox } from "@/components/ui/checkbox"@@ -74,19 +73,15 @@ const SYSTEM_STATUS_COLORS = {const isMuted = (record: NetworkMonitorRecord, systemRecord: SystemRecord | undefined) =>!record.enabled || systemRecord?.status !== SystemStatus.Up-export function getMonitorColumns(- longestTarget = "",- $longestSystemName: ReadableAtom<string>,- {- onEdit,- onDelete,- onSetEnabled,- }: {- onEdit?: (monitor: NetworkMonitorRecord) => void- onDelete?: (monitors: NetworkMonitorRecord[]) => void | Promise<void>- onSetEnabled?: (monitors: NetworkMonitorRecord[], enabled: boolean) => void | Promise<void>- } = {}-): ColumnDef<NetworkMonitorRecord>[] {+export function getMonitorColumns({+ onEdit,+ onDelete,+ onSetEnabled,+}: {+ onEdit?: (monitor: NetworkMonitorRecord) => void+ onDelete?: (monitors: NetworkMonitorRecord[]) => void | Promise<void>+ onSetEnabled?: (monitors: NetworkMonitorRecord[], enabled: boolean) => void | Promise<void>+} = {}): ColumnDef<NetworkMonitorRecord>[] {return [{id: "select",@@ -128,7 +123,6 @@ export function getMonitorColumns(header: ({ column }) => <HeaderButton column={column} name={t`System`} Icon={ServerIcon} />,cell: ({ getValue }) => {const system = useStore($allSystemsById)[getValue() as string] as SystemRecord | undefined- const longestSystemName = useStore($longestSystemName)const name = system?.nameconst status = system?.status as SystemStatus // undefined val is fine but makes lsp mad@@ -136,15 +130,10 @@ export function getMonitorColumns(() => (<div className="ms-1.5 max-w-44 flex gap-2 items-center tabular-nums"><span className={cn("shrink-0 size-2 rounded-full", SYSTEM_STATUS_COLORS[status])} />- <div className="relative w-fit min-w-0 max-w-full">- <span className="invisible block whitespace-nowrap" aria-hidden="true">- {longestSystemName}- </span>- <span className="absolute inset-0 truncate">{name}</span>- </div>+ <span className="truncate">{name}</span></div>),- [status, name, longestSystemName]+ [status, name])},},@@ -170,12 +159,7 @@ export function getMonitorColumns(return (<div className="ms-1.5 max-w-64 flex gap-2 items-center tabular-nums"><span className={cn("shrink-0 size-2 rounded-full", color)} />- <div className="relative w-fit min-w-0 max-w-full">- <span className="invisible block overflow-hidden whitespace-nowrap" aria-hidden="true">- {longestTarget}- </span>- <span className="absolute inset-0 truncate">{getValue() as string}</span>- </div>+ <span className="truncate">{getValue() as string}</span></div>)},diff --git a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx b/internal/site/src/components/network-monitors-table/network-monitors-table.tsxindex 71c5b91d3..69f7b6558 100644--- a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx+++ b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx@@ -11,6 +11,7 @@ import {flexRender,getCoreRowModel,getFilteredRowModel,+ getPaginationRowModel,getSortedRowModel,type Row,type RowSelectionState,@@ -19,7 +20,6 @@ import {useReactTable,type VisibilityState,} from "@tanstack/react-table"-import { useVirtualizer, type VirtualItem } from "@tanstack/react-virtual"import {AlertDialog,AlertDialogAction,@@ -35,14 +35,15 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"import { subscribeKeys } from "nanostores"import { getMonitorColumns } from "@/components/network-monitors-table/network-monitors-columns"import { Card, CardHeader, CardTitle } from "@/components/ui/card"+import { DataTablePagination, usePagination } from "@/components/ui/data-table-pagination"import { Input } from "@/components/ui/input"import { TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"import { useToast } from "@/components/ui/use-toast"import { isReadOnlyUser, queueUserSettings } from "@/lib/api"import { pb } from "@/lib/api"import { SystemStatus } from "@/lib/enums"-import { $allSystemsById, $direction, $textMeasureVersion, $userSettings, getUserChartTime } from "@/lib/stores"-import { cn, formatShortDate, isVisuallyLonger, matchesFilterGroups, parseFilterGroups, parseSemVer } from "@/lib/utils"+import { $allSystemsById, $direction, $userSettings, getUserChartTime } from "@/lib/stores"+import { cn, formatShortDate, matchesFilterGroups, parseFilterGroups, parseSemVer } from "@/lib/utils"import type { ChartOptions, MonitorCertInfo, NetworkMonitorRecord } from "@/types"import { AddMonitorDialog, EditMonitorDialog, MonitorMultiSelect, SystemMultiSelect } from "./monitor-dialog"import {@@ -104,6 +105,7 @@ export default function NetworkMonitorsTableNew({)const [rowSelection, setRowSelection] = useState<RowSelectionState>({})const [globalFilter, setGlobalFilter] = useState("")+ const { pagination, onPaginationChange, resetPageIndex } = usePagination()const [deleteOpen, setDeleteOpen] = useState(false)const [pendingDelete, setPendingDelete] = useState<NetworkMonitorRecord[]>([])const [editingMonitor, setEditingMonitor] = useState<NetworkMonitorRecord>()@@ -148,42 +150,11 @@ export default function NetworkMonitorsTableNew({queueUserSettings({ [sortSettingsKey]: next })return next})+ resetPageIndex()},- [sortSettingsKey, sortStorageKey]+ [sortSettingsKey, sortStorageKey, resetPageIndex])- // recompute when measured widths are invalidated (e.g. web font finished loading)- const textMeasureVersion = useStore($textMeasureVersion)- const longestTarget = useMemo(() => {- let longestTarget = ""- for (const p of monitors) {- if (isVisuallyLonger(getMonitorTarget(p), longestTarget)) {- longestTarget = getMonitorTarget(p)- }- }- return longestTarget- }, [monitors, textMeasureVersion])-- // longest name among systems that have monitors in this table (skipped for single-system view).- // Held in a store because memoized rows don't re-render when column definitions change.- const $longestSystemName = useMemo(() => atom(""), [])- useEffect(() => {- if (systemId) {- return- }- const systemIds = new Set(monitors.map((m) => m.system))- return $allSystemsById.subscribe((systems) => {- let longest = ""- for (const id of systemIds) {- const name = systems[id]?.name ?? ""- if (isVisuallyLonger(name, longest)) {- longest = name- }- }- $longestSystemName.set(longest)- })- }, [monitors, systemId, textMeasureVersion, $longestSystemName])-const runMonitorBatch = useCallback(async (ids: string[], enqueue: (batch: ReturnType<typeof pb.createBatch>, id: string) => void) => {let batch = pb.createBatch()@@ -270,7 +241,7 @@ export default function NetworkMonitorsTableNew({)const columns = useMemo(() => {- let columns = getMonitorColumns(longestTarget, $longestSystemName, {+ let columns = getMonitorColumns({onEdit: setEditingMonitor,onDelete: handleDeleteRequest,onSetEnabled: handleSetEnabled,@@ -278,7 +249,7 @@ export default function NetworkMonitorsTableNew({columns = systemId ? columns.filter((col) => col.id !== "system") : columnscolumns = canManageMonitors ? columns : columns.filter((col) => col.id !== "actions")return columns- }, [canManageMonitors, handleDeleteRequest, handleSetEnabled, systemId, longestTarget, $longestSystemName])+ }, [canManageMonitors, handleDeleteRequest, handleSetEnabled, systemId])const table = useReactTable({data: monitors,@@ -287,6 +258,9 @@ export default function NetworkMonitorsTableNew({getCoreRowModel: getCoreRowModel(),getSortedRowModel: getSortedRowModel(),getFilteredRowModel: getFilteredRowModel(),+ getPaginationRowModel: getPaginationRowModel(),+ autoResetPageIndex: false,+ onPaginationChange,onSortingChange: handleSortingChange,onColumnFiltersChange: setColumnFilters,onColumnVisibilityChange: handleColumnVisibilityChange,@@ -302,8 +276,12 @@ export default function NetworkMonitorsTableNew({columnVisibility,rowSelection,globalFilter,+ pagination,+ },+ onGlobalFilterChange: (value) => {+ setGlobalFilter(value)+ resetPageIndex()},- onGlobalFilterChange: setGlobalFilter,globalFilterFn: (row, _columnId, filterValue) => {const value = (filterValue as string).trim()if (!value) return true@@ -338,7 +316,7 @@ export default function NetworkMonitorsTableNew({<Inputplaceholder={t`Filter...`}value={globalFilter}- onChange={(e) => setGlobalFilter(e.target.value)}+ onChange={(e) => table.setGlobalFilter(e.target.value)}className="ms-auto px-4 w-full max-w-full md-lg:w-50"/>{globalFilter && (@@ -348,7 +326,7 @@ export default function NetworkMonitorsTableNew({size="icon"aria-label={t`Clear`}className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7 text-muted-foreground"- onClick={() => setGlobalFilter("")}+ onClick={() => table.setGlobalFilter("")}><XIcon className="h-4 w-4" /></Button>@@ -480,6 +458,7 @@ export default function NetworkMonitorsTableNew({includesAllSystems={!systemId}/></div>+ <DataTablePagination table={table} /></Card>)}@@ -502,7 +481,6 @@ const NetworkMonitorsTable = memo(function NetworkMonitorTable({/** The table lists every system's monitors, so the sheet can compare without fetching. */includesAllSystems: boolean}) {- const scrollRef = useRef<HTMLDivElement>(null)const [sheetOpen, setSheetOpen] = useState(false)const [activeMonitorId, setActiveMonitorId] = useState<string | null>(null)const activeMonitor = activeMonitorId@@ -513,58 +491,37 @@ const NetworkMonitorsTable = memo(function NetworkMonitorTable({setSheetOpen(true)}, [])- const virtualizer = useVirtualizer<HTMLDivElement, HTMLTableRowElement>({- count: rows.length,- estimateSize: () => 54,- getScrollElement: () => scrollRef.current,- overscan: 5,- })- const virtualRows = virtualizer.getVirtualItems()-- const paddingTop = Math.max(0, virtualRows[0]?.start ?? 0 - virtualizer.options.scrollMargin)- const paddingBottom = Math.max(0, virtualizer.getTotalSize() - (virtualRows[virtualRows.length - 1]?.end ?? 0))-return (- <div- className={cn(- "h-min max-h-[calc(100dvh-17rem)] max-w-full relative overflow-auto border rounded-md",- (!rows.length || rows.length > 2) && "min-h-50"- )}- ref={scrollRef}- >- <div style={{ height: `${virtualizer.getTotalSize() + 48}px`, paddingTop, paddingBottom }}>- <table className="text-sm w-full h-full text-nowrap">- <NetworkMonitorTableHead table={table} />- <TableBody>- {rows.length ? (- virtualRows.map((virtualRow) => {- const row = rows[virtualRow.index]- return (- <NetworkMonitorTableRow- key={row.id}- row={row}- virtualRow={virtualRow}- isSelected={row.getIsSelected()}- rowSelection={rowSelection}- visibleColumnsKey={visibleColumnsKey}- openSheet={openSheet}- />- )- })- ) : (- <TableRow>- <TableCell colSpan={colLength} className="h-37 text-center pointer-events-none">- {isLoading ? (- <LoaderCircleIcon className="animate-spin size-10 opacity-60 mx-auto" />- ) : (- <Trans>No results.</Trans>- )}- </TableCell>- </TableRow>- )}- </TableBody>- </table>- </div>+ <div className="max-w-full relative overflow-auto border rounded-md">+ <table className="text-sm w-full h-full text-nowrap">+ <NetworkMonitorTableHead table={table} />+ <TableBody>+ {rows.length ? (+ rows.map((row) => {+ return (+ <NetworkMonitorTableRow+ key={row.id}+ row={row}+ isSelected={row.getIsSelected()}+ rowSelection={rowSelection}+ visibleColumnsKey={visibleColumnsKey}+ openSheet={openSheet}+ />+ )+ })+ ) : (+ <TableRow>+ <TableCell colSpan={colLength} className="h-37 text-center pointer-events-none">+ {isLoading ? (+ <LoaderCircleIcon className="animate-spin size-10 opacity-60 mx-auto" />+ ) : (+ <Trans>No results.</Trans>+ )}+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </table><NetworkMonitorSheetopen={sheetOpen}onOpenChange={(nextOpen) => {@@ -598,7 +555,6 @@ function NetworkMonitorTableHead({ table }: { table: TableType<NetworkMonitorRecconst NetworkMonitorTableRow = memo(function NetworkMonitorTableRow({row,- virtualRow,isSelected,rowSelection: _rowSelection,// Column visibility doesn't change the row object identity, so this prop exists only@@ -607,7 +563,6 @@ const NetworkMonitorTableRow = memo(function NetworkMonitorTableRow({openSheet,}: {row: Row<NetworkMonitorRecord>- virtualRow: VirtualItemisSelected: boolean// Menus depend on the entire selection, including changes to other rows.rowSelection: RowSelectionState@@ -629,7 +584,7 @@ const NetworkMonitorTableRow = memo(function NetworkMonitorTableRow({className="py-0"style={{width: `${cell.column.getSize()}px`,- height: virtualRow.size,+ height: 54,}}>{flexRender(cell.column.columnDef.cell, cell.getContext())}@@ -679,13 +634,7 @@ function CertExpiry({ cert }: { cert: MonitorCertInfo }) {<Separator orientation="vertical" className="h-2.5 bg-muted-foreground opacity-70" /><ShieldCheckIcon className={cn("size-3.5 text-muted-foreground -me-1", certExpiryTextColors[level])} /><span className={certExpiryTextColors[level]}>- {daysLeft < 0 ? (- <Trans>Certificate expired {expires}</Trans>- ) : (- <Trans>- Certificate expires {expires}- </Trans>- )}+ {daysLeft < 0 ? <Trans>Certificate expired {expires}</Trans> : <Trans>Certificate expires {expires}</Trans>}</span>{cert.issuer && (<>diff --git a/internal/site/src/components/routes/settings/alerts-history-data-table.tsx b/internal/site/src/components/routes/settings/alerts-history-data-table.tsxindex 763daa063..b7e7f7f54 100644--- a/internal/site/src/components/routes/settings/alerts-history-data-table.tsx+++ b/internal/site/src/components/routes/settings/alerts-history-data-table.tsx@@ -7,19 +7,11 @@ import {getFilteredRowModel,getPaginationRowModel,getSortedRowModel,- type PaginationState,type SortingState,useReactTable,type VisibilityState,} from "@tanstack/react-table"-import {- ChevronLeftIcon,- ChevronRightIcon,- ChevronsLeftIcon,- ChevronsRightIcon,- DownloadIcon,- Trash2Icon,-} from "lucide-react"+import { DownloadIcon, Trash2Icon } from "lucide-react"import { memo, useEffect, useState } from "react"import {AlertDialog,@@ -34,14 +26,13 @@ import {} from "@/components/ui/alert-dialog"import { Button, buttonVariants } from "@/components/ui/button"import { Checkbox } from "@/components/ui/checkbox"+import { DataTablePagination, usePagination } from "@/components/ui/data-table-pagination"import { Input } from "@/components/ui/input"-import { Label } from "@/components/ui/label"-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"import { useToast } from "@/components/ui/use-toast"import { alertInfo } from "@/lib/alerts"import { pb } from "@/lib/api"-import { cn, formatDuration, formatShortDate, useBrowserStorage } from "@/lib/utils"+import { cn, formatDuration, formatShortDate } from "@/lib/utils"import type { AlertsHistoryRecord } from "@/types"import { alertsHistoryColumns } from "../../alerts-history-columns"@@ -67,12 +58,7 @@ export default function AlertsHistoryDataTable() {const [globalFilter, setGlobalFilter] = useState("")const { toast } = useToast()const [deleteOpen, setDeleteDialogOpen] = useState(false)-- // Store pagination preference in local storage- const [pagination, setPagination] = useBrowserStorage<PaginationState>("ah-pagination", {- pageIndex: 0,- pageSize: 10,- })+ const { pagination, onPaginationChange } = usePagination()useEffect(() => {let unsubscribe: (() => void) | undefined@@ -143,7 +129,7 @@ export default function AlertsHistoryDataTable() {onColumnFiltersChange: setColumnFilters,onColumnVisibilityChange: setColumnVisibility,onRowSelectionChange: setRowSelection,- onPaginationChange: setPagination,+ onPaginationChange,state: {sorting,columnFilters,@@ -312,84 +298,7 @@ export default function AlertsHistoryDataTable() {</TableBody></Table></div>- <div className="flex items-center justify-between ps-1 tabular-nums">- <div className="text-muted-foreground hidden flex-1 text-sm lg:flex">- <Trans>- {table.getFilteredSelectedRowModel().rows.length} of {table.getFilteredRowModel().rows.length} row(s)- selected.- </Trans>- </div>- <div className="flex w-full items-center gap-8 lg:w-fit my-3">- <div className="hidden items-center gap-2 lg:flex">- <Label htmlFor="rows-per-page" className="text-sm font-medium">- <Trans>Rows per page</Trans>- </Label>- <Select- value={`${table.getState().pagination.pageSize}`}- onValueChange={(value) => {- table.setPageSize(Number(value));- }}- >- <SelectTrigger className="w-18" id="rows-per-page">- <SelectValue placeholder={table.getState().pagination.pageSize} />- </SelectTrigger>- <SelectContent side="top">- {[10, 20, 50, 100, 200].map((pageSize) => (- <SelectItem key={pageSize} value={`${pageSize}`}>- {pageSize}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- <div className="flex w-fit items-center justify-center text-sm font-medium">- <Trans>- Page {table.getState().pagination.pageIndex + 1} of {table.getPageCount()}- </Trans>- </div>- <div className="ms-auto flex items-center gap-2 lg:ms-0">- <Button- variant="outline"- className="hidden size-9 p-0 lg:flex"- onClick={() => table.setPageIndex(0)}- disabled={!table.getCanPreviousPage()}- >- <span className="sr-only">Go to first page</span>- <ChevronsLeftIcon className="size-5" />- </Button>- <Button- variant="outline"- className="size-9"- size="icon"- onClick={() => table.previousPage()}- disabled={!table.getCanPreviousPage()}- >- <span className="sr-only">Go to previous page</span>- <ChevronLeftIcon className="size-5" />- </Button>- <Button- variant="outline"- className="size-9"- size="icon"- onClick={() => table.nextPage()}- disabled={!table.getCanNextPage()}- >- <span className="sr-only">Go to next page</span>- <ChevronRightIcon className="size-5" />- </Button>- <Button- variant="outline"- className="hidden size-9 lg:flex"- size="icon"- onClick={() => table.setPageIndex(table.getPageCount() - 1)}- disabled={!table.getCanNextPage()}- >- <span className="sr-only">Go to last page</span>- <ChevronsRightIcon className="size-5" />- </Button>- </div>- </div>- </div>+ <DataTablePagination table={table} /></div>)}diff --git a/internal/site/src/components/routes/system/package-updates-table.tsx b/internal/site/src/components/routes/system/package-updates-table.tsxindex 1977946d6..fb6ce7f4e 100644--- a/internal/site/src/components/routes/system/package-updates-table.tsx+++ b/internal/site/src/components/routes/system/package-updates-table.tsx@@ -8,16 +8,11 @@ import {getFilteredRowModel,getPaginationRowModel,getSortedRowModel,- type PaginationState,type SortingState,useReactTable,} from "@tanstack/react-table"import {ArrowUpDownIcon,- ChevronLeftIcon,- ChevronRightIcon,- ChevronsLeftIcon,- ChevronsRightIcon,GitCompareArrowsIcon,PackageCheckIcon,PackageIcon,@@ -29,14 +24,13 @@ import { useEffect, useMemo, useState } from "react"import { Badge, type BadgeProps } from "@/components/ui/badge"import { Button } from "@/components/ui/button"import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"+import { DataTablePagination, usePagination } from "@/components/ui/data-table-pagination"import { Input } from "@/components/ui/input"-import { Label } from "@/components/ui/label"-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"import { Separator } from "@/components/ui/separator"import { TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"import { pb } from "@/lib/api"import { classifyVersionChange, type VersionChange } from "@/lib/package-updates"-import { cn, formatShortDate, useBrowserStorage } from "@/lib/utils"+import { cn, formatShortDate } from "@/lib/utils"import type { PackageUpdate, PackageUpdates } from "@/types"interface PackageUpdateRow extends PackageUpdate {@@ -54,8 +48,6 @@ const changeVariant: Record<VersionChange, BadgeProps["variant"]> = {other: "outline",}-const pageSizes = [10, 20, 50, 100, 200]-function changeLabel(change: VersionChange) {switch (change) {case "major":@@ -188,10 +180,7 @@ export default function PackageUpdatesTable({ systemId, counts }: { systemId: stconst [error, setError] = useState<string | null>(null)const [sorting, setSorting] = useState<SortingState>([{ id: "name", desc: false }])const [globalFilter, setGlobalFilter] = useState("")- // Store page size preference in local storage- const [pageSize, setPageSize] = useBrowserStorage("pu-page-size", pageSizes[1], sessionStorage)- const [pageIndex, setPageIndex] = useState(0)- const pagination = useMemo<PaginationState>(() => ({ pageIndex, pageSize }), [pageIndex, pageSize])+ const { pagination, onPaginationChange, resetPageIndex } = usePagination()useEffect(() => {let cancelled = false@@ -224,13 +213,16 @@ export default function PackageUpdatesTable({ systemId, counts }: { systemId: stgetSortedRowModel: getSortedRowModel(),getFilteredRowModel: getFilteredRowModel(),getPaginationRowModel: getPaginationRowModel(),- onSortingChange: setSorting,- onGlobalFilterChange: setGlobalFilter,- onPaginationChange: (updater) => {- const next = typeof updater === "function" ? updater(pagination) : updater- setPageIndex(next.pageIndex)- setPageSize(next.pageSize)+ onSortingChange: (updater) => {+ setSorting(updater)+ resetPageIndex()+ },+ onGlobalFilterChange: (value) => {+ setGlobalFilter(value)+ resetPageIndex()},+ autoResetPageIndex: false,+ onPaginationChange,state: { sorting, globalFilter, pagination },globalFilterFn: (row, _columnId, filterValue: string) => {const pkg = row.original@@ -284,7 +276,7 @@ export default function PackageUpdatesTable({ systemId, counts }: { systemId: st<Inputplaceholder={t`Filter...`}value={globalFilter}- onChange={(event) => setGlobalFilter(event.target.value)}+ onChange={(event) => table.setGlobalFilter(event.target.value)}className="px-4 w-full max-w-full md:w-64"/>{globalFilter && (@@ -294,7 +286,7 @@ export default function PackageUpdatesTable({ systemId, counts }: { systemId: stsize="icon"aria-label={t`Clear`}className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7 text-muted-foreground"- onClick={() => setGlobalFilter("")}+ onClick={() => table.setGlobalFilter("")}><XIcon className="h-4 w-4" /></Button>@@ -341,73 +333,7 @@ export default function PackageUpdatesTable({ systemId, counts }: { systemId: st</table></div>)}- {!error && rows.length > pageSizes[0] && (- <div className="flex items-center gap-8 mt-3 sm:mt-4 ps-1 tabular-nums">- <div className="hidden items-center gap-2 me-auto @xl:flex">- <Label htmlFor="pu-rows-per-page" className="text-sm font-medium">- <Trans>Rows per page</Trans>- </Label>- <Select value={`${pageSize}`} onValueChange={(value) => table.setPageSize(Number(value))}>- <SelectTrigger className="w-18" id="pu-rows-per-page">- <SelectValue placeholder={pageSize} />- </SelectTrigger>- <SelectContent side="top">- {pageSizes.map((size) => (- <SelectItem key={size} value={`${size}`}>- {size}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- <div className="flex w-fit items-center justify-center text-sm font-medium">- <Trans>- Page {pageIndex + 1} of {Math.max(table.getPageCount(), 1)}- </Trans>- </div>- <div className="ms-auto flex items-center gap-2 @xl:ms-0">- <Button- variant="outline"- className="hidden size-9 p-0 @xl:flex"- onClick={() => table.setPageIndex(0)}- disabled={!table.getCanPreviousPage()}- >- <span className="sr-only">Go to first page</span>- <ChevronsLeftIcon className="size-5" />- </Button>- <Button- variant="outline"- className="size-9"- size="icon"- onClick={() => table.previousPage()}- disabled={!table.getCanPreviousPage()}- >- <span className="sr-only">Go to previous page</span>- <ChevronLeftIcon className="size-5" />- </Button>- <Button- variant="outline"- className="size-9"- size="icon"- onClick={() => table.nextPage()}- disabled={!table.getCanNextPage()}- >- <span className="sr-only">Go to next page</span>- <ChevronRightIcon className="size-5" />- </Button>- <Button- variant="outline"- className="hidden size-9 @xl:flex"- size="icon"- onClick={() => table.setPageIndex(table.getPageCount() - 1)}- disabled={!table.getCanNextPage()}- >- <span className="sr-only">Go to last page</span>- <ChevronsRightIcon className="size-5" />- </Button>- </div>- </div>- )}+ {!error && <DataTablePagination table={table} showSelected={false} />}</Card>)}diff --git a/internal/site/src/components/routes/system/smart-table.tsx b/internal/site/src/components/routes/system/smart-table.tsxindex cf62a0c27..2c31b577f 100644--- a/internal/site/src/components/routes/system/smart-table.tsx+++ b/internal/site/src/components/routes/system/smart-table.tsx@@ -9,10 +9,10 @@ import {flexRender,getCoreRowModel,getFilteredRowModel,+ getPaginationRowModel,getSortedRowModel,useReactTable,} from "@tanstack/react-table"-import { useVirtualizer, type VirtualItem } from "@tanstack/react-virtual"import {Activity,Box,@@ -32,6 +32,7 @@ import {} from "lucide-react"import { Card, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet"+import { DataTablePagination, usePagination } from "@/components/ui/data-table-pagination"import { Input } from "@/components/ui/input"import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"import { Badge } from "@/components/ui/badge"@@ -61,7 +62,7 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu"-import { memo, useCallback, useMemo, useEffect, useRef, useState } from "react"+import { memo, useCallback, useMemo, useEffect, useState } from "react"import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"// Column definition for S.M.A.R.T. attributes table@@ -116,11 +117,7 @@ function formatDataUnits(units: number): string {const SMART_DEVICE_FIELDS = "id,system,name,model,state,capacity,temp,type,hours,cycles,updated"-export const createColumns = (- longestName: string,- longestModel: string,- longestDevice: string-): ColumnDef<SmartDeviceRecord>[] => [+export const createColumns = (): ColumnDef<SmartDeviceRecord>[] => [{id: "system",accessorFn: (record) => record.system,@@ -133,14 +130,7 @@ export const createColumns = (header: ({ column }) => <HeaderButton column={column} name={t`System`} Icon={ServerIcon} />,cell: ({ getValue }) => {const allSystems = useStore($allSystemsById)- return (- <div className="ms-1.5 relative w-fit max-w-44">- <span className="invisible block whitespace-nowrap" aria-hidden="true">- {longestName}- </span>- <span className="absolute inset-0 truncate">{allSystems[getValue() as string]?.name ?? ""}</span>- </div>- )+ return <div className="ms-1.5 max-w-44 truncate">{allSystems[getValue() as string]?.name ?? ""}</div>},},{@@ -148,11 +138,8 @@ export const createColumns = (sortingFn: (a, b) => a.original.name.localeCompare(b.original.name),header: ({ column }) => <HeaderButton column={column} name={t`Device`} Icon={HardDrive} />,cell: ({ getValue }) => (- <div className="font-medium ms-1 relative w-fit max-w-44" title={getValue() as string}>- <span className="invisible block whitespace-nowrap" aria-hidden="true">- {longestDevice}- </span>- <span className="absolute inset-0 truncate">{getValue() as string}</span>+ <div className="font-medium ms-1 max-w-44 truncate" title={getValue() as string}>+ {getValue() as string}</div>),},@@ -163,11 +150,8 @@ export const createColumns = (<HeaderButton column={column} name={t({ message: "Model", comment: "Device model" })} Icon={Box} />),cell: ({ getValue }) => (- <div className="ms-1 relative w-fit max-w-44" title={getValue() as string}>- <span className="invisible block whitespace-nowrap" aria-hidden="true">- {longestModel}- </span>- <span className="absolute inset-0 truncate">{getValue() as string}</span>+ <div className="ms-1 max-w-44 truncate" title={getValue() as string}>+ {getValue() as string}</div>),},@@ -307,7 +291,7 @@ export default function DisksTable({ systemId }: { systemId?: string }) {const [sheetOpen, setSheetOpen] = useState(false)const [rowActionState, setRowActionState] = useState<{ type: "refresh" | "delete"; id: string } | null>(null)const [globalFilter, setGlobalFilter] = useState("")- const allSystems = useStore($allSystemsById)+ const { pagination, onPaginationChange, resetPageIndex } = usePagination()// duplicate the devices to test with more rows// if (@@ -319,31 +303,6 @@ export default function DisksTable({ systemId }: { systemId?: string }) {// setSmartDevices([...smartDevices, ...smartDevices, ...smartDevices])// }- // Calculate the right width for the columns based on the longest strings among the displayed devices- const { longestName, longestModel, longestDevice } = useMemo(() => {- const result = { longestName: "", longestModel: "", longestDevice: "" }- if (!smartDevices || Object.keys(allSystems).length === 0) {- return result- }- const seenSystems = new Set<string>()- for (const device of smartDevices) {- if (!systemId && !seenSystems.has(device.system)) {- seenSystems.add(device.system)- const name = allSystems[device.system]?.name ?? ""- if (name.length > result.longestName.length) {- result.longestName = name- }- }- if ((device.model ?? "").length > result.longestModel.length) {- result.longestModel = device.model ?? ""- }- if ((device.name ?? "").length > result.longestDevice.length) {- result.longestDevice = device.name ?? ""- }- }- return result- }, [smartDevices, systemId, allSystems])-const openSheet = (disk: SmartDeviceRecord) => {setActiveDiskId(disk.id)setSheetOpen(true)@@ -508,27 +467,37 @@ export default function DisksTable({ systemId }: { systemId?: string }) {// Filter columns based on whether systemId is providedconst tableColumns = useMemo(() => {- const columns = createColumns(longestName, longestModel, longestDevice)+ const columns = createColumns()const baseColumns = systemId ? columns.filter((col) => col.id !== "system") : columnsreturn isReadOnlyUser() ? baseColumns : [...baseColumns, actionColumn]- }, [systemId, actionColumn, longestName, longestModel, longestDevice])+ }, [systemId, actionColumn])const table = useReactTable({data: smartDevices || ([] as SmartDeviceRecord[]),columns: tableColumns,- onSortingChange: setSorting,+ onSortingChange: (updater) => {+ setSorting(updater)+ resetPageIndex()+ },onColumnFiltersChange: setColumnFilters,getCoreRowModel: getCoreRowModel(),getSortedRowModel: getSortedRowModel(),getFilteredRowModel: getFilteredRowModel(),+ getPaginationRowModel: getPaginationRowModel(),+ autoResetPageIndex: false,+ onPaginationChange,onRowSelectionChange: setRowSelection,state: {sorting,columnFilters,rowSelection,globalFilter,+ pagination,+ },+ onGlobalFilterChange: (value) => {+ setGlobalFilter(value)+ resetPageIndex()},- onGlobalFilterChange: setGlobalFilter,globalFilterFn: (row, _columnId, filterValue) => {const disk = row.originalconst systemName = $allSystemsById.get()[disk.system]?.name ?? ""@@ -565,7 +534,7 @@ export default function DisksTable({ systemId }: { systemId?: string }) {<Inputplaceholder={t`Filter...`}value={globalFilter}- onChange={(event) => setGlobalFilter(event.target.value)}+ onChange={(event) => table.setGlobalFilter(event.target.value)}className="px-4 w-full max-w-full md:w-64"/>{globalFilter && (@@ -575,7 +544,7 @@ export default function DisksTable({ systemId }: { systemId?: string }) {size="icon"aria-label={t`Clear`}className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7 text-muted-foreground"- onClick={() => setGlobalFilter("")}+ onClick={() => table.setGlobalFilter("")}><XIcon className="h-4 w-4" /></Button>@@ -590,6 +559,7 @@ export default function DisksTable({ systemId }: { systemId?: string }) {data={smartDevices}openSheet={openSheet}/>+ <DataTablePagination table={table} showSelected={false} /></Card><DiskSheet diskId={activeDiskId} open={sheetOpen} onOpenChange={setSheetOpen} /></div>@@ -609,48 +579,24 @@ const SmartDevicesTable = memo(function SmartDevicesTable({data: SmartDeviceRecord[] | undefinedopenSheet: (disk: SmartDeviceRecord) => void}) {- const scrollRef = useRef<HTMLDivElement>(null)-- const virtualizer = useVirtualizer<HTMLDivElement, HTMLTableRowElement>({- count: rows.length,- estimateSize: () => 65,- getScrollElement: () => scrollRef.current,- overscan: 5,- })- const virtualRows = virtualizer.getVirtualItems()-- const paddingTop = Math.max(0, virtualRows[0]?.start ?? 0 - virtualizer.options.scrollMargin)- const paddingBottom = Math.max(0, virtualizer.getTotalSize() - (virtualRows[virtualRows.length - 1]?.end ?? 0))-return (- <div- className={cn(- "h-min max-h-[calc(100dvh-17rem)] max-w-full relative overflow-auto rounded-md border",- (!rows.length || rows.length > 2) && "min-h-50"- )}- ref={scrollRef}- >- <div style={{ height: `${virtualizer.getTotalSize() + 48}px`, paddingTop, paddingBottom }}>- <table className="w-full text-sm text-nowrap">- <SmartTableHead table={table} />- <TableBody>- {rows.length ? (- virtualRows.map((virtualRow) => {- const row = rows[virtualRow.index]- return <SmartDeviceTableRow key={row.id} row={row} virtualRow={virtualRow} openSheet={openSheet} />- })- ) : (- <TableCell colSpan={colLength} className="h-37 text-center pointer-events-none">- {data ? (- <Trans>No results.</Trans>- ) : (- <LoaderCircleIcon className="animate-spin size-10 opacity-60 mx-auto" />- )}- </TableCell>- )}- </TableBody>- </table>- </div>+ <div className="max-w-full relative overflow-auto rounded-md border">+ <table className="w-full text-sm text-nowrap">+ <SmartTableHead table={table} />+ <TableBody>+ {rows.length ? (+ rows.map((row) => <SmartDeviceTableRow key={row.id} row={row} openSheet={openSheet} />)+ ) : (+ <TableCell colSpan={colLength} className="h-37 text-center pointer-events-none">+ {data ? (+ <Trans>No results.</Trans>+ ) : (+ <LoaderCircleIcon className="animate-spin size-10 opacity-60 mx-auto" />+ )}+ </TableCell>+ )}+ </TableBody>+ </table></div>)})@@ -673,11 +619,9 @@ function SmartTableHead({ table }: { table: TableType<SmartDeviceRecord> }) {const SmartDeviceTableRow = memo(function SmartDeviceTableRow({row,- virtualRow,openSheet,}: {row: Row<SmartDeviceRecord>- virtualRow: VirtualItemopenSheet: (disk: SmartDeviceRecord) => void}) {return (@@ -691,7 +635,7 @@ const SmartDeviceTableRow = memo(function SmartDeviceTableRow({key={cell.id}className="md:ps-5 py-0"style={{- height: virtualRow.size,+ height: 65,}}>{flexRender(cell.column.columnDef.cell, cell.getContext())}diff --git a/internal/site/src/components/routes/system/storage-pools-table.tsx b/internal/site/src/components/routes/system/storage-pools-table.tsxindex 06d5c596b..491c71e50 100644--- a/internal/site/src/components/routes/system/storage-pools-table.tsx+++ b/internal/site/src/components/routes/system/storage-pools-table.tsx@@ -2,6 +2,7 @@ import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"import { Badge } from "@/components/ui/badge"import { Button } from "@/components/ui/button"import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"+import { DataTablePagination, usePagination } from "@/components/ui/data-table-pagination"import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"import { Input } from "@/components/ui/input"import { Separator } from "@/components/ui/separator"@@ -12,11 +13,12 @@ import { cn, formatBytes, formatShortDate, hourWithSeconds, toFixedFloat } fromimport type { ZfsDataset, ZfsPoolRecord, ZfsVdev } from "@/types"import { t } from "@lingui/core/macro"import { Trans } from "@lingui/react/macro"-import type { Column, ColumnDef } from "@tanstack/react-table"+import type { Column, ColumnDef, SortingState } from "@tanstack/react-table"import {flexRender,getCoreRowModel,getFilteredRowModel,+ getPaginationRowModel,getSortedRowModel,useReactTable,} from "@tanstack/react-table"@@ -449,6 +451,8 @@ function PoolSheet({export default function ZfsTable({ systemId }: { systemId?: string }) {const [zfsPools, setZfsPools] = useState<ZfsPoolRecord[]>()const [globalFilter, setGlobalFilter] = useState("")+ const [sorting, setSorting] = useState<SortingState>([{ id: "name", desc: false }])+ const { pagination, onPaginationChange, resetPageIndex } = usePagination()const [activePoolId, setActivePoolId] = useState<string | null>(null)const [sheetOpen, setSheetOpen] = useState(false)const [refreshingId, setRefreshingId] = useState<string | null>(null)@@ -591,12 +595,21 @@ export default function ZfsTable({ systemId }: { systemId?: string }) {const table = useReactTable({data: zfsPools || ([] as ZfsPoolRecord[]),columns: tableColumns,- initialState: { sorting: [{ id: "name", desc: false }] },getCoreRowModel: getCoreRowModel(),getSortedRowModel: getSortedRowModel(),getFilteredRowModel: getFilteredRowModel(),- state: { globalFilter },- onGlobalFilterChange: setGlobalFilter,+ getPaginationRowModel: getPaginationRowModel(),+ autoResetPageIndex: false,+ onPaginationChange,+ state: { sorting, globalFilter, pagination },+ onSortingChange: (updater) => {+ setSorting(updater)+ resetPageIndex()+ },+ onGlobalFilterChange: (value) => {+ setGlobalFilter(value)+ resetPageIndex()+ },globalFilterFn: (row, _columnId, filterValue) => {const pool = row.originalconst searchString = `${pool.display_name ?? ""} ${pool.name} ${poolType(pool)} ${pool.health ?? ""}`.toLowerCase()@@ -633,7 +646,7 @@ export default function ZfsTable({ systemId }: { systemId?: string }) {<Inputplaceholder={t`Filter...`}value={globalFilter}- onChange={(event) => setGlobalFilter(event.target.value)}+ onChange={(event) => table.setGlobalFilter(event.target.value)}className="px-4 w-full max-w-full md:w-64"/>{globalFilter && (@@ -643,7 +656,7 @@ export default function ZfsTable({ systemId }: { systemId?: string }) {size="icon"aria-label={t`Clear`}className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7 text-muted-foreground"- onClick={() => setGlobalFilter("")}+ onClick={() => table.setGlobalFilter("")}><XIcon className="h-4 w-4" /></Button>@@ -680,6 +693,7 @@ export default function ZfsTable({ systemId }: { systemId?: string }) {</TableBody></Table></div>+ <DataTablePagination table={table} showSelected={false} /></Card><PoolSheet poolId={activePoolId} open={sheetOpen} onOpenChange={setSheetOpen} /></div>diff --git a/internal/site/src/components/systemd-table/systemd-table.tsx b/internal/site/src/components/systemd-table/systemd-table.tsxindex 6197f5a66..531d6b944 100644--- a/internal/site/src/components/systemd-table/systemd-table.tsx+++ b/internal/site/src/components/systemd-table/systemd-table.tsx@@ -5,6 +5,7 @@ import {flexRender,getCoreRowModel,getFilteredRowModel,+ getPaginationRowModel,getSortedRowModel,type Row,type SortingState,@@ -12,13 +13,13 @@ import {useReactTable,type VisibilityState,} from "@tanstack/react-table"-import { useVirtualizer, type VirtualItem } from "@tanstack/react-virtual"import { LoaderCircleIcon, MaximizeIcon, RefreshCwIcon } from "lucide-react"import { listenKeys } from "nanostores"import { memo, type ReactNode, useEffect, useMemo, useRef, useState } from "react"import { getStatusColor, systemdTableCols } from "@/components/systemd-table/systemd-table-columns"import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"import { Card, CardHeader, CardTitle } from "@/components/ui/card"+import { DataTablePagination, usePagination } from "@/components/ui/data-table-pagination"import { Input } from "@/components/ui/input"import { LogsDisplay, LogsFullscreenDialog, LogsIconButton, LogsTimestampToggle } from "@/components/logs-display"import { getLogTimestampDecorations } from "@/lib/logs"@@ -61,9 +62,11 @@ export default function SystemdTable({ systemId }: { systemId?: string }) {const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([])const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})const [globalFilter, setGlobalFilter] = useState("")+ const { pagination, onPaginationChange, resetPageIndex } = usePagination()// clear old data when systemId changesuseEffect(() => {+ resetPageIndex()return setData([])}, [systemId])@@ -129,7 +132,13 @@ export default function SystemdTable({ systemId }: { systemId?: string }) {getCoreRowModel: getCoreRowModel(),getSortedRowModel: getSortedRowModel(),getFilteredRowModel: getFilteredRowModel(),- onSortingChange: setSorting,+ getPaginationRowModel: getPaginationRowModel(),+ autoResetPageIndex: false,+ onPaginationChange,+ onSortingChange: (updater) => {+ setSorting(updater)+ resetPageIndex()+ },onColumnFiltersChange: setColumnFilters,onColumnVisibilityChange: setColumnVisibility,defaultColumn: {@@ -142,8 +151,12 @@ export default function SystemdTable({ systemId }: { systemId?: string }) {columnFilters,columnVisibility,globalFilter,+ pagination,+ },+ onGlobalFilterChange: (value) => {+ setGlobalFilter(value)+ resetPageIndex()},- onGlobalFilterChange: setGlobalFilter,globalFilterFn: (row, _columnId, filterValue) => {const service = row.originalconst systemName = $allSystemsById.get()[service.system]?.name ?? ""@@ -193,7 +206,7 @@ export default function SystemdTable({ systemId }: { systemId?: string }) {<Inputplaceholder={t`Filter...`}value={globalFilter}- onChange={(e) => setGlobalFilter(e.target.value)}+ onChange={(e) => table.setGlobalFilter(e.target.value)}className="ms-auto px-4 w-full max-w-full md:w-64"/></div>@@ -201,6 +214,7 @@ export default function SystemdTable({ systemId }: { systemId?: string }) {<div className="rounded-md"><AllSystemdTable table={table} rows={rows} colLength={visibleColumns.length} systemId={systemId} /></div>+ <DataTablePagination table={table} showSelected={false} /></Card>)}@@ -216,8 +230,6 @@ const AllSystemdTable = memo(function AllSystemdTable({colLength: numbersystemId?: string}) {- // The virtualizer will need a reference to the scrollable container element- const scrollRef = useRef<HTMLDivElement>(null)const activeService = useRef<SystemdRecord | null>(null)const [sheetOpen, setSheetOpen] = useState(false)const [sheetSession, setSheetSession] = useState(0)@@ -227,46 +239,22 @@ const AllSystemdTable = memo(function AllSystemdTable({setSheetOpen(true)}- const virtualizer = useVirtualizer<HTMLDivElement, HTMLTableRowElement>({- count: rows.length,- estimateSize: () => 54,- getScrollElement: () => scrollRef.current,- overscan: 5,- })- const virtualRows = virtualizer.getVirtualItems()-- const paddingTop = Math.max(0, virtualRows[0]?.start ?? 0 - virtualizer.options.scrollMargin)- const paddingBottom = Math.max(0, virtualizer.getTotalSize() - (virtualRows[virtualRows.length - 1]?.end ?? 0))-return (- <div- className={cn(- "h-min max-h-[calc(100dvh-17rem)] max-w-full relative overflow-auto border rounded-md",- // don't set min height if there are less than 2 rows, do set if we need to display the empty state- (!rows.length || rows.length > 2) && "min-h-50"- )}- ref={scrollRef}- >- {/* add header height to table size */}- <div style={{ height: `${virtualizer.getTotalSize() + 48}px`, paddingTop, paddingBottom }}>- <table className="text-sm w-full h-full text-nowrap">- <SystemdTableHead table={table} />- <TableBody>- {rows.length ? (- virtualRows.map((virtualRow) => {- const row = rows[virtualRow.index]- return <SystemdTableRow key={row.id} row={row} virtualRow={virtualRow} openSheet={openSheet} />- })- ) : (- <TableRow>- <TableCell colSpan={colLength} className="h-37 text-center pointer-events-none">- <Trans>No results.</Trans>- </TableCell>- </TableRow>- )}- </TableBody>- </table>- </div>+ <div className="max-w-full relative overflow-auto border rounded-md">+ <table className="text-sm w-full h-full text-nowrap">+ <SystemdTableHead table={table} />+ <TableBody>+ {rows.length ? (+ rows.map((row) => <SystemdTableRow key={row.id} row={row} openSheet={openSheet} />)+ ) : (+ <TableRow>+ <TableCell colSpan={colLength} className="h-37 text-center pointer-events-none">+ <Trans>No results.</Trans>+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </table><SystemdSheetkey={sheetSession}sheetOpen={sheetOpen}@@ -757,11 +745,9 @@ function SystemdTableHead({ table }: { table: TableType<SystemdRecord> }) {const SystemdTableRow = memo(function SystemdTableRow({row,- virtualRow,openSheet,}: {row: Row<SystemdRecord>- virtualRow: VirtualItemopenSheet: (service: SystemdRecord) => void}) {return (@@ -775,7 +761,7 @@ const SystemdTableRow = memo(function SystemdTableRow({key={cell.id}className="py-0"style={{- height: virtualRow.size,+ height: 54,}}>{flexRender(cell.column.columnDef.cell, cell.getContext())}diff --git a/internal/site/src/components/systems-table/systems-table-columns.tsx b/internal/site/src/components/systems-table/systems-table-columns.tsxindex 0454fa939..890e99fa1 100644--- a/internal/site/src/components/systems-table/systems-table-columns.tsx+++ b/internal/site/src/components/systems-table/systems-table-columns.tsx@@ -27,7 +27,7 @@ import { memo, useMemo, useRef, useState } from "react"import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"import { isReadOnlyUser, pb } from "@/lib/api"import { BatteryState, ConnectionType, connectionTypeLabels, MeterState, SystemStatus } from "@/lib/enums"-import { $longestSystemName, $userSettings } from "@/lib/stores"+import { $userSettings } from "@/lib/stores"import {cn,copyToClipboard,@@ -146,7 +146,6 @@ export function SystemsTableColumns(viewMode: "table" | "grid"): ColumnDef<SysteIcon: ServerIcon,cell: (info) => {const { name, id } = info.row.original- const longestName = useStore($longestSystemName)const linkUrl = getPagePath($router, "system", { id })return (@@ -156,7 +155,7 @@ export function SystemsTableColumns(viewMode: "table" | "grid"): ColumnDef<Syste<Linkhref={linkUrl}tabIndex={-1}- className="relative w-fit max-w-48 z-10"+ className="relative block max-w-48 truncate z-10"onMouseEnter={(e) => {// set title on hover if text is truncated to show full nameconst a = e.currentTarget@@ -167,10 +166,7 @@ export function SystemsTableColumns(viewMode: "table" | "grid"): ColumnDef<Syste}}}>- <span className="invisible block" aria-hidden="true">- {longestName}- </span>- <span className="absolute inset-0 truncate">{name}</span>+ {name}</Link></span><Link href={linkUrl} className="inset-0 absolute size-full" aria-label={name}></Link>diff --git a/internal/site/src/components/systems-table/systems-table.tsx b/internal/site/src/components/systems-table/systems-table.tsxindex c533dad9d..96fc2befa 100644--- a/internal/site/src/components/systems-table/systems-table.tsx+++ b/internal/site/src/components/systems-table/systems-table.tsx@@ -9,6 +9,7 @@ import {flexRender,getCoreRowModel,getFilteredRowModel,+ getPaginationRowModel,getSortedRowModel,type Row,type SortingState,@@ -16,7 +17,6 @@ import {useReactTable,type VisibilityState,} from "@tanstack/react-table"-import { useVirtualizer, type VirtualItem } from "@tanstack/react-virtual"import {ArrowDownIcon,ArrowUpDownIcon,@@ -42,6 +42,7 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu"+import { DataTablePagination, usePagination } from "@/components/ui/data-table-pagination"import { Input } from "@/components/ui/input"import { TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"import { SystemStatus } from "@/lib/enums"@@ -79,6 +80,7 @@ export default function SystemsTable() {JSON.parse(sessionStorage.getItem("besz-sortMode") || "null") ?? [{ id: "system", desc: false }])const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([])+ const { pagination, onPaginationChange, resetPageIndex } = usePagination()const [columnVisibility, setColumnVisibility] = useState<VisibilityState>(() => $userSettings.get().cols ?? JSON.parse(localStorage.getItem("besz-cols") || "{}"))@@ -119,13 +121,17 @@ export default function SystemsTable() {[])- const handleStatusFilterChange = useCallback((value: string) => {- const next = value as StatusFilter- setStatusFilter(next)- localStorage.setItem("besz-statusFilter", JSON.stringify(next))- $userSettings.setKey("statusFilter", next)- queueUserSettings({ statusFilter: next })- }, [])+ const handleStatusFilterChange = useCallback(+ (value: string) => {+ const next = value as StatusFilter+ setStatusFilter(next)+ resetPageIndex()+ localStorage.setItem("besz-statusFilter", JSON.stringify(next))+ $userSettings.setKey("statusFilter", next)+ queueUserSettings({ statusFilter: next })+ },+ [resetPageIndex]+ )const handleViewModeChange = useCallback((view: string) => {const next = view as ViewMode@@ -135,15 +141,19 @@ export default function SystemsTable() {queueUserSettings({ viewMode: next })}, [])- const handleSortingChange = useCallback((updater: SortingState | ((prev: SortingState) => SortingState)) => {- setSorting((prev) => {- const next = typeof updater === "function" ? updater(prev) : updater- sessionStorage.setItem("besz-sortMode", JSON.stringify(next))- $userSettings.setKey("sortMode", next)- queueUserSettings({ sortMode: next })- return next- })- }, [])+ const handleSortingChange = useCallback(+ (updater: SortingState | ((prev: SortingState) => SortingState)) => {+ setSorting((prev) => {+ const next = typeof updater === "function" ? updater(prev) : updater+ sessionStorage.setItem("besz-sortMode", JSON.stringify(next))+ $userSettings.setKey("sortMode", next)+ queueUserSettings({ sortMode: next })+ return next+ })+ resetPageIndex()+ },+ [resetPageIndex]+ )const locale = i18n.locale@@ -172,6 +182,7 @@ export default function SystemsTable() {useEffect(() => {if (filter !== undefined) {table.getColumn("system")?.setFilterValue(filter)+ resetPageIndex()}}, [filter])@@ -185,11 +196,15 @@ export default function SystemsTable() {getSortedRowModel: getSortedRowModel(),onColumnFiltersChange: setColumnFilters,getFilteredRowModel: getFilteredRowModel(),+ getPaginationRowModel: getPaginationRowModel(),+ autoResetPageIndex: false,+ onPaginationChange,onColumnVisibilityChange: handleColumnVisibilityChange,state: {sorting,columnFilters,columnVisibility,+ pagination,},defaultColumn: {invertSorting: true,@@ -400,6 +415,7 @@ export default function SystemsTable() {)}</div>)}+ <DataTablePagination table={table} showSelected={false} /></Card>)}@@ -416,61 +432,28 @@ const AllSystemsTable = memo(colLength: numberisLoading: boolean}) => {- // The virtualizer will need a reference to the scrollable container element- const scrollRef = useRef<HTMLDivElement>(null)-- const virtualizer = useVirtualizer<HTMLDivElement, HTMLTableRowElement>({- count: rows.length,- estimateSize: () => (rows.length > 10 ? 56 : 60),- getScrollElement: () => scrollRef.current,- overscan: 5,- })- const virtualRows = virtualizer.getVirtualItems()-- const paddingTop = Math.max(0, virtualRows[0]?.start ?? 0 - virtualizer.options.scrollMargin)- const paddingBottom = Math.max(0, virtualizer.getTotalSize() - (virtualRows[virtualRows.length - 1]?.end ?? 0))-+ // based on all filtered rows rather than the current page, so every page uses the same height+ const rowHeight = table.getPrePaginationRowModel().rows.length > 10 ? 56 : 60return (- <div- className={cn(- "h-min max-h-[calc(100dvh-17rem)] max-w-full relative overflow-auto border rounded-md",- // don't set min height if there are less than 2 rows, do set if we need to display the empty state- (!rows.length || rows.length > 2) && "min-h-50"- )}- ref={scrollRef}- >- {/* add header height to table size */}- <div style={{ height: `${virtualizer.getTotalSize() + 50}px`, paddingTop, paddingBottom }}>- <table className="text-sm w-full h-full">- <SystemsTableHead table={table} />- <TableBody onMouseEnter={preloadSystemDetail}>- {rows.length ? (- virtualRows.map((virtualRow) => {- const row = rows[virtualRow.index] as Row<SystemRecord>- return (- <SystemTableRow- key={row.id}- row={row}- virtualRow={virtualRow}- length={rows.length}- colLength={colLength}- />- )- })- ) : (- <TableRow>- <TableCell colSpan={colLength} className="h-37 text-center pointer-events-none">- {isLoading ? (- <LoaderCircleIcon className="animate-spin size-10 opacity-60 mx-auto" />- ) : (- <Trans>No systems found.</Trans>- )}- </TableCell>- </TableRow>- )}- </TableBody>- </table>- </div>+ <div className="max-w-full relative overflow-auto border rounded-md">+ <table className="text-sm w-full h-full">+ <SystemsTableHead table={table} />+ <TableBody onMouseEnter={preloadSystemDetail}>+ {rows.length ? (+ rows.map((row) => <SystemTableRow key={row.id} row={row} rowHeight={rowHeight} colLength={colLength} />)+ ) : (+ <TableRow>+ <TableCell colSpan={colLength} className="h-37 text-center pointer-events-none">+ {isLoading ? (+ <LoaderCircleIcon className="animate-spin size-10 opacity-60 mx-auto" />+ ) : (+ <Trans>No systems found.</Trans>+ )}+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </table></div>)}@@ -496,16 +479,7 @@ function SystemsTableHead({ table }: { table: TableType<SystemRecord> }) {}const SystemTableRow = memo(- ({- row,- virtualRow,- colLength,- }: {- row: Row<SystemRecord>- virtualRow: VirtualItem- length: number- colLength: number- }) => {+ ({ row, rowHeight, colLength }: { row: Row<SystemRecord>; rowHeight: number; colLength: number }) => {const system = row.originalconst { t } = useLingui()return useMemo(() => {@@ -521,7 +495,7 @@ const SystemTableRow = memo(key={cell.id}style={{width: cell.column.getSize(),- height: virtualRow.size,+ height: rowHeight,}}className="py-0 ps-4.5">@@ -530,7 +504,7 @@ const SystemTableRow = memo())}</TableRow>)- }, [system, system.status, colLength, t])+ }, [system, system.status, colLength, rowHeight, t])})@@ -568,7 +542,10 @@ const SystemCard = memo(</div></CardHeader><CardContent className="text-sm px-5 pt-3.5 pb-4">- <div className="grid gap-2.5" style={{ gridTemplateColumns: "24px minmax(80px, max-content) minmax(0, 1fr)" }}>+ <div+ className="grid gap-2.5"+ style={{ gridTemplateColumns: "24px minmax(80px, max-content) minmax(0, 1fr)" }}+ >{table.getAllColumns().map((column) => {if (!column.getIsVisible() || column.id === "system" || column.id === "actions") return nullconst cell = row.getAllCells().find((cell) => cell.column.id === column.id)diff --git a/internal/site/src/components/ui/data-table-pagination.tsx b/internal/site/src/components/ui/data-table-pagination.tsxnew file mode 100644index 000000000..95c5be4ff--- /dev/null+++ b/internal/site/src/components/ui/data-table-pagination.tsx@@ -0,0 +1,168 @@+import { Trans } from "@lingui/react/macro"+import { useStore } from "@nanostores/react"+import type { PaginationState, Table, Updater } from "@tanstack/react-table"+import { ChevronLeftIcon, ChevronRightIcon, ChevronsLeftIcon, ChevronsRightIcon } from "lucide-react"+import { useCallback, useEffect, useId, useMemo, useState } from "react"+import { Button } from "@/components/ui/button"+import { Label } from "@/components/ui/label"+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"+import { atom } from "nanostores"++const defaultPageSizes = [10, 15, 20, 30, 40, 50, 100, 200]+const pageSizeKey = "besz-pageSize"++// The page size is stored per device in localStorage rather than in user settings by design.+// The right number of rows depends on screen size (e.g. 20 on desktop, 10 on a phone), so+// syncing it across devices would mean changing it every time you switch devices.+const $pageSize = atom<number>(getLocalPageSize())++/**+ * Pagination state for a table. The page size is shared by all tables on this device.+ * Pass `pagination` to table state and `onPaginationChange` to the table options along with+ * `autoResetPageIndex: false`, so realtime data updates don't jump back to the first page.+ * Call `resetPageIndex` when the filter or sort changes.+ */+export function usePagination() {+ const savedPageSize = useStore($pageSize)+ // saved sizes below the smallest option (e.g. the removed 5) fall back to the smallest option+ const pageSize = Math.max(savedPageSize, defaultPageSizes[0])+ const [pageIndex, setPageIndex] = useState(0)+ const pagination = useMemo<PaginationState>(() => ({ pageIndex, pageSize }), [pageIndex, pageSize])+ const onPaginationChange = useCallback(+ (updater: Updater<PaginationState>) => {+ const next = typeof updater === "function" ? updater(pagination) : updater+ setPageIndex(next.pageIndex)+ if (next.pageSize !== pageSize) {+ localStorage.setItem(pageSizeKey, JSON.stringify(next.pageSize))+ $pageSize.set(next.pageSize)+ }+ },+ [pagination, pageSize]+ )+ const resetPageIndex = useCallback(() => setPageIndex(0), [])+ return { pagination, onPaginationChange, resetPageIndex }+}++/** Page size saved on this device */+function getLocalPageSize(): number {+ try {+ return JSON.parse(localStorage.getItem(pageSizeKey) || "null") ?? 20+ } catch {+ return 20+ }+}++export function DataTablePagination<T>({+ table,+ pageSizes = defaultPageSizes,+ showSelected = true,+}: {+ table: Table<T>+ pageSizes?: number[]+ showSelected?: boolean+}) {+ const { pageIndex } = table.getState().pagination+ const pageCount = table.getPageCount()+ // unique per instance, since several tables can be on the same page+ const selectId = useId()++ // move back when the current page no longer exists (e.g. after rows are removed)+ useEffect(() => {+ if (pageIndex > 0 && pageIndex >= pageCount) {+ table.setPageIndex(Math.max(0, pageCount - 1))+ }+ }, [table, pageIndex, pageCount])++ // every page size option shows all rows, so there's nothing to paginate or change+ if (table.getFilteredRowModel().rows.length <= Math.min(...pageSizes)) {+ return null+ }++ return (+ // sections show based on the width of this container rather than the viewport,+ // since tables are often rendered in cards narrower than the screen+ <div className="@container mt-3.5">+ <div className="flex items-center gap-4 ps-1 tabular-nums @xl:gap-6 @3xl:gap-8">+ <div className="text-muted-foreground hidden flex-1 text-sm @3xl:flex">+ {showSelected ? (+ <Trans>+ {table.getFilteredSelectedRowModel().rows.length} of {table.getFilteredRowModel().rows.length} row(s)+ selected.+ </Trans>+ ) : (+ <Trans>{table.getFilteredRowModel().rows.length} row(s)</Trans>+ )}+ </div>+ <div className="hidden items-center gap-2 @xs:flex">+ <Label htmlFor={selectId} className="sr-only text-sm font-medium @xl:not-sr-only">+ <Trans>Rows per page</Trans>+ </Label>+ <Select+ value={`${table.getState().pagination.pageSize}`}+ onValueChange={(value) => {+ table.setPageSize(Number(value))+ }}+ >+ <SelectTrigger className="w-18" id={selectId}>+ <SelectValue placeholder={table.getState().pagination.pageSize} />+ </SelectTrigger>+ <SelectContent side="top">+ {pageSizes.map((pageSize) => (+ <SelectItem key={pageSize} value={`${pageSize}`}>+ {pageSize}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="text-sm font-medium whitespace-nowrap">+ <Trans>+ Page {pageIndex + 1} of {Math.max(1, pageCount)}+ </Trans>+ </div>+ <div className="ms-auto flex items-center gap-2 @3xl:ms-0">+ <Button+ variant="outline"+ className="hidden size-9 @md:flex"+ size="icon"+ onClick={() => table.setPageIndex(0)}+ disabled={!table.getCanPreviousPage()}+ >+ <span className="sr-only">Go to first page</span>+ <ChevronsLeftIcon className="size-5" />+ </Button>+ <Button+ variant="outline"+ className="size-9"+ size="icon"+ onClick={() => table.previousPage()}+ disabled={!table.getCanPreviousPage()}+ >+ <span className="sr-only">Go to previous page</span>+ <ChevronLeftIcon className="size-5" />+ </Button>+ <Button+ variant="outline"+ className="size-9"+ size="icon"+ onClick={() => table.nextPage()}+ disabled={!table.getCanNextPage()}+ >+ <span className="sr-only">Go to next page</span>+ <ChevronRightIcon className="size-5" />+ </Button>+ <Button+ variant="outline"+ className="hidden size-9 @md:flex"+ size="icon"+ onClick={() => table.setPageIndex(pageCount - 1)}+ disabled={!table.getCanNextPage()}+ >+ <span className="sr-only">Go to last page</span>+ <ChevronsRightIcon className="size-5" />+ </Button>+ </div>+ </div>+ </div>+ )+}diff --git a/internal/site/src/lib/stores.ts b/internal/site/src/lib/stores.tsindex 8cc357cf5..fc0d2905a 100644--- a/internal/site/src/lib/stores.ts+++ b/internal/site/src/lib/stores.ts@@ -103,11 +103,3 @@ export const $copyContent = atom("")/** Direction for localization */export const $direction = atom<"ltr" | "rtl">("ltr")--/** Longest system name string. Used to reserve width in virtualized tables. */-export const $longestSystemName = atom("")--/** Incremented when measured text widths are invalidated (e.g. web font finished loading).- * Anything that caches a comparison from isVisuallyLonger should recompute when this changes.- */-export const $textMeasureVersion = atom(0)diff --git a/internal/site/src/lib/systemsManager.ts b/internal/site/src/lib/systemsManager.tsindex 2e002074e..6e64d95ca 100644--- a/internal/site/src/lib/systemsManager.ts+++ b/internal/site/src/lib/systemsManager.ts@@ -5,13 +5,11 @@ import {$allSystemsById,$allSystemsByName,$downSystems,- $longestSystemName,$pausedSystems,$systemsLoaded,- $textMeasureVersion,$upSystems,} from "@/lib/stores"-import { isVisuallyLonger, updateFavicon } from "@/lib/utils"+import { updateFavicon } from "@/lib/utils"import type { SystemRecord } from "@/types"import { SystemStatus } from "./enums"@@ -43,7 +41,7 @@ export function init() {}if (!newSystem) {- onSystemsChanged(newSystems, newSystem, oldSystem)+ onSystemsChanged()return}@@ -67,41 +65,13 @@ export function init() {}// run things that need to be done when systems change- onSystemsChanged(newSystems, newSystem, oldSystem)+ onSystemsChanged()})-- // widths measured with the fallback font may rank names differently, so recompute once they're invalidated- $textMeasureVersion.listen(() => {- $longestSystemName.set(findLongestName($allSystemsById.get()))- })-}--/** Update the longest system name string and favicon based on system status */-function onSystemsChanged(systems: Record<string, SystemRecord>, newSystem?: SystemRecord, oldSystem?: SystemRecord) {- const downSystemsStore = $downSystems.get()- const downSystems = Object.values(downSystemsStore)-- // if the old system's old name was the longest, we need to find the new longest name- // otherwise, if the changed system's new name is longer than the current longest, update it- const longestName = $longestSystemName.get()- if (oldSystem?.name === longestName && oldSystem.name !== newSystem?.name) {- $longestSystemName.set(findLongestName(systems))- } else if (newSystem && newSystem.name !== longestName && isVisuallyLonger(newSystem.name, longestName)) {- $longestSystemName.set(newSystem.name)- }-- updateFavicon(downSystems.length)}-/** Find the visually longest system name */-function findLongestName(systems: Record<string, SystemRecord>): string {- let longest = ""- for (const id in systems) {- if (isVisuallyLonger(systems[id].name, longest)) {- longest = systems[id].name- }- }- return longest+/** Update the favicon based on system status */+function onSystemsChanged() {+ updateFavicon(Object.keys($downSystems.get()).length)}/** Fetch systems from collection */diff --git a/internal/site/src/lib/utils.ts b/internal/site/src/lib/utils.tsindex 4cd328228..cc70b93bf 100644--- a/internal/site/src/lib/utils.ts+++ b/internal/site/src/lib/utils.ts@@ -8,7 +8,7 @@ import { twMerge } from "tailwind-merge"import { toast } from "@/components/ui/use-toast"import type { ChartTimeData, FingerprintRecord, SemVer, SystemRecord } from "@/types"import { HourFormat, Unit } from "./enums"-import { $copyContent, $textMeasureVersion, $userSettings } from "./stores"+import { $copyContent, $userSettings } from "./stores"export function cn(...inputs: ClassValue[]) {return twMerge(clsx(inputs))@@ -464,92 +464,6 @@ export function runOnce<T extends (...args: any[]) => any>(fn: T): T {}) as T}-const visualWidthCache = new Map<string, number>()--let measureContext: CanvasRenderingContext2D | null | undefined-let measureFont = ""--/** Canvas context for measuring text in the font the app renders with, or null where canvas is unavailable.- * Only relative widths matter here, so the font size is arbitrary.- */-function getMeasureContext(): CanvasRenderingContext2D | null {- if (measureContext === undefined) {- measureContext = document.createElement("canvas").getContext("2d")- // the fallback font has different metrics, so re-measure whenever a font finishes loading.- // loadingdone also covers fonts that start loading after the first measurement,- // which fonts.ready does not if it has already resolved.- if (measureContext && "fonts" in document) {- document.fonts.addEventListener("loadingdone", invalidateVisualWidths)- }- }- if (measureContext) {- const { fontFamily, fontWeight } = getComputedStyle(document.body)- const font = `${fontWeight} 16px ${fontFamily}`- if (font !== measureFont) {- const isFirstFont = !measureFont- measureFont = font- measureContext.font = font- visualWidthCache.clear()- // defer so stores aren't updated in the middle of a comparison or a render- if (!isFirstFont) {- queueMicrotask(invalidateVisualWidths)- }- }- }- return measureContext-}--/** Drop cached widths and notify anything holding a result from isVisuallyLonger */-function invalidateVisualWidths() {- visualWidthCache.clear()- $textMeasureVersion.set($textMeasureVersion.get() + 1)-}--/** Get the visual width of a string, accounting for full-width and narrow punctuation characters.- * Don't use for monospaced fonts, use .length instead- */-function getVisualStringWidth(str: string): number {- const cached = visualWidthCache.get(str)- if (cached !== undefined) {- return cached- }- const measured = getMeasureContext()?.measureText(str).width- if (measured !== undefined) {- visualWidthCache.set(str, measured)- return measured- }- let width = 0- for (const char of str) {- if (char === ".") {- width += 0.7- continue- }- const code = char.codePointAt(0) || 0- // Hangul Jamo and Syllables are often slightly thinner than Hanzi/Kanji- if ((code >= 0x1100 && code <= 0x115f) || (code >= 0xac00 && code <= 0xd7af)) {- width += 1.8- continue- }- // Count CJK and other full-width characters as 2 units, others as 1- // Arabic and Cyrillic are counted as 1- const isFullWidth =- (code >= 0x2e80 && code <= 0x9fff) || // CJK Radicals, Symbols, and Ideographs- (code >= 0xf900 && code <= 0xfaff) || // CJK Compatibility Ideographs- (code >= 0xfe30 && code <= 0xfe6f) || // CJK Compatibility Forms- (code >= 0xff00 && code <= 0xff60) || // Fullwidth Forms- (code >= 0xffe0 && code <= 0xffe6) || // Fullwidth Symbols- code > 0xffff // Emojis and other supplementary plane characters- width += isFullWidth ? 2 : 1- }- visualWidthCache.set(str, width)- return width-}--/** Compare the visual width of two strings imprecisely */-export function isVisuallyLonger(str1: string, str2: string): boolean {- return getVisualStringWidth(str1) > getVisualStringWidth(str2)-}-/** Parses a filter string into OR'd groups of AND'd terms: "a b, c" -> [["a","b"], ["c"]] */export function parseFilterGroups(value: string): string[][] {return value