PlotDirector/PlotLine/wwwroot/js/context-threads.js
2026-12-06 17:57:40 +00:00

224 lines
12 KiB
JavaScript

(() => {
'use strict';
const instances = new WeakMap();
const el = (tag, text, cls) => {
const node = document.createElement(tag);
if (text != null) node.textContent = text;
if (cls) node.className = cls;
return node;
};
const button = (text, action) => {
const node = el('button', text, 'btn btn-outline-secondary btn-sm');
node.type = 'button'; node.addEventListener('click', action); return node;
};
const sceneLabel = s => `Scene ${s.sceneNumber}: ${s.sceneTitle}`;
function mount(node) {
if (instances.has(node)) return;
const bookID = Number(node.dataset.bookId), sceneID = Number(node.dataset.sceneId) || null, chapterID = Number(node.dataset.chapterId);
const add = node.querySelector('[data-thread-add]'), rows = node.querySelector('[data-thread-rows]');
const error = node.querySelector('[data-thread-error]');
let alive = true, busy = false, dialog, data, readVersion = 0;
const controller = new AbortController();
const guard = (value, deferRefresh = false) => {
busy = value;
node.dispatchEvent(new CustomEvent('context-panel-state', { bubbles: true, detail: { dirty: value, busy: false, deferRefresh } }));
};
const fail = e => { if (alive) { error.textContent = e.message; window.PlotDirector?.toast?.error(e.message); } };
async function read() {
const version = ++readVersion;
const query = new URLSearchParams({ bookId: bookID, chapterId: chapterID, ...(sceneID ? { sceneId: sceneID } : {}) });
const response = await fetch('/ContextThreads/State?' + query, { cache: 'no-store', signal: controller.signal });
if (!response.ok || response.redirected) throw Error('Threads are unavailable. Check book access and refresh saved data.');
const result = await response.json();
if (!alive || version !== readVersion) return;
data = result;
const included = data.threads.filter(t => t.includedInChapter || t.includedInScene);
const historical = data.threads.filter(t => t.hasManuscriptAssociation || t.previousScenes.length || (t.assigned && !t.includedInChapter && !t.includedInScene));
const focusKey = rows.contains(document.activeElement) ? document.activeElement.dataset.threadFocus : null;
const openChapters = new Map([...rows.querySelectorAll('details')].map(group => [group.dataset.threadChapter, group.open]));
rows.replaceChildren();
rows.append(el('h3', 'Included here', 'h6 mb-0'));
if (!included.length) rows.append(el('p', 'No threads included here.', 'small mb-1'));
for (const thread of included) {
const article = el('div', null, 'd-flex gap-2 align-items-center justify-content-between');
const label = el('div', thread.title);
label.append(el('small', ` · ${thread.plotLineName} · ${thread.includedInChapter ? 'Chapter' : 'Scene'}`, 'text-body-secondary'));
article.append(label);
if (thread.canRemove) {
const remove = button('Remove', () => removeLink(thread.plotThreadID, thread.includedInChapter));
remove.dataset.threadFocus = `remove:${thread.plotThreadID}`;
remove.setAttribute('aria-label', `Remove ${thread.title} from ${thread.includedInChapter ? 'chapter' : 'scene'}`);
article.append(remove);
}
rows.append(article);
}
const history = el('details');
history.dataset.threadChapter = 'history';
history.open = openChapters.get('history') ?? false;
history.append(el('summary', 'Assigned elsewhere and scene history'));
for (const thread of historical) {
const article = el('article', null, 'writing-context-card');
article.append(el('p', thread.plotLineName, 'small text-body-secondary mb-1'),
el('h3', thread.title, 'h6'));
if (thread.assignedElsewhere && thread.assignmentLabel) article.append(el('p', thread.assignmentLabel, 'small mb-2'));
else if (!thread.previousScenes.length && thread.hasManuscriptAssociation) article.append(el('p', 'Linked in this scene.', 'small mb-2'));
if (thread.previousScenes.length) {
const chapters = new Map();
const lastPickup = thread.previousScenes.at(-1);
for (const scene of thread.previousScenes) {
const key = `${thread.plotThreadID}:${scene.chapterID}`;
if (!chapters.has(key)) {
const group = el('details', null, 'small mb-1');
group.dataset.threadChapter = key;
group.open = openChapters.get(key) ?? true;
const summary = el('summary', `Ch ${scene.chapterNumber}: ${scene.chapterTitle}`, 'fw-semibold');
summary.dataset.threadFocus = `chapter:${key}`;
const list = el('ul', null, 'mb-1');
group.append(summary, list);
chapters.set(key, list);
article.append(group);
}
const item = el('li');
const link = el('a', sceneLabel(scene));
link.href = `/Scenes/Edit/${scene.sceneID}?retainNarrativeFocus=true`;
link.target = '_blank'; link.rel = 'noopener';
link.dataset.contextNarrative = 'author';
link.dataset.threadFocus = `scene:${thread.plotThreadID}:${scene.sceneID}`;
item.append(link);
if (scene === lastPickup) item.append(el('strong', 'Last pickup', 'ms-2'));
chapters.get(key).append(item);
}
}
history.append(article);
}
if (historical.length) rows.append(history);
add.disabled = !data.scope.canEdit;
if (focusKey) {
const nextFocus = [...rows.querySelectorAll('[data-thread-focus]')].find(control => control.dataset.threadFocus === focusKey);
(nextFocus || add).focus({ preventScroll: true });
}
}
async function removeLink(threadID, chapter) {
if (!alive || busy || !data?.scope.canEdit) return;
guard(true); error.textContent = '';
try {
const response = await fetch('/ContextThreads/Remove', {
method: 'POST', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', RequestVerificationToken: node.querySelector('[name="__RequestVerificationToken"]').value },
body: JSON.stringify({ bookID, sceneID, chapterID, threadID, chapter })
});
if (!response.ok || response.redirected) {
const body = await response.json().catch(() => null);
throw Error(body?.message || 'The thread link could not be removed. Review access and try again.');
}
window.PlotDirector?.toast?.success('Thread link removed');
try { await read(); }
catch { error.textContent = 'The link was removed. Refresh saved data to reload the scene.'; }
} catch (e) { fail(e); }
finally {
if (alive) {
guard(false, true);
node.closest('[data-context-workspace]')?.contextController?.invalidate({ bookId: bookID, kind: 'threads' });
}
}
}
function picker() {
if (!alive || busy || !data?.scope.canEdit) return;
guard(true); error.textContent = '';
dialog = el('dialog', null, 'pd-location-picker-dialog');
const heading = el('h2', 'Include threads');
const target = el('p', sceneID ? data.scope.label : data.scope.chapterTitle);
const chapter = el('input');
chapter.type = 'checkbox'; chapter.checked = true; chapter.disabled = !sceneID;
const scopeLabel = el('label', null, 'd-block mb-2');
scopeLabel.append(chapter, ' Include in chapter');
const search = el('input', null, 'form-control');
search.type = 'search'; search.placeholder = 'Search Plot Lines and Threads'; search.setAttribute('aria-label', 'Search Plot Lines and Threads');
const tree = el('div', null, 'pd-location-picker-tree');
const message = el('p'); message.setAttribute('role', 'status');
const selected = new Set();
let saving = false;
const submit = button('Include selected', save), cancel = button('Cancel', () => dialog.close());
submit.className = 'btn btn-primary btn-sm'; submit.disabled = true;
function render() {
tree.replaceChildren();
const term = search.value.trim().toLocaleLowerCase();
const matches = data.threads.filter(thread => !thread.assigned &&
`${thread.plotLineName} ${thread.title}`.toLocaleLowerCase().includes(term));
const reason = thread => chapter.checked ? thread.chapterBlock : thread.sceneBlock;
for (const [title, items] of [
['Available', matches.filter(thread => !reason(thread))],
['Blocked', matches.filter(thread => reason(thread))]
]) {
if (!items.length) continue;
tree.append(el('h3', title, 'h6 mt-2'));
for (const thread of items) {
const label = el('label', null, 'pd-location-picker-row');
const input = el('input');
input.type = 'checkbox';
input.disabled = !!reason(thread) || saving;
input.checked = selected.has(thread.plotThreadID);
input.addEventListener('change', () => {
if (input.checked) selected.add(thread.plotThreadID); else selected.delete(thread.plotThreadID);
submit.disabled = !selected.size;
});
label.append(input, el('span', `${thread.title} · ${thread.plotLineName}`));
if (reason(thread)) label.append(el('small', reason(thread)));
tree.append(label);
}
}
if (!tree.children.length) tree.append(el('p', 'No matching unassigned threads.'));
}
async function save() {
if (saving || !selected.size) return;
saving = true; submit.disabled = true; cancel.disabled = true; search.disabled = true; chapter.disabled = true; render();
message.textContent = 'Saving threads…';
try {
const response = await fetch('/ContextThreads/Add', {
method: 'POST', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', RequestVerificationToken: node.querySelector('[name="__RequestVerificationToken"]').value },
body: JSON.stringify({ bookID, sceneID, chapterID, threadIDs: [...selected], chapter: chapter.checked })
});
if (!response.ok || response.redirected) {
const body = await response.json().catch(() => null);
throw Error(body?.message || 'Threads could not be saved. Review access and try again.');
}
// Keep the dialog and panel guarded until the saved data has reloaded.
try { await read(); }
catch { error.textContent = 'Threads were saved. Refresh saved data to reload the scene.'; }
window.PlotDirector?.toast?.success('Threads included');
saving = false; dialog.close();
} catch (e) {
message.textContent = e.message; window.PlotDirector?.toast?.error(e.message);
saving = false; submit.disabled = false; cancel.disabled = false; search.disabled = false; chapter.disabled = !sceneID; render();
}
}
search.addEventListener('input', render);
chapter.addEventListener('change', () => { selected.clear(); submit.disabled = true; render(); });
dialog.addEventListener('cancel', event => { if (saving) event.preventDefault(); });
dialog.addEventListener('close', () => {
dialog.remove(); dialog = null;
if (alive) {
add.focus(); guard(false, true);
node.closest('[data-context-workspace]')?.contextController?.invalidate({ bookId: bookID, kind: 'threads' });
}
}, { once: true });
dialog.append(heading, target, scopeLabel, search, tree, message, submit, cancel);
dialog.setAttribute('aria-label', 'Include threads');
document.body.append(dialog); render(); dialog.showModal(); search.focus();
}
add.addEventListener('click', picker);
instances.set(node, { busy: () => busy, refresh: () => read().catch(fail), dispose() { alive = false; controller.abort(); dialog?.remove(); add.removeEventListener('click', picker); } });
read().catch(e => { if (e.name !== 'AbortError') fail(e); });
}
window.PlotDirectorContextLifecycles = { ...(window.PlotDirectorContextLifecycles || {}), threads: {
mount, canRefresh: node => !instances.get(node)?.busy(),
onInvalidation(node) {
const instance = instances.get(node);
if (!instance || instance.busy()) return false;
instance.refresh(); return true;
},
dispose(node) { instances.get(node)?.dispose(); instances.delete(node); }
} };
})();