From e2fd8d455bbc38b084daf6a2fb9fa8053612404a Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Fri, 20 Nov 2026 17:06:59 +0000 Subject: [PATCH] Synchronise chapter and accepted Review focus targets reliably --- .../FocusSynchronisationCorrection.md | 44 ++++++++++ .../Browser/focus-synchronisation.cjs | 50 ++++++++++++ PlotLine.Tests/Browser/narrative-focus.cjs | 2 + PlotLine.Tests/ManuscriptReaderTests.cs | 17 ++++ PlotLine.Tests/ToolbarBrowserHost.cs | 8 +- PlotLine.Tests/WriterReviewFixture.cs | 2 +- PlotLine/Views/Chapters/Details.cshtml | 3 + PlotLine/Views/Writer/Chapter.cshtml | 5 +- PlotLine/wwwroot/css/scene-explorer.css | 3 + PlotLine/wwwroot/js/manuscript-reader.js | 22 ++++- PlotLine/wwwroot/js/maps-story.js | 2 +- PlotLine/wwwroot/js/narrative-focus-review.js | 81 ++++++++++--------- .../wwwroot/js/narrative-focus-workspaces.js | 26 ++++++ PlotLine/wwwroot/js/narrative-focus.js | 8 +- PlotLine/wwwroot/js/scene-explorer.js | 8 +- PlotLine/wwwroot/js/story-point.js | 6 +- PlotLine/wwwroot/js/writer-review.js | 3 +- 17 files changed, 234 insertions(+), 56 deletions(-) create mode 100644 Docs/Navigation/FocusSynchronisationCorrection.md create mode 100644 PlotLine.Tests/Browser/focus-synchronisation.cjs diff --git a/Docs/Navigation/FocusSynchronisationCorrection.md b/Docs/Navigation/FocusSynchronisationCorrection.md new file mode 100644 index 00000000..478918e5 --- /dev/null +++ b/Docs/Navigation/FocusSynchronisationCorrection.md @@ -0,0 +1,44 @@ +# Focus synchronisation correction — audit before behavioural changes + +## Authoritative path + +`NarrativeFocus` and its Dapper stored procedures remain authoritative per user/project/book. `NarrativeFocus_Set` in migration 294 steps via stable SceneID and `NarrativeSceneOrder.BookSceneIndex`, including chapter boundaries; it does not index accepted paragraphs. Header selection, recent selection and ribbon Previous/Next all call the same browser `set`, POST once, publish the returned stable IDs/version once after success, and notify other windows. Read refreshes use an epoch guard and queue behind commits. Explicit document navigation is adopted by `NarrativeNavigationFilter`; presentation-only chapter destinations must retain focus. + +## Findings + +- **Chapter Details:** no adapter or focus-change subscriber was implemented. The adapter file covers Books/Details but not Chapters/Details. Writer/Chapter is a separate workflow with chapter-bound forms; Chapters/Edit is an editing target and must not be retargeted. Details has a bulk POV form, so following must defer when that form is dirty or submitting. Existing chapter navigation is document navigation, not an AJAX chapter renderer. +- **Review:** every initiating control reaches the same `showScene` and selects the same first accepted DOM paragraph carrying the SceneID. There is no scene-to-paragraph index arithmetic to correct. The accepted projection orders paragraphs by occurrence ordinal and exposes a scene only through an active canonical scene association in the accepted chapter. +- Review's positioning is not coordinated with layout. `showScene` scrolls before hiding/updating the notice and before asynchronous note/context replacements finish. `writer-review.js` captures a previous reading anchor when a context request starts, then restores it in a later animation frame even if explicit scene navigation intervened. Initial context loading and older scene requests can therefore move the reader after navigation. A later Go scrolls again after the layout settles. Header dismissal also calls focus without `preventScroll`, which can move the document back to the header. Initial-load, same-chapter, cross-chapter and accepted-update timing are not unified. +- Reproduced before modification in Chromium using the real compiled Review and its accepted SceneID 31 paragraph, delayed context response and expanded fixture geometry: the **same paragraph ID** appeared at viewport Y 612 after focus selection, Y 286 after context completion, and Y 145 after Go. This demonstrates layout/anchor timing, not an off-by-one or a different canonical scene. Fixture geometry is deliberately synthetic; these measurements are not an assertion about a particular author's manuscript. +- **Other enabled no-ops:** Scene Explorer's adapter checks membership but `choose` silently returns when exploration is disabled. Story Point catches failed loads without rejecting its Go operation. Maps can select a scene while its story layer or local mapping/planning filters still hide it. Unsupported adapters disable Go without an explanatory tooltip. Filtered Timeline/Plot Lines already have explicit reveal/inspect feedback and must retain filters. +- **Focus/Help border:** Focus is DOM-last but visually ordered before Help. The generic `:last-child { border:0 }` therefore removes its divider despite Help being visually next. Restore the shared border only when the active panel has a Help group. + +## Workspace contracts + +| Behaviour | Pages | Contract | +| --- | --- | --- | +| Follow focus when safe | Chapter Details, chapter workflow, integrated Review | Stable ChapterID; preserve SceneID, defer dirty/busy editing, Go explicitly resynchronises. Chapter editing forms remain independent targets. | +| Independent visualisation | Relationships, Maps, Floor Plans | No automatic local movement. Go explicitly aligns an eligible local scene; unavailable/disabled/dirty operations explain or disable. Preserve specialised markers, journeys and occupancy editing. | +| Exploratory | Timeline, Plot Lines, At This Point | Preserve filters/snapshots until Go; locate/reveal/inspect through existing mechanisms. | +| Chapter destination | Book Overview | Go opens focused chapter with retainNarrativeFocus, preserving scene focus. | +| Other editing/unsupported pages | Chapter Edit and unrelated workspaces | Disable Go with explanation; never retarget forms, objectives, sessions or verified Word state. | + +## Correction plan + +Add a guarded chapter adapter using existing document routes. Give Review one cancellable navigation path for initial load, events and Go: await its accepted-context selection, invalidate obsolete reader-anchor restorations, settle layout, resolve again against the current accepted revision, then position a stable accepted paragraph (or show a precise-position-unavailable chapter fallback). Keep the service and SQL unchanged. Qualify delayed/out-of-order responses, control equivalence, initial load, revisions, sticky/narrow layouts, unsaved forms and all existing independent adapters. Add the scoped Focus/Help divider correction. + +## Implemented and qualified correction + +Chapter Details and Writer chapter workflow now carry explicit scope/ChapterID markers and share a focus-following adapter. Clean chapter changes use the existing document route with `retainNarrativeFocus=true`; scene rows are located by stable SceneID. Dirty/busy forms defer following and explain how to resynchronise. Aligned Go confirms the location without changing focus. Refresh/reveal actions also retain narrative focus. Chapter Edit remains a fixed editing target and has disabled Go with an explanation. + +Review now has one version/generation-checked, cancellable pipeline for initial focus, every successful focus event, accepted-content updates and explicit Go. It awaits accepted-context selection and layout frames before resolving and positioning the first accepted paragraph carrying the stable SceneID. Resolution repeats against the current displayed accepted version. Missing mappings produce a chapter-level fallback and an explicit precision-unavailable notice. Reader anchor callbacks captured before explicit navigation cannot restore an older position afterwards. Header dismissal preserves keyboard focus without scrolling back to the header. Page-show reconciliation reads the authoritative focus after document navigation; it does not write or infer a location. + +Local explorers keep independent positions. Disabled/outdated explorer targets are explained; no-op selection is no longer reported as successful Go. Snapshot failures propagate an explicit failure. Maps reveals its story layer, checks mapping/planning eligibility before changing the local target, and explains missing data or unmapped locations while retaining local filters. Timeline and Plot Lines retain their existing reveal/inspect contracts. Unsupported pages have explanatory disabled tooltips. + +The Focus/Help separator reuses the standard ribbon border variable and dimensions, overriding the DOM-last exception only when a Help group is present. No extra Help group or gap was added. + +Qualification uses compiled MVC/Razor and production JavaScript with isolated representative accepted manuscripts. The new accepted fixture has multiple mapped scenes/chapters, deliberately different scene-record order, coherent accepted heading/paragraph windows and a missing-mapping variant. Automated coverage checks stable-ID/accepted-order resolution, all control paths yielding the same paragraph/viewport offset, initial load, refresh, chapter boundaries, rapid clicks, late chapter responses, obsolete anchor callbacks, dirty chapter forms, missing mappings, sticky/narrow layouts, unsupported explanations and the Focus/Help divider. Existing objective/session/annotation/Word safeguards and local visualisation isolation remain covered by the regression suites. No SQL/schema or synchronisation changes were needed. + +Qualification results: solution build passed with zero warnings/errors; full executable regression harness passed all 632 checks, including new stable-ID accepted-projection assertions. `focus-synchronisation.cjs` passed in Chromium and a CDP-installed standalone Chromium PWA, at 1666/950/650px in light/dark themes. It also verifies an editor opened during an in-flight context load is retained. Existing Focus ribbon, narrative-focus architecture/local explorer, popup and manuscript-reader browser suites passed; architecture checks additionally cover map-filter refusal and revealing a hidden story layer. Reader regression covers three widths × four themes × browser/PWA. These are isolated fixture tests, not a claim of live physical Word-device qualification. + +Remaining boundaries are deliberate: Chapter pages reuse document navigation because they have no in-place chapter renderer; dirty editing defers following until the author saves/cancels and resynchronises. Exact Review scene positioning requires an accepted canonical association. Unsupported editing pages, unavailable local scenes and mismatched workspace scopes stay disabled or report the reason rather than guessing, changing filters or retargeting edits. diff --git a/PlotLine.Tests/Browser/focus-synchronisation.cjs b/PlotLine.Tests/Browser/focus-synchronisation.cjs new file mode 100644 index 00000000..45256f0c --- /dev/null +++ b/PlotLine.Tests/Browser/focus-synchronisation.cjs @@ -0,0 +1,50 @@ +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+'/Chapters/Details/21');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus); + await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-position]').selectOption('22/32');await p.waitForURL(/Chapters\/Details\/22/);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.sceneID===32);assert.equal(await p.locator('[data-focus-chapter]').getAttribute('data-chapter'),'22'); + await command('previous');await p.waitForURL(/Chapters\/Details\/21/);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.sceneID===101);assert.equal(await p.locator('[data-pd-context=scene][aria-current=location]').getAttribute('data-pd-context-id'),'101'); + const form=p.locator('[data-focus-chapter] form:has(input[name=overwriteAuthor])');await form.locator('input[type=checkbox]').check();await set({chapterID:22,sceneID:32});assert.equal(await p.locator('[data-focus-chapter]').getAttribute('data-chapter'),'21');await go();assert.match(await p.locator('[data-focus-workspace-status]').textContent(),/Save or cancel/);await form.evaluate(n=>n.reset());await go();await p.waitForURL(/Chapters\/Details\/22/);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.sceneID===32); + const version=(await state()).version;await go();assert.equal((await state()).version,version,'aligned Chapter Go retains scene and version'); + await p.goto(base+'/Writer/Review?projectId=7&bookId=12');await positioned(32);let baseline=await position();assert(baseline.id,'initial Review load positions verified scene');await clear();await go();await positioned(32);assert.deepEqual(await position(),baseline,'initial load and Go use identical accepted target and offset'); + for(const scene of [31,101,32]){const chapter=scene===32?22:21;await choose(chapter+'/'+scene);baseline=await position();assert.equal((await p.evaluate(()=>window.__focusEvents.length)),1,'one authoritative event per successful selection');assert.equal(baseline.id,await p.locator(`[data-paragraph-id][data-scene-id="${scene}"]`).first().getAttribute('data-paragraph-id'));await clear();await go();await positioned(scene);assert.deepEqual(await position(),baseline,'Go leaves identical scene position unchanged');} + // Return to the same scene through canonical ribbon stepping and recent history. + await choose('21/101');baseline=await position();await clear();await command('previous');await positioned(31);await clear();await command('next');await positioned(101);assert.deepEqual(await position(),baseline);await choose('22/32');await clear();await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-recent]').selectOption('21/101');await positioned(101);assert.deepEqual(await position(),baseline,'recent, header and ribbon target the same paragraph/offset'); + // A late context response must not replace an editor opened while navigation is loading. + await choose('21/31');let releaseContext;const contextGate=new Promise(r=>releaseContext=r);await p.route('**/WriterReview/Panel?*',async route=>{const response=await route.fetch();await contextGate;await route.fulfill({response}).catch(()=>{});});const contextRequest=p.waitForRequest('**/WriterReview/Panel?*');await set({chapterID:21,sceneID:101});await contextRequest;await p.locator('[data-authoring-edit]').first().click();const draft=p.locator('[data-authoring-form]:not([hidden]) textarea').first();await draft.fill('Unsaved chapter note during focus navigation');releaseContext();await p.unroute('**/WriterReview/Panel?*');await p.waitForFunction(()=>document.querySelector('[data-review-message]').textContent.includes('edits are retained'));assert.equal(await draft.inputValue(),'Unsaved chapter note during focus navigation');await p.locator('[data-authoring-form]:not([hidden]) [data-authoring-cancel]').click();await clear();await go();await positioned(101); + // A callback captured before navigation cannot undo a newer explicit target. + await p.evaluate(()=>window.__oldReadingAnchor=document.querySelector('.manuscript-reader').readerPreserveView());await choose('21/31');const beforeOldRestore=await position();await p.evaluate(()=>window.__oldReadingAnchor());assert.deepEqual(await position(),beforeOldRestore); + // Hold a chapter response, return to the displayed chapter, then deliver the stale response. + let release;const held=new Promise(r=>release=r);await p.route('**/Writer/ReviewContent?*',async route=>{const response=await route.fetch();await held;await route.fulfill({response}).catch(()=>{});});const requested=p.waitForRequest('**/Writer/ReviewContent?*');await set({chapterID:22,sceneID:32});await requested;await clear();await set({chapterID:21,sceneID:101});await positioned(101);release();await p.unroute('**/Writer/ReviewContent?*');await p.waitForTimeout(150);assert.equal((await position()).chapter,'21');assert.equal(await p.locator('[data-paragraph-id][data-scene-id="101"]').first().getAttribute('data-paragraph-id'),(await position()).id,'older chapter response cannot overwrite newer scene'); + await choose('21/31');await clear();await p.locator(active+' [data-global-focus=next]').evaluate(n=>{n.click();n.click();});await positioned(101);assert.equal((await state()).sceneID,101);assert.equal(await p.evaluate(()=>window.__focusEvents.length),1,'rapid clicks accept one scoped update while the command is busy');assert.deepEqual(await p.evaluate(()=>window.__focusEvents.map(e=>[e.chapterID,e.sceneID])),[[21,101]]); + for(const width of [1666,950,650])for(const theme of ['modern-light','modern-dark']){await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);await p.setViewportSize({width,height:1050});await choose('21/101');const before=await position();await clear();await go();await positioned(101);const after=await position();assert.equal(after.id,before.id);assert(Math.abs(after.top-before.top)<1,'sticky/narrow reader offset is repeatable');await p.screenshot({path:`/tmp/pd-focus-sync-${installed?'pwa':'browser'}-${width}-${theme}.png`});} + await p.reload();await positioned(101);assert.equal((await position()).id,baseline.id,'refresh resolves the same accepted paragraph identity'); + await c.addCookies([{name:'fixture-focus-reader',value:'unmapped',url:base}]);await p.goto(base+'/Writer/Review?projectId=7&bookId=12');await choose('22/32');assert.equal((await position()).id,'');assert.match(await p.locator('[data-review-focus-notice]').textContent(),/Precise scene positioning is unavailable/);assert.equal((await position()).chapter,'22'); + await p.goto(base+'/fixture?desktop=StoryPoint');await p.waitForFunction(()=>document.querySelector('.pd-ribbon-panel:not([hidden]) .pd-ribbon-group[aria-label=Help]')||!matchMedia('(display-mode: standalone)').matches); + if(installed){const divider=await p.locator(active+' .pd-ribbon-focus').evaluate(n=>{const s=getComputedStyle(n);return {width:s.borderRightWidth,style:s.borderRightStyle,color:s.borderRightColor};});assert.equal(divider.width,'1px');assert.equal(divider.style,'solid');} + await p.route('**/StoryPoint?*',r=>r.fulfill({status:503,body:'Synthetic unavailable snapshot'}));await p.route('**/StoryPoint/Index?*',r=>r.fulfill({status:503,body:'Synthetic unavailable snapshot'}));await go();assert.match(await p.locator('[data-focus-workspace-status]').textContent(),/could not be loaded/); + await p.goto(base+'/fixture?desktop=Characters');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);assert(await p.locator(active+' [data-global-focus=go]').isDisabled());assert.match(await p.locator(active+' [data-global-focus=go]').getAttribute('title'),/does not support/); + console.log(`PASS ${installed?'installed Chromium PWA':'Chromium'} focus synchronisation: stable-ID chapter follow/dirty guard/Go, identical initial/header/recent/ribbon/Go/refresh accepted positions, canonical boundaries, stale anchor/response rejection, missing-map fallback, repeatable sticky/narrow offsets, disabled explanations and Focus/Help divider.`); + }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/Browser/narrative-focus.cjs b/PlotLine.Tests/Browser/narrative-focus.cjs index 63c0ca98..016533cc 100644 --- a/PlotLine.Tests/Browser/narrative-focus.cjs +++ b/PlotLine.Tests/Browser/narrative-focus.cjs @@ -93,6 +93,8 @@ const base=process.env.PD_NARRATIVE_TEST_URL||'http://127.0.0.1:5238'; await p.locator('#mapStoryScene').evaluate(n=>{n.value='90';n.dispatchEvent(new Event('change',{bubbles:true}));});assert.equal((await state()).version,mapVersion,'Maps scene selection is local'); const mapScene=await p.locator('#mapStoryScene').inputValue();await set({chapterID:21,sceneID:31});assert.equal(await p.locator('#mapStoryScene').inputValue(),mapScene,'global focus retains map position and journey context');const mapFocusVersion=(await state()).version;await go();assert.equal(await p.locator('#mapStoryScene').inputValue(),'31');assert.equal((await state()).version,mapFocusVersion); assert.match(await p.locator('#mapsDetailContent').innerText(),/Harbour morning/); + await p.locator('#mapStoryScene').evaluate(n=>{n.value='90';n.dispatchEvent(new Event('change',{bubbles:true}));});const filteredPosition=await p.locator('#mapStoryScene').inputValue();const excludedMapping=mapFixture.scenes.find(s=>s.sceneID===31).position.featureID?'unmapped':'mapped';await p.locator('#mapStoryMapping').evaluate((n,value)=>{n.value=value;n.dispatchEvent(new Event('change',{bubbles:true}));},excludedMapping);await go();assert.match(await p.locator('[data-focus-workspace-status]').textContent(),/mapping or planning filters/);assert.equal(await p.locator('#mapStoryScene').inputValue(),filteredPosition,'filtered Go preserves the existing local map target');assert.equal(await p.locator('#mapStoryMapping').inputValue(),excludedMapping);await p.locator('#mapStoryMapping').evaluate(n=>{n.value='all';n.dispatchEvent(new Event('change',{bubbles:true}));});await p.locator('#mapStoryLayer').evaluate(n=>n.click());assert.equal(await p.evaluate(()=>window.PlotDirectorStoryOverlay.state.visible),false);await go();assert.equal(await p.evaluate(()=>window.PlotDirectorStoryOverlay.state.visible),true,'Go reveals a hidden story layer');assert.equal((await state()).version,mapFocusVersion); + await p.screenshot({path:`/tmp/pd-narrative-${installed?'pwa':'browser'}-Maps.png`}); await p.goto(base+'/Timeline/Index?ProjectID=7');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.bookID===12);assert.match(await p.locator('[data-focus-label]').textContent(),/A Distant Shore/);await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-book]').selectOption('13');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.bookID===13);assert.equal((await state()).sceneID,null);assert.equal(await p.locator('.timeline-scene-card').count(),3,'focus book selection preserves project-wide Timeline');assert(!new URL(p.url()).searchParams.has('BookID'));await p.locator('[data-focus-book]').selectOption('12');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.bookID===12); await p.locator('[data-focus-position]').selectOption('23/');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.chapterID===23);assert(await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="next"]').isDisabled(),'no following scene after the final empty chapter');assert(await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="previous"]').isEnabled());await openFocus();await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="previous"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32);await set({chapterID:21,sceneID:31}); diff --git a/PlotLine.Tests/ManuscriptReaderTests.cs b/PlotLine.Tests/ManuscriptReaderTests.cs index bc630eb9..dfdd221f 100644 --- a/PlotLine.Tests/ManuscriptReaderTests.cs +++ b/PlotLine.Tests/ManuscriptReaderTests.cs @@ -32,6 +32,19 @@ internal static class ManuscriptReaderTests ] }; } + internal static ParagraphManuscript FocusSnapshot(bool unmapped=false) + { + var state=Snapshot();state.Paragraphs.Clear();state.Chapters.Clear();state.Scenes.Clear();state.Revision=7; + // Scene-record order differs from canonical scene order; accepted paragraph/heading windows remain coherent. + foreach(var pair in new[]{(22,new[]{32}),(21,new[]{101,31})}){ + var heading=Guid.NewGuid();state.Chapters.Add(new(){CanonicalId=pair.Item1,HeadingId=heading}); + state.Paragraphs.Add(new(){ChapterId=pair.Item1,Occurrence=new(){Id=heading,Ordinal=pair.Item1==21?0:100,Outline=1,Text="Synthetic chapter "+pair.Item1}}); + foreach(var id in pair.Item2){var scene=Guid.NewGuid();state.Scenes.Add(new(){Id=scene,CanonicalId=id,ChapterId=pair.Item1}); + for(var i=0;i<25;i++)state.Paragraphs.Add(new(){ChapterId=pair.Item1,SceneId=unmapped&&id==32?null:scene,Story=true,Occurrence=new(){Id=Guid.NewGuid(),Ordinal=(id==31?1:id==101?30:101)+i,Outline=10,Text=$"Scene {id}, accepted paragraph {i}. "+string.Join(" ",Enumerable.Repeat("Synthetic accepted prose for stable position regression.",8))}}); + } + } + state.Paragraphs=state.Paragraphs.OrderBy(p=>p.Occurrence.Ordinal).ToList();return state; + } internal static ManuscriptReaderService FixtureService(Func? snapshot = null, Action? onRead = null,bool allowSecondBook=false) { var fixture = Snapshot(); @@ -66,6 +79,10 @@ internal static class ManuscriptReaderTests public static async Task Run() { void Check(bool value, string message) { if (!value) throw new Exception(message); } + var focused=FocusSnapshot();var focusedReader=FixtureService(()=>focused);var mapped=(await focusedReader.Read(4,12,21))!; + Check(mapped.Paragraphs.Where(p=>p.SceneID.HasValue).Select(p=>p.SceneID).Distinct().SequenceEqual(new int?[]{31,101}),"Accepted scene targets resolve stable canonical IDs in accepted paragraph order, independently of scene-record order"); + var firstScene=mapped.Paragraphs.First(p=>p.SceneID==101);Check(firstScene.Id==focused.Paragraphs.OrderBy(p=>p.Occurrence.Ordinal).First(p=>p.SceneId==focused.Scenes.Single(s=>s.CanonicalId==101).Id).Occurrence.Id,"Scene positioning uses the first accepted mapped paragraph identity rather than a scene or paragraph index"); + var missing=(await FixtureService(()=>FocusSnapshot(true)).Read(4,12,22))!;Check(missing.Paragraphs.All(p=>p.SceneID is null),"Missing accepted scene associations remain unverified rather than being inferred from narrative focus"); var state = Snapshot(); var reads = 0; var service = FixtureService(() => state, () => reads++); var first = (await service.Read(4, 12, null))!; Check(first.Chapters.Count == 3 && first.Chapter!.ChapterID == 21, "Book context and canonical chapter ordering"); diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index a73b7bda..16ea8bea 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -21,6 +21,8 @@ internal static class ToolbarBrowserHost { private static readonly ParagraphManuscript readerFixture = ReviewSnapshot(); private static ParagraphManuscript ReviewSnapshot(){var state=ManuscriptReaderTests.Snapshot();var scene=Guid.NewGuid();state.Scenes=[new(){Id=scene,CanonicalId=31,ChapterId=21}];foreach(var p in state.Paragraphs.Where(p=>p.ChapterId==21&&p.Story))p.SceneId=scene;return state;} + private static readonly ParagraphManuscript readerFocusFixture=ManuscriptReaderTests.FocusSnapshot(); + private static readonly ParagraphManuscript readerUnmappedFixture=ManuscriptReaderTests.FocusSnapshot(true); private static readonly ParagraphManuscript readerLongFixture = ManuscriptReaderTests.LongSnapshot(); private static readonly System.Collections.Concurrent.ConcurrentDictionary<(int User, int Chapter), ChapterGoal> writerGoals = new(); @@ -151,12 +153,12 @@ internal static class ToolbarBrowserHost })); builder.Services.AddSingleton(FixtureProxy((name,args)=>{ if(name!="GetDetailAsync")throw new NotSupportedException(name); - var id=(int)args![0]!;return Task.FromResult(new(){Project=new(){ProjectID=7,ProjectName="The Glass Harbour"},Book=new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore"},Chapter=new(){ChapterID=id,BookID=12,ChapterNumber=id==21?1:2,ChapterTitle="Focused chapter"}}); + var id=(int)args![0]!;return Task.FromResult(new(){Project=new(){ProjectID=7,ProjectName="The Glass Harbour"},Book=new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore"},Chapter=new(){ChapterID=id,BookID=12,ChapterNumber=id==21?1:2,ChapterTitle="Focused chapter"},Scenes=(id==21?new[]{31,101}:new[]{32}).Select(scene=>new Scene{SceneID=scene,ChapterID=id,SceneTitle="Scene "+scene,SceneNumber=scene==101?2:1}).ToArray()}); })); builder.Services.AddSingleton(); builder.Services.AddScoped(services => ManuscriptReaderTests.FixtureService(() => services.GetRequiredService().HttpContext!.Request.Query["reader-error"] == "true" - ? throw new TimeoutException("Synthetic unavailable manuscript") : services.GetRequiredService().HttpContext!.Request.Query["reader-long"] == "true" ? readerLongFixture : readerFixture,allowSecondBook:true)); + ? throw new TimeoutException("Synthetic unavailable manuscript") : services.GetRequiredService().HttpContext!.Request.Cookies["fixture-focus-reader"]=="mapped"?readerFocusFixture:services.GetRequiredService().HttpContext!.Request.Cookies["fixture-focus-reader"]=="unmapped"?readerUnmappedFixture:services.GetRequiredService().HttpContext!.Request.Query["reader-long"] == "true" ? readerLongFixture : readerFixture,allowSecondBook:true)); builder.Services.AddHttpContextAccessor(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); @@ -179,7 +181,7 @@ internal static class ToolbarBrowserHost "GetChapterWorkflowAsync" => Task.FromResult(new() { Project = new() { ProjectID = 7, ProjectName = "The Glass Harbour" }, Book = new() { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" }, - Chapter = new() { ChapterID = 21, BookID = 12, ChapterNumber = 1, ChapterTitle = "The crossing" }, + Chapter = new() { ChapterID = (int)args![0]!, BookID = 12, ChapterNumber = (int)args[0]! ==21?1:2, ChapterTitle = "The crossing" }, Goal = writerGoals.GetOrAdd((services.GetRequiredService().UserId!.Value, 21), _ => new() { ChapterID = 21, GoalSummary = "Reveal the consequence" }) }), "SaveChapterGoalAsync" => SaveFixtureGoal(services.GetRequiredService().UserId!.Value, (ChapterGoalEditViewModel)args![0]!), diff --git a/PlotLine.Tests/WriterReviewFixture.cs b/PlotLine.Tests/WriterReviewFixture.cs index 05480d5a..ce10e33d 100644 --- a/PlotLine.Tests/WriterReviewFixture.cs +++ b/PlotLine.Tests/WriterReviewFixture.cs @@ -4,7 +4,7 @@ using PlotLine.Models; internal sealed class WriterReviewFixture(ManuscriptReaderService reader,IWriterAuthoringService intentions):IWriterReviewService { private static readonly object gate=new();private static readonly Dictionary rows=[]; - public async Task Read(int actor,int book,int chapter,Guid? paragraph,string? version,int page,Guid? endParagraph=null){var source=await reader.Read(actor,book,chapter)??throw new KeyNotFoundException();var selected=source.ContentVersion==version?source.Paragraphs.FirstOrDefault(p=>p.Id==paragraph):null;var context=await intentions.Read(actor,12,21,selected?.SceneID);if(chapter!=21)context=new(){BookID=12,ChapterID=chapter,Chapter=source.Chapter!,Sections=context.Sections.Where(x=>x.Kind is "Chapter" or "Goals").ToArray()};lock(gate){var found=rows.Values.Where(r=>r.UserID==actor&&r.BookID==book&&r.ChapterID==chapter).OrderByDescending(x=>x.CreatedUtc).Skip((page-1)*50).Take(51).ToArray();foreach(var row in found)row.AnchorState=WriterReviewService.AnchorState(row,source);return new(context,found.Take(50).ToArray(),page,found.Length>50,selected?.SceneID!=null?"Scene context comes from accepted paragraph assignments.":"No verified scene assignment; chapter intentions remain available.");}} + public async Task Read(int actor,int book,int chapter,Guid? paragraph,string? version,int page,Guid? endParagraph=null){var source=await reader.Read(actor,book,chapter)??throw new KeyNotFoundException();var selected=source.ContentVersion==version?source.Paragraphs.FirstOrDefault(p=>p.Id==paragraph):null;var context=await intentions.Read(actor,12,21,selected?.SceneID==31?31:null);if(chapter!=21||selected?.SceneID is int scene&&scene!=31)context=new(){BookID=12,ChapterID=chapter,SceneID=selected?.SceneID,Chapter=source.Chapter!,Scene=selected?.SceneID is int id?new(){SceneID=id,ChapterID=chapter,SceneTitle="Mapped scene "+id}:null,Sections=context.Sections.Where(x=>x.Kind is "Chapter" or "Goals").ToArray()};lock(gate){var found=rows.Values.Where(r=>r.UserID==actor&&r.BookID==book&&r.ChapterID==chapter).OrderByDescending(x=>x.CreatedUtc).Skip((page-1)*50).Take(51).ToArray();foreach(var row in found)row.AnchorState=WriterReviewService.AnchorState(row,source);return new(context,found.Take(50).ToArray(),page,found.Length>50,selected?.SceneID!=null?"Scene context comes from accepted paragraph assignments.":"No verified scene assignment; chapter intentions remain available.");}} public async Task Save(int actor,ReviewSave r){var source=await reader.Read(actor,r.BookID,r.ChapterID)??throw new KeyNotFoundException();var error=WriterReviewService.Validate(r);if(error.Length>0)throw new ArgumentException(error);lock(gate){if(r.Version==0){if(rows.TryGetValue(r.ID,out var existing)){if(existing.UserID==actor&&existing.Observation==r.Observation)return existing;throw new AuthoringConflictException("Observation changed; your text is retained.");}if(source.ContentVersion!=r.ContentVersion)throw new AuthoringConflictException("Accepted chapter changed; your text is retained.");var anchors=WriterReviewService.Anchor(source,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset);var row=new ReviewObservation{ID=r.ID,UserID=actor,BookID=r.BookID,ChapterID=r.ChapterID,ContentVersion=r.ContentVersion,ManuscriptID=source.ManuscriptID,SnapshotRevision=source.Revision,StartParagraph=r.StartParagraph,EndParagraph=r.EndParagraph,StartOffset=r.StartOffset,EndOffset=r.EndOffset,AnchorHash=anchors.Length>0?WriterReviewService.Hash(anchors):null,SceneID=r.Scope=="Scene"?r.SceneID:anchors.FirstOrDefault()?.SceneID,Scope=string.IsNullOrEmpty(r.Scope)?null:r.Scope,Classification=r.Classification,Observation=r.Observation,Decision=r.Decision,Status=r.Status,Version=1,CreatedUtc=DateTime.UtcNow,UpdatedUtc=DateTime.UtcNow};rows[r.ID]=row;return row;} if(!rows.TryGetValue(r.ID,out var saved)||saved.UserID!=actor||saved.BookID!=r.BookID||saved.ChapterID!=r.ChapterID||saved.Version!=r.Version)throw new AuthoringConflictException("Another window changed this observation; your text is retained.");saved.Observation=r.Observation;saved.Decision=r.Decision;saved.Status=r.Status;saved.Classification=r.Classification;saved.Version++;saved.UpdatedUtc=DateTime.UtcNow;return saved;}} } diff --git a/PlotLine/Views/Chapters/Details.cshtml b/PlotLine/Views/Chapters/Details.cshtml index 52273d2c..5302800f 100644 --- a/PlotLine/Views/Chapters/Details.cshtml +++ b/PlotLine/Views/Chapters/Details.cshtml @@ -5,6 +5,7 @@ ViewData["ProjectSection"] = "Overview"; } +
} + + diff --git a/PlotLine/Views/Writer/Chapter.cshtml b/PlotLine/Views/Writer/Chapter.cshtml index 8661a055..52d6c696 100644 --- a/PlotLine/Views/Writer/Chapter.cshtml +++ b/PlotLine/Views/Writer/Chapter.cshtml @@ -8,6 +8,7 @@ var polishCount = Model.Scenes.Count(x => x.RevisionStatusName == "Revised"); } +