Shipments
A wide logistics table you shape yourself: drag-resizable columns with saved widths, pin left / right / unpin and hide from each column menu, a Reset layout button, route and late ETA cells, and copy ID / mark delivered / flag exception actions.
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/shipments-tablePreview
"use client"
import * as React from "react"import { DataTableRoot } from "@/components/niko-table/core/data-table-root"import { DataTable } from "@/components/niko-table/core/data-table"import { DataTableBody, DataTableEmptyBody, DataTableHeader,} from "@/components/niko-table/core/data-table-structure"import { useDataTable } from "@/components/niko-table/core/data-table-context"import { DataTableColumnHeader } from "@/components/niko-table/components/data-table-column-header"import { DataTableColumnTitle } from "@/components/niko-table/components/data-table-column-title"import { DataTableColumnActions } from "@/components/niko-table/components/data-table-column-actions"import { DataTableColumnSortOptions } from "@/components/niko-table/components/data-table-column-sort"import { DataTableColumnPinOptions } from "@/components/niko-table/components/data-table-column-pin"import { DataTableColumnHideOptions } from "@/components/niko-table/components/data-table-column-hide"import { DataTableColumnResize } from "@/components/niko-table/components/data-table-column-resize"import { useColumnSizingPersistence } from "@/components/niko-table/lib/use-column-sizing-persistence"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 { DataTableViewMenu } from "@/components/niko-table/components/data-table-view-menu"import { DataTablePagination } from "@/components/niko-table/components/data-table-pagination"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 { FILTER_VARIANTS } from "@/components/niko-table/lib/constants"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 { ArrowRight, MoreHorizontal, PackageX, SearchX } from "lucide-react"import { cn } from "@/lib/utils"import { carrierOptions, isLate, isToday, NOW, serviceOptions, shipments as sampleShipments, statusOptions, type Shipment,} from "./shipments-data"import { formatCost, formatDay, formatWeight, statusDot, statusLabel,} from "./shipments-format"import { SIZING_KEY, useLayoutPersistence } from "./shipments-layout"
type Actions = { copyId: (shipment: Shipment) => void markDelivered: (shipment: Shipment) => void flagException: (shipment: Shipment) => void}
/* * Row actions: one small piece per action, each reading its row from context. * `ShipmentsTable` composes them into ONE fragment that both the "⋯" dropdown * and the right-click menu render. */function CopyIdItem({ copyId }: Pick<Actions, "copyId">) { const shipment = useDataTableRow<Shipment>() return ( <RowMenuItem onClick={() => copyId(shipment)}>Copy tracking ID</RowMenuItem> )}
function MarkDeliveredItem({ markDelivered }: Pick<Actions, "markDelivered">) { const shipment = useDataTableRow<Shipment>() return ( <RowMenuItem disabled={shipment.status === "delivered"} onClick={() => markDelivered(shipment)} > Mark delivered </RowMenuItem> )}
function FlagExceptionItem({ flagException }: Pick<Actions, "flagException">) { const shipment = useDataTableRow<Shipment>() return ( <RowMenuItem variant="destructive" disabled={ shipment.status === "delivered" || shipment.status === "exception" } onClick={() => flagException(shipment)} > Flag exception </RowMenuItem> )}
/** Every header: sort, pin left / right / unpin, hide. Numbers align right. */function columnHeader(align: "start" | "end" = "start") { return ( <DataTableColumnHeader className={cn(align === "end" && "justify-end")}> <DataTableColumnTitle /> <DataTableColumnActions> <DataTableColumnSortOptions /> <DataTableColumnPinOptions /> <DataTableColumnHideOptions /> </DataTableColumnActions> </DataTableColumnHeader> )}
/* * Default sizes are deliberate: narrow numbers, a wide route. Column ids are * the keys of the saved widths, pinning and visibility. */function useShipmentColumns(rowMenu: React.ReactNode) { return React.useMemo<DataTableColumnDef<Shipment>[]>( () => [ { id: "tracking", accessorKey: "id", size: 130, meta: { label: "Tracking ID" }, header: () => columnHeader(), cell: ({ row }) => ( <span className="font-medium whitespace-nowrap tabular-nums"> {row.original.id} </span> ), }, { id: "route", // Both cities, so search finds either end. accessorFn: s => `${s.origin} ${s.destination}`, size: 280, meta: { label: "Route" }, header: () => columnHeader(), cell: ({ row }) => ( <span className="flex min-w-0 items-center gap-1.5"> <span className="truncate">{row.original.origin}</span> <ArrowRight className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" /> <span className="sr-only">to</span> <span className="truncate">{row.original.destination}</span> </span> ), }, { accessorKey: "carrier", size: 180, meta: { label: "Carrier", options: carrierOptions }, enableColumnFilter: true, header: () => columnHeader(), cell: ({ row }) => ( <span className="truncate">{row.original.carrier}</span> ), }, { accessorKey: "service", size: 110, meta: { label: "Service", options: serviceOptions }, enableColumnFilter: true, header: () => columnHeader(), cell: ({ row }) => ( <Badge variant="outline" className="capitalize"> {row.original.service} </Badge> ), }, { accessorKey: "status", size: 160, meta: { label: "Status", options: statusOptions }, enableColumnFilter: true, header: () => columnHeader(), cell: ({ row }) => ( <Badge variant="secondary" className="gap-1.5 whitespace-nowrap"> <span className={cn( "size-2 rounded-full", statusDot[row.original.status], )} aria-hidden="true" /> {statusLabel[row.original.status]} </Badge> ), }, { accessorKey: "shippedAt", size: 110, meta: { label: "Shipped", variant: FILTER_VARIANTS.DATE }, header: () => columnHeader(), cell: ({ row }) => ( <span className="whitespace-nowrap text-muted-foreground tabular-nums"> {formatDay(row.original.shippedAt)} </span> ), }, { accessorKey: "eta", size: 130, meta: { label: "ETA", variant: FILTER_VARIANTS.DATE }, header: () => columnHeader(), cell: ({ row }) => { const late = isLate(row.original) return ( <span className={cn( "whitespace-nowrap tabular-nums", late && "font-medium text-destructive", )} > {formatDay(row.original.eta)} {late && <span className="sr-only"> (late)</span>} </span> ) }, }, { accessorKey: "weightKg", size: 100, meta: { label: "Weight", variant: FILTER_VARIANTS.NUMBER }, header: () => columnHeader("end"), cell: ({ row }) => ( <div className="text-right whitespace-nowrap tabular-nums"> {formatWeight(row.original.weightKg)} </div> ), }, { accessorKey: "pieces", size: 80, meta: { label: "Pieces", variant: FILTER_VARIANTS.NUMBER }, header: () => columnHeader("end"), cell: ({ row }) => ( <div className="text-right tabular-nums">{row.original.pieces}</div> ), }, { accessorKey: "costUsd", size: 110, meta: { label: "Cost", variant: FILTER_VARIANTS.NUMBER }, header: () => columnHeader("end"), cell: ({ row }) => ( <div className="text-right whitespace-nowrap tabular-nums"> {formatCost(row.original.costUsd)} </div> ), }, { accessorKey: "recipient", size: 190, meta: { label: "Recipient" }, header: () => columnHeader(), cell: ({ row }) => ( <span className="truncate">{row.original.recipient}</span> ), }, { accessorKey: "reference", size: 130, meta: { label: "Reference" }, header: () => columnHeader(), cell: ({ row }) => ( <span className="whitespace-nowrap text-muted-foreground tabular-nums"> {row.original.reference} </span> ), }, { // Pinned to the end: the menu is always reachable. id: "actions", size: 56, enableSorting: false, enableHiding: false, enableResizing: false, header: () => <span className="sr-only">Actions</span>, cell: ({ row }) => ( <div className="flex justify-end"> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" size="icon" className="size-8" aria-label={`Open actions for ${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 ShipmentsHeader() { const { table } = useDataTable<Shipment>() const rows = table.getCoreRowModel().rows.map(row => row.original) const inTransit = rows.filter( s => s.status === "in-transit" || s.status === "out-for-delivery", ).length const deliveredToday = rows.filter(s => isToday(s.deliveredAt)).length const exceptions = rows.filter(s => s.status === "exception").length return ( <div className="flex flex-col gap-0.5"> <h2 className="text-base font-semibold">Shipments</h2> <p className="text-sm text-muted-foreground"> {inTransit} in transit · {deliveredToday} delivered today ·{" "} <span className={cn(exceptions > 0 && "text-destructive")}> {exceptions} {exceptions === 1 ? "exception" : "exceptions"} </span> </p> </div> )}
export default function ShipmentsTable() { const [shipments, setShipments] = React.useState(sampleShipments) const [lastAction, setLastAction] = React.useState("")
const { columnSizing, onColumnSizingChange, resetColumnSizing } = useColumnSizingPersistence(SIZING_KEY) const { columnPinning, columnVisibility, onColumnPinningChange, onColumnVisibilityChange, resetLayout, } = useLayoutPersistence()
const actions = React.useMemo<Actions>(() => { const update = (id: string, change: Partial<Shipment>) => setShipments(rows => rows.map(row => (row.id === id ? { ...row, ...change } : row)), ) return { copyId: shipment => { void navigator.clipboard?.writeText(shipment.id).catch(() => {}) setLastAction(`Copied ${shipment.id}`) }, markDelivered: shipment => { update(shipment.id, { status: "delivered", deliveredAt: NOW }) setLastAction(`${shipment.id} marked delivered`) }, flagException: shipment => { update(shipment.id, { status: "exception" }) setLastAction(`${shipment.id} flagged as an exception`) }, } }, [])
// The row actions, composed ONCE and mounted in both the "⋯" dropdown and // the right-click menu. const rowMenu = React.useMemo( () => ( <> <CopyIdItem copyId={actions.copyId} /> <MarkDeliveredItem markDelivered={actions.markDelivered} /> <FlagExceptionItem flagException={actions.flagException} /> </> ), [actions], ) const columns = useShipmentColumns(rowMenu)
const resetAll = () => { resetColumnSizing() resetLayout() setLastAction("Layout reset") }
return ( <div className="w-full rounded-xl border bg-card p-4 text-card-foreground shadow-sm"> <DataTableRoot data={shipments} columns={columns} getRowId={shipment => shipment.id} state={{ columnSizing, columnPinning, columnVisibility }} onColumnSizingChange={onColumnSizingChange} onColumnPinningChange={onColumnPinningChange} onColumnVisibilityChange={onColumnVisibilityChange} > <DataTableColumnResize /> <div className="flex flex-col gap-4"> <ShipmentsHeader /> <DataTableToolbarSection className="flex-wrap px-0"> <DataTableSearchFilter placeholder="Search shipments..." className="min-w-48 flex-none sm:w-72" /> <DataTableFacetedFilter accessorKey="status" multiple /> <DataTableFacetedFilter accessorKey="carrier" multiple /> <DataTableClearFilter /> <div className="ml-auto flex items-center gap-2"> <Button variant="outline" size="sm" onClick={resetAll}> Reset layout </Button> <DataTableViewMenu /> </div> </DataTableToolbarSection> <DataTable> <DataTableHeader /> <DataTableBody> <DataTableRowContextMenuSlot> {rowMenu} </DataTableRowContextMenuSlot> <DataTableEmptyBody> <DataTableEmptyMessage> <DataTableEmptyIcon> <PackageX className="size-12" /> </DataTableEmptyIcon> <DataTableEmptyTitle>No shipments</DataTableEmptyTitle> <DataTableEmptyDescription> New shipments show up here. </DataTableEmptyDescription> </DataTableEmptyMessage> <DataTableEmptyFilteredMessage> <DataTableEmptyIcon> <SearchX className="size-12" /> </DataTableEmptyIcon> <DataTableEmptyTitle> No matching shipments </DataTableEmptyTitle> <DataTableEmptyDescription> Try another search, or clear the filters. </DataTableEmptyDescription> </DataTableEmptyFilteredMessage> </DataTableEmptyBody> </DataTableBody> </DataTable> <DataTablePagination /> {lastAction && ( <p className="text-xs text-muted-foreground" aria-live="polite"> {lastAction} </p> )} </div> </DataTableRoot> </div> )}/* * Pinning and visibility persistence. Widths are saved by the library's * `useColumnSizingPersistence` under their own key; this saves the rest of * the layout under another, with guards for SSR and corrupt JSON. */import * as React from "react"
export type Pinning = { start: string[]; end: string[] }export type Visibility = Record<string, boolean>type Layout = { pinning: Pinning; visibility: Visibility }type Updater<T> = T | ((old: T) => T)
export const SIZING_KEY = "shipments-table:sizing"export const LAYOUT_KEY = "shipments-table:layout"
/** Tracking ID stays on the left and the row menu on the right. */export const DEFAULT_PINNING: Pinning = { start: ["tracking"], end: ["actions"],}
/** Data columns the reader may hide. The actions column never hides. */const HIDEABLE = [ "tracking", "route", "carrier", "service", "status", "shippedAt", "eta", "weightKg", "pieces", "costUsd", "recipient", "reference",]const PINNABLE = [...HIDEABLE, "actions"]
const DEFAULT_LAYOUT: Layout = { pinning: DEFAULT_PINNING, visibility: {} }
/** Known ids only, no repeats; undefined when the value is not a string list. */function ids(value: unknown, known: string[]): string[] | undefined { if (!Array.isArray(value) || !value.every(i => typeof i === "string")) { return undefined } return [...new Set(value as string[])].filter(id => known.includes(id))}
/** Each field falls back to its default when missing or the wrong shape. */function read(): Layout { if (typeof window === "undefined") return DEFAULT_LAYOUT try { const raw: unknown = JSON.parse( window.localStorage.getItem(LAYOUT_KEY) ?? "null", ) if (!raw || typeof raw !== "object" || Array.isArray(raw)) { return DEFAULT_LAYOUT } const { pinning, visibility } = raw as Record<string, unknown> const p = (pinning && typeof pinning === "object" ? pinning : {}) as Record< string, unknown > const start = ids(p.start, PINNABLE) ?? DEFAULT_PINNING.start const end = (ids(p.end, PINNABLE) ?? DEFAULT_PINNING.end).filter( id => !start.includes(id), ) const v = visibility && typeof visibility === "object" && !Array.isArray(visibility) ? Object.entries(visibility) : [] return { pinning: { start, end }, visibility: Object.fromEntries( v.filter( ([id, shown]) => HIDEABLE.includes(id) && typeof shown === "boolean", ), ), } } catch { return DEFAULT_LAYOUT }}
function write(layout: Layout | null) { if (typeof window === "undefined") return try { if (layout) window.localStorage.setItem(LAYOUT_KEY, JSON.stringify(layout)) else window.localStorage.removeItem(LAYOUT_KEY) } catch { // Quota or private mode: skip persistence. }}
/** * Pinning and visibility state, saved on every change. The first render uses * the defaults (so server and client HTML match); the saved layout is applied * right after mount. */export function useLayoutPersistence() { const [layout, setLayout] = React.useState<Layout>(DEFAULT_LAYOUT) const layoutRef = React.useRef(layout)
React.useEffect(() => { const stored = read() layoutRef.current = stored setLayout(stored) }, [])
const change = React.useCallback( <K extends keyof Layout>(key: K, updater: Updater<Layout[K]>) => { const old = layoutRef.current const next = { ...old, [key]: typeof updater === "function" ? updater(old[key]) : updater, } layoutRef.current = next setLayout(next) write(next) }, [], )
const onColumnPinningChange = React.useCallback( (updater: Updater<Pinning>) => change("pinning", updater), [change], ) const onColumnVisibilityChange = React.useCallback( (updater: Updater<Visibility>) => change("visibility", updater), [change], ) const resetLayout = React.useCallback(() => { write(null) layoutRef.current = DEFAULT_LAYOUT setLayout(DEFAULT_LAYOUT) }, [])
return { columnPinning: layout.pinning, columnVisibility: layout.visibility, onColumnPinningChange, onColumnVisibilityChange, resetLayout, }}import type { ShipmentStatus } from "./shipments-data"
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD",})
export function formatCost(value: number) { return usd.format(value)}
export function formatWeight(kg: number) { return `${kg.toLocaleString("en-US", { maximumFractionDigits: 1 })} kg`}
/** "Nov 2", in UTC so it matches the fixed sample date everywhere. */export function formatDay(date: Date) { return date.toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC", })}
export const statusLabel: Record<ShipmentStatus, string> = { "label-created": "Label created", "in-transit": "In transit", "out-for-delivery": "Out for delivery", delivered: "Delivered", exception: "Exception",}
export const statusDot: Record<ShipmentStatus, string> = { "label-created": "bg-muted-foreground", "in-transit": "bg-primary", "out-for-delivery": "bg-warning", delivered: "bg-success", exception: "bg-destructive",}export type ShipmentStatus = | "label-created" | "in-transit" | "out-for-delivery" | "delivered" | "exception"export type ShipmentService = "standard" | "express" | "freight"
export type Shipment = { id: string origin: string destination: string carrier: string service: ShipmentService status: ShipmentStatus shippedAt: Date /** Promised delivery time. */ eta: Date /** Set once the shipment is delivered. */ deliveredAt: Date | null weightKg: number pieces: number costUsd: number recipient: string reference: string}
/** Fixed "now" for the sample data, so lateness and "today" never drift. */export const NOW = new Date(Date.UTC(2026, 10, 2, 15, 0))
export const statusOptions = [ { label: "Label created", value: "label-created" }, { label: "In transit", value: "in-transit" }, { label: "Out for delivery", value: "out-for-delivery" }, { label: "Delivered", value: "delivered" }, { label: "Exception", value: "exception" },]
export const carrierNames = [ "Harbor Line Freight", "Kestrel Express", "Northgate Parcel", "Tallow Bay Logistics", "Meridian Courier",]
export const carrierOptions = carrierNames.map(name => ({ label: name, value: name,}))
export const serviceOptions = [ { label: "Standard", value: "standard" }, { label: "Express", value: "express" }, { label: "Freight", value: "freight" },]
/** True when the promised time has passed and it has not arrived. */export function isLate(shipment: Pick<Shipment, "eta" | "status">) { return shipment.status !== "delivered" && shipment.eta < NOW}
/** Same UTC calendar day as the sample data's NOW. */export function isToday(date: Date | null) { return ( date !== null && date.toISOString().slice(0, 10) === NOW.toISOString().slice(0, 10) )}
/** * Sample data, generated rather than hand-written. A seeded PRNG (mulberry32) * keeps it random-looking but identical on every render. Swap `shipments` for * your own rows. */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 cities = [ "Portland", "Denver", "Austin", "Chicago", "Atlanta", "Seattle", "Phoenix", "Boston", "Nashville", "Salt Lake City", "Columbus", "Sacramento",]
const firstNames = ["Alma", "Ben", "Carmen", "Dmitri", "Esi", "Farid", "Greta"]const lastNames = ["Okafor", "Lindqvist", "Marchetti", "Tanaka", "Vega", "Hale"]const businesses = ["Pinecrest Supply", "Larkspur Goods", "Ironwood Labs"]
const HOUR = 3_600_000const DAY = 24 * HOURconst COUNT = 45
function generate(): Shipment[] { const rand = seededRandom(48_201) const pick = <T>(list: readonly T[]) => list[Math.floor(rand() * list.length)] as T
const rows: Shipment[] = [] for (let i = 0; i < COUNT; i++) { // Oldest first; ids follow shipping order. const ageHours = ((COUNT - 1 - i) / (COUNT - 1)) * 13 * 24 + rand() * 6 const shippedAt = new Date(NOW.getTime() - ageHours * HOUR)
const roll = rand() const service: ShipmentService = roll < 0.2 ? "express" : roll < 0.8 ? "standard" : "freight" const transitDays = service === "express" ? 1 + rand() * 1.5 : service === "standard" ? 3 + rand() * 3 : 5 + rand() * 5 const eta = new Date(shippedAt.getTime() + transitDays * DAY)
const origin = pick(cities) let destination = pick(cities) if (destination === origin) { destination = cities[ (cities.indexOf(origin) + 1) % cities.length ] as string }
let status: ShipmentStatus let deliveredAt: Date | null = null const hoursToEta = (eta.getTime() - NOW.getTime()) / HOUR if (ageHours < 6) status = "label-created" else if (rand() < 0.07) status = "exception" else if (hoursToEta <= 0) { // Past due: mostly delivered, a few still on the road (late). status = rand() < 0.82 ? "delivered" : "in-transit" } else if (hoursToEta < 20) { status = rand() < 0.6 ? "out-for-delivery" : "in-transit" } else status = "in-transit" if (status === "delivered") { const arrived = eta.getTime() + (rand() - 0.6) * 20 * HOUR deliveredAt = new Date(Math.min(arrived, NOW.getTime() - HOUR)) }
const weightKg = service === "freight" ? Math.round((180 + rand() * 900) * 10) / 10 : Math.round((0.4 + rand() * 24) * 10) / 10 const pieces = service === "freight" ? 2 + Math.floor(rand() * 10) : 1 + Math.floor(rand() * 3) const costUsd = Math.round( (service === "express" ? 24 : service === "standard" ? 11 : 140) * (1 + weightKg / (service === "freight" ? 400 : 12)) * 100, ) / 100
rows.push({ id: `SHP-${48_201 + i}`, origin, destination, carrier: pick(carrierNames), service, status, shippedAt, eta, deliveredAt, weightKg, pieces, costUsd, recipient: rand() < 0.4 ? pick(businesses) : `${pick(firstNames)} ${pick(lastNames)}`, reference: `PO-${1000 + Math.floor(rand() * 9000)}`, }) } // Newest first, like a dispatch board. return rows.reverse()}
export const shipments: Shipment[] = generate()Usage
The files land in components/shipments-table/. Render the block anywhere:
import Shipments from "@/components/shipments-table/shipments-table"
export default function Page() { return <Shipments />}Then replace the generated rows in shipments-data.ts with your own data, or load it from your API and pass it in.