From 88f224a059b0b2102e4b5f942637f0cd29372cae Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Wed, 18 Nov 2026 21:08:08 +0000 Subject: [PATCH] Unify Writer ribbon context, immediate checklists and confirmed Word navigation --- .../Agent/TrayCoordinator.cs | 2 +- PlotLine.Tests/WriterNavigationTests.cs | 4 ++-- PlotLine/Controllers/WriterController.cs | 3 ++- PlotLine/Models/WriterAuthoring.cs | 2 +- PlotLine/Services/ApplicationNavigation.cs | 2 ++ PlotLine/Services/WriterNavigation.cs | 4 ++-- .../ViewModels/ApplicationNavigationViewModel.cs | 2 ++ PlotLine/Views/Shared/_ApplicationShell.cshtml | 8 ++++++++ PlotLine/Views/Shared/_Layout.cshtml | 1 + PlotLine/Views/Writer/_AuthoringSection.cshtml | 3 ++- PlotLine/Views/Writer/_Writer3Header.cshtml | 2 +- PlotLine/Views/Writer/_WriterAuthoring.cshtml | 5 +++-- PlotLine/Views/Writer/_WriterWord.cshtml | 6 ++---- PlotLine/Views/Writer/_WriterWrite.cshtml | 4 ++-- PlotLine/wwwroot/js/writer-authoring.js | 7 +++++++ PlotLine/wwwroot/js/writer-word.js | 14 +++++++++----- 16 files changed, 47 insertions(+), 22 deletions(-) diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs index 73023702..eb33d2b8 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs @@ -165,7 +165,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway public async Task Heartbeat(CancellationToken cancellation) { while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromMilliseconds(500),cancellation);var available=Documents.Where(d=>d.Authentication==cloud.Status().AuthenticationContext&&cloud.Status().Health?.Authentication=="verified").ToArray(); - foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc0&&reply.ParagraphRevision0&&reply.ParagraphRevision0&&!ChapterCapable(doc.Instance))lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext){doc.ChapterId=reply.ChapterId;doc.SceneId=reply.SceneId;} if(reply.Navigation is {Kind:"wizard-capture",BookId:>0} requested&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Book==0){await cloud.CheckConnection();lock(gate){if(doc.Book==0&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext&&cloud.Allows(doc.Authentication,requested.BookId)&&documents.GetValueOrDefault(doc.Session)==doc){doc.Book=requested.BookId;cloud.RememberBinding(doc.Manuscript,doc.Book,doc.Authentication);doc.LastPresenceKey="";}}} if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision){if((reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")&&captureInstances.Contains(doc.Instance)&&(reply.Navigation.BookId==0||reply.Navigation.BookId==doc.Book)&&cloud.Allows(doc.Authentication,doc.Book)){if(uploading!=0||documents.Values.Any(d=>d.Capture!=null)){_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);continue;}var retained=doc.RetryCapture;var reusable=retained!=null&&doc.RetryAuthentication==doc.Authentication&&doc.RetryBook==doc.Book&&retained.ManuscriptId==doc.Manuscript&&retained.Revision==doc.Revision&&retained.ParagraphTracking==reply.Navigation.ParagraphTracking; diff --git a/PlotLine.Tests/WriterNavigationTests.cs b/PlotLine.Tests/WriterNavigationTests.cs index b522d5b7..5d636107 100644 --- a/PlotLine.Tests/WriterNavigationTests.cs +++ b/PlotLine.Tests/WriterNavigationTests.cs @@ -37,9 +37,9 @@ internal static class WriterNavigationTests Check(model.BookID==13&&model.Objective==null&&model.WorkingContext?.Working==null,"destination "+destination+" never carries a focus into another book"); Check(await load(999) is NotFoundResult,"destination "+destination+" refuses unavailable book"); } - Check((await controller.Index(7,12,workspace:"Revision") is RedirectToActionResult queueAlias&&queueAlias.ActionName=="Workspaces"&&(string?)queueAlias.RouteValues!["workspace"]=="Revision")&&((ViewResult)await controller.Index(7,12,journey:true)).ViewName=="Legacy","legacy query routes still reach their actual workspaces/calendar"); + Check((await controller.Index(7,12,workspace:"Revision") is RedirectToActionResult queueAlias&&queueAlias.ActionName=="Workspaces"&&(string?)queueAlias.RouteValues!["workspace"]=="Revision")&&(await controller.Index(7,12,journey:true) is RedirectToActionResult reflection&&reflection.ActionName=="Reflect"),"legacy query routes still reach their actual workspaces/calendar"); Check(((WriterDashboardViewModel)((ViewResult)await controller.Index(7,12,setup:true)).Model!).Destination=="Write","old objective setup URL reaches Write"); - Check(((ViewResult)await controller.Workspaces(7,12)).ViewName=="Legacy"&&((ViewResult)await controller.Journey(7,12)).ViewName=="Legacy"&&((ViewResult)await controller.Overview(7,12)).ViewName=="Legacy","full legacy desk, Journey and Workspaces remain rendered, not retired"); + Check(((ViewResult)await controller.Workspaces(7,12)).ViewName=="Legacy"&&(controller.Journey(7,12) is RedirectToActionResult journey&&journey.ActionName=="Reflect")&&((ViewResult)await controller.Overview(7,12)).ViewName=="Legacy","legacy desk and queues remain available; Journey redirects to Reflect"); allowed=false;Check(await controller.Write(null,12) is NotFoundResult&&await controller.Explore(null,12) is NotFoundResult,"book-only new route checks access before metadata"); foreach(var destination in WriterNavigation.Destinations){ Check(WriterNavigation.BookSwitchAction(destination)==destination,"book switching retains "+destination+" without chapter parameters"); diff --git a/PlotLine/Controllers/WriterController.cs b/PlotLine/Controllers/WriterController.cs index 7c864b00..0dd4a2b1 100644 --- a/PlotLine/Controllers/WriterController.cs +++ b/PlotLine/Controllers/WriterController.cs @@ -16,6 +16,7 @@ public sealed class WriterController( { public Task Index(int? projectId, int? bookId = null, string? workspace = null, bool journey = false, int? year = null, int? month = null, DateTime? day = null, bool setup = false) { + if(journey)return Task.FromResult(RedirectToAction(nameof(Reflect),new{projectId,bookId,year,month,day})); if(!setup&&!journey&&workspace!=null)return Task.FromResult(RedirectToAction(nameof(Workspaces),new{projectId,bookId,workspace})); return LoadDestination(setup ? "Write" : journey ? "Legacy" : "Home", projectId, bookId, workspace, journey, year, month, day); } @@ -113,7 +114,7 @@ public sealed class WriterController( return View(destination == "Home" ? "Index" : destination == "Legacy" ? "Legacy" : "Destination", model); } public Task Workspaces(int? projectId,int? bookId,string? workspace=null)=>LoadDestination("Legacy",projectId,bookId,workspace); - public Task Journey(int? projectId,int? bookId,int? year=null,int? month=null,DateTime? day=null)=>LoadDestination("Legacy",projectId,bookId,journey:true,year:year,month:month,day:day); + public IActionResult Journey(int? projectId,int? bookId,int? year=null,int? month=null,DateTime? day=null)=>RedirectToAction(nameof(Reflect),new{projectId,bookId,year,month,day}); public IActionResult DisplaySetup(int? projectId,int? bookId)=>Redirect(Url.Action(nameof(Overview),new{projectId,bookId})+"#display-setup"); [HttpGet("Write"),HttpGet("Write/Index")] public IActionResult LegacyWrite(int? projectId,int? bookId)=>RedirectToAction(nameof(Index),new{projectId,bookId}); diff --git a/PlotLine/Models/WriterAuthoring.cs b/PlotLine/Models/WriterAuthoring.cs index 050d4a08..052a7d9b 100644 --- a/PlotLine/Models/WriterAuthoring.cs +++ b/PlotLine/Models/WriterAuthoring.cs @@ -8,7 +8,7 @@ public sealed class AuthoringSection public int BookID {get;set;} public int ChapterID {get;set;} public int? SceneID {get;set;} public IReadOnlyList<(string Value,string Label)> Purposes {get;set;}=[]; public IReadOnlyList<(string Value,string Label)> NoteTypes {get;set;}=[]; public IReadOnlyList Fields=>AuthoringSchema.Fields(Kind); - public string Title=>Kind switch{"Chapter"=>"Chapter purpose and summary","Goals"=>"What should this chapter accomplish?","Scene"=>"What needs to happen in this scene?","Workflow"=>"Working details and blockers","Note"=>"Scene note","AddNote"=>"Add a scene note","Checklist"=>"Reminder","AddChecklist"=>"Add something to remember",_=>Kind}; + public string Title=>Kind switch{"Chapter"=>"Chapter purpose and summary","Goals"=>"What should this chapter accomplish?","Scene"=>"What needs to happen in this scene?","Workflow"=>"Working details and blockers","Note"=>"Scene note","AddNote"=>"Add a scene note","Checklist"=>"Scene checklist item","AddChecklist"=>"Add a checklist item",_=>Kind}; public string Value(string key){if(Kind.StartsWith("Add",StringComparison.Ordinal))return key=="SceneNoteTypeID"?NoteTypes.FirstOrDefault().Value??"":"";using var json=JsonDocument.Parse(Data);if(json.RootElement.ValueKind!=JsonValueKind.Object||!json.RootElement.TryGetProperty(key,out var v)||v.ValueKind==JsonValueKind.Null)return "";return v.ValueKind==JsonValueKind.True?"true":v.ValueKind==JsonValueKind.False?"false":v.ToString();} public string Key=>$"{Kind}-{EntityID}"; } diff --git a/PlotLine/Services/ApplicationNavigation.cs b/PlotLine/Services/ApplicationNavigation.cs index b09d86be..07a34ab0 100644 --- a/PlotLine/Services/ApplicationNavigation.cs +++ b/PlotLine/Services/ApplicationNavigation.cs @@ -55,6 +55,8 @@ public sealed class ApplicationNavigation(IProjectRepository projects, IBookRepo result.Project = project; result.Books = projectBooks.Where(x => !x.IsArchived).ToList(); result.Book = result.Books.FirstOrDefault(x => x.BookID == selectedBookId); + result.WordChapterID = (model as WriterDashboardViewModel)?.ReviewReader?.Chapter?.ChapterID ?? ((model as WriterDashboardViewModel)?.Destination=="Write" ? (model as WriterDashboardViewModel)?.Objective?.ChapterID : null) ?? PositiveId(Property(model,"ChapterID")) ?? PositiveId(Property(Property(model,"Scene"),"ChapterID")); + result.WordSceneID = ((model as WriterDashboardViewModel)?.Destination=="Write" ? (model as WriterDashboardViewModel)?.Objective?.SceneID : null) ?? PositiveId(Property(model,"SceneID")) ?? PositiveId(Property(Property(model,"Scene"),"SceneID")); return result; } diff --git a/PlotLine/Services/WriterNavigation.cs b/PlotLine/Services/WriterNavigation.cs index 50810701..e6cf1c68 100644 --- a/PlotLine/Services/WriterNavigation.cs +++ b/PlotLine/Services/WriterNavigation.cs @@ -36,10 +36,10 @@ public static class WriterNavigation var context = destination switch { "Write" => new RibbonGroup("Current work", new("Chapters","bible","Books","Details","book"), new("Scene queues","threads","Writer","Workspaces","writerBook"), new("Writing Dashboard","metrics","Writer","Dashboard","writerBook"), new("Writing Plan","calendar","Writer","WritingPlans","writerBook")), - "Explore" => new RibbonGroup("Story exploration", investigation ? new("Guided investigation","point","WriterInvestigations","Index","writerBook") : new("Problem Solver","point","WritingProblems","Index","global"), new("Story overview","timeline","Timeline","Index","writerBook")), + "Explore" => new RibbonGroup("Story exploration", new("Guided investigation","point","Writer","Explore","writerBook"), new("Story overview","timeline","Timeline","Index","writerBook")), "Plan" => new RibbonGroup("Writing plans", new("Writing Plan","calendar","Writer","WritingPlans","writerBook"), new("Schedule Preview","calendar","Writer","SchedulePreview","writerBook")), "Review" => new RibbonGroup("Reading & review", new("Reading mode","bible","ManuscriptReader","Index","writerBook"), new("Writing Dashboard","metrics","Writer","Dashboard","writerBook")), - "Reflect" => new RibbonGroup("Writing history", new("Writing Journey","calendar","Writer","Journey","writerBook"), new("Reports","metrics","WritingActivity","Index","writerBook",OwnerOnly:true)), + "Reflect" => new RibbonGroup("Writing history", new RibbonCommand("Reports","metrics","WritingActivity","Index","writerBook",OwnerOnly:true)), _ => new RibbonGroup("Your writing", new RibbonCommand("Writing Dashboard","metrics","Writer","Dashboard","writerBook")) }; groups.Add(context); diff --git a/PlotLine/ViewModels/ApplicationNavigationViewModel.cs b/PlotLine/ViewModels/ApplicationNavigationViewModel.cs index d0e62a06..0b5400ae 100644 --- a/PlotLine/ViewModels/ApplicationNavigationViewModel.cs +++ b/PlotLine/ViewModels/ApplicationNavigationViewModel.cs @@ -4,6 +4,8 @@ namespace PlotLine.ViewModels; public sealed class ApplicationNavigationViewModel { + public int? WordChapterID { get; set; } + public int? WordSceneID { get; set; } public bool IsAdmin { get; set; } public bool ShowCompanionPresence { get; set; } public int FeatureRequestAttentionCount { get; set; } diff --git a/PlotLine/Views/Shared/_ApplicationShell.cshtml b/PlotLine/Views/Shared/_ApplicationShell.cshtml index 10a73558..38bf5977 100644 --- a/PlotLine/Views/Shared/_ApplicationShell.cshtml +++ b/PlotLine/Views/Shared/_ApplicationShell.cshtml @@ -166,6 +166,12 @@ @group.Label } + @if(category.Key==selectedCategory && book!=null){ +
+ @foreach(var target in new[]{("chapter","Chapter in Word","bible"),("scene","Scene in Word","threads"),("paragraph","Paragraph in Word","point")}){ + + }
Word navigation
+ } @if (category.Key == selectedCategory) { + +@if(book!=null){} diff --git a/PlotLine/Views/Shared/_Layout.cshtml b/PlotLine/Views/Shared/_Layout.cshtml index bd13192f..35108567 100644 --- a/PlotLine/Views/Shared/_Layout.cshtml +++ b/PlotLine/Views/Shared/_Layout.cshtml @@ -354,6 +354,7 @@ } + diff --git a/PlotLine/Views/Writer/_AuthoringSection.cshtml b/PlotLine/Views/Writer/_AuthoringSection.cshtml index 04601cdf..1be302ba 100644 --- a/PlotLine/Views/Writer/_AuthoringSection.cshtml +++ b/PlotLine/Views/Writer/_AuthoringSection.cshtml @@ -3,8 +3,9 @@

@Model.Title

+ @if(Model.Kind=="Checklist"){} @if(add){

Optional — keep a useful detail here when you need it.

} - else{ + else if(Model.Kind!="Checklist"){ var readable=Model.Fields.Where(x=>!string.IsNullOrWhiteSpace(Model.Value(x.Name)) && Model.Value(x.Name)!="false").ToArray(); @if(readable.Length==0){

Nothing recorded yet. Add this when it helps your writing.

} @foreach(var f in (Model.Kind=="Goals"?readable.Take(1):readable)){var value=Model.Value(f.Name);
@if(f.Label!=Model.Title){@f.Label}@if(f.Type=="textarea"&&value.Length>280){

@value[..280]…

Read complete text

@value

}else{

@(f.Type=="checkbox"?"Yes":f.Type=="purpose"?Model.Purposes.FirstOrDefault(x=>x.Value==value).Label??"Recorded purpose":f.Type=="noteType"?Model.NoteTypes.FirstOrDefault(x=>x.Value==value).Label??"Recorded note":value)

}
} diff --git a/PlotLine/Views/Writer/_Writer3Header.cshtml b/PlotLine/Views/Writer/_Writer3Header.cshtml index 2cec71b1..9d09af2d 100644 --- a/PlotLine/Views/Writer/_Writer3Header.cshtml +++ b/PlotLine/Views/Writer/_Writer3Header.cshtml @@ -4,7 +4,7 @@ var title = string.IsNullOrWhiteSpace(Model.Book?.BookDisplayTitle) ? "Choose a book" : Model.Book.BookDisplayTitle; var heading = home ? title : Model.Destination == "Dashboard" ? "Writing Dashboard" : Model.Destination; } -
+
@if(home&&!string.IsNullOrWhiteSpace(Model.Book?.CoverThumbnailPath)){ Cover of @title }else if(home){} diff --git a/PlotLine/Views/Writer/_WriterAuthoring.cshtml b/PlotLine/Views/Writer/_WriterAuthoring.cshtml index 11a3688f..f380ae5a 100644 --- a/PlotLine/Views/Writer/_WriterAuthoring.cshtml +++ b/PlotLine/Views/Writer/_WriterAuthoring.cshtml @@ -10,8 +10,9 @@ @if(Model.SceneID.HasValue){

Notes and things to remember

    @foreach(var section in Model.Sections.Where(x=>x.Kind=="Note" && x.Value("IsResolved")!="true" || x.Kind=="Checklist" && x.Value("IsCompleted")!="true").OrderByDescending(x=>x.Value("IsPinned")=="true").ThenBy(x=>int.TryParse(x.Value("SortOrder"),out var order)?order:int.MaxValue).Take(3)){
  • @{var text=section.Kind=="Note"?section.Value("NoteText"):section.Value("ItemText");}@(text.Length>240?text[..240]+"…":text)
  • }
-
All scene notes, reminders and working details - @foreach(var section in Model.Sections.Where(x=>x.Kind is "Note" or "Checklist")){} +

Scene checklist

@foreach(var item in Model.Sections.Where(x=>x.Kind=="Checklist")){} +
Scene notes, reminders and working details + @foreach(var section in Model.Sections.Where(x=>x.Kind=="Note")){}

Saving working details does not change scene revision state or checklist completion. Recorded working words are separate from accepted manuscript counts.

diff --git a/PlotLine/Views/Writer/_WriterWord.cshtml b/PlotLine/Views/Writer/_WriterWord.cshtml index c0cf1c43..492fd4ec 100644 --- a/PlotLine/Views/Writer/_WriterWord.cshtml +++ b/PlotLine/Views/Writer/_WriterWord.cshtml @@ -6,10 +6,8 @@

Word position has not been verified.

Your latest changes have not yet been confirmed in PlotDirector.

-
- @if(reviewing){} - @if(focus?.ChapterID.HasValue==true){@if(focus.SceneID.HasValue){}} - +
Connection and update options

@(reviewing?"Review selection":"Working focus") and Word position can differ. Navigation does not save Word or change your session. Reader shows accepted content.

diff --git a/PlotLine/Views/Writer/_WriterWrite.cshtml b/PlotLine/Views/Writer/_WriterWrite.cshtml index d71b7a63..e93e53b2 100644 --- a/PlotLine/Views/Writer/_WriterWrite.cshtml +++ b/PlotLine/Views/Writer/_WriterWrite.cshtml @@ -7,7 +7,7 @@ @if(focus != null && !editing){

@(focus.SceneTitle ?? focus.ChapterTitle ?? "Your manuscript")

@focus.Activity

@if(focus.ChapterID.HasValue){

Chapter: @focus.ChapterTitle

}@if(!string.IsNullOrWhiteSpace(focus.Intention)){

@focus.Intention

}

Keep your intention here; write manuscript prose in Word.

- @if(focus.SceneID.HasValue){Open current scene } + @if(focus.SceneID.HasValue){Open selected scene workspace } else if(focus.ChapterID.HasValue){Open current chapter } else{Open your chapters }
@@ -17,7 +17,7 @@ }
- +

Focus selects your working context. It does not change the manuscript or start recording.

Loading your recorded intentions…

@if(!Model.ActivityIsPrivate){ diff --git a/PlotLine/wwwroot/js/writer-authoring.js b/PlotLine/wwwroot/js/writer-authoring.js index 66b24cdf..83ff6a6f 100644 --- a/PlotLine/wwwroot/js/writer-authoring.js +++ b/PlotLine/wwwroot/js/writer-authoring.js @@ -15,6 +15,13 @@ edit.addEventListener('click',()=>{card.querySelector('[data-authoring-status]').textContent='';form.hidden=false;display.hidden=true;edit.hidden=true;edit.setAttribute('aria-expanded','true');focusEditor(card);}); form.querySelector('[data-authoring-cancel]').addEventListener('click',()=>{if(form.dataset.busy==='true')return;form.reset();card.querySelector('[data-authoring-status]').textContent='';form.dataset.dirty='false';form.hidden=true;display.hidden=false;edit.hidden=false;edit.setAttribute('aria-expanded','false');error.hidden=true;edit.focus();}); form.querySelector('[data-authoring-reload]').addEventListener('click',async()=>{if(!confirm('Reload the recorded version? Copy any text you want to keep first.'))return;try{const doc=await read();replaceCard(card,doc);}catch{error.textContent='Could not reload. Your text is still here.';}}); + card.querySelector('[data-checklist-toggle]')?.addEventListener('change',async event=>{ + const box=event.target;if(form.dataset.busy==='true'){box.checked=!box.checked;return;}const prior=!box.checked;box.disabled=true;form.dataset.busy='true'; + const data=new FormData(form);for(const input of form.querySelectorAll('input[type=checkbox]'))data.set(input.name,String(input.name==='IsCompleted'?box.checked:input.checked)); + try{const response=await fetch(form.action,{method:'POST',body:data});if(!response.ok)throw Error();const doc=await read();replaceCard(card,doc);} + catch{box.checked=prior;card.querySelector('[data-authoring-status]').textContent='Completion could not be refreshed. Reload the recorded version before retrying.';box.disabled=true;form.querySelector('[data-authoring-reload]').hidden=false;} + finally{form.dataset.busy='false';} + }); form.addEventListener('submit',async e=>{ e.preventDefault();if(form.dataset.busy==='true')return;form.dataset.busy='true';const save=form.querySelector('[data-authoring-save]'),cancel=form.querySelector('[data-authoring-cancel]'),reload=form.querySelector('[data-authoring-reload]');let committed=false;save.disabled=true;cancel.disabled=true;reload.disabled=true;error.hidden=true; const data=new FormData(form);for(const input of form.querySelectorAll('input[type=checkbox]'))data.set(input.name,String(input.checked)); diff --git a/PlotLine/wwwroot/js/writer-word.js b/PlotLine/wwwroot/js/writer-word.js index e9a4cecd..f77cbbc0 100644 --- a/PlotLine/wwwroot/js/writer-word.js +++ b/PlotLine/wwwroot/js/writer-word.js @@ -1,12 +1,12 @@ // Consumes the existing native presence/status stream. No second background poller or global selection. -(()=>{'use strict';const root=document.querySelector('[data-writer-word]');if(!root)return; -const book=Number(root.dataset.bookId),chapter=Number(root.dataset.chapterId),scene=Number(root.dataset.sceneId),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]'); +(()=>{'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; const verified=l=>(packet?.verifiedPositions||[]).find(p=>key(p)===key(l)); const requestStatus=()=>window.dispatchEvent(new Event('plotdirector:refresh-word-status')); -function render(data){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; +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; if(old&&(!current||key(old)!==key(current)||old.revision!==current.revision||old.manuscriptId!==current.manuscriptId)&&busy){abort?.abort();message.textContent='Word document changed or disconnected. Navigation was not confirmed.';} if(syncPending&&(!current||syncPending.key!==key(current)||Date.now()-syncPending.started>120000||(syncPending.requestId&¤t.paragraphTransfer?.requestId===syncPending.requestId&&['accepted','needs-review','failed','cancelled'].includes(current.paragraphTransfer.state))))syncPending=null; const identity=current&&data.canonical?.manuscriptID===current.manuscriptId;const observed=current&&verified(current); @@ -17,12 +17,16 @@ 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.'; -if(paragraphButton)paragraphButton.disabled ||= !root.dataset.paragraphId; +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&¶ms.get('wordInstanceId')===current.instanceId&¶ms.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)); -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();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.';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'){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();}} +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'});}); + +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();}}); paragraphButton?.addEventListener('click',()=>void navigate(false,true));window.addEventListener('review-reference-changed',()=>{if(packet)render(packet);}); nav?.addEventListener('click',()=>void navigate(false));sceneNav?.addEventListener('click',()=>void navigate(true));