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
6 changes: 6 additions & 0 deletions apps/reader/scripts/audit-library-article.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,12 @@ try {
console.log("Library", size, width, "mounted rows", await rows.count());
}
}
await page.keyboard.press("Control+k");
const palette = page.getByRole("dialog", { name: "Reader commands" });
await palette.getByRole("combobox").fill("Study 09999");
await expect(palette.getByRole("option", { name: /Study 09999/u })).toBeVisible();
await page.keyboard.press("Escape");
await expect(palette).toBeHidden();
const scrollMedian = await grid.evaluate(async (el) => {
const frame = el.closest(".library-table-frame");
const times = [];
Expand Down
145 changes: 92 additions & 53 deletions apps/reader/scripts/benchmark-library-article.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
// Run locally with a warmed Vite server. Each row has one warm-up and nine samples.
// Optional second server runs the same fixture on the baseline revision.
import { chromium, expect } from "@playwright/test";

const origin = process.env.READER_AUDIT_ORIGIN ?? "http://127.0.0.1:5311";
if (!/^http:\/\/(127\.0\.0\.1|localhost):\d+$/u.test(origin)) {
throw new Error("Performance measurements require a loopback origin.");
const origins = [process.env.READER_BASELINE_ORIGIN, origin].filter(Boolean);
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 articles = Array.from({ length: 10_000 }, (_, index) => ({
collectionId: "benchmark",
Expand All @@ -20,7 +23,6 @@ const articles = Array.from({ length: 10_000 }, (_, index) => ({
recordRevision: "rev-1",
}));
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });

function summary(times) {
const sorted = times.toSorted((a, b) => a - b);
Expand All @@ -32,57 +34,94 @@ function summary(times) {
}

try {
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
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;
return route.fulfill({ json: path.endsWith("/library") ? articles : [] });
});
await page.addInitScript(() => {
globalThis.readerGridReady = new Promise((resolve) => {
const observer = new globalThis.MutationObserver(() => {
if (globalThis.document.querySelector('.library-table[aria-rowcount="10001"]')) {
observer.disconnect();
resolve(performance.now());
}
const reports = {};
for (const count of [100, 10_000]) {
const sources = articles.slice(0, count);
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 : [] });
});
observer.observe(globalThis.document, { attributes: true, childList: true, subtree: true });
});
});
const startup = [];
const grid = page.locator(".library-table:visible");
for (let i = 0; i < 10; i++) {
await page.goto(`${origin}/test-fixtures/audit-reader.html`, { waitUntil: "domcontentloaded" });
const elapsed = await page.evaluate(() => globalThis.readerGridReady);
if (i) startup.push(elapsed);
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: {} });
}
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 (const { url, page, times } of lanes) {
reports[`${count} @ ${url}`] = Object.fromEntries(
Object.entries(times).map(([k, v]) => [k, summary(v)]),
);
await page.context().close();
}
}
await expect(grid).toHaveAttribute("aria-rowcount", "10001");
expect(await grid.locator("[data-row-index]").count()).toBeLessThan(60);
const runs = await page.evaluate(
async ({ sources, moduleUrl }) => {
const { measureLibraryAndArticle } = await import(moduleUrl);
return measureLibraryAndArticle(sources);
},
{ sources: articles, moduleUrl: "/test-fixtures/library-article-benchmark.tsx" },
);
expect(errors).toEqual([]);
console.log(
JSON.stringify(
{
chromium: browser.version(),
milliseconds: Object.fromEntries(
[["startup to virtualized 10k grid", startup], ...Object.entries(runs)].map(
([label, times]) => [label, summary(times)],
),
),
},
null,
2,
),
);
console.log(JSON.stringify({ chromium: browser.version(), milliseconds: reports }, null, 2));
} finally {
await browser.close();
}
3 changes: 3 additions & 0 deletions apps/reader/src/ReaderWorkspaceView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,9 @@ function useCommandsForView(
},
): ReturnType<typeof readerCommands> {
const createSourceParts = useSourcePartCreation();
if (!model.commandsOpen) {
return [];
}
return readerCommands({
libraryViews: model.libraryViews.views,
sources: model.library.sources,
Expand Down
3 changes: 3 additions & 0 deletions apps/reader/src/library-columns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,9 @@ export function propertyValue(
if (selected && key in selected) {
return selected[key];
}
if (!key.includes(".")) {
return source.properties?.[key];
}
let current: unknown = source.properties;
for (const part of key.split(".")) {
if (typeof current !== "object" || current === null || Array.isArray(current)) {
Expand Down
18 changes: 18 additions & 0 deletions apps/reader/src/mdbase-library-views.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,24 @@ describe("mdbase library views", () => {
]);
});

it("keeps title ties stable in both directions when filtering mixed-case tags", () => {
const rows = [
source("b", "Same", "reading", ["Study"]),
source("c", "Last", "reading", ["study"]),
source("a", "Same", "reading", ["STUDY"]),
];
const base = defaultLibraryViewConfiguration;
const filter = { ...base.filter, query: "author", tag: "study" };
for (const sortDirection of ["asc", "desc"] as const) {
const configuration = { ...base, sortDirection };
const filtered = applyLibraryViewConfiguration(rows, { ...configuration, filter });
expect(filtered.map((row) => row.id)).toEqual(
sortDirection === "asc" ? ["c", "b", "a"] : ["b", "a", "c"],
);
}
expect(rows.map((row) => row.id)).toEqual(["b", "c", "a"]);
});

it("round-trips Reader presentation options", () => {
const configuration = libraryViewConfiguration({
type: "table",
Expand Down
72 changes: 46 additions & 26 deletions apps/reader/src/mdbase-library-views.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,31 +215,53 @@ export function applyLibraryViewConfiguration(
}
const query = configuration.filter.query.trim().toLocaleLowerCase();
const tag = configuration.filter.tag.trim().toLocaleLowerCase();
const filtered = sources.filter((source) => {
if (
configuration.filter.status !== "all" &&
(source.readingStatus ?? "inbox") !== configuration.filter.status
) {
return false;
}
if (
configuration.filter.format !== "all" &&
sourceFormat(source) !== configuration.filter.format
) {
return false;
}
if (tag && !source.tags.some((candidate) => candidate.toLocaleLowerCase() === tag)) {
return false;
}
if (
!configuration.filter.conditions.every((condition) => matchesCondition(source, condition))
) {
return false;
}
return !query || metadataSearchText(source, parentTitle).includes(query);
});
const { sortField, sortDirection } = configuration;
const { sortField, sortDirection, filter } = configuration;
const direction = sortDirection === "asc" ? 1 : -1;
// Empty filters are the common library-open path. Sorting owns its input.
const unfiltered =
!query &&
!tag &&
filter.status === "all" &&
filter.format === "all" &&
filter.conditions.length === 0;
const matchingTags = new Map<string, boolean>();
function matchesTag(candidate: string): boolean {
const known = matchingTags.get(candidate);
if (known !== undefined) {
return known;
}
const matches = candidate.toLocaleLowerCase() === tag;
matchingTags.set(candidate, matches);
return matches;
}
const filtered = unfiltered
? [...sources]
: sources.filter((source) => {
if (
configuration.filter.status !== "all" &&
(source.readingStatus ?? "inbox") !== configuration.filter.status
) {
return false;
}
if (
configuration.filter.format !== "all" &&
sourceFormat(source) !== configuration.filter.format
) {
return false;
}
if (tag && !source.tags.some(matchesTag)) {
return false;
}
if (
!configuration.filter.conditions.every((condition) => matchesCondition(source, condition))
) {
return false;
}
return !query || metadataSearchText(source, parentTitle).includes(query);
});
if (sortField === "title") {
return filtered.sort((a, b) => direction * a.title.localeCompare(b.title));
}
const key = propertyKey(sortField);
if (key !== null) {
// Dotted paths and formatted property values are independent of the comparison pair.
Expand Down Expand Up @@ -366,8 +388,6 @@ function columnSelection(column: LibraryColumn): string {

function sortValue(source: SourceSummary, field: LibrarySortField): string | number {
switch (field) {
case "title":
return source.title;
case "creator":
return source.creators[0] ?? "";
case "published":
Expand Down
Loading