PlotDirector/PlotLine/wwwroot/js/plot-line-workspace.js

347 lines
22 KiB
JavaScript

(() => {
const form = document.getElementById("plot-workspace-form");
const inspector = document.getElementById("plot-inspector");
const inspectorContent = document.getElementById("plot-inspector-content");
const backdrop = document.getElementById("plot-inspector-backdrop");
if (!form || !inspector || !inspectorContent || !backdrop) return;
const projectId = form.querySelector('[name="projectId"]')?.value;
const bookId = () => form.querySelector('[name="bookId"]')?.value || "";
const scenarioId = () => form.querySelector('[name="scenarioId"]')?.value || "";
form.querySelectorAll("[data-plot-submit]").forEach(control => control.addEventListener("change", () => form.submit()));
form.querySelectorAll("[data-line-choice]").forEach(control => control.addEventListener("change", () => {
if (!form.querySelector("[data-line-choice]:checked")) control.checked = true;
form.querySelectorAll('[name="threadId"]').forEach(thread => thread.checked = false);
form.submit();
}));
let sharedOnly=false,intersectionIndex=-1;
const applySceneFilter=()=>{
const query=(document.getElementById("plot-scene-search")?.value||"").trim().toLocaleLowerCase();
const toggle=document.getElementById("plot-shared-only");if(toggle)toggle.checked=sharedOnly;
document.querySelectorAll("[data-plot-scene]").forEach(card=>{card.hidden=(query.length>0&&!card.dataset.searchText.toLocaleLowerCase().includes(query))||(sharedOnly&&card.dataset.shared!=="true");});
intersectionIndex=-1;const count=[...document.querySelectorAll('[data-plot-scene][data-shared="true"]')].filter(card=>!card.hidden).length;const status=document.querySelector('[data-weave-status]');if(status)status.textContent=count+' visible intersections';
};
document.getElementById("plot-scene-search")?.addEventListener("input",applySceneFilter);
document.addEventListener('change',event=>{if(event.target.id==='plot-shared-only'){sharedOnly=event.target.checked;applySceneFilter();}});
document.addEventListener('click',event=>{
if(!event.target.closest('#plot-next-intersection'))return;
const cards=[...document.querySelectorAll('[data-plot-scene][data-shared="true"]')].filter(card=>!card.hidden);if(!cards.length){applySceneFilter();return;}
intersectionIndex=(intersectionIndex+1)%cards.length;document.querySelectorAll('.plot-weave-focus').forEach(card=>card.classList.remove('plot-weave-focus'));const card=cards[intersectionIndex];card.classList.add('plot-weave-focus');card.scrollIntoView({block:'nearest',inline:'center'});card.querySelector('button')?.focus({preventScroll:true});const status=document.querySelector('[data-weave-status]');if(status)status.textContent='Intersection '+(intersectionIndex+1)+' of '+cards.length;
});
const strip = document.getElementById("plot-association-strip");
const dialog = document.getElementById("plot-association-dialog");
let selectedScene = null;
let associationMode = false;
let draggingScene = false;
let dragFrame = 0;
let dragSpeed = 0;
let dragPoint = null;
let lastDragOver = 0;
const stopDragScroll = () => {
cancelAnimationFrame(dragFrame);
dragFrame = 0;
dragSpeed = 0;
dragPoint = null;
};
const highlightLine = line => document.querySelectorAll("[data-drop-line]").forEach(item =>
item.classList.toggle("is-drop-target", !!line && item.dataset.dropLine === line.dataset.dropLine));
const usableTop = () => {
const header = document.querySelector(".pd-application-header");
return header && ["sticky", "fixed"].includes(getComputedStyle(header).position)
? Math.max(0, header.getBoundingClientRect().bottom) : 0;
};
const positionTray = () => strip?.style.setProperty("--plot-tray-top", `${usableTop() + 6}px`);
const header = document.querySelector(".pd-application-header");
if (header) new ResizeObserver(positionTray).observe(header);
window.addEventListener("resize", positionTray);
positionTray();
const scrollDrag = timestamp => {
dragFrame = 0;
if (!draggingScene || !associationMode || !dragPoint || performance.now() - lastDragOver > 400) {
stopDragScroll();
return;
}
const elapsed = Math.min(32, timestamp - (scrollDrag.previous || timestamp));
scrollDrag.previous = timestamp;
window.scrollBy({ top: dragSpeed * elapsed / 1000, behavior: "instant" });
highlightLine(document.elementFromPoint(dragPoint.x, dragPoint.y)?.closest("[data-drop-line]"));
dragFrame = requestAnimationFrame(scrollDrag);
};
const updateDragScroll = event => {
const bounds = document.querySelector(".plot-map-scroll")?.getBoundingClientRect();
const top = Math.max(usableTop(), Math.min(innerHeight, strip.getBoundingClientRect().bottom));
const bottom = Math.min(innerHeight, bounds?.bottom ?? innerHeight);
const zone = Math.min(72, Math.max(0, (bottom - top) / 3));
const y = event.clientY;
if (!bounds || zone === 0 || event.clientX < bounds.left || event.clientX > bounds.right || y < top - 12 || y > bottom) {
stopDragScroll();
return;
}
const proportion = y < top + zone ? -Math.min(1, (top + zone - y) / zone)
: y > bottom - zone ? Math.min(1, (y - bottom + zone) / zone) : 0;
if (!proportion) { stopDragScroll(); return; }
dragSpeed = proportion * 540;
dragPoint = { x: event.clientX, y };
lastDragOver = performance.now();
if (!dragFrame) {
scrollDrag.previous = performance.now();
dragFrame = requestAnimationFrame(scrollDrag);
}
};
const endSceneDrag = () => {
draggingScene = false;
stopDragScroll();
highlightLine(null);
};
document.addEventListener("dragend", endSceneDrag);
document.addEventListener("keydown", event => { if (event.key === "Escape") endSceneDrag(); });
window.addEventListener("blur", endSceneDrag);
document.addEventListener("visibilitychange", () => { if (document.hidden) endSceneDrag(); });
const drawMemberships = () => {
const map = document.querySelector(".plot-narrative-map");
if (!map) return;
map.querySelector(".plot-membership-overlay")?.remove();
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.classList.add("plot-membership-overlay");
svg.setAttribute("width", "100%"); svg.setAttribute("height", "100%");
const origin = map.getBoundingClientRect();
map.querySelectorAll("[data-scene-column]").forEach(card => {
const column = card.dataset.sceneColumn;
const bounds = card.getBoundingClientRect();
const stems = map.querySelectorAll(`.plot-scene-stem[style*="--column:${column};"]`);
stems.forEach((stem, index) => {
const x = stem.offsetLeft, y = stem.offsetTop + 3;
const cx = bounds.right - origin.left;
const cy = bounds.top - origin.top + 24 + index * Math.min(14, 65 / stems.length);
const path = document.createElementNS(svg.namespaceURI, "path");
path.setAttribute("d", stems.length > 1
? `M ${x} ${y} L ${cx + 12 + index * 6} ${y} L ${cx + 12 + index * 6} ${cy} L ${cx} ${cy}`
: `M ${x} ${y} L ${x} ${bounds.top - origin.top > y ? bounds.top - origin.top : bounds.bottom - origin.top}`);
path.style.stroke = getComputedStyle(stem).getPropertyValue("--line-colour");
path.classList.toggle("is-shared", stems.length > 1);
svg.append(path);
});
});
map.append(svg);
};
new ResizeObserver(drawMemberships).observe(document.querySelector(".plot-map-scroll") || form);
drawMemberships();
document.querySelectorAll("[data-map-mode]").forEach(button => button.addEventListener("click", () => {
const associate = button.dataset.mapMode === "associate";
associationMode = associate;
document.body.classList.toggle("plot-associating", associate);
positionTray();
if (!associate) endSceneDrag();
strip.hidden = !associate;
document.querySelectorAll(".plot-associate-action").forEach(action => action.hidden = !associate);
document.querySelectorAll("[data-map-mode]").forEach(item => {
const active = item === button;
item.setAttribute("aria-pressed", String(active));
item.classList.toggle("btn-primary", active);
item.classList.toggle("btn-outline-secondary", !active);
});
}));
const layoutMap = () => {
const map = document.querySelector(".plot-narrative-map");
if (!map) return;
const step = Number(document.getElementById("plot-map-zoom")?.value || 224);
const offset = parseFloat(getComputedStyle(map).getPropertyValue("--plot-map-origin")) || 260;
map.style.setProperty("--step", `${step}px`);
map.querySelectorAll("[data-source-column]").forEach(path => {
const sx = offset + Number(path.dataset.sourceColumn) * step;
const tx = offset + Number(path.dataset.targetColumn) * step;
const sy = Number(path.dataset.sourceY), ty = Number(path.dataset.targetY);
path.setAttribute("d", `M ${sx} ${sy} Q ${(sx + tx) / 2} ${Math.min(sy, ty) - 45} ${tx} ${ty}`);
});
map.style.width = `${Math.max(900, Number(map.dataset.mapColumns) * step + offset)}px`;
drawMemberships();
};
document.getElementById("plot-map-zoom")?.addEventListener("change", layoutMap);
window.addEventListener("resize", layoutMap);
layoutMap();
const selectScene = button => {
selectedScene = button.dataset.associateScene;
document.querySelectorAll("[data-associate-scene]").forEach(item => item.setAttribute("aria-pressed", String(item === button)));
document.getElementById("plot-association-status").textContent = `Selected: ${button.title}. Choose Add selected scene on a plot line.`;
};
document.querySelectorAll("[data-associate-scene]").forEach(button => {
button.addEventListener("click", () => selectScene(button));
button.addEventListener("dragstart", event => {
selectScene(button);
draggingScene = associationMode;
event.dataTransfer.setData("text/plain", selectedScene);
});
});
const associateScene = async lineId => {
if (!selectedScene) {
document.getElementById("plot-association-status").textContent = "Choose a manuscript scene first.";
return;
}
const pagePosition = { left: window.scrollX, top: window.scrollY };
const stripPosition = strip.querySelector(".plot-scene-strip").scrollLeft;
const mapPosition = document.querySelector(".plot-map-scroll").scrollLeft;
const editor = dialog.querySelector("[data-association-editor]");
const result = dialog.querySelector("[data-association-result]");
editor.replaceChildren();
result.textContent = "Loading thread event editor…";
const lineName = document.querySelector(`[data-drop-line="${lineId}"].plot-lane-label [data-lane-name]`)?.textContent.trim() || "Plot Line";
dialog.querySelector("h2").textContent = `${document.querySelector(`[data-associate-scene="${selectedScene}"] strong`)?.textContent || "Scene"} → ${lineName}`;
if (!dialog.open) dialog.showModal();
try {
const response = await fetch(`/Scenes/SceneThreadsEditor?sceneId=${encodeURIComponent(selectedScene)}`);
if (!response.ok) throw new Error("The editor could not be loaded.");
const documentFragment = document.createElement("div");
documentFragment.innerHTML = await response.text();
const source = documentFragment.querySelector('form[action$="AddThreadEvent"]');
if (!source) throw new Error("The thread event editor is unavailable.");
source.removeAttribute("data-scene-editor-form");
source.dataset.confirmSkip = "true";
const advanced = document.createElement("details");
const summary = document.createElement("summary");
summary.textContent = "Connections / Advanced";
advanced.append(summary);
["TargetPlotLineID", "SelectedTargetPlotLineIDs"].forEach(name => {
const group = source.querySelector(`[name="${name}"]`)?.closest(".form-group");
if (group) advanced.append(group);
});
source.querySelector('[type="submit"]')?.parentElement.before(advanced);
const thread = source.querySelector('[name="PlotThreadID"]');
const allowedThreads = new Set(Array.from(document.querySelectorAll(`[data-line-thread="${lineId}"]`), item => item.value));
Array.from(thread.options).forEach(option => { if (option.value && !allowedThreads.has(option.value)) option.remove(); });
if (thread.options.length > 1) thread.selectedIndex = 1;
const line = document.createElement("input");
line.type = "hidden"; line.name = "PlotLineID"; line.value = lineId; source.append(line);
editor.append(source);
result.textContent = "Choose a thread and contribution role, then add the canonical event.";
source.addEventListener("submit", async event => {
event.preventDefault();
event.stopPropagation();
const save = source.querySelector('[type="submit"]');
save.disabled = true;
try {
const saved = await fetch(source.action, { method: "POST", body: new FormData(source), headers: { "X-Requested-With": "XMLHttpRequest" } });
if (!saved.ok) {
const error = await saved.json();
throw new Error(error.message || "The association could not be saved.");
}
dialog.close();
const status = document.getElementById("plot-association-status");
status.textContent = "Association saved. Updating map…";
try {
const query = new URLSearchParams(new FormData(form));
const response = await fetch(`${form.action || location.pathname}?${query}`, { headers: { "X-Plot-Map": "true" } });
if (!response.ok || response.redirected) throw new Error("Map refresh failed");
const updated = new DOMParser().parseFromString(await response.text(), "text/html");
const nextMap = updated.querySelector(".plot-narrative-map");
if (!nextMap) throw new Error("Map refresh failed");
const scroll = document.querySelector(".plot-map-scroll");
const offset = mapPosition;
scroll.querySelector(".plot-narrative-map").replaceWith(nextMap);
updated.querySelectorAll("[data-map-line-count]").forEach(count => {
const label = form.querySelector(`[data-line-count="${count.dataset.mapLineCount}"]`);
if (label) label.textContent = `${count.value} scenes`;
});
updated.querySelectorAll("[data-associate-scene]").forEach(scene => {
const state = document.querySelector(`[data-associate-scene="${scene.dataset.associateScene}"] [data-association-state]`);
if (state) state.textContent = scene.querySelector("[data-association-state]").textContent;
});
document.querySelectorAll("[data-line-thread]").forEach(input => input.remove());
updated.querySelectorAll("[data-line-thread]").forEach(input => strip.before(input));
nextMap.querySelectorAll(".plot-associate-action").forEach(button => button.hidden = !associationMode);
document.getElementById("plot-map-zoom").dispatchEvent(new Event("change"));
scroll.scrollLeft = offset;
document.getElementById("plot-scene-search")?.dispatchEvent(new Event("input"));
strip.querySelector(".plot-scene-strip").scrollLeft = stripPosition;
window.scrollTo({ ...pagePosition, behavior: "instant" });
status.textContent = "Association saved. Continue adding scenes.";
} catch {
status.textContent = "Association saved, but the map could not refresh. Refresh the view before continuing.";
}
} catch (error) { result.textContent = error.message; }
finally { save.disabled = false; }
});
} catch (error) { result.textContent = error.message; }
};
document.addEventListener("click", event => {
const button = event.target.closest("[data-add-line]");
if (button) associateScene(button.dataset.addLine);
});
document.addEventListener("dragover", event => {
const line = event.target.closest("[data-drop-line]");
if (!associationMode || !draggingScene) return;
updateDragScroll(event);
highlightLine(line);
if (line) event.preventDefault();
});
document.addEventListener("dragleave", event => {
if (!event.relatedTarget && (event.clientX <= 0 || event.clientX >= innerWidth || event.clientY <= 0 || event.clientY >= innerHeight)) stopDragScroll();
if (event.target.closest("[data-drop-line]") && !event.relatedTarget?.closest?.("[data-drop-line]")) document.querySelectorAll(".is-drop-target").forEach(item => item.classList.remove("is-drop-target"));
});
document.addEventListener("drop", event => {
const line = event.target.closest("[data-drop-line]");
endSceneDrag();
if (!associationMode || !selectedScene || !line) return;
event.preventDefault();
document.querySelectorAll(".is-drop-target").forEach(item => item.classList.remove("is-drop-target"));
associateScene(line.dataset.dropLine);
});
dialog?.querySelector("[data-association-close]").addEventListener("click", () => dialog.close());
const closeInspector = () => {
inspector.setAttribute("aria-hidden", "true");
backdrop.hidden = true;
document.body.classList.remove("plot-inspector-open");
};
const bindInspector = () => {
inspectorContent.querySelector("[data-inspector-close]")?.addEventListener("click", closeInspector);
inspectorContent.querySelectorAll("[data-inspector-tab]").forEach(tab => tab.addEventListener("click", () => {
inspectorContent.querySelectorAll("[data-inspector-tab]").forEach(item => item.classList.toggle("active", item === tab));
inspectorContent.querySelectorAll("[data-inspector-panel]").forEach(panel => panel.hidden = panel.dataset.inspectorPanel !== tab.dataset.inspectorTab);
}));
inspectorContent.querySelector("[data-manuscript-load]")?.addEventListener("click", async event => {
const target = document.getElementById("plot-manuscript-content");
event.currentTarget.disabled = true;
target.innerHTML = '<p class="muted">Loading manuscript…</p>';
const query = new URLSearchParams({ projectId, bookId: bookId(), sceneId: event.currentTarget.dataset.manuscriptLoad });
const response = await fetch(`/PlotLineWorkspace/Manuscript?${query}`);
target.innerHTML = response.ok ? await response.text() : '<p class="text-danger">The manuscript excerpt could not be loaded.</p>';
});
};
document.addEventListener("click", async event => {
const trigger = event.target.closest("[data-health-line]");
if (!trigger) return;
inspectorContent.textContent = "Loading health evidence…";
inspector.setAttribute("aria-hidden", "false");
backdrop.hidden = false;
document.body.classList.add("plot-inspector-open");
try {
const query = new URLSearchParams({ projectId, bookId: bookId(), scenarioId: scenarioId(), plotLineId: trigger.dataset.healthLine });
const response = await fetch(`/PlotLineWorkspace/Health?${query}`);
if (!response.ok || response.redirected) throw new Error("Health evidence could not be loaded.");
inspectorContent.innerHTML = await response.text();
bindInspector();
if (trigger.dataset.healthMarkerScene) inspectorContent.querySelector(`[data-health-scene="${trigger.dataset.healthMarkerScene}"]`)?.scrollIntoView({ block: "nearest" });
inspectorContent.querySelector("[data-inspector-close]")?.focus({ preventScroll: true });
} catch (error) { inspectorContent.textContent = error.message; }
});
document.addEventListener("click", async event => {
const trigger = event.target.closest("[data-scene-inspector]");
if (!trigger) return;
const query = new URLSearchParams({ projectId, bookId: bookId(), sceneId: trigger.dataset.sceneInspector, scenarioId: scenarioId() });
inspectorContent.innerHTML = '<div class="plot-inspector-loading">Loading scene…</div>';
inspector.setAttribute("aria-hidden", "false");
backdrop.hidden = false;
document.body.classList.add("plot-inspector-open");
const response = await fetch(`/PlotLineWorkspace/Inspector?${query}`);
inspectorContent.innerHTML = response.ok ? await response.text() : '<p class="text-danger">The scene inspector could not be loaded.</p>';
if (response.ok) bindInspector();
});
backdrop.addEventListener("click", closeInspector);
document.addEventListener("keydown", event => { if (event.key === "Escape") closeInspector(); });
})();