Skip to content
Niko Table

Transactions Ledger

A bank-style ledger that loads as you scroll: 20,000 transactions served 100 at a time by a fake server, a virtualized body, server-side search, category and type filters, money in and out totals, and a details panel with a copy ID button.

Built only from Niko Table pieces and shadcn/ui components. Install it, then swap the sample data for your own.

Installation

pnpm dlx shadcn@latest add @niko-table/transactions-table

Preview

npx shadcn@latest add @niko-table/transactions-table
transactions-table.tsx
"use client"
import * as React from "react"
import type { ColumnFiltersState, Updater } from "@tanstack/react-table"
import { DataTableRoot } from "@/components/niko-table/core/data-table-root"
import { DataTable } from "@/components/niko-table/core/data-table"
import {
DataTableVirtualizedBody,
DataTableVirtualizedEmptyBody,
DataTableVirtualizedHeader,
} from "@/components/niko-table/core/data-table-virtualized-structure"
import { useDataTable } from "@/components/niko-table/core/data-table-context"
import {
FILTER_OPERATORS,
FILTER_VARIANTS,
JOIN_OPERATORS,
} from "@/components/niko-table/lib/constants"
import { DataTableColumnHeader } from "@/components/niko-table/components/data-table-column-header"
import { DataTableColumnTitle } from "@/components/niko-table/components/data-table-column-title"
import { DataTableToolbarSection } from "@/components/niko-table/components/data-table-toolbar-section"
import { DataTableSearchFilter } from "@/components/niko-table/components/data-table-search-filter"
import { DataTableFacetedFilter } from "@/components/niko-table/components/data-table-faceted-filter"
import { DataTableClearFilter } from "@/components/niko-table/components/data-table-clear-filter"
import {
DataTableEmptyDescription,
DataTableEmptyFilteredMessage,
DataTableEmptyIcon,
DataTableEmptyMessage,
DataTableEmptyTitle,
} from "@/components/niko-table/components/data-table-empty-state"
import {
DataTableRowMenuScope,
RowMenuItem,
useDataTableRow,
} from "@/components/niko-table/components/data-table-row-menu"
import { DataTableRowContextMenuSlot } from "@/components/niko-table/components/data-table-row-context-menu-slot"
import type { DataTableColumnDef } from "@/components/niko-table/types"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/niko-table/primitives/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/components/niko-table/primitives/dropdown-menu"
import { Landmark, MoreHorizontal, SearchX } from "lucide-react"
import { cn } from "@/lib/utils"
import {
categoryOptions,
fetchTransactions,
PAGE_SIZE,
queryTransactions,
typeOptions,
type Transaction,
type TransactionCategory,
type TransactionPage,
type TransactionQuery,
} from "./transactions-data"
import {
amountStyle,
formatClock,
formatDay,
formatMoney,
formatSigned,
sameDay,
} from "./transactions-format"
import { TransactionSheet } from "./transaction-sheet"
// Row height = cell p-2 (16px) + tallest cell (description + account, 20px + 16px line heights = 36px) + 1px border-b. Change one, change all.
const ROW_HEIGHT = 53
const SEARCH_DEBOUNCE_MS = 300
type Actions = {
view: (transaction: Transaction) => void
copyId: (transaction: Transaction) => void
onlyCategory: (transaction: Transaction) => void
}
/*
* Row actions: one small piece per action, each reading its row from context.
* `TransactionsTable` composes them into ONE fragment that both the "⋯"
* dropdown and the right-click menu render.
*/
function ViewDetailsItem({ view }: Pick<Actions, "view">) {
const transaction = useDataTableRow<Transaction>()
return (
<RowMenuItem onClick={() => view(transaction)}>View details</RowMenuItem>
)
}
function CopyTransactionIdItem({ copyId }: Pick<Actions, "copyId">) {
const transaction = useDataTableRow<Transaction>()
return (
<RowMenuItem onClick={() => copyId(transaction)}>
Copy transaction ID
</RowMenuItem>
)
}
function ShowOnlyCategoryItem({ onlyCategory }: Pick<Actions, "onlyCategory">) {
const transaction = useDataTableRow<Transaction>()
const { table } = useDataTable<Transaction>()
const current = selectedValues(table.state.columnFilters, "category")
const already = current.length === 1 && current[0] === transaction.category
return (
<RowMenuItem disabled={already} onClick={() => onlyCategory(transaction)}>
Show only {transaction.category}
</RowMenuItem>
)
}
/** The values a faceted filter holds for one column. */
function selectedValues(filters: ColumnFiltersState, id: string): string[] {
const inner = (
filters.find(f => f.id === id)?.value as { value?: unknown } | undefined
)?.value
return Array.isArray(inner) ? inner.map(String) : []
}
/** Same shape the toolbar's faceted filter writes, so both stay in sync. */
function categoryFilter(category: TransactionCategory) {
return {
id: "category",
value: {
id: "category",
value: [category],
variant: FILTER_VARIANTS.MULTI_SELECT,
operator: FILTER_OPERATORS.IN,
filterId: "faceted-category",
joinOperator: JOIN_OPERATORS.AND,
},
}
}
function plainHeader() {
return (
<DataTableColumnHeader>
<DataTableColumnTitle />
</DataTableColumnHeader>
)
}
function rightHeader() {
return (
<DataTableColumnHeader className="justify-end">
<DataTableColumnTitle />
</DataTableColumnHeader>
)
}
function useTransactionColumns(rowMenu: React.ReactNode) {
return React.useMemo<DataTableColumnDef<Transaction>[]>(
() => [
{
accessorKey: "date",
meta: { label: "Date" },
header: plainHeader,
size: 130,
enableSorting: false,
cell: ({ row, table }) => {
// Show the day once, then a lighter time for the rest of that day.
const previous = table.getRowModel().rows[row.index - 1]?.original
const first = !previous || !sameDay(previous, row.original)
return (
<span className="flex flex-col leading-tight whitespace-nowrap">
<span
className={cn(
"text-sm",
first ? "font-medium" : "text-muted-foreground",
)}
>
{formatDay(row.original.date)}
</span>
<span className="text-xs text-muted-foreground tabular-nums">
{formatClock(row.original.date)} UTC
</span>
</span>
)
},
},
{
accessorKey: "description",
meta: { label: "Description" },
header: plainHeader,
size: 300,
enableSorting: false,
cell: ({ row }) => (
<span className="flex max-w-72 flex-col">
<span className="truncate text-sm">{row.original.description}</span>
<span className="truncate text-xs text-muted-foreground">
{row.original.account}
</span>
</span>
),
},
{
accessorKey: "category",
meta: { label: "Category", options: categoryOptions },
header: plainHeader,
size: 120,
enableSorting: false,
enableColumnFilter: true,
enableGlobalFilter: false,
cell: ({ row }) => (
<Badge variant="secondary">{row.original.category}</Badge>
),
},
{
accessorKey: "type",
// Hidden: backs the Type filter.
meta: { label: "Type", options: typeOptions },
enableColumnFilter: true,
enableHiding: false,
enableSorting: false,
enableGlobalFilter: false,
},
{
accessorKey: "amount",
meta: { label: "Amount" },
size: 130,
enableSorting: false,
enableGlobalFilter: false,
header: rightHeader,
cell: ({ row }) => (
<span
className={cn(
"block text-right text-sm font-medium whitespace-nowrap tabular-nums",
amountStyle(row.original),
)}
>
{formatSigned(row.original.amount)}
</span>
),
},
{
accessorKey: "balance",
meta: { label: "Balance" },
size: 130,
enableSorting: false,
enableGlobalFilter: false,
header: rightHeader,
cell: ({ row }) => (
<span className="block text-right text-sm whitespace-nowrap text-muted-foreground tabular-nums">
{formatMoney(row.original.balance)}
</span>
),
},
{
accessorKey: "status",
meta: { label: "Status" },
header: plainHeader,
size: 100,
enableSorting: false,
enableGlobalFilter: false,
cell: ({ row }) =>
row.original.status === "pending" ? (
<Badge variant="outline" className="border-warning/40 text-warning">
Pending
</Badge>
) : (
<span className="text-xs text-muted-foreground">Posted</span>
),
},
{
id: "actions",
size: 56,
enableSorting: false,
enableHiding: false,
cell: ({ row }) => (
<div className="flex justify-end">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="size-6"
aria-label={`Open actions for transaction ${row.original.id}`}
>
<MoreHorizontal className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DataTableRowMenuScope row={row.original} surface="dropdown">
{rowMenu}
</DataTableRowMenuScope>
</DropdownMenuContent>
</DropdownMenu>
</div>
),
},
],
[rowMenu],
)
}
function Stat({
label,
value,
tone,
}: {
label: string
value: string
tone?: string
}) {
return (
<div className="flex flex-col gap-0.5 rounded-lg border bg-background px-3 py-2">
<span className="text-xs text-muted-foreground">{label}</span>
<span className={cn("text-base font-semibold tabular-nums", tone)}>
{value}
</span>
</div>
)
}
/** Debounces a value so typing and filter clicks make one request. */
function useDebounced<T>(value: T, delay: number) {
const [debounced, setDebounced] = React.useState(value)
React.useEffect(() => {
const timer = setTimeout(() => setDebounced(value), delay)
return () => clearTimeout(timer)
}, [value, delay])
return debounced
}
type Loaded = TransactionPage & {
/** The query these rows answer. Paging continues with the same one. */
query: Omit<TransactionQuery, "cursor">
rows: Transaction[]
}
const firstQuery = { limit: PAGE_SIZE, search: "", category: [], type: [] }
export default function TransactionsTable() {
// The first page is ready on mount; later pages come from the fake server.
const [loaded, setLoaded] = React.useState<Loaded>(() => ({
...queryTransactions({ ...firstQuery, cursor: 0 }),
query: firstQuery,
}))
const [fetching, setFetching] = React.useState<"more" | "filters" | null>(
null,
)
const [search, setSearch] = React.useState<string | object>("")
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[],
)
const [viewing, setViewing] = React.useState<Transaction | null>(null)
const [lastAction, setLastAction] = React.useState("")
// Ignore any response that is not for the newest request.
const requestId = React.useRef(0)
// Set while a page is in flight, so a fast scroll cannot load it twice.
const busy = React.useRef(false)
// An end-of-list signal that arrived while busy; runs when the request settles.
const pendingMore = React.useRef(false)
const bodyRef = React.useRef<HTMLDivElement>(null)
const input = React.useMemo(
() => ({
search: typeof search === "string" ? search : "",
category: selectedValues(columnFilters, "category"),
type: selectedValues(columnFilters, "type"),
}),
[search, columnFilters],
)
const wanted = useDebounced(input, SEARCH_DEBOUNCE_MS)
// Key on the content, so a re-created but equal filter never refetches.
const queryKey = JSON.stringify({ limit: PAGE_SIZE, ...wanted })
const query = React.useMemo(
() => JSON.parse(queryKey) as Omit<TransactionQuery, "cursor">,
[queryKey],
)
const shownKey = React.useRef(JSON.stringify(firstQuery))
// A rejected request must not leave "Loading more…" stuck.
const fail = React.useCallback((id: number) => {
if (id !== requestId.current) return
busy.current = false
setFetching(null)
setLastAction("Could not load transactions")
}, [])
// Filters changed: start over from the first page.
React.useEffect(() => {
if (shownKey.current === queryKey) {
// Back to what is on screen: drop any request still in flight.
requestId.current++
busy.current = false
setFetching(null)
return
}
const id = ++requestId.current
busy.current = true
setFetching("filters")
void fetchTransactions({ ...query, cursor: 0 }).then(
page => {
if (id !== requestId.current) return
shownKey.current = queryKey
busy.current = false
pendingMore.current = false
setLoaded({ ...page, query })
setFetching(null)
// New list: start at the top so the old offset cannot trigger a page.
const scroller = bodyRef.current?.querySelector<HTMLElement>(
'[data-slot="table-container"]',
)
if (scroller) scroller.scrollTop = 0
},
() => fail(id),
)
}, [queryKey, query, fail])
// Scrolling near the end calls this. The footer button calls it too.
const loadMore = React.useCallback(() => {
if (loaded.nextCursor === null) return
if (busy.current) {
// onNearEnd fires once per approach, so remember it instead of dropping it.
pendingMore.current = true
return
}
const id = requestId.current
busy.current = true
setFetching("more")
void fetchTransactions({ ...loaded.query, cursor: loaded.nextCursor }).then(
page => {
if (id !== requestId.current) return
busy.current = false
setLoaded(prev => ({
...page,
query: prev.query,
rows: [...prev.rows, ...page.rows],
}))
setFetching(null)
},
() => fail(id),
)
}, [loaded.nextCursor, loaded.query, fail])
React.useEffect(() => {
if (fetching === null && pendingMore.current) {
pendingMore.current = false
loadMore()
}
}, [fetching, loadMore])
const actions = React.useMemo<Actions>(
() => ({
view: transaction => setViewing(transaction),
copyId: transaction => {
void navigator.clipboard?.writeText(transaction.id).catch(() => {})
setLastAction(`Copied ${transaction.id}`)
},
onlyCategory: transaction => {
setColumnFilters(prev => [
...prev.filter(f => f.id !== "category"),
categoryFilter(transaction.category),
])
setLastAction(`Showing only ${transaction.category}`)
},
}),
[],
)
// The row actions, composed ONCE and mounted in both the "⋯" dropdown and
// the right-click menu.
const rowMenu = React.useMemo(
() => (
<>
<ViewDetailsItem view={actions.view} />
<CopyTransactionIdItem copyId={actions.copyId} />
<ShowOnlyCategoryItem onlyCategory={actions.onlyCategory} />
</>
),
[actions],
)
const columns = useTransactionColumns(rowMenu)
const done = loaded.nextCursor === null
const footer =
fetching === "more"
? "Loading more…"
: fetching === "filters"
? "Updating…"
: done
? "End of list"
: ""
return (
<div className="w-full rounded-xl border bg-card p-4 text-card-foreground shadow-sm">
<DataTableRoot
data={loaded.rows}
columns={columns}
getRowId={transaction => transaction.id}
config={{ manualFiltering: true }}
state={{ globalFilter: search, columnFilters }}
onGlobalFilterChange={setSearch}
onColumnFiltersChange={(updater: Updater<ColumnFiltersState>) =>
setColumnFilters(updater)
}
initialState={{ columnVisibility: { type: false } }}
>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-0.5">
<h2 className="text-base font-semibold">Transactions</h2>
<p className="text-sm text-muted-foreground">
Loaded {loaded.rows.length.toLocaleString("en-US")} of{" "}
{loaded.total.toLocaleString("en-US")}. More load as you scroll.
</p>
</div>
<div className="grid grid-cols-1 gap-2 sm:grid-cols-3">
<Stat
label="Money in"
value={formatSigned(loaded.moneyIn)}
tone="text-success"
/>
<Stat label="Money out" value={formatSigned(loaded.moneyOut)} />
<Stat label="Current balance" value={formatMoney(loaded.balance)} />
</div>
<DataTableToolbarSection className="flex-wrap px-0">
<DataTableSearchFilter
placeholder="Search description, ID or account..."
className="min-w-48 flex-none sm:w-72"
/>
{/* Static options, no counts: the server holds the rows, so the loaded rows would hide options and give wrong numbers. */}
<DataTableFacetedFilter
accessorKey="category"
options={categoryOptions}
multiple
showCounts={false}
/>
<DataTableFacetedFilter
accessorKey="type"
options={typeOptions}
multiple
showCounts={false}
/>
<DataTableClearFilter />
</DataTableToolbarSection>
{/* 20,000 transactions on the server, 100 per page, windowed here. */}
<div ref={bodyRef}>
<DataTable
height={560}
className={cn(
"rounded-lg border",
fetching === "filters" && "opacity-60",
)}
>
<DataTableVirtualizedHeader />
<DataTableVirtualizedBody<Transaction>
estimateSize={ROW_HEIGHT}
fixedRowHeight
prefetchThreshold={15}
onNearEnd={loadMore}
onRowClick={transaction => setViewing(transaction)}
>
<DataTableRowContextMenuSlot>
{rowMenu}
</DataTableRowContextMenuSlot>
<DataTableVirtualizedEmptyBody>
<DataTableEmptyMessage>
<DataTableEmptyIcon>
<Landmark className="size-12" />
</DataTableEmptyIcon>
<DataTableEmptyTitle>
No transactions yet
</DataTableEmptyTitle>
<DataTableEmptyDescription>
Money in and out shows up here.
</DataTableEmptyDescription>
</DataTableEmptyMessage>
<DataTableEmptyFilteredMessage>
<DataTableEmptyIcon>
<SearchX className="size-12" />
</DataTableEmptyIcon>
<DataTableEmptyTitle>
No matching transactions
</DataTableEmptyTitle>
<DataTableEmptyDescription>
Try a different search or clear the filters.
</DataTableEmptyDescription>
</DataTableEmptyFilteredMessage>
</DataTableVirtualizedEmptyBody>
</DataTableVirtualizedBody>
</DataTable>
</div>
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
<p aria-live="polite">{footer}</p>
{!done && fetching === null && (
<Button variant="ghost" size="sm" onClick={loadMore}>
Load more
</Button>
)}
</div>
{lastAction && (
<p className="text-xs text-muted-foreground" aria-live="polite">
{lastAction}
</p>
)}
</div>
</DataTableRoot>
<TransactionSheet
transaction={viewing}
onOpenChange={open => !open && setViewing(null)}
onCopyId={actions.copyId}
/>
</div>
)
}
transaction-sheet.tsx
"use client"
import * as React from "react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/niko-table/primitives/button"
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/niko-table/primitives/sheet"
import { Check, Copy } from "lucide-react"
import { cn } from "@/lib/utils"
import type { Transaction } from "./transactions-data"
import {
amountStyle,
formatClock,
formatDay,
formatMoney,
formatSigned,
} from "./transactions-format"
function DetailRow({
label,
children,
}: {
label: string
children: React.ReactNode
}) {
return (
<div className="flex items-center justify-between gap-4 py-2 text-sm">
<dt className="text-muted-foreground">{label}</dt>
<dd className="min-w-0 text-right">{children}</dd>
</div>
)
}
/** Side panel with one transaction's details. Opens on row click. */
export function TransactionSheet({
transaction,
onOpenChange,
onCopyId,
}: {
transaction: Transaction | null
onOpenChange: (open: boolean) => void
onCopyId: (transaction: Transaction) => void
}) {
const [copied, setCopied] = React.useState(false)
return (
<Sheet
open={transaction !== null}
onOpenChange={open => {
if (!open) setCopied(false)
onOpenChange(open)
}}
>
<SheetContent className="flex w-full flex-col gap-0 sm:max-w-md">
{transaction && (
<>
<SheetHeader className="border-b">
<SheetTitle>{transaction.description}</SheetTitle>
<SheetDescription>
{formatDay(transaction.date)} at {formatClock(transaction.date)}{" "}
UTC
</SheetDescription>
</SheetHeader>
<div className="flex flex-1 flex-col gap-6 overflow-y-auto p-4">
<p
className={cn(
"text-3xl font-semibold tabular-nums",
amountStyle(transaction),
)}
>
{formatSigned(transaction.amount)}
</p>
<dl className="divide-y">
<DetailRow label="Transaction ID">
<span className="font-mono text-xs">{transaction.id}</span>
</DetailRow>
<DetailRow label="Category">
<Badge variant="secondary">{transaction.category}</Badge>
</DetailRow>
<DetailRow label="Type">
<span className="capitalize">{transaction.type}</span>
</DetailRow>
<DetailRow label="Status">
<span className="capitalize">{transaction.status}</span>
</DetailRow>
<DetailRow label="Account">{transaction.account}</DetailRow>
<DetailRow label="Balance after">
<span className="tabular-nums">
{formatMoney(transaction.balance)}
</span>
</DetailRow>
</dl>
<Button
variant="outline"
onClick={() => {
onCopyId(transaction)
setCopied(true)
}}
>
{copied ? <Check /> : <Copy />}
Copy transaction ID
</Button>
</div>
</>
)}
</SheetContent>
</Sheet>
)
}
transactions-format.ts
import type { Transaction } from "./transactions-data"
const money = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
})
/** Cents to "$1,234.50". */
export function formatMoney(cents: number) {
return money.format(cents / 100)
}
/** Cents to "+$12.00" or "-$12.00". */
export function formatSigned(cents: number) {
return `${cents > 0 ? "+" : cents < 0 ? "-" : ""}${money.format(Math.abs(cents) / 100)}`
}
const dayFormat = new Intl.DateTimeFormat("en-US", {
month: "short",
day: "numeric",
year: "numeric",
timeZone: "UTC",
})
/** "Nov 2, 2026" (UTC, so the sample reads the same everywhere). */
export function formatDay(timestamp: number) {
return dayFormat.format(timestamp)
}
/** "14:03" (UTC). */
export function formatClock(timestamp: number) {
return new Date(timestamp).toISOString().slice(11, 16)
}
/** True when two transactions fall on the same UTC day. */
export function sameDay(a: Transaction, b: Transaction) {
return a.date - (a.date % 86_400_000) === b.date - (b.date % 86_400_000)
}
export function amountStyle(transaction: Transaction) {
return transaction.type === "credit" ? "text-success" : "text-foreground"
}
transactions-data.ts
export type TransactionCategory =
| "Groceries"
| "Rent"
| "Salary"
| "Transport"
| "Dining"
| "Utilities"
| "Software"
| "Transfers"
export type TransactionType = "debit" | "credit"
export type TransactionStatus = "posted" | "pending"
export type Transaction = {
id: string
/** Milliseconds since the epoch. */
date: number
description: string
category: TransactionCategory
type: TransactionType
/** Cents. Credits are positive, debits negative. */
amount: number
/** Account balance in cents after this transaction. */
balance: number
status: TransactionStatus
account: string
}
export type TransactionQuery = {
/** Index into the filtered list, 0 for the first page. */
cursor: number
limit: number
search?: string
category?: TransactionCategory[]
type?: TransactionType[]
}
export type TransactionPage = {
rows: Transaction[]
/** `null` when there is nothing after this page. */
nextCursor: number | null
/** Rows matching the filters, across all pages. */
total: number
/** The account's current balance in cents. Not affected by filters. */
balance: number
/** Sum of incoming amounts (cents) for the current filters, across all pages. */
moneyIn: number
/** Sum of outgoing amounts (cents, negative) for the current filters. */
moneyOut: number
}
/** Fixed "now" for the sample data, so the ledger never drifts. */
export const NOW = Date.UTC(2026, 10, 2, 12, 0, 0, 0)
export const TRANSACTION_COUNT = 20_000
export const PAGE_SIZE = 100
export const FAKE_LATENCY_MS = 350
/** Roughly 18 months of history. */
const SPAN_MS = 548 * 24 * 60 * 60 * 1000
const STEP_MS = SPAN_MS / TRANSACTION_COUNT
/** Only the newest few transactions have not posted yet. */
const PENDING_COUNT = 6
export const categoryOptions = [
{ label: "Groceries", value: "Groceries" },
{ label: "Rent", value: "Rent" },
{ label: "Salary", value: "Salary" },
{ label: "Transport", value: "Transport" },
{ label: "Dining", value: "Dining" },
{ label: "Utilities", value: "Utilities" },
{ label: "Software", value: "Software" },
{ label: "Transfers", value: "Transfers" },
]
export const typeOptions = [
{ label: "Credit (money in)", value: "credit" },
{ label: "Debit (money out)", value: "debit" },
]
const accounts = ["Everyday ••4821", "Savings ••7305"] as const
/** Merchants and payees are invented. */
const merchants: Record<TransactionCategory, string[]> = {
Groceries: [
"Larkfield Market",
"Basil & Barrel Grocer",
"Fernhill Fresh Foods",
"Corner Crate Co-op",
"Tidewater Produce",
],
Rent: ["Alder Court Rent", "Maple Row Lettings"],
Salary: ["Brightwave Studio payroll", "Quillon Labs payroll"],
Transport: [
"Northline Transit",
"Ridgeway Fuel",
"Pedal & Co bike share",
"Harbor Cab",
"Skyhop Rail pass",
],
Dining: [
"Saffron Table",
"The Copper Kettle",
"Noodle Lantern",
"Birchwood Bakery",
"Little Ember Pizza",
"Juniper Coffee Bar",
],
Utilities: [
"Brookside Power",
"ClearStream Water",
"Halcyon Fibre internet",
"Mobile Meadow phone plan",
],
Software: [
"Notewise subscription",
"Pixelforge cloud storage",
"Tallyhub accounting",
"Mintbox music",
"Quillon Labs license",
],
Transfers: [
"Transfer to Savings",
"Transfer from Savings",
"Transfer to Sam",
],
}
const categoryWeights: [TransactionCategory, number][] = [
["Groceries", 22],
["Dining", 20],
["Transport", 16],
["Transfers", 14],
["Utilities", 9],
["Software", 9],
["Salary", 6],
["Rent", 4],
]
const weightTotal = categoryWeights.reduce((sum, [, w]) => sum + w, 0)
/** Cents: [min, max] for the amount of one transaction. */
const amountRange: Record<TransactionCategory, [number, number]> = {
Groceries: [900, 18_000],
Rent: [165_000, 165_000],
Salary: [150_000, 240_000],
Transport: [250, 7_500],
Dining: [600, 9_500],
Utilities: [3_500, 14_000],
Software: [499, 6_900],
Transfers: [2_000, 60_000],
}
/**
* Sample data, generated rather than hand-written. Row `i` is derived from a
* seeded hash of `i` (mulberry32 mixing), so any page can be produced on its
* own without building the other rows. Swap `fetchTransactions` for your API.
*/
function seededRandom(seed: number) {
let a = seed
return () => {
a = (a + 0x6d2b79f5) | 0
let t = Math.imul(a ^ (a >>> 15), 1 | a)
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
const SEED = 20261102
/** A deterministic stream of numbers for row `index`. */
function streamFor(index: number) {
return seededRandom(SEED + Math.imul(index + 1, 0x9e3779b1))
}
type Skeleton = {
category: TransactionCategory
type: TransactionType
amount: number
account: string
merchant: string
jitter: number
}
/** The cheap part of a row: enough to filter and to build balances. */
function skeletonAt(index: number): Skeleton {
const random = streamFor(index)
random() // the first draw correlates with small seeds; skip it
let pickWeight = random() * weightTotal
let category: TransactionCategory = "Groceries"
for (const [name, weight] of categoryWeights) {
pickWeight -= weight
if (pickWeight < 0) {
category = name
break
}
}
const names = merchants[category]
const merchant =
names[Math.floor(random() * names.length)] ?? "Larkfield Market"
const [lo, hi] = amountRange[category]
const magnitude = Math.round((lo + random() * (hi - lo)) / 100) * 100 || lo
const refund =
category !== "Salary" && category !== "Transfers" && random() < 0.04
const credit =
category === "Salary" ||
refund ||
(category === "Transfers" && merchant === "Transfer from Savings")
return {
category,
type: credit ? "credit" : "debit",
amount: credit ? magnitude : -magnitude,
account: random() < 0.82 ? accounts[0] : accounts[1],
merchant: refund ? `Refund: ${merchant}` : merchant,
jitter: random() * STEP_MS * 0.5,
}
}
const skeleton = skeletonAt
let balances: Int32Array | undefined
/** Running balances, newest first. Built once, as numbers only (80 KB), not as row objects. */
function balanceAt(index: number) {
if (!balances) {
const raw = new Float64Array(TRANSACTION_COUNT)
let sum = 0
let min = 0
for (let i = TRANSACTION_COUNT - 1; i >= 0; i--) {
sum += skeleton(i).amount
raw[i] = sum
min = Math.min(min, sum)
}
// Start high enough that the account never goes below $1,500.
const start = 150_000 - min
balances = Int32Array.from(raw, value => value + start)
}
return balances[index] ?? 0
}
/** Transaction `index`, where 0 is the newest. */
export function transactionAt(index: number): Transaction {
const s = skeleton(index)
return {
id: `TX-${String(TRANSACTION_COUNT - index).padStart(6, "0")}`,
date: Math.round(NOW - index * STEP_MS - s.jitter),
description: s.merchant,
category: s.category,
type: s.type,
amount: s.amount,
balance: balanceAt(index),
status: index < PENDING_COUNT ? "pending" : "posted",
account: s.account,
}
}
function matches(index: number, query: TransactionQuery) {
const s = skeleton(index)
if (query.category?.length && !query.category.includes(s.category))
return false
if (query.type?.length && !query.type.includes(s.type)) return false
const term = query.search?.trim().toLowerCase()
if (!term) return true
const id = TRANSACTION_COUNT - index
return (
s.merchant.toLowerCase().includes(term) ||
`tx-${String(id).padStart(6, "0")}`.includes(term) ||
s.account.toLowerCase().includes(term)
)
}
/** The server's work, without the delay. Also used for the first page. */
export function queryTransactions(query: TransactionQuery): TransactionPage {
const hits: number[] = []
let moneyIn = 0
let moneyOut = 0
for (let i = 0; i < TRANSACTION_COUNT; i++) {
if (!matches(i, query)) continue
hits.push(i)
const amount = skeleton(i).amount
if (amount > 0) moneyIn += amount
else moneyOut += amount
}
const start = Math.max(0, query.cursor)
const slice = hits.slice(start, start + query.limit)
const end = start + slice.length
return {
rows: slice.map(transactionAt),
nextCursor: end < hits.length ? end : null,
total: hits.length,
balance: balanceAt(0),
moneyIn,
moneyOut,
}
}
/** Fake server call: the same answer as `queryTransactions`, after a delay. */
export function fetchTransactions(
query: TransactionQuery,
): Promise<TransactionPage> {
return new Promise(resolve => {
setTimeout(() => resolve(queryTransactions(query)), FAKE_LATENCY_MS)
})
}

Usage

The files land in components/transactions-table/. Render the block anywhere:

import TransactionsLedger from "@/components/transactions-table/transactions-table"
export default function Page() {
return <TransactionsLedger />
}

Then replace the generated rows in transactions-data.ts with your own data, or load it from your API and pass it in.