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
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ jobs:
run: pnpm --filter @mdbase-reader/app test:pdf-touch
- name: Verify library keyboard navigation and restored article highlights
run: pnpm --filter @mdbase-reader/app test:library-article
- name: Verify mobile library filters and article accessibility
run: pnpm --filter @mdbase-reader/app test:mobile-library
- name: Verify imported SVG rendering in the HTML sandbox
run: pnpm --filter @mdbase-reader/app test:html-svg
- name: Verify private feedback with sample data and intercepted delivery
Expand Down
2 changes: 2 additions & 0 deletions apps/reader/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
"preview": "vite preview --host 127.0.0.1",
"test": "pnpm manifest && pnpm manifest:verify && node --test scripts/*.test.mjs && vitest run src capture --maxWorkers=2 --testTimeout=15000",
"bench:library": "vitest run test-fixtures/library-scale.test.tsx",
"bench:import-progress": "node scripts/benchmark-import-progress.mjs",
"test:browser": "node scripts/audit-reader.mjs",
"test:mobile-library": "node scripts/audit-mobile-library.mjs",
"test:library-article": "node scripts/audit-library-article.mjs",
"test:html-svg": "node scripts/audit-html-svg.mjs",
"test:feedback": "node scripts/feedback-browser-test.mjs",
Expand Down
172 changes: 172 additions & 0 deletions apps/reader/scripts/audit-mobile-library.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import { createHash } from "node:crypto";
import { createRequire } from "node:module";
import { resolve } from "node:path";

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

const root = resolve(import.meta.dirname, "..");
const axePath = createRequire(import.meta.url).resolve("axe-core/axe.min.js");
const server = await createServer({
root,
server: { host: "127.0.0.1", port: 0, strictPort: true },
});
const article = `<!doctype html><html lang="en"><head><title>Attention and memory</title></head><body><main><h1>Attention and memory</h1><h2>Methods</h2>${"<p>The authors compared two reading methods.</p>".repeat(1200)}</main></body></html>`;
const collection = [
{
collectionId: "audit",
id: "attention",
path: "sources/attention.md",
title: "Attention and memory",
creators: ["Ada"],
tags: ["research"],
documents: [
{
fileId: "article",
file: "[[article.html]]",
revision: `sha256:${createHash("sha256").update(article).digest("hex")}`,
mediaType: "text/html",
role: "primary",
},
],
frontmatter: {},
body: "",
recordRevision: "rev-1",
},
{
collectionId: "audit",
id: "structural",
path: "sources/structural.md",
title: "Structural learning",
creators: ["Inez"],
tags: ["learning"],
documents: [],
frontmatter: {},
body: "",
recordRevision: "rev-2",
},
];

let browser;
try {
await server.listen();
const origin = `http://127.0.0.1:${server.httpServer.address().port}`;
browser = await chromium.launch();
for (const colorScheme of ["light", "dark"]) {
const context = await browser.newContext({
viewport: { width: 360, height: 740 },
isMobile: true,
hasTouch: true,
colorScheme,
reducedMotion: "reduce",
});
const page = await context.newPage();
await page.route("**/*", (route) =>
new URL(route.request().url()).origin === origin ? route.continue() : route.abort(),
);
await page.route(origin + "/__reader-audit/**", (route) => {
const path = new URL(route.request().url()).pathname.slice("/__reader-audit/".length);
if (path === "library") return route.fulfill({ json: collection });
if (path === "document/article")
return route.fulfill({ body: article, contentType: "text/html" });
if (path.startsWith("source/")) {
const source = collection.find(({ id }) => id === path.slice("source/".length));
if (source) return route.fulfill({ json: source });
}
if (path === "search" || path.startsWith("annotations/")) return route.fulfill({ json: [] });
return route.fulfill({ status: 404 });
});
const fixtureUrl = origin + "/test-fixtures/audit-reader.html?unrelated=keep";
await page.goto(fixtureUrl);
const grid = page.getByRole("treegrid", { name: "Sources" });
const search = page.getByRole("textbox", { name: "Search this view" });
await expect(grid).toHaveAttribute("aria-rowcount", "3", { timeout: 60000 });
await assertAxe(page, `${colorScheme} library`);
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 });
await tag.fill("research");
await expect(grid).toHaveAttribute("aria-rowcount", "2");
const bounds = await options.boundingBox();
expect(bounds?.x).toBeGreaterThanOrEqual(0);
expect(bounds.x + bounds.width).toBeLessThanOrEqual(360);
await assertAxe(page, `${colorScheme} open filters`);
await page.keyboard.press("Escape");
await expect(filter).toBeFocused();
await expect.poll(() => new URL(page.url()).hash).toContain("reader-filter=");
expect(new URL(page.url()).searchParams.get("unrelated")).toBe("keep");
const filteredUrl = page.url();
await page.reload();
await expect(search).toHaveValue("attention");
await filter.tap();
await expect(tag).toHaveValue("research");
await page.keyboard.press("Escape");
await page.keyboard.press("/");
await search.press("Escape");
await expect(search).toHaveValue("");
await expect(grid).toHaveAttribute("aria-rowcount", "2");
await search.press("ArrowDown");
const row = grid.getByRole("row", { name: /^Attention and memory/u });
await expect(row).toBeFocused();
await page.evaluate((hash) => {
globalThis.location.hash = hash;
}, new URL(filteredUrl).hash);
await expect(search).toHaveValue("attention");
await page.evaluate(() => {
globalThis.location.hash = "";
});
await expect(grid).toHaveAttribute("aria-rowcount", "3");
await page.goBack();
await expect(search).toHaveValue("attention");
await row.getByRole("link").tap();
const frame = page.locator("iframe.html-viewer:visible");
await expect(frame).toBeVisible();
await expect(
frame.contentFrame().getByRole("heading", { name: "Attention and memory" }),
).toBeVisible();
const document = frame.contentFrame().locator("html");
await expect(document).toHaveAttribute("data-reader-scheme", colorScheme);
await frame.contentFrame().locator("h1").tap();
await page.keyboard.press("PageDown");
await expect.poll(() => document.evaluate((root) => root.scrollTop)).toBeGreaterThan(0);
const sourceViews = page.getByRole("navigation", { name: "Source views" });
await expect(sourceViews).toBeVisible();
for (const button of await sourceViews.getByRole("button").all()) {
const bounds = await button.boundingBox();
expect(bounds?.height).toBeGreaterThanOrEqual(44);
expect(bounds?.width).toBeGreaterThanOrEqual(44);
}
expect(
await page.evaluate(() => ({
viewport: globalThis.innerWidth,
document: globalThis.document.documentElement.scrollWidth,
dark: globalThis.matchMedia("(prefers-color-scheme: dark)").matches,
})),
).toEqual({ viewport: 360, document: 360, dark: colorScheme === "dark" });
await assertAxe(page, `${colorScheme} article`);
await context.close();
}
console.log(
"360px touch Chromium: filters, URL restoration, keyboard and article controls passed in light and dark",
);
} finally {
await browser?.close();
await server.close();
}

async function assertAxe(page, label) {
await page.addScriptTag({ path: axePath });
const violations = await page.evaluate(async () => {
const results = await globalThis.axe.run(globalThis.document, { resultTypes: ["violations"] });
return results.violations.map(({ id, nodes }) => ({
id,
targets: nodes.map(({ target, failureSummary }) => ({ target, failureSummary })),
}));
});
expect(violations, label).toEqual([]);
}
77 changes: 77 additions & 0 deletions apps/reader/scripts/benchmark-import-progress.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { resolve } from "node:path";

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

import { auditEpub, auditPdf } from "./reader-audit-documents.mjs";

const root = resolve(import.meta.dirname, "..");
const server = await createServer({
root,
server: { host: "127.0.0.1", port: 0, strictPort: true },
});
let browser;
try {
await server.listen();
const origin = `http://127.0.0.1:${server.httpServer.address().port}`;
browser = await chromium.launch();
const page = await browser.newPage({ reducedMotion: "reduce" });
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.route(`${origin}/__performance`, async (route) =>
route.fulfill({
contentType: "text/html",
body: await server.transformIndexHtml(
"/__performance",
"<!doctype html><html><head><title>Reader performance fixture</title></head><body></body></html>",
),
}),
);
await page.goto(`${origin}/__performance`);
const chapter = Array.from(
{ length: 1200 },
(_, i) =>
`<p id="p${i}"${i === 0 ? ' onclick="return false"' : ""}>${"Research notes and patient attention. ".repeat(12)}</p>`,
).join("");
const importFiles = new Map([
["article.html", Buffer.from(`<!doctype html><html><body>${chapter}</body></html>`)],
[
"book.epub",
await auditEpub(
`${chapter}<img alt="" src="data:image/png;base64,${"AAAA".repeat(150000)}" />`,
),
],
["papers.pdf", auditPdf(1000, 40)],
]);
const files = [];
for (const [name, body] of importFiles) {
const url = `${origin}/__performance/${name}`;
await page.route(url, (route) => route.fulfill({ body }));
files.push({ name, url });
}
const moduleUrl = `/@fs${root}/test-fixtures/performance-fixture.tsx`;
const imports = await page.evaluate(
async ({ moduleUrl, files }) => {
const { runImportFixture } = await import(moduleUrl);
return runImportFixture(files);
},
{ moduleUrl, files },
);
await page.context().setOffline(true);
const progress = await page.evaluate(async (moduleUrl) => {
const { runProgressFixture } = await import(moduleUrl);
if (globalThis.navigator.onLine) throw new Error("Progress fixture must run offline");
return runProgressFixture();
}, moduleUrl);
console.log(
"Chromium input bytes",
Object.fromEntries([...importFiles].map(([name, file]) => [name, file.length])),
);
console.log("Chromium import", imports);
console.log("Chromium offline progress", progress);
expect(errors).toEqual([]);
console.log("Chromium", browser.version());
} finally {
await browser?.close();
await server.close();
}
10 changes: 5 additions & 5 deletions apps/reader/scripts/reader-audit-documents.mjs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { ZipWriter, Uint8ArrayWriter, TextReader } from "@zip.js/zip.js";

export function auditPdf() {
export function auditPdf(pageCount = 8, lines = 1) {
const objects = [
"<< /Type /Catalog /Pages 2 0 R >>",
"",
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
];
const pages = [];
for (let page = 1; page <= 8; page += 1) {
for (let page = 1; page <= pageCount; page += 1) {
const id = objects.length + 1;
pages.push(`${id} 0 R`);
const text = `BT /F1 18 Tf 60 700 Td ([test] PDF reading fixture - Page ${page}) Tj 0 -35 Td (Patient attention and durable research notes.) Tj ET`;
const text = `BT /F1 18 Tf 60 700 Td ([test] PDF reading fixture - Page ${page}) Tj 0 -35 Td (Patient attention and durable research notes.) Tj${" 0 -15 Td (Patient attention and durable research notes.) Tj".repeat(lines - 1)} ET`;
objects.push(
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents ${id + 1} 0 R >>`,
);
Expand All @@ -31,7 +31,7 @@ export function auditPdf() {
return Buffer.from(pdf);
}

export async function auditEpub() {
export async function auditEpub(chapter) {
const writer = new ZipWriter(new Uint8ArrayWriter(), { useWebWorkers: false, level: 0 });
const entries = {
mimetype: "application/epub+zip",
Expand All @@ -41,7 +41,7 @@ export async function auditEpub() {
'<?xml version="1.0"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="id">test-reader-epub</dc:identifier><dc:title>[test] EPUB reading fixture</dc:title><dc:language>en</dc:language><meta property="dcterms:modified">2026-09-01T00:00:00Z</meta></metadata><manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>',
"OEBPS/nav.xhtml":
'<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><head><title>Contents</title></head><body><nav epub:type="toc"><ol><li><a href="chapter.xhtml">Reading</a></li></ol></nav></body></html>',
"OEBPS/chapter.xhtml": `<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Reading</title></head><body><h1>[test] EPUB reading fixture</h1>${Array.from({ length: 30 }, (_, index) => `<p>Patient attention and durable research notes. This is disposable test paragraph ${index + 1}.</p>`).join("")}</body></html>`,
"OEBPS/chapter.xhtml": `<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Reading</title></head><body><h1>[test] EPUB reading fixture</h1>${chapter ?? Array.from({ length: 30 }, (_, index) => `<p>Patient attention and durable research notes. This is disposable test paragraph ${index + 1}.</p>`).join("")}</body></html>`,
};
for (const [path, content] of Object.entries(entries)) {
await writer.add(path, new TextReader(content));
Expand Down
13 changes: 10 additions & 3 deletions apps/reader/src/LibraryWorkspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import { Menu } from "./Menu.js";
import { OverlayPresence } from "./OverlayPresence.js";
import { ReaderNotice } from "./ReaderNotice.js";
import { useInspectedLibraryRow } from "./use-inspected-library-row.js";
import { useLibraryFilter } from "./use-library-filter.js";
import { layoutOf, useLibraryLayoutDraft } from "./use-library-layout-draft.js";
import { useLibraryWrites } from "./use-library-writes.js";
import { useRovingControls } from "./use-roving-controls.js";
Expand All @@ -72,6 +73,7 @@ export function LibraryWorkspace({
gateway,
controller,
focused,
syncFilterUrl = false,
onOpenView,
onOpenSource,
onOpenBeside,
Expand Down Expand Up @@ -101,6 +103,7 @@ export function LibraryWorkspace({
readonly gateway: ReaderWorkspaceGateway;
readonly controller: MdbaseLibraryViewsController;
readonly focused: boolean;
readonly syncFilterUrl?: boolean;
readonly onOpenView: (view: MdbaseLibraryView) => void;
readonly onOpenSource: (sourceId: SourceId) => void;
readonly onOpenBeside: (sourceId: SourceId) => void;
Expand All @@ -112,7 +115,7 @@ export function LibraryWorkspace({
const trailingControls = useRovingControls();
const collectionKey = allSources[0]?.collectionId ?? "library";
const [layout, setLayout] = useLibraryLayoutDraft(collectionKey, view);
const [filter, setFilter] = useState(view.configuration.filter);
const [filter, setFilter] = useLibraryFilter(view.configuration.filter, syncFilterUrl);
const configuration = useMemo<LibraryViewConfiguration>(
() => ({ ...layout, filter }),
[layout, filter],
Expand Down Expand Up @@ -431,12 +434,16 @@ export function LibraryWorkspace({
) : null}
<Menu
className="library-workspace-more"
label={t`Filter`}
label={filterCount ? `${t`Filter`} · ${String(filterCount)}` : t`Filter`}
title={t`Filter`}
trigger={
<>
<FilterIcon />
{filterCount ? <span className="menu-badge">{filterCount}</span> : null}
{filterCount ? (
<span className="menu-badge" aria-hidden>
{filterCount}
</span>
) : null}
</>
}
>
Expand Down
8 changes: 7 additions & 1 deletion apps/reader/src/ReaderWorkspaceView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { inspectorSourceForTab } from "./inspector-source.js";
import { InspectorPane, preloadInspectorTools } from "./InspectorPane.js";
import { LibraryNavigator } from "./LibraryNavigator.js";
import { LibraryWorkspace } from "./LibraryWorkspace.js";
import { defaultLibraryView } from "./mdbase-library-views.js";
import { mobileSourceBar } from "./mobile-source-bar.js";
import { OverlayPresence } from "./OverlayPresence.js";
import { followedPane, notesView } from "./panel-workspace-state.js";
Expand Down Expand Up @@ -147,6 +148,9 @@ export function ReaderWorkspaceView({
const shellRef = useRef<HTMLDivElement>(null);
useShellChrome(shellRef, model, mobile);
const annotationCounts = useLibraryAnnotationCounts(model);
const urlLibraryTab = sourceWorkspace.layout.panes
.flatMap(({ tabs }) => tabs)
.find((tab) => tab.kind === "library" && tab.libraryViewId === defaultLibraryView.key);
const notices = useShellNotices(
model.deploymentUpdateAvailable,
model.gateway.createFollowThrough,
Expand Down Expand Up @@ -322,9 +326,10 @@ export function ReaderWorkspaceView({
}}
renderLibrary={(workspaceTab, focused) => {
const libraryView = model.libraryViews.view(workspaceTab.libraryViewId);
const syncFilterUrl = workspaceTab.id === urlLibraryTab?.id;
return (
<LibraryWorkspace
key={libraryView.key}
key={`${libraryView.key}:${String(syncFilterUrl)}`}
view={libraryView}
availableViews={model.libraryViews.views}
allSources={library.sources}
Expand All @@ -333,6 +338,7 @@ export function ReaderWorkspaceView({
onOpenSourceView={(id, view) => sourceWorkspace.openView(id, view)}
controller={model.libraryViews}
focused={focused}
syncFilterUrl={syncFilterUrl}
// A tab's own view switcher changes that tab, even one pinned to its view.
onOpenView={(next) => dock.showLibraryView(workspaceTab.id, next.key, next.name)}
onOpenSource={(id) => sourceWorkspace.open(id)}
Expand Down
Loading