Skip to content

CategoryPicker

Hierarchical with rule creation.
Implemented
Status
Implemented
Family
5 of 13
Registry
@lopifi/category-picker
npx shadcn@latest add @lopifi/theme @lopifi/category-picker

The component, rendering

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

Preview

The four-layer spec

Hierarchical, searchable, keyboard-first. Recents pinned. Inline "create a rule from this" — categorizing one transaction and offering to categorize the other 40 like it is the highest-leverage interaction in bookkeeping software. Rule preview shows the match count before applying.

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/category-picker.tsx

Lopifi dependencies · 3
buttoncnicons
npm packages
@base-ui-components/reactclass-variance-authorityclsxtailwind-merge
Registry entry
/r/category-picker.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/category-picker.tsx
"use client";

import { Popover } from "@base-ui-components/react/popover";
import * as React from "react";
import { cn } from "@/lib/ledger/cn";
import { Button } from "@/components/ledger/button";
import { ChevronDownIcon, MagnifyingGlassIcon, SparklesIcon } from "@/components/ledger/icons";

export type CategoryNode = {
  id: string;
  label: string;
  children?: CategoryNode[];
};

export interface CategoryPickerProps {
  className?: string;
  /** The preview count is shown before the rule is applied, never after. */
  onCreateRule?: (categoryId: string) => { matchCount: number; description: string };
  onValueChange: (id: string) => void;
  recents?: string[];
  tree: CategoryNode[];
  value: string | null;
}

/**
 * Categorizing one transaction and offering to categorize the other 40 like
 * it is the highest-leverage interaction in bookkeeping software. The rule
 * preview shows the match count *before* applying.
 */
export function CategoryPicker({
  tree,
  value,
  onValueChange,
  recents = [],
  onCreateRule,
  className,
}: CategoryPickerProps) {
  const [open, setOpen] = React.useState(false);
  const [query, setQuery] = React.useState("");
  const [rulePreview, setRulePreview] = React.useState<{
    matchCount: number;
    description: string;
  } | null>(null);

  const flat = React.useMemo(() => flatten(tree), [tree]);
  const selected = flat.find((n) => n.id === value);
  const filtered = query ? flat.filter((n) => n.label.toLowerCase().includes(query.toLowerCase())) : flat;

  return (
    <Popover.Root onOpenChange={setOpen} open={open}>
      <Popover.Trigger
        aria-label={selected ? `Category: ${selected.label}` : "Choose a category"}
        className={cn(
          "inline-flex h-8 items-center gap-2 rounded-sm border border-border bg-surface px-3",
          "text-label transition-colors duration-1 ease-standard hover:bg-surface-hover",
          className,
        )}
      >
        {selected?.label ?? "Uncategorized"}
        <ChevronDownIcon aria-hidden="true" className="size-3.5 text-text-tertiary" />
      </Popover.Trigger>
      <Popover.Portal>
        <Popover.Positioner align="start" className="z-dropdown" sideOffset={8}>
          <Popover.Popup
            className="w-[320px] overflow-hidden rounded-md border border-border bg-surface-raised shadow-elevation-3"
            style={{ transformOrigin: "var(--transform-origin)" }}
          >
            <div className="flex items-center gap-2 border-b border-border-subtle px-3">
              <MagnifyingGlassIcon aria-hidden="true" className="size-4 text-text-tertiary" />
              <input
                aria-label="Search categories"
                autoFocus
                className="h-10 flex-1 bg-transparent text-body outline-none"
                onChange={(e) => setQuery(e.target.value)}
                placeholder="Search categories"
                value={query}
              />
            </div>
            <div className="max-h-[280px] overflow-y-auto py-1 scrollbar-thin">
              {!query && recents.length > 0 ? (
                <>
                  <p className="px-3 py-1 text-caption text-text-tertiary">Recent</p>
                  {recents.map((id) => {
                    const node = flat.find((n) => n.id === id);
                    if (!node) return null;
                    return (
                      <Option
                        key={`r-${id}`}
                        node={node}
                        onSelect={() => {
                          onValueChange(id);
                          setRulePreview(onCreateRule?.(id) ?? null);
                        }}
                        selected={id === value}
                      />
                    );
                  })}
                </>
              ) : null}
              {filtered.map((n) => (
                <Option
                  key={n.id}
                  node={n}
                  onSelect={() => {
                    onValueChange(n.id);
                    setRulePreview(onCreateRule?.(n.id) ?? null);
                  }}
                  selected={n.id === value}
                />
              ))}
            </div>

            {rulePreview ? (
              <div className="ledger-crossfade border-t border-border-subtle bg-accent-subtle p-3">
                <p className="flex items-start gap-2 text-caption text-text-primary">
                  <SparklesIcon aria-hidden="true" className="mt-0.5 size-3.5 shrink-0 text-accent" />
                  {rulePreview.description} — this would recategorize{" "}
                  <span className="numeric font-medium">{rulePreview.matchCount}</span> other transactions.
                </p>
                <div className="mt-2 flex gap-2">
                  <Button onClick={() => setRulePreview(null)} size="sm" variant="primary">
                    Create the rule
                  </Button>
                  <Button onClick={() => setRulePreview(null)} size="sm" variant="ghost">
                    Just this one
                  </Button>
                </div>
              </div>
            ) : null}
          </Popover.Popup>
        </Popover.Positioner>
      </Popover.Portal>
    </Popover.Root>
  );
}

type FlatNode = CategoryNode & { depth: number };

function flatten(nodes: CategoryNode[], depth = 0): FlatNode[] {
  return nodes.flatMap((n) => [{ ...n, depth }, ...(n.children ? flatten(n.children, depth + 1) : [])]);
}

function Option({ node, selected, onSelect }: { node: FlatNode; selected: boolean; onSelect: () => void }) {
  return (
    <button
      className={cn(
        "block w-full px-3 py-2 text-left text-body",
        "transition-colors duration-1 ease-standard hover:bg-surface-hover",
        selected && "bg-surface-selected",
        node.children && node.depth === 0 && "font-medium",
      )}
      onClick={onSelect}
      style={{ paddingLeft: 12 + node.depth * 16 }}
      type="button"
    >
      {node.label}
    </button>
  );
}

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 CategoryPicker 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.