Skip to content

MoneyBarChart

Grouped/stacked, zero-baseline origin, hatched negatives.
Implemented
Status
Implemented
Family
7 of 13
Registry
@lopifi/money-bar-chart
npx shadcn@latest add @lopifi/theme @lopifi/money-bar-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

Grouped and stacked.

  • transform-origin at the zero baseline, not the bottom. Otherwise negative bars grow upward from the floor and briefly display the wrong sign — a real correctness issue in an animation.
  • Negative bars hatched.
  • Stacked totals labeled at the bar end.
  • Bar radius 4 on the outer corners only, and square below 12px bar width — a rounded 6px bar is a blob.
  • Draw-in: scaleY 0→1, 400ms, stagger 30ms capped at 240ms. First paint only.

Lifted verbatim from Dashboard & charts. 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-bar-chart.tsx

Lopifi dependencies · 9
chart-primitiveschart-utilscnformat-moneymoneymoney.typestooltipuse-in-viewuse-media-query
npm packages
@base-ui-components/reactclass-variance-authorityclsxtailwind-merge
Registry entry
/r/money-bar-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/money-bar-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 { axisLabel, domainFor, niceTicks, vizColorFor } from "@/lib/ledger/chart-utils";
import { ChartLegend, DataTableToggle, HatchDefs } from "@/components/ledger/chart-primitives";
import { Money } from "@/components/ledger/money";

export type BarSeries = { key: string; label: string; values: number[] };

export interface MoneyBarChartProps {
  className?: string;
  currency: string;
  height?: number;
  labels: string[];
  mode?: "grouped" | "stacked";
  series: BarSeries[];
  title?: string;
}

const PAD = { bottom: 28, left: 64, right: 16, top: 16 };

/**
 * `transform-origin` sits at the zero baseline, not at the bottom — otherwise
 * a negative bar grows upward from the floor and briefly displays the wrong
 * sign, which is a correctness issue inside an animation.
 *
 * Bar radius 4 on the outer corners only, square below 12px width.
 */
export function MoneyBarChart({
  labels,
  series,
  currency,
  mode = "grouped",
  height = 260,
  className,
  title,
}: MoneyBarChartProps) {
  const [isolated, setIsolated] = React.useState<string | null>(null);
  const reduced = useReducedMotion();
  /* The bars grow when the chart is scrolled to, not when it mounts. A chart
     below the fold used to play its whole 400ms while nobody was looking and
     was fully grown by the time the reader got there — the animation existed
     and was never once seen. Once, and never again on the way back up. */
  const [viewRef, inView] = useInViewOnce<SVGSVGElement>();
  const uid = React.useId().replace(/:/g, "");
  const width = 720;

  const visible = isolated ? series.filter((s) => s.key === isolated) : series;
  const stackedTotals = labels.map((_, i) => visible.reduce((sum, s) => sum + s.values[i], 0));
  const domainValues = mode === "stacked" ? stackedTotals : visible.flatMap((s) => s.values);
  const { min, max } = domainFor(domainValues.length ? domainValues : [0]);
  const ticks = niceTicks(min, max);
  const domainMin = Math.min(min, ticks[0]);
  const domainMax = Math.max(max, ticks[ticks.length - 1]);

  const plotW = width - PAD.left - PAD.right;
  const plotH = height - PAD.top - PAD.bottom;
  const y = (v: number) => PAD.top + plotH - ((v - domainMin) / (domainMax - domainMin || 1)) * plotH;
  const zeroY = y(0);

  const groupWidth = plotW / labels.length;
  const innerPad = groupWidth * 0.2;
  const barWidth =
    mode === "stacked" ? groupWidth - innerPad : (groupWidth - innerPad) / Math.max(1, visible.length);
  const radius = barWidth < 12 ? 0 : 4;

  return (
    <DataTableToggle
      className={className}
      table={
        <table className="w-full text-body">
          <caption className="sr-only">{title ?? "Chart data"}</caption>
          <thead>
            <tr className="border-b border-border-subtle">
              <th className="py-2 text-left text-label text-text-secondary" scope="col">
                Period
              </th>
              {series.map((s) => (
                <th className="py-2 text-right text-label text-text-secondary" key={s.key} scope="col">
                  {s.label}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {labels.map((label, i) => (
              <tr className="border-b border-border-subtle" key={label}>
                <th className="py-2 text-left font-normal" scope="row">
                  {label}
                </th>
                {series.map((s) => (
                  <td className="py-2 text-right" key={s.key}>
                    <Money accounting value={{ amount: s.values[i], currency }} />
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      }
    >
      <svg
        aria-label={title ?? "Bar chart"}
        className="w-full"
        ref={viewRef}
        role="img"
        style={{ height }}
        viewBox={`0 0 ${width} ${height}`}
      >
        <HatchDefs id={`hatch-${uid}`} />

        {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}
            >
              {axisLabel(t, currency)}
            </text>
          </g>
        ))}

        <line stroke="var(--border-strong)" x1={PAD.left} x2={width - PAD.right} y1={zeroY} y2={zeroY} />

        {labels.map((label, i) => {
          const groupX = PAD.left + i * groupWidth + innerPad / 2;
          let positiveCursor = 0;
          let negativeCursor = 0;

          return (
            <g key={label}>
              {visible.map((s, si) => {
                const v = s.values[i];
                const negative = v < 0;
                let top: number;
                let bottom: number;

                if (mode === "stacked") {
                  const base = negative ? negativeCursor : positiveCursor;
                  const next = base + v;
                  if (negative) negativeCursor = next;
                  else positiveCursor = next;
                  top = y(Math.max(base, next));
                  bottom = y(Math.min(base, next));
                } else {
                  top = y(Math.max(0, v));
                  bottom = y(Math.min(0, v));
                }

                const barX = mode === "stacked" ? groupX : groupX + si * barWidth;
                const h = Math.max(1, bottom - top);

                return (
                  <rect
                    fill={negative ? `url(#hatch-${uid})` : vizColorFor(s.key)}
                    height={h}
                    key={s.key}
                    rx={radius}
                    stroke={negative ? "var(--negative)" : "none"}
                    strokeWidth={negative ? 1 : 0}
                    style={
                      reduced
                        ? undefined
                        : {
                            animation: inView
                              ? `ledger-bar-grow 400ms var(--ease-out) ${Math.min(i * 30, 240)}ms both`
                              : undefined,
                            /* Held flat until the chart is on screen, so the
                               growth is the first thing the reader sees rather
                               than something that finished without them. */
                            transform: inView ? undefined : "scaleY(0)",
                            transformBox: "fill-box",
                            // Grow from the zero baseline, never from the floor.
                            transformOrigin: negative ? "center top" : "center bottom",
                          }
                    }
                    width={Math.max(1, barWidth - 2)}
                    x={barX}
                    y={top}
                  />
                );
              })}
              {mode === "stacked" ? (
                <text
                  className="numeric"
                  fill="var(--text-secondary)"
                  fontSize="11"
                  textAnchor="middle"
                  x={groupX + barWidth / 2}
                  y={y(stackedTotals[i]) - 6}
                >
                  {axisLabel(stackedTotals[i], currency)}
                </text>
              ) : null}
              <text
                className="numeric"
                fill="var(--text-tertiary)"
                fontSize="12"
                textAnchor="middle"
                x={groupX + (mode === "stacked" ? barWidth : barWidth * visible.length) / 2}
                y={height - 8}
              >
                {label}
              </text>
            </g>
          );
        })}
      </svg>

      {series.length > 1 ? (
        <ChartLegend
          className="mt-3"
          isolated={isolated}
          items={series.map((s) => ({ color: vizColorFor(s.key), key: s.key, label: s.label }))}
          onIsolate={setIsolated}
        />
      ) : null}

      <style>
        {"@keyframes ledger-bar-grow { from { transform: scaleY(0); } to { transform: scaleY(1); } }"}
      </style>
    </DataTableToggle>
  );
}

Also in Dashboard & charts

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 MoneyBarChart 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 Dashboard & charts 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.