# Spending Ring
> A spending breakdown you spin like a dial; flick the ring and it settles with a category under the marker.

## Installation

```bash
npx shadcn@latest add @kokonutui/spending-ring
```

## Props

| Prop           | Type                 | Default                | Description |
|----------------|----------------------|------------------------|-------------|
| `title?`      | `string`             | `"October spending"` |             |
| `categories?` | `SpendingCategory[]` | `built-in`           |             |
| `currency?`   | `string`             | `"USD"`              |             |
| `className?`  | `string`             |                        | Extra classes for the root element. |

### SpendingCategory

| Field   | Type   | Description                           |
|---------|--------|---------------------------------------|
| `name`  | `string`  |                                       |
| `amount`| `number`  |                                       |
| `change?`| `number`| Change from last month, in percent.   |
| `stroke`| `string` | Tailwind classes for the segment stroke and the legend dot. |
| `dot`   | `string` |                                       |

## Source

```tsx
"use client";

export interface SpendingCategory {
  name: string;
  amount: number;
  /** Change from last month, in percent. */
  change?: number;
  /** Tailwind classes for the segment stroke and the legend dot. */
  stroke: string;
  dot: string;
}

export interface SpendingRingProps {
  title?: string;
  categories?: SpendingCategory[];
  currency?: string;
  className?: string;
}

const DEFAULT_CATEGORIES: SpendingCategory[] = [
  {
    name: "Housing",
    amount: 1250,
    change: 0,
    stroke: "stroke-sky-500 dark:stroke-sky-400",
    dot: "bg-sky-500 dark:bg-sky-400",
  },
  {
    name: "Groceries",
    amount: 486.2,
    change: -6.1,
    stroke: "stroke-emerald-500 dark:stroke-emerald-400",
    dot: "bg-emerald-500 dark:bg-emerald-400",
  },
  {
    name: "Shopping",
    amount: 398.1,
    change: 22.4,
    stroke: "stroke-rose-500 dark:stroke-rose-400",
    dot: "bg-rose-500 dark:bg-rose-400",
  },
  {
    name: "Dining out",
    amount: 312.75,
    change: 12.8,
    stroke: "stroke-amber-400 dark:stroke-amber-300",
    dot: "bg-amber-400 dark:bg-amber-300",
  },
  {
    name: "Transport",
    amount: 214.4,
    change: -3.5,
    stroke: "stroke-violet-500 dark:stroke-violet-400",
    dot: "bg-violet-500 dark:bg-violet-400",
  },
  {
    name: "Subscriptions",
    amount: 86.97,
    change: 0,
    stroke: "stroke-zinc-400 dark:stroke-zinc-500",
    dot: "bg-zinc-400 dark:bg-zinc-500",
  },
];

/** Wraps an angle into -180..180. */
const wrap = (deg: number) => ((((deg + 180) % 360) + 360) % 360) - 180);

/** A point on the ring, with 0° at the top and angles running clockwise. */
function polar(deg: number, r = R) {
  const rad = (deg * Math.PI) / 180;
  return [C + r * Math.sin(rad), C - r * Math.cos(rad)] as const;
}

function arc(from: number, to: number) {
  const [x0, y0] = polar(from);
  const [x1, y1] = polar(to);
  const large = to - from > 180 ? 1 : 0;
  return `M${x0.toFixed(2)} ${y0.toFixed(2)} A${R} ${R} 0 ${large} 1 ${x1.toFixed(2)} ${y1.toFixed(2)}`;
}

/** The category whose slice covers an angle on the ring. */
function sliceAt(spans: { from: number; to: number }[], deg: number) {
  const a = ((deg % 360) + 360) % 360;
  const index = spans.findIndex((s) => a >= s.from && a < s.to);
  return index === -1 ? 0 : index;
}

/** One step of a damped spring, in small slices for stability. */
function springStep(state: { a: number; v: number }, target: number, dt: number) {
  // ... implementation ...
}

export default function SpendingRing({
  title = "October spending",
  categories = DEFAULT_CATEGORIES,
  currency = "USD",
  className,
}: SpendingRingProps) {
  const [selected, setSelected] = useState(0);
  const [dragging, setDragging] = useState(false);
  const ringRef = useRef<SVGGElement>(null);
  const selectedRef = useRef(0);

const total = categories.reduce((sum, c) => sum + c.amount, 0);
  const spans = useMemo(() => {
    // ... implementation ...
  }, [categories, total]);

const money = useMemo(() => new Intl.NumberFormat("en-US", { style: "currency", currency, maximumFractionDigits: 2, minimumFractionDigits: 2 }), [currency]);

/** Show whichever slice is under the marker right now. */
  const track = useCallback(() => {
    const index = sliceAt(spans, -sim.current.a);
    if (index !== selectedRef.current) {
      selectedRef.current = index;
      setSelected(index);
    }
  }, [spans]);

const tick = useCallback((now: number) => { /* ... implementation ... */ }, [paint, track]);

const turnTo = useCallback((index: number, rest = sim.current.a, coast = false) => { /* ... implementation ... */ }, [paint, spans, tick, track]);

return (
    <div className={cn("w-full max-w-sm rounded-3xl border border-zinc-200 bg-white p-5 text-zinc-900 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-100", className)}>
      <div className="flex items-baseline justify-between gap-4">
        <p className="text-sm text-zinc-500 dark:text-zinc-400">{title}</p>
        <p className="font-medium text-sm tabular-nums">{money.format(total)}</p>
      </div>
      <div aria-label="Spending by category. Use the arrow keys to turn the ring." aria-valuemax={categories.length} aria-valuemin={1} aria-valuenow={selected + 1} aria-valuetext={current ? `${current.name}, ${money.format(current.amount)}` : ""} className={cn("relative mx-auto mt-3 aspect-square w-full max-w-[240px] touch-none select-none rounded-full outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 focus-visible:ring-offset-4 dark:focus-visible:ring-offset-zinc-950", dragging ? "cursor-grabbing" : "cursor-grab")} role="slider" tabIndex={0}>
        <svg aria-hidden="true" className="absolute inset-0 size-full" viewBox={`0 0 ${SIZE} ${SIZE}`}> {/* SVG CONTENT */} </svg>
        <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center text-center"> {/* SPENDING DETAILS */} </div>
      </div>
      <ul className="mt-4 grid grid-cols-2 gap-1">{categories.map((category, i) => ( <li key={category.name}> {/* CATEGORY BUTTON */} </li>))}</ul>
    </div>
  );
}
```
