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: "Canonical character route fixture

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((m, _) => m switch @@ -35,14 +35,14 @@ internal static class RelationshipWorkspaceTests "GetAsync" => Task.FromResult(new() { ProjectID = 7, ProjectName = "Cast fixture" }), _ => throw new Exception(m) }), Repository(data)); - public static async Task LargeFixture(int count,string network) + public static async Task LargeFixture(int count,string network,int? sceneId=null) { var original=Data(); var cast=Enumerable.Range(1,count).Select(i=>new Character{CharacterID=i,ProjectID=7,CharacterName=$"Person {i:000}",CharacterImportance=i%4==0?10:i%4==1?6:i%4==2?2:null}).ToList(); var pairs=new List<(int A,int B,string Type,string Category)>(); - if(network=="family") { for(var i=2;i<=count;i++)pairs.Add((Math.Max(1,i/2),i,i%7==0?"Adoptive Parent":"Parent","Family")); } + if(network=="family") { for(var i=3;i<=count;i++){if(i is 5 or 20 or 21 or 22)continue;pairs.Add((i<=4?1:Math.Max(1,i/2),i,i%7==0?"Adoptive Parent":"Parent","Family"));}if(count>=2)pairs.Add((1,2,"Spouse","Romantic / Sexual"));if(count>=3)pairs.Add((2,3,"Parent","Family"));if(count>=4)pairs.Add((2,4,"Parent","Family"));if(count>=5)pairs.Add((3,5,"Spouse","Romantic / Sexual"));if(count>=6)pairs.Add((5,6,"Parent","Family"));if(count>=22){pairs.Add((20,21,"Spouse","Romantic / Sexual"));pairs.Add((20,22,"Parent","Family"));pairs.Add((21,22,"Parent","Family"));} } else if(network!="isolated") { for(var i=1;i<=count;i++)for(var step=1;step<=(network=="dense"?6:network=="clusters"?3:1);step++){var target=i+step;if(target<=count&&(network!="clusters"||i/12==target/12||i%12==0&&step==1)&&(network!="sparse"||i%4==0))pairs.Add((i,target,"Friend","Friendship"));} } - var relationships=pairs.Select((p,i)=>new CharacterRelationship{CharacterRelationshipID=i+1,ProjectID=7,CharacterAID=p.A,CharacterBID=p.B,CharacterAName=$"Person {p.A:000}",CharacterBName=$"Person {p.B:000}",RelationshipTypeID=1,RelationshipTypeName=p.Type,RelationshipCategoryName=p.Category,IsInitialRelationship=true,InitialRelationshipStateID=1,InitialRelationshipStateName="Established",IsReciprocal=p.Category!="Family"}).ToList();var data=new RelationshipMapData{Books=original.Books,Chapters=original.Chapters,Scenes=original.Scenes,Characters=cast,Relationships=relationships,RelationshipCategories=original.RelationshipCategories,RelationshipEvents=[]}; - return (await Service(data).GetAsync(7,null,null,null,null,true))!; + var relationships=pairs.Select((p,i)=>new CharacterRelationship{CharacterRelationshipID=i+1,ProjectID=7,CharacterAID=p.A,CharacterBID=p.B,CharacterAName=$"Person {p.A:000}",CharacterBName=$"Person {p.B:000}",RelationshipTypeID=p.Type=="Parent"?2:p.Type=="Adoptive Parent"?3:p.Type=="Spouse"?4:1,RelationshipTypeName=p.Type,RelationshipCategoryName=p.Category,IsInitialRelationship=true,InitialRelationshipStateID=1,InitialRelationshipStateName="Established",IsReciprocal=p.Type=="Spouse"||p.Category!="Family"}).ToList();var data=new RelationshipMapData{Books=original.Books,Chapters=original.Chapters,Scenes=original.Scenes,Characters=cast,Relationships=relationships,RelationshipCategories=network=="family"?[new(){RelationshipCategoryID=2,CategoryName="Family"},new(){RelationshipCategoryID=3,CategoryName="Romantic / Sexual"}]:original.RelationshipCategories,RelationshipEvents=relationships.Count>0?[new(){RelationshipEventID=91,CharacterRelationshipID=1,SceneID=100,RelationshipStateID=2,RelationshipStateName="Distrustful"},new(){RelationshipEventID=92,CharacterRelationshipID=1,SceneID=200,RelationshipStateID=1,RelationshipStateName="Established"}]:[]}; + return (await Service(data).GetAsync(7,null,null,sceneId,null,true))!; } public static async Task Fixture() => (await Service(Data()).GetAsync(7, null, null, null, null, true))!; public static void StateAndEditing() => Run().GetAwaiter().GetResult(); @@ -68,9 +68,10 @@ internal static class RelationshipWorkspaceTests Check(focused.Relationships.Count == 1 && focused.Nodes.Single(x => x.IsFocus).CharacterID == 2, "existing Focus Mode"); var saves = new List(); var characters = Stub((m,a) => { saves.Add(a![0]!); return m switch { "SaveInitialRelationshipAsync" or "UpdateRelationshipEventAsync" or "AddRelationshipEventAsync" => Task.FromResult(1), _ => throw new Exception(m) }; }); - var controller = new RelationshipMapController(service, Repository(data), characters); + var hints=0;var client=NativeWorkflowTests.Proxy((_,_)=>{hints++;return Task.CompletedTask;});var clients=NativeWorkflowTests.Proxy((_,_)=>client);var hub=NativeWorkflowTests.Proxy>((_,_)=>clients);var notifications=new ContextWorkspaceNotifications(hub,Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + var controller = new RelationshipMapController(service, Repository(data), characters, Stub((m,_)=>Task.FromResult(new(){ProjectID=7})), Stub((m,_)=>23),notifications); var edit = new WorkspaceRelationshipEdit { ProjectID = 7, SourceID = 2, TargetID = 1, TypeID = 1, StateID = 2, Mutual = true }; - Check(await controller.Save(edit) is OkResult, "initial edit"); + Check(await controller.Save(edit) is OkResult&&hints==1, "initial edit publishes one existing-channel data invalidation"); Check(((InitialRelationshipEditViewModel)saves.Single()).CharacterRelationshipID == 1, "reverse reciprocal pair reuses canonical record"); saves.Clear(); edit.SceneID = 100; Check(await controller.Save(edit) is OkResult, "scene edit"); @@ -90,6 +91,16 @@ internal static class RelationshipWorkspaceTests Check(await controller.Save(edit) is BadRequestObjectResult, "reject self relationships"); edit.SourceID = 2; edit.TargetID = 1; edit.SceneID = 999; Check(await controller.Save(edit) is BadRequestObjectResult, "reject foreign scene"); + var familyData=new RelationshipMapData{Characters=data.Characters,Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes,RelationshipCategories=data.RelationshipCategories,Relationships=[new(){CharacterRelationshipID=900,ProjectID=7,CharacterAID=1,CharacterBID=2,RelationshipCategoryName="Family",RelationshipTypeName="Parent",StartSceneID=250},new(){CharacterRelationshipID=901,ProjectID=7,CharacterAID=1,CharacterBID=3,RelationshipCategoryName="Friendship",RelationshipTypeName="Friend",IsInitialRelationship=true}]}; + var access=Stub((m,args)=>Task.FromResult((int)args![0]! ==7?new(){ProjectID=7}:null)); + var familyController=new RelationshipMapController(Service(familyData),Repository(familyData),characters,access,Stub((m,_)=>23),notifications); + var authorFamily=System.Text.Json.JsonSerializer.Serialize(((JsonResult)await familyController.Family(7)).Value); + Check(authorFamily.Contains("Parent")&&!authorFamily.Contains("Friend"),"main author family uses canonical family truth without story/POV reinterpretation"); + Check(!(await Service(familyData).GetAsync(7,null,null,1,null,true))!.Relationships.Any(r=>r.CharacterRelationshipID==900),"author-family read does not change historical Story resolution"); + Check(await familyController.Family(8) is NotFoundResult,"main family read rejects an unauthorised project"); + var anonymous=new RelationshipMapController(Service(familyData),Repository(familyData),characters,access,Stub((m,_)=>null),notifications); + Check(await anonymous.Family(7) is UnauthorizedResult,"main family read requires the authenticated author"); + } private static void Check(bool condition, string message) { if (!condition) throw new Exception(message); } private static T Stub(Func invoke) where T : class diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 3b9933cf..acd797b4 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -268,6 +268,8 @@ internal static class ToolbarBrowserHost await context.RequestServices.GetRequiredService().Open(context.RequestServices.GetRequiredService().UserId!.Value,null,id); await RenderFullAsync(context,"Scenes","Edit",model); }).WithOrder(-1); + app.MapGet("/relationship-main-state-fixture",async (HttpContext context)=>await context.Response.WriteAsJsonAsync(await RelationshipWorkspaceTests.LargeFixture(int.TryParse(context.Request.Query["cast"],out var n)?Math.Clamp(n,1,200):75,context.Request.Query["network"].ToString(),int.TryParse(context.Request.Query["sceneId"],out var scene)?scene:null))); + app.MapGet("/relationship-main-family-fixture",async (HttpContext context)=>{var model=await RelationshipWorkspaceTests.LargeFixture(int.TryParse(context.Request.Query["cast"],out var n)?Math.Clamp(n,1,200):75,"family");await context.Response.WriteAsJsonAsync(new{canEdit=true,relationships=model.Relationships,nodes=model.Cast.Select(c=>new{id=c.CharacterID,name=c.CharacterName,birthDate=(string?)null})});}); app.MapGet("/character-attribute-definitions-fixture",()=>Results.Json(CharacterQuickAttributes.Definitions([new(){CharacterSexValueID=1,SexName="Male",IsSystem=true},new(){CharacterSexValueID=2,SexName="Female",IsSystem=true},new(){CharacterSexValueID=3,SexName="Custom recorded sex"}]).Select(g=>new{g.Id,g.Label,values=g.Values.Select(CharacterQuickAttributes.Presentation),fallback=g.RecordedFallback is {} fallback?CharacterQuickAttributes.Presentation(fallback):null}))); app.MapGet("/character-attributes-fixture",async (HttpContext context)=>{ var count=int.TryParse(context.Request.Query["count"],out var n)?Math.Clamp(n,1,500):10; diff --git a/PlotLine/Controllers/RelationshipMapController.cs b/PlotLine/Controllers/RelationshipMapController.cs index 6910a3fd..59f41b8e 100644 --- a/PlotLine/Controllers/RelationshipMapController.cs +++ b/PlotLine/Controllers/RelationshipMapController.cs @@ -8,7 +8,7 @@ using PlotLine.ViewModels; namespace PlotLine.Controllers; [Authorize] -public sealed class RelationshipMapController(IRelationshipMapService relationshipMap, ICharacterRepository repository, ICharacterService characters) : Controller +public sealed class RelationshipMapController(IRelationshipMapService relationshipMap, ICharacterRepository repository, ICharacterService characters, IProjectRepository projectAccess, ICurrentUserService user, ContextWorkspaceNotifications notifications) : Controller { public async Task Index(int projectId, int? bookId, int? chapterId, int? sceneId, int? focusCharacterId, bool showFullNetwork = false) { @@ -30,6 +30,51 @@ public sealed class RelationshipMapController(IRelationshipMapService relationsh return model is null ? NotFound() : Json(model); } + // Main workspace author-reference facts, independent of manuscript scene/POV visibility. + [HttpGet] + public async Task Family(int projectId) + { + if (user.UserId is not int author) return Unauthorized(); + var project = await projectAccess.GetForUserAsync(projectId, author); + if (project is null) return NotFound(); + var data = await repository.GetRelationshipMapAsync(projectId); + var people = data.Characters.Where(c => !c.IsArchived).ToDictionary(c => c.CharacterID); + var sceneOrder = StoryStateService.OrderScenes(new TimelineData + { Books = data.Books, Chapters = data.Chapters, Scenes = data.Scenes }) + .Select((scene, index) => (scene.SceneID, index)).ToDictionary(s => s.SceneID, s => s.index); + var history = data.RelationshipEvents.ToLookup(e => e.CharacterRelationshipID); + var relationships = data.Relationships.Where(r => !r.IsArchived + && people.ContainsKey(r.CharacterAID) && people.ContainsKey(r.CharacterBID) + && PlotLine.Services.Context.ContextRelationshipLenses.Family(r.RelationshipCategoryName, r.RelationshipTypeName)) + .Select(r => new RelationshipMapRelationshipViewModel + { + CharacterRelationshipID = r.CharacterRelationshipID, + CharacterAID = r.CharacterAID, CharacterBID = r.CharacterBID, + CharacterAName = people[r.CharacterAID].CharacterName, CharacterBName = people[r.CharacterBID].CharacterName, + RelationshipTypeName = r.RelationshipTypeName, RelationshipCategoryName = r.RelationshipCategoryName, + CssClass = r.RelationshipCategoryName == "Family" ? "relationship-category-family" : "relationship-category-romantic", + InitialStateEditable = r.IsInitialRelationship, + InitialStateName = r.InitialRelationshipStateName ?? r.RelationshipTypeName, + CurrentStateName = r.InitialRelationshipStateName ?? r.RelationshipTypeName, + InitialIntensity = r.InitialIntensity, CurrentIntensity = r.InitialIntensity, + IsReciprocal = r.IsReciprocal, Known = r.ReaderInitiallyKnows, Notes = r.Notes, + History = history[r.CharacterRelationshipID] + .OrderBy(e => sceneOrder.GetValueOrDefault(e.SceneID, int.MaxValue)) + .ThenBy(e => e.CreatedDate).ThenBy(e => e.RelationshipEventID) + .Select(e => new RelationshipMapHistoryItemViewModel + { + SceneID = e.SceneID, + Label = $"{e.BookDisplayTitle} · Ch {e.ChapterNumber} · Scene {e.SceneNumber}: {e.SceneTitle}", + StateName = e.RelationshipStateName, Intensity = e.Intensity, Notes = e.Description + }).ToArray() + }).ToArray(); + return Json(new + { + canEdit = PlotLine.Services.Context.ContextEditPolicy.CanEdit(project), relationships, + nodes = people.Values.Select(c => new { id = c.CharacterID, name = c.CharacterName, birthDate = c.BirthDate }) + }); + } + [HttpPost] [ValidateAntiForgeryToken] public async Task Save(WorkspaceRelationshipEdit model) @@ -75,6 +120,7 @@ public sealed class RelationshipMapController(IRelationshipMapService relationsh InitialIntensity = model.Intensity, IsReciprocal = model.Mutual, ReaderInitiallyKnows = model.Known, Notes = model.Notes }); } + if (user.UserId is int author) await notifications.Invalidate(author, projectId: model.ProjectID, kind: "relationships"); return Ok(); } } diff --git a/PlotLine/Help/Articles/RelationshipMap/Overview.md b/PlotLine/Help/Articles/RelationshipMap/Overview.md index f59b029d..56cc0c2a 100644 --- a/PlotLine/Help/Articles/RelationshipMap/Overview.md +++ b/PlotLine/Help/Articles/RelationshipMap/Overview.md @@ -11,52 +11,40 @@ screenshot: # Overview -The Relationship Map visualises connections between characters. It gives a high-level view of social structure within the story. +The main Relationships workspace combines a diagram, the existing character groups, Details, a colour key and Scene Explorer. Context and individual Character Details keep their own relationship views and settings. -# When Should I Use This? +# Working with the diagram -Use it when you want to see family, friendship, romance, conflict, professional ties or other relationship patterns without reading every character profile. +Scroll the mouse wheel over the diagram to zoom around the pointer. Drag with the middle mouse button to pan. The existing Pan, Select, zoom, Fit and centre controls remain available; arrow keys pan and Home fits. Drag a character card to reposition it. Single-click selects without moving the view; double-click opens the existing Character Details page. Selecting a character in a palette explicitly centres it. -# How To Use It +Right-click a character, relationship or blank canvas for the relevant commands in browser or installed PWA mode. Keyboard users can focus the canvas and press Shift+F10 or the Context Menu key. The **Diagram menu** button opens canvas commands; selecting a character exposes **Character actions** in Details for keyboard and touch use. Ctrl+right-click retains the browser menu. Normal text selection and editing menus remain available elsewhere. -In the installed PWA, workspace commands appear in the existing ribbon: **View**, **Focus**, **Relationship**, **Arrange**, **Layout** and **Display**. The Focus command shows the current character and offers Clear focus. Layout and Display retain their existing options; narrower windows use the ribbon’s standard overflow menus. The browser version keeps its workspace toolbar. Both presentations control the same map, list, focus and maximise state. +# Membership, pins and Undo -The map has three independently scrolling character palettes: **Major** across the top, **all Supporting** characters down the left, and **Minor / unset** across the bottom. These use the existing importance classifications; this layout does not change stored importance. The right panel is dedicated to contextual Details. +**Remove from diagram** (or Delete while a character is selected on the canvas) hides only that character from this diagram. It does not archive or delete any character or relationship. Drag a palette character onto blank canvas to add them again; duplicates are prevented. **Clear diagram** makes a custom diagram empty and keeps it empty through scene changes and reloads until you add characters or choose a preset. -**Find character** searches the whole cast across all three palettes, ignoring case and accents. There is no importance filter to switch first. Select a matching character in their palette to focus and centre them on the map; their palette entry is also brought into view. **Layout → Characters** collapses the character palettes while keeping Details available. +Pin a character through its menu to keep its exact position during arrangements. Pins have a pin badge and double border. A family arrangement asks whether to keep pins, rearrange the family or cancel. Conflicting pinned positions can overlap: move or unpin them to resolve that conflict. **Undo layout change** (Ctrl+Z on the canvas) restores the previous membership, positions, pins and view. This is separate from Undo importance. -Click or tap a character to bring them to the centre and activate Focus Mode. With **Show full network** off, the map shows their immediate connections; with it on, unrelated connections are dimmed. The focus chip in the toolbar names the current character; click it or the canvas target control to centre them, or **×** to clear focus. +# Character importance -Drag a palette character onto blank canvas to position them without creating a relationship. The character remains in the palette. Drag onto another character to open the relationship editor. Dragging a map card moves it; the small arrow beside the focused map character starts a relationship instead. +The groups remain Major at the top, Supporting on the left and Minor along the bottom, with an Unclassified subgroup. Counts and icons reflect recorded importance. Drag a character between groups to save their canonical importance immediately, or use **Character actions → Story importance**. Empty groups remain drop targets. A same-group drop is a no-op. Successful changes offer **Undo importance**, which refuses to overwrite a newer change. Failed assignments retain the recorded grouping and show an error. Moving a diagram node never changes importance. -For keyboard and touch editing, choose **Add relationship**, then select source and target. The arrow beside any palette character also opens the editor with that source. The editor shows the chosen pair with their avatars; expand **Change characters** to edit either endpoint. Choose the existing relationship type, state, intensity and optional notes. Mutual status belongs to the initial relationship; scene changes use the existing mutual status. Review **Apply at** before saving. +# Layout and Display -**Initial** edits the starting relationship. A scene selection records a change at that scene. Saving reuses a matching relationship of the same type, and edits an existing event at that scene rather than adding another. Different relationship types may coexist between the same people. The focused character remains centred and zoom is retained after saving. +In the PWA, commands use the existing ribbon; the browser keeps the workspace toolbar. **Diagram focus** describes the selected character, separate from the global manuscript focus. Layout contains the arrangement, connection depth, pins, removal, clear and diagram Undo. Display contains presets, connector style and the existing story-point controls. Map/List and maximise remain available. -The **Relationship Timeline** shows the state after all changes up to the selected scene. Dots identify scenes with changes, and the selected scene is shown beside the timeline heading. **Initial** and **End** jump to the boundaries. Use the slider's arrow keys or **Previous change / Next change** to navigate without displaying hundreds of labels. **End** shows the state at the final scene. The current point supplies the editor's default scene. +Arrangements apply only when requested. **Relationship clusters** uses recorded connected components and denser subgroups within a connected network. **Focused radial** puts the chosen character at the centre and places connected characters by relationship distance; use Connection depth to control exploration. Unrelated characters already included in the diagram are parked separately. **Traditional family tree** uses authoritative family definitions, parents above children and recorded partners together, with shared family junctions where applicable. It does not infer partnerships from shared children and is independent of scene/POV disclosure. **Story importance** places recorded tiers in separate, wrapped bands, ordered by connections within each tier. Circle remains available. -Drag empty canvas to pan. Use **+ / −**, Ctrl/Cmd-wheel, or a two-finger pinch to zoom. The vertical canvas toolbar contains select, pan, fit, zoom and centre controls. **Auto-arrange** recalculates positions. **Layout → Reset layout** restores removed map characters and rearranges locally. **Layout → Remove focused from map** hides a node locally and does not delete the character or relationship. The maximise control expands the workspace within the application; click it again or press Escape to restore. In the PWA it sits directly on the ribbon and temporarily hides the title and category-tab rows to give the canvas more height, while keeping the command row and Restore button available. +Choose straight, curved or orthogonal connectors. Automatic uses curved social links and orthogonal family links. Parallel links receive distinct paths. Routing avoids unrelated cards where practical; dense graphs can still have crossings. For dense diagrams labels concentrate on selected, hovered and focused connections; **Show all relationship labels** overrides this. Details and List retain the recorded information. Large arrangements start at a readable zoom; **Fit diagram** gives an overview, then wheel zoom and pan let you inspect a region. After manually moving a family card, routing uses independent orthogonal paths until the next family arrangement rebuilds shared junctions. -Installed PWA users can right-click palette characters, map characters, connections or canvas to access the existing application command menu. The same actions are available through buttons, with no right-click required. Select a connection to inspect its history or edit it at the timeline point. **Map / List** switches between workspace views of the same relationship state. The right rail always contains contextual Details. Focusing a character shows their relationship count, connections, editing actions and history; selecting a connection shows its current state, notes and history. +Presets are **Connected characters** (the default), **Full cast**, **Major and Supporting**, **Selected character and connections**, **Family only** and **Custom diagram**. Connected uses relationships at the current Scene Explorer point; an empty relationship state starts empty. Family only uses author-reference facts. Removing or adding characters creates a custom diagram. Returning to Custom restores its membership, positions, pins and view after a preset excursion. -Positions, focus, zoom, pan and palette collapse are remembered in this browser for the project/book. They do not sync to other devices. On smaller screens, **Characters** opens a searchable drawer containing the whole cast, and **Details** opens the contextual panel. Selecting a character closes the drawer and returns to the map. The canvas and timeline remain the primary surface. **Display** opens a panel with Book, Chapter, Scene and Character focus select lists stacked under simple labels, followed by Show full network and **Update Map**. These controls are directly available in both browser and PWA mode; choose the story point and select Update Map. The relationship colour key stays at the bottom of the right panel. +# Scene Explorer and persistence -# Example +Initial, previous/next change, previous/next scene, selection and End retain their existing historical resolution. Scene Explorer changes only this visualisation. **Set Current Focus Here** is the explicit action that changes shared manuscript focus. Historical states, live data refreshes and importance changes preserve manual positions, custom membership, pins, zoom, pan and panel widths. -A mystery may reveal that one suspect is socially isolated from everyone except the victim, which could be a useful structural clue. +Drag either divider, use its arrow keys or double-click to reset its width. Both sides are remembered independently. Layout, connectors, membership, positions, pins, view and widths are stored locally for this author/project/book and survive navigation, reload and application restart. Clearing browser site data removes these local preferences. None of these diagram preferences is a character or relationship record. -# Writer Tip +# Editing relationships -The map is a perspective tool. Use it to ask better questions about the cast. - -# Common Mistakes - -- Assuming a sparse map is always bad. -- Forgetting relationships can change over time. -- Treating the map as a replacement for character detail pages. - -# Related Guides - -- [Characters](/Help/Article/characters.overview) -- [Story Bible](/Help/Article/storyBible.overview) -- [Character Relationships](/Help/Article/characters.currentRelationships) +Drag a palette character onto another character to open the existing relationship editor, or use Add relationship. The small arrow beside a focused diagram character starts a relationship rather than moving the character. Choose the recorded type, state, intensity, notes and reference point, then Save. Existing validation and permissions remain in force. Family definitions that require the canonical character editor open the existing Character Details relationship record. No AI processing is performed by this workspace. diff --git a/PlotLine/Views/RelationshipMap/Index.cshtml b/PlotLine/Views/RelationshipMap/Index.cshtml index 32b4bcbe..abb958c7 100644 --- a/PlotLine/Views/RelationshipMap/Index.cshtml +++ b/PlotLine/Views/RelationshipMap/Index.cshtml @@ -5,25 +5,30 @@ ViewData["ShellClass"] = "plotline-shell-wide rw-shell"; } -
+

Relationships

-
+
-
Layout
+
Layout
+
+ + +
Display
+
diff --git a/PlotLine/Views/RelationshipMap/_Details.cshtml b/PlotLine/Views/RelationshipMap/_Details.cshtml index d15286c5..9cae1b51 100644 --- a/PlotLine/Views/RelationshipMap/_Details.cshtml +++ b/PlotLine/Views/RelationshipMap/_Details.cshtml @@ -20,6 +20,7 @@ +
History
    diff --git a/PlotLine/Views/RelationshipMap/_GraphScripts.cshtml b/PlotLine/Views/RelationshipMap/_GraphScripts.cshtml index f5ae9ca1..e2c23738 100644 --- a/PlotLine/Views/RelationshipMap/_GraphScripts.cshtml +++ b/PlotLine/Views/RelationshipMap/_GraphScripts.cshtml @@ -1,8 +1,9 @@ @using System.Text.Json @model RelationshipMapViewModel +@inject Microsoft.AspNetCore.Mvc.ViewFeatures.IFileVersionProvider FileVersions @{ var jsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; } - + + + + diff --git a/PlotLine/Views/RelationshipMap/_Workspace.cshtml b/PlotLine/Views/RelationshipMap/_Workspace.cshtml index c3352060..948f70f0 100644 --- a/PlotLine/Views/RelationshipMap/_Workspace.cshtml +++ b/PlotLine/Views/RelationshipMap/_Workspace.cshtml @@ -14,7 +14,7 @@

    Supporting (@supporting.Count)

    } -
    +
    @if (side == "top" || side == "bottom") {

    @(side == "top" ? "Major" : "Minor") (@cast.Count())

    } @foreach (var character in cast) { @@ -60,6 +60,7 @@

    The renderer could not load. Character details and the relationship list remain available.

    +

    @@ -95,3 +96,7 @@
    + +

    Arrange pinned family positions

    Keeping pins may produce an irregular tree. Rearranging keeps the previous pins available through Undo layout change.

    + +

    Choose the central character

    diff --git a/PlotLine/wwwroot/css/relationship-workspace.css b/PlotLine/wwwroot/css/relationship-workspace.css index c96fe64c..dfb59fc2 100644 --- a/PlotLine/wwwroot/css/relationship-workspace.css +++ b/PlotLine/wwwroot/css/relationship-workspace.css @@ -156,13 +156,13 @@ html[data-standalone="true"] body.rw-page:has(#rwApp.rw-maximised) .pd-applicati html[data-standalone="true"] body.rw-page:has(#rwApp.rw-maximised) .pd-application-header .pd-ribbon-heading { display: none; } /* Equal compact actions keep Focus balanced and stable in both focus states. */ -body.rw-page [data-pwa-context-controls] .pd-context-group[aria-label="Focus"] details[data-compact="false"] > .pd-ribbon-commands { +body.rw-page [data-pwa-context-controls] .pd-context-group[aria-label="Diagram focus"] details[data-compact="false"] > .pd-ribbon-commands { width: 196px; } -body.rw-page [data-pwa-context-controls] .pd-context-group[aria-label="Focus"] details[data-compact="false"] > .pd-ribbon-commands > .pd-context-command { +body.rw-page [data-pwa-context-controls] .pd-context-group[aria-label="Diagram focus"] details[data-compact="false"] > .pd-ribbon-commands > .pd-context-command { flex: 0 0 96px; width: 96px; min-width: 0; } -body.rw-page [data-pwa-context-controls] .pd-context-group[aria-label="Focus"] .pd-context-command > span { +body.rw-page [data-pwa-context-controls] .pd-context-group[aria-label="Diagram focus"] .pd-context-command > span { display: block; max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } @@ -175,3 +175,24 @@ body.rw-page [data-pwa-context-controls] .pd-context-group[aria-label="Focus"] . .rw-timeline{overflow:visible;} .rw-board.palettes-hidden{grid-template-rows:minmax(0,1fr) auto;} @media(max-width:800px){.rw-board{grid-template-rows:minmax(0,1fr) auto;}} + +/* Main Relationships enhancements. Protected Context/Character Details do not contain #rwApp. */ +#rwApp [data-rw-tier]{min-height:48px;transition:background-color .12s} +#rwApp .rw-importance-drop{background:var(--pd-selected);outline:2px solid var(--pd-focus);outline-offset:-2px} +#rwApp .rw-unclassified{display:flex;align-items:center;gap:6px;flex:none;padding:3px 8px;border-left:1px solid var(--pd-border)} +#rwApp .rw-unclassified h3{white-space:nowrap} +#rwApp .rw-importance-icon{width:15px;height:15px;vertical-align:middle;fill:none;stroke:currentColor;stroke-width:1.8;flex:none} +#rwApp .rw-importance-icon[data-tone=warning]{color:var(--pd-warning)} +#rwApp .rw-importance-icon[data-tone=info]{color:var(--pd-info)} +#rwApp .rw-importance-icon[data-tone=secondary]{color:var(--pd-muted)} +#rwApp [data-rw-importance-indicator]{display:inline-flex;margin-left:auto;flex:none} +#rwApp #rwCanvasMenu{position:absolute;right:8px;bottom:30px;z-index:3} +#rwApp .rw-main-empty{position:absolute;inset:20% 15% auto;padding:18px;background:var(--pd-surface);color:var(--pd-text);border:1px solid var(--pd-border);border-radius:6px;z-index:2;text-align:center;pointer-events:none} +#rwApp .rw-main-empty button{pointer-events:auto} +#rwApp .rw-middle-pan{cursor:grabbing!important} +#rwApp #rwLayoutOptions,#rwApp #rwDiagramDisplay{display:grid;gap:6px;margin-bottom:8px} +#rwApp #rwDiagramDisplay>label:last-child{display:flex;align-items:center;gap:6px} +#rwApp .rw-strip>h2,#rwApp .rw-navigation>h3{display:flex;gap:4px;align-items:center} +:is(#rwPinDialog,#rwCentreDialog){max-width:min(520px,95vw);padding:20px;background:var(--pd-surface);color:var(--pd-text);border:1px solid var(--pd-border);border-radius:8px} +:is(#rwPinDialog,#rwCentreDialog)::backdrop{background:color-mix(in srgb,var(--pd-text) 25%,transparent)} +:is(#rwPinDialog,#rwCentreDialog) .rw-tools{display:flex;gap:8px;flex-wrap:wrap} diff --git a/PlotLine/wwwroot/js/relationship-main-layout.js b/PlotLine/wwwroot/js/relationship-main-layout.js new file mode 100644 index 00000000..3757774c --- /dev/null +++ b/PlotLine/wwwroot/js/relationship-main-layout.js @@ -0,0 +1,755 @@ +// Main Relationships only. Pure deterministic geometry; no persistence, DOM, data writes or AI. +(() => { + "use strict"; + const order = (a, b) => a.id - b.id, + key = (a, b) => (a < b ? a + ":" + b : b + ":" + a); + const rect = (n, p, pad = 0) => ({ + x1: p.x - n.w / 2 - pad, + y1: p.y - n.h / 2 - pad, + x2: p.x + n.w / 2 + pad, + y2: p.y + n.h / 2 + pad, + }); + const intersects = (a, b) => + a.x1 < b.x2 && a.x2 > b.x1 && a.y1 < b.y2 && a.y2 > b.y1; + function adjacency(nodes, edges) { + const a = new Map(nodes.map((n) => [n.id, new Map()])); + for (const e of edges) + if (e.a !== e.b && a.has(e.a) && a.has(e.b)) { + a.get(e.a).set(e.b, (a.get(e.a).get(e.b) || 0) + 1); + a.get(e.b).set(e.a, (a.get(e.b).get(e.a) || 0) + 1); + } + return a; + } + function components(nodes, adj) { + const byId = new Map(nodes.map((n) => [n.id, n])), + seen = new Set(), + groups = []; + for (const node of [...nodes].sort(order)) { + if (seen.has(node.id)) continue; + const ids = [node.id], + group = []; + seen.add(node.id); + for (let i = 0; i < ids.length; i++) { + const id = ids[i]; + group.push(byId.get(id)); + for (const next of [...adj.get(id).keys()].sort((a, b) => a - b)) + if (!seen.has(next)) { + seen.add(next); + ids.push(next); + } + } + groups.push(group); + } + return groups.sort((a, b) => b.length - a.length || a[0].id - b[0].id); + } + // Greedy modularity refinement reveals recorded dense subgroups within connected components. + function communities(nodes, adj) { + const ids = new Set(nodes.map((n) => n.id)), + degree = new Map( + nodes.map((n) => [ + n.id, + [...adj.get(n.id)] + .filter(([id]) => ids.has(id)) + .reduce((sum, [, w]) => sum + w, 0), + ]), + ), + mass = [...degree.values()].reduce((a, b) => a + b, 0) || 1, + labels = new Map(nodes.map((n) => [n.id, n.id])), + totals = new Map(degree); + for (let round = 0; round < 16; round++) { + let changed = false; + for (const n of [...nodes].sort(order)) { + const old = labels.get(n.id), + d = degree.get(n.id); + totals.set(old, (totals.get(old) || 0) - d); + const weights = new Map(); + for (const [id, w] of adj.get(n.id)) + if (ids.has(id)) { + const label = labels.get(id); + weights.set(label, (weights.get(label) || 0) + w); + } + let best = old, + score = (weights.get(old) || 0) - (d * (totals.get(old) || 0)) / mass; + for (const [label, w] of [...weights].sort((a, b) => a[0] - b[0])) { + const next = w - (d * (totals.get(label) || 0)) / mass; + if (next > score + 1e-8) { + best = label; + score = next; + } + } + labels.set(n.id, best); + totals.set(best, (totals.get(best) || 0) + d); + changed ||= best !== old; + } + if (!changed) break; + } + const groups = new Map(); + for (const n of nodes) { + const label = labels.get(n.id); + if (!groups.has(label)) groups.set(label, []); + groups.get(label).push(n); + } + return [...groups.values()].sort( + (a, b) => b.length - a.length || a[0].id - b[0].id, + ); + } + function noOverlap(nodes, positions, pins = {}, gap = 28) { + const placed = []; + for (const n of [...nodes].sort( + (a, b) => Number(!!pins[b.id]) - Number(!!pins[a.id]) || order(a, b), + )) { + let p = { ...(pins[n.id] || positions[n.id] || { x: 0, y: 0 }) }; + if (!pins[n.id]) { + const origin = { ...p }, + stepX = n.w + gap, + stepY = n.h + gap; + let found = false; + for ( + let ring = 0; + ring < Math.max(100, nodes.length) && !found; + ring++ + ) { + const candidates = []; + if (!ring) candidates.push(origin); + else + for (let x = -ring; x <= ring; x++) + for (const y of [-ring, ring]) + candidates.push({ + x: origin.x + (x * stepX) / 2, + y: origin.y + (y * stepY) / 2, + }); + if (ring) + for (let y = -ring + 1; y < ring; y++) + for (const x of [-ring, ring]) + candidates.push({ + x: origin.x + (x * stepX) / 2, + y: origin.y + (y * stepY) / 2, + }); + candidates.sort( + (a, b) => + (a.x - origin.x) ** 2 + + (a.y - origin.y) ** 2 - + ((b.x - origin.x) ** 2 + (b.y - origin.y) ** 2) || + a.y - b.y || + a.x - b.x, + ); + for (const candidate of candidates) + if ( + !placed.some((other) => + intersects(rect(n, candidate, gap / 2), other), + ) + ) { + p = candidate; + found = true; + break; + } + } + } + positions[n.id] = p; + placed.push(rect(n, p, gap / 2)); + } + return positions; + } + function bounds(nodes, p) { + if (!nodes.length) return { x1: 0, y1: 0, w: 0, h: 0 }; + const rs = nodes.map((n) => rect(n, p[n.id])); + const x1 = Math.min(...rs.map((x) => x.x1)), + y1 = Math.min(...rs.map((x) => x.y1)); + return { + x1, + y1, + w: Math.max(...rs.map((x) => x.x2)) - x1, + h: Math.max(...rs.map((x) => x.y2)) - y1, + }; + } + function pack(blocks, aspect = 1.8, gap = 100) { + const area = blocks.reduce( + (s, b) => s + (b.box.w + gap) * (b.box.h + gap), + 0, + ), + target = Math.max( + ...blocks.map((b) => b.box.w), + Math.sqrt(area * Math.max(0.6, Math.min(3, aspect))), + ); + let x = 0, + y = 0, + row = 0; + const p = {}; + for (const b of blocks) { + if (x && x + b.box.w > target) { + x = 0; + y += row + gap; + row = 0; + } + for (const n of b.nodes) + p[n.id] = { + x: b.p[n.id].x - b.box.x1 + x, + y: b.p[n.id].y - b.box.y1 + y, + }; + x += b.box.w + gap; + row = Math.max(row, b.box.h); + } + return p; + } + function force(nodes, adj) { + const p = {}, + ids = new Set(nodes.map((n) => n.id)); + for (const [i, n] of [...nodes].sort(order).entries()) { + const angle = i * 2.399963229728653, + r = 90 * Math.sqrt(i); + p[n.id] = { x: Math.cos(angle) * r, y: Math.sin(angle) * r }; + } + for (let pass = 0; pass < 100; pass++) { + const delta = new Map( + nodes.map((n) => [ + n.id, + { x: -p[n.id].x * 0.005, y: -p[n.id].y * 0.005 }, + ]), + ); + for (let i = 0; i < nodes.length; i++) + for (let j = i + 1; j < nodes.length; j++) { + const a = nodes[i], + b = nodes[j], + dx = p[b.id].x - p[a.id].x || 0.01, + dy = p[b.id].y - p[a.id].y || 0.02, + d = Math.max(10, Math.hypot(dx, dy)), + desired = Math.hypot((a.w + b.w) / 2 + 36, (a.h + b.h) / 2 + 28), + f = Math.min(28, ((desired * desired) / (d * d)) * 7); + delta.get(a.id).x -= (dx / d) * f; + delta.get(a.id).y -= (dy / d) * f; + delta.get(b.id).x += (dx / d) * f; + delta.get(b.id).y += (dy / d) * f; + } + for (const n of nodes) + for (const [id] of adj.get(n.id)) + if (ids.has(id) && id > n.id) { + const dx = p[id].x - p[n.id].x, + dy = p[id].y - p[n.id].y, + d = Math.hypot(dx, dy) || 1, + f = + (d - (n.w + nodes.find((n) => n.id === id).w) / 2 - 70) * 0.04; + delta.get(n.id).x += (dx / d) * f; + delta.get(n.id).y += (dy / d) * f; + delta.get(id).x -= (dx / d) * f; + delta.get(id).y -= (dy / d) * f; + } + for (const n of nodes) { + const d = delta.get(n.id), + cool = 1 - pass / 125; + p[n.id].x += Math.max(-25, Math.min(25, d.x)) * cool; + p[n.id].y += Math.max(-25, Math.min(25, d.y)) * cool; + } + } + const box = bounds(nodes, p), + area = nodes.reduce((sum, n) => sum + (n.w + 36) * (n.h + 32), 0), + sx = Math.min(1, Math.sqrt(area * 1.8) / Math.max(1, box.w)), + sy = Math.min(1, Math.sqrt(area / 1.8) / Math.max(1, box.h)); + for (const point of Object.values(p)) { + point.x *= sx; + point.y *= sy; + } + return noOverlap(nodes, p); + } + function clustered(nodes, adj, aspect) { + const blocks = [], + groups = []; + const isolated = []; + for (const component of components(nodes, adj)) { + if (component.length === 1) { + isolated.push(component[0]); + continue; + } + const communitiesInComponent = communities(component, adj), + inner = []; + for (const group of communitiesInComponent) { + const p = force(group, adj); + inner.push({ nodes: group, p, box: bounds(group, p) }); + groups.push(group.map((n) => n.id)); + } + let p; + if (inner.length < 2) p = inner[0].p; + else { + const membership = new Map( + inner.flatMap((block, index) => + block.nodes.map((n) => [n.id, index + 1]), + ), + ), + virtual = inner.map((block, index) => ({ + id: index + 1, + w: block.box.w + 50, + h: block.box.h + 50, + })), + bridges = []; + for (const n of component) + for (const [id, weight] of adj.get(n.id)) + if ( + id > n.id && + membership.has(id) && + membership.get(n.id) !== membership.get(id) + ) + for (let count = 0; count < Math.min(4, weight); count++) + bridges.push({ + a: membership.get(n.id), + b: membership.get(id), + }); + const centres = force(virtual, adjacency(virtual, bridges)); + const scale = Math.sqrt(Math.max(0.7, Math.min(2.6, aspect))); + for (const centre of Object.values(centres)) { + centre.x *= scale; + centre.y /= scale; + } + noOverlap(virtual, centres, {}, 60); + p = {}; + inner.forEach((block, index) => { + const centre = centres[index + 1]; + for (const n of block.nodes) + p[n.id] = { + x: block.p[n.id].x - block.box.x1 - block.box.w / 2 + centre.x, + y: block.p[n.id].y - block.box.y1 - block.box.h / 2 + centre.y, + }; + }); + } + blocks.push({ nodes: component, p, box: bounds(component, p) }); + } + if (isolated.length) { + const p = {}, + columns = Math.max( + 1, + Math.ceil(Math.sqrt(isolated.length * aspect * 0.45)), + ), + w = Math.max(...isolated.map((n) => n.w)) + 36, + h = Math.max(...isolated.map((n) => n.h)) + 32; + isolated.sort(order).forEach( + (n, i) => + (p[n.id] = { + x: (i % columns) * w, + y: Math.floor(i / columns) * h, + }), + ); + blocks.push({ nodes: isolated, p, box: bounds(isolated, p) }); + } + return { positions: pack(blocks, aspect, 130), communities: groups }; + } + function radial(nodes, adj, focus, depth) { + if (!nodes.length) return { positions: {}, distances: {} }; + focus = nodes.some((n) => n.id === focus) + ? focus + : [...nodes].sort( + (a, b) => adj.get(b.id).size - adj.get(a.id).size || order(a, b), + )[0].id; + const distance = new Map([[focus, 0]]), + branch = new Map([[focus, focus]]), + queue = [focus]; + for (let i = 0; i < queue.length; i++) { + const id = queue[i]; + if (distance.get(id) >= depth) continue; + for (const next of [...adj.get(id).keys()].sort((a, b) => a - b)) + if (!distance.has(next)) { + distance.set(next, distance.get(id) + 1); + branch.set(next, id === focus ? next : branch.get(id)); + queue.push(next); + } + } + const p = { [focus]: { x: 0, y: 0 } }, + rings = new Map(); + for (const n of nodes) + if (n.id !== focus && distance.has(n.id)) { + const d = distance.get(n.id); + if (!rings.has(d)) rings.set(d, []); + rings.get(d).push(n); + } + let previous = 0; + for (const [d, ring] of rings) { + const maxW = Math.max(...ring.map((n) => n.w)), + maxH = Math.max(...ring.map((n) => n.h)), + radius = Math.max( + previous + Math.hypot(maxW, maxH) + 75, + (ring.length * (Math.hypot(maxW, maxH) + 45)) / (2 * Math.PI), + ); + ring + .sort((a, b) => branch.get(a.id) - branch.get(b.id) || order(a, b)) + .forEach((n, i) => { + const angle = -Math.PI / 2 + (2 * Math.PI * i) / ring.length; + p[n.id] = { + x: Math.cos(angle) * radius, + y: Math.sin(angle) * radius, + }; + }); + previous = radius; + } + const unrelated = nodes.filter((n) => !distance.has(n.id)); + if (unrelated.length) { + const w = Math.max(...unrelated.map((n) => n.w)) + 35, + h = Math.max(...unrelated.map((n) => n.h)) + 35, + cols = Math.max(1, Math.ceil(Math.sqrt(unrelated.length))); + unrelated.sort(order).forEach( + (n, i) => + (p[n.id] = { + x: previous + w + (i % cols) * w, + y: Math.floor(i / cols) * h, + }), + ); + } + return { positions: p, distances: Object.fromEntries(distance), focus }; + } + function tiers(nodes, adj, aspect) { + const community = new Map( + communities(nodes, adj).flatMap((group, index) => + group.map((n) => [n.id, index]), + ), + ), + p = {}, + levels = [ + (n) => n.importance >= 8, + (n) => n.importance >= 4 && n.importance < 8, + (n) => n.importance >= 1 && n.importance < 4, + (n) => !(n.importance >= 1), + ]; + let y = 0; + for (const test of levels) { + const group = nodes.filter(test); + if (!group.length) continue; + const degree = (n) => + [...adj.get(n.id).values()].reduce((a, b) => a + b, 0); + const bary = (n) => { + const neighbours = [...adj.get(n.id).keys()].filter((id) => p[id]); + return neighbours.length + ? neighbours.reduce((sum, id) => sum + p[id].x, 0) / neighbours.length + : 0; + }; + group.sort( + (a, b) => + (community.get(a.id) || 0) - (community.get(b.id) || 0) || + bary(a) - bary(b) || + degree(b) - degree(a) || + order(a, b), + ); + const cols = Math.max( + 1, + Math.ceil(Math.sqrt(group.length * aspect * 0.4)), + ), + w = Math.max(...group.map((n) => n.w)) + 46, + h = Math.max(...group.map((n) => n.h)) + 40; + group.forEach( + (n, i) => + (p[n.id] = { x: (i % cols) * w, y: y + Math.floor(i / cols) * h }), + ); + y += Math.ceil(group.length / cols) * h + 100; + } + return p; + } + function layout(input) { + const nodes = [...input.nodes].sort(order), + edges = input.edges, + adj = adjacency(nodes, edges), + aspect = + (input.viewport?.width || 1200) / + Math.max(200, input.viewport?.height || 700); + let result; + if (!nodes.length) return { positions: {}, communities: [], warnings: [] }; + switch (input.layout) { + case "radial": + result = radial(nodes, adj, input.focus, input.depth || 2); + break; + case "importance": + result = { positions: tiers(nodes, adj, aspect) }; + break; + case "family": { + const engine = globalThis.PlotDirectorContextRelationshipLayout; + const family = engine.family( + nodes.map((n) => ({ + id: n.id, + name: n.name, + birthDate: n.birthDate, + })), + edges.map((e) => ({ + id: e.id, + a: e.a, + b: e.b, + type: e.type, + reciprocal: e.reciprocal, + })), + ); + result = { + ...family, + positions: Object.fromEntries( + Object.entries(family.positions).map(([id, p]) => [ + id, + { x: p.x + family.nodeWidth / 2, y: p.y + family.nodeHeight / 2 }, + ]), + ), + }; + break; + } + case "circle": { + const radius = Math.max( + 180, + (nodes.length * Math.max(...nodes.map((n) => Math.hypot(n.w, n.h)))) / + (2 * Math.PI), + ); + result = { + positions: Object.fromEntries( + nodes.map((n, i) => [ + n.id, + { + x: Math.cos((2 * Math.PI * i) / nodes.length) * radius, + y: Math.sin((2 * Math.PI * i) / nodes.length) * radius, + }, + ]), + ), + }; + break; + } + default: + result = clustered(nodes, adj, aspect); + } + result.positions = noOverlap( + nodes, + result.positions, + input.pins || {}, + input.layout === "family" ? 12 : 28, + ); + const pinnedNodes = nodes.filter((n) => input.pins?.[n.id]); + if ( + pinnedNodes.some((n, i) => + pinnedNodes + .slice(i + 1) + .some((other) => + intersects( + rect(n, result.positions[n.id]), + rect(other, result.positions[other.id]), + ), + ), + ) + ) + result.warnings = [ + ...(result.warnings || []), + "Pinned character positions overlap. Unpin or move them to separate the cards.", + ]; + result.preferredCenter = + input.focus && result.positions[input.focus] + ? input.focus + : [...nodes].sort( + (a, b) => adj.get(b.id).size - adj.get(a.id).size || order(a, b), + )[0].id; + return { ...result, bounds: bounds(nodes, result.positions) }; + } + function crosses(a, b, r) { + let lo = 0, + hi = 1; + const dx = b.x - a.x, + dy = b.y - a.y; + for (const [p, q] of [ + [-dx, a.x - r.x1], + [dx, r.x2 - a.x], + [-dy, a.y - r.y1], + [dy, r.y2 - a.y], + ]) { + if (!p) { + if (q < 0) return false; + } else { + const t = q / p; + if (p < 0) lo = Math.max(lo, t); + else hi = Math.min(hi, t); + if (lo > hi) return false; + } + } + return true; + } + function orthogonal(a, b, obstacles, lane = 0) { + const gap = 28 + Math.abs(lane), + mx = (a.x + b.x) / 2 + lane, + my = (a.y + b.y) / 2 + lane, + horizontal = Math.abs(b.x - a.x) >= Math.abs(b.y - a.y), + preferred = horizontal + ? [a, { x: a.x, y: my }, { x: b.x, y: my }, b] + : [a, { x: mx, y: a.y }, { x: mx, y: b.y }, b]; + const score = (path) => { + let hits = 0, + length = 0; + for (let i = 1; i < path.length; i++) { + length += Math.hypot( + path[i].x - path[i - 1].x, + path[i].y - path[i - 1].y, + ); + hits += obstacles.filter((r) => + crosses(path[i - 1], path[i], r), + ).length; + } + return hits * 1e7 + length; + }; + if (lane && score(preferred) < 1e7) return preferred; + const candidates = [ + preferred, + [a, { x: mx, y: a.y }, { x: mx, y: b.y }, b], + [a, { x: a.x, y: my }, { x: b.x, y: my }, b], + ], + blocked = obstacles.filter((r) => crosses(a, b, r)); + for (const r of blocked) + for (const x of [r.x1 - gap + lane, r.x2 + gap + lane]) + candidates.push([a, { x, y: a.y }, { x, y: b.y }, b]); + for (const r of blocked) + for (const y of [r.y1 - gap + lane, r.y2 + gap + lane]) + candidates.push([a, { x: a.x, y }, { x: b.x, y }, b]); + let best = candidates + .map((p, i) => ({ p, i, s: score(p) })) + .sort((a, b) => a.s - b.s || a.i - b.i)[0]; + const seen = new Set(); + for (let pass = 0; pass < 12 && best.s >= 1e7; pass++) { + const signature = JSON.stringify(best.p); + if (seen.has(signature)) break; + seen.add(signature); + let conflict; + for (let i = 1; i < best.p.length && !conflict; i++) { + const hit = obstacles.find((r) => crosses(best.p[i - 1], best.p[i], r)); + if (hit) conflict = { i, r: hit }; + } + if (!conflict) break; + const { i, r } = conflict, + p = best.p[i - 1], + q = best.p[i], + detours = + p.y === q.y + ? [r.y1 - gap + lane, r.y2 + gap + lane].map((y) => [ + p, + { x: p.x, y }, + { x: q.x, y }, + q, + ]) + : [r.x1 - gap + lane, r.x2 + gap + lane].map((x) => [ + p, + { x, y: p.y }, + { x, y: q.y }, + q, + ]); + const alternatives = detours + .map((points, n) => { + const path = [ + ...best.p.slice(0, i - 1), + ...points, + ...best.p.slice(i + 1), + ]; + return { p: path, i: n, s: score(path) }; + }) + .sort((a, b) => a.s - b.s || a.i - b.i); + if (alternatives[0].s >= best.s) break; + best = alternatives[0]; + } + return best.p; + } + function route(nodes, edge, style, lane = 0, familyPath) { + const byId = new Map(nodes.map((n) => [n.id, n])), + a = byId.get(edge.a), + b = byId.get(edge.b); + if (!a || !b) return null; + const obstacles = nodes + .filter((n) => n !== a && n !== b) + .map((n) => rect(n, n, 10)); + if (style === "straight") { + const dx = b.x - a.x, + dy = b.y - a.y, + clamp = (v, min, max) => Math.max(min, Math.min(max, v)); + return { + style: "straight", + sourceEndpoint: lane + ? Math.abs(dx) >= Math.abs(dy) + ? { + x: (Math.sign(dx) * a.w) / 2, + y: clamp(lane, -a.h / 2 + 6, a.h / 2 - 6), + } + : { + x: clamp(lane, -a.w / 2 + 6, a.w / 2 - 6), + y: (Math.sign(dy) * a.h) / 2, + } + : null, + targetEndpoint: lane + ? Math.abs(dx) >= Math.abs(dy) + ? { + x: (-Math.sign(dx) * b.w) / 2, + y: clamp(lane, -b.h / 2 + 6, b.h / 2 - 6), + } + : { + x: clamp(lane, -b.w / 2 + 6, b.w / 2 - 6), + y: (-Math.sign(dy) * b.h) / 2, + } + : null, + }; + } + if (style === "orthogonal") { + if (familyPath && !lane) { + let current = { x: 0, y: 0 }; + const points = []; + for (const part of familyPath.matchAll( + /([MHV])\s*(-?[\d.]+)(?:\s+(-?[\d.]+))?/g, + )) { + current = + part[1] === "M" + ? { x: +part[2], y: +part[3] } + : part[1] === "H" + ? { x: +part[2], y: current.y } + : { x: current.x, y: +part[2] }; + points.push(current); + } + if (points.length > 2) { + if ( + Math.hypot(points[0].x - b.x, points[0].y - b.y) < + Math.hypot(points[0].x - a.x, points[0].y - a.y) + ) + points.reverse(); + return { style: "segments", points: points.slice(1, -1) }; + } + } + return { + style: "segments", + points: orthogonal(a, b, obstacles, lane).slice(1, -1), + }; + } + const dx = b.x - a.x, + dy = b.y - a.y, + length = Math.hypot(dx, dy) || 1, + nx = -dy / length, + ny = dx / length; + let best = { distance: lane || 22, hits: Infinity }; + for (const distance of [ + lane || 22, + 60 + lane, + -60 + lane, + 130 + lane, + -130 + lane, + 240 + lane, + -240 + lane, + ]) { + const control = { + x: (a.x + b.x) / 2 + nx * distance, + y: (a.y + b.y) / 2 + ny * distance, + }; + let hits = 0, + previous = a; + for (let i = 1; i <= 16; i++) { + const t = i / 16, + p = { + x: (1 - t) ** 2 * a.x + 2 * (1 - t) * t * control.x + t * t * b.x, + y: (1 - t) ** 2 * a.y + 2 * (1 - t) * t * control.y + t * t * b.y, + }; + hits += obstacles.filter((r) => crosses(previous, p, r)).length; + previous = p; + } + if (hits < best.hits) { + best = { distance, hits }; + if (!hits) break; + } + } + return { style: "unbundled-bezier", distance: best.distance }; + } + globalThis.PlotDirectorMainRelationshipLayout = { + layout, + route, + adjacency, + communities, + components, + noOverlap, + rect, + intersects, + key, + }; +})(); diff --git a/PlotLine/wwwroot/js/relationship-main-worker.js b/PlotLine/wwwroot/js/relationship-main-worker.js new file mode 100644 index 00000000..196da12c --- /dev/null +++ b/PlotLine/wwwroot/js/relationship-main-worker.js @@ -0,0 +1,36 @@ +// Only the main Relationships workspace starts this worker. Shared family code is read-only. +self.window = self; +self.onmessage = (event) => { + const input = event.data; + if (input.init) { + importScripts(input.engineUrl, input.familyUrl); + postMessage({ ready: true }); + return; + } + try { + if (input.routes) { + postMessage({ + id: input.id, + result: { + routes: input.routes.edges.map((edge) => ({ + id: edge.id, + ...self.PlotDirectorMainRelationshipLayout.route( + input.routes.nodes, + edge, + input.routes.style, + edge.lane, + edge.path, + ), + })), + }, + }); + return; + } + postMessage({ + id: input.id, + result: self.PlotDirectorMainRelationshipLayout.layout(input.graph), + }); + } catch (error) { + postMessage({ id: input.id, error: error.message }); + } +}; diff --git a/PlotLine/wwwroot/js/relationship-main.js b/PlotLine/wwwroot/js/relationship-main.js new file mode 100644 index 00000000..4ee0ad80 --- /dev/null +++ b/PlotLine/wwwroot/js/relationship-main.js @@ -0,0 +1,2283 @@ +// Opt-in main Relationships controller. No Context/Character Details renderer or state is changed. +(() => { + "use strict"; + const LAYOUTS = [ + ["clusters", "Relationship clusters", "relationships"], + ["radial", "Focused radial", "focus"], + ["family", "Traditional family tree", "characters"], + ["importance", "Story importance", "attribute-star-filled"], + ["circle", "Circle", "layout"], + ]; + const PRESETS = [ + ["connected", "Connected characters"], + ["full", "Full cast"], + ["major", "Major and Supporting"], + ["selected", "Selected character and connections"], + ["family", "Family only"], + ["custom", "Custom diagram"], + ]; + const tier = (value) => + value >= 8 ? "10" : value >= 4 ? "6" : value >= 1 ? "2" : ""; + const copy = (value) => JSON.parse(JSON.stringify(value)); + window.PlotDirectorMainRelationships = { + mount(a) { + const { app, workspace: w, cy, graph, board, cast, castById } = a, + geometry = window.PlotDirectorMainRelationshipLayout, + toast = Object.fromEntries( + ["info", "success", "error", "warning"].map((kind) => [ + kind, + (...args) => window.PlotDirector?.toast?.[kind](...args), + ]), + ), + life = new AbortController(), + listen = (n, e, fn, options = {}) => + n?.addEventListener(e, fn, { ...options, signal: life.signal }); + const user = + document.body.dataset.pdUserId || + document.querySelector("[data-toast-host]")?.dataset.toastUser || + "session", + storageKey = `pd.relationship-workspace.v2.${user}.${w.projectId}.${w.bookId || "project"}`; + const $ = (id) => document.getElementById(id), + status = $("rwStatus"), + presetControl = $("rwPreset"), + layoutControl = $("rwLayout"), + connectorControl = $("rwConnector"), + depthControl = $("rwDepth"); + for (const [id, label] of PRESETS) + presetControl.add(new Option(label, id)); + for (const [id, label] of LAYOUTS) + layoutControl.add(new Option(label, id)); + let initialised = false, + pendingCommands = 0; + function command(task) { + pendingCommands++; + return Promise.resolve() + .then(task) + .catch((error) => toast.error(error.message)) + .finally(() => pendingCommands--); + } + function setPreset(next) { + return command(() => performPreset(next)); + } + function arrange(kind, options) { + return command(() => performArrange(kind, options)); + } + let saved; + try { + saved = JSON.parse(localStorage.getItem(storageKey) || "null"); + } catch {} + // Claim legacy browser preferences once; never import another author's unscoped state. + let legacy = null; + try { + const suffix = `${w.projectId}.${w.bookId || "project"}`, + ownerKey = "pd.relationship-workspace.v1-owner." + suffix; + let owner = localStorage.getItem(ownerKey); + if (!owner) { + owner = user; + localStorage.setItem(ownerKey, user); + } + if (owner === user) { + if (!saved) legacy = a.legacy; + localStorage.removeItem("pd.relationship-workspace.v1." + suffix); + } + } catch { + /* Optional legacy migration. */ + } + let preset = + saved?.preset || + (legacy + ? legacy.focus + ? "selected" + : "custom" + : w.focusCharacterId + ? "selected" + : "connected"), + layout = saved?.layout || "clusters", + connector = saved?.connector || "auto", + depth = Math.max(1, Math.min(6, saved?.depth || 2)), + familyRoot = saved?.familyRoot || null, + allLabels = !!saved?.allLabels; + if (!PRESETS.some(([id]) => id === preset)) preset = "connected"; + if (!LAYOUTS.some(([id]) => id === layout)) layout = "clusters"; + if (!["auto", "straight", "curved", "orthogonal"].includes(connector)) + connector = "auto"; + let members = new Set( + ( + saved?.members || + (legacy && + cast + .map((c) => c.characterID) + .filter((id) => !legacy.removed?.includes(id))) || + [] + ).filter((id) => castById.has(id)), + ), + pins = new Set((saved?.pins || []).filter((id) => castById.has(id))), + custom = saved?.custom || null; + let family = null, + familyPromise = null, + familyEpoch = 0, + readVersions = new Map(), + canEdit = w.canEdit, + assignBusy = false, + pendingHint = false, + undoAttribute = null, + undoStack = [], + saveTimer, + routeFrame, + layoutEpoch = 0, + arranging = false, + worker, + workerReady, + pendingWorker = new Map(), + workerSequence = 0, + modelSync = false, + connection, + refreshTimer, + menuHit = null, + dragSnapshot = null; + const positions = new Map( + Object.entries(saved?.positions || legacy?.positions || {}) + .filter( + ([id, p]) => + castById.has(+id.replace("c-", "")) && + Number.isFinite(p?.x) && + Number.isFinite(p?.y), + ) + .map(([id, p]) => [+id.replace("c-", ""), { x: p.x, y: p.y }]), + ); + const definitions = w.importanceDefinitions || [], + definition = (value) => + definitions.find((v) => v.value === tier(value)), + known = (id) => castById.has(+id), + node = (id) => cy.$id("c-" + id), + visible = () => cy.nodes(":visible"), + isFamily = () => preset === "family" || layout === "family", + familyRecords = () => family?.relationships || []; + function records() { + return isFamily() ? familyRecords() : w.relationships(); + } + function edges() { + return records().map((r) => ({ + id: r.characterRelationshipID, + a: r.characterAID, + b: r.characterBID, + type: r.relationshipTypeName, + reciprocal: r.isReciprocal, + record: r, + })); + } + function snapshot() { + const ps = {}; + cy.nodes().forEach((n) => { + const id = n.data("characterID"); + if (known(id)) ps[id] = { ...n.position() }; + }); + return { + members: [...members], + positions: ps, + pins: [...pins], + preset, + layout, + connector, + depth, + familyRoot, + familyRoutes: Object.fromEntries(familyRoutes), + zoom: cy.zoom(), + pan: { ...cy.pan() }, + focus: a.getFocus(), + allLabels, + view: $("rwListPanel").hidden ? "map" : "list", + custom: copy(custom), + collapsed: board.classList.contains("palettes-hidden"), + }; + } + function remember() { + clearTimeout(saveTimer); + saveTimer = setTimeout(() => { + try { + localStorage.setItem(storageKey, JSON.stringify(snapshot())); + } catch {} + }, 250); + } + function checkpoint() { + layoutEpoch++; + undoStack.push(snapshot()); + if (undoStack.length > 24) undoStack.shift(); + $("rwUndoLayout").disabled = false; + } + function rememberCustom() { + custom = { + members: [...members], + positions: Object.fromEntries(positions), + pins: [...pins], + layout, + zoom: cy.zoom(), + pan: { ...cy.pan() }, + }; + cy.nodes().forEach((n) => { + if (known(n.data("characterID"))) + custom.positions[n.data("characterID")] = { ...n.position() }; + }); + } + function toCustom() { + if (preset === "custom") return; + preset = "custom"; + familyRoot = null; + rememberCustom(); + syncControls(); + } + function restoreView(view) { + members = new Set((view.members || []).filter(known)); + pins = new Set((view.pins || []).filter(known)); + preset = view.preset || "custom"; + layout = view.layout || "clusters"; + connector = view.connector || connector; + depth = view.depth || depth; + familyRoot = view.familyRoot || null; + allLabels = view.allLabels ?? allLabels; + custom = copy(view.custom ?? custom); + familyRoutes = new Map( + Object.entries(view.familyRoutes || {}).map(([id, d]) => [+id, d]), + ); + a.setFocus(known(view.focus) ? view.focus : null); + for (const [id, p] of Object.entries(view.positions || {})) + if (known(id) && Number.isFinite(p?.x) && Number.isFinite(p?.y)) { + positions.set(+id, { ...p }); + a.ensureNode(+id).position(p); + } + if (Number.isFinite(view.zoom)) cy.zoom(view.zoom); + if (Number.isFinite(view.pan?.x) && Number.isFinite(view.pan?.y)) + cy.pan(view.pan); + a.setView(view.view || "map"); + syncControls(); + void applyFocus(false); + } + function undoLayout() { + const previous = undoStack.pop(); + if (!previous) return; + layoutEpoch++; + restoreView(previous); + $("rwUndoLayout").disabled = !undoStack.length; + remember(); + toast?.info("Previous diagram state restored."); + } + function neighbours(start, links, maximum = depth, allowed) { + const adj = new Map(); + for (const e of links) { + if (allowed && (!allowed.has(e.a) || !allowed.has(e.b))) continue; + if (!adj.has(e.a)) adj.set(e.a, []); + if (!adj.has(e.b)) adj.set(e.b, []); + adj.get(e.a).push(e.b); + adj.get(e.b).push(e.a); + } + const found = new Set(known(start) ? [start] : []), + queue = [{ id: start, d: 0 }]; + for (let i = 0; i < queue.length; i++) { + const next = queue[i]; + if (next.d >= maximum) continue; + for (const id of adj.get(next.id) || []) + if (!found.has(id)) { + found.add(id); + queue.push({ id, d: next.d + 1 }); + } + } + return found; + } + async function loadFamily(force = false) { + if (family && !force) return family; + if (familyPromise) return familyPromise; + const epoch = familyEpoch; + familyPromise = (async () => { + const response = await fetch( + "/RelationshipMap/Family?" + + new URLSearchParams({ projectId: w.projectId }), + { cache: "no-store", signal: life.signal }, + ); + if (!response.ok || response.redirected) + throw Error( + "Author-reference family relationships could not be loaded.", + ); + const result = await response.json(); + if (epoch !== familyEpoch) return null; + family = result; + return result; + })(); + try { + return await familyPromise; + } finally { + familyPromise = null; + } + } + function freePosition(id, preferred) { + const c = castById.get(id), + other = visible() + .filter((n) => n.data("characterID") !== id) + .map((n) => ({ + id: n.data("characterID"), + w: n.outerWidth(), + h: n.outerHeight(), + ...n.position(), + })), + w = 190, + h = 82; + let near = preferred; + const neighbour = edges().find( + (e) => + (e.a === id && members.has(e.b)) || + (e.b === id && members.has(e.a)), + ); + if (!near && neighbour) { + const n = node(neighbour.a === id ? neighbour.b : neighbour.a); + if (n.length) near = n.position(); + } + near ||= { + x: (graph.clientWidth / 2 - cy.pan().x) / cy.zoom(), + y: (graph.clientHeight / 2 - cy.pan().y) / cy.zoom(), + }; + const ps = Object.fromEntries( + other.map((n) => [n.id, { x: n.x, y: n.y }]), + ); + ps[id] = near; + const pinPositions = Object.fromEntries( + other.map((n) => [n.id, { x: n.x, y: n.y }]), + ); + return geometry.noOverlap( + [...other, { id, w, h }], + ps, + pinPositions, + 28, + )[id]; + } + function ensurePosition(id, preferred) { + const n = a.ensureNode(id); + if (!n.length) return n; + const p = preferred || positions.get(id) || freePosition(id); + n.position(p); + positions.set(id, { ...p }); + return n; + } + function effectiveConnector() { + return connector === "auto" + ? isFamily() + ? "orthogonal" + : "curved" + : connector; + } + function syncControls() { + presetControl.value = preset; + layoutControl.value = layout; + connectorControl.value = connector; + depthControl.value = String(depth); + $("rwAllLabels").checked = allLabels; + document.querySelector('[name="showFullNetwork"]').checked = + preset === "full"; + $("rwCharacterMenu").hidden = !a.getFocus(); + $("rwClearPins").disabled = !pins.size; + $("rwUndoLayout").disabled = !undoStack.length; + app.dataset.diagramPreset = preset; + app.dataset.connectorStyle = effectiveConnector(); + app.dataset.diagramLayout = layout; + for (const id of ["rwConnect", "rwDetailConnect", "rwEditLine"]) + if ($(id)) $(id).disabled = !canEdit; + $("rwFocusName").title = $("rwFocusName").textContent; + $("rwFocusName").setAttribute( + "aria-description", + "Diagram character focus; does not change manuscript focus", + ); + } + function updateMembership() { + const reference = + preset === "family" + ? edges() + : w + .relationships() + .map((r) => ({ a: r.characterAID, b: r.characterBID })); + let desired; + if (preset === "custom") desired = new Set([...members].filter(known)); + else if (preset === "full") + desired = new Set(cast.map((c) => c.characterID)); + else if (preset === "major") + desired = new Set( + cast + .filter((c) => c.characterImportance >= 4) + .map((c) => c.characterID), + ); + else if (preset === "selected") + desired = neighbours(a.getFocus(), reference); + else if (preset === "family") + desired = familyRoot + ? neighbours(familyRoot, edges()) + : new Set(edges().flatMap((e) => [e.a, e.b])); + else desired = new Set(reference.flatMap((e) => [e.a, e.b])); + members = new Set([...desired].filter(known)); + } + let legendSignature = ""; + function renderLegend() { + const values = [ + ...new Map( + records().map((r) => [ + r.relationshipCategoryName, + { label: r.relationshipCategoryName, css: r.cssClass }, + ]), + ).values(), + ], + signature = JSON.stringify(values); + if (signature === legendSignature) return; + legendSignature = signature; + const host = app.querySelector(".relationship-map-legend-grid"); + if (!host) return; + host.replaceChildren( + ...values.map((value) => { + const item = document.createElement("span"); + item.className = + "relationship-map-legend-item " + (value.css || ""); + const line = document.createElement("span"); + line.className = "relationship-map-legend-line"; + line.setAttribute("aria-hidden", "true"); + item.append( + line, + document.createTextNode(value.label || "Relationship"), + ); + return item; + }), + ); + } + function renderList() { + const host = app.querySelector(".relationship-map-list"); + if (!host) return; + const title = $("rwListPanel").querySelector("h2"); + title.textContent = isFamily() + ? "Author-reference family relationships" + : "Relationships at the current story point"; + host.replaceChildren( + ...records() + .filter( + (r) => members.has(r.characterAID) && members.has(r.characterBID), + ) + .map((r) => { + const button = document.createElement("button"); + button.type = "button"; + button.className = "relationship-map-list-item"; + button.textContent = `${r.characterAName} – ${r.characterBName}: ${r.relationshipTypeName} / ${r.currentStateName}`; + button.addEventListener("click", () => + selectRelationship(r.characterRelationshipID), + ); + return button; + }), + ); + } + let referenceRecords = null; + function syncReferenceEdges() { + const current = records(); + if (referenceRecords === current) return; + for (const r of current) { + if (!known(r.characterAID) || !known(r.characterBID)) continue; + for (const id of [r.characterAID, r.characterBID]) a.ensureNode(id); + let e = cy.$id("r-" + r.characterRelationshipID); + const data = { + relationshipID: r.characterRelationshipID, + source: "c-" + r.characterAID, + target: "c-" + r.characterBID, + label: r.relationshipTypeName, + intensity: r.currentIntensity || r.initialIntensity || 4, + category: r.relationshipCategoryName, + tooltip: `${r.characterAName} — ${r.relationshipTypeName} — ${r.characterBName}: ${r.currentStateName}${isFamily() ? " (author reference)" : ""}`, + }; + if (!e.length) + e = cy.add({ + group: "edges", + data: { id: "r-" + r.characterRelationshipID, ...data }, + classes: r.cssClass, + }); + else { + if ( + e.source().id() !== data.source || + e.target().id() !== data.target + ) + e.move({ source: data.source, target: data.target }); + e.data(data); + const selected = e.hasClass("is-selected"), + hover = e.hasClass("is-main-hover"); + e.classes(r.cssClass || ""); + e.toggleClass("is-selected", selected); + e.toggleClass("is-main-hover", hover); + } + if (isFamily()) { + const role = window.PlotDirectorContextRelationshipLayout.role({ + a: r.characterAID, + b: r.characterBID, + type: r.relationshipTypeName, + reciprocal: r.isReciprocal, + }); + e.style( + "line-style", + role.style === "adoptive" + ? "dashed" + : role.style === "step" + ? "dotted" + : "solid", + ); + } else e.removeStyle("line-style"); + e.data("mainFamily", isFamily()); + } + referenceRecords = current; + } + async function applyFocus(centre = false) { + if (isFamily() && !family) { + status.textContent = "Loading author-reference family facts…"; + try { + await loadFamily(); + } catch (error) { + status.textContent = error.message; + return; + } + } + updateMembership(); + if (isFamily()) + cy.nodes().style({ width: 180, height: 66, padding: 0 }); + else cy.nodes().removeStyle("width height padding"); + modelSync = true; + cy.batch(() => { + syncReferenceEdges(); + for (const id of members) ensurePosition(id); + cy.nodes().forEach((n) => { + const id = n.data("characterID"); + n.removeClass("is-focus is-dimmed"); + n.toggleClass("is-main-pinned", pins.has(id)); + if (members.has(id)) n.show(); + else n.hide(); + if (pins.has(id)) n.lock(); + else n.unlock(); + }); + const allowedEdges = new Set(edges().map((e) => "r-" + e.id)); + cy.edges().forEach((e) => { + if ( + allowedEdges.has(e.id()) && + members.has(+e.source().data("characterID")) && + members.has(+e.target().data("characterID")) + ) + e.show(); + else e.hide(); + }); + const selectedNode = node(a.getFocus()); + if (selectedNode.length && selectedNode.visible()) + selectedNode.addClass("is-focus"); + }); + modelSync = false; + app + .querySelectorAll("[data-rw-entry]") + .forEach((e) => + e.classList.toggle("is-focus", +e.dataset.rwEntry === a.getFocus()), + ); + $("focusCharacterId").value = a.getFocus() || ""; + $("rwFocusName").textContent = a.getFocus() + ? "Focus: " + (castById.get(a.getFocus())?.characterName || "") + : PRESETS.find(([id]) => id === preset)?.[1] || "Diagram"; + $("rwClearFocus").hidden = !a.getFocus(); + $("rwEmpty").hidden = members.size > 0; + if (a.getFocus()) a.renderCharacterDetail(); + a.positionHandle(); + if (centre) { + const selected = node(a.getFocus()); + if (selected.length && selected.visible()) cy.center(selected); + } + syncControls(); + renderLegend(); + if (!$("rwListPanel").hidden) renderList(); + refreshIndicators(); + scheduleRoutes(); + remember(); + status.textContent = `${members.size} displayed · ${cy.edges(":visible").length} ${isFamily() ? "author-reference family" : "recorded"} connections${arranging ? " · Arranging…" : ""}.`; + } + function focusCharacter(id, centre = true) { + id = +id; + if (!known(id)) return; + a.setFocus(id); + if (!members.has(id)) { + checkpoint(); + toCustom(); + members.add(id); + ensurePosition(id); + } + void applyFocus(centre); + if (window.innerWidth > 800) a.showDetail(); + else { + board.classList.remove("mobile-characters"); + $("rwCharacters").setAttribute("aria-expanded", "false"); + } + remember(); + } + function clearFocus() { + a.setFocus(null); + if (preset === "selected") preset = "connected"; + a.clearDetail(); + void applyFocus(false); + remember(); + } + function remove(id = a.getFocus()) { + if (!known(id) || !members.has(id)) return; + checkpoint(); + toCustom(); + members.delete(+id); + pins.delete(+id); + if (a.getFocus() === +id) { + a.setFocus(null); + a.clearDetail(); + } + void applyFocus(false); + remember(); + toast?.info( + "Character removed from this diagram; project records retained.", + ); + } + function clear() { + if (!members.size && preset === "custom") return; + checkpoint(); + toCustom(); + members.clear(); + pins.clear(); + a.setFocus(null); + a.clearDetail(); + void applyFocus(false); + remember(); + toast?.info( + "Diagram cleared. Project characters and relationships retained.", + ); + } + function add(id, position) { + if (!known(id)) return; + checkpoint(); + toCustom(); + members.add(+id); + const n = ensurePosition(+id, pins.has(+id) ? null : position); + a.setFocus(+id); + void applyFocus(false); + n.select(); + remember(); + } + function pin(id = a.getFocus()) { + if (!known(id) || !members.has(id)) return; + checkpoint(); + pins.has(id) ? pins.delete(id) : pins.add(id); + positions.set(id, { ...node(id).position() }); + void applyFocus(false); + remember(); + } + async function performPreset(next) { + if (!PRESETS.some(([id]) => id === next)) return; + checkpoint(); + layoutEpoch++; + if (preset === "custom") rememberCustom(); + preset = next; + familyRoot = null; + if (next !== "family" && layout === "family") { + layout = "clusters"; + familyRoutes.clear(); + visible().removeStyle("width height padding"); + } + if (next === "custom" && custom) { + members = new Set(custom.members.filter(known)); + pins = new Set(custom.pins.filter(known)); + layout = custom.layout || layout; + for (const [id, p] of Object.entries(custom.positions)) + if (known(id)) { + positions.set(+id, p); + a.ensureNode(+id).position(p); + } + cy.zoom(custom.zoom); + cy.pan(custom.pan); + } + await applyFocus(false); + if (next === "family") { + layout = "family"; + await arrange("family", { checkpoint: false }); + } + remember(); + } + function dimensions() { + return visible().map((n) => ({ + id: n.data("characterID"), + name: n.data("label"), + importance: castById.get(n.data("characterID"))?.characterImportance, + w: n.boundingBox().w, + h: n.boundingBox().h, + ...n.position(), + birthDate: family?.nodes?.find((c) => c.id === n.data("characterID")) + ?.birthDate, + })); + } + function startWorker() { + if (worker) return workerReady; + try { + worker = new Worker(w.assetUrls.worker); + workerReady = new Promise((resolve, reject) => { + worker.onmessage = (event) => { + if (event.data.ready) { + resolve(); + return; + } + const pending = pendingWorker.get(event.data.id); + if (!pending) return; + pendingWorker.delete(event.data.id); + event.data.error + ? pending.reject(Error(event.data.error)) + : pending.resolve(event.data.result); + }; + worker.onerror = () => { + reject(Error("Layout worker unavailable")); + for (const pending of pendingWorker.values()) + pending.reject(Error("Layout worker unavailable")); + pendingWorker.clear(); + worker?.terminate(); + worker = null; + }; + worker.postMessage({ + init: true, + engineUrl: w.assetUrls.engine, + familyUrl: w.assetUrls.family, + }); + }); + return workerReady; + } catch { + return Promise.reject(Error("Layout worker unavailable")); + } + } + async function calculate(input) { + try { + await startWorker(); + return await new Promise((resolve, reject) => { + const id = ++workerSequence; + pendingWorker.set(id, { resolve, reject }); + worker.postMessage({ id, graph: input }); + }); + } catch { + return geometry.layout(input); + } + } + async function pinChoice() { + if (!pins.size) return "keep"; + const dialog = $("rwPinDialog"); + return new Promise((resolve) => { + const choose = (event) => { + const button = event.target.closest("[data-pin-choice]"); + if (!button) return; + finish(button.dataset.pinChoice); + }, + cancel = (event) => { + event.preventDefault(); + finish("cancel"); + }; + function finish(value) { + dialog.removeEventListener("click", choose); + dialog.removeEventListener("cancel", cancel); + dialog.close(); + resolve(value); + } + dialog.addEventListener("click", choose); + dialog.addEventListener("cancel", cancel); + dialog.showModal(); + }); + } + async function chooseCentre() { + const dialog = $("rwCentreDialog"), + select = $("rwCentreChoice"); + select.replaceChildren( + ...cast + .filter((c) => members.has(c.characterID)) + .map((c) => new Option(c.characterName, c.characterID)), + ); + dialog.showModal(); + const chosen = await new Promise((resolve) => { + function closed() { + dialog.removeEventListener("close", closed); + resolve(dialog.returnValue === "arrange" ? +select.value : null); + } + dialog.addEventListener("close", closed); + }); + if (chosen) { + a.setFocus(chosen); + await arrange("radial"); + } + } + let familyRoutes = new Map( + Object.entries(saved?.familyRoutes || {}).map(([id, d]) => [+id, d]), + ); + async function performArrange(kind = layout, options = {}) { + if (arranging) return; + if (!members.size) { + toast?.info( + "Add characters or choose a display preset before arranging.", + ); + return; + } + if (kind === "radial" && !a.getFocus()) { + status.textContent = + "Select the central character in the diagram or character groups, then choose Focused radial."; + await chooseCentre(); + return; + } + if (!LAYOUTS.some(([id]) => id === kind)) return; + if (kind === "family") { + const choice = await pinChoice(); + if (choice === "cancel") return; + if (options.checkpoint !== false) checkpoint(); + if (choice === "release") pins.clear(); + await loadFamily(); + } else if (options.checkpoint !== false) checkpoint(); + layout = kind; + await applyFocus(false); + syncControls(); + const epoch = ++layoutEpoch, + arrangementStarted = performance.now(); + arranging = true; + status.textContent = "Arranging displayed characters…"; + app.querySelector("[data-map-reset]").disabled = true; + try { + if (kind === "family") { + visible().style({ width: 180, height: 66, padding: 0 }); + } else visible().removeStyle("width height padding"); + const nodes = dimensions(), + ids = new Set(nodes.map((n) => n.id)), + input = { + nodes, + edges: edges() + .filter((e) => ids.has(e.a) && ids.has(e.b)) + .map(({ record, ...e }) => e), + layout: kind, + focus: a.getFocus(), + depth, + viewport: { + width: graph.clientWidth, + height: graph.clientHeight, + }, + pins: Object.fromEntries( + [...pins] + .filter((id) => ids.has(id)) + .map((id) => [id, { ...node(id).position() }]), + ), + }; + const result = await calculate(input); + if (epoch !== layoutEpoch) return; + modelSync = true; + cy.batch(() => { + for (const [id, p] of Object.entries(result.positions)) + if (known(id)) { + node(+id).position(p); + positions.set(+id, p); + } + }); + modelSync = false; + familyRoutes = new Map( + kind === "family" && !pins.size + ? (result.routes || []).map((r) => [r.id, r.d]) + : [], + ); + cy.fit(visible(), 45); + if (cy.zoom() < 0.85) { + cy.zoom(0.85); + const community = + !a.getFocus() && kind === "clusters" + ? result.communities?.find((group) => + group.includes(result.preferredCenter), + ) + : null; + const centred = community + ? visible().filter((n) => + community.includes(n.data("characterID")), + ) + : node(result.preferredCenter); + if (centred.length) cy.center(centred); + if (kind === "family") { + const box = visible().boundingBox(); + cy.pan({ x: cy.pan().x, y: 45 - box.y1 * cy.zoom() }); + } + } + if (result.warnings?.length) toast?.info(result.warnings.join(" ")); + w.lastLayout = { + kind, + result, + durationMs: performance.now() - arrangementStarted, + sequence: epoch, + nodes: nodes.length, + }; + scheduleRoutes(); + remember(); + } catch (error) { + toast?.error( + "The layout could not be applied. Your diagram is retained. " + + error.message, + ); + } finally { + arranging = false; + app.querySelector("[data-map-reset]").disabled = false; + syncControls(); + status.textContent = `${members.size} displayed · ${LAYOUTS.find(([id]) => id === layout)?.[1]}.`; + } + } + function fit() { + cy.resize(); + cy.fit(visible(), 45); + remember(); + } + function reset() { + checkpoint(); + cy.zoom(1); + cy.pan({ x: 0, y: 0 }); + if (a.getFocus() && members.has(a.getFocus())) + cy.center(node(a.getFocus())); + remember(); + } + let routingBusy = false, + reroute = false, + routeVersion = 0, + draggedId = null; + async function routeEdges() { + routeFrame = null; + if (arranging) { + reroute = false; + return; + } + if (routingBusy) { + reroute = true; + return; + } + routingBusy = true; + const version = routeVersion, + started = performance.now(), + ns = dimensions(), + byId = new Map(ns.map((n) => [n.id, n])), + groups = new Map(), + es = cy.edges(":visible"), + requests = []; + for (const e of es) { + const pair = geometry.key( + +e.source().data("characterID"), + +e.target().data("characterID"), + ); + if (!groups.has(pair)) groups.set(pair, []); + groups.get(pair).push(e); + } + for (const group of groups.values()) { + group.sort( + (a, b) => a.data("relationshipID") - b.data("relationshipID"), + ); + for (let i = 0; i < group.length; i++) { + const e = group[i], + id = e.data("relationshipID"), + aId = +e.source().data("characterID"), + bId = +e.target().data("characterID"); + if (draggedId && aId !== draggedId && bId !== draggedId) continue; + requests.push({ + id, + a: aId, + b: bId, + lane: (i - (group.length - 1) / 2) * 32, + path: familyRoutes.get(id), + labelIndex: i, + }); + } + } + try { + let result; + const input = { + nodes: ns, + edges: requests, + style: effectiveConnector(), + }; + try { + await startWorker(); + result = await new Promise((resolve, reject) => { + const id = ++workerSequence; + pendingWorker.set(id, { resolve, reject }); + worker.postMessage({ id, routes: input }); + }); + } catch { + result = { routes: [] }; + for (let i = 0; i < requests.length; i++) { + const edge = requests[i]; + result.routes.push({ + id: edge.id, + ...geometry.route(ns, edge, input.style, edge.lane, edge.path), + }); + if (i % 12 === 11) + await new Promise((resolve) => requestAnimationFrame(resolve)); + } + } + if (version !== routeVersion) { + reroute = true; + return; + } + const routedById = new Map(result.routes.map((r) => [r.id, r])); + cy.batch(() => { + for (const request of requests) { + const e = cy.$id("r-" + request.id), + routed = routedById.get(request.id), + aPos = byId.get(request.a), + bPos = byId.get(request.b); + if (!e.length || !routed || !aPos || !bPos) continue; + e.removeStyle( + "curve-style control-point-distances control-point-weights segment-distances segment-weights source-endpoint target-endpoint", + ); + e.style({ + "curve-style": routed.style, + "edge-distances": "node-position", + "text-rotation": "autorotate", + "text-events": "yes", + "text-margin-y": request.labelIndex % 2 ? -10 : 10, + "text-background-opacity": 0.94, + "line-opacity": 1, + "overlay-padding": 8, + }); + if (routed.sourceEndpoint) + e.style( + "source-endpoint", + `${routed.sourceEndpoint.x}px ${routed.sourceEndpoint.y}px`, + ); + if (routed.targetEndpoint) + e.style( + "target-endpoint", + `${routed.targetEndpoint.x}px ${routed.targetEndpoint.y}px`, + ); + if (routed.points?.length) { + const dx = bPos.x - aPos.x, + dy = bPos.y - aPos.y, + len = Math.hypot(dx, dy) || 1; + e.style({ + "segment-weights": routed.points + .map( + (p) => + ((p.x - aPos.x) * dx + (p.y - aPos.y) * dy) / + (len * len), + ) + .join(" "), + "segment-distances": routed.points + .map( + (p) => ((p.y - aPos.y) * dx - (p.x - aPos.x) * dy) / len, + ) + .join(" "), + }); + } else if (routed.distance !== undefined) + e.style({ + "control-point-distances": routed.distance, + "control-point-weights": 0.5, + }); + } + }); + updateLabels(); + w.mainRoutingStats = { + edges: es.length, + routed: requests.length, + style: effectiveConnector(), + durationMs: performance.now() - started, + }; + } finally { + routingBusy = false; + if (reroute) { + reroute = false; + scheduleRoutes(); + } + } + } + function updateLabels() { + const es = cy.edges(":visible"); + cy.batch(() => { + es.forEach((e) => { + const ids = [ + +e.source().data("characterID"), + +e.target().data("characterID"), + ], + show = + allLabels || + e.hasClass("is-selected") || + e.hasClass("is-main-hover") || + (es.length < 60 && cy.zoom() >= 0.65) || + (a.getFocus() && ids.includes(a.getFocus())); + const label = show ? e.data("label") : ""; + if (e.style("label") !== label) e.style("label", label); + }); + }); + } + function scheduleRoutes() { + routeVersion++; + if (routingBusy) { + reroute = true; + return; + } + if (!routeFrame) routeFrame = requestAnimationFrame(routeEdges); + } + function selectRelationship(id) { + const r = records().find((r) => r.characterRelationshipID === +id); + if (!r) return; + selectionKind = "relationship"; + w.selectRelationship(+id, r); + a.showRelationshipDetail(); + scheduleRoutes(); + } + function editRelationship( + id = w.selectedRelationship?.characterRelationshipID, + ) { + const r = records().find((r) => r.characterRelationshipID === +id); + if (!r || !canEdit) return; + if (isFamily() && !r.initialStateEditable) { + flush(); + location.assign( + `/Characters/Details/${r.characterAID}?tab=relationships&relationshipId=${r.characterRelationshipID}`, + ); + return; + } + a.openEditor(r.characterAID, r.characterBID, isFamily() ? r : null); + } + function svg(value) { + const icon = document.createElementNS( + "http://www.w3.org/2000/svg", + "svg", + ); + icon.setAttribute("viewBox", "0 0 24 24"); + icon.setAttribute("aria-hidden", "true"); + icon.classList.add("rw-importance-icon"); + icon.dataset.tone = value.tone; + const path = document.createElementNS(icon.namespaceURI, "path"); + path.setAttribute("d", value.path); + path.setAttribute("fill", value.filled ? "currentColor" : "none"); + path.setAttribute("fill-rule", "evenodd"); + icon.append(path); + return icon; + } + // Palette homes continue to be moved by the established narrow-screen drawer. + const bottom = app.querySelector(".rw-bottom"), + unknown = document.createElement("div"); + unknown.className = "rw-unclassified"; + unknown.tabIndex = 0; + unknown.dataset.rwTier = ""; + unknown.setAttribute("role", "region"); + unknown.setAttribute("aria-label", "Unclassified character group"); + const unknownTitle = document.createElement("h3"); + unknownTitle.dataset.rwTitle = ""; + unknown.append(unknownTitle); + bottom.append(unknown); + const groups = [...app.querySelectorAll("[data-rw-tier]")]; + function refreshPaletteTitles() { + for (const group of groups) { + const value = group.dataset.rwTier, + def = definitions.find((v) => v.value === value); + if (!def) continue; + let heading = + group === app.querySelector(".rw-left") + ? app.querySelector(".rw-navigation h3") + : group.querySelector(":scope > h2,:scope > h3"); + if (!heading) { + heading = document.createElement("h3"); + group.prepend(heading); + } + const count = cast.filter( + (c) => tier(c.characterImportance) === value, + ).length; + if (group.classList.contains("rw-left") && window.innerWidth <= 800) { + heading.replaceChildren( + document.createTextNode(`All characters (${cast.length})`), + ); + continue; + } + heading.replaceChildren( + svg(def), + document.createTextNode(`${def.label} (${count})`), + ); + group.setAttribute( + "aria-label", + `${def.label}: ${count} characters. Drop a character to assign ${def.label}.`, + ); + } + } + function ensurePaletteEntry(c) { + if (app.querySelector(`[data-rw-entry="${c.characterID}"]`)) return; + const sample = app.querySelector("[data-rw-entry]"); + const entry = sample + ? sample.cloneNode(true) + : document.createElement("div"); + if (!sample) { + entry.className = "rw-entry"; + entry.dataset.pdContext = "character"; + entry.innerHTML = + 'Edit character'; + } + entry.dataset.rwEntry = c.characterID; + entry.hidden = false; + entry.classList.remove("is-focus"); + const button = entry.querySelector("[data-rw-character]"), + link = entry.querySelector("[data-rw-link]"), + edit = entry.querySelector("a.rw-edit"); + button.dataset.rwCharacter = c.characterID; + button.setAttribute("aria-label", "Focus " + c.characterName); + link.dataset.rwLink = c.characterID; + link.setAttribute( + "aria-label", + "Add relationship from " + c.characterName, + ); + edit.href = "/Characters/Edit/" + c.characterID; + const avatar = entry.querySelector(".visual-avatar"); + avatar.replaceChildren(); + const path = + c.avatarThumbnailPath || + c.avatarImagePath || + c.thumbnailPath || + c.imagePath; + if (path) { + const image = document.createElement("img"); + image.src = path; + image.alt = ""; + image.loading = "lazy"; + avatar.append(image); + } else { + const initials = document.createElement("span"); + initials.textContent = c.characterName?.slice(0, 1) || "?"; + avatar.append(initials); + } + button.addEventListener("click", () => + focusCharacter(c.characterID, true), + ); + link.addEventListener("click", () => + a.openEditor(c.characterID, a.getFocus()), + ); + for (const handle of [button, link]) { + handle.addEventListener("dragstart", (event) => + a.startDrag(event, c.characterID), + ); + handle.addEventListener("dragend", a.endSourceDrag); + } + const group = groups.find( + (g) => g.dataset.rwTier === tier(c.characterImportance), + ); + group?.append(entry); + w.paletteHomes?.set(entry, group); + } + function syncPalettes() { + for (const c of cast) if (known(c.characterID)) ensurePaletteEntry(c); + for (const entry of app.querySelectorAll("[data-rw-entry]")) { + const c = castById.get(+entry.dataset.rwEntry); + if (!c) { + w.paletteHomes?.delete(entry); + entry.remove(); + continue; + } + const group = groups.find( + (g) => g.dataset.rwTier === tier(c.characterImportance), + ); + if (group) { + w.paletteHomes?.set(entry, group); + if (window.innerWidth > 800) group.append(entry); + } + entry.querySelector("[data-rw-character]").dataset.importance = + c.characterImportance ?? ""; + const label = entry.querySelector( + "[data-rw-character]>span:not(.visual-avatar):not([data-rw-importance-indicator])", + ); + if (label) label.textContent = c.characterName; + entry + .querySelector("[data-rw-character]") + .setAttribute("aria-label", "Focus " + c.characterName); + let indicator = entry.querySelector("[data-rw-importance-indicator]"); + if (!indicator) { + indicator = document.createElement("span"); + indicator.dataset.rwImportanceIndicator = ""; + entry.querySelector("[data-rw-character]").append(indicator); + } + const def = definition(c.characterImportance); + indicator.replaceChildren(); + if (def) { + indicator.append(svg(def)); + indicator.title = "Story importance: " + def.label; + indicator.setAttribute("aria-label", indicator.title); + } + } + refreshPaletteTitles(); + a.filter(); + } + async function directory() { + const response = await fetch( + "/CharacterAttributes/Directory?" + + new URLSearchParams({ projectId: w.projectId }), + { cache: "no-store", signal: life.signal }, + ); + if (!response.ok || response.redirected) + throw Error("Character importance could not be refreshed."); + const data = await response.json(); + canEdit = data.canEdit; + let importanceChanged = false; + for (const r of data.characters) { + readVersions.set(r.id, r.version); + const c = castById.get(r.id); + if (c) { + const value = + r.values.importance === "" ? null : Number(r.values.importance); + importanceChanged ||= c.characterImportance !== value; + c.characterImportance = value; + } + } + syncPalettes(); + refreshIndicators(); + syncControls(); + return { ...data, importanceChanged }; + } + function refreshIndicators() { + const tokens = getComputedStyle(document.documentElement); + cy.batch(() => { + cy.nodes().forEach((n) => { + const c = castById.get(n.data("characterID")); + if (!c) return; + n.data("label", c.characterName); + n.data("importance", c.characterImportance ?? 0); + n.toggleClass("is-major-character", c.characterImportance >= 8); + n.toggleClass( + "is-supporting-character", + c.characterImportance >= 4 && c.characterImportance < 8, + ); + const def = definition(c.characterImportance); + if (def) { + const color = tokens + .getPropertyValue( + def.tone === "warning" + ? "--pd-warning" + : def.tone === "info" + ? "--pd-info" + : "--pd-muted", + ) + .trim(), + markup = ``; + n.data( + "importanceIcon", + "data:image/svg+xml;charset=utf-8," + + encodeURIComponent(markup), + ); + const portrait = n.data("portrait"), + pinDefinition = w.pinDefinition, + pinSvg = + pinDefinition && pins.has(c.characterID) + ? "data:image/svg+xml;charset=utf-8," + + encodeURIComponent( + ``, + ) + : null; + if (portrait) { + const images = [ + portrait, + n.data("importanceIcon"), + ...(pinSvg ? [pinSvg] : []), + ]; + n.style({ + "background-image": images, + "background-width": images.map((_, i) => (i ? 14 : 34)), + "background-height": images.map((_, i) => (i ? 14 : 34)), + "background-position-x": images.map((_, i) => + i ? "100%" : "8px", + ), + "background-position-y": images.map((_, i) => + i === 0 ? "50%" : i === 1 ? "0%" : "100%", + ), + "background-fit": images.map(() => "none"), + }); + } + } + n.style( + "border-style", + pins.has(c.characterID) ? "double" : "solid", + ); + n.style( + "border-width", + pins.has(c.characterID) || n.hasClass("is-focus") + ? 4 + : c.characterImportance >= 8 + ? 3 + : c.characterImportance >= 4 + ? 2.5 + : 2, + ); + n.style( + "border-color", + pins.has(c.characterID) || + n.hasClass("is-focus") || + c.characterImportance >= 8 + ? tokens.getPropertyValue("--pd-focus").trim() + : tokens.getPropertyValue("--pd-border").trim(), + ); + }); + }); + } + function updateAssigned(result) { + for (const r of result.characters || []) { + readVersions.set(r.id, r.version); + const c = castById.get(r.id); + if (c) { + const value = + r.values.importance === "" ? null : Number(r.values.importance); + c.characterImportance = value; + } + } + syncPalettes(); + refreshIndicators(); + void applyFocus(false); + if (a.getFocus()) a.renderCharacterDetail(); + } + async function undoImportance(token) { + if (assignBusy) return; + assignBusy = true; + try { + const response = await fetch("/CharacterAttributes/Undo", { + method: "POST", + headers: { + "Content-Type": "application/json", + RequestVerificationToken: app.querySelector( + '[name="__RequestVerificationToken"]', + ).value, + }, + body: JSON.stringify({ token }), + }); + const result = await response.json(); + if (!response.ok || !result.saved) + throw Error( + result.message || + "Importance could not be restored; a newer change may exist.", + ); + updateAssigned(result); + toast?.success("Character importance restored."); + } catch (error) { + toast?.error(error.message); + } finally { + assignBusy = false; + if (pendingHint) { + pendingHint = false; + void liveRefresh(); + } + } + } + async function assignImportance(id, value) { + if (!known(id) || assignBusy) return; + const c = castById.get(id); + if (tier(c.characterImportance) === value) { + toast?.info("That importance is already recorded."); + return; + } + if (!canEdit) { + toast?.info("This project is read-only."); + return; + } + assignBusy = true; + try { + if (!readVersions.has(id)) await directory(); + const response = await fetch("/CharacterAttributes/Assign", { + method: "POST", + headers: { + "Content-Type": "application/json", + RequestVerificationToken: app.querySelector( + '[name="__RequestVerificationToken"]', + ).value, + }, + body: JSON.stringify({ + projectId: w.projectId, + attribute: "importance", + changes: [{ id, value, version: readVersions.get(id) }], + }), + }); + let result; + try { + result = await response.json(); + } catch { + throw Error("Character importance was not saved."); + } + if (!response.ok || !result.saved) + throw Error( + result.message || "Character importance was not saved.", + ); + updateAssigned(result); + if (!result.characters.length) { + toast?.info("That importance is already recorded."); + return; + } + undoAttribute = result.undoToken; + const token = undoAttribute; + toast?.success( + `${c.characterName} classified as ${definitions.find((v) => v.value === value)?.label || "Unclassified"}.`, + { + duration: 10000, + action: { + label: "Undo importance", + run: () => undoImportance(token), + }, + }, + ); + } catch (error) { + toast?.error(error.message); + try { + await directory(); + } catch {} + } finally { + assignBusy = false; + if (pendingHint) { + pendingHint = false; + void liveRefresh(); + } + } + } + for (const group of groups) { + listen(group, "dragover", (event) => { + if ( + !canEdit || + !event.dataTransfer.types.includes( + "application/x-plotdirector-character", + ) + ) + return; + event.preventDefault(); + event.stopPropagation(); + app + .querySelectorAll(".rw-importance-drop") + .forEach((n) => n.classList.remove("rw-importance-drop")); + group.classList.add("rw-importance-drop"); + event.dataTransfer.dropEffect = "move"; + }); + listen(group, "dragleave", (event) => { + if (!group.contains(event.relatedTarget)) + group.classList.remove("rw-importance-drop"); + }); + listen(group, "drop", (event) => { + const id = +event.dataTransfer.getData( + "application/x-plotdirector-character", + ); + if (!id) return; + event.preventDefault(); + event.stopPropagation(); + group.classList.remove("rw-importance-drop"); + void assignImportance(id, group.dataset.rwTier); + }); + } + listen(document, "dragend", () => + app + .querySelectorAll(".rw-importance-drop") + .forEach((n) => n.classList.remove("rw-importance-drop")), + ); + function menuCommands(hit) { + if (hit.kind === "node") { + const id = hit.id, + c = castById.get(id); + return [ + { + label: c?.characterName || "Character", + disabled: true, + icon: "characters", + }, + { + label: "View character", + icon: "details", + run: () => { + flush(); + location.assign("/Characters/Details/" + id); + }, + }, + { + label: "Edit character", + icon: "writer", + disabled: !canEdit, + run: () => { + flush(); + location.assign("/Characters/Edit/" + id); + }, + }, + { separator: true }, + { + label: "Focus on character", + icon: "focus", + run: () => focusCharacter(id, true), + }, + { + label: "Show connected characters", + icon: "relationships", + run: () => { + a.setFocus(id); + void setPreset("selected"); + }, + }, + { + label: "Show family branch", + icon: "characters", + run: async () => { + checkpoint(); + if (preset === "custom") rememberCustom(); + a.setFocus(id); + preset = "family"; + familyRoot = id; + await applyFocus(false); + await arrange("family", { checkpoint: false }); + }, + }, + { + label: "Add relationship", + icon: "add", + disabled: !canEdit, + run: () => a.openEditor(id, null), + }, + { + label: pins.has(id) ? "Unpin position" : "Pin position", + icon: pins.has(id) ? "attribute-unpin" : "attribute-pin", + run: () => pin(id), + }, + { + label: "Story importance", + icon: "attribute-star-filled", + children: definitions.map((d) => ({ + label: d.label, + icon: d.icon, + tone: d.tone, + checked: tier(c?.characterImportance) === d.value, + disabled: !canEdit || assignBusy, + run: () => assignImportance(id, d.value), + })), + }, + { separator: true }, + { + label: "Remove from diagram", + icon: "hide-node", + run: () => remove(id), + }, + ]; + } + if (hit.kind === "edge") + return [ + { + label: + records().find((r) => r.characterRelationshipID === hit.id) + ?.relationshipTypeName || "Relationship", + icon: "relationships", + disabled: true, + }, + { + label: "View relationship details", + icon: "details", + run: () => selectRelationship(hit.id), + }, + { + label: "Edit relationship", + icon: "writer", + disabled: !canEdit, + run: () => editRelationship(hit.id), + }, + ]; + return [ + { label: "Diagram", disabled: true, icon: "relationships" }, + { label: "Fit diagram", icon: "maximise", run: fit }, + { label: "Reset view", icon: "restore", run: reset }, + { + label: "Auto-arrange", + icon: "auto-arrange", + disabled: arranging, + run: () => arrange(), + }, + { + label: "Layout", + icon: "layout", + children: LAYOUTS.map(([id, label, icon]) => ({ + label, + icon, + checked: layout === id, + disabled: arranging, + run: () => arrange(id), + })), + }, + { separator: true }, + { label: "Clear diagram", icon: "hide-node", run: clear }, + { + label: "Undo layout change", + icon: "undo", + disabled: !undoStack.length, + run: undoLayout, + }, + ]; + } + function openMenu(hit, x, y, keyboard = false, target = graph) { + menuHit = hit; + window.PlotDirectorContextMenus?.openAt(target, x, y, false); + } + const registerMenu = + window.PlotDirectorContextMenus?.register || + ((selector, provider) => + (window.PlotDirectorContextProviders ||= []).push({ + selector, + provider, + })); + registerMenu("#rwApp #relationshipMapGraph", () => ({ + commands: menuCommands(menuHit || { kind: "canvas" }), + invoker: graph, + })); + registerMenu("#rwApp [data-rw-entry]", (target) => ({ + commands: menuCommands({ + kind: "node", + id: +target.closest("[data-rw-entry]").dataset.rwEntry, + }), + invoker: target.closest("[data-rw-entry]").querySelector("button"), + })); + function renderedGeometry(edge, method) { + try { + return edge[method]?.(); + } catch { + return null; + } + } + function hitAt(event) { + const b = graph.getBoundingClientRect(), + p = { x: event.clientX - b.left, y: event.clientY - b.top }; + const n = visible() + .filter((n) => { + const b = n.renderedBoundingBox(); + return p.x >= b.x1 && p.x <= b.x2 && p.y >= b.y1 && p.y <= b.y2; + }) + .last(); + if (n.length) return { kind: "node", id: n.data("characterID") }; + let best = null, + distance = 12; + for (const e of cy.edges(":visible")) { + const curve = e.style("curve-style"); + let points = + curve === "segments" + ? renderedGeometry(e, "renderedSegmentPoints") + : null; + if (!points?.length) { + const controls = curve.includes("bezier") + ? renderedGeometry(e, "renderedControlPoints") + : null, + a = e.renderedSourceEndpoint?.() || e.source().renderedPosition(), + b = e.renderedTargetEndpoint?.() || e.target().renderedPosition(); + if (controls?.length) { + points = []; + for (let i = 0; i <= 24; i++) { + const t = i / 24, + c = controls[0]; + points.push({ + x: (1 - t) ** 2 * a.x + 2 * (1 - t) * t * c.x + t * t * b.x, + y: (1 - t) ** 2 * a.y + 2 * (1 - t) * t * c.y + t * t * b.y, + }); + } + } else points = [a, b]; + } else + points = [ + e.source().renderedPosition(), + ...points, + e.target().renderedPosition(), + ]; + for (let i = 1; i < points.length; i++) { + const a = points[i - 1], + b = points[i], + dx = b.x - a.x, + dy = b.y - a.y, + t = Math.max( + 0, + Math.min( + 1, + ((p.x - a.x) * dx + (p.y - a.y) * dy) / + (dx * dx + dy * dy || 1), + ), + ), + d = Math.hypot(p.x - a.x - t * dx, p.y - a.y - t * dy); + if (d < distance) { + distance = d; + best = { kind: "edge", id: e.data("relationshipID") }; + } + } + } + return best || { kind: "canvas" }; + } + let selectionKind = a.getFocus() ? "character" : "canvas", + lastTap = null, + middle = null; + cy.on("tap", "node", (event) => { + selectionKind = "character"; + graph.focus({ preventScroll: true }); + const id = event.target.data("characterID"), + now = performance.now(); + if (lastTap?.id === id && now - lastTap.time < 350) { + flush(); + location.assign("/Characters/Details/" + id); + } + lastTap = { id, time: now }; + }); + cy.on("tap", "edge", (event) => { + selectionKind = "relationship"; + selectRelationship(event.target.data("relationshipID")); + }); + cy.on("tap", (event) => { + if (event.target !== cy) return; + const original = event.originalEvent; + if (original) { + const hit = hitAt(original); + if (hit.kind === "edge") { + selectRelationship(hit.id); + return; + } + } + selectionKind = "canvas"; + }); + cy.on("mouseover", "edge", (event) => { + event.target.addClass("is-main-hover"); + updateLabels(); + }); + cy.on("mouseout", "edge", (event) => { + event.target.removeClass("is-main-hover"); + updateLabels(); + }); + cy.on("grab", "node", (event) => { + layoutEpoch++; + draggedId = event.target.data("characterID"); + dragSnapshot = snapshot(); + }); + cy.on("free", "node", () => { + draggedId = null; + if (dragSnapshot) { + undoStack.push(dragSnapshot); + if (undoStack.length > 24) undoStack.shift(); + dragSnapshot = null; + familyRoutes.clear(); + $("rwUndoLayout").disabled = false; + } + cy.nodes().forEach((n) => { + if (known(n.data("characterID"))) + positions.set(n.data("characterID"), { ...n.position() }); + }); + scheduleRoutes(); + remember(); + }); + cy.on("position", "node", (event) => { + if (modelSync) return; + positions.set(event.target.data("characterID"), { + ...event.target.position(), + }); + scheduleRoutes(); + remember(); + }); + cy.on("zoom", () => { + updateLabels(); + remember(); + }); + listen( + graph, + "wheel", + (event) => { + event.preventDefault(); + event.stopPropagation(); + const b = graph.getBoundingClientRect(), + delta = + event.deltaY * + (event.deltaMode === 1 + ? 16 + : event.deltaMode === 2 + ? graph.clientHeight + : 1); + cy.zoom({ + level: Math.max( + cy.minZoom(), + Math.min( + cy.maxZoom(), + cy.zoom() * + Math.exp(-Math.max(-120, Math.min(120, delta)) * 0.002), + ), + ), + renderedPosition: { + x: event.clientX - b.left, + y: event.clientY - b.top, + }, + }); + }, + { passive: false }, + ); + listen( + graph, + "pointerdown", + (event) => { + if (event.button !== 1) return; + event.preventDefault(); + event.stopImmediatePropagation(); + middle = { + pointer: event.pointerId, + x: event.clientX, + y: event.clientY, + pan: { ...cy.pan() }, + panning: cy.userPanningEnabled(), + }; + cy.userPanningEnabled(false); + graph.setPointerCapture(event.pointerId); + graph.classList.add("rw-middle-pan"); + }, + { capture: true }, + ); + listen( + graph, + "pointermove", + (event) => { + if (!middle || event.pointerId !== middle.pointer) return; + event.preventDefault(); + event.stopImmediatePropagation(); + cy.pan({ + x: middle.pan.x + event.clientX - middle.x, + y: middle.pan.y + event.clientY - middle.y, + }); + }, + { capture: true }, + ); + function endMiddle() { + if (!middle) return; + cy.userPanningEnabled(middle.panning); + middle = null; + graph.classList.remove("rw-middle-pan"); + remember(); + } + for (const e of ["pointerup", "pointercancel", "lostpointercapture"]) + listen(graph, e, endMiddle, { capture: true }); + listen(graph, "auxclick", (event) => { + if (event.button === 1) event.preventDefault(); + }); + listen( + graph, + "contextmenu", + (event) => { + if (event.ctrlKey || getSelection()?.toString()) return; + event.preventDefault(); + event.stopPropagation(); + const hit = hitAt(event); + if (hit.kind === "node") { + a.setFocus(hit.id); + selectionKind = "character"; + void applyFocus(false); + } else if (hit.kind === "edge") selectRelationship(hit.id); + openMenu(hit, event.clientX, event.clientY); + }, + { capture: true }, + ); + listen(graph, "keydown", (event) => { + if (event.target.closest("input,textarea,select,[contenteditable]")) + return; + if (event.key === "Delete" && selectionKind === "character") { + event.preventDefault(); + remove(); + } else if ( + event.key === "ContextMenu" || + (event.shiftKey && event.key === "F10") + ) { + event.preventDefault(); + event.stopPropagation(); + const b = graph.getBoundingClientRect(), + hit = + selectionKind === "character" && a.getFocus() + ? { kind: "node", id: a.getFocus() } + : selectionKind === "relationship" && w.selectedRelationship + ? { + kind: "edge", + id: w.selectedRelationship.characterRelationshipID, + } + : { kind: "canvas" }; + openMenu(hit, b.left + 40, b.top + 40, true); + } else if ( + (event.ctrlKey || event.metaKey) && + event.key.toLowerCase() === "z" + ) { + event.preventDefault(); + undoLayout(); + } else if ( + ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes( + event.key, + ) + ) { + event.preventDefault(); + const p = cy.pan(), + step = event.shiftKey ? 80 : 30; + cy.pan({ + x: + p.x + + (event.key === "ArrowLeft" + ? step + : event.key === "ArrowRight" + ? -step + : 0), + y: + p.y + + (event.key === "ArrowUp" + ? step + : event.key === "ArrowDown" + ? -step + : 0), + }); + } else if (event.key === "Home") { + event.preventDefault(); + fit(); + } + }); + listen($("rwCharacterMenu"), "click", (event) => { + if (!a.getFocus()) return; + const b = event.currentTarget.getBoundingClientRect(); + openMenu({ kind: "node", id: a.getFocus() }, b.left, b.bottom, true); + }); + listen($("rwCanvasMenu"), "click", () => { + const b = graph.getBoundingClientRect(); + openMenu({ kind: "canvas" }, b.left + 50, b.top + 40, true); + }); + listen($("rwEmptyFull"), "click", () => void setPreset("full")); + listen($("rwClearDiagram"), "click", clear); + listen($("rwUndoLayout"), "click", undoLayout); + listen($("rwClearPins"), "click", () => { + if (!pins.size) return; + checkpoint(); + pins.clear(); + void applyFocus(false); + remember(); + }); + listen( + presetControl, + "change", + () => void setPreset(presetControl.value), + ); + listen(layoutControl, "change", () => void arrange(layoutControl.value)); + listen(connectorControl, "change", () => { + checkpoint(); + connector = connectorControl.value; + syncControls(); + scheduleRoutes(); + remember(); + }); + listen(depthControl, "change", () => { + depth = +depthControl.value; + if (preset === "selected" || (preset === "family" && familyRoot)) + void applyFocus(false); + remember(); + }); + listen($("rwAllLabels"), "change", () => { + allLabels = $("rwAllLabels").checked; + scheduleRoutes(); + remember(); + }); + for (const id of ["rwLayoutOptions", "rwDiagramDisplay"]) + listen($(id), "submit", (event) => event.preventDefault()); + for (const id of ["rwMapView", "rwListView"]) + listen($(id), "click", remember); + function drop(event, id, target) { + if (!id) return; + event.preventDefault(); + const rect = graph.getBoundingClientRect(); + if (target.length && target.data("characterID") !== id) { + if (!canEdit) return; + focusCharacter(target.data("characterID"), false); + a.openEditor(id, target.data("characterID")); + } else + add(id, { + x: (event.clientX - rect.left - cy.pan().x) / cy.zoom(), + y: (event.clientY - rect.top - cy.pan().y) / cy.zoom(), + }); + } + function refreshDetail() { + if (selectionKind === "relationship" && w.selectedRelationship) { + const current = records().find( + (r) => + r.characterRelationshipID === + w.selectedRelationship.characterRelationshipID, + ); + if (current) { + w.selectRelationship(current.characterRelationshipID, current); + a.showRelationshipDetail(); + return; + } + } + if (a.getFocus()) a.renderCharacterDetail(); + else a.clearDetail(); + } + function modelUpdated(model) { + referenceRecords = null; + if (model.cast) { + for (const c of model.cast) { + const existing = castById.get(c.characterID); + if (existing) Object.assign(existing, c); + else { + cast.push(c); + castById.set(c.characterID, c); + } + } + const ids = new Set(model.cast.map((c) => c.characterID)); + for (const id of [...castById.keys()]) + if (!ids.has(id)) { + castById.delete(id); + members.delete(id); + pins.delete(id); + positions.delete(id); + node(id).remove(); + if (a.getFocus() === id) a.setFocus(null); + } + for (let i = cast.length - 1; i >= 0; i--) + if (!ids.has(cast[i].characterID)) cast.splice(i, 1); + } + for (const select of [ + $("focusCharacterId"), + document.querySelector('[name="SourceID"]'), + document.querySelector('[name="TargetID"]'), + ]) { + if (!select) continue; + const selected = select.value, + placeholder = + select.options[0]?.value === "" ? select.options[0].text : null; + select.replaceChildren( + ...(placeholder ? [new Option(placeholder, "")] : []), + ...cast.map((c) => new Option(c.characterName, c.characterID)), + ); + select.value = selected; + } + syncPalettes(); + a.decorateNodes(); + refreshIndicators(); + void applyFocus(false).then(refreshDetail); + } + async function relationshipSaved() { + familyEpoch++; + family = null; + await a.refresh(); + await applyFocus(false); + refreshDetail(); + toast?.success("Relationship saved."); + } + async function liveRefresh() { + if (assignBusy) { + pendingHint = true; + return; + } + try { + familyEpoch++; + family = null; + await Promise.all([directory(), a.refresh()]); + if (isFamily()) await loadFamily(); + await applyFocus(false); + } catch (error) { + if (error.name !== "AbortError") + toast?.error( + "Relationship data could not be refreshed. Your diagram is retained.", + ); + } + } + function wire(c) { + if (connection || !c) return; + connection = c; + c.on("ContextInvalidated", (hint) => { + if ( + (!hint.projectId || +hint.projectId === +w.projectId) && + (!hint.kind || ["characters", "relationships"].includes(hint.kind)) + ) { + if (assignBusy) pendingHint = true; + else { + clearTimeout(refreshTimer); + refreshTimer = setTimeout(() => void liveRefresh(), 180); + } + } + }); + c.onreconnected(() => void liveRefresh()); + } + listen(document, "pd-presence-connection", (event) => wire(event.detail)); + listen(document, "pd-presence-ready", () => + wire(window.PlotDirectorPresenceConnection), + ); + wire(window.PlotDirectorPresenceConnection); + function flush() { + clearTimeout(saveTimer); + try { + localStorage.setItem(storageKey, JSON.stringify(snapshot())); + } catch {} + } + listen(window, "pagehide", flush); + async function initialise() { + if (saved?.focus && known(saved.focus)) a.setFocus(saved.focus); + else if (!a.getFocus() && legacy?.focus && known(legacy.focus)) + a.setFocus(legacy.focus); + if (saved?.collapsed || legacy?.collapsed) { + board.classList.add("palettes-hidden"); + $("rwPalettes").setAttribute("aria-expanded", "false"); + } + syncControls(); + syncPalettes(); + await applyFocus(false); + if (saved) { + if (Number.isFinite(saved.zoom)) cy.zoom(saved.zoom); + if (Number.isFinite(saved.pan?.x) && Number.isFinite(saved.pan?.y)) + cy.pan(saved.pan); + a.setView(saved.view || "map"); + } else if (legacy) { + if (Number.isFinite(legacy.zoom)) cy.zoom(legacy.zoom); + if (Number.isFinite(legacy.pan?.x) && Number.isFinite(legacy.pan?.y)) + cy.pan(legacy.pan); + } else if (members.size) await arrange(layout, { checkpoint: false }); + try { + const current = await directory(); + if (current.importanceChanged) await applyFocus(false); + } catch { + status.textContent += + " Importance assignment is temporarily unavailable."; + } + syncControls(); + remember(); + initialised = true; + } + const api = { + records, + renderList, + setPreset, + applyFocus, + focusCharacter, + clearFocus, + remove, + clear, + pin, + reset, + drop, + remember, + arrange, + fit, + modelUpdated, + initialise, + undoLayout, + assignImportance, + editRelationship, + relationshipSaved, + refreshDetail, + refreshPaletteTitles, + restyle() { + refreshIndicators(); + scheduleRoutes(); + }, + get familyMode() { + return isFamily(); + }, + get preset() { + return preset; + }, + get members() { + return [...members]; + }, + get pins() { + return [...pins]; + }, + get undoCount() { + return undoStack.length; + }, + get arranging() { + return arranging; + }, + get routing() { + return routingBusy || !!routeFrame || reroute; + }, + get storageKey() { + return storageKey; + }, + dispose() { + flush(); + life.abort(); + worker?.terminate(); + cancelAnimationFrame(routeFrame); + }, + }; + Object.defineProperty(api, "initialised", { get: () => initialised }); + Object.defineProperty(api, "busy", { + get: () => !!pendingCommands || arranging || !!familyPromise, + }); + w.mainCommands = api; + return api; + }, + }; +})(); diff --git a/PlotLine/wwwroot/js/relationship-workspace.js b/PlotLine/wwwroot/js/relationship-workspace.js index ddb5e39e..a53461e8 100644 --- a/PlotLine/wwwroot/js/relationship-workspace.js +++ b/PlotLine/wwwroot/js/relationship-workspace.js @@ -15,6 +15,7 @@ if (chrome) chromeObserver.observe(chrome); new ResizeObserver(() => resizeGraph()).observe(app); function setView(view) { + if(view==='list')window.PlotDirectorRelationshipWorkspace?.mainCommands?.renderList(); document.getElementById('rwBoard').hidden = view === 'list'; document.getElementById('rwListPanel').hidden = view !== 'list'; document.getElementById('rwMapView').setAttribute('aria-pressed', String(view !== 'list')); @@ -23,6 +24,7 @@ } document.getElementById('rwMapView').addEventListener('click', () => setView('map')); document.getElementById('rwListView').addEventListener('click', () => setView('list')); + app.dataset.workspacePreferenceScope=`${document.body.dataset.pdUserId||'session'}.${app.dataset.projectId}.${app.dataset.bookId||'project'}`; window.PlotDirectorWorkspaceSurface.attach(app,document.getElementById('rwMaximise'),{className:'rw-maximised',onChange:sizeWorkspace,allowPwa:true}); document.addEventListener('keydown', event => { if (event.key === 'Escape' && app.querySelector('.rw-menu[open]')) { @@ -43,6 +45,7 @@ const editStatus = document.getElementById('rwEditStatus'); const field = name => form.elements.namedItem(name); const castById = new Map(cast.map(c => [c.characterID, c])); + let enhancement = null; const storageKey = `pd.relationship-workspace.v1.${projectId}.${workspace.bookId || 'project'}`; let requestedDefinition=Number(new URL(location.href).searchParams.get("relationshipId")); let focus = workspace.focusCharacterId, source = null, saveTimer, request = null, loading = false, stateLoaded = true; @@ -55,6 +58,8 @@ const extraNodes = new Set(restored?.extraNodes || []); const removed = new Set(restored?.removed || []); const remember = () => { + if(!enhancement && window.PlotDirectorMainRelationships)return; // Never regenerate unscoped v1 state during enhanced startup. + if(enhancement){enhancement.remember();return;} clearTimeout(saveTimer); saveTimer = setTimeout(() => { const positions = {}; @@ -77,6 +82,7 @@ return node; } function applyFocus(centre = false) { + if(enhancement){void enhancement.applyFocus(centre);return;} cy.elements().removeClass('is-focus is-dimmed'); cy.elements().show(); if (focus) { @@ -98,7 +104,8 @@ if (focus) renderCharacterDetail(); positionHandle(); } - function focusCharacter(id) { + function focusCharacter(id, centre = true) { + if(enhancement){enhancement.focusCharacter(id,centre);return;} focus = Number(id); extraNodes.add(focus); ensureNode(focus); if (cy.zoom() < .6) cy.zoom(.8); applyFocus(true); @@ -124,16 +131,16 @@ } document.getElementById('rwSearch').addEventListener('input', filter); document.querySelectorAll('[data-rw-character]').forEach(button => button.addEventListener('click', () => focusCharacter(button.dataset.rwCharacter))); - function openEditor(from, to) { + function openEditor(from, to, familyDefinition = null) { if (loading || !stateLoaded) { status.textContent = 'Wait for the timeline to finish loading.'; return; } editorRequest?.abort(); editorRequest = null; editorReady = true; form.querySelector('[type="submit"]').disabled = false; form.reset(); field('SourceID').value = from || cast[0]?.characterID || ''; field('TargetID').value = to || focus || cast[1]?.characterID || ''; - field('SceneID').value = currentScene || ''; + field('SceneID').value = familyDefinition ? '' : currentScene || ''; editStatus.textContent = ''; - editorRelationships = workspace.relationships(); + editorRelationships = familyDefinition ? [familyDefinition] : workspace.relationships(); const pair = editorRelationships.filter(r => (r.characterAID === Number(field('SourceID').value) && r.characterBID === Number(field('TargetID').value)) || (r.isReciprocal && r.characterBID === Number(field('SourceID').value) && r.characterAID === Number(field('TargetID').value))); if (pair.length === 1) { const type = [...field('TypeID').options].find(o => o.textContent === pair[0].relationshipTypeName); @@ -178,6 +185,7 @@ finally { if (active === editorRequest) submit.disabled = !editorReady; } }); document.getElementById('rwEditLine').addEventListener('click', () => { + if(enhancement?.familyMode){enhancement.editRelationship();return;} activeRelationship = workspace.selectedRelationship || activeRelationship; if (!activeRelationship) return; openEditor(activeRelationship.characterAID, activeRelationship.characterBID); @@ -222,6 +230,7 @@ graph.addEventListener('dragleave', () => cy.nodes().removeClass('is-drop-target')); graph.addEventListener('drop', event => { if (!source) return; + if(enhancement){const id=source;source=null;enhancement.drop(event,id,hit(event));cy.nodes().removeClass('is-drop-target');return;} event.preventDefault(); const id = source, target = hit(event); source = null; cy.nodes().removeClass('is-drop-target'); @@ -252,12 +261,14 @@ handle.addEventListener('dragend', () => { source = null; cy.nodes().removeClass('is-drop-target'); }); handle.addEventListener('click', () => openEditor(focus, null)); cy.style().selector('node.is-drop-target').style({ 'border-width': 6, 'border-color': '#198754', 'overlay-opacity': .15 }).update(); - cy.on('tap', 'node', event => focusCharacter(event.target.data('characterID'))); + cy.on('tap', 'node', event => focusCharacter(event.target.data('characterID'), false)); cy.on('cxttap', 'node', event => { + if(enhancement)return; focusCharacter(event.target.data('characterID')); openContext(document.querySelector(`[data-rw-entry="${focus}"]`), event.originalEvent); }); cy.on('cxttap', 'edge', event => { + if(enhancement)return; workspace.selectRelationship(event.target.data('relationshipID')); openContext(document.querySelector('.relationship-map-details'), event.originalEvent); }); @@ -273,13 +284,13 @@ document.getElementById('rwZoomIn').addEventListener('click', () => cy.zoom({ level: Math.min(2.5, cy.zoom() * 1.2), renderedPosition: { x: graph.clientWidth / 2, y: graph.clientHeight / 2 } })); document.getElementById('rwZoomOut').addEventListener('click', () => cy.zoom({ level: Math.max(.05, cy.zoom() / 1.2), renderedPosition: { x: graph.clientWidth / 2, y: graph.clientHeight / 2 } })); document.getElementById('rwCentre').addEventListener('click', () => applyFocus(true)); - document.getElementById('rwRemove').addEventListener('click', () => { if (focus) { removed.add(focus); extraNodes.delete(focus); focus = null; applyFocus(); remember(); } }); - document.getElementById('rwReset').addEventListener('click', () => { removed.clear(); document.querySelector('[data-map-reset]').click(); applyFocus(); remember(); }); + document.getElementById('rwRemove').addEventListener('click', () => { if(enhancement){enhancement.remove();return;} if (focus) { removed.add(focus); extraNodes.delete(focus); focus = null; applyFocus(); remember(); } }); + document.getElementById('rwReset').addEventListener('click', () => { if(enhancement){enhancement.reset();return;} removed.clear(); document.querySelector('[data-map-reset]').click(); applyFocus(); remember(); }); document.getElementById('rwPalettes').addEventListener('click', event => { if (window.innerWidth <= 800) { toggleCharacters(); return; } const hidden = board.classList.toggle('palettes-hidden'); event.currentTarget.setAttribute('aria-expanded', String(!hidden)); cy.resize(); applyFocus(true); remember(); }); - document.querySelector('[name="showFullNetwork"]').addEventListener('change', () => applyFocus()); + document.querySelector('[name="showFullNetwork"]').addEventListener('change', event => { if(enhancement){enhancement.setPreset(event.target.checked ? 'full' : focus ? 'selected' : 'connected');return;} applyFocus(); }); // Ordinary scrolling remains available; zoom with Ctrl/Cmd + wheel, buttons or pinch. cy.userZoomingEnabled(false); - graph.addEventListener('wheel', event => { if (!event.ctrlKey && !event.metaKey) return; event.preventDefault(); cy.zoom(Math.max(.05, Math.min(2.5, cy.zoom() * (event.deltaY < 0 ? 1.1 : .9)))); }, { passive: false }); + graph.addEventListener('wheel', event => { if(enhancement)return; if (!event.ctrlKey && !event.metaKey) return; event.preventDefault(); cy.zoom(Math.max(.05, Math.min(2.5, cy.zoom() * (event.deltaY < 0 ? 1.1 : .9)))); }, { passive: false }); let sceneExplorer = null; let changes = workspace.changeSceneIDs.map(id => scenes.findIndex(s => Number(s.value) === id) + 1).filter(n => n > 0).sort((a,b) => a-b); const changeMarks = document.getElementById('rwChanges'); @@ -338,9 +349,9 @@ changes.forEach(n => { const option = document.createElement('option'); option.value = n; option.label = scenes[n-1].text; changeMarks.append(option); }); } const visible = cy.nodes(':visible'); - visible.forEach((n,i) => { if (!restored?.positions?.[n.id()] && n.position().x === 0 && n.position().y === 0) n.position({ x: 200 + i % 6 * 190, y: 150 + Math.floor(i/6)*100 }); }); + if(!enhancement)visible.forEach((n,i) => { if (!restored?.positions?.[n.id()] && n.position().x === 0 && n.position().y === 0) n.position({ x: 200 + i % 6 * 190, y: 150 + Math.floor(i/6)*100 }); }); status.textContent = `${point.textContent}: ${model.relationships.length} relationships.`; - if (focus) renderCharacterDetail(); + if(enhancement)enhancement.refreshDetail();else if (focus) renderCharacterDetail(); else clearDetail(); } catch (error) { if (error.name !== 'AbortError') { stateLoaded = false; status.textContent = error.message; } } finally { if (active === request){loading = false;if(stateLoaded)selectRequestedDefinition(true);} } @@ -362,10 +373,9 @@ const response = await fetch(form.action, { method: 'POST', body: new FormData(form) }); if (!response.ok) throw new Error(await response.text() || 'The relationship could not be saved.'); const selected = field('SceneID').value; - timeline.value = selected ? scenes.findIndex(s => s.value === selected) + 1 : 0; - labelPoint(); + if(!enhancement?.familyMode){timeline.value = selected ? scenes.findIndex(s => s.value === selected) + 1 : 0;labelPoint();} dialog.close(); - await refresh(); applyFocus(true); remember(); + if(enhancement)await enhancement.relationshipSaved();else await refresh(); applyFocus(!enhancement); remember(); } catch (error) { editStatus.textContent = error.message; } finally { submit.disabled = false; } }); @@ -399,9 +409,9 @@ document.getElementById('relationshipMapDetail').classList.remove('d-none'); document.querySelector('[data-map-detail-title]').textContent = character.characterName; const portrait = document.querySelector('[data-map-detail-avatar]'); portrait.classList.remove('d-none'); avatar(character, portrait); - const relationships = workspace.relationships().filter(r => r.characterAID === focus || r.characterBID === focus); + const relationships = (enhancement?.records() || workspace.relationships()).filter(r => r.characterAID === focus || r.characterBID === focus); const importance = character.characterImportance || 0; - document.querySelector('[data-map-detail-category]').textContent = importance >= 8 ? 'Major' : importance >= 4 ? 'Supporting' : 'Minor / unset'; + document.querySelector('[data-map-detail-category]').textContent = workspace.importanceDefinitions?.find(value=>value.value===(importance>=8?'10':importance>=4?'6':importance>=1?'2':''))?.label || 'Unclassified'; document.querySelector('[data-map-detail-reciprocal]').textContent = `${relationships.length} relationship${relationships.length === 1 ? '' : 's'}`; document.querySelector('.relationship-map-detail-list').hidden = true; document.querySelector('[data-map-detail-notes]').textContent = ''; @@ -413,11 +423,11 @@ const otherID = r.characterAID === focus ? r.characterBID : r.characterAID; const otherName = castById.get(otherID)?.characterName || r.characterBName; button.textContent = `${otherName} · ${r.relationshipTypeName} — ${r.currentStateName}`; - button.addEventListener('click', () => { workspace.selectRelationship(r.characterRelationshipID); showRelationshipDetail(); }); + button.addEventListener('click', () => { workspace.selectRelationship(r.characterRelationshipID, r); showRelationshipDetail(); }); list.append(button); }); const history = document.querySelector('[data-map-detail-history]'); history.replaceChildren(); - relationships.flatMap(r => r.history.map(h => ({...h, type:r.relationshipTypeName}))).filter(h => h.sceneID).forEach(h => { + relationships.flatMap(r => (r.history || []).map(h => ({...h, type:r.relationshipTypeName}))).filter(h => h.sceneID).forEach(h => { const item = document.createElement('li'); item.textContent = `${h.label}: ${h.type} — ${h.stateName}`; history.append(item); }); } @@ -456,10 +466,11 @@ const width = graph.clientWidth, height = graph.clientHeight; if (!width || !height) return; const changed = width !== graphWidth || height !== graphHeight; const pan = cy.pan(); cy.resize(); - if (changed && focus) cy.center(cy.$id(`c-${focus}`)); else cy.pan(pan); + cy.pan(pan); graphWidth = width; graphHeight = height; positionHandle(); }; const homes = new Map([...document.querySelectorAll('[data-rw-entry]')].map(e => [e,e.parentElement])); + workspace.paletteHomes=homes; const supportingTitle = document.querySelector('.rw-navigation h3').textContent; const adaptPalettes = () => { const mobile = window.innerWidth <= 800; @@ -467,7 +478,7 @@ homes.forEach((home, entry) => (mobile ? left : home).append(entry)); document.querySelector('.rw-navigation h3').textContent = mobile ? `All characters (${cast.length})` : supportingTitle; if (!mobile) { board.classList.remove('mobile-characters','mobile-detail'); } - resizeGraph(); + enhancement?.refreshPaletteTitles();resizeGraph(); }; const breakpoint = matchMedia('(max-width:800px)'); breakpoint.addEventListener('change', adaptPalettes); adaptPalettes(); document.getElementById('rwCharacters').addEventListener('click', toggleCharacters); @@ -476,7 +487,7 @@ const active = board.classList.toggle('mobile-detail'); board.classList.remove('mobile-characters'); document.getElementById('rwInfo').setAttribute('aria-expanded', String(active)); }); - document.getElementById('rwClearFocus').addEventListener('click', () => { focus = null; applyFocus(); clearDetail(); remember(); }); + document.getElementById('rwClearFocus').addEventListener('click', () => { if(enhancement){enhancement.clearFocus();return;} focus = null; applyFocus(); clearDetail(); remember(); }); document.getElementById('rwFocusName').addEventListener('click', () => applyFocus(true)); document.getElementById('rwDetailConnect').addEventListener('click', () => openEditor(null, focus)); document.getElementById('rwSelect').addEventListener('click', () => setPanMode(false)); @@ -484,7 +495,7 @@ document.querySelector('.relationship-map-list').addEventListener('click', event => { if (event.target.closest('button')) showRelationshipDetail(); }); decorateNodes(); cy.on('add', 'node', () => decorateNodes()); - const themeObserver = new MutationObserver(() => { workspace.refreshStyle(); decorateNodes(); }); + const themeObserver = new MutationObserver(() => { workspace.refreshStyle(); decorateNodes(); enhancement?.restyle(); }); themeObserver.observe(document.documentElement, { attributes:true, attributeFilter:['data-app-theme'] }); window.addEventListener('pd:relationship-selected', showRelationshipDetail); sizeWorkspace(); @@ -495,6 +506,9 @@ document.getElementById('rwPan').setAttribute('aria-pressed', String(active)); } initialisePresentation(); + enhancement=window.PlotDirectorMainRelationships?.mount({app,workspace,cy,graph,board,cast,castById,legacy:restored, + getFocus:()=>focus,setFocus:id=>{focus=id;},ensureNode,renderCharacterDetail,clearDetail,showDetail,showRelationshipDetail,openEditor,refresh,filter,positionHandle,setView,decorateNodes,startDrag,endSourceDrag:()=>{source=null;cy.nodes().removeClass('is-drop-target');}}); + if(enhancement){void enhancement.initialise();}else{ extraNodes.forEach(id => ensureNode(id)); if (restored?.positions) cy.nodes().forEach(node => { const p = restored.positions[node.id()]; if (Number.isFinite(p?.x) && Number.isFinite(p?.y)) node.position(p); }); if (!focus && castById.has(restored?.focus)) focus = restored.focus; @@ -504,6 +518,7 @@ applyFocus(!!workspace.focusCharacterId); if (focus && window.innerWidth > 800) showDetail(); + } function selectRequestedDefinition(consume=false){if(!requestedDefinition)return;const definition=workspace.relationships().find(r=>r.characterRelationshipID===requestedDefinition);if(definition){workspace.selectRelationship(requestedDefinition);showRelationshipDetail();}else if(!loading)status.textContent="The requested definition is not established at this story point. Select its applicable story point to review it.";if(consume)requestedDefinition=0;} selectRequestedDefinition();setTimeout(()=>{if(!loading&&stateLoaded)requestedDefinition=0;},0); })(); diff --git a/PlotLine/wwwroot/js/workspace-surface.js b/PlotLine/wwwroot/js/workspace-surface.js index a610c8a3..759a9be9 100644 --- a/PlotLine/wwwroot/js/workspace-surface.js +++ b/PlotLine/wwwroot/js/workspace-surface.js @@ -17,9 +17,17 @@ const sides = single ? ['left'] : ['left', 'right']; const minimum = single?.minimum ?? 150; const maximum = () => single ? Math.max(minimum, Math.min(single.maximum ?? Infinity, layout.clientWidth - single.remaining - 16)) : 480; - const key = `plotdirector.workspace.panels.${name}`; + const key = `plotdirector.workspace.panels.${name}${app.dataset.workspacePreferenceScope ? "."+app.dataset.workspacePreferenceScope : ""}`; let saved = {}; - try { saved = JSON.parse(localStorage.getItem(key) || '{}') || {}; } catch { /* Optional preferences. */ } + try { + let stored = localStorage.getItem(key); + if (stored === null && app.dataset.workspacePreferenceScope) { + const legacyKey = `plotdirector.workspace.panels.${name}`; + const legacy = localStorage.getItem(legacyKey); + if (legacy) { stored = legacy; localStorage.setItem(key, legacy); localStorage.removeItem(legacyKey); } + } + saved = JSON.parse(stored || '{}') || {}; + } catch { /* Optional preferences. */ } const widths = { ...defaults }; for (const side of sides) if (Number.isFinite(saved[side])) widths[side] = Math.max(minimum, Math.min(single ? Infinity : 480, saved[side])); const handles = {};