From ea0199a6b4254e252b7c0656de4e7d12c98b1a25 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Mon, 23 Nov 2026 22:02:00 +0000 Subject: [PATCH] Fix Context location choices and use text-only Hold Release toggle --- .../Context-Location-Correction-20261123.md | 26 +++++++++ .../Browser/context-location-correction.cjs | 58 +++++++++++++++++++ PlotLine.Tests/ContextCharacterTests.cs | 16 ++++- .../Context/ContextCharacterEditing.cs | 8 ++- .../Views/Shared/_FocusFollowControl.cshtml | 2 +- .../Writing/_ContextCharacterEdit.cshtml | 1 + .../wwwroot/js/shared-manuscript-focus.js | 2 +- 7 files changed, 108 insertions(+), 5 deletions(-) create mode 100644 Docs/Writer/Context-Location-Correction-20261123.md create mode 100644 PlotLine.Tests/Browser/context-location-correction.cjs diff --git a/Docs/Writer/Context-Location-Correction-20261123.md b/Docs/Writer/Context-Location-Correction-20261123.md new file mode 100644 index 00000000..c747ce82 --- /dev/null +++ b/Docs/Writer/Context-Location-Correction-20261123.md @@ -0,0 +1,26 @@ +# Context location selector and Hold button correction — 23 November 2026 + +## Root cause and corrections + +`ContextCharacterEditing.Load` reused `SceneEditViewModel.LocationOptions`. Context requests `GetForSceneAsync(..., forWriting: true, includeNarrative: false)`, which uses the deliberately lightweight `PopulateWritingDataAsync` path. That path loads scene participation records but intentionally omits editor lookup choices. Consequently the correction modal received only its own “No recorded location” option, regardless of available library locations or character history. + +The location correction now calls the existing `ILocationRepository.ListByProjectAsync` / `dbo.Location_ListByProject` after book, project edit-access, scene and character-scope validation. Active locations from that project populate the dropdown, using canonical hierarchy paths with a name fallback. The empty option clears the scene-specific location; an empty library also displays an explicit inline empty state. Save reloads the authorised choices and rejects foreign/archived values. It continues to use the existing `UpdateSceneCharacterAsync` persistence and Context data invalidation. No schema change, new location, scene-primary-location write or shared-focus publication was introduced. + +The standalone Context toolbar renders no SVG for its existing Hold toggle, and specifies “Release” as its held label. Classes, placement, fixed width, availability gate and Hold behaviour remain unchanged. Main ribbon buttons retain their existing pause/play SVG and Hold/Resume text. Word VSTO and all three Word caret controls are unchanged; Focus Previous/Next/History are unchanged. + +## Verification + +- Solution build: zero warnings/errors. +- Full executable regression harness: 809 PASS checks. +- Focused service regression reproduces empty writing-model choices, with no recorded character location, while a canonical library exists. It verifies project-scoped lookup, hierarchical labels, scene-participation persistence, unrelated-field preservation, reopen, clear, foreign/archived exclusion, empty library and existing edit authorisation. +- Existing chronology checks preserve canonical Previous/Now/Next ordering and exclude future information from current blanks. +- Existing shared-focus reliability browser checks pass: connection/revision races, independent Hold/reconnect, genuine unavailable states and no adjacent status controls. +- New real authenticated browser test `PlotLine.Tests/Browser/context-location-correction.cjs` passes against the isolated Development host with actual SQL and SignalR. It verifies library choices, hierarchy, assign/clear/reopen, chronology, another character and other scenes, single-pane and two simultaneous character panes, remote live refresh while held, preserved character expansion/scene/focus/Hold state, text-only Hold/Release, main ribbon icons/Hold/Resume and three retained Word caret actions. +- Its `--empty-library` case also passes against a genuinely empty active fixture library and verifies the explicit empty message and clearing option. +- Direct fixture checks confirm no duplicate locations, scene primary location unchanged and clearing persisted. + +Testing uses disposable characters and scenes, not changes to Rick or the real manuscript. Development database identity was verified, and a unique copy-only checksum backup was created and verified before fixture preparation. The application principal could create the backup but lacked RESTORE VERIFYONLY permission; the existing protected administrator helper verified it successfully. No schema migration was needed. Existing unrelated untracked investigation files are preserved. + +## Delivery + +Implementation/push/deployment and public Development acceptance evidence will be completed after installation. Production remains untouched. diff --git a/PlotLine.Tests/Browser/context-location-correction.cjs b/PlotLine.Tests/Browser/context-location-correction.cjs new file mode 100644 index 00000000..31da2527 --- /dev/null +++ b/PlotLine.Tests/Browser/context-location-correction.cjs @@ -0,0 +1,58 @@ +// Real Development auth/SQL/SignalR; only the guarded disposable shared-focus fixture. +const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict'); +const base=process.env.PD_SHARED_FOCUS_URL||'http://127.0.0.1:5258'; +(async()=>{ + const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),s=JSON.parse(fs.readFileSync('/tmp/shared-focus-browser-scope.json')); + assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);assert(who.Email.startsWith('pwa-browser-')); + const browser=await chromium.launch();let step='login';const errors=[]; + try{ + const c=await browser.newContext({viewport:{width:1450,height:1000}}); + c.on('page',p=>p.on('pageerror',e=>errors.push(e.message))); + 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')})); + const login=await c.newPage();await login.goto(base+'/Account/Login');await login.locator('[name=Email]').fill(who.Email);await login.locator('[name=Password]').fill(who.Password); + await Promise.all([login.waitForURL(u=>u.pathname!='/Account/Login'),login.locator('button[type=submit]').click()]); + const url=`${base}/Writing/Context?projectId=${s.project}&bookId=${s.book}&sceneId=${s.scene2}`; + async function ready(p){await p.waitForFunction(()=>window.PlotDirectorSharedFocus&&document.querySelector('[data-context-workspace]')?.contextController?.connection?.state==='Connected');await p.waitForSelector('[data-context-tab-fragment]');await p.waitForFunction(()=>!document.querySelector('[data-shared-focus-hold]').disabled);} + async function open(){const p=await c.newPage();await p.goto(url);await ready(p);await p.selectOption('[data-context-tab]','characters');await p.waitForSelector(`[data-context-character="${s.character1}"]`);return p;} + const a=await open(); + if(process.argv.includes('--empty-library')){ + await a.locator(`[data-context-edit="location"][data-character-id="${s.character1}"]`).click();await a.waitForSelector('[data-context-edit-form] select[name=Value]'); + assert.equal(await a.locator('[name=Value] option').count(),1);assert.equal(await a.locator('[name=Value] option').getAttribute('value'),''); + assert.match(await a.locator('[data-context-edit-form]').innerText(),/No locations are available in this project's Locations Library/); + console.log('PASS real empty project Locations Library: explicit empty state and clearing option.');return; + } + const b=await open(); + await a.selectOption('[data-context-scene]',String(s.scene2));await a.waitForFunction(id=>PlotDirectorSharedFocus.local.sceneID===id,s.scene2); + await b.click('[data-shared-focus-hold]');assert.equal(await b.locator('[data-shared-focus-hold]').innerText(),'Release'); + for(const p of [a,b])assert.equal(await p.locator('[data-shared-focus-hold] svg').count(),0); + await b.selectOption('[data-context-layout]','columns');await b.selectOption('[data-context-pane="1"] [data-context-tab]','characters');await b.waitForSelector(`[data-context-pane="1"] [data-context-character="${s.character1}"]`); + async function expand(p,pane,id){const row=p.locator(`[data-context-pane="${pane}"] [data-context-character="${id}"]`);await row.evaluate(n=>n.open=true);return row;} + for(const [p,pane] of [[a,0],[b,0],[b,1]])await expand(p,pane,s.character1); + const snapshot=p=>p.evaluate(()=>({local:PlotDirectorSharedFocus.local,shared:PlotDirectorSharedFocus.shared,held:PlotDirectorSharedFocus.held})); + const beforeA=await snapshot(a),beforeB=await snapshot(b); + async function edit(id=s.character1){await expand(a,0,id);await a.locator(`[data-context-pane="0"] [data-context-edit="location"][data-character-id="${id}"]`).click();await a.waitForSelector('[data-context-edit-form] select[name=Value]');} + async function save(value){await a.selectOption('[data-context-edit-form] [name=Value]',value);await a.locator('[data-context-edit-form] button[type=submit]').click();await a.waitForFunction(()=>!document.querySelector('[data-context-edit-dialog]').open);} + async function now(p,pane,id,value){await p.waitForFunction(({pane,id,value})=>{const n=document.querySelector(`[data-context-pane="${pane}"] [data-character-detail="${id}"] .context-location-rail > div:nth-child(2)`);return n?.textContent.includes(value);},{pane,id,value});} + step='original failure: no previous current location still gets the whole project library';await edit(); + const options=await a.locator('[name=Value] option').evaluateAll(ns=>ns.map(n=>({text:n.textContent,value:n.value}))); + assert.equal(options[0].value,'');assert.match(options[0].text,/No recorded location/);assert(options.length>=4); + const room=options.find(o=>o.text.includes('Fixture room'));assert(room&&room.text.includes('Fixture house'),'hierarchy path shown');const garden=options.find(o=>o.text.includes('Fixture garden'));assert(garden); + step='canonical save refreshes single and both split panes, including held window';await save(room.value); + for(const [p,pane] of [[a,0],[b,0],[b,1]]){await now(p,pane,s.character1,'Fixture room');assert.equal(await p.locator(`[data-context-pane="${pane}"] [data-context-character="${s.character1}"]`).evaluate(n=>n.open),true,'selected character remains expanded');} + assert.deepEqual(await snapshot(a),beforeA);assert.deepEqual(await snapshot(b),beforeB); + const rail=a.locator(`[data-character-detail="${s.character1}"] .context-location-rail`);assert.match(await rail.innerText(),/Previous[\s\S]*Fixture house[\s\S]*Now[\s\S]*Fixture room[\s\S]*Next[\s\S]*Fixture garden/); + step='refresh/reopening persists without changing Hold or scene';await b.reload();await ready(b);await now(b,0,s.character1,'Fixture room');assert.equal(await b.locator('[data-shared-focus-hold]').innerText(),'Release');assert.deepEqual(await snapshot(b),beforeB); + await edit();assert.equal(await a.locator('[name=Value]').inputValue(),room.value);await a.click('[data-context-edit-cancel]'); + const reopened=await open();await now(reopened,0,s.character1,'Fixture room'); + step='other character remains unrecorded and can be corrected independently';await edit(s.character2);assert.equal(await a.locator('[name=Value]').inputValue(),'');await save(garden.value);await now(b,1,s.character2,'Fixture garden');await now(a,0,s.character1,'Fixture room'); + step='clear persists and updates held panes';await edit();await save('');for(const [p,pane] of [[a,0],[b,0],[b,1]])await now(p,pane,s.character1,'No recorded location here'); + await edit();assert.equal(await a.locator('[name=Value]').inputValue(),'');await a.click('[data-context-edit-cancel]');assert.deepEqual(await snapshot(a),beforeA);assert.deepEqual(await snapshot(b),beforeB); + const state=await a.evaluate(async s=>{const results=[];for(const scene of [s.scene1,s.scene3]){const response=await fetch(`/Writing/Context/EditCharacter?bookId=${s.book}&sceneId=${scene}&characterId=${s.character1}&field=location`);const doc=new DOMParser().parseFromString(await response.text(),'text/html');results.push(doc.querySelector('[name=Value] option:checked')?.textContent);}return results;},s); + assert.match(state[0],/Fixture house/);assert.match(state[1],/Fixture garden/); + await b.click('[data-shared-focus-hold]');await b.waitForFunction(()=>!PlotDirectorSharedFocus.held);assert.equal(await b.locator('[data-shared-focus-hold]').innerText(),'Hold');assert.equal(await b.locator('[data-shared-focus-hold] svg').count(),0); + step='main ribbon remains Hold/Resume with icons and three Word caret actions';await login.goto(`${base}/Writer/Review?projectId=${s.project}&bookId=${s.book}&chapterId=${s.chapter1}`); + const main=login.locator('.pd-ribbon-panel:not([hidden]) [data-shared-focus-hold]');await main.waitFor({state:'visible'});await login.waitForFunction(()=>!document.querySelector('.pd-ribbon-panel:not([hidden]) [data-shared-focus-hold]').disabled); + assert.equal(await main.locator('svg [data-focus-mode-icon]').count(),1);await main.click();assert.equal(await main.innerText(),'Resume');await main.click();await login.waitForFunction(()=>!PlotDirectorSharedFocus.held);assert.equal(await main.innerText(),'Hold');assert.equal(await login.locator('[data-ribbon-word]').count(),3); + assert.deepEqual(errors,[]);console.log('PASS real Context location correction: canonical library without history, hierarchy, save/clear/reopen, chronology, independent other character/scenes, single/split panes, held live invalidation, focus/selection preserved, text-only Hold/Release, main ribbon icons and Word caret controls unchanged.'); + }catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await browser.close();} +})(); diff --git a/PlotLine.Tests/ContextCharacterTests.cs b/PlotLine.Tests/ContextCharacterTests.cs index 69257477..ac3a9aee 100644 --- a/PlotLine.Tests/ContextCharacterTests.cs +++ b/PlotLine.Tests/ContextCharacterTests.cs @@ -41,9 +41,14 @@ internal static class ContextCharacterTests Task AddAlias(string value){aliases.Add(new(){CharacterAliasID=12,CharacterID=5,Alias=value});return Task.FromResult(12);} Task UpdateAlias(int id,string value){aliases.Single(a=>a.CharacterAliasID==id).Alias=value;return Task.CompletedTask;} Task DeleteAlias(int id){aliases.RemoveAll(a=>a.CharacterAliasID==id);return Task.CompletedTask;} + IReadOnlyList library=[new(){LocationID=41,ProjectID=7,LocationName="Room",LocationPath="House / Room"},new(){LocationID=42,ProjectID=8,LocationName="Other project"},new(){LocationID=43,ProjectID=7,LocationName="Archived",IsArchived=true}]; + var locationReads=0; + var locationRepository=NativeWorkflowTests.Proxy((name,args)=>{ + Check(name=="ListByProjectAsync"&&(int)args![0]! ==7,"location lookup uses the authorised book's project");locationReads++;return Task.FromResult(library); + }); var edit=new ContextCharacterEditing(service, NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){Position=new(7,12,10,22),Scene=new(){SceneID=22,SceneCharacters=[appearance]}})), - repository, + repository,locationRepository, NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){BookId=12,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=22}]}]})), NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){BookID=12,ProjectID=7})),NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){ProjectID=7,AccessRole=role})), NativeWorkflowTests.Proxy((_,_)=>7),new ContextWorkspaceNotifications(hub,NullLogger.Instance)); @@ -51,6 +56,15 @@ internal static class ContextCharacterTests var old=form.Fingerprint;form.Value="6";await edit.Save(form);Check(character.CharacterImportance==6&&character.CharacterName=="Preserve name"&&character.Aliases.SequenceEqual(["Kept alias"]),"focused classification save preserves unrelated canonical identity fields"); try{form.Fingerprint=old;await edit.Save(form);throw new Exception("Stale save accepted");}catch(InvalidOperationException){Check(true,"stale drafts are rejected rather than overwriting a newer correction");} var state=await edit.Read(12,22,5,"emotion");state.Value="After";await edit.Save(state);Check(savedAppearance?.EmotionalState=="After"&&savedAppearance.PhysicalCondition=="Preserve physical"&&savedAppearance.KnowledgeNotes=="Preserve knowledge"&&savedAppearance.LocationID==2,"focused scene-state save preserves the rest of the participation record"); + appearance.LocationID=null; + var location=await edit.Read(12,22,5,"location"); + Check(location.Value==null&&location.Options.Count==2&&location.Options.Any(o=>o.Value=="41"&&o.Text=="House / Room"),"empty writing-model choices and no location history still expose the canonical project library with hierarchy"); + location.Value="41";await edit.Save(location); + Check(savedAppearance?.LocationID==41&&savedAppearance.SceneCharacterID==8&&savedAppearance.SceneID==22&&savedAppearance.CharacterID==5&&savedAppearance.PhysicalCondition=="Preserve physical"&&savedAppearance.KnowledgeNotes=="Preserve knowledge","location correction updates only the current participation through canonical persistence"); + appearance.LocationID=41;location=await edit.Read(12,22,5,"location");Check(location.Value=="41","reopened correction reflects the persisted location"); + location.Value="";await edit.Save(location);Check(savedAppearance?.LocationID==null,"clearing explicitly saves an unrecorded scene-specific location"); + var beforeInvalid=writes;location.Value="42";try{await edit.Save(location);throw new Exception("Foreign location accepted");}catch(ArgumentException){Check(writes==beforeInvalid,"foreign/archived location values cannot be saved");} + library=[];location=await edit.Read(12,22,5,"location");Check(location.Options.Count==1&&location.Options[0].Value=="","empty library preserves the clearing option"); var rename=await edit.Read(12,22,5,"name");rename.Value="New canonical";await edit.Save(rename);Check(character.CharacterName=="New canonical"&&character.Aliases.Contains("Preserve name"),"canonical rename retains the old spelling as an alias"); var add=await edit.Read(12,22,5,"alias-add");add.Value="New variant";await edit.Save(add);Check(aliases.Any(a=>a.Alias=="New variant"),"focused alias add reuses existing alias persistence"); var correction=await edit.Read(12,22,5,"alias:11");correction.Value="Corrected alias";await edit.Save(correction);Check(aliases.Single(a=>a.CharacterAliasID==11).Alias=="Corrected alias","individual alias correction preserves identity"); diff --git a/PlotLine/Services/Context/ContextCharacterEditing.cs b/PlotLine/Services/Context/ContextCharacterEditing.cs index 854bd781..6ab508b9 100644 --- a/PlotLine/Services/Context/ContextCharacterEditing.cs +++ b/PlotLine/Services/Context/ContextCharacterEditing.cs @@ -16,7 +16,7 @@ public sealed class ContextCharacterEditForm public IReadOnlyList Options{get;set;}=[]; } public sealed class ContextCharacterEditing(ICharacterService characters,IStoryContextService stories,ICharacterRepository repository, - IWordCompanionRepository access,IBookRepository books,IProjectRepository projects,ICurrentUserService user,ContextWorkspaceNotifications notifications) + ILocationRepository locations,IWordCompanionRepository access,IBookRepository books,IProjectRepository projects,ICurrentUserService user,ContextWorkspaceNotifications notifications) { private static readonly SemaphoreSlim[] Locks=Enumerable.Range(0,64).Select(_=>new SemaphoreSlim(1,1)).ToArray(); private sealed record Frame(ContextCharacterEditForm Form,CharacterEditViewModel Character,SceneEditViewModel? Scene,PlotLine.Models.SceneCharacter? Appearance); @@ -52,7 +52,11 @@ public sealed class ContextCharacterEditing(ICharacterService characters,IStoryC var choices=new List{new("Unclassified",""),new("Major · author choice","10"),new("Supporting","6"),new("Minor","2")}; if(value!=null&&choices.All(c=>c.Value!=value))choices.Add(new("Current recorded classification ("+value+")",value));options=choices; } - if(field=="location")options=[new("No recorded location",""),..scene!.LocationOptions]; + if(field=="location"){ + var library=await locations.ListByProjectAsync(book.ProjectID); + options=[new("No recorded location",""),..library.Where(l=>l.ProjectID==book.ProjectID&&!l.IsArchived) + .Select(l=>new SelectListItem(string.IsNullOrWhiteSpace(l.LocationPath)?l.LocationName:l.LocationPath,l.LocationID.ToString()))]; + } var hash=appearance!=null?Hash(new{appearance.SceneCharacterID,appearance.SceneID,appearance.CharacterID,appearance.RoleInSceneTypeID,appearance.PresenceTypeID,appearance.LocationID,appearance.EntryLocationID,appearance.ExitLocationID,appearance.AppearanceNotes,appearance.OutfitDescription,appearance.EmotionalState,appearance.PhysicalCondition,appearance.KnowledgeNotes}):Hash(new{character.CharacterID,character.CharacterName,character.Aliases,character.CharacterImportance,character.DefaultDescription,character.SexValueID,character.Sex,character.BirthDate,character.IsDeceased,character.AgeAtSeriesStart,character.Height,character.EyeColour,character.ShowInQuickAddBar,character.ImagePath,character.ThumbnailPath,AliasRecords=aliases}); return new(new(){BookID=bookId,SceneID=sceneId,CharacterID=characterId,Field=field,Value=value,Label=labels[field],CharacterName=character.CharacterName,Fingerprint=hash,Options=options},character,scene,appearance); } diff --git a/PlotLine/Views/Shared/_FocusFollowControl.cshtml b/PlotLine/Views/Shared/_FocusFollowControl.cshtml index 3196527f..bac388e8 100644 --- a/PlotLine/Views/Shared/_FocusFollowControl.cshtml +++ b/PlotLine/Views/Shared/_FocusFollowControl.cshtml @@ -1,2 +1,2 @@ @{var embedded=ViewContext.RouteData.Values["controller"]?.ToString()=="Writing";} - + diff --git a/PlotLine/Views/Writing/_ContextCharacterEdit.cshtml b/PlotLine/Views/Writing/_ContextCharacterEdit.cshtml index 03e84a2b..e4158185 100644 --- a/PlotLine/Views/Writing/_ContextCharacterEdit.cshtml +++ b/PlotLine/Views/Writing/_ContextCharacterEdit.cshtml @@ -8,6 +8,7 @@ @if(Model.Options.Count>0){} else{} + @if(Model.Field=="location"&&Model.Options.Count==1){

No locations are available in this project's Locations Library.

}

Only this correction is saved. Other character and scene fields are retained.

diff --git a/PlotLine/wwwroot/js/shared-manuscript-focus.js b/PlotLine/wwwroot/js/shared-manuscript-focus.js index d2952ee3..a0dd426e 100644 --- a/PlotLine/wwwroot/js/shared-manuscript-focus.js +++ b/PlotLine/wwwroot/js/shared-manuscript-focus.js @@ -1,7 +1,7 @@ // One user/book/canonical-manuscript focus stream over the window's existing presence connection. (()=>{'use strict';function start(){const context=document.querySelector('[data-context-workspace]'),header=document.querySelector('[data-narrative-focus]'),reader=document.querySelector('.manuscript-reader');if(!context&&!header)return;const initial=window.PlotDirectorNarrativeFocus?.state||(header?JSON.parse(header.querySelector('[data-narrative-initial]').textContent):{});let project=Number(context?.dataset.scopeProjectId||initial.projectID),book=Number(context?.dataset.scopeBookId||initial.bookID),connection,connected=false,authoritative=false,readFlight=null,readAbort=null,readyKey=null,generation=0,disconnected=false,latest=null,local=null,epoch=0,sequence=0,held=false,publishing=false,selectionPublishing=false,queuedTarget=null,heldRecent=null;const user=document.body.dataset.pdUserId||context?.dataset.user||'',page=crypto.randomUUID(),buttons=[...document.querySelectorAll('[data-shared-focus-hold]')],outputs=[...document.querySelectorAll('[data-shared-focus-status]')];let id=context?.contextController?.windowId||sessionStorage.getItem('pd.shared-focus.window');if(!/^[\da-f-]{36}$/i.test(id||''))id=crypto.randomUUID();sessionStorage.setItem('pd.shared-focus.window',id);const normal=p=>({projectID:Number(p.projectID||p.projectId||project),bookID:Number(p.bookID||p.bookId||book),chapterID:Number(p.chapterID||p.chapterId)||null,sceneID:Number(p.sceneID||p.sceneId)||null,paragraphID:p.paragraphID||p.paragraphId||null,manuscriptID:p.manuscriptID||p.manuscriptId||null,originWindowID:p.originWindowID||p.originWindowId||null,version:Number(p.version||0),isValid:p.isValid!==false});const key=()=>`pd.shared-focus.${user}.${id}`;const positionKey=p=>p&&[p.projectID,p.bookID,p.manuscriptID,p.chapterID,p.sceneID,p.paragraphID].join('/');function save(){try{sessionStorage.setItem(key(),JSON.stringify({held,local,sequence,heldRecent}));}catch{}}function restore(){try{const data=JSON.parse(sessionStorage.getItem(key())||'null');held=data?.held??context?.dataset.followMode==='snapshot';local=data?.local||normal(context?.contextController?.position||{...initial,chapterID:Number(reader?.dataset.chapterId)||initial.chapterID});sequence=data?.sequence||0;heldRecent=data?.heldRecent||null;}catch{held=false;}} const traceEnabled=new URLSearchParams(location.search).get('focusDiagnostics')==='1',traceRows=[];function trace(stage,outcome,p=latest){if(!traceEnabled)return;traceRows.push({stage,outcome,source:context?'Context':'Review',windowID:id,bookID:book,chapterID:p?.chapterID,sceneID:p?.sceneID,paragraphID:p?.paragraphID,version:p?.version,held});if(traceRows.length>128)traceRows.shift();let panel=document.querySelector('[data-focus-diagnostics]');if(!panel){panel=document.createElement('pre');panel.dataset.focusDiagnostics='';document.body.append(panel);}panel.textContent=JSON.stringify(traceRows,null,2);} -let lastNotice='';function status(message=''){const available=!!book&&connected&&authoritative&&!disconnected;buttons.forEach(b=>{(b.querySelector('span')||b).textContent=held?'Resume':'Hold';const icon=b.querySelector('[data-focus-mode-icon]');if(icon)icon.setAttribute('d',held?'M8 4l12 8-12 8z':'M8 4v16 M16 4v16');b.setAttribute('aria-pressed',String(held));b.disabled=!available;b.classList.toggle('active',held);b.title=!available?(book?'Shared focus is connecting. Your local position is retained.':'Select a book first.'):(held?'Catch up to the latest shared manuscript position.':'Hold this window at its local manuscript position.');});outputs.forEach(n=>{n.textContent=message;n.hidden=!message;});document.documentElement.dataset.manuscriptFocusMode=held?'held':'follow';if(message&&message!==lastNotice){lastNotice=message;window.PlotDirector?.toast?.warning?.(message);}if(!message)lastNotice='';}function apply(position,reason){local=normal(position);save();trace('reconcile',reason,local);window.dispatchEvent(new CustomEvent('plotdirector:shared-focus',{detail:{position:local,reason}}));status();}function accept(packet,force=false,metadata=false){const next=normal(packet);if(next.bookID!==book||next.projectID!==project)return false;if(latest&&next.version{(b.querySelector('span')||b).textContent=held?(b.dataset.focusHeldLabel||'Resume'):'Hold';const icon=b.querySelector('[data-focus-mode-icon]');if(icon)icon.setAttribute('d',held?'M8 4l12 8-12 8z':'M8 4v16 M16 4v16');b.setAttribute('aria-pressed',String(held));b.disabled=!available;b.classList.toggle('active',held);b.title=!available?(book?'Shared focus is connecting. Your local position is retained.':'Select a book first.'):(held?'Catch up to the latest shared manuscript position.':'Hold this window at its local manuscript position.');});outputs.forEach(n=>{n.textContent=message;n.hidden=!message;});document.documentElement.dataset.manuscriptFocusMode=held?'held':'follow';if(message&&message!==lastNotice){lastNotice=message;window.PlotDirector?.toast?.warning?.(message);}if(!message)lastNotice='';}function apply(position,reason){local=normal(position);save();trace('reconcile',reason,local);window.dispatchEvent(new CustomEvent('plotdirector:shared-focus',{detail:{position:local,reason}}));status();}function accept(packet,force=false,metadata=false){const next=normal(packet);if(next.bookID!==book||next.projectID!==project)return false;if(latest&&next.versionnull);if(!response.ok||response.redirected)throw Error(packet?.message||'Focus could not be changed. Your local reference is retained.');return normal(packet);} function invalidateRead(){epoch++;generation++;readAbort?.abort();readAbort=null;readFlight=null;authoritative=false;} function refresh(force=false){if(!book||!connected)return Promise.resolve(false);if(readFlight)return readFlight;const mine=++epoch,scope=book,transport=generation;readAbort=new AbortController();const signal=readAbort.signal;trace('read','started');const task=(async()=>{try{const response=await fetch(`/NarrativeFocus/Shared?projectID=${project}&bookID=${book}`,{cache:'no-store',signal});if(!response.ok||response.redirected)throw Error();const packet=await response.json();if(mine!==epoch||scope!==book||transport!==generation)return false;const recovering=disconnected;disconnected=false;authoritative=true;accept(packet,force,true);status(!held&&latest?.isValid===false?'Shared focus is unavailable. Select another position; your local reference is retained.':'');trace('read','reconciled');if(recovering)void validateLocal();return true;}catch(error){if(signal.aborted)return false;if(mine===epoch){disconnected=true;status('Shared focus disconnected. Your local position is retained.');trace('read','failed');}return false;}finally{if(readFlight===task){readFlight=null;readAbort=null;}}})();readFlight=task;return task;}