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
68 changes: 68 additions & 0 deletions benchmarks/browser-fixture.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import {createTestMdbase} from "@mdbase-dev/sdk/testing";
import {JournalDrafts} from "../src/drafts.ts";
import {JOURNAL_CONTRACT} from "../src/journal-data.ts";
import {mountJournal} from "../src/view.ts";

const el = id => document.getElementById(id);
const pastDate = "2010-01-01";
const largeBody = "A line of journal writing.\n".repeat(2048);
const recordId = index => "018e0000-0000-7000-8000-" + (index + 1).toString(16).padStart(12, "0");
const pastId = recordId(0);
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
async function until(check) {
const deadline = performance.now() + 10000;
while (!check()) {
if (performance.now() > deadline) throw Error("Timed out waiting for " + check);
await tick();
}
}

export async function start(size, recovery = false) {
const type = "journal-bench-entry";
const records = Array.from({length: size}, (_, index) => {
const created = new Date(Date.UTC(2010, 0, index + 1, 12)).toISOString();
return {id: recordId(index), path: 'journal/' + created.slice(0, 10) + '.md',
types: [type], frontmatter: {created}};
});
const original = records[0];
const mdbase = await createTestMdbase({collections: [{name: "Writing", contracts: [
{id: JOURNAL_CONTRACT.id, version: JOURNAL_CONTRACT.version, type, fields: {created: "created"}, contractDigest: JOURNAL_CONTRACT.digest}
]}]});
const client = mdbase.fixture.client();
await client.settle(client.create({id: pastId, path: original.path, type, frontmatter: original.frontmatter, body: largeBody}));
let historyReads = 0;
client.pages = async function* () {
for (let i = 0; i < size; i += 500) yield {complete: true, records: records.slice(i, i + 500)};
historyReads++;
};
const drafts = new JournalDrafts(localStorage, undefined, op => navigator.locks.request("journal.native.drafts", op));
if (recovery) await drafts.mutate(() => drafts.put({...drafts.blank(client.collection), body: "Keep my local changes",
path: original.path, recordId: pastId, savedBody: largeBody, reviewRequired: true}));
const start = performance.now();
const view = await drafts.mutate(() => mountJournal(document, drafts, mdbase));
await until(() => historyReads > 0);
return {startup: performance.now() - start, async sample() {
const t = performance.now();
el("browse-button").click();
await until(() => el("entry-range").textContent === '1–50 of ' + size && !el("entries-status").textContent);
const picker = performance.now() - t;
const p = performance.now();
el("older-entries").click();
if (el("entry-range").textContent !== '51–100 of ' + size) throw Error("Wrong page");
const paginate = performance.now() - p;
const d = performance.now();
el("entry-date").value = pastDate;
el("entry-date").dispatchEvent(new Event("input"));
if (el("entry-list").children.length !== 1) throw Error("Wrong date");
const filter = performance.now() - d;
el("entry-list").firstElementChild.click();
await until(() => el("page").value === largeBody && el("status").textContent === "Saved");
const input = el("page");
const k = performance.now();
input.setRangeText("!", input.value.length, input.value.length, "end");
input.dispatchEvent(new Event("input"));
const typing = performance.now() - k;
await until(() => view.currentDraft().savedBody === largeBody + "!");
return {picker, paginate, filter, typing, autosave: performance.now() - k};
}};
}
123 changes: 123 additions & 0 deletions benchmarks/browser-journal.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import assert from "node:assert/strict";
import {readFile} from "node:fs/promises";
import {createRequire} from "node:module";
import {fileURLToPath} from "node:url";
import {resolve} from "node:path";
import {build} from "esbuild";

const require = createRequire(new URL("../tools/smoke/package.json", import.meta.url));
const {chromium} = require("playwright");
const root = fileURLToPath(new URL("../", import.meta.url));
const fixture = await readFile(new URL("./browser-fixture.mjs", import.meta.url), "utf8");
async function assetsFor(directory) {
const bundle = await build({stdin: {contents: fixture, resolveDir: resolve(directory, "benchmarks")},
bundle: true, write: false, format: "iife", globalName: "JournalFixture", define: {"process.env.NODE_ENV": '"production"'}});
const packages = createRequire(resolve(directory, "package.json"));
const styles = await build({entryPoints: [packages.resolve("@mdbase-dev/ui/collections.css")], bundle: true, write: false});
return new Map([
["/", ["text/html", await readFile(resolve(directory, "public/index.html"), "utf8")]],
["/journal.js", ["text/javascript", bundle.outputFiles[0].text + "\nglobalThis.JournalFixture = JournalFixture;"]],
["/mdbase-shell-register.js", ["text/javascript", ""]],
["/journal.css", ["text/css", await readFile(resolve(directory, "public/journal.css"), "utf8")]],
["/mdbase-collections.css", ["text/css", styles.outputFiles[0].text]]
]);
}
const headAssets = await assetsFor(root);
const browser = await chromium.launch();
async function open(options = {}, assets = headAssets) {
const page = await browser.newPage({timezoneId: "UTC", reducedMotion: "reduce", ...options});
await page.route("**/*", route => {
const url = new URL(route.request().url());
const asset = url.origin === "https://journal.test" && assets.get(url.pathname);
return asset ? route.fulfill({contentType: asset[0], body: asset[1]}) : route.abort();
});
await page.goto("https://journal.test/");
return page;
}
async function benchmark(base) {
const revisions = [{name: "head", assets: headAssets}];
if (base) revisions.unshift({name: "base", assets: await assetsFor(base)});
for (const size of [5000, 10000]) {
const samples = new Map(revisions.map(({name}) => [name, []]));
for (let i = 0; i <= 9; i++) {
for (const revision of i % 2 ? revisions.toReversed() : revisions) {
const page = await open({}, revision.assets);
try {
const row = await page.evaluate(async size => {
const fixture = await JournalFixture.start(size);
return {startup: fixture.startup, ...await fixture.sample()};
}, size);
if (i) samples.get(revision.name).push(row);
} finally {await page.close();}
}
}
for (const [name, rows] of samples) for (const key of Object.keys(rows[0])) {
const values = rows.map(row => row[key]).sort((a, b) => a - b);
console.log(name, size, key, "median", values[4].toFixed(2), "p95", values[8].toFixed(2), "ms");
}
}
}
async function audit() {
let failures = 0;
for (const width of [360, 1280]) for (const colorScheme of ["light", "dark"]) {
const options = {viewport: {width, height: 800}, colorScheme, hasTouch: width === 360};
const page = await open(options);
async function scan(name) {
const result = await page.evaluate(async () => {
const scopes = [document.documentElement, ...document.querySelectorAll("dialog[open], dialog[open] .sheet")];
const overflow = scopes.filter(el => el.scrollWidth > el.clientWidth + 1).map(el => el.id || el.tagName);
const {violations} = await axe.run(document, {runOnly: ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"]});
return {overflow, violations: violations.map(v => [v.id, v.nodes.map(n => [n.target, n.failureSummary])])};
});
console.log(width, colorScheme, name, JSON.stringify(result));
if (result.violations.length || result.overflow.length) failures++;
}
try {
await page.evaluate(() => JournalFixture.start(5000).then(() => {}));
await page.addScriptTag({path: require.resolve("axe-core/axe.min.js")});
await scan("Today");
await page.locator("#browse-button").click();
await page.locator("#entry-range").getByText("1–50 of 5000").waitFor();
await scan("Picker");
await page.keyboard.press("Escape");
// Let the native dialog close event and any app focus handler finish.
await page.waitForFunction(() => !document.querySelector("#entries").open);
await page.evaluate(() => new Promise(requestAnimationFrame));
if (await page.evaluate(() => document.activeElement.id) !== "browse-button") {
console.error("Picker dismissal lost opener focus", width, colorScheme);
failures++;
}
await page.locator("#browse-button").click();
await page.locator("#entry-date").fill("2010-01-01");
await scan("Date search");
await page.locator("#entry-list button").click();
await page.waitForFunction(() => document.querySelector("#page").value.length > 50000 && document.activeElement.id === "page");
await scan("Past entry");
await page.locator("#page").press("Control+End");
await page.keyboard.insertText("!");
if (width === 360) {
const visible = await page.evaluate(() => ["header", ".context", "#menu-button"].every(selector =>
Number(getComputedStyle(document.querySelector(selector)).opacity) === 1));
if (!visible) {console.error("Touch navigation faded while typing", colorScheme); failures++;}
await scan("Touch typing");
}
await page.mouse.move(10, 10);
await page.locator("#menu-button").click();
await scan("Settings");
await page.keyboard.press("Escape");
assert.equal(await page.evaluate(() => document.activeElement.id), "menu-button");
await page.reload();
await page.evaluate(() => {localStorage.clear(); return JournalFixture.start(5000, true).then(() => {});});
await page.locator("#draft-conflict").waitFor();
await page.addScriptTag({path: require.resolve("axe-core/axe.min.js")});
await scan("Recovery");
} finally {await page.close();}
}
assert.equal(failures, 0, "axe, overflow, focus or touch visibility checks failed");
}
try {
console.log("Chromium", browser.version());
if (process.argv[2] === "axe") await audit();
else if (process.argv[2] === "bench") await benchmark(process.argv[3]);
else throw Error("Choose bench or axe");
} finally {await browser.close();}
4 changes: 2 additions & 2 deletions public/journal.css

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/draft-opens.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {JournalDrafts} from "./drafts.js";
import {hasDraftContent, JournalDrafts} from "./drafts.js";
import type {JournalData, JournalEntryType} from "./journal-data.js";
export interface DraftOpenState {readonly state: "opening" | "unresolved"}
/** Independent acquisition of original SDK record leases. This is not autosave:
Expand Down Expand Up @@ -50,7 +50,7 @@ export class DraftOpens {
request(id: string, type?: JournalEntryType, viewed = false, edited = false): void {
if (this.disposed || !this.isCurrent()) return;
const draft = this.drafts.get(id);
if (!draft || draft.deletedElsewhere || draft.reviewRequired || draft.legacyKey || !draft.body.trim() || draft.body === draft.savedBody && (!viewed || !draft.recordId) ||
if (!draft || draft.deletedElsewhere || draft.reviewRequired || draft.legacyKey || !hasDraftContent(draft) || draft.body === draft.savedBody && (!viewed || !draft.recordId) ||
draft.targetCollectionId && draft.targetCollectionId !== this.data.connection.id || this.data.snapshot(id) || this.jobs.has(id)) return;
this.types.set(id, type);
if (!this.owns(id)) {
Expand Down
4 changes: 4 additions & 0 deletions src/drafts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ export interface JournalDraft {
/** Prototype text has no original native capture identity. Import is local only. */
legacyKey?: string;
}
/** Empty text is a real edit once a page has an original save identity. */
export function hasDraftContent(draft: JournalDraft): boolean {
return !!draft.recordId || !!draft.createAttempt || !!draft.body.trim();
}
export type DraftStorage = Pick<Storage, "getItem" | "setItem" | "removeItem" | "key" | "length">;
const prefix = "journal.native.note.";
const object = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
Expand Down
4 changes: 2 additions & 2 deletions src/journal-data.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {revisionOf, uuidv7, type DescribeResult, type MdbaseApplicationConnection, type RecordLease, type RecordSessionSnapshot, type RecordView, type FileRef} from "@mdbase-dev/sdk";
import {JournalDrafts, type JournalDraft} from "./drafts.js";
import {hasDraftContent, JournalDrafts, type JournalDraft} from "./drafts.js";
export const JOURNAL_CONTRACT = Object.freeze({id: "journal.entry", version: "0.1.0", digest: "sha256:7e95bdf03621919fb0e722e5a29b48a68d7a4eaa3a94aea033d96ea2f7ec34cc"});
export interface JournalEntryType {readonly name: string; readonly createdField: string}
export interface JournalEntry {readonly id: string; readonly created: string; readonly createdMs: number; readonly path: string}
Expand Down Expand Up @@ -158,7 +158,7 @@ export class JournalData {
}
private async acquire(id: string, type?: JournalEntryType): Promise<RecordLease> {
let draft = this.drafts.get(id);
if (!draft || !draft.path || (!draft.recordId && !draft.body.trim())) throw new Error("Write something before saving this page.");
if (!draft || !draft.path || !hasDraftContent(draft)) throw new Error("Write something before saving this page.");
this.ensure(draft);
if (!draft.targetCollectionId) draft = await this.drafts.mutate(() => this.drafts.patch(id, {targetCollectionId: this.connection.id}));
if (!draft.recordId) {
Expand Down
Loading