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
1 change: 1 addition & 0 deletions apps/reader/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"manifest:verify": "node scripts/verify-manifest.mjs",
"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",
"test:browser": "node scripts/audit-reader.mjs",
"test:html-svg": "node scripts/audit-html-svg.mjs",
"test:feedback": "node scripts/feedback-browser-test.mjs",
Expand Down
11 changes: 10 additions & 1 deletion apps/reader/scripts/audit-pages-offline.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { createServer } from "node:http";
import { extname, resolve } from "node:path";
import { chromium } from "@playwright/test";

import { unexpectedShellFailures } from "./pages-offline-requests.mjs";

const directory = resolve(import.meta.dirname, "../dist");
const types = {
".html": "text/html",
Expand Down Expand Up @@ -51,7 +53,13 @@ try {
const page = await context.newPage();
const failed = [];
const pageErrors = [];
context.on("requestfailed", (request) => failed.push(new URL(request.url()).pathname));
context.on("requestfailed", (request) =>
failed.push({
url: request.url(),
worker: Boolean(request.serviceWorker()),
error: request.failure()?.errorText,
}),
);
page.on("pageerror", (error) => pageErrors.push(error.message));
await page.goto(origin + "/?preview=1");
await page.waitForFunction(() => navigator.serviceWorker.controller !== null, null, {
Expand All @@ -76,6 +84,7 @@ try {
await page.getByText("The Principles of Psychology", { exact: true }).first().waitFor();
assert.equal(await page.title(), "mdbase reader");
const onlineFailedRequests = [...failed];
assert.deepEqual(unexpectedShellFailures(onlineFailedRequests, origin), []);
await context.setOffline(true);
const offline = await page.reload();
await page.getByText("The Principles of Psychology", { exact: true }).first().waitFor();
Expand Down
13 changes: 13 additions & 0 deletions apps/reader/scripts/pages-offline-requests.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Only the worker's initial HTML filename probes may fail on a clean-URL host.
// A successful canonical retry is verified separately through the installed cache.
export function unexpectedShellFailures(requests, origin) {
return requests.filter(({ url, worker, error }) => {
const request = new URL(url);
if (request.origin !== origin) return false;
return !(
worker &&
error === "net::ERR_FAILED" &&
(request.href === origin + "/index.html" || request.href === origin + "/404.html")
);
});
}
22 changes: 22 additions & 0 deletions apps/reader/scripts/pages-offline-requests.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import assert from "node:assert/strict";
import test from "node:test";
import { unexpectedShellFailures } from "./pages-offline-requests.mjs";

test("only tolerates worker HTML redirect probes during online shell startup", () => {
const origin = "https://reader.example";
const probe = { url: origin + "/index.html", worker: true, error: "net::ERR_FAILED" };
const unexpected = [
{ ...probe, worker: false },
{ ...probe, url: origin + "/" },
{ ...probe, url: origin + "/assets/reader.js" },
{ ...probe, url: origin + "/index.html?q=1" },
{ ...probe, error: "net::ERR_INTERNET_DISCONNECTED" },
];
assert.deepEqual(
unexpectedShellFailures(
[probe, { ...probe, url: origin + "/404.html" }, ...unexpected],
origin,
),
unexpected,
);
});
8 changes: 7 additions & 1 deletion apps/reader/src/AnnotationCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,13 @@ function AnnotationCardView({
showKind={annotation.annotationType !== "highlight"}
showLocation={showLocation}
// Without group headings, a card outside its chapter's pages says so itself.
outsideChapter={showLocation && annotationOutsideChapter(annotation, owners ?? [])}
outsideChapter={
showLocation &&
annotationOutsideChapter(
annotation,
owners?.find(({ id }) => id === annotation.sourceId),
)
}
draft={needsAttention ? draftLabel(conflict) : null}
/>
<AnnotationCardActions
Expand Down
7 changes: 5 additions & 2 deletions apps/reader/src/LibraryWorkspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,9 @@ export function LibraryWorkspace({
const filterCount = activeFilterCount(configuration);
// Prefer the library's copy of each source, so edits such as a status change show at once.
const freshSources = useMemo(() => {
if (allSources === executedSources) {
return allSources;
}
const byId = new Map(allSources.map((source) => [source.id, source]));
return executedSources.map((source) => byId.get(source.id) ?? source);
}, [allSources, executedSources]);
Expand Down Expand Up @@ -200,10 +203,10 @@ export function LibraryWorkspace({
noteSearch.matches.size === 0
? []
: applyLibraryViewConfiguration(
baseSources,
baseSources.filter(({ id }) => noteSearch.matches.has(id)),
{ ...view.configuration, sortField, sortDirection, filter: { ...filter, query: "" } },
allSources,
).filter(({ id }) => noteSearch.matches.has(id)),
),
[
allSources,
baseSources,
Expand Down
21 changes: 21 additions & 0 deletions apps/reader/src/annotation-groups.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,24 @@ it("notes a run of cards outside their chapter's pages once, on its first headin
false,
]);
});

it("looks up owners once per library and retains the first title for a duplicate id", () => {
let reads = 0;
const owners = Array.from({ length: 100 }, (_, index) => ({
...sources[0]!,
get id() {
reads++;
return sourceId(String(index));
},
title: String(index),
}));
const last = sourceId("99");
const headings = annotationGroupHeadings(
Array.from({ length: 100 }, (_, index) => onPage(String(index), index, last)),
undefined,
[...owners, { ...sources[0]!, id: last, title: "Duplicate" }],
true,
);
expect(headings.every((heading) => heading?.source?.summary === owners.at(-1))).toBe(true);
expect(reads).toBeLessThanOrEqual(2 * owners.length);
});
20 changes: 14 additions & 6 deletions apps/reader/src/annotation-groups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,8 @@ export interface AnnotationGroupHeading {
/** A PDF annotation owned by a chapter source but placed outside that chapter's page range. */
export function annotationOutsideChapter(
annotation: Annotation,
sources: readonly SourceSummary[],
owner: SourceSummary | undefined,
): boolean {
const owner = sources.find(({ id }) => id === annotation.sourceId);
const range = owner?.documents.find(
(document) =>
sameDocument(document, annotation.document) &&
Expand Down Expand Up @@ -78,8 +77,18 @@ export function annotationGroupHeadings(
let headed = false;
let outsideRun = false;
let outsideNoted = false;
if (results.length === 0) {
return [];
}
const byId = new Map<SourceId, SourceSummary>();
for (const source of sources) {
if (!byId.has(source.id)) {
byId.set(source.id, source);
}
}
return results.map((annotation) => {
const outside = annotationOutsideChapter(annotation, sources);
const owner = byId.get(annotation.sourceId);
const outside = annotationOutsideChapter(annotation, owner);
if (!outside || !outsideRun) {
outsideNoted = false;
}
Expand All @@ -94,7 +103,7 @@ export function annotationGroupHeadings(
headed = true;
const heading = {
label: group.label,
source: group.other ? groupSource(annotation, sources) : null,
source: group.other ? groupSource(annotation, owner) : null,
};
if (outside && !outsideNoted) {
outsideNoted = true;
Expand Down Expand Up @@ -126,8 +135,7 @@ function annotationGroup(

function groupSource(
annotation: Annotation,
sources: readonly SourceSummary[],
summary: SourceSummary | undefined,
): NonNullable<AnnotationGroupHeading["source"]> {
const summary = sources.find(({ id }) => id === annotation.sourceId);
return summary ? { title: summary.title, summary } : { title: annotation.source };
}
8 changes: 8 additions & 0 deletions apps/reader/src/library-source-parts.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ const section = partSource("Section", "Chapter");
const all = [chapter, book, section];

describe("library source parts", () => {
it("reuses sorted standalone matches and keeps their treegrid metadata", () => {
const other = partSource("Other");
const matches = [other, book];
const result = librarySourceParts(matches, all, new Set([book.id]), false, false);
expect(result.sources).toBe(matches);
expect(result.rows.get(other.id)).toEqual({ depth: 0, expanded: true, expandable: false });
expect(result.rows.get(book.id)).toEqual({ depth: 0, expanded: false, expandable: false });
});
it("nests independently sorted parts, supports collapse, and keeps filtered-out parents' children at root", () => {
const nested = librarySourceParts(all, all, new Set(), false, true);
expect(nested.sources.map(({ id }) => id)).toEqual([book.id, chapter.id, section.id]);
Expand Down
14 changes: 14 additions & 0 deletions apps/reader/src/library-source-parts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,20 @@ export function librarySourceParts(
readonly sources: readonly SourceSummary[];
readonly rows: ReadonlyMap<SourceId, LibraryPartRow>;
} {
// With no part-of edges among the matches, even a filtered list is already in tree order.
if (
!matches.some(
(source) =>
source.partOf !== undefined ||
source.relations?.some(({ relation }) => relation === "part-of"),
)
) {
const rows = new Map<SourceId, LibraryPartRow>();
for (const { id } of matches) {
rows.set(id, { depth: 0, expandable: false, expanded: !collapsed.has(id) });
}
return { sources: matches, rows };
}
const byId = new Map([...library, ...matches].map((source) => [source.id, source]));
const included = new Set(matches.map(({ id }) => id));
const children = new Map<SourceId, SourceSummary[]>();
Expand Down
10 changes: 7 additions & 3 deletions apps/reader/src/mdbase-library-views.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,11 @@ export function applyLibraryViewConfiguration(
configuration: LibraryViewConfiguration,
contextSources: readonly SourceSummary[] = sources,
): readonly SourceSummary[] {
const parentTitles = new Map(contextSources.map(({ id, title }) => [id, title]));
let parentTitles: Map<SourceSummary["id"], string> | undefined;
function parentTitle(id: SourceSummary["id"]): string | undefined {
parentTitles ??= new Map(contextSources.map((source) => [source.id, source.title]));
return parentTitles.get(id);
}
const query = configuration.filter.query.trim().toLocaleLowerCase();
const tag = configuration.filter.tag.trim().toLocaleLowerCase();
const filtered = sources.filter((source) => {
Expand Down Expand Up @@ -234,14 +238,14 @@ export function applyLibraryViewConfiguration(
source.title,
...source.creators,
...source.tags.map(String),
source.partOf ? parentTitles.get(source.partOf) : undefined,
source.partOf ? parentTitle(source.partOf) : undefined,
]
.join(" ")
.toLocaleLowerCase()
.includes(query)
);
});
return [...filtered].sort((left, right) => compareSources(left, right, configuration));
return filtered.sort((left, right) => compareSources(left, right, configuration));
}

/** A source's format; `note` means no file is attached, `file` an unrecognised one. */
Expand Down
24 changes: 24 additions & 0 deletions apps/reader/src/source-library-loader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,30 @@ const first: SourceSummary = {
};

describe("loadSourceLibrary", () => {
it("shows the first row immediately without publishing every one-row page", async () => {
const sources = Array.from({ length: 1000 }, (_, i) => ({
...first,
id: sourceId(String(i)),
}));
const progress = vi.fn<(snapshot: ReaderLibrarySnapshot) => void>();
async function* pages(): AsyncGenerator<Page<SourceSummary>> {
for (const source of sources) {
yield await Promise.resolve({ items: [source] });
}
}
const complete = await loadSourceLibrary({
repository: { listPages: pages } as unknown as SourceRepository,
collectionId: first.collectionId,
collectionName: "Reading",
options: {},
onProgress: progress,
});
expect(progress.mock.calls[0]?.[0].sources).toEqual(sources.slice(0, 1));
expect(progress.mock.calls.reduce((sum, [page]) => sum + page.sources.length, 0)).toBeLessThan(
5000,
);
expect(complete.sources).toEqual(sources);
});
it("bounds cumulative snapshot copies when old authorities keep small pages", async () => {
const sources = Array.from({ length: 10_000 }, (_, i) => ({
...first,
Expand Down
2 changes: 1 addition & 1 deletion apps/reader/src/source-library-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ async function loadStablePages(
total = page.totalCount ?? total;
// Old authorities may still pin tiny pages. Avoid repeatedly copying and
// rerendering the entire growing index; first rows stay immediate.
if (sources.length <= 1000 || sources.length - published >= Math.ceil(published / 4)) {
if (sources.length - published >= Math.max(1, Math.ceil(published / 4))) {
publish(input, sources, false, total);
published = sources.length;
}
Expand Down
86 changes: 86 additions & 0 deletions apps/reader/test-fixtures/library-scale.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { stdout } from "node:process";

import { annotationId, collectionId, dateTime, sourceId } from "@mdbase-reader/core";
import { expect, it } from "vitest";

import { annotationGroupHeadings } from "../src/annotation-groups.js";
import { librarySourceParts } from "../src/library-source-parts.js";
import {
applyLibraryViewConfiguration,
defaultLibraryViewConfiguration as view,
} from "../src/mdbase-library-views.js";
import { loadSourceLibrary } from "../src/source-library-loader.js";

import type { Annotation, Page, SourceRepository, SourceSummary } from "@mdbase-reader/core";

const collection = collectionId("benchmark");
const collapsed = new Set<SourceSummary["id"]>();

/** Local CPU only. Already-decoded pages, no network, SDK I/O, React commit or paint. */
for (const count of [1000, 10_000]) {
it(`profiles a library of ${String(count)} sources`, async () => {
const sources: SourceSummary[] = Array.from({ length: count }, (_, index) => ({
collectionId: collection,
id: sourceId(`source-${String(index)}`),
path: `sources/${String(index)}.md`,
title: `Paper ${String((index * 7919) % count)}`,
creators: ["Research group"],
tags: [index % 10 === 0 ? "history" : "science"],
documents: [],
}));
const annotations: Annotation[] = sources.map((owner, index) => ({
id: annotationId(`highlight-${String(index)}`),
collectionId: collection,
sourceId: owner.id,
source: `[[${owner.path}]]`,
annotationType: "highlight",
body: "> Selected passage",
tags: [],
createdAt: dateTime("2026-01-01T00:00:00Z"),
target: { position: { kind: "pdf", pageIndex: index % 80 } },
}));
const repository = {
async *listPages(): AsyncGenerator<Page<SourceSummary>> {
for (let offset = 0; offset < count; offset += 128) {
yield await Promise.resolve({
items: sources.slice(offset, offset + 128),
totalCount: count,
});
}
},
} as unknown as SourceRepository;
function rows(items: readonly SourceSummary[], query = ""): number {
const matches = applyLibraryViewConfiguration(items, {
...view,
filter: { ...view.filter, query },
});
return librarySourceParts(matches, items, collapsed, Boolean(query), true).sources.length;
}
await median("progressive library and rows", async () => {
const snapshot = await loadSourceLibrary({
repository,
collectionId: collection,
collectionName: "Benchmark",
options: {},
onProgress: ({ sources: page }) => rows(page),
});
expect(rows(snapshot.sources)).toBe(count);
});
await median("filtered rows", () => expect(rows(sources, "history")).toBe(count / 10));
await median("collection highlight headings", () => {
const headings = annotationGroupHeadings(annotations, undefined, sources, true);
expect(headings.at(-1)?.source?.summary).toBe(sources.at(-1));
});
}, 60_000);
}

async function median(label: string, run: () => Promise<void> | void): Promise<void> {
await run();
const samples: number[] = [];
for (let sample = 0; sample < 7; sample++) {
const start = performance.now();
await run();
samples.push(performance.now() - start);
}
stdout.write(`${label}: ${String(samples.sort((a, b) => a - b)[3]?.toFixed(2))} ms\n`);
}
Loading