Skip to content
Merged
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
11 changes: 11 additions & 0 deletions apps/reader/scripts/audit-library-article.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,17 @@ try {
return times.sort((a, b) => a - b)[3];
});
console.log("10k grid scroll to mounted row, ms", scrollMedian);
await grid.locator('[aria-rowindex="2"]').focus();
await grid.evaluate((element) => {
element.closest(".library-table-frame").scrollTop = 4800;
});
await expect(grid.locator('[aria-rowindex="2"]')).toHaveCount(0);
const search = page.getByRole("textbox", { name: "Search this view" });
await search.focus();
await search.press("ArrowDown");
await expect(grid.locator("[data-row-index]:focus")).toHaveCount(1);
await page.keyboard.press("Home");
await expect(grid.locator('[aria-rowindex="2"]')).toBeFocused();
await page.addScriptTag({ path: createRequire(import.meta.url).resolve("axe-core/axe.min.js") });
for (const width of [360, 768, 1280]) {
await page.setViewportSize({ width, height: 900 });
Expand Down
15 changes: 14 additions & 1 deletion apps/reader/scripts/audit-mobile-library.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { resolve } from "node:path";
import { chromium, expect } from "@playwright/test";
import { createServer } from "vite";

import { chooseOption } from "./audit-select.mjs";

const root = resolve(import.meta.dirname, "..");
const axePath = createRequire(import.meta.url).resolve("axe-core/axe.min.js");
const server = await createServer({
Expand Down Expand Up @@ -36,6 +38,7 @@ const collection = [
{
collectionId: "audit",
id: "structural",
readingStatus: "finished",
path: "sources/structural.md",
title: "Structural learning",
creators: ["Inez"],
Expand Down Expand Up @@ -82,11 +85,21 @@ try {
const search = page.getByRole("textbox", { name: "Search this view" });
await expect(grid).toHaveAttribute("aria-rowcount", "3", { timeout: 60000 });
await assertAxe(page, `${colorScheme} library`);
const filter = page.locator(".library-workspace-more > summary:visible");
await filter.tap();
const status = page.getByRole("combobox", { name: "Status", exact: true });
await chooseOption(status, "finished");
await expect(grid).toHaveAttribute("aria-rowcount", "2");
await expect(grid.getByRole("row", { name: /^Structural learning/u })).toBeVisible();
await chooseOption(status, "inbox");
await expect(grid.getByRole("row", { name: /^Attention and memory/u })).toBeVisible();
await chooseOption(status, "all");
await page.keyboard.press("Escape");
await expect(filter).toBeFocused();
await page.keyboard.press("/");
await expect(search).toBeFocused();
await search.fill("attention");
await expect(grid).toHaveAttribute("aria-rowcount", "2");
const filter = page.locator(".library-workspace-more > summary:visible");
await filter.tap();
const options = page.locator(".reader-menu-panel:visible").filter({ hasText: "Clear filters" });
const tag = page.getByRole("textbox", { name: "Tag", exact: true });
Expand Down
249 changes: 183 additions & 66 deletions apps/reader/scripts/benchmark-library-article.mjs
Original file line number Diff line number Diff line change
@@ -1,13 +1,45 @@
// Optional second server runs the same fixture on the baseline revision.
import { createHash } from "node:crypto";

import { chromium, expect } from "@playwright/test";

const origin = process.env.READER_AUDIT_ORIGIN ?? "http://127.0.0.1:5311";
const pairs = Number(process.env.READER_BENCH_PAIRS ?? 9);
const origins = [process.env.READER_BASELINE_ORIGIN, origin].filter(Boolean);
if (!Number.isInteger(pairs) || pairs < 1) {
throw new Error("READER_BENCH_PAIRS must be a positive integer.");
}
for (const url of origins) {
if (!/^http:\/\/(127\.0\.0\.1|localhost):\d+$/u.test(url)) {
throw new Error("Performance measurements require a loopback origin.");
}
}
const article = `<!doctype html><title>Long article</title><article><h1>Study 00000</h1>${Array.from(
{ length: 3000 },
(_, index) =>
`${index % 10 === 0 ? `<h2>Section ${index / 10}</h2>` : ""}<p id="p${index}">Passage [${index}]. ${"Attention and retention. ".repeat(6)}</p>`,
).join("")}</article>`;
const target = {
fileId: "article",
file: "[[article.html]]",
revision: `sha256:${createHash("sha256").update(article).digest("hex")}`,
mediaType: "text/html",
role: "primary",
};
const highlights = Array.from({ length: 600 }, (_, index) => ({
collectionId: "benchmark",
sourceId: "source-0",
id: `highlight-${index}`,
body: `> Passage [${index * 5}]

Reader highlight comment.`,
annotationType: "highlight",
tags: [],
createdAt: "2026-01-01T00:00:00Z",
recordRevision: "rev-1",
document: target,
target: { quote: { exact: `Passage [${index * 5}]` } },
}));
const articles = Array.from({ length: 10_000 }, (_, index) => ({
collectionId: "benchmark",
id: `source-${index}`,
Expand All @@ -16,7 +48,8 @@ const articles = Array.from({ length: 10_000 }, (_, index) => ({
creators: [`Author ${index % 673}`],
tags: [`tag-${index % 100}`, index % 2 ? "reading" : "research"],
published: String(1900 + (index % 125)),
documents: [],
readingStatus: ["inbox", "reading", "finished"][index % 3],
documents: index === 0 ? [target] : [],
properties: { tags: [`tag-${index % 100}`, index % 2 ? "reading" : "research"] },
frontmatter: {},
body: "",
Expand All @@ -27,9 +60,9 @@ const browser = await chromium.launch();
function summary(times) {
const sorted = times.toSorted((a, b) => a - b);
return {
median: Number(sorted[Math.floor(sorted.length / 2)].toFixed(2)),
p95: Number(sorted[Math.ceil(sorted.length * 0.95) - 1].toFixed(2)),
samples: times.map((time) => Number(time.toFixed(2))),
median: Number(sorted[Math.floor(sorted.length / 2)].toFixed(3)),
p95: Number(sorted[Math.ceil(sorted.length * 0.95) - 1].toFixed(3)),
samples: times.map((time) => Number(time.toFixed(3))),
};
}

Expand All @@ -40,85 +73,169 @@ try {
const lanes = [];
for (const url of origins) {
const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });
const page = await context.newPage();
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
await context.route(
(request) => request.origin !== url,
(route) => route.abort(),
);
await page.route(`${url}/__reader-audit/**`, (route) => {
const library = new URL(route.request().url()).pathname.endsWith("/library");
return route.fulfill({ json: library ? sources : [] });
});
await page.addInitScript((count) => {
performance.setResourceTimingBufferSize(5000);
globalThis.readerGridReady = new Promise((resolve, reject) => {
const observer = new globalThis.MutationObserver(() => {
if (globalThis.document.querySelector(`.library-table[aria-rowcount="${count + 1}"]`)) {
observer.disconnect();
const now = performance.now();
const response = performance.getEntriesByName(
new URL("/__reader-audit/library", globalThis.location.href).href,
)[0];
if (!response) {
reject(new Error("Missing library response timing"));
return;
}
resolve({
"startup to virtualized grid": now,
"library response to grid": now - response.responseEnd,
});
}
});
observer.observe(globalThis.document, {
attributes: true,
childList: true,
subtree: true,
});
});
}, count);
// Keep component timings independent of deferred React work following the first grid commit.
const fixture = await context.newPage();
fixture.on("pageerror", (error) => errors.push(error.message));
await fixture.goto(`${url}/test-fixtures/import-proof.html`);
lanes.push({ url, page, fixture, errors, times: {} });
const sidebarPage = await context.newPage();
sidebarPage.on("pageerror", (error) => errors.push(error.message));
lanes.push({ url, context, fixture, sidebarPage, errors, times: {} });
}
for (let pair = 0; pair < 10; pair++) {
for (const { url, page, fixture, errors, times } of pair % 2 ? lanes.toReversed() : lanes) {
await page.goto(`${url}/test-fixtures/audit-reader.html`, {
waitUntil: "domcontentloaded",
});
await expect(page.locator(".library-table:visible")).toHaveAttribute(
"aria-rowcount",
String(count + 1),
{ timeout: 60_000 },
);
const grid = await page.evaluate(() => globalThis.readerGridReady);
expect(await page.locator(".library-table:visible [data-row-index]").count()).toBeLessThan(
60,
);
const runs = await fixture.evaluate(
async ({ sources, moduleUrl }) =>
(await import(moduleUrl)).measureLibraryAndArticle(sources),
{ sources, moduleUrl: "/test-fixtures/library-article-benchmark.tsx" },
);
expect(errors).toEqual([]);
if (pair > 0) {
for (const [label, ms] of Object.entries({
...grid,
...runs,
})) {
(times[label] ??= []).push(ms);
for (let pair = 0; pair <= pairs; pair++) {
for (const { url, fixture, sidebarPage, errors, times } of pair % 2
? lanes.toReversed()
: lanes) {
console.error(`Benchmarking ${count} sources, pair ${pair || "warm-up"}, ${url}`);
const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });
try {
await context.route(
(request) => request.origin !== url,
(route) => route.abort(),
);
const page = await context.newPage();
page.on("pageerror", (error) => errors.push(error.message));
await page.route(`${url}/__reader-audit/**`, (route) => {
const path = new URL(route.request().url()).pathname.slice("/__reader-audit/".length);
if (path === "library") return route.fulfill({ json: sources });
if (path === "source/source-0") return route.fulfill({ json: sources[0] });
if (path === "document/article")
return route.fulfill({ body: article, contentType: "text/html" });
if (path === "annotations/source-0") return route.fulfill({ json: highlights });
return route.fulfill({ json: [] });
});
await page.addInitScript((count) => {
performance.setResourceTimingBufferSize(5000);
globalThis.readerGridReady = new Promise((resolve, reject) => {
const observer = new globalThis.MutationObserver(() => {
if (
globalThis.document.querySelector(`.library-table[aria-rowcount="${count + 1}"]`)
) {
observer.disconnect();
const now = performance.now();
const response = performance.getEntriesByName(
new URL("/__reader-audit/library", globalThis.location.href).href,
)[0];
if (!response) {
reject(new Error("Missing library response timing"));
return;
}
resolve({
"startup to virtualized grid": now,
"library response to grid": now - response.responseEnd,
});
}
});
observer.observe(globalThis.document, {
attributes: true,
childList: true,
subtree: true,
});
});
}, count);
await page.goto(`${url}/test-fixtures/audit-reader.html`, {
waitUntil: "domcontentloaded",
});
await expect(page.locator(".library-table:visible")).toHaveAttribute(
"aria-rowcount",
String(count + 1),
{ timeout: 60_000 },
);
const grid = await page.evaluate(() => globalThis.readerGridReady);
expect(
await page.locator(".library-table:visible [data-row-index]").count(),
).toBeLessThan(60);
const scroll = await page
.locator(".library-table:visible")
.evaluate(async (table, count) => {
const viewport = table.closest(".library-table-frame");
const index = Math.floor(count * 0.7);
const start = performance.now();
viewport.scrollTop = index * 48;
while (!table.querySelector(`[data-row-index="${index}"]`)) {
if (performance.now() - start > 5000)
throw new Error("Grid did not mount target row");
await new Promise((done) => globalThis.requestAnimationFrame(done));
}
const elapsed = performance.now() - start;
viewport.scrollTop = 0;
return elapsed;
}, count);
const open = await page
.locator('.library-table:visible a[href="#source=source-0"]')
.evaluate((link) => {
const start = performance.now();
link.click();
return new Promise((resolve, reject) => {
function wait() {
const frame = globalThis.document.querySelector("iframe.html-viewer");
const paragraph = frame?.contentDocument?.getElementById("p2999");
if (paragraph?.getBoundingClientRect().height) resolve(performance.now() - start);
else if (performance.now() - start > 10000)
reject(new Error("Article did not render"));
else globalThis.requestAnimationFrame(wait);
}
wait();
});
});
await page.close();
await sidebarPage.goto(
`${url}/test-fixtures/annotation-scale.html?count=600&format=html`,
{
waitUntil: "domcontentloaded",
},
);
const annotationPanel = sidebarPage.getByRole("button", { name: "Mount annotations" });
const sidebar = await annotationPanel.evaluate((tab) => {
const start = performance.now();
tab.click();
return new Promise((resolve, reject) => {
function wait() {
const cards = [
...globalThis.document.querySelectorAll('[data-item-id][aria-setsize="600"]'),
].filter(
(item) =>
item.getBoundingClientRect().height > 0 && !item.closest("[hidden], [inert]"),
);
if (cards.length > 0 && cards.length < 30) resolve(performance.now() - start);
else if (performance.now() - start > 10000)
reject(new Error("Annotation sidebar did not render a bounded window"));
else globalThis.requestAnimationFrame(wait);
}
wait();
});
});
const runs = await fixture.evaluate(
async ({ sources, moduleUrl }) =>
(await import(moduleUrl)).measureLibraryAndArticle(sources),
{ sources, moduleUrl: "/test-fixtures/library-article-benchmark.tsx" },
);
expect(errors).toEqual([]);
if (pair > 0) {
for (const [label, ms] of Object.entries({
...grid,
"virtualized scroll to target row": scroll,
"open article to first usable iframe": open,
"open annotation sidebar (600 highlights)": sidebar,
...runs,
})) {
(times[label] ??= []).push(ms);
}
}
} finally {
await context.close();
}
}
}
for (const { url, page, times } of lanes) {
for (const { url, context, times } of lanes) {
reports[`${count} @ ${url}`] = Object.fromEntries(
Object.entries(times).map(([k, v]) => [k, summary(v)]),
);
await page.context().close();
await context.close();
}
}
console.log(JSON.stringify({ chromium: browser.version(), milliseconds: reports }, null, 2));
Expand Down
13 changes: 8 additions & 5 deletions apps/reader/src/LibraryWorkspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -401,11 +401,14 @@ export function LibraryWorkspace({
updateFilter({ query: "" });
} else if (event.key === "ArrowDown" || event.key === "Escape") {
event.preventDefault();
resultsAreaRef.current
?.querySelector<HTMLElement>(
'.search-passage-list button, .library-table-row:not(.is-header)[tabindex="0"]',
)
?.focus();
const results = resultsAreaRef.current;
// The roving tab stop can be outside the mounted window after scrolling.
const target =
results?.querySelector<HTMLElement>(
'.search-passage-list button, .library-table-row[data-row-index][tabindex="0"]',
) ??
results?.querySelector<HTMLElement>(".library-table-row[data-row-index]");
target?.focus();
}
}}
/>
Expand Down
Loading