diff --git a/Docs/Relationships/Workspace.md b/Docs/Relationships/Workspace.md new file mode 100644 index 00000000..00cb14da --- /dev/null +++ b/Docs/Relationships/Workspace.md @@ -0,0 +1,29 @@ +# Relationships Workspace + +## Investigation and implementation boundary + +The previous `RelationshipMap/Index` page offered GET selectors for book, chapter, scene and character focus; a Cytoscape graph; category legend; detail/history pane; and conventional relationship listing. Circle/COSE layouts and node dragging existed, but there was no saved layout. Cytoscape already supplied panning and zooming. The page had no direct editing workflow and did not render the graph when there were no links. + +`RelationshipMapService` reads `ICharacterRepository.GetRelationshipMapAsync`, groups canonical `RelationshipEvent` records by relationship, and resolves state in manuscript order. `CharacterRelationship` holds the factual type, optional initial book, initial state/intensity, reciprocal status and notes. Events hold a scene, state/intensity, awareness and description. Existing character detail forms use `ICharacterService.SaveInitialRelationshipAsync`; scene editing uses `AddRelationshipEventAsync` and `UpdateRelationshipEventAsync`. The workspace uses these same services and stored-procedure repositories. No schema, SQL or migration is added. + +Existing graph category colours, labels, intensity widths, hover text, selected-line styling and history rendering are retained in `_GraphScripts`. Focus Mode still displays the chosen character's immediate network or dims the unrelated full network. Client navigation now applies that same rule without a page reload. Map and list update from the same server response. Timeline reads the existing state resolver rather than computing a second relationship state in JavaScript. The resolver also excludes archived records and relationships before their recorded starting scene/book. + +Characters have numeric `CharacterImportance`; existing graph thresholds are 8+ and 4+. Palettes use those thresholds, splitting supporting characters between the sides. Names and avatar/portrait paths come from the existing character records. Only real importance data is offered as a filter. Each character has one palette entry with a lazy portrait. The timeline uses a native range input and change markers instead of hundreds of labels. + +Character analysis exposes a generated `Summary` and run/completion metadata (`CharacterEnrichmentCharacterStatus`), and structured enrichment results. Summary length is measurable but is a generated output with no calibrated relationship to importance. A separate suggestion feature should combine scene presence and POV evidence with analysis coverage, evaluate ranking across several books, and require author acceptance. This pass deliberately does not infer or change author importance. + +PWA context menus discover commands from `data-pd-context` regions and invoke their original controls. Palette, canvas and detail actions participate in this existing system; graph context gestures select a node/line and route to the appropriate region. Browser fallback and touch/keyboard users have explicit buttons and native select controls. No new menu framework or browser confirmation is used. + +## Layout and limits + +Positions, extra/removed nodes, focus, pan, zoom and palette collapse are stored locally by project and selected book, with a 250ms debounce. Browser profiles provide local user separation; settings do not roam between devices. Reset layout is local and never deletes canonical characters or relationships. + +On narrow displays, the four palettes become horizontal scrolling rows above/below the canvas. All palettes can be collapsed. Explicit zoom controls and Ctrl/Cmd-wheel avoid taking over ordinary wheel scrolling. Touch users can pinch and use the relationship dialog without dragging. + +The timeline spans project manuscript order, consistent with the existing scene selectors. Initial means project start; End resolves the last scene. Book-specific initial boundaries on existing records are preserved. Changes to an existing relationship at a scene update its canonical event at that scene; additional changes create events on that relationship. Different factual types remain separate relationships. Ambiguous duplicate records produce a conflict for review rather than an arbitrary overwrite. Concurrent creation from separate browser sessions remains subject to the existing stored procedure's concurrency guarantees; no new database uniqueness constraint is claimed. + +Not included: cross-device layout storage, automatic importance suggestions, timeline animation playback, deleting canonical relationships from the canvas, or a rewrite of character/continuity systems. Character detail editing remains the place for archival and advanced canonical metadata. Scene changes affect state, intensity and awareness; mutual status belongs to the relationship itself. Database-backed live smoke testing and deployment are separate operational steps. + +## Verification + +`RelationshipWorkspaceTests` exercises a 75-character, 74-relationship, 300-scene fixture, importance ordering, temporal carry-forward, canonical map/list correspondence, existing Focus Mode, reciprocal edits, same-scene updates and invalid project selections. Browser coverage is in `PlotLine.Tests/Browser/relationship-workspace.cjs`, using the isolated compiled Razor host and mocked HTTP responses for interaction checks. No live manuscript/database writes are required. diff --git a/PlotLine.Tests/Browser/package.json b/PlotLine.Tests/Browser/package.json index a02a2167..0c21db68 100644 --- a/PlotLine.Tests/Browser/package.json +++ b/PlotLine.Tests/Browser/package.json @@ -14,7 +14,8 @@ "test:pwa-context": "xvfb-run -a node pwa-context-menu.cjs", "test:scene-workspace": "xvfb-run -a node scene-workspace.cjs", "test:desktop-promotion": "node desktop-promotion.cjs", - "test:record-workspaces": "node record-workspaces.cjs" + "test:record-workspaces": "node record-workspaces.cjs", + "test:relationships": "node relationship-workspace.cjs" }, "devDependencies": { "chart.js": "4.4.9", diff --git a/PlotLine.Tests/Browser/relationship-workspace.cjs b/PlotLine.Tests/Browser/relationship-workspace.cjs new file mode 100644 index 00000000..3dee104e --- /dev/null +++ b/PlotLine.Tests/Browser/relationship-workspace.cjs @@ -0,0 +1,115 @@ +const { chromium } = require('playwright'); +const assert = require('node:assert/strict'); +const base = 'http://127.0.0.1:5238'; +(async () => { + const browser = await chromium.launch(); + const errors = []; + try { + const context = await browser.newContext({ viewport: { width: 1600, height: 1100 } }); + const page = await context.newPage(); + page.on('pageerror', e => errors.push(e.message)); + let state, posted; + await page.route('**/RelationshipMap/State?**', async route => { + const scene = Number(new URL(route.request().url()).searchParams.get('sceneId')); + const model = structuredClone(state); + if (scene >= 100 && scene < 200) model.relationships.find(r => r.characterRelationshipID === 1).currentStateName = 'Distrustful'; + await route.fulfill({ json: model }); + }); + 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); + 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') })) }; + }); + assert.equal(await page.locator('[data-rw-character]').count(), 75); + await page.locator('[data-map-fit]').click(); + assert(await page.evaluate(() => { const cy = window.PlotDirectorRelationshipWorkspace.cy, box = cy.nodes(':visible').renderedBoundingBox(); return box.w <= cy.width()+1 && box.h <= cy.height()+1; }), 'Fit all contains the large cast'); + for (const [side, min, max] of [['top',8,10],['left',4,7],['right',4,7],['bottom',0,3]]) { + const values = await page.locator(`.rw-${side} [data-rw-character]`).evaluateAll(nodes => nodes.map(n => Number(n.dataset.importance))); + assert(values.length && values.every(n => n >= min && n <= max), side + ' importance population'); + } + const filteringMs = await page.evaluate(() => { const start = performance.now(); const search = document.getElementById('rwSearch'); for (let i=0;i<100;i++) { search.value = i%2 ? 'cast' : 'elan'; search.dispatchEvent(new Event('input')); } return performance.now()-start; }); + assert(filteringMs < 1500, '100 large-cast filter updates remain responsive'); + console.log(`75-character filtering: ${filteringMs.toFixed(1)}ms for 100 updates`); + await page.locator('#rwSearch').fill('elan'); + assert.equal(await page.locator('[data-rw-entry]:not([hidden])').count(), 1, 'accent-insensitive search'); + await page.locator('[data-rw-character="1"]').click(); + let centred = await page.evaluate(() => { + const cy = window.PlotDirectorRelationshipWorkspace.cy, p = cy.$id('c-1').renderedPosition(); + return Math.abs(p.x - cy.width()/2) < 2 && Math.abs(p.y - cy.height()/2) < 2 && cy.$id('c-1').hasClass('is-focus'); + }); + assert(centred, 'click focuses and centres'); + await page.locator('#rwSearch').fill(''); + await page.locator('#rwImportance').selectOption('major'); + assert.equal(await page.locator('[data-rw-entry]:not([hidden]) [data-rw-character][data-importance="3"]').count(), 0); + await page.locator('#rwImportance').selectOption(''); + // Exercise actual HTML drag events with a DataTransfer and rendered Cytoscape hit-testing. + async function drag(id, target, mapHandle = false) { + await page.evaluate(({id,target,mapHandle}) => { + const button = mapHandle ? document.querySelector('[aria-label="Drag to another character, or click to add a relationship"]') : document.querySelector(`[data-rw-character="${id}"]`), graph = document.getElementById('relationshipMapGraph'); + const cy = window.PlotDirectorRelationshipWorkspace.cy; + const p = target ? cy.$id(`c-${target}`).renderedPosition() : { x: 24, y: 24 }; + const box = graph.getBoundingClientRect(), dataTransfer = new DataTransfer(); + button.dispatchEvent(new DragEvent('dragstart', { bubbles: true, dataTransfer })); + for (const type of ['dragover','drop']) graph.dispatchEvent(new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer, clientX: box.left+p.x, clientY: box.top+p.y })); + }, {id,target,mapHandle}); + } + 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 drag(1, 2, true); + await page.locator('#rwDialog[open]').waitFor(); + assert.equal(await page.locator('[name="SourceID"]').inputValue(), '1', 'map connector supplies source'); + await page.keyboard.press('Escape'); + await drag(2, 1); + await page.locator('#rwDialog[open]').waitFor(); + assert.equal(await page.locator('[name="SourceID"]').inputValue(), '2'); + assert.equal(await page.locator('[name="TargetID"]').inputValue(), '1'); + assert.equal(await page.locator('[name="SceneID"]').inputValue(), ''); + const zoom = await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.zoom()); + await page.locator('#rwForm [type="submit"]').click(); + await page.waitForFunction(() => !document.getElementById('rwDialog').open); + await page.waitForTimeout(300); + assert(posted.includes('SourceID') && posted.includes('__RequestVerificationToken'), 'canonical POST with antiforgery token'); + 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.waitForTimeout(250); + assert.match(await page.locator('.relationship-map-list').innerText(), /Distrustful/, 'timeline and list share state'); + await page.locator('#rwConnect').focus(); await page.keyboard.press('Enter'); + assert.equal(await page.locator('[name="SceneID"]').inputValue(), '100', 'timeline defaults editor scene'); + await page.keyboard.press('Escape'); + await page.locator('#rwNext').click(); await page.waitForTimeout(300); + assert.equal(await page.locator('#rwTimeline').inputValue(), '200'); + await page.locator('#rwPrevious').click(); await page.waitForTimeout(300); + assert.equal(await page.locator('#rwTimeline').inputValue(), '100'); + await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.zoom(.7)); + await page.waitForTimeout(350); + await page.reload(); await page.waitForFunction(() => !!window.PlotDirectorRelationshipWorkspace); + assert(Math.abs(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.zoom()) - .7) < .01, 'layout restores zoom'); + for (const width of [1200, 700, 390]) { + await page.setViewportSize({ width, height: 1100 }); + const dimensions = await page.locator('#rwBoard').evaluate(e => ({ width: e.clientWidth, scroll: e.scrollWidth, canvas: document.getElementById('relationshipMapGraph').clientWidth })); + assert(dimensions.scroll <= dimensions.width + 1 && dimensions.canvas >= 200, 'usable canvas at ' + width); + } + // Existing application menu discovery in installed mode, plus keyboard fallback. + const pwa = await browser.newContext({ viewport: { width: 1600, height: 1100 } }); + 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.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.locator('.pd-context-popup').waitFor(); + assert.match(await app.locator('.pd-context-popup').innerText(), /Edit at timeline point/, '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'); + assert.deepEqual(errors, []); + console.log('PASS Relationships workspace: 75 cast, 300 scenes, focus, search, drag/drop, editor, timeline, persistence, responsive layout and PWA menu'); + } finally { await browser.close(); } +})().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 8e7a272b..37d43132 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -67,6 +67,7 @@ var tests = new (string Name, Action Test)[] ("Exception review uses evidence, identity, consequence and directional conflicts", ExceptionReviewTests.DomainPolicy), ("Exception assessment preserves author decisions and scene history", ExceptionReviewTests.PreserveDecisionsAndObservations), ("Character card widths reflect displayed text without changing character data", CharacterCardLayoutTests.DisplayedContent), + ("Relationships workspace large cast, temporal states and canonical edits", RelationshipWorkspaceTests.StateAndEditing), ("Scene relationship proposals preserve direction and validate acceptance", RelationshipDevelopmentTests.SceneReviewAndAcceptance), ("Location and asset merges require confirmation and distinct records", EntityMergeTests.ConfirmationAndDistinctRecordsAreRequired), ("Location persisted analysis preserves contextual bedrooms and setting provenance", LocationSignificanceTests.PersistedAnalysisKeepsContextAndParentEvidence), diff --git a/PlotLine.Tests/RelationshipWorkspaceTests.cs b/PlotLine.Tests/RelationshipWorkspaceTests.cs new file mode 100644 index 00000000..cee1dac4 --- /dev/null +++ b/PlotLine.Tests/RelationshipWorkspaceTests.cs @@ -0,0 +1,95 @@ +using System.Reflection; +using Microsoft.AspNetCore.Mvc; +using PlotLine.Controllers; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; +using PlotLine.ViewModels; + +internal static class RelationshipWorkspaceTests +{ + public static RelationshipMapData Data() => new() + { + Books = [new() { BookID = 12, ProjectID = 7, BookNumber = 1 }], + Chapters = [new() { ChapterID = 21, BookID = 12, ChapterNumber = 1 }], + Scenes = Enumerable.Range(1, 300).Select(i => new Scene { SceneID = i, ChapterID = 21, SceneNumber = i, SceneTitle = $"Scene {i}", SortOrder = i }).ToList(), + Characters = Enumerable.Range(1, 75).Select(i => new Character { CharacterID = i, ProjectID = 7, CharacterName = i == 1 ? "Élan Vale" : $"Cast {i:00}", CharacterImportance = i % 11 }).ToList(), + Relationships = Enumerable.Range(1, 74).Select(i => new CharacterRelationship { CharacterRelationshipID = i, ProjectID = 7, CharacterAID = 1, CharacterBID = i + 1, CharacterAName = "Élan Vale", CharacterBName = $"Cast {i + 1:00}", RelationshipTypeID = 1, RelationshipTypeName = "Friend", RelationshipCategoryName = "Friendship", IsInitialRelationship = true, InitialRelationshipStateID = 1, InitialRelationshipStateName = "Friendly", IsReciprocal = true }).ToList(), + RelationshipCategories = [new() { RelationshipCategoryID = 1, CategoryName = "Friendship" }], + RelationshipEvents = [new() { RelationshipEventID = 91, CharacterRelationshipID = 1, SceneID = 100, RelationshipStateID = 2, RelationshipStateName = "Distrustful" }, new() { RelationshipEventID = 92, CharacterRelationshipID = 1, SceneID = 200, RelationshipStateID = 1, RelationshipStateName = "Friendly" }] + }; + public static CharacterLookupData Lookups() => new() + { + RelationshipTypes = [new() { RelationshipTypeID = 1, TypeName = "Friend", 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 + { + "GetRelationshipMapAsync" => Task.FromResult(data), + "ListCharactersAsync" => Task.FromResult(data.Characters), + "GetLookupsAsync" => Task.FromResult(Lookups()), + _ => throw new Exception(m) + }); + public static RelationshipMapService Service(RelationshipMapData data) => new(Stub((m, _) => m switch + { + "GetAsync" => Task.FromResult(new() { ProjectID = 7, ProjectName = "Cast fixture" }), + _ => throw new Exception(m) + }), Repository(data)); + public static async Task Fixture() => (await Service(Data()).GetAsync(7, null, null, null, null, true))!; + public static void StateAndEditing() => Run().GetAwaiter().GetResult(); + private static async Task Run() + { + var data = Data(); var service = Service(data); + var initial = (await service.GetAsync(7, null, null, null, null, true))!; + Check(initial.Cast.Count == 75 && initial.Cast.Select(x => x.CharacterID).Distinct().Count() == 75, "complete cast without duplication"); + Check(initial.Cast.Select(x => x.CharacterImportance).SequenceEqual(initial.Cast.Select(x => x.CharacterImportance).OrderDescending()), "importance ordering"); + Check(initial.SceneOptions.Count == 300 && initial.ChangeSceneIDs.Order().SequenceEqual(new[] { 100, 200 }), "long timeline and change markers"); + Check(initial.Relationships.First().CurrentStateName == "Friendly", "initial state"); + foreach (var (scene, expected) in new[] { (99,"Friendly"), (100,"Distrustful"), (199,"Distrustful"), (200,"Friendly"), (300,"Friendly") }) + { + var point = (await service.GetAsync(7, null, null, scene, null, true))!; + Check(point.Relationships.Single(x => x.CharacterRelationshipID == 1).CurrentStateName == expected, $"state after scene {scene}"); + Check(point.Links.Count == point.Relationships.Count && point.Links.All(l => point.Relationships.Any(r => r.CharacterRelationshipID == l.CharacterRelationshipID && r.CssClass == l.CssClass)), "canonical map/list lines"); + } + var dated = new RelationshipMapData { Characters = data.Characters, Books = data.Books, Chapters = data.Chapters, Scenes = data.Scenes, + Relationships = [new() { CharacterRelationshipID = 800, CharacterAID = 3, CharacterBID = 4, StartSceneID = 150, RelationshipTypeName = "Friend" }] }; + Check(!(await Service(dated).GetAsync(7, null, null, 149, null, true))!.Relationships.Any(), "future relationship hidden"); + Check((await Service(dated).GetAsync(7, null, null, 150, null, true))!.Relationships.Count == 1, "dated relationship starts on its scene"); + var focused = (await service.GetAsync(7, null, null, 100, 2, false))!; + 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 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(((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"); + Check(((RelationshipEventCreateViewModel)saves.Single()).RelationshipEventID == 91, "same-scene event updates rather than duplicates"); + saves.Clear(); edit.SceneID = 101; + await controller.Save(edit); + Check(((RelationshipEventCreateViewModel)saves.Single()).CharacterRelationshipID == 1, "new scene change uses existing record"); + saves.Clear(); edit.SourceID = 3; edit.TargetID = 4; edit.SceneID = null; + Check(await controller.Save(edit) is OkResult, "new initial relationship"); + Check(((InitialRelationshipEditViewModel)saves.Single()).CharacterRelationshipID == 0, "new initial uses canonical creation"); + saves.Clear(); edit.SceneID = 50; + Check(await controller.Save(edit) is OkResult, "new scene-specific relationship"); + Check(((RelationshipEventCreateViewModel)saves.Single()).CharacterRelationshipID is null && ((RelationshipEventCreateViewModel)saves.Single()).IsReciprocal, "new scene relationship preserves mutual status"); + saves.Clear(); edit.SourceID = 999; + Check(await controller.Save(edit) is BadRequestObjectResult && saves.Count == 0, "reject foreign character without writes"); + edit.SourceID = 1; edit.TargetID = 1; + 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"); + } + private static void Check(bool condition, string message) { if (!condition) throw new Exception(message); } + private static T Stub(Func invoke) where T : class + { + var proxy = DispatchProxy.Create(); ((Proxy)(object)proxy).Handler = invoke; return proxy; + } + public class Proxy : DispatchProxy + { + public Func Handler = null!; + protected override object? Invoke(MethodInfo? method, object?[]? args) => Handler(method!.Name, args); + } +} diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index d7075148..81ab4f6c 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -159,7 +159,7 @@ internal static class ToolbarBrowserHost if (dashboardPage) model.ActiveSection = "Overview"; if (timelinePage) model.ActiveSection = "Timeline"; var appearance = await context.RequestServices.GetRequiredService().GetAsync(int.Parse(context.User.FindFirstValue(ClaimTypes.NameIdentifier)!)); - var route = new RouteData(); route.Values["controller"] = dashboardPage ? "Projects" : "StoryCalendar"; route.Values["action"] = dashboardPage ? "Details" : "Index"; + var route = new RouteData(); route.Values["controller"] = context.Request.Query["page"] == "relationships" ? "RelationshipMap" : dashboardPage ? "Projects" : "StoryCalendar"; route.Values["action"] = dashboardPage ? "Details" : "Index"; var action = new ActionContext(context, route, new ActionDescriptor()); async Task Render(string name, object? viewModel = null) { @@ -207,7 +207,7 @@ internal static class ToolbarBrowserHost calendar.EarliestStoryDate = new DateOnly(2026, 10, 3); calendar.LatestStoryDate = new DateOnly(2026, 10, 24); } - var surface = dashboardPage ? "" : await Render("StoryCalendar/_StoryCalendarSurface", calendar); + var surface = dashboardPage || context.Request.Query["page"] == "relationships" ? "" : await Render("StoryCalendar/_StoryCalendarSurface", calendar); if (timelinePage) { surface = """ @@ -313,6 +313,12 @@ internal static class ToolbarBrowserHost // The fixture renders a partial page; include its normal Scripts section explicitly. surface += ""; } + if (context.Request.Query["page"] == "relationships") + { + var relationships = await RelationshipWorkspaceTests.Fixture(); + surface = await Render("RelationshipMap/Index", relationships); + surface += await Render("RelationshipMap/_GraphScripts", relationships); + } surface += await Render("Shared/_ConfirmationDialog"); var initialTheme = appearance.ThemeKey ?? "warm-light"; var appearanceScript = ""; diff --git a/PlotLine/Controllers/RelationshipMapController.cs b/PlotLine/Controllers/RelationshipMapController.cs index a522e4f2..6910a3fd 100644 --- a/PlotLine/Controllers/RelationshipMapController.cs +++ b/PlotLine/Controllers/RelationshipMapController.cs @@ -2,18 +2,95 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using PlotLine.Models; using PlotLine.Services; +using PlotLine.Data; +using PlotLine.ViewModels; namespace PlotLine.Controllers; [Authorize] -public sealed class RelationshipMapController(IRelationshipMapService relationshipMap) : Controller +public sealed class RelationshipMapController(IRelationshipMapService relationshipMap, ICharacterRepository repository, ICharacterService characters) : Controller { public async Task Index(int projectId, int? bookId, int? chapterId, int? sceneId, int? focusCharacterId, bool showFullNetwork = false) { var position = StoryPosition.FromTimelineSelection(projectId, bookId, chapterId, sceneId); var model = position is null ? null - : await relationshipMap.GetAsync(position, focusCharacterId, showFullNetwork); - return model is null ? NotFound() : View(model); + : await relationshipMap.GetAsync(position, null, true); + if (model is null) return NotFound(); + model.FocusCharacterID = focusCharacterId; + model.ShowFullNetwork = showFullNetwork; + foreach (var node in model.Nodes) node.IsFocus = node.CharacterID == focusCharacterId; + return View(model); + } + + [HttpGet] + public async Task State(int projectId, int? bookId, int? sceneId) + { + var model = await relationshipMap.GetAsync(projectId, bookId, null, sceneId, null, true); + return model is null ? NotFound() : Json(model); + } + + [HttpPost] + [ValidateAntiForgeryToken] + public async Task Save(WorkspaceRelationshipEdit model) + { + if (!ModelState.IsValid) return BadRequest("Check the relationship fields."); + var data = await repository.GetRelationshipMapAsync(model.ProjectID); + var lookups = await repository.GetLookupsAsync(model.ProjectID); + if (model.SourceID == model.TargetID + || !data.Characters.Any(x => x.CharacterID == model.SourceID) + || !data.Characters.Any(x => x.CharacterID == model.TargetID) + || !lookups.RelationshipTypes.Any(x => x.RelationshipTypeID == model.TypeID) + || !lookups.RelationshipStates.Any(x => x.RelationshipStateID == model.StateID) + || (model.SceneID.HasValue && !data.Scenes.Any(x => x.SceneID == model.SceneID))) + return BadRequest("Choose valid characters, type, state and scene from this project."); + var matches = data.Relationships.Where(x => !x.IsArchived && x.RelationshipTypeID == model.TypeID + && ((x.CharacterAID == model.SourceID && x.CharacterBID == model.TargetID) + || (x.IsReciprocal && x.CharacterAID == model.TargetID && x.CharacterBID == model.SourceID))).ToList(); + if (matches.Count > 1) return Conflict("Multiple matching relationships exist. Review them in the character details before editing."); + var existing = matches.SingleOrDefault(); + if (model.SceneID.HasValue) + { + var previous = data.RelationshipEvents.Where(x => x.CharacterRelationshipID == existing?.CharacterRelationshipID && x.SceneID == model.SceneID) + .OrderByDescending(x => x.RelationshipEventID).FirstOrDefault(); + var change = new RelationshipEventCreateViewModel + { + RelationshipEventID = previous?.RelationshipEventID ?? 0, + CharacterRelationshipID = existing?.CharacterRelationshipID, + SceneID = model.SceneID.Value, CharacterAID = model.SourceID, CharacterBID = model.TargetID, + RelationshipTypeID = model.TypeID, RelationshipStateID = model.StateID, Intensity = model.Intensity, + IsReciprocal = model.Mutual, Description = model.Notes, IsKnownToOtherCharacter = model.Known, ReturnProjectID = model.ProjectID + }; + if (previous is null) await characters.AddRelationshipEventAsync(change); + else await characters.UpdateRelationshipEventAsync(change); + } + else + { + await characters.SaveInitialRelationshipAsync(new InitialRelationshipEditViewModel + { + CharacterRelationshipID = existing?.CharacterRelationshipID ?? 0, + ProjectID = model.ProjectID, CharacterID = existing?.CharacterAID ?? model.SourceID, + RelatedCharacterID = existing?.CharacterBID ?? model.TargetID, RelationshipTypeID = model.TypeID, + InitialBookID = existing?.InitialBookID, InitialRelationshipStateID = model.StateID, + InitialIntensity = model.Intensity, IsReciprocal = model.Mutual, ReaderInitiallyKnows = model.Known, Notes = model.Notes + }); + } + return Ok(); } } + +public sealed class WorkspaceRelationshipEdit +{ + public int ProjectID { get; set; } + public int SourceID { get; set; } + public int TargetID { get; set; } + public int TypeID { get; set; } + public int StateID { get; set; } + public int? SceneID { get; set; } + [System.ComponentModel.DataAnnotations.Range(1, 10)] + public int? Intensity { get; set; } + public bool Mutual { get; set; } + public bool Known { get; set; } + [System.ComponentModel.DataAnnotations.StringLength(4000)] + public string? Notes { get; set; } +} diff --git a/PlotLine/Help/Articles/RelationshipMap/Overview.md b/PlotLine/Help/Articles/RelationshipMap/Overview.md index ff80785c..54149d4e 100644 --- a/PlotLine/Help/Articles/RelationshipMap/Overview.md +++ b/PlotLine/Help/Articles/RelationshipMap/Overview.md @@ -19,7 +19,23 @@ Use it when you want to see family, friendship, romance, conflict, professional # How To Use It -Choose a story point or character focus, then inspect the visible network. Look for isolated characters, overloaded hubs or relationship groups that do not interact. +The map sits between four independently scrolling character palettes. Characters with importance 8–10 appear at the top, 4–7 at the sides, and lower or unset importance at the bottom. Search ignores case and accents; the importance filter narrows the palettes immediately. **Characters** collapses the palettes to give the canvas more room. + +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. **Centre focus** returns to the focused character. + +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. + +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. 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. + +**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. + +The **Relationship Timeline** shows the state after all changes up to the selected scene. Tick marks identify scenes with changes. 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. + +Drag empty canvas to pan. Use **+ / −**, Ctrl/Cmd-wheel, or a two-finger pinch to zoom. **Fit all** fits the visible network; **Auto-arrange** recalculates positions. **Reset layout** restores removed map characters and rearranges locally. **Remove focused from map** hides a node locally and does not delete the character or relationship. + +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. **List** jumps to the conventional list, which shows the same relationship state as the map. + +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 the side palettes become horizontal strips, keeping the canvas usable. # Example diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index 366d43c8..482560ec 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -5881,11 +5881,17 @@ public sealed class RelationshipMapService(IProjectRepository projects, ICharact var characterImageLookup = (await characters.ListCharactersAsync(projectId)).ToDictionary(x => x.CharacterID); var sceneOrder = BuildSceneOrder(data); var point = ResolveStoryPoint(data, sceneOrder, bookId, chapterId, sceneId); + var chapterBooks = data.Chapters.ToDictionary(x => x.ChapterID, x => x.BookID); + var bookStarts = data.Scenes.Where(x => chapterBooks.ContainsKey(x.ChapterID)) + .GroupBy(x => chapterBooks[x.ChapterID]).ToDictionary(x => x.Key, x => x.Min(s => SceneIndex(sceneOrder, s.SceneID))); var eventsByRelationship = data.RelationshipEvents .GroupBy(x => x.CharacterRelationshipID) .ToDictionary(x => x.Key, x => x.OrderBy(e => SceneIndex(sceneOrder, e.SceneID)).ThenBy(e => e.CreatedDate).ThenBy(e => e.RelationshipEventID).ToList()); var relationships = data.Relationships + .Where(x => !x.IsArchived + && (!x.StartSceneID.HasValue || SceneIndex(sceneOrder, x.StartSceneID.Value) <= point.MaxSceneIndex) + && (!x.InitialBookID.HasValue || bookStarts.GetValueOrDefault(x.InitialBookID.Value, int.MaxValue) <= point.MaxSceneIndex)) .Select(relationship => BuildRelationship(relationship, eventsByRelationship.TryGetValue(relationship.CharacterRelationshipID, out var events) ? events : [], sceneOrder, point.MaxSceneIndex)) .Where(x => x is not null) .Select(x => x!) @@ -5911,7 +5917,6 @@ public sealed class RelationshipMapService(IProjectRepository projects, ICharact } var nodes = data.Characters - .Where(x => activeCharacterIds.Contains(x.CharacterID) || (!focusCharacterId.HasValue && !relationships.Any())) .OrderByDescending(x => x.CharacterID == focusCharacterId) .ThenBy(x => x.CharacterName) .Select(x => new RelationshipMapNodeViewModel @@ -5946,7 +5951,11 @@ public sealed class RelationshipMapService(IProjectRepository projects, ICharact CategoryName = x.CategoryName, CssClass = RelationshipCategoryCss(x.CategoryName) }).ToList(), - Nodes = nodes, + Cast = nodes.OrderByDescending(x => x.CharacterImportance).ThenBy(x => x.CharacterName).ToList(), + TimelineSceneID = data.Scenes.FirstOrDefault(x => SceneIndex(sceneOrder, x.SceneID) == point.MaxSceneIndex)?.SceneID, + WorkspaceLookups = await characters.GetLookupsAsync(projectId), + ChangeSceneIDs = data.RelationshipEvents.Select(x => x.SceneID).Distinct().ToList(), + Nodes = nodes.Where(x => activeCharacterIds.Contains(x.CharacterID) || (!focusCharacterId.HasValue && !relationships.Any())).ToList(), Links = relationships.Select(x => new RelationshipMapLinkViewModel { CharacterRelationshipID = x.CharacterRelationshipID, @@ -6031,6 +6040,7 @@ public sealed class RelationshipMapService(IProjectRepository projects, ICharact CssClass = RelationshipCategoryCss(relationship.RelationshipCategoryName), InitialStateName = initialState, CurrentStateName = currentState, + Known = latestEvent?.IsKnownToOtherCharacter ?? relationship.ReaderInitiallyKnows, InitialIntensity = relationship.InitialIntensity, CurrentIntensity = latestEvent?.Intensity ?? relationship.InitialIntensity, IsReciprocal = relationship.IsReciprocal, @@ -10219,6 +10229,8 @@ public sealed class CharacterService( CharacterAID = model.CharacterAID.Value, CharacterBID = model.CharacterBID.Value, RelationshipTypeID = model.RelationshipTypeID.Value, + IsReciprocal = model.IsReciprocal, + StartSceneID = model.SceneID, IsKnownToReader = true }); } diff --git a/PlotLine/ViewModels/CoreViewModels.cs b/PlotLine/ViewModels/CoreViewModels.cs index b72a1928..68387a88 100644 --- a/PlotLine/ViewModels/CoreViewModels.cs +++ b/PlotLine/ViewModels/CoreViewModels.cs @@ -2029,6 +2029,10 @@ public sealed class CurrentRelationshipViewModel public sealed class RelationshipMapViewModel { + public IReadOnlyList Cast { get; set; } = []; + public int? TimelineSceneID { get; set; } + public CharacterLookupData WorkspaceLookups { get; set; } = new(); + public IReadOnlyList ChangeSceneIDs { get; set; } = []; public Project Project { get; set; } = new(); public int? BookID { get; set; } public int? ChapterID { get; set; } @@ -2078,6 +2082,7 @@ public sealed class RelationshipMapLinkViewModel public sealed class RelationshipMapRelationshipViewModel { + public bool Known { get; set; } public int CharacterRelationshipID { get; set; } public int CharacterAID { get; set; } public string CharacterAName { get; set; } = string.Empty; @@ -2186,6 +2191,7 @@ public sealed class CharacterKnowledgeCreateViewModel public sealed class RelationshipEventCreateViewModel { + public bool IsReciprocal { get; set; } public int RelationshipEventID { get; set; } public int SceneID { get; set; } public int? CharacterRelationshipID { get; set; } diff --git a/PlotLine/Views/RelationshipMap/Index.cshtml b/PlotLine/Views/RelationshipMap/Index.cshtml index f29a1147..47a00c8e 100644 --- a/PlotLine/Views/RelationshipMap/Index.cshtml +++ b/PlotLine/Views/RelationshipMap/Index.cshtml @@ -14,14 +14,15 @@ -
+

Relationships

-

Relationship Map

-

A read-only network of character relationships as of @Model.StoryPointLabel.

+

Relationships Workspace

+

Explore and change relationships through the story.

+
Story point and focus options
@@ -55,12 +56,9 @@ Project Start +
-
-

Relationship key

-

Category colours

-
@foreach (var category in Model.Categories) { @@ -74,25 +72,10 @@
- @if (!Model.Nodes.Any() || !Model.Links.Any()) - { -
-

No visible relationships at this point

-

Add initial relationships or relationship events, choose a later story point, or remove the character focus to build the map.

-
- } - else - { -
- - -
- -

The relationship map renderer could not load. The relationship list below is still available.

- } +
-
-
+

Visible relationships

- @if (!Model.Relationships.Any()) - { -

No relationships are visible for this map state.

- } - else - {
@foreach (var relationship in Model.Relationships) { @@ -139,348 +117,8 @@ }
- }
@section Scripts { - - + } diff --git a/PlotLine/Views/RelationshipMap/_GraphScripts.cshtml b/PlotLine/Views/RelationshipMap/_GraphScripts.cshtml new file mode 100644 index 00000000..015a8888 --- /dev/null +++ b/PlotLine/Views/RelationshipMap/_GraphScripts.cshtml @@ -0,0 +1,383 @@ +@using System.Text.Json +@model RelationshipMapViewModel +@{ var jsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; } + + + diff --git a/PlotLine/Views/RelationshipMap/_Workspace.cshtml b/PlotLine/Views/RelationshipMap/_Workspace.cshtml new file mode 100644 index 00000000..cf8d58c0 --- /dev/null +++ b/PlotLine/Views/RelationshipMap/_Workspace.cshtml @@ -0,0 +1,75 @@ +@model RelationshipMapViewModel + +
+ + + + + List +
+
+ @foreach (var side in new[] { "top", "left", "right", "bottom" }) + { + var supporting = Model.Cast.Where(x => x.CharacterImportance >= 4 && x.CharacterImportance < 8).ToList(); + var cast = side == "top" ? Model.Cast.Where(x => x.CharacterImportance >= 8) + : side == "bottom" ? Model.Cast.Where(x => (x.CharacterImportance ?? 0) < 4) + : supporting.Where((x, i) => i % 2 == (side == "left" ? 0 : 1)); +
+ @foreach (var character in cast) + { + var portrait = character.AvatarThumbnailPath ?? character.AvatarImagePath ?? character.ThumbnailPath ?? character.ImagePath; +
+ + + Edit character +
+ } +
+ } +
+
+ + + + + + + +
+
+

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

+

+
+
+
+ + + + + +
+ +
+

Create / change relationship

+ + + + + + + + + + +

+
+
+
diff --git a/PlotLine/wwwroot/css/relationship-workspace.css b/PlotLine/wwwroot/css/relationship-workspace.css new file mode 100644 index 00000000..9cfdf1d6 --- /dev/null +++ b/PlotLine/wwwroot/css/relationship-workspace.css @@ -0,0 +1,7 @@ +.relationship-map-workspace{grid-template-columns:minmax(0,1fr) 260px}.relationship-map-canvas{min-width:0}.rw-tools{display:flex;gap:.5rem;align-items:end;flex-wrap:wrap;margin-bottom:.5rem}.rw-tools label{margin:0}.rw-board{display:grid;grid-template-columns:140px minmax(0,1fr) 140px;grid-template-rows:82px minmax(430px,60vh) 82px;gap:.4rem}.rw-strip{overflow:auto;overscroll-behavior:contain;display:flex;gap:.3rem;padding:.25rem;border:1px solid var(--app-border);border-radius:.4rem}.rw-top{grid-column:1/4;grid-row:1}.rw-bottom{grid-column:1/4;grid-row:3}.rw-left{grid-column:1;grid-row:2;flex-direction:column}.rw-right{grid-column:3;grid-row:2;flex-direction:column}.rw-centre{grid-column:2;grid-row:2;position:relative;min-width:0;display:flex;flex-direction:column}.rw-centre .relationship-map-graph{height:auto;min-height:240px;flex:1}.rw-centre .relationship-map-toolbar{position:static;display:flex;flex-wrap:wrap;gap:.25rem}.rw-entry{position:relative;flex-shrink:0;display:flex;align-items:center;max-width:180px}.rw-character{display:flex;gap:.3rem;align-items:center;text-align:left;width:100%;border:1px solid var(--app-border);border-radius:.4rem;padding:.3rem;background:var(--app-surface);color:inherit;font-size:.8rem;min-height:44px}.rw-character .visual-avatar{width:28px;height:28px;min-width:28px}.rw-link{color:inherit;background:transparent;border:0;min-width:30px;min-height:44px}.rw-entry.is-focus .rw-character,.rw-character:focus-visible,.rw-link:focus-visible{outline:3px solid var(--bs-primary,#c47c2c);outline-offset:-3px}.rw-edit{display:none}.rw-entry[hidden]{display:none}.rw-timeline{padding-top:.5rem}.rw-timeline input{width:100%;display:block}.rw-timeline label{display:block}#rwStatus{font-size:.8rem;margin:0;min-height:1.4em}#rwDialog{color:var(--app-text);background:var(--app-surface);border:1px solid var(--app-border);border-radius:.6rem;width:min(480px,96vw);max-height:90dvh;overflow:auto}#rwDialog::backdrop{background:#0008}#rwForm{display:grid;gap:.5rem}#rwForm label{display:block}.rw-board.palettes-hidden{grid-template-columns:1fr;grid-template-rows:minmax(430px,60vh)}.rw-board.palettes-hidden .rw-strip{display:none}.rw-board.palettes-hidden .rw-centre{grid-column:1;grid-row:1} +@media(max-width:1200px){.relationship-map-workspace{grid-template-columns:1fr}.relationship-map-details{max-height:240px;overflow:auto}.rw-board{grid-template-columns:100px minmax(0,1fr) 100px}} +@media(max-width:700px){.rw-board{grid-template-columns:minmax(0,1fr);grid-template-rows:65px 65px minmax(380px,55vh) 65px 65px}.rw-top{grid-row:1}.rw-left{grid-row:2}.rw-centre{grid-row:3}.rw-right{grid-row:4}.rw-bottom{grid-row:5}.rw-strip,.rw-centre{grid-column:1;flex-direction:row}.rw-centre{flex-direction:column}.rw-entry{max-width:160px}.rw-character{white-space:nowrap}.relationship-map-canvas{padding:.4rem}} + +.rw-centre{overflow:hidden}.rw-character span:last-child{overflow:hidden;text-overflow:ellipsis}.rw-link:focus-visible{outline-offset:-2px} + +.relationship-workspace-heading{margin:.5rem 0}.relationship-workspace-heading h1{font-size:1.7rem;margin:0}.relationship-workspace-heading .lead-text{font-size:.9rem;margin:0}.rw-options{margin-bottom:.5rem}.rw-options summary{cursor:pointer;font-size:.85rem;padding:.3rem}.relationship-map-legend{padding:.5rem 1rem;margin-bottom:.5rem}.rw-list .relationship-map-list{display:grid;grid-template-columns:1fr;max-height:320px;overflow:auto;gap:.2rem}.rw-list .relationship-map-list-item{display:grid;grid-template-columns:minmax(0,2fr) minmax(0,1fr) auto;align-items:center;padding:.4rem .6rem;gap:.4rem;box-shadow:none;min-height:44px}.rw-list h2{font-size:1.1rem}.rw-list{padding:.7rem;margin-top:.5rem}.rw-entry:focus-within{z-index:1} diff --git a/PlotLine/wwwroot/js/relationship-workspace.js b/PlotLine/wwwroot/js/relationship-workspace.js new file mode 100644 index 00000000..8e740767 --- /dev/null +++ b/PlotLine/wwwroot/js/relationship-workspace.js @@ -0,0 +1,301 @@ +(() => { + const workspace = window.PlotDirectorRelationshipWorkspace; + if (!workspace) return; + const { cy, cast, scenes, projectId } = workspace; + const graph = document.getElementById('relationshipMapGraph'); + const board = document.getElementById('rwBoard'); + const dialog = document.getElementById('rwDialog'); + const form = document.getElementById('rwForm'); + const timeline = document.getElementById('rwTimeline'); + const point = document.getElementById('rwPoint'); + const status = document.getElementById('rwStatus'); + const editStatus = document.getElementById('rwEditStatus'); + const field = name => form.elements.namedItem(name); + const castById = new Map(cast.map(c => [c.characterID, c])); + const storageKey = `pd.relationship-workspace.v1.${projectId}.${workspace.bookId || 'project'}`; + let focus = workspace.focusCharacterId, source = null, saveTimer, request = null, loading = false, stateLoaded = true; + let currentScene = workspace.sceneId; + let editorRelationships = workspace.relationships(), editorRequest = null, activeRelationship = null; + let editorReady = true; + let restored = null; + try { restored = JSON.parse(localStorage.getItem(storageKey)); } catch { /* Storage can be unavailable. */ } + const extraNodes = new Set(restored?.extraNodes || []); + const removed = new Set(restored?.removed || []); + const remember = () => { + clearTimeout(saveTimer); + saveTimer = setTimeout(() => { + const positions = {}; + cy.nodes().forEach(n => { positions[n.id()] = n.position(); }); + try { localStorage.setItem(storageKey, JSON.stringify({ positions, zoom: cy.zoom(), pan: cy.pan(), focus, + extraNodes: [...extraNodes], removed: [...removed], collapsed: board.classList.contains('palettes-hidden') })); } catch { /* Layout persistence is optional. */ } + }, 250); + }; + function ensureNode(id, position) { + const character = castById.get(Number(id)); + if (!character) return cy.collection(); + let node = cy.$id(`c-${id}`); + if (!node.length) { + node = cy.add({ data: { id: `c-${id}`, characterID: Number(id), label: character.characterName, + width: character.characterImportance >= 8 ? 158 : 144, height: 46 }, + classes: character.characterImportance >= 8 ? 'is-major-character' : character.characterImportance >= 4 ? 'is-supporting-character' : '', + position: position || { x: (graph.clientWidth / 2 - cy.pan().x) / cy.zoom(), y: (graph.clientHeight / 2 - cy.pan().y) / cy.zoom() } }); + } else if (position) node.position(position); + removed.delete(Number(id)); + return node; + } + function applyFocus(centre = false) { + cy.elements().removeClass('is-focus is-dimmed'); + cy.elements().show(); + if (focus) { + const node = ensureNode(focus); + node.addClass('is-focus'); + const neighbours = node.closedNeighborhood(); + const full = document.querySelector('[name="showFullNetwork"]').checked; + if (full) cy.elements().difference(neighbours).addClass('is-dimmed'); + else cy.elements().difference(neighbours).hide(); + if (centre) cy.center(node); + status.textContent = `Focused: ${castById.get(focus)?.characterName || ''}. Drag a character here or choose Add relationship.`; + } + for (const id of removed) cy.$id(`c-${id}`).closedNeighborhood().filter('edge').hide(); + for (const id of removed) cy.$id(`c-${id}`).hide(); + document.querySelectorAll('[data-rw-entry]').forEach(e => e.classList.toggle('is-focus', Number(e.dataset.rwEntry) === focus)); + document.getElementById('focusCharacterId').value = focus || ''; + positionHandle(); + } + function focusCharacter(id) { + focus = Number(id); extraNodes.add(focus); ensureNode(focus); + if (cy.zoom() < .6) cy.zoom(.8); + applyFocus(true); remember(); + } + function normalise(value) { return value.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim(); } + function filter() { + const query = normalise(document.getElementById('rwSearch').value).split(' ').filter(Boolean); + const importance = document.getElementById('rwImportance').value; + document.querySelectorAll('[data-rw-character]').forEach(button => { + const n = Number(button.dataset.importance); + const group = n >= 8 ? 'major' : n >= 4 ? 'supporting' : 'minor'; + button.closest('[data-rw-entry]').hidden = (importance && group !== importance) || !query.every(word => normalise(button.textContent).includes(word)); + }); + } + document.getElementById('rwSearch').addEventListener('input', filter); + document.getElementById('rwImportance').addEventListener('change', filter); + document.querySelectorAll('[data-rw-character]').forEach(button => button.addEventListener('click', () => focusCharacter(button.dataset.rwCharacter))); + function openEditor(from, to) { + 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 || ''; + editStatus.textContent = ''; + editorRelationships = 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); + if (type) field('TypeID').value = type.value; + } + populateExisting(); + dialog.showModal(); + } + function populateExisting() { + const a = Number(field('SourceID').value), b = Number(field('TargetID').value), type = field('TypeID'); + const pair = editorRelationships.filter(r => (r.characterAID === a && r.characterBID === b) || (r.isReciprocal && r.characterAID === b && r.characterBID === a)); + const relationship = pair.find(r => r.relationshipTypeName === type.selectedOptions[0]?.textContent); + const state = relationship?.currentStateName; + field('Mutual').checked = false; field('Known').checked = false; field('Intensity').value = ''; field('Notes').value = ''; + field('StateID').selectedIndex = 0; + if (relationship) { + field('Mutual').checked = relationship.isReciprocal; + field('Known').checked = relationship.known; + field('Intensity').value = relationship.currentIntensity || ''; + field('Notes').value = relationship.notes || ''; + const option = [...field('StateID').options].find(o => o.textContent === state); + if (option) field('StateID').value = option.value; + } + field('Mutual').disabled = !!field('SceneID').value && !!relationship; + editStatus.textContent = relationship ? 'Updates this relationship; an existing event at the selected scene will be edited.' : 'Creates a relationship of this type, or updates a matching record if one exists outside the current view.'; + document.getElementById('rwDialogTitle').textContent = `${castById.get(a)?.characterName || 'Source'} → ${castById.get(b)?.characterName || 'Target'}`; + } + ['SourceID', 'TargetID', 'TypeID'].forEach(name => field(name).addEventListener('change', populateExisting)); + field('SceneID').addEventListener('change', async () => { + editorRequest?.abort(); const active = editorRequest = new AbortController(); + const submit = form.querySelector('[type="submit"]'); submit.disabled = true; editorReady = false; + try { + const params = new URLSearchParams({ projectId }); + if (field('SceneID').value) params.set('sceneId', field('SceneID').value); + const response = await fetch(`/RelationshipMap/State?${params}`, { signal: active.signal }); + if (!response.ok) throw new Error('Could not load the selected scene.'); + editorRelationships = (await response.json()).relationships; editorReady = true; populateExisting(); + } catch (error) { if (error.name !== 'AbortError') editStatus.textContent = error.message; } + finally { if (active === editorRequest) submit.disabled = !editorReady; } + }); + document.getElementById('rwEditLine').addEventListener('click', () => { + activeRelationship = workspace.selectedRelationship || activeRelationship; + if (!activeRelationship) return; + openEditor(activeRelationship.characterAID, activeRelationship.characterBID); + const type = [...field('TypeID').options].find(o => o.textContent === activeRelationship.relationshipTypeName); + if (type) field('TypeID').value = type.value; + populateExisting(); + }); + cy.on('tap cxttap', 'edge', event => { + activeRelationship = workspace.relationships().find(r => r.characterRelationshipID === event.target.data('relationshipID')); + workspace.selectRelationship(event.target.data('relationshipID')); + }); + document.querySelectorAll('[data-map-select]').forEach(button => button.addEventListener('click', () => { + activeRelationship = workspace.relationships().find(r => r.characterRelationshipID === Number(button.dataset.mapSelect)); + })); + document.getElementById('rwConnect').addEventListener('click', () => openEditor(null, focus)); + document.getElementById('rwCancel').addEventListener('click', () => dialog.close()); + document.querySelectorAll('[data-rw-link]').forEach(button => button.addEventListener('click', () => openEditor(Number(button.dataset.rwLink), focus))); + function startDrag(event, id) { + source = Number(id); + event.dataTransfer.setData('application/x-plotdirector-character', String(id)); + event.dataTransfer.effectAllowed = 'copy'; + } + document.querySelectorAll('[data-rw-character], [data-rw-link]').forEach(button => { + button.addEventListener('dragstart', event => startDrag(event, button.dataset.rwCharacter || button.dataset.rwLink)); + button.addEventListener('dragend', () => { source = null; cy.nodes().removeClass('is-drop-target'); }); + }); + function hit(event) { + const rect = graph.getBoundingClientRect(); + const x = event.clientX - rect.left, y = event.clientY - rect.top; + return cy.nodes(':visible').filter(node => { const box = node.renderedBoundingBox(); return x >= box.x1 && x <= box.x2 && y >= box.y1 && y <= box.y2; }).last(); + } + graph.addEventListener('dragover', event => { + if (!source) return; + event.preventDefault(); + cy.nodes().removeClass('is-drop-target'); + const target = hit(event); + if (target.length && target.data('characterID') !== source) { + target.addClass('is-drop-target'); status.textContent = `Drop to create or change a relationship with ${target.data('label')}.`; + } else status.textContent = 'Drop on blank canvas to position this character.'; + }); + graph.addEventListener('dragleave', () => cy.nodes().removeClass('is-drop-target')); + graph.addEventListener('drop', event => { + if (!source) return; + event.preventDefault(); + const id = source, target = hit(event); source = null; + cy.nodes().removeClass('is-drop-target'); + if (target.length && target.data('characterID') !== id) openEditor(id, target.data('characterID')); + else if (!target.length) { + const rect = graph.getBoundingClientRect(); + ensureNode(id, { x: (event.clientX - rect.left - cy.pan().x) / cy.zoom(), y: (event.clientY - rect.top - cy.pan().y) / cy.zoom() }); + extraNodes.add(id); applyFocus(); cy.$id(`c-${id}`).show(); remember(); + } + }); + // A connector is separate from Cytoscape's node-position drag gesture. + const handle = document.createElement('button'); + handle.type = 'button'; handle.draggable = true; handle.textContent = '↗'; + handle.className = 'btn btn-primary btn-sm'; handle.style.cssText = 'position:absolute;z-index:3;min-width:36px;min-height:36px'; + handle.title = 'Drag to another character, or click to add a relationship'; handle.setAttribute('aria-label', handle.title); + graph.parentElement.append(handle); + function positionHandle() { + const node = cy.$id(`c-${focus}`); + handle.hidden = !node.length || !node.visible(); + if (handle.hidden) return; + const box = node.renderedBoundingBox(); + handle.style.left = `${box.x2}px`; handle.style.top = `${graph.offsetTop + box.y1}px`; + } + handle.addEventListener('dragstart', event => startDrag(event, focus)); + 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('cxttap', 'node', event => { + focusCharacter(event.target.data('characterID')); + openContext(document.querySelector(`[data-rw-entry="${focus}"]`), event.originalEvent); + }); + cy.on('cxttap', 'edge', event => { + workspace.selectRelationship(event.target.data('relationshipID')); + openContext(document.querySelector('.relationship-map-details'), event.originalEvent); + }); + function openContext(element, original) { + if (!window.PlotDirectorPwa?.standalone || original?.ctrlKey || !element) return; + element.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, + clientX: original?.clientX || 100, clientY: original?.clientY || 100 })); + } + cy.on('pan zoom position', () => { positionHandle(); remember(); }); + 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('rwPalettes').addEventListener('click', event => { 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()); + // 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 }); + 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'); + changes.forEach(n => { const option = document.createElement('option'); option.value = n; option.label = scenes[n-1].text; changeMarks.append(option); }); + timeline.value = currentScene ? scenes.findIndex(s => Number(s.value) === currentScene) + 1 : workspace.bookId ? scenes.length + 1 : 0; + function labelPoint() { + const index = Number(timeline.value); + point.textContent = index === 0 ? 'Initial' : index > scenes.length ? 'End' : scenes[index - 1].text; + timeline.setAttribute('aria-valuetext', point.textContent); + currentScene = index === 0 ? null : Number(scenes[Math.min(index, scenes.length) - 1]?.value) || null; + } + labelPoint(); + let pinchDistance = null; + graph.addEventListener('touchstart', event => { if (event.touches.length === 2) pinchDistance = Math.hypot(event.touches[0].clientX-event.touches[1].clientX, event.touches[0].clientY-event.touches[1].clientY); }, { passive: true }); + graph.addEventListener('touchmove', event => { + if (event.touches.length !== 2 || !pinchDistance) return; + event.preventDefault(); + const distance = Math.hypot(event.touches[0].clientX-event.touches[1].clientX, event.touches[0].clientY-event.touches[1].clientY); + cy.zoom(Math.max(.05, Math.min(2.5, cy.zoom() * distance / pinchDistance))); pinchDistance = distance; + }, { passive: false }); + graph.addEventListener('touchend', () => { pinchDistance = null; }); + let scrubTimer; + async function refresh() { + request?.abort(); request = new AbortController(); const active = request; + loading = true; + try { + const params = new URLSearchParams({ projectId }); + if (currentScene) params.set('sceneId', currentScene); + const response = await fetch(`/RelationshipMap/State?${params}`, { signal: active.signal }); + if (!response.ok) throw new Error('Could not load relationship state.'); + const model = await response.json(); + if (active !== request) return; + stateLoaded = true; workspace.update(model); applyFocus(); + if (model.changeSceneIDs) { + changes = model.changeSceneIDs.map(id => scenes.findIndex(s => Number(s.value) === id) + 1).filter(n => n > 0).sort((a,b) => a-b); + changeMarks.replaceChildren(); + 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 }); }); + status.textContent = `${point.textContent}: ${model.relationships.length} relationships.`; + document.getElementById('relationshipMapEmptyDetail')?.classList.remove('d-none'); + document.getElementById('relationshipMapDetail')?.classList.add('d-none'); + } catch (error) { if (error.name !== 'AbortError') { stateLoaded = false; status.textContent = error.message; } } + finally { if (active === request) loading = false; } + } + timeline.addEventListener('input', () => { labelPoint(); loading = true; stateLoaded = false; clearTimeout(scrubTimer); scrubTimer = setTimeout(refresh, 160); }); + function jump(next) { const n = Number(timeline.value); timeline.value = next ? changes.find(i => i > n) ?? scenes.length + 1 : [...changes].reverse().find(i => i < n) ?? 0; timeline.dispatchEvent(new Event('input')); } + document.getElementById('rwPrevious').addEventListener('click', () => jump(false)); + document.getElementById('rwNext').addEventListener('click', () => jump(true)); + form.addEventListener('submit', async event => { + event.preventDefault(); + if (!editorReady || !form.reportValidity()) return; + const submit = form.querySelector('[type="submit"]'); submit.disabled = true; + try { + 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(); + dialog.close(); + await refresh(); applyFocus(true); remember(); + } catch (error) { editStatus.textContent = error.message; } + finally { submit.disabled = false; } + }); + 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; + if (Number.isFinite(restored?.zoom)) cy.zoom(restored.zoom); + if (Number.isFinite(restored?.pan?.x) && Number.isFinite(restored?.pan?.y)) cy.pan(restored.pan); + if (restored?.collapsed) { board.classList.add('palettes-hidden'); document.getElementById('rwPalettes').setAttribute('aria-expanded', 'false'); cy.resize(); } + document.querySelector('.list-section').id = 'rwList'; + applyFocus(!!workspace.focusCharacterId); +})();