diff --git a/Docs/Navigation/SceneEditFocusFollowing.md b/Docs/Navigation/SceneEditFocusFollowing.md new file mode 100644 index 00000000..89dcf999 --- /dev/null +++ b/Docs/Navigation/SceneEditFocusFollowing.md @@ -0,0 +1,23 @@ +# Scene Edit focus following + +## Cause + +`NarrativeNavigationFilter` already commits explicit successful Scene Edit opens to the authoritative narrative focus, but the presentation adapter registry omitted Scene Edit. Header/ribbon changes therefore persisted correctly while leaving the editing document and all its targets unchanged. + +## Correction + +The Scene Edit view identifies its stable SceneID and authorised project/book scope. The shared workspace adapter subscribes to the existing authoritative focus event and navigates the whole document to `/Scenes/Edit/{SceneID}?retainNarrativeFocus=true`. It also aligns initial stale documents and implements Go to Focus. A matching SceneID is a no-op. The existing controller loads every panel again; no partial scene data are substituted. The retain flag prevents the destination GET from writing focus back or changing history again. + +Chapter-only focus opens `/Chapters/Details/{ChapterID}?retainNarrativeFocus=true`, the existing chapter-view route. It never invents a SceneID. Chapter Edit retains its specialised independent editing contract. + +Scene Inspector's existing overlay `data-dirty` and save-button state are reused. A small optional adapter lifecycle hook checks unsaved changes **before** `/NarrativeFocus/Set`. Cancel means no request, no history/version change and no event. Approval temporarily makes the scene editing workspace inert until the request finishes, preventing a new draft while the guarded navigation is pending. Failure unlocks the editor and retains its draft. An active save blocks navigation. Normal document departures also get a beforeunload guard. + +Focus changed in another window is already authoritative: a dirty scene stays open with an explicit mismatch/recovery notice. It does not roll back another window's focus. Go asks before discarding the draft. Independent visualisation adapters and the service/persistence contracts are unchanged. + +## Qualification + +Automated Chromium and genuinely installed standalone Chromium PWA checks use isolated compiled Razor fixtures with canonical scenes 31, 101 and 32 across two chapters. No real author's scene is edited. They cover whole-document identity and six panel reloads; Previous/Next across chapters; header/history; stale-document recovery; aligned Go; cancel before persistence; failed request draft retention and unlock; external focus with dirty draft and explicit Go recovery; chapter-only navigation and internal installed-app navigation. Screenshots inspect the rendered Scene Edit workspace. + +Existing focus-synchronisation tests cover Review's accepted paragraph identity/offset, chapter following, stale responses and dirty editing guards. Scene workspace and narrative-focus regressions cover the existing editor, local Scene Explorers, objectives and related isolation. Build and executable harness results are recorded in the completion report. + +Qualified: solution build (0 warnings/errors), executable regression harness (632 PASS), `scene-focus.cjs` normal/installed, `focus-synchronisation.cjs` normal/installed, `scene-workspace.cjs` normal/installed, and `narrative-focus.cjs` normal/installed all passed. Visual screenshots include normal desktop and 950px dark installed-app rendering. Browser checks use isolated application fixtures, not the live author record 9126. No schema, SQL procedures, objective targets, Word verification, or local Scene Explorer behaviour were changed. diff --git a/PlotLine.Tests/Browser/scene-focus.cjs b/PlotLine.Tests/Browser/scene-focus.cjs new file mode 100644 index 00000000..ab02e610 --- /dev/null +++ b/PlotLine.Tests/Browser/scene-focus.cjs @@ -0,0 +1,52 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'); +const base=process.env.PD_NARRATIVE_TEST_URL||'http://127.0.0.1:5238'; +(async()=>{ + const installed=process.argv.includes('--installed'),profile=fs.mkdtempSync('/tmp/pd-narrative-pwa-'); + const c=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1666,height:1050}}):await(await chromium.launch()).newContext({viewport:{width:1666,height:1050}}),b=c.browser(); + try{ + await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:null,defaultPauseOnEdit:true}})); + await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false,state:'Disconnected',wordConnected:false}})); + await c.route('**/native-companion/status*',r=>r.fulfill({json:{leases:[]}})); + await c.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')})); + await c.route('**/hubs/**',r=>r.abort()); + await c.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()}))); + let p; + if(installed){const tab=c.pages()[0];await tab.goto(base+'/fixture');const d=await b.newBrowserCDPSession(),manifestId=base+'/Projects';await d.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture'});await d.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=c.waitForEvent('page');await d.send('PWA.launch',{manifestId,url:base+'/fixture'});p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else p=await c.newPage(); + + + + await c.addCookies([{name:'fixture-focus-reader',value:'mapped',url:base}]); + await c.addInitScript(()=>{window.__focusEvents=[];window.__positions=[];window.addEventListener('plotdirector:narrative-focus-changed',e=>window.__focusEvents.push({chapterID:e.detail.chapterID,sceneID:e.detail.sceneID,version:e.detail.version}));document.addEventListener('reader:focus-positioned',e=>window.__positions.push(e.detail));}); + const active='.pd-ribbon-panel:not([hidden])',command=async kind=>{const menu=p.locator(active+' .pd-ribbon-focus details[data-compact=true]');if(await menu.count()&&!await menu.evaluate(n=>n.open))await menu.locator('summary').click();await p.locator(active+' [data-global-focus='+kind+']').click();},go=()=>command('go'),state=()=>p.evaluate(()=>window.PlotDirectorNarrativeFocus.state),set=t=>p.evaluate(t=>window.PlotDirectorNarrativeFocus.set(t),t); + const clear=()=>p.evaluate(()=>{window.__positions=[];window.__focusEvents=[];}); + async function positioned(scene){await p.waitForFunction(id=>window.__positions.some(e=>e.sceneID===id),scene);} + async function position(){return p.evaluate(()=>{const r=document.querySelector('.manuscript-reader'),n=r.querySelector(`[data-paragraph-id="${r.dataset.focusParagraph}"]`);return {id:r.dataset.focusParagraph,top:n?.getBoundingClientRect().top,revision:r.dataset.revision,version:r.dataset.version,chapter:r.dataset.chapterId};});} + async function choose(value){await clear();await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-position]').selectOption(value);await positioned(Number(value.split('/')[1]));} + await p.goto(base+'/Scenes/Edit/31');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.sceneID===31); + const assertScene=async id=>{await p.waitForURL(new RegExp('/Scenes/Edit/'+id+'(?:\\?|$)'));await p.waitForFunction(id=>window.PlotDirectorNarrativeFocus?.state.sceneID===id,id);assert.equal(await p.locator('[data-scene-workspace]').getAttribute('data-scene-id'),String(id));assert.equal(await p.locator('[data-focus-scene]').getAttribute('data-focus-scene'),String(id));assert.match(await p.locator('[data-scene-identity]').textContent(),new RegExp('Fixture scene '+id));assert.equal(await p.locator('[data-scene-summary-part]').count(),6);}; + await command('next');await assertScene(101);await command('previous');await assertScene(31); + await command('next');await assertScene(101);await command('next');await assertScene(32); + await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-position]').selectOption('21/31');await assertScene(31); + await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-recent]').selectOption('22/32');await assertScene(32); + await p.goto(base+'/Scenes/Edit/31?retainNarrativeFocus=true');await assertScene(32); + // Retain a deliberately stale view until the explicit recovery action. + await p.goto(base+'/Scenes/Edit/31');await assertScene(31); + const before=(await state()).version;await go();assert.equal((await state()).version,before,'aligned Go does not write focus or reload'); + // Use the actual scene editor dirty contract and a real form input event. + await p.evaluate(()=>{const o=document.querySelector('[data-scene-editor-overlay]');o.hidden=false;const t=document.createElement('textarea');t.value='Unsaved draft';o.append(t);t.dispatchEvent(new Event('input',{bubbles:true}));}); + const version=(await state()).version;p.once('dialog',d=>d.dismiss());assert.equal(await set({chapterID:22,sceneID:32}),false);assert.equal((await state()).version,version);assert.equal((await state()).sceneID,31);assert.match(p.url(),/Scenes\/Edit\/31/);assert.equal(await p.locator('[data-scene-editor-overlay] textarea').last().inputValue(),'Unsaved draft'); + // A failed authoritative request retains draft and unlocks the editor. + p.once('dialog',d=>d.accept());await p.route('**/NarrativeFocus/Set',r=>r.fulfill({status:503,json:{message:'Synthetic focus failure'}}));assert.equal(await set({chapterID:22,sceneID:32}),false);assert.equal((await state()).sceneID,31);assert.equal(await p.locator('[data-scene-workspace]').evaluate(n=>n.inert),false);await p.unroute('**/NarrativeFocus/Set'); + p.once('dialog',d=>d.dismiss());await command('next');assert.equal((await state()).version,version,'ribbon cancellation never persists a focus change'); + // Another window can change authoritative focus; retain this draft and offer explicit recovery. + await p.evaluate(async()=>{const f=window.PlotDirectorNarrativeFocus.state,r=document.querySelector('[data-narrative-focus]');await fetch('/NarrativeFocus/Set',{method:'POST',body:new URLSearchParams({projectId:f.projectID,bookId:f.bookID,version:f.version,chapterId:22,sceneId:32,__RequestVerificationToken:r.querySelector('[name=__RequestVerificationToken]').value})});window.dispatchEvent(new Event('focus'));}); + await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32);assert.match(p.url(),/Scenes\/Edit\/31/);assert.match(await p.locator('[data-focus-workspace-status]').textContent(),/unsaved scene edits are retained/); + p.once('dialog',d=>d.accept());await go();await assertScene(32); + // Chapter-only focus navigates to Chapter Details without inventing a scene. + await set({chapterID:23});await p.waitForURL(/Chapters\/Details\/23/);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.chapterID===23);assert.equal((await state()).sceneID,null); + await p.goto(base+'/Scenes/Edit/101');await assertScene(101);await p.screenshot({path:'/tmp/pd-scene-focus-'+(installed?'pwa':'browser')+'.png'}); + await p.setViewportSize({width:950,height:1050});await p.evaluate(()=>window.PlotDirectorApplyApplicationTheme('modern-dark'));await p.screenshot({path:'/tmp/pd-scene-focus-'+(installed?'pwa':'browser')+'-narrow-dark.png'}); + if(installed){assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));assert.equal(c.pages().length,2,'all document navigation stays inside installed application');} + console.log('PASS '+(installed?'installed PWA':'Chromium')+' Scene Edit: whole-document stable-ID follow, chapter boundaries, header/history, stale recovery, aligned no-op, cancel before POST, draft retained on failure, chapter-only fallback and internal navigation.'); + }finally{await c.close();await b?.close();fs.rmSync(profile,{recursive:true,force:true});} +})().catch(e=>{console.error(e.stack);process.exitCode=1;}); diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 16ea8bea..5cc5a334 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -247,6 +247,15 @@ internal static class ToolbarBrowserHost app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); + app.MapGet("/Scenes/Edit/{id:int}", async (HttpContext context, int id) => { + var model=SceneWorkspaceFixture(); + 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") + await context.RequestServices.GetRequiredService().Open(context.RequestServices.GetRequiredService().UserId!.Value,null,id); + await RenderFullAsync(context,"Scenes","Edit",model); + }).WithOrder(-1); app.MapGet("/Projects", () => Results.Redirect("/fixture")); app.MapGet("/map-story-fixture", () => { var projection = MapStoryComposer.Compose(MapStoryTests.Fixture(), MapStoryTests.Plots(), 1); @@ -382,6 +391,8 @@ internal static class ToolbarBrowserHost model.Project = new Project { ProjectID = 7, ProjectName = "The Glass Harbour", AccessRole = context.Request.Query["owner"] == "false" ? "Editor" : "Owner" }; model.Book = new Book { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore", BookNumber = 1 }; model.Books = [model.Book, new Book { BookID = 13, ProjectID = 7, BookTitle = "The Return", BookNumber = 2 }]; + if(context.Request.Query["page"]=="scene-edit") + await context.RequestServices.GetRequiredService().Open(context.RequestServices.GetRequiredService().UserId!.Value,null,SceneWorkspaceFixture().SceneID); model.NarrativeFocus=await context.RequestServices.GetRequiredService().Read(context.RequestServices.GetRequiredService().UserId!.Value,7,12); } var fullLayout = context.Request.Query["layout"] == "full"; diff --git a/PlotLine/Views/Scenes/Edit.cshtml b/PlotLine/Views/Scenes/Edit.cshtml index 384fd3bd..9739f107 100644 --- a/PlotLine/Views/Scenes/Edit.cshtml +++ b/PlotLine/Views/Scenes/Edit.cshtml @@ -5,6 +5,7 @@ ViewData["ShellClass"] = "plotline-shell-wide"; } +
+ @section Scripts { diff --git a/PlotLine/wwwroot/js/narrative-focus-workspaces.js b/PlotLine/wwwroot/js/narrative-focus-workspaces.js index 3ee69518..ecda1f8e 100644 --- a/PlotLine/wwwroot/js/narrative-focus-workspaces.js +++ b/PlotLine/wwwroot/js/narrative-focus-workspaces.js @@ -5,6 +5,41 @@ const controller=shell.dataset.workspaceController,action=shell.dataset.workspaceAction; function offer(message,label,perform){let output=document.querySelector('[data-focus-workspace-status]');if(!output){output=document.createElement('p');output.dataset.focusWorkspaceStatus='';output.setAttribute('role','status');shell.after(output);}output.replaceChildren(document.createTextNode(message+' '));if(perform){const button=document.createElement('button');button.type='button';button.className='btn btn-sm btn-outline-secondary';button.textContent=label;button.addEventListener('click',perform);output.append(button);}} const sceneURL=focus=>{const url=new URL('/Timeline/Index',location.origin);url.search=new URLSearchParams({projectId:focus.projectID,bookId:focus.bookID,selectedSceneId:focus.sceneID,retainNarrativeFocus:true});return url;}; + const scenePage=document.querySelector('[data-focus-scene]'); + if(scenePage&&Number(scenePage.dataset.focusScene)>0){ + const scene=Number(scenePage.dataset.focusScene),editor=scenePage.querySelector('[data-scene-workspace]'); + let approved=false,leaving=false,priorInert=false,locked=false; + const dirty=()=>!!scenePage.querySelector('[data-scene-editor-overlay][data-dirty=true]'); + const saving=()=>!!scenePage.querySelector('[data-scene-editor-save]:disabled'); + const scope=f=>f?.projectID===Number(scenePage.dataset.project)&&f.bookID===Number(scenePage.dataset.book)&&!!f.chapterID; + function permit(){ + if(saving()){offer('Wait for the scene editor to finish saving before navigating.');return false;} + return !dirty()||window.confirm('Discard unsaved scene edits and navigate to Current Focus?'); + } + function align(focus,explicit=false){ + if(!scope(focus)){offer('Current Focus belongs to another book. This scene’s editing target is unchanged.');return;} + if(focus.sceneID===scene)return; + if(!approved&&(dirty()||saving())&&(!explicit||!permit())){ + offer('Current Focus changed elsewhere. Your unsaved scene edits are retained.','Go to Focus',()=>align(window.PlotDirectorNarrativeFocus.state,true));return; + } + leaving=true; + const path=focus.sceneID?'/Scenes/Edit/'+focus.sceneID:'/Chapters/Details/'+focus.chapterID; + location.assign(path+'?retainNarrativeFocus=true'); + } + registry.register({canGo:scope,unavailable:'Choose a chapter or scene in this scene’s book',go:f=>align(f,true), + beforeChange:target=>{ + if(target.sceneID===scene&&!target.direction)return true; + if(!permit())return false; + approved=true; + // Keep the guarded draft stable until the authoritative request succeeds or fails. + if(editor){priorInert=editor.inert;editor.inert=true;locked=true;} + return true; + },changeFinished:()=>{approved=false;if(locked){editor.inert=priorInert;locked=false;}}}); + window.addEventListener('plotdirector:narrative-focus-changed',e=>align(e.detail)); + window.addEventListener('beforeunload',e=>{if(!leaving&&dirty()){e.preventDefault();e.returnValue='';}}); + window.addEventListener('pageshow',()=>{leaving=false;}); + const initial=window.PlotDirectorNarrativeFocus?.state;if(initial)align(initial); + } const chapterPage=document.querySelector('[data-focus-chapter]'); if(chapterPage){ let submitting=false; diff --git a/PlotLine/wwwroot/js/narrative-focus.js b/PlotLine/wwwroot/js/narrative-focus.js index f20b4788..35f4645c 100644 --- a/PlotLine/wwwroot/js/narrative-focus.js +++ b/PlotLine/wwwroot/js/narrative-focus.js @@ -33,6 +33,8 @@ async function set(target={}){ if(busy||!state.bookID){status.textContent='Choose a focus book first.';return false;} if(target.bookID&&Number(target.bookID)!==state.bookID||target.projectID&&Number(target.projectID)!==state.projectID){status.textContent='Choose this book in the header before setting its focus.';return false;} + const adapter=window.PlotDirectorFocusWorkspace?.adapter; + if(adapter?.beforeChange&&!adapter.beforeChange(target)){render();return false;} const fromPicker=root.querySelector('.pd-focus-picker').contains(document.activeElement); busy=true;++epoch;render();status.textContent='Updating current focus…'; const body=new URLSearchParams({projectId:state.projectID,bookId:state.bookID,version:state.version,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value}); @@ -43,7 +45,7 @@ state=result;publish();status.textContent='Current focus updated. Your workspace and saved targets are retained.'; try{localStorage.setItem(notificationKey(),String(state.version));}catch{} dismiss(fromPicker&&document.activeElement===document.body);return true; - }catch(error){status.textContent=error.message;if(toggle.getAttribute('aria-expanded')!=='true')showWorkspaceMessage(error.message);return false;}finally{busy=false;render();if(refreshQueued){refreshQueued=false;void refresh();}} + }catch(error){status.textContent=error.message;if(toggle.getAttribute('aria-expanded')!=='true')showWorkspaceMessage(error.message);return false;}finally{adapter?.changeFinished?.();busy=false;render();if(refreshQueued){refreshQueued=false;void refresh();}} } const choose=value=>{const p=entries().find(p=>key(p)===value);if(p)void set(p);else render();}; search.addEventListener('input',render);select.addEventListener('change',()=>choose(select.value));recent.addEventListener('change',()=>choose(recent.value));