diff --git a/public/index.html b/public/index.html index 2b6fd01..81077a6 100644 --- a/public/index.html +++ b/public/index.html @@ -59,6 +59,7 @@

Resolve setup conflict

+
diff --git a/public/journal.css b/public/journal.css index fa1ac17..c8b217b 100644 --- a/public/journal.css +++ b/public/journal.css @@ -29,7 +29,6 @@ textarea { display:block; width:100%; max-width:680px; min-height:100vh; min-hei .dot.saved { background:var(--accent); } .dot.pending { background:var(--warn); } .status,.hint { background:var(--bg); } .status.routine span { position:absolute; width:1px; height:1px; overflow:hidden; clip-path:inset(50%); } -.status.notice { opacity:.55; } .status.notice:hover,.status.notice:focus-visible { opacity:1; } body.quiet .status.notice:not(:focus-visible) { opacity:0; pointer-events:none; } .hint { opacity:0; transition:opacity .6s ease; white-space:nowrap; border-radius:6px; } body.typing:not(.quiet) .hint,body.undo .hint,body.retry .hint,.hint:focus-within { opacity:1; } @@ -66,6 +65,7 @@ body.typing:not(.quiet) .hint,body.undo .hint,body.retry .hint,.hint:focus-withi .setup-recovery-actions button.primary { border-color:var(--accent); background:var(--accent); color:var(--panel); font-weight:500; } .setup-recovery-actions button.primary:hover { color:var(--panel); opacity:.92; } .setup-recovery-notice { margin:0; padding-left:10px; border-left:2px solid var(--accent); overflow-wrap:anywhere; color:var(--ink); } +#collection-panel[data-journal-recovery] .mdbase-collections-setup { display:none; } #returning-user-notice { display:grid; grid-template-columns:minmax(0,1fr); gap:.5rem; width:min(680px,calc(100% - 32px)); margin:5rem auto 0; padding:1rem 0; border-bottom:1px solid var(--faint); color:var(--muted); line-height:1.5; overflow-wrap:anywhere; } #returning-user-notice p { min-width:0; margin:0; } #returning-user-notice>div { display:flex; flex-wrap:wrap; gap:1rem; } diff --git a/src/setup-conflicts.ts b/src/setup-conflicts.ts index 3765853..1a02fc7 100644 --- a/src/setup-conflicts.ts +++ b/src/setup-conflicts.ts @@ -1,6 +1,7 @@ import { describeError, isMdbaseError, + revisionOf, type Mdbase, type MdbaseApplicationConnection, type MdbaseSetupConflict, @@ -15,10 +16,14 @@ export interface BundledSetupDefinition { readonly document: string; } +interface ReviewedSetupDefinition extends BundledSetupDefinition { + readonly reviewedRevision?: string; +} + export interface SetupConflictGuidance { readonly collectionId: string; readonly conflicts: readonly MdbaseSetupConflict[]; - readonly restorable: readonly BundledSetupDefinition[]; + readonly restorable: readonly ReviewedSetupDefinition[]; readonly manualOnly: readonly MdbaseSetupConflict[]; readonly canRestoreWithBackup: boolean; readonly backupFolder: string | null; @@ -77,28 +82,28 @@ export function backupFolderFor(connection: MdbaseApplicationConnection | null): return allowed ? `${allowed}/${DEFAULT_BACKUP_FOLDER}` : null; } -/** Non-adoptable setup conflicts that leave the shared setup review stuck at only "Try again". */ +/** Match a remapped target only when Core's review stages Journal's exact bytes there. */ export function inspectSetupConflicts( plan: MdbaseSetupPlan, collectionId: string, connection: MdbaseApplicationConnection | null, + staged: MdbaseSetupPlan["staged"] = plan.staged, ): SetupConflictGuidance | null { if (plan.canApply || plan.conflicts.length === 0) return null; - if (plan.refusal?.code === "setup_forbidden" || plan.refusal?.code === "installed_newer") return null; - const conflicts = plan.conflicts.filter( - conflict => !conflict.adoptable && !Object.hasOwn(plan.adoptable, conflict.target), - ); - if (conflicts.length === 0) return null; + if (plan.refusal?.code === "installed_newer" || plan.refusal?.code === "setup_downgrade") return null; + const conflicts = plan.conflicts; const bundled = bundledSetupDefinitions(); - const restorable: BundledSetupDefinition[] = []; + const restorable: ReviewedSetupDefinition[] = []; const manualOnly: MdbaseSetupConflict[] = []; for (const conflict of conflicts) { - const definition = bundled.get(conflict.target); - if (definition) restorable.push(definition); + const stagedDocument = staged.find(item => item.path === conflict.target)?.document; + const definition = bundled.get(conflict.target) ?? [...bundled.values()].find(item => item.document === stagedDocument); + const reviewedRevision = conflict.adoptable?.digest ?? (Object.hasOwn(plan.adoptable, conflict.target) ? plan.adoptable[conflict.target] : undefined); + if (definition) restorable.push({...definition, target: conflict.target, ...(reviewedRevision ? {reviewedRevision} : {})}); else manualOnly.push(conflict); } const live = connection !== null && connection.id === collectionId && connection.isCurrent(); - const canManage = live && connection.records.hello.grant.capabilities.includes("definitions.manage"); + const canManage = live && plan.refusal?.code !== "setup_forbidden" && connection.records.hello.grant.capabilities.includes("definitions.manage"); const backupFolder = live ? backupFolderFor(connection) : null; const canRestoreWithBackup = restorable.length > 0 && canManage && backupFolder !== null; const unavailableReason: SetupConflictGuidance["unavailableReason"] = @@ -196,9 +201,9 @@ function errorDetail(error: unknown, fallback: string): string { * Never overwrites a hand-edited file if saving its backup fails. */ export async function restoreSetupDefinitions( - mdbase: Pick, + mdbase: Pick, collectionId: string, - targets: readonly string[], + definitions: readonly ReviewedSetupDefinition[], options: RestoreSetupOptions = {}, ): Promise { const connection = mdbase.connection(collectionId); @@ -212,69 +217,57 @@ export async function restoreSetupDefinitions( if (!backupFolder) { throw new Error("Journal can't save a backup copy in this collection, so nothing was overwritten."); } - const bundled = bundledSetupDefinitions(); const encoder = new TextEncoder(); const now = options.now ?? (() => new Date()); const readOptions = options.signal ? { signal: options.signal } : undefined; const restored: RestoredSetupDefinition[] = []; - for (const target of targets) { + for (const canonical of definitions) { + const {target, reviewedRevision} = canonical; options.signal?.throwIfAborted(); - const canonical = bundled.get(target); - if (!canonical) { - throw new Error(`Journal does not ship a definition for ${target}. Resolve it by hand.`); - } - let existing: { text: string; revision: string } | null = null; + let existing: { text: string; revision: string }; try { const view = await connection.records.resources.get(target, readOptions); - if (typeof view.text !== "string") { + if (view.path !== target || typeof view.text !== "string" || revisionOf(view.text) !== view.revision) { throw new Error(`Could not read the current contents of ${target}, so Journal left your file unchanged.`); } existing = { text: view.text, revision: view.revision }; } catch (error) { - if (!isMdbaseError(error, "not_found")) { - throw new Error(`Could not read ${target} before restoring: ${errorDetail(error, "nothing was changed.")}`); - } + throw new Error(`Could not read ${target} before restoring: ${errorDetail(error, "nothing was changed.")}`); } if (!connection.isCurrent()) { throw new Error("This collection changed while restoring. Nothing further was changed."); } - if (existing && existing.text === canonical.document) { + if (existing.text === canonical.document) { restored.push(Object.freeze({ target, backupPath: null, unchanged: true })); continue; } - let backupPath: string | null = null; - if (existing) { - backupPath = backupPathFor(target, now(), backupFolder, options.suffix?.()); - try { - const upload = await connection.files.upload( - backupPath, - encoder.encode(existing.text), - options.signal ? { signal: options.signal } : undefined, - ); - await upload.confirmed; - } catch (error) { - throw new Error( - `Could not save a backup copy of ${target} (${errorDetail(error, "backup failed")}), so Journal left your file unchanged.`, - ); - } - if (!connection.isCurrent()) { - throw new Error(`This collection changed after saving your backup at ${backupPath}. Your original file was left unchanged.`); - } + if (reviewedRevision && existing.revision !== reviewedRevision) { + throw new Error(`${target} changed since setup was reviewed. Choose Try again to review the current file.`); + } + const backupPath = backupPathFor(target, now(), backupFolder, options.suffix?.()); + try { + const upload = await connection.files.upload(backupPath, encoder.encode(existing.text), readOptions); + await upload.confirmed; + } catch (error) { + throw new Error( + `Could not save a backup copy of ${target} (${errorDetail(error, "backup failed")}), so Journal left your file unchanged.`, + ); + } + if (!connection.isCurrent()) { + throw new Error(`This collection changed after saving your backup at ${backupPath}. Your original file was left unchanged.`); } try { const write = await connection.records.resources.put( target, canonical.document, - existing - ? { baseRevision: existing.revision, ...(options.signal ? { signal: options.signal } : {}) } - : { mustNotExist: true, ...(options.signal ? { signal: options.signal } : {}) }, + { baseRevision: existing.revision, ...(options.signal ? { signal: options.signal } : {}) }, ); await write.confirmed; } catch (error) { - const backupNote = backupPath ? ` Your backup copy was saved to ${backupPath}.` : ""; + const backupNote = ` Your backup copy was saved to ${backupPath}.`; if (isMdbaseError(error, "conflict")) { throw new Error(`${target} changed while restoring, so Journal didn't overwrite it.${backupNote} Try again.`); } @@ -284,6 +277,5 @@ export async function restoreSetupDefinitions( restored.push(Object.freeze({ target, backupPath, unchanged: false })); } - await mdbase.assess(options.signal ? { signal: options.signal } : undefined); return Object.freeze({ restored: Object.freeze(restored) }); } diff --git a/src/view.ts b/src/view.ts index d3de434..3bfef64 100644 --- a/src/view.ts +++ b/src/view.ts @@ -6,6 +6,7 @@ import {DELETED_ENTRY_NOTICE, JournalCatalogError, JournalData, type JournalEntr import {DraftOpens} from "./draft-opens.js"; import {connectionNotice, connectionNoticeLabels} from "./connection-notice.js"; import { + bundledSetupDefinitions, inspectSetupConflicts, restoreConfirmationText, restoreSetupDefinitions, @@ -57,6 +58,7 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase: let setupConflictCollectionId: string | null = null; let setupConflictChecking = false; let setupConflictController: AbortController | null = null; + let recheckingSetup = false; let restoringSetup = false; let switchingSetupCollection = false; let setupConflictFeedback: string | null = null; @@ -291,18 +293,25 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase: element("menu-connection").textContent = openId && catalogProblem ? `${catalogProblem.title}. ${catalogProblem.detail}` : openId ? `Notes save to ${name}.` : "Notes stay on this device until a collection is open."; const recovery = element("setup-conflict-recovery"); + // The shared panel still owns normal setup and its collection navigation. + // While Journal reviews a conflict, hide the shared replacement controls. + element("collection-panel").toggleAttribute("data-journal-recovery", !!setupConflictController || !!setupConflict); recovery.hidden = !setupConflict; if (setupConflict) { element("setup-conflict-guidance").textContent = setupConflictGuidanceText(setupConflict); const restoreButton = element("restore-setup-definition"); restoreButton.hidden = !setupConflict.canRestoreWithBackup; restoreButton.textContent = restoringSetup ? "Restoring…" : "Restore Journal’s version (keep backup)"; - restoreButton.disabled = restoringSetup || switchingSetupCollection; + const busy = restoringSetup || switchingSetupCollection || recheckingSetup; + restoreButton.disabled = busy || !!setupConflictController; const switchButton = element("switch-setup-collection"); switchButton.hidden = state?.signIn?.state !== "paired"; switchButton.textContent = switchingSetupCollection ? "Switching…" : "Switch collection"; - switchButton.disabled = restoringSetup || switchingSetupCollection; - element("cancel-setup-conflict").disabled = restoringSetup || switchingSetupCollection; + switchButton.disabled = busy; + const retrySetup = element("retry-setup-conflict"); + retrySetup.disabled = busy; + retrySetup.textContent = recheckingSetup ? "Checking…" : "Try again"; + element("cancel-setup-conflict").disabled = busy; const feedback = element("setup-conflict-feedback"); feedback.hidden = !setupConflictFeedback; feedback.textContent = setupConflictFeedback ?? ""; @@ -457,15 +466,27 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase: setupConflictController?.abort(); const controller = new (document.defaultView?.AbortController ?? AbortController)(); setupConflictController = controller; - void mdbase.setup.plan({signal: controller.signal}).then(plan => { - if (disposed || controller.signal.aborted || setupConflictController !== controller) return; + const signal = controller.signal; + const inspect = async () => { + const plan = await mdbase.setup.plan({signal}); + const adopt = Object.fromEntries(Object.entries(plan.adoptable).filter(([target]) => !bundledSetupDefinitions().has(target))); + let staged = plan.staged; + if (plan.refusal?.code === "setup_conflict" && Object.keys(adopt).length) { + // A dry replan gives the exact staged document at Core's resolved path. + // It never applies the SDK's unbacked replacement. + try {staged = (await mdbase.setup.plan({adopt, signal})).staged;} catch {/* Unknown paths stay manual. */} + } const currentPhase = snapshot()?.phase; - if (currentPhase?.kind !== "needs_setup" || currentPhase.collectionId !== collectionId) return; - setupConflict = inspectSetupConflicts(plan, collectionId, mdbase.connection(collectionId)); - render(); - }, () => { + if (signal.aborted || currentPhase?.kind !== "needs_setup" || currentPhase.collectionId !== collectionId) return; + setupConflict = inspectSetupConflicts(plan, collectionId, mdbase.connection(collectionId), staged); + }; + void inspect().catch(() => { if (disposed || controller.signal.aborted || setupConflictController !== controller) return; - setupConflict = null; + // An existing review stays in place if a recheck fails. + if (setupConflict) setupConflictFeedback = "Could not check setup right now. Try again."; + }).finally(() => { + if (disposed || controller.signal.aborted || setupConflictController !== controller) return; + setupConflictController = null; render(); }); } @@ -484,7 +505,7 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase: setupConflictCollectionId = currentPhase.collectionId; setupConflictChecking = checking; if (entered) {setupConflict = null; setupConflictFeedback = null;} - if ((entered || settled) && !restoringSetup) inspectSetupPlan(currentPhase.collectionId); + if ((entered || settled) && !restoringSetup && !recheckingSetup) inspectSetupPlan(currentPhase.collectionId); } else { setupConflictController?.abort(); setupConflictController = null; @@ -615,13 +636,18 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase: }); listen(element("restore-setup-definition"), "click", () => { const active = setupConflict; - if (!mdbase || disposed || restoringSetup || switchingSetupCollection || !active?.canRestoreWithBackup) return; + if (!mdbase || disposed || setupConflictController || restoringSetup || switchingSetupCollection || recheckingSetup || !active?.canRestoreWithBackup) return; restoringSetup = true; setupConflictFeedback = null; setupConflictNotice = null; render(); - void restoreSetupDefinitions(mdbase, active.collectionId, active.restorable.map(item => item.target), {signal: caller.signal}).then(result => { + void restoreSetupDefinitions(mdbase, active.collectionId, active.restorable, {signal: caller.signal}).then(async result => { if (disposed) return; const confirmation = restoreConfirmationText(result); setupConflictNotice = confirmation; setupConflictFeedback = confirmation; + try {await mdbase.assess({signal: caller.signal});} + catch { + setupConflictNotice = `${confirmation} Journal could not recheck setup. Open Settings to try again.`; + setupConflictFeedback = setupConflictNotice; + } }, error => { if (disposed) return; setupConflictFeedback = error instanceof Error && error.message.trim() ? error.message : "Could not restore Journal’s definition. Your file was left unchanged."; @@ -633,8 +659,19 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase: render(); }); }); + listen(element("retry-setup-conflict"), "click", () => { + const active = setupConflict; + if (!mdbase || !active || disposed || restoringSetup || switchingSetupCollection || recheckingSetup) return; + recheckingSetup = true; setupConflictFeedback = null; render(); + void mdbase.assess({signal: caller.signal}).then(() => { + const phase = snapshot()?.phase; + if (!disposed && phase?.kind === "needs_setup" && phase.collectionId === active.collectionId) inspectSetupPlan(active.collectionId); + }, () => { + if (!disposed && setupConflict === active) setupConflictFeedback = "Could not check setup right now. Try again."; + }).finally(() => {recheckingSetup = false; render();}); + }); listen(element("switch-setup-collection"), "click", () => { - if (!mdbase || disposed || restoringSetup || switchingSetupCollection) return; + if (!mdbase || disposed || restoringSetup || switchingSetupCollection || recheckingSetup) return; switchingSetupCollection = true; setupConflictFeedback = null; render(); void mdbase.chooseAnother({signal: caller.signal}).catch(error => { if (disposed) return; @@ -648,7 +685,7 @@ export function mountJournal(document: Document, drafts: JournalDrafts, mdbase: }); }); listen(element("cancel-setup-conflict"), "click", () => { - if (disposed || restoringSetup || switchingSetupCollection) return; + if (disposed || restoringSetup || switchingSetupCollection || recheckingSetup) return; setupConflictNotice = null; setupConflictFeedback = null; if (menu.open) menu.close(); diff --git a/tests/setup-conflicts.test.ts b/tests/setup-conflicts.test.ts index e2844f8..4e73496 100644 --- a/tests/setup-conflicts.test.ts +++ b/tests/setup-conflicts.test.ts @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import {readFileSync} from "node:fs"; import {mock, test} from "node:test"; import {JSDOM} from "jsdom"; -import type {MdbaseApplicationConnection, MdbaseSetupPlan} from "@mdbase-dev/sdk"; +import {revisionOf, type MdbaseApplicationConnection, type MdbaseSetupPlan} from "@mdbase-dev/sdk"; import {JournalDrafts} from "../src/drafts.js"; import { backupFolderFor, @@ -123,7 +123,7 @@ test("backupPathFor produces safe non-record, non-resource backup paths", () => assert.equal(path.startsWith("_types/"), false); }); -test("inspectSetupConflicts ignores adoptable conflicts and classifies non-adoptable conflicts by grant", async () => { +test("inspectSetupConflicts offers backed-up restoration for adoptable and non-adoptable definitions", async () => { const f = await applicationFixture(); try { const adoptablePlan: MdbaseSetupPlan = { @@ -131,13 +131,13 @@ test("inspectSetupConflicts ignores adoptable conflicts and classifies non-adopt conflicts: [{target: "_types/journal-entry.md", message: "Differs.", adoptable: {digest: "sha256:" + "b".repeat(64)}}], adoptable: {"_types/journal-entry.md": "sha256:" + "b".repeat(64)}, }; - assert.equal(inspectSetupConflicts(adoptablePlan, f.connection.id, f.connection), null); + assert.equal(inspectSetupConflicts(adoptablePlan, f.connection.id, f.connection)?.canRestoreWithBackup, true); const forbiddenPlan: MdbaseSetupPlan = { ...nonAdoptablePlan(), refusal: {code: "setup_forbidden", message: "No permission"}, }; - assert.equal(inspectSetupConflicts(forbiddenPlan, f.connection.id, f.connection), null); + assert.equal(inspectSetupConflicts(forbiddenPlan, f.connection.id, f.connection)?.unavailableReason, "no_permission"); const restorable = inspectSetupConflicts(nonAdoptablePlan(), f.connection.id, f.connection); assert(restorable); @@ -249,6 +249,75 @@ test("restoreSetupDefinitions backs up the hand-edited file, restores Journal's } }); +test("Journal takes over the shared review for a remapped, adoptable contract and backs up the edited bytes", async () => { + const f = await applicationFixture(); + const h = dom(); + const {document} = h.window; + const style = document.createElement("style"); + style.textContent = readFileSync(new URL("../public/journal.css", import.meta.url), "utf8"); + document.head.append(style); + const target = "_mdbase/contracts/journal.entry.md"; + const canonical = bundledSetupDefinitions().get(CONTRACT_TARGET)!.document; + const digest = revisionOf(HAND_EDITED_CONTRACT); + const refusal = nonAdoptablePlan(target); + const conflict: MdbaseSetupPlan = {...refusal, adoptable: {[target]: digest}, + conflicts: [{...refusal.conflicts[0]!, adoptable: {digest}}]}; + const {refusal: _refusal, ...review} = conflict; + const adopted: MdbaseSetupPlan = {...review, status: "setup", canApply: true, conflicts: [], adoptable: {}, staged: [{path: target, document: canonical}]}; + try { + await (await f.records.resources.put(target, HAND_EDITED_CONTRACT)).confirmed; + f.fixture.controls.publishSnapshot(needsSetupSnapshot(f.ready)); + const plan = mock.fn(async request => { + if (request?.adopt) assert.deepEqual(request.adopt, {[target]: digest}); + return request?.adopt ? adopted : conflict; + }); + const apply = mock.fn(f.mdbase.setup.apply); + const mdbase = {...f.mdbase, setup: {plan, apply}, assess: async () => { + f.fixture.controls.publishSnapshot(f.ready); + return f.ready.readiness; + }}; + const view = mountJournal(document, new JournalDrafts(memoryStorage()), mdbase); + try { + h.write("A draft on the edited collection"); + h.click("status-button"); + const shared = await until(() => document.querySelector("#collection-panel .mdbase-collections-setup") ?? undefined); + assert.match(shared.textContent!, /Use Journal.s version/); + assert.equal(h.window.getComputedStyle(shared).display, "none"); + const restore = document.querySelector("#restore-setup-definition")!; + await until(() => !restore.hidden || undefined); + assert.match(document.getElementById("setup-conflict-guidance")!.textContent!, /_mdbase\/contracts\/journal\.entry\.md/); + + h.click("cancel-setup-conflict"); + assert.equal(h.menu.open, false); + assert.equal(view.currentDraft().body, "A draft on the edited collection"); + assert.equal((await f.records.resources.get(target)).text, HAND_EDITED_CONTRACT); + + h.click("status-button"); + restore.click(); + const backup = await until(() => document.getElementById("setup-conflict-notice")!.textContent?.match(/journal-setup-backups\/[^\s]+\.bak\.txt/)?.[0]); + assert.equal((await f.records.resources.get(target)).text, canonical); + assert.equal(new TextDecoder().decode(await f.records.files.download({path: backup})), HAND_EDITED_CONTRACT); + assert.equal(apply.mock.callCount(), 0); + } finally {view.dispose();} + } finally {h.window.close(); await f.fixture.close();} +}); + +test("an adoptable definition changed before restore is left for a fresh review", async () => { + const f = await applicationFixture(); + const definition = bundledSetupDefinitions().get(CONTRACT_TARGET)!; + const upload = mock.method(f.records.files, "upload"); + try { + const newer = HAND_EDITED_CONTRACT + "Another edit."; + await (await f.records.resources.put(CONTRACT_TARGET, newer)).confirmed; + await assert.rejects( + restoreSetupDefinitions(f.mdbase, f.connection.id, [{...definition, reviewedRevision: revisionOf(HAND_EDITED_CONTRACT)}]), + /changed since setup was reviewed/, + ); + assert.equal(upload.mock.callCount(), 0); + assert.equal((await f.records.resources.get(CONTRACT_TARGET)).text, newer); + } finally {upload.mock.restore(); await f.fixture.close();} +}); + test("restoreSetupDefinitions never overwrites the hand-edited file if saving its backup fails", async () => { const f = await applicationFixture(); const h = dom(); @@ -299,7 +368,7 @@ test("restoreSetupDefinitions refuses blind overwrite when the definition change }); try { await assert.rejects( - restoreSetupDefinitions(f.mdbase, f.connection.id, [CONTRACT_TARGET], { + restoreSetupDefinitions(f.mdbase, f.connection.id, [bundledSetupDefinitions().get(CONTRACT_TARGET)!], { now: () => new Date("2026-11-27T08:30:15Z"), suffix: () => "race01", }), diff --git a/tests/view-availability.test.ts b/tests/view-availability.test.ts index 03fe855..306ba04 100644 --- a/tests/view-availability.test.ts +++ b/tests/view-availability.test.ts @@ -7,6 +7,40 @@ import {journalConnection} from "../src/application.js"; import {mountJournal} from "../src/view.js"; import {applicationFixture, catalog, deferred, memoryStorage} from "./support.js"; const html = readFileSync(new URL("../public/index.html", import.meta.url), "utf8"); + +test("the opening status meets WCAG AA in light and dark mode", async () => { + const f = await applicationFixture(); + const {window} = new JSDOM(html); + const {document} = window; + const style = document.createElement("style"); + style.textContent = readFileSync(new URL("../public/journal.css", import.meta.url), "utf8"); + document.head.append(style); + const drafts = new JournalDrafts(memoryStorage()); + const mdbase = {...f.mdbase, getSnapshot: () => ({...f.mdbase.getSnapshot(), + phase: {kind: "opening" as const, collectionId: f.connection.id, displayName: "Writing", slow: false}})}; + const view = mountJournal(document, drafts, mdbase); + try { + assert.match(document.getElementById("status")!.textContent!, /Opening Writing/); + const button = document.getElementById("status-button")!; + assert(button.classList.contains("notice")); + const luminance = (rgb: number[]) => rgb.map(channel => { + const value = channel / 255; + return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4; + }).reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index]!, 0); + const rgb = (hex: string) => hex.trim().slice(1).match(/../g)!.map(pair => parseInt(pair, 16)); + for (const theme of ["light", "dark"]) { + document.documentElement.dataset.theme = theme; + const palette = window.getComputedStyle(document.documentElement); + const background = rgb(palette.getPropertyValue("--bg")); + const foreground = rgb(palette.getPropertyValue("--muted")); + const opacity = Number(window.getComputedStyle(button).opacity || 1); + const composited = foreground.map((value, i) => value * opacity + background[i]! * (1 - opacity)); + const values = [luminance(background), luminance(composited)]; + const ratio = (Math.max(...values) + 0.05) / (Math.min(...values) + 0.05); + assert(ratio >= 4.5, `${theme} opening status contrast is ${ratio.toFixed(2)}:1`); + } + } finally {view.dispose(); window.close(); await f.fixture.close();} +}); test("advisory list unavailability cannot retire the original ready lease, clear writing or change its identity", async () => { const f = await applicationFixture(), job = deferred>(), describe = mock.method(f.records, "describe", () => job.promise); const h = new JSDOM(html, {runScripts: "outside-only"}), drafts = new JournalDrafts(memoryStorage());