PlotDirector/PlotLine/wwwroot/js/location-details.js

521 lines
26 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.

(() => {
const source = document.getElementById('location-detail-data');
if (!source) return;
const data = JSON.parse(source.textContent);
const locations = new Map(data.locations.map(item => [item.id, item]));
const ordered = [...locations.values()].sort((a, b) => a.name.localeCompare(b.name) || a.id - b.id);
const children = new Map();
for (const item of ordered) {
if (!children.has(item.parent)) children.set(item.parent, []);
children.get(item.parent).push(item);
}
function element(tag, text, className) {
const node = document.createElement(tag);
if (text != null) node.textContent = text;
if (className) node.className = className;
return node;
}
function button(text, action, className = 'btn btn-outline-secondary btn-sm') {
const node = element('button', text, className);
node.type = 'button';
node.addEventListener('click', action);
return node;
}
function onTab(name, callback) {
const pane = document.getElementById(`location-panel-${name}`);
document.getElementById(`location-tab-${name}`).addEventListener('shown.bs.tab', callback);
if (pane.classList.contains('active')) callback();
}
function mountHierarchy() {
const root = document.querySelector('[data-location-hierarchy]');
const viewport = root.querySelector('.location-tree-viewport');
const space = root.querySelector('.location-tree-space');
const graph = root.querySelector('.location-tree-graph');
const lineage = new Map();
const visited = new Set();
let top = locations.get(data.current);
for (let parent = locations.get(top.parent); parent && !visited.has(parent.id) && parent.id !== data.current;
parent = locations.get(top.parent)) {
visited.add(parent.id);
lineage.set(parent.id, top);
top = parent;
}
let scale = 1;
let initialized = false;
let drag;
function branch(item, depth) {
const node = element('div', null, 'location-tree-branch');
const card = element('div', null, 'location-tree-node');
const link = element('a', item.name);
link.href = item.hierarchyUrl;
link.title = item.path || item.name;
if (item.id === data.current) {
card.dataset.current = '';
link.setAttribute('aria-current', 'page');
}
card.append(link);
node.append(card);
const descendants = lineage.has(item.id) ? [lineage.get(item.id)] :
(children.get(item.id) || []).filter(child => !visited.has(child.id) && child.id !== data.current);
if (!descendants.length) return node;
const row = element('div', null, 'location-tree-children');
const populate = () => row.replaceChildren(...descendants.map(child => branch(child, depth + 1)));
if (!lineage.has(item.id)) {
row.hidden = depth > lineage.size + 1;
const toggle = button('', () => {
row.hidden = !row.hidden;
if (!row.hidden && !row.childElementCount) populate();
describe();
resize();
}, 'location-tree-toggle');
function describe() {
toggle.textContent = row.hidden ? '+' : '−';
toggle.setAttribute('aria-expanded', String(!row.hidden));
toggle.setAttribute('aria-label', `${row.hidden ? 'Expand' : 'Collapse'} ${item.name} (${descendants.length} children)`);
}
describe();
card.append(toggle);
}
if (!row.hidden) populate();
node.append(row);
return node;
}
function resize() {
graph.style.transform = `scale(${scale})`;
space.style.width = `${viewport.clientWidth + graph.offsetWidth * scale}px`;
space.style.height = `${viewport.clientHeight + graph.offsetHeight * scale}px`;
graph.style.top = `${viewport.clientHeight / 2}px`;
}
function centre(target) {
const bounds = target.getBoundingClientRect();
const frame = viewport.getBoundingClientRect();
viewport.scrollLeft += bounds.left + bounds.width / 2 - frame.left - viewport.clientWidth / 2;
viewport.scrollTop += bounds.top + bounds.height / 2 - frame.top - viewport.clientHeight / 2;
}
function fit() {
scale = Math.max(.03, Math.min(1, (viewport.clientWidth - 34) / graph.offsetWidth,
(viewport.clientHeight - 34) / graph.offsetHeight));
resize();
centre(graph);
}
function zoom(factor) {
const frame = viewport.getBoundingClientRect();
const before = graph.getBoundingClientRect();
const x = (frame.left + viewport.clientWidth / 2 - before.left) / scale;
const y = (frame.top + viewport.clientHeight / 2 - before.top) / scale;
scale = Math.max(.03, Math.min(2.5, scale * factor));
resize();
const after = graph.getBoundingClientRect();
viewport.scrollLeft += after.left + x * scale - frame.left - viewport.clientWidth / 2;
viewport.scrollTop += after.top + y * scale - frame.top - viewport.clientHeight / 2;
}
root.querySelector('[data-tree-fit]').addEventListener('click', fit);
root.querySelector('[data-tree-centre]').addEventListener('click', () => centre(graph.querySelector('[data-current]')));
for (const control of root.querySelectorAll('[data-tree-zoom]')) {
control.addEventListener('click', () => zoom(Number(control.dataset.treeZoom)));
}
viewport.addEventListener('pointerdown', event => {
if (event.button !== 0 || event.target.closest('a, button') ||
event.offsetX >= viewport.clientWidth && event.target === viewport) return;
drag = { x: event.clientX + viewport.scrollLeft, y: event.clientY + viewport.scrollTop };
viewport.setPointerCapture(event.pointerId);
});
viewport.addEventListener('pointermove', event => {
if (!drag) return;
viewport.scrollLeft = drag.x - event.clientX;
viewport.scrollTop = drag.y - event.clientY;
});
viewport.addEventListener('lostpointercapture', () => { drag = null; });
onTab('hierarchy', () => {
if (!initialized) {
graph.append(branch(top, 0));
initialized = true;
fit();
} else resize();
});
new ResizeObserver(() => { if (initialized && viewport.clientWidth) resize(); }).observe(viewport);
}
const typeIcons = new Map([
['Adjacent To', '▥'], ['Above', '↑'], ['Below', '↓'], ['Connected To', '↔'],
['Visible From', '◉'], ['Audible From', '♫'], ['Near', '≈'], ['Leads To', '⇥'],
['Overlooks', '↘'], ['Same Building As', '▣'], ['Same Area As', '▧'],
['Secret Passage', '◇'], ['Road Connection', '═']
]);
const traits = [
['canSeeMovement', '◐', 'See movement'],
['canSeeClearly', '◉', 'See clearly'],
['canHearNormalSpeech', '♪', 'Hear normal speech'],
['canHearLoudNoise', '♫', 'Hear loud noise'],
['canTravelDirectly', '⇢', 'Travel directly']
];
const symbol = name => typeIcons.get(name) || '•';
function mountMatrix() {
const root = document.querySelector('[data-location-matrix]');
const table = root.querySelector('[data-matrix-table]');
const editor = root.querySelector('[data-matrix-editor]');
const filter = root.querySelector('[data-matrix-filter]');
const add = root.querySelector('[data-matrix-add]');
const legend = root.querySelector('[data-matrix-legend]');
const error = root.querySelector('[data-matrix-error]');
const current = locations.get(data.current);
const selected = new Set([
current.id, ...(current.parent ? [current.parent] : []),
...(children.get(current.parent) || []).map(item => item.id),
...(children.get(current.id) || []).map(item => item.id)
]);
const types = new Map(data.types.map(type => [type.id, type]));
const pairs = new Map();
let activePair;
let loaded = false;
let loading = false;
let busy = false;
const key = (from, to) => `${from}/${to}`;
const forPair = (from, to) => pairs.get(key(from, to)) || [];
function status(message = '') {
error.textContent = message;
error.hidden = !message;
}
async function read() {
const response = await fetch(root.dataset.readUrl, { cache: 'no-store' });
if (!response.ok || response.redirected) throw new Error('Unable to load relationships.');
const records = await response.json();
pairs.clear();
for (const record of records) {
const direction = key(record.fromLocationID, record.toLocationID);
if (!pairs.has(direction)) pairs.set(direction, []);
pairs.get(direction).push(record);
if (!types.has(record.locationRelationshipTypeID)) {
types.set(record.locationRelationshipTypeID, {
id: record.locationRelationshipTypeID, name: record.relationshipTypeName, inactive: true
});
}
if (record.fromLocationID === current.id) selected.add(record.toLocationID);
if (record.toLocationID === current.id) selected.add(record.fromLocationID);
}
}
function renderControls() {
const previous = filter.value;
filter.replaceChildren(new Option('All types', ''), ...[...types.values()].map(type => new Option(type.name, type.id)));
filter.value = previous;
add.replaceChildren(new Option('Choose location', ''), ...ordered.filter(item => !selected.has(item.id))
.map(item => new Option(item.path || item.name, item.id)));
legend.replaceChildren(
element('span', '→ Stored direction'), element('span', '⇄ Explicitly bidirectional'), element('span', '· No relationship'),
...[...types.values()].map(type => element('span', `${symbol(type.name)} ${type.name}`)),
...traits.map(([, icon, label]) => element('span', `${icon} ${label}`))
);
}
function indicators(record) {
const marks = [record.isBidirectional ? '⇄' : '→', symbol(record.relationshipTypeName)];
const labels = [record.relationshipTypeName, record.isBidirectional ? 'both ways' : 'one way'];
for (const [field, icon, label] of traits) {
if (!record[field]) continue;
marks.push(icon);
labels.push(label);
}
const indicator = element('span', marks.join(' '), 'location-matrix-indicator');
indicator.setAttribute('aria-label', labels.join(', '));
indicator.title = labels.join(', ');
return indicator;
}
function drawMatrix() {
const items = ordered.filter(item => selected.has(item.id));
const header = element('tr');
header.append(element('th', 'From / To'));
for (const item of items) header.append(heading(item, 'col'));
const head = element('thead');
head.append(header);
const body = element('tbody');
for (const from of items) {
const row = element('tr');
row.append(heading(from, 'row'));
for (const to of items) {
const cell = element('td');
if (from.id === current.id || to.id === current.id) cell.classList.add('location-matrix-current');
if (from.id === to.id) cell.textContent = '—';
else {
const records = [
...forPair(from.id, to.id),
...forPair(to.id, from.id).filter(record => record.isBidirectional)
].filter(record => !filter.value || String(record.locationRelationshipTypeID) === filter.value);
const control = button('', () => select(from.id, to.id), 'location-matrix-cell');
control.dataset.pair = key(from.id, to.id);
control.disabled = busy;
control.setAttribute('aria-pressed', String(activePair?.[0] === from.id && activePair?.[1] === to.id));
const marks = records.map(indicators);
control.setAttribute('aria-label', `${from.name} to ${to.name}: ${marks.map(mark =>
mark.title).join('; ') || 'No matching relationship'}`);
control.append(...(marks.length ? marks : ['·']));
cell.append(control);
}
row.append(cell);
}
body.append(row);
}
table.replaceChildren(head, body);
}
function heading(item, scope) {
const node = element('th', item.name);
node.scope = scope;
node.title = item.path;
if (item.id === current.id) node.classList.add('location-matrix-current');
return node;
}
function select(from, to) {
if (busy) return;
activePair = [from, to];
for (const cell of table.querySelectorAll('[data-pair]')) {
cell.setAttribute('aria-pressed', String(cell.dataset.pair === key(from, to)));
}
status();
drawEditor();
}
function field(label, input) {
const wrapper = element('label', null, 'location-direction-field');
wrapper.append(element('span', label), input);
return wrapper;
}
function updateReciprocal(section, from, to) {
const notice = section.querySelector('[data-reciprocal]');
const inherited = forPair(to, from).filter(record => record.isBidirectional);
notice.hidden = !inherited.length;
notice.textContent = inherited.length
? `Applies both ways from the opposite panel: ${inherited.map(r => r.relationshipTypeName).join(', ')}.` : '';
}
function panel(from, to, selectedRecord) {
const section = element('section', null, 'location-direction-panel');
section.dataset.direction = key(from, to);
section.append(element('h3', `${locations.get(from).name} → ${locations.get(to).name}`));
const records = forPair(from, to);
const notice = element('p', null, 'small muted');
notice.dataset.reciprocal = '';
section.append(notice);
updateReciprocal(section, from, to);
if (!records.length) section.append(element('p', 'No relationship stored in this direction.', 'small muted'));
const saved = element('select', null, 'form-select form-select-sm');
records.forEach(record => saved.add(new Option(record.relationshipTypeName, record.locationRelationshipID)));
if (data.canEdit) saved.add(new Option('New directional relationship', '0'));
if (records.some(record => record.locationRelationshipID === selectedRecord)) saved.value = selectedRecord;
if (saved.length > 1) section.append(field('Relationship record', saved));
const host = element('div');
section.append(host);
function show() {
const record = records.find(item => item.locationRelationshipID === Number(saved.value));
host.replaceChildren();
if (!record && !data.canEdit) return;
const form = element('form', null, 'location-direction-form');
const controls = element('fieldset');
controls.disabled = !data.canEdit || busy;
const type = element('select', null, 'form-select form-select-sm');
type.name = 'LocationRelationshipTypeID';
type.required = true;
type.add(new Option('Choose type', ''));
for (const item of types.values()) {
if (!item.inactive || item.id === record?.locationRelationshipTypeID) type.add(new Option(item.name, item.id));
}
type.value = record?.locationRelationshipTypeID || filter.value || '';
const strength = element('input', null, 'form-control form-control-sm');
Object.assign(strength, { name: 'Strength', type: 'number', min: '1', max: '10', value: record?.strength ?? '' });
controls.append(field('Type', type), field('Strength (1–10, optional)', strength));
for (const [property, , label] of [...traits, ['isBidirectional', '', 'Applies in both directions']]) {
const input = element('input', null, 'form-check-input');
Object.assign(input, { type: 'checkbox', name: property, value: 'true', checked: Boolean(record?.[property]) });
const checkbox = element('label', null, 'location-direction-check');
checkbox.append(input, label);
controls.append(checkbox);
}
const notes = element('textarea', null, 'form-control form-control-sm');
Object.assign(notes, { name: 'Notes', rows: 3, value: record?.notes || '' });
controls.append(field('Notes', notes));
if (data.canEdit) {
const actions = element('div', null, 'button-row');
const save = element('button', 'Save', 'btn btn-primary btn-sm');
save.type = 'submit';
actions.append(save);
if (record) actions.append(button('Archive', () => {
if (window.confirm('Archive this relationship? It can be restored from Archived Items.')) {
void write(form, from, to, record, true);
}
}));
controls.append(actions);
}
form.append(controls);
form.addEventListener('submit', event => {
event.preventDefault();
void write(form, from, to, record, false);
});
host.append(form);
}
saved.addEventListener('change', show);
show();
return section;
}
function drawEditor() {
if (!activePair) return;
const [from, to] = activePair;
editor.replaceChildren(panel(from, to), panel(to, from));
}
async function write(form, from, to, record, archive) {
if (busy) return;
const body = new FormData(form);
for (const [name, value] of Object.entries({
__RequestVerificationToken: root.querySelector('[name=__RequestVerificationToken]').value,
ProjectID: data.projectID, FromLocationID: from, ToLocationID: to,
LocationRelationshipID: record?.locationRelationshipID || 0,
ExpectedUpdatedDate: record?.updatedDate || '', Archive: archive
})) body.set(name, value);
busy = true;
root.setAttribute('aria-busy', 'true');
editor.inert = true;
status();
let refresh = false;
let saved = false;
let savedId;
try {
const response = await fetch(root.dataset.writeUrl, { method: 'POST', body });
if (!response.ok || response.redirected) {
const problem = await response.json().catch(() => null);
refresh = response.status === 409;
throw new Error(problem?.error || 'Unable to save this relationship.');
}
saved = true;
refresh = true;
savedId = (await response.json()).id;
window.PlotDirector?.toast?.success(archive ? 'Relationship archived.' : 'Relationship saved.');
} catch (failure) {
status(failure.message);
} finally {
try {
if (refresh) {
await read();
renderControls();
}
} catch {
status(saved ? 'Saved. Reload this page to refresh the matrix.' : 'Reload this page to refresh the matrix.');
}
busy = false;
root.removeAttribute('aria-busy');
editor.inert = false;
if (refresh) {
drawMatrix();
editor.querySelector(`[data-direction="${key(from, to)}"]`)
?.replaceWith(panel(from, to, savedId ?? record?.locationRelationshipID));
updateReciprocal(editor.querySelector(`[data-direction="${key(to, from)}"]`), to, from);
table.querySelector(`[data-pair="${key(...activePair)}"]`)?.focus({ preventScroll: true });
}
}
}
add.addEventListener('change', () => {
if (!add.value) return;
selected.add(Number(add.value));
renderControls();
drawMatrix();
});
filter.addEventListener('change', drawMatrix);
onTab('relationships', async () => {
if (loaded || loading) return;
loading = true;
status();
table.setAttribute('aria-busy', 'true');
try {
await read();
renderControls();
drawMatrix();
loaded = true;
} catch (failure) {
status(failure.message);
} finally {
loading = false;
table.removeAttribute('aria-busy');
}
});
}
function mountSpatial() {
const map = document.querySelector('[data-location-map]');
const floor = document.querySelector('[data-location-floor]');
if (map) {
const channel = crypto.randomUUID();
const feature = map.dataset.locationMap;
const send = (action, fields) => map.contentWindow?.postMessage({
type: 'plotdirector.spatial.command', channel, action, ...fields
}, location.origin);
const centre = () => send('centre', { id: feature, force: true });
map.addEventListener('load', () => send('init'));
window.addEventListener('message', event => {
if (event.origin !== location.origin || event.source !== map.contentWindow ||
event.data?.channel !== channel || event.data.type !== 'plotdirector.spatial.renderer' ||
event.data.action !== 'ready') return;
send('highlight', { highlights: [{ featureID: feature, roles: [0], label: map.dataset.mapLabel, badge: '' }] });
send('fit', { ids: [feature] });
});
document.querySelector('[data-map-centre]').addEventListener('click', centre);
}
onTab('spatial', () => {
if (map && !map.getAttribute('src')) map.src = map.dataset.src;
if (!floor || floor.dataset.ready) return;
floor.dataset.ready = 'true';
const level = floor.querySelector('[data-floor-level]');
const engine = window.PlotDirectorFloorPlanRenderer.create(floor);
const scroll = floor.querySelector('.location-floor-scroll');
const highlight = floor.dataset.locationBlock
? floor.querySelector(`[data-block="${floor.dataset.locationBlock}"]`)
: floor.querySelector(`[data-floor-grid="${floor.dataset.locationFloor}"]`);
for (const control of floor.querySelectorAll('.floor-plan-stage button')) {
control.tabIndex = -1;
control.setAttribute('aria-disabled', 'true');
}
highlight?.classList.add('location-floor-current');
function showLevel() {
for (const panel of floor.querySelectorAll('[data-floor-panel]')) {
const active = panel.dataset.floorPanel === level.value;
panel.classList.toggle('active', active);
if (!active) continue;
const visible = engine.refreshSharedWalls(panel);
engine.refreshHiddenLocationStyles(visible);
engine.positionTransitions(panel, visible);
}
if (highlight?.closest('[data-floor-panel]').classList.contains('active')) {
const block = highlight.getBoundingClientRect();
const frame = scroll.getBoundingClientRect();
scroll.scrollLeft += block.left + block.width / 2 - frame.left - scroll.clientWidth / 2;
scroll.scrollTop += block.top + block.height / 2 - frame.top - scroll.clientHeight / 2;
} else scroll.scrollTo(0, 0);
}
showLevel();
level.addEventListener('change', showLevel);
});
}
mountHierarchy();
mountMatrix();
mountSpatial();
})();