68 lines
8.5 KiB
JavaScript
68 lines
8.5 KiB
JavaScript
(() => {
|
||
'use strict';
|
||
const model=window.PlotDirectorCalendar,instances=new WeakMap(),states=new WeakMap(),cache=new Map();
|
||
const element=(tag,text)=>{const n=document.createElement(tag);if(text!=null)n.textContent=text;return n;};
|
||
function load(book,refresh){if(refresh)cache.delete(book);if(!cache.has(book)){if(cache.size>32)cache.delete(cache.keys().next().value);const promise=fetch(`/Writing/Context/Calendar/State?bookId=${book}`,{cache:'no-store',signal:AbortSignal.timeout(20000)}).then(async r=>{if(!r.ok||r.redirected)throw Error('Calendar unavailable. Check access and refresh saved data.');return r.json();}).catch(e=>{if(cache.get(book)===promise)cache.delete(book);throw e;});cache.set(book,promise);}return cache.get(book);}
|
||
function mount(node,context){
|
||
if(instances.has(node))return;
|
||
const q=s=>node.querySelector(s),pane=node.closest('[data-context-pane]');
|
||
let state=states.get(pane);if(!state){state={month:new Date().toISOString().slice(0,7),selected:null,hold:false,books:'current',from:'',expanded:new Set()};states.set(pane,state);}
|
||
let position=context.position,data,epoch=0,disposed=false;
|
||
const status=q('[data-calendar-status]'),grid=q('[data-calendar-grid]'),details=q('[data-calendar-details]');
|
||
const label=day=>model.date(day)?.toLocaleDateString('en-GB',{timeZone:'UTC',weekday:'long',day:'numeric',month:'long',year:'numeric'});
|
||
function elapsed(){const n=model.elapsed(state.from,state.selected);q('[data-calendar-destination]').textContent=state.selected?label(state.selected):'Select a date';q('[data-calendar-elapsed]').textContent=n==null?'Choose a start date':`${n} days · ${n<0?'−':''}${Math.floor(Math.abs(n)/7)} weeks, ${Math.abs(n)%7} days`;}
|
||
function drawDetails(){
|
||
details.replaceChildren(element('h3',state.selected?label(state.selected):'Select a date'));
|
||
const scenes=data.scenes.filter(s=>state.books==='all'||s.bookID===position.bookId),groups=model.chapters(scenes,state.selected);
|
||
details.append(element('p',`${groups.length} chapters · ${groups.reduce((n,g)=>n+g.scenes.length,0)} scenes`));
|
||
if(!groups.length)details.append(element('p','No dated chapters or scenes on this date.'));
|
||
for(const group of groups){const key=state.selected+'/'+group.bookID+'/'+group.chapterID,section=element('details');section.open=state.expanded.has(key);section.addEventListener('toggle',()=>{if(!section.isConnected)return;if(section.open)state.expanded.add(key);else state.expanded.delete(key);});
|
||
section.append(element('summary',`${state.books==='all'?group.bookLabel+' · ':''}Ch ${group.chapterNumber} · ${group.chapterTitle} (${group.scenes.length} scenes)`));
|
||
for(const scene of group.scenes){const sceneKey=key+'/'+scene.sceneID,row=element('details');row.open=state.expanded.has(sceneKey);row.addEventListener('toggle',()=>{if(!row.isConnected)return;if(row.open)state.expanded.add(sceneKey);else state.expanded.delete(sceneKey);});row.append(element('summary',`Scene ${scene.sceneNumber} · ${scene.title}`));const link=element('a','Open scene in main window');link.href=`/Scenes/Edit/${scene.sceneID}?retainNarrativeFocus=true`;link.dataset.contextNarrative='author';link.target='_blank';link.rel='noopener';const summary=element('p',scene.summary?.trim()||'No saved scene summary.');summary.className='context-calendar-scene-summary';row.append(summary,link);section.append(row);}
|
||
details.append(section);
|
||
}
|
||
elapsed();
|
||
}
|
||
function draw(){if(!data)return;
|
||
const current=model.manuscript(data.scenes,position);
|
||
if(!state.hold&¤t.date){state.month=current.date.slice(0,7);state.selected=current.date;}
|
||
q('[data-calendar-month]').value=state.month;q('[data-calendar-books]').value=state.books;
|
||
q('[data-calendar-hold]').setAttribute('aria-pressed',String(state.hold));
|
||
status.textContent=`${state.hold?'Browsing / Hold':'Following scene'} · Manuscript: ${current.date?label(current.date)+' · '+current.source:'undated; month retained'}`;
|
||
q('[data-calendar-title]').textContent=model.date(state.month+'-01').toLocaleDateString('en-GB',{month:'long',year:'numeric',timeZone:'UTC'});
|
||
q('[data-calendar-previous]').disabled=!model.shift(state.month,-1);q('[data-calendar-next]').disabled=!model.shift(state.month,1);
|
||
grid.replaceChildren();const days=model.grid(state.month);grid.style.setProperty('--calendar-weeks',days.length/7);
|
||
const scenes=data.scenes.filter(s=>state.books==='all'||s.bookID===position.bookId);
|
||
function select(day,group){state.hold=true;state.selected=day;state.month=day.slice(0,7);if(group)state.expanded.add(day+'/'+group.bookID+'/'+group.chapterID);draw();const cell=node.querySelector(`[data-calendar-date="${day}"]`);(group?cell?.querySelector(`[data-chapter-id="${group.chapterID}"]`):cell?.querySelector('button'))?.focus({preventScroll:true});}
|
||
for(const day of days){if(!day){grid.append(element('span'));continue;}const groups=model.chapters(scenes,day),cell=element('div');cell.dataset.calendarDate=day;cell.className='context-calendar-day';
|
||
cell.classList.toggle('is-overflow',day.slice(0,7)!==state.month);cell.classList.toggle('is-manuscript',day===current.date);cell.dataset.selected=String(day===state.selected);if(day===current.date)cell.setAttribute('aria-current','date');
|
||
const head=element('button',`${Number(day.slice(-2))}${day===current.date?' ●':''}`);head.type='button';head.className='context-calendar-day-number';head.setAttribute('aria-pressed',String(day===state.selected));head.setAttribute('aria-label',`${label(day)}, ${groups.length} chapters, ${groups.reduce((n,g)=>n+g.scenes.length,0)} scenes`);head.onclick=()=>select(day);cell.append(head);
|
||
const chips=element('div');chips.className='context-calendar-chips';
|
||
for(const group of groups){const text=`${state.books==='all'?group.bookLabel+' · ':''}Ch ${group.chapterNumber}`,chip=element('button',text);chip.type='button';chip.title=`${text} · ${group.chapterTitle} (${group.scenes.length} scenes)`;chip.className='context-calendar-chapter';chip.dataset.chapterId=group.chapterID;chip.onclick=()=>select(day,group);chips.append(chip);}
|
||
cell.append(chips);const more=element('button');more.type='button';more.className='context-calendar-more';more.hidden=true;more.onclick=()=>select(day);cell.append(more);grid.append(cell);
|
||
}
|
||
fitChips();
|
||
drawDetails();
|
||
}
|
||
function fitChips(){
|
||
for(const cell of grid.querySelectorAll('.context-calendar-day')){
|
||
const chips=cell.querySelector('.context-calendar-chips'),items=[...chips.children],more=cell.querySelector('.context-calendar-more');
|
||
more.hidden=true;for(const chip of items)chip.hidden=false;
|
||
if(chips.scrollHeight<=chips.clientHeight+1)continue;
|
||
more.hidden=false;more.textContent=`+${items.length}`;
|
||
let hidden=0;for(let i=items.length-1;i>=0&&chips.scrollHeight>chips.clientHeight+1;i--){items[i].hidden=true;hidden++;}
|
||
more.hidden=!hidden;more.textContent=`+${hidden}`;more.setAttribute('aria-label',`${hidden} more chapters on ${label(cell.dataset.calendarDate)}`);
|
||
}
|
||
}
|
||
const resize=new ResizeObserver(()=>fitChips());resize.observe(grid);
|
||
async function reload(refresh=false){const ticket=++epoch;try{const result=await load(position.bookId,refresh);if(disposed||ticket!==epoch)return;data=result;draw();}catch(e){if(!disposed&&ticket===epoch)status.textContent=e.message;}}
|
||
q('[data-calendar-books]').onchange=e=>{state.books=e.target.value;draw();};
|
||
q('[data-calendar-month]').onchange=e=>{if(model.date(e.target.value+'-01')){state.hold=true;state.month=e.target.value;draw();}};
|
||
for(const [selector,step]of [['[data-calendar-previous]',-1],['[data-calendar-next]',1]])q(selector).onclick=()=>{const month=model.shift(state.month,step);if(month){state.hold=true;state.month=month;draw();}};
|
||
q('[data-calendar-hold]').onclick=()=>{state.hold=true;draw();};q('[data-calendar-return]').onclick=()=>{state.hold=false;draw();};
|
||
q('[data-calendar-from]').value=state.from;q('[data-calendar-from]').onchange=e=>{state.from=e.target.value;elapsed();};
|
||
instances.set(node,{position(next){position=next;draw();},refresh(){void reload(true);},dispose(){disposed=true;epoch++;resize.disconnect();}});void reload();
|
||
}
|
||
window.PlotDirectorContextLifecycles={...(window.PlotDirectorContextLifecycles||{}),calendar:{mount,dispose(node){instances.get(node)?.dispose();instances.delete(node);},onPosition(node,next){const instance=instances.get(node);if(!instance)return false;instance.position(next);return true;},onCacheInvalidation(){cache.clear();},onInvalidation(node){const instance=instances.get(node);if(!instance)return false;instance.refresh();return true;}}};
|
||
})();
|