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
2 changes: 1 addition & 1 deletion docs/specs/tanstack-charts/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ PR 1 = S1–S6 (foundation + the four easy charts); S1 and S3 landed in [#8623](
| [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) |
| [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 | |
| [x] | 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 | Done in [#8626](https://github.com/monkeytypegame/monkeytype/pull/8626): `HistogramChart` dual-renderer with a pure `buildHistogramChartDefinition` (band x + 0.28 padding, zero-based nice linear y, `group-x` focus + `Tests: N` tooltip) asserted via `createChartScene` in `__tests__/components/pages/account/HistogramChart.spec.tsx`. Browser parity on the account page, both renderers: bar ratio 0.72 in both, `subAlt` grids (like chart.js), theme change + tooltip OK; at narrow widths the labels thin (13→5, ends kept) vs chart.js's rotate-and-skip (accepted, same as S3). `vendor-chart` unchanged (416.5 kB / 138.0 kB gzip, identical to S3) |
| [ ] | 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) |
| [ ] | S6 | S · PR (in PR 1) | **Mini result chart** (modal) on TanStack Charts: wpm/burst `lineY` + error cross mark (S2) on a named right axis; `beginAtZero` + unit follow the existing config signals | S1, S2 | Modal-sized (240 px); tooltip `group-x` as today |
| [ ] | S7 | M · PR | **Activity calendar** (account page and profile) on TanStack Charts, after catalog example 118 (token-usage-calendar): one `cell` mark per in-window day, x = week band scale, y = weekday band scale, colour = ordinal scale over five levels; the `getBuckets` level logic (trim 10%/10% of non-zero counts, buckets from the middle average: outlier-insensitive) moves into the component, which works only on `days: TestActivityDay[]` (prop) + `isAccountPage` and computes the window (last 12 months / full year), week/weekday placement, the months row (x-axis ticks: explicit values + names + responsive thinning) and the weekday column (y-axis ticks, shortened/hidden responsively) itself; the `getBuckets`-family calendar helpers in `states/test-activity.ts` become dead and go, `loadAllYearsTestActivity` stays (the only import besides the type); tooltip via `format` with the existing per-day labels + keyboard focus (an improvement over the balloon); square cells via `aspectRatio`; the chrome stays Solid (year dropdown, total-tests title, less→more legend, UTC note, no-data state); delete `elements/test-activity.ts` and trim `test-activity.scss` (level colours move to `tanstack-charts.scss` as `--activity-level-0…4`, same color-mix values, shared by the scale range and the legend) | S3, S4, S5, S6 (its own PR, after PR 1) | No Chart.js involved: this retires the legacy DOM calendar, the "left: the Solid component" remainder of solid-monkeytype U2 (that row links here), and trims its scss |
Expand Down
162 changes: 162 additions & 0 deletions frontend/__tests__/components/pages/account/HistogramChart.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { Mode } from "@monkeytype/schemas/shared";
import { render } from "@solidjs/testing-library";
import { createChartScene } from "@tanstack/charts/scene";
import { afterEach, 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,
}),
}),
};
});
// no canvas in jsdom - the chart halves render test markers
vi.mock("../../../../src/ts/components/common/ChartJs", () => ({
ChartJs: () => <div data-testid="chartjs" />,
}));
vi.mock("@tanstack/charts/solid", () => ({
Chart: (props: { ariaLabel?: string }) => (
<div data-testid="tanstack-chart" aria-label={props.ariaLabel} />
),
}));

import type { NormalizedLocalResult } from "../../../../src/ts/collections/results";

import {
buildHistogramChartDefinition,
HistogramChart,
type HistogramChartRow,
} from "../../../../src/ts/components/pages/account/HistogramChart";
import { Theme } from "../../../../src/ts/constants/themes";
import {
getUseTanstackCharts,
setUseTanstackCharts,
} from "../../../../src/ts/dev/chart-parity";
import { get as getTypingSpeedUnit } from "../../../../src/ts/utils/typing-speed-units";

const theme = (): Theme =>
({
name: "default",
bg: "#111111",
main: "#222222",
caret: "#333333",
sub: "#444444",
subAlt: "#555555",
text: "#666666",
error: "#777777",
errorExtra: "#888888",
colorfulError: "#777777",
colorfulErrorExtra: "#888888",
}) as Theme;

// fixed wpm data: ten wpm buckets up to 50 wpm, one empty bucket
const rows: HistogramChartRow[] = [
{ label: "0-9", count: 3 },
{ label: "10-19", count: 5 },
{ label: "20-29", count: 12 },
{ label: "30-39", count: 0 },
{ label: "40-49", count: 2 },
];

describe("buildHistogramChartDefinition", () => {
it("places every bucket on the x scale and counts on a zero-based y scale", () => {
const definition = buildHistogramChartDefinition(rows, theme);

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

expect(scene.scales["x"]?.domain).toEqual(rows.map((it) => it.label));
const yDomain = scene.scales["y"]?.domain as [number, number] | undefined;
expect(yDomain?.[0]).toBe(0);
expect(yDomain?.[1] ?? 0).toBeGreaterThanOrEqual(12);
});

it("keeps one bar per bucket painted in the theme main; zero stays zero", () => {
const definition = buildHistogramChartDefinition(rows, theme);

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

expect(scene.points.map((point) => point.yValue)).toEqual([3, 5, 12, 0, 2]);
expect(scene.points[0]?.xValue).toBe("0-9");
expect(scene.points.every((point) => point.color === "#222222")).toBe(true);
});

it("focuses by bucket (group-x) and labels the tooltip with the test count", () => {
const definition = buildHistogramChartDefinition(rows, theme);

expect(definition.focus).toEqual("group-x");

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

const content = definition.tooltip?.content;
expect(content).toBeDefined();
// the focused points for a group-x hover: the one bar under the pointer
const focusedPoint = scene.points[2];
expect(focusedPoint).toBeDefined();
const result = content?.([focusedPoint as never]);

expect(result).toBeDefined();
expect(result?.title).toBe(rows[2]?.label);
expect(result?.rows).toEqual([
{ label: "Tests: 12", value: "", color: "#222222" },
]);
});
});

describe("HistogramChart", () => {
const results = [
{ wpm: 12.5 },
{ wpm: 18 },
{ wpm: 21 },
{ wpm: 33.2 },
] as NormalizedLocalResult<Mode>[];

const unit = getTypingSpeedUnit("wpm");

afterEach(() => {
setUseTanstackCharts(false);
});

it("renders the Chart.js half by default", () => {
const { getByTestId, queryByTestId } = render(() => (
<HistogramChart results={results} typingSpeedUnit={unit} />
));

expect(getUseTanstackCharts()).toBe(false);
expect(getByTestId("chartjs")).not.toBeNull();
expect(queryByTestId("tanstack-chart")).toBeNull();
});

it("renders the TanStack half when the parity flag is on", () => {
setUseTanstackCharts(true);

const { getByTestId, queryByTestId } = render(() => (
<HistogramChart results={results} typingSpeedUnit={unit} />
));

expect(getUseTanstackCharts()).toBe(true);
expect(getByTestId("tanstack-chart")).not.toBeNull();
expect(queryByTestId("chartjs")).toBeNull();
});
});
Loading
Loading