diff --git a/Docs/Writer/Spatial-Context.md b/Docs/Writer/Spatial-Context.md index 0f95e1d3..6bac9f6d 100644 --- a/Docs/Writer/Spatial-Context.md +++ b/Docs/Writer/Spatial-Context.md @@ -39,3 +39,31 @@ Canonical floor-plan blocks require a location ID; there is no separate unassoci Immediate child exploration is bounded to forty entries; open Locations for a larger directory. Advanced boundaries, snapping, smoothing, walls, furniture and architectural construction remain in the main World editors. No routing, geocoding, name inference, AI requests or automatic story-data mutations are introduced. Physical Windows/Word verification and installed PWA results must be recorded separately from synthetic focus tests in the delivery report. + +## Main application navigation from Context + +Context is a persistent companion workspace. Main application pages must open in +its existing main PlotDirector window, leaving every Context pane, draft, selection, +viewport and Hold/Follow state intact. Context-local buttons (including Show on map, +Show floor plan, scene navigation and inline editing) remain local. + +`context-main-window.js` is the shared delegation point. Its document-level handler +covers same-origin page anchors inside the Context root, including dynamically +loaded partials, dialogs and expanded sections. Existing +`data-context-workspace-target` commands retain their entity/story-point resolver. +Other page links retain their exact path, query and fragment through the optional +`ContextWorkspaceTarget.Url` contract (`tool: page`). `ContextWorkspaceNavigation` +allows only known read-only main-page routes; destination controllers retain normal +authorisation. Add a future page route to that central allowlist rather than adding +feature-specific window discovery, `window.open` calls or click handlers. + +Both forms use the existing `workspace.open` interaction, Context window registry, +browser/PWA environment identity, native presence connection, main-window activation +and named-window fallback. No extra registry or SignalR connection is introduced. +Rapid requests coalesce to the latest queued destination while a main window opens. +Blocked popups remain intercepted and report through the shared toast; browser/OS +focus policies may require the author to switch windows manually. + +Do not change main-page Back buttons to return to Context. Never navigate the +Context document to a main page. Fragment anchors, `/Writing/Context` routes and +local button interactions are deliberately excluded from this delegation. diff --git a/PlotLine.Tests/Browser/context-external-navigation-development.cjs b/PlotLine.Tests/Browser/context-external-navigation-development.cjs new file mode 100644 index 00000000..01b2c6b3 --- /dev/null +++ b/PlotLine.Tests/Browser/context-external-navigation-development.cjs @@ -0,0 +1,25 @@ +// Opt-in authenticated Development acceptance; disposable author scope only. +const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict'); +const file=process.argv[2],pwa=process.argv.includes('--pwa'),base='https://dev.plotdirector.com',out='/tmp/pd-context-navigation-evidence'; +assert(file?.startsWith('/tmp/pd-dev-browser-'));const i=JSON.parse(fs.readFileSync(file)),f=i.SpatialFixture;assert(i.Database==='PlotDirector_Development'&&i.Email.startsWith('pwa-browser-')&&f&&i.NavigationCharacterID);fs.mkdirSync(out,{recursive:true}); +(async()=>{let browser,c,cdp,profile,step='login';const errors=[],checks=[];try{ + if(pwa){profile=fs.mkdtempSync('/tmp/pd-context-nav-pwa-');c=await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1600,height:1050}});cdp=await c.browser().newBrowserCDPSession();}else{browser=await chromium.launch();c=await browser.newContext({viewport:{width:1600,height:1050}});} + c.on('page',p=>p.on('pageerror',e=>errors.push(e.message)));let main=c.pages()[0]||await c.newPage();await main.goto(base+'/Account/Login');await main.locator('#Email').fill(i.Email);await main.locator('#Password').fill(i.Password);await Promise.all([main.waitForURL('**/Projects'),main.locator('form button[type=submit]').click()]);await main.goto(base+'/Projects/Details/'+i.ProjectID); + const url=base+`/Writing/Context?projectId=${i.ProjectID}&bookId=${i.BookID}&sceneId=${f.scenes[1]}&pinned=true`;let p; + if(pwa){await cdp.send('PWA.install',{manifestId:base+'/Projects',installUrlOrBundleUrl:base+'/Projects'});await cdp.send('PWA.changeAppUserSettings',{manifestId:base+'/Projects',displayMode:'standalone'});const opened=c.waitForEvent('page');await cdp.send('PWA.launch',{manifestId:base+'/Projects',url});p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else{p=await c.newPage();await p.goto(url);} + const tabs=n=>`[data-context-pane="${n}"] [data-context-tab]`;await p.selectOption(tabs(0),'locations');await p.getByRole('heading',{name:'Bedroom',exact:true}).waitFor();await p.selectOption('[data-context-layout]','columns');await p.selectOption(tabs(1),'maps');await p.waitForFunction(()=>document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.document.features.length>0);await p.evaluate(()=>document.querySelector('iframe').contentWindow.PlotDirectorMapWorkspace.setView({x:10,y:20,w:900,h:650})); + const snap=()=>p.evaluate(()=>({url:location.href,layout:document.querySelector('[data-context-layout]').value,tabs:[...document.querySelectorAll('[data-context-tab]')].map(n=>n.value),scene:document.querySelector('[data-context-scene]').value,position:document.querySelector('[data-context-workspace]').contextController.position,hold:document.querySelector('[data-shared-focus-hold]').getAttribute('aria-pressed'),selection:document.querySelector('[data-spatial-details] h2')?.textContent,view:document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.view,scroll:[...document.querySelectorAll('[data-context-pane-body], [data-spatial-details]')].map(n=>[n.scrollLeft,n.scrollTop])})); + const ready=async()=>{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)),i.BookID);await p.waitForTimeout(600);}; + async function follow(link,expected){step=expected;await ready();await link.scrollIntoViewIfNeeded();const before=await snap(),count=c.pages().length;await link.click();await main.waitForURL(u=>u.pathname+u.search===expected);assert.equal(c.pages().length,count);assert.deepEqual(await snap(),before);checks.push(expected);} + step='existing spatial main reuse';await follow(p.getByRole('link',{name:'Location Details',exact:true}),`/Locations/Details/${f.locations[1]}`);await follow(p.getByRole('link',{name:'Edit Location',exact:true}),`/Locations/Edit/${f.locations[1]}`);const mapped=new URL(await p.getByRole('link',{name:'Open in Maps',exact:true}).getAttribute('href'),base);assert(mapped.searchParams.get('featureId'));await follow(p.getByRole('link',{name:'Open in Maps',exact:true}),mapped.pathname+mapped.search);await p.screenshot({path:out+`/${pwa?'pwa':'browser'}-locations-maps-preserved.png`}); + step='floor exact block and split preservation';await p.selectOption(tabs(1),'floorplans');await p.locator('[data-block]').first().waitFor();const floorUrl=new URL(await p.getByRole('link',{name:'Open in Floor Plans',exact:true}).getAttribute('href'),base);assert(floorUrl.searchParams.get('selectedBlockId'));await follow(p.getByRole('link',{name:'Open in Floor Plans',exact:true}),floorUrl.pathname+floorUrl.search);await p.screenshot({path:out+`/${pwa?'pwa':'browser'}-locations-floorplans-preserved.png`}); + step='Characters and expanded details';await p.selectOption(tabs(0),'characters');const row=p.locator(`[data-context-character="${i.NavigationCharacterID}"]`);await row.waitFor();if(!await row.evaluate(n=>n.open))await row.locator('summary').click();await follow(p.locator(`a[data-context-workspace-target="characters"][data-context-entity="${i.NavigationCharacterID}"]`).last(),`/Characters/Details/${i.NavigationCharacterID}`); + // Edit Character is supplied by the shared Name Details partial; dynamic-anchor + // coverage uses exactly its unmarked href contract without changing author data. + await p.evaluate(id=>{const a=document.createElement('a');a.textContent='Edit fixture Character';a.href='/Characters/Edit/'+id;document.querySelector('[data-character-explorer]').append(a);},i.NavigationCharacterID);await follow(p.getByRole('link',{name:'Edit fixture Character',exact:true}),`/Characters/Edit/${i.NavigationCharacterID}`); + step='Overview main links';await p.selectOption(tabs(0),'overview');const calendar=p.locator('a[href^="/StoryCalendar"]').first();await calendar.waitFor();const cal=new URL(await calendar.getAttribute('href'),base);await follow(calendar,cal.pathname+cal.search);const storyMaps=p.locator('a[href^="/Maps"]').first(),storyUrl=new URL(await storyMaps.getAttribute('href'),base);await follow(storyMaps,storyUrl.pathname+storyUrl.search); + step='multiple Context and following';const second=await c.newPage();await second.goto(url.replace('&pinned=true',''));await second.selectOption(tabs(0),'locations');await second.getByRole('heading',{name:'Bedroom',exact:true}).waitFor();await ready();const original=await snap();await second.getByRole('link',{name:'Location Details',exact:true}).click();await main.waitForURL('**/Locations/Details/'+f.locations[1]);assert.deepEqual(await snap(),original);assert.equal(await second.locator('[data-context-scene]').inputValue(),String(f.scenes[1]));checks.push('independent held/following Context windows'); + step='closed main location fallback and rapid reuse';await p.selectOption(tabs(0),'locations');await p.getByRole('heading',{name:'Bedroom',exact:true}).waitFor();await main.close();await p.waitForTimeout(700);const pop=p.waitForEvent('popup');await p.getByRole('link',{name:'Location Details',exact:true}).click();main=await pop;await main.waitForURL('**/Locations/Details/'+f.locations[1]);await follow(p.getByRole('link',{name:'Open in Floor Plans',exact:true}),floorUrl.pathname+floorUrl.search);checks.push('closed-main fallback reused'); + step='Context internal editing';await p.getByRole('button',{name:'Edit description',exact:true}).click();await p.locator('[data-spatial-operation] textarea').waitFor();await follow(p.getByRole('link',{name:'Location Details',exact:true}),`/Locations/Details/${f.locations[1]}`);assert(await p.locator('[data-spatial-operation] textarea').isVisible());await p.getByRole('button',{name:'Cancel',exact:true}).click(); + assert.deepEqual(errors,[]);fs.writeFileSync(out+`/${pwa?'pwa':'browser'}-results.json`,JSON.stringify({passed:true,authenticated:true,installedPwa:pwa,checks,errors,physicalWindowsWord:false},null,2));console.log('PASS authenticated '+(pwa?'installed PWA':'browser')+' external Context navigation: exact routes, existing/closed-main reuse, two held/following windows, split/map viewport retained, inline draft retained.'); + }catch(e){console.error('FAIL '+step,e);process.exitCode=1;}finally{if(cdp)await cdp.send('PWA.uninstall',{manifestId:base+'/Projects'}).catch(()=>{});await c?.close();await browser?.close();if(profile)fs.rmSync(profile,{recursive:true,force:true});}})(); diff --git a/PlotLine.Tests/Browser/context-external-navigation.cjs b/PlotLine.Tests/Browser/context-external-navigation.cjs new file mode 100644 index 00000000..29eafe40 --- /dev/null +++ b/PlotLine.Tests/Browser/context-external-navigation.cjs @@ -0,0 +1,18 @@ +// Actual compiled Context/renderers + existing registry; disposable loopback main-page shells. +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'); +const base='http://127.0.0.1:5238'; +(async()=>{const browser=await chromium.launch();let step='setup';try{const c=await browser.newContext({viewport:{width:1500,height:1000}});const errors=[];c.on('page',p=>p.on('pageerror',e=>errors.push(e.message))); +for(const route of ['**/native-companion/status','**/native-companion/connection-state'])await c.route(route,r=>r.fulfill({json:[]}));await c.route('**/Writing/Context/Position?*',r=>r.fulfill({json:{connected:false}}));await c.route('**/Writing/Context/Tabs/*',r=>r.fulfill({body:'
Existing tool
',contentType:'text/html'})); +for(const route of ['/Locations/**','/Characters/Details/**','/Characters/Edit/**','/FloorPlans/Edit/**','/StoryCalendar*','/PlotThreads/Edit/**','/RelationshipMap*'])await c.route(base+route,async r=>{if(r.request().isNavigationRequest())await r.fulfill({response:await r.fetch({url:base+'/fixture?layout=full'})});else await r.continue();}); +await c.route(base+'/Maps?*',async r=>{if(r.request().isNavigationRequest())await r.fulfill({response:await r.fetch({url:base+'/fixture?layout=full'})});else await r.continue();}); +let main=await c.newPage();await main.goto(base+'/fixture?layout=full');const p=await c.newPage();await p.goto(base+'/Writing/Context?pinned=true');await p.selectOption('[data-context-pane="0"] [data-context-tab]','locations');await p.getByRole('heading',{name:'Bedroom',exact:true}).waitFor();await p.selectOption('[data-context-layout]','columns');await p.selectOption('[data-context-pane="1"] [data-context-tab]','maps');await p.waitForFunction(()=>document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.document.features.length===2);await p.evaluate(()=>document.querySelector('iframe').contentWindow.PlotDirectorMapWorkspace.setView({x:50,y:60,w:900,h:700})); +const snapshot=()=>p.evaluate(()=>({url:location.href,layout:document.querySelector('[data-context-layout]').value,tabs:[...document.querySelectorAll('[data-context-tab]')].map(n=>n.value),position:document.querySelector('[data-context-workspace]').contextController.position,held:document.querySelector('[data-context-workspace]').contextController.held,heading:document.querySelector('[data-spatial-details] h2')?.textContent,view:document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.view})); +const before=await snapshot(),count=c.pages().length;const ready=async()=>{await p.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected'&&document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',12).then(rows=>rows.some(r=>r.kind==='main')));await p.waitForTimeout(600);}; +async function go(label,expected){console.log("CHECK",label,expected);await ready();await p.getByRole('link',{name:label,exact:true}).click();await main.waitForURL(u=>u.pathname+u.search===expected);assert.equal(c.pages().length,count);assert.deepEqual(await snapshot(),before);} +step='spatial exact URLs in existing main';await go('Location Details','/Locations/Details/103');await go('Edit Location','/Locations/Edit/103');const mapUrl=new URL(await p.getByRole('link',{name:'Open in Maps',exact:true}).getAttribute('href'),base);await go('Open in Maps',mapUrl.pathname+mapUrl.search); +step='dynamic links, modifiers, keyboard and selected blocks';const links=[['Floor editor','/FloorPlans/Edit/9?selectedBlockId=51'],['Edit Character','/Characters/Edit/5'],['Character Details','/Characters/Details/5'],['Calendar','/StoryCalendar?projectId=7&bookId=12'],['Thread','/PlotThreads/Edit/6']];for(const [label,url] of links){await p.evaluate(([text,href])=>{const a=document.createElement('a');a.textContent=text;a.href=href;document.querySelector('[data-context-pane="1"]').append(a);},[label,url]);await go(label,url);} +step='multiple Context windows';const second=await c.newPage();await second.goto(base+'/Writing/Context?pinned=true');await second.selectOption('[data-context-pane="0"] [data-context-tab]','locations');await second.getByRole('heading',{name:'Bedroom',exact:true}).waitFor();await ready();await second.getByRole('link',{name:'Edit Location',exact:true}).click();await main.waitForURL('**/Locations/Edit/103');assert.deepEqual(await snapshot(),before); +step='closed main and rapid requests';await main.close();await p.waitForTimeout(600);await p.evaluate(()=>{const a=document.createElement('a');a.textContent='Fallback main';a.href='/Characters?projectId=7';document.querySelector('[data-spatial-details]').append(a);});const popup=p.waitForEvent('popup');await p.getByRole('link',{name:'Fallback main',exact:true}).click();main=await popup;await main.waitForURL('**/Characters?projectId=7');await p.getByRole('link',{name:'Open in Maps',exact:true}).click();await main.waitForURL(u=>u.pathname+u.search===mapUrl.pathname+mapUrl.search);assert.equal(c.pages().length,count+1);assert.deepEqual(await snapshot(),before); +step='blocked popup remains intercepted';await main.close();await p.waitForTimeout(600);await p.evaluate(()=>{window.open=()=>null;});await p.getByRole('link',{name:'Edit Location',exact:true}).click();await p.getByText('Your browser blocked the main window.',{exact:false}).waitFor();assert.deepEqual(await snapshot(),before); +assert.deepEqual(errors,[]);console.log('PASS Context external navigation: exact spatial routes, dynamically inserted main-page links, existing registry/main reuse, closed-main fallback, rapid requests, two Context windows, pinned split/map viewport preserved, popup blocking never escapes Context.'); +}catch(e){console.error('FAIL '+step,e);process.exitCode=1;}finally{await browser.close();}})(); diff --git a/PlotLine.Tests/ContextWindowsTests.cs b/PlotLine.Tests/ContextWindowsTests.cs index 15fdaf7c..3bb8eaea 100644 --- a/PlotLine.Tests/ContextWindowsTests.cs +++ b/PlotLine.Tests/ContextWindowsTests.cs @@ -30,6 +30,12 @@ internal static class ContextWindowsTests 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");} + var mainLaunch=new ContextWindows(clock);var mainEnvironment=Guid.NewGuid(); + mainLaunch.Register(7,"origin",Registration(Guid.NewGuid(),12,"workspace.open") with{EnvironmentID=mainEnvironment}); + Check(mainLaunch.TryLaunch(7,"origin",12,mainEnvironment),"main launch reservation acquired"); + mainLaunch.Register(7,"main",new(1,12,Guid.NewGuid(),[new("0","main",["workspace.open"])],mainEnvironment,"main")); + mainLaunch.Remove("main"); + Check(mainLaunch.TryLaunch(7,"origin",12,mainEnvironment),"a registered main can close and reopen without waiting for its old launch reservation"); var launchStore=new ContextWindows(clock);var browser=Guid.NewGuid(); launchStore.Register(7,"launcher",new(1,12,Guid.NewGuid(),[],browser)); launchStore.Register(8,"foreign-user",Registration(Guid.NewGuid(),12,"scene.focus") with{EnvironmentID=browser}); diff --git a/PlotLine.Tests/ContextWorkspaceNavigationTests.cs b/PlotLine.Tests/ContextWorkspaceNavigationTests.cs new file mode 100644 index 00000000..499c5160 --- /dev/null +++ b/PlotLine.Tests/ContextWorkspaceNavigationTests.cs @@ -0,0 +1,16 @@ +using PlotLine.Services.Context; +internal static class ContextWorkspaceNavigationTests +{ + public static void Run() + { + foreach(var url in new[]{"/Locations/Details/15", "/Locations/Edit/15", "/Characters/Edit/8", "/Maps?projectId=7&id=12&featureId=one", "/FloorPlans/Edit/5?selectedBlockId=44", "/StoryCalendar?bookId=12", "/PlotThreads/Edit/8", "/RelationshipMap?sceneId=20"}) + if(!ContextWorkspaceNavigation.IsAllowed(url))throw new Exception("Main page rejected: "+url); + foreach(var url in new[]{"https://example.com/Maps", "//example.com/Maps", "/\\example.com/Maps", "/Maps\r\n", "/Maps/Save", "/FloorPlans/Delete/5", "/Writing/Context", "/Maps/../Account/Logout", "/%4daps"}) + if(ContextWorkspaceNavigation.IsAllowed(url))throw new Exception("Unsafe or non-page route accepted: "+url); + var root=Directory.GetCurrentDirectory(); + while(!File.Exists(Path.Combine(root,"PlotLine.slnx")))root=Directory.GetParent(root)?.FullName??throw new Exception("Repository missing"); + var script=File.ReadAllText(Path.Combine(root,"PlotLine/wwwroot/js/context-main-window.js")); + if(!script.Contains("closest?.('a[href]')")||!script.Contains("root.contains(link)")||!script.Contains("/Writing\\/Context")||script.Contains("link.removeAttribute('data-context-workspace-target')")) + throw new Exception("Context must delegate dynamically inserted main-page links and keep blocked links intercepted."); + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index f3011130..08105b87 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -221,6 +221,7 @@ var tests = new (string Name, Action Test)[] ("Context relationship state and focused editing",()=>ContextRelationshipTests.Run().GetAwaiter().GetResult()), ("Context character narrative projection and focused editing",()=>ContextCharacterTests.Run().GetAwaiter().GetResult()), ("Context My Windows routing and lifecycle",ContextWindowsTests.Run), + ("Context main-page navigation safety and delegated link coverage",ContextWorkspaceNavigationTests.Run), ("Bounded opt-in shared focus diagnostics",SharedFocusDiagnosticsTests.Run), ("Settlement boundaries preserve anchors, routes and backup/import contracts",MapSettlementTests.Run), ("Shared boundary topology preserves map and project contracts",MapTopologyTests.Run), diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 7525c122..0c1830f8 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -401,7 +401,7 @@ internal static class ToolbarBrowserHost if(step=="Preview")model.Preview=new(new(upload,[12,13],0,"Recovered harbour","",Guid.NewGuid(),DateTime.UtcNow.AddMinutes(20)),"fixture-confirmation",snapshot,12,5,context.Request.Query.ContainsKey("full")?0:4,package.Warnings); await RenderFullAsync(context,"BookRecovery",step,step=="Complete"?new BookRecoveryReceipt{ProjectID=7,BooksCreated=2}:model); }); - app.MapGet("/Writing/Context/{spatial}", async (HttpContext context,string spatial)=>{ + app.MapGet("/Writing/Context/{spatial:regex(^(Locations|Maps|FloorPlans)$)}", async (HttpContext context,string spatial)=>{ if(!new[]{"Locations","Maps","FloorPlans"}.Contains(spatial)){context.Response.StatusCode=404;return;} var scene=int.TryParse(context.Request.Query["sceneId"],out var n)?n:22; await RenderFullAsync(context,"Writing","_ContextSpatial",new PlotLine.Services.Context.SpatialFragment(spatial.ToLowerInvariant(),SpatialContextBrowserFixture.Scope(scene))); diff --git a/PlotLine/Controllers/ContextNavigationController.cs b/PlotLine/Controllers/ContextNavigationController.cs index 1293a0b9..2004ac74 100644 --- a/PlotLine/Controllers/ContextNavigationController.cs +++ b/PlotLine/Controllers/ContextNavigationController.cs @@ -7,12 +7,13 @@ namespace PlotLine.Controllers; 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) + public async Task OpenWorkspace(int bookId,string tool,int? entityId,[FromServices] IBookRepository books,[FromServices] ICharacterRepository characters,bool resolve=false,int? sceneId=null,string? destination=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=="page"&&PlotLine.Services.Context.ContextWorkspaceNavigation.IsAllowed(destination))url=destination; 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"){ diff --git a/PlotLine/Hubs/NativeCompanionPresenceHub.cs b/PlotLine/Hubs/NativeCompanionPresenceHub.cs index b71aa895..96c6b4f0 100644 --- a/PlotLine/Hubs/NativeCompanionPresenceHub.cs +++ b/PlotLine/Hubs/NativeCompanionPresenceHub.cs @@ -65,6 +65,7 @@ public sealed class NativeCompanionPresenceHub(ContextWindows windows,IWordCompa return target.Tool switch{ "characters"=>!target.EntityID.HasValue||(await characters.GetCharacterAsync(target.EntityID.Value))?.ProjectID==project, "names"=>!target.EntityID.HasValue, + "page"=>ContextWorkspaceNavigation.IsAllowed(target.Url), "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}; } diff --git a/PlotLine/Services/Context/ContextWindows.cs b/PlotLine/Services/Context/ContextWindows.cs index ed4b11d2..f34dd138 100644 --- a/PlotLine/Services/Context/ContextWindows.cs +++ b/PlotLine/Services/Context/ContextWindows.cs @@ -7,7 +7,7 @@ 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,ContextWorkspaceTarget? Workspace=null); -public sealed record ContextWorkspaceTarget(string Tool,int? EntityID=null); +public sealed record ContextWorkspaceTarget(string Tool,int? EntityID=null,string? Url=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); @@ -55,7 +55,8 @@ public sealed class ContextWindows(TimeProvider clock) 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."); - leases[connection]=new(user,connection,registration,clock.GetUtcNow());} + leases[connection]=new(user,connection,registration,clock.GetUtcNow()); + if(registration.Kind=="main"&®istration.EnvironmentID is Guid environment)launches.Remove((user,environment));} } 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) diff --git a/PlotLine/Services/Context/ContextWorkspaceNavigation.cs b/PlotLine/Services/Context/ContextWorkspaceNavigation.cs new file mode 100644 index 00000000..3158425e --- /dev/null +++ b/PlotLine/Services/Context/ContextWorkspaceNavigation.cs @@ -0,0 +1,18 @@ +using System.Text.RegularExpressions; +namespace PlotLine.Services.Context; + +// Only read-only main-page destinations are delegated. Destination controllers retain +// their normal entity/project authorisation. Never accept a general redirect URL. +public static partial class ContextWorkspaceNavigation +{ + public static bool IsAllowed(string? url) + { + if (string.IsNullOrWhiteSpace(url) || url.Length > 4096 || !url.StartsWith('/') || + url.StartsWith("//") || url.Any(c => char.IsControl(c) || c == '\\')) return false; + var path = url.Split('?', '#')[0]; + return MainPage().IsMatch(path); + } + + [GeneratedRegex(@"^/(?:Characters(?:/(?:Details|Edit)/[1-9][0-9]*)?|Locations(?:/(?:Details|Edit)/[1-9][0-9]*)?|Maps|FloorPlans(?:/Edit/[1-9][0-9]*)?|Scenes/Edit/[1-9][0-9]*|Names|RelationshipMap|StoryCalendar|PlotLineWorkspace|PlotThreads/Edit/[1-9][0-9]*|Writer)/?$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex MainPage(); +} diff --git a/PlotLine/wwwroot/js/context-main-window.js b/PlotLine/wwwroot/js/context-main-window.js index 87dfdd91..9c512edc 100644 --- a/PlotLine/wwwroot/js/context-main-window.js +++ b/PlotLine/wwwroot/js/context-main-window.js @@ -3,19 +3,61 @@ 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=link.dataset.contextNarrative==='author'?null:Number(link.dataset.contextOpenScene||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');}}; + const controller=root.contextController,connection=controller?.connection; + if(!controller)return; + let sending=false,queued=null;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);}); + function destination(link){ + if(link.hasAttribute('download'))return null; + const url=new URL(link.href,location.origin); + // Fragment links and Context routes remain local. Delegation also covers links + // inserted by later partial refreshes, without feature-specific click handlers. + if(url.origin!==location.origin||!/^https?:$/.test(url.protocol)|| + (url.pathname===location.pathname&&url.search===location.search&&url.hash)|| + /^\/Writing\/Context(?:\/|$)/i.test(url.pathname))return null; + return url.pathname+url.search+url.hash; + } + async function navigate(link){ + if(sending){queued=link;return;}sending=true; + const fragment=link.closest('[data-context-tab-fragment]'),bookID=Number(fragment?.dataset.bookId||controller.announcement.bookID), + legacy=link.dataset.contextWorkspaceTarget,tool=legacy||'page',entityID=Number(link.dataset.contextEntity)||null, + sceneID=link.dataset.contextNarrative==='author'?null:Number(link.dataset.contextOpenScene||fragment?.dataset.sceneId||controller.position.sceneId)||null, + page=legacy?null:destination(link); + const requestUrl=(resolve=false)=>{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);if(page)url.searchParams.set('destination',page);if(resolve)url.searchParams.set('resolve','true');return url;}; + const fallback=()=>{const url=requestUrl();const ref=window.open(url.href,targetName);if(ref){try{ref.focus();}catch{}}else{ + // Keep the Context link intercepted. A subsequent trusted click can retry the + // same named window without ever falling through to Context navigation. + window.PlotDirector?.toast?.info('Your browser blocked the main window. Allow pop-ups for PlotDirector and retry this link.'); + }}; try{ - if(connection.state!=='Connected'){fallback();return;} + 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; + const command={version:1,bookID,originPaneID:link.closest('[data-context-pane]')?.dataset.contextPane||'0',action:'workspace.open',workspace:{tool,entityID,url:page},storyPoint:sceneID?{sceneID}:null}; + let result=await connection.invoke('SendContextInteraction',command); + if(result.status==='no-handler'){ + if(!environment||await connection.invoke('ClaimContextMainWindow',bookID,environment)){fallback();return;} + // Another Context may have just opened the single main window. Wait for its + // existing registration rather than dropping a rapid request or opening one more. + for(let attempt=0;attempt<20&&result.status==='no-handler';attempt++){ + await new Promise(resolve=>setTimeout(resolve,250));result=await connection.invoke('SendContextInteraction',command); + } + } + if(result.status==='no-handler')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;const next=queued;queued=null;if(next?.isConnected)void navigate(next);},500);} + } + function click(event){ + const link=event.target.closest?.('a[href]');if(!link||!root.contains(link)||!destination(link)||event.button>1)return; + event.preventDefault();void navigate(link); + } + document.addEventListener('click',click); + document.addEventListener('auxclick',click); + 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; @@ -23,7 +65,7 @@ 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 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(t.url)url.searchParams.set('destination',t.url);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;}