102 lines
18 KiB
JavaScript
102 lines
18 KiB
JavaScript
// Presentation for the existing canonical focus controller and its bounded recent-focus history.
|
|
(() => {
|
|
'use strict';
|
|
const root=document.querySelector('[data-narrative-focus]');if(!root)return;
|
|
let state=JSON.parse(root.querySelector('[data-narrative-initial]').textContent),busy=false,epoch=0,refreshQueued=false,metadataFlight=null,metadataUnavailable=false;
|
|
const tree=root.querySelector('[data-focus-hierarchy]'),status=root.querySelector('[data-narrative-status]'),bookPicker=root.querySelector('[data-focus-book]'),toggle=root.querySelector('[data-focus-toggle]');
|
|
const historyLists=[...document.querySelectorAll('[data-focus-history-list]')],historyToggles=[...document.querySelectorAll('[data-focus-history-toggle]')];
|
|
const expanded=new Set();let renderedBook=null,renderedChapter=null;
|
|
const scopeKey=`pd-narrative-book:${document.body.dataset.pdUserId}:${state.projectID}`;
|
|
const notificationKey=()=>`pd-narrative-focus:${document.body.dataset.pdUserId}:${state.projectID}:${state.bookID}`;
|
|
const key=p=>`${p.chapterID||''}/${p.sceneID||''}`;
|
|
const point=p=>({chapterID:Number(p.chapterID)||null,sceneID:Number(p.sceneID)||null,...(p.sequence!=null?{sequence:p.sequence}:{})});
|
|
const recent=items=>{const seen=new Set();return items.filter(p=>p?.chapterID&&!seen.has(key(p))&&seen.add(key(p))).slice(0,20).map(point);};
|
|
const entries=()=>{const chapters=new Set(),items=[];for(const p of state.positions){if(!chapters.has(p.chapterID)){chapters.add(p.chapterID);items.push({...p,sceneID:null,label:`Ch ${p.chapterNumber}: ${p.chapterTitle}`});}if(p.sceneID)items.push(p);}return items;};
|
|
const currentLabel=()=>`${bookPicker&&state.bookID?([...bookPicker.options].find(o=>Number(o.value)===state.bookID)?.textContent||'Book')+' · ':''}${state.label||'Choose chapter or scene'}`;
|
|
function dismiss(restore=false){restore=restore===true||root.querySelector('.pd-focus-picker').contains(document.activeElement);bootstrap.Dropdown.getOrCreateInstance(toggle).hide();if(restore)toggle.focus({preventScroll:true});}
|
|
function validRecent(items){const valid=new Set(entries().map(key));return recent(items.filter(p=>valid.has(key(p))));}
|
|
function followingHistory(){const frame=window.PlotDirectorSharedFocus?.heldRecent;if(frame?.bookID!==state.bookID||frame.resumeVersion==null)return state.recent;return validRecent([...state.recent.filter(p=>p.sequence>frame.resumeVersion),...frame.items,...state.recent.filter(p=>p.sequence<=frame.resumeVersion)]);}
|
|
function heldHistory(){
|
|
const shared=window.PlotDirectorSharedFocus;if(!shared?.held)return null;
|
|
let snapshot=shared.heldRecent;
|
|
if(snapshot?.bookID!==state.bookID||snapshot.resumeVersion!=null){const local=shared.local||state,cutoff=local.version||state.version,previous=followingHistory();snapshot={bookID:state.bookID,cutoff,items:recent([local,...previous.filter(p=>p.sequence==null||p.sequence<=cutoff)])};shared.setHeldRecent(snapshot);}
|
|
return snapshot;
|
|
}
|
|
function visitHeld(p){const snapshot=heldHistory();if(snapshot){snapshot.items=recent([p,...snapshot.items]);window.PlotDirectorSharedFocus.setHeldRecent(snapshot);}}
|
|
function renderTree(){
|
|
const focused=tree.contains(document.activeElement)?{target:document.activeElement.dataset.focusTarget,expand:document.activeElement.dataset.focusExpand}:null;
|
|
if(renderedBook!==state.bookID){expanded.clear();renderedChapter=null;renderedBook=state.bookID;}
|
|
if(renderedChapter!==state.chapterID){if(state.chapterID)expanded.add(state.chapterID);renderedChapter=state.chapterID;}
|
|
tree.replaceChildren();const all=entries(),chapters=all.filter(p=>!p.sceneID);
|
|
for(const chapter of chapters){
|
|
const li=document.createElement('li'),row=document.createElement('div');row.className='pd-focus-chapter-row';
|
|
const scenes=all.filter(p=>p.chapterID===chapter.chapterID&&p.sceneID),open=expanded.has(chapter.chapterID),group=document.createElement('ul');group.className='pd-focus-scenes';group.id=`focus-scenes-${chapter.chapterID}`;group.hidden=!open;
|
|
const expand=document.createElement('button');expand.type='button';expand.className='pd-focus-expand';expand.dataset.focusExpand=chapter.chapterID;expand.textContent=open?'▾':'▸';expand.setAttribute('aria-label',`${open?'Collapse':'Expand'} chapter ${chapter.chapterNumber}`);expand.setAttribute('aria-expanded',String(open));expand.setAttribute('aria-controls',group.id);expand.disabled=!scenes.length;
|
|
row.append(expand,targetButton(chapter));li.append(row,group);for(const scene of scenes){const item=document.createElement('li');item.append(targetButton(scene));group.append(item);}tree.append(li);
|
|
}
|
|
if(!chapters.length){const empty=document.createElement('li');empty.className='pd-focus-empty';empty.textContent=metadataUnavailable?'Navigation unavailable. Reopen to retry.':'Choose a book with saved chapters.';tree.append(empty);}
|
|
if(focused){const match=[...tree.querySelectorAll('button')].find(b=>focused.target?b.dataset.focusTarget===focused.target:b.dataset.focusExpand===focused.expand);match?.focus({preventScroll:true});}
|
|
}
|
|
function targetButton(p){const button=document.createElement('button');button.type='button';button.className='dropdown-item';button.dataset.focusTarget=key(p);button.dataset.chapter=p.chapterID;button.textContent=p.sceneID?`Scene ${p.sceneNumber}: ${p.sceneTitle}`:p.label;button.disabled=busy||!state.bookID||metadataUnavailable;if(key(p)===key(state))button.setAttribute('aria-current','location');return button;}
|
|
function renderHistory(){
|
|
const snapshot=heldHistory(),all=entries(),items=validRecent(snapshot?snapshot.items:followingHistory()).filter(p=>key(p)!==key(state)).map(p=>all.find(a=>key(a)===key(p))).filter(Boolean);
|
|
for(const list of historyLists){const focused=list.contains(document.activeElement)?document.activeElement.dataset.focusHistoryTarget:null;list.replaceChildren();if(metadataUnavailable||!items.length){const li=document.createElement('li');li.className='pd-focus-empty';li.textContent=metadataUnavailable?'History unavailable. Reopen to retry.':'No previous positions in this book.';list.append(li);if(focused)list.parentElement.querySelector('[data-focus-history-toggle]').focus({preventScroll:true});continue;}for(const p of items){const li=document.createElement('li'),button=document.createElement('button');button.type='button';button.className='dropdown-item';button.dataset.focusHistoryTarget=key(p);button.textContent=p.label;button.disabled=busy;li.append(button);list.append(li);}if(focused){const button=[...list.querySelectorAll('[data-focus-history-target]')].find(b=>b.dataset.focusHistoryTarget===focused&&!b.disabled);(button||list.parentElement.querySelector('[data-focus-history-toggle]')).focus({preventScroll:true});}}
|
|
historyToggles.forEach(b=>b.disabled=busy||!state.bookID);
|
|
}
|
|
function render(){
|
|
root.querySelector('[data-focus-label]').textContent=`Current Focus: ${currentLabel()}`;root.querySelector('[data-focus-label]').title=`Current narrative focus: ${currentLabel()}`;
|
|
renderTree();renderHistory();
|
|
const scenes=state.positions.filter(p=>p.sceneID),at=scenes.findIndex(p=>p.sceneID===state.sceneID),chapterAt=state.positions.findIndex(p=>p.chapterID===state.chapterID),hasChapterScenes=scenes.some(p=>p.chapterID===state.chapterID);
|
|
document.querySelectorAll('[data-global-focus=previous],[data-global-focus=next]').forEach(b=>{const direction=b.dataset.globalFocus==='previous'?-1:1;const available=at>=0?(direction<0?at>0:at<scenes.length-1):chapterAt>=0?(hasChapterScenes||state.positions.some((p,i)=>p.sceneID&&(direction<0?i<chapterAt:i>chapterAt))):scenes.length>0;b.disabled=busy||!available;});
|
|
if(bookPicker){bookPicker.value=String(state.bookID||'');bookPicker.disabled=busy;}
|
|
}
|
|
function publish(){document.querySelector('[data-focus-workspace-status]')?.remove();render();try{if(state.bookID)localStorage.setItem(scopeKey,String(state.bookID));}catch{}
|
|
for(const card of document.querySelectorAll('.timeline-scene-card[data-scene-id]')){const current=Number(card.dataset.sceneId)===state.sceneID;card.classList.toggle('pd-current-narrative-focus',current);if(current)card.setAttribute('aria-current','location');else if(card.getAttribute('aria-current')==='location')card.removeAttribute('aria-current');}
|
|
for(const link of document.querySelectorAll('[data-focus-reference-link]')){const url=new URL(link.href);url.searchParams.delete('chapterId');url.searchParams.delete('sceneId');if(state.chapterID)url.searchParams.set('chapterId',state.chapterID);if(state.sceneID)url.searchParams.set('sceneId',state.sceneID);link.href=url;}
|
|
window.dispatchEvent(new CustomEvent('plotdirector:narrative-focus-changed',{detail:state}));
|
|
}
|
|
async function metadata(){
|
|
if(!state.bookID)return;if(metadataFlight?.book===state.bookID)return metadataFlight.promise;
|
|
const book=state.bookID,project=state.projectID;
|
|
const promise=(async()=>{try{const response=await fetch(`/NarrativeFocus/Read?projectId=${project}&bookId=${book}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const data=await response.json();if(state.bookID!==book||state.projectID!==project)return;state.positions=data.positions;state.recent=data.recent;metadataUnavailable=false;const snapshot=heldHistory();if(snapshot){snapshot.items=recent([...snapshot.items,...data.recent.filter(p=>p.sequence<=snapshot.cutoff)]);window.PlotDirectorSharedFocus.setHeldRecent(snapshot);}render();status.textContent='';}catch{if(state.bookID===book){metadataUnavailable=true;status.textContent='Navigation history could not be refreshed. Reopen to retry.';render();}}finally{if(metadataFlight?.book===book)metadataFlight=null;}})();metadataFlight={book,promise};return promise;
|
|
}
|
|
async function loadScope(book){if(!book){render();return;}const mine=++epoch;busy=true;render();try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${book}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const result=await response.json();if(mine!==epoch)return;state=result;metadataUnavailable=false;if(window.PlotDirectorSharedFocus)await window.PlotDirectorSharedFocus.scope(state);publish();status.textContent='';}catch{status.textContent='This focus book is unavailable. Your workspace is unchanged.';}finally{busy=false;render();if(refreshQueued){refreshQueued=false;void refresh();}}}
|
|
async function refresh(){if(window.PlotDirectorSharedFocus){await window.PlotDirectorSharedFocus.refresh();return;}if(!state.bookID)return;if(busy){refreshQueued=true;return;}refreshQueued=false;const mine=++epoch;try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${state.bookID}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const fresh=await response.json();if(mine!==epoch||busy)return;if(fresh.version!==state.version){state=fresh;publish();}else{state=fresh;render();}}catch{if(mine===epoch&&!busy)status.textContent='Current focus could not be refreshed. Your edits are retained.';}}
|
|
async function set(target={}){
|
|
if(busy||!state.bookID){status.textContent='Choose a focus book first.';return false;}
|
|
if(target.bookID&&Number(target.bookID)!==state.bookID||target.projectID&&Number(target.projectID)!==state.projectID){status.textContent='Choose this book in the header before setting its focus.';return false;}
|
|
const fromPicker=root.querySelector('.pd-focus-picker').contains(document.activeElement);
|
|
const adapter=window.PlotDirectorFocusWorkspace?.adapter;if(adapter?.beforeChange&&!adapter.beforeChange(target)){render();return false;}
|
|
if(window.PlotDirectorSharedFocus?.ownsScope(state)){busy=true;render();try{const result=await window.PlotDirectorSharedFocus.navigate(target);if(result)dismiss(fromPicker);else if(fromPicker)toggle.focus({preventScroll:true});return result;}finally{adapter?.changeFinished?.();busy=false;render();}}
|
|
busy=true;++epoch;render();status.textContent='Updating current focus…';
|
|
const body=new URLSearchParams({projectId:state.projectID,bookId:state.bookID,version:state.version,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});
|
|
if(target.chapterID)body.set('chapterId',target.chapterID);if(target.sceneID)body.set('sceneId',target.sceneID);if(target.direction)body.set('direction',target.direction);
|
|
try{const response=await fetch('/NarrativeFocus/Set',{method:'POST',body});const result=await response.json().catch(()=>null);if(!response.ok||response.redirected){if(response.status===409){busy=false;await refresh();}throw Error(result?.message||'Current focus could not be changed.');}state=result;publish();status.textContent='';try{localStorage.setItem(notificationKey(),String(state.version));}catch{}dismiss(fromPicker&&document.activeElement===document.body);return true;
|
|
}catch(error){status.textContent=error.message;if(toggle.getAttribute('aria-expanded')!=='true')showWorkspaceMessage(error.message);return false;}finally{adapter?.changeFinished?.();busy=false;render();if(refreshQueued){refreshQueued=false;void refresh();}}
|
|
}
|
|
function choose(value){const p=entries().find(p=>key(p)===value);return p?set(p):Promise.resolve(false);}
|
|
tree.addEventListener('click',event=>{const expand=event.target.closest('[data-focus-expand]');if(expand){const id=Number(expand.dataset.focusExpand);expanded.has(id)?expanded.delete(id):expanded.add(id);renderTree();return;}const button=event.target.closest('[data-focus-target]');if(button)void choose(button.dataset.focusTarget);});
|
|
tree.addEventListener('keydown',event=>{const button=event.target.closest('[data-focus-target]');if(!button)return;const chapter=Number(button.dataset.chapter),value=button.dataset.focusTarget;
|
|
if(['ArrowRight','ArrowLeft'].includes(event.key)){event.preventDefault();if(event.key==='ArrowRight'&&!value.endsWith('/'))return;if(event.key==='ArrowRight')expanded.add(chapter);else if(value.endsWith('/'))expanded.delete(chapter);renderTree();tree.querySelector(`[data-focus-target="${chapter}/"]`)?.focus();return;}
|
|
if(!['ArrowDown','ArrowUp','Home','End'].includes(event.key))return;event.preventDefault();const targets=[...tree.querySelectorAll('[data-focus-target]')].filter(b=>b.getClientRects().length&&!b.disabled),at=targets.indexOf(button),next=event.key==='Home'?0:event.key==='End'?targets.length-1:Math.max(0,Math.min(targets.length-1,at+(event.key==='ArrowDown'?1:-1)));targets[next]?.focus();
|
|
});
|
|
root.addEventListener('keydown',event=>{if(event.key==='Escape'){event.preventDefault();dismiss(true);}});
|
|
function closeRibbonMenu(button){const menu=button.closest('details[data-compact=true]');if(menu){const restore=menu.contains(document.activeElement)||document.activeElement===document.body;menu.open=false;if(restore)menu.querySelector('summary').focus({preventScroll:true});}}
|
|
document.querySelectorAll('[data-global-focus=previous],[data-global-focus=next]').forEach(b=>b.addEventListener('click',async()=>{if(await set({direction:b.dataset.globalFocus==='previous'?-1:1}))closeRibbonMenu(b);}));
|
|
for(const button of historyToggles){bootstrap.Dropdown.getOrCreateInstance(button,{popperConfig:config=>({...config,strategy:'fixed',modifiers:[...(config.modifiers||[]),{name:'preventOverflow',options:{boundary:'viewport',padding:12}}]})});button.parentElement.addEventListener('shown.bs.dropdown',()=>void metadata());}
|
|
for(const list of historyLists)list.addEventListener('click',async event=>{const button=event.target.closest('[data-focus-history-target]');if(!button)return;if(await choose(button.dataset.focusHistoryTarget)){const toggle=list.parentElement.querySelector('[data-focus-history-toggle]');bootstrap.Dropdown.getOrCreateInstance(toggle).hide();toggle.focus({preventScroll:true});}});
|
|
root.addEventListener('shown.bs.dropdown',()=>void metadata());bookPicker?.addEventListener('change',()=>void loadScope(Number(bookPicker.value)));
|
|
window.addEventListener('plotdirector:focus-adapter-ready',render);
|
|
window.addEventListener('plotdirector:shared-focus',event=>{const p=event.detail.position;if(p.bookID!==state.bookID||p.projectID!==state.projectID)return;if(window.PlotDirectorSharedFocus?.held)visitHeld(p);const position=state.positions.find(x=>x.chapterID===p.chapterID&&(!p.sceneID||x.sceneID===p.sceneID));state={...state,...p,label:position?(p.sceneID?position.label:`Ch ${position.chapterNumber}: ${position.chapterTitle}`):'Choose chapter or scene'};if(event.detail.reason==='selection')render();else publish();if(!window.PlotDirectorSharedFocus?.held&&historyToggles.some(b=>b.getAttribute('aria-expanded')==='true'))void metadata();});
|
|
window.addEventListener('plotdirector:focus-mode',()=>{if(window.PlotDirectorSharedFocus?.held){const p=window.PlotDirectorSharedFocus.local;if(p?.bookID===state.bookID){const entry=entries().find(x=>key(x)===key(p));state={...state,...p,label:entry?.label||state.label};}heldHistory();render();void metadata();}else{const shared=window.PlotDirectorSharedFocus,frame=shared?.heldRecent;if(frame?.bookID===state.bookID){frame.items=recent([shared.local,...frame.items]);frame.resumeVersion=shared.shared?.version??state.version;shared.setHeldRecent(frame);}}renderHistory();});
|
|
window.addEventListener('plotdirector:shared-focus-ready',()=>{heldHistory();renderHistory();});
|
|
function showWorkspaceMessage(message){let output=document.querySelector('[data-focus-workspace-status]');if(!output){output=document.createElement('p');output.dataset.focusWorkspaceStatus='';output.setAttribute('role','status');document.querySelector('.pd-shell').after(output);}output.textContent=message;}
|
|
document.addEventListener('click',event=>{const b=event.target.closest('[data-go-objective],[data-narrative-scene]');if(b)void set({bookID:Number(b.dataset.narrativeBook)||state.bookID,chapterID:Number(b.dataset.chapter||b.dataset.narrativeChapter)||null,sceneID:Number(b.dataset.scene||b.dataset.narrativeScene)||null});});
|
|
window.addEventListener('storage',event=>{if(event.key===notificationKey())void refresh();});window.addEventListener('focus',()=>void refresh());window.addEventListener('pageshow',()=>void refresh());window.addEventListener('pagehide',()=>dismiss());
|
|
const restored=window.PlotDirectorSharedFocus;
|
|
if(restored?.held&&restored.local?.bookID===state.bookID&&restored.local?.projectID===state.projectID){const p=restored.local,entry=entries().find(x=>key(x)===key(p));state={...state,...p,label:entry?.label||'Held reference unavailable'};}
|
|
window.PlotDirectorNarrativeFocus={set,refresh,get state(){return state;}};publish();
|
|
if(!state.bookID&&bookPicker){try{const book=localStorage.getItem(scopeKey);if([...bookPicker.options].some(o=>o.value===book))void loadScope(Number(book));}catch{}}
|
|
const url=new URL(location.href);if(url.searchParams.has('navigateFocus')){url.searchParams.delete('navigateFocus');history.replaceState(history.state,'',url);}
|
|
})();
|