An open source design system that's fully customizable and agent ready
TypeScript
feat(charts): first pass — extract config-model chart into private @astryxdesign/charts (#3672)
Joey5796875e2a8d
diff --git a/CHARTV2_PHASE1_PLAN.md b/CHARTV2_PHASE1_PLAN.mdnew file mode 100644index 0000000000..74868c581f--- /dev/null+++ b/CHARTV2_PHASE1_PLAN.md@@ -0,0 +1,232 @@+# ChartV2 — Phase 1 Plan (make it good, in place)++Living plan for getting `packages/lab/src/ChartV2/` production-ready **in place** — no+renames, no deleting Chart v1, no new package, no docsite. Guiding principle+(from the owner): **real, production-ready fixes; default to the proper fix+whenever it's obviously right.**++Status legend: `[ ]` todo · `[~]` in progress · `[x]` done++---++## 0. How to run / review++```bash+pnpm -F @astryxdesign/build build # prereq+pnpm -F @astryxdesign/core build # prereq (lab typecheck needs core's dist)+pnpm storybook # http://localhost:6006 (Lab / ChartV2*)+pnpm -F @astryxdesign/lab typecheck # ChartV2 currently typechecks clean+pnpm test # vitest (no ChartV2 tests exist yet)+```++**Visual review harness** (how we "look at every chart"): a Playwright script+screenshots every ChartV2 story in light + dark by hitting+`iframe.html?id=<storyId>&globals=colorMode:{light|dark}`. Story IDs come from+`http://localhost:6006/index.json`. Kept in `/tmp/chartv2-shots/`. This is the+review loop — re-run after each change and eyeball the diffs.++---++## 1. Confirmed findings (evidence)++### Scale / domain++- **Continuous marks (line/area/dot) glue to plot edges + overshoot escapes.**+ `computeLayout` sets y-domain to exactly `[min,max]` (`.nice()` adds no padding+ when bounds are already round). `Simple Line`: Jan(38)=min sits on the axis,+ Jun(52)=max at top, and the `monotone` curve overshoots _above_ the plot.+ There is **no clipPath** (v1 has `astryx-chart-plot`) so overshoot renders into+ the margin. Bars look fine only because they force `includeZero`.+ → `layout.ts:128-136`, no clip in `Chart.tsx:295-346`.+- **Empty data breaks scales → streaming renders nothing.** With `data=[]`,+ `isNumericX` is false (`xValues.length > 0` guard), so x falls into the **band**+ branch with an empty domain; y-domain becomes `[Infinity,-Infinity]`. `streamGL`+ then maps pushed points through `xScale(n)`/`yScale(n)` → `undefined`/`NaN` →+ blank. Verified blank after 5s. → `layout.ts:44-60,84-136`, `streamGL.tsx:146-152`.+ **streamGL cannot work without `xDomain`/`yDomain` on the root.**+- **Financial composite is misleading**: volume bars (500–1500) share the price+ y-axis (80–130) and crush the candlesticks/MA to a sliver. Inherent to one+ shared scale. Story needs rethinking (drop volume, or a documented secondary-axis+ pattern). → `ChartV2Advanced.stories.tsx:121-171`.++### Chrome / layout++- **Band axis draws every category → candlestick x-labels overlap** into a smear+ (30 "Day N" labels). Auto-skip only runs if caller passes `maxTicks`. Needs+ width-aware default skipping. → `ChartAxis.tsx:89-113`.+- **Reference-line label badges clip** at the right edge ("Acceptable"); text width+ is estimated (`label.length*5.5+8`) and can overrun. → `referenceLine.tsx:70-71,177`.+- **Mixed Marks with `legend="end"` clips** the last bar/label (chart area shrinks+ but plot width/label centering overflow). → `Chart.tsx:277-282`.+- **Heatmap top row clips** slightly at the plot top. → `heatmapGL.tsx:102-105`.++### Broken defaults / correctness++- **Every mark's default color token is undefined.** `--color-chart-1`+ (bar/line/dot/area/band) and `--color-positive`/`--color-negative`+ (candlestick) do **not** exist in `packages/core/src/theme`. Default-colored+ marks render black fills / invisible strokes. All current stories dodge this by+ passing explicit hex. → `bar.tsx:72`, `line.tsx:35`, `dot.tsx:22`, `area.tsx:37`,+ `band.tsx`, `candlestick.tsx:21-22`.+- **Duplicate-key collision.** Series identity = `dataKey` (`key: dataKey`). Two+ series on one dataKey collide in the `resolved` map (`layout.ts` `resolved.set(s.key,…)`)+ and in React keys (`Chart.tsx` `key={s.key}`), silently dropping data. Live React+ warning fires on `AreaGradient` (`area('revenue')` + `line('revenue')`).+ Also `area` builds `gradientId = area-grad-${dataKey}` → duplicate DOM ids.+ → `types.ts:52-54`, all mark factories, `layout.ts:219`, `Chart.tsx:310-316`.+- **streamGL hardcodes `key:'stream'`** → two streams collide. → `streamGL.tsx:228`.+- **Inconsistent color API.** `bar`/`dot` accept `ColorAccessor` (string | fn);+ `line`/`area`/`band`/etc. accept only `string`. Accessor-colored series also+ vanish from the legend: `deriveLegendItems` drops any series with `color == null`,+ and accessor series set `color: undefined`. → `bar.tsx:12-14,83`, `dot.tsx:11,30`,+ `line.tsx:26-27`, `area.tsx:26-27`, `legend.ts:18-32`.+- **`dot.dodge` is a stubbed TODO** (declared, never used). → `dot.tsx:17,48`.+- **`key={i}` array-index React keys** in mark render loops → reconciliation bugs+ on reorder/stream. → `bar.tsx:151`, `line.tsx:88`, `dot.tsx:58`,+ `candlestick.tsx:83`, `errorBar.tsx:67`.+- **No color palette API** (v1 has `useChartColors`/`getChartColors` with+ `categorical`/`sequential`/`diverging`/`semantic`/`structural`/`alpha`). v2+ ships none. → compare `Chart/useChartColors.ts`, `Chart/getChartColors.ts`.+- **heatmapGL builds its own y band scale** (breaks one-shared-scale). → `heatmapGL.tsx:102-105`.++### Works well (leave alone)++All bar variants, negative values, grouped/stacked, mixed, area + stacked area,+confidence bands, error bars + reference band, WebGL scatter, heatmap coloring,+legend, swatch, and **dark mode across the board**.++---++## 2. Locked decisions++1. **Palette API** → build the real thing (reuse v1's `getChartColors`/`useChartColors`+ from the same package; wire marks to consume it + fix the broken default token).+2. **heatmapGL scale** → real fix: teach the chart root a categorical y-scale so the+ heatmap shares it.+3. **`yBaseline`/`yDomain`/`xDomain`** → full v1 parity (required for streaming).+4. **Mark names** (`bar`/`line`/`dot`) → deferred to packaging (not a bug; on the+ "not now" list). No renames now.++---++## 3. Work items (ordered)++Ordered to build foundation first and keep each step independently verifiable via+the screenshot harness.++### W1 — Series identity (`_uid`) [ ]++- **Problem:** duplicate-key collision (#3) + `key={i}` (#7) + streamGL key (#5).+- **Approach:** add layout-assigned `_uid` (mutable field, mirrors `_isTopOfStack`)+ = `${index}:${key}`; use it as the true identity for the `resolved` map, the+ `Chart` render key, tooltip lookups (`resolved.get`, `resolvedKeys`), and hover-dot+ keys. `key` stays a semantic label. Replace every `key={i}` in mark render loops+ with a stable per-datum key (e.g. `${dataIndex}` is fine _within_ a series, but+ prefer the x-value; index-in-series is acceptable since series are `_uid`-scoped).+ Fix `area` `gradientId` to include `_uid`.+- **Files:** `types.ts`, `layout.ts`, `Chart.tsx`, `ChartTooltip.tsx`, `tooltip.ts`,+ `marks/{bar,line,dot,candlestick,errorBar,area}.tsx`.+- **Verify:** `AreaGradient` React warning gone; a new "two series, same dataKey"+ story renders both.++### W2 — Domain / baseline parity + clip + continuous headroom [ ]++- **Problem:** edge-gluing + overshoot + empty-data breakage (#2, streaming).+- **Approach:** add `yBaseline?: 'auto'|'zero'|'data'`, `yDomain?`, `xDomain?` to+ `ChartProps`; thread into `computeLayout` (mirror v1 `Chart/Chart.tsx:150-220`:+ explicit domains authoritative + no `.nice()`; `zero` symmetric; `auto` includes+ 0). Precedence: `yDomain` > root `yBaseline` > per-mark `includeZero`. Add a+ `clipPath` (like v1 `astryx-chart-plot`) around the marks layer. Add small domain+ **headroom** for continuous-only charts (no bar/includeZero, no explicit domain)+ so line/area/dot endpoints aren't glued to edges. Handle empty-data: if `xDomain`+ given, honor it even when `data=[]` (so streaming has a real numeric scale);+ likewise `yDomain`.+- **Files:** `Chart.tsx`, `layout.ts`, `types.ts` (SeriesContext already carries scales).+- **Verify:** `Simple Line` no longer clips; streaming story (given `xDomain`/`yDomain`,+ or a rolling window) draws.++### W3 — Streaming works end-to-end [ ]++- Depends on W2. Update `StreamingLine` story to pass a domain / rolling window (v1+ "stable streaming window"). Confirm streamGL maps points and the axis slides.+- **Files:** `ChartV2Advanced.stories.tsx`, possibly `streamGL.tsx` (guard when scale+ isn't linear).++### W4 — Color: unified accessor + palette API + legend fix [ ]++- **Problem:** inconsistent color (#4), broken default token, accessor legend drop,+ no palette (#8).+- **Approach:**+ - Re-export v1 palette from ChartV2 (`useChartColors`, `getChartColors`, types) via+ `ChartV2/index.ts` + package `index.ts`.+ - Marks default `color` to `undefined` = "auto"; the **Chart root** resolves a+ categorical palette (`useChartColors().categorical(n)`) and assigns a color to+ each series lacking one, by index — store as `_resolvedColor` on the def (like+ `_uid`); marks read `self._resolvedColor ?? ownColor`. Fixes the broken token+ AND gives multi-series auto colors.+ - Widen `line`/`area` (and `band` where sensible) to accept `ColorAccessor` for+ parity with `bar`/`dot`. Share one `ColorAccessor` type (move to `types.ts`).+ - Legend: show accessor-colored series using a representative color (resolve the+ accessor at index 0, or the assigned palette color) instead of dropping them.+- **Files:** `ChartV2/index.ts`, package `index.ts`, `types.ts`, `Chart.tsx`,+ `legend.ts`, `marks/{bar,dot,line,area,band,candlestick}.tsx`.+- **Verify:** default-colored multi-series chart shows distinct colors; new+ accessor-colored story appears in legend; dark mode palette adapts.++### W5 — dot.dodge [ ]++- Implement real dodge (offset overlapping points at the same x by radius), or+ remove the option. Prefer implement (production-ready). → `dot.tsx`.++### W6 — heatmapGL shares the chart scale [ ]++- Add categorical y-scale support to the chart root so the heatmap reads the shared+ y-scale instead of building its own. Bigger core change; do after W1–W4 land.+- **Files:** `layout.ts`, `types.ts` (ChartScale/SeriesContext), `Chart.tsx`,+ `ChartAxis.tsx`/`ChartGrid.tsx` (categorical y), `marks/heatmapGL.tsx`.+- **Verify:** heatmap rows align to a shared left axis; no own `scaleBand`.++### W7 — Axis label auto-density [ ]++- Width-aware default label skipping for band axes (fix candlestick smear) without+ requiring `maxTicks`. → `ChartAxis.tsx:89-113`.++### W8 — Story-level fixes [ ]++- Reference-line label clipping (measure/clamp badge x). Mixed-marks `legend="end"`+ clipping. Financial composite rework (secondary-axis story or drop volume).+ Heatmap top-row clip.++### W9 — New stories (review targets from the brief) [ ]++- Plain SVG `dot` scatter (not WebGL).+- `dotGLInteractive` hover.+- `referenceLine` solo: single `y`; `y`+`y2` band; `x` line.+- Edge cases: empty data, single point, all zero, all negative, one huge outlier.+- Accessor-colored series (exercises the legend fix).+- Duplicate-dataKey series (exercises W1).+- Dark-mode coverage confirmed for each via the harness.++### W10 — Tests + final verification [ ]++- Add colocated vitest for: `layout` (domain/baseline/empty/stacking), `_uid`+ uniqueness, `legend` derivation (incl. accessor), `tooltip` derivation. Run+ `pnpm test`, `pnpm -F @astryxdesign/lab typecheck`, `lint`, and re-screenshot all+ forms light+dark.++---++## 4. To verify / open questions++- Confirm exact set of missing tokens and the right categorical token names to+ default to (palette resolves `--color-data-categorical-*`).+- Headroom amount for continuous charts (e.g. ~5%) — pick + document.+- heatmap categorical-y: does introducing a band y-scale disturb any existing+ numeric-y consumer? (Guard: only when a mark requests categorical y.)+- Should `yBaseline` default stay `'auto'`-equivalent given per-mark `includeZero`+ already exists? (Lean: root override wins; keep per-mark default.)++## 5. Out of scope (deferred)++Rename ChartV2 → Chart · delete Chart v1 · move to `packages/charts` · docsite+second-library support + README · publish + CI.diff --git a/CHARTV2_READINESS.md b/CHARTV2_READINESS.mdnew file mode 100644index 0000000000..81264e9a30--- /dev/null+++ b/CHARTV2_READINESS.md@@ -0,0 +1,91 @@+# @astryxdesign/charts — Launch Readiness Audit++Full inventory of what the package contains today and how ready each piece is to+ship (canary), based on the API audit, the verification checklist, and the Stage 1+fixes already landed on `feat/charts-extraction`. Goal: pick a solid first slice to+ship soon (coordinated with the vega launch), and track the rest as fast-follows.++Readiness legend:++- **Ship-ready** — verified working, fixes landed, low risk for canary.+- **Minor polish** — works; needs 1–2 small fixes and/or a story before it's presentable.+- **Needs work** — architectural gap or unverified interaction; not for the first slice.++Bar for "ready" = canary quality: works, looks right in light + dark, reasonable API,+has a story. (Not full stable/a11y bar — that's later.)++---++## Marks (12)++| Mark | What it is | Readiness | Notes / blockers |+| ------------------ | ----------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------- |+| `bar` | Bars: simple/stacked/grouped/grouped-stacked/negative | **Ship-ready** | All variants verified L+D; `_uid` + color fixes landed |+| `line` | Line series (curves, optional dots) | **Ship-ready** | Edge-clip + headroom fixed |+| `area` | Area fill (+gradient, stacked) | **Ship-ready** | Gradient-id collision fixed |+| `dot` | SVG scatter | **Ship-ready** | `dodge` implemented; story added |+| `band` | Confidence-interval band | Minor polish | Utility (no legend); translucent fill washes out in dark |+| `candlestick` | OHLC financial | Minor polish | Semantic default colors now; not in legend by default; tooltip shows only the `open` value |+| `errorBar` | Whisker/error bars | Minor polish | Utility; dark custom color (#1e3a5f) washes out on dark |+| `referenceLine` | Annotation line/band at fixed x or y | Minor polish | Label clamp fixed; needs solo stories; `x` only on linear scale |+| `dotGL` | WebGL scatter (large N) | Minor polish | Works; hex-only color (not palette/token integrated) |+| `streamGL` | WebGL streaming line (imperative push) | Minor polish | Renders now with a domain window; niche; needs a documented usage pattern |+| `dotGLInteractive` | WebGL scatter + GPU-picking hover | **Needs work** | Hover interaction never exercised by a story / unverified |+| `heatmapGL` | WebGL 2D heatmap | **Needs work** | Builds its own categorical y-scale (breaks the shared-scale rule); top-row clip; hex ramp isn't token-aware |++## Chrome (6)++| Component | What it is | Readiness | Notes / blockers |+| -------------- | ---------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------- |+| `Chart` | Root: layout, scales, domains, clip, palette, events | **Ship-ready** | Strong; domains/baseline/streaming/palette all landed |+| `ChartAxis` | Axes (ticks, formatters, density) | **Ship-ready** | Label auto-density fixed; time axis + top/right/`showTicks` combos less tested (minor) |+| `ChartGrid` | Grid lines (h/v) | **Ship-ready** | — |+| `ChartLegend` | Legend (positions, alignment) | **Ship-ready** | Accessor/auto-color series now appear |+| `ChartSwatch` | Color swatch primitive | **Ship-ready** | Component fine; story under-demonstrates (cosmetic) |+| `ChartTooltip` | Grouped hover tooltip + crosshair | Minor polish | Core works but hover interaction isn't screenshot-verified; value semantics wrong for candlestick/streamGL/GL |++## Utilities++| Util | Readiness | Notes |+| ------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------- |+| `useChartColors` / `getChartColors` (palette) | **Ship-ready** | Solid; resolves the `--color-data-*` tokens (which are JS-only, not CSS vars) |+| `currency` formatter | **Ship-ready** | Verified on an axis |+| `percent` / `compactNumber` / `shortDate` / `monthYear` | Minor polish | Not yet verified in a story |++---++## Recommended first slice (ship to canary next week, with vega)++Everything in this set is **Ship-ready** and covers the "few basic charts" people+have been asking for:++- **Marks:** `bar`, `line`, `area`, `dot`+- **Chrome:** `Chart`, `ChartAxis`, `ChartGrid`, `ChartLegend`, `ChartSwatch`, `ChartTooltip`*+- **Utilities:** the color palette + `currency`++\* Tooltip's static rendering is fine; before shipping, do one pass of hover+verification (it's the one interaction we haven't screenshot-tested).++**Stretch (nice for a compelling demo, small effort):** `candlestick` — a strong+financial showcase; just needs the legend/tooltip-value polish. And confirm the+remaining formatters render.++To actually ship this slice, the remaining work is small:++1. Verify tooltip hover (Playwright-drive a hover) — the last unverified interaction.+2. Confirm `percent`/date formatters in a story.+3. Wire `/charts` into the docsite (add as a dep, fill the empty `.doc.mjs` files) so it appears in docs.+4. Final light+dark screenshot pass of the slice.++## Fast-follows (after the first slice)++- `heatmapGL` categorical-y shared-scale fix (the architectural exception).+- `dotGLInteractive` hover story + verification.+- Mode-aware translucent fills so bands/error bars read in dark mode.+- Tooltip value semantics for candlestick (OHLC) / streamGL / GL marks.+- `dotGL` palette/token color integration.+- Time scale + date-axis formatting.+- `referenceLine` solo stories; edge-case stories (empty/single/all-zero/outlier).+- Tests (unit + export-surface + SSR) and a11y pass.+- Cross-chart interactivity broker — owned by indigo; keep `Chart`'s container+ context + pointer stream clean as the integration seam.diff --git a/CHARTV2_STAGE1_DESIGN.md b/CHARTV2_STAGE1_DESIGN.mdnew file mode 100644index 0000000000..e1c66a28ae--- /dev/null+++ b/CHARTV2_STAGE1_DESIGN.md@@ -0,0 +1,396 @@+# ChartV2 Stage 1 — Design & Correctness Research++Deep design work for the "make it correct + a genuinely good API" stage. This is the+thinking behind Stage 1 of the plan (the package-extraction is a separate, mechanical+stage). Goal: decide what a great, hard-to-regret chart API looks like before we lock+it by publishing. Companion to `CHARTV2_PHASE1_PLAN.md` (findings/evidence) and the+plan panel (sequencing).++Status: research + proposals. Owner decisions needed in section 8.++---++## 0. TL;DR++- The core architecture — **marks are factory functions returning config; the chart+ owns one x/y scale; marks resolve() then render()** — is the modern, correct choice.+ It matches Observable Plot (the best-in-class "marks + shared scale" design) and the+ series-array model of MUI X / Plotly / Highcharts. We should keep it.+- The **API surface is inconsistent** in ~25 concrete ways (color has 5 shapes,+ `size` vs `radius`, `upper/lower` vs `high/low`, positional vs options-only, label+ only on 4 marks, GL marks can't take theme colors, etc.). This is where most of the+ design effort goes.+- The **single highest-leverage idea** is to adopt a **channel/encoding model** (a+ visual property can be a constant, a field name, or an accessor) uniformly across+ color/size/opacity. It collapses most inconsistencies into one coherent concept and+ fixes the accessor-color + legend problems as a side effect.+- The **color tokens are good** (10 categorical + 9 sequential ramps + neutral) and v1+ already has a strong palette API to adopt. Real gaps: auto-assignment, GL can't use+ tokens, categorical tokens are identical in light/dark, CVD-safety unverified.+- The biggest **correctness** gaps are scale-related: no time scale, no log scale,+ degenerate domains (single point / zero range / empty), and no honest baseline/clip+ (already in the plan). Plus a long failure-mode matrix (section 5).++---++## 1. Where ChartV2 sits in the charting-library landscape++There are four broad API families. Understanding them tells us which lessons to borrow.++- **Compositional / JSX children** — Recharts, Victory, visx.+ `<LineChart data><Line dataKey="x"/><XAxis/></LineChart>`. Discoverable and+ React-idiomatic, but scales are hard to coordinate, perf suffers with many nodes,+ and cross-mark consistency is manual. **This is exactly Chart v1's model** — and the+ reason v2 exists.+- **Per-chart-type config monolith** — Nivo, Chart.js, (partly) Tremor.+ `<ResponsiveLine data={...} big-prop-bag/>`. Fast for the common case; poor at mixing+ mark types (bar + line + band on one chart) and at composition.+- **Grammar of graphics / marks** — Observable Plot, Vega-Lite, AntV G2.+ `Plot.plot({marks:[Plot.barY(data,{x,y,fill}), Plot.lineY(...)]})`. Marks are+ functions/objects; the plot owns scales; every visual property is a **channel**.+ Best-in-class for correctness and composition; slightly higher concept count.+- **Series array config** — MUI X Charts, Plotly, Highcharts, ECharts.+ `series={[{type:'bar', data...}, {type:'line', ...}]}`, axes configured separately,+ multiple named axes for dual-scale. Pragmatic, very common in dashboards.++**ChartV2 is a hybrid of the best two:** Observable-Plot-style marks (`bar(...)`,+`line(...)` returning config) fed through a MUI-style `series={[...]}` array, with a+single shared scale. That is a strong, defensible foundation. Verdict: **keep the+architecture; fix the API surface and add the missing scale capabilities.**++What the best-in-class do that we currently don't:++1. **Uniform channels** (Plot/Vega-Lite): color/size/opacity accept constant | field |+ accessor everywhere. (We do this only for `bar`/`dot` color.)+2. **First-class, configurable scales** (all of MUI/ECharts/Plot): x/y (and color/size)+ scale _type_ and options are explicit and overridable. We infer linear-or-band from+ data and expose nothing.+3. **Time scale** (everyone). We have none — financial/streaming fake it with band+ strings or raw numbers. (`ScaleTime` is imported in the axis types but the root+ never builds one.)+4. **Multiple / secondary axes** (MUI/ECharts/Highcharts/Plotly/Chart.js) for dual-unit+ charts (price vs volume). We force one shared y — which is why the financial+ composite looks broken.+5. **CVD-safe default categorical palette** (Vega/Plot ship tableau10-like sets). Ours+ is close in spirit; needs verification.+6. (Out of scope, noting for completeness) **faceting / small multiples**.++---++## 2. The encoding / channel model (the biggest single API decision)++### The problem, concretely++From the API audit, "how do I set a visual property" is spelled many ways:++- color: `ColorAccessor` (bar/dot) | `string` (line/area/band/errorBar/referenceLine)+ | required `string` (dotGL/dotGLInteractive/streamGL) | `string[]` ramp (heatmapGL)+ | `upColor/downColor` pair (candlestick). Five shapes.+- "size of a point": `radius` (dot, a radius) vs `size` (dotGL, a diameter).+- opacity: `opacity` (most) vs `bandOpacity` (referenceLine) vs none (line/candlestick).++### The proposal: one `Channel<T>` concept++Borrow Observable Plot's channels. A visual property accepts one of three things:++```ts+type Channel<T> =+ | T // constant: color: '#0171E3' or a token+ | {field: string} // read a data column (maps via a scale)+ | ((datum: Row, index: number) => T); // accessor+```++Apply it uniformly to the properties that vary per-datum or per-series: `color`+(fill/stroke), `size`/`r`, `opacity`. Then:++- `bar('rev', {color: '#...'})` still works (constant).+- `bar('rev', {color: d => d.up ? green : red})` works (accessor) — and shows in the+ legend (section 3).+- `dot('y', {color: {field: 'category'}})` maps a column through the color scale+ (categorical) — the thing you actually want for scatter-by-category, which is+ currently impossible.++This single concept replaces C3/C8/C9/C14 from the audit and unlocks+color-by-field (a common, currently-missing capability). It is additive: constants+(today's usage) keep working.++Scope note: we do NOT need the full Vega-Lite type system (quantitative/ordinal/+temporal). Channels + a small set of explicit scales (section 4) is the right amount+of power for this library.++---++## 3. Color system (deep dive)++### What we have (good foundation)++Tokens (`packages/core/src/theme/domainTokens/dataTokens.ts`):++- **10 categorical**: blue, orange, purple, green, pink, cyan, red, teal, brown,+ indigo. (Tableau10-like — distinct hues for distinct series.)+- **9 sequential ramps × 5 steps** (5=darkest → 1=lightest): blue, shamrock, orange,+ pink, purple, red, teal, yellow, gray. For ordered/quantitative (heatmaps, choropleth).+- **1 neutral** (labels, reference lines, empty states).++v1's palette API (`getChartColors`/`useChartColors`) already exposes: `categorical(n)`,+`sequential[hue](n)`, `diverging.positiveNegative/coldHot/custom`, `semantic`+(positive/negative/warning/neutral), `structural` (axis/grid/tick/label), `alpha()`.+This is a genuinely good API — **adopt it wholesale** into the charts package.++### The problems to fix++1. **Broken defaults.** Marks default to `--color-chart-1` / `--color-positive` /+ `--color-negative`, none of which exist → black/invisible. Fix by **auto-assigning+ the categorical palette by series index at the chart root** (mark default color =+ "auto"; the root fills unset colors via `categorical(n)`). Candlestick up/down and+ errorBar/referenceLine default to `semantic`/`structural` from the palette.+2. **GL marks can't use tokens.** `hexToGL` does `parseInt(hex,16)` — a CSS var or+ `rgb()` becomes `NaN` (silent mis-render), which is why GL color is required-hex.+ Fix: resolve any CSS color (token/var/named/rgb) to concrete RGB before GL upload —+ via the theme resolver (we already have `token(name)`) and/or a canvas+ `getComputedStyle` fallback. Then GL marks accept the same colors as SVG marks and+ can auto-assign from the palette too.+3. **Accessor colors vanish from the legend.** `deriveLegendItems` drops any series+ whose `color` isn't a static string. With channels, a series has a _resolved_+ representative color (the assigned categorical slot, or the accessor sampled at a+ stable point, or — for color-by-field — a small scale the legend can enumerate).+ Legend should show it.+4. **Dark mode.** The categorical tokens are identical in light and dark+ (`light-dark(#0171E3, #0171E3)`). They're mid-tones chosen to read on both, and our+ screenshot pass shows them working — but this is a deliberate design point to+ confirm, not an accident. The **sequential ramps** include very dark steps+ (`#02165E`) that will lose contrast on the dark body; heatmaps/areas using low ramp+ steps need checking in dark mode.+5. **CVD (color-blind) safety.** The 10 categorical are tableau10-like but not verified+ for deuteranopia/protanopia/tritanopia. Add a verification task; document a+ recommended max distinct series (~8) before hues get hard to distinguish.+6. **Too many series.** Decide behavior past 10 categorical: recycle with a pattern/+ opacity shift, or warn. (Plot warns; ECharts recycles.) Recommend: recycle + dev+ warning.++### Color scale (new, small)++Introduce an explicit **color scale** at the root for `color: {field}` usage:++- categorical field → `categorical(n)` by distinct value (ordinal color scale).+- quantitative field → a sequential ramp (choose hue).+- diverging → `diverging.*` around a midpoint.+ This is what makes color-by-field coherent and legendable.++---++## 4. Scales — the correctness foundation++### Current state++`computeLayout` builds **either** `scaleLinear` (numeric x) **or** `scaleBand` (else)+for x, and always `scaleLinear` for y with domain `[min,max].nice()` (+ zero-inclusion+only if a bar/area is present). No configuration is exposed. Consequences:++- Endpoints glue to edges; monotone curves overshoot outside the plot (no clip).+- Empty data → band branch → `NaN` positions → streaming renders nothing.+- No time scale; no log scale; no per-axis control.++### Proposal++1. **Domain/baseline parity** (already planned): `yBaseline: 'auto'|'zero'|'data'`,+ `yDomain`, `xDomain` — authoritative when provided (no `.nice()`), mirroring v1.+ Add a plot **clipPath** and small **headroom** for continuous-only charts.+2. **Degenerate-domain handling** (correctness): single point / zero range / all-equal+ → synthesize a sensible span (e.g., `v±1` or `[0, v*2]`) so the mark is visible and+ ticks are sane; empty + explicit domain → honor the domain (fixes streaming).+3. **Explicit scale config** (new, optional): allow the caller to set x/y scale _type_+ and options rather than pure inference:+ ```+ xScale={{type: 'time'}} // or 'linear' | 'band' | 'log'+ yScale={{type: 'log', domain: [1, 1e6], nice: true}}+ ```+ Inference stays the default. This is how MUI/ECharts/Plot all work and it removes a+ class of "it guessed wrong" bugs.+4. **Time scale** (fills a real gap): `scaleTime` for Date x-values; the axis already+ references `ScaleTime`. Enables honest financial/streaming time axes and good tick+ formatting (via the ported `shortDate`/`monthYear`).+5. **Secondary y-axis** (resolves the financial-composite problem): allow a mark to+ target a secondary y-scale (e.g., `bar('volume', {axis: 'y2'})`) with its own+ domain, like MUI's `yAxisId` / Plotly's `y2`. This is the principled fix for+ price-vs-volume rather than crushing one series. Decision needed (section 8) —+ it's powerful but adds surface; could be deferred to a follow-on if we instead+ document "don't mix incompatible units on one axis."++Design tension to be explicit about: **one shared scale is the whole value prop**+(marks can't disagree). Secondary axes are the _sanctioned_ exception, opt-in and+explicit, not automatic — preserving the guarantee for the default case.++---++## 5. Everything that can go wrong (failure-mode matrix)++For each: what happens today → what should happen. Drives Stage 1 fixes + Stage 2 tests.++### Data pathologies++- **Empty `data=[]`** → band scale, NaN, blank (breaks streaming). → honor explicit+ domain; otherwise render an empty-state (axes + "no data").+- **Single datum** → zero-width/near-degenerate domain. → synthesize span; center the point.+- **All values equal / zero range** → flat domain, `nice()` may collapse ticks. → pad domain.+- **All zero / all negative** → baseline handling (bars grow wrong way?). → verified by+ new edge-case stories; `yBaseline` correctness.+- **One huge outlier** → everything else squashed. → document log scale option; outlier+ is legitimate but the story should show the log remedy.+- **NaN / null / undefined / non-numeric in a numeric column** → currently coerced to 0+ silently (misleading). → skip (gap in line/area path) vs 0; decide + document. Prefer+ gap for line/area, skip point for dot.+- **Missing dataKey** (typo) → silent 0/undefined everywhere. → dev warning.+- **Duplicate x values** (band) / **unsorted x** (line) → band de-dupes silently; line+ draws zig-zag. → dev warning for unsorted line x.+- **Very large N** (10k+ SVG nodes) → jank. → GL marks exist; document thresholds;+ (m4 downsampling is a tracked follow-on).++### Scale / rendering++- **Overshoot outside plot** (monotone/natural curves) → escapes into margins. → clipPath.+- **Axis label overflow / overlap** (many band categories; long labels; big numbers) →+ candlestick smear today. → width-aware auto-skip + rotation/truncation option.+- **Tooltip at viewport edges** → can clip. → flip/clamp (partly handled; verify).+- **Legend overflow** (many series) → wrap/scroll; `legend="end"` currently clips the plot.+- **Reference-line label off-canvas** → clamp badge within plot.++### Runtime / platform++- **SSR / no DOM** (Next.js) → ResizeObserver/canvas/`window` access. → guard; render+ nothing or a placeholder until mounted. (Docsite is Next.js — this matters.)+- **WebGL unavailable / context loss** → GL marks blank. → fallback message or SVG path;+ handle `webglcontextlost`.+- **Canvas / listener cleanup** (streaming rAF, ring buffer, ResizeObserver) → leaks. →+ audit teardown.+- **High-DPI** → blurriness. → DPR handling exists in webgl utils; verify across marks.+- **Theme switch at runtime** → colors must re-resolve (esp. GL, which caches hex). →+ re-upload on theme change.+- **Reduced motion** → axis has `animated`; honor `prefers-reduced-motion`.++### Accessibility++- **Screen readers** → SVG has title/desc on root only; series/points aren't described.+ → at least role/aria-label; consider a data-table fallback (Highcharts/visx pattern).+- **Keyboard** → no keyboard access to tooltip/points. → follow-on, but note it.+- **Contrast** → structural (axis/grid/label) and series colors vs both backgrounds.++### i18n / formatting++- **Number/date/locale** → formatters exist (`currency`/`percent`/`compactNumber`/+ `shortDate`/`monthYear`); ensure locale-aware and ported into the package.+- **RTL** → axis sides, legend order, tooltip placement.++---++## 6. Per-mark API consistency pass (proposed normalization)++Target: a predictable surface where the same concept has the same name/shape everywhere.+(Full current-state evidence in the audit; this is the proposed end-state.)++- **Data input:** every data-bound mark takes a positional primary key where it has an+ obvious "primary" (`bar/line/dot/area/dotGL/dotGLInteractive`); multi-field marks stay+ options-only (`band/candlestick/errorBar/heatmapGL`) but use **consistent field+ names**.+- **Bounds naming:** unify the interval concept. Pick one vocabulary for+ `band`/`errorBar` (they're twins): recommend `high`/`low` (matches candlestick/finance)+ or `upper`/`lower` — one, not both. `referenceLine` keeps `y`/`y2` (they're values,+ not fields) but document the distinction.+- **Color:** one `Channel<Color>` everywhere (section 2); default = auto palette;+ candlestick uses `{up, down}` as a documented special case (or `color:{up,down}`).+- **Size:** standardize on one meaning. Recommend `radius` (SVG semantics) everywhere+ points are round; if we keep GL `size` as diameter, document the 2× relationship or+ convert so `radius` means radius for both.+- **Stroke:** `strokeWidth` everywhere (retire `lineWidth` on streamGL); expose the+ currently-hardcoded strokes (area top line, candlestick wick, line-dots radius).+- **Opacity:** `opacity` everywhere (retire `bandOpacity`; referenceLine band uses+ `fillOpacity` or nested `band:{opacity}`).+- **Curve:** export one shared `CurveType`; expose `curve` on area (and band?) using it.+- **label:** every non-utility mark accepts `label` and sets `SeriesDef.label` so legend/+ tooltip are correct; referenceLine's `label` is the badge (document the difference).+- **key/identity:** semantic `key` + layout-assigned `_uid` (planned) so duplicate+ dataKeys and two streams/refs don't collide.+- **x-scale requirements in types:** encode band-vs-linear-vs-time requirements so the+ compiler catches "heatmap on a linear x" instead of a silent null (via typed mark+ variants or a runtime dev warning at minimum).+- **De-dupe:** share the `xPixel` helper (every mark reinvents the band/linear px math);+ share `ColorAccessor`/`Channel` types (currently duplicated in bar/dot, unexported).+- **Tooltip semantics:** fix value derivation (candlestick shows only `open`; streamGL+ yields `undefined`; GL scatter creates chrome-tooltip rows). Decide per-mark what a+ tooltip row means, or let marks declare their tooltip contribution.++---++## 7. What is genuinely good (keep, don't churn)++- The marks + one-shared-scale architecture; `resolve()`/`render()` split; "root has+ zero knowledge of mark types."+- The `series={[...]}` config ergonomics; `legend`/`tooltip` as boolean-or-config props.+- Composable chrome primitives (`ChartSwatch`, standalone `ChartLegend`, `ChartAxis`+ toggles for line/ticks/grid).+- The pointer-event model (single capture rect → subscribers; tooltip re-renders only+ on index change).+- v1's palette API design and the token set.+- WebGL marks for scale (scatter/heatmap/stream) — a real differentiator vs Recharts/Nivo.+- Dark mode already works across the SVG marks.++---++## 8. Design decisions — DECIDED (recommended defaults; vetoable)++These meaningfully change scope/shape. Owner is new to charting and delegated these to+the recommended, industry-standard calls; each is reversible and open to veto by the+owner or by Ruby Cheung in the Stage-4 design review. Ranked by leverage.++1. **Channel model — ADOPTED.** `color`/`size`/`opacity` accept+ `constant | {field} | accessor` uniformly across marks. It's the backbone that makes+ the API coherent and unlocks color-by-field. (Bigger refactor of mark options, worth it.)+2. **Secondary y-axis — DESIGN NOW, implement if time allows.** Provide an opt-in+ `axis:'y2'` for dual-unit charts (price/volume); it also informs heatmap categorical-y.+ If it slips, document "one scale — don't mix units" and defer implementation to a+ follow-on. The default stays one shared scale (the core guarantee).+3. **Scales — parity + time + degenerate now; log if cheap.** Do `yBaseline`/`yDomain`/+ `xDomain` parity + clip + headroom + degenerate-domain handling + a time scale ++ explicit scale config this stage. Add explicit `type:'log'` if inexpensive, else+ follow-on.+4. **Null/NaN policy — DECIDED: gap + skip + dev warning.** Line/area break the path at+ null/NaN (gap); point marks skip the point; emit a dev-only warning. No silent+ coerce-to-zero.+5. **Bounds vocabulary — DECIDED: `high`/`low`.** Use `high`/`low` for both `band` and+ `errorBar` (matches candlestick/finance). `referenceLine` keeps `y`/`y2` (values, not+ fields), documented.+6. **Beyond-10 series — DECIDED: recycle + dev warning.** Reuse the categorical palette+ past 10 series and warn in dev; recommend a practical max of ~8 distinct hues.+7. **A11y target — DECIDED: minimum now.** Root aria/title/desc + per-series labels this+ stage; keyboard nav and a data-table fallback are a tracked follow-on.++Additional call recorded here: 8. **CVD-safety — verify, don't redesign.** Keep the existing categorical tokens; add a+verification pass (deuter/protan/tritan) and document findings rather than inventing a+new palette this stage.++---++## 9. Testing implications (feeds Stage 2)++- **Unit**: scale/domain (auto, baseline modes, explicit, empty, single, zero-range,+ time), channel resolution (constant/field/accessor), palette resolver + token→hex,+ legend/tooltip derivation (incl. accessor + color-by-field), `_uid` uniqueness,+ formatters, each mark factory's `SeriesDef` shape.+- **Failure-mode fixtures**: one dataset per row in section 5, asserted to not throw and+ to produce sane output.+- **Export-surface test**: the barrel + package aliases export the full contract.+- **Visual**: Playwright screenshots of every story in light + dark (existing harness),+ including the new edge-case and channel/color-by-field stories.+- **SSR smoke**: render to string without a DOM (guards Next.js/docsite usage).++---++## Appendix — source references++- Tokens: `packages/core/src/theme/domainTokens/dataTokens.ts`+- Palette API (to adopt): `packages/lab/src/Chart/getChartColors.ts`, `useChartColors.ts`+- GL color (hex-only): `packages/lab/src/Chart/webgl.ts` `hexToGL`+- Shared x helper (underused): `packages/lab/src/Chart/utils.ts` `xPixel`+- Domain/baseline parity reference: `packages/lab/src/Chart/Chart.tsx`+- Full API audit + inconsistency list: this session's catalog (mirrored into+ `CHARTV2_PHASE1_PLAN.md` findings).diff --git a/CHARTV2_VERIFICATION_CHECKLIST.md b/CHARTV2_VERIFICATION_CHECKLIST.mdnew file mode 100644index 0000000000..220069bc86--- /dev/null+++ b/CHARTV2_VERIFICATION_CHECKLIST.md@@ -0,0 +1,294 @@+# ChartV2 — Verification Checklist++Exhaustive, specific things to verify before we call the chart library "correct." This+is the QA backbone for Stage 1 (fixes) and Stage 2 (tests). It combines (a) what the+screenshot pass already checked and (b) everything still untested.++Status legend:++- `[ok]` verified acceptable in the light+dark screenshot review of all 21 stories+- `[BUG]` confirmed problem (tracked in Stage 1)+- `[?]` not yet verified — needs a check and/or a dedicated story+- `[new]` needs a new story/fixture to even exercise it++How we verify:++- **Visual**: Playwright screenshot harness over every story, light + dark (existing).+- **Unit**: vitest on layout/scales/color/legend/tooltip/formatters.+- **Manual**: hover/keyboard/resize interactions Playwright can drive.+- **SSR**: render-to-string smoke test.++---++## 1. Axes ("are all axes good?")++### Positions & structure++- `[ok]` Bottom axis renders a baseline line; labels centered under band categories.+- `[ok]` Left axis renders as floating labels (no line, no ticks) by default.+- `[?]` Confirm the floating y-axis (no line/no ticks by default) is the INTENDED default+ look vs. drawing a subtle axis line/ticks. (Design call — looks Google-Sheets clean.)+- `[?]` Right axis (`position="right"`) — placement, label anchor (start), used for+ secondary-axis story. `[new]`+- `[?]` Top axis (`position="top"`) — label placement above plot. `[new]`+- `[?]` `showAxisLine` / `showTicks` toggles in every combination (line-only,+ line+ticks, ticks force line on). `[new]` dedicated story.++### Ticks & density++- `[BUG]` Band axis with many categories overlaps into a smear (candlestick, 30 days).+ Needs width-aware auto-skip without requiring `maxTicks`.+- `[?]` `tickCount` respected for linear axes (d3 picks "nice" counts near it).+- `[?]` `maxTicks` evenly skips labels when exceeded (verify the every-Nth logic).+- `[?]` Long category labels — truncation (`truncate`) appends "…"; consider rotation.+- `[new]` Rotated labels option for dense/long band labels (currently none).+- `[?]` First/last linear tick not clipped at plot edges (edge visibility guard exists —+ offset within [-10, width+10]).+- `[?]` Gridlines align exactly with axis tick positions (grid uses `yScale.ticks(5)`;+ axis uses `tickCount=5` — confirm they match when `tickCount` changes).++### Domains reflected in axis++- `[ok]` Negative y domain: bottom axis line drawn at y=0, not chart edge (NegativeValues).+- `[ok]` Currency formatter on left axis ($ values) renders (SimpleBar).+- `[?]` Percent / compactNumber / shortDate / monthYear formatters on axes. `[new]`+- `[BUG]` Continuous y (line/area/dot) glues min/max to top/bottom edges (no headroom).+- `[new]` Time axis: Date x-values with sensible date ticks + formatting (no time scale today).+- `[new]` Log axis: decade ticks (1,10,100…) (no log scale today).+- `[?]` Zero-range / single-value domain: axis still shows sane ticks (not all same).++### Axis appearance++- `[ok]` Axis label text color adapts in dark mode (secondary text token).+- `[?]` Axis line / tick contrast on both light and dark bodies.+- `[?]` RTL: left/right axis sides + label anchors mirror. `[new]`+- `[?]` Streaming: axis tick slide animation (`animated`) is smooth and honors+ reduced-motion. `[new]`++---++## 2. Scales & domains++- `[BUG]` Empty data → band fallback → NaN → blank (breaks streaming).+- `[BUG]` No `yBaseline`/`yDomain`/`xDomain` control (v1 parity).+- `[new]` Single datum → domain must synthesize a span; point centered/visible.+- `[new]` All-equal / zero-range values → padded domain, sane ticks.+- `[new]` All zero → baseline correct, bars flat at 0.+- `[new]` All negative → bars grow downward from 0; axis line at 0 (top).+- `[new]` One huge outlier → document/log remedy; linear still not throwing.+- `[?]` `nice()` behavior: applied for auto domains, NOT for explicit domains (avoid+ ratcheting during zoom/stream).+- `[?]` x numeric vs band inference correctness (all-number → linear; else band).+- `[new]` Explicit scale config (`type: 'linear'|'band'|'time'|'log'`) overrides inference.+- `[new]` Secondary y-axis (`axis:'y2'`) maps a mark to its own domain (financial).+- `[?]` Stacked domain = sum of stack (verified visually on StackedBars/Areas); unit-test it.+- `[?]` Mixed positive/negative stacks compute correct extents.++---++## 3. Colors & palette ("colors?")++### Palette correctness++- `[BUG]` Default color tokens (`--color-chart-1`, `--color-positive/negative`) don't+ exist → black/invisible when no color passed. Fix: auto-assign categorical by index.+- `[?]` `categorical(n)` returns distinct hues in series order; matches legend swatches.+- `[?]` `sequential[hue](n)` ramp ordering (dark→light) for heatmaps/choropleth.+- `[?]` `diverging.positiveNegative/coldHot/custom` around a midpoint.+- `[?]` `semantic` (positive/negative/warning/neutral) drive candlestick up/down,+ reference lines, error bars (not raw tokens).+- `[?]` `structural` (axis/grid/tick/label) used by chrome, theme-aware.+- `[?]` `alpha(hex, o)` produces correct rgba.++### Dark mode & contrast++- `[ok]` Solid SVG marks (bar/line/area-line/dot) and GL scatter dots read with good+ contrast on the dark body (reviewed: bars, line, scatter, candlestick, heatmap).+- `[BUG]` **Translucent / dark-hued fills wash out on dark — broad.** Reviewed in dark:+ confidence bands (opacity 0.1–0.2) nearly invisible; kitchen-sink reference bands+ (amber 0.15 / green 0.08) go muddy; area-gradient fill very dark; **error bars+ (`#1e3a5f`) nearly invisible on dark bars**; financial volume bars (gray 0.3) muddy.+ Root cause: colors/opacities are chosen for a light background (often hardcoded hex),+ not mode-aware. Fix at the palette/semantic level (mode-aware fill base + opacity;+ error-bar/structural defaults from theme tokens, not hex).+- `[ok]` Categorical mid-tones read acceptably on dark for the ones exercised (blue/red/+ orange/green). Still `[?]` for the full 10 (cyan/teal/brown/indigo/purple/pink) on dark.+- `[ok]` Heatmap sequential ramp low-end (near-white) reads fine on dark (high contrast);+ BUT note it's a story-supplied hex range, not a theme token (see below).+- `[note]` **Heatmap `colorRange` and candlestick up/down colors are story-supplied hex,+ not theme tokens** → they don't adapt to light/dark. Consider defaulting heatmap to a+ sequential-ramp token set and candlestick to `semantic.positive/negative`.+- `[new]` CVD (color-blind) safety pass on the 10 categorical (deuter/protan/tritan);+ document a recommended max (~8) distinct series.++### Color application++- `[BUG]` Accessor-colored series vanish from the legend.+- `[new]` Color-by-field (`color:{field}`) → ordinal color scale + legend entries.+- `[BUG]` GL marks can't take tokens (`hexToGL` is hex-only) — need token→hex resolver.+- `[?]` Theme switch at runtime re-resolves colors, including cached GL hex.+- `[new]` >10 series → palette recycles + dev warning.+- `[?]` Opacity: stacked/overlapping fills (area 0.3, band 0.15) composite correctly.+- `[?]` Gradient fill (area `gradient`) stops from color→transparent; unique per series+ (gradient id collision when two areas share a dataKey → dedupe via `_uid`).+- `[?]` Swatch color exactly matches the rendered series color (square for bar, line else).+- `[BUG-story]` The Swatch story renders only a single square — it under-demonstrates+ (no `line` variant, no multiple colors, no dark comparison). Expand the story.++---++## 4. Legend++- `[ok]` Standalone legend renders items with swatches + labels (Legend story).+- `[ok]` Positions top/bottom (horizontal wrap) and start/end (vertical stack).+- `[BUG]` `legend="end"` shrinks the plot but the last bar/label clips (MixedMarks).+- `[?]` Alignment start/center/end within position.+- `[?]` Utility marks (band/errorBar/referenceLine) correctly EXCLUDED from legend.+- `[BUG]` Marks with no `SeriesDef.color` (candlestick/GL) excluded — after color fix,+ decide which should appear (candlestick up/down? GL series?).+- `[new]` Many-series legend overflow (wrap/scroll), long labels.+- `[?]` Legend swatch variant matches mark type (bar=square, others=line).+- `[?]` Duplicate labels don't collide as React keys (legend keys on `label`).++---++## 5. Tooltip & hover (largely UNTESTED — screenshots are static)++- `[?]` Hover shows crosshair for line/area/dot; band-highlight rect for bars.+- `[?]` Tooltip card content: correct series rows, labels, colors, values at hovered x.+- `[BUG-latent]` Tooltip value = `datum[dataKeys[0]]`: candlestick shows only `open`;+ streamGL yields `undefined`; GL scatter creates rows. Fix per-mark tooltip semantics.+- `[?]` Hover dots render for line/area/dot at the focused index; skipped for bars/utility.+- `[?]` Card flips/clamps near viewport edges (placement auto/left/right/top).+- `[?]` Re-render only on data-index change (perf) — verify no per-move React renders.+- `[?]` Tooltip in dark mode (popover bg, text, swatch).+- `[?]` `dotGLInteractive` GPU-picking hover fires its own `renderTooltip`; ensure it+ doesn't double up with the chrome tooltip.+- `[new]` Empty/pointer-leave clears the card and indicator.+- `[?]` Touch/pointer on mobile (touch-action) — no scroll interference.++---++## 6. Grid++- `[ok]` Horizontal grid default; aligns with y ticks; skips the y=0 line.+- `[?]` Vertical grid (`vertical`) for band (per category) and linear (ticks).+- `[?]` Grid contrast in dark mode (border-emphasized token).+- `[?]` Grid behind marks (render order) — never over data.++---++## 7. Per-mark rendering (all 12)++- `[ok]` `bar` — simple/stacked/grouped/grouped-stacked/negative; rounded top corners;+ corner radius only on stack top.+- `[ok]` `line` — curves (monotone default); optional dots (hardcoded r=3 — expose?).+- `[ok]` `area` — fill + gradient + stacked; top stroke.+- `[?]` `dot` (SVG scatter) — no dedicated story yet. `[new]`+- `[BUG]` `dot.dodge` — declared, does nothing.+- `[ok]` `band` — confidence interval between upper/lower.+- `[ok]` `candlestick` — up/down bodies + wicks; min body height.+- `[ok]` `errorBar` — stem + caps.+- `[ok]` `referenceLine` — single y, y+y2 band, x line (need solo stories). `[new]`+- `[BUG]` `referenceLine` label badge clips at right edge (Acceptable/Target).+- `[ok]` `dotGL` — WebGL scatter (200 pts).+- `[new]` `dotGLInteractive` — hover/picking not exercised by a story.+- `[BUG]` `heatmapGL` — builds its own y scale; top row clips; should share chart scale.+- `[BUG]` `streamGL` — blank (empty-data scale); hardcoded key collides for two streams.+- `[?]` Marks with x-scale requirements fail gracefully on the wrong scale+ (heatmap needs band; referenceLine.x needs linear; streamGL needs numeric).+- `[BUG]` Two series on the same dataKey collide (resolved map + React key) — dup-key.++---++## 8. Layout & responsiveness++- `[ok]` Title/subtitle render above chart; aria wired to `<title>`/`<desc>`.+- `[?]` Responsive width via ResizeObserver — resize from wide→narrow re-lays-out.+- `[?]` Container width 0 (initial mount) renders a placeholder, no crash.+- `[?]` Very small container (e.g. 150px) — axes/labels degrade gracefully.+- `[?]` `margin` overrides — insets applied; enough room for long axis labels.+- `[BUG]` `legend="end"` clips plot (see §4).+- `[?]` Multiple charts on one page don't share/leak ids (gradient/clip ids unique).++---++## 9. Data edge cases (need fixtures — §5 of design doc)++- `[new]` Empty `[]`, single row, two rows.+- `[new]` `null`/`undefined`/`NaN`/non-numeric in a numeric column → gap (line/area) /+ skip (points) + dev warning (per decision).+- `[new]` Missing dataKey (typo) → dev warning, not silent zeros.+- `[new]` Duplicate x values (band); unsorted x (line) → dev warning.+- `[new]` Very large N (5k–50k) → GL path; document SVG thresholds.+- `[new]` Extreme values (1e9, 1e-9) → axis formatting (compactNumber) not overflowing.++---++## 10. Platform / runtime++- `[new]` SSR: render-to-string without DOM (Next.js/docsite) — guarded, no crash.+- `[?]` WebGL unavailable / `webglcontextlost` → GL marks fallback/message, no hard fail.+- `[?]` High-DPI (retina) — GL circles/lines crisp; SVG sharp.+- `[?]` Memory: streaming ring buffer bounded; canvas/ResizeObserver/rAF cleaned up on+ unmount (no leaks over long sessions).+- `[?]` `prefers-reduced-motion` honored (axis slide, any transitions).+- `[?]` Rapid re-render / prop churn — layout memoization stable (no thrash).++---++## 11. Accessibility (minimum target this stage)++- `[?]` Root SVG has role/title/desc; aria-label from title.+- `[new]` Per-series accessible labels (name + type).+- `[new]` Color is not the ONLY channel where it matters (consider patterns/labels).+- `[new]` (Follow-on) keyboard navigation of points/tooltip; data-table fallback.+- `[?]` Focus-visible styles for any interactive elements.++---++## 12. Theming / dark mode++- `[ok]` All 21 stories reviewed in dark mode; chrome + SVG marks adapt.+- `[?]` Non-neutral themes (stone, y2k) — chart colors + structural tokens resolve.+- `[?]` `theme="none"` (base tokens only) — no broken/missing token fallbacks.+- `[?]` Live theme/mode switch mid-session re-resolves everything (incl. GL).++---++## 13. Formatting / i18n++- `[ok]` `currency()` on axis.+- `[?]` `percent`, `compactNumber`, `shortDate`, `monthYear` on axes + tooltip.+- `[?]` Locale-awareness (decimal/grouping separators, date locale).+- `[?]` RTL layout (axes, legend, tooltip placement).++---++## 14. API / type-level verifications++- `[new]` Export-surface test: barrel + package aliases export the full contract+ (option types, `ColorAccessor`/`Channel`, legend/margin/scale/`YBaseline` types).+- `[?]` No mark leaks internal-only fields; `SeriesDef` shape stable across all 12.+- `[?]` Channel type accepts constant | {field} | accessor uniformly (post-refactor).+- `[?]` `_uid` uniqueness across series (incl. dup dataKey, two streams, two ref lines).+- `[?]` Types encode x-scale requirements (or dev-warn) so wrong-scale pairings caught.+- `[?]` Tree-shaking: importing one mark doesn't pull all GL/d3 code.++---++## Current-state summary (from the screenshot pass — light + dark, all 21 stories)++Confirmed working: all bar variants, negative values, area/stacked area, WebGL scatter+(light+dark), heatmap coloring (light+dark), candlestick colors (light+dark), legend,+and dark-mode chrome/solid marks generally.+Confirmed bugs: line/area/dot edge clipping + overshoot; streaming blank; candlestick+axis-label smear (light+dark); financial-composite shared-scale; reference-label clip;+`legend="end"` clip; duplicate-key warning; broken default color tokens; heatmap+top-row clip + own scale; **translucent fills (band/area) wash out on dark**; Swatch+story under-demonstrates.+Design notes: heatmap ramp + candlestick colors are story-supplied hex, not theme+tokens (don't adapt to mode); y-axis is intentionally floating labels (confirm).+Largely untested: all hover/tooltip INTERACTION (screenshots are static), time/log+scales, SSR, WebGL context loss, runtime theme switching, non-neutral themes (stone/y2k),+RTL, a11y, formatters beyond currency, and all data edge cases.diff --git a/apps/docsite/package.json b/apps/docsite/package.jsonindex dea65fc6bc..eedf99d8cb 100644--- a/apps/docsite/package.json+++ b/apps/docsite/package.json@@ -19,6 +19,7 @@"@stylexjs/stylex": "^0.18.3","@vercel/analytics": "^2.0.1","@vercel/speed-insights": "^1.2.0",+ "@astryxdesign/charts": "*","@astryxdesign/cli": "*","@astryxdesign/core": "*","@astryxdesign/theme-butter": "*",diff --git a/apps/sandbox/package.json b/apps/sandbox/package.jsonindex 7bffa09752..4635163b5f 100644--- a/apps/sandbox/package.json+++ b/apps/sandbox/package.json@@ -16,6 +16,7 @@"dependencies": {"@heroicons/react": "^2.2.0","@stylexjs/stylex": "^0.18.3",+ "@astryxdesign/charts": "*","@astryxdesign/cli": "*","@astryxdesign/core": "*","@astryxdesign/lab": "*",diff --git a/apps/storybook/.storybook/main.ts b/apps/storybook/.storybook/main.tsindex fff99c7745..c931c5ac54 100644--- a/apps/storybook/.storybook/main.ts+++ b/apps/storybook/.storybook/main.ts@@ -86,6 +86,12 @@ const config: StorybookConfig = {'@astryxdesign/core': [path.join(rootDir, 'packages/core/src')],'@astryxdesign/lab/*': [path.join(rootDir, 'packages/lab/src/*')],'@astryxdesign/lab': [path.join(rootDir, 'packages/lab/src')],+ '@astryxdesign/charts/*': [+ path.join(rootDir, 'packages/charts/src/*'),+ ],+ '@astryxdesign/charts': [+ path.join(rootDir, 'packages/charts/src'),+ ],'@astryxdesign/theme-neutral/*': [path.join(rootDir, 'packages/themes/neutral/src/*'),],@@ -113,6 +119,7 @@ const config: StorybookConfig = {...config.resolve?.alias,'@astryxdesign/core': path.resolve(rootDir, 'packages/core/src'),'@astryxdesign/lab': path.resolve(rootDir, 'packages/lab/src'),+ '@astryxdesign/charts': path.resolve(rootDir, 'packages/charts/src'),'@astryxdesign/theme-neutral': path.resolve(rootDir,'packages/themes/neutral/src/source.ts',diff --git a/apps/storybook/package.json b/apps/storybook/package.jsonindex c7d7584c5b..489388b679 100644--- a/apps/storybook/package.json+++ b/apps/storybook/package.json@@ -8,6 +8,7 @@"typecheck": "tsc --noEmit"},"dependencies": {+ "@astryxdesign/charts": "*","@astryxdesign/core": "*","@astryxdesign/lab": "*","@astryxdesign/theme-neutral": "*",diff --git a/apps/storybook/stories/ChartV2.stories.tsx b/apps/storybook/stories/ChartV2.stories.tsxdeleted file mode 100644index 7005d60bbc..0000000000--- a/apps/storybook/stories/ChartV2.stories.tsx+++ /dev/null@@ -1,261 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--import type {Meta, StoryObj} from '@storybook/react';-import {ChartV2 as Chart, bar, line, area} from '@astryxdesign/lab';-import {- ChartV2Grid as ChartGrid,- ChartV2Axis as ChartAxis,- currency,-} from '@astryxdesign/lab';--const meta: Meta<typeof Chart> = {- title: 'Lab/ChartV2',- component: Chart,-};-export default meta;--const monthlyData = [- {month: 'Jan', revenue: 45, costs: 30, trend: 38},- {month: 'Feb', revenue: 52, costs: 35, trend: 42},- {month: 'Mar', revenue: 48, costs: 32, trend: 40},- {month: 'Apr', revenue: 61, costs: 38, trend: 48},- {month: 'May', revenue: 55, costs: 34, trend: 45},- {month: 'Jun', revenue: 70, costs: 40, trend: 52},-];--const groupedStackData = [- {month: 'Jan', revenueA: 30, costsA: 15, revenueB: 25, costsB: 20},- {month: 'Feb', revenueA: 35, costsA: 18, revenueB: 28, costsB: 22},- {month: 'Mar', revenueA: 28, costsA: 14, revenueB: 32, costsB: 18},- {month: 'Apr', revenueA: 42, costsA: 20, revenueB: 35, costsB: 25},- {month: 'May', revenueA: 38, costsA: 17, revenueB: 30, costsB: 21},- {month: 'Jun', revenueA: 50, costsA: 22, revenueB: 40, costsB: 28},-];--/** Simple bar chart */-export const SimpleBar: StoryObj = {- render: () => (- <Chart- data={monthlyData}- xKey="month"- title="Monthly Revenue"- series={[bar('revenue', {color: '#3b82f6'})]}- tooltip={true}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" tickFormat={currency()} />- </>- }- height={300}- />- ),-};--/** Simple line chart */-export const SimpleLine: StoryObj = {- render: () => (- <Chart- data={monthlyData}- xKey="month"- series={[line('trend', {color: '#3b82f6'})]}- tooltip={true}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={300}- />- ),-};--/** Stacked bars */-export const StackedBars: StoryObj = {- render: () => (- <Chart- data={monthlyData}- xKey="month"- title="Revenue & Costs"- subtitle="Stacked by category"- series={[- bar('revenue', {color: '#3b82f6', stack: 'totals', label: 'Revenue'}),- bar('costs', {color: '#ef4444', stack: 'totals', label: 'Costs'}),- ]}- legend={{position: 'bottom', alignment: 'center'}}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={300}- />- ),-};--/** Grouped bars */-export const GroupedBars: StoryObj = {- render: () => (- <Chart- data={monthlyData}- xKey="month"- title="Revenue vs Costs"- series={[- bar('revenue', {color: '#3b82f6', group: 'compare', label: 'Revenue'}),- bar('costs', {color: '#ef4444', group: 'compare', label: 'Costs'}),- ]}- legend={{position: 'top', alignment: 'end'}}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={300}- />- ),-};--/** Grouped stacked bars — two stacks side by side per x value */-export const GroupedStackedBars: StoryObj = {- render: () => (- <Chart- data={groupedStackData}- xKey="month"- series={[- // Stack A (left bar in each group)- bar('revenueA', {- color: '#3b82f6',- stack: 'stackA',- group: 'comparison',- }),- bar('costsA', {color: '#93c5fd', stack: 'stackA', group: 'comparison'}),- // Stack B (right bar in each group)- bar('revenueB', {- color: '#ef4444',- stack: 'stackB',- group: 'comparison',- }),- bar('costsB', {color: '#fca5a5', stack: 'stackB', group: 'comparison'}),- ]}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={300}- />- ),-};--/** Mixed: bars + line */-export const MixedMarks: StoryObj = {- render: () => (- <Chart- data={monthlyData}- xKey="month"- title="Revenue vs Trend"- subtitle="Bar chart with trendline overlay"- series={[- bar('revenue', {color: '#3b82f6', label: 'Revenue'}),- line('trend', {color: '#f59e0b', label: 'Trend'}),- ]}- tooltip={true}- legend={{position: 'end', alignment: 'start'}}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={300}- />- ),-};--/** Area with gradient */-export const AreaGradient: StoryObj = {- render: () => (- <Chart- data={monthlyData}- xKey="month"- title="Revenue Over Time"- series={[- area('revenue', {color: '#3b82f6', gradient: true}),- line('revenue', {color: '#3b82f6'}),- ]}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={300}- />- ),-};--/** Stacked areas */-export const StackedAreas: StoryObj = {- render: () => (- <Chart- data={monthlyData}- xKey="month"- title="Revenue & Costs Over Time"- series={[- area('revenue', {color: '#3b82f6', stack: 'total', label: 'Revenue'}),- area('costs', {color: '#ef4444', stack: 'total', label: 'Costs'}),- ]}- legend={true}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={300}- />- ),-};--const profitLossData = [- {month: 'Jan', profit: 20, trend: 15},- {month: 'Feb', profit: -10, trend: 5},- {month: 'Mar', profit: 35, trend: 20},- {month: 'Apr', profit: -25, trend: -5},- {month: 'May', profit: 15, trend: 10},- {month: 'Jun', profit: -5, trend: 8},-];--/** Mixed marks with negative values */-export const NegativeValues: StoryObj = {- render: () => (- <Chart- data={profitLossData}- xKey="month"- series={[- bar('profit', {color: '#3b82f6'}),- line('trend', {color: '#f59e0b', dots: true, strokeWidth: 2}),- ]}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={300}- />- ),-};diff --git a/apps/storybook/stories/ChartV2Advanced.stories.tsx b/apps/storybook/stories/ChartV2Advanced.stories.tsxdeleted file mode 100644index a4bbfd8809..0000000000--- a/apps/storybook/stories/ChartV2Advanced.stories.tsx+++ /dev/null@@ -1,369 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--import type {Meta, StoryObj} from '@storybook/react';-import {useMemo, useRef, useEffect, type MutableRefObject} from 'react';-import {- ChartV2 as Chart,- bar,- line,- band,- candlestick,- errorBar,- referenceLine,- dotGL,- heatmapGL,- streamGL,- type StreamGLHandle,-} from '@astryxdesign/lab';-import {- ChartV2Grid as ChartGrid,- ChartV2Axis as ChartAxis,-} from '@astryxdesign/lab';--const meta: Meta<typeof Chart> = {- title: 'Lab/ChartV2Advanced',- component: Chart,-};-export default meta;--// ─── Data ──────────────────────────────────────────────────────────────────--const stockData = Array.from({length: 30}, (_, i) => {- const base = 100 + Math.sin(i / 5) * 20 + i * 0.5;- const open = base + (Math.random() - 0.5) * 8;- const close = base + (Math.random() - 0.5) * 8;- return {- day: `Day ${i + 1}`,- open: Math.round(open * 10) / 10,- close: Math.round(close * 10) / 10,- high:- Math.round(Math.max(open, close, base + Math.random() * 10) * 10) / 10,- low: Math.round(Math.min(open, close, base - Math.random() * 10) * 10) / 10,- volume: Math.round(500 + Math.random() * 1000),- };-});--const predictionData = Array.from({length: 20}, (_, i) => {- const x = i;- const mean = 30 + i * 2 + Math.sin(i / 3) * 5;- return {- x,- mean: Math.round(mean * 10) / 10,- upper95: Math.round((mean + 8 + i * 0.3) * 10) / 10,- lower95: Math.round((mean - 8 - i * 0.3) * 10) / 10,- upper80: Math.round((mean + 4 + i * 0.15) * 10) / 10,- lower80: Math.round((mean - 4 - i * 0.15) * 10) / 10,- };-});--const salesData = [- {month: 'Jan', sales: 45, target: 50, errorHigh: 48, errorLow: 42},- {month: 'Feb', sales: 52, target: 50, errorHigh: 56, errorLow: 48},- {month: 'Mar', sales: 48, target: 50, errorHigh: 52, errorLow: 44},- {month: 'Apr', sales: 61, target: 50, errorHigh: 66, errorLow: 56},- {month: 'May', sales: 55, target: 50, errorHigh: 59, errorLow: 51},- {month: 'Jun', sales: 70, target: 50, errorHigh: 76, errorLow: 64},-];--const scatterData = Array.from({length: 200}, _ => ({- x: Math.random() * 100,- y: Math.random() * 100,-}));--const heatmapData: Record<string, unknown>[] = [];-const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];-for (const day of days) {- for (let hour = 0; hour < 24; hour++) {- heatmapData.push({- hour: `${hour}`,- day,- traffic: Math.round(- 50 +- Math.sin(hour / 4) * 30 +- (day === 'Sat' || day === 'Sun' ? -20 : 10) +- Math.random() * 20,- ),- });- }-}--// ─── Stories ───────────────────────────────────────────────────────────────--/** Candlestick chart */-export const Candlestick: StoryObj = {- render: () => (- <Chart- data={stockData}- xKey="day"- series={[- candlestick({- open: 'open',- high: 'high',- low: 'low',- close: 'close',- upColor: '#22c55e',- downColor: '#ef4444',- }),- ]}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={350}- />- ),-};--/** Candlestick + MA line + volume bars */-export const FinancialComposite: StoryObj = {- name: 'Financial (Candlestick + MA + Volume)',- render: () => {- const data = useMemo(() => {- let sum = 0;- return stockData.map((d, i) => {- sum += d.close;- return {- ...d,- ma5:- i >= 4- ? Math.round(- ((sum -- stockData- .slice(0, i - 4)- .reduce((s, v) => s + v.close, 0)) /- 5) *- 10,- ) / 10- : undefined,- };- });- }, []);- return (- <Chart- data={data}- xKey="day"- series={[- candlestick({- open: 'open',- high: 'high',- low: 'low',- close: 'close',- upColor: '#22c55e',- downColor: '#ef4444',- }),- line('ma5', {color: '#f59e0b', strokeWidth: 1.5}),- bar('volume', {color: '#94a3b8', opacity: 0.3}),- ]}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={400}- />- );- },-};--/** Confidence bands (80% + 95%) */-export const ConfidenceBands: StoryObj = {- render: () => (- <Chart- data={predictionData}- xKey="x"- series={[- band({- upper: 'upper95',- lower: 'lower95',- color: '#3b82f6',- opacity: 0.1,- }),- band({- upper: 'upper80',- lower: 'lower80',- color: '#3b82f6',- opacity: 0.2,- }),- line('mean', {color: '#3b82f6', strokeWidth: 2}),- ]}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={300}- />- ),-};--/** Error bars on bar chart + reference line */-export const ErrorBarsWithTarget: StoryObj = {- name: 'Error Bars + Reference Line',- render: () => (- <Chart- data={salesData}- xKey="month"- series={[- bar('sales', {color: '#3b82f6'}),- errorBar({high: 'errorHigh', low: 'errorLow', color: '#1e3a5f'}),- referenceLine({y: 50, label: 'Target', color: '#ef4444'}),- referenceLine({- y: 40,- y2: 60,- label: 'Acceptable',- color: '#22c55e',- bandOpacity: 0.1,- }),- ]}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={300}- />- ),-};--/** WebGL scatter — 200 points */-export const WebGLScatter: StoryObj = {- name: 'WebGL Scatter (dotGL)',- render: () => (- <Chart- data={scatterData}- xKey="x"- series={[dotGL('y', {color: '#3b82f6', size: 4})]}- grid={<ChartGrid horizontal vertical />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={400}- />- ),-};--/** WebGL heatmap — traffic by hour × day */-export const WebGLHeatmap: StoryObj = {- name: 'WebGL Heatmap',- render: () => (- <Chart- data={heatmapData}- xKey="hour"- series={[- heatmapGL({- xKey: 'hour',- yKey: 'day',- valueKey: 'traffic',- colorRange: ['#eff6ff', '#1e40af'],- }),- ]}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={280}- />- ),-};--/** Streaming line — real-time data */-export const StreamingLine: StoryObj = {- name: 'Streaming (streamGL)',- render: () => {- const handleRef = useRef<StreamGLHandle | null>(- null,- ) as MutableRefObject<StreamGLHandle | null>;- useEffect(() => {- let t = 0;- const interval = setInterval(() => {- handleRef.current?.push(- t,- 50 + Math.sin(t / 10) * 30 + Math.random() * 10,- );- t++;- }, 200);- return () => clearInterval(interval);- }, []);-- return (- <Chart- data={[]}- xKey="x"- series={[streamGL({handleRef, color: '#3b82f6'})]}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={300}- />- );- },-};--/** Mixed: bars with error bars, line, reference line, confidence band */-export const KitchenSink: StoryObj = {- name: 'Kitchen Sink',- render: () => {- const data = salesData.map((d, i, arr) => ({- ...d,- runAvg:- Math.round(- (arr.slice(0, i + 1).reduce((s, v) => s + v.sales, 0) / (i + 1)) * 10,- ) / 10,- upper:- Math.round(- (arr.slice(0, i + 1).reduce((s, v) => s + v.sales, 0) / (i + 1) + 8) *- 10,- ) / 10,- lower:- Math.round(- (arr.slice(0, i + 1).reduce((s, v) => s + v.sales, 0) / (i + 1) - 8) *- 10,- ) / 10,- }));- return (- <Chart- data={data}- xKey="month"- series={[- referenceLine({y: 40, y2: 60, color: '#22c55e', bandOpacity: 0.08}),- referenceLine({y: 50, label: 'Target', color: '#ef4444'}),- band({- upper: 'upper',- lower: 'lower',- color: '#f59e0b',- opacity: 0.15,- }),- bar('sales', {color: '#3b82f6'}),- errorBar({high: 'errorHigh', low: 'errorLow', color: '#1e3a5f'}),- line('runAvg', {color: '#f59e0b', strokeWidth: 2}),- ]}- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" />- </>- }- height={400}- />- );- },-};diff --git a/apps/storybook/stories/ChartV2Legend.stories.tsx b/apps/storybook/stories/ChartV2Legend.stories.tsxdeleted file mode 100644index 9d855ebd71..0000000000--- a/apps/storybook/stories/ChartV2Legend.stories.tsx+++ /dev/null@@ -1,37 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--import type {Meta, StoryObj} from '@storybook/react';-import {ChartV2Legend} from '@astryxdesign/lab';--const sampleItems = [- {label: 'Revenue', color: '#3b82f6', type: 'bar'},- {label: 'Costs', color: '#ef4444', type: 'bar'},- {label: 'Trend', color: '#f59e0b', type: 'line'},-];--const meta: Meta<typeof ChartV2Legend> = {- title: 'Lab/ChartV2Legend',- component: ChartV2Legend,- argTypes: {- position: {- control: 'inline-radio',- options: ['top', 'bottom', 'start', 'end'],- },- alignment: {- control: 'inline-radio',- options: ['start', 'center', 'end'],- },- items: {table: {disable: true}},- },- args: {- items: sampleItems,- alignment: 'start',- },- render: args => <ChartV2Legend {...args} />,-};-export default meta;--/** Standalone chart legend. Use the Controls panel to switch position and alignment. */-export const Legend: StoryObj = {- args: {position: 'bottom'},-};diff --git a/apps/storybook/stories/ChartV2Swatch.stories.tsx b/apps/storybook/stories/ChartV2Swatch.stories.tsxdeleted file mode 100644index 6a954f0978..0000000000--- a/apps/storybook/stories/ChartV2Swatch.stories.tsx+++ /dev/null@@ -1,24 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--import type {Meta, StoryObj} from '@storybook/react';-import {ChartV2Swatch} from '@astryxdesign/lab';--const meta: Meta<typeof ChartV2Swatch> = {- title: 'Lab/ChartV2Swatch',- component: ChartV2Swatch,- argTypes: {- color: {control: 'color'},- variant: {- control: 'inline-radio',- options: ['square', 'line'],- },- },- args: {- color: '#3b82f6',- variant: 'square',- },-};-export default meta;--/** Color swatch primitive — square for bar series, line for line/dot/area and any other non-bar mark. */-export const Swatch: StoryObj = {};diff --git a/apps/storybook/stories/ChartV2Tooltip.stories.tsx b/apps/storybook/stories/ChartV2Tooltip.stories.tsxdeleted file mode 100644index 51441b1695..0000000000--- a/apps/storybook/stories/ChartV2Tooltip.stories.tsx+++ /dev/null@@ -1,49 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--import type {Meta, StoryObj} from '@storybook/react';-import {ChartV2 as Chart, bar, line} from '@astryxdesign/lab';-import {- ChartV2Grid as ChartGrid,- ChartV2Axis as ChartAxis,- currency,-} from '@astryxdesign/lab';--const meta: Meta = {- title: 'Lab/ChartV2Tooltip',-};-export default meta;--const monthlyData = [- {month: 'Jan', revenue: 45, costs: 30, trend: 38},- {month: 'Feb', revenue: 52, costs: 35, trend: 42},- {month: 'Mar', revenue: 48, costs: 32, trend: 40},- {month: 'Apr', revenue: 61, costs: 38, trend: 48},- {month: 'May', revenue: 55, costs: 34, trend: 45},- {month: 'Jun', revenue: 70, costs: 40, trend: 52},-];--const series = [- bar('revenue', {color: '#3b82f6', label: 'Revenue'}),- bar('costs', {color: '#ef4444', label: 'Costs'}),- line('trend', {color: '#f59e0b', label: 'Trend'}),-];--/** Hover over the chart to see the grouped tooltip with all series values at the hovered x-position. */-export const Tooltip: StoryObj = {- render: () => (- <Chart- data={monthlyData}- xKey="month"- series={series}- tooltip- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" tickFormat={currency()} />- </>- }- height={300}- />- ),-};diff --git a/apps/storybook/stories/charts/Area.stories.tsx b/apps/storybook/stories/charts/Area.stories.tsxnew file mode 100644index 0000000000..01f804c0f0--- /dev/null+++ b/apps/storybook/stories/charts/Area.stories.tsx@@ -0,0 +1,53 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {Chart, area, line, ChartGrid, ChartAxis} from '@astryxdesign/charts';+import {monthlyData} from './_data';++const meta: Meta<typeof Chart> = {+ title: 'Charts/Area',+ component: Chart,+};+export default meta;++const axes = (+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" />+ </>+);++export const Gradient: StoryObj = {+ render: () => (+ <Chart+ data={monthlyData}+ xKey="month"+ title="Revenue over time"+ series={[+ area('revenue', {color: '#3b82f6', gradient: true}),+ line('revenue', {color: '#3b82f6'}),+ ]}+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ ),+};++export const Stacked: StoryObj = {+ render: () => (+ <Chart+ data={monthlyData}+ xKey="month"+ title="Revenue & Costs"+ series={[+ area('revenue', {color: '#3b82f6', stack: 'total', label: 'Revenue'}),+ area('costs', {color: '#ef4444', stack: 'total', label: 'Costs'}),+ ]}+ legend+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ ),+};diff --git a/apps/storybook/stories/ChartV2Grid.stories.tsx b/apps/storybook/stories/charts/AxesAndGrids.stories.tsxsimilarity index 52%rename from apps/storybook/stories/ChartV2Grid.stories.tsxrename to apps/storybook/stories/charts/AxesAndGrids.stories.tsxindex 5e7af9e06c..d3a0ef2477 100644--- a/apps/storybook/stories/ChartV2Grid.stories.tsx+++ b/apps/storybook/stories/charts/AxesAndGrids.stories.tsx@@ -1,27 +1,19 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import type {Meta, StoryObj} from '@storybook/react';-import {ChartV2 as Chart, bar} from '@astryxdesign/lab';-import {- ChartV2Grid as ChartGrid,- ChartV2Axis as ChartAxis,-} from '@astryxdesign/lab';+import {Chart, bar, ChartGrid, ChartAxis} from '@astryxdesign/charts';+import {monthlyData} from './_data';-interface AxesAndGridsArgs {- /** Show horizontal grid lines */+interface Args {horizontalGrid: boolean;- /** Show vertical grid lines */verticalGrid: boolean;- /** Show the bottom (x) axis edge line */bottomAxisLine: boolean;- /** Show the left (y) axis edge line */leftAxisLine: boolean;- /** Show perpendicular tick marks on both axes */showTicks: boolean;}-const meta: Meta<AxesAndGridsArgs> = {- title: 'Lab/Chart v2/Primitives/Axes & Grids',+const meta: Meta<Args> = {+ title: 'Charts/Chrome/Axes & Grids',argTypes: {horizontalGrid: {control: 'boolean'},verticalGrid: {control: 'boolean'},@@ -39,26 +31,8 @@ const meta: Meta<AxesAndGridsArgs> = {};export default meta;-const monthlyData = [- {month: 'Jan', revenue: 45},- {month: 'Feb', revenue: 52},- {month: 'Mar', revenue: 48},- {month: 'Apr', revenue: 61},- {month: 'May', revenue: 55},- {month: 'Jun', revenue: 70},-];--/**- * Toggle grid lines, axis edge lines, and tick marks independently.- *- * - Grid lines use `--color-border-emphasized`; the y=0 / domain axis line- * uses `--color-icon-primary`.- * - The bottom axis edge line is on by default; the left/top/right are off.- * - When showing vertical grid lines, enable `leftAxisLine` so the grid- * has a clear left edge to anchor against.- */-export const AxesAndGrids: StoryObj<AxesAndGridsArgs> = {- name: 'Axes & Grids',+/** Toggle grid lines, axis edge lines, and tick marks independently. */+export const Playground: StoryObj<Args> = {render: args => (<Chartdata={monthlyData}diff --git a/apps/storybook/stories/charts/Band.stories.tsx b/apps/storybook/stories/charts/Band.stories.tsxnew file mode 100644index 0000000000..044f4740ac--- /dev/null+++ b/apps/storybook/stories/charts/Band.stories.tsx@@ -0,0 +1,45 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {Chart, band, line, ChartGrid, ChartAxis} from '@astryxdesign/charts';+import {predictionData} from './_data';++const meta: Meta<typeof Chart> = {+ title: 'Charts/Band',+ component: Chart,+};+export default meta;++/** Confidence bands (80% + 95%) around a forecast line. */+export const ConfidenceBands: StoryObj = {+ render: () => (+ <Chart+ data={predictionData}+ xKey="x"+ title="Forecast with confidence bands"+ series={[+ band({+ upper: 'upper95',+ lower: 'lower95',+ color: '#3b82f6',+ opacity: 0.12,+ }),+ band({+ upper: 'upper80',+ lower: 'lower80',+ color: '#3b82f6',+ opacity: 0.22,+ }),+ line('mean', {color: '#3b82f6', strokeWidth: 2}),+ ]}+ grid={<ChartGrid />}+ axes={+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" />+ </>+ }+ height={320}+ />+ ),+};diff --git a/apps/storybook/stories/charts/Bar.stories.tsx b/apps/storybook/stories/charts/Bar.stories.tsxnew file mode 100644index 0000000000..9c5bfd6327--- /dev/null+++ b/apps/storybook/stories/charts/Bar.stories.tsx@@ -0,0 +1,108 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {Chart, bar, ChartGrid, ChartAxis, currency} from '@astryxdesign/charts';+import {monthlyData, groupedStackData, profitLossData} from './_data';++const meta: Meta<typeof Chart> = {+ title: 'Charts/Bar',+ component: Chart,+};+export default meta;++const axes = (+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" />+ </>+);++export const Simple: StoryObj = {+ render: () => (+ <Chart+ data={monthlyData}+ xKey="month"+ title="Monthly Revenue"+ series={[bar('revenue', {color: '#3b82f6'})]}+ tooltip+ grid={<ChartGrid />}+ axes={+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" tickFormat={currency()} />+ </>+ }+ height={300}+ />+ ),+};++export const Stacked: StoryObj = {+ render: () => (+ <Chart+ data={monthlyData}+ xKey="month"+ title="Revenue & Costs"+ subtitle="Stacked by category"+ series={[+ bar('revenue', {color: '#3b82f6', stack: 'totals', label: 'Revenue'}),+ bar('costs', {color: '#ef4444', stack: 'totals', label: 'Costs'}),+ ]}+ legend={{position: 'bottom', alignment: 'center'}}+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ ),+};++export const Grouped: StoryObj = {+ render: () => (+ <Chart+ data={monthlyData}+ xKey="month"+ title="Revenue vs Costs"+ series={[+ bar('revenue', {color: '#3b82f6', group: 'compare', label: 'Revenue'}),+ bar('costs', {color: '#ef4444', group: 'compare', label: 'Costs'}),+ ]}+ legend={{position: 'top', alignment: 'end'}}+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ ),+};++export const GroupedStacked: StoryObj = {+ render: () => (+ <Chart+ data={groupedStackData}+ xKey="month"+ title="Grouped + stacked"+ series={[+ bar('revenueA', {color: '#3b82f6', stack: 'a', group: 'cmp'}),+ bar('costsA', {color: '#93c5fd', stack: 'a', group: 'cmp'}),+ bar('revenueB', {color: '#ef4444', stack: 'b', group: 'cmp'}),+ bar('costsB', {color: '#fca5a5', stack: 'b', group: 'cmp'}),+ ]}+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ ),+};++export const NegativeValues: StoryObj = {+ render: () => (+ <Chart+ data={profitLossData}+ xKey="month"+ title="Profit / Loss"+ series={[bar('profit', {color: '#3b82f6'})]}+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ ),+};diff --git a/apps/storybook/stories/charts/Candlestick.stories.tsx b/apps/storybook/stories/charts/Candlestick.stories.tsxnew file mode 100644index 0000000000..f3f94374ad--- /dev/null+++ b/apps/storybook/stories/charts/Candlestick.stories.tsx@@ -0,0 +1,75 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {useMemo} from 'react';+import {+ Chart,+ candlestick,+ line,+ ChartGrid,+ ChartAxis,+} from '@astryxdesign/charts';+import {stockData} from './_data';++const meta: Meta<typeof Chart> = {+ title: 'Charts/Candlestick',+ component: Chart,+};+export default meta;++const axes = (+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" />+ </>+);++/** OHLC candlesticks. Up/down default to the theme's success/error colors. */+export const Basic: StoryObj = {+ render: () => (+ <Chart+ data={stockData}+ xKey="day"+ title="Price (OHLC)"+ series={[+ candlestick({open: 'open', high: 'high', low: 'low', close: 'close'}),+ ]}+ grid={<ChartGrid />}+ axes={axes}+ height={360}+ />+ ),+};++/** Candlesticks + a moving-average line overlay on the shared price scale. */+export const WithMovingAverage: StoryObj = {+ render: () => {+ const data = useMemo(() => {+ let sum = 0;+ return stockData.map((d, i) => {+ sum += d.close;+ const ma =+ i >= 4+ ? (sum -+ stockData.slice(0, i - 4).reduce((s, v) => s + v.close, 0)) /+ 5+ : undefined;+ return {...d, ma5: ma == null ? undefined : Math.round(ma * 10) / 10};+ });+ }, []);+ return (+ <Chart+ data={data}+ xKey="day"+ title="Price + 5-day MA"+ series={[+ candlestick({open: 'open', high: 'high', low: 'low', close: 'close'}),+ line('ma5', {color: '#f59e0b', strokeWidth: 1.5}),+ ]}+ grid={<ChartGrid />}+ axes={axes}+ height={360}+ />+ );+ },+};diff --git a/apps/storybook/stories/charts/Color.stories.tsx b/apps/storybook/stories/charts/Color.stories.tsxnew file mode 100644index 0000000000..3479fa3aef--- /dev/null+++ b/apps/storybook/stories/charts/Color.stories.tsx@@ -0,0 +1,63 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {Chart, bar, line, ChartGrid, ChartAxis} from '@astryxdesign/charts';+import {monthlyData, profitLossData} from './_data';++const meta: Meta<typeof Chart> = {+ title: 'Charts/Color',+ component: Chart,+};+export default meta;++const axes = (+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" />+ </>+);++/** No colors passed — the chart assigns distinct colors from the theme palette. */+export const AutoPalette: StoryObj = {+ render: () => (+ <Chart+ data={monthlyData}+ xKey="month"+ title="Auto palette"+ subtitle="No colors passed — assigned from the theme's categorical palette"+ series={[+ bar('revenue', {group: 'g'}),+ bar('costs', {group: 'g'}),+ line('trend'),+ ]}+ legend+ grid={<ChartGrid />}+ axes={axes}+ height={320}+ />+ ),+};++/** Per-datum color via an accessor; the series still shows in the legend. */+export const AccessorColor: StoryObj = {+ render: () => (+ <Chart+ data={profitLossData}+ xKey="month"+ title="Green when positive, red when negative"+ series={[+ bar('profit', {+ label: 'Profit',+ color: d =>+ (d.profit as number) >= 0+ ? 'var(--color-success)'+ : 'var(--color-error)',+ }),+ ]}+ legend+ grid={<ChartGrid />}+ axes={axes}+ height={320}+ />+ ),+};diff --git a/apps/storybook/stories/charts/Composite.stories.tsx b/apps/storybook/stories/charts/Composite.stories.tsxnew file mode 100644index 0000000000..c6cb4cfd6a--- /dev/null+++ b/apps/storybook/stories/charts/Composite.stories.tsx@@ -0,0 +1,87 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {+ Chart,+ bar,+ line,+ band,+ errorBar,+ referenceLine,+ ChartGrid,+ ChartAxis,+} from '@astryxdesign/charts';+import {monthlyData, salesData} from './_data';++const meta: Meta<typeof Chart> = {+ title: 'Charts/Composite',+ component: Chart,+};+export default meta;++const axes = (+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" />+ </>+);++/** Bars + a trendline overlay sharing one scale. */+export const MixedMarks: StoryObj = {+ render: () => (+ <Chart+ data={monthlyData}+ xKey="month"+ title="Revenue vs trend"+ subtitle="Bars with a trendline overlay"+ series={[+ bar('revenue', {color: '#3b82f6', label: 'Revenue'}),+ line('trend', {color: '#f59e0b', label: 'Trend'}),+ ]}+ tooltip+ legend+ grid={<ChartGrid />}+ axes={axes}+ height={320}+ />+ ),+};++/** Many marks at once: reference band + line, confidence band, bars, error bars, line. */+export const KitchenSink: StoryObj = {+ render: () => {+ const data = salesData.map((d, i, arr) => {+ const avg =+ arr.slice(0, i + 1).reduce((s, v) => s + v.sales, 0) / (i + 1);+ return {+ ...d,+ runAvg: Math.round(avg * 10) / 10,+ upper: Math.round((avg + 8) * 10) / 10,+ lower: Math.round((avg - 8) * 10) / 10,+ };+ });+ return (+ <Chart+ data={data}+ xKey="month"+ title="Kitchen sink"+ series={[+ referenceLine({y: 40, y2: 60, color: '#22c55e', bandOpacity: 0.08}),+ referenceLine({y: 50, label: 'Target', color: '#ef4444'}),+ band({+ upper: 'upper',+ lower: 'lower',+ color: '#f59e0b',+ opacity: 0.15,+ }),+ bar('sales', {color: '#3b82f6', label: 'Sales'}),+ errorBar({high: 'errorHigh', low: 'errorLow', color: '#1e3a5f'}),+ line('runAvg', {color: '#f59e0b', strokeWidth: 2, label: 'Run avg'}),+ ]}+ grid={<ChartGrid />}+ axes={axes}+ height={400}+ />+ );+ },+};diff --git a/apps/storybook/stories/charts/Dot.stories.tsx b/apps/storybook/stories/charts/Dot.stories.tsxnew file mode 100644index 0000000000..e3ae16b069--- /dev/null+++ b/apps/storybook/stories/charts/Dot.stories.tsx@@ -0,0 +1,48 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {Chart, dot, ChartGrid, ChartAxis} from '@astryxdesign/charts';+import {scatterData, stripData} from './_data';++const meta: Meta<typeof Chart> = {+ title: 'Charts/Dot',+ component: Chart,+};+export default meta;++const axes = (+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" />+ </>+);++/** SVG scatter (numeric x/y). For large N (thousands of points) use `dotGL`. */+export const Scatter: StoryObj = {+ render: () => (+ <Chart+ data={scatterData}+ xKey="x"+ title="Scatter (SVG)"+ series={[dot('y', {color: '#3b82f6', radius: 4, opacity: 0.7})]}+ grid={<ChartGrid horizontal vertical />}+ axes={axes}+ height={360}+ />+ ),+};++/** `dodge` spreads points sharing a category so they don't overlap. */+export const Dodged: StoryObj = {+ render: () => (+ <Chart+ data={stripData}+ xKey="group"+ title="Values by group (dodged)"+ series={[dot('value', {dodge: true, radius: 5})]}+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ ),+};diff --git a/apps/storybook/stories/charts/ErrorBar.stories.tsx b/apps/storybook/stories/charts/ErrorBar.stories.tsxnew file mode 100644index 0000000000..956deed506--- /dev/null+++ b/apps/storybook/stories/charts/ErrorBar.stories.tsx@@ -0,0 +1,34 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {Chart, bar, errorBar, ChartGrid, ChartAxis} from '@astryxdesign/charts';+import {salesData} from './_data';++const meta: Meta<typeof Chart> = {+ title: 'Charts/Error Bar',+ component: Chart,+};+export default meta;++/** Error bars pair with a value mark (here, bars) to show a high/low range. */+export const OnBars: StoryObj = {+ render: () => (+ <Chart+ data={salesData}+ xKey="month"+ title="Sales with error bars"+ series={[+ bar('sales', {color: '#3b82f6'}),+ errorBar({high: 'errorHigh', low: 'errorLow', color: '#1e3a5f'}),+ ]}+ grid={<ChartGrid />}+ axes={+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" />+ </>+ }+ height={320}+ />+ ),+};diff --git a/apps/storybook/stories/charts/Legend.stories.tsx b/apps/storybook/stories/charts/Legend.stories.tsxnew file mode 100644index 0000000000..6b4e784629--- /dev/null+++ b/apps/storybook/stories/charts/Legend.stories.tsx@@ -0,0 +1,29 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {ChartLegend} from '@astryxdesign/charts';++const sampleItems = [+ {label: 'Revenue', color: '#3b82f6', type: 'bar'},+ {label: 'Costs', color: '#ef4444', type: 'bar'},+ {label: 'Trend', color: '#f59e0b', type: 'line'},+];++const meta: Meta<typeof ChartLegend> = {+ title: 'Charts/Chrome/Legend',+ component: ChartLegend,+ argTypes: {+ position: {+ control: 'inline-radio',+ options: ['top', 'bottom', 'start', 'end'],+ },+ alignment: {control: 'inline-radio', options: ['start', 'center', 'end']},+ items: {table: {disable: true}},+ },+ args: {items: sampleItems, position: 'bottom', alignment: 'start'},+ render: args => <ChartLegend {...args} />,+};+export default meta;++/** Standalone legend. Swatch shape follows the mark type (square for bar). */+export const Default: StoryObj = {};diff --git a/apps/storybook/stories/charts/Line.stories.tsx b/apps/storybook/stories/charts/Line.stories.tsxnew file mode 100644index 0000000000..de5debb25d--- /dev/null+++ b/apps/storybook/stories/charts/Line.stories.tsx@@ -0,0 +1,83 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {Chart, line, ChartGrid, ChartAxis} from '@astryxdesign/charts';+import {monthlyData} from './_data';++const meta: Meta<typeof Chart> = {+ title: 'Charts/Line',+ component: Chart,+};+export default meta;++const axes = (+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" />+ </>+);++export const Simple: StoryObj = {+ render: () => (+ <Chart+ data={monthlyData}+ xKey="month"+ title="Trend"+ series={[line('trend', {color: '#3b82f6'})]}+ tooltip+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ ),+};++export const WithDots: StoryObj = {+ render: () => (+ <Chart+ data={monthlyData}+ xKey="month"+ series={[line('trend', {color: '#3b82f6', dots: true, strokeWidth: 2})]}+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ ),+};++export const MultiSeries: StoryObj = {+ render: () => (+ <Chart+ data={monthlyData}+ xKey="month"+ series={[+ line('revenue', {color: '#3b82f6', label: 'Revenue'}),+ line('costs', {color: '#ef4444', label: 'Costs'}),+ line('trend', {color: '#f59e0b', label: 'Trend'}),+ ]}+ legend+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ ),+};++export const Curves: StoryObj = {+ render: () => (+ <Chart+ data={monthlyData}+ xKey="month"+ subtitle="linear vs monotone vs step"+ series={[+ line('revenue', {color: '#3b82f6', curve: 'linear', label: 'linear'}),+ line('costs', {color: '#22c55e', curve: 'monotone', label: 'monotone'}),+ line('trend', {color: '#f59e0b', curve: 'step', label: 'step'}),+ ]}+ legend+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ ),+};diff --git a/apps/storybook/stories/charts/ReferenceLine.stories.tsx b/apps/storybook/stories/charts/ReferenceLine.stories.tsxnew file mode 100644index 0000000000..395a71b7e1--- /dev/null+++ b/apps/storybook/stories/charts/ReferenceLine.stories.tsx@@ -0,0 +1,85 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {+ Chart,+ bar,+ line,+ referenceLine,+ ChartGrid,+ ChartAxis,+} from '@astryxdesign/charts';+import {salesData, predictionData} from './_data';++const meta: Meta<typeof Chart> = {+ title: 'Charts/Reference Line',+ component: Chart,+};+export default meta;++const axes = (+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" />+ </>+);++/** A single horizontal reference line at a fixed y value. */+export const Horizontal: StoryObj = {+ render: () => (+ <Chart+ data={salesData}+ xKey="month"+ title="Sales vs target"+ series={[+ bar('sales', {color: '#3b82f6'}),+ referenceLine({y: 50, label: 'Target', color: '#ef4444'}),+ ]}+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ ),+};++/** A shaded band between two y values (y + y2). */+export const Band: StoryObj = {+ render: () => (+ <Chart+ data={salesData}+ xKey="month"+ title="Acceptable range"+ series={[+ bar('sales', {color: '#3b82f6'}),+ referenceLine({+ y: 40,+ y2: 60,+ label: 'Acceptable',+ color: '#22c55e',+ bandOpacity: 0.12,+ }),+ ]}+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ ),+};++/** A vertical reference line at a fixed x value (linear x scale only). */+export const Vertical: StoryObj = {+ render: () => (+ <Chart+ data={predictionData}+ xKey="x"+ title="Event marker"+ series={[+ line('mean', {color: '#3b82f6'}),+ referenceLine({x: 10, label: 'Launch', color: '#6b1efd'}),+ ]}+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ ),+};diff --git a/apps/storybook/stories/charts/Swatch.stories.tsx b/apps/storybook/stories/charts/Swatch.stories.tsxnew file mode 100644index 0000000000..1782cf3424--- /dev/null+++ b/apps/storybook/stories/charts/Swatch.stories.tsx@@ -0,0 +1,45 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {ChartSwatch} from '@astryxdesign/charts';++const meta: Meta<typeof ChartSwatch> = {+ title: 'Charts/Chrome/Swatch',+ component: ChartSwatch,+ argTypes: {+ color: {control: 'color'},+ variant: {control: 'inline-radio', options: ['square', 'line']},+ },+ args: {color: '#3b82f6', variant: 'square'},+};+export default meta;++const COLORS = [+ '#3b82f6',+ '#eb6e00',+ '#6b1efd',+ '#0b991f',+ '#f351c0',+ '#f5394f',+];++/** The color swatch primitive — `square` for bar series, `line` for others. */+export const Gallery: StoryObj = {+ render: () => (+ <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>+ <div style={{display: 'flex', gap: 12, alignItems: 'center'}}>+ {COLORS.map(c => (+ <ChartSwatch key={`sq-${c}`} color={c} variant="square" />+ ))}+ </div>+ <div style={{display: 'flex', gap: 12, alignItems: 'center'}}>+ {COLORS.map(c => (+ <ChartSwatch key={`ln-${c}`} color={c} variant="line" />+ ))}+ </div>+ </div>+ ),+};++/** Interactive single swatch. */+export const Playground: StoryObj = {};diff --git a/apps/storybook/stories/charts/Tooltip.stories.tsx b/apps/storybook/stories/charts/Tooltip.stories.tsxnew file mode 100644index 0000000000..cf01dacf45--- /dev/null+++ b/apps/storybook/stories/charts/Tooltip.stories.tsx@@ -0,0 +1,43 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {+ Chart,+ bar,+ line,+ ChartGrid,+ ChartAxis,+ currency,+} from '@astryxdesign/charts';+import {monthlyData} from './_data';++const meta: Meta<typeof Chart> = {+ title: 'Charts/Chrome/Tooltip',+ component: Chart,+};+export default meta;++/** Hover the chart: a grouped tooltip shows every series value at that x, with a+ * column highlight for bars and hover dots on lines. */+export const Default: StoryObj = {+ render: () => (+ <Chart+ data={monthlyData}+ xKey="month"+ series={[+ bar('revenue', {color: '#3b82f6', label: 'Revenue', stack: 'x'}),+ bar('costs', {color: '#ef4444', label: 'Costs', stack: 'x'}),+ line('trend', {color: '#f59e0b', label: 'Trend'}),+ ]}+ tooltip+ grid={<ChartGrid />}+ axes={+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" tickFormat={currency()} />+ </>+ }+ height={320}+ />+ ),+};diff --git a/apps/storybook/stories/charts/WebGL.stories.tsx b/apps/storybook/stories/charts/WebGL.stories.tsxnew file mode 100644index 0000000000..6c4cfcbac9--- /dev/null+++ b/apps/storybook/stories/charts/WebGL.stories.tsx@@ -0,0 +1,134 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {useRef, useEffect, useState, type MutableRefObject} from 'react';+import {+ Chart,+ dotGL,+ dotGLInteractive,+ heatmapGL,+ streamGL,+ type StreamGLHandle,+ ChartGrid,+ ChartAxis,+} from '@astryxdesign/charts';+import {scatterData, heatmapData} from './_data';++const meta: Meta<typeof Chart> = {+ title: 'Charts/WebGL',+ component: Chart,+};+export default meta;++const axes = (+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" />+ </>+);++/**+ * Static, high-performance GPU scatter (`dotGL`) — one draw call, scales to+ * tens of thousands of points. Intentionally has NO hover/tooltip; for+ * interactivity see "Interactive scatter" below.+ */+export const Scatter: StoryObj = {+ name: 'Scatter — static (high-performance)',+ render: () => (+ <Chart+ data={scatterData}+ xKey="x"+ title="WebGL scatter — static (dotGL)"+ series={[dotGL('y', {color: '#3b82f6', size: 5})]}+ grid={<ChartGrid horizontal vertical />}+ axes={axes}+ height={400}+ />+ ),+};++/**+ * GPU scatter with color-picking hover (`dotGLInteractive`) — hover any point+ * for a highlight + tooltip. O(1) hit detection regardless of point count.+ */+export const InteractiveScatter: StoryObj = {+ name: 'Interactive scatter — hover + tooltip',+ render: () => (+ <Chart+ data={scatterData}+ xKey="x"+ title="WebGL scatter — interactive hover (dotGLInteractive)"+ series={[+ dotGLInteractive('y', {+ color: '#6b1efd',+ size: 6,+ renderTooltip: (d: Record<string, unknown>) => (+ <span>+ x: {Math.round(d.x as number)}, y: {Math.round(d.y as number)}+ </span>+ ),+ }),+ ]}+ grid={<ChartGrid horizontal vertical />}+ axes={axes}+ height={400}+ />+ ),+};++/** GPU heatmap — a 2D grid of colored cells (traffic by hour x day). */+export const Heatmap: StoryObj = {+ render: () => (+ <Chart+ data={heatmapData}+ xKey="hour"+ title="Traffic heatmap"+ series={[+ heatmapGL({+ xKey: 'hour',+ yKey: 'day',+ valueKey: 'traffic',+ colorRange: ['#eff6ff', '#1e40af'],+ }),+ ]}+ axes={axes}+ height={280}+ />+ ),+};++/** Streaming line via an imperative push handle + a sliding domain window. */+export const Streaming: StoryObj = {+ render: () => {+ const handleRef = useRef<StreamGLHandle | null>(+ null,+ ) as MutableRefObject<StreamGLHandle | null>;+ const WINDOW = 60;+ const [windowEnd, setWindowEnd] = useState(WINDOW);+ useEffect(() => {+ let t = 0;+ const interval = setInterval(() => {+ handleRef.current?.push(+ t,+ 50 + Math.sin(t / 10) * 30 + Math.random() * 10,+ );+ t++;+ setWindowEnd(Math.max(WINDOW, t));+ }, 200);+ return () => clearInterval(interval);+ }, []);+ return (+ <Chart+ data={[]}+ xKey="x"+ title="Live stream (streamGL)"+ xDomain={[Math.max(0, windowEnd - WINDOW), windowEnd]}+ yDomain={[0, 100]}+ series={[streamGL({handleRef, color: '#3b82f6'})]}+ grid={<ChartGrid />}+ axes={axes}+ height={300}+ />+ );+ },+};diff --git a/apps/storybook/stories/charts/_data.ts b/apps/storybook/stories/charts/_data.tsnew file mode 100644index 0000000000..3321ae7d6c--- /dev/null+++ b/apps/storybook/stories/charts/_data.ts@@ -0,0 +1,109 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Shared sample datasets for the Charts stories. Not a story file (no `.stories`+ * suffix) so Storybook won't pick it up as a story.+ */++export const monthlyData = [+ {month: 'Jan', revenue: 45, costs: 30, trend: 38},+ {month: 'Feb', revenue: 52, costs: 35, trend: 42},+ {month: 'Mar', revenue: 48, costs: 32, trend: 40},+ {month: 'Apr', revenue: 61, costs: 38, trend: 48},+ {month: 'May', revenue: 55, costs: 34, trend: 45},+ {month: 'Jun', revenue: 70, costs: 40, trend: 52},+];++export const profitLossData = [+ {month: 'Jan', profit: 20, trend: 15},+ {month: 'Feb', profit: -10, trend: 5},+ {month: 'Mar', profit: 35, trend: 20},+ {month: 'Apr', profit: -25, trend: -5},+ {month: 'May', profit: 15, trend: 10},+ {month: 'Jun', profit: -5, trend: 8},+];++export const groupedStackData = [+ {month: 'Jan', revenueA: 30, costsA: 15, revenueB: 25, costsB: 20},+ {month: 'Feb', revenueA: 35, costsA: 18, revenueB: 28, costsB: 22},+ {month: 'Mar', revenueA: 28, costsA: 14, revenueB: 32, costsB: 18},+ {month: 'Apr', revenueA: 42, costsA: 20, revenueB: 35, costsB: 25},+ {month: 'May', revenueA: 38, costsA: 17, revenueB: 30, costsB: 21},+ {month: 'Jun', revenueA: 50, costsA: 22, revenueB: 40, costsB: 28},+];++export const predictionData = Array.from({length: 20}, (_, i) => {+ const mean = 30 + i * 2 + Math.sin(i / 3) * 5;+ return {+ x: i,+ mean: Math.round(mean * 10) / 10,+ upper95: Math.round((mean + 8 + i * 0.3) * 10) / 10,+ lower95: Math.round((mean - 8 - i * 0.3) * 10) / 10,+ upper80: Math.round((mean + 4 + i * 0.15) * 10) / 10,+ lower80: Math.round((mean - 4 - i * 0.15) * 10) / 10,+ };+});++export const salesData = [+ {month: 'Jan', sales: 45, target: 50, errorHigh: 48, errorLow: 42},+ {month: 'Feb', sales: 52, target: 50, errorHigh: 56, errorLow: 48},+ {month: 'Mar', sales: 48, target: 50, errorHigh: 52, errorLow: 44},+ {month: 'Apr', sales: 61, target: 50, errorHigh: 66, errorLow: 56},+ {month: 'May', sales: 55, target: 50, errorHigh: 59, errorLow: 51},+ {month: 'Jun', sales: 70, target: 50, errorHigh: 76, errorLow: 64},+];++export const stockData = Array.from({length: 30}, (_, i) => {+ const base = 100 + Math.sin(i / 5) * 20 + i * 0.5;+ const open = base + (Math.random() - 0.5) * 8;+ const close = base + (Math.random() - 0.5) * 8;+ return {+ day: `Day ${i + 1}`,+ open: Math.round(open * 10) / 10,+ close: Math.round(close * 10) / 10,+ high:+ Math.round(Math.max(open, close, base + Math.random() * 10) * 10) / 10,+ low: Math.round(Math.min(open, close, base - Math.random() * 10) * 10) / 10,+ volume: Math.round(500 + Math.random() * 1000),+ };+});++export const scatterData = Array.from({length: 200}, () => ({+ x: Math.random() * 100,+ y: Math.random() * 100,+}));++export const heatmapData: Record<string, unknown>[] = [];+const HEATMAP_DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];+for (const day of HEATMAP_DAYS) {+ for (let hour = 0; hour < 24; hour++) {+ heatmapData.push({+ hour: `${hour}`,+ day,+ traffic: Math.round(+ 50 ++ Math.sin(hour / 4) * 30 ++ (day === 'Sat' || day === 'Sun' ? -20 : 10) ++ Math.random() * 20,+ ),+ });+ }+}++export const stripData = [+ {group: 'A', value: 12},+ {group: 'A', value: 15},+ {group: 'A', value: 13},+ {group: 'A', value: 16},+ {group: 'A', value: 14},+ {group: 'B', value: 22},+ {group: 'B', value: 20},+ {group: 'B', value: 25},+ {group: 'B', value: 21},+ {group: 'C', value: 17},+ {group: 'C', value: 18},+ {group: 'C', value: 15},+ {group: 'C', value: 19},+ {group: 'C', value: 16},+ {group: 'C', value: 20},+];diff --git a/packages/charts/README.md b/packages/charts/README.mdindex 1bddbe9928..2325ed0799 100644--- a/packages/charts/README.md+++ b/packages/charts/README.md@@ -1,21 +1,41 @@# @astryxdesign/charts-Astryx chart components. This package provides thin, themeable wrappers over a peer charting engine — it owns the design-system surface while leaving the rendering engine as a peer dependency the consumer manages.+Astryx charts — a config-model data visualization library built on d3.-It ships to npm **only under the `@canary` dist-tag** — there is never a stable (`latest`) release yet.+```tsx+import {Chart, bar, line} from '@astryxdesign/charts';-## Status+<Chart data={data} xKey="month" series={[bar('revenue'), line('trend')]} />;+```++Marks are factory functions (`bar`, `line`, `area`, `dot`, `band`, `candlestick`,+`errorBar`, `referenceLine`, and WebGL variants) that return config objects passed+via the `series` prop. The chart root owns **one** x/y scale that every mark, axis,+and grid line reads, so they can never disagree. It consumes `@astryxdesign/core`+theme tokens directly (StyleX build mirrors `@astryxdesign/lab`).-**Bootstrap scaffold.** The package is set up and building but ships no components yet. Add components under `src/` and export them from `src/index.ts`. The StyleX + Astryx-token build setup mirrors `@astryxdesign/lab`, so components can consume `@astryxdesign/core` theme tokens directly.+It ships to npm **only under the `@canary` dist-tag** — there is never a stable+(`latest`) release yet.++> Note: this package is the successor to the experimental `Chart` (formerly+> `ChartV2`) that used to live in `@astryxdesign/lab`; that code has moved here and+> d3 is a direct dependency. (Supersedes the original "thin wrappers over a peer+> engine" framing of the bootstrap scaffold.)++## Status-> When the first component adds StyleX styles, wire up a pre-compiled stylesheet the same way `lab` does: add a `charts` target to `scripts/build-css.mjs`, restore the `build:css` script and the `./charts.css` export in `package.json`, and document the `import '@astryxdesign/charts/charts.css'` step below.+Under active development. The config-model chart and its marks/chrome are in place;+API and visuals are still being refined. See the repo-root `CHARTV2_*` docs for the+plan, design research, and verification checklist.## UsageInside the monorepo (storybook/sandbox), imports resolve via pnpm workspaces:```tsx-import {} from /* ... */ '@astryxdesign/charts';+import {Chart, bar, line, ChartGrid, ChartAxis} from '@astryxdesign/charts';+import '@astryxdesign/core/astryx.css';+import '@astryxdesign/charts/charts.css';```### Trying charts in your own project (canary)diff --git a/packages/charts/package.json b/packages/charts/package.jsonindex fb7d0f4f25..1053e6f407 100644--- a/packages/charts/package.json+++ b/packages/charts/package.json@@ -2,7 +2,7 @@"name": "@astryxdesign/charts","version": "0.1.4","private": true,- "description": "Astryx chart components — thin, themeable wrappers over a peer charting engine. Published to npm only under the @canary dist-tag for early testing; never released as a stable (latest) version.",+ "description": "Astryx charts — a config-model data visualization library (d3-based). Published to npm only under the @canary dist-tag for early testing; never released as a stable (latest) version.","author": "Meta Open Source","license": "MIT","homepage": "https://github.com/facebook/astryx#readme",@@ -39,12 +39,16 @@"source": "./src/index.ts","types": "./dist/index.d.ts","default": "./dist/index.js"+ },+ "./charts.css": {+ "default": "./dist/charts.css"}},"scripts": {"prepack": "pnpm build",- "build": "rm -rf dist && pnpm build:esm && tsc --project tsconfig.build.json",+ "build": "rm -rf dist && pnpm build:esm && tsc --project tsconfig.build.json && pnpm build:css","build:esm": "babel src --out-dir dist --extensions '.ts,.tsx' --out-file-extension '.js' --ignore '**/*.test.ts,**/*.test.tsx,**/__tests__/**,**/*.perf.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css,**/*.css.d.ts' --config-file ./babel.config.js",+ "build:css": "node ../../scripts/build-css.mjs --package charts","dev": "babel src --watch --out-dir dist --extensions '.ts,.tsx' --out-file-extension '.js' --ignore '**/*.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css*' --config-file ./babel.config.js","test": "vitest run --root ../..","test:watch": "vitest --root ../..",@@ -56,5 +60,15 @@"@astryxdesign/core": "0.1.4","react": ">=19.0.0","react-dom": ">=19.0.0"+ },+ "dependencies": {+ "d3-array": "^3.2.4",+ "d3-scale": "^4.0.2",+ "d3-shape": "^3.2.0"+ },+ "devDependencies": {+ "@types/d3-array": "^3.2.2",+ "@types/d3-scale": "^4.0.9",+ "@types/d3-shape": "^3.1.8"}}diff --git a/packages/lab/src/ChartV2/ChartV2.doc.mjs b/packages/charts/src/Chart.doc.mjssimilarity index 77%rename from packages/lab/src/ChartV2/ChartV2.doc.mjsrename to packages/charts/src/Chart.doc.mjsindex c2a8651faf..f2845e86ee 100644--- a/packages/lab/src/ChartV2/ChartV2.doc.mjs+++ b/packages/charts/src/Chart.doc.mjs@@ -3,9 +3,9 @@/** @type {import('../../core/src/docs-types').ComponentDoc} */export const docs = {- name: 'ChartV2',- displayName: 'Chart V2',- group: 'ChartV2',+ name: 'Chart',+ displayName: 'Chart',+ group: 'Charts',category: 'Data Visualization',usage: {diff --git a/packages/lab/src/ChartV2/Chart.tsx b/packages/charts/src/Chart.tsxsimilarity index 71%rename from packages/lab/src/ChartV2/Chart.tsxrename to packages/charts/src/Chart.tsxindex 1660d3fa5b..c7359cdf21 100644--- a/packages/lab/src/ChartV2/Chart.tsx+++ b/packages/charts/src/Chart.tsx@@ -11,6 +11,8 @@* 3. Provides a single event layer for interaction children*/+'use client';+import {type ReactNode,useId,@@ -20,17 +22,18 @@ import {useCallback,useLayoutEffect,} from 'react';-import type {SeriesDef} from './types';-import type {ChartV2Context, ChartMargin, ChartPointerEvent} from './types';+import type {SeriesDef, YBaseline} from './types';+import type {ChartContext, ChartMargin, ChartPointerEvent} from './types';import {computeLayout} from './layout';-import {ChartV2Provider} from './ChartV2Context';-import {ChartProvider} from '../Chart/ChartContext';+import {ChartProvider} from './ChartContext';import {Text} from '@astryxdesign/core';import {VStack, HStack} from '@astryxdesign/core';import * as stylex from '@stylexjs/stylex';import {ChartLegend, type ChartLegendProps} from './ChartLegend';import {deriveLegendItems} from './legend';import {ChartTooltip, type ChartTooltipProps} from './ChartTooltip';+import {useChartColors} from './useChartColors';+import {isUtilityMarkType} from './types';export interface ChartProps {data: Record<string, unknown>[];@@ -38,6 +41,15 @@ export interface ChartProps {series: SeriesDef[];height?: number;margin?: Partial<ChartMargin>;+ /** How the y-domain is derived when `yDomain` is not set. Default `'auto'`. */+ yBaseline?: YBaseline;+ /** Explicit y-domain [min, max]. Authoritative — disables baseline/headroom. */+ yDomain?: [number, number];+ /**+ * Explicit x-domain [min, max] for numeric/linear x. Honored even when `data`+ * is empty (stable streaming window). Ignored for categorical (band) scales.+ */+ xDomain?: [number, number];grid?: ReactNode;axes?: ReactNode;legend?: boolean | ChartLegendProps;@@ -70,6 +82,9 @@ export function Chart({series,height = 300,margin: marginOverride,+ yBaseline,+ yDomain,+ xDomain,grid,axes,legend,@@ -81,6 +96,8 @@ export function Chart({}: ChartProps) {const chartId = useId();const descId = `${chartId}-desc`;+ // useId() can contain ':' which is invalid in an SVG url(#id) reference.+ const clipId = `plot-${chartId.replace(/:/g, '')}`;const containerRef = useRef<HTMLDivElement>(null);const svgRef = useRef<SVGSVGElement>(null);const [containerWidth, setContainerWidth] = useState(0);@@ -109,6 +126,22 @@ export function Chart({const innerWidth = Math.max(0, containerWidth - margin.left - margin.right);const innerHeight = Math.max(0, height - margin.top - margin.bottom);+ // ─── Color assignment ─────────────────────────────────────────────────+ // Give every primary series that doesn't supply a static color (auto-colored+ // or accessor-colored) a distinct color from the theme's categorical palette.+ // Utility marks (band/errorBar/referenceLine) don't consume palette slots.+ // Assigned during render (like the layout pass annotates `_uid`) so the first+ // paint is already colored; intentionally not a `useMemo` — it mutates the+ // caller's series defs, and useMemo is allowed to drop its cached result.+ const chartColors = useChartColors();+ const needsColor = series.filter(+ s => !isUtilityMarkType(s.type) && s.color == null,+ );+ const palette = chartColors.categorical(Math.max(needsColor.length, 1));+ for (let i = 0; i < needsColor.length; i++) {+ needsColor[i]._resolvedColor = palette[i % palette.length];+ }+// ─── Layout pass ──────────────────────────────────────────────────────const layout = useMemo(() =>@@ -118,8 +151,11 @@ export function Chart({series,width: innerWidth,height: innerHeight,+ yBaseline,+ yDomain,+ xDomain,}),- [data, xKey, series, innerWidth, innerHeight],+ [data, xKey, series, innerWidth, innerHeight, yBaseline, yDomain, xDomain],);const seriesCtx = useMemo(@@ -185,7 +221,7 @@ export function Chart({}, [dispatch]);// ─── Context for interactions + v1 chrome ─────────────────────────────- const ctx: ChartV2Context = useMemo(+ const ctx: ChartContext = useMemo(() => ({width: innerWidth,height: innerHeight,@@ -201,33 +237,6 @@ export function Chart({[innerWidth, innerHeight, margin, data, xKey, layout, onPointer],);- // Bridge v1 context for ChartGrid/Axis compatibility- const v1Ctx = useMemo(- () => ({- width: innerWidth,- height: innerHeight,- margin,- xKey,- data,- xScale: layout.xScale,- yScale: layout.yScale,- svgRef,- pointerToData: () => ({- x: null as string | number | null,- y: 0,- px: 0,- py: 0,- }),- pixelToData: (px: number, py: number) => ({- x: null as string | number | null,- y: 0,- px,- py,- }),- }),- [innerWidth, innerHeight, margin, xKey, data, layout, svgRef],- );-// ─── Legend ────────────────────────────────────────────────────────────const legendConfig = legend === true ? {} : legend || null;@@ -270,25 +279,23 @@ export function Chart({)}</div>)}- <ChartV2Provider value={ctx}>- <ChartProvider value={v1Ctx}>- {legendConfig == null ? (- renderSvg()- ) : isLegendHorizontal ? (- <HStack gap={4}>- {legendPosition === 'start' && legendElement}- <div {...stylex.props(styles.chartArea)}>{renderSvg()}</div>- {legendPosition === 'end' && legendElement}- </HStack>- ) : (- <VStack gap={4}>- {legendPosition === 'top' && legendElement}- {renderSvg()}- {legendPosition === 'bottom' && legendElement}- </VStack>- )}- </ChartProvider>- </ChartV2Provider>+ <ChartProvider value={ctx}>+ {legendConfig == null ? (+ renderSvg()+ ) : isLegendHorizontal ? (+ <HStack gap={4}>+ {legendPosition === 'start' && legendElement}+ <div {...stylex.props(styles.chartArea)}>{renderSvg()}</div>+ {legendPosition === 'end' && legendElement}+ </HStack>+ ) : (+ <VStack gap={4}>+ {legendPosition === 'top' && legendElement}+ {renderSvg()}+ {legendPosition === 'bottom' && legendElement}+ </VStack>+ )}+ </ChartProvider></div>);@@ -302,18 +309,26 @@ export function Chart({aria-describedby={subtitle ? descId : undefined}>{title && <title>{title}</title>}{subtitle && <desc id={descId}>{subtitle}</desc>}+ <defs>+ <clipPath id={clipId}>+ <rect x={0} y={0} width={innerWidth} height={innerHeight} />+ </clipPath>+ </defs><g transform={`translate(${margin.left},${margin.top})`}>{/* 1. Grid */}{grid}- {/* 2. Marks — each series renders itself */}- {series.map(s => {- const resolved = layout.resolved.get(s.key);- if (!resolved) {- return null;- }- return <g key={s.key}>{s.render(resolved, seriesCtx)}</g>;- })}+ {/* 2. Marks — each series renders itself. Clipped to the plot area so+ curve overshoot (monotone/natural) can't escape into the margins. */}+ <g clipPath={`url(#${clipId})`}>+ {series.map(s => {+ const resolved = s._uid ? layout.resolved.get(s._uid) : undefined;+ if (!resolved) {+ return null;+ }+ return <g key={s._uid}>{s.render(resolved, seriesCtx)}</g>;+ })}+ </g>{/* 3. Axes */}{axes}diff --git a/packages/lab/src/ChartV2/ChartAxis.tsx b/packages/charts/src/ChartAxis.tsxsimilarity index 68%rename from packages/lab/src/ChartV2/ChartAxis.tsxrename to packages/charts/src/ChartAxis.tsxindex 4dcdb549c3..6e4c871d2b 100644--- a/packages/lab/src/ChartV2/ChartAxis.tsx+++ b/packages/charts/src/ChartAxis.tsx@@ -10,14 +10,18 @@* `<ChartGrid>`). To stay consistent with most charts, the bottom axis* draws its edge line by default and other positions don't.*+ * Labels use d3's native tick formatter for continuous scales by default (clean+ * numbers/dates) unless a `tickFormat` is supplied, and are auto-thinned to the+ * available width (horizontal) or height (vertical) to avoid overlap.+ ** Ticks use CSS transitions for smooth sliding during streaming updates.*/-import {useMemo} from 'react';+import {useCallback, useMemo} from 'react';import * as stylex from '@stylexjs/stylex';import {colorVars} from '@astryxdesign/core/theme/tokens.stylex';-import {useChart} from '../Chart/ChartContext';-import {isBandScale} from '../Chart/utils';+import {useChart} from './ChartContext';+import {isBandScale} from './utils';import type {ScaleLinear, ScaleTime} from 'd3-scale';export interface ChartAxisProps {@@ -86,6 +90,30 @@ export function ChartAxis({const isHorizontal = position === 'top' || position === 'bottom';const scale = isHorizontal ? xScale : yScale;+ // Default label formatter. For continuous (linear/time) scales, use d3's own+ // tick formatter so numbers get sensible precision (no floating-point dust+ // like "0.30000000000000004") and dates render as calendar labels instead of+ // `String(Date)`. Band scales keep their category strings.+ const autoFormat = useMemo<((v: unknown) => string) | null>(() => {+ if (tickFormat || isBandScale(scale)) {+ return null;+ }+ const continuous = scale as+ ScaleLinear<number, number> | ScaleTime<number, number>;+ const fmt = continuous.tickFormat(tickCount);+ return (v: unknown) => fmt(v as number & Date);+ }, [tickFormat, scale, tickCount]);++ const format = useCallback(+ (value: unknown): string => {+ const str = (tickFormat ?? autoFormat ?? String)(value);+ return truncate && str.length > truncate+ ? str.slice(0, truncate) + '\u2026'+ : str;+ },+ [tickFormat, autoFormat, truncate],+ );+const ticks = useMemo(() => {let allTicks: {value: unknown; offset: number}[];if (isBandScale(scale)) {@@ -95,22 +123,40 @@ export function ChartAxis({}));} else {const linearScale = scale as- | ScaleLinear<number, number>- | ScaleTime<number, number>;+ ScaleLinear<number, number> | ScaleTime<number, number>;allTicks = linearScale.ticks(tickCount).map(d => ({value: d,offset: linearScale(d as number & Date),}));}- // Auto-skip: show every Nth label if maxTicks is exceeded- if (maxTicks && allTicks.length > maxTicks) {- const step = Math.ceil(allTicks.length / maxTicks);+ // Cap label count to avoid overlap. An explicit `maxTicks` always wins.+ // Otherwise derive a cap from the available space and label size so dense+ // axes don't smear into an unreadable blur: width ÷ widest-label for+ // horizontal (e.g. 30 daily categories), height ÷ line-height for vertical+ // (e.g. a categorical y-axis on a horizontal bar chart). Labels are then+ // evenly skipped down to the cap.+ let cap = maxTicks;+ if (cap == null && allTicks.length > 1) {+ if (isHorizontal && width > 0) {+ const widestChars = allTicks.reduce(+ (m, t) => Math.max(m, format(t.value).length),+ 1,+ );+ const approxLabelPx = widestChars * 7 + 16;+ cap = Math.max(1, Math.floor(width / approxLabelPx));+ } else if (!isHorizontal && height > 0) {+ // ~12px glyph + breathing room keeps stacked labels from touching.+ cap = Math.max(1, Math.floor(height / 18));+ }+ }+ if (cap && allTicks.length > cap) {+ const step = Math.ceil(allTicks.length / cap);allTicks = allTicks.filter((_, i) => i % step === 0);}return allTicks;- }, [scale, tickCount, maxTicks]);+ }, [scale, tickCount, maxTicks, isHorizontal, width, height, format]);const transform =position === 'bottom'@@ -132,20 +178,12 @@ export function ChartAxis({return 0;})();- const baseFormat = tickFormat ?? String;- const format = truncate- ? (value: unknown) => {- const str = baseFormat(value);- return str.length > truncate ? str.slice(0, truncate) + '\u2026' : str;- }- : baseFormat;-const tickTransition = animated? 'transform 150ms linear, opacity 150ms ease': undefined;return (- <g transform={transform}>+ <g transform={transform} role="group" aria-label={`${position} axis`}>{renderAxisLine && (<linex1={0}@@ -157,6 +195,9 @@ export function ChartAxis({)}{ticks.map(({value, offset}) => {const label = format(value);+ // Key off the raw tick value, not the formatted label: distinct ticks+ // can format (or truncate) to the same string and would collide as keys.+ const key = String(value);const isVisible = isHorizontal? offset >= -10 && offset <= width + 10: offset >= -10 && offset <= height + 10;@@ -165,7 +206,7 @@ export function ChartAxis({const y = position === 'bottom' ? TICK_SIZE : -TICK_SIZE;return (<g- key={label}+ key={key}style={{transform: `translateX(${offset}px)`,transition: tickTransition,@@ -186,7 +227,7 @@ export function ChartAxis({const x = position === 'left' ? -TICK_SIZE : TICK_SIZE;return (<g- key={label}+ key={key}style={{transform: `translateY(${offset}px)`,transition: tickTransition,diff --git a/packages/lab/src/ChartV2/ChartV2Context.ts b/packages/charts/src/ChartContext.tssimilarity index 50%rename from packages/lab/src/ChartV2/ChartV2Context.tsrename to packages/charts/src/ChartContext.tsindex fcf69d3454..38d37be1b4 100644--- a/packages/lab/src/ChartV2/ChartV2Context.ts+++ b/packages/charts/src/ChartContext.ts@@ -1,12 +1,13 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {createContext, useContext} from 'react';-import type {ChartV2Context} from './types';+import type {ChartContext} from './types';-const Ctx = createContext<ChartV2Context | null>(null);-export const ChartV2Provider = Ctx.Provider;+const Ctx = createContext<ChartContext | null>(null);+Ctx.displayName = 'ChartContext';+export const ChartProvider = Ctx.Provider;-export function useChartV2(): ChartV2Context {+export function useChart(): ChartContext {const ctx = useContext(Ctx);if (!ctx) {throw new Error('Must be used inside <Chart>');diff --git a/packages/lab/src/ChartV2/ChartGrid.tsx b/packages/charts/src/ChartGrid.tsxsimilarity index 61%rename from packages/lab/src/ChartV2/ChartGrid.tsxrename to packages/charts/src/ChartGrid.tsxindex cd2e3b4301..1934cc75ec 100644--- a/packages/lab/src/ChartV2/ChartGrid.tsx+++ b/packages/charts/src/ChartGrid.tsx@@ -9,8 +9,8 @@import {useMemo} from 'react';import * as stylex from '@stylexjs/stylex';import {colorVars} from '@astryxdesign/core/theme/tokens.stylex';-import {useChart} from '../Chart/ChartContext';-import {isBandScale} from '../Chart/utils';+import {useChart} from './ChartContext';+import {isBandScale} from './utils';import type {ScaleLinear, ScaleTime} from 'd3-scale';export interface ChartGridProps {@@ -18,6 +18,12 @@ export interface ChartGridProps {horizontal?: boolean;/** Show vertical grid lines. Default: `false`. */vertical?: boolean;+ /**+ * Approximate number of grid lines per axis. Match your `<ChartAxis>`+ * `tickCount` so grid lines and tick labels land on the same values.+ * Default: `5`.+ */+ tickCount?: number;}const styles = stylex.create({@@ -42,20 +48,23 @@ const styles = stylex.create({export function ChartGrid({horizontal = true,vertical = false,+ tickCount = 5,}: ChartGridProps) {const {width, height, xScale, yScale} = useChart();// Skip the y=0 line when emphasizing it via the axis. Without this we'd- // double-draw on top of the axis line.+ // double-draw on top of the axis line. Each line carries its tick `value`,+ // used as a stable React key — the pixel position can be NaN/duplicated for+ // degenerate (zero-range / unmeasured) scales and would collide as a key.const hLines = useMemo(() => {if (!horizontal) {return [];}return yScale- .ticks(5)+ .ticks(tickCount).filter(tick => tick !== 0)- .map(tick => yScale(tick));- }, [horizontal, yScale]);+ .map(tick => ({value: tick, pos: yScale(tick)}));+ }, [horizontal, yScale, tickCount]);const vLines = useMemo(() => {if (!vertical) {@@ -64,31 +73,32 @@ export function ChartGrid({if (isBandScale(xScale)) {return xScale.domain()- .map(d => (xScale(d) ?? 0) + xScale.bandwidth() / 2);+ .map(d => ({value: d, pos: (xScale(d) ?? 0) + xScale.bandwidth() / 2}));}const linear = xScale as- | ScaleLinear<number, number>- | ScaleTime<number, number>;- return linear.ticks(5).map(d => linear(d as number & Date));- }, [vertical, xScale]);+ ScaleLinear<number, number> | ScaleTime<number, number>;+ return linear+ .ticks(tickCount)+ .map(d => ({value: String(d), pos: linear(d as number & Date)}));+ }, [vertical, xScale, tickCount]);return (<g>- {hLines.map(y => (+ {hLines.map(({value, pos}) => (<line- key={`h-${y}`}+ key={`h-${value}`}x1={0}x2={width}- y1={y}- y2={y}+ y1={pos}+ y2={pos}{...stylex.props(styles.gridLine)}/>))}- {vLines.map(x => (+ {vLines.map(({value, pos}) => (<line- key={`v-${x}`}- x1={x}- x2={x}+ key={`v-${value}`}+ x1={pos}+ x2={pos}y1={0}y2={height}{...stylex.props(styles.gridLine)}diff --git a/packages/lab/src/ChartV2/ChartLegend.tsx b/packages/charts/src/ChartLegend.tsxsimilarity index 75%rename from packages/lab/src/ChartV2/ChartLegend.tsxrename to packages/charts/src/ChartLegend.tsxindex 806f38ec24..828c54947b 100644--- a/packages/lab/src/ChartV2/ChartLegend.tsx+++ b/packages/charts/src/ChartLegend.tsx@@ -43,8 +43,10 @@ export function ChartLegend({const isVertical = position === 'start' || position === 'end';- const legendItems = items.map(item => (- <HStack key={item.label} gap={2} vAlign="center">+ // Rows are stateless, but labels aren't guaranteed unique (two series can+ // share a label), so disambiguate with the index to keep keys collision-free.+ const legendItems = items.map((item, i) => (+ <HStack key={`${item.label}-${i}`} gap={2} vAlign="center" role="listitem"><ChartSwatchcolor={item.color}variant={swatchVariantForType(item.type)}@@ -55,14 +57,20 @@ export function ChartLegend({if (isVertical) {return (- <VStack gap={2} hAlign={alignment}>+ <VStack gap={2} hAlign={alignment} role="list" aria-label="Chart legend">{legendItems}</VStack>);}return (- <HStack gap={4} justify={alignment} vAlign="center" wrap="wrap">+ <HStack+ gap={4}+ justify={alignment}+ vAlign="center"+ wrap="wrap"+ role="list"+ aria-label="Chart legend">{legendItems}</HStack>);diff --git a/packages/lab/src/ChartV2/ChartSwatch.doc.mjs b/packages/charts/src/ChartSwatch.doc.mjssimilarity index 94%rename from packages/lab/src/ChartV2/ChartSwatch.doc.mjsrename to packages/charts/src/ChartSwatch.doc.mjsindex 2509f82bde..6b494f6cf1 100644--- a/packages/lab/src/ChartV2/ChartSwatch.doc.mjs+++ b/packages/charts/src/ChartSwatch.doc.mjs@@ -5,7 +5,7 @@export const docs = {name: 'ChartSwatch',displayName: 'Chart Swatch',- group: 'ChartV2',+ group: 'Charts',category: 'Data Visualization',isHiddenFromOverview: true,diff --git a/packages/lab/src/ChartV2/ChartSwatch.tsx b/packages/charts/src/ChartSwatch.tsxsimilarity index 90%rename from packages/lab/src/ChartV2/ChartSwatch.tsxrename to packages/charts/src/ChartSwatch.tsxindex 01eed41d72..d62ae6bc79 100644--- a/packages/lab/src/ChartV2/ChartSwatch.tsx+++ b/packages/charts/src/ChartSwatch.tsx@@ -46,6 +46,10 @@ const styles = stylex.create({height: 3,borderRadius: 1.5,},+ // Runtime color → dynamic StyleX (not an inline style), per repo convention.+ fill: (color: string) => ({+ backgroundColor: color,+ }),});/**@@ -60,8 +64,7 @@ function ChartSwatchImpl({color, variant = 'square'}: ChartSwatchProps) {return (<divaria-hidden- {...stylex.props(styles.base, styles[variant])}- style={{backgroundColor: color}}+ {...stylex.props(styles.base, styles[variant], styles.fill(color))}/>);}diff --git a/packages/lab/src/ChartV2/ChartTooltip.tsx b/packages/charts/src/ChartTooltip.tsxsimilarity index 84%rename from packages/lab/src/ChartV2/ChartTooltip.tsxrename to packages/charts/src/ChartTooltip.tsxindex 8796c51eca..365e4df0c7 100644--- a/packages/lab/src/ChartV2/ChartTooltip.tsx+++ b/packages/charts/src/ChartTooltip.tsx@@ -5,7 +5,7 @@* @output Grouped chart tooltip — shows all series values at the hovered x-position.* Composable: drop into `<Chart tooltip>` or render directly inside a chart* to take full control of props.- * @position Reads from ChartV2Context — must render inside an <Chart>.+ * @position Reads from ChartContext — must render inside an <Chart>.** @example* ```@@ -43,7 +43,7 @@ import {} from '@astryxdesign/core/theme/tokens.stylex';import {Text} from '@astryxdesign/core';import {VStack, HStack} from '@astryxdesign/core';-import {useChartV2} from './ChartV2Context';+import {useChart} from './ChartContext';import {ChartSwatch, swatchVariantForType} from './ChartSwatch';import {deriveTooltipSeriesValues,@@ -51,7 +51,7 @@ import {type TooltipSeriesValue,} from './tooltip';import type {SeriesDef, ChartPointerEvent} from './types';-import type {ScaleBand} from 'd3-scale';+import {isBandScale, xPixel} from './utils';export type ChartTooltipPlacement = 'auto' | 'right' | 'left' | 'top';@@ -128,8 +128,8 @@ const DefaultTooltipContent = memo(function DefaultTooltipContent({<Text type="supporting">{String(rows[0].value)}</Text>) : (<VStack gap={1}>- {rows.map(row => (- <HStack key={row.key} gap={2} vAlign="center">+ {rows.map((row, i) => (+ <HStack key={`${row.key}-${i}`} gap={2} vAlign="center"><ChartSwatchcolor={row.color}variant={swatchVariantForType(row.type)}@@ -170,7 +170,7 @@ export function ChartTooltip({xScale,width,height,- } = useChartV2();+ } = useChart();const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);const cardRef = useRef<HTMLDivElement>(null);@@ -198,6 +198,7 @@ export function ChartTooltip({const cardWidth = card.offsetWidth;const cardHeight = card.offsetHeight;const viewportWidth = window.innerWidth;+ const viewportHeight = window.innerHeight;const gap = 8;let x: number;@@ -223,6 +224,12 @@ export function ChartTooltip({}}+ // Clamp to the viewport so the card never clips off-screen — it's+ // portaled and position:fixed, so this keeps it fully visible for every+ // placement (pinned placements and the near-edge `auto` flip alike).+ x = Math.max(gap, Math.min(x, viewportWidth - cardWidth - gap));+ y = Math.max(gap, Math.min(y, viewportHeight - cardHeight - gap));+card.style.left = `${x}px`;card.style.top = `${y}px`;card.style.display = 'block';@@ -263,19 +270,21 @@ export function ChartTooltip({if (!shouldRenderHoverDot(s.type)) {continue;}- const points = resolved.get(s.key);+ const points = s._uid ? resolved.get(s._uid) : undefined;const point = points?.find(p => p.dataIndex === hoveredIndex);if (!point) {continue;}elements.push(<circle- key={s.key}+ key={s._uid}cx={point.px}cy={point.py}r={4}fill="var(--color-background-surface)"- stroke={s.color ?? 'var(--color-border-emphasized)'}+ stroke={+ s.color ?? s._resolvedColor ?? 'var(--color-border-emphasized)'+ }strokeWidth={2}pointerEvents="none"/>,@@ -291,18 +300,17 @@ export function ChartTooltip({if (!hoverIndicator || hoveredIndex == null) {return null;}- const xv = data[hoveredIndex]?.[xKey];- if (xv == null) {+ const hoveredDatum = data[hoveredIndex];+ const xv = hoveredDatum?.[xKey];+ if (hoveredDatum == null || xv == null) {return null;}- const isBandScale = 'bandwidth' in xScale;const hasBars = series.some(s => s.type === 'bar');// Bar charts on a band scale → soft column highlight.- if (hasBars && isBandScale) {- const bandScale = xScale as ScaleBand<string>;- const x = bandScale(String(xv)) ?? 0;- const bw = bandScale.bandwidth();+ if (hasBars && isBandScale(xScale)) {+ const x = xScale(String(xv)) ?? 0;+ const bw = xScale.bandwidth();const pad = 8;const rectX = Math.max(0, x - pad);const rectRight = Math.min(width, x + bw + pad);@@ -322,11 +330,9 @@ export function ChartTooltip({);}- // Line / area / dot charts → vertical crosshair through the point.- const px = isBandScale- ? ((xScale as ScaleBand<string>)(String(xv)) ?? 0) +- (xScale as ScaleBand<string>).bandwidth() / 2- : (xScale as (v: number) => number)(xv as number);+ // Line / area / dot charts → vertical crosshair through the point+ // (band-center or linear position, resolved by the shared helper).+ const px = xPixel(hoveredDatum, xKey, xScale);return (<linex1={px}@@ -349,6 +355,21 @@ export function ChartTooltip({margin.top,]);+ // Honor the documented contract: a custom `render` returning null hides the+ // card (band highlight + dots still show). Without this, positionCard would+ // leave an empty bordered box at the hovered point. Runs after commit so it+ // also clears the frame positionCard optimistically displayed; effects never+ // run during SSR, so `render` stays off the server path.+ useEffect(() => {+ if (!render || hoveredIndex == null) {+ return;+ }+ const card = cardRef.current;+ if (card && render(xValue, seriesValues) == null) {+ card.style.display = 'none';+ }+ }, [render, hoveredIndex, xValue, seriesValues]);+// ─── Render ────────────────────────────────────────────────────────────if (typeof document === 'undefined') {// SSR: no DOM portal target; band highlight + dots still render in SVG.@@ -372,7 +393,7 @@ export function ChartTooltip({{hoverIndicatorElement}{dots}{createPortal(- <div ref={cardRef} {...stylex.props(styles.card)}>+ <div ref={cardRef} role="tooltip" {...stylex.props(styles.card)}>{cardContent}</div>,document.body,diff --git a/packages/charts/src/formatters.ts b/packages/charts/src/formatters.tsnew file mode 100644index 0000000000..0eb5cc8f41--- /dev/null+++ b/packages/charts/src/formatters.ts@@ -0,0 +1,157 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file formatters.ts+ * @output Built-in, locale-aware tick/value format utilities for common data types+ * @position Utility; consumed by ChartAxis via tickFormat prop+ *+ * Formatters degrade gracefully: non-finite numbers (NaN/±Infinity) and+ * unparseable values are passed through as-is rather than producing garbage+ * like "InfinityB", and no input throws. Numeric/date formatting is delegated+ * to cached `Intl` formatters so output is locale-aware and rounding is correct+ * across the full magnitude range (K/M/B/T and beyond).+ */++/** Lazily create a value once and cache it — keeps `Intl` construction off the import path. */+function once<T>(create: () => T): () => T {+ let cached: {value: T} | null = null;+ return () => (cached ??= {value: create()}).value;+}++const getCompactFormat = once(+ () =>+ new Intl.NumberFormat(undefined, {+ notation: 'compact',+ maximumFractionDigits: 1,+ }),+);++const getPercentFormat = once(+ () =>+ new Intl.NumberFormat(undefined, {+ style: 'percent',+ maximumFractionDigits: 1,+ }),+);++const getShortDateFormat = once(+ () => new Intl.DateTimeFormat(undefined, {month: 'short', day: 'numeric'}),+);++const getMonthYearFormat = once(+ () => new Intl.DateTimeFormat(undefined, {month: 'short', year: 'numeric'}),+);++/**+ * Compact number formatter (e.g. 1200 → "1.2K", 1500000 → "1.5M", 1e12 → "1T").+ *+ * Non-numeric values (e.g. category labels) and non-finite numbers pass through+ * unchanged, so it is safe to use as a general-purpose tick formatter.+ */+export function compactNumber(value: unknown): string {+ const n = Number(value);+ if (!Number.isFinite(n)) {+ return String(value);+ }+ return getCompactFormat().format(n);+}++/**+ * Currency formatter factory. Returns a tick format function.+ *+ * The symbol prefixes the magnitude and the sign leads the symbol, so negatives+ * read as "-$1.5K" rather than "$-1.5K". Large values use compact notation.+ *+ * @example+ * ```+ * <ChartAxis tickFormat={currency()} /> // $1.5K+ * <ChartAxis tickFormat={currency('€')} /> // €1.5K+ * <ChartAxis tickFormat={currency('¥')} /> // ¥1.5K+ * ```+ */+export function currency(symbol = '$'): (value: unknown) => string {+ return (value: unknown) => {+ const n = Number(value);+ if (!Number.isFinite(n)) {+ return String(value);+ }+ const sign = n < 0 ? '-' : '';+ const abs = Math.abs(n);+ const body =+ abs >= 1000 ? getCompactFormat().format(abs) : abs.toLocaleString();+ return `${sign}${symbol}${body}`;+ };+}++/**+ * Percent formatter (e.g. 0.45 → "45%", 1.2 → "120%", 0.005 → "0.5%").+ *+ * The input is a ratio; it is multiplied by 100 and localized. Whole percents+ * render without a decimal, and up to one fractional digit is shown otherwise.+ */+export function percent(value: unknown): string {+ const n = Number(value);+ if (!Number.isFinite(n)) {+ return String(value);+ }+ return getPercentFormat().format(n);+}++/**+ * Coerce a value into a Date.+ *+ * Accepts a `Date`, epoch milliseconds (number or numeric string), or a date+ * string (ISO 8601, RFC 2822, …). Returns an invalid Date for anything else so+ * callers can pass the original value through unchanged.+ *+ * Date-only ISO strings (`YYYY-MM-DD`) are constructed at local midnight rather+ * than the spec's UTC midnight, so the calendar day survives local formatting+ * in negative-offset timezones (`"2024-01-05"` stays "Jan 5", not "Jan 4").+ */+function toDate(value: unknown): Date {+ if (value instanceof Date) {+ return value;+ }+ if (typeof value === 'number') {+ return new Date(value);+ }+ if (typeof value === 'string') {+ const s = value.trim();+ if (s === '') {+ return new Date(NaN);+ }+ const dateOnly = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);+ if (dateOnly) {+ return new Date(+ Number(dateOnly[1]),+ Number(dateOnly[2]) - 1,+ Number(dateOnly[3]),+ );+ }+ const asNumber = Number(s);+ return new Date(Number.isFinite(asNumber) ? asNumber : s);+ }+ return new Date(NaN);+}++/**+ * Date formatter — short date (e.g. "Jan 5", "Mar 12").+ */+export function shortDate(value: unknown): string {+ const d = toDate(value);+ if (Number.isNaN(d.getTime())) {+ return String(value);+ }+ return getShortDateFormat().format(d);+}++/**+ * Date formatter — month/year (e.g. "Jan 2024", "Mar 2025").+ */+export function monthYear(value: unknown): string {+ const d = toDate(value);+ if (Number.isNaN(d.getTime())) {+ return String(value);+ }+ return getMonthYearFormat().format(d);+}diff --git a/packages/charts/src/getChartColors.ts b/packages/charts/src/getChartColors.tsnew file mode 100644index 0000000000..f8e544aca1--- /dev/null+++ b/packages/charts/src/getChartColors.ts@@ -0,0 +1,289 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file getChartColors.ts+ * @output Pure function to resolve chart colors from a theme — no React required+ * @position Foundation utility; consumed by useChartColors and non-React contexts+ *+ * Takes a token resolver function (or a defined theme + mode) and returns+ * the full chart colors API. The useChartColors hook wraps this.+ *+ * Palettes degrade gracefully for any count: the categorical scale wraps+ * around its slots, and the sequential/diverging scales pick hand-tuned token+ * stops when enough exist and interpolate across the ramp when more are asked+ * for. The theme entry point resolves through the canonical token resolver, so+ * data tokens fall back to their defaults even when a theme doesn't override+ * them.+ */++import {resolveThemeTokens, type DefinedTheme} from '@astryxdesign/core/theme';++// =============================================================================+// Types+// =============================================================================++/** Hue names available in the sequential ramps */+export type SequentialHue =+ | 'blue'+ | 'shamrock'+ | 'orange'+ | 'pink'+ | 'purple'+ | 'red'+ | 'teal'+ | 'yellow'+ | 'gray';++/** The chart colors API returned by both getChartColors and useChartColors */+export interface ChartColorsAPI {+ categorical(n: number): string[];+ sequential: Record<SequentialHue, (n: number) => string[]>;+ diverging: {+ positiveNegative(n: number): string[];+ coldHot(n: number): string[];+ custom(+ neg: SequentialHue,+ pos: SequentialHue,+ n: number,+ midpoint?: string,+ ): string[];+ };+ semantic: {+ positive: string;+ negative: string;+ warning: string;+ neutral: string;+ };+ /** Structural colors for chart chrome — axes, grid, ticks, labels */+ structural: {+ axis: string;+ grid: string;+ tick: string;+ label: string;+ };+ alpha(hex: string, opacity: number): string;+}++/** A function that resolves a token name to its current value */+export type TokenResolver = (name: string) => string;++// =============================================================================+// Internals+// =============================================================================++const CATEGORICAL_TOKENS = [+ '--color-data-categorical-blue',+ '--color-data-categorical-orange',+ '--color-data-categorical-purple',+ '--color-data-categorical-green',+ '--color-data-categorical-pink',+ '--color-data-categorical-cyan',+ '--color-data-categorical-red',+ '--color-data-categorical-teal',+ '--color-data-categorical-brown',+ '--color-data-categorical-indigo',+] as const;++const SEQUENTIAL_HUES: SequentialHue[] = [+ 'blue',+ 'shamrock',+ 'orange',+ 'pink',+ 'purple',+ 'red',+ 'teal',+ 'yellow',+ 'gray',+];++/** Parse a `#rgb`, `#rrggbb`, or `#rrggbbaa` color to `[r, g, b]`; null for anything else. */+function parseHex(color: string): [number, number, number] | null {+ const hex = color.trim().replace(/^#/, '');+ if (/^[0-9a-fA-F]{3}$/.test(hex)) {+ return [+ parseInt(hex[0] + hex[0], 16),+ parseInt(hex[1] + hex[1], 16),+ parseInt(hex[2] + hex[2], 16),+ ];+ }+ if (/^[0-9a-fA-F]{6}$/.test(hex) || /^[0-9a-fA-F]{8}$/.test(hex)) {+ return [+ parseInt(hex.slice(0, 2), 16),+ parseInt(hex.slice(2, 4), 16),+ parseInt(hex.slice(4, 6), 16),+ ];+ }+ return null;+}++function toHexChannel(value: number): string {+ return Math.max(0, Math.min(255, Math.round(value)))+ .toString(16)+ .padStart(2, '0');+}++/** Interpolate between two hex colors in sRGB. Non-hex input falls back to the nearer endpoint. */+function lerpHex(a: string, b: string, t: number): string {+ const ca = parseHex(a);+ const cb = parseHex(b);+ if (ca === null || cb === null) {+ return t < 0.5 ? a : b;+ }+ const mix = (i: number): number => ca[i] + (cb[i] - ca[i]) * t;+ return `#${toHexChannel(mix(0))}${toHexChannel(mix(1))}${toHexChannel(mix(2))}`;+}++/**+ * Sample `n` colors from an ordered ramp of stops.+ * - `n <= stops.length` → picks the nearest exact stops, preserving the+ * hand-tuned design-token values.+ * - `n > stops.length` → interpolates across the ramp so any count is supported+ * instead of silently capping at the number of stops.+ * - `n === 1` → the middle stop, a single representative tone.+ */+function sampleRamp(stops: string[], n: number): string[] {+ const len = stops.length;+ if (n <= 0 || len === 0) {+ return [];+ }+ if (n === 1) {+ return [stops[Math.floor((len - 1) / 2)]];+ }+ if (len === 1) {+ return Array.from({length: n}, () => stops[0]);+ }+ if (n <= len) {+ return Array.from(+ {length: n},+ (_, i) => stops[Math.round((i * (len - 1)) / (n - 1))],+ );+ }+ return Array.from({length: n}, (_, i) => {+ const t = (i * (len - 1)) / (n - 1);+ const lo = Math.floor(t);+ const frac = t - lo;+ return frac === 0 ? stops[lo] : lerpHex(stops[lo], stops[lo + 1], frac);+ });+}++/** Apply an opacity to a hex color as an `rgba()` string. Non-hex input is returned unchanged. */+function hexAlpha(hex: string, opacity: number): string {+ const rgb = parseHex(hex);+ if (rgb === null) {+ return hex;+ }+ const a = Number.isFinite(opacity) ? Math.max(0, Math.min(1, opacity)) : 1;+ return `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${a})`;+}++// =============================================================================+// Public API+// =============================================================================++/**+ * Build chart colors from a token resolver function.+ * This is the lowest-level API — pass any function that maps token names to values.+ */+export function getChartColorsFromResolver(+ resolve: TokenResolver,+): ChartColorsAPI {+ const categorical = CATEGORICAL_TOKENS.map(t => resolve(t));++ const ramp = (hue: SequentialHue): string[] =>+ [5, 4, 3, 2, 1].map(step => resolve(`--color-data-${hue}-${step}`));++ const gray1 = resolve('--color-data-gray-1');++ function buildDiverging(+ negHue: SequentialHue,+ posHue: SequentialHue,+ n: number,+ midpoint: string = gray1,+ ): string[] {+ if (n <= 0) {+ return [];+ }+ if (n === 1) {+ return [midpoint];+ }+ const half = Math.floor(n / 2);+ const hasCenter = n % 2 === 1;+ const negSide = sampleRamp(ramp(negHue), half);+ const posSide = sampleRamp(ramp(posHue), half).reverse();+ if (hasCenter) {+ return [...negSide, midpoint, ...posSide];+ }+ return [...negSide, ...posSide];+ }++ return {+ categorical(n: number): string[] {+ if (n <= 0 || categorical.length === 0) {+ return [];+ }+ // Wrap around the palette so any series count gets a deterministic color.+ return Array.from(+ {length: n},+ (_, i) => categorical[i % categorical.length],+ );+ },++ sequential: Object.fromEntries(+ SEQUENTIAL_HUES.map(hue => [+ hue,+ (n: number): string[] => sampleRamp(ramp(hue), n),+ ]),+ ) as Record<SequentialHue, (n: number) => string[]>,++ diverging: {+ positiveNegative: (n: number) => buildDiverging('shamrock', 'red', n),+ coldHot: (n: number) => buildDiverging('blue', 'red', n),+ custom: (+ neg: SequentialHue,+ pos: SequentialHue,+ n: number,+ mid?: string,+ ) => buildDiverging(neg, pos, n, mid),+ },++ semantic: {+ positive: resolve('--color-data-categorical-green'),+ negative: resolve('--color-data-categorical-red'),+ warning: resolve('--color-data-categorical-orange'),+ neutral: resolve('--color-data-neutral'),+ },++ structural: {+ axis: resolve('--color-border-emphasized'),+ grid: resolve('--color-border'),+ tick: resolve('--color-border-emphasized'),+ label: resolve('--color-text-secondary'),+ },++ alpha: hexAlpha,+ };+}++/**+ * Build chart colors from a defined theme and color mode.+ *+ * Use this in non-React contexts — WebGL setup, SSR, tests, Node scripts.+ *+ * Resolves through the canonical theme token resolver, so data tokens fall back+ * to their defaults when the theme doesn't override them, and both+ * `light-dark()` strings and `[light, dark]` tuples are handled for `mode`.+ *+ * @example+ * ```+ * import { neutralTheme } from '@astryxdesign/theme-neutral';+ * const colors = getChartColors(neutralTheme, 'light');+ * colors.categorical(5)+ * ```+ */+export function getChartColors(+ theme: DefinedTheme,+ mode: 'light' | 'dark' = 'light',+): ChartColorsAPI {+ const tokens = resolveThemeTokens(theme, {mode});+ return getChartColorsFromResolver(name => tokens[name] ?? '');+}diff --git a/packages/charts/src/index.ts b/packages/charts/src/index.tsindex 2706cc1df4..04045e55bf 100644--- a/packages/charts/src/index.ts+++ b/packages/charts/src/index.ts@@ -1,17 +1,88 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-/**- * @astryxdesign/charts — Astryx chart components- *- * Thin, themeable wrappers over a peer charting engine. This package owns the- * design-system surface while leaving the rendering engine as a peer- * dependency the consumer manages.- *- * This package is published to npm ONLY under the @canary dist-tag- * (npm install @astryxdesign/charts@canary). It is never released as a- * stable (latest) version.- *- * Bootstrap scaffold — no components yet. Add exports here as components land.- */+export {Chart, type ChartProps} from './Chart';+export {ChartAxis, type ChartAxisProps} from './ChartAxis';+export {ChartGrid, type ChartGridProps} from './ChartGrid';+export {+ ChartLegend,+ type ChartLegendProps,+ type LegendPosition,+ type LegendAlignment,+} from './ChartLegend';+export {type LegendItem} from './legend';+export {+ ChartSwatch,+ swatchVariantForType,+ type ChartSwatchProps,+ type ChartSwatchVariant,+} from './ChartSwatch';+export {+ ChartTooltip,+ type ChartTooltipProps,+ type ChartTooltipPlacement,+} from './ChartTooltip';+export {type TooltipSeriesValue} from './tooltip';+export {+ bar,+ line,+ dot,+ area,+ band,+ candlestick,+ errorBar,+ referenceLine,+ dotGL,+ dotGLInteractive,+ heatmapGL,+ streamGL,+} from './marks';+export type {+ BarOptions,+ LineOptions,+ DotOptions,+ AreaOptions,+ BandOptions,+ CandlestickOptions,+ ErrorBarOptions,+ ReferenceLineOptions,+ DotGLOptions,+ DotGLInteractiveOptions,+ HeatmapGLOptions,+ StreamGLOptions,+ StreamGLHandle,+} from './marks';+export {useChart} from './ChartContext';+export type {+ SeriesDef,+ ChartContext,+ ChartPointerEvent,+ ResolvedPoint,+ ResolvedPositions,+ SeriesContext,+ ChartMargin,+ ChartScale,+ YBaseline,+ ColorAccessor,+} from './types';-export {};+// Color palette — theme-aware data-visualization colors+export {useChartColors} from './useChartColors';+export {+ getChartColors,+ getChartColorsFromResolver,+ type ChartColorsAPI,+ type SequentialHue,+ type TokenResolver,+} from './getChartColors';++// Tick / value formatters+export {+ compactNumber,+ currency,+ percent,+ shortDate,+ monthYear,+} from './formatters';++// Scale utilities+export {isBandScale, xPixel} from './utils';diff --git a/packages/lab/src/ChartV2/layout.ts b/packages/charts/src/layout.tssimilarity index 50%rename from packages/lab/src/ChartV2/layout.tsrename to packages/charts/src/layout.tsindex 785334e1dd..1b8f2a1394 100644--- a/packages/lab/src/ChartV2/layout.ts+++ b/packages/charts/src/layout.ts@@ -17,14 +17,31 @@ import type {ChartScale,ResolvedPoint,SeriesContext,+ YBaseline,} from './types';+/**+ * Fraction of the data range added as padding above/below for continuous-only+ * charts (no bar/area zero baseline), so endpoints and curve overshoot don't+ * glue to the plot edges.+ */+const CONTINUOUS_HEADROOM = 0.08;+export interface LayoutInput {data: Record<string, unknown>[];xKey: string;series: SeriesDef[];width: number;height: number;+ /** How the y-domain is derived when `yDomain` is not provided. Default 'auto'. */+ yBaseline?: YBaseline;+ /** Explicit y-domain [min, max]. Authoritative — no baseline/headroom/nice(). */+ yDomain?: [number, number];+ /**+ * Explicit x-domain [min, max] for numeric/linear x. Authoritative and honored+ * even when `data` is empty (stable streaming window). Ignored for band scales.+ */+ xDomain?: [number, number];}export interface LayoutResult {@@ -33,12 +50,50 @@ export interface LayoutResult {resolved: Map<string, ResolvedPoint[]>;}+/** True only when both ends of an explicit domain are usable finite numbers. */+function isFiniteDomain(domain: [number, number]): boolean {+ return Number.isFinite(domain[0]) && Number.isFinite(domain[1]);+}++/**+ * Finite [min, max] of a numeric column, robust to the two failure modes of+ * `Math.min(...arr)` / `Math.max(...arr)`: a NaN/Infinity poisoning the result,+ * and a call-stack overflow when spreading a very large array (GL marks push+ * hundreds of thousands of points). Empty or degenerate (all-equal) extents are+ * expanded so the resulting scale never collapses onto a single pixel.+ */+function finiteExtent(nums: number[]): [number, number] {+ let lo = Infinity;+ let hi = -Infinity;+ for (const v of nums) {+ if (Number.isFinite(v)) {+ if (v < lo) {+ lo = v;+ }+ if (v > hi) {+ hi = v;+ }+ }+ }+ if (!Number.isFinite(lo) || !Number.isFinite(hi)) {+ return [0, 1];+ }+ if (lo === hi) {+ const pad = Math.abs(lo) * 0.5 || 1;+ return [lo - pad, hi + pad];+ }+ return [lo, hi];+}+export function computeLayout({data,xKey,series,width,height,+ yBaseline,+ yDomain,+ xDomain,}: LayoutInput): LayoutResult {// ─── 1. X scale ──────────────────────────────────────────────────────const xValues = data.map(d => d[xKey]);@@ -46,12 +101,15 @@ export function computeLayout({xValues.length > 0 && xValues.every(v => typeof v === 'number');let xScale: ChartScale;- if (isNumericX) {- const nums = xValues as number[];- xScale = scaleLinear()- .domain([Math.min(...nums), Math.max(...nums)])- .range([0, width])- .nice();+ if (xDomain && isFiniteDomain(xDomain)) {+ // Explicit domain is authoritative (no .nice()) — enables a stable+ // streaming window and a valid scale even when `data` is empty. Trusted+ // only when finite; a NaN/Infinity domain would collapse the scale.+ xScale = scaleLinear().domain(xDomain).range([0, width]);+ } else if (isNumericX) {+ // NaN passes `typeof === 'number'`, so derive the extent defensively.+ const [lo, hi] = finiteExtent(xValues as number[]);+ xScale = scaleLinear().domain([lo, hi]).range([0, width]).nice();} else {xScale = scaleBand<string>().domain(xValues.map(String))@@ -60,8 +118,12 @@ export function computeLayout({}// ─── 2. Y domain from all series dataKeys ────────────────────────────+ // One pass collects the union of data keys, whether any mark wants a zero+ // baseline, and the stack groupings. `stackGroups` is reused verbatim by the+ // stacking pass below (§3) — previously these groups were built twice.const allKeys = new Set<string>();let includeZero = false;+ const stackGroups = new Map<string, string[]>();for (const s of series) {for (const k of s.dataKeys) {allKeys.add(k);@@ -69,24 +131,22 @@ export function computeLayout({if (s.layout.includeZero) {includeZero = true;}- }-- // Collect which keys are stacked together so we can compute stacked extents- const stackGroupKeys = new Map<string, string[]>();- for (const s of series) {- if (s.layout.stack) {- const group = stackGroupKeys.get(s.layout.stack) ?? [];- group.push(s.dataKeys[0]);- stackGroupKeys.set(s.layout.stack, group);+ const primaryKey = s.dataKeys[0];+ if (s.layout.stack && primaryKey != null) {+ const group = stackGroups.get(s.layout.stack) ?? [];+ group.push(primaryKey);+ stackGroups.set(s.layout.stack, group);}}let yMin = Infinity,yMax = -Infinity;- // For stacked series, compute the sum at each data point+ // Stacked series contribute their per-datum accumulated total. `Number.isFinite`+ // (not `typeof === 'number'`) so a stray NaN/Infinity can't corrupt the domain+ // into a NaN/Infinity scale.const stackedKeys = new Set<string>();- for (const [, keys] of stackGroupKeys) {+ for (const [, keys] of stackGroups) {for (const k of keys) {stackedKeys.add(k);}@@ -94,8 +154,8 @@ export function computeLayout({let sum = 0;for (const k of keys) {const v = d[k];- if (typeof v === 'number') {- sum += v;+ if (Number.isFinite(v)) {+ sum += v as number;}}if (sum > yMax) {@@ -107,44 +167,80 @@ export function computeLayout({}}- // For non-stacked series, use individual values+ // Non-stacked series contribute their individual finite values.for (const d of data) {for (const k of allKeys) {if (stackedKeys.has(k)) {continue;} // already handled aboveconst v = d[k];- if (typeof v === 'number') {- if (v < yMin) {- yMin = v;+ if (Number.isFinite(v)) {+ const n = v as number;+ if (n < yMin) {+ yMin = n;}- if (v > yMax) {- yMax = v;+ if (n > yMax) {+ yMax = n;}}}}- if (includeZero) {- if (yMin > 0) {+ // ─── Resolve the final y-domain ──────────────────────────────────────+ let yDomainFinal: [number, number];+ let applyNice = true;++ if (yDomain && isFiniteDomain(yDomain)) {+ // Caller owns the exact domain (e.g. zoom/streaming). No baseline,+ // headroom, or .nice() — rounding here would cause visual ratcheting.+ // Trusted only when finite; a NaN/Infinity domain falls through to auto.+ yDomainFinal = yDomain;+ applyNice = false;+ } else {+ // Degenerate: no finite values (empty data / all non-numeric).+ if (!Number.isFinite(yMin) || !Number.isFinite(yMax)) {yMin = 0;+ yMax = 1;}- if (yMax < 0) {- yMax = 0;+ // Degenerate: zero range (single point / all-equal) — expand so the mark+ // is visible and ticks are sane.+ if (yMin === yMax) {+ const pad = Math.abs(yMin) * 0.5 || 1;+ yMin -= pad;+ yMax += pad;}- }- const yScale = scaleLinear().domain([yMin, yMax]).range([height, 0]).nice();- // ─── 3. Stacking ─────────────────────────────────────────────────────- const stackGroups = new Map<string, string[]>();- for (const s of series) {- if (s.layout.stack) {- const group = stackGroups.get(s.layout.stack) ?? [];- group.push(s.dataKeys[0]);- stackGroups.set(s.layout.stack, group);+ const mode: YBaseline = yBaseline ?? 'auto';+ if (mode === 'zero') {+ const abs = Math.max(Math.abs(yMin), Math.abs(yMax));+ yMin = -abs;+ yMax = abs;+ } else if (mode === 'data') {+ // Tight fit — no zero forcing, no headroom.+ } else {+ // 'auto': bar/area marks pin an honest zero baseline; continuous-only+ // charts get headroom so endpoints/overshoot don't glue to the edges.+ if (includeZero) {+ if (yMin > 0) {+ yMin = 0;+ }+ if (yMax < 0) {+ yMax = 0;+ }+ } else {+ const pad = (yMax - yMin || 1) * CONTINUOUS_HEADROOM;+ yMin -= pad;+ yMax += pad;+ }}+ yDomainFinal = [yMin, yMax];}+ const yScaleBase = scaleLinear().domain(yDomainFinal).range([height, 0]);+ const yScale = applyNice ? yScaleBase.nice() : yScaleBase;++ // ─── 3. Stacking ─────────────────────────────────────────────────────+ // Reuses `stackGroups` collected during the domain pass (§2).const stackedData = new Map<string, {y0: number; y1: number}[]>();for (const [, keys] of stackGroups) {const stackGen = d3Stack<Record<string, unknown>>()@@ -192,7 +288,12 @@ export function computeLayout({}}- for (const s of series) {+ for (let seriesIndex = 0; seriesIndex < series.length; seriesIndex++) {+ const s = series[seriesIndex];+ // Assign a collision-free identity from array position. Two series sharing+ // a dataKey (and thus `key`) still get distinct uids, so neither the+ // resolved map nor React keys silently drop one of them.+ s._uid = `${seriesIndex}:${s.key}`;const stackOffsets = stackedData.get(s.dataKeys[0]);// Mark whether this series is the topmost in its stack@@ -216,7 +317,7 @@ export function computeLayout({}const points = s.resolve(ctx, stackOffsets, groupInfo);- resolved.set(s.key, points);+ resolved.set(s._uid, points);}return {xScale, yScale, resolved};diff --git a/packages/charts/src/legend.ts b/packages/charts/src/legend.tsnew file mode 100644index 0000000000..c48371ffc5--- /dev/null+++ b/packages/charts/src/legend.ts@@ -0,0 +1,44 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file legend.ts+ * @output Legend utility — derives legend items from series definitions+ * @position Used by Chart to bridge series → legend items+ */++import {DEFAULT_SERIES_COLOR, isUtilityMarkType, type SeriesDef} from './types';++export interface LegendItem {+ label: string;+ color: string;+ /** Mark type — determines swatch shape (square for bar, line for everything else) */+ type?: string;+}++/**+ * A series appears in the legend if it's a primary (non-utility) mark. Its+ * representative color is the static color, else the root-assigned palette color+ * (so auto-colored AND accessor-colored series still show up — previously an+ * accessor color silently dropped the series from the legend).+ */+function legendColor(series: SeriesDef): string | undefined {+ if (isUtilityMarkType(series.type)) {+ return undefined;+ }+ return series.color ?? series._resolvedColor ?? DEFAULT_SERIES_COLOR;+}++/**+ * Derive legend items from series definitions. Skips utility marks.+ */+export function deriveLegendItems(series: readonly SeriesDef[]): LegendItem[] {+ const items: LegendItem[] = [];+ for (const s of series) {+ const color = legendColor(s);+ if (color == null) {+ continue;+ }+ items.push({label: s.label ?? s.key, color, type: s.type});+ }+ return items;+}diff --git a/packages/charts/src/markColor.ts b/packages/charts/src/markColor.tsnew file mode 100644index 0000000000..5d0d7c018c--- /dev/null+++ b/packages/charts/src/markColor.ts@@ -0,0 +1,63 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file markColor.ts+ * @output Color resolution shared by marks+ * @position Used by mark renderers to turn an optional color into a concrete one+ *+ * Precedence: an explicit color (string or accessor) always wins; otherwise the+ * chart root's palette color for the series (`_resolvedColor`); otherwise a real+ * data-viz token fallback. This is what makes an un-colored `bar('revenue')`+ * render a real color instead of the historical broken `--color-chart-1`.+ *+ * Empty strings are treated as "unset" at every level (an empty `fill`/`stroke`+ * paints nothing), and a per-point accessor that returns a non-string or empty+ * value falls through to the palette rather than emitting an invalid paint.+ */++import {+ DEFAULT_SERIES_COLOR,+ type SeriesDef,+ type ColorAccessor,+} from './types';++/** A usable CSS paint value — a non-empty string. */+function isPaint(value: unknown): value is string {+ return typeof value === 'string' && value.length > 0;+}++/** The palette color assigned by the chart root, or the last-resort token. */+function fallbackFill(def: SeriesDef): string {+ return isPaint(def._resolvedColor)+ ? def._resolvedColor+ : DEFAULT_SERIES_COLOR;+}++/** The single resolved color for a series (line/area/band and similar). */+export function seriesFill(+ def: SeriesDef,+ color: ColorAccessor | undefined,+): string {+ if (isPaint(color)) {+ return color;+ }+ return fallbackFill(def);+}++/** Per-point fill: an accessor wins, then an explicit string, then the palette. */+export function pointFill(+ def: SeriesDef,+ color: ColorAccessor | undefined,+ datum: Record<string, unknown>,+ index: number,+): string {+ if (typeof color === 'function') {+ const resolved = color(datum, index);+ if (isPaint(resolved)) {+ return resolved;+ }+ } else if (isPaint(color)) {+ return color;+ }+ return fallbackFill(def);+}diff --git a/packages/lab/src/ChartV2/marks/area.tsx b/packages/charts/src/marks/area.tsxsimilarity index 54%rename from packages/lab/src/ChartV2/marks/area.tsxrename to packages/charts/src/marks/area.tsxindex b37d4e5053..9dc88cc0ec 100644--- a/packages/lab/src/ChartV2/marks/area.tsx+++ b/packages/charts/src/marks/area.tsx@@ -3,6 +3,11 @@/*** @file marks/area.tsx* @output Area series — fill under line with stacking + gradient support+ *+ * Missing / non-finite values (including gaps in a stacked baseline) become+ * holes via d3's `.defined()` rather than collapsing to zero. The gradient id is+ * salted with the series' collision-free `_uid` so overlapping areas over the+ * same dataKey never share (and steal) each other's fill.*/import {@@ -14,7 +19,8 @@ import {} from 'd3-shape';import {line as d3Line} from 'd3-shape';import type {SeriesDef, ResolvedPoint} from '../types';-import type {ScaleBand} from 'd3-scale';+import {seriesFill} from '../markColor';+import {xPixel} from '../utils';const CURVES = {linear: curveLinear,@@ -33,14 +39,24 @@ export interface AreaOptions {label?: string;}+/** Both edges of an area point must be finite for the span to be drawable. */+function isFinitePoint(p: ResolvedPoint): boolean {+ return (+ Number.isFinite(p.px) && Number.isFinite(p.py) && Number.isFinite(p.py0)+ );+}+export function area(dataKey: string, options: AreaOptions = {}): SeriesDef {- const color = options.color ?? 'var(--color-chart-1)';- const opacity = options.opacity ?? 0.3;+ const color = options.color;+ const opacity =+ typeof options.opacity === 'number' && Number.isFinite(options.opacity)+ ? Math.min(1, Math.max(0, options.opacity))+ : 0.3;const curve = options.curve ?? 'monotone';const gradient = options.gradient ?? false;const stroke = options.stroke ?? true;- return {+ const seriesDef: SeriesDef = {type: 'area',key: dataKey,dataKeys: [dataKey],@@ -53,24 +69,18 @@ export function area(dataKey: string, options: AreaOptions = {}): SeriesDef {const points: ResolvedPoint[] = [];for (let i = 0; i < data.length; i++) {const d = data[i];- let px: number;- if ('bandwidth' in xScale) {- px =- ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) +- (xScale as ScaleBand<string>).bandwidth() / 2;- } else {- px = xScale(d[xKey] as number);- }let py: number, py0: number;if (stackOffsets) {- py = yScale(stackOffsets[i].y1);- py0 = yScale(stackOffsets[i].y0);+ const offset = stackOffsets[i];+ py = offset ? yScale(offset.y1) : NaN;+ py0 = offset ? yScale(offset.y0) : NaN;} else {- const v = typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;+ const raw = d[dataKey];+ const v = typeof raw === 'number' && Number.isFinite(raw) ? raw : NaN;py = yScale(v);py0 = yScale(0);}- points.push({px, py, py0, dataIndex: i});+ points.push({px: xPixel(d, xKey, xScale), py, py0, dataIndex: i});}return points;},@@ -79,9 +89,10 @@ export function area(dataKey: string, options: AreaOptions = {}): SeriesDef {if (resolved.length === 0) {return null;}- const curveFactory = CURVES[curve];+ const curveFactory = CURVES[curve] ?? curveMonotoneX;const areaGen = d3Area<ResolvedPoint>()+ .defined(isFinitePoint).x(d => d.px).y0(d => d.py0).y1(d => d.py)@@ -89,34 +100,43 @@ export function area(dataKey: string, options: AreaOptions = {}): SeriesDef {const pathD = areaGen(resolved) ?? '';const lineGen = d3Line<ResolvedPoint>()+ .defined(isFinitePoint).x(d => d.px).y(d => d.py).curve(curveFactory);const strokeD = lineGen(resolved) ?? '';- const gradientId = `area-grad-${dataKey}`;+ // Unique per series instance so two areas over the same dataKey don't+ // share a gradient id (which would make one steal the other's fill).+ const gradientId = `area-grad-${(seriesDef._uid ?? dataKey).replace(+ /[^a-zA-Z0-9_-]/g,+ '-',+ )}`;+ const fillColor = seriesFill(seriesDef, color);return (<g>{gradient && (<defs><linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">- <stop offset="0%" stopColor={color} stopOpacity={opacity} />- <stop offset="100%" stopColor={color} stopOpacity={0} />+ <stop offset="0%" stopColor={fillColor} stopOpacity={opacity} />+ <stop offset="100%" stopColor={fillColor} stopOpacity={0} /></linearGradient></defs>)}<pathd={pathD}- fill={gradient ? `url(#${gradientId})` : color}+ fill={gradient ? `url(#${gradientId})` : fillColor}fillOpacity={gradient ? 1 : opacity}stroke="none"/>{stroke && (- <path d={strokeD} fill="none" stroke={color} strokeWidth={2} />+ <path d={strokeD} fill="none" stroke={fillColor} strokeWidth={2} />)}</g>);},};++ return seriesDef;}diff --git a/packages/lab/src/ChartV2/marks/band.tsx b/packages/charts/src/marks/band.tsxsimilarity index 62%rename from packages/lab/src/ChartV2/marks/band.tsxrename to packages/charts/src/marks/band.tsxindex d47122f7dd..1960fab5ca 100644--- a/packages/lab/src/ChartV2/marks/band.tsx+++ b/packages/charts/src/marks/band.tsx@@ -2,11 +2,17 @@/*** @file marks/band.tsx- * @output Band (confidence interval) series+ * @output Band (confidence interval) series — area between upper/lower bounds.+ * Non-numeric/NaN bounds break the area into gaps instead of collapsing to a+ * false zero baseline.*/import {area as d3Area, curveMonotoneX} from 'd3-shape';-import type {SeriesDef, ResolvedPoint} from '../types';+import {+ DEFAULT_SERIES_COLOR,+ type SeriesDef,+ type ResolvedPoint,+} from '../types';import type {ScaleBand} from 'd3-scale';export interface BandOptions {@@ -17,7 +23,7 @@ export interface BandOptions {}export function band(options: BandOptions): SeriesDef {- const color = options.color ?? 'var(--color-chart-1)';+ const color = options.color ?? DEFAULT_SERIES_COLOR;const opacity = options.opacity ?? 0.15;return {@@ -39,14 +45,12 @@ export function band(options: BandOptions): SeriesDef {} else {px = xScale(d[xKey] as number);}- const upper =- typeof d[options.upper] === 'number'- ? (d[options.upper] as number)- : 0;- const lower =- typeof d[options.lower] === 'number'- ? (d[options.lower] as number)- : 0;+ // NaN for missing/non-numeric bounds so render() can gap the area+ // rather than draw a spike down to the axis.+ const upperVal = d[options.upper];+ const lowerVal = d[options.lower];+ const upper = Number.isFinite(upperVal) ? (upperVal as number) : NaN;+ const lower = Number.isFinite(lowerVal) ? (lowerVal as number) : NaN;points.push({px, py: yScale(upper), py0: yScale(lower), dataIndex: i});}return points;@@ -57,11 +61,20 @@ export function band(options: BandOptions): SeriesDef {return null;}const areaGen = d3Area<ResolvedPoint>()+ .defined(+ d =>+ Number.isFinite(d.px) &&+ Number.isFinite(d.py) &&+ Number.isFinite(d.py0),+ ).x(d => d.px).y0(d => d.py0).y1(d => d.py).curve(curveMonotoneX);const pathD = areaGen(resolved) ?? '';+ if (!pathD) {+ return null;+ }return (<path d={pathD} fill={color} fillOpacity={opacity} stroke="none" />);diff --git a/packages/lab/src/ChartV2/marks/bar.tsx b/packages/charts/src/marks/bar.tsxsimilarity index 52%rename from packages/lab/src/ChartV2/marks/bar.tsxrename to packages/charts/src/marks/bar.tsxindex 847ea5fa66..9f4a18410e 100644--- a/packages/lab/src/ChartV2/marks/bar.tsx+++ b/packages/charts/src/marks/bar.tsx@@ -4,14 +4,17 @@* @file marks/bar.tsx* @output Bar series — self-contained resolve + render* @position Standalone mark; chart root calls resolve() then render()+ *+ * Robust to missing/NaN values (bars with no finite height are skipped rather+ * than drawn at the baseline) and to degenerate bandwidths (grouped bar widths+ * are clamped to a non-negative value). Negative values grow downward from zero.*/-import type {SeriesDef, ResolvedPoint} from '../types';+import type {SeriesDef, ResolvedPoint, ColorAccessor} from '../types';import type {ScaleBand} from 'd3-scale';+import {pointFill} from '../markColor';-export type ColorAccessor =- | string- | ((datum: Record<string, unknown>, index: number) => string);+export type {ColorAccessor};export interface BarOptions {color?: ColorAccessor;@@ -22,9 +25,34 @@ export interface BarOptions {label?: string;}+/** Clamp a user opacity into [0,1], falling back when it isn't a finite number. */+function clampOpacity(value: number | undefined, fallback: number): number {+ const n =+ typeof value === 'number' && Number.isFinite(value) ? value : fallback;+ return Math.min(1, Math.max(0, n));+}++/** Coerce a user length (radius/width) to a finite, non-negative number. */+function nonNegative(value: number | undefined, fallback: number): number {+ return typeof value === 'number' && Number.isFinite(value)+ ? Math.max(0, value)+ : fallback;+}++/** True when every coordinate is finite — a NaN/Infinity would corrupt the path. */+function rectIsFinite(x: number, y: number, w: number, h: number): boolean {+ return (+ Number.isFinite(x) &&+ Number.isFinite(y) &&+ Number.isFinite(w) &&+ Number.isFinite(h)+ );+}+/*** Build an SVG path for a rectangle with only the top corners rounded.- * When `r` is 0, produces a simple rect path with no curves.+ * When `r` is 0, produces a simple rect path with no curves. Returns an empty+ * path (draws nothing) if any coordinate is non-finite.*/function roundedTopRect(x: number,@@ -33,9 +61,12 @@ function roundedTopRect(h: number,r: number,): string {+ if (!rectIsFinite(x, y, w, h)) {+ return '';+ }// Clamp radius to half the smaller dimensionconst cr = Math.min(r, w / 2, h / 2);- if (cr <= 0) {+ if (!(cr > 0)) {return `M${x},${y + h}V${y}H${x + w}V${y + h}Z`;}return (@@ -48,6 +79,7 @@ function roundedTopRect(/*** Build an SVG path for a rectangle with only the bottom corners rounded.+ * Returns an empty path if any coordinate is non-finite.*/function roundedBottomRect(x: number,@@ -56,8 +88,11 @@ function roundedBottomRect(h: number,r: number,): string {+ if (!rectIsFinite(x, y, w, h)) {+ return '';+ }const cr = Math.min(r, w / 2, h / 2);- if (cr <= 0) {+ if (!(cr > 0)) {return `M${x},${y}V${y + h}H${x + w}V${y}Z`;}return (@@ -69,9 +104,9 @@ function roundedBottomRect(}export function bar(dataKey: string, options: BarOptions = {}): SeriesDef {- const color = options.color ?? 'var(--color-chart-1)';- const opacity = options.opacity ?? 1;- const radius = options.radius ?? 4;+ const color = options.color;+ const opacity = clampOpacity(options.opacity, 1);+ const radius = nonNegative(options.radius, 4);let barWidth = 0;let barOffset = 0;@@ -97,10 +132,12 @@ export function bar(dataKey: string, options: BarOptions = {}): SeriesDef {const bandScale = xScale as ScaleBand<string>;const bw = bandScale.bandwidth();- if (groupInfo) {+ if (groupInfo && groupInfo.count > 0) {const gutter = bw * 0.05;const totalGutters = gutter * (groupInfo.count - 1);- barWidth = (bw - totalGutters) / groupInfo.count;+ // Clamp: with many groups in a narrow band, gutters can exceed the band+ // and drive the raw width negative — a negative width mirrors the path.+ barWidth = Math.max(0, (bw - totalGutters) / groupInfo.count);barOffset = groupInfo.index * (barWidth + gutter);} else {barWidth = bw;@@ -110,16 +147,20 @@ export function bar(dataKey: string, options: BarOptions = {}): SeriesDef {const points: ResolvedPoint[] = [];for (let i = 0; i < data.length; i++) {const d = data[i];- const xBase = bandScale(String(d[xKey])) ?? 0;- const px = xBase + barOffset + barWidth / 2;+ // Unknown categories aren't in the band domain → NaN px so render skips+ // them rather than stacking phantom bars at the origin.+ const xBase = bandScale(String(d[xKey]));+ const px = xBase == null ? NaN : xBase + barOffset + barWidth / 2;let py: number;let py0: number;if (stackOffsets) {- py = yScale(stackOffsets[i].y1);- py0 = yScale(stackOffsets[i].y0);+ const offset = stackOffsets[i];+ py = offset ? yScale(offset.y1) : NaN;+ py0 = offset ? yScale(offset.y0) : NaN;} else {- const v = typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;+ const raw = d[dataKey];+ const v = typeof raw === 'number' && Number.isFinite(raw) ? raw : NaN;py = yScale(v);py0 = yScale(0);}@@ -132,13 +173,23 @@ export function bar(dataKey: string, options: BarOptions = {}): SeriesDef {const {data} = ctx;const isTop = seriesDef._isTopOfStack !== false;const r = isTop ? radius : 0;+ if (!(barWidth > 0)) {+ return null;+ }return (<g opacity={opacity}>- {resolved.map((p, i) => {+ {resolved.map(p => {const d = data[p.dataIndex];- const fill =- typeof color === 'function' ? color(d, p.dataIndex) : color;+ if (+ !d ||+ !Number.isFinite(p.px) ||+ !Number.isFinite(p.py) ||+ !Number.isFinite(p.py0)+ ) {+ return null;+ }+ const fill = pointFill(seriesDef, color, d, p.dataIndex);const x = p.px - barWidth / 2;const y = Math.min(p.py, p.py0);const h = Math.max(0, Math.abs(p.py0 - p.py));@@ -148,7 +199,7 @@ export function bar(dataKey: string, options: BarOptions = {}): SeriesDef {? roundedTopRect(x, y, barWidth, h, r): roundedBottomRect(x, y, barWidth, h, r);- return <path key={i} d={d_attr} fill={fill} />;+ return <path key={p.dataIndex} d={d_attr} fill={fill} />;})}</g>);diff --git a/packages/charts/src/marks/candlestick.tsx b/packages/charts/src/marks/candlestick.tsxnew file mode 100644index 0000000000..9e9db9e2b3--- /dev/null+++ b/packages/charts/src/marks/candlestick.tsx@@ -0,0 +1,131 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file marks/candlestick.tsx+ * @output Candlestick (OHLC) series. Renders on both band and linear/time x+ * scales; candles missing any OHLC field are skipped rather than drawn to 0.+ */++import type {SeriesDef, ResolvedPoint, SeriesContext} from '../types';+import type {ScaleBand} from 'd3-scale';++export interface CandlestickOptions {+ open: string;+ high: string;+ low: string;+ close: string;+ upColor?: string;+ downColor?: string;+}++/** Read a datum field as a finite number, or NaN when missing/non-numeric. */+function readNumber(d: Record<string, unknown>, key: string): number {+ const v = d[key];+ return typeof v === 'number' && Number.isFinite(v) ? v : NaN;+}++/**+ * Pixel width of one candle body. On a band scale this is the bandwidth; on a+ * linear/time scale it's derived from the smallest gap between adjacent points+ * (falling back to a modest width when there's only one point).+ */+function candleSlot(resolved: ResolvedPoint[], ctx: SeriesContext): number {+ const {xScale, width} = ctx;+ if ('bandwidth' in xScale) {+ return (xScale as ScaleBand<string>).bandwidth();+ }+ const xs = resolved+ .map(p => p.px)+ .filter(x => Number.isFinite(x))+ .sort((a, b) => a - b);+ let minGap = Infinity;+ for (let i = 1; i < xs.length; i++) {+ const gap = xs[i] - xs[i - 1];+ if (gap > 0 && gap < minGap) {+ minGap = gap;+ }+ }+ return Number.isFinite(minGap) ? minGap : Math.min(width, 40);+}++export function candlestick(options: CandlestickOptions): SeriesDef {+ // Emitted core semantic tokens (data-viz --color-data-* tokens aren't CSS vars).+ const upColor = options.upColor ?? 'var(--color-success)';+ const downColor = options.downColor ?? 'var(--color-error)';++ return {+ type: 'candlestick',+ key: `ohlc-${options.close}`,+ dataKeys: [options.open, options.high, options.low, options.close],+ layout: {},++ resolve(ctx) {+ const {data, xKey, xScale, yScale} = ctx;+ const points: ResolvedPoint[] = [];+ for (let i = 0; i < data.length; i++) {+ const d = data[i];+ let px: number;+ if ('bandwidth' in xScale) {+ px =+ ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) ++ (xScale as ScaleBand<string>).bandwidth() / 2;+ } else {+ px = xScale(d[xKey] as number);+ }+ const close = readNumber(d, options.close);+ points.push({px, py: yScale(close), py0: yScale(0), dataIndex: i});+ }+ return points;+ },++ render(resolved, ctx) {+ const {data, yScale} = ctx;+ const bodyWidth = Math.max(1, candleSlot(resolved, ctx) * 0.6);++ return (+ <g>+ {resolved.map(p => {+ const d = data[p.dataIndex];+ const o = readNumber(d, options.open);+ const c = readNumber(d, options.close);+ const h = readNumber(d, options.high);+ const l = readNumber(d, options.low);+ // Drop candles missing any OHLC field (or an unplaceable x) — a gap+ // reads more honestly than a full-height candle anchored at 0.+ if (+ !Number.isFinite(p.px) ||+ !Number.isFinite(o) ||+ !Number.isFinite(c) ||+ !Number.isFinite(h) ||+ !Number.isFinite(l)+ ) {+ return null;+ }+ const col = c >= o ? upColor : downColor;+ const bodyTop = yScale(Math.max(o, c));+ const bodyHeight = Math.max(1, Math.abs(yScale(o) - yScale(c)));+ return (+ <g key={p.dataIndex}>+ <line+ x1={p.px}+ x2={p.px}+ y1={yScale(h)}+ y2={yScale(l)}+ stroke={col}+ strokeWidth={1}+ />+ <rect+ x={p.px - bodyWidth / 2}+ y={bodyTop}+ width={bodyWidth}+ height={bodyHeight}+ fill={col}+ />+ </g>+ );+ })}+ </g>+ );+ },+ };+}diff --git a/packages/charts/src/marks/dot.tsx b/packages/charts/src/marks/dot.tsxnew file mode 100644index 0000000000..6bd7399ee0--- /dev/null+++ b/packages/charts/src/marks/dot.tsx@@ -0,0 +1,116 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file marks/dot.tsx+ * @output Dot/scatter series — self-contained resolve + render+ *+ * Points with missing / non-finite values are skipped rather than plotted at the+ * baseline. Optional `dodge` spreads coincident points horizontally, ignoring+ * non-finite ones so a single missing value can't collapse a whole dodge group.+ */++import type {SeriesDef, ResolvedPoint, ColorAccessor} from '../types';+import {pointFill} from '../markColor';+import {xPixel} from '../utils';++export type {ColorAccessor};++export interface DotOptions {+ color?: ColorAccessor;+ radius?: number;+ opacity?: number;+ dodge?: boolean;+ label?: string;+}++export function dot(dataKey: string, options: DotOptions = {}): SeriesDef {+ const color = options.color;+ const radius =+ typeof options.radius === 'number' && Number.isFinite(options.radius)+ ? Math.max(0, options.radius)+ : 4;+ const opacity =+ typeof options.opacity === 'number' && Number.isFinite(options.opacity)+ ? Math.min(1, Math.max(0, options.opacity))+ : 0.8;+ const dodge = options.dodge ?? false;++ const seriesDef: SeriesDef = {+ type: 'dot',+ key: dataKey,+ dataKeys: [dataKey],+ color: typeof color === 'string' ? color : undefined,+ label: options.label ?? dataKey,+ layout: {},++ resolve(ctx) {+ const {data, xKey, xScale, yScale} = ctx;+ const points: ResolvedPoint[] = [];+ for (let i = 0; i < data.length; i++) {+ const d = data[i];+ const raw = d[dataKey];+ const v = typeof raw === 'number' && Number.isFinite(raw) ? raw : NaN;+ points.push({+ px: xPixel(d, xKey, xScale),+ py: yScale(v),+ py0: yScale(0),+ dataIndex: i,+ });+ }++ if (dodge) {+ // Spread points that land on the same x (e.g. dots over band categories)+ // horizontally so they don't overlap, centered on the original x.+ const groups = new Map<number, ResolvedPoint[]>();+ for (const p of points) {+ if (!Number.isFinite(p.px)) {+ continue;+ }+ const key = Math.round(p.px);+ const group = groups.get(key) ?? [];+ group.push(p);+ groups.set(key, group);+ }+ const spacing = radius * 2 + 1;+ for (const group of groups.values()) {+ if (group.length < 2) {+ continue;+ }+ const mid = (group.length - 1) / 2;+ group.forEach((p, idx) => {+ p.px += (idx - mid) * spacing;+ });+ }+ }++ return points;+ },++ render(resolved, ctx) {+ const {data} = ctx;+ return (+ <g>+ {resolved.map(p => {+ const d = data[p.dataIndex];+ if (!d || !Number.isFinite(p.px) || !Number.isFinite(p.py)) {+ return null;+ }+ const fill = pointFill(seriesDef, color, d, p.dataIndex);+ return (+ <circle+ key={p.dataIndex}+ cx={p.px}+ cy={p.py}+ r={radius}+ fill={fill}+ opacity={opacity}+ />+ );+ })}+ </g>+ );+ },+ };++ return seriesDef;+}diff --git a/packages/lab/src/ChartV2/marks/dotGL.tsx b/packages/charts/src/marks/dotGL.tsxsimilarity index 53%rename from packages/lab/src/ChartV2/marks/dotGL.tsxrename to packages/charts/src/marks/dotGL.tsxindex 1b7d54d065..cdd981e4f2 100644--- a/packages/lab/src/ChartV2/marks/dotGL.tsx+++ b/packages/charts/src/marks/dotGL.tsx@@ -3,12 +3,15 @@/*** @file marks/dotGL.tsx* @output WebGL scatter — canvas overlay, single draw call+ *+ * GL context, program, and vertex buffer are created once and reused across+ * redraws; all are released (and the context eagerly lost) on unmount. Handles+ * context loss/restore and skips non-finite points.*/-import {useRef, useEffect, useCallback} from 'react';+import {useRef, useEffect, useMemo, useState} from 'react';import type {SeriesDef, ResolvedPoint} from '../types';import type {ScaleBand} from 'd3-scale';-import {useChartV2} from '../ChartV2Context';import {hexToGL,getWebGLContext,@@ -16,8 +19,10 @@ import {sizeCanvas,mountCanvasOverSVG,createProgram,+ registerContextLossHandlers,+ loseContext,POINT_SIZE_COMPENSATION,-} from '../../Chart/webgl';+} from '../webgl';export interface DotGLOptions {color: string;@@ -50,9 +55,18 @@ const FRAG = `}`;+type DotGLLocations = {+ aPosition: number;+ uResolution: WebGLUniformLocation | null;+ uColor: WebGLUniformLocation | null;+ uSize: WebGLUniformLocation | null;+ uOpacity: WebGLUniformLocation | null;+};+/**- * Inline component returned by render() — manages the WebGL canvas lifecycle.- * Needs access to svgRef from ChartV2Context to mount the canvas outside SVG.+ * Inline component returned by render() — owns the WebGL canvas lifecycle. The+ * canvas is mounted as a sibling of the SVG (via a marker <g>) for sharp Retina+ * output without foreignObject blur.*/function DotGLCanvas({resolved,@@ -69,21 +83,27 @@ function DotGLCanvas({width: number;height: number;}) {- const {svgRef: _svgRef} = useChartV2();const canvasRef = useRef<HTMLCanvasElement | null>(null);const glRef = useRef<WebGLRenderingContext | null>(null);const programRef = useRef<WebGLProgram | null>(null);+ const bufferRef = useRef<WebGLBuffer | null>(null);+ const locsRef = useRef<DotGLLocations | null>(null);const markerRef = useRef<SVGGElement>(null);+ // Bumped on context restore to force the draw effect to rebuild + repaint.+ const [contextEpoch, setContextEpoch] = useState(0);- const getPositions = useCallback((): Float32Array => {- const positions: number[] = [];+ const positions = useMemo(() => {+ const out: number[] = [];for (const p of resolved) {- positions.push(p.px, p.py);+ if (Number.isFinite(p.px) && Number.isFinite(p.py)) {+ out.push(p.px, p.py);+ }}- return new Float32Array(positions);+ return new Float32Array(out);}, [resolved]);- // Mount canvas outside SVG+ // Mount the canvas outside the SVG and wire context-loss recovery. The canvas+ // element persists across resizes; only its DOM attachment is re-established.useEffect(() => {const marker = markerRef.current;if (!marker) {@@ -92,10 +112,26 @@ function DotGLCanvas({if (!canvasRef.current) {canvasRef.current = document.createElement('canvas');}- return mountCanvasOverSVG(marker, canvasRef.current, width, height);+ const canvas = canvasRef.current;+ const detach = mountCanvasOverSVG(marker, canvas, width, height);+ const unregister = registerContextLossHandlers(+ canvas,+ () => {+ glRef.current = null;+ programRef.current = null;+ bufferRef.current = null;+ locsRef.current = null;+ },+ () => setContextEpoch(e => e + 1),+ );+ return () => {+ unregister();+ detach?.();+ };}, [width, height]);- // Draw+ // Draw. The context, program, and buffer are created lazily once and reused;+ // only vertex data + uniforms are re-uploaded per redraw.useEffect(() => {const canvas = canvasRef.current;if (!canvas || width <= 0 || height <= 0) {@@ -108,39 +144,75 @@ function DotGLCanvas({glRef.current = getWebGLContext(canvas);}const gl = glRef.current;- if (!gl) {+ if (!gl || gl.isContextLost()) {return;}if (!programRef.current) {programRef.current = createProgram(gl, VERT, FRAG);+ locsRef.current = null;}const program = programRef.current;if (!program) {return;}+ if (!bufferRef.current) {+ bufferRef.current = gl.createBuffer();+ }+ const buffer = bufferRef.current;+ if (!buffer) {+ return;+ }++ if (!locsRef.current) {+ locsRef.current = {+ aPosition: gl.getAttribLocation(program, 'a_position'),+ uResolution: gl.getUniformLocation(program, 'u_resolution'),+ uColor: gl.getUniformLocation(program, 'u_color'),+ uSize: gl.getUniformLocation(program, 'u_size'),+ uOpacity: gl.getUniformLocation(program, 'u_opacity'),+ };+ }+ const locs = locsRef.current;+gl.viewport(0, 0, canvas.width, canvas.height);setupGLState(gl);gl.useProgram(program);- const positions = getPositions();- const posBuffer = gl.createBuffer();- gl.bindBuffer(gl.ARRAY_BUFFER, posBuffer);+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);- const aPos = gl.getAttribLocation(program, 'a_position');- gl.enableVertexAttribArray(aPos);- gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);+ gl.enableVertexAttribArray(locs.aPosition);+ gl.vertexAttribPointer(locs.aPosition, 2, gl.FLOAT, false, 0, 0);const [r, g, b] = hexToGL(color);- gl.uniform2f(gl.getUniformLocation(program, 'u_resolution'), width, height);- gl.uniform3f(gl.getUniformLocation(program, 'u_color'), r, g, b);- gl.uniform1f(gl.getUniformLocation(program, 'u_size'), size * dpr);- gl.uniform1f(gl.getUniformLocation(program, 'u_opacity'), opacity);+ gl.uniform2f(locs.uResolution, width, height);+ gl.uniform3f(locs.uColor, r, g, b);+ gl.uniform1f(locs.uSize, size * dpr);+ gl.uniform1f(locs.uOpacity, opacity);gl.drawArrays(gl.POINTS, 0, positions.length / 2);- gl.deleteBuffer(posBuffer);- }, [width, height, color, size, opacity, getPositions]);+ }, [width, height, color, size, opacity, positions, contextEpoch]);++ // Release all GL resources on unmount.+ useEffect(() => {+ return () => {+ const gl = glRef.current;+ if (gl) {+ if (bufferRef.current) {+ gl.deleteBuffer(bufferRef.current);+ }+ if (programRef.current) {+ gl.deleteProgram(programRef.current);+ }+ loseContext(gl);+ }+ glRef.current = null;+ programRef.current = null;+ bufferRef.current = null;+ locsRef.current = null;+ };+ }, []);if (width <= 0 || height <= 0) {return null;diff --git a/packages/lab/src/ChartV2/marks/dotGLInteractive.tsx b/packages/charts/src/marks/dotGLInteractive.tsxsimilarity index 50%rename from packages/lab/src/ChartV2/marks/dotGLInteractive.tsxrename to packages/charts/src/marks/dotGLInteractive.tsxindex 9969e71e0b..648c03552a 100644--- a/packages/lab/src/ChartV2/marks/dotGLInteractive.tsx+++ b/packages/charts/src/marks/dotGLInteractive.tsx@@ -6,6 +6,11 @@** Each point gets a unique color encoding its index. On hover, readPixels* from an offscreen framebuffer decodes the hovered index — no JS iteration.+ *+ * Two GL contexts (visible + offscreen pick) plus their programs, buffers,+ * framebuffer, and pick texture are created once and reused. The pick texture+ * is re-allocated only when the drawing-buffer size changes, and everything is+ * released (both contexts eagerly lost) on unmount. Recovers from context loss.*/import {@@ -18,7 +23,12 @@ import {} from 'react';import type {SeriesDef, ResolvedPoint} from '../types';import type {ScaleBand} from 'd3-scale';-import {hexToGL} from '../../Chart/webgl';+import {+ hexToGL,+ createProgram,+ registerContextLossHandlers,+ loseContext,+} from '../webgl';export interface DotGLInteractiveOptions {color: string;@@ -28,6 +38,13 @@ export interface DotGLInteractiveOptions {renderTooltip?: (datum: Record<string, unknown>, index: number) => ReactNode;}+/**+ * Extra radius (CSS px) added to each point in the pick pass only, so hover+ * feels "magnetic" — you don't have to land pixel-perfectly on a small dot.+ * The visible pass is unaffected, so dots still render at their real size.+ */+const HIT_PADDING = 16;+/** Encode a point index as an RGB color (supports up to 16.7M points) */function indexToColor(i: number): [number, number, number] {const id = i + 1;@@ -46,48 +63,6 @@ function colorToIndex(r: number, g: number, b: number): number {return ((r << 16) | (g << 8) | b) - 1;}-function compileShader(- gl: WebGLRenderingContext,- type: number,- src: string,-): WebGLShader | null {- const s = gl.createShader(type);- if (!s) {- return null;- }- gl.shaderSource(s, src);- gl.compileShader(s);- if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {- gl.deleteShader(s);- return null;- }- return s;-}--function linkProgram(- gl: WebGLRenderingContext,- vert: string,- frag: string,-): WebGLProgram | null {- const vs = compileShader(gl, gl.VERTEX_SHADER, vert);- const fs = compileShader(gl, gl.FRAGMENT_SHADER, frag);- if (!vs || !fs) {- return null;- }- const p = gl.createProgram();- if (!p) {- return null;- }- gl.attachShader(p, vs);- gl.attachShader(p, fs);- gl.linkProgram(p);- if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {- gl.deleteProgram(p);- return null;- }- return p;-}-// Visible passconst VERT_VIS = `attribute vec2 a_position;@@ -121,7 +96,7 @@ const VERT_PICK = `void main() {vec2 clip = (a_position / u_resolution) * 2.0 - 1.0;gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);- gl_PointSize = u_size + 4.0;+ gl_PointSize = u_size;v_pickColor = a_pickColor;}`;@@ -162,47 +137,72 @@ function DotGLInteractiveCanvas({const pickCanvasRef = useRef<HTMLCanvasElement>(null);const [hoverIndex, setHoverIndex] = useState<number>(-1);const [mousePos, setMousePos] = useState<{x: number; y: number} | null>(null);+ // Bumped on context restore to force the render effect to rebuild + repaint.+ const [contextEpoch, setContextEpoch] = useState(0);const visGLRef = useRef<{gl: WebGLRenderingContext;prog: WebGLProgram;} | null>(null);+ const visBufRef = useRef<WebGLBuffer | null>(null);const pickGLRef = useRef<{gl: WebGLRenderingContext;prog: WebGLProgram;fb: WebGLFramebuffer;tex: WebGLTexture;+ // Drawing-buffer size the pick texture is currently allocated for, and the+ // DPR it was built with — used to avoid needless re-allocation and to keep+ // hover pixel math consistent with the framebuffer.+ texW: number;+ texH: number;+ dpr: number;} | null>(null);+ const pickPosBufRef = useRef<WebGLBuffer | null>(null);+ const pickColBufRef = useRef<WebGLBuffer | null>(null);+ // Positions and pick colors are index-aligned with `resolved` (and thus with+ // `data`); do NOT drop entries here or hover decode would map to wrong rows.+ // Non-finite points get NaN clip positions and simply don't rasterize.const positions = useMemo(() => {- const pos: number[] = [];- for (const p of resolved) {- pos.push(p.px, p.py);+ const pos = new Float32Array(resolved.length * 2);+ for (let i = 0; i < resolved.length; i++) {+ pos[i * 2] = resolved[i].px;+ pos[i * 2 + 1] = resolved[i].py;}- return new Float32Array(pos);+ return pos;}, [resolved]);const pickColors = useMemo(() => {- const colors: number[] = [];+ const colors = new Float32Array(resolved.length * 3);for (let i = 0; i < resolved.length; i++) {const [r, g, b] = indexToColor(i);- colors.push(r, g, b);+ colors[i * 3] = r;+ colors[i * 3 + 1] = g;+ colors[i * 3 + 2] = b;}- return new Float32Array(colors);+ return colors;}, [resolved.length]);- // Render both passes+ // Render both passes. Contexts, programs, buffers, framebuffer, and pick+ // texture are created once and reused; only vertex data + uniforms upload per+ // run, and the pick texture re-allocates only when the buffer size changes.useEffect(() => {if (width <= 0 || height <= 0) {return;}const dpr = window.devicePixelRatio || 1;+ const bufW = Math.max(1, Math.round(width * dpr));+ const bufH = Math.max(1, Math.round(height * dpr));- // Visible canvas+ // ── Visible pass ──const visCanvas = visCanvasRef.current;if (visCanvas) {- visCanvas.width = width * dpr;- visCanvas.height = height * dpr;+ if (visCanvas.width !== bufW) {+ visCanvas.width = bufW;+ }+ if (visCanvas.height !== bufH) {+ visCanvas.height = bufH;+ }if (!visGLRef.current) {const gl = visCanvas.getContext('webgl', {@@ -210,49 +210,58 @@ function DotGLInteractiveCanvas({premultipliedAlpha: false,antialias: true,});- const prog = gl ? linkProgram(gl, VERT_VIS, FRAG_VIS) : null;+ const prog = gl ? createProgram(gl, VERT_VIS, FRAG_VIS) : null;if (gl && prog) {visGLRef.current = {gl, prog};+ visBufRef.current = null;}}const vis = visGLRef.current;- if (vis) {+ if (vis && !vis.gl.isContextLost()) {const {gl, prog} = vis;- gl.viewport(0, 0, visCanvas.width, visCanvas.height);- gl.clearColor(0, 0, 0, 0);- gl.clear(gl.COLOR_BUFFER_BIT);- gl.enable(gl.BLEND);- gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);- gl.useProgram(prog);-- const buf = gl.createBuffer();- gl.bindBuffer(gl.ARRAY_BUFFER, buf);- gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);- const aPos = gl.getAttribLocation(prog, 'a_position');- gl.enableVertexAttribArray(aPos);- gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);-- const [r, g, b] = hexToGL(color);- gl.uniform2f(- gl.getUniformLocation(prog, 'u_resolution'),- width,- height,- );- gl.uniform3f(gl.getUniformLocation(prog, 'u_color'), r, g, b);- gl.uniform1f(gl.getUniformLocation(prog, 'u_size'), size * dpr);- gl.uniform1f(gl.getUniformLocation(prog, 'u_opacity'), opacity);-- gl.drawArrays(gl.POINTS, 0, positions.length / 2);- gl.deleteBuffer(buf);+ if (!visBufRef.current) {+ visBufRef.current = gl.createBuffer();+ }+ const buf = visBufRef.current;+ if (buf) {+ gl.viewport(0, 0, visCanvas.width, visCanvas.height);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);+ gl.useProgram(prog);++ gl.bindBuffer(gl.ARRAY_BUFFER, buf);+ gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);+ const aPos = gl.getAttribLocation(prog, 'a_position');+ gl.enableVertexAttribArray(aPos);+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);++ const [r, g, b] = hexToGL(color);+ gl.uniform2f(+ gl.getUniformLocation(prog, 'u_resolution'),+ width,+ height,+ );+ gl.uniform3f(gl.getUniformLocation(prog, 'u_color'), r, g, b);+ gl.uniform1f(gl.getUniformLocation(prog, 'u_size'), size * dpr);+ gl.uniform1f(gl.getUniformLocation(prog, 'u_opacity'), opacity);++ gl.drawArrays(gl.POINTS, 0, positions.length / 2);+ }}}- // Pick canvas (offscreen)+ // ── Pick pass (offscreen framebuffer) ──const pickCanvas = pickCanvasRef.current;if (pickCanvas) {- pickCanvas.width = width * dpr;- pickCanvas.height = height * dpr;+ if (pickCanvas.width !== bufW) {+ pickCanvas.width = bufW;+ }+ if (pickCanvas.height !== bufH) {+ pickCanvas.height = bufH;+ }if (!pickGLRef.current) {const gl = pickCanvas.getContext('webgl', {@@ -262,22 +271,11 @@ function DotGLInteractiveCanvas({preserveDrawingBuffer: true,});if (gl) {- const prog = linkProgram(gl, VERT_PICK, FRAG_PICK);+ const prog = createProgram(gl, VERT_PICK, FRAG_PICK);const fb = gl.createFramebuffer();const tex = gl.createTexture();if (prog && fb && tex) {gl.bindTexture(gl.TEXTURE_2D, tex);- gl.texImage2D(- gl.TEXTURE_2D,- 0,- gl.RGBA,- pickCanvas.width,- pickCanvas.height,- 0,- gl.RGBA,- gl.UNSIGNED_BYTE,- null,- );gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);gl.bindFramebuffer(gl.FRAMEBUFFER, fb);@@ -289,67 +287,165 @@ function DotGLInteractiveCanvas({0,);gl.bindFramebuffer(gl.FRAMEBUFFER, null);- pickGLRef.current = {gl, prog, fb, tex};+ pickGLRef.current = {gl, prog, fb, tex, texW: 0, texH: 0, dpr};+ pickPosBufRef.current = null;+ pickColBufRef.current = null;}}}const pick = pickGLRef.current;- if (pick) {+ if (pick && !pick.gl.isContextLost()) {const {gl, prog, fb, tex} = pick;+ pick.dpr = dpr;++ // (Re)allocate the pick texture only when the buffer size changes.+ if (pick.texW !== pickCanvas.width || pick.texH !== pickCanvas.height) {+ gl.bindTexture(gl.TEXTURE_2D, tex);+ gl.texImage2D(+ gl.TEXTURE_2D,+ 0,+ gl.RGBA,+ pickCanvas.width,+ pickCanvas.height,+ 0,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ null,+ );+ pick.texW = pickCanvas.width;+ pick.texH = pickCanvas.height;+ }- gl.bindTexture(gl.TEXTURE_2D, tex);- gl.texImage2D(- gl.TEXTURE_2D,- 0,- gl.RGBA,- pickCanvas.width,- pickCanvas.height,- 0,- gl.RGBA,- gl.UNSIGNED_BYTE,- null,- );-- gl.bindFramebuffer(gl.FRAMEBUFFER, fb);- gl.viewport(0, 0, pickCanvas.width, pickCanvas.height);- gl.clearColor(0, 0, 0, 1);- gl.clear(gl.COLOR_BUFFER_BIT);- gl.disable(gl.BLEND);- gl.useProgram(prog);-- const posBuf = gl.createBuffer();- gl.bindBuffer(gl.ARRAY_BUFFER, posBuf);- gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);- const aPos = gl.getAttribLocation(prog, 'a_position');- gl.enableVertexAttribArray(aPos);- gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);-- const colBuf = gl.createBuffer();- gl.bindBuffer(gl.ARRAY_BUFFER, colBuf);- gl.bufferData(gl.ARRAY_BUFFER, pickColors, gl.STATIC_DRAW);- const aCol = gl.getAttribLocation(prog, 'a_pickColor');- gl.enableVertexAttribArray(aCol);- gl.vertexAttribPointer(aCol, 3, gl.FLOAT, false, 0, 0);-- gl.uniform2f(- gl.getUniformLocation(prog, 'u_resolution'),- width,- height,- );- gl.uniform1f(gl.getUniformLocation(prog, 'u_size'), (size + 4) * dpr);-- gl.drawArrays(gl.POINTS, 0, positions.length / 2);- gl.deleteBuffer(posBuf);- gl.deleteBuffer(colBuf);- gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ if (!pickPosBufRef.current) {+ pickPosBufRef.current = gl.createBuffer();+ }+ if (!pickColBufRef.current) {+ pickColBufRef.current = gl.createBuffer();+ }+ const posBuf = pickPosBufRef.current;+ const colBuf = pickColBufRef.current;++ if (posBuf && colBuf) {+ gl.bindFramebuffer(gl.FRAMEBUFFER, fb);+ gl.viewport(0, 0, pickCanvas.width, pickCanvas.height);+ gl.clearColor(0, 0, 0, 1);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.disable(gl.BLEND);+ gl.useProgram(prog);++ gl.bindBuffer(gl.ARRAY_BUFFER, posBuf);+ gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);+ const aPos = gl.getAttribLocation(prog, 'a_position');+ gl.enableVertexAttribArray(aPos);+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);++ gl.bindBuffer(gl.ARRAY_BUFFER, colBuf);+ gl.bufferData(gl.ARRAY_BUFFER, pickColors, gl.STATIC_DRAW);+ const aCol = gl.getAttribLocation(prog, 'a_pickColor');+ gl.enableVertexAttribArray(aCol);+ gl.vertexAttribPointer(aCol, 3, gl.FLOAT, false, 0, 0);++ gl.uniform2f(+ gl.getUniformLocation(prog, 'u_resolution'),+ width,+ height,+ );+ gl.uniform1f(+ gl.getUniformLocation(prog, 'u_size'),+ (size + HIT_PADDING) * dpr,+ );++ gl.drawArrays(gl.POINTS, 0, positions.length / 2);+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ }}}- }, [width, height, positions, pickColors, color, size, opacity]);+ }, [+ width,+ height,+ positions,+ pickColors,+ color,+ size,+ opacity,+ contextEpoch,+ ]);++ // Register context-loss recovery for both canvases (runs once post-mount).+ useEffect(() => {+ const cleanups: Array<() => void> = [];+ const visCanvas = visCanvasRef.current;+ if (visCanvas) {+ cleanups.push(+ registerContextLossHandlers(+ visCanvas,+ () => {+ visGLRef.current = null;+ visBufRef.current = null;+ },+ () => setContextEpoch(e => e + 1),+ ),+ );+ }+ const pickCanvas = pickCanvasRef.current;+ if (pickCanvas) {+ cleanups.push(+ registerContextLossHandlers(+ pickCanvas,+ () => {+ pickGLRef.current = null;+ pickPosBufRef.current = null;+ pickColBufRef.current = null;+ },+ () => setContextEpoch(e => e + 1),+ ),+ );+ }+ return () => {+ for (const c of cleanups) {+ c();+ }+ };+ }, []);++ // Release both GL contexts and all their resources on unmount.+ useEffect(() => {+ return () => {+ const vis = visGLRef.current;+ if (vis) {+ const {gl, prog} = vis;+ if (visBufRef.current) {+ gl.deleteBuffer(visBufRef.current);+ }+ gl.deleteProgram(prog);+ loseContext(gl);+ }+ const pick = pickGLRef.current;+ if (pick) {+ const {gl, prog, fb, tex} = pick;+ if (pickPosBufRef.current) {+ gl.deleteBuffer(pickPosBufRef.current);+ }+ if (pickColBufRef.current) {+ gl.deleteBuffer(pickColBufRef.current);+ }+ gl.deleteFramebuffer(fb);+ gl.deleteTexture(tex);+ gl.deleteProgram(prog);+ loseContext(gl);+ }+ visGLRef.current = null;+ visBufRef.current = null;+ pickGLRef.current = null;+ pickPosBufRef.current = null;+ pickColBufRef.current = null;+ };+ }, []);const handleMouseMove = useCallback((e: React.MouseEvent<SVGRectElement>) => {const pick = pickGLRef.current;- if (!pick) {+ if (!pick || pick.gl.isContextLost()) {return;}@@ -357,27 +453,29 @@ function DotGLInteractiveCanvas({if (!svg) {return;}+ const ctm = e.currentTarget.getScreenCTM();+ if (!ctm) {+ return;+ }const pt = svg.createSVGPoint();pt.x = e.clientX;pt.y = e.clientY;- const local = pt.matrixTransform(e.currentTarget.getScreenCTM()?.inverse());+ const local = pt.matrixTransform(ctm.inverse());- const dpr = window.devicePixelRatio || 1;+ // Use the DPR the pick framebuffer was built with so pixel math stays in+ // sync even if devicePixelRatio changed since the last render.+ const {gl, fb, dpr, texW, texH} = pick;const px = Math.floor(local.x * dpr);const py = Math.floor(local.y * dpr);+ if (px < 0 || py < 0 || px >= texW || py >= texH) {+ setHoverIndex(-1);+ setMousePos(null);+ return;+ }- const {gl, fb} = pick;gl.bindFramebuffer(gl.FRAMEBUFFER, fb);const pixel = new Uint8Array(4);- gl.readPixels(- px,- gl.canvas.height - py,- 1,- 1,- gl.RGBA,- gl.UNSIGNED_BYTE,- pixel,- );+ gl.readPixels(px, texH - py, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);gl.bindFramebuffer(gl.FRAMEBUFFER, null);const idx = colorToIndex(pixel[0], pixel[1], pixel[2]);@@ -442,16 +540,28 @@ function DotGLInteractiveCanvas({/>{datum && hoverIndex >= 0 && (- <circle- cx={positions[hoverIndex * 2]}- cy={positions[hoverIndex * 2 + 1]}- r={size / 2 + 3}- fill="none"- stroke={color}- strokeWidth={2}- strokeOpacity={0.8}- pointerEvents="none"- />+ <g pointerEvents="none">+ {/* Soft outer halo — reads on top of neighbouring points. */}+ <circle+ cx={positions[hoverIndex * 2]}+ cy={positions[hoverIndex * 2 + 1]}+ r={size / 2 + 7}+ fill="none"+ stroke={color}+ strokeWidth={2}+ strokeOpacity={0.35}+ />+ {/* Solid marker with a white outline — unmistakable "you're on this+ point" affordance that stays visible on any background. */}+ <circle+ cx={positions[hoverIndex * 2]}+ cy={positions[hoverIndex * 2 + 1]}+ r={size / 2 + 2.5}+ fill={color}+ stroke="var(--color-background-body, #fff)"+ strokeWidth={2}+ />+ </g>)}{datum && mousePos && (diff --git a/packages/charts/src/marks/errorBar.tsx b/packages/charts/src/marks/errorBar.tsxnew file mode 100644index 0000000000..f25b2de9d9--- /dev/null+++ b/packages/charts/src/marks/errorBar.tsx@@ -0,0 +1,118 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file marks/errorBar.tsx+ * @output Error bar (whisker) series — vertical high/low bounds. Bounds are+ * absolute (so asymmetric intervals work); a point missing either bound is+ * skipped rather than drawn down to the axis.+ */++import type {SeriesDef, ResolvedPoint} from '../types';+import type {ScaleBand} from 'd3-scale';++export interface ErrorBarOptions {+ /** Data key for the upper bound */+ high: string;+ /** Data key for the lower bound */+ low: string;+ /** Stroke color */+ color?: string;+ /** Stroke width */+ strokeWidth?: number;+ /** Width of the whisker caps in pixels */+ capWidth?: number;+}++/**+ * Error bars with whisker caps. Pair with bar() or dot().+ *+ * @example+ * ```+ * series={[bar('mean'), errorBar({high: 'upper95', low: 'lower95'})]}+ * ```+ */+export function errorBar(options: ErrorBarOptions): SeriesDef {+ const {high, low} = options;+ const color = options.color ?? 'var(--color-text-primary)';+ const strokeWidth = options.strokeWidth ?? 1.5;+ const capWidth = options.capWidth ?? 8;++ return {+ type: 'errorBar',+ key: `errorBar-${high}-${low}`,+ dataKeys: [high, low],+ layout: {},++ resolve(ctx) {+ const {data, xKey, xScale, yScale} = ctx;+ const points: ResolvedPoint[] = [];+ for (let i = 0; i < data.length; i++) {+ const d = data[i];+ let px: number;+ if ('bandwidth' in xScale) {+ px =+ ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) ++ (xScale as ScaleBand<string>).bandwidth() / 2;+ } else {+ px = xScale(d[xKey] as number);+ }+ // NaN for a missing bound so render() skips the whole whisker instead+ // of anchoring a cap at the axis (a misleading zero-height error bar).+ const hiVal = d[high];+ const loVal = d[low];+ const upper = Number.isFinite(hiVal) ? (hiVal as number) : NaN;+ const lower = Number.isFinite(loVal) ? (loVal as number) : NaN;+ points.push({px, py: yScale(upper), py0: yScale(lower), dataIndex: i});+ }+ return points;+ },++ render(resolved) {+ const half = Math.max(0, capWidth) / 2;+ return (+ <g>+ {resolved.map(p => {+ if (+ !Number.isFinite(p.px) ||+ !Number.isFinite(p.py) ||+ !Number.isFinite(p.py0)+ ) {+ return null;+ }+ return (+ <g key={p.dataIndex}>+ {/* Vertical stem */}+ <line+ x1={p.px}+ x2={p.px}+ y1={p.py}+ y2={p.py0}+ stroke={color}+ strokeWidth={strokeWidth}+ />+ {/* Upper cap */}+ <line+ x1={p.px - half}+ x2={p.px + half}+ y1={p.py}+ y2={p.py}+ stroke={color}+ strokeWidth={strokeWidth}+ />+ {/* Lower cap */}+ <line+ x1={p.px - half}+ x2={p.px + half}+ y1={p.py0}+ y2={p.py0}+ stroke={color}+ strokeWidth={strokeWidth}+ />+ </g>+ );+ })}+ </g>+ );+ },+ };+}diff --git a/packages/lab/src/ChartV2/marks/heatmapGL.tsx b/packages/charts/src/marks/heatmapGL.tsxsimilarity index 59%rename from packages/lab/src/ChartV2/marks/heatmapGL.tsxrename to packages/charts/src/marks/heatmapGL.tsxindex b46c3fe953..da1dea8f4e 100644--- a/packages/lab/src/ChartV2/marks/heatmapGL.tsx+++ b/packages/charts/src/marks/heatmapGL.tsx@@ -3,9 +3,13 @@/*** @file marks/heatmapGL.tsx* @output WebGL heatmap — 2D grid of colored cells on canvas+ *+ * Cell geometry is memoized; GL context, program, and the position/color+ * buffers are created once and reused across redraws, then released (context+ * eagerly lost) on unmount. Handles context loss/restore and empty/NaN data.*/-import {useRef, useEffect, useMemo} from 'react';+import {useRef, useEffect, useMemo, useState} from 'react';import {scaleBand} from 'd3-scale';import type {SeriesDef, ResolvedPoint} from '../types';import type {ScaleBand} from 'd3-scale';@@ -16,7 +20,9 @@ import {sizeCanvas,mountCanvasOverSVG,createProgram,-} from '../../Chart/webgl';+ registerContextLossHandlers,+ loseContext,+} from '../webgl';export interface HeatmapGLOptions {xKey: string;@@ -51,7 +57,10 @@ function sampleRamp(ramp: [number, number, number][],t: number,): [number, number, number] {- const c = Math.max(0, Math.min(1, t));+ if (ramp.length === 0) {+ return [0, 0, 0];+ }+ const c = Math.max(0, Math.min(1, Number.isFinite(t) ? t : 0));if (ramp.length === 1) {return ramp[0];}@@ -66,6 +75,12 @@ function sampleRamp(];}+type HeatmapGLLocations = {+ aPosition: number;+ aColor: number;+ uResolution: WebGLUniformLocation | null;+};+/*** Inline component — manages the heatmap WebGL canvas and its own y band scale.*/@@ -95,7 +110,12 @@ function HeatmapGLCanvas({const canvasRef = useRef<HTMLCanvasElement | null>(null);const glRef = useRef<WebGLRenderingContext | null>(null);const programRef = useRef<WebGLProgram | null>(null);+ const posBufferRef = useRef<WebGLBuffer | null>(null);+ const colBufferRef = useRef<WebGLBuffer | null>(null);+ const locsRef = useRef<HeatmapGLLocations | null>(null);const markerRef = useRef<SVGGElement>(null);+ // Bumped on context restore to force the draw effect to rebuild + repaint.+ const [contextEpoch, setContextEpoch] = useState(0);const ramp = useMemo(() => colorRange.map(hexToGL), [colorRange]);@@ -112,7 +132,7 @@ function HeatmapGLCanvas({max = -Infinity;for (const d of data) {const v = d[valueKey];- if (typeof v === 'number') {+ if (typeof v === 'number' && Number.isFinite(v)) {if (v < min) {min = v;}@@ -121,10 +141,55 @@ function HeatmapGLCanvas({}}}+ // No finite values → neutral [0, 1] so t/ramp math never yields NaN.+ if (!Number.isFinite(min) || !Number.isFinite(max)) {+ return [0, 1];+ }return [min, max];}, [data, valueKey, domainProp]);- // Mount canvas outside SVG+ // Build interleaved triangle geometry (2 triangles/cell) + per-vertex colors.+ // Memoized so redraws (resize, context restore) don't re-walk the dataset.+ const geometry = useMemo(() => {+ const positions: number[] = [];+ const colors: number[] = [];+ const [dMin, dMax] = domain;+ const range = dMax - dMin || 1;+ const gap = cellGap;+ const xBW = xScale.bandwidth();+ const yBW = yBandScale.bandwidth();++ for (const d of data) {+ const xVal = xScale(String(d[xKey]));+ const yVal = yBandScale(String(d[yKey]));+ if (xVal == null || yVal == null) {+ continue;+ }++ const raw = d[valueKey];+ const v = typeof raw === 'number' && Number.isFinite(raw) ? raw : 0;+ const t = (v - dMin) / range;+ const [r, g, b] = sampleRamp(ramp, t);++ const x0 = xVal + gap / 2;+ const x1 = xVal + xBW - gap / 2;+ const y0 = yVal + gap / 2;+ const y1 = yVal + yBW - gap / 2;++ positions.push(x0, y0, x1, y0, x0, y1, x1, y0, x1, y1, x0, y1);+ for (let i = 0; i < 6; i++) {+ colors.push(r, g, b);+ }+ }++ return {+ positions: new Float32Array(positions),+ colors: new Float32Array(colors),+ vertexCount: positions.length / 2,+ };+ }, [data, xKey, yKey, valueKey, xScale, yBandScale, domain, ramp, cellGap]);++ // Mount the canvas outside the SVG and wire context-loss recovery.useEffect(() => {const marker = markerRef.current;if (!marker) {@@ -133,10 +198,26 @@ function HeatmapGLCanvas({if (!canvasRef.current) {canvasRef.current = document.createElement('canvas');}- return mountCanvasOverSVG(marker, canvasRef.current, width, height);+ const canvas = canvasRef.current;+ const detach = mountCanvasOverSVG(marker, canvas, width, height);+ const unregister = registerContextLossHandlers(+ canvas,+ () => {+ glRef.current = null;+ programRef.current = null;+ posBufferRef.current = null;+ colBufferRef.current = null;+ locsRef.current = null;+ },+ () => setContextEpoch(e => e + 1),+ );+ return () => {+ unregister();+ detach?.();+ };}, [width, height]);- // Draw+ // Draw. Context, program, and both buffers are created once and reused.useEffect(() => {const canvas = canvasRef.current;if (!canvas || width <= 0 || height <= 0) {@@ -149,85 +230,81 @@ function HeatmapGLCanvas({glRef.current = getWebGLContext(canvas);}const gl = glRef.current;- if (!gl) {+ if (!gl || gl.isContextLost()) {return;}if (!programRef.current) {programRef.current = createProgram(gl, VERT, FRAG);+ locsRef.current = null;}const program = programRef.current;if (!program) {return;}+ if (!posBufferRef.current) {+ posBufferRef.current = gl.createBuffer();+ }+ if (!colBufferRef.current) {+ colBufferRef.current = gl.createBuffer();+ }+ const posBuffer = posBufferRef.current;+ const colBuffer = colBufferRef.current;+ if (!posBuffer || !colBuffer) {+ return;+ }++ if (!locsRef.current) {+ locsRef.current = {+ aPosition: gl.getAttribLocation(program, 'a_position'),+ aColor: gl.getAttribLocation(program, 'a_color'),+ uResolution: gl.getUniformLocation(program, 'u_resolution'),+ };+ }+ const locs = locsRef.current;+gl.viewport(0, 0, canvas.width, canvas.height);setupGLState(gl);gl.useProgram(program);- const positions: number[] = [];- const colors: number[] = [];- const [dMin, dMax] = domain;- const range = dMax - dMin || 1;- const gap = cellGap;- const xBW = xScale.bandwidth();- const yBW = yBandScale.bandwidth();+ gl.bindBuffer(gl.ARRAY_BUFFER, posBuffer);+ gl.bufferData(gl.ARRAY_BUFFER, geometry.positions, gl.STATIC_DRAW);+ gl.enableVertexAttribArray(locs.aPosition);+ gl.vertexAttribPointer(locs.aPosition, 2, gl.FLOAT, false, 0, 0);- for (const d of data) {- const xVal = xScale(String(d[xKey]));- const yVal = yBandScale(String(d[yKey]));- if (xVal == null || yVal == null) {- continue;- }+ gl.bindBuffer(gl.ARRAY_BUFFER, colBuffer);+ gl.bufferData(gl.ARRAY_BUFFER, geometry.colors, gl.STATIC_DRAW);+ gl.enableVertexAttribArray(locs.aColor);+ gl.vertexAttribPointer(locs.aColor, 3, gl.FLOAT, false, 0, 0);- const v = typeof d[valueKey] === 'number' ? (d[valueKey] as number) : 0;- const t = (v - dMin) / range;- const [r, g, b] = sampleRamp(ramp, t);+ gl.uniform2f(locs.uResolution, width, height);+ gl.drawArrays(gl.TRIANGLES, 0, geometry.vertexCount);+ }, [geometry, width, height, contextEpoch]);- const x0 = xVal + gap / 2;- const x1 = xVal + xBW - gap / 2;- const y0 = yVal + gap / 2;- const y1 = yVal + yBW - gap / 2;-- // Two triangles per cell- positions.push(x0, y0, x1, y0, x0, y1, x1, y0, x1, y1, x0, y1);- for (let i = 0; i < 6; i++) {- colors.push(r, g, b);+ // Release all GL resources on unmount.+ useEffect(() => {+ return () => {+ const gl = glRef.current;+ if (gl) {+ if (posBufferRef.current) {+ gl.deleteBuffer(posBufferRef.current);+ }+ if (colBufferRef.current) {+ gl.deleteBuffer(colBufferRef.current);+ }+ if (programRef.current) {+ gl.deleteProgram(programRef.current);+ }+ loseContext(gl);}- }-- const posBuf = gl.createBuffer();- gl.bindBuffer(gl.ARRAY_BUFFER, posBuf);- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);- const aPos = gl.getAttribLocation(program, 'a_position');- gl.enableVertexAttribArray(aPos);- gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);-- const colBuf = gl.createBuffer();- gl.bindBuffer(gl.ARRAY_BUFFER, colBuf);- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);- const aCol = gl.getAttribLocation(program, 'a_color');- gl.enableVertexAttribArray(aCol);- gl.vertexAttribPointer(aCol, 3, gl.FLOAT, false, 0, 0);-- gl.uniform2f(gl.getUniformLocation(program, 'u_resolution'), width, height);- gl.drawArrays(gl.TRIANGLES, 0, positions.length / 2);-- gl.deleteBuffer(posBuf);- gl.deleteBuffer(colBuf);- }, [- data,- xKey,- yKey,- valueKey,- xScale,- yBandScale,- width,- height,- domain,- ramp,- cellGap,- ]);+ glRef.current = null;+ programRef.current = null;+ posBufferRef.current = null;+ colBufferRef.current = null;+ locsRef.current = null;+ };+ }, []);if (width <= 0 || height <= 0) {return null;diff --git a/packages/lab/src/ChartV2/marks/index.ts b/packages/charts/src/marks/index.tssimilarity index 88%rename from packages/lab/src/ChartV2/marks/index.tsrename to packages/charts/src/marks/index.tsindex 77250188bd..96ad673a38 100644--- a/packages/lab/src/ChartV2/marks/index.ts+++ b/packages/charts/src/marks/index.ts@@ -9,6 +9,9 @@ export {candlestick, type CandlestickOptions} from './candlestick';export {errorBar, type ErrorBarOptions} from './errorBar';export {referenceLine, type ReferenceLineOptions} from './referenceLine';export {dotGL, type DotGLOptions} from './dotGL';-export {dotGLInteractive, type DotGLInteractiveOptions} from './dotGLInteractive';+export {+ dotGLInteractive,+ type DotGLInteractiveOptions,+} from './dotGLInteractive';export {heatmapGL, type HeatmapGLOptions} from './heatmapGL';export {streamGL, type StreamGLOptions, type StreamGLHandle} from './streamGL';diff --git a/packages/lab/src/ChartV2/marks/line.tsx b/packages/charts/src/marks/line.tsxsimilarity index 52%rename from packages/lab/src/ChartV2/marks/line.tsxrename to packages/charts/src/marks/line.tsxindex e1f7a8115a..a6819cc056 100644--- a/packages/lab/src/ChartV2/marks/line.tsx+++ b/packages/charts/src/marks/line.tsx@@ -3,6 +3,10 @@/*** @file marks/line.tsx* @output Line series — self-contained resolve + render+ *+ * Missing / non-finite values become gaps (via d3's `.defined()`) instead of a+ * misleading drop to the baseline, and per-point dots are only drawn where the+ * point is finite.*/import {@@ -13,7 +17,8 @@ import {curveStep,} from 'd3-shape';import type {SeriesDef, ResolvedPoint} from '../types';-import type {ScaleBand} from 'd3-scale';+import {seriesFill} from '../markColor';+import {xPixel} from '../utils';const CURVES = {linear: curveLinear,@@ -31,13 +36,22 @@ export interface LineOptions {label?: string;}+/** A point is drawable only when both of its plotted coordinates are finite. */+function isFinitePoint(p: ResolvedPoint): boolean {+ return Number.isFinite(p.px) && Number.isFinite(p.py);+}+export function line(dataKey: string, options: LineOptions = {}): SeriesDef {- const color = options.color ?? 'var(--color-chart-1)';+ const color = options.color;const curve = options.curve ?? 'monotone';- const strokeWidth = options.strokeWidth ?? 2;+ const strokeWidth =+ typeof options.strokeWidth === 'number' &&+ Number.isFinite(options.strokeWidth)+ ? Math.max(0, options.strokeWidth)+ : 2;const dots = options.dots ?? false;- return {+ const seriesDef: SeriesDef = {type: 'line',key: dataKey,dataKeys: [dataKey],@@ -50,16 +64,14 @@ export function line(dataKey: string, options: LineOptions = {}): SeriesDef {const points: ResolvedPoint[] = [];for (let i = 0; i < data.length; i++) {const d = data[i];- let px: number;- if ('bandwidth' in xScale) {- px =- ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) +- (xScale as ScaleBand<string>).bandwidth() / 2;- } else {- px = xScale(d[xKey] as number);- }- const v = typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;- points.push({px, py: yScale(v), py0: yScale(0), dataIndex: i});+ const raw = d[dataKey];+ const v = typeof raw === 'number' && Number.isFinite(raw) ? raw : NaN;+ points.push({+ px: xPixel(d, xKey, xScale),+ py: yScale(v),+ py0: yScale(0),+ dataIndex: i,+ });}return points;},@@ -68,27 +80,39 @@ export function line(dataKey: string, options: LineOptions = {}): SeriesDef {if (resolved.length === 0) {return null;}- const curveFactory = CURVES[curve];+ const curveFactory = CURVES[curve] ?? curveMonotoneX;const pathGen = d3Line<ResolvedPoint>()+ .defined(isFinitePoint).x(d => d.px).y(d => d.py).curve(curveFactory);const pathD = pathGen(resolved) ?? '';+ const strokeColor = seriesFill(seriesDef, color);return (<g><pathd={pathD}fill="none"- stroke={color}+ stroke={strokeColor}strokeWidth={strokeWidth}/>{dots &&- resolved.map((p, i) => (- <circle key={i} cx={p.px} cy={p.py} r={3} fill={color} />- ))}+ resolved+ .filter(isFinitePoint)+ .map(p => (+ <circle+ key={p.dataIndex}+ cx={p.px}+ cy={p.py}+ r={3}+ fill={strokeColor}+ />+ ))}</g>);},};++ return seriesDef;}diff --git a/packages/lab/src/ChartV2/marks/referenceLine.tsx b/packages/charts/src/marks/referenceLine.tsxsimilarity index 55%rename from packages/lab/src/ChartV2/marks/referenceLine.tsxrename to packages/charts/src/marks/referenceLine.tsxindex 345f74ebcc..002b191a2f 100644--- a/packages/lab/src/ChartV2/marks/referenceLine.tsx+++ b/packages/charts/src/marks/referenceLine.tsx@@ -2,7 +2,9 @@/*** @file marks/referenceLine.tsx- * @output Horizontal or vertical reference line/band annotation+ * @output Horizontal or vertical reference line/band annotation. Labels are+ * clamped to stay fully inside the plot (which is clipped) for both+ * orientations, and non-finite y/x values render nothing.*/import type {SeriesDef} from '../types';@@ -29,6 +31,66 @@ export interface ReferenceLineOptions {bandOpacity?: number;}+// Badge dimensions — matches crosshair label style.+const BADGE_H = 14;+const BADGE_RX = 3;+const LABEL_FONT_SIZE = 10;+// Rough per-glyph advance + horizontal padding for width estimation.+const LABEL_CHAR_W = 6.5;+const LABEL_PAD = 12;++const clamp = (v: number, lo: number, hi: number): number =>+ Math.max(lo, Math.min(v, hi));++/** Estimated badge width for a label (0 when there's no label). */+function labelWidth(label: string | undefined): number {+ return label ? label.length * LABEL_CHAR_W + LABEL_PAD : 0;+}++/**+ * The label badge, positioned by its top-left corner so callers can clamp it+ * into the plot uniformly regardless of orientation.+ */+function ReferenceLabel({+ x,+ topY,+ width,+ color,+ text,+}: {+ x: number;+ topY: number;+ width: number;+ color: string;+ text: string;+}) {+ return (+ <g transform={`translate(${x},${topY})`} pointerEvents="none">+ <rect+ x={0}+ y={0}+ width={width}+ height={BADGE_H}+ rx={BADGE_RX}+ fill="var(--color-background-popover)"+ fillOpacity={0.85}+ stroke={color}+ strokeWidth={0.5}+ />+ <text+ x={width / 2}+ y={BADGE_H / 2}+ dy="0.35em"+ textAnchor="middle"+ fontSize={LABEL_FONT_SIZE}+ fontWeight={500}+ fill={color}>+ {text}+ </text>+ </g>+ );+}+/*** Reference line or band annotation. Not a data series — renders at fixed values.*@@ -45,10 +107,7 @@ export function referenceLine(options: ReferenceLineOptions): SeriesDef {const labelPosition = options.labelPosition ?? 'end';const bandOpacity = options.bandOpacity ?? 0.1;- // Badge dimensions — matches crosshair label style- const badgeH = 14;- const badgeRx = 3;- const fontSize = 10;+ const textW = labelWidth(label);return {type: 'referenceLine',@@ -63,15 +122,24 @@ export function referenceLine(options: ReferenceLineOptions): SeriesDef {render(_resolved, ctx) {const {width, height, xScale, yScale} = ctx;+ // Keep the badge fully inside the (clipped) plot on both axes.+ const bxMax = width - textW - 2;// Horizontal reference line or bandif (options.y != null) {+ if (!Number.isFinite(options.y)) {+ return null;+ }const py = yScale(options.y);- const textW = label ? label.length * 5.5 + 8 : 0;- const bx = labelPosition === 'end' ? width - textW - 2 : 2;+ if (!Number.isFinite(py)) {+ return null;+ }+ const desiredBx = labelPosition === 'end' ? bxMax : 2;+ const bx = clamp(desiredBx, 2, bxMax);+ const labelTopY = clamp(py - BADGE_H / 2, 0, height - BADGE_H);// Band mode: shaded region between y and y2- if (options.y2 != null) {+ if (options.y2 != null && Number.isFinite(options.y2)) {const py2 = yScale(options.y2);const top = Math.min(py, py2);const bandHeight = Math.abs(py2 - py);@@ -104,28 +172,13 @@ export function referenceLine(options: ReferenceLineOptions): SeriesDef {strokeDasharray={strokeDasharray}/>{label && (- <g transform={`translate(${bx},${py})`} pointerEvents="none">- <rect- x={0}- y={-badgeH / 2}- width={textW}- height={badgeH}- rx={badgeRx}- fill="var(--color-background-popover)"- fillOpacity={0.85}- stroke={color}- strokeWidth={0.5}- />- <text- x={textW / 2}- dy="0.35em"- textAnchor="middle"- fontSize={fontSize}- fontWeight={500}- fill={color}>- {label}- </text>- </g>+ <ReferenceLabel+ x={bx}+ topY={labelTopY}+ width={textW}+ color={color}+ text={label}+ />)}</g>);@@ -144,38 +197,31 @@ export function referenceLine(options: ReferenceLineOptions): SeriesDef {strokeDasharray={strokeDasharray}/>{label && (- <g transform={`translate(${bx},${py})`} pointerEvents="none">- <rect- x={0}- y={-badgeH / 2}- width={textW}- height={badgeH}- rx={badgeRx}- fill="var(--color-background-popover)"- fillOpacity={0.85}- stroke={color}- strokeWidth={0.5}- />- <text- x={textW / 2}- dy="0.35em"- textAnchor="middle"- fontSize={fontSize}- fontWeight={500}- fill={color}>- {label}- </text>- </g>+ <ReferenceLabel+ x={bx}+ topY={labelTopY}+ width={textW}+ color={color}+ text={label}+ />)}</g>);}- // Vertical reference line+ // Vertical reference line (linear x only — a band scale has no pixel+ // position for an arbitrary numeric x).if (options.x != null && !('bandwidth' in xScale)) {+ if (!Number.isFinite(options.x)) {+ return null;+ }const px = (xScale as ScaleLinear<number, number>)(options.x);- const textW = label ? label.length * 5.5 + 8 : 0;- const by = labelPosition === 'end' ? 4 : height - badgeH - 4;+ if (!Number.isFinite(px)) {+ return null;+ }+ const desiredTopY = labelPosition === 'end' ? 4 : height - BADGE_H - 4;+ const labelTopY = clamp(desiredTopY, 0, height - BADGE_H);+ const bx = clamp(px - textW / 2, 2, bxMax);return (<g><line@@ -188,31 +234,13 @@ export function referenceLine(options: ReferenceLineOptions): SeriesDef {strokeDasharray={strokeDasharray}/>{label && (- <g- transform={`translate(${px - textW / 2},${by})`}- pointerEvents="none">- <rect- x={0}- y={0}- width={textW}- height={badgeH}- rx={badgeRx}- fill="var(--color-background-popover)"- fillOpacity={0.85}- stroke={color}- strokeWidth={0.5}- />- <text- x={textW / 2}- y={badgeH / 2}- dy="0.35em"- textAnchor="middle"- fontSize={fontSize}- fontWeight={500}- fill={color}>- {label}- </text>- </g>+ <ReferenceLabel+ x={bx}+ topY={labelTopY}+ width={textW}+ color={color}+ text={label}+ />)}</g>);diff --git a/packages/charts/src/marks/streamGL.tsx b/packages/charts/src/marks/streamGL.tsxnew file mode 100644index 0000000000..942e82421b--- /dev/null+++ b/packages/charts/src/marks/streamGL.tsx@@ -0,0 +1,381 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file marks/streamGL.tsx+ * @output WebGL streaming time-series line — ring buffer, canvas outside SVG+ *+ * Data is pushed imperatively via the returned handle, not from the static dataset.+ * The chart's xScale/yScale map pushed values to pixel coordinates.+ *+ * Draws are coalesced onto a single requestAnimationFrame so a burst of pushes+ * repaints once per frame. The GL context, program, and vertex buffer are made+ * once and reused; all are released (rAF cancelled, context eagerly lost) on+ * unmount. Redraws on resize / scale change and recovers from context loss.+ */++import {+ useRef,+ useEffect,+ useImperativeHandle,+ useCallback,+ useState,+ type MutableRefObject,+} from 'react';+import type {SeriesDef} from '../types';+import {useChart} from '../ChartContext';+import {+ hexToGL,+ getWebGLContext,+ setupGLState,+ sizeCanvas,+ mountCanvasOverSVG,+ createProgram,+ registerContextLossHandlers,+ loseContext,+} from '../webgl';++export interface StreamGLHandle {+ push(x: number, y: number): void;+ clear(): void;+}++export interface StreamGLOptions {+ color: string;+ bufferSize?: number;+ lineWidth?: number;+ opacity?: number;+ /** Ref to receive the push/clear handle */+ handleRef?: MutableRefObject<StreamGLHandle | null>;+}++const VERT = `+ attribute vec2 a_position;+ uniform vec2 u_resolution;+ void main() {+ vec2 clip = (a_position / u_resolution) * 2.0 - 1.0;+ gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);+ }+`;++const FRAG = `+ precision mediump float;+ uniform vec3 u_color;+ uniform float u_opacity;+ void main() {+ float a = u_opacity;+ gl_FragColor = vec4(u_color * a, a);+ }+`;++type StreamGLLocations = {+ aPosition: number;+ uResolution: WebGLUniformLocation | null;+ uColor: WebGLUniformLocation | null;+ uOpacity: WebGLUniformLocation | null;+};++/**+ * Inline component — manages the ring buffer, canvas, and rAF draw loop.+ */+function StreamGLCanvas({+ color,+ bufferSize,+ lineWidth,+ opacity,+ width,+ height,+ handleRef,+}: {+ color: string;+ bufferSize: number;+ lineWidth: number;+ opacity: number;+ width: number;+ height: number;+ handleRef?: MutableRefObject<StreamGLHandle | null>;+}) {+ const {xScale, yScale} = useChart();+ const canvasRef = useRef<HTMLCanvasElement | null>(null);+ const glRef = useRef<WebGLRenderingContext | null>(null);+ const programRef = useRef<WebGLProgram | null>(null);+ const bufRef = useRef<WebGLBuffer | null>(null);+ const locsRef = useRef<StreamGLLocations | null>(null);+ const markerRef = useRef<SVGGElement>(null);+ const rafRef = useRef<number | null>(null);+ // Bumped on context restore to force a rebuild + repaint.+ const [contextEpoch, setContextEpoch] = useState(0);++ // Ring buffer + a reusable scratch array for the pixel-space draw data. The+ // capacity is captured on the ring itself so head/count math stays consistent+ // even if the `bufferSize` prop changes (handled by the resize effect below).+ const ringRef = useRef({+ data: new Float32Array(bufferSize * 2),+ head: 0,+ count: 0,+ capacity: bufferSize,+ });+ const scratchRef = useRef<Float32Array>(new Float32Array(bufferSize * 2));++ // Re-allocate the ring if bufferSize changes (rare — resets the stream).+ useEffect(() => {+ const ring = ringRef.current;+ if (ring.capacity !== bufferSize) {+ ring.data = new Float32Array(bufferSize * 2);+ ring.head = 0;+ ring.count = 0;+ ring.capacity = bufferSize;+ scratchRef.current = new Float32Array(bufferSize * 2);+ }+ }, [bufferSize]);++ const draw = useCallback(() => {+ const canvas = canvasRef.current;+ if (!canvas || width <= 0 || height <= 0) {+ return;+ }+ if (!glRef.current) {+ glRef.current = getWebGLContext(canvas);+ }+ const gl = glRef.current;+ if (!gl || gl.isContextLost()) {+ return;+ }++ if (!programRef.current) {+ programRef.current = createProgram(gl, VERT, FRAG);+ locsRef.current = null;+ }+ const program = programRef.current;+ if (!program) {+ return;+ }++ if (!bufRef.current) {+ bufRef.current = gl.createBuffer();+ }+ const buffer = bufRef.current;+ if (!buffer) {+ return;+ }++ if (!locsRef.current) {+ locsRef.current = {+ aPosition: gl.getAttribLocation(program, 'a_position'),+ uResolution: gl.getUniformLocation(program, 'u_resolution'),+ uColor: gl.getUniformLocation(program, 'u_color'),+ uOpacity: gl.getUniformLocation(program, 'u_opacity'),+ };+ }+ const locs = locsRef.current;++ gl.viewport(0, 0, canvas.width, canvas.height);+ setupGLState(gl);++ const {data: ringData, head, count, capacity} = ringRef.current;+ if (count < 2) {+ // Buffer already cleared above — nothing to stroke yet.+ return;+ }++ const linearX = xScale as (v: number) => number;+ const drawBuf = scratchRef.current;+ for (let i = 0; i < count; i++) {+ const idx = ((head - count + i + capacity) % capacity) * 2;+ drawBuf[i * 2] = linearX(ringData[idx]);+ drawBuf[i * 2 + 1] = yScale(ringData[idx + 1]);+ }++ gl.useProgram(program);+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);+ gl.bufferData(+ gl.ARRAY_BUFFER,+ drawBuf.subarray(0, count * 2),+ gl.DYNAMIC_DRAW,+ );+ gl.enableVertexAttribArray(locs.aPosition);+ gl.vertexAttribPointer(locs.aPosition, 2, gl.FLOAT, false, 0, 0);++ const [r, g, b] = hexToGL(color);+ gl.uniform2f(locs.uResolution, width, height);+ gl.uniform3f(locs.uColor, r, g, b);+ gl.uniform1f(locs.uOpacity, opacity);++ gl.lineWidth(lineWidth);+ gl.drawArrays(gl.LINE_STRIP, 0, count);+ }, [width, height, color, lineWidth, opacity, xScale, yScale]);++ // Keep the latest draw reachable from the single coalesced rAF callback, so a+ // frame scheduled before a scale/size change still paints with current state.+ const drawRef = useRef(draw);+ useEffect(() => {+ drawRef.current = draw;+ }, [draw]);++ // Coalesce redraws onto one rAF so a burst of pushes paints once per frame.+ // Stable identity keeps the imperative push/clear handle from churning.+ const scheduleDraw = useCallback(() => {+ if (rafRef.current != null) {+ return;+ }+ rafRef.current = requestAnimationFrame(() => {+ rafRef.current = null;+ drawRef.current();+ });+ }, []);++ // Mount the canvas outside the SVG and wire context-loss recovery.+ useEffect(() => {+ const marker = markerRef.current;+ if (!marker) {+ return;+ }+ if (!canvasRef.current) {+ canvasRef.current = document.createElement('canvas');+ }+ const canvas = canvasRef.current;+ const detach = mountCanvasOverSVG(marker, canvas, width, height);+ const unregister = registerContextLossHandlers(+ canvas,+ () => {+ if (rafRef.current != null) {+ cancelAnimationFrame(rafRef.current);+ rafRef.current = null;+ }+ glRef.current = null;+ programRef.current = null;+ bufRef.current = null;+ locsRef.current = null;+ },+ () => setContextEpoch(e => e + 1),+ );+ return () => {+ unregister();+ detach?.();+ };+ }, [width, height]);++ // Size the canvas when the plot area changes.+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || width <= 0 || height <= 0) {+ return;+ }+ sizeCanvas(canvas, width, height);+ }, [width, height]);++ // Redraw the retained buffer when scales, size, or the GL context change so a+ // paused stream doesn't leave a stale frame after a resize or window slide.+ useEffect(() => {+ scheduleDraw();+ }, [draw, scheduleDraw, contextEpoch]);++ // Expose push/clear handle via ref.+ useImperativeHandle(+ handleRef as MutableRefObject<StreamGLHandle | null>,+ () => ({+ push(x: number, y: number) {+ if (!Number.isFinite(x) || !Number.isFinite(y)) {+ return;+ }+ const ring = ringRef.current;+ const idx = ring.head * 2;+ ring.data[idx] = x;+ ring.data[idx + 1] = y;+ ring.head = (ring.head + 1) % ring.capacity;+ ring.count = Math.min(ring.count + 1, ring.capacity);+ scheduleDraw();+ },+ clear() {+ const ring = ringRef.current;+ ring.head = 0;+ ring.count = 0;+ if (rafRef.current != null) {+ cancelAnimationFrame(rafRef.current);+ rafRef.current = null;+ }+ const gl = glRef.current;+ if (gl && !gl.isContextLost()) {+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ }+ },+ }),+ [scheduleDraw],+ );++ // Cancel any pending frame and release all GL resources on unmount.+ useEffect(() => {+ return () => {+ if (rafRef.current != null) {+ cancelAnimationFrame(rafRef.current);+ rafRef.current = null;+ }+ const gl = glRef.current;+ if (gl) {+ if (bufRef.current) {+ gl.deleteBuffer(bufRef.current);+ }+ if (programRef.current) {+ gl.deleteProgram(programRef.current);+ }+ loseContext(gl);+ }+ glRef.current = null;+ programRef.current = null;+ bufRef.current = null;+ locsRef.current = null;+ };+ }, []);++ if (width <= 0 || height <= 0) {+ return null;+ }+ return <g ref={markerRef} />;+}++/**+ * WebGL streaming line. Data is pushed imperatively via handleRef,+ * not from the chart's static dataset. Internally uses a ring buffer.+ *+ * @example+ * ```+ * const streamRef = useRef<StreamGLHandle>(null);+ * // Push data points in a rAF loop or event handler:+ * streamRef.current?.push(Date.now(), value);+ *+ * <Chart series={[streamGL({color: '#10b981', handleRef: streamRef})]} />+ * ```+ */+export function streamGL(options: StreamGLOptions): SeriesDef {+ const {color} = options;+ const bufferSize = options.bufferSize ?? 500;+ const lineWidth = options.lineWidth ?? 2;+ const opacity = options.opacity ?? 1;+ const handleRef = options.handleRef;++ return {+ type: 'streamGL',+ key: 'stream',+ dataKeys: [],+ layout: {},++ // Streaming data is pushed, not in the static dataset+ resolve() {+ return [];+ },++ render(_resolved, ctx) {+ return (+ <StreamGLCanvas+ color={color}+ bufferSize={bufferSize}+ lineWidth={lineWidth}+ opacity={opacity}+ width={ctx.width}+ height={ctx.height}+ handleRef={handleRef}+ />+ );+ },+ };+}diff --git a/packages/lab/src/ChartV2/tooltip.ts b/packages/charts/src/tooltip.tssimilarity index 82%rename from packages/lab/src/ChartV2/tooltip.tsrename to packages/charts/src/tooltip.tsindex 34a0871586..f99aa7bf17 100644--- a/packages/lab/src/ChartV2/tooltip.ts+++ b/packages/charts/src/tooltip.ts@@ -8,7 +8,7 @@* lives in ChartTooltip.tsx.*/-import {isUtilityMarkType, type SeriesDef} from './types';+import {DEFAULT_SERIES_COLOR, isUtilityMarkType, type SeriesDef} from './types';/*** One row of tooltip data — represents a single series' value at the@@ -46,13 +46,16 @@ export function deriveTooltipSeriesValues(if (isUtilityMarkType(s.type)) {continue;}- if (!resolvedKeys.has(s.key)) {+ // resolvedKeys holds layout-assigned _uids (collision-free), not `key`.+ if (!s._uid || !resolvedKeys.has(s._uid)) {continue;}out.push({key: s.key,label: s.label ?? s.key,- color: s.color ?? 'var(--color-text-primary)',+ // Same representative-color precedence as the legend, so a series' tooltip+ // swatch and legend swatch always match.+ color: s.color ?? s._resolvedColor ?? DEFAULT_SERIES_COLOR,type: s.type,value: datum[s.dataKeys[0]],});diff --git a/packages/lab/src/ChartV2/types.ts b/packages/charts/src/types.tssimilarity index 62%rename from packages/lab/src/ChartV2/types.tsrename to packages/charts/src/types.tsindex b3bc72b56f..990f898c97 100644--- a/packages/lab/src/ChartV2/types.ts+++ b/packages/charts/src/types.ts@@ -11,6 +11,32 @@ import type {ScaleLinear, ScaleBand} from 'd3-scale';export type ChartScale = ScaleLinear<number, number> | ScaleBand<string>;+/**+ * A color for a mark: either a constant CSS color/token, or an accessor that+ * returns a color per datum (for per-element coloring, e.g. positive/negative).+ */+export type ColorAccessor =+ string | ((datum: Record<string, unknown>, index: number) => string);++/**+ * Fallback series color used when a mark has neither an explicit color nor a+ * palette color assigned by the chart root. Uses an EMITTED core token+ * (`--color-accent`) — the data-viz `--color-data-*` tokens are JS-only values+ * (resolved via useChartColors), not CSS custom properties, so `var(--color-data-*)`+ * would render nothing. The chart root normally assigns a resolved palette color,+ * so this is only a last-resort fallback.+ */+export const DEFAULT_SERIES_COLOR = 'var(--color-accent)';++/**+ * Controls how the y-axis domain is derived when no explicit `yDomain` is given:+ * - `'auto'` (default) — bar/area marks pin an honest zero baseline; continuous-+ * only charts (line/dot/…) get a little headroom so points don't touch edges.+ * - `'zero'` — symmetric around zero (good for +/- data like profit/loss).+ * - `'data'` — tight fit to the data extent (no zero forcing, no headroom).+ */+export type YBaseline = 'auto' | 'zero' | 'data';+export interface ChartMargin {top: number;right: number;@@ -46,18 +72,40 @@ export interface SeriesContext {* The standardized shape every mark helper returns.* Each mark type is self-contained: it knows how to resolve positions* and how to render itself. The chart root just iterates and calls.+ *+ * A SeriesDef instance is single-use: the layout/render pass annotates it in+ * place (`_uid`, `_isTopOfStack`, `_resolvedColor`), so a given def must belong+ * to exactly one <Chart>. Build a fresh series array per chart rather than+ * sharing the same mark objects across charts.*/export interface SeriesDef {/** Mark type identifier */readonly type: string;- /** Unique key for this series (typically the dataKey) */+ /**+ * Semantic key for this series — typically the dataKey. Used as a+ * human-readable label fallback and for stack/group coordination. It is NOT+ * guaranteed unique (two series can share a dataKey), so it must never be+ * used as a Map key or React key — use `_uid` for identity instead.+ */readonly key: string;/** Data keys this series reads from — used to compute y domain */readonly dataKeys: string[];+ /**+ * Collision-free per-instance identity, assigned by the layout pass from the+ * series' position in the `series` array. This is the key used for the+ * resolved map, React keys, and tooltip/hover lookups. Never set it yourself.+ */+ _uid?: string;/** Whether this series is the topmost in its stack (set during layout) */_isTopOfStack?: boolean;/** Static color for legend display. Undefined if color is dynamic (accessor function). */readonly color?: string;+ /**+ * Palette color assigned by the chart root for series that don't supply a+ * static color (auto-colored or accessor-colored). Used as the render fallback+ * and the legend/tooltip representative color. Never set it yourself.+ */+ _resolvedColor?: string;/** Human-readable label for legend. Falls back to key if not provided. */readonly label?: string;/** Layout hints the chart root uses for cross-series coordination */@@ -99,7 +147,7 @@ export interface ChartPointerEvent {}/** Context provided by Chart to interaction children */-export interface ChartV2Context {+export interface ChartContext {width: number;height: number;margin: ChartMargin;diff --git a/packages/charts/src/useChartColors.ts b/packages/charts/src/useChartColors.tsnew file mode 100644index 0000000000..256b86d7f5--- /dev/null+++ b/packages/charts/src/useChartColors.ts@@ -0,0 +1,41 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useChartColors.ts+ * @output Theme-aware chart color palette hook+ * @position React hook wrapping getChartColors — resolves from live theme context+ *+ * Returns a stable reference across renders — the palette only rebuilds when the+ * resolved theme tokens change (theme or color mode), so consumers can safely+ * use the result in effect/memo dependency arrays.+ */++import {useMemo} from 'react';+import {useTheme} from '@astryxdesign/core/theme';+import {getChartColorsFromResolver} from './getChartColors';+import type {ChartColorsAPI} from './getChartColors';++/**+ * Theme-aware chart colors. Resolves data-viz tokens from the current+ * theme context — respects light/dark mode and custom themes.+ *+ * @example+ * ```+ * const colors = useChartColors();+ * colors.categorical(5)+ * colors.sequential.blue(3)+ * colors.diverging.positiveNegative(5)+ * colors.alpha('#0171E3', 0.5)+ * ```+ */+export function useChartColors(): ChartColorsAPI {+ // Depend on the memoized token map (stable per theme + mode), not useTheme's+ // `token` function, which is a fresh closure on every render and would defeat+ // memoization — returning a new palette object each render.+ const {tokens} = useTheme();++ return useMemo(+ () => getChartColorsFromResolver(name => tokens[name] ?? ''),+ [tokens],+ );+}diff --git a/packages/charts/src/utils.ts b/packages/charts/src/utils.tsnew file mode 100644index 0000000000..4fc86868a8--- /dev/null+++ b/packages/charts/src/utils.ts@@ -0,0 +1,36 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file utils.ts+ * @output Shared utilities for chart components+ * @position Internal helpers; consumed by mark, axis, and interaction components+ */++import type {ScaleBand} from 'd3-scale';+import type {ChartScale} from './types';++/** Type guard for d3 band scales */+export function isBandScale(scale: ChartScale): scale is ScaleBand<string> {+ return typeof scale === 'function' && 'bandwidth' in scale;+}++/**+ * Get the x pixel position for a datum using the chart's xKey and xScale.+ * For band scales, returns the center of the band.+ */+export function xPixel(+ d: Record<string, unknown>,+ xKey: string,+ xScale: ChartScale,+): number {+ const raw = d[xKey];+ if (isBandScale(xScale)) {+ return (xScale(String(raw)) ?? 0) + xScale.bandwidth() / 2;+ }+ // Not a band scale → the guard narrows `xScale` to the linear scale, so no+ // cast is needed. Coerce explicitly: numbers pass through, Date/numeric-string+ // map as d3 would, and non-numerics become NaN (an off-canvas point) rather+ // than a silently wrong position.+ const value = typeof raw === 'number' ? raw : Number(raw);+ return xScale(value);+}diff --git a/packages/charts/src/webgl.ts b/packages/charts/src/webgl.tsnew file mode 100644index 0000000000..cdeaba0ccf--- /dev/null+++ b/packages/charts/src/webgl.ts@@ -0,0 +1,263 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file webgl.ts+ * @output Shared WebGL utilities for chart components+ * @position Internal helpers; consumed by all GL mark components+ *+ * Provides:+ * - Canvas mounting outside SVG (avoids foreignObject DPR blur)+ * - Premultiplied alpha setup (correct compositing over page)+ * - Shader compilation helpers+ * - Smoothstep circle fragment for crisp point sprites+ * - Robust hex/shorthand color parsing (fallback instead of NaN)+ * - Context-loss registration + eager context teardown helpers+ */++/** Compile a WebGL shader, returns null on failure */+export function compileShader(+ gl: WebGLRenderingContext,+ type: number,+ src: string,+): WebGLShader | null {+ const s = gl.createShader(type);+ if (!s) {+ return null;+ }+ gl.shaderSource(s, src);+ gl.compileShader(s);+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {+ gl.deleteShader(s);+ return null;+ }+ return s;+}++/** Link a vertex + fragment shader into a program */+export function createProgram(+ gl: WebGLRenderingContext,+ vertSrc: string,+ fragSrc: string,+): WebGLProgram | null {+ const vs = compileShader(gl, gl.VERTEX_SHADER, vertSrc);+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, fragSrc);+ if (!vs || !fs) {+ return null;+ }+ const p = gl.createProgram();+ if (!p) {+ return null;+ }+ gl.attachShader(p, vs);+ gl.attachShader(p, fs);+ gl.linkProgram(p);+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {+ gl.deleteProgram(p);+ return null;+ }+ return p;+}++/** Neutral fallback (mid-grey) for colors we can't parse — visible, never NaN. */+const HEX_FALLBACK: [number, number, number] = [0.5, 0.5, 0.5];++/**+ * Parse a hex color to [r, g, b] floats in 0-1.+ *+ * Accepts `#rgb`, `#rgba`, `#rrggbb`, and `#rrggbbaa`, with or without the+ * leading `#` (any alpha byte is ignored). Non-hex input — CSS custom+ * properties, `rgb()`, named colors, or malformed strings — returns a neutral+ * fallback rather than producing NaN, so the GPU never receives a bad uniform.+ */+export function hexToGL(hex: string): [number, number, number] {+ if (typeof hex !== 'string') {+ return HEX_FALLBACK;+ }+ let h = hex.trim().replace(/^#/, '');+ // Expand shorthand: `rgb`/`rgba` -> `rrggbb`/`rrggbbaa`.+ if (h.length === 3 || h.length === 4) {+ h = h.replace(/./g, c => c + c);+ }+ // Drop the alpha byte if present — the GL path only needs rgb.+ if (h.length === 8) {+ h = h.slice(0, 6);+ }+ if (!/^[0-9a-fA-F]{6}$/.test(h)) {+ return HEX_FALLBACK;+ }+ const n = parseInt(h, 16);+ return [(n >> 16) / 255, ((n >> 8) & 0xff) / 255, (n & 0xff) / 255];+}++/** DPR with 2x supersampling for crisp circles. SSR-safe (falls back to 2). */+export function getCanvasDPR(): number {+ const base = typeof window !== 'undefined' ? window.devicePixelRatio : 0;+ return (base || 2) * 2;+}++/**+ * Create or get a WebGL context with correct alpha settings.+ * Uses premultiplied alpha for correct compositing over the page.+ */+export function getWebGLContext(+ canvas: HTMLCanvasElement,+): WebGLRenderingContext | null {+ return canvas.getContext('webgl', {+ alpha: true,+ premultipliedAlpha: true,+ antialias: true,+ });+}++/**+ * Set up standard GL state for chart rendering:+ * - Clear with transparent+ * - Enable premultiplied alpha blending+ */+export function setupGLState(gl: WebGLRenderingContext): void {+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);+}++/**+ * Size a canvas for sharp rendering, accounting for DPR.+ * Returns the DPR used.+ */+export function sizeCanvas(+ canvas: HTMLCanvasElement,+ width: number,+ height: number,+): number {+ const dpr = getCanvasDPR();+ // The drawing buffer must be a positive integer — a 0-sized (or fractional)+ // buffer makes GL viewport/draw calls silently fail.+ canvas.width = Math.max(1, Math.round(width * dpr));+ canvas.height = Math.max(1, Math.round(height * dpr));+ canvas.style.width = `${Math.max(0, width)}px`;+ canvas.style.height = `${Math.max(0, height)}px`;+ return dpr;+}++/**+ * Mount a canvas as an absolute-positioned sibling to an SVG element.+ * Automatically aligns with the SVG marker's position — no manual margin+ * offset needed. This is a Tier 1 guarantee: the canvas lands exactly+ * where the SVG content area is, regardless of chart margins or transforms.+ *+ * Call from a useEffect. Returns a cleanup function.+ */+export function mountCanvasOverSVG(+ svgMarker: SVGGraphicsElement,+ canvas: HTMLCanvasElement,+ width: number,+ height: number,+): (() => void) | undefined {+ const svg = svgMarker.ownerSVGElement;+ if (!svg) {+ return;+ }+ const parent = svg.parentElement;+ if (!parent) {+ return;+ }++ if (getComputedStyle(parent).position === 'static') {+ parent.style.position = 'relative';+ }++ canvas.style.position = 'absolute';+ canvas.style.pointerEvents = 'none';++ // Compute offset from the SVG marker's actual screen position.+ // The marker sits inside the chart's <g transform="translate(margin)">+ // so its bounding rect includes the margin offset automatically.+ // This is a Tier 1 guarantee — we derive position from the SVG, not from props.+ const parentRect = parent.getBoundingClientRect();+ const markerCTM = svgMarker.getScreenCTM();+ if (markerCTM) {+ canvas.style.left = `${markerCTM.e - parentRect.left}px`;+ canvas.style.top = `${markerCTM.f - parentRect.top}px`;+ } else {+ canvas.style.left = '0';+ canvas.style.top = '0';+ }+ canvas.style.width = `${width}px`;+ canvas.style.height = `${height}px`;++ parent.appendChild(canvas);++ return () => {+ if (canvas.parentElement === parent) {+ parent.removeChild(canvas);+ }+ };+}++/**+ * Register WebGL context-loss/restore handlers on a canvas.+ *+ * Calling `preventDefault()` on the lost event is REQUIRED — without it the+ * browser will never fire `webglcontextrestored`. `onLost` should drop any+ * cached GL handles (they are all invalid after loss); `onRestored` should+ * trigger a rebuild + redraw.+ *+ * Returns a cleanup that removes both listeners.+ */+export function registerContextLossHandlers(+ canvas: HTMLCanvasElement,+ onLost: () => void,+ onRestored: () => void,+): () => void {+ const handleLost = (e: Event) => {+ e.preventDefault();+ onLost();+ };+ canvas.addEventListener('webglcontextlost', handleLost, false);+ canvas.addEventListener('webglcontextrestored', onRestored, false);+ return () => {+ canvas.removeEventListener('webglcontextlost', handleLost, false);+ canvas.removeEventListener('webglcontextrestored', onRestored, false);+ };+}++/**+ * Eagerly release a WebGL context and its GPU resources on teardown.+ *+ * Browsers cap the number of live contexts (~16), so freeing on unmount rather+ * than waiting for GC prevents "too many active WebGL contexts" failures when+ * many charts mount/unmount over a session.+ */+export function loseContext(gl: WebGLRenderingContext): void {+ const ext = gl.getExtension('WEBGL_lose_context');+ if (ext) {+ ext.loseContext();+ }+}++/**+ * GLSL fragment for premultiplied-alpha circle with smoothstep AA.+ * Use in fragment shaders that render point sprites.+ *+ * Expects:+ * - varying float v_alpha (the final alpha before edge AA)+ * - uniform vec3 u_color+ *+ * Returns: gl_FragColor with premultiplied alpha+ */+export const CIRCLE_FRAG_BODY = `+ vec2 coord = gl_PointCoord - vec2(0.5);+ float dist = length(coord);+ if (dist > 0.5) discard;+ float edge = 1.0 - smoothstep(0.48, 0.5, dist);+ float a = v_alpha * edge;+ gl_FragColor = vec4(u_color * a, a);+`;++/**+ * Smoothstep compensation factor for gl_PointSize.+ * The visible circle radius is 0.48 of the point sprite (smoothstep starts there),+ * so we scale up by 1/0.96 to match SVG circle radius exactly.+ */+export const POINT_SIZE_COMPENSATION = 1.0 / 0.96;diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 19db7a5baa..4705d7be3c 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -80,12 +80,16 @@"zod": "^4.4.3"},"peerDependencies": {+ "@astryxdesign/charts": "*","@astryxdesign/core": "*","@astryxdesign/lab": "*","@astryxdesign/theme-neutral": "*","gpt-tokenizer": "^3.4.0"},"peerDependenciesMeta": {+ "@astryxdesign/charts": {+ "optional": true+ },"@astryxdesign/core": {"optional": true},@@ -97,6 +101,7 @@}},"devDependencies": {+ "@astryxdesign/charts": "*","@astryxdesign/core": "*","@astryxdesign/lab": "*","@astryxdesign/theme-neutral": "*",diff --git a/packages/cli/templates/pages/table-page-chart/page.tsx b/packages/cli/templates/pages/table-page-chart/page.tsxindex f925db15b2..1c94f542f7 100644--- a/packages/cli/templates/pages/table-page-chart/page.tsx+++ b/packages/cli/templates/pages/table-page-chart/page.tsx@@ -19,13 +19,7 @@ import {Link} from '@astryxdesign/core/Link';import {Thumbnail} from '@astryxdesign/core/Thumbnail';import {Table, proportional, pixel} from '@astryxdesign/core/Table';import type {TableColumn} from '@astryxdesign/core/Table';-import {- ChartV2 as Chart,- ChartGrid,- ChartAxis,- area,- line,-} from '@astryxdesign/lab';+import {Chart, ChartGrid, ChartAxis, area, line} from '@astryxdesign/charts';import {FunnelIcon,ArrowDownTrayIcon,@@ -481,17 +475,13 @@ const columns: TableColumn<OrderRow>[] = [key: 'amount',header: 'Amount',width: pixel(90),- renderCell: (item: OrderRow) => (- <Text type="body">${item.amount}</Text>- ),+ renderCell: (item: OrderRow) => <Text type="body">${item.amount}</Text>,},{key: 'customer',header: 'Customer',width: proportional(2),- renderCell: (item: OrderRow) => (- <Text type="body">{item.customer}</Text>- ),+ renderCell: (item: OrderRow) => <Text type="body">{item.customer}</Text>,},{key: 'email',diff --git a/packages/cli/templates/pages/table-page-shoe-store-heatmap/page.tsx b/packages/cli/templates/pages/table-page-shoe-store-heatmap/page.tsxindex 5de6647d30..bb34c644c0 100644--- a/packages/cli/templates/pages/table-page-shoe-store-heatmap/page.tsx+++ b/packages/cli/templates/pages/table-page-shoe-store-heatmap/page.tsx@@ -19,13 +19,7 @@ import {Link} from '@astryxdesign/core/Link';import {Thumbnail} from '@astryxdesign/core/Thumbnail';import {Table, proportional, pixel} from '@astryxdesign/core/Table';import type {TableColumn} from '@astryxdesign/core/Table';-import {- ChartV2 as Chart,- ChartGrid,- ChartAxis,- area,- line,-} from '@astryxdesign/lab';+import {Chart, ChartGrid, ChartAxis, area, line} from '@astryxdesign/charts';import {FunnelIcon,ArrowDownTrayIcon,@@ -35,11 +29,7 @@ import {// ============= DATA =============type ProductCategory =- | 'Running'- | 'Lifestyle'- | 'Basketball'- | 'Training'- | 'Skateboarding';+ 'Running' | 'Lifestyle' | 'Basketball' | 'Training' | 'Skateboarding';function shoeSvg(bg: string, accent: string) {const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect width="100" height="100" rx="12" fill="${bg}"/><g transform="translate(22.5, 22.5) scale(2.29)" fill="none" stroke="${accent}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="m15 10.42 4.8-5.07"/><path d="M19 18h3"/><path d="M9.5 22 21.414 9.415A2 2 0 0 0 21.2 6.4l-5.61-4.208A1 1 0 0 0 14 3v2a2 2 0 0 1-1.394 1.906L8.677 8.053A1 1 0 0 0 8 9c-.155 6.393-2.082 9-4 9a2 2 0 0 0 0 4h14"/></g></svg>`;@@ -839,17 +829,13 @@ const columns: TableColumn<OrderRow>[] = [key: 'amount',header: 'Amount',width: pixel(90),- renderCell: (item: OrderRow) => (- <Text type="body">${item.amount}</Text>- ),+ renderCell: (item: OrderRow) => <Text type="body">${item.amount}</Text>,},{key: 'customer',header: 'Customer',width: proportional(2),- renderCell: (item: OrderRow) => (- <Text type="body">{item.customer}</Text>- ),+ renderCell: (item: OrderRow) => <Text type="body">{item.customer}</Text>,},{key: 'email',diff --git a/packages/lab/src/ChartV2/index.ts b/packages/lab/src/ChartV2/index.tsdeleted file mode 100644index 432ab6639c..0000000000--- a/packages/lab/src/ChartV2/index.ts+++ /dev/null@@ -1,62 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--export {Chart, type ChartProps} from './Chart';-export {ChartAxis, type ChartAxisProps} from './ChartAxis';-export {ChartGrid, type ChartGridProps} from './ChartGrid';-export {- ChartLegend,- type ChartLegendProps,- type LegendPosition,- type LegendAlignment,-} from './ChartLegend';-export {type LegendItem} from './legend';-export {- ChartSwatch,- swatchVariantForType,- type ChartSwatchProps,- type ChartSwatchVariant,-} from './ChartSwatch';-export {- ChartTooltip,- type ChartTooltipProps,- type ChartTooltipPlacement,-} from './ChartTooltip';-export {type TooltipSeriesValue} from './tooltip';-export {- bar,- line,- dot,- area,- band,- candlestick,- errorBar,- referenceLine,- dotGL,- dotGLInteractive,- heatmapGL,- streamGL,-} from './marks';-export type {- BarOptions,- LineOptions,- DotOptions,- AreaOptions,- BandOptions,- CandlestickOptions,- ErrorBarOptions,- ReferenceLineOptions,- DotGLOptions,- DotGLInteractiveOptions,- HeatmapGLOptions,- StreamGLOptions,- StreamGLHandle,-} from './marks';-export {useChartV2} from './ChartV2Context';-export type {- SeriesDef,- ChartV2Context,- ChartPointerEvent,- ResolvedPoint,- ResolvedPositions,- SeriesContext,-} from './types';diff --git a/packages/lab/src/ChartV2/legend.ts b/packages/lab/src/ChartV2/legend.tsdeleted file mode 100644index 7590decb38..0000000000--- a/packages/lab/src/ChartV2/legend.ts+++ /dev/null@@ -1,32 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--/**- * @file legend.ts- * @output Legend utility — derives legend items from series definitions- * @position Used by Chart to bridge series → legend items- */--import {isUtilityMarkType, type SeriesDef} from './types';--export interface LegendItem {- label: string;- color: string;- /** Mark type — determines swatch shape (square for bar, line for everything else) */- type?: string;-}--function hasLegendColor(- series: SeriesDef,-): series is SeriesDef & {readonly color: string} {- return !isUtilityMarkType(series.type) && series.color != null;-}--/**- * Derive legend items from series definitions.- * Skips utility marks and series without a color.- */-export function deriveLegendItems(series: readonly SeriesDef[]): LegendItem[] {- return series- .filter(hasLegendColor)- .map(s => ({label: s.label ?? s.key, color: s.color, type: s.type}));-}diff --git a/packages/lab/src/ChartV2/marks/candlestick.tsx b/packages/lab/src/ChartV2/marks/candlestick.tsxdeleted file mode 100644index 49599b9443..0000000000--- a/packages/lab/src/ChartV2/marks/candlestick.tsx+++ /dev/null@@ -1,106 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--/**- * @file marks/candlestick.tsx- * @output Candlestick (OHLC) series- */--import type {SeriesDef, ResolvedPoint} from '../types';-import type {ScaleBand} from 'd3-scale';--export interface CandlestickOptions {- open: string;- high: string;- low: string;- close: string;- upColor?: string;- downColor?: string;-}--export function candlestick(options: CandlestickOptions): SeriesDef {- const upColor = options.upColor ?? 'var(--color-positive)';- const downColor = options.downColor ?? 'var(--color-negative)';-- return {- type: 'candlestick',- key: `ohlc-${options.close}`,- dataKeys: [options.open, options.high, options.low, options.close],- layout: {},-- resolve(ctx) {- const {data, xKey, xScale, yScale} = ctx;- const points: ResolvedPoint[] = [];- for (let i = 0; i < data.length; i++) {- const d = data[i];- let px: number;- if ('bandwidth' in xScale) {- px =- ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) +- (xScale as ScaleBand<string>).bandwidth() / 2;- } else {- px = xScale(d[xKey] as number);- }- const close =- typeof d[options.close] === 'number'- ? (d[options.close] as number)- : 0;- points.push({px, py: yScale(close), py0: yScale(0), dataIndex: i});- }- return points;- },-- render(resolved, ctx) {- const {data, xScale, yScale} = ctx;- if (!('bandwidth' in xScale)) {- return null;- }- const bw = (xScale as ScaleBand<string>).bandwidth();- const bodyWidth = bw * 0.6;-- return (- <g>- {resolved.map((p, i) => {- const d = data[p.dataIndex];- const o =- typeof d[options.open] === 'number'- ? (d[options.open] as number)- : 0;- const c =- typeof d[options.close] === 'number'- ? (d[options.close] as number)- : 0;- const h =- typeof d[options.high] === 'number'- ? (d[options.high] as number)- : 0;- const l =- typeof d[options.low] === 'number'- ? (d[options.low] as number)- : 0;- const isUp = c >= o;- const col = isUp ? upColor : downColor;- return (- <g key={i}>- <line- x1={p.px}- x2={p.px}- y1={yScale(h)}- y2={yScale(l)}- stroke={col}- strokeWidth={1}- />- <rect- x={p.px - bodyWidth / 2}- y={yScale(Math.max(o, c))}- width={bodyWidth}- height={Math.max(1, Math.abs(yScale(o) - yScale(c)))}- fill={col}- />- </g>- );- })}- </g>- );- },- };-}diff --git a/packages/lab/src/ChartV2/marks/dot.tsx b/packages/lab/src/ChartV2/marks/dot.tsxdeleted file mode 100644index 342a55ab18..0000000000--- a/packages/lab/src/ChartV2/marks/dot.tsx+++ /dev/null@@ -1,64 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--/**- * @file marks/dot.tsx- * @output Dot/scatter series — self-contained resolve + render- */--import type {SeriesDef, ResolvedPoint} from '../types';-import type {ScaleBand} from 'd3-scale';--export type ColorAccessor = string | ((datum: Record<string, unknown>, index: number) => string);--export interface DotOptions {- color?: ColorAccessor;- radius?: number;- opacity?: number;- dodge?: boolean;- label?: string;-}--export function dot(dataKey: string, options: DotOptions = {}): SeriesDef {- const color = options.color ?? 'var(--color-chart-1)';- const radius = options.radius ?? 4;- const opacity = options.opacity ?? 0.8;-- return {- type: 'dot',- key: dataKey,- dataKeys: [dataKey],- color: typeof color === 'string' ? color : undefined,- label: options.label ?? dataKey,- layout: {},-- resolve(ctx) {- const {data, xKey, xScale, yScale} = ctx;- const points: ResolvedPoint[] = [];- for (let i = 0; i < data.length; i++) {- const d = data[i];- let px: number;- if ('bandwidth' in xScale) {- px = ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) + (xScale as ScaleBand<string>).bandwidth() / 2;- } else {- px = xScale(d[xKey] as number);- }- const v = typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;- points.push({px, py: yScale(v), py0: yScale(0), dataIndex: i});- }- // TODO: dodge layout runs here — has access to radius + all points- return points;- },-- render(resolved, ctx) {- const {data} = ctx;- return (- <g>- {resolved.map((p, i) => {- const fill = typeof color === 'function' ? color(data[p.dataIndex], p.dataIndex) : color;- return <circle key={i} cx={p.px} cy={p.py} r={radius} fill={fill} opacity={opacity} />;- })}- </g>- );- },- };-}diff --git a/packages/lab/src/ChartV2/marks/errorBar.tsx b/packages/lab/src/ChartV2/marks/errorBar.tsxdeleted file mode 100644index 25ac19d080..0000000000--- a/packages/lab/src/ChartV2/marks/errorBar.tsx+++ /dev/null@@ -1,89 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--/**- * @file marks/errorBar.tsx- * @output Error bar (whisker) series — vertical high/low bounds- */--import type {SeriesDef, ResolvedPoint} from '../types';-import type {ScaleBand} from 'd3-scale';--export interface ErrorBarOptions {- /** Data key for the upper bound */- high: string;- /** Data key for the lower bound */- low: string;- /** Stroke color */- color?: string;- /** Stroke width */- strokeWidth?: number;- /** Width of the whisker caps in pixels */- capWidth?: number;-}--/**- * Error bars with whisker caps. Pair with bar() or dot().- *- * @example- * ```- * series={[bar('mean'), errorBar({high: 'upper95', low: 'lower95'})]}- * ```- */-export function errorBar(options: ErrorBarOptions): SeriesDef {- const {high, low} = options;- const color = options.color ?? 'var(--color-text-primary)';- const strokeWidth = options.strokeWidth ?? 1.5;- const capWidth = options.capWidth ?? 8;-- return {- type: 'errorBar',- key: `errorBar-${high}-${low}`,- dataKeys: [high, low],- layout: {},-- resolve(ctx) {- const {data, xKey, xScale, yScale} = ctx;- const points: ResolvedPoint[] = [];- for (let i = 0; i < data.length; i++) {- const d = data[i];- let px: number;- if ('bandwidth' in xScale) {- px = ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) + (xScale as ScaleBand<string>).bandwidth() / 2;- } else {- px = xScale(d[xKey] as number);- }- const upper = typeof d[high] === 'number' ? (d[high] as number) : 0;- const lower = typeof d[low] === 'number' ? (d[low] as number) : 0;- points.push({px, py: yScale(upper), py0: yScale(lower), dataIndex: i});- }- return points;- },-- render(resolved) {- const half = capWidth / 2;- return (- <g>- {resolved.map((p, i) => (- <g key={i}>- {/* Vertical stem */}- <line- x1={p.px} x2={p.px} y1={p.py} y2={p.py0}- stroke={color} strokeWidth={strokeWidth}- />- {/* Upper cap */}- <line- x1={p.px - half} x2={p.px + half} y1={p.py} y2={p.py}- stroke={color} strokeWidth={strokeWidth}- />- {/* Lower cap */}- <line- x1={p.px - half} x2={p.px + half} y1={p.py0} y2={p.py0}- stroke={color} strokeWidth={strokeWidth}- />- </g>- ))}- </g>- );- },- };-}diff --git a/packages/lab/src/ChartV2/marks/streamGL.tsx b/packages/lab/src/ChartV2/marks/streamGL.tsxdeleted file mode 100644index 1e1bdbc526..0000000000--- a/packages/lab/src/ChartV2/marks/streamGL.tsx+++ /dev/null@@ -1,251 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--/**- * @file marks/streamGL.tsx- * @output WebGL streaming time-series line — ring buffer, canvas outside SVG- *- * Data is pushed imperatively via the returned handle, not from the static dataset.- * The chart's xScale/yScale map pushed values to pixel coordinates.- */--import {- useRef,- useEffect,- useImperativeHandle,- useCallback,- type MutableRefObject,-} from 'react';-import type {SeriesDef} from '../types';-import {useChartV2} from '../ChartV2Context';-import {- hexToGL,- getWebGLContext,- setupGLState,- sizeCanvas,- mountCanvasOverSVG,- createProgram,-} from '../../Chart/webgl';--export interface StreamGLHandle {- push(x: number, y: number): void;- clear(): void;-}--export interface StreamGLOptions {- color: string;- bufferSize?: number;- lineWidth?: number;- opacity?: number;- /** Ref to receive the push/clear handle */- handleRef?: MutableRefObject<StreamGLHandle | null>;-}--const VERT = `- attribute vec2 a_position;- uniform vec2 u_resolution;- void main() {- vec2 clip = (a_position / u_resolution) * 2.0 - 1.0;- gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);- }-`;--const FRAG = `- precision mediump float;- uniform vec3 u_color;- uniform float u_opacity;- void main() {- float a = u_opacity;- gl_FragColor = vec4(u_color * a, a);- }-`;--/**- * Inline component — manages the ring buffer, canvas, and rAF draw loop.- */-function StreamGLCanvas({- color,- bufferSize,- lineWidth,- opacity,- width,- height,- handleRef,-}: {- color: string;- bufferSize: number;- lineWidth: number;- opacity: number;- width: number;- height: number;- handleRef?: MutableRefObject<StreamGLHandle | null>;-}) {- const {xScale, yScale} = useChartV2();- const canvasRef = useRef<HTMLCanvasElement | null>(null);- const glRef = useRef<WebGLRenderingContext | null>(null);- const programRef = useRef<WebGLProgram | null>(null);- const bufRef = useRef<WebGLBuffer | null>(null);- const markerRef = useRef<SVGGElement>(null);-- const ring = useRef({- data: new Float32Array(bufferSize * 2),- head: 0,- count: 0,- });-- // Mount canvas outside SVG- useEffect(() => {- const marker = markerRef.current;- if (!marker) {- return;- }- if (!canvasRef.current) {- canvasRef.current = document.createElement('canvas');- }- return mountCanvasOverSVG(marker, canvasRef.current, width, height);- }, [width, height]);-- // Size canvas- useEffect(() => {- const canvas = canvasRef.current;- if (!canvas || width <= 0 || height <= 0) {- return;- }- sizeCanvas(canvas, width, height);- }, [width, height]);-- const draw = useCallback(() => {- const canvas = canvasRef.current;- if (!canvas) {- return;- }- if (!glRef.current) {- glRef.current = getWebGLContext(canvas);- }- const gl = glRef.current;- if (!gl) {- return;- }-- if (!programRef.current) {- programRef.current = createProgram(gl, VERT, FRAG);- }- const program = programRef.current;- if (!program) {- return;- }-- if (!bufRef.current) {- bufRef.current = gl.createBuffer();- }-- const {data: ringData, head, count} = ring.current;- if (count < 2) {- return;- }-- const linearX = xScale as (v: number) => number;- const drawBuf = new Float32Array(count * 2);- for (let i = 0; i < count; i++) {- const idx = ((head - count + i + bufferSize) % bufferSize) * 2;- drawBuf[i * 2] = linearX(ringData[idx]);- drawBuf[i * 2 + 1] = yScale(ringData[idx + 1]);- }-- gl.viewport(0, 0, canvas.width, canvas.height);- setupGLState(gl);- gl.useProgram(program);-- gl.bindBuffer(gl.ARRAY_BUFFER, bufRef.current);- gl.bufferData(gl.ARRAY_BUFFER, drawBuf, gl.DYNAMIC_DRAW);-- const aPos = gl.getAttribLocation(program, 'a_position');- gl.enableVertexAttribArray(aPos);- gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);-- const [r, g, b] = hexToGL(color);- gl.uniform2f(gl.getUniformLocation(program, 'u_resolution'), width, height);- gl.uniform3f(gl.getUniformLocation(program, 'u_color'), r, g, b);- gl.uniform1f(gl.getUniformLocation(program, 'u_opacity'), opacity);-- gl.lineWidth(lineWidth);- gl.drawArrays(gl.LINE_STRIP, 0, count);- }, [width, height, color, lineWidth, opacity, bufferSize, xScale, yScale]);-- // Expose push/clear handle via ref- useImperativeHandle(- handleRef as MutableRefObject<StreamGLHandle | null>,- () => ({- push(x: number, y: number) {- const r = ring.current;- const idx = r.head * 2;- r.data[idx] = x;- r.data[idx + 1] = y;- r.head = (r.head + 1) % bufferSize;- r.count = Math.min(r.count + 1, bufferSize);- draw();- },- clear() {- ring.current.head = 0;- ring.current.count = 0;- const gl = glRef.current;- if (gl) {- gl.clearColor(0, 0, 0, 0);- gl.clear(gl.COLOR_BUFFER_BIT);- }- },- }),- [bufferSize, draw],- );-- if (width <= 0 || height <= 0) {- return null;- }- return <g ref={markerRef} />;-}--/**- * WebGL streaming line. Data is pushed imperatively via handleRef,- * not from the chart's static dataset. Internally uses a ring buffer.- *- * @example- * ```- * const streamRef = useRef<StreamGLHandle>(null);- * // Push data points in a rAF loop or event handler:- * streamRef.current?.push(Date.now(), value);- *- * <Chart series={[streamGL({color: '#10b981', handleRef: streamRef})]} />- * ```- */-export function streamGL(options: StreamGLOptions): SeriesDef {- const {color} = options;- const bufferSize = options.bufferSize ?? 500;- const lineWidth = options.lineWidth ?? 2;- const opacity = options.opacity ?? 1;- const handleRef = options.handleRef;-- return {- type: 'streamGL',- key: 'stream',- dataKeys: [],- layout: {},-- // Streaming data is pushed, not in the static dataset- resolve() {- return [];- },-- render(_resolved, ctx) {- return (- <StreamGLCanvas- color={color}- bufferSize={bufferSize}- lineWidth={lineWidth}- opacity={opacity}- width={ctx.width}- height={ctx.height}- handleRef={handleRef}- />- );- },- };-}diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 9e1650ee78..1ed041621f 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -203,51 +203,7 @@ export {type SankeyContext,} from './Sankey';-// Chart v2 — config model-export {- Chart as ChartV2,- type ChartProps as ChartV2Props,- ChartLegend as ChartV2Legend,- type ChartLegendProps as ChartV2LegendProps,- type LegendItem as ChartV2LegendItem,- ChartAxis as ChartV2Axis,- type ChartAxisProps as ChartV2AxisProps,- ChartGrid as ChartV2Grid,- type ChartGridProps as ChartV2GridProps,- ChartSwatch as ChartV2Swatch,- swatchVariantForType as xdsChartV2SwatchVariantForType,- type ChartSwatchProps as ChartV2SwatchProps,- type ChartSwatchVariant as ChartV2SwatchVariant,- ChartTooltip as ChartV2Tooltip,- type ChartTooltipProps as ChartV2TooltipProps,- type ChartTooltipPlacement as ChartV2TooltipPlacement,- type TooltipSeriesValue as ChartV2TooltipSeriesValue,- bar,- line,- dot,- area,- band,- candlestick,- errorBar,- referenceLine,- dotGL,- dotGLInteractive,- heatmapGL,- streamGL,- useChartV2,- type SeriesDef,- type ChartV2Context,- type ChartPointerEvent,- type ResolvedPoint,- type ResolvedPositions,- type SeriesContext,- type ErrorBarOptions,- type ReferenceLineOptions,- type DotGLOptions,- type DotGLInteractiveOptions,- type HeatmapGLOptions,- type StreamGLOptions,- type StreamGLHandle,-} from './ChartV2';+// Chart v2 (config model) moved to its own package: @astryxdesign/charts.+// It is no longer re-exported from @astryxdesign/lab.export * from './Stepper';export * from './CircularProgress';diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 03c8d640a9..61cbdcf2e4 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -105,6 +105,9 @@ importers:apps/docsite:dependencies:+ '@astryxdesign/charts':+ specifier: '*'+ version: link:../../packages/charts'@astryxdesign/cli':specifier: '*'version: link:../../packages/cli@@ -442,6 +445,9 @@ importers:apps/sandbox:dependencies:+ '@astryxdesign/charts':+ specifier: '*'+ version: link:../../packages/charts'@astryxdesign/cli':specifier: '*'version: link:../../packages/cli@@ -524,6 +530,9 @@ importers:apps/storybook:dependencies:+ '@astryxdesign/charts':+ specifier: '*'+ version: link:../../packages/charts'@astryxdesign/core':specifier: '*'version: link:../../packages/core@@ -722,12 +731,31 @@ importers:'@stylexjs/stylex':specifier: '>=0.10.0'version: 0.18.3+ d3-array:+ specifier: ^3.2.4+ version: 3.2.4+ d3-scale:+ specifier: ^4.0.2+ version: 4.0.2+ d3-shape:+ specifier: ^3.2.0+ version: 3.2.0react:specifier: '>=19.0.0'version: 19.2.7react-dom:specifier: '>=19.0.0'version: 19.2.7([email protected])+ devDependencies:+ '@types/d3-array':+ specifier: ^3.2.2+ version: 3.2.2+ '@types/d3-scale':+ specifier: ^4.0.9+ version: 4.0.9+ '@types/d3-shape':+ specifier: ^3.1.8+ version: 3.1.8packages/cli:dependencies:@@ -747,6 +775,9 @@ importers:specifier: ^4.4.3version: 4.4.3devDependencies:+ '@astryxdesign/charts':+ specifier: '*'+ version: link:../charts'@astryxdesign/core':specifier: '*'version: link:../corediff --git a/scripts/build-css.mjs b/scripts/build-css.mjsindex 36b9a346f5..3e0b3dc4c9 100644--- a/scripts/build-css.mjs+++ b/scripts/build-css.mjs@@ -52,6 +52,19 @@ const TARGETS = {'@astryxdesign/core': [path.join(ROOT, 'packages/core/src')],},},+ charts: {+ src: path.resolve(ROOT, 'packages/charts/src'),+ dist: path.resolve(ROOT, 'packages/charts/dist'),+ outFile: 'charts.css',+ banner:+ 'Astryx Charts Pre-compiled StyleX CSS — data visualization components',+ // charts imports @astryxdesign/core/theme/tokens.stylex; point the resolver+ // at core's source so the cross-package token reference resolves.+ aliases: {+ '@astryxdesign/core/*': [path.join(ROOT, 'packages/core/src/*')],+ '@astryxdesign/core': [path.join(ROOT, 'packages/core/src')],+ },+ },};function parseTarget() {