Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/specs/tanstack-charts/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ Companion to `spec.md` next to this file. One row per step; each step is one PR.

## Step by step

PR 1 = S1–S6 (foundation + the four easy charts). PR 2 = S7 (activity calendar). PR 3 = S8. PR 4 = S9. PR 5 = S10 (dev modal). S11 (measure) is a commit on the branch. S12 is the **move PR into `master`**: it applies the removal and ships the whole plan in one deploy.
PR 1 = S1–S6 (foundation + the four easy charts); S1 and S3 landed in [#8623](https://github.com/monkeytypegame/monkeytype/pull/8623) and S2 is a stacked PR on it, so PR 1 is now S4–S6. PR 2 = S7 (activity calendar). PR 3 = S8. PR 4 = S9. PR 5 = S10 (dev modal). S11 (measure) is a commit on the branch. S12 is the **move PR into `master`**: it applies the removal and ships the whole plan in one deploy.

| Done | ID | Size | Step | Blocked by | Notes |
|---|---|---|---|---|---|
| [x] | S1 | M · PR | **Foundation** (creates `integration/charts`): add `@tanstack/charts` 1.5.0 (solid peer); `vendor-chart` bundle test becomes `/node_modules\/(chart\|@tanstack\/charts\|d3-)/` moved ahead of `vendor-tanstack` (first match wins) — verify with a production build that the core + d3 modules land in `vendor-chart`; new `src/styles/tanstack-charts.scss` (host `color` + `--ts-chart-1…4` + `--ts-chart-tooltip-*` from our theme variables) imported in `vendor.scss`; dev-only parity flag (dev state module, DevOptionsModal button, `__mt` handle, default Chart.js) | none | Done in [#8623](https://github.com/monkeytypegame/monkeytype/pull/8623): dep, bundle group, tokens, parity flag (button shows the active renderer). Measured: core + solid adapter +41.2 kB gzip in `vendor-chart` (spec estimated 43–50); placement verified with a temporary probe import, since S1 imports the package nowhere — the core ships in the production build from S3 (first chart) until S12. After the first chart lands, `vendor-chart` measures 416.50 kB raw / 137.96 kB gzip (+52.7 kB gzip vs the 265.50/85.30 baseline — within the 150 kB-class budget) |
| [ ] | S2 | S · commit in PR 1 | **Cross mark**: small shared error-marker mark (rotated cross of constant-pixel arms) via `createMark`/`compositeMark` beside the built-in `dot`, with the existing "zero value → invisible" radius behaviour; falls back to plain `dot` if the composition proves fiddly | S1 | Used by S6 and S9. No `chart.js` `pointStyle: "crossRot"` equivalent exists in the library, hence the custom mark (spec, settled 4) |
| [x] | S2 | S · PR | **Cross mark**: small shared error-marker mark (rotated cross of constant-pixel arms) via `createMark`/`compositeMark` beside the built-in `dot`, with the existing "zero value → invisible" radius behaviour; falls back to plain `dot` if the composition proves fiddly | S1 | Done in [#8624](https://github.com/monkeytypegame/monkeytype/pull/8624), a stacked PR on S1 (#8623): `components/charts/error-cross.ts` exports `errorCross(rows, { x, y, yScale, color, size, strokeWidth })`, a `createMark` (not a composite: no built-in mark draws short free-standing segments) painting two constant-pixel `rule` arms per row — the Chart.js `crossRot` geometry, defaults matching its `pointRadius: 3`/`borderWidth: 2` — and one interaction point per row that stays at zero counts (the "hidden when zero" behaviour, the index-mode tooltip keeps zero rows); scale bindings follow the built-ins' `OptionScaleId` so an unbound mark owns the reserved scales in its type; asserted through `createChartScene` in `__tests__/components/charts/`. No chart consumes it yet (S6 and S9 will), so no visible change and no bundle delta: the `createMark` export ships in the `@tanstack/charts` root entry that S3 already pulls into `vendor-chart` (verified absent from the production build). The dot fallback is not taken. Used by S6 and S9; no `chart.js` `pointStyle: "crossRot"` equivalent exists in the library, hence the custom mark (spec, settled 4) |
| [x] | S3 | S · PR (in PR 1) | **About page speed histogram** on TanStack Charts: `barY` over the existing label/value rows, `scalePoint`/`scaleBand` x, linear y; axes/ticks/tooltip via the grammar; `minBarLength` has no equivalent (recorded deviation) | S1 | Done in [#8623](https://github.com/monkeytypegame/monkeytype/pull/8623): `SpeedHistogram` dual-renderer component with a pure `buildSpeedHistogramDefinition` (band x, zero-based nice linear y, group-x focus + tooltip) asserted via `createChartScene` in `__tests__/components/pages/SpeedHistogram.spec.tsx`. Browser parity verified on the about page, both renderers: the TanStack host follows the container width (no width; fixed 192 px height + `initialWidth` first frame per the responsive guide), labels thin collision-aware (13→5 at ~296 px, ends kept) like Chart.js's auto-rotation, theme change + tooltip OK. Zero buckets render empty (accepted `minBarLength` deviation). S4–S12 follow the same responsive host pattern |
| [ ] | S4 | S · PR (in PR 1) | **Account histogram** on TanStack Charts: `barY` over the existing buckets, same two axes; tooltip `group-x` index mode as today | S1 | |
| [ ] | S5 | M · PR (in PR 1) | **Daily activity chart** on TanStack Charts: `barY` (minutes, `count` axis) + `lineY` (avg speed, named right axis) + `linearRegressionY` dotted trendline (replaces `chartjs-plugin-trendline`); `scaleUtc` x with `Intl` day ticks ("d MMM"); tooltip `format`/`renderTooltipBody` reproducing the six-line content; `chartjs-adapter-date-fns` no longer needed by this chart | S1 | The trendline plugin and date adapter lose their last real users here (the Chart.js halves keep them until S12) |
Expand Down
6 changes: 3 additions & 3 deletions docs/specs/tanstack-charts/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Every chart becomes a direct consumer of TanStack Solid Charts' `Chart` componen
- **The activity calendar becomes a chart.** Following the library's calendar example (catalog 118, token-usage-calendar): one `cell` mark per in-window day on a week × weekday band-scale grid, an ordinal colour scale over the five levels, the months row as x-axis ticks and the weekday column as responsive y-axis ticks. The component works only on `days` and computes window, levels, months and weekdays itself. It retires the legacy DOM calendar module, completing solid-monkeytype U2 (that row links here and keeps its remainder text).
- **One integration branch, one move to master.** Every step lands on `integration/charts` (S1 creates it; each step is a PR against it). During development each chart component keeps its Chart.js implementation beside the new one, selected by a temporary dev-only flag (DevOptionsModal checkbox + `__mt` handle, default Chart.js), so reviewers compare the two renderings in the browser per step. When the last step is in, a single move PR brings the whole branch into `master`, and the removal of the Chart.js code ships inside that same PR: master never carries both chart libraries, and users get the new charts in one deploy. The calendar has no Chart.js half to compare against: it is verified against the existing calendar's behaviour directly.

Users see no behaviour change except the recorded deviations below: error markers may become dots, PB-line labels lose their badge background, zero-value bars may render at zero width, and tooltips move from the canvas to the library's DOM tooltip (styled to match via the scss tokens).
Users see no behaviour change except the recorded deviations below: PB-line labels lose their badge background, zero-value bars may render at zero width, and tooltips move from the canvas to the library's DOM tooltip (styled to match via the scss tokens).

## User Stories

Expand All @@ -47,7 +47,7 @@ Users see no behaviour change except the recorded deviations below: error marker
- Lines: `lineY`; smooth curves via `d3Curve(d3.curveCardinal.tension(0.5))` (Chart.js global `tension: 0.5`); straight where today is straight (daily-activity line). Where both look acceptable in the comparison, monotone is the fallback.
- Fills: `areaY`/gradient or `fill` + `fillOpacity` (result burst fill; the themed-area catalog example is the reference composition, with `decorative()` on the area/line where only the points or the tooltip should be interactive).
- Bars: `barY` with the existing categorical domain (histogram buckets, about-page histogram, daily-activity minutes).
- Error markers (rotated cross today): a small shared custom mark built with `createMark`/`compositeMark` drawing constant-pixel cross arms, reusing the existing "hidden when zero" radius logic; if the custom mark proves fiddly, plain `dot` is the recorded fallback.
- Error markers (rotated cross today): a shared `errorCross` mark in `components/charts/error-cross.ts`, a `createMark` (not a `compositeMark` — no built-in mark draws short free-standing segments) painting two constant-pixel rule arms per row, the Chart.js `crossRot` geometry with its `pointRadius: 3`/`borderWidth: 2` defaults; one interaction point per row, the arms dropped when the count is not positive — the existing "hidden when zero" behaviour, which keeps zero rows in the index-mode tooltip. Its scale bindings follow the built-ins' `OptionScaleId` semantics, so a mark without `yScale` owns the reserved scales in its type. The cross is kept (settled 4); the dot fallback is not taken.
- PB/funbox/percentile/identity annotation lines: `ruleY`/`ruleX` (+ `text` marks for labels); labels are plain text — the badge background is dropped (deviation).
- Daily-activity trendline: the `linearRegressionY` mark (dotted) replaces `chartjs-plugin-trendline`.
- Dual y-axes (result, history, daily activity, mini result): named scales with `channel: 'y'` + `side` + `yScale` binding; reversed axes via `reverse: true` (history x and accuracy); axis titles/labels via `axis.label`/`axis.ticks.format` (ticks thin and rotate automatically, replacing `autoSkip*`).
Expand All @@ -59,7 +59,7 @@ Users see no behaviour change except the recorded deviations below: error marker
- **Theme colors**: `src/styles/tanstack-charts.scss` sets, on the chart host class: `color` (foreground for ticks, labels, titles, grid defaults) from the text/sub variables, `--ts-chart-1…4` from `--main-color`/`--sub-color`/`--error-color`/`--sub-alt-color`, and `--ts-chart-tooltip-*` (background from `--bg-color`, border/radius/shadow from sub-alt + roundness). It is imported in `vendor.scss` alongside the other vendor libraries. Visible grid lines that Chart.js painted with `subAlt` are set per-scale with that variable in the definition. Data-mark paints resolve the theme state in the definition as today.
- **Bundle**: `vite.config.ts` `vendor-chart` group test becomes `/node_modules\/(chart|@tanstack\/charts|d3-)/` and the group moves ahead of `vendor-tanstack` (first match wins), so the core, its d3 dependencies, and the legacy Chart.js packages all land in one chunk until the removal step. No `@tanstack/charts/canvas` import ships until the (later) canvas step.
- **Parity flag**: one dev-only boolean (dev state module, DevOptionsModal checkbox, exposed on `__mt`) that each chart component reads to pick between its two implementations; it defaults to Chart.js, so an unverified chart on the integration branch behaves exactly as on master, and tests are unchanged. Both implementations in a chart component are visible side by side in code; the old half carries a `// Stepping stone: replaced by the TanStack implementation; removed in S12` comment.
- **Intended deviations** (user-visible, accepted): error markers may render as dots instead of rotated crosses; PB/funbox annotation labels lose their rounded badge background; zero-value bars may render at zero width (no `minBarLength`); tooltips are DOM elements with the library's positioning instead of Chart.js's on-canvas box (visuals matched via the scss tokens).
- **Intended deviations** (user-visible, accepted): PB/funbox annotation labels lose their rounded badge background; zero-value bars may render at zero width (no `minBarLength`); tooltips are DOM elements with the library's positioning instead of Chart.js's on-canvas box (visuals matched via the scss tokens).

## Testing Decisions

Expand Down
181 changes: 181 additions & 0 deletions frontend/__tests__/components/charts/error-cross.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import { scaleLinear } from "@tanstack/charts/scales/linear";
import { defineChart } from "@tanstack/charts";
import { createChartScene } from "@tanstack/charts/scene";
import { describe, expect, it, vi } from "vitest";

// jsdom has no font metrics: a deterministic stub keeps the scene layout stable
vi.mock("@tanstack/charts/scene", async (importOriginal) => {
const actual =
await importOriginal<typeof import("@tanstack/charts/scene")>();
return {
...actual,
createChartScene: (
definition: unknown,
size: { width: number; height: number },
) =>
actual.createChartScene(definition as never, size, {
measureText: (text: string) => ({
x: 0,
y: 0,
width: text.length * 6,
height: 10,
}),
}),
};
});

import type { SceneGroup, SceneNode } from "@tanstack/charts";
import {
errorCross,
type ErrorCrossOptions,
} from "../../../src/ts/components/charts/error-cross";

type ErrorRow = {
second: number;
err: number;
};

const rows: ErrorRow[] = [
{ second: 1, err: 0 },
{ second: 2, err: 0 },
{ second: 3, err: 3 },
{ second: 4, err: 0 },
{ second: 5, err: 2 },
];

const COLOR = "#ff0000";

const definition = defineChart({
marks: [
errorCross(rows, {
x: "second",
y: "err",
color: COLOR,
} satisfies ErrorCrossOptions<ErrorRow>),
],
scales: {
x: { scale: () => scaleLinear() },
y: { scale: () => scaleLinear() },
},
});

const scene = createChartScene(definition as never, {
width: 800,
height: 200,
});

function markGroup(node: SceneNode): SceneGroup | undefined {
if (node.kind !== "group") return undefined;
if (node.className === "ts-chart__error-cross") return node;
for (const child of node.children) {
const found = markGroup(child);
if (found) return found;
}
return undefined;
}

const group = scene.nodes.map(markGroup).find((it) => it !== undefined);

describe("errorCross", () => {
it("binds the error counts to the y scale", () => {
const yDomain = scene.scales["y"]?.domain as readonly number[];
expect(yDomain).toEqual([0, 3]);
const xDomain = scene.scales["x"]?.domain as readonly number[];
expect(xDomain).toEqual([1, 5]);
});

it("emits one point per row, zero errors included", () => {
const points = scene.points.filter((point) => point.color === COLOR);
expect(points.map((point) => point.yValue)).toEqual([0, 0, 3, 0, 2]);
expect(points.map((point) => point.xValue)).toEqual([1, 2, 3, 4, 5]);
// stable keys, one per row
expect(points.map((point) => point.key).sort()).toEqual(
[...points.map((point) => point.key)].sort(),
);
expect(new Set(points.map((point) => point.key)).size).toBe(5);
// every point sits on its row
expect(points.every((point) => Number.isFinite(point.x))).toBe(true);
expect(points.every((point) => Number.isFinite(point.y))).toBe(true);
});

it("paints a rotated cross per positive error and nothing for zero", () => {
expect(group?.kind).toBe("group");
const rules = (group?.children ?? []).filter(
(node) => node.kind === "rule",
);
// rows 3 and 5 have errors; each paints two arms
expect(rules.length).toBe(4);

const yScale = scene.scales["y"];
const xScale = scene.scales["x"];
if (!yScale || !xScale) throw new Error("scales missing");
const x3 = xScale.map(3);
const y3 = yScale.map(3);
const arm = 3 / Math.SQRT2;

const first = rules[0];
expect(first?.kind).toBe("rule");
if (first?.kind === "rule") {
expect(first.x1).toBeCloseTo(x3 - arm);
expect(first.y1).toBeCloseTo(y3 - arm);
expect(first.x2).toBeCloseTo(x3 + arm);
expect(first.y2).toBeCloseTo(y3 + arm);
expect(first.style?.stroke).toBe(COLOR);
expect(first.style?.strokeWidth).toBe(2);
}
// the second arm is the other diagonal
const second = rules[1];
if (second?.kind === "rule") {
expect(second.x1).toBeCloseTo(x3 - arm);
expect(second.y1).toBeCloseTo(y3 + arm);
expect(second.x2).toBeCloseTo(x3 + arm);
expect(second.y2).toBeCloseTo(y3 - arm);
}
// the zero rows paint nothing
const y0 = yScale.map(0);
const onZeroRows = rules.filter((node) => {
if (node.kind !== "rule") return false;
return Math.abs(node.y1 - y0) < 1e-9 && Math.abs(node.y2 - y0) < 1e-9;
});
expect(onZeroRows).toEqual([]);
});

it("binds to a named error scale when given", () => {
const named = defineChart({
marks: [
errorCross(rows, {
x: "second",
y: "err",
yScale: "error",
color: COLOR,
}),
],
scales: {
x: { scale: () => scaleLinear() },
// the mark binds its y channel to the named scale, so the reserved
// y scale is dormant
y: null,
error: {
scale: () => scaleLinear(),
channel: "y",
side: "right",
},
},
});

const scene = createChartScene(named as never, {
width: 800,
height: 200,
});

const errorDomain = scene.scales["error"]?.domain as readonly number[];
expect(errorDomain).toEqual([0, 3]);
const errorScale = scene.scales["error"];
if (!errorScale) throw new Error("error scale missing");
const y0 = errorScale.map(0);
const y3 = errorScale.map(3);
const y2 = errorScale.map(2);
const points = scene.points.filter((point) => point.color === COLOR);
expect(points.map((point) => point.y)).toEqual([y0, y0, y3, y0, y2]);
});
});
Loading
Loading