Merge pull request #1145 from MBombeck/perf/dashboard-client

perf: faster charts and insights, no sidebar scrollbar flash, Umami events delivered
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-10-04 17:33:51 +02:00
commit 006679ed9e
33 files changed
+1458 -393

No files matched your search

+6
View File
@@ -6,6 +6,7 @@ import { STORAGE_STATE_PATH } from "./setup/global-setup";
import { aiBlockAvailable, serveAiBlock } from "./setup/ai-capabilities";
import { openMenu } from "./open-menu";
import { POPULATED_SUMMARIES } from "./utils/mock-dashboard-snapshot";
import { revealDeferredSections } from "./utils/deferred-sections";
type AxeViolation = Awaited<
ReturnType<AxeBuilder["analyze"]>
@@ -41,6 +42,8 @@ type RouteCase = {
name: string;
path: string;
painted: (page: Page) => Locator;
/** Runs after navigation, before the painted gate (e.g. mount deferred sections). */
prepare?: (page: Page) => Promise<void>;
};
const THEMES: readonly Theme[] = ["light", "dark"];
@@ -325,6 +328,7 @@ async function visitAndScan(
): Promise<AxeViolation[]> {
return test.step(`${theme} ${routeCase.name}`, async () => {
await page.goto(routeCase.path, { waitUntil: "domcontentloaded" });
await routeCase.prepare?.(page);
return scanPaintedState(
page,
theme,
@@ -773,6 +777,8 @@ const INSIGHTS_ROUTES: readonly RouteCase[] = [
{
name: "/insights overview",
path: "/insights",
// Scan the whole overview, the sections that mount near the viewport too.
prepare: revealDeferredSections,
// The vitals grid, settled. The scores strip is not a stable gate: it
// unmounts for an account with no score yet, and since v1.39 it no longer
// keeps an empty cell for a cycle ring that has no dial to draw.
+104
View File
@@ -0,0 +1,104 @@
import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
/**
* Recharts measures every tick label in one shared off-screen span
* (`#recharts_measurement_span`). Under `<body>` each read cost a
* document-wide style recalc, because the stylesheet's descendant-subject
* `:has()` rules leave Chromium no way to scope the invalidation; on a
* seeded dashboard that was about 1.8 s of main-thread time under a 4x CPU
* slowdown. The chart runtime now parks the span in a contained host under
* `<html>` (`src/components/charts/text-measurement-host.ts`).
*
* Pinned here, in a real engine:
* - the span Recharts uses is the one in the host, not a second one it
* created under `<body>`, including after a client-side round trip;
* - every string the charts drew measures exactly as it does under
* `<body>`, so the move cannot change a single tick or label.
*/
test.describe("chart text measurement host", () => {
test.use({ storageState: STORAGE_STATE_PATH });
async function assertHostInPlace(page: import("@playwright/test").Page) {
const placement = await page.evaluate(() => {
const spans = document.querySelectorAll("#recharts_measurement_span");
const span = spans[0] as HTMLElement | undefined;
return {
count: spans.length,
hostSlot: span?.parentElement?.dataset.slot ?? null,
hostParent: span?.parentElement?.parentElement?.tagName ?? null,
};
});
expect(placement).toEqual({
count: 1,
hostSlot: "chart-text-measurement-host",
hostParent: "HTML",
});
}
test("the dashboard charts measure text outside <body>, with identical results", async ({
page,
}) => {
await page.goto("/", { waitUntil: "domcontentloaded" });
await expect(page.locator(".recharts-wrapper").first()).toBeVisible({
timeout: 20_000,
});
await assertHostInPlace(page);
const parity = await page.evaluate(() => {
const host = document.getElementById(
"recharts_measurement_span",
) as HTMLElement;
const reference = document.createElement("span");
document.body.appendChild(reference);
// Recharts' own measurement style (`getStringSize`).
const base = {
position: "absolute",
top: "-20000px",
left: "0",
padding: "0",
margin: "0",
border: "none",
whiteSpace: "pre",
};
const strings = [
...new Set(
[...document.querySelectorAll(".recharts-wrapper text")]
.map((el) => el.textContent ?? "")
.filter(Boolean),
),
];
const mismatches: string[] = [];
for (const fontSize of ["10px", "12px", "14px"]) {
for (const text of strings) {
Object.assign(host.style, base, { fontSize });
Object.assign(reference.style, base, { fontSize });
host.textContent = text;
reference.textContent = text;
const a = host.getBoundingClientRect();
const b = reference.getBoundingClientRect();
if (a.width !== b.width || a.height !== b.height) {
mismatches.push(`${text}@${fontSize}`);
}
}
}
reference.remove();
return { measured: strings.length, mismatches };
});
// A chart with no labels would make the parity check vacuous.
expect(parity.measured).toBeGreaterThan(0);
expect(parity.mismatches).toEqual([]);
// A client-side round trip re-renders the shell; the host must survive
// it, or Recharts quietly recreates its span under <body>.
await page.locator('a[href="/insights"]:visible').first().click();
await page.waitForURL((url) => url.pathname === "/insights");
await page.locator('a[href="/"]:visible').first().click();
await page.waitForURL((url) => url.pathname === "/");
await expect(page.locator(".recharts-wrapper").first()).toBeVisible({
timeout: 20_000,
});
await assertHostInPlace(page);
});
});
+7
View File
@@ -9,6 +9,7 @@ import {
PHONE_WIDTHS,
settleForOverflowMeasurement,
} from "./utils/horizontal-overflow";
import { revealDeferredSections } from "./utils/deferred-sections";
/**
* The content-heavy routes must not scroll sideways at any phone width.
@@ -73,6 +74,9 @@ test.describe("content-heavy routes have no horizontal page scroll at phone widt
for (const width of PHONE_WIDTHS) {
await page.setViewportSize({ width, height: 851 });
await page.goto(routeCase.path, { waitUntil: "domcontentloaded" });
// Measure the whole page, the overview sections that wait for the
// viewport included, or a wide card far down would go unmeasured.
if (routeCase.path === "/insights") await revealDeferredSections(page);
await expect(page.locator(routeCase.ready).first()).toBeVisible();
await settleForOverflowMeasurement(page);
await expectNoHorizontalOverflow(page, `${routeCase.path} @${width}px`);
@@ -93,6 +97,7 @@ test.describe("content-heavy routes have no horizontal page scroll at phone widt
await mockPopulatedInsights(page);
await page.setViewportSize({ width: 390, height: 851 });
await page.goto("/insights", { waitUntil: "domcontentloaded" });
await revealDeferredSections(page);
const signals = page.locator('[data-slot="coincident-deviation-section"]');
await expect(signals).toBeVisible();
@@ -129,6 +134,7 @@ test.describe("content-heavy routes have no horizontal page scroll at phone widt
await mockPopulatedInsights(page);
await page.setViewportSize({ width: 390, height: 851 });
await page.goto("/insights", { waitUntil: "domcontentloaded" });
await revealDeferredSections(page);
// Wait on the CAPTION, not the heading: the card first paints a skeleton
// whose heading carries no action slot, then swaps to the resolved shell.
@@ -179,6 +185,7 @@ test.describe("content-heavy routes have no horizontal page scroll at phone widt
await mockPopulatedInsights(page);
await page.setViewportSize({ width: 390, height: 851 });
await page.goto("/insights", { waitUntil: "domcontentloaded" });
await revealDeferredSections(page);
// Wait for the same readiness signal and settle step every route case
// above uses. This was the one test in the file that measured and injected
// straight after `domcontentloaded`, against a tree that was still
+3
View File
@@ -25,6 +25,7 @@ import type { Page } from "@playwright/test";
import { MODULES_STORAGE_STATE_PATH } from "./setup/global-setup";
import { modulesSeedState } from "./setup/modules-fixture";
import { expect, test } from "./setup/test";
import { revealDeferredSections } from "./utils/deferred-sections";
test.use({ storageState: MODULES_STORAGE_STATE_PATH });
test.describe.configure({ mode: "serial" });
@@ -130,6 +131,8 @@ test("mood and medications, switched off, leave every surface they own", async (
await expect(
page.locator('[data-slot="insights-tab-strip-pill"][href="/insights"]'),
).toBeVisible({ timeout: 20_000 });
// The trends row sits below the sections that mount with the page.
await revealDeferredSections(page);
await expect(page.locator('[data-slot="trends-row"]')).toBeVisible();
await expect(page.locator(moodPill)).toHaveCount(0);
await expect(page.locator(medsPill)).toHaveCount(0);
+139
View File
@@ -0,0 +1,139 @@
import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
/**
* Expanding the sidebar must never flash a scrollbar on the nav list.
*
* The rail animates `width` from `w-16` to `w-64`. When the labels laid out
* against the growing width, every row overran the 48 px nav and the
* multi-word labels wrapped, so the nav's `overflow-y-auto` painted a
* vertical and a horizontal scrollbar until the transition ended. The fix
* lays the column out at its final width from the first frame and lets the
* rail clip it (see `sidebar-column` in `src/components/layout/sidebar-nav.tsx`).
*
* This samples the nav on every animation frame of a real expand and a real
* collapse, so it fails on the overflow itself rather than on a class name.
* Desktop only: the sidebar is hidden below `md`.
*/
test.describe("sidebar width transition", () => {
test.use({ storageState: STORAGE_STATE_PATH });
test.beforeEach(({}, testInfo) => {
test.skip(
testInfo.project.name === "chromium-mobile",
"global sidebar is desktop-only (md+)",
);
});
test("the nav list never overflows while the rail expands or collapses", async ({
page,
}) => {
await page.goto("/", { waitUntil: "domcontentloaded" });
const toggle = page.locator('[data-slot="sidebar-collapse-toggle"]');
await expect(toggle).toBeVisible();
const nav = page.locator("aside nav").first();
await expect(nav).toBeVisible();
async function sampleToggle() {
const heightBefore = await nav.evaluate((el) => el.scrollHeight);
await page.evaluate(() => {
const el = document.querySelector("aside nav") as HTMLElement;
const samples: { sw: number; cw: number; sh: number }[] = [];
(window as unknown as { __navSamples: typeof samples }).__navSamples =
samples;
const t0 = performance.now();
const tick = () => {
samples.push({
sw: el.scrollWidth,
cw: el.clientWidth,
sh: el.scrollHeight,
});
if (performance.now() - t0 < 600) requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
});
await toggle.click();
await page.waitForTimeout(700);
const samples = await page.evaluate(
() =>
(
window as unknown as {
__navSamples: { sw: number; cw: number; sh: number }[];
}
).__navSamples,
);
const heightAfter = await nav.evaluate((el) => el.scrollHeight);
// Expanded rows are taller than rail rows, so the list may legitimately
// be either rest height while the width moves, never more.
return { samples, restHeight: Math.max(heightBefore, heightAfter) };
}
// Two round trips, so the run covers both directions whichever state
// the stored preference started in.
for (let i = 0; i < 4; i++) {
const { samples, restHeight } = await sampleToggle();
// A 200 ms transition yields several frames; too few means the
// sampler never ran and the assertions below would prove nothing.
expect(samples.length).toBeGreaterThan(5);
for (const s of samples) {
// No horizontal overflow: no row is wider than the nav.
expect(s.sw).toBeLessThanOrEqual(s.cw + 1);
}
// No vertical growth: no label wraps mid-transition, so the list is
// never taller than at rest and cannot summon a scrollbar.
const tallest = Math.max(...samples.map((s) => s.sh));
expect(tallest).toBeLessThanOrEqual(restHeight + 1);
}
});
test("on a short window the list scrolls behind a visible edge, never under the footer", async ({
page,
}) => {
// Short enough that the list cannot fit between the logo band and the
// footer group. The rail used to cut the last visible entry off right at
// the Collapse row with nothing marking the edge, which read as the
// footer covering the entry.
await page.setViewportSize({ width: 1280, height: 600 });
await page.goto("/", { waitUntil: "domcontentloaded" });
const nav = page.locator("aside nav").first();
const footer = page.locator('aside [data-slot="sidebar-footer"]');
await expect(nav).toBeVisible();
await expect(footer).toHaveAttribute("data-nav-overflows", "true");
const borderTop = await footer.evaluate(
(el) => getComputedStyle(el).borderTopWidth,
);
expect(borderTop).toBe("1px");
// Scrolled to its end, the last entry sits wholly inside the list,
// above the footer, and is the element under its own centre.
const end = await nav.evaluate((el) => {
el.scrollTop = el.scrollHeight;
const links = [...el.querySelectorAll("a")];
const last = links[links.length - 1] as HTMLElement;
const r = last.getBoundingClientRect();
const navBox = el.getBoundingClientRect();
const footerTop = (
document.querySelector('aside [data-slot="sidebar-footer"]') as Element
).getBoundingClientRect().top;
const hit = document.elementFromPoint(
r.left + r.width / 2,
r.top + r.height / 2,
);
return {
insideList: r.bottom <= navBox.bottom + 0.5,
aboveFooter: r.bottom <= footerTop + 0.5,
hitsItself: last.contains(hit),
};
});
expect(end).toEqual({
insideList: true,
aboveFooter: true,
hitsItself: true,
});
// With room to spare there is no edge: the default rail is unchanged.
await page.setViewportSize({ width: 1280, height: 1400 });
await expect(footer).not.toHaveAttribute("data-nav-overflows", "true");
});
});
+38
View File
@@ -0,0 +1,38 @@
import { expect, type Page } from "@playwright/test";
/**
* Mount every overview section that waits for the viewport.
*
* Sections below the first screens of `/insights` render as a 1 px
* `[data-deferred-section]` sentinel until they come near the visible area
* (`src/components/insights/defer-until-near.tsx`). A spec that asserts on
* one of them, or measures or scans the whole page, scrolls each sentinel
* into view first, the way a reader would, until none is left. Polled, since
* the observers only exist once the page has hydrated.
*/
export async function revealDeferredSections(page: Page): Promise<void> {
// The sentinels render with the overview itself; until the hero is there,
// "no sentinel" only means the page has not rendered yet.
await expect(page.locator('[data-slot="insights-hero-strip"]')).toBeAttached({
timeout: 20_000,
});
const sentinels = page.locator("[data-deferred-section]");
await expect
.poll(
async () => {
const remaining = await sentinels.count();
if (remaining > 0) {
await sentinels
.first()
.scrollIntoViewIfNeeded({ timeout: 1_000 })
.catch(() => {
// Mounted between the count and the scroll.
});
}
return remaining;
},
{ timeout: 20_000 },
)
.toBe(0);
await page.evaluate(() => document.querySelector("main")?.scrollTo(0, 0));
}