Skip to content

feat(mosaic): add the headless Chart primitive with stacked bars - #10953

Draft
austincalvelage wants to merge 39 commits into
mainfrom
austin/mosaic-bar-chart
Draft

austincalvelage wants to merge 39 commits into
mainfrom
austin/mosaic-bar-chart

Conversation

@austincalvelage

@austincalvelage austincalvelage commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Description

Adds a headless Chart primitive to Mosaic at @clerk/mosaic/primitives/chart. Its first chart type is stacked bars, with values above and below zero. A single series is a plain bar chart. A line chart will add Chart.useLineChart and line marks to the same namespace in a later PR.

import { type ActiveBar, Chart } from '@clerk/mosaic/primitives/chart';

const series = [{ key: 'agents', label: 'Active agents', value: (row: Row) => row.agents }];
const chart = Chart.useBarChart({ data, series, index, onActivate });

<Chart.Root chart={chart} aria-label='Active agents by day'>
  <Chart.Grid>{ticks => ticks.map(t => <Chart.YLine key={t.value} value={t.value} />)}</Chart.Grid>
  <Chart.Bars>
    <Chart.Bar />
    <Chart.YLine value={0} />
  </Chart.Bars>
  <Chart.YAxis>{ticks => ticks.map(t => <Chart.YTick key={t.value} tick={t} />)}</Chart.YAxis>
  <Chart.XAxis>{ticks => ticks.map(t => <Chart.XTick key={t.key} tick={t} />)}</Chart.XAxis>
  <Chart.Selection>
    <Chart.Cursor />
    <Chart.Tooltip<ActiveBar<Row>>>{active => <Summary row={active.datum} />}</Chart.Tooltip>
  </Chart.Selection>
</Chart.Root>;
  • Parts.
    • Shared: Root, Grid, YLine, YAxis, YTick, XAxis, XTick, Selection, Cursor and Tooltip.
    • Bars: useBarChart, Bars, Bar, ProjectionOutline and CanvasRenderError.
  • Rendering. D3 computes scales and stacks, Canvas paints the bars, and one SVG overlay draws the grid, axes and marks.
  • Styling. The primitive ships no styles. Canvas takes its bar color, max width, gap and radii from the computed CSS of a hidden Chart.Bar element. Consumers target that element with data-series, data-inactive and data-projection.
  • Repainting. The Canvas repaints when the theme changes on any ancestor (class, style, data-theme), when prefers-color-scheme flips, and when the pixel ratio changes.
  • Selection. Selection, pointer, keyboard and announcements run in one internal engine in chart/internal/. A lint rule allows only the chart-type folders under chart/ to import it. Each chart type supplies its own hit test from a chart point, its Up/Down rules and its tooltip anchor.
    • A pointer selects the nearest column anywhere in the plot, the same area the hover band shows, and the section on its side of the zero line. Leaving the plot, tapping outside the chart or Escape closes the tooltip.
    • Options: selection, defaultSelection, onSelectionChange, onActivate(active, event) and disabled. A disabled chart ignores the pointer and keyboard, leaves the tab order and carries aria-disabled.
    • getInteractionProps(props) returns the surface props for a custom surface. Handlers passed in run after the chart's.
  • First paint. The chart measures its container when rootRef attaches, so React paints the canvas in the commit that mounts or hydrates it. A ResizeObserver commits every later size.
  • Tooltip. Chart.Tooltip is one div, portaled and positioned with Floating UI against the selected category. Its children render the content, and returning null hides it. It takes side, sideOffset, collisionPadding, collisionBoundary and pinned, and the div's own props and ref.
  • Value axis. ChartInstance has no Y scale. CartesianChartInstance adds scaleY and yTicks, and useBarChart returns one. Chart.Grid, Chart.YAxis and Chart.YLine throw with the part's name for a chart without a value axis, so a chart type such as a donut fits Chart.Root without a fake or nullable scale.
  • Screen reader text. The status region reads the period and each nonzero value in the selection, such as Nov 24, 2026, Active agents 53, plus the projection.
    • It names the section (negative values, …) only when some value in the chart is negative. The keyboard instructions leave Up and Down out otherwise.
    • Series and projections take an optional label. Every chart type takes formatValue.
    • The text comes through a messages option (ChartMessages, and BarChartMessages for the sections and the projection), with English defaults. A styled layer passes localized strings.
  • X labels. Each category label centers under its bar and moves to the plot's edge only where centered it would overflow.
  • Contract checks. chart/line-chart-contract.test-d.ts compiles a type-only line chart and a chart without a value axis against the shared contract.
  • Published. It is published with a package export, a tsdown entry and chart.doc.ts. The changeset is minor.

Ported from the Dashboard's stacked bar chart, with the same layout and keyboard model. A styled Chart built on these parts is stacked on this PR in #10960.

For review

  • Keyboard focus. The chart is one tab stop with arrow keys inside. A keyboard selection shows the same band and tooltip as a pointer, and the chart-wide ring marks focus. Ringing just the selected bar was tried and dropped: it looked heavy and needs the painted bar geometry the shared cursor does not have.
  • First paint. Before this, the first size came from the first ResizeObserver callback, at the next rendering step after hydration. In a Swingset production build, syntax highlighting ran first on 3 of 11 warm reloads and held the chart blank 186 to 212ms, against 63 to 72ms otherwise. An immediate measurement removed those (none of 11, measured with offsetWidth; this PR uses getBoundingClientRect(), which keeps fractional widths).
  • Not Mosaic's Tooltip. Mosaic's Tooltip opens from a trigger on hover and focus, and describes that trigger. The chart opens its tooltip from the selection and announces it through the status region, so it uses none of that. Building it from the Tooltip parts meant faking their context and nesting three parts to show content, so Chart.Tooltip positions one element itself.
  • Tooltip side. It starts on side, flips when that side does not fit, and keeps the side it chose last so it does not cross the selection twice near an edge.
  • Chart.Bars, not Chart.StackedBars. The marks part is named for bars in general. A later mode: 'grouped' on useBarChart can render through the same part without a breaking rename.
  • Bundle cost of one namespace. Every Chart consumer bundles the bar code and d3, about 19KB gzip, even one that uses only the shared parts.
    • The cause is that tsdown emits the namespace as one __exportAll getter object. I measured it with webpack 5, rollup and esbuild.
    • Publishing a native export * as re-export lets webpack and rollup drop the unused members, but not esbuild. That fix is deferred to the line chart PR, where the cost first applies.
  • Public hook. A hook next to the parts (Chart.useBarChart) is new for Mosaic primitives. React Aria's useListBox with ListBox is the closest precedent.
  • Dependencies. Adds d3-scale 4.0.2 and d3-shape 3.2.0. Neither is in dist/index.js.
  • getInteractionProps() returns a ref. It lets the chart end a pointer or keyboard selection when its interaction surface unmounts.
  • Change reasons. onSelectionChange passes only the selection, as Mosaic's other primitives pass only their value. Passing { reason, event } would be a Mosaic-wide change, so it is left out here.

How to test

  • pnpm --filter @clerk/mosaic test and test:browser. The browser tests cover painting, resize, pointer and touch selection, selecting the column above a short bar, the section on each side of the zero line, a first paint without any ResizeObserver callback, tooltip placement and side, a tooltip hidden by null content, and repaint after theme, color scheme and pixel ratio changes.
  • pnpm --filter @clerk/mosaic test:visual runs the 4 chart screenshots.
  • pnpm dev:swingset, then open /primitives/chart. Hover a bar, then move above a short one: the tooltip closes. Focus the chart and use the arrow keys, Home and End, and read the status region.

Verification

On 262c951b20:

  • lint, format:check, test (3,584 passed, 2 todo), test:browser (160) and build pass. The build includes typecheck, the client-boundary check and the docs-export check.
  • axe reports no violations for the chart as a group or as a button.
  • New tests that failed before their fix: selecting the column above a short bar with a mouse and with a tap, the section on each side of the zero line, centered category labels, and a first paint with a ResizeObserver that never calls back.
  • On the Swingset page:
    • Hovering the empty top of the short September column opens its tooltip, and leaving the chart closes it.
    • It is one portaled, fixed element, 16px from the category center, with pointer-events: none.
    • The status region reads Nov 24, 2026, Active agents 53 for one series, and Jan 12, 2026, negative values, Retained churned -25, Reactivated churned -11, New churned -18 after Down on the stacked example.

On an earlier commit of this PR, and not rerun since:

  • A scratch consumer installed from the packed tarball resolved types (bundler and nodenext) and runtime for @clerk/mosaic/primitives/chart.
  • Chart unit and browser tests passed on React 19.2.3 through a throwaway install.
  • react-doctor 0.9.23 reported one deliberate no-flush-sync warning: the resize observer commits the new size in the same frame, so Canvas never paints at the old size.

Not verified

  • The 4 chart screenshots have not run since the edge labels started centering. Docker was not available. The weekly chart's first and last labels now center, so expect stacked-bars-* baselines to change.
  • Touch on a real device, and a chart inside an iframe, where a tap outside the frame may not reach the chart's document.
  • A real screen reader speaking the announcements. The tests and Swingset check the status region's text.
  • Calendar X ticks (ticks='calendar') have no screenshot test.
  • No test throws CanvasRenderError end to end in this PR. The stacked styled PR covers error and retry.

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

🤖 Generated with Claude Code

…chart object

useBarChart measures the container, projects the layout and owns the
selection, keyboard handling and announcements. Root takes `chart`,
BarSelection spreads `chart.getInteractionProps()`, and `selection` /
`onSelectionChange` control the selection. useStackedBarLayout and
BarSelection's onActiveChange are removed.
…d a bar SelectionModel

The reducer, controlled reconcile, pointer coalescing, keyboard, activation and
announcements now live in useChartInstance, generic over the selection type. The
bar section rules (hit test near the zero line, Up and Down, resolving a section)
move into barSelectionModel. The pointer snaps to the nearest category center
instead of dividing by the band step.
Chart.Root, Grid, YLine, YAxis, YTick, XAxis, XTick, Selection, Cursor and
Tooltip live in primitives/chart and read only the shared ChartInstance, so a
second chart type can reuse them. BarChart keeps useBarChart, StackedBars, Bar,
ProjectionOutline and CanvasRenderError; its marks read their layout through a
module-private symbol on the instance.

- GridLine and ZeroLine become Chart.YLine value. BarSelection becomes
  Chart.Selection. Categories carry x and width instead of bandX and
  bandWidth, and chart.step is gone.
- The selection engine moves to chart/internal, fenced by lint to the
  *-chart folders.
- The tooltip anchor carries a y, and calendar ticks interpolate between
  category centers instead of assuming evenly split bands.
- A type-level line chart fixture proves the contract fits points.
primitives/chart/README.md documents the shared parts, the chart object,
selection, keyboard, tooltip and paint order. The bar-chart README keeps what
bars own: useBarChart, the marks, sections, Canvas styling and layout. The
Swingset page moves to Chart.* names and stays one raw Default story.
…ce unmounts

Unmounting Chart.Selection while a period was selected left the selection
stuck: no pointerleave or blur fires on a removed element, so
onSelectionChange never reported null and Chart.XTick kept data-active.
The interaction props now carry a ref whose detach clears a pointer or
keyboard selection. A selection set through selection or select stays.
…tio changes

Browser tests change the class on <html> and the device pixel ratio, then
read the painted Canvas: the new theme color, and a backing buffer at the
new ratio capped at 2 with the bars repainted. Chromium's device emulation
does not fire the resolution query's change event, so the test sends it.
@vercel

vercel Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
clerk-js-sandbox Ready Ready Preview Nov 26, 2026 12:53am UTC
mosaic-docs Ready Ready Preview Nov 26, 2026 12:53am UTC
swingset Ready Ready Preview Nov 26, 2026 12:53am UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 262c951

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
@clerk/mosaic Minor
@clerk/mosaic-docs Patch
@clerk/swingset Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@pkg-pr-new

pkg-pr-new Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@10953

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@10953

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@10953

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@10953

@clerk/electron

npm i https://pkg.pr.new/@clerk/electron@10953

@clerk/electron-passkeys

npm i https://pkg.pr.new/@clerk/electron-passkeys@10953

@clerk/eslint-plugin

npm i https://pkg.pr.new/@clerk/eslint-plugin@10953

@clerk/expo

npm i https://pkg.pr.new/@clerk/expo@10953

@clerk/expo-biometrics

npm i https://pkg.pr.new/@clerk/expo-biometrics@10953

@clerk/expo-google-signin

npm i https://pkg.pr.new/@clerk/expo-google-signin@10953

@clerk/expo-native-components

npm i https://pkg.pr.new/@clerk/expo-native-components@10953

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@10953

@clerk/express

npm i https://pkg.pr.new/@clerk/express@10953

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@10953

@clerk/hono

npm i https://pkg.pr.new/@clerk/hono@10953

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@10953

@clerk/mosaic

npm i https://pkg.pr.new/@clerk/mosaic@10953

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@10953

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@10953

@clerk/react

npm i https://pkg.pr.new/@clerk/react@10953

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@10953

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@10953

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@10953

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@10953

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@10953

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@10953

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@10953

commit: 262c951

… changes

The bars Canvas read colors from BarChart.Bar's computed style but only
repainted on <html> attribute changes. A light-dark() color under
`color-scheme: light dark` stayed stale when the OS color scheme flipped,
and a theme class or color-scheme set on a wrapper never repainted.

Watch class, style and data-theme on every ancestor of BarChart.Bar and
the prefers-color-scheme media query instead of <html> alone.
The bar-chart entry re-exports CanvasRenderError before any 'use client'
module, so its module must import nothing but relative modules. Its old
home in bar-chart-canvas reached d3-scale, which fails check:bundle once
the entry is published.
Add the @clerk/mosaic/primitives/chart and
@clerk/mosaic/primitives/bar-chart exports, their tsdown entries and
their agent docs, and describe the new entries in the changeset.
@austincalvelage austincalvelage changed the title feat(mosaic): add the Chart and BarChart headless primitives feat(mosaic): add the headless Chart primitive with stacked bars Nov 23, 2026
The marks part paints whatever arrangement useBarChart lays out. A
single series is a plain bar chart, and a later grouped mode would
render through the same part, so the name no longer says "stacked".
The stack layout functions keep their names, since they compute the
stacked arrangement itself.
- Take the screen reader text through a `messages` option with English
  defaults (`ChartMessages`, and `BarChartMessages` for the Up and Down
  sections), so a styled layer can pass localized strings.
- Drop `data-chart-interaction` from the inner interaction surface:
  primitives emit no slot attributes. Find the surface by its role.
- Move the tests that cover the whole chart from bars/__tests__ to
  chart/__tests__, with their screenshots, and add axe checks.
…the value axis

A pointer over the empty plot above or below the bars selected the nearest
period, so clicking or tapping off a bar left its tooltip open. The bar model
now hit-tests the point itself and selects only on a section's bars, or within
a 24px minimum target of the zero line for a short one.

Keyboard announcements read the selected period's nonzero values, such as
`Feb, Sign-ups 20`, and the projection. They name the section only when some
value in the chart is negative, and the keyboard instructions leave Up and
Down out otherwise. Series and projections take an optional `label`, and every
chart type takes `formatValue`.

The selection model now takes a chart point in `hitTest`, returns the tooltip
`anchor` as a point, and describes the resolved selection. `ChartInstance` no
longer carries `scaleY` and `yTicks`; `CartesianChartInstance` adds them, and
`Chart.Grid`, `Chart.YAxis` and `Chart.YLine` throw for a chart without them,
so a chart type with no value axis, such as a donut, fits `Chart.Root`.
…ound out the chart options

`Chart.Tooltip` now renders no element. It positions against the selected
category and provides the Tooltip primitive's context, so the chart renders
its tooltip with `Chart.TooltipPortal`, `Chart.TooltipPositioner`,
`Chart.TooltipPopup` and `Chart.TooltipArrow`, the same parts as Mosaic's
Tooltip. Its fixed offsets become `side`, `sideOffset`, `collisionPadding`,
`collisionBoundary` (was `boundaryRef`) and `pinned`.

The chart options gain `defaultSelection` and `disabled`, `onActivate`
receives the mouse or keyboard event that activated the period, and
`getInteractionProps` takes the surface's own props and runs their handlers
after the chart's.
…d overflow

The first and last category labels were always pinned to the plot's edges, so
with a few wide bars they sat away from their bars. Category labels now use
the calendar labels' rule: centered under the category, and moved to the edge
only where centered they would leave the plot.
…tegory

The chart is one tab stop with arrow keys inside, so the focus ring belongs on
the selected category rather than around the whole chart. `selectionSource`
on the chart says what made the selection, and `Chart.Cursor` carries
`data-focus-visible` while it was the keyboard.
The chart tooltip used none of Mosaic's Tooltip behavior: no trigger, no
hover or focus wiring, no description link. Composing it from the Tooltip
parts meant faking their context and nesting three parts to show content.
`Chart.Tooltip` is one positioned `div` again that renders its children's
content, takes `div` props and `ref`, and hides when the content is null.
It keeps `side`, `sideOffset`, `collisionPadding`, `collisionBoundary` and
`pinned`. `Chart.TooltipPortal`, `TooltipPositioner`, `TooltipPopup` and
`TooltipArrow` are removed.
…e column

A ring around the full column said which period the keyboard was on but not
which side of a stacked bar. The selection model now gives a `focusRect`,
the selected section from the zero line to its far edge, at least 24px tall
like the hit test and at least 12px wide so a ring stays findable on dense
data. `Chart.Cursor` covers it while the keyboard made the selection; a
mouse hover keeps the full-height column.
The hover band covers the full column, but only the bar and a 24px minimum
answered the pointer, so the empty band above a short bar showed a target
that did not respond. A pointer selects the nearest column anywhere in the
plot again, and the section on its side of the zero line, as Dashboard's
chart does. Leaving the plot, tapping outside the chart and Escape still
close the tooltip. The keyboard focus ring keeps outlining just the section.
The focus box followed the column band, so it was wider than the bars and
brought the band's fill with it. `Chart.FocusOutline` is a `rect` in the
`Chart.Bars` SVG around the selected section's painted bars, the projection
included, `offset` px outside them and at least `minSize` px each way. It
renders only for a keyboard selection. `focusRect` is removed, and
`Chart.Cursor` is the column band again.
Reverts bb31b51 (`Chart.FocusOutline`), 0e9a749 (`focusRect`) and
5245c6e (`selectionSource` and the cursor's `data-focus-visible`). A
keyboard selection shows the same band and tooltip as a pointer again, and
the chart-wide ring marks focus. The column hit test from 8a23d9e stays,
and the section measurement only the focus box used is removed.
…sizeObserver callback

The chart learned its size only from its first ResizeObserver callback, at
the next rendering step after hydration, so any effect the page ran first
held the canvas blank. In a Swingset production build, syntax highlighting
did that on 3 of 11 warm reloads, leaving the chart blank 186 to 212ms
against 63 to 72ms otherwise. Measuring the element as it attaches removed
those slow reloads (none of 11, measured with `offsetWidth`). The chart now
reads `getBoundingClientRect()` when `rootRef` attaches, which keeps
fractional widths, so React paints the canvas in the commit that mounts or
hydrates it. The ResizeObserver still commits every later size, and
corrects the first one under a scaled ancestor.

This branch was successfully deployed

2 active deployments
Preview – swingset — 262c951b Deployed Nov 26, 2026 by vercel[bot]
Preview – clerk-js-sandbox — 262c951b Deployed Nov 26, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant