function initialiseManuscriptReader() { const root = document.querySelector('.manuscript-reader'); if (!root) return; root.readerCleanup?.(); const listeners = new AbortController(); const on = (node, name, handler) => node.addEventListener(name, handler, { signal: listeners.signal }); const focus = root.querySelector('#reader-focus'); const content = root.querySelector('#reader-content'); const message = root.querySelector('#reader-update-status'); let dismissUpdateError, updateError = false; const notifyUpdateError = () => { if (!updateError) { updateError = true; dismissUpdateError = window.PlotDirector?.toast?.error(message.textContent); } }; const clearUpdateError = () => { updateError = false; dismissUpdateError?.(); }; const apply = root.querySelector('#reader-apply-update'); const pause = root.querySelector('#reader-pause'); const loading = root.querySelector('#reader-loading'); const bookId = root.dataset.bookId; const chapterId = root.dataset.chapterId; let revision = root.dataset.revision; let displayedVersion = root.dataset.version; let observedVersion = displayedVersion; let timer, request, busy = false, stopped = false, blocked = false, resumePending = false; const interval = 12000; const subdued=new Map(); const setFocus = enabled => { const changing=root.dataset.focus!==String(enabled), viewport=root.dataset.focus==='true'?root.getBoundingClientRect().top:Math.max(0,document.querySelector('.pd-application-header')?.getBoundingClientRect().bottom||0); const visible=changing?[...content.querySelectorAll('[data-paragraph-id]')].find(n=>n.getBoundingClientRect().bottom>viewport):null; const offset=visible?visible.getBoundingClientRect().top-viewport:0; if(enabled){for(const node of document.querySelectorAll('.pd-application-header,.writer3-header,.writer3-reference,.pd-investigation,.pd-investigation-splitter,.plotline-help-drawer,.plotline-help-splitter')){if(!subdued.has(node))subdued.set(node,node.inert);node.inert=true;}} else{for(const [node,previous] of subdued)node.inert=previous;subdued.clear();} root.dataset.focus = String(enabled); const exit=root.querySelector('[data-reader-exit-focus]');if(exit)exit.hidden=true; // Link remains a no-script exit; the live toolbar has its own focus toggle. document.body.classList.toggle('reader-focused', enabled); focus.setAttribute('aria-pressed', String(enabled)); focus.textContent = enabled ? 'Exit focus reading' : 'Focus reading'; root.querySelector('input[name="focus"]').value = String(enabled); root.querySelectorAll('a:not([data-reader-exit-focus])').forEach(link => { const url = new URL(link.href); if (url.origin === location.origin && url.pathname.replace(/\/$/, '').toLowerCase() === location.pathname.replace(/\/$/, '').toLowerCase()) { if (enabled) url.searchParams.set('focus', 'true'); else url.searchParams.delete('focus'); link.href = url.href; } }); // Keep the current Reader URL consistent for reload/back without persisting focus outside it. const url = new URL(location.href); if (enabled) url.searchParams.set('focus', 'true'); else url.searchParams.delete('focus'); history.replaceState(history.state, '', url);root.dispatchEvent(new Event('reader:focus-mode',{bubbles:true})); if(visible)requestAnimationFrame(()=>{const top=enabled?root.getBoundingClientRect().top:Math.max(0,document.querySelector('.pd-application-header')?.getBoundingClientRect().bottom||0),delta=visible.getBoundingClientRect().top-top-offset;if(enabled)root.scrollBy({top:delta,behavior:'instant'});else window.scrollBy({top:delta,behavior:'instant'});}); }; focus.hidden = false; setFocus(root.dataset.focus === 'true'); on(focus, 'click', () => setFocus(root.dataset.focus !== 'true')); on(document, 'keydown', event => { if (event.key === 'Escape') setFocus(false); }); on(root.querySelector('.reader-controls form'), 'submit', () => { loading.hidden = false; stop(); }); on(root, 'click', event => { if (event.target.closest('a') && !event.ctrlKey && !event.metaKey && !event.shiftKey && event.button === 0) stop(); }); const audio=root.querySelector('#reader-audio-dialog');if(audio){on(root.querySelector('#reader-audio'),'click',()=>audio.showModal());on(audio.querySelector('[data-reader-audio-close]'),'click',()=>audio.close());} const pauseToggle=root.querySelector('#reader-pause-toggle');if(pauseToggle)on(pauseToggle,'click',()=>{pause.checked=!pause.checked;pause.dispatchEvent(new Event('change'));}); const hasSelection = () => { const selection = window.getSelection(); // A selection anywhere on the page is a reason to defer; extensions may select outside prose. return selection && !selection.isCollapsed; }; const pending = () => observedVersion !== displayedVersion; const indicate = () => { apply.hidden = !pending();if(pauseToggle){pauseToggle.setAttribute('aria-pressed',String(pause.checked));pauseToggle.textContent=pause.checked?'Resume updates':'Pause updates';pauseToggle.title=pause.checked?'Resume automatic manuscript updates':'Pause automatic manuscript updates';} if (!pending()) message.textContent = pause.checked ? "Automatic updates paused." : "Checking for accepted chapter changes automatically."; else message.textContent = hasSelection() ? 'Updated chapter available. It will appear after you clear the text selection.' : pause.checked ? 'Updated chapter available. Automatic updates are paused.' : 'Updated chapter available.'; }; const scrollPanel=root.closest('[data-writer-destination=Review]') ? null : root.closest('.writer3-main'); const viewportTop = () => root.dataset.focus === 'true' ? root.getBoundingClientRect().top : scrollPanel?.getBoundingClientRect().top||0; const rememberPosition = () => { const top = viewportTop(); const rows = [...content.querySelectorAll('[data-paragraph-id]')]; const index = rows.findIndex(row => row.getBoundingClientRect().bottom > top); if (index < 0) return null; // Keep neighbours in case the currently visible paragraph is deleted by the accepted update. return rows.slice(Math.max(0, index - 2), index + 3).map(row => ({ id: row.dataset.paragraphId, text: row.textContent, offset: row.getBoundingClientRect().top - top, primary: row === rows[index] })).sort((a, b) => Number(b.primary) - Number(a.primary)); }; const restorePosition = anchors => { if (!anchors) return; const rows = [...content.querySelectorAll('[data-paragraph-id]')]; for (const anchor of anchors) { const row = rows.find(p => p.dataset.paragraphId === anchor.id) || rows.find(p => p.textContent === anchor.text); if (!row) continue; const delta = row.getBoundingClientRect().top - viewportTop() - anchor.offset; if (root.dataset.focus === 'true') root.scrollBy({ top: delta, behavior: 'instant' }); else if(scrollPanel)scrollPanel.scrollBy({top:delta,behavior:'instant'});else window.scrollBy({ top: delta, behavior: 'instant' }); break; } }; let narrativePosition=0; root.readerPreserveView=()=>{const mine=narrativePosition,anchors=rememberPosition();return ()=>{if(root.isConnected&&mine===narrativePosition)restorePosition(anchors);};}; root.readerResolveFocus=target=>{ if(Number(bookId)!==target.bookID||Number(chapterId)!==target.chapterID)return null; const exact=target.paragraphID?content.querySelector(`[data-paragraph-id="${CSS.escape(target.paragraphID)}"]`):null; const paragraph=exact||(target.sceneID?[...content.querySelectorAll('[data-paragraph-id][data-scene-id]')].find(n=>Number(n.dataset.sceneId)===target.sceneID):null); return {paragraph,precise:target.paragraphID?!!exact:!!paragraph,version:root.dataset.version,revision:root.dataset.revision}; }; root.readerLocateFocus=target=>{ const resolved=root.readerResolveFocus(target);if(!resolved)return null; ++narrativePosition; const row=resolved.paragraph||content.querySelector('[data-paragraph-id],h2,.reader-empty'); root.dataset.focusParagraph=resolved.paragraph?.dataset.paragraphId||''; if(!row)return resolved; const focused=root.dataset.focus==='true',container=focused?root:scrollPanel; const header=document.querySelector('.pd-application-header'),sticky=header&&['sticky','fixed'].includes(getComputedStyle(header).position); let top=container?container.getBoundingClientRect().top:sticky?Math.max(0,header.getBoundingClientRect().bottom):0; if(focused)top+=root.querySelector('.reader-controls')?.getBoundingClientRect().height||0; else {const columns=root.closest('[data-review-columns]');if(columns?.dataset.compact==='true')top+=Math.max(...[...columns.querySelectorAll(':scope>.writer21-notes')].map(n=>n.getBoundingClientRect().height),0)+12;} (container||window).scrollBy({top:row.getBoundingClientRect().top-top-12,behavior:'instant'}); return resolved; }; const fetchJson = async url => { request = new AbortController(); const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store', signal: request.signal }); if (response.redirected || [401, 403, 404].includes(response.status)) { blocked = true; throw new Error('access'); } if (!response.ok) throw new Error('network'); return response.json(); }; const urlFor = endpoint => { const url = new URL(endpoint, location.href); url.searchParams.set('bookId', bookId); url.searchParams.set('chapterId', chapterId); return url; }; const render = data => { const fragment = document.createDocumentFragment(); const article = document.createElement(data.paragraphs.length ? 'article' : 'section'); article.className = data.paragraphs.length ? 'reader-page' : 'reader-empty'; if (data.paragraphs.length) { article.setAttribute('aria-label', 'Chapter manuscript'); // Preserve the existing canonical chapter identification and title when no captured heading exists. const oldHeader = content.querySelector('.reader-page header'); const header = oldHeader ? oldHeader.cloneNode(true) : document.createElement('header'); if (!oldHeader) { const label = document.createElement('p'); label.className = 'eyebrow'; label.textContent = 'Chapter ' + root.dataset.chapterNumber; header.append(label); } header.querySelector('h2')?.remove(); if (!data.paragraphs[0].isHeading) { const title = document.createElement('h2'); title.textContent = data.title; header.append(title); } article.append(header); data.paragraphs.forEach((paragraph, index) => { const node = document.createElement(paragraph.isHeading ? index === 0 ? 'h2' : 'h3' : 'p'); node.className = 'reader-paragraph' + (paragraph.isHeading ? ' reader-heading' : ''); node.dataset.paragraphId = paragraph.id;node.dataset.sceneId=paragraph.sceneId||''; node.textContent = paragraph.text; article.append(node); }); } else { article.setAttribute('role', 'status'); const title = document.createElement('h2'); title.textContent = data.title; const text = document.createElement('p'); text.textContent = 'No accepted manuscript text is available for this chapter. Save and successfully synchronise it using Word Companion.'; article.append(title, text); } fragment.append(article); return fragment; }; const timestamps = data => { const area = root.querySelector('#reader-timestamps'); const nodes = []; for (const [label, value] of [['Last successful chapter synchronisation', data.lastSuccessfulSyncUtc], ['Accepted manuscript snapshot captured', data.snapshotCapturedUtc]]) { const p = document.createElement('p'); if (value) { p.append(label + ': '); const time = document.createElement('time'); time.dateTime = value; time.textContent = new Date(value).toLocaleString('en-GB', { timeZone: 'UTC', hour12: false }) + ' UTC'; p.append(time); } else if (label.startsWith('Last')) p.textContent = 'No successful chapter synchronisation timestamp is recorded.'; else continue; nodes.push(p); } area.replaceChildren(...nodes); }; const update = async (force = false) => { if (!pending() || pause.checked || hasSelection() || stopped || document.hidden) return; const data = await fetchJson(urlFor(root.dataset.chapterUrl)); if (stopped || document.hidden || String(data.bookId) !== bookId || String(data.chapterId) !== chapterId) return; revision = data.revision; observedVersion = data.version; if (!pending()) { apply.hidden = true; message.textContent = ''; return; } if (pause.checked || hasSelection()) { indicate(); return; } const anchors = rememberPosition(); // If no surviving anchor can preserve the reading session, offer the update instead. if (!force && anchors && !anchors.some(a => data.paragraphs.some(p => p.id === a.id || p.text === a.text))) { pause.checked = true; indicate(); return; } const fragment = render(data); content.replaceChildren(fragment); timestamps(data); displayedVersion = data.version; root.dataset.version = displayedVersion; root.dataset.revision = revision; restorePosition(anchors); root.dispatchEvent(new CustomEvent('reader:updated',{bubbles:true,detail:{revision,version:displayedVersion}})); apply.hidden = true; message.textContent = 'Chapter updated.'; clearUpdateError(); if (force) window.PlotDirector?.toast?.success('Chapter updated.'); }; const schedule = () => { clearTimeout(timer); if (!stopped && !blocked && !document.hidden && chapterId) timer = setTimeout(check, interval); }; const finish = () => { busy = false; request = null; if (resumePending && !stopped && !document.hidden) { resumePending = false; void check(); } else schedule(); }; const check = async () => { if (busy || stopped || blocked || document.hidden || !chapterId) return; clearTimeout(timer); busy = true; try { const url = urlFor(root.dataset.checkUrl); url.searchParams.set('knownRevision', revision); url.searchParams.set('knownVersion', observedVersion); const data = await fetchJson(url); if (stopped || document.hidden) return; revision = data.revision; observedVersion = data.version; if (!pending()) {root.dataset.revision=revision;root.dispatchEvent(new CustomEvent('reader:metadata',{bubbles:true}));if(data.lastSuccessfulSyncUtc || data.snapshotCapturedUtc)timestamps(data);} indicate(); await update(); clearUpdateError(); } catch (error) { if (error.name !== 'AbortError' && !stopped) { message.textContent = blocked ? 'Updates stopped. Sign in again or reopen this chapter to check access.' : 'Updates temporarily unavailable. Your chapter is retained; retrying automatically.'; notifyUpdateError(); } } finally { finish(); } }; const tryUpdate = async (force = false) => { if (busy || stopped || blocked || document.hidden) return; clearTimeout(timer); busy = true; try { await update(force); } catch (error) { if (error.name !== 'AbortError') { message.textContent = 'Update could not be loaded. Retrying automatically.'; notifyUpdateError(); } } finally { finish(); } }; const stop = () => { stopped = true; clearTimeout(timer); request?.abort(); }; root.readerCleanup = () => { stop(); listeners.abort(); for(const [node,previous] of subdued)node.inert=previous;subdued.clear();document.body.classList.remove('reader-focused'); }; on(document, 'selectionchange', () => { if (pending() && !hasSelection()) void tryUpdate(); }); on(pause, 'change', () => { indicate(); if (!pause.checked) void tryUpdate(); }); on(apply, 'click', () => { pause.checked = false; window.getSelection()?.removeAllRanges(); void tryUpdate(true); }); on(document, 'visibilitychange', () => { clearTimeout(timer); if (document.hidden) request?.abort(); else if (busy) resumePending = true; else void check(); }); on(window, 'native-companion-presence', event => { if (!busy && !stopped && (event.detail?.reconnected || event.detail?.some(l => Number(l.bookId) === Number(bookId) && l.snapshotRevision != null && String(l.snapshotRevision) !== String(revision)))) void check(); }); on(window, 'online', () => { if (!busy) void check(); }); on(window, 'pagehide', stop); on(window, 'pageshow', event => { loading.hidden = true; if (event.persisted) { stopped = false; void check(); } }); indicate(); if (chapterId) { root.querySelector('.reader-live-controls').hidden = false; void check(); } } window.PlotDirectorManuscriptReader={mount:initialiseManuscriptReader};initialiseManuscriptReader();