Money
- Status
- Implemented
- Family
- 1 of 13
- Registry
- @lopifi/money
npx shadcn@latest add @lopifi/theme @lopifi/moneyThe component, rendering
Real data, the shipped component. Switch the theme to check the claims the spec makes below.
The four-layer spec
The core primitive. Every monetary value in the system renders through it.
<Money value={{ amount: 124056, currency: "USD" }} /> // $1,240.56
<Money value={{ amount: -124056, currency: "USD" }} accounting /> // ($1,240.56)
<Money value={null} /> // n/a
<Money value={{ amount: 0, currency: "USD" }} statement /> // —
interface MoneyProps extends React.ComponentPropsWithoutRef<"span"> {
value: MoneyValue | null;
/** parentheses for negatives (statements/tables) vs. a leading − (deltas) */
accounting?: boolean;
/** em dash for a true zero — statements only */
statement?: boolean;
size?: "xs" | "sm" | "md" | "lg" | "hero";
/** subordinate the symbol; default true */
showSymbol?: boolean;
/** show the ISO code — required in mixed-currency contexts */
showCode?: boolean;
/** mark as converted: renders "≈" and requires a rate for the tooltip */
approximate?: { rate: number; asOf: Date; from: string };
redacted?: boolean;
locale?: string;
}
Layer 3 — structure: [≈] [symbol] [integer] [.decimals] [code] — five slots, four optional. The paren column is reserved on both sides regardless of sign.
Layer 4 — type: one size, one weight. tnum + case always. Symbol and code at --text-tertiary; decimals at --text-tertiary only at lg/hero.
Motion: none, except the value flash when live and the crossfade when the value changes from a user action. Never interpolates.
Edge cases: JPY 0dp · KWD 3dp · bigint amounts · negative zero (renders as zero) · the widest-plausible-value width reservation · aria-label announcing the sign in words.
Why it matters: if this is wrong, everything is wrong. It also carries the whole case/tnum/paren-alignment craft that the rest of the library assumes.
Lifted verbatim from Primitives. The doc and this page are the same paragraphs, so they cannot disagree.
What lands in your repository
One component is never one file. Everything below is copied into your project, where you own it.
- Files
components/ledger/money.tsx
- Lopifi dependencies · 4
- cnformat-moneymoney.typestooltip
- npm packages
- @base-ui-components/reactclass-variance-authorityclsxtailwind-merge
- Registry entry
- /r/money.json
The whole component
No compiled bundle, no black box. This is the file the registry copies, and the file you will edit.
import { cva, type VariantProps } from "class-variance-authority";
import * as React from "react";
import { cn } from "@/lib/ledger/cn";
import { formatMoneyParts, isNegative, isZero, moneyAriaLabel, rawMoney } from "@/lib/ledger/format-money";
import type { MoneyValue } from "@/lib/ledger/money.types";
import { Tooltip } from "@/components/ledger/tooltip";
/* Server-safe by design: a 400-row statement renders on the server. */
/* `relative` anchors the absolutely-positioned spoken label to the figure, so
it can never widen a scroll container it sits in. */
const moneyVariants = cva("numeric relative inline-flex items-baseline whitespace-nowrap", {
defaultVariants: { size: "sm", tone: "primary" },
variants: {
size: {
hero: "text-figure-hero font-medium",
lg: "text-figure-lg font-medium",
md: "text-figure-md font-medium",
sm: "text-figure-sm font-normal",
xs: "text-figure-xs font-normal",
},
tone: {
inherit: "text-inherit",
negative: "text-negative",
positive: "text-positive",
primary: "text-text-primary",
// Never --text-tertiary for a monetary value: money holds 7:1.
secondary: "text-text-secondary",
},
},
});
export interface MoneyProps
extends Omit<React.ComponentPropsWithoutRef<"span">, "children">,
VariantProps<typeof moneyVariants> {
/** Parentheses for negatives — statements and tables. */
accounting?: boolean;
/** A converted value is a derived value: renders "≈" and states its basis. */
approximate?: { rate: number; asOf: Date; from: string };
/** Colour the figure by sign. Off by default; the glyphs carry the sign. */
colorBySign?: boolean;
/** Drop the cents. Display surfaces only — never a table or a statement. */
dropCents?: boolean;
locale?: string;
redacted?: boolean;
/** The ISO code — required in a mixed-currency context. */
showCode?: boolean;
/** Subordinate the symbol. Default true. */
showSymbol?: boolean;
/** Em dash for a true zero — statements only. */
statement?: boolean;
value: MoneyValue | null | undefined;
}
/**
* The core primitive. Every monetary value in the system renders through it.
*
* Five slots, four optional: [≈] [symbol] [integer] [.decimals] [code].
* The paren column is reserved on both sides regardless of sign, so a
* right-aligned column of mixed-sign values keeps its decimal alignment.
*/
export const Money = React.forwardRef<HTMLSpanElement, MoneyProps>(
(
{
className,
value,
size,
tone,
accounting = false,
statement = false,
showSymbol = true,
showCode = false,
approximate,
redacted = false,
dropCents = false,
colorBySign = false,
locale,
...props
},
ref,
) => {
// Five distinct renders. Never `value ?? 0`.
if (value == null) {
return (
<span
className={cn(moneyVariants({ size, tone: "secondary" }), "text-text-tertiary", className)}
ref={ref}
{...props}
>
<span aria-hidden="true">n/a</span>
<Spoken>not available</Spoken>
</span>
);
}
if (redacted) {
return (
<span
className={cn(moneyVariants({ size, tone }), "text-text-tertiary", className)}
ref={ref}
{...props}
>
<span aria-hidden="true">••••</span>
<Spoken>hidden</Spoken>
</span>
);
}
if (statement && isZero(value)) {
return (
<span className={cn(moneyVariants({ size, tone }), className)} ref={ref} {...props}>
<span aria-hidden="true">—</span>
<Spoken>zero</Spoken>
<ParenSlot />
</span>
);
}
const negative = isNegative(value);
const parts = formatMoneyParts(value, { dropCents, locale, showSymbol });
const useParens = accounting && negative;
const largeFigure = size === "lg" || size === "hero";
const resolvedTone =
colorBySign && negative ? "negative" : colorBySign && !isZero(value) ? "positive" : tone;
const label = moneyAriaLabel(value, { locale });
const spoken = approximate ? `approximately ${label}` : label;
const body = (
<span
className={cn(moneyVariants({ size, tone: resolvedTone }), className)}
data-raw={rawMoney(value, locale)}
ref={ref}
{...props}
>
{approximate ? (
// The figure face has no ≈; the text face does, at the same weight.
<span aria-hidden="true" className="mr-1 font-sans text-text-tertiary">
≈
</span>
) : null}
{/* Opening paren slot — reserved on both signs so digits never shift. */}
<span aria-hidden="true" className={useParens ? undefined : "invisible"}>
(
</span>
{!useParens && negative ? (
// U+2212, not a hyphen: it aligns with the plus and sits on the
// lining figures once `case` is on.
<span aria-hidden="true">−</span>
) : null}
{parts.symbol ? (
<span aria-hidden="true" className="mr-[var(--numeric-symbol-gap)] font-normal text-text-tertiary">
{parts.symbol}
</span>
) : null}
<span aria-hidden="true">{parts.integer}</span>
{parts.fraction ? (
<span aria-hidden="true" className={largeFigure ? "text-text-tertiary" : undefined}>
{parts.fraction}
</span>
) : null}
{parts.symbolSuffix ? (
<span aria-hidden="true" className="ml-1 font-normal text-text-tertiary">
{parts.symbolSuffix}
</span>
) : null}
<span aria-hidden="true" className={useParens ? undefined : "invisible"}>
)
</span>
{showCode ? (
<span aria-hidden="true" className="ml-1 text-caption text-text-tertiary">
{value.currency}
</span>
) : null}
<Spoken>{spoken}</Spoken>
</span>
);
// A converted value is a derived value. The basis — source currency, rate,
// and the instant it was struck — is the tooltip's whole job here.
if (!approximate) return body;
return <Tooltip content={approximateTitle(value, approximate, locale)}>{body}</Tooltip>;
},
);
Money.displayName = "Money";
/**
* What a screen reader says in place of the glyphs, which are all
* `aria-hidden`. Text rather than `aria-label`: a label on a role-less span is
* prohibited ARIA and ignored by some readers. `select-none` keeps it out of a
* copied selection, so a figure pasted into a spreadsheet is still the figure.
*/
function Spoken({ children }: { children: React.ReactNode }) {
return <span className="sr-only select-none">{children}</span>;
}
/** Keeps a `—` or `n/a` on the same decimal grid as its neighbours. */
function ParenSlot() {
return (
<span aria-hidden="true" className="invisible">
)
</span>
);
}
function approximateTitle(
value: MoneyValue,
approximate: NonNullable<MoneyProps["approximate"]>,
locale?: string,
): string {
void value;
void locale;
const stamp = new Intl.DateTimeFormat("en-GB", {
day: "numeric",
hour: "2-digit",
minute: "2-digit",
month: "short",
timeZone: "UTC",
year: "numeric",
}).format(approximate.asOf);
return `Converted from ${approximate.from} @ ${approximate.rate} · ${stamp} UTC`;
}
The accounting it encodes
Concepts this component renders. Each one is defined once, in the lexicon, and used identically in the code and the copy.
Also in Primitives
- DeltaA signed change, with polarity and a redundant non-color cue.
- FigureA large display numeral with automatic size step-down.
- PercentPercent vs. percentage points, explicitly discriminated.
- RuleSingle / double / section accounting rule lines.
- StatusPillPayment and reconciliation states.
- SparklineInline trend, one-shot draw.
- TrendArrow + delta + optional sparkline, composed.
- AsOfTimestamp with live relative formatting and a stated timezone.
- RedactedMasked value with reveal.
- ReferenceCopyable transaction/account ID with disambiguated glyphs.
- CurrencyBadgeISO code + optional flag.
- EntityMarkBank/merchant logo with the full fallback ladder.
- TooltipHover/focus restatement. Never the only home of a fact.
- InfoTipThe ⓘ. Extra context that survives touch, because it opens on press.
See also
A component is specified in one place, defined in another, and running in a third. All three, from here.
- Primitives — the family specThe four-layer specification this component was built against, before it was written.Doc
- Money and figure primitivesThe family running, with real figures in it, in both themes and at every density.Live
- CatalogAll 179 components, specified before they are written.Doc
- As atThe point-in-time label for a balance sheetTerm
Elsewhere in the system
Where Money sits in the rest of the system — the live section it renders in, the calculators that compute what it displays, and the ledger payloads it is fed from.
- Money, runningThe primitives showcase — live, with theme, density, greyscale and reduced-motion switches.Live
- Penny-exact allocationSplit 100.00 three ways and get 33.34 / 33.33 / 33.33 — never a cent left in suspense.Tool
- Number cleaner(1,234.56) · 1.234,56 · 1,234.56- · $ 1 234.56 · 1.2k → clean signed values, one per line.Tool
- Amount in wordsFor the check, the note, the contract schedule — with the cents as a fraction over 100.Tool
- PrimitivesBuild these first. Everything above them inherits their mistakes. Specs for 15 React components: Money, Delta, Figure, Percent and 11 more.Doc
- Currency decimal placesHow many decimals each ISO 4217 code is stored at, and where Intl disagrees.Doc
Components are copied into your repository and meant to be edited — rounding policy, fiscal calendar and compliance copy differ per company.
Told when Primitives changes
Components are copied into your repo, so a fix here does not reach you on its own. One email when a component in this family changes in a way that needs a migration — and nothing when it does not.