PlotDirector/PlotLine/wwwroot/js/relationship-main.js

2312 lines
80 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Opt-in main Relationships controller. No Context/Character Details renderer or state is changed.
(() => {
"use strict";
const LAYOUTS = [
["clusters", "Relationship clusters", "relationships"],
["radial", "Focused radial", "focus"],
["family", "Traditional family tree", "characters"],
["importance", "Story importance", "attribute-star-filled"],
["circle", "Circle", "layout"],
];
const PRESETS = [
["connected", "Connected characters"],
["full", "Full cast"],
["major", "Major and Supporting"],
["selected", "Selected character and connections"],
["family", "Family only"],
["custom", "Custom diagram"],
];
const tier = (value) =>
value >= 8 ? "10" : value >= 4 ? "6" : value >= 1 ? "2" : "";
const copy = (value) => JSON.parse(JSON.stringify(value));
window.PlotDirectorMainRelationships = {
mount(a) {
const { app, workspace: w, cy, graph, board, cast, castById } = a,
geometry = window.PlotDirectorMainRelationshipLayout,
toast = Object.fromEntries(
["info", "success", "error", "warning"].map((kind) => [
kind,
(...args) => window.PlotDirector?.toast?.[kind](...args),
]),
),
life = new AbortController(),
listen = (n, e, fn, options = {}) =>
n?.addEventListener(e, fn, { ...options, signal: life.signal });
const user =
document.body.dataset.pdUserId ||
document.querySelector("[data-toast-host]")?.dataset.toastUser ||
"session",
storageKey = `pd.relationship-workspace.v2.${user}.${w.projectId}.${w.bookId || "project"}`;
const $ = (id) => document.getElementById(id),
status = $("rwStatus"),
presetControl = $("rwPreset"),
layoutControl = $("rwLayout"),
connectorControl = $("rwConnector"),
depthControl = $("rwDepth");
for (const [id, label] of PRESETS)
presetControl.add(new Option(label, id));
for (const [id, label] of LAYOUTS)
layoutControl.add(new Option(label, id));
let initialised = false,
viewUnavailable = false,
pendingCommands = 0;
function command(task) {
pendingCommands++;
return Promise.resolve()
.then(task)
.catch((error) => {
syncControls();
toast.error(error.message);
})
.finally(() => pendingCommands--);
}
function setPreset(next) {
return command(() => performPreset(next));
}
function arrange(kind, options) {
return command(() => performArrange(kind, options));
}
let saved;
try {
saved = JSON.parse(localStorage.getItem(storageKey) || "null");
} catch {}
// Claim legacy browser preferences once; never import another author's unscoped state.
let legacy = null;
try {
const suffix = `${w.projectId}.${w.bookId || "project"}`,
ownerKey = "pd.relationship-workspace.v1-owner." + suffix;
let owner = localStorage.getItem(ownerKey);
if (!owner) {
owner = user;
localStorage.setItem(ownerKey, user);
}
if (owner === user) {
if (!saved) legacy = a.legacy;
localStorage.removeItem("pd.relationship-workspace.v1." + suffix);
}
} catch {
/* Optional legacy migration. */
}
let preset =
saved?.preset ||
(legacy
? legacy.focus
? "selected"
: "custom"
: w.focusCharacterId
? "selected"
: "connected"),
layout = saved?.layout || "clusters",
connector = saved?.connector || "auto",
depth = Math.max(1, Math.min(6, saved?.depth || 2)),
familyRoot = saved?.familyRoot || null,
allLabels = !!saved?.allLabels;
if (!PRESETS.some(([id]) => id === preset)) preset = "connected";
if (!LAYOUTS.some(([id]) => id === layout)) layout = "clusters";
if (!["auto", "straight", "curved", "orthogonal"].includes(connector))
connector = "auto";
let members = new Set(
(
saved?.members ||
(legacy &&
cast
.map((c) => c.characterID)
.filter((id) => !legacy.removed?.includes(id))) ||
[]
).filter((id) => castById.has(id)),
),
pins = new Set((saved?.pins || []).filter((id) => castById.has(id))),
custom = saved?.custom || null;
let family = null,
familyPromise = null,
familyEpoch = 0,
readVersions = new Map(),
canEdit = w.canEdit,
assignBusy = false,
pendingHint = false,
undoAttribute = null,
undoStack = [],
saveTimer,
routeFrame,
layoutEpoch = 0,
arranging = false,
worker,
workerReady,
pendingWorker = new Map(),
workerSequence = 0,
modelSync = false,
connection,
refreshTimer,
menuHit = null,
dragSnapshot = null;
const positions = new Map(
Object.entries(saved?.positions || legacy?.positions || {})
.filter(
([id, p]) =>
castById.has(+id.replace("c-", "")) &&
Number.isFinite(p?.x) &&
Number.isFinite(p?.y),
)
.map(([id, p]) => [+id.replace("c-", ""), { x: p.x, y: p.y }]),
);
const definitions = w.importanceDefinitions || [],
definition = (value) =>
definitions.find((v) => v.value === tier(value)),
known = (id) => castById.has(+id),
node = (id) => cy.$id("c-" + id),
visible = () => cy.nodes(":visible"),
isFamily = () => preset === "family" || layout === "family",
familyRecords = () => family?.relationships || [];
function records() {
return isFamily() ? familyRecords() : w.relationships();
}
function edges() {
return records().map((r) => ({
id: r.characterRelationshipID,
a: r.characterAID,
b: r.characterBID,
type: r.relationshipTypeName,
reciprocal: r.isReciprocal,
record: r,
}));
}
function snapshot() {
if (viewUnavailable) {
try {
const retained = localStorage.getItem(storageKey);
if (retained) return JSON.parse(retained);
} catch {}
if (saved) return copy(saved);
}
const ps = Object.fromEntries(positions);
cy.nodes().forEach((n) => {
const id = n.data("characterID");
if (known(id) && !viewUnavailable && !familyPromise)
ps[id] = { ...n.position() };
});
return {
members: [...members],
positions: ps,
pins: [...pins],
preset,
layout,
connector,
depth,
familyRoot,
familyRoutes: Object.fromEntries(familyRoutes),
zoom: cy.zoom(),
pan: { ...cy.pan() },
focus: a.getFocus(),
allLabels,
view: $("rwListPanel").hidden ? "map" : "list",
custom: copy(custom),
collapsed: board.classList.contains("palettes-hidden"),
};
}
function remember() {
clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
if (viewUnavailable || familyPromise) return;
try {
localStorage.setItem(storageKey, JSON.stringify(snapshot()));
} catch {}
}, 250);
}
function checkpoint() {
layoutEpoch++;
undoStack.push(snapshot());
if (undoStack.length > 24) undoStack.shift();
$("rwUndoLayout").disabled = false;
}
function rememberCustom() {
custom = {
members: [...members],
positions: Object.fromEntries(positions),
pins: [...pins],
layout,
zoom: cy.zoom(),
pan: { ...cy.pan() },
};
cy.nodes().forEach((n) => {
if (known(n.data("characterID")))
custom.positions[n.data("characterID")] = { ...n.position() };
});
}
function toCustom() {
if (preset === "custom") return;
preset = "custom";
familyRoot = null;
rememberCustom();
syncControls();
}
function restoreView(view) {
members = new Set((view.members || []).filter(known));
pins = new Set((view.pins || []).filter(known));
preset = view.preset || "custom";
layout = view.layout || "clusters";
connector = view.connector || connector;
depth = view.depth || depth;
familyRoot = view.familyRoot || null;
allLabels = view.allLabels ?? allLabels;
custom = copy(view.custom ?? custom);
familyRoutes = new Map(
Object.entries(view.familyRoutes || {}).map(([id, d]) => [+id, d]),
);
a.setFocus(known(view.focus) ? view.focus : null);
for (const [id, p] of Object.entries(view.positions || {}))
if (known(id) && Number.isFinite(p?.x) && Number.isFinite(p?.y)) {
positions.set(+id, { ...p });
a.ensureNode(+id).position(p);
}
if (Number.isFinite(view.zoom)) cy.zoom(view.zoom);
if (Number.isFinite(view.pan?.x) && Number.isFinite(view.pan?.y))
cy.pan(view.pan);
a.setView(view.view || "map");
syncControls();
void applyFocus(false);
}
function undoLayout() {
const previous = undoStack.pop();
if (!previous) return;
layoutEpoch++;
restoreView(previous);
$("rwUndoLayout").disabled = !undoStack.length;
remember();
toast?.info("Previous diagram state restored.");
}
function neighbours(start, links, maximum = depth, allowed) {
const adj = new Map();
for (const e of links) {
if (allowed && (!allowed.has(e.a) || !allowed.has(e.b))) continue;
if (!adj.has(e.a)) adj.set(e.a, []);
if (!adj.has(e.b)) adj.set(e.b, []);
adj.get(e.a).push(e.b);
adj.get(e.b).push(e.a);
}
const found = new Set(known(start) ? [start] : []),
queue = [{ id: start, d: 0 }];
for (let i = 0; i < queue.length; i++) {
const next = queue[i];
if (next.d >= maximum) continue;
for (const id of adj.get(next.id) || [])
if (!found.has(id)) {
found.add(id);
queue.push({ id, d: next.d + 1 });
}
}
return found;
}
async function loadFamily(force = false) {
if (family && !force) return family;
if (familyPromise) return familyPromise;
const epoch = familyEpoch;
familyPromise = (async () => {
const response = await fetch(
"/RelationshipMap/Family?" +
new URLSearchParams({ projectId: w.projectId }),
{ cache: "no-store", signal: life.signal },
);
if (!response.ok || response.redirected)
throw Error(
"Author-reference family relationships could not be loaded.",
);
const result = await response.json();
if (epoch !== familyEpoch) return null;
family = result;
return result;
})();
try {
return await familyPromise;
} finally {
familyPromise = null;
}
}
function freePosition(id, preferred) {
const c = castById.get(id),
other = cy
.nodes()
.filter(
(n) =>
n.data("characterID") !== id &&
members.has(n.data("characterID")) &&
positions.has(n.data("characterID")),
)
.map((n) => ({
id: n.data("characterID"),
w: n.outerWidth(),
h: n.outerHeight(),
...n.position(),
})),
w = 190,
h = 82;
let near = preferred;
const neighbour = edges().find(
(e) =>
(e.a === id && members.has(e.b)) ||
(e.b === id && members.has(e.a)),
);
if (!near && neighbour) {
const n = node(neighbour.a === id ? neighbour.b : neighbour.a);
if (n.length) near = n.position();
}
near ||= {
x: (graph.clientWidth / 2 - cy.pan().x) / cy.zoom(),
y: (graph.clientHeight / 2 - cy.pan().y) / cy.zoom(),
};
const ps = Object.fromEntries(
other.map((n) => [n.id, { x: n.x, y: n.y }]),
);
ps[id] = near;
const pinPositions = Object.fromEntries(
other.map((n) => [n.id, { x: n.x, y: n.y }]),
);
return geometry.noOverlap(
[...other, { id, w, h }],
ps,
pinPositions,
28,
)[id];
}
function ensurePosition(id, preferred) {
const n = a.ensureNode(id);
if (!n.length) return n;
const p = preferred || positions.get(id) || freePosition(id);
n.position(p);
positions.set(id, { ...p });
return n;
}
function effectiveConnector() {
return connector === "auto"
? isFamily()
? "orthogonal"
: "curved"
: connector;
}
function syncControls() {
presetControl.value = preset;
layoutControl.value = layout;
connectorControl.value = connector;
depthControl.value = String(depth);
$("rwAllLabels").checked = allLabels;
document.querySelector('[name="showFullNetwork"]').checked =
preset === "full";
$("rwCharacterMenu").hidden = !a.getFocus();
$("rwClearPins").disabled = !pins.size;
$("rwUndoLayout").disabled = !undoStack.length;
app.dataset.diagramPreset = preset;
app.dataset.connectorStyle = effectiveConnector();
app.dataset.diagramLayout = layout;
for (const id of ["rwConnect", "rwDetailConnect", "rwEditLine"])
if ($(id)) $(id).disabled = !canEdit;
$("rwFocusName").title = $("rwFocusName").textContent;
$("rwFocusName").setAttribute(
"aria-description",
"Diagram character focus; does not change manuscript focus",
);
}
function updateMembership() {
const reference =
preset === "family"
? edges()
: w
.relationships()
.map((r) => ({ a: r.characterAID, b: r.characterBID }));
let desired;
if (preset === "custom") desired = new Set([...members].filter(known));
else if (preset === "full")
desired = new Set(cast.map((c) => c.characterID));
else if (preset === "major")
desired = new Set(
cast
.filter((c) => c.characterImportance >= 4)
.map((c) => c.characterID),
);
else if (preset === "selected")
desired = neighbours(a.getFocus(), reference);
else if (preset === "family")
desired = familyRoot
? neighbours(familyRoot, edges())
: new Set(edges().flatMap((e) => [e.a, e.b]));
else desired = new Set(reference.flatMap((e) => [e.a, e.b]));
members = new Set([...desired].filter(known));
}
let legendSignature = "";
function renderLegend() {
const values = [
...new Map(
records().map((r) => [
r.relationshipCategoryName,
{ label: r.relationshipCategoryName, css: r.cssClass },
]),
).values(),
],
signature = JSON.stringify(values);
if (signature === legendSignature) return;
legendSignature = signature;
const host = app.querySelector(".relationship-map-legend-grid");
if (!host) return;
host.replaceChildren(
...values.map((value) => {
const item = document.createElement("span");
item.className =
"relationship-map-legend-item " + (value.css || "");
const line = document.createElement("span");
line.className = "relationship-map-legend-line";
line.setAttribute("aria-hidden", "true");
item.append(
line,
document.createTextNode(value.label || "Relationship"),
);
return item;
}),
);
}
function renderList() {
const host = app.querySelector(".relationship-map-list");
if (!host) return;
const title = $("rwListPanel").querySelector("h2");
title.textContent = isFamily()
? "Author-reference family relationships"
: "Relationships at the current story point";
host.replaceChildren(
...records()
.filter(
(r) => members.has(r.characterAID) && members.has(r.characterBID),
)
.map((r) => {
const button = document.createElement("button");
button.type = "button";
button.className = "relationship-map-list-item";
button.textContent = `${r.characterAName} – ${r.characterBName}: ${r.relationshipTypeName} / ${r.currentStateName}`;
button.addEventListener("click", () =>
selectRelationship(r.characterRelationshipID),
);
return button;
}),
);
}
let referenceRecords = null;
function syncReferenceEdges() {
const current = records();
if (referenceRecords === current) return;
for (const r of current) {
if (!known(r.characterAID) || !known(r.characterBID)) continue;
for (const id of [r.characterAID, r.characterBID]) a.ensureNode(id);
let e = cy.$id("r-" + r.characterRelationshipID);
const data = {
relationshipID: r.characterRelationshipID,
source: "c-" + r.characterAID,
target: "c-" + r.characterBID,
label: r.relationshipTypeName,
intensity: r.currentIntensity || r.initialIntensity || 4,
category: r.relationshipCategoryName,
tooltip: `${r.characterAName} — ${r.relationshipTypeName} — ${r.characterBName}: ${r.currentStateName}${isFamily() ? " (author reference)" : ""}`,
};
if (!e.length)
e = cy.add({
group: "edges",
data: { id: "r-" + r.characterRelationshipID, ...data },
classes: r.cssClass,
});
else {
if (
e.source().id() !== data.source ||
e.target().id() !== data.target
)
e.move({ source: data.source, target: data.target });
e.data(data);
const selected = e.hasClass("is-selected"),
hover = e.hasClass("is-main-hover");
e.classes(r.cssClass || "");
e.toggleClass("is-selected", selected);
e.toggleClass("is-main-hover", hover);
}
if (isFamily()) {
const role = window.PlotDirectorContextRelationshipLayout.role({
a: r.characterAID,
b: r.characterBID,
type: r.relationshipTypeName,
reciprocal: r.isReciprocal,
});
e.style(
"line-style",
role.style === "adoptive"
? "dashed"
: role.style === "step"
? "dotted"
: "solid",
);
} else e.removeStyle("line-style");
e.data("mainFamily", isFamily());
}
referenceRecords = current;
}
async function applyFocus(centre = false) {
if (isFamily() && !family && (preset !== "custom" || members.size)) {
status.textContent = "Loading author-reference family facts…";
try {
await loadFamily();
} catch (error) {
status.textContent = error.message;
viewUnavailable = true;
if (!initialised) cy.elements().hide();
return false;
}
}
viewUnavailable = false;
updateMembership();
if (isFamily())
cy.nodes().style({ width: 180, height: 66, padding: 0 });
else cy.nodes().removeStyle("width height padding");
modelSync = true;
cy.batch(() => {
syncReferenceEdges();
for (const id of members) ensurePosition(id);
cy.nodes().forEach((n) => {
const id = n.data("characterID");
n.removeClass("is-focus is-dimmed");
n.toggleClass("is-main-pinned", pins.has(id));
if (members.has(id)) n.show();
else n.hide();
if (pins.has(id)) n.lock();
else n.unlock();
});
const allowedEdges = new Set(edges().map((e) => "r-" + e.id));
cy.edges().forEach((e) => {
if (
allowedEdges.has(e.id()) &&
members.has(+e.source().data("characterID")) &&
members.has(+e.target().data("characterID"))
)
e.show();
else e.hide();
});
const selectedNode = node(a.getFocus());
if (selectedNode.length && selectedNode.visible())
selectedNode.addClass("is-focus");
});
modelSync = false;
app
.querySelectorAll("[data-rw-entry]")
.forEach((e) =>
e.classList.toggle("is-focus", +e.dataset.rwEntry === a.getFocus()),
);
$("focusCharacterId").value = a.getFocus() || "";
$("rwFocusName").textContent = a.getFocus()
? "Focus: " + (castById.get(a.getFocus())?.characterName || "")
: PRESETS.find(([id]) => id === preset)?.[1] || "Diagram";
$("rwClearFocus").hidden = !a.getFocus();
$("rwEmpty").hidden = members.size > 0;
if (a.getFocus()) a.renderCharacterDetail();
a.positionHandle();
if (centre) {
const selected = node(a.getFocus());
if (selected.length && selected.visible()) cy.center(selected);
}
syncControls();
renderLegend();
if (!$("rwListPanel").hidden) renderList();
refreshIndicators();
scheduleRoutes();
remember();
status.textContent = `${members.size} displayed · ${cy.edges(":visible").length} ${isFamily() ? "author-reference family" : "recorded"} connections${arranging ? " · Arranging…" : ""}.`;
}
function focusCharacter(id, centre = true) {
id = +id;
if (!known(id)) return;
a.setFocus(id);
if (!members.has(id)) {
checkpoint();
toCustom();
members.add(id);
ensurePosition(id);
}
void applyFocus(centre);
if (window.innerWidth > 800) a.showDetail();
else {
board.classList.remove("mobile-characters");
$("rwCharacters").setAttribute("aria-expanded", "false");
}
remember();
}
function clearFocus() {
a.setFocus(null);
if (preset === "selected") preset = "connected";
a.clearDetail();
void applyFocus(false);
remember();
}
function remove(id = a.getFocus()) {
if (!known(id) || !members.has(id)) return;
checkpoint();
toCustom();
members.delete(+id);
pins.delete(+id);
if (a.getFocus() === +id) {
a.setFocus(null);
a.clearDetail();
}
void applyFocus(false);
remember();
toast?.info(
"Character removed from this diagram; project records retained.",
);
}
function clear() {
if (!members.size && preset === "custom") return;
checkpoint();
toCustom();
members.clear();
pins.clear();
a.setFocus(null);
a.clearDetail();
void applyFocus(false);
remember();
toast?.info(
"Diagram cleared. Project characters and relationships retained.",
);
}
function add(id, position) {
if (!known(id)) return;
checkpoint();
toCustom();
members.add(+id);
const n = ensurePosition(+id, pins.has(+id) ? null : position);
a.setFocus(+id);
void applyFocus(false);
n.select();
remember();
}
function pin(id = a.getFocus()) {
if (!known(id) || !members.has(id) || !node(id).visible()) return;
checkpoint();
pins.has(id) ? pins.delete(id) : pins.add(id);
positions.set(id, { ...node(id).position() });
void applyFocus(false);
remember();
}
async function performPreset(next) {
if (!PRESETS.some(([id]) => id === next)) return;
if (next === "family") await loadFamily();
checkpoint();
layoutEpoch++;
if (preset === "custom") rememberCustom();
preset = next;
familyRoot = null;
if (next !== "family" && layout === "family") {
layout = "clusters";
familyRoutes.clear();
visible().removeStyle("width height padding");
}
if (next === "custom" && custom) {
members = new Set(custom.members.filter(known));
pins = new Set(custom.pins.filter(known));
layout = custom.layout || layout;
for (const [id, p] of Object.entries(custom.positions))
if (known(id)) {
positions.set(+id, p);
a.ensureNode(+id).position(p);
}
cy.zoom(custom.zoom);
cy.pan(custom.pan);
}
await applyFocus(false);
if (next === "family") {
layout = "family";
await arrange("family", { checkpoint: false });
}
remember();
}
function dimensions() {
return visible().map((n) => ({
id: n.data("characterID"),
name: n.data("label"),
importance: castById.get(n.data("characterID"))?.characterImportance,
w: n.boundingBox().w,
h: n.boundingBox().h,
...n.position(),
birthDate: family?.nodes?.find((c) => c.id === n.data("characterID"))
?.birthDate,
}));
}
function startWorker() {
if (worker) return workerReady;
try {
worker = new Worker(w.assetUrls.worker);
workerReady = new Promise((resolve, reject) => {
worker.onmessage = (event) => {
if (event.data.ready) {
resolve();
return;
}
const pending = pendingWorker.get(event.data.id);
if (!pending) return;
pendingWorker.delete(event.data.id);
event.data.error
? pending.reject(Error(event.data.error))
: pending.resolve(event.data.result);
};
worker.onerror = () => {
reject(Error("Layout worker unavailable"));
for (const pending of pendingWorker.values())
pending.reject(Error("Layout worker unavailable"));
pendingWorker.clear();
worker?.terminate();
worker = null;
};
worker.postMessage({
init: true,
engineUrl: w.assetUrls.engine,
familyUrl: w.assetUrls.family,
});
});
return workerReady;
} catch {
return Promise.reject(Error("Layout worker unavailable"));
}
}
async function calculate(input) {
try {
await startWorker();
return await new Promise((resolve, reject) => {
const id = ++workerSequence;
pendingWorker.set(id, { resolve, reject });
worker.postMessage({ id, graph: input });
});
} catch {
return geometry.layout(input);
}
}
async function pinChoice() {
if (!pins.size) return "keep";
const dialog = $("rwPinDialog");
return new Promise((resolve) => {
const choose = (event) => {
const button = event.target.closest("[data-pin-choice]");
if (!button) return;
finish(button.dataset.pinChoice);
},
cancel = (event) => {
event.preventDefault();
finish("cancel");
};
function finish(value) {
dialog.removeEventListener("click", choose);
dialog.removeEventListener("cancel", cancel);
dialog.close();
resolve(value);
}
dialog.addEventListener("click", choose);
dialog.addEventListener("cancel", cancel);
dialog.showModal();
});
}
async function chooseCentre() {
const dialog = $("rwCentreDialog"),
select = $("rwCentreChoice");
select.replaceChildren(
...cast
.filter((c) => members.has(c.characterID))
.map((c) => new Option(c.characterName, c.characterID)),
);
dialog.showModal();
const chosen = await new Promise((resolve) => {
function closed() {
dialog.removeEventListener("close", closed);
resolve(dialog.returnValue === "arrange" ? +select.value : null);
}
dialog.addEventListener("close", closed);
});
if (chosen) {
a.setFocus(chosen);
await arrange("radial");
}
}
let familyRoutes = new Map(
Object.entries(saved?.familyRoutes || {}).map(([id, d]) => [+id, d]),
);
async function performArrange(kind = layout, options = {}) {
if (arranging) return;
if (!members.size) {
toast?.info(
"Add characters or choose a display preset before arranging.",
);
return;
}
if (kind === "radial" && !a.getFocus()) {
status.textContent =
"Select the central character in the diagram or character groups, then choose Focused radial.";
await chooseCentre();
return;
}
if (!LAYOUTS.some(([id]) => id === kind)) return;
if (kind === "family") {
await loadFamily();
const choice = await pinChoice();
if (choice === "cancel") return;
if (options.checkpoint !== false) checkpoint();
if (choice === "release") pins.clear();
} else if (options.checkpoint !== false) checkpoint();
layout = kind;
if ((await applyFocus(false)) === false) return;
syncControls();
const epoch = ++layoutEpoch,
arrangementStarted = performance.now();
arranging = true;
status.textContent = "Arranging displayed characters…";
app.querySelector("[data-map-reset]").disabled = true;
try {
if (kind === "family") {
visible().style({ width: 180, height: 66, padding: 0 });
} else visible().removeStyle("width height padding");
const nodes = dimensions(),
ids = new Set(nodes.map((n) => n.id)),
input = {
nodes,
edges: edges()
.filter((e) => ids.has(e.a) && ids.has(e.b))
.map(({ record, ...e }) => e),
layout: kind,
focus: a.getFocus(),
depth,
viewport: {
width: graph.clientWidth,
height: graph.clientHeight,
},
pins: Object.fromEntries(
[...pins]
.filter((id) => ids.has(id))
.map((id) => [id, { ...node(id).position() }]),
),
};
const result = await calculate(input);
if (epoch !== layoutEpoch) return;
modelSync = true;
cy.batch(() => {
for (const [id, p] of Object.entries(result.positions))
if (known(id)) {
node(+id).position(p);
positions.set(+id, p);
}
});
modelSync = false;
familyRoutes = new Map(
kind === "family" && !pins.size
? (result.routes || []).map((r) => [r.id, r.d])
: [],
);
cy.fit(visible(), 45);
if (cy.zoom() < 0.85) {
cy.zoom(0.85);
const community =
!a.getFocus() && kind === "clusters"
? result.communities?.find((group) =>
group.includes(result.preferredCenter),
)
: null;
const centred = community
? visible().filter((n) =>
community.includes(n.data("characterID")),
)
: node(result.preferredCenter);
if (centred.length) cy.center(centred);
if (kind === "family") {
const box = visible().boundingBox();
cy.pan({ x: cy.pan().x, y: 45 - box.y1 * cy.zoom() });
}
}
if (result.warnings?.length) toast?.info(result.warnings.join(" "));
w.lastLayout = {
kind,
result,
durationMs: performance.now() - arrangementStarted,
sequence: epoch,
nodes: nodes.length,
};
scheduleRoutes();
remember();
} catch (error) {
toast?.error(
"The layout could not be applied. Your diagram is retained. " +
error.message,
);
} finally {
arranging = false;
app.querySelector("[data-map-reset]").disabled = false;
syncControls();
status.textContent = `${members.size} displayed · ${LAYOUTS.find(([id]) => id === layout)?.[1]}.`;
}
}
function fit() {
cy.resize();
cy.fit(visible(), 45);
remember();
}
function reset() {
checkpoint();
cy.zoom(1);
cy.pan({ x: 0, y: 0 });
if (a.getFocus() && members.has(a.getFocus()))
cy.center(node(a.getFocus()));
remember();
}
let routingBusy = false,
reroute = false,
routeVersion = 0,
draggedId = null;
async function routeEdges() {
routeFrame = null;
if (arranging) {
reroute = false;
return;
}
if (routingBusy) {
reroute = true;
return;
}
routingBusy = true;
const version = routeVersion,
started = performance.now(),
ns = dimensions(),
byId = new Map(ns.map((n) => [n.id, n])),
groups = new Map(),
es = cy.edges(":visible"),
requests = [];
for (const e of es) {
const pair = geometry.key(
+e.source().data("characterID"),
+e.target().data("characterID"),
);
if (!groups.has(pair)) groups.set(pair, []);
groups.get(pair).push(e);
}
for (const group of groups.values()) {
group.sort(
(a, b) => a.data("relationshipID") - b.data("relationshipID"),
);
for (let i = 0; i < group.length; i++) {
const e = group[i],
id = e.data("relationshipID"),
aId = +e.source().data("characterID"),
bId = +e.target().data("characterID");
if (draggedId && aId !== draggedId && bId !== draggedId) continue;
requests.push({
id,
a: aId,
b: bId,
lane: (i - (group.length - 1) / 2) * 32,
path: familyRoutes.get(id),
labelIndex: i,
});
}
}
try {
let result;
const input = {
nodes: ns,
edges: requests,
style: effectiveConnector(),
};
try {
await startWorker();
result = await new Promise((resolve, reject) => {
const id = ++workerSequence;
pendingWorker.set(id, { resolve, reject });
worker.postMessage({ id, routes: input });
});
} catch {
result = { routes: [] };
for (let i = 0; i < requests.length; i++) {
const edge = requests[i];
result.routes.push({
id: edge.id,
...geometry.route(ns, edge, input.style, edge.lane, edge.path),
});
if (i % 12 === 11)
await new Promise((resolve) => requestAnimationFrame(resolve));
}
}
if (version !== routeVersion) {
reroute = true;
return;
}
const routedById = new Map(result.routes.map((r) => [r.id, r]));
cy.batch(() => {
for (const request of requests) {
const e = cy.$id("r-" + request.id),
routed = routedById.get(request.id),
aPos = byId.get(request.a),
bPos = byId.get(request.b);
if (!e.length || !routed || !aPos || !bPos) continue;
e.removeStyle(
"curve-style control-point-distances control-point-weights segment-distances segment-weights source-endpoint target-endpoint",
);
e.style({
"curve-style": routed.style,
"edge-distances": "node-position",
"text-rotation": "autorotate",
"text-events": "yes",
"text-margin-y": request.labelIndex % 2 ? -10 : 10,
"text-background-opacity": 0.94,
"line-opacity": 1,
"overlay-padding": 8,
});
if (routed.sourceEndpoint)
e.style(
"source-endpoint",
`${routed.sourceEndpoint.x}px ${routed.sourceEndpoint.y}px`,
);
if (routed.targetEndpoint)
e.style(
"target-endpoint",
`${routed.targetEndpoint.x}px ${routed.targetEndpoint.y}px`,
);
if (routed.points?.length) {
const dx = bPos.x - aPos.x,
dy = bPos.y - aPos.y,
len = Math.hypot(dx, dy) || 1;
e.style({
"segment-weights": routed.points
.map(
(p) =>
((p.x - aPos.x) * dx + (p.y - aPos.y) * dy) /
(len * len),
)
.join(" "),
"segment-distances": routed.points
.map(
(p) => ((p.y - aPos.y) * dx - (p.x - aPos.x) * dy) / len,
)
.join(" "),
});
} else if (routed.distance !== undefined)
e.style({
"control-point-distances": routed.distance,
"control-point-weights": 0.5,
});
}
});
updateLabels();
w.mainRoutingStats = {
edges: es.length,
routed: requests.length,
style: effectiveConnector(),
durationMs: performance.now() - started,
};
} finally {
routingBusy = false;
if (reroute) {
reroute = false;
scheduleRoutes();
}
}
}
function updateLabels() {
const es = cy.edges(":visible");
cy.batch(() => {
es.forEach((e) => {
const ids = [
+e.source().data("characterID"),
+e.target().data("characterID"),
],
show =
allLabels ||
e.hasClass("is-selected") ||
e.hasClass("is-main-hover") ||
(es.length < 60 && cy.zoom() >= 0.65) ||
(a.getFocus() && ids.includes(a.getFocus()));
const label = show ? e.data("label") : "";
if (e.style("label") !== label) e.style("label", label);
});
});
}
function scheduleRoutes() {
routeVersion++;
if (routingBusy) {
reroute = true;
return;
}
if (!routeFrame) routeFrame = requestAnimationFrame(routeEdges);
}
function selectRelationship(id) {
const r = records().find((r) => r.characterRelationshipID === +id);
if (!r) return;
selectionKind = "relationship";
w.selectRelationship(+id, r);
a.showRelationshipDetail();
scheduleRoutes();
}
function editRelationship(
id = w.selectedRelationship?.characterRelationshipID,
) {
const r = records().find((r) => r.characterRelationshipID === +id);
if (!r || !canEdit) return;
if (isFamily() && !r.initialStateEditable) {
flush();
location.assign(
`/Characters/Details/${r.characterAID}?tab=relationships&relationshipId=${r.characterRelationshipID}`,
);
return;
}
a.openEditor(r.characterAID, r.characterBID, isFamily() ? r : null);
}
function svg(value) {
const icon = document.createElementNS(
"http://www.w3.org/2000/svg",
"svg",
);
icon.setAttribute("viewBox", "0 0 24 24");
icon.setAttribute("aria-hidden", "true");
icon.classList.add("rw-importance-icon");
icon.dataset.tone = value.tone;
const path = document.createElementNS(icon.namespaceURI, "path");
path.setAttribute("d", value.path);
path.setAttribute("fill", value.filled ? "currentColor" : "none");
path.setAttribute("fill-rule", "evenodd");
icon.append(path);
return icon;
}
// Palette homes continue to be moved by the established narrow-screen drawer.
const bottom = app.querySelector(".rw-bottom"),
unknown = document.createElement("div");
unknown.className = "rw-unclassified";
unknown.tabIndex = 0;
unknown.dataset.rwTier = "";
unknown.setAttribute("role", "region");
unknown.setAttribute("aria-label", "Unclassified character group");
const unknownTitle = document.createElement("h3");
unknownTitle.dataset.rwTitle = "";
unknown.append(unknownTitle);
bottom.append(unknown);
const groups = [...app.querySelectorAll("[data-rw-tier]")];
function refreshPaletteTitles() {
for (const group of groups) {
const value = group.dataset.rwTier,
def = definitions.find((v) => v.value === value);
if (!def) continue;
let heading =
group === app.querySelector(".rw-left")
? app.querySelector(".rw-navigation h3")
: group.querySelector(":scope > h2,:scope > h3");
if (!heading) {
heading = document.createElement("h3");
group.prepend(heading);
}
const count = cast.filter(
(c) => tier(c.characterImportance) === value,
).length;
if (group.classList.contains("rw-left") && window.innerWidth <= 800) {
heading.replaceChildren(
document.createTextNode(`All characters (${cast.length})`),
);
continue;
}
heading.replaceChildren(
svg(def),
document.createTextNode(`${def.label} (${count})`),
);
group.setAttribute(
"aria-label",
`${def.label}: ${count} characters. Drop a character to assign ${def.label}.`,
);
}
}
function ensurePaletteEntry(c) {
if (app.querySelector(`[data-rw-entry="${c.characterID}"]`)) return;
const sample = app.querySelector("[data-rw-entry]");
const entry = sample
? sample.cloneNode(true)
: document.createElement("div");
if (!sample) {
entry.className = "rw-entry";
entry.dataset.pdContext = "character";
entry.innerHTML =
'<button type="button" draggable="true" class="rw-character" data-rw-character><span class="visual-avatar"></span><span></span></button><button type="button" class="rw-link" draggable="true" data-rw-link>↗</button><a class="rw-edit">Edit character</a>';
}
entry.dataset.rwEntry = c.characterID;
entry.hidden = false;
entry.classList.remove("is-focus");
const button = entry.querySelector("[data-rw-character]"),
link = entry.querySelector("[data-rw-link]"),
edit = entry.querySelector("a.rw-edit");
button.dataset.rwCharacter = c.characterID;
button.setAttribute("aria-label", "Focus " + c.characterName);
link.dataset.rwLink = c.characterID;
link.setAttribute(
"aria-label",
"Add relationship from " + c.characterName,
);
edit.href = "/Characters/Edit/" + c.characterID;
const avatar = entry.querySelector(".visual-avatar");
avatar.replaceChildren();
const path =
c.avatarThumbnailPath ||
c.avatarImagePath ||
c.thumbnailPath ||
c.imagePath;
if (path) {
const image = document.createElement("img");
image.src = path;
image.alt = "";
image.loading = "lazy";
avatar.append(image);
} else {
const initials = document.createElement("span");
initials.textContent = c.characterName?.slice(0, 1) || "?";
avatar.append(initials);
}
button.addEventListener("click", () =>
focusCharacter(c.characterID, true),
);
link.addEventListener("click", () =>
a.openEditor(c.characterID, a.getFocus()),
);
for (const handle of [button, link]) {
handle.addEventListener("dragstart", (event) =>
a.startDrag(event, c.characterID),
);
handle.addEventListener("dragend", a.endSourceDrag);
}
const group = groups.find(
(g) => g.dataset.rwTier === tier(c.characterImportance),
);
group?.append(entry);
w.paletteHomes?.set(entry, group);
}
function syncPalettes() {
for (const c of cast) if (known(c.characterID)) ensurePaletteEntry(c);
for (const entry of app.querySelectorAll("[data-rw-entry]")) {
const c = castById.get(+entry.dataset.rwEntry);
if (!c) {
w.paletteHomes?.delete(entry);
entry.remove();
continue;
}
const group = groups.find(
(g) => g.dataset.rwTier === tier(c.characterImportance),
);
if (group) {
w.paletteHomes?.set(entry, group);
if (window.innerWidth > 800) group.append(entry);
}
entry.querySelector("[data-rw-character]").dataset.importance =
c.characterImportance ?? "";
const label = entry.querySelector(
"[data-rw-character]>span:not(.visual-avatar):not([data-rw-importance-indicator])",
);
if (label) label.textContent = c.characterName;
entry
.querySelector("[data-rw-character]")
.setAttribute("aria-label", "Focus " + c.characterName);
let indicator = entry.querySelector("[data-rw-importance-indicator]");
if (!indicator) {
indicator = document.createElement("span");
indicator.dataset.rwImportanceIndicator = "";
entry.querySelector("[data-rw-character]").append(indicator);
}
const def = definition(c.characterImportance);
indicator.replaceChildren();
if (def) {
indicator.append(svg(def));
indicator.title = "Story importance: " + def.label;
indicator.setAttribute("aria-label", indicator.title);
}
}
refreshPaletteTitles();
a.filter();
}
async function directory() {
const response = await fetch(
"/CharacterAttributes/Directory?" +
new URLSearchParams({ projectId: w.projectId }),
{ cache: "no-store", signal: life.signal },
);
if (!response.ok || response.redirected)
throw Error("Character importance could not be refreshed.");
const data = await response.json();
canEdit = data.canEdit;
let importanceChanged = false;
for (const r of data.characters) {
readVersions.set(r.id, r.version);
const c = castById.get(r.id);
if (c) {
const value =
r.values.importance === "" ? null : Number(r.values.importance);
importanceChanged ||= c.characterImportance !== value;
c.characterImportance = value;
}
}
syncPalettes();
refreshIndicators();
syncControls();
return { ...data, importanceChanged };
}
function refreshIndicators() {
const tokens = getComputedStyle(document.documentElement);
cy.batch(() => {
cy.nodes().forEach((n) => {
const c = castById.get(n.data("characterID"));
if (!c) return;
n.data("label", c.characterName);
n.data("importance", c.characterImportance ?? 0);
n.toggleClass("is-major-character", c.characterImportance >= 8);
n.toggleClass(
"is-supporting-character",
c.characterImportance >= 4 && c.characterImportance < 8,
);
const def = definition(c.characterImportance);
if (def) {
const color = tokens
.getPropertyValue(
def.tone === "warning"
? "--pd-warning"
: def.tone === "info"
? "--pd-info"
: "--pd-muted",
)
.trim(),
markup = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="${def.path}" fill="${def.filled ? color : "none"}" fill-rule="evenodd" stroke="${color}" stroke-width="1.8"/></svg>`;
n.data(
"importanceIcon",
"data:image/svg+xml;charset=utf-8," +
encodeURIComponent(markup),
);
const portrait = n.data("portrait"),
pinDefinition = w.pinDefinition,
pinSvg =
pinDefinition && pins.has(c.characterID)
? "data:image/svg+xml;charset=utf-8," +
encodeURIComponent(
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="${pinDefinition.path}" fill="none" stroke="${tokens.getPropertyValue("--pd-focus").trim()}" stroke-width="1.8"/></svg>`,
)
: null;
if (portrait) {
const images = [
portrait,
n.data("importanceIcon"),
...(pinSvg ? [pinSvg] : []),
];
n.style({
"background-image": images,
"background-width": images.map((_, i) => (i ? 14 : 34)),
"background-height": images.map((_, i) => (i ? 14 : 34)),
"background-position-x": images.map((_, i) =>
i ? "100%" : "8px",
),
"background-position-y": images.map((_, i) =>
i === 0 ? "50%" : i === 1 ? "0%" : "100%",
),
"background-fit": images.map(() => "none"),
});
}
}
n.style(
"border-style",
pins.has(c.characterID) ? "double" : "solid",
);
n.style(
"border-width",
pins.has(c.characterID) || n.hasClass("is-focus")
? 4
: c.characterImportance >= 8
? 3
: c.characterImportance >= 4
? 2.5
: 2,
);
n.style(
"border-color",
pins.has(c.characterID) ||
n.hasClass("is-focus") ||
c.characterImportance >= 8
? tokens.getPropertyValue("--pd-focus").trim()
: tokens.getPropertyValue("--pd-border").trim(),
);
});
});
}
function updateAssigned(result) {
for (const r of result.characters || []) {
readVersions.set(r.id, r.version);
const c = castById.get(r.id);
if (c) {
const value =
r.values.importance === "" ? null : Number(r.values.importance);
c.characterImportance = value;
}
}
syncPalettes();
refreshIndicators();
void applyFocus(false);
if (a.getFocus()) a.renderCharacterDetail();
}
async function undoImportance(token) {
if (assignBusy) return;
assignBusy = true;
try {
const response = await fetch("/CharacterAttributes/Undo", {
method: "POST",
headers: {
"Content-Type": "application/json",
RequestVerificationToken: app.querySelector(
'[name="__RequestVerificationToken"]',
).value,
},
body: JSON.stringify({ token }),
});
const result = await response.json();
if (!response.ok || !result.saved)
throw Error(
result.message ||
"Importance could not be restored; a newer change may exist.",
);
updateAssigned(result);
toast?.success("Character importance restored.");
} catch (error) {
toast?.error(error.message);
} finally {
assignBusy = false;
if (pendingHint) {
pendingHint = false;
void liveRefresh();
}
}
}
async function assignImportance(id, value) {
if (!known(id) || assignBusy) return;
const c = castById.get(id);
if (tier(c.characterImportance) === value) {
toast?.info("That importance is already recorded.");
return;
}
if (!canEdit) {
toast?.info("This project is read-only.");
return;
}
assignBusy = true;
try {
if (!readVersions.has(id)) await directory();
const response = await fetch("/CharacterAttributes/Assign", {
method: "POST",
headers: {
"Content-Type": "application/json",
RequestVerificationToken: app.querySelector(
'[name="__RequestVerificationToken"]',
).value,
},
body: JSON.stringify({
projectId: w.projectId,
attribute: "importance",
changes: [{ id, value, version: readVersions.get(id) }],
}),
});
let result;
try {
result = await response.json();
} catch {
throw Error("Character importance was not saved.");
}
if (!response.ok || !result.saved)
throw Error(
result.message || "Character importance was not saved.",
);
updateAssigned(result);
if (!result.characters.length) {
toast?.info("That importance is already recorded.");
return;
}
undoAttribute = result.undoToken;
const token = undoAttribute;
toast?.success(
`${c.characterName} classified as ${definitions.find((v) => v.value === value)?.label || "Unclassified"}.`,
{
duration: 10000,
action: {
label: "Undo importance",
run: () => undoImportance(token),
},
},
);
} catch (error) {
toast?.error(error.message);
try {
await directory();
} catch {}
} finally {
assignBusy = false;
if (pendingHint) {
pendingHint = false;
void liveRefresh();
}
}
}
for (const group of groups) {
listen(group, "dragover", (event) => {
if (
!canEdit ||
!event.dataTransfer.types.includes(
"application/x-plotdirector-character",
)
)
return;
event.preventDefault();
event.stopPropagation();
app
.querySelectorAll(".rw-importance-drop")
.forEach((n) => n.classList.remove("rw-importance-drop"));
group.classList.add("rw-importance-drop");
event.dataTransfer.dropEffect = "move";
});
listen(group, "dragleave", (event) => {
if (!group.contains(event.relatedTarget))
group.classList.remove("rw-importance-drop");
});
listen(group, "drop", (event) => {
const id = +event.dataTransfer.getData(
"application/x-plotdirector-character",
);
if (!id) return;
event.preventDefault();
event.stopPropagation();
group.classList.remove("rw-importance-drop");
void assignImportance(id, group.dataset.rwTier);
});
}
listen(document, "dragend", () =>
app
.querySelectorAll(".rw-importance-drop")
.forEach((n) => n.classList.remove("rw-importance-drop")),
);
function menuCommands(hit) {
if (hit.kind === "node") {
const id = hit.id,
c = castById.get(id);
return [
{
label: c?.characterName || "Character",
disabled: true,
icon: "characters",
},
{
label: "View character",
icon: "details",
run: () => {
flush();
location.assign("/Characters/Details/" + id);
},
},
{
label: "Edit character",
icon: "writer",
disabled: !canEdit,
run: () => {
flush();
location.assign("/Characters/Edit/" + id);
},
},
{ separator: true },
{
label: "Focus on character",
icon: "focus",
run: () => focusCharacter(id, true),
},
{
label: "Show connected characters",
icon: "relationships",
run: () => {
a.setFocus(id);
void setPreset("selected");
},
},
{
label: "Show family branch",
icon: "characters",
run: async () => {
checkpoint();
if (preset === "custom") rememberCustom();
a.setFocus(id);
preset = "family";
familyRoot = id;
await applyFocus(false);
await arrange("family", { checkpoint: false });
},
},
{
label: "Add relationship",
icon: "add",
disabled: !canEdit,
run: () => a.openEditor(id, null),
},
{
label: pins.has(id) ? "Unpin position" : "Pin position",
icon: pins.has(id) ? "attribute-unpin" : "attribute-pin",
run: () => pin(id),
},
{
label: "Story importance",
icon: "attribute-star-filled",
children: definitions.map((d) => ({
label: d.label,
icon: d.icon,
tone: d.tone,
checked: tier(c?.characterImportance) === d.value,
disabled: !canEdit || assignBusy,
run: () => assignImportance(id, d.value),
})),
},
{ separator: true },
{
label: "Remove from diagram",
icon: "hide-node",
run: () => remove(id),
},
];
}
if (hit.kind === "edge")
return [
{
label:
records().find((r) => r.characterRelationshipID === hit.id)
?.relationshipTypeName || "Relationship",
icon: "relationships",
disabled: true,
},
{
label: "View relationship details",
icon: "details",
run: () => selectRelationship(hit.id),
},
{
label: "Edit relationship",
icon: "writer",
disabled: !canEdit,
run: () => editRelationship(hit.id),
},
];
return [
{ label: "Diagram", disabled: true, icon: "relationships" },
{ label: "Fit diagram", icon: "maximise", run: fit },
{ label: "Reset view", icon: "restore", run: reset },
{
label: "Auto-arrange",
icon: "auto-arrange",
disabled: arranging,
run: () => arrange(),
},
{
label: "Layout",
icon: "layout",
children: LAYOUTS.map(([id, label, icon]) => ({
label,
icon,
checked: layout === id,
disabled: arranging,
run: () => arrange(id),
})),
},
{ separator: true },
{ label: "Clear diagram", icon: "hide-node", run: clear },
{
label: "Undo layout change",
icon: "undo",
disabled: !undoStack.length,
run: undoLayout,
},
];
}
function openMenu(hit, x, y, keyboard = false, target = graph) {
menuHit = hit;
window.PlotDirectorContextMenus?.openAt(target, x, y, false);
}
const registerMenu =
window.PlotDirectorContextMenus?.register ||
((selector, provider) =>
(window.PlotDirectorContextProviders ||= []).push({
selector,
provider,
}));
registerMenu("#rwApp #relationshipMapGraph", () => ({
commands: menuCommands(menuHit || { kind: "canvas" }),
invoker: graph,
}));
registerMenu("#rwApp [data-rw-entry]", (target) => ({
commands: menuCommands({
kind: "node",
id: +target.closest("[data-rw-entry]").dataset.rwEntry,
}),
invoker: target.closest("[data-rw-entry]").querySelector("button"),
}));
function renderedGeometry(edge, method) {
try {
return edge[method]?.();
} catch {
return null;
}
}
function hitAt(event) {
const b = graph.getBoundingClientRect(),
p = { x: event.clientX - b.left, y: event.clientY - b.top };
const n = visible()
.filter((n) => {
const b = n.renderedBoundingBox();
return p.x >= b.x1 && p.x <= b.x2 && p.y >= b.y1 && p.y <= b.y2;
})
.last();
if (n.length) return { kind: "node", id: n.data("characterID") };
let best = null,
distance = 12;
for (const e of cy.edges(":visible")) {
const curve = e.style("curve-style");
let points =
curve === "segments"
? renderedGeometry(e, "renderedSegmentPoints")
: null;
if (!points?.length) {
const controls = curve.includes("bezier")
? renderedGeometry(e, "renderedControlPoints")
: null,
a = e.renderedSourceEndpoint?.() || e.source().renderedPosition(),
b = e.renderedTargetEndpoint?.() || e.target().renderedPosition();
if (controls?.length) {
points = [];
for (let i = 0; i <= 24; i++) {
const t = i / 24,
c = controls[0];
points.push({
x: (1 - t) ** 2 * a.x + 2 * (1 - t) * t * c.x + t * t * b.x,
y: (1 - t) ** 2 * a.y + 2 * (1 - t) * t * c.y + t * t * b.y,
});
}
} else points = [a, b];
} else
points = [
e.source().renderedPosition(),
...points,
e.target().renderedPosition(),
];
for (let i = 1; i < points.length; i++) {
const a = points[i - 1],
b = points[i],
dx = b.x - a.x,
dy = b.y - a.y,
t = Math.max(
0,
Math.min(
1,
((p.x - a.x) * dx + (p.y - a.y) * dy) /
(dx * dx + dy * dy || 1),
),
),
d = Math.hypot(p.x - a.x - t * dx, p.y - a.y - t * dy);
if (d < distance) {
distance = d;
best = { kind: "edge", id: e.data("relationshipID") };
}
}
}
return best || { kind: "canvas" };
}
let selectionKind = a.getFocus() ? "character" : "canvas",
lastTap = null,
middle = null;
cy.on("tap", "node", (event) => {
selectionKind = "character";
graph.focus({ preventScroll: true });
const id = event.target.data("characterID"),
now = performance.now();
if (lastTap?.id === id && now - lastTap.time < 350) {
flush();
location.assign("/Characters/Details/" + id);
}
lastTap = { id, time: now };
});
cy.on("tap", "edge", (event) => {
selectionKind = "relationship";
selectRelationship(event.target.data("relationshipID"));
});
cy.on("tap", (event) => {
if (event.target !== cy) return;
const original = event.originalEvent;
if (original) {
const hit = hitAt(original);
if (hit.kind === "edge") {
selectRelationship(hit.id);
return;
}
}
selectionKind = "canvas";
});
cy.on("mouseover", "edge", (event) => {
event.target.addClass("is-main-hover");
updateLabels();
});
cy.on("mouseout", "edge", (event) => {
event.target.removeClass("is-main-hover");
updateLabels();
});
cy.on("grab", "node", (event) => {
layoutEpoch++;
draggedId = event.target.data("characterID");
dragSnapshot = snapshot();
});
cy.on("free", "node", () => {
draggedId = null;
if (dragSnapshot) {
undoStack.push(dragSnapshot);
if (undoStack.length > 24) undoStack.shift();
dragSnapshot = null;
familyRoutes.clear();
$("rwUndoLayout").disabled = false;
}
cy.nodes().forEach((n) => {
if (known(n.data("characterID")))
positions.set(n.data("characterID"), { ...n.position() });
});
scheduleRoutes();
remember();
});
cy.on("position", "node", (event) => {
if (modelSync) return;
positions.set(event.target.data("characterID"), {
...event.target.position(),
});
scheduleRoutes();
remember();
});
cy.on("zoom", () => {
updateLabels();
remember();
});
listen(
graph,
"wheel",
(event) => {
event.preventDefault();
event.stopPropagation();
const b = graph.getBoundingClientRect(),
delta =
event.deltaY *
(event.deltaMode === 1
? 16
: event.deltaMode === 2
? graph.clientHeight
: 1);
cy.zoom({
level: Math.max(
cy.minZoom(),
Math.min(
cy.maxZoom(),
cy.zoom() *
Math.exp(-Math.max(-120, Math.min(120, delta)) * 0.002),
),
),
renderedPosition: {
x: event.clientX - b.left,
y: event.clientY - b.top,
},
});
},
{ passive: false },
);
listen(
graph,
"pointerdown",
(event) => {
if (event.button !== 1) return;
event.preventDefault();
event.stopImmediatePropagation();
middle = {
pointer: event.pointerId,
x: event.clientX,
y: event.clientY,
pan: { ...cy.pan() },
panning: cy.userPanningEnabled(),
};
cy.userPanningEnabled(false);
graph.setPointerCapture(event.pointerId);
graph.classList.add("rw-middle-pan");
},
{ capture: true },
);
listen(
graph,
"pointermove",
(event) => {
if (!middle || event.pointerId !== middle.pointer) return;
event.preventDefault();
event.stopImmediatePropagation();
cy.pan({
x: middle.pan.x + event.clientX - middle.x,
y: middle.pan.y + event.clientY - middle.y,
});
},
{ capture: true },
);
function endMiddle() {
if (!middle) return;
cy.userPanningEnabled(middle.panning);
middle = null;
graph.classList.remove("rw-middle-pan");
remember();
}
for (const e of ["pointerup", "pointercancel", "lostpointercapture"])
listen(graph, e, endMiddle, { capture: true });
listen(graph, "auxclick", (event) => {
if (event.button === 1) event.preventDefault();
});
listen(
graph,
"contextmenu",
(event) => {
if (event.ctrlKey || getSelection()?.toString()) return;
event.preventDefault();
event.stopPropagation();
const hit = hitAt(event);
if (hit.kind === "node") {
a.setFocus(hit.id);
selectionKind = "character";
void applyFocus(false);
} else if (hit.kind === "edge") selectRelationship(hit.id);
openMenu(hit, event.clientX, event.clientY);
},
{ capture: true },
);
listen(graph, "keydown", (event) => {
if (event.target.closest("input,textarea,select,[contenteditable]"))
return;
if (event.key === "Delete" && selectionKind === "character") {
event.preventDefault();
remove();
} else if (
event.key === "ContextMenu" ||
(event.shiftKey && event.key === "F10")
) {
event.preventDefault();
event.stopPropagation();
const b = graph.getBoundingClientRect(),
hit =
selectionKind === "character" && a.getFocus()
? { kind: "node", id: a.getFocus() }
: selectionKind === "relationship" && w.selectedRelationship
? {
kind: "edge",
id: w.selectedRelationship.characterRelationshipID,
}
: { kind: "canvas" };
openMenu(hit, b.left + 40, b.top + 40, true);
} else if (
(event.ctrlKey || event.metaKey) &&
event.key.toLowerCase() === "z"
) {
event.preventDefault();
undoLayout();
} else if (
["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(
event.key,
)
) {
event.preventDefault();
const p = cy.pan(),
step = event.shiftKey ? 80 : 30;
cy.pan({
x:
p.x +
(event.key === "ArrowLeft"
? step
: event.key === "ArrowRight"
? -step
: 0),
y:
p.y +
(event.key === "ArrowUp"
? step
: event.key === "ArrowDown"
? -step
: 0),
});
} else if (event.key === "Home") {
event.preventDefault();
fit();
}
});
listen($("rwCharacterMenu"), "click", (event) => {
if (!a.getFocus()) return;
const b = event.currentTarget.getBoundingClientRect();
openMenu({ kind: "node", id: a.getFocus() }, b.left, b.bottom, true);
});
listen($("rwCanvasMenu"), "click", () => {
const b = graph.getBoundingClientRect();
openMenu({ kind: "canvas" }, b.left + 50, b.top + 40, true);
});
listen($("rwEmptyFull"), "click", () => void setPreset("full"));
listen($("rwClearDiagram"), "click", clear);
listen($("rwUndoLayout"), "click", undoLayout);
listen($("rwClearPins"), "click", () => {
if (!pins.size) return;
checkpoint();
pins.clear();
void applyFocus(false);
remember();
});
listen(
presetControl,
"change",
() => void setPreset(presetControl.value),
);
listen(layoutControl, "change", () => void arrange(layoutControl.value));
listen(connectorControl, "change", () => {
checkpoint();
connector = connectorControl.value;
syncControls();
scheduleRoutes();
remember();
});
listen(depthControl, "change", () => {
depth = +depthControl.value;
if (preset === "selected" || (preset === "family" && familyRoot))
void applyFocus(false);
remember();
});
listen($("rwAllLabels"), "change", () => {
allLabels = $("rwAllLabels").checked;
scheduleRoutes();
remember();
});
for (const id of ["rwLayoutOptions", "rwDiagramDisplay"])
listen($(id), "submit", (event) => event.preventDefault());
for (const id of ["rwMapView", "rwListView"])
listen($(id), "click", remember);
function drop(event, id, target) {
if (!id) return;
event.preventDefault();
const rect = graph.getBoundingClientRect();
if (target.length && target.data("characterID") !== id) {
if (!canEdit) return;
focusCharacter(target.data("characterID"), false);
a.openEditor(id, target.data("characterID"));
} else
add(id, {
x: (event.clientX - rect.left - cy.pan().x) / cy.zoom(),
y: (event.clientY - rect.top - cy.pan().y) / cy.zoom(),
});
}
function refreshDetail() {
if (selectionKind === "relationship" && w.selectedRelationship) {
const current = records().find(
(r) =>
r.characterRelationshipID ===
w.selectedRelationship.characterRelationshipID,
);
if (current) {
w.selectRelationship(current.characterRelationshipID, current);
a.showRelationshipDetail();
return;
}
}
if (a.getFocus()) a.renderCharacterDetail();
else a.clearDetail();
}
function modelUpdated(model) {
referenceRecords = null;
if (model.cast) {
for (const c of model.cast) {
const existing = castById.get(c.characterID);
if (existing) Object.assign(existing, c);
else {
cast.push(c);
castById.set(c.characterID, c);
}
}
const ids = new Set(model.cast.map((c) => c.characterID));
for (const id of [...castById.keys()])
if (!ids.has(id)) {
castById.delete(id);
members.delete(id);
pins.delete(id);
positions.delete(id);
node(id).remove();
if (a.getFocus() === id) a.setFocus(null);
}
for (let i = cast.length - 1; i >= 0; i--)
if (!ids.has(cast[i].characterID)) cast.splice(i, 1);
}
for (const select of [
$("focusCharacterId"),
document.querySelector('[name="SourceID"]'),
document.querySelector('[name="TargetID"]'),
]) {
if (!select) continue;
const selected = select.value,
placeholder =
select.options[0]?.value === "" ? select.options[0].text : null;
select.replaceChildren(
...(placeholder ? [new Option(placeholder, "")] : []),
...cast.map((c) => new Option(c.characterName, c.characterID)),
);
select.value = selected;
}
syncPalettes();
a.decorateNodes();
refreshIndicators();
void applyFocus(false).then(refreshDetail);
}
async function relationshipSaved() {
familyEpoch++;
family = null;
await a.refresh();
await applyFocus(false);
refreshDetail();
toast?.success("Relationship saved.");
}
async function liveRefresh() {
if (assignBusy) {
pendingHint = true;
return;
}
try {
familyEpoch++;
family = null;
await Promise.all([directory(), a.refresh()]);
if (isFamily()) await loadFamily();
await applyFocus(false);
} catch (error) {
if (error.name !== "AbortError")
toast?.error(
"Relationship data could not be refreshed. Your diagram is retained.",
);
}
}
function wire(c) {
if (connection || !c) return;
connection = c;
c.on("ContextInvalidated", (hint) => {
if (
(!hint.projectId || +hint.projectId === +w.projectId) &&
(!hint.kind || ["characters", "relationships"].includes(hint.kind))
) {
if (assignBusy) pendingHint = true;
else {
clearTimeout(refreshTimer);
refreshTimer = setTimeout(() => void liveRefresh(), 180);
}
}
});
c.onreconnected(() => void liveRefresh());
}
listen(document, "pd-presence-connection", (event) => wire(event.detail));
listen(document, "pd-presence-ready", () =>
wire(window.PlotDirectorPresenceConnection),
);
wire(window.PlotDirectorPresenceConnection);
function flush() {
clearTimeout(saveTimer);
if (viewUnavailable || familyPromise) return;
try {
localStorage.setItem(storageKey, JSON.stringify(snapshot()));
} catch {}
}
listen(window, "pagehide", flush);
async function initialise() {
if (saved?.focus && known(saved.focus)) a.setFocus(saved.focus);
else if (!a.getFocus() && legacy?.focus && known(legacy.focus))
a.setFocus(legacy.focus);
if (saved?.collapsed || legacy?.collapsed) {
board.classList.add("palettes-hidden");
$("rwPalettes").setAttribute("aria-expanded", "false");
}
syncControls();
syncPalettes();
if ((await applyFocus(false)) === false) {
initialised = true;
return;
}
if (saved) {
if (Number.isFinite(saved.zoom)) cy.zoom(saved.zoom);
if (Number.isFinite(saved.pan?.x) && Number.isFinite(saved.pan?.y))
cy.pan(saved.pan);
a.setView(saved.view || "map");
} else if (legacy) {
if (Number.isFinite(legacy.zoom)) cy.zoom(legacy.zoom);
if (Number.isFinite(legacy.pan?.x) && Number.isFinite(legacy.pan?.y))
cy.pan(legacy.pan);
} else if (members.size) await arrange(layout, { checkpoint: false });
try {
const current = await directory();
if (current.importanceChanged) await applyFocus(false);
} catch {
status.textContent +=
" Importance assignment is temporarily unavailable.";
}
syncControls();
remember();
initialised = true;
}
const api = {
records,
renderList,
setPreset,
applyFocus,
focusCharacter,
clearFocus,
remove,
clear,
pin,
reset,
drop,
remember,
arrange,
fit,
modelUpdated,
initialise,
undoLayout,
assignImportance,
editRelationship,
relationshipSaved,
refreshDetail,
refreshPaletteTitles,
restyle() {
refreshIndicators();
updateLabels();
scheduleRoutes();
},
get familyMode() {
return isFamily();
},
get preset() {
return preset;
},
get members() {
return [...members];
},
get pins() {
return [...pins];
},
get undoCount() {
return undoStack.length;
},
get arranging() {
return arranging;
},
get routing() {
return routingBusy || !!routeFrame || reroute;
},
get storageKey() {
return storageKey;
},
dispose() {
flush();
life.abort();
worker?.terminate();
cancelAnimationFrame(routeFrame);
},
};
Object.defineProperty(api, "initialised", { get: () => initialised });
Object.defineProperty(api, "busy", {
get: () => !!pendingCommands || arranging || !!familyPromise,
});
w.mainCommands = api;
return api;
},
};
})();