503 lines
35 KiB
JavaScript
503 lines
35 KiB
JavaScript
(() => {
|
|
const app = document.getElementById('rwApp');
|
|
if (!app) return;
|
|
document.body.classList.add('rw-page');
|
|
let resizeGraph = () => {};
|
|
const sizeWorkspace = () => {
|
|
app.style.setProperty('--rw-ribbon-bottom', `${(document.querySelector('.pd-application-header')?.getBoundingClientRect().bottom || 0) + 4}px`);
|
|
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) { setView('list'); return; }
|
|
const { cy, cast, scenes, projectId } = workspace;
|
|
const graph = document.getElementById('relationshipMapGraph');
|
|
const board = document.getElementById('rwBoard');
|
|
const dialog = document.getElementById('rwDialog');
|
|
const form = document.getElementById('rwForm');
|
|
const timeline = document.getElementById('rwTimeline');
|
|
const point = document.getElementById('rwPoint');
|
|
const status = document.getElementById('rwStatus');
|
|
const editStatus = document.getElementById('rwEditStatus');
|
|
const field = name => form.elements.namedItem(name);
|
|
const castById = new Map(cast.map(c => [c.characterID, c]));
|
|
const storageKey = `pd.relationship-workspace.v1.${projectId}.${workspace.bookId || 'project'}`;
|
|
let focus = workspace.focusCharacterId, source = null, saveTimer, request = null, loading = false, stateLoaded = true;
|
|
let currentScene = workspace.sceneId;
|
|
let editorRelationships = workspace.relationships(), editorRequest = null, activeRelationship = null;
|
|
let editorReady = true;
|
|
let restored = null;
|
|
try { restored = JSON.parse(localStorage.getItem(storageKey)); } catch { /* Storage can be unavailable. */ }
|
|
const extraNodes = new Set(restored?.extraNodes || []);
|
|
const removed = new Set(restored?.removed || []);
|
|
const remember = () => {
|
|
clearTimeout(saveTimer);
|
|
saveTimer = setTimeout(() => {
|
|
const positions = {};
|
|
cy.nodes().forEach(n => { positions[n.id()] = n.position(); });
|
|
try { localStorage.setItem(storageKey, JSON.stringify({ positions, zoom: cy.zoom(), pan: cy.pan(), focus,
|
|
extraNodes: [...extraNodes], removed: [...removed], collapsed: board.classList.contains('palettes-hidden') })); } catch { /* Layout persistence is optional. */ }
|
|
}, 250);
|
|
};
|
|
function ensureNode(id, position) {
|
|
const character = castById.get(Number(id));
|
|
if (!character) return cy.collection();
|
|
let node = cy.$id(`c-${id}`);
|
|
if (!node.length) {
|
|
node = cy.add({ data: { id: `c-${id}`, characterID: Number(id), label: character.characterName,
|
|
width: character.characterImportance >= 8 ? 158 : 144, height: 46 },
|
|
classes: character.characterImportance >= 8 ? 'is-major-character' : character.characterImportance >= 4 ? 'is-supporting-character' : '',
|
|
position: position || { x: (graph.clientWidth / 2 - cy.pan().x) / cy.zoom(), y: (graph.clientHeight / 2 - cy.pan().y) / cy.zoom() } });
|
|
} else if (position) node.position(position);
|
|
removed.delete(Number(id));
|
|
return node;
|
|
}
|
|
function applyFocus(centre = false) {
|
|
cy.elements().removeClass('is-focus is-dimmed');
|
|
cy.elements().show();
|
|
if (focus) {
|
|
const node = ensureNode(focus);
|
|
node.addClass('is-focus');
|
|
const neighbours = node.closedNeighborhood();
|
|
const full = document.querySelector('[name="showFullNetwork"]').checked;
|
|
if (full) cy.elements().difference(neighbours).addClass('is-dimmed');
|
|
else cy.elements().difference(neighbours).hide();
|
|
if (centre) cy.center(node);
|
|
status.textContent = `Focused: ${castById.get(focus)?.characterName || ''}. Drag a character here or choose Add relationship.`;
|
|
}
|
|
for (const id of removed) cy.$id(`c-${id}`).closedNeighborhood().filter('edge').hide();
|
|
for (const id of removed) cy.$id(`c-${id}`).hide();
|
|
document.querySelectorAll('[data-rw-entry]').forEach(e => e.classList.toggle('is-focus', Number(e.dataset.rwEntry) === focus));
|
|
document.getElementById('focusCharacterId').value = focus || '';
|
|
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);
|
|
const entry = document.querySelector(`[data-rw-entry="${focus}"]`);
|
|
const palette = entry?.closest('.rw-strip');
|
|
if (palette?.clientWidth && palette.clientHeight) {
|
|
const item = entry.getBoundingClientRect(), view = palette.getBoundingClientRect();
|
|
if (item.left < view.left) palette.scrollLeft -= view.left - item.left;
|
|
else if (item.right > view.right) palette.scrollLeft += item.right - view.right;
|
|
if (item.top < view.top) palette.scrollTop -= view.top - item.top;
|
|
else if (item.bottom > view.bottom) palette.scrollTop += item.bottom - view.bottom;
|
|
}
|
|
if (window.innerWidth > 800) showDetail();
|
|
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() {
|
|
const query = normalise(document.getElementById('rwSearch').value).split(' ').filter(Boolean);
|
|
document.querySelectorAll('[data-rw-character]').forEach(button => {
|
|
button.closest('[data-rw-entry]').hidden = !query.every(word => normalise(button.textContent).includes(word));
|
|
});
|
|
}
|
|
document.getElementById('rwSearch').addEventListener('input', filter);
|
|
document.querySelectorAll('[data-rw-character]').forEach(button => button.addEventListener('click', () => focusCharacter(button.dataset.rwCharacter)));
|
|
function openEditor(from, to) {
|
|
if (loading || !stateLoaded) { status.textContent = 'Wait for the timeline to finish loading.'; return; }
|
|
editorRequest?.abort(); editorRequest = null; editorReady = true;
|
|
form.querySelector('[type="submit"]').disabled = false;
|
|
form.reset();
|
|
field('SourceID').value = from || cast[0]?.characterID || '';
|
|
field('TargetID').value = to || focus || cast[1]?.characterID || '';
|
|
field('SceneID').value = currentScene || '';
|
|
editStatus.textContent = '';
|
|
editorRelationships = workspace.relationships();
|
|
const pair = editorRelationships.filter(r => (r.characterAID === Number(field('SourceID').value) && r.characterBID === Number(field('TargetID').value)) || (r.isReciprocal && r.characterBID === Number(field('SourceID').value) && r.characterAID === Number(field('TargetID').value)));
|
|
if (pair.length === 1) {
|
|
const type = [...field('TypeID').options].find(o => o.textContent === pair[0].relationshipTypeName);
|
|
if (type) field('TypeID').value = type.value;
|
|
}
|
|
populateExisting();
|
|
form.querySelector('.rw-pair-edit').open = !from || !to;
|
|
renderDialogPair();
|
|
dialog.showModal();
|
|
}
|
|
function populateExisting() {
|
|
const a = Number(field('SourceID').value), b = Number(field('TargetID').value), type = field('TypeID');
|
|
const pair = editorRelationships.filter(r => (r.characterAID === a && r.characterBID === b) || (r.isReciprocal && r.characterAID === b && r.characterBID === a));
|
|
const relationship = pair.find(r => r.relationshipTypeName === type.selectedOptions[0]?.textContent);
|
|
const state = relationship?.currentStateName;
|
|
field('Mutual').checked = false; field('Known').checked = false; field('Intensity').value = ''; field('Notes').value = '';
|
|
field('StateID').selectedIndex = 0;
|
|
if (relationship) {
|
|
field('Mutual').checked = relationship.isReciprocal;
|
|
field('Known').checked = relationship.known;
|
|
field('Intensity').value = relationship.currentIntensity || '';
|
|
field('Notes').value = relationship.notes || '';
|
|
const option = [...field('StateID').options].find(o => o.textContent === state);
|
|
if (option) field('StateID').value = option.value;
|
|
}
|
|
field('Mutual').disabled = !!field('SceneID').value && !!relationship;
|
|
editStatus.textContent = relationship ? 'Updates this relationship; an existing event at the selected scene will be edited.' : 'Creates a relationship of this type, or updates a matching record if one exists outside the current view.';
|
|
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));
|
|
field('SceneID').addEventListener('change', async () => {
|
|
editorRequest?.abort(); const active = editorRequest = new AbortController();
|
|
const submit = form.querySelector('[type="submit"]'); submit.disabled = true; editorReady = false;
|
|
try {
|
|
const params = new URLSearchParams({ projectId });
|
|
if (field('SceneID').value) params.set('sceneId', field('SceneID').value);
|
|
const response = await fetch(`/RelationshipMap/State?${params}`, { signal: active.signal });
|
|
if (!response.ok) throw new Error('Could not load the selected scene.');
|
|
editorRelationships = (await response.json()).relationships; editorReady = true; populateExisting();
|
|
} catch (error) { if (error.name !== 'AbortError') editStatus.textContent = error.message; }
|
|
finally { if (active === editorRequest) submit.disabled = !editorReady; }
|
|
});
|
|
document.getElementById('rwEditLine').addEventListener('click', () => {
|
|
activeRelationship = workspace.selectedRelationship || activeRelationship;
|
|
if (!activeRelationship) return;
|
|
openEditor(activeRelationship.characterAID, activeRelationship.characterBID);
|
|
const type = [...field('TypeID').options].find(o => o.textContent === activeRelationship.relationshipTypeName);
|
|
if (type) field('TypeID').value = type.value;
|
|
populateExisting();
|
|
});
|
|
cy.on('tap cxttap', 'edge', event => {
|
|
activeRelationship = workspace.relationships().find(r => r.characterRelationshipID === event.target.data('relationshipID'));
|
|
workspace.selectRelationship(event.target.data('relationshipID'));
|
|
showRelationshipDetail();
|
|
});
|
|
document.querySelectorAll('[data-map-select]').forEach(button => button.addEventListener('click', () => {
|
|
activeRelationship = workspace.relationships().find(r => r.characterRelationshipID === Number(button.dataset.mapSelect));
|
|
}));
|
|
document.getElementById('rwConnect').addEventListener('click', () => openEditor(null, focus));
|
|
document.getElementById('rwCancel').addEventListener('click', () => dialog.close());
|
|
document.querySelectorAll('[data-rw-link]').forEach(button => button.addEventListener('click', () => openEditor(Number(button.dataset.rwLink), focus)));
|
|
function startDrag(event, id) {
|
|
source = Number(id);
|
|
event.dataTransfer.setData('application/x-plotdirector-character', String(id));
|
|
event.dataTransfer.effectAllowed = 'copy';
|
|
}
|
|
document.querySelectorAll('[data-rw-character], [data-rw-link]').forEach(button => {
|
|
button.addEventListener('dragstart', event => startDrag(event, button.dataset.rwCharacter || button.dataset.rwLink));
|
|
button.addEventListener('dragend', () => { source = null; cy.nodes().removeClass('is-drop-target'); });
|
|
});
|
|
function hit(event) {
|
|
const rect = graph.getBoundingClientRect();
|
|
const x = event.clientX - rect.left, y = event.clientY - rect.top;
|
|
return cy.nodes(':visible').filter(node => { const box = node.renderedBoundingBox(); return x >= box.x1 && x <= box.x2 && y >= box.y1 && y <= box.y2; }).last();
|
|
}
|
|
graph.addEventListener('dragover', event => {
|
|
if (!source) return;
|
|
event.preventDefault();
|
|
cy.nodes().removeClass('is-drop-target');
|
|
const target = hit(event);
|
|
if (target.length && target.data('characterID') !== source) {
|
|
target.addClass('is-drop-target'); status.textContent = `Drop to create or change a relationship with ${target.data('label')}.`;
|
|
} else status.textContent = 'Drop on blank canvas to position this character.';
|
|
});
|
|
graph.addEventListener('dragleave', () => cy.nodes().removeClass('is-drop-target'));
|
|
graph.addEventListener('drop', event => {
|
|
if (!source) return;
|
|
event.preventDefault();
|
|
const id = source, target = hit(event); source = null;
|
|
cy.nodes().removeClass('is-drop-target');
|
|
if (target.length && target.data('characterID') !== id) {
|
|
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() });
|
|
extraNodes.add(id); applyFocus(); cy.$id(`c-${id}`).show(); remember();
|
|
}
|
|
});
|
|
// A connector is separate from Cytoscape's node-position drag gesture.
|
|
const handle = document.createElement('button');
|
|
handle.type = 'button'; handle.draggable = true; handle.textContent = '↗';
|
|
handle.className = 'btn btn-primary btn-sm'; handle.style.cssText = 'position:absolute;z-index:3;min-width:36px;min-height:36px';
|
|
handle.title = 'Drag to another character, or click to add a relationship'; handle.setAttribute('aria-label', handle.title);
|
|
graph.parentElement.append(handle);
|
|
function positionHandle() {
|
|
const node = cy.$id(`c-${focus}`);
|
|
handle.hidden = !node.length || !node.visible();
|
|
if (handle.hidden) return;
|
|
const box = node.renderedBoundingBox();
|
|
handle.style.left = `${box.x2}px`; handle.style.top = `${graph.offsetTop + box.y1}px`;
|
|
}
|
|
handle.addEventListener('dragstart', event => startDrag(event, focus));
|
|
handle.addEventListener('dragend', () => { source = null; cy.nodes().removeClass('is-drop-target'); });
|
|
handle.addEventListener('click', () => openEditor(focus, null));
|
|
cy.style().selector('node.is-drop-target').style({ 'border-width': 6, 'border-color': '#198754', 'overlay-opacity': .15 }).update();
|
|
cy.on('tap', 'node', event => focusCharacter(event.target.data('characterID')));
|
|
cy.on('cxttap', 'node', event => {
|
|
focusCharacter(event.target.data('characterID'));
|
|
openContext(document.querySelector(`[data-rw-entry="${focus}"]`), event.originalEvent);
|
|
});
|
|
cy.on('cxttap', 'edge', event => {
|
|
workspace.selectRelationship(event.target.data('relationshipID'));
|
|
openContext(document.querySelector('.relationship-map-details'), event.originalEvent);
|
|
});
|
|
function openContext(element, original) {
|
|
if (!window.PlotDirectorPwa?.standalone || original?.ctrlKey || !element) return;
|
|
if (!element.getClientRects().length || element.closest('[hidden]')) {
|
|
showDetail(); element = document.getElementById('rwDetailPanel');
|
|
}
|
|
element.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true,
|
|
clientX: original?.clientX || 100, clientY: original?.clientY || 100 }));
|
|
}
|
|
cy.on('pan zoom position', () => { positionHandle(); remember(); });
|
|
document.getElementById('rwZoomIn').addEventListener('click', () => cy.zoom({ level: Math.min(2.5, cy.zoom() * 1.2), renderedPosition: { x: graph.clientWidth / 2, y: graph.clientHeight / 2 } }));
|
|
document.getElementById('rwZoomOut').addEventListener('click', () => cy.zoom({ level: Math.max(.05, cy.zoom() / 1.2), renderedPosition: { x: graph.clientWidth / 2, y: graph.clientHeight / 2 } }));
|
|
document.getElementById('rwCentre').addEventListener('click', () => applyFocus(true));
|
|
document.getElementById('rwRemove').addEventListener('click', () => { if (focus) { removed.add(focus); extraNodes.delete(focus); focus = null; applyFocus(); remember(); } });
|
|
document.getElementById('rwReset').addEventListener('click', () => { removed.clear(); document.querySelector('[data-map-reset]').click(); applyFocus(); remember(); });
|
|
document.getElementById('rwPalettes').addEventListener('click', event => { 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); 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 => {
|
|
if (event.touches.length !== 2 || !pinchDistance) return;
|
|
event.preventDefault();
|
|
const distance = Math.hypot(event.touches[0].clientX-event.touches[1].clientX, event.touches[0].clientY-event.touches[1].clientY);
|
|
cy.zoom(Math.max(.05, Math.min(2.5, cy.zoom() * distance / pinchDistance))); pinchDistance = distance;
|
|
}, { passive: false });
|
|
graph.addEventListener('touchend', () => { pinchDistance = null; });
|
|
let scrubTimer;
|
|
async function refresh() {
|
|
request?.abort(); request = new AbortController(); const active = request;
|
|
loading = true;
|
|
try {
|
|
const params = new URLSearchParams({ projectId });
|
|
if (currentScene) params.set('sceneId', currentScene);
|
|
const response = await fetch(`/RelationshipMap/State?${params}`, { signal: active.signal });
|
|
if (!response.ok) throw new Error('Could not load relationship state.');
|
|
const model = await response.json();
|
|
if (active !== request) return;
|
|
stateLoaded = true; workspace.update(model); applyFocus();
|
|
if (model.changeSceneIDs) {
|
|
changes = model.changeSceneIDs.map(id => scenes.findIndex(s => Number(s.value) === id) + 1).filter(n => n > 0).sort((a,b) => a-b);
|
|
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.`;
|
|
if (focus) renderCharacterDetail();
|
|
else clearDetail();
|
|
} catch (error) { if (error.name !== 'AbortError') { stateLoaded = false; status.textContent = error.message; } }
|
|
finally { if (active === request) loading = false; }
|
|
}
|
|
timeline.addEventListener('input', () => { labelPoint(); loading = true; stateLoaded = false; clearTimeout(scrubTimer); scrubTimer = setTimeout(refresh, 160); });
|
|
function jump(next) { const n = Number(timeline.value); timeline.value = next ? changes.find(i => i > n) ?? scenes.length + 1 : [...changes].reverse().find(i => i < n) ?? 0; timeline.dispatchEvent(new Event('input')); }
|
|
document.getElementById('rwPrevious').addEventListener('click', () => jump(false));
|
|
document.getElementById('rwNext').addEventListener('click', () => jump(true));
|
|
form.addEventListener('submit', async event => {
|
|
event.preventDefault();
|
|
if (!editorReady || !form.reportValidity()) return;
|
|
const submit = form.querySelector('[type="submit"]'); submit.disabled = true;
|
|
try {
|
|
const response = await fetch(form.action, { method: 'POST', body: new FormData(form) });
|
|
if (!response.ok) throw new Error(await response.text() || 'The relationship could not be saved.');
|
|
const selected = field('SceneID').value;
|
|
timeline.value = selected ? scenes.findIndex(s => s.value === selected) + 1 : 0;
|
|
labelPoint();
|
|
dialog.close();
|
|
await refresh(); applyFocus(true); remember();
|
|
} catch (error) { editStatus.textContent = error.message; }
|
|
finally { submit.disabled = false; }
|
|
});
|
|
|
|
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 showDetail() { document.getElementById('rwDetailPanel').hidden = false; }
|
|
function clearDetail() {
|
|
document.getElementById('relationshipMapEmptyDetail').classList.remove('d-none');
|
|
document.getElementById('relationshipMapDetail').classList.add('d-none');
|
|
workspace.selectedRelationship = null; activeRelationship = null;
|
|
}
|
|
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;
|
|
showDetail();
|
|
}
|
|
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 supportingTitle = document.querySelector('.rw-navigation h3').textContent;
|
|
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 (${cast.length})` : supportingTitle;
|
|
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('rwInfo').addEventListener('click', () => {
|
|
if (focus) renderCharacterDetail(); showDetail();
|
|
const active = board.classList.toggle('mobile-detail'); board.classList.remove('mobile-characters');
|
|
document.getElementById('rwInfo').setAttribute('aria-expanded', String(active));
|
|
});
|
|
document.getElementById('rwClearFocus').addEventListener('click', () => { focus = null; applyFocus(); clearDetail(); remember(); });
|
|
document.getElementById('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.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(); }
|
|
|
|
applyFocus(!!workspace.focusCharacterId);
|
|
if (focus && window.innerWidth > 800) showDetail();
|
|
})();
|