Unify Writer ribbon context, immediate checklists and confirmed Word navigation
This commit is contained in:
parent
f228d4068f
commit
88f224a059
@ -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.LastPresenceUtc<TimeSpan.FromSeconds(2))continue;var key=$"{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{(ParagraphCapable(doc.Instance)||!doc.SceneId.HasValue?doc.Cursor:0)}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(15))continue;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CanAcknowledgeNavigation=acknowledgedNavigationInstances.Contains(doc.Instance),NavigationAcknowledgedId=doc.NavigationAcknowledgedId,NavigationResult=doc.NavigationResult,CaptureRequestId=doc.Capture?.RequestId,CaptureProgress=doc.Progress,ChapterIssue=ChapterIssue(doc),CanChapterSync=ChapterCapable(doc.Instance),CanParagraphSync=ParagraphCapable(doc.Instance),CanCapture=captureInstances.Contains(doc.Instance),WordRunning=true,WordSaved=doc.WordSaved,CursorStart=doc.Cursor,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc||(ChapterCapable(doc.Instance)&&reply.Revision!=doc.Revision)||doc.Authentication!=cloud.Status().AuthenticationContext)continue;if(ChapterCapable(doc.Instance)&&chapterWork.TryGetValue(doc.Session,out var currentChapters)&¤tChapters.Manifest!=null&&reply.ParagraphRevision>0&&reply.ParagraphRevision<currentChapters.Manifest.Revision)continue;doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;doc.ChapterProgress=reply.ChapterProgress;if(ChapterCapable(doc.Instance))ChapterCursorEvidence.Apply(doc,reply);else{doc.ChapterTitle=reply.ChapterTitle;doc.SceneTitle=reply.SceneTitle;}ObserveChapterPresence(doc,reply);}
|
||||
foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(2))continue;var key=$"{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{doc.NavigationAcknowledgedId}:{doc.NavigationResult}:{(ParagraphCapable(doc.Instance)||!doc.SceneId.HasValue?doc.Cursor:0)}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(acknowledgedNavigationInstances.Contains(doc.Instance)?2:15))continue;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CanAcknowledgeNavigation=acknowledgedNavigationInstances.Contains(doc.Instance),NavigationAcknowledgedId=doc.NavigationAcknowledgedId,NavigationResult=doc.NavigationResult,CaptureRequestId=doc.Capture?.RequestId,CaptureProgress=doc.Progress,ChapterIssue=ChapterIssue(doc),CanChapterSync=ChapterCapable(doc.Instance),CanParagraphSync=ParagraphCapable(doc.Instance),CanCapture=captureInstances.Contains(doc.Instance),WordRunning=true,WordSaved=doc.WordSaved,CursorStart=doc.Cursor,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc||(ChapterCapable(doc.Instance)&&reply.Revision!=doc.Revision)||doc.Authentication!=cloud.Status().AuthenticationContext)continue;if(ChapterCapable(doc.Instance)&&chapterWork.TryGetValue(doc.Session,out var currentChapters)&¤tChapters.Manifest!=null&&reply.ParagraphRevision>0&&reply.ParagraphRevision<currentChapters.Manifest.Revision)continue;doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;doc.ChapterProgress=reply.ChapterProgress;if(ChapterCapable(doc.Instance))ChapterCursorEvidence.Apply(doc,reply);else{doc.ChapterTitle=reply.ChapterTitle;doc.SceneTitle=reply.SceneTitle;}ObserveChapterPresence(doc,reply);}
|
||||
if(reply.ParagraphRevision>0&&!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;
|
||||
|
||||
@ -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");
|
||||
|
||||
@ -16,6 +16,7 @@ public sealed class WriterController(
|
||||
{
|
||||
public Task<IActionResult> 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<IActionResult>(RedirectToAction(nameof(Reflect),new{projectId,bookId,year,month,day}));
|
||||
if(!setup&&!journey&&workspace!=null)return Task.FromResult<IActionResult>(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<IActionResult> Workspaces(int? projectId,int? bookId,string? workspace=null)=>LoadDestination("Legacy",projectId,bookId,workspace);
|
||||
public Task<IActionResult> 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});
|
||||
|
||||
@ -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<AuthoringField> 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}";
|
||||
}
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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; }
|
||||
|
||||
@ -166,6 +166,12 @@
|
||||
<span class="pd-ribbon-group-label">@group.Label</span>
|
||||
</div>
|
||||
}
|
||||
@if(category.Key==selectedCategory && book!=null){
|
||||
<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>
|
||||
}
|
||||
@if (category.Key == selectedCategory)
|
||||
{
|
||||
<div class="pd-page-context" data-pwa-context-host hidden aria-label="Current page commands">
|
||||
@ -202,3 +208,5 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if(book!=null){<template data-word-fallback><partial name="~/Views/Writer/_WriterWord.cshtml" model="new WriterDashboardViewModel{BookID=book.BookID,ProjectID=book.ProjectID,Objective=new(){ChapterID=Model.WordChapterID,SceneID=Model.WordSceneID}}" /></template>}
|
||||
|
||||
@ -354,6 +354,7 @@
|
||||
<script src="~/js/application-toolbar.js" asp-append-version="true"></script>
|
||||
<script src="~/js/application-shell.js" asp-append-version="true"></script>
|
||||
}
|
||||
<script src="~/js/writer-word.js" asp-append-version="true" defer></script>
|
||||
<script src="~/js/native-companion-status.js" asp-append-version="true" defer></script>
|
||||
<script src="~/js/word-companion-presence.js" asp-append-version="true"></script>
|
||||
<script src="~/js/story-intelligence-global-progress.js" asp-append-version="true"></script>
|
||||
|
||||
@ -3,8 +3,9 @@
|
||||
<section class="writer3-authoring-card" data-authoring-card data-key="@Model.Key" data-kind="@Model.Kind">
|
||||
<div class="writer3-authoring-heading"><h3>@Model.Title</h3><button type="button" class="btn btn-sm btn-outline-secondary" data-authoring-edit aria-controls="@id" aria-expanded="false">@(add?"Add":"Edit")<span class="visually-hidden"> @Model.Title</span></button></div>
|
||||
<div data-authoring-display>
|
||||
@if(Model.Kind=="Checklist"){<label><input type="checkbox" data-checklist-toggle checked="@(Model.Value("IsCompleted")=="true")" /> @Model.Value("ItemText")</label>}
|
||||
@if(add){<p class="muted">Optional — keep a useful detail here when you need it.</p>}
|
||||
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){<p class="muted">Nothing recorded yet. Add this when it helps your writing.</p>}
|
||||
@foreach(var f in (Model.Kind=="Goals"?readable.Take(1):readable)){var value=Model.Value(f.Name);<div class="writer3-recorded-field">@if(f.Label!=Model.Title){<strong>@f.Label</strong>}@if(f.Type=="textarea"&&value.Length>280){<p>@value[..280]…</p><details><summary>Read complete text</summary><p>@value</p></details>}else{<p>@(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)</p>}</div>}
|
||||
|
||||
@ -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;
|
||||
}
|
||||
<header class="writer3-header" data-pwa-task>
|
||||
<header class="writer3-header @(home||Model.Destination=="Dashboard"?"":"visually-hidden")" 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>}
|
||||
|
||||
@ -10,8 +10,9 @@
|
||||
@if(Model.SceneID.HasValue){
|
||||
<h2>Notes and things to remember</h2>
|
||||
<ul class="writer3-reminder-preview">@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)){<li>@{var text=section.Kind=="Note"?section.Value("NoteText"):section.Value("ItemText");}@(text.Length>240?text[..240]+"…":text)</li>}</ul>
|
||||
<details class="writer3-authoring-details"><summary>All scene notes, reminders and working details</summary>
|
||||
@foreach(var section in Model.Sections.Where(x=>x.Kind is "Note" or "Checklist")){<partial name="~/Views/Writer/_AuthoringSection.cshtml" model="section" />}
|
||||
<h3>Scene checklist</h3>@foreach(var item in Model.Sections.Where(x=>x.Kind=="Checklist")){<partial name="_AuthoringSection" model="item" />}
|
||||
<details class="writer3-authoring-details"><summary>Scene notes, reminders and working details</summary>
|
||||
@foreach(var section in Model.Sections.Where(x=>x.Kind=="Note")){<partial name="~/Views/Writer/_AuthoringSection.cshtml" model="section" />}
|
||||
<partial name="~/Views/Writer/_AuthoringSection.cshtml" model="@(Model.Sections.First(x=>x.Kind=="Workflow"))" />
|
||||
<p class="writer3-caption">Saving working details does not change scene revision state or checklist completion. Recorded working words are separate from accepted manuscript counts.</p>
|
||||
</details>
|
||||
|
||||
@ -6,10 +6,8 @@
|
||||
<label data-word-choose hidden>Choose the manuscript in Word<select class="form-select" data-word-document><option value="">Choose a document</option></select></label>
|
||||
<p class="writer3-caption" data-word-position>Word position has not been verified.</p>
|
||||
<p class="writer3-caption" data-word-freshness>Your latest changes have not yet been confirmed in PlotDirector.</p>
|
||||
<div class="button-row">
|
||||
@if(reviewing){<button type="button" class="btn btn-sm btn-outline-secondary" data-word-paragraph disabled>Open paragraph in Word</button>}
|
||||
@if(focus?.ChapterID.HasValue==true){<button type="button" class="btn btn-sm btn-outline-primary" data-word-navigate disabled>Open this chapter in Word</button>@if(focus.SceneID.HasValue){<button type="button" class="btn btn-sm btn-outline-secondary" data-word-scene disabled>Open this scene in Word</button>}}
|
||||
|
||||
<div class="button-row" data-word-legacy-navigation hidden>
|
||||
<button type="button" data-word-paragraph disabled>Paragraph in Word</button><button type="button" data-word-navigate disabled>Chapter in Word</button><button type="button" data-word-scene disabled>Scene in Word</button>
|
||||
</div>
|
||||
<details><summary>Connection and update options</summary><p class="writer3-caption">@(reviewing?"Review selection":"Working focus") and Word position can differ. Navigation does not save Word or change your session. Reader shows accepted content.</p><div class="button-row"><button type="button" class="btn btn-sm btn-outline-secondary" data-word-sync disabled>Check saved manuscript</button><button type="button" class="btn btn-sm btn-outline-secondary" data-word-check>Check connection & updates</button></div></details>
|
||||
<p data-word-command role="status" aria-live="polite"></p>
|
||||
|
||||
@ -7,7 +7,7 @@
|
||||
@if(focus != null && !editing){
|
||||
<h2>@(focus.SceneTitle ?? focus.ChapterTitle ?? "Your manuscript")</h2><p class="writer3-focus-kind">@focus.Activity</p>@if(focus.ChapterID.HasValue){<p class="writer3-caption">Chapter: @focus.ChapterTitle</p>}@if(!string.IsNullOrWhiteSpace(focus.Intention)){<p class="review-recorded">@focus.Intention</p>}<p>Keep your intention here; write manuscript prose in Word.</p>
|
||||
<div class="button-row">
|
||||
@if(focus.SceneID.HasValue){<a class="btn btn-primary writer3-cta" asp-controller="Scenes" asp-action="Edit" asp-route-id="@focus.SceneID">Open current scene <span aria-hidden="true">→</span></a>}
|
||||
@if(focus.SceneID.HasValue){<a class="btn btn-primary writer3-cta" asp-controller="Scenes" asp-action="Edit" asp-route-id="@focus.SceneID">Open selected scene workspace <span aria-hidden="true">→</span></a>}
|
||||
else if(focus.ChapterID.HasValue){<a class="btn btn-primary writer3-cta" asp-action="Chapter" asp-route-id="@focus.ChapterID">Open current chapter <span aria-hidden="true">→</span></a>}
|
||||
else{<a class="btn btn-primary writer3-cta" asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID" asp-fragment="chapters">Open your chapters <span aria-hidden="true">→</span></a>}
|
||||
</div>
|
||||
@ -17,7 +17,7 @@
|
||||
}
|
||||
|
||||
</div>
|
||||
<button type="button" class="btn btn-link" hidden="@(focus==null||editing)" data-change-focus>Change focus</button>
|
||||
<button type="button" class="btn btn-link" hidden="@(focus==null||editing)" data-change-focus>Change activity, chapter or scene</button><p class="writer3-caption">Focus selects your working context. It does not change the manuscript or start recording.</p>
|
||||
<div id="objective-setup" hidden="@(focus!=null&&!editing)">@if(focus==null||editing){<partial name="_WriterFocusForm" model="Model" />}</div>
|
||||
<div class="writer3-authoring" data-writer-authoring data-inspect-url="@(focus?.ChapterID.HasValue==true?Url.Action("Inspect","WriterAuthoring",new{bookId=Model.BookID,chapterId=focus.ChapterID,sceneId=focus.SceneID}):null)" aria-live="polite"><p>Loading your recorded intentions…</p></div>
|
||||
@if(!Model.ActivityIsPrivate){
|
||||
|
||||
@ -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));
|
||||
|
||||
@ -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));
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user