diff --git a/Docs/Relationships/MainWorkspaceEnhancement-20261126.md b/Docs/Relationships/MainWorkspaceEnhancement-20261126.md index e233d09b..9a35132e 100644 --- a/Docs/Relationships/MainWorkspaceEnhancement-20261126.md +++ b/Docs/Relationships/MainWorkspaceEnhancement-20261126.md @@ -11,3 +11,29 @@ Existing main state: local v1 project/book layout, manual extra/removed nodes, f Plan/checkpoints: A baseline/isolation; B scoped interaction/menus; C membership/pins/layout undo; D shared importance assignment; E clustered/radial/family/importance layouts; F routing; G presets/history stability; H persistence/dividers; I build/full regression, rendered browser/PWA, all themes, protected comparisons, performance, documentation and Development smoke/deployment. Do not deploy an incomplete checkpoint. Preserve unrelated investigation files and existing author data. Acceptance evidence and measured results will be appended after implementation. The user attachment remains the authoritative checklist, including every section 21 criterion and requested screenshots. Any unverified or incomplete requirement must be labelled explicitly in the final matrix. + +## Implemented boundary and architecture + +The main page explicitly loads `relationship-main.js`, `relationship-main-layout.js` and one dedicated calculation worker. `_GraphScripts` remains main-only. No Context or Character Details renderer, layout, stylesheet, controller, focus contract or default has changed. The only shared-surface change is an opt-in author/project/book preference-key suffix; unscoped callers retain their original key and behaviour. + +The main adapter retains the existing canonical editor, historical State resolver, Scene Explorer, Details, full-width shell, palette responsive drawer, Map/List and maximise. It diffs edges and updates affected cast records rather than remounting Cytoscape. Family-only/reference layouts lazily retrieve an explicitly authorised author-reference projection from the existing relationship repository. Family classification and deterministic family geometry reuse the existing Context family predicate/algorithm without changing them. History ordering reuses `StoryStateService.OrderScenes`. The family projection is a read model, not another relationship store. + +Importance uses `CharacterQuickAttributes` presentation definitions and the existing Directory/Assign/Undo endpoints, row versions, antiforgery, project permissions, protected undo tokens and shared actionable toast service. It performs no optimistic reclassification. Equal values are client/server no-ops. Relationship saves publish lightweight existing `ContextWorkspaceNotifications`; receiving views continue authenticated data retrieval. The main page subscribes once to the existing presence connection, coalesces hints and never constructs a SignalR connection. No new SQL or migrations are needed. No AI or author-data classification is involved. + +### Geometry and interaction + +Cluster placement uses recorded connected components, deterministic greedy modularity communities inside each component, bounded local/community force placement and actual rectangular collision clearance. Isolated members are compactly parked. Radial uses breadth-first recorded relationship distance, a chosen centre and bounded depth. Importance uses wrapped tiers with community/degree/barycentre ordering. Family uses existing canonical parent/child/partner/sibling roles and shared junction routes, including adoption/step styles; it never infers a partnership from shared children. Circle remains available. Pinned positions are exact; conflicting pins warn rather than moving an author's pin. + +Layout and route batches run in a single main-page worker with request generations; stale results are discarded. If unavailable, the same pure engine supplies the fallback and route work yields in batches. Node movement recalculates incident routes while dragging and a complete batch on release. Zoom updates labels without route recalculation or network calls. Straight links have distinct boundary endpoints; curves use bounded obstacle-aware candidates; orthogonal links use doglegs and bounded obstacle detours, including parallel lane offsets. Dense labels concentrate on selection/hover/focus with an explicit Show all option. Crossings remain possible in dense networks. + +Pointer-anchored ordinary wheel zoom and captured middle-button pan are confined to the main canvas. Node selection preserves viewport position; explicit palette/centre actions centre it. Native pointer context menus reuse the shared service via its existing queued registration pattern; geometry APIs are selected by connector style. Shift+F10/Context Menu key, Diagram menu and selected Character actions provide keyboard/touch alternatives. Delete is guarded to a canvas character selection, leaving text editing alone. Double-click uses the existing Character Details route. + +### Membership and local preferences + +Version 2 preferences are keyed by author/project/book and migrate existing main v1 positions, removed/extra nodes, focus and viewport. They contain membership, positions, pins, preset, arrangement, connector, depth, label preference, Map/List, palette collapse and zoom/pan. The custom snapshot survives a preset excursion. A separate bounded diagram Undo stack restores diagram state; importance Undo continues server-side concurrency checks. Clear/remove are purely diagram operations, never archive/delete operations. Two independent divider widths use the existing workspace-surface storage with the same opt-in scope. Preferences are local browser data and do not synchronise across devices; no canonical records are used as a preference store. + +Family pin choices are explicit Keep/Rearrange/Cancel. After a manual family-card move, independent orthogonal routing is used until the next explicit family arrangement rebuilds shared junction paths. General routing is best effort, not a guarantee of a planar graph. Very large arrangements begin at readable zoom; Fit provides an overview and pointer zoom/pan exposes individual regions. Forced conflicting pins are the only permitted card-overlap exception. + +## Verification and delivery + +See the accompanying acceptance report for the per-criterion matrix, exact before/after protected comparisons, measured timings, screenshots, commit IDs and Development receipt. Baseline comparisons were captured before implementation. Synthetic fixtures exercise 20, 75, 100 and 200 characters, sparse/dense networks, connected subgroups, isolated members and canonical multi-generation family definitions. Existing author records are not demonstration fixtures. Production is outside this release. diff --git a/Docs/Relationships/Workspace.md b/Docs/Relationships/Workspace.md index 9d146102..4863817c 100644 --- a/Docs/Relationships/Workspace.md +++ b/Docs/Relationships/Workspace.md @@ -75,3 +75,9 @@ The initial stability styling reserved unequal 150px/65px slots, leaving an unev The existing 8+/4–7/below-4 classifications and Model.Cast order are unchanged. Supporting entries are no longer split by alternating index: the complete existing collection renders on the left. Major and Minor entries keep their top and bottom homes. The left keeps Find character and a Supporting count, with the dropdown and three importance filter buttons removed. Search still matches every cast entry using the existing accent/case normalization, and palette-local scrolling brings a focused result into view without scrolling the outer workspace. The right is Details only, with the existing character/relationship content and colour key. Clear focus resets the contextual content instead of switching to a Supporting list. Collapsing character palettes retains Details. The mobile drawer continues to move all existing character entries into one list, then restore their desktop homes on resize; no duplicate portraits or records are introduced. Tests cover complete Supporting population/order, absence of the removed controls/tab, search/focus across all classes, Supporting drag/drop, Details, mobile and existing map/ribbon stability. + +## Main-only diagram enhancement (2026-11-26) + +The main workspace now has pointer-anchored wheel zoom, middle-button pan, scoped menus, persistent custom membership, pins and separate diagram Undo. Major/Supporting/Minor/Unclassified palette assignment reuses canonical quick attributes and protected Undo. Layout and Display contain the new arrangements, depth, routing and membership presets. Scene Explorer and the existing editor remain authoritative; ordinary diagram operations do not change shared manuscript focus. + +Details of the opt-in boundary, algorithms, worker, persistence and practical routing limits are in [Main workspace implementation](MainWorkspaceEnhancement-20261126.md). The updated Relationship Map help article explains author interactions. The corresponding acceptance report contains the explicit checklist and protected Context/Character Details before/after evidence. Existing Context Family/Story and Character Details relationship SVGs, defaults and interaction systems are unchanged; these new preferences and controls apply only to the main Relationships page. diff --git a/PlotLine.Tests/Browser/package-lock.json b/PlotLine.Tests/Browser/package-lock.json index 1f8cce03..6d86d82f 100644 --- a/PlotLine.Tests/Browser/package-lock.json +++ b/PlotLine.Tests/Browser/package-lock.json @@ -7,6 +7,7 @@ "devDependencies": { "@microsoft/signalr": "8.0.7", "chart.js": "4.4.9", + "cytoscape": "3.35.0", "playwright": "1.58.2", "sharp": "^0.35.5" } @@ -644,6 +645,16 @@ "pnpm": ">=8" } }, + "node_modules/cytoscape": { + "version": "3.35.0", + "resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.35.0.tgz", + "integrity": "sha512-sMvBIXiGMnhkCaWz2R06FwF/27MNlS+Tqvi17foO9UhnUg3XGZccKjxsvEqQFAQYMSSZmN5SxYzUYlQ0DOJJ3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", diff --git a/PlotLine.Tests/Browser/package.json b/PlotLine.Tests/Browser/package.json index 246bf104..f90bffbb 100644 --- a/PlotLine.Tests/Browser/package.json +++ b/PlotLine.Tests/Browser/package.json @@ -23,11 +23,15 @@ "test:maps-story": "node maps-story-engine.cjs && node maps-story.cjs", "test:writer": "node writer-workspace.cjs", "test:writer-goals": "node writer-goal-navigation.cjs", - "test:word-companion": "node context-workspace-foundation.cjs" + "test:word-companion": "node context-workspace-foundation.cjs", + "test:relationships-main": "node relationship-main-layout.cjs && node relationship-main-workspace.cjs && node relationship-main-parallel.cjs && node relationship-main-scope.cjs", + "test:relationships-main-pwa": "xvfb-run -a node relationship-main-workspace.cjs --installed", + "test:relationships-performance": "node relationship-main-performance.cjs" }, "devDependencies": { "@microsoft/signalr": "8.0.7", "chart.js": "4.4.9", + "cytoscape": "3.35.0", "playwright": "1.58.2", "sharp": "^0.35.5" } diff --git a/PlotLine.Tests/Browser/relationship-focus-stability.cjs b/PlotLine.Tests/Browser/relationship-focus-stability.cjs index 17f47818..89b6971e 100644 --- a/PlotLine.Tests/Browser/relationship-focus-stability.cjs +++ b/PlotLine.Tests/Browser/relationship-focus-stability.cjs @@ -9,11 +9,11 @@ const base='http://127.0.0.1:5238'; if(pwa) await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true})); const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message)); await page.goto(base+'/fixture?page=relationships',{waitUntil:'domcontentloaded'}); - await page.waitForFunction(()=>!!window.PlotDirectorRelationshipWorkspace); + await page.waitForFunction(()=>!!window.PlotDirectorRelationshipWorkspace?.mainCommands?.initialised && !window.PlotDirectorRelationshipWorkspace.mainCommands.arranging && !window.PlotDirectorRelationshipWorkspace.mainCommands.routing); if(pwa && width===1920) { await page.getByRole('tab',{name:'Characters',exact:true}).click(); - await page.waitForFunction(()=>document.querySelector('[data-pwa-context-controls] .pd-context-group[aria-label="Focus"] details')?.dataset.compact==='false'); - const spacing=await page.evaluate(()=>{const group=document.querySelector('[data-pwa-context-controls] .pd-context-group[aria-label="Focus"]');const buttons=[...group.querySelectorAll('button')];return {compact:group.querySelector('details').dataset.compact,rects:buttons.map(b=>b.getBoundingClientRect().toJSON()),clear:buttons[1].textContent.trim(),disabled:buttons[1].disabled,clipped:buttons[1].querySelector('span').scrollWidth>buttons[1].querySelector('span').clientWidth+1}}); + await page.waitForFunction(()=>document.querySelector('[data-pwa-context-controls] .pd-context-group[aria-label="Diagram focus"] details')?.dataset.compact==='false'); + const spacing=await page.evaluate(()=>{const group=document.querySelector('[data-pwa-context-controls] .pd-context-group[aria-label="Diagram focus"]');const buttons=[...group.querySelectorAll('button')];return {compact:group.querySelector('details').dataset.compact,rects:buttons.map(b=>b.getBoundingClientRect().toJSON()),clear:buttons[1].textContent.trim(),disabled:buttons[1].disabled,clipped:buttons[1].querySelector('span').scrollWidth>buttons[1].querySelector('span').clientWidth+1}}); assert.equal(spacing.compact,'false');assert.equal(spacing.clear,'Clear focus');assert(spacing.disabled,'Clear focus is disabled without a focus'); assert(spacing.rects.every(r=>r.width>0&&r.height>0),'both actions present without an empty slot'); assert(Math.abs(spacing.rects[0].width-spacing.rects[1].width)<1,'balanced action widths'); @@ -58,7 +58,7 @@ const base='http://127.0.0.1:5238'; result.samples.forEach((sample,index)=>sample.forEach((rect,region)=>rect.forEach((value,axis)=>assert(Math.abs(value-result.baseline[region][axis])<=1,`${pwa?'PWA':'web'} ${width}: shifted region ${region} axis ${axis} sample ${index}: ${value} vs ${result.baseline[region][axis]}`)))); if(pwa) {assert.equal(result.rebuilds,0,'focus must not rebuild contextual ribbon');assert(result.sameNodes,'ribbon nodes retained');} assert(result.sameGraph&&result.positionsUnchanged,'canvas instance and node layout retained');assert.equal(result.zoom,.9); - if(pwa){assert.equal(result.caption,'Focus: '+result.long);assert.equal(result.tooltip,result.caption);assert.equal(result.clearLabel,'Full cast'); + if(pwa){assert.equal(result.caption,'Focus: '+result.long);assert.equal(result.tooltip,result.caption);assert.equal(result.clearLabel,'Connected characters'); assert.equal(await page.locator('[data-pwa-context-controls]').getByRole('button',{name:'Maximise workspace',exact:true,includeHidden:true}).count(),1); assert.equal(await page.locator('[data-pwa-context-controls] .pd-context-group:empty').count(),0); await page.evaluate(()=>{const source=document.createElement('button');source.id='focusFixtureCommand';source.type='button';source.textContent='Fixture command';source.dataset.ribbonIcon='list';source.onclick=()=>window.__fixtureInvoked=true;document.querySelector('.rw-view-switch').append(source)}); diff --git a/PlotLine.Tests/Browser/relationship-main-layout.cjs b/PlotLine.Tests/Browser/relationship-main-layout.cjs new file mode 100644 index 00000000..e686bc60 --- /dev/null +++ b/PlotLine.Tests/Browser/relationship-main-layout.cjs @@ -0,0 +1,189 @@ +const vm = require("vm"), + fs = require("fs"), + assert = require("assert/strict"); +const box = {}; +box.window = box; +vm.createContext(box); +for (const file of [ + "context-relationship-layout.js", + "relationship-main-layout.js", +]) + vm.runInContext(fs.readFileSync("PlotLine/wwwroot/js/" + file, "utf8"), box); +const engine = box.PlotDirectorMainRelationshipLayout; +const nodes = Array.from({ length: 200 }, (_, i) => ({ + id: i + 1, + name: "Person " + (i + 1), + w: 184 + (i % 3) * 12, + h: 70 + (i % 2) * 12, + importance: [10, 6, 2, null][i % 4], +})); +const overlap = (a, b, ps) => + engine.intersects(engine.rect(a, ps[a.id]), engine.rect(b, ps[b.id])); +const results = []; +for (const count of [20, 75, 100, 200]) + for (const network of ["sparse", "dense", "clusters", "isolated"]) { + const ns = nodes.slice(0, count), + edges = []; + for (let id = 1; id <= count; id++) + for ( + let step = 1; + step <= (network === "dense" ? 6 : network === "clusters" ? 3 : 1); + step++ + ) + if ( + network !== "isolated" && + id + step <= count && + (network !== "sparse" || id % 4 === 0) && + (network !== "clusters" || + Math.floor(id / 12) === Math.floor((id + step) / 12) || + (id % 12 === 0 && step === 1)) + ) + edges.push({ + id: edges.length + 1, + a: id, + b: id + step, + type: "Friend", + reciprocal: true, + }); + const input = { + nodes: ns, + edges, + layout: "clusters", + viewport: { width: 1400, height: 650 }, + }, + start = performance.now(), + result = engine.layout(input), + ms = performance.now() - start; + assert.equal(Object.keys(result.positions).length, count); + for (let i = 0; i < count; i++) + for (let j = i + 1; j < count; j++) + assert( + !overlap(ns[i], ns[j], result.positions), + `${count}/${network}: overlap ${i}/${j}`, + ); + assert.equal( + JSON.stringify(result.positions), + JSON.stringify(engine.layout(input).positions), + "deterministic", + ); + results.push({ + count, + network, + layoutMs: ms, + communities: result.communities?.length, + aspect: result.bounds.w / result.bounds.h, + }); + } +const clique = nodes.slice(0, 12), + edges = []; +for (let a = 1; a <= 12; a++) + for (let b = a + 1; b <= 12; b++) + if (a <= 6 === b <= 6 || (a === 6 && b === 7)) + edges.push({ id: edges.length + 1, a, b }); +const clustered = engine.layout({ nodes: clique, edges, layout: "clusters" }); +assert( + clustered.communities.length >= 2, + "connected graph reveals recorded subgroups", +); +assert(clustered.communities.some((g) => g.length >= 4)); +const radial = engine.layout({ + nodes: nodes.slice(0, 8), + edges: [ + { id: 1, a: 1, b: 2 }, + { id: 2, a: 2, b: 3 }, + { id: 3, a: 3, b: 4 }, + { id: 4, a: 1, b: 5 }, + ], + focus: 1, + depth: 3, + layout: "radial", +}); +assert.equal(radial.distances[2], 1); +assert.equal(radial.distances[3], 2); +assert.equal(radial.distances[4], 3); +assert.equal(radial.distances[6], undefined); +assert( + Math.hypot(radial.positions[2].x, radial.positions[2].y) < + Math.hypot(radial.positions[3].x, radial.positions[3].y), +); +const family = engine.layout({ + nodes: nodes.slice(0, 8).map((n) => ({ ...n, w: 180, h: 66 })), + edges: [ + { id: 1, a: 1, b: 2, type: "Spouse", reciprocal: true }, + { id: 2, a: 1, b: 3, type: "Parent" }, + { id: 3, a: 2, b: 3, type: "Parent" }, + { id: 4, a: 3, b: 4, type: "Adoptive Parent" }, + { id: 5, a: 3, b: 5, type: "Parent" }, + { id: 6, a: 6, b: 5, type: "Parent" }, + ], + layout: "family", +}); +assert( + family.positions[1].y < family.positions[3].y && + family.positions[3].y < family.positions[4].y, +); +assert.equal(family.positions[1].y, family.positions[2].y); +assert.equal(family.positions[4].y, family.positions[5].y); +assert(family.routes.some((r) => r.kind === "adoptive")); +assert(family.junctions.length); +const pinned = engine.layout({ + nodes: nodes.slice(0, 20), + edges: [], + pins: { 1: { x: 10, y: 15 } }, + layout: "importance", +}); +assert.deepEqual(JSON.parse(JSON.stringify(pinned.positions[1])), { + x: 10, + y: 15, +}); +for (let i = 1; i < 20; i++) + assert(!overlap(nodes[0], nodes[i], pinned.positions)); +const route = engine.route( + [ + { id: 1, x: 0, y: 0, w: 100, h: 50 }, + { id: 2, x: 500, y: 0, w: 100, h: 50 }, + { id: 3, x: 250, y: 0, w: 120, h: 100 }, + ], + { id: 1, a: 1, b: 2 }, + "orthogonal", +); +assert(route.points.some((p) => Math.abs(p.y) > 60 || p.x < 180 || p.x > 320)); +const curve = engine.route( + [ + { id: 1, x: 0, y: 0, w: 100, h: 50 }, + { id: 2, x: 500, y: 0, w: 100, h: 50 }, + { id: 3, x: 250, y: 0, w: 120, h: 100 }, + ], + { id: 1, a: 1, b: 2 }, + "curved", +); +assert(Math.abs(curve.distance) > 100); +fs.mkdirSync("/tmp/pd-main-relationships-after", { recursive: true }); +fs.writeFileSync( + "/tmp/pd-main-relationships-after/layout-performance.json", + JSON.stringify(results, null, 2), +); +console.log( + "PASS main-only deterministic clustered/subgroup, distance-ring radial, shared canonical family, importance/pins, collision separation and obstacle routing fixtures", + results, +); + +const parallelNodes = [ + { id: 1, x: 0, y: 0, w: 100, h: 50 }, + { id: 2, x: 500, y: 0, w: 100, h: 50 }, + { id: 3, x: 250, y: 0, w: 120, h: 100 }, +]; +for (const style of ["straight", "curved", "orthogonal"]) + assert.notDeepEqual( + JSON.parse( + JSON.stringify( + engine.route(parallelNodes, { id: 1, a: 1, b: 2 }, style, -16), + ), + ), + JSON.parse( + JSON.stringify( + engine.route(parallelNodes, { id: 2, a: 1, b: 2 }, style, 16), + ), + ), + style + " parallel paths remain distinct around an obstacle", + ); diff --git a/PlotLine.Tests/Browser/relationship-main-parallel.cjs b/PlotLine.Tests/Browser/relationship-main-parallel.cjs new file mode 100644 index 00000000..959a20ee --- /dev/null +++ b/PlotLine.Tests/Browser/relationship-main-parallel.cjs @@ -0,0 +1,144 @@ +// Parallel recorded relationships rendered through the real main renderer; no persistence calls. +const { chromium } = require("playwright"), + fs = require("fs"), + path = require("path"), + assert = require("assert/strict"); +(async () => { + const b = await chromium.launch(); + try { + const c = await b.newContext({ viewport: { width: 1920, height: 1080 } }), + p = await c.newPage(), + errors = []; + p.on("pageerror", (e) => errors.push(e.message)); + await c.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 c.route("**/CharacterAttributes/Directory?*", (r) => + r.fulfill({ json: { canEdit: true, characters: [] } }), + ); + await p.goto( + "http://127.0.0.1:5238/fixture?page=relationships&layout=full&cast=20&network=clusters", + ); + const ready = () => + p.waitForFunction(() => { + const m = window.PlotDirectorRelationshipWorkspace?.mainCommands; + return m?.initialised && !m.busy && !m.routing; + }); + await ready(); + const model = await ( + await p.request.get( + "http://127.0.0.1:5238/relationship-main-state-fixture?cast=20&network=clusters", + ) + ).json(), + record = model.relationships[0], + link = model.links.find( + (e) => e.characterRelationshipID === record.characterRelationshipID, + ); + model.relationships.push({ + ...record, + characterRelationshipID: 900, + relationshipTypeName: "Rival", + relationshipCategoryName: "Hostile / Conflict", + cssClass: "relationship-category-hostile", + }); + model.links.push({ + ...link, + characterRelationshipID: 900, + relationshipLabel: "Rival", + categoryName: "Hostile / Conflict", + cssClass: "relationship-category-hostile", + }); + await p.evaluate( + (model) => window.PlotDirectorRelationshipWorkspace.update(model), + model, + ); + await ready(); + for (const style of ["straight", "curved", "orthogonal"]) { + await p.locator(".rw-display > summary").click(); + await p.locator("#rwConnector").selectOption(style); + await p.keyboard.press("Escape"); + await ready(); + const geometry = await p.evaluate( + ({ first, style }) => { + const cy = window.PlotDirectorRelationshipWorkspace.cy, + edges = [cy.$id("r-" + first), cy.$id("r-900")]; + return edges.map((e) => ({ + path: + style === "orthogonal" + ? e.renderedSegmentPoints() + : style === "straight" + ? [e.renderedSourceEndpoint(), e.renderedTargetEndpoint()] + : e.renderedControlPoints(), + color: e.style("line-color"), + id: e.data("relationshipID"), + })); + }, + { first: record.characterRelationshipID, style }, + ); + assert.notDeepEqual( + geometry[0].path, + geometry[1].path, + style + " visible parallel paths", + ); + assert.notEqual( + geometry[0].color, + geometry[1].color, + "category colours preserved", + ); + for (const id of [record.characterRelationshipID, 900]) { + const pt = await p.evaluate((id) => { + const cy = window.PlotDirectorRelationshipWorkspace.cy, + e = cy.$id("r-" + id); + cy.center(e); + const box = document + .getElementById("relationshipMapGraph") + .getBoundingClientRect(), + point = e.renderedMidpoint(); + return { x: box.x + point.x, y: box.y + point.y }; + }, id); + await p.mouse.click(pt.x, pt.y, { button: "right" }); + await p + .getByRole("menuitem", { + name: "View relationship details", + exact: true, + }) + .click(); + assert.equal( + await p.evaluate( + () => + window.PlotDirectorRelationshipWorkspace.selectedRelationship + .characterRelationshipID, + ), + id, + style + " separately selects " + id, + ); + } + if (style === "curved") + await p.screenshot({ + path: "/tmp/pd-main-relationships-after/parallel-curved.png", + }); + } + assert.deepEqual(errors, []); + console.log( + "PASS rendered parallel straight/curved/orthogonal paths, category colours and individual native pointer selection", + ); + } finally { + await b.close(); + } +})().catch((e) => { + console.error(e.stack); + process.exitCode = 1; +}); diff --git a/PlotLine.Tests/Browser/relationship-main-performance.cjs b/PlotLine.Tests/Browser/relationship-main-performance.cjs new file mode 100644 index 00000000..1dbd9be4 --- /dev/null +++ b/PlotLine.Tests/Browser/relationship-main-performance.cjs @@ -0,0 +1,243 @@ +// Compare with captured pre-enhancement fixtures. One catalogue read per page, no per-node queries. +const { chromium } = require("playwright"), + fs = require("fs"), + path = require("path"), + assert = require("assert/strict"); +(async () => { + const browser = await chromium.launch(); + try { + const context = await browser.newContext({ + viewport: { width: 1920, height: 1080 }, + }); + 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("**/CharacterAttributes/Directory?*", (r) => + r.fulfill({ json: { canEdit: true, characters: [] } }), + ); + const page = await context.newPage(), + out = "/tmp/pd-main-relationships-after", + results = []; + await page.addInitScript(() => { + window.mainFrames = []; + let last; + function tick(t) { + if (last) mainFrames.push(t - last); + last = t; + requestAnimationFrame(tick); + } + requestAnimationFrame(tick); + }); + const navigationOnly = process.argv.includes("--navigation-only"); + for (const count of navigationOnly ? [200] : [20, 75, 100, 200]) + for (const network of navigationOnly + ? ["dense"] + : ["sparse", "clusters", "dense", "isolated"]) { + await page.goto("http://127.0.0.1:5238/fixture?page=calendar-test"); + await page.evaluate(() => localStorage.clear()); + const started = Date.now(); + await page.goto( + `http://127.0.0.1:5238/fixture?page=relationships&cast=${count}&network=${network}`, + ); + await page.waitForFunction(() => { + const m = window.PlotDirectorRelationshipWorkspace?.mainCommands; + return m?.initialised && !m.busy && !m.routing; + }); + const loadMs = Date.now() - started; + const membershipStarted = Date.now(); + await page.evaluate(() => + window.PlotDirectorRelationshipWorkspace.mainCommands.setPreset( + "full", + ), + ); + const membershipMs = Date.now() - membershipStarted; + await page.evaluate(() => + window.PlotDirectorRelationshipWorkspace.mainCommands.arrange( + "clusters", + ), + ); + await page.waitForFunction( + () => !window.PlotDirectorRelationshipWorkspace.mainCommands.routing, + ); + const result = await page.evaluate(() => { + const w = window.PlotDirectorRelationshipWorkspace, + cy = w.cy, + ns = cy.nodes(":visible"), + box = ns.boundingBox(); + let overlaps = 0; + for (let i = 0; i < ns.length; i++) + for (let j = i + 1; j < ns.length; j++) { + const a = ns[i].boundingBox(), + b = ns[j].boundingBox(); + if (a.x1 < b.x2 && a.x2 > b.x1 && a.y1 < b.y2 && a.y2 > b.y1) + overlaps++; + } + return { + nodes: ns.length, + edges: cy.edges(":visible").length, + overlaps, + layoutMs: w.lastLayout.durationMs, + routingMs: w.mainRoutingStats.durationMs, + communities: w.lastLayout.result.communities?.length, + aspect: box.w / box.h, + zoom: cy.zoom(), + smallestRenderedWidth: Math.min( + ...ns.map((n) => n.renderedWidth()), + ), + frameP95: mainFrames.sort((a, b) => a - b)[ + Math.floor(mainFrames.length * 0.95) + ], + }; + }); + assert.equal( + result.overlaps, + 0, + count + "/" + network + " actual box overlaps", + ); + if (navigationOnly) { + const positionsBefore = await page.evaluate(() => { + const g = document.getElementById("rwApp"); + window.navigationFrames = []; + for (const name of ["wheel", "pointermove"]) + g.addEventListener( + name, + () => { + const t = performance.now(); + requestAnimationFrame(() => + requestAnimationFrame(() => + navigationFrames.push(performance.now() - t), + ), + ); + }, + { capture: true }, + ); + return JSON.stringify( + window.PlotDirectorRelationshipWorkspace.cy + .nodes() + .map((n) => [n.id(), n.position()]), + ); + }); + let retrievals = 0; + const countReads = (r) => { + if ( + /\/(RelationshipMap|CharacterAttributes)\//.test( + new URL(r.url()).pathname, + ) + ) + retrievals++; + }; + page.on("request", countReads); + const box = await page.locator("#relationshipMapGraph").boundingBox(); + await page.mouse.move( + box.x + box.width * 0.5, + box.y + box.height * 0.5, + ); + const started = Date.now(); + await page.mouse.wheel(0, -80); + await page.evaluate( + () => + new Promise((r) => + requestAnimationFrame(() => requestAnimationFrame(r)), + ), + ); + const beforePan = await page.evaluate(() => + window.PlotDirectorRelationshipWorkspace.cy.pan(), + ); + await page.mouse.down({ button: "middle" }); + await page.mouse.move( + box.x + box.width * 0.5 + 55, + box.y + box.height * 0.5 + 40, + { steps: 10 }, + ); + await page.mouse.up({ button: "middle" }); + await page.evaluate( + () => + new Promise((r) => + requestAnimationFrame(() => requestAnimationFrame(r)), + ), + ); + const response = await page.evaluate(() => ({ + pan: window.PlotDirectorRelationshipWorkspace.cy.pan(), + positions: JSON.stringify( + window.PlotDirectorRelationshipWorkspace.cy + .nodes() + .map((n) => [n.id(), n.position()]), + ), + frames: navigationFrames, + })); + assert.equal(response.positions, positionsBefore); + assert( + Math.abs(response.pan.x - beforePan.x - 55) < 1 && + Math.abs(response.pan.y - beforePan.y - 40) < 1, + ); + assert.equal(retrievals, 0); + result.navigation = { + totalNativeSequenceMs: Date.now() - started, + twoFrameResponseMaxMs: Math.max(...response.frames), + twoFrameResponseAverageMs: + response.frames.reduce((a, b) => a + b, 0) / + response.frames.length, + samples: response.frames.length, + retrievals, + nodePositionsUnchanged: true, + }; + assert( + result.navigation.twoFrameResponseMaxMs < 500, + "200-character dense diagram remains navigable", + ); + page.off("request", countReads); + } + results.push({ count, network, loadMs, membershipMs, ...result }); + if ( + !navigationOnly && + ((count === 75 && network === "clusters") || + (count === 200 && network === "dense") || + (count === 75 && network === "sparse")) + ) { + await page.screenshot({ + path: `${out}/main-${count}-${network}.png`, + }); + await page.evaluate(() => + window.PlotDirectorRelationshipWorkspace.mainCommands.fit(), + ); + await page.screenshot({ + path: `${out}/main-${count}-${network}-overview.png`, + }); + } + console.log( + count, + network, + loadMs, + Math.round(result.layoutMs), + Math.round(result.routingMs), + result.overlaps, + ); + } + fs.writeFileSync( + out + + (navigationOnly ? "/navigation-performance.json" : "/performance.json"), + JSON.stringify(results, null, 2), + ); + console.log( + "PASS actual rendered full-cast20/75/100/200: sparse, connected subgroups, dense and isolated; measured layout/routing/frame intervals, zero card overlaps", + ); + } finally { + await browser.close(); + } +})().catch((e) => { + console.error(e.stack); + process.exitCode = 1; +}); diff --git a/PlotLine.Tests/Browser/relationship-main-protected-comparison.cjs b/PlotLine.Tests/Browser/relationship-main-protected-comparison.cjs new file mode 100644 index 00000000..edf893a1 --- /dev/null +++ b/PlotLine.Tests/Browser/relationship-main-protected-comparison.cjs @@ -0,0 +1,77 @@ +// Compare controlled before/after captures. Only ephemeral SVG marker UUIDs are normalised. +const fs = require("fs"), + path = require("path"), + crypto = require("crypto"), + sharp = require("sharp"), + assert = require("assert/strict"); +(async () => { + const before = process.env.PD_BEFORE || "/tmp/pd-main-relationships-before", + after = process.env.PD_AFTER || "/tmp/pd-main-relationships-after", + hashes = JSON.parse( + fs.readFileSync(path.join(before, "protected-source-hashes.json")), + ), + results = []; + for (const [file, expected] of Object.entries(hashes)) + assert.equal( + crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"), + expected, + "protected source changed " + file, + ); + for (const name of [ + "context-family", + "context-story", + "character-relationships", + ]) { + const normalise = (s) => + s.replace( + /((?:pd-context-arrow-\d+-|cw-arrow-))[\da-f-]{36}/g, + "$1INSTANCE", + ); + assert.equal( + normalise(fs.readFileSync(path.join(after, name + ".svg"), "utf8")), + normalise(fs.readFileSync(path.join(before, name + ".svg"), "utf8")), + name + " geometry/markup changed", + ); + const a = await sharp(path.join(before, name + ".png")) + .raw() + .toBuffer({ resolveWithObject: true }), + b = await sharp(path.join(after, name + ".png")) + .raw() + .toBuffer({ resolveWithObject: true }); + assert.deepEqual(a.info, b.info); + let changed = 0, + maxDifference = 0; + for (let i = 0; i < a.data.length; i += a.info.channels) { + let different = false; + for (let j = 0; j < a.info.channels; j++) { + const d = Math.abs(a.data[i + j] - b.data[i + j]); + maxDifference = Math.max(d, maxDifference); + different ||= d > 0; + } + if (different) changed++; + } + assert(changed <= 12, name + " screenshot changed: " + changed + " pixels"); + results.push({ + name, + sourceHashesUnchanged: true, + svgGeometryAndMarkupIdentical: true, + changedPixels: changed, + totalPixels: a.info.width * a.info.height, + maxDifference, + note: changed + ? "Only fringe rasterisation pixels; identical vectors, data, layout and styles." + : "Exact PNG match.", + }); + } + fs.writeFileSync( + path.join(after, "protected-comparison.json"), + JSON.stringify(results, null, 2), + ); + console.log( + "PASS protected source hashes, identical SVG geometry/markup and screenshot comparisons", + results, + ); +})().catch((e) => { + console.error(e.message); + process.exitCode = 1; +}); diff --git a/PlotLine.Tests/Browser/relationship-main-scope.cjs b/PlotLine.Tests/Browser/relationship-main-scope.cjs new file mode 100644 index 00000000..019d6fec --- /dev/null +++ b/PlotLine.Tests/Browser/relationship-main-scope.cjs @@ -0,0 +1,248 @@ +// Synthetic scope projections exercise only local preferences and shared quick-assignment UI. +// Server authorisation is independently covered by RelationshipWorkspaceTests. +const { chromium } = require("playwright"), + fs = require("fs"), + path = require("path"), + assert = require("assert/strict"); +(async () => { + const b = await chromium.launch(); + try { + const c = await b.newContext({ viewport: { width: 1920, height: 1080 } }), + p = await c.newPage(), + errors = [], + values = new Map(); + p.on("pageerror", (e) => errors.push(e.message)); + await c.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 c.route("**/NarrativeFocus/Shared?*", (r) => + r.fulfill({ + json: { + projectID: 7, + bookID: 12, + chapterID: 21, + sceneID: 1, + version: 1, + isValid: true, + }, + }), + ); + await c.route("**/CharacterAttributes/Directory?*", (r) => + r.fulfill({ + json: { + canEdit: true, + characters: Array.from({ length: 20 }, (_, i) => ({ + id: i + 1, + version: "v1", + values: { importance: values.get(i + 1) || "6" }, + })), + }, + }), + ); + await c.route("**/CharacterAttributes/Assign", (r) => { + const body = r.request().postDataJSON(); + assert.equal(body.projectId, 8); + assert.equal(body.attribute, "importance"); + assert.deepEqual(body.changes, [{ id: 1, value: "10", version: "v1" }]); + values.set(1, "10"); + return r.fulfill({ + json: { + saved: true, + undoToken: "scope-fixture", + characters: [{ id: 1, version: "v2", values: { importance: "10" } }], + }, + }); + }); + await c.route("**/CharacterAttributes/Undo", (r) => { + assert.equal(r.request().postDataJSON().token, "scope-fixture"); + values.delete(1); + return r.fulfill({ + json: { + saved: true, + characters: [{ id: 1, version: "v3", values: { importance: "6" } }], + }, + }); + }); + await c.route("**/fixture?**", async (r) => { + if (new URL(r.request().url()).searchParams.get("scope") !== "8") + return r.continue(); + const response = await r.fetch(), + html = (await response.text()) + .replace( + 'data-project-id="7" data-book-id="" id="rwApp"', + 'data-project-id="8" data-book-id="" id="rwApp"', + ) + .replace("projectId: 7,", "projectId: 8,"); + return r.fulfill({ response, body: html }); + }); + const ready = () => + p.waitForFunction(() => { + const m = window.PlotDirectorRelationshipWorkspace?.mainCommands; + return m?.initialised && !m.busy && !m.routing; + }), + open = async (scope) => { + await p.goto( + "http://127.0.0.1:5238/fixture?page=relationships&layout=full&cast=20&network=isolated&scope=" + + scope, + ); + await ready(); + }, + view = () => + p.evaluate(() => { + const w = window.PlotDirectorRelationshipWorkspace, + m = w.mainCommands; + return { + key: m.storageKey, + members: m.members, + pins: m.pins, + zoom: w.cy.zoom(), + pan: w.cy.pan(), + positions: Object.fromEntries( + w.cy.nodes(":visible").map((n) => [n.id(), n.position()]), + ), + left: document + .querySelector(".rw-navigation") + .getBoundingClientRect().width, + }; + }); + await open(7); + assert.equal( + (await view()).members.length, + 0, + "fresh Connected with no relationships remains empty", + ); + await p.evaluate(() => { + const w = window.PlotDirectorRelationshipWorkspace; + w.mainCommands.focusCharacter(1); + w.cy.$id("c-1").position({ x: 305, y: 207 }); + w.mainCommands.pin(1); + w.cy.zoom(1.1); + w.cy.pan({ x: 60, y: 75 }); + }); + await p + .getByRole("separator", { name: "Resize left panel" }) + .press("ArrowRight"); + await p.waitForTimeout(350); + const expected = await view(); + assert(expected.key.includes(".4.7.")); + await open(8); + assert((await view()).key.includes(".4.8.")); + assert.equal((await view()).members.length, 0); + assert.notEqual( + (await view()).left, + expected.left, + "independent project divider width", + ); + assert.equal( + await p.locator('[data-rw-tier="10"] [data-rw-character]').count(), + 0, + ); + await p.evaluate(() => { + const source = document.querySelector('[data-rw-character="1"]'), + target = document.querySelector('[data-rw-tier="10"]'), + dataTransfer = new DataTransfer(); + source.dispatchEvent( + new DragEvent("dragstart", { bubbles: true, dataTransfer }), + ); + target.dispatchEvent( + new DragEvent("drop", { + bubbles: true, + cancelable: true, + dataTransfer, + }), + ); + source.dispatchEvent( + new DragEvent("dragend", { bubbles: true, dataTransfer }), + ); + }); + await p + .getByRole("button", { name: "Undo importance", exact: true }) + .waitFor(); + assert.equal( + await p.locator('[data-rw-tier="10"] [data-rw-character="1"]').count(), + 1, + "empty Major remains a drop target", + ); + assert.match( + await p.locator('[data-rw-tier="10"]').getAttribute("aria-label"), + /Major: 1/, + ); + await p + .getByRole("button", { name: "Undo importance", exact: true }) + .click(); + await p.waitForFunction(() => + document.querySelector('[data-rw-tier="6"] [data-rw-character="1"]'), + ); + assert.equal( + await p.locator('[data-rw-tier="10"] [data-rw-character]').count(), + 0, + ); + await p.locator("#rwEmptyFull").click(); + await ready(); + await p.locator('.rw-menu[data-pwa-context="Layout"] > summary').click(); + await p.locator("#rwLayout").selectOption("radial"); + await p.locator("#rwCentreDialog[open]").waitFor(); + await p.getByLabel("Central character", { exact: true }).selectOption("3"); + await p + .getByRole("button", { name: "Arrange radial", exact: true }) + .click(); + await ready(); + assert.equal( + await p.evaluate( + () => window.PlotDirectorRelationshipWorkspace.lastLayout.result.focus, + ), + 3, + "radial centre is chosen through an accessible dialog", + ); + await p.screenshot({ + path: "/tmp/pd-main-relationships-after/empty-group-and-centre.png", + }); + await open(7); + assert.deepEqual( + await view(), + expected, + "project-specific membership, positions, pin, viewport and divider restored", + ); + await c.addCookies([ + { name: "fixture-user", value: "5", url: "http://127.0.0.1:5238" }, + ]); + await open(7); + assert((await view()).key.includes(".5.7.")); + assert.equal( + (await view()).members.length, + 0, + "different author has independent preferences", + ); + await c.addCookies([ + { name: "fixture-user", value: "4", url: "http://127.0.0.1:5238" }, + ]); + await open(7); + assert.deepEqual( + await view(), + expected, + "return to original author restores only that author state", + ); + assert.deepEqual(errors, []); + console.log( + "PASS empty connected network, empty importance target/count/Undo, radial chooser, independent author/project membership, positions, pins, viewport and divider preferences", + ); + } finally { + await b.close(); + } +})().catch((e) => { + console.error(e.stack); + process.exitCode = 1; +}); diff --git a/PlotLine.Tests/Browser/relationship-main-workspace.cjs b/PlotLine.Tests/Browser/relationship-main-workspace.cjs new file mode 100644 index 00000000..a10e4ac9 --- /dev/null +++ b/PlotLine.Tests/Browser/relationship-main-workspace.cjs @@ -0,0 +1,772 @@ +// 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 }, + 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]; + 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)); + if (!(await page.locator("dialog[open]").count())) + await page.keyboard.press("Escape"); + await ready(); + } + 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"); + // 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 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.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; +}); diff --git a/PlotLine.Tests/Browser/relationship-protected-character-capture.cjs b/PlotLine.Tests/Browser/relationship-protected-character-capture.cjs new file mode 100644 index 00000000..b9d99e94 --- /dev/null +++ b/PlotLine.Tests/Browser/relationship-protected-character-capture.cjs @@ -0,0 +1,174 @@ +// Controlled synthetic capture matching the pre-change baseline; no author data. +const { chromium } = require("playwright"), + assert = require("node:assert/strict"), + fs = require("node:fs"), + path = require("node:path"); +const base = process.env.PD_BROWSER_BASE || "http://127.0.0.1:5238"; +(async () => { + const b = await chromium.launch(); + let step = "setup"; + try { + const c = await b.newContext({ viewport: { width: 1366, height: 1000 } }); + await c.route("**/cdn.jsdelivr.net/**signalr*", (r) => + r.fulfill({ + contentType: "application/javascript", + body: fs.readFileSync( + path.join( + __dirname, + "node_modules/@microsoft/signalr/dist/browser/signalr.min.js", + ), + ), + }), + ); + await c.route("**/native-companion/status", (r) => r.fulfill({ json: [] })); + await c.route("**/native-companion/connection-state", (r) => + r.fulfill({ json: { known: false } }), + ); + let removed = false, + notes = null, + fail = false, + viewer = false, + tabReads = [], + familyReads = 0; + for (const [endpoint, fixture] of [ + ["Tab", "tab"], + ["Family", "family"], + ["Operation", "operation"], + ]) + await c.route("**/Characters/Workspace/" + endpoint + "/*", async (r) => { + const u = new URL(r.request().url()); + if (endpoint === "Operation" && r.request().method() === "POST") { + if (fail) { + fail = false; + await r.fulfill({ + response: await r.fetch({ + method: "GET", + url: + base + + "/character-workspace-operation-fixture?operation=definition&relationshipId=9&invalid=true¬es=" + + encodeURIComponent("Draft retained"), + }), + }); + return; + } + if (r.request().postData()?.includes("archive")) removed = true; + else notes = "Saved fixture definition"; + await r.fulfill({ + json: { + saved: true, + message: removed + ? "Relationship archived; history retained." + : "Relationship saved.", + }, + }); + return; + } + if (endpoint === "Tab") { + tabReads.push(u.searchParams.get("Tab")); + u.searchParams.set("id", u.pathname.split("/").at(-1)); + } + if (endpoint === "Family") familyReads++; + u.searchParams.set("viewer", String(viewer)); + u.searchParams.set("removed", String(removed)); + if (notes) u.searchParams.set("notes", notes); + await r.fulfill({ + response: await r.fetch({ + url: + base + "/character-workspace-" + fixture + "-fixture" + u.search, + }), + }); + }); + await c.route("**/Characters/Workspace/Lookup/*", (r) => + r.fulfill({ json: [{ id: 6, name: "Another established character" }] }), + ); + await c.route("**/Characters/Workspace/Story/*", (r) => + r.fulfill({ + json: { + lens: "story", + focusID: 5, + povID: null, + sceneID: 22, + canEdit: !viewer, + truncated: false, + nodes: [ + { id: 5, name: "Current character" }, + { id: 7, name: "Recorded colleague" }, + ], + links: [ + { + id: 12, + a: 5, + b: 7, + type: "Friend", + category: "Friendship", + state: "Earlier recorded state", + reciprocal: false, + initial: true, + recent: [], + }, + ], + }, + }), + ); + await c.route("**/Characters/Details/*", async (r) => { + const u = new URL(r.request().url()); + u.searchParams.set("id", u.pathname.split("/").at(-1)); + await r.fulfill({ + response: await r.fetch({ + url: base + "/character-workspace-fixture" + u.search, + }), + }); + }); + const p = await c.newPage(), + errors = []; + await p.addLocatorHandler( + p.locator("[data-desktop-continue]"), + async (locator) => locator.click(), + ); + let native = 0, + si = 0; + p.on("pageerror", (e) => errors.push(e.message)); + p.on("request", (r) => { + if (r.url().includes("/hubs/native-companion/negotiate")) native++; + if (r.url().includes("/hubs/story-intelligence/negotiate")) si++; + }); + await p.goto(base + "/character-workspace-fixture"); + await p.waitForSelector('[data-character-tab-content="overview"]'); + + assert.equal( + await p.locator('script[src*="/relationship-main"]').count(), + 0, + "protected view must not load main enhancement code", + ); + const output = process.env.PD_CAPTURE_OUTPUT; + fs.mkdirSync(output, { recursive: true }); + await p.evaluate(() => { + document.documentElement.dataset.appTheme = "modern-light"; + document.documentElement.dataset.bsTheme = "light"; + }); + await p.click('[data-character-tab="relationships"]'); + await p.waitForSelector('[data-character-node="5"]'); + await p.evaluate(() => document.fonts.ready); + await p.waitForTimeout(300); + await p + .locator('[data-character-tab-content="relationships"]') + .screenshot({ + path: output + "/character-relationships.png", + animations: "disabled", + }); + fs.writeFileSync( + output + "/character-relationships.svg", + await p + .locator( + '[data-character-tab-content="relationships"] [data-character-graph] svg', + ) + .evaluate((n) => n.outerHTML), + ); + console.log("PASS captured protected Character relationships baseline"); + } catch (e) { + console.error(e.name + ": " + e.message.split("Call log:")[0]); + process.exitCode = 1; + } finally { + await b.close(); + } +})(); diff --git a/PlotLine.Tests/Browser/relationship-protected-context-capture.cjs b/PlotLine.Tests/Browser/relationship-protected-context-capture.cjs new file mode 100644 index 00000000..7309f04f --- /dev/null +++ b/PlotLine.Tests/Browser/relationship-protected-context-capture.cjs @@ -0,0 +1,150 @@ +// Controlled synthetic capture matching the pre-change baseline; no author data. +const { chromium } = require("playwright"), + assert = require("node:assert/strict"), + fs = require("node:fs"), + path = require("node:path"); +const base = process.env.PD_BROWSER_BASE || "http://127.0.0.1:5238"; +(async () => { + const b = await chromium.launch(); + let step = "setup"; + try { + const c = await b.newContext({ viewport: { width: 1366, height: 900 } }); + await c.route("**/cdn.jsdelivr.net/**signalr*", (r) => + r.fulfill({ + contentType: "application/javascript", + body: fs.readFileSync( + path.join( + __dirname, + "node_modules/@microsoft/signalr/dist/browser/signalr.min.js", + ), + ), + }), + ); + for (const url of [ + "**/native-companion/status", + "**/native-companion/connection-state", + "**/Writing/Context/Position?*", + ]) + await c.route(url, (r) => + r.fulfill({ + json: url.endsWith("status") + ? [] + : { known: false, connected: false }, + }), + ); + await c.route("**/Writing/Context/Tabs/*", async (r) => { + const u = new URL(r.request().url()); + await r.fulfill({ + response: await r.fetch({ + url: + base + + "/context-tab-fixture/" + + u.pathname.split("/").at(-1) + + u.search, + }), + }); + }); + let graphReads = 0, + large = false, + readOnly = false, + editQuery; + await c.route("**/Writing/Context/Relationships/Graph?*", async (r) => { + graphReads++; + const u = new URL(r.request().url()); + await r.fulfill({ + response: await r.fetch({ + url: + base + + "/context-lenses-fixture" + + u.search + + "&large=" + + large + + "&readonly=" + + readOnly, + }), + }); + }); + await c.route("**/Writing/Context/Relationships/Lookup?*", async (r) => + r.fulfill({ + response: await r.fetch({ + url: base + "/context-lenses-lookup-fixture", + }), + }), + ); + await c.route("**/Writing/Context/EditRelationship?*", async (r) => { + editQuery = new URL(r.request().url()).searchParams; + await r.fulfill({ + response: await r.fetch({ + url: base + "/context-relationship-edit-fixture", + }), + }); + }); + for (const [route, fixture] of [ + ["FamilyIndex", "index"], + ["FamilyTree", "tree"], + ]) + await c.route( + "**/Writing/Context/Relationships/" + route + "?*", + async (r) => { + const u = new URL(r.request().url()); + graphReads++; + await r.fulfill({ + response: await r.fetch({ + url: + base + + "/context-family-" + + fixture + + "-fixture" + + u.search + + "&large=" + + large + + "&readonly=" + + readOnly, + }), + }); + }, + ); + const p = await c.newPage(), + errors = []; + p.on("pageerror", (e) => errors.push(e.message)); + await p.goto(base + "/Writing/Context"); + await p.selectOption("[data-context-tab]", "relationships"); + await p.waitForSelector('[data-graph-node="5"]'); + + assert.equal( + await p.locator('script[src*="/relationship-main"]').count(), + 0, + "protected view must not load main enhancement code", + ); + const output = process.env.PD_CAPTURE_OUTPUT; + fs.mkdirSync(output, { recursive: true }); + await p.evaluate(() => { + document.documentElement.dataset.appTheme = "modern-light"; + document.documentElement.dataset.bsTheme = "light"; + }); + await p.evaluate(() => document.fonts.ready); + await p.waitForTimeout(300); + for (const lens of ["family", "story"]) { + await p.locator('[data-relationship-lens="' + lens + '"]').click(); + await p.waitForTimeout(300); + await p + .locator('[data-context-pane="0"]') + .screenshot({ + path: output + "/context-" + lens + ".png", + animations: "disabled", + }); + fs.writeFileSync( + output + "/context-" + lens + ".svg", + await p + .locator('[data-context-pane="0"] [data-relationship-svg]') + .evaluate((n) => n.outerHTML), + ); + } + console.log("PASS captured protected Context Family/Story baseline"); + } catch (e) { + console.error(e.name + ": " + e.message.split("Call log:")[0]); + process.exitCode = 1; + } finally { + await b.close(); + } +})(); diff --git a/PlotLine.Tests/Browser/relationship-workspace.cjs b/PlotLine.Tests/Browser/relationship-workspace.cjs index 6f36411c..af24f371 100644 --- a/PlotLine.Tests/Browser/relationship-workspace.cjs +++ b/PlotLine.Tests/Browser/relationship-workspace.cjs @@ -17,7 +17,7 @@ const base = 'http://127.0.0.1:5238'; }); await page.route('**/RelationshipMap/Save', async route => { posted = route.request().postData(); await route.fulfill({ status: 200 }); }); assert.equal((await page.goto(base + '/fixture?page=relationships')).status(), 200); - await page.waitForFunction(() => !!window.PlotDirectorRelationshipWorkspace); + await page.waitForFunction(() => !!window.PlotDirectorRelationshipWorkspace?.mainCommands?.initialised && !window.PlotDirectorRelationshipWorkspace.mainCommands.arranging && !window.PlotDirectorRelationshipWorkspace.mainCommands.routing); state = await page.evaluate(() => { const w = window.PlotDirectorRelationshipWorkspace; return { cast: w.cast, relationships: w.relationships(), links: w.cy.edges().map(e => ({ characterRelationshipID: e.data('relationshipID'), sourceCharacterID: Number(e.data('source').slice(2)), targetCharacterID: Number(e.data('target').slice(2)), relationshipLabel: e.data('label'), cssClass: e.classes().join(' '), intensity: e.data('intensity') })) }; @@ -79,6 +79,7 @@ const base = 'http://127.0.0.1:5238'; await drag(75, null); assert.equal(await page.locator('#rwDialog').evaluate(e => e.open), false, 'blank drop does not create relationship'); assert(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.$id('c-75').visible())); + await page.locator('[data-rw-character="1"]').click(); await drag(1, 2, true); await page.locator('#rwDialog[open]').waitFor(); assert.equal(await page.locator('[name="SourceID"]').inputValue(), '1', 'map connector supplies source'); @@ -96,7 +97,7 @@ const base = 'http://127.0.0.1:5238'; assert.equal(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.zoom()), zoom, 'save preserves zoom'); assert(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.$id('c-1').hasClass('is-focus')), 'save preserves focus'); await page.locator('#rwTimeline').fill('100'); - await page.waitForFunction(() => document.getElementById('rwStatus').textContent.includes('relationships.')); + await page.waitForFunction(() => window.PlotDirectorRelationshipWorkspace.relationships().some(r=>r.currentStateName==='Distrustful')); await page.waitForTimeout(250); await page.locator('#rwListView').click(); assert(await page.locator('#rwListPanel').isVisible(), 'List replaces the canvas rather than extending the page'); @@ -111,7 +112,7 @@ const base = 'http://127.0.0.1:5238'; assert.equal(await page.locator('#rwTimeline').inputValue(), '100'); await page.evaluate(() => { window.PlotDirectorRelationshipWorkspace.cy.zoom(.7); window.PlotDirectorRelationshipWorkspace.cy.pan({x:50,y:70}); }); await page.waitForTimeout(350); - await page.reload(); await page.waitForFunction(() => !!window.PlotDirectorRelationshipWorkspace); + await page.reload(); await page.waitForFunction(() => !!window.PlotDirectorRelationshipWorkspace?.mainCommands?.initialised && !window.PlotDirectorRelationshipWorkspace.mainCommands.arranging && !window.PlotDirectorRelationshipWorkspace.mainCommands.routing); assert(Math.abs(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.zoom()) - .7) < .01, 'layout restores zoom'); assert.deepEqual(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.pan()), {x:50,y:70}, 'layout restores manual pan'); for (const width of [1600, 1200, 700, 390]) { @@ -151,7 +152,7 @@ const base = 'http://127.0.0.1:5238'; await page.keyboard.press('Escape'); assert.equal(await page.locator('#rwMaximise').getAttribute('aria-pressed'), 'false'); await page.locator('#rwClearFocus').click(); - assert.equal(await page.locator('#rwFocusName').innerText(), 'Full cast'); + assert.equal(await page.locator('#rwFocusName').innerText(), 'Custom diagram'); await page.locator('#rwPan').click(); assert(await page.evaluate(()=>window.PlotDirectorRelationshipWorkspace.cy.autoungrabify())); await page.locator('#rwSelect').click(); assert(!(await page.evaluate(()=>window.PlotDirectorRelationshipWorkspace.cy.autoungrabify()))); assert.equal(await page.locator('.list-section').count(), 0, 'no relationship list below workspace'); @@ -160,17 +161,17 @@ const base = 'http://127.0.0.1:5238'; await pwa.addInitScript(() => Object.defineProperty(navigator, 'standalone', { value: true })); const app = await pwa.newPage(); app.on('pageerror', e => errors.push(e.message)); await app.goto(base + '/fixture?page=relationships'); - await app.waitForFunction(() => !!window.PlotDirectorRelationshipWorkspace); + await app.waitForFunction(() => !!window.PlotDirectorRelationshipWorkspace?.mainCommands?.initialised && !window.PlotDirectorRelationshipWorkspace.mainCommands.arranging && !window.PlotDirectorRelationshipWorkspace.mainCommands.routing); await app.locator('[data-rw-character="1"]').evaluate(e => e.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX:100,clientY:200 }))); await app.locator('.pd-context-popup').waitFor(); assert.match(await app.locator('.pd-context-popup').innerText(), /Focus|relationship|Edit character/); await app.keyboard.press('Escape'); - await app.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.$id('r-1').emit('cxttap')); + await app.evaluate(() => {getSelection().removeAllRanges();const g=document.getElementById('relationshipMapGraph'),b=g.getBoundingClientRect(),p=window.PlotDirectorRelationshipWorkspace.cy.$id('r-1').renderedMidpoint();g.dispatchEvent(new MouseEvent('contextmenu',{bubbles:true,cancelable:true,clientX:b.x+p.x,clientY:b.y+p.y}));}); await app.locator('.pd-context-popup').waitFor(); - assert.match(await app.locator('.pd-context-popup').innerText(), /Edit at timeline point/, 'line actions use application menu'); + assert.match(await app.locator('.pd-context-popup').innerText(), /Edit relationship/, 'line actions use application menu'); await app.keyboard.press('Escape'); assert(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.$id('r-1').hasClass('relationship-category-friendship')), 'existing line category retained'); - await app.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.$id('c-18').emit('cxttap')); + await app.evaluate(() => {const cy=window.PlotDirectorRelationshipWorkspace.cy,g=document.getElementById('relationshipMapGraph');cy.center(cy.$id('c-18'));const b=g.getBoundingClientRect(),p=cy.$id('c-18').renderedPosition();g.dispatchEvent(new MouseEvent('contextmenu',{bubbles:true,cancelable:true,clientX:b.x+p.x,clientY:b.y+p.y}));}); await app.locator('.pd-context-popup').waitFor(); assert.match(await app.locator('.pd-context-popup').innerText(), /Edit character|Add relationship/, 'map context actions remain available after focusing'); await app.keyboard.press('Escape'); diff --git a/PlotLine.Tests/Browser/relationships-ribbon.cjs b/PlotLine.Tests/Browser/relationships-ribbon.cjs index 8b0c3806..1eed96b0 100644 --- a/PlotLine.Tests/Browser/relationships-ribbon.cjs +++ b/PlotLine.Tests/Browser/relationships-ribbon.cjs @@ -6,24 +6,24 @@ const base='http://127.0.0.1:5238'; try { const context=await browser.newContext({viewport:{width:1700,height:1000}}); const web=await context.newPage();web.on('pageerror',e=>errors.push(e.message)); - await web.goto(base+'/fixture?page=relationships');await web.waitForFunction(()=>!!window.PlotDirectorRelationshipWorkspace); + await web.goto(base+'/fixture?page=relationships');await web.waitForFunction(()=>!!window.PlotDirectorRelationshipWorkspace?.mainCommands?.initialised && !window.PlotDirectorRelationshipWorkspace.mainCommands.arranging && !window.PlotDirectorRelationshipWorkspace.mainCommands.routing); assert(await web.locator('.rw-toolbar').isVisible(),'browser toolbar remains'); const webRow=await web.locator('#rwApp').evaluate(e=>getComputedStyle(e).gridTemplateRows.split(' ')[0]);assert.equal(webRow,'44px'); const appContext=await browser.newContext({viewport:{width:1700,height:1000}}); await appContext.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true})); const app=await appContext.newPage();app.on('pageerror',e=>errors.push(e.message)); - await app.goto(base+'/fixture?page=relationships');await app.waitForFunction(()=>!!window.PlotDirectorRelationshipWorkspace); + await app.goto(base+'/fixture?page=relationships');await app.waitForFunction(()=>!!window.PlotDirectorRelationshipWorkspace?.mainCommands?.initialised && !window.PlotDirectorRelationshipWorkspace.mainCommands.arranging && !window.PlotDirectorRelationshipWorkspace.mainCommands.routing); assert(await app.locator('.rw-toolbar').isHidden(),'PWA has no second toolbar'); const shell=app.locator('[data-pwa-context-controls]'); async function command(name){ - const target=shell.getByRole('button',{name,exact:true,includeHidden:true});assert.equal(await target.count(),1,'single ribbon command '+name); + const target=name==='Clear focus'?shell.locator('[data-command-identity="handler:rwClearFocus"]'):shell.getByRole('button',{name,exact:true,includeHidden:true});assert.equal(await target.count(),1,'single ribbon command '+name); const menu=target.locator('xpath=ancestor::details[@data-compact="true"]').last(); if(await menu.count() && !(await menu.evaluate(e=>e.open))) await menu.locator(':scope > summary').click(); await target.waitFor({state:'visible'}); return target; } - for(const name of ['Map','List','Full cast','Details','Add relationship','Auto-arrange','Remove focused from map','Reset layout','Characters','Maximise workspace']) await command(name); - for(const name of ['View','Focus','Relationship','Arrange','Layout','Display']) assert(await shell.locator(`.pd-context-group[aria-label="${name}"]`).count(),name+' group'); + for(const name of ['Map','List','Connected characters','Details','Add relationship','Auto-arrange','Remove focused from map','Reset layout','Characters','Maximise workspace']) await command(name); + for(const name of ['View','Diagram focus','Relationship','Arrange','Layout','Display']) assert(await shell.locator(`.pd-context-group[aria-label="${name}"]`).count(),name+' group'); assert(await shell.locator('[data-help-open]').count(),'Help uses ribbon help'); assert.equal(await shell.locator('.relationship-map-legend-grid').count(),0,'legend removed from ribbon'); assert(await app.locator('.rw-rail .rw-colour-key').isVisible(),'colour key at bottom of right panel'); @@ -41,7 +41,7 @@ const base='http://127.0.0.1:5238'; for (const id of ['bookId','chapterId','sceneId']) assert(await web.locator('#'+id).isVisible(),'browser dropdown '+id); assert(await web.locator('.rw-display > .rw-menu-panel').evaluate(e=>e.scrollHeight<=e.clientHeight+1),'browser Display does not scroll'); const iconPaths=await shell.locator('button.pd-context-command').evaluateAll(nodes=>nodes.map(n=>n.querySelector('svg path')?.getAttribute('d'))); - assert(iconPaths.every(Boolean),'every command has a relevant icon'); assert.equal(new Set(iconPaths).size,iconPaths.length,'command icons are distinct'); + assert(iconPaths.every(Boolean),'every command has a relevant icon'); assert(new Set(iconPaths).size>=iconPaths.length-1,'commands retain distinct existing icons; related clear/remove diagram commands share the existing hide-node glyph'); if (!(await display.locator('..').evaluate(e=>e.open))) await display.locator('..').locator(':scope > summary').click(); assert(await display.evaluate(e=>e.scrollHeight<=e.clientHeight+1 && e.scrollWidth<=e.clientWidth+1),'Display has no scrolling'); assert(await (await command('Update Map')).isVisible()); assert(await (await command('Maximise workspace')).isVisible()); @@ -52,12 +52,12 @@ const base='http://127.0.0.1:5238'; await app.locator('[data-rw-character="1"]').click(); await app.waitForFunction(()=>[...document.querySelectorAll('[data-pwa-context-controls] button')].some(b=>b.textContent.includes('Focus: Élan Vale'))); assert.equal(await (await command('Focus: Élan Vale')).count(),1); - await (await command('Clear focus')).click();await app.waitForFunction(()=>document.getElementById('rwFocusName').textContent==='Full cast'); - assert.equal(await (await command('Full cast')).count(),1); + await (await command('Clear focus')).click();await app.waitForFunction(()=>document.getElementById('rwFocusName').textContent==='Connected characters'); + assert.equal(await (await command('Connected characters')).count(),1); await (await command('Details')).click();assert(await app.locator('#rwDetailPanel').isVisible()); await (await command('Add relationship')).click();assert(await app.locator('#rwDialog').evaluate(e=>e.open));await app.keyboard.press('Escape'); - await app.evaluate(()=>{window.__layouts=0;window.PlotDirectorRelationshipWorkspace.cy.on('layoutstop',()=>window.__layouts++);}); - await (await command('Auto-arrange')).click();assert(await app.evaluate(()=>window.__layouts>0),'original auto-arrange handler'); + await app.evaluate(()=>{window.__layoutSequence=window.PlotDirectorRelationshipWorkspace.lastLayout.sequence;}); + await (await command('Auto-arrange')).click();await app.waitForFunction(()=>window.PlotDirectorRelationshipWorkspace.lastLayout.sequence>window.__layoutSequence&&!window.PlotDirectorRelationshipWorkspace.mainCommands.busy);assert(await app.evaluate(()=>window.PlotDirectorRelationshipWorkspace.lastLayout.kind==='clusters'),'canonical Auto-arrange command invokes selected main layout'); await (await command('Characters')).click();assert(await app.locator('#rwBoard').evaluate(e=>e.classList.contains('palettes-hidden')));assert(await app.locator('#rwDetailPanel').isVisible(),'Details remains when palettes collapse');await (await command('Characters')).click(); const maximise=await command('Maximise workspace'); assert.equal(await maximise.locator('xpath=ancestor::details[@data-compact="true"]').count(),0,'Maximise is directly on ribbon, not in a dropdown'); diff --git a/PlotLine.Tests/Browser/workspace-panels.cjs b/PlotLine.Tests/Browser/workspace-panels.cjs index 7439af46..5e2b21f4 100644 --- a/PlotLine.Tests/Browser/workspace-panels.cjs +++ b/PlotLine.Tests/Browser/workspace-panels.cjs @@ -30,7 +30,7 @@ const assert = require('node:assert/strict'); assert.ok(await r.evaluate(node=>node.getBoundingClientRect().width)>rightBefore+25,name+' pointer right resize'); assert.equal(await page.evaluate(()=>document.documentElement.classList.contains('pd-panel-resizing')),false); assert.equal(await page.evaluate(()=>getSelection().toString()),''); - const saved=await page.evaluate(name=>JSON.parse(localStorage.getItem(`plotdirector.workspace.panels.${name}`)),name); + const saved=await page.evaluate(name=>JSON.parse(localStorage.getItem(`plotdirector.workspace.panels.${name}${name==='relationships'?'.'+document.getElementById('rwApp').dataset.workspacePreferenceScope:''}`)),name); assert.ok(saved.left && saved.right); assert.equal(await page.evaluate(() => window.canvasPointerEvents), 0, 'Divider must not begin canvas dragging'); if (mapBefore) assert.equal(await page.evaluate(() => JSON.stringify(window.PlotDirectorMapWorkspace.document)), mapBefore, 'Panel resize preserves map objects'); diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index f0622c33..52fb2e29 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -17,6 +17,7 @@ using PlotLine.ViewModels; if(args.Contains("--shared-focus-concurrent")){await SharedFocusDatabaseTests.Concurrent();return;} if(args.Contains("--shared-focus-cleanup")){await SharedFocusDatabaseTests.Concurrent(true);return;} +if(args.Contains("--relationship-workspace")){RelationshipWorkspaceTests.StateAndEditing();Console.WriteLine("PASS main Relationships canonical editing, historical resolution and isolated author-family access");return;} if(args.Contains("--shared-focus-browser-host")){await SharedFocusBrowserHost.Run();return;} if(args.Contains("--shared-focus-database")){await SharedFocusDatabaseTests.Run(args.Last());return;} if(args.Contains("--shared-focus-browser-setup")){await SharedFocusDatabaseTests.Run(args.Last(),true);return;} diff --git a/PlotLine.Tests/RelationshipWorkspaceTests.cs b/PlotLine.Tests/RelationshipWorkspaceTests.cs index e7cadb5f..0992bb4d 100644 --- a/PlotLine.Tests/RelationshipWorkspaceTests.cs +++ b/PlotLine.Tests/RelationshipWorkspaceTests.cs @@ -20,7 +20,7 @@ internal static class RelationshipWorkspaceTests }; public static CharacterLookupData Lookups() => new() { - RelationshipTypes = [new() { RelationshipTypeID = 1, TypeName = "Friend", IsActive = true }], + RelationshipTypes = [new() { RelationshipTypeID = 1, TypeName = "Friend", IsActive = true },new(){RelationshipTypeID=2,TypeName="Parent",IsActive=true},new(){RelationshipTypeID=3,TypeName="Adoptive Parent",IsActive=true},new(){RelationshipTypeID=4,TypeName="Spouse",IsActive=true}], RelationshipStates = [new() { RelationshipStateID = 1, StateName = "Friendly", IsActive = true }, new() { RelationshipStateID = 2, StateName = "Distrustful", IsActive = true }] }; public static ICharacterRepository Repository(RelationshipMapData data) => Stub