Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(charts): add ScatterChart to quill-charts (#81127)

Sam Penningtonaba988f1b754
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4186f60f124a..56c7df973f3c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -20,6 +20,26 @@ snapshots:
hash: v1.k794b7964.8e7770037014d788ef5b7299b6b2f834c2afcad14dd6c6033ddd8ac885faa1c6.buSflXKIcQC5dcm7fbQWsczrZY8TleOkvO86ugYW8yw
charts-heatmap--linear-color-scale--light:
hash: v1.k794b7964.c94c02704b7f9b4972f811336d019e15b77cff047551902ca74d65c1571ea6ff.PA6k_wyPYr-SNYm1-Mv8sa0DFCLb2-8QxOVNlDn4hE8
+ charts-scatterchart--clusters-with-centroids--dark:
+ hash: v1.k794b7964.21db57f09c276546fb27d3a6ba87bdb6e91c323ea1070df94f9ab87a8c1945d3.tANHwlLV16_HsvrEm1NqaeZNbmXRJRRk1P26nJ1hH6c
+ charts-scatterchart--clusters-with-centroids--light:
+ hash: v1.k794b7964.03ab0bc96065b4d9fd29c44294a5ca9fe190888bf2b25d62781e3a12ee5cc28c.Xy62i5CD7gue5KBERU9SjmQSiUV74Egkhqr8spYc860
+ charts-scatterchart--default--dark:
+ hash: v1.k794b7964.aebd76878009b31fe2b80abc4e763126c03de0f30720987699655562b66e3c20.fnDgKQRhUD2VHDe1F4Y2i2R-8ezNHmywjBC9c8j22Ug
+ charts-scatterchart--default--light:
+ hash: v1.k794b7964.cb01f3479b7f8c16fc97c63f3b1ed50a9ad0b3add055c8c34be783af33528a54.iKjjzFL-X7IH43v6VBoH5NDgBY8kFJNobPSGixUoZF8
+ charts-scatterchart--host-chrome--dark:
+ hash: v1.k794b7964.0cb579a6053bad39bf97315f2786192cca1ac72365b562366f060f1933a960aa.XqEqyyhRx6TR3_j7P74hBJDh3YntsUt4Ob0q7AB41C0
+ charts-scatterchart--host-chrome--light:
+ hash: v1.k794b7964.c7eadd07aadab92bf308c2dd24717d65acca0ee337d84172093e3cba44204851.1mt2G1j78u-of7RjwAlND--A6SCVQanxAWBORROMXkg
+ charts-scatterchart--log-scales--dark:
+ hash: v1.k794b7964.d2d05a7fe8441d56372fe8197954f9d10ed8b3d3822b01333e4f75ec0adfc012.DXnKqZq_G6CC3Y-PZhUtBMbTooMHmBc7Wo6bPgyltvE
+ charts-scatterchart--log-scales--light:
+ hash: v1.k794b7964.f2f83cf6a99be2ae5faba7dc8db617a78fa6d037bb9c28b0fd88f90b8ae291bd.8yH79camnLhL5YEVVTyB5YhEedP879UtEDg7d1UR6ZY
+ charts-scatterchart--multiple-series--dark:
+ hash: v1.k794b7964.814e966199ad4afdc5b65654bfa99d4b989f6ea7a1fb95f5ba9cb27f51d49723.5k5z4yZFuEgVgKOj36M_XSN5PTSqJ6C0d90l1CHw8YY
+ charts-scatterchart--multiple-series--light:
+ hash: v1.k794b7964.687da6d6d700f2ca42e09504d32be843fa131cf829abdd331e4a3bf7c03f385a.xgZefYbeMslA7TIrSIqk8AgQGyqHCgaiRo0KfAEB69M
components-account-project-switcher--no-pending-invite--dark:
hash: v1.k794b7964.ddbb5d27187cb1eb9341734e0b780c762cdfbc09aae81833c970369bd7ad4f32.3HNFMfb4Lflcg3uKD1-KNl09d3leMhmfuhR2WVLjLRE
components-account-project-switcher--no-pending-invite--light:
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index c3ce313336ce..e4e0d921a5af 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -7,6 +7,7 @@ Quick-reference for AI agents using `@posthog/quill-charts`. Canvas-rendered cha
| Chart | Use when |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| LineChart | Categorical x-axis trends; area fills, fill-between (confidence ribbons) |
+| ScatterChart | Two continuous numeric axes — one marker per `{ x, y }` point, no connecting line. Takes `series` of `points` instead of `series`/`labels`; per-axis linear/log scale and pinned domain, per-series shape and color, drag-to-select |
| BarChart | Categorical comparisons — `barLayout: 'stacked' \| 'grouped' \| 'percent'`, `axisOrientation: 'horizontal'` for horizontal bars; end-cap rounding via top-level `barCornerRadius` (the same key across the time-series/combo configs) |
| FunnelChart | Funnel steps as grouped vertical bars over a hatched drop-off track — one band per step, one bar per variant, valued as percent-of-first-step (0–100) |
| ComboChart | Mixed bar/line/area series on one band x-axis — set `Series.type`; vertical-only, `barLayout: 'stacked' \| 'grouped' \| 'percent'` (percent stacks bar series to 100%; a line/area series needs its own `yAxisId: 'right'` axis — one sharing the bars' axis can't plot raw values against their [0,1] scale) |
@@ -102,7 +103,8 @@ Safari is the exception: it never fires `contextrestored`, so a context lost the
- y-axis baseline: defaults to clamping a non-negative axis down to 0 (matching the classic insight axis). To float the axis to its data range instead — zooming in on the variation — set `yAxis.startAtZero: false` on `TimeSeriesLineChart`, or `config.floatBaseline: true` on the lower-level `LineChart`. Ignored on a log scale (no zero baseline) and applied to the primary axis only. Bar charts always draw from a zero baseline, so the flag is a no-op there.
- Dual / multi y-axis: give a series a `yAxisId` to scale it against a second axis. On `TimeSeriesLineChart`, pass `config.yAxis` as an **array** — one `YAxisConfig` per axis — to format/scale each axis independently: set `id` (matches `Series.yAxisId`; first entry defaults to `'left'`), `position` (`'left'`/`'right'`; first entry defaults to `'left'`, the rest to `'right'`), and the usual `scale`/`format`/`tickFormatter`/`label`/`showGrid` per entry. Duration formatters accept seconds (`duration`), milliseconds (`duration_ms`), or nanoseconds (`duration_ns`). `hide` and `startAtZero` are honored per entry (bar-series axes keep their zero baseline). A single object stays single-axis (unchanged). The second axis only renders when a series actually targets it; the primary (left) axis owns the gridlines. More than two axes work too (trends `showMultipleYAxes`): they stack outward per side and alternate sides. Each entry's `label` renders that axis's title at its own gutter — every axis is titled the same way (a single-object `yAxis`/scalar `yAxisLabel` is just the one left axis), driven by the shared `computeYAxisGutters` layout that `AxisLabels` (ticks) and `AxisTitles` (titles) both read so the two can't drift. `TimeSeriesBarChart`/`TimeSeriesComboChart` take the same `yAxis` array; a sole axis pinned `right` renders on the right on every chart type.
- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/`BarChart`/`TimeSeriesBarChart`/base `Chart`) enables x-axis drag-to-zoom: the user drags horizontally and the callback fires once with `{ startLabel, endLabel, startIndex, endIndex }` for the spanned range. Despite the name it is label-generic — it resolves the drag against label positions, so it works the same on categorical labels (weekdays, duration buckets) as on dates. A drag whose edges both snap to the same label (common on sparse charts, e.g. a 3-bar monthly chart) selects that single bucket, provided the drag spans enough horizontal distance to read as intentional. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis (`axisOrientation: 'horizontal'` bars, where the core disables the gesture).
-- `onAreaSelect` (base `Chart`, chart-type adapters only) is the 2D-brush sibling of `onDateRangeZoom`: the drag tracks both axes, the selection rect clamps to the dragged vertical range, and the completed gesture reports the x label range plus the y pixel span (with the committed scales, so the adapter maps pixels onto its own bands). `Heatmap` exposes it as `onBrush` with row/column index ranges; a near-horizontal drag (<8px vertical) spans every row. Takes precedence over `onDateRangeZoom` when both are set.
+- `onAreaSelect` (base `Chart`, chart-type adapters only) is the 2D-brush sibling of `onDateRangeZoom`: the drag tracks both axes, the selection rect clamps to the dragged vertical range, and the completed gesture reports the x label range plus the raw x and y pixel spans (with the committed scales, so the adapter maps pixels onto its own bands). `Heatmap` exposes it as `onBrush` with row/column index ranges; a near-horizontal drag (<8px vertical) spans every row. `ScatterChart` exposes it as its own `onAreaSelect`, inverting the pixel spans through its continuous scales — the label range is meaningless there, since it snaps to whichever points sit near the drag edges. Each edge is clamped to its axis first, so a drag that overshoots the plot (routine when brushing into a corner) reports the rectangle the user saw rather than an extrapolated one. Takes precedence over `onDateRangeZoom` when both are set.
+- `ScatterChart` takes `series: ScatterSeries[]` — each `{ key, label, points: { x, y, label?, radius?, color?, meta? }[], color?, pointRadius?, shape? }` — and no `labels`, since both axes are continuous. `config.xAxis` / `config.yAxis` are symmetric `ScatterAxisConfig`s (`scaleType: 'linear' | 'log'`, `domain` to pin the range, `label`, `tickFormatter`, `hide`, `startAtZero`); unlike a trend, both axes float to their data range by default, because forcing either to zero squashes the correlation into a corner. On a log axis, points with a non-positive coordinate can't be placed and are dropped from the chart. A pinned `domain` narrows the chart rather than just its viewport: points outside it are dropped too, so nothing is drawn out in the axis gutters or piled onto the plot edge at a value it doesn't have. `shape` (`circle` | `square` | `triangle` | `cross`) separates series without relying on color alone, and markers fill at `config.fillOpacity` (0.7) over an opaque outline so a dense cloud reads as density. Hit-testing is 2D and edge-based: the tooltip resolves the marker nearest the cursor in both axes (a large marker the cursor sits inside beats a small one whose center is nearer), and empty plot area resolves to nothing at all rather than to the nearest column. `onPointClick` and the `tooltip` render prop both receive the resolved point (`ScatterPointDatum`, with its series and `meta`) rather than a data index; `config.legend` and `config.tooltip` (`enabled`, `placement`, `labelFormatter`, `xFormatter`, `yFormatter`) work as elsewhere, and the chrome toggles are the same keys every other chart takes — `showGrid`, `showAxisLines`, `showTickMarks`, `showCrosshair`, all off by default — so a host's shared config defaults reach a scatter the same way they reach a line chart. Its x ticks are resolved once per layout, so the grid lines, the tick marks, and the labels are the same set rather than three that can drift.
## Testing
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.stories.tsx b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.stories.tsx
new file mode 100644
index 000000000000..c217f0fbe152
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.stories.tsx
@@ -0,0 +1,244 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { useState } from 'react'
+
+import { Stage, useReactiveTheme } from '../../story-helpers'
+import { ScatterChart } from './ScatterChart'
+import type { ScatterAreaSelection, ScatterChartConfig, ScatterPoint, ScatterSeries } from './types'
+
+// Deterministic pseudo-random spread, so visual snapshots are stable across runs.
+function makeRandom(seed: number): () => number {
+ let state = seed
+ return () => {
+ state = (state * 1103515245 + 12345) & 0x7fffffff
+ return state / 0x7fffffff
+ }
+}
+
+/** A correlated cloud: usage on x, activity on y, with enough scatter to be worth plotting. */
+function makeCloud(count: number, seed: number, slope: number, spread: number): ScatterPoint[] {
+ const next = makeRandom(seed)
+ return Array.from({ length: count }, (_, i) => {
+ const x = Math.round(next() * 900) + 20
+ return {
+ x,
+ y: Math.max(1, Math.round(x * slope + (next() - 0.5) * spread)),
+ label: `Org ${seed}-${i + 1}`,
+ }
+ })
+}
+
+const SINGLE: ScatterSeries[] = [{ key: 'orgs', label: 'Organizations', points: makeCloud(160, 1, 0.6, 260) }]
+
+// Chrome is off by default in the library, so every story opts into `showGrid` the way the other
+// chart types' stories do. `HostChrome` below shows what a product consumer sees instead.
+const CHROME = { showGrid: true } satisfies ScatterChartConfig
+
+const AXES = { ...CHROME, xAxis: { label: 'GB ingested' }, yAxis: { label: 'Queries run' } }
+
+const meta: Meta<typeof ScatterChart> = {
+ title: 'Charts/ScatterChart',
+ component: ScatterChart,
+ tags: ['autodocs'],
+}
+export default meta
+
+type Story = StoryObj<typeof ScatterChart>
+
+export const Default: Story = {
+ render: function Render() {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={620} height={360}>
+ <ScatterChart series={SINGLE} theme={theme} config={AXES} />
+ </Stage>
+ )
+ },
+}
+
+/** Several groups at once: color and marker shape both separate them, and the legend hides them. */
+export const MultipleSeries: Story = {
+ render: function Render() {
+ const theme = useReactiveTheme()
+ const series: ScatterSeries[] = [
+ { key: 'enterprise', label: 'Enterprise', points: makeCloud(60, 3, 0.9, 200) },
+ { key: 'scale', label: 'Scale', points: makeCloud(60, 7, 0.5, 200), shape: 'square' },
+ { key: 'free', label: 'Free', points: makeCloud(60, 11, 0.2, 160), shape: 'cross' },
+ ]
+ return (
+ <Stage width={620} height={380}>
+ <ScatterChart series={series} theme={theme} config={{ ...AXES, legend: { show: true } }} />
+ </Stage>
+ )
+ },
+}
+
+/** Heavy-tailed data — the reason both axes take a log scale. */
+export const LogScales: Story = {
+ render: function Render() {
+ const theme = useReactiveTheme()
+ const next = makeRandom(5)
+ const points: ScatterPoint[] = Array.from({ length: 90 }, (_, i) => {
+ const x = 10 ** (1 + next() * 3)
+ return { x, y: Math.max(1, x ** 0.7 * (0.4 + next())), label: `Tenant ${i + 1}` }
+ })
+ return (
+ <Stage width={620} height={360}>
+ <ScatterChart
+ series={[{ key: 'tenants', label: 'Tenants', points }]}
+ theme={theme}
+ config={{
+ ...CHROME,
+ xAxis: { label: 'Rows stored', scaleType: 'log' },
+ yAxis: { label: 'Query cost', scaleType: 'log' },
+ }}
+ />
+ </Stage>
+ )
+ },
+}
+
+/** Cluster members plus an oversized centroid per cluster — per-point radius and color. */
+export const ClustersWithCentroids: Story = {
+ render: function Render() {
+ const theme = useReactiveTheme()
+ const centers = [
+ [200, 700],
+ [600, 250],
+ [800, 800],
+ ]
+ const series: ScatterSeries[] = centers.map(([cx, cy], cluster) => {
+ const next = makeRandom(cluster * 17 + 3)
+ const members: ScatterPoint[] = Array.from({ length: 40 }, (_, i) => ({
+ x: cx + (next() - 0.5) * 260,
+ y: cy + (next() - 0.5) * 260,
+ label: `Trace ${cluster + 1}-${i + 1}`,
+ }))
+ return {
+ key: `cluster-${cluster}`,
+ label: `Cluster ${cluster + 1}`,
+ points: [...members, { x: cx, y: cy, label: `Cluster ${cluster + 1} centroid`, radius: 9 }],
+ }
+ })
+ return (
+ <Stage width={620} height={380}>
+ <ScatterChart
+ series={series}
+ theme={theme}
+ config={{ ...CHROME, xAxis: { hide: true }, yAxis: { hide: true }, legend: { show: true } }}
+ />
+ </Stage>
+ )
+ },
+}
+
+/** Drag a rectangle to zoom; the button restores the data-derived domains. */
+export const DragToZoom: Story = {
+ // Skipped from visual regression: the selection rect only exists mid-drag, so a static snapshot
+ // is Default again. The story stays for interactive documentation of onAreaSelect.
+ tags: ['test-skip'],
+ render: function Render() {
+ const theme = useReactiveTheme()
+ const [zoom, setZoom] = useState<ScatterAreaSelection | null>(null)
+ return (
+ <Stage width={620} height={380}>
+ <ScatterChart
+ series={SINGLE}
+ theme={theme}
+ config={{
+ ...CHROME,
+ xAxis: { label: 'GB ingested', domain: zoom?.x },
+ yAxis: { label: 'Queries run', domain: zoom?.y },
+ }}
+ onAreaSelect={setZoom}
+ />
+ <button type="button" onClick={() => setZoom(null)} disabled={!zoom}>
+ Reset zoom
+ </button>
+ </Stage>
+ )
+ },
+}
+
+// The dashed grid and crosshair are theme rather than config, and the token vars carry no dash
+// pattern: PostHog layers these on top in `chartThemeDefaults` (`frontend/src/lib/charts/hooks.ts`).
+const HOST_THEME_CHROME = { gridDashPattern: [3, 3], crosshairDashPattern: [3, 3] }
+
+/** The chart as PostHog renders it: every chrome toggle on, as a host's shared chart config defaults
+ * set them, over a theme carrying the host's dashed grid. */
+export const HostChrome: Story = {
+ render: function Render() {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={620} height={360}>
+ <ScatterChart
+ series={SINGLE}
+ theme={{ ...theme, ...HOST_THEME_CHROME }}
+ config={{
+ ...AXES,
+ showAxisLines: true,
+ showTickMarks: true,
+ showCrosshair: true,
+ }}
+ />
+ </Stage>
+ )
+ },
+}
+
+/** A degenerate domain: one point gives the axis no range to span. */
+export const SinglePoint: Story = {
+ // Skipped from visual regression: the degenerate-domain handling is `buildValueScale`'s, covered
+ // in core/scales.test.ts. The story stays to show the result.
+ tags: ['test-skip'],
+ render: function Render() {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={620} height={360}>
+ <ScatterChart
+ series={[{ key: 'one', label: 'Only', points: [{ x: 42, y: 17, label: 'Only point' }] }]}
+ theme={theme}
+ config={AXES}
+ />
+ </Stage>
+ )
+ },
+}
+
+/** No series at all: the axes fall back to 0–1. */
+export const Empty: Story = {
+ // Skipped from visual regression: the empty-series fallback is `buildValueScale`'s, covered in
+ // core/scales.test.ts.
+ tags: ['test-skip'],
+ render: function Render() {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={620} height={360}>
+ <ScatterChart series={[]} theme={theme} config={AXES} />
+ </Stage>
+ )
+ },
+}
+
+/** Thousands of overlapping markers, which is what the translucent fill is for. */
+export const DenseCloud: Story = {
+ // Skipped from visual regression: Default already covers the translucent fill at the same
+ // opacity, and 3000 markers make for a slow, jitter-prone screenshot.
+ tags: ['test-skip'],
+ render: function Render() {
+ const theme = useReactiveTheme()
+ const next = makeRandom(23)
+ const points: ScatterPoint[] = Array.from({ length: 3000 }, () => {
+ const x = next() * 1000
+ return { x, y: x * 0.5 + (next() + next() + next() - 1.5) * 300 }
+ })
+ return (
+ <Stage width={620} height={360}>
+ <ScatterChart
+ series={[{ key: 'events', label: 'Events', points }]}
+ theme={theme}
+ config={{ ...AXES, pointRadius: 2.5 }}
+ />
+ </Stage>
+ )
+ },
+}
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.test.tsx b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.test.tsx
new file mode 100644
index 000000000000..0505457a631b
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.test.tsx
@@ -0,0 +1,194 @@
+import { act, fireEvent, waitFor } from '@testing-library/react'
+
+import type { ChartMargins, ChartTheme } from '../../core/types'
+import {
+ createDefaultTooltipAccessor,
+ getHogChartTooltip,
+ rawDrag,
+ renderHogChart,
+ waitForHogChartTooltip,
+} from '../../testing'
+import { ScatterChart } from './ScatterChart'
+import type { ScatterAreaSelection, ScatterChartConfig, ScatterPointDatum, ScatterSeries } from './types'
+
+const THEME: ChartTheme = {
+ colors: ['#1f77b4', '#ff7f0e'],
+ backgroundColor: '#ffffff',
+ gridColor: '#eeeeee',
+}
+
+// Zeroed margins make the plot the whole 800×400 jsdom canvas, so a data coordinate maps to a
+// client pixel the test can compute exactly.
+const MARGINS: Partial<ChartMargins> = { top: 0, right: 0, bottom: 0, left: 0 }
+const PLOT_WIDTH = 800
+const PLOT_HEIGHT = 400
+/** Both axes span 0–100 across every fixture below, so `nice()` leaves the domain alone. */
+const clientX = (x: number): number => (x / 100) * PLOT_WIDTH
+const clientY = (y: number): number => PLOT_HEIGHT - (y / 100) * PLOT_HEIGHT
+
+const SERIES: ScatterSeries[] = [
+ {
+ key: 'reads',
+ label: 'Reads',
+ points: [
+ { x: 0, y: 0, label: 'Bottom left' },
+ { x: 100, y: 100, label: 'Top right' },
+ // Off the diagonal, so a tooltip that swapped the two axes couldn't still read correctly.
+ { x: 25, y: 80, label: 'Off diagonal' },
+ ],
+ },
+ { key: 'writes', label: 'Writes', points: [{ x: 0, y: 100, label: 'Top left' }] },
+]
+
+function renderScatter(
+ props: Partial<React.ComponentProps<typeof ScatterChart>> = {}
+): ReturnType<typeof renderHogChart> {
+ return renderHogChart(
+ <ScatterChart
+ series={SERIES}
+ theme={THEME}
+ config={{ margins: MARGINS, xAxis: { label: 'Reads' }, yAxis: { label: 'Writes' }, ...props.config }}
+ {...props}
+ />,
+ { nativeTooltip: true }
+ )
+}
+
+/** Hover a data coordinate, re-dispatching until the chart has committed its scales. */
+async function hoverPoint(wrapper: HTMLElement, x: number, y: number): Promise<HTMLElement> {
+ return waitForHogChartTooltip(3000, () => {
+ act(() => {
+ fireEvent.mouseMove(wrapper, { clientX: clientX(x), clientY: clientY(y) })
+ })
+ })
+}
+
+describe('ScatterChart', () => {
+ it('ticks each axis over its own value range, not once per point', () => {
+ const { chart } = renderScatter()
+ expect(chart.xTicks()).toContain('100')
+ expect(chart.xAxisLabel()).toBe('Reads')
+ })
+
+ it('reads a hovered point as both of its coordinates', async () => {
+ const { chart } = renderScatter()
+ const tooltip = createDefaultTooltipAccessor(await hoverPoint(chart.element, 25, 80))
+ expect(tooltip.label()).toBe('Off diagonal')
+ expect(tooltip.value('Reads')).toBe('25')
+ expect(tooltip.value('Writes')).toBe('80')
+ })
+
+ it.each<[string, ScatterChartConfig, string, string[]]>([
+ [
+ 'pins each axis to a caller domain',
+ { xAxis: { domain: [0, 50] }, yAxis: { domain: [0, 50] } },
+ '50',
+ ['100'],
+ ],
+ [
+ 'falls back to linear when a log domain starts at a non-positive bound',
+ { xAxis: { scaleType: 'log', domain: [0, 100] }, yAxis: { scaleType: 'log', domain: [0, 100] } },
+ '100',
+ [],
+ ],
+ ])('%s', (_, config, expected, absent) => {
+ const { chart } = renderScatter({ config: { margins: MARGINS, ...config } })
+ // Asserted on both axes, so a scale built against the wrong axis fails too.
+ for (const ticks of [chart.xTicks(), chart.yTicks()]) {
+ expect(ticks).toContain(expected)
+ expect(ticks.filter((tick) => absent.includes(tick))).toEqual([])
+ }
+ })
+
+ it('drops a point outside a pinned domain rather than clamping it onto the plot edge', async () => {
+ const series: ScatterSeries[] = [
+ {
+ key: 'latency',
+ label: 'Latency',
+ points: [
+ { x: 10, y: 10, label: 'In range' },
+ { x: 10, y: 1000, label: 'Above the domain' },
+ ],
+ },
+ ]
+ const { chart } = renderHogChart(
+ <ScatterChart
+ series={series}
+ theme={THEME}
+ config={{
+ margins: MARGINS,
+ xAxis: { domain: [0, 100] },
+ yAxis: { scaleType: 'log', domain: [1, 100] },
+ }}
+ />,
+ { nativeTooltip: true }
+ )
+ // A log scale clamps, so the excluded point would otherwise sit hoverable on the top edge.
+ await waitForHogChartTooltip(3000, () => {
+ act(() => {
+ fireEvent.mouseMove(chart.element, { clientX: clientX(10), clientY: PLOT_HEIGHT / 2 })
+ })
+ })
+ act(() => {
+ fireEvent.mouseMove(chart.element, { clientX: clientX(10), clientY: 4 })
+ })
+ await waitFor(() => expect(getHogChartTooltip()).toBeNull())
+ })
+
+ it('drops a legend-hidden series from the plot, not just from the legend', async () => {
+ const { chart } = renderScatter({ config: { margins: MARGINS, legend: { hiddenKeys: ['writes'] } } })
+ // Hover a visible point first, or an absent tooltip passes on uncommitted scales alone.
+ await hoverPoint(chart.element, 100, 100)
+ act(() => {
+ fireEvent.mouseMove(chart.element, { clientX: clientX(0), clientY: clientY(100) })
+ })
+ await waitFor(() => expect(getHogChartTooltip()).toBeNull())
+ })
+
+ it('reports the clicked point with its series and consumer meta', async () => {
+ const onPointClick = jest.fn()
+ const series: ScatterSeries<{ orgId: string }>[] = [
+ { key: 'orgs', label: 'Orgs', points: [{ x: 100, y: 100, label: 'Hedgebox', meta: { orgId: 'hb' } }] },
+ ]
+ const { chart } = renderHogChart(
+ <ScatterChart series={series} theme={THEME} config={{ margins: MARGINS }} onPointClick={onPointClick} />,
+ { nativeTooltip: true }
+ )
+ await hoverPoint(chart.element, 100, 100)
+ fireEvent.click(chart.element)
+
+ expect(onPointClick).toHaveBeenCalledTimes(1)
+ expect(onPointClick.mock.calls[0][0]).toMatchObject<Partial<ScatterPointDatum<{ orgId: string }>>>({
+ x: 100,
+ y: 100,
+ label: 'Hedgebox',
+ seriesKey: 'orgs',
+ seriesLabel: 'Orgs',
+ pointIndex: 0,
+ meta: { orgId: 'hb' },
+ })
+ })
+
+ it.each<[string, { x: number; y: number }, ScatterAreaSelection]>([
+ ['in the points own units, not pixels', { x: 60, y: 30 }, { x: [20, 60], y: [30, 80] }],
+ // Brushing into a corner routinely leaves the plot, where an unclamped pixel inverts to a
+ // range wider than the rectangle the user saw.
+ ['clamped to each axis when the drag overshoots the plot', { x: -30, y: 130 }, { x: [0, 20], y: [80, 100] }],
+ ])('reports a drag selection %s', async (_, to, expected) => {
+ const onAreaSelect = jest.fn()
+ const { chart } = renderScatter({ onAreaSelect })
+ await hoverPoint(chart.element, 100, 100)
+
+ rawDrag(chart.element, {
+ from: { x: clientX(20), y: clientY(80) },
+ to: { x: clientX(to.x), y: clientY(to.y) },
+ })
+
+ expect(onAreaSelect).toHaveBeenCalledTimes(1)
+ const selection = onAreaSelect.mock.calls[0][0] as ScatterAreaSelection
+ expect(selection.x[0]).toBeCloseTo(expected.x[0])
+ expect(selection.x[1]).toBeCloseTo(expected.x[1])
+ expect(selection.y[0]).toBeCloseTo(expected.y[0])
+ expect(selection.y[1]).toBeCloseTo(expected.y[1])
+ })
+})
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx
new file mode 100644
index 000000000000..d7b3f18bd900
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx
@@ -0,0 +1,341 @@
+import React, { useCallback, useMemo } from 'react'
+
+import { ChartLegend } from '../../components/Legend/ChartLegend'
+import { useChartLegend } from '../../components/Legend/useChartLegend'
+import { drawAxes, drawGrid, drawTickMarks, resolveAxisLineColor } from '../../core/canvas-renderer'
+import type { DrawContext } from '../../core/canvas-renderer'
+import { Chart } from '../../core/Chart'
+import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
+import { applyMarginOverride, DEFAULT_MARGINS } from '../../core/hooks/useChartMargins'
+import { sanitizeFixedDomain } from '../../core/scales'
+import type {
+ AreaSelectData,
+ ChartConfig,
+ ChartDimensions,
+ ChartDrawArgs,
+ ChartMargins,
+ ChartScales,
+ ChartTheme,
+ CreateScalesFn,
+ PointClickData,
+ ResolvedSeries,
+ ResolveValueFn,
+ Series,
+ TooltipContext,
+} from '../../core/types'
+import { drawScatterHoverMarker, drawScatterMarkers } from './draw-scatter'
+import { findNearestPointIndex } from './nearest-point'
+import { flattenScatterPoints, toAdapterSeries, toPointDatum } from './scatter-data'
+import type { FlatScatterPoint } from './scatter-data'
+import { createScatterScales, readScatterLayout } from './scatter-layout'
+import { clampToRange, xLabelEdgeReserve } from './scatter-scales'
+import { ScatterTooltip } from './ScatterTooltip'
+import { ScatterXAxisLabels } from './ScatterXAxisLabels'
+import type {
+ ScatterAreaSelection,
+ ScatterAxisConfig,
+ ScatterChartConfig,
+ ScatterPointDatum,
+ ScatterSeries,
+ ScatterTooltipContext,
+} from './types'
+
+const DEFAULT_POINT_RADIUS = 3.5
+const DEFAULT_FILL_OPACITY = 0.7
+
+const EMPTY_AXIS_CONFIG: ScatterAxisConfig = {}
+
+/** Blanks the base chart's category x-axis layer, which {@link ScatterXAxisLabels} replaces. At
+ * module scope so it can't churn the base chart's margin and tick memos. */
+const NO_CATEGORY_X_LABELS = (): null => null
+
+export interface ScatterChartProps<Meta = unknown> {
+ series: ScatterSeries<Meta>[]
+ theme: ChartTheme
+ config?: ScatterChartConfig<Meta>
+ tooltip?: (ctx: ScatterTooltipContext<Meta>) => React.ReactNode
+ onPointClick?: (point: ScatterPointDatum<Meta>) => void
+ /** Fires once per completed drag. Feed its bounds back as the axes' `domain` to zoom. */
+ onAreaSelect?: (selection: ScatterAreaSelection) => void
+ className?: string
+ /** `data-attr` applied to the chart wrapper. See `ChartProps.dataAttr`. */
+ dataAttr?: string
+ children?: React.ReactNode
+ onError?: (error: Error, info: React.ErrorInfo) => void
+}
+
+export function ScatterChart<Meta = unknown>({ onError, ...rest }: ScatterChartProps<Meta>): React.ReactElement {
+ return (
+ <ChartErrorBoundary onError={onError}>
+ <ScatterChartInner {...rest} />
+ </ChartErrorBoundary>
+ )
+}
+
+function ScatterChartInner<Meta = unknown>({
+ series,
+ theme,
+ config,
+ tooltip,
+ onPointClick,
+ onAreaSelect,
+ className,
+ dataAttr,
+ children,
+}: Omit<ScatterChartProps<Meta>, 'onError'>): React.ReactElement {
+ const {
+ xAxis = EMPTY_AXIS_CONFIG,
+ yAxis = EMPTY_AXIS_CONFIG,
+ pointRadius: defaultPointRadius = DEFAULT_POINT_RADIUS,
+ fillOpacity = DEFAULT_FILL_OPACITY,
+ showGrid = false,
+ showAxisLines = false,
+ showTickMarks = false,
+ showCrosshair = false,
+ margins,
+ } = config ?? {}
+ // Destructured to primitives, so an inline `config` literal can't re-run the scale build.
+ const { scaleType: xScaleType, domain: xDomain, startAtZero: xStartAtZero, tickFormatter: xTickFormatter } = xAxis
+ const { scaleType: yScaleType, domain: yDomain, startAtZero: yStartAtZero, tickFormatter: yTickFormatter } = yAxis
+
+ const points = useMemo(
+ () => flattenScatterPoints(series, { xLogScale: xScaleType === 'log', yLogScale: yScaleType === 'log' }),
+ [series, xScaleType, yScaleType]
+ )
+ const labels = useMemo(() => points.map((_, i) => String(i)), [points])
+
+ const adaptedSeries = useMemo(() => toAdapterSeries(series, points), [series, points])
+
+ const { visibleSeries, legendProps } = useChartLegend(adaptedSeries, theme, config?.legend)
+
+ const createScales: CreateScalesFn = useCallback(
+ (coloredSeries: ResolvedSeries[], _labels: string[], dimensions: ChartDimensions): ChartScales =>
+ createScatterScales({
+ points,
+ seriesStyles: series,
+ coloredSeries,
+ dimensions,
+ xAxis: { scaleType: xScaleType, domain: xDomain, startAtZero: xStartAtZero },
+ yAxis: { scaleType: yScaleType, domain: yDomain, startAtZero: yStartAtZero },
+ xTickFormatter,
+ defaultPointRadius,
+ fallbackColor: theme.colors[0],
+ }),
+ [
+ points,
+ series,
+ xScaleType,
+ xDomain,
+ xStartAtZero,
+ yScaleType,
+ yDomain,
+ yStartAtZero,
+ xTickFormatter,
+ defaultPointRadius,
+ theme.colors,
+ ]
+ )
+
+ const drawStatic = useCallback(
+ ({ ctx, dimensions, scales, theme: drawTheme }: ChartDrawArgs) => {
+ const layout = readScatterLayout(scales)
+ if (!layout) {
+ return
+ }
+ const drawCtx: DrawContext = { ctx, dimensions, xScale: scales.x, yScale: layout.yScale, labels: [] }
+ const axisLineColor = showAxisLines ? resolveAxisLineColor(drawTheme) : undefined
+ const xTickPixels = layout.xTicks.map((tick) => tick.x)
+
+ if (showGrid) {
+ drawGrid(drawCtx, {
+ gridColor: drawTheme.gridColor,
+ gridDash: drawTheme.gridDashPattern,
+ frame: !axisLineColor,
+ categoryTicks: xTickPixels,
+ })
+ }
+
+ // The base chart's x tick marks come off category labels, so draw this axis' own here.
+ if (showTickMarks) {
+ drawTickMarks(ctx, dimensions, { xs: xTickPixels, ys: [] }, axisLineColor)
+ }
+
+ drawScatterMarkers(ctx, layout.positions, fillOpacity)
+
+ if (axisLineColor) {
+ drawAxes(drawCtx, { axisColor: axisLineColor })
+ }
+ },
+ [showGrid, showAxisLines, showTickMarks, fillOpacity]
+ )
+
+ const drawHover = useCallback(({ ctx, scales, hoverIndex, hoverProgress, theme: drawTheme }: ChartDrawArgs) => {
+ const position = readScatterLayout(scales)?.positions.find((p) => p.index === hoverIndex)
+ if (!position) {
+ return false
+ }
+ drawScatterHoverMarker(ctx, position, drawTheme.backgroundColor ?? '#ffffff', hoverProgress)
+ return true
+ }, [])
+
+ // The base chart resolves by x alone, which can't tell points stacked at one x apart.
+ const resolveHoverIndex = useCallback(
+ (_index: number, cursor: { x: number; y: number }, scales: ChartScales): number => {
+ const layout = readScatterLayout(scales)
+ if (!layout) {
+ return -1
+ }
+ return findNearestPointIndex(layout.positions, cursor.x, cursor.y, layout.maxRadius)
+ },
+ []
+ )
+
+ // A gap must stay NaN. The shared default coerces one to 0, anchoring the tooltip at whatever
+ // pixel `0` maps to for every series with no point at this index.
+ const resolveValue: ResolveValueFn = useCallback((s, dataIndex) => {
+ const value = s.data[dataIndex]
+ return typeof value === 'number' && isFinite(value) ? value : NaN
+ }, [])
+
+ const resolvePoint = useCallback(
+ (dataIndex: number): ScatterPointDatum<Meta> | null => {
+ const point = points[dataIndex] as FlatScatterPoint<Meta> | undefined
+ if (!point) {
+ return null
+ }
+ const { seriesIndex } = point
+ return toPointDatum(point, series[seriesIndex], theme.colors[seriesIndex % theme.colors.length])
+ },
+ [points, series, theme.colors]
+ )
+
+ const tooltipConfig = config?.tooltip
+ const xAxisLabel = xAxis.label
+ const yAxisLabel = yAxis.label
+ const renderTooltip = useCallback(
+ (ctx: TooltipContext): React.ReactNode => {
+ const point = resolvePoint(ctx.dataIndex)
+ if (!point) {
+ return null
+ }
+ if (tooltip) {
+ return tooltip({ ...ctx, point })
+ }
+ return (
+ <ScatterTooltip
+ point={point}
+ header={tooltipConfig?.labelFormatter?.(point)}
+ xLabel={xAxisLabel}
+ yLabel={yAxisLabel}
+ xValue={tooltipConfig?.xFormatter?.(point.x, point) ?? xTickFormatter?.(point.x)}
+ yValue={tooltipConfig?.yFormatter?.(point.y, point) ?? yTickFormatter?.(point.y)}
+ />
+ )
+ },
+ [resolvePoint, tooltip, tooltipConfig, xAxisLabel, yAxisLabel, xTickFormatter, yTickFormatter]
+ )
+
+ const handlePointClick = useCallback(
+ (data: PointClickData): void => {
+ const point = resolvePoint(data.dataIndex)
+ if (point) {
+ onPointClick?.(point)
+ }
+ },
+ [onPointClick, resolvePoint]
+ )
+
+ // The core's label range means nothing on a continuous axis, so invert its raw pixels instead.
+ const handleAreaSelect = useCallback(
+ (data: AreaSelectData, scales: ChartScales): void => {
+ const layout = readScatterLayout(scales)
+ if (!layout || !onAreaSelect) {
+ return
+ }
+ const { xScale, yScale } = layout
+ onAreaSelect({
+ x: sanitizeFixedDomain([
+ xScale.invert(clampToRange(data.xPixel0, xScale)),
+ xScale.invert(clampToRange(data.xPixel1, xScale)),
+ ]),
+ // The y pixel range runs top-to-bottom, so its low pixel inverts to the high value.
+ y: sanitizeFixedDomain([
+ yScale.invert(clampToRange(data.yPixel1, yScale)),
+ yScale.invert(clampToRange(data.yPixel0, yScale)),
+ ]),
+ })
+ },
+ [onAreaSelect]
+ )
+
+ // Otherwise the y gutter is sized from the adapter series, which stop short of a pinned domain.
+ const valueRangeSeries = useMemo<Series[] | undefined>(() => {
+ if (!yDomain) {
+ return undefined
+ }
+ return [{ key: '__scatter_y_domain', label: '', data: sanitizeFixedDomain(yDomain) }]
+ }, [yDomain])
+
+ const resolvedMargins = useMemo<Partial<ChartMargins> | undefined>(() => {
+ if (xAxis.hide) {
+ return margins
+ }
+ // Right side only, since the y-axis gutter already reserves more than half a tick label.
+ const computed: Partial<ChartMargins> = {
+ right: Math.max(DEFAULT_MARGINS.right, xLabelEdgeReserve(points, xDomain, xTickFormatter)),
+ }
+ return margins ? applyMarginOverride(computed, margins) : computed
+ }, [xAxis.hide, margins, points, xDomain, xTickFormatter])
+
+ const baseConfig = useMemo<ChartConfig>(
+ () => ({
+ xTickFormatter: NO_CATEGORY_X_LABELS,
+ yTickFormatter,
+ xAxisLabel,
+ yAxisLabel,
+ hideXAxis: xAxis.hide,
+ hideYAxis: yAxis.hide,
+ margins: resolvedMargins,
+ showTickMarks,
+ showCrosshair,
+ tooltip: { enabled: tooltipConfig?.enabled, placement: tooltipConfig?.placement },
+ }),
+ [
+ yTickFormatter,
+ xAxisLabel,
+ yAxisLabel,
+ xAxis.hide,
+ yAxis.hide,
+ resolvedMargins,
+ showTickMarks,
+ showCrosshair,
+ tooltipConfig?.enabled,
+ tooltipConfig?.placement,
+ ]
+ )
+
+ return (
+ <ChartLegend {...legendProps} legendDataAttr="hog-chart-scatter-legend">
+ <Chart
+ series={visibleSeries}
+ labels={labels}
+ config={baseConfig}
+ theme={theme}
+ createScales={createScales}
+ drawStatic={drawStatic}
+ drawHover={drawHover}
+ resolveHoverIndex={resolveHoverIndex}
+ resolveValue={resolveValue}
+ valueRangeSeries={valueRangeSeries}
+ tooltip={renderTooltip}
+ onPointClick={onPointClick ? handlePointClick : undefined}
+ onAreaSelect={onAreaSelect ? handleAreaSelect : undefined}
+ className={className}
+ dataAttr={dataAttr}
+ >
+ {!xAxis.hide && <ScatterXAxisLabels />}
+ {children}
+ </Chart>
+ </ChartLegend>
+ )
+}
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterTooltip.tsx b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterTooltip.tsx
new file mode 100644
index 000000000000..a72dc6074fea
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterTooltip.tsx
@@ -0,0 +1,55 @@
+import React from 'react'
+
+import { TooltipSurface, TooltipSwatch } from '../../overlays/TooltipSurface'
+import type { ScatterPointDatum } from './types'
+
+export interface ScatterTooltipProps<Meta = unknown> {
+ point: ScatterPointDatum<Meta>
+ header?: React.ReactNode
+ xLabel?: string
+ yLabel?: string
+ xValue?: React.ReactNode
+ yValue?: React.ReactNode
+}
+
+function Row({ label, value }: { label: string; value: React.ReactNode }): React.ReactElement {
+ return (
+ <div data-attr="hog-chart-tooltip-row" className="flex items-center gap-2 min-w-0 py-0.5">
+ <span data-attr="hog-chart-tooltip-series" className="flex-1 min-w-0 truncate opacity-60">
+ {label}
+ </span>
+ <strong data-attr="hog-chart-tooltip-value" className="tabular-nums">
+ {value}
+ </strong>
+ </div>
+ )
+}
+
+/** `DefaultTooltip` can't serve, because its rows are series values at one x-axis label, whereas a
+ * scatter point *is* the reading. Its `data-attr` hooks are reused, so the shared tooltip test
+ * accessor reads this one too. */
+export function ScatterTooltip<Meta = unknown>({
+ point,
+ header,
+ xLabel,
+ yLabel,
+ xValue,
+ yValue,
+}: ScatterTooltipProps<Meta>): React.ReactElement {
+ const title = header ?? point.label ?? point.seriesLabel
+ return (
+ <TooltipSurface>
+ {title ? (
+ <div
+ data-attr="hog-chart-tooltip-label"
+ className="flex items-center gap-2 min-w-0 font-semibold mb-1 opacity-60"
+ >
+ <TooltipSwatch color={point.color} />
+ <span className="truncate">{title}</span>
+ </div>
+ ) : null}
+ <Row label={xLabel || 'X'} value={xValue ?? point.x.toLocaleString()} />
+ <Row label={yLabel || 'Y'} value={yValue ?? point.y.toLocaleString()} />
+ </TooltipSurface>
+ )
+}
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterXAxisLabels.tsx b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterXAxisLabels.tsx
new file mode 100644
index 000000000000..05ace0f51cdb
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterXAxisLabels.tsx
@@ -0,0 +1,43 @@
+import React from 'react'
+
+import { useChartLayout } from '../../core/chart-context'
+import { TICK_GAP } from '../../core/y-axis-gutters'
+import { readScatterLayout } from './scatter-layout'
+
+// Matches the base chart's fallback, so a theme without an axis color renders both axes alike.
+const DEFAULT_AXIS_COLOR = 'rgba(0, 0, 0, 0.5)'
+
+const TICK_STYLE: React.CSSProperties = {
+ position: 'absolute',
+ fontSize: 12,
+ pointerEvents: 'none',
+ whiteSpace: 'nowrap',
+ transform: 'translateX(-50%)',
+}
+
+/** Stands in for the base chart's one-label-per-category x-axis layer, carrying the same
+ * `data-attr` so test accessors read either chart alike. */
+export function ScatterXAxisLabels(): React.ReactElement | null {
+ const { scales, dimensions, theme } = useChartLayout()
+ const ticks = readScatterLayout(scales)?.xTicks
+
+ if (!ticks?.length) {
+ return null
+ }
+
+ const top = dimensions.plotTop + dimensions.plotHeight + TICK_GAP
+ return (
+ <>
+ {ticks.map(({ tick, text, x }) => (
+ <div
+ key={tick}
+ data-attr="hog-chart-axis-tick-x"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ ...TICK_STYLE, left: x, top, color: theme.axisColor ?? DEFAULT_AXIS_COLOR }}
+ >
+ {text}
+ </div>
+ ))}
+ </>
+ )
+}
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/draw-scatter.ts b/packages/quill/packages/charts/src/charts/ScatterChart/draw-scatter.ts
new file mode 100644
index 000000000000..1365a13ee7e7
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/draw-scatter.ts
@@ -0,0 +1,57 @@
+import { traceScatterMarker } from '../../core/canvas-renderer'
+import { dimColor } from '../../core/color-utils'
+import type { ScatterPointPosition } from './scatter-layout'
+
+const MARKER_STROKE_WIDTH = 1.25
+const HOVER_HALO_WIDTH = 3
+const HOVER_HALO_RADIUS_PX = 2
+
+/** Fills translucent and strokes opaque, so an overlapping cloud reads as density while each marker
+ * keeps a crisp edge. A `cross` is strokes only, so it skips the fill. */
+export function drawScatterMarkers(
+ ctx: CanvasRenderingContext2D,
+ positions: ScatterPointPosition[],
+ fillOpacity: number
+): void {
+ const fills = new Map<string, string>()
+ ctx.save()
+ ctx.lineWidth = MARKER_STROKE_WIDTH
+ for (const position of positions) {
+ traceScatterMarker(ctx, position.shape, position.x, position.y, position.radius)
+ if (position.shape !== 'cross') {
+ let fill = fills.get(position.color)
+ if (fill === undefined) {
+ fill = dimColor(position.color, fillOpacity)
+ fills.set(position.color, fill)
+ }
+ ctx.fillStyle = fill
+ ctx.fill()
+ }
+ ctx.strokeStyle = position.color
+ ctx.stroke()
+ }
+ ctx.restore()
+}
+
+export function drawScatterHoverMarker(
+ ctx: CanvasRenderingContext2D,
+ position: ScatterPointPosition,
+ backgroundColor: string,
+ alpha: number
+): void {
+ ctx.save()
+ ctx.globalAlpha = alpha
+ ctx.lineWidth = HOVER_HALO_WIDTH
+ ctx.strokeStyle = backgroundColor
+ traceScatterMarker(ctx, position.shape, position.x, position.y, position.radius + HOVER_HALO_RADIUS_PX)
+ ctx.stroke()
+ ctx.lineWidth = MARKER_STROKE_WIDTH
+ ctx.strokeStyle = position.color
+ ctx.fillStyle = position.color
+ traceScatterMarker(ctx, position.shape, position.x, position.y, position.radius)
+ if (position.shape !== 'cross') {
+ ctx.fill()
+ }
+ ctx.stroke()
+ ctx.restore()
+}
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/nearest-point.test.ts b/packages/quill/packages/charts/src/charts/ScatterChart/nearest-point.test.ts
new file mode 100644
index 000000000000..5b620d6a4214
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/nearest-point.test.ts
@@ -0,0 +1,35 @@
+import { findNearestPointIndex } from './nearest-point'
+import type { ScatterPointPosition } from './scatter-layout'
+
+function position(index: number, x: number, y: number, radius = 4): ScatterPointPosition {
+ return { index, x, y, radius, color: '#000', shape: 'circle' }
+}
+
+describe('findNearestPointIndex', () => {
+ // Two points on one x pixel: what an x-only bisector can't resolve.
+ const stacked = [position(0, 100, 20), position(1, 100, 200)]
+
+ it.each([
+ ['the upper point', 22, 0],
+ ['the lower point', 198, 1],
+ ])('picks %s when two points share an x position', (_, cursorY, expected) => {
+ expect(findNearestPointIndex(stacked, 100, cursorY, 4)).toBe(expected)
+ })
+
+ it('reports no hit when the cursor is in empty plot area', () => {
+ expect(findNearestPointIndex(stacked, 400, 110, 4)).toBe(-1)
+ })
+
+ it('hits a marker from just outside its edge but not from beyond the tolerance', () => {
+ const points = [position(7, 100, 100, 4)]
+ expect(findNearestPointIndex(points, 109, 100, 4)).toBe(7)
+ expect(findNearestPointIndex(points, 111, 100, 4)).toBe(-1)
+ })
+
+ it('prefers a large marker the cursor sits inside over a small one whose center is nearer', () => {
+ // The small marker's center is 5px away and the large one's 8px, but the cursor is inside
+ // the large marker.
+ const points = [position(0, 92, 100, 10), position(1, 105, 100, 2)]
+ expect(findNearestPointIndex(points, 100, 100, 10)).toBe(0)
+ })
+})
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/nearest-point.ts b/packages/quill/packages/charts/src/charts/ScatterChart/nearest-point.ts
new file mode 100644
index 000000000000..cf41b7161659
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/nearest-point.ts
@@ -0,0 +1,53 @@
+import type { ScatterPointPosition } from './scatter-layout'
+
+// How far past a marker's edge still counts as hovering it, so a small dot doesn't demand
+// pixel-perfect aim while empty plot area still reads as empty.
+const HOVER_TOLERANCE_PX = 6
+
+/** Global index of the marker nearest the cursor, or -1 when none is in reach. Ranking by distance to
+ * a marker's *edge* lets a large marker the cursor sits inside beat a small one centered nearer.
+ *
+ * `positions` must be x-sorted: this binary-searches to the cursor's x, then sweeps outward only
+ * while the x gap alone could still win, bounded by `maxRadius`. */
+export function findNearestPointIndex(
+ positions: ScatterPointPosition[],
+ cursorX: number,
+ cursorY: number,
+ maxRadius: number
+): number {
+ let lo = 0
+ let hi = positions.length
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1
+ if (positions[mid].x < cursorX) {
+ lo = mid + 1
+ } else {
+ hi = mid
+ }
+ }
+
+ let best = -1
+ let bestScore = HOVER_TOLERANCE_PX
+ const scoreAt = (i: number, dx: number): void => {
+ const score = Math.hypot(dx, positions[i].y - cursorY) - positions[i].radius
+ if (score < bestScore) {
+ bestScore = score
+ best = positions[i].index
+ }
+ }
+ for (let i = lo; i < positions.length; i++) {
+ const dx = positions[i].x - cursorX
+ if (dx - maxRadius > bestScore) {
+ break
+ }
+ scoreAt(i, dx)
+ }
+ for (let i = lo - 1; i >= 0; i--) {
+ const dx = cursorX - positions[i].x
+ if (dx - maxRadius > bestScore) {
+ break
+ }
+ scoreAt(i, dx)
+ }
+ return best
+}
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/scatter-data.test.ts b/packages/quill/packages/charts/src/charts/ScatterChart/scatter-data.test.ts
new file mode 100644
index 000000000000..a1909c9aa6dd
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/scatter-data.test.ts
@@ -0,0 +1,50 @@
+import { flattenScatterPoints, scatterValueRange } from './scatter-data'
+import type { ScatterSeries } from './types'
+
+describe('scatter-data', () => {
+ it('interleaves every series into one x-sorted list that remembers where each point came from', () => {
+ const series: ScatterSeries[] = [
+ {
+ key: 'a',
+ label: 'A',
+ points: [
+ { x: 30, y: 1 },
+ { x: 10, y: 2 },
+ ],
+ },
+ { key: 'b', label: 'B', points: [{ x: 20, y: 3 }] },
+ ]
+ expect(flattenScatterPoints(series).map((p) => [p.x, p.seriesKey, p.pointIndex])).toEqual([
+ [10, 'a', 1],
+ [20, 'b', 0],
+ [30, 'a', 0],
+ ])
+ })
+
+ it.each<[string, { x: number; y: number }, Parameters<typeof flattenScatterPoints>[1], { x: number }[]]>([
+ ['a non-finite x', { x: NaN, y: 1 }, undefined, [{ x: 5 }]],
+ ['a non-finite y', { x: 1, y: Infinity }, undefined, [{ x: 5 }]],
+ ['a zero on a log x axis', { x: 0, y: 1 }, { xLogScale: true }, [{ x: 5 }]],
+ ['a negative on a log y axis', { x: 1, y: -5 }, { yLogScale: true }, [{ x: 5 }]],
+ // A linear axis has room for both, so an over-eager filter fails this row.
+ ['a non-positive coordinate on a linear axis', { x: 0, y: -5 }, undefined, [{ x: 0 }, { x: 5 }]],
+ ])('keeps only what it can plot, given %s', (_, point, options, expected) => {
+ const series: ScatterSeries[] = [{ key: 'a', label: 'A', points: [point, { x: 5, y: 5 }] }]
+ expect(flattenScatterPoints(series, options)).toMatchObject(expected)
+ })
+
+ it('ranges each axis independently, and reports the smallest positive value for log domains', () => {
+ const points = flattenScatterPoints([
+ {
+ key: 'a',
+ label: 'A',
+ points: [
+ { x: -4, y: 2 },
+ { x: 8, y: 60 },
+ ],
+ },
+ ])
+ expect(scatterValueRange(points, 'x')).toMatchObject({ min: -4, max: 8, minPositive: 8, count: 2 })
+ expect(scatterValueRange(points, 'y')).toMatchObject({ min: 2, max: 60, minPositive: 2, count: 2 })
+ })
+})
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/scatter-data.ts b/packages/quill/packages/charts/src/charts/ScatterChart/scatter-data.ts
new file mode 100644
index 000000000000..9ef99f9e837c
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/scatter-data.ts
@@ -0,0 +1,80 @@
+import { extendValueRange } from '../../core/scales'
+import type { SeriesValueRange } from '../../core/scales'
+import type { Series } from '../../core/types'
+import type { ScatterPointDatum, ScatterSeries } from './types'
+
+/** A point in the chart's flat, x-sorted index space. Its position there is the `dataIndex` the base
+ * chart, the tooltip, and click payloads all speak in. */
+export interface FlatScatterPoint<Meta = unknown> {
+ seriesIndex: number
+ seriesKey: string
+ /** Index of this point within its own series' `points` array. */
+ pointIndex: number
+ x: number
+ y: number
+ label?: string
+ radius?: number
+ color?: string
+ meta?: Meta
+}
+
+// Clamping a non-positive coordinate onto a log axis' edge would draw it at a value it lacks.
+function isPlottable(value: number, logScale: boolean): boolean {
+ return Number.isFinite(value) && (!logScale || value > 0)
+}
+
+/** Flattened into one list, sorted by x so the hit test can binary-search it. Unplottable points are
+ * dropped here, so everything downstream works off a drawable list. */
+export function flattenScatterPoints<Meta>(
+ series: ScatterSeries<Meta>[],
+ options: { xLogScale?: boolean; yLogScale?: boolean } = {}
+): FlatScatterPoint<Meta>[] {
+ const { xLogScale = false, yLogScale = false } = options
+ const flat: FlatScatterPoint<Meta>[] = []
+ for (let seriesIndex = 0; seriesIndex < series.length; seriesIndex++) {
+ const s = series[seriesIndex]
+ for (let pointIndex = 0; pointIndex < s.points.length; pointIndex++) {
+ const point = s.points[pointIndex]
+ if (!isPlottable(point.x, xLogScale) || !isPlottable(point.y, yLogScale)) {
+ continue
+ }
+ flat.push({ ...point, seriesIndex, seriesKey: s.key, pointIndex })
+ }
+ }
+ return flat.sort((a, b) => a.x - b.x)
+}
+
+export function scatterValueRange(points: FlatScatterPoint[], axis: 'x' | 'y'): SeriesValueRange {
+ const empty: SeriesValueRange = { min: Infinity, max: -Infinity, minPositive: Infinity, count: 0 }
+ return extendValueRange(
+ empty,
+ points.map((point) => point[axis])
+ )
+}
+
+/** One base-chart series per scatter series, carrying its own points' y values at their global
+ * indices and a gap (NaN) everywhere else. The gaps are what make the legend, the y-margin sizing,
+ * and the tooltip rows resolve to the one series holding the hovered point. */
+export function toAdapterSeries(series: ScatterSeries<unknown>[], points: FlatScatterPoint[]): Series[] {
+ const data = series.map(() => new Array<number>(points.length).fill(NaN))
+ for (let i = 0; i < points.length; i++) {
+ data[points[i].seriesIndex][i] = points[i].y
+ }
+ return series.map((s, i) => ({ key: s.key, label: s.label, data: data[i], color: s.color }))
+}
+
+export function toPointDatum<Meta>(
+ point: FlatScatterPoint<Meta>,
+ owner: ScatterSeries<Meta> | undefined,
+ paletteColor: string
+): ScatterPointDatum<Meta> {
+ const { seriesKey, seriesIndex, pointIndex, ...rest } = point
+ return {
+ ...rest,
+ seriesKey,
+ seriesIndex,
+ pointIndex,
+ seriesLabel: owner?.label ?? '',
+ color: point.color ?? owner?.color ?? paletteColor,
+ }
+}
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/scatter-layout.ts b/packages/quill/packages/charts/src/charts/ScatterChart/scatter-layout.ts
new file mode 100644
index 000000000000..2c9d31d36f5d
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/scatter-layout.ts
@@ -0,0 +1,131 @@
+import { resolveCssColor } from '../../core/color-utils'
+import { yTickCountForHeight } from '../../core/scales'
+import type { D3YScale } from '../../core/scales'
+import type { ChartDimensions, ChartScales, ResolvedSeries, ScatterMarkerShape } from '../../core/types'
+import type { FlatScatterPoint } from './scatter-data'
+import { buildScatterAxisScale, domainBounds, resolveXTicks, xTickCountForWidth } from './scatter-scales'
+import type { ScatterAxisScale, ScatterXTick } from './scatter-scales'
+import type { ScatterSeries } from './types'
+
+export interface ScatterPointPosition {
+ /** Global index into the flattened point list. */
+ index: number
+ x: number
+ y: number
+ radius: number
+ color: string
+ shape: ScatterMarkerShape
+}
+
+/** What the draw, hit-test, and axis-overlay code read back out of `ChartScales._private`, so each
+ * render carries its own self-consistent layout rather than a side-channel ref. */
+export interface ScatterLayout {
+ xScale: D3YScale
+ yScale: D3YScale
+ /** Visible, drawable points in ascending x-pixel order, which the hit test binary-searches. */
+ positions: ScatterPointPosition[]
+ /** Resolved once, so the grid lines, the tick marks, and the labels are the same set. */
+ xTicks: ScatterXTick[]
+ maxRadius: number
+}
+
+interface ScatterChartPrivate {
+ __scatter: ScatterLayout
+}
+
+export function readScatterLayout(scales: ChartScales): ScatterLayout | undefined {
+ return (scales._private as ScatterChartPrivate | undefined)?.__scatter
+}
+
+export interface ScatterScalesInput {
+ points: FlatScatterPoint[]
+ /** Indexed by `FlatScatterPoint.seriesIndex`. */
+ seriesStyles: Pick<ScatterSeries, 'pointRadius' | 'shape'>[]
+ coloredSeries: ResolvedSeries[]
+ dimensions: ChartDimensions
+ xAxis: ScatterAxisScale
+ yAxis: ScatterAxisScale
+ xTickFormatter?: (value: number) => string
+ defaultPointRadius: number
+ fallbackColor: string
+}
+
+export function createScatterScales({
+ points,
+ seriesStyles,
+ coloredSeries,
+ dimensions,
+ xAxis,
+ yAxis,
+ xTickFormatter,
+ defaultPointRadius,
+ fallbackColor,
+}: ScatterScalesInput): ChartScales {
+ const hidden = new Set(coloredSeries.filter((s) => s.visibility?.excluded).map((s) => s.key))
+ const visiblePoints = hidden.size === 0 ? points : points.filter((p) => !hidden.has(p.seriesKey))
+
+ const xTickCount = xTickCountForWidth(dimensions.plotWidth)
+ const yTickCount = yTickCountForHeight(dimensions.plotHeight)
+ const xScale = buildScatterAxisScale(
+ visiblePoints,
+ 'x',
+ [dimensions.plotLeft, dimensions.plotLeft + dimensions.plotWidth],
+ xTickCount,
+ xAxis
+ )
+ const yScale = buildScatterAxisScale(
+ visiblePoints,
+ 'y',
+ [dimensions.plotTop + dimensions.plotHeight, dimensions.plotTop],
+ yTickCount,
+ yAxis
+ )
+ const [xLow, xHigh] = domainBounds(xScale)
+ const [yLow, yHigh] = domainBounds(yScale)
+
+ const positions: ScatterPointPosition[] = []
+ const xByIndex = new Array<number | undefined>(points.length)
+ let maxRadius = 0
+ for (let i = 0; i < points.length; i++) {
+ const point = points[i]
+ // A pinned domain narrows the chart rather than just its viewport, so a point outside it is
+ // dropped from drawing, hit-testing, and the hover halo alike. Left in, a linear scale draws
+ // it in the axis gutters and a clamped log scale on the plot edge, at a value it doesn't have.
+ if (hidden.has(point.seriesKey) || point.x < xLow || point.x > xHigh || point.y < yLow || point.y > yHigh) {
+ continue
+ }
+ const x = xScale(point.x)
+ const y = yScale(point.y)
+ if (!isFinite(x) || !isFinite(y)) {
+ continue
+ }
+ xByIndex[i] = x
+ const style = seriesStyles[point.seriesIndex]
+ const radius = point.radius ?? style?.pointRadius ?? defaultPointRadius
+ maxRadius = Math.max(maxRadius, radius)
+ positions.push({
+ index: i,
+ x,
+ y,
+ radius,
+ // Canvas can't resolve `var(--…)`, which a consumer color may still be.
+ color: resolveCssColor(point.color ?? coloredSeries[point.seriesIndex]?.color ?? fallbackColor),
+ shape: style?.shape ?? 'circle',
+ })
+ }
+
+ return {
+ x: (label: string) => xByIndex[Number(label)],
+ y: (value: number) => yScale(value),
+ yTicks: () => yScale.ticks?.(yTickCount) ?? [],
+ _private: {
+ __scatter: {
+ xScale,
+ yScale,
+ positions,
+ xTicks: resolveXTicks(xScale, xTickCount, xTickFormatter),
+ maxRadius,
+ },
+ } satisfies ScatterChartPrivate,
+ }
+}
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/scatter-scales.test.ts b/packages/quill/packages/charts/src/charts/ScatterChart/scatter-scales.test.ts
new file mode 100644
index 000000000000..38b10a9caea4
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/scatter-scales.test.ts
@@ -0,0 +1,31 @@
+import { flattenScatterPoints } from './scatter-data'
+import { xLabelEdgeReserve } from './scatter-scales'
+import type { ScatterSeries } from './types'
+
+jest.mock('../../utils/text-measure', () => ({
+ ...jest.requireActual('../../utils/text-measure'),
+ measureLabelWidth: (text: string) => text.length * 10,
+}))
+
+const POINTS = flattenScatterPoints([
+ {
+ key: 'a',
+ label: 'A',
+ points: [
+ { x: 30, y: 1 },
+ { x: 10, y: 2 },
+ ],
+ },
+] satisfies ScatterSeries[])
+
+describe('xLabelEdgeReserve', () => {
+ // measureLabelWidth is mocked above at 10px per character, over the 4px shared edge padding.
+ it.each<[string, Parameters<typeof xLabelEdgeReserve>, number]>([
+ // Ticks run to '$30' over the points' 10–30 span: 3 characters, so 15px of overhang.
+ ['half the widest tick label, formatted the way the axis formats it', [POINTS, undefined, (v) => `$${v}`], 19],
+ ['a pinned domain rather than the points', [POINTS, [0, 1000], (v) => `$${v}`], 29],
+ ['nothing when there is no point to label', [[], undefined, undefined], 0],
+ ])('reserves %s', (_, args, expected) => {
+ expect(xLabelEdgeReserve(...args)).toBe(expected)
+ })
+})
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/scatter-scales.ts b/packages/quill/packages/charts/src/charts/ScatterChart/scatter-scales.ts
new file mode 100644
index 000000000000..4e637919b7d0
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/scatter-scales.ts
@@ -0,0 +1,109 @@
+import { scaleLinear, scaleLog } from 'd3-scale'
+
+import { X_LABEL_EDGE_PADDING } from '../../core/hooks/useChartMargins'
+import { autoFormatterFor, buildValueScale, sanitizeFixedDomain } from '../../core/scales'
+import type { D3YScale } from '../../core/scales'
+import { computeVisibleValueTicks } from '../../overlays/AxisLabels'
+import { measureLabelWidth } from '../../utils/text-measure'
+import { scatterValueRange } from './scatter-data'
+import type { FlatScatterPoint } from './scatter-data'
+import type { ScatterAxisConfig } from './types'
+
+// Wider than the y axis' spacing because horizontal numeric labels are wide.
+const X_TICK_SPACING_PX = 90
+const MAX_X_TICKS = 12
+
+export interface ScatterXTick {
+ tick: number
+ text: string
+ x: number
+}
+
+export type ScatterAxisScale = Pick<ScatterAxisConfig, 'scaleType' | 'domain' | 'startAtZero'>
+
+export function xTickCountForWidth(plotWidth: number): number {
+ if (!isFinite(plotWidth) || plotWidth <= 0) {
+ return 2
+ }
+ return Math.max(2, Math.min(MAX_X_TICKS, Math.floor(plotWidth / X_TICK_SPACING_PX)))
+}
+
+/** Derived through the shared value-scale builder when unpinned, so a scatter axis gets the same log,
+ * degenerate-range, and `nice()` handling as every other value axis. */
+export function buildScatterAxisScale(
+ points: FlatScatterPoint[],
+ axis: 'x' | 'y',
+ pixelRange: [number, number],
+ tickCount: number,
+ { scaleType = 'linear', domain, startAtZero = false }: ScatterAxisScale
+): D3YScale {
+ if (domain) {
+ const [min, max] = sanitizeFixedDomain(domain)
+ // A log scale maps a non-positive bound to NaN, blanking the plot, so fall back to linear.
+ if (scaleType === 'log' && min > 0) {
+ return scaleLog().domain([min, max]).range(pixelRange).clamp(true)
+ }
+ return scaleLinear().domain([min, max]).range(pixelRange)
+ }
+ return buildValueScale({
+ range: scatterValueRange(points, axis),
+ valueRange: pixelRange,
+ tickCount,
+ scaleType,
+ floatBaseline: !startAtZero,
+ })
+}
+
+/** Thinned by label collision, since a grid line under no label reads as a stray. */
+export function resolveXTicks(
+ xScale: D3YScale,
+ tickCount: number,
+ tickFormatter: ((value: number) => string) | undefined
+): ScatterXTick[] {
+ const ticks = xScale.ticks?.(tickCount) ?? []
+ return computeVisibleValueTicks(ticks, xScale, tickFormatter ?? autoFormatterFor(ticks))
+}
+
+// A y range runs bottom-to-top and a domain may descend, so neither end is reliably the low one.
+function bounds(interval: number[]): [number, number] {
+ const first = interval[0]
+ const last = interval[interval.length - 1]
+ return first <= last ? [first, last] : [last, first]
+}
+
+export function domainBounds(scale: D3YScale): [number, number] {
+ return bounds(scale.domain())
+}
+
+/** A drag can end outside the plot, where inverting the raw pixel reports a value the user never
+ * brushed. A log scale clamps on `invert` already; this makes the linear one agree. */
+export function clampToRange(pixel: number, scale: D3YScale): number {
+ const [low, high] = bounds(scale.range())
+ return Math.min(Math.max(pixel, low), high)
+}
+
+/** Gutter for the outer half of a tick label centered on the plot's edge, which `overflow` would
+ * otherwise cut. An estimate, since the ticks that render depend on the plot width this decides. */
+export function xLabelEdgeReserve(
+ points: FlatScatterPoint[],
+ domain: readonly [number, number] | undefined,
+ tickFormatter: ((value: number) => string) | undefined
+): number {
+ let extent: [number, number]
+ if (domain) {
+ extent = sanitizeFixedDomain(domain)
+ } else {
+ const range = scatterValueRange(points, 'x')
+ if (range.count === 0) {
+ return 0
+ }
+ extent = [range.min, range.max]
+ }
+ const ticks = scaleLinear().domain(extent).nice(6).ticks(6)
+ const format = tickFormatter ?? autoFormatterFor(ticks)
+ let widest = 0
+ for (const tick of ticks) {
+ widest = Math.max(widest, measureLabelWidth(format(tick)))
+ }
+ return Math.ceil(widest / 2) + X_LABEL_EDGE_PADDING
+}
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/types.ts b/packages/quill/packages/charts/src/charts/ScatterChart/types.ts
new file mode 100644
index 000000000000..9f3c4dab4699
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/types.ts
@@ -0,0 +1,94 @@
+import type { ReactNode } from 'react'
+
+import type {
+ ChartLegendConfig,
+ ChartMargins,
+ ScatterMarkerShape,
+ TooltipConfig,
+ TooltipContext,
+} from '../../core/types'
+
+export type { ScatterMarkerShape }
+
+export interface ScatterPoint<Meta = unknown> {
+ x: number
+ y: number
+ /** Tooltip header. Falls back to the series label. */
+ label?: string
+ radius?: number
+ color?: string
+ /** Arbitrary consumer data, handed back on hover and click. */
+ meta?: Meta
+}
+
+export interface ScatterSeries<Meta = unknown> {
+ /** React key, legend identity, and the handle for hiding the series. */
+ key: string
+ label: string
+ points: ScatterPoint<Meta>[]
+ /** Omit to take a palette color by series index. */
+ color?: string
+ pointRadius?: number
+ shape?: ScatterMarkerShape
+}
+
+export interface ScatterAxisConfig {
+ /** A `log` axis drops points it can't place, meaning non-positive ones. */
+ scaleType?: 'linear' | 'log'
+ /** Pins the domain instead of deriving it from the data. Pass a range back from `onAreaSelect`
+ * for drag-to-zoom, or share one domain across sibling charts. */
+ domain?: readonly [number, number]
+ /** Axis title. */
+ label?: string
+ tickFormatter?: (value: number) => string
+ hide?: boolean
+ /** Off by default, because forcing either of two independent measures to zero squashes the
+ * correlation into a corner. No-op on a log scale. */
+ startAtZero?: boolean
+}
+
+export interface ScatterTooltipConfig<Meta = unknown> {
+ enabled?: boolean
+ placement?: TooltipConfig['placement']
+ labelFormatter?: (point: ScatterPointDatum<Meta>) => ReactNode
+ xFormatter?: (value: number, point: ScatterPointDatum<Meta>) => ReactNode
+ yFormatter?: (value: number, point: ScatterPointDatum<Meta>) => ReactNode
+}
+
+export interface ScatterChartConfig<Meta = unknown> {
+ xAxis?: ScatterAxisConfig
+ yAxis?: ScatterAxisConfig
+ pointRadius?: number
+ /** Under 1 so a dense cloud reads as denser rather than painting over itself. Markers keep an
+ * opaque outline either way. */
+ fillOpacity?: number
+ showGrid?: boolean
+ showAxisLines?: boolean
+ showTickMarks?: boolean
+ showCrosshair?: boolean
+ legend?: ChartLegendConfig
+ tooltip?: ScatterTooltipConfig<Meta>
+ /** Applied over the computed margins. Should be referentially stable (a module-level constant). */
+ margins?: Partial<ChartMargins>
+}
+
+export interface ScatterPointDatum<Meta = unknown> extends ScatterPoint<Meta> {
+ seriesKey: string
+ seriesLabel: string
+ seriesIndex: number
+ /** Index of this point within its own series' `points` array. */
+ pointIndex: number
+ color: string
+}
+
+/** {@link TooltipContext} with the hovered point resolved, since the base context's `dataIndex`
+ * refers to the chart's internal flat index space. */
+export interface ScatterTooltipContext<Meta = unknown> extends TooltipContext {
+ point: ScatterPointDatum<Meta>
+}
+
+/** Bounds of a completed drag, in the points' own units. Feed back as an axis `domain` to zoom. */
+export interface ScatterAreaSelection {
+ x: [number, number]
+ y: [number, number]
+}
diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.test.ts b/packages/quill/packages/charts/src/core/canvas-renderer.test.ts
index ed2fa0f09c16..e9a57f746fbf 100644
--- a/packages/quill/packages/charts/src/core/canvas-renderer.test.ts
+++ b/packages/quill/packages/charts/src/core/canvas-renderer.test.ts
@@ -13,9 +13,10 @@ import {
drawSelectionRect,
drawTickMarks,
resolveAxisLineColor,
+ traceScatterMarker,
withVerticalClip,
} from './canvas-renderer'
-import type { ChartDrawArgs, ChartTheme } from './types'
+import type { ChartDrawArgs, ChartTheme, ScatterMarkerShape } from './types'
function mockCanvasContext(): jest.Mocked<CanvasRenderingContext2D> {
return {
@@ -1181,6 +1182,49 @@ describe('hog-charts canvas-renderer', () => {
}
)
})
+
+ describe('traceScatterMarker', () => {
+ it.each<[ScatterMarkerShape, 'arc' | 'rect', number[]]>([
+ ['circle', 'arc', [10, 20, 6, 0, Math.PI * 2]],
+ ['square', 'rect', [4, 14, 12, 12]],
+ ])('traces a %s as one path spanning the radius on every side', (shape, method, args) => {
+ const ctx = mockCanvasContext()
+
+ traceScatterMarker(ctx, shape, 10, 20, 6)
+
+ expect(ctx.beginPath).toHaveBeenCalledTimes(1)
+ expect(ctx[method]).toHaveBeenCalledWith(...args)
+ })
+
+ it('centers a triangle on the data point, not on its bounding box', () => {
+ const ctx = mockCanvasContext()
+
+ traceScatterMarker(ctx, 'triangle', 10, 20, 6)
+
+ const vertices = [...ctx.moveTo.mock.calls, ...ctx.lineTo.mock.calls]
+ expect(vertices).toHaveLength(3)
+ const centroid = vertices.reduce(([sx, sy], [x, y]) => [sx + x / 3, sy + y / 3], [0, 0])
+ expect(centroid).toEqual([10, 20])
+ expect(ctx.closePath).toHaveBeenCalledTimes(1)
+ })
+
+ it('traces a cross as two open strokes', () => {
+ const ctx = mockCanvasContext()
+
+ traceScatterMarker(ctx, 'cross', 10, 20, 6)
+
+ expect(ctx.moveTo.mock.calls).toEqual([
+ [4, 14],
+ [16, 14],
+ ])
+ expect(ctx.lineTo.mock.calls).toEqual([
+ [16, 26],
+ [4, 26],
+ ])
+ // Closing the path would break ScatterChart's "a cross is strokes only" fill skip.
+ expect(ctx.closePath).not.toHaveBeenCalled()
+ })
+ })
})
describe('withVerticalClip', () => {
diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.ts b/packages/quill/packages/charts/src/core/canvas-renderer.ts
index 974b1d94d273..a68f5feb888a 100644
--- a/packages/quill/packages/charts/src/core/canvas-renderer.ts
+++ b/packages/quill/packages/charts/src/core/canvas-renderer.ts
@@ -10,6 +10,7 @@ import type {
ChartTheme,
DrawHoverResult,
ResolvedSeries,
+ ScatterMarkerShape,
} from './types'
export interface DrawContext {
@@ -591,6 +592,41 @@ export function drawPoints(drawCtx: DrawContext, series: ResolvedSeries, yValues
}
}
+/** Trace a scatter marker's outline at (x, y) without painting it, so the caller can fill it
+ * translucently and stroke it opaquely from one traced path. `radius` is the glyph's half-extent,
+ * so every shape spans the same width as a circle of that radius. `cross` traces two open strokes
+ * and can only be stroked. */
+export function traceScatterMarker(
+ ctx: CanvasRenderingContext2D,
+ shape: ScatterMarkerShape,
+ x: number,
+ y: number,
+ radius: number
+): void {
+ ctx.beginPath()
+ switch (shape) {
+ case 'square':
+ ctx.rect(x - radius, y - radius, radius * 2, radius * 2)
+ return
+ case 'triangle':
+ // Base at half the radius, which puts the centroid rather than the bounding box on the
+ // data point, so the glyph's visual weight sits where the value is.
+ ctx.moveTo(x, y - radius)
+ ctx.lineTo(x + radius, y + radius * 0.5)
+ ctx.lineTo(x - radius, y + radius * 0.5)
+ ctx.closePath()
+ return
+ case 'cross':
+ ctx.moveTo(x - radius, y - radius)
+ ctx.lineTo(x + radius, y + radius)
+ ctx.moveTo(x + radius, y - radius)
+ ctx.lineTo(x - radius, y + radius)
+ return
+ default:
+ ctx.arc(x, y, radius, 0, Math.PI * 2)
+ }
+}
+
/** Snap a coordinate to the nearest half-pixel so a 1px stroke fills exactly one pixel row/column.
* Every axis-adjacent stroke — grid lines, axis baselines, tick marks — must share this rule, or
* they land one pixel apart and visibly misalign. */
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
index 64326ec24030..aba5676774cc 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
@@ -24,7 +24,9 @@ const Y_LABEL_LEFT_GUTTER = 6
/** Horizontal gap between stacked value-axis gutters on the same side — shared by the margin
* reservation here and the gutter rendering in AxisLabels so the two can't drift. */
export const GUTTER_GAP = 12
-const X_LABEL_EDGE_PADDING = 4
+/** Breathing room past half an edge tick label, so the outermost label doesn't sit flush against
+ * the wrapper's clip. Shared with chart types that reserve their own x-label gutters. */
+export const X_LABEL_EDGE_PADDING = 4
export const X_AXIS_TITLE_MARGIN = 22
export const Y_AXIS_TITLE_MARGIN = 24
diff --git a/packages/quill/packages/charts/src/core/hooks/useDragToZoom.ts b/packages/quill/packages/charts/src/core/hooks/useDragToZoom.ts
index 855a9556749f..0fcc1f9e1234 100644
--- a/packages/quill/packages/charts/src/core/hooks/useDragToZoom.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useDragToZoom.ts
@@ -83,6 +83,8 @@ export function useDragToZoom({
if (onAreaSelectRef.current) {
onAreaSelectRef.current({
...labelRange,
+ xPixel0: Math.min(origin.x, mouseX),
+ xPixel1: Math.max(origin.x, mouseX),
yPixel0: Math.min(origin.y, mouseY),
yPixel1: Math.max(origin.y, mouseY),
})
diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.ts
index 6f1be6ef2902..0086473629d6 100644
--- a/packages/quill/packages/charts/src/core/types.ts
+++ b/packages/quill/packages/charts/src/core/types.ts
@@ -544,8 +544,15 @@ export type DateRangeZoomData = LabelRange
/** Payload of a completed 2D brush ({@link ChartProps.onAreaSelect}). The x axis resolves to
* labels like `onDateRangeZoom`; the y axis stays in canvas pixels — the core is label-generic
* and has no y-band concept, so chart-type adapters map the pixel range onto their own scales
- * (e.g. the Heatmap converts it to row indices). */
+ * (e.g. the Heatmap converts it to row indices). The raw x pixels come along too, for chart types
+ * whose x axis is continuous rather than a band (e.g. ScatterChart inverts them back to data
+ * values), where the label range would round the selection to whichever points sit near the drag
+ * edges. */
export interface AreaSelectData extends LabelRange {
+ /** Left edge of the dragged range in canvas pixels (always <= xPixel1). */
+ xPixel0: number
+ /** Right edge of the dragged range in canvas pixels. */
+ xPixel1: number
/** Top of the dragged range in canvas pixels (always <= yPixel1). */
yPixel0: number
/** Bottom of the dragged range in canvas pixels. */
@@ -597,6 +604,10 @@ export interface BoxRect {
dataIndex: number
}
+/** Marker glyph drawn at a scatter point. `cross` is the one open glyph, so it stays readable as a
+ * distinct category where the filled shapes overlap into a blob. */
+export type ScatterMarkerShape = 'circle' | 'square' | 'triangle' | 'cross'
+
/** Generic scale interface that Chart uses for shared overlays and interaction. */
export interface ChartScales {
/** Maps a label to an x pixel coordinate. For chart types where data points
diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.ts
index 40897463d4d8..63896303bbbb 100644
--- a/packages/quill/packages/charts/src/index.ts
+++ b/packages/quill/packages/charts/src/index.ts
@@ -7,6 +7,21 @@ export { funnelConversionRate, funnelFromCounts, RATE_TO_PERCENT } from './chart
export type { FunnelFromCountsOptions, FunnelStepCount } from './charts/FunnelChart/funnel-data'
export { LineChart } from './charts/LineChart/LineChart'
export type { LineChartProps } from './charts/LineChart/LineChart'
+export { ScatterChart } from './charts/ScatterChart/ScatterChart'
+export type { ScatterChartProps } from './charts/ScatterChart/ScatterChart'
+export { ScatterTooltip } from './charts/ScatterChart/ScatterTooltip'
+export type { ScatterTooltipProps } from './charts/ScatterChart/ScatterTooltip'
+export type {
+ ScatterAreaSelection,
+ ScatterAxisConfig,
+ ScatterChartConfig,
+ ScatterMarkerShape,
+ ScatterPoint,
+ ScatterPointDatum,
+ ScatterSeries,
+ ScatterTooltipConfig,
+ ScatterTooltipContext,
+} from './charts/ScatterChart/types'
export { ComboChart } from './charts/ComboChart/ComboChart'
export type { ComboChartProps } from './charts/ComboChart/ComboChart'
export { TimeSeriesLineChart } from './charts/TimeSeriesLineChart/TimeSeriesLineChart'