# Currency Bar

The HUD wallet: one chip per currency with its icon and amount. When an amount changes it counts up or down and a small "+120" or "−60" floats off the chip. Chips can show a cap with a fill bar (energy), a "+" button, a clickable state, and a shake with a red face for "not enough coins". Screen readers hear one polite message per change, not every frame. The game owns the wallet; this only draws it.

Docs: https://cozy-ui.solo.engineer/docs/components/currency-bar/

Install: `npx shadcn@latest add @cozy/currency-bar`

### Usage

```tsx
import { CurrencyBar } from "@/components/ui/currency-bar"

const [wallet, setWallet] = useState({ coin: 1250, gem: 40, energy: 35 })

<CurrencyBar
  wallet={wallet}
  caps={{ energy: 60 }}
  onAdd={(id) => openShop(id)}
  highlight={notEnough ? "coin" : null}
  onHighlightEnd={() => setNotEnough(false)}
/>
```

### Props

| Prop | Type | Default | Description |
|---|---|---|---|
| wallet | `Wallet` | – | How much of each currency the player has, keyed by currency id: `{ coin: 1250, gem: 40 }`. Required. |
| currencies | `Record<string, Currency>` | `DEFAULT_CURRENCIES` | Currency definitions `{ label, icon?, color? }` by id. `icon` is a node or an image URL; `color` tints the cap bar. |
| show | `string[]` | `keys of wallet` | Which currencies to show and in what order. Default: the keys of `wallet` that exist in `currencies`. |
| onAdd / addable | `(id) => void / string[]` | – | With `onAdd` every chip gets a "+" button (accessible name "Get more Coins"); `addable` limits it to some ids. |
| caps | `Record<string, number>` | – | Upper limit per currency, e.g. `{ energy: 60 }`. Shows "35 / 60" and a thin fill bar. |
| highlight / onHighlightEnd | `string \| null / (id) => void` | `null` | The chip shakes and turns red once each time `highlight` changes to a currency id. Set it back to null in `onHighlightEnd` so the same id can fire again. Under reduced motion it only turns red. |
| compact | `boolean` | `false` | Short numbers: 12500 shows as "12.5K" (from 10,000 up). |
| size | `"sm" \| "md" \| "lg"` | `"md"` | Chip size. |
| orientation | `"horizontal" \| "vertical"` | `"horizontal"` | Chips in a row (wrapping) or a column. |
| onCurrencySelect | `(id) => void` | – | Makes each chip a button, e.g. to open the shop at that currency. |
| labels | `Partial<CurrencyBarLabels>` | `English` | Strings with `{currency}`, `{value}`, `{max}`, `{delta}` placeholders: label, add, amount, amountOfMax, gained, lost. |

The number counts for about 0.65 s and jumps straight to the new value under `prefers-reduced-motion`; the delta then stays still for a moment instead of rising.

Screen readers read a static text per chip ("Coins: 1,250", "Energy: 35 of 60") and get one announcement after changes settle ("Coins up 120, now 1,370"). Rapid changes are merged into one net announcement.

Each chip is a plain group; it becomes a button only when `onCurrencySelect` is set. The "+" button has a 40 px touch target.

### Example

```tsx
import * as React from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { CurrencyBar } from "@/components/ui/currency-bar";
import { CURRENCIES, START_WALLET } from "./economy-data";

export default function Demo() {
  const [wallet, setWallet] = React.useState(START_WALLET);
  const [highlight, setHighlight] = React.useState<string | null>(null);
  const add = (id: string, n: number) => setWallet((w) => ({ ...w, [id]: Math.max(0, w[id] + n) }));

  return (
    <div className="flex w-full flex-col items-center gap-8">
      <CurrencyBar
        wallet={wallet}
        currencies={CURRENCIES}
        caps={{ energy: 60 }}
        onAdd={(id) => toast(`Open the ${CURRENCIES[id].label} shop`)}
        addable={["coin", "gem"]}
        highlight={highlight}
        onHighlightEnd={() => setHighlight(null)}
      />
      <div className="flex flex-wrap justify-center gap-3">
        <Button variant="reward" size="sm" onClick={() => add("coin", 120)}>Earn 120 coins</Button>
        <Button variant="outline" size="sm" onClick={() => add("coin", -60)}>Spend 60 coins</Button>
        <Button variant="secondary" size="sm" onClick={() => add("gem", 5)}>Find 5 gems</Button>
        <Button variant="outline" size="sm" onClick={() => add("energy", -10)}>Use 10 energy</Button>
        <Button variant="destructive" size="sm" onClick={() => { setHighlight("coin"); toast("Not enough coins"); }}>Buy something too expensive</Button>
      </div>
    </div>
  );
}
```

### Source (components/ui/currency-bar.tsx)

```tsx
import * as React from "react";
import { cn } from "@/lib/utils";
import { DEFAULT_CURRENCIES, formatAmount, type Currency, type Wallet } from "./economy-core";
import { GameIcon } from "./game-core";

/* The HUD wallet: one chip per currency with its icon and amount. Amounts
   count up and down, a small delta floats off the chip, and screen readers
   get one polite announcement per change (not one per frame). The game owns
   the wallet; this only draws it. */

/** Strings used by CurrencyBar. `{currency}`, `{value}`, `{max}` and `{delta}` are replaced. */
export type CurrencyBarLabels = {
  /** Accessible name of the whole bar. Default "Wallet". */
  label: string;
  /** Name of the "+" button. Default "Get more {currency}". */
  add: string;
  /** Screen reader text of a chip. Default "{currency}: {value}". */
  amount: string;
  /** Screen reader text of a chip with a cap. Default "{currency}: {value} of {max}". */
  amountOfMax: string;
  /** Announced when an amount goes up. Default "{currency} up {delta}, now {value}". */
  gained: string;
  /** Announced when an amount goes down. Default "{currency} down {delta}, now {value}". */
  lost: string;
};

const DEFAULT_LABELS: CurrencyBarLabels = {
  label: "Wallet",
  add: "Get more {currency}",
  amount: "{currency}: {value}",
  amountOfMax: "{currency}: {value} of {max}",
  gained: "{currency} up {delta}, now {value}",
  lost: "{currency} down {delta}, now {value}",
};

const fill = (tpl: string, vars: Record<string, string>) => tpl.replace(/\{(\w+)\}/g, (_, k: string) => vars[k] ?? "");

type CurrencyBarProps = Omit<React.ComponentProps<"div">, "children"> & {
  /** How much of each currency the player has: `{ coin: 1250, gem: 40 }`. */
  wallet: Wallet;
  /** Currency definitions by id (label, icon, color). Default `DEFAULT_CURRENCIES` (coin, gem). */
  currencies?: Record<string, Currency>;
  /** Which currencies to show, in this order. Default: the keys of `wallet` that exist in `currencies`. */
  show?: string[];
  /** Shows a "+" button on each chip (or those in `addable`). Gets the currency id. */
  onAdd?: (currencyId: string) => void;
  /** Currency ids that get the "+" button. Default: all shown, when `onAdd` is set. */
  addable?: string[];
  /** Upper limit per currency, e.g. `{ energy: 60 }`. Shows "35 / 60" and a thin fill bar. */
  caps?: Record<string, number>;
  /** Shakes this chip and turns it red, once each time it changes to a currency id (e.g. "not enough coins"). Set it back to null in `onHighlightEnd` so the same id can fire again. Default null. */
  highlight?: string | null;
  /** Called with the currency id when the highlight animation is over. */
  onHighlightEnd?: (currencyId: string) => void;
  /** Short amounts: 12500 shows as "12.5K". Default false. */
  compact?: boolean;
  /** Chip size. Default "md". */
  size?: "sm" | "md" | "lg";
  /** Lay chips out in a row or a column. Default "horizontal". */
  orientation?: "horizontal" | "vertical";
  /** Makes each chip a button (e.g. to open the shop on that currency). Gets the currency id. */
  onCurrencySelect?: (currencyId: string) => void;
  /** Override any built-in string (for translation). */
  labels?: Partial<CurrencyBarLabels>;
};

function useReducedMotion() {
  const [reduced, setReduced] = React.useState(false);
  React.useEffect(() => {
    const m = window.matchMedia?.("(prefers-reduced-motion: reduce)");
    if (!m) return;
    const sync = () => setReduced(m.matches);
    sync();
    m.addEventListener("change", sync);
    return () => m.removeEventListener("change", sync);
  }, []);
  return reduced;
}

/** Eases the shown number toward `target`; jumps straight there when `instant`. */
function useCountTo(target: number, instant: boolean, duration = 650) {
  const [shown, setShown] = React.useState(target);
  const current = React.useRef(target);
  React.useEffect(() => {
    if (instant) {
      current.current = target;
      setShown(target);
      return;
    }
    const from = current.current;
    if (from === target) return;
    const t0 = performance.now();
    let raf = 0;
    const tick = (now: number) => {
      const p = Math.min(1, (now - t0) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      current.current = p >= 1 ? target : from + (target - from) * eased;
      setShown(Math.round(current.current));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, instant, duration]);
  return shown;
}

type Delta = { key: number; amount: number };

type ChipProps = {
  id: string;
  currency: Currency;
  value: number;
  cap?: number;
  compact: boolean;
  alert: number | null;
  instant: boolean;
  canAdd: boolean;
  onAdd?: (id: string) => void;
  onSelect?: (id: string) => void;
  labels: CurrencyBarLabels;
};

function Chip({ id, currency, value, cap, compact, alert, instant, canAdd, onAdd, onSelect, labels }: ChipProps) {
  const shown = useCountTo(value, instant);
  const [deltas, setDeltas] = React.useState<Delta[]>([]);
  const [announcement, setAnnouncement] = React.useState("");
  const prev = React.useRef(value);
  const pending = React.useRef(0);
  const seq = React.useRef(0);
  const timers = React.useRef<number[]>([]);
  const announceTimer = React.useRef<number>(0);

  React.useEffect(() => {
    const diff = value - prev.current;
    prev.current = value;
    if (diff === 0) return;
    const key = ++seq.current;
    setDeltas((d) => [...d.slice(-2), { key, amount: diff }]);
    timers.current.push(window.setTimeout(() => setDeltas((d) => d.filter((x) => x.key !== key)), 1400));
    // one announcement after the changes settle, with the net change
    pending.current += diff;
    window.clearTimeout(announceTimer.current);
    announceTimer.current = window.setTimeout(() => {
      const net = pending.current;
      pending.current = 0;
      if (net === 0) return;
      setAnnouncement(fill(net > 0 ? labels.gained : labels.lost, { currency: currency.label, delta: formatAmount(Math.abs(net)), value: formatAmount(value) }));
    }, 500);
  }, [value]); // eslint-disable-line react-hooks/exhaustive-deps

  React.useEffect(() => () => {
    timers.current.forEach(window.clearTimeout);
    window.clearTimeout(announceTimer.current);
  }, []);

  const text = cap != null
    ? fill(labels.amountOfMax, { currency: currency.label, value: formatAmount(value), max: formatAmount(cap) })
    : fill(labels.amount, { currency: currency.label, value: formatAmount(value) });

  const body = (
    <>
      <span className="cz-currency__icon" aria-hidden><GameIcon icon={currency.icon} alt="" /></span>
      <span className="cz-currency__text" aria-hidden>
        <span className="cz-currency__line">
          <span className="cz-currency__value">{formatAmount(shown, compact)}</span>
          {cap != null && <span className="cz-currency__max">/ {formatAmount(cap, compact)}</span>}
        </span>
        {cap != null && (
          <span className="cz-currency__cap"><span className="cz-currency__cap-fill" style={{ width: `${cap > 0 ? Math.max(0, Math.min(1, shown / cap)) * 100 : 0}%` }} /></span>
        )}
      </span>
      <span className="cz-sr-only">{text}</span>
    </>
  );

  return (
    <div
      data-slot="currency-bar-chip"
      data-currency={id}
      data-alert={alert ?? undefined}
      data-full={cap != null && value >= cap ? "" : undefined}
      data-addable={canAdd || undefined}
      className="cz-currency"
      style={currency.color ? ({ "--cur": currency.color } as React.CSSProperties) : undefined}
    >
      {onSelect ? (
        <button type="button" className="cz-currency__main" onClick={() => onSelect(id)}>{body}</button>
      ) : (
        <div className="cz-currency__main">{body}</div>
      )}
      {canAdd && (
        <button type="button" className="cz-currency__add" aria-label={fill(labels.add, { currency: currency.label })} onClick={() => onAdd?.(id)}>
          <svg viewBox="0 0 16 16" aria-hidden><path d="M8 3v10M3 8h10" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" /></svg>
        </button>
      )}
      <span className="cz-currency__deltas" aria-hidden>
        {deltas.map((d) => (
          <span key={d.key} className="cz-currency__delta" data-sign={d.amount > 0 ? "up" : "down"}>
            {d.amount > 0 ? "+" : "−"}{formatAmount(Math.abs(d.amount), compact)}
          </span>
        ))}
      </span>
      <span className="cz-sr-only" aria-live="polite" aria-atomic="true">{announcement}</span>
    </div>
  );
}

/** The HUD wallet: a chip per currency with animated amounts, floating deltas, optional caps, "+" buttons and a "not enough" shake. */
function CurrencyBar({
  wallet, currencies = DEFAULT_CURRENCIES, show, onAdd, addable, caps, highlight = null, onHighlightEnd,
  compact = false, size = "md", orientation = "horizontal", onCurrencySelect, labels: labelsProp, className, ...props
}: CurrencyBarProps) {
  const labels = { ...DEFAULT_LABELS, ...labelsProp };
  const reduced = useReducedMotion();
  const ids = show ?? Object.keys(wallet).filter((k) => k in currencies);

  // `n` flips between 0 and 1 so the shake restarts when the same chip is hit twice
  const [alert, setAlert] = React.useState<{ id: string; n: number } | null>(null);
  const endRef = React.useRef(onHighlightEnd);
  endRef.current = onHighlightEnd;
  const alertTimer = React.useRef(0);
  const reducedRef = React.useRef(reduced);
  reducedRef.current = reduced;
  React.useEffect(() => {
    if (!highlight) return;
    window.clearTimeout(alertTimer.current);
    setAlert((a) => ({ id: highlight, n: a ? 1 - a.n : 0 }));
    alertTimer.current = window.setTimeout(() => {
      setAlert(null);
      endRef.current?.(highlight);
    }, reducedRef.current ? 900 : 700);
  }, [highlight]);
  React.useEffect(() => () => window.clearTimeout(alertTimer.current), []);

  return (
    <div role="group" aria-label={labels.label} data-slot="currency-bar" data-size={size} data-orientation={orientation} className={cn("cz-currency-bar", className)} {...props}>
      {ids.map((id) => (
        <Chip
          key={id}
          id={id}
          currency={currencies[id] ?? { label: id }}
          value={wallet[id] ?? 0}
          cap={caps?.[id]}
          compact={compact}
          alert={alert?.id === id ? alert.n : null}
          instant={reduced}
          canAdd={!!onAdd && (!addable || addable.includes(id))}
          onAdd={onAdd}
          onSelect={onCurrencySelect}
          labels={labels}
        />
      ))}
    </div>
  );
}

export { CurrencyBar };
export type { CurrencyBarProps };
```

npm: `import { CurrencyBar } from "@0xtrou/cozy-ui"` (after `npm install @0xtrou/cozy-ui` and `import "@0xtrou/cozy-ui/styles.css"`).
