// Rendered main-only acceptance. Synthetic canonical fixture data; no author data or AI. const { chromium } = require("playwright"), assert = require("node:assert/strict"), fs = require("node:fs"), os = require("node:os"), path = require("node:path"); const base = "http://127.0.0.1:5238", installed = process.argv.includes("--installed"), mode = installed ? "pwa" : "browser", out = "/tmp/pd-main-relationships-after", profile = fs.mkdtempSync(path.join(os.tmpdir(), "pd-main-relationships-")), manifestId = base + "/Projects"; fs.mkdirSync(out, { recursive: true }); (async () => { let context, page, cdp; const errors = [], calls = { directory: 0, state: 0, family: 0, assign: 0, undo: 0, save: 0, focusWrites: 0, }, values = new Map(), previous = new Map(); let fail = 0; const metrics = []; async function launch(restart = false) { context = await chromium.launchPersistentContext(profile, { headless: !installed, viewport: { width: 1920, height: 1080 }, }); page = context.pages()[0]; context.on("request", (r) => { if ( r.method() === "POST" && /\/NarrativeFocus\/(?:Shared\/Publish|Set)$/.test( new URL(r.url()).pathname, ) ) calls.focusWrites++; }); await context.route("https://cdn.jsdelivr.net/**", (r) => r.fulfill({ contentType: "application/javascript", body: fs.readFileSync( path.join( __dirname, "node_modules", r.request().url().includes("cytoscape") ? "cytoscape/dist/cytoscape.min.js" : r.request().url().includes("chart.umd") ? "chart.js/dist/chart.umd.js" : "@microsoft/signalr/dist/browser/signalr.min.js", ), ), }), ); await context.route("**/NarrativeFocus/Shared?*", (r) => r.fulfill({ json: { projectID: 7, bookID: 12, chapterID: 21, sceneID: 1, version: 1, isValid: true, }, }), ); await context.route("**/CharacterAttributes/Directory?*", async (r) => { calls.directory++; const cast = await page.evaluate( () => window.PlotDirectorRelationshipWorkspace?.cast || [], ); return r.fulfill({ json: { canEdit: true, characters: cast.map((c) => ({ id: c.characterID, version: "fixture-v1", values: { importance: values.has(c.characterID) ? values.get(c.characterID) : c.characterImportance == null ? "" : String(c.characterImportance), }, })), }, }); }); await context.route("**/CharacterAttributes/Assign", (r) => { calls.assign++; const b = r.request().postDataJSON(); assert.equal(b.attribute, "importance"); assert.equal(b.changes.length, 1); assert.equal(b.changes[0].version, "fixture-v1"); if (fail) { const status = fail; fail = 0; return r.fulfill({ status, json: { saved: false, message: "Fixture conflict: a newer value is recorded.", }, }); } const { id, value } = b.changes[0]; previous.set("undo-" + calls.assign, { id, value: values.has(id) ? values.get(id) : "", }); values.set(id, value); return r.fulfill({ json: { saved: true, undoToken: "undo-" + calls.assign, characters: [ { id, version: "fixture-v1", values: { importance: value } }, ], }, }); }); await context.route("**/CharacterAttributes/Undo", (r) => { calls.undo++; const { id, value } = previous.get(r.request().postDataJSON().token); values.set(id, value); return r.fulfill({ json: { saved: true, characters: [ { id, version: "fixture-v1", values: { importance: value } }, ], }, }); }); await context.route("**/RelationshipMap/State?*", async (r) => { calls.state++; const u = new URL(r.request().url()), q = new URLSearchParams( await page.evaluate(() => ({ cast: new URL(location.href).searchParams.get("cast") || 75, network: new URL(location.href).searchParams.get("network") || "clusters", })), ); if (u.searchParams.has("sceneId")) q.set("sceneId", u.searchParams.get("sceneId")); const model = await ( await page.request.get(base + "/relationship-main-state-fixture?" + q) ).json(); for (const c of model.cast) if (values.has(c.characterID)) c.characterImportance = values.get(c.characterID) === "" ? null : +values.get(c.characterID); return r.fulfill({ json: model }); }); await context.route("**/RelationshipMap/Family?*", async (r) => { calls.family++; return r.fulfill({ response: await page.request.get( base + "/relationship-main-family-fixture?cast=75", ), }); }); await context.route("**/RelationshipMap/Save", (r) => { calls.save++; assert(r.request().postData().includes("__RequestVerificationToken")); return r.fulfill({ status: 200 }); }); await page.goto(base + "/fixture?page=calendar-test"); if (installed) { cdp = await context.browser().newBrowserCDPSession(); if (!restart) { await cdp.send("PWA.install", { manifestId, installUrlOrBundleUrl: page.url(), }); await cdp.send("PWA.changeAppUserSettings", { manifestId, displayMode: "standalone", }); } const opened = context.waitForEvent("page"); await cdp.send("PWA.launch", { manifestId, url: page.url() }); page = await opened; await page.waitForLoadState(); assert( await page.evaluate( () => matchMedia("(display-mode: standalone)").matches, ), ); await page.setViewportSize({ width: 1920, height: 1080 }); } page.on("pageerror", (e) => errors.push(e.message)); } async function ready() { await page.waitForFunction(() => { const w = window.PlotDirectorRelationshipWorkspace; return ( w?.mainCommands?.initialised && !w.mainCommands.busy && !w.mainCommands.routing ); }); await page.waitForTimeout(150); } async function open(count = 75, network = "clusters") { await page.goto( `${base}/fixture?page=relationships&layout=full&cast=${count}&network=${network}`, ); await ready(); } async function state() { return page.evaluate(() => { const w = window.PlotDirectorRelationshipWorkspace, m = w.mainCommands; return { members: m.members.sort((a, b) => a - b), pins: m.pins, preset: m.preset, zoom: w.cy.zoom(), pan: w.cy.pan(), positions: Object.fromEntries( w.cy.nodes(":visible").map((n) => [n.id(), n.position()]), ), relationships: w.relationships().map((r) => r.characterRelationshipID), widths: JSON.parse( localStorage.getItem( "plotdirector.workspace.panels.relationships." + document.getElementById("rwApp").dataset.workspacePreferenceScope, ) || "{}", ), key: m.storageKey, }; }); } async function option(label, value, group) { console.log("option", label, value); const source = page.getByLabel(label, { exact: true }); const visible = await source.all(); let control; for (const n of visible) if (await n.isVisible()) { control = n; break; } if (!control && !installed) { const sourceDetails = source .first() .locator("xpath=ancestor::details[1]"); await sourceDetails.locator(":scope > summary").click(); control = source.first(); } if (!control) { const g = page.locator(`.pd-context-group[aria-label="${group}"]`); await g.locator(":scope > details > summary").click(); control = g.getByLabel(label, { exact: true }); } await control.selectOption(value); if (!installed) await control.evaluate((n) => (n.closest("details").open = false)); await ready(); if (!(await page.locator("dialog[open]").count())) await page.keyboard.press("Escape"); } async function shot(name) { await page.screenshot({ path: `${out}/${mode}-${name}.png` }); } async function nodePoint(id) { return page.evaluate((id) => { const w = window.PlotDirectorRelationshipWorkspace, n = w.cy.$id("c-" + id); w.cy.center(n); const r = document .getElementById("relationshipMapGraph") .getBoundingClientRect(), p = n.renderedPosition(); return { x: r.x + p.x, y: r.y + p.y }; }, id); } async function drop(id, selector) { await page.evaluate( ({ id, selector }) => { const source = document.querySelector(`[data-rw-character="${id}"]`), target = document.querySelector(selector), b = target.getBoundingClientRect(), dataTransfer = new DataTransfer(); source.dispatchEvent( new DragEvent("dragstart", { bubbles: true, dataTransfer }), ); for (const type of ["dragover", "drop"]) target.dispatchEvent( new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer, clientX: b.x + (selector === "#relationshipMapGraph" ? { 1: 250, 2: 550, 3: 400 }[id] || 250 : b.width / 2), clientY: b.y + (selector === "#relationshipMapGraph" ? id === 3 ? 350 : 180 : b.height / 2), }), ); source.dispatchEvent( new DragEvent("dragend", { bubbles: true, dataTransfer }), ); }, { id, selector }, ); await ready(); } async function unchanged(before, label) { const after = await state(); for (const k of ["positions", "members", "pins", "zoom", "pan", "widths"]) assert.deepEqual(after[k], before[k], label + " " + k); } try { await launch(); await open(); assert.equal((await state()).preset, "connected"); assert.equal((await state()).members.length, 75); await shot("connected-clusters"); // Pointer-anchored wheel and middle pan; no HTTP lookups. let beforeCalls = { ...calls }, b = await page.locator("#relationshipMapGraph").boundingBox(), pointer = { x: b.width * 0.43, y: b.height * 0.47 }; await page.mouse.move(b.x + pointer.x, b.y + pointer.y); let anchor = await page.evaluate((p) => { const c = window.PlotDirectorRelationshipWorkspace.cy; return { x: (p.x - c.pan().x) / c.zoom(), y: (p.y - c.pan().y) / c.zoom(), z: c.zoom(), }; }, pointer); await page.mouse.wheel(0, -100); await page.waitForTimeout(100); let after = await page.evaluate((p) => { const c = window.PlotDirectorRelationshipWorkspace.cy; return { x: (p.x - c.pan().x) / c.zoom(), y: (p.y - c.pan().y) / c.zoom(), z: c.zoom(), }; }, pointer); assert(after.z > anchor.z); assert( Math.hypot(anchor.x - after.x, anchor.y - after.y) < 0.5, "pointer zoom anchor " + JSON.stringify({ anchor, after, pointer }), ); let before = await state(); await page.mouse.down({ button: "middle" }); await page.mouse.move(b.x + pointer.x + 70, b.y + pointer.y + 45, { steps: 12, }); await page.mouse.up({ button: "middle" }); after = await state(); assert(Math.abs(after.pan.x - before.pan.x - 70) < 1); assert.deepEqual(after.positions, before.positions); assert.deepEqual( calls, beforeCalls, "pointer navigation performs no retrieval", ); // Native canvas node drag. Importance must not change. let p = await nodePoint(1); before = await state(); await page.mouse.move(p.x, p.y); await page.mouse.down(); await page.mouse.move(p.x + 62, p.y + 35, { steps: 12 }); await page.mouse.up(); await ready(); after = await state(); assert.notDeepEqual(after.positions["c-1"], before.positions["c-1"]); assert.equal(calls.assign, 0); // Browser + actual PWA right click, pin, keyboard menu/Delete and separate diagram undo. p = await nodePoint(1); await page.mouse.click(p.x, p.y, { button: "right" }); await page .getByRole("menuitem", { name: "Pin position", exact: true }) .click(); await ready(); assert((await state()).pins.includes(1)); await shot("pinned-position"); await page.locator("#relationshipMapGraph").press("Shift+F10"); await page .getByRole("menuitem", { name: "Remove from diagram", exact: true }) .click(); await ready(); assert(!(await state()).members.includes(1)); assert.equal(await page.locator('[data-rw-character="1"]').count(), 1); assert.equal( (await state()).relationships.length, before.relationships.length, ); await page.locator("#relationshipMapGraph").press("Control+z"); await ready(); assert((await state()).members.includes(1)); assert((await state()).pins.includes(1)); // Pinned auto-arrange keeps exact position; family explicitly asks about pins. before = await state(); await option("Diagram arrangement", "importance", "Layout"); assert.deepEqual((await state()).positions["c-1"], before.positions["c-1"]); await shot("importance-layout"); const beforeCancel = await state(); const layoutPromise = option("Diagram arrangement", "family", "Layout"); await page.locator("#rwPinDialog[open]").waitFor(); await page.getByRole("button", { name: "Cancel", exact: true }).click(); await layoutPromise; assert.deepEqual( (await state()).positions, beforeCancel.positions, "cancel preserves arrangement", ); // Family pin choices preserve or explicitly release pins; layout Undo restores the individual position. before = await state(); const keepFamily = option("Diagram arrangement", "family", "Layout"); await page.locator("#rwPinDialog[open]").waitFor(); await page .getByRole("button", { name: "Keep pinned positions", exact: true }) .click(); await keepFamily; assert.deepEqual((await state()).positions["c-1"], before.positions["c-1"]); assert((await state()).pins.includes(1)); await page.locator("#relationshipMapGraph").press("Control+z"); await ready(); assert.deepEqual((await state()).positions, before.positions); const releaseFamily = option("Diagram arrangement", "family", "Layout"); await page.locator("#rwPinDialog[open]").waitFor(); await page .getByRole("button", { name: "Rearrange family", exact: true }) .click(); await releaseFamily; assert.equal((await state()).pins.length, 0); await page.locator("#relationshipMapGraph").press("Control+z"); await ready(); assert.deepEqual((await state()).pins, before.pins); assert.deepEqual((await state()).positions, before.positions); before = await state(); await page.locator("#relationshipMapGraph").press("Delete"); await ready(); assert(!(await state()).members.includes(1)); await page.locator("#relationshipMapGraph").press("Control+z"); await ready(); assert.deepEqual((await state()).members, before.members); await page.locator("#rwSearch").fill("Person"); await page.locator("#rwSearch").press("Delete"); assert.deepEqual( (await state()).members, before.members, "Delete in a text field does not remove a character", ); await page.locator("#rwSearch").fill(""); // Character importance canonical operation, counts, success Undo, no-op and conflict. values.set(1, ""); await page.evaluate( () => (window.PlotDirectorRelationshipWorkspace.cast.find( (c) => c.characterID === 1, ).characterImportance = null), ); await drop(1, '[data-rw-tier="10"]'); assert.equal(calls.assign, 1); assert.equal( await page.locator('[data-rw-tier="10"] [data-rw-character="1"]').count(), 1, ); await shot("importance-assigned"); await page .getByRole("button", { name: "Undo importance", exact: true }) .click(); await ready(); assert.equal(calls.undo, 1); assert.equal( await page.locator('[data-rw-tier=""] [data-rw-character="1"]').count(), 1, ); await drop(1, '[data-rw-tier=""]'); assert.equal(calls.assign, 1, "same importance no write"); fail = 409; await drop(1, '[data-rw-tier="6"]'); assert.equal(calls.assign, 2); assert.equal( await page.locator('[data-rw-tier=""] [data-rw-character="1"]').count(), 1, "failed assignment retained group", ); // Existing single presence connection; receiving an invalidation refreshes only data. before = await state(); const stateReads = calls.state; values.set(2, "10"); await page.evaluate(() => { const connection = window.PlotDirectorPresenceConnection; if (!connection) throw Error("Existing presence connection missing"); window.mainTestConnection = connection; const handlers = connection._methods?.contextinvalidated || connection.handlers?.ContextInvalidated || Object.values(connection).find( (value) => value && typeof value === "object" && Array.isArray(value.contextinvalidated), )?.contextinvalidated; if (!handlers?.length) throw Error( "Existing channel has no invalidation handlers: " + Object.keys(connection), ); for (const handler of Array.isArray(handlers) ? handlers : [handlers]) handler({ projectId: 7, kind: "characters" }); }); await page.waitForFunction( () => window.PlotDirectorRelationshipWorkspace.cast.find( (c) => c.characterID === 2, ).characterImportance === 10, ); await ready(); assert(calls.state > stateReads); await unchanged(before, "live data update"); assert( await page.evaluate( () => mainTestConnection === PlotDirectorPresenceConnection, ), "no replacement or extra card connections", ); // Clear stays empty through history, reload, live invalidation; explicit readd no duplicate. await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.mainCommands.clear(), ); await ready(); assert.equal((await state()).members.length, 0); await page.locator("#rwTimeline").fill("100"); await page.waitForTimeout(400); await ready(); assert.equal((await state()).members.length, 0); await page.reload(); await ready(); assert.equal((await state()).members.length, 0); await drop(1, "#relationshipMapGraph"); await drop(1, "#relationshipMapGraph"); await drop(2, "#relationshipMapGraph"); await drop(3, "#relationshipMapGraph"); assert.deepEqual((await state()).members, [1, 2, 3]); await shot("removed-readded-custom"); // Custom arrangement/pins survive preset excursion and reload. await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.mainCommands.pin(1), ); before = await state(); await option("Diagram display preset", "full", "Display"); assert.equal((await state()).members.length, 75); await shot("full-cast"); await option("Diagram display preset", "custom", "Display"); assert.deepEqual((await state()).positions, before.positions); assert.deepEqual((await state()).members, [1, 2, 3]); assert.deepEqual((await state()).pins, [1]); await option("Diagram display preset", "full", "Display"); await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.mainCommands.pin(1), ); await option("Diagram arrangement", "clusters", "Layout"); await shot("full-cast-clusters"); await page .locator('[data-toast-host] button[aria-label^="Dismiss"]') .evaluateAll((ns) => ns.forEach((n) => n.click())); await page.locator('[data-rw-character="1"]').click(); await option("Diagram arrangement", "radial", "Layout"); await shot("radial"); await option("Diagram display preset", "selected", "Display"); assert((await state()).members.length < 75); await option("Connection depth", "1", "Layout"); assert((await state()).members.length <= 10); await option("Diagram display preset", "family", "Display"); assert.equal((await state()).members.length, 75); await shot("family-tree"); for (const connector of ["straight", "curved", "orthogonal"]) { await option("Connectors", connector, "Display"); assert.equal( await page.locator("#rwApp").getAttribute("data-connector-style"), connector, ); await shot(connector + "-connectors"); const ep = await page.evaluate(() => { const w = window.PlotDirectorRelationshipWorkspace, cy = w.cy, g = document .getElementById("relationshipMapGraph") .getBoundingClientRect(); for (const e of cy.edges(":visible")) { cy.center(e); const p = e.renderedMidpoint(); if (!p || !Number.isFinite(p.x)) continue; if ( !cy.nodes(":visible").some((n) => { const b = n.renderedBoundingBox(); return p.x >= b.x1 && p.x <= b.x2 && p.y >= b.y1 && p.y <= b.y2; }) ) return { x: g.x + p.x, y: g.y + p.y }; } throw Error("No exposed edge midpoint"); }); await page.mouse.click(ep.x, ep.y, { button: "right" }); await page .getByRole("menuitem", { name: "View relationship details", exact: true, }) .waitFor(); await page.keyboard.press("Escape"); await page.evaluate( () => (window.PlotDirectorRelationshipWorkspace.selectedRelationship = null), ); await page.mouse.click(ep.x, ep.y); await page.waitForFunction( () => !!window.PlotDirectorRelationshipWorkspace.selectedRelationship, ); } // Details and right-click line preserve canonical author reference. p = await nodePoint(1); await page.mouse.click(p.x, p.y, { button: "right" }); await shot("character-menu"); await page.keyboard.press("Escape"); await page.locator("#rwCanvasMenu").click(); await page .getByRole("menuitem", { name: "Fit diagram", exact: true }) .click(); await ready(); // Actual DOM bounds of arranged cards, all layouts; dimensions, not just centres. await option("Diagram display preset", "full", "Display"); for (const kind of ["clusters", "radial", "importance", "family"]) { await option("Diagram arrangement", kind, "Layout"); const measurement = await page.evaluate(() => { const w = window.PlotDirectorRelationshipWorkspace, ns = w.cy.nodes(":visible").map((n) => ({ id: n.id(), ...n.boundingBox({ includeLabels: false, includeOverlays: false, }), })); let overlaps = 0; for (let i = 0; i < ns.length; i++) for (let j = i + 1; j < ns.length; j++) if ( Math.min(ns[i].x2, ns[j].x2) > Math.max(ns[i].x1, ns[j].x1) + 0.5 && Math.min(ns[i].y2, ns[j].y2) > Math.max(ns[i].y1, ns[j].y1) + 0.5 ) overlaps++; return { kind: w.lastLayout.kind, ms: w.lastLayout.durationMs, overlaps, nodes: ns.length, }; }); metrics.push(measurement); assert.equal(measurement.kind, kind); assert.equal(measurement.overlaps, 0, kind + " actual card overlaps"); } // Existing independent panel width controls, no fetch on resize; zoom/pan stable. const handles = page.getByRole("separator"), n = await handles.count(); assert(n >= 2); before = await state(); beforeCalls = { ...calls }; for (let i = 0; i < 2; i++) { await handles .nth(i) .press(i === 0 ? "Shift+ArrowRight" : "Shift+ArrowLeft"); await handles .nth(i) .press(i === 0 ? "Shift+ArrowRight" : "Shift+ArrowLeft"); } await ready(); assert.deepEqual((await state()).positions, before.positions); assert.deepEqual((await state()).pan, before.pan); assert.equal((await state()).zoom, before.zoom); assert.deepEqual(calls, beforeCalls); await shot("resized-panels"); // Double-click follows the canonical route and Back retains diagram state. p = await nodePoint(1); before = await state(); await context.route("**/Characters/Details/1", (r) => r.fulfill({ contentType: "text/html", body: "
Character details navigation fixture
", }), ); await page.mouse.dblclick(p.x, p.y); await page.waitForURL("**/Characters/Details/1"); await page.goBack(); await ready(); await unchanged(before, "character navigation and Back"); // Touch/keyboard alternative opens the same selected-character menu. await page .getByRole("button", { name: "Selected character actions", exact: true }) .click(); await page .getByRole("menuitem", { name: "Remove from diagram", exact: true }) .waitFor(); await page.keyboard.press("Escape"); // Scene Explorer is local; only its explicit promotion invokes the established focus setter. const promotionTarget = await page.evaluate(() => { const focus = window.PlotDirectorNarrativeFocus, target = focus.state.positions.find((p) => p.sceneID); if (!target) throw Error("Fixture requires a known focus scene"); window.mainPromotions = []; focus.set = async (target) => { mainPromotions.push(target); return true; }; return target; }); before = await state(); await page .getByLabel("Scene to visualise", { exact: true }) .selectOption(String(promotionTarget.sceneID)); await page.waitForTimeout(350); await ready(); assert.equal( await page.evaluate(() => mainPromotions.length), 0, "local scene exploration never invokes global setter", ); await unchanged(before, "Scene Explorer selection"); assert( await page.evaluate(() => { const w = window.PlotDirectorRelationshipWorkspace; return w.mainCommands.records().every((r) => { const e = w.cy.$id("r-" + r.characterRelationshipID); return ( e.source().data("characterID") === r.characterAID && e.target().data("characterID") === r.characterBID && e.hasClass(r.cssClass) && e.data("label") === r.relationshipTypeName ); }); }), "historical refresh retains author-family endpoints, categories and labels", ); await page .getByRole("button", { name: "Set Current Focus Here", exact: true }) .click(); assert.equal(await page.evaluate(() => mainPromotions.length), 1); assert.equal( await page.evaluate(() => mainPromotions[0].sceneID), promotionTarget.sceneID, ); calls.explicitPromotion = 1; // Seven themes and representative widths, no horizontal overflow. for (const width of [1280, 1920, 2560, 3840, 800, 390, 1920]) { await page.setViewportSize({ width, height: 1080 }); await page.waitForTimeout(150); assert( await page.evaluate( () => document.documentElement.scrollWidth <= innerWidth + 2, ), "overflow " + width, ); if (width === 2560) await shot("wide-2560"); } for (const theme of [ "plotdirector", "modern-light", "modern-dark", "warm-light", "warm-dark", "rose-pink", "baby-blue", ]) { await page.evaluate((t) => { document.documentElement.dataset.appTheme = t; document.documentElement.dataset.bsTheme = t.endsWith("dark") ? "dark" : "light"; }, theme); await ready(); await shot("theme-" + theme); } await page.waitForTimeout(400); before = await state(); await page.reload(); await ready(); await unchanged(before, "reload"); await context.close(); await launch(true); await open(); await unchanged(before, "persistent Chromium/PWA restart"); assert.equal( calls.focusWrites, 0, "diagram operations made no shared-focus write requests", ); assert.deepEqual(errors, []); fs.writeFileSync( `${out}/${mode}-acceptance.json`, JSON.stringify( { status: "passed", actualInstalledPwa: installed, restart: true, calls, metrics, errors, }, null, 2, ), ); console.log( "PASS main Relationships " + mode + " rendered interaction, canonical assignment/Undo, presets/layouts/routes, scoped persistence/restart, themes and widths", ); } finally { if (cdp) await cdp.send("PWA.uninstall", { manifestId }).catch(() => {}); await context?.close(); fs.rmSync(profile, { recursive: true, force: true }); } })().catch((e) => { console.error(e.stack); process.exitCode = 1; });