Make relationships a viewport-filling application workspace

This commit is contained in:
Nick Beckley 2026-10-31 20:36:19 +00:00
parent bb95811e53
commit 6a9b79e6be
9 changed files with 524 additions and 148 deletions

View File

@ -18,7 +18,7 @@ PWA context menus discover commands from `data-pd-context` regions and invoke th
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.
On narrow displays, the correction pass below replaces the four palettes with one searchable character drawer. All desktop 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.
@ -27,3 +27,15 @@ Not included: cross-device layout storage, automatic importance suggestions, tim
## 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.
## Visual/layout correction pass
The page is now a single bounded application surface beneath the existing ribbon in browser and PWA mode. A page-scoped shell class removes content-width limits and gutters. Height follows the actual ribbon and viewport via ResizeObserver; internal palettes, history and List scroll without extending the document. The application maximise mode has an explicit restore button and Escape fallback, with no browser fullscreen API.
The toolbar contains Map/List, a named focus chip with clear action, Auto-arrange, Layout and Display. The legend and original selectors are inside Display. The map's fit, zoom, centre and select/pan controls form a floating vertical toolbar. The right rail shares its space between Supporting characters and contextual detail. Character detail is built from the same canonical response and includes existing avatar, importance, relationship count and selectable connections/history. List is a separate workspace view; no standalone list remains beneath the map.
The timeline retains its existing state resolver, range keyboard navigation and scene defaults. Presentation adds explicit Initial/End buttons, change dots, progress and selected-scene output. Relationship dialogs retain their form and save path, with avatar pairs and subordinate endpoint selectors. Graph nodes retain Cytoscape and category line colours, adding existing portrait paths or generated initials. Node, label, focus, palette and timeline surfaces use the application's semantic theme tokens and update when the active theme changes.
At 800px and below, the four permanent palettes become one drawer: existing character entries move into it and return to their desktop homes on resize. No repeated portrait lists are introduced. Selecting a character dismisses the drawer; Details is independently available. The v1 position/pan/zoom/focus storage and canonical server/save code are unchanged in this pass.
Browser regression coverage additionally checks viewport bounds, complete mobile cast access, Map/List replacement, focus clearing, select/pan controls, maximise/restore and all four principal themes (True Light/Dark use `modern-light`/`modern-dark` theme keys). The normal 75-character/300-scene interactions remain covered. Visual checks use the isolated compiled-Razor fixture; live authenticated author data has not been changed. No schema work or automatic importance inference was added.

View File

@ -77,7 +77,10 @@ const base = 'http://127.0.0.1:5238';
await page.locator('#rwTimeline').fill('100');
await page.waitForFunction(() => document.getElementById('rwStatus').textContent.includes('relationships.'));
await page.waitForTimeout(250);
await page.locator('#rwListView').click();
assert(await page.locator('#rwListPanel').isVisible(), 'List replaces the canvas rather than extending the page');
assert.match(await page.locator('.relationship-map-list').innerText(), /Distrustful/, 'timeline and list share state');
await page.locator('#rwMapView').click();
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');
@ -85,15 +88,52 @@ const base = 'http://127.0.0.1:5238';
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.evaluate(() => { window.PlotDirectorRelationshipWorkspace.cy.zoom(.7); window.PlotDirectorRelationshipWorkspace.cy.pan({x:50,y:70}); });
await page.waitForTimeout(350);
await page.reload(); await page.waitForFunction(() => !!window.PlotDirectorRelationshipWorkspace);
assert(Math.abs(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.zoom()) - .7) < .01, 'layout restores zoom');
for (const width of [1200, 700, 390]) {
assert.deepEqual(await page.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.pan()), {x:50,y:70}, 'layout restores manual pan');
for (const width of [1600, 1200, 700, 390]) {
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);
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 2), 'no horizontal page overflow at ' + width);
assert(await page.evaluate(() => document.documentElement.scrollHeight <= innerHeight + 2), 'no page scrolling at ' + width);
if (width <= 800) {
await page.locator('#rwCharacters').click();
assert.equal(await page.locator('.rw-left [data-rw-character]').count(), 75, 'mobile drawer keeps the complete cast available');
await page.locator('#rwSearch').fill('elan');
await page.locator('[data-rw-character="1"]').click();
assert(await page.locator('.rw-navigation').isHidden(), 'selection returns touch users to the map');
await page.locator('#rwCharacters').click(); await page.locator('#rwSearch').fill(''); await page.locator('#rwCharacters').click();
}
}
await page.setViewportSize({width:1600,height:1000});
for (const theme of ['modern-light','modern-dark','warm-light','warm-dark']) {
await page.evaluate(theme => { document.documentElement.dataset.appTheme = theme; document.documentElement.dataset.theme = theme.endsWith('dark') ? 'dark':'light'; }, theme);
await page.waitForTimeout(100);
const themeState = await page.evaluate(() => {
const w = window.PlotDirectorRelationshipWorkspace, style = getComputedStyle(document.documentElement);
const swatch = document.createElement('span'); swatch.style.color = style.getPropertyValue('--pd-text'); document.body.append(swatch); const expected = getComputedStyle(swatch).color; swatch.remove();
return { node:w.cy.$id('c-1').style('color'), expected, portrait:w.cy.$id('c-1').data('portrait'), canvas:getComputedStyle(document.getElementById('relationshipMapGraph')).backgroundColor };
});
assert(themeState.portrait.startsWith('data:image/svg+xml'), theme+' initials fallback on graph nodes');
assert.equal(themeState.node.replace(/\s/g,''), themeState.expected.replace(/\s/g,''), theme+' graph text follows active theme tokens');
assert(themeState.canvas, theme+' themed canvas');
await page.screenshot({path:`/srv/repos/relationships-${theme}.png`});
}
assert(await page.locator('#rwApp').evaluate(e=>e.getBoundingClientRect().width>=innerWidth-12), 'workspace uses essentially the entire application width');
const beforeMax = await page.locator('#relationshipMapGraph').boundingBox();
await page.locator('#rwMaximise').click();
assert.equal(await page.locator('#rwMaximise').getAttribute('aria-pressed'), 'true');
const afterMax = await page.locator('#relationshipMapGraph').boundingBox(); assert(afterMax.height>beforeMax.height, 'maximise grows the application canvas');
await page.keyboard.press('Escape');
assert.equal(await page.locator('#rwMaximise').getAttribute('aria-pressed'), 'false');
await page.locator('#rwClearFocus').click();
assert.equal(await page.locator('#rwFocusName').innerText(), 'Full cast');
await page.locator('#rwPan').click(); assert(await page.evaluate(()=>window.PlotDirectorRelationshipWorkspace.cy.autoungrabify()));
await page.locator('#rwSelect').click(); assert(!(await page.evaluate(()=>window.PlotDirectorRelationshipWorkspace.cy.autoungrabify())));
assert.equal(await page.locator('.list-section').count(), 0, 'no relationship list below workspace');
// 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 }));
@ -109,6 +149,10 @@ const base = 'http://127.0.0.1:5238';
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');
await app.evaluate(() => window.PlotDirectorRelationshipWorkspace.cy.$id('c-18').emit('cxttap'));
await app.locator('.pd-context-popup').waitFor();
assert.match(await app.locator('.pd-context-popup').innerText(), /Edit character|Add relationship/, 'map context actions remain available when its palette is hidden behind Details');
await app.keyboard.press('Escape');
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(); }

View File

@ -19,23 +19,23 @@ Use it when you want to see family, friendship, romance, conflict, professional
# How To Use It
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.
The map sits between four independently scrolling character palettes. **Major** characters appear at the top, **Supporting** characters at the sides, and **Minor / unset** characters at the bottom. These groups preserve the existing importance thresholds (8+, 4–7 and below 4). Search ignores case and accents; the importance filter narrows the palettes immediately. **Layout → 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.
Click or tap a character to bring them to the centre and activate Focus Mode. With **Show full network** off, the map shows their immediate connections; with it on, unrelated connections are dimmed. The focus chip in the toolbar names the current character; click it or the canvas target control to centre them, or **×** to clear focus.
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.
For keyboard and touch editing, choose **Add relationship**, then select source and target. The arrow beside any palette character also opens the editor with that source. The editor shows the chosen pair with their avatars; expand **Change characters** to edit either endpoint. Choose the existing relationship type, state, intensity and optional notes. Mutual status belongs to the initial relationship; scene changes use the existing mutual status. Review **Apply at** before saving.
**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.
The **Relationship Timeline** shows the state after all changes up to the selected scene. Dots identify scenes with changes, and the selected scene is shown beside the timeline heading. **Initial** and **End** jump to the boundaries. Use the slider's arrow keys or **Previous change / Next change** to navigate without displaying hundreds of labels. **End** shows the state at the final scene. The current point supplies the editor's default scene.
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.
Drag empty canvas to pan. Use **+ / −**, Ctrl/Cmd-wheel, or a two-finger pinch to zoom. The vertical canvas toolbar contains select, pan, fit, zoom and centre controls. **Auto-arrange** recalculates positions. **Layout → Reset layout** restores removed map characters and rearranges locally. **Layout → Remove focused from map** hides a node locally and does not delete the character or relationship. The maximise control expands the workspace within the application; click it again or press Escape to restore.
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.
Installed PWA users can right-click palette characters, map characters, connections or canvas to access the existing application command menu. The same actions are available through buttons, with no right-click required. Select a connection to inspect its history or edit it at the timeline point. **Map / List** switches between workspace views of the same relationship state. The right rail switches between Supporting characters and contextual Details. Focusing a character shows their relationship count, connections, editing actions and history; selecting a connection shows its current state, notes and history.
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.
Positions, focus, zoom, pan and palette collapse are remembered in this browser for the project/book. They do not sync to other devices. On smaller screens, **Characters** opens a searchable drawer containing the whole cast, and **Details** opens the contextual panel. Selecting a character closes the drawer and returns to the map. The canvas and timeline remain the primary surface. **Display** contains the compact relationship legend and the older book/chapter/scene selectors.
# Example

View File

@ -1,29 +1,30 @@
@using System.Text.Json
@model RelationshipMapViewModel
@{
ViewData["Title"] = $"Relationship Map - {Model.Project.ProjectName}";
ViewData["Title"] = $"Relationships - {Model.Project.ProjectName}";
ViewData["ProjectSection"] = "Relationships";
var jsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
ViewData["ShellClass"] = "plotline-shell-wide rw-shell";
}
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
<a asp-controller="Projects" asp-action="Index">Projects</a>
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
<span>Relationship Map</span>
</nav>
<partial name="_ProjectSectionNav" model="Model.Project" />
<div data-pwa-help class="page-heading relationship-workspace-heading">
<div>
<p data-pwa-identity class="eyebrow">Relationships</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">
<link rel="stylesheet" href="~/css/relationship-workspace.css" asp-append-version="true" />
<section id="rwApp" class="rw-app" aria-label="Relationships workspace">
<header class="rw-toolbar" data-pd-context="workspace">
<h1>Relationships <help-icon key="relationshipMap.overview" /></h1>
<div class="rw-view-switch" role="group" aria-label="Workspace view">
<button type="button" class="btn btn-sm" id="rwMapView" aria-pressed="true">Map</button>
<button type="button" class="btn btn-sm" id="rwListView" aria-pressed="false">List</button>
</div>
<div class="rw-focus-chip"><button type="button" id="rwFocusName" title="Centre focused character">Full cast</button><button type="button" id="rwClearFocus" aria-label="Clear character focus" hidden>×</button></div>
<div class="rw-toolbar-actions">
<button type="button" class="btn btn-outline-secondary btn-sm rw-mobile-only" id="rwCharacters" aria-expanded="false">Characters</button>
<button type="button" class="btn btn-outline-secondary btn-sm" id="rwInfo" aria-expanded="false">Details</button>
<button type="button" class="btn btn-outline-secondary btn-sm" id="rwConnect">Add relationship</button>
<button class="btn btn-outline-secondary btn-sm rw-arrange" type="button" data-map-reset>Auto-arrange</button>
<details class="rw-menu"><summary class="btn btn-outline-secondary btn-sm">Layout</summary><div class="rw-menu-panel">
<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>
<button type="button" class="btn btn-outline-secondary btn-sm" id="rwPalettes" aria-expanded="true">Characters</button>
</div></details>
<details class="rw-menu rw-display"><summary class="btn btn-outline-secondary btn-sm">Display</summary><div class="rw-menu-panel">
<form class="relationship-map-controls" method="get" asp-action="Index">
<input type="hidden" name="projectId" value="@Model.Project.ProjectID" />
<div>
<label class="form-label" for="bookId">Book</label>
@ -56,10 +57,7 @@
<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 class="relationship-map-legend-grid">
<div class="relationship-map-legend-grid">
@foreach (var category in Model.Categories)
{
<span class="relationship-map-legend-item @category.CssClass">
@ -68,46 +66,15 @@
</span>
}
</div>
</section>
<section class="relationship-map-workspace">
<div class="relationship-map-canvas plain-card">
<partial name="_Workspace" model="Model" />
</div>
<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>
<p class="muted">Click a connecting line or choose a relationship below to inspect its current state and history.</p>
</div></details>
<button type="button" id="rwMaximise" class="btn btn-outline-secondary btn-sm" aria-label="Maximise workspace" aria-pressed="false" title="Maximise workspace">⛶</button>
</div>
<div id="relationshipMapDetail" class="d-none">
<div class="relationship-map-detail-heading">
<span class="visual-avatar visual-avatar--lg d-none" data-map-detail-avatar aria-hidden="true"></span>
<h2 data-map-detail-title></h2>
</div>
<div class="relationship-map-detail-badges">
<span class="status-pill" data-map-detail-category></span>
<span class="status-pill" data-map-detail-reciprocal></span>
</div>
<dl class="relationship-map-detail-list">
<dt>Relationship type</dt>
<dd data-map-detail-type></dd>
<dt>Initial state</dt>
<dd data-map-detail-initial></dd>
<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 rw-list">
<h2>Visible relationships</h2>
<div class="relationship-map-list">
</header>
<partial name="_Workspace" model="Model" />
<div id="rwListPanel" class="rw-list-panel" hidden aria-label="Relationship list">
<h2>Relationships at the current story point</h2>
<div class="relationship-map-list">
@foreach (var relationship in Model.Relationships)
{
<button data-pd-context="relationship" data-pd-context-id="@relationship.CharacterRelationshipID" data-pd-context-label="Select relationship" data-pwa-icon="relationships" class="relationship-map-list-item" type="button" data-map-select="@relationship.CharacterRelationshipID">
@ -117,8 +84,9 @@
</button>
}
</div>
</section>
</div>
</section>
@section Scripts {
<partial name="_GraphScripts" model="Model" />
}

View File

@ -0,0 +1,26 @@
@model RelationshipMapViewModel
<aside class="relationship-map-details" data-pd-context="relationship" id="rwDetailPanel" hidden>
<div id="relationshipMapEmptyDetail" class="muted">Choose a character or relationship.</div>
<div id="relationshipMapDetail" class="d-none">
<div class="relationship-map-detail-heading">
<span class="visual-avatar visual-avatar--lg d-none" data-map-detail-avatar aria-hidden="true"></span>
<h2 data-map-detail-title></h2>
</div>
<div class="relationship-map-detail-badges">
<span class="status-pill" data-map-detail-category></span>
<span class="status-pill" data-map-detail-reciprocal></span>
</div>
<dl class="relationship-map-detail-list">
<dt>Relationship type</dt><dd data-map-detail-type></dd>
<dt>Initial state</dt><dd data-map-detail-initial></dd>
<dt>Current state</dt><dd data-map-detail-current></dd>
</dl>
<p class="rw-detail-notes" data-map-detail-notes></p>
<p class="muted rw-detail-point" id="rwDetailPoint"></p>
<button type="button" class="btn btn-outline-secondary btn-sm" id="rwEditLine">Edit at timeline point</button>
<a class="btn btn-outline-secondary btn-sm" id="rwEditCharacter" hidden>Edit character</a>
<button type="button" class="btn btn-outline-secondary btn-sm" id="rwDetailConnect">Add relationship</button>
<div id="rwFocusRelationships" aria-label="Focused character relationships"></div>
<details class="rw-history"><summary>History</summary><ol class="relationship-map-history" data-map-detail-history></ol></details>
</div>
</aside>

View File

@ -98,26 +98,6 @@
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 || "");
@ -139,7 +119,7 @@
});
window.PlotDirectorRelationshipWorkspace = {
cy, focusCharacterId, selectRelationship, selectedRelationship: relationships[0] || null,
cy, focusCharacterId, selectRelationship, refreshStyle: () => cy.style(relationshipMapStyle()), 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)),
@ -208,6 +188,7 @@
const history = document.querySelector("[data-map-detail-history]");
history.innerHTML = "";
window.dispatchEvent(new CustomEvent('pd:relationship-selected', { detail: relationship }));
relationship.history.forEach(item => {
const li = document.createElement("li");
const notes = item.notes ? ` - ${item.notes}` : "";
@ -263,14 +244,16 @@
}
function relationshipMapStyle() {
const tokens = getComputedStyle(document.documentElement);
const token = name => tokens.getPropertyValue(name).trim();
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";
const nodeFill = token('--pd-card');
const nodeText = token('--pd-text');
const focusFill = token('--pd-selected');
const majorFill = token('--pd-nested');
const supportingFill = token('--pd-surface');
const labelFill = token('--pd-text');
const labelBackground = token('--pd-canvas');
return [
{
selector: "node",
@ -280,7 +263,7 @@
"width": "data(width)",
"height": "data(height)",
"background-color": nodeFill,
"border-color": "#6b7280",
"border-color": token("--pd-border"),
"border-width": 2,
"color": nodeText,
"font-size": 12,
@ -302,7 +285,7 @@
selector: "node.is-supporting-character",
style: {
"background-color": supportingFill,
"border-color": isDark ? "#b9a891" : "#b99970",
"border-color": token("--pd-border"),
"border-width": 2.5,
"font-weight": 700
}
@ -311,7 +294,7 @@
selector: "node.is-major-character",
style: {
"background-color": majorFill,
"border-color": "#c47c2c",
"border-color": token("--pd-focus"),
"border-width": 3,
"font-size": 13,
"font-weight": 800,
@ -324,7 +307,7 @@
"width": "data(width)",
"height": "data(height)",
"background-color": focusFill,
"border-color": "#c47c2c",
"border-color": token("--pd-focus"),
"border-width": 4,
"font-size": 13,
"font-weight": 850,
@ -349,12 +332,12 @@
"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: "edge.relationship-category-family", style: { "line-color": "#b86522", "color": labelFill } },
{ selector: "edge.relationship-category-friendship", style: { "line-color": "#2f9e5f", "color": labelFill } },
{ selector: "edge.relationship-category-romantic", style: { "line-color": "#d9467f", "color": labelFill } },
{ selector: "edge.relationship-category-hostile", style: { "line-color": "#dc3f3f", "color": labelFill } },
{ selector: "edge.relationship-category-professional", style: { "line-color": "#4f7fd8", "color": labelFill } },
{ selector: "edge.relationship-category-other", style: { "line-color": "#7a8796", "color": labelFill } },
{
selector: ".is-dimmed",
style: {
@ -372,7 +355,7 @@
{
selector: "node:selected",
style: {
"border-color": "#c47c2c",
"border-color": token("--pd-focus"),
"border-width": 4
}
}

View File

@ -1,12 +1,4 @@
@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" })
{
@ -14,7 +6,24 @@
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));
@if (side == "left")
{
@:<aside class="rw-navigation" aria-label="Character search and groups">
<h2>Characters <span>(@Model.Cast.Count)</span></h2>
<label class="visually-hidden" for="rwSearch">Find character</label>
<input id="rwSearch" type="search" class="form-control form-control-sm" placeholder="Find character…" autocomplete="off" />
<label class="visually-hidden" for="rwImportance">Importance</label>
<select id="rwImportance" class="form-select form-select-sm"><option value="">All importance</option><option value="major">Major</option><option value="supporting">Supporting</option><option value="minor">Minor / unset</option></select>
<div class="rw-groups" role="group" aria-label="Character importance groups"><button type="button" data-rw-group="major">Major</button><button type="button" data-rw-group="supporting">Supporting</button><button type="button" data-rw-group="minor">Minor</button></div>
<h3>Supporting characters</h3>
}
@if (side == "right")
{
@:<aside class="rw-rail" aria-label="Characters and relationship detail">
<div class="rw-rail-tabs" role="group" aria-label="Side panel"><button type="button" id="rwPaletteTab" aria-pressed="true">Supporting</button><button type="button" id="rwDetailTab" aria-pressed="false">Details</button></div>
}
<div class="rw-strip rw-@side" role="region" aria-label="@side character palette" tabindex="0">
@if (side == "top" || side == "bottom") { <h2>@(side == "top" ? "Major" : "Minor") <span>(@cast.Count())</span></h2> }
@foreach (var character in cast)
{
var portrait = character.AvatarThumbnailPath ?? character.AvatarImagePath ?? character.ThumbnailPath ?? character.ImagePath;
@ -31,35 +40,43 @@
</div>
}
</div>
@if (side == "right") { <partial name="_Details" model="Model" /> }
@if (side == "left" || side == "right") { @:</aside>
}
}
<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>
<button class="btn btn-outline-secondary btn-sm" type="button" id="rwSelect" aria-label="Select and move characters" title="Select and move characters" aria-pressed="true">↖</button>
<button class="btn btn-outline-secondary btn-sm" type="button" id="rwPan" aria-label="Pan canvas" title="Pan canvas" aria-pressed="false">✥</button>
<button class="btn btn-outline-secondary btn-sm" type="button" data-map-fit aria-label="Fit all" title="Fit all">⛶</button>
<button class="btn btn-outline-secondary btn-sm" type="button" id="rwZoomIn" aria-label="Zoom in" title="Zoom in">+</button>
<button class="btn btn-outline-secondary btn-sm" type="button" id="rwZoomOut" aria-label="Zoom out" title="Zoom out">−</button>
<button class="btn btn-outline-secondary btn-sm" type="button" id="rwCentre" aria-label="Centre focus" title="Centre focus">⊙</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 class="rw-timeline-heading"><label for="rwTimeline">Relationship Timeline</label><output id="rwPoint">@Model.StoryPointLabel</output>
<div><button type="button" class="btn btn-outline-secondary btn-sm" id="rwPrevious" aria-label="Previous change" title="Previous change">‹</button><button type="button" class="btn btn-outline-secondary btn-sm" id="rwNext" aria-label="Next change" title="Next change">›</button></div>
</div>
<div class="rw-timeline-track"><button type="button" class="btn btn-outline-secondary btn-sm" id="rwInitial">Initial</button><div class="rw-scrubber">
<div id="rwTimelineMarkers" class="rw-timeline-markers" aria-label="Relationship changes"></div>
<input id="rwTimeline" type="range" aria-label="Story position" min="0" max="@(Model.SceneOptions.Count + 1)" value="0" step="1" list="rwChanges" />
<datalist id="rwChanges"></datalist>
</div><button type="button" class="btn btn-outline-secondary btn-sm" id="rwEnd">End</button></div>
</div>
</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" />
<div id="rwDialogPair" class="rw-dialog-pair" aria-hidden="true"></div>
<details class="rw-pair-edit"><summary>Change characters</summary>
<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>
</details>
<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>

View File

@ -1,7 +1,131 @@
.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}}
/* A bounded application surface: only palettes, panels and the list scroll. */
body.rw-page { overflow: hidden; }
body.app-layout.rw-page .plotline-shell, .plotline-shell.rw-shell { max-width: none; width: 100%; padding: 4px; }
.rw-page .plotline-help-main { padding: 0; min-width: 0; }
.rw-page main[data-pwa-page-content] { padding: 0 !important; }
.rw-page > footer { display: none; }
.rw-app { height: calc(100dvh - 190px); min-height: 260px; display: grid; grid-template-rows: 44px minmax(0,1fr); gap: 5px; position: relative; font: 12px/1.4 var(--pd-font-ui); color: var(--pd-text); background: var(--pd-workspace); }
.rw-app *, #rwDialog * { box-sizing: border-box; }
.rw-app [hidden] { display: none !important; }
.rw-app h1, .rw-app h2, .rw-app h3 { font-family: var(--pd-font-ui); color: var(--pd-heading); margin: 0; font-weight: 600; }
.rw-app h1 { font-size: 18px; white-space: nowrap; }
.rw-app h2 { font-size: 13px; } .rw-app h3 { font-size: 11px; color: var(--pd-muted); }
.rw-app .btn, #rwDialog .btn { border-radius: 4px; font: 12px/1.3 var(--pd-font-ui); min-height: 30px; padding: 5px 9px; box-shadow: none; }
.rw-app .btn-outline-secondary { color: var(--pd-text); border-color: var(--pd-border); background: var(--pd-control); }
.rw-app :is(button,a,input,select,summary):focus-visible, #rwDialog :is(button,input,select,textarea,summary):focus-visible { outline: 2px solid var(--pd-focus); outline-offset: 2px; }
.rw-app button { cursor: pointer; }
.rw-toolbar { display: flex; align-items: center; gap: 12px; border-bottom: 1px solid var(--pd-border); padding: 3px 6px; min-width: 0; }
.rw-toolbar-actions { display: flex; align-items: center; gap: 6px; margin-left: auto; }
.rw-view-switch { display: flex; border: 1px solid var(--pd-border); border-radius: 5px; }
.rw-app [aria-pressed="true"], .rw-app .rw-entry.is-focus .rw-character { background: var(--pd-selected); color: var(--pd-text); border-color: var(--pd-focus); }
.rw-focus-chip { display: flex; align-items: center; gap: 3px; min-width: 0; border: 1px solid var(--pd-border); border-radius: 4px; }
.rw-focus-chip button { background: transparent; border: 0; color: var(--pd-text); min-height: 30px; }
#rwFocusName { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 230px; }
.rw-menu { position: relative; }
.rw-menu summary { list-style: none; white-space: nowrap; } .rw-menu summary::after { content: '⌄'; margin-left: 7px; }
.rw-menu-panel { position: absolute; right: 0; top: calc(100% + 6px); z-index: 10; display: grid; gap: 7px; width: 240px; max-height: min(70dvh,600px); overflow: auto; padding: 10px; border: 1px solid var(--pd-border); border-radius: 5px; background: var(--pd-elevated); box-shadow: var(--pd-shadow); }
.rw-display .rw-menu-panel { width: min(340px,90vw); }
.rw-app .relationship-map-controls { display: grid; grid-template-columns: 1fr; gap: 7px; padding: 0; margin: 0; border: 0; }
.rw-app .relationship-map-legend-grid { display: flex; flex-wrap: wrap; gap: 7px; font-size: 11px; }
.rw-board { min-height: 0; display: grid; grid-template-columns: 185px minmax(0,1fr) 230px; grid-template-rows: 76px minmax(0,1fr) 88px 72px; gap: 6px; }
.rw-navigation, .rw-rail, .rw-strip, .rw-timeline, .rw-list-panel { border: 1px solid var(--pd-border); border-radius: 5px; background: var(--pd-section); min-width: 0; min-height: 0; }
.rw-navigation { grid-column: 1; grid-row: 1/5; display: flex; flex-direction: column; gap: 7px; padding: 8px 6px; }
.rw-rail { grid-column: 3; grid-row: 1/5; display: flex; flex-direction: column; overflow: hidden; }
.rw-groups { display: flex; gap: 2px; }
.rw-groups button { flex: 1; font-size: 10px; min-height: 28px; background: var(--pd-nested); color: var(--pd-text); border: 1px solid var(--pd-border); border-radius: 3px; padding: 2px; }
.rw-rail-tabs { display: flex; padding: 4px; gap: 4px; border-bottom: 1px solid var(--pd-border); }
.rw-rail-tabs button { flex: 1; border: 1px solid transparent; border-radius: 3px; padding: 6px; background: transparent; color: var(--pd-text); }
.rw-strip { overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; scrollbar-color: var(--pd-border) transparent; display: flex; gap: 4px; padding: 4px; }
.rw-top { grid-column: 2; grid-row: 1; }
.rw-bottom { grid-column: 2; grid-row: 4; }
.rw-left, .rw-right { flex-direction: column; border: 0; flex: 1; }
.rw-top h2, .rw-bottom h2 { position: sticky; left: -4px; z-index: 1; background: var(--pd-section); display: flex; align-items: center; gap: 4px; padding: 6px; min-width: 65px; font-size: 12px; }
.rw-strip h2 span { font-size: 10px; color: var(--pd-muted); }
.rw-entry { flex-shrink: 0; display: flex; align-items: center; min-width: 0; position: relative; }
.rw-character { display: flex; gap: 7px; align-items: center; text-align: left; border: 1px solid transparent; border-radius: 4px; padding: 4px; color: var(--pd-text); background: transparent; font: 12px/1.2 var(--pd-font-ui); min-height: 44px; min-width: 0; flex: 1; }
.rw-character:hover { background: var(--pd-hover); }
.rw-character > span:last-child { overflow: hidden; text-overflow: ellipsis; }
.rw-character .visual-avatar { width: 34px; height: 34px; min-width: 34px; background: var(--pd-nested); border-radius: 4px; color: var(--pd-text); }
.rw-character img { width: 100%; height: 100%; object-fit: cover; }
.rw-top .rw-character, .rw-bottom .rw-character { flex-direction: column; gap: 2px; width: 78px; padding: 2px; font-size: 11px; }
.rw-top .rw-character .visual-avatar, .rw-bottom .rw-character .visual-avatar { width: 38px; height: 38px; }
.rw-link { background: transparent; color: var(--pd-muted); border: 0; width: 24px; min-height: 44px; font-size: 15px; padding: 0; }
.rw-top .rw-link, .rw-bottom .rw-link { position: absolute; right: 0; top: 0; min-height: 24px; width: 20px; }
.rw-edit { display: none; }
.rw-entry.is-focus .rw-character { box-shadow: inset 0 0 0 1px var(--pd-focus); }
.rw-centre { grid-column: 2; grid-row: 2; position: relative; min-width: 0; min-height: 0; overflow: hidden; border: 1px solid var(--pd-border); border-radius: 5px; background: var(--pd-canvas); }
#rwApp .relationship-map-graph { position: absolute; inset: 0; width: 100%; height: 100%; min-height: 0; border: 0; border-radius: 0; background-color: var(--pd-canvas); background-image: radial-gradient(var(--pd-border-subtle) .7px,transparent .7px); background-size: 18px 18px; }
#rwApp .relationship-map-toolbar { position: absolute; top: 8px; left: 8px; z-index: 2; display: flex; flex-direction: column; padding: 4px; gap: 4px; border: 1px solid var(--pd-border); border-radius: 5px; background: var(--pd-elevated); }
#rwApp .relationship-map-toolbar .btn { width: 32px; height: 32px; padding: 2px; font-size: 19px; }
#rwStatus { position: absolute; left: 52px; right: 5px; bottom: 3px; pointer-events: none; font-size: 10px; line-height: 1.3; margin: 0; color: var(--pd-muted); background: var(--pd-canvas); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
#relationshipMapError { position: absolute; bottom: 25px; left: 50px; right: 10px; z-index: 2; }
.rw-timeline { grid-column: 2; grid-row: 3; padding: 6px 10px; overflow: hidden; }
.rw-timeline-heading { display: flex; align-items: center; gap: 8px; min-width: 0; }
.rw-timeline-heading label { font-weight: 600; margin: 0; white-space: nowrap; }
#rwPoint { font-size: 11px; padding: 3px 8px; background: var(--pd-selected); color: var(--pd-text); border: 1px solid var(--pd-border); border-radius: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-left: auto; }
.rw-timeline-heading > div { display: flex; gap: 3px; }
.rw-timeline-track { display: flex; gap: 10px; align-items: center; margin-top: 4px; }
.rw-scrubber { position: relative; flex: 1; min-width: 0; height: 28px; }
#rwTimeline { position: relative; z-index: 1; appearance: none; width: 100%; margin: 10px 0 0; height: 5px; background: linear-gradient(to right,var(--pd-accent) var(--rw-progress,0%),var(--pd-border) var(--rw-progress,0%)); border-radius: 10px; cursor: pointer; }
#rwTimeline::-webkit-slider-thumb { appearance: none; width: 17px; height: 17px; border-radius: 50%; border: 3px solid var(--pd-accent); background: var(--pd-elevated); box-shadow: 0 0 0 3px var(--pd-selected); }
#rwTimeline::-moz-range-thumb { width: 13px; height: 13px; border-radius: 50%; border: 3px solid var(--pd-accent); background: var(--pd-elevated); }
.rw-timeline-markers { position: absolute; inset: 10px 8px auto; height: 5px; z-index: 2; pointer-events: none; }
.rw-timeline-marker { position: absolute; width: 8px; height: 8px; border-radius: 50%; background: var(--pd-accent); border: 1px solid var(--pd-surface); top: -1px; transform: translateX(-50%); }
#rwApp .relationship-map-details { padding: 10px; overflow: auto; flex: 1; min-height: 0; border: 0; box-shadow: none; background: var(--pd-section); color: var(--pd-text); }
#rwApp .relationship-map-detail-heading { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
#rwApp .relationship-map-detail-heading h2 { font-size: 16px; overflow-wrap: anywhere; }
#rwApp .relationship-map-detail-heading .visual-avatar { flex-shrink: 0; width: 56px; height: 56px; border-radius: 5px; }
#rwApp .relationship-map-detail-list { font-size: 11px; display: grid; grid-template-columns: 85px 1fr; gap: 5px; margin: 10px 0; }
#rwApp .relationship-map-detail-list dd { margin: 0; overflow-wrap: anywhere; }
.rw-detail-notes, .rw-detail-point { font-size: 11px; overflow-wrap: anywhere; }
#rwFocusRelationships { display: grid; margin-top: 10px; }
#rwFocusRelationships button { border: 0; border-bottom: 1px solid var(--pd-border-subtle); text-align: left; color: var(--pd-text); background: transparent; padding: 9px 2px; font-size: 11px; }
.rw-history { margin-top: 10px; font-size: 11px; } .rw-history summary { cursor: pointer; padding: 5px 0; }
.rw-app .relationship-map-history { padding-left: 18px; font-size: 11px; }
.rw-list-panel { grid-column: 1; grid-row: 2; overflow: auto; padding: 10px; }
#rwApp .relationship-map-list { display: grid; grid-template-columns: 1fr; gap: 2px; margin-top: 8px; }
#rwApp .relationship-map-list-item { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; padding: 8px; border: 1px solid var(--pd-border-subtle); border-radius: 4px; box-shadow: none; color: var(--pd-text); background: var(--pd-section); min-height: 44px; text-align: left; font-size: 12px; }
#rwApp .relationship-map-list-item strong { flex: 1; }
#rwApp .relationship-map-list-item.is-selected { border-color: var(--pd-focus); background: var(--pd-selected); }
#rwApp .status-pill { font-size: 10px; }
.rw-board.palettes-hidden { grid-template-columns: minmax(0,1fr); grid-template-rows: minmax(0,1fr) 88px; }
.rw-board.palettes-hidden > .rw-strip, .rw-board.palettes-hidden > .rw-navigation, .rw-board.palettes-hidden > .rw-rail { display: none; }
.rw-board.palettes-hidden .rw-centre { grid-column: 1; grid-row: 1; }.rw-board.palettes-hidden .rw-timeline { grid-column: 1; grid-row: 2; }
.rw-app.rw-maximised { position: fixed; inset: 4px; height: auto !important; z-index: 1040; }
#rwDialog { font: 12px/1.4 var(--pd-font-ui); color: var(--pd-text); background: var(--pd-elevated); border: 1px solid var(--pd-border); border-radius: 7px; width: min(480px,96vw); max-height: 90dvh; padding: 16px; }
#rwDialog::backdrop { background: rgb(0 0 0 / 50%); }
#rwForm { display: grid; grid-template-columns: 1fr 1fr; gap: 9px; }
#rwForm > h2, #rwForm > .rw-dialog-pair, #rwForm > .rw-pair-edit, #rwForm > label:has(textarea), #rwEditStatus, #rwForm > .rw-tools { grid-column: 1/-1; }
#rwForm h2 { font: 600 17px var(--pd-font-ui); margin: 0; color: var(--pd-heading); }
#rwForm label { display: block; font-size: 11px; }
#rwForm .form-control, #rwForm .form-select { font-size: 12px; padding: 5px; }
.rw-tools { display: flex; gap: 6px; }
.rw-pair-edit { font-size: 11px; } .rw-pair-edit summary { cursor: pointer; color: var(--pd-muted); }
.rw-pair-edit[open] { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; } .rw-pair-edit summary { grid-column: 1/-1; }
.rw-dialog-pair { display: flex; gap: 10px; align-items: center; padding: 8px; background: var(--pd-nested); border: 1px solid var(--pd-border-subtle); border-radius: 5px; }
.rw-dialog-person { display: flex; align-items: center; gap: 6px; flex: 1; min-width: 0; font-weight: 600; }
.rw-dialog-person .visual-avatar { width: 34px; height: 34px; min-width: 34px; }
@media(max-width:1150px) { .rw-board { grid-template-columns: 150px minmax(0,1fr) 190px; } .rw-toolbar { gap: 5px; } #rwFocusName { max-width: 145px; } .rw-arrange { display: none; } }
@media(max-width:800px) {
.rw-app { grid-template-rows: auto minmax(0,1fr); }
.rw-toolbar { flex-wrap: wrap; gap: 4px; } .rw-toolbar h1 { font-size: 15px; } .rw-toolbar-actions { gap: 4px; }
#rwFocusName { max-width: 120px; } #rwConnect { font-size: 11px; }
.rw-board { grid-template-columns: minmax(0,1fr); grid-template-rows: minmax(0,1fr) 92px; position: relative; }
.rw-board > .rw-top, .rw-board > .rw-bottom { display: none; }
.rw-navigation { display: none; position: absolute; z-index: 5; inset: 0 auto 98px 0; width: min(270px,85%); box-shadow: var(--pd-shadow); }
.rw-board.mobile-characters .rw-navigation { display: flex; }
.rw-rail { display: none; position: absolute; z-index: 4; top: 0; right: 0; bottom: 98px; width: min(260px,85%); box-shadow: var(--pd-shadow); }
.rw-board.mobile-detail .rw-rail { display: flex; }
.rw-centre { grid-column: 1; grid-row: 1; } .rw-timeline { grid-column: 1; grid-row: 2; padding: 5px; }
.rw-timeline-heading label { font-size: 11px; } .rw-timeline-heading { gap: 3px; } #rwPoint { max-width: 45%; }
.rw-groups button { min-height: 32px; }
.rw-board.mobile-characters .rw-top, .rw-board.mobile-characters .rw-bottom, .rw-board.mobile-characters .rw-right { display: none; }
.rw-toolbar-actions #rwPalettes { display: inline-block; }
}
.rw-centre{overflow:hidden}.rw-character span:last-child{overflow:hidden;text-overflow:ellipsis}.rw-link:focus-visible{outline-offset:-2px}
.rw-mobile-only{display:none}
@media(max-width:800px){.rw-mobile-only{display:inline-block}.rw-focus-chip{order:3;max-width:100%;}.rw-toolbar-actions{flex-wrap:wrap}#rwConnect{display:none}.rw-timeline-heading{min-height:30px}}
.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}
body.app-layout.rw-page .plotline-help-layout{margin-top:0;padding-top:0}body.app-layout.rw-page .plotline-help-main{padding-top:0}
body.app-layout.rw-page > .pd-application-header,
body.app-layout.rw-page .pd-application-header .pd-shell { margin-bottom: 0; }

View File

@ -1,6 +1,43 @@
(() => {
const app = document.getElementById('rwApp');
if (!app) return;
document.body.classList.add('rw-page');
let resizeGraph = () => {};
const sizeWorkspace = () => {
if (!app.classList.contains('rw-maximised')) app.style.height = `${Math.max(260, window.innerHeight - app.getBoundingClientRect().top - 5)}px`;
resizeGraph();
};
sizeWorkspace();
window.addEventListener('resize', sizeWorkspace);
const chromeObserver = new ResizeObserver(sizeWorkspace);
const chrome = document.querySelector('.pd-application-header');
if (chrome) chromeObserver.observe(chrome);
new ResizeObserver(() => resizeGraph()).observe(app);
function setView(view) {
document.getElementById('rwBoard').hidden = view === 'list';
document.getElementById('rwListPanel').hidden = view !== 'list';
document.getElementById('rwMapView').setAttribute('aria-pressed', String(view !== 'list'));
document.getElementById('rwListView').setAttribute('aria-pressed', String(view === 'list'));
resizeGraph();
}
document.getElementById('rwMapView').addEventListener('click', () => setView('map'));
document.getElementById('rwListView').addEventListener('click', () => setView('list'));
document.getElementById('rwMaximise').addEventListener('click', event => {
const active = app.classList.toggle('rw-maximised');
event.currentTarget.setAttribute('aria-pressed', String(active));
event.currentTarget.setAttribute('aria-label', active ? 'Restore workspace' : 'Maximise workspace');
event.currentTarget.title = event.currentTarget.getAttribute('aria-label');
sizeWorkspace();
});
document.addEventListener('keydown', event => {
if (event.key === 'Escape' && app.querySelector('.rw-menu[open]')) {
const menu = app.querySelector('.rw-menu[open]'); menu.open = false; menu.querySelector('summary').focus(); return;
}
if (event.key === 'Escape' && app.classList.contains('rw-maximised') && !document.querySelector('dialog[open]')) document.getElementById('rwMaximise').click();
});
document.addEventListener('click', event => app.querySelectorAll('.rw-menu[open]').forEach(menu => { if (!menu.contains(event.target)) menu.open = false; }));
const workspace = window.PlotDirectorRelationshipWorkspace;
if (!workspace) return;
if (!workspace) { setView('list'); return; }
const { cy, cast, scenes, projectId } = workspace;
const graph = document.getElementById('relationshipMapGraph');
const board = document.getElementById('rwBoard');
@ -60,12 +97,18 @@
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 || '';
document.getElementById('rwFocusName').textContent = focus ? `Focus: ${castById.get(focus)?.characterName || ''}` : 'Full cast';
document.getElementById('rwClearFocus').hidden = !focus;
if (focus) renderCharacterDetail();
positionHandle();
}
function focusCharacter(id) {
focus = Number(id); extraNodes.add(focus); ensureNode(focus);
if (cy.zoom() < .6) cy.zoom(.8);
applyFocus(true); remember();
applyFocus(true);
if (window.innerWidth > 800) showRail('detail');
else { board.classList.remove('mobile-characters'); document.getElementById('rwCharacters').setAttribute('aria-expanded', 'false'); }
remember();
}
function normalise(value) { return value.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim(); }
function filter() {
@ -96,6 +139,8 @@
if (type) field('TypeID').value = type.value;
}
populateExisting();
form.querySelector('.rw-pair-edit').open = !from || !to;
renderDialogPair();
dialog.showModal();
}
function populateExisting() {
@ -115,6 +160,7 @@
}
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.';
renderDialogPair();
document.getElementById('rwDialogTitle').textContent = `${castById.get(a)?.characterName || 'Source'} → ${castById.get(b)?.characterName || 'Target'}`;
}
['SourceID', 'TargetID', 'TypeID'].forEach(name => field(name).addEventListener('change', populateExisting));
@ -141,6 +187,7 @@
cy.on('tap cxttap', 'edge', event => {
activeRelationship = workspace.relationships().find(r => r.characterRelationshipID === event.target.data('relationshipID'));
workspace.selectRelationship(event.target.data('relationshipID'));
showRelationshipDetail();
});
document.querySelectorAll('[data-map-select]').forEach(button => button.addEventListener('click', () => {
activeRelationship = workspace.relationships().find(r => r.characterRelationshipID === Number(button.dataset.mapSelect));
@ -177,7 +224,10 @@
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'));
if (target.length && target.data('characterID') !== id) {
focusCharacter(target.data('characterID'));
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() });
@ -212,6 +262,9 @@
});
function openContext(element, original) {
if (!window.PlotDirectorPwa?.standalone || original?.ctrlKey || !element) return;
if (!element.getClientRects().length || element.closest('[hidden]')) {
showRail('detail'); element = document.getElementById('rwDetailPanel');
}
element.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true,
clientX: original?.clientX || 100, clientY: original?.clientY || 100 }));
}
@ -221,22 +274,36 @@
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.getElementById('rwPalettes').addEventListener('click', event => { if (window.innerWidth <= 800) { toggleCharacters(); return; } const hidden = board.classList.toggle('palettes-hidden'); event.currentTarget.setAttribute('aria-expanded', String(!hidden)); cy.resize(); applyFocus(true); remember(); });
document.querySelector('[name="showFullNetwork"]').addEventListener('change', () => applyFocus());
// 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');
function renderMarkers() {
const markers = document.getElementById('rwTimelineMarkers'); markers.replaceChildren();
changes.forEach(n => {
const marker = document.createElement('span'); marker.className = 'rw-timeline-marker';
marker.style.left = `${n / Math.max(1, Number(timeline.max)) * 100}%`; marker.title = scenes[n-1].text;
markers.append(marker);
});
}
renderMarkers();
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);
timeline.setAttribute('aria-valuetext', point.textContent); point.title = point.textContent;
currentScene = index === 0 ? null : Number(scenes[Math.min(index, scenes.length) - 1]?.value) || null;
timeline.style.setProperty('--rw-progress', `${index / Math.max(1, Number(timeline.max)) * 100}%`);
document.getElementById('rwDetailPoint').textContent = `At: ${point.textContent}`;
}
labelPoint();
function navigatePoint(value) { timeline.value = value; timeline.dispatchEvent(new Event('input')); }
document.getElementById('rwInitial').addEventListener('click', () => navigatePoint(0));
document.getElementById('rwEnd').addEventListener('click', () => navigatePoint(timeline.max));
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 => {
@ -260,14 +327,15 @@
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);
renderMarkers();
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');
if (focus) renderCharacterDetail();
else showRail('palette');
} catch (error) { if (error.name !== 'AbortError') { stateLoaded = false; status.textContent = error.message; } }
finally { if (active === request) loading = false; }
}
@ -290,12 +358,146 @@
} catch (error) { editStatus.textContent = error.message; }
finally { submit.disabled = false; }
});
function avatar(character, container) {
container.replaceChildren();
const imagePath = character?.avatarThumbnailPath || character?.avatarImagePath || character?.thumbnailPath || character?.imagePath;
if (imagePath) { const img = document.createElement('img'); img.src = imagePath; img.alt = ''; container.append(img); }
else container.textContent = (character?.characterName || '?').trim().split(/\s+/).slice(0,2).map(x => x[0]).join('').toUpperCase();
}
function renderDialogPair() {
const pair = document.getElementById('rwDialogPair'); pair.replaceChildren();
['SourceID','TargetID'].forEach((name,i) => {
if (i) { const arrow = document.createElement('span'); arrow.textContent = '→'; pair.append(arrow); }
const character = castById.get(Number(field(name).value));
const person = document.createElement('span'); person.className = 'rw-dialog-person';
const portrait = document.createElement('span'); portrait.className = 'visual-avatar'; avatar(character, portrait);
const label = document.createElement('span'); label.textContent = character?.characterName || 'Choose character';
person.append(portrait,label); pair.append(person);
});
}
function showRail(mode) {
document.querySelector('.rw-right').hidden = mode !== 'palette';
document.getElementById('rwDetailPanel').hidden = mode !== 'detail';
document.getElementById('rwPaletteTab').setAttribute('aria-pressed', String(mode === 'palette'));
document.getElementById('rwDetailTab').setAttribute('aria-pressed', String(mode === 'detail'));
}
function renderCharacterDetail() {
const character = castById.get(focus); if (!character) return;
document.getElementById('relationshipMapEmptyDetail').classList.add('d-none');
document.getElementById('relationshipMapDetail').classList.remove('d-none');
document.querySelector('[data-map-detail-title]').textContent = character.characterName;
const portrait = document.querySelector('[data-map-detail-avatar]'); portrait.classList.remove('d-none'); avatar(character, portrait);
const relationships = workspace.relationships().filter(r => r.characterAID === focus || r.characterBID === focus);
const importance = character.characterImportance || 0;
document.querySelector('[data-map-detail-category]').textContent = importance >= 8 ? 'Major' : importance >= 4 ? 'Supporting' : 'Minor / unset';
document.querySelector('[data-map-detail-reciprocal]').textContent = `${relationships.length} relationship${relationships.length === 1 ? '' : 's'}`;
document.querySelector('.relationship-map-detail-list').hidden = true;
document.querySelector('[data-map-detail-notes]').textContent = '';
document.getElementById('rwEditLine').hidden = true;
const edit = document.getElementById('rwEditCharacter'); edit.hidden = false; edit.href = `/Characters/Edit/${focus}`;
const list = document.getElementById('rwFocusRelationships'); list.replaceChildren(); list.hidden = false;
relationships.forEach(r => {
const button = document.createElement('button'); button.type = 'button';
const otherID = r.characterAID === focus ? r.characterBID : r.characterAID;
const otherName = castById.get(otherID)?.characterName || r.characterBName;
button.textContent = `${otherName} · ${r.relationshipTypeName} — ${r.currentStateName}`;
button.addEventListener('click', () => { workspace.selectRelationship(r.characterRelationshipID); showRelationshipDetail(); });
list.append(button);
});
const history = document.querySelector('[data-map-detail-history]'); history.replaceChildren();
relationships.flatMap(r => r.history.map(h => ({...h, type:r.relationshipTypeName}))).filter(h => h.sceneID).forEach(h => {
const item = document.createElement('li'); item.textContent = `${h.label}: ${h.type} — ${h.stateName}`; history.append(item);
});
}
function showRelationshipDetail() {
const relationship = workspace.selectedRelationship; if (!relationship) return;
document.querySelector('.relationship-map-detail-list').hidden = false;
document.querySelector('[data-map-detail-notes]').textContent = relationship.notes || '';
document.getElementById('rwEditLine').hidden = false;
document.getElementById('rwEditCharacter').hidden = true;
document.getElementById('rwFocusRelationships').hidden = true;
showRail('detail');
}
function toggleCharacters() {
setView('map');
const active = board.classList.toggle('mobile-characters');
board.classList.remove('mobile-detail'); document.getElementById('rwInfo').setAttribute('aria-expanded', 'false');
document.getElementById('rwCharacters').setAttribute('aria-expanded', String(active));
if (active) document.getElementById('rwSearch').focus();
}
function decorateNodes() {
const tokens = getComputedStyle(document.documentElement);
cy.nodes().forEach(node => {
const character = castById.get(node.data('characterID'));
const name = character?.characterName || '?';
const initials = name.trim().split(/\s+/).slice(0,2).map(p => p[0]).join('').toUpperCase().replace(/[<>&"']/g,'');
const image = character?.avatarThumbnailPath || character?.avatarImagePath || character?.thumbnailPath || character?.imagePath;
const fallback = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><rect width="40" height="40" rx="5" fill="${tokens.getPropertyValue('--pd-nested').trim()}"/><text x="20" y="25" font-family="sans-serif" font-size="15" text-anchor="middle" fill="${tokens.getPropertyValue('--pd-text').trim()}">${initials}</text></svg>`)}`;
node.data('portrait', image || fallback);
});
cy.style().selector('node').style({ 'background-image':'data(portrait)', 'background-fit':'none', 'background-width':34, 'background-height':34, 'background-position-x':'8px', 'background-position-y':'50%', 'text-margin-x':20, 'text-max-width':105 }).update();
cy.style().selector('node.is-drop-target').style({ 'border-width':6, 'border-color':tokens.getPropertyValue('--pd-success').trim(), 'overlay-opacity':.15 }).update();
}
function initialisePresentation() {
let graphWidth = graph.clientWidth, graphHeight = graph.clientHeight;
resizeGraph = () => {
const width = graph.clientWidth, height = graph.clientHeight; if (!width || !height) return;
const changed = width !== graphWidth || height !== graphHeight;
const pan = cy.pan(); cy.resize();
if (changed && focus) cy.center(cy.$id(`c-${focus}`)); else cy.pan(pan);
graphWidth = width; graphHeight = height; positionHandle();
};
const homes = new Map([...document.querySelectorAll('[data-rw-entry]')].map(e => [e,e.parentElement]));
const adaptPalettes = () => {
const mobile = window.innerWidth <= 800;
const left = document.querySelector('.rw-left');
homes.forEach((home, entry) => (mobile ? left : home).append(entry));
document.querySelector('.rw-navigation h3').textContent = mobile ? 'All characters' : 'Supporting characters';
if (!mobile) { board.classList.remove('mobile-characters','mobile-detail'); }
resizeGraph();
};
const breakpoint = matchMedia('(max-width:800px)'); breakpoint.addEventListener('change', adaptPalettes); adaptPalettes();
document.getElementById('rwCharacters').addEventListener('click', toggleCharacters);
document.getElementById('rwPaletteTab').addEventListener('click', () => showRail('palette'));
document.getElementById('rwDetailTab').addEventListener('click', () => { if (focus) renderCharacterDetail(); showRail('detail'); });
document.getElementById('rwInfo').addEventListener('click', () => {
if (focus) renderCharacterDetail(); showRail('detail');
const active = board.classList.toggle('mobile-detail'); board.classList.remove('mobile-characters');
document.getElementById('rwInfo').setAttribute('aria-expanded', String(active));
});
document.getElementById('rwClearFocus').addEventListener('click', () => { focus = null; applyFocus(); showRail('palette'); remember(); });
document.getElementById('rwFocusName').addEventListener('click', () => applyFocus(true));
document.getElementById('rwDetailConnect').addEventListener('click', () => openEditor(null, focus));
document.getElementById('rwSelect').addEventListener('click', () => setPanMode(false));
document.getElementById('rwPan').addEventListener('click', () => setPanMode(true));
document.querySelectorAll('[data-rw-group]').forEach(button => button.addEventListener('click', () => {
const input = document.getElementById('rwImportance'); input.value = input.value === button.dataset.rwGroup ? '' : button.dataset.rwGroup;
input.dispatchEvent(new Event('change'));
const target = input.value === 'major' ? '.rw-top' : input.value === 'minor' ? '.rw-bottom' : '.rw-left';
document.querySelector(target)?.scrollTo(0,0);
}));
document.querySelector('.relationship-map-list').addEventListener('click', event => { if (event.target.closest('button')) showRelationshipDetail(); });
decorateNodes();
cy.on('add', 'node', () => decorateNodes());
const themeObserver = new MutationObserver(() => { workspace.refreshStyle(); decorateNodes(); });
themeObserver.observe(document.documentElement, { attributes:true, attributeFilter:['data-app-theme'] });
window.addEventListener('pd:relationship-selected', showRelationshipDetail);
sizeWorkspace();
}
function setPanMode(active) {
cy.autoungrabify(active); graph.style.cursor = active ? 'grab' : '';
document.getElementById('rwSelect').setAttribute('aria-pressed', String(!active));
document.getElementById('rwPan').setAttribute('aria-pressed', String(active));
}
initialisePresentation();
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);
if (focus && window.innerWidth > 800) showRail('detail');
})();