{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "seat-chart",
  "type": "registry:ui",
  "title": "Seat Chart",
  "description": "How an assembly divides its seats: a half-circle of dots, one per seat, filled group by group. It answers the question a results table cannot answer at a glance: who holds the room, and how far each side is from a majority.",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "data",
    "chart"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/skeleton.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/charts/seat-chart.tsx",
      "target": "components/ui/charts/seat-chart.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/seat-chart v1.2.1 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/seat-chart\n// What changed since: https://ds.interlace.tools/c/seat-chart#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — SeatChart\n *\n * How an assembly divides its seats: a half-circle of dots, one per seat,\n * filled group by group. It answers the question a results table cannot\n * answer at a glance: who holds the room, and how far each side is from a\n * majority.\n *\n * ## The layout\n *\n * Seats sit on concentric rows of the half-circle with one pitch for every\n * row, so seats are evenly spaced along each arc and between arcs. The row\n * count is the smallest that holds the total; each row takes a share of the\n * seats in proportion to its length. All seats are then ordered by angle and\n * handed to the groups in turn, so each group is a wedge, and the seat at the\n * top centre is the one a majority must reach. `seatLayout()` is exported\n * and pure, so the geometry is tested on its own.\n *\n * ## Sides\n *\n * Pass `sides` (government and opposition, say; they are only labelled\n * props) and give each group a `side`. Each side has one tone, and every\n * group in it takes a distinguishable shade of that tone, so the split reads\n * in colour first and the groups inside it second. The first side fills from\n * the left end, the last from the right end, and anything else sits between\n * them, next to the majority mark. Big totals for each side sit above the\n * arc (`tally`). Without sides, each group has its own colour: the five\n * chart hues in order, then the same hues alternately deeper and paler, then\n * a pale grey; a tone used\n * twice gets its next shade, so neighbours never merge. There are five\n * shades per tone: a sixth group on one side starts the shades again, so\n * split a side that large across two tones, or rely on the legend counts.\n *\n * ## Colour is never the only channel\n *\n * The legend prints every count beside its name, by side. The SVG is one\n * `role=\"img\"` with a sentence that names the total, every side and group,\n * and who is how far from a majority. A table of groups, sides, seats and\n * shares sits behind the picture (`showTable` shows it). Seats no group\n * holds are drawn as outlines and counted as vacant. Every shade keeps 3:1\n * against the page in light and dark.\n *\n * ## Pointing at a group\n *\n * Hovering a seat or a legend entry, or focusing a legend entry, dims every\n * other group and puts that group's count in the middle of the arc. A click\n * on a legend entry pins it (`aria-pressed`); a second click lets go. The\n * dimming is a colour change, instant under reduced motion.\n *\n * ## Motion\n *\n * The whole chart is in the server HTML. The first time it scrolls into\n * view, the seats fill in once, left to right, in under a second. Under\n * `prefers-reduced-motion` they are simply there. It runs on the Web\n * Animations API, so there are no keyframes to add.\n *\n * ## Container, not viewport\n *\n * The SVG scales to its box up to 36rem, the numbers are HTML sized against\n * the chart's own width, and the legend fills as many 11–14rem columns as\n * that width holds. `SeatChartCompare` sets two or three charts side by side\n * once its own box is wide enough for them, and stacks them otherwise.\n *\n * ## MIN_VIEWPORT — 320\n *\n * ## Anatomy\n *\n *   <figure data-slot=\"seat-chart\" data-min-viewport=\"320\">\n *     <figcaption>{label}</figcaption>\n *     <div data-slot=\"seat-chart-tally\" />                       (big side totals)\n *     <div data-slot=\"seat-chart-plot\">\n *       <svg role=\"img\" aria-label=\"{summary}\">\n *         <circle data-slot=\"seat-chart-seat\" data-group=\"0\" /> × total\n *         <line data-slot=\"seat-chart-majority\" />\n *       </svg>\n *       <p data-slot=\"seat-chart-total\" aria-hidden />          (the number in the hollow)\n *     </div>\n *     <p data-slot=\"seat-chart-readout\" />                       (majority caption)\n *     <div data-slot=\"seat-chart-legend\"> <button aria-pressed /> × groups </div>\n *     <table data-slot=\"seat-chart-table\" />                     (sr-only unless showTable)\n *   </figure>\n *\n * | Rule | Concept                    | Where in this file                                        |\n * | ---- | -------------------------- | --------------------------------------------------------- |\n * | R4   | Extends native el          | `React.ComponentProps<'figure'>`                           |\n * | R6   | data-slot on every part    | `seat-chart` / `-plot` / `-seat` / `-legend` / `-table`     |\n * | R7   | className merged + ...rest | `cn(...)` + `{...props}`                                   |\n * | R8   | Enums, not booleans        | `tone`, `tally: 'none' \\| 'sides' \\| 'leaders'`             |\n * | R13  | Ecosystem first            | no charting dep: `seatLayout` + SVG                        |\n * | R14  | Declares min viewport      | `data-min-viewport={String(MIN_VIEWPORT)}`                 |\n * | R18  | Tailwind only              | zero inline `style`; the reveal runs on WAAPI              |\n * | R19  | Tokens only                | `--chart-1..5`, `--muted-foreground`, mixed with `--foreground` |\n * | R23  | Loading reserves its box   | `loading` → `<Skeleton variant=\"chart\">`                   |\n * | R25  | Client component           | the reveal and the highlight run in the browser            |\n * | R26  | A11y                       | `role=\"img\"` + sentence + counts in the legend + table     |\n */\n\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { Skeleton } from '@/components/ui/skeleton';\n\nexport const MIN_VIEWPORT = 320 as const;\n\nexport type SeatTone = 1 | 2 | 3 | 4 | 5 | 'neutral';\n\nexport type SeatSide = {\n  /** What groups name in their `side`. */\n  id: string;\n  /** The side's name, such as \"Coalition\". */\n  label: string;\n  /** The tone family every group on this side is a shade of. */\n  tone: SeatTone;\n};\n\nexport type SeatGroup = {\n  /** The group's name, as the legend and the table print it. */\n  label: string;\n  /** Seats it holds. */\n  seats: number;\n  /** The `id` of the side it sits with. */\n  side?: string;\n  /** Its colour. On a side, the side's tone is the default. @default the five hues, then the same hues deeper and paler in turn, then grey */\n  tone?: SeatTone;\n};\n\nexport type SeatTally = 'none' | 'sides' | 'leaders';\n\n/**\n * Five shades per tone, in the order groups take them. Shade 0 is the token;\n * shade 1 is it deepened (30% toward black), which stays far from the token in\n * both schemes; shade 2 leans toward the page (18%, 22% for grey); shades 3 and 4 grey it toward\n * the muted text and pull it toward the text colour, and sit closer to the\n * others, so they come last. Each keeps 3:1 against the page in the default\n * light and dark themes. Written out in full so Tailwind sees every class.\n */\nconst SHADES: Record<SeatTone, readonly string[]> = {\n  1: [\n    'fill-chart-1',\n    'fill-[color-mix(in_oklab,var(--chart-1),black_30%)]',\n    'fill-[color-mix(in_oklab,var(--chart-1),var(--background)_18%)]',\n    'fill-[color-mix(in_oklab,var(--chart-1),var(--muted-foreground)_50%)]',\n    'fill-[color-mix(in_oklab,var(--chart-1),var(--foreground)_75%)]',\n  ],\n  2: [\n    'fill-chart-2',\n    'fill-[color-mix(in_oklab,var(--chart-2),black_30%)]',\n    'fill-[color-mix(in_oklab,var(--chart-2),var(--background)_18%)]',\n    'fill-[color-mix(in_oklab,var(--chart-2),var(--muted-foreground)_50%)]',\n    'fill-[color-mix(in_oklab,var(--chart-2),var(--foreground)_75%)]',\n  ],\n  3: [\n    'fill-chart-3',\n    'fill-[color-mix(in_oklab,var(--chart-3),black_30%)]',\n    'fill-[color-mix(in_oklab,var(--chart-3),var(--background)_18%)]',\n    'fill-[color-mix(in_oklab,var(--chart-3),var(--muted-foreground)_50%)]',\n    'fill-[color-mix(in_oklab,var(--chart-3),var(--foreground)_75%)]',\n  ],\n  4: [\n    'fill-chart-4',\n    'fill-[color-mix(in_oklab,var(--chart-4),black_30%)]',\n    'fill-[color-mix(in_oklab,var(--chart-4),var(--background)_18%)]',\n    'fill-[color-mix(in_oklab,var(--chart-4),var(--muted-foreground)_50%)]',\n    'fill-[color-mix(in_oklab,var(--chart-4),var(--foreground)_75%)]',\n  ],\n  5: [\n    'fill-chart-5',\n    'fill-[color-mix(in_oklab,var(--chart-5),black_30%)]',\n    'fill-[color-mix(in_oklab,var(--chart-5),var(--background)_18%)]',\n    'fill-[color-mix(in_oklab,var(--chart-5),var(--muted-foreground)_50%)]',\n    'fill-[color-mix(in_oklab,var(--chart-5),var(--foreground)_75%)]',\n  ],\n  neutral: [\n    'fill-muted-foreground',\n    'fill-[color-mix(in_oklab,var(--muted-foreground),black_30%)]',\n    'fill-[color-mix(in_oklab,var(--muted-foreground),var(--background)_22%)]',\n    'fill-[color-mix(in_oklab,var(--muted-foreground),var(--foreground)_55%)]',\n    'fill-[color-mix(in_oklab,var(--muted-foreground),var(--foreground)_75%)]',\n  ],\n};\n\n// ─────────────────────────────────────────────────────────────────\n// Geometry\n// ─────────────────────────────────────────────────────────────────\n\n/** Inner radius of the half-circle, as a share of the outer. The hollow holds the total. */\nconst INNER = 0.4;\n\nexport type Seat = {\n  /** Distance from the centre, 0 to 1 (1 = the outer row). */\n  r: number;\n  /** Angle in radians, π (left) to 0 (right). */\n  angle: number;\n  /** Row index, 0 = the innermost. */\n  row: number;\n};\n\nexport type SeatLayout = {\n  seats: Seat[];\n  rows: number;\n  /** Distance between neighbouring seats, in the same unit as `r`. */\n  pitch: number;\n};\n\nfunction rowRadii(rows: number): { radii: number[]; pitch: number } {\n  if (rows === 1) return { radii: [(1 + INNER) / 2], pitch: 1 - INNER };\n  const pitch = (1 - INNER) / (rows - 1);\n  return { radii: Array.from({ length: rows }, (_, i) => INNER + i * pitch), pitch };\n}\n\nconst capacity = (r: number, pitch: number) => Math.floor((Math.PI * r) / pitch) + 1;\n\n/**\n * Place `total` seats on a half-circle: the fewest rows that hold them,\n * seats shared between rows by length, all ordered left to right.\n */\nexport function seatLayout(total: number): SeatLayout {\n  const count = Math.max(0, Math.floor(total));\n  if (count === 0) return { seats: [], rows: 0, pitch: 0 };\n\n  let rows = 1;\n  let shape = rowRadii(rows);\n  while (shape.radii.reduce((sum, r) => sum + capacity(r, shape.pitch), 0) < count) {\n    rows += 1;\n    shape = rowRadii(rows);\n  }\n  const { radii, pitch } = shape;\n\n  // Share the seats by row length: each row takes its whole share, and the\n  // seats left over go to the rows with the largest remainders.\n  const length = radii.reduce((sum, r) => sum + r, 0);\n  const exact = radii.map((r) => (count * r) / length);\n  const perRow = exact.map(Math.floor);\n  const left = count - perRow.reduce((sum, n) => sum + n, 0);\n  exact\n    .map((x, i) => ({ i, rest: x - Math.floor(x) }))\n    .sort((a, b) => b.rest - a.rest)\n    .slice(0, left)\n    .forEach(({ i }) => {\n      perRow[i]! += 1;\n    });\n\n  const seats: Seat[] = [];\n  radii.forEach((r, row) => {\n    const n = perRow[row]!;\n    for (let k = 0; k < n; k++) {\n      const angle = n === 1 ? Math.PI / 2 : Math.PI * ((n - 1 - k) / (n - 1));\n      seats.push({ r, angle, row });\n    }\n  });\n  // Left to right; on a tie, the outer row first, so a wedge fills its\n  // column from the rim inward.\n  seats.sort((a, b) => b.angle - a.angle || b.r - a.r);\n  return { seats, rows, pitch };\n}\n\n\n// ─────────────────────────────────────────────────────────────────\n// Who sits where\n// ─────────────────────────────────────────────────────────────────\n\nexport type PlacedGroup = SeatGroup & {\n  /** Position in the `groups` prop. */\n  index: number;\n  /** The side's position in `sides`, or -1 when it has none. */\n  sideIndex: number;\n  tone: SeatTone;\n  /** Which shade of its tone it takes. */\n  shade: number;\n};\n\n/**\n * The colour each group takes when it names no tone and no side, in order.\n * The five hues first; then the five again, alternating deeper and paler so\n * neighbouring hues in the second round also differ in lightness (green and\n * teal, orange and gold sit far apart); then a pale grey; then the rounds\n * swapped. Measured on the default tokens: every added colour sits at least\n * as far from the rest as the base palette's own closest pair, in light and\n * dark.\n */\nconst DEFAULT_COLOURS: readonly (readonly [SeatTone, number])[] = [\n  [1, 0], [2, 0], [3, 0], [4, 0], [5, 0],\n  [1, 1], [2, 2], [3, 1], [4, 2], [5, 1],\n  ['neutral', 2],\n  [1, 2], [2, 1], [3, 2], [4, 1], [5, 2],\n  ['neutral', 0], ['neutral', 1],\n];\n\n/**\n * Order the groups along the arc and give each its colour. With sides, the\n * first side runs from the left end, the last from the right end, and the\n * rest sit between; each group takes the next shade of its side's tone.\n * Without sides, groups keep their order and a repeated tone takes its next\n * shade. A group with no tone and no side takes the next free entry of\n * `DEFAULT_COLOURS`, so eleven lists get eleven colours. Groups that name a\n * tone claim their shades first, so the two kinds never share a fill.\n */\nexport function placeGroups(groups: readonly SeatGroup[], sides: readonly SeatSide[] = []): PlacedGroup[] {\n  const sideAt = (id?: string) => sides.findIndex((side) => side.id === id);\n  // Shades already taken per tone, so a group with its own tone and a group\n  // given a default colour never share a fill.\n  const taken = new Map<string, Set<number>>();\n  const take = (key: string, shade?: number) => {\n    const set = taken.get(key) ?? new Set<number>();\n    taken.set(key, set);\n    let n = shade ?? 0;\n    if (shade === undefined) while (set.has(n)) n += 1;\n    set.add(n);\n    return n;\n  };\n  const isTaken = ([tone, shade]: readonly [SeatTone, number]) =>\n    taken.get(`tone:${tone}`)?.has(shade) ?? false;\n  // Groups that name a tone or a side claim their shades first, in order.\n  const fixed = groups.map((group) => {\n    const side = sides[sideAt(group.side)];\n    if (group.tone) return take(`tone:${group.tone}`);\n    if (side) {\n      const shade = take(`side:${side.id}`);\n      take(`tone:${side.tone}`, shade);\n      return shade;\n    }\n    return undefined;\n  });\n  // The rest take the next default colour that is still free.\n  let cursor = 0;\n  const nextDefault = () => {\n    for (let tries = 0; tries < DEFAULT_COLOURS.length; tries += 1) {\n      const colour = DEFAULT_COLOURS[cursor % DEFAULT_COLOURS.length]!;\n      cursor += 1;\n      if (!isTaken(colour)) return colour;\n    }\n    return DEFAULT_COLOURS[(cursor - 1) % DEFAULT_COLOURS.length]!;\n  };\n  const placed = groups.map((group, index): PlacedGroup => {\n    const sideIndex = sideAt(group.side);\n    const side = sides[sideIndex];\n    let tone: SeatTone = group.tone ?? side?.tone ?? 'neutral';\n    let shade = fixed[index];\n    if (shade === undefined) {\n      const colour = nextDefault();\n      tone = colour[0];\n      shade = take(`tone:${tone}`, colour[1]);\n    }\n    return {\n      ...group,\n      seats: Math.max(0, Math.floor(group.seats)),\n      index,\n      sideIndex,\n      tone,\n      shade,\n    };\n  });\n  if (sides.length === 0) return placed;\n\n  const last = sides.length - 1;\n  const left = placed.filter((g) => g.sideIndex === 0);\n  const right = last > 0 ? placed.filter((g) => g.sideIndex === last).reverse() : [];\n  // Middle sides in their own order, then groups with no side.\n  const middle = [\n    ...sides.slice(1, last).flatMap((_, k) => placed.filter((g) => g.sideIndex === k + 1)),\n    ...placed.filter((g) => g.sideIndex === -1),\n  ];\n  return [...left, ...middle, ...right];\n}\n\n// ─────────────────────────────────────────────────────────────────\n// Words\n// ─────────────────────────────────────────────────────────────────\n\nconst plural = (n: number, one: string, many: string, number: (n: number) => string) =>\n  `${number(n)} ${n === 1 ? one : many}`;\n\nconst sideTotal = (groups: readonly SeatGroup[], id: string) =>\n  groups.filter((g) => g.side === id).reduce((sum, g) => sum + Math.max(0, Math.floor(g.seats)), 0);\n\n/** What the screen-reader sentence is built from, so it can be written in any language. */\nexport interface SeatSummary {\n  /** Seats in the assembly. */\n  total: number;\n  /** Seats no group holds. */\n  vacant: number;\n  /** Seats needed for a majority, when given. */\n  majority?: number;\n  /** True when the groups are grouped into sides. */\n  sided: boolean;\n  /** The sides with their groups, or each group on its own when there are no sides. */\n  blocs: readonly { label: string; seats: number; members: readonly SeatGroup[] }[];\n  /** Groups that belong to no listed side. */\n  loose: readonly SeatGroup[];\n  /** The largest bloc and how many seats it is short of a majority (0 or less when it holds one). */\n  largest?: { label: string; seats: number; short: number };\n  /** Formats a count in the chart's locale. */\n  number: (n: number) => string;\n}\n\n/** Every fixed word in SeatChart. Pass only the ones to change. */\nexport interface SeatChartLabels {\n  /** Shown when there are no seats. */\n  empty: string;\n  /** The row and legend entry for seats no group holds. */\n  vacant: string;\n  /** The legend heading for groups outside every side. */\n  noSide: string;\n  /** Table column headers and the footer row. */\n  group: string;\n  side: string;\n  seats: string;\n  share: string;\n  total: string;\n  /** The caption under the arc when there is a majority. Gets the formatted count. */\n  majorityNeeded: (majority: string) => string;\n  /** The table footer's majority cell. Gets the formatted count. */\n  majorityCell: (majority: string) => string;\n  /** The table caption, given the chart's label when it is a string. */\n  tableCaption: (label?: string) => string;\n  /** The sentence a screen reader hears for the picture. */\n  summary: (summary: SeatSummary) => string;\n}\n\nconst LABELS: SeatChartLabels = {\n  empty: 'No seats to show yet.',\n  vacant: 'Vacant',\n  noSide: 'No side',\n  group: 'Group',\n  side: 'Side',\n  seats: 'Seats',\n  share: 'Share',\n  total: 'Total',\n  majorityNeeded: (m) => `${m} needed for a majority`,\n  majorityCell: (m) => `Majority ${m}`,\n  tableCaption: (label) => (label ? `${label}: seats by group` : 'Seats by group'),\n  summary: (s) => {\n    const n = s.number;\n    const count = (k: number) => plural(k, 'seat', 'seats', n);\n    const list = (gs: readonly { label: string; seats: number }[]) => gs.map((g) => `${g.label} ${n(g.seats)}`).join(', ');\n    const parts = [`${count(s.total)}.`];\n    if (s.sided) {\n      for (const b of s.blocs) parts.push(b.members.length > 0 ? `${b.label} ${n(b.seats)}: ${list(b.members)}.` : `${b.label} 0.`);\n      if (s.loose.length > 0) parts.push(`No side: ${list(s.loose)}.`);\n    } else if (s.blocs.length > 0) {\n      parts.push(`${list(s.blocs)}.`);\n    }\n    if (s.vacant > 0) parts.push(`${count(s.vacant)} vacant.`);\n    if (s.majority !== undefined) {\n      parts.push(`A majority is ${n(s.majority)}.`);\n      if (s.largest) {\n        parts.push(\n          s.largest.short <= 0\n            ? `${s.largest.label} holds a majority${s.sided ? '' : ' on its own'}.`\n            : `The largest ${s.sided ? 'side' : 'group'}, ${s.largest.label}, is ${count(s.largest.short)} short.`,\n        );\n      }\n    }\n    return parts.join(' ');\n  },\n};\n\n/** The sentence a screen reader hears for the picture. */\nexport function describeSeats(\n  groups: readonly SeatGroup[],\n  total: number,\n  majority?: number,\n  sides: readonly SeatSide[] = [],\n  { summary = LABELS.summary, locale }: { summary?: SeatChartLabels['summary']; locale?: string } = {},\n): string {\n  groups = groups.map((g) => ({ ...g, seats: Math.max(0, Math.floor(g.seats)) }));\n  const held = groups.reduce((sum, g) => sum + g.seats, 0);\n  const format = new Intl.NumberFormat(locale);\n  const sided = sides.length > 0;\n  const blocs = sided\n    ? sides.map((side) => ({\n        label: side.label,\n        seats: sideTotal(groups, side.id),\n        members: groups.filter((g) => g.side === side.id),\n      }))\n    : groups.map((g) => ({ label: g.label, seats: g.seats, members: [g] }));\n  const best = blocs.reduce<(typeof blocs)[number] | undefined>(\n    (top, b) => (!top || b.seats > top.seats ? b : top),\n    undefined,\n  );\n  return summary({\n    total,\n    vacant: Math.max(0, total - held),\n    majority,\n    sided,\n    blocs,\n    loose: sided ? groups.filter((g) => !sides.some((side) => side.id === g.side)) : [],\n    largest: best && majority !== undefined ? { label: best.label, seats: best.seats, short: majority - best.seats } : undefined,\n    number: (k) => format.format(k),\n  });\n}\n\n// ─────────────────────────────────────────────────────────────────\n// SeatChart\n// ─────────────────────────────────────────────────────────────────\n\n/** Drawing box. The viewBox scales it to any width. */\nconst W = 400;\nconst SCALE = 188;\nconst TOP = 14;\nconst CX = W / 2;\nconst CY = TOP + SCALE;\n\nconst SPREAD_MS = 520;\nconst SEAT_MS = 280;\nconst EASE_ENTER = 'cubic-bezier(0.2, 0, 0, 1)';\n\nconst fillOf = (group: PlacedGroup) => {\n  const shades = SHADES[group.tone];\n  return shades[group.shade % shades.length]!;\n};\n\nfunction Swatch({ className, vacant }: { className?: string; vacant?: boolean }) {\n  return (\n    <svg aria-hidden viewBox=\"0 0 10 10\" className=\"size-2.5 shrink-0 self-center\">\n      {vacant ? (\n        <circle cx={5} cy={5} r={4.25} strokeWidth={1.5} className=\"fill-none stroke-muted-foreground\" />\n      ) : (\n        <circle cx={5} cy={5} r={5} className={className} />\n      )}\n    </svg>\n  );\n}\n\nexport interface SeatChartProps extends Omit<React.ComponentProps<'figure'>, 'children'> {\n  /** The groups. Without sides, their wedges run left to right in this order. */\n  groups: readonly SeatGroup[];\n  /** Sides the groups belong to, such as government and opposition. The first fills from the left, the last from the right. */\n  sides?: readonly SeatSide[];\n  /** Seats in the assembly. @default the sum of the groups; any seats beyond it are vacant */\n  total?: number;\n  /** Seats needed for a majority, marked at the top centre of the arc. Leave out for no mark. */\n  majority?: number;\n  /** The caption under the arc. @default '{majority} needed for a majority' */\n  majorityLabel?: React.ReactNode;\n  /** Big totals above the arc: one per side, the two largest groups, or none. @default 'sides' with sides, else 'none' */\n  tally?: SeatTally;\n  /** The chart's title, such as the election or the year. */\n  label?: React.ReactNode;\n  /**\n   * The noun after a count, on screen. The spoken sentence has its own words: set\n   * `labels.summary` for those. @default 'seats'\n   */\n  seatsLabel?: string;\n  /** The same noun for a count of one. @default 'seat' when `seatsLabel` is 'seats', else `seatsLabel` */\n  seatLabel?: string;\n  /** The locale for numbers. @default the reader's */\n  locale?: string;\n  /** Replace any fixed word: headers, captions, the empty note, the spoken summary. */\n  labels?: Partial<SeatChartLabels>;\n  /** Show the table of groups and seats, which otherwise is for screen readers only. */\n  showTable?: boolean;\n  /** Reserve the chart's box while the data loads. */\n  loading?: boolean;\n}\n\nexport const SeatChart = React.forwardRef<HTMLElement, SeatChartProps>(function SeatChart(\n  {\n    groups,\n    sides = [],\n    total: totalProp,\n    majority,\n    majorityLabel,\n    tally,\n    label,\n    seatsLabel = 'seats',\n    seatLabel = seatsLabel === 'seats' ? 'seat' : seatsLabel,\n    locale,\n    labels: labelsProp,\n    showTable = false,\n    loading = false,\n    className,\n    ...props\n  },\n  ref,\n) {\n  const reduced = useReducedMotion();\n  const labels = { ...LABELS, ...labelsProp };\n  const numberFormat = new Intl.NumberFormat(locale);\n  const number = (n: number) => numberFormat.format(n);\n  const labelId = React.useId();\n  const plotRef = React.useRef<SVGSVGElement>(null);\n  const [hovered, setHovered] = React.useState<number | null>(null);\n  const [pinned, setPinned] = React.useState<number | null>(null);\n\n  const placed = React.useMemo(() => placeGroups(groups, sides), [groups, sides]);\n  const held = placed.reduce((sum, g) => sum + g.seats, 0);\n  const total = Math.max(held, Math.floor(totalProp ?? held));\n  const layout = React.useMemo(() => seatLayout(total), [total]);\n\n  // Which group holds each seat, in left-to-right order. -1 is vacant: it\n  // sits between the left-hand groups and a right-hand side, if any.\n  const owner: number[] = [];\n  const rightStart = sides.length > 1 ? placed.findIndex((g) => g.sideIndex === sides.length - 1) : -1;\n  const split = rightStart === -1 ? placed.length : rightStart;\n  const take = (g: PlacedGroup) => {\n    for (let k = 0; k < g.seats; k++) owner.push(g.index);\n  };\n  placed.slice(0, split).forEach(take);\n  for (let k = held; k < total; k++) owner.push(-1);\n  placed.slice(split).forEach(take);\n\n  // The first view fills the seats in, once, left to right.\n  React.useLayoutEffect(() => {\n    const svg = plotRef.current;\n    if (!svg || reduced || typeof IntersectionObserver === 'undefined') return;\n    const seats = Array.from(svg.querySelectorAll<SVGElement>('[data-slot=\"seat-chart-seat\"]'));\n    if (typeof seats[0]!.animate !== 'function') return;\n    for (const seat of seats) seat.style.opacity = '0';\n    const io = new IntersectionObserver(\n      (entries) => {\n        if (!entries.some((e) => e.isIntersecting)) return;\n        io.disconnect();\n        const last = Math.max(1, seats.length - 1);\n        seats.forEach((seat, i) => {\n          seat.style.opacity = '';\n          seat.animate(\n            [\n              { opacity: 0, transform: 'scale(0.4)' },\n              { opacity: 1, transform: 'none' },\n            ],\n            { duration: SEAT_MS, delay: (i / last) * SPREAD_MS, easing: EASE_ENTER, fill: 'backwards' },\n          );\n        });\n      },\n      { threshold: 0.25 },\n    );\n    io.observe(svg);\n    return () => {\n      io.disconnect();\n      for (const seat of seats) {\n        seat.style.opacity = '';\n        for (const animation of seat.getAnimations()) animation.cancel();\n      }\n    };\n  }, [reduced, total, groups.length]);\n\n  if (loading) {\n    return (\n      <figure\n        ref={ref}\n        data-slot=\"seat-chart\"\n        data-state=\"loading\"\n        data-min-viewport={String(MIN_VIEWPORT)}\n        aria-busy=\"true\"\n        className={cn('m-0 w-full', className)}\n        {...props}\n      >\n        <Skeleton variant=\"chart\" />\n      </figure>\n    );\n  }\n\n  if (total === 0) {\n    return (\n      <figure\n        ref={ref}\n        data-slot=\"seat-chart\"\n        data-state=\"empty\"\n        data-min-viewport={String(MIN_VIEWPORT)}\n        className={cn('m-0 w-full rounded-xl border border-border p-6', className)}\n        {...props}\n      >\n        <p className=\"text-sm text-muted-foreground\">{labels.empty}</p>\n      </figure>\n    );\n  }\n\n  const byIndex = new Map(placed.map((g) => [g.index, g]));\n  const active = hovered ?? pinned;\n  const activeGroup = active === null ? undefined : byIndex.get(active);\n  const seatRadius = layout.pitch * SCALE * 0.42;\n  // The bottom row sits on the centre line; the box ends just past its seats.\n  const H = Math.ceil(CY + seatRadius + 2);\n  const innerEdge = CY - (0.4 * SCALE - seatRadius - 4);\n  const summary = describeSeats(groups, total, majority, sides, { summary: labels.summary, locale });\n  const percent = new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 });\n  const pct = (n: number) => percent.format(n / total);\n  const vacant = total - held;\n  const seatsWord = (n: number) => plural(n, seatLabel, seatsLabel, number);\n\n  const tallyMode: SeatTally = tally ?? (sides.length > 0 ? 'sides' : 'none');\n  const tallies: { key: string; label: string; seats: number; fill: string }[] =\n    tallyMode === 'sides'\n      ? sides.map((side) => ({\n          key: side.id,\n          label: side.label,\n          seats: sideTotal(groups, side.id),\n          fill: SHADES[side.tone][0]!,\n        }))\n      : tallyMode === 'leaders'\n        ? [...placed]\n            .sort((a, b) => b.seats - a.seats)\n            .slice(0, 2)\n            .sort((a, b) => placed.indexOf(a) - placed.indexOf(b))\n            .map((g) => ({ key: `g${g.index}`, label: g.label, seats: g.seats, fill: fillOf(g) }))\n        : [];\n\n  const point = (event: React.PointerEvent<SVGSVGElement>) => {\n    const group = (event.target as Element).getAttribute('data-group');\n    setHovered(group === null || group === '-1' ? null : Number(group));\n  };\n\n  const legendEntry = (g: PlacedGroup) => (\n    <li key={g.index}>\n      <button\n        type=\"button\"\n        aria-pressed={pinned === g.index}\n        data-slot=\"seat-chart-legend-item\"\n        data-active={active === g.index ? '' : undefined}\n        onPointerEnter={() => setHovered(g.index)}\n        onPointerLeave={() => setHovered(null)}\n        onFocus={() => setHovered(g.index)}\n        onBlur={() => setHovered(null)}\n        onClick={() => setPinned((current) => (current === g.index ? null : g.index))}\n        className={cn(\n          '-mx-1.5 flex min-h-target w-[calc(100%+0.75rem)] min-w-0 items-baseline gap-2 rounded-md px-1.5 py-0.5 text-start',\n          'hover:bg-muted data-[active]:bg-muted aria-pressed:bg-muted',\n          'focus-visible:ring-ring focus-visible:ring-offset-background focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:outline-hidden',\n        )}\n      >\n        <Swatch className={fillOf(g)} />\n        <span className=\"text-foreground min-w-0 flex-1 break-words\">{g.label}</span>\n        <span className=\"text-foreground shrink-0 font-medium tabular-nums\">\n          {number(g.seats)}\n          <span className=\"sr-only\"> {g.seats === 1 ? seatLabel : seatsLabel}</span>\n        </span>\n      </button>\n    </li>\n  );\n\n  const vacantEntry =\n    vacant > 0 ? (\n      <li className=\"flex min-h-target min-w-0 items-baseline gap-2 py-0.5\">\n        <Swatch vacant />\n        <span className=\"text-muted-foreground min-w-0 flex-1\">{labels.vacant}</span>\n        <span className=\"text-foreground shrink-0 font-medium tabular-nums\">{number(vacant)}</span>\n      </li>\n    ) : null;\n\n  const LIST = 'm-0 grid list-none grid-cols-[repeat(auto-fill,minmax(min(100%,11rem),14rem))] gap-x-8 p-0 text-ui-sm';\n\n  // The legend by side, in the order of `sides`, each in its given order.\n  const bySide =\n    sides.length > 0\n      ? [\n          ...sides.map((side, s) => ({\n            key: side.id,\n            label: side.label as string | undefined,\n            seats: sideTotal(groups, side.id),\n            members: placed.filter((g) => g.sideIndex === s).sort((a, b) => a.index - b.index),\n          })),\n          {\n            key: '__none',\n            label: undefined,\n            seats: 0,\n            members: placed.filter((g) => g.sideIndex === -1),\n          },\n        ].filter((block) => block.members.length > 0)\n      : [];\n\n  return (\n    <figure\n      ref={ref}\n      data-slot=\"seat-chart\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      data-total={String(total)}\n      aria-labelledby={label ? labelId : undefined}\n      className={cn('@container/seats m-0 flex w-full min-w-0 flex-col gap-3', className)}\n      {...props}\n    >\n      {label ? (\n        <figcaption id={labelId} data-slot=\"seat-chart-label\" className=\"text-foreground text-ui-sm font-medium\">\n          {label}\n        </figcaption>\n      ) : null}\n\n      {tallies.length > 0 ? (\n        <div\n          data-slot=\"seat-chart-tally\"\n          className=\"mx-auto flex w-full max-w-144 flex-wrap items-end justify-between gap-x-4 gap-y-2\"\n        >\n          {tallies.map((t, i) => (\n            <React.Fragment key={t.key}>\n              {i > 0 ? <span aria-hidden className=\"bg-border w-px self-stretch\" /> : null}\n              <div\n                className={cn(\n                  'flex min-w-0 flex-1 flex-col',\n                  i === 0 ? 'items-start text-start' : i === tallies.length - 1 ? 'items-end text-end' : 'items-center text-center',\n                )}\n              >\n                <span className=\"text-muted-foreground flex items-center gap-1.5 text-caption\">\n                  <Swatch className={t.fill} />\n                  {t.label}\n                </span>\n                <span className=\"text-foreground leading-none font-semibold tabular-nums text-[min(2.5rem,12cqi)]\">\n                  {number(t.seats)}\n                </span>\n              </div>\n            </React.Fragment>\n          ))}\n        </div>\n      ) : null}\n\n      <div data-slot=\"seat-chart-plot\" className=\"relative mx-auto w-full max-w-144\">\n        <svg\n          ref={plotRef}\n          viewBox={`0 0 ${W} ${H}`}\n          className=\"block h-auto w-full\"\n          role=\"img\"\n          aria-label={summary}\n          onPointerMove={point}\n          onPointerLeave={() => setHovered(null)}\n        >\n          {layout.seats.map((seat, i) => {\n            const index = owner[i]!;\n            const group = byIndex.get(index);\n            const x = CX + seat.r * SCALE * Math.cos(seat.angle);\n            const y = CY - seat.r * SCALE * Math.sin(seat.angle);\n            return (\n              <circle\n                key={i}\n                data-slot=\"seat-chart-seat\"\n                data-group={index}\n                cx={Number(x.toFixed(2))}\n                cy={Number(y.toFixed(2))}\n                r={Number(seatRadius.toFixed(2))}\n                strokeWidth={group ? undefined : 1.25}\n                className={cn(\n                  'origin-center [transform-box:fill-box] motion-safe:transition-opacity motion-safe:duration-(--duration-fast)',\n                  group ? fillOf(group) : 'fill-none stroke-muted-foreground',\n                  active !== null && index !== active && 'opacity-20',\n                )}\n              />\n            );\n          })}\n          {majority !== undefined ? (\n            <line\n              data-slot=\"seat-chart-majority\"\n              x1={CX}\n              x2={CX}\n              y1={1}\n              y2={Number(innerEdge.toFixed(2))}\n              strokeWidth={1.5}\n              strokeLinecap=\"round\"\n              className=\"stroke-foreground\"\n            />\n          ) : null}\n        </svg>\n        <p\n          data-slot=\"seat-chart-total\"\n          aria-hidden\n          className=\"text-foreground pointer-events-none absolute inset-x-0 bottom-0 m-0 text-center leading-none font-semibold tabular-nums text-[min(2.25rem,11cqi)]\"\n        >\n          {number(activeGroup ? activeGroup.seats : total)}\n        </p>\n      </div>\n\n      <p\n        data-slot=\"seat-chart-readout\"\n        className=\"text-muted-foreground m-0 text-center text-caption tabular-nums\"\n      >\n        {activeGroup ? (\n          <>\n            {activeGroup.label}: {seatsWord(activeGroup.seats)}, {pct(activeGroup.seats)}\n          </>\n        ) : majority !== undefined ? (\n          (majorityLabel ?? labels.majorityNeeded(number(majority)))\n        ) : (\n          seatsWord(total)\n        )}\n      </p>\n\n      {placed.length > 0 ? (\n        <div data-slot=\"seat-chart-legend\" className=\"flex flex-col gap-3\">\n          {sides.length > 0 ? (\n            bySide.map((block, b) => (\n              <div key={block.key} className=\"flex flex-col gap-1\">\n                <p className=\"text-muted-foreground m-0 text-caption\">\n                  {block.label ? (\n                    <>\n                      {block.label} <span className=\"text-foreground font-medium tabular-nums\">{number(block.seats)}</span>\n                    </>\n                  ) : (\n                    labels.noSide\n                  )}\n                </p>\n                <ul className={LIST}>\n                  {block.members.map(legendEntry)}\n                  {b === bySide.length - 1 ? vacantEntry : null}\n                </ul>\n              </div>\n            ))\n          ) : (\n            <ul className={LIST}>\n              {[...placed].sort((a, b) => a.index - b.index).map(legendEntry)}\n              {vacantEntry}\n            </ul>\n          )}\n        </div>\n      ) : null}\n\n      <div data-slot=\"seat-chart-table\" className={cn(showTable ? 'overflow-x-auto' : 'sr-only')}>\n        <table className=\"w-full text-ui-sm tabular-nums\">\n          <caption className=\"text-muted-foreground pb-2 text-start text-caption\">\n            {labels.tableCaption(typeof label === 'string' ? label : undefined)}\n          </caption>\n          <thead>\n            <tr className=\"border-border border-b\">\n              <th scope=\"col\" className=\"py-1.5 pe-4 text-start font-medium\">\n                {labels.group}\n              </th>\n              {sides.length > 0 ? (\n                <th scope=\"col\" className=\"py-1.5 pe-4 text-start font-medium\">\n                  {labels.side}\n                </th>\n              ) : null}\n              <th scope=\"col\" className=\"py-1.5 pe-4 text-end font-medium\">\n                {labels.seats}\n              </th>\n              <th scope=\"col\" className=\"py-1.5 text-end font-medium\">\n                {labels.share}\n              </th>\n            </tr>\n          </thead>\n          <tbody>\n            {groups.map((group, index) => (\n              <tr key={`${group.label}-${index}`} className=\"border-border border-b\">\n                <th scope=\"row\" className=\"py-1.5 pe-4 text-start font-normal\">\n                  {group.label}\n                </th>\n                {sides.length > 0 ? (\n                  <td className=\"py-1.5 pe-4\">{sides.find((side) => side.id === group.side)?.label ?? '—'}</td>\n                ) : null}\n                <td className=\"py-1.5 pe-4 text-end\">{number(byIndex.get(index)!.seats)}</td>\n                <td className=\"py-1.5 text-end\">{pct(byIndex.get(index)!.seats)}</td>\n              </tr>\n            ))}\n            {vacant > 0 ? (\n              <tr className=\"border-border border-b\">\n                <th scope=\"row\" className=\"py-1.5 pe-4 text-start font-normal\">\n                  {labels.vacant}\n                </th>\n                {sides.length > 0 ? <td className=\"py-1.5 pe-4\">—</td> : null}\n                <td className=\"py-1.5 pe-4 text-end\">{number(vacant)}</td>\n                <td className=\"py-1.5 text-end\">{pct(vacant)}</td>\n              </tr>\n            ) : null}\n          </tbody>\n          <tfoot>\n            <tr>\n              <th scope=\"row\" className=\"py-1.5 pe-4 text-start font-medium\">\n                {labels.total}\n              </th>\n              {sides.length > 0 ? <td /> : null}\n              <td className=\"py-1.5 pe-4 text-end font-medium\">{number(total)}</td>\n              <td className=\"py-1.5 text-end\">{majority !== undefined ? labels.majorityCell(number(majority)) : ''}</td>\n            </tr>\n          </tfoot>\n        </table>\n      </div>\n    </figure>\n  );\n});\nSeatChart.displayName = 'SeatChart';\n\n// ─────────────────────────────────────────────────────────────────\n// SeatChartCompare\n// ─────────────────────────────────────────────────────────────────\n\nconst COLUMNS = {\n  2: '@2xl/compare:grid-cols-2',\n  3: '@4xl/compare:grid-cols-3',\n} as const;\n\nexport interface SeatChartCompareProps extends React.ComponentProps<'div'> {\n  /** How many charts sit side by side when there is room. @default 2 */\n  columns?: keyof typeof COLUMNS;\n}\n\n/**\n * Two or three seat charts side by side (two elections, say), stacked when\n * the box is too narrow for them. The switch is a container query on this\n * box, not the window.\n */\nexport function SeatChartCompare({ columns = 2, className, children, ...props }: SeatChartCompareProps) {\n  return (\n    <div data-slot=\"seat-chart-compare\" className={cn('@container/compare', className)} {...props}>\n      <div data-slot=\"seat-chart-compare-grid\" className={cn('grid grid-cols-1 gap-x-10 gap-y-12', COLUMNS[columns])}>\n        {children}\n      </div>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "tier": "chart",
    "client": true,
    "minViewport": 320,
    "loading": true,
    "version": "1.2.1",
    "since": "2.0.0"
  },
  "docs": "## @interlace/seat-chart\n\nInstalled to `components/ui/charts/seat-chart.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/charts/seat-chart';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/seat-chart\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
