Skip to content

CurrencyPairChart

Rate history with a period selector.
Implemented
Status
Implemented
Family
4 of 13
Registry
@lopifi/currency-pair-chart
npx shadcn@latest add @lopifi/theme @lopifi/currency-pair-chart

The component, rendering

Real data, the shipped component. Switch the theme to check the claims the spec makes below.

Preview

The four-layer spec

Rate history with a period selector. Y-axis does not start at zero — it's a rate, not a quantity, and forcing zero destroys the resolution. This is the one sanctioned exception to the zero-baseline rule, and the axis is labeled clearly so it can't mislead.

Draws once on mount. Instant on period change.

Lifted verbatim from Swaps & FX. 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/currency-pair-chart.tsx

Lopifi dependencies · 10
as-ofchart-utilscnfiscal-periodformat-moneymoney.typestooltipuse-in-viewuse-media-queryuse-shared-now
npm packages
@base-ui-components/reactclsxtailwind-merge
Registry entry
/r/currency-pair-chart.json

The whole component

No compiled bundle, no black box. This is the file the registry copies, and the file you will edit.

components/ledger/currency-pair-chart.tsx
"use client";

import * as React from "react";
import { useInViewOnce } from "@/hooks/ledger/use-in-view";
import { useReducedMotion } from "@/hooks/ledger/use-media-query";
import { niceTicks } from "@/lib/ledger/chart-utils";
import { cn } from "@/lib/ledger/cn";
import { AsOf } from "@/components/ledger/as-of";

export const CHART_PERIODS = ["1D", "1W", "1M", "3M", "1Y"] as const;
export type ChartPeriod = (typeof CHART_PERIODS)[number];

export interface RateSeries {
  labels: string[];
  /** Rate history, oldest first. */
  rates: number[];
}

export interface CurrencyPairChartProps {
  asOf: Date;
  className?: string;
  /** Falls back to 1M, then to the longest horizon supplied. */
  defaultPeriod?: ChartPeriod;
  from: string;
  /**
   * One entry per horizon you actually hold history for. The selector renders
   * exactly these and nothing else: a period button that redraws the same
   * line is a control that lies about the data behind it, and one horizon of
   * history is a chart, not a chart with a broken selector.
   */
  series: Partial<Record<ChartPeriod, RateSeries>>;
  to: string;
}

/**
 * The Y-axis does not start at zero. It is a rate, not a quantity, and
 * forcing zero destroys the resolution — this is the one sanctioned
 * exception to the zero-baseline rule, and the axis says so.
 *
 * Draws once on mount, instant on period change.
 */
export function CurrencyPairChart({
  from,
  to,
  series,
  defaultPeriod,
  asOf,
  className,
}: CurrencyPairChartProps) {
  /* Two points are a line segment, not a history. */
  const offered = CHART_PERIODS.filter((p) => (series[p]?.rates.length ?? 0) > 1);
  const initial =
    (defaultPeriod && offered.includes(defaultPeriod) ? defaultPeriod : undefined) ??
    (offered.includes("1M") ? "1M" : offered.at(-1));
  const [period, setPeriod] = React.useState<ChartPeriod | undefined>(initial);
  const reduced = useReducedMotion();
  const [_viewRef, inView] = useInViewOnce<SVGSVGElement>();

  const active = (period ? series[period] : undefined) ?? { labels: [], rates: [] };
  const { rates, labels } = active;
  if (rates.length < 2) return null;

  const width = 720;
  const height = 220;
  const PAD = { bottom: 28, left: 72, right: 16, top: 16 };

  const min = Math.min(...rates);
  const max = Math.max(...rates);
  const pad = (max - min) * 0.15 || 0.001;
  const lo = min - pad;
  const hi = max + pad;
  const ticks = niceTicks(lo, hi, 4);

  const plotW = width - PAD.left - PAD.right;
  const plotH = height - PAD.top - PAD.bottom;
  const x = (i: number) => PAD.left + (i / (rates.length - 1)) * plotW;
  const y = (v: number) => PAD.top + plotH - ((v - lo) / (hi - lo || 1)) * plotH;
  const path = rates.map((v, i) => `${i === 0 ? "M" : "L"}${x(i)},${y(v)}`).join(" ");

  return (
    <div className={cn("w-full", className)}>
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <p className="text-label font-medium">
            {from}/{to}
          </p>
          <AsOf date={asOf} />
        </div>
        {/* One horizon is not a choice, and a single pressed button that does
            nothing is worse than no button at all. */}
        {offered.length > 1 ? (
          <div aria-label="Chart period" className="flex gap-1" role="group">
            {offered.map((p) => (
              <button
                aria-pressed={period === p}
                className={cn(
                  "h-8 rounded-sm px-2.5 text-label font-medium",
                  "transition-colors duration-1 ease-standard",
                  period === p
                    ? "bg-surface-selected text-text-primary"
                    : "text-text-secondary hover:bg-surface-hover",
                )}
                key={p}
                onClick={() => setPeriod(p)}
                type="button"
              >
                {p}
              </button>
            ))}
          </div>
        ) : null}
      </div>

      <svg
        aria-label={`${from} to ${to} rate history`}
        className="mt-3 w-full"
        role="img"
        style={{ height }}
        viewBox={`0 0 ${width} ${height}`}
      >
        {ticks.map((t) => (
          <g key={t}>
            <line stroke="var(--border-subtle)" x1={PAD.left} x2={width - PAD.right} y1={y(t)} y2={y(t)} />
            <text
              className="numeric"
              fill="var(--text-tertiary)"
              fontSize="12"
              textAnchor="end"
              x={PAD.left - 8}
              y={y(t) + 4}
            >
              {t.toFixed(4)}
            </text>
          </g>
        ))}
        <path
          d={path}
          fill="none"
          stroke="var(--viz-1)"
          strokeLinejoin="round"
          strokeWidth="2"
          style={
            reduced
              ? undefined
              : {
                  animation: inView ? "ledger-draw 400ms var(--ease-out) forwards" : undefined,
                  strokeDasharray: 2000,
                  strokeDashoffset: 2000,
                }
          }
        />
        {labels.map((label, i) =>
          i % Math.ceil(labels.length / 6) === 0 ? (
            /* Labels repeat across horizons — "Mon" twice in a week — so the
               index is part of the key. */
            <text
              className="numeric"
              fill="var(--text-tertiary)"
              fontSize="12"
              key={`${label}-${i}`}
              textAnchor="middle"
              x={x(i)}
              y={height - 8}
            >
              {label}
            </text>
          ) : null,
        )}
      </svg>
      <p className="text-caption text-text-tertiary">
        Axis does not start at zero — this is a rate, not a quantity.
      </p>
    </div>
  );
}

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 Swaps & FX

See also

A component is specified in one place, defined in another, and running in a third. All three, from here.

Elsewhere in the system

Where CurrencyPairChart 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.

Components are copied into your repository and meant to be edited — rounding policy, fiscal calendar and compliance copy differ per company.

Told when Swaps & FX 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.

One address, no list rental, unsubscribe in one click.

Works in your QuickBooks Online or Xero file

Get your books closed every month

Lopifi is building AI bookkeeping that keeps your books closed on US GAAP as transactions happen, with a CPA review every quarter, for $200 a month. We’re not open yet.

$200/month when we open. No card now.