147 lines
7.9 KiB
JavaScript
147 lines
7.9 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 => `Ch ${s.chapterNumber}: ${s.chapterTitle} · Scene ${s.sceneNumber}: ${s.sceneTitle}`;
|
|
function mount(node) {
|
|
if (instances.has(node)) return;
|
|
const bookID = Number(node.dataset.bookId), sceneID = Number(node.dataset.sceneId);
|
|
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 response = await fetch(`/ContextThreads/State?bookId=${bookID}&sceneId=${sceneID}`, { 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 linked = data.threads.filter(t => t.linked);
|
|
rows.replaceChildren();
|
|
if (!linked.length) rows.append(el('p', 'No threads linked to this scene.'));
|
|
for (const thread of linked) {
|
|
const article = el('article', null, 'writing-context-card');
|
|
article.append(el('h3', `${thread.plotLineName} / ${thread.title}`, 'h6'));
|
|
if (!thread.previousScenes.length) article.append(el('p', 'First picked up here.'));
|
|
else {
|
|
article.append(el('p', 'Previously picked up in:'));
|
|
const list = el('ol');
|
|
for (const scene of thread.previousScenes) list.append(el('li', sceneLabel(scene)));
|
|
article.append(list);
|
|
}
|
|
rows.append(article);
|
|
}
|
|
add.disabled = !data.scope.canEdit;
|
|
}
|
|
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', 'Add threads to scene');
|
|
const target = el('p', data.scope.label);
|
|
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(), expanded = new Set();
|
|
let saving = false;
|
|
const submit = button('Add to scene', 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 groups = new Map();
|
|
for (const thread of data.threads) {
|
|
if (!groups.has(thread.plotLineID)) groups.set(thread.plotLineID, []);
|
|
groups.get(thread.plotLineID).push(thread);
|
|
}
|
|
for (const [lineID, threads] of groups) {
|
|
const matches = term ? threads.filter(t => `${t.plotLineName} ${t.title}`.toLocaleLowerCase().includes(term)) : threads;
|
|
if (!matches.length) continue;
|
|
const group = el('details'); group.open = !!term || expanded.has(lineID);
|
|
group.append(el('summary', threads[0].plotLineName));
|
|
group.addEventListener('toggle', () => { if (!term) { if (group.open) expanded.add(lineID); else expanded.delete(lineID); } });
|
|
for (const thread of matches) {
|
|
const label = el('label', null, 'pd-location-picker-row');
|
|
label.style.setProperty('--picker-depth', '1');
|
|
const input = el('input'); input.type = 'checkbox'; input.value = String(thread.plotThreadID);
|
|
input.disabled = thread.linked || saving; input.checked = thread.linked || selected.has(thread.plotThreadID);
|
|
input.addEventListener('change', () => {
|
|
if (input.checked) selected.add(thread.plotThreadID); else selected.delete(thread.plotThreadID);
|
|
submit.disabled = !selected.size; message.textContent = `${selected.size} selected`;
|
|
});
|
|
label.append(input, el('span', thread.title));
|
|
if (thread.linked) label.append(el('small', ' · Already linked'));
|
|
group.append(label);
|
|
}
|
|
tree.append(group);
|
|
}
|
|
if (!tree.children.length) tree.append(el('p', 'No matching threads.'));
|
|
}
|
|
async function save() {
|
|
if (saving || !selected.size) return;
|
|
saving = true; submit.disabled = true; cancel.disabled = true; search.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, threadIDs: [...selected] })
|
|
});
|
|
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 added to scene');
|
|
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; render();
|
|
}
|
|
}
|
|
search.addEventListener('input', 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, search, tree, message, submit, cancel);
|
|
dialog.setAttribute('aria-label', 'Add threads to scene');
|
|
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); }
|
|
} };
|
|
})();
|