Add interactive relationships workspace and timeline
This commit is contained in:
parent
3338101964
commit
bb95811e53
29
Docs/Relationships/Workspace.md
Normal file
29
Docs/Relationships/Workspace.md
Normal file
@ -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.
|
||||
@ -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",
|
||||
|
||||
115
PlotLine.Tests/Browser/relationship-workspace.cjs
Normal file
115
PlotLine.Tests/Browser/relationship-workspace.cjs
Normal file
@ -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; });
|
||||
@ -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),
|
||||
|
||||
95
PlotLine.Tests/RelationshipWorkspaceTests.cs
Normal file
95
PlotLine.Tests/RelationshipWorkspaceTests.cs
Normal file
@ -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<ICharacterRepository>((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<IProjectRepository>((m, _) => m switch
|
||||
{
|
||||
"GetAsync" => Task.FromResult<Project?>(new() { ProjectID = 7, ProjectName = "Cast fixture" }),
|
||||
_ => throw new Exception(m)
|
||||
}), Repository(data));
|
||||
public static async Task<RelationshipMapViewModel> 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<object>();
|
||||
var characters = Stub<ICharacterService>((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<T>(Func<string, object?[]?, object?> invoke) where T : class
|
||||
{
|
||||
var proxy = DispatchProxy.Create<T, Proxy>(); ((Proxy)(object)proxy).Handler = invoke; return proxy;
|
||||
}
|
||||
public class Proxy : DispatchProxy
|
||||
{
|
||||
public Func<string, object?[]?, object?> Handler = null!;
|
||||
protected override object? Invoke(MethodInfo? method, object?[]? args) => Handler(method!.Name, args);
|
||||
}
|
||||
}
|
||||
@ -159,7 +159,7 @@ internal static class ToolbarBrowserHost
|
||||
if (dashboardPage) model.ActiveSection = "Overview";
|
||||
if (timelinePage) model.ActiveSection = "Timeline";
|
||||
var appearance = await context.RequestServices.GetRequiredService<IAppearanceRepository>().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<string> 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 += "<script src='/js/scene-inspector-v2.js'></script>";
|
||||
}
|
||||
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 = "<script>window.plotdirectorAppearance=" + System.Text.Json.JsonSerializer.Serialize(new { theme = initialTheme, migrate = false, collapsed = appearance.RibbonCollapsed }) + ";</script>";
|
||||
|
||||
@ -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<IActionResult> 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<IActionResult> 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<IActionResult> 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; }
|
||||
}
|
||||
|
||||
@ -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
|
||||
|
||||
|
||||
@ -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
|
||||
});
|
||||
}
|
||||
|
||||
@ -2029,6 +2029,10 @@ public sealed class CurrentRelationshipViewModel
|
||||
|
||||
public sealed class RelationshipMapViewModel
|
||||
{
|
||||
public IReadOnlyList<RelationshipMapNodeViewModel> Cast { get; set; } = [];
|
||||
public int? TimelineSceneID { get; set; }
|
||||
public CharacterLookupData WorkspaceLookups { get; set; } = new();
|
||||
public IReadOnlyList<int> 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; }
|
||||
|
||||
@ -14,14 +14,15 @@
|
||||
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<div data-pwa-help class="page-heading">
|
||||
<div data-pwa-help class="page-heading relationship-workspace-heading">
|
||||
<div>
|
||||
<p data-pwa-identity class="eyebrow">Relationships</p>
|
||||
<div data-pwa-header><h1>Relationship Map <help-icon key="relationshipMap.overview" /></h1></div>
|
||||
<p class="lead-text">A read-only network of character relationships as of @Model.StoryPointLabel.</p>
|
||||
<div data-pwa-header><h1>Relationships Workspace <help-icon key="relationshipMap.overview" /></h1></div>
|
||||
<p class="lead-text">Explore and change relationships through the story.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<details class="rw-options"><summary>Story point and focus options</summary>
|
||||
<form class="relationship-map-controls plain-card" method="get" asp-action="Index">
|
||||
<input type="hidden" name="projectId" value="@Model.Project.ProjectID" />
|
||||
<div>
|
||||
@ -55,12 +56,9 @@
|
||||
<button class="btn btn-primary btn-sm" type="submit">Update Map</button>
|
||||
<a class="btn btn-outline-secondary btn-sm" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Project Start</a>
|
||||
</form>
|
||||
</details>
|
||||
|
||||
<section class="relationship-map-legend plain-card" aria-label="Relationship categories">
|
||||
<div>
|
||||
<p class="eyebrow">Relationship key</p>
|
||||
<h2>Category colours</h2>
|
||||
</div>
|
||||
<div class="relationship-map-legend-grid">
|
||||
@foreach (var category in Model.Categories)
|
||||
{
|
||||
@ -74,25 +72,10 @@
|
||||
|
||||
<section class="relationship-map-workspace">
|
||||
<div class="relationship-map-canvas plain-card">
|
||||
@if (!Model.Nodes.Any() || !Model.Links.Any())
|
||||
{
|
||||
<div class="empty-state">
|
||||
<h2>No visible relationships at this point</h2>
|
||||
<p class="muted">Add initial relationships or relationship events, choose a later story point, or remove the character focus to build the map.</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="relationship-map-toolbar" aria-label="Map controls">
|
||||
<button class="btn btn-outline-secondary btn-sm" type="button" data-map-fit>Fit</button>
|
||||
<button class="btn btn-outline-secondary btn-sm" type="button" data-map-reset>Reset view</button>
|
||||
</div>
|
||||
<div id="relationshipMapGraph" class="relationship-map-graph" role="img" aria-label="Relationship network"></div>
|
||||
<p id="relationshipMapError" class="alert alert-warning d-none mt-3">The relationship map renderer could not load. The relationship list below is still available.</p>
|
||||
}
|
||||
<partial name="_Workspace" model="Model" />
|
||||
</div>
|
||||
|
||||
<aside class="relationship-map-details plain-card">
|
||||
<aside class="relationship-map-details plain-card" data-pd-context="relationship">
|
||||
<p class="eyebrow">Relationship detail</p>
|
||||
<div id="relationshipMapEmptyDetail">
|
||||
<h2>Select a relationship</h2>
|
||||
@ -115,20 +98,15 @@
|
||||
<dt>Current state</dt>
|
||||
<dd data-map-detail-current></dd>
|
||||
</dl>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" id="rwEditLine">Edit at timeline point</button>
|
||||
<h3>History</h3>
|
||||
<ol class="relationship-map-history" data-map-detail-history></ol>
|
||||
</div>
|
||||
</aside>
|
||||
</section>
|
||||
|
||||
<section class="list-section">
|
||||
<section class="list-section rw-list">
|
||||
<h2>Visible relationships</h2>
|
||||
@if (!Model.Relationships.Any())
|
||||
{
|
||||
<p class="muted">No relationships are visible for this map state.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="relationship-map-list">
|
||||
@foreach (var relationship in Model.Relationships)
|
||||
{
|
||||
@ -139,348 +117,8 @@
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
@section Scripts {
|
||||
<script src="https://cdn.jsdelivr.net/npm/cytoscape/dist/cytoscape.min.js"></script>
|
||||
<script>
|
||||
(() => {
|
||||
const nodes = @Html.Raw(JsonSerializer.Serialize(Model.Nodes, jsonOptions));
|
||||
const links = @Html.Raw(JsonSerializer.Serialize(Model.Links, jsonOptions));
|
||||
const relationships = @Html.Raw(JsonSerializer.Serialize(Model.Relationships, jsonOptions));
|
||||
const relationshipById = new Map(relationships.map(item => [item.characterRelationshipID, item]));
|
||||
const nodeById = new Map(nodes.map(item => [item.characterID, item]));
|
||||
const graph = document.getElementById("relationshipMapGraph");
|
||||
const error = document.getElementById("relationshipMapError");
|
||||
if (!graph || !nodes.length) return;
|
||||
|
||||
if (!window.cytoscape) {
|
||||
error?.classList.remove("d-none");
|
||||
return;
|
||||
}
|
||||
|
||||
const focusCharacterId = @Html.Raw(JsonSerializer.Serialize(Model.FocusCharacterID));
|
||||
const fullNetwork = @Html.Raw(JsonSerializer.Serialize(Model.ShowFullNetwork));
|
||||
const connectedToFocus = new Set();
|
||||
if (focusCharacterId && fullNetwork) {
|
||||
links.forEach(link => {
|
||||
if (link.sourceCharacterID === focusCharacterId) connectedToFocus.add(link.targetCharacterID);
|
||||
if (link.targetCharacterID === focusCharacterId) connectedToFocus.add(link.sourceCharacterID);
|
||||
});
|
||||
}
|
||||
|
||||
const elements = [
|
||||
...nodes.map(node => ({
|
||||
group: "nodes",
|
||||
data: {
|
||||
id: `c-${node.characterID}`,
|
||||
characterID: node.characterID,
|
||||
label: node.characterName,
|
||||
importance: node.characterImportance || 0,
|
||||
width: node.isFocus ? 172 : node.characterImportance >= 8 ? 158 : node.characterImportance >= 4 ? 144 : 128,
|
||||
height: node.isFocus ? 58 : node.characterImportance >= 8 ? 52 : 46,
|
||||
isFocus: node.isFocus,
|
||||
isNeighbour: connectedToFocus.has(node.characterID)
|
||||
},
|
||||
classes: [
|
||||
node.isFocus ? "is-focus" : "",
|
||||
node.characterImportance >= 8 ? "is-major-character" : "",
|
||||
node.characterImportance >= 4 && node.characterImportance < 8 ? "is-supporting-character" : "",
|
||||
focusCharacterId && fullNetwork && !node.isFocus && !connectedToFocus.has(node.characterID) ? "is-dimmed" : ""
|
||||
].filter(Boolean).join(" ")
|
||||
})),
|
||||
...links.map(link => ({
|
||||
group: "edges",
|
||||
data: {
|
||||
id: `r-${link.characterRelationshipID}`,
|
||||
relationshipID: link.characterRelationshipID,
|
||||
source: `c-${link.sourceCharacterID}`,
|
||||
target: `c-${link.targetCharacterID}`,
|
||||
label: link.relationshipLabel,
|
||||
category: link.categoryName,
|
||||
intensity: link.intensity || 4,
|
||||
tooltip: buildRelationshipTooltip(relationshipById.get(link.characterRelationshipID))
|
||||
},
|
||||
classes: [
|
||||
link.cssClass,
|
||||
focusCharacterId && fullNetwork && link.sourceCharacterID !== focusCharacterId && link.targetCharacterID !== focusCharacterId ? "is-dimmed" : ""
|
||||
].filter(Boolean).join(" ")
|
||||
}))
|
||||
];
|
||||
|
||||
const cy = cytoscape({
|
||||
container: graph,
|
||||
elements,
|
||||
minZoom: 0.25,
|
||||
maxZoom: 2.5,
|
||||
wheelSensitivity: 0.18,
|
||||
style: relationshipMapStyle(),
|
||||
layout: {
|
||||
name: nodes.length <= 8 ? "circle" : "cose",
|
||||
animate: false,
|
||||
fit: true,
|
||||
padding: 48,
|
||||
nodeRepulsion: 9000,
|
||||
idealEdgeLength: 170,
|
||||
edgeElasticity: 80,
|
||||
numIter: 1200,
|
||||
randomize: false
|
||||
}
|
||||
});
|
||||
|
||||
cy.ready(() => {
|
||||
cy.fit(undefined, 48);
|
||||
const first = relationships[0];
|
||||
if (first) selectRelationship(first.characterRelationshipID);
|
||||
});
|
||||
|
||||
cy.on("tap", "edge", event => {
|
||||
selectRelationship(event.target.data("relationshipID"));
|
||||
});
|
||||
|
||||
cy.on("tap", "node", event => {
|
||||
const characterId = event.target.data("characterID");
|
||||
const characterName = event.target.data("label");
|
||||
const character = nodeById.get(characterId);
|
||||
document.getElementById("relationshipMapEmptyDetail")?.classList.add("d-none");
|
||||
document.getElementById("relationshipMapDetail")?.classList.remove("d-none");
|
||||
document.querySelector("[data-map-detail-title]").textContent = characterName;
|
||||
renderDetailAvatar(character);
|
||||
document.querySelector("[data-map-detail-category]").textContent = "Character";
|
||||
document.querySelector("[data-map-detail-reciprocal]").textContent = characterId === focusCharacterId ? "Focused" : "Node";
|
||||
document.querySelector("[data-map-detail-type]").textContent = "Character";
|
||||
document.querySelector("[data-map-detail-initial]").textContent = "Select a relationship line to see relationship state.";
|
||||
document.querySelector("[data-map-detail-current]").textContent = "Use Character focus to centre this character.";
|
||||
const history = document.querySelector("[data-map-detail-history]");
|
||||
history.innerHTML = "";
|
||||
const li = document.createElement("li");
|
||||
li.innerHTML = `<a href="/Characters/Details/${characterId}">Open character details</a> or <a href="/RelationshipMap?projectId=@Model.Project.ProjectID&focusCharacterId=${characterId}">focus this character</a>.`;
|
||||
history.append(li);
|
||||
});
|
||||
|
||||
cy.on("mouseover", "node, edge", event => {
|
||||
const label = event.target.isNode() ? event.target.data("label") : event.target.data("tooltip");
|
||||
graph.setAttribute("title", label || "");
|
||||
});
|
||||
|
||||
document.querySelector("[data-map-fit]")?.addEventListener("click", () => {
|
||||
cy.resize();
|
||||
cy.fit(undefined, 48);
|
||||
});
|
||||
|
||||
document.querySelector("[data-map-reset]")?.addEventListener("click", () => {
|
||||
cy.layout({
|
||||
name: nodes.length <= 8 ? "circle" : "cose",
|
||||
animate: false,
|
||||
fit: true,
|
||||
padding: 48,
|
||||
randomize: false
|
||||
}).run();
|
||||
});
|
||||
|
||||
window.addEventListener("resize", () => {
|
||||
window.requestAnimationFrame(() => {
|
||||
cy.resize();
|
||||
cy.fit(undefined, 48);
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll("[data-map-select]").forEach(button => {
|
||||
button.addEventListener("click", () => selectRelationship(Number(button.dataset.mapSelect)));
|
||||
});
|
||||
|
||||
function selectRelationship(id) {
|
||||
const relationship = relationshipById.get(id);
|
||||
if (!relationship) return;
|
||||
|
||||
cy.elements().removeClass("is-selected");
|
||||
cy.$id(`r-${id}`).addClass("is-selected");
|
||||
document.querySelectorAll(".relationship-map-list-item").forEach(item => item.classList.remove("is-selected"));
|
||||
document.querySelectorAll(`[data-map-select="${id}"]`).forEach(item => item.classList.add("is-selected"));
|
||||
|
||||
document.getElementById("relationshipMapEmptyDetail")?.classList.add("d-none");
|
||||
document.getElementById("relationshipMapDetail")?.classList.remove("d-none");
|
||||
document.querySelector("[data-map-detail-title]").textContent = `${relationship.characterAName} - ${relationship.characterBName}`;
|
||||
renderDetailAvatar(null);
|
||||
document.querySelector("[data-map-detail-category]").textContent = relationship.relationshipCategoryName;
|
||||
document.querySelector("[data-map-detail-reciprocal]").textContent = relationship.isReciprocal ? "Reciprocal" : "Directional";
|
||||
document.querySelector("[data-map-detail-type]").textContent = relationship.relationshipTypeName;
|
||||
document.querySelector("[data-map-detail-initial]").textContent = formatState(relationship.initialStateName, relationship.initialIntensity);
|
||||
document.querySelector("[data-map-detail-current]").textContent = formatState(relationship.currentStateName, relationship.currentIntensity);
|
||||
|
||||
const history = document.querySelector("[data-map-detail-history]");
|
||||
history.innerHTML = "";
|
||||
relationship.history.forEach(item => {
|
||||
const li = document.createElement("li");
|
||||
const notes = item.notes ? ` - ${item.notes}` : "";
|
||||
li.textContent = `${item.label}: ${formatState(item.stateName, item.intensity)}${notes}`;
|
||||
history.append(li);
|
||||
});
|
||||
}
|
||||
|
||||
function formatState(name, intensity) {
|
||||
return intensity ? `${name} / Intensity ${intensity}` : name;
|
||||
}
|
||||
|
||||
function renderDetailAvatar(character) {
|
||||
const avatar = document.querySelector("[data-map-detail-avatar]");
|
||||
if (!avatar) return;
|
||||
|
||||
avatar.innerHTML = "";
|
||||
if (!character) {
|
||||
avatar.classList.add("d-none");
|
||||
return;
|
||||
}
|
||||
|
||||
const imagePath = character.avatarThumbnailPath || character.avatarImagePath || character.thumbnailPath || character.imagePath;
|
||||
if (imagePath) {
|
||||
const image = document.createElement("img");
|
||||
image.src = imagePath;
|
||||
image.alt = "";
|
||||
image.loading = "lazy";
|
||||
avatar.append(image);
|
||||
} else {
|
||||
const fallback = document.createElement("span");
|
||||
fallback.textContent = initials(character.characterName);
|
||||
avatar.append(fallback);
|
||||
}
|
||||
|
||||
avatar.title = character.characterName;
|
||||
avatar.classList.remove("d-none");
|
||||
}
|
||||
|
||||
function initials(value) {
|
||||
const parts = (value || "")
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.slice(0, 2);
|
||||
const text = parts.map(part => part[0]).join("").toUpperCase();
|
||||
return text || "?";
|
||||
}
|
||||
|
||||
function buildRelationshipTooltip(relationship) {
|
||||
if (!relationship) return "";
|
||||
return `${relationship.characterAName} - ${relationship.characterBName}: ${relationship.relationshipTypeName}; current ${formatState(relationship.currentStateName, relationship.currentIntensity)}`;
|
||||
}
|
||||
|
||||
function relationshipMapStyle() {
|
||||
const isDark = document.documentElement.dataset.theme === "dark";
|
||||
const nodeFill = isDark ? "#222126" : "#fffdf8";
|
||||
const nodeText = isDark ? "#f7efe4" : "#1f2937";
|
||||
const focusFill = isDark ? "#3b2a16" : "#fff3d8";
|
||||
const majorFill = isDark ? "#332417" : "#fff0d5";
|
||||
const supportingFill = isDark ? "#29252c" : "#fbf6ef";
|
||||
const labelFill = isDark ? "#f7efe4" : "#2f3742";
|
||||
const labelBackground = isDark ? "#17171c" : "#fffdf8";
|
||||
return [
|
||||
{
|
||||
selector: "node",
|
||||
style: {
|
||||
"label": "data(label)",
|
||||
"shape": "round-rectangle",
|
||||
"width": "data(width)",
|
||||
"height": "data(height)",
|
||||
"background-color": nodeFill,
|
||||
"border-color": "#6b7280",
|
||||
"border-width": 2,
|
||||
"color": nodeText,
|
||||
"font-size": 12,
|
||||
"font-weight": 650,
|
||||
"text-wrap": "wrap",
|
||||
"text-max-width": 118,
|
||||
"text-valign": "center",
|
||||
"text-halign": "center",
|
||||
"text-margin-y": 0,
|
||||
"padding": "10px",
|
||||
"shadow-blur": 10,
|
||||
"shadow-color": isDark ? "rgba(0, 0, 0, 0.45)" : "rgba(31, 41, 55, 0.18)",
|
||||
"shadow-opacity": 0.32,
|
||||
"shadow-offset-y": 3,
|
||||
"overlay-opacity": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
selector: "node.is-supporting-character",
|
||||
style: {
|
||||
"background-color": supportingFill,
|
||||
"border-color": isDark ? "#b9a891" : "#b99970",
|
||||
"border-width": 2.5,
|
||||
"font-weight": 700
|
||||
}
|
||||
},
|
||||
{
|
||||
selector: "node.is-major-character",
|
||||
style: {
|
||||
"background-color": majorFill,
|
||||
"border-color": "#c47c2c",
|
||||
"border-width": 3,
|
||||
"font-size": 13,
|
||||
"font-weight": 800,
|
||||
"shadow-opacity": 0.42
|
||||
}
|
||||
},
|
||||
{
|
||||
selector: "node.is-focus",
|
||||
style: {
|
||||
"width": "data(width)",
|
||||
"height": "data(height)",
|
||||
"background-color": focusFill,
|
||||
"border-color": "#c47c2c",
|
||||
"border-width": 4,
|
||||
"font-size": 13,
|
||||
"font-weight": 850,
|
||||
"shadow-opacity": 0.5
|
||||
}
|
||||
},
|
||||
{
|
||||
selector: "edge",
|
||||
style: {
|
||||
"label": "data(label)",
|
||||
"curve-style": "bezier",
|
||||
"width": "mapData(intensity, 1, 10, 2, 8)",
|
||||
"line-color": "#7a8796",
|
||||
"target-arrow-shape": "none",
|
||||
"font-size": 11,
|
||||
"font-weight": 700,
|
||||
"color": labelFill,
|
||||
"text-background-color": labelBackground,
|
||||
"text-background-opacity": 0.88,
|
||||
"text-background-padding": 3,
|
||||
"text-rotation": "none",
|
||||
"overlay-opacity": 0
|
||||
}
|
||||
},
|
||||
{ selector: "edge.relationship-category-family", style: { "line-color": "#b86522", "color": "#7c3f12" } },
|
||||
{ selector: "edge.relationship-category-friendship", style: { "line-color": "#2f9e5f", "color": "#14532d" } },
|
||||
{ selector: "edge.relationship-category-romantic", style: { "line-color": "#d9467f", "color": "#831843" } },
|
||||
{ selector: "edge.relationship-category-hostile", style: { "line-color": "#dc3f3f", "color": "#7f1d1d" } },
|
||||
{ selector: "edge.relationship-category-professional", style: { "line-color": "#4f7fd8", "color": "#1e3a8a" } },
|
||||
{ selector: "edge.relationship-category-other", style: { "line-color": "#7a8796", "color": "#374151" } },
|
||||
{
|
||||
selector: ".is-dimmed",
|
||||
style: {
|
||||
"opacity": 0.25
|
||||
}
|
||||
},
|
||||
{
|
||||
selector: "edge.is-selected",
|
||||
style: {
|
||||
"width": 9,
|
||||
"z-index": 20,
|
||||
"text-background-opacity": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
selector: "node:selected",
|
||||
style: {
|
||||
"border-color": "#c47c2c",
|
||||
"border-width": 4
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<partial name="_GraphScripts" model="Model" />
|
||||
}
|
||||
|
||||
383
PlotLine/Views/RelationshipMap/_GraphScripts.cshtml
Normal file
383
PlotLine/Views/RelationshipMap/_GraphScripts.cshtml
Normal file
@ -0,0 +1,383 @@
|
||||
@using System.Text.Json
|
||||
@model RelationshipMapViewModel
|
||||
@{ var jsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; }
|
||||
<script src="https://cdn.jsdelivr.net/npm/cytoscape/dist/cytoscape.min.js"></script>
|
||||
<script>
|
||||
(() => {
|
||||
let nodes = @Html.Raw(JsonSerializer.Serialize(Model.Nodes, jsonOptions));
|
||||
let links = @Html.Raw(JsonSerializer.Serialize(Model.Links, jsonOptions));
|
||||
let relationships = @Html.Raw(JsonSerializer.Serialize(Model.Relationships, jsonOptions));
|
||||
const relationshipById = new Map(relationships.map(item => [item.characterRelationshipID, item]));
|
||||
const castMetadata = @Html.Raw(JsonSerializer.Serialize(Model.Cast, jsonOptions));
|
||||
const nodeById = new Map(castMetadata.map(item => [item.characterID, item]));
|
||||
const graph = document.getElementById("relationshipMapGraph");
|
||||
const error = document.getElementById("relationshipMapError");
|
||||
if (!graph) return;
|
||||
|
||||
if (!window.cytoscape) {
|
||||
error?.classList.remove("d-none");
|
||||
return;
|
||||
}
|
||||
|
||||
let focusCharacterId = @Html.Raw(JsonSerializer.Serialize(Model.FocusCharacterID));
|
||||
const fullNetwork = @Html.Raw(JsonSerializer.Serialize(Model.ShowFullNetwork));
|
||||
const connectedToFocus = new Set();
|
||||
if (focusCharacterId && fullNetwork) {
|
||||
links.forEach(link => {
|
||||
if (link.sourceCharacterID === focusCharacterId) connectedToFocus.add(link.targetCharacterID);
|
||||
if (link.targetCharacterID === focusCharacterId) connectedToFocus.add(link.sourceCharacterID);
|
||||
});
|
||||
}
|
||||
|
||||
const elements = [
|
||||
...nodes.map(node => ({
|
||||
group: "nodes",
|
||||
data: {
|
||||
id: `c-${node.characterID}`,
|
||||
characterID: node.characterID,
|
||||
label: node.characterName,
|
||||
importance: node.characterImportance || 0,
|
||||
width: node.isFocus ? 172 : node.characterImportance >= 8 ? 158 : node.characterImportance >= 4 ? 144 : 128,
|
||||
height: node.isFocus ? 58 : node.characterImportance >= 8 ? 52 : 46,
|
||||
isFocus: node.isFocus,
|
||||
isNeighbour: connectedToFocus.has(node.characterID)
|
||||
},
|
||||
classes: [
|
||||
node.isFocus ? "is-focus" : "",
|
||||
node.characterImportance >= 8 ? "is-major-character" : "",
|
||||
node.characterImportance >= 4 && node.characterImportance < 8 ? "is-supporting-character" : "",
|
||||
focusCharacterId && fullNetwork && !node.isFocus && !connectedToFocus.has(node.characterID) ? "is-dimmed" : ""
|
||||
].filter(Boolean).join(" ")
|
||||
})),
|
||||
...links.map(link => ({
|
||||
group: "edges",
|
||||
data: {
|
||||
id: `r-${link.characterRelationshipID}`,
|
||||
relationshipID: link.characterRelationshipID,
|
||||
source: `c-${link.sourceCharacterID}`,
|
||||
target: `c-${link.targetCharacterID}`,
|
||||
label: link.relationshipLabel,
|
||||
category: link.categoryName,
|
||||
intensity: link.intensity || 4,
|
||||
tooltip: buildRelationshipTooltip(relationshipById.get(link.characterRelationshipID))
|
||||
},
|
||||
classes: [
|
||||
link.cssClass,
|
||||
focusCharacterId && fullNetwork && link.sourceCharacterID !== focusCharacterId && link.targetCharacterID !== focusCharacterId ? "is-dimmed" : ""
|
||||
].filter(Boolean).join(" ")
|
||||
}))
|
||||
];
|
||||
|
||||
const cy = cytoscape({
|
||||
container: graph,
|
||||
elements,
|
||||
minZoom: 0.05,
|
||||
maxZoom: 2.5,
|
||||
wheelSensitivity: 0.18,
|
||||
style: relationshipMapStyle(),
|
||||
layout: {
|
||||
name: nodes.length <= 8 ? "circle" : "cose",
|
||||
animate: false,
|
||||
fit: true,
|
||||
padding: 48,
|
||||
nodeRepulsion: 9000,
|
||||
idealEdgeLength: 170,
|
||||
edgeElasticity: 80,
|
||||
numIter: 1200,
|
||||
randomize: false
|
||||
}
|
||||
});
|
||||
|
||||
cy.ready(() => {
|
||||
cy.fit(undefined, 48);
|
||||
const first = relationships[0];
|
||||
if (first) selectRelationship(first.characterRelationshipID);
|
||||
});
|
||||
|
||||
cy.on("tap", "edge", event => {
|
||||
selectRelationship(event.target.data("relationshipID"));
|
||||
});
|
||||
|
||||
cy.on("tap", "node", event => {
|
||||
const characterId = event.target.data("characterID");
|
||||
const characterName = event.target.data("label");
|
||||
const character = nodeById.get(characterId);
|
||||
document.getElementById("relationshipMapEmptyDetail")?.classList.add("d-none");
|
||||
document.getElementById("relationshipMapDetail")?.classList.remove("d-none");
|
||||
document.querySelector("[data-map-detail-title]").textContent = characterName;
|
||||
renderDetailAvatar(character);
|
||||
document.querySelector("[data-map-detail-category]").textContent = "Character";
|
||||
document.querySelector("[data-map-detail-reciprocal]").textContent = characterId === focusCharacterId ? "Focused" : "Node";
|
||||
document.querySelector("[data-map-detail-type]").textContent = "Character";
|
||||
document.querySelector("[data-map-detail-initial]").textContent = "Select a relationship line to see relationship state.";
|
||||
document.querySelector("[data-map-detail-current]").textContent = "Use Character focus to centre this character.";
|
||||
const history = document.querySelector("[data-map-detail-history]");
|
||||
history.innerHTML = "";
|
||||
const li = document.createElement("li");
|
||||
li.innerHTML = `<a href="/Characters/Details/${characterId}">Open character details</a> or <a href="/RelationshipMap?projectId=@Model.Project.ProjectID&focusCharacterId=${characterId}">focus this character</a>.`;
|
||||
history.append(li);
|
||||
});
|
||||
|
||||
cy.on("mouseover", "node, edge", event => {
|
||||
const label = event.target.isNode() ? event.target.data("label") : event.target.data("tooltip");
|
||||
graph.setAttribute("title", label || "");
|
||||
});
|
||||
|
||||
document.querySelector("[data-map-fit]")?.addEventListener("click", () => {
|
||||
cy.resize();
|
||||
cy.fit(undefined, 48);
|
||||
});
|
||||
|
||||
document.querySelector("[data-map-reset]")?.addEventListener("click", () => {
|
||||
cy.layout({
|
||||
name: nodes.length <= 8 ? "circle" : "cose",
|
||||
animate: false,
|
||||
fit: true,
|
||||
padding: 48,
|
||||
randomize: false
|
||||
}).run();
|
||||
});
|
||||
|
||||
window.PlotDirectorRelationshipWorkspace = {
|
||||
cy, focusCharacterId, selectRelationship, selectedRelationship: relationships[0] || null,
|
||||
cast: @Html.Raw(JsonSerializer.Serialize(Model.Cast, jsonOptions)),
|
||||
scenes: @Html.Raw(JsonSerializer.Serialize(Model.SceneOptions, jsonOptions)),
|
||||
changeSceneIDs: @Html.Raw(JsonSerializer.Serialize(Model.ChangeSceneIDs)),
|
||||
projectId: @Model.Project.ProjectID,
|
||||
bookId: @Html.Raw(JsonSerializer.Serialize(Model.BookID)),
|
||||
sceneId: @Html.Raw(JsonSerializer.Serialize(Model.SceneID ?? Model.TimelineSceneID)),
|
||||
update(model) {
|
||||
relationships = model.relationships;
|
||||
relationshipById.clear();
|
||||
relationships.forEach(item => relationshipById.set(item.characterRelationshipID, item));
|
||||
cy.edges().remove();
|
||||
model.links.forEach(link => {
|
||||
for (const id of [link.sourceCharacterID, link.targetCharacterID]) {
|
||||
if (!cy.$id(`c-${id}`).length) {
|
||||
const node = model.cast.find(n => n.characterID === id);
|
||||
cy.add({ data: { id: `c-${id}`, characterID: id, label: node.characterName, width: 144, height: 46 } });
|
||||
}
|
||||
}
|
||||
cy.add({ data: { id: `r-${link.characterRelationshipID}`, relationshipID: link.characterRelationshipID,
|
||||
source: `c-${link.sourceCharacterID}`, target: `c-${link.targetCharacterID}`, label: link.relationshipLabel,
|
||||
intensity: link.intensity || 4, tooltip: buildRelationshipTooltip(relationshipById.get(link.characterRelationshipID)) }, classes: link.cssClass });
|
||||
});
|
||||
const list = document.querySelector('.relationship-map-list');
|
||||
if (list) {
|
||||
list.replaceChildren();
|
||||
relationships.forEach(item => {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button'; button.className = 'relationship-map-list-item';
|
||||
button.dataset.pdContext = 'relationship'; button.dataset.pdContextId = item.characterRelationshipID; button.dataset.pdContextLabel = 'Select relationship';
|
||||
button.textContent = `${item.characterAName} – ${item.characterBName}: ${item.relationshipTypeName} / ${item.currentStateName}`;
|
||||
button.addEventListener('click', () => selectRelationship(item.characterRelationshipID)); list.append(button);
|
||||
});
|
||||
}
|
||||
},
|
||||
relationships: () => relationships
|
||||
};
|
||||
window.addEventListener("resize", () => {
|
||||
window.requestAnimationFrame(() => {
|
||||
cy.resize();
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll("[data-map-select]").forEach(button => {
|
||||
button.addEventListener("click", () => selectRelationship(Number(button.dataset.mapSelect)));
|
||||
});
|
||||
|
||||
function selectRelationship(id) {
|
||||
const relationship = relationshipById.get(id);
|
||||
if (!relationship) return;
|
||||
if (window.PlotDirectorRelationshipWorkspace) window.PlotDirectorRelationshipWorkspace.selectedRelationship = relationship;
|
||||
|
||||
cy.elements().removeClass("is-selected");
|
||||
cy.$id(`r-${id}`).addClass("is-selected");
|
||||
document.querySelectorAll(".relationship-map-list-item").forEach(item => item.classList.remove("is-selected"));
|
||||
document.querySelectorAll(`[data-map-select="${id}"]`).forEach(item => item.classList.add("is-selected"));
|
||||
|
||||
document.getElementById("relationshipMapEmptyDetail")?.classList.add("d-none");
|
||||
document.getElementById("relationshipMapDetail")?.classList.remove("d-none");
|
||||
document.querySelector("[data-map-detail-title]").textContent = `${relationship.characterAName} - ${relationship.characterBName}`;
|
||||
renderDetailAvatar(null);
|
||||
document.querySelector("[data-map-detail-category]").textContent = relationship.relationshipCategoryName;
|
||||
document.querySelector("[data-map-detail-reciprocal]").textContent = relationship.isReciprocal ? "Reciprocal" : "Directional";
|
||||
document.querySelector("[data-map-detail-type]").textContent = relationship.relationshipTypeName;
|
||||
document.querySelector("[data-map-detail-initial]").textContent = formatState(relationship.initialStateName, relationship.initialIntensity);
|
||||
document.querySelector("[data-map-detail-current]").textContent = formatState(relationship.currentStateName, relationship.currentIntensity);
|
||||
|
||||
const history = document.querySelector("[data-map-detail-history]");
|
||||
history.innerHTML = "";
|
||||
relationship.history.forEach(item => {
|
||||
const li = document.createElement("li");
|
||||
const notes = item.notes ? ` - ${item.notes}` : "";
|
||||
li.textContent = `${item.label}: ${formatState(item.stateName, item.intensity)}${notes}`;
|
||||
history.append(li);
|
||||
});
|
||||
}
|
||||
|
||||
function formatState(name, intensity) {
|
||||
return intensity ? `${name} / Intensity ${intensity}` : name;
|
||||
}
|
||||
|
||||
function renderDetailAvatar(character) {
|
||||
const avatar = document.querySelector("[data-map-detail-avatar]");
|
||||
if (!avatar) return;
|
||||
|
||||
avatar.innerHTML = "";
|
||||
if (!character) {
|
||||
avatar.classList.add("d-none");
|
||||
return;
|
||||
}
|
||||
|
||||
const imagePath = character.avatarThumbnailPath || character.avatarImagePath || character.thumbnailPath || character.imagePath;
|
||||
if (imagePath) {
|
||||
const image = document.createElement("img");
|
||||
image.src = imagePath;
|
||||
image.alt = "";
|
||||
image.loading = "lazy";
|
||||
avatar.append(image);
|
||||
} else {
|
||||
const fallback = document.createElement("span");
|
||||
fallback.textContent = initials(character.characterName);
|
||||
avatar.append(fallback);
|
||||
}
|
||||
|
||||
avatar.title = character.characterName;
|
||||
avatar.classList.remove("d-none");
|
||||
}
|
||||
|
||||
function initials(value) {
|
||||
const parts = (value || "")
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.slice(0, 2);
|
||||
const text = parts.map(part => part[0]).join("").toUpperCase();
|
||||
return text || "?";
|
||||
}
|
||||
|
||||
function buildRelationshipTooltip(relationship) {
|
||||
if (!relationship) return "";
|
||||
return `${relationship.characterAName} - ${relationship.characterBName}: ${relationship.relationshipTypeName}; current ${formatState(relationship.currentStateName, relationship.currentIntensity)}`;
|
||||
}
|
||||
|
||||
function relationshipMapStyle() {
|
||||
const isDark = document.documentElement.dataset.theme === "dark";
|
||||
const nodeFill = isDark ? "#222126" : "#fffdf8";
|
||||
const nodeText = isDark ? "#f7efe4" : "#1f2937";
|
||||
const focusFill = isDark ? "#3b2a16" : "#fff3d8";
|
||||
const majorFill = isDark ? "#332417" : "#fff0d5";
|
||||
const supportingFill = isDark ? "#29252c" : "#fbf6ef";
|
||||
const labelFill = isDark ? "#f7efe4" : "#2f3742";
|
||||
const labelBackground = isDark ? "#17171c" : "#fffdf8";
|
||||
return [
|
||||
{
|
||||
selector: "node",
|
||||
style: {
|
||||
"label": "data(label)",
|
||||
"shape": "round-rectangle",
|
||||
"width": "data(width)",
|
||||
"height": "data(height)",
|
||||
"background-color": nodeFill,
|
||||
"border-color": "#6b7280",
|
||||
"border-width": 2,
|
||||
"color": nodeText,
|
||||
"font-size": 12,
|
||||
"font-weight": 650,
|
||||
"text-wrap": "wrap",
|
||||
"text-max-width": 118,
|
||||
"text-valign": "center",
|
||||
"text-halign": "center",
|
||||
"text-margin-y": 0,
|
||||
"padding": "10px",
|
||||
"shadow-blur": 10,
|
||||
"shadow-color": isDark ? "rgba(0, 0, 0, 0.45)" : "rgba(31, 41, 55, 0.18)",
|
||||
"shadow-opacity": 0.32,
|
||||
"shadow-offset-y": 3,
|
||||
"overlay-opacity": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
selector: "node.is-supporting-character",
|
||||
style: {
|
||||
"background-color": supportingFill,
|
||||
"border-color": isDark ? "#b9a891" : "#b99970",
|
||||
"border-width": 2.5,
|
||||
"font-weight": 700
|
||||
}
|
||||
},
|
||||
{
|
||||
selector: "node.is-major-character",
|
||||
style: {
|
||||
"background-color": majorFill,
|
||||
"border-color": "#c47c2c",
|
||||
"border-width": 3,
|
||||
"font-size": 13,
|
||||
"font-weight": 800,
|
||||
"shadow-opacity": 0.42
|
||||
}
|
||||
},
|
||||
{
|
||||
selector: "node.is-focus",
|
||||
style: {
|
||||
"width": "data(width)",
|
||||
"height": "data(height)",
|
||||
"background-color": focusFill,
|
||||
"border-color": "#c47c2c",
|
||||
"border-width": 4,
|
||||
"font-size": 13,
|
||||
"font-weight": 850,
|
||||
"shadow-opacity": 0.5
|
||||
}
|
||||
},
|
||||
{
|
||||
selector: "edge",
|
||||
style: {
|
||||
"label": "data(label)",
|
||||
"curve-style": "bezier",
|
||||
"width": "mapData(intensity, 1, 10, 2, 8)",
|
||||
"line-color": "#7a8796",
|
||||
"target-arrow-shape": "none",
|
||||
"font-size": 11,
|
||||
"font-weight": 700,
|
||||
"color": labelFill,
|
||||
"text-background-color": labelBackground,
|
||||
"text-background-opacity": 0.88,
|
||||
"text-background-padding": 3,
|
||||
"text-rotation": "none",
|
||||
"overlay-opacity": 0
|
||||
}
|
||||
},
|
||||
{ selector: "edge.relationship-category-family", style: { "line-color": "#b86522", "color": "#7c3f12" } },
|
||||
{ selector: "edge.relationship-category-friendship", style: { "line-color": "#2f9e5f", "color": "#14532d" } },
|
||||
{ selector: "edge.relationship-category-romantic", style: { "line-color": "#d9467f", "color": "#831843" } },
|
||||
{ selector: "edge.relationship-category-hostile", style: { "line-color": "#dc3f3f", "color": "#7f1d1d" } },
|
||||
{ selector: "edge.relationship-category-professional", style: { "line-color": "#4f7fd8", "color": "#1e3a8a" } },
|
||||
{ selector: "edge.relationship-category-other", style: { "line-color": "#7a8796", "color": "#374151" } },
|
||||
{
|
||||
selector: ".is-dimmed",
|
||||
style: {
|
||||
"opacity": 0.25
|
||||
}
|
||||
},
|
||||
{
|
||||
selector: "edge.is-selected",
|
||||
style: {
|
||||
"width": 9,
|
||||
"z-index": 20,
|
||||
"text-background-opacity": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
selector: "node:selected",
|
||||
style: {
|
||||
"border-color": "#c47c2c",
|
||||
"border-width": 4
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<script src="~/js/relationship-workspace.js" asp-append-version="true"></script>
|
||||
75
PlotLine/Views/RelationshipMap/_Workspace.cshtml
Normal file
75
PlotLine/Views/RelationshipMap/_Workspace.cshtml
Normal file
@ -0,0 +1,75 @@
|
||||
@model RelationshipMapViewModel
|
||||
<link rel="stylesheet" href="~/css/relationship-workspace.css" asp-append-version="true" />
|
||||
<div class="rw-tools" data-pd-context="workspace">
|
||||
<label>Find character <input id="rwSearch" type="search" class="form-control form-control-sm" autocomplete="off" /></label>
|
||||
<label>Importance <select id="rwImportance" class="form-select form-select-sm"><option value="">All</option><option value="major">8–10</option><option value="supporting">4–7</option><option value="minor">0–3 / unset</option></select></label>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" id="rwConnect">Add relationship</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" id="rwPalettes" aria-expanded="true">Characters</button>
|
||||
<a href="#rwList" class="btn btn-outline-secondary btn-sm">List</a>
|
||||
</div>
|
||||
<div class="rw-board" id="rwBoard">
|
||||
@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));
|
||||
<div class="rw-strip rw-@side" role="region" aria-label="@side character palette" tabindex="0">
|
||||
@foreach (var character in cast)
|
||||
{
|
||||
var portrait = character.AvatarThumbnailPath ?? character.AvatarImagePath ?? character.ThumbnailPath ?? character.ImagePath;
|
||||
<div class="rw-entry" data-pd-context="character" data-rw-entry="@character.CharacterID">
|
||||
<button type="button" draggable="true" class="rw-character" data-pd-context-command data-rw-character="@character.CharacterID" data-importance="@(character.CharacterImportance ?? 0)" aria-label="Focus @character.CharacterName">
|
||||
<span class="visual-avatar" aria-hidden="true">
|
||||
@if (!string.IsNullOrEmpty(portrait)) { <img src="@portrait" alt="" loading="lazy" /> }
|
||||
else { <span>@(string.IsNullOrEmpty(character.CharacterName) ? "?" : character.CharacterName[..1])</span> }
|
||||
</span>
|
||||
<span>@character.CharacterName</span>
|
||||
</button>
|
||||
<button type="button" class="rw-link" draggable="true" data-rw-link="@character.CharacterID" data-pd-context-command aria-label="Add relationship from @character.CharacterName" title="Drag onto a character, or click to connect to the focus">↗</button>
|
||||
<a asp-controller="Characters" asp-action="Edit" asp-route-id="@character.CharacterID" data-pd-context-command class="rw-edit">Edit character</a>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
<div class="rw-centre" data-pd-context="relationship canvas">
|
||||
<div class="relationship-map-toolbar" aria-label="Canvas controls">
|
||||
<button class="btn btn-outline-secondary btn-sm" type="button" data-map-fit>Fit all</button>
|
||||
<button class="btn btn-outline-secondary btn-sm" type="button" data-map-reset>Auto-arrange</button>
|
||||
<button class="btn btn-outline-secondary btn-sm" type="button" id="rwZoomIn" aria-label="Zoom in">+</button>
|
||||
<button class="btn btn-outline-secondary btn-sm" type="button" id="rwZoomOut" aria-label="Zoom out">−</button>
|
||||
<button class="btn btn-outline-secondary btn-sm" type="button" id="rwCentre">Centre focus</button>
|
||||
<button class="btn btn-outline-secondary btn-sm" type="button" id="rwRemove">Remove focused from map</button>
|
||||
<button class="btn btn-outline-secondary btn-sm" type="button" id="rwReset">Reset layout</button>
|
||||
</div>
|
||||
<div id="relationshipMapGraph" class="relationship-map-graph" role="application" aria-label="Relationship canvas. Use character palettes and Add relationship for keyboard editing." tabindex="0"></div>
|
||||
<p id="relationshipMapError" class="alert alert-warning d-none">The renderer could not load. Character details and the relationship list remain available.</p>
|
||||
<p id="rwStatus" role="status" aria-live="polite" class="muted"></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rw-timeline">
|
||||
<label for="rwTimeline">Relationship Timeline: <output id="rwPoint">@Model.StoryPointLabel</output></label>
|
||||
<input id="rwTimeline" type="range" min="0" max="@(Model.SceneOptions.Count + 1)" value="0" step="1" list="rwChanges" />
|
||||
<datalist id="rwChanges"></datalist>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" id="rwPrevious">Previous change</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" id="rwNext">Next change</button>
|
||||
</div>
|
||||
<dialog id="rwDialog" aria-labelledby="rwDialogTitle">
|
||||
<form id="rwForm" asp-controller="RelationshipMap" asp-action="Save" method="post">
|
||||
<h2 id="rwDialogTitle">Create / change relationship</h2>
|
||||
<input type="hidden" name="ProjectID" value="@Model.Project.ProjectID" />
|
||||
<label>Source <select name="SourceID" required class="form-select" asp-items="Model.CharacterOptions"></select></label>
|
||||
<label>Target <select name="TargetID" required class="form-select" asp-items="Model.CharacterOptions"></select></label>
|
||||
<label>Relationship type <select name="TypeID" required class="form-select">
|
||||
@foreach (var type in Model.WorkspaceLookups.RelationshipTypes) { <option value="@type.RelationshipTypeID">@type.TypeName</option> }
|
||||
</select></label>
|
||||
<label>Apply at <select name="SceneID" class="form-select"><option value="">Initial</option>@foreach (var scene in Model.SceneOptions) { <option value="@scene.Value">@scene.Text</option> }</select></label>
|
||||
<label>State <select name="StateID" required class="form-select">@foreach (var state in Model.WorkspaceLookups.RelationshipStates) { <option value="@state.RelationshipStateID">@state.StateName</option> }</select></label>
|
||||
<label>Intensity <input name="Intensity" type="number" min="1" max="10" class="form-control" /></label>
|
||||
<label><input name="Mutual" type="checkbox" value="true" /> Mutual (initial relationship)</label>
|
||||
<label><input name="Known" type="checkbox" value="true" /> Known to reader initially / to other character at scene</label>
|
||||
<label>Notes <textarea name="Notes" maxlength="4000" rows="2" class="form-control"></textarea></label>
|
||||
<p id="rwEditStatus" role="status"></p>
|
||||
<div class="rw-tools"><button type="submit" class="btn btn-primary">Save</button><button type="button" id="rwCancel" class="btn btn-outline-secondary">Cancel</button></div>
|
||||
</form>
|
||||
</dialog>
|
||||
7
PlotLine/wwwroot/css/relationship-workspace.css
Normal file
7
PlotLine/wwwroot/css/relationship-workspace.css
Normal file
@ -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}
|
||||
301
PlotLine/wwwroot/js/relationship-workspace.js
Normal file
301
PlotLine/wwwroot/js/relationship-workspace.js
Normal file
@ -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);
|
||||
})();
|
||||
Loading…
x
Reference in New Issue
Block a user