From 435adee15baa7c3dd3d89789af39cd615765f41f Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 10:28:26 -0700 Subject: [PATCH 01/46] feat(mosaic): add the categorical chart palette tokens Add --cl-color-chart-1 to -6 to colorVars. Each light-dark() value is tuned per mode so the palette passes the data-viz lightness, chroma, adjacent CVD, normal-vision and 3:1 contrast checks on the surface, and a unit test reruns those checks on the token text. --- .../chart/__tests__/chart-palette.test.ts | 47 ++++++ .../chart/__tests__/palette-checks.ts | 139 ++++++++++++++++++ packages/mosaic/src/tokens.stylex.ts | 10 ++ 3 files changed, 196 insertions(+) create mode 100644 packages/mosaic/src/components/chart/__tests__/chart-palette.test.ts create mode 100644 packages/mosaic/src/components/chart/__tests__/palette-checks.ts diff --git a/packages/mosaic/src/components/chart/__tests__/chart-palette.test.ts b/packages/mosaic/src/components/chart/__tests__/chart-palette.test.ts new file mode 100644 index 00000000000..dfe3eb55294 --- /dev/null +++ b/packages/mosaic/src/components/chart/__tests__/chart-palette.test.ts @@ -0,0 +1,47 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +import { assertChartPalette, oklchToSrgb8, type PaletteMode, type Srgb8 } from './palette-checks'; + +const tokens = readFileSync(resolve(import.meta.dirname, '../../../tokens.stylex.ts'), 'utf8'); + +const OKLCH = String.raw`oklch\(([\d.]+) ([\d.]+) ([\d.]+)\)`; +const TOKEN = new RegExp(String.raw`'--cl-color-chart-(\d+)': 'light-dark\(${OKLCH}, ${OKLCH}\)'`, 'g'); + +function palette(mode: PaletteMode): Srgb8[] { + const slots = [...tokens.matchAll(TOKEN)]; + return slots.map(([, , ...values]) => { + const [l, c, h] = (mode === 'light' ? values.slice(0, 3) : values.slice(3)).map(Number); + return oklchToSrgb8(l, c, h); + }); +} + +const white = oklchToSrgb8(1, 0, 0); +// `--cl-color-surface` in dark mode: 5% of the white neutral mixed in OKLab into the 0.16 page. +const darkSurface = oklchToSrgb8(0.95 * 0.16 + 0.05, 0, 0); +const darkPage = oklchToSrgb8(0.16, 0, 0); + +describe('chart palette tokens', () => { + it('defines six slots, in order, each as one light-dark value', () => { + expect([...tokens.matchAll(TOKEN)].map(([, slot]) => slot)).toEqual(['1', '2', '3', '4', '5', '6']); + }); + + it('passes the data-viz checks in light mode on the surface', () => { + expect(() => assertChartPalette(palette('light'), 'light', white)).not.toThrow(); + }); + + it('passes the data-viz checks in dark mode on the surface and on the page', () => { + expect(() => assertChartPalette(palette('dark'), 'dark', darkSurface)).not.toThrow(); + expect(() => assertChartPalette(palette('dark'), 'dark', darkPage)).not.toThrow(); + }); + + it('rejects the original story hues, which fail the band and chroma checks', () => { + const channel = (value: string, at: number) => parseInt(value.slice(at, at + 2), 16) / 255; + const hex = (value: string): Srgb8 => [channel(value, 0), channel(value, 2), channel(value, 4)]; + const original = ['7c3aed', '0ea5e9', 'f97316', '06b6d4', 'eab308', '64748b'].map(hex); + + expect(() => assertChartPalette(original, 'light', white)).toThrow(/slot 5: lightness .*\n.*slot 6: chroma/s); + }); +}); diff --git a/packages/mosaic/src/components/chart/__tests__/palette-checks.ts b/packages/mosaic/src/components/chart/__tests__/palette-checks.ts new file mode 100644 index 00000000000..199f6102475 --- /dev/null +++ b/packages/mosaic/src/components/chart/__tests__/palette-checks.ts @@ -0,0 +1,139 @@ +// The computable checks of the data-viz palette validator (dataviz skill, `validate_palette.js`), +// ported with its thresholds and its Machado 2009 CVD model so the token test fails where the +// validator would. + +type Vector = readonly [number, number, number]; + +export type PaletteMode = 'light' | 'dark'; + +const BAND: Record = { light: [0.43, 0.77], dark: [0.48, 0.67] }; +const CHROMA_FLOOR = 0.1; +const CVD_TARGET = 8; +const NORMAL_FLOOR = 15; +const CONTRAST_MIN = 3; + +const MACHADO = { + protan: [ + [0.152286, 1.052583, -0.204868], + [0.114503, 0.786281, 0.099216], + [-0.003882, -0.048116, 1.051998], + ], + deutan: [ + [0.367322, 0.860646, -0.227968], + [0.280085, 0.672501, 0.047413], + [-0.01182, 0.04294, 0.968881], + ], +} as const; + +const multiply = (matrix: readonly (readonly number[])[], [r, g, b]: Vector): Vector => [ + matrix[0][0] * r + matrix[0][1] * g + matrix[0][2] * b, + matrix[1][0] * r + matrix[1][1] * g + matrix[1][2] * b, + matrix[2][0] * r + matrix[2][1] * g + matrix[2][2] * b, +]; + +const clamp = (value: number) => Math.min(1, Math.max(0, value)); +const toLinear = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4); +const toGamma = (c: number) => (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055); + +/** An sRGB color quantized to 8 bits per channel, as the validator reads a hex value. */ +export type Srgb8 = Vector; + +export function oklchToSrgb8(l: number, c: number, h: number): Srgb8 { + const rad = (h * Math.PI) / 180; + const a = c * Math.cos(rad); + const b = c * Math.sin(rad); + const lms: Vector = [ + (l + 0.3963377774 * a + 0.2158037573 * b) ** 3, + (l - 0.1055613458 * a - 0.0638541728 * b) ** 3, + (l - 0.0894841775 * a - 1.291485548 * b) ** 3, + ]; + const linear = multiply( + [ + [4.0767416621, -3.3077115913, 0.2309699292], + [-1.2684380046, 2.6097574011, -0.3413193965], + [-0.0041960863, -0.7034186147, 1.707614701], + ], + lms, + ); + if (linear.some(channel => channel < -1e-4 || channel > 1 + 1e-4)) { + throw new Error(`oklch(${l} ${c} ${h}) is outside sRGB`); + } + const [r, g, bl] = linear.map(channel => Math.round(toGamma(clamp(channel)) * 255) / 255); + return [r, g, bl]; +} + +const linearOf = (color: Srgb8): Vector => [toLinear(color[0]), toLinear(color[1]), toLinear(color[2])]; + +function oklabOfLinear([r, g, b]: Vector): Vector { + const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); + const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); + const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); + return [ + 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, + 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, + 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s, + ]; +} + +function deltaE(first: Srgb8, second: Srgb8, kind?: keyof typeof MACHADO) { + const view = (color: Srgb8) => { + const linear = linearOf(color); + if (!kind) { + return oklabOfLinear(linear); + } + const [r, g, b] = multiply(MACHADO[kind], linear); + return oklabOfLinear([clamp(r), clamp(g), clamp(b)]); + }; + const [l1, a1, b1] = view(first); + const [l2, a2, b2] = view(second); + return 100 * Math.hypot(l1 - l2, a1 - a2, b1 - b2); +} + +function contrast(first: Srgb8, second: Srgb8) { + const luminance = (color: Srgb8) => { + const [r, g, b] = linearOf(color); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; + }; + const [high, low] = [luminance(first), luminance(second)].sort((x, y) => y - x); + return (high + 0.05) / (low + 0.05); +} + +/** + * Throws with every failed check when a categorical palette, in slot order, fails the validator's + * adjacent-pair checks against a surface: lightness band, chroma floor, CVD separation (protan and + * deutan), the normal-vision floor and 3:1 contrast. + */ +export function assertChartPalette(palette: readonly Srgb8[], mode: PaletteMode, surface: Srgb8) { + const failures: string[] = []; + const [low, high] = BAND[mode]; + palette.forEach((color, index) => { + const [l, a, b] = oklabOfLinear(linearOf(color)); + const slot = index + 1; + if (l < low || l > high) { + failures.push(`slot ${slot}: lightness ${l.toFixed(3)} outside ${low}-${high}`); + } + if (Math.hypot(a, b) < CHROMA_FLOOR) { + failures.push(`slot ${slot}: chroma ${Math.hypot(a, b).toFixed(3)} below ${CHROMA_FLOOR}`); + } + if (contrast(color, surface) < CONTRAST_MIN) { + failures.push(`slot ${slot}: contrast ${contrast(color, surface).toFixed(2)} below ${CONTRAST_MIN}:1`); + } + }); + for (let index = 1; index < palette.length; index++) { + const pair = `slots ${index} and ${index + 1}`; + const cvd = Math.min( + deltaE(palette[index - 1], palette[index], 'protan'), + deltaE(palette[index - 1], palette[index], 'deutan'), + ); + if (cvd < CVD_TARGET) { + failures.push(`${pair}: CVD ΔE ${cvd.toFixed(1)} below ${CVD_TARGET}`); + } + const normal = deltaE(palette[index - 1], palette[index]); + if (normal < NORMAL_FLOOR) { + failures.push(`${pair}: ΔE ${normal.toFixed(1)} below ${NORMAL_FLOOR}`); + } + } + if (failures.length > 0) { + throw new Error(`The ${mode} chart palette fails the data-viz checks:\n${failures.join('\n')}`); + } +} diff --git a/packages/mosaic/src/tokens.stylex.ts b/packages/mosaic/src/tokens.stylex.ts index 800b359cdea..d5d31a8b95f 100644 --- a/packages/mosaic/src/tokens.stylex.ts +++ b/packages/mosaic/src/tokens.stylex.ts @@ -86,6 +86,16 @@ const colorDefaults = { '--cl-color-input-placeholder': neutralMix(45, 64.25), '--cl-color-ring': neutralMix(80, 90), + + // The categorical chart palette, named by slot rather than hue so an override never makes a name + // wrong. Each step is chosen per mode to pass the data-viz checks against the surface; + // `components/chart/__tests__/chart-palette.test.ts` reruns them on these values. + '--cl-color-chart-1': 'light-dark(oklch(0.5413 0.2466 293.01), oklch(0.5995 0.2298 293.13))', + '--cl-color-chart-2': 'light-dark(oklch(0.5814 0.1271 237.19), oklch(0.6004 0.1307 237.14))', + '--cl-color-chart-3': 'light-dark(oklch(0.6198 0.1695 47.72), oklch(0.6198 0.1695 47.72))', + '--cl-color-chart-4': 'light-dark(oklch(0.6498 0.115 215.37), oklch(0.6646 0.1167 214.95))', + '--cl-color-chart-5': 'light-dark(oklch(0.6608 0.1347 85.9), oklch(0.665 0.136 85.61))', + '--cl-color-chart-6': 'light-dark(oklch(0.4802 0.1034 256.97), oklch(0.5389 0.1039 257.52))', } as const; export const colorVars = stylex.defineVars(colorDefaults); From 00f62c0aa801222b5a976463542a80c285182ca0 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 10:39:33 -0700 Subject: [PATCH 02/46] feat(mosaic): add the shared styled Chart legend, tooltip content and frame Chart.Legend and Chart.TooltipContent take plain data and read no context, so they render beside any chart, a skeleton or a card header. components/chart/internal holds the frame every styled chart type renders through: the series bridge that keys series by position for the headless hook, the static per-slot color rules, locale formatting, grid, axes, selection layer and overlays. The chart internal lint fence now lets only components/*-chart/ import it. --- packages/mosaic/oxlint.config.mjs | 32 ++- .../components/chart/__tests__/chart.test.tsx | 93 +++++++++ .../src/components/chart/chart-series.ts | 81 ++++++++ .../src/components/chart/chart.messages.ts | 5 + .../src/components/chart/chart.parts.ts | 1 + .../src/components/chart/chart.styles.ts | 101 ++++++++++ .../mosaic/src/components/chart/chart.tsx | 167 +++++++++++++++ packages/mosaic/src/components/chart/index.ts | 13 ++ .../chart/internal/chart-frame.styles.ts | 86 ++++++++ .../components/chart/internal/chart-frame.tsx | 190 ++++++++++++++++++ .../chart/internal/series-bridge.ts | 66 ++++++ .../chart/internal/series.styles.ts | 37 ++++ .../chart/internal/use-chart-format.ts | 45 +++++ packages/mosaic/src/localization/registry.ts | 2 + packages/mosaic/src/styles/index.ts | 10 + 15 files changed, 926 insertions(+), 3 deletions(-) create mode 100644 packages/mosaic/src/components/chart/__tests__/chart.test.tsx create mode 100644 packages/mosaic/src/components/chart/chart-series.ts create mode 100644 packages/mosaic/src/components/chart/chart.messages.ts create mode 100644 packages/mosaic/src/components/chart/chart.parts.ts create mode 100644 packages/mosaic/src/components/chart/chart.styles.ts create mode 100644 packages/mosaic/src/components/chart/chart.tsx create mode 100644 packages/mosaic/src/components/chart/index.ts create mode 100644 packages/mosaic/src/components/chart/internal/chart-frame.styles.ts create mode 100644 packages/mosaic/src/components/chart/internal/chart-frame.tsx create mode 100644 packages/mosaic/src/components/chart/internal/series-bridge.ts create mode 100644 packages/mosaic/src/components/chart/internal/series.styles.ts create mode 100644 packages/mosaic/src/components/chart/internal/use-chart-format.ts diff --git a/packages/mosaic/oxlint.config.mjs b/packages/mosaic/oxlint.config.mjs index c0aeffc3085..0a7de75fcbd 100644 --- a/packages/mosaic/oxlint.config.mjs +++ b/packages/mosaic/oxlint.config.mjs @@ -24,7 +24,7 @@ const restrictedImports = { ], }; 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/.'; + 'The chart internals are for chart types. Import primitives/chart/internal only from a chart-type folder under src/primitives/chart/, such as chart/bars/, and components/chart/internal only from a src/components/-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 = [ @@ -472,7 +472,14 @@ export default defineConfig({ }, { files: ['src/**/*'], - excludeFiles: ['src/primitives/chart/**', 'src/**/__tests__/**', 'src/**/*.test.{ts,tsx}', 'src/**/*.test-d.ts'], + excludeFiles: [ + 'src/primitives/chart/**', + 'src/components/*-chart/**', + 'src/components/chart/internal/**', + 'src/**/__tests__/**', + 'src/**/*.test.{ts,tsx}', + 'src/**/*.test-d.ts', + ], rules: { 'no-restricted-imports': [ 'error', @@ -490,7 +497,26 @@ export default defineConfig({ }, }, { - files: ['src/primitives/chart/*'], + files: ['src/components/*-chart/**', 'src/components/chart/internal/**'], + excludeFiles: ['src/**/__tests__/**', 'src/**/*.test.{ts,tsx}', 'src/**/*.test-d.ts'], + rules: { + 'no-restricted-imports': [ + 'error', + { + ...rootRestrictedImports, + patterns: [ + ...rootRestrictedImports.patterns, + { + group: ['**/primitives/chart/internal', '**/primitives/chart/internal/*'], + message: chartInternalMessage, + }, + ], + }, + ], + }, + }, + { + files: ['src/primitives/chart/*', 'src/components/chart/*'], excludeFiles: ['src/**/*.test.{ts,tsx}', 'src/**/*.test-d.ts'], rules: { 'no-restricted-imports': [ diff --git a/packages/mosaic/src/components/chart/__tests__/chart.test.tsx b/packages/mosaic/src/components/chart/__tests__/chart.test.tsx new file mode 100644 index 00000000000..552aca114d7 --- /dev/null +++ b/packages/mosaic/src/components/chart/__tests__/chart.test.tsx @@ -0,0 +1,93 @@ +import { act, cleanup, render, screen, within } from '@testing-library/react'; +import { afterEach, describe, expect, it } from 'vitest'; + +import { Chart, type ChartSeries } from '..'; +import { bridgeSeries } from '../internal/series-bridge'; + +afterEach(() => cleanup()); + +type Row = { signups: number; churned: number }; + +const signups: ChartSeries = { key: 'signups', label: 'Sign-ups', color: 1, value: row => row.signups }; + +const series: ChartSeries[] = [ + signups, + { key: 'churned', label: 'Churned', color: 'var(--brand-red)', value: row => row.churned, description: 'Lost users' }, +]; + +describe('Chart.Legend', () => { + it('lists each series by label, keyed by its series key', () => { + render(); + + const items = screen.getAllByRole('listitem'); + expect(items.map(item => item.textContent)).toEqual(['Sign-ups', 'Churned']); + expect(items.map(item => item.getAttribute('data-series'))).toEqual(['signups', 'churned']); + }); + + it('makes an item with a description a button that shows it in a tooltip', async () => { + render(); + + const trigger = screen.getByRole('button', { name: 'Churned' }); + await act(() => trigger.focus()); + + expect(await screen.findByRole('tooltip')).toHaveTextContent('Lost users'); + expect(screen.queryByRole('button', { name: 'Sign-ups' })).toBeNull(); + }); + + it('draws a dashed swatch for a projection entry', () => { + render( + , + ); + + expect(screen.getByRole('listitem').querySelector('.cl-chart-swatch')).toHaveAttribute('data-swatch', 'dashed'); + }); +}); + +describe('Chart.TooltipContent', () => { + it('shows the heading, the metrics and one row per series with its value', () => { + render( + +12%} + metrics={[{ label: 'Total', value: '1,204' }]} + rows={[ + { key: 'signups', label: 'Sign-ups', color: 1, value: '1,000' }, + { key: 'returning', label: 'Returning', color: 2, value: '204' }, + ]} + footer={

Incomplete period

} + />, + ); + + expect(screen.getByText('Jan 5, 2026').parentElement).toHaveTextContent('Jan 5, 2026+12%'); + expect(screen.getByRole('term')).toHaveTextContent('Total'); + expect(screen.getByRole('definition')).toHaveTextContent('1,204'); + const rows = within(screen.getByRole('list')).getAllByRole('listitem'); + expect(rows.map(row => [row.getAttribute('data-series'), row.textContent])).toEqual([ + ['signups', 'Sign-ups1,000'], + ['returning', 'Returning204'], + ]); + expect(screen.getByText('Incomplete period')).toBeInTheDocument(); + }); +}); + +describe('series boundary', () => { + it('keys series by position and resolves palette slots to their tokens', () => { + const bridge = bridgeSeries(series); + + expect(bridge.positioned.map(entry => entry.key)).toEqual(['0', '1']); + expect(bridge.colors).toEqual(['var(--cl-color-chart-1)', 'var(--brand-red)']); + expect(bridge.seriesAt('1').key).toBe('churned'); + }); + + it('rejects a repeated key', () => { + expect(() => bridgeSeries([...series, signups])).toThrow('Two chart series share the key "signups"'); + }); + + it('rejects more series than the chart has slots, naming the fix', () => { + const many = Array.from({ length: 9 }, (_, i): ChartSeries => ({ ...signups, key: `s${i}` })); + + expect(() => bridgeSeries(many)).toThrow(/at most 8 series, and got 9. Fold the smallest into one "Other" series/); + }); +}); diff --git a/packages/mosaic/src/components/chart/chart-series.ts b/packages/mosaic/src/components/chart/chart-series.ts new file mode 100644 index 00000000000..bd3a9830a75 --- /dev/null +++ b/packages/mosaic/src/components/chart/chart-series.ts @@ -0,0 +1,81 @@ +import type React from 'react'; + +import type { colorVars } from '../../tokens.stylex'; + +type ChartTokenName = Extract; + +/** + * A palette slot, `n` for `--cl-color-chart-n`. Derived from the tokens, so a new slot token widens + * it and nothing else lists the slots. + */ +export type ChartPaletteSlot = ChartTokenName extends `--cl-color-chart-${infer Slot extends number}` ? Slot : never; + +/** + * A color outside the palette, for a series whose color carries meaning, such as a ramp or a brand + * color. A bare keyword such as `'purple'` does not compile, which also catches a misspelled slot. + */ +export type ChartCustomColor = + | `var(--${string})` + | `light-dark(${string})` + | `oklch(${string})` + | `oklab(${string})` + | `color-mix(${string})` + | `rgb(${string})` + | `hsl(${string})` + | `#${string}`; + +export type ChartColor = ChartPaletteSlot | ChartCustomColor; + +/** Slot `n` becomes `var(--cl-color-chart-n)`. A custom color passes through. */ +export function resolveChartColor(color: ChartColor): string { + return typeof color === 'number' ? `var(--cl-color-chart-${color})` : color; +} + +/** + * One series, for any chart type. The series owns its color: marks, legend and tooltip all read + * this field, so filtering the list never repaints the series that remain. + */ +export interface ChartSeries { + /** Unique within the chart. Reflected as `data-series` on legend items and tooltip rows. */ + key: string; + /** Shown in the legend and tooltip. */ + label: string; + /** A palette slot or a CSS color. There is no default by position. */ + color: ChartColor; + /** Reads the value from a row. Missing or non-finite values count as zero. */ + value: (datum: TDatum) => number | null | undefined; + /** Shown in a tooltip on the legend item, which becomes focusable. */ + description?: string; +} + +/** `square` mirrors a bar, `line` a line, `dashed` a projection. */ +export type ChartSwatch = 'square' | 'line' | 'dashed'; + +/** What a legend shows. A `ChartSeries` is assignable to it. */ +export interface ChartLegendItem { + key: string; + label: string; + color: ChartColor; + description?: string; + /** Default: 'square' */ + swatch?: ChartSwatch; +} + +/** One series row in a tooltip. `value` is already formatted. */ +export interface ChartTooltipRow { + key: string; + label: string; + color: ChartColor; + value: React.ReactNode; + /** Default: 'line' */ + swatch?: ChartSwatch; +} + +/** A summary row above the series rows, such as a total or a projection. */ +export interface ChartTooltipMetric { + label: string; + value: React.ReactNode; +} + +/** Where a formatted string appears. An axis wants the short form, a tooltip the full one. */ +export type ChartFormatPlace = 'axis' | 'tooltip'; diff --git a/packages/mosaic/src/components/chart/chart.messages.ts b/packages/mosaic/src/components/chart/chart.messages.ts new file mode 100644 index 00000000000..e5404e1d24c --- /dev/null +++ b/packages/mosaic/src/components/chart/chart.messages.ts @@ -0,0 +1,5 @@ +export const chartMessages = { + empty: 'No data to show', + renderError: 'The chart could not be displayed.', + retry: 'Try again', +}; diff --git a/packages/mosaic/src/components/chart/chart.parts.ts b/packages/mosaic/src/components/chart/chart.parts.ts new file mode 100644 index 00000000000..2d1acb2ce84 --- /dev/null +++ b/packages/mosaic/src/components/chart/chart.parts.ts @@ -0,0 +1 @@ +export { ChartLegend as Legend, ChartTooltipContent as TooltipContent } from './chart'; diff --git a/packages/mosaic/src/components/chart/chart.styles.ts b/packages/mosaic/src/components/chart/chart.styles.ts new file mode 100644 index 00000000000..9b83913a6ed --- /dev/null +++ b/packages/mosaic/src/components/chart/chart.styles.ts @@ -0,0 +1,101 @@ +import * as stylex from '@stylexjs/stylex'; + +import { colorVars, fontWeightVars, space, typeScaleVars } from '../../tokens.stylex'; + +const swatchColor = 'var(--_cl-chart-swatch)'; + +export const legendStyles = stylex.create({ + root: { + listStyle: 'none', + alignItems: 'center', + color: colorVars['--cl-color-foreground-secondary'], + columnGap: space['4'], + display: 'flex', + flexWrap: 'wrap', + fontSize: typeScaleVars['--cl-text-sm-size'], + lineHeight: typeScaleVars['--cl-text-sm-leading'], + rowGap: space['1.5'], + }, + item: { + gap: space['1.5'], + alignItems: 'center', + display: 'inline-flex', + }, + trigger: { + borderWidth: 0, + gap: space['1.5'], + alignItems: 'center', + backgroundColor: 'transparent', + cursor: 'help', + display: 'inline-flex', + textDecorationLine: 'underline', + textDecorationStyle: 'dotted', + textUnderlineOffset: '0.2em', + }, +}); + +export const swatchStyles = stylex.create({ + base: { + display: 'inline-block', + flexShrink: 0, + }, + square: { + borderRadius: '2px', + backgroundColor: swatchColor, + height: '0.625rem', + width: '0.625rem', + }, + line: { + borderRadius: '1px', + backgroundColor: swatchColor, + height: '0.875rem', + width: '0.25rem', + }, + dashed: { + borderTopColor: swatchColor, + borderTopStyle: 'dashed', + borderTopWidth: '2px', + height: 0, + width: '0.875rem', + }, + color: (color: string) => ({ '--_cl-chart-swatch': color }), +}); + +export const tooltipContentStyles = stylex.create({ + root: { + gap: space['2'], + color: colorVars['--cl-color-foreground'], + display: 'flex', + flexDirection: 'column', + fontSize: typeScaleVars['--cl-text-sm-size'], + lineHeight: typeScaleVars['--cl-text-sm-leading'], + minWidth: '10rem', + }, + heading: { + gap: space['3'], + alignItems: 'center', + display: 'flex', + fontWeight: fontWeightVars['--cl-font-medium'], + justifyContent: 'space-between', + }, + list: { + gap: space['1'], + listStyle: 'none', + display: 'flex', + flexDirection: 'column', + }, + row: { + gap: space['2'], + alignItems: 'center', + display: 'flex', + }, + label: { + color: colorVars['--cl-color-foreground-secondary'], + flexGrow: 1, + }, + value: { + fontVariantNumeric: 'tabular-nums', + fontWeight: fontWeightVars['--cl-font-medium'], + textAlign: 'end', + }, +}); diff --git a/packages/mosaic/src/components/chart/chart.tsx b/packages/mosaic/src/components/chart/chart.tsx new file mode 100644 index 00000000000..87a39e711b0 --- /dev/null +++ b/packages/mosaic/src/components/chart/chart.tsx @@ -0,0 +1,167 @@ +'use client'; + +import * as stylex from '@stylexjs/stylex'; +import React from 'react'; + +import type { MosaicElementProps } from '../../props'; +import { mergeStyleProps, themeProps } from '../../props'; +import { focusOutline } from '../../styles/focus-outline.styles'; +import { reset } from '../../styles/reset.styles'; +import { Tooltip } from '../tooltip'; +import { legendStyles, swatchStyles, tooltipContentStyles } from './chart.styles'; +import { + type ChartColor, + type ChartLegendItem, + type ChartSwatch, + type ChartTooltipMetric, + type ChartTooltipRow, + resolveChartColor, +} from './chart-series'; + +function Swatch({ color, swatch }: Readonly<{ color: ChartColor; swatch: ChartSwatch }>) { + return ( +