PlotDirector/PlotLine/wwwroot/js/writing-follow.js

429 lines
23 KiB
JavaScript

(() => {
const defaults = {
rootSelector: "",
contentSelector: "",
fragmentSelector: "",
statusTextSelector: "",
tabSelector: "",
panelSelector: "",
selectSelector: "",
tabDataKey: "",
panelDataKey: "",
storageKey: "",
defaultTab: "",
defaultEndpoint: "",
source: "WritingMode",
allowChapterOnly: false,
waitingStatus: "Connected, waiting for scene",
updatingStatus: "Updating",
disconnectedStatus: "Word not connected"
};
const parsePositiveInt = (value) => {
const parsed = Number.parseInt(value || "", 10);
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
};
const fragmentFromHtml = (html, selector) => {
const parsed = new DOMParser().parseFromString(html, 'text/html');
const fragment = parsed.body.firstElementChild;
if (/<!doctype|<html[\s>]|<head[\s>]|<body[\s>]/i.test(html) || !fragment?.matches(selector) || parsed.body.children.length !== 1) throw new Error('Expected a writing fragment, received a full page or invalid response');
return fragment;
};
const initialize = (options) => {
const config = { ...defaults, ...options };
const root = document.querySelector(config.rootSelector);
if (!root) {
return null;
}
const contentHost = root.querySelector(config.contentSelector);
const statusText = root.querySelector(config.statusTextSelector);
const endpoint = root.dataset.contextUrl || config.defaultEndpoint;
const scopedProjectId = parsePositiveInt(root.dataset.scopeProjectId);
const scopedBookId = parsePositiveInt(root.dataset.scopeBookId);
let currentFragment = contentHost?.querySelector(config.fragmentSelector);
let currentSceneId = parsePositiveInt(currentFragment?.dataset.sceneId);
let currentChapterId = parsePositiveInt(currentFragment?.dataset.chapterId);
let loadingSceneId = null;
let loadingChapterId = null;
let requestGeneration = 0;
let pendingRequest = null, navigationRequest = null;
let manualGeneration=0;
let selectedDocument = root.dataset.wordInstance && root.dataset.wordSession ? root.dataset.wordInstance + '/' + root.dataset.wordSession : '';
let nativePositionKey = '', nativeWasConnected = false, nativeLeases = [];
const viewState = new Map(), viewNodeIds=new WeakMap();let viewNodeSequence=0;
const viewIdentity=node=>{if(!viewNodeIds.has(node))viewNodeIds.set(node,++viewNodeSequence);return viewNodeIds.get(node);};
const saveView = () => {
contentHost?.querySelectorAll('[data-writing-view-state]').forEach(node => viewState.set(node.dataset.writingViewState, { value: node.value, checked: node.checked, instance:viewIdentity(node), manualPan:node.dataset.contextManualPan, left: node.scrollLeft, top: node.scrollTop, viewBox: node.getAttribute("viewBox") }));
};
const restoreView = () => {
contentHost?.querySelectorAll('[data-writing-view-state]').forEach(node => {
const state = viewState.get(node.dataset.writingViewState); if (!state||state.instance===viewIdentity(node)) return;
if (node.matches('select') && [...node.options].some(o => o.value === state.value) || node.matches('input')) node.value = state.value;
if (node.matches('input[type=checkbox]')) node.checked = state.checked;
node.scrollLeft = state.left; node.scrollTop = state.top;
if(state.viewBox&&node.tagName.toLowerCase()==="svg"){node.setAttribute("viewBox",state.viewBox);if(state.manualPan==='true')node.dataset.contextManualPan='true';else delete node.dataset.contextManualPan;}
state.instance=viewIdentity(node);
});
root.dispatchEvent(new CustomEvent('writing-fragment-ready'));
};
root.addEventListener("writing-component-loaded",restoreView);
root.addEventListener("writing-view-before-refresh",saveView);
const setStatus = (value) => {
if (statusText && value && statusText.textContent!==value) {
statusText.textContent = value;
}
};
const setEmptyState = (title, message) => {
const empty = contentHost?.querySelector(".writing-context-empty");
const heading = empty?.querySelector("h2");
const copy = empty?.querySelector("p:last-child");
if (heading && title) {
heading.textContent = title;
}
if (copy && message) {
copy.textContent = message;
}
};
const noCurrentSceneMessage = () => {
const bits = [];
if (scopedProjectId) bits.push(`project ${scopedProjectId}`);
if (scopedBookId) bits.push(`book ${scopedBookId}`);
const scope = bits.length ? ` for ${bits.join(", ")}` : "";
return `No current Word scene has been received${scope}. Reopen this screen from Word Companion after the manuscript scene is detected, or choose a scene manually.`;
};
const registerWorkspaceRole = () => {
if (root.dataset.followMode === "snapshot") return;
const role = config.source === "WritingContext"
? window.PlotDirectorWritingWorkspace?.roles?.context
: config.source === "WritingIntent"
? window.PlotDirectorWritingWorkspace?.roles?.intent
: null;
if (!role || !window.PlotDirectorWritingWorkspace?.registerWindow) {
return;
}
const fragment = contentHost?.querySelector(config.fragmentSelector);
void window.PlotDirectorWritingWorkspace.registerWindow({
projectID: fragment?.dataset.projectId || root.dataset.scopeProjectId,
bookID: fragment?.dataset.bookId || root.dataset.scopeBookId,
writingRole: role,
displayLabel: config.source === "WritingContext" ? "Writing Context" : "Writing Intent"
}).catch(() => null);
};
const storyPositionFromWorkspaceStatus = (status) => {
const position = status?.currentStoryPosition || status?.CurrentStoryPosition;
if (!position) {
return null;
}
return window.PlotDirectorStoryPosition?.normalise(position, "WordCompanion") || position;
};
const readStoredTab = () => {
try {
return localStorage.getItem(config.storageKey) || config.defaultTab;
} catch {
return config.defaultTab;
}
};
let selectedTab=readStoredTab();
const activeTab = () => {
const active = contentHost?.querySelector(`${config.tabSelector}.active`)?.dataset[config.tabDataKey];
return active || readStoredTab();
};
const activateTab = (tabName) => {
const requested = tabName || config.defaultTab;
const nextTab=[...contentHost.querySelectorAll(config.tabSelector)].some(button=>button.dataset[config.tabDataKey]===requested)?requested:config.defaultTab;
selectedTab=nextTab;
contentHost?.querySelectorAll(config.tabSelector).forEach((button) => {
const active = button.dataset[config.tabDataKey] === nextTab;
button.classList.toggle("active", active);
button.setAttribute("aria-selected", String(active));
button.setAttribute("role","tab");button.tabIndex=active?0:-1;
});
contentHost?.querySelectorAll(config.panelSelector).forEach((panel) => {
const active = panel.dataset[config.panelDataKey] === nextTab;
panel.classList.toggle("active", active);
panel.hidden = !active;
});
try {
localStorage.setItem(config.storageKey, nextTab);
root.dispatchEvent(new CustomEvent("writing-view-activated"));
} catch {
// Remembering the selected tab is a convenience only.
}
};
const wireFragment = () => {
activateTab(selectedTab);
const fragment = contentHost?.querySelector(config.fragmentSelector);
const fragmentStatus = fragment?.dataset.followStatus;
if (fragmentStatus) {
setStatus(root.dataset.followMode === "snapshot" ? "Saved PlotDirector snapshot — manual selection" : fragmentStatus);
}
registerWorkspaceRole();
const fragmentSceneId = parsePositiveInt(fragment?.dataset.sceneId);
if (fragmentSceneId) {
currentSceneId = fragmentSceneId;
}
const fragmentChapterId = parsePositiveInt(fragment?.dataset.chapterId);
if (fragmentChapterId) {
currentChapterId = fragmentChapterId;
}
contentHost?.querySelectorAll(config.tabSelector).forEach((button) => {
button.addEventListener("click", () => activateTab(button.dataset[config.tabDataKey]));
button.closest('nav')?.setAttribute('role','tablist');
button.addEventListener('keydown',event=>{
if(!['ArrowLeft','ArrowRight','Home','End'].includes(event.key))return;
event.preventDefault();const tabs=[...contentHost.querySelectorAll(config.tabSelector)],at=tabs.indexOf(button);
const index=event.key==='Home'?0:event.key==='End'?tabs.length-1:(at+(event.key==='ArrowRight'?1:-1)+tabs.length)%tabs.length;
activateTab(tabs[index].dataset[config.tabDataKey]);tabs[index].focus({preventScroll:true});
});
});
const navigate = async (id, userInitiated=false) => {
const sceneId = parsePositiveInt(id); if (!sceneId) return;
const manual=++manualGeneration;navigationRequest?.abort();
const fragment = contentHost?.querySelector(config.fragmentSelector);
const position = { source: config.source, projectId: parsePositiveInt(fragment?.dataset.projectId || root.dataset.scopeProjectId), bookId: parsePositiveInt(fragment?.dataset.bookId || root.dataset.scopeBookId), sceneId };
await loadPosition(position, true);
if (manual!==manualGeneration || currentSceneId !== sceneId || root.dataset.followMode === 'snapshot' || !userInitiated) return;
const token = root.querySelector('[name=__RequestVerificationToken]')?.value;
if (!token) return;
const body = new URLSearchParams({bookId: position.bookId, sceneId, navigationId:crypto.randomUUID(), __RequestVerificationToken: token});
if (selectedDocument) { const [instanceId, sessionId] = selectedDocument.split('/'); body.set('instanceId', instanceId); body.set('sessionId', sessionId); }
const beforeNavigation=nativePositionKey;
try {
navigationRequest=new AbortController();
const response = await fetch('/Writing/Context/Navigate', { method: 'POST', body, signal:navigationRequest.signal, headers: {'X-Requested-With':'XMLHttpRequest'} });
const result = await response.json();
if (manual===manualGeneration&&currentSceneId === sceneId&&nativePositionKey===beforeNavigation) setStatus(result.message || 'Saved scene selected; Word navigation unavailable.');
} catch (error) { if (manual===manualGeneration&&error?.name!=='AbortError'&&currentSceneId === sceneId) setStatus('Saved scene selected. Word navigation is unavailable.'); }
};
contentHost?.querySelector(config.selectSelector)?.addEventListener('change', event => void navigate(event.target.value,event.isTrusted));
contentHost?.querySelectorAll('[data-writing-scene-step]').forEach(button => button.addEventListener('click', event => void navigate(button.dataset.writingSceneStep,event.isTrusted)));
root.navigateExplicitScene=navigate;
contentHost?.querySelector("[data-writing-intent-chapter-select]")?.addEventListener("change", (event) => {
const chapterId = parsePositiveInt(event.target.value);
if (!chapterId) {
return;
}
const fragment = contentHost?.querySelector(config.fragmentSelector);
void loadPosition({
source: config.source,
projectId: parsePositiveInt(fragment?.dataset.projectId),
bookId: parsePositiveInt(fragment?.dataset.bookId),
chapterId
});
});
};
const inScope = (position) => {
if (scopedProjectId && position.projectId !== scopedProjectId) {
return false;
}
if (scopedBookId && position.bookId && position.bookId !== scopedBookId) {
return false;
}
return true;
};
const loadPosition = async (position, userInitiated=false) => {
const hasScene = Number.isInteger(position?.sceneId) && position.sceneId > 0;
const hasChapter = Number.isInteger(position?.chapterId) && position.chapterId > 0;
if (!position || !inScope(position) || (!hasScene && (!config.allowChapterOnly || !hasChapter))) {
return;
}
if (hasScene && position.sceneId === currentSceneId && (loadingChapterId !== null || (loadingSceneId !== null && position.sceneId !== loadingSceneId))) {
++requestGeneration; pendingRequest?.abort(); pendingRequest = null;
loadingSceneId = null; loadingChapterId = null; setStatus(root.dataset.followMode === "snapshot" ? "Saved PlotDirector snapshot — manual selection" : "Following Word"); return;
}
if (!hasScene && currentSceneId === null && position.chapterId === currentChapterId && (loadingChapterId !== null || loadingSceneId !== null)) {
++requestGeneration; pendingRequest?.abort(); pendingRequest = null;
loadingSceneId = null; loadingChapterId = null; setStatus(root.dataset.followMode === "snapshot" ? "Saved PlotDirector snapshot — manual selection" : "Following Word"); return;
}
if (hasScene && (position.sceneId === currentSceneId || position.sceneId === loadingSceneId)) {
return;
}
if (!hasScene && ((currentSceneId === null && position.chapterId === currentChapterId) || position.chapterId === loadingChapterId)) {
return;
}
const generation = ++requestGeneration;
pendingRequest?.abort();
const controller = new AbortController();
pendingRequest = controller;
loadingSceneId = hasScene ? position.sceneId : null;
loadingChapterId = !hasScene ? position.chapterId : null;
setStatus(config.updatingStatus);
const url = new URL(endpoint, window.location.origin);
if (position.projectId) url.searchParams.set("projectId", position.projectId);
if (position.bookId) url.searchParams.set("bookId", position.bookId);
if (position.chapterId) url.searchParams.set("chapterId", position.chapterId);
if (hasScene) url.searchParams.set("sceneId", position.sceneId);
try {
console.info(`[${config.source}] Loading writing position.`, position);
const response = await fetch(url, { signal: controller.signal, headers: { "X-Requested-With": "XMLHttpRequest" } });
if (!response.ok || response.redirected) {
throw new Error(`${config.source} request failed: ${response.status}`);
}
const html = await response.text();
if (generation !== requestGeneration) return;
// Only the expected server-rendered fragment may enter this workspace. Never embed a shell/login/Timeline page.
const fragment = fragmentFromHtml(html, config.fragmentSelector);
const tab = activeTab(), scroll = {x: window.scrollX, y: window.scrollY};
const focused=userInitiated&&document.hasFocus()&&contentHost.contains(document.activeElement)?document.activeElement:null;
const focusedTab=focused?.dataset[config.tabDataKey],focusedSelect=focused?.matches(config.selectSelector);
saveView();
for(const panel of contentHost.querySelectorAll('[data-writing-stable-panel]')) {
const replacement=[...fragment.querySelectorAll('[data-writing-stable-panel]')].find(p=>p.dataset.writingStablePanel===panel.dataset.writingStablePanel);
if(replacement){
if(panel.dataset.writingComponent==='map'&&panel.dataset.componentUrl!==replacement.dataset.componentUrl){panel.dataset.componentUrl=replacement.dataset.componentUrl;delete panel.dataset.loaded;}
replacement.replaceWith(panel);
}
}
contentHost.replaceChildren(fragment);
currentFragment = fragment;
currentSceneId = hasScene ? position.sceneId : null;
if (hasChapter) {
currentChapterId = position.chapterId;
}
wireFragment();
activateTab(tab);
if(root.dataset.followMode!=="snapshot")setStatus(position.source==="WordCompanion"?"Following Word":"Saved scene");
restoreView();
if(focused?.isConnected)focused.focus({preventScroll:true});
else if(focusedTab)[...contentHost.querySelectorAll(config.tabSelector)].find(button=>button.dataset[config.tabDataKey]===focusedTab)?.focus({preventScroll:true});
else if(focusedSelect)contentHost.querySelector(config.selectSelector)?.focus({preventScroll:true});
window.scrollTo(scroll.x, scroll.y);
} catch (error) {
if (generation !== requestGeneration || error?.name === "AbortError") return;
console.warn(`${config.source} could not update.`, error);
setStatus("Context unavailable");
setEmptyState(
config.source === "WritingIntent" ? "No writing intent is available" : "No Story Intelligence context is available",
`PlotDirector could not load ${config.source === "WritingIntent" ? "intent" : "context"} for the selected Word position. Check that the scene belongs to this project/book and that import data exists.`
);
} finally {
if (generation === requestGeneration) {
loadingSceneId = null;
loadingChapterId = null;
pendingRequest = null;
}
}
};
const followNative = (leases) => {
nativeLeases = leases;
if(leases.reconnected)nativeWasConnected=false;
const available = leases.filter(l => Date.parse(l.expires) > Date.now() && l.wordAvailable && (!scopedBookId || Number(l.bookId) === scopedBookId));
if(!available.length&&document.querySelector('[data-word-companion-presence]')?.dataset.officeConnected==='true'){nativeWasConnected=false;nativePositionKey='';return;}
const active = available.filter(l => l.active);
const chosen = selectedDocument ? available.filter(l => l.instanceId + '/' + l.sessionId === selectedDocument) : active.length === 1 ? active : available;
const lease = chosen.length === 1 ? chosen[0] : null;
if (!lease) { nativeWasConnected = false; nativePositionKey = ''; setStatus(available.length > 1 && !selectedDocument ? 'Choose a Word document using the connection indicator' : selectedDocument ? 'Selected Word document is disconnected · saved scene remains available' : leases.some(l=>l.wordAvailable) ? 'Saved scene · no live Word position for this book' : 'Word disconnected · saved scene remains available'); return; }
const key = [lease.instanceId, lease.sessionId, lease.chapterId, lease.sceneId, lease.wordSaved].join(':');
if ((!lease.sceneId && !(config.allowChapterOnly && lease.chapterId)) || lease.wordSaved === false) { nativeWasConnected = true; nativePositionKey = key; setStatus(lease.positionMessage?lease.positionMessage+' · saved scene remains available':lease.wordSaved===false?'Save Word, then synchronise to refresh its scene mapping · saved scene remains available':'Word scene mapping is unavailable · synchronise from Word; saved scene remains available'); return; }
if (!nativeWasConnected || key !== nativePositionKey || (!pendingRequest && Number(lease.sceneId)!==currentSceneId)) {
nativeWasConnected = true; nativePositionKey = key;
void loadPosition({source:'WordCompanion',projectId:scopedProjectId || parsePositiveInt(currentFragment?.dataset.projectId),bookId:Number(lease.bookId),chapterId:Number(lease.chapterId),sceneId:lease.sceneId?Number(lease.sceneId):null});
setStatus('Following Word');
}
};
if (root.dataset.followMode !== 'snapshot') {
window.addEventListener('native-companion-presence', event => followNative(event.detail || []));
window.addEventListener('plotdirector:word-return-to-current',()=>{nativePositionKey='';nativeWasConnected=false;followNative(nativeLeases);});
window.addEventListener('plotdirector:word-document-selected', event => { selectedDocument = event.detail || ''; nativePositionKey = ''; nativeWasConnected = false; followNative(nativeLeases); });
}
if (root.dataset.followMode === "snapshot") { wireFragment(); setStatus("Saved PlotDirector snapshot — manual selection"); return { loadPosition, activateTab }; }
document.addEventListener(window.PlotDirectorStoryPosition?.eventName || "plotdirector:story-position-changed", (event) => {
if(selectedDocument||nativeLeases.some(l=>l.wordAvailable&&Date.parse(l.expires)>Date.now()&&(!scopedBookId||Number(l.bookId)===scopedBookId)))return;
void loadPosition(event.detail);
});
if (typeof window.PlotDirectorWritingWorkspace?.watchWorkspace === 'function') {
const acceptWorkspace = async status => {
if(selectedDocument||nativeLeases.some(l=>l.wordAvailable&&Date.parse(l.expires)>Date.now()&&(!scopedBookId||Number(l.bookId)===scopedBookId)))return;
const position=storyPositionFromWorkspaceStatus(status);
if(position?.sceneId || config.allowChapterOnly&&position?.chapterId)await loadPosition(position);
};
void window.PlotDirectorWritingWorkspace.watchWorkspace({projectID:scopedProjectId,bookID:scopedBookId}).then(acceptWorkspace).catch(()=>{if(!nativeWasConnected)setStatus(config.disconnectedStatus);});
document.addEventListener('plotdirector:writing-workspace-reconnected',event=>void acceptWorkspace(event.detail));
} else if (window.signalR) {
const connection = new signalR.HubConnectionBuilder()
.withUrl("/hubs/word-companion-follow")
.withAutomaticReconnect()
.build();
connection.on("storyPositionChanged", (payload) => {
window.PlotDirectorStoryPosition?.publishChanged(payload, payload?.source || payload?.Source || "WordCompanion");
});
connection.start()
.then(async () => {
const status = await connection.invoke("WatchWritingWorkspace", {
projectID: scopedProjectId,
bookID: scopedBookId
}).catch(() => null);
const position = storyPositionFromWorkspaceStatus(status);
if (position?.sceneId || (config.allowChapterOnly && position?.chapterId)) {
await loadPosition(position);
}
if (!currentSceneId && !(config.allowChapterOnly && currentChapterId)) {
setStatus("No current Word scene received");
setEmptyState("No current Word scene received", noCurrentSceneMessage());
}
})
.catch((error) => {
if(nativeWasConnected)return;
console.warn(`${config.source} follow connection unavailable.`, error);
setStatus(config.disconnectedStatus);
setEmptyState(
"Word Companion connection unavailable",
`This ${config.source === "WritingIntent" ? "Intent" : "Context"} screen could not connect to the Word Companion session. Reopen it from Word Companion, or use the manual scene controls.`
);
});
} else {
setStatus(config.disconnectedStatus);
setEmptyState(
"Word Companion connection unavailable",
"SignalR did not load for this screen, so live Word updates are unavailable. Use a URL with project/book/scene IDs or the manual scene controls."
);
}
root.addEventListener('click',event=>{const button=event.target.closest('[data-context-go-scene]');if(button&&event.isTrusted)void root.navigateExplicitScene?.(button.dataset.contextGoScene,true);});
wireFragment();
restoreView();
const observed=document.querySelector('#native-companion-status')?.nativePresence;if(observed)followNative(observed);
return { loadPosition, activateTab };
};
window.PlotDirectorWritingFollow = { initialize, fragmentFromHtml };
})();