diff --git a/Docs/Writer/Context-UX-Refinement-20261122.md b/Docs/Writer/Context-UX-Refinement-20261122.md new file mode 100644 index 00000000..6bd62eb0 --- /dev/null +++ b/Docs/Writer/Context-UX-Refinement-20261122.md @@ -0,0 +1,17 @@ +# Context UX refinement, Names Library and visual relationships + +Development-only programme requested 22 November 2026. Base implementation: `504ecca`; evidence-only follow-up `2eede4e`. Existing untracked user investigations remain untouched. Production is outside scope. + +## Stage 1: shared UI and main-window reuse + +Shared correction form geometry gives all controls full available content width, consistent spacing, minimum textarea height and vertical resizing. The shell dialog responds to viewport width independently of its originating pane. Loaded forms expose one Save and one Cancel; the shell fallback Cancel appears only if loading fails. Nested labels, initial input focus, Escape, inline validation, dirty-draft confirmation and the shared toast service are retained. + +Main navigation extends `ContextWindows` / the existing authenticated presence hub with `workspace.open` and a closed structured target `{tool, entityID}`. `ContextNavigationController` resolves permitted Characters, Names, Relationships and Scene targets from canonical IDs after book/project/entity checks. No caller-supplied URL is accepted. Main shells register on the existing native presence connection; a shell without that connection creates one shared connection, not one per feature. Context windows retain their one connection. + +A user/browser-profile environment preference restricts automatic main navigation to the same browser environment. It is not an authentication credential: every command and destination is independently authorised. Normal reference focus commands retain their book isolation; main navigation is explicitly allowed to an authenticated same-user main shell currently showing another book, because it revalidates the requested book before navigating. Another environment/device is never selected automatically. Browser-private/storage-disabled environments cannot share this preference and use the named-window fallback. + +Main recipients acknowledge navigation, attempt focus where permitted and protect unsaved ordinary forms; Maps uses its existing `requestLeave` guard. Busy/declined/unconfirmed requests do not automatically open another window. Missing recipients use one named main window and an account/environment-scoped ten-second launch reservation in the existing registry to suppress concurrent fallback opens. Blocked popups retain an explicit named link retry. Focus and named-window targeting remain subject to browser security and browsing-context isolation. Transient leases, reconnect registration, authenticated IDs and data-change notifications remain separate from navigation. No Word navigation is requested. + +Context workspace links use `data-context-workspace-target` plus optional `data-context-entity` as the reusable standard; href remains an accessible fallback. Existing main editors are not redesigned. + +Stage 1 qualification: clean solution build (zero warnings/errors), 19 registry/routing/lease assertions, real-SignalR isolated browser routing suite, existing Characters editing/responsive suite and expanded shared-refinement browser acceptance passed. Every existing character/name correction variant (classification, description, emotional state, physical condition, location, canonical name, alias add and alias correction/removal) and the relationship form was checked for full-width controls; desktop/mobile, one Save/Cancel and Escape passed. Existing-main reuse, repeated actions, unsaved-main cancellation and one named missing-main fallback passed. Browser fixture editor endpoints render the real application shell/views; canonical persistence is qualified separately. Relationship main-editor navigation retains the selected story point. No database migration was needed in this stage. diff --git a/PlotLine.Tests/Browser/context-refine-live-navigation.cjs b/PlotLine.Tests/Browser/context-refine-live-navigation.cjs new file mode 100644 index 00000000..19e84717 --- /dev/null +++ b/PlotLine.Tests/Browser/context-refine-live-navigation.cjs @@ -0,0 +1,7 @@ +// Explicit Development-only read/navigation acceptance on disposable scope; no Word commands or edits. +const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict'); +(async()=>{assert(process.env.PD_CONTEXT_IDENTITY&&process.env.PD_CONTEXT_SCOPE);const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),s=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE));assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);assert(who.Email.startsWith('pwa-browser-'));const b=await chromium.launch();let step='login';try{const c=await b.newContext({viewport:{width:1366,height:900}}),main=await c.newPage();await main.goto('https://dev.plotdirector.com/Account/Login');await main.locator('[name=Email]').fill(who.Email);await main.locator('[name=Password]').fill(who.Password);await Promise.all([main.waitForURL(u=>u.pathname!='/Account/Login'),main.locator('button[type=submit]').click()]);await main.goto('https://dev.plotdirector.com/Projects/Details/'+s.project);let word=0;c.on('request',r=>{if(/\/(Writing\/Context|WriterWord)\/Navigate/.test(new URL(r.url()).pathname))word++;});const p=await c.newPage();await p.goto(`https://dev.plotdirector.com/Writing/Context?projectId=${s.project}&bookId=${s.book}&sceneId=${s.scene}`);await p.waitForSelector('[data-context-tab-fragment]');await p.waitForFunction(book=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected'&&document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',book).then(rows=>rows.some(r=>r.kind==='main'&&r.environmentID===window.PlotDirectorContextEnvironment)),s.book); + const count=c.pages().length;step='scene editor in existing main';await p.click('[data-context-editor]');await main.waitForURL(u=>u.pathname==='/Scenes/Edit/'+s.scene);assert.equal(c.pages().length,count); + for(const [tool,button,path] of [['characters',`[data-context-workspace-target="characters"][data-context-entity="${s.characters[0]}"]`,'/Characters/Details/'+s.characters[0]],['names','[data-context-workspace-target="names"]','/Names'],['relationships','[data-context-workspace-target="relationships"]','/RelationshipMap']]){step=tool+' existing-main reuse';await p.selectOption('[data-context-tab]',tool);await p.waitForSelector('[data-context-tab-fragment]');if(tool==='characters'){const row=p.locator(`[data-context-character="${s.characters[0]}"]`);if(!await row.evaluate(n=>n.open))await row.locator('summary').click();}await p.waitForTimeout(600);await p.locator(button).last().click();await main.waitForURL(u=>u.pathname===path);assert.equal(c.pages().length,count);} + assert.equal(word,0);assert.equal(await p.locator('[data-context-scene]').inputValue(),String(s.scene));console.log('PASS Development main-window navigation: actual scene, character, Names and Relationships editors reused one existing main window; Context scene and Word position unchanged. Browser focus remains discretionary.'); +} catch(e){console.error('FAILED '+step+': '+e.message);process.exitCode=1;}finally{await b.close();}})(); diff --git a/PlotLine.Tests/Browser/context-refine-shared.cjs b/PlotLine.Tests/Browser/context-refine-shared.cjs new file mode 100644 index 00000000..b1cd07d2 --- /dev/null +++ b/PlotLine.Tests/Browser/context-refine-shared.cjs @@ -0,0 +1,13 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; +(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1280,height:900}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));for(const url of ['**/native-companion/status','**/native-companion/connection-state','**/Writing/Context/Position?*'])await c.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{known:false,connected:false}}));await c.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});}); + await c.route('**/Writing/Context/EditCharacter?*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-edit-fixture?field='+u.searchParams.get('field')})});});await c.route('**/Writing/Context/EditRelationship?*',async r=>r.fulfill({response:await r.fetch({url:base+'/context-relationship-edit-fixture'})})); + const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto(base+'/Writing/Context');await p.selectOption('[data-context-tab]','characters');await p.waitForSelector('[data-character-explorer]'); + step='all shared modal forms fill content';for(const width of [1280,390]){await p.setViewportSize({width,height:900});for(const field of ['classification','description','emotion','condition','location','name','alias-add','alias:11']){await p.evaluate(field=>{const host=document.querySelector('[data-character-explorer]'),button=document.createElement('button');button.dataset.contextEdit=field;button.dataset.characterId='5';host.append(button);button.click();button.remove();},field);await p.waitForSelector('[data-context-edit-form]');assert.equal(await p.locator('[data-context-edit-dialog] button:visible').count(),2);assert(await p.locator('[data-context-edit-form]').evaluate(f=>[...f.querySelectorAll('textarea,select,input:not([type=hidden]):not([type=checkbox])')].every(n=>n.getBoundingClientRect().width>=f.clientWidth*.92&&n.scrollWidth<=n.clientWidth+2)));await p.keyboard.press('Escape');await p.waitForFunction(()=>!document.querySelector('[data-context-edit-dialog]').open);}} + step='relationship modal shares full-width layout';await p.selectOption('[data-context-tab]','relationships');await p.waitForSelector('[data-context-relationships]');await p.locator('[data-context-relationship="9"] summary').first().click();await p.locator('[data-context-relationship="9"] [data-context-relationship-edit="scene"]').click();await p.waitForSelector('[data-context-edit-form]');assert(await p.locator('[data-context-edit-form]').evaluate(f=>[...f.querySelectorAll('textarea,select,input:not([type=hidden]):not([type=checkbox])')].every(n=>n.getBoundingClientRect().width>=f.clientWidth*.92)));assert.equal(await p.locator('[data-context-edit-dialog] button:visible').count(),2);await p.keyboard.press('Escape');await p.selectOption('[data-context-tab]','characters');await p.waitForSelector('[data-character-explorer]'); + step='main shell registers on existing native connection';const main=await c.newPage();let hubs=0;main.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))hubs++;});await main.goto(base+'/fixture?layout=full');await p.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',12).then(rows=>rows.some(r=>r.kind==='main')));assert.equal(hubs,1); + step='scene editor reuses main window with no popup';const originalPages=c.pages().length;await p.click('[data-context-editor]');await main.waitForURL(/\/Scenes\/Edit\/22/);assert.equal(c.pages().length,originalPages);assert.equal(await p.locator('[data-context-tab]').first().inputValue(),'characters'); + step='repeat navigation retains one main window';await p.waitForTimeout(550);await main.waitForFunction(()=>window.PlotDirectorPresenceConnection?.state==='Connected');await p.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',12).then(rows=>rows.some(r=>r.kind==='main')));await p.click('[data-context-editor]');await p.waitForTimeout(700);assert.equal(c.pages().length,originalPages); + step='unsaved main form can decline navigation';await main.waitForTimeout(500);const beforeDirty=main.url();await main.evaluate(()=>{const f=document.createElement('form');f.method='post';f.innerHTML='';document.body.append(f);});await main.locator('[name=SyntheticDraft]').fill('Unsaved draft');main.once('dialog',d=>d.dismiss());await p.waitForTimeout(550);await p.locator('a[href="/Characters?projectId=7"]').click();await p.waitForTimeout(700);assert.equal(main.url(),beforeDirty);assert.equal(c.pages().length,originalPages); + step='missing main opens only one named fallback';await main.close();const popupPromise=p.waitForEvent('popup');await p.waitForTimeout(550);await p.locator('a[href="/Characters?projectId=7"]').click();const popup=await popupPromise;await popup.waitForURL(/Characters\?projectId=7/);await popup.waitForFunction(()=>window.PlotDirectorPresenceConnection?.state==='Connected',{},{timeout:7000}).catch(async e=>{const info=await popup.evaluate(()=>({user:document.body.dataset.pdUserId,books:document.body.dataset.pdBookIds,env:window.PlotDirectorContextEnvironment,state:window.PlotDirectorPresenceConnection?.state,ready:document.readyState,title:document.title}));throw Error(e.message+JSON.stringify(info));});await p.waitForTimeout(550);await p.locator('a[href="/Characters?projectId=7"]').click();await p.waitForTimeout(600);assert.equal(c.pages().length,originalPages); + assert.deepEqual(errors,[]);console.log('PASS shared Context refinement: all eight character/name modal variants full-width at desktop/mobile, one Save/Cancel, Escape; real registry/main shell reuses native connection and existing main window, repeated navigation creates no popup.'); +} catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await b.close();}})(); diff --git a/PlotLine.Tests/ContextWindowsTests.cs b/PlotLine.Tests/ContextWindowsTests.cs index ef5a5df0..7fc9cd3b 100644 --- a/PlotLine.Tests/ContextWindowsTests.cs +++ b/PlotLine.Tests/ContextWindowsTests.cs @@ -22,6 +22,13 @@ internal static class ContextWindowsTests store.Remove("remote-device");Check(store.Route(7,"origin",command)==null,"disconnect removes eligible destinations"); clock.Now+=TimeSpan.FromSeconds(61);Check(store.List(7,12).Length==0,"missed disconnects expire on authoritative discovery"); store.Register(7,"reconnected",Registration(first,12,"scene.focus"));Check(store.List(7,12).Length==1,"reconnection registers current capability state"); + var environment=Guid.NewGuid();store.Register(7,"reconnected",Registration(first,12,"scene.focus") with{EnvironmentID=environment}); + store.Register(7,"main-remote",new(1,12,Guid.NewGuid(),[new("0","main",["workspace.open"])],Guid.NewGuid(),"main")); + var open=new ContextInteraction(1,12,"0","workspace.open",Workspace:new("characters",5));Check(store.Route(7,"reconnected",open)==null,"main navigation never targets another browser environment/device"); + store.Register(7,"main-local",new(1,13,Guid.NewGuid(),[new("0","main",["workspace.open"])],environment,"main",[12,13])); + Check(store.Route(7,"reconnected",open)?.Window.Connection=="main-local","same-environment main shell can receive authorised navigation for its project books"); + Check(store.Route(7,"reconnected",open with{TargetSessionID="main-remote"})==null,"explicit target cannot bypass same-environment restriction"); + store.Remove("main-local");store.Remove("main-remote");Check(store.TryLaunch(7,"reconnected",12,environment),"one browser environment can reserve a missing main-window launch");Check(!store.TryLaunch(7,"reconnected",12,environment),"concurrent fallback launches are suppressed");clock.Now+=TimeSpan.FromSeconds(11);Check(store.TryLaunch(7,"reconnected",12,environment),"failed or blocked main launches can be retried after the short lease"); try{store.Register(7,"bad",new(1,12,Guid.NewGuid(),[new("0","fake",["word.navigate"])]));throw new Exception("Word action accepted");}catch(ArgumentException){Check(true,"interaction contract cannot invoke Word navigation");} } } diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index eeada1f1..85fe1c01 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -260,10 +260,11 @@ internal static class ToolbarBrowserHost model.SceneID=id;model.ChapterID=id==32?22:21;model.SceneNumber=id==101?2:1; model.SceneTitle=$"Fixture scene {id}"; model.Chapter!.ChapterID=model.ChapterID;model.Chapter.ChapterNumber=id==32?2:1; - if(context.Request.Query["retainNarrativeFocus"]!="true") + if(context.Request.Query["retainNarrativeFocus"]!="true"&&id is not (22 or 23)) await context.RequestServices.GetRequiredService().Open(context.RequestServices.GetRequiredService().UserId!.Value,null,id); await RenderFullAsync(context,"Scenes","Edit",model); }).WithOrder(-1); + app.MapGet("/Characters",async (HttpContext context)=>await RenderFullAsync(context,"Characters","Index",new CharacterListViewModel{Project=new(){ProjectID=7,ProjectName="Fixture project",AccessRole="Owner"},Characters=[new(){CharacterID=5,ProjectID=7,CharacterName="Fixture participant",CharacterImportance=6}]})).WithOrder(-1); app.MapGet("/Projects", () => Results.Redirect("/fixture")); app.MapGet("/map-story-fixture", () => { var projection = MapStoryComposer.Compose(MapStoryTests.Fixture(), MapStoryTests.Plots(), 1); @@ -397,6 +398,7 @@ internal static class ToolbarBrowserHost app.MapGet("/context-edit-fixture",async context=>{ var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Writing/_ContextCharacterEdit.cshtml",false); var model=new PlotLine.Services.Context.ContextCharacterEditForm{BookID=12,SceneID=22,CharacterID=5,Field=context.Request.Query["field"].ToString(),CharacterName="Fixture participant",Label="Focused correction",Value="Saved value",Fingerprint="fixture-fingerprint"}; + if(model.Field is "classification" or "location")model.Options=[new("Recorded option","Saved value"),new("Other option","Other")]; using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model}; if(context.Request.Query["invalid"]=="true"){data.ModelState.AddModelError("Value","Synthetic validation: draft retained.");model.Value="Entered draft";} await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions()));context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString()); diff --git a/PlotLine/Controllers/ContextNavigationController.cs b/PlotLine/Controllers/ContextNavigationController.cs new file mode 100644 index 00000000..1293a0b9 --- /dev/null +++ b/PlotLine/Controllers/ContextNavigationController.cs @@ -0,0 +1,26 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using PlotLine.Data; +using PlotLine.Services; +namespace PlotLine.Controllers; +[Authorize,Route("Writing/Context"),ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] +public sealed class ContextNavigationController(IWordCompanionRepository companion,ICurrentUserService currentUser):Controller +{ + [HttpGet("OpenWorkspace")] + public async Task OpenWorkspace(int bookId,string tool,int? entityId,[FromServices] IBookRepository books,[FromServices] ICharacterRepository characters,bool resolve=false,int? sceneId=null) + { + var structure=currentUser.UserId.HasValue?await companion.GetBookStructureAsync(bookId,currentUser.UserId.Value):null;if(structure==null)return Forbid(); + var book=await books.GetAsync(bookId);if(book==null)return NotFound(); + if(sceneId.HasValue&&!structure.Chapters.Any(c=>c.Scenes.Any(s=>s.SceneId==sceneId)))return BadRequest(); + string? url=null; + if(tool=="characters"&&(!entityId.HasValue||(await characters.GetCharacterAsync(entityId.Value))?.ProjectID==book.ProjectID))url=entityId.HasValue?$"/Characters/Details/{entityId}":$"/Characters?projectId={book.ProjectID}"; + if(tool=="names"&&!entityId.HasValue)url=$"/Names?projectId={book.ProjectID}&bookId={bookId}"; + if(tool=="relationships"){ + var relation=entityId.HasValue?await characters.GetRelationshipAsync(entityId.Value):null; + if(!entityId.HasValue||relation?.ProjectID==book.ProjectID)url=$"/RelationshipMap?projectId={book.ProjectID}&bookId={bookId}"+(relation==null?"":$"&focusCharacterId={relation.CharacterAID}"); + } + if(tool=="scene"&&entityId.HasValue&&structure.Chapters.Any(c=>c.Scenes.Any(s=>s.SceneId==entityId)))url=$"/Scenes/Edit/{entityId}"; + if(url==null)return BadRequest();if(tool=="relationships"&&sceneId.HasValue)url+=$"&sceneId={sceneId}";return resolve?Ok(new{url}):Redirect(url); + } + +} diff --git a/PlotLine/Hubs/NativeCompanionPresenceHub.cs b/PlotLine/Hubs/NativeCompanionPresenceHub.cs index f4332f7e..b7facaa0 100644 --- a/PlotLine/Hubs/NativeCompanionPresenceHub.cs +++ b/PlotLine/Hubs/NativeCompanionPresenceHub.cs @@ -17,7 +17,9 @@ public sealed class NativeCompanionPresenceHub(ContextWindows windows,IWordCompa => await access.GetBookStructureAsync(book,Author)??throw new HubException("Book unavailable."); public async Task RegisterContextWindow(ContextWindowRegistration registration) { - if(registration==null)throw new HubException("Invalid registration.");await Book(registration.BookID); + if(registration==null)throw new HubException("Invalid registration.");if(registration.BookID>0||registration.Kind!="main")await Book(registration.BookID); + if(registration.Kind!="main"&®istration.BookIDs?.Length>0)throw new HubException("Invalid book registration."); + if(registration.Kind=="main"){if(registration.EnvironmentID is null||registration.EnvironmentID==Guid.Empty)throw new HubException("Browser environment required.");foreach(var id in (registration.BookIDs??[]).Distinct().Take(65))await Book(id);} var prior=windows.Read(Context.ConnectionId); try{windows.Register(Author,Context.ConnectionId,registration);}catch(Exception e)when(e is ArgumentException or InvalidOperationException){throw new HubException(e.Message);} if(prior!=null&&prior.Registration.BookID!=registration.BookID){await Groups.RemoveFromGroupAsync(Context.ConnectionId,ContextWindows.Group(Author,prior.Registration.BookID));await Clients.Group(ContextWindows.Group(Author,prior.Registration.BookID)).SendAsync("ContextWindowsChanged");} @@ -27,6 +29,8 @@ public sealed class NativeCompanionPresenceHub(ContextWindows windows,IWordCompa await Clients.Group(ContextWindows.Group(Author,registration.BookID)).SendAsync("ContextWindowsChanged"); return windows.List(Author,registration.BookID); } + public async Task ClaimContextMainWindow(int bookId,Guid environmentID) + {await Book(bookId);try{return windows.TryLaunch(Author,Context.ConnectionId,bookId,environmentID);}catch(ArgumentException){throw new HubException("Invalid navigation scope.");}} public async Task MyContextWindows(int bookId){await Book(bookId);return windows.List(Author,bookId);} public async Task SendContextInteraction(ContextInteraction command) { @@ -39,6 +43,7 @@ public sealed class NativeCompanionPresenceHub(ContextWindows windows,IWordCompa "location.focus" or "location.focusAtStoryPoint"=>command.LocationID is >0&&(await locations.GetAsync(command.LocationID.Value))?.ProjectID==book.ProjectID, "relationship.focus"=>command.RelationshipID is >0&&(await characters.GetRelationshipAsync(command.RelationshipID.Value))?.ProjectID==book.ProjectID, "scene.focus"=>command.StoryPoint?.SceneID is >0, + "workspace.open"=>await WorkspaceAllowed(command,book.ProjectID,structure), _=>false}; if(!allowed)throw new HubException("Reference unavailable in this book's project."); (ContextWindowLease Window,ContextPaneCapability Pane,Guid CommandID)? target; @@ -47,6 +52,15 @@ public sealed class NativeCompanionPresenceHub(ContextWindows windows,IWordCompa await Clients.Client(target.Value.Window.Connection).SendAsync("ContextInteraction",new ContextInteractionDelivery(target.Value.CommandID,command,target.Value.Pane.PaneID)); return new("delivered",target.Value.CommandID); } + private async Task WorkspaceAllowed(ContextInteraction command,int project,PlotLine.Models.WordCompanionBookStructureResponse structure) + { + var target=command.Workspace;if(target==null)return false; + return target.Tool switch{ + "characters"=>!target.EntityID.HasValue||(await characters.GetCharacterAsync(target.EntityID.Value))?.ProjectID==project, + "names"=>!target.EntityID.HasValue, + "relationships"=>!target.EntityID.HasValue||(await characters.GetRelationshipAsync(target.EntityID.Value))?.ProjectID==project, + "scene"=>target.EntityID is >0&&structure.Chapters.Any(c=>c.Scenes.Any(s=>s.SceneId==target.EntityID)),_=>false}; + } public async Task CompleteContextInteraction(Guid commandId,string status) { if(status is not ("focused" or "not-visible" or "busy" or "unavailable"))throw new HubException("Invalid result."); diff --git a/PlotLine/Services/Context/ContextWindows.cs b/PlotLine/Services/Context/ContextWindows.cs index c6589a78..a1329ea8 100644 --- a/PlotLine/Services/Context/ContextWindows.cs +++ b/PlotLine/Services/Context/ContextWindows.cs @@ -1,12 +1,13 @@ namespace PlotLine.Services.Context; public sealed record ContextPaneCapability(string PaneID, string ToolID, string[] Actions, bool Available = true); -public sealed record ContextWindowRegistration(int Version, int BookID, Guid WindowID, ContextPaneCapability[] Panes); -public sealed record ContextConnectedWindow(Guid WindowID, string SessionID, int BookID, ContextPaneCapability[] Panes, DateTimeOffset LastSeen); +public sealed record ContextWindowRegistration(int Version, int BookID, Guid WindowID, ContextPaneCapability[] Panes,Guid? EnvironmentID=null,string Kind="context",int[]? BookIDs=null); +public sealed record ContextConnectedWindow(Guid WindowID, string SessionID, int BookID, ContextPaneCapability[] Panes, DateTimeOffset LastSeen,Guid? EnvironmentID=null,string Kind="context"); public sealed record ContextStoryPoint(int? ChapterID, int? SceneID); public sealed record ContextInteraction(int Version, int BookID, string OriginPaneID, string Action, int? CharacterID = null, int? LocationID = null, int? RelationshipID = null, ContextStoryPoint? StoryPoint = null, - Guid? TargetWindowID = null, string? TargetPaneID = null, int? TargetUserID = null, string? TargetSessionID = null); + Guid? TargetWindowID = null, string? TargetPaneID = null, int? TargetUserID = null, string? TargetSessionID = null,ContextWorkspaceTarget? Workspace=null); +public sealed record ContextWorkspaceTarget(string Tool,int? EntityID=null); public sealed record ContextInteractionDelivery(Guid CommandID, ContextInteraction Command, string PaneID); public sealed record ContextInteractionResult(string Status, Guid? CommandID = null); public sealed record ContextWindowLease(int User, string Connection, ContextWindowRegistration Registration, DateTimeOffset Seen); @@ -18,18 +19,25 @@ public sealed class ContextWindows(TimeProvider clock) private readonly object gate = new(); private readonly Dictionary leases = []; private readonly Dictionary pending = []; - public static readonly string[] Actions = ["character.focus", "location.focus", "location.focusAtStoryPoint", "relationship.focus", "scene.focus"]; + public static readonly string[] Actions = ["character.focus", "location.focus", "location.focusAtStoryPoint", "relationship.focus", "scene.focus", "workspace.open"]; public static string Group(int user,int book) => $"context-windows:{user}:{book}"; + private readonly Dictionary<(int,Guid),DateTimeOffset> launches=[]; + public bool TryLaunch(int user,string connection,int book,Guid environment) + {lock(gate){Prune();var source=leases.GetValueOrDefault(connection);if(source?.User!=user||source.Registration.BookID!=book||source.Registration.EnvironmentID!=environment||environment==Guid.Empty)throw new ArgumentException("Invalid navigation scope."); + if(leases.Values.Any(x=>x.User==user&&x.Registration.Kind=="main"&&x.Registration.EnvironmentID==environment)||launches.ContainsKey((user,environment))||launches.Count>=4096)return false; + launches[(user,environment)]=clock.GetUtcNow().AddSeconds(10);return true;}} private void Prune() { var now=clock.GetUtcNow(); + foreach(var key in launches.Where(x=>x.Value<=now).Select(x=>x.Key).ToArray())launches.Remove(key); foreach(var key in leases.Where(x=>now-x.Value.Seen>TimeSpan.FromSeconds(60)).Select(x=>x.Key).ToArray())leases.Remove(key); foreach(var key in pending.Where(x=>x.Value.Expires<=now).Select(x=>x.Key).ToArray())pending.Remove(key); } public ContextWindowLease? Read(string connection) { lock(gate){Prune();return leases.GetValueOrDefault(connection);} } public void Register(int user,string connection,ContextWindowRegistration registration) { - if(registration.Version!=1||registration.BookID<=0||registration.WindowID==Guid.Empty||registration.Panes==null||registration.Panes.Length>2|| + if(registration.Version!=1||(registration.BookID<=0&®istration.Kind!="main")||registration.WindowID==Guid.Empty||registration.Panes==null||registration.Panes.Length>2|| + registration.Kind is not ("context" or "main")||registration.BookIDs?.Length>64|| registration.Panes.Any(p=>p==null||p.PaneID is not ("0" or "1")||string.IsNullOrWhiteSpace(p.ToolID)||p.ToolID.Length>48||p.Actions==null||p.Actions.Length>Actions.Length||p.Actions.Any(a=>!Actions.Contains(a)))|| registration.Panes.Select(p=>p.PaneID).Distinct().Count()!=registration.Panes.Length)throw new ArgumentException("Invalid Context registration."); lock(gate){Prune();if(!leases.ContainsKey(connection)&&(leases.Count>=4096||leases.Values.Count(x=>x.User==user)>=32))throw new InvalidOperationException("Too many Context windows."); @@ -38,14 +46,15 @@ public sealed class ContextWindows(TimeProvider clock) public ContextWindowLease? Remove(string connection) {lock(gate){var prior=leases.GetValueOrDefault(connection);leases.Remove(connection);foreach(var id in pending.Where(x=>x.Value.Target==connection||x.Value.Origin==connection).Select(x=>x.Key).ToArray())pending.Remove(id);return prior;}} public ContextConnectedWindow[] List(int user,int book) { - lock(gate){Prune();return leases.Values.Where(x=>x.User==user&&x.Registration.BookID==book).OrderByDescending(x=>x.Seen) - .Select(x=>new ContextConnectedWindow(x.Registration.WindowID,x.Connection,x.Registration.BookID,x.Registration.Panes,x.Seen)).ToArray();} + lock(gate){Prune();return leases.Values.Where(x=>x.User==user&&(x.Registration.Kind=="main"||x.Registration.BookID==book||x.Registration.BookIDs?.Contains(book)==true)).OrderByDescending(x=>x.Seen) + .Select(x=>new ContextConnectedWindow(x.Registration.WindowID,x.Connection,x.Registration.BookID,x.Registration.Panes,x.Seen,x.Registration.EnvironmentID,x.Registration.Kind)).ToArray();} } public (ContextWindowLease Window,ContextPaneCapability Pane,Guid CommandID)? Route(int user,string origin,ContextInteraction command) { lock(gate){Prune();var source=leases.GetValueOrDefault(origin); if(source?.User!=user||source.Registration.BookID!=command.BookID||command.Version!=1||command.TargetUserID.HasValue||!Actions.Contains(command.Action)||!source.Registration.Panes.Any(p=>p.PaneID==command.OriginPaneID))throw new ArgumentException("Invalid interaction scope."); - var targets=leases.Values.Where(x=>x.User==user&&x.Registration.BookID==command.BookID&&(!command.TargetWindowID.HasValue||x.Registration.WindowID==command.TargetWindowID)&&(string.IsNullOrWhiteSpace(command.TargetSessionID)||x.Connection==command.TargetSessionID)) + var targets=leases.Values.Where(x=>x.User==user&&((command.Action=="workspace.open"&&x.Registration.Kind=="main")||x.Registration.BookID==command.BookID||x.Registration.BookIDs?.Contains(command.BookID)==true)&& + (command.Action!="workspace.open"||(source.Registration.EnvironmentID.HasValue&&source.Registration.EnvironmentID==x.Registration.EnvironmentID&&x.Registration.Kind=="main"))&&(!command.TargetWindowID.HasValue||x.Registration.WindowID==command.TargetWindowID)&&(string.IsNullOrWhiteSpace(command.TargetSessionID)||x.Connection==command.TargetSessionID)) .OrderByDescending(x=>x.Connection==origin).ThenByDescending(x=>x.Seen); foreach(var target in targets){var pane=target.Registration.Panes.FirstOrDefault(p=>p.Available&&p.Actions.Contains(command.Action)&&(string.IsNullOrWhiteSpace(command.TargetPaneID)||p.PaneID==command.TargetPaneID)); if(pane==null)continue;if(pending.Values.Count(x=>x.Origin==origin)>=16)throw new InvalidOperationException("Wait for pending Context commands."); diff --git a/PlotLine/Views/Shared/_Layout.cshtml b/PlotLine/Views/Shared/_Layout.cshtml index 1ceaf6b2..d212b643 100644 --- a/PlotLine/Views/Shared/_Layout.cshtml +++ b/PlotLine/Views/Shared/_Layout.cshtml @@ -23,7 +23,7 @@ var storyIntelligenceProgress = User.Identity?.IsAuthenticated == true && !isMarketingPage ? await StoryIntelligenceGlobalProgress.GetForCurrentUserAsync() : new StoryIntelligenceGlobalProgressViewModel(); - var appNavigation = User.Identity?.IsAuthenticated == true + ApplicationNavigationViewModel appNavigation = User.Identity?.IsAuthenticated == true ? await Navigation.BuildAsync(ViewData.Model, ViewData["ProjectSection"] as string, Context.Request) : new ApplicationNavigationViewModel(); appNavigation.IsAdmin = isAdmin; @@ -149,7 +149,7 @@ } - +b.BookID))" data-pd-project-id="@appNavigation.Project?.ProjectID" data-pd-scene-id="@(ViewContext.RouteData.Values["controller"]?.ToString() == "Scenes" ? ViewContext.RouteData.Values["id"] : null)" data-pd-user-id="@userId" data-desktop-eligible="@(isApplication && appNavigation.Project is not null && appNavigation.Books.Count > 0 ? "true" : "false")" data-desktop-user="@(isApplication ? userId : null)" class="@(User.Identity?.IsAuthenticated == true && !isMarketingPage ? "app-layout" : null)">
@if (User.Identity?.IsAuthenticated == true) { @@ -364,6 +364,8 @@ + + diff --git a/PlotLine/Views/Writing/Context.cshtml b/PlotLine/Views/Writing/Context.cshtml index 0da5a0dc..ddb16cd5 100644 --- a/PlotLine/Views/Writing/Context.cshtml +++ b/PlotLine/Views/Writing/Context.cshtml @@ -30,7 +30,7 @@ - Open scene editor + Open scene editor
@for(var pane = 0; pane < 2; pane++) { @@ -42,7 +42,7 @@ }
-

Focused correction

+

Focused correction

My Context windows

Only your connected windows for this book appear. Commands focus a reference tool; they do not navigate Word.

@@ -56,6 +56,8 @@ - - + + + + } diff --git a/PlotLine/Views/Writing/_ContextCharacterDetail.cshtml b/PlotLine/Views/Writing/_ContextCharacterDetail.cshtml index baabd261..89db8224 100644 --- a/PlotLine/Views/Writing/_ContextCharacterDetail.cshtml +++ b/PlotLine/Views/Writing/_ContextCharacterDetail.cshtml @@ -4,15 +4,15 @@
@foreach(var item in new[]{("Previous",row.Previous),("Now",row.Now),("Next · future record",row.Next)}){ -
@item.Item1@if(item.Item2 is {} place){Source scene} +
@item.Item1@if(item.Item2 is {} place){Source scene} else{@(item.Item1=="Now"?(row.Participation=="Mentioned only"?"Mentioned only · no physical presence implied":row.Participation=="Unknown"?"Location unknown (recorded presence state)":row.Participation=="Off-screen"?"Off-screen · location not recorded":"No recorded location here"):"No recorded location")}
}
Emotional state
@(string.IsNullOrWhiteSpace(row.Emotion)?"Not recorded in this scene":row.Emotion)
Physical condition
@(string.IsNullOrWhiteSpace(row.Condition)?"Not recorded in this scene":row.Condition)
Reference
@(string.IsNullOrWhiteSpace(row.Character.DefaultDescription)?"No character description recorded":row.Character.DefaultDescription)
- @if(row.Knowledge.Any()){

@(row.IsPov?"Verified viewpoint knowledge at this point":"Author reference: this character’s established knowledge; not necessarily viewpoint knowledge")

    @foreach(var fact in row.Knowledge.Take(4)){
  • @fact.KnowledgeStateName: @fact.Description Source
  • }
} + @if(row.Knowledge.Any()){

@(row.IsPov?"Verified viewpoint knowledge at this point":"Author reference: this character’s established knowledge; not necessarily viewpoint knowledge")

    @foreach(var fact in row.Knowledge.Take(4)){
  • @fact.KnowledgeStateName: @fact.Description Source
  • }
} @if(explorer.CanEdit){
@foreach(var field in new[]{("classification","Classification"),("description","Description")}){} @if(row.Appearance!=null){@foreach(var field in new[]{("emotion","Emotional state"),("condition","Physical condition"),("location","Current location")}){}}
}else{

Read-only reference.

} - Open character workspace + Open character workspace
diff --git a/PlotLine/Views/Writing/_ContextNames.cshtml b/PlotLine/Views/Writing/_ContextNames.cshtml index 181c6a67..67408ad7 100644 --- a/PlotLine/Views/Writing/_ContextNames.cshtml +++ b/PlotLine/Views/Writing/_ContextNames.cshtml @@ -11,8 +11,8 @@ @if(panel.CanEdit){}
    @foreach(var alias in entry.Aliases){
  • @alias.Alias (alias / known variant)@if(panel.CanEdit&&!string.Equals(alias.Alias,entry.Character.CharacterName,StringComparison.OrdinalIgnoreCase)){}
  • }
@if(panel.CanEdit){} -Full character editor
} +Full character editor}
Name suggestions and related forms
-

Open full Names workspace +

Open full Names workspace } diff --git a/PlotLine/Views/Writing/_ContextRelationships.cshtml b/PlotLine/Views/Writing/_ContextRelationships.cshtml index fb24e59e..dbdf0f36 100644 --- a/PlotLine/Views/Writing/_ContextRelationships.cshtml +++ b/PlotLine/Views/Writing/_ContextRelationships.cshtml @@ -12,12 +12,12 @@ var rows=(Model.AtPoint?.Relationships??Model.RelationshipMap?.Relationships??[]

@r.RelationshipCategoryName · @(r.IsReciprocal?"Reciprocal connection":"Directional connection: From → To") @if(r.CurrentIntensity.HasValue){· Intensity @r.CurrentIntensity / 10}

@if(!string.IsNullOrWhiteSpace(r.Notes)){

Recorded notes: @r.Notes

}else{

No author notes recorded for this state.

}

First meeting: no structured marker is available. Explicit meeting evidence, if recorded, remains in the notes and developments below; earliest co-occurrence is never treated as a meeting.

-
Latest recorded developments (@r.History.Count)
    @foreach(var item in r.History.OrderBy(h=>h.SceneID.HasValue?(Model.Context.Narrative?.Scenes.ToList().FindIndex(s=>s.SceneID==h.SceneID)??-1):-1).Reverse().Take(3)){
  • @item.Label · @item.StateName @item.Notes @if(item.SceneID.HasValue){Source scene}
  • }
+
Latest recorded developments (@r.History.Count)
    @foreach(var item in r.History.OrderBy(h=>h.SceneID.HasValue?(Model.Context.Narrative?.Scenes.ToList().FindIndex(s=>s.SceneID==h.SceneID)??-1):-1).Reverse().Take(3)){
  • @item.Label · @item.StateName @item.Notes @if(item.SceneID.HasValue){Source scene}
  • }
@if(canEdit){
@if(r.InitialStateEditable){}
} -Open in Relationships Editor +Open in Relationships Editor
} } @if(canEdit){
} -

Open in Relationships Editor +

Open in Relationships Editor diff --git a/PlotLine/Views/Writing/_WritingContextOverview.cshtml b/PlotLine/Views/Writing/_WritingContextOverview.cshtml index 9102e9ac..654571ce 100644 --- a/PlotLine/Views/Writing/_WritingContextOverview.cshtml +++ b/PlotLine/Views/Writing/_WritingContextOverview.cshtml @@ -97,7 +97,7 @@ Story Maps · choose a saved map @if(scene.FloorPlanID.HasValue){Linked floor plan}else{No floor plan mapped} Plot Lines - Characters and relationships + Characters and relationships
@@ -106,12 +106,12 @@

Verified records through this scene in manuscript order. States may include uncertainty or lack of knowledge. Reader knowledge is not independently recorded here.

@if(scene.POVCharacterID is null){

No viewpoint character recorded. No viewpoint knowledge is inferred.

} else if(Model.AtPoint?.ViewpointKnowledge.Any()!=true){

No verified knowledge records for this viewpoint at this point.

} - else{
    @foreach(var fact in Model.AtPoint.ViewpointKnowledge.Take(5)){
  • @fact.KnowledgeStateName: @(fact.Description??fact.AssetName??fact.ThreadTitle??"Recorded knowledge") Source scene
  • }

Open People for other participants’ knowledge records.

} + else{
    @foreach(var fact in Model.AtPoint.ViewpointKnowledge.Take(5)){
  • @fact.KnowledgeStateName: @(fact.Description??fact.AssetName??fact.ThreadTitle??"Recorded knowledge") Source scene
  • }

Open People for other participants’ knowledge records.

}

Relevant unresolved threads

Established through this scene; prioritised by current events, knowledge records and this chapter. Author reference, not proof of viewpoint awareness.

@if(!Model.RelevantThreads.Any()){

No established unresolved threads linked to this scene, its participants or this chapter.

} - else{} + else{}
diff --git a/PlotLine/Views/Writing/_WritingContextPeople.cshtml b/PlotLine/Views/Writing/_WritingContextPeople.cshtml index c45c446f..eabf1a09 100644 --- a/PlotLine/Views/Writing/_WritingContextPeople.cshtml +++ b/PlotLine/Views/Writing/_WritingContextPeople.cshtml @@ -21,5 +21,5 @@

- Open full Characters workspace + Open full Characters workspace diff --git a/PlotLine/wwwroot/css/context-workspace.css b/PlotLine/wwwroot/css/context-workspace.css index ca8338d9..53559592 100644 --- a/PlotLine/wwwroot/css/context-workspace.css +++ b/PlotLine/wwwroot/css/context-workspace.css @@ -48,3 +48,12 @@ body:has([data-context-workspace])>.writing-window-bar { flex:none; } .context-location-rail button{white-space:normal;text-align:start;overflow-wrap:anywhere;padding:.2rem 0;} .context-location-rail strong{font-size:.8rem;} @container(max-width:420px){.context-location-rail{grid-template-columns:minmax(0,1fr);}.context-location-rail>div{display:grid;grid-template-columns:5rem minmax(0,1fr);}.context-location-rail>div>a{grid-column:2;}} +/* Shared correction form geometry, independent of the originating pane width. */ +[data-context-edit-dialog]{width:min(42rem,calc(100vw - 2rem));max-width:calc(100vw - 1rem);max-height:calc(100dvh - 2rem);padding:clamp(1rem,3vw,1.6rem);overflow:auto;box-sizing:border-box;} +[data-context-edit-dialog] [data-context-edit-form]{display:flex;flex-wrap:wrap;gap:1rem;min-width:0;} +[data-context-edit-form]>p,[data-context-edit-form]>div,[data-context-edit-form]>label{flex-basis:100%;width:100%;min-width:0;margin:0;} +[data-context-edit-form]>label{display:flex;flex-direction:column;gap:.35rem;} +[data-context-edit-form] input:not([type=hidden]):not([type=checkbox]),[data-context-edit-form] select,[data-context-edit-form] textarea{display:block;width:100%;max-width:100%;min-width:0;box-sizing:border-box;} +[data-context-edit-form] label:has(input[type=checkbox]){flex-direction:row;align-items:center;} +[data-context-edit-form] textarea{min-height:9rem;resize:vertical;} +[data-context-edit-form] input[type=checkbox]{flex:0 0 auto;} diff --git a/PlotLine/wwwroot/js/context-editing.js b/PlotLine/wwwroot/js/context-editing.js index 34cfa5e8..f871c1a4 100644 --- a/PlotLine/wwwroot/js/context-editing.js +++ b/PlotLine/wwwroot/js/context-editing.js @@ -2,13 +2,13 @@ 'use strict';const root=document.querySelector('[data-context-workspace]');if(!root)return; const dialog=root.querySelector('[data-context-edit-dialog]'),host=dialog.querySelector('[data-context-edit-content]'),status=dialog.querySelector('[data-context-edit-status]');let pane,dirty=false,busy=false,originalFocus,load; function state(deferRefresh=false){pane?.dispatchEvent(new CustomEvent('context-panel-state',{detail:{dirty,busy,deferRefresh}}));root.dispatchEvent(new CustomEvent('context-window-state',{detail:{busy:dialog.open}}));} - function install(html){const doc=new DOMParser().parseFromString(html,'text/html');const form=doc.querySelector('[data-context-edit-form]');if(!form||doc.querySelector('html>head>title')||/head>title')||/{const button=event.target.closest('[data-context-edit],[data-context-relationship-edit]');if(!button||dialog.open)return; pane=button.closest('[data-context-pane]');originalFocus=button;const fragment=button.closest('[data-context-tab-fragment]');const relationship=button.hasAttribute('data-context-relationship-edit');const url=new URL(relationship?'/Writing/Context/EditRelationship':'/Writing/Context/EditCharacter',location.origin);url.searchParams.set('bookId',fragment.dataset.bookId);url.searchParams.set('sceneId',fragment.dataset.sceneId);if(relationship){url.searchParams.set('relationshipId',button.dataset.relationshipId||'0');url.searchParams.set('mode',button.dataset.contextRelationshipEdit);}else{url.searchParams.set('characterId',button.dataset.characterId);url.searchParams.set('field',button.dataset.contextEdit);} - dialog.showModal();dirty=false;busy=true;state();status.textContent='Loading current saved values…';host.replaceChildren();load=new AbortController(); + dialog.querySelector('[data-context-edit-close]').hidden=true;dialog.showModal();dirty=false;busy=true;state();status.textContent='Loading current saved values…';host.replaceChildren();load=new AbortController(); try{const response=await fetch(url,{signal:load.signal,cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok||response.redirected)throw Error('This correction is unavailable. Check sign-in and editing permission.');install(await response.text());status.textContent='';} - catch(error){if(error.name!=='AbortError'){status.textContent=error.message;window.PlotDirector?.toast?.error(error.message);}} + catch(error){if(error.name!=='AbortError'){status.textContent=error.message;dialog.querySelector('[data-context-edit-close]').hidden=false;window.PlotDirector?.toast?.error(error.message);}} finally{busy=false;state();} }); dialog.addEventListener('input',()=>{dirty=true;state();});dialog.addEventListener('change',()=>{dirty=true;state();}); diff --git a/PlotLine/wwwroot/js/context-environment.js b/PlotLine/wwwroot/js/context-environment.js new file mode 100644 index 00000000..c56cf0b7 --- /dev/null +++ b/PlotLine/wwwroot/js/context-environment.js @@ -0,0 +1,2 @@ +// A browser-profile preference, never an authentication credential. It prevents remote-device navigation. +(() => {const user=document.body.dataset.pdUserId;if(!user)return;let id;try{const key='pd.context.environment.'+user;id=localStorage.getItem(key);if(!/^[a-f0-9-]{36}$/i.test(id||'')){id=crypto.randomUUID();localStorage.setItem(key,id);}}catch{}window.PlotDirectorContextEnvironment=id||null;})(); diff --git a/PlotLine/wwwroot/js/context-main-window.js b/PlotLine/wwwroot/js/context-main-window.js new file mode 100644 index 00000000..13ecb14f --- /dev/null +++ b/PlotLine/wwwroot/js/context-main-window.js @@ -0,0 +1,39 @@ +(() => { + 'use strict';const root=document.querySelector('[data-context-workspace]'),environment=window.PlotDirectorContextEnvironment,user=document.body.dataset.pdUserId; + if(!user)return; + const targetName='pd-main-'+user; + if(root){ + const controller=root.contextController,connection=controller?.connection;if(!connection)return;let sending=false;const receipts=new Map(),waiters=new Map(); + connection.on('ContextInteractionResult',r=>{if(!sending)return;receipts.set(r.commandID,r.status);waiters.get(r.commandID)?.(r.status);}); + document.addEventListener('click',async event=>{ + const link=event.target.closest('a[data-context-workspace-target]');if(!link||event.button!==0||event.ctrlKey||event.metaKey||event.shiftKey||event.altKey)return;event.preventDefault();if(sending)return;sending=true; + const fragment=link.closest('[data-context-tab-fragment]'),bookID=Number(fragment?.dataset.bookId||controller.announcement.bookID),tool=link.dataset.contextWorkspaceTarget,entityID=Number(link.dataset.contextEntity)||null,sceneID=Number(fragment?.dataset.sceneId||controller.position.sceneId)||null; + const fallback=()=>{const url=new URL('/Writing/Context/OpenWorkspace',location.origin);url.searchParams.set('bookId',bookID);url.searchParams.set('tool',tool);if(entityID)url.searchParams.set('entityId',entityID);if(sceneID)url.searchParams.set('sceneId',sceneID);const windowRef=window.open(url.href,targetName);if(windowRef){try{windowRef.focus();}catch{}}else{link.href=url.href;link.target=targetName;window.PlotDirector?.toast?.info('Your browser blocked opening the main window. Use this link again to open it.');link.removeAttribute('data-context-workspace-target');}}; + try{ + if(connection.state!=='Connected'){fallback();return;} + await connection.invoke('RegisterContextWindow',{...controller.announcement,environmentID:environment}); + const result=await connection.invoke('SendContextInteraction',{version:1,bookID,originPaneID:link.closest('[data-context-pane]')?.dataset.contextPane||'0',action:'workspace.open',workspace:{tool,entityID},storyPoint:sceneID?{sceneID}:null}); + if(result.status==='no-handler'){if(!environment||await connection.invoke('ClaimContextMainWindow',bookID,environment))fallback();else window.PlotDirector?.toast?.info('Your main window is opening or busy. Check it before retrying.');}else{const status=receipts.get(result.commandID)||await new Promise(resolve=>{waiters.set(result.commandID,resolve);setTimeout(()=>resolve('unavailable'),12000);});waiters.delete(result.commandID);receipts.delete(result.commandID);window.PlotDirector?.toast?.info(status==='focused'?'Opened in your main PlotDirector window. Your browser may require you to switch to it.':status==='busy'?'The main window kept its unsaved work. Save or cancel there and retry.':'The main window did not confirm navigation. Check it before retrying.');} + }catch{window.PlotDirector?.toast?.error('Main-window navigation is unavailable. Check sign-in and retry.');}finally{receipts.clear();setTimeout(()=>sending=false,500);} + });return; + } + if(!environment)return; + const books=(document.body.dataset.pdBookIds||'').split(',').map(Number).filter(n=>n>0);if(!document.body.classList.contains('app-layout')||document.body.classList.contains('writing-embedded'))return; + window.name=targetName;let connection,starting=false,timer,windowID=crypto.randomUUID(),busy=false;let dirty=false; + document.addEventListener('input',e=>{if(e.target.closest('form')&&!e.target.closest('form[method=get]'))dirty=true;}); + async function register(){if(connection?.state==='Connected')try{await connection.invoke('RegisterContextWindow',{version:1,bookID:books[0]||0,bookIDs:books,windowID,environmentID:environment,kind:'main',panes:[{paneID:'0',toolID:'main',actions:['workspace.open'],available:!busy}]});}catch{}} + async function receive(delivery){if(delivery.command.action!=='workspace.open')return;if(busy){void connection.invoke('CompleteContextInteraction',delivery.commandID,'busy');return;}busy=true;let status='unavailable';try{ + const c=delivery.command,t=c.workspace,url=new URL('/Writing/Context/OpenWorkspace',location.origin);url.searchParams.set('bookId',c.bookID);url.searchParams.set('tool',t.tool);url.searchParams.set('resolve','true');if(t.entityID)url.searchParams.set('entityId',t.entityID);if(c.storyPoint?.sceneID)url.searchParams.set('sceneId',c.storyPoint.sceneID); + const response=await fetch(url,{cache:'no-store',signal:AbortSignal.timeout(10000)});if(!response.ok||response.redirected)throw Error();const value=await response.json(),destination=new URL(value.url,location.origin);if(destination.origin!==location.origin)throw Error(); + const navigate=async()=>{status='focused';await connection.invoke('CompleteContextInteraction',delivery.commandID,status);try{window.focus();}catch{}location.assign(destination.href);}; + if(window.PlotDirectorMapWorkspace?.requestLeave){if(!await window.PlotDirectorMapWorkspace.requestLeave(navigate))status='busy';return;} + if(dirty&&!confirm('Leave this workspace with unsaved changes?')){status='busy';return;} + await navigate();return; + }catch{}finally{if(status!=='focused')await connection.invoke('CompleteContextInteraction',delivery.commandID,status).catch(()=>{});busy=false;} + } + function attach(c){if(connection)return;connection=c;connection.on('ContextInteraction',receive);connection.onreconnected(register);void register();timer=setInterval(()=>{if(connection.state==='Disconnected'&&!starting){starting=true;connection.start().then(register).catch(()=>{}).finally(()=>starting=false);}else void register();},15000);} + document.addEventListener('pd-presence-ready',register); + document.addEventListener('pd-presence-connection',e=>attach(e.detail)); + document.addEventListener('DOMContentLoaded',()=>{if(window.PlotDirectorPresenceConnection)attach(window.PlotDirectorPresenceConnection);else if(window.signalR){const c=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();window.PlotDirectorPresenceConnection=c;attach(c);starting=true;c.start().then(register).catch(()=>{}).finally(()=>starting=false);}}); + window.addEventListener('pagehide',()=>clearInterval(timer)); +})(); diff --git a/PlotLine/wwwroot/js/context-windows.js b/PlotLine/wwwroot/js/context-windows.js index d8adf78f..dccd485f 100644 --- a/PlotLine/wwwroot/js/context-windows.js +++ b/PlotLine/wwwroot/js/context-windows.js @@ -11,7 +11,7 @@ if([...target.options].some(option=>option.value===previous))target.value=previous; } async function register(){if(!connection||connection.state!=='Connected'||closed||!controller.announcement.bookID)return;if(registering){again=true;return;}registering=true; - try{const announcement=controller.announcement;render(await connection.invoke('RegisterContextWindow',announcement));lastBook=announcement.bookID;} + try{const announcement={...controller.announcement,environmentID:window.PlotDirectorContextEnvironment};render(await connection.invoke('RegisterContextWindow',announcement));lastBook=announcement.bookID;} catch{message.textContent='Window discovery unavailable. Reconnect or retry My Windows.';} finally{registering=false;if(again){again=false;void register();}} } diff --git a/PlotLine/wwwroot/js/context-workspace.js b/PlotLine/wwwroot/js/context-workspace.js index 79304ccc..4c6b5a98 100644 --- a/PlotLine/wwwroot/js/context-workspace.js +++ b/PlotLine/wwwroot/js/context-workspace.js @@ -139,6 +139,7 @@ if(!force&&JSON.stringify(before)===JSON.stringify(normalized))return; position=normalized;generation++;cancelRequests(); sceneSelect.value=position.sceneId||''; + root.querySelector('[data-context-editor]').dataset.contextEntity=position.sceneId||''; root.querySelector('[data-context-editor]').href=position.sceneId?`/Scenes/Edit/${position.sceneId}`:'/Writer'; 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(); diff --git a/PlotLine/wwwroot/js/native-companion-status.js b/PlotLine/wwwroot/js/native-companion-status.js index 2a87b29f..a365e4f8 100644 --- a/PlotLine/wwwroot/js/native-companion-status.js +++ b/PlotLine/wwwroot/js/native-companion-status.js @@ -66,5 +66,5 @@ }leases.reconnected=reconnect;root.nativePresence=leases;renderDetails(leases);window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases})); }catch{window.dispatchEvent(new CustomEvent('writer-word-state',{detail:{unavailable:true}}));offline('Companion status unavailable');const unavailable=[];unavailable.connectionState='Disconnected';unavailable.reconnected=reconnect;root.nativePresence=unavailable;renderDetails(unavailable);window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:unavailable}));}finally{pending=false;if(refreshAgain){refreshAgain=false;void update();}}} let reconnectHub=()=>{};void update();let timer;const startTimer=()=>{clearInterval(timer);timer=setInterval(()=>{reconnectHub();void update();},15000);};startTimer();window.addEventListener('pageshow',event=>{if(event.persisted){startTimer();reconnectHub();void update(true);}});document.addEventListener('visibilitychange',()=>{if(!document.hidden)void update();});window.addEventListener('pagehide',()=>clearInterval(timer));window.addEventListener('plotdirector:refresh-word-status',event=>void update(!!event.detail?.reconnected)); - if(window.signalR&&!document.querySelector('[data-context-workspace]')){let refresh;const connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();connection.on('NativePresenceChanged',hint=>{window.dispatchEvent(new CustomEvent('plotdirector:native-presence-changed',{detail:hint}));clearTimeout(refresh);refresh=setTimeout(()=>void update(),250);});connection.onreconnected(()=>void update(true));let starting=false;reconnectHub=()=>{if(starting||connection.state&&connection.state!=='Disconnected')return;starting=true;void connection.start().then(()=>void update(true)).catch(()=>{}).finally(()=>starting=false);};reconnectHub();window.addEventListener('pagehide',()=>{clearTimeout(refresh);void connection.stop();});} + if(window.signalR&&!document.querySelector('[data-context-workspace]')){let refresh;const connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();window.PlotDirectorPresenceConnection=connection;document.dispatchEvent(new CustomEvent('pd-presence-connection',{detail:connection}));connection.on('NativePresenceChanged',hint=>{window.dispatchEvent(new CustomEvent('plotdirector:native-presence-changed',{detail:hint}));clearTimeout(refresh);refresh=setTimeout(()=>void update(),250);});connection.onreconnected(()=>void update(true));let starting=false;reconnectHub=()=>{if(starting||connection.state&&connection.state!=='Disconnected')return;starting=true;void connection.start().then(()=>{void update(true);document.dispatchEvent(new Event('pd-presence-ready'));}).catch(()=>{}).finally(()=>starting=false);};reconnectHub();window.addEventListener('pagehide',()=>{clearTimeout(refresh);void connection.stop();});} })();