From 57aeca0992ef28da162b71bffcaf02ddb2809931 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Sun, 22 Nov 2026 19:14:21 -0700 Subject: [PATCH 01/40] chore(mosaic): add d3-scale and d3-shape for the bar chart primitive --- .changeset/mosaic-bar-chart-primitive.md | 2 + packages/mosaic/package.json | 6 +- pnpm-lock.yaml | 120 ++++++++++++++++++++++- 3 files changed, 123 insertions(+), 5 deletions(-) create mode 100644 .changeset/mosaic-bar-chart-primitive.md diff --git a/.changeset/mosaic-bar-chart-primitive.md b/.changeset/mosaic-bar-chart-primitive.md new file mode 100644 index 00000000000..a845151cc84 --- /dev/null +++ b/.changeset/mosaic-bar-chart-primitive.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/packages/mosaic/package.json b/packages/mosaic/package.json index 2d5998d426c..27c53f017a7 100644 --- a/packages/mosaic/package.json +++ b/packages/mosaic/package.json @@ -537,7 +537,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 +551,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/pnpm-lock.yaml b/pnpm-lock.yaml index 336f102d0e7..c9ff469e5fd 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==} @@ -18260,7 +18324,7 @@ snapshots: dependencies: '@types/istanbul-lib-coverage': 2.0.6 '@types/istanbul-reports': 3.0.4 - '@types/node': 22.20.1 + '@types/node': 24.19.2 '@types/yargs': 15.0.20 chalk: 4.1.2 optional: true @@ -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 @@ -21489,7 +21565,7 @@ snapshots: '@types/ws@7.4.7': dependencies: - '@types/node': 22.20.1 + '@types/node': 12.20.55 '@types/ws@8.18.1': dependencies: @@ -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 @@ -26643,7 +26755,7 @@ snapshots: jest-worker@27.5.1: dependencies: - '@types/node': 22.20.1 + '@types/node': 24.19.2 merge-stream: 2.0.0 supports-color: 8.1.1 optional: true @@ -30217,7 +30329,7 @@ snapshots: rpc-websockets@9.3.8: dependencies: - '@swc/helpers': 0.5.21 + '@swc/helpers': 0.5.23 '@types/uuid': 10.0.0 '@types/ws': 8.18.1 buffer: 6.0.3 From fa7b8ad874ee513eb62e3fc338984f42a8515f42 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Sun, 22 Nov 2026 19:18:08 -0700 Subject: [PATCH 02/40] feat(mosaic): port the bar chart layout, canvas, selection and tick modules --- .../__tests__/bar-chart-layout.test.ts | 91 +++++ .../__tests__/calendar-ticks.test.ts | 106 +++++ .../bar-chart/__tests__/x-ticks.test.ts | 123 ++++++ .../primitives/bar-chart/bar-chart-canvas.ts | 294 ++++++++++++++ .../primitives/bar-chart/bar-chart-layout.ts | 376 ++++++++++++++++++ .../bar-chart/bar-chart-selection.ts | 179 +++++++++ .../primitives/bar-chart/calendar-ticks.ts | 96 +++++ .../mosaic/src/primitives/bar-chart/types.ts | 81 ++++ .../src/primitives/bar-chart/x-ticks.ts | 137 +++++++ 9 files changed, 1483 insertions(+) create mode 100644 packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts create mode 100644 packages/mosaic/src/primitives/bar-chart/__tests__/calendar-ticks.test.ts create mode 100644 packages/mosaic/src/primitives/bar-chart/__tests__/x-ticks.test.ts create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-canvas.ts create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts create mode 100644 packages/mosaic/src/primitives/bar-chart/calendar-ticks.ts create mode 100644 packages/mosaic/src/primitives/bar-chart/types.ts create mode 100644 packages/mosaic/src/primitives/bar-chart/x-ticks.ts diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts new file mode 100644 index 00000000000..90acee62f81 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from 'vitest'; + +import { DEFAULT_CHART_MARGIN, prepareStackedBars, projectStackedBars } from '../bar-chart-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/bar-chart/__tests__/calendar-ticks.test.ts b/packages/mosaic/src/primitives/bar-chart/__tests__/calendar-ticks.test.ts new file mode 100644 index 00000000000..40a8964e93e --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/calendar-ticks.test.ts @@ -0,0 +1,106 @@ +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) => + selectCalendarTicks({ + timestamps, + plot: { x: 76, width: width - 92 }, + 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('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/bar-chart/__tests__/x-ticks.test.ts b/packages/mosaic/src/primitives/bar-chart/__tests__/x-ticks.test.ts new file mode 100644 index 00000000000..369d986c552 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/x-ticks.test.ts @@ -0,0 +1,123 @@ +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.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/bar-chart/bar-chart-canvas.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-canvas.ts new file mode 100644 index 00000000000..8ac51c67018 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-canvas.ts @@ -0,0 +1,294 @@ +import { getComputedStyle } from '../utils/dom'; +import { type BarGeometry, type PaintedProjection, UNSTYLED_BAR_GEOMETRY } from './bar-chart-layout'; +import type { BarIdentity, BarMark, ChartSize } from './types'; + +const TILE_DEVICE_PIXELS = 32; + +export class CanvasRenderError extends Error { + constructor(message: string, cause: unknown) { + super(message, { cause }); + this.name = 'CanvasRenderError'; + } +} + +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 `BarChart.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, + }; +} + +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 }; +} + +type PaintOptions = Readonly<{ + canvas: HTMLCanvasElement; + marks: readonly BarMark[]; + projection: PaintedProjection | null; + size: ChartSize; + pixelRatio: number; + isBarActive?: (bar: BarIdentity) => boolean; + /** The `BarChart.Bar` element. Without it, nothing is painted. */ + bar: BarStyleElement | null; +}>; + +export function paintStackedBarCanvas({ + canvas, + marks, + projection, + size, + pixelRatio, + isBarActive, + bar, +}: 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(); + } + 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/bar-chart/bar-chart-layout.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts new file mode 100644 index 00000000000..945351ac22c --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts @@ -0,0 +1,376 @@ +import { scaleBand, scaleLinear } from 'd3-scale'; +import { stack, stackOffsetDiverging } from 'd3-shape'; + +import type { BarCategory, BarMark, BarProjection, BarSeries, ChartFrame, ChartMargin, ChartSize } from './types'; + +const Y_TICK_COUNT = 5; + +export const DEFAULT_CHART_MARGIN: ChartMargin = { + top: 8, + right: 16, + bottom: 36, + left: 52, +}; + +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 = ChartFrame & + Readonly<{ + categoryGap: number; + projection?: BarProjection; + }>; + +/** Bar geometry read from `BarChart.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; + } +} + +function projectMarksAndPaintInsets(layout: StackedBarLayout, { maxWidth, gap }: BarGeometry) { + 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 barWidth = Math.min(category.bandWidth, maxWidth); + 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: category.bandX + (category.bandWidth - barWidth) / 2, + y: rawTop, + width: barWidth, + 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, + bandX, + bandWidth: 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 { x, y, innerWidth, innerHeight } = scales; + const projectedBar = projectOptionalProjection(prepared.indexes, acceptedProjection, scales); + + return { + prepared, + scaleY: (value: number) => y(value), + categories: projectCategories(prepared, projectedBar, scales), + step: x.step(), + 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>; + +export function projectStackedBarMarks( + layout: StackedBarLayout, + geometry: BarGeometry, +): BarMark[] { + return applyCornerRadii(projectMarksAndPaintInsets(layout, geometry), geometry); +} + +export type PaintedProjection = NonNullable['projection']> & Readonly<{ radius: number }>; + +export function fitProjectionToBar( + projection: StackedBarLayout['projection'], + { maxWidth, outerRadius }: BarGeometry, +): PaintedProjection | null { + if (!projection) { + return null; + } + const width = Math.min(projection.width, maxWidth); + return { + ...projection, + x: projection.x + (projection.width - width) / 2, + width, + radius: Math.min(outerRadius, width / 2), + }; +} diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts new file mode 100644 index 00000000000..0013501b943 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts @@ -0,0 +1,179 @@ +import type { StackedBarLayout } from './bar-chart-layout'; +import type { ActiveBar, BarCategory, BarSection, BarSelection } from './types'; + +export type Selected = Readonly<{ + status: 'selected'; + source: 'pointer' | 'keyboard'; + category: string; + /** Null when the keyboard lands on a category with nothing to select. */ + section: BarSection | 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: Selected | null }> + | Readonly<{ type: 'keyboard'; category: BarCategory | undefined; section?: BarSection }> + | Readonly<{ type: 'clear' }> + | Readonly<{ type: 'dismiss' }>; + +export const NO_SELECTION: SelectionState = { status: 'none' }; + +export function selectionReducer(state: SelectionState, action: SelectionAction): SelectionState { + switch (action.type) { + case 'pointer': + return action.selection ?? NO_SELECTION; + case 'clear': + return state.status === 'dismissed' ? state : NO_SELECTION; + case 'dismiss': + return { status: 'dismissed' }; + case 'keyboard': { + const { category, section } = action; + if (!category) { + return NO_SELECTION; + } + return { + status: 'selected', + source: 'keyboard', + category: category.key, + section: + section && category.sections[section] + ? section + : category.sections.positive + ? 'positive' + : category.sections.negative + ? 'negative' + : null, + }; + } + } +} + +export function hitTest( + layout: StackedBarLayout, + local: Readonly<{ x: number; y: number }>, + stickySection: BarSection | undefined, +): Selected | null { + const first = layout.categories[0]; + if (!first) { + return null; + } + const datumIndex = Math.max( + 0, + Math.min(layout.categories.length - 1, Math.round((local.x - first.center) / layout.step)), + ); + const category = layout.categories[datumIndex]; + if (!category) { + return null; + } + const { positive, negative } = category.sections; + if (!positive && !negative) { + return null; + } + const nearZero = Math.abs(local.y - layout.zeroY) <= Math.max(4, Math.round(layout.plot.height * 0.015)); + const section: BarSection = !negative + ? 'positive' + : !positive + ? 'negative' + : nearZero + ? (stickySection ?? 'positive') + : local.y < layout.zeroY + ? 'positive' + : 'negative'; + return { status: 'selected', source: 'pointer', category: category.key, section }; +} + +export function selectedState(state: SelectionState): Selected | null { + return state.status === 'selected' ? state : null; +} + +export function isSelectable(selection: Selected, category: BarCategory) { + return selection.section === null || category.sections[selection.section]; +} + +export function resolveSelection(selection: Selected | null, category: BarCategory | undefined): BarSelection | null { + if (!selection?.section || !category?.sections[selection.section]) { + return null; + } + return { + category: category.key, + datumIndex: category.datumIndex, + section: selection.section, + }; +} + +export function sameSelection(a: BarSelection | null, b: BarSelection | null) { + return a?.category === b?.category && a?.datumIndex === b?.datumIndex && a?.section === b?.section; +} + +export function getActiveBar( + bar: BarSelection | null, + data: readonly TDatum[], + categoryByKey: ReadonlyMap, +): ActiveBar | null { + const datum = bar ? data[bar.datumIndex] : undefined; + const category = bar ? categoryByKey.get(bar.category) : undefined; + if (!bar || datum === undefined || !category) { + return null; + } + return { + ...bar, + datum, + hasValues: category.hasValues, + projected: category.projected, + }; +} + +export type KeyIntent = + | Readonly<{ type: 'dismiss' }> + | Readonly<{ type: 'select'; index: number; section: BarSection | undefined; activate: boolean }>; + +export function getKeyIntent( + key: string, + index: number, + lastIndex: number, + section: BarSection | undefined, + canActivate: boolean, +): KeyIntent | null { + switch (key) { + case 'Escape': + return { type: 'dismiss' }; + case 'ArrowUp': + return { type: 'select', index, section: 'positive', activate: false }; + case 'ArrowDown': + return { type: 'select', index, section: 'negative', activate: false }; + case 'ArrowLeft': + return { type: 'select', index: index - 1, section, activate: false }; + case 'ArrowRight': + return { type: 'select', index: index + 1, section, activate: false }; + case 'Home': + return { type: 'select', index: 0, section, activate: false }; + case 'End': + return { type: 'select', index: lastIndex, section, activate: false }; + case 'Enter': + case ' ': + return canActivate ? { type: 'select', index, section, activate: true } : null; + default: + return null; + } +} + +export function getKeyboardAnnouncement( + selection: Selected | null, + category: BarCategory | undefined, + formatCategory: (category: string) => string | null, +) { + if (selection?.source !== 'keyboard') { + return ''; + } + if (selection.section) { + const label = formatCategory(selection.category) ?? selection.category; + return `${label}, ${selection.section} values`; + } + const hasValues = !!category && (category.sections.positive || category.sections.negative); + return hasValues ? '' : 'No values for this period'; +} diff --git a/packages/mosaic/src/primitives/bar-chart/calendar-ticks.ts b/packages/mosaic/src/primitives/bar-chart/calendar-ticks.ts new file mode 100644 index 00000000000..06a4372b1e0 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/calendar-ticks.ts @@ -0,0 +1,96 @@ +type CalendarTick = Readonly<{ label: string; coordinate: number }>; + +type CalendarAxis = Readonly<{ + timestamps: 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[], plot: CalendarAxis['plot']): 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 offset = rightDate === leftDate ? right : left + (timestamp - leftDate) / (rightDate - leftDate); + return plot.x + ((offset + 0.5) / timestamps.length) * plot.width; +} + +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, 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, plot), + })) + .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/bar-chart/types.ts b/packages/mosaic/src/primitives/bar-chart/types.ts new file mode 100644 index 00000000000..e8a1d3f2e45 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/types.ts @@ -0,0 +1,81 @@ +export type ChartSize = Readonly<{ width: number; height: number }>; + +export type ChartMargin = Readonly<{ + top: number; + right: number; + bottom: number; + left: number; +}>; + +/** The measured container and the margin around the plot. */ +export type ChartFrame = Readonly<{ size: ChartSize; margin: ChartMargin }>; + +export type ChartPlot = Readonly<{ + x: number; + y: number; + width: number; + height: number; +}>; + +export type ChartTick = Readonly<{ value: number; y: number }>; + +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; +}>; + +export type BarSeries = Readonly<{ + key: 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'; + +export type BarCategory = Readonly<{ + key: string; + datumIndex: number; + bandX: number; + bandWidth: number; + center: number; + /** 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; +}>; + +export type BarSelection = Readonly<{ + category: string; + datumIndex: number; + section: BarSection; +}>; + +export type ActiveBar = BarSelection & + Readonly<{ + datum: TDatum; + hasValues: BarCategory['hasValues']; + projected: BarCategory['projected']; + }>; diff --git a/packages/mosaic/src/primitives/bar-chart/x-ticks.ts b/packages/mosaic/src/primitives/bar-chart/x-ticks.ts new file mode 100644 index 00000000000..45cb2bafe12 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/x-ticks.ts @@ -0,0 +1,137 @@ +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; + +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'; +}>; + +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 hasDistinctEdges = categories.length > 1; + 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 isFirst = hasDistinctEdges && datumIndex === 0; + const isLast = hasDistinctEdges && datumIndex === categories.length - 1; + const placement: Pick = isFirst + ? { x: plot.x + EDGE_INSET, textAnchor: 'start' } + : isLast + ? { x: plot.x + plot.width - EDGE_INSET, textAnchor: 'end' } + : { x: category.center, textAnchor: 'middle' }; + const width = measure(label); + 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, + 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), + })); +} From f85e0feaa8ccd129a69e1517765ba3c9b10c0a58 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Sun, 22 Nov 2026 19:24:58 -0700 Subject: [PATCH 03/40] feat(mosaic): add the BarChart primitive parts and tooltip --- .../bar-chart/__tests__/bar-chart.test.tsx | 395 +++++++++++++++++ .../bar-chart/__tests__/fixtures.tsx | 98 +++++ .../bar-chart/__tests__/test-chart.tsx | 83 ++++ .../bar-chart/bar-chart-bar-selection.tsx | 397 ++++++++++++++++++ .../primitives/bar-chart/bar-chart-bar.tsx | 30 ++ .../primitives/bar-chart/bar-chart-context.ts | 78 ++++ .../primitives/bar-chart/bar-chart-cursor.tsx | 37 ++ .../bar-chart/bar-chart-grid-line.tsx | 34 ++ .../primitives/bar-chart/bar-chart-grid.tsx | 33 ++ .../bar-chart-projection-outline.tsx | 34 ++ .../primitives/bar-chart/bar-chart-root.tsx | 79 ++++ .../bar-chart/bar-chart-stacked-bars.tsx | 146 +++++++ .../bar-chart/bar-chart-tooltip.tsx | 130 ++++++ .../primitives/bar-chart/bar-chart-x-axis.tsx | 53 +++ .../primitives/bar-chart/bar-chart-x-tick.tsx | 36 ++ .../primitives/bar-chart/bar-chart-y-axis.tsx | 46 ++ .../primitives/bar-chart/bar-chart-y-tick.tsx | 32 ++ .../bar-chart/bar-chart-zero-line.tsx | 30 ++ .../mosaic/src/primitives/bar-chart/index.ts | 37 ++ .../mosaic/src/primitives/bar-chart/parts.ts | 23 + .../primitives/bar-chart/use-chart-size.ts | 49 +++ .../bar-chart/use-stacked-bar-layout.ts | 44 ++ 22 files changed, 1924 insertions(+) create mode 100644 packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/__tests__/fixtures.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/__tests__/test-chart.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-bar.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-context.ts create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-cursor.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-grid-line.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-grid.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-projection-outline.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-root.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-x-axis.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-x-tick.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-y-axis.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-y-tick.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-zero-line.tsx create mode 100644 packages/mosaic/src/primitives/bar-chart/index.ts create mode 100644 packages/mosaic/src/primitives/bar-chart/parts.ts create mode 100644 packages/mosaic/src/primitives/bar-chart/use-chart-size.ts create mode 100644 packages/mosaic/src/primitives/bar-chart/use-stacked-bar-layout.ts diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx new file mode 100644 index 00000000000..d3d1798e6f5 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx @@ -0,0 +1,395 @@ +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 type { RenderProps } from '../../utils'; +import { BarChart, type BarSelection } from '../index'; +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 layout = BarChart.useStackedBarLayout({ 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([ + ['Grid', ], + ['StackedBars', ], + ['BarSelection', ], + ])('throws when BarChart.%s is used outside BarChart.Root', (part, element) => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + expect(() => renderComponent(element)).toThrow(` must be used within `); + }); + + it.each([ + ['Cursor', ], + ['Tooltip', {() => 'Growth'}], + ])('throws when BarChart.%s is used outside BarChart.BarSelection', (part, element) => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + expect(() => render({element})).toThrow( + ` must be used within `, + ); + }); + + it('throws when BarChart.Bar is used outside BarChart.StackedBars', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + expect(() => + render( + + + , + ), + ).toThrow(' must be used within '); + }); + + 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 BarChart.BarSelection 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({ barSelection: 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 }); + }); + + it.each([ + { + name: 'the selected period and section', + props: { data: quarter }, + keys: ['ArrowRight'], + announcement: 'Feb, positive values', + }, + { + name: 'the formatted period name', + props: { + data: quarter, + formatXTick: (period: string) => `${period} 2026`, + }, + keys: [], + announcement: 'Jan 2026, positive values', + }, + { + 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')).toHaveTextContent(announcement); + }); +}); + +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, onActiveChange: 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 })); + }); + + 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' })); + }); + + 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, positive values'); + fireEvent.keyDown(interaction, { key: 'Enter' }); + expect(active()).toMatchObject({ category: 'Mar', section: 'positive' }); + expect(onActivate).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ datum, datumIndex: 0, section: 'positive' }), + ); + }); + + 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 onActiveChange = vi.fn(); + const onActivate = vi.fn(); + const { interaction, getByRole } = renderChart({ + data: [{ period: 'Jan', value: 0 }], + projection, + onActiveChange, + onActivate, + }); + + fireEvent.focus(interaction); + expect(getByRole('status')).toHaveTextContent('No values for this period'); + fireEvent.keyDown(interaction, { key: 'Enter' }); + + expect(onActiveChange).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, positive values'); + fireEvent.keyDown(getByRole('button'), { key: 'Enter' }); + expect(onActivate).toHaveBeenLastCalledWith(expect.objectContaining({ datum: refreshed, datumIndex: 1 })); + }); + + 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' + onActiveChange={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] })); + } + }, + ); + + 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'); + rerenderChart({ data: [{ period: 'Jan', gained: 10, lost: 0 }] }); + expect(active()).toBeNull(); + expect(getByRole('status')).toBeEmptyDOMElement(); + fireEvent.keyDown(control, { key: 'ArrowDown' }); + expect(getByRole('status')).toHaveTextContent('Jan, positive values'); + }); +}); + +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, positive values'); + + rerenderChart({ data: [{ period: 'Feb', value: 25 }] }); + expect(getByRole('status')).toBeEmptyDOMElement(); + + fireEvent.keyDown(interaction, { key: 'Home' }); + expect(getByRole('status')).toHaveTextContent('Feb, positive values'); + }); +}); diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/fixtures.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/fixtures.tsx new file mode 100644 index 00000000000..b6d78477703 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/fixtures.tsx @@ -0,0 +1,98 @@ +import { act, render as renderComponent } from '@testing-library/react'; +import type { ReactElement } from 'react'; +import { vi } from 'vitest'; + +import type { BarSelection } from '../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 last published selection. + */ +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 onActiveChange = vi.fn<(active: BarSelection | null) => void>(); + const chartProps = { ...base, onActiveChange, ...props }; + const view = render(); + const name = chartProps.ariaLabel; + const interaction = view.queryByRole('button', { name }) ?? view.getByRole('group', { name }); + return { + ...view, + interaction, + active: () => onActiveChange.mock.lastCall?.[0] ?? 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(), +}; + +/** 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/bar-chart/__tests__/test-chart.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/test-chart.tsx new file mode 100644 index 00000000000..cccbb656895 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/test-chart.tsx @@ -0,0 +1,83 @@ +import type { ReactNode } from 'react'; + +import { + BarChart, + type BarChartBarSelectionProps, + type BarChartStackedBarsProps, + type StackedBarLayoutOptions, +} from '../index'; +import type { ActiveBar } from '../types'; + +export type TestChartProps = StackedBarLayoutOptions & + Pick, 'onActiveChange' | 'onActivate'> & { + ariaLabel: string; + formatXTick?: (value: string) => string | null; + /** Mounts `BarChart.BarSelection`. Default: true */ + barSelection?: boolean; + renderTooltip?: (active: ActiveBar) => ReactNode; + boundary?: React.RefObject; + height?: number | string; + barClassName?: string; + isBarActive?: BarChartStackedBarsProps['isBarActive']; + }; + +/** Composes every bar chart part from one flat set of test props. */ +export function TestChart({ + data, + series, + index, + categoryGap, + projection, + ariaLabel, + formatXTick, + barSelection = true, + onActiveChange, + onActivate, + renderTooltip, + boundary, + height, + barClassName, + isBarActive, +}: TestChartProps) { + const layout = BarChart.useStackedBarLayout({ data, series, index, categoryGap, projection }); + return ( + + isBarActive={isBarActive}> + + + + + + {ticks => + ticks.map(tick => ( + + )) + } + + {barSelection ? ( + + onActiveChange={onActiveChange} + onActivate={onActivate} + formatCategory={formatXTick} + > + + {renderTooltip ? ( + + boundaryRef={boundary} + data-testid='tooltip' + > + {renderTooltip} + + ) : null} + + ) : null} + + ); +} diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx new file mode 100644 index 00000000000..7adbd3eec9e --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx @@ -0,0 +1,397 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { BarSelectionContext, type BarSelectionContextValue, hasArea, useBarChartContext } from './bar-chart-context'; +import type { StackedBarLayout } from './bar-chart-layout'; +import { + getActiveBar, + getKeyboardAnnouncement, + getKeyIntent, + hitTest, + isSelectable, + NO_SELECTION, + resolveSelection, + sameSelection, + type Selected, + selectedState, + type SelectionAction, + selectionReducer, +} from './bar-chart-selection'; +import type { ActiveBar, BarCategory, BarSection, BarSelection, ChartSize } 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 BarChartBarSelectionProps = ComponentProps<'div'> & { + /** Receives the selected category and section, or null. Read values from current data. */ + onActiveChange?: (active: BarSelection | null) => void; + /** Called on click, Enter or Space. Makes the surface a button. */ + onActivate?: (active: ActiveBar) => void; + /** Names a category in announcements. Default: the category key */ + formatCategory?: (category: string) => string | null; +}; + +/** Coalesces pointer moves into at most one selection update per frame. */ +function useFramePointerUpdates(onFrame: (selection: Selected | null) => void, layout: unknown) { + 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: Selected | null) => { + pendingRef.current = selection; + if (frameRef.current !== null) { + return; + } + frameRef.current = requestAnimationFrame(() => { + frameRef.current = null; + const pending = pendingRef.current; + pendingRef.current = undefined; + if (pending !== undefined) { + onFrame(pending); + } + }); + }; + const pendingSection = () => pendingRef.current?.section ?? undefined; + return { schedule, cancel, pendingSection }; +} + +/** Calls `onActiveChange` when the active bar changes and on unmount. */ +function usePublishActive( + active: BarSelection | null, + onActiveChange: ((active: BarSelection | null) => void) | undefined, +) { + const onActiveChangeRef = React.useRef(onActiveChange); + const publishedRef = React.useRef(null); + React.useLayoutEffect(() => { + onActiveChangeRef.current = onActiveChange; + }, [onActiveChange]); + React.useLayoutEffect(() => { + if (sameSelection(active, publishedRef.current)) { + return; + } + publishedRef.current = active; + onActiveChangeRef.current?.(active); + }); + React.useEffect( + () => () => { + if (publishedRef.current) { + onActiveChangeRef.current?.(null); + } + }, + [], + ); +} + +/** Holds the selection and drops it when its category or section disappears. */ +function useBarSelection(categories: readonly BarCategory[]) { + const [state, dispatch] = React.useReducer(selectionReducer, NO_SELECTION); + const categoryByKey = React.useMemo( + () => new Map(categories.map(category => [category.key, category])), + [categories], + ); + const stored = selectedState(state); + const storedCategory = stored ? categoryByKey.get(stored.category) : undefined; + const isValid = !!stored && !!storedCategory && isSelectable(stored, storedCategory); + return { + state, + selection: isValid ? stored : null, + selectedCategory: isValid ? storedCategory : undefined, + categoryByKey, + dispatch, + }; +} + +function KeyboardInstructions({ + id, + canActivate, + announcement, +}: Readonly<{ id: string; canActivate: boolean; announcement: string }>) { + return ( + <> + + Use Left and Right to choose a period, or Home and End to jump to the first or last. Use Up and Down to choose + positive or negative values. {canActivate ? 'Press Enter or Space to open the selected period. ' : ''} + Press Escape to dismiss. + + + {announcement} + + + ); +} + +// eslint-disable-next-line typescript/consistent-type-assertions -- The ref wrapper drops the row type parameter; `onActivate` only receives rows the chart was given. +export const BarChartBarSelection = React.forwardRef( + function BarChartBarSelection(props, ref) { + const { frame, layout, data, ariaLabel, registerInteraction, setActiveCategory } = + useBarChartContext('BarSelection'); + React.useLayoutEffect(registerInteraction, [registerInteraction]); + if (!hasArea(frame.size) || layout.categories.length === 0) { + return null; + } + return ( + + ); + }, +) as ( + props: BarChartBarSelectionProps & { ref?: React.Ref }, +) => React.ReactElement | null; + +const formatCategoryKey = (category: string) => category; + +type SurfaceProps = BarChartBarSelectionProps & { + forwardedRef: React.ForwardedRef; + data: readonly unknown[]; + layout: StackedBarLayout; + size: ChartSize; + ariaLabel: string; + setActiveCategory: (category: string | null) => void; +}; + +function BarSelectionSurface({ + forwardedRef, + data, + layout, + size, + ariaLabel, + setActiveCategory, + onActiveChange, + onActivate, + formatCategory = formatCategoryKey, + children, + render, + ...otherProps +}: SurfaceProps) { + const chartBoxRef = React.useRef(null); + const { state, selection, selectedCategory, categoryByKey, dispatch } = useBarSelection(layout.categories); + const surfaceRef = React.useRef(null); + const lastIndexRef = React.useRef(0); + const keyboardInstructionsId = React.useId(); + const [tooltipCount, setTooltipCount] = React.useState(0); + const registerTooltip = React.useCallback(() => { + setTooltipCount(count => count + 1); + return () => setTooltipCount(count => count - 1); + }, []); + const pointerUpdates = useFramePointerUpdates(next => dispatch({ type: 'pointer', selection: next }), layout); + + const selectedSection = selection?.section ?? undefined; + const selectedIndex = selectedCategory?.datumIndex; + React.useLayoutEffect(() => { + if (selectedIndex !== undefined) { + lastIndexRef.current = selectedIndex; + } + }, [selectedIndex]); + const keyboardIndex = () => selectedIndex ?? lastIndexRef.current; + const keyboardAnnouncement = getKeyboardAnnouncement(selection, selectedCategory, formatCategory); + + // A tap fires no pointerleave or blur, so a tap anywhere else dismisses. + const hasPointerSelection = selection?.source === 'pointer'; + React.useEffect(() => { + if (!hasPointerSelection) { + return; + } + const dismissOutside = (event: PointerEvent) => { + if (!(event.target instanceof Node) || !surfaceRef.current?.contains(event.target)) { + dispatch({ type: 'clear' }); + } + }; + document.addEventListener('pointerdown', dismissOutside, true); + return () => document.removeEventListener('pointerdown', dismissOutside, true); + }, [dispatch, hasPointerSelection]); + + const active = resolveSelection(selection, selectedCategory); + usePublishActive(active, onActiveChange); + const activeCategory = active?.category ?? null; + React.useLayoutEffect(() => { + setActiveCategory(activeCategory); + return () => setActiveCategory(null); + }, [activeCategory, setActiveCategory]); + + const pointerSelection = (clientX: number, clientY: number) => { + const bounds = chartBoxRef.current?.getBoundingClientRect(); + const local = + bounds && bounds.width > 0 && bounds.height > 0 + ? { + x: ((clientX - bounds.left) / bounds.width) * size.width, + y: ((clientY - bounds.top) / bounds.height) * size.height, + } + : { x: 0, y: layout.zeroY }; + return hitTest(layout, local, pointerUpdates.pendingSection() ?? selectedSection); + }; + + const resolveNext = (next: Selected | null) => + resolveSelection(next, next ? categoryByKey.get(next.category) : undefined); + + const dispatchSelection = (action: SelectionAction) => { + if (action.type !== 'pointer') { + pointerUpdates.cancel(); + } + dispatch(action); + return resolveNext(selectedState(selectionReducer(state, action))); + }; + + const selectKeyboardIndex = (index: number, section?: BarSection) => + dispatchSelection({ + type: 'keyboard', + category: layout.categories[Math.max(0, Math.min(layout.categories.length - 1, index))], + section, + }); + + const activate = (bar: BarSelection | null) => { + const activated = getActiveBar(bar, data, categoryByKey); + if (activated) { + onActivate?.(activated); + } + }; + + const activateKeyboardSelection = (section: BarSection | undefined) => { + const dismissed = state.status === 'dismissed'; + const bar = selectKeyboardIndex(keyboardIndex(), section); + if (!dismissed) { + activate(bar); + } + }; + + const interactive = !!(onActiveChange || onActivate || tooltipCount > 0); + const selectionContext: BarSelectionContextValue = { + activeBar: getActiveBar(active, data, categoryByKey), + selectedCategory: selection?.section ? selectedCategory : undefined, + plot: layout.plot, + chartWidth: size.width, + chartBoxRef, + registerTooltip, + }; + + const eventHandlers: 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(); + dispatchSelection({ type: 'pointer', selection: pointerSelection(event.clientX, event.clientY) }); + }, + onPointerLeave: event => { + if (event.pointerType !== 'touch') { + dispatchSelection({ type: 'clear' }); + } + }, + onPointerCancel: () => { + dispatchSelection({ type: 'clear' }); + }, + onPointerMove: event => { + pointerUpdates.schedule(pointerSelection(event.clientX, event.clientY)); + }, + onFocus: () => { + selectKeyboardIndex(keyboardIndex()); + }, + onBlur: () => { + dispatchSelection({ 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(selectedSection); + return; + } + activate(resolveNext(pointerSelection(event.clientX, event.clientY))); + }, + onKeyDown: event => { + const intent = getKeyIntent( + event.key, + keyboardIndex(), + layout.categories.length - 1, + selectedSection, + !!onActivate, + ); + if (!intent) { + return; + } + event.preventDefault(); + if (intent.type === 'dismiss') { + dispatchSelection({ type: 'dismiss' }); + } else if (intent.activate) { + activateKeyboardSelection(intent.section); + } else { + selectKeyboardIndex(intent.index, intent.section); + } + }, + }; + + 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/bar-chart/bar-chart-bar.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-bar.tsx new file mode 100644 index 00000000000..26078589605 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-bar.tsx @@ -0,0 +1,30 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { useStackedBarsContext } from './bar-chart-context'; + +export type BarChartBarProps = ComponentProps<'g'>; + +/** + * Styles the bars that `BarChart.StackedBars` 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 BarChartBar = React.forwardRef(function BarChartBar(props, ref) { + const { render, ...otherProps } = props; + const { setBar } = useStackedBarsContext('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/bar-chart/bar-chart-context.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-context.ts new file mode 100644 index 00000000000..b9a3f5f118b --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-context.ts @@ -0,0 +1,78 @@ +import { createContext, type RefObject, useContext } from 'react'; + +import type { BarStyleElement } from './bar-chart-canvas'; +import type { PaintedProjection, StackedBarLayout } from './bar-chart-layout'; +import type { ActiveBar, BarCategory, ChartFrame, ChartPlot, ChartSize } from './types'; + +export interface BarChartContextValue { + frame: ChartFrame; + layout: StackedBarLayout; + data: readonly unknown[]; + ariaLabel: string; + /** Marks the chart interactive while the returned cleanup has not run. */ + registerInteraction: () => () => void; + setActiveCategory: (category: string | null) => void; +} + +export const BarChartContext = createContext(null); + +/** Separate from `BarChartContext` so a selection change re-renders only the parts that show it. */ +export const BarChartActiveCategoryContext = createContext(null); + +export function useBarChartContext(part: string) { + const context = useContext(BarChartContext); + if (!context) { + throw new Error(` must be used within `); + } + return { + ...context, + // SAFETY: `BarChart.Root` holds the rows and layout of one `useStackedBarLayout` call, and + // a part's `TDatum` is the type of the chart it renders in. Context cannot carry the parameter. + // eslint-disable-next-line typescript/consistent-type-assertions -- React context is not generic per consumer. + layout: context.layout as StackedBarLayout, + // eslint-disable-next-line typescript/consistent-type-assertions -- React context is not generic per consumer. + data: context.data as readonly TDatum[], + }; +} + +export function hasArea(size: ChartSize) { + return size.width > 0 && size.height > 0; +} + +export interface StackedBarsContextValue { + /** Registers the `BarChart.Bar` element whose computed `color` paints bars. */ + setBar: (element: BarStyleElement | null) => void; + projection: PaintedProjection | null; +} + +export const StackedBarsContext = createContext(null); + +export function useStackedBarsContext(part: string) { + const context = useContext(StackedBarsContext); + if (!context) { + throw new Error(` must be used within `); + } + return context; +} + +export interface BarSelectionContextValue { + activeBar: ActiveBar | null; + /** The selected category while a section is selected. */ + selectedCategory: BarCategory | undefined; + plot: ChartPlot; + chartWidth: number; + /** 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 BarSelectionContext = createContext(null); + +export function useBarSelectionContext(part: string) { + const context = useContext(BarSelectionContext); + if (!context) { + throw new Error(` must be used within `); + } + return context; +} diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-cursor.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-cursor.tsx new file mode 100644 index 00000000000..b27565e3b25 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-cursor.tsx @@ -0,0 +1,37 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { useBarSelectionContext } from './bar-chart-context'; + +export type BarChartCursorProps = ComponentProps<'div'>; + +export const BarChartCursor = React.forwardRef( + function BarChartCursor(props, ref) { + const { render, ...otherProps } = props; + const { selectedCategory, plot } = useBarSelectionContext('Cursor'); + + const ownProps = { + 'aria-hidden': 'true', + style: selectedCategory + ? { + position: 'absolute', + top: 0, + bottom: 0, + left: selectedCategory.bandX - plot.x, + width: selectedCategory.bandWidth, + 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/bar-chart/bar-chart-grid-line.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-grid-line.tsx new file mode 100644 index 00000000000..da3a860ad43 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-grid-line.tsx @@ -0,0 +1,34 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { useBarChartContext } from './bar-chart-context'; +import type { ChartTick } from './types'; + +export type BarChartGridLineProps = ComponentProps<'line'> & { + /** An entry from the `BarChart.Grid` children function. */ + line: ChartTick; +}; + +export const BarChartGridLine = React.forwardRef( + function BarChartGridLine(props, ref) { + const { line, render, ...otherProps } = props; + const { layout } = useBarChartContext('GridLine'); + + const ownProps = { + x1: layout.plot.x, + x2: layout.plot.x + layout.plot.width, + y1: line.y, + y2: line.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/bar-chart/bar-chart-grid.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-grid.tsx new file mode 100644 index 00000000000..925d6668bff --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-grid.tsx @@ -0,0 +1,33 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { hasArea, useBarChartContext } from './bar-chart-context'; +import type { ChartTick } from './types'; + +export type BarChartGridProps = Omit, 'children'> & { + /** Renders the lines, usually one `BarChart.GridLine` per entry. */ + children?: (lines: readonly ChartTick[]) => React.ReactNode; +}; + +export const BarChartGrid = React.forwardRef(function BarChartGrid(props, ref) { + const { children, render, ...otherProps } = props; + const { frame, layout } = useBarChartContext('Grid'); + + const ownProps = { + width: frame.size.width, + height: frame.size.height, + 'aria-hidden': 'true', + style: { position: 'absolute', inset: 0, display: 'block', pointerEvents: 'none' }, + children: children?.(layout.yTicks), + } satisfies DefaultProps<'svg'>; + + return useRender({ + defaultTagName: 'svg', + render, + ref, + enabled: hasArea(frame.size), + props: mergeProps<'svg'>(ownProps, otherProps), + }); +}); diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-projection-outline.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-projection-outline.tsx new file mode 100644 index 00000000000..39e832520fa --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-projection-outline.tsx @@ -0,0 +1,34 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { useStackedBarsContext } from './bar-chart-context'; + +export type BarChartProjectionOutlineProps = ComponentProps<'rect'>; + +export const BarChartProjectionOutline = React.forwardRef( + function BarChartProjectionOutline(props, ref) { + const { render, ...otherProps } = props; + const { projection } = useStackedBarsContext('ProjectionOutline'); + + const ownProps = projection + ? ({ + x: projection.x - 1, + y: projection.y - 1, + width: projection.width + 2, + height: projection.height + 1, + rx: projection.radius, + pointerEvents: 'none', + } satisfies DefaultProps<'rect'>) + : {}; + + return useRender({ + defaultTagName: 'rect', + render, + ref, + enabled: !!projection, + props: mergeProps<'rect'>(ownProps, otherProps), + }); + }, +); diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-root.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-root.tsx new file mode 100644 index 00000000000..5594992a14c --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-root.tsx @@ -0,0 +1,79 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { BarChartActiveCategoryContext, BarChartContext, type BarChartContextValue } from './bar-chart-context'; +import { DEFAULT_CHART_MARGIN } from './bar-chart-layout'; +import type { ChartMargin } from './types'; +import { useChartSize } from './use-chart-size'; +import type { StackedBarLayoutSource } from './use-stacked-bar-layout'; + +export type BarChartRootProps = Omit, 'aria-label'> & { + /** A stable layout source from `BarChart.useStackedBarLayout`. */ + layout: StackedBarLayoutSource; + /** Default: 500 */ + height?: number | string; + margin?: Partial; + /** Labels the bars image and the interaction surface. */ + 'aria-label': string; +}; + +type InteractionMode = 'pending' | 'interactive' | 'visual-only'; + +export const BarChartRoot = React.forwardRef(function BarChartRoot(props, ref) { + const { layout, height = 500, margin, 'aria-label': ariaLabel, render, children, ...otherProps } = props; + const { ref: sizeRef, size } = useChartSize(); + 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 frame = React.useMemo(() => ({ size, margin: { top, right, bottom, left } }), [bottom, left, right, size, top]); + const projected = React.useMemo(() => layout.project(frame), [frame, layout]); + + const [interactionLayers, setInteractionLayers] = React.useState(0); + const registerInteraction = React.useCallback(() => { + setInteractionLayers(count => count + 1); + return () => setInteractionLayers(count => count - 1); + }, []); + const [activeCategory, setActiveCategory] = React.useState(null); + + const context = React.useMemo( + () => ({ + frame, + layout: projected, + data: layout.data, + ariaLabel, + registerInteraction, + setActiveCategory, + }), + [ariaLabel, frame, layout.data, projected, registerInteraction], + ); + + const interactionMode: InteractionMode = + size.width <= 0 + ? 'pending' + : interactionLayers > 0 && projected.categories.length > 0 + ? 'interactive' + : 'visual-only'; + + const ownProps = { + style: { position: 'relative', minWidth: 0, overflow: 'hidden', height }, + children: ( + {children} + ), + } satisfies DefaultProps<'div'>; + + const element = useRender({ + defaultTagName: 'div', + render, + ref: [sizeRef, 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/bar-chart/bar-chart-stacked-bars.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx new file mode 100644 index 00000000000..31fcc0d4e99 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx @@ -0,0 +1,146 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { + type BarStyleElement, + CanvasRenderError, + getBarGeometrySnapshot, + paintStackedBarCanvas, + parseBarGeometry, +} from './bar-chart-canvas'; +import { hasArea, StackedBarsContext, useBarChartContext } from './bar-chart-context'; +import { fitProjectionToBar, projectStackedBarMarks } from './bar-chart-layout'; +import type { BarIdentity } from './types'; + +export type BarChartStackedBarsProps = ComponentProps<'div'> & { + /** Returns false for a bar that `BarChart.Bar` styles through `data-inactive`. Default: every bar is active */ + isBarActive?: (bar: BarIdentity) => boolean; +}; + +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); +} + +function getRootThemeAttributes() { + const root = document.documentElement; + return JSON.stringify([root.getAttribute('class'), root.getAttribute('style'), root.getAttribute('data-theme')]); +} + +function subscribeToRootTheme(onChange: () => void) { + const observer = new MutationObserver(onChange); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style', 'data-theme'] }); + return () => observer.disconnect(); +} + +const getServerSnapshot = () => ''; +const getServerPixelRatio = () => 1; + +// eslint-disable-next-line typescript/consistent-type-assertions -- The ref wrapper drops the row type parameter; `isBarActive` only receives rows the chart was given. +export const BarChartStackedBars = React.forwardRef( + function BarChartStackedBars(props, ref) { + const { isBarActive, children, render, ...otherProps } = props; + const { frame, layout, ariaLabel } = useBarChartContext('StackedBars'); + const { size } = frame; + const rootThemeAttributes = React.useSyncExternalStore( + subscribeToRootTheme, + getRootThemeAttributes, + getServerSnapshot, + ); + 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 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(layout, geometry), [geometry, layout]); + const projection = React.useMemo( + () => fitProjectionToBar(layout.projection, geometry), + [geometry, layout.projection], + ); + const stackedBarsContext = React.useMemo(() => ({ setBar, projection }), [projection]); + + React.useLayoutEffect(() => { + if (!canvas || !hasArea(size)) { + return; + } + paintStackedBarCanvas({ canvas, marks, projection, size, pixelRatio, isBarActive, bar }); + const onContextLost = () => { + setCanvasError(new CanvasRenderError('Canvas 2D context was lost', null)); + }; + canvas.addEventListener('contextlost', onContextLost); + return () => canvas.removeEventListener('contextlost', onContextLost); + // `barClass` and `rootThemeAttributes` are not read here: they change the computed colors the paint reads from the DOM. + }, [bar, barClass, canvas, isBarActive, marks, pixelRatio, projection, rootThemeAttributes, 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; + }, +) as ( + props: BarChartStackedBarsProps & { ref?: React.Ref }, +) => React.ReactElement | null; diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx new file mode 100644 index 00000000000..17352d882b9 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx @@ -0,0 +1,130 @@ +'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 { useBarSelectionContext } from './bar-chart-context'; +import type { ActiveBar } from './types'; + +const EDGE = 8; +const SIDE_OFFSET = 16; +const PINNED_BELOW_PLOT_WIDTH = 416; + +export type BarChartTooltipProps = Omit, 'children'> & { + /** Content for the selected bar. Return null to hide the tooltip. */ + children: (active: ActiveBar) => React.ReactNode; + /** Element the tooltip stays inside. Default: the chart */ + boundaryRef?: React.RefObject; +}; + +type Side = 'left' | 'right'; + +function tooltipMiddleware(getBoundary: () => Element | undefined, pinned: boolean) { + return [ + offset(pinned ? 0 : SIDE_OFFSET), + flip(() => ({ boundary: getBoundary(), padding: EDGE, crossAxis: false })), + shift(() => ({ boundary: getBoundary(), padding: EDGE, crossAxis: true })), + size(() => ({ + boundary: getBoundary(), + padding: EDGE, + apply({ elements }) { + const boundary = getBoundary()?.getBoundingClientRect(); + const viewportWidth = getWindow(elements.floating).document.documentElement.clientWidth; + const left = Math.max(EDGE, (boundary?.left ?? 0) + EDGE); + const right = Math.min(viewportWidth - EDGE, (boundary?.right ?? viewportWidth) - EDGE); + elements.floating.style.maxWidth = `${Math.max(0, right - left)}px`; + }, + })), + ]; +} + +// eslint-disable-next-line typescript/consistent-type-assertions -- The ref wrapper drops the row type parameter; `children` only receives rows the chart was given. +export const BarChartTooltip = React.forwardRef( + function BarChartTooltip(props, ref) { + const { children, boundaryRef, render, ...otherProps } = props; + const { activeBar, selectedCategory, registerTooltip, plot, chartWidth, chartBoxRef } = + useBarSelectionContext('Tooltip'); + React.useLayoutEffect(registerTooltip, [registerTooltip]); + + const content = activeBar && selectedCategory ? children(activeBar) : null; + const open = content !== null && content !== undefined; + const anchorX = selectedCategory?.center; + + const pinned = plot.width < PINNED_BELOW_PLOT_WIDTH; + const popupRef = React.useRef(null); + const getBoundary = React.useCallback( + () => boundaryRef?.current ?? chartBoxRef.current ?? undefined, + [boundaryRef, chartBoxRef], + ); + // eslint-disable-next-line react/refs -- The middleware reads the boundary refs when floating-ui computes a position, not during render. + const middleware = React.useMemo(() => tooltipMiddleware(getBoundary, pinned), [getBoundary, pinned]); + + const [lastSide, setLastSide] = React.useState('right'); + 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 bar twice near an edge. + if (!pinned && (resolvedSide === 'left' || resolvedSide === 'right') && resolvedSide !== lastSide) { + setLastSide(resolvedSide); + } + + React.useLayoutEffect(() => { + const chart = chartBoxRef.current; + if (anchorX === undefined || !chart || chartWidth <= 0) { + return; + } + const getBoundingClientRect = () => { + const chartRect = chart.getBoundingClientRect(); + if (pinned) { + const boundary = getBoundary()?.getBoundingClientRect() ?? chartRect; + return new DOMRect(boundary.left + EDGE, boundary.top + EDGE, 0, 0); + } + const x = Math.round((chartRect.left + (anchorX / chartWidth) * chartRect.width) * 2) / 2; + return new DOMRect(x, chartRect.top + plot.y, 0, 0); + }; + refs.setReference({ getBoundingClientRect, contextElement: chart }); + }, [anchorX, chartBoxRef, chartWidth, getBoundary, pinned, plot, 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: BarChartTooltipProps & { ref?: React.Ref }, +) => React.ReactElement | null; diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-x-axis.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-x-axis.tsx new file mode 100644 index 00000000000..d7d4968808e --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-x-axis.tsx @@ -0,0 +1,53 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { hasArea, useBarChartContext } from './bar-chart-context'; +import { selectXTicks, type XTick } from './x-ticks'; + +export type BarChartXAxisProps = 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?: 'category' | 'calendar'; + /** 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 `BarChart.XTick` per entry. */ + children?: (ticks: readonly XTick[]) => React.ReactNode; +}; + +const formatCategory = (value: string) => value; + +export const BarChartXAxis = React.forwardRef(function BarChartXAxis(props, ref) { + const { ticks = 'category', format = formatCategory, children, render, ...otherProps } = props; + const { frame, layout } = useBarChartContext('XAxis'); + const xTicks = React.useMemo( + () => + selectXTicks({ + categories: layout.categories, + plot: layout.plot, + viewportWidth: frame.size.width, + xAxis: ticks === 'calendar' ? 'calendar' : undefined, + formatXTick: format, + }), + [format, frame.size.width, layout.categories, layout.plot, ticks], + ); + + const ownProps = { + width: frame.size.width, + height: frame.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(frame.size), + props: mergeProps<'svg'>(ownProps, otherProps), + }); +}); diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-x-tick.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-x-tick.tsx new file mode 100644 index 00000000000..4aec0800c59 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-x-tick.tsx @@ -0,0 +1,36 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { BarChartActiveCategoryContext, useBarChartContext } from './bar-chart-context'; +import type { XTick } from './x-ticks'; + +export type BarChartXTickProps = ComponentProps<'text'> & { + /** An entry from the `BarChart.XAxis` children function. */ + tick: XTick; +}; + +export const BarChartXTick = React.forwardRef(function BarChartXTick(props, ref) { + const { tick, render, ...otherProps } = props; + const { layout } = useBarChartContext('XTick'); + const activeCategory = React.useContext(BarChartActiveCategoryContext); + + const ownProps = { + x: tick.x, + y: layout.plot.y + layout.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/bar-chart/bar-chart-y-axis.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-y-axis.tsx new file mode 100644 index 00000000000..11ce57b21a2 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-y-axis.tsx @@ -0,0 +1,46 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { hasArea, useBarChartContext } from './bar-chart-context'; + +export interface BarChartYTickItem { + value: number; + y: number; + label: React.ReactNode; +} + +export type BarChartYAxisProps = Omit, 'children' | 'format'> & { + /** Formats a tick value. Default: the locale number */ + format?: (value: number) => React.ReactNode; + /** Renders the labels, usually one `BarChart.YTick` per entry. */ + children?: (ticks: readonly BarChartYTickItem[]) => React.ReactNode; +}; + +const formatNumber = (value: number) => value.toLocaleString(); + +export const BarChartYAxis = React.forwardRef(function BarChartYAxis(props, ref) { + const { format = formatNumber, children, render, ...otherProps } = props; + const { frame, layout } = useBarChartContext('YAxis'); + const ticks = React.useMemo( + () => layout.yTicks.map(tick => ({ value: tick.value, y: tick.y, label: format(tick.value) })), + [format, layout.yTicks], + ); + + const ownProps = { + width: frame.size.width, + height: frame.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(frame.size), + props: mergeProps<'svg'>(ownProps, otherProps), + }); +}); diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-y-tick.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-y-tick.tsx new file mode 100644 index 00000000000..06d5909abf2 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-y-tick.tsx @@ -0,0 +1,32 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { useBarChartContext } from './bar-chart-context'; +import type { BarChartYTickItem } from './bar-chart-y-axis'; + +export type BarChartYTickProps = ComponentProps<'text'> & { + /** An entry from the `BarChart.YAxis` children function. */ + tick: BarChartYTickItem; +}; + +export const BarChartYTick = React.forwardRef(function BarChartYTick(props, ref) { + const { tick, render, ...otherProps } = props; + const { frame } = useBarChartContext('YTick'); + + const ownProps = { + x: frame.margin.left - 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/bar-chart/bar-chart-zero-line.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-zero-line.tsx new file mode 100644 index 00000000000..6307f77f002 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-zero-line.tsx @@ -0,0 +1,30 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; +import { useBarChartContext } from './bar-chart-context'; + +export type BarChartZeroLineProps = ComponentProps<'line'>; + +export const BarChartZeroLine = React.forwardRef( + function BarChartZeroLine(props, ref) { + const { render, ...otherProps } = props; + const { layout } = useBarChartContext('ZeroLine'); + + const ownProps = { + x1: layout.plot.x, + x2: layout.plot.x + layout.plot.width, + y1: layout.zeroY, + y2: layout.zeroY, + 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/bar-chart/index.ts b/packages/mosaic/src/primitives/bar-chart/index.ts new file mode 100644 index 00000000000..8a225b7e93f --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/index.ts @@ -0,0 +1,37 @@ +export * as BarChart from './parts'; + +export type { + BarChartBarProps, + BarChartBarSelectionProps, + BarChartCursorProps, + BarChartGridLineProps, + BarChartGridProps, + BarChartProjectionOutlineProps, + BarChartRootProps, + BarChartStackedBarsProps, + BarChartTooltipProps, + BarChartXAxisProps, + BarChartXTickProps, + BarChartYAxisProps, + BarChartYTickItem, + BarChartYTickProps, + BarChartZeroLineProps, + StackedBarLayoutOptions, + StackedBarLayoutSource, +} from './parts'; +export type { StackedBarLayout } from './bar-chart-layout'; +export type { + ActiveBar, + BarCategory, + BarIdentity, + BarProjection, + BarSection, + BarSelection, + BarSeries, + ChartFrame, + ChartMargin, + ChartPlot, + ChartSize, + ChartTick, +} from './types'; +export type { XTick } from './x-ticks'; diff --git a/packages/mosaic/src/primitives/bar-chart/parts.ts b/packages/mosaic/src/primitives/bar-chart/parts.ts new file mode 100644 index 00000000000..001a0ceee7e --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/parts.ts @@ -0,0 +1,23 @@ +export { type BarChartRootProps, BarChartRoot as Root } from './bar-chart-root'; +export { type BarChartGridProps, BarChartGrid as Grid } from './bar-chart-grid'; +export { type BarChartGridLineProps, BarChartGridLine as GridLine } from './bar-chart-grid-line'; +export { type BarChartYAxisProps, type BarChartYTickItem, BarChartYAxis as YAxis } from './bar-chart-y-axis'; +export { type BarChartYTickProps, BarChartYTick as YTick } from './bar-chart-y-tick'; +export { type BarChartXAxisProps, BarChartXAxis as XAxis } from './bar-chart-x-axis'; +export { type BarChartXTickProps, BarChartXTick as XTick } from './bar-chart-x-tick'; +export { type BarChartStackedBarsProps, BarChartStackedBars as StackedBars } from './bar-chart-stacked-bars'; +export { type BarChartBarProps, BarChartBar as Bar } from './bar-chart-bar'; +export { + type BarChartProjectionOutlineProps, + BarChartProjectionOutline as ProjectionOutline, +} from './bar-chart-projection-outline'; +export { type BarChartZeroLineProps, BarChartZeroLine as ZeroLine } from './bar-chart-zero-line'; +export { type BarChartBarSelectionProps, BarChartBarSelection as BarSelection } from './bar-chart-bar-selection'; +export { type BarChartCursorProps, BarChartCursor as Cursor } from './bar-chart-cursor'; +export { type BarChartTooltipProps, BarChartTooltip as Tooltip } from './bar-chart-tooltip'; +export { CanvasRenderError } from './bar-chart-canvas'; +export { + type StackedBarLayoutOptions, + type StackedBarLayoutSource, + useStackedBarLayout, +} from './use-stacked-bar-layout'; diff --git a/packages/mosaic/src/primitives/bar-chart/use-chart-size.ts b/packages/mosaic/src/primitives/bar-chart/use-chart-size.ts new file mode 100644 index 00000000000..33455aa92ef --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/use-chart-size.ts @@ -0,0 +1,49 @@ +'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; + observerRef.current = new ResizeObserver(entries => { + const entry = entries[entries.length - 1]; + const box = entry?.borderBoxSize?.[0]; + const width = toHalfPixel(box?.inlineSize ?? entry?.contentRect.width ?? 0); + const height = toHalfPixel(box?.blockSize ?? entry?.contentRect.height ?? 0); + if (lastSize?.width === width && lastSize.height === height) { + return; + } + const next = { width, height }; + lastSize = 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' }); + }, + [disconnect], + ); + + useLayoutEffect(() => disconnect, [disconnect]); + + return { ref, size } as const; +} diff --git a/packages/mosaic/src/primitives/bar-chart/use-stacked-bar-layout.ts b/packages/mosaic/src/primitives/bar-chart/use-stacked-bar-layout.ts new file mode 100644 index 00000000000..b4d59e82cab --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/use-stacked-bar-layout.ts @@ -0,0 +1,44 @@ +'use client'; + +import { useMemo } from 'react'; + +import { prepareStackedBars, projectStackedBars, type StackedBarLayout } from './bar-chart-layout'; +import type { BarProjection, BarSeries, ChartFrame } from './types'; + +export interface StackedBarLayoutOptions { + data: readonly TDatum[]; + series: readonly BarSeries[]; + /** Returns a unique, stable category key. */ + 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; +} + +/** Prepared rows and a function that projects them into a measured frame. */ +export interface StackedBarLayoutSource { + data: readonly TDatum[]; + project: (frame: ChartFrame) => StackedBarLayout; +} + +/** + * Prepares stacked bar data for `BarChart.Root`. Preparation reruns when `data`, `series` or `index` + * change, so memoize `series` and `index`. + */ +export function useStackedBarLayout({ + data, + series, + index, + categoryGap = 0.28, + projection, +}: StackedBarLayoutOptions): StackedBarLayoutSource { + const prepared = useMemo(() => prepareStackedBars({ data, series, index }), [data, index, series]); + return useMemo( + () => ({ + data, + project: (frame: ChartFrame) => projectStackedBars(prepared, { ...frame, categoryGap, projection }), + }), + [categoryGap, data, prepared, projection], + ); +} From a8f5c29a25228ca7f24fa94031c2ac180654ac0e Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Sun, 22 Nov 2026 19:29:42 -0700 Subject: [PATCH 04/40] test(mosaic): cover bar chart painting, resizing, pointer selection and tooltip placement in Chromium --- .../__tests__/bar-chart.browser.test.tsx | 264 ++++++++++++++++++ .../bar-chart/__tests__/test-chart.tsx | 5 +- 2 files changed, 268 insertions(+), 1 deletion(-) create mode 100644 packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx new file mode 100644 index 00000000000..515dfc53d50 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx @@ -0,0 +1,264 @@ +import { cleanup, render as renderComponent, screen } from '@testing-library/react'; +import type { ReactElement } from 'react'; +import { useRef } from 'react'; +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { page, userEvent } from 'vitest/browser'; + +import type { BarSelection } from '../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); } + `; + 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 BarChart.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 BarChart.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('paints nothing without BarChart.Bar', async () => { + await render(); + const { x, y } = insideLastBar(); + + await expect.poll(() => surface()).toBeTruthy(); + expect(pixelAt(x, y)).toBe('rgba(0, 0, 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)'); + }); +}); + +describe('choosing a period with a pointer', () => { + it('selects the period under a mouse and clears it when the mouse leaves', async () => { + const onActiveChange = vi.fn<(active: 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(() => onActiveChange.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(() => onActiveChange.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 onActiveChange = vi.fn<(active: BarSelection | null) => void>(); + await render(); + const { x, y } = centerOfCategory(1); + + pointer('pointerdown', surface(), x, y, 'touch'); + surface().dispatchEvent( + new PointerEvent('pointerout', { bubbles: true, pointerType: 'touch', relatedTarget: document.body }), + ); + await expect.poll(() => onActiveChange.mock.lastCall?.[0]).toMatchObject({ category: 'Feb' }); + + pointer('pointerdown', document.body, 0, 0, 'touch'); + await expect.poll(() => onActiveChange.mock.lastCall?.[0]).toBeNull(); + }); +}); + +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('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(); + }); +}); diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/test-chart.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/test-chart.tsx index cccbb656895..7fd986f7aa9 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/test-chart.tsx +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/test-chart.tsx @@ -17,6 +17,8 @@ export type TestChartProps = StackedBarLayoutOptions & renderTooltip?: (active: ActiveBar) => ReactNode; boundary?: React.RefObject; height?: number | string; + /** Mounts `BarChart.Bar`. Default: true */ + bar?: boolean; barClassName?: string; isBarActive?: BarChartStackedBarsProps['isBarActive']; }; @@ -36,6 +38,7 @@ export function TestChart({ renderTooltip, boundary, height, + bar = true, barClassName, isBarActive, }: TestChartProps) { @@ -47,7 +50,7 @@ export function TestChart({ aria-label={ariaLabel} > isBarActive={isBarActive}> - + {bar ? : null}
From 352a35d1a600b82838958b836b1cdd05ef13cc36 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Sun, 22 Nov 2026 19:34:43 -0700 Subject: [PATCH 05/40] test(mosaic): add bar chart screenshot tests --- ...-chart-dimmed-selection-chromium-linux.png | Bin 0 -> 8252 bytes .../bar-chart-diverging-chromium-linux.png | Bin 0 -> 8506 bytes .../bar-chart-projection-chromium-linux.png | Bin 0 -> 7889 bytes .../bar-chart-tooltip-open-chromium-linux.png | Bin 0 -> 13642 bytes .../__tests__/bar-chart.visual.test.tsx | 169 ++++++++++++++++++ 5 files changed, 169 insertions(+) create mode 100644 packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-dimmed-selection-chromium-linux.png create mode 100644 packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-diverging-chromium-linux.png create mode 100644 packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-projection-chromium-linux.png create mode 100644 packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-tooltip-open-chromium-linux.png create mode 100644 packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-dimmed-selection-chromium-linux.png b/packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-dimmed-selection-chromium-linux.png new file mode 100644 index 0000000000000000000000000000000000000000..0a8bca3c2ad2b19dd19f5b4c9f994df77e9b723c GIT binary patch literal 8252 zcmcgxcQ{<%y533<1c``VLP&_j=-o)vAV?%ih~9gTZX^UD{D>&Q2oj=qGJ5ZfMAV7i z8NH4&bGPLD?m54E&vVOj&vW-bGkZU4)?TyL_r34?yo&KM8_luL*{G;v2jX-;bKNw2eLeJN zPm`-=wwArnNaLp}{?@A%F_qtbx~SmW6=bTn8#-(z3b>nk@Okq(yH>9|nw_9rsxsmKB}($()=y z8bIi-0svcSKDa)4COmQgM&x38t-7Y>#rpUV3RUAYCF3nfMe<{4NLW-(zs-GV>5;_g#7Da%GxEiNUM zl9(vgcChmGl*z*O{93gxwCWZ}CRTm^{5cH`O}f*)goFg0r%$^o4E0#0eab(7Zd-7D zSi%gz5-sMv8@;`~D=I41*VhXQ3ikK+F&K=N6EVPM*|#b+eLF5be)z|aPP~$QRTULd zGP3MR3P85^!}?Vr03abq$RGq{3GnH_5FjxI03pbZsxAQZwhvfu9o?*to(P(G)KZ@o zcf|>DUHtA+^_L#W`rr$);Tlp+g0C_i8xo}>6#Tku>iE03AlY5LXW4=raG2(G!LfsA zRW$nt2tJW<@xgW6ff+&I>dr;EJ8-MB2As6Fzv9bACXdp(~vlF8LjD=ngR9Hx;yrKeOP*`7I zzq-1*x3`y)!h|O%24z~_C8`bj2zfbS`=COq$vTrFZY%b+os?0n1Fg$%aL=Osw&9`S4ZUYI;`A+oVoP5a#f@ zjx6ibr_PI3;uqF;F+@Z}0Vk-b!e#Y*Lk?_1_FmYL7`9!Y`TtzUQ(Vl6P9Hm8}V^*^PV-?2#tm* zje@)lI&9I~*JSG{o^Vu!ZTarcyjS-)S&uuqK7Y4kk-K5EtJqJ_Ej*o(k&$5NV{^DM z(UZV8RppfSbJ<;@&T#Vx>g(kt#?SBaK~lwZ&0tS;N#y!7;c@ScAvrm@ z`=9&!`+v`NEmOv&Q+Rr3XNQ28q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kMC-a&tdWzo6!Yyu>IHIpXT*T}s@oF$<<1A0N`Rr1oewqTzU`DB!4tmDGR>Es|y* zx+902X$fWZMf01uDpshOnr5JvT<`6H`H0(Up|qImlqP$Z>_2CKm56Z)DNU>2?U#&} z+6k-WzDc>De2kjHRzlM4Dtl>|%|AFG6yZi|SH5eT*iZ=9=P^mv8pbVRe`?nR7Wy%pR$>&utr#bl>zTvorz=Rn!Syi?A8wLR_)`4#2A|3OCpW{cb0t zXZTg0OEOOCKNP%hhf$%wHci}(3v^TGw&^DcrhL{4-rdxAE%K~`#P89lgG@Sz5uh0% zKEv0G{1P9NYEVzIP`&6Bu$v5aHni)7f4UDoY@W9q6Vs_xk8SU~=e(T7dm7LH$I@awES654j--_|~ z#9_~NvLFS2&rY6k@Z}Yef#s0_pm`=B5X~&fwH6y2+m|fbvw#{%Gf&oj@3Wb}JOhYw%T5ovYIVFs#ubtLZEH+S2}(apC)O>zbCC#MwudCQo`&Wc+=QaOu*# z9!m`Nu)#=EldYEz-JZ1N!475D(b1`@sJLTTdvt(u;=6m7Wh!|^ZCGFs%~s~;h1UGh z|N2l{@B-M#bR#m8`QPK;ug1+Q9B3Wla1OjXlmGw_ofrHBz}J_k@2?3R#=s}Q0|j;Y J!u!TA{|)hvT3rAD literal 0 HcmV?d00001 diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-diverging-chromium-linux.png b/packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-diverging-chromium-linux.png new file mode 100644 index 0000000000000000000000000000000000000000..a50f90a181d6776ee2f1ec8862b0eafce3df7655 GIT binary patch literal 8506 zcmch7byQSsyZ5F+NtS_VXVM7j~_md>GJ z7~*X4Jn#FSbDp)nZ@ue$-~RKSz4q*V@9X;2wcn^eRUo}`;|c%(q>4`-YXSf^3;?iX z2(iJH>{3Hx0JsV$K7Od}owhL*q;0fVkJ^D+LE1@hUn^0*P2y~8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b8>PA85`{KC-*eL5V3zr|wGu>=I4PJysf~ zV^<$)TBoc&^lDB7o7U>?uBo(y^n?xpk z@PJ)R$@tf5`uf83+!rL+3}%zqx82z67X@P0EOJ8*D*>-7wy!kXKgM5M z()$Axjf3s#Xi2FbzzhIEVJ2;f7M9p^x!9c$%hKif0|xB6O;dZ#m$TNE=J2G*Z8hH2 zReSfJ@d0Dj7mS52XrWpGjkDQ{Z&sUtssiA_Z;gD#cu`#{dU^`~8p?Zrs;P+yPA)D* z-~*0_`y0l7+T>)%u!1zK!+#G@AZxB6&-wsA{~xPw;3Fmo^!O;->dOIihWwP~5J1-1 WH$JRLJFdV#AQ=fo@sjt3LH`4I!@ko1 literal 0 HcmV?d00001 diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx new file mode 100644 index 00000000000..6f4338e1760 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx @@ -0,0 +1,169 @@ +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 { BarChart, type BarIdentity, type BarProjection } from '../index'; + +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 layout = BarChart.useStackedBarLayout({ + data: growth, + series, + index: getWeek, + projection: projected ? projection : undefined, + }); + const isBarActive = useCallback( + (bar: BarIdentity) => + !selected || (bar.datum.week === selected.week && bar.positive === selected.positive), + [selected], + ); + return ( +

+ + + {lines => + lines.map(line => ( + + )) + } + + isBarActive={isBarActive}> + + + + + + {ticks => + ticks.map(tick => ( + + )) + } + + + {ticks => + ticks.map(tick => ( + + )) + } + + formatCategory={formatWeek}> + + + className='tooltip' + boundaryRef={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('BarChart visual state', () => { + it('stacks values above and below zero', async () => { + const chart = await renderChart(); + await expect(chart).toMatchScreenshot('bar-chart-diverging'); + }); + + it('dims every bar outside the selected section', async () => { + const chart = await renderChart(); + await expect(chart).toMatchScreenshot('bar-chart-dimmed-selection'); + }); + + it('draws a projection above the latest bar', async () => { + const chart = await renderChart(); + await expect(chart).toMatchScreenshot('bar-chart-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('bar-chart-tooltip-open'); + }); +}); From 98803c15d5f3aae60e31b7fbbb05df41196c81d7 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Sun, 22 Nov 2026 19:38:41 -0700 Subject: [PATCH 06/40] docs(mosaic): document the BarChart primitive --- .../mosaic/src/primitives/bar-chart/README.md | 271 ++++++++++++++++++ 1 file changed, 271 insertions(+) create mode 100644 packages/mosaic/src/primitives/bar-chart/README.md diff --git a/packages/mosaic/src/primitives/bar-chart/README.md b/packages/mosaic/src/primitives/bar-chart/README.md new file mode 100644 index 00000000000..8a0f2e8dbe4 --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/README.md @@ -0,0 +1,271 @@ +# Bar chart + +A headless stacked bar chart built from composable parts. D3 computes the diverging stacks and scales, Canvas paints the bars and the projection fill, one SVG over the Canvas draws the grid, axes, zero line and projection outline, and React handles interaction. The parts emit no visual styles: style each one with `className` and `data-*` attributes. + +## 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. +- A decorative placeholder chart: leave out `BarChart.BarSelection`. + +## Usage + +```tsx +import { BarChart } from '@clerk/mosaic/primitives/bar-chart'; + +const layout = BarChart.useStackedBarLayout({ data, series, index }); + + + + {lines => + lines.map(line => ( + + )) + } + + + + + + + + {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. 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` and `index`, or define them at module level. + +A container renders only the items its children function returns. A bare `` renders an empty SVG. + +## Parts + +| Part | Default element | Description | +| ---------------------------- | --------------- | ------------------------------------------------------------------- | +| `BarChart.Root` | `
` | Measures the container and provides the layout to the other parts | +| `BarChart.Grid` | `` | Holds the grid lines | +| `BarChart.GridLine` | `` | One line across the plot at a Y tick | +| `BarChart.StackedBars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | +| `BarChart.Bar` | `` | Hidden. Its computed style paints the bars | +| `BarChart.ProjectionOutline` | `` | Outlines the projected bar | +| `BarChart.ZeroLine` | `` | The line at zero | +| `BarChart.YAxis` | `` | Holds the Y tick labels in the left margin | +| `BarChart.YTick` | `` | One Y tick label | +| `BarChart.XAxis` | `` | Holds the category labels below the plot | +| `BarChart.XTick` | `` | One category label | +| `BarChart.BarSelection` | `
` | Pointer and keyboard selection over the whole chart | +| `BarChart.Cursor` | `
` | Covers the selected category's band | +| `BarChart.Tooltip` | `
` | The tooltip for the selected bar, 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 `BarChart.Root`. `BarChart.Bar`, `BarChart.ProjectionOutline` and `BarChart.ZeroLine` live inside `BarChart.StackedBars`, and `BarChart.Bar` and `BarChart.ProjectionOutline` throw outside it. `BarChart.Cursor` and `BarChart.Tooltip` throw outside `BarChart.BarSelection`. + +The namespace also holds `BarChart.useStackedBarLayout` and `BarChart.CanvasRenderError`. + +## Props + +### `BarChart.useStackedBarLayout` + +| 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 | +| `projection` | `{ datumIndex: number; value: number }` | — | A projected total, drawn when it rises above its category's stack | + +### `BarChart.Root` + +| Prop | Type | Default | Description | +| ------------ | ------------------------ | --------------- | ------------------------------------------------------------- | +| `layout` | `StackedBarLayoutSource` | (required) | The result of `BarChart.useStackedBarLayout` | +| `aria-label` | `string` | (required) | Labels the bars image and the interaction surface | +| `height` | `number \| string` | `500` | The container height | +| `margin` | `Partial` | `8, 16, 36, 52` | Space around the plot for the axes (top, right, bottom, left) | + +### `BarChart.Grid`, `BarChart.YAxis`, `BarChart.XAxis` + +| Part | Prop | Type | Default | Description | +| ---------------- | ---------- | ------------------------------------------- | ------------- | ---------------------------------------------------------------------------------------------- | +| `BarChart.Grid` | `children` | `(lines: ChartTick[]) => ReactNode` | — | Renders the lines | +| `BarChart.YAxis` | `format` | `(value: number) => ReactNode` | locale number | Formats a tick value | +| `BarChart.YAxis` | `children` | `(ticks: BarChartYTickItem[]) => ReactNode` | — | Renders the labels | +| `BarChart.XAxis` | `ticks` | `'category' \| 'calendar'` | `'category'` | `category` thins labels to fit. `calendar` labels calendar boundaries for long UTC date ranges | +| `BarChart.XAxis` | `format` | `(key: string) => string \| null` | the key | Labels a category, or returns null to omit it | +| `BarChart.XAxis` | `children` | `(ticks: XTick[]) => ReactNode` | — | Renders the labels | + +`BarChart.GridLine`, `BarChart.YTick` and `BarChart.XTick` each take the entry their container passed: `line` (`{ value, y }`) or `tick` (`{ 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. + +### `BarChart.StackedBars` + +| Prop | Type | Default | Description | +| ------------- | --------------------------------------- | ---------------- | --------------------------------------------------------------------- | +| `isBarActive` | `(bar: BarIdentity) => boolean` | every bar active | Returns false for a bar that `BarChart.Bar` styles as `data-inactive` | + +A new `isBarActive` function repaints the Canvas, so memoize it. + +### `BarChart.BarSelection` + +| Prop | Type | Default | Description | +| ---------------- | ---------------------------------------- | ------- | ----------------------------------------------------------- | +| `onActiveChange` | `(active: BarSelection \| null) => void` | — | Receives the selected category and section, or null | +| `onActivate` | `(active: ActiveBar) => void` | — | Called on click, Enter or Space. Makes the surface a button | +| `formatCategory` | `(key: string) => string \| null` | the key | Names a period in keyboard announcements | + +### `BarChart.Tooltip` + +| Prop | Type | Default | Description | +| ------------- | ------------------------------------------ | --------- | ------------------------------------------------------------- | +| `children` | `(active: ActiveBar) => ReactNode` | — | Content for the selected bar. Return null to hide the tooltip | +| `boundaryRef` | `RefObject` | the chart | Element the tooltip stays inside | + +`ActiveBar` is the selected period: its `category`, `datumIndex`, `datum` and `section`, which sections have values (`hasValues`), and whether the chart draws the projection there (`projected`). + +## Keyboard + +The interaction surface is focusable while `BarChart.BarSelection` has `onActiveChange`, `onActivate` or a `BarChart.Tooltip`. + +| Key | Behavior | +| ------------------------ | ------------------------------------------------------------------------ | +| `ArrowLeft`/`ArrowRight` | Selects the previous or next period | +| `Home`/`End` | Selects the first or last period | +| `ArrowUp`/`ArrowDown` | Selects the positive or negative section of the period | +| `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 the period under it. A tap selects on contact and stays selected until the user taps elsewhere or the gesture is cancelled. + +## Data attributes + +| Attribute | Part | Description | +| ----------------------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------- | +| `data-chart-interaction-mode` | `BarChart.Root` | `pending` before the first measurement, `interactive` with `BarChart.BarSelection` and categories, otherwise `visual-only` | +| `data-active` | `BarChart.XTick` | Present while the tick's period is selected. Calendar boundary labels never carry it | +| `data-chart-interaction` | `BarChart.BarSelection` | On the interaction surface inside the part | +| `data-active-section` | `BarChart.BarSelection` | On the interaction surface: `positive` or `negative` while a section is selected | +| `data-side` | `BarChart.Tooltip` | `left` or `right` of the selected period, or `bottom` when pinned to the top of a narrow chart | +| `data-open` / `data-closed` | `BarChart.Tooltip` | The tooltip's open state, with `data-starting-style` and `data-ending-style` during transitions | + +## Accessibility + +- The bars Canvas carries `role="img"` and the `aria-label` from `BarChart.Root`. The grid, axes, cursor and marks 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`. +- Visually hidden text describes the keys. A `status` region announces the selected period, named through `formatCategory`, and its section. +- 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. + +### `BarChart.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. `BarChart.Bar` renders one `aria-hidden` ``. Before each paint, `BarChart.StackedBars` puts it in every state it draws, reads its computed `color`, caches it per state, paints, then restores the element: + +| State | Set on `BarChart.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 `BarChart.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. + +`BarChart.Bar` also sets the bar geometry from its computed style. Only pixel values count: + +| CSS on `BarChart.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. `BarChart.ProjectionOutline` takes its width and corner radius from the same geometry. + +The Canvas repaints in the same frame when `BarChart.Bar` mounts, unmounts or changes `class`, when `` changes `class`, `style` or `data-theme`, when the pixel ratio changes (capped at 2), and when the layout or the props of `BarChart.StackedBars` change. 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. + +The primitive reads and writes no CSS variables. + +### Inline styles + +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 `BarChart.BarSelection` reaches the interaction surface. + +## Paint order + +Root does not reorder its children, so paint order is JSX order. Write the parts in this order: + +1. `BarChart.Grid` +2. `BarChart.StackedBars`, with `BarChart.ProjectionOutline` before `BarChart.ZeroLine`. The position of `BarChart.Bar` does not matter +3. `BarChart.YAxis` +4. `BarChart.XAxis` +5. `BarChart.BarSelection`, last, so its surface receives the pointer and its cursor paints over the bars + +Each container renders nothing until Root has measured a non-zero size. + +## Tooltip + +`BarChart.Tooltip` positions with Floating UI against a virtual element at the selected period: the band center, at the top of the plot. It opens to the right, flips left when the right side does not fit inside `boundaryRef`, and keeps the side it chose last until that side stops fitting, so it does not cross the bar twice near an edge. 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. + +## Layout + +`useStackedBarLayout` prepares the stacks when `data`, `series` or `index` change. Root measures its container, then projects the layout for each size or layout change. `BarChart.StackedBars` projects the bar marks when the layout or the bar geometry changes. The container size is committed 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 `BarChart.CanvasRenderError`, with the original failure as its `cause`, so an error boundary can offer a retry that mounts a fresh Canvas. From 646c21dc8f7c383d74390195f20e251041cd3c90 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Sun, 22 Nov 2026 19:38:51 -0700 Subject: [PATCH 07/40] docs(swingset): add the BarChart primitive page --- .../swingset/src/components/DocsViewer.tsx | 1 + packages/swingset/src/lib/registry.ts | 3 + packages/swingset/src/stories/bar-chart.mdx | 225 ++++++++++++++++++ .../src/stories/bar-chart.stories.tsx | 94 ++++++++ 4 files changed, 323 insertions(+) create mode 100644 packages/swingset/src/stories/bar-chart.mdx create mode 100644 packages/swingset/src/stories/bar-chart.stories.tsx diff --git a/packages/swingset/src/components/DocsViewer.tsx b/packages/swingset/src/components/DocsViewer.tsx index 54f30f1d696..dbd1a5ea949 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')), + 'bar-chart': dynamic(() => import('../stories/bar-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..60eabc4c1b6 100644 --- a/packages/swingset/src/lib/registry.ts +++ b/packages/swingset/src/lib/registry.ts @@ -55,6 +55,7 @@ import { LabelOnly as BannerLabelOnly, meta as bannerMeta, } from '../stories/banner.stories'; +import { meta as barChartMeta } from '../stories/bar-chart.stories'; 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'; @@ -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 barChartModule: StoryModule = { meta: barChartMeta }; 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, + barChartModule, comboboxPrimitiveModule, collapsibleModule, dialogModule, diff --git a/packages/swingset/src/stories/bar-chart.mdx b/packages/swingset/src/stories/bar-chart.mdx new file mode 100644 index 00000000000..a435f990bb0 --- /dev/null +++ b/packages/swingset/src/stories/bar-chart.mdx @@ -0,0 +1,225 @@ +import * as BarChartStories from './bar-chart.stories'; + +# BarChart + +A stacked bar chart over a category or time axis, with values above and below zero. It is a +**headless** primitive: 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 { BarChart } from '@clerk/mosaic/primitives/bar-chart'; + +const layout = BarChart.useStackedBarLayout({ data, series, index }); + + + + {lines => + lines.map(line => ( + + )) + } + + + + + + + + {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. This keeps one week's +positive section at full color: + +```tsx +const isBarActive = useCallback( + (bar: BarIdentity) => bar.datum.week === selectedWeek && bar.positive, + [selectedWeek], +); + + + +; +``` + +### Projection + +`projection` draws a projected total above one category's positive stack. The fill is painted +with `BarChart.Bar`'s `data-projection` color, and `BarChart.ProjectionOutline` draws its outline. +It is drawn only when `value` is above that category's stack. + +```tsx +const layout = BarChart.useStackedBarLayout({ + data, + series, + index, + projection: { datumIndex: data.length - 1, value: 130 }, +}); +``` + +## Parts + +| Part | Default Element | Description | +| ---------------------------- | --------------- | ------------------------------------------------------------------- | +| `BarChart.Root` | `
` | Measures the container and provides the layout | +| `BarChart.Grid` | `` | Holds the grid lines | +| `BarChart.GridLine` | `` | One line across the plot at a Y tick | +| `BarChart.StackedBars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | +| `BarChart.Bar` | `` | Hidden. Its computed style paints the bars | +| `BarChart.ProjectionOutline` | `` | Outlines the projected bar | +| `BarChart.ZeroLine` | `` | The line at zero | +| `BarChart.YAxis` | `` | Holds the Y tick labels | +| `BarChart.YTick` | `` | One Y tick label | +| `BarChart.XAxis` | `` | Holds the category labels | +| `BarChart.XTick` | `` | One category label | +| `BarChart.BarSelection` | `
` | Pointer and keyboard selection | +| `BarChart.Cursor` | `
` | Covers the selected category's band | +| `BarChart.Tooltip` | `
` | The tooltip for the selected bar, portaled | + +Every part accepts a `render` prop and the standard attributes of its default element. Every part +throws outside `BarChart.Root`. `BarChart.Bar` and `BarChart.ProjectionOutline` throw outside +`BarChart.StackedBars`, and `BarChart.Cursor` and `BarChart.Tooltip` throw outside +`BarChart.BarSelection`. + +## Props + +### `BarChart.useStackedBarLayout` + +| 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 | +| projection | { datumIndex: number; value: number } | — | A projected total, drawn when it rises above its stack | + +### `BarChart.Root` + +| Prop | Type | Default | Description | +| ----------------------- | --------------------------------------- | -------------------------- | ------------------------------------------------- | +| layout | StackedBarLayoutSource | — (required) | The result of `BarChart.useStackedBarLayout` | +| aria-label | string | — (required) | Labels the bars image and the interaction surface | +| height | number \| string | 500 | The container height | +| margin | Partial<ChartMargin> | 8, 16, 36, 52 | Space for the axes: top, right, bottom, left | + +### `BarChart.StackedBars` + +| Prop | Type | Default | Description | +| ------------------------ | -------------------------------------------------------- | ---------------- | ------------------------------------------------------ | +| isBarActive | (bar: BarIdentity<TDatum>) => boolean | every bar active | Returns false for a bar styled through `data-inactive` | + +### `BarChart.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 | + +`BarChart.YAxis` takes `format` (`(value: number) => ReactNode`, locale number by default). +`BarChart.Grid`, `BarChart.YAxis` and `BarChart.XAxis` take a `children` function that receives +their items. `BarChart.GridLine` takes `line`, and `BarChart.YTick` and `BarChart.XTick` take +`tick`. + +### `BarChart.BarSelection` + +| Prop | Type | Default | Description | +| --------------------------- | ------------------------------------------------------ | ------- | --------------------------------------------------- | +| onActiveChange | (active: BarSelection \| null) => void | — | Receives the selected category and section, or null | +| onActivate | (active: ActiveBar<TDatum>) => void | — | Called on click, Enter or Space | +| formatCategory | (key: string) => string \| null | the key | Names a period in keyboard announcements | + +### `BarChart.Tooltip` + +| Prop | Type | Default | Description | +| ------------------------ | ----------------------------------------------------------- | ------------ | ------------------------------------------- | +| children | (active: ActiveBar<TDatum>) => ReactNode | — (required) | Content for the selected bar; null hides it | +| boundaryRef | RefObject<HTMLElement \| null> | the chart | Element the tooltip stays inside | + +## Styling + +`BarChart.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 +`BarChart.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` | BarSelection | `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/bar-chart.stories.tsx b/packages/swingset/src/stories/bar-chart.stories.tsx new file mode 100644 index 00000000000..ab4b904e790 --- /dev/null +++ b/packages/swingset/src/stories/bar-chart.stories.tsx @@ -0,0 +1,94 @@ +'use client'; + +import { BarChart } from '@clerk/mosaic/primitives/bar-chart'; + +import type { StoryMeta } from '@/lib/types'; + +export const meta: StoryMeta = { + group: 'Primitives', + status: 'wip', + title: 'BarChart', + label: 'Bar Chart', + source: 'packages/mosaic/src/primitives/bar-chart/index.ts', +}; + +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; + +export function Default() { + const layout = BarChart.useStackedBarLayout({ data: growth, series, index: getWeek }); + return ( + + + {lines => + lines.map(line => ( + + )) + } + + + + + + + {ticks => + ticks.map(tick => ( + + )) + } + + + {ticks => + ticks.map(tick => ( + + )) + } + + > + + > + {({ datum }) => ( + <> +

{datum.week}

+ {series.map(s => ( +

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

+ ))} + + )} + + +
+ ); +} From 76a860f4597c927ea80992de18e4815497255c5e Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Sun, 22 Nov 2026 21:14:45 -0700 Subject: [PATCH 08/40] feat(mosaic): add BarChart.useBarChart and render the parts from its chart object useBarChart measures the container, projects the layout and owns the selection, keyboard handling and announcements. Root takes `chart`, BarSelection spreads `chart.getInteractionProps()`, and `selection` / `onSelectionChange` control the selection. useStackedBarLayout and BarSelection's onActiveChange are removed. --- .../__tests__/bar-chart.browser.test.tsx | 20 +- .../bar-chart/__tests__/bar-chart.test.tsx | 104 ++++- .../__tests__/bar-chart.visual.test.tsx | 20 +- .../bar-chart/__tests__/fixtures.tsx | 10 +- .../bar-chart/__tests__/test-chart.tsx | 75 ++-- .../bar-chart/bar-chart-bar-selection.tsx | 318 ++------------ .../primitives/bar-chart/bar-chart-context.ts | 26 +- .../primitives/bar-chart/bar-chart-cursor.tsx | 7 +- .../bar-chart/bar-chart-grid-line.tsx | 6 +- .../primitives/bar-chart/bar-chart-grid.tsx | 11 +- .../primitives/bar-chart/bar-chart-layout.ts | 9 +- .../primitives/bar-chart/bar-chart-root.tsx | 51 +-- .../bar-chart/bar-chart-selection.ts | 47 ++- .../bar-chart/bar-chart-stacked-bars.tsx | 25 +- .../bar-chart/bar-chart-tooltip.tsx | 9 +- .../primitives/bar-chart/bar-chart-x-axis.tsx | 26 +- .../primitives/bar-chart/bar-chart-x-tick.tsx | 8 +- .../primitives/bar-chart/bar-chart-y-axis.tsx | 13 +- .../primitives/bar-chart/bar-chart-y-tick.tsx | 4 +- .../bar-chart/bar-chart-zero-line.tsx | 10 +- .../mosaic/src/primitives/bar-chart/index.ts | 7 +- .../mosaic/src/primitives/bar-chart/parts.ts | 11 +- .../mosaic/src/primitives/bar-chart/types.ts | 4 +- .../src/primitives/bar-chart/use-bar-chart.ts | 393 ++++++++++++++++++ .../bar-chart/use-stacked-bar-layout.ts | 44 -- 25 files changed, 708 insertions(+), 550 deletions(-) create mode 100644 packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts delete mode 100644 packages/mosaic/src/primitives/bar-chart/use-stacked-bar-layout.ts diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx index 515dfc53d50..201eeb85011 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx @@ -42,7 +42,7 @@ function Chart({ width = 600, ...props }: Partial> & { width ariaLabel='Growth' height={300} barClassName='red' - onActiveChange={() => {}} + onSelectionChange={() => {}} {...props} />
@@ -133,35 +133,37 @@ describe('resizing', () => { describe('choosing a period with a pointer', () => { it('selects the period under a mouse and clears it when the mouse leaves', async () => { - const onActiveChange = vi.fn<(active: BarSelection | null) => void>(); - await render(); + 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(() => onActiveChange.mock.lastCall?.[0]).toMatchObject({ category: 'Apr', section: 'positive' }); + 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(() => onActiveChange.mock.lastCall?.[0]).toBeNull(); + 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 onActiveChange = vi.fn<(active: BarSelection | null) => void>(); - await render(); + const onSelectionChange = vi.fn<(selection: BarSelection | null) => void>(); + await render(); const { x, y } = centerOfCategory(1); pointer('pointerdown', surface(), x, y, 'touch'); surface().dispatchEvent( new PointerEvent('pointerout', { bubbles: true, pointerType: 'touch', relatedTarget: document.body }), ); - await expect.poll(() => onActiveChange.mock.lastCall?.[0]).toMatchObject({ category: 'Feb' }); + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toMatchObject({ category: 'Feb' }); pointer('pointerdown', document.body, 0, 0, 'touch'); - await expect.poll(() => onActiveChange.mock.lastCall?.[0]).toBeNull(); + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toBeNull(); }); }); diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx index d3d1798e6f5..b4c0dc35a36 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx @@ -19,10 +19,10 @@ function StackedChart({ render?: React.ComponentProps['render']; children?: React.ReactNode; }) { - const layout = BarChart.useStackedBarLayout({ data, series: chartFixture.series, index: chartFixture.index }); + const chart = BarChart.useBarChart({ data, series: chartFixture.series, index: chartFixture.index }); return ( @@ -220,7 +220,7 @@ describe('activating a period', () => { { name: 'Enter', props: { data: quarter }, keys: ['ArrowRight', 'Enter'] }, { name: 'Enter when the consumer only handles clicks', - props: { data: quarter, onActiveChange: undefined }, + props: { data: quarter, onSelectionChange: undefined }, keys: ['ArrowRight', 'Enter'], }, { @@ -284,12 +284,12 @@ describe('activating a period', () => { projection: { datumIndex: 0, value: -10 }, }, ])('does not activate zero values with an $name projection', ({ projection }) => { - const onActiveChange = vi.fn(); + const onSelectionChange = vi.fn(); const onActivate = vi.fn(); const { interaction, getByRole } = renderChart({ data: [{ period: 'Jan', value: 0 }], projection, - onActiveChange, + onSelectionChange, onActivate, }); @@ -297,7 +297,7 @@ describe('activating a period', () => { expect(getByRole('status')).toHaveTextContent('No values for this period'); fireEvent.keyDown(interaction, { key: 'Enter' }); - expect(onActiveChange).not.toHaveBeenCalledWith(expect.anything()); + expect(onSelectionChange).not.toHaveBeenCalledWith(expect.anything()); expect(onActivate).not.toHaveBeenCalled(); }); }); @@ -331,7 +331,7 @@ describe('keeping the selection when data changes', () => { series={[{ key: 'value', value: datum => datum.value }]} index={datum => datum.period} ariaLabel='Growth' - onActiveChange={setActive} + onSelectionChange={setActive} /> ); @@ -393,3 +393,93 @@ describe('reading the selected period as data changes', () => { expect(getByRole('status')).toHaveTextContent('Feb, positive values'); }); }); + +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' })); + }); +}); + +describe('rendering from the chart object', () => { + it('selects with the keyboard on a surface that spreads the interaction props', () => { + function CustomChart() { + const chart = BarChart.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'); + }); +}); diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx index 6f4338e1760..527e81c077c 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx @@ -54,17 +54,19 @@ function GrowthChart({ projected?: boolean; }) { const boundary = useRef(null); - const layout = BarChart.useStackedBarLayout({ - data: growth, - series, - index: getWeek, - projection: projected ? projection : undefined, - }); const isBarActive = useCallback( (bar: BarIdentity) => !selected || (bar.datum.week === selected.week && bar.positive === selected.positive), [selected], ); + const chart = BarChart.useBarChart({ + data: growth, + series, + index: getWeek, + projection: projected ? projection : undefined, + isBarActive, + formatCategory: formatWeek, + }); return (
@@ -87,7 +89,7 @@ function GrowthChart({ )) } - isBarActive={isBarActive}> + @@ -114,7 +116,7 @@ function GrowthChart({ )) } - formatCategory={formatWeek}> + className='tooltip' diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/fixtures.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/fixtures.tsx index b6d78477703..6485036df20 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/fixtures.tsx +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/fixtures.tsx @@ -2,6 +2,7 @@ import { act, render as renderComponent } from '@testing-library/react'; import type { ReactElement } from 'react'; import { vi } from 'vitest'; +import type { BarChartInstance } from '../index'; import type { BarSelection } from '../types'; import { TestChart, type TestChartProps } from './test-chart'; @@ -36,20 +37,21 @@ export const chartFixture = { /** * Renders the chart with a one-series fixture. Pass `data`, `series` and `index` together to use - * another row shape. `active()` returns the last published selection. + * 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 onActiveChange = vi.fn<(active: BarSelection | null) => void>(); - const chartProps = { ...base, onActiveChange, ...props }; + 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: () => onActiveChange.mock.lastCall?.[0] ?? null, + active: () => chartRef.current?.selected ?? null, rerenderChart: (next: Partial>) => view.rerender( = StackedBarLayoutOptions & - Pick, 'onActiveChange' | 'onActivate'> & { - ariaLabel: string; - formatXTick?: (value: string) => string | null; - /** Mounts `BarChart.BarSelection`. Default: true */ - barSelection?: boolean; - renderTooltip?: (active: ActiveBar) => ReactNode; - boundary?: React.RefObject; - height?: number | string; - /** Mounts `BarChart.Bar`. Default: true */ - bar?: boolean; - barClassName?: string; - isBarActive?: BarChartStackedBarsProps['isBarActive']; - }; +export type TestChartProps = Pick< + UseBarChartOptions, + | 'data' + | 'series' + | 'index' + | 'categoryGap' + | 'projection' + | 'isBarActive' + | 'selection' + | 'onSelectionChange' + | 'onActivate' +> & { + ariaLabel: string; + formatXTick?: (value: string) => string | null; + /** Mounts `BarChart.BarSelection`. Default: true */ + barSelection?: boolean; + renderTooltip?: (active: ActiveBar) => ReactNode; + boundary?: RefObject; + height?: number | string; + /** Mounts `BarChart.Bar`. Default: true */ + bar?: boolean; + barClassName?: 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({ - data, - series, - index, - categoryGap, - projection, ariaLabel, formatXTick, barSelection = true, - onActiveChange, - onActivate, renderTooltip, boundary, height, bar = true, barClassName, - isBarActive, + chartRef, + ...options }: TestChartProps) { - const layout = BarChart.useStackedBarLayout({ data, series, index, categoryGap, projection }); + const chart = BarChart.useBarChart({ ...options, formatCategory: formatXTick }); + useLayoutEffect(() => { + if (chartRef) { + chartRef.current = chart; + } + }); return ( - isBarActive={isBarActive}> + {bar ? : null} @@ -65,11 +70,7 @@ export function TestChart({ } {barSelection ? ( - - onActiveChange={onActiveChange} - onActivate={onActivate} - formatCategory={formatXTick} - > + {renderTooltip ? ( diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx index 7adbd3eec9e..4c38495d9b0 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx @@ -4,22 +4,7 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; import { BarSelectionContext, type BarSelectionContextValue, hasArea, useBarChartContext } from './bar-chart-context'; -import type { StackedBarLayout } from './bar-chart-layout'; -import { - getActiveBar, - getKeyboardAnnouncement, - getKeyIntent, - hitTest, - isSelectable, - NO_SELECTION, - resolveSelection, - sameSelection, - type Selected, - selectedState, - type SelectionAction, - selectionReducer, -} from './bar-chart-selection'; -import type { ActiveBar, BarCategory, BarSection, BarSelection, ChartSize } from './types'; +import type { BarChartInstance } from './use-bar-chart'; const VISUALLY_HIDDEN_STYLE: React.CSSProperties = { position: 'absolute', @@ -33,92 +18,7 @@ const VISUALLY_HIDDEN_STYLE: React.CSSProperties = { border: 0, }; -export type BarChartBarSelectionProps = ComponentProps<'div'> & { - /** Receives the selected category and section, or null. Read values from current data. */ - onActiveChange?: (active: BarSelection | null) => void; - /** Called on click, Enter or Space. Makes the surface a button. */ - onActivate?: (active: ActiveBar) => void; - /** Names a category in announcements. Default: the category key */ - formatCategory?: (category: string) => string | null; -}; - -/** Coalesces pointer moves into at most one selection update per frame. */ -function useFramePointerUpdates(onFrame: (selection: Selected | null) => void, layout: unknown) { - 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: Selected | null) => { - pendingRef.current = selection; - if (frameRef.current !== null) { - return; - } - frameRef.current = requestAnimationFrame(() => { - frameRef.current = null; - const pending = pendingRef.current; - pendingRef.current = undefined; - if (pending !== undefined) { - onFrame(pending); - } - }); - }; - const pendingSection = () => pendingRef.current?.section ?? undefined; - return { schedule, cancel, pendingSection }; -} - -/** Calls `onActiveChange` when the active bar changes and on unmount. */ -function usePublishActive( - active: BarSelection | null, - onActiveChange: ((active: BarSelection | null) => void) | undefined, -) { - const onActiveChangeRef = React.useRef(onActiveChange); - const publishedRef = React.useRef(null); - React.useLayoutEffect(() => { - onActiveChangeRef.current = onActiveChange; - }, [onActiveChange]); - React.useLayoutEffect(() => { - if (sameSelection(active, publishedRef.current)) { - return; - } - publishedRef.current = active; - onActiveChangeRef.current?.(active); - }); - React.useEffect( - () => () => { - if (publishedRef.current) { - onActiveChangeRef.current?.(null); - } - }, - [], - ); -} - -/** Holds the selection and drops it when its category or section disappears. */ -function useBarSelection(categories: readonly BarCategory[]) { - const [state, dispatch] = React.useReducer(selectionReducer, NO_SELECTION); - const categoryByKey = React.useMemo( - () => new Map(categories.map(category => [category.key, category])), - [categories], - ); - const stored = selectedState(state); - const storedCategory = stored ? categoryByKey.get(stored.category) : undefined; - const isValid = !!stored && !!storedCategory && isSelectable(stored, storedCategory); - return { - state, - selection: isValid ? stored : null, - selectedCategory: isValid ? storedCategory : undefined, - categoryByKey, - dispatch, - }; -} +export type BarChartBarSelectionProps = ComponentProps<'div'>; function KeyboardInstructions({ id, @@ -145,242 +45,72 @@ function KeyboardInstructions({ ); } -// eslint-disable-next-line typescript/consistent-type-assertions -- The ref wrapper drops the row type parameter; `onActivate` only receives rows the chart was given. export const BarChartBarSelection = React.forwardRef( function BarChartBarSelection(props, ref) { - const { frame, layout, data, ariaLabel, registerInteraction, setActiveCategory } = - useBarChartContext('BarSelection'); + const { chart, ariaLabel, registerInteraction } = useBarChartContext('BarSelection'); React.useLayoutEffect(registerInteraction, [registerInteraction]); - if (!hasArea(frame.size) || layout.categories.length === 0) { + if (!hasArea(chart.size) || chart.categories.length === 0) { return null; } return ( ); }, -) as ( - props: BarChartBarSelectionProps & { ref?: React.Ref }, -) => React.ReactElement | null; - -const formatCategoryKey = (category: string) => category; +); type SurfaceProps = BarChartBarSelectionProps & { forwardedRef: React.ForwardedRef; - data: readonly unknown[]; - layout: StackedBarLayout; - size: ChartSize; + chart: BarChartInstance; ariaLabel: string; - setActiveCategory: (category: string | null) => void; }; -function BarSelectionSurface({ - forwardedRef, - data, - layout, - size, - ariaLabel, - setActiveCategory, - onActiveChange, - onActivate, - formatCategory = formatCategoryKey, - children, - render, - ...otherProps -}: SurfaceProps) { +function BarSelectionSurface({ forwardedRef, chart, ariaLabel, children, render, ...otherProps }: SurfaceProps) { const chartBoxRef = React.useRef(null); - const { state, selection, selectedCategory, categoryByKey, dispatch } = useBarSelection(layout.categories); - const surfaceRef = React.useRef(null); - const lastIndexRef = React.useRef(0); const keyboardInstructionsId = React.useId(); const [tooltipCount, setTooltipCount] = React.useState(0); const registerTooltip = React.useCallback(() => { setTooltipCount(count => count + 1); return () => setTooltipCount(count => count - 1); }, []); - const pointerUpdates = useFramePointerUpdates(next => dispatch({ type: 'pointer', selection: next }), layout); - - const selectedSection = selection?.section ?? undefined; - const selectedIndex = selectedCategory?.datumIndex; - React.useLayoutEffect(() => { - if (selectedIndex !== undefined) { - lastIndexRef.current = selectedIndex; - } - }, [selectedIndex]); - const keyboardIndex = () => selectedIndex ?? lastIndexRef.current; - const keyboardAnnouncement = getKeyboardAnnouncement(selection, selectedCategory, formatCategory); - - // A tap fires no pointerleave or blur, so a tap anywhere else dismisses. - const hasPointerSelection = selection?.source === 'pointer'; - React.useEffect(() => { - if (!hasPointerSelection) { - return; - } - const dismissOutside = (event: PointerEvent) => { - if (!(event.target instanceof Node) || !surfaceRef.current?.contains(event.target)) { - dispatch({ type: 'clear' }); - } - }; - document.addEventListener('pointerdown', dismissOutside, true); - return () => document.removeEventListener('pointerdown', dismissOutside, true); - }, [dispatch, hasPointerSelection]); - - const active = resolveSelection(selection, selectedCategory); - usePublishActive(active, onActiveChange); - const activeCategory = active?.category ?? null; - React.useLayoutEffect(() => { - setActiveCategory(activeCategory); - return () => setActiveCategory(null); - }, [activeCategory, setActiveCategory]); - - const pointerSelection = (clientX: number, clientY: number) => { - const bounds = chartBoxRef.current?.getBoundingClientRect(); - const local = - bounds && bounds.width > 0 && bounds.height > 0 - ? { - x: ((clientX - bounds.left) / bounds.width) * size.width, - y: ((clientY - bounds.top) / bounds.height) * size.height, - } - : { x: 0, y: layout.zeroY }; - return hitTest(layout, local, pointerUpdates.pendingSection() ?? selectedSection); - }; - - const resolveNext = (next: Selected | null) => - resolveSelection(next, next ? categoryByKey.get(next.category) : undefined); - - const dispatchSelection = (action: SelectionAction) => { - if (action.type !== 'pointer') { - pointerUpdates.cancel(); - } - dispatch(action); - return resolveNext(selectedState(selectionReducer(state, action))); - }; - - const selectKeyboardIndex = (index: number, section?: BarSection) => - dispatchSelection({ - type: 'keyboard', - category: layout.categories[Math.max(0, Math.min(layout.categories.length - 1, index))], - section, - }); - - const activate = (bar: BarSelection | null) => { - const activated = getActiveBar(bar, data, categoryByKey); - if (activated) { - onActivate?.(activated); - } - }; - - const activateKeyboardSelection = (section: BarSection | undefined) => { - const dismissed = state.status === 'dismissed'; - const bar = selectKeyboardIndex(keyboardIndex(), section); - if (!dismissed) { - activate(bar); - } - }; - - const interactive = !!(onActiveChange || onActivate || tooltipCount > 0); - const selectionContext: BarSelectionContextValue = { - activeBar: getActiveBar(active, data, categoryByKey), - selectedCategory: selection?.section ? selectedCategory : undefined, - plot: layout.plot, - chartWidth: size.width, - chartBoxRef, - registerTooltip, - }; + const selectionContext = React.useMemo( + () => ({ chartBoxRef, registerTooltip }), + [registerTooltip], + ); - const eventHandlers: 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(); - dispatchSelection({ type: 'pointer', selection: pointerSelection(event.clientX, event.clientY) }); - }, - onPointerLeave: event => { - if (event.pointerType !== 'touch') { - dispatchSelection({ type: 'clear' }); - } - }, - onPointerCancel: () => { - dispatchSelection({ type: 'clear' }); - }, - onPointerMove: event => { - pointerUpdates.schedule(pointerSelection(event.clientX, event.clientY)); - }, - onFocus: () => { - selectKeyboardIndex(keyboardIndex()); - }, - onBlur: () => { - dispatchSelection({ 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(selectedSection); - return; - } - activate(resolveNext(pointerSelection(event.clientX, event.clientY))); - }, - onKeyDown: event => { - const intent = getKeyIntent( - event.key, - keyboardIndex(), - layout.categories.length - 1, - selectedSection, - !!onActivate, - ); - if (!intent) { - return; - } - event.preventDefault(); - if (intent.type === 'dismiss') { - dispatchSelection({ type: 'dismiss' }); - } else if (intent.activate) { - activateKeyboardSelection(intent.section); - } else { - selectKeyboardIndex(intent.index, intent.section); - } - }, - }; + const interaction = chart.getInteractionProps(); + const focusable = 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}
), diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-context.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-context.ts index b9a3f5f118b..474f0e316a5 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-context.ts +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-context.ts @@ -1,24 +1,19 @@ import { createContext, type RefObject, useContext } from 'react'; import type { BarStyleElement } from './bar-chart-canvas'; -import type { PaintedProjection, StackedBarLayout } from './bar-chart-layout'; -import type { ActiveBar, BarCategory, ChartFrame, ChartPlot, ChartSize } from './types'; +import type { PaintedProjection } from './bar-chart-layout'; +import type { ChartSize } from './types'; +import type { BarChartInstance } from './use-bar-chart'; export interface BarChartContextValue { - frame: ChartFrame; - layout: StackedBarLayout; - data: readonly unknown[]; + chart: BarChartInstance; ariaLabel: string; /** Marks the chart interactive while the returned cleanup has not run. */ registerInteraction: () => () => void; - setActiveCategory: (category: string | null) => void; } export const BarChartContext = createContext(null); -/** Separate from `BarChartContext` so a selection change re-renders only the parts that show it. */ -export const BarChartActiveCategoryContext = createContext(null); - export function useBarChartContext(part: string) { const context = useContext(BarChartContext); if (!context) { @@ -26,12 +21,10 @@ export function useBarChartContext(part: string) { } return { ...context, - // SAFETY: `BarChart.Root` holds the rows and layout of one `useStackedBarLayout` call, and - // a part's `TDatum` is the type of the chart it renders in. Context cannot carry the parameter. - // eslint-disable-next-line typescript/consistent-type-assertions -- React context is not generic per consumer. - layout: context.layout as StackedBarLayout, + // SAFETY: `BarChart.Root` holds one `useBarChart` result, and a part's `TDatum` is the + // type of the chart it renders in. Context cannot carry the parameter. // eslint-disable-next-line typescript/consistent-type-assertions -- React context is not generic per consumer. - data: context.data as readonly TDatum[], + chart: context.chart as unknown as BarChartInstance, }; } @@ -56,11 +49,6 @@ export function useStackedBarsContext(part: string) { } export interface BarSelectionContextValue { - activeBar: ActiveBar | null; - /** The selected category while a section is selected. */ - selectedCategory: BarCategory | undefined; - plot: ChartPlot; - chartWidth: number; /** Spans the whole chart, so its client rect anchors the tooltip. */ chartBoxRef: RefObject; /** Makes the surface focusable while the returned cleanup has not run. */ diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-cursor.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-cursor.tsx index b27565e3b25..102cd521a1f 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-cursor.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-cursor.tsx @@ -3,14 +3,17 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { useBarSelectionContext } from './bar-chart-context'; +import { useBarChartContext, useBarSelectionContext } from './bar-chart-context'; export type BarChartCursorProps = ComponentProps<'div'>; export const BarChartCursor = React.forwardRef( function BarChartCursor(props, ref) { const { render, ...otherProps } = props; - const { selectedCategory, plot } = useBarSelectionContext('Cursor'); + useBarSelectionContext('Cursor'); + const { chart } = useBarChartContext('Cursor'); + const { plot, selected } = chart; + const selectedCategory = selected ? chart.categories[selected.datumIndex] : undefined; const ownProps = { 'aria-hidden': 'true', diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-grid-line.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-grid-line.tsx index da3a860ad43..314393b6841 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-grid-line.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-grid-line.tsx @@ -14,11 +14,11 @@ export type BarChartGridLineProps = ComponentProps<'line'> & { export const BarChartGridLine = React.forwardRef( function BarChartGridLine(props, ref) { const { line, render, ...otherProps } = props; - const { layout } = useBarChartContext('GridLine'); + const { chart } = useBarChartContext('GridLine'); const ownProps = { - x1: layout.plot.x, - x2: layout.plot.x + layout.plot.width, + x1: chart.plot.x, + x2: chart.plot.x + chart.plot.width, y1: line.y, y2: line.y, vectorEffect: 'non-scaling-stroke', diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-grid.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-grid.tsx index 925d6668bff..65e9eac3c85 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-grid.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-grid.tsx @@ -13,21 +13,22 @@ export type BarChartGridProps = Omit, 'children'> & { export const BarChartGrid = React.forwardRef(function BarChartGrid(props, ref) { const { children, render, ...otherProps } = props; - const { frame, layout } = useBarChartContext('Grid'); + const { chart } = useBarChartContext('Grid'); + const { size, yTicks } = chart; const ownProps = { - width: frame.size.width, - height: frame.size.height, + width: size.width, + height: size.height, 'aria-hidden': 'true', style: { position: 'absolute', inset: 0, display: 'block', pointerEvents: 'none' }, - children: children?.(layout.yTicks), + children: children?.(yTicks), } satisfies DefaultProps<'svg'>; return useRender({ defaultTagName: 'svg', render, ref, - enabled: hasArea(frame.size), + enabled: hasArea(size), props: mergeProps<'svg'>(ownProps, otherProps), }); }); diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts index 945351ac22c..ce5a60c61f8 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts @@ -165,7 +165,7 @@ function splitNeighbourGap(previous: DraftBarMark, mark: DraftBa } } -function projectMarksAndPaintInsets(layout: StackedBarLayout, { maxWidth, gap }: BarGeometry) { +function projectMarksAndPaintInsets(layout: MarkSource, { maxWidth, gap }: BarGeometry) { const { categories, scaleY } = layout; const marks: DraftBarMark[] = []; const previousMarkByStack = new Map>(); @@ -350,10 +350,9 @@ export function projectStackedBars( export type StackedBarLayout = ReturnType>; -export function projectStackedBarMarks( - layout: StackedBarLayout, - geometry: BarGeometry, -): BarMark[] { +type MarkSource = Pick, 'prepared' | 'categories' | 'scaleY'>; + +export function projectStackedBarMarks(layout: MarkSource, geometry: BarGeometry): BarMark[] { return applyCornerRadii(projectMarksAndPaintInsets(layout, geometry), geometry); } diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-root.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-root.tsx index 5594992a14c..8ad6efe13e6 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-root.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-root.tsx @@ -3,71 +3,48 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { BarChartActiveCategoryContext, BarChartContext, type BarChartContextValue } from './bar-chart-context'; -import { DEFAULT_CHART_MARGIN } from './bar-chart-layout'; -import type { ChartMargin } from './types'; -import { useChartSize } from './use-chart-size'; -import type { StackedBarLayoutSource } from './use-stacked-bar-layout'; +import { BarChartContext, type BarChartContextValue } from './bar-chart-context'; +import type { BarChartInstance } from './use-bar-chart'; -export type BarChartRootProps = Omit, 'aria-label'> & { - /** A stable layout source from `BarChart.useStackedBarLayout`. */ - layout: StackedBarLayoutSource; +export type BarChartRootProps = Omit, 'aria-label'> & { + /** The result of `BarChart.useBarChart`. */ + chart: BarChartInstance; /** Default: 500 */ height?: number | string; - margin?: Partial; /** Labels the bars image and the interaction surface. */ 'aria-label': string; }; type InteractionMode = 'pending' | 'interactive' | 'visual-only'; +// eslint-disable-next-line typescript/consistent-type-assertions -- The ref wrapper drops the row type parameter; the parts read the chart through context. export const BarChartRoot = React.forwardRef(function BarChartRoot(props, ref) { - const { layout, height = 500, margin, 'aria-label': ariaLabel, render, children, ...otherProps } = props; - const { ref: sizeRef, size } = useChartSize(); - 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 frame = React.useMemo(() => ({ size, margin: { top, right, bottom, left } }), [bottom, left, right, size, top]); - const projected = React.useMemo(() => layout.project(frame), [frame, layout]); + 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 [activeCategory, setActiveCategory] = React.useState(null); - const context = React.useMemo( - () => ({ - frame, - layout: projected, - data: layout.data, - ariaLabel, - registerInteraction, - setActiveCategory, - }), - [ariaLabel, frame, layout.data, projected, registerInteraction], - ); + const context: BarChartContextValue = { chart, ariaLabel, registerInteraction }; const interactionMode: InteractionMode = - size.width <= 0 + chart.size.width <= 0 ? 'pending' - : interactionLayers > 0 && projected.categories.length > 0 + : interactionLayers > 0 && chart.categories.length > 0 ? 'interactive' : 'visual-only'; const ownProps = { style: { position: 'relative', minWidth: 0, overflow: 'hidden', height }, - children: ( - {children} - ), + children, } satisfies DefaultProps<'div'>; const element = useRender({ defaultTagName: 'div', render, - ref: [sizeRef, ref], + ref: [chart.rootRef, ref], state: { interactionMode }, stateAttributesMapping: { interactionMode: (mode: InteractionMode) => ({ 'data-chart-interaction-mode': mode }), @@ -76,4 +53,6 @@ export const BarChartRoot = React.forwardRef( }); return {element}; -}); +}) as ( + props: BarChartRootProps & { ref?: React.Ref }, +) => React.ReactElement | null; diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts index 0013501b943..47f33942e3d 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts @@ -3,7 +3,8 @@ import type { ActiveBar, BarCategory, BarSection, BarSelection } from './types'; export type Selected = Readonly<{ status: 'selected'; - source: 'pointer' | 'keyboard'; + /** `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. */ section: BarSection | null; @@ -18,6 +19,7 @@ export type SelectionState = Readonly<{ status: 'none' }> | Readonly<{ status: ' export type SelectionAction = | Readonly<{ type: 'pointer'; selection: Selected | null }> | Readonly<{ type: 'keyboard'; category: BarCategory | undefined; section?: BarSection }> + | Readonly<{ type: 'select'; selection: BarSelection }> | Readonly<{ type: 'clear' }> | Readonly<{ type: 'dismiss' }>; @@ -27,6 +29,8 @@ export function selectionReducer(state: SelectionState, action: SelectionAction) switch (action.type) { case 'pointer': return action.selection ?? NO_SELECTION; + case 'select': + return { status: 'selected', source: 'external', ...action.selection }; case 'clear': return state.status === 'dismissed' ? state : NO_SELECTION; case 'dismiss': @@ -95,33 +99,44 @@ export function isSelectable(selection: Selected, category: BarCategory) { return selection.section === null || category.sections[selection.section]; } -export function resolveSelection(selection: Selected | null, category: BarCategory | undefined): BarSelection | null { - if (!selection?.section || !category?.sections[selection.section]) { - return null; - } - return { - category: category.key, - datumIndex: category.datumIndex, - section: selection.section, - }; +/** The public value of a selection state: the selected category and section, or null. */ +export function toBarSelection(state: SelectionState): BarSelection | null { + return state.status === 'selected' && state.section ? { category: state.category, section: state.section } : null; } export function sameSelection(a: BarSelection | null, b: BarSelection | null) { - return a?.category === b?.category && a?.datumIndex === b?.datumIndex && a?.section === b?.section; + return a?.category === b?.category && a?.section === b?.section; +} + +/** + * 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: BarSelection | null): SelectionState { + if (sameSelection(toBarSelection(state), value)) { + return state; + } + return value ? { status: 'selected', source: 'external', ...value } : NO_SELECTION; } export function getActiveBar( - bar: BarSelection | null, + selection: Selected | null, data: readonly TDatum[], categoryByKey: ReadonlyMap, ): ActiveBar | null { - const datum = bar ? data[bar.datumIndex] : undefined; - const category = bar ? categoryByKey.get(bar.category) : undefined; - if (!bar || datum === undefined || !category) { + const category = selection ? categoryByKey.get(selection.category) : undefined; + if (!selection?.section || !category?.sections[selection.section]) { + return null; + } + const datum = data[category.datumIndex]; + if (datum === undefined) { return null; } return { - ...bar, + category: category.key, + section: selection.section, + datumIndex: category.datumIndex, datum, hasValues: category.hasValues, projected: category.projected, diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx index 31fcc0d4e99..e1002f3bea1 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx @@ -12,12 +12,8 @@ import { } from './bar-chart-canvas'; import { hasArea, StackedBarsContext, useBarChartContext } from './bar-chart-context'; import { fitProjectionToBar, projectStackedBarMarks } from './bar-chart-layout'; -import type { BarIdentity } from './types'; -export type BarChartStackedBarsProps = ComponentProps<'div'> & { - /** Returns false for a bar that `BarChart.Bar` styles through `data-inactive`. Default: every bar is active */ - isBarActive?: (bar: BarIdentity) => boolean; -}; +export type BarChartStackedBarsProps = ComponentProps<'div'>; function subscribeToPixelRatio(callback: () => void) { let query = window.matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`); @@ -49,12 +45,11 @@ function subscribeToRootTheme(onChange: () => void) { const getServerSnapshot = () => ''; const getServerPixelRatio = () => 1; -// eslint-disable-next-line typescript/consistent-type-assertions -- The ref wrapper drops the row type parameter; `isBarActive` only receives rows the chart was given. export const BarChartStackedBars = React.forwardRef( function BarChartStackedBars(props, ref) { - const { isBarActive, children, render, ...otherProps } = props; - const { frame, layout, ariaLabel } = useBarChartContext('StackedBars'); - const { size } = frame; + const { children, render, ...otherProps } = props; + const { chart, ariaLabel } = useBarChartContext('StackedBars'); + const { size, prepared, categories, scaleY, isBarActive, projection: projectedBar } = chart; const rootThemeAttributes = React.useSyncExternalStore( subscribeToRootTheme, getRootThemeAttributes, @@ -86,11 +81,11 @@ export const BarChartStackedBars = React.forwardRef parseBarGeometry(barGeometry), [barGeometry]); - const marks = React.useMemo(() => projectStackedBarMarks(layout, geometry), [geometry, layout]); - const projection = React.useMemo( - () => fitProjectionToBar(layout.projection, geometry), - [geometry, layout.projection], + const marks = React.useMemo( + () => projectStackedBarMarks({ prepared, categories, scaleY }, geometry), + [categories, geometry, prepared, scaleY], ); + const projection = React.useMemo(() => fitProjectionToBar(projectedBar, geometry), [geometry, projectedBar]); const stackedBarsContext = React.useMemo(() => ({ setBar, projection }), [projection]); React.useLayoutEffect(() => { @@ -141,6 +136,4 @@ export const BarChartStackedBars = React.forwardRef( - props: BarChartStackedBarsProps & { ref?: React.Ref }, -) => React.ReactElement | null; +); diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx index 17352d882b9..8819336c786 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx @@ -8,7 +8,7 @@ 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 { useBarSelectionContext } from './bar-chart-context'; +import { useBarChartContext, useBarSelectionContext } from './bar-chart-context'; import type { ActiveBar } from './types'; const EDGE = 8; @@ -47,8 +47,11 @@ function tooltipMiddleware(getBoundary: () => Element | undefined, pinned: boole export const BarChartTooltip = React.forwardRef( function BarChartTooltip(props, ref) { const { children, boundaryRef, render, ...otherProps } = props; - const { activeBar, selectedCategory, registerTooltip, plot, chartWidth, chartBoxRef } = - useBarSelectionContext('Tooltip'); + const { registerTooltip, chartBoxRef } = useBarSelectionContext('Tooltip'); + const { chart } = useBarChartContext('Tooltip'); + const { plot, selected: activeBar } = chart; + const chartWidth = chart.size.width; + const selectedCategory = activeBar ? chart.categories[activeBar.datumIndex] : undefined; React.useLayoutEffect(registerTooltip, [registerTooltip]); const content = activeBar && selectedCategory ? children(activeBar) : null; diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-x-axis.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-x-axis.tsx index d7d4968808e..b8c14cdc9ad 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-x-axis.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-x-axis.tsx @@ -4,14 +4,15 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; import { hasArea, useBarChartContext } from './bar-chart-context'; -import { selectXTicks, type XTick } from './x-ticks'; +import type { XTickMode } from './use-bar-chart'; +import type { XTick } from './x-ticks'; export type BarChartXAxisProps = 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?: 'category' | 'calendar'; + 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 `BarChart.XTick` per entry. */ @@ -22,22 +23,13 @@ const formatCategory = (value: string) => value; export const BarChartXAxis = React.forwardRef(function BarChartXAxis(props, ref) { const { ticks = 'category', format = formatCategory, children, render, ...otherProps } = props; - const { frame, layout } = useBarChartContext('XAxis'); - const xTicks = React.useMemo( - () => - selectXTicks({ - categories: layout.categories, - plot: layout.plot, - viewportWidth: frame.size.width, - xAxis: ticks === 'calendar' ? 'calendar' : undefined, - formatXTick: format, - }), - [format, frame.size.width, layout.categories, layout.plot, ticks], - ); + const { chart } = useBarChartContext('XAxis'); + const { size, xTicks: getXTicks } = chart; + const xTicks = React.useMemo(() => getXTicks({ mode: ticks, format }), [format, getXTicks, ticks]); const ownProps = { - width: frame.size.width, - height: frame.size.height, + width: size.width, + height: size.height, 'aria-hidden': 'true', style: { position: 'absolute', inset: 0, display: 'block', overflow: 'visible' }, children: children?.(xTicks), @@ -47,7 +39,7 @@ export const BarChartXAxis = React.forwardRef defaultTagName: 'svg', render, ref, - enabled: hasArea(frame.size), + enabled: hasArea(size), props: mergeProps<'svg'>(ownProps, otherProps), }); }); diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-x-tick.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-x-tick.tsx index 4aec0800c59..87a514a52a9 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-x-tick.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-x-tick.tsx @@ -3,7 +3,7 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { BarChartActiveCategoryContext, useBarChartContext } from './bar-chart-context'; +import { useBarChartContext } from './bar-chart-context'; import type { XTick } from './x-ticks'; export type BarChartXTickProps = ComponentProps<'text'> & { @@ -13,12 +13,12 @@ export type BarChartXTickProps = ComponentProps<'text'> & { export const BarChartXTick = React.forwardRef(function BarChartXTick(props, ref) { const { tick, render, ...otherProps } = props; - const { layout } = useBarChartContext('XTick'); - const activeCategory = React.useContext(BarChartActiveCategoryContext); + const { chart } = useBarChartContext('XTick'); + const activeCategory = chart.selected?.category ?? null; const ownProps = { x: tick.x, - y: layout.plot.y + layout.plot.height + 24, + y: chart.plot.y + chart.plot.height + 24, textAnchor: tick.textAnchor, children: tick.label, } satisfies DefaultProps<'text'>; diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-y-axis.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-y-axis.tsx index 11ce57b21a2..704fd187402 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-y-axis.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-y-axis.tsx @@ -22,15 +22,16 @@ const formatNumber = (value: number) => value.toLocaleString(); export const BarChartYAxis = React.forwardRef(function BarChartYAxis(props, ref) { const { format = formatNumber, children, render, ...otherProps } = props; - const { frame, layout } = useBarChartContext('YAxis'); + const { chart } = useBarChartContext('YAxis'); + const { size, yTicks } = chart; const ticks = React.useMemo( - () => layout.yTicks.map(tick => ({ value: tick.value, y: tick.y, label: format(tick.value) })), - [format, layout.yTicks], + () => yTicks.map(tick => ({ value: tick.value, y: tick.y, label: format(tick.value) })), + [format, yTicks], ); const ownProps = { - width: frame.size.width, - height: frame.size.height, + width: size.width, + height: size.height, 'aria-hidden': 'true', style: { position: 'absolute', inset: 0, display: 'block', overflow: 'visible' }, children: children?.(ticks), @@ -40,7 +41,7 @@ export const BarChartYAxis = React.forwardRef defaultTagName: 'svg', render, ref, - enabled: hasArea(frame.size), + enabled: hasArea(size), props: mergeProps<'svg'>(ownProps, otherProps), }); }); diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-y-tick.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-y-tick.tsx index 06d5909abf2..61fd69e9559 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-y-tick.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-y-tick.tsx @@ -13,10 +13,10 @@ export type BarChartYTickProps = ComponentProps<'text'> & { export const BarChartYTick = React.forwardRef(function BarChartYTick(props, ref) { const { tick, render, ...otherProps } = props; - const { frame } = useBarChartContext('YTick'); + const { chart } = useBarChartContext('YTick'); const ownProps = { - x: frame.margin.left - 12, + x: chart.plot.x - 12, y: tick.y, dy: '0.32em', textAnchor: 'end', diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-zero-line.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-zero-line.tsx index 6307f77f002..ab5c8ab615f 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-zero-line.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-zero-line.tsx @@ -10,13 +10,13 @@ export type BarChartZeroLineProps = ComponentProps<'line'>; export const BarChartZeroLine = React.forwardRef( function BarChartZeroLine(props, ref) { const { render, ...otherProps } = props; - const { layout } = useBarChartContext('ZeroLine'); + const { chart } = useBarChartContext('ZeroLine'); const ownProps = { - x1: layout.plot.x, - x2: layout.plot.x + layout.plot.width, - y1: layout.zeroY, - y2: layout.zeroY, + x1: chart.plot.x, + x2: chart.plot.x + chart.plot.width, + y1: chart.zeroY, + y2: chart.zeroY, vectorEffect: 'non-scaling-stroke', } satisfies DefaultProps<'line'>; diff --git a/packages/mosaic/src/primitives/bar-chart/index.ts b/packages/mosaic/src/primitives/bar-chart/index.ts index 8a225b7e93f..fb3fa02c4a6 100644 --- a/packages/mosaic/src/primitives/bar-chart/index.ts +++ b/packages/mosaic/src/primitives/bar-chart/index.ts @@ -5,6 +5,8 @@ export type { BarChartBarSelectionProps, BarChartCursorProps, BarChartGridLineProps, + BarChartInstance, + BarChartInteractionProps, BarChartGridProps, BarChartProjectionOutlineProps, BarChartRootProps, @@ -16,8 +18,9 @@ export type { BarChartYTickItem, BarChartYTickProps, BarChartZeroLineProps, - StackedBarLayoutOptions, - StackedBarLayoutSource, + UseBarChartOptions, + XTickMode, + XTicksOptions, } from './parts'; export type { StackedBarLayout } from './bar-chart-layout'; export type { diff --git a/packages/mosaic/src/primitives/bar-chart/parts.ts b/packages/mosaic/src/primitives/bar-chart/parts.ts index 001a0ceee7e..9eff94b4a37 100644 --- a/packages/mosaic/src/primitives/bar-chart/parts.ts +++ b/packages/mosaic/src/primitives/bar-chart/parts.ts @@ -17,7 +17,10 @@ export { type BarChartCursorProps, BarChartCursor as Cursor } from './bar-chart- export { type BarChartTooltipProps, BarChartTooltip as Tooltip } from './bar-chart-tooltip'; export { CanvasRenderError } from './bar-chart-canvas'; export { - type StackedBarLayoutOptions, - type StackedBarLayoutSource, - useStackedBarLayout, -} from './use-stacked-bar-layout'; + type BarChartInstance, + type BarChartInteractionProps, + useBarChart, + type UseBarChartOptions, + type XTickMode, + type XTicksOptions, +} from './use-bar-chart'; diff --git a/packages/mosaic/src/primitives/bar-chart/types.ts b/packages/mosaic/src/primitives/bar-chart/types.ts index e8a1d3f2e45..1b0ed10a6af 100644 --- a/packages/mosaic/src/primitives/bar-chart/types.ts +++ b/packages/mosaic/src/primitives/bar-chart/types.ts @@ -67,14 +67,16 @@ export type BarCategory = Readonly<{ projected: boolean; }>; +/** A selected category and section. */ export type BarSelection = Readonly<{ category: string; - datumIndex: number; section: BarSection; }>; +/** A selected bar resolved against the current data. */ export type ActiveBar = BarSelection & Readonly<{ + datumIndex: number; datum: TDatum; hasValues: BarCategory['hasValues']; projected: BarCategory['projected']; diff --git a/packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts b/packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts new file mode 100644 index 00000000000..f6a8f1c839a --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts @@ -0,0 +1,393 @@ +'use client'; + +import React from 'react'; + +import { useControllableState } from '../hooks/use-controllable-state'; +import { + DEFAULT_CHART_MARGIN, + prepareStackedBars, + projectStackedBars, + type StackedBarLayout, +} from './bar-chart-layout'; +import { + getActiveBar, + getKeyboardAnnouncement, + getKeyIntent, + hitTest, + isSelectable, + NO_SELECTION, + reconcileSelection, + sameSelection, + type Selected, + selectedState, + type SelectionAction, + selectionReducer, + type SelectionState, + toBarSelection, +} from './bar-chart-selection'; +import type { + ActiveBar, + BarIdentity, + BarProjection, + BarSection, + BarSelection, + BarSeries, + ChartMargin, + ChartSize, +} from './types'; +import { useChartSize } from './use-chart-size'; +import { selectXTicks, type XTick } from './x-ticks'; + +export interface UseBarChartOptions { + 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; + /** Space around the plot for the axes. Default: 8, 16, 36, 52 (top, right, bottom, left) */ + margin?: Partial; + /** Paints a projected total behind the bar at `datumIndex`, when it rises above the bar. */ + projection?: BarProjection; + /** Returns false for a bar that `BarChart.Bar` styles through `data-inactive`. Default: every bar is active */ + isBarActive?: (bar: BarIdentity) => boolean; + /** The selected category and section, or null. Leave it undefined to let the chart hold the selection. */ + selection?: BarSelection | null; + /** Called when the user or `select`/`clear` changes the selection. */ + onSelectionChange?: (selection: BarSelection | null) => void; + /** Called on click, Enter or Space. Makes the interaction surface a button. */ + onActivate?: (active: ActiveBar) => void; + /** Names a category in announcements. Default: the category key */ + formatCategory?: (category: string) => string | null; +} + +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 BarChartInteractionProps = Readonly<{ + role: 'button' | 'group'; + /** 0 while something reads the selection: `selection`, `onSelectionChange` or `onActivate`. */ + tabIndex: 0 | undefined; + 'data-active-section': BarSection | undefined; + onPointerDown: React.PointerEventHandler; + onPointerLeave: React.PointerEventHandler; + onPointerCancel: React.PointerEventHandler; + onPointerMove: React.PointerEventHandler; + onFocus: React.FocusEventHandler; + onBlur: React.FocusEventHandler; + onClick: React.MouseEventHandler; + onKeyDown: React.KeyboardEventHandler; +}>; + +/** The measured layout and selection of one chart, returned by `BarChart.useBarChart`. */ +export type BarChartInstance = StackedBarLayout & + Readonly<{ + /** Measures the chart. `BarChart.Root` attaches it. */ + rootRef: (element: HTMLElement | null) => void; + /** The measured container, zero until the first measurement. */ + size: ChartSize; + xTicks: (options?: XTicksOptions) => XTick[]; + isBarActive: ((bar: BarIdentity) => boolean) | undefined; + /** The selected bar in the current data, or null. */ + selected: ActiveBar | null; + /** The text of the keyboard selection's status announcement. */ + announcement: string; + select: (selection: BarSelection) => void; + clear: () => void; + getInteractionProps: () => BarChartInteractionProps; + }>; + +const formatCategoryKey = (category: string) => category; + +/** Coalesces pointer moves into at most one selection update per frame. */ +function useFramePointerUpdates(layout: unknown) { + const applyRef = React.useRef<(selection: Selected | 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: Selected | null, apply: (selection: Selected | 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 pendingSection = () => pendingRef.current?.section ?? undefined; + return { schedule, cancel, pendingSection }; +} + +/** + * Measures, lays out and selects a stacked bar chart. Pass the result to `BarChart.Root`, or render + * from it directly. + */ +export function useBarChart(options: UseBarChartOptions): BarChartInstance { + const { + data, + series, + index, + categoryGap = 0.28, + margin, + projection, + isBarActive, + onActivate, + formatCategory = formatCategoryKey, + } = options; + + 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; + // 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: { top, right, bottom, left }, + categoryGap, + projection: + projectionIndex === undefined || projectionValue === undefined + ? undefined + : { datumIndex: projectionIndex, value: projectionValue }, + }), + [bottom, categoryGap, left, prepared, projectionIndex, projectionValue, right, size, top], + ); + const { categories, plot } = layout; + const xTicks = React.useCallback( + ({ mode = 'category', format = formatCategoryKey }: XTicksOptions = {}) => + selectXTicks({ + categories, + plot, + viewportWidth: size.width, + xAxis: mode === 'calendar' ? 'calendar' : undefined, + formatXTick: format, + }), + [categories, plot, size.width], + ); + + const [value, setValue] = useControllableState( + options.selection, + 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; + // A selection whose category or section left the data reads as none until the user moves. + const valid = current && currentCategory && isSelectable(current, currentCategory) ? current : null; + const selected = getActiveBar(valid, data, categoryByKey); + const announcement = getKeyboardAnnouncement(valid, currentCategory, formatCategory); + + 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 = toBarSelection(next); + if (!sameSelection(toBarSelection(previous), nextValue)) { + setValue(nextValue); + } + return next; + }; + const dispatchRef = React.useRef(dispatch); + React.useLayoutEffect(() => { + dispatchRef.current = dispatch; + }); + const select = React.useCallback((selection: BarSelection) => { + dispatchRef.current({ type: 'select', selection }); + }, []); + const clear = React.useCallback(() => { + dispatchRef.current({ type: 'clear' }); + }, []); + + // Only a pointer event on the surface makes a pointer selection, so its target is the surface. + const surfaceRef = React.useRef(null); + + // 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 instanceof Node) || !surface.contains(event.target)) { + clear(); + } + }; + document.addEventListener('pointerdown', dismissOutside, true); + return () => document.removeEventListener('pointerdown', dismissOutside, true); + }, [clear, hasPointerSelection]); + + const pointerSelection = (clientX: number, clientY: number) => { + const bounds = rootElementRef.current?.getBoundingClientRect(); + const local = + bounds && bounds.width > 0 && bounds.height > 0 + ? { + x: ((clientX - bounds.left) / bounds.width) * size.width, + y: ((clientY - bounds.top) / bounds.height) * size.height, + } + : { x: 0, y: layout.zeroY }; + return hitTest(layout, local, pointerUpdates.pendingSection() ?? valid?.section ?? undefined); + }; + + const selectKeyboardIndex = (target: number, section?: BarSection) => + dispatch({ + type: 'keyboard', + category: categories[Math.max(0, Math.min(categories.length - 1, target))], + section, + }); + + const activate = (selection: Selected | null) => { + const bar = getActiveBar(selection, data, categoryByKey); + if (bar) { + onActivate?.(bar); + } + }; + + const activateKeyboardSelection = (section: BarSection | undefined) => { + const dismissed = stateRef.current.status === 'dismissed'; + const next = selectKeyboardIndex(keyboardIndex(), section); + if (!dismissed) { + activate(selectedState(next)); + } + }; + + const activeSection = valid?.section ?? undefined; + const reads = options.selection !== undefined || !!options.onSelectionChange || !!onActivate; + const getInteractionProps = (): BarChartInteractionProps => ({ + role: onActivate ? 'button' : 'group', + tabIndex: reads ? 0 : undefined, + 'data-active-section': activeSection, + onPointerDown: event => { + event.preventDefault(); + surfaceRef.current = event.currentTarget; + // 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 => { + surfaceRef.current = event.currentTarget; + pointerUpdates.schedule(pointerSelection(event.clientX, event.clientY), next => + dispatch({ type: 'pointer', selection: next }), + ); + }, + onFocus: () => { + selectKeyboardIndex(keyboardIndex()); + }, + 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(activeSection); + return; + } + activate(pointerSelection(event.clientX, event.clientY)); + }, + onKeyDown: event => { + const intent = getKeyIntent(event.key, keyboardIndex(), categories.length - 1, activeSection, !!onActivate); + if (!intent) { + return; + } + event.preventDefault(); + if (intent.type === 'dismiss') { + dispatch({ type: 'dismiss' }); + } else if (intent.activate) { + activateKeyboardSelection(intent.section); + } else { + selectKeyboardIndex(intent.index, intent.section); + } + }, + }); + + return { + ...layout, + rootRef, + size, + xTicks, + isBarActive, + selected, + announcement, + select, + clear, + getInteractionProps, + }; +} diff --git a/packages/mosaic/src/primitives/bar-chart/use-stacked-bar-layout.ts b/packages/mosaic/src/primitives/bar-chart/use-stacked-bar-layout.ts deleted file mode 100644 index b4d59e82cab..00000000000 --- a/packages/mosaic/src/primitives/bar-chart/use-stacked-bar-layout.ts +++ /dev/null @@ -1,44 +0,0 @@ -'use client'; - -import { useMemo } from 'react'; - -import { prepareStackedBars, projectStackedBars, type StackedBarLayout } from './bar-chart-layout'; -import type { BarProjection, BarSeries, ChartFrame } from './types'; - -export interface StackedBarLayoutOptions { - data: readonly TDatum[]; - series: readonly BarSeries[]; - /** Returns a unique, stable category key. */ - 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; -} - -/** Prepared rows and a function that projects them into a measured frame. */ -export interface StackedBarLayoutSource { - data: readonly TDatum[]; - project: (frame: ChartFrame) => StackedBarLayout; -} - -/** - * Prepares stacked bar data for `BarChart.Root`. Preparation reruns when `data`, `series` or `index` - * change, so memoize `series` and `index`. - */ -export function useStackedBarLayout({ - data, - series, - index, - categoryGap = 0.28, - projection, -}: StackedBarLayoutOptions): StackedBarLayoutSource { - const prepared = useMemo(() => prepareStackedBars({ data, series, index }), [data, index, series]); - return useMemo( - () => ({ - data, - project: (frame: ChartFrame) => projectStackedBars(prepared, { ...frame, categoryGap, projection }), - }), - [categoryGap, data, prepared, projection], - ); -} From 73a8dce4df420438be6d3188c1a7cb72856ad5f6 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Sun, 22 Nov 2026 21:18:35 -0700 Subject: [PATCH 09/40] docs(mosaic): document BarChart.useBarChart, its chart object and controlled selection --- .../mosaic/src/primitives/bar-chart/README.md | 167 ++++++++++++------ 1 file changed, 112 insertions(+), 55 deletions(-) diff --git a/packages/mosaic/src/primitives/bar-chart/README.md b/packages/mosaic/src/primitives/bar-chart/README.md index 8a0f2e8dbe4..eda71496f38 100644 --- a/packages/mosaic/src/primitives/bar-chart/README.md +++ b/packages/mosaic/src/primitives/bar-chart/README.md @@ -1,6 +1,6 @@ # Bar chart -A headless stacked bar chart built from composable parts. D3 computes the diverging stacks and scales, Canvas paints the bars and the projection fill, one SVG over the Canvas draws the grid, axes, zero line and projection outline, and React handles interaction. The parts emit no visual styles: style each one with `className` and `data-*` attributes. +A headless stacked bar chart: a hook that owns the layout and selection, and composable parts that render from it. D3 computes the diverging stacks and scales, Canvas paints the bars and the projection fill, one SVG over the Canvas draws the grid, axes, zero line and projection outline, and React handles interaction. The parts emit no visual styles: style each one with `className` and `data-*` attributes. ## When to use @@ -13,10 +13,10 @@ A headless stacked bar chart built from composable parts. D3 computes the diverg ```tsx import { BarChart } from '@clerk/mosaic/primitives/bar-chart'; -const layout = BarChart.useStackedBarLayout({ data, series, index }); +const chart = BarChart.useBarChart({ data, series, index, onActivate: openPeriod }); @@ -31,7 +31,7 @@ const layout = BarChart.useStackedBarLayout({ data, series, index }); )) } - + @@ -58,62 +58,89 @@ const layout = BarChart.useStackedBarLayout({ data, series, index }); )) } - + {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` and `index`, or define them at module level. +`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. A container renders only the items its children function returns. A bare `` renders an empty SVG. ## Parts -| Part | Default element | Description | -| ---------------------------- | --------------- | ------------------------------------------------------------------- | -| `BarChart.Root` | `
` | Measures the container and provides the layout to the other parts | -| `BarChart.Grid` | `` | Holds the grid lines | -| `BarChart.GridLine` | `` | One line across the plot at a Y tick | -| `BarChart.StackedBars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | -| `BarChart.Bar` | `` | Hidden. Its computed style paints the bars | -| `BarChart.ProjectionOutline` | `` | Outlines the projected bar | -| `BarChart.ZeroLine` | `` | The line at zero | -| `BarChart.YAxis` | `` | Holds the Y tick labels in the left margin | -| `BarChart.YTick` | `` | One Y tick label | -| `BarChart.XAxis` | `` | Holds the category labels below the plot | -| `BarChart.XTick` | `` | One category label | -| `BarChart.BarSelection` | `
` | Pointer and keyboard selection over the whole chart | -| `BarChart.Cursor` | `
` | Covers the selected category's band | -| `BarChart.Tooltip` | `
` | The tooltip for the selected bar, portaled | +| Part | Default element | Description | +| ---------------------------- | --------------- | -------------------------------------------------------------------- | +| `BarChart.Root` | `
` | Attaches the chart's measurement and provides the chart to the parts | +| `BarChart.Grid` | `` | Holds the grid lines | +| `BarChart.GridLine` | `` | One line across the plot at a Y tick | +| `BarChart.StackedBars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | +| `BarChart.Bar` | `` | Hidden. Its computed style paints the bars | +| `BarChart.ProjectionOutline` | `` | Outlines the projected bar | +| `BarChart.ZeroLine` | `` | The line at zero | +| `BarChart.YAxis` | `` | Holds the Y tick labels in the left margin | +| `BarChart.YTick` | `` | One Y tick label | +| `BarChart.XAxis` | `` | Holds the category labels below the plot | +| `BarChart.XTick` | `` | One category label | +| `BarChart.BarSelection` | `
` | Pointer and keyboard selection over the whole chart | +| `BarChart.Cursor` | `
` | Covers the selected category's band | +| `BarChart.Tooltip` | `
` | The tooltip for the selected bar, 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 `BarChart.Root`. `BarChart.Bar`, `BarChart.ProjectionOutline` and `BarChart.ZeroLine` live inside `BarChart.StackedBars`, and `BarChart.Bar` and `BarChart.ProjectionOutline` throw outside it. `BarChart.Cursor` and `BarChart.Tooltip` throw outside `BarChart.BarSelection`. -The namespace also holds `BarChart.useStackedBarLayout` and `BarChart.CanvasRenderError`. +The namespace also holds `BarChart.useBarChart` and `BarChart.CanvasRenderError`. ## Props -### `BarChart.useStackedBarLayout` - -| 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 | -| `projection` | `{ datumIndex: number; value: number }` | — | A projected total, drawn when it rises above its category's stack | +### `BarChart.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` | `{ datumIndex: number; value: number }` | — | A projected total, drawn when it rises above its category's stack | +| `isBarActive` | `(bar: BarIdentity) => boolean` | every bar | Returns false for a bar that `BarChart.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 | +| `onActivate` | `(active: ActiveBar) => void` | — | Called on click, Enter or Space. Makes the surface a button | +| `formatCategory` | `(key: string) => string \| null` | the key | Names a period in keyboard announcements | + +`BarSelection` is `{ category, section }`. A new `isBarActive` function repaints the Canvas. + +The hook returns a `BarChartInstance`, the chart object: + +| Field | Type | Description | +| ----------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------- | +| `rootRef` | `(element: HTMLElement \| null) => void` | Measures the element. `BarChart.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` | Maps a value to a Y coordinate | +| `zeroY` | `number` | The Y coordinate of zero | +| `categories` | `readonly BarCategory[]` | One band per row, with its selectable sections | +| `yTicks` | `readonly ChartTick[]` | The Y ticks | +| `xTicks` | `(options?: { mode?, format? }) => XTick[]` | The X labels for a tick mode, as `BarChart.XAxis` computes them | +| `projection` | `{ datumIndex, x, y, width, height } \| null` | The accepted projection's band rectangle | +| `selected` | `ActiveBar \| null` | The selected bar in the current data | +| `announcement` | `string` | The status text for the keyboard selection | +| `select`, `clear` | `(selection: BarSelection) => void`, `() => void` | Change the selection and call `onSelectionChange` | +| `getInteractionProps()` | `BarChartInteractionProps` | Role, `tabIndex`, `data-active-section` and the pointer, focus and key handlers | + +The object also carries `isBarActive` and the layout internals `prepared` and `step`. ### `BarChart.Root` -| Prop | Type | Default | Description | -| ------------ | ------------------------ | --------------- | ------------------------------------------------------------- | -| `layout` | `StackedBarLayoutSource` | (required) | The result of `BarChart.useStackedBarLayout` | -| `aria-label` | `string` | (required) | Labels the bars image and the interaction surface | -| `height` | `number \| string` | `500` | The container height | -| `margin` | `Partial` | `8, 16, 36, 52` | Space around the plot for the axes (top, right, bottom, left) | +| Prop | Type | Default | Description | +| ------------ | -------------------------- | ---------- | ------------------------------------------------- | +| `chart` | `BarChartInstance` | (required) | The result of `BarChart.useBarChart` | +| `aria-label` | `string` | (required) | Labels the bars image and the interaction surface | +| `height` | `number \| string` | `500` | The container height | ### `BarChart.Grid`, `BarChart.YAxis`, `BarChart.XAxis` @@ -128,21 +155,7 @@ The namespace also holds `BarChart.useStackedBarLayout` and `BarChart.CanvasRend `BarChart.GridLine`, `BarChart.YTick` and `BarChart.XTick` each take the entry their container passed: `line` (`{ value, y }`) or `tick` (`{ 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. -### `BarChart.StackedBars` - -| Prop | Type | Default | Description | -| ------------- | --------------------------------------- | ---------------- | --------------------------------------------------------------------- | -| `isBarActive` | `(bar: BarIdentity) => boolean` | every bar active | Returns false for a bar that `BarChart.Bar` styles as `data-inactive` | - -A new `isBarActive` function repaints the Canvas, so memoize it. - -### `BarChart.BarSelection` - -| Prop | Type | Default | Description | -| ---------------- | ---------------------------------------- | ------- | ----------------------------------------------------------- | -| `onActiveChange` | `(active: BarSelection \| null) => void` | — | Receives the selected category and section, or null | -| `onActivate` | `(active: ActiveBar) => void` | — | Called on click, Enter or Space. Makes the surface a button | -| `formatCategory` | `(key: string) => string \| null` | the key | Names a period in keyboard announcements | +`BarChart.StackedBars` and `BarChart.BarSelection` take only the props of their element. `isBarActive`, `onActivate` and `formatCategory` are `useBarChart` options. ### `BarChart.Tooltip` @@ -155,7 +168,7 @@ A new `isBarActive` function repaints the Canvas, so memoize it. ## Keyboard -The interaction surface is focusable while `BarChart.BarSelection` has `onActiveChange`, `onActivate` or a `BarChart.Tooltip`. +The interaction surface is focusable while something reads the selection: `selection`, `onSelectionChange` or `onActivate` on `useBarChart`, or a `BarChart.Tooltip`. | Key | Behavior | | ------------------------ | ------------------------------------------------------------------------ | @@ -169,6 +182,50 @@ Left and Right do not follow `useDirection()`. A time axis reads left to right i A pointer selects the period under it. A tap selects on contact and stays selected until the user taps elsewhere or the gesture is cancelled. +## Selection + +The chart holds the selection unless you pass `selection`. `onSelectionChange` is called with `{ category, section }` or null whenever a pointer move, a key, a focus change, `select` or `clear` changes it, in both modes. It is not called when data changes: `chart.selected` resolves the selection against the current data, so a selection whose category or section disappears reads as null until the user moves. + +A controlled `selection` decides which bar 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. + +```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 = BarChart.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, 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 = BarChart.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 object does not do, because their color and geometry come from `BarChart.Bar`'s computed style: keep `BarChart.StackedBars` for that. + ## Data attributes | Attribute | Part | Description | @@ -260,7 +317,7 @@ Each container renders nothing until Root has measured a non-zero size. ## Layout -`useStackedBarLayout` prepares the stacks when `data`, `series` or `index` change. Root measures its container, then projects the layout for each size or layout change. `BarChart.StackedBars` projects the bar marks when the layout or the bar geometry changes. The container size is committed before paint, so the chart follows its container while resizing. +`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. `BarChart.StackedBars` projects the bar marks when the layout or the bar geometry changes. The container size is committed 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. From 734102ac08b26c71f57b3722a459cdaef34a4cfc Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Sun, 22 Nov 2026 21:18:37 -0700 Subject: [PATCH 10/40] docs(swingset): move the BarChart page to useBarChart --- packages/swingset/src/stories/bar-chart.mdx | 113 +++++++++--------- .../src/stories/bar-chart.stories.tsx | 6 +- 2 files changed, 57 insertions(+), 62 deletions(-) diff --git a/packages/swingset/src/stories/bar-chart.mdx b/packages/swingset/src/stories/bar-chart.mdx index a435f990bb0..9164e2b33a2 100644 --- a/packages/swingset/src/stories/bar-chart.mdx +++ b/packages/swingset/src/stories/bar-chart.mdx @@ -3,7 +3,8 @@ import * as BarChartStories from './bar-chart.stories'; # BarChart A stacked bar chart over a category or time axis, with values above and below zero. It is a -**headless** primitive: D3 computes the stacks and scales, Canvas paints the bars, SVG draws the +**headless** primitive: `BarChart.useBarChart` owns the layout and selection, and the parts render +from the chart object it 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. @@ -22,10 +23,10 @@ unstyled, so the bars take the inherited text color and the grid and zero lines ```tsx import { BarChart } from '@clerk/mosaic/primitives/bar-chart'; -const layout = BarChart.useStackedBarLayout({ data, series, index }); +const chart = BarChart.useBarChart({ data, series, index, onActivate: openPeriod }); @@ -39,7 +40,7 @@ const layout = BarChart.useStackedBarLayout({ data, series, index }); )) } - + @@ -64,7 +65,7 @@ const layout = BarChart.useStackedBarLayout({ data, series, index }); )) } - + {active => } @@ -76,18 +77,17 @@ returns each row's unique category key. Memoize `series`, `index` and `isBarActi ### Dimming bars -`isBarActive` marks every other bar `data-inactive`, so CSS can dim it. This keeps one week's -positive section at full color: +`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) => bar.datum.week === selectedWeek && bar.positive, - [selectedWeek], + (bar: BarIdentity) => + !selection || (bar.datum.week === selection.category && bar.positive === (selection.section === 'positive')), + [selection], ); - - - -; +const chart = BarChart.useBarChart({ data, series, index, selection, onSelectionChange: setSelection, isBarActive }); ``` ### Projection @@ -97,7 +97,7 @@ with `BarChart.Bar`'s `data-projection` color, and `BarChart.ProjectionOutline` It is drawn only when `value` is above that category's stack. ```tsx -const layout = BarChart.useStackedBarLayout({ +const chart = BarChart.useBarChart({ data, series, index, @@ -107,22 +107,22 @@ const layout = BarChart.useStackedBarLayout({ ## Parts -| Part | Default Element | Description | -| ---------------------------- | --------------- | ------------------------------------------------------------------- | -| `BarChart.Root` | `
` | Measures the container and provides the layout | -| `BarChart.Grid` | `` | Holds the grid lines | -| `BarChart.GridLine` | `` | One line across the plot at a Y tick | -| `BarChart.StackedBars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | -| `BarChart.Bar` | `` | Hidden. Its computed style paints the bars | -| `BarChart.ProjectionOutline` | `` | Outlines the projected bar | -| `BarChart.ZeroLine` | `` | The line at zero | -| `BarChart.YAxis` | `` | Holds the Y tick labels | -| `BarChart.YTick` | `` | One Y tick label | -| `BarChart.XAxis` | `` | Holds the category labels | -| `BarChart.XTick` | `` | One category label | -| `BarChart.BarSelection` | `
` | Pointer and keyboard selection | -| `BarChart.Cursor` | `
` | Covers the selected category's band | -| `BarChart.Tooltip` | `
` | The tooltip for the selected bar, portaled | +| Part | Default Element | Description | +| ---------------------------- | --------------- | -------------------------------------------------------------------- | +| `BarChart.Root` | `
` | Attaches the chart's measurement and provides the chart to the parts | +| `BarChart.Grid` | `` | Holds the grid lines | +| `BarChart.GridLine` | `` | One line across the plot at a Y tick | +| `BarChart.StackedBars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | +| `BarChart.Bar` | `` | Hidden. Its computed style paints the bars | +| `BarChart.ProjectionOutline` | `` | Outlines the projected bar | +| `BarChart.ZeroLine` | `` | The line at zero | +| `BarChart.YAxis` | `` | Holds the Y tick labels | +| `BarChart.YTick` | `` | One Y tick label | +| `BarChart.XAxis` | `` | Holds the category labels | +| `BarChart.XTick` | `` | One category label | +| `BarChart.BarSelection` | `
` | Pointer and keyboard selection | +| `BarChart.Cursor` | `
` | Covers the selected category's band | +| `BarChart.Tooltip` | `
` | The tooltip for the selected bar, portaled | Every part accepts a `render` prop and the standard attributes of its default element. Every part throws outside `BarChart.Root`. `BarChart.Bar` and `BarChart.ProjectionOutline` throw outside @@ -131,30 +131,33 @@ throws outside `BarChart.Root`. `BarChart.Bar` and `BarChart.ProjectionOutline` ## Props -### `BarChart.useStackedBarLayout` - -| 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 | -| projection | { datumIndex: number; value: number } | — | A projected total, drawn when it rises above its stack | +### `BarChart.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`, `zeroY`, `categories`, +`yTicks`, `xTicks(options)`, `projection`, `selected`, `announcement`, `select`, `clear` and +`getInteractionProps()`. Render from it directly to skip the parts. ### `BarChart.Root` -| Prop | Type | Default | Description | -| ----------------------- | --------------------------------------- | -------------------------- | ------------------------------------------------- | -| layout | StackedBarLayoutSource | — (required) | The result of `BarChart.useStackedBarLayout` | -| aria-label | string | — (required) | Labels the bars image and the interaction surface | -| height | number \| string | 500 | The container height | -| margin | Partial<ChartMargin> | 8, 16, 36, 52 | Space for the axes: top, right, bottom, left | - -### `BarChart.StackedBars` - -| Prop | Type | Default | Description | -| ------------------------ | -------------------------------------------------------- | ---------------- | ------------------------------------------------------ | -| isBarActive | (bar: BarIdentity<TDatum>) => boolean | every bar active | Returns false for a bar styled through `data-inactive` | +| Prop | Type | Default | Description | +| ----------------------- | ------------------------------------------- | ---------------- | ------------------------------------------------- | +| chart | BarChartInstance<TDatum> | — (required) | The result of `BarChart.useBarChart` | +| aria-label | string | — (required) | Labels the bars image and the interaction surface | +| height | number \| string | 500 | The container height | ### `BarChart.XAxis` @@ -168,14 +171,6 @@ throws outside `BarChart.Root`. `BarChart.Bar` and `BarChart.ProjectionOutline` their items. `BarChart.GridLine` takes `line`, and `BarChart.YTick` and `BarChart.XTick` take `tick`. -### `BarChart.BarSelection` - -| Prop | Type | Default | Description | -| --------------------------- | ------------------------------------------------------ | ------- | --------------------------------------------------- | -| onActiveChange | (active: BarSelection \| null) => void | — | Receives the selected category and section, or null | -| onActivate | (active: ActiveBar<TDatum>) => void | — | Called on click, Enter or Space | -| formatCategory | (key: string) => string \| null | the key | Names a period in keyboard announcements | - ### `BarChart.Tooltip` | Prop | Type | Default | Description | diff --git a/packages/swingset/src/stories/bar-chart.stories.tsx b/packages/swingset/src/stories/bar-chart.stories.tsx index ab4b904e790..39fcc6b2cdd 100644 --- a/packages/swingset/src/stories/bar-chart.stories.tsx +++ b/packages/swingset/src/stories/bar-chart.stories.tsx @@ -32,10 +32,10 @@ const series = [ const getWeek = (row: GrowthRow) => row.week; export function Default() { - const layout = BarChart.useStackedBarLayout({ data: growth, series, index: getWeek }); + const chart = BarChart.useBarChart({ data: growth, series, index: getWeek }); return ( - > + > {({ datum }) => ( From cfab5b7234f99c891ba6e29dc6ebaf91c1ef80dc Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 07:26:01 -0700 Subject: [PATCH 11/40] refactor(mosaic): run bar chart selection through a generic engine and a bar SelectionModel The reducer, controlled reconcile, pointer coalescing, keyboard, activation and announcements now live in useChartInstance, generic over the selection type. The bar section rules (hit test near the zero line, Up and Down, resolving a section) move into barSelectionModel. The pointer snaps to the nearest category center instead of dividing by the band step. --- .../__tests__/bar-chart-layout.test.ts | 3 +- .../bar-chart/bar-chart-bar-selection.tsx | 10 +- .../primitives/bar-chart/bar-chart-layout.ts | 10 +- .../bar-chart/bar-chart-selection.ts | 235 +++-------- .../bar-chart/bar-chart-tooltip.tsx | 13 +- .../primitives/bar-chart/chart-selection.ts | 192 +++++++++ .../mosaic/src/primitives/bar-chart/types.ts | 39 +- .../src/primitives/bar-chart/use-bar-chart.ts | 364 +---------------- .../bar-chart/use-chart-instance.ts | 374 ++++++++++++++++++ 9 files changed, 670 insertions(+), 570 deletions(-) create mode 100644 packages/mosaic/src/primitives/bar-chart/chart-selection.ts create mode 100644 packages/mosaic/src/primitives/bar-chart/use-chart-instance.ts diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts index 90acee62f81..efcfae52086 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts @@ -1,7 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { DEFAULT_CHART_MARGIN, prepareStackedBars, projectStackedBars } from '../bar-chart-layout'; +import { prepareStackedBars, projectStackedBars } from '../bar-chart-layout'; import type { BarProjection } from '../types'; +import { DEFAULT_CHART_MARGIN } from '../use-chart-instance'; interface TypedRow { start: string; diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx index 4c38495d9b0..825bf028ab5 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx @@ -22,18 +22,16 @@ export type BarChartBarSelectionProps = ComponentProps<'div'>; function KeyboardInstructions({ id, - canActivate, + instructions, announcement, -}: Readonly<{ id: string; canActivate: boolean; announcement: string }>) { +}: Readonly<{ id: string; instructions: string; announcement: string }>) { return ( <> - Use Left and Right to choose a period, or Home and End to jump to the first or last. Use Up and Down to choose - positive or negative values. {canActivate ? 'Press Enter or Space to open the selected period. ' : ''} - Press Escape to dismiss. + {instructions} diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts index ce5a60c61f8..b3b1459a315 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts @@ -5,13 +5,6 @@ import type { BarCategory, BarMark, BarProjection, BarSeries, ChartFrame, ChartM const Y_TICK_COUNT = 5; -export const DEFAULT_CHART_MARGIN: ChartMargin = { - top: 8, - right: 16, - bottom: 36, - left: 52, -}; - type PrepareOptions = Readonly<{ data: readonly TDatum[]; series: readonly BarSeries[]; @@ -350,7 +343,8 @@ export function projectStackedBars( export type StackedBarLayout = ReturnType>; -type MarkSource = Pick, 'prepared' | 'categories' | 'scaleY'>; +type MarkSource = Pick, 'prepared' | 'scaleY'> & + Readonly<{ categories: readonly BarCategory[] }>; export function projectStackedBarMarks(layout: MarkSource, geometry: BarGeometry): BarMark[] { return applyCornerRadii(projectMarksAndPaintInsets(layout, geometry), geometry); diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts index 47f33942e3d..d3186bcbbbf 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts @@ -1,194 +1,59 @@ import type { StackedBarLayout } from './bar-chart-layout'; +import type { SelectionModel } from './chart-selection'; import type { ActiveBar, BarCategory, BarSection, BarSelection } from './types'; -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. */ - section: BarSection | 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: Selected | null }> - | Readonly<{ type: 'keyboard'; category: BarCategory | undefined; section?: BarSection }> - | Readonly<{ type: 'select'; selection: BarSelection }> - | Readonly<{ type: 'clear' }> - | Readonly<{ type: 'dismiss' }>; - -export const NO_SELECTION: SelectionState = { status: 'none' }; - -export function selectionReducer(state: SelectionState, action: SelectionAction): SelectionState { - switch (action.type) { - case 'pointer': - return action.selection ?? NO_SELECTION; - case 'select': - return { status: 'selected', source: 'external', ...action.selection }; - case 'clear': - return state.status === 'dismissed' ? state : NO_SELECTION; - case 'dismiss': - return { status: 'dismissed' }; - case 'keyboard': { - const { category, section } = action; - if (!category) { - return NO_SELECTION; +/** Selects a section of a stacked bar: above the zero line or below it. */ +export function barSelectionModel( + layout: Pick, 'plot' | 'zeroY'>, + data: readonly TDatum[], +): SelectionModel, BarCategory> { + return { + hitTest: (category, y, current) => { + const { positive, negative } = category.sections; + if (!positive && !negative) { + return null; + } + const nearZero = Math.abs(y - layout.zeroY) <= Math.max(4, Math.round(layout.plot.height * 0.015)); + const section: BarSection = !negative + ? 'positive' + : !positive + ? 'negative' + : 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 { - status: 'selected', - source: 'keyboard', category: category.key, - section: - section && category.sections[section] - ? section - : category.sections.positive - ? 'positive' - : category.sections.negative - ? 'negative' - : null, + section: selection.section, + datumIndex: category.datumIndex, + datum, + hasValues: category.hasValues, + projected: category.projected, }; - } - } -} - -export function hitTest( - layout: StackedBarLayout, - local: Readonly<{ x: number; y: number }>, - stickySection: BarSection | undefined, -): Selected | null { - const first = layout.categories[0]; - if (!first) { - return null; - } - const datumIndex = Math.max( - 0, - Math.min(layout.categories.length - 1, Math.round((local.x - first.center) / layout.step)), - ); - const category = layout.categories[datumIndex]; - if (!category) { - return null; - } - const { positive, negative } = category.sections; - if (!positive && !negative) { - return null; - } - const nearZero = Math.abs(local.y - layout.zeroY) <= Math.max(4, Math.round(layout.plot.height * 0.015)); - const section: BarSection = !negative - ? 'positive' - : !positive - ? 'negative' - : nearZero - ? (stickySection ?? 'positive') - : local.y < layout.zeroY - ? 'positive' - : 'negative'; - return { status: 'selected', source: 'pointer', category: category.key, section }; -} - -export function selectedState(state: SelectionState): Selected | null { - return state.status === 'selected' ? state : null; -} - -export function isSelectable(selection: Selected, category: BarCategory) { - return selection.section === null || category.sections[selection.section]; -} - -/** The public value of a selection state: the selected category and section, or null. */ -export function toBarSelection(state: SelectionState): BarSelection | null { - return state.status === 'selected' && state.section ? { category: state.category, section: state.section } : null; -} - -export function sameSelection(a: BarSelection | null, b: BarSelection | null) { - return a?.category === b?.category && a?.section === b?.section; -} - -/** - * 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: BarSelection | null): SelectionState { - if (sameSelection(toBarSelection(state), value)) { - return state; - } - return value ? { status: 'selected', source: 'external', ...value } : NO_SELECTION; -} - -export function getActiveBar( - selection: Selected | null, - data: readonly TDatum[], - categoryByKey: ReadonlyMap, -): ActiveBar | null { - const category = selection ? categoryByKey.get(selection.category) : undefined; - if (!selection?.section || !category?.sections[selection.section]) { - return null; - } - const datum = data[category.datumIndex]; - if (datum === undefined) { - return null; - } - return { - category: category.key, - section: selection.section, - datumIndex: category.datumIndex, - datum, - hasValues: category.hasValues, - projected: category.projected, + }, + describe: selection => `${selection.section} values`, + verticalInstructions: 'Use Up and Down to choose positive or negative values.', + anchorY: () => layout.plot.y, + surfaceAttributes: selection => ({ 'data-active-section': selection?.section }), }; } - -export type KeyIntent = - | Readonly<{ type: 'dismiss' }> - | Readonly<{ type: 'select'; index: number; section: BarSection | undefined; activate: boolean }>; - -export function getKeyIntent( - key: string, - index: number, - lastIndex: number, - section: BarSection | undefined, - canActivate: boolean, -): KeyIntent | null { - switch (key) { - case 'Escape': - return { type: 'dismiss' }; - case 'ArrowUp': - return { type: 'select', index, section: 'positive', activate: false }; - case 'ArrowDown': - return { type: 'select', index, section: 'negative', activate: false }; - case 'ArrowLeft': - return { type: 'select', index: index - 1, section, activate: false }; - case 'ArrowRight': - return { type: 'select', index: index + 1, section, activate: false }; - case 'Home': - return { type: 'select', index: 0, section, activate: false }; - case 'End': - return { type: 'select', index: lastIndex, section, activate: false }; - case 'Enter': - case ' ': - return canActivate ? { type: 'select', index, section, activate: true } : null; - default: - return null; - } -} - -export function getKeyboardAnnouncement( - selection: Selected | null, - category: BarCategory | undefined, - formatCategory: (category: string) => string | null, -) { - if (selection?.source !== 'keyboard') { - return ''; - } - if (selection.section) { - const label = formatCategory(selection.category) ?? selection.category; - return `${label}, ${selection.section} values`; - } - const hasValues = !!category && (category.sections.positive || category.sections.negative); - return hasValues ? '' : 'No values for this period'; -} diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx index 8819336c786..00d780fe3bf 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx @@ -51,12 +51,13 @@ export const BarChartTooltip = React.forwardRef(null); @@ -89,7 +90,7 @@ export const BarChartTooltip = React.forwardRef { const chart = chartBoxRef.current; - if (anchorX === undefined || !chart || chartWidth <= 0) { + if (anchorX === undefined || anchorY === undefined || !chart || chartWidth <= 0) { return; } const getBoundingClientRect = () => { @@ -99,10 +100,10 @@ export const BarChartTooltip = React.forwardRef = Readonly<{ + /** The selection under a pointer at plot-space `y` over `category`. `current` lets a model hold its pick near a boundary. */ + hitTest: (category: TCategory, y: number, 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, such as `positive values`. */ + describe: (selection: TSelection) => string; + /** The sentence about Up and Down in the keyboard instructions. */ + verticalInstructions: string; + /** Where a tooltip points on the Y axis, in chart coordinates. */ + anchorY: (selection: TSelection, category: TCategory) => number; + /** 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( + selected: Selected | null, + category: TCategory | undefined, + model: Pick, 'describe' | 'land'>, + formatCategory: (category: string) => string | null, +) { + if (selected?.source !== 'keyboard') { + return ''; + } + if (selected.selection) { + const label = formatCategory(selected.category) ?? selected.category; + return `${label}, ${model.describe(selected.selection)}`; + } + const hasValues = !!category && model.land(category, undefined, null) !== null; + return hasValues ? '' : 'No values for this period'; +} + +export function getKeyboardInstructions(verticalInstructions: string, canActivate: boolean) { + return [ + 'Use Left and Right to choose a period, or Home and End to jump to the first or last.', + verticalInstructions, + canActivate ? 'Press Enter or Space to open the selected period.' : '', + 'Press Escape to dismiss.', + ] + .filter(Boolean) + .join(' '); +} diff --git a/packages/mosaic/src/primitives/bar-chart/types.ts b/packages/mosaic/src/primitives/bar-chart/types.ts index 1b0ed10a6af..3b5ab2f5756 100644 --- a/packages/mosaic/src/primitives/bar-chart/types.ts +++ b/packages/mosaic/src/primitives/bar-chart/types.ts @@ -19,6 +19,16 @@ export type ChartPlot = Readonly<{ export type ChartTick = Readonly<{ value: number; y: number }>; +/** One datum's place on the X axis. */ +export type ChartCategory = Readonly<{ + key: string; + datumIndex: number; + center: number; +}>; + +/** What a selection names. Each chart type extends it with what else a user can pick there. */ +export type ChartSelection = Readonly<{ category: string }>; + export type CornerRadii = readonly [number, number, number, number]; /** A projected total for one category, drawn only above its positive stack. */ @@ -53,25 +63,20 @@ export type BarMark = BarIdentity & export type BarSection = 'positive' | 'negative'; -export type BarCategory = Readonly<{ - key: string; - datumIndex: number; - bandX: number; - bandWidth: number; - center: number; - /** 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; -}>; +export type BarCategory = ChartCategory & + Readonly<{ + bandX: number; + bandWidth: number; + /** 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 = Readonly<{ - category: string; - section: BarSection; -}>; +export type BarSelection = ChartSelection & Readonly<{ section: BarSection }>; /** A selected bar resolved against the current data. */ export type ActiveBar = BarSelection & diff --git a/packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts b/packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts index f6a8f1c839a..7b9d6834685 100644 --- a/packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts +++ b/packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts @@ -2,43 +2,14 @@ import React from 'react'; -import { useControllableState } from '../hooks/use-controllable-state'; -import { - DEFAULT_CHART_MARGIN, - prepareStackedBars, - projectStackedBars, - type StackedBarLayout, -} from './bar-chart-layout'; -import { - getActiveBar, - getKeyboardAnnouncement, - getKeyIntent, - hitTest, - isSelectable, - NO_SELECTION, - reconcileSelection, - sameSelection, - type Selected, - selectedState, - type SelectionAction, - selectionReducer, - type SelectionState, - toBarSelection, -} from './bar-chart-selection'; -import type { - ActiveBar, - BarIdentity, - BarProjection, - BarSection, - BarSelection, - BarSeries, - ChartMargin, - ChartSize, -} from './types'; -import { useChartSize } from './use-chart-size'; -import { selectXTicks, type XTick } from './x-ticks'; +import { prepareStackedBars, projectStackedBars, type StackedBarLayout } from './bar-chart-layout'; +import { barSelectionModel } from './bar-chart-selection'; +import type { ActiveBar, BarCategory, BarIdentity, BarProjection, BarSelection, BarSeries } from './types'; +import { type ChartOptions, useChartFrame, useChartInstance } from './use-chart-instance'; -export interface UseBarChartOptions { +export type { ChartInteractionProps as BarChartInteractionProps, XTickMode, XTicksOptions } from './use-chart-instance'; + +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[]; @@ -46,135 +17,28 @@ export interface UseBarChartOptions { index: (datum: TDatum, index: number) => string; /** Fraction of each category band left empty between bars. Default: 0.28 */ categoryGap?: number; - /** Space around the plot for the axes. Default: 8, 16, 36, 52 (top, right, bottom, left) */ - margin?: Partial; /** Paints a projected total behind the bar at `datumIndex`, when it rises above the bar. */ projection?: BarProjection; /** Returns false for a bar that `BarChart.Bar` styles through `data-inactive`. Default: every bar is active */ isBarActive?: (bar: BarIdentity) => boolean; - /** The selected category and section, or null. Leave it undefined to let the chart hold the selection. */ - selection?: BarSelection | null; - /** Called when the user or `select`/`clear` changes the selection. */ - onSelectionChange?: (selection: BarSelection | null) => void; - /** Called on click, Enter or Space. Makes the interaction surface a button. */ - onActivate?: (active: ActiveBar) => void; - /** Names a category in announcements. Default: the category key */ - formatCategory?: (category: string) => string | null; } -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 BarChartInteractionProps = Readonly<{ - role: 'button' | 'group'; - /** 0 while something reads the selection: `selection`, `onSelectionChange` or `onActivate`. */ - tabIndex: 0 | undefined; - 'data-active-section': BarSection | undefined; - onPointerDown: React.PointerEventHandler; - onPointerLeave: React.PointerEventHandler; - onPointerCancel: React.PointerEventHandler; - onPointerMove: React.PointerEventHandler; - onFocus: React.FocusEventHandler; - onBlur: React.FocusEventHandler; - onClick: React.MouseEventHandler; - onKeyDown: React.KeyboardEventHandler; -}>; - /** The measured layout and selection of one chart, returned by `BarChart.useBarChart`. */ -export type BarChartInstance = StackedBarLayout & +export type BarChartInstance = Omit, 'categories' | 'yTicks'> & + ReturnType, BarCategory>> & Readonly<{ - /** Measures the chart. `BarChart.Root` attaches it. */ - rootRef: (element: HTMLElement | null) => void; - /** The measured container, zero until the first measurement. */ - size: ChartSize; - xTicks: (options?: XTicksOptions) => XTick[]; isBarActive: ((bar: BarIdentity) => boolean) | undefined; - /** The selected bar in the current data, or null. */ - selected: ActiveBar | null; - /** The text of the keyboard selection's status announcement. */ - announcement: string; - select: (selection: BarSelection) => void; - clear: () => void; - getInteractionProps: () => BarChartInteractionProps; }>; -const formatCategoryKey = (category: string) => category; - -/** Coalesces pointer moves into at most one selection update per frame. */ -function useFramePointerUpdates(layout: unknown) { - const applyRef = React.useRef<(selection: Selected | 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: Selected | null, apply: (selection: Selected | 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 pendingSection = () => pendingRef.current?.section ?? undefined; - return { schedule, cancel, pendingSection }; -} - /** * Measures, lays out and selects a stacked bar chart. Pass the result to `BarChart.Root`, or render * from it directly. */ export function useBarChart(options: UseBarChartOptions): BarChartInstance { - const { - data, - series, - index, - categoryGap = 0.28, - margin, - projection, - isBarActive, - onActivate, - formatCategory = formatCategoryKey, - } = options; - - const { ref: sizeRef, size } = useChartSize(); - const rootElementRef = React.useRef(null); - const rootRef = React.useCallback( - (element: HTMLElement | null) => { - rootElementRef.current = element; - sizeRef(element); - }, - [sizeRef], - ); + const { data, series, index, categoryGap = 0.28, projection, isBarActive } = options; - 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 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; @@ -183,211 +47,17 @@ export function useBarChart(options: UseBarChartOptions): BarCha () => projectStackedBars(prepared, { size, - margin: { top, right, bottom, left }, + margin, categoryGap, projection: projectionIndex === undefined || projectionValue === undefined ? undefined : { datumIndex: projectionIndex, value: projectionValue }, }), - [bottom, categoryGap, left, prepared, projectionIndex, projectionValue, right, size, top], - ); - const { categories, plot } = layout; - const xTicks = React.useCallback( - ({ mode = 'category', format = formatCategoryKey }: XTicksOptions = {}) => - selectXTicks({ - categories, - plot, - viewportWidth: size.width, - xAxis: mode === 'calendar' ? 'calendar' : undefined, - formatXTick: format, - }), - [categories, plot, size.width], - ); - - const [value, setValue] = useControllableState( - options.selection, - 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], + [categoryGap, margin, prepared, projectionIndex, projectionValue, size], ); - const current = selectedState(state); - const currentCategory = current ? categoryByKey.get(current.category) : undefined; - // A selection whose category or section left the data reads as none until the user moves. - const valid = current && currentCategory && isSelectable(current, currentCategory) ? current : null; - const selected = getActiveBar(valid, data, categoryByKey); - const announcement = getKeyboardAnnouncement(valid, currentCategory, formatCategory); - - 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 = toBarSelection(next); - if (!sameSelection(toBarSelection(previous), nextValue)) { - setValue(nextValue); - } - return next; - }; - const dispatchRef = React.useRef(dispatch); - React.useLayoutEffect(() => { - dispatchRef.current = dispatch; - }); - const select = React.useCallback((selection: BarSelection) => { - dispatchRef.current({ type: 'select', selection }); - }, []); - const clear = React.useCallback(() => { - dispatchRef.current({ type: 'clear' }); - }, []); - - // Only a pointer event on the surface makes a pointer selection, so its target is the surface. - const surfaceRef = React.useRef(null); - - // 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 instanceof Node) || !surface.contains(event.target)) { - clear(); - } - }; - document.addEventListener('pointerdown', dismissOutside, true); - return () => document.removeEventListener('pointerdown', dismissOutside, true); - }, [clear, hasPointerSelection]); - - const pointerSelection = (clientX: number, clientY: number) => { - const bounds = rootElementRef.current?.getBoundingClientRect(); - const local = - bounds && bounds.width > 0 && bounds.height > 0 - ? { - x: ((clientX - bounds.left) / bounds.width) * size.width, - y: ((clientY - bounds.top) / bounds.height) * size.height, - } - : { x: 0, y: layout.zeroY }; - return hitTest(layout, local, pointerUpdates.pendingSection() ?? valid?.section ?? undefined); - }; - - const selectKeyboardIndex = (target: number, section?: BarSection) => - dispatch({ - type: 'keyboard', - category: categories[Math.max(0, Math.min(categories.length - 1, target))], - section, - }); - - const activate = (selection: Selected | null) => { - const bar = getActiveBar(selection, data, categoryByKey); - if (bar) { - onActivate?.(bar); - } - }; - - const activateKeyboardSelection = (section: BarSection | undefined) => { - const dismissed = stateRef.current.status === 'dismissed'; - const next = selectKeyboardIndex(keyboardIndex(), section); - if (!dismissed) { - activate(selectedState(next)); - } - }; - - const activeSection = valid?.section ?? undefined; - const reads = options.selection !== undefined || !!options.onSelectionChange || !!onActivate; - const getInteractionProps = (): BarChartInteractionProps => ({ - role: onActivate ? 'button' : 'group', - tabIndex: reads ? 0 : undefined, - 'data-active-section': activeSection, - onPointerDown: event => { - event.preventDefault(); - surfaceRef.current = event.currentTarget; - // 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 => { - surfaceRef.current = event.currentTarget; - pointerUpdates.schedule(pointerSelection(event.clientX, event.clientY), next => - dispatch({ type: 'pointer', selection: next }), - ); - }, - onFocus: () => { - selectKeyboardIndex(keyboardIndex()); - }, - 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(activeSection); - return; - } - activate(pointerSelection(event.clientX, event.clientY)); - }, - onKeyDown: event => { - const intent = getKeyIntent(event.key, keyboardIndex(), categories.length - 1, activeSection, !!onActivate); - if (!intent) { - return; - } - event.preventDefault(); - if (intent.type === 'dismiss') { - dispatch({ type: 'dismiss' }); - } else if (intent.activate) { - activateKeyboardSelection(intent.section); - } else { - selectKeyboardIndex(intent.index, intent.section); - } - }, - }); + const model = React.useMemo(() => barSelectionModel(layout, data), [data, layout]); + const instance = useChartInstance({ frame, layout, model, options }); - return { - ...layout, - rootRef, - size, - xTicks, - isBarActive, - selected, - announcement, - select, - clear, - getInteractionProps, - }; + return { ...layout, ...instance, isBarActive }; } diff --git a/packages/mosaic/src/primitives/bar-chart/use-chart-instance.ts b/packages/mosaic/src/primitives/bar-chart/use-chart-instance.ts new file mode 100644 index 00000000000..ed11f0b86ca --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/use-chart-instance.ts @@ -0,0 +1,374 @@ +'use client'; + +import React from 'react'; + +import { useControllableState } from '../hooks/use-controllable-state'; +import { + getKeyboardAnnouncement, + getKeyboardInstructions, + getKeyIntent, + nearestCategory, + NO_SELECTION, + reconcileSelection, + sameSelection, + selectedState, + type SelectionAction, + type SelectionModel, + selectionReducer, + type SelectionState, + toPublicSelection, + type VerticalMove, +} from './chart-selection'; +import type { ChartCategory, ChartMargin, ChartPlot, ChartSelection, ChartSize, ChartTick } from './types'; +import { useChartSize } from './use-chart-size'; +import { selectXTicks, type XTick } from './x-ticks'; + +export const DEFAULT_CHART_MARGIN: ChartMargin = { + top: 8, + right: 16, + bottom: 36, + left: 52, +}; + +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 = Readonly<{ + role: 'button' | 'group'; + /** 0 while something reads the selection: `selection`, `onSelectionChange` or `onActivate`. */ + tabIndex: 0 | undefined; + onPointerDown: React.PointerEventHandler; + onPointerLeave: React.PointerEventHandler; + onPointerCancel: React.PointerEventHandler; + onPointerMove: React.PointerEventHandler; + onFocus: React.FocusEventHandler; + onBlur: React.FocusEventHandler; + onClick: React.MouseEventHandler; + onKeyDown: React.KeyboardEventHandler; + /** State the chart type exposes on the surface, such as `data-active-section`. */ + [attribute: `data-${string}`]: string | undefined; +}>; + +/** 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; + /** Called when the user or `select`/`clear` changes the selection. */ + onSelectionChange?: (selection: TSelection | null) => void; + /** Called on click, Enter or Space. Makes the interaction surface a button. */ + onActivate?: (active: TActive) => void; + /** Names a category in announcements. Default: the category key */ + formatCategory?: (category: string) => string | null; +} + +/** What a chart type's layout gives the shared instance. */ +export type ChartLayout = Readonly<{ + plot: ChartPlot; + yTicks: readonly ChartTick[]; + 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({ + frame, + layout, + model, + options, +}: Readonly<{ + frame: ChartFrame; + layout: ChartLayout; + model: SelectionModel; + options: ChartOptions; +}>) { + 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, 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 announcement = getKeyboardAnnouncement(valid, currentCategory, model, formatCategory); + const keyboardInstructions = getKeyboardInstructions(model.verticalInstructions, !!onActivate); + const tooltipAnchor = + valid?.selection && currentCategory && selected + ? { x: currentCategory.center, y: model.anchorY(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' }); + }, []); + + // Only a pointer event on the surface makes a pointer selection, so its target is the surface. + const surfaceRef = React.useRef(null); + + // 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 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 x = ((clientX - bounds.left) / bounds.width) * size.width; + const y = ((clientY - bounds.top) / bounds.height) * size.height; + const category = categories[nearestCategory(categories, x)]; + return category ? model.hitTest(category, y, pointerUpdates.pending() ?? currentSelection) : null; + }; + + 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, + }); + }; + + const activate = (selection: TSelection | null) => { + const active = resolve(selection); + if (active) { + onActivate?.(active); + } + }; + + const activateKeyboardSelection = () => { + const dismissed = stateRef.current.status === 'dismissed'; + const next = selectKeyboardIndex(keyboardIndex(), undefined, currentSelection); + if (!dismissed) { + activate(toPublicSelection(next)); + } + }; + + const reads = options.selection !== undefined || !!options.onSelectionChange || !!onActivate; + const getInteractionProps = (): ChartInteractionProps => ({ + ...model.surfaceAttributes(currentSelection), + role: onActivate ? 'button' : 'group', + tabIndex: reads ? 0 : undefined, + onPointerDown: event => { + event.preventDefault(); + surfaceRef.current = event.currentTarget; + // 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 => { + surfaceRef.current = event.currentTarget; + 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(); + return; + } + activate(pointerSelection(event.clientX, event.clientY)); + }, + 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(); + } else { + selectKeyboardIndex(intent.index, intent.move, currentSelection); + } + }, + }); + + return { + rootRef, + size, + plot, + yTicks: layout.yTicks, + categories, + xTicks, + selected, + tooltipAnchor, + announcement, + keyboardInstructions, + select, + clear, + getInteractionProps, + }; +} From dcbfa916bec4f2d0738a124410781c98b210538f Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 07:35:46 -0700 Subject: [PATCH 12/40] refactor(mosaic): move the shared chart parts into a Chart primitive Chart.Root, Grid, YLine, YAxis, YTick, XAxis, XTick, Selection, Cursor and Tooltip live in primitives/chart and read only the shared ChartInstance, so a second chart type can reuse them. BarChart keeps useBarChart, StackedBars, Bar, ProjectionOutline and CanvasRenderError; its marks read their layout through a module-private symbol on the instance. - GridLine and ZeroLine become Chart.YLine value. BarSelection becomes Chart.Selection. Categories carry x and width instead of bandX and bandWidth, and chart.step is gone. - The selection engine moves to chart/internal, fenced by lint to the *-chart folders. - The tooltip anchor carries a y, and calendar ticks interpolate between category centers instead of assuming evenly split bands. - A type-level line chart fixture proves the contract fits points. --- packages/mosaic/oxlint.config.mjs | 44 ++++++ .../__tests__/bar-chart-layout.test.ts | 2 +- .../bar-chart/__tests__/bar-chart.test.tsx | 33 ++--- .../__tests__/bar-chart.visual.test.tsx | 48 ++++--- .../bar-chart/__tests__/test-chart.tsx | 34 ++--- .../primitives/bar-chart/bar-chart-canvas.ts | 3 +- .../primitives/bar-chart/bar-chart-context.ts | 71 ++++------ .../primitives/bar-chart/bar-chart-cursor.tsx | 40 ------ .../bar-chart/bar-chart-grid-line.tsx | 34 ----- .../primitives/bar-chart/bar-chart-layout.ts | 25 ++-- .../bar-chart/bar-chart-selection.ts | 2 +- .../bar-chart/bar-chart-stacked-bars.tsx | 8 +- .../bar-chart/bar-chart-tooltip.tsx | 134 ------------------ .../bar-chart/bar-chart-zero-line.tsx | 30 ---- .../mosaic/src/primitives/bar-chart/index.ts | 34 +---- .../mosaic/src/primitives/bar-chart/parts.ts | 20 +-- .../mosaic/src/primitives/bar-chart/types.ts | 38 +---- .../src/primitives/bar-chart/use-bar-chart.ts | 21 +-- .../src/primitives/chart/chart-context.ts | 41 ++++++ .../src/primitives/chart/chart-cursor.tsx | 38 +++++ .../chart-grid.tsx} | 12 +- .../chart-root.tsx} | 23 ++- .../chart-selection.tsx} | 24 ++-- .../src/primitives/chart/chart-tooltip.tsx | 132 +++++++++++++++++ .../chart-x-axis.tsx} | 13 +- .../chart-x-tick.tsx} | 12 +- .../chart-y-axis.tsx} | 14 +- .../src/primitives/chart/chart-y-line.tsx | 33 +++++ .../chart-y-tick.tsx} | 14 +- packages/mosaic/src/primitives/chart/index.ts | 30 ++++ .../__tests__/calendar-ticks.test.ts | 28 +++- .../internal}/__tests__/x-ticks.test.ts | 0 .../internal}/calendar-ticks.ts | 22 ++- .../internal/selection.ts} | 6 +- .../internal}/use-chart-instance.ts | 74 ++++------ .../internal}/use-chart-size.ts | 2 +- .../{bar-chart => chart/internal}/x-ticks.ts | 12 +- .../chart/line-chart-contract.test-d.ts | 62 ++++++++ packages/mosaic/src/primitives/chart/parts.ts | 10 ++ packages/mosaic/src/primitives/chart/types.ts | 123 ++++++++++++++++ .../src/stories/bar-chart.stories.tsx | 45 +++--- 41 files changed, 788 insertions(+), 603 deletions(-) delete mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-cursor.tsx delete mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-grid-line.tsx delete mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx delete mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-zero-line.tsx create mode 100644 packages/mosaic/src/primitives/chart/chart-context.ts create mode 100644 packages/mosaic/src/primitives/chart/chart-cursor.tsx rename packages/mosaic/src/primitives/{bar-chart/bar-chart-grid.tsx => chart/chart-grid.tsx} (60%) rename packages/mosaic/src/primitives/{bar-chart/bar-chart-root.tsx => chart/chart-root.tsx} (57%) rename packages/mosaic/src/primitives/{bar-chart/bar-chart-bar-selection.tsx => chart/chart-selection.tsx} (75%) create mode 100644 packages/mosaic/src/primitives/chart/chart-tooltip.tsx rename packages/mosaic/src/primitives/{bar-chart/bar-chart-x-axis.tsx => chart/chart-x-axis.tsx} (71%) rename packages/mosaic/src/primitives/{bar-chart/bar-chart-x-tick.tsx => chart/chart-x-tick.tsx} (66%) rename packages/mosaic/src/primitives/{bar-chart/bar-chart-y-axis.tsx => chart/chart-y-axis.tsx} (67%) create mode 100644 packages/mosaic/src/primitives/chart/chart-y-line.tsx rename packages/mosaic/src/primitives/{bar-chart/bar-chart-y-tick.tsx => chart/chart-y-tick.tsx} (52%) create mode 100644 packages/mosaic/src/primitives/chart/index.ts rename packages/mosaic/src/primitives/{bar-chart => chart/internal}/__tests__/calendar-ticks.test.ts (77%) rename packages/mosaic/src/primitives/{bar-chart => chart/internal}/__tests__/x-ticks.test.ts (100%) rename packages/mosaic/src/primitives/{bar-chart => chart/internal}/calendar-ticks.ts (81%) rename packages/mosaic/src/primitives/{bar-chart/chart-selection.ts => chart/internal/selection.ts} (97%) rename packages/mosaic/src/primitives/{bar-chart => chart/internal}/use-chart-instance.ts (82%) rename packages/mosaic/src/primitives/{bar-chart => chart/internal}/use-chart-size.ts (97%) rename packages/mosaic/src/primitives/{bar-chart => chart/internal}/x-ticks.ts (94%) create mode 100644 packages/mosaic/src/primitives/chart/line-chart-contract.test-d.ts create mode 100644 packages/mosaic/src/primitives/chart/parts.ts create mode 100644 packages/mosaic/src/primitives/chart/types.ts diff --git a/packages/mosaic/oxlint.config.mjs b/packages/mosaic/oxlint.config.mjs index 2da74dc1b84..7aa01bc3696 100644 --- a/packages/mosaic/oxlint.config.mjs +++ b/packages/mosaic/oxlint.config.mjs @@ -5,6 +5,9 @@ import noUnneededEffects from 'eslint-plugin-react-you-might-not-need-an-effect' import { defineConfig } from 'oxlint'; const mosaicRoot = import.meta.dirname; +const [, rootRestrictedImports] = rootConfig.rules['no-restricted-imports']; +const chartInternalMessage = + 'The chart selection engine is for chart-type hooks. Import it only from a src/primitives/-chart/ folder.'; const SHARED = ['primitives', 'icons', 'machine', 'utils', 'hooks', 'styles', 'components', 'localization', 'root']; const FLOW_UI = { file: { categories: { anyOf: ['view', 'controller'] } } }; const CLERK_DATA_HOOKS = [ @@ -471,6 +474,47 @@ export default defineConfig({ 'no-unused-vars': 'off', }, }, + { + files: ['src/**/*'], + excludeFiles: [ + 'src/primitives/*-chart/**', + 'src/primitives/chart/internal/**', + 'src/**/__tests__/**', + 'src/**/*.test.{ts,tsx}', + 'src/**/*.test-d.ts', + ], + rules: { + 'no-restricted-imports': [ + 'error', + { + ...rootRestrictedImports, + patterns: [ + ...rootRestrictedImports.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', + { + ...rootRestrictedImports, + patterns: [ + ...rootRestrictedImports.patterns, + { group: ['./internal', './internal/*'], message: chartInternalMessage }, + ], + }, + ], + }, + }, { files: [ 'src/primitives/file-upload/file-upload-dropzone.tsx', diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts index efcfae52086..08af192eac6 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest'; +import { DEFAULT_CHART_MARGIN } from '../../chart/internal/use-chart-instance'; import { prepareStackedBars, projectStackedBars } from '../bar-chart-layout'; import type { BarProjection } from '../types'; -import { DEFAULT_CHART_MARGIN } from '../use-chart-instance'; interface TypedRow { start: string; diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx index b4c0dc35a36..18513504dce 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx @@ -2,6 +2,7 @@ import { cleanup, fireEvent, render as renderComponent, screen } from '@testing- import { useState } from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { Chart } from '../../chart'; import type { RenderProps } from '../../utils'; import { BarChart, type BarSelection } from '../index'; import { chartFixture, type ChartRow, growthChart, quarter, render, renderChart, setupChart } from './fixtures'; @@ -16,18 +17,18 @@ function StackedChart({ children, }: { data?: readonly ChartRow[]; - render?: React.ComponentProps['render']; + render?: React.ComponentProps['render']; children?: React.ReactNode; }) { const chart = BarChart.useBarChart({ data, series: chartFixture.series, index: chartFixture.index }); return ( - {children} - + ); } @@ -41,21 +42,21 @@ function chartRoot(container: HTMLElement) { describe('composing parts', () => { it.each([ - ['Grid', ], - ['StackedBars', ], - ['BarSelection', ], - ])('throws when BarChart.%s is used outside BarChart.Root', (part, element) => { + ['Chart.Grid', ], + ['Chart.Selection', ], + ['BarChart.StackedBars', ], + ])('throws when %s is used outside Chart.Root', (part, element) => { vi.spyOn(console, 'error').mockImplementation(() => {}); - expect(() => renderComponent(element)).toThrow(` must be used within `); + expect(() => renderComponent(element)).toThrow(`<${part}> must be used within `); }); it.each([ - ['Cursor', ], - ['Tooltip', {() => 'Growth'}], - ])('throws when BarChart.%s is used outside BarChart.BarSelection', (part, element) => { + ['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 `, + ` must be used within `, ); }); @@ -92,11 +93,11 @@ describe('composing parts', () => { expect(screen.getAllByRole('img').map(image => image.getAttribute('aria-label'))).toEqual(['Growth']); }); - it('is interactive with BarChart.BarSelection and categories', () => { + it('is interactive with Chart.Selection and categories', () => { const { container, rerender } = render( - + , ); @@ -106,7 +107,7 @@ describe('composing parts', () => { rerender( - + , ); expect(chartRoot(container)).toHaveAttribute('data-chart-interaction-mode', 'visual-only'); @@ -134,7 +135,7 @@ describe('choosing a period', () => { const mode = () => container.firstElementChild?.getAttribute('data-chart-interaction-mode'); expect(mode()).toBe('interactive'); - rerenderChart({ barSelection: false }); + rerenderChart({ selectionPart: false }); expect(queryByRole('group', { name: 'Growth' })).toBeNull(); expect(mode()).toBe('visual-only'); }); diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx index 527e81c077c..52c78fdebdc 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx @@ -3,7 +3,8 @@ import { useCallback, useRef } from 'react'; import { beforeAll, describe, expect, it } from 'vitest'; import { page, userEvent } from 'vitest/browser'; -import { BarChart, type BarIdentity, type BarProjection } from '../index'; +import { Chart } from '../../chart'; +import { type ActiveBar, BarChart, type BarIdentity, type BarProjection } from '../index'; const growth = [ { week: '2026-01-05', signups: 40, returning: 22, churned: -14 }, @@ -73,52 +74,55 @@ function GrowthChart({ className='chart' data-testid='chart' > - - - {lines => - lines.map(line => ( - + {ticks => + ticks.map(tick => ( + )) } - + - + - + {ticks => ticks.map(tick => ( - )) } - - + + {ticks => ticks.map(tick => ( - )) } - - - - + + + + > className='tooltip' boundaryRef={boundary} > @@ -129,9 +133,9 @@ function GrowthChart({
Churned: {datum.churned}
)} - -
-
+ + +
); } diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/test-chart.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/test-chart.tsx index d07b8e1c5b2..83ed1913006 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/test-chart.tsx +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/test-chart.tsx @@ -1,7 +1,7 @@ import { type ReactNode, type RefObject, useLayoutEffect } from 'react'; -import { BarChart, type BarChartInstance, type UseBarChartOptions } from '../index'; -import type { ActiveBar } from '../types'; +import { Chart } from '../../chart'; +import { type ActiveBar, BarChart, type BarChartInstance, type UseBarChartOptions } from '../index'; export type TestChartProps = Pick< UseBarChartOptions, @@ -17,8 +17,8 @@ export type TestChartProps = Pick< > & { ariaLabel: string; formatXTick?: (value: string) => string | null; - /** Mounts `BarChart.BarSelection`. Default: true */ - barSelection?: boolean; + /** Mounts `Chart.Selection`. Default: true */ + selectionPart?: boolean; renderTooltip?: (active: ActiveBar) => ReactNode; boundary?: RefObject; height?: number | string; @@ -33,7 +33,7 @@ export type TestChartProps = Pick< export function TestChart({ ariaLabel, formatXTick, - barSelection = true, + selectionPart = true, renderTooltip, boundary, height, @@ -49,7 +49,7 @@ export function TestChart({ } }); return ( - ({ {bar ? : null} - + - + {ticks => ticks.map(tick => ( - )) } - - {barSelection ? ( - - + + {selectionPart ? ( + + {renderTooltip ? ( - + > boundaryRef={boundary} data-testid='tooltip' > {renderTooltip} - + ) : null} - + ) : null} - + ); } diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-canvas.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-canvas.ts index 8ac51c67018..6026d715846 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-canvas.ts +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-canvas.ts @@ -1,6 +1,7 @@ +import type { ChartSize } from '../chart/types'; import { getComputedStyle } from '../utils/dom'; import { type BarGeometry, type PaintedProjection, UNSTYLED_BAR_GEOMETRY } from './bar-chart-layout'; -import type { BarIdentity, BarMark, ChartSize } from './types'; +import type { BarIdentity, BarMark } from './types'; const TILE_DEVICE_PIXELS = 32; diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-context.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-context.ts index 474f0e316a5..fbdd8076608 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-context.ts +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-context.ts @@ -1,35 +1,39 @@ -import { createContext, type RefObject, useContext } from 'react'; +import { createContext, useContext } from 'react'; +import { ChartContext } from '../chart/chart-context'; +import type { ChartInstance } from '../chart/types'; import type { BarStyleElement } from './bar-chart-canvas'; -import type { PaintedProjection } from './bar-chart-layout'; -import type { ChartSize } from './types'; -import type { BarChartInstance } from './use-bar-chart'; +import type { PaintedProjection, PreparedStackedBars, StackedBarLayout } from './bar-chart-layout'; +import type { ActiveBar, BarCategory, BarIdentity, BarSelection } from './types'; -export interface BarChartContextValue { - chart: BarChartInstance; - ariaLabel: string; - /** Marks the chart interactive while the returned cleanup has not run. */ - registerInteraction: () => () => void; -} +/** Only `useBarChart` sets it, so a chart that carries it came from `useBarChart`. */ +export const BAR_LAYOUT: unique symbol = Symbol('BarChart layout'); -export const BarChartContext = createContext(null); +/** What the bar marks paint from. Read by `BarChart` parts only. */ +export type BarLayout = Readonly<{ + prepared: PreparedStackedBars; + projection: StackedBarLayout['projection']; + isBarActive: ((bar: BarIdentity) => boolean) | undefined; +}>; -export function useBarChartContext(part: string) { - const context = useContext(BarChartContext); - if (!context) { - throw new Error(` must be used within `); - } - return { - ...context, - // SAFETY: `BarChart.Root` holds one `useBarChart` result, and a part's `TDatum` is the - // type of the chart it renders in. Context cannot carry the parameter. - // eslint-disable-next-line typescript/consistent-type-assertions -- React context is not generic per consumer. - chart: context.chart as unknown as BarChartInstance, - }; +/** The measured layout and selection of one stacked bar chart, returned by `BarChart.useBarChart`. */ +export type BarChartInstance = ChartInstance, BarSelection, BarCategory> & + Readonly<{ [BAR_LAYOUT]: BarLayout }>; + +function isBarChart(chart: ChartInstance): chart is BarChartInstance { + return BAR_LAYOUT in chart; } -export function hasArea(size: ChartSize) { - return size.width > 0 && size.height > 0; +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 BarChart.useBarChart`); + } + return { chart, layout: chart[BAR_LAYOUT], ariaLabel }; } export interface StackedBarsContextValue { @@ -47,20 +51,3 @@ export function useStackedBarsContext(part: string) { } return context; } - -export interface BarSelectionContextValue { - /** 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 BarSelectionContext = createContext(null); - -export function useBarSelectionContext(part: string) { - const context = useContext(BarSelectionContext); - if (!context) { - throw new Error(` must be used within `); - } - return context; -} diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-cursor.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-cursor.tsx deleted file mode 100644 index 102cd521a1f..00000000000 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-cursor.tsx +++ /dev/null @@ -1,40 +0,0 @@ -'use client'; - -import React from 'react'; - -import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { useBarChartContext, useBarSelectionContext } from './bar-chart-context'; - -export type BarChartCursorProps = ComponentProps<'div'>; - -export const BarChartCursor = React.forwardRef( - function BarChartCursor(props, ref) { - const { render, ...otherProps } = props; - useBarSelectionContext('Cursor'); - const { chart } = useBarChartContext('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.bandX - plot.x, - width: selectedCategory.bandWidth, - 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/bar-chart/bar-chart-grid-line.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-grid-line.tsx deleted file mode 100644 index 314393b6841..00000000000 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-grid-line.tsx +++ /dev/null @@ -1,34 +0,0 @@ -'use client'; - -import React from 'react'; - -import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { useBarChartContext } from './bar-chart-context'; -import type { ChartTick } from './types'; - -export type BarChartGridLineProps = ComponentProps<'line'> & { - /** An entry from the `BarChart.Grid` children function. */ - line: ChartTick; -}; - -export const BarChartGridLine = React.forwardRef( - function BarChartGridLine(props, ref) { - const { line, render, ...otherProps } = props; - const { chart } = useBarChartContext('GridLine'); - - const ownProps = { - x1: chart.plot.x, - x2: chart.plot.x + chart.plot.width, - y1: line.y, - y2: line.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/bar-chart/bar-chart-layout.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts index b3b1459a315..a111a7146ba 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts @@ -1,7 +1,8 @@ import { scaleBand, scaleLinear } from 'd3-scale'; import { stack, stackOffsetDiverging } from 'd3-shape'; -import type { BarCategory, BarMark, BarProjection, BarSeries, ChartFrame, ChartMargin, ChartSize } from './types'; +import type { ChartMargin, ChartSize } from '../chart/types'; +import type { BarCategory, BarMark, BarProjection, BarSeries } from './types'; const Y_TICK_COUNT = 5; @@ -29,11 +30,12 @@ export type PreparedStackedBars = Readonly<{ domain: readonly [number, number]; }>; -type ProjectOptions = ChartFrame & - Readonly<{ - categoryGap: number; - projection?: BarProjection; - }>; +type ProjectOptions = Readonly<{ + size: ChartSize; + margin: ChartMargin; + categoryGap: number; + projection?: BarProjection; +}>; /** Bar geometry read from `BarChart.Bar`'s computed style. */ export type BarGeometry = Readonly<{ @@ -173,7 +175,7 @@ function projectMarksAndPaintInsets(layout: MarkSource, { maxWid 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 barWidth = Math.min(category.bandWidth, maxWidth); + const barWidth = Math.min(category.width, maxWidth); const stackKey = `${point.datumIndex}:${point.positive}`; const previousMark = previousMarkByStack.get(stackKey); const mark: DraftBarMark = { @@ -181,7 +183,7 @@ function projectMarksAndPaintInsets(layout: MarkSource, { maxWid datum: point.datum, datumIndex: point.datumIndex, value: point.value, - x: category.bandX + (category.bandWidth - barWidth) / 2, + x: category.x + (category.width - barWidth) / 2, y: rawTop, width: barWidth, height, @@ -287,8 +289,8 @@ function projectCategories( return { key, datumIndex, - bandX, - bandWidth: x.bandwidth(), + x: bandX, + width: x.bandwidth(), center: bandX + x.bandwidth() / 2, sections: { positive: positive.has(datumIndex) || projected === datumIndex, @@ -321,14 +323,13 @@ export function projectStackedBars( categoryGap, projection: acceptedProjection, }); - const { x, y, innerWidth, innerHeight } = scales; + const { y, innerWidth, innerHeight } = scales; const projectedBar = projectOptionalProjection(prepared.indexes, acceptedProjection, scales); return { prepared, scaleY: (value: number) => y(value), categories: projectCategories(prepared, projectedBar, scales), - step: x.step(), zeroY: y(0), yTicks: y.ticks(Y_TICK_COUNT).map(value => ({ value, y: y(value) })), plot: { diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts index d3186bcbbbf..078da73ccb1 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts @@ -1,5 +1,5 @@ +import type { SelectionModel } from '../chart/internal/selection'; import type { StackedBarLayout } from './bar-chart-layout'; -import type { SelectionModel } from './chart-selection'; import type { ActiveBar, BarCategory, BarSection, BarSelection } from './types'; /** Selects a section of a stacked bar: above the zero line or below it. */ diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx index e1002f3bea1..451ce84e179 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx @@ -2,6 +2,7 @@ import React from 'react'; +import { hasArea } from '../chart/chart-context'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; import { type BarStyleElement, @@ -10,7 +11,7 @@ import { paintStackedBarCanvas, parseBarGeometry, } from './bar-chart-canvas'; -import { hasArea, StackedBarsContext, useBarChartContext } from './bar-chart-context'; +import { StackedBarsContext, useBarChartContext } from './bar-chart-context'; import { fitProjectionToBar, projectStackedBarMarks } from './bar-chart-layout'; export type BarChartStackedBarsProps = ComponentProps<'div'>; @@ -48,8 +49,9 @@ const getServerPixelRatio = () => 1; export const BarChartStackedBars = React.forwardRef( function BarChartStackedBars(props, ref) { const { children, render, ...otherProps } = props; - const { chart, ariaLabel } = useBarChartContext('StackedBars'); - const { size, prepared, categories, scaleY, isBarActive, projection: projectedBar } = chart; + const { chart, layout, ariaLabel } = useBarChartContext('StackedBars'); + const { size, categories, scaleY } = chart; + const { prepared, isBarActive, projection: projectedBar } = layout; const rootThemeAttributes = React.useSyncExternalStore( subscribeToRootTheme, getRootThemeAttributes, diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx deleted file mode 100644 index 00d780fe3bf..00000000000 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-tooltip.tsx +++ /dev/null @@ -1,134 +0,0 @@ -'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 { useBarChartContext, useBarSelectionContext } from './bar-chart-context'; -import type { ActiveBar } from './types'; - -const EDGE = 8; -const SIDE_OFFSET = 16; -const PINNED_BELOW_PLOT_WIDTH = 416; - -export type BarChartTooltipProps = Omit, 'children'> & { - /** Content for the selected bar. Return null to hide the tooltip. */ - children: (active: ActiveBar) => React.ReactNode; - /** Element the tooltip stays inside. Default: the chart */ - boundaryRef?: React.RefObject; -}; - -type Side = 'left' | 'right'; - -function tooltipMiddleware(getBoundary: () => Element | undefined, pinned: boolean) { - return [ - offset(pinned ? 0 : SIDE_OFFSET), - flip(() => ({ boundary: getBoundary(), padding: EDGE, crossAxis: false })), - shift(() => ({ boundary: getBoundary(), padding: EDGE, crossAxis: true })), - size(() => ({ - boundary: getBoundary(), - padding: EDGE, - apply({ elements }) { - const boundary = getBoundary()?.getBoundingClientRect(); - const viewportWidth = getWindow(elements.floating).document.documentElement.clientWidth; - const left = Math.max(EDGE, (boundary?.left ?? 0) + EDGE); - const right = Math.min(viewportWidth - EDGE, (boundary?.right ?? viewportWidth) - EDGE); - elements.floating.style.maxWidth = `${Math.max(0, right - left)}px`; - }, - })), - ]; -} - -// eslint-disable-next-line typescript/consistent-type-assertions -- The ref wrapper drops the row type parameter; `children` only receives rows the chart was given. -export const BarChartTooltip = React.forwardRef( - function BarChartTooltip(props, ref) { - const { children, boundaryRef, render, ...otherProps } = props; - const { registerTooltip, chartBoxRef } = useBarSelectionContext('Tooltip'); - const { chart } = useBarChartContext('Tooltip'); - const { plot, selected: activeBar } = chart; - const chartWidth = chart.size.width; - React.useLayoutEffect(registerTooltip, [registerTooltip]); - - const anchor = chart.tooltipAnchor; - const content = activeBar && anchor ? children(activeBar) : null; - const open = content !== null && content !== undefined; - const anchorX = anchor?.x; - const anchorY = anchor?.y; - - const pinned = plot.width < PINNED_BELOW_PLOT_WIDTH; - const popupRef = React.useRef(null); - const getBoundary = React.useCallback( - () => boundaryRef?.current ?? chartBoxRef.current ?? undefined, - [boundaryRef, chartBoxRef], - ); - // eslint-disable-next-line react/refs -- The middleware reads the boundary refs when floating-ui computes a position, not during render. - const middleware = React.useMemo(() => tooltipMiddleware(getBoundary, pinned), [getBoundary, pinned]); - - const [lastSide, setLastSide] = React.useState('right'); - 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 bar twice near an edge. - if (!pinned && (resolvedSide === 'left' || resolvedSide === 'right') && resolvedSide !== lastSide) { - setLastSide(resolvedSide); - } - - React.useLayoutEffect(() => { - const chart = chartBoxRef.current; - if (anchorX === undefined || anchorY === undefined || !chart || chartWidth <= 0) { - return; - } - const getBoundingClientRect = () => { - const chartRect = chart.getBoundingClientRect(); - if (pinned) { - const boundary = getBoundary()?.getBoundingClientRect() ?? chartRect; - return new DOMRect(boundary.left + EDGE, boundary.top + EDGE, 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: chart }); - }, [anchorX, anchorY, chartBoxRef, chartWidth, getBoundary, 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: BarChartTooltipProps & { ref?: React.Ref }, -) => React.ReactElement | null; diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-zero-line.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-zero-line.tsx deleted file mode 100644 index ab5c8ab615f..00000000000 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-zero-line.tsx +++ /dev/null @@ -1,30 +0,0 @@ -'use client'; - -import React from 'react'; - -import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { useBarChartContext } from './bar-chart-context'; - -export type BarChartZeroLineProps = ComponentProps<'line'>; - -export const BarChartZeroLine = React.forwardRef( - function BarChartZeroLine(props, ref) { - const { render, ...otherProps } = props; - const { chart } = useBarChartContext('ZeroLine'); - - const ownProps = { - x1: chart.plot.x, - x2: chart.plot.x + chart.plot.width, - y1: chart.zeroY, - y2: chart.zeroY, - 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/bar-chart/index.ts b/packages/mosaic/src/primitives/bar-chart/index.ts index fb3fa02c4a6..dd42129ca05 100644 --- a/packages/mosaic/src/primitives/bar-chart/index.ts +++ b/packages/mosaic/src/primitives/bar-chart/index.ts @@ -2,39 +2,9 @@ export * as BarChart from './parts'; export type { BarChartBarProps, - BarChartBarSelectionProps, - BarChartCursorProps, - BarChartGridLineProps, - BarChartInstance, - BarChartInteractionProps, - BarChartGridProps, BarChartProjectionOutlineProps, - BarChartRootProps, BarChartStackedBarsProps, - BarChartTooltipProps, - BarChartXAxisProps, - BarChartXTickProps, - BarChartYAxisProps, - BarChartYTickItem, - BarChartYTickProps, - BarChartZeroLineProps, UseBarChartOptions, - XTickMode, - XTicksOptions, } from './parts'; -export type { StackedBarLayout } from './bar-chart-layout'; -export type { - ActiveBar, - BarCategory, - BarIdentity, - BarProjection, - BarSection, - BarSelection, - BarSeries, - ChartFrame, - ChartMargin, - ChartPlot, - ChartSize, - ChartTick, -} from './types'; -export type { XTick } from './x-ticks'; +export type { BarChartInstance } from './bar-chart-context'; +export type { ActiveBar, BarCategory, BarIdentity, BarProjection, BarSection, BarSelection, BarSeries } from './types'; diff --git a/packages/mosaic/src/primitives/bar-chart/parts.ts b/packages/mosaic/src/primitives/bar-chart/parts.ts index 9eff94b4a37..0f3ea8d01fc 100644 --- a/packages/mosaic/src/primitives/bar-chart/parts.ts +++ b/packages/mosaic/src/primitives/bar-chart/parts.ts @@ -1,26 +1,8 @@ -export { type BarChartRootProps, BarChartRoot as Root } from './bar-chart-root'; -export { type BarChartGridProps, BarChartGrid as Grid } from './bar-chart-grid'; -export { type BarChartGridLineProps, BarChartGridLine as GridLine } from './bar-chart-grid-line'; -export { type BarChartYAxisProps, type BarChartYTickItem, BarChartYAxis as YAxis } from './bar-chart-y-axis'; -export { type BarChartYTickProps, BarChartYTick as YTick } from './bar-chart-y-tick'; -export { type BarChartXAxisProps, BarChartXAxis as XAxis } from './bar-chart-x-axis'; -export { type BarChartXTickProps, BarChartXTick as XTick } from './bar-chart-x-tick'; +export { useBarChart, type UseBarChartOptions } from './use-bar-chart'; export { type BarChartStackedBarsProps, BarChartStackedBars as StackedBars } from './bar-chart-stacked-bars'; export { type BarChartBarProps, BarChartBar as Bar } from './bar-chart-bar'; export { type BarChartProjectionOutlineProps, BarChartProjectionOutline as ProjectionOutline, } from './bar-chart-projection-outline'; -export { type BarChartZeroLineProps, BarChartZeroLine as ZeroLine } from './bar-chart-zero-line'; -export { type BarChartBarSelectionProps, BarChartBarSelection as BarSelection } from './bar-chart-bar-selection'; -export { type BarChartCursorProps, BarChartCursor as Cursor } from './bar-chart-cursor'; -export { type BarChartTooltipProps, BarChartTooltip as Tooltip } from './bar-chart-tooltip'; export { CanvasRenderError } from './bar-chart-canvas'; -export { - type BarChartInstance, - type BarChartInteractionProps, - useBarChart, - type UseBarChartOptions, - type XTickMode, - type XTicksOptions, -} from './use-bar-chart'; diff --git a/packages/mosaic/src/primitives/bar-chart/types.ts b/packages/mosaic/src/primitives/bar-chart/types.ts index 3b5ab2f5756..8017d236ea7 100644 --- a/packages/mosaic/src/primitives/bar-chart/types.ts +++ b/packages/mosaic/src/primitives/bar-chart/types.ts @@ -1,33 +1,4 @@ -export type ChartSize = Readonly<{ width: number; height: number }>; - -export type ChartMargin = Readonly<{ - top: number; - right: number; - bottom: number; - left: number; -}>; - -/** The measured container and the margin around the plot. */ -export type ChartFrame = Readonly<{ size: ChartSize; margin: ChartMargin }>; - -export type ChartPlot = Readonly<{ - x: number; - y: number; - width: number; - height: number; -}>; - -export type ChartTick = Readonly<{ value: number; y: number }>; - -/** One datum's place on the X axis. */ -export type ChartCategory = Readonly<{ - key: string; - datumIndex: number; - center: number; -}>; - -/** What a selection names. Each chart type extends it with what else a user can pick there. */ -export type ChartSelection = Readonly<{ category: string }>; +import type { ChartActive, ChartCategory, ChartSelection } from '../chart/types'; export type CornerRadii = readonly [number, number, number, number]; @@ -65,8 +36,6 @@ export type BarSection = 'positive' | 'negative'; export type BarCategory = ChartCategory & Readonly<{ - bandX: number; - bandWidth: number; /** Sections a user can select, including a projection-only positive bar. */ sections: Readonly>; /** Sections with nonzero data values. */ @@ -79,10 +48,9 @@ export type BarCategory = ChartCategory & export type BarSelection = ChartSelection & Readonly<{ section: BarSection }>; /** A selected bar resolved against the current data. */ -export type ActiveBar = BarSelection & +export type ActiveBar = ChartActive & + BarSelection & Readonly<{ - datumIndex: number; - datum: TDatum; hasValues: BarCategory['hasValues']; projected: BarCategory['projected']; }>; diff --git a/packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts b/packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts index 7b9d6834685..5b7f218566d 100644 --- a/packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts +++ b/packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts @@ -2,12 +2,12 @@ import React from 'react'; -import { prepareStackedBars, projectStackedBars, type StackedBarLayout } from './bar-chart-layout'; +import { useChartFrame, useChartInstance } from '../chart/internal/use-chart-instance'; +import type { ChartOptions } from '../chart/types'; +import { BAR_LAYOUT, type BarChartInstance } from './bar-chart-context'; +import { prepareStackedBars, projectStackedBars } from './bar-chart-layout'; import { barSelectionModel } from './bar-chart-selection'; -import type { ActiveBar, BarCategory, BarIdentity, BarProjection, BarSelection, BarSeries } from './types'; -import { type ChartOptions, useChartFrame, useChartInstance } from './use-chart-instance'; - -export type { ChartInteractionProps as BarChartInteractionProps, XTickMode, XTicksOptions } from './use-chart-instance'; +import type { ActiveBar, BarIdentity, BarProjection, BarSelection, BarSeries } from './types'; export interface UseBarChartOptions extends ChartOptions> { data: readonly TDatum[]; @@ -23,15 +23,8 @@ export interface UseBarChartOptions extends ChartOptions) => boolean; } -/** The measured layout and selection of one chart, returned by `BarChart.useBarChart`. */ -export type BarChartInstance = Omit, 'categories' | 'yTicks'> & - ReturnType, BarCategory>> & - Readonly<{ - isBarActive: ((bar: BarIdentity) => boolean) | undefined; - }>; - /** - * Measures, lays out and selects a stacked bar chart. Pass the result to `BarChart.Root`, or render + * 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 { @@ -59,5 +52,5 @@ export function useBarChart(options: UseBarChartOptions): BarCha const model = React.useMemo(() => barSelectionModel(layout, data), [data, layout]); const instance = useChartInstance({ frame, layout, model, options }); - return { ...layout, ...instance, isBarActive }; + return { ...instance, [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..bf13ad13ec7 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart-context.ts @@ -0,0 +1,41 @@ +import { createContext, type RefObject, useContext } from 'react'; + +import type { 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; +} + +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/bar-chart/bar-chart-grid.tsx b/packages/mosaic/src/primitives/chart/chart-grid.tsx similarity index 60% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-grid.tsx rename to packages/mosaic/src/primitives/chart/chart-grid.tsx index 65e9eac3c85..faa2f846550 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-grid.tsx +++ b/packages/mosaic/src/primitives/chart/chart-grid.tsx @@ -3,17 +3,17 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { hasArea, useBarChartContext } from './bar-chart-context'; +import { hasArea, useChartContext } from './chart-context'; import type { ChartTick } from './types'; -export type BarChartGridProps = Omit, 'children'> & { - /** Renders the lines, usually one `BarChart.GridLine` per entry. */ - children?: (lines: readonly ChartTick[]) => React.ReactNode; +export type ChartGridProps = Omit, 'children'> & { + /** Renders the lines, usually one `Chart.YLine` per tick value. */ + children?: (ticks: readonly ChartTick[]) => React.ReactNode; }; -export const BarChartGrid = React.forwardRef(function BarChartGrid(props, ref) { +export const ChartGrid = React.forwardRef(function ChartGrid(props, ref) { const { children, render, ...otherProps } = props; - const { chart } = useBarChartContext('Grid'); + const { chart } = useChartContext('Grid'); const { size, yTicks } = chart; const ownProps = { diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-root.tsx b/packages/mosaic/src/primitives/chart/chart-root.tsx similarity index 57% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-root.tsx rename to packages/mosaic/src/primitives/chart/chart-root.tsx index 8ad6efe13e6..86f58516eb7 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-root.tsx +++ b/packages/mosaic/src/primitives/chart/chart-root.tsx @@ -3,22 +3,21 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { BarChartContext, type BarChartContextValue } from './bar-chart-context'; -import type { BarChartInstance } from './use-bar-chart'; +import { ChartContext, type ChartContextValue } from './chart-context'; +import type { ChartInstance } from './types'; -export type BarChartRootProps = Omit, 'aria-label'> & { - /** The result of `BarChart.useBarChart`. */ - chart: BarChartInstance; +export type ChartRootProps = Omit, 'aria-label'> & { + /** The result of a chart-type hook, such as `BarChart.useBarChart`. */ + chart: ChartInstance; /** Default: 500 */ height?: number | string; - /** Labels the bars image and the interaction surface. */ + /** Labels the chart image and the interaction surface. */ 'aria-label': string; }; type InteractionMode = 'pending' | 'interactive' | 'visual-only'; -// eslint-disable-next-line typescript/consistent-type-assertions -- The ref wrapper drops the row type parameter; the parts read the chart through context. -export const BarChartRoot = React.forwardRef(function BarChartRoot(props, ref) { +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); @@ -27,7 +26,7 @@ export const BarChartRoot = React.forwardRef( return () => setInteractionLayers(count => count - 1); }, []); - const context: BarChartContextValue = { chart, ariaLabel, registerInteraction }; + const context: ChartContextValue = { chart, ariaLabel, registerInteraction }; const interactionMode: InteractionMode = chart.size.width <= 0 @@ -52,7 +51,5 @@ export const BarChartRoot = React.forwardRef( props: mergeProps<'div'>(ownProps, otherProps), }); - return {element}; -}) as ( - props: BarChartRootProps & { ref?: React.Ref }, -) => React.ReactElement | null; + return {element}; +}); diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx b/packages/mosaic/src/primitives/chart/chart-selection.tsx similarity index 75% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx rename to packages/mosaic/src/primitives/chart/chart-selection.tsx index 825bf028ab5..2827e2cb9f4 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-bar-selection.tsx +++ b/packages/mosaic/src/primitives/chart/chart-selection.tsx @@ -3,8 +3,8 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { BarSelectionContext, type BarSelectionContextValue, hasArea, useBarChartContext } from './bar-chart-context'; -import type { BarChartInstance } from './use-bar-chart'; +import { hasArea, SelectionContext, type SelectionContextValue, useChartContext } from './chart-context'; +import type { ChartInstance } from './types'; const VISUALLY_HIDDEN_STYLE: React.CSSProperties = { position: 'absolute', @@ -18,7 +18,7 @@ const VISUALLY_HIDDEN_STYLE: React.CSSProperties = { border: 0, }; -export type BarChartBarSelectionProps = ComponentProps<'div'>; +export type ChartSelectionProps = ComponentProps<'div'>; function KeyboardInstructions({ id, @@ -43,15 +43,15 @@ function KeyboardInstructions({ ); } -export const BarChartBarSelection = React.forwardRef( - function BarChartBarSelection(props, ref) { - const { chart, ariaLabel, registerInteraction } = useBarChartContext('BarSelection'); +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 ( - ; - chart: BarChartInstance; + chart: ChartInstance; ariaLabel: string; }; -function BarSelectionSurface({ forwardedRef, chart, ariaLabel, children, render, ...otherProps }: SurfaceProps) { +function SelectionSurface({ forwardedRef, chart, ariaLabel, children, render, ...otherProps }: SurfaceProps) { const chartBoxRef = React.useRef(null); const keyboardInstructionsId = React.useId(); const [tooltipCount, setTooltipCount] = React.useState(0); @@ -75,7 +75,7 @@ function BarSelectionSurface({ forwardedRef, chart, ariaLabel, children, render, setTooltipCount(count => count + 1); return () => setTooltipCount(count => count - 1); }, []); - const selectionContext = React.useMemo( + const selectionContext = React.useMemo( () => ({ chartBoxRef, registerTooltip }), [registerTooltip], ); @@ -121,5 +121,5 @@ function BarSelectionSurface({ forwardedRef, chart, ariaLabel, children, render, props: mergeProps<'div'>(ownProps, otherProps), }); - return {element}; + 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..8cf60c28f7f --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart-tooltip.tsx @@ -0,0 +1,132 @@ +'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 EDGE = 8; +const SIDE_OFFSET = 16; +const PINNED_BELOW_PLOT_WIDTH = 416; + +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; + /** Element the tooltip stays inside. Default: the chart */ + boundaryRef?: React.RefObject; +}; + +type Side = 'left' | 'right'; + +function tooltipMiddleware(getBoundary: () => Element | undefined, pinned: boolean) { + return [ + offset(pinned ? 0 : SIDE_OFFSET), + flip(() => ({ boundary: getBoundary(), padding: EDGE, crossAxis: false })), + shift(() => ({ boundary: getBoundary(), padding: EDGE, crossAxis: true })), + size(() => ({ + boundary: getBoundary(), + padding: EDGE, + apply({ elements }) { + const boundary = getBoundary()?.getBoundingClientRect(); + const viewportWidth = getWindow(elements.floating).document.documentElement.clientWidth; + const left = Math.max(EDGE, (boundary?.left ?? 0) + EDGE); + const right = Math.min(viewportWidth - EDGE, (boundary?.right ?? viewportWidth) - EDGE); + 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, boundaryRef, 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 = plot.width < PINNED_BELOW_PLOT_WIDTH; + const popupRef = React.useRef(null); + const getBoundary = React.useCallback( + () => boundaryRef?.current ?? chartBoxRef.current ?? undefined, + [boundaryRef, chartBoxRef], + ); + // eslint-disable-next-line react/refs -- The middleware reads the boundary refs when floating-ui computes a position, not during render. + const middleware = React.useMemo(() => tooltipMiddleware(getBoundary, pinned), [getBoundary, pinned]); + + const [lastSide, setLastSide] = React.useState('right'); + 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 chart = chartBoxRef.current; + if (anchorX === undefined || anchorY === undefined || !chart || chartWidth <= 0) { + return; + } + const getBoundingClientRect = () => { + const chartRect = chart.getBoundingClientRect(); + if (pinned) { + const boundary = getBoundary()?.getBoundingClientRect() ?? chartRect; + return new DOMRect(boundary.left + EDGE, boundary.top + EDGE, 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: chart }); + }, [anchorX, anchorY, chartBoxRef, chartWidth, getBoundary, 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/bar-chart/bar-chart-x-axis.tsx b/packages/mosaic/src/primitives/chart/chart-x-axis.tsx similarity index 71% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-x-axis.tsx rename to packages/mosaic/src/primitives/chart/chart-x-axis.tsx index b8c14cdc9ad..afb0ac78b45 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-x-axis.tsx +++ b/packages/mosaic/src/primitives/chart/chart-x-axis.tsx @@ -3,11 +3,10 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { hasArea, useBarChartContext } from './bar-chart-context'; -import type { XTickMode } from './use-bar-chart'; -import type { XTick } from './x-ticks'; +import { hasArea, useChartContext } from './chart-context'; +import type { XTick, XTickMode } from './types'; -export type BarChartXAxisProps = Omit, 'children' | 'format'> & { +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' @@ -15,15 +14,15 @@ export type BarChartXAxisProps = Omit, 'children' | 'forma 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 `BarChart.XTick` per entry. */ + /** Renders the labels, usually one `Chart.XTick` per entry. */ children?: (ticks: readonly XTick[]) => React.ReactNode; }; const formatCategory = (value: string) => value; -export const BarChartXAxis = React.forwardRef(function BarChartXAxis(props, ref) { +export const ChartXAxis = React.forwardRef(function ChartXAxis(props, ref) { const { ticks = 'category', format = formatCategory, children, render, ...otherProps } = props; - const { chart } = useBarChartContext('XAxis'); + const { chart } = useChartContext('XAxis'); const { size, xTicks: getXTicks } = chart; const xTicks = React.useMemo(() => getXTicks({ mode: ticks, format }), [format, getXTicks, ticks]); diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-x-tick.tsx b/packages/mosaic/src/primitives/chart/chart-x-tick.tsx similarity index 66% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-x-tick.tsx rename to packages/mosaic/src/primitives/chart/chart-x-tick.tsx index 87a514a52a9..589d01917a5 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-x-tick.tsx +++ b/packages/mosaic/src/primitives/chart/chart-x-tick.tsx @@ -3,17 +3,17 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { useBarChartContext } from './bar-chart-context'; -import type { XTick } from './x-ticks'; +import { useChartContext } from './chart-context'; +import type { XTick } from './types'; -export type BarChartXTickProps = ComponentProps<'text'> & { - /** An entry from the `BarChart.XAxis` children function. */ +export type ChartXTickProps = ComponentProps<'text'> & { + /** An entry from the `Chart.XAxis` children function. */ tick: XTick; }; -export const BarChartXTick = React.forwardRef(function BarChartXTick(props, ref) { +export const ChartXTick = React.forwardRef(function ChartXTick(props, ref) { const { tick, render, ...otherProps } = props; - const { chart } = useBarChartContext('XTick'); + const { chart } = useChartContext('XTick'); const activeCategory = chart.selected?.category ?? null; const ownProps = { diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-y-axis.tsx b/packages/mosaic/src/primitives/chart/chart-y-axis.tsx similarity index 67% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-y-axis.tsx rename to packages/mosaic/src/primitives/chart/chart-y-axis.tsx index 704fd187402..3df9588e3e2 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-y-axis.tsx +++ b/packages/mosaic/src/primitives/chart/chart-y-axis.tsx @@ -3,26 +3,26 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { hasArea, useBarChartContext } from './bar-chart-context'; +import { hasArea, useChartContext } from './chart-context'; -export interface BarChartYTickItem { +export interface ChartYTickItem { value: number; y: number; label: React.ReactNode; } -export type BarChartYAxisProps = Omit, 'children' | 'format'> & { +export type ChartYAxisProps = Omit, 'children' | 'format'> & { /** Formats a tick value. Default: the locale number */ format?: (value: number) => React.ReactNode; - /** Renders the labels, usually one `BarChart.YTick` per entry. */ - children?: (ticks: readonly BarChartYTickItem[]) => 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 BarChartYAxis = React.forwardRef(function BarChartYAxis(props, ref) { +export const ChartYAxis = React.forwardRef(function ChartYAxis(props, ref) { const { format = formatNumber, children, render, ...otherProps } = props; - const { chart } = useBarChartContext('YAxis'); + const { chart } = useChartContext('YAxis'); const { size, yTicks } = chart; const ticks = React.useMemo( () => yTicks.map(tick => ({ value: tick.value, y: tick.y, label: format(tick.value) })), 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..aa77ca28af9 --- /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 { useChartContext } 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 } = useChartContext('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/bar-chart/bar-chart-y-tick.tsx b/packages/mosaic/src/primitives/chart/chart-y-tick.tsx similarity index 52% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-y-tick.tsx rename to packages/mosaic/src/primitives/chart/chart-y-tick.tsx index 61fd69e9559..e42f71a8958 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-y-tick.tsx +++ b/packages/mosaic/src/primitives/chart/chart-y-tick.tsx @@ -3,17 +3,17 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { useBarChartContext } from './bar-chart-context'; -import type { BarChartYTickItem } from './bar-chart-y-axis'; +import { useChartContext } from './chart-context'; +import type { ChartYTickItem } from './chart-y-axis'; -export type BarChartYTickProps = ComponentProps<'text'> & { - /** An entry from the `BarChart.YAxis` children function. */ - tick: BarChartYTickItem; +export type ChartYTickProps = ComponentProps<'text'> & { + /** An entry from the `Chart.YAxis` children function. */ + tick: ChartYTickItem; }; -export const BarChartYTick = React.forwardRef(function BarChartYTick(props, ref) { +export const ChartYTick = React.forwardRef(function ChartYTick(props, ref) { const { tick, render, ...otherProps } = props; - const { chart } = useBarChartContext('YTick'); + const { chart } = useChartContext('YTick'); const ownProps = { x: chart.plot.x - 12, diff --git a/packages/mosaic/src/primitives/chart/index.ts b/packages/mosaic/src/primitives/chart/index.ts new file mode 100644 index 00000000000..ae189560567 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/index.ts @@ -0,0 +1,30 @@ +export * as Chart from './parts'; + +export type { + ChartCursorProps, + ChartGridProps, + ChartRootProps, + ChartSelectionProps, + ChartTooltipProps, + ChartXAxisProps, + ChartXTickProps, + ChartYAxisProps, + ChartYLineProps, + ChartYTickItem, + ChartYTickProps, +} from './parts'; +export type { + ChartActive, + ChartCategory, + ChartInstance, + ChartInteractionProps, + ChartMargin, + ChartOptions, + ChartPlot, + ChartSelection, + ChartSize, + ChartTick, + XTick, + XTickMode, + XTicksOptions, +} from './types'; diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/calendar-ticks.test.ts b/packages/mosaic/src/primitives/chart/internal/__tests__/calendar-ticks.test.ts similarity index 77% rename from packages/mosaic/src/primitives/bar-chart/__tests__/calendar-ticks.test.ts rename to packages/mosaic/src/primitives/chart/internal/__tests__/calendar-ticks.test.ts index 40a8964e93e..a584691489c 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/calendar-ticks.test.ts +++ b/packages/mosaic/src/primitives/chart/internal/__tests__/calendar-ticks.test.ts @@ -9,13 +9,17 @@ 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) => - selectCalendarTicks({ +const axis = (timestamps: readonly number[], width: number) => { + const plot = { x: 76, width: width - 92 }; + const step = plot.width / timestamps.length; + return selectCalendarTicks({ timestamps, - plot: { x: 76, width: width - 92 }, + 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', () => { @@ -55,6 +59,24 @@ describe('calendar boundaries', () => { }); }); +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)) }, diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/x-ticks.test.ts b/packages/mosaic/src/primitives/chart/internal/__tests__/x-ticks.test.ts similarity index 100% rename from packages/mosaic/src/primitives/bar-chart/__tests__/x-ticks.test.ts rename to packages/mosaic/src/primitives/chart/internal/__tests__/x-ticks.test.ts diff --git a/packages/mosaic/src/primitives/bar-chart/calendar-ticks.ts b/packages/mosaic/src/primitives/chart/internal/calendar-ticks.ts similarity index 81% rename from packages/mosaic/src/primitives/bar-chart/calendar-ticks.ts rename to packages/mosaic/src/primitives/chart/internal/calendar-ticks.ts index 06a4372b1e0..b8d4c515546 100644 --- a/packages/mosaic/src/primitives/bar-chart/calendar-ticks.ts +++ b/packages/mosaic/src/primitives/chart/internal/calendar-ticks.ts @@ -2,6 +2,8 @@ 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; @@ -28,7 +30,7 @@ export function parseCalendarDates(indexes: readonly string[]): number[] | null return timestamps; } -function coordinateAt(timestamp: number, timestamps: readonly number[], plot: CalendarAxis['plot']): number { +function coordinateAt(timestamp: number, timestamps: readonly number[], centers: readonly number[]): number { let low = 0; let high = timestamps.length; while (low < high) { @@ -43,8 +45,12 @@ function coordinateAt(timestamp: number, timestamps: readonly number[], plot: Ca const left = Math.max(0, right - 1); const leftDate = timestamps[left] ?? timestamp; const rightDate = timestamps[right] ?? timestamp; - const offset = rightDate === leftDate ? right : left + (timestamp - leftDate) / (rightDate - leftDate); - return plot.x + ((offset + 0.5) / timestamps.length) * plot.width; + 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[] { @@ -63,7 +69,13 @@ function monthBoundaries(first: number, last: number, step: number): Date[] { return result; } -export function selectCalendarTicks({ timestamps, plot, viewportWidth, measure }: CalendarAxis): CalendarTick[] { +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) { @@ -74,7 +86,7 @@ export function selectCalendarTicks({ timestamps, plot, viewportWidth, measure } const ticks = monthBoundaries(first, last, step) .map(date => ({ label: monthLabel.format(date), - coordinate: coordinateAt(date.getTime(), timestamps, plot), + coordinate: coordinateAt(date.getTime(), timestamps, centers), })) .filter(tick => { const halfWidth = measure(tick.label) / 2; diff --git a/packages/mosaic/src/primitives/bar-chart/chart-selection.ts b/packages/mosaic/src/primitives/chart/internal/selection.ts similarity index 97% rename from packages/mosaic/src/primitives/bar-chart/chart-selection.ts rename to packages/mosaic/src/primitives/chart/internal/selection.ts index e9d65b6b955..e09a3a14dc7 100644 --- a/packages/mosaic/src/primitives/bar-chart/chart-selection.ts +++ b/packages/mosaic/src/primitives/chart/internal/selection.ts @@ -1,4 +1,4 @@ -import type { ChartCategory, ChartSelection } from './types'; +import type { ChartActive, ChartCategory, ChartSelection } from '../types'; export type VerticalMove = 'up' | 'down'; @@ -8,7 +8,7 @@ export type VerticalMove = 'up' | 'down'; */ export type SelectionModel< TSelection extends ChartSelection, - TActive, + TActive extends ChartActive, TCategory extends ChartCategory = ChartCategory, > = Readonly<{ /** The selection under a pointer at plot-space `y` over `category`. `current` lets a model hold its pick near a boundary. */ @@ -166,7 +166,7 @@ export function getKeyIntent(key: string, index: number, lastIndex: number, canA export function getKeyboardAnnouncement( selected: Selected | null, category: TCategory | undefined, - model: Pick, 'describe' | 'land'>, + model: Pick, 'describe' | 'land'>, formatCategory: (category: string) => string | null, ) { if (selected?.source !== 'keyboard') { diff --git a/packages/mosaic/src/primitives/bar-chart/use-chart-instance.ts b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts similarity index 82% rename from packages/mosaic/src/primitives/bar-chart/use-chart-instance.ts rename to packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts index ed11f0b86ca..f658c29efe0 100644 --- a/packages/mosaic/src/primitives/bar-chart/use-chart-instance.ts +++ b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts @@ -2,7 +2,21 @@ import React from 'react'; -import { useControllableState } from '../hooks/use-controllable-state'; +import { useControllableState } from '../../hooks/use-controllable-state'; +import type { + ChartActive, + ChartCategory, + ChartInstance, + ChartInteractionProps, + ChartMargin, + ChartOptions, + ChartPlot, + ChartSelection, + ChartSize, + ChartTick, + XTick, + XTicksOptions, +} from '../types'; import { getKeyboardAnnouncement, getKeyboardInstructions, @@ -18,10 +32,9 @@ import { type SelectionState, toPublicSelection, type VerticalMove, -} from './chart-selection'; -import type { ChartCategory, ChartMargin, ChartPlot, ChartSelection, ChartSize, ChartTick } from './types'; +} from './selection'; import { useChartSize } from './use-chart-size'; -import { selectXTicks, type XTick } from './x-ticks'; +import { selectXTicks } from './x-ticks'; export const DEFAULT_CHART_MARGIN: ChartMargin = { top: 8, @@ -30,52 +43,10 @@ export const DEFAULT_CHART_MARGIN: ChartMargin = { left: 52, }; -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 = Readonly<{ - role: 'button' | 'group'; - /** 0 while something reads the selection: `selection`, `onSelectionChange` or `onActivate`. */ - tabIndex: 0 | undefined; - onPointerDown: React.PointerEventHandler; - onPointerLeave: React.PointerEventHandler; - onPointerCancel: React.PointerEventHandler; - onPointerMove: React.PointerEventHandler; - onFocus: React.FocusEventHandler; - onBlur: React.FocusEventHandler; - onClick: React.MouseEventHandler; - onKeyDown: React.KeyboardEventHandler; - /** State the chart type exposes on the surface, such as `data-active-section`. */ - [attribute: `data-${string}`]: string | undefined; -}>; - -/** 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; - /** Called when the user or `select`/`clear` changes the selection. */ - onSelectionChange?: (selection: TSelection | null) => void; - /** Called on click, Enter or Space. Makes the interaction surface a button. */ - onActivate?: (active: TActive) => void; - /** Names a category in announcements. Default: the category key */ - formatCategory?: (category: string) => string | null; -} - /** What a chart type's layout gives the shared instance. */ export type ChartLayout = Readonly<{ plot: ChartPlot; + scaleY: (value: number) => number; yTicks: readonly ChartTick[]; categories: readonly TCategory[]; }>; @@ -149,7 +120,11 @@ const formatCategoryKey = (category: string) => category; * 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({ +export function useChartInstance< + TSelection extends ChartSelection, + TActive extends ChartActive, + TCategory extends ChartCategory, +>({ frame, layout, model, @@ -159,7 +134,7 @@ export function useChartInstance; model: SelectionModel; options: ChartOptions; -}>) { +}>): ChartInstance { const { onActivate, formatCategory = formatCategoryKey } = options; const { rootRef, rootElementRef, size } = frame; const { categories, plot } = layout; @@ -360,6 +335,7 @@ export function useChartInstance; const EDGE_INSET = 4; const TARGET_SPACING = 56; const MIN_LABEL_GAP = 8; -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'; -}>; - type Plot = Readonly<{ x: number; width: number }>; type SelectXTicksOptions = Readonly<{ @@ -120,6 +113,7 @@ export function selectXTicks(options: SelectXTicksOptions): XTick[] { const calendarTicks = timestamps ? selectCalendarTicks({ timestamps, + centers: options.categories.map(category => category.center), plot: options.plot, viewportWidth: options.viewportWidth, measure, 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..3e7a823bda4 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/line-chart-contract.test-d.ts @@ -0,0 +1,62 @@ +import { describe, expectTypeOf, test } from 'vitest'; + +import type { BarChartInstance } from '../bar-chart'; +import type { SelectionModel } from './internal/selection'; +import type { useChartInstance } from './internal/use-chart-instance'; +import type { ChartRootProps, ChartTooltipProps } from './parts'; +import type { ChartActive, ChartCategory, ChartInstance, ChartSelection } from './types'; + +// A line chart sketched in types only, to prove the shared contract fits a second chart type before +// `line-chart/` exists. Its categories are points, and it selects a category and nothing else. + +type Row = Readonly<{ date: string; users: number }>; + +declare const LINE_LAYOUT: unique symbol; + +type LineChartInstance = ChartInstance, ChartSelection> & + Readonly<{ [LINE_LAYOUT]: Readonly<{ lines: readonly Readonly<{ key: string; d: string }>[] }> }>; + +const point = { key: '2026-01-05', datumIndex: 0, center: 120, x: 120, width: 0 } satisfies ChartCategory; + +const lineModel = { + hitTest: category => ({ category: category.key }), + land: category => ({ category: category.key }), + resolve: (selection, category) => ({ + category: selection.category, + datumIndex: category.datumIndex, + datum: { date: category.key, users: 0 }, + }), + describe: () => 'users', + verticalInstructions: '', + anchorY: () => 0, + surfaceAttributes: () => ({}), +} satisfies SelectionModel>; + +describe('a line chart 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 a line instance from it', () => { + expectTypeOf, ChartCategory>>>().toEqualTypeOf< + ChartInstance, ChartSelection> + >(); + }); + + test('Chart.Root takes a line chart and a bar chart without a cast', () => { + 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..2ada85cf95b --- /dev/null +++ b/packages/mosaic/src/primitives/chart/parts.ts @@ -0,0 +1,10 @@ +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'; diff --git a/packages/mosaic/src/primitives/chart/types.ts b/packages/mosaic/src/primitives/chart/types.ts new file mode 100644 index 00000000000..4245dd44f58 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/types.ts @@ -0,0 +1,123 @@ +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 }>; + +/** + * 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 }>; + +/** 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; + /** Called when the user or `select`/`clear` changes the selection. */ + onSelectionChange?: (selection: TSelection | null) => void; + /** Called on click, Enter or Space. Makes the interaction surface a button. */ + onActivate?: (active: TActive) => void; + /** Names a category in announcements. Default: the category key */ + formatCategory?: (category: string) => string | null; +} + +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 = Readonly<{ + role: 'button' | 'group'; + /** 0 while something reads the selection: `selection`, `onSelectionChange` or `onActivate`. */ + tabIndex: 0 | undefined; + onPointerDown: React.PointerEventHandler; + onPointerLeave: React.PointerEventHandler; + onPointerCancel: React.PointerEventHandler; + onPointerMove: React.PointerEventHandler; + onFocus: React.FocusEventHandler; + onBlur: React.FocusEventHandler; + onClick: React.MouseEventHandler; + onKeyDown: React.KeyboardEventHandler; + /** State the chart type exposes on the surface, such as `data-active-section`. */ + [attribute: `data-${string}`]: string | undefined; +}>; + +/** + * The measured layout and selection of one chart, returned by a chart-type hook such as + * `BarChart.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; + scaleY: (value: number) => number; + yTicks: readonly ChartTick[]; + 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: Readonly<{ x: number; y: number }> | 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: () => ChartInteractionProps; +}>; diff --git a/packages/swingset/src/stories/bar-chart.stories.tsx b/packages/swingset/src/stories/bar-chart.stories.tsx index 39fcc6b2cdd..889e9808c8d 100644 --- a/packages/swingset/src/stories/bar-chart.stories.tsx +++ b/packages/swingset/src/stories/bar-chart.stories.tsx @@ -1,6 +1,7 @@ 'use client'; -import { BarChart } from '@clerk/mosaic/primitives/bar-chart'; +import { type ActiveBar, BarChart } from '@clerk/mosaic/primitives/bar-chart'; +import { Chart } from '@clerk/mosaic/primitives/chart'; import type { StoryMeta } from '@/lib/types'; @@ -34,49 +35,49 @@ const getWeek = (row: GrowthRow) => row.week; export function Default() { const chart = BarChart.useBarChart({ data: growth, series, index: getWeek }); return ( - - - {lines => - lines.map(line => ( - + {ticks => + ticks.map(tick => ( + )) } - + - + - + {ticks => ticks.map(tick => ( - )) } - - + + {ticks => ticks.map(tick => ( - )) } - - - - > + + + + >> {({ datum }) => ( <>

{datum.week}

@@ -87,8 +88,8 @@ export function Default() { ))} )} - -
-
+ +
+
); } From 347e0cf5328811a7fc4709a5243da16ec92ca85e Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 07:38:34 -0700 Subject: [PATCH 13/40] docs(mosaic,swingset): document the Chart parts and the BarChart marks primitives/chart/README.md documents the shared parts, the chart object, selection, keyboard, tooltip and paint order. The bar-chart README keeps what bars own: useBarChart, the marks, sections, Canvas styling and layout. The Swingset page moves to Chart.* names and stays one raw Default story. --- .../mosaic/src/primitives/bar-chart/README.md | 223 ++++----------- .../mosaic/src/primitives/chart/README.md | 254 ++++++++++++++++++ packages/swingset/src/stories/bar-chart.mdx | 142 +++++----- 3 files changed, 376 insertions(+), 243 deletions(-) create mode 100644 packages/mosaic/src/primitives/chart/README.md diff --git a/packages/mosaic/src/primitives/bar-chart/README.md b/packages/mosaic/src/primitives/bar-chart/README.md index eda71496f38..14cf37d5138 100644 --- a/packages/mosaic/src/primitives/bar-chart/README.md +++ b/packages/mosaic/src/primitives/bar-chart/README.md @@ -1,96 +1,87 @@ # Bar chart -A headless stacked bar chart: a hook that owns the layout and selection, and composable parts that render from it. D3 computes the diverging stacks and scales, Canvas paints the bars and the projection fill, one SVG over the Canvas draws the grid, axes, zero line and projection outline, and React handles interaction. The parts emit no visual styles: style each one with `className` and `data-*` attributes. +A headless stacked bar chart: `BarChart.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`. The root, grid, axes, selection, cursor and tooltip are the shared [`Chart`](../chart/README.md) parts. The parts emit no visual styles: style each one with `className` and `data-*` attributes. ## 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. -- A decorative placeholder chart: leave out `BarChart.BarSelection`. +- A decorative placeholder chart: leave out `Chart.Selection`. ## Usage ```tsx -import { BarChart } from '@clerk/mosaic/primitives/bar-chart'; +import { type ActiveBar, BarChart } from '@clerk/mosaic/primitives/bar-chart'; +import { Chart } from '@clerk/mosaic/primitives/chart'; const chart = BarChart.useBarChart({ data, series, index, onActivate: openPeriod }); - - - {lines => - lines.map(line => ( - + {ticks => + ticks.map(tick => ( + )) } - + - + - + {ticks => ticks.map(tick => ( - )) } - - + + {ticks => ticks.map(tick => ( - )) } - - - - {active => } - -; + + + + > 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. -A container renders only the items its children function returns. A bare `` renders an empty SVG. - ## Parts -| Part | Default element | Description | -| ---------------------------- | --------------- | -------------------------------------------------------------------- | -| `BarChart.Root` | `
` | Attaches the chart's measurement and provides the chart to the parts | -| `BarChart.Grid` | `` | Holds the grid lines | -| `BarChart.GridLine` | `` | One line across the plot at a Y tick | -| `BarChart.StackedBars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | -| `BarChart.Bar` | `` | Hidden. Its computed style paints the bars | -| `BarChart.ProjectionOutline` | `` | Outlines the projected bar | -| `BarChart.ZeroLine` | `` | The line at zero | -| `BarChart.YAxis` | `` | Holds the Y tick labels in the left margin | -| `BarChart.YTick` | `` | One Y tick label | -| `BarChart.XAxis` | `` | Holds the category labels below the plot | -| `BarChart.XTick` | `` | One category label | -| `BarChart.BarSelection` | `
` | Pointer and keyboard selection over the whole chart | -| `BarChart.Cursor` | `
` | Covers the selected category's band | -| `BarChart.Tooltip` | `
` | The tooltip for the selected bar, 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 `BarChart.Root`. `BarChart.Bar`, `BarChart.ProjectionOutline` and `BarChart.ZeroLine` live inside `BarChart.StackedBars`, and `BarChart.Bar` and `BarChart.ProjectionOutline` throw outside it. `BarChart.Cursor` and `BarChart.Tooltip` throw outside `BarChart.BarSelection`. +| Part | Default element | Description | +| ---------------------------- | --------------- | ------------------------------------------------------------------- | +| `BarChart.StackedBars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | +| `BarChart.Bar` | `` | Hidden. Its computed style paints the bars | +| `BarChart.ProjectionOutline` | `` | Outlines the projected bar | + +Every part takes `className`, `ref`, `render` and the native props of its default element, merged as the [`Chart` parts](../chart/README.md#parts) are. + +`BarChart.StackedBars` throws outside `Chart.Root`, and throws when the chart did not come from `BarChart.useBarChart`. `BarChart.Bar` and `BarChart.ProjectionOutline` throw outside `BarChart.StackedBars`. A `Chart.YLine` inside `BarChart.StackedBars`, such as the zero line, paints over the bars. The namespace also holds `BarChart.useBarChart` and `BarChart.CanvasRenderError`. @@ -112,86 +103,19 @@ The namespace also holds `BarChart.useBarChart` and `BarChart.CanvasRenderError` | `onActivate` | `(active: ActiveBar) => void` | — | Called on click, Enter or Space. Makes the surface a button | | `formatCategory` | `(key: string) => string \| null` | the key | Names a period in keyboard announcements | -`BarSelection` is `{ category, section }`. A new `isBarActive` function repaints the Canvas. - -The hook returns a `BarChartInstance`, the chart object: - -| Field | Type | Description | -| ----------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------- | -| `rootRef` | `(element: HTMLElement \| null) => void` | Measures the element. `BarChart.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` | Maps a value to a Y coordinate | -| `zeroY` | `number` | The Y coordinate of zero | -| `categories` | `readonly BarCategory[]` | One band per row, with its selectable sections | -| `yTicks` | `readonly ChartTick[]` | The Y ticks | -| `xTicks` | `(options?: { mode?, format? }) => XTick[]` | The X labels for a tick mode, as `BarChart.XAxis` computes them | -| `projection` | `{ datumIndex, x, y, width, height } \| null` | The accepted projection's band rectangle | -| `selected` | `ActiveBar \| null` | The selected bar in the current data | -| `announcement` | `string` | The status text for the keyboard selection | -| `select`, `clear` | `(selection: BarSelection) => void`, `() => void` | Change the selection and call `onSelectionChange` | -| `getInteractionProps()` | `BarChartInteractionProps` | Role, `tabIndex`, `data-active-section` and the pointer, focus and key handlers | - -The object also carries `isBarActive` and the layout internals `prepared` and `step`. - -### `BarChart.Root` - -| Prop | Type | Default | Description | -| ------------ | -------------------------- | ---------- | ------------------------------------------------- | -| `chart` | `BarChartInstance` | (required) | The result of `BarChart.useBarChart` | -| `aria-label` | `string` | (required) | Labels the bars image and the interaction surface | -| `height` | `number \| string` | `500` | The container height | - -### `BarChart.Grid`, `BarChart.YAxis`, `BarChart.XAxis` - -| Part | Prop | Type | Default | Description | -| ---------------- | ---------- | ------------------------------------------- | ------------- | ---------------------------------------------------------------------------------------------- | -| `BarChart.Grid` | `children` | `(lines: ChartTick[]) => ReactNode` | — | Renders the lines | -| `BarChart.YAxis` | `format` | `(value: number) => ReactNode` | locale number | Formats a tick value | -| `BarChart.YAxis` | `children` | `(ticks: BarChartYTickItem[]) => ReactNode` | — | Renders the labels | -| `BarChart.XAxis` | `ticks` | `'category' \| 'calendar'` | `'category'` | `category` thins labels to fit. `calendar` labels calendar boundaries for long UTC date ranges | -| `BarChart.XAxis` | `format` | `(key: string) => string \| null` | the key | Labels a category, or returns null to omit it | -| `BarChart.XAxis` | `children` | `(ticks: XTick[]) => ReactNode` | — | Renders the labels | - -`BarChart.GridLine`, `BarChart.YTick` and `BarChart.XTick` each take the entry their container passed: `line` (`{ value, y }`) or `tick` (`{ 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. - -`BarChart.StackedBars` and `BarChart.BarSelection` take only the props of their element. `isBarActive`, `onActivate` and `formatCategory` are `useBarChart` options. - -### `BarChart.Tooltip` - -| Prop | Type | Default | Description | -| ------------- | ------------------------------------------ | --------- | ------------------------------------------------------------- | -| `children` | `(active: ActiveBar) => ReactNode` | — | Content for the selected bar. Return null to hide the tooltip | -| `boundaryRef` | `RefObject` | the chart | Element the tooltip stays inside | - -`ActiveBar` is the selected period: its `category`, `datumIndex`, `datum` and `section`, which sections have values (`hasValues`), and whether the chart draws the projection there (`projected`). - -## Keyboard +`BarSelection` is `{ category, section }`. A new `isBarActive` function repaints the Canvas. `margin` and the last four options are the [options every chart type takes](../chart/README.md#options-every-chart-type-takes). -The interaction surface is focusable while something reads the selection: `selection`, `onSelectionChange` or `onActivate` on `useBarChart`, or a `BarChart.Tooltip`. +The hook returns a `BarChartInstance`: the [chart object](../chart/README.md#the-chart-object) with `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. -| Key | Behavior | -| ------------------------ | ------------------------------------------------------------------------ | -| `ArrowLeft`/`ArrowRight` | Selects the previous or next period | -| `Home`/`End` | Selects the first or last period | -| `ArrowUp`/`ArrowDown` | Selects the positive or negative section of the period | -| `Enter`/`Space` | Calls `onActivate`. After `Escape`, reselects the dismissed period first | -| `Escape` | Clears the selection and remembers the period | +`ActiveBar` is the selected period: its `category`, `datumIndex`, `datum` and `section`, plus `hasValues` and `projected`. Name it on the tooltip: `>>`. -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. +## Keyboard and selection -A pointer selects the period under it. A tap selects on contact and stays selected until the user taps elsewhere or the gesture is cancelled. +Selection follows [`Chart`](../chart/README.md#keyboard). 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. A pointer selects the section above or below the zero line, and keeps the current section within a few pixels of it. -## Selection +The interaction surface carries `data-active-section`, `positive` or `negative` while a section is selected. The status region announces the period and its section, such as `Feb, positive values`, or `No values for this period`. -The chart holds the selection unless you pass `selection`. `onSelectionChange` is called with `{ category, section }` or null whenever a pointer move, a key, a focus change, `select` or `clear` changes it, in both modes. It is not called when data changes: `chart.selected` resolves the selection against the current data, so a selection whose category or section disappears reads as null until the user moves. - -A controlled `selection` decides which bar 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. +Dim every bar outside the selected section by controlling the selection: ```tsx const [selection, setSelection] = useState(null); @@ -203,51 +127,14 @@ const isBarActive = useCallback( const chart = BarChart.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, 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 = BarChart.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 object does not do, because their color and geometry come from `BarChart.Bar`'s computed style: keep `BarChart.StackedBars` for that. - -## Data attributes - -| Attribute | Part | Description | -| ----------------------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------- | -| `data-chart-interaction-mode` | `BarChart.Root` | `pending` before the first measurement, `interactive` with `BarChart.BarSelection` and categories, otherwise `visual-only` | -| `data-active` | `BarChart.XTick` | Present while the tick's period is selected. Calendar boundary labels never carry it | -| `data-chart-interaction` | `BarChart.BarSelection` | On the interaction surface inside the part | -| `data-active-section` | `BarChart.BarSelection` | On the interaction surface: `positive` or `negative` while a section is selected | -| `data-side` | `BarChart.Tooltip` | `left` or `right` of the selected period, or `bottom` when pinned to the top of a narrow chart | -| `data-open` / `data-closed` | `BarChart.Tooltip` | The tooltip's open state, with `data-starting-style` and `data-ending-style` during transitions | +Painting the bars is the one thing the chart object does not do, because their color and geometry come from `BarChart.Bar`'s computed style: keep `BarChart.StackedBars` for that. ## Accessibility -- The bars Canvas carries `role="img"` and the `aria-label` from `BarChart.Root`. The grid, axes, cursor and marks 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`. -- Visually hidden text describes the keys. A `status` region announces the selected period, named through `formatCategory`, and its section. -- An assistive-technology click without coordinates activates the selected period. +The bars Canvas carries `role="img"` and the `aria-label` from `Chart.Root`. The projection outline is `aria-hidden`. The rest is in [`Chart`](../chart/README.md#accessibility). ## 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. - ### `BarChart.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. `BarChart.Bar` renders one `aria-hidden` ``. Before each paint, `BarChart.StackedBars` puts it in every state it draws, reads its computed `color`, caches it per state, paints, then restores the element: @@ -293,27 +180,9 @@ The geometry is paint only. Selection, the cursor and the scales use the categor The Canvas repaints in the same frame when `BarChart.Bar` mounts, unmounts or changes `class`, when `` changes `class`, `style` or `data-theme`, when the pixel ratio changes (capped at 2), and when the layout or the props of `BarChart.StackedBars` change. 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. -The primitive reads and writes no CSS variables. - -### Inline styles - -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 `BarChart.BarSelection` reaches the interaction surface. - ## Paint order -Root does not reorder its children, so paint order is JSX order. Write the parts in this order: - -1. `BarChart.Grid` -2. `BarChart.StackedBars`, with `BarChart.ProjectionOutline` before `BarChart.ZeroLine`. The position of `BarChart.Bar` does not matter -3. `BarChart.YAxis` -4. `BarChart.XAxis` -5. `BarChart.BarSelection`, last, so its surface receives the pointer and its cursor paints over the bars - -Each container renders nothing until Root has measured a non-zero size. - -## Tooltip - -`BarChart.Tooltip` positions with Floating UI against a virtual element at the selected period: the band center, at the top of the plot. It opens to the right, flips left when the right side does not fit inside `boundaryRef`, and keeps the side it chose last until that side stops fitting, so it does not cross the bar twice near an edge. 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. +Follow [`Chart`'s paint order](../chart/README.md#paint-order). Inside `BarChart.StackedBars`, put `BarChart.ProjectionOutline` before the zero `Chart.YLine`. The position of `BarChart.Bar` does not matter. ## Layout diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md new file mode 100644 index 00000000000..6207c658163 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/README.md @@ -0,0 +1,254 @@ +# Chart + +The headless parts every chart type shares: the root, grid, axes, Y lines, and pointer and keyboard selection with its cursor and tooltip. A chart-type hook, such as `BarChart.useBarChart` ([`bar-chart/`](../bar-chart/README.md)), owns the layout and selection and returns a chart object. `Chart.Root` takes any chart object, and the shared parts render from it. The parts emit no visual styles: style each one with `className` and `data-*` attributes. + +## When to use + +- 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`. + +`Chart` draws no data. Its marks come from the chart type, such as `BarChart.StackedBars`. + +## Usage + +```tsx +import { type ActiveBar, BarChart } from '@clerk/mosaic/primitives/bar-chart'; +import { Chart } from '@clerk/mosaic/primitives/chart'; + +const chart = BarChart.useBarChart({ data, series, index, onActivate: openPeriod }); + + + + {ticks => + ticks.map(tick => ( + + )) + } + + + + + + + {ticks => + ticks.map(tick => ( + + )) + } + + + {ticks => + ticks.map(tick => ( + + )) + } + + + + > className='tooltip'>{active => } + +; +``` + +A container renders only the items its children function returns. A bare `` renders an empty SVG. + +## 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.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.Cursor` and `Chart.Tooltip` throw outside `Chart.Selection`. + +## 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 | + +`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 | +| `boundaryRef` | `RefObject` | the chart | Element the tooltip stays inside | + +Name the active type the chart's hook selects, such as `>>`. It defaults to `ChartActive`: the selected `category`, `datumIndex` and `datum`. + +## The chart object + +A chart-type hook returns a `ChartInstance` plus what its own marks need: + +| 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` | Maps a value to a Y coordinate | +| `yTicks` | `readonly ChartTick[]` | 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()` | `ChartInteractionProps` | Role, `tabIndex`, the chart type's `data-*` state and the event handlers | + +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. + +## 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 | +| `onActivate` | `(active: TActive) => void` | — | Called on click, Enter or Space. Makes the surface a button | +| `formatCategory` | `(key: string) => string \| null` | the key | Names a period in keyboard announcements | + +## 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 the category whose center is nearest. A tap selects on contact and stays selected until the user taps elsewhere or the gesture is cancelled. + +## Selection + +The chart holds the selection unless you pass `selection`. `onSelectionChange` is called whenever a pointer move, a key, a focus change, `select` or `clear` changes it, in both modes. It is not called when data changes: `chart.selected` resolves the selection against the current data, so a selection whose category disappears reads as null until the user moves. + +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. + +## Rendering from the chart object + +The parts are optional. Attach `rootRef` to the measured element, spread `getInteractionProps()` on the element that takes selection, 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 = BarChart.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. + +## 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-chart-interaction` | `Chart.Selection` | On the interaction surface inside the part | +| `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. + +## Accessibility + +- The chart type's marks carry `role="img"` and the `aria-label` from `Chart.Root`. The grid, axes, cursor and lines 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`. +- Visually hidden text describes the keys. A `status` region announces the selected period, named through `formatCategory`, and what the chart type adds. +- 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. + +## 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 `BarChart.StackedBars`, 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. + +## 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 to the right, flips left when the right side does not fit inside `boundaryRef`, and keeps the side it chose last until that side stops fitting, so it does not cross the selection twice near an edge. 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. + +## Adding a chart type + +A chart type lives in its own `src/primitives/-chart/` folder. Its hook measures with `useChartFrame`, lays out its categories, and passes a pure `SelectionModel` to `useChartInstance`, both from `chart/internal/`. Lint lets only `*-chart/` folders import `chart/internal/`. The model owns the hit test, where the keyboard lands, how a selection resolves against the data, the announcement and the tooltip's Y. Its marks read their own layout from a module-private symbol on the instance, as `BarChart.StackedBars` does. `line-chart-contract.test-d.ts` checks that a point chart fits the contract. diff --git a/packages/swingset/src/stories/bar-chart.mdx b/packages/swingset/src/stories/bar-chart.mdx index 9164e2b33a2..b54367ad537 100644 --- a/packages/swingset/src/stories/bar-chart.mdx +++ b/packages/swingset/src/stories/bar-chart.mdx @@ -3,10 +3,11 @@ import * as BarChartStories from './bar-chart.stories'; # BarChart A stacked bar chart over a category or time axis, with values above and below zero. It is a -**headless** primitive: `BarChart.useBarChart` owns the layout and selection, and the parts render -from the chart object it 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. +**headless** primitive: `BarChart.useBarChart` owns the layout and selection, `BarChart` parts paint +the bars, and the shared `Chart` 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 @@ -21,55 +22,56 @@ unstyled, so the bars take the inherited text color and the grid and zero lines ## Usage ```tsx -import { BarChart } from '@clerk/mosaic/primitives/bar-chart'; +import { type ActiveBar, BarChart } from '@clerk/mosaic/primitives/bar-chart'; +import { Chart } from '@clerk/mosaic/primitives/chart'; const chart = BarChart.useBarChart({ data, series, index, onActivate: openPeriod }); - - - {lines => - lines.map(line => ( - + {ticks => + ticks.map(tick => ( + )) } - + - + - + {ticks => ticks.map(tick => ( - )) } - - + + {ticks => ticks.map(tick => ( - )) } - - - - {active => } - -; + + + + >>{active => } + +; ``` `series` is an ordered list of `{ key, value }`, where `value` reads a number from a row. `index` @@ -109,25 +111,25 @@ const chart = BarChart.useBarChart({ | Part | Default Element | Description | | ---------------------------- | --------------- | -------------------------------------------------------------------- | -| `BarChart.Root` | `
` | Attaches the chart's measurement and provides the chart to the parts | -| `BarChart.Grid` | `` | Holds the grid lines | -| `BarChart.GridLine` | `` | One line across the plot at a Y tick | +| `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 | | `BarChart.StackedBars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | | `BarChart.Bar` | `` | Hidden. Its computed style paints the bars | | `BarChart.ProjectionOutline` | `` | Outlines the projected bar | -| `BarChart.ZeroLine` | `` | The line at zero | -| `BarChart.YAxis` | `` | Holds the Y tick labels | -| `BarChart.YTick` | `` | One Y tick label | -| `BarChart.XAxis` | `` | Holds the category labels | -| `BarChart.XTick` | `` | One category label | -| `BarChart.BarSelection` | `
` | Pointer and keyboard selection | -| `BarChart.Cursor` | `
` | Covers the selected category's band | -| `BarChart.Tooltip` | `
` | The tooltip for the selected bar, portaled | - +| `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 | + +`Chart` parts come from `@clerk/mosaic/primitives/chart` and work with any chart type's hook. Every part accepts a `render` prop and the standard attributes of its default element. Every part -throws outside `BarChart.Root`. `BarChart.Bar` and `BarChart.ProjectionOutline` throw outside -`BarChart.StackedBars`, and `BarChart.Cursor` and `BarChart.Tooltip` throw outside -`BarChart.BarSelection`. +throws outside `Chart.Root`, and `BarChart.StackedBars` also throws for a chart that did not come +from `BarChart.useBarChart`. `BarChart.Bar` and `BarChart.ProjectionOutline` throw outside +`BarChart.StackedBars`, and `Chart.Cursor` and `Chart.Tooltip` throw outside `Chart.Selection`. ## Props @@ -147,36 +149,44 @@ throws outside `BarChart.Root`. `BarChart.Bar` and `BarChart.ProjectionOutline` | 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`, `zeroY`, `categories`, -`yTicks`, `xTicks(options)`, `projection`, `selected`, `announcement`, `select`, `clear` and -`getInteractionProps()`. Render from it directly to skip the parts. +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. -### `BarChart.Root` +### `Chart.Root` -| Prop | Type | Default | Description | -| ----------------------- | ------------------------------------------- | ---------------- | ------------------------------------------------- | -| chart | BarChartInstance<TDatum> | — (required) | The result of `BarChart.useBarChart` | -| aria-label | string | — (required) | Labels the bars image and the interaction surface | -| height | number \| string | 500 | The container height | +| 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 | -### `BarChart.XAxis` +### `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 | -`BarChart.YAxis` takes `format` (`(value: number) => ReactNode`, locale number by default). -`BarChart.Grid`, `BarChart.YAxis` and `BarChart.XAxis` take a `children` function that receives -their items. `BarChart.GridLine` takes `line`, and `BarChart.YTick` and `BarChart.XTick` take -`tick`. +`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` -### `BarChart.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 | -| Prop | Type | Default | Description | -| ------------------------ | ----------------------------------------------------------- | ------------ | ------------------------------------------- | -| children | (active: ActiveBar<TDatum>) => 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 @@ -193,13 +203,13 @@ Its `max-width` caps the bar width, `row-gap` sets the gap between segments, its rounds a stack's outer end and its bottom corner radius rounds every other corner. Without `BarChart.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` | BarSelection | `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` | +| 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'] { From 093dcf69eb19710eb193d2eab37eafb18077061f Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 08:53:02 -0700 Subject: [PATCH 14/40] fix(mosaic): end a pointer or keyboard chart selection when its surface unmounts Unmounting Chart.Selection while a period was selected left the selection stuck: no pointerleave or blur fires on a removed element, so onSelectionChange never reported null and Chart.XTick kept data-active. The interaction props now carry a ref whose detach clears a pointer or keyboard selection. A selection set through selection or select stays. --- .../__tests__/bar-chart.browser.test.tsx | 65 +++++++++++++++++++ .../mosaic/src/primitives/chart/README.md | 32 ++++----- .../chart/internal/use-chart-instance.ts | 16 +++-- packages/mosaic/src/primitives/chart/types.ts | 2 + 4 files changed, 95 insertions(+), 20 deletions(-) diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx index 201eeb85011..4ec754eb325 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx @@ -264,3 +264,68 @@ describe('the tooltip', () => { 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/README.md b/packages/mosaic/src/primitives/chart/README.md index 6207c658163..dc2479e3533 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -128,21 +128,21 @@ Name the active type the chart's hook selects, such as ` 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` | Maps a value to a Y coordinate | -| `yTicks` | `readonly ChartTick[]` | 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()` | `ChartInteractionProps` | Role, `tabIndex`, the chart type's `data-*` state and the event handlers | +| 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` | Maps a value to a Y coordinate | +| `yTicks` | `readonly ChartTick[]` | 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()` | `ChartInteractionProps` | Role, `tabIndex`, `ref`, the chart type's `data-*` state and the event handlers | 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. @@ -176,6 +176,8 @@ A pointer selects the category whose center is nearest. A tap selects on contact The chart holds the selection unless you pass `selection`. `onSelectionChange` is called whenever a pointer move, a key, a focus change, `select` or `clear` changes it, in both modes. It is not called when data changes: `chart.selected` resolves the selection against the current data, so a selection whose category disappears reads as null until the user moves. +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. diff --git a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts index f658c29efe0..cd9c0c8c269 100644 --- a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts +++ b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts @@ -215,8 +215,15 @@ export function useChartInstance< dispatchRef.current({ type: 'clear' }); }, []); - // Only a pointer event on the surface makes a pointer selection, so its target is the surface. - const surfaceRef = React.useRef(null); + 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'; @@ -226,7 +233,7 @@ export function useChartInstance< } const dismissOutside = (event: PointerEvent) => { const surface = surfaceRef.current; - if (!(event.target instanceof Node) || !(surface instanceof Node) || !surface.contains(event.target)) { + if (!(event.target instanceof Node) || !surface?.contains(event.target)) { clear(); } }; @@ -276,9 +283,9 @@ export function useChartInstance< ...model.surfaceAttributes(currentSelection), role: onActivate ? 'button' : 'group', tabIndex: reads ? 0 : undefined, + ref: attachSurface, onPointerDown: event => { event.preventDefault(); - surfaceRef.current = event.currentTarget; // A tap fires no pointermove, so touch selects on contact and survives the pointerleave that // follows the finger lifting. if (event.pointerType !== 'touch') { @@ -296,7 +303,6 @@ export function useChartInstance< dispatch({ type: 'clear' }); }, onPointerMove: event => { - surfaceRef.current = event.currentTarget; pointerUpdates.schedule(pointerSelection(event.clientX, event.clientY), next => dispatch({ type: 'pointer', selection: next }), ); diff --git a/packages/mosaic/src/primitives/chart/types.ts b/packages/mosaic/src/primitives/chart/types.ts index 4245dd44f58..83bfe0f1661 100644 --- a/packages/mosaic/src/primitives/chart/types.ts +++ b/packages/mosaic/src/primitives/chart/types.ts @@ -78,6 +78,8 @@ export type ChartInteractionProps = Readonly<{ role: 'button' | 'group'; /** 0 while something reads the selection: `selection`, `onSelectionChange` or `onActivate`. */ tabIndex: 0 | undefined; + /** Removing the surface ends a pointer or keyboard selection, as leaving or blurring it does. */ + ref: React.RefCallback; onPointerDown: React.PointerEventHandler; onPointerLeave: React.PointerEventHandler; onPointerCancel: React.PointerEventHandler; From 037d5b1262c2bcb137bb8f8cdc8045cd6b7830c6 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 09:03:31 -0700 Subject: [PATCH 15/40] test(mosaic): check that the bar chart repaints on theme and pixel ratio changes Browser tests change the class on and the device pixel ratio, then read the painted Canvas: the new theme color, and a backing buffer at the new ratio capped at 2 with the bars repainted. Chromium's device emulation does not fire the resolution query's change event, so the test sends it. --- .../__tests__/bar-chart.browser.test.tsx | 56 ++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx index 4ec754eb325..4cc7d09ac29 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx @@ -1,8 +1,9 @@ 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 { page, userEvent } from 'vitest/browser'; +import { cdp, page, userEvent } from 'vitest/browser'; import type { BarSelection } from '../types'; import { TestChart, type TestChartProps } from './test-chart'; @@ -20,6 +21,7 @@ beforeAll(async () => { .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); } `; document.head.append(style); }); @@ -108,6 +110,58 @@ describe('painting', () => { 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 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 BarChart.Bar', async () => { await render(); const { x, y } = insideLastBar(); From 9a78f6715f7688f953f69f6fb29a0fb15f772141 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 09:07:13 -0700 Subject: [PATCH 16/40] docs(mosaic): note that emptied data ends a pointer or keyboard chart selection --- packages/mosaic/src/primitives/chart/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index dc2479e3533..f548a0b7b9b 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -174,7 +174,7 @@ A pointer selects the category whose center is nearest. A tap selects on contact ## Selection -The chart holds the selection unless you pass `selection`. `onSelectionChange` is called whenever a pointer move, a key, a focus change, `select` or `clear` changes it, in both modes. It is not called when data changes: `chart.selected` resolves the selection against the current data, so a selection whose category disappears reads as null until the user moves. +The chart holds the selection unless you pass `selection`. `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. From 5094e683c30dc15f4cb4188861b4994ce4842333 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 09:12:07 -0700 Subject: [PATCH 17/40] perf(mosaic): memoize the Chart.Root context value --- packages/mosaic/src/primitives/chart/chart-root.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/mosaic/src/primitives/chart/chart-root.tsx b/packages/mosaic/src/primitives/chart/chart-root.tsx index 86f58516eb7..7e4d9927f70 100644 --- a/packages/mosaic/src/primitives/chart/chart-root.tsx +++ b/packages/mosaic/src/primitives/chart/chart-root.tsx @@ -26,7 +26,10 @@ export const ChartRoot = React.forwardRef(functi return () => setInteractionLayers(count => count - 1); }, []); - const context: ChartContextValue = { chart, ariaLabel, registerInteraction }; + const context = React.useMemo( + () => ({ chart, ariaLabel, registerInteraction }), + [chart, ariaLabel, registerInteraction], + ); const interactionMode: InteractionMode = chart.size.width <= 0 From a536d6ba9ea13710e44b38883dc6313fbfdd28c5 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 09:49:24 -0700 Subject: [PATCH 18/40] fix(mosaic): repaint bar chart when an ancestor theme or color scheme changes The bars Canvas read colors from BarChart.Bar's computed style but only repainted on attribute changes. A light-dark() color under `color-scheme: light dark` stayed stale when the OS color scheme flipped, and a theme class or color-scheme set on a wrapper never repainted. Watch class, style and data-theme on every ancestor of BarChart.Bar and the prefers-color-scheme media query instead of alone. --- .../mosaic/src/primitives/bar-chart/README.md | 10 +++- .../__tests__/bar-chart.browser.test.tsx | 31 +++++++++++ .../bar-chart/bar-chart-stacked-bars.tsx | 52 ++++++++++++++----- 3 files changed, 79 insertions(+), 14 deletions(-) diff --git a/packages/mosaic/src/primitives/bar-chart/README.md b/packages/mosaic/src/primitives/bar-chart/README.md index 14cf37d5138..31feaf6b3ce 100644 --- a/packages/mosaic/src/primitives/bar-chart/README.md +++ b/packages/mosaic/src/primitives/bar-chart/README.md @@ -178,7 +178,15 @@ Tailwind reads `_` inside `data-[…]` as a space, so a key such as `first_activ The geometry is paint only. Selection, the cursor and the scales use the category band. `BarChart.ProjectionOutline` takes its width and corner radius from the same geometry. -The Canvas repaints in the same frame when `BarChart.Bar` mounts, unmounts or changes `class`, when `` changes `class`, `style` or `data-theme`, when the pixel ratio changes (capped at 2), and when the layout or the props of `BarChart.StackedBars` change. 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. +The Canvas repaints in the same frame when: + +- `BarChart.Bar` mounts, unmounts or changes `class` +- any ancestor of `BarChart.Bar`, up to ``, changes `class`, `style` or `data-theme`, so a theme class or `color-scheme` set on a wrapper repaints the bars +- `prefers-color-scheme` changes, 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 `BarChart.StackedBars` change + +Other changes to the computed color do not repaint: a stylesheet added or removed, another media query such as `prefers-contrast`, or an attribute other than those three on an ancestor. Change the class of `BarChart.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 diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx index 4cc7d09ac29..ebde64433f0 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx @@ -22,6 +22,8 @@ beforeAll(async () => { .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); } `; document.head.append(style); }); @@ -123,6 +125,35 @@ describe('painting', () => { } }); + 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 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); diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx index 451ce84e179..1ef0de20c8b 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx @@ -32,15 +32,41 @@ function getPixelRatio() { return Math.min(window.devicePixelRatio || 1, 2); } -function getRootThemeAttributes() { - const root = document.documentElement; - return JSON.stringify([root.getAttribute('class'), root.getAttribute('style'), root.getAttribute('data-theme')]); +const THEME_ATTRIBUTES = ['class', 'style', 'data-theme']; +const PREFERS_DARK = '(prefers-color-scheme: dark)'; + +function getAncestors(element: Element) { + const ancestors: Element[] = []; + for (let node = element.parentElement; node; node = node.parentElement) { + ancestors.push(node); + } + return ancestors; +} + +function getThemeSnapshot(bar: Element | null) { + if (!bar) { + return ''; + } + return JSON.stringify([ + window.matchMedia(PREFERS_DARK).matches, + ...getAncestors(bar).flatMap(element => THEME_ATTRIBUTES.map(name => element.getAttribute(name))), + ]); } -function subscribeToRootTheme(onChange: () => void) { +function subscribeToTheme(bar: Element | null, onChange: () => void) { + if (!bar) { + return () => {}; + } const observer = new MutationObserver(onChange); - observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style', 'data-theme'] }); - return () => observer.disconnect(); + for (const element of getAncestors(bar)) { + observer.observe(element, { attributes: true, attributeFilter: THEME_ATTRIBUTES }); + } + const query = window.matchMedia(PREFERS_DARK); + query.addEventListener('change', onChange); + return () => { + observer.disconnect(); + query.removeEventListener('change', onChange); + }; } const getServerSnapshot = () => ''; @@ -52,11 +78,6 @@ export const BarChartStackedBars = React.forwardRef(null); const [canvasError, setCanvasError] = React.useState(null); @@ -72,6 +93,11 @@ export const BarChartStackedBars = React.forwardRef void) => subscribeToTheme(bar, onChange), [bar]), + () => getThemeSnapshot(bar), + getServerSnapshot, + ); const barClass = React.useSyncExternalStore( subscribeToBarClass, () => bar?.getAttribute('class') ?? '', @@ -100,8 +126,8 @@ export const BarChartStackedBars = React.forwardRef canvas.removeEventListener('contextlost', onContextLost); - // `barClass` and `rootThemeAttributes` are not read here: they change the computed colors the paint reads from the DOM. - }, [bar, barClass, canvas, isBarActive, marks, pixelRatio, projection, rootThemeAttributes, size]); + // `barClass` and `theme` are not read here: they change the computed colors the paint reads from the DOM. + }, [bar, barClass, canvas, isBarActive, marks, pixelRatio, projection, size, theme]); const ownProps = { style: { position: 'absolute', inset: 0 }, From 27cb673bed0c94cf6b57277cf086de2e40a2c0ad Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 10:20:18 -0700 Subject: [PATCH 19/40] refactor(mosaic): move CanvasRenderError into a module with no imports The bar-chart entry re-exports CanvasRenderError before any 'use client' module, so its module must import nothing but relative modules. Its old home in bar-chart-canvas reached d3-scale, which fails check:bundle once the entry is published. --- .../src/primitives/bar-chart/bar-chart-canvas-error.ts | 6 ++++++ .../mosaic/src/primitives/bar-chart/bar-chart-canvas.ts | 8 +------- .../src/primitives/bar-chart/bar-chart-stacked-bars.tsx | 2 +- packages/mosaic/src/primitives/bar-chart/parts.ts | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart-canvas-error.ts diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-canvas-error.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-canvas-error.ts new file mode 100644 index 00000000000..3ee35c799ba --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-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/bar-chart/bar-chart-canvas.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart-canvas.ts index 6026d715846..e0603b72a16 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-canvas.ts +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-canvas.ts @@ -1,17 +1,11 @@ import type { ChartSize } from '../chart/types'; import { getComputedStyle } from '../utils/dom'; +import { CanvasRenderError } from './bar-chart-canvas-error'; import { type BarGeometry, type PaintedProjection, UNSTYLED_BAR_GEOMETRY } from './bar-chart-layout'; import type { BarIdentity, BarMark } from './types'; const TILE_DEVICE_PIXELS = 32; -export class CanvasRenderError extends Error { - constructor(message: string, cause: unknown) { - super(message, { cause }); - this.name = 'CanvasRenderError'; - } -} - type BarCanvasContext = Pick< CanvasRenderingContext2D, 'save' | 'restore' | 'beginPath' | 'rect' | 'roundRect' | 'clip' | 'fill' | 'fillStyle' diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx b/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx index 1ef0de20c8b..229eff5c675 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx @@ -6,11 +6,11 @@ import { hasArea } from '../chart/chart-context'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; import { type BarStyleElement, - CanvasRenderError, getBarGeometrySnapshot, paintStackedBarCanvas, parseBarGeometry, } from './bar-chart-canvas'; +import { CanvasRenderError } from './bar-chart-canvas-error'; import { StackedBarsContext, useBarChartContext } from './bar-chart-context'; import { fitProjectionToBar, projectStackedBarMarks } from './bar-chart-layout'; diff --git a/packages/mosaic/src/primitives/bar-chart/parts.ts b/packages/mosaic/src/primitives/bar-chart/parts.ts index 0f3ea8d01fc..588feabff28 100644 --- a/packages/mosaic/src/primitives/bar-chart/parts.ts +++ b/packages/mosaic/src/primitives/bar-chart/parts.ts @@ -5,4 +5,4 @@ export { type BarChartProjectionOutlineProps, BarChartProjectionOutline as ProjectionOutline, } from './bar-chart-projection-outline'; -export { CanvasRenderError } from './bar-chart-canvas'; +export { CanvasRenderError } from './bar-chart-canvas-error'; From 42c79546af89bb607f34b3aea80b90fd44bb2c37 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 10:20:19 -0700 Subject: [PATCH 20/40] feat(mosaic): publish the Chart and BarChart primitives Add the @clerk/mosaic/primitives/chart and @clerk/mosaic/primitives/bar-chart exports, their tsdown entries and their agent docs, and describe the new entries in the changeset. --- .changeset/mosaic-bar-chart-primitive.md | 19 ++ packages/mosaic/package.json | 10 + .../src/primitives/bar-chart/bar-chart.doc.ts | 97 +++++++++ .../mosaic/src/primitives/chart/chart.doc.ts | 186 ++++++++++++++++++ packages/mosaic/tsdown.config.mts | 2 + 5 files changed, 314 insertions(+) create mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart.doc.ts create mode 100644 packages/mosaic/src/primitives/chart/chart.doc.ts diff --git a/.changeset/mosaic-bar-chart-primitive.md b/.changeset/mosaic-bar-chart-primitive.md index a845151cc84..50973d9ed7c 100644 --- a/.changeset/mosaic-bar-chart-primitive.md +++ b/.changeset/mosaic-bar-chart-primitive.md @@ -1,2 +1,21 @@ --- +'@clerk/mosaic': minor --- + +Add headless `Chart` and `BarChart` primitives for stacked bar charts with values above and below zero. `BarChart.useBarChart` lays out the bars and owns pointer and keyboard selection, `BarChart.StackedBars` paints them on Canvas, and the `Chart` parts add the grid, axes, cursor and tooltip. The parts ship no styles: style `BarChart.Bar` and each `Chart` part with `className` and `data-*` attributes. + +```tsx +import { BarChart } from '@clerk/mosaic/primitives/bar-chart'; +import { Chart } from '@clerk/mosaic/primitives/chart'; + +const chart = BarChart.useBarChart({ data, series, index }); + + + + + + {ticks => ticks.map(tick => )} +; +``` + +`d3-scale` and `d3-shape` are new dependencies, loaded only by `@clerk/mosaic/primitives/bar-chart`. diff --git a/packages/mosaic/package.json b/packages/mosaic/package.json index 27c53f017a7..084f6c629e2 100644 --- a/packages/mosaic/package.json +++ b/packages/mosaic/package.json @@ -386,11 +386,21 @@ "import": "./dist/primitives/autocomplete.js", "default": "./dist/primitives/autocomplete.js" }, + "./primitives/bar-chart": { + "types": "./dist/primitives/bar-chart.d.ts", + "import": "./dist/primitives/bar-chart.js", + "default": "./dist/primitives/bar-chart.js" + }, "./primitives/button": { "types": "./dist/primitives/button.d.ts", "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", diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart.doc.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart.doc.ts new file mode 100644 index 00000000000..3cb92c08b2f --- /dev/null +++ b/packages/mosaic/src/primitives/bar-chart/bar-chart.doc.ts @@ -0,0 +1,97 @@ +import type { ComponentDoc } from '../../docs-schema'; +import type { BarChartBarProps, BarChartProjectionOutlineProps, BarChartStackedBarsProps } from './parts'; + +export default { + name: 'BarChart', + description: + 'Headless, unstyled stacked bar chart with values above and below zero. `BarChart.useBarChart` owns the layout and selection, D3 computes the stacks and scales, and `BarChart.StackedBars` paints the bars on Canvas, styled through the hidden `BarChart.Bar`. The root, grid, axes, selection, cursor and tooltip are the shared `Chart` parts. Up and Down select the positive or negative section of a period.', + 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', + ], + keywords: ['bar chart', 'stacked bars', 'chart', 'graph', 'canvas', 'diverging', 'projection', 'useBarChart'], + practices: [ + { + 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 `BarChart.Bar` with a `color` per `data-series`, and `data-projection` whenever there is a projection. Without it nothing is painted.', + }, + { + do: true, + text: 'Catch `BarChart.CanvasRenderError` in an error boundary and offer a retry that mounts a fresh chart.', + }, + { + do: false, + text: 'Animate the bar color with a CSS transition. `BarChart.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 `BarChart.Bar`, or of an ancestor, to repaint.', + }, + ], + parts: { + 'BarChart.StackedBars': { + description: + 'A `div` that paints the bars on a Canvas with `role="img"`, and holds one SVG over it for `BarChart.ProjectionOutline` and any `Chart.YLine`. Throws outside `Chart.Root`, and when the chart did not come from `BarChart.useBarChart`.', + }, + 'BarChart.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 `BarChart.StackedBars`.', + }, + 'BarChart.ProjectionOutline': { + description: + 'An `aria-hidden` `rect` that outlines the projected bar, when `projection` rises above its stack. Throws outside `BarChart.StackedBars`.', + }, + }, + examples: [ + { + title: 'Stacked bars with a projection', + code: ` +const chart = BarChart.useBarChart({ data, series, index, projection }); + + + + + + + + + >>{active => } + + +`, + }, + { + 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 = BarChart.useBarChart({ data, series, index, selection, onSelectionChange: setSelection, isBarActive }); +`, + }, + ], + related: ['Chart'], + exports: { + 'BarChart.useBarChart': { + description: + 'Lays out stacked bars and owns their selection: `BarChart.useBarChart({ data, series, index })`, plus `categoryGap`, `margin`, `projection`, `isBarActive`, `selection`, `onSelectionChange`, `onActivate` and `formatCategory`. Returns the chart object for `Chart.Root`.', + }, + 'BarChart.CanvasRenderError': { + description: + 'Thrown when the Canvas 2D context is missing or lost, or painting fails, with the original failure as its `cause`.', + }, + }, +} satisfies ComponentDoc<{ + 'BarChart.StackedBars': BarChartStackedBarsProps; + 'BarChart.Bar': BarChartBarProps; + 'BarChart.ProjectionOutline': BarChartProjectionOutlineProps; +}>; 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..2460ac5a4ae --- /dev/null +++ b/packages/mosaic/src/primitives/chart/chart.doc.ts @@ -0,0 +1,186 @@ +import type { ComponentDoc } from '../../docs-schema'; +import type { + ChartCursorProps, + ChartGridProps, + ChartRootProps, + ChartSelectionProps, + ChartTooltipProps, + ChartXAxisProps, + ChartXTickProps, + ChartYAxisProps, + ChartYLineProps, + ChartYTickProps, +} from './parts'; + +export default { + name: 'Chart', + description: + 'Headless, unstyled parts every chart type shares: the root, grid, axes, Y lines, and pointer and keyboard selection with its cursor and tooltip. A chart-type hook, such as `BarChart.useBarChart`, owns the layout and selection and returns a chart object; `Chart.Root` takes it and the parts render from it. `Chart` draws no data. Each container renders nothing until the root has a measured, non-zero size.', + useFor: [ + 'axes, a grid and reference lines for a bar chart', + 'pointer and keyboard selection over a chart, with a cursor and a tooltip', + 'a decorative placeholder chart with no selection', + ], + keywords: ['chart', 'graph', '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: 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.', + }, + ], + 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 `BarChart.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.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`, with `data-chart-interaction` 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` for the selected category. Opens to the right, flips left when it does not fit, and pins to the top of a plot narrower than 416px. 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.', + }, + boundaryRef: { + type: 'React.RefObject', + doc: 'Element the tooltip stays inside.', + default: 'the chart', + }, + }, + }, + }, + examples: [ + { + title: 'Axes, grid, cursor and tooltip around a bar chart', + code: ` +const chart = BarChart.useBarChart({ data, series, index, onActivate: openPeriod }); + + + + {ticks => ticks.map(tick => )} + + + + + + {ticks => ticks.map(tick => )} + + + {ticks => ticks.map(tick => )} + + + + > className='tooltip'>{active => } + + +`, + }, + ], + related: ['BarChart', 'Portal'], +} satisfies ComponentDoc<{ + 'Chart.Root': ChartRootProps; + 'Chart.Grid': ChartGridProps; + 'Chart.YLine': ChartYLineProps; + '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/tsdown.config.mts b/packages/mosaic/tsdown.config.mts index 9417bb5801a..a96d88c37a9 100644 --- a/packages/mosaic/tsdown.config.mts +++ b/packages/mosaic/tsdown.config.mts @@ -87,7 +87,9 @@ export default defineConfig({ 'icons/glyphs/users-add-right': './src/icons/glyphs/users-add-right.tsx', 'primitives/accordion': './src/primitives/accordion/index.ts', 'primitives/autocomplete': './src/primitives/autocomplete/index.ts', + 'primitives/bar-chart': './src/primitives/bar-chart/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', From bb9ee9d3faf3674d2695b1c64d24d13202b5f1e8 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 11:21:04 -0700 Subject: [PATCH 21/40] refactor(mosaic): fold the BarChart primitive into Chart --- .changeset/mosaic-bar-chart-primitive.md | 21 -- .changeset/mosaic-chart-primitive.md | 20 ++ packages/mosaic/oxlint.config.mjs | 10 +- packages/mosaic/package.json | 5 - .../mosaic/src/primitives/bar-chart/README.md | 205 ------------------ .../src/primitives/bar-chart/bar-chart.doc.ts | 97 --------- .../mosaic/src/primitives/bar-chart/index.ts | 10 - .../mosaic/src/primitives/bar-chart/parts.ts | 8 - .../mosaic/src/primitives/chart/README.md | 177 ++++++++++++--- ...-bars-dimmed-selection-chromium-linux.png} | Bin ...stacked-bars-diverging-chromium-linux.png} | Bin ...tacked-bars-projection-chromium-linux.png} | Bin ...cked-bars-tooltip-open-chromium-linux.png} | Bin .../bars/__tests__/bar-layout.test.ts} | 4 +- .../bars}/__tests__/fixtures.tsx | 2 +- .../__tests__/stacked-bars.browser.test.tsx} | 6 +- .../bars/__tests__/stacked-bars.test.tsx} | 23 +- .../__tests__/stacked-bars.visual.test.tsx} | 23 +- .../bars}/__tests__/test-chart.tsx | 15 +- .../bars/bar-canvas-error.ts} | 0 .../bars/bar-canvas.ts} | 12 +- .../bars/bar-context.ts} | 22 +- .../bars/bar-layout.ts} | 4 +- .../bars/bar-selection.ts} | 4 +- .../bars/chart-bar.tsx} | 10 +- .../bars/chart-projection-outline.tsx} | 10 +- .../bars/chart-stacked-bars.tsx} | 23 +- .../{bar-chart => chart/bars}/types.ts | 2 +- .../bars}/use-bar-chart.ts | 12 +- .../src/primitives/chart/chart-root.tsx | 2 +- .../mosaic/src/primitives/chart/chart.doc.ts | 115 +++++++++- packages/mosaic/src/primitives/chart/index.ts | 14 ++ .../chart/line-chart-contract.test-d.ts | 2 +- packages/mosaic/src/primitives/chart/parts.ts | 8 + packages/mosaic/src/primitives/chart/types.ts | 2 +- packages/mosaic/tsdown.config.mts | 1 - .../swingset/src/components/DocsViewer.tsx | 2 +- packages/swingset/src/lib/registry.ts | 6 +- .../src/stories/{bar-chart.mdx => chart.mdx} | 80 +++---- ...ar-chart.stories.tsx => chart.stories.tsx} | 17 +- 40 files changed, 435 insertions(+), 539 deletions(-) delete mode 100644 .changeset/mosaic-bar-chart-primitive.md create mode 100644 .changeset/mosaic-chart-primitive.md delete mode 100644 packages/mosaic/src/primitives/bar-chart/README.md delete mode 100644 packages/mosaic/src/primitives/bar-chart/bar-chart.doc.ts delete mode 100644 packages/mosaic/src/primitives/bar-chart/index.ts delete mode 100644 packages/mosaic/src/primitives/bar-chart/parts.ts rename packages/mosaic/src/primitives/{bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-dimmed-selection-chromium-linux.png => chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-dimmed-selection-chromium-linux.png} (100%) rename packages/mosaic/src/primitives/{bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-diverging-chromium-linux.png => chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-diverging-chromium-linux.png} (100%) rename packages/mosaic/src/primitives/{bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-projection-chromium-linux.png => chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-projection-chromium-linux.png} (100%) rename packages/mosaic/src/primitives/{bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-tooltip-open-chromium-linux.png => chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-tooltip-open-chromium-linux.png} (100%) rename packages/mosaic/src/primitives/{bar-chart/__tests__/bar-chart-layout.test.ts => chart/bars/__tests__/bar-layout.test.ts} (95%) rename packages/mosaic/src/primitives/{bar-chart => chart/bars}/__tests__/fixtures.tsx (98%) rename packages/mosaic/src/primitives/{bar-chart/__tests__/bar-chart.browser.test.tsx => chart/bars/__tests__/stacked-bars.browser.test.tsx} (98%) rename packages/mosaic/src/primitives/{bar-chart/__tests__/bar-chart.test.tsx => chart/bars/__tests__/stacked-bars.test.tsx} (95%) rename packages/mosaic/src/primitives/{bar-chart/__tests__/bar-chart.visual.test.tsx => chart/bars/__tests__/stacked-bars.visual.test.tsx} (88%) rename packages/mosaic/src/primitives/{bar-chart => chart/bars}/__tests__/test-chart.tsx (81%) rename packages/mosaic/src/primitives/{bar-chart/bar-chart-canvas-error.ts => chart/bars/bar-canvas-error.ts} (100%) rename packages/mosaic/src/primitives/{bar-chart/bar-chart-canvas.ts => chart/bars/bar-canvas.ts} (95%) rename packages/mosaic/src/primitives/{bar-chart/bar-chart-context.ts => chart/bars/bar-context.ts} (67%) rename packages/mosaic/src/primitives/{bar-chart/bar-chart-layout.ts => chart/bars/bar-layout.ts} (98%) rename packages/mosaic/src/primitives/{bar-chart/bar-chart-selection.ts => chart/bars/bar-selection.ts} (94%) rename packages/mosaic/src/primitives/{bar-chart/bar-chart-bar.tsx => chart/bars/chart-bar.tsx} (64%) rename packages/mosaic/src/primitives/{bar-chart/bar-chart-projection-outline.tsx => chart/bars/chart-projection-outline.tsx} (69%) rename packages/mosaic/src/primitives/{bar-chart/bar-chart-stacked-bars.tsx => chart/bars/chart-stacked-bars.tsx} (90%) rename packages/mosaic/src/primitives/{bar-chart => chart/bars}/types.ts (98%) rename packages/mosaic/src/primitives/{bar-chart => chart/bars}/use-bar-chart.ts (82%) rename packages/swingset/src/stories/{bar-chart.mdx => chart.mdx} (72%) rename packages/swingset/src/stories/{bar-chart.stories.tsx => chart.stories.tsx} (83%) diff --git a/.changeset/mosaic-bar-chart-primitive.md b/.changeset/mosaic-bar-chart-primitive.md deleted file mode 100644 index 50973d9ed7c..00000000000 --- a/.changeset/mosaic-bar-chart-primitive.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -'@clerk/mosaic': minor ---- - -Add headless `Chart` and `BarChart` primitives for stacked bar charts with values above and below zero. `BarChart.useBarChart` lays out the bars and owns pointer and keyboard selection, `BarChart.StackedBars` paints them on Canvas, and the `Chart` parts add the grid, axes, cursor and tooltip. The parts ship no styles: style `BarChart.Bar` and each `Chart` part with `className` and `data-*` attributes. - -```tsx -import { BarChart } from '@clerk/mosaic/primitives/bar-chart'; -import { Chart } from '@clerk/mosaic/primitives/chart'; - -const chart = BarChart.useBarChart({ data, series, index }); - - - - - - {ticks => ticks.map(tick => )} -; -``` - -`d3-scale` and `d3-shape` are new dependencies, loaded only by `@clerk/mosaic/primitives/bar-chart`. diff --git a/.changeset/mosaic-chart-primitive.md b/.changeset/mosaic-chart-primitive.md new file mode 100644 index 00000000000..12709e1d6a9 --- /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.StackedBars` 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 7aa01bc3696..aebb3ea6405 100644 --- a/packages/mosaic/oxlint.config.mjs +++ b/packages/mosaic/oxlint.config.mjs @@ -7,7 +7,7 @@ import { defineConfig } from 'oxlint'; const mosaicRoot = import.meta.dirname; const [, rootRestrictedImports] = rootConfig.rules['no-restricted-imports']; const chartInternalMessage = - 'The chart selection engine is for chart-type hooks. Import it only from a src/primitives/-chart/ folder.'; + '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 = [ @@ -476,13 +476,7 @@ export default defineConfig({ }, { files: ['src/**/*'], - excludeFiles: [ - 'src/primitives/*-chart/**', - 'src/primitives/chart/internal/**', - 'src/**/__tests__/**', - 'src/**/*.test.{ts,tsx}', - 'src/**/*.test-d.ts', - ], + excludeFiles: ['src/primitives/chart/**', 'src/**/__tests__/**', 'src/**/*.test.{ts,tsx}', 'src/**/*.test-d.ts'], rules: { 'no-restricted-imports': [ 'error', diff --git a/packages/mosaic/package.json b/packages/mosaic/package.json index 084f6c629e2..37e8d2f8c1a 100644 --- a/packages/mosaic/package.json +++ b/packages/mosaic/package.json @@ -386,11 +386,6 @@ "import": "./dist/primitives/autocomplete.js", "default": "./dist/primitives/autocomplete.js" }, - "./primitives/bar-chart": { - "types": "./dist/primitives/bar-chart.d.ts", - "import": "./dist/primitives/bar-chart.js", - "default": "./dist/primitives/bar-chart.js" - }, "./primitives/button": { "types": "./dist/primitives/button.d.ts", "import": "./dist/primitives/button.js", diff --git a/packages/mosaic/src/primitives/bar-chart/README.md b/packages/mosaic/src/primitives/bar-chart/README.md deleted file mode 100644 index 31feaf6b3ce..00000000000 --- a/packages/mosaic/src/primitives/bar-chart/README.md +++ /dev/null @@ -1,205 +0,0 @@ -# Bar chart - -A headless stacked bar chart: `BarChart.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`. The root, grid, axes, selection, cursor and tooltip are the shared [`Chart`](../chart/README.md) parts. The parts emit no visual styles: style each one with `className` and `data-*` attributes. - -## 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. -- A decorative placeholder chart: leave out `Chart.Selection`. - -## Usage - -```tsx -import { type ActiveBar, BarChart } from '@clerk/mosaic/primitives/bar-chart'; -import { Chart } from '@clerk/mosaic/primitives/chart'; - -const chart = BarChart.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 | -| ---------------------------- | --------------- | ------------------------------------------------------------------- | -| `BarChart.StackedBars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | -| `BarChart.Bar` | `` | Hidden. Its computed style paints the bars | -| `BarChart.ProjectionOutline` | `` | Outlines the projected bar | - -Every part takes `className`, `ref`, `render` and the native props of its default element, merged as the [`Chart` parts](../chart/README.md#parts) are. - -`BarChart.StackedBars` throws outside `Chart.Root`, and throws when the chart did not come from `BarChart.useBarChart`. `BarChart.Bar` and `BarChart.ProjectionOutline` throw outside `BarChart.StackedBars`. A `Chart.YLine` inside `BarChart.StackedBars`, such as the zero line, paints over the bars. - -The namespace also holds `BarChart.useBarChart` and `BarChart.CanvasRenderError`. - -## Props - -### `BarChart.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` | `{ datumIndex: number; value: number }` | — | A projected total, drawn when it rises above its category's stack | -| `isBarActive` | `(bar: BarIdentity) => boolean` | every bar | Returns false for a bar that `BarChart.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 | -| `onActivate` | `(active: ActiveBar) => void` | — | Called on click, Enter or Space. Makes the surface a button | -| `formatCategory` | `(key: string) => string \| null` | the key | Names a period in keyboard announcements | - -`BarSelection` is `{ category, section }`. A new `isBarActive` function repaints the Canvas. `margin` and the last four options are the [options every chart type takes](../chart/README.md#options-every-chart-type-takes). - -The hook returns a `BarChartInstance`: the [chart object](../chart/README.md#the-chart-object) with `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: `>>`. - -## Keyboard and selection - -Selection follows [`Chart`](../chart/README.md#keyboard). 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. A pointer selects the section above or below 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 its section, such as `Feb, positive values`, or `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 = BarChart.useBarChart({ data, series, index, selection, onSelectionChange: setSelection, isBarActive }); -``` - -Painting the bars is the one thing the chart object does not do, because their color and geometry come from `BarChart.Bar`'s computed style: keep `BarChart.StackedBars` for that. - -## Accessibility - -The bars Canvas carries `role="img"` and the `aria-label` from `Chart.Root`. The projection outline is `aria-hidden`. The rest is in [`Chart`](../chart/README.md#accessibility). - -## Styling - -### `BarChart.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. `BarChart.Bar` renders one `aria-hidden` ``. Before each paint, `BarChart.StackedBars` puts it in every state it draws, reads its computed `color`, caches it per state, paints, then restores the element: - -| State | Set on `BarChart.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 `BarChart.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. - -`BarChart.Bar` also sets the bar geometry from its computed style. Only pixel values count: - -| CSS on `BarChart.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. `BarChart.ProjectionOutline` takes its width and corner radius from the same geometry. - -The Canvas repaints in the same frame when: - -- `BarChart.Bar` mounts, unmounts or changes `class` -- any ancestor of `BarChart.Bar`, up to ``, changes `class`, `style` or `data-theme`, so a theme class or `color-scheme` set on a wrapper repaints the bars -- `prefers-color-scheme` changes, 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 `BarChart.StackedBars` change - -Other changes to the computed color do not repaint: a stylesheet added or removed, another media query such as `prefers-contrast`, or an attribute other than those three on an ancestor. Change the class of `BarChart.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 - -Follow [`Chart`'s paint order](../chart/README.md#paint-order). Inside `BarChart.StackedBars`, put `BarChart.ProjectionOutline` before the zero `Chart.YLine`. The position of `BarChart.Bar` does not matter. - -## 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. `BarChart.StackedBars` projects the bar marks when the layout or the bar geometry changes. The container size is committed 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 `BarChart.CanvasRenderError`, with the original failure as its `cause`, so an error boundary can offer a retry that mounts a fresh Canvas. diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart.doc.ts b/packages/mosaic/src/primitives/bar-chart/bar-chart.doc.ts deleted file mode 100644 index 3cb92c08b2f..00000000000 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart.doc.ts +++ /dev/null @@ -1,97 +0,0 @@ -import type { ComponentDoc } from '../../docs-schema'; -import type { BarChartBarProps, BarChartProjectionOutlineProps, BarChartStackedBarsProps } from './parts'; - -export default { - name: 'BarChart', - description: - 'Headless, unstyled stacked bar chart with values above and below zero. `BarChart.useBarChart` owns the layout and selection, D3 computes the stacks and scales, and `BarChart.StackedBars` paints the bars on Canvas, styled through the hidden `BarChart.Bar`. The root, grid, axes, selection, cursor and tooltip are the shared `Chart` parts. Up and Down select the positive or negative section of a period.', - 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', - ], - keywords: ['bar chart', 'stacked bars', 'chart', 'graph', 'canvas', 'diverging', 'projection', 'useBarChart'], - practices: [ - { - 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 `BarChart.Bar` with a `color` per `data-series`, and `data-projection` whenever there is a projection. Without it nothing is painted.', - }, - { - do: true, - text: 'Catch `BarChart.CanvasRenderError` in an error boundary and offer a retry that mounts a fresh chart.', - }, - { - do: false, - text: 'Animate the bar color with a CSS transition. `BarChart.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 `BarChart.Bar`, or of an ancestor, to repaint.', - }, - ], - parts: { - 'BarChart.StackedBars': { - description: - 'A `div` that paints the bars on a Canvas with `role="img"`, and holds one SVG over it for `BarChart.ProjectionOutline` and any `Chart.YLine`. Throws outside `Chart.Root`, and when the chart did not come from `BarChart.useBarChart`.', - }, - 'BarChart.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 `BarChart.StackedBars`.', - }, - 'BarChart.ProjectionOutline': { - description: - 'An `aria-hidden` `rect` that outlines the projected bar, when `projection` rises above its stack. Throws outside `BarChart.StackedBars`.', - }, - }, - examples: [ - { - title: 'Stacked bars with a projection', - code: ` -const chart = BarChart.useBarChart({ data, series, index, projection }); - - - - - - - - - >>{active => } - - -`, - }, - { - 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 = BarChart.useBarChart({ data, series, index, selection, onSelectionChange: setSelection, isBarActive }); -`, - }, - ], - related: ['Chart'], - exports: { - 'BarChart.useBarChart': { - description: - 'Lays out stacked bars and owns their selection: `BarChart.useBarChart({ data, series, index })`, plus `categoryGap`, `margin`, `projection`, `isBarActive`, `selection`, `onSelectionChange`, `onActivate` and `formatCategory`. Returns the chart object for `Chart.Root`.', - }, - 'BarChart.CanvasRenderError': { - description: - 'Thrown when the Canvas 2D context is missing or lost, or painting fails, with the original failure as its `cause`.', - }, - }, -} satisfies ComponentDoc<{ - 'BarChart.StackedBars': BarChartStackedBarsProps; - 'BarChart.Bar': BarChartBarProps; - 'BarChart.ProjectionOutline': BarChartProjectionOutlineProps; -}>; diff --git a/packages/mosaic/src/primitives/bar-chart/index.ts b/packages/mosaic/src/primitives/bar-chart/index.ts deleted file mode 100644 index dd42129ca05..00000000000 --- a/packages/mosaic/src/primitives/bar-chart/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -export * as BarChart from './parts'; - -export type { - BarChartBarProps, - BarChartProjectionOutlineProps, - BarChartStackedBarsProps, - UseBarChartOptions, -} from './parts'; -export type { BarChartInstance } from './bar-chart-context'; -export type { ActiveBar, BarCategory, BarIdentity, BarProjection, BarSection, BarSelection, BarSeries } from './types'; diff --git a/packages/mosaic/src/primitives/bar-chart/parts.ts b/packages/mosaic/src/primitives/bar-chart/parts.ts deleted file mode 100644 index 588feabff28..00000000000 --- a/packages/mosaic/src/primitives/bar-chart/parts.ts +++ /dev/null @@ -1,8 +0,0 @@ -export { useBarChart, type UseBarChartOptions } from './use-bar-chart'; -export { type BarChartStackedBarsProps, BarChartStackedBars as StackedBars } from './bar-chart-stacked-bars'; -export { type BarChartBarProps, BarChartBar as Bar } from './bar-chart-bar'; -export { - type BarChartProjectionOutlineProps, - BarChartProjectionOutline as ProjectionOutline, -} from './bar-chart-projection-outline'; -export { CanvasRenderError } from './bar-chart-canvas-error'; diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index f548a0b7b9b..f71b2914fbc 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -1,21 +1,22 @@ # Chart -The headless parts every chart type shares: the root, grid, axes, Y lines, and pointer and keyboard selection with its cursor and tooltip. A chart-type hook, such as `BarChart.useBarChart` ([`bar-chart/`](../bar-chart/README.md)), owns the layout and selection and returns a chart object. `Chart.Root` takes any chart object, and the shared parts render from it. The parts emit no visual styles: style each one with `className` and `data-*` attributes. +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`. -`Chart` draws no data. Its marks come from the chart type, such as `BarChart.StackedBars`. - ## Usage ```tsx -import { type ActiveBar, BarChart } from '@clerk/mosaic/primitives/bar-chart'; -import { Chart } from '@clerk/mosaic/primitives/chart'; +import { type ActiveBar, Chart } from '@clerk/mosaic/primitives/chart'; -const chart = BarChart.useBarChart({ data, series, index, onActivate: openPeriod }); +const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }); - - + + + - + {ticks => ticks.map(tick => ( @@ -69,26 +71,31 @@ const chart = BarChart.useBarChart({ data, series, index, onActivate: openPeriod ; ``` -A container renders only the items its children function returns. A bare `` renders an empty SVG. +`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.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 | +| 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.StackedBars` | `
` | 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` | `` | 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.Cursor` and `Chart.Tooltip` throw outside `Chart.Selection`. +Every part throws outside `Chart.Root`. `Chart.StackedBars` also throws when the chart did not come from `Chart.useBarChart`. `Chart.Bar` and `Chart.ProjectionOutline` throw outside `Chart.StackedBars`, and `Chart.Cursor` and `Chart.Tooltip` throw outside `Chart.Selection`. A `Chart.YLine` inside `Chart.StackedBars`, such as the zero line, paints over the bars. + +The namespace also holds `Chart.useBarChart` and `Chart.CanvasRenderError`. ## Props @@ -124,6 +131,28 @@ Every part throws outside `Chart.Root`. `Chart.Cursor` and `Chart.Tooltip` throw 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` | `{ datumIndex: number; value: number }` | — | 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 | +| `onActivate` | `(active: ActiveBar) => void` | — | Called on click, Enter or Space. Makes the surface a button | +| `formatCategory` | `(key: string) => string \| null` | the key | Names a period in keyboard announcements | + +`BarSelection` is `{ category, section }`. A new `isBarActive` function repaints the Canvas. `margin` and the last four options are the [options every chart type takes](#options-every-chart-type-takes). + +The hook returns a `BarChartInstance`: the [chart object](#the-chart-object) with `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: @@ -185,12 +214,30 @@ A controlled `selection` decides what is selected. The chart also remembers two 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. A pointer selects the section above or below 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 its section, such as `Feb, positive values`, or `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, 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 = BarChart.useBarChart({ data, series, index, onSelectionChange }); +const chart = Chart.useBarChart({ data, series, index, onSelectionChange }); const { rootRef } = chart;
@@ -208,6 +255,8 @@ const { rootRef } = chart; 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.StackedBars` for that. + ## Data attributes | Attribute | Part | Description | @@ -215,14 +264,15 @@ The pointer maps client coordinates through the `rootRef` element's bounds. | `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-chart-interaction` | `Chart.Selection` | On the interaction surface inside the part | +| `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. +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`. The grid, axes, cursor and lines are `aria-hidden`. +- 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`. - Visually hidden text describes the keys. A `status` region announces the selected period, named through `formatCategory`, and what the chart type adds. - An assistive-technology click without coordinates activates the selected period. @@ -235,22 +285,93 @@ The parts set only the inline styles that layout and behavior depend on: absolut 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.StackedBars` 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. `Chart.ProjectionOutline` takes its width and corner radius from the same geometry. + +The Canvas repaints in the same frame when: + +- `Chart.Bar` mounts, unmounts or changes `class` +- any ancestor of `Chart.Bar`, up to ``, changes `class`, `style` or `data-theme`, so a theme class or `color-scheme` set on a wrapper repaints the bars +- `prefers-color-scheme` changes, 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.StackedBars` change + +Other changes to the computed color do not repaint: a stylesheet added or removed, another media query such as `prefers-contrast`, or an attribute other than those three on an ancestor. 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 `BarChart.StackedBars`, with any `Chart.YLine` inside their SVG +2. The chart type's marks, such as `Chart.StackedBars`, 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.StackedBars`, put `Chart.ProjectionOutline` before the zero `Chart.YLine`. The position of `Chart.Bar` does not matter. + +## 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.StackedBars` projects the bar marks when the layout or the bar geometry changes. The container size is committed 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 to the right, flips left when the right side does not fit inside `boundaryRef`, and keeps the side it chose last until that side stops fitting, so it does not cross the selection twice near an edge. 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 `src/primitives/-chart/` folder. Its hook measures with `useChartFrame`, lays out its categories, and passes a pure `SelectionModel` to `useChartInstance`, both from `chart/internal/`. Lint lets only `*-chart/` folders import `chart/internal/`. The model owns the hit test, where the keyboard lands, how a selection resolves against the data, the announcement and the tooltip's Y. Its marks read their own layout from a module-private symbol on the instance, as `BarChart.StackedBars` does. `line-chart-contract.test-d.ts` checks that a point chart fits the contract. +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, where the keyboard lands, how a selection resolves against the data, the announcement and the tooltip's Y. Its marks read their own layout from a module-private symbol on the instance, as `Chart.StackedBars` does. Its hook and parts join the `Chart` namespace in `parts.ts`. `line-chart-contract.test-d.ts` checks that a point chart fits the contract. diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-dimmed-selection-chromium-linux.png b/packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-dimmed-selection-chromium-linux.png similarity index 100% rename from packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-dimmed-selection-chromium-linux.png rename to packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-dimmed-selection-chromium-linux.png diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-diverging-chromium-linux.png b/packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-diverging-chromium-linux.png similarity index 100% rename from packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-diverging-chromium-linux.png rename to packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-diverging-chromium-linux.png diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-projection-chromium-linux.png b/packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-projection-chromium-linux.png similarity index 100% rename from packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-projection-chromium-linux.png rename to packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-projection-chromium-linux.png diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-tooltip-open-chromium-linux.png b/packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-tooltip-open-chromium-linux.png similarity index 100% rename from packages/mosaic/src/primitives/bar-chart/__tests__/__screenshots__/bar-chart.visual.test.tsx/bar-chart-tooltip-open-chromium-linux.png rename to packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-tooltip-open-chromium-linux.png diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts b/packages/mosaic/src/primitives/chart/bars/__tests__/bar-layout.test.ts similarity index 95% rename from packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts rename to packages/mosaic/src/primitives/chart/bars/__tests__/bar-layout.test.ts index 08af192eac6..cf15b70183c 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart-layout.test.ts +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/bar-layout.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { DEFAULT_CHART_MARGIN } from '../../chart/internal/use-chart-instance'; -import { prepareStackedBars, projectStackedBars } from '../bar-chart-layout'; +import { DEFAULT_CHART_MARGIN } from '../../internal/use-chart-instance'; +import { prepareStackedBars, projectStackedBars } from '../bar-layout'; import type { BarProjection } from '../types'; interface TypedRow { diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/fixtures.tsx b/packages/mosaic/src/primitives/chart/bars/__tests__/fixtures.tsx similarity index 98% rename from packages/mosaic/src/primitives/bar-chart/__tests__/fixtures.tsx rename to packages/mosaic/src/primitives/chart/bars/__tests__/fixtures.tsx index 6485036df20..a82fbee3dfd 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/fixtures.tsx +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/fixtures.tsx @@ -2,7 +2,7 @@ import { act, render as renderComponent } from '@testing-library/react'; import type { ReactElement } from 'react'; import { vi } from 'vitest'; -import type { BarChartInstance } from '../index'; +import type { BarChartInstance } from '../..'; import type { BarSelection } from '../types'; import { TestChart, type TestChartProps } from './test-chart'; diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx similarity index 98% rename from packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx rename to packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx index ebde64433f0..1767cce4483 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx @@ -88,7 +88,7 @@ function centerOfCategory(categoryIndex: number) { } describe('painting', () => { - it('paints the bars in the computed color of BarChart.Bar', async () => { + it('paints the bars in the computed color of Chart.Bar', async () => { await render(); const { x, y } = insideLastBar(); @@ -102,7 +102,7 @@ describe('painting', () => { await expect.poll(() => pixelAt(x, y)).toBe('rgba(0, 128, 0, 255)'); }); - it('repaints when the class of BarChart.Bar changes', async () => { + 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)'); @@ -193,7 +193,7 @@ describe('painting', () => { } }); - it('paints nothing without BarChart.Bar', async () => { + it('paints nothing without Chart.Bar', async () => { await render(); const { x, y } = insideLastBar(); diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.test.tsx similarity index 95% rename from packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx rename to packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.test.tsx index 18513504dce..e4dd08ef4d9 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.test.tsx +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.test.tsx @@ -2,9 +2,8 @@ import { cleanup, fireEvent, render as renderComponent, screen } from '@testing- import { useState } from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { Chart } from '../../chart'; -import type { RenderProps } from '../../utils'; -import { BarChart, type BarSelection } from '../index'; +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'; @@ -20,7 +19,7 @@ function StackedChart({ render?: React.ComponentProps['render']; children?: React.ReactNode; }) { - const chart = BarChart.useBarChart({ data, series: chartFixture.series, index: chartFixture.index }); + const chart = Chart.useBarChart({ data, series: chartFixture.series, index: chartFixture.index }); return ( { it.each([ ['Chart.Grid', ], ['Chart.Selection', ], - ['BarChart.StackedBars', ], + ['Chart.StackedBars', ], ])('throws when %s is used outside Chart.Root', (part, element) => { vi.spyOn(console, 'error').mockImplementation(() => {}); expect(() => renderComponent(element)).toThrow(`<${part}> must be used within `); @@ -60,15 +59,15 @@ describe('composing parts', () => { ); }); - it('throws when BarChart.Bar is used outside BarChart.StackedBars', () => { + it('throws when Chart.Bar is used outside Chart.StackedBars', () => { vi.spyOn(console, 'error').mockImplementation(() => {}); expect(() => render( - + , ), - ).toThrow(' must be used within '); + ).toThrow(' must be used within '); }); it.each([ @@ -77,7 +76,7 @@ describe('composing parts', () => { ])('renders a part as %s passed to render', (_, renderElement) => { const { container } = render( - + , ); @@ -96,7 +95,7 @@ describe('composing parts', () => { it('is interactive with Chart.Selection and categories', () => { const { container, rerender } = render( - + , ); @@ -106,7 +105,7 @@ describe('composing parts', () => { rerender( - + , ); @@ -460,7 +459,7 @@ describe('controlling the selection', () => { describe('rendering from the chart object', () => { it('selects with the keyboard on a surface that spreads the interaction props', () => { function CustomChart() { - const chart = BarChart.useBarChart({ ...chartFixture, data: quarter, onSelectionChange: () => {} }); + const chart = Chart.useBarChart({ ...chartFixture, data: quarter, onSelectionChange: () => {} }); const { rootRef } = chart; return (
diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.visual.test.tsx similarity index 88% rename from packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx rename to packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.visual.test.tsx index 52c78fdebdc..1e951f9bbba 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/bar-chart.visual.test.tsx +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.visual.test.tsx @@ -3,8 +3,7 @@ import { useCallback, useRef } from 'react'; import { beforeAll, describe, expect, it } from 'vitest'; import { page, userEvent } from 'vitest/browser'; -import { Chart } from '../../chart'; -import { type ActiveBar, BarChart, type BarIdentity, type BarProjection } from '../index'; +import { type ActiveBar, type BarIdentity, type BarProjection, Chart } from '../..'; const growth = [ { week: '2026-01-05', signups: 40, returning: 22, churned: -14 }, @@ -60,7 +59,7 @@ function GrowthChart({ !selected || (bar.datum.week === selected.week && bar.positive === selected.positive), [selected], ); - const chart = BarChart.useBarChart({ + const chart = Chart.useBarChart({ data: growth, series, index: getWeek, @@ -90,14 +89,14 @@ function GrowthChart({ )) } - - - + + + - + {ticks => ticks.map(tick => ( @@ -147,20 +146,20 @@ async function renderChart(ui: React.ReactElement) { return page.elementLocator(screen.getByTestId('chart')); } -describe('BarChart visual state', () => { +describe('Chart stacked bars visual state', () => { it('stacks values above and below zero', async () => { const chart = await renderChart(); - await expect(chart).toMatchScreenshot('bar-chart-diverging'); + await expect(chart).toMatchScreenshot('stacked-bars-diverging'); }); it('dims every bar outside the selected section', async () => { const chart = await renderChart(); - await expect(chart).toMatchScreenshot('bar-chart-dimmed-selection'); + 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('bar-chart-projection'); + await expect(chart).toMatchScreenshot('stacked-bars-projection'); }); it('opens the tooltip beside the selected period', async () => { @@ -170,6 +169,6 @@ describe('BarChart visual state', () => { await expect .poll(() => screen.queryByText('Sign-ups: 52')?.closest('.tooltip')?.style.visibility) .toBe(''); - await expect(chart).toMatchScreenshot('bar-chart-tooltip-open'); + await expect(chart).toMatchScreenshot('stacked-bars-tooltip-open'); }); }); diff --git a/packages/mosaic/src/primitives/bar-chart/__tests__/test-chart.tsx b/packages/mosaic/src/primitives/chart/bars/__tests__/test-chart.tsx similarity index 81% rename from packages/mosaic/src/primitives/bar-chart/__tests__/test-chart.tsx rename to packages/mosaic/src/primitives/chart/bars/__tests__/test-chart.tsx index 83ed1913006..9904238baf4 100644 --- a/packages/mosaic/src/primitives/bar-chart/__tests__/test-chart.tsx +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/test-chart.tsx @@ -1,7 +1,6 @@ import { type ReactNode, type RefObject, useLayoutEffect } from 'react'; -import { Chart } from '../../chart'; -import { type ActiveBar, BarChart, type BarChartInstance, type UseBarChartOptions } from '../index'; +import { type ActiveBar, type BarChartInstance, Chart, type UseBarChartOptions } from '../..'; export type TestChartProps = Pick< UseBarChartOptions, @@ -22,7 +21,7 @@ export type TestChartProps = Pick< renderTooltip?: (active: ActiveBar) => ReactNode; boundary?: RefObject; height?: number | string; - /** Mounts `BarChart.Bar`. Default: true */ + /** Mounts `Chart.Bar`. Default: true */ bar?: boolean; barClassName?: string; /** Receives the chart object after each render. */ @@ -42,7 +41,7 @@ export function TestChart({ chartRef, ...options }: TestChartProps) { - const chart = BarChart.useBarChart({ ...options, formatCategory: formatXTick }); + const chart = Chart.useBarChart({ ...options, formatCategory: formatXTick }); useLayoutEffect(() => { if (chartRef) { chartRef.current = chart; @@ -54,11 +53,11 @@ export function TestChart({ height={height} aria-label={ariaLabel} > - - {bar ? : null} - + + {bar ? : null} + - + {ticks => ticks.map(tick => ( diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-canvas-error.ts b/packages/mosaic/src/primitives/chart/bars/bar-canvas-error.ts similarity index 100% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-canvas-error.ts rename to packages/mosaic/src/primitives/chart/bars/bar-canvas-error.ts diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-canvas.ts b/packages/mosaic/src/primitives/chart/bars/bar-canvas.ts similarity index 95% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-canvas.ts rename to packages/mosaic/src/primitives/chart/bars/bar-canvas.ts index e0603b72a16..7fd3dea6a60 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-canvas.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-canvas.ts @@ -1,7 +1,7 @@ -import type { ChartSize } from '../chart/types'; -import { getComputedStyle } from '../utils/dom'; -import { CanvasRenderError } from './bar-chart-canvas-error'; -import { type BarGeometry, type PaintedProjection, UNSTYLED_BAR_GEOMETRY } from './bar-chart-layout'; +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; @@ -139,7 +139,7 @@ function readPixels(value: string, fallback: number) { } /** - * Serializes the bar geometry from `BarChart.Bar`'s computed style, so it can be a + * Serializes the bar geometry from `Chart.Bar`'s computed style, so it can be a * `useSyncExternalStore` snapshot. */ export function getBarGeometrySnapshot(element: BarStyleElement | null) { @@ -221,7 +221,7 @@ type PaintOptions = Readonly<{ size: ChartSize; pixelRatio: number; isBarActive?: (bar: BarIdentity) => boolean; - /** The `BarChart.Bar` element. Without it, nothing is painted. */ + /** The `Chart.Bar` element. Without it, nothing is painted. */ bar: BarStyleElement | null; }>; diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-context.ts b/packages/mosaic/src/primitives/chart/bars/bar-context.ts similarity index 67% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-context.ts rename to packages/mosaic/src/primitives/chart/bars/bar-context.ts index fbdd8076608..9b0b474e091 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-context.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-context.ts @@ -1,22 +1,22 @@ import { createContext, useContext } from 'react'; -import { ChartContext } from '../chart/chart-context'; -import type { ChartInstance } from '../chart/types'; -import type { BarStyleElement } from './bar-chart-canvas'; -import type { PaintedProjection, PreparedStackedBars, StackedBarLayout } from './bar-chart-layout'; +import { ChartContext } from '../chart-context'; +import type { ChartInstance } from '../types'; +import type { BarStyleElement } from './bar-canvas'; +import type { PaintedProjection, 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('BarChart layout'); +export const BAR_LAYOUT: unique symbol = Symbol('bar layout'); -/** What the bar marks paint from. Read by `BarChart` parts only. */ +/** 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 `BarChart.useBarChart`. */ +/** The measured layout and selection of one stacked bar chart, returned by `Chart.useBarChart`. */ export type BarChartInstance = ChartInstance, BarSelection, BarCategory> & Readonly<{ [BAR_LAYOUT]: BarLayout }>; @@ -27,17 +27,17 @@ function isBarChart(chart: ChartInstance): chart is BarChartInstance { export function useBarChartContext(part: string) { const context = useContext(ChartContext); if (!context) { - throw new Error(` must be used within `); + throw new Error(` must be used within `); } const { chart, ariaLabel } = context; if (!isBarChart(chart)) { - throw new Error(` needs a chart from BarChart.useBarChart`); + throw new Error(` needs a chart from Chart.useBarChart`); } return { chart, layout: chart[BAR_LAYOUT], ariaLabel }; } export interface StackedBarsContextValue { - /** Registers the `BarChart.Bar` element whose computed `color` paints bars. */ + /** Registers the `Chart.Bar` element whose computed `color` paints bars. */ setBar: (element: BarStyleElement | null) => void; projection: PaintedProjection | null; } @@ -47,7 +47,7 @@ export const StackedBarsContext = createContext( export function useStackedBarsContext(part: string) { const context = useContext(StackedBarsContext); if (!context) { - throw new Error(` must be used within `); + throw new Error(` must be used within `); } return context; } diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts b/packages/mosaic/src/primitives/chart/bars/bar-layout.ts similarity index 98% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts rename to packages/mosaic/src/primitives/chart/bars/bar-layout.ts index a111a7146ba..91da3dd39de 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-layout.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-layout.ts @@ -1,7 +1,7 @@ import { scaleBand, scaleLinear } from 'd3-scale'; import { stack, stackOffsetDiverging } from 'd3-shape'; -import type { ChartMargin, ChartSize } from '../chart/types'; +import type { ChartMargin, ChartSize } from '../types'; import type { BarCategory, BarMark, BarProjection, BarSeries } from './types'; const Y_TICK_COUNT = 5; @@ -37,7 +37,7 @@ type ProjectOptions = Readonly<{ projection?: BarProjection; }>; -/** Bar geometry read from `BarChart.Bar`'s computed style. */ +/** Bar geometry read from `Chart.Bar`'s computed style. */ export type BarGeometry = Readonly<{ maxWidth: number; gap: number; diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts similarity index 94% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts rename to packages/mosaic/src/primitives/chart/bars/bar-selection.ts index 078da73ccb1..8c6b8fa4e51 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-selection.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts @@ -1,5 +1,5 @@ -import type { SelectionModel } from '../chart/internal/selection'; -import type { StackedBarLayout } from './bar-chart-layout'; +import type { SelectionModel } from '../internal/selection'; +import type { StackedBarLayout } from './bar-layout'; import type { ActiveBar, BarCategory, BarSection, BarSelection } from './types'; /** Selects a section of a stacked bar: above the zero line or below it. */ diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-bar.tsx b/packages/mosaic/src/primitives/chart/bars/chart-bar.tsx similarity index 64% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-bar.tsx rename to packages/mosaic/src/primitives/chart/bars/chart-bar.tsx index 26078589605..2e8c004d0f6 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-bar.tsx +++ b/packages/mosaic/src/primitives/chart/bars/chart-bar.tsx @@ -2,17 +2,17 @@ import React from 'react'; -import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { useStackedBarsContext } from './bar-chart-context'; +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../../utils'; +import { useStackedBarsContext } from './bar-context'; -export type BarChartBarProps = ComponentProps<'g'>; +export type ChartBarProps = ComponentProps<'g'>; /** - * Styles the bars that `BarChart.StackedBars` paints on Canvas. Before each paint the primitive puts + * Styles the bars that `Chart.StackedBars` 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 BarChartBar = React.forwardRef(function BarChartBar(props, ref) { +export const ChartBar = React.forwardRef(function ChartBar(props, ref) { const { render, ...otherProps } = props; const { setBar } = useStackedBarsContext('Bar'); diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-projection-outline.tsx b/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx similarity index 69% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-projection-outline.tsx rename to packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx index 39e832520fa..8b95e54bcd9 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-projection-outline.tsx +++ b/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx @@ -2,13 +2,13 @@ import React from 'react'; -import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { useStackedBarsContext } from './bar-chart-context'; +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../../utils'; +import { useStackedBarsContext } from './bar-context'; -export type BarChartProjectionOutlineProps = ComponentProps<'rect'>; +export type ChartProjectionOutlineProps = ComponentProps<'rect'>; -export const BarChartProjectionOutline = React.forwardRef( - function BarChartProjectionOutline(props, ref) { +export const ChartProjectionOutline = React.forwardRef( + function ChartProjectionOutline(props, ref) { const { render, ...otherProps } = props; const { projection } = useStackedBarsContext('ProjectionOutline'); diff --git a/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx b/packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx similarity index 90% rename from packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx rename to packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx index 229eff5c675..295bacc01a9 100644 --- a/packages/mosaic/src/primitives/bar-chart/bar-chart-stacked-bars.tsx +++ b/packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx @@ -2,19 +2,14 @@ import React from 'react'; -import { hasArea } from '../chart/chart-context'; -import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { - type BarStyleElement, - getBarGeometrySnapshot, - paintStackedBarCanvas, - parseBarGeometry, -} from './bar-chart-canvas'; -import { CanvasRenderError } from './bar-chart-canvas-error'; -import { StackedBarsContext, useBarChartContext } from './bar-chart-context'; -import { fitProjectionToBar, projectStackedBarMarks } from './bar-chart-layout'; +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../../utils'; +import { hasArea } from '../chart-context'; +import { type BarStyleElement, getBarGeometrySnapshot, paintStackedBarCanvas, parseBarGeometry } from './bar-canvas'; +import { CanvasRenderError } from './bar-canvas-error'; +import { StackedBarsContext, useBarChartContext } from './bar-context'; +import { fitProjectionToBar, projectStackedBarMarks } from './bar-layout'; -export type BarChartStackedBarsProps = ComponentProps<'div'>; +export type ChartStackedBarsProps = ComponentProps<'div'>; function subscribeToPixelRatio(callback: () => void) { let query = window.matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`); @@ -72,8 +67,8 @@ function subscribeToTheme(bar: Element | null, onChange: () => void) { const getServerSnapshot = () => ''; const getServerPixelRatio = () => 1; -export const BarChartStackedBars = React.forwardRef( - function BarChartStackedBars(props, ref) { +export const ChartStackedBars = React.forwardRef( + function ChartStackedBars(props, ref) { const { children, render, ...otherProps } = props; const { chart, layout, ariaLabel } = useBarChartContext('StackedBars'); const { size, categories, scaleY } = chart; diff --git a/packages/mosaic/src/primitives/bar-chart/types.ts b/packages/mosaic/src/primitives/chart/bars/types.ts similarity index 98% rename from packages/mosaic/src/primitives/bar-chart/types.ts rename to packages/mosaic/src/primitives/chart/bars/types.ts index 8017d236ea7..23745e5361f 100644 --- a/packages/mosaic/src/primitives/bar-chart/types.ts +++ b/packages/mosaic/src/primitives/chart/bars/types.ts @@ -1,4 +1,4 @@ -import type { ChartActive, ChartCategory, ChartSelection } from '../chart/types'; +import type { ChartActive, ChartCategory, ChartSelection } from '../types'; export type CornerRadii = readonly [number, number, number, number]; diff --git a/packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts b/packages/mosaic/src/primitives/chart/bars/use-bar-chart.ts similarity index 82% rename from packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts rename to packages/mosaic/src/primitives/chart/bars/use-bar-chart.ts index 5b7f218566d..5a34d12feba 100644 --- a/packages/mosaic/src/primitives/bar-chart/use-bar-chart.ts +++ b/packages/mosaic/src/primitives/chart/bars/use-bar-chart.ts @@ -2,11 +2,11 @@ import React from 'react'; -import { useChartFrame, useChartInstance } from '../chart/internal/use-chart-instance'; -import type { ChartOptions } from '../chart/types'; -import { BAR_LAYOUT, type BarChartInstance } from './bar-chart-context'; -import { prepareStackedBars, projectStackedBars } from './bar-chart-layout'; -import { barSelectionModel } from './bar-chart-selection'; +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 } from './bar-selection'; import type { ActiveBar, BarIdentity, BarProjection, BarSelection, BarSeries } from './types'; export interface UseBarChartOptions extends ChartOptions> { @@ -19,7 +19,7 @@ export interface UseBarChartOptions extends ChartOptions) => boolean; } diff --git a/packages/mosaic/src/primitives/chart/chart-root.tsx b/packages/mosaic/src/primitives/chart/chart-root.tsx index 7e4d9927f70..f1f5deca1aa 100644 --- a/packages/mosaic/src/primitives/chart/chart-root.tsx +++ b/packages/mosaic/src/primitives/chart/chart-root.tsx @@ -7,7 +7,7 @@ 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 `BarChart.useBarChart`. */ + /** The result of a chart-type hook, such as `Chart.useBarChart`. */ chart: ChartInstance; /** Default: 500 */ height?: number | string; diff --git a/packages/mosaic/src/primitives/chart/chart.doc.ts b/packages/mosaic/src/primitives/chart/chart.doc.ts index 2460ac5a4ae..a0d152ba207 100644 --- a/packages/mosaic/src/primitives/chart/chart.doc.ts +++ b/packages/mosaic/src/primitives/chart/chart.doc.ts @@ -1,9 +1,12 @@ import type { ComponentDoc } from '../../docs-schema'; import type { + ChartBarProps, ChartCursorProps, ChartGridProps, + ChartProjectionOutlineProps, ChartRootProps, ChartSelectionProps, + ChartStackedBarsProps, ChartTooltipProps, ChartXAxisProps, ChartXTickProps, @@ -15,13 +18,32 @@ import type { export default { name: 'Chart', description: - 'Headless, unstyled parts every chart type shares: the root, grid, axes, Y lines, and pointer and keyboard selection with its cursor and tooltip. A chart-type hook, such as `BarChart.useBarChart`, owns the layout and selection and returns a chart object; `Chart.Root` takes it and the parts render from it. `Chart` draws no data. Each container renders nothing until the root has a measured, non-zero size.', + '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.StackedBars` 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: [ - 'axes, a grid and reference lines for a bar chart', + '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', 'axis', 'grid', 'tick', 'tooltip', 'cursor', 'selection', 'data visualization'], + keywords: [ + 'chart', + 'graph', + 'bar chart', + 'stacked bars', + 'diverging', + 'projection', + 'canvas', + 'useBarChart', + 'axis', + 'grid', + 'tick', + 'tooltip', + 'cursor', + 'selection', + 'data visualization', + ], practices: [ { do: true, @@ -39,6 +61,19 @@ export default { 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.', @@ -47,13 +82,21 @@ export default { 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 `BarChart.useBarChart`.' }, + 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' }, }, @@ -74,6 +117,18 @@ export default { value: { type: 'number', doc: 'The value on the Y axis the line marks, such as a tick value or `0`.' }, }, }, + 'Chart.StackedBars': { + description: + 'A `div` that paints the bars on a Canvas with `role="img"`, and holds one SVG over it for `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.StackedBars`.', + }, + 'Chart.ProjectionOutline': { + description: + 'An `aria-hidden` `rect` that outlines the projected bar, when `projection` rises above its stack. Throws outside `Chart.StackedBars`.', + }, 'Chart.YAxis': { description: 'An `aria-hidden` `svg` that holds the Y tick labels in the left margin.', props: { @@ -146,17 +201,18 @@ export default { }, examples: [ { - title: 'Axes, grid, cursor and tooltip around a bar chart', + title: 'Stacked bars with axes, a grid, a cursor and a tooltip', code: ` -const chart = BarChart.useBarChart({ data, series, index, onActivate: openPeriod }); +const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }); {ticks => ticks.map(tick => )} - - - + + + + {ticks => ticks.map(tick => )} @@ -168,14 +224,53 @@ const chart = BarChart.useBarChart({ data, series, index, onActivate: openPeriod > 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: ['BarChart', 'Portal'], + 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`, `onSelectionChange`, `onActivate` and `formatCategory`. 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.StackedBars': ChartStackedBarsProps; + 'Chart.Bar': ChartBarProps; + 'Chart.ProjectionOutline': ChartProjectionOutlineProps; 'Chart.YAxis': ChartYAxisProps; 'Chart.YTick': ChartYTickProps; 'Chart.XAxis': ChartXAxisProps; diff --git a/packages/mosaic/src/primitives/chart/index.ts b/packages/mosaic/src/primitives/chart/index.ts index ae189560567..79a090dd0a3 100644 --- a/packages/mosaic/src/primitives/chart/index.ts +++ b/packages/mosaic/src/primitives/chart/index.ts @@ -1,10 +1,13 @@ export * as Chart from './parts'; export type { + ChartBarProps, ChartCursorProps, ChartGridProps, + ChartProjectionOutlineProps, ChartRootProps, ChartSelectionProps, + ChartStackedBarsProps, ChartTooltipProps, ChartXAxisProps, ChartXTickProps, @@ -12,6 +15,7 @@ export type { ChartYLineProps, ChartYTickItem, ChartYTickProps, + UseBarChartOptions, } from './parts'; export type { ChartActive, @@ -28,3 +32,13 @@ export type { XTickMode, XTicksOptions, } from './types'; +export type { BarChartInstance } from './bars/bar-context'; +export type { + ActiveBar, + BarCategory, + BarIdentity, + BarProjection, + BarSection, + BarSelection, + BarSeries, +} from './bars/types'; 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 index 3e7a823bda4..97dc111e19b 100644 --- a/packages/mosaic/src/primitives/chart/line-chart-contract.test-d.ts +++ b/packages/mosaic/src/primitives/chart/line-chart-contract.test-d.ts @@ -1,6 +1,6 @@ import { describe, expectTypeOf, test } from 'vitest'; -import type { BarChartInstance } from '../bar-chart'; +import type { BarChartInstance } from '.'; import type { SelectionModel } from './internal/selection'; import type { useChartInstance } from './internal/use-chart-instance'; import type { ChartRootProps, ChartTooltipProps } from './parts'; diff --git a/packages/mosaic/src/primitives/chart/parts.ts b/packages/mosaic/src/primitives/chart/parts.ts index 2ada85cf95b..5037ebfcac1 100644 --- a/packages/mosaic/src/primitives/chart/parts.ts +++ b/packages/mosaic/src/primitives/chart/parts.ts @@ -8,3 +8,11 @@ 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 ChartStackedBarsProps, ChartStackedBars as StackedBars } from './bars/chart-stacked-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 index 83bfe0f1661..e71aafac755 100644 --- a/packages/mosaic/src/primitives/chart/types.ts +++ b/packages/mosaic/src/primitives/chart/types.ts @@ -94,7 +94,7 @@ export type ChartInteractionProps = Readonly<{ /** * The measured layout and selection of one chart, returned by a chart-type hook such as - * `BarChart.useBarChart`. `TSelection` defaults to `never`, so `Chart.Root` takes any chart and the + * `Chart.useBarChart`. `TSelection` defaults to `never`, so `Chart.Root` takes any chart and the * shared parts cannot call `select`. */ export type ChartInstance< diff --git a/packages/mosaic/tsdown.config.mts b/packages/mosaic/tsdown.config.mts index a96d88c37a9..ea35fcd5a65 100644 --- a/packages/mosaic/tsdown.config.mts +++ b/packages/mosaic/tsdown.config.mts @@ -87,7 +87,6 @@ export default defineConfig({ 'icons/glyphs/users-add-right': './src/icons/glyphs/users-add-right.tsx', 'primitives/accordion': './src/primitives/accordion/index.ts', 'primitives/autocomplete': './src/primitives/autocomplete/index.ts', - 'primitives/bar-chart': './src/primitives/bar-chart/index.ts', 'primitives/button': './src/primitives/button/index.ts', 'primitives/chart': './src/primitives/chart/index.ts', 'primitives/collapsible': './src/primitives/collapsible/index.ts', diff --git a/packages/swingset/src/components/DocsViewer.tsx b/packages/swingset/src/components/DocsViewer.tsx index dbd1a5ea949..eeb58fd1562 100644 --- a/packages/swingset/src/components/DocsViewer.tsx +++ b/packages/swingset/src/components/DocsViewer.tsx @@ -140,7 +140,7 @@ const docModules: Record> = { // Headless primitives — alphabetical. accordion: dynamic(() => import('../stories/accordion.mdx')), autocomplete: dynamic(() => import('../stories/autocomplete.mdx')), - 'bar-chart': dynamic(() => import('../stories/bar-chart.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 60eabc4c1b6..6c4c3a80723 100644 --- a/packages/swingset/src/lib/registry.ts +++ b/packages/swingset/src/lib/registry.ts @@ -55,10 +55,10 @@ import { LabelOnly as BannerLabelOnly, meta as bannerMeta, } from '../stories/banner.stories'; -import { meta as barChartMeta } from '../stories/bar-chart.stories'; 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, @@ -1148,7 +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 barChartModule: StoryModule = { meta: barChartMeta }; +const chartModule: StoryModule = { meta: chartMeta }; const comboboxPrimitiveModule: StoryModule = { meta: comboboxPrimitiveMeta }; const collapsibleModule: StoryModule = { meta: collapsibleMeta }; const dialogModule: StoryModule = { meta: dialogMeta }; @@ -1655,7 +1655,7 @@ export const registry: StoryModule[] = [ // Primitives accordionModule, autocompleteModule, - barChartModule, + chartModule, comboboxPrimitiveModule, collapsibleModule, dialogModule, diff --git a/packages/swingset/src/stories/bar-chart.mdx b/packages/swingset/src/stories/chart.mdx similarity index 72% rename from packages/swingset/src/stories/bar-chart.mdx rename to packages/swingset/src/stories/chart.mdx index b54367ad537..82e816d491b 100644 --- a/packages/swingset/src/stories/bar-chart.mdx +++ b/packages/swingset/src/stories/chart.mdx @@ -1,12 +1,13 @@ -import * as BarChartStories from './bar-chart.stories'; +import * as ChartStories from './chart.stories'; -# BarChart +# Chart A stacked bar chart over a category or time axis, with values above and below zero. It is a -**headless** primitive: `BarChart.useBarChart` owns the layout and selection, `BarChart` parts paint -the bars, and the shared `Chart` 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. +**headless** primitive: `Chart.useBarChart` owns the layout and selection, `Chart.StackedBars` 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 @@ -16,16 +17,15 @@ unstyled, so the bars take the inherited text color and the grid and zero lines ## Usage ```tsx -import { type ActiveBar, BarChart } from '@clerk/mosaic/primitives/bar-chart'; -import { Chart } from '@clerk/mosaic/primitives/chart'; +import { type ActiveBar, Chart } from '@clerk/mosaic/primitives/chart'; -const chart = BarChart.useBarChart({ data, series, index, onActivate: openPeriod }); +const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }); - - - + + + - + {ticks => ticks.map(tick => ( @@ -89,17 +89,17 @@ const isBarActive = useCallback( !selection || (bar.datum.week === selection.category && bar.positive === (selection.section === 'positive')), [selection], ); -const chart = BarChart.useBarChart({ data, series, index, selection, onSelectionChange: setSelection, isBarActive }); +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 `BarChart.Bar`'s `data-projection` color, and `BarChart.ProjectionOutline` draws its outline. +with `Chart.Bar`'s `data-projection` color, and `Chart.ProjectionOutline` draws its outline. It is drawn only when `value` is above that category's stack. ```tsx -const chart = BarChart.useBarChart({ +const chart = Chart.useBarChart({ data, series, index, @@ -109,31 +109,31 @@ const chart = BarChart.useBarChart({ ## 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 | -| `BarChart.StackedBars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | -| `BarChart.Bar` | `` | Hidden. Its computed style paints the bars | -| `BarChart.ProjectionOutline` | `` | 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 | - -`Chart` parts come from `@clerk/mosaic/primitives/chart` and work with any chart type's hook. +| 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.StackedBars` | `
` | 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` | `` | 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 `BarChart.StackedBars` also throws for a chart that did not come -from `BarChart.useBarChart`. `BarChart.Bar` and `BarChart.ProjectionOutline` throw outside -`BarChart.StackedBars`, and `Chart.Cursor` and `Chart.Tooltip` throw outside `Chart.Selection`. +throws outside `Chart.Root`, and `Chart.StackedBars` also throws for a chart that did not come +from `Chart.useBarChart`. `Chart.Bar` and `Chart.ProjectionOutline` throw outside +`Chart.StackedBars`, and `Chart.Cursor` and `Chart.Tooltip` throw outside `Chart.Selection`. ## Props -### `BarChart.useBarChart` +### `Chart.useBarChart` | Prop | Type | Default | Description | | ------------------------------ | ------------------------------------------------------------ | -------------------------- | ------------------------------------------------------ | @@ -190,7 +190,7 @@ Name the active type the hook selects: `>>`. ## Styling -`BarChart.Bar` styles the Canvas. Before each paint the chart sets these attributes on it, reads +`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 | @@ -201,7 +201,7 @@ its computed `color`, and paints with it: 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 -`BarChart.Bar`, nothing is painted. +`Chart.Bar`, nothing is painted. | Attribute | Applies To | Description | | ----------------------------- | ---------- | -------------------------------------------------------------- | diff --git a/packages/swingset/src/stories/bar-chart.stories.tsx b/packages/swingset/src/stories/chart.stories.tsx similarity index 83% rename from packages/swingset/src/stories/bar-chart.stories.tsx rename to packages/swingset/src/stories/chart.stories.tsx index 889e9808c8d..a3e036e33d7 100644 --- a/packages/swingset/src/stories/bar-chart.stories.tsx +++ b/packages/swingset/src/stories/chart.stories.tsx @@ -1,16 +1,15 @@ 'use client'; -import { type ActiveBar, BarChart } from '@clerk/mosaic/primitives/bar-chart'; -import { Chart } from '@clerk/mosaic/primitives/chart'; +import { type ActiveBar, Chart } from '@clerk/mosaic/primitives/chart'; import type { StoryMeta } from '@/lib/types'; export const meta: StoryMeta = { group: 'Primitives', status: 'wip', - title: 'BarChart', - label: 'Bar Chart', - source: 'packages/mosaic/src/primitives/bar-chart/index.ts', + title: 'Chart', + label: 'Chart', + source: 'packages/mosaic/src/primitives/chart/index.ts', }; const growth = [ @@ -33,7 +32,7 @@ const series = [ const getWeek = (row: GrowthRow) => row.week; export function Default() { - const chart = BarChart.useBarChart({ data: growth, series, index: getWeek }); + const chart = Chart.useBarChart({ data: growth, series, index: getWeek }); return ( - - + + - + {ticks => ticks.map(tick => ( From a58720c86ea347d3a9a6e7d127bc2ca0808269f3 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 12:26:08 -0700 Subject: [PATCH 22/40] fix(mosaic): trace the projection fill with a concentric, crisp outline Chart.ProjectionOutline drew a rect 1px outside the projection fill with one corner radius for all four corners. Its top corners were not concentric with the fill, its bottom corners pulled away from the zero line, and a 1px stroke on it spread across two half-covered pixels. The outline is now a path derived from the same painted projection the Canvas fills: 1.5px outside it, with a top radius of the fill's radius plus 1.5px and square bottom corners on the zero line. Bars 2px or wider and the projection snap their sides to whole pixels, and the projection snaps its top, so a 1px stroke covers whole pixels and leaves a 1px gap. The projection radius is clamped to its height in one place, so the Canvas and the outline read the same number. --- .../mosaic/src/primitives/chart/README.md | 4 +- ...d-bars-dimmed-selection-chromium-linux.png | Bin 8252 -> 7392 bytes .../stacked-bars-diverging-chromium-linux.png | Bin 8506 -> 7347 bytes ...stacked-bars-projection-chromium-linux.png | Bin 7889 -> 6632 bytes ...acked-bars-tooltip-open-chromium-linux.png | Bin 13642 -> 12611 bytes .../__tests__/stacked-bars.browser.test.tsx | 126 ++++++++++++++++++ .../chart/bars/__tests__/test-chart.tsx | 4 +- .../src/primitives/chart/bars/bar-layout.ts | 35 ++++- .../chart/bars/chart-projection-outline.tsx | 38 ++++-- .../mosaic/src/primitives/chart/chart.doc.ts | 2 +- packages/swingset/src/stories/chart.mdx | 2 +- 11 files changed, 190 insertions(+), 21 deletions(-) diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index f71b2914fbc..fc358e486b0 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -82,7 +82,7 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) | `Chart.YLine` | `` | One line across the plot at a Y value, inside any chart SVG | | `Chart.StackedBars` | `
` | 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` | `` | Outlines the projected bar | +| `Chart.ProjectionOutline` | `` | 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 | @@ -326,7 +326,7 @@ Tailwind reads `_` inside `data-[…]` as a space, so a key such as `first_activ | 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. `Chart.ProjectionOutline` takes its width and corner radius from the same geometry. +The geometry is paint only. Selection, the cursor and the scales use the category band. Bars 2px or wider snap their sides to whole pixels, and the projection also snaps its top. `Chart.ProjectionOutline` traces the projection fill the Canvas paints, 1.5px outside it, so a 1px stroke covers whole pixels and leaves a 1px gap. Its top corner radius is the fill's plus 1.5px, so the corners stay concentric, and its bottom corners are square on the zero line. The Canvas repaints in the same frame when: diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-dimmed-selection-chromium-linux.png b/packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-dimmed-selection-chromium-linux.png index 0a8bca3c2ad2b19dd19f5b4c9f994df77e9b723c..7cf4aed9f0463807ebba6c007e2a559fc7e88c4f 100644 GIT binary patch literal 7392 zcmc&(cT`i|p1l+)(nJIVDT>mhDk9RQiF6d{D7`2p6oJr#G(iOE9mE1k5fn8M-`@K~>T0Xf9A`ZaK@g4FP37AV zM2vtSqU#jIVCH3s$z2FK0jVh~+<|8<3s7VakDIQ* z+ZynlItf8%zZ8MzQ)VZkh7e?BbywCmHy8Uq6_%8gpwah+smVfIkQJXkb&a|fanPd& z;NuXK+Wo`6+OXta!0v4RQWfE_J+8jKJ|>1XrCHy^#CLh5hJjaGnS&gv{+P#6t)!$R z?X^(8HSDLVnx2tiTW4oyH#IfI#K{lKar7i6E)XhvgWqg;+i?Y44*N6U|2!|j$%vL(^NLn)Hr>!PQr@$0^o zYHDiq^}J)dj)`DhFsxD8g3S-FCj0vOHZ?b6avlkT^$QB(r+saQIyySKyQkbyT+t+u zg~^S3s_FYA;!=qyzgM&2RGWJ*sa@$>PdI*-mO>ouV`^1oD=KCI)%)cg z%oPT09)Bt8gIo&>y2+H9Dw-27V4&*CG{zYa2P9p zcvjxKRk1{wuJz8MLg z%#f%sLc|>HzcThsE8}XTl(_h(SFa{e)7eynHz<_P-saD=w6qVx7cV||@PG?pog>e8 zXr5AngK4hcTS``T9DSiI%}-rDNbSd{siqc3)#gs=>*~7Plq3K{?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6m7Wh!|^ZCGFs%~s~;h1UGh z|N2l{@B-M#bR#m8`QPK;ug1+Q9B3Wla1OjXlmGw_ofrHBz}J_k@2?3R#=s}Q0|j;Y J!u!TA{|)hvT3rAD diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-diverging-chromium-linux.png b/packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-diverging-chromium-linux.png index a50f90a181d6776ee2f1ec8862b0eafce3df7655..38d1ba0c303d9eea86767a757be9411d71400420 100644 GIT binary patch literal 7347 zcmc(kbyQSq+r~E`A+6%jD2RYGNJ%M(NJxl)w1~70T@o`&sgx*!NQ}}-mo$S&gCNok z(#-%vGxI&@Ipak8 zEoDM7oPUaTG(0P~tYeo|@S2az;Wl^6!1i(;gCa?aLCfdch?3&=tM{2M#$D(S6rqoB zveUSHV@QqXHaVGK{=}+Z-RA_Ifu9>k%QmrVn<6+2&VOL7|C`LXP~MTh!uT4~%H|$1 z1d-+N5I~S(1VjQ|4X_nCVQOkBC=_qY0zus; zag=3fG~!@;r7cE)nfYT*&Z9?<+^-}C1qFprv)bF)k;_s;NV^m4wVa%s!=E2j9&Had z-B?^&vZ_x{O?_Z(eT5~WqN1X93WDD1uM^1nY%d2$#K@UVx6$AmKkX*j5L5}2pGfB!x?Suu&W?TUhef~2J6x)cPZ zi}$L3hoEz0zVuuW#6(*QLAF;RBIx~-C`k(fNSMAek@@ik>rQ1gCoCkqT)|F1Z02*| z{3~>*vBdbrI!bVp_Wg-MDL?1be#>^px5V*QU$Sj0_3kkp=vB@o8TbS;DO9?8jD4GY z^Cf|RNI0qJBcjs>Zc&^QdLND5^Lk>p7=o_85WV+hIJQmz8An8NFaO1BIQ_!Xc;O+Z z@U7}mF^*_ycb&<`040b>c;E}o#RHn$z~ROZ{b_VTy27 z`k)Q!P067SC`Si}tnP*7g#}(AAuTnv*5+o~XT(DIu1$F7&9!_jhV$ne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U!5*DsdCy*kO?F9-9VdH+}5C6Py#lK#0n>5$;XDoW)oU~ zK#@i!s`*qhEh>5ak?YUCmfUwQJQMrDRL~C-;qzJ+QsUT0KTCUi=mhIFL+N!ou~m0I zY_*g%O&<7YguL zdloLdRR@J?Z+CtHK|UJ4jE26v&gp!C!PZe)@$J*F_Uc6CvbS}&i|DxQH^HN)O$Fia zq2fM2xYq!1;tkNO>&{HSzrqL8>TGim$b8>PA85`{KC-*eL5V3zr|wGu>=I4PJysf~ zV^<$)TBoc&^lDB7o7U>?uBo(y^n?xpk z@PJ)R$@tf5`uf83+!rL+3}%zqx82z67X@P0EOJ8*D*>-7wy!kXKgM5M z()$Axjf3s#Xi2FbzzhIEVJ2;f7M9p^x!9c$%hKif0|xB6O;dZ#m$TNE=J2G*Z8hH2 zReSfJ@d0Dj7mS52XrWpGjkDQ{Z&sUtssiA_Z;gD#cu`#{dU^`~8p?Zrs;P+yPA)D* z-~*0_`y0l7+T>)%u!1zK!+#G@AZxB6&-wsA{~xPw;3Fmo^!O;->dOIihWwP~5J1-1 WH$JRLJFdV#AQ=fo@sjt3LH`4I!@ko1 diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx index 1767cce4483..cebbdad5986 100644 --- a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx @@ -24,6 +24,10 @@ beforeAll(async () => { 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); } + .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); } + .outline.hairline { stroke-width: 0.25px; } `; document.head.append(style); }); @@ -202,6 +206,128 @@ describe('painting', () => { }); }); +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})`; + }; + } + + function outline() { + const element = document.querySelector('.outline'); + if (!(element instanceof SVGGeometryElement)) { + throw new Error('The projection outline is not an SVG shape'); + } + return element; + } + + 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('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 (!outline().isPointInStroke(new DOMPoint(x, y))) { + 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')); + const inStroke = (x: number, y: number) => outline().isPointInStroke(new DOMPoint(x, y)); + + expect([inStroke(left - 1.5, zero - 0.1), inStroke(right + 1.5, zero - 0.1)]).toEqual([true, true]); + expect([inStroke(left - 1.5, zero + 0.5), inStroke(right + 1.5, zero + 0.5)]).toEqual([false, false]); + }); +}); + describe('resizing', () => { it('follows its container and keeps painting the full width', async () => { const { rerender } = await render(); diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/test-chart.tsx b/packages/mosaic/src/primitives/chart/bars/__tests__/test-chart.tsx index 9904238baf4..2120bd36be9 100644 --- a/packages/mosaic/src/primitives/chart/bars/__tests__/test-chart.tsx +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/test-chart.tsx @@ -24,6 +24,7 @@ export type TestChartProps = Pick< /** Mounts `Chart.Bar`. Default: true */ bar?: boolean; barClassName?: string; + outlineClassName?: string; /** Receives the chart object after each render. */ chartRef?: { current: BarChartInstance | null }; }; @@ -38,6 +39,7 @@ export function TestChart({ height, bar = true, barClassName, + outlineClassName, chartRef, ...options }: TestChartProps) { @@ -55,7 +57,7 @@ export function TestChart({ > {bar ? : null} - + diff --git a/packages/mosaic/src/primitives/chart/bars/bar-layout.ts b/packages/mosaic/src/primitives/chart/bars/bar-layout.ts index 91da3dd39de..4cf9375914c 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-layout.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-layout.ts @@ -160,6 +160,23 @@ function splitNeighbourGap(previous: DraftBarMark, mark: DraftBa } } +/** Bars at least this wide snap their sides to whole pixels; narrower bars would lose too much width. */ +const MIN_SNAPPED_WIDTH = 2; + +/** + * 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 pixels, so they paint crisp and line up. + */ +function fitBarToBand(band: Readonly<{ x: number; width: number }>, maxWidth: 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 = Math.round(x); + return { x: left, width: Math.round(x + width) - left }; +} + function projectMarksAndPaintInsets(layout: MarkSource, { maxWidth, gap }: BarGeometry) { const { categories, scaleY } = layout; const marks: DraftBarMark[] = []; @@ -175,7 +192,7 @@ function projectMarksAndPaintInsets(layout: MarkSource, { maxWid 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 barWidth = Math.min(category.width, maxWidth); + const fitted = fitBarToBand(category, maxWidth); const stackKey = `${point.datumIndex}:${point.positive}`; const previousMark = previousMarkByStack.get(stackKey); const mark: DraftBarMark = { @@ -183,9 +200,9 @@ function projectMarksAndPaintInsets(layout: MarkSource, { maxWid datum: point.datum, datumIndex: point.datumIndex, value: point.value, - x: category.x + (category.width - barWidth) / 2, + x: fitted.x, y: rawTop, - width: barWidth, + width: fitted.width, height, radii: [0, 0, 0, 0], positive: point.positive, @@ -351,6 +368,7 @@ export function projectStackedBarMarks(layout: MarkSource, geome return applyCornerRadii(projectMarksAndPaintInsets(layout, geometry), 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( @@ -360,11 +378,16 @@ export function fitProjectionToBar( if (!projection) { return null; } - const width = Math.min(projection.width, maxWidth); + const { x, width } = fitBarToBand(projection, maxWidth); + const bottom = projection.y + projection.height; + const y = Math.min(Math.round(projection.y), bottom); + const height = bottom - y; return { ...projection, - x: projection.x + (projection.width - width) / 2, + x, + y, width, - radius: Math.min(outerRadius, width / 2), + height, + radius: Math.min(outerRadius, width / 2, height), }; } diff --git a/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx b/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx index 8b95e54bcd9..f43019fd179 100644 --- a/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx +++ b/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx @@ -4,31 +4,49 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../../utils'; import { useStackedBarsContext } from './bar-context'; +import type { PaintedProjection } from './bar-layout'; -export type ChartProjectionOutlineProps = ComponentProps<'rect'>; +export type ChartProjectionOutlineProps = ComponentProps<'path'>; -export const ChartProjectionOutline = React.forwardRef( +/** From the fill's edge to the path, so a 1px stroke leaves a 1px gap and covers whole pixels. */ +const OUTLINE_OFFSET = 1.5; + +/** Traces the fill at a constant offset, with concentric top corners and a square bottom on zero. */ +function getOutlinePath({ x, y, width, height, radius }: PaintedProjection) { + const left = x - OUTLINE_OFFSET; + const right = x + width + OUTLINE_OFFSET; + const top = y - OUTLINE_OFFSET; + const bottom = y + height; + const r = radius > 0 ? radius + OUTLINE_OFFSET : 0; + return [ + `M${left} ${bottom}`, + `V${top + r}`, + `A${r} ${r} 0 0 1 ${left + r} ${top}`, + `H${right - r}`, + `A${r} ${r} 0 0 1 ${right} ${top + r}`, + `V${bottom}`, + 'Z', + ].join(''); +} + +export const ChartProjectionOutline = React.forwardRef( function ChartProjectionOutline(props, ref) { const { render, ...otherProps } = props; const { projection } = useStackedBarsContext('ProjectionOutline'); const ownProps = projection ? ({ - x: projection.x - 1, - y: projection.y - 1, - width: projection.width + 2, - height: projection.height + 1, - rx: projection.radius, + d: getOutlinePath(projection), pointerEvents: 'none', - } satisfies DefaultProps<'rect'>) + } satisfies DefaultProps<'path'>) : {}; return useRender({ - defaultTagName: 'rect', + defaultTagName: 'path', render, ref, enabled: !!projection, - props: mergeProps<'rect'>(ownProps, otherProps), + props: mergeProps<'path'>(ownProps, otherProps), }); }, ); diff --git a/packages/mosaic/src/primitives/chart/chart.doc.ts b/packages/mosaic/src/primitives/chart/chart.doc.ts index a0d152ba207..bc4d94ebe97 100644 --- a/packages/mosaic/src/primitives/chart/chart.doc.ts +++ b/packages/mosaic/src/primitives/chart/chart.doc.ts @@ -127,7 +127,7 @@ export default { }, 'Chart.ProjectionOutline': { description: - 'An `aria-hidden` `rect` that outlines the projected bar, when `projection` rises above its stack. Throws outside `Chart.StackedBars`.', + 'An `aria-hidden` `path` that outlines the projected bar 1.5px outside its fill, with concentric top corners and a square bottom on the zero line, when `projection` rises above its stack. Throws outside `Chart.StackedBars`.', }, 'Chart.YAxis': { description: 'An `aria-hidden` `svg` that holds the Y tick labels in the left margin.', diff --git a/packages/swingset/src/stories/chart.mdx b/packages/swingset/src/stories/chart.mdx index 82e816d491b..3ec3ef824ff 100644 --- a/packages/swingset/src/stories/chart.mdx +++ b/packages/swingset/src/stories/chart.mdx @@ -116,7 +116,7 @@ const chart = Chart.useBarChart({ | `Chart.YLine` | `` | One line across the plot at a Y value, such as a tick or zero | | `Chart.StackedBars` | `
` | 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` | `` | Outlines the projected bar | +| `Chart.ProjectionOutline` | `` | Outlines the projected bar | | `Chart.YAxis` | `` | Holds the Y tick labels | | `Chart.YTick` | `` | One Y tick label | | `Chart.XAxis` | `` | Holds the category labels | From 9452a77e79e87ad9209628a19c278b780c25b305 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 12:29:56 -0700 Subject: [PATCH 23/40] fix(mosaic): repaint bar chart when a theme switches through any ancestor attribute The theme observer watched only class, style and data-theme on the ancestors of Chart.Bar. A theme switched through another attribute, such as Swingset's html[data-swingset-theme], left the Canvas in stale colors. The observer now watches every attribute on each ancestor up to . Its snapshot is the colors Chart.Bar computes to in each state the bars paint, so an unrelated attribute change compares equal and does not repaint. With 3 series, an inactive state and a projection, the snapshot reads 7 computed colors from the hidden part, about 10 microseconds in Chromium. --- .../mosaic/src/primitives/chart/README.md | 6 +- .../__tests__/stacked-bars.browser.test.tsx | 14 +++++ .../src/primitives/chart/bars/bar-canvas.ts | 15 ++++- .../chart/bars/chart-stacked-bars.tsx | 57 +++++++++---------- 4 files changed, 59 insertions(+), 33 deletions(-) diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index fc358e486b0..6c17929065e 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -331,12 +331,12 @@ The geometry is paint only. Selection, the cursor and the scales use the categor The Canvas repaints in the same frame when: - `Chart.Bar` mounts, unmounts or changes `class` -- any ancestor of `Chart.Bar`, up to ``, changes `class`, `style` or `data-theme`, so a theme class or `color-scheme` set on a wrapper repaints the bars -- `prefers-color-scheme` changes, so `light-dark()` colors under `color-scheme: light dark` follow the OS +- 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.StackedBars` change -Other changes to the computed color do not repaint: a stylesheet added or removed, another media query such as `prefers-contrast`, or an attribute other than those three on an ancestor. 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. +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 diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx index cebbdad5986..c653fa352bf 100644 --- a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx @@ -24,6 +24,7 @@ beforeAll(async () => { 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); } @@ -143,6 +144,19 @@ describe('painting', () => { 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 { diff --git a/packages/mosaic/src/primitives/chart/bars/bar-canvas.ts b/packages/mosaic/src/primitives/chart/bars/bar-canvas.ts index 7fd3dea6a60..11a44f717f2 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-canvas.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-canvas.ts @@ -173,7 +173,7 @@ export function parseBarGeometry(snapshot: string): BarGeometry { }; } -type BarState = Readonly<{ +export type BarState = Readonly<{ seriesKey?: string; inactive?: boolean; projection?: boolean; @@ -214,6 +214,19 @@ function createBarColorResolver(element: BarStyleElement) { 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(); + } +} + type PaintOptions = Readonly<{ canvas: HTMLCanvasElement; marks: readonly BarMark[]; diff --git a/packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx b/packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx index 295bacc01a9..253303b2391 100644 --- a/packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx +++ b/packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx @@ -4,7 +4,14 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../../utils'; import { hasArea } from '../chart-context'; -import { type BarStyleElement, getBarGeometrySnapshot, paintStackedBarCanvas, parseBarGeometry } from './bar-canvas'; +import { + type BarState, + type BarStyleElement, + getBarGeometrySnapshot, + getBarPaletteSnapshot, + paintStackedBarCanvas, + parseBarGeometry, +} from './bar-canvas'; import { CanvasRenderError } from './bar-canvas-error'; import { StackedBarsContext, useBarChartContext } from './bar-context'; import { fitProjectionToBar, projectStackedBarMarks } from './bar-layout'; @@ -27,34 +34,16 @@ function getPixelRatio() { return Math.min(window.devicePixelRatio || 1, 2); } -const THEME_ATTRIBUTES = ['class', 'style', 'data-theme']; const PREFERS_DARK = '(prefers-color-scheme: dark)'; -function getAncestors(element: Element) { - const ancestors: Element[] = []; - for (let node = element.parentElement; node; node = node.parentElement) { - ancestors.push(node); - } - return ancestors; -} - -function getThemeSnapshot(bar: Element | null) { - if (!bar) { - return ''; - } - return JSON.stringify([ - window.matchMedia(PREFERS_DARK).matches, - ...getAncestors(bar).flatMap(element => THEME_ATTRIBUTES.map(name => element.getAttribute(name))), - ]); -} - +/** 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 (const element of getAncestors(bar)) { - observer.observe(element, { attributes: true, attributeFilter: THEME_ATTRIBUTES }); + for (let element = bar.parentElement; element; element = element.parentElement) { + observer.observe(element, { attributes: true }); } const query = window.matchMedia(PREFERS_DARK); query.addEventListener('change', onChange); @@ -88,11 +77,6 @@ export const ChartStackedBars = React.forwardRef void) => subscribeToTheme(bar, onChange), [bar]), - () => getThemeSnapshot(bar), - getServerSnapshot, - ); const barClass = React.useSyncExternalStore( subscribeToBarClass, () => bar?.getAttribute('class') ?? '', @@ -109,6 +93,21 @@ export const ChartStackedBars = React.forwardRef fitProjectionToBar(projectedBar, geometry), [geometry, 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 stackedBarsContext = React.useMemo(() => ({ setBar, projection }), [projection]); React.useLayoutEffect(() => { @@ -121,8 +120,8 @@ export const ChartStackedBars = React.forwardRef canvas.removeEventListener('contextlost', onContextLost); - // `barClass` and `theme` are not read here: they change the computed colors the paint reads from the DOM. - }, [bar, barClass, canvas, isBarActive, marks, pixelRatio, projection, size, theme]); + // `barClass` and `palette` are not read here: they change the computed colors the paint reads from the DOM. + }, [bar, barClass, canvas, isBarActive, marks, palette, pixelRatio, projection, size]); const ownProps = { style: { position: 'absolute', inset: 0 }, From 790a13d39fba14dd3ec13df7f346ec2787bfd72c Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 14:58:00 -0700 Subject: [PATCH 24/40] chore(repo): dedupe the lockfile --- pnpm-lock.yaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c9ff469e5fd..b6078dd14da 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -18324,7 +18324,7 @@ snapshots: dependencies: '@types/istanbul-lib-coverage': 2.0.6 '@types/istanbul-reports': 3.0.4 - '@types/node': 24.19.2 + '@types/node': 22.20.1 '@types/yargs': 15.0.20 chalk: 4.1.2 optional: true @@ -21565,7 +21565,7 @@ snapshots: '@types/ws@7.4.7': dependencies: - '@types/node': 12.20.55 + '@types/node': 22.20.1 '@types/ws@8.18.1': dependencies: @@ -26755,7 +26755,7 @@ snapshots: jest-worker@27.5.1: dependencies: - '@types/node': 24.19.2 + '@types/node': 22.20.1 merge-stream: 2.0.0 supports-color: 8.1.1 optional: true @@ -30329,7 +30329,7 @@ snapshots: rpc-websockets@9.3.8: dependencies: - '@swc/helpers': 0.5.23 + '@swc/helpers': 0.5.21 '@types/uuid': 10.0.0 '@types/ws': 8.18.1 buffer: 6.0.3 From 07e127572012ee936d0b026695d3a9982b9e86b7 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 15:27:42 -0700 Subject: [PATCH 25/40] fix(mosaic): paint the projection outline on the Canvas, snapped to device pixels The outline was an SVG path over the Canvas. At a fractional pixel ratio such as 1.1 or 1.25, the two layers rounded the bar edges to device pixels differently, so the gap beside the fill was wider on one side. Chart.ProjectionOutline is now a hidden element like Chart.Bar. The Canvas reads its stroke, stroke-width and stroke-dasharray and strokes the outline in the same pass as the fill. Bars, the fill and the outline snap to whole device pixels instead of whole CSS pixels, so both sides match at any ratio. --- .../mosaic/src/primitives/chart/README.md | 10 ++- .../chart/bars/__tests__/fixtures.tsx | 7 ++ .../__tests__/stacked-bars.browser.test.tsx | 82 ++++++++++++++++--- .../src/primitives/chart/bars/bar-canvas.ts | 69 ++++++++++++++++ .../src/primitives/chart/bars/bar-context.ts | 5 +- .../src/primitives/chart/bars/bar-layout.ts | 36 +++++--- .../chart/bars/chart-projection-outline.tsx | 50 ++++------- .../chart/bars/chart-stacked-bars.tsx | 53 ++++++++++-- .../mosaic/src/primitives/chart/chart.doc.ts | 4 +- packages/swingset/src/stories/chart.mdx | 6 +- 10 files changed, 247 insertions(+), 75 deletions(-) diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index 6c17929065e..0dc75fde612 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -82,7 +82,7 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) | `Chart.YLine` | `` | One line across the plot at a Y value, inside any chart SVG | | `Chart.StackedBars` | `
` | 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` | `` | Outlines the projected bar | +| `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 | @@ -326,11 +326,13 @@ Tailwind reads `_` inside `data-[…]` as a space, so a key such as `first_activ | 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 pixels, and the projection also snaps its top. `Chart.ProjectionOutline` traces the projection fill the Canvas paints, 1.5px outside it, so a 1px stroke covers whole pixels and leaves a 1px gap. Its top corner radius is the fill's plus 1.5px, so the corners stay concentric, and its bottom corners are square on the zero line. +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` mounts, unmounts or changes `class` +- `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) @@ -350,7 +352,7 @@ Root does not reorder its children, so paint order is JSX order. Write the parts Each container renders nothing until Root has measured a non-zero size. -Inside `Chart.StackedBars`, put `Chart.ProjectionOutline` before the zero `Chart.YLine`. The position of `Chart.Bar` does not matter. +Inside `Chart.StackedBars`, the position of `Chart.Bar` and `Chart.ProjectionOutline` does not matter: both are hidden, and the Canvas paints under every `Chart.YLine`. ## Layout diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/fixtures.tsx b/packages/mosaic/src/primitives/chart/bars/__tests__/fixtures.tsx index a82fbee3dfd..6ee7f9bc1f1 100644 --- a/packages/mosaic/src/primitives/chart/bars/__tests__/fixtures.tsx +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/fixtures.tsx @@ -89,6 +89,13 @@ const context = { 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. */ diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx index c653fa352bf..bd993a91a16 100644 --- a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx @@ -28,7 +28,6 @@ beforeAll(async () => { .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); } - .outline.hairline { stroke-width: 0.25px; } `; document.head.append(style); }); @@ -277,12 +276,26 @@ describe('the projection outline', () => { }; } - function outline() { - const element = document.querySelector('.outline'); - if (!(element instanceof SVGGeometryElement)) { - throw new Error('The projection outline is not an SVG shape'); + /** 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'); } - return element; + 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)'; @@ -307,8 +320,54 @@ describe('the projection outline', () => { 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 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; @@ -321,7 +380,7 @@ describe('the projection outline', () => { [left + RADIUS - dx, top + RADIUS - dy], [right - RADIUS + dx, top + RADIUS - dy], ]) { - if (!outline().isPointInStroke(new DOMPoint(x, y))) { + if (inkAt(x, y) === 0) { missed.push(`${degrees}deg (${x.toFixed(2)}, ${y.toFixed(2)})`); } } @@ -331,14 +390,13 @@ describe('the projection outline', () => { }); it('meets the zero line with square bottom corners', async () => { - await render(); + 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')); - const inStroke = (x: number, y: number) => outline().isPointInStroke(new DOMPoint(x, y)); - expect([inStroke(left - 1.5, zero - 0.1), inStroke(right + 1.5, zero - 0.1)]).toEqual([true, true]); - expect([inStroke(left - 1.5, zero + 0.5), inStroke(right + 1.5, zero + 0.5)]).toEqual([false, false]); + 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]); }); }); diff --git a/packages/mosaic/src/primitives/chart/bars/bar-canvas.ts b/packages/mosaic/src/primitives/chart/bars/bar-canvas.ts index 11a44f717f2..5967e5469a7 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-canvas.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-canvas.ts @@ -227,6 +227,68 @@ export function getBarPaletteSnapshot(element: BarStyleElement | null, states: r } } +/** 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[]; @@ -236,6 +298,8 @@ type PaintOptions = Readonly<{ 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({ @@ -246,6 +310,7 @@ export function paintStackedBarCanvas({ pixelRatio, isBarActive, bar, + projectionOutline, }: PaintOptions) { try { const context = canvas.getContext('2d'); @@ -282,6 +347,10 @@ export function paintStackedBarCanvas({ 0, ]); context.fill(); + const outline = readProjectionOutlineStyle(projectionOutline); + if (outline) { + strokeProjectionOutline(context, projection, outline, pixelRatio); + } } drawCanvasBars({ context, diff --git a/packages/mosaic/src/primitives/chart/bars/bar-context.ts b/packages/mosaic/src/primitives/chart/bars/bar-context.ts index 9b0b474e091..f805fd9410b 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-context.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-context.ts @@ -3,7 +3,7 @@ import { createContext, useContext } from 'react'; import { ChartContext } from '../chart-context'; import type { ChartInstance } from '../types'; import type { BarStyleElement } from './bar-canvas'; -import type { PaintedProjection, PreparedStackedBars, StackedBarLayout } from './bar-layout'; +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`. */ @@ -39,7 +39,8 @@ export function useBarChartContext(part: string) { export interface StackedBarsContextValue { /** Registers the `Chart.Bar` element whose computed `color` paints bars. */ setBar: (element: BarStyleElement | null) => void; - projection: PaintedProjection | null; + /** Registers the `Chart.ProjectionOutline` element whose computed stroke outlines the projection. */ + setProjectionOutline: (element: BarStyleElement | null) => void; } export const StackedBarsContext = createContext(null); diff --git a/packages/mosaic/src/primitives/chart/bars/bar-layout.ts b/packages/mosaic/src/primitives/chart/bars/bar-layout.ts index 4cf9375914c..13f6f344486 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-layout.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-layout.ts @@ -160,24 +160,33 @@ function splitNeighbourGap(previous: DraftBarMark, mark: DraftBa } } -/** Bars at least this wide snap their sides to whole pixels; narrower bars would lose too much width. */ +/** 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 pixels, so they paint crisp and line up. + * 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) { +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 = Math.round(x); - return { x: left, width: Math.round(x + width) - left }; + const left = snapToDevicePixels(x, pixelRatio); + return { x: left, width: snapToDevicePixels(x + width, pixelRatio) - left }; } -function projectMarksAndPaintInsets(layout: MarkSource, { maxWidth, gap }: BarGeometry) { +function projectMarksAndPaintInsets( + layout: MarkSource, + { maxWidth, gap }: BarGeometry, + pixelRatio: number, +) { const { categories, scaleY } = layout; const marks: DraftBarMark[] = []; const previousMarkByStack = new Map>(); @@ -192,7 +201,7 @@ function projectMarksAndPaintInsets(layout: MarkSource, { maxWid 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); + const fitted = fitBarToBand(category, maxWidth, pixelRatio); const stackKey = `${point.datumIndex}:${point.positive}`; const previousMark = previousMarkByStack.get(stackKey); const mark: DraftBarMark = { @@ -364,8 +373,12 @@ export type StackedBarLayout = ReturnType = Pick, 'prepared' | 'scaleY'> & Readonly<{ categories: readonly BarCategory[] }>; -export function projectStackedBarMarks(layout: MarkSource, geometry: BarGeometry): BarMark[] { - return applyCornerRadii(projectMarksAndPaintInsets(layout, geometry), geometry); +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. */ @@ -374,13 +387,14 @@ export type PaintedProjection = NonNullable['projectio export function fitProjectionToBar( projection: StackedBarLayout['projection'], { maxWidth, outerRadius }: BarGeometry, + pixelRatio: number, ): PaintedProjection | null { if (!projection) { return null; } - const { x, width } = fitBarToBand(projection, maxWidth); + const { x, width } = fitBarToBand(projection, maxWidth, pixelRatio); const bottom = projection.y + projection.height; - const y = Math.min(Math.round(projection.y), bottom); + const y = Math.min(snapToDevicePixels(projection.y, pixelRatio), bottom); const height = bottom - y; return { ...projection, diff --git a/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx b/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx index f43019fd179..b1e0d704eb0 100644 --- a/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx +++ b/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx @@ -4,49 +4,29 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../../utils'; import { useStackedBarsContext } from './bar-context'; -import type { PaintedProjection } from './bar-layout'; -export type ChartProjectionOutlineProps = ComponentProps<'path'>; +export type ChartProjectionOutlineProps = ComponentProps<'g'>; -/** From the fill's edge to the path, so a 1px stroke leaves a 1px gap and covers whole pixels. */ -const OUTLINE_OFFSET = 1.5; - -/** Traces the fill at a constant offset, with concentric top corners and a square bottom on zero. */ -function getOutlinePath({ x, y, width, height, radius }: PaintedProjection) { - const left = x - OUTLINE_OFFSET; - const right = x + width + OUTLINE_OFFSET; - const top = y - OUTLINE_OFFSET; - const bottom = y + height; - const r = radius > 0 ? radius + OUTLINE_OFFSET : 0; - return [ - `M${left} ${bottom}`, - `V${top + r}`, - `A${r} ${r} 0 0 1 ${left + r} ${top}`, - `H${right - r}`, - `A${r} ${r} 0 0 1 ${right} ${top + r}`, - `V${bottom}`, - 'Z', - ].join(''); -} - -export const ChartProjectionOutline = React.forwardRef( +/** + * Styles the outline that `Chart.StackedBars` 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 { projection } = useStackedBarsContext('ProjectionOutline'); + const { setProjectionOutline } = useStackedBarsContext('ProjectionOutline'); - const ownProps = projection - ? ({ - d: getOutlinePath(projection), - pointerEvents: 'none', - } satisfies DefaultProps<'path'>) - : {}; + const ownProps = { + 'aria-hidden': true, + style: { display: 'none' }, + } satisfies DefaultProps<'g'>; return useRender({ - defaultTagName: 'path', + defaultTagName: 'g', render, - ref, - enabled: !!projection, - props: mergeProps<'path'>(ownProps, otherProps), + ref: [setProjectionOutline, ref], + props: mergeProps<'g'>(ownProps, otherProps), }); }, ); diff --git a/packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx b/packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx index 253303b2391..f70308795bb 100644 --- a/packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx +++ b/packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx @@ -9,6 +9,7 @@ import { type BarStyleElement, getBarGeometrySnapshot, getBarPaletteSnapshot, + getProjectionOutlineSnapshot, paintStackedBarCanvas, parseBarGeometry, } from './bar-canvas'; @@ -53,6 +54,20 @@ function subscribeToTheme(bar: Element | null, onChange: () => void) { }; } +/** 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; @@ -66,6 +81,7 @@ export const ChartStackedBars = React.forwardRef(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) { @@ -89,10 +105,13 @@ export const ChartStackedBars = React.forwardRef parseBarGeometry(barGeometry), [barGeometry]); const marks = React.useMemo( - () => projectStackedBarMarks({ prepared, categories, scaleY }, geometry), - [categories, geometry, prepared, scaleY], + () => projectStackedBarMarks({ prepared, categories, scaleY }, geometry, pixelRatio), + [categories, geometry, pixelRatio, prepared, scaleY], + ); + const projection = React.useMemo( + () => fitProjectionToBar(projectedBar, geometry, pixelRatio), + [geometry, pixelRatio, projectedBar], ); - const projection = React.useMemo(() => fitProjectionToBar(projectedBar, geometry), [geometry, projectedBar]); const paletteStates = React.useMemo(() => { const states: BarState[] = projection ? [{ projection: true }] : []; for (const seriesKey of new Set(marks.map(mark => mark.seriesKey))) { @@ -108,20 +127,40 @@ export const ChartStackedBars = React.forwardRef getBarPaletteSnapshot(bar, paletteStates), getServerSnapshot, ); - const stackedBarsContext = React.useMemo(() => ({ setBar, projection }), [projection]); + const outlineStyle = React.useSyncExternalStore( + React.useCallback( + (onChange: () => void) => subscribeToPartStyle(projectionOutline, onChange), + [projectionOutline], + ), + () => getProjectionOutlineSnapshot(projectionOutline), + getServerSnapshot, + ); + const stackedBarsContext = React.useMemo(() => ({ setBar, setProjectionOutline }), []); React.useLayoutEffect(() => { if (!canvas || !hasArea(size)) { return; } - paintStackedBarCanvas({ canvas, marks, projection, size, pixelRatio, isBarActive, bar }); + 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` and `palette` are not read here: they change the computed colors the paint reads from the DOM. - }, [bar, barClass, canvas, isBarActive, marks, palette, pixelRatio, projection, size]); + // `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 }, diff --git a/packages/mosaic/src/primitives/chart/chart.doc.ts b/packages/mosaic/src/primitives/chart/chart.doc.ts index bc4d94ebe97..9f01041791c 100644 --- a/packages/mosaic/src/primitives/chart/chart.doc.ts +++ b/packages/mosaic/src/primitives/chart/chart.doc.ts @@ -119,7 +119,7 @@ export default { }, 'Chart.StackedBars': { description: - 'A `div` that paints the bars on a Canvas with `role="img"`, and holds one SVG over it for `Chart.ProjectionOutline` and any `Chart.YLine`. Throws outside `Chart.Root`, and when the chart did not come from `Chart.useBarChart`.', + '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: @@ -127,7 +127,7 @@ export default { }, 'Chart.ProjectionOutline': { description: - 'An `aria-hidden` `path` that outlines the projected bar 1.5px outside its fill, with concentric top corners and a square bottom on the zero line, when `projection` rises above its stack. Throws outside `Chart.StackedBars`.', + '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.StackedBars`.', }, 'Chart.YAxis': { description: 'An `aria-hidden` `svg` that holds the Y tick labels in the left margin.', diff --git a/packages/swingset/src/stories/chart.mdx b/packages/swingset/src/stories/chart.mdx index 3ec3ef824ff..e7eb4272b2a 100644 --- a/packages/swingset/src/stories/chart.mdx +++ b/packages/swingset/src/stories/chart.mdx @@ -95,7 +95,9 @@ const chart = Chart.useBarChart({ data, series, index, selection, onSelectionCha ### Projection `projection` draws a projected total above one category's positive stack. The fill is painted -with `Chart.Bar`'s `data-projection` color, and `Chart.ProjectionOutline` draws its outline. +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 @@ -116,7 +118,7 @@ const chart = Chart.useBarChart({ | `Chart.YLine` | `` | One line across the plot at a Y value, such as a tick or zero | | `Chart.StackedBars` | `
` | 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` | `` | Outlines the projected bar | +| `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 | From 1fdc34eacdd5ff0f8df854384c8297930acc6368 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 16:02:32 -0700 Subject: [PATCH 26/40] docs(swingset): show Dashboard's weekly active users in the chart primitive story --- .../swingset/src/stories/chart.stories.tsx | 90 ++++++++++++++++--- 1 file changed, 80 insertions(+), 10 deletions(-) diff --git a/packages/swingset/src/stories/chart.stories.tsx b/packages/swingset/src/stories/chart.stories.tsx index a3e036e33d7..cfd5c8de159 100644 --- a/packages/swingset/src/stories/chart.stories.tsx +++ b/packages/swingset/src/stories/chart.stories.tsx @@ -12,21 +12,91 @@ export const meta: StoryMeta = { source: 'packages/mosaic/src/primitives/chart/index.ts', }; +/** Weekly active users, as Dashboard's overview reports them. */ 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 }, + { + 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, + retainedChurned: -12, + reactivatedChurned: -6, + newChurned: -9, + }, ]; 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 }, + { 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; @@ -37,7 +107,7 @@ export function Default() { From 6a3edd9e35d5b6126442a13f9f4b0f78866ac6ec Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 16:12:15 -0700 Subject: [PATCH 27/40] docs(swingset): leave churn out of the week in progress, as Dashboard does --- packages/swingset/src/stories/chart.stories.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/swingset/src/stories/chart.stories.tsx b/packages/swingset/src/stories/chart.stories.tsx index cfd5c8de159..64728d06c73 100644 --- a/packages/swingset/src/stories/chart.stories.tsx +++ b/packages/swingset/src/stories/chart.stories.tsx @@ -82,9 +82,10 @@ const growth = [ retained: 158, reactivated: 14, new: 27, - retainedChurned: -12, - reactivatedChurned: -6, - newChurned: -9, + // Churn is known only once the week ends, so the week in progress has none. + retainedChurned: null, + reactivatedChurned: null, + newChurned: null, }, ]; From 6004e422da96e685801e11c5465b7e2c0ae2cacd Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 19:51:30 -0700 Subject: [PATCH 28/40] refactor(mosaic): rename Chart.StackedBars to Chart.Bars The marks part paints whatever arrangement useBarChart lays out. A single series is a plain bar chart, and a later grouped mode would render through the same part, so the name no longer says "stacked". The stack layout functions keep their names, since they compute the stacked arrangement itself. --- .changeset/mosaic-chart-primitive.md | 6 +- .../mosaic/src/primitives/chart/README.md | 22 +- .../bars/__tests__/stacked-bars.test.tsx | 12 +- .../__tests__/stacked-bars.visual.test.tsx | 4 +- .../chart/bars/__tests__/test-chart.tsx | 4 +- .../src/primitives/chart/bars/bar-context.ts | 10 +- .../src/primitives/chart/bars/chart-bar.tsx | 6 +- .../src/primitives/chart/bars/chart-bars.tsx | 195 +++++++++++++++++ .../chart/bars/chart-projection-outline.tsx | 6 +- .../chart/bars/chart-stacked-bars.tsx | 200 ------------------ .../mosaic/src/primitives/chart/chart.doc.ts | 20 +- packages/mosaic/src/primitives/chart/index.ts | 2 +- packages/mosaic/src/primitives/chart/parts.ts | 2 +- packages/swingset/src/stories/chart.mdx | 12 +- .../swingset/src/stories/chart.stories.tsx | 4 +- 15 files changed, 250 insertions(+), 255 deletions(-) create mode 100644 packages/mosaic/src/primitives/chart/bars/chart-bars.tsx delete mode 100644 packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx diff --git a/.changeset/mosaic-chart-primitive.md b/.changeset/mosaic-chart-primitive.md index 12709e1d6a9..a5d85e9d73c 100644 --- a/.changeset/mosaic-chart-primitive.md +++ b/.changeset/mosaic-chart-primitive.md @@ -2,7 +2,7 @@ '@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.StackedBars` 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. +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'; @@ -10,9 +10,9 @@ import { Chart } from '@clerk/mosaic/primitives/chart'; const chart = Chart.useBarChart({ data, series, index }); - + - + {ticks => ticks.map(tick => )} ; ``` diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index 0dc75fde612..96a10cca61e 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -34,14 +34,14 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) )) } - + - + {ticks => ticks.map(tick => ( @@ -80,7 +80,7 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) | `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.StackedBars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | +| `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 | @@ -93,7 +93,7 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) 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.StackedBars` also throws when the chart did not come from `Chart.useBarChart`. `Chart.Bar` and `Chart.ProjectionOutline` throw outside `Chart.StackedBars`, and `Chart.Cursor` and `Chart.Tooltip` throw outside `Chart.Selection`. A `Chart.YLine` inside `Chart.StackedBars`, such as the zero line, paints over the bars. +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`. @@ -255,7 +255,7 @@ const { rootRef } = chart; 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.StackedBars` for that. +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 @@ -287,7 +287,7 @@ 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.StackedBars` puts it in every state it draws, reads its computed `color`, caches it per state, paints, then restores the element: +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` | | --------------- | ----------------------------------- | @@ -336,7 +336,7 @@ The Canvas repaints in the same frame when: - 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.StackedBars` change +- 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. @@ -345,18 +345,18 @@ Other changes to the computed color do not repaint: a stylesheet added or remove 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.StackedBars`, with any `Chart.YLine` inside their SVG +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.StackedBars`, the position of `Chart.Bar` and `Chart.ProjectionOutline` does not matter: both are hidden, and the Canvas paints under every `Chart.YLine`. +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.StackedBars` projects the bar marks when the layout or the bar geometry changes. The container size is committed before paint, so the chart follows its container while resizing. +`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 container size is committed 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. @@ -376,4 +376,4 @@ A lost or missing 2D context throws `Chart.CanvasRenderError`, with the original ## 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, where the keyboard lands, how a selection resolves against the data, the announcement and the tooltip's Y. Its marks read their own layout from a module-private symbol on the instance, as `Chart.StackedBars` does. Its hook and parts join the `Chart` namespace in `parts.ts`. `line-chart-contract.test-d.ts` checks that a point chart fits the contract. +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, where the keyboard lands, how a selection resolves against the data, the announcement and the tooltip's Y. 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 fits the contract. diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.test.tsx b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.test.tsx index e4dd08ef4d9..ad4676a8801 100644 --- a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.test.tsx +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.test.tsx @@ -43,7 +43,7 @@ describe('composing parts', () => { it.each([ ['Chart.Grid', ], ['Chart.Selection', ], - ['Chart.StackedBars', ], + ['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 `); @@ -59,7 +59,7 @@ describe('composing parts', () => { ); }); - it('throws when Chart.Bar is used outside Chart.StackedBars', () => { + it('throws when Chart.Bar is used outside Chart.Bars', () => { vi.spyOn(console, 'error').mockImplementation(() => {}); expect(() => render( @@ -67,7 +67,7 @@ describe('composing parts', () => { , ), - ).toThrow(' must be used within '); + ).toThrow(' must be used within '); }); it.each([ @@ -76,7 +76,7 @@ describe('composing parts', () => { ])('renders a part as %s passed to render', (_, renderElement) => { const { container } = render( - + , ); @@ -95,7 +95,7 @@ describe('composing parts', () => { it('is interactive with Chart.Selection and categories', () => { const { container, rerender } = render( - + , ); @@ -105,7 +105,7 @@ describe('composing parts', () => { rerender( - + , ); diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.visual.test.tsx b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.visual.test.tsx index 1e951f9bbba..8edce2426ca 100644 --- a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.visual.test.tsx +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.visual.test.tsx @@ -89,14 +89,14 @@ function GrowthChart({ )) } - + - + {ticks => ticks.map(tick => ( diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/test-chart.tsx b/packages/mosaic/src/primitives/chart/bars/__tests__/test-chart.tsx index 2120bd36be9..8369243067f 100644 --- a/packages/mosaic/src/primitives/chart/bars/__tests__/test-chart.tsx +++ b/packages/mosaic/src/primitives/chart/bars/__tests__/test-chart.tsx @@ -55,11 +55,11 @@ export function TestChart({ height={height} aria-label={ariaLabel} > - + {bar ? : null} - + {ticks => ticks.map(tick => ( diff --git a/packages/mosaic/src/primitives/chart/bars/bar-context.ts b/packages/mosaic/src/primitives/chart/bars/bar-context.ts index f805fd9410b..b339a934874 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-context.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-context.ts @@ -36,19 +36,19 @@ export function useBarChartContext(part: string) { return { chart, layout: chart[BAR_LAYOUT], ariaLabel }; } -export interface StackedBarsContextValue { +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 StackedBarsContext = createContext(null); +export const BarsContext = createContext(null); -export function useStackedBarsContext(part: string) { - const context = useContext(StackedBarsContext); +export function useBarsContext(part: string) { + const context = useContext(BarsContext); if (!context) { - throw new Error(` must be used within `); + throw new Error(` must be used within `); } return context; } diff --git a/packages/mosaic/src/primitives/chart/bars/chart-bar.tsx b/packages/mosaic/src/primitives/chart/bars/chart-bar.tsx index 2e8c004d0f6..1c7f0c65ef9 100644 --- a/packages/mosaic/src/primitives/chart/bars/chart-bar.tsx +++ b/packages/mosaic/src/primitives/chart/bars/chart-bar.tsx @@ -3,18 +3,18 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../../utils'; -import { useStackedBarsContext } from './bar-context'; +import { useBarsContext } from './bar-context'; export type ChartBarProps = ComponentProps<'g'>; /** - * Styles the bars that `Chart.StackedBars` paints on Canvas. Before each paint the primitive puts + * 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 } = useStackedBarsContext('Bar'); + const { setBar } = useBarsContext('Bar'); const ownProps = { 'aria-hidden': true, 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 index b1e0d704eb0..97ddcd8acfe 100644 --- a/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx +++ b/packages/mosaic/src/primitives/chart/bars/chart-projection-outline.tsx @@ -3,19 +3,19 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../../utils'; -import { useStackedBarsContext } from './bar-context'; +import { useBarsContext } from './bar-context'; export type ChartProjectionOutlineProps = ComponentProps<'g'>; /** - * Styles the outline that `Chart.StackedBars` paints around the projection on Canvas, in the same + * 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 } = useStackedBarsContext('ProjectionOutline'); + const { setProjectionOutline } = useBarsContext('ProjectionOutline'); const ownProps = { 'aria-hidden': true, diff --git a/packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx b/packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx deleted file mode 100644 index f70308795bb..00000000000 --- a/packages/mosaic/src/primitives/chart/bars/chart-stacked-bars.tsx +++ /dev/null @@ -1,200 +0,0 @@ -'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 { StackedBarsContext, useBarChartContext } from './bar-context'; -import { fitProjectionToBar, projectStackedBarMarks } from './bar-layout'; - -export type ChartStackedBarsProps = 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 ChartStackedBars = React.forwardRef( - function ChartStackedBars(props, ref) { - const { children, render, ...otherProps } = props; - const { chart, layout, ariaLabel } = useBarChartContext('StackedBars'); - 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 stackedBarsContext = 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/chart.doc.ts b/packages/mosaic/src/primitives/chart/chart.doc.ts index 9f01041791c..2583244ddf2 100644 --- a/packages/mosaic/src/primitives/chart/chart.doc.ts +++ b/packages/mosaic/src/primitives/chart/chart.doc.ts @@ -1,12 +1,12 @@ import type { ComponentDoc } from '../../docs-schema'; import type { ChartBarProps, + ChartBarsProps, ChartCursorProps, ChartGridProps, ChartProjectionOutlineProps, ChartRootProps, ChartSelectionProps, - ChartStackedBarsProps, ChartTooltipProps, ChartXAxisProps, ChartXTickProps, @@ -18,7 +18,7 @@ import type { 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.StackedBars` 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.', + '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', @@ -117,17 +117,17 @@ export default { value: { type: 'number', doc: 'The value on the Y axis the line marks, such as a tick value or `0`.' }, }, }, - 'Chart.StackedBars': { + '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.StackedBars`.', + '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.StackedBars`.', + '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.', @@ -209,10 +209,10 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) {ticks => ticks.map(tick => )} - + - + {ticks => ticks.map(tick => )} @@ -232,11 +232,11 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) const chart = Chart.useBarChart({ data, series, index, projection: { datumIndex: data.length - 1, value: 130 } }); - + - + `, }, @@ -268,7 +268,7 @@ const chart = Chart.useBarChart({ data, series, index, selection, onSelectionCha 'Chart.Root': ChartRootProps; 'Chart.Grid': ChartGridProps; 'Chart.YLine': ChartYLineProps; - 'Chart.StackedBars': ChartStackedBarsProps; + 'Chart.Bars': ChartBarsProps; 'Chart.Bar': ChartBarProps; 'Chart.ProjectionOutline': ChartProjectionOutlineProps; 'Chart.YAxis': ChartYAxisProps; diff --git a/packages/mosaic/src/primitives/chart/index.ts b/packages/mosaic/src/primitives/chart/index.ts index 79a090dd0a3..e54d0bf17a7 100644 --- a/packages/mosaic/src/primitives/chart/index.ts +++ b/packages/mosaic/src/primitives/chart/index.ts @@ -2,12 +2,12 @@ export * as Chart from './parts'; export type { ChartBarProps, + ChartBarsProps, ChartCursorProps, ChartGridProps, ChartProjectionOutlineProps, ChartRootProps, ChartSelectionProps, - ChartStackedBarsProps, ChartTooltipProps, ChartXAxisProps, ChartXTickProps, diff --git a/packages/mosaic/src/primitives/chart/parts.ts b/packages/mosaic/src/primitives/chart/parts.ts index 5037ebfcac1..8047f6dc07e 100644 --- a/packages/mosaic/src/primitives/chart/parts.ts +++ b/packages/mosaic/src/primitives/chart/parts.ts @@ -9,7 +9,7 @@ export { type ChartSelectionProps, ChartSelection as Selection } from './chart-s 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 ChartStackedBarsProps, ChartStackedBars as StackedBars } from './bars/chart-stacked-bars'; +export { type ChartBarsProps, ChartBars as Bars } from './bars/chart-bars'; export { type ChartBarProps, ChartBar as Bar } from './bars/chart-bar'; export { type ChartProjectionOutlineProps, diff --git a/packages/swingset/src/stories/chart.mdx b/packages/swingset/src/stories/chart.mdx index e7eb4272b2a..6756d88d925 100644 --- a/packages/swingset/src/stories/chart.mdx +++ b/packages/swingset/src/stories/chart.mdx @@ -3,7 +3,7 @@ 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.StackedBars` and +**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 @@ -42,11 +42,11 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) )) } - + - + {ticks => ticks.map(tick => ( @@ -116,7 +116,7 @@ const chart = Chart.useBarChart({ | `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.StackedBars` | `
` | Paints the bars on Canvas and holds an SVG for the marks above them | +| `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 | @@ -129,9 +129,9 @@ const chart = Chart.useBarChart({ 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.StackedBars` also throws for a chart that did not come +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.StackedBars`, and `Chart.Cursor` and `Chart.Tooltip` throw outside `Chart.Selection`. +`Chart.Bars`, and `Chart.Cursor` and `Chart.Tooltip` throw outside `Chart.Selection`. ## Props diff --git a/packages/swingset/src/stories/chart.stories.tsx b/packages/swingset/src/stories/chart.stories.tsx index 64728d06c73..ba440b58543 100644 --- a/packages/swingset/src/stories/chart.stories.tsx +++ b/packages/swingset/src/stories/chart.stories.tsx @@ -121,10 +121,10 @@ export function Default() { )) } - + - + {ticks => ticks.map(tick => ( From 567038746b0f1677054af6cb2884773ca981ca56 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 22:42:49 -0700 Subject: [PATCH 29/40] fix(mosaic): follow the primitive conventions in the Chart primitive - Take the screen reader text through a `messages` option with English defaults (`ChartMessages`, and `BarChartMessages` for the Up and Down sections), so a styled layer can pass localized strings. - Drop `data-chart-interaction` from the inner interaction surface: primitives emit no slot attributes. Find the surface by its role. - Move the tests that cover the whole chart from bars/__tests__ to chart/__tests__, with their screenshots, and add axe checks. --- .../mosaic/src/primitives/chart/README.md | 21 ++++---- ...d-bars-dimmed-selection-chromium-linux.png | Bin .../stacked-bars-diverging-chromium-linux.png | Bin ...stacked-bars-projection-chromium-linux.png | Bin ...acked-bars-tooltip-open-chromium-linux.png | Bin .../chart.browser.test.tsx} | 2 +- .../chart.test.tsx} | 51 +++++++++++++++++- .../chart.visual.test.tsx} | 2 +- .../chart/{bars => }/__tests__/fixtures.tsx | 4 +- .../chart/{bars => }/__tests__/test-chart.tsx | 3 +- .../primitives/chart/bars/bar-selection.ts | 14 +++-- .../mosaic/src/primitives/chart/bars/types.ts | 13 ++++- .../primitives/chart/bars/use-bar-chart.ts | 16 ++++-- .../src/primitives/chart/chart-selection.tsx | 1 - .../mosaic/src/primitives/chart/chart.doc.ts | 4 +- packages/mosaic/src/primitives/chart/index.ts | 2 + .../primitives/chart/internal/selection.ts | 21 ++++---- .../chart/internal/use-chart-instance.ts | 6 ++- packages/mosaic/src/primitives/chart/types.ts | 14 +++++ 19 files changed, 136 insertions(+), 38 deletions(-) rename packages/mosaic/src/primitives/chart/{bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx => __tests__/__screenshots__/chart.visual.test.tsx}/stacked-bars-dimmed-selection-chromium-linux.png (100%) rename packages/mosaic/src/primitives/chart/{bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx => __tests__/__screenshots__/chart.visual.test.tsx}/stacked-bars-diverging-chromium-linux.png (100%) rename packages/mosaic/src/primitives/chart/{bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx => __tests__/__screenshots__/chart.visual.test.tsx}/stacked-bars-projection-chromium-linux.png (100%) rename packages/mosaic/src/primitives/chart/{bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx => __tests__/__screenshots__/chart.visual.test.tsx}/stacked-bars-tooltip-open-chromium-linux.png (100%) rename packages/mosaic/src/primitives/chart/{bars/__tests__/stacked-bars.browser.test.tsx => __tests__/chart.browser.test.tsx} (99%) rename packages/mosaic/src/primitives/chart/{bars/__tests__/stacked-bars.test.tsx => __tests__/chart.test.tsx} (90%) rename packages/mosaic/src/primitives/chart/{bars/__tests__/stacked-bars.visual.test.tsx => __tests__/chart.visual.test.tsx} (99%) rename packages/mosaic/src/primitives/chart/{bars => }/__tests__/fixtures.tsx (97%) rename packages/mosaic/src/primitives/chart/{bars => }/__tests__/test-chart.tsx (98%) diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index 96a10cca61e..30822cb885d 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -146,8 +146,9 @@ Name the active type the chart's hook selects, such as ` void` | — | Called when the user, `select` or `clear` changes the selection | | `onActivate` | `(active: ActiveBar) => void` | — | Called on click, Enter or Space. Makes the surface a button | | `formatCategory` | `(key: string) => string \| null` | the key | Names a period in keyboard announcements | +| `messages` | `Partial` | English | Screen reader text, including how Up and Down move | -`BarSelection` is `{ category, section }`. A new `isBarActive` function repaints the Canvas. `margin` and the last four options are the [options every chart type takes](#options-every-chart-type-takes). +`BarSelection` is `{ category, section }`. A new `isBarActive` function repaints the Canvas. `margin` and the last five options are the [options every chart type takes](#options-every-chart-type-takes). `BarChartMessages` adds `vertical`, `positiveValues` and `negativeValues` to `ChartMessages`. The hook returns a `BarChartInstance`: the [chart object](#the-chart-object) with `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. @@ -177,13 +178,14 @@ A category's `x` and `width` are the extent its marks occupy: a band for bars. I ## 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 | -| `onActivate` | `(active: TActive) => void` | — | Called on click, Enter or Space. Makes the surface a button | -| `formatCategory` | `(key: string) => string \| null` | the key | Names a period in keyboard announcements | +| 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 | +| `onActivate` | `(active: TActive) => void` | — | Called on click, Enter or Space. Makes the surface a button | +| `formatCategory` | `(key: string) => string \| null` | the key | Names a period in keyboard announcements | +| `messages` | `Partial` | English | Screen reader text: `navigate`, `activate`, `dismiss`, `noValues` | ## Keyboard @@ -263,7 +265,6 @@ Painting the bars is the one thing the chart object does not do, because their c | ----------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------- | | `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-chart-interaction` | `Chart.Selection` | On the interaction surface inside the part | | `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 | @@ -274,7 +275,7 @@ The interaction surface also carries the chart type's state, such as `data-activ - 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`. -- Visually hidden text describes the keys. A `status` region announces the selected period, named through `formatCategory`, and what the chart type adds. +- 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 diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.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 similarity index 100% rename from packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-dimmed-selection-chromium-linux.png rename to packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-dimmed-selection-chromium-linux.png diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.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 similarity index 100% rename from packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-diverging-chromium-linux.png rename to packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-diverging-chromium-linux.png diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.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 similarity index 100% rename from packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-projection-chromium-linux.png rename to packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-projection-chromium-linux.png diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.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 similarity index 100% rename from packages/mosaic/src/primitives/chart/bars/__tests__/__screenshots__/stacked-bars.visual.test.tsx/stacked-bars-tooltip-open-chromium-linux.png rename to packages/mosaic/src/primitives/chart/__tests__/__screenshots__/chart.visual.test.tsx/stacked-bars-tooltip-open-chromium-linux.png diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx similarity index 99% rename from packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx rename to packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx index bd993a91a16..dd1bbde5694 100644 --- a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx @@ -5,7 +5,7 @@ import { useRef } from 'react'; import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import { cdp, page, userEvent } from 'vitest/browser'; -import type { BarSelection } from '../types'; +import type { BarSelection } from '../bars/types'; import { TestChart, type TestChartProps } from './test-chart'; type Row = { period: string; value: number }; diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx similarity index 90% rename from packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.test.tsx rename to packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx index ad4676a8801..b55dcc9d44e 100644 --- a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx @@ -2,8 +2,9 @@ import { cleanup, fireEvent, render as renderComponent, screen } from '@testing- import { useState } from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { RenderProps } from '../../../utils'; -import { type BarSelection, Chart } from '../..'; +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'; @@ -213,6 +214,52 @@ describe('choosing a period with the keyboard', () => { press(interaction, ...keys); expect(getByRole('status')).toHaveTextContent(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, data: twoSided, messages: french }); + press(interaction, 'ArrowDown'); + expect(getByRole('status')).toHaveTextContent('Jan, valeurs négatives'); + }); + + 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('describes the keys in the language of `messages`', () => { + const { interaction } = renderChart({ + data: quarter, + 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', () => { diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.visual.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.visual.test.tsx similarity index 99% rename from packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.visual.test.tsx rename to packages/mosaic/src/primitives/chart/__tests__/chart.visual.test.tsx index 8edce2426ca..69768647930 100644 --- a/packages/mosaic/src/primitives/chart/bars/__tests__/stacked-bars.visual.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.visual.test.tsx @@ -3,7 +3,7 @@ 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 '../..'; +import { type ActiveBar, type BarIdentity, type BarProjection, Chart } from '..'; const growth = [ { week: '2026-01-05', signups: 40, returning: 22, churned: -14 }, diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/fixtures.tsx b/packages/mosaic/src/primitives/chart/__tests__/fixtures.tsx similarity index 97% rename from packages/mosaic/src/primitives/chart/bars/__tests__/fixtures.tsx rename to packages/mosaic/src/primitives/chart/__tests__/fixtures.tsx index 6ee7f9bc1f1..4e7d8bbf273 100644 --- a/packages/mosaic/src/primitives/chart/bars/__tests__/fixtures.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/fixtures.tsx @@ -2,8 +2,8 @@ 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 '../types'; +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. */ diff --git a/packages/mosaic/src/primitives/chart/bars/__tests__/test-chart.tsx b/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx similarity index 98% rename from packages/mosaic/src/primitives/chart/bars/__tests__/test-chart.tsx rename to packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx index 8369243067f..67214607e11 100644 --- a/packages/mosaic/src/primitives/chart/bars/__tests__/test-chart.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx @@ -1,6 +1,6 @@ import { type ReactNode, type RefObject, useLayoutEffect } from 'react'; -import { type ActiveBar, type BarChartInstance, Chart, type UseBarChartOptions } from '../..'; +import { type ActiveBar, type BarChartInstance, Chart, type UseBarChartOptions } from '..'; export type TestChartProps = Pick< UseBarChartOptions, @@ -13,6 +13,7 @@ export type TestChartProps = Pick< | 'selection' | 'onSelectionChange' | 'onActivate' + | 'messages' > & { ariaLabel: string; formatXTick?: (value: string) => string | null; diff --git a/packages/mosaic/src/primitives/chart/bars/bar-selection.ts b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts index 8c6b8fa4e51..b2622bd8697 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-selection.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts @@ -1,11 +1,19 @@ import type { SelectionModel } from '../internal/selection'; +import type { ChartMessages } from '../types'; import type { StackedBarLayout } from './bar-layout'; -import type { ActiveBar, BarCategory, BarSection, BarSelection } from './types'; +import type { ActiveBar, BarCategory, BarChartMessages, BarSection, BarSelection } from './types'; + +export const DEFAULT_BAR_MESSAGES = { + vertical: 'Use Up and Down to choose positive or negative values.', + positiveValues: 'positive values', + negativeValues: 'negative values', +} as const satisfies Omit; /** Selects a section of a stacked bar: above the zero line or below it. */ export function barSelectionModel( layout: Pick, 'plot' | 'zeroY'>, data: readonly TDatum[], + messages: Pick = DEFAULT_BAR_MESSAGES, ): SelectionModel, BarCategory> { return { hitTest: (category, y, current) => { @@ -51,8 +59,8 @@ export function barSelectionModel( projected: category.projected, }; }, - describe: selection => `${selection.section} values`, - verticalInstructions: 'Use Up and Down to choose positive or negative values.', + describe: selection => (selection.section === 'positive' ? messages.positiveValues : messages.negativeValues), + verticalInstructions: messages.vertical, anchorY: () => layout.plot.y, surfaceAttributes: selection => ({ 'data-active-section': selection?.section }), }; diff --git a/packages/mosaic/src/primitives/chart/bars/types.ts b/packages/mosaic/src/primitives/chart/bars/types.ts index 23745e5361f..7560b3b385a 100644 --- a/packages/mosaic/src/primitives/chart/bars/types.ts +++ b/packages/mosaic/src/primitives/chart/bars/types.ts @@ -1,4 +1,4 @@ -import type { ChartActive, ChartCategory, ChartSelection } from '../types'; +import type { ChartActive, ChartCategory, ChartMessages, ChartSelection } from '../types'; export type CornerRadii = readonly [number, number, number, number]; @@ -34,6 +34,17 @@ export type BarMark = BarIdentity & 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; + }>; + export type BarCategory = ChartCategory & Readonly<{ /** Sections a user can select, including a projection-only positive bar. */ diff --git a/packages/mosaic/src/primitives/chart/bars/use-bar-chart.ts b/packages/mosaic/src/primitives/chart/bars/use-bar-chart.ts index 5a34d12feba..05d74f71d25 100644 --- a/packages/mosaic/src/primitives/chart/bars/use-bar-chart.ts +++ b/packages/mosaic/src/primitives/chart/bars/use-bar-chart.ts @@ -6,8 +6,8 @@ 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 } from './bar-selection'; -import type { ActiveBar, BarIdentity, BarProjection, BarSelection, BarSeries } from './types'; +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[]; @@ -21,6 +21,8 @@ export interface UseBarChartOptions extends ChartOptions) => boolean; + /** Screen reader text, including how Up and Down move between sections. Default: English */ + messages?: Partial; } /** @@ -49,7 +51,15 @@ export function useBarChart(options: UseBarChartOptions): BarCha }), [categoryGap, margin, prepared, projectionIndex, projectionValue, size], ); - const model = React.useMemo(() => barSelectionModel(layout, data), [data, layout]); + const { + vertical = DEFAULT_BAR_MESSAGES.vertical, + positiveValues = DEFAULT_BAR_MESSAGES.positiveValues, + negativeValues = DEFAULT_BAR_MESSAGES.negativeValues, + } = options.messages ?? {}; + const model = React.useMemo( + () => barSelectionModel(layout, data, { vertical, positiveValues, negativeValues }), + [data, layout, vertical, positiveValues, negativeValues], + ); const instance = useChartInstance({ frame, layout, model, options }); return { ...instance, [BAR_LAYOUT]: { prepared, projection: layout.projection, isBarActive } }; diff --git a/packages/mosaic/src/primitives/chart/chart-selection.tsx b/packages/mosaic/src/primitives/chart/chart-selection.tsx index 2827e2cb9f4..c2d75b6eb9f 100644 --- a/packages/mosaic/src/primitives/chart/chart-selection.tsx +++ b/packages/mosaic/src/primitives/chart/chart-selection.tsx @@ -91,7 +91,6 @@ function SelectionSurface({ forwardedRef, chart, ariaLabel, children, render, .. <>
, 'describe' | 'land'>, formatCategory: (category: string) => string | null, + messages: ChartMessages, ) { if (selected?.source !== 'keyboard') { return ''; @@ -177,16 +185,11 @@ export function getKeyboardAnnouncement; /** 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) */ @@ -50,6 +62,8 @@ export interface ChartOptions void; /** Names a category in announcements. Default: the category key */ formatCategory?: (category: string) => string | null; + /** Screen reader text. Default: English */ + messages?: Partial; } export type XTick = Readonly<{ From ed1f79612e4feaf1965e15509b9517557c0b0404 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 25 Nov 2026 09:59:50 -0700 Subject: [PATCH 30/40] fix(mosaic): select only on bars, announce bar values, and split out the value axis A pointer over the empty plot above or below the bars selected the nearest period, so clicking or tapping off a bar left its tooltip open. The bar model now hit-tests the point itself and selects only on a section's bars, or within a 24px minimum target of the zero line for a short one. Keyboard announcements read the selected period's nonzero values, such as `Feb, Sign-ups 20`, and the projection. They name the section only when some value in the chart is negative, and the keyboard instructions leave Up and Down out otherwise. Series and projections take an optional `label`, and every chart type takes `formatValue`. The selection model now takes a chart point in `hitTest`, returns the tooltip `anchor` as a point, and describes the resolved selection. `ChartInstance` no longer carries `scaleY` and `yTicks`; `CartesianChartInstance` adds them, and `Chart.Grid`, `Chart.YAxis` and `Chart.YLine` throw for a chart without them, so a chart type with no value axis, such as a donut, fits `Chart.Root`. --- .../mosaic/src/primitives/chart/README.md | 26 ++-- .../chart/__tests__/chart.browser.test.tsx | 51 +++++++- .../primitives/chart/__tests__/chart.test.tsx | 102 +++++++++++++--- .../primitives/chart/__tests__/test-chart.tsx | 1 + .../src/primitives/chart/bars/bar-context.ts | 4 +- .../primitives/chart/bars/bar-selection.ts | 114 ++++++++++++++---- .../mosaic/src/primitives/chart/bars/types.ts | 6 + .../primitives/chart/bars/use-bar-chart.ts | 37 +++++- .../src/primitives/chart/chart-context.ts | 15 ++- .../src/primitives/chart/chart-grid.tsx | 4 +- .../src/primitives/chart/chart-y-axis.tsx | 4 +- .../src/primitives/chart/chart-y-line.tsx | 4 +- .../mosaic/src/primitives/chart/chart.doc.ts | 2 +- packages/mosaic/src/primitives/chart/index.ts | 2 + .../primitives/chart/internal/selection.ts | 30 +++-- .../chart/internal/use-chart-instance.ts | 28 ++--- .../chart/line-chart-contract.test-d.ts | 32 +++-- packages/mosaic/src/primitives/chart/types.ts | 23 +++- 18 files changed, 380 insertions(+), 105 deletions(-) diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index 30822cb885d..5b6cabfd4f9 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -140,31 +140,32 @@ Name the active type the chart's hook selects, such as ` 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` | `{ datumIndex: number; value: number }` | — | A projected total, drawn when it rises above its category's stack | +| `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 | | `onActivate` | `(active: ActiveBar) => void` | — | Called on click, Enter or Space. Makes the surface a button | | `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 | -`BarSelection` is `{ category, section }`. A new `isBarActive` function repaints the Canvas. `margin` and the last five options are the [options every chart type takes](#options-every-chart-type-takes). `BarChartMessages` adds `vertical`, `positiveValues` and `negativeValues` to `ChartMessages`. +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 `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. +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-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` | Maps a value to a Y coordinate | -| `yTicks` | `readonly ChartTick[]` | The Y ticks | +| `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 | @@ -174,7 +175,7 @@ A chart-type hook returns a `ChartInstance` plus what its own marks need: | `select`, `clear` | `(selection) => void`, `() => void` | Change the selection and call `onSelectionChange` | | `getInteractionProps()` | `ChartInteractionProps` | Role, `tabIndex`, `ref`, the chart type's `data-*` state and the event handlers | -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. +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 @@ -185,6 +186,7 @@ A category's `x` and `width` are the extent its marks occupy: a band for bars. I | `onSelectionChange` | `(selection: TSelection \| null) => void` | — | Called when the user, `select` or `clear` changes the selection | | `onActivate` | `(active: TActive) => void` | — | Called on click, Enter or Space. Makes the surface a button | | `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 @@ -201,7 +203,7 @@ The interaction surface is focusable while something reads the selection: `selec 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 the category whose center is nearest. A tap selects on contact and stays selected until the user taps elsewhere or the gesture is cancelled. +A pointer selects what the chart type hit-tests under it, and nothing over empty plot. A tap selects on contact and stays selected until the user taps elsewhere, including the empty plot, or the gesture is cancelled. ## Selection @@ -218,9 +220,11 @@ A selection set through `selection` or `select` is not announced. Announcements ### 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. A pointer selects the section above or below the zero line, and keeps the current section within a few pixels of it. +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. -The interaction surface carries `data-active-section`, `positive` or `negative` while a section is selected. The status region announces the period and its section, such as `Feb, positive values`, or `No values for this period`. +A pointer selects the period whose center is nearest when it is over a section's bars, or within 24px of the zero line for a shorter section, so a short bar is still a usable target. Over the empty plot above or below the bars it selects nothing. It keeps the current section within a few pixels of the zero line. + +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: @@ -377,4 +381,4 @@ A lost or missing 2D context throws `Chart.CanvasRenderError`, with the original ## 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, where the keyboard lands, how a selection resolves against the data, the announcement and the tooltip's Y. 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 fits the contract. +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__/chart.browser.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx index dd1bbde5694..6621e513654 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx @@ -437,9 +437,9 @@ describe('choosing a period with a pointer', () => { 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, y } = centerOfCategory(1); + const { x } = centerOfCategory(1); - pointer('pointerdown', surface(), x, y, 'touch'); + pointer('pointerdown', surface(), x, surface().getBoundingClientRect().bottom - 4, 'touch'); surface().dispatchEvent( new PointerEvent('pointerout', { bubbles: true, pointerType: 'touch', relatedTarget: document.body }), ); @@ -448,6 +448,53 @@ describe('choosing a period with a pointer', () => { pointer('pointerdown', document.body, 0, 0, 'touch'); await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toBeNull(); }); + + it('closes the tooltip when a mouse moves off a bar into the empty plot above it', async () => { + const onSelectionChange = vi.fn<(selection: BarSelection | null) => void>(); + await render( + active.category} + />, + ); + const plot = surface().getBoundingClientRect(); + const tallest = centerOfCategory(5); + await userEvent.hover(surface(), { position: { x: tallest.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]).toBeNull(); + await expect.poll(() => screen.queryByTestId('tooltip')).toBeNull(); + }); + + it('dismisses a touch selection on a tap in the empty plot above a bar', 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]).toBeNull(); + }); + + it('selects a short bar from a minimum target above its top', async () => { + const onSelectionChange = vi.fn<(selection: BarSelection | null) => void>(); + await render( + , + ); + const plot = surface().getBoundingClientRect(); + + pointer('pointerdown', surface(), plot.left + plot.width / 4, plot.bottom - 20, 'touch'); + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toMatchObject({ category: 'Jan' }); + }); }); function BoundedChart({ width, chartWidth }: { width: number; chartWidth: number }) { diff --git a/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx index b55dcc9d44e..7728ff4fc0d 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx @@ -71,6 +71,35 @@ describe('composing parts', () => { ).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) =>
], @@ -182,21 +211,42 @@ describe('choosing a period with the keyboard', () => { 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 selected period and section', + 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, positive values', + announcement: 'Feb, value 20', }, { - name: 'the formatted period name', + 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, positive values', + 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', @@ -210,17 +260,31 @@ describe('choosing a period with the keyboard', () => { announcement: 'No values for this period', }, ])('announces $name', ({ props, keys, announcement }) => { - const { interaction, getByRole } = renderChart(props); + 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')).toHaveTextContent(announcement); + 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, data: twoSided, messages: french }); + const { interaction, getByRole } = renderChart({ + ...growthChart, + series: gainedAndLost, + data: twoSided, + messages: french, + }); press(interaction, 'ArrowDown'); - expect(getByRole('status')).toHaveTextContent('Jan, valeurs négatives'); + expect(getByRole('status').textContent).toBe('Jan, valeurs négatives, Lost -4'); }); it('announces a period with no values in the language of `messages`', () => { @@ -235,9 +299,17 @@ describe('choosing a period with the keyboard', () => { 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({ - data: quarter, + ...growthChart, + data: twoSided, onActivate: () => {}, messages: { navigate: 'Gauche et Droite choisissent une période.', @@ -308,7 +380,7 @@ describe('activating a period', () => { }); fireEvent.focus(interaction); - expect(getByRole('status')).toHaveTextContent('Mar, positive values'); + expect(getByRole('status')).toHaveTextContent('Mar, Projected 20'); fireEvent.keyDown(interaction, { key: 'Enter' }); expect(active()).toMatchObject({ category: 'Mar', section: 'positive' }); expect(onActivate).toHaveBeenCalledExactlyOnceWith( @@ -361,7 +433,7 @@ describe('keeping the selection when data changes', () => { const refreshed = { period: 'Jan', value: 99 }; rerenderChart({ data: [data[1], refreshed] }); expect(active()).toMatchObject({ category: 'Jan', datumIndex: 1 }); - expect(getByRole('status')).toHaveTextContent('Jan, positive values'); + expect(getByRole('status')).toHaveTextContent('Jan, value 99'); fireEvent.keyDown(getByRole('button'), { key: 'Enter' }); expect(onActivate).toHaveBeenLastCalledWith(expect.objectContaining({ datum: refreshed, datumIndex: 1 })); }); @@ -416,12 +488,12 @@ describe('keeping the selection when data changes', () => { }); const control = getByRole('group'); press(control, 'ArrowDown'); - expect(getByRole('status')).toHaveTextContent('Jan, negative values'); + 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')).toHaveTextContent('Jan, positive values'); + expect(getByRole('status').textContent).toBe('Jan, gained 10'); }); }); @@ -431,13 +503,13 @@ describe('reading the selected period as data changes', () => { data: [{ period: 'Jan', value: 10 }], }); fireEvent.focus(interaction); - expect(getByRole('status')).toHaveTextContent('Jan, positive values'); + 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, positive values'); + expect(getByRole('status')).toHaveTextContent('Feb, value 25'); }); }); diff --git a/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx b/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx index 67214607e11..f133e2fcffe 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx @@ -14,6 +14,7 @@ export type TestChartProps = Pick< | 'onSelectionChange' | 'onActivate' | 'messages' + | 'formatValue' > & { ariaLabel: string; formatXTick?: (value: string) => string | null; diff --git a/packages/mosaic/src/primitives/chart/bars/bar-context.ts b/packages/mosaic/src/primitives/chart/bars/bar-context.ts index b339a934874..f2066c4eedd 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-context.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-context.ts @@ -1,7 +1,7 @@ import { createContext, useContext } from 'react'; import { ChartContext } from '../chart-context'; -import type { ChartInstance } from '../types'; +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'; @@ -17,7 +17,7 @@ export type BarLayout = Readonly<{ }>; /** The measured layout and selection of one stacked bar chart, returned by `Chart.useBarChart`. */ -export type BarChartInstance = ChartInstance, BarSelection, BarCategory> & +export type BarChartInstance = CartesianChartInstance, BarSelection, BarCategory> & Readonly<{ [BAR_LAYOUT]: BarLayout }>; function isBarChart(chart: ChartInstance): chart is BarChartInstance { diff --git a/packages/mosaic/src/primitives/chart/bars/bar-selection.ts b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts index b2622bd8697..453b9cf00d9 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-selection.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts @@ -1,37 +1,91 @@ -import type { SelectionModel } from '../internal/selection'; +import { nearestCategory, type SelectionModel } from '../internal/selection'; import type { ChartMessages } from '../types'; import type { StackedBarLayout } from './bar-layout'; -import type { ActiveBar, BarCategory, BarChartMessages, BarSection, BarSelection } from './types'; +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; -/** Selects a section of a stacked bar: above the zero line or below it. */ -export function barSelectionModel( - layout: Pick, 'plot' | 'zeroY'>, - data: readonly TDatum[], - messages: Pick = DEFAULT_BAR_MESSAGES, -): SelectionModel, BarCategory> { +/** WCAG 2.5.8's minimum target size, so a short bar can still be picked. */ +const MIN_TARGET = 24; + +type BarSelectionOptions = Readonly<{ + layout: Pick, 'plot' | 'zeroY' | 'categories' | 'prepared' | 'scaleY' | 'projection'>; + data: readonly TDatum[]; + series: readonly BarSeries[]; + projection: BarProjection | undefined; + formatValue: (value: number) => string; + messages: Pick; +}>; + +/** How far up each category's positive section and down its negative section a pointer selects. */ +function sectionReach(layout: BarSelectionOptions['layout']) { + const top = new Map(); + const bottom = new Map(); + for (const point of layout.prepared.points) { + if (point.positive) { + top.set(point.datumIndex, Math.min(top.get(point.datumIndex) ?? layout.zeroY, layout.scaleY(point.end))); + } else { + bottom.set(point.datumIndex, Math.max(bottom.get(point.datumIndex) ?? layout.zeroY, layout.scaleY(point.start))); + } + } + if (layout.projection) { + const { datumIndex, y } = layout.projection; + top.set(datumIndex, Math.min(top.get(datumIndex) ?? layout.zeroY, y)); + } return { - hitTest: (category, y, current) => { - const { positive, negative } = category.sections; - if (!positive && !negative) { + positive: (datumIndex: number) => Math.min(top.get(datumIndex) ?? layout.zeroY, layout.zeroY - MIN_TARGET), + negative: (datumIndex: number) => Math.max(bottom.get(datumIndex) ?? layout.zeroY, layout.zeroY + MIN_TARGET), + }; +} + +/** + * Selects a section of a stacked bar: above the zero line or below it. A pointer selects only on a + * bar, or within the minimum target of a short one, so the empty plot around the bars selects nothing. + */ +export function barSelectionModel({ + layout, + data, + series, + projection, + formatValue, + messages, +}: BarSelectionOptions): SelectionModel, BarCategory> { + const reach = sectionReach(layout); + 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 nearZero = Math.abs(y - layout.zeroY) <= Math.max(4, Math.round(layout.plot.height * 0.015)); - const section: BarSection = !negative - ? 'positive' - : !positive - ? 'negative' - : nearZero - ? (current?.section ?? 'positive') - : y < layout.zeroY - ? 'positive' - : 'negative'; - return { category: category.key, section }; + const { positive, negative } = category.sections; + const onPositive = positive && y >= reach.positive(category.datumIndex) && y <= layout.zeroY + nearZero; + const onNegative = negative && y <= reach.negative(category.datumIndex) && y >= layout.zeroY - nearZero; + const section: BarSection | null = + onPositive && onNegative + ? (current?.section ?? (y < layout.zeroY ? 'positive' : 'negative')) + : onPositive + ? 'positive' + : onNegative + ? 'negative' + : null; + return section ? { category: category.key, section } : null; }, land: (category, move, current) => { const wanted = move === 'up' ? 'positive' : move === 'down' ? 'negative' : current?.section; @@ -59,9 +113,19 @@ export function barSelectionModel( projected: category.projected, }; }, - describe: selection => (selection.section === 'positive' ? messages.positiveValues : messages.negativeValues), - verticalInstructions: messages.vertical, - anchorY: () => layout.plot.y, + 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/types.ts b/packages/mosaic/src/primitives/chart/bars/types.ts index 7560b3b385a..bbb737f5e34 100644 --- a/packages/mosaic/src/primitives/chart/bars/types.ts +++ b/packages/mosaic/src/primitives/chart/bars/types.ts @@ -6,10 +6,14 @@ export type CornerRadii = readonly [number, number, number, number]; 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; }>; @@ -43,6 +47,8 @@ export type BarChartMessages = ChartMessages & 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 & diff --git a/packages/mosaic/src/primitives/chart/bars/use-bar-chart.ts b/packages/mosaic/src/primitives/chart/bars/use-bar-chart.ts index 05d74f71d25..c2560a6920f 100644 --- a/packages/mosaic/src/primitives/chart/bars/use-bar-chart.ts +++ b/packages/mosaic/src/primitives/chart/bars/use-bar-chart.ts @@ -55,12 +55,43 @@ export function useBarChart(options: UseBarChartOptions): BarCha 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, { vertical, positiveValues, negativeValues }), - [data, layout, vertical, positiveValues, negativeValues], + () => + 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, [BAR_LAYOUT]: { prepared, projection: layout.projection, isBarActive } }; + 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 index bf13ad13ec7..74de6411915 100644 --- a/packages/mosaic/src/primitives/chart/chart-context.ts +++ b/packages/mosaic/src/primitives/chart/chart-context.ts @@ -1,6 +1,6 @@ import { createContext, type RefObject, useContext } from 'react'; -import type { ChartInstance, ChartSize } from './types'; +import type { CartesianChartInstance, ChartInstance, ChartSize } from './types'; export interface ChartContextValue { chart: ChartInstance; @@ -19,6 +19,19 @@ export function useChartContext(part: string) { 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; } diff --git a/packages/mosaic/src/primitives/chart/chart-grid.tsx b/packages/mosaic/src/primitives/chart/chart-grid.tsx index faa2f846550..66d5b226c6e 100644 --- a/packages/mosaic/src/primitives/chart/chart-grid.tsx +++ b/packages/mosaic/src/primitives/chart/chart-grid.tsx @@ -3,7 +3,7 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { hasArea, useChartContext } from './chart-context'; +import { hasArea, useCartesianChart } from './chart-context'; import type { ChartTick } from './types'; export type ChartGridProps = Omit, 'children'> & { @@ -13,7 +13,7 @@ export type ChartGridProps = Omit, 'children'> & { export const ChartGrid = React.forwardRef(function ChartGrid(props, ref) { const { children, render, ...otherProps } = props; - const { chart } = useChartContext('Grid'); + const chart = useCartesianChart('Grid'); const { size, yTicks } = chart; const ownProps = { diff --git a/packages/mosaic/src/primitives/chart/chart-y-axis.tsx b/packages/mosaic/src/primitives/chart/chart-y-axis.tsx index 3df9588e3e2..4e1c9d9b17e 100644 --- a/packages/mosaic/src/primitives/chart/chart-y-axis.tsx +++ b/packages/mosaic/src/primitives/chart/chart-y-axis.tsx @@ -3,7 +3,7 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { hasArea, useChartContext } from './chart-context'; +import { hasArea, useCartesianChart } from './chart-context'; export interface ChartYTickItem { value: number; @@ -22,7 +22,7 @@ const formatNumber = (value: number) => value.toLocaleString(); export const ChartYAxis = React.forwardRef(function ChartYAxis(props, ref) { const { format = formatNumber, children, render, ...otherProps } = props; - const { chart } = useChartContext('YAxis'); + 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) })), diff --git a/packages/mosaic/src/primitives/chart/chart-y-line.tsx b/packages/mosaic/src/primitives/chart/chart-y-line.tsx index aa77ca28af9..fa571c8c28f 100644 --- a/packages/mosaic/src/primitives/chart/chart-y-line.tsx +++ b/packages/mosaic/src/primitives/chart/chart-y-line.tsx @@ -3,7 +3,7 @@ import React from 'react'; import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../utils'; -import { useChartContext } from './chart-context'; +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. */ @@ -13,7 +13,7 @@ export type ChartYLineProps = ComponentProps<'line'> & { /** 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 } = useChartContext('YLine'); + const chart = useCartesianChart('YLine'); const y = chart.scaleY(value); const ownProps = { diff --git a/packages/mosaic/src/primitives/chart/chart.doc.ts b/packages/mosaic/src/primitives/chart/chart.doc.ts index 78178950dc6..d5043e6d582 100644 --- a/packages/mosaic/src/primitives/chart/chart.doc.ts +++ b/packages/mosaic/src/primitives/chart/chart.doc.ts @@ -257,7 +257,7 @@ const chart = Chart.useBarChart({ data, series, index, selection, onSelectionCha exports: { 'Chart.useBarChart': { description: - 'Lays out stacked bars and owns their selection: `Chart.useBarChart({ data, series, index })`, plus `categoryGap`, `margin`, `projection`, `isBarActive`, `selection`, `onSelectionChange`, `onActivate`, `formatCategory` and `messages`. Returns the chart object for `Chart.Root`.', + 'Lays out stacked bars and owns their selection: `Chart.useBarChart({ data, series, index })`, plus `categoryGap`, `margin`, `projection`, `isBarActive`, `selection`, `onSelectionChange`, `onActivate`, `formatCategory`, `formatValue` and `messages`. Give each series a `label` so announcements name it. Returns the chart object for `Chart.Root`.', }, 'Chart.CanvasRenderError': { description: diff --git a/packages/mosaic/src/primitives/chart/index.ts b/packages/mosaic/src/primitives/chart/index.ts index d8577d2ecfa..8bbd675973e 100644 --- a/packages/mosaic/src/primitives/chart/index.ts +++ b/packages/mosaic/src/primitives/chart/index.ts @@ -18,6 +18,7 @@ export type { UseBarChartOptions, } from './parts'; export type { + CartesianChartInstance, ChartActive, ChartCategory, ChartInstance, @@ -26,6 +27,7 @@ export type { ChartMessages, ChartOptions, ChartPlot, + ChartPoint, ChartSelection, ChartSize, ChartTick, diff --git a/packages/mosaic/src/primitives/chart/internal/selection.ts b/packages/mosaic/src/primitives/chart/internal/selection.ts index d9b0f40275f..572670a5b73 100644 --- a/packages/mosaic/src/primitives/chart/internal/selection.ts +++ b/packages/mosaic/src/primitives/chart/internal/selection.ts @@ -1,4 +1,4 @@ -import type { ChartActive, ChartCategory, ChartMessages, ChartSelection } from '../types'; +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.', @@ -18,8 +18,11 @@ export type SelectionModel< TActive extends ChartActive, TCategory extends ChartCategory = ChartCategory, > = Readonly<{ - /** The selection under a pointer at plot-space `y` over `category`. `current` lets a model hold its pick near a boundary. */ - hitTest: (category: TCategory, y: number, current: TSelection | null) => TSelection | null; + /** + * 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. @@ -27,12 +30,12 @@ export type SelectionModel< 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, such as `positive values`. */ - describe: (selection: TSelection) => string; + /** 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 points on the Y axis, in chart coordinates. */ - anchorY: (selection: TSelection, category: TCategory) => number; + /** 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>; }>; @@ -170,19 +173,24 @@ export function getKeyIntent(key: string, index: number, lastIndex: number, canA } } -export function getKeyboardAnnouncement( +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'>, + model: Pick, 'describe' | 'land'>, formatCategory: (category: string) => string | null, messages: ChartMessages, ) { if (selected?.source !== 'keyboard') { return ''; } - if (selected.selection) { + if (active) { const label = formatCategory(selected.category) ?? selected.category; - return `${label}, ${model.describe(selected.selection)}`; + return [label, model.describe(active)].filter(Boolean).join(', '); } const hasValues = !!category && model.land(category, undefined, null) !== null; return hasValues ? '' : messages.noValues; diff --git a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts index 289a8288b2b..4cbcc435c84 100644 --- a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts +++ b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts @@ -13,7 +13,6 @@ import type { ChartPlot, ChartSelection, ChartSize, - ChartTick, XTick, XTicksOptions, } from '../types'; @@ -22,7 +21,6 @@ import { getKeyboardAnnouncement, getKeyboardInstructions, getKeyIntent, - nearestCategory, NO_SELECTION, reconcileSelection, sameSelection, @@ -47,8 +45,6 @@ export const DEFAULT_CHART_MARGIN: ChartMargin = { /** What a chart type's layout gives the shared instance. */ export type ChartLayout = Readonly<{ plot: ChartPlot; - scaleY: (value: number) => number; - yTicks: readonly ChartTick[]; categories: readonly TCategory[]; }>; @@ -174,12 +170,17 @@ export function useChartInstance< // 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, currentCategory, model, formatCategory, 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 - ? { x: currentCategory.center, y: model.anchorY(valid.selection, currentCategory) } - : null; + valid?.selection && currentCategory && selected ? model.anchor(valid.selection, currentCategory) : null; const lastIndexRef = React.useRef(0); const selectedIndex = valid ? currentCategory?.datumIndex : undefined; @@ -250,10 +251,11 @@ export function useChartInstance< if (!bounds || bounds.width <= 0 || bounds.height <= 0) { return null; } - const x = ((clientX - bounds.left) / bounds.width) * size.width; - const y = ((clientY - bounds.top) / bounds.height) * size.height; - const category = categories[nearestCategory(categories, x)]; - return category ? model.hitTest(category, y, pointerUpdates.pending() ?? currentSelection) : 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) => { @@ -343,8 +345,6 @@ export function useChartInstance< rootRef, size, plot, - scaleY: layout.scaleY, - yTicks: layout.yTicks, categories, xTicks, selected, 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 index 97dc111e19b..b4e8296448e 100644 --- a/packages/mosaic/src/primitives/chart/line-chart-contract.test-d.ts +++ b/packages/mosaic/src/primitives/chart/line-chart-contract.test-d.ts @@ -1,38 +1,45 @@ import { describe, expectTypeOf, test } from 'vitest'; import type { BarChartInstance } from '.'; -import type { SelectionModel } from './internal/selection'; +import { nearestCategory, type SelectionModel } from './internal/selection'; import type { useChartInstance } from './internal/use-chart-instance'; import type { ChartRootProps, ChartTooltipProps } from './parts'; -import type { ChartActive, ChartCategory, ChartInstance, ChartSelection } from './types'; +import type { CartesianChartInstance, ChartActive, ChartCategory, ChartInstance, ChartSelection } from './types'; -// A line chart sketched in types only, to prove the shared contract fits a second chart type before -// `line-chart/` exists. Its categories are points, and it selects a category and nothing else. +// 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 = ChartInstance, ChartSelection> & +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: category => ({ category: category.key }), + 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: () => 'users', + describe: active => `Users ${active.datum.users}`, verticalInstructions: '', - anchorY: () => 0, + anchor: (_, category) => ({ x: category.center, y: 0 }), surfaceAttributes: () => ({}), } satisfies SelectionModel>; -describe('a line chart on the shared contract', () => { +describe('other chart types on the shared contract', () => { test('a point is a category with no width', () => { expectTypeOf(point).toExtend(); }); @@ -41,14 +48,17 @@ describe('a line chart on the shared contract', () => { expectTypeOf(lineModel).toExtend>>(); }); - test('the engine builds a line instance from it', () => { + 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 and a bar chart without a cast', () => { + test('Chart.Root takes a line chart, a donut and a bar chart without a cast', () => { expectTypeOf().toExtend(); + expectTypeOf().toExtend(); expectTypeOf>().toExtend(); }); diff --git a/packages/mosaic/src/primitives/chart/types.ts b/packages/mosaic/src/primitives/chart/types.ts index e7c91a3b55e..e646dda3e35 100644 --- a/packages/mosaic/src/primitives/chart/types.ts +++ b/packages/mosaic/src/primitives/chart/types.ts @@ -18,6 +18,9 @@ export type ChartPlot = Readonly<{ 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. @@ -62,6 +65,8 @@ export interface ChartOptions void; /** 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; } @@ -121,14 +126,12 @@ export type ChartInstance< /** The measured container, zero until the first measurement. */ size: ChartSize; plot: ChartPlot; - scaleY: (value: number) => number; - yTicks: readonly ChartTick[]; 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: Readonly<{ x: number; y: number }> | null; + 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. */ @@ -137,3 +140,17 @@ export type ChartInstance< clear: () => void; getInteractionProps: () => 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[]; + }>; From 9049acf183f00e5b192f64f160790ce27ce0c6f9 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 25 Nov 2026 10:56:14 -0700 Subject: [PATCH 31/40] feat(mosaic): compose the chart tooltip from the Tooltip parts, and round out the chart options `Chart.Tooltip` now renders no element. It positions against the selected category and provides the Tooltip primitive's context, so the chart renders its tooltip with `Chart.TooltipPortal`, `Chart.TooltipPositioner`, `Chart.TooltipPopup` and `Chart.TooltipArrow`, the same parts as Mosaic's Tooltip. Its fixed offsets become `side`, `sideOffset`, `collisionPadding`, `collisionBoundary` (was `boundaryRef`) and `pinned`. The chart options gain `defaultSelection` and `disabled`, `onActivate` receives the mouse or keyboard event that activated the period, and `getInteractionProps` takes the surface's own props and runs their handlers after the chart's. --- .../mosaic/src/primitives/chart/README.md | 136 ++++++++------ .../chart/__tests__/chart.browser.test.tsx | 17 ++ .../primitives/chart/__tests__/chart.test.tsx | 72 +++++++- .../chart/__tests__/chart.visual.test.tsx | 21 ++- .../primitives/chart/__tests__/test-chart.tsx | 18 +- .../src/primitives/chart/chart-selection.tsx | 4 +- .../src/primitives/chart/chart-tooltip.tsx | 174 +++++++++++------- .../mosaic/src/primitives/chart/chart.doc.ts | 55 +++++- packages/mosaic/src/primitives/chart/index.ts | 5 + .../chart/internal/use-chart-instance.ts | 44 +++-- packages/mosaic/src/primitives/chart/parts.ts | 16 ++ packages/mosaic/src/primitives/chart/types.ts | 45 +++-- 12 files changed, 429 insertions(+), 178 deletions(-) diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index 5b6cabfd4f9..3fcb12cd585 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -66,7 +66,17 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) - > className='tooltip'>{active => } + >> + {active => ( + + + + + + + + )} + ; ``` @@ -89,7 +99,11 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) | `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 | +| `Chart.Tooltip` | (none) | Positions a tooltip at the selected category | +| `Chart.TooltipPortal` | (none) | Portals the tooltip while it is mounted | +| `Chart.TooltipPositioner` | `
` | The positioned element. Carries `data-side` | +| `Chart.TooltipPopup` | `
` | The element that animates. Carries `data-open` and `data-closed` | +| `Chart.TooltipArrow` | `` | An arrow pointing at the selected category | 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. @@ -124,30 +138,38 @@ The namespace also holds `Chart.useBarChart` and `Chart.CanvasRenderError`. ### `Chart.Tooltip` -| Prop | Type | Default | Description | -| ------------- | -------------------------------- | --------- | ------------------------------------------------------------------ | -| `children` | `(active: TActive) => ReactNode` | — | Content for the selected category. Return null to hide the tooltip | -| `boundaryRef` | `RefObject` | the chart | Element the tooltip stays inside | +| Prop | Type | Default | Description | +| ------------------- | -------------------------------- | --------- | --------------------------------------------------------------------------- | +| `children` | `(active: TActive) => ReactNode` | — | Renders the tooltip parts. While it closes, receives the last selection | +| `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` renders no element. It provides the context of the [Tooltip primitive](../tooltip/README.md), so `Chart.TooltipPortal`, `Chart.TooltipPositioner`, `Chart.TooltipPopup` and `Chart.TooltipArrow` are the Tooltip parts, anchored to the chart instead of a trigger. Style the popup, not the positioner, which keeps `pointer-events: none` so the tooltip never takes the pointer from the chart. 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 | -| `onActivate` | `(active: ActiveBar) => void` | — | Called on click, Enter or Space. Makes the surface a button | -| `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 | +| 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`. @@ -159,35 +181,37 @@ The hook returns a `BarChartInstance`: the [chart object](#the-chart-obj 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()` | `ChartInteractionProps` | Role, `tabIndex`, `ref`, the chart type's `data-*` state and the event handlers | +| 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 | -| `onActivate` | `(active: TActive) => void` | — | Called on click, Enter or Space. Makes the surface a button | -| `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` | +| 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 @@ -207,7 +231,7 @@ A pointer selects what the chart type hit-tests under it, and nothing over empty ## Selection -The chart holds the selection unless you pass `selection`. `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. +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. @@ -240,7 +264,7 @@ const chart = Chart.useBarChart({ data, series, index, selection, onSelectionCha ## Rendering from the chart object -The parts are optional. Attach `rootRef` to the measured element, spread `getInteractionProps()` on the element that takes selection, 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. +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 }); @@ -265,20 +289,20 @@ Painting the bars is the one thing the chart object does not do, because their c ## 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 | +| 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.TooltipPositioner` | `left` or `right` of the selected period, or `bottom` when pinned to the top of a narrow chart | +| `data-open` / `data-closed` | `Chart.TooltipPopup` | 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`. +- 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. @@ -373,7 +397,7 @@ A lost or missing 2D context throws `Chart.CanvasRenderError`, with the original ## 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 to the right, flips left when the right side does not fit inside `boundaryRef`, and keeps the side it chose last until that side stops fitting, so it does not cross the selection twice near an edge. 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. +`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. `Chart.TooltipPortal` portals through Mosaic's `Portal`, so a `PortalProvider` decides where. `Chart.TooltipPopup` animates through `data-open`, `data-closed`, `data-starting-style` and `data-ending-style`, and `Chart.Tooltip` passes its children the last selection while the popup closes. ## Dependencies and bundle size diff --git a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx index 6621e513654..7b0c3f4d5d8 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx @@ -532,6 +532,23 @@ function contains(outer: DOMRect, inner: DOMRect) { } describe('the tooltip', () => { + 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( { if (click) { fireEvent.click(interaction, { detail: 0 }); } - expect(onActivate).toHaveBeenLastCalledWith(expect.objectContaining({ datumIndex: 1 })); + expect(onActivate).toHaveBeenLastCalledWith( + expect.objectContaining({ datumIndex: 1 }), + expect.objectContaining({ type: click ? 'click' : 'keydown' }), + ); }); it('reselects a dismissed period on Enter before opening it', () => { @@ -366,7 +369,7 @@ describe('activating a period', () => { expect(active()).toMatchObject({ category: 'Mar' }); fireEvent.keyDown(interaction, { key: 'Enter' }); - expect(onActivate).toHaveBeenLastCalledWith(expect.objectContaining({ category: 'Mar' })); + expect(onActivate).toHaveBeenLastCalledWith(expect.objectContaining({ category: 'Mar' }), expect.anything()); }); it('selects and activates a projection-only period with the keyboard', () => { @@ -385,6 +388,7 @@ describe('activating a period', () => { expect(active()).toMatchObject({ category: 'Mar', section: 'positive' }); expect(onActivate).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ datum, datumIndex: 0, section: 'positive' }), + expect.anything(), ); }); @@ -435,7 +439,10 @@ describe('keeping the selection when data changes', () => { 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(onActivate).toHaveBeenLastCalledWith( + expect.objectContaining({ datum: refreshed, datumIndex: 1 }), + expect.anything(), + ); }); it('keeps a consumer that stores the selection in sync as its data changes', () => { @@ -476,7 +483,10 @@ describe('keeping the selection when data changes', () => { 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(onActivate).toHaveBeenLastCalledWith( + expect.objectContaining({ datumIndex: 0, datum: quarter[0] }), + expect.anything(), + ); } }, ); @@ -571,7 +581,7 @@ describe('controlling the selection', () => { expect(selectedTick()).toBe('Mar'); fireEvent.keyDown(interaction, { key: 'Enter' }); - expect(onActivate).toHaveBeenLastCalledWith(expect.objectContaining({ category: 'Mar' })); + expect(onActivate).toHaveBeenLastCalledWith(expect.objectContaining({ category: 'Mar' }), expect.anything()); }); }); @@ -601,4 +611,56 @@ describe('rendering from the chart object', () => { 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 index 69768647930..45ee4618538 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.visual.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.visual.test.tsx @@ -121,16 +121,17 @@ function GrowthChart({ - > - className='tooltip' - boundaryRef={boundary} - > + > collisionBoundary={boundary}> {({ datum }) => ( - <> -
{datum.week}
-
Sign-ups: {datum.signups}
-
Churned: {datum.churned}
- + + + +
{datum.week}
+
Sign-ups: {datum.signups}
+
Churned: {datum.churned}
+
+
+
)}
@@ -167,7 +168,7 @@ describe('Chart stacked bars visual state', () => { screen.getByRole('group', { name: 'Weekly growth' }).focus(); await userEvent.keyboard('{ArrowRight}'); await expect - .poll(() => screen.queryByText('Sign-ups: 52')?.closest('.tooltip')?.style.visibility) + .poll(() => screen.queryByText('Sign-ups: 52')?.closest('[data-side]')?.style.visibility) .toBe(''); await expect(chart).toMatchScreenshot('stacked-bars-tooltip-open'); }); diff --git a/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx b/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx index f133e2fcffe..9e7df150caa 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx @@ -1,6 +1,6 @@ import { type ReactNode, type RefObject, useLayoutEffect } from 'react'; -import { type ActiveBar, type BarChartInstance, Chart, type UseBarChartOptions } from '..'; +import { type ActiveBar, type BarChartInstance, Chart, type ChartTooltipProps, type UseBarChartOptions } from '..'; export type TestChartProps = Pick< UseBarChartOptions, @@ -15,12 +15,15 @@ export type TestChartProps = Pick< | '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 */ @@ -37,6 +40,7 @@ export function TestChart({ formatXTick, selectionPart = true, renderTooltip, + tooltip, boundary, height, bar = true, @@ -77,10 +81,16 @@ export function TestChart({ {renderTooltip ? ( > - boundaryRef={boundary} - data-testid='tooltip' + collisionBoundary={boundary} + {...tooltip} > - {renderTooltip} + {active => ( + + + {renderTooltip(active)} + + + )} ) : null} diff --git a/packages/mosaic/src/primitives/chart/chart-selection.tsx b/packages/mosaic/src/primitives/chart/chart-selection.tsx index c2d75b6eb9f..255adf80d6c 100644 --- a/packages/mosaic/src/primitives/chart/chart-selection.tsx +++ b/packages/mosaic/src/primitives/chart/chart-selection.tsx @@ -81,7 +81,7 @@ function SelectionSurface({ forwardedRef, chart, ariaLabel, children, render, .. ); const interaction = chart.getInteractionProps(); - const focusable = interaction.tabIndex === 0 || tooltipCount > 0; + const focusable = !interaction['aria-disabled'] && (interaction.tabIndex === 0 || tooltipCount > 0); const surfaceProps = { ...interaction, tabIndex: focusable ? 0 : undefined }; const { plot } = chart; @@ -100,7 +100,7 @@ function SelectionSurface({ forwardedRef, chart, ariaLabel, children, render, .. pointerEvents: 'auto', }} aria-describedby={keyboardInstructionsId} - aria-label={focusable ? ariaLabel : undefined} + aria-label={focusable || surfaceProps['aria-disabled'] ? ariaLabel : undefined} > {children}
diff --git a/packages/mosaic/src/primitives/chart/chart-tooltip.tsx b/packages/mosaic/src/primitives/chart/chart-tooltip.tsx index 8cf60c28f7f..280bc83e6a9 100644 --- a/packages/mosaic/src/primitives/chart/chart-tooltip.tsx +++ b/packages/mosaic/src/primitives/chart/chart-tooltip.tsx @@ -1,77 +1,124 @@ 'use client'; -import { autoUpdate, flip, offset, shift, size, useFloating } from '@floating-ui/react'; +import { arrow, autoUpdate, flip, offset, shift, size, useFloating, useInteractions } 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 { TooltipContext, type TooltipContextValue } from '../tooltip/tooltip-context'; +import { cssVars } from '../utils/css-vars'; import { getWindow } from '../utils/dom'; import { parsePlacement } from '../utils/side-offset'; import { useChartContext, useSelectionContext } from './chart-context'; import type { ChartActive } from './types'; -const EDGE = 8; -const SIDE_OFFSET = 16; const PINNED_BELOW_PLOT_WIDTH = 416; -export type ChartTooltipProps = Omit, 'children'> & { - /** Content for the selected category, such as an `ActiveBar` from a bar chart. Return null to hide the tooltip. */ +type Side = 'left' | 'right'; + +export interface ChartTooltipProps { + /** + * Renders the tooltip for the selected category, usually `Chart.TooltipPortal`, + * `Chart.TooltipPositioner` and `Chart.TooltipPopup`. While the tooltip closes it receives the + * last selection, so the content does not change under the exit. + */ 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 */ - boundaryRef?: React.RefObject; -}; + 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 Side = 'left' | 'right'; +type BoundaryRef = React.RefObject; -function tooltipMiddleware(getBoundary: () => Element | undefined, pinned: boolean) { +/** 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, + arrowRef: React.RefObject, +) { return [ - offset(pinned ? 0 : SIDE_OFFSET), - flip(() => ({ boundary: getBoundary(), padding: EDGE, crossAxis: false })), - shift(() => ({ boundary: getBoundary(), padding: EDGE, crossAxis: true })), + offset(pinned ? 0 : sideOffset), + flip(() => ({ boundary: getBoundary(), padding, crossAxis: false })), + shift(() => ({ boundary: getBoundary(), padding, crossAxis: true })), size(() => ({ boundary: getBoundary(), - padding: EDGE, + padding, apply({ elements }) { const boundary = getBoundary()?.getBoundingClientRect(); const viewportWidth = getWindow(elements.floating).document.documentElement.clientWidth; - const left = Math.max(EDGE, (boundary?.left ?? 0) + EDGE); - const right = Math.min(viewportWidth - EDGE, (boundary?.right ?? viewportWidth) - EDGE); + 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`; }, })), + arrow({ element: arrowRef }), + cssVars({ sideOffset }), ]; } -// 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, boundaryRef, render, ...otherProps } = props; +/** + * Positions a tooltip beside the selected category. It renders no element: it provides the + * Tooltip primitive's context, so `Chart.TooltipPortal`, `Chart.TooltipPositioner`, + * `Chart.TooltipPopup` and `Chart.TooltipArrow` are the Tooltip parts, anchored to the chart. + */ +export function ChartTooltip(props: ChartTooltipProps) { + const { + children, + side = 'right', + sideOffset = 16, + collisionPadding = 8, + collisionBoundary, + pinned: pinnedProp = 'auto', + } = 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 { plot } = chart; + const chartWidth = chart.size.width; const anchor = chart.tooltipAnchor; - const content = active && anchor ? children(active) : null; - const open = content !== null && content !== undefined; + // eslint-disable-next-line typescript/consistent-type-assertions -- The context holds the chart without its active type; the caller names the type its chart-type hook selects. + const active = chart.selected as TActive | null; + const open = active !== null && anchor !== null; const anchorX = anchor?.x; const anchorY = anchor?.y; - const pinned = plot.width < PINNED_BELOW_PLOT_WIDTH; + const [held, setHeld] = React.useState(active); + if (open && !Object.is(held, active)) { + setHeld(active); + } + + const pinned = pinnedProp === 'auto' ? plot.width < PINNED_BELOW_PLOT_WIDTH : pinnedProp; const popupRef = React.useRef(null); - const getBoundary = React.useCallback( - () => boundaryRef?.current ?? chartBoxRef.current ?? undefined, - [boundaryRef, chartBoxRef], + const arrowRef = React.useRef(null); + const middleware = React.useMemo( + () => + // eslint-disable-next-line react/refs -- The middleware reads the boundary and arrow refs when floating-ui computes a position, not during render. + tooltipMiddleware(boundaryReader(collisionBoundary, chartBoxRef), pinned, sideOffset, collisionPadding, arrowRef), + [chartBoxRef, collisionBoundary, collisionPadding, pinned, sideOffset], ); - // eslint-disable-next-line react/refs -- The middleware reads the boundary refs when floating-ui computes a position, not during render. - const middleware = React.useMemo(() => tooltipMiddleware(getBoundary, pinned), [getBoundary, pinned]); - const [lastSide, setLastSide] = React.useState('right'); + const [lastSide, setLastSide] = React.useState(side); const { refs, floatingStyles, - placement: resolvedPlacement, + context: floatingContext, + placement, isPositioned, } = useFloating({ open, @@ -81,52 +128,53 @@ export const ChartTooltip = React.forwardRef( middleware, whileElementsMounted: autoUpdate, }); - const resolvedSide = parsePlacement(resolvedPlacement).side; + const resolvedSide = parsePlacement(placement).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 chart = chartBoxRef.current; - if (anchorX === undefined || anchorY === undefined || !chart || chartWidth <= 0) { + const box = chartBoxRef.current; + if (anchorX === undefined || anchorY === undefined || !box || chartWidth <= 0) { return; } const getBoundingClientRect = () => { - const chartRect = chart.getBoundingClientRect(); + const chartRect = box.getBoundingClientRect(); if (pinned) { - const boundary = getBoundary()?.getBoundingClientRect() ?? chartRect; - return new DOMRect(boundary.left + EDGE, boundary.top + EDGE, 0, 0); + 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: chart }); - }, [anchorX, anchorY, chartBoxRef, chartWidth, getBoundary, pinned, refs]); + refs.setReference({ getBoundingClientRect, contextElement: box }); + }, [anchorX, anchorY, chartBoxRef, chartWidth, collisionBoundary, collisionPadding, pinned, refs]); const { mounted, transitionProps } = useTransition({ open, ref: popupRef }); + const { getReferenceProps, getFloatingProps } = useInteractions([]); - 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), - }); + const style = React.useMemo( + () => ({ ...floatingStyles, pointerEvents: 'none', ...(isPositioned ? null : { visibility: 'hidden' }) }), + [floatingStyles, isPositioned], + ); + const context = React.useMemo( + () => ({ + open, + floatingContext, + refs, + floatingStyles: style, + placement, + getReferenceProps, + getFloatingProps, + popupRef, + arrowRef, + mounted, + transitionProps, + }), + [floatingContext, getFloatingProps, getReferenceProps, mounted, open, placement, refs, style, transitionProps], + ); - return mounted ? {element} : null; -}) as ( - props: ChartTooltipProps & { ref?: React.Ref }, -) => React.ReactElement | null; + const shown = open ? active : held; + return {mounted && shown ? children(shown) : null}; +} diff --git a/packages/mosaic/src/primitives/chart/chart.doc.ts b/packages/mosaic/src/primitives/chart/chart.doc.ts index d5043e6d582..5ba35c835f8 100644 --- a/packages/mosaic/src/primitives/chart/chart.doc.ts +++ b/packages/mosaic/src/primitives/chart/chart.doc.ts @@ -7,6 +7,10 @@ import type { ChartProjectionOutlineProps, ChartRootProps, ChartSelectionProps, + ChartTooltipArrowProps, + ChartTooltipPopupProps, + ChartTooltipPortalProps, + ChartTooltipPositionerProps, ChartTooltipProps, ChartXAxisProps, ChartXTickProps, @@ -185,19 +189,46 @@ export default { }, 'Chart.Tooltip': { description: - 'A `div` portaled through `Portal` for the selected category. Opens to the right, flips left when it does not fit, and pins to the top of a plot narrower than 416px. Carries `data-side`, `data-open`, `data-closed`, `data-starting-style` and `data-ending-style`. Throws outside `Chart.Selection`.', + 'Positions a tooltip beside the selected category and renders no element. It provides the Tooltip primitive context, so `Chart.TooltipPortal`, `Chart.TooltipPositioner`, `Chart.TooltipPopup` and `Chart.TooltipArrow` render it. Opens on `side`, flips to the other side when it does not fit, and keeps the side it chose last. Throws outside `Chart.Selection`.', props: { children: { type: '(active: TActive) => React.ReactNode', - doc: 'Content for the selected category. Return null to hide the tooltip.', + doc: 'Renders the tooltip parts for the selected category. While the tooltip closes it receives the last selection.', }, - boundaryRef: { + 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'", + }, }, }, + 'Chart.TooltipPortal': { + description: + 'The Tooltip primitive `Portal`: renders its children through Mosaic `Portal` while the tooltip is mounted.', + }, + 'Chart.TooltipPositioner': { + description: + 'The Tooltip primitive `Positioner`: a fixed `div` at the computed position, with `pointer-events: none` so it never takes the pointer from the chart. Carries `data-side`.', + }, + 'Chart.TooltipPopup': { + description: + 'The Tooltip primitive `Popup`: the element that animates, with `data-open`, `data-closed`, `data-starting-style` and `data-ending-style`.', + }, + 'Chart.TooltipArrow': { + description: 'The Tooltip primitive `Arrow`, pointing at the selected category.', + }, }, examples: [ { @@ -221,7 +252,17 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) - > className='tooltip'>{active => } + >> + {active => ( + + + + + + + + )} + `, @@ -257,7 +298,7 @@ const chart = Chart.useBarChart({ data, series, index, selection, onSelectionCha exports: { 'Chart.useBarChart': { description: - 'Lays out stacked bars and owns their selection: `Chart.useBarChart({ data, series, index })`, plus `categoryGap`, `margin`, `projection`, `isBarActive`, `selection`, `onSelectionChange`, `onActivate`, `formatCategory`, `formatValue` and `messages`. Give each series a `label` so announcements name it. Returns the chart object for `Chart.Root`.', + '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: @@ -278,4 +319,8 @@ const chart = Chart.useBarChart({ data, series, index, selection, onSelectionCha 'Chart.Selection': ChartSelectionProps; 'Chart.Cursor': ChartCursorProps; 'Chart.Tooltip': ChartTooltipProps; + 'Chart.TooltipPortal': ChartTooltipPortalProps; + 'Chart.TooltipPositioner': ChartTooltipPositionerProps; + 'Chart.TooltipPopup': ChartTooltipPopupProps; + 'Chart.TooltipArrow': ChartTooltipArrowProps; }>; diff --git a/packages/mosaic/src/primitives/chart/index.ts b/packages/mosaic/src/primitives/chart/index.ts index 8bbd675973e..c6d7df612f7 100644 --- a/packages/mosaic/src/primitives/chart/index.ts +++ b/packages/mosaic/src/primitives/chart/index.ts @@ -8,6 +8,10 @@ export type { ChartProjectionOutlineProps, ChartRootProps, ChartSelectionProps, + ChartTooltipArrowProps, + ChartTooltipPopupProps, + ChartTooltipPortalProps, + ChartTooltipPositionerProps, ChartTooltipProps, ChartXAxisProps, ChartXTickProps, @@ -22,6 +26,7 @@ export type { ChartActive, ChartCategory, ChartInstance, + ChartInteractionInput, ChartInteractionProps, ChartMargin, ChartMessages, diff --git a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts index 4cbcc435c84..bc6f50ee58d 100644 --- a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts +++ b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts @@ -3,10 +3,12 @@ import React from 'react'; import { useControllableState } from '../../hooks/use-controllable-state'; +import { mergeProps } from '../../utils'; import type { ChartActive, ChartCategory, ChartInstance, + ChartInteractionInput, ChartInteractionProps, ChartMargin, ChartOptions, @@ -148,7 +150,11 @@ export function useChartInstance< [categories, plot, size.width], ); - const [value, setValue] = useControllableState(options.selection, null, options.onSelectionChange); + 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); @@ -267,27 +273,25 @@ export function useChartInstance< }); }; - const activate = (selection: TSelection | null) => { + type ActivationEvent = React.MouseEvent | React.KeyboardEvent; + const activate = (selection: TSelection | null, event: ActivationEvent) => { const active = resolve(selection); if (active) { - onActivate?.(active); + onActivate?.(active, event); } }; - const activateKeyboardSelection = () => { + const activateKeyboardSelection = (event: ActivationEvent) => { const dismissed = stateRef.current.status === 'dismissed'; const next = selectKeyboardIndex(keyboardIndex(), undefined, currentSelection); if (!dismissed) { - activate(toPublicSelection(next)); + activate(toPublicSelection(next), event); } }; + const { disabled = false } = options; const reads = options.selection !== undefined || !!options.onSelectionChange || !!onActivate; - const getInteractionProps = (): ChartInteractionProps => ({ - ...model.surfaceAttributes(currentSelection), - role: onActivate ? 'button' : 'group', - tabIndex: reads ? 0 : undefined, - ref: attachSurface, + const handlers = (): React.HTMLAttributes => ({ onPointerDown: event => { event.preventDefault(); // A tap fires no pointermove, so touch selects on contact and survives the pointerleave that @@ -320,10 +324,10 @@ export function useChartInstance< 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(); + activateKeyboardSelection(event); return; } - activate(pointerSelection(event.clientX, event.clientY)); + activate(pointerSelection(event.clientX, event.clientY), event); }, onKeyDown: event => { const intent = getKeyIntent(event.key, keyboardIndex(), categories.length - 1, !!onActivate); @@ -334,12 +338,26 @@ export function useChartInstance< if (intent.type === 'dismiss') { dispatch({ type: 'dismiss' }); } else if (intent.activate) { - activateKeyboardSelection(); + 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, diff --git a/packages/mosaic/src/primitives/chart/parts.ts b/packages/mosaic/src/primitives/chart/parts.ts index 8047f6dc07e..28f4344e3ad 100644 --- a/packages/mosaic/src/primitives/chart/parts.ts +++ b/packages/mosaic/src/primitives/chart/parts.ts @@ -8,6 +8,22 @@ 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 { + type TooltipPortalProps as ChartTooltipPortalProps, + TooltipPortal as TooltipPortal, +} from '../tooltip/tooltip-portal'; +export { + type TooltipPositionerProps as ChartTooltipPositionerProps, + TooltipPositioner as TooltipPositioner, +} from '../tooltip/tooltip-positioner'; +export { + type TooltipPopupProps as ChartTooltipPopupProps, + TooltipPopup as TooltipPopup, +} from '../tooltip/tooltip-popup'; +export { + type TooltipArrowProps as ChartTooltipArrowProps, + TooltipArrow as TooltipArrow, +} from '../tooltip/tooltip-arrow'; 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'; diff --git a/packages/mosaic/src/primitives/chart/types.ts b/packages/mosaic/src/primitives/chart/types.ts index e646dda3e35..48447aa59d0 100644 --- a/packages/mosaic/src/primitives/chart/types.ts +++ b/packages/mosaic/src/primitives/chart/types.ts @@ -59,10 +59,17 @@ export interface ChartOptions; /** 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. Makes the interaction surface a button. */ - onActivate?: (active: TActive) => 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)` */ @@ -93,23 +100,21 @@ export type XTicksOptions = Readonly<{ }>; /** Props for the element that takes pointer and keyboard selection, usually the plot. */ -export type ChartInteractionProps = Readonly<{ - role: 'button' | 'group'; - /** 0 while something reads the selection: `selection`, `onSelectionChange` or `onActivate`. */ - tabIndex: 0 | undefined; - /** Removing the surface ends a pointer or keyboard selection, as leaving or blurring it does. */ - ref: React.RefCallback; - onPointerDown: React.PointerEventHandler; - onPointerLeave: React.PointerEventHandler; - onPointerCancel: React.PointerEventHandler; - onPointerMove: React.PointerEventHandler; - onFocus: React.FocusEventHandler; - onBlur: React.FocusEventHandler; - onClick: React.MouseEventHandler; - onKeyDown: React.KeyboardEventHandler; - /** State the chart type exposes on the surface, such as `data-active-section`. */ - [attribute: `data-${string}`]: string | undefined; -}>; +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 @@ -138,7 +143,7 @@ export type ChartInstance< keyboardInstructions: string; select: (selection: TSelection) => void; clear: () => void; - getInteractionProps: () => ChartInteractionProps; + getInteractionProps: (props?: ChartInteractionInput) => ChartInteractionProps; }>; /** From 8ef4ea83f2576c8611e59e1ef02822e2696ab40a Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 25 Nov 2026 11:23:36 -0700 Subject: [PATCH 32/40] fix(mosaic): center category labels under their bars unless they would overflow The first and last category labels were always pinned to the plot's edges, so with a few wide bars they sat away from their bars. Category labels now use the calendar labels' rule: centered under the category, and moved to the edge only where centered they would leave the plot. --- .../mosaic/src/primitives/chart/README.md | 2 +- .../chart/internal/__tests__/x-ticks.test.ts | 29 +++++++++++++++++++ .../src/primitives/chart/internal/x-ticks.ts | 9 +----- 3 files changed, 31 insertions(+), 9 deletions(-) diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index 3fcb12cd585..e7a45ae6c3f 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -132,7 +132,7 @@ The namespace also holds `Chart.useBarChart` and `Chart.CanvasRenderError`. | `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 | -`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. +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. 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 index 369d986c552..a69d6969a45 100644 --- a/packages/mosaic/src/primitives/chart/internal/__tests__/x-ticks.test.ts +++ b/packages/mosaic/src/primitives/chart/internal/__tests__/x-ticks.test.ts @@ -41,6 +41,35 @@ function expectReadable(ticks: readonly XTick[], area: Plot, measure: (label: st } 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'] }, diff --git a/packages/mosaic/src/primitives/chart/internal/x-ticks.ts b/packages/mosaic/src/primitives/chart/internal/x-ticks.ts index dcf5520a16e..53cd469d15d 100644 --- a/packages/mosaic/src/primitives/chart/internal/x-ticks.ts +++ b/packages/mosaic/src/primitives/chart/internal/x-ticks.ts @@ -64,7 +64,6 @@ function selectCategoryTicks({ formatXTick, measure, }: SelectXTicksOptions & { measure: (label: string) => number }): XTick[] { - const hasDistinctEdges = categories.length > 1; const candidates = evenlySpacedIndexes(categories.length, plot.width).flatMap(datumIndex => { const category = categories[datumIndex]; if (!category) { @@ -74,14 +73,8 @@ function selectCategoryTicks({ if (label === null) { return []; } - const isFirst = hasDistinctEdges && datumIndex === 0; - const isLast = hasDistinctEdges && datumIndex === categories.length - 1; - const placement: Pick = isFirst - ? { x: plot.x + EDGE_INSET, textAnchor: 'start' } - : isLast - ? { x: plot.x + plot.width - EDGE_INSET, textAnchor: 'end' } - : { x: category.center, textAnchor: 'middle' }; 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 }]; From f32c68368d05dcb2af30e3817b44a86d30544bb6 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 25 Nov 2026 12:01:52 -0700 Subject: [PATCH 33/40] feat(mosaic): mark the chart cursor when the keyboard selected its category The chart is one tab stop with arrow keys inside, so the focus ring belongs on the selected category rather than around the whole chart. `selectionSource` on the chart says what made the selection, and `Chart.Cursor` carries `data-focus-visible` while it was the keyboard. --- .../mosaic/src/primitives/chart/README.md | 32 ++++++++++--------- .../primitives/chart/__tests__/chart.test.tsx | 16 ++++++++++ .../src/primitives/chart/chart-cursor.tsx | 4 +++ .../mosaic/src/primitives/chart/chart.doc.ts | 2 +- .../chart/internal/use-chart-instance.ts | 1 + packages/mosaic/src/primitives/chart/types.ts | 5 +++ 6 files changed, 44 insertions(+), 16 deletions(-) diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index e7a45ae6c3f..b4528ce904d 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -181,21 +181,22 @@ The hook returns a `BarChartInstance`: the [chart object](#the-chart-obj 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` | +| 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 | +| `selectionSource` | `'pointer' \| 'keyboard' \| 'external' \| null` | What made `selected`. `keyboard` is when a focus ring belongs on the selected category | +| `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. @@ -294,6 +295,7 @@ Painting the bars is the one thing the chart object does not do, because their c | `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-focus-visible` | `Chart.Cursor` | Present while the keyboard selected the category. Ring the cursor then, not the whole chart | | `data-side` | `Chart.TooltipPositioner` | `left` or `right` of the selected period, or `bottom` when pinned to the top of a narrow chart | | `data-open` / `data-closed` | `Chart.TooltipPopup` | The tooltip's open state, with `data-starting-style` and `data-ending-style` during transitions | diff --git a/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx index d4546e79cc8..a2621abbec8 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx @@ -171,6 +171,22 @@ describe('choosing a period', () => { }); describe('choosing a period with the keyboard', () => { + it.each([ + { name: 'a keyboard selection', setup: { data: quarter }, keyboard: true, focusVisible: true }, + { + name: 'a selection the consumer set', + setup: { data: quarter, selection: { category: 'Feb', section: 'positive' as const } }, + keyboard: false, + focusVisible: false, + }, + ])('marks the cursor data-focus-visible only for $name', ({ setup, keyboard, focusVisible }) => { + const { interaction, getByTestId } = renderChart(setup); + if (keyboard) { + press(interaction, 'ArrowRight'); + } + expect(getByTestId('cursor').hasAttribute('data-focus-visible')).toBe(focusVisible); + }); + it('is a focusable group, not a button or an image', () => { const { getByRole } = renderChart({ data: quarter }); const group = getByRole('group', { name: 'Growth' }); diff --git a/packages/mosaic/src/primitives/chart/chart-cursor.tsx b/packages/mosaic/src/primitives/chart/chart-cursor.tsx index 41e66431350..7c4667c7432 100644 --- a/packages/mosaic/src/primitives/chart/chart-cursor.tsx +++ b/packages/mosaic/src/primitives/chart/chart-cursor.tsx @@ -33,6 +33,10 @@ export const ChartCursor = React.forwardRef(fu render, ref, enabled: !!selectedCategory, + state: { focusVisible: chart.selectionSource === 'keyboard' }, + stateAttributesMapping: { + focusVisible: (focusVisible: boolean) => (focusVisible ? { 'data-focus-visible': '' } : null), + }, props: mergeProps<'div'>(ownProps, otherProps), }); }); diff --git a/packages/mosaic/src/primitives/chart/chart.doc.ts b/packages/mosaic/src/primitives/chart/chart.doc.ts index 5ba35c835f8..45eb26704d1 100644 --- a/packages/mosaic/src/primitives/chart/chart.doc.ts +++ b/packages/mosaic/src/primitives/chart/chart.doc.ts @@ -185,7 +185,7 @@ export default { }, 'Chart.Cursor': { description: - 'An `aria-hidden` `div` that covers the selected category, with its width. Throws outside `Chart.Selection`.', + 'An `aria-hidden` `div` that covers the selected category, with its width. Carries `data-focus-visible` while the keyboard selected the category, so the focus ring can sit on it. Throws outside `Chart.Selection`.', }, 'Chart.Tooltip': { description: diff --git a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts index bc6f50ee58d..90c7843e409 100644 --- a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts +++ b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts @@ -366,6 +366,7 @@ export function useChartInstance< categories, xTicks, selected, + selectionSource: selected ? (valid?.source ?? null) : null, tooltipAnchor, announcement, keyboardInstructions, diff --git a/packages/mosaic/src/primitives/chart/types.ts b/packages/mosaic/src/primitives/chart/types.ts index 48447aa59d0..b206b573f1c 100644 --- a/packages/mosaic/src/primitives/chart/types.ts +++ b/packages/mosaic/src/primitives/chart/types.ts @@ -135,6 +135,11 @@ export type ChartInstance< xTicks: (options?: XTicksOptions) => XTick[]; /** The selection in the current data, or null. */ selected: TActive | null; + /** + * What made `selected`: a pointer, the keyboard, or `selection`/`select`. Null with no selection. + * `keyboard` is when a focus ring belongs on the selected category. + */ + selectionSource: 'pointer' | 'keyboard' | 'external' | null; /** Where a tooltip for `selected` points, in chart coordinates. */ tooltipAnchor: ChartPoint | null; /** The text of the keyboard selection's status announcement. */ From 3aa491acf55274b70589890fe95e931ace1f9a60 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 25 Nov 2026 15:01:57 -0700 Subject: [PATCH 34/40] refactor(mosaic): render the chart tooltip as one element again The chart tooltip used none of Mosaic's Tooltip behavior: no trigger, no hover or focus wiring, no description link. Composing it from the Tooltip parts meant faking their context and nesting three parts to show content. `Chart.Tooltip` is one positioned `div` again that renders its children's content, takes `div` props and `ref`, and hides when the content is null. It keeps `side`, `sideOffset`, `collisionPadding`, `collisionBoundary` and `pinned`. `Chart.TooltipPortal`, `TooltipPositioner`, `TooltipPopup` and `TooltipArrow` are removed. --- .../mosaic/src/primitives/chart/README.md | 40 +++---- .../chart/__tests__/chart.browser.test.tsx | 9 ++ .../chart/__tests__/chart.visual.test.tsx | 21 ++-- .../primitives/chart/__tests__/test-chart.tsx | 9 +- .../src/primitives/chart/chart-tooltip.tsx | 100 +++++++----------- .../mosaic/src/primitives/chart/chart.doc.ts | 39 +------ packages/mosaic/src/primitives/chart/index.ts | 4 - packages/mosaic/src/primitives/chart/parts.ts | 16 --- 8 files changed, 78 insertions(+), 160 deletions(-) diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index b4528ce904d..0008d7e3aa8 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -66,17 +66,7 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) - >> - {active => ( - - - - - - - - )} - + > className='tooltip'>{active => } ; ``` @@ -99,11 +89,7 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) | `Chart.XTick` | `` | One category label | | `Chart.Selection` | `
` | Pointer and keyboard selection over the whole chart | | `Chart.Cursor` | `
` | Covers the selected category | -| `Chart.Tooltip` | (none) | Positions a tooltip at the selected category | -| `Chart.TooltipPortal` | (none) | Portals the tooltip while it is mounted | -| `Chart.TooltipPositioner` | `
` | The positioned element. Carries `data-side` | -| `Chart.TooltipPopup` | `
` | The element that animates. Carries `data-open` and `data-closed` | -| `Chart.TooltipArrow` | `` | An arrow pointing at 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. @@ -140,14 +126,14 @@ Each X label centers under its category, and moves to the plot's edge only where | Prop | Type | Default | Description | | ------------------- | -------------------------------- | --------- | --------------------------------------------------------------------------- | -| `children` | `(active: TActive) => ReactNode` | — | Renders the tooltip parts. While it closes, receives the last selection | +| `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` renders no element. It provides the context of the [Tooltip primitive](../tooltip/README.md), so `Chart.TooltipPortal`, `Chart.TooltipPositioner`, `Chart.TooltipPopup` and `Chart.TooltipArrow` are the Tooltip parts, anchored to the chart instead of a trigger. Style the popup, not the positioner, which keeps `pointer-events: none` so the tooltip never takes the pointer from the chart. +`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`. @@ -290,14 +276,14 @@ Painting the bars is the one thing the chart object does not do, because their c ## 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-focus-visible` | `Chart.Cursor` | Present while the keyboard selected the category. Ring the cursor then, not the whole chart | -| `data-side` | `Chart.TooltipPositioner` | `left` or `right` of the selected period, or `bottom` when pinned to the top of a narrow chart | -| `data-open` / `data-closed` | `Chart.TooltipPopup` | The tooltip's open state, with `data-starting-style` and `data-ending-style` during transitions | +| 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-focus-visible` | `Chart.Cursor` | Present while the keyboard selected the category. Ring the cursor then, not the whole chart | +| `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). @@ -399,7 +385,7 @@ A lost or missing 2D context throws `Chart.CanvasRenderError`, with the original ## 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. `Chart.TooltipPortal` portals through Mosaic's `Portal`, so a `PortalProvider` decides where. `Chart.TooltipPopup` animates through `data-open`, `data-closed`, `data-starting-style` and `data-ending-style`, and `Chart.Tooltip` passes its children the last selection while the popup closes. +`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 diff --git a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx index 7b0c3f4d5d8..d357fa10d05 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx @@ -532,6 +532,15 @@ function contains(outer: DOMRect, inner: DOMRect) { } 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( - > collisionBoundary={boundary}> + > + className='tooltip' + collisionBoundary={boundary} + > {({ datum }) => ( - - - -
{datum.week}
-
Sign-ups: {datum.signups}
-
Churned: {datum.churned}
-
-
-
+ <> +
{datum.week}
+
Sign-ups: {datum.signups}
+
Churned: {datum.churned}
+ )}
@@ -168,7 +167,7 @@ describe('Chart stacked bars visual state', () => { screen.getByRole('group', { name: 'Weekly growth' }).focus(); await userEvent.keyboard('{ArrowRight}'); await expect - .poll(() => screen.queryByText('Sign-ups: 52')?.closest('[data-side]')?.style.visibility) + .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__/test-chart.tsx b/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx index 9e7df150caa..cb1c60c5cf4 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx @@ -82,15 +82,10 @@ export function TestChart({ {renderTooltip ? ( > collisionBoundary={boundary} + data-testid='tooltip' {...tooltip} > - {active => ( - - - {renderTooltip(active)} - - - )} + {renderTooltip} ) : null} diff --git a/packages/mosaic/src/primitives/chart/chart-tooltip.tsx b/packages/mosaic/src/primitives/chart/chart-tooltip.tsx index 280bc83e6a9..338dc80e56c 100644 --- a/packages/mosaic/src/primitives/chart/chart-tooltip.tsx +++ b/packages/mosaic/src/primitives/chart/chart-tooltip.tsx @@ -1,11 +1,11 @@ 'use client'; -import { arrow, autoUpdate, flip, offset, shift, size, useFloating, useInteractions } from '@floating-ui/react'; +import { autoUpdate, flip, offset, shift, size, useFloating } from '@floating-ui/react'; import React from 'react'; import { useTransition } from '../hooks/use-transition'; -import { TooltipContext, type TooltipContextValue } from '../tooltip/tooltip-context'; -import { cssVars } from '../utils/css-vars'; +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'; @@ -15,12 +15,8 @@ const PINNED_BELOW_PLOT_WIDTH = 416; type Side = 'left' | 'right'; -export interface ChartTooltipProps { - /** - * Renders the tooltip for the selected category, usually `Chart.TooltipPortal`, - * `Chart.TooltipPositioner` and `Chart.TooltipPopup`. While the tooltip closes it receives the - * last selection, so the content does not change under the exit. - */ +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; @@ -35,7 +31,7 @@ export interface ChartTooltipProps { * `'auto'` pins it while the plot is narrower than 416px. Default: 'auto' */ pinned?: boolean | 'auto'; -} +}; type BoundaryRef = React.RefObject; @@ -49,7 +45,6 @@ function tooltipMiddleware( pinned: boolean, sideOffset: number, padding: number, - arrowRef: React.RefObject, ) { return [ offset(pinned ? 0 : sideOffset), @@ -66,17 +61,11 @@ function tooltipMiddleware( elements.floating.style.maxWidth = `${Math.max(0, right - left)}px`; }, })), - arrow({ element: arrowRef }), - cssVars({ sideOffset }), ]; } -/** - * Positions a tooltip beside the selected category. It renders no element: it provides the - * Tooltip primitive's context, so `Chart.TooltipPortal`, `Chart.TooltipPositioner`, - * `Chart.TooltipPopup` and `Chart.TooltipArrow` are the Tooltip parts, anchored to the chart. - */ -export function ChartTooltip(props: ChartTooltipProps) { +// 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', @@ -84,32 +73,27 @@ export function ChartTooltip(props: C 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 { plot } = chart; - const chartWidth = chart.size.width; const anchor = chart.tooltipAnchor; - // eslint-disable-next-line typescript/consistent-type-assertions -- The context holds the chart without its active type; the caller names the type its chart-type hook selects. - const active = chart.selected as TActive | null; - const open = active !== null && anchor !== null; + const content = active && anchor ? children(active) : null; + const open = content !== null && content !== undefined; const anchorX = anchor?.x; const anchorY = anchor?.y; - const [held, setHeld] = React.useState(active); - if (open && !Object.is(held, active)) { - setHeld(active); - } - const pinned = pinnedProp === 'auto' ? plot.width < PINNED_BELOW_PLOT_WIDTH : pinnedProp; const popupRef = React.useRef(null); - const arrowRef = React.useRef(null); const middleware = React.useMemo( () => - // eslint-disable-next-line react/refs -- The middleware reads the boundary and arrow refs when floating-ui computes a position, not during render. - tooltipMiddleware(boundaryReader(collisionBoundary, chartBoxRef), pinned, sideOffset, collisionPadding, arrowRef), + // 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], ); @@ -117,8 +101,7 @@ export function ChartTooltip(props: C const { refs, floatingStyles, - context: floatingContext, - placement, + placement: resolvedPlacement, isPositioned, } = useFloating({ open, @@ -128,7 +111,7 @@ export function ChartTooltip(props: C middleware, whileElementsMounted: autoUpdate, }); - const resolvedSide = parsePlacement(placement).side; + 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); @@ -152,29 +135,28 @@ export function ChartTooltip(props: C }, [anchorX, anchorY, chartBoxRef, chartWidth, collisionBoundary, collisionPadding, pinned, refs]); const { mounted, transitionProps } = useTransition({ open, ref: popupRef }); - const { getReferenceProps, getFloatingProps } = useInteractions([]); - const style = React.useMemo( - () => ({ ...floatingStyles, pointerEvents: 'none', ...(isPositioned ? null : { visibility: 'hidden' }) }), - [floatingStyles, isPositioned], - ); - const context = React.useMemo( - () => ({ - open, - floatingContext, - refs, - floatingStyles: style, - placement, - getReferenceProps, - getFloatingProps, - popupRef, - arrowRef, - mounted, - transitionProps, - }), - [floatingContext, getFloatingProps, getReferenceProps, mounted, open, placement, refs, style, transitionProps], - ); + 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), + }); - const shown = open ? active : held; - return {mounted && shown ? children(shown) : null}; -} + return mounted ? {element} : null; +}) as ( + props: ChartTooltipProps & { ref?: React.Ref }, +) => React.ReactElement | null; diff --git a/packages/mosaic/src/primitives/chart/chart.doc.ts b/packages/mosaic/src/primitives/chart/chart.doc.ts index 45eb26704d1..1e1c0d567db 100644 --- a/packages/mosaic/src/primitives/chart/chart.doc.ts +++ b/packages/mosaic/src/primitives/chart/chart.doc.ts @@ -7,10 +7,6 @@ import type { ChartProjectionOutlineProps, ChartRootProps, ChartSelectionProps, - ChartTooltipArrowProps, - ChartTooltipPopupProps, - ChartTooltipPortalProps, - ChartTooltipPositionerProps, ChartTooltipProps, ChartXAxisProps, ChartXTickProps, @@ -189,11 +185,11 @@ export default { }, 'Chart.Tooltip': { description: - 'Positions a tooltip beside the selected category and renders no element. It provides the Tooltip primitive context, so `Chart.TooltipPortal`, `Chart.TooltipPositioner`, `Chart.TooltipPopup` and `Chart.TooltipArrow` render it. Opens on `side`, flips to the other side when it does not fit, and keeps the side it chose last. Throws outside `Chart.Selection`.', + '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: 'Renders the tooltip parts for the selected category. While the tooltip closes it receives the last selection.', + 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' }, @@ -214,21 +210,6 @@ export default { }, }, }, - 'Chart.TooltipPortal': { - description: - 'The Tooltip primitive `Portal`: renders its children through Mosaic `Portal` while the tooltip is mounted.', - }, - 'Chart.TooltipPositioner': { - description: - 'The Tooltip primitive `Positioner`: a fixed `div` at the computed position, with `pointer-events: none` so it never takes the pointer from the chart. Carries `data-side`.', - }, - 'Chart.TooltipPopup': { - description: - 'The Tooltip primitive `Popup`: the element that animates, with `data-open`, `data-closed`, `data-starting-style` and `data-ending-style`.', - }, - 'Chart.TooltipArrow': { - description: 'The Tooltip primitive `Arrow`, pointing at the selected category.', - }, }, examples: [ { @@ -252,17 +233,7 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) - >> - {active => ( - - - - - - - - )} - + > className='tooltip'>{active => } `, @@ -319,8 +290,4 @@ const chart = Chart.useBarChart({ data, series, index, selection, onSelectionCha 'Chart.Selection': ChartSelectionProps; 'Chart.Cursor': ChartCursorProps; 'Chart.Tooltip': ChartTooltipProps; - 'Chart.TooltipPortal': ChartTooltipPortalProps; - 'Chart.TooltipPositioner': ChartTooltipPositionerProps; - 'Chart.TooltipPopup': ChartTooltipPopupProps; - 'Chart.TooltipArrow': ChartTooltipArrowProps; }>; diff --git a/packages/mosaic/src/primitives/chart/index.ts b/packages/mosaic/src/primitives/chart/index.ts index c6d7df612f7..9a739115120 100644 --- a/packages/mosaic/src/primitives/chart/index.ts +++ b/packages/mosaic/src/primitives/chart/index.ts @@ -8,10 +8,6 @@ export type { ChartProjectionOutlineProps, ChartRootProps, ChartSelectionProps, - ChartTooltipArrowProps, - ChartTooltipPopupProps, - ChartTooltipPortalProps, - ChartTooltipPositionerProps, ChartTooltipProps, ChartXAxisProps, ChartXTickProps, diff --git a/packages/mosaic/src/primitives/chart/parts.ts b/packages/mosaic/src/primitives/chart/parts.ts index 28f4344e3ad..8047f6dc07e 100644 --- a/packages/mosaic/src/primitives/chart/parts.ts +++ b/packages/mosaic/src/primitives/chart/parts.ts @@ -8,22 +8,6 @@ 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 { - type TooltipPortalProps as ChartTooltipPortalProps, - TooltipPortal as TooltipPortal, -} from '../tooltip/tooltip-portal'; -export { - type TooltipPositionerProps as ChartTooltipPositionerProps, - TooltipPositioner as TooltipPositioner, -} from '../tooltip/tooltip-positioner'; -export { - type TooltipPopupProps as ChartTooltipPopupProps, - TooltipPopup as TooltipPopup, -} from '../tooltip/tooltip-popup'; -export { - type TooltipArrowProps as ChartTooltipArrowProps, - TooltipArrow as TooltipArrow, -} from '../tooltip/tooltip-arrow'; 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'; From d906b2ba6047510186ad05d3cd2260f1c98790e8 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 25 Nov 2026 16:26:49 -0700 Subject: [PATCH 35/40] feat(mosaic): outline the keyboard-selected bar section, not the whole column A ring around the full column said which period the keyboard was on but not which side of a stacked bar. The selection model now gives a `focusRect`, the selected section from the zero line to its far edge, at least 24px tall like the hit test and at least 12px wide so a ring stays findable on dense data. `Chart.Cursor` covers it while the keyboard made the selection; a mouse hover keeps the full-height column. --- .../mosaic/src/primitives/chart/README.md | 39 ++++++------ .../chart/__tests__/chart.browser.test.tsx | 59 +++++++++++++++++++ .../primitives/chart/bars/bar-selection.ts | 9 +++ .../src/primitives/chart/chart-cursor.tsx | 24 ++++++-- .../mosaic/src/primitives/chart/chart.doc.ts | 2 +- packages/mosaic/src/primitives/chart/index.ts | 1 + .../primitives/chart/internal/selection.ts | 4 +- .../chart/internal/use-chart-instance.ts | 3 + .../chart/line-chart-contract.test-d.ts | 1 + packages/mosaic/src/primitives/chart/types.ts | 5 ++ 10 files changed, 120 insertions(+), 27 deletions(-) diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index 0008d7e3aa8..865a4ed1aab 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -88,7 +88,7 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) | `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.Cursor` | `
` | Covers the selected category, or its section for the keyboard | | `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. @@ -167,22 +167,23 @@ The hook returns a `BarChartInstance`: the [chart object](#the-chart-obj 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 | -| `selectionSource` | `'pointer' \| 'keyboard' \| 'external' \| null` | What made `selected`. `keyboard` is when a focus ring belongs on the selected category | -| `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` | +| 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 | +| `selectionSource` | `'pointer' \| 'keyboard' \| 'external' \| null` | What made `selected`. `keyboard` is when a focus ring belongs on the selected category | +| `tooltipAnchor` | `{ x, y } \| null` | Where a tooltip for `selected` points | +| `focusRect` | `{ x, y, width, height } \| null` | The box a focus ring for `selected` outlines: for bars, the selected section, at least 12px wide and 24px tall | +| `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. @@ -281,7 +282,7 @@ Painting the bars is the one thing the chart object does not do, because their c | `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-focus-visible` | `Chart.Cursor` | Present while the keyboard selected the category. Ring the cursor then, not the whole chart | +| `data-focus-visible` | `Chart.Cursor` | Present while the keyboard selected the category. The cursor then covers `focusRect`; ring it, not the whole chart | | `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 | @@ -393,4 +394,4 @@ A lost or missing 2D context throws `Chart.CanvasRenderError`, with the original ## 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. +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, the tooltip's anchor and the focus ring's box. 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__/chart.browser.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx index d357fa10d05..1a5994b8688 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx @@ -414,6 +414,65 @@ describe('resizing', () => { }); }); +describe('the keyboard focus on a section', () => { + type Signed = { period: string; gained: number; lost: number }; + const signedSeries = [ + { key: 'gained', value: (row: Signed) => row.gained }, + { key: 'lost', value: (row: Signed) => row.lost }, + ]; + const signedIndex = (row: Signed) => row.period; + const cursor = () => screen.getByTestId('cursor').getBoundingClientRect(); + + it('covers the selected section from the zero line to its far edge', async () => { + await render( +
+ {}} + /> +
, + ); + const plot = surface().getBoundingClientRect(); + + surface().focus(); + await expect.poll(() => screen.queryByTestId('cursor')?.hasAttribute('data-focus-visible')).toBe(true); + const positive = cursor(); + await userEvent.keyboard('{ArrowDown}'); + await expect.poll(() => cursor().top).toBeGreaterThan(positive.top); + const negative = cursor(); + + expect(positive.top).toBeCloseTo(plot.top, -1); + expect(negative.top).toBeCloseTo(positive.bottom, 0); + expect(negative.bottom).toBeCloseTo(plot.bottom, -1); + expect(positive.height).toBeLessThan(plot.height); + }); + + it('keeps a minimum width on dense data', async () => { + const dense = Array.from({ length: 400 }, (_, i) => ({ period: `P${i}`, value: 10 + (i % 7) })); + await render(); + surface().focus(); + await expect.poll(() => screen.queryByTestId('cursor')?.hasAttribute('data-focus-visible')).toBe(true); + expect(cursor().width).toBeGreaterThanOrEqual(12); + }); + + it('keeps the full-height band for a mouse hover', async () => { + await render(); + const plot = surface().getBoundingClientRect(); + await userEvent.hover(surface(), { position: { x: centerOfCategory(0).x - plot.left, y: plot.height - 4 } }); + await expect.poll(() => screen.queryByTestId('cursor')).toBeTruthy(); + expect(cursor().height).toBeCloseTo(plot.height, 0); + await userEvent.unhover(surface()); + }); +}); + 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>(); diff --git a/packages/mosaic/src/primitives/chart/bars/bar-selection.ts b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts index 453b9cf00d9..04bac19f8e8 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-selection.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts @@ -21,6 +21,9 @@ export const DEFAULT_BAR_MESSAGES = { /** WCAG 2.5.8's minimum target size, so a short bar can still be picked. */ const MIN_TARGET = 24; +/** The narrowest a focus ring gets, so it stays findable when bars are a pixel or two wide. */ +const MIN_FOCUS_WIDTH = 12; + type BarSelectionOptions = Readonly<{ layout: Pick, 'plot' | 'zeroY' | 'categories' | 'prepared' | 'scaleY' | 'projection'>; data: readonly TDatum[]; @@ -126,6 +129,12 @@ export function barSelectionModel({ }, verticalInstructions: twoSided ? messages.vertical : '', anchor: (_, category) => ({ x: category.center, y: layout.plot.y }), + focusRect: (selection, category) => { + const width = Math.max(category.width, MIN_FOCUS_WIDTH); + const top = selection.section === 'positive' ? reach.positive(category.datumIndex) : layout.zeroY; + const bottom = selection.section === 'positive' ? layout.zeroY : reach.negative(category.datumIndex); + return { x: category.center - width / 2, y: top, width, height: bottom - top }; + }, surfaceAttributes: selection => ({ 'data-active-section': selection?.section }), }; } diff --git a/packages/mosaic/src/primitives/chart/chart-cursor.tsx b/packages/mosaic/src/primitives/chart/chart-cursor.tsx index 7c4667c7432..f0fbf6484f0 100644 --- a/packages/mosaic/src/primitives/chart/chart-cursor.tsx +++ b/packages/mosaic/src/primitives/chart/chart-cursor.tsx @@ -14,18 +14,30 @@ export const ChartCursor = React.forwardRef(fu const { plot, selected } = chart; const selectedCategory = selected ? chart.categories[selected.datumIndex] : undefined; + // A keyboard selection outlines just its section, such as one side of a stacked bar; a pointer + // shows the whole column. + const focusRect = chart.selectionSource === 'keyboard' ? chart.focusRect : null; const ownProps = { 'aria-hidden': 'true', - style: selectedCategory + style: focusRect ? { position: 'absolute', - top: 0, - bottom: 0, - left: selectedCategory.x - plot.x, - width: selectedCategory.width, + top: focusRect.y - plot.y, + left: focusRect.x - plot.x, + width: focusRect.width, + height: focusRect.height, pointerEvents: 'none', } - : undefined, + : selectedCategory + ? { + position: 'absolute', + top: 0, + bottom: 0, + left: selectedCategory.x - plot.x, + width: selectedCategory.width, + pointerEvents: 'none', + } + : undefined, } satisfies DefaultProps<'div'>; return useRender({ diff --git a/packages/mosaic/src/primitives/chart/chart.doc.ts b/packages/mosaic/src/primitives/chart/chart.doc.ts index 1e1c0d567db..ec73c8df900 100644 --- a/packages/mosaic/src/primitives/chart/chart.doc.ts +++ b/packages/mosaic/src/primitives/chart/chart.doc.ts @@ -181,7 +181,7 @@ export default { }, 'Chart.Cursor': { description: - 'An `aria-hidden` `div` that covers the selected category, with its width. Carries `data-focus-visible` while the keyboard selected the category, so the focus ring can sit on it. Throws outside `Chart.Selection`.', + 'An `aria-hidden` `div` that covers the selected category, with its width. While the keyboard selected the category it carries `data-focus-visible` and covers just the selected section (`focusRect`, at least 12px wide and 24px tall), so the focus ring can sit on it. Throws outside `Chart.Selection`.', }, 'Chart.Tooltip': { description: diff --git a/packages/mosaic/src/primitives/chart/index.ts b/packages/mosaic/src/primitives/chart/index.ts index 9a739115120..46540c3990b 100644 --- a/packages/mosaic/src/primitives/chart/index.ts +++ b/packages/mosaic/src/primitives/chart/index.ts @@ -29,6 +29,7 @@ export type { ChartOptions, ChartPlot, ChartPoint, + ChartRect, ChartSelection, ChartSize, ChartTick, diff --git a/packages/mosaic/src/primitives/chart/internal/selection.ts b/packages/mosaic/src/primitives/chart/internal/selection.ts index 572670a5b73..6e6a9811ea0 100644 --- a/packages/mosaic/src/primitives/chart/internal/selection.ts +++ b/packages/mosaic/src/primitives/chart/internal/selection.ts @@ -1,4 +1,4 @@ -import type { ChartActive, ChartCategory, ChartMessages, ChartPoint, ChartSelection } from '../types'; +import type { ChartActive, ChartCategory, ChartMessages, ChartPoint, ChartRect, 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.', @@ -36,6 +36,8 @@ export type SelectionModel< verticalInstructions: string; /** Where a tooltip for the selection points. */ anchor: (selection: TSelection, category: TCategory) => ChartPoint; + /** The box a focus ring for the selection outlines, large enough to find on dense data. */ + focusRect: (selection: TSelection, category: TCategory) => ChartRect; /** State the interaction surface carries for styling, such as `data-active-section`. */ surfaceAttributes: (selection: TSelection | null) => Readonly>; }>; diff --git a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts index 90c7843e409..57292780398 100644 --- a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts +++ b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts @@ -187,6 +187,8 @@ export function useChartInstance< const keyboardInstructions = getKeyboardInstructions(messages, model.verticalInstructions, !!onActivate); const tooltipAnchor = valid?.selection && currentCategory && selected ? model.anchor(valid.selection, currentCategory) : null; + const focusRect = + valid?.selection && currentCategory && selected ? model.focusRect(valid.selection, currentCategory) : null; const lastIndexRef = React.useRef(0); const selectedIndex = valid ? currentCategory?.datumIndex : undefined; @@ -368,6 +370,7 @@ export function useChartInstance< selected, selectionSource: selected ? (valid?.source ?? null) : null, tooltipAnchor, + focusRect, announcement, keyboardInstructions, select, 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 index b4e8296448e..921aa4d8454 100644 --- a/packages/mosaic/src/primitives/chart/line-chart-contract.test-d.ts +++ b/packages/mosaic/src/primitives/chart/line-chart-contract.test-d.ts @@ -36,6 +36,7 @@ const lineModel = { describe: active => `Users ${active.datum.users}`, verticalInstructions: '', anchor: (_, category) => ({ x: category.center, y: 0 }), + focusRect: (_, category) => ({ x: category.center - 6, y: 0, width: 12, height: 12 }), surfaceAttributes: () => ({}), } satisfies SelectionModel>; diff --git a/packages/mosaic/src/primitives/chart/types.ts b/packages/mosaic/src/primitives/chart/types.ts index b206b573f1c..ae276666377 100644 --- a/packages/mosaic/src/primitives/chart/types.ts +++ b/packages/mosaic/src/primitives/chart/types.ts @@ -21,6 +21,9 @@ 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 }>; +/** A box in chart coordinates. */ +export type ChartRect = Readonly<{ x: number; y: number; width: number; height: 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. @@ -142,6 +145,8 @@ export type ChartInstance< selectionSource: 'pointer' | 'keyboard' | 'external' | null; /** Where a tooltip for `selected` points, in chart coordinates. */ tooltipAnchor: ChartPoint | null; + /** The box a focus ring for `selected` outlines, such as a bar section. Null with no selection. */ + focusRect: ChartRect | null; /** The text of the keyboard selection's status announcement. */ announcement: string; /** The keys the chart answers to, for the visually hidden description. */ From 3977274a5f2ea1f826a779620afbffb20d510933 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 25 Nov 2026 16:45:43 -0700 Subject: [PATCH 36/40] fix(mosaic): select the whole column under the pointer again The hover band covers the full column, but only the bar and a 24px minimum answered the pointer, so the empty band above a short bar showed a target that did not respond. A pointer selects the nearest column anywhere in the plot again, and the section on its side of the zero line, as Dashboard's chart does. Leaving the plot, tapping outside the chart and Escape still close the tooltip. The keyboard focus ring keeps outlining just the section. --- .../mosaic/src/primitives/chart/README.md | 4 +- .../chart/__tests__/chart.browser.test.tsx | 48 ++++++++++++------- .../primitives/chart/bars/bar-selection.ts | 39 ++++++++------- 3 files changed, 54 insertions(+), 37 deletions(-) diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index 865a4ed1aab..37efe93bda3 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -215,7 +215,7 @@ The interaction surface is focusable while something reads the selection: `selec 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, and nothing over empty plot. A tap selects on contact and stays selected until the user taps elsewhere, including the empty plot, or the gesture is cancelled. +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 @@ -234,7 +234,7 @@ A selection set through `selection` or `select` is not announced. Announcements 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 when it is over a section's bars, or within 24px of the zero line for a shorter section, so a short bar is still a usable target. Over the empty plot above or below the bars it selects nothing. It keeps the current section within a few pixels of the zero line. +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`. diff --git a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx index 1a5994b8688..476099bc270 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx @@ -508,7 +508,7 @@ describe('choosing a period with a pointer', () => { await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toBeNull(); }); - it('closes the tooltip when a mouse moves off a bar into the empty plot above it', async () => { + 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( { />, ); const plot = surface().getBoundingClientRect(); - const tallest = centerOfCategory(5); - await userEvent.hover(surface(), { position: { x: tallest.x - plot.left, y: plot.height - 4 } }); + 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]).toBeNull(); - await expect.poll(() => screen.queryByTestId('tooltip')).toBeNull(); + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toMatchObject({ category: 'Jan' }); + await expect.poll(() => screen.queryByTestId('tooltip')).toHaveTextContent('Jan'); + await userEvent.unhover(surface()); }); - it('dismisses a touch selection on a tap in the empty plot above a bar', async () => { + 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(); @@ -535,24 +535,38 @@ describe('choosing a period with a pointer', () => { 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]).toBeNull(); + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toMatchObject({ category: 'Jan' }); }); - it('selects a short bar from a minimum target above its top', async () => { + 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('pointerdown', surface(), plot.left + plot.width / 4, plot.bottom - 20, 'touch'); - await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toMatchObject({ category: 'Jan' }); + 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' }); }); }); diff --git a/packages/mosaic/src/primitives/chart/bars/bar-selection.ts b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts index 04bac19f8e8..4a0596c7bd0 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-selection.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts @@ -18,8 +18,8 @@ export const DEFAULT_BAR_MESSAGES = { projected: 'Projected', } as const satisfies Omit; -/** WCAG 2.5.8's minimum target size, so a short bar can still be picked. */ -const MIN_TARGET = 24; +/** The shortest a focus ring gets, so one around a short section stays visible. */ +const MIN_FOCUS_HEIGHT = 24; /** The narrowest a focus ring gets, so it stays findable when bars are a pixel or two wide. */ const MIN_FOCUS_WIDTH = 12; @@ -33,7 +33,7 @@ type BarSelectionOptions = Readonly<{ messages: Pick; }>; -/** How far up each category's positive section and down its negative section a pointer selects. */ +/** How far up each category's positive section and down its negative section a focus ring reaches. */ function sectionReach(layout: BarSelectionOptions['layout']) { const top = new Map(); const bottom = new Map(); @@ -49,14 +49,15 @@ function sectionReach(layout: BarSelectionOptions['layout']) { top.set(datumIndex, Math.min(top.get(datumIndex) ?? layout.zeroY, y)); } return { - positive: (datumIndex: number) => Math.min(top.get(datumIndex) ?? layout.zeroY, layout.zeroY - MIN_TARGET), - negative: (datumIndex: number) => Math.max(bottom.get(datumIndex) ?? layout.zeroY, layout.zeroY + MIN_TARGET), + positive: (datumIndex: number) => Math.min(top.get(datumIndex) ?? layout.zeroY, layout.zeroY - MIN_FOCUS_HEIGHT), + negative: (datumIndex: number) => Math.max(bottom.get(datumIndex) ?? layout.zeroY, layout.zeroY + MIN_FOCUS_HEIGHT), }; } /** - * Selects a section of a stacked bar: above the zero line or below it. A pointer selects only on a - * bar, or within the minimum target of a short one, so the empty plot around the bars selects nothing. + * 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, @@ -78,17 +79,19 @@ export function barSelectionModel({ return null; } const { positive, negative } = category.sections; - const onPositive = positive && y >= reach.positive(category.datumIndex) && y <= layout.zeroY + nearZero; - const onNegative = negative && y <= reach.negative(category.datumIndex) && y >= layout.zeroY - nearZero; - const section: BarSection | null = - onPositive && onNegative - ? (current?.section ?? (y < layout.zeroY ? 'positive' : 'negative')) - : onPositive - ? 'positive' - : onNegative - ? 'negative' - : null; - return section ? { category: category.key, section } : null; + 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; From bd0b3c404f9c186cb75f6f56a820a29a87102102 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 25 Nov 2026 16:59:06 -0700 Subject: [PATCH 37/40] feat(mosaic): outline the keyboard-selected section's painted bars The focus box followed the column band, so it was wider than the bars and brought the band's fill with it. `Chart.FocusOutline` is a `rect` in the `Chart.Bars` SVG around the selected section's painted bars, the projection included, `offset` px outside them and at least `minSize` px each way. It renders only for a keyboard selection. `focusRect` is removed, and `Chart.Cursor` is the column band again. --- .../mosaic/src/primitives/chart/README.md | 46 ++++++++++--------- .../chart/__tests__/chart.browser.test.tsx | 46 ++++++++++++------- .../primitives/chart/__tests__/chart.test.tsx | 11 +++++ .../primitives/chart/__tests__/test-chart.tsx | 1 + .../src/primitives/chart/bars/bar-context.ts | 4 +- .../src/primitives/chart/bars/bar-layout.ts | 38 +++++++++++++++ .../primitives/chart/bars/bar-selection.ts | 34 -------------- .../src/primitives/chart/bars/chart-bars.tsx | 14 +++++- .../chart/bars/chart-focus-outline.tsx | 44 ++++++++++++++++++ .../src/primitives/chart/chart-cursor.tsx | 24 +++------- .../mosaic/src/primitives/chart/chart.doc.ts | 16 ++++++- packages/mosaic/src/primitives/chart/index.ts | 2 +- .../primitives/chart/internal/selection.ts | 4 +- .../chart/internal/use-chart-instance.ts | 3 -- .../chart/line-chart-contract.test-d.ts | 1 - packages/mosaic/src/primitives/chart/parts.ts | 1 + packages/mosaic/src/primitives/chart/types.ts | 5 -- 17 files changed, 187 insertions(+), 107 deletions(-) create mode 100644 packages/mosaic/src/primitives/chart/bars/chart-focus-outline.tsx diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index 37efe93bda3..dcc26dc482a 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -83,17 +83,18 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) | `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.FocusOutline` | `` | Outlines the keyboard-selected section's painted bars | | `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, or its section for the keyboard | +| `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. +Every part throws outside `Chart.Root`. `Chart.Bars` also throws when the chart did not come from `Chart.useBarChart`. `Chart.Bar`, `Chart.ProjectionOutline` and `Chart.FocusOutline` 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`. @@ -167,23 +168,22 @@ The hook returns a `BarChartInstance`: the [chart object](#the-chart-obj 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 | -| `selectionSource` | `'pointer' \| 'keyboard' \| 'external' \| null` | What made `selected`. `keyboard` is when a focus ring belongs on the selected category | -| `tooltipAnchor` | `{ x, y } \| null` | Where a tooltip for `selected` points | -| `focusRect` | `{ x, y, width, height } \| null` | The box a focus ring for `selected` outlines: for bars, the selected section, at least 12px wide and 24px tall | -| `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` | +| 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 | +| `selectionSource` | `'pointer' \| 'keyboard' \| 'external' \| null` | What made `selected`. `keyboard` is when a focus ring belongs on the selected category | +| `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. @@ -282,7 +282,7 @@ Painting the bars is the one thing the chart object does not do, because their c | `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-focus-visible` | `Chart.Cursor` | Present while the keyboard selected the category. The cursor then covers `focusRect`; ring it, not the whole chart | +| `data-focus-visible` | `Chart.Cursor` | Present while the keyboard selected the category, while `Chart.FocusOutline` outlines it | | `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 | @@ -358,6 +358,10 @@ The Canvas repaints in the same frame when: 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. +### `Chart.FocusOutline` + +While the keyboard has a section selected, `Chart.FocusOutline` draws a `rect` around that section's painted bars: the bars less the gaps between them, and the projection above a positive stack. It sits `offset` px outside them and is at least `minSize` px each way, so it stays findable around a bar a pixel or two wide. It is a real SVG element, so style `stroke`, `stroke-width` and `rx` with CSS; the primitive sets only `fill: none` and `pointer-events: none`. A pointer never shows it: the hover band marks a pointer selection. + ## Paint order Root does not reorder its children, so paint order is JSX order. Write the parts in this order: @@ -394,4 +398,4 @@ A lost or missing 2D context throws `Chart.CanvasRenderError`, with the original ## 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, the tooltip's anchor and the focus ring's box. 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. +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__/chart.browser.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx index 476099bc270..2f0d9b6be01 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx @@ -414,16 +414,23 @@ describe('resizing', () => { }); }); -describe('the keyboard focus on a section', () => { +describe('the keyboard focus outline', () => { type Signed = { period: string; gained: number; lost: number }; const signedSeries = [ { key: 'gained', value: (row: Signed) => row.gained }, { key: 'lost', value: (row: Signed) => row.lost }, ]; const signedIndex = (row: Signed) => row.period; - const cursor = () => screen.getByTestId('cursor').getBoundingClientRect(); + const outline = () => screen.queryByTestId('focus-outline'); + const box = () => { + const element = outline(); + if (!element) { + throw new Error('No focus outline'); + } + return element.getBoundingClientRect(); + }; - it('covers the selected section from the zero line to its far edge', async () => { + it('outlines the painted bars of the selected section, not the column', async () => { await render(
{ index={signedIndex} ariaLabel='Growth' height={300} - barClassName='red' + barClassName='projected' onSelectionChange={() => {}} />
, @@ -443,33 +450,38 @@ describe('the keyboard focus on a section', () => { const plot = surface().getBoundingClientRect(); surface().focus(); - await expect.poll(() => screen.queryByTestId('cursor')?.hasAttribute('data-focus-visible')).toBe(true); - const positive = cursor(); + await expect.poll(outline).toBeTruthy(); + const positive = box(); await userEvent.keyboard('{ArrowDown}'); - await expect.poll(() => cursor().top).toBeGreaterThan(positive.top); - const negative = cursor(); + await expect.poll(() => box().top).toBeGreaterThan(positive.top); + const negative = box(); - expect(positive.top).toBeCloseTo(plot.top, -1); - expect(negative.top).toBeCloseTo(positive.bottom, 0); - expect(negative.bottom).toBeCloseTo(plot.bottom, -1); - expect(positive.height).toBeLessThan(plot.height); + expect(positive.width).toBeCloseTo(32 + 2 * 2, 0); + expect(positive.width).toBeLessThan(plot.width / 4); + expect(Math.abs(positive.bottom - negative.top)).toBeLessThanOrEqual(5); + expect(negative.bottom).toBeGreaterThan(negative.top); }); - it('keeps a minimum width on dense data', async () => { + it('keeps a minimum size on dense data', async () => { const dense = Array.from({ length: 400 }, (_, i) => ({ period: `P${i}`, value: 10 + (i % 7) })); await render(); surface().focus(); - await expect.poll(() => screen.queryByTestId('cursor')?.hasAttribute('data-focus-visible')).toBe(true); - expect(cursor().width).toBeGreaterThanOrEqual(12); + await expect.poll(outline).toBeTruthy(); + expect(box().width).toBeGreaterThanOrEqual(12); }); - it('keeps the full-height band for a mouse hover', async () => { + it('shows only for the keyboard and goes away on Escape', async () => { await render(); const plot = surface().getBoundingClientRect(); await userEvent.hover(surface(), { position: { x: centerOfCategory(0).x - plot.left, y: plot.height - 4 } }); await expect.poll(() => screen.queryByTestId('cursor')).toBeTruthy(); - expect(cursor().height).toBeCloseTo(plot.height, 0); + expect(outline()).toBeNull(); await userEvent.unhover(surface()); + + surface().focus(); + await expect.poll(outline).toBeTruthy(); + await userEvent.keyboard('{Escape}'); + await expect.poll(outline).toBeNull(); }); }); diff --git a/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx index a2621abbec8..a5d213a62a1 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx @@ -60,6 +60,17 @@ describe('composing parts', () => { ); }); + it('throws when Chart.FocusOutline is used outside Chart.Bars', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + expect(() => + render( + + + , + ), + ).toThrow(' must be used within '); + }); + it('throws when Chart.Bar is used outside Chart.Bars', () => { vi.spyOn(console, 'error').mockImplementation(() => {}); expect(() => diff --git a/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx b/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx index cb1c60c5cf4..6af197daae3 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx @@ -64,6 +64,7 @@ export function TestChart({ {bar ? : null} + diff --git a/packages/mosaic/src/primitives/chart/bars/bar-context.ts b/packages/mosaic/src/primitives/chart/bars/bar-context.ts index f2066c4eedd..e839fe76d5a 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-context.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-context.ts @@ -3,7 +3,7 @@ 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 { BarBounds, 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`. */ @@ -41,6 +41,8 @@ export interface BarsContextValue { setBar: (element: BarStyleElement | null) => void; /** Registers the `Chart.ProjectionOutline` element whose computed stroke outlines the projection. */ setProjectionOutline: (element: BarStyleElement | null) => void; + /** The painted extent of the keyboard-selected section, or null. `Chart.FocusOutline` draws around it. */ + focusBounds: BarBounds | null; } export const BarsContext = createContext(null); diff --git a/packages/mosaic/src/primitives/chart/bars/bar-layout.ts b/packages/mosaic/src/primitives/chart/bars/bar-layout.ts index 13f6f344486..95768887eb0 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-layout.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-layout.ts @@ -405,3 +405,41 @@ export function fitProjectionToBar( radius: Math.min(outerRadius, width / 2, height), }; } + +export type BarBounds = Readonly<{ x: number; y: number; width: number; height: number }>; + +/** + * The painted extent of one category's positive or negative section: its marks less the gaps + * between them, and the projection above a positive stack. Null when the section paints nothing. + */ +export function paintedSectionBounds( + marks: readonly BarMark[], + projection: PaintedProjection | null, + datumIndex: number, + positive: boolean, +): BarBounds | null { + let left = Infinity; + let right = -Infinity; + let top = Infinity; + let bottom = -Infinity; + const include = (x: number, y: number, width: number, height: number) => { + left = Math.min(left, x); + right = Math.max(right, x + width); + top = Math.min(top, y); + bottom = Math.max(bottom, y + height); + }; + for (const mark of marks) { + if (mark.datumIndex === datumIndex && mark.positive === positive) { + include( + mark.x, + mark.y + mark.paintInsetTop, + mark.width, + mark.height - mark.paintInsetTop - mark.paintInsetBottom, + ); + } + } + if (positive && projection?.datumIndex === datumIndex) { + include(projection.x, projection.y, projection.width, projection.height); + } + return left < right && top < bottom ? { x: left, y: top, width: right - left, height: bottom - top } : null; +} diff --git a/packages/mosaic/src/primitives/chart/bars/bar-selection.ts b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts index 4a0596c7bd0..5b486e66dfb 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-selection.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts @@ -18,12 +18,6 @@ export const DEFAULT_BAR_MESSAGES = { projected: 'Projected', } as const satisfies Omit; -/** The shortest a focus ring gets, so one around a short section stays visible. */ -const MIN_FOCUS_HEIGHT = 24; - -/** The narrowest a focus ring gets, so it stays findable when bars are a pixel or two wide. */ -const MIN_FOCUS_WIDTH = 12; - type BarSelectionOptions = Readonly<{ layout: Pick, 'plot' | 'zeroY' | 'categories' | 'prepared' | 'scaleY' | 'projection'>; data: readonly TDatum[]; @@ -33,27 +27,6 @@ type BarSelectionOptions = Readonly<{ messages: Pick; }>; -/** How far up each category's positive section and down its negative section a focus ring reaches. */ -function sectionReach(layout: BarSelectionOptions['layout']) { - const top = new Map(); - const bottom = new Map(); - for (const point of layout.prepared.points) { - if (point.positive) { - top.set(point.datumIndex, Math.min(top.get(point.datumIndex) ?? layout.zeroY, layout.scaleY(point.end))); - } else { - bottom.set(point.datumIndex, Math.max(bottom.get(point.datumIndex) ?? layout.zeroY, layout.scaleY(point.start))); - } - } - if (layout.projection) { - const { datumIndex, y } = layout.projection; - top.set(datumIndex, Math.min(top.get(datumIndex) ?? layout.zeroY, y)); - } - return { - positive: (datumIndex: number) => Math.min(top.get(datumIndex) ?? layout.zeroY, layout.zeroY - MIN_FOCUS_HEIGHT), - negative: (datumIndex: number) => Math.max(bottom.get(datumIndex) ?? layout.zeroY, layout.zeroY + MIN_FOCUS_HEIGHT), - }; -} - /** * 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 @@ -67,7 +40,6 @@ export function barSelectionModel({ formatValue, messages, }: BarSelectionOptions): SelectionModel, BarCategory> { - const reach = sectionReach(layout); 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)); @@ -132,12 +104,6 @@ export function barSelectionModel({ }, verticalInstructions: twoSided ? messages.vertical : '', anchor: (_, category) => ({ x: category.center, y: layout.plot.y }), - focusRect: (selection, category) => { - const width = Math.max(category.width, MIN_FOCUS_WIDTH); - const top = selection.section === 'positive' ? reach.positive(category.datumIndex) : layout.zeroY; - const bottom = selection.section === 'positive' ? layout.zeroY : reach.negative(category.datumIndex); - return { x: category.center - width / 2, y: top, width, height: bottom - top }; - }, surfaceAttributes: selection => ({ 'data-active-section': selection?.section }), }; } diff --git a/packages/mosaic/src/primitives/chart/bars/chart-bars.tsx b/packages/mosaic/src/primitives/chart/bars/chart-bars.tsx index 994a78a3cff..03287eeb8e0 100644 --- a/packages/mosaic/src/primitives/chart/bars/chart-bars.tsx +++ b/packages/mosaic/src/primitives/chart/bars/chart-bars.tsx @@ -15,7 +15,7 @@ import { } from './bar-canvas'; import { CanvasRenderError } from './bar-canvas-error'; import { BarsContext, useBarChartContext } from './bar-context'; -import { fitProjectionToBar, projectStackedBarMarks } from './bar-layout'; +import { fitProjectionToBar, paintedSectionBounds, projectStackedBarMarks } from './bar-layout'; export type ChartBarsProps = ComponentProps<'div'>; @@ -131,7 +131,17 @@ export const ChartBars = React.forwardRef(functi () => getProjectionOutlineSnapshot(projectionOutline), getServerSnapshot, ); - const barsContext = React.useMemo(() => ({ setBar, setProjectionOutline }), []); + const focused = chart.selectionSource === 'keyboard' ? chart.selected : null; + const focusDatumIndex = focused?.datumIndex; + const focusPositive = focused ? focused.section === 'positive' : undefined; + const focusBounds = React.useMemo( + () => + focusDatumIndex === undefined || focusPositive === undefined + ? null + : paintedSectionBounds(marks, projection, focusDatumIndex, focusPositive), + [focusDatumIndex, focusPositive, marks, projection], + ); + const barsContext = React.useMemo(() => ({ setBar, setProjectionOutline, focusBounds }), [focusBounds]); React.useLayoutEffect(() => { if (!canvas || !hasArea(size)) { diff --git a/packages/mosaic/src/primitives/chart/bars/chart-focus-outline.tsx b/packages/mosaic/src/primitives/chart/bars/chart-focus-outline.tsx new file mode 100644 index 00000000000..b4dcc994273 --- /dev/null +++ b/packages/mosaic/src/primitives/chart/bars/chart-focus-outline.tsx @@ -0,0 +1,44 @@ +'use client'; + +import React from 'react'; + +import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../../utils'; +import { useBarsContext } from './bar-context'; + +export type ChartFocusOutlineProps = ComponentProps<'rect'> & { + /** Space in px between the painted bars and the outline. Default: 2 */ + offset?: number; + /** The smallest width and height in px, so the outline stays findable around thin or short bars. Default: 12 */ + minSize?: number; +}; + +/** + * Outlines the painted bars of the selected section while the keyboard made the selection. A + * `rect` in the `Chart.Bars` SVG, so CSS styles its `stroke`, `stroke-width` and `rx` directly. + */ +export const ChartFocusOutline = React.forwardRef( + function ChartFocusOutline(props, ref) { + const { offset = 2, minSize = 12, render, ...otherProps } = props; + const { focusBounds } = useBarsContext('FocusOutline'); + + const width = focusBounds ? Math.max(focusBounds.width + offset * 2, minSize) : 0; + const height = focusBounds ? Math.max(focusBounds.height + offset * 2, minSize) : 0; + const ownProps = { + 'aria-hidden': true, + x: focusBounds ? focusBounds.x + focusBounds.width / 2 - width / 2 : 0, + y: focusBounds ? focusBounds.y + focusBounds.height / 2 - height / 2 : 0, + width, + height, + fill: 'none', + pointerEvents: 'none', + } satisfies DefaultProps<'rect'>; + + return useRender({ + defaultTagName: 'rect', + render, + enabled: focusBounds !== null, + ref, + props: mergeProps<'rect'>(ownProps, otherProps), + }); + }, +); diff --git a/packages/mosaic/src/primitives/chart/chart-cursor.tsx b/packages/mosaic/src/primitives/chart/chart-cursor.tsx index f0fbf6484f0..7c4667c7432 100644 --- a/packages/mosaic/src/primitives/chart/chart-cursor.tsx +++ b/packages/mosaic/src/primitives/chart/chart-cursor.tsx @@ -14,30 +14,18 @@ export const ChartCursor = React.forwardRef(fu const { plot, selected } = chart; const selectedCategory = selected ? chart.categories[selected.datumIndex] : undefined; - // A keyboard selection outlines just its section, such as one side of a stacked bar; a pointer - // shows the whole column. - const focusRect = chart.selectionSource === 'keyboard' ? chart.focusRect : null; const ownProps = { 'aria-hidden': 'true', - style: focusRect + style: selectedCategory ? { position: 'absolute', - top: focusRect.y - plot.y, - left: focusRect.x - plot.x, - width: focusRect.width, - height: focusRect.height, + top: 0, + bottom: 0, + left: selectedCategory.x - plot.x, + width: selectedCategory.width, pointerEvents: 'none', } - : selectedCategory - ? { - position: 'absolute', - top: 0, - bottom: 0, - left: selectedCategory.x - plot.x, - width: selectedCategory.width, - pointerEvents: 'none', - } - : undefined, + : undefined, } satisfies DefaultProps<'div'>; return useRender({ diff --git a/packages/mosaic/src/primitives/chart/chart.doc.ts b/packages/mosaic/src/primitives/chart/chart.doc.ts index ec73c8df900..7016a221865 100644 --- a/packages/mosaic/src/primitives/chart/chart.doc.ts +++ b/packages/mosaic/src/primitives/chart/chart.doc.ts @@ -3,6 +3,7 @@ import type { ChartBarProps, ChartBarsProps, ChartCursorProps, + ChartFocusOutlineProps, ChartGridProps, ChartProjectionOutlineProps, ChartRootProps, @@ -129,6 +130,18 @@ export default { 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.FocusOutline': { + description: + 'A `rect` in the `Chart.Bars` SVG around the painted bars of the selected section, rendered only while the keyboard made the selection. Style its `stroke`, `stroke-width` and `rx`; it has `fill: none`. Throws outside `Chart.Bars`.', + props: { + offset: { type: 'number', doc: 'Space in px between the painted bars and the outline.', default: '2' }, + minSize: { + type: 'number', + doc: 'The smallest width and height in px, so the outline stays findable around thin or short bars.', + default: '12', + }, + }, + }, 'Chart.YAxis': { description: 'An `aria-hidden` `svg` that holds the Y tick labels in the left margin.', props: { @@ -181,7 +194,7 @@ export default { }, 'Chart.Cursor': { description: - 'An `aria-hidden` `div` that covers the selected category, with its width. While the keyboard selected the category it carries `data-focus-visible` and covers just the selected section (`focusRect`, at least 12px wide and 24px tall), so the focus ring can sit on it. Throws outside `Chart.Selection`.', + 'An `aria-hidden` `div` that covers the selected category, with its width. Carries `data-focus-visible` while the keyboard selected the category. Throws outside `Chart.Selection`.', }, 'Chart.Tooltip': { description: @@ -283,6 +296,7 @@ const chart = Chart.useBarChart({ data, series, index, selection, onSelectionCha 'Chart.Bars': ChartBarsProps; 'Chart.Bar': ChartBarProps; 'Chart.ProjectionOutline': ChartProjectionOutlineProps; + 'Chart.FocusOutline': ChartFocusOutlineProps; 'Chart.YAxis': ChartYAxisProps; 'Chart.YTick': ChartYTickProps; 'Chart.XAxis': ChartXAxisProps; diff --git a/packages/mosaic/src/primitives/chart/index.ts b/packages/mosaic/src/primitives/chart/index.ts index 46540c3990b..4121446ac40 100644 --- a/packages/mosaic/src/primitives/chart/index.ts +++ b/packages/mosaic/src/primitives/chart/index.ts @@ -4,6 +4,7 @@ export type { ChartBarProps, ChartBarsProps, ChartCursorProps, + ChartFocusOutlineProps, ChartGridProps, ChartProjectionOutlineProps, ChartRootProps, @@ -29,7 +30,6 @@ export type { ChartOptions, ChartPlot, ChartPoint, - ChartRect, ChartSelection, ChartSize, ChartTick, diff --git a/packages/mosaic/src/primitives/chart/internal/selection.ts b/packages/mosaic/src/primitives/chart/internal/selection.ts index 6e6a9811ea0..572670a5b73 100644 --- a/packages/mosaic/src/primitives/chart/internal/selection.ts +++ b/packages/mosaic/src/primitives/chart/internal/selection.ts @@ -1,4 +1,4 @@ -import type { ChartActive, ChartCategory, ChartMessages, ChartPoint, ChartRect, ChartSelection } from '../types'; +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.', @@ -36,8 +36,6 @@ export type SelectionModel< verticalInstructions: string; /** Where a tooltip for the selection points. */ anchor: (selection: TSelection, category: TCategory) => ChartPoint; - /** The box a focus ring for the selection outlines, large enough to find on dense data. */ - focusRect: (selection: TSelection, category: TCategory) => ChartRect; /** State the interaction surface carries for styling, such as `data-active-section`. */ surfaceAttributes: (selection: TSelection | null) => Readonly>; }>; diff --git a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts index 57292780398..90c7843e409 100644 --- a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts +++ b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts @@ -187,8 +187,6 @@ export function useChartInstance< const keyboardInstructions = getKeyboardInstructions(messages, model.verticalInstructions, !!onActivate); const tooltipAnchor = valid?.selection && currentCategory && selected ? model.anchor(valid.selection, currentCategory) : null; - const focusRect = - valid?.selection && currentCategory && selected ? model.focusRect(valid.selection, currentCategory) : null; const lastIndexRef = React.useRef(0); const selectedIndex = valid ? currentCategory?.datumIndex : undefined; @@ -370,7 +368,6 @@ export function useChartInstance< selected, selectionSource: selected ? (valid?.source ?? null) : null, tooltipAnchor, - focusRect, announcement, keyboardInstructions, select, 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 index 921aa4d8454..b4e8296448e 100644 --- a/packages/mosaic/src/primitives/chart/line-chart-contract.test-d.ts +++ b/packages/mosaic/src/primitives/chart/line-chart-contract.test-d.ts @@ -36,7 +36,6 @@ const lineModel = { describe: active => `Users ${active.datum.users}`, verticalInstructions: '', anchor: (_, category) => ({ x: category.center, y: 0 }), - focusRect: (_, category) => ({ x: category.center - 6, y: 0, width: 12, height: 12 }), surfaceAttributes: () => ({}), } satisfies SelectionModel>; diff --git a/packages/mosaic/src/primitives/chart/parts.ts b/packages/mosaic/src/primitives/chart/parts.ts index 8047f6dc07e..bb9b59f4a75 100644 --- a/packages/mosaic/src/primitives/chart/parts.ts +++ b/packages/mosaic/src/primitives/chart/parts.ts @@ -15,4 +15,5 @@ export { type ChartProjectionOutlineProps, ChartProjectionOutline as ProjectionOutline, } from './bars/chart-projection-outline'; +export { type ChartFocusOutlineProps, ChartFocusOutline as FocusOutline } from './bars/chart-focus-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 index ae276666377..b206b573f1c 100644 --- a/packages/mosaic/src/primitives/chart/types.ts +++ b/packages/mosaic/src/primitives/chart/types.ts @@ -21,9 +21,6 @@ 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 }>; -/** A box in chart coordinates. */ -export type ChartRect = Readonly<{ x: number; y: number; width: number; height: 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. @@ -145,8 +142,6 @@ export type ChartInstance< selectionSource: 'pointer' | 'keyboard' | 'external' | null; /** Where a tooltip for `selected` points, in chart coordinates. */ tooltipAnchor: ChartPoint | null; - /** The box a focus ring for `selected` outlines, such as a bar section. Null with no selection. */ - focusRect: ChartRect | null; /** The text of the keyboard selection's status announcement. */ announcement: string; /** The keys the chart answers to, for the visually hidden description. */ From 7eed3a48ab2fce937a6360f1c17c0273a2785586 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 25 Nov 2026 17:05:03 -0700 Subject: [PATCH 38/40] revert(mosaic): drop the chart's keyboard focus ring changes Reverts bb31b51e0a (`Chart.FocusOutline`), 0e9a749be5 (`focusRect`) and 5245c6ee00 (`selectionSource` and the cursor's `data-focus-visible`). A keyboard selection shows the same band and tooltip as a pointer again, and the chart-wide ring marks focus. The column hit test from 8a23d9e7f0 stays, and the section measurement only the focus box used is removed. --- .../mosaic/src/primitives/chart/README.md | 39 +++++----- .../chart/__tests__/chart.browser.test.tsx | 71 ------------------- .../primitives/chart/__tests__/chart.test.tsx | 27 ------- .../primitives/chart/__tests__/test-chart.tsx | 1 - .../src/primitives/chart/bars/bar-context.ts | 4 +- .../src/primitives/chart/bars/bar-layout.ts | 38 ---------- .../primitives/chart/bars/bar-selection.ts | 2 +- .../src/primitives/chart/bars/chart-bars.tsx | 14 +--- .../chart/bars/chart-focus-outline.tsx | 44 ------------ .../src/primitives/chart/chart-cursor.tsx | 4 -- .../mosaic/src/primitives/chart/chart.doc.ts | 16 +---- packages/mosaic/src/primitives/chart/index.ts | 1 - .../chart/internal/use-chart-instance.ts | 1 - packages/mosaic/src/primitives/chart/parts.ts | 1 - packages/mosaic/src/primitives/chart/types.ts | 5 -- 15 files changed, 21 insertions(+), 247 deletions(-) delete mode 100644 packages/mosaic/src/primitives/chart/bars/chart-focus-outline.tsx diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index dcc26dc482a..0046825777f 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -83,7 +83,6 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) | `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.FocusOutline` | `` | Outlines the keyboard-selected section's painted bars | | `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 | @@ -94,7 +93,7 @@ const chart = Chart.useBarChart({ data, series, index, onActivate: openPeriod }) 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`, `Chart.ProjectionOutline` and `Chart.FocusOutline` 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. +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`. @@ -168,22 +167,21 @@ The hook returns a `BarChartInstance`: the [chart object](#the-chart-obj 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 | -| `selectionSource` | `'pointer' \| 'keyboard' \| 'external' \| null` | What made `selected`. `keyboard` is when a focus ring belongs on the selected category | -| `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` | +| 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. @@ -282,7 +280,6 @@ Painting the bars is the one thing the chart object does not do, because their c | `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-focus-visible` | `Chart.Cursor` | Present while the keyboard selected the category, while `Chart.FocusOutline` outlines it | | `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 | @@ -358,10 +355,6 @@ The Canvas repaints in the same frame when: 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. -### `Chart.FocusOutline` - -While the keyboard has a section selected, `Chart.FocusOutline` draws a `rect` around that section's painted bars: the bars less the gaps between them, and the projection above a positive stack. It sits `offset` px outside them and is at least `minSize` px each way, so it stays findable around a bar a pixel or two wide. It is a real SVG element, so style `stroke`, `stroke-width` and `rx` with CSS; the primitive sets only `fill: none` and `pointer-events: none`. A pointer never shows it: the hover band marks a pointer selection. - ## Paint order Root does not reorder its children, so paint order is JSX order. Write the parts in this order: diff --git a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx index 2f0d9b6be01..6e66ff5b799 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx @@ -414,77 +414,6 @@ describe('resizing', () => { }); }); -describe('the keyboard focus outline', () => { - type Signed = { period: string; gained: number; lost: number }; - const signedSeries = [ - { key: 'gained', value: (row: Signed) => row.gained }, - { key: 'lost', value: (row: Signed) => row.lost }, - ]; - const signedIndex = (row: Signed) => row.period; - const outline = () => screen.queryByTestId('focus-outline'); - const box = () => { - const element = outline(); - if (!element) { - throw new Error('No focus outline'); - } - return element.getBoundingClientRect(); - }; - - it('outlines the painted bars of the selected section, not the column', async () => { - await render( -
- {}} - /> -
, - ); - const plot = surface().getBoundingClientRect(); - - surface().focus(); - await expect.poll(outline).toBeTruthy(); - const positive = box(); - await userEvent.keyboard('{ArrowDown}'); - await expect.poll(() => box().top).toBeGreaterThan(positive.top); - const negative = box(); - - expect(positive.width).toBeCloseTo(32 + 2 * 2, 0); - expect(positive.width).toBeLessThan(plot.width / 4); - expect(Math.abs(positive.bottom - negative.top)).toBeLessThanOrEqual(5); - expect(negative.bottom).toBeGreaterThan(negative.top); - }); - - it('keeps a minimum size on dense data', async () => { - const dense = Array.from({ length: 400 }, (_, i) => ({ period: `P${i}`, value: 10 + (i % 7) })); - await render(); - surface().focus(); - await expect.poll(outline).toBeTruthy(); - expect(box().width).toBeGreaterThanOrEqual(12); - }); - - it('shows only for the keyboard and goes away on Escape', async () => { - await render(); - const plot = surface().getBoundingClientRect(); - await userEvent.hover(surface(), { position: { x: centerOfCategory(0).x - plot.left, y: plot.height - 4 } }); - await expect.poll(() => screen.queryByTestId('cursor')).toBeTruthy(); - expect(outline()).toBeNull(); - await userEvent.unhover(surface()); - - surface().focus(); - await expect.poll(outline).toBeTruthy(); - await userEvent.keyboard('{Escape}'); - await expect.poll(outline).toBeNull(); - }); -}); - 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>(); diff --git a/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx index a5d213a62a1..d4546e79cc8 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.test.tsx @@ -60,17 +60,6 @@ describe('composing parts', () => { ); }); - it('throws when Chart.FocusOutline is used outside Chart.Bars', () => { - vi.spyOn(console, 'error').mockImplementation(() => {}); - expect(() => - render( - - - , - ), - ).toThrow(' must be used within '); - }); - it('throws when Chart.Bar is used outside Chart.Bars', () => { vi.spyOn(console, 'error').mockImplementation(() => {}); expect(() => @@ -182,22 +171,6 @@ describe('choosing a period', () => { }); describe('choosing a period with the keyboard', () => { - it.each([ - { name: 'a keyboard selection', setup: { data: quarter }, keyboard: true, focusVisible: true }, - { - name: 'a selection the consumer set', - setup: { data: quarter, selection: { category: 'Feb', section: 'positive' as const } }, - keyboard: false, - focusVisible: false, - }, - ])('marks the cursor data-focus-visible only for $name', ({ setup, keyboard, focusVisible }) => { - const { interaction, getByTestId } = renderChart(setup); - if (keyboard) { - press(interaction, 'ArrowRight'); - } - expect(getByTestId('cursor').hasAttribute('data-focus-visible')).toBe(focusVisible); - }); - it('is a focusable group, not a button or an image', () => { const { getByRole } = renderChart({ data: quarter }); const group = getByRole('group', { name: 'Growth' }); diff --git a/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx b/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx index 6af197daae3..cb1c60c5cf4 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/test-chart.tsx @@ -64,7 +64,6 @@ export function TestChart({ {bar ? : null} - diff --git a/packages/mosaic/src/primitives/chart/bars/bar-context.ts b/packages/mosaic/src/primitives/chart/bars/bar-context.ts index e839fe76d5a..f2066c4eedd 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-context.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-context.ts @@ -3,7 +3,7 @@ import { createContext, useContext } from 'react'; import { ChartContext } from '../chart-context'; import type { CartesianChartInstance, ChartInstance } from '../types'; import type { BarStyleElement } from './bar-canvas'; -import type { BarBounds, PreparedStackedBars, StackedBarLayout } from './bar-layout'; +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`. */ @@ -41,8 +41,6 @@ export interface BarsContextValue { setBar: (element: BarStyleElement | null) => void; /** Registers the `Chart.ProjectionOutline` element whose computed stroke outlines the projection. */ setProjectionOutline: (element: BarStyleElement | null) => void; - /** The painted extent of the keyboard-selected section, or null. `Chart.FocusOutline` draws around it. */ - focusBounds: BarBounds | null; } export const BarsContext = createContext(null); diff --git a/packages/mosaic/src/primitives/chart/bars/bar-layout.ts b/packages/mosaic/src/primitives/chart/bars/bar-layout.ts index 95768887eb0..13f6f344486 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-layout.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-layout.ts @@ -405,41 +405,3 @@ export function fitProjectionToBar( radius: Math.min(outerRadius, width / 2, height), }; } - -export type BarBounds = Readonly<{ x: number; y: number; width: number; height: number }>; - -/** - * The painted extent of one category's positive or negative section: its marks less the gaps - * between them, and the projection above a positive stack. Null when the section paints nothing. - */ -export function paintedSectionBounds( - marks: readonly BarMark[], - projection: PaintedProjection | null, - datumIndex: number, - positive: boolean, -): BarBounds | null { - let left = Infinity; - let right = -Infinity; - let top = Infinity; - let bottom = -Infinity; - const include = (x: number, y: number, width: number, height: number) => { - left = Math.min(left, x); - right = Math.max(right, x + width); - top = Math.min(top, y); - bottom = Math.max(bottom, y + height); - }; - for (const mark of marks) { - if (mark.datumIndex === datumIndex && mark.positive === positive) { - include( - mark.x, - mark.y + mark.paintInsetTop, - mark.width, - mark.height - mark.paintInsetTop - mark.paintInsetBottom, - ); - } - } - if (positive && projection?.datumIndex === datumIndex) { - include(projection.x, projection.y, projection.width, projection.height); - } - return left < right && top < bottom ? { x: left, y: top, width: right - left, height: bottom - top } : null; -} diff --git a/packages/mosaic/src/primitives/chart/bars/bar-selection.ts b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts index 5b486e66dfb..5c965223d6a 100644 --- a/packages/mosaic/src/primitives/chart/bars/bar-selection.ts +++ b/packages/mosaic/src/primitives/chart/bars/bar-selection.ts @@ -19,7 +19,7 @@ export const DEFAULT_BAR_MESSAGES = { } as const satisfies Omit; type BarSelectionOptions = Readonly<{ - layout: Pick, 'plot' | 'zeroY' | 'categories' | 'prepared' | 'scaleY' | 'projection'>; + layout: Pick, 'plot' | 'zeroY' | 'categories' | 'prepared'>; data: readonly TDatum[]; series: readonly BarSeries[]; projection: BarProjection | undefined; diff --git a/packages/mosaic/src/primitives/chart/bars/chart-bars.tsx b/packages/mosaic/src/primitives/chart/bars/chart-bars.tsx index 03287eeb8e0..994a78a3cff 100644 --- a/packages/mosaic/src/primitives/chart/bars/chart-bars.tsx +++ b/packages/mosaic/src/primitives/chart/bars/chart-bars.tsx @@ -15,7 +15,7 @@ import { } from './bar-canvas'; import { CanvasRenderError } from './bar-canvas-error'; import { BarsContext, useBarChartContext } from './bar-context'; -import { fitProjectionToBar, paintedSectionBounds, projectStackedBarMarks } from './bar-layout'; +import { fitProjectionToBar, projectStackedBarMarks } from './bar-layout'; export type ChartBarsProps = ComponentProps<'div'>; @@ -131,17 +131,7 @@ export const ChartBars = React.forwardRef(functi () => getProjectionOutlineSnapshot(projectionOutline), getServerSnapshot, ); - const focused = chart.selectionSource === 'keyboard' ? chart.selected : null; - const focusDatumIndex = focused?.datumIndex; - const focusPositive = focused ? focused.section === 'positive' : undefined; - const focusBounds = React.useMemo( - () => - focusDatumIndex === undefined || focusPositive === undefined - ? null - : paintedSectionBounds(marks, projection, focusDatumIndex, focusPositive), - [focusDatumIndex, focusPositive, marks, projection], - ); - const barsContext = React.useMemo(() => ({ setBar, setProjectionOutline, focusBounds }), [focusBounds]); + const barsContext = React.useMemo(() => ({ setBar, setProjectionOutline }), []); React.useLayoutEffect(() => { if (!canvas || !hasArea(size)) { diff --git a/packages/mosaic/src/primitives/chart/bars/chart-focus-outline.tsx b/packages/mosaic/src/primitives/chart/bars/chart-focus-outline.tsx deleted file mode 100644 index b4dcc994273..00000000000 --- a/packages/mosaic/src/primitives/chart/bars/chart-focus-outline.tsx +++ /dev/null @@ -1,44 +0,0 @@ -'use client'; - -import React from 'react'; - -import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../../utils'; -import { useBarsContext } from './bar-context'; - -export type ChartFocusOutlineProps = ComponentProps<'rect'> & { - /** Space in px between the painted bars and the outline. Default: 2 */ - offset?: number; - /** The smallest width and height in px, so the outline stays findable around thin or short bars. Default: 12 */ - minSize?: number; -}; - -/** - * Outlines the painted bars of the selected section while the keyboard made the selection. A - * `rect` in the `Chart.Bars` SVG, so CSS styles its `stroke`, `stroke-width` and `rx` directly. - */ -export const ChartFocusOutline = React.forwardRef( - function ChartFocusOutline(props, ref) { - const { offset = 2, minSize = 12, render, ...otherProps } = props; - const { focusBounds } = useBarsContext('FocusOutline'); - - const width = focusBounds ? Math.max(focusBounds.width + offset * 2, minSize) : 0; - const height = focusBounds ? Math.max(focusBounds.height + offset * 2, minSize) : 0; - const ownProps = { - 'aria-hidden': true, - x: focusBounds ? focusBounds.x + focusBounds.width / 2 - width / 2 : 0, - y: focusBounds ? focusBounds.y + focusBounds.height / 2 - height / 2 : 0, - width, - height, - fill: 'none', - pointerEvents: 'none', - } satisfies DefaultProps<'rect'>; - - return useRender({ - defaultTagName: 'rect', - render, - enabled: focusBounds !== null, - ref, - props: mergeProps<'rect'>(ownProps, otherProps), - }); - }, -); diff --git a/packages/mosaic/src/primitives/chart/chart-cursor.tsx b/packages/mosaic/src/primitives/chart/chart-cursor.tsx index 7c4667c7432..41e66431350 100644 --- a/packages/mosaic/src/primitives/chart/chart-cursor.tsx +++ b/packages/mosaic/src/primitives/chart/chart-cursor.tsx @@ -33,10 +33,6 @@ export const ChartCursor = React.forwardRef(fu render, ref, enabled: !!selectedCategory, - state: { focusVisible: chart.selectionSource === 'keyboard' }, - stateAttributesMapping: { - focusVisible: (focusVisible: boolean) => (focusVisible ? { 'data-focus-visible': '' } : null), - }, props: mergeProps<'div'>(ownProps, otherProps), }); }); diff --git a/packages/mosaic/src/primitives/chart/chart.doc.ts b/packages/mosaic/src/primitives/chart/chart.doc.ts index 7016a221865..fb31c06d0a3 100644 --- a/packages/mosaic/src/primitives/chart/chart.doc.ts +++ b/packages/mosaic/src/primitives/chart/chart.doc.ts @@ -3,7 +3,6 @@ import type { ChartBarProps, ChartBarsProps, ChartCursorProps, - ChartFocusOutlineProps, ChartGridProps, ChartProjectionOutlineProps, ChartRootProps, @@ -130,18 +129,6 @@ export default { 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.FocusOutline': { - description: - 'A `rect` in the `Chart.Bars` SVG around the painted bars of the selected section, rendered only while the keyboard made the selection. Style its `stroke`, `stroke-width` and `rx`; it has `fill: none`. Throws outside `Chart.Bars`.', - props: { - offset: { type: 'number', doc: 'Space in px between the painted bars and the outline.', default: '2' }, - minSize: { - type: 'number', - doc: 'The smallest width and height in px, so the outline stays findable around thin or short bars.', - default: '12', - }, - }, - }, 'Chart.YAxis': { description: 'An `aria-hidden` `svg` that holds the Y tick labels in the left margin.', props: { @@ -194,7 +181,7 @@ export default { }, 'Chart.Cursor': { description: - 'An `aria-hidden` `div` that covers the selected category, with its width. Carries `data-focus-visible` while the keyboard selected the category. Throws outside `Chart.Selection`.', + 'An `aria-hidden` `div` that covers the selected category, with its width. Throws outside `Chart.Selection`.', }, 'Chart.Tooltip': { description: @@ -296,7 +283,6 @@ const chart = Chart.useBarChart({ data, series, index, selection, onSelectionCha 'Chart.Bars': ChartBarsProps; 'Chart.Bar': ChartBarProps; 'Chart.ProjectionOutline': ChartProjectionOutlineProps; - 'Chart.FocusOutline': ChartFocusOutlineProps; 'Chart.YAxis': ChartYAxisProps; 'Chart.YTick': ChartYTickProps; 'Chart.XAxis': ChartXAxisProps; diff --git a/packages/mosaic/src/primitives/chart/index.ts b/packages/mosaic/src/primitives/chart/index.ts index 4121446ac40..9a739115120 100644 --- a/packages/mosaic/src/primitives/chart/index.ts +++ b/packages/mosaic/src/primitives/chart/index.ts @@ -4,7 +4,6 @@ export type { ChartBarProps, ChartBarsProps, ChartCursorProps, - ChartFocusOutlineProps, ChartGridProps, ChartProjectionOutlineProps, ChartRootProps, diff --git a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts index 90c7843e409..bc6f50ee58d 100644 --- a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts +++ b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts @@ -366,7 +366,6 @@ export function useChartInstance< categories, xTicks, selected, - selectionSource: selected ? (valid?.source ?? null) : null, tooltipAnchor, announcement, keyboardInstructions, diff --git a/packages/mosaic/src/primitives/chart/parts.ts b/packages/mosaic/src/primitives/chart/parts.ts index bb9b59f4a75..8047f6dc07e 100644 --- a/packages/mosaic/src/primitives/chart/parts.ts +++ b/packages/mosaic/src/primitives/chart/parts.ts @@ -15,5 +15,4 @@ export { type ChartProjectionOutlineProps, ChartProjectionOutline as ProjectionOutline, } from './bars/chart-projection-outline'; -export { type ChartFocusOutlineProps, ChartFocusOutline as FocusOutline } from './bars/chart-focus-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 index b206b573f1c..48447aa59d0 100644 --- a/packages/mosaic/src/primitives/chart/types.ts +++ b/packages/mosaic/src/primitives/chart/types.ts @@ -135,11 +135,6 @@ export type ChartInstance< xTicks: (options?: XTicksOptions) => XTick[]; /** The selection in the current data, or null. */ selected: TActive | null; - /** - * What made `selected`: a pointer, the keyboard, or `selection`/`select`. Null with no selection. - * `keyboard` is when a focus ring belongs on the selected category. - */ - selectionSource: 'pointer' | 'keyboard' | 'external' | null; /** Where a tooltip for `selected` points, in chart coordinates. */ tooltipAnchor: ChartPoint | null; /** The text of the keyboard selection's status announcement. */ From fd5318bf4af87ecf2b5508f9b8f1a0fd650d21d3 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 25 Nov 2026 17:49:04 -0700 Subject: [PATCH 39/40] perf(mosaic): measure the chart when it attaches, not at the first ResizeObserver callback The chart learned its size only from its first ResizeObserver callback, at the next rendering step after hydration, so any effect the page ran first held the canvas blank. In a Swingset production build, syntax highlighting did that on 3 of 11 warm reloads, leaving the chart blank 186 to 212ms against 63 to 72ms otherwise. Measuring the element as it attaches removed those slow reloads (none of 11, measured with `offsetWidth`). The chart now reads `getBoundingClientRect()` when `rootRef` attaches, which keeps fractional widths, so React paints the canvas in the commit that mounts or hydrates it. The ResizeObserver still commits every later size, and corrects the first one under a scaled ancestor. --- .../mosaic/src/primitives/chart/README.md | 2 +- .../chart/__tests__/chart.browser.test.tsx | 18 +++++++++++ .../chart/internal/use-chart-size.ts | 30 ++++++++++++++----- 3 files changed, 41 insertions(+), 9 deletions(-) diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index 0046825777f..0264fdc746d 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -371,7 +371,7 @@ Inside `Chart.Bars`, the position of `Chart.Bar` and `Chart.ProjectionOutline` d ## 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 container size is committed before paint, so the chart follows its container while resizing. +`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. diff --git a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx index 6e66ff5b799..2eb2a63a3c2 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx @@ -412,6 +412,24 @@ describe('resizing', () => { 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', () => { diff --git a/packages/mosaic/src/primitives/chart/internal/use-chart-size.ts b/packages/mosaic/src/primitives/chart/internal/use-chart-size.ts index 4cdfb0a5b5b..bf28674fda2 100644 --- a/packages/mosaic/src/primitives/chart/internal/use-chart-size.ts +++ b/packages/mosaic/src/primitives/chart/internal/use-chart-size.ts @@ -25,20 +25,34 @@ export function useChartSize() { 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 width = toHalfPixel(box?.inlineSize ?? entry?.contentRect.width ?? 0); - const height = toHalfPixel(box?.blockSize ?? entry?.contentRect.height ?? 0); - if (lastSize?.width === width && lastSize.height === height) { - return; + 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)); } - const next = { width, height }; - lastSize = 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], ); From 52c04622b254ab45d9bf72b581c3f2196bc8adec Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 2 Dec 2026 17:06:06 -0700 Subject: [PATCH 40/40] fix(mosaic): read the restricted imports from the mosaic lint config Main inlined the root Oxlint config into the mosaic config and dropped the rootConfig import, so the chart import overrides read an undefined binding. Keep the restricted imports in one constant that the base rule and the chart overrides spread. --- packages/mosaic/oxlint.config.mjs | 50 ++++++++++++++----------------- 1 file changed, 23 insertions(+), 27 deletions(-) diff --git a/packages/mosaic/oxlint.config.mjs b/packages/mosaic/oxlint.config.mjs index aebb3ea6405..c0aeffc3085 100644 --- a/packages/mosaic/oxlint.config.mjs +++ b/packages/mosaic/oxlint.config.mjs @@ -5,7 +5,24 @@ import noUnneededEffects from 'eslint-plugin-react-you-might-not-need-an-effect' import { defineConfig } from 'oxlint'; const mosaicRoot = import.meta.dirname; -const [, rootRestrictedImports] = rootConfig.rules['no-restricted-imports']; +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']; @@ -301,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', @@ -481,9 +477,9 @@ export default defineConfig({ 'no-restricted-imports': [ 'error', { - ...rootRestrictedImports, + ...restrictedImports, patterns: [ - ...rootRestrictedImports.patterns, + ...restrictedImports.patterns, { group: ['**/chart/internal', '**/chart/internal/*'], message: chartInternalMessage, @@ -500,9 +496,9 @@ export default defineConfig({ 'no-restricted-imports': [ 'error', { - ...rootRestrictedImports, + ...restrictedImports, patterns: [ - ...rootRestrictedImports.patterns, + ...restrictedImports.patterns, { group: ['./internal', './internal/*'], message: chartInternalMessage }, ], },