Validate ribbon navigation availability and instrument Word dispatch stages

This commit is contained in:
Nick Beckley 2026-11-18 21:26:28 +00:00
parent 9d397c0ae3
commit ebfc5815e9
8 changed files with 40 additions and 16 deletions

View File

@ -107,7 +107,7 @@ namespace PlotDirector.WordAddIn
if((message.Action=="tray-sync"||message.Action=="tray-repair")&&message.Status!="ok")PostToUi(()=>{
if(active?.Session==message.SessionId)ShowChapterCommandFailure("Companion could not accept this command ("+message.Status+"). Check the current document and retry.");
});
if(message.Command!=null){var delivery=Stopwatch.StartNew();PostToUi(()=>{if(message.Command.Kind=="chapter-check")Metric("chapter-command-ui-dispatch",delivery.Elapsed.TotalMilliseconds);HandleCommand(message.Command);});}
if(message.Command!=null){var delivery=Stopwatch.StartNew();PostToUi(()=>{if(message.Command.Kind=="chapter-check")Metric("chapter-command-ui-dispatch",delivery.Elapsed.TotalMilliseconds);if(message.Command.Kind=="navigate")Metric("navigation-ui-dispatch",delivery.Elapsed.TotalMilliseconds);HandleCommand(message.Command);});}
if(message.WordCount.HasValue)PostToUi(()=>{var doc=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);if(doc!=null)doc.WordCount=message.WordCount;});
if(message.Status!="ok"&&message.Status!="ready")lastResult=message.Status;
};
@ -276,10 +276,11 @@ namespace PlotDirector.WordAddIn
}
else if(command.Kind=="cancel"){CancelChapterRead(doc);CancelExtraction(doc);doc.AiJob=Guid.Empty;}
else if(command.Kind=="navigate"&&command.Chapter!=null){
var navigationClock=Stopwatch.StartNew();
if(!NavigationPolicy.Current(command,doc.Session,doc.Revision,doc.Identity,DateTime.UtcNow,Com(()=>doc.Document.Saved)))throw new InvalidOperationException("Navigation expired or document changed.");
if(completedNavigationIds.Contains(command.Id)){Reply(command,"ok");return;}
var position=command.Chapter.Start;if(position<0||position>DocumentEnd(doc.Document))throw new InvalidOperationException("Position no longer exists.");
Word.Range range=null;try{range=Com(()=>doc.Document.Range(position,position));Com(()=>{range.Select();return true;});navigationExecutions++;lastNavigationId=command.Id;if(completedNavigationIds.Count==64)completedNavigationIds.Dequeue();completedNavigationIds.Enqueue(command.Id);}finally{Release(range);}
Metric("navigation-identity-and-target",navigationClock.Elapsed.TotalMilliseconds);navigationClock.Restart();Word.Range range=null;try{range=Com(()=>doc.Document.Range(position,position));Com(()=>{range.Select();return true;});Metric("navigation-word-selection",navigationClock.Elapsed.TotalMilliseconds);navigationExecutions++;lastNavigationId=command.Id;if(completedNavigationIds.Count==64)completedNavigationIds.Dequeue();completedNavigationIds.Enqueue(command.Id);}finally{Release(range);}
}
else if(command.Kind=="associate"){
if(command.Remember){

View File

@ -15,12 +15,22 @@ public sealed class WriterWordController(WriterWordService words,IWordCompanionR
Response.Headers.CacheControl="no-store";
if(!ModelState.IsValid||bookId<=0||chapterId<=0||sceneId is <=0||instanceId==Guid.Empty||sessionId==Guid.Empty||manuscriptId==Guid.Empty||navigationId==Guid.Empty||revision<0)return BadRequest();
if(await access.GetBookStructureAsync(bookId,Author)==null)return NotFound();
try { return await words.Navigate(Author,bookId,chapterId,sceneId,instanceId,sessionId,manuscriptId,revision,navigationId,paragraphId,acceptedRevision)?Accepted(new{navigationId,message="Requested in Word; waiting for confirmation."}):Conflict(new{message="This Word document or chapter position is not currently verified, or Word is busy. Check Companion and try again. Nothing was moved."}); }
var timer=System.Diagnostics.Stopwatch.StartNew();
try { var queued=await words.Navigate(Author,bookId,chapterId,sceneId,instanceId,sessionId,manuscriptId,revision,navigationId,paragraphId,acceptedRevision);Response.Headers.Append("Server-Timing",FormattableString.Invariant($"word-target-and-queue;dur={timer.Elapsed.TotalMilliseconds:F2}"));return queued?Accepted(new{navigationId,message="Requested in Word; waiting for confirmation."}):Conflict(new{message="This Word document or chapter position is not currently verified, or Word is busy. Check Companion and try again. Nothing was moved."}); }
catch(UnauthorizedAccessException){return NotFound();}
catch(Microsoft.Data.SqlClient.SqlException e) when(e.Number==51000){return NotFound();}
catch(Exception e) when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){return StatusCode(503,new{message="Word navigation is temporarily unavailable. Your saved work is retained."});}
}
[HttpGet]
public async Task<IActionResult> Availability(int bookId,int chapterId,int? sceneId,Guid instanceId,Guid sessionId,Guid manuscriptId,long revision,Guid? paragraphId=null,long? acceptedRevision=null)
{
Response.Headers.CacheControl="no-store";
if(!ModelState.IsValid||bookId<=0||chapterId<=0||instanceId==Guid.Empty||sessionId==Guid.Empty||manuscriptId==Guid.Empty||revision<0)return BadRequest();
if(await access.GetBookStructureAsync(bookId,Author)==null)return NotFound();
try{return Json(new{chapter=await words.Navigate(Author,bookId,chapterId,null,instanceId,sessionId,manuscriptId,revision,Guid.NewGuid(),validateOnly:true),scene=sceneId.HasValue&&await words.Navigate(Author,bookId,chapterId,sceneId,instanceId,sessionId,manuscriptId,revision,Guid.NewGuid(),validateOnly:true),paragraph=paragraphId.HasValue&&await words.Navigate(Author,bookId,chapterId,null,instanceId,sessionId,manuscriptId,revision,Guid.NewGuid(),paragraphId,acceptedRevision,true)});}
catch(Exception e)when(e is UnauthorizedAccessException or Microsoft.Data.SqlClient.SqlException or TimeoutException){return StatusCode(503);}
}
[HttpGet]
public async Task<IActionResult> Navigation(int bookId,Guid instanceId,Guid sessionId,Guid navigationId)
{
Response.Headers.CacheControl="no-store";if(await access.GetBookStructureAsync(bookId,Author)==null)return NotFound();var state=presence.NavigationState(Author,bookId,instanceId,sessionId,navigationId);return state==null?NotFound():Json(new{state});

View File

@ -10,15 +10,20 @@ public sealed class WriterWordMetadata
}
public sealed class WriterWordService(ISqlConnectionFactory factory,IWordCompanionRepository access,IParagraphManuscriptRepository paragraphs,IChapterSyncRepository chapters,NativePresenceStore presence)
{
private readonly Dictionary<(int User,int Book),Task<ParagraphManuscript?>> acceptedReads=[];
private Task<ParagraphManuscript?> Accepted(int user,int book){if(!acceptedReads.TryGetValue((user,book),out var pending)){pending=paragraphs.Get(user,book);acceptedReads[(user,book)]=pending;}return pending;}
private static T? One<T>(IEnumerable<T> rows) where T:class {var candidates=rows.Take(2).ToArray();return candidates.Length==1?candidates[0]:null;}
public async Task<WriterWordMetadata?> Metadata(int user,int book,int? chapter){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<WriterWordMetadata>("dbo.WriterWord_Status",new{UserID=user,BookID=book,ChapterID=chapter},commandType:CommandType.StoredProcedure);}
public async Task<ParagraphPosition?> Position(int user,NativeLease lease,WriterWordMetadata? metadata){var p=lease.Position;if(p.WordSaved!=true||!p.WordAvailable||!p.CursorStart.HasValue||metadata?.ManuscriptID!=p.ManuscriptId)return null;var position=p.CanChapterSync?await chapters.Position(user,p.BookId,p.ManuscriptId,lease.Session,p.Revision,p.CursorStart.Value):await paragraphs.Position(user,p.BookId,p.ManuscriptId,lease.Session,p.Revision,p.CursorStart.Value);return position?.HasSnapshot==true&&position.Revision==metadata.Revision?position:null;}
public async Task<bool> Navigate(int user,int book,int chapter,int? scene,Guid instance,Guid session,Guid manuscript,long revision,Guid id,Guid? paragraphId=null,long? acceptedRevision=null)
public async Task<bool> Navigate(int user,int book,int chapter,int? scene,Guid instance,Guid session,Guid manuscript,long revision,Guid id,Guid? paragraphId=null,long? acceptedRevision=null,bool validateOnly=false)
{
var structure=await access.GetBookStructureAsync(book,user);var target=structure==null?null:One(structure.Chapters.Where(c=>c.ChapterId==chapter));if(target==null||scene.HasValue&&!target.Scenes.Any(s=>s.SceneId==scene))return false;
var lease=One(presence.Read(user,book).Where(l=>l.Instance==instance&&l.Session==session&&l.Position.ManuscriptId==manuscript&&l.Position.Revision==revision&&l.Position.WordAvailable&&l.Position.WordSaved==true&&l.Position.CanAcknowledgeNavigation));
if(lease==null)return false;
var state=await paragraphs.Get(user,book);if(state==null||state.ManuscriptId!=manuscript)return false;
ParagraphManuscript? state;
if(!scene.HasValue&&!paragraphId.HasValue&&lease.Position.CanChapterSync){var meta=await Metadata(user,book,chapter);state=meta==null?null:new(){ManuscriptId=meta.ManuscriptID,Revision=meta.Revision};}
else state=await Accepted(user,book);
if(state==null||state.ManuscriptId!=manuscript)return false;
int? start=null;
if(paragraphId.HasValue){
if(acceptedRevision!=state.Revision)return false;
@ -37,6 +42,6 @@ public sealed class WriterWordService(ISqlConnectionFactory factory,IWordCompani
// The live lookup joins current accepted checkpoint hashes and manuscript identity. A stale list is never proof.
var position=lease.Position.CanChapterSync?await chapters.Position(user,book,manuscript,session,revision,start.Value):await paragraphs.Position(user,book,manuscript,session,revision,start.Value);
if(position?.HasSnapshot!=true||position.Revision!=state.Revision||position.ChapterID!=chapter||scene.HasValue&&position.SceneID!=scene)return false;
return presence.Navigate(user,book,instance,session,manuscript,revision,start.Value,requireSaved:true,navigationId:id,requireAcknowledgement:true);
return validateOnly||presence.Navigate(user,book,instance,session,manuscript,revision,start.Value,requireSaved:true,navigationId:id,requireAcknowledgement:true);
}
}

View File

@ -170,7 +170,7 @@
<div class="pd-ribbon-group" role="group" aria-label="Word navigation"><div class="pd-ribbon-commands" data-word-ribbon>
@foreach(var target in new[]{("chapter","Chapter in Word","bible"),("scene","Scene in Word","threads"),("paragraph","Paragraph in Word","point")}){
<button type="button" class="pd-ribbon-command" data-ribbon-word="@target.Item1" disabled title="Select a verified target and connect its Word manuscript"><svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon(target.Item3).IconPath"/></svg><span>@target.Item2</span></button>
}</div><span class="pd-ribbon-group-label">Word navigation</span></div>
}</div><span data-word-ribbon-status role="status" class="writer3-caption"></span><span class="pd-ribbon-group-label">Word navigation</span></div>
}
@if (category.Key == selectedCategory)
{

View File

@ -4,7 +4,8 @@
var title = string.IsNullOrWhiteSpace(Model.Book?.BookDisplayTitle) ? "Choose a book" : Model.Book.BookDisplayTitle;
var heading = home ? title : Model.Destination == "Dashboard" ? "Writing Dashboard" : Model.Destination;
}
<header class="writer3-header @(home||Model.Destination=="Dashboard"?"":"visually-hidden")" data-pwa-task>
@if(!home&&Model.Destination!="Dashboard"){<h1 class="visually-hidden">@heading</h1>}else{
<header class="writer3-header" data-pwa-task>
@if(home&&!string.IsNullOrWhiteSpace(Model.Book?.CoverThumbnailPath)){
<img class="writer3-cover" src="@Url.Content(Model.Book.CoverThumbnailPath)" alt="Cover of @title" />
}else if(home){<div class="writer3-cover writer3-cover-empty" aria-hidden="true">@title[..1]</div>}
@ -15,5 +16,6 @@
</div>
</header>
}
@if(TempData["WriterWorkspaceMessage"] is string message){<p class="alert alert-info" role="status">@message</p>}
@if(TempData["WriterWorkspaceError"] is string error){<p class="alert alert-warning" role="alert">@error</p>}

View File

@ -26,13 +26,13 @@
else{<p class="muted">Work-session evidence is private to the book owner. Your chapter and scene tools remain available.</p>}
</section>
<aside class="writer3-panel writer3-reference" tabindex="0" aria-label="Writing tools">
<h2>Keep your story close</h2><div class="button-row writer3-window-actions"><button type="button" class="btn btn-sm btn-outline-secondary" data-open-writing-context>Open Context <span aria-hidden="true">↗</span></button><button type="button" class="btn btn-sm btn-outline-secondary" data-open-writing-intent>Open Intent <span aria-hidden="true">↗</span></button></div><p data-writing-workspace-message role="status"></p><partial name="_WriterWord" model="Model" /><div data-authoring-references></div><p>Open the existing tools when you need more detail.</p>
<h2>Keep your story close</h2><div class="button-row"><a class="btn btn-outline-secondary" data-focus-reference-link asp-controller="Writing" asp-action="Context" asp-route-bookId="@Model.BookID" asp-route-chapterId="@focus?.ChapterID" asp-route-sceneId="@focus?.SceneID">Context</a><a class="btn btn-outline-secondary" data-focus-reference-link asp-controller="Writing" asp-action="Intent" asp-route-bookId="@Model.BookID" asp-route-chapterId="@focus?.ChapterID" asp-route-sceneId="@focus?.SceneID">Intent</a></div><p data-writing-workspace-message role="status"></p><partial name="_WriterWord" model="Model" /><div data-authoring-references></div><p>Open the existing tools when you need more detail.</p>
<div class="writer3-link-list">
<a asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID" asp-fragment="chapters">Chapters &amp; scenes <span aria-hidden="true">↗</span></a>
@if(focus?.ChapterID.HasValue==true){<a asp-action="Chapter" asp-route-id="@focus.ChapterID">Chapter goals &amp; workflow <span aria-hidden="true">↗</span></a>}
<a asp-action="Workspaces" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Scene workspaces <span aria-hidden="true">↗</span></a>
</div>
@if(Model.ProjectID.HasValue){<details class="writer3-authoring-details"><summary>Open story reference tools</summary><div class="writer3-link-list"><a asp-controller="Characters" asp-action="Index" asp-route-projectId="@Model.ProjectID">Characters</a><a asp-controller="PlotLineWorkspace" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Plot lines and threads</a><a asp-controller="RelationshipMap" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Relationships</a><a asp-controller="Maps" asp-action="Index" asp-route-projectId="@Model.ProjectID">Maps and locations</a><a asp-controller="ProjectMetrics" asp-action="Index" asp-route-projectId="@Model.ProjectID">Recorded emotion and scene metrics</a></div></details>}
<p class="writer3-caption">Context and Intent open as standalone reference windows. Their selection is separate from your saved writing focus.</p>
<p class="writer3-caption">Context and Intent are reference tools. Their selection is separate from your saved writing focus; use Back to return.</p>
</aside>
</div>

View File

@ -10,8 +10,8 @@
form.querySelector('[data-focus-cancel]').addEventListener('click',()=>{host.hidden=true;const change=root.querySelector('[data-change-focus]');if(change)change.hidden=false;root.querySelector('[data-change-focus]')?.focus();});
form.addEventListener('submit',async e=>{e.preventDefault();if(e.defaultPrevented&&e.cancelBubble)return;if(busy)return;if(step!==2){step++;render();return;}busy=true;const button=form.querySelector('[data-save-focus]');button.disabled=true;form.querySelector('[data-focus-error]').textContent='';try{const response=await fetch(form.action,{method:'POST',body:new FormData(form),headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw Error();const data=await response.json();if(!data.saved)throw Error();
root.dataset.savedActivity=data.activity;root.dataset.savedChapter=data.chapterID||'';root.dataset.savedSessionKind=data.sessionKind||'';
let summary=root.querySelector('[data-focus-summary]');if(!summary){summary=document.createElement('div');host.before(summary);}summary.replaceChildren();const h=document.createElement('h2');h.textContent=data.activity+' · '+data.title;const p=document.createElement('p');p.textContent=data.intention||'Your focus is saved. No recording has started.';const a=document.createElement('a');a.href=data.continueUrl;a.className='btn btn-primary';a.textContent='Continue this work';summary.append(h,p,a);host.hidden=true;const change=root.querySelector('[data-change-focus]');if(change)change.hidden=false;busy=false;button.disabled=false;
window.dispatchEvent(new CustomEvent('plotdirector:focus-saved',{detail:data}));summary.tabIndex=-1;summary.focus();}catch{form.querySelector('[data-focus-error]').textContent='Your focus could not be confirmed. Your choices are retained; please try again.';busy=false;button.disabled=false;}});
let summary=root.querySelector('[data-focus-summary]');if(!summary){summary=document.createElement('div');host.before(summary);}summary.replaceChildren();const h=document.createElement('h2');h.textContent=data.activity+' · '+data.title;const p=document.createElement('p');p.textContent=data.intention||'Your focus is saved. No recording has started.';const a=document.createElement('a');a.href=data.continueUrl;a.className='btn btn-primary';a.textContent=data.sceneID?'Open selected scene workspace':data.chapterID?'Open selected chapter workspace':'Open chapters';summary.append(h,p,a);host.hidden=true;const change=root.querySelector('[data-change-focus]');if(change)change.hidden=false;busy=false;button.disabled=false;
for(const link of document.querySelectorAll('[data-focus-reference-link]')){const target=new URL(link.href);target.searchParams.delete('chapterId');target.searchParams.delete('sceneId');if(data.chapterID)target.searchParams.set('chapterId',data.chapterID);if(data.sceneID)target.searchParams.set('sceneId',data.sceneID);link.href=target;}window.dispatchEvent(new CustomEvent('plotdirector:focus-saved',{detail:data}));summary.tabIndex=-1;summary.focus();}catch{form.querySelector('[data-focus-error]').textContent='Your focus could not be confirmed. Your choices are retained; please try again.';busy=false;button.disabled=false;}});
}
root.querySelector('[data-change-focus]')?.addEventListener('click',async e=>{e.preventDefault();if(loading)return;e.currentTarget.hidden=true;if(host.querySelector('form')){host.hidden=false;return;}loading=true;host.hidden=false;host.textContent='Loading your focus…';try{const r=await fetch(root.dataset.focusUrl);if(!r.ok)throw Error();host.innerHTML=await r.text();initialise();}catch{host.textContent='Focus is temporarily unavailable. Try Change focus again.';const change=root.querySelector('[data-change-focus]');if(change)change.hidden=false;}finally{loading=false;}});
initialise();

View File

@ -2,8 +2,8 @@
(()=>{'use strict';let root=document.querySelector('[data-writer-word]');if(root?.dataset.bound)return;if(!root){const template=document.querySelector('[data-word-fallback]');if(!template)return;const holder=document.createElement('details');holder.className='writer3-inset';const summary=document.createElement('summary');summary.textContent='Word connection and manuscript';holder.append(summary,template.content.cloneNode(true));document.querySelector('main')?.append(holder);root=holder.querySelector('[data-writer-word]');}if(!root)return;root.dataset.bound='true';
const book=Number(root.dataset.bookId);let chapter=Number(root.dataset.chapterId),scene=Number(root.dataset.sceneId);const state=root.querySelector('[data-word-state]'),position=root.querySelector('[data-word-position]'),freshness=root.querySelector('[data-word-freshness]'),message=root.querySelector('[data-word-command]'),choose=root.querySelector('[data-word-choose]'),select=root.querySelector('[data-word-document]'),nav=root.querySelector('[data-word-navigate]'),sceneNav=root.querySelector('[data-word-scene]'),adopt=root.querySelector('[data-word-adopt]');
const reviewing=root.dataset.wordContext==='review',paragraphButton=root.querySelector('[data-word-paragraph]');
let packet=null,current=null,busy=false,abort=null,checkBusy=false,syncPending=null;const sync=root.querySelector('[data-word-sync]');
const key=l=>l.instanceId+'/'+l.sessionId;
let availabilityKey='',availability={},availabilityEpoch=0;let packet=null,current=null,busy=false,abort=null,checkBusy=false,syncPending=null;const sync=root.querySelector('[data-word-sync]');
const key=l=>l.instanceId+'/'+l.sessionId;new MutationObserver(()=>{for(const status of document.querySelectorAll('[data-word-ribbon-status]'))status.textContent=message.textContent;}).observe(message,{childList:true,subtree:true,characterData:true});
const verified=l=>(packet?.verifiedPositions||[]).find(p=>key(p)===key(l));
const requestStatus=()=>window.dispatchEvent(new Event('plotdirector:refresh-word-status'));
function render(data){chapter=Number(root.dataset.chapterId);scene=Number(root.dataset.sceneId);packet=data;const old=current;const leases=(data.leases||[]).filter(l=>l.wordAvailable&&l.bookId===book&&Date.parse(l.expires)>Date.now());const originParams=new URLSearchParams(location.search);const originKey=originParams.get('wordInstanceId')+'/'+originParams.get('wordSessionId');const selected=select.value||originKey;select.replaceChildren(new Option('Choose a document',''),...leases.map(l=>new Option(l.documentTitle,key(l))));if(leases.some(l=>key(l)===selected))select.value=selected;else if(leases.length===1)select.value=key(leases[0]);current=leases.find(l=>key(l)===select.value)||null;choose.hidden=leases.length<2;
@ -17,14 +17,20 @@ if(data.canonical?.chapterAcceptedUtc)status+=' This chapter last accepted: '+ne
sync.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!(current.canChapterSync||current.canParagraphSync);
for(const button of [nav,sceneNav,paragraphButton])if(button)button.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!current.canAcknowledgeNavigation;
if(identity&&!current.canAcknowledgeNavigation)position.textContent+=' Update the Word add-in and Companion together to enable confirmed navigation.';
const targetKey=identity&&current.wordSaved===true&&chapter?[chapter,scene,root.dataset.paragraphId,root.dataset.acceptedRevision,key(current),current.manuscriptId,current.revision,data.canonical?.revision].join(':'):'';
if(targetKey!==availabilityKey){availabilityKey=targetKey;availability={};const epoch=++availabilityEpoch;
if(targetKey){const query=new URLSearchParams({bookId:book,chapterId:chapter,instanceId:current.instanceId,sessionId:current.sessionId,manuscriptId:current.manuscriptId,revision:current.revision});if(scene)query.set('sceneId',scene);if(root.dataset.paragraphId){query.set('paragraphId',root.dataset.paragraphId);query.set('acceptedRevision',root.dataset.acceptedRevision);}
fetch('/WriterWord/Availability?'+query,{cache:'no-store'}).then(async response=>{if(!response.ok)throw Error();return response.json();}).then(value=>{if(epoch!==availabilityEpoch)return;availability=value;if(packet)render(packet);}).catch(()=>{if(epoch!==availabilityEpoch)return;message.textContent='Verified Word target mapping is unavailable. Check synchronisation or retry the connection.';availabilityKey='';});}
}
if(nav)nav.disabled ||= availability.chapter!==true;if(sceneNav)sceneNav.disabled ||= availability.scene!==true;if(paragraphButton)paragraphButton.disabled ||= availability.paragraph!==true;
if(nav)nav.disabled ||= !chapter;if(sceneNav)sceneNav.disabled ||= !scene;if(paragraphButton)paragraphButton.disabled ||= !root.dataset.paragraphId;
for(const button of document.querySelectorAll('[data-ribbon-word]')){const original=button.dataset.ribbonWord==='chapter'?nav:button.dataset.ribbonWord==='scene'?sceneNav:paragraphButton;button.disabled=!original||original.disabled;button.title=button.disabled?'Select a verified target, connect and synchronise its Word manuscript':button.textContent.trim();}
const params=new URLSearchParams(location.search),origin=current&&params.get('wordInstanceId')===current.instanceId&&params.get('wordSessionId')===current.sessionId;
adopt.hidden=reviewing||!(origin&&observed&&observed.chapterId!==chapter);if(!adopt.hidden){adopt.querySelector('[name=ChapterID]').value=observed.chapterId;adopt.querySelector('[name=SceneID]').value=observed.sceneId||'';adopt.querySelector('[data-word-origin]').textContent='Opened from verified Word chapter '+(observed.chapterTitle||'in this manuscript')+'. Your saved working focus is unchanged.';}
}
select.addEventListener('change',()=>render(packet));
window.addEventListener('plotdirector:focus-saved',event=>{abort?.abort();chapter=Number(event.detail.chapterID)||0;scene=Number(event.detail.sceneID)||0;root.dataset.chapterId=chapter||'';root.dataset.sceneId=scene||'';root.dataset.paragraphId='';root.dataset.statusUrl='/native-companion/status?writerBookId='+book+'&writerChapterId='+chapter;if(packet)render(packet);requestStatus();});
for(const button of document.querySelectorAll('[data-ribbon-word]'))button.addEventListener('click',()=>{if(button.disabled)return;(button.dataset.ribbonWord==='chapter'?nav:button.dataset.ribbonWord==='scene'?sceneNav:paragraphButton)?.click();root.querySelector('[data-word-command]')?.scrollIntoView({block:'nearest'});});
window.addEventListener('plotdirector:focus-saved',event=>{abort?.abort();message.textContent='Working target changed. Word has not moved.';chapter=Number(event.detail.chapterID)||0;scene=Number(event.detail.sceneID)||0;root.dataset.chapterId=chapter||'';root.dataset.sceneId=scene||'';root.dataset.paragraphId='';root.dataset.statusUrl='/native-companion/status?writerBookId='+book+'&writerChapterId='+chapter;if(packet)render(packet);requestStatus();});
for(const button of document.querySelectorAll('[data-ribbon-word]'))button.addEventListener('click',()=>{if(button.disabled)return;(button.dataset.ribbonWord==='chapter'?nav:button.dataset.ribbonWord==='scene'?sceneNav:paragraphButton)?.click();});
async function navigate(toScene,toParagraph=false){if(busy||!current||!chapter)return;if(Date.parse(current.expires)<=Date.now()){message.textContent='Word connection expired. Check the connection before navigating.';render({...packet,leases:[]});requestStatus();return;}busy=true;abort=new AbortController();const selected={...current},id=crypto.randomUUID(),dispatch=performance.now();render(packet);message.textContent='Requesting navigation in Word…';const form=new URLSearchParams({bookId:String(book),chapterId:String(chapter),instanceId:selected.instanceId,sessionId:selected.sessionId,manuscriptId:selected.manuscriptId,revision:String(selected.revision),navigationId:id,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});if(toScene)form.set('sceneId',String(scene));if(toParagraph){form.set('paragraphId',root.dataset.paragraphId);form.set('acceptedRevision',root.dataset.acceptedRevision);}try{const response=await fetch('/WriterWord/Navigate',{method:'POST',body:form,signal:abort.signal});const data=await response.json().catch(()=>null);if(!response.ok)throw Error(data?.message||'Navigation could not be requested. Check your connection and sign-in.');message.textContent='Requested in Word; waiting for confirmation.';console.debug('Word navigation',id,'server request ms',Math.round(performance.now()-dispatch));const start=Date.now();let done=false;while(Date.now()-start<30000){await new Promise((resolve,reject)=>{const signal=abort.signal;const cancel=()=>{clearTimeout(timer);reject(new Error('Navigation was not confirmed. Word changed or disconnected.'));};const timer=setTimeout(()=>{signal.removeEventListener('abort',cancel);resolve();},1000);signal.addEventListener('abort',cancel,{once:true});});const receipt=await fetch(`/WriterWord/Navigation?bookId=${book}&instanceId=${selected.instanceId}&sessionId=${selected.sessionId}&navigationId=${id}`,{signal:abort.signal,cache:'no-store'});if(!receipt.ok)throw Error('Navigation confirmation unavailable.');const result=await receipt.json();if(result.state!=='requested'){console.debug('Word navigation',id,'confirmation ms',Math.round(performance.now()-dispatch),result.state);message.textContent=result.state==='completed'?(toParagraph?'Word confirmed navigation to the paragraph start.':'Word confirmed navigation.'):result.state==='failed'?'Word could not navigate. Your work was retained.':'Navigation expired or the document changed. No completion was confirmed.';done=true;break;}}if(!done)message.textContent='Word did not confirm navigation in time. Check the manuscript before retrying.';}catch(error){message.textContent=error.name==='AbortError'?'Navigation was not confirmed. Check Word before retrying.':error.message;}finally{busy=false;abort=null;if(packet)render(packet);requestStatus();}}
sync.addEventListener('click',async()=>{if(sync.disabled||!current)return;const selected={...current};syncPending={key:key(selected),started:Date.now()};sync.disabled=true;const body=new URLSearchParams({bookId:String(book),instanceId:selected.instanceId,sessionId:selected.sessionId,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});try{const response=await fetch('/manuscript/paragraphs/snapshot',{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)});const result=await response.json();if(!response.ok||response.redirected)throw Error(result.message||'Manuscript check unavailable.');if(syncPending)syncPending.requestId=result.requestId;message.textContent='Saved manuscript check requested; acceptance has not yet been confirmed. '+(result.message||'');}catch(error){syncPending=null;message.textContent=error.message||'Could not request manuscript check.';}finally{requestStatus();}});