diff --git a/Docs/Writer/Unified-Manuscript-Focus-20261123.md b/Docs/Writer/Unified-Manuscript-Focus-20261123.md new file mode 100644 index 00000000..6cba58da --- /dev/null +++ b/Docs/Writer/Unified-Manuscript-Focus-20261123.md @@ -0,0 +1,64 @@ +# Unified manuscript focus — implementation and qualification + +Development only, 23 November 2026. Existing feature branch: `codex/word-companion-native-phase1-20261104`. The application commit, release directory, hashes and post-deployment results are recorded in the deployment evidence linked below. + +## Audit and architectural choice + +Previously, `NarrativeFocus` stored personal chapter/scene navigation, with browser storage/focus events supplying recovery. Review's chapter GET could change that state. Context principally followed native/Office presence and its navigation endpoint requested a Word command, which made it ineffective without Word. Review's paragraph selection updated review tools and the explicit Word target, but did not publish a common manuscript position. + +Context already owned one native-presence SignalR connection per window, independent cached tabs, split panes, layout persistence, window identity and duplicate-window detection. Its invalidation handler already allowed an earlier-scene change to invalidate later-scene projections; it must remain independent of navigation. Snapshot windows previously skipped connection setup. The main application already had a shared native-presence connection, and the native tray Companion already had a validated command queue, asynchronous agent wake notifications, exact document sessions and acknowledgements. + +The implementation extends these paths. It does not introduce another hub, Context connection, manuscript copy, editor owner, focus polling loop or Intent surface. Existing content/status checks remain. The current Windows VSTO/tray architecture is the Word implementation target; the older Office.js task-pane shell remains unchanged and is not advertised as a shared-focus client. + +## Server contract + +Forward-only migrations **314–316** extend the existing `NarrativeFocus` row with canonical manuscript/paragraph and originating-window IDs; add a per-origin sequence replay ledger; replace implicit objective seeding and read-time redirection; and resolve Word positions from exact-session verified chapter evidence. Backup `/var/opt/mssql/backup/shared-manuscript-focus-20261123T125506Z.bak` completed with COPY_ONLY/CHECKSUM and passed VERIFYONLY before migration. VERIFYONLY is not a restore test. + +`GET /NarrativeFocus/Shared?projectID=…&bookID=…` retrieves authoritative focus. Antiforgery-protected POSTs to `/NarrativeFocus/Shared/Publish`, `/Resolve` and `/Validate` accept existing identifiers. `Resolve` performs held local navigation; `Validate` checks a retained reference; neither publishes. Every operation verifies active authenticated access, project/book membership, canonical manuscript identity and chapter/scene/paragraph compatibility in stored procedures accessed through Dapper. Navigation remains available to read-only subscription accounts. + +The packet contains `ProjectID`, `BookID`, `ManuscriptID`, `ChapterID`, optional `SceneID`/`ParagraphID`, `OriginWindowID`, `Version`, `IsValid` and `Changed`. It contains no prose, Word offsets or contextual datasets. The server locks the existing focus row and assigns increasing revisions atomically. Different clients are ordered by accepted server revisions, without client timestamps. Duplicate/older per-window sequences and unchanged effective targets do not create another revision. A stale stored reference is returned as invalid, without silently moving it. + +`ManuscriptFocusChanged` uses the existing authenticated `NativeCompanionPresenceHub.UserGroup`. `ManuscriptFocusDelivery` reports unavailable Word mapping without blocking other clients. Browser clients scope-filter messages, reject obsolete/duplicate revisions, serialize rapid local intent and recover on connect/reconnect. Ordinary GETs, refreshes, passive observations and received navigation do not publish. Existing explicit browser navigation delegates to the coordinator; server GET hooks no longer write focus. + +A future editor can use the same identifier-only contract and existing authenticated transport without changing manuscript content ownership. + +## Clients and Hold + +Review publishes deliberate paragraph clicks, paragraph keyboard navigation and chapter/scene selectors, including when Word is closed. Accepted content remains authoritative. Incoming focus uses the existing partial chapter/scene positioning pipeline, preserves open editors and review tools, and explains missing precise paragraph/scene mapping before showing a deterministic scene/chapter fallback. Scrolling does not publish. + +Context dropdown, Previous, Next and Go to Focus use shared focus directly, without a Word navigation request. Each window retains its panes, tools, divider, cached tab state and layout. Snapshot windows also keep data notifications. Focus changes only invalidate panels whose scope changed. Data invalidation is independent of Hold and conservatively refreshes affected visible relationship/character panels across scenes; hidden panels are marked stale until activated. Structural invalidation retains the held reference and offers another local selection or Release Hold. + +Browser Hold is stored in session storage under authenticated-user/window identity, separately from global book preferences. An ordinary refresh retains Hold and local position. Existing Context identity arbitration plus browser identity claims prevent duplicated storage from sharing Hold. New windows default to Follow. Release obtains current authoritative focus, then follows it; it never publishes the held position. With no valid shared focus, it retains the local position and follows without creating one. Failed recovery retains Hold. + +The static Hold control and status appear in Review/application ribbons and Context. Hold remains visible when the installed PWA compacts Previous/Go/Next into its existing menu. Labels explicitly say Following/Held and Release Hold; colour is supplementary. + +Native Word adds Hold/Follow to the existing ribbon and uses a distinct state/identity for each actual Word window. The adapter distinguishes foreground mouse/navigation-key selection events from passive observations and suppresses incoming-navigation publication. Deliberate observations pass through existing framed IPC and native presence, then resolve canonical paragraph IDs using saved, fresh, exact-session verified chapter positions. Existing agent wake/command/receipt delivery supplies background following. Shared commands use `Window.ScrollIntoView`, not `Select`, `Activate` or a foreground-window call; editing selection/content ownership is retained. Unmapped, unsaved and busy states are explicit. Word Outline view cannot use this API and requires changing view before retrying ([Microsoft API contract](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.window.scrollintoview?view=word-pia)). Window state rejects old/duplicate deliveries and Release can catch the same window's own previously published shared position. + +Explicit Open in Word controls are retained, including paragraph navigation: physical native replacement qualification is not complete, so removing these controls would be premature. They remain useful for unsupported/disconnected/held/unmapped Word sessions and opening the manuscript. Shared paragraph/Context selection never automatically launches Word. + +## Verification + +- Solution build: zero warnings/errors; full executable regression harness: **786 passing checks**. +- Native portable regression harness: **320 passing checks**, including the dedicated per-window Hold/revision cases. These exercise managed production logic and IPC, not Word COM. +- Development rollback-only SQL tests cover no initial publication, canonical paragraph resolution, monotonic revisions, unchanged-target suppression, replay rejection, held resolution without mutation, canonical cross-chapter stepping, invalid references, verified Word offsets, exact-session isolation and authorisation. The updated historical six-phase SQL regression also passes with no implicit seed/redirection. +- Sixteen real concurrent SQL connections verify contiguous unique accepted revisions and a final durable read equal to the highest revision. Real coordinator/SQL/native-queue integration also verifies Word-only publication, browser-to-Word chapter crossing, passive suppression, Hold/release, failed receipts, unsaved documents and exact-session isolation through a recording transport. +- Real authenticated Chromium and installed standalone Chromium PWA tests use the actual controllers, SQL and SignalR with a synthetic isolated project/manuscript. They cover Context alone; Review/Context without Word; local scrolling; exact paragraphs and chapter crossing; independent Hold; local held Review navigation; refresh and release without publication; rapid and obsolete ordering; new/duplicated-window isolation; reconnect; responsive widths; hidden tabs; and relationship edits in an earlier scene refreshing both held panes. The refreshed later-scene graph is checked for the new note, not just a refresh request. +- Actual loopback server restart passed: durable focus recovered, SignalR reconnected, and the held window detected an offline structural change without redirecting. Browser structural archival acceptance passed. Final public Development smoke results are recorded in deployment evidence. Browser fixtures are isolated and archived after testing; no real manuscript text or relationships are edited. + +Reproducible entry points: `PlotLine.Tests --shared-focus-database ` (rollback); `--shared-focus-browser-setup `; `--shared-focus-browser-host` (loopback only, real auth/SQL/hub, no hosted workers); `--shared-focus-concurrent`; `--shared-focus-cleanup`. Browser: `PlotLine.Tests/Browser/shared-manuscript-focus.cjs`, optionally `--installed`, `--structure`, or the externally coordinated `--restart` case, with private disposable identity supplied through `PD_CONTEXT_IDENTITY`. Portable native: `--shared-focus`. No credentials are in the report or repository. + +## Windows qualification still required + +This Linux host cannot compile/load the Office/VSTO project or run physical Word, Windows foreground handling or multiple monitors. The main .NET build deliberately excludes that project. Browser and portable native passes are **not physical Word acceptance**; no new Word binary has been installed or published by this task. + +1. On an Office-equipped Windows development machine, use the existing shared branch and `PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1` workflow at the recorded commit. Build/sign/verify the package, then use its existing explicit development installation procedure. Verify the loaded add-in/agent commit before testing. +2. Associate/save a disposable Development manuscript and complete chapter position verification. With Word alone, click and keyboard-select paragraphs across chapter/scene boundaries. Inspect shared revisions, then open Review/Context and verify initialization at the latest position without a new publication. +3. Exercise Word+Review, Word+Context and all three, with two Context windows (one Held) and split panes. Scroll Word and Review without changing shared focus. Select paragraphs/chapter/scene deliberately in each client and verify only followers move. +4. Keep Review foreground on another monitor. Select a paragraph there; verify Word reveals the exact target while the Windows foreground process, insertion point, selection and manuscript text remain unchanged. Repeat while Word has a dialog, protected view or editing activity; verify explicit busy/unmapped handling without activation. +5. Hold each Word window independently, including two windows on the same document. Navigate/edit locally; verify content synchronization continues and shared revision is unchanged. Release to the latest shared point, including one originally published by that same window. Close/reopen a window and verify new Follow identity. +6. Close each client in turn, including Word unexpectedly, and verify remaining pairs still navigate. Reconnect/restart the agent/service, rapidly alternate publications, and replay/delay notifications; verify newest accepted focus wins without an echo. Test saved/unsaved and stale/expired mapping transitions and independent manuscripts/accounts. +7. Repeat the earlier-scene relationship edit while a later-scene diagram is Held; verify data changes without movement. Archive a disposable held scene and verify explicit invalid-reference recovery. Confirm existing editing, synchronization, review tools, launch actions and ribbon layout. + +Older native installations do not advertise the new capability and retain their existing behavior. Precise native following requires fresh verified saved chapter positions; legacy paragraph-only offsets are not guessed. Historical Office.js hosting requires separate host-specific implementation/qualification before shared-focus support can be claimed there. + +Deployment evidence: [Unified-Manuscript-Focus-Deployment-20261123.md](Unified-Manuscript-Focus-Deployment-20261123.md). diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs index c1174419..ee0e5bf0 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs @@ -42,7 +42,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway else{ doc.Observed=DateTime.UtcNow; if(request.Kind=="active"){foreach(var d in documents.Values)d.Active=false;doc.Active=true;} - if(request.Kind=="selection"){doc.WordObservedUtc=request.WordObservedUtc.HasValue?(request.WordObservedUtc.Value.ToUniversalTime()<=ChapterNow?request.WordObservedUtc.Value.ToUniversalTime():null):ChapterNow;if(doc.WordSaved!=request.WordSaved&&request.WordSaved==true&&doc.NextChapterCheckUtc!=default)doc.NextChapterCheckUtc=ChapterNow.AddSeconds(3);if(ChapterCapable(instance)&&(doc.Cursor!=request.Start||doc.WordSaved!=request.WordSaved)){ChapterCursorEvidence.Invalidate(doc);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(doc.WordSaved==true&&doc.RibbonNotice?.State=="Save required")doc.RibbonNotice=null;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}} + if(request.Kind=="selection"){if(doc.FocusWindowID!=request.FocusWindowID||doc.FocusModeRequest!=request.FocusModeRequest)doc.DeliberateFocusSequence=0;doc.CanSharedFocus=request.CanSharedFocus;doc.FocusHeld=request.FocusHeld;doc.AnyFollowingWindows=request.AnyFollowingWindows;doc.FocusWindowID=request.FocusWindowID;doc.FocusModeRequest=request.FocusModeRequest;if(request.DeliberateFocusSequence>0)doc.DeliberateFocusSequence=request.DeliberateFocusSequence;if(request.CanSharedFocus&&(request.DeliberateFocusSequence>0||doc.LastFocusModeRequest!=request.FocusModeRequest)){doc.PresenceRequested=true;doc.LastFocusModeRequest=request.FocusModeRequest;}doc.WordObservedUtc=request.WordObservedUtc.HasValue?(request.WordObservedUtc.Value.ToUniversalTime()<=ChapterNow?request.WordObservedUtc.Value.ToUniversalTime():null):ChapterNow;if(doc.WordSaved!=request.WordSaved&&request.WordSaved==true&&doc.NextChapterCheckUtc!=default)doc.NextChapterCheckUtc=ChapterNow.AddSeconds(3);if(ChapterCapable(instance)&&(doc.Cursor!=request.Start||doc.WordSaved!=request.WordSaved)){ChapterCursorEvidence.Invalidate(doc);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(doc.WordSaved==true&&doc.RibbonNotice?.State=="Save required")doc.RibbonNotice=null;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}} if(request.Kind=="selection"&&doc.LastPresenceKey!=""&&chapterWork.TryGetValue(doc.Session,out var localWork)&&CurrentChapterWork(doc,localWork)&&localWork.Supported) PumpChapterWork(doc,localWork); ChapterFrame(doc,request,answer); @@ -54,6 +54,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway if (request.Kind == "tray-workspace" && answer.Status == "ok") _ = OpenRibbonWorkspace(doc.Session, request.Revision, "book"); CaptureFrame(doc,request,answer); + answer.SharedFocusStatus=doc.SharedFocusStatus; if((request.Kind=="selection"||request.Kind=="snapshot-end")&&!ChapterCapable(instance)){doc.ChapterId=answer.ChapterId;doc.SceneId=answer.SceneId;doc.ChapterTitle=answer.ChapterTitle;doc.SceneTitle=answer.SceneTitle;} if(answer.WordCount.HasValue)doc.Words=answer.WordCount; if(request.Kind.StartsWith("snapshot-",StringComparison.Ordinal)&&answer.Status is not ("ok" or "analysis-complete" or "awaiting-structure")){Cancel(doc);doc.Status="Local reading failed: "+answer.Status+". Detect chapters again.";} @@ -193,7 +194,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway } private async Task PublishPresence(TrayDocument doc,bool force,CancellationToken cancellation) { -var freshObservation=FreshWordObservation(doc);if(!force&&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);return;}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; @@ -244,6 +245,7 @@ var freshObservation=FreshWordObservation(doc);if(!force&&doc.LastPresenceKey==" } public sealed class TrayDocument { + public string SharedFocusStatus="";public bool CanSharedFocus,FocusHeld,AnyFollowingWindows;public Guid FocusWindowID,FocusModeRequest,LastFocusModeRequest;public long DeliberateFocusSequence; internal long AudioTextChanges; public PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? ChapterProgress; public long NavigationQueuedTimestamp,NavigationAckTimestamp;public Guid LastTracedNavigationAck;public Guid? NavigationAcknowledgedId;public string NavigationResult="";public Guid PendingNavigation;public long NavigationRevision;public DateTime NavigationExpires;public string LastPresenceKey="";public DateTime LastPresenceUtc;public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Link this manuscript to a book, then use Import manuscript in PlotDirector.",ReviewPath=""; diff --git a/PlotDirector.NativeCompanion/Protocol/FocusWindowState.cs b/PlotDirector.NativeCompanion/Protocol/FocusWindowState.cs new file mode 100644 index 00000000..2ce4a16e --- /dev/null +++ b/PlotDirector.NativeCompanion/Protocol/FocusWindowState.cs @@ -0,0 +1,10 @@ +namespace PlotDirector.Companion.Protocol; +// Per actual editor window; independent of content synchronisation and document ownership. +public sealed class FocusWindowState +{ + public Guid Id {get;}=Guid.NewGuid();public bool Held{get;private set;}public long Sequence{get;private set;}public long LastSharedRevision{get;private set;}public Guid ModeRequest{get;private set;}=Guid.NewGuid(); + private int start=-1,end=-1;private long appliedRevision=-1;private bool catchup; + public void Hold(bool held){if(Held==held)return;Held=held;if(!held){appliedRevision=-1;catchup=true;}ModeRequest=Guid.NewGuid();} + public long Observe(int nextStart,int nextEnd,bool deliberate){var changed=start!=nextStart||end!=nextEnd;start=nextStart;end=nextEnd;return changed&&deliberate&&!Held?++Sequence:0;} + public bool Accept(long revision,Guid origin){if(revision{if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);});return;} if(args.Contains("--word-observation")){await WordObservationTests.Run((ok,name)=>{if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);});return;} if(args.Contains("--chapter-sync")){ChapterRangeVerificationTests.Run();ChapterReopenTests.Run();await ChapterAgentTests.Run();await ChapterHandshakeTests.Run();await WordReopeningWorkTests.Run();return;} if(args.Contains("--native-capture-upload")){await NativeCaptureUploadTests.Run();return;} @@ -28,6 +29,7 @@ void SchedulerChecks() var rejected=false;var thread=new Thread(()=>{try{scheduler.Pump();}catch(InvalidOperationException){rejected=true;}});thread.Start();thread.Join();Check(rejected,"Word scheduler rejects wrong thread"); scheduler.PrioritizeAuthor(TimeSpan.FromMinutes(1));scheduler.Post("low",()=>value=0);Check(!scheduler.Pump()&&value==999,"author activity suspends low priority work"); } +SharedFocusTests.Run(Check); SchedulerChecks(); var mailbox=new BoundedMailbox();var id=Guid.NewGuid(); for(var i=0;i<10000;i++)mailbox.TryPost(new Message{Kind="selection",SessionId=id,Start=i}); diff --git a/PlotDirector.NativeCompanion/Tests/SharedFocusTests.cs b/PlotDirector.NativeCompanion/Tests/SharedFocusTests.cs new file mode 100644 index 00000000..be7db9bc --- /dev/null +++ b/PlotDirector.NativeCompanion/Tests/SharedFocusTests.cs @@ -0,0 +1,22 @@ +using PlotDirector.Companion.Protocol; + +internal static class SharedFocusTests +{ + public static void Run(Action check) + { + var a=new FocusWindowState();var b=new FocusWindowState();var origin=Guid.NewGuid(); + check(!a.Held&&!b.Held&&a.Id!=b.Id,"new Word windows follow with independent identities"); + check(a.Observe(10,10,false)==0&&a.Observe(20,20,false)==0,"passive Word observations never publish"); + check(a.Observe(30,30,true)==1&&a.Observe(30,30,true)==0,"deliberate changed selection publishes once"); + var mode=a.ModeRequest;a.Hold(true); + check(a.Held&&!b.Held&&a.ModeRequest!=mode,"holding Word affects only that window"); + check(a.Observe(40,40,true)==0&&a.Sequence==1,"held selection remains local without consuming a publication"); + check(!a.Accept(4,origin)&&a.LastSharedRevision==4,"held window records latest shared revision without navigation"); + a.Hold(false); + check(a.Sequence==1&&a.Accept(4,origin),"release catches latest focus without publishing held position"); + check(!a.Accept(4,origin)&&!a.Accept(3,origin),"duplicate and delayed Word focus deliveries cannot navigate again"); + check(!a.Accept(5,a.Id)&&a.LastSharedRevision==5,"originating Word window does not echo its own selection"); + a.Hold(true);a.Observe(50,50,true);a.Hold(false);check(a.Accept(5,a.Id),"release returns to shared reference even when this same Word window originally published it"); + check(b.Accept(5,a.Id),"another following Word window can receive that selection"); + } +} diff --git a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs index d28e23a8..e2e108c7 100644 --- a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs +++ b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs @@ -37,6 +37,7 @@ namespace PlotDirector.WordAddIn try { Refresh("PlotDirectorStatus", GetStatus(null)); + Refresh("PlotDirectorHold",GetFocusHeld(null).ToString());Refresh("PlotDirectorFocusState",GetFocusState(null)); Refresh("PlotDirectorBook", GetBookTip(null)); Refresh("PlotDirectorChapter", GetChapterTip(null)); Refresh("PlotDirectorScene", GetSceneTip(null)); @@ -68,6 +69,10 @@ namespace PlotDirector.WordAddIn ui?.InvalidateControl(control.Id); } + public bool GetFocusHeld(Office.IRibbonControl control)=>adapter()?.FocusHeld==true; + public string GetFocusState(Office.IRibbonControl control)=>adapter()?.FocusStateLabel??"Following"; + public string GetFocusTip(Office.IRibbonControl control)=>GetFocusHeld(control)?"Release Hold: catch up to shared manuscript focus. Content synchronisation stays active.":"Hold this Word window at its local position. Other windows and content synchronisation continue."; + public void ToggleFocusHold(Office.IRibbonControl control,bool pressed){adapter()?.SetFocusHeld(pressed);Invalidate();} public bool CanOpenBook(Office.IRibbonControl control) => adapter()?.HasRibbonBook == true; public string GetBookTip(Office.IRibbonControl control) => adapter()?.RibbonBook ?? "No linked book"; public string GetChapterTip(Office.IRibbonControl control) => adapter()?.RibbonChapter ?? "Chapter unverified"; diff --git a/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj index bc439f1b..c182e0f2 100644 --- a/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj +++ b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj @@ -23,7 +23,7 @@ PlotDirector.Companion.Protocol PlotDirector.Companion.Client ThisAddIn.cs - + ThisAddIn.cs diff --git a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml index f7ddc9ba..1a95637c 100644 --- a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml +++ b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml @@ -7,6 +7,7 @@ + diff --git a/PlotLine/Views/Shared/_FocusRibbon.cshtml b/PlotLine/Views/Shared/_FocusRibbon.cshtml index da28b982..00affbb5 100644 --- a/PlotLine/Views/Shared/_FocusRibbon.cshtml +++ b/PlotLine/Views/Shared/_FocusRibbon.cshtml @@ -1,5 +1,6 @@ @* One shared global navigation group; workspace adapters only control Go to Focus. *@
+
@foreach(var command in new[]{("previous","Previous","chevron-left","Previous scene in manuscript order"),("go","Go to Focus","focus","Display Current Focus in this workspace"),("next","Next","chevron-right","Next scene in manuscript order")}){ diff --git a/PlotLine/Views/Shared/_Layout.cshtml b/PlotLine/Views/Shared/_Layout.cshtml index d212b643..fce28734 100644 --- a/PlotLine/Views/Shared/_Layout.cshtml +++ b/PlotLine/Views/Shared/_Layout.cshtml @@ -189,6 +189,7 @@ { + diff --git a/PlotLine/Views/Shared/_WritingCompanionLayout.cshtml b/PlotLine/Views/Shared/_WritingCompanionLayout.cshtml index c946df77..ff2bda5a 100644 --- a/PlotLine/Views/Shared/_WritingCompanionLayout.cshtml +++ b/PlotLine/Views/Shared/_WritingCompanionLayout.cshtml @@ -5,4 +5,4 @@ var appearance=userID>0?await AppearancePreferences.GetAsync(userID):new ApplicationAppearance(); } @ViewData["Title"] · PlotDirector -
PlotDirector
@RenderBody()@await RenderSectionAsync("Scripts",required:false) +
PlotDirector
@RenderBody()@await RenderSectionAsync("Scripts",required:false) diff --git a/PlotLine/Views/Writing/Context.cshtml b/PlotLine/Views/Writing/Context.cshtml index af2c6ae5..6ab7efda 100644 --- a/PlotLine/Views/Writing/Context.cshtml +++ b/PlotLine/Views/Writing/Context.cshtml @@ -21,6 +21,7 @@

Context

+ @@ -29,7 +30,7 @@
diff --git a/PlotLine/wwwroot/css/application-shell.css b/PlotLine/wwwroot/css/application-shell.css index 7f029a12..62ec137b 100644 --- a/PlotLine/wwwroot/css/application-shell.css +++ b/PlotLine/wwwroot/css/application-shell.css @@ -857,3 +857,14 @@ html[data-app-theme] .scenario-workspace :is(h1, h2, h3) { } .scenario-workspace .attention-list p { grid-column: 1 / -1; } .scenario-workspace .scenario-warning-badge { justify-self: start; } +/* Static focus commands reserve their width in both modes; no delayed ribbon insertion. */ +.pd-shell [data-shared-focus-hold]{width:104px;min-width:104px;max-width:104px} +.pd-ribbon-focus [data-shared-focus-status]{width:140px;min-width:140px;max-height:68px;overflow:auto;white-space:normal;overflow-wrap:anywhere;font-size:11px;line-height:1.2;align-self:center} +[data-context-workspace] [data-shared-focus-hold]{min-width:190px} + +/* Hold remains visible when the PWA compacts Previous/Go/Next into its existing menu. */ +.pd-shell .pd-ribbon-focus{display:grid;grid-template-columns:auto auto;grid-template-rows:1fr auto;column-gap:4px} +.pd-ribbon-focus-mode{grid-column:1;grid-row:1;display:flex;align-items:flex-start;gap:4px} +.pd-ribbon-focus>.pd-ribbon-commands,.pd-ribbon-focus>.pd-base-overflow{grid-column:2;grid-row:1} +.pd-ribbon-focus>.pd-ribbon-group-label{grid-column:1/-1;grid-row:2} +@media(max-width:760px){.pd-ribbon-focus [data-shared-focus-status]{width:90px;min-width:90px}} diff --git a/PlotLine/wwwroot/js/context-workspace.js b/PlotLine/wwwroot/js/context-workspace.js index 4c6b5a98..59fc0394 100644 --- a/PlotLine/wwwroot/js/context-workspace.js +++ b/PlotLine/wwwroot/js/context-workspace.js @@ -128,6 +128,8 @@ generation++;cancelRequests(); for(const pane of panes){for(const record of pane.records.values()){ if(record.tab.contentRefresh==='none')continue; + if(hint.kind==='relationships'&&!['overview','characters','relationships'].includes(record.tab.id))continue; + if(hint.kind==='characters'&&!['overview','characters','relationships','names'].includes(record.tab.id))continue; // Scene projections can depend on established earlier records: book-level is conservative. record.stale=true; }void refreshPane(pane);} @@ -144,45 +146,9 @@ for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');for(const record of pane.records.values())if(force||scopeChanged(record.tab,before,position))record.stale=true;void refreshPane(pane);} announce(); } - async function recoverOffice(force=false) { - if(pinned||selectedDocument||nativeLeases.some(l=>l.wordAvailable&&(!scope.bookId||Number(l.bookId)===scope.bookId)))return; - if(recoveryPending){recoveryAgain ||= force;return;} - recoveryPending=true;const epoch=recoveryGeneration; - try { - const url=new URL('/Writing/Context/Position',location.origin);for(const [key,value]of Object.entries(scope))if(value)url.searchParams.set(key,value); - const response=await fetch(url,{cache:'no-store',signal:AbortSignal.timeout(8000),headers:{'X-Requested-With':'XMLHttpRequest'}}); - if(!response.ok||response.redirected)throw Error();const packet=await response.json(); - if(epoch!==recoveryGeneration||selectedDocument||nativeLeases.some(l=>l.wordAvailable&&(!scope.bookId||Number(l.bookId)===scope.bookId)))return; - const office=packet.position; - window.PlotDirector?.wordNotifications?.connection('office',packet.connected); - const indicator=document.querySelector('[data-word-companion-presence]');if(indicator)indicator.dataset.officeConnected=String(packet.connected); - if(packet.connected&&office){unavailable=false;status.textContent='Following Word · saved reference data';setPosition(office,force);} - else {unavailable=true;status.textContent='Word disconnected · saved scene browsing remains available';if(force)invalidate();} - } catch {if(epoch===recoveryGeneration){unavailable=true;status.textContent='Word status unavailable · saved reference remains available';if(force)invalidate();}} - finally {recoveryPending=false;if(recoveryAgain){recoveryAgain=false;void recoverOffice(true);}} - } - function followNative(leases,force=false) { - nativeLeases=leases.filter(l=>Date.parse(l.expires)>Date.now());recoveryGeneration++; - const available=nativeLeases.filter(l=>l.wordAvailable&&(!scope.bookId||Number(l.bookId)===scope.bookId)); - const active=available.filter(l=>l.active); - const chosen=selectedDocument?available.filter(l=>`${l.instanceId}/${l.sessionId}`===selectedDocument):active.length===1?active:available; - const lease=chosen.length===1?chosen[0]:null; - if(!lease){ - if(selectedDocument||available.length){unavailable=true;nativeKey='';status.textContent=available.length>1&&!selectedDocument?'Choose a Word document using the connection indicator':'Selected Word document disconnected · saved reference remains available';if(position.instanceId){generation++;cancelRequests();for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');if(current(pane))current(pane).stale=true;pane.status.textContent='Live position unavailable · displayed reference may be stale.';}}return;} - nativeKey='';void recoverOffice(force);return; - } - if(lease.wordSaved!==true||lease.positionVerified===false||!lease.sceneId){ - unavailable=true;nativeKey='';if(position.instanceId){generation++;cancelRequests();for(const pane of panes){pane.revision++;pane.host.removeAttribute('aria-busy');if(current(pane))current(pane).stale=true;pane.status.textContent='Displayed reference is saved data · current Word scene is unavailable.';}} - status.textContent=lease.positionMessage||'Save Word and verify its scene mapping · saved reference remains available';return; - } - unavailable=false; - const key=[lease.instanceId,lease.sessionId,lease.manuscriptId,lease.revision,lease.snapshotRevision,lease.chapterId,lease.sceneId].join(':'); - const changed=nativeKey!==key;nativeKey=key; - status.textContent='Following Word · saved reference data'; - // Observed revision alone is not accepted content. It only causes position verification. - setPosition({ ...scope,bookId:Number(lease.bookId),chapterId:Number(lease.chapterId),sceneId:Number(lease.sceneId),instanceId:lease.instanceId,sessionId:lease.sessionId },force||leases.reconnected); - if(changed&&lease.mappingCurrent)invalidate({bookId:lease.bookId}); - } + async function recoverOffice(){if(window.PlotDirectorSharedFocus)await window.PlotDirectorSharedFocus.refresh();} + function followNative(leases){const changed=leases.some(l=>Number(l.bookId)===scope.bookId&&l.snapshotRevision&&nativeLeases.find(old=>old.instanceId===l.instanceId&&old.sessionId===l.sessionId)?.snapshotRevision!==l.snapshotRevision);nativeLeases=leases.filter(l=>Date.parse(l.expires)>Date.now());if(changed||leases.reconnected){invalidate({bookId:scope.bookId});void refreshStructure();void window.PlotDirectorSharedFocus?.validateLocal();}} + async function refreshStructure(){try{const response=await fetch(`/NarrativeFocus/Read?projectId=${scope.projectId}&bookId=${scope.bookId}`,{cache:'no-store'});if(!response.ok||response.redirected)return;const data=await response.json(),id=position.sceneId,options=[new Option('Choose a saved scene',''),...data.positions.filter(p=>p.sceneID).map(p=>new Option(p.label,String(p.sceneID)))];if(id&&!options.some(o=>Number(o.value)===id)){const missing=new Option('Reference unavailable · choose another scene',String(id));missing.disabled=true;options.push(missing);}sceneSelect.replaceChildren(...options);sceneSelect.value=id||'';}catch{/* Saved reference remains visible. */}} function applyLayout() { grid.dataset.layout=state.layout;layoutSelect.value=state.layout; panes[1].element.hidden=state.layout==='single';divider.hidden=state.layout==='single'; @@ -215,23 +181,16 @@ const record=current(pane);if(!record)return;record.dirty=!!event.detail?.dirty;record.busy=!!event.detail?.busy;if(!guarded(record)&&record.stale&&!event.detail?.deferRefresh)void refreshPane(pane);announce(); }); } - async function navigate(sceneId,sendWord=false) { - const id=number(sceneId);if(!id)return; - const manual=++manualGeneration;navigationRequest?.abort(); - setPosition({...scope,chapterId:null,sceneId:id});status.textContent=pinned?'Saved PlotDirector snapshot · manual selection':'Saved scene selected'; - if(!sendWord||pinned||!scope.bookId)return; - navigationRequest=new AbortController(); - const token=document.querySelector('[data-word-sync-form] [name=__RequestVerificationToken]')?.value; - const body=new URLSearchParams({bookId:scope.bookId,sceneId:id,navigationId:uuid(),__RequestVerificationToken:token||''}); - if(selectedDocument){const [instanceId,sessionId]=selectedDocument.split('/');body.set('instanceId',instanceId);body.set('sessionId',sessionId);} - try{const response=await fetch('/Writing/Context/Navigate',{method:'POST',body,signal:navigationRequest.signal,headers:{'X-Requested-With':'XMLHttpRequest'}});const packet=await response.json();if(manual===manualGeneration)status.textContent=packet.message||'Saved scene selected';}catch(error){if(error.name!=='AbortError'&&manual===manualGeneration)status.textContent='Saved scene selected · Word navigation unavailable';} - } + async function navigate(sceneId){const id=number(sceneId);if(!id)return;if(windowBusy||panes.some(p=>guarded(current(p)))){status.textContent='Save or cancel the current editor before changing manuscript position.';return;}if(!window.PlotDirectorSharedFocus){status.textContent='Focus is initialising; retry this selection.';return;}const moved=await window.PlotDirectorSharedFocus.navigate({projectID:scope.projectId,bookID:scope.bookId,sceneID:id});if(!moved)sceneSelect.value=position.sceneId||'';} + function sharedPosition(event){const p=event.detail.position;setPosition({projectId:p.projectID,bookId:p.bookID,chapterId:p.chapterID,sceneId:p.sceneID,paragraphId:p.paragraphID});status.textContent=window.PlotDirectorSharedFocus?.held?'Held at local manuscript position · saved data remains live':'Following shared manuscript focus · saved reference data';} + window.addEventListener('plotdirector:shared-focus',sharedPosition); + root.querySelector('[data-context-go-focus]')?.addEventListener('click',()=>void window.PlotDirectorSharedFocus?.go()); sceneSelect.addEventListener('change',event=>void navigate(sceneSelect.value,event.isTrusted)); - for(const [selector,step]of [['[data-context-previous]',-1],['[data-context-next]',1]])root.querySelector(selector).addEventListener('click',event=>{const at=[...sceneSelect.options].findIndex(o=>Number(o.value)===position.sceneId);const next=sceneSelect.options[at+step];if(next?.value)void navigate(next.value,event.isTrusted);}); + for(const [selector,step]of [['[data-context-previous]',-1],['[data-context-next]',1]])root.querySelector(selector).addEventListener('click',()=>{const choices=[...sceneSelect.options].filter(o=>number(o.value)),at=choices.findIndex(o=>Number(o.value)===position.sceneId),next=at<0?(step>0?choices[0]:choices.at(-1)):choices[at+step];if(next)void navigate(next.value);}); root.querySelector('[data-context-new]').addEventListener('click',()=>window.PlotDirectorWritingWorkspace.openContext({...position,pinned})); root.querySelector('[data-context-refresh]').addEventListener('click',()=>invalidate()); - window.addEventListener('native-companion-presence',event=>{if(!pinned)followNative(event.detail||[],!!event.detail?.reconnected);}); - window.addEventListener('plotdirector:word-document-selected',event=>{if(pinned)return;selectedDocument=event.detail||'';presentSelectedDocument();const url=new URL(location.href);if(selectedDocument){url.searchParams.set('instanceId',root.dataset.wordInstance);url.searchParams.set('sessionId',root.dataset.wordSession);}else{url.searchParams.delete('instanceId');url.searchParams.delete('sessionId');}history.replaceState(null,'',url);nativeKey='';save();followNative(nativeLeases,true);}); + window.addEventListener('native-companion-presence',event=>{followNative(event.detail||[]);}); + window.addEventListener('plotdirector:word-document-selected',event=>{selectedDocument=event.detail||'';presentSelectedDocument();const url=new URL(location.href);if(selectedDocument){url.searchParams.set('instanceId',root.dataset.wordInstance);url.searchParams.set('sessionId',root.dataset.wordSession);}else{url.searchParams.delete('instanceId');url.searchParams.delete('sessionId');}history.replaceState(null,'',url);nativeKey='';save();followNative(nativeLeases,true);}); window.addEventListener('plotdirector:word-return-to-current',()=>{if(!pinned){nativeKey='';followNative(nativeLeases,true);}}); function wakeStatus(reconnected=false){window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status',{detail:{reconnected}}));} async function startConnection(){ @@ -239,17 +198,17 @@ connectionStarting=true; try{await connection.start();wakeStatus(true);void recoverOffice(true);root.dispatchEvent(new Event('context-connection-ready'));}catch{status.textContent='Context notifications disconnected · retrying; saved browsing remains available';}finally{connectionStarting=false;} } - if(!pinned&&window.signalR){ + if(window.signalR){ connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build(); connection.on('NativePresenceChanged',hint=>{window.dispatchEvent(new CustomEvent('plotdirector:native-presence-changed',{detail:hint}));wakeStatus();}); connection.on('ContextPositionChanged',()=>void recoverOffice()); - connection.on('ContextInvalidated',hint=>{invalidate(hint);wakeStatus();}); + connection.on('ContextInvalidated',hint=>{invalidate(hint);if(hint.kind==='structure')void refreshStructure();wakeStatus();}); connection.onreconnecting(()=>status.textContent='Context notifications reconnecting · saved reference may be stale'); connection.onreconnected(()=>{wakeStatus(true);void recoverOffice(true);invalidate();root.dispatchEvent(new Event('context-connection-ready'));}); connection.onclose(()=>status.textContent='Context notifications disconnected · saved browsing remains available'); void startConnection(); } - const timer=pinned?null:setInterval(()=>{void startConnection();void recoverOffice();announce();},15000); + const timer=setInterval(()=>{void startConnection();announce();},15000); document.addEventListener('visibilitychange',()=>{if(!document.hidden&&!pinned){void startConnection();wakeStatus(true);void recoverOffice(true);}}); window.addEventListener('pageshow',event=>{if(event.persisted)location.reload();}); // Duplicated browser tabs clone both URL and session storage. The live owner answers claims. @@ -274,5 +233,5 @@ root.contextController={ get windowId(){return windowId;}, get position(){return {...position};}, invalidate,setPosition,get connection(){return connection;},get announcement(){return {version:1,bookID:position.bookId,windowID:windowId,panes:panes.filter(visible).map(pane=>({paneID:String(pane.index),toolID:state.panes[pane.index].tab,actions:registry.get(state.panes[pane.index].tab).actions||[],available:!windowBusy&&!!current(pane)?.node&&!current(pane).stale&&!guarded(current(pane))}))};},receiveInteraction:async delivery=>{if(windowBusy)return 'busy';const pane=panes.find(p=>String(p.index)===delivery.paneID);if(!pane||!visible(pane))return 'not-visible';const record=current(pane);if(guarded(record))return 'busy';if(!record?.node||record.stale)return 'unavailable';record.stale=true;await refreshPane(pane);if(record.stale||guarded(record))return 'unavailable';return await lifecycles[record.tab.lifecycle]?.onInteraction?.(record.node,delivery.command,{position:{...position},pane})||'not-visible';},registerLifecycle:(name,hooks)=>lifecycles[name]=hooks }; window.addEventListener('pagehide',()=>{stopped=true;panes.forEach(pane=>{remember(pane);dispose(current(pane));});save();cancelRequests();navigationRequest?.abort();clearInterval(timer);observer.disconnect();channel?.close();void connection?.stop();}); save();applyLayout(); - if(pinned)status.textContent='Saved PlotDirector snapshot · manual selection · live follow disabled'; + status.textContent='Shared manuscript focus initialising · local saved data remains available'; })(); diff --git a/PlotLine/wwwroot/js/manuscript-reader.js b/PlotLine/wwwroot/js/manuscript-reader.js index 2ffe0dc6..9c21cd4f 100644 --- a/PlotLine/wwwroot/js/manuscript-reader.js +++ b/PlotLine/wwwroot/js/manuscript-reader.js @@ -103,8 +103,9 @@ function initialiseManuscriptReader() { root.readerPreserveView=()=>{const mine=narrativePosition,anchors=rememberPosition();return ()=>{if(root.isConnected&&mine===narrativePosition)restorePosition(anchors);};}; root.readerResolveFocus=target=>{ if(Number(bookId)!==target.bookID||Number(chapterId)!==target.chapterID)return null; - const paragraph=target.sceneID?[...content.querySelectorAll('[data-paragraph-id][data-scene-id]')].find(n=>Number(n.dataset.sceneId)===target.sceneID):null; - return {paragraph,precise:!!paragraph,version:root.dataset.version,revision:root.dataset.revision}; + const exact=target.paragraphID?content.querySelector(`[data-paragraph-id="${CSS.escape(target.paragraphID)}"]`):null; + const paragraph=exact||(target.sceneID?[...content.querySelectorAll('[data-paragraph-id][data-scene-id]')].find(n=>Number(n.dataset.sceneId)===target.sceneID):null); + return {paragraph,precise:target.paragraphID?!!exact:!!paragraph,version:root.dataset.version,revision:root.dataset.revision}; }; root.readerLocateFocus=target=>{ const resolved=root.readerResolveFocus(target);if(!resolved)return null; diff --git a/PlotLine/wwwroot/js/narrative-focus-review.js b/PlotLine/wwwroot/js/narrative-focus-review.js index f7869f8a..04c18c75 100644 --- a/PlotLine/wwwroot/js/narrative-focus-review.js +++ b/PlotLine/wwwroot/js/narrative-focus-review.js @@ -15,7 +15,7 @@ if(!canChange()){offer('Save or cancel open editors, clear any text selection and close dialogs before changing the displayed chapter or scene. Your original references are retained.');return;} try{ if(focus.chapterID!==Number(reader.dataset.chapterId)){ - request=new AbortController();const url=new URL('/Writer/ReviewContent',location.origin);url.search=new URLSearchParams({projectId:focus.projectID,bookId:focus.bookID,version:focus.version,focus:reader.dataset.focus==='true',reading:reader.dataset.reading==='true'}); + request=new AbortController();const url=new URL('/Writer/ReviewContent',location.origin);url.search=new URLSearchParams({projectId:focus.projectID,bookId:focus.bookID,version:focus.version,focus:reader.dataset.focus==='true',reading:reader.dataset.reading==='true',chapterId:focus.chapterID,localFocus:window.PlotDirectorSharedFocus?.held===true}); const response=await fetch(url,{cache:'no-store',signal:request.signal});if(!response.ok||response.redirected)throw Error('The chapter could not be refreshed.'); const doc=new DOMParser().parseFromString(await response.text(),'text/html'),fresh=doc.querySelector('[data-review-columns]'),nextReader=fresh?.querySelector('.manuscript-reader'); if(!nextReader||Number(nextReader.dataset.bookId)!==focus.bookID||Number(nextReader.dataset.chapterId)!==focus.chapterID)throw Error('The requested chapter is unavailable.'); @@ -36,8 +36,8 @@ if(mine!==generation||!same(focus,current())||!canChange())return; for(const [name,value]of reader._focusFilters||[]){const select=columns.querySelector(`[data-annotation-filter="${name}"]`);if(select){select.value=value;select.dispatchEvent(new Event('change',{bubbles:true}));}}delete reader._focusFilters; const resolved=reader.readerResolveFocus(focus); - notice.hidden=!focus.sceneID||resolved.precise; - if(!notice.hidden)notice.textContent='Current Focus: '+focus.label+'. Precise scene positioning is unavailable: no accepted paragraph is mapped to this scene. Chapter context is shown; select an accepted passage for verified scene context.'; + notice.hidden=!(focus.sceneID||focus.paragraphID)||resolved.precise; + if(!notice.hidden)notice.textContent=(focus.paragraphID?'The requested paragraph is unavailable in this accepted chapter. The mapped scene or chapter is shown. ':'')+'Current Focus: '+focus.label+'. Precise scene positioning is unavailable: no accepted paragraph is mapped to this scene. Chapter context is shown; select an accepted passage for verified scene context.'; window.dispatchEvent(new Event('plotdirector:context-changed')); await frame();await frame(); if(mine!==generation||!same(focus,current())||!reader.isConnected||!canChange())return; @@ -45,9 +45,15 @@ reader.dispatchEvent(new CustomEvent('reader:focus-positioned',{bubbles:true,detail:{chapterID:focus.chapterID,sceneID:focus.sceneID,paragraphID:reader.dataset.focusParagraph||null,version:reader.dataset.version}})); }catch(error){if(error.name!=='AbortError'&&mine===generation)offer((error.message||'Current Focus could not be displayed.')+' Your content and edits are retained.');} } - window.addEventListener('plotdirector:narrative-focus-changed',event=>void apply(event.detail)); - window.PlotDirectorFocusWorkspace.register({canGo:focus=>focus.bookID===Number(document.querySelector('.manuscript-reader')?.dataset.bookId)&&!!focus.chapterID,unavailable:'Choose a chapter in this Review book to display Current Focus',go:apply}); + window.addEventListener('plotdirector:narrative-focus-changed',event=>{if(window.PlotDirectorSharedFocus)void apply(event.detail);}); + window.PlotDirectorFocusWorkspace.register({canGo:focus=>focus.bookID===Number(document.querySelector('.manuscript-reader')?.dataset.bookId)&&!!focus.chapterID,beforeChange:()=>canChange(),unavailable:'Choose a chapter in this Review book to display Current Focus',go:apply}); document.addEventListener('reader:updated',()=>void apply(current())); - if(current())void apply(current()); + if(current()&&window.PlotDirectorSharedFocus)void apply(current()); window.addEventListener('pagehide',()=>{++generation;request?.abort();}); + function selectParagraph(p){const r=p.closest('.manuscript-reader');if(!r||document.querySelector('[data-writer-review]')?.canChangeNarrative?.()===false)return;for(const item of r.querySelectorAll('[data-paragraph-id]'))item.tabIndex=item===p?0:-1;void window.PlotDirectorSharedFocus?.navigate({projectID:current()?.projectID,bookID:Number(r.dataset.bookId),chapterID:Number(r.dataset.chapterId),sceneID:Number(p.dataset.sceneId)||null,paragraphID:p.dataset.paragraphId,localSelection:true});} + document.addEventListener('click',event=>{if(!event.isTrusted)return;const p=event.target.closest('.manuscript-reader [data-paragraph-id]');if(p)selectParagraph(p);const link=event.target.closest('.reader-chapter-navigation a[href]');if(link){event.preventDefault();const chapter=Number(new URL(link.href).searchParams.get('chapterId'));if(chapter)void window.PlotDirectorSharedFocus?.navigate({chapterID:chapter});}}); + document.addEventListener('submit',event=>{if(event.defaultPrevented)return;const form=event.target;if(form.closest('.reader-chapter-navigation')){event.preventDefault();const chapter=Number(new FormData(form).get('chapterId'));if(chapter)void window.PlotDirectorSharedFocus?.navigate({chapterID:chapter});}}); + document.addEventListener('keydown',event=>{if(!event.target.matches('.manuscript-reader [data-paragraph-id]')||!['ArrowUp','ArrowDown','Home','End'].includes(event.key))return;event.preventDefault();const paragraphs=[...event.target.closest('.manuscript-reader').querySelectorAll('[data-paragraph-id]')],index=paragraphs.indexOf(event.target),next=event.key==='Home'?0:event.key==='End'?paragraphs.length-1:Math.max(0,Math.min(paragraphs.length-1,index+(event.key==='ArrowDown'?1:-1)));const p=paragraphs[next];p.focus({preventScroll:true});p.scrollIntoView({block:'nearest'});p.click();selectParagraph(p);}); + document.querySelector('.manuscript-reader [data-paragraph-id]')?.setAttribute('tabindex','0'); + })(); diff --git a/PlotLine/wwwroot/js/narrative-focus-workspaces.js b/PlotLine/wwwroot/js/narrative-focus-workspaces.js index 4cde8acf..3ae2f2e6 100644 --- a/PlotLine/wwwroot/js/narrative-focus-workspaces.js +++ b/PlotLine/wwwroot/js/narrative-focus-workspaces.js @@ -38,7 +38,7 @@ window.addEventListener('plotdirector:narrative-focus-changed',e=>align(e.detail)); window.addEventListener('beforeunload',e=>{if(!leaving&&dirty()){e.preventDefault();e.returnValue='';}}); window.addEventListener('pageshow',()=>{leaving=false;}); - const initial=window.PlotDirectorNarrativeFocus?.state;if(initial)align(initial); + const initial=window.PlotDirectorNarrativeFocus?.state;if(initial&&window.PlotDirectorSharedFocus)align(initial); } const chapterPage=document.querySelector('[data-focus-chapter]'); if(chapterPage){ @@ -63,7 +63,7 @@ } registry.register({canGo:scope,unavailable:'Choose a chapter in this chapter page’s book',go:align}); window.addEventListener('plotdirector:narrative-focus-changed',e=>align(e.detail)); - const initial=window.PlotDirectorNarrativeFocus?.state;if(initial)align(initial); + const initial=window.PlotDirectorNarrativeFocus?.state;if(initial&&window.PlotDirectorSharedFocus)align(initial); window.addEventListener('beforeunload',e=>{if(chapterPage.querySelector('form[data-focus-dirty=true]')&&!submitting){e.preventDefault();e.returnValue='';}}); } if(controller==='Books'&&action==='Details')registry.register({canGo:focus=>!!focus.chapterID,go:focus=>location.assign(`/Chapters/Details/${focus.chapterID}?retainNarrativeFocus=true`)}); diff --git a/PlotLine/wwwroot/js/narrative-focus.js b/PlotLine/wwwroot/js/narrative-focus.js index 28327a39..b1f6ada8 100644 --- a/PlotLine/wwwroot/js/narrative-focus.js +++ b/PlotLine/wwwroot/js/narrative-focus.js @@ -8,7 +8,7 @@ const dismiss=(restore=false)=>{restore=restore===true||root.querySelector('.pd-focus-picker').contains(document.activeElement);bootstrap.Dropdown.getOrCreateInstance(toggle).hide();if(restore)toggle.focus({preventScroll:true});}; const scopeKey=`pd-narrative-book:${document.body.dataset.pdUserId}:${state.projectID}`; const notificationKey=()=>`pd-narrative-focus:${document.body.dataset.pdUserId}:${state.projectID}:${state.bookID}`; - async function loadScope(book){if(!book){render();return;}const mine=++epoch;busy=true;render();try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${book}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const result=await response.json();if(mine!==epoch)return;state=result;publish();status.textContent='';}catch{status.textContent='This focus book is unavailable. Your workspace is unchanged.';}finally{busy=false;render();if(refreshQueued){refreshQueued=false;void refresh();}}} + async function loadScope(book){if(!book){render();return;}const mine=++epoch;busy=true;render();try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${book}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const result=await response.json();if(mine!==epoch)return;state=result;if(window.PlotDirectorSharedFocus)await window.PlotDirectorSharedFocus.scope(state);publish();status.textContent='';}catch{status.textContent='This focus book is unavailable. Your workspace is unchanged.';}finally{busy=false;render();if(refreshQueued){refreshQueued=false;void refresh();}}} bookPicker?.addEventListener('change',()=>void loadScope(Number(bookPicker.value))); const key=p=>`${p.chapterID||''}/${p.sceneID||''}`; const selected=()=>key(state); @@ -28,12 +28,13 @@ for(const card of document.querySelectorAll('.timeline-scene-card[data-scene-id]')){const current=Number(card.dataset.sceneId)===state.sceneID;card.classList.toggle('pd-current-narrative-focus',current);if(current)card.setAttribute('aria-current','location');else if(card.getAttribute('aria-current')==='location')card.removeAttribute('aria-current');} for(const link of document.querySelectorAll('[data-focus-reference-link]')){const url=new URL(link.href);url.searchParams.delete('chapterId');url.searchParams.delete('sceneId');if(state.chapterID)url.searchParams.set('chapterId',state.chapterID);if(state.sceneID)url.searchParams.set('sceneId',state.sceneID);link.href=url;} window.dispatchEvent(new CustomEvent('plotdirector:narrative-focus-changed',{detail:state}));} - async function refresh(){if(!state.bookID)return;if(busy){refreshQueued=true;return;}refreshQueued=false;const mine=++epoch;try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${state.bookID}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const fresh=await response.json();if(mine!==epoch||busy)return;if(fresh.version!==state.version){state=fresh;publish();}else{state=fresh;render();}}catch{if(mine===epoch&&!busy)status.textContent='Current focus could not be refreshed. Your edits are retained.';}} + async function refresh(){if(window.PlotDirectorSharedFocus){await window.PlotDirectorSharedFocus.refresh();return;}if(!state.bookID)return;if(busy){refreshQueued=true;return;}refreshQueued=false;const mine=++epoch;try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${state.bookID}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const fresh=await response.json();if(mine!==epoch||busy)return;if(fresh.version!==state.version){state=fresh;publish();}else{state=fresh;render();}}catch{if(mine===epoch&&!busy)status.textContent='Current focus could not be refreshed. Your edits are retained.';}} async function set(target={}){ if(busy||!state.bookID){status.textContent='Choose a focus book first.';return false;} if(target.bookID&&Number(target.bookID)!==state.bookID||target.projectID&&Number(target.projectID)!==state.projectID){status.textContent='Choose this book in the header before setting its focus.';return false;} const adapter=window.PlotDirectorFocusWorkspace?.adapter; if(adapter?.beforeChange&&!adapter.beforeChange(target)){render();return false;} + if(window.PlotDirectorSharedFocus?.ownsScope(state)){busy=true;render();try{const result=await window.PlotDirectorSharedFocus.navigate(target);if(result)dismiss();return result;}finally{adapter?.changeFinished?.();busy=false;render();}} const fromPicker=root.querySelector('.pd-focus-picker').contains(document.activeElement); busy=true;++epoch;render();status.textContent='Updating current focus…'; const body=new URLSearchParams({projectId:state.projectID,bookId:state.bookID,version:state.version,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value}); @@ -51,11 +52,13 @@ function closeRibbonMenu(button){const menu=button.closest('details[data-compact=true]');if(menu){const restore=menu.contains(document.activeElement)||document.activeElement===document.body;menu.open=false;if(restore)menu.querySelector('summary').focus({preventScroll:true});}else if(document.activeElement===document.body){const target=button.disabled?button.closest('.pd-ribbon-focus').querySelector('button:not(:disabled)'):button;target?.focus({preventScroll:true});}} document.querySelectorAll('[data-global-focus=previous],[data-global-focus=next]').forEach(b=>b.addEventListener('click',async()=>{if(await set({direction:(b.dataset.globalFocus==='previous'?-1:1)}))closeRibbonMenu(b);})); window.addEventListener('plotdirector:focus-adapter-ready',render); - document.querySelectorAll('[data-global-focus=go]').forEach(b=>b.addEventListener('click',async()=>{const adapter=window.PlotDirectorFocusWorkspace?.adapter;if(busy)return;if(!adapter?.canGo(state)){showWorkspaceMessage(adapter?.unavailable||'Current Focus is unavailable in this workspace.');render();return;}document.querySelector('[data-focus-workspace-status]')?.remove();busy=true;render();let succeeded=false;try{await adapter.go(state);succeeded=true;}catch(error){showWorkspaceMessage(error.message||'Current Focus could not be displayed.');}finally{busy=false;render();if(succeeded)closeRibbonMenu(b);if(refreshQueued){refreshQueued=false;void refresh();}}})); + document.querySelectorAll('[data-global-focus=go]').forEach(b=>b.addEventListener('click',async()=>{const adapter=window.PlotDirectorFocusWorkspace?.adapter;if(busy)return;if(window.PlotDirectorSharedFocus?.ownsScope(state)){await window.PlotDirectorSharedFocus.go();return;}if(!adapter?.canGo(state)){showWorkspaceMessage(adapter?.unavailable||'Current Focus is unavailable in this workspace.');render();return;}document.querySelector('[data-focus-workspace-status]')?.remove();busy=true;render();let succeeded=false;try{await adapter.go(state);succeeded=true;}catch(error){showWorkspaceMessage(error.message||'Current Focus could not be displayed.');}finally{busy=false;render();if(succeeded)closeRibbonMenu(b);if(refreshQueued){refreshQueued=false;void refresh();}}})); function showWorkspaceMessage(message){let output=document.querySelector('[data-focus-workspace-status]');if(!output){output=document.createElement('p');output.dataset.focusWorkspaceStatus='';output.setAttribute('role','status');document.querySelector('.pd-shell').after(output);}output.textContent=message;} window.addEventListener('pagehide',dismiss); document.addEventListener('click',e=>{const b=e.target.closest('[data-go-objective],[data-narrative-scene]');if(!b)return;void set({bookID:Number(b.dataset.narrativeBook)||state.bookID,chapterID:Number(b.dataset.chapter||b.dataset.narrativeChapter)||null,sceneID:Number(b.dataset.scene||b.dataset.narrativeScene)||null});}); window.addEventListener('storage',e=>{if(e.key===notificationKey())void refresh();});window.addEventListener('focus',()=>void refresh());window.addEventListener('pageshow',()=>void refresh());root.addEventListener('shown.bs.dropdown',()=>void refresh()); + window.addEventListener('plotdirector:shared-focus',event=>{const p=event.detail.position;if(p.bookID!==state.bookID||p.projectID!==state.projectID)return;const position=state.positions.find(x=>x.chapterID===p.chapterID&&(!p.sceneID||x.sceneID===p.sceneID));state={...state,...p,label:position?(p.sceneID?position.label:`Ch ${position.chapterNumber}: ${position.chapterTitle}`):'Choose chapter or scene'};if(event.detail.reason==='selection')render();else publish();}); + root.addEventListener('shown.bs.dropdown',async()=>{if(!state.bookID)return;try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${state.bookID}`,{cache:'no-store'});if(response.ok&&!response.redirected){const data=await response.json();state.positions=data.positions;state.recent=data.recent;render();}}catch{}}); window.PlotDirectorNarrativeFocus={set,refresh,get state(){return state;}}; publish(); if(!state.bookID&&bookPicker){try{const book=localStorage.getItem(scopeKey);if([...bookPicker.options].some(o=>o.value===book))void loadScope(Number(book));}catch{}} diff --git a/PlotLine/wwwroot/js/shared-manuscript-focus.js b/PlotLine/wwwroot/js/shared-manuscript-focus.js new file mode 100644 index 00000000..03a7a6fd --- /dev/null +++ b/PlotLine/wwwroot/js/shared-manuscript-focus.js @@ -0,0 +1,13 @@ +// One user/book/canonical-manuscript focus stream over the window's existing presence connection. +(()=>{'use strict';function start(){const context=document.querySelector('[data-context-workspace]'),header=document.querySelector('[data-narrative-focus]'),reader=document.querySelector('.manuscript-reader');if(!context&&!header)return;const initial=window.PlotDirectorNarrativeFocus?.state||(header?JSON.parse(header.querySelector('[data-narrative-initial]').textContent):{});let project=Number(context?.dataset.scopeProjectId||initial.projectID),book=Number(context?.dataset.scopeBookId||initial.bookID),connection,disconnected=false,latest=null,local=null,epoch=0,sequence=0,held=false,publishing=false,selectionPublishing=false,queuedTarget=null;const user=document.body.dataset.pdUserId||context?.dataset.user||'',page=crypto.randomUUID(),buttons=[...document.querySelectorAll('[data-shared-focus-hold]')],outputs=[...document.querySelectorAll('[data-shared-focus-status]')];let id=context?.contextController?.windowId||sessionStorage.getItem('pd.shared-focus.window');if(!/^[\da-f-]{36}$/i.test(id||''))id=crypto.randomUUID();sessionStorage.setItem('pd.shared-focus.window',id);const normal=p=>({projectID:Number(p.projectID||p.projectId||project),bookID:Number(p.bookID||p.bookId||book),chapterID:Number(p.chapterID||p.chapterId)||null,sceneID:Number(p.sceneID||p.sceneId)||null,paragraphID:p.paragraphID||p.paragraphId||null,manuscriptID:p.manuscriptID||p.manuscriptId||null,originWindowID:p.originWindowID||p.originWindowId||null,version:Number(p.version||0),isValid:p.isValid!==false});const key=()=>`pd.shared-focus.${user}.${id}`;const positionKey=p=>p&&[p.projectID,p.bookID,p.manuscriptID,p.chapterID,p.sceneID,p.paragraphID].join('/');function save(){try{sessionStorage.setItem(key(),JSON.stringify({held,local,sequence}));}catch{}}function restore(){try{const data=JSON.parse(sessionStorage.getItem(key())||'null');held=data?.held??context?.dataset.followMode==='snapshot';local=data?.local||normal(context?.contextController?.position||{...initial,chapterID:Number(reader?.dataset.chapterId)||initial.chapterID});sequence=data?.sequence||0;}catch{held=false;}} +function status(message=''){buttons.forEach(b=>{(b.querySelector('span')||b).textContent=held?'Held · Release Hold':'Following · Hold';b.setAttribute('aria-pressed',String(held));b.disabled=!book;});outputs.forEach(n=>n.textContent=message||(held?'Held at local manuscript position · data updates remain live':'Following shared manuscript focus'));document.documentElement.dataset.manuscriptFocusMode=held?'held':'follow';}function apply(position,reason){local=normal(position);save();window.dispatchEvent(new CustomEvent('plotdirector:shared-focus',{detail:{position:local,reason}}));status();}function accept(packet,force=false){const next=normal(packet);if(next.bookID!==book||next.projectID!==project)return false;if(latest&&(next.versionnull);if(!response.ok||response.redirected)throw Error(packet?.message||'Focus could not be changed. Your local reference is retained.');return normal(packet);} +async function refresh(force=false){if(!book)return;const mine=++epoch;try{const response=await fetch(`/NarrativeFocus/Shared?projectID=${project}&bookID=${book}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const packet=await response.json();if(mine===epoch){const recovering=disconnected;disconnected=false;accept(packet,force);if(recovering){status();void validateLocal();}return true;}return false;}catch{disconnected=true;status('Shared focus disconnected · local position and data are retained. Reconnect to catch up.');return false;}} +async function navigate(target,forcePublication=false){const priorLocal=local;if(target.localSelection&&Number(target.bookID||book)===book){local=normal({...local,projectID:project,bookID:book,chapterID:target.chapterID,sceneID:target.sceneID||null,paragraphID:target.paragraphID});save();}if(publishing){queuedTarget=target;return true;}const effective=held?priorLocal:latest?.isValid?latest:null;if(!forcePublication&&Number(target.sceneID||target.sceneId)>0&&Number(target.sceneID||target.sceneId)===effective?.sceneID&&!effective.paragraphID&&!target.paragraphID&&!target.paragraphId)return true;const paragraph=target.paragraphID||target.paragraphId;if(!forcePublication&¶graph&¶graph===effective?.paragraphID&&Number(target.chapterID||target.chapterId)===effective.chapterID)return true;if(publishing)return false;if(target.bookID&&Number(target.bookID)!==book)return false;publishing=true;const localRequest=held;selectionPublishing=target.localSelection===true;try{const normalized={chapterID:target.chapterID||target.chapterId||null,sceneID:target.sceneID||target.sceneId||null,paragraphID:target.paragraphID||target.paragraphId||null,...(target.direction?{direction:target.direction}:{}),...(target.manuscriptID?{manuscriptID:target.manuscriptID}:{})};if(held&&target.direction)Object.assign(normalized,{chapterID:local.chapterID,sceneID:local.sceneID});const result=await request(localRequest?'Resolve':'Publish',normalized);if(result.bookID!==book||result.projectID!==project)return false;if(localRequest){if(held)apply(result,selectionPublishing?'selection':'local');else await refresh(true);}else accept(result,true);return true;}catch(error){status(error.message);return false;}finally{publishing=false;selectionPublishing=false;if(queuedTarget){const next=queuedTarget;queuedTarget=null;void navigate(next,true);}}} +async function toggle(){queuedTarget=null;if(held){if(!await refresh()){status('Hold retained: reconnect before catching up to authoritative shared focus.');return;}held=false;save();if(latest?.isValid&&latest.chapterID)apply(latest,'release');else status('Following · no valid shared focus; local position retained.');}else{held=true;save();status();}window.dispatchEvent(new CustomEvent('plotdirector:focus-mode',{detail:{held}}));} +async function validateLocal(){if(!held||!local?.chapterID)return;try{const result=await request('Validate',local);if(!result.isValid)status('Held reference is no longer valid. Select another local position or Release Hold.');}catch{status('Held reference cannot be resolved. Select another position; data updates remain connected.');}} +function wire(c){if(!c||connection)return;connection=c;c.on('ManuscriptFocusChanged',packet=>accept(packet));c.on('ManuscriptFocusDelivery',packet=>{if(Number(packet.bookID||packet.bookId)===book&&Number(packet.version)===latest?.version)status('Word cannot follow this reference in the background. Save and synchronise Word; other windows remain independent.');});c.on('ContextInvalidated',hint=>{if(hint.bookId&&Number(hint.bookId)!==book||hint.projectId&&Number(hint.projectId)!==project)return;window.dispatchEvent(new CustomEvent('plotdirector:reference-invalidated',{detail:hint}));void validateLocal();});c.onreconnecting(()=>{disconnected=true;status('Shared focus reconnecting · local position retained.');});c.onclose(()=>{disconnected=true;status('Shared focus disconnected · local position retained.');});c.onreconnected(()=>{void refresh().then(()=>validateLocal());});void refresh();} +const channel=!context&&window.BroadcastChannel?new BroadcastChannel('pd.shared-focus.identity.'+user):null;channel?.addEventListener('message',event=>{const m=event.data;if(m.id!==id||m.page===page)return;if(m.kind==='claim')channel.postMessage({kind:'occupied',id,page,target:m.page});if(m.kind==='occupied'&&m.target===page){id=crypto.randomUUID();sessionStorage.setItem('pd.shared-focus.window',id);held=false;sequence=0;save();status();void refresh(true);}});channel?.postMessage({kind:'claim',id,page}); +context?.addEventListener('context-capabilities-changed',()=>{const next=context.contextController?.windowId;if(next&&next!==id){id=next;held=false;sequence=0;save();status();void refresh(true);}}); +restore();status();buttons.forEach(b=>b.addEventListener('click',()=>void toggle()));document.addEventListener('pd-presence-connection',e=>wire(e.detail));document.addEventListener('pd-presence-ready',()=>wire(window.PlotDirectorPresenceConnection));context?.addEventListener('context-connection-ready',()=>wire(context.contextController?.connection));wire(context?.contextController?.connection||window.PlotDirectorPresenceConnection);window.addEventListener('focus',()=>void refresh());window.addEventListener('pagehide',()=>{save();channel?.close();});window.PlotDirectorSharedFocus={navigate,refresh,toggle,validateLocal,get held(){return held;},get local(){return local;},get shared(){return latest;},get windowID(){return id;},async go(){if(await refresh(true)&&held&&latest?.isValid)apply(latest,'local');},ownsScope:p=>Number(p.bookID)===book&&Number(p.projectID)===project,async scope(p){project=Number(p.projectID);book=Number(p.bookID);queuedTarget=null;latest=null;const wasHeld=held;restore();held=wasHeld;local=normal(p);save();status();if(held)apply(local,'local');await refresh(true);}};document.addEventListener('click',async event=>{if(!event.isTrusted||event.defaultPrevented||event.button!==0||event.ctrlKey||event.metaKey||event.shiftKey||event.altKey)return;const link=event.target.closest('a[href]');if(!link||link.target&&link.target!=='_self'||link.closest('.reader-chapter-navigation'))return;const url=new URL(link.href,location.href);if(url.origin!==location.origin||url.searchParams.get('retainNarrativeFocus')==='true')return;const match=url.pathname.match(/^\/(Scenes\/Edit|Chapters\/(?:Details|Edit)|Writer\/Chapter)\/(\d+)$/i),timeline=/^\/Timeline(?:\/Index)?$/i.test(url.pathname)&&url.searchParams.get('navigateFocus')==='true';if(!match&&!timeline)return;const selectedScene=Number([...url.searchParams].find(([key])=>key.toLowerCase()==='selectedsceneid')?.[1]);const target=timeline?{sceneID:selectedScene}:match[1].toLowerCase()==='scenes/edit'?{sceneID:Number(match[2])}:{chapterID:Number(match[2])};if(timeline&&!selectedScene)return;event.preventDefault();const adapter=window.PlotDirectorFocusWorkspace?.adapter;try{if(adapter?.beforeChange&&await adapter.beforeChange(target)===false)return;await navigate(target);url.searchParams.delete('navigateFocus');url.searchParams.set('retainNarrativeFocus','true');location.assign(url);}finally{adapter?.changeFinished?.();}});window.dispatchEvent(new Event('plotdirector:shared-focus-ready'));void refresh();if(held&&local?.chapterID){apply(local,'restore');void validateLocal();}} +if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})(); diff --git a/PlotLine/wwwroot/js/writer-review.js b/PlotLine/wwwroot/js/writer-review.js index c2dbaa9f..454c0349 100644 --- a/PlotLine/wwwroot/js/writer-review.js +++ b/PlotLine/wwwroot/js/writer-review.js @@ -44,6 +44,6 @@ readerContent.addEventListener('keyup',()=>{if(dirty||busy)return;const choice=c reader.addEventListener('reader:metadata',()=>{if(!dirty)wordReference(selected);}); reader.addEventListener('reader:updated',()=>{if(dirty)return;if(selected&&!readerContent.querySelector(`[data-paragraph-id="${CSS.escape(selected)}"]`)){selected=null;anchor=null;wordReference(null);message.textContent='The selected paragraph is no longer in the accepted chapter. Original observation references remain recorded.';}else wordReference(selected);void load();}); function guard(e){if(!dirty&&!busy)return;const target=e.target.closest('a,form');if(!target||target===form||target.matches('[data-work-start]')||target.target==='_blank'||target.matches('.plotline-help-more')&&window.PlotLineHelpDrawer)return;if(!confirm(busy?'An observation save may still finish. Leave this Review page?':'Leave without saving your review observation?')){e.preventDefault();e.stopImmediatePropagation();}else allowLeave=true;} -onDocument('click',e=>{if(e.target.closest('a'))guard(e);},true);onDocument('submit',guard,true);onWindow('beforeunload',e=>{if((dirty||busy)&&!allowLeave){e.preventDefault();e.returnValue='';}});onWindow('pageshow',e=>{allowLeave=false;if(e.persisted&&!dirty)void load();});onWindow('pagehide',()=>{clearTimeout(selectionTimer);controller?.abort();});for(const b of document.querySelectorAll('[data-review-scope-new]'))b.addEventListener('click',()=>{begin(b.dataset.reviewScopeNew);});onWindow('review:notes-saved',()=>void load());void load(); +onDocument('click',e=>{if(e.target.closest('a'))guard(e);},true);onDocument('submit',guard,true);onWindow('beforeunload',e=>{if((dirty||busy)&&!allowLeave){e.preventDefault();e.returnValue='';}});onWindow('pageshow',e=>{allowLeave=false;if(e.persisted&&!dirty)void load();});onWindow('pagehide',()=>{clearTimeout(selectionTimer);controller?.abort();});for(const b of document.querySelectorAll('[data-review-scope-new]'))b.addEventListener('click',()=>{begin(b.dataset.reviewScopeNew);});onWindow('plotdirector:reference-invalidated',event=>{const hint=event.detail||{};if(hint.bookId&&Number(hint.bookId)!==Number(root.dataset.book))return;if(root.canChangeNarrative())void load(true,true);else message.textContent='Saved information changed. Your local reference and edits are retained; reload observations when ready.';});onWindow('review:notes-saved',()=>void load());void load(); } window.PlotDirectorReview={mount:initialiseReview};initialiseReview();