Skip to content
SprecherEast
Issue 592

feat: Charts for posts, events and pages: one Chart component behind our own interface, drawn by visx on the server, with a data table

Back to our plan
Open
enhancementfrontendcmsvisualizationpriority: highshared-component

Problem

In plain words: some facts are clearer as a picture. How a tax bill splits, how a project's money came from borrowing and fees, how a rate changed over five years. Editors, and agents after #593, need a chart they can drop into a post, an event or a page. It must stay readable on a phone, in dark mode and with a screen reader. It should come from an established open-source chart library, not charts we draw from scratch. The site's code must never depend on that library directly, so it can be swapped later.

Summary of the owner's request (2026-11-02, Claude conversation, text): he wants graphs and diagrams that look good, and for us to produce intuitive visuals such as infographics and diagrams.

The owner (Amine, 2026-11-03, Claude Code session, text) asked for an established free, open-source charting library instead of hand-written charts, used behind an interface (ports and adapters) so the site isn't locked in, and built as one common component used across the app: posts, events, pages and future explainers.

Today (checked 2026-11-03):

  • No chart. package.json has no chart library, and no rich-text block draws a chart.
  • Versions. package-lock.json pins Next 16.4.2, React 19.2.8, Payload 3.91.0, Tailwind 4.2.1 and eslint-plugin-boundaries 7.2.0.
  • Where blocks live. The visual blocks are in src/platform/richtext/editorial/ and are registered in EDITORIAL_BLOCKS (blockConfigs.ts) and richTextBlocks.tsx. Each one is a Payload config, a mapper to plain props (decision 0013) and a server component.
  • Rules that apply.
    • No inline style={} and no hex colours (nextjs-tailwind.md, eslint.theme.config.mjs).
    • No inline SVG in feature code (guard rail 2). The kit (src/platform/ui/) is exempt from the raw-tag lint.
    • No direct dangerouslySetInnerHTML (security.md).
    • platform/ imports no module (eslint.boundaries.config.mjs, rule 3).
  • Chart tokens exist but fail contrast. chart-1 to chart-5 are in tokens.ts and src/themes/default/theme.css, and themes.test.ts checks no chart pair. Calculated from the theme values:
    • Light chart-2 (#e8923a) is 2.30:1 on the background.
    • Light chart-3 and chart-4 are 2.92:1 and 2.89:1 on the surface.
    • Dark chart-5 is 3.15:1 on the surface.
    • Neighbouring series are 1.3–1.5:1 against each other.
  • shadcn. components.json (shadcn config) exists, and the tokens use shadcn names, but no shadcn component is installed.
  • Payload Markdown. Payload 3.91.0's propsToJSXString writes arrays and objects as prop={[...]}, so chart data fits in tag props (read in the package source).
  • Library check. Full table: chart_library_evaluation.md. It was tested locally with react-server-dom-webpack (the renderer behind server components) and react-dom/server:
    • Recharts 3.10.1 (and the shadcn chart built on it) fails as a server component (createContext). Through react-dom/server it outputs an empty <div> with no SVG, even at a fixed size. It adds 99 KB gzip (bars only) to 128 KB (all forms) of client JavaScript.
    • visx 4.0.0 (MIT, published 2026-06-11, React 18/19 peer) renders as a server component: @visx/shape, group, scale, axis, text, pattern, sankey and hierarchy. 0 KB of client JavaScript.

Proposed fix

One shared chart component with our own interface, and visx behind it.

Architecture (ports and adapters):

PieceWhereImports
ChartSpec types, the zod schema, toChartTable(spec), toChartSummary(spec), toWaffleCells(rows) (largest remainder to exactly 100), value formattingsrc/platform/lib/chart/nothing from React or visx. A module's domain/ may build a ChartSpec (it may use platform/lib/)
ChartAdapter interface, the adapter registry (one line picks the default), chartPalette.ts (series index → fill-chart-N and stroke-chart-N classes)src/platform/ui/chart/platform/lib/chart
Chart (the only component the app uses): <figure> + title, the adapter's SVG, ChartDataTable, source and certainty linesrc/platform/ui/chart/Chart.tsx, exported from @/platform/uithe registry, never a library
The visx adapter: one composed component per formsrc/platform/ui/chart/adapters/visx/the only folder allowed to import @visx/*
The text adapter: renders the summary and the table only. It is the fallback for an unsupported form, and the second adapter the contract runs againstsrc/platform/ui/chart/adapters/text/nothing
The contract suite describeChartAdapter(adapter)src/platform/ui/chart/chartAdapter.contract.tsxruns in every adapter's test
The Chart block: config, mapper toChartSpec(stored), jsx convertersrc/platform/richtext/editorial/@/platform/ui Chart
// src/platform/lib/chart/spec.ts: plain data, no framework
export type ChartUnit = 'usd' | 'percent' | 'mills' | 'count'
export type ChartDatum = { label: string; value: number; note?: string }
export type ChartSeries = { key: string; label: string; values: (number | null)[] }
type ChartBase = {
  title: string
  summary: string // the <desc> and the line under the title: the takeaway in words
  unit: ChartUnit
  asOf?: string // "December 2024 bill"
  certainty?: Certainty // reused from Key facts: `import type` from editorial/certainty.ts, or move it to platform/lib/
  sources?: { label: string; href: string }[]
}
export type ChartSpec = ChartBase &
  (
    | { kind: 'bar'; orientation: 'horizontal' | 'vertical'; data: ChartDatum[] } // ≤ 12 bars
    | { kind: 'share'; display: 'stackedBar' | 'waffle' | 'both'; data: ChartDatum[] } // of $100, ≤ 6 parts
    | { kind: 'series'; mark: 'column' | 'line'; x: string[]; series: ChartSeries[] } // years, ≤ 12 × 5
    | { kind: 'stacked'; x: string[]; series: ChartSeries[] } // cost by year by funding source
    | { kind: 'parts'; display: 'donut' | 'treemap'; data: (ChartDatum & { group?: string })[] } // budget split
    | { kind: 'flow'; nodes: { id: string; label: string }[]; links: { source: string; target: string; value: number }[] } // Sankey
  )
export type ChartKind = ChartSpec['kind']

// src/platform/ui/chart/chartAdapter.ts: the port
export type ChartRenderContext = { titleId: string; descId: string; palette: readonly SeriesClasses[] }
export interface ChartAdapter {
  readonly name: string
  readonly kinds: ReadonlySet<ChartKind>
  /** A server component tree. No hooks, no 'use client', no style attribute, no colour literal. */
  render(spec: ValidChartSpec, ctx: ChartRenderContext): React.ReactNode
}

How it draws:

  • Server components only. The SVG is in the HTML. No chart JavaScript reaches a post page. #595's interactive estimate wraps the same adapter in a client leaf, so visx is about 24 KB gzip on that page only.
  • Phone first without measuring.
    • Each form draws a compact layout (viewBox 320 wide) and a wide one (640), and sm: classes show one.
    • The hidden one is display: none, so it is out of the accessibility tree.
    • Labels sit in their own rows, never squeezed beside bars. No @visx/text wrapping, since the server can't measure text.
  • Token colours only.
    • Marks take fill-chart-N classes from chartPalette.ts.
    • Segments are separated by a 2 px stroke-background gap.
    • Every mark has its value as text, and every series is named in a text legend, with @visx/pattern lines as a second cue beyond 3 series. Colour never carries meaning alone.
  • Accessible.
    • <svg role="img" aria-labelledby="{titleId} {descId}"> with <title> and <desc> from toChartSummary.
    • A real <table> built from the same spec by toChartTable (caption, scope headers, unit in the header). It is open by default under sm, and in a Disclosure from sm.
  • The waffle. It is 100 rects laid out by @visx/scale scaleBand. Rounding to whole cells is toWaffleCells (largest remainder), unit tested, so the cells always add up to 100.

Keeping the library inside the adapter: a policy in eslint.boundaries.config.mjs follows the existing PAYLOAD pattern (rule 6):

const CHART_LIBRARIES = [{ to: { module: { source: ['@visx/*', 'd3-*', 'recharts', 'echarts', '@nivo/*'] } } }]
// …in policies:
{
  from: [{ element: { type: ['app', 'module'] } }, { element: { type: 'platform', fileInternalPath: '!ui/chart/adapters/**' } }],
  disallow: CHART_LIBRARIES,
  message: 'Chart libraries only inside src/platform/ui/chart/adapters/: use Chart from @/platform/ui (#592)',
}

The contract test (proves no lock-in). describeChartAdapter(adapter) runs these checks for one fixture of every kind the adapter supports:

  • The output renders through react-dom/server, and the markup contains the SVG and one mark per datum. This catches a library that only draws in the browser.
  • It has no style= attribute and no #hex, rgb( or hsl( values.
  • Fills only use classes from the palette.
  • Every label and formatted value appears as text.
  • aria-labelledby points at the title and the description.
  • axe passes (expectAccessible).

It runs against the visx adapter and the text adapter. A future adapter (for example shadcn/Recharts for a hover-heavy chart) must pass the same suite before the registry may use it. Swapping libraries means one new adapter folder and one line in the registry. Posts, blocks, taxYears and the Markdown stay as they are.

The Payload Chart block (chartBlockConfig.ts):

  • Fields:
    • title, summary, kind, a display or orientation that depends on the kind, unit, as of
    • certainty (reused)
    • sources (linkFields)
    • rows: an array of label, series key (optional), value and note
    • links: an array of from, to and value, shown only for flow
  • toChartSpec(stored) maps the rows to the kind's shape, as Timeline and Key facts do (decision 0013). The schema refuses a share that doesn't add up to 100 ± 0.5, a negative value, or a flow link to an unknown node, with a field error.
  • Registered in EDITORIAL_BLOCKS and richTextBlocks.
  • Data from taxYears (#594) doesn't go through the block. The civic module's domain builds a ChartSpec from the stored year and renders Chart, so platform/ never imports a module.

Markdown (agents). The block's jsx converter, after #593, uses Payload's native props: <Chart kind="share" title="Of every $100 on the bill" unit="usd" asOf="December 2024 bill" summary="Schools take the largest share." data={[{"label":"MMSD","value":47.3}]} />. Import goes through the same zod schema, so a malformed chart is refused with the field error, and submitSuggestion returns it to the agent.

Watch out: this adds a shared component to src/platform/ui/ and a block to src/platform/richtext/, which every post and event uses. Label shared-component. Check that the existing blocks still render.

Split. Four sub-issues, stacked in order: (1) port, visx adapter, contract and lint; (2) Chart block and Markdown converter; (3) money flow (Sankey); (4) stacked cost by year by funding source. Drafts are in chart_subissues.md. This issue closes with the last one.

Native first, one line per step:

  1. Native: Payload BlocksFeature and the block jsx converter (both in 3.91.0), React server components, SVG. Neither Payload nor Next has a chart.
  2. Official plugins: none for charts in @payloadcms/*.
  3. Open source (checked 2026-11-03, npm registry and local render tests):
    • visx 4.0.0 chosen. MIT, established (Airbnb, 21k stars), renders as a server component, 0 KB of client JS, colours as our token classes, and Sankey, treemap, stack, pie and axes built in.
    • Recharts 3.10.1 and the shadcn chart: runner-up, not now. They draw nothing on the server and add 99–128 KB of client JS. Their var(--chart-N) colours would work.
    • ECharts 6.1.0 and Observable Plot 0.6.18: rejected. Their server SVG comes as a string that needs dangerouslySetInnerHTML, with inline styles and hex values.
    • Nivo 0.99.0: rejected. Last published 2025-05-23, client-only as a server component, hex fills and inline styles.
    • Victory 37.4.1: rejected. Client-only, no Sankey.
    • Tremor 3.18.7: rejected. Peer React 18 only, built on Recharts 2.
    • Chart.js: rejected. It draws on canvas, not SVG.
  4. Our code: the spec, the schema and table functions, the port, two adapters (visx compositions plus the text fallback), the waffle cell function, the block and its converter, and their tests. No scales, layouts or path maths of our own.

Acceptance criteria

  • Not done: Chart from @/platform/ui is the only way the app draws a chart. Lint fails on an @visx/*, d3-*, recharts, echarts or @nivo/* import outside src/platform/ui/chart/adapters/ (a test file proves the rule fires).
  • Not done: describeChartAdapter passes for the visx adapter and the text adapter. It includes the server-markup check, so a library that only draws in the browser fails it.
  • Not done: Editors can add a Chart block to posts and events. Each kind in the spec renders: bar, share (stacked bar and 10×10 waffle), series (columns, line), stacked, parts (donut, treemap) and flow.
  • Not done: No chart JavaScript in the client bundle of a post page with a chart (checked in the next build output and in the PR).
  • Not done: Each chart has a data table with the same numbers, role="img" with a title and a description, and its values as text. axe passes (expectAccessible). Colour is never the only cue.
  • Not done: The chart tokens are fixed where they fail, and themes.test.ts checks every chart token against background, surface and card in light and dark mode (WCAG AA 3:1 for marks, 4.5:1 for text on marks).
  • Not done: At the six widths (320, 430, 768, 1024, 1280, 1920), light and dark, no chart overflows or scrolls sideways. Screenshots are in the PR.
  • Not done: The Markdown converter round-trips (Markdown → block → Markdown) in a test, and a malformed <Chart> is refused with a clear error.
  • Not done: docs/ui/component-set.md has the Chart row, /dev/gallery shows every kind, and a decision record (docs/architecture/decisions/) records visx behind the port and why.

Area

frontend, cms, visualization

Priority

high


Generated by Claude Code, opens in a new tab

See it on GitHub, opens in a new tab