Skip to content

LedgerTable

Double-entry with debit/credit columns and a balance check.
Implemented
Status
Implemented
Family
5 of 13
Registry
@lopifi/ledger-table
npx shadcn@latest add @lopifi/theme @lopifi/ledger-table

The component, rendering

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

Preview

The four-layer spec

Double-entry. Debit and credit as two separate columns, never one signed column — collapsing them destroys the reader's ability to verify, which is the entire purpose of double-entry. Column totals with the balance check displayed; a failing check is a prominent error state, not a silent discrepancy.

The shared grid model

Every table in this family — and in statements, schedules and the close — is driven by the same two primitives, because an accountant does not distinguish between them. They arrive from a spreadsheet and press the arrow keys.

  • useGridNav for tables that are already client components (TransactionTable). GridKeyboard wraps the ones that are deliberately server-rendered, reading the DOM they produced rather than forcing a rewrite — a 400-row statement should not ship 400 rows of JavaScript to be rendered twice.
  • One tab stop per grid. Tab to the table, arrow within it. Arrows move, Cmd+arrow jumps to the edge, PageUp/PageDown move a screen, Home/End the row, Space selects, Enter opens, Escape collapses.
  • Shift+arrows select a block, Cmd+C copies it — as TSV and as HTML, so every paste target gets its best flavour.
  • The clipboard carries the value, not the presentation. Money stamps every figure with data-raw, so a copied column lands in Excel as -1240.56 and sums. ($1,240.56) pastes as text, and a column of text does not add up.
  • The label column freezes. Any table wider than its container pins its row header with FROZEN_LABEL — scrolling a general ledger sideways and losing the account name is the exact motion this family exists to support.
  • Every column sorts and drags. ColumnHeader for the tables that render their own rows, TableColumns for the ones that render on the server — the same split, and the same reason, as useGridNav and GridKeyboard.

Lifted verbatim from Ledger & tables. 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/ledger-table.tsx

Lopifi dependencies · 10
cnfiscal-periodformat-moneygroup-rowsiconsmoneymoney.typesruletooltipuse-scroll-edges
npm packages
@base-ui-components/reactclass-variance-authorityclsxtailwind-merge
Registry entry
/r/ledger-table.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/ledger-table.tsx
import * as React from "react";
import { useScrollEdges } from "@/hooks/ledger/use-scroll-edges";
import { cn } from "@/lib/ledger/cn";
import { formatDateShort } from "@/lib/ledger/fiscal-period";
import { byMonthDescending, groupRows, monthBucket, type RowGroup } from "@/lib/ledger/group-rows";
import type { MoneyValue } from "@/lib/ledger/money.types";
import { CheckIcon, ExclamationTriangleIcon } from "@/components/ledger/icons";
import { Money } from "@/components/ledger/money";
import { Rule } from "@/components/ledger/rule";

export type LedgerLine = {
  id: string;
  date: Date;
  account: string;
  accountNumber: string;
  memo?: string;
  /** Two separate columns. Never one signed column. */
  debit?: MoneyValue;
  credit?: MoneyValue;
};

export interface LedgerTableProps extends React.ComponentPropsWithoutRef<"div"> {
  /** Whether the sign convention in force is stated in the UI, not assumed. */
  basisNote?: string;
  /**
   * Cut the lines into groups, each with its own header and debit/credit
   * subtotals.
   *
   * `undefined` is a flat ledger, which is what this should open as — a
   * general ledger is posted in date order and that order is information.
   * Grouping by account is the second thing anyone does with it, and grouping
   * by month is how a year of one account gets read.
   *
   * The subtotals are summed from the lines in each group. That is safe here
   * in a way it would not be for the grand totals — which stay passed in,
   * because they are a claim about the whole set and only the backend knows
   * the whole set.
   */
  groupBy?: LedgerGroupKey;
  lines: LedgerLine[];
  /**
   * Caps the scroller so the header and the date/account pair can freeze.
   * Without a height the page scrolls instead and there is nothing for the
   * frozen header to stick to.
   */
  maxHeight?: number;
  totalCredit: MoneyValue;
  /** Passed in, already computed. */
  totalDebit: MoneyValue;
}

/** What a ledger can be cut by. Two, and both are questions people ask. */
export type LedgerGroupKey = "account" | "month";

export const LEDGER_GROUPS: { key: LedgerGroupKey; label: string; hint: string }[] = [
  { hint: "Debits and credits per account", key: "account", label: "Account" },
  { hint: "The year, one month at a time", key: "month", label: "Month" },
];

/**
 * Double-entry. Debit and credit as two separate columns — collapsing them
 * destroys the reader's ability to verify, which is the entire purpose of
 * double-entry.
 *
 * The balance check is displayed, never assumed. A failing check is a
 * prominent error state, not a silent discrepancy.
 */
/* The account column freezes to the right of the date column, so its sticky
   offset is that column's width. Declared once rather than at four call
   sites, because the two have to agree or the pane shears. */
const FREEZE_ACCOUNT = { "--ledger-freeze-left": "92px" } as React.CSSProperties;

export const LedgerTable = React.forwardRef<HTMLDivElement, LedgerTableProps>(
  ({ className, lines, totalDebit, totalCredit, basisNote, maxHeight = 520, groupBy, ...props }, ref) => {
    const scroller = useScrollEdges<HTMLDivElement>();

    /* Debit and credit are subtotalled separately and never netted — the whole
       reason they are two columns is that the reader verifies them against
       each other, and a group header showing one signed number takes that
       away. `amountOf` is left off for the same reason: there is no single
       "amount" on a ledger line to sum. */
    const groups = React.useMemo(() => {
      if (!groupBy) return null;
      return groupRows(lines, {
        compare: groupBy === "month" ? byMonthDescending : undefined,
        keyOf: (l) =>
          groupBy === "account"
            ? { key: l.accountNumber, label: `${l.accountNumber} ${l.account}` }
            : monthBucket(l.date),
      });
    }, [lines, groupBy]);

    const balanced = Number(totalDebit.amount) === Number(totalCredit.amount);
    const difference = Number(totalDebit.amount) - Number(totalCredit.amount);

    return (
      <div className={cn("rounded-xl border border-border bg-surface", className)} ref={ref} {...props}>
        {/* Outside the scroller. A basis note that scrolls away from the
            figures it qualifies is a basis note nobody reads. */}
        <div className="px-6 pb-4 pt-6">
          <p className="text-title-sm font-medium">General ledger detail</p>
          {basisNote ? <p className="text-caption text-text-secondary">{basisNote}</p> : null}
        </div>
        <div className="ledger-frozen scrollbar-thin" ref={scroller} style={{ maxHeight }}>
          <table className="w-full min-w-[720px]">
            <caption className="sr-only">General ledger detail{basisNote ? `. ${basisNote}` : ""}</caption>
            <thead>
              <tr className="border-b border-border-subtle">
                <th
                  className="w-[92px] px-6 py-3 text-left text-label font-medium text-text-secondary"
                  data-frozen="left inner"
                  scope="col"
                >
                  Date
                </th>
                <th
                  className="px-3 py-3 text-left text-label font-medium text-text-secondary"
                  data-frozen="left"
                  scope="col"
                  style={FREEZE_ACCOUNT}
                >
                  Account
                </th>
                <th className="px-3 py-3 text-right text-label font-medium text-text-secondary" scope="col">
                  Debit
                </th>
                <th className="px-6 py-3 text-right text-label font-medium text-text-secondary" scope="col">
                  Credit
                </th>
              </tr>
            </thead>
            <tbody>
              {groups
                ? groups.map((group) => (
                    <React.Fragment key={group.key}>
                      <LedgerGroupHeader currency={totalDebit.currency} group={group} />
                      {group.rows.map((l) => (
                        <tr className="border-b border-border-subtle" key={l.id}>
                          <td
                            className="numeric px-6 py-3 text-figure-sm text-text-secondary"
                            data-frozen="left inner"
                          >
                            {formatDateShort(l.date)}
                          </td>
                          <th className="px-3 py-3 text-left font-normal" scope="row" style={FREEZE_ACCOUNT}>
                            <span className="reference-numeric text-caption text-text-tertiary">
                              {l.accountNumber}
                            </span>{" "}
                            <span className="text-body">{l.account}</span>
                            {l.memo ? (
                              <span className="block text-caption text-text-secondary">{l.memo}</span>
                            ) : null}
                          </th>
                          <td className="px-3 py-3 text-right align-top">
                            {l.debit ? <Money accounting value={l.debit} /> : null}
                          </td>
                          <td className="px-6 py-3 text-right align-top">
                            {l.credit ? <Money accounting value={l.credit} /> : null}
                          </td>
                        </tr>
                      ))}
                    </React.Fragment>
                  ))
                : lines.map((l) => (
                    <tr className="border-b border-border-subtle" key={l.id}>
                      <td
                        className="numeric px-6 py-3 text-figure-sm text-text-secondary"
                        data-frozen="left inner"
                      >
                        {formatDateShort(l.date)}
                      </td>
                      <th className="px-3 py-3 text-left font-normal" scope="row" style={FREEZE_ACCOUNT}>
                        <span className="reference-numeric text-caption text-text-tertiary">
                          {l.accountNumber}
                        </span>{" "}
                        <span className="text-body">{l.account}</span>
                        {l.memo ? (
                          <span className="block text-caption text-text-secondary">{l.memo}</span>
                        ) : null}
                      </th>
                      <td className="px-3 py-3 text-right align-top">
                        {l.debit ? <Money accounting value={l.debit} /> : null}
                      </td>
                      <td className="px-6 py-3 text-right align-top">
                        {l.credit ? <Money accounting value={l.credit} /> : null}
                      </td>
                    </tr>
                  ))}
            </tbody>
            <tfoot>
              <tr>
                <td colSpan={2} data-frozen="left inner" />
                <td className="px-3">
                  <Rule variant="subtotal" />
                </td>
                <td className="px-6">
                  <Rule variant="subtotal" />
                </td>
              </tr>
              <tr>
                <th
                  className="px-6 py-3 text-left text-label font-medium"
                  colSpan={2}
                  data-frozen="left inner"
                  scope="row"
                >
                  Totals
                </th>
                <td className="px-3 py-3 text-right">
                  <Money accounting size="md" value={totalDebit} />
                </td>
                <td className="px-6 py-3 text-right">
                  <Money accounting size="md" value={totalCredit} />
                </td>
              </tr>
              <tr>
                <td colSpan={2} data-frozen="left inner" />
                <td className="px-3">
                  <Rule variant="total" />
                </td>
                <td className="px-6">
                  <Rule variant="total" />
                </td>
              </tr>
            </tfoot>
          </table>
        </div>

        <div
          className={cn(
            "m-6 mt-4 flex items-center gap-2 rounded-sm px-3 py-2",
            balanced ? "bg-positive-subtle text-positive" : "bg-negative-subtle text-negative",
          )}
          role={balanced ? undefined : "alert"}
        >
          {balanced ? (
            <CheckIcon aria-hidden="true" className="size-4 shrink-0" />
          ) : (
            <ExclamationTriangleIcon aria-hidden="true" className="size-4 shrink-0" />
          )}
          <span className="text-body">
            {balanced ? (
              "Debits equal credits."
            ) : (
              <>
                Out of balance by{" "}
                <Money
                  tone="inherit"
                  value={{ amount: Math.abs(difference), currency: totalDebit.currency }}
                />
                . This entry cannot post.
              </>
            )}
          </span>
        </div>
      </div>
    );
  },
);
LedgerTable.displayName = "LedgerTable";

/**
 * A group's own line, with its two subtotals in the columns they belong to.
 *
 * `colSpan={2}` over the frozen pair, marked `inner` so the seam is drawn once
 * at the outer edge and not through the middle of the frozen columns.
 */
function LedgerGroupHeader({ group, currency }: { group: RowGroup<LedgerLine>; currency: string }) {
  const debit = group.rows.reduce((sum, l) => sum + Number(l.debit?.amount ?? 0), 0);
  const credit = group.rows.reduce((sum, l) => sum + Number(l.credit?.amount ?? 0), 0);
  return (
    <tr className="border-b border-border bg-surface-sunken">
      <th
        className="px-6 py-2 text-left text-label font-medium"
        colSpan={2}
        data-frozen="left inner"
        scope="colgroup"
      >
        {group.label}{" "}
        <span className="numeric font-normal text-text-tertiary">{group.count.toLocaleString()}</span>
      </th>
      <td className="px-3 py-2 text-right">
        <Money accounting value={{ amount: debit, currency }} />
      </td>
      <td className="px-6 py-2 text-right">
        <Money accounting value={{ amount: credit, currency }} />
      </td>
    </tr>
  );
}

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 Ledger & tables

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 LedgerTable 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 Ledger & tables 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.