diff --git a/.changeset/mosaic-chart-primitive.md b/.changeset/mosaic-chart-primitive.md new file mode 100644 index 00000000000..a5d85e9d73c --- /dev/null +++ b/.changeset/mosaic-chart-primitive.md @@ -0,0 +1,20 @@ +--- +'@clerk/mosaic': minor +--- + +Add a headless `Chart` primitive for stacked bar charts with values above and below zero. `Chart.useBarChart` lays out the bars and owns pointer and keyboard selection, `Chart.Bars` paints them on Canvas, and the shared `Chart` parts add the grid, axes, cursor and tooltip. The parts ship no styles: style `Chart.Bar` and each other part with `className` and `data-*` attributes. + +```tsx +import { Chart } from '@clerk/mosaic/primitives/chart'; + +const chart = Chart.useBarChart({ data, series, index }); + + + + + + {ticks => ticks.map(tick => )} +; +``` + +`d3-scale` and `d3-shape` are new dependencies of `@clerk/mosaic/primitives/chart`. diff --git a/packages/mosaic/oxlint.config.mjs b/packages/mosaic/oxlint.config.mjs index 2da74dc1b84..c0aeffc3085 100644 --- a/packages/mosaic/oxlint.config.mjs +++ b/packages/mosaic/oxlint.config.mjs @@ -5,6 +5,26 @@ import noUnneededEffects from 'eslint-plugin-react-you-might-not-need-an-effect' import { defineConfig } from 'oxlint'; const mosaicRoot = import.meta.dirname; +const restrictedImports = { + paths: [ + { + message: "Please always import from '@clerk/shared/' instead of '@clerk/shared'.", + name: '@clerk/shared', + }, + ], + patterns: [ + { + group: ['!@clerk/shared/*'], + message: 'ignore this line -- eslint matching workaround to allow all imports except @clerk/shared', + }, + { + group: ['@emotion/*'], + message: 'Please do not import emotion directly. Import helpers from ./design-system or ./primitives instead.', + }, + ], +}; +const chartInternalMessage = + 'The chart selection engine is for chart-type hooks. Import it only from a chart-type folder under src/primitives/chart/, such as chart/bars/.'; const SHARED = ['primitives', 'icons', 'machine', 'utils', 'hooks', 'styles', 'components', 'localization', 'root']; const FLOW_UI = { file: { categories: { anyOf: ['view', 'controller'] } } }; const CLERK_DATA_HOOKS = [ @@ -298,28 +318,7 @@ export default defineConfig({ 'custom-rules/no-unstable-methods': 'error', 'custom-rules/no-raw-inert': 'error', 'no-label-var': 'error', - 'no-restricted-imports': [ - 'error', - { - paths: [ - { - message: "Please always import from '@clerk/shared/' instead of '@clerk/shared'.", - name: '@clerk/shared', - }, - ], - patterns: [ - { - group: ['!@clerk/shared/*'], - message: 'ignore this line -- eslint matching workaround to allow all imports except @clerk/shared', - }, - { - group: ['@emotion/*'], - message: - 'Please do not import emotion directly. Import helpers from ./design-system or ./primitives instead.', - }, - ], - }, - ], + 'no-restricted-imports': ['error', restrictedImports], 'react/button-has-type': 'error', 'react/jsx-boolean-value': 'error', 'react/jsx-fragments': 'error', @@ -471,6 +470,41 @@ export default defineConfig({ 'no-unused-vars': 'off', }, }, + { + files: ['src/**/*'], + excludeFiles: ['src/primitives/chart/**', 'src/**/__tests__/**', 'src/**/*.test.{ts,tsx}', 'src/**/*.test-d.ts'], + rules: { + 'no-restricted-imports': [ + 'error', + { + ...restrictedImports, + patterns: [ + ...restrictedImports.patterns, + { + group: ['**/chart/internal', '**/chart/internal/*'], + message: chartInternalMessage, + }, + ], + }, + ], + }, + }, + { + files: ['src/primitives/chart/*'], + excludeFiles: ['src/**/*.test.{ts,tsx}', 'src/**/*.test-d.ts'], + rules: { + 'no-restricted-imports': [ + 'error', + { + ...restrictedImports, + patterns: [ + ...restrictedImports.patterns, + { group: ['./internal', './internal/*'], message: chartInternalMessage }, + ], + }, + ], + }, + }, { files: [ 'src/primitives/file-upload/file-upload-dropzone.tsx', diff --git a/packages/mosaic/package.json b/packages/mosaic/package.json index 2d5998d426c..37e8d2f8c1a 100644 --- a/packages/mosaic/package.json +++ b/packages/mosaic/package.json @@ -391,6 +391,11 @@ "import": "./dist/primitives/button.js", "default": "./dist/primitives/button.js" }, + "./primitives/chart": { + "types": "./dist/primitives/chart.d.ts", + "import": "./dist/primitives/chart.js", + "default": "./dist/primitives/chart.js" + }, "./primitives/collapsible": { "types": "./dist/primitives/collapsible.d.ts", "import": "./dist/primitives/collapsible.js", @@ -537,7 +542,9 @@ }, "dependencies": { "@clerk/shared": "workspace:^", - "@floating-ui/react": "catalog:repo" + "@floating-ui/react": "catalog:repo", + "d3-scale": "4.0.2", + "d3-shape": "3.2.0" }, "devDependencies": { "@clerk/clerk-js": "workspace:^", @@ -549,6 +556,8 @@ "@testing-library/jest-dom": "^6.9.1", "@testing-library/react": "^16.3.2", "@testing-library/user-event": "^14.6.5", + "@types/d3-scale": "4.0.9", + "@types/d3-shape": "3.1.7", "@types/react": "catalog:react", "@types/react-dom": "catalog:react", "@wallet-standard/core": "catalog:module-manager", diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md new file mode 100644 index 00000000000..0264fdc746d --- /dev/null +++ b/packages/mosaic/src/primitives/chart/README.md @@ -0,0 +1,394 @@ +# Chart + +Headless charts. A chart-type hook owns the layout and selection and returns a chart object. `Chart.Root` takes any chart object, and the parts render from it. The shared parts draw the root, grid, axes, Y lines, and pointer and keyboard selection with its cursor and tooltip. The parts emit no visual styles: style each one with `className` and `data-*` attributes. + +The one chart type today is stacked bars: `Chart.useBarChart` owns the layout and selection, and its marks paint the bars. D3 computes the diverging stacks and scales, Canvas paints the bars and the projection fill, and one SVG over the Canvas holds the projection outline and any `Chart.YLine`. + +## When to use + +- A stacked bar chart over a category or time axis, with values above and below zero. +- A chart with thousands of bars that still needs keyboard and pointer selection. +- Axes, a grid, reference lines, a cursor or a tooltip for a chart built with a chart-type hook. +- A decorative placeholder chart: leave out `Chart.Selection`. + +## Usage + +```tsx +import { type ActiveBar, Chart } from '@clerk/mosaic/primitives/chart'; + +const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }); + + + + {ticks => + ticks.map(tick => ( + + )) + } + + + + + + + + {ticks => + ticks.map(tick => ( + + )) + } + + + {ticks => + ticks.map(tick => ( + + )) + } + + + + > className='tooltip'>{active => } + +; +``` + +`series` is an ordered list of `{ key, value }`, where `value` reads a number from a row. Rows can be any type. Missing or non-finite values count as zero. `index` returns each row's category key; keys must be unique, because repeated keys share a band. Memoize `series`, `index` and `isBarActive`, or define them at module level: the component that calls `useBarChart` re-renders on every selection change, and a new `series` or `index` prepares the stacks again. + +## Parts + +| Part | Default element | Description | +| ------------------------- | --------------- | -------------------------------------------------------------------- | +| `Chart.Root` | `
` | Attaches the chart's measurement and provides the chart to the parts | +| `Chart.Grid` | `` | Holds the grid lines | +| `Chart.YLine` | `` | One line across the plot at a Y value, inside any chart SVG | +| `Chart.Bars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | +| `Chart.Bar` | `` | Hidden. Its computed style paints the bars | +| `Chart.ProjectionOutline` | `` | Hidden. Its computed stroke outlines the projected bar | +| `Chart.YAxis` | `` | Holds the Y tick labels in the left margin | +| `Chart.YTick` | `` | One Y tick label | +| `Chart.XAxis` | `` | Holds the category labels below the plot | +| `Chart.XTick` | `` | One category label | +| `Chart.Selection` | `
` | Pointer and keyboard selection over the whole chart | +| `Chart.Cursor` | `
` | Covers the selected category | +| `Chart.Tooltip` | `
` | The tooltip for the selected category, portaled | + +Every part takes `className`, `ref`, `render` and the native props of its default element. `mergeProps` runs the part's props first: `className` concatenates, `style` merges, handlers chain, and yours override everything else. + +Every part throws outside `Chart.Root`. `Chart.Bars` also throws when the chart did not come from `Chart.useBarChart`. `Chart.Bar` and `Chart.ProjectionOutline` throw outside `Chart.Bars`, and `Chart.Cursor` and `Chart.Tooltip` throw outside `Chart.Selection`. A `Chart.YLine` inside `Chart.Bars`, such as the zero line, paints over the bars. + +The namespace also holds `Chart.useBarChart` and `Chart.CanvasRenderError`. + +## Props + +### `Chart.Root` + +| Prop | Type | Default | Description | +| ------------ | ------------------ | ---------- | -------------------------------------------------- | +| `chart` | `ChartInstance` | (required) | The result of a chart-type hook | +| `aria-label` | `string` | (required) | Labels the chart image and the interaction surface | +| `height` | `number \| string` | `500` | The container height | + +### `Chart.Grid`, `Chart.YAxis`, `Chart.XAxis` + +| Part | Prop | Type | Default | Description | +| ------------- | ---------- | ---------------------------------------- | ------------- | ---------------------------------------------------------------------------------------------- | +| `Chart.Grid` | `children` | `(ticks: ChartTick[]) => ReactNode` | — | Renders the lines | +| `Chart.YAxis` | `format` | `(value: number) => ReactNode` | locale number | Formats a tick value | +| `Chart.YAxis` | `children` | `(ticks: ChartYTickItem[]) => ReactNode` | — | Renders the labels | +| `Chart.XAxis` | `ticks` | `'category' \| 'calendar'` | `'category'` | `category` thins labels to fit. `calendar` labels calendar boundaries for long UTC date ranges | +| `Chart.XAxis` | `format` | `(key: string) => string \| null` | the key | Labels a category, or returns null to omit it | +| `Chart.XAxis` | `children` | `(ticks: XTick[]) => ReactNode` | — | Renders the labels | + +Each X label centers under its category, and moves to the plot's edge only where centered it would overflow, so a few wide bars keep their labels under them and a dense axis still shows its first and last dates. `Chart.YLine` takes `value`, the Y value it marks: a grid tick's `value`, `0` for a zero line, or any reference value. `Chart.YTick` and `Chart.XTick` take the `tick` their container passed: `{ value, y, label }` for Y, `{ key, category, label, x, textAnchor }` for X. `XTick.category` is the labelled category key, or null for a calendar boundary label. Calendar labels sit between the centers of the categories dated around them. + +`Chart.Selection` and `Chart.Cursor` take only the props of their element. + +### `Chart.Tooltip` + +| Prop | Type | Default | Description | +| ------------------- | -------------------------------- | --------- | --------------------------------------------------------------------------- | +| `children` | `(active: TActive) => ReactNode` | — | Content for the selected category. Return null to hide the tooltip | +| `side` | `'left' \| 'right'` | `'right'` | The side tried first | +| `sideOffset` | `number` | `16` | Distance in px from the category center | +| `collisionPadding` | `number` | `8` | Space in px kept from the edges of `collisionBoundary` | +| `collisionBoundary` | `RefObject` | the chart | Element the tooltip stays inside | +| `pinned` | `boolean \| 'auto'` | `'auto'` | Pins the tooltip to the top left of the boundary. `auto` below a 416px plot | + +`Chart.Tooltip` keeps `pointer-events: none`, so it never takes the pointer from the chart. It is not Mosaic's `Tooltip`: that one opens from a trigger on hover and focus and describes it, while the chart opens its tooltip from the selection and announces it through the `status` region. + +Name the active type the chart's hook selects, such as `>>`. It defaults to `ChartActive`: the selected `category`, `datumIndex` and `datum`. + +### `Chart.useBarChart` + +| Option | Type | Default | Description | +| ------------------- | -------------------------------------------- | --------------- | ------------------------------------------------------------------ | +| `data` | `readonly TDatum[]` | (required) | The rows | +| `series` | `readonly BarSeries[]` | (required) | Stack order and each series' value | +| `index` | `(datum: TDatum, index: number) => string` | (required) | A unique, stable category key | +| `categoryGap` | `number` | `0.28` | Fraction of each category band left empty | +| `margin` | `Partial` | `8, 16, 36, 52` | Space around the plot for the axes (top, right, bottom, left) | +| `projection` | `BarProjection` | — | A projected total, drawn when it rises above its category's stack | +| `isBarActive` | `(bar: BarIdentity) => boolean` | every bar | Returns false for a bar that `Chart.Bar` styles as `data-inactive` | +| `selection` | `BarSelection \| null` | uncontrolled | The selected category and section. `null` selects nothing | +| `onSelectionChange` | `(selection: BarSelection \| null) => void` | — | Called when the user, `select` or `clear` changes the selection | +| `defaultSelection` | `BarSelection \| null` | `null` | The selection the chart starts with when it holds the selection | +| `onActivate` | `(active: ActiveBar, event) => void` | — | Called on click, Enter or Space, with the event. Makes a button | +| `disabled` | `boolean` | `false` | Ignores the pointer and keyboard and leaves the tab order | +| `formatCategory` | `(key: string) => string \| null` | the key | Names a period in keyboard announcements | +| `formatValue` | `(value: number) => string` | `String` | Formats a value in keyboard announcements | +| `messages` | `Partial` | English | Screen reader text, including how Up and Down move | + +A `BarSeries` is `{ key, label?, value }`, and a `BarProjection` is `{ datumIndex, value, label? }`. Announcements name each by its `label`, or by `key` and `messages.projected`. `BarSelection` is `{ category, section }`. A new `isBarActive` function repaints the Canvas. `margin` and the last six options are the [options every chart type takes](#options-every-chart-type-takes). `BarChartMessages` adds `vertical`, `positiveValues`, `negativeValues` and `projected` to `ChartMessages`. + +The hook returns a `BarChartInstance`: the [chart object](#the-chart-object) with its value axis, `ActiveBar` as `selected` and `BarCategory` entries in `categories`. A `BarCategory` adds the sections a user can select (`sections`), which sections have values (`hasValues`) and whether the chart draws the projection there (`projected`). Its `x` and `width` are the category band. + +`ActiveBar` is the selected period: its `category`, `datumIndex`, `datum` and `section`, plus `hasValues` and `projected`. Name it on the tooltip: `>>`. + +## The chart object + +A chart-type hook returns a `ChartInstance` plus what its own marks need. A chart with a value axis, such as bars, returns a `CartesianChartInstance`, which adds `scaleY` and `yTicks`: + +| Field | Type | Description | +| ----------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `rootRef` | `(element: HTMLElement \| null) => void` | Measures the element. `Chart.Root` attaches it | +| `size` | `ChartSize` | The measured container, zero until the first measurement | +| `plot` | `ChartPlot` | The plot rectangle inside the margin | +| `scaleY` | `(value: number) => number` | Cartesian only. Maps a value to a Y coordinate | +| `yTicks` | `readonly ChartTick[]` | Cartesian only. The Y ticks | +| `categories` | `readonly ChartCategory[]` | One entry per row: `key`, `datumIndex`, `center`, `x` and `width` | +| `xTicks` | `(options?: XTicksOptions) => XTick[]` | The X labels for a tick mode, as `Chart.XAxis` computes them | +| `selected` | `TActive \| null` | The selection in the current data | +| `tooltipAnchor` | `{ x, y } \| null` | Where a tooltip for `selected` points | +| `announcement` | `string` | The status text for the keyboard selection | +| `keyboardInstructions` | `string` | The keys the chart answers to | +| `select`, `clear` | `(selection) => void`, `() => void` | Change the selection and call `onSelectionChange` | +| `getInteractionProps()` | `(props?) => ChartInteractionProps` | Role, `tabIndex`, `ref`, the chart type's `data-*` state and the event handlers, merged with `props` | + +A category's `x` and `width` are the extent its marks occupy: a band for bars. Its `center` is where the pointer snaps, the X tick sits and the tooltip anchors. `Chart.Root` and the shared parts hold the chart as a `ChartInstance`, whose `select` takes no value, so only the code that called the hook can select. `Chart.Grid`, `Chart.YAxis` and `Chart.YLine` throw when the chart has no value axis. + +## Options every chart type takes + +| Option | Type | Default | Description | +| ------------------- | ----------------------------------------- | --------------- | ----------------------------------------------------------------------------------------------- | +| `margin` | `Partial` | `8, 16, 36, 52` | Space around the plot for the axes (top, right, bottom, left) | +| `selection` | `TSelection \| null` | uncontrolled | The selection. `null` selects nothing | +| `onSelectionChange` | `(selection: TSelection \| null) => void` | — | Called when the user, `select` or `clear` changes the selection | +| `defaultSelection` | `TSelection \| null` | `null` | The selection the chart starts with when it holds the selection | +| `onActivate` | `(active: TActive, event) => void` | — | Called on click, Enter or Space, with the mouse or keyboard event. Makes the surface a button | +| `disabled` | `boolean` | `false` | Ignores the pointer and keyboard and leaves the tab order. `select` and `selection` still apply | +| `formatCategory` | `(key: string) => string \| null` | the key | Names a period in keyboard announcements | +| `formatValue` | `(value: number) => string` | `String` | Formats a value in keyboard announcements | +| `messages` | `Partial` | English | Screen reader text: `navigate`, `activate`, `dismiss`, `noValues` | + +## Keyboard + +The interaction surface is focusable while something reads the selection: `selection`, `onSelectionChange` or `onActivate` on the hook, or a `Chart.Tooltip`. + +| Key | Behavior | +| ------------------------ | ------------------------------------------------------------------------ | +| `ArrowLeft`/`ArrowRight` | Selects the previous or next period | +| `Home`/`End` | Selects the first or last period | +| `ArrowUp`/`ArrowDown` | Moves within the period, as the chart type defines (sections for bars) | +| `Enter`/`Space` | Calls `onActivate`. After `Escape`, reselects the dismissed period first | +| `Escape` | Clears the selection and remembers the period | + +Left and Right do not follow `useDirection()`. A time axis reads left to right in every locale, so the earlier period is always on the left. + +A pointer selects what the chart type hit-tests under it. A tap selects on contact and stays selected until the user taps outside the chart or the gesture is cancelled. + +## Selection + +The chart holds the selection unless you pass `selection`, starting from `defaultSelection`. `onSelectionChange` is called whenever a pointer move, a key, a focus change, `select` or `clear` changes it, in both modes. A data change alone does not call it: `chart.selected` resolves the selection against the current data, so a selection whose category disappears reads as null until the user moves. The exception is data that empties, covered below. + +Removing the interaction surface, such as unmounting `Chart.Selection`, ends a pointer or keyboard selection and calls `onSelectionChange` with null, as leaving or blurring the surface does. A selection set through `selection` or `select` stays. `Chart.Selection` also removes its surface when the data has no categories. + +A controlled `selection` decides what is selected. The chart also remembers two things the value cannot hold, and keeps them only while the controlled value agrees: + +- After Escape the selection is `dismissed`: the value is null, and the period is remembered so Enter reselects it instead of activating it. If the consumer then passes a non-null `selection`, that wins. +- Keyboard focus on a period with no values keeps that period for the next arrow key, with a null value. + +A selection set through `selection` or `select` is not announced. Announcements follow keyboard moves only. + +### Bar sections + +Up and Down select the positive or negative section of the period. Left, Right, Home and End keep the section when the new period has it, and otherwise take positive, then negative. When no value in the chart is negative, the keyboard instructions leave Up and Down out. + +A pointer selects the period whose center is nearest, anywhere in the plot: the same column the hover band shows, so a short or thin bar is as easy to point at as a tall one. It selects the section on its side of the zero line, and keeps the current section within a few pixels of it. + +The interaction surface carries `data-active-section`, `positive` or `negative` while a section is selected. The status region announces the period and each nonzero value in the section, such as `Feb, Sign-ups 20`, and the projection when the period has one. When some value in the chart is negative, it names the section first: `Feb, negative values, Churned -4`. A period with nothing to select announces `No values for this period`. + +Dim every bar outside the selected section by controlling the selection: + +```tsx +const [selection, setSelection] = useState(null); +const isBarActive = useCallback( + (bar: BarIdentity) => + !selection || (bar.datum.week === selection.category && bar.positive === (selection.section === 'positive')), + [selection], +); +const chart = Chart.useBarChart({ data, series, index, selection, onSelectionChange: setSelection, isBarActive }); +``` + +## Rendering from the chart object + +The parts are optional. Attach `rootRef` to the measured element, spread `getInteractionProps()` on the element that takes selection (pass your own handlers to it, and they run after the chart's), and render from the layout fields. Read `rootRef` into its own variable first: the React Compiler lint treats an object whose member is passed to `ref` as a ref, and then flags calls on it during render. + +```tsx +const chart = Chart.useBarChart({ data, series, index, onSelectionChange }); +const { rootRef } = chart; + +
+
+ {chart.categories.map(category => ( + {category.key} + ))} +
+ {chart.selected?.category} +
; +``` + +The pointer maps client coordinates through the `rootRef` element's bounds. + +Painting the bars is the one thing the chart object does not do, because their color and geometry come from `Chart.Bar`'s computed style: keep `Chart.Bars` for that. + +## Data attributes + +| Attribute | Part | Description | +| ----------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------- | +| `data-chart-interaction-mode` | `Chart.Root` | `pending` before the first measurement, `interactive` with `Chart.Selection` and categories, otherwise `visual-only` | +| `data-active` | `Chart.XTick` | Present while the tick's period is selected. Calendar boundary labels never carry it | +| `data-active-section` | `Chart.Selection` | `positive` or `negative` on the interaction surface while a bar section is selected | +| `data-side` | `Chart.Tooltip` | `left` or `right` of the selected period, or `bottom` when pinned to the top of a narrow chart | +| `data-open` / `data-closed` | `Chart.Tooltip` | The tooltip's open state, with `data-starting-style` and `data-ending-style` during transitions | + +The interaction surface also carries the chart type's state, such as `data-active-section` for bars. `Chart.Bar` takes its own attributes before each paint, listed under [Styling](#styling). + +## Accessibility + +- The chart type's marks carry `role="img"` and the `aria-label` from `Chart.Root`: for bars, the Canvas. The grid, axes, cursor, lines and projection outline are `aria-hidden`. +- The interaction surface sits outside the image role, so assistive technology can reach it. It is a `button` with `onActivate`, otherwise a `group`, and takes the same `aria-label`. With `disabled` it carries `aria-disabled="true"` and leaves the tab order. +- Visually hidden text describes the keys. A `status` region announces the selected period, named through `formatCategory`, and what the chart type adds. Pass `messages` to localize both. +- An assistive-technology click without coordinates activates the selected period. + +## Styling + +An unstyled chart is incomplete on purpose: SVG lines without a stroke do not paint, and text without a fill is black. Pass `className` to each item part. + +The parts set only the inline styles that layout and behavior depend on: absolute positioning, sizes, `pointer-events`, the tooltip's fixed position and maximum width, `vector-effect` on lines, and the visually hidden announcements. No part sets a z-index. `cursor` is inherited, so a pointer cursor on `Chart.Selection` reaches the interaction surface. `Chart.Cursor` has the selected category's `width`, so it covers a band and has no width over a point. + +The primitive reads and writes no CSS variables. + +### `Chart.Bar` + +Canvas cannot take a class, so the bars are styled through one hidden part. This is the one departure from the part model, where `data-*` attributes stay on the rendered element. `Chart.Bar` renders one `aria-hidden` ``. Before each paint, `Chart.Bars` puts it in every state it draws, reads its computed `color`, caches it per state, paints, then restores the element: + +| State | Set on `Chart.Bar` | +| --------------- | ----------------------------------- | +| A bar | `data-series` set to the series key | +| An inactive bar | The same, plus `data-inactive` | +| The projection | `data-projection` | + +Inspect a state by adding the attribute to the part in DevTools and reading its computed `color`. Without `Chart.Bar` nothing is painted, and there is no default color. Style `data-projection` whenever the layout has a projection, or the projection paints in the inherited text color. + +```css +.bar[data-series='signups'] { + --bar: #6d28d9; +} +.bar[data-series='churned'] { + --bar: #f97316; +} +.bar { + color: var(--bar); +} +.bar[data-inactive] { + color: color-mix(in srgb, var(--bar) 50%, white); +} +.bar[data-projection] { + color: #e5e5e5; +} +``` + +Tailwind reads `_` inside `data-[…]` as a space, so a key such as `first_active` needs an escaped underscore (`first\_active`), or the selector never matches and that series paints nothing. + +`Chart.Bar` also sets the bar geometry from its computed style. Only pixel values count: + +| CSS on `Chart.Bar` | Sets | Unstyled | +| -------------------- | ------------------------------------------------------- | -------------- | +| `max-width` | The widest a bar can be, centered in its category band | Fills the band | +| `row-gap` | The gap between segments and beside the zero line | No gap | +| Top corner radius | The corners at a stack's outer end, mirrored below zero | Square | +| Bottom corner radius | Every other corner | Square | + +The geometry is paint only. Selection, the cursor and the scales use the category band. Bars 2px or wider snap their sides to whole device pixels, and the projection also snaps its top, so edges stay crisp at a pixel ratio such as 1.25. + +`Chart.ProjectionOutline` styles the outline the Canvas strokes around the projection fill, in the same pass, so the two stay aligned at any pixel ratio. The Canvas reads its computed `stroke`, `stroke-width` and `stroke-dasharray`; unstyled, its `stroke` is `none` and nothing is drawn. The outline leaves a 1px gap outside the fill. The gap, and a stroke one device pixel or wider, round to whole device pixels, so both sides match. Its top corner radius is the fill's plus that offset, so the corners stay concentric, and its sides end square on the zero line. + +The Canvas repaints in the same frame when: + +- `Chart.Bar` or `Chart.ProjectionOutline` mounts, unmounts or changes `class` +- any attribute on an ancestor of `Chart.Bar`, up to ``, changes and a color the bars paint computes to a new value, so a theme switched through a class, `style`, `data-theme` or any other attribute repaints the bars, and an unrelated attribute change does not +- `prefers-color-scheme` changes and a color the bars paint computes to a new value, so `light-dark()` colors under `color-scheme: light dark` follow the OS +- the pixel ratio changes (capped at 2) +- the layout or the props of `Chart.Bars` change + +Other changes to the computed color do not repaint: a stylesheet added or removed, or another media query such as `prefers-contrast`. Change the class of `Chart.Bar` to repaint after one. The backing buffer is resized only when its pixel size changes. The part is `display: none`, so a CSS transition on its color does not animate the bars. + +## Paint order + +Root does not reorder its children, so paint order is JSX order. Write the parts in this order: + +1. `Chart.Grid` +2. The chart type's marks, such as `Chart.Bars`, with any `Chart.YLine` inside their SVG +3. `Chart.YAxis` +4. `Chart.XAxis` +5. `Chart.Selection`, last, so its surface receives the pointer and its cursor paints over the marks + +Each container renders nothing until Root has measured a non-zero size. + +Inside `Chart.Bars`, the position of `Chart.Bar` and `Chart.ProjectionOutline` does not matter: both are hidden, and the Canvas paints under every `Chart.YLine`. + +## Layout + +`useBarChart` prepares the stacks when `data`, `series` or `index` change, measures the `rootRef` element, and projects the layout for each size, margin, gap or projection change. `Chart.Bars` projects the bar marks when the layout or the bar geometry changes. The chart measures its container when `rootRef` attaches, so the first paint lands in the commit that mounts or hydrates it rather than a frame later behind the page's own effects, and a `ResizeObserver` commits each later size before paint, so the chart follows its container while resizing. + +The Y scale contains zero and the full positive and negative extents, including an accepted projection, before tick rounding. Gaps and the clearance from the zero line are paint insets: they move no values, ticks or stack endpoints. Insets and radii shrink on small marks so at least one pixel stays visible. + +A projection is drawn only when its `value` is finite and rises above its category's positive stack. The category and its `ActiveBar` then carry `projected: true`, and a projection-only category is selectable in its positive section. + +Dense paths are clipped into 32-device-pixel columns, which bounds software rasterization work in browsers without GPU rasterization. + +A lost or missing 2D context throws `Chart.CanvasRenderError`, with the original failure as its `cause`, so an error boundary can offer a retry that mounts a fresh Canvas. + +## Tooltip + +`Chart.Tooltip` positions with Floating UI against a virtual element at the chart's `tooltipAnchor`: the selected category's center, at the Y the chart type gives (the top of the plot for bars). It opens on `side`, flips to the other side when that one does not fit inside `collisionBoundary`, and keeps the side it chose last until that side stops fitting, so it does not cross the selection twice near an edge. A keyboard selection starts at the first period, so near the left edge it usually settles on the right. When `pinned`, or by default when the plot is narrower than 416px, it pins to the top-left of the boundary instead. It portals through Mosaic's `Portal`, so a `PortalProvider` decides where. It animates through `data-open`, `data-closed`, `data-starting-style` and `data-ending-style`, and holds its last content while it closes. + +## Dependencies and bundle size + +`d3-scale` and `d3-shape` compute the bar stacks and scales. Every `Chart` consumer currently bundles the bar code and d3, about 19KB gzip, even one that uses only the shared parts. The published `Chart` namespace is a single object, so webpack, Rollup and esbuild cannot drop its unused members. + +## Adding a chart type + +A chart type lives in its own folder under `src/primitives/chart/`, as stacked bars live in `bars/`. Its hook measures with `useChartFrame`, lays out its categories, and passes a pure `SelectionModel` to `useChartInstance`, both from `chart/internal/`. Lint lets only files under `chart/` import `chart/internal/`, and keeps the shared parts at the top of `chart/` out of it. The model owns the hit test from a chart point, where the keyboard lands, how a selection resolves against the data, the announcement and the tooltip's anchor. A chart with a value axis adds `scaleY` and `yTicks` to the instance, as `Chart.useBarChart` does; a chart without one, such as a donut, leaves them out. Its marks read their own layout from a module-private symbol on the instance, as `Chart.Bars` does. Its hook and parts join the `Chart` namespace in `parts.ts`. `line-chart-contract.test-d.ts` checks that a point chart and a chart without a value axis fit the contract. diff --git a/packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-dimmed-selection-chromium-linux.png b/packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-dimmed-selection-chromium-linux.png new file mode 100644 index 00000000000..7cf4aed9f04 Binary files /dev/null and b/packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-dimmed-selection-chromium-linux.png differ diff --git a/packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-diverging-chromium-linux.png b/packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-diverging-chromium-linux.png new file mode 100644 index 00000000000..38d1ba0c303 Binary files /dev/null and b/packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-diverging-chromium-linux.png differ diff --git a/packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-projection-chromium-linux.png b/packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-projection-chromium-linux.png new file mode 100644 index 00000000000..7e662b7cec2 Binary files /dev/null and b/packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-projection-chromium-linux.png differ diff --git a/packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-tooltip-open-chromium-linux.png b/packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-tooltip-open-chromium-linux.png new file mode 100644 index 00000000000..5d5c711c75b Binary files /dev/null and b/packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-tooltip-open-chromium-linux.png differ diff --git a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx new file mode 100644 index 00000000000..2eb2a63a3c2 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx @@ -0,0 +1,719 @@ +import { cleanup, render as renderComponent, screen } from '@testing-library/react'; +import type {} from '@vitest/browser-playwright'; +import type { ReactElement } from 'react'; +import { useRef } from 'react'; +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { cdp, page, userEvent } from 'vitest/browser'; + +import type { BarSelection } from '../bars/types'; +import { TestChart, type TestChartProps } from './test-chart'; + +type Row = { period: string; value: number }; + +const series = [{ key: 'value', value: (row: Row) => row.value }]; +const index = (row: Row) => row.period; +const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'].map((period, i) => ({ period, value: (i + 1) * 10 })); + +beforeAll(async () => { + await page.viewport(1280, 900); + const style = document.createElement('style'); + style.textContent = ` + .red { color: rgb(255, 0, 0); } + .blue { color: rgb(0, 0, 255); } + .series [data-series='value'], .series[data-series='value'] { color: rgb(0, 128, 0); } + html.dark .themed { color: rgb(0, 0, 255); } + .scheme { color-scheme: light dark; color: light-dark(rgb(255, 0, 0), rgb(0, 0, 255)); } + .dark-scope .scoped { color: rgb(0, 0, 255); } + html[data-brand-theme='night'] .branded { color: rgb(0, 0, 255); } + .projected { max-width: 32px; border-radius: 4px 4px 2px 2px; color: rgb(0, 0, 255); } + .projected[data-projection] { color: rgb(255, 0, 0); } + .outline { fill: none; stroke: rgb(0, 0, 0); } + `; + document.head.append(style); +}); + +afterEach(() => cleanup()); + +async function render(element: ReactElement) { + const view = renderComponent(element); + await expect.poll(() => screen.queryByRole('img', { name: 'Growth' })).toBeTruthy(); + return view; +} + +function Chart({ width = 600, ...props }: Partial> & { width?: number }) { + return ( +
+ {}} + {...props} + /> +
+ ); +} + +function surface() { + return screen.getByRole('group', { name: 'Growth' }); +} + +/** The color the Canvas painted at a point given in CSS pixels relative to the canvas. */ +function pixelAt(x: number, y: number) { + const canvas = screen.getByRole('img', { name: 'Growth' }); + if (!(canvas instanceof HTMLCanvasElement)) { + throw new Error('The chart image is not a canvas'); + } + const ratio = canvas.width / canvas.getBoundingClientRect().width; + const [r, g, b, a] = + canvas.getContext('2d')?.getImageData(Math.round(x * ratio), Math.round(y * ratio), 1, 1).data ?? []; + return `rgba(${r}, ${g}, ${b}, ${a})`; +} + +/** A point inside the last, tallest bar, relative to the canvas. */ +function insideLastBar() { + const canvas = screen.getByRole('img', { name: 'Growth' }).getBoundingClientRect(); + const plot = surface().getBoundingClientRect(); + const step = plot.width / months.length; + return { x: plot.right - step / 2 - canvas.left, y: plot.bottom - 4 - canvas.top }; +} + +function pointer(type: string, target: Element, clientX: number, clientY: number, pointerType = 'mouse') { + target.dispatchEvent(new PointerEvent(type, { bubbles: true, clientX, clientY, pointerType })); +} + +function centerOfCategory(categoryIndex: number) { + const plot = surface().getBoundingClientRect(); + const step = plot.width / months.length; + return { x: plot.left + step * (categoryIndex + 0.5), y: plot.top + plot.height / 2 }; +} + +describe('painting', () => { + it('paints the bars in the computed color of Chart.Bar', async () => { + await render(); + const { x, y } = insideLastBar(); + + await expect.poll(() => pixelAt(x, y)).toBe('rgba(255, 0, 0, 255)'); + }); + + it('paints each series in the color its data-series state computes to', async () => { + await render(); + const { x, y } = insideLastBar(); + + await expect.poll(() => pixelAt(x, y)).toBe('rgba(0, 128, 0, 255)'); + }); + + it('repaints when the class of Chart.Bar changes', async () => { + const { rerender } = await render(); + const { x, y } = insideLastBar(); + await expect.poll(() => pixelAt(x, y)).toBe('rgba(255, 0, 0, 255)'); + + rerender(); + + await expect.poll(() => pixelAt(x, y)).toBe('rgba(0, 0, 255, 255)'); + }); + + it('repaints when the theme on changes', async () => { + await render(); + const { x, y } = insideLastBar(); + await expect.poll(() => pixelAt(x, y)).toBe('rgba(255, 0, 0, 255)'); + + document.documentElement.classList.add('dark'); + try { + await expect.poll(() => pixelAt(x, y)).toBe('rgba(0, 0, 255, 255)'); + } finally { + document.documentElement.classList.remove('dark'); + } + }); + + it('repaints when the theme on an ancestor element changes', async () => { + await render( +
+ +
, + ); + const { x, y } = insideLastBar(); + await expect.poll(() => pixelAt(x, y)).toBe('rgba(255, 0, 0, 255)'); + + screen.getByTestId('scope').classList.add('dark-scope'); + + await expect.poll(() => pixelAt(x, y)).toBe('rgba(0, 0, 255, 255)'); + }); + + it('repaints when a theme switches through any attribute on ', async () => { + await render(); + const { x, y } = insideLastBar(); + await expect.poll(() => pixelAt(x, y)).toBe('rgba(255, 0, 0, 255)'); + + document.documentElement.setAttribute('data-brand-theme', 'night'); + try { + await expect.poll(() => pixelAt(x, y)).toBe('rgba(0, 0, 255, 255)'); + } finally { + document.documentElement.removeAttribute('data-brand-theme'); + } + }); + + it('repaints when the preferred color scheme changes', async () => { + await cdp().send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'light' }] }); + try { + await render(); + const { x, y } = insideLastBar(); + await expect.poll(() => pixelAt(x, y)).toBe('rgba(255, 0, 0, 255)'); + + await cdp().send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'dark' }] }); + + await expect.poll(() => pixelAt(x, y)).toBe('rgba(0, 0, 255, 255)'); + } finally { + await cdp().send('Emulation.setEmulatedMedia', { features: [] }); + } + }); + + it('repaints at the new pixel ratio, capped at 2', async () => { + const resolutionQueries: MediaQueryList[] = []; + const matchMedia = window.matchMedia.bind(window); + vi.spyOn(window, 'matchMedia').mockImplementation(query => { + const list = matchMedia(query); + if (query.includes('resolution')) { + resolutionQueries.push(list); + } + return list; + }); + await render(); + const canvas = screen.getByRole('img', { name: 'Growth' }); + if (!(canvas instanceof HTMLCanvasElement)) { + throw new Error('The chart image is not a canvas'); + } + const { x, y } = insideLastBar(); + await expect.poll(() => pixelAt(x, y)).toBe('rgba(255, 0, 0, 255)'); + const cssWidth = canvas.getBoundingClientRect().width; + expect(canvas.width).toBe(cssWidth); + + await cdp().send('Emulation.setDeviceMetricsOverride', { + width: 0, + height: 0, + deviceScaleFactor: 3, + mobile: false, + }); + try { + // Chromium's device emulation changes devicePixelRatio without firing the resolution query's + // change event, so send the event that moving to another display sends. + for (const list of [...resolutionQueries]) { + list.dispatchEvent(new MediaQueryListEvent('change', { media: list.media, matches: list.matches })); + } + await expect.poll(() => canvas.width).toBe(cssWidth * 2); + await expect.poll(() => pixelAt(x, y)).toBe('rgba(255, 0, 0, 255)'); + } finally { + await cdp().send('Emulation.clearDeviceMetricsOverride'); + } + }); + + it('paints nothing without Chart.Bar', async () => { + await render(); + const { x, y } = insideLastBar(); + + await expect.poll(() => surface()).toBeTruthy(); + expect(pixelAt(x, y)).toBe('rgba(0, 0, 0, 0)'); + }); +}); + +describe('the projection outline', () => { + const RADIUS = 4; + const projection = { datumIndex: months.length - 1, value: 120 }; + + function ProjectedChart({ outlineClassName = 'outline' }: { outlineClassName?: string }) { + return ( +
+ +
+ ); + } + + /** The projection fill's edges in CSS pixels: the run of opaque projection color on the Canvas. */ + function projectionFill() { + const canvas = screen.getByRole('img', { name: 'Growth' }); + const { width, height } = canvas.getBoundingClientRect(); + const red = 'rgba(255, 0, 0, 255)'; + const row = Array.from({ length: width }, (_, x) => x).filter(x => pixelAt(x, 20) === red); + const left = Math.min(...row); + const right = Math.max(...row) + 1; + const column = Array.from({ length: height }, (_, y) => y).filter( + y => pixelAt(Math.floor((left + right) / 2), y) === red, + ); + return { left, right, top: Math.min(...column) }; + } + + /** What the screen shows at CSS pixels, by decoding a screenshot of the chart. */ + async function screenPixels() { + const chart = screen.getByTestId('projected'); + const base64 = await page.elementLocator(chart).screenshot({ save: false }); + const image = new Image(); + image.src = `data:image/png;base64,${base64}`; + await image.decode(); + const canvas = document.createElement('canvas'); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext('2d', { willReadFrequently: true }); + context?.drawImage(image, 0, 0); + const origin = chart.getBoundingClientRect(); + const ratio = image.width / origin.width; + const canvasBox = screen.getByRole('img', { name: 'Growth' }).getBoundingClientRect(); + return (x: number, y: number) => { + const px = Math.floor((x + canvasBox.left - origin.left) * ratio); + const py = Math.floor((y + canvasBox.top - origin.top) * ratio); + const [r, g, b] = context?.getImageData(px, py, 1, 1).data ?? []; + return `rgb(${r}, ${g}, ${b})`; + }; + } + + /** One row of the screenshot at device-pixel resolution, as `[r, g, b]` per device pixel. */ + /** The Canvas row at CSS `y`, one entry per device pixel. */ + function canvasRow(y: number) { + const canvas = screen.getByRole('img', { name: 'Growth' }); + if (!(canvas instanceof HTMLCanvasElement)) { + throw new Error('The chart image is not a canvas'); + } + const ratio = canvas.width / canvas.getBoundingClientRect().width; + const data = canvas.getContext('2d')?.getImageData(0, Math.floor(y * ratio), canvas.width, 1).data ?? []; + return Array.from({ length: canvas.width }, (_, x) => Array.from(data.slice(x * 4, x * 4 + 4)).join(',')); + } + + /** The Canvas alpha at the device pixel that contains a CSS point. */ + function inkAt(x: number, y: number) { + const canvas = screen.getByRole('img', { name: 'Growth' }); + if (!(canvas instanceof HTMLCanvasElement)) { + throw new Error('The chart image is not a canvas'); + } + const ratio = canvas.width / canvas.getBoundingClientRect().width; + return canvas.getContext('2d')?.getImageData(Math.floor(x * ratio), Math.floor(y * ratio), 1, 1).data[3] ?? 0; + } + + const fill = 'rgb(255, 0, 0)'; + const gap = 'rgb(255, 255, 255)'; + const stroke = 'rgb(0, 0, 0)'; + + it('draws a crisp 1px stroke 1px outside the fill on both sides and the top', async () => { + await render(); + await expect.poll(() => pixelAt(insideLastBar().x, 20.5)).toBe('rgba(255, 0, 0, 255)'); + const { left, right, top } = projectionFill(); + const at = await screenPixels(); + const middle = top + 10.5; + const center = (left + right) / 2; + + expect([left - 2.5, left - 1.5, left - 0.5, left + 0.5].map(x => at(x, middle))).toEqual([gap, stroke, gap, fill]); + expect([right - 0.5, right + 0.5, right + 1.5, right + 2.5].map(x => at(x, middle))).toEqual([ + fill, + gap, + stroke, + gap, + ]); + expect([top - 2.5, top - 1.5, top - 0.5, top + 0.5].map(y => at(center, y))).toEqual([gap, stroke, gap, fill]); + }); + + it('leaves the same crisp gap on both sides at fractional pixel ratios', async () => { + const uneven: string[] = []; + try { + for (const deviceScaleFactor of [1.1, 1.25, 1.5, 1.8, 2]) { + await cdp().send('Emulation.setDeviceMetricsOverride', { + width: 1280, + height: 900, + deviceScaleFactor, + mobile: false, + }); + await render(); + await expect.poll(() => pixelAt(insideLastBar().x, 20.5)).toBe('rgba(255, 0, 0, 255)'); + // Rounding in the Canvas transform can leave a 1/255 sliver, so a pixel is classed by coverage. + const kinds = canvasRow(projectionFill().top + 10.5).map(pixel => { + const [r, g, , a] = pixel.split(',').map(Number); + if ((a ?? 0) < 16) { + return 'gap'; + } + if ((a ?? 0) > 240) { + return r === 255 && g === 0 ? 'fill' : 'stroke'; + } + return 'blur'; + }); + const first = kinds.indexOf('fill'); + const last = kinds.lastIndexOf('fill'); + const side = (pixels: string[]) => + pixels + .join(' ') + .replace(/(\w+)( \1)*/g, (run, kind: string) => `${kind}×${run.split(' ').length}`) + .split(' ') + .slice(0, 2) + .join(' '); + const left = side(kinds.slice(0, first).reverse()); + const right = side(kinds.slice(last + 1)); + if (left !== right || !left.startsWith('gap×') || !left.includes('stroke×')) { + uneven.push(`${deviceScaleFactor}x: left ${left}, right ${right}`); + } + cleanup(); + } + } finally { + await cdp().send('Emulation.clearDeviceMetricsOverride'); + } + + expect(uneven).toEqual([]); + }); + + it('keeps the top corners concentric with the fill', async () => { + await render(); + await expect.poll(() => pixelAt(insideLastBar().x, 20.5)).toBe('rgba(255, 0, 0, 255)'); + const { left, right, top } = projectionFill(); + const distance = RADIUS + 1.5; + const missed: string[] = []; + for (let degrees = 0; degrees <= 90; degrees += 15) { + const angle = (degrees * Math.PI) / 180; + const dx = distance * Math.cos(angle); + const dy = distance * Math.sin(angle); + for (const [x, y] of [ + [left + RADIUS - dx, top + RADIUS - dy], + [right - RADIUS + dx, top + RADIUS - dy], + ]) { + if (inkAt(x, y) === 0) { + missed.push(`${degrees}deg (${x.toFixed(2)}, ${y.toFixed(2)})`); + } + } + } + + expect(missed).toEqual([]); + }); + + it('meets the zero line with square bottom corners', async () => { + await render(); + await expect.poll(() => pixelAt(insideLastBar().x, 20.5)).toBe('rgba(255, 0, 0, 255)'); + const { left, right } = projectionFill(); + const zero = Number(document.querySelector('line')?.getAttribute('y1')); + + expect([inkAt(left - 1.5, zero - 1), inkAt(right + 1.5, zero - 1)]).toEqual([255, 255]); + expect([inkAt(left - 1.5, zero + 1), inkAt(right + 1.5, zero + 1)]).toEqual([0, 0]); + }); +}); + +describe('resizing', () => { + it('follows its container and keeps painting the full width', async () => { + const { rerender } = await render(); + await expect.poll(() => surface().getBoundingClientRect().width).toBeGreaterThan(0); + const before = surface().getBoundingClientRect().width; + + rerender(); + + await expect.poll(() => surface().getBoundingClientRect().width).toBe(before + 300); + const { x, y } = insideLastBar(); + await expect.poll(() => pixelAt(x, y)).toBe('rgba(255, 0, 0, 255)'); + }); + + it('paints in the commit that mounts it, without waiting for a ResizeObserver callback', async () => { + vi.stubGlobal( + 'ResizeObserver', + class { + observe() {} + unobserve() {} + disconnect() {} + }, + ); + try { + await render(); + const { x, y } = insideLastBar(); + expect(pixelAt(x, y)).toBe('rgba(255, 0, 0, 255)'); + } finally { + vi.unstubAllGlobals(); + } + }); +}); + +describe('choosing a period with a pointer', () => { + it('selects the period under a mouse and clears it when the mouse leaves', async () => { + const onSelectionChange = vi.fn<(selection: BarSelection | null) => void>(); + await render(); + const { x, y } = centerOfCategory(3); + + const plot = surface().getBoundingClientRect(); + await userEvent.hover(surface(), { position: { x: x - plot.left, y: y - plot.top } }); + await expect + .poll(() => onSelectionChange.mock.lastCall?.[0]) + .toMatchObject({ category: 'Apr', section: 'positive' }); + const cursor = screen.getByTestId('cursor').getBoundingClientRect(); + expect(cursor.left).toBeLessThan(x); + expect(cursor.right).toBeGreaterThan(x); + + await userEvent.unhover(surface()); + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toBeNull(); + expect(screen.queryByTestId('cursor')).toBeNull(); + }); + + it('selects on touch contact, keeps it after the finger lifts, and dismisses on a touch elsewhere', async () => { + const onSelectionChange = vi.fn<(selection: BarSelection | null) => void>(); + await render(); + const { x } = centerOfCategory(1); + + pointer('pointerdown', surface(), x, surface().getBoundingClientRect().bottom - 4, 'touch'); + surface().dispatchEvent( + new PointerEvent('pointerout', { bubbles: true, pointerType: 'touch', relatedTarget: document.body }), + ); + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toMatchObject({ category: 'Feb' }); + + pointer('pointerdown', document.body, 0, 0, 'touch'); + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toBeNull(); + }); + + it('selects the column under the mouse anywhere in the plot, above a short bar too', async () => { + const onSelectionChange = vi.fn<(selection: BarSelection | null) => void>(); + await render( + active.category} + />, + ); + const plot = surface().getBoundingClientRect(); + await userEvent.hover(surface(), { position: { x: centerOfCategory(5).x - plot.left, y: plot.height - 4 } }); + await expect.poll(() => screen.queryByTestId('tooltip')).toHaveTextContent('Jun'); + + await userEvent.hover(surface(), { position: { x: centerOfCategory(0).x - plot.left, y: 4 } }); + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toMatchObject({ category: 'Jan' }); + await expect.poll(() => screen.queryByTestId('tooltip')).toHaveTextContent('Jan'); + await userEvent.unhover(surface()); + }); + + it('moves a touch selection to the column tapped, above its bar too', async () => { + const onSelectionChange = vi.fn<(selection: BarSelection | null) => void>(); + await render(); + const plot = surface().getBoundingClientRect(); + + pointer('pointerdown', surface(), centerOfCategory(5).x, plot.bottom - 4, 'touch'); + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toMatchObject({ category: 'Jun' }); + + pointer('pointerdown', surface(), centerOfCategory(0).x, plot.top + 4, 'touch'); + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toMatchObject({ category: 'Jan' }); + }); + + it('selects the section on the same side of the zero line as the pointer, past the bars too', async () => { + type Signed = { period: string; gained: number; lost: number }; + const onSelectionChange = vi.fn<(selection: BarSelection | null) => void>(); + await render( +
+ row.gained }, + { key: 'lost', value: (row: Signed) => row.lost }, + ]} + index={(row: Signed) => row.period} + ariaLabel='Growth' + height={300} + barClassName='red' + onSelectionChange={onSelectionChange} + /> +
, + ); + const plot = surface().getBoundingClientRect(); + const jan = plot.left + plot.width / 4; + + pointer('pointermove', surface(), jan, plot.top + 4); + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toEqual({ category: 'Jan', section: 'positive' }); + pointer('pointermove', surface(), jan, plot.bottom - 4); + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toEqual({ category: 'Jan', section: 'negative' }); + }); +}); + +function BoundedChart({ width, chartWidth }: { width: number; chartWidth: number }) { + const boundary = useRef(null); + return ( +
+ ( +
+ {active.category}: {active.datum.value} +
+ )} + /> +
+ ); +} + +async function focusPeriod(presses: number) { + surface().focus(); + for (let i = 0; i < presses; i++) { + await userEvent.keyboard('{ArrowRight}'); + } + await expect.poll(() => screen.queryByTestId('tooltip')?.style.visibility).toBe(''); + return screen.getByTestId('tooltip'); +} + +function contains(outer: DOMRect, inner: DOMRect) { + return inner.left >= outer.left && inner.right <= outer.right && inner.top >= outer.top; +} + +describe('the tooltip', () => { + it('stays closed for a period whose content is null', async () => { + await render( (active.category === 'Feb' ? null : active.category)} />); + await focusPeriod(0); + expect(screen.getByTestId('tooltip')).toHaveTextContent('Jan'); + + await userEvent.keyboard('{ArrowRight}'); + await expect.poll(() => screen.queryByTestId('tooltip')).toBeNull(); + }); + + it('opens on `side` at `sideOffset` from the period', async () => { + await render( +
{active.category}
} + tooltip={{ side: 'left', sideOffset: 24 }} + />, + ); + const plot = surface().getBoundingClientRect(); + await userEvent.hover(surface(), { position: { x: centerOfCategory(3).x - plot.left, y: plot.height - 4 } }); + await expect.poll(() => screen.queryByTestId('tooltip')?.style.visibility).toBe(''); + + const tooltip = screen.getByTestId('tooltip'); + expect(tooltip).toHaveAttribute('data-side', 'left'); + expect(centerOfCategory(3).x - tooltip.getBoundingClientRect().right).toBeCloseTo(24, 0); + }); + + it('opens beside the selected period and shows its content', async () => { + await render( + , + ); + await focusPeriod(1); + + const tooltip = screen.getByTestId('tooltip'); + expect(tooltip).toHaveTextContent('Feb: 20'); + expect(tooltip).toHaveAttribute('data-side', 'right'); + expect(tooltip.getBoundingClientRect().left).toBeGreaterThan(centerOfCategory(1).x); + }); + + it('moves to the left of a period near the right edge and stays inside the boundary', async () => { + await render( + , + ); + await focusPeriod(5); + + const tooltip = screen.getByTestId('tooltip'); + await expect.poll(() => tooltip.getAttribute('data-side')).toBe('left'); + expect(tooltip.getBoundingClientRect().right).toBeLessThan(centerOfCategory(5).x); + expect(contains(screen.getByTestId('boundary').getBoundingClientRect(), tooltip.getBoundingClientRect())).toBe( + true, + ); + }); + + it('pins to the top of the boundary on a narrow plot', async () => { + await render( + , + ); + await focusPeriod(2); + + const boundary = screen.getByTestId('boundary').getBoundingClientRect(); + const tooltip = screen.getByTestId('tooltip').getBoundingClientRect(); + expect(tooltip.left).toBe(boundary.left + 8); + expect(tooltip.top).toBe(boundary.top + 8); + expect(contains(boundary, tooltip)).toBe(true); + }); + + it('closes when the selection is dismissed', async () => { + await render( + , + ); + await focusPeriod(1); + + await userEvent.keyboard('{Escape}'); + + await expect.poll(() => screen.queryByTestId('tooltip')).toBeNull(); + }); +}); + +function activeTicks() { + return [...document.querySelectorAll('text[data-active]')].map(tick => tick.textContent); +} + +describe('removing Chart.Selection', () => { + it('ends a keyboard selection', async () => { + const onSelectionChange = vi.fn<(selection: BarSelection | null) => void>(); + const { rerender } = await render(); + surface().focus(); + await userEvent.keyboard('{ArrowRight}'); + await expect.poll(activeTicks).toEqual(['Feb']); + + rerender( + , + ); + + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toBeNull(); + expect(activeTicks()).toEqual([]); + }); + + it('ends a pointer selection', async () => { + const onSelectionChange = vi.fn<(selection: BarSelection | null) => void>(); + const { rerender } = await render(); + const { x, y } = centerOfCategory(3); + pointer('pointermove', surface(), x, y); + await expect.poll(activeTicks).toEqual(['Apr']); + + rerender( + , + ); + + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toBeNull(); + expect(activeTicks()).toEqual([]); + }); + + it('keeps a selection the consumer set', async () => { + const onSelectionChange = vi.fn<(selection: BarSelection | null) => void>(); + const selection: BarSelection = { category: 'Mar', section: 'positive' }; + const { rerender } = await render( + , + ); + await expect.poll(activeTicks).toEqual(['Mar']); + + rerender( + , + ); + + expect(activeTicks()).toEqual(['Mar']); + expect(onSelectionChange).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx new file mode 100644 index 00000000000..d4546e79cc8 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx @@ -0,0 +1,666 @@ +import { cleanup, fireEvent, render as renderComponent, screen } from '@testing-library/react'; +import { useState } from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { axe } from '../../test-utils/axe'; +import type { RenderProps } from '../../utils'; +import { type BarSelection, Chart } from '..'; +import { chartFixture, type ChartRow, growthChart, quarter, render, renderChart, setupChart } from './fixtures'; +import { TestChart } from './test-chart'; + +beforeEach(setupChart); +afterEach(cleanup); + +function StackedChart({ + data = chartFixture.data, + render: renderProp, + children, +}: { + data?: readonly ChartRow[]; + render?: React.ComponentProps['render']; + children?: React.ReactNode; +}) { + const chart = Chart.useBarChart({ data, series: chartFixture.series, index: chartFixture.index }); + return ( + + {children} + + ); +} + +function chartRoot(container: HTMLElement) { + const root = container.firstElementChild; + if (!root) { + throw new Error('Missing chart root'); + } + return root; +} + +describe('composing parts', () => { + it.each([ + ['Chart.Grid', ], + ['Chart.Selection', ], + ['Chart.Bars', ], + ])('throws when %s is used outside Chart.Root', (part, element) => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + expect(() => renderComponent(element)).toThrow(`<${part}> must be used within `); + }); + + it.each([ + ['Cursor', ], + ['Tooltip', {() => 'Growth'}], + ])('throws when Chart.%s is used outside Chart.Selection', (part, element) => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + expect(() => render({element})).toThrow( + ` must be used within `, + ); + }); + + it('throws when Chart.Bar is used outside Chart.Bars', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + expect(() => + render( + + + , + ), + ).toThrow(' must be used within '); + }); + + function ChartWithoutValueAxis({ children }: { children: React.ReactNode }) { + const { scaleY: _scaleY, yTicks: _yTicks, ...chart } = Chart.useBarChart(chartFixture); + return ( + + {children} + + ); + } + + it.each([ + ['Grid', ], + ['YAxis', ], + [ + 'YLine', + , + ], + ])('throws when Chart.%s is given a chart without a value axis', (part, element) => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + expect(() => render({element})).toThrow( + ` needs a chart with a value axis, such as one from Chart.useBarChart`, + ); + }); + + it.each([ + ['an element',
], + ['a function', (props: RenderProps) =>
], + ])('renders a part as %s passed to render', (_, renderElement) => { + const { container } = render( + + + , + ); + + const root = chartRoot(container); + expect(root.tagName).toBe('SECTION'); + expect(root).toHaveAttribute('data-chart-interaction-mode', 'visual-only'); + expect(root).toContainElement(screen.getByRole('img', { name: 'Growth' })); + }); + + it('exposes the bars as the one labelled chart image', () => { + renderChart(); + + expect(screen.getAllByRole('img').map(image => image.getAttribute('aria-label'))).toEqual(['Growth']); + }); + + it('is interactive with Chart.Selection and categories', () => { + const { container, rerender } = render( + + + + , + ); + + expect(chartRoot(container)).toHaveAttribute('data-chart-interaction-mode', 'interactive'); + expect(screen.getByRole('group')).toBeInTheDocument(); + + rerender( + + + + , + ); + expect(chartRoot(container)).toHaveAttribute('data-chart-interaction-mode', 'visual-only'); + expect(screen.queryByRole('group')).toBeNull(); + }); +}); + +const twoSided = [{ period: 'Jan', gained: 12, lost: -4 }]; + +function press(target: Element, ...keys: string[]) { + fireEvent.focus(target); + keys.forEach(key => fireEvent.keyDown(target, { key })); +} + +describe('choosing a period', () => { + it('keeps dense data selectable until bar selection is turned off', () => { + const data = Array.from({ length: 2200 }, (_, period) => ({ + period: String(period), + value: period + 1, + })); + const { container, queryByRole, rerenderChart } = renderChart({ + data, + projection: { datumIndex: 2199, value: 2300 }, + }); + const mode = () => container.firstElementChild?.getAttribute('data-chart-interaction-mode'); + + expect(mode()).toBe('interactive'); + rerenderChart({ selectionPart: false }); + expect(queryByRole('group', { name: 'Growth' })).toBeNull(); + expect(mode()).toBe('visual-only'); + }); +}); + +describe('choosing a period with the keyboard', () => { + it('is a focusable group, not a button or an image', () => { + const { getByRole } = renderChart({ data: quarter }); + const group = getByRole('group', { name: 'Growth' }); + expect(group).toHaveAttribute('tabindex', '0'); + expect(getByRole('img', { name: 'Growth' })).not.toContainElement(group); + }); + + it.each([ + { keys: [], selection: { category: 'Jan', section: 'positive' } }, + { keys: ['ArrowRight'], selection: { category: 'Feb', datumIndex: 1 } }, + { keys: ['End'], selection: { category: 'Mar' } }, + { keys: ['End', 'Home'], selection: { category: 'Jan' } }, + { keys: ['End', 'ArrowLeft'], selection: { category: 'Feb' } }, + { + keys: ['ArrowRight', 'Escape', 'ArrowRight'], + selection: { category: 'Mar' }, + }, + { keys: ['End', 'Escape'], selection: null }, + ])('selects $selection after $keys', ({ keys, selection }) => { + const { interaction, active } = renderChart({ data: quarter }); + press(interaction, ...keys); + if (selection) { + expect(active()).toMatchObject(selection); + } else { + expect(active()).toBeNull(); + } + }); + + it.each([ + { keys: ['ArrowDown'], section: 'negative' }, + { keys: ['ArrowDown', 'ArrowUp'], section: 'positive' }, + ])('selects the $section section after $keys', ({ keys, section }) => { + const { interaction, active } = renderChart({ + ...growthChart, + data: twoSided, + }); + press(interaction, ...keys); + expect(active()).toMatchObject({ datumIndex: 0, section }); + }); + + const signups = [{ key: 'signups', label: 'Sign-ups', value: (row: ChartRow) => row.value }]; + const gainedAndLost = [ + { key: 'gained', label: 'Gained', value: (row: (typeof twoSided)[number]) => row.gained }, + { key: 'lost', label: 'Lost', value: (row: (typeof twoSided)[number]) => row.lost }, + { key: 'paused', label: 'Paused', value: () => 0 }, + ]; + + it.each([ + { + name: 'the period and its value, without a section, when no value is negative', + props: { data: quarter, series: signups }, + keys: ['ArrowRight'], + announcement: 'Feb, Sign-ups 20', + }, + { + name: 'the series key when a series has no label', + props: { data: quarter }, + keys: ['ArrowRight'], + announcement: 'Feb, value 20', + }, + { + name: 'the formatted period name and value', + props: { + data: quarter, + series: signups, + formatXTick: (period: string) => `${period} 2026`, + formatValue: (value: number) => `${value} people`, + }, + keys: [], + announcement: 'Jan 2026, Sign-ups 10 people', + }, + { + name: 'the projection beside the values', + props: { data: quarter, series: signups, projection: { datumIndex: 2, value: 50, label: 'Projected' } }, + keys: ['End'], + announcement: 'Mar, Sign-ups 30, Projected 50', + }, + { + name: 'a period that has no values', + props: { + data: [ + { period: 'Jan', value: 10 }, + { period: 'Feb', value: 0 }, + ], + }, + keys: ['ArrowRight'], + announcement: 'No values for this period', + }, + ])('announces $name', ({ props, keys, announcement }) => { + const { interaction, getByRole } = renderChart(props); + press(interaction, ...keys); + expect(getByRole('status').textContent).toBe(announcement); + }); + + it.each([ + { keys: [], announcement: 'Jan, positive values, Gained 12' }, + { keys: ['ArrowDown'], announcement: 'Jan, negative values, Lost -4' }, + ])('announces the section and its nonzero values after $keys on a stacked chart', ({ keys, announcement }) => { + const { interaction, getByRole } = renderChart({ ...growthChart, series: gainedAndLost, data: twoSided }); + press(interaction, ...keys); + expect(getByRole('status').textContent).toBe(announcement); + }); + + const french = { negativeValues: 'valeurs négatives', noValues: 'Aucune valeur pour cette période' }; + + it('announces a section in the language of `messages`', () => { + const { interaction, getByRole } = renderChart({ + ...growthChart, + series: gainedAndLost, + data: twoSided, + messages: french, + }); + press(interaction, 'ArrowDown'); + expect(getByRole('status').textContent).toBe('Jan, valeurs négatives, Lost -4'); + }); + + it('announces a period with no values in the language of `messages`', () => { + const { interaction, getByRole } = renderChart({ + data: [ + { period: 'Jan', value: 10 }, + { period: 'Feb', value: 0 }, + ], + messages: french, + }); + press(interaction, 'ArrowRight'); + expect(getByRole('status')).toHaveTextContent('Aucune valeur pour cette période'); + }); + + it('leaves Up and Down out of the keys when no value is negative', () => { + const { interaction } = renderChart({ data: quarter }); + expect(interaction).toHaveAccessibleDescription( + 'Use Left and Right to choose a period, or Home and End to jump to the first or last. Press Escape to dismiss.', + ); + }); + + it('describes the keys in the language of `messages`', () => { + const { interaction } = renderChart({ + ...growthChart, + data: twoSided, + onActivate: () => {}, + messages: { + navigate: 'Gauche et Droite choisissent une période.', + vertical: 'Haut et Bas choisissent une section.', + activate: 'Entrée ouvre la période.', + dismiss: 'Échap ferme.', + }, + }); + expect(interaction).toHaveAccessibleDescription( + 'Gauche et Droite choisissent une période. Haut et Bas choisissent une section. Entrée ouvre la période. Échap ferme.', + ); + }); +}); + +describe('accessibility (axe)', () => { + it.each([ + { name: 'a group', props: {} }, + { name: 'a button', props: { onActivate: () => {} } }, + ])('has no violations as $name', async ({ props }) => { + const { container } = renderChart({ data: quarter, ...props }); + expect(await axe(container)).toHaveNoViolations(); + }); +}); + +describe('activating a period', () => { + it.each([ + { name: 'Enter', props: { data: quarter }, keys: ['ArrowRight', 'Enter'] }, + { + name: 'Enter when the consumer only handles clicks', + props: { data: quarter, onSelectionChange: undefined }, + keys: ['ArrowRight', 'Enter'], + }, + { + name: 'an assistive technology click without coordinates', + props: { data: quarter }, + keys: ['ArrowRight'], + click: true, + }, + ])('opens the selected period with $name', ({ props, keys, click }) => { + const onActivate = vi.fn(); + const { interaction } = renderChart({ ...props, onActivate }); + press(interaction, ...keys); + if (click) { + fireEvent.click(interaction, { detail: 0 }); + } + expect(onActivate).toHaveBeenLastCalledWith( + expect.objectContaining({ datumIndex: 1 }), + expect.objectContaining({ type: click ? 'click' : 'keydown' }), + ); + }); + + it('reselects a dismissed period on Enter before opening it', () => { + const onActivate = vi.fn(); + const { interaction, active } = renderChart({ data: quarter, onActivate }); + press(interaction, 'End', 'Escape', 'Enter'); + expect(onActivate).not.toHaveBeenCalled(); + expect(active()).toMatchObject({ category: 'Mar' }); + + fireEvent.keyDown(interaction, { key: 'Enter' }); + expect(onActivate).toHaveBeenLastCalledWith(expect.objectContaining({ category: 'Mar' }), expect.anything()); + }); + + it('selects and activates a projection-only period with the keyboard', () => { + const datum = { period: 'Mar', gained: 0, lost: 0 }; + const onActivate = vi.fn(); + const { interaction, getByRole, active } = renderChart({ + ...growthChart, + data: [datum], + onActivate, + projection: { datumIndex: 0, value: 20 }, + }); + + fireEvent.focus(interaction); + expect(getByRole('status')).toHaveTextContent('Mar, Projected 20'); + fireEvent.keyDown(interaction, { key: 'Enter' }); + expect(active()).toMatchObject({ category: 'Mar', section: 'positive' }); + expect(onActivate).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ datum, datumIndex: 0, section: 'positive' }), + expect.anything(), + ); + }); + + it.each([ + { name: 'absent', projection: undefined }, + { + name: 'rejected', + projection: { datumIndex: 0, value: 0 }, + }, + { + name: 'out-of-range', + projection: { datumIndex: 1, value: 20 }, + }, + { + name: 'zero-height', + projection: { datumIndex: 0, value: -10 }, + }, + ])('does not activate zero values with an $name projection', ({ projection }) => { + const onSelectionChange = vi.fn(); + const onActivate = vi.fn(); + const { interaction, getByRole } = renderChart({ + data: [{ period: 'Jan', value: 0 }], + projection, + onSelectionChange, + onActivate, + }); + + fireEvent.focus(interaction); + expect(getByRole('status')).toHaveTextContent('No values for this period'); + fireEvent.keyDown(interaction, { key: 'Enter' }); + + expect(onSelectionChange).not.toHaveBeenCalledWith(expect.anything()); + expect(onActivate).not.toHaveBeenCalled(); + }); +}); + +describe('keeping the selection when data changes', () => { + it('keeps the selected period when the data is reordered', () => { + const onActivate = vi.fn(); + const data = quarter.slice(0, 2); + const { rerenderChart, getByRole, active } = renderChart({ + data, + onActivate, + }); + fireEvent.focus(getByRole('button')); + const refreshed = { period: 'Jan', value: 99 }; + rerenderChart({ data: [data[1], refreshed] }); + expect(active()).toMatchObject({ category: 'Jan', datumIndex: 1 }); + expect(getByRole('status')).toHaveTextContent('Jan, value 99'); + fireEvent.keyDown(getByRole('button'), { key: 'Enter' }); + expect(onActivate).toHaveBeenLastCalledWith( + expect.objectContaining({ datum: refreshed, datumIndex: 1 }), + expect.anything(), + ); + }); + + it('keeps a consumer that stores the selection in sync as its data changes', () => { + function Consumer({ value }: { value: number }) { + const data = [{ period: 'Jan', value }]; + const [active, setActive] = useState(null); + return ( + <> + {data.find(datum => datum.period === active?.category)?.value} + datum.value }]} + index={datum => datum.period} + ariaLabel='Growth' + onSelectionChange={setActive} + /> + + ); + } + const { getByRole, rerender } = render(); + const selectedValue = () => getByRole('status', { name: 'Selected value' }); + fireEvent.focus(getByRole('group', { name: 'Growth' })); + expect(selectedValue()).toHaveTextContent('10'); + rerender(); + expect(selectedValue()).toHaveTextContent('25'); + }); + + it.each(['Enter', ' ', 'ArrowDown'])( + 'moves the keyboard selection to a remaining period after data shrinks for %s', + key => { + const onActivate = vi.fn(); + const { interaction, rerenderChart, active } = renderChart({ + data: quarter, + onActivate, + }); + press(interaction, 'End'); + rerenderChart({ data: quarter.slice(0, 1) }); + fireEvent.keyDown(interaction, { key }); + expect(active()).toMatchObject({ datumIndex: 0, category: 'Jan' }); + if (key !== 'ArrowDown') { + expect(onActivate).toHaveBeenLastCalledWith( + expect.objectContaining({ datumIndex: 0, datum: quarter[0] }), + expect.anything(), + ); + } + }, + ); + + it('clears the keyboard announcement when its selected section disappears', () => { + const { getByRole, rerenderChart, active } = renderChart({ + ...growthChart, + data: [{ period: 'Jan', gained: 10, lost: -10 }], + }); + const control = getByRole('group'); + press(control, 'ArrowDown'); + expect(getByRole('status')).toHaveTextContent('Jan, negative values, lost -10'); + rerenderChart({ data: [{ period: 'Jan', gained: 10, lost: 0 }] }); + expect(active()).toBeNull(); + expect(getByRole('status')).toBeEmptyDOMElement(); + fireEvent.keyDown(control, { key: 'ArrowDown' }); + expect(getByRole('status').textContent).toBe('Jan, gained 10'); + }); +}); + +describe('reading the selected period as data changes', () => { + it('clears a removed period and announces the next selected one', () => { + const { interaction, getByRole, rerenderChart } = renderChart({ + data: [{ period: 'Jan', value: 10 }], + }); + fireEvent.focus(interaction); + expect(getByRole('status')).toHaveTextContent('Jan, value 10'); + + rerenderChart({ data: [{ period: 'Feb', value: 25 }] }); + expect(getByRole('status')).toBeEmptyDOMElement(); + + fireEvent.keyDown(interaction, { key: 'Home' }); + expect(getByRole('status')).toHaveTextContent('Feb, value 25'); + }); +}); + +describe('controlling the selection', () => { + const selectedTick = () => document.querySelector('text[data-active]')?.textContent ?? null; + + it('reports each keyboard move to onSelectionChange', () => { + const onSelectionChange = vi.fn(); + const { interaction } = renderChart({ data: quarter, onSelectionChange }); + + press(interaction, 'ArrowRight', 'ArrowRight', 'Escape'); + + expect(onSelectionChange.mock.calls).toEqual([ + [{ category: 'Jan', section: 'positive' }], + [{ category: 'Feb', section: 'positive' }], + [{ category: 'Mar', section: 'positive' }], + [null], + ]); + }); + + it('shows the controlled selection and keeps it until the value changes', () => { + const onSelectionChange = vi.fn(); + const { interaction, getByTestId, queryByTestId, rerenderChart, active } = renderChart({ + data: quarter, + selection: { category: 'Feb', section: 'positive' }, + onSelectionChange, + }); + expect(selectedTick()).toBe('Feb'); + expect(getByTestId('cursor')).toBeInTheDocument(); + + fireEvent.keyDown(interaction, { key: 'ArrowRight' }); + expect(onSelectionChange).toHaveBeenLastCalledWith({ category: 'Mar', section: 'positive' }); + expect(active()).toMatchObject({ category: 'Feb', datumIndex: 1 }); + + rerenderChart({ selection: null }); + expect(selectedTick()).toBeNull(); + expect(queryByTestId('cursor')).toBeNull(); + }); + + it('reselects a dismissed period on Enter when the consumer holds the selection', () => { + const onActivate = vi.fn(); + function Consumer() { + const [selection, setSelection] = useState(null); + return ( + + ); + } + render(); + const interaction = screen.getByRole('button', { name: 'Growth' }); + + press(interaction, 'End', 'Escape', 'Enter'); + expect(onActivate).not.toHaveBeenCalled(); + expect(selectedTick()).toBe('Mar'); + + fireEvent.keyDown(interaction, { key: 'Enter' }); + expect(onActivate).toHaveBeenLastCalledWith(expect.objectContaining({ category: 'Mar' }), expect.anything()); + }); +}); + +describe('rendering from the chart object', () => { + it('selects with the keyboard on a surface that spreads the interaction props', () => { + function CustomChart() { + const chart = Chart.useBarChart({ ...chartFixture, data: quarter, onSelectionChange: () => {} }); + const { rootRef } = chart; + return ( +
+
+ {chart.categories.map(category => ( + {category.key} + ))} +
+ {chart.selected?.category} +
+ ); + } + render(); + const surface = screen.getByRole('group', { name: 'Growth' }); + + press(surface, 'End'); + + expect(screen.getByRole('status', { name: 'Selected period' })).toHaveTextContent('Mar'); + }); + + it('runs handlers passed to getInteractionProps after its own', () => { + const onKeyDown = vi.fn(); + function CustomChart() { + const chart = Chart.useBarChart({ ...chartFixture, data: quarter, onSelectionChange: () => {} }); + const { rootRef } = chart; + return ( +
+
+ {chart.selected?.category} +
+ ); + } + render(); + + press(screen.getByRole('group', { name: 'Growth' }), 'End'); + + expect(screen.getByRole('status', { name: 'Selected period' })).toHaveTextContent('Mar'); + expect(onKeyDown).toHaveBeenCalledWith(expect.objectContaining({ key: 'End' })); + }); +}); + +describe('starting and disabling the selection', () => { + it('starts from `defaultSelection` and then holds the selection itself', () => { + const onSelectionChange = vi.fn(); + const { interaction, active } = renderChart({ + data: quarter, + onSelectionChange, + defaultSelection: { category: 'Feb', section: 'positive' }, + }); + expect(active()).toMatchObject({ category: 'Feb' }); + expect(onSelectionChange).not.toHaveBeenCalled(); + + fireEvent.keyDown(interaction, { key: 'End' }); + expect(active()).toMatchObject({ category: 'Mar' }); + }); + + it('ignores the pointer and keyboard and leaves the tab order while `disabled`', () => { + const onActivate = vi.fn(); + const { interaction, active } = renderChart({ data: quarter, onActivate, disabled: true }); + expect(interaction).not.toHaveAttribute('tabindex'); + expect(interaction).toHaveAttribute('aria-disabled', 'true'); + + press(interaction, 'End', 'Enter'); + fireEvent.click(interaction, { detail: 0 }); + + expect(active()).toBeNull(); + expect(onActivate).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/mosaic/src/primitives/chart/__tests__/chart.visual.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.visual.test.tsx new file mode 100644 index 00000000000..d707a69ed08 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.visual.test.tsx @@ -0,0 +1,174 @@ +import { render, screen } from '@testing-library/react'; +import { useCallback, useRef } from 'react'; +import { beforeAll, describe, expect, it } from 'vitest'; +import { page, userEvent } from 'vitest/browser'; + +import { type ActiveBar, type BarIdentity, type BarProjection, Chart } from '..'; + +const growth = [ + { week: '2026-01-05', signups: 40, returning: 22, churned: -14 }, + { week: '2026-01-12', signups: 52, returning: 30, churned: -18 }, + { week: '2026-01-19', signups: 36, returning: 26, churned: -22 }, + { week: '2026-01-26', signups: 61, returning: 34, churned: -12 }, + { week: '2026-02-02', signups: 48, returning: 29, churned: -25 }, + { week: '2026-02-09', signups: 55, returning: 41, churned: -17 }, +]; + +type GrowthRow = (typeof growth)[number]; + +const series = [ + { key: 'signups', value: (row: GrowthRow) => row.signups }, + { key: 'returning', value: (row: GrowthRow) => row.returning }, + { key: 'churned', value: (row: GrowthRow) => row.churned }, +]; + +const getWeek = (row: GrowthRow) => row.week; +const formatWeek = (week: string) => week.slice(5); +const projection: BarProjection = { datumIndex: 5, value: 120 }; + +beforeAll(() => { + const style = document.createElement('style'); + style.textContent = ` + .chart { width: 640px; font-size: 12px; background: white; } + .grid-line { stroke: #d4d4d4; stroke-dasharray: 1 3; } + .zero-line { stroke: #171717; stroke-width: 2; } + .tick { fill: #525252; } + .projection-outline { fill: none; stroke: #525252; stroke-dasharray: 3 3; } + .bar { max-width: 32px; row-gap: 2px; border-radius: 4px 4px 2px 2px; color: var(--bar); } + .bar[data-series='signups'] { --bar: #6d28d9; } + .bar[data-series='returning'] { --bar: #0ea5e9; } + .bar[data-series='churned'] { --bar: #f97316; } + .bar[data-inactive] { color: color-mix(in srgb, var(--bar) 40%, white); } + .bar[data-projection] { color: #e5e5e5; } + .cursor { background: #a3a3a3; opacity: 0.15; } + .tooltip { background: white; border: 1px solid #d4d4d4; border-radius: 6px; padding: 8px; } + `; + document.head.append(style); +}); + +function GrowthChart({ + selected, + projected = false, +}: { + selected?: { week: string; positive: boolean }; + projected?: boolean; +}) { + const boundary = useRef(null); + const isBarActive = useCallback( + (bar: BarIdentity) => + !selected || (bar.datum.week === selected.week && bar.positive === selected.positive), + [selected], + ); + const chart = Chart.useBarChart({ + data: growth, + series, + index: getWeek, + projection: projected ? projection : undefined, + isBarActive, + formatCategory: formatWeek, + }); + return ( +
+ + + {ticks => + ticks.map(tick => ( + + )) + } + + + + + + + + {ticks => + ticks.map(tick => ( + + )) + } + + + {ticks => + ticks.map(tick => ( + + )) + } + + + + > + className='tooltip' + collisionBoundary={boundary} + > + {({ datum }) => ( + <> +
{datum.week}
+
Sign-ups: {datum.signups}
+
Churned: {datum.churned}
+ + )} + +
+
+
+ ); +} + +async function renderChart(ui: React.ReactElement) { + render(ui); + await expect.poll(() => screen.queryByRole('img', { name: 'Weekly growth' })).toBeTruthy(); + await document.fonts.ready; + return page.elementLocator(screen.getByTestId('chart')); +} + +describe('Chart stacked bars visual state', () => { + it('stacks values above and below zero', async () => { + const chart = await renderChart(); + await expect(chart).toMatchScreenshot('stacked-bars-diverging'); + }); + + it('dims every bar outside the selected section', async () => { + const chart = await renderChart(); + await expect(chart).toMatchScreenshot('stacked-bars-dimmed-selection'); + }); + + it('draws a projection above the latest bar', async () => { + const chart = await renderChart(); + await expect(chart).toMatchScreenshot('stacked-bars-projection'); + }); + + it('opens the tooltip beside the selected period', async () => { + const chart = await renderChart(); + screen.getByRole('group', { name: 'Weekly growth' }).focus(); + await userEvent.keyboard('{ArrowRight}'); + await expect + .poll(() => screen.queryByText('Sign-ups: 52')?.closest('.tooltip')?.style.visibility) + .toBe(''); + await expect(chart).toMatchScreenshot('stacked-bars-tooltip-open'); + }); +}); diff --git a/packages/mosaic/src/primitives/chart/__tests__/fixtures.tsx b/packages/mosaic/src/primitives/chart/__tests__/fixtures.tsx new file mode 100644 index 00000000000..4e7d8bbf273 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/__tests__/fixtures.tsx @@ -0,0 +1,107 @@ +import { act, render as renderComponent } from '@testing-library/react'; +import type { ReactElement } from 'react'; +import { vi } from 'vitest'; + +import type { BarChartInstance } from '..'; +import type { BarSelection } from '../bars/types'; +import { TestChart, type TestChartProps } from './test-chart'; + +/** Every observed element reports a 600x300 box when `render` flushes it; happy-dom has no layout. */ +const observed: (() => void)[] = []; + +class TestResizeObserver { + constructor(private callback: ResizeObserverCallback) {} + observe(target: Element) { + const entry = { target, borderBoxSize: [{ inlineSize: 600, blockSize: 300 }] }; + // eslint-disable-next-line typescript/consistent-type-assertions -- A stub entry carries only the fields the chart reads. + observed.push(() => this.callback([entry as unknown as ResizeObserverEntry], this)); + } + unobserve() {} + disconnect() {} +} + +export function render(element: ReactElement) { + const view = renderComponent(element); + act(() => observed.splice(0).forEach(report => report())); + return view; +} + +export type ChartRow = { period: string; value: number }; + +export const chartFixture = { + data: [{ period: 'Jan', value: 10 }], + series: [{ key: 'value', value: (row: ChartRow) => row.value }], + index: (row: ChartRow) => row.period, + ariaLabel: 'Growth', +} satisfies TestChartProps; + +/** + * Renders the chart with a one-series fixture. Pass `data`, `series` and `index` together to use + * another row shape. `active()` returns the chart's selected bar. + */ +export function renderChart(props: Partial> = {}) { + // eslint-disable-next-line typescript/consistent-type-assertions -- Callers that change the row type pass their own data, series and index. + const base = chartFixture as unknown as TestChartProps; + const onSelectionChange = vi.fn<(selection: BarSelection | null) => void>(); + const chartRef: { current: BarChartInstance | null } = { current: null }; + const chartProps = { ...base, onSelectionChange, chartRef, ...props }; + const view = render(); + const name = chartProps.ariaLabel; + const interaction = view.queryByRole('button', { name }) ?? view.getByRole('group', { name }); + return { + ...view, + interaction, + active: () => chartRef.current?.selected ?? null, + rerenderChart: (next: Partial>) => + view.rerender( + , + ), + }; +} + +type GrowthRow = { period: string; gained: number; lost: number }; + +export const growthChart = { + series: [ + { key: 'gained', value: (row: GrowthRow) => row.gained }, + { key: 'lost', value: (row: GrowthRow) => row.lost }, + ], + index: (row: GrowthRow) => row.period, +}; + +export const quarter = [ + { period: 'Jan', value: 10 }, + { period: 'Feb', value: 20 }, + { period: 'Mar', value: 30 }, +]; + +const context = { + save: vi.fn(), + restore: vi.fn(), + clip: vi.fn(), + beginPath: vi.fn(), + clearRect: vi.fn(), + fill: vi.fn(), + fillStyle: '', + rect: vi.fn(), + roundRect: vi.fn(), + setTransform: vi.fn(), + moveTo: vi.fn(), + arcTo: vi.fn(), + lineTo: vi.fn(), + stroke: vi.fn(), + setLineDash: vi.fn(), + strokeStyle: '', + lineWidth: 1, +}; + +/** Fakes what happy-dom lacks for the chart to mount: a measured size and a 2D context. */ +export function setupChart() { + observed.length = 0; + vi.stubGlobal('ResizeObserver', TestResizeObserver); + // eslint-disable-next-line typescript/consistent-type-assertions -- happy-dom has no 2D context; the stub records nothing the tests read. + vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context as unknown as CanvasRenderingContext2D); +} diff --git a/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx b/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx new file mode 100644 index 00000000000..cb1c60c5cf4 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx @@ -0,0 +1,95 @@ +import { type ReactNode, type RefObject, useLayoutEffect } from 'react'; + +import { type ActiveBar, type BarChartInstance, Chart, type ChartTooltipProps, type UseBarChartOptions } from '..'; + +export type TestChartProps = Pick< + UseBarChartOptions, + | 'data' + | 'series' + | 'index' + | 'categoryGap' + | 'projection' + | 'isBarActive' + | 'selection' + | 'onSelectionChange' + | 'onActivate' + | 'messages' + | 'formatValue' + | 'defaultSelection' + | 'disabled' +> & { + ariaLabel: string; + formatXTick?: (value: string) => string | null; + /** Mounts `Chart.Selection`. Default: true */ + selectionPart?: boolean; + renderTooltip?: (active: ActiveBar) => ReactNode; + tooltip?: Pick; + boundary?: RefObject; + height?: number | string; + /** Mounts `Chart.Bar`. Default: true */ + bar?: boolean; + barClassName?: string; + outlineClassName?: string; + /** Receives the chart object after each render. */ + chartRef?: { current: BarChartInstance | null }; +}; + +/** Composes every bar chart part from one flat set of test props. */ +export function TestChart({ + ariaLabel, + formatXTick, + selectionPart = true, + renderTooltip, + tooltip, + boundary, + height, + bar = true, + barClassName, + outlineClassName, + chartRef, + ...options +}: TestChartProps) { + const chart = Chart.useBarChart({ ...options, formatCategory: formatXTick }); + useLayoutEffect(() => { + if (chartRef) { + chartRef.current = chart; + } + }); + return ( + + + {bar ? : null} + + + + + {ticks => + ticks.map(tick => ( + + )) + } + + {selectionPart ? ( + + + {renderTooltip ? ( + > + collisionBoundary={boundary} + data-testid='tooltip' + {...tooltip} + > + {renderTooltip} + + ) : null} + + ) : null} + + ); +} diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/bar-layout.test.ts b/packages/mosaic/src/primitives/chart/bars/__tests__/bar-layout.test.ts new file mode 100644 index 00000000000..cf15b70183c --- /dev/null +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/bar-layout.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from 'vitest'; + +import { DEFAULT_CHART_MARGIN } from '../../internal/use-chart-instance'; +import { prepareStackedBars, projectStackedBars } from '../bar-layout'; +import type { BarProjection } from '../types'; + +interface TypedRow { + start: string; + gained: number; + lost: number; +} + +describe('typed rows', () => { + it('reads interface rows through series accessors and keeps each original row', () => { + const rows: TypedRow[] = [ + { start: 'Jan', gained: 4, lost: -2 }, + { start: 'Feb', gained: 0, lost: -1 }, + ]; + const prepared = prepareStackedBars({ + data: rows, + series: [ + { key: 'up', value: row => row.gained * 2 }, + { key: 'down', value: row => row.lost }, + ], + index: row => row.start, + }); + + expect(prepared.points.map(point => [point.seriesKey, point.value])).toEqual([ + ['up', 8], + ['down', -2], + ['down', -1], + ]); + expect(prepared.points[0].datum).toBe(rows[0]); + expect(prepared.domain).toEqual([-2, 8]); + }); +}); + +describe('projection acceptance', () => { + it.each<{ projection: BarProjection; projected: boolean }>([ + { projection: { datumIndex: 0, value: 20 }, projected: true }, + { projection: { datumIndex: 0, value: 10.5 }, projected: true }, + { projection: { datumIndex: 99, value: 10000 }, projected: false }, + { projection: { datumIndex: -1, value: 10000 }, projected: false }, + { projection: { datumIndex: 0.5, value: 10000 }, projected: false }, + { projection: { datumIndex: NaN, value: 10000 }, projected: false }, + { projection: { datumIndex: 0, value: 5 }, projected: false }, + { projection: { datumIndex: 0, value: 10 }, projected: false }, + { projection: { datumIndex: 0, value: NaN }, projected: false }, + { projection: { datumIndex: 0, value: Infinity }, projected: false }, + ])( + 'draws projection $projection.datumIndex/$projection.value over a bar of 10: $projected', + ({ projection, projected }) => { + const prepared = prepareStackedBars({ + data: [{ period: 'Jan', value: 10 }], + series: [{ key: 'value', value: row => row.value }], + index: row => row.period, + }); + const result = projectStackedBars(prepared, { + size: { width: 400, height: 300 }, + margin: DEFAULT_CHART_MARGIN, + categoryGap: 0.25, + projection, + }); + + expect(result.projection !== null).toBe(projected); + expect(result.categories[0]?.projected).toBe(projected); + if (projected) { + expect(result.yTicks.at(-1)?.value).toBeGreaterThanOrEqual(projection.value); + } + }, + ); + + it('makes a projection-only category selectable in its positive section', () => { + const prepared = prepareStackedBars({ + data: [{ period: 'Mar', value: 0 }], + series: [{ key: 'value', value: row => row.value }], + index: row => row.period, + }); + const [category] = projectStackedBars(prepared, { + size: { width: 400, height: 300 }, + margin: DEFAULT_CHART_MARGIN, + categoryGap: 0.25, + projection: { datumIndex: 0, value: 20 }, + }).categories; + + expect(category).toMatchObject({ + projected: true, + sections: { positive: true, negative: false }, + hasValues: { positive: false, negative: false }, + }); + }); +}); diff --git a/packages/mosaic/src/primitives/chart/bars/bar-canvas-error.ts b/packages/mosaic/src/primitives/chart/bars/bar-canvas-error.ts new file mode 100644 index 00000000000..3ee35c799ba --- /dev/null +++ b/packages/mosaic/src/primitives/chart/bars/bar-canvas-error.ts @@ -0,0 +1,6 @@ +export class CanvasRenderError extends Error { + constructor(message: string, cause: unknown) { + super(message, { cause }); + this.name = 'CanvasRenderError'; + } +} diff --git a/packages/mosaic/src/primitives/chart/bars/bar-canvas.ts b/packages/mosaic/src/primitives/chart/bars/bar-canvas.ts new file mode 100644 index 00000000000..5967e5469a7 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/bars/bar-canvas.ts @@ -0,0 +1,371 @@ +import { getComputedStyle } from '../../utils/dom'; +import type { ChartSize } from '../types'; +import { CanvasRenderError } from './bar-canvas-error'; +import { type BarGeometry, type PaintedProjection, UNSTYLED_BAR_GEOMETRY } from './bar-layout'; +import type { BarIdentity, BarMark } from './types'; + +const TILE_DEVICE_PIXELS = 32; + +type BarCanvasContext = Pick< + CanvasRenderingContext2D, + 'save' | 'restore' | 'beginPath' | 'rect' | 'roundRect' | 'clip' | 'fill' | 'fillStyle' +>; + +export function getPaintedBarMark( + mark: Pick, 'y' | 'height' | 'width' | 'radii' | 'paintInsetTop' | 'paintInsetBottom'>, +) { + const requestedInset = mark.paintInsetTop + mark.paintInsetBottom; + const scale = requestedInset > 0 ? Math.min(1, Math.max(0, mark.height - 1) / requestedInset) : 1; + const top = mark.paintInsetTop * scale; + const bottom = mark.paintInsetBottom * scale; + const height = Math.max(0, mark.height - top - bottom); + const limit = (radius: number) => Math.min(radius, mark.width / 2, height / 2); + const radii: BarMark['radii'] = [ + limit(mark.radii[0]), + limit(mark.radii[1]), + limit(mark.radii[2]), + limit(mark.radii[3]), + ]; + return { y: mark.y + top, height, radii }; +} + +type BarBatch = { + context: BarCanvasContext; + tileWidth: number; + height: number; + tiles: Map[]>; + hasOpenPath: boolean; +}; + +function fillTiles(batch: BarBatch) { + const { context, tileWidth, height } = batch; + for (const [tile, tileMarks] of batch.tiles) { + context.save(); + context.beginPath(); + context.rect(tile * tileWidth, 0, tileWidth, height); + context.clip(); + context.beginPath(); + for (const mark of tileMarks) { + const painted = getPaintedBarMark(mark); + context.rect(mark.x, painted.y, mark.width, painted.height); + } + context.fill(); + context.restore(); + } + batch.tiles.clear(); +} + +function flush(batch: BarBatch) { + if (batch.hasOpenPath) { + batch.context.fill(); + batch.hasOpenPath = false; + } + fillTiles(batch); +} + +function addThinBar(batch: BarBatch, mark: BarMark) { + if (batch.hasOpenPath) { + flush(batch); + } + // Disjoint device-pixel clips bound software raster work without widening bars or blending a + // shared fractional pixel twice at a batch boundary. + const { tileWidth, tiles } = batch; + for (let tile = Math.floor(mark.x / tileWidth); tile < Math.ceil((mark.x + mark.width) / tileWidth); tile++) { + const tileMarks = tiles.get(tile); + if (tileMarks) { + tileMarks.push(mark); + } else { + tiles.set(tile, [mark]); + } + } +} + +function addRoundedBar(batch: BarBatch, mark: BarMark) { + if (batch.tiles.size > 0) { + flush(batch); + } + if (!batch.hasOpenPath) { + batch.context.beginPath(); + batch.hasOpenPath = true; + } + const painted = getPaintedBarMark(mark); + batch.context.roundRect(mark.x, painted.y, mark.width, painted.height, painted.radii); +} + +export function drawCanvasBars({ + context, + marks, + pixelRatio, + height, + getFill, +}: Readonly<{ + context: BarCanvasContext; + marks: readonly BarMark[]; + pixelRatio: number; + height: number; + getFill: (mark: BarMark) => string; +}>) { + const batch: BarBatch = { + context, + tileWidth: TILE_DEVICE_PIXELS / pixelRatio, + height, + tiles: new Map(), + hasOpenPath: false, + }; + let activeFill: string | undefined; + for (const mark of marks) { + const fill = getFill(mark); + if (fill !== activeFill) { + flush(batch); + activeFill = fill; + context.fillStyle = fill; + } + if (mark.width < 2) { + addThinBar(batch, mark); + } else { + addRoundedBar(batch, mark); + } + } + flush(batch); +} + +const BAR_STATE_ATTRIBUTES = ['data-series', 'data-inactive', 'data-projection'] as const; + +export type BarStyleElement = HTMLElement | SVGElement; + +function readPixels(value: string, fallback: number) { + const pixels = Number.parseFloat(value); + return value.trim().endsWith('px') && Number.isFinite(pixels) ? pixels : fallback; +} + +/** + * Serializes the bar geometry from `Chart.Bar`'s computed style, so it can be a + * `useSyncExternalStore` snapshot. + */ +export function getBarGeometrySnapshot(element: BarStyleElement | null) { + if (!element) { + return ''; + } + const style = getComputedStyle(element); + return JSON.stringify([ + readPixels(style.maxWidth, UNSTYLED_BAR_GEOMETRY.maxWidth), + readPixels(style.rowGap, UNSTYLED_BAR_GEOMETRY.gap), + readPixels(style.borderTopLeftRadius, UNSTYLED_BAR_GEOMETRY.outerRadius), + readPixels(style.borderBottomLeftRadius, UNSTYLED_BAR_GEOMETRY.radius), + ]); +} + +export function parseBarGeometry(snapshot: string): BarGeometry { + if (!snapshot) { + return UNSTYLED_BAR_GEOMETRY; + } + const parsed: unknown = JSON.parse(snapshot); + if (!Array.isArray(parsed)) { + return UNSTYLED_BAR_GEOMETRY; + } + const [maxWidth, gap, outerRadius, radius] = parsed.map(value => (typeof value === 'number' ? value : null)); + return { + // JSON turns an unstyled `Infinity` into null. + maxWidth: maxWidth ?? Infinity, + gap: gap ?? 0, + outerRadius: outerRadius ?? 0, + radius: radius ?? 0, + }; +} + +export type BarState = Readonly<{ + seriesKey?: string; + inactive?: boolean; + projection?: boolean; +}>; + +function createBarColorResolver(element: BarStyleElement) { + const previousAttributes = BAR_STATE_ATTRIBUTES.map(name => [name, element.getAttribute(name)] as const); + const cache = new Map(); + + const resolve = ({ seriesKey, inactive, projection }: BarState) => { + const key = JSON.stringify([seriesKey, inactive, projection]); + const cached = cache.get(key); + if (cached) { + return cached; + } + if (seriesKey) { + element.setAttribute('data-series', seriesKey); + } else { + element.removeAttribute('data-series'); + } + element.toggleAttribute('data-inactive', Boolean(inactive)); + element.toggleAttribute('data-projection', Boolean(projection)); + const resolved = getComputedStyle(element).color; + cache.set(key, resolved); + return resolved; + }; + + const restore = () => { + for (const [name, value] of previousAttributes) { + if (value === null) { + element.removeAttribute(name); + } else { + element.setAttribute(name, value); + } + } + }; + + return { resolve, restore }; +} + +/** The colors these states compute to, serialized so a theme change can be told from an unrelated one. */ +export function getBarPaletteSnapshot(element: BarStyleElement | null, states: readonly BarState[]) { + if (!element) { + return ''; + } + const barColor = createBarColorResolver(element); + try { + return JSON.stringify(states.map(barColor.resolve)); + } finally { + barColor.restore(); + } +} + +/** How `Chart.ProjectionOutline` strokes, read from its computed style. Without a stroke color, nothing is drawn. */ +type ProjectionOutlineStyle = Readonly<{ color: string; width: number; dash: number[] }>; + +function readProjectionOutlineStyle(element: BarStyleElement | null): ProjectionOutlineStyle | null { + if (!element) { + return null; + } + const style = getComputedStyle(element); + const width = readPixels(style.strokeWidth, 1); + if (!style.stroke || style.stroke === 'none' || style.stroke.startsWith('url(') || width <= 0) { + return null; + } + const dash = + style.strokeDasharray === 'none' + ? [] + : style.strokeDasharray + .split(/[\s,]+/) + .map(value => Number.parseFloat(value)) + .filter(Number.isFinite); + return { color: style.stroke, width, dash }; +} + +/** The outline stroke serialized, so a change to it can be a `useSyncExternalStore` snapshot. */ +export function getProjectionOutlineSnapshot(element: BarStyleElement | null) { + return JSON.stringify(readProjectionOutlineStyle(element)); +} + +/** The gap between the fill and the inside of the outline stroke. */ +const PROJECTION_OUTLINE_GAP = 1; + +/** + * Traces the fill at a constant offset, with concentric top corners and open, square ends on zero. + * The gap and a stroke at least one device pixel wide round to whole device pixels, so both sides + * match and the stroke stays crisp at any pixel ratio. + */ +function strokeProjectionOutline( + context: CanvasRenderingContext2D, + projection: PaintedProjection, + outline: ProjectionOutlineStyle, + pixelRatio: number, +) { + const gap = Math.max(1, Math.round(PROJECTION_OUTLINE_GAP * pixelRatio)) / pixelRatio; + const deviceWidth = outline.width * pixelRatio; + const width = (deviceWidth < 1 ? deviceWidth : Math.round(deviceWidth)) / pixelRatio; + const offset = gap + width / 2; + const left = projection.x - offset; + const right = projection.x + projection.width + offset; + const top = projection.y - offset; + const bottom = projection.y + projection.height; + const radius = projection.radius > 0 ? projection.radius + offset : 0; + context.strokeStyle = outline.color; + context.lineWidth = width; + context.setLineDash(outline.dash); + context.beginPath(); + context.moveTo(left, bottom); + context.arcTo(left, top, right, top, radius); + context.arcTo(right, top, right, bottom, radius); + context.lineTo(right, bottom); + context.stroke(); + context.setLineDash([]); +} + +type PaintOptions = Readonly<{ + canvas: HTMLCanvasElement; + marks: readonly BarMark[]; + projection: PaintedProjection | null; + size: ChartSize; + pixelRatio: number; + isBarActive?: (bar: BarIdentity) => boolean; + /** The `Chart.Bar` element. Without it, nothing is painted. */ + bar: BarStyleElement | null; + /** The `Chart.ProjectionOutline` element, whose stroke outlines the projection. */ + projectionOutline: BarStyleElement | null; +}>; + +export function paintStackedBarCanvas({ + canvas, + marks, + projection, + size, + pixelRatio, + isBarActive, + bar, + projectionOutline, +}: PaintOptions) { + try { + const context = canvas.getContext('2d'); + if (!context || context.isContextLost?.()) { + throw new CanvasRenderError('Canvas 2D context is unavailable', null); + } + + const pixelWidth = Math.round(size.width * pixelRatio); + const pixelHeight = Math.round(size.height * pixelRatio); + if (canvas.width !== pixelWidth) { + canvas.width = pixelWidth; + } + if (canvas.height !== pixelHeight) { + canvas.height = pixelHeight; + } + canvas.style.width = `${size.width}px`; + canvas.style.height = `${size.height}px`; + context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); + context.clearRect(0, 0, size.width, size.height); + + if (!bar) { + return; + } + + const barColor = createBarColorResolver(bar); + try { + if (projection) { + context.fillStyle = barColor.resolve({ projection: true }); + context.beginPath(); + context.roundRect(projection.x, projection.y, projection.width, projection.height, [ + projection.radius, + projection.radius, + 0, + 0, + ]); + context.fill(); + const outline = readProjectionOutlineStyle(projectionOutline); + if (outline) { + strokeProjectionOutline(context, projection, outline, pixelRatio); + } + } + drawCanvasBars({ + context, + marks, + pixelRatio, + height: size.height, + getFill: mark => barColor.resolve({ seriesKey: mark.seriesKey, inactive: isBarActive?.(mark) === false }), + }); + } finally { + barColor.restore(); + } + } catch (cause) { + if (cause instanceof CanvasRenderError) { + throw cause; + } + throw new CanvasRenderError('Canvas 2D rendering failed', cause); + } +} diff --git a/packages/mosaic/src/primitives/chart/bars/bar-context.ts b/packages/mosaic/src/primitives/chart/bars/bar-context.ts new file mode 100644 index 00000000000..f2066c4eedd --- /dev/null +++ b/packages/mosaic/src/primitives/chart/bars/bar-context.ts @@ -0,0 +1,54 @@ +import { createContext, useContext } from 'react'; + +import { ChartContext } from '../chart-context'; +import type { CartesianChartInstance, ChartInstance } from '../types'; +import type { BarStyleElement } from './bar-canvas'; +import type { PreparedStackedBars, StackedBarLayout } from './bar-layout'; +import type { ActiveBar, BarCategory, BarIdentity, BarSelection } from './types'; + +/** Only `useBarChart` sets it, so a chart that carries it came from `useBarChart`. */ +export const BAR_LAYOUT: unique symbol = Symbol('bar layout'); + +/** What the bar marks paint from. Read by the bar parts only. */ +export type BarLayout = Readonly<{ + prepared: PreparedStackedBars; + projection: StackedBarLayout['projection']; + isBarActive: ((bar: BarIdentity) => boolean) | undefined; +}>; + +/** The measured layout and selection of one stacked bar chart, returned by `Chart.useBarChart`. */ +export type BarChartInstance = CartesianChartInstance, BarSelection, BarCategory> & + Readonly<{ [BAR_LAYOUT]: BarLayout }>; + +function isBarChart(chart: ChartInstance): chart is BarChartInstance { + return BAR_LAYOUT in chart; +} + +export function useBarChartContext(part: string) { + const context = useContext(ChartContext); + if (!context) { + throw new Error(` must be used within `); + } + const { chart, ariaLabel } = context; + if (!isBarChart(chart)) { + throw new Error(` needs a chart from Chart.useBarChart`); + } + return { chart, layout: chart[BAR_LAYOUT], ariaLabel }; +} + +export interface BarsContextValue { + /** Registers the `Chart.Bar` element whose computed `color` paints bars. */ + setBar: (element: BarStyleElement | null) => void; + /** Registers the `Chart.ProjectionOutline` element whose computed stroke outlines the projection. */ + setProjectionOutline: (element: BarStyleElement | null) => void; +} + +export const BarsContext = createContext(null); + +export function useBarsContext(part: string) { + const context = useContext(BarsContext); + if (!context) { + throw new Error(` must be used within `); + } + return context; +} diff --git a/packages/mosaic/src/primitives/chart/bars/bar-layout.ts b/packages/mosaic/src/primitives/chart/bars/bar-layout.ts new file mode 100644 index 00000000000..13f6f344486 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/bars/bar-layout.ts @@ -0,0 +1,407 @@ +import { scaleBand, scaleLinear } from 'd3-scale'; +import { stack, stackOffsetDiverging } from 'd3-shape'; + +import type { ChartMargin, ChartSize } from '../types'; +import type { BarCategory, BarMark, BarProjection, BarSeries } from './types'; + +const Y_TICK_COUNT = 5; + +type PrepareOptions = Readonly<{ + data: readonly TDatum[]; + series: readonly BarSeries[]; + index: (datum: TDatum, index: number) => string; +}>; + +type PreparedPoint = Readonly<{ + seriesKey: string; + datum: TDatum; + datumIndex: number; + value: number; + start: number; + end: number; + positive: boolean; + hasNeighbour: boolean; + zeroAdjacent: boolean; +}>; + +export type PreparedStackedBars = Readonly<{ + indexes: readonly string[]; + points: readonly PreparedPoint[]; + domain: readonly [number, number]; +}>; + +type ProjectOptions = Readonly<{ + size: ChartSize; + margin: ChartMargin; + categoryGap: number; + projection?: BarProjection; +}>; + +/** Bar geometry read from `Chart.Bar`'s computed style. */ +export type BarGeometry = Readonly<{ + maxWidth: number; + gap: number; + outerRadius: number; + radius: number; +}>; + +export const UNSTYLED_BAR_GEOMETRY: BarGeometry = { + maxWidth: Infinity, + gap: 0, + outerRadius: 0, + radius: 0, +}; + +function readValue(series: BarSeries | undefined, datum: TDatum) { + const value = series?.value(datum); + return typeof value === 'number' && Number.isFinite(value) ? value : 0; +} + +export function prepareStackedBars({ + data, + series, + index, +}: PrepareOptions): PreparedStackedBars { + const indexes = data.map(index); + const seriesByKey = new Map(series.map(item => [item.key, item])); + const stackGenerator = stack() + .keys(series.map(item => item.key)) + .value((datum, key) => readValue(seriesByKey.get(key), datum)) + .offset(stackOffsetDiverging); + const points: PreparedPoint[] = []; + let domainMin = 0; + let domainMax = 0; + + for (const layer of stackGenerator(data)) { + const definition = seriesByKey.get(layer.key); + if (!definition) { + continue; + } + layer.forEach((point, datumIndex) => { + // D3 represents each stacked value as a cumulative [start, end] tuple. The diverging offset + // grows positive tuples above zero and negative tuples below zero. + domainMin = Math.min(domainMin, point[0], point[1]); + domainMax = Math.max(domainMax, point[0], point[1]); + const datum = point.data; + const value = readValue(definition, datum); + if (value === 0) { + return; + } + const positive = value > 0; + points.push({ + seriesKey: layer.key, + datum, + datumIndex, + value, + start: point[0], + end: point[1], + positive, + hasNeighbour: positive ? point[0] > 0 : point[1] < 0, + zeroAdjacent: positive ? point[0] === 0 : point[1] === 0, + }); + }); + } + + return { indexes, points, domain: [domainMin, domainMax] }; +} + +function createStackedBarScales({ + indexes, + preparedDomain, + size, + margin, + categoryGap, + projection, +}: Readonly<{ + indexes: readonly string[]; + preparedDomain: readonly [number, number]; + size: ChartSize; + margin: ChartMargin; + categoryGap: number; + projection?: BarProjection; +}>) { + const innerWidth = Math.max(0, size.width - margin.left - margin.right); + const innerHeight = Math.max(0, size.height - margin.top - margin.bottom); + const x = scaleBand() + .domain(indexes) + .range([margin.left, margin.left + innerWidth]) + .paddingInner(Math.min(0.95, Math.max(0, categoryGap))) + .paddingOuter(Math.min(0.5, Math.max(0, categoryGap / 2))); + const domain: [number, number] = [ + Math.min(0, preparedDomain[0]), + Math.max(0, preparedDomain[1], projection?.value ?? 0), + ]; + if (domain[0] === domain[1]) { + domain[1] = domain[0] + 1; + } + const y = scaleLinear() + .domain(domain) + .range([margin.top + innerHeight, margin.top]) + .nice(Y_TICK_COUNT); + + return { x, y, innerWidth, innerHeight }; +} + +type StackedBarScales = ReturnType; + +type DraftBarMark = Omit, 'paintInsetTop' | 'paintInsetBottom'> & { + paintInsetTop: number; + paintInsetBottom: number; +}; + +function splitNeighbourGap(previous: DraftBarMark, mark: DraftBarMark, gap: number) { + const half = Math.max(0, Math.min(gap, (mark.height - 1) * 2, (previous.height - 1) * 2)) / 2; + if (mark.positive) { + previous.paintInsetTop += half; + mark.paintInsetBottom += half; + } else { + previous.paintInsetBottom += half; + mark.paintInsetTop += half; + } +} + +/** Bars at least this wide snap their sides to whole device pixels; narrower bars would lose too much width. */ +const MIN_SNAPPED_WIDTH = 2; + +/** Rounds a CSS length to whole device pixels, which are fractional CSS pixels at a ratio such as 1.25. */ +export function snapToDevicePixels(value: number, pixelRatio: number) { + return Math.round(value * pixelRatio) / pixelRatio; +} + +/** + * Centers a bar of at most `maxWidth` in its category band. Snapping keeps the sides of the bars, the + * projection and its outline on the same whole device pixels, so they paint crisp and line up. + */ +function fitBarToBand(band: Readonly<{ x: number; width: number }>, maxWidth: number, pixelRatio: number) { + const width = Math.min(band.width, maxWidth); + const x = band.x + (band.width - width) / 2; + if (width < MIN_SNAPPED_WIDTH) { + return { x, width }; + } + const left = snapToDevicePixels(x, pixelRatio); + return { x: left, width: snapToDevicePixels(x + width, pixelRatio) - left }; +} + +function projectMarksAndPaintInsets( + layout: MarkSource, + { maxWidth, gap }: BarGeometry, + pixelRatio: number, +) { + const { categories, scaleY } = layout; + const marks: DraftBarMark[] = []; + const previousMarkByStack = new Map>(); + + // Gap insets affect paint only, so stack endpoints stay on the Y scale. Internal neighbours split + // the gap; marks beside zero take the full clearance. + for (const point of layout.prepared.points) { + const category = categories[point.datumIndex]; + if (category === undefined) { + continue; + } + const rawTop = Math.min(scaleY(point.start), scaleY(point.end)); + const rawBottom = Math.max(scaleY(point.start), scaleY(point.end)); + const height = Math.max(0, rawBottom - rawTop); + const fitted = fitBarToBand(category, maxWidth, pixelRatio); + const stackKey = `${point.datumIndex}:${point.positive}`; + const previousMark = previousMarkByStack.get(stackKey); + const mark: DraftBarMark = { + seriesKey: point.seriesKey, + datum: point.datum, + datumIndex: point.datumIndex, + value: point.value, + x: fitted.x, + y: rawTop, + width: fitted.width, + height, + radii: [0, 0, 0, 0], + positive: point.positive, + paintInsetTop: !point.positive && point.zeroAdjacent ? gap : 0, + paintInsetBottom: point.positive && point.zeroAdjacent ? gap : 0, + }; + if (point.hasNeighbour && gap > 0 && previousMark !== undefined) { + splitNeighbourGap(previousMark, mark, gap); + } + previousMarkByStack.set(stackKey, mark); + marks.push(mark); + } + + return marks; +} + +function applyCornerRadii(marks: readonly BarMark[], { outerRadius, radius }: BarGeometry) { + const topByDatum = new Map(); + const bottomByDatum = new Map(); + for (const mark of marks) { + if (mark.positive) { + topByDatum.set(mark.datumIndex, Math.min(topByDatum.get(mark.datumIndex) ?? Infinity, mark.y)); + } else { + bottomByDatum.set( + mark.datumIndex, + Math.max(bottomByDatum.get(mark.datumIndex) ?? -Infinity, mark.y + mark.height), + ); + } + } + + return marks.map(mark => { + const isOuter = mark.positive + ? mark.y === topByDatum.get(mark.datumIndex) + : mark.y + mark.height === bottomByDatum.get(mark.datumIndex); + const outer = Math.min(outerRadius, mark.width / 2, mark.height / 2); + const inner = Math.min(radius, mark.width / 2, mark.height / 2); + const radii: BarMark['radii'] = !isOuter + ? [inner, inner, inner, inner] + : mark.positive + ? [outer, outer, inner, inner] + : [inner, inner, outer, outer]; + return { ...mark, radii }; + }); +} + +function projectOptionalProjection( + indexes: readonly string[], + projection: BarProjection | undefined, + { x, y }: StackedBarScales, +) { + if (!projection) { + return null; + } + const categoryX = x(indexes[projection.datumIndex] ?? ''); + if (categoryX === undefined) { + return null; + } + const top = y(projection.value); + return { + datumIndex: projection.datumIndex, + x: categoryX, + y: top, + width: x.bandwidth(), + height: Math.max(0, y(0) - top), + }; +} + +function acceptProjection( + projection: BarProjection | undefined, + { indexes, points }: PreparedStackedBars, +): BarProjection | undefined { + if ( + !projection || + !Number.isInteger(projection.datumIndex) || + projection.datumIndex < 0 || + projection.datumIndex >= indexes.length || + !Number.isFinite(projection.value) + ) { + return undefined; + } + const stackTop = points.reduce( + (top, point) => (point.positive && point.datumIndex === projection.datumIndex ? Math.max(top, point.end) : top), + 0, + ); + return projection.value > stackTop ? projection : undefined; +} + +function projectCategories( + { indexes, points }: PreparedStackedBars, + projection: ReturnType, + { x }: StackedBarScales, +): BarCategory[] { + const positive = new Set(); + const negative = new Set(); + for (const point of points) { + (point.positive ? positive : negative).add(point.datumIndex); + } + const projected = projection && projection.width > 0 && projection.height > 0 ? projection.datumIndex : undefined; + return indexes.map((key, datumIndex) => { + const bandX = x(key) ?? 0; + return { + key, + datumIndex, + x: bandX, + width: x.bandwidth(), + center: bandX + x.bandwidth() / 2, + sections: { + positive: positive.has(datumIndex) || projected === datumIndex, + negative: negative.has(datumIndex), + }, + hasValues: { + positive: positive.has(datumIndex), + negative: negative.has(datumIndex), + }, + projected: projected === datumIndex, + }; + }); +} + +/** + * Projects scales, categories, ticks and the projection bar for a measured frame. Bar marks are + * projected separately by `projectStackedBarMarks`, because their width, gaps and radii come from + * CSS and must not move the scales or the category bands that selection uses. + */ +export function projectStackedBars( + prepared: PreparedStackedBars, + { size, margin, categoryGap, projection }: ProjectOptions, +) { + const acceptedProjection = acceptProjection(projection, prepared); + const scales = createStackedBarScales({ + indexes: prepared.indexes, + preparedDomain: prepared.domain, + size, + margin, + categoryGap, + projection: acceptedProjection, + }); + const { y, innerWidth, innerHeight } = scales; + const projectedBar = projectOptionalProjection(prepared.indexes, acceptedProjection, scales); + + return { + prepared, + scaleY: (value: number) => y(value), + categories: projectCategories(prepared, projectedBar, scales), + zeroY: y(0), + yTicks: y.ticks(Y_TICK_COUNT).map(value => ({ value, y: y(value) })), + plot: { + x: margin.left, + y: margin.top, + width: innerWidth, + height: innerHeight, + }, + projection: projectedBar, + }; +} + +export type StackedBarLayout = ReturnType>; + +type MarkSource = Pick, 'prepared' | 'scaleY'> & + Readonly<{ categories: readonly BarCategory[] }>; + +export function projectStackedBarMarks( + layout: MarkSource, + geometry: BarGeometry, + pixelRatio: number, +): BarMark[] { + return applyCornerRadii(projectMarksAndPaintInsets(layout, geometry, pixelRatio), geometry); +} + +/** The projection fill as the Canvas paints it: `radius` rounds the top corners, and the bottom is square on zero. */ +export type PaintedProjection = NonNullable['projection']> & Readonly<{ radius: number }>; + +export function fitProjectionToBar( + projection: StackedBarLayout['projection'], + { maxWidth, outerRadius }: BarGeometry, + pixelRatio: number, +): PaintedProjection | null { + if (!projection) { + return null; + } + const { x, width } = fitBarToBand(projection, maxWidth, pixelRatio); + const bottom = projection.y + projection.height; + const y = Math.min(snapToDevicePixels(projection.y, pixelRatio), bottom); + const height = bottom - y; + return { + ...projection, + x, + y, + width, + height, + radius: Math.min(outerRadius, width / 2, height), + }; +} diff --git a/packages/mosaic/src/primitives/chart/bars/bar-selection.ts b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts new file mode 100644 index 00000000000..5c965223d6a --- /dev/null +++ b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts @@ -0,0 +1,109 @@ +import { nearestCategory, type SelectionModel } from '../internal/selection'; +import type { ChartMessages } from '../types'; +import type { StackedBarLayout } from './bar-layout'; +import type { + ActiveBar, + BarCategory, + BarChartMessages, + BarProjection, + BarSection, + BarSelection, + BarSeries, +} from './types'; + +export const DEFAULT_BAR_MESSAGES = { + vertical: 'Use Up and Down to choose positive or negative values.', + positiveValues: 'positive values', + negativeValues: 'negative values', + projected: 'Projected', +} as const satisfies Omit; + +type BarSelectionOptions = Readonly<{ + layout: Pick, 'plot' | 'zeroY' | 'categories' | 'prepared'>; + data: readonly TDatum[]; + series: readonly BarSeries[]; + projection: BarProjection | undefined; + formatValue: (value: number) => string; + messages: Pick; +}>; + +/** + * Selects a section of a stacked bar: above the zero line or below it. 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. + */ +export function barSelectionModel({ + layout, + data, + series, + projection, + formatValue, + messages, +}: BarSelectionOptions): SelectionModel, BarCategory> { + const labels = new Map(series.map(item => [item.key, item.label ?? item.key])); + const twoSided = layout.categories.some(category => category.hasValues.negative); + const nearZero = Math.max(4, Math.round(layout.plot.height * 0.015)); + + return { + hitTest: ({ x, y }, current) => { + const category = layout.categories[nearestCategory(layout.categories, x)]; + if (!category) { + return null; + } + const { positive, negative } = category.sections; + if (!positive && !negative) { + return null; + } + const section: BarSection = !negative + ? 'positive' + : !positive + ? 'negative' + : Math.abs(y - layout.zeroY) <= nearZero + ? (current?.section ?? 'positive') + : y < layout.zeroY + ? 'positive' + : 'negative'; + return { category: category.key, section }; + }, + land: (category, move, current) => { + const wanted = move === 'up' ? 'positive' : move === 'down' ? 'negative' : current?.section; + const section = + wanted && category.sections[wanted] + ? wanted + : category.sections.positive + ? 'positive' + : category.sections.negative + ? 'negative' + : null; + return section ? { category: category.key, section } : null; + }, + resolve: (selection, category) => { + const datum = data[category.datumIndex]; + if (!category.sections[selection.section] || datum === undefined) { + return null; + } + return { + category: category.key, + section: selection.section, + datumIndex: category.datumIndex, + datum, + hasValues: category.hasValues, + projected: category.projected, + }; + }, + describe: active => { + const positive = active.section === 'positive'; + const values = layout.prepared.points + .filter(point => point.datumIndex === active.datumIndex && point.positive === positive) + .map(point => `${labels.get(point.seriesKey) ?? point.seriesKey} ${formatValue(point.value)}`); + if (positive && active.projected && projection) { + values.push(`${projection.label ?? messages.projected} ${formatValue(projection.value)}`); + } + const section = twoSided ? (positive ? messages.positiveValues : messages.negativeValues) : ''; + return [section, ...values].filter(Boolean).join(', '); + }, + verticalInstructions: twoSided ? messages.vertical : '', + anchor: (_, category) => ({ x: category.center, y: layout.plot.y }), + surfaceAttributes: selection => ({ 'data-active-section': selection?.section }), + }; +} diff --git a/packages/mosaic/src/primitives/chart/bars/chart-bar.tsx b/packages/mosaic/src/primitives/chart/bars/chart-bar.tsx new file mode 100644 index 00000000000..1c7f0c65ef9 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/bars/chart-bar.tsx @@ -0,0 +1,30 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../../utils'; +import { useBarsContext } from './bar-context'; + +export type ChartBarProps = ComponentProps<'g'>; + +/** + * Styles the bars that `Chart.Bars` paints on Canvas. Before each paint the primitive puts + * this hidden element in every state it draws, through `data-series`, `data-inactive` and + * `data-projection`, and paints with the element's computed `color`. + */ +export const ChartBar = React.forwardRef(function ChartBar(props, ref) { + const { render, ...otherProps } = props; + const { setBar } = useBarsContext('Bar'); + + const ownProps = { + 'aria-hidden': true, + style: { display: 'none' }, + } satisfies DefaultProps<'g'>; + + return useRender({ + defaultTagName: 'g', + render, + ref: [setBar, ref], + props: mergeProps<'g'>(ownProps, otherProps), + }); +}); diff --git a/packages/mosaic/src/primitives/chart/bars/chart-bars.tsx b/packages/mosaic/src/primitives/chart/bars/chart-bars.tsx new file mode 100644 index 00000000000..994a78a3cff --- /dev/null +++ b/packages/mosaic/src/primitives/chart/bars/chart-bars.tsx @@ -0,0 +1,195 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../../utils'; +import { hasArea } from '../chart-context'; +import { + type BarState, + type BarStyleElement, + getBarGeometrySnapshot, + getBarPaletteSnapshot, + getProjectionOutlineSnapshot, + paintStackedBarCanvas, + parseBarGeometry, +} from './bar-canvas'; +import { CanvasRenderError } from './bar-canvas-error'; +import { BarsContext, useBarChartContext } from './bar-context'; +import { fitProjectionToBar, projectStackedBarMarks } from './bar-layout'; + +export type ChartBarsProps = ComponentProps<'div'>; + +function subscribeToPixelRatio(callback: () => void) { + let query = window.matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`); + const onChange = () => { + query.removeEventListener('change', onChange); + query = window.matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`); + query.addEventListener('change', onChange); + callback(); + }; + query.addEventListener('change', onChange); + return () => query.removeEventListener('change', onChange); +} + +function getPixelRatio() { + return Math.min(window.devicePixelRatio || 1, 2); +} + +const PREFERS_DARK = '(prefers-color-scheme: dark)'; + +/** A theme can switch through any attribute on an ancestor; the palette snapshot ignores the rest. */ +function subscribeToTheme(bar: Element | null, onChange: () => void) { + if (!bar) { + return () => {}; + } + const observer = new MutationObserver(onChange); + for (let element = bar.parentElement; element; element = element.parentElement) { + observer.observe(element, { attributes: true }); + } + const query = window.matchMedia(PREFERS_DARK); + query.addEventListener('change', onChange); + return () => { + observer.disconnect(); + query.removeEventListener('change', onChange); + }; +} + +/** The outline repaints on a class change and on a theme change, like the bars. */ +function subscribeToPartStyle(element: Element | null, onChange: () => void) { + if (!element) { + return () => {}; + } + const observer = new MutationObserver(onChange); + observer.observe(element, { attributes: true, attributeFilter: ['class'] }); + const unsubscribeFromTheme = subscribeToTheme(element, onChange); + return () => { + observer.disconnect(); + unsubscribeFromTheme(); + }; +} + +const getServerSnapshot = () => ''; +const getServerPixelRatio = () => 1; + +export const ChartBars = React.forwardRef(function ChartBars(props, ref) { + const { children, render, ...otherProps } = props; + const { chart, layout, ariaLabel } = useBarChartContext('Bars'); + const { size, categories, scaleY } = chart; + const { prepared, isBarActive, projection: projectedBar } = layout; + const pixelRatio = React.useSyncExternalStore(subscribeToPixelRatio, getPixelRatio, getServerPixelRatio); + const [canvas, setCanvas] = React.useState(null); + const [canvasError, setCanvasError] = React.useState(null); + const [bar, setBar] = React.useState(null); + const [projectionOutline, setProjectionOutline] = React.useState(null); + const subscribeToBarClass = React.useCallback( + (onChange: () => void) => { + if (!bar) { + return () => {}; + } + const observer = new MutationObserver(onChange); + observer.observe(bar, { attributes: true, attributeFilter: ['class'] }); + return () => observer.disconnect(); + }, + [bar], + ); + const barClass = React.useSyncExternalStore( + subscribeToBarClass, + () => bar?.getAttribute('class') ?? '', + getServerSnapshot, + ); + const barGeometry = React.useSyncExternalStore( + subscribeToBarClass, + () => getBarGeometrySnapshot(bar), + getServerSnapshot, + ); + const geometry = React.useMemo(() => parseBarGeometry(barGeometry), [barGeometry]); + const marks = React.useMemo( + () => projectStackedBarMarks({ prepared, categories, scaleY }, geometry, pixelRatio), + [categories, geometry, pixelRatio, prepared, scaleY], + ); + const projection = React.useMemo( + () => fitProjectionToBar(projectedBar, geometry, pixelRatio), + [geometry, pixelRatio, projectedBar], + ); + const paletteStates = React.useMemo(() => { + const states: BarState[] = projection ? [{ projection: true }] : []; + for (const seriesKey of new Set(marks.map(mark => mark.seriesKey))) { + states.push({ seriesKey }); + if (isBarActive) { + states.push({ seriesKey, inactive: true }); + } + } + return states; + }, [isBarActive, marks, projection]); + const palette = React.useSyncExternalStore( + React.useCallback((onChange: () => void) => subscribeToTheme(bar, onChange), [bar]), + () => getBarPaletteSnapshot(bar, paletteStates), + getServerSnapshot, + ); + const outlineStyle = React.useSyncExternalStore( + React.useCallback((onChange: () => void) => subscribeToPartStyle(projectionOutline, onChange), [projectionOutline]), + () => getProjectionOutlineSnapshot(projectionOutline), + getServerSnapshot, + ); + const barsContext = React.useMemo(() => ({ setBar, setProjectionOutline }), []); + + React.useLayoutEffect(() => { + if (!canvas || !hasArea(size)) { + return; + } + paintStackedBarCanvas({ canvas, marks, projection, size, pixelRatio, isBarActive, bar, projectionOutline }); + const onContextLost = () => { + setCanvasError(new CanvasRenderError('Canvas 2D context was lost', null)); + }; + canvas.addEventListener('contextlost', onContextLost); + return () => canvas.removeEventListener('contextlost', onContextLost); + // `barClass`, `palette` and `outlineStyle` are not read here: they change the computed styles the paint reads from the DOM. + }, [ + bar, + barClass, + canvas, + isBarActive, + marks, + outlineStyle, + palette, + pixelRatio, + projection, + projectionOutline, + size, + ]); + + const ownProps = { + style: { position: 'absolute', inset: 0 }, + children: ( + <> + + + + ), + } satisfies DefaultProps<'div'>; + + const element = useRender({ + defaultTagName: 'div', + render, + ref, + enabled: hasArea(size), + props: mergeProps<'div'>(ownProps, otherProps), + }); + + if (canvasError) { + throw canvasError; + } + return element; +}); diff --git a/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx b/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx new file mode 100644 index 00000000000..97ddcd8acfe --- /dev/null +++ b/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx @@ -0,0 +1,32 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../../utils'; +import { useBarsContext } from './bar-context'; + +export type ChartProjectionOutlineProps = ComponentProps<'g'>; + +/** + * Styles the outline that `Chart.Bars` paints around the projection on Canvas, in the same + * pass as the fill, so the two stay aligned at any pixel ratio. The Canvas reads this hidden + * element's computed `stroke`, `stroke-width` and `stroke-dasharray`. + */ +export const ChartProjectionOutline = React.forwardRef( + function ChartProjectionOutline(props, ref) { + const { render, ...otherProps } = props; + const { setProjectionOutline } = useBarsContext('ProjectionOutline'); + + const ownProps = { + 'aria-hidden': true, + style: { display: 'none' }, + } satisfies DefaultProps<'g'>; + + return useRender({ + defaultTagName: 'g', + render, + ref: [setProjectionOutline, ref], + props: mergeProps<'g'>(ownProps, otherProps), + }); + }, +); diff --git a/packages/mosaic/src/primitives/chart/bars/types.ts b/packages/mosaic/src/primitives/chart/bars/types.ts new file mode 100644 index 00000000000..bbb737f5e34 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/bars/types.ts @@ -0,0 +1,73 @@ +import type { ChartActive, ChartCategory, ChartMessages, ChartSelection } from '../types'; + +export type CornerRadii = readonly [number, number, number, number]; + +/** A projected total for one category, drawn only above its positive stack. */ +export type BarProjection = Readonly<{ + datumIndex: number; + value: number; + /** Names the projection in announcements. Default: `messages.projected` */ + label?: string; +}>; + +export type BarSeries = Readonly<{ + key: string; + /** Names the series in announcements. Default: `key` */ + label?: string; + value: (datum: TDatum) => number | null | undefined; +}>; + +export type BarIdentity = Readonly<{ + seriesKey: string; + datum: TDatum; + datumIndex: number; + value: number; + positive: boolean; +}>; + +export type BarMark = BarIdentity & + Readonly<{ + x: number; + y: number; + width: number; + height: number; + radii: CornerRadii; + paintInsetTop: number; + paintInsetBottom: number; + }>; + +export type BarSection = 'positive' | 'negative'; + +/** Screen reader text for a bar chart: the shared chart text plus the Up and Down sections. */ +export type BarChartMessages = ChartMessages & + Readonly<{ + /** How Up and Down move between the positive and negative sections. */ + vertical: string; + /** Follows the period name when the positive section is selected. */ + positiveValues: string; + /** Follows the period name when the negative section is selected. */ + negativeValues: string; + /** Names the projection in announcements when it has no `label`. */ + projected: string; + }>; + +export type BarCategory = ChartCategory & + Readonly<{ + /** Sections a user can select, including a projection-only positive bar. */ + sections: Readonly>; + /** Sections with nonzero data values. */ + hasValues: Readonly>; + /** True when the chart draws the projection at this category. */ + projected: boolean; + }>; + +/** A selected category and section. */ +export type BarSelection = ChartSelection & Readonly<{ section: BarSection }>; + +/** A selected bar resolved against the current data. */ +export type ActiveBar = ChartActive & + BarSelection & + Readonly<{ + hasValues: BarCategory['hasValues']; + projected: BarCategory['projected']; + }>; diff --git a/packages/mosaic/src/primitives/chart/bars/use-bar-chart.ts b/packages/mosaic/src/primitives/chart/bars/use-bar-chart.ts new file mode 100644 index 00000000000..c2560a6920f --- /dev/null +++ b/packages/mosaic/src/primitives/chart/bars/use-bar-chart.ts @@ -0,0 +1,97 @@ +'use client'; + +import React from 'react'; + +import { useChartFrame, useChartInstance } from '../internal/use-chart-instance'; +import type { ChartOptions } from '../types'; +import { BAR_LAYOUT, type BarChartInstance } from './bar-context'; +import { prepareStackedBars, projectStackedBars } from './bar-layout'; +import { barSelectionModel, DEFAULT_BAR_MESSAGES } from './bar-selection'; +import type { ActiveBar, BarChartMessages, BarIdentity, BarProjection, BarSelection, BarSeries } from './types'; + +export interface UseBarChartOptions extends ChartOptions> { + data: readonly TDatum[]; + /** Stack order and each series' value. Memoize it: a new array prepares the stacks again. */ + series: readonly BarSeries[]; + /** Returns a unique, stable category key. Memoize it: a new function prepares the stacks again. */ + index: (datum: TDatum, index: number) => string; + /** Fraction of each category band left empty between bars. Default: 0.28 */ + categoryGap?: number; + /** Paints a projected total behind the bar at `datumIndex`, when it rises above the bar. */ + projection?: BarProjection; + /** Returns false for a bar that `Chart.Bar` styles through `data-inactive`. Default: every bar is active */ + isBarActive?: (bar: BarIdentity) => boolean; + /** Screen reader text, including how Up and Down move between sections. Default: English */ + messages?: Partial; +} + +/** + * Measures, lays out and selects a stacked bar chart. Pass the result to `Chart.Root`, or render + * from it directly. + */ +export function useBarChart(options: UseBarChartOptions): BarChartInstance { + const { data, series, index, categoryGap = 0.28, projection, isBarActive } = options; + + const frame = useChartFrame(options.margin); + const { size, margin } = frame; + // The owner re-renders on every selection change, so an inline `projection` must not relayout. + const projectionIndex = projection?.datumIndex; + const projectionValue = projection?.value; + const prepared = React.useMemo(() => prepareStackedBars({ data, series, index }), [data, index, series]); + const layout = React.useMemo( + () => + projectStackedBars(prepared, { + size, + margin, + categoryGap, + projection: + projectionIndex === undefined || projectionValue === undefined + ? undefined + : { datumIndex: projectionIndex, value: projectionValue }, + }), + [categoryGap, margin, prepared, projectionIndex, projectionValue, size], + ); + const { + vertical = DEFAULT_BAR_MESSAGES.vertical, + positiveValues = DEFAULT_BAR_MESSAGES.positiveValues, + negativeValues = DEFAULT_BAR_MESSAGES.negativeValues, + projected = DEFAULT_BAR_MESSAGES.projected, + } = options.messages ?? {}; + const projectionLabel = projection?.label; + const { formatValue = String } = options; + const model = React.useMemo( + () => + barSelectionModel({ + layout, + data, + series, + projection: + projectionIndex === undefined || projectionValue === undefined + ? undefined + : { datumIndex: projectionIndex, value: projectionValue, label: projectionLabel }, + formatValue, + messages: { vertical, positiveValues, negativeValues, projected }, + }), + [ + data, + formatValue, + layout, + negativeValues, + positiveValues, + projectionIndex, + projectionLabel, + projectionValue, + projected, + series, + vertical, + ], + ); + const instance = useChartInstance({ frame, layout, model, options }); + + return { + ...instance, + scaleY: layout.scaleY, + yTicks: layout.yTicks, + [BAR_LAYOUT]: { prepared, projection: layout.projection, isBarActive }, + }; +} diff --git a/packages/mosaic/src/primitives/chart/chart-context.ts b/packages/mosaic/src/primitives/chart/chart-context.ts new file mode 100644 index 00000000000..74de6411915 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart-context.ts @@ -0,0 +1,54 @@ +import { createContext, type RefObject, useContext } from 'react'; + +import type { CartesianChartInstance, ChartInstance, ChartSize } from './types'; + +export interface ChartContextValue { + chart: ChartInstance; + ariaLabel: string; + /** Marks the chart interactive while the returned cleanup has not run. */ + registerInteraction: () => () => void; +} + +export const ChartContext = createContext(null); + +export function useChartContext(part: string) { + const context = useContext(ChartContext); + if (!context) { + throw new Error(` must be used within `); + } + return context; +} + +function hasValueAxis(chart: ChartInstance): chart is CartesianChartInstance { + return 'scaleY' in chart; +} + +/** The chart of a part that draws against the value axis, such as `Chart.YAxis`. */ +export function useCartesianChart(part: string) { + const { chart } = useChartContext(part); + if (!hasValueAxis(chart)) { + throw new Error(` needs a chart with a value axis, such as one from Chart.useBarChart`); + } + return chart; +} + +export function hasArea(size: ChartSize) { + return size.width > 0 && size.height > 0; +} + +export interface SelectionContextValue { + /** Spans the whole chart, so its client rect anchors the tooltip. */ + chartBoxRef: RefObject; + /** Makes the surface focusable while the returned cleanup has not run. */ + registerTooltip: () => () => void; +} + +export const SelectionContext = createContext(null); + +export function useSelectionContext(part: string) { + const context = useContext(SelectionContext); + if (!context) { + throw new Error(` must be used within `); + } + return context; +} diff --git a/packages/mosaic/src/primitives/chart/chart-cursor.tsx b/packages/mosaic/src/primitives/chart/chart-cursor.tsx new file mode 100644 index 00000000000..41e66431350 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart-cursor.tsx @@ -0,0 +1,38 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { useChartContext, useSelectionContext } from './chart-context'; + +export type ChartCursorProps = ComponentProps<'div'>; + +export const ChartCursor = React.forwardRef(function ChartCursor(props, ref) { + const { render, ...otherProps } = props; + useSelectionContext('Cursor'); + const { chart } = useChartContext('Cursor'); + const { plot, selected } = chart; + const selectedCategory = selected ? chart.categories[selected.datumIndex] : undefined; + + const ownProps = { + 'aria-hidden': 'true', + style: selectedCategory + ? { + position: 'absolute', + top: 0, + bottom: 0, + left: selectedCategory.x - plot.x, + width: selectedCategory.width, + pointerEvents: 'none', + } + : undefined, + } satisfies DefaultProps<'div'>; + + return useRender({ + defaultTagName: 'div', + render, + ref, + enabled: !!selectedCategory, + props: mergeProps<'div'>(ownProps, otherProps), + }); +}); diff --git a/packages/mosaic/src/primitives/chart/chart-grid.tsx b/packages/mosaic/src/primitives/chart/chart-grid.tsx new file mode 100644 index 00000000000..66d5b226c6e --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart-grid.tsx @@ -0,0 +1,34 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { hasArea, useCartesianChart } from './chart-context'; +import type { ChartTick } from './types'; + +export type ChartGridProps = Omit, 'children'> & { + /** Renders the lines, usually one `Chart.YLine` per tick value. */ + children?: (ticks: readonly ChartTick[]) => React.ReactNode; +}; + +export const ChartGrid = React.forwardRef(function ChartGrid(props, ref) { + const { children, render, ...otherProps } = props; + const chart = useCartesianChart('Grid'); + const { size, yTicks } = chart; + + const ownProps = { + width: size.width, + height: size.height, + 'aria-hidden': 'true', + style: { position: 'absolute', inset: 0, display: 'block', pointerEvents: 'none' }, + children: children?.(yTicks), + } satisfies DefaultProps<'svg'>; + + return useRender({ + defaultTagName: 'svg', + render, + ref, + enabled: hasArea(size), + props: mergeProps<'svg'>(ownProps, otherProps), + }); +}); diff --git a/packages/mosaic/src/primitives/chart/chart-root.tsx b/packages/mosaic/src/primitives/chart/chart-root.tsx new file mode 100644 index 00000000000..f1f5deca1aa --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart-root.tsx @@ -0,0 +1,58 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { ChartContext, type ChartContextValue } from './chart-context'; +import type { ChartInstance } from './types'; + +export type ChartRootProps = Omit, 'aria-label'> & { + /** The result of a chart-type hook, such as `Chart.useBarChart`. */ + chart: ChartInstance; + /** Default: 500 */ + height?: number | string; + /** Labels the chart image and the interaction surface. */ + 'aria-label': string; +}; + +type InteractionMode = 'pending' | 'interactive' | 'visual-only'; + +export const ChartRoot = React.forwardRef(function ChartRoot(props, ref) { + const { chart, height = 500, 'aria-label': ariaLabel, render, children, ...otherProps } = props; + + const [interactionLayers, setInteractionLayers] = React.useState(0); + const registerInteraction = React.useCallback(() => { + setInteractionLayers(count => count + 1); + return () => setInteractionLayers(count => count - 1); + }, []); + + const context = React.useMemo( + () => ({ chart, ariaLabel, registerInteraction }), + [chart, ariaLabel, registerInteraction], + ); + + const interactionMode: InteractionMode = + chart.size.width <= 0 + ? 'pending' + : interactionLayers > 0 && chart.categories.length > 0 + ? 'interactive' + : 'visual-only'; + + const ownProps = { + style: { position: 'relative', minWidth: 0, overflow: 'hidden', height }, + children, + } satisfies DefaultProps<'div'>; + + const element = useRender({ + defaultTagName: 'div', + render, + ref: [chart.rootRef, ref], + state: { interactionMode }, + stateAttributesMapping: { + interactionMode: (mode: InteractionMode) => ({ 'data-chart-interaction-mode': mode }), + }, + props: mergeProps<'div'>(ownProps, otherProps), + }); + + return {element}; +}); diff --git a/packages/mosaic/src/primitives/chart/chart-selection.tsx b/packages/mosaic/src/primitives/chart/chart-selection.tsx new file mode 100644 index 00000000000..255adf80d6c --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart-selection.tsx @@ -0,0 +1,124 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { hasArea, SelectionContext, type SelectionContextValue, useChartContext } from './chart-context'; +import type { ChartInstance } from './types'; + +const VISUALLY_HIDDEN_STYLE: React.CSSProperties = { + position: 'absolute', + width: 1, + height: 1, + margin: -1, + padding: 0, + overflow: 'hidden', + clipPath: 'inset(50%)', + whiteSpace: 'nowrap', + border: 0, +}; + +export type ChartSelectionProps = ComponentProps<'div'>; + +function KeyboardInstructions({ + id, + instructions, + announcement, +}: Readonly<{ id: string; instructions: string; announcement: string }>) { + return ( + <> + + {instructions} + + + {announcement} + + + ); +} + +export const ChartSelection = React.forwardRef( + function ChartSelection(props, ref) { + const { chart, ariaLabel, registerInteraction } = useChartContext('Selection'); + React.useLayoutEffect(registerInteraction, [registerInteraction]); + if (!hasArea(chart.size) || chart.categories.length === 0) { + return null; + } + return ( + + ); + }, +); + +type SurfaceProps = ChartSelectionProps & { + forwardedRef: React.ForwardedRef; + chart: ChartInstance; + ariaLabel: string; +}; + +function SelectionSurface({ forwardedRef, chart, ariaLabel, children, render, ...otherProps }: SurfaceProps) { + const chartBoxRef = React.useRef(null); + const keyboardInstructionsId = React.useId(); + const [tooltipCount, setTooltipCount] = React.useState(0); + const registerTooltip = React.useCallback(() => { + setTooltipCount(count => count + 1); + return () => setTooltipCount(count => count - 1); + }, []); + const selectionContext = React.useMemo( + () => ({ chartBoxRef, registerTooltip }), + [registerTooltip], + ); + + const interaction = chart.getInteractionProps(); + const focusable = !interaction['aria-disabled'] && (interaction.tabIndex === 0 || tooltipCount > 0); + const surfaceProps = { ...interaction, tabIndex: focusable ? 0 : undefined }; + const { plot } = chart; + + const ownProps = { + style: { position: 'absolute', inset: 0, pointerEvents: 'none' }, + children: ( + <> +
+ {children} +
+ + + ), + } satisfies DefaultProps<'div'>; + + const element = useRender({ + defaultTagName: 'div', + render, + ref: [chartBoxRef, forwardedRef], + props: mergeProps<'div'>(ownProps, otherProps), + }); + + return {element}; +} diff --git a/packages/mosaic/src/primitives/chart/chart-tooltip.tsx b/packages/mosaic/src/primitives/chart/chart-tooltip.tsx new file mode 100644 index 00000000000..338dc80e56c --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart-tooltip.tsx @@ -0,0 +1,162 @@ +'use client'; + +import { autoUpdate, flip, offset, shift, size, useFloating } from '@floating-ui/react'; +import React from 'react'; + +import { useTransition } from '../hooks/use-transition'; +import { Portal } from '../portal'; +import { type ComponentProps, type DefaultProps, Freeze, mergeProps, useRender } from '../utils'; +import { getWindow } from '../utils/dom'; +import { parsePlacement } from '../utils/side-offset'; +import { useChartContext, useSelectionContext } from './chart-context'; +import type { ChartActive } from './types'; + +const PINNED_BELOW_PLOT_WIDTH = 416; + +type Side = 'left' | 'right'; + +export type ChartTooltipProps = Omit, 'children'> & { + /** Content for the selected category, such as an `ActiveBar` from a bar chart. Return null to hide the tooltip. */ + children: (active: TActive) => React.ReactNode; + /** The side tried first. The tooltip flips to the other side when this one does not fit. Default: 'right' */ + side?: Side; + /** Distance in px from the selected category's center. Default: 16 */ + sideOffset?: number; + /** Space in px kept between the tooltip and the edges of `collisionBoundary`. Default: 8 */ + collisionPadding?: number; + /** Element the tooltip stays inside. Default: the chart */ + collisionBoundary?: React.RefObject; + /** + * Pins the tooltip to the top left of `collisionBoundary` instead of beside the selection. + * `'auto'` pins it while the plot is narrower than 416px. Default: 'auto' + */ + pinned?: boolean | 'auto'; +}; + +type BoundaryRef = React.RefObject; + +/** Reads the boundary when floating-ui computes a position, not during render. */ +function boundaryReader(collisionBoundary: BoundaryRef | undefined, chartBoxRef: BoundaryRef) { + return () => collisionBoundary?.current ?? chartBoxRef.current ?? undefined; +} + +function tooltipMiddleware( + getBoundary: () => Element | undefined, + pinned: boolean, + sideOffset: number, + padding: number, +) { + return [ + offset(pinned ? 0 : sideOffset), + flip(() => ({ boundary: getBoundary(), padding, crossAxis: false })), + shift(() => ({ boundary: getBoundary(), padding, crossAxis: true })), + size(() => ({ + boundary: getBoundary(), + padding, + apply({ elements }) { + const boundary = getBoundary()?.getBoundingClientRect(); + const viewportWidth = getWindow(elements.floating).document.documentElement.clientWidth; + const left = Math.max(padding, (boundary?.left ?? 0) + padding); + const right = Math.min(viewportWidth - padding, (boundary?.right ?? viewportWidth) - padding); + elements.floating.style.maxWidth = `${Math.max(0, right - left)}px`; + }, + })), + ]; +} + +// eslint-disable-next-line typescript/consistent-type-assertions -- The ref wrapper drops the active type parameter; the caller names the type its chart-type hook selects. +export const ChartTooltip = React.forwardRef(function ChartTooltip(props, ref) { + const { + children, + side = 'right', + sideOffset = 16, + collisionPadding = 8, + collisionBoundary, + pinned: pinnedProp = 'auto', + render, + ...otherProps + } = props; + const { registerTooltip, chartBoxRef } = useSelectionContext('Tooltip'); + const { chart } = useChartContext('Tooltip'); + const { plot, selected: active } = chart; + const chartWidth = chart.size.width; + React.useLayoutEffect(registerTooltip, [registerTooltip]); + + const anchor = chart.tooltipAnchor; + const content = active && anchor ? children(active) : null; + const open = content !== null && content !== undefined; + const anchorX = anchor?.x; + const anchorY = anchor?.y; + + const pinned = pinnedProp === 'auto' ? plot.width < PINNED_BELOW_PLOT_WIDTH : pinnedProp; + const popupRef = React.useRef(null); + const middleware = React.useMemo( + () => + // eslint-disable-next-line react/refs -- The middleware reads the boundary refs when floating-ui computes a position, not during render. + tooltipMiddleware(boundaryReader(collisionBoundary, chartBoxRef), pinned, sideOffset, collisionPadding), + [chartBoxRef, collisionBoundary, collisionPadding, pinned, sideOffset], + ); + + const [lastSide, setLastSide] = React.useState(side); + const { + refs, + floatingStyles, + placement: resolvedPlacement, + isPositioned, + } = useFloating({ + open, + strategy: 'fixed', + transform: false, + placement: pinned ? 'bottom-start' : `${lastSide}-start`, + middleware, + whileElementsMounted: autoUpdate, + }); + const resolvedSide = parsePlacement(resolvedPlacement).side; + // Starting from the side chosen last time stops the tooltip crossing the selection twice near an edge. + if (!pinned && (resolvedSide === 'left' || resolvedSide === 'right') && resolvedSide !== lastSide) { + setLastSide(resolvedSide); + } + + React.useLayoutEffect(() => { + const box = chartBoxRef.current; + if (anchorX === undefined || anchorY === undefined || !box || chartWidth <= 0) { + return; + } + const getBoundingClientRect = () => { + const chartRect = box.getBoundingClientRect(); + if (pinned) { + const boundary = boundaryReader(collisionBoundary, chartBoxRef)()?.getBoundingClientRect() ?? chartRect; + return new DOMRect(boundary.left + collisionPadding, boundary.top + collisionPadding, 0, 0); + } + const x = Math.round((chartRect.left + (anchorX / chartWidth) * chartRect.width) * 2) / 2; + return new DOMRect(x, chartRect.top + anchorY, 0, 0); + }; + refs.setReference({ getBoundingClientRect, contextElement: box }); + }, [anchorX, anchorY, chartBoxRef, chartWidth, collisionBoundary, collisionPadding, pinned, refs]); + + const { mounted, transitionProps } = useTransition({ open, ref: popupRef }); + + const ownProps = { + ...transitionProps, + 'data-side': resolvedSide, + style: { + ...floatingStyles, + pointerEvents: 'none', + ...(isPositioned ? null : { visibility: 'hidden' }), + ...transitionProps.style, + }, + children: {open ? content : null}, + } satisfies DefaultProps<'div'>; + + const element = useRender({ + defaultTagName: 'div', + render, + enabled: mounted, + ref: [refs.setFloating, popupRef, ref], + props: mergeProps<'div'>(ownProps, otherProps), + }); + + return mounted ? {element} : null; +}) as ( + props: ChartTooltipProps & { ref?: React.Ref }, +) => React.ReactElement | null; diff --git a/packages/mosaic/src/primitives/chart/chart-x-axis.tsx b/packages/mosaic/src/primitives/chart/chart-x-axis.tsx new file mode 100644 index 00000000000..afb0ac78b45 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart-x-axis.tsx @@ -0,0 +1,44 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { hasArea, useChartContext } from './chart-context'; +import type { XTick, XTickMode } from './types'; + +export type ChartXAxisProps = Omit, 'children' | 'format'> & { + /** + * `category` thins category labels to fit. `calendar` labels calendar boundaries for long ranges; + * category keys must be UTC dates. Default: 'category' + */ + ticks?: XTickMode; + /** Returns the label for a category key, or null to omit it. Default: the key */ + format?: (value: string) => string | null; + /** Renders the labels, usually one `Chart.XTick` per entry. */ + children?: (ticks: readonly XTick[]) => React.ReactNode; +}; + +const formatCategory = (value: string) => value; + +export const ChartXAxis = React.forwardRef(function ChartXAxis(props, ref) { + const { ticks = 'category', format = formatCategory, children, render, ...otherProps } = props; + const { chart } = useChartContext('XAxis'); + const { size, xTicks: getXTicks } = chart; + const xTicks = React.useMemo(() => getXTicks({ mode: ticks, format }), [format, getXTicks, ticks]); + + const ownProps = { + width: size.width, + height: size.height, + 'aria-hidden': 'true', + style: { position: 'absolute', inset: 0, display: 'block', overflow: 'visible' }, + children: children?.(xTicks), + } satisfies DefaultProps<'svg'>; + + return useRender({ + defaultTagName: 'svg', + render, + ref, + enabled: hasArea(size), + props: mergeProps<'svg'>(ownProps, otherProps), + }); +}); diff --git a/packages/mosaic/src/primitives/chart/chart-x-tick.tsx b/packages/mosaic/src/primitives/chart/chart-x-tick.tsx new file mode 100644 index 00000000000..589d01917a5 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart-x-tick.tsx @@ -0,0 +1,36 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { useChartContext } from './chart-context'; +import type { XTick } from './types'; + +export type ChartXTickProps = ComponentProps<'text'> & { + /** An entry from the `Chart.XAxis` children function. */ + tick: XTick; +}; + +export const ChartXTick = React.forwardRef(function ChartXTick(props, ref) { + const { tick, render, ...otherProps } = props; + const { chart } = useChartContext('XTick'); + const activeCategory = chart.selected?.category ?? null; + + const ownProps = { + x: tick.x, + y: chart.plot.y + chart.plot.height + 24, + textAnchor: tick.textAnchor, + children: tick.label, + } satisfies DefaultProps<'text'>; + + return useRender({ + defaultTagName: 'text', + render, + ref, + state: { active: tick.category !== null && tick.category === activeCategory }, + stateAttributesMapping: { + active: (active: boolean) => (active ? { 'data-active': '' } : null), + }, + props: mergeProps<'text'>(ownProps, otherProps), + }); +}); diff --git a/packages/mosaic/src/primitives/chart/chart-y-axis.tsx b/packages/mosaic/src/primitives/chart/chart-y-axis.tsx new file mode 100644 index 00000000000..4e1c9d9b17e --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart-y-axis.tsx @@ -0,0 +1,47 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { hasArea, useCartesianChart } from './chart-context'; + +export interface ChartYTickItem { + value: number; + y: number; + label: React.ReactNode; +} + +export type ChartYAxisProps = Omit, 'children' | 'format'> & { + /** Formats a tick value. Default: the locale number */ + format?: (value: number) => React.ReactNode; + /** Renders the labels, usually one `Chart.YTick` per entry. */ + children?: (ticks: readonly ChartYTickItem[]) => React.ReactNode; +}; + +const formatNumber = (value: number) => value.toLocaleString(); + +export const ChartYAxis = React.forwardRef(function ChartYAxis(props, ref) { + const { format = formatNumber, children, render, ...otherProps } = props; + const chart = useCartesianChart('YAxis'); + const { size, yTicks } = chart; + const ticks = React.useMemo( + () => yTicks.map(tick => ({ value: tick.value, y: tick.y, label: format(tick.value) })), + [format, yTicks], + ); + + const ownProps = { + width: size.width, + height: size.height, + 'aria-hidden': 'true', + style: { position: 'absolute', inset: 0, display: 'block', overflow: 'visible' }, + children: children?.(ticks), + } satisfies DefaultProps<'svg'>; + + return useRender({ + defaultTagName: 'svg', + render, + ref, + enabled: hasArea(size), + props: mergeProps<'svg'>(ownProps, otherProps), + }); +}); diff --git a/packages/mosaic/src/primitives/chart/chart-y-line.tsx b/packages/mosaic/src/primitives/chart/chart-y-line.tsx new file mode 100644 index 00000000000..fa571c8c28f --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart-y-line.tsx @@ -0,0 +1,33 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { useCartesianChart } from './chart-context'; + +export type ChartYLineProps = ComponentProps<'line'> & { + /** The value on the Y axis the line marks, such as a tick value or 0. */ + value: number; +}; + +/** A line across the plot at a Y value, inside any chart SVG. */ +export const ChartYLine = React.forwardRef(function ChartYLine(props, ref) { + const { value, render, ...otherProps } = props; + const chart = useCartesianChart('YLine'); + const y = chart.scaleY(value); + + const ownProps = { + x1: chart.plot.x, + x2: chart.plot.x + chart.plot.width, + y1: y, + y2: y, + vectorEffect: 'non-scaling-stroke', + } satisfies DefaultProps<'line'>; + + return useRender({ + defaultTagName: 'line', + render, + ref, + props: mergeProps<'line'>(ownProps, otherProps), + }); +}); diff --git a/packages/mosaic/src/primitives/chart/chart-y-tick.tsx b/packages/mosaic/src/primitives/chart/chart-y-tick.tsx new file mode 100644 index 00000000000..e42f71a8958 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart-y-tick.tsx @@ -0,0 +1,32 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { useChartContext } from './chart-context'; +import type { ChartYTickItem } from './chart-y-axis'; + +export type ChartYTickProps = ComponentProps<'text'> & { + /** An entry from the `Chart.YAxis` children function. */ + tick: ChartYTickItem; +}; + +export const ChartYTick = React.forwardRef(function ChartYTick(props, ref) { + const { tick, render, ...otherProps } = props; + const { chart } = useChartContext('YTick'); + + const ownProps = { + x: chart.plot.x - 12, + y: tick.y, + dy: '0.32em', + textAnchor: 'end', + children: tick.label, + } satisfies DefaultProps<'text'>; + + return useRender({ + defaultTagName: 'text', + render, + ref, + props: mergeProps<'text'>(ownProps, otherProps), + }); +}); diff --git a/packages/mosaic/src/primitives/chart/chart.doc.ts b/packages/mosaic/src/primitives/chart/chart.doc.ts new file mode 100644 index 00000000000..fb31c06d0a3 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart.doc.ts @@ -0,0 +1,293 @@ +import type { ComponentDoc } from '../../docs-schema'; +import type { + ChartBarProps, + ChartBarsProps, + ChartCursorProps, + ChartGridProps, + ChartProjectionOutlineProps, + ChartRootProps, + ChartSelectionProps, + ChartTooltipProps, + ChartXAxisProps, + ChartXTickProps, + ChartYAxisProps, + ChartYLineProps, + ChartYTickProps, +} from './parts'; + +export default { + name: 'Chart', + description: + 'Headless, unstyled charts. A chart-type hook owns the layout and selection and returns a chart object; `Chart.Root` takes it, and the parts render from it. The shared parts draw the root, grid, axes, Y lines, and pointer and keyboard selection with its cursor and tooltip. Stacked bars with values above and below zero come from `Chart.useBarChart`: D3 computes the stacks and scales, and `Chart.Bars` paints the bars on Canvas, styled through the hidden `Chart.Bar`. Up and Down select the positive or negative section of a period. Each container renders nothing until the root has a measured, non-zero size.', + useFor: [ + 'a stacked bar chart over a category or time axis', + 'bars with values above and below zero', + 'a chart with thousands of bars that still needs keyboard and pointer selection', + 'axes, a grid and reference lines for a chart', + 'pointer and keyboard selection over a chart, with a cursor and a tooltip', + 'a decorative placeholder chart with no selection', + ], + keywords: [ + 'chart', + 'graph', + 'bar chart', + 'stacked bars', + 'diverging', + 'projection', + 'canvas', + 'useBarChart', + 'axis', + 'grid', + 'tick', + 'tooltip', + 'cursor', + 'selection', + 'data visualization', + ], + practices: [ + { + do: true, + text: 'Pass `className` to every item part and style it. An unstyled line has no stroke and an unstyled label is black.', + }, + { + do: true, + text: 'Write the parts in paint order: `Chart.Grid`, the marks of the chart type, `Chart.YAxis`, `Chart.XAxis`, then `Chart.Selection` last.', + }, + { + do: true, + text: 'Name the active type on the tooltip, such as `>>`, so its children get the fields of the chart type.', + }, + { + do: true, + text: 'Leave out `Chart.Selection` for a decorative chart. It then has no interaction surface and takes no focus.', + }, + { + do: true, + text: 'Memoize `series`, `index` and `isBarActive`, or define them at module level. A new `series` or `index` prepares the stacks again on every selection change.', + }, + { do: true, text: 'Return a unique category key from `index`. Repeated keys share a band.' }, + { + do: true, + text: 'Style `Chart.Bar` with a `color` per `data-series`, and `data-projection` whenever there is a projection. Without it nothing is painted.', + }, + { + do: true, + text: 'Catch `Chart.CanvasRenderError` in an error boundary and offer a retry that mounts a fresh chart.', + }, + { + do: false, + text: 'Expect Left and Right to follow `useDirection()`. A time axis reads left to right in every locale.', + }, + { + do: false, + text: 'Render a bare `` or ``. A container renders only the items its children function returns.', + }, + { + do: false, + text: 'Animate the bar color with a CSS transition. `Chart.Bar` is `display: none`, so the bars repaint at the end value.', + }, + { + do: false, + text: 'Expect a stylesheet change alone to repaint. Change the class of `Chart.Bar`, or of an ancestor, to repaint.', + }, + ], + parts: { + 'Chart.Root': { + description: + 'A `div` that attaches the measurement of the chart and provides the chart to the parts. Carries `data-chart-interaction-mode`: `pending` before the first measurement, `interactive` with `Chart.Selection` and categories, otherwise `visual-only`.', + props: { + chart: { type: 'ChartInstance', doc: 'The result of a chart-type hook, such as `Chart.useBarChart`.' }, + 'aria-label': { type: 'string', doc: 'Labels the chart image and the interaction surface.' }, + height: { type: 'number | string', doc: 'The container height.', default: '500' }, + }, + }, + 'Chart.Grid': { + description: 'An `aria-hidden` `svg` over the whole chart that holds the grid lines.', + props: { + children: { + type: '(ticks: readonly ChartTick[]) => React.ReactNode', + doc: 'Renders the lines, usually one `Chart.YLine` per tick value.', + }, + }, + }, + 'Chart.YLine': { + description: + 'A `line` across the plot at a Y value, inside any chart SVG: `Chart.Grid`, or the marks of a chart type for a zero line.', + props: { + value: { type: 'number', doc: 'The value on the Y axis the line marks, such as a tick value or `0`.' }, + }, + }, + 'Chart.Bars': { + description: + 'A `div` that paints the bars and the projection outline on a Canvas with `role="img"`, and holds one SVG over it for `Chart.Bar`, `Chart.ProjectionOutline` and any `Chart.YLine`. Throws outside `Chart.Root`, and when the chart did not come from `Chart.useBarChart`.', + }, + 'Chart.Bar': { + description: + 'A hidden `g` whose computed style paints the bars. Before each paint it takes `data-series`, `data-inactive` and `data-projection` in turn and the bars use its `color`. Its `max-width`, `row-gap` and corner radii in pixels set the bar geometry. Throws outside `Chart.Bars`.', + }, + 'Chart.ProjectionOutline': { + description: + 'A hidden `g` whose computed `stroke`, `stroke-width` and `stroke-dasharray` outline the projected bar on the Canvas, 1px outside its fill, with concentric top corners and square ends on the zero line, when `projection` rises above its stack. Throws outside `Chart.Bars`.', + }, + 'Chart.YAxis': { + description: 'An `aria-hidden` `svg` that holds the Y tick labels in the left margin.', + props: { + format: { + type: '(value: number) => React.ReactNode', + doc: 'Formats a tick value.', + default: 'the locale number', + }, + children: { + type: '(ticks: readonly ChartYTickItem[]) => React.ReactNode', + doc: 'Renders the labels, usually one `Chart.YTick` per entry.', + }, + }, + }, + 'Chart.YTick': { + description: 'One Y tick label, a `text` right-aligned against the plot.', + props: { + tick: { type: 'ChartYTickItem', doc: 'An entry from the `Chart.YAxis` children function.' }, + }, + }, + 'Chart.XAxis': { + description: 'An `aria-hidden` `svg` that holds the category labels below the plot.', + props: { + ticks: { + type: "'category' | 'calendar'", + doc: '`category` thins labels to fit. `calendar` labels calendar boundaries for long ranges, and needs UTC date keys.', + default: "'category'", + }, + format: { + type: '(value: string) => string | null', + doc: 'Returns the label for a category key, or null to omit it.', + default: 'the key', + }, + children: { + type: '(ticks: readonly XTick[]) => React.ReactNode', + doc: 'Renders the labels, usually one `Chart.XTick` per entry.', + }, + }, + }, + 'Chart.XTick': { + description: + 'One category label, a `text` below the plot. Carries `data-active` while its period is selected; a calendar boundary label never does.', + props: { + tick: { type: 'XTick', doc: 'An entry from the `Chart.XAxis` children function.' }, + }, + }, + 'Chart.Selection': { + description: + 'A `div` holding the interaction surface: a `button` when the hook has `onActivate`, otherwise a `group`, and a `status` region that announces keyboard moves. Removes its surface when the data has no categories, and unmounting it ends a pointer or keyboard selection.', + }, + 'Chart.Cursor': { + description: + 'An `aria-hidden` `div` that covers the selected category, with its width. Throws outside `Chart.Selection`.', + }, + 'Chart.Tooltip': { + description: + 'A `div` portaled through `Portal` beside the selected category. Opens on `side`, flips to the other side when it does not fit, and keeps the side it chose last. Pins to the top left of the boundary on a plot narrower than 416px by default. Carries `data-side`, `data-open`, `data-closed`, `data-starting-style` and `data-ending-style`. Throws outside `Chart.Selection`.', + props: { + children: { + type: '(active: TActive) => React.ReactNode', + doc: 'Content for the selected category. Return null to hide the tooltip.', + }, + side: { type: "'left' | 'right'", doc: 'The side tried first.', default: "'right'" }, + sideOffset: { type: 'number', doc: 'Distance in px from the category center.', default: '16' }, + collisionPadding: { + type: 'number', + doc: 'Space in px kept between the tooltip and the boundary edges.', + default: '8', + }, + collisionBoundary: { + type: 'React.RefObject', + doc: 'Element the tooltip stays inside.', + default: 'the chart', + }, + pinned: { + type: "boolean | 'auto'", + doc: 'Pins the tooltip to the top left of the boundary. `auto` pins it below a 416px plot.', + default: "'auto'", + }, + }, + }, + }, + examples: [ + { + title: 'Stacked bars with axes, a grid, a cursor and a tooltip', + code: ` +const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }); + + + + {ticks => ticks.map(tick => )} + + + + + + + {ticks => ticks.map(tick => )} + + + {ticks => ticks.map(tick => )} + + + + > className='tooltip'>{active => } + + +`, + }, + { + title: 'A projected total', + code: ` +const chart = Chart.useBarChart({ data, series, index, projection: { datumIndex: data.length - 1, value: 130 } }); + + + + + + + + +`, + }, + { + title: 'Dim the bars outside the selected section', + code: ` +const [selection, setSelection] = useState(null); +const isBarActive = useCallback( + (bar: BarIdentity) => + !selection || (bar.datum.week === selection.category && bar.positive === (selection.section === 'positive')), + [selection], +); +const chart = Chart.useBarChart({ data, series, index, selection, onSelectionChange: setSelection, isBarActive }); +`, + }, + ], + related: ['Portal'], + exports: { + 'Chart.useBarChart': { + description: + 'Lays out stacked bars and owns their selection: `Chart.useBarChart({ data, series, index })`, plus `categoryGap`, `margin`, `projection`, `isBarActive`, `selection`, `defaultSelection`, `onSelectionChange`, `onActivate`, `disabled`, `formatCategory`, `formatValue` and `messages`. Give each series a `label` so announcements name it. Returns the chart object for `Chart.Root`.', + }, + 'Chart.CanvasRenderError': { + description: + 'Thrown when the Canvas 2D context is missing or lost, or painting fails, with the original failure as its `cause`.', + }, + }, +} satisfies ComponentDoc<{ + 'Chart.Root': ChartRootProps; + 'Chart.Grid': ChartGridProps; + 'Chart.YLine': ChartYLineProps; + 'Chart.Bars': ChartBarsProps; + 'Chart.Bar': ChartBarProps; + 'Chart.ProjectionOutline': ChartProjectionOutlineProps; + 'Chart.YAxis': ChartYAxisProps; + 'Chart.YTick': ChartYTickProps; + 'Chart.XAxis': ChartXAxisProps; + 'Chart.XTick': ChartXTickProps; + 'Chart.Selection': ChartSelectionProps; + 'Chart.Cursor': ChartCursorProps; + 'Chart.Tooltip': ChartTooltipProps; +}>; diff --git a/packages/mosaic/src/primitives/chart/index.ts b/packages/mosaic/src/primitives/chart/index.ts new file mode 100644 index 00000000000..9a739115120 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/index.ts @@ -0,0 +1,49 @@ +export * as Chart from './parts'; + +export type { + ChartBarProps, + ChartBarsProps, + ChartCursorProps, + ChartGridProps, + ChartProjectionOutlineProps, + ChartRootProps, + ChartSelectionProps, + ChartTooltipProps, + ChartXAxisProps, + ChartXTickProps, + ChartYAxisProps, + ChartYLineProps, + ChartYTickItem, + ChartYTickProps, + UseBarChartOptions, +} from './parts'; +export type { + CartesianChartInstance, + ChartActive, + ChartCategory, + ChartInstance, + ChartInteractionInput, + ChartInteractionProps, + ChartMargin, + ChartMessages, + ChartOptions, + ChartPlot, + ChartPoint, + ChartSelection, + ChartSize, + ChartTick, + XTick, + XTickMode, + XTicksOptions, +} from './types'; +export type { BarChartInstance } from './bars/bar-context'; +export type { + ActiveBar, + BarCategory, + BarChartMessages, + BarIdentity, + BarProjection, + BarSection, + BarSelection, + BarSeries, +} from './bars/types'; diff --git a/packages/mosaic/src/primitives/chart/internal/__tests__/calendar-ticks.test.ts b/packages/mosaic/src/primitives/chart/internal/__tests__/calendar-ticks.test.ts new file mode 100644 index 00000000000..a584691489c --- /dev/null +++ b/packages/mosaic/src/primitives/chart/internal/__tests__/calendar-ticks.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from 'vitest'; + +import { selectCalendarTicks } from '../calendar-ticks'; +import { selectXTicks } from '../x-ticks'; + +const day = 24 * 60 * 60 * 1000; +const labelWidth = 64; +const dates = (count: number, start = Date.UTC(2020, 0, 14)) => + Array.from({ length: count }, (_, index) => start + index * day); +const isoDates = (timestamps: readonly number[]) => + timestamps.map(timestamp => new Date(timestamp).toISOString().slice(0, 10)); +const axis = (timestamps: readonly number[], width: number) => { + const plot = { x: 76, width: width - 92 }; + const step = plot.width / timestamps.length; + return selectCalendarTicks({ + timestamps, + centers: timestamps.map((_, index) => plot.x + step * (index + 0.5)), + plot, + viewportWidth: width, + measure: () => labelWidth, + }); +}; + +describe('calendar boundaries', () => { + it('labels year boundaries with their year on a multi-year daily chart', () => { + const ticks = axis(dates(2200), 722); + + expect(ticks.map(tick => tick.label)).toEqual(expect.arrayContaining(['Jan 2021', 'Jan 2025'])); + for (const tick of ticks) { + expect(tick.label).toMatch(/^Jan \d{4}$/); + expect(tick.coordinate - labelWidth / 2).toBeGreaterThanOrEqual(0); + expect(tick.coordinate + labelWidth / 2).toBeLessThanOrEqual(722); + } + }); + + it('labels a month that has no bar of its own, in date order', () => { + const ticks = axis( + [Date.UTC(2024, 0, 1), Date.UTC(2024, 0, 15), Date.UTC(2024, 2, 1), Date.UTC(2024, 3, 1), Date.UTC(2024, 4, 1)], + 1000, + ); + + expect(ticks.map(tick => tick.label)).toContain('Feb 2024'); + const coordinates = ticks.map(tick => tick.coordinate); + expect(coordinates).toEqual([...coordinates].sort((a, b) => a - b)); + }); + + it('gives narrower charts fewer labels that never overlap', () => { + const axes = [450, 722, 1200].map(width => axis(dates(2200), width)); + const counts = axes.map(ticks => ticks.length); + + expect(counts[0]).toBeLessThan(counts[2] ?? 0); + expect(counts).toEqual([...counts].sort((a, b) => a - b)); + for (const ticks of axes) { + ticks.slice(1).forEach((tick, index) => { + const previous = ticks[index]?.coordinate ?? -Infinity; + expect(tick.coordinate - previous).toBeGreaterThan(labelWidth); + }); + } + }); +}); + +describe('placing boundaries on the categories', () => { + it('puts a boundary at the center of the category dated on it, wherever the chart type centers it', () => { + const timestamps = dates(120, Date.UTC(2024, 0, 1)); + const plot = { x: 40, width: 800 }; + const pointCenters = timestamps.map((_, index) => plot.x + (index / (timestamps.length - 1)) * plot.width); + const ticks = selectCalendarTicks({ + timestamps, + centers: pointCenters, + plot, + viewportWidth: 880, + measure: () => labelWidth, + }); + + const february = timestamps.indexOf(Date.UTC(2024, 1, 1)); + expect(ticks.find(tick => tick.label === 'Feb 2024')?.coordinate).toBe(pointCenters[february]); + }); +}); + +describe('category fallback', () => { + it.each([ + { name: 'a short range', keys: isoDates(dates(7)) }, + { + name: 'an invalid date', + keys: ['2024-01-01', 'not a date', '2024-06-01'], + }, + { + name: 'unordered dates', + keys: ['2024-06-01', '2024-01-01', '2024-09-01'], + }, + ])('labels categories for $name', ({ keys }) => { + const plot = { x: 0, width: 600 }; + const step = plot.width / keys.length; + const ticks = selectXTicks({ + categories: keys.map((key, index) => ({ + key, + center: index * step + step / 2, + })), + plot, + viewportWidth: 600, + xAxis: 'calendar', + formatXTick: label => label, + }); + + expect(ticks.length).toBeGreaterThan(0); + for (const tick of ticks) { + expect(tick.category).toBe(tick.label); + } + }); + + it('keeps calendar labels when a date repeats', () => { + const timestamps = dates(200); + const keys = isoDates([timestamps[0] ?? 0, ...timestamps]); + const plot = { x: 0, width: 600 }; + const ticks = selectXTicks({ + categories: keys.map((key, index) => ({ key, center: index })), + plot, + viewportWidth: 600, + xAxis: 'calendar', + formatXTick: label => label, + }); + + expect(ticks.length).toBeGreaterThan(0); + for (const tick of ticks) { + expect(tick.category).toBeNull(); + } + }); +}); diff --git a/packages/mosaic/src/primitives/chart/internal/__tests__/x-ticks.test.ts b/packages/mosaic/src/primitives/chart/internal/__tests__/x-ticks.test.ts new file mode 100644 index 00000000000..a69d6969a45 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/internal/__tests__/x-ticks.test.ts @@ -0,0 +1,152 @@ +import { describe, expect, it } from 'vitest'; + +import { selectXTicks, type XTick } from '../x-ticks'; + +type Plot = { x: number; width: number }; + +const plot = { x: 0, width: 600 }; +const gutteredPlot = { x: 64, width: 480 }; +const measureByLength = (label: string) => label.length * 8; + +function categories(keys: readonly string[], area: Plot = plot) { + const step = area.width / keys.length; + return keys.map((key, datumIndex) => ({ + key, + center: area.x + datumIndex * step + step / 2, + })); +} + +function dailyDates(count: number, start: number) { + return Array.from({ length: count }, (_, index) => + new Date(start + index * 24 * 60 * 60 * 1000).toISOString().slice(0, 10), + ); +} + +function extent(tick: XTick, measure: (label: string) => number) { + const width = measure(tick.label); + const left = tick.textAnchor === 'start' ? tick.x : tick.textAnchor === 'end' ? tick.x - width : tick.x - width / 2; + return { left, right: left + width }; +} + +function expectReadable(ticks: readonly XTick[], area: Plot, measure: (label: string) => number) { + const extents = ticks.map(tick => extent(tick, measure)); + extents.forEach((current, index) => { + expect(current.left).toBeGreaterThanOrEqual(area.x); + expect(current.right).toBeLessThanOrEqual(area.x + area.width); + const previous = extents[index - 1]; + if (previous) { + expect(current.left).toBeGreaterThan(previous.right); + } + }); +} + +describe('category labels', () => { + it('centers each label under its category when it fits there', () => { + const months = categories(['Sep', 'Oct', 'Nov']); + const ticks = selectXTicks({ + categories: months, + plot, + viewportWidth: 600, + formatXTick: label => label, + measure: measureByLength, + }); + + expect(ticks.map(({ x, textAnchor }) => ({ x, textAnchor }))).toEqual( + months.map(({ center }) => ({ x: center, textAnchor: 'middle' })), + ); + }); + + it('keeps a label that would overflow the plot inside its edge', () => { + const days = categories(dailyDates(30, Date.UTC(2026, 9, 27))); + const ticks = selectXTicks({ + categories: days, + plot, + viewportWidth: 600, + formatXTick: label => label, + measure: measureByLength, + }); + + expect(ticks[0]).toMatchObject({ textAnchor: 'start', x: 4 }); + expect(ticks.at(-1)).toMatchObject({ textAnchor: 'end', x: 596 }); + }); + + it.each([ + { name: 'short labels', width: 20, labels: ['Jan', 'Feb', 'Mar'] }, + { name: 'wide labels', width: 260, labels: ['Jan', 'Mar'] }, + ])('labels the first and last periods without overlap for $name', ({ width, labels }) => { + const measure = () => width; + const ticks = selectXTicks({ + categories: categories(['Jan', 'Feb', 'Mar']), + plot, + viewportWidth: 600, + formatXTick: label => label, + measure, + }); + + expect(ticks.map(tick => tick.label)).toEqual(labels); + expectReadable(ticks, plot, measure); + }); + + it('omits a null label without hiding the other labels', () => { + const ticks = selectXTicks({ + categories: categories(['Jan', 'Feb', 'Mar', 'Apr', 'May']), + plot, + viewportWidth: 600, + formatXTick: label => (label === 'Mar' ? null : label), + measure: () => 20, + }); + + expect(ticks.map(tick => tick.label)).toEqual(['Jan', 'Feb', 'Apr', 'May']); + }); + + it('thins dense periods and keeps the first and latest', () => { + const wide = { x: 0, width: 960 }; + const keys = Array.from({ length: 30 }, (_, position) => String(position)); + const measure = () => 30; + const ticks = selectXTicks({ + categories: categories(keys, wide), + plot: wide, + viewportWidth: 960, + formatXTick: label => label, + measure, + }); + + expect(ticks.length).toBeLessThan(keys.length); + expect(ticks[0]?.label).toBe('0'); + expect(ticks.at(-1)?.label).toBe('29'); + expectReadable(ticks, wide, measure); + }); +}); + +describe('calendar labels', () => { + it.each([ + { + name: 'a range starting on a month boundary', + days: dailyDates(365, Date.UTC(2025, 6, 1)), + }, + { + name: 'a range starting mid-month', + days: dailyDates(124, Date.UTC(2025, 6, 14)), + }, + { + name: 'a range ending just after a month boundary', + days: dailyDates(379, Date.UTC(2025, 6, 1)), + }, + ])('labels month boundaries inside the plot for $name', ({ days }) => { + const ticks = selectXTicks({ + categories: categories(days, gutteredPlot), + plot: gutteredPlot, + viewportWidth: 560, + xAxis: 'calendar', + formatXTick: () => null, + measure: measureByLength, + }); + + expect(ticks.length).toBeGreaterThan(1); + for (const tick of ticks) { + expect(tick.label).toMatch(/^[A-Z][a-z]{2} \d{4}$/); + expect(tick.category).toBeNull(); + } + expectReadable(ticks, gutteredPlot, measureByLength); + }); +}); diff --git a/packages/mosaic/src/primitives/chart/internal/calendar-ticks.ts b/packages/mosaic/src/primitives/chart/internal/calendar-ticks.ts new file mode 100644 index 00000000000..b8d4c515546 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/internal/calendar-ticks.ts @@ -0,0 +1,108 @@ +type CalendarTick = Readonly<{ label: string; coordinate: number }>; + +type CalendarAxis = Readonly<{ + timestamps: readonly number[]; + /** The center of the category at each timestamp. */ + centers: readonly number[]; + plot: { x: number; width: number }; + viewportWidth: number; + measure: (label: string) => number; +}>; + +const day = 24 * 60 * 60 * 1000; +const monthSteps = [1, 3, 6, 12, 24, 60, 120]; +const monthLabel = new Intl.DateTimeFormat('en-US', { + month: 'short', + year: 'numeric', + timeZone: 'UTC', +}); + +export function parseCalendarDates(indexes: readonly string[]): number[] | null { + const timestamps = indexes.map(Date.parse); + if ( + timestamps.some( + (timestamp, index) => + !Number.isFinite(timestamp) || (index > 0 && timestamp < (timestamps[index - 1] ?? timestamp)), + ) + ) { + return null; + } + return timestamps; +} + +function coordinateAt(timestamp: number, timestamps: readonly number[], centers: readonly number[]): number { + let low = 0; + let high = timestamps.length; + while (low < high) { + const middle = Math.floor((low + high) / 2); + if ((timestamps[middle] ?? Infinity) < timestamp) { + low = middle + 1; + } else { + high = middle; + } + } + const right = Math.min(low, timestamps.length - 1); + const left = Math.max(0, right - 1); + const leftDate = timestamps[left] ?? timestamp; + const rightDate = timestamps[right] ?? timestamp; + const leftCenter = centers[left] ?? 0; + const rightCenter = centers[right] ?? leftCenter; + if (rightDate === leftDate) { + return rightCenter; + } + return leftCenter + ((timestamp - leftDate) / (rightDate - leftDate)) * (rightCenter - leftCenter); +} + +function monthBoundaries(first: number, last: number, step: number): Date[] { + const start = new Date(first); + const firstMonth = start.getUTCFullYear() * 12 + start.getUTCMonth(); + const result: Date[] = []; + for (let month = Math.ceil(firstMonth / step) * step; ; month += step) { + const date = new Date(Date.UTC(Math.floor(month / 12), month % 12, 1)); + if (date.getTime() > last) { + break; + } + if (date.getTime() >= first) { + result.push(date); + } + } + return result; +} + +export function selectCalendarTicks({ + timestamps, + centers, + plot, + viewportWidth, + measure, +}: CalendarAxis): CalendarTick[] { + const first = timestamps[0]; + const last = timestamps[timestamps.length - 1]; + if (first === undefined || last === undefined || last - first < 90 * day || plot.width <= 0) { + return []; + } + + for (const step of monthSteps) { + const ticks = monthBoundaries(first, last, step) + .map(date => ({ + label: monthLabel.format(date), + coordinate: coordinateAt(date.getTime(), timestamps, centers), + })) + .filter(tick => { + const halfWidth = measure(tick.label) / 2; + return tick.coordinate - halfWidth >= 0 && tick.coordinate + halfWidth <= viewportWidth; + }); + if ( + ticks.length > 0 && + ticks.every( + (tick, index) => + index === 0 || + tick.coordinate - (ticks[index - 1]?.coordinate ?? 0) >= + (measure(tick.label) + measure(ticks[index - 1]?.label ?? '')) / 2 + 20, + ) + ) { + return ticks; + } + } + return []; +} diff --git a/packages/mosaic/src/primitives/chart/internal/selection.ts b/packages/mosaic/src/primitives/chart/internal/selection.ts new file mode 100644 index 00000000000..572670a5b73 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/internal/selection.ts @@ -0,0 +1,203 @@ +import type { ChartActive, ChartCategory, ChartMessages, ChartPoint, ChartSelection } from '../types'; + +export const DEFAULT_CHART_MESSAGES = { + navigate: 'Use Left and Right to choose a period, or Home and End to jump to the first or last.', + activate: 'Press Enter or Space to open the selected period.', + dismiss: 'Press Escape to dismiss.', + noValues: 'No values for this period', +} as const satisfies ChartMessages; + +export type VerticalMove = 'up' | 'down'; + +/** + * A chart type's selection rules. A chart-type hook builds one per layout, closing over its + * categories and data, and the selection engine asks it everything that is not shared. + */ +export type SelectionModel< + TSelection extends ChartSelection, + TActive extends ChartActive, + TCategory extends ChartCategory = ChartCategory, +> = Readonly<{ + /** + * The selection under a pointer, or null when the pointer is off every mark. `current` lets a + * model hold its pick near a boundary. + */ + hitTest: (point: ChartPoint, current: TSelection | null) => TSelection | null; + /** + * Where the keyboard lands on `category`. Up and Down pass `move`; otherwise the model keeps what it + * can of `current`. Null when the category has nothing to select. + */ + land: (category: TCategory, move: VerticalMove | undefined, current: TSelection | null) => TSelection | null; + /** The selection read against the current data, or null when the data no longer has it. */ + resolve: (selection: TSelection, category: TCategory) => TActive | null; + /** Follows the category name in an announcement: the selected values, such as `Sign-ups 20`. */ + describe: (active: TActive) => string; + /** The sentence about Up and Down in the keyboard instructions. */ + verticalInstructions: string; + /** Where a tooltip for the selection points. */ + anchor: (selection: TSelection, category: TCategory) => ChartPoint; + /** State the interaction surface carries for styling, such as `data-active-section`. */ + surfaceAttributes: (selection: TSelection | null) => Readonly>; +}>; + +export type Selected = Readonly<{ + status: 'selected'; + /** `external` is a selection set through `selection` or `select`. */ + source: 'pointer' | 'keyboard' | 'external'; + category: string; + /** Null when the keyboard lands on a category with nothing to select. */ + selection: TSelection | null; +}>; + +/** + * `dismissed` is the state after Escape: the period is remembered, so Enter reselects it instead of + * activating it. + */ +export type SelectionState = + | Readonly<{ status: 'none' }> + | Readonly<{ status: 'dismissed' }> + | Selected; + +export type SelectionAction = + | Readonly<{ type: 'pointer'; selection: TSelection | null }> + | Readonly<{ type: 'keyboard'; category: string | undefined; selection: TSelection | null }> + | Readonly<{ type: 'select'; selection: TSelection }> + | Readonly<{ type: 'clear' }> + | Readonly<{ type: 'dismiss' }>; + +export const NO_SELECTION = { status: 'none' } as const satisfies SelectionState; + +export function selectionReducer( + state: SelectionState, + action: SelectionAction, +): SelectionState { + switch (action.type) { + case 'pointer': + return action.selection + ? { status: 'selected', source: 'pointer', category: action.selection.category, selection: action.selection } + : NO_SELECTION; + case 'select': + return { + status: 'selected', + source: 'external', + category: action.selection.category, + selection: action.selection, + }; + case 'clear': + return state.status === 'dismissed' ? state : NO_SELECTION; + case 'dismiss': + return { status: 'dismissed' }; + case 'keyboard': + return action.category === undefined + ? NO_SELECTION + : { status: 'selected', source: 'keyboard', category: action.category, selection: action.selection }; + } +} + +export function selectedState(state: SelectionState): Selected | null { + return state.status === 'selected' ? state : null; +} + +/** The public value of a selection state: the selection, or null. */ +export function toPublicSelection(state: SelectionState): TSelection | null { + return state.status === 'selected' ? state.selection : null; +} + +/** Selections are flat records of primitives, so two with the same fields name the same thing. */ +export function sameSelection(a: ChartSelection | null, b: ChartSelection | null) { + if (!a || !b) { + return a === b; + } + const aEntries = Object.entries(a); + const bValues = new Map(Object.entries(b)); + return aEntries.length === bValues.size && aEntries.every(([key, value]) => bValues.get(key) === value); +} + +/** + * Applies a controlled value to the stored state. The stored state is kept while its public value + * matches, so a dismissed period and a keyboard selection on an empty period survive a controlled + * `null`; otherwise the controlled value wins. + */ +export function reconcileSelection( + state: SelectionState, + value: TSelection | null, +): SelectionState { + if (sameSelection(toPublicSelection(state), value)) { + return state; + } + return value ? { status: 'selected', source: 'external', category: value.category, selection: value } : NO_SELECTION; +} + +/** Index of the category whose center is nearest `x`, the later one on a tie. -1 when there is none. */ +export function nearestCategory(categories: readonly Pick[], x: number) { + let low = 0; + let high = categories.length - 1; + while (low < high) { + const middle = Math.floor((low + high) / 2); + const left = categories[middle]?.center ?? 0; + const right = categories[middle + 1]?.center ?? 0; + if (x - left >= right - x) { + low = middle + 1; + } else { + high = middle; + } + } + return high; +} + +export type KeyIntent = + | Readonly<{ type: 'dismiss' }> + | Readonly<{ type: 'select'; index: number; move: VerticalMove | undefined; activate: boolean }>; + +export function getKeyIntent(key: string, index: number, lastIndex: number, canActivate: boolean): KeyIntent | null { + switch (key) { + case 'Escape': + return { type: 'dismiss' }; + case 'ArrowUp': + return { type: 'select', index, move: 'up', activate: false }; + case 'ArrowDown': + return { type: 'select', index, move: 'down', activate: false }; + case 'ArrowLeft': + return { type: 'select', index: index - 1, move: undefined, activate: false }; + case 'ArrowRight': + return { type: 'select', index: index + 1, move: undefined, activate: false }; + case 'Home': + return { type: 'select', index: 0, move: undefined, activate: false }; + case 'End': + return { type: 'select', index: lastIndex, move: undefined, activate: false }; + case 'Enter': + case ' ': + return canActivate ? { type: 'select', index, move: undefined, activate: true } : null; + default: + return null; + } +} + +export function getKeyboardAnnouncement< + TSelection extends ChartSelection, + TActive extends ChartActive, + TCategory extends ChartCategory, +>( + selected: Selected | null, + active: TActive | null, + category: TCategory | undefined, + model: Pick, 'describe' | 'land'>, + formatCategory: (category: string) => string | null, + messages: ChartMessages, +) { + if (selected?.source !== 'keyboard') { + return ''; + } + if (active) { + const label = formatCategory(selected.category) ?? selected.category; + return [label, model.describe(active)].filter(Boolean).join(', '); + } + const hasValues = !!category && model.land(category, undefined, null) !== null; + return hasValues ? '' : messages.noValues; +} + +export function getKeyboardInstructions(messages: ChartMessages, verticalInstructions: string, canActivate: boolean) { + return [messages.navigate, verticalInstructions, canActivate ? messages.activate : '', messages.dismiss] + .filter(Boolean) + .join(' '); +} diff --git a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts new file mode 100644 index 00000000000..bc6f50ee58d --- /dev/null +++ b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts @@ -0,0 +1,376 @@ +'use client'; + +import React from 'react'; + +import { useControllableState } from '../../hooks/use-controllable-state'; +import { mergeProps } from '../../utils'; +import type { + ChartActive, + ChartCategory, + ChartInstance, + ChartInteractionInput, + ChartInteractionProps, + ChartMargin, + ChartOptions, + ChartPlot, + ChartSelection, + ChartSize, + XTick, + XTicksOptions, +} from '../types'; +import { + DEFAULT_CHART_MESSAGES, + getKeyboardAnnouncement, + getKeyboardInstructions, + getKeyIntent, + NO_SELECTION, + reconcileSelection, + sameSelection, + selectedState, + type SelectionAction, + type SelectionModel, + selectionReducer, + type SelectionState, + toPublicSelection, + type VerticalMove, +} from './selection'; +import { useChartSize } from './use-chart-size'; +import { selectXTicks } from './x-ticks'; + +export const DEFAULT_CHART_MARGIN: ChartMargin = { + top: 8, + right: 16, + bottom: 36, + left: 52, +}; + +/** What a chart type's layout gives the shared instance. */ +export type ChartLayout = Readonly<{ + plot: ChartPlot; + categories: readonly TCategory[]; +}>; + +export type ChartFrame = Readonly<{ + rootRef: (element: HTMLElement | null) => void; + rootElementRef: React.RefObject; + /** The measured container, zero until the first measurement. */ + size: ChartSize; + /** Stable while its four numbers are, so an inline `margin` does not relayout. */ + margin: ChartMargin; +}>; + +/** Measures the chart root and resolves the margin around the plot. */ +export function useChartFrame(margin: Partial | undefined): ChartFrame { + const { ref: sizeRef, size } = useChartSize(); + const rootElementRef = React.useRef(null); + const rootRef = React.useCallback( + (element: HTMLElement | null) => { + rootElementRef.current = element; + sizeRef(element); + }, + [sizeRef], + ); + const top = margin?.top ?? DEFAULT_CHART_MARGIN.top; + const right = margin?.right ?? DEFAULT_CHART_MARGIN.right; + const bottom = margin?.bottom ?? DEFAULT_CHART_MARGIN.bottom; + const left = margin?.left ?? DEFAULT_CHART_MARGIN.left; + const resolved = React.useMemo(() => ({ top, right, bottom, left }), [bottom, left, right, top]); + return { rootRef, rootElementRef, size, margin: resolved }; +} + +/** Coalesces pointer moves into at most one selection update per frame. */ +function useFramePointerUpdates(layout: unknown) { + const applyRef = React.useRef<(selection: TSelection | null) => void>(() => {}); + const pendingRef = React.useRef(undefined); + const frameRef = React.useRef(null); + const cancel = React.useCallback(() => { + pendingRef.current = undefined; + if (frameRef.current !== null) { + cancelAnimationFrame(frameRef.current); + frameRef.current = null; + } + }, []); + // A new layout invalidates a pending hit test. + React.useLayoutEffect(() => cancel, [cancel, layout]); + + const schedule = (selection: TSelection | null, apply: (selection: TSelection | null) => void) => { + pendingRef.current = selection; + applyRef.current = apply; + if (frameRef.current !== null) { + return; + } + frameRef.current = requestAnimationFrame(() => { + frameRef.current = null; + const pending = pendingRef.current; + pendingRef.current = undefined; + if (pending !== undefined) { + applyRef.current(pending); + } + }); + }; + const pending = () => pendingRef.current ?? null; + return { schedule, cancel, pending }; +} + +const formatCategoryKey = (category: string) => category; + +/** + * Owns selection for every chart type: the controlled value, the reducer, one pointer update per + * frame, touch select and outside dismissal, the remembered keyboard index, keys, activation, the + * announcement and the X ticks. The chart type's rules come in through `model`. + */ +export function useChartInstance< + TSelection extends ChartSelection, + TActive extends ChartActive, + TCategory extends ChartCategory, +>({ + frame, + layout, + model, + options, +}: Readonly<{ + frame: ChartFrame; + layout: ChartLayout; + model: SelectionModel; + options: ChartOptions; +}>): ChartInstance { + const { onActivate, formatCategory = formatCategoryKey } = options; + const { rootRef, rootElementRef, size } = frame; + const { categories, plot } = layout; + + const xTicks = React.useCallback( + ({ mode = 'category', format = formatCategoryKey }: XTicksOptions = {}): XTick[] => + selectXTicks({ + categories, + plot, + viewportWidth: size.width, + xAxis: mode === 'calendar' ? 'calendar' : undefined, + formatXTick: format, + }), + [categories, plot, size.width], + ); + + const [value, setValue] = useControllableState( + options.selection, + options.defaultSelection ?? null, + options.onSelectionChange, + ); + const [stored, setStored] = React.useState>(NO_SELECTION); + const state = reconcileSelection(stored, value); + const stateRef = React.useRef(state); + React.useLayoutEffect(() => { + stateRef.current = state; + }); + + const categoryByKey = React.useMemo( + () => new Map(categories.map(category => [category.key, category])), + [categories], + ); + const current = selectedState(state); + const currentCategory = current ? categoryByKey.get(current.category) : undefined; + const resolve = (selection: TSelection | null) => { + const category = selection ? categoryByKey.get(selection.category) : undefined; + return selection && category ? model.resolve(selection, category) : null; + }; + const selected = resolve(current?.selection ?? null); + // A selection whose category or value left the data reads as none until the user moves. + const valid = current && currentCategory && (current.selection === null || selected) ? current : null; + const messages = { ...DEFAULT_CHART_MESSAGES, ...options.messages }; + const announcement = getKeyboardAnnouncement( + valid, + valid?.selection ? selected : null, + currentCategory, + model, + formatCategory, + messages, + ); + const keyboardInstructions = getKeyboardInstructions(messages, model.verticalInstructions, !!onActivate); + const tooltipAnchor = + valid?.selection && currentCategory && selected ? model.anchor(valid.selection, currentCategory) : null; + + const lastIndexRef = React.useRef(0); + const selectedIndex = valid ? currentCategory?.datumIndex : undefined; + React.useLayoutEffect(() => { + if (selectedIndex !== undefined) { + lastIndexRef.current = selectedIndex; + } + }, [selectedIndex]); + const keyboardIndex = () => selectedIndex ?? lastIndexRef.current; + + const pointerUpdates = useFramePointerUpdates(layout); + + const dispatch = (action: SelectionAction) => { + if (action.type !== 'pointer') { + pointerUpdates.cancel(); + } + const previous = stateRef.current; + const next = selectionReducer(previous, action); + stateRef.current = next; + setStored(next); + const nextValue = toPublicSelection(next); + if (!sameSelection(toPublicSelection(previous), nextValue)) { + setValue(nextValue); + } + return next; + }; + const dispatchRef = React.useRef(dispatch); + React.useLayoutEffect(() => { + dispatchRef.current = dispatch; + }); + const select = React.useCallback((selection: TSelection) => { + dispatchRef.current({ type: 'select', selection }); + }, []); + const clear = React.useCallback(() => { + dispatchRef.current({ type: 'clear' }); + }, []); + + const surfaceRef = React.useRef(null); + // A removed surface fires no pointerleave or blur, so its removal ends what the user selected on it. + const attachSurface = React.useCallback((element: HTMLElement | null) => { + surfaceRef.current = element; + const state = stateRef.current; + if (!element && state.status === 'selected' && state.source !== 'external') { + dispatchRef.current({ type: 'clear' }); + } + }, []); + + // A tap fires no pointerleave or blur, so a tap anywhere else dismisses. + const hasPointerSelection = valid?.source === 'pointer'; + React.useEffect(() => { + if (!hasPointerSelection) { + return; + } + const dismissOutside = (event: PointerEvent) => { + const surface = surfaceRef.current; + if (!(event.target instanceof Node) || !surface?.contains(event.target)) { + clear(); + } + }; + document.addEventListener('pointerdown', dismissOutside, true); + return () => document.removeEventListener('pointerdown', dismissOutside, true); + }, [clear, hasPointerSelection]); + + const currentSelection = valid?.selection ?? null; + + const pointerSelection = (clientX: number, clientY: number) => { + const bounds = rootElementRef.current?.getBoundingClientRect(); + if (!bounds || bounds.width <= 0 || bounds.height <= 0) { + return null; + } + const point = { + x: ((clientX - bounds.left) / bounds.width) * size.width, + y: ((clientY - bounds.top) / bounds.height) * size.height, + }; + return model.hitTest(point, pointerUpdates.pending() ?? currentSelection); + }; + + const selectKeyboardIndex = (target: number, move: VerticalMove | undefined, from: TSelection | null) => { + const category = categories[Math.max(0, Math.min(categories.length - 1, target))]; + return dispatch({ + type: 'keyboard', + category: category?.key, + selection: category ? model.land(category, move, from) : null, + }); + }; + + type ActivationEvent = React.MouseEvent | React.KeyboardEvent; + const activate = (selection: TSelection | null, event: ActivationEvent) => { + const active = resolve(selection); + if (active) { + onActivate?.(active, event); + } + }; + + const activateKeyboardSelection = (event: ActivationEvent) => { + const dismissed = stateRef.current.status === 'dismissed'; + const next = selectKeyboardIndex(keyboardIndex(), undefined, currentSelection); + if (!dismissed) { + activate(toPublicSelection(next), event); + } + }; + + const { disabled = false } = options; + const reads = options.selection !== undefined || !!options.onSelectionChange || !!onActivate; + const handlers = (): React.HTMLAttributes => ({ + onPointerDown: event => { + event.preventDefault(); + // A tap fires no pointermove, so touch selects on contact and survives the pointerleave that + // follows the finger lifting. + if (event.pointerType !== 'touch') { + return; + } + pointerUpdates.cancel(); + dispatch({ type: 'pointer', selection: pointerSelection(event.clientX, event.clientY) }); + }, + onPointerLeave: event => { + if (event.pointerType !== 'touch') { + dispatch({ type: 'clear' }); + } + }, + onPointerCancel: () => { + dispatch({ type: 'clear' }); + }, + onPointerMove: event => { + pointerUpdates.schedule(pointerSelection(event.clientX, event.clientY), next => + dispatch({ type: 'pointer', selection: next }), + ); + }, + onFocus: () => { + selectKeyboardIndex(keyboardIndex(), undefined, null); + }, + onBlur: () => { + dispatch({ type: 'clear' }); + }, + onClick: event => { + // Assistive technology activates the chart with a synthetic click that has no coordinates. + if (event.detail === 0 && event.clientX === 0 && event.clientY === 0) { + activateKeyboardSelection(event); + return; + } + activate(pointerSelection(event.clientX, event.clientY), event); + }, + onKeyDown: event => { + const intent = getKeyIntent(event.key, keyboardIndex(), categories.length - 1, !!onActivate); + if (!intent) { + return; + } + event.preventDefault(); + if (intent.type === 'dismiss') { + dispatch({ type: 'dismiss' }); + } else if (intent.activate) { + activateKeyboardSelection(event); + } else { + selectKeyboardIndex(intent.index, intent.move, currentSelection); + } + }, + }); + const getInteractionProps = (props: ChartInteractionInput = {}): ChartInteractionProps => { + const own = { + ...(disabled ? null : handlers()), + ...model.surfaceAttributes(currentSelection), + 'aria-disabled': disabled ? (true as const) : undefined, + }; + return { + ...mergeProps<'div'>(own, props), + role: onActivate ? 'button' : 'group', + tabIndex: reads && !disabled ? 0 : undefined, + ref: attachSurface, + 'aria-disabled': own['aria-disabled'], + }; + }; + + return { + rootRef, + size, + plot, + categories, + xTicks, + selected, + tooltipAnchor, + announcement, + keyboardInstructions, + select, + clear, + getInteractionProps, + }; +} diff --git a/packages/mosaic/src/primitives/chart/internal/use-chart-size.ts b/packages/mosaic/src/primitives/chart/internal/use-chart-size.ts new file mode 100644 index 00000000000..bf28674fda2 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/internal/use-chart-size.ts @@ -0,0 +1,63 @@ +'use client'; + +import { useCallback, useLayoutEffect, useRef, useState } from 'react'; +import { flushSync } from 'react-dom'; + +import type { ChartSize } from '../types'; + +const EMPTY_SIZE: ChartSize = { width: 0, height: 0 }; + +const toHalfPixel = (value: number) => Math.round(value * 2) / 2; + +export function useChartSize() { + const observerRef = useRef(null); + const [size, setSize] = useState(EMPTY_SIZE); + + const disconnect = useCallback(() => { + observerRef.current?.disconnect(); + observerRef.current = null; + }, []); + + const ref = useCallback( + (element: TElement | null) => { + disconnect(); + if (!element) { + return; + } + let lastSize: ChartSize | undefined; + const accept = (width: number, height: number) => { + if (lastSize?.width === width && lastSize.height === height) { + return null; + } + lastSize = { width, height }; + return lastSize; + }; + observerRef.current = new ResizeObserver(entries => { + const entry = entries[entries.length - 1]; + const box = entry?.borderBoxSize?.[0]; + const next = accept( + toHalfPixel(box?.inlineSize ?? entry?.contentRect.width ?? 0), + toHalfPixel(box?.blockSize ?? entry?.contentRect.height ?? 0), + ); + if (next) { + // ResizeObserver runs before paint; committing now keeps the chart in step with its container. + flushSync(() => setSize(next)); + } + }); + observerRef.current.observe(element, { box: 'border-box' }); + // Measure now as well, so the first paint happens in the commit that attached the chart rather + // than at the next frame's ResizeObserver callback, after any effects the page runs on hydration. + // A scaled ancestor makes this differ from the layout size; the observer corrects it a frame later. + const rect = element.getBoundingClientRect(); + const initial = accept(toHalfPixel(rect.width), toHalfPixel(rect.height)); + if (initial) { + setSize(initial); + } + }, + [disconnect], + ); + + useLayoutEffect(() => disconnect, [disconnect]); + + return { ref, size } as const; +} diff --git a/packages/mosaic/src/primitives/chart/internal/x-ticks.ts b/packages/mosaic/src/primitives/chart/internal/x-ticks.ts new file mode 100644 index 00000000000..53cd469d15d --- /dev/null +++ b/packages/mosaic/src/primitives/chart/internal/x-ticks.ts @@ -0,0 +1,124 @@ +import type { XTick } from '../types'; +import { parseCalendarDates, selectCalendarTicks } from './calendar-ticks'; + +type XCategory = Readonly<{ key: string; center: number }>; + +const EDGE_INSET = 4; +const TARGET_SPACING = 56; +const MIN_LABEL_GAP = 8; + +type Plot = Readonly<{ x: number; width: number }>; + +type SelectXTicksOptions = Readonly<{ + categories: readonly XCategory[]; + plot: Plot; + viewportWidth: number; + xAxis?: 'calendar'; + formatXTick: (value: string) => string | null; + measure?: (label: string) => number; +}>; + +const toCategoryTick = ({ key, label, x, textAnchor }: Omit): XTick => ({ + key, + category: key, + label, + x, + textAnchor, +}); + +/** Approximates a 12px label without touching the DOM. */ +export const estimateLabelWidth = (label: string) => label.length * 8; + +function evenlySpacedIndexes(count: number, plotWidth: number) { + if (count <= 0) { + return []; + } + if (count === 1) { + return [0]; + } + const visibleCount = Math.min(count, Math.max(2, Math.floor(plotWidth / TARGET_SPACING))); + const stride = Math.ceil((count - 1) / (visibleCount - 1)); + const indexes = new Set(); + for (let index = 0; index < count; index += stride) { + indexes.add(index); + } + indexes.add(count - 1); + return Array.from(indexes); +} + +function clampToPlot(center: number, width: number, plot: Plot): Pick { + const leftEdge = plot.x + EDGE_INSET; + const rightEdge = plot.x + plot.width - EDGE_INSET; + if (center - width / 2 < leftEdge) { + return { x: leftEdge, textAnchor: 'start' }; + } + if (center + width / 2 > rightEdge) { + return { x: rightEdge, textAnchor: 'end' }; + } + return { x: center, textAnchor: 'middle' }; +} + +function selectCategoryTicks({ + categories, + plot, + formatXTick, + measure, +}: SelectXTicksOptions & { measure: (label: string) => number }): XTick[] { + const candidates = evenlySpacedIndexes(categories.length, plot.width).flatMap(datumIndex => { + const category = categories[datumIndex]; + if (!category) { + return []; + } + const label = formatXTick(category.key); + if (label === null) { + return []; + } + const width = measure(label); + const placement = clampToPlot(category.center, width, plot); + const left = + placement.x - (placement.textAnchor === 'end' ? width : placement.textAnchor === 'middle' ? width / 2 : 0); + return [{ key: category.key, label, ...placement, left, right: left + width }]; + }); + + const first = candidates[0]; + if (!first) { + return []; + } + const last = candidates.at(-1); + if (!last || last === first || last.left - first.right < MIN_LABEL_GAP) { + return [first].map(toCategoryTick); + } + const visible = [first]; + let right = first.right; + for (const tick of candidates.slice(1, -1)) { + if (tick.left - right >= MIN_LABEL_GAP && last.left - tick.right >= MIN_LABEL_GAP) { + visible.push(tick); + right = tick.right; + } + } + return [...visible, last].map(toCategoryTick); +} + +export function selectXTicks(options: SelectXTicksOptions): XTick[] { + const measure = options.measure ?? estimateLabelWidth; + const timestamps = + options.xAxis === 'calendar' ? parseCalendarDates(options.categories.map(category => category.key)) : null; + const calendarTicks = timestamps + ? selectCalendarTicks({ + timestamps, + centers: options.categories.map(category => category.center), + plot: options.plot, + viewportWidth: options.viewportWidth, + measure, + }) + : []; + if (calendarTicks.length === 0) { + return selectCategoryTicks({ ...options, measure }); + } + return calendarTicks.map(tick => ({ + key: `${tick.label}:${tick.coordinate}`, + category: null, + label: tick.label, + ...clampToPlot(tick.coordinate, measure(tick.label), options.plot), + })); +} diff --git a/packages/mosaic/src/primitives/chart/line-chart-contract.test-d.ts b/packages/mosaic/src/primitives/chart/line-chart-contract.test-d.ts new file mode 100644 index 00000000000..b4e8296448e --- /dev/null +++ b/packages/mosaic/src/primitives/chart/line-chart-contract.test-d.ts @@ -0,0 +1,72 @@ +import { describe, expectTypeOf, test } from 'vitest'; + +import type { BarChartInstance } from '.'; +import { nearestCategory, type SelectionModel } from './internal/selection'; +import type { useChartInstance } from './internal/use-chart-instance'; +import type { ChartRootProps, ChartTooltipProps } from './parts'; +import type { CartesianChartInstance, ChartActive, ChartCategory, ChartInstance, ChartSelection } from './types'; + +// A line chart and a donut sketched in types only, to prove the shared contract fits other chart +// types before their folders exist. A line's categories are points on a value axis; a donut's are +// slices with no value axis. Each selects a category and nothing else. + +type Row = Readonly<{ date: string; users: number }>; + +declare const LINE_LAYOUT: unique symbol; + +type LineChartInstance = CartesianChartInstance, ChartSelection> & + Readonly<{ [LINE_LAYOUT]: Readonly<{ lines: readonly Readonly<{ key: string; d: string }>[] }> }>; + +type DonutChartInstance = ChartInstance, ChartSelection>; + +const point = { key: '2026-01-05', datumIndex: 0, center: 120, x: 120, width: 0 } satisfies ChartCategory; +const points: ChartCategory[] = [point]; + +const lineModel = { + hitTest: ({ x }) => { + const category = points[nearestCategory(points, x)]; + return category ? { category: category.key } : null; + }, + land: category => ({ category: category.key }), + resolve: (selection, category) => ({ + category: selection.category, + datumIndex: category.datumIndex, + datum: { date: category.key, users: 0 }, + }), + describe: active => `Users ${active.datum.users}`, + verticalInstructions: '', + anchor: (_, category) => ({ x: category.center, y: 0 }), + surfaceAttributes: () => ({}), +} satisfies SelectionModel>; + +describe('other chart types on the shared contract', () => { + test('a point is a category with no width', () => { + expectTypeOf(point).toExtend(); + }); + + test('a selection model with no Up and Down rules satisfies the engine', () => { + expectTypeOf(lineModel).toExtend>>(); + }); + + test('the engine builds an instance without a value axis, which the chart type adds', () => { + expectTypeOf, ChartCategory>>>().toEqualTypeOf< + ChartInstance, ChartSelection> + >(); + expectTypeOf().not.toHaveProperty('scaleY'); + expectTypeOf['scaleY']>().toEqualTypeOf<(value: number) => number>(); + }); + + test('Chart.Root takes a line chart, a donut and a bar chart without a cast', () => { + expectTypeOf().toExtend(); + expectTypeOf().toExtend(); + expectTypeOf>().toExtend(); + }); + + test('the chart a shared part holds cannot select', () => { + expectTypeOf().parameter(0).toBeNever(); + }); + + test('a line tooltip reads its rows', () => { + expectTypeOf>['children']>().parameter(0).toEqualTypeOf>(); + }); +}); diff --git a/packages/mosaic/src/primitives/chart/parts.ts b/packages/mosaic/src/primitives/chart/parts.ts new file mode 100644 index 00000000000..8047f6dc07e --- /dev/null +++ b/packages/mosaic/src/primitives/chart/parts.ts @@ -0,0 +1,18 @@ +export { type ChartRootProps, ChartRoot as Root } from './chart-root'; +export { type ChartGridProps, ChartGrid as Grid } from './chart-grid'; +export { type ChartYLineProps, ChartYLine as YLine } from './chart-y-line'; +export { type ChartYAxisProps, type ChartYTickItem, ChartYAxis as YAxis } from './chart-y-axis'; +export { type ChartYTickProps, ChartYTick as YTick } from './chart-y-tick'; +export { type ChartXAxisProps, ChartXAxis as XAxis } from './chart-x-axis'; +export { type ChartXTickProps, ChartXTick as XTick } from './chart-x-tick'; +export { type ChartSelectionProps, ChartSelection as Selection } from './chart-selection'; +export { type ChartCursorProps, ChartCursor as Cursor } from './chart-cursor'; +export { type ChartTooltipProps, ChartTooltip as Tooltip } from './chart-tooltip'; +export { useBarChart, type UseBarChartOptions } from './bars/use-bar-chart'; +export { type ChartBarsProps, ChartBars as Bars } from './bars/chart-bars'; +export { type ChartBarProps, ChartBar as Bar } from './bars/chart-bar'; +export { + type ChartProjectionOutlineProps, + ChartProjectionOutline as ProjectionOutline, +} from './bars/chart-projection-outline'; +export { CanvasRenderError } from './bars/bar-canvas-error'; diff --git a/packages/mosaic/src/primitives/chart/types.ts b/packages/mosaic/src/primitives/chart/types.ts new file mode 100644 index 00000000000..48447aa59d0 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/types.ts @@ -0,0 +1,161 @@ +import type React from 'react'; + +export type ChartSize = Readonly<{ width: number; height: number }>; + +export type ChartMargin = Readonly<{ + top: number; + right: number; + bottom: number; + left: number; +}>; + +export type ChartPlot = Readonly<{ + x: number; + y: number; + width: number; + height: number; +}>; + +export type ChartTick = Readonly<{ value: number; y: number }>; + +/** A point in chart coordinates, relative to the top left of `Chart.Root`. */ +export type ChartPoint = Readonly<{ x: number; y: number }>; + +/** + * One datum's place on the X axis. A bar chart gives each category a band; a point chart gives it a + * point, so `width` is 0. Shared parts read only these numbers. + */ +export type ChartCategory = Readonly<{ + key: string; + datumIndex: number; + /** The pointer snaps to the nearest center. Ticks label it and the tooltip anchors on it. */ + center: number; + /** Left edge of the extent the category's marks occupy. `Chart.Cursor` covers it. */ + x: number; + width: number; +}>; + +/** What a selection names. Each chart type extends it with what else a user can pick there. */ +export type ChartSelection = Readonly<{ category: string }>; + +/** A selection resolved against the current data. */ +export type ChartActive = ChartSelection & Readonly<{ datumIndex: number; datum: TDatum }>; + +/** Screen reader text every chart type reads out. Pass localized strings; each defaults to English. */ +export type ChartMessages = Readonly<{ + /** How Left, Right, Home and End move. */ + navigate: string; + /** How Enter and Space open the selected period. Read only when the hook has `onActivate`. */ + activate: string; + /** How Escape dismisses the selection. */ + dismiss: string; + /** Announced when the keyboard lands on a period with nothing to select. */ + noValues: string; +}>; + +/** Options every chart-type hook takes. */ +export interface ChartOptions { + /** Space around the plot for the axes. Default: 8, 16, 36, 52 (top, right, bottom, left) */ + margin?: Partial; + /** The selection, or null. Leave it undefined to let the chart hold the selection. */ + selection?: TSelection | null; + /** The selection the chart starts with when it holds the selection. Default: null */ + defaultSelection?: TSelection | null; + /** Called when the user or `select`/`clear` changes the selection. */ + onSelectionChange?: (selection: TSelection | null) => void; + /** + * Called on click, Enter or Space, with the event that activated it. Makes the interaction surface + * a button. + */ + onActivate?: (active: TActive, event: React.MouseEvent | React.KeyboardEvent) => void; + /** Ignores the pointer and keyboard and leaves the tab order. `select` and `selection` still apply. Default: false */ + disabled?: boolean; + /** Names a category in announcements. Default: the category key */ + formatCategory?: (category: string) => string | null; + /** Formats a value in announcements. Default: `String(value)` */ + formatValue?: (value: number) => string; + /** Screen reader text. Default: English */ + messages?: Partial; +} + +export type XTick = Readonly<{ + key: string; + /** The labelled category key, or null for a calendar boundary label. */ + category: string | null; + label: string; + x: number; + textAnchor: 'start' | 'middle' | 'end'; +}>; + +export type XTickMode = 'category' | 'calendar'; + +export type XTicksOptions = Readonly<{ + /** + * `category` thins category labels to fit. `calendar` labels calendar boundaries for long ranges; + * category keys must be UTC dates. Default: 'category' + */ + mode?: XTickMode; + /** Returns the label for a category key, or null to omit it. Default: the key */ + format?: (key: string) => string | null; +}>; + +/** Props for the element that takes pointer and keyboard selection, usually the plot. */ +export type ChartInteractionProps = Omit, 'role' | 'tabIndex'> & + Readonly<{ + role: 'button' | 'group'; + /** 0 while something reads the selection: `selection`, `onSelectionChange` or `onActivate`. Never while disabled. */ + tabIndex: 0 | undefined; + /** Removing the surface ends a pointer or keyboard selection, as leaving or blurring it does. */ + ref: React.RefCallback; + 'aria-disabled': true | undefined; + /** State the chart type exposes on the surface, such as `data-active-section`. */ + [attribute: `data-${string}`]: string | undefined; + }>; + +/** Props a custom surface passes to `getInteractionProps`. Its handlers run after the chart's. */ +export type ChartInteractionInput = Omit, 'role' | 'tabIndex'> & + Readonly<{ [attribute: `data-${string}`]: string | undefined }>; + +/** + * The measured layout and selection of one chart, returned by a chart-type hook such as + * `Chart.useBarChart`. `TSelection` defaults to `never`, so `Chart.Root` takes any chart and the + * shared parts cannot call `select`. + */ +export type ChartInstance< + TActive extends ChartActive = ChartActive, + TSelection extends ChartSelection = never, + TCategory extends ChartCategory = ChartCategory, +> = Readonly<{ + /** Measures the chart. `Chart.Root` attaches it. */ + rootRef: (element: HTMLElement | null) => void; + /** The measured container, zero until the first measurement. */ + size: ChartSize; + plot: ChartPlot; + categories: readonly TCategory[]; + xTicks: (options?: XTicksOptions) => XTick[]; + /** The selection in the current data, or null. */ + selected: TActive | null; + /** Where a tooltip for `selected` points, in chart coordinates. */ + tooltipAnchor: ChartPoint | null; + /** The text of the keyboard selection's status announcement. */ + announcement: string; + /** The keys the chart answers to, for the visually hidden description. */ + keyboardInstructions: string; + select: (selection: TSelection) => void; + clear: () => void; + getInteractionProps: (props?: ChartInteractionInput) => ChartInteractionProps; +}>; + +/** + * A chart with a value axis, such as bars or lines. `Chart.Grid`, `Chart.YAxis` and `Chart.YLine` + * need one; a chart without a value axis, such as a donut, is a plain `ChartInstance`. + */ +export type CartesianChartInstance< + TActive extends ChartActive = ChartActive, + TSelection extends ChartSelection = never, + TCategory extends ChartCategory = ChartCategory, +> = ChartInstance & + Readonly<{ + scaleY: (value: number) => number; + yTicks: readonly ChartTick[]; + }>; diff --git a/packages/mosaic/tsdown.config.mts b/packages/mosaic/tsdown.config.mts index 9417bb5801a..ea35fcd5a65 100644 --- a/packages/mosaic/tsdown.config.mts +++ b/packages/mosaic/tsdown.config.mts @@ -88,6 +88,7 @@ export default defineConfig({ 'primitives/accordion': './src/primitives/accordion/index.ts', 'primitives/autocomplete': './src/primitives/autocomplete/index.ts', 'primitives/button': './src/primitives/button/index.ts', + 'primitives/chart': './src/primitives/chart/index.ts', 'primitives/collapsible': './src/primitives/collapsible/index.ts', 'primitives/combobox': './src/primitives/combobox/index.ts', 'primitives/dialog': './src/primitives/dialog/index.ts', diff --git a/packages/swingset/src/components/DocsViewer.tsx b/packages/swingset/src/components/DocsViewer.tsx index 54f30f1d696..eeb58fd1562 100644 --- a/packages/swingset/src/components/DocsViewer.tsx +++ b/packages/swingset/src/components/DocsViewer.tsx @@ -140,6 +140,7 @@ const docModules: Record> = { // Headless primitives — alphabetical. accordion: dynamic(() => import('../stories/accordion.mdx')), autocomplete: dynamic(() => import('../stories/autocomplete.mdx')), + chart: dynamic(() => import('../stories/chart.mdx')), combobox: dynamic(() => import('../stories/combobox.primitive.mdx')), collapsible: dynamic(() => import('../stories/collapsible.mdx')), dialog: dynamic(() => import('../stories/dialog.mdx')), diff --git a/packages/swingset/src/lib/registry.ts b/packages/swingset/src/lib/registry.ts index 2e43d9584cc..6c4c3a80723 100644 --- a/packages/swingset/src/lib/registry.ts +++ b/packages/swingset/src/lib/registry.ts @@ -58,6 +58,7 @@ import { import { Disabled, meta as buttonMeta, Primary, Sizes } from '../stories/button.stories'; import { Default as CaptchaDefault, meta as captchaMeta } from '../stories/captcha.stories'; import { Default as CardDefault, meta as cardComponentMeta } from '../stories/card.component.stories'; +import { meta as chartMeta } from '../stories/chart.stories'; import { Default as CheckboxDefault, meta as checkboxMeta, @@ -1147,6 +1148,7 @@ const iconFrameModule: StoryModule = { // `` embeds in the MDX, which import the stories module directly. const accordionModule: StoryModule = { meta: accordionMeta }; const autocompleteModule: StoryModule = { meta: autocompleteMeta }; +const chartModule: StoryModule = { meta: chartMeta }; const comboboxPrimitiveModule: StoryModule = { meta: comboboxPrimitiveMeta }; const collapsibleModule: StoryModule = { meta: collapsibleMeta }; const dialogModule: StoryModule = { meta: dialogMeta }; @@ -1653,6 +1655,7 @@ export const registry: StoryModule[] = [ // Primitives accordionModule, autocompleteModule, + chartModule, comboboxPrimitiveModule, collapsibleModule, dialogModule, diff --git a/packages/swingset/src/stories/chart.mdx b/packages/swingset/src/stories/chart.mdx new file mode 100644 index 00000000000..6756d88d925 --- /dev/null +++ b/packages/swingset/src/stories/chart.mdx @@ -0,0 +1,232 @@ +import * as ChartStories from './chart.stories'; + +# Chart + +A stacked bar chart over a category or time axis, with values above and below zero. It is a +**headless** primitive: `Chart.useBarChart` owns the layout and selection, `Chart.Bars` and +`Chart.Bar` paint the bars, and the shared parts draw the root, grid, axes, lines, selection, +cursor and tooltip from the chart object the hook returns. D3 computes the stacks and scales, +Canvas paints the bars, SVG draws the grid, axes and marks, and the primitive handles pointer and +keyboard selection. +It ships **no styles**. Every part, including the Canvas bars, takes its appearance from your CSS. + +## Example + +Move the pointer over the chart, or focus it and use the arrow keys, to select a week. The chart is +unstyled, so the bars take the inherited text color and the grid and zero lines have no stroke. + + + +## Usage + +```tsx +import { type ActiveBar, Chart } from '@clerk/mosaic/primitives/chart'; + +const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }); + + + + {ticks => + ticks.map(tick => ( + + )) + } + + + + + + + + {ticks => + ticks.map(tick => ( + + )) + } + + + {ticks => + ticks.map(tick => ( + + )) + } + + + + >>{active => } + +; +``` + +`series` is an ordered list of `{ key, value }`, where `value` reads a number from a row. `index` +returns each row's unique category key. Memoize `series`, `index` and `isBarActive`. + +### Dimming bars + +`isBarActive` marks every other bar `data-inactive`, so CSS can dim it. Control the selection to +dim every bar outside the selected section: + +```tsx +const [selection, setSelection] = useState(null); +const isBarActive = useCallback( + (bar: BarIdentity) => + !selection || (bar.datum.week === selection.category && bar.positive === (selection.section === 'positive')), + [selection], +); +const chart = Chart.useBarChart({ data, series, index, selection, onSelectionChange: setSelection, isBarActive }); +``` + +### Projection + +`projection` draws a projected total above one category's positive stack. The fill is painted +with `Chart.Bar`'s `data-projection` color, and the outline with `Chart.ProjectionOutline`'s +`stroke`, `stroke-width` and `stroke-dasharray`. The Canvas paints both, so they stay aligned at any +pixel ratio. +It is drawn only when `value` is above that category's stack. + +```tsx +const chart = Chart.useBarChart({ + data, + series, + index, + projection: { datumIndex: data.length - 1, value: 130 }, +}); +``` + +## Parts + +| Part | Default Element | Description | +| ------------------------- | --------------- | -------------------------------------------------------------------- | +| `Chart.Root` | `
` | Attaches the chart's measurement and provides the chart to the parts | +| `Chart.Grid` | `` | Holds the grid lines | +| `Chart.YLine` | `` | One line across the plot at a Y value, such as a tick or zero | +| `Chart.Bars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | +| `Chart.Bar` | `` | Hidden. Its computed style paints the bars | +| `Chart.ProjectionOutline` | `` | Hidden. Its computed stroke outlines the projected bar | +| `Chart.YAxis` | `` | Holds the Y tick labels | +| `Chart.YTick` | `` | One Y tick label | +| `Chart.XAxis` | `` | Holds the category labels | +| `Chart.XTick` | `` | One category label | +| `Chart.Selection` | `
` | Pointer and keyboard selection | +| `Chart.Cursor` | `
` | Covers the selected category's band | +| `Chart.Tooltip` | `
` | The tooltip for the selected bar, portaled | + +Every part comes from `@clerk/mosaic/primitives/chart`. +Every part accepts a `render` prop and the standard attributes of its default element. Every part +throws outside `Chart.Root`, and `Chart.Bars` also throws for a chart that did not come +from `Chart.useBarChart`. `Chart.Bar` and `Chart.ProjectionOutline` throw outside +`Chart.Bars`, and `Chart.Cursor` and `Chart.Tooltip` throw outside `Chart.Selection`. + +## Props + +### `Chart.useBarChart` + +| Prop | Type | Default | Description | +| ------------------------------ | ------------------------------------------------------------ | -------------------------- | ------------------------------------------------------ | +| data | readonly TDatum[] | — (required) | The rows | +| series | readonly BarSeries<TDatum>[] | — (required) | Stack order and each series' value | +| index | (datum: TDatum, index: number) => string | — (required) | A unique, stable category key | +| categoryGap | number | 0.28 | Fraction of each band left empty | +| margin | Partial<ChartMargin> | 8, 16, 36, 52 | Space for the axes: top, right, bottom, left | +| projection | { datumIndex: number; value: number } | — | A projected total, drawn when it rises above its stack | +| isBarActive | (bar: BarIdentity<TDatum>) => boolean | every bar active | Returns false for a bar styled through `data-inactive` | +| selection | BarSelection \| null | uncontrolled | The selected category and section | +| onSelectionChange | (selection: BarSelection \| null) => void | — | Called when the selection changes | +| onActivate | (active: ActiveBar<TDatum>) => void | — | Called on click, Enter or Space | +| formatCategory | (key: string) => string \| null | the key | Names a period in keyboard announcements | + +The hook returns the chart object: `rootRef`, `size`, `plot`, `scaleY`, `categories`, `yTicks`, +`xTicks(options)`, `selected`, `tooltipAnchor`, `announcement`, `keyboardInstructions`, `select`, +`clear` and `getInteractionProps()`. Each category carries `key`, `datumIndex`, `center`, and its +band as `x` and `width`. Render from it directly to skip the parts. + +### `Chart.Root` + +| Prop | Type | Default | Description | +| ----------------------- | ----------------------------- | ---------------- | -------------------------------------------------- | +| chart | ChartInstance | — (required) | The result of a chart-type hook | +| aria-label | string | — (required) | Labels the chart image and the interaction surface | +| height | number \| string | 500 | The container height | + +### `Chart.YLine` + +| Prop | Type | Default | Description | +| ------------------ | ------------------- | ------------ | ----------------------------------------------- | +| value | number | — (required) | The Y value the line marks, such as a tick or 0 | + +### `Chart.XAxis` + +| Prop | Type | Default | Description | +| ------------------- | -------------------------------------------- | ----------------------- | -------------------------------------------------------------- | +| ticks | 'category' \| 'calendar' | 'category' | `calendar` labels calendar boundaries for long UTC date ranges | +| format | (key: string) => string \| null | the key | Labels a category, or returns null to omit it | + +`Chart.YAxis` takes `format` (`(value: number) => ReactNode`, locale number by default). +`Chart.Grid`, `Chart.YAxis` and `Chart.XAxis` take a `children` function that receives their +items. `Chart.YTick` and `Chart.XTick` take `tick`. + +### `Chart.Tooltip` + +| Prop | Type | Default | Description | +| ------------------------ | ------------------------------------------------- | ------------ | ------------------------------------------- | +| children | (active: TActive) => ReactNode | — (required) | Content for the selected bar; null hides it | +| boundaryRef | RefObject<HTMLElement \| null> | the chart | Element the tooltip stays inside | + +Name the active type the hook selects: `>>`. + +## Styling + +`Chart.Bar` styles the Canvas. Before each paint the chart sets these attributes on it, reads +its computed `color`, and paints with it: + +| Attribute | Description | +| ----------------- | -------------------------------- | +| `data-series` | The series key of the bar | +| `data-inactive` | The bar is outside `isBarActive` | +| `data-projection` | The projection fill | + +Its `max-width` caps the bar width, `row-gap` sets the gap between segments, its top corner radius +rounds a stack's outer end and its bottom corner radius rounds every other corner. Without +`Chart.Bar`, nothing is painted. + +| Attribute | Applies To | Description | +| ----------------------------- | ---------- | -------------------------------------------------------------- | +| `data-chart-interaction-mode` | Root | `pending`, `interactive` or `visual-only` | +| `data-active` | XTick | Present while the tick's period is selected | +| `data-active-section` | Selection | `positive` or `negative` on the interaction surface | +| `data-side` | Tooltip | `left` or `right` of the period, or `bottom` when pinned | +| `data-open` / `data-closed` | Tooltip | Open state, with `data-starting-style` and `data-ending-style` | + +```css +.bar[data-series='signups'] { + --bar: #7c3aed; +} +.bar { + max-width: 32px; + row-gap: 2px; + border-radius: 4px 4px 2px 2px; + color: var(--bar); +} +.bar[data-inactive] { + color: color-mix(in srgb, var(--bar) 40%, transparent); +} +.bar[data-projection] { + color: #d4d4d4; +} +``` diff --git a/packages/swingset/src/stories/chart.stories.tsx b/packages/swingset/src/stories/chart.stories.tsx new file mode 100644 index 00000000000..ba440b58543 --- /dev/null +++ b/packages/swingset/src/stories/chart.stories.tsx @@ -0,0 +1,165 @@ +'use client'; + +import { type ActiveBar, Chart } from '@clerk/mosaic/primitives/chart'; + +import type { StoryMeta } from '@/lib/types'; + +export const meta: StoryMeta = { + group: 'Primitives', + status: 'wip', + title: 'Chart', + label: 'Chart', + source: 'packages/mosaic/src/primitives/chart/index.ts', +}; + +/** Weekly active users, as Dashboard's overview reports them. */ +const growth = [ + { + week: '2026-01-05', + retained: 120, + reactivated: 18, + new: 34, + retainedChurned: -22, + reactivatedChurned: -9, + newChurned: -15, + }, + { + week: '2026-01-12', + retained: 128, + reactivated: 22, + new: 41, + retainedChurned: -25, + reactivatedChurned: -11, + newChurned: -18, + }, + { + week: '2026-01-19', + retained: 131, + reactivated: 19, + new: 38, + retainedChurned: -24, + reactivatedChurned: -12, + newChurned: -16, + }, + { + week: '2026-01-26', + retained: 137, + reactivated: 25, + new: 46, + retainedChurned: -27, + reactivatedChurned: -10, + newChurned: -20, + }, + { + week: '2026-02-02', + retained: 142, + reactivated: 21, + new: 43, + retainedChurned: -29, + reactivatedChurned: -13, + newChurned: -19, + }, + { + week: '2026-02-09', + retained: 150, + reactivated: 27, + new: 52, + retainedChurned: -28, + reactivatedChurned: -12, + newChurned: -22, + }, + { + week: '2026-02-16', + retained: 155, + reactivated: 24, + new: 49, + retainedChurned: -31, + reactivatedChurned: -14, + newChurned: -21, + }, + { + week: '2026-02-23', + retained: 158, + reactivated: 14, + new: 27, + // Churn is known only once the week ends, so the week in progress has none. + retainedChurned: null, + reactivatedChurned: null, + newChurned: null, + }, +]; + +type GrowthRow = (typeof growth)[number]; + +const series = [ + { key: 'retained', value: (row: GrowthRow) => row.retained }, + { key: 'reactivated', value: (row: GrowthRow) => row.reactivated }, + { key: 'new', value: (row: GrowthRow) => row.new }, + { key: 'retainedChurned', value: (row: GrowthRow) => row.retainedChurned }, + { key: 'reactivatedChurned', value: (row: GrowthRow) => row.reactivatedChurned }, + { key: 'newChurned', value: (row: GrowthRow) => row.newChurned }, +]; + +const getWeek = (row: GrowthRow) => row.week; + +export function Default() { + const chart = Chart.useBarChart({ data: growth, series, index: getWeek }); + return ( + + + {ticks => + ticks.map(tick => ( + + )) + } + + + + + + + {ticks => + ticks.map(tick => ( + + )) + } + + + {ticks => + ticks.map(tick => ( + + )) + } + + + + >> + {({ datum }) => ( + <> +

{datum.week}

+ {series.map(s => ( +

+ {s.key}: {s.value(datum)} +

+ ))} + + )} + +
+
+ ); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 336f102d0e7..b6078dd14da 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -969,6 +969,12 @@ importers: '@floating-ui/react': specifier: catalog:repo version: 0.27.20(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + d3-scale: + specifier: 4.0.2 + version: 4.0.2 + d3-shape: + specifier: 3.2.0 + version: 3.2.0 devDependencies: '@clerk/clerk-js': specifier: workspace:^ @@ -997,6 +1003,12 @@ importers: '@testing-library/user-event': specifier: ^14.6.5 version: 14.6.7(@testing-library/dom@10.4.1) + '@types/d3-scale': + specifier: 4.0.9 + version: 4.0.9 + '@types/d3-shape': + specifier: 3.1.7 + version: 3.1.7 '@types/react': specifier: catalog:react version: 18.3.28 @@ -6294,6 +6306,18 @@ packages: '@types/cors@2.8.19': resolution: {integrity: sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==} + '@types/d3-path@3.1.1': + resolution: {integrity: sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==} + + '@types/d3-scale@4.0.9': + resolution: {integrity: sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==} + + '@types/d3-shape@3.1.7': + resolution: {integrity: sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==} + + '@types/d3-time@3.0.4': + resolution: {integrity: sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==} + '@types/debug@4.1.12': resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==} @@ -8481,6 +8505,42 @@ packages: engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} hasBin: true + d3-array@3.2.5: + resolution: {integrity: sha512-Th8qGXoBalmWsstpkuhmBuTsBQIFqYOJtjlBvNVvBfJ8E3uYusBUwUR8HU20U0qKKQkgCvKyR1YjiozWadk5QA==} + engines: {node: '>=12'} + + d3-color@3.1.1: + resolution: {integrity: sha512-lfab8x0Bj0UO7SNsY8dZSbNIA6ipbkE3X0NG9nqjCu6CfCHZseuDnOSJY7hidKrjpP++i1M2qT+FlAdPKYRilA==} + engines: {node: '>=12'} + + d3-format@3.1.3: + resolution: {integrity: sha512-+F+/49swqmGuQJmSKnVMIDH/QkEFV5li9QRj0xm/KhyAUBv099O5PrvpQFxBp24PYph17Mnvt9mjKQV0ii0nMA==} + engines: {node: '>=12'} + + d3-interpolate@3.0.2: + resolution: {integrity: sha512-IRzGU62DtxhvsnSTWMQIdnoZ6gA+BCWwBon1EJI6SjoN595799b6z/QRBzXfFhE8iupUPp3042yBNo0STPqnzQ==} + engines: {node: '>=12'} + + d3-path@3.1.1: + resolution: {integrity: sha512-jsbgV8zIT38ReB9O7X7gcLndTQRONSqNNd+oGIaTBdUug4r5jFmp0N6RY9R5GWbdUDucn0qoTGyfjapT4tDhcg==} + engines: {node: '>=12'} + + d3-scale@4.0.2: + resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==} + engines: {node: '>=12'} + + d3-shape@3.2.0: + resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==} + engines: {node: '>=12'} + + d3-time-format@4.1.1: + resolution: {integrity: sha512-22XaqjyCjpqgda20erhsOjGmC3vvYwTNYniKAd45W5UWLDF43moeOuV9qYpRqobIlsnK0UhnKZjUUJm3VgORUA==} + engines: {node: '>=12'} + + d3-time@3.1.1: + resolution: {integrity: sha512-Ze7rjrhMzdeulh0/hjcfFj7XLAHOfowtEMfsoG6DU866HPynQNW7Wfen6hzXcqKTv8XzxvF6Hzr5XD6bMHr2ug==} + engines: {node: '>=12'} + damerau-levenshtein@1.0.8: resolution: {integrity: sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==} @@ -10360,6 +10420,10 @@ packages: resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==} engines: {node: '>= 0.4'} + internmap@2.0.3: + resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==} + engines: {node: '>=12'} + invariant@2.2.4: resolution: {integrity: sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==} @@ -21298,6 +21362,18 @@ snapshots: dependencies: '@types/node': 22.20.1 + '@types/d3-path@3.1.1': {} + + '@types/d3-scale@4.0.9': + dependencies: + '@types/d3-time': 3.0.4 + + '@types/d3-shape@3.1.7': + dependencies: + '@types/d3-path': 3.1.1 + + '@types/d3-time@3.0.4': {} + '@types/debug@4.1.12': dependencies: '@types/ms': 2.1.0 @@ -23921,6 +23997,40 @@ snapshots: untildify: 4.0.0 yauzl: 2.10.0 + d3-array@3.2.5: + dependencies: + internmap: 2.0.3 + + d3-color@3.1.1: {} + + d3-format@3.1.3: {} + + d3-interpolate@3.0.2: + dependencies: + d3-color: 3.1.1 + + d3-path@3.1.1: {} + + d3-scale@4.0.2: + dependencies: + d3-array: 3.2.5 + d3-format: 3.1.3 + d3-interpolate: 3.0.2 + d3-time: 3.1.1 + d3-time-format: 4.1.1 + + d3-shape@3.2.0: + dependencies: + d3-path: 3.1.1 + + d3-time-format@4.1.1: + dependencies: + d3-time: 3.1.1 + + d3-time@3.1.1: + dependencies: + d3-array: 3.2.5 + damerau-levenshtein@1.0.8: {} dashdash@1.14.1: @@ -26304,6 +26414,8 @@ snapshots: hasown: 2.0.4 side-channel: 1.1.0 + internmap@2.0.3: {} + invariant@2.2.4: dependencies: loose-envify: 1.4.0