61 lines
8.5 KiB
JavaScript
61 lines
8.5 KiB
JavaScript
// One accepted-target/layout pipeline for initial load, focus events and explicit Go.
|
|
(() => {
|
|
const columns=document.querySelector('[data-review-columns]');if(!columns)return;
|
|
const notice=document.createElement('p');notice.className='writer3-caption';notice.dataset.reviewFocusNotice='true';notice.hidden=true;columns.before(notice);
|
|
let request=null,generation=0;
|
|
const canChange=()=>document.querySelector('[data-writer-review]')?.canChangeNarrative?.()!==false&&!columns.querySelector('[data-authoring-form]:not([hidden]),[data-busy="true"]');
|
|
const current=()=>window.PlotDirectorNarrativeFocus?.state;
|
|
const same=(a,b)=>a&&b&&a.projectID===b.projectID&&a.bookID===b.bookID&&a.chapterID===b.chapterID&&a.sceneID===b.sceneID&&a.version===b.version;
|
|
const frame=()=>new Promise(resolve=>requestAnimationFrame(resolve));
|
|
function offer(text){notice.hidden=false;notice.replaceChildren(document.createTextNode(text+' '));const button=document.createElement('button');button.type='button';button.className='btn btn-sm btn-link';button.textContent='Show current focus';button.addEventListener('click',()=>void apply(current()));notice.append(button);}
|
|
async function apply(focus){
|
|
if(!focus?.chapterID)return;
|
|
const mine=++generation;request?.abort();
|
|
let reader=document.querySelector('.manuscript-reader');if(focus.bookID!==Number(reader?.dataset.bookId))return;
|
|
if(!canChange()){offer('Save or cancel open editors, clear any text selection and close dialogs before changing the displayed chapter or scene. Your original references are retained.');return;}
|
|
try{
|
|
if(focus.chapterID!==Number(reader.dataset.chapterId)){
|
|
request=new AbortController();const url=new URL('/Writer/ReviewContent',location.origin);url.search=new URLSearchParams({projectId:focus.projectID,bookId:focus.bookID,version:focus.version,focus:reader.dataset.focus==='true',reading:reader.dataset.reading==='true',chapterId:focus.chapterID,localFocus:window.PlotDirectorSharedFocus?.held===true});
|
|
const response=await fetch(url,{cache:'no-store',signal:request.signal});if(!response.ok||response.redirected)throw Error('The chapter could not be refreshed.');
|
|
const doc=new DOMParser().parseFromString(await response.text(),'text/html'),fresh=doc.querySelector('[data-review-columns]'),nextReader=fresh?.querySelector('.manuscript-reader');
|
|
if(!nextReader||Number(nextReader.dataset.bookId)!==focus.bookID||Number(nextReader.dataset.chapterId)!==focus.chapterID)throw Error('The requested chapter is unavailable.');
|
|
if(mine!==generation||!same(focus,current()))return;
|
|
if(!canChange()){offer('Current focus changed. Your open editors retain their original target.');return;}
|
|
const sections=['#review-chapter-notes','.writer21-manuscript','#review-scene-notes'].map(selector=>({old:columns.querySelector(selector),next:fresh.querySelector(selector)}));if(sections.some(p=>!p.old||!p.next))throw Error('The chapter could not be refreshed.');
|
|
const oldWord=columns.querySelector('[data-writer-word]'),newWord=fresh.querySelector('[data-writer-word]');if(oldWord&&newWord)newWord.replaceWith(oldWord);
|
|
const work=[...columns.querySelectorAll('[data-writer-work]')],newWork=[...fresh.querySelectorAll('[data-writer-work]')];work.forEach((node,i)=>newWork[i]?.replaceWith(node));
|
|
const filters=[...columns.querySelectorAll('[data-annotation-filter]')].map(n=>[n.dataset.annotationFilter,n.value]),paused=reader.querySelector('#reader-pause')?.checked===true;
|
|
document.querySelector('[data-writer-review]')?.reviewDispose?.();reader.readerCleanup?.();for(const {old,next}of sections)old.replaceChildren(...next.childNodes);
|
|
const pause=columns.querySelector('#reader-pause');if(pause)pause.checked=paused;
|
|
window.PlotDirectorManuscriptReader?.mount();window.PlotDirectorReview?.mount();window.dispatchEvent(new CustomEvent('review:narrative-applied',{detail:{...focus,sceneID:null}}));
|
|
// Context loading below completes before positioning; no old reading-anchor callback may win.
|
|
reader=columns.querySelector('.manuscript-reader');reader._focusFilters=filters;
|
|
}
|
|
const target=reader.readerResolveFocus?.(focus);if(!target)throw Error('Current Focus is unavailable in the displayed accepted chapter.');
|
|
if(window.PlotDirectorSharedFocus?.held&&(focus.paragraphID||focus.sceneID)&&!target.precise){notice.hidden=false;notice.textContent='The held reference no longer has a precise accepted passage. Your current view is retained. Select another local reference or Release Hold.';return;}
|
|
await document.querySelector('[data-writer-review]')?.selectNarrativeParagraph?.(target.paragraph?.dataset.paragraphId||null);
|
|
if(mine!==generation||!same(focus,current())||!canChange())return;
|
|
for(const [name,value]of reader._focusFilters||[]){const select=columns.querySelector(`[data-annotation-filter="${name}"]`);if(select){select.value=value;select.dispatchEvent(new Event('change',{bubbles:true}));}}delete reader._focusFilters;
|
|
const resolved=reader.readerResolveFocus(focus);
|
|
notice.hidden=!(focus.sceneID||focus.paragraphID)||resolved.precise;
|
|
if(!notice.hidden)notice.textContent=(focus.paragraphID?'The requested paragraph is unavailable in this accepted chapter. The mapped scene or chapter is shown. ':'')+'Current Focus: '+focus.label+'. Precise scene positioning is unavailable: no accepted paragraph is mapped to this scene. Chapter context is shown; select an accepted passage for verified scene context.';
|
|
window.dispatchEvent(new Event('plotdirector:context-changed'));
|
|
await frame();await frame();
|
|
if(mine!==generation||!same(focus,current())||!reader.isConnected||!canChange())return;
|
|
reader.readerLocateFocus(focus);
|
|
reader.dispatchEvent(new CustomEvent('reader:focus-positioned',{bubbles:true,detail:{chapterID:focus.chapterID,sceneID:focus.sceneID,paragraphID:reader.dataset.focusParagraph||null,version:reader.dataset.version}}));
|
|
}catch(error){if(error.name!=='AbortError'&&mine===generation)offer((error.message||'Current Focus could not be displayed.')+' Your content and edits are retained.');}
|
|
}
|
|
window.addEventListener('plotdirector:narrative-focus-changed',event=>{if(window.PlotDirectorSharedFocus)void apply(event.detail);});
|
|
window.PlotDirectorFocusWorkspace.register({canGo:focus=>focus.bookID===Number(document.querySelector('.manuscript-reader')?.dataset.bookId)&&!!focus.chapterID,beforeChange:()=>canChange(),unavailable:'Choose a chapter in this Review book to display Current Focus',go:apply});
|
|
document.addEventListener('reader:updated',()=>void apply(current()));
|
|
if(current()&&window.PlotDirectorSharedFocus)void apply(current());
|
|
window.addEventListener('pagehide',()=>{++generation;request?.abort();});
|
|
function selectParagraph(p){const r=p.closest('.manuscript-reader');if(!r||document.querySelector('[data-writer-review]')?.canChangeNarrative?.()===false)return;notice.hidden=true;for(const item of r.querySelectorAll('[data-paragraph-id]'))item.tabIndex=item===p?0:-1;void window.PlotDirectorSharedFocus?.navigate({projectID:current()?.projectID,bookID:Number(r.dataset.bookId),chapterID:Number(r.dataset.chapterId),sceneID:Number(p.dataset.sceneId)||null,paragraphID:p.dataset.paragraphId,localSelection:true});}
|
|
document.addEventListener('click',event=>{if(!event.isTrusted)return;const p=event.target.closest('.manuscript-reader [data-paragraph-id]');if(p)selectParagraph(p);const link=event.target.closest('.reader-chapter-navigation a[href]');if(link){event.preventDefault();const chapter=Number(new URL(link.href).searchParams.get('chapterId'));if(chapter)void window.PlotDirectorSharedFocus?.navigate({chapterID:chapter});}});
|
|
document.addEventListener('submit',event=>{if(event.defaultPrevented)return;const form=event.target;if(form.closest('.reader-chapter-navigation')){event.preventDefault();const chapter=Number(new FormData(form).get('chapterId'));if(chapter)void window.PlotDirectorSharedFocus?.navigate({chapterID:chapter});}});
|
|
document.addEventListener('keydown',event=>{if(!event.target.matches('.manuscript-reader [data-paragraph-id]')||!['ArrowUp','ArrowDown','Home','End'].includes(event.key))return;event.preventDefault();const paragraphs=[...event.target.closest('.manuscript-reader').querySelectorAll('[data-paragraph-id]')],index=paragraphs.indexOf(event.target),next=event.key==='Home'?0:event.key==='End'?paragraphs.length-1:Math.max(0,Math.min(paragraphs.length-1,index+(event.key==='ArrowDown'?1:-1)));const p=paragraphs[next];p.focus({preventScroll:true});p.scrollIntoView({block:'nearest'});p.click();selectParagraph(p);});
|
|
document.querySelector('.manuscript-reader [data-paragraph-id]')?.setAttribute('tabindex','0');
|
|
|
|
})();
|