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 @@ -12,9 +12,9 @@ PR 1 = S1–S6 (foundation + the four easy charts). PR 2 = S7 (activity calendar

| Done | ID | Size | Step | Blocked by | Notes |
|---|---|---|---|---|---|
| [ ] | 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 checkbox, `__mt` handle, default Chart.js) | none | Nothing user-visible yet: the branch is not merged, and the flag defaults to Chart.js. On the branch, the TanStack core (~43–50 kB gzip) ships beside Chart.js until S12 |
| [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) |
| [ ] | 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 | `--ts-chart-1` palette + scss chrome; parity check on the about page |
| [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) |
| [ ] | 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 |
Expand Down
147 changes: 147 additions & 0 deletions frontend/__tests__/components/pages/SpeedHistogram.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
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 {
buildSpeedHistogramDefinition,
SpeedHistogram,
type SpeedHistogramData,
} from "../../../src/ts/components/pages/SpeedHistogram";
import { Theme } from "../../../src/ts/constants/themes";
import {
getUseTanstackCharts,
setUseTanstackCharts,
} from "../../../src/ts/dev/chart-parity";

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;

const data: SpeedHistogramData = {
labels: ["80 - 89", "90 - 99", "100 - 109", "110 - 119", "120 - 129"],
data: [
{ x: 80, y: 4, topPercentage: "top 99.50%" },
{ x: 90, y: 12, topPercentage: "top 97.00%" },
{ x: 100, y: 148, topPercentage: "top 85.00%" },
{ x: 110, y: 1 },
{ x: 120, y: 0 },
],
};

const rows = data.data.map((it, i) => ({
label: data.labels[i] ?? `${it.x} - ${it.x + 9}`,
count: it.y,
topPercentage: it.topPercentage,
}));

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

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

expect(scene.scales["x"]?.domain).toEqual([
"80 - 89",
"90 - 99",
"100 - 109",
"110 - 119",
"120 - 129",
]);
const yDomain = scene.scales["y"]?.domain as [number, number] | undefined;
expect(yDomain?.[0]).toBe(0);
expect(yDomain?.[1]).toBe(150);
});

it("keeps one bar per row; tiny buckets get a 2px minimum, zero stays zero", () => {
const definition = buildSpeedHistogramDefinition(rows, theme);

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

// the tiny bucket is clamped to chart.js's minBarLength: 2 (in count space);
// the zero bucket stays zero (accepted deviation: no minBarLength)
expect(scene.points.map((point) => point.yValue)).toEqual([
4,
12,
148,
(2 / 92) * 148,
0,
]);
expect(scene.points[0]?.xValue).toBe("80 - 89");
expect(scene.points[0]?.color).toBe("#222222");
});
});

describe("SpeedHistogram", () => {
afterEach(() => {
setUseTanstackCharts(false);
});

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

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(() => (
<SpeedHistogram data={data} />
));

expect(getUseTanstackCharts()).toBe(true);
expect(getByTestId("tanstack-chart")).not.toBeNull();
expect(queryByTestId("chartjs")).toBeNull();
});
});
1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"@solid-primitives/refs": "1.1.3",
"@solid-primitives/transition-group": "1.1.2",
"@solidjs/meta": "0.29.4",
"@tanstack/charts": "1.5.0",
"@tanstack/pacer-lite": "0.3.0",
"@tanstack/query-db-collection": "1.4.8",
"@tanstack/solid-db": "0.3.12",
Expand Down
58 changes: 58 additions & 0 deletions frontend/src/styles/tanstack-charts.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// TanStack Charts theme tokens (docs/specs/tanstack-charts): the library
// reads these off its chart host element (.ts-chart-host), so a theme change
// repaints the charts without touching chart definitions.
.ts-chart-host {
// foreground for ticks, labels, titles and default grid lines
color: var(--sub-color);

// default categorical palette for marks without an explicit paint
--ts-chart-1: var(--main-color);
--ts-chart-2: var(--sub-color);
--ts-chart-4: var(--sub-alt-color);
--ts-chart-3: var(--error-color);

// DOM tooltip chrome: the old Chart.js tooltip was a fixed dark bubble in
// every theme (the values below are its defaults), so parity means fixed
// values here, not theme variables
--ts-chart-tooltip-background: rgba(0, 0, 0, 0.8);
--ts-chart-tooltip-color: #fff;
--ts-chart-tooltip-border: 1px solid rgba(0, 0, 0, 0);
--ts-chart-tooltip-border-radius: 6px;
--ts-chart-tooltip-padding: 6px;
--ts-chart-tooltip-shadow: none;
--ts-chart-tooltip-font: 400 12px / 1.3 var(--font);
--ts-chart-tooltip-max-width: 200px;

// the library gives the chart's <svg> tabindex 0 (for keyboard focus), and
// Chrome paints the UA focus ring on mouse click even though :focus-visible
// does not match; the old Chart.js canvas wasn't focusable, so suppress the
// ring for pointer focus. The keyboard ring stays (:focus-visible).
svg:focus:not(:focus-visible) {
outline: none;
}

// chart.js parity: the library defaults its axis labels to 11px / weight 600
// at 0.76 opacity and its tick labels to 11px at 0.68 opacity, while the
// chart.js half renders scale titles and ticks at 12px / weight 400 / full
// opacity (its font defaults; the wrapper only overrides the family). These
// emit as SVG presentation attributes, which a stylesheet rule beats, so the
// host pins the chart.js metrics for every chart. The family inherits from
// the body (the site font) via the library's `inherit`, like chart.js.
svg text {
font-size: 12px;
font-weight: 400;
fill-opacity: 1;
}

// chart.js parity for the scale chrome: the library paints grid lines at
// 0.11 opacity and axis/tick lines at 0.28, while chart.js paints them at
// full opacity. These emit stroke-opacity as SVG presentation attributes,
// which a stylesheet rule beats, so the host pins it for every chart.
// Scoped to the grid/axis groups so chart marks (rules, areas, …) keep
// their own paint and opacity; stroke colors stay with each chart's scale
// options.
.ts-chart__grid line,
.ts-chart__axes line {
stroke-opacity: 1;
}
}
1 change: 1 addition & 0 deletions frontend/src/styles/vendor.scss
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
@import "fontawesome-5";
@import "slim-select/styles";
@import "balloon-css/src/balloon";
@import "tanstack-charts";
}
10 changes: 10 additions & 0 deletions frontend/src/ts/components/modals/DevOptionsModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import { z } from "zod";

import Ape from "../../ape";
import { refetchInboxCollection } from "../../collections/inbox";
import {
getUseTanstackCharts,
setUseTanstackCharts,
} from "../../dev/chart-parity";
import {
cycleUserDataLoadFail,
getForcedUserDataLoadFail,
Expand Down Expand Up @@ -147,6 +151,12 @@ export function DevOptionsModal(): JSXElement {
showModal("DevInboxPicker");
},
},
{
icon: "fa-chart-area",
label: () =>
`Chart Renderer (${getUseTanstackCharts() ? "TanStack Charts" : "Chart.js"})`,
onClick: () => setUseTanstackCharts(!getUseTanstackCharts()),
},
{
icon: "fa-chart-bar",
label: () => "Toggle Fake Chart Data",
Expand Down
74 changes: 2 additions & 72 deletions frontend/src/ts/components/pages/AboutPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@ import {
getTypingStatsQueryOptions,
} from "../../queries/public";
import { showModal } from "../../states/modals";
import { getTheme } from "../../theme/state";
import { getNumberWithMagnitude } from "../../utils/numbers";
import { Advertisement } from "../common/Advertisement";
import AsyncContent from "../common/AsyncContent";
import { Button } from "../common/Button";
import { ChartJs } from "../common/ChartJs";
import { H2, H3 } from "../common/Headers";
import { CommandlineHotkey } from "../core/hotkeys/CommandlineHotkey";
import { QuickRestartHotkey } from "../core/hotkeys/QuickRestartHotkey";
import { SpeedHistogram } from "./SpeedHistogram";

export function AboutPage(): JSXElement {
const contributors = useQuery(() => getContributorsQueryOptions());
Expand Down Expand Up @@ -88,76 +87,7 @@ export function AboutPage(): JSXElement {
>
{({ speedHistogramData }) => (
<>
<ChartJs
name="SpeedHistogram"
type="bar"
data={{
labels: speedHistogramData()?.labels ?? [],
datasets: [
{
yAxisID: "count",
label: "Users",
data: speedHistogramData()?.data ?? [],
minBarLength: 2,
backgroundColor: getTheme().main,
borderColor: getTheme().main,
},
],
}}
options={{
responsive: true,
maintainAspectRatio: false,
hover: {
mode: "nearest",
intersect: false,
},
scales: {
x: {
axis: "x",
bounds: "ticks",
display: true,
title: {
display: false,
text: "Bucket",
},
offset: true,
},
count: {
axis: "y",
beginAtZero: true,
min: 0,
ticks: {
autoSkip: true,
autoSkipPadding: 20,
stepSize: 10,
},
display: true,
title: {
display: true,
text: "Users",
},
},
},
plugins: {
annotation: {
annotations: [],
},
tooltip: {
animation: { duration: 250 },
intersect: false,
mode: "index",
callbacks: {
afterLabel: (context) => {
return (
(context.raw as { topPercentage?: string })
.topPercentage ?? ""
);
},
},
},
},
}}
/>
<SpeedHistogram data={speedHistogramData()} />
<div class="text-right text-xs text-sub">
distribution of time 60 leaderboard results (wpm) <br />
{numberOfHistogramRecords(speedHistogramData()?.data)} total
Expand Down
Loading
Loading