(() => { '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); 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); 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(); 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('p', thread.plotLineName, 'small text-body-secondary mb-1'), el('h3', thread.title, 'h6')); if (!thread.previousScenes.length) article.append(el('p', 'First picked up here.', 'small mb-2')); else { 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); } } if (thread.canRemove) { const remove = button('Remove from scene', () => removeLink(thread.plotThreadID)); remove.dataset.threadFocus = `remove:${thread.plotThreadID}`; remove.setAttribute('aria-label', `Remove ${thread.title} from scene`); article.append(remove); } rows.append(article); } 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) { 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, threadID }) }); 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', '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); } } }; })();