Wallets
What each wallet is worth, how many assets it holds and which one leads it, the day's move, and the balance split between them as a bar; reads walletSummaries().
Preview
import { WalletIcon } from "lucide-react"
import { formatCurrency, formatPercent } from "@/lib/format"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { MetricDelta } from "@/components/ui/metric-delta"
import { PercentageBar } from "@/components/ui/percentage-bar"
import { type WalletSummary } from "../data"
const money = (cents: number) => formatCurrency(cents / 100, "USD", { maximumFractionDigits: 0 })
/**
* The three wallets, one line each: what each is worth, how many assets it
* holds and which one leads, with the day's move on the right and the split
* of the balance between them as a bar underneath. The holdings themselves
* are the table further down; this card is the sum. No state, so it renders
* on the server.
*/
export function WalletsList({ wallets }: { wallets: WalletSummary[] }) {
return (
<Card data-widget="widget-finance-crypto-wallets-list" role="region" aria-label="Wallets" className="h-full">
<CardHeader>
<CardTitle>Wallets</CardTitle>
<CardDescription>{"What each wallet is worth, at today's prices."}</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<ul className="flex flex-col divide-y divide-rule">
{wallets.map((wallet) => (
<li key={wallet.wallet} data-slot="wallet-row" className="flex items-center gap-3 py-3 first:pt-0 last:pb-0">
<span
aria-hidden="true"
className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground [&_svg]:size-4"
>
<WalletIcon />
</span>
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
<h2 className="truncate text-sm font-medium">{`${wallet.wallet} wallet`}</h2>
<span className="truncate text-xs text-muted-foreground">
{`${wallet.assets} ${wallet.assets === 1 ? "asset" : "assets"} · ${wallet.top.asset} ${formatPercent(wallet.top.share, { maximumFractionDigits: 0 })}`}
</span>
</span>
<span className="flex shrink-0 flex-col items-end gap-0.5">
<span className="text-sm tabular-nums">{money(wallet.totalCents)}</span>
<MetricDelta value={wallet.change24h} size="sm" />
</span>
</li>
))}
</ul>
{/* The rows carry the sums; the legend only needs the shares. */}
<PercentageBar
segments={wallets.map((wallet) => ({ label: wallet.wallet, value: wallet.totalCents }))}
height="sm"
className="mt-auto border-t border-rule pt-4"
/>
</CardContent>
</Card>
)
}Install
$
npx shadcn@latest add @vibra/widget-finance-crypto-wallets-listNeeds the @vibra registry in your components.json — set it up once.
Source
import { WalletIcon } from "lucide-react"
import { formatCurrency, formatPercent } from "@/lib/format"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { MetricDelta } from "@/components/ui/metric-delta"
import { PercentageBar } from "@/components/ui/percentage-bar"
import { type WalletSummary } from "../data"
const money = (cents: number) => formatCurrency(cents / 100, "USD", { maximumFractionDigits: 0 })
/**
* The three wallets, one line each: what each is worth, how many assets it
* holds and which one leads, with the day's move on the right and the split
* of the balance between them as a bar underneath. The holdings themselves
* are the table further down; this card is the sum. No state, so it renders
* on the server.
*/
export function WalletsList({ wallets }: { wallets: WalletSummary[] }) {
return (
<Card data-widget="widget-finance-crypto-wallets-list" role="region" aria-label="Wallets" className="h-full">
<CardHeader>
<CardTitle>Wallets</CardTitle>
<CardDescription>{"What each wallet is worth, at today's prices."}</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<ul className="flex flex-col divide-y divide-rule">
{wallets.map((wallet) => (
<li key={wallet.wallet} data-slot="wallet-row" className="flex items-center gap-3 py-3 first:pt-0 last:pb-0">
<span
aria-hidden="true"
className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground [&_svg]:size-4"
>
<WalletIcon />
</span>
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
<h2 className="truncate text-sm font-medium">{`${wallet.wallet} wallet`}</h2>
<span className="truncate text-xs text-muted-foreground">
{`${wallet.assets} ${wallet.assets === 1 ? "asset" : "assets"} · ${wallet.top.asset} ${formatPercent(wallet.top.share, { maximumFractionDigits: 0 })}`}
</span>
</span>
<span className="flex shrink-0 flex-col items-end gap-0.5">
<span className="text-sm tabular-nums">{money(wallet.totalCents)}</span>
<MetricDelta value={wallet.change24h} size="sm" />
</span>
</li>
))}
</ul>
{/* The rows carry the sums; the legend only needs the shares. */}
<PercentageBar
segments={wallets.map((wallet) => ({ label: wallet.wallet, value: wallet.totalCents }))}
height="sm"
className="mt-auto border-t border-rule pt-4"
/>
</CardContent>
</Card>
)
}/**
* What this page reads. Every holding comes from `db.holdings` and every
* movement from `db.trades`; the balance, the wallet groups, the three
* totals and the seven-month flow are rules over those rows, so nothing here
* is a literal. "Now" is `REFERENCE_DATE`.
*
* The client islands import only the types below. The words the page puts on
* a trade's kind live beside them in `components/crypto-vocabulary.ts`, so
* nothing that reaches `db` is ever pulled into the browser.
*/
import { getInitials } from "@/lib/format"
import { REFERENCE_DATE, db, type Holding, type Member, type Trade } from "@/lib/sample-data"
export type TradeKind = Trade["kind"]
export type Wallet = Holding["wallet"]
/** One holding as the holdings table prints it. */
export type HoldingRow = {
id: string
asset: string
symbol: string
/** The letter in the tinted circle, in place of the coin's mark. */
initial: string
amount: number
priceCents: number
change24h: number
wallet: Wallet
/** What the holding is worth now, in cents. */
valueCents: number
}
/** One movement as the activity list prints it. Exported because the order returns one. */
export type TradeRow = {
id: string
asset: string
symbol: string
initial: string
kind: TradeKind
amount: number
priceCents: number
valueCents: number
at: Date
status: Trade["status"]
}
// Read per call, never held at module scope: a holding bought into since the
// server started names its trades on the next render.
const assetsBySymbol = () => new Map(db.holdings.all().map((row) => [row.symbol, row.asset]))
const initialOf = (asset: string) => asset.charAt(0).toUpperCase()
export function toHoldingRow(row: Holding): HoldingRow {
return {
id: row.id,
asset: row.asset,
symbol: row.symbol,
initial: initialOf(row.asset),
amount: row.amount,
priceCents: row.priceCents,
change24h: row.change24h,
wallet: row.wallet,
valueCents: Math.round(row.amount * row.priceCents),
}
}
export function toTradeRow(row: Trade, assets = assetsBySymbol()): TradeRow {
const asset = assets.get(row.symbol) ?? row.symbol
return {
id: row.id,
asset,
symbol: row.symbol,
initial: initialOf(asset),
kind: row.kind,
amount: row.amount,
priceCents: row.priceCents,
valueCents: Math.round(row.amount * row.priceCents),
at: row.at,
status: row.status,
}
}
export type Overview = {
transactions: number
wallets: number
balanceCents: number
/** What the last day's prices did to the balance, in cents: each holding's value times its own move. */
move24hCents: number
/** The same move as a share of the balance — the last day's change, weighted by value. */
change24h: number
}
/** The headline card: how many movements, how many wallets, and what it all adds up to. */
export function overview(): Overview {
const holdings = db.holdings.all()
const balanceCents = holdings.reduce((sum, row) => sum + row.amount * row.priceCents, 0)
const move24hCents = holdings.reduce((sum, row) => sum + row.amount * row.priceCents * row.change24h, 0)
return {
transactions: db.trades.all().length,
wallets: new Set(holdings.map((row) => row.wallet)).size,
balanceCents,
move24hCents,
change24h: balanceCents === 0 ? 0 : move24hCents / balanceCents,
}
}
export type WalletGroup = { wallet: Wallet; rows: HoldingRow[]; totalCents: number }
const WALLET_ORDER: Wallet[] = ["Main", "Savings", "Trading"]
/** Every holding under its wallet, the largest holding first inside each. */
export function walletGroups(): WalletGroup[] {
const rows = db.holdings.all().map(toHoldingRow)
return WALLET_ORDER.filter((wallet) => rows.some((row) => row.wallet === wallet)).map((wallet) => {
const inWallet = rows.filter((row) => row.wallet === wallet).sort((a, b) => b.valueCents - a.valueCents)
return { wallet, rows: inWallet, totalCents: inWallet.reduce((sum, row) => sum + row.valueCents, 0) }
})
}
export type WalletSummary = {
wallet: Wallet
/** How many assets the wallet holds. */
assets: number
totalCents: number
/** The wallet's last-day move, weighted by value. */
change24h: number
/** The largest holding in the wallet, and its share of the wallet. */
top: { asset: string; share: number }
}
/** Each wallet on one line: what it holds, what that is worth, and how the day treated it. */
export function walletSummaries(): WalletSummary[] {
return walletGroups().map((group) => {
const [top] = group.rows
const weighted = group.rows.reduce((sum, row) => sum + row.valueCents * row.change24h, 0)
return {
wallet: group.wallet,
assets: group.rows.length,
totalCents: group.totalCents,
change24h: group.totalCents === 0 ? 0 : weighted / group.totalCents,
top: {
asset: top?.asset ?? "",
share: top && group.totalCents > 0 ? top.valueCents / group.totalCents : 0,
},
}
})
}
/** Every holding in every wallet, the largest first — the table under the desk. */
export function holdings(): HoldingRow[] {
return db.holdings
.all()
.map(toHoldingRow)
.sort((a, b) => b.valueCents - a.valueCents)
}
export type Coin = { symbol: string; asset: string; priceCents: number }
/** The assets the trade form offers: one entry per symbol, at today's price. */
export function coins(): Coin[] {
const seen = new Map<string, Coin>()
for (const row of db.holdings.all()) {
if (!seen.has(row.symbol)) seen.set(row.symbol, { symbol: row.symbol, asset: row.asset, priceCents: row.priceCents })
}
return [...seen.values()]
}
/** Every movement, newest first. */
export function recentTrades(): TradeRow[] {
const assets = assetsBySymbol()
return db.trades
.all()
.sort((a, b) => b.at.getTime() - a.at.getTime())
.map((row) => toTradeRow(row, assets))
}
export type BalanceSummary = { receivedCents: number; sentCents: number; withdrawnCents: number }
const valueOf = (rows: Trade[], kind: TradeKind) =>
rows.filter((row) => row.kind === kind).reduce((sum, row) => sum + row.amount * row.priceCents, 0)
/** What came in from other wallets, what went out to them, and what was sold for cash. */
export function balanceSummary(): BalanceSummary {
const rows = db.trades.all()
return {
receivedCents: valueOf(rows, "receive"),
sentCents: valueOf(rows, "send"),
withdrawnCents: valueOf(rows, "sell"),
}
}
const MONTH = new Intl.DateTimeFormat("en-US", { month: "short", timeZone: "UTC" })
/** The first of the month `back` months before the reference month. */
function monthStart(back: number): Date {
return new Date(Date.UTC(REFERENCE_DATE.getUTCFullYear(), REFERENCE_DATE.getUTCMonth() - back, 1))
}
export type FlowPoint = { month: string; received: number; sent: number; withdrawn: number }
/** The three flows by month over the last seven months, in dollars, oldest first. */
export function flowByMonth(): FlowPoint[] {
const rows = db.trades.all()
return Array.from({ length: 7 }, (_, index) => 6 - index).map((back) => {
const start = monthStart(back)
const end = monthStart(back - 1)
const inMonth = rows.filter((row) => row.at >= start && row.at < end)
return {
month: MONTH.format(start),
received: Math.round(valueOf(inMonth, "receive") / 100),
sent: Math.round(valueOf(inMonth, "send") / 100),
withdrawn: Math.round(valueOf(inMonth, "sell") / 100),
}
})
}
/** The bell's contents: the newest notifications, unread first in the panel. */
export function shellNotifications() {
return db.notifications
.all()
.sort((a, b) => b.at.getTime() - a.at.getTime())
.slice(0, 6)
.map(({ id, title, description, at, read, href }) => ({ id, title, description, at, read, href }))
}
function ownerRow(): Member {
return db.members.all().find((member) => member.role === "owner") ?? db.members.all()[0]
}
/** The person looking at the page: whoever owns this workspace. */
export function currentUser() {
const owner = ownerRow()
return { name: owner.name, email: owner.email, initials: getInitials(owner.name), avatarUrl: owner.avatarUrl }
}Its page
On its page the card sits among the rest of the dashboard and shares its range and its data with them.
From the Crypto dashboard page