diff --git a/Docs/Writer/Shared-Focus-Ribbon-Refinement-20261123.md b/Docs/Writer/Shared-Focus-Ribbon-Refinement-20261123.md
new file mode 100644
index 00000000..e4ac35d5
--- /dev/null
+++ b/Docs/Writer/Shared-Focus-Ribbon-Refinement-20261123.md
@@ -0,0 +1,36 @@
+# Shared focus ribbon and navigation refinement — 23 November 2026
+
+Development-only implementation following Windows .47 source `cfcd40b5b9175f26ca1ab1de0d1fdfbcfe4147f5` and handover `de083c5d87ce251405c6f16d8730f0d245695a90`.
+
+## Audit and implementation
+
+Reused the shared manuscript focus controller, existing SignalR transport, canonical positions, navigation adapters, Hold/Resume implementation and persisted user/book recent-focus history. No database migration, competing controller or history service was needed.
+
+The main Focus group now contains **Previous | Hold/Resume | Next | History**, with the established ribbon separator. Previous/Next retain narrative ordering, chapter boundaries and endpoint disabling. Hold uses pause; Resume uses play. One fixed-size button retains the existing availability gate. The main Go to Focus control and its presentation wiring were removed; reusable navigation and Context's separate controls remain available.
+
+The header selector now displays ordered, expandable chapters and their scenes, including genuine chapter-only targets. Search and the old scene/recent selectors were removed. Current selection, arrow/Home/End navigation, Escape, successful-selection dismissal and focus restoration are supported. Both menus are scroll bounded and viewport constrained. Essential Focus controls remain visible in the existing compact ribbon system.
+
+History reuses the existing server-backed 20-position store. Meaningful published visits from all clients reorder/deduplicate by chapter/scene; refreshing and reconnecting do not publish visits. Current and invalid targets are excluded. History selection uses existing navigation, independently of Previous/Next. Scope stays within the authorised current book.
+
+A bounded held-history snapshot/local-visit overlay is saved inside the existing per-window shared-focus session record. It freezes incoming visits while held, records accepted local navigation, survives refresh and preserves those local visits after Resume. Subsequent published visits lead that retained list. Resume itself retains established catch-up semantics and does not publish a new focus. Canonical persisted history survives reopening; per-window held history survives where Chromium restores the existing session. No new storage key/table or polling loop was introduced. Restored held header presentation now uses the actual local position even when the shared controller starts before the header presenter.
+
+## Open in Word audit
+
+All three Chapter, Scene and Paragraph actions are retained under **Word caret**. The explicit Writer Word navigation path queues native navigation whose Word implementation selects the target range (`range.Select()`). Shared-focus navigation scrolls using `Window.ScrollIntoView`, preserving the caret. These remain distinct useful actions; labels/tooltips clarify their purpose. Windows/VSTO/installer source is unchanged.
+
+Removed the persistent Chapter verified ribbon label and its presentation update. Verification, connection handling, actionable warnings and body diagnostics remain operational. No status text was added beside Hold/Resume.
+
+## Verification before deployment
+
+- Solution build: zero warnings/errors.
+- Full executable regression harness: 797 passing checks.
+- Existing shared-focus reliability browser checks: pass, including unavailable/disconnected gates and genuine disabled states.
+- Existing real shared-focus multi-window browser suite: pass, including Review/Context propagation, independent Hold, reconnect/refresh and live relationship/graph data updates while held.
+- New `PlotLine.Tests/Browser/focus-ribbon-refinement.cjs`: pass in normal Chromium and installed Chromium standalone PWA. Covers navigation/history ordering, chapter-only targets, current exclusion, deduplication, invalid targets, refresh/reconnect, held local history and Resume, mouse/keyboard/Escape/focus restoration, 200-chapter menus, dark theme, widths 1500/1000/650/390, bounded dropdowns and stable Hold dimensions.
+- Existing reliability runner defaults to bundled Chromium, with optional `PD_BROWSER_CHANNEL`, allowing execution on Atlas without a system Google Chrome installation.
+
+Tests use a disposable authorised Development fixture; no real manuscript is edited. Physical Microsoft Word is unavailable on Linux. Supported shared-focus fixtures cover the protocol; manual Windows .47 acceptance remains required: Word-originated focus, explicit caret movement at chapter/scene/paragraph, shared scroll preserving caret, independent Hold/Resume and catch-up across Word/Review/Context.
+
+## Release evidence
+
+Implementation commit, remote push, Development deployment and post-deployment acceptance are recorded below after installation. Production is outside this task.
diff --git a/PlotLine.Tests/Browser/focus-ribbon-refinement.cjs b/PlotLine.Tests/Browser/focus-ribbon-refinement.cjs
new file mode 100644
index 00000000..9cdb480d
--- /dev/null
+++ b/PlotLine.Tests/Browser/focus-ribbon-refinement.cjs
@@ -0,0 +1,25 @@
+// Real auth/controllers/SQL/SignalR, disposable fixture only. No physical Word claim.
+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',installed=process.argv.includes('--installed');
+(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);const profile=installed?fs.mkdtempSync('/tmp/pd-focus-refinement-'):null,persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1500,height:1000}}):null,browser=persistent?.browser()||await chromium.launch();let step='login';const errors=[];
+try{const c=persistent||await browser.newContext({viewport:{width:1500,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')}));await c.addInitScript(user=>{try{localStorage.setItem('plotdirector.desktop.v1.'+user,JSON.stringify({dismissedAt:Date.now()}));}catch{}},who.UserID);
+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()]);let desktop;if(installed){await login.goto(`${base}/Projects/Details/${s.project}`);desktop=await browser.newBrowserCDPSession();await desktop.send('PWA.install',{manifestId:base+'/Projects',installUrlOrBundleUrl:`${base}/Projects/Details/${s.project}`});await desktop.send('PWA.changeAppUserSettings',{manifestId:base+'/Projects',displayMode:'standalone'});}
+async function surface(url){if(!installed){const p=await c.newPage();await p.goto(url);return p;}const opened=c.waitForEvent('page');await desktop.send('PWA.launch',{manifestId:base+'/Projects',url});const p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));return p;}
+const p=await surface(`${base}/Writer/Review?projectId=${s.project}&bookId=${s.book}&chapterId=${s.chapter1}`),active='.pd-ribbon-panel:not([hidden]) .pd-ribbon-focus';await p.waitForFunction(()=>window.PlotDirectorSharedFocus);
+const state=()=>p.evaluate(()=>PlotDirectorNarrativeFocus.state),shared=()=>p.evaluate(()=>PlotDirectorSharedFocus.shared),waitScene=id=>p.waitForFunction(id=>PlotDirectorNarrativeFocus.state.sceneID===id,id);
+const read=()=>p.evaluate(async url=>{const response=await fetch(url,{cache:'no-store'});if(!response.ok||response.redirected)throw Error('Authenticated history read failed');return response.json();},`${base}/NarrativeFocus/Read?projectId=${s.project}&bookId=${s.book}`);
+async function choose(chapter,scene=null){if(await p.locator('[data-focus-toggle]').getAttribute('aria-expanded')!=='true')await p.click('[data-focus-toggle]');const expand=p.locator(`[data-focus-expand="${chapter}"]`);if(scene&&await expand.getAttribute('aria-expanded')!=='true')await expand.click();await p.locator(`[data-focus-target="${chapter}/${scene||''}"]`).click();await p.waitForFunction(t=>PlotDirectorNarrativeFocus.state.chapterID===t.chapter&&PlotDirectorNarrativeFocus.state.sceneID===t.scene,{chapter,scene});await p.waitForFunction(()=>document.querySelector('[data-focus-toggle]').getAttribute('aria-expanded')==='false');assert.equal(await p.evaluate(()=>document.activeElement.hasAttribute('data-focus-toggle')),true,'successful hierarchy selection restores header focus');}
+async function history(){const toggle=p.locator(active+' [data-focus-history-toggle]');if(await toggle.getAttribute('aria-expanded')!=='true')await toggle.click();await p.waitForTimeout(170);return p.locator(active+' [data-focus-history-target]').evaluateAll(nodes=>nodes.map(n=>n.dataset.focusHistoryTarget));}
+const closeHistory=async()=>{if(await p.locator(active+' [data-focus-history-toggle]').getAttribute('aria-expanded')==='true')await p.locator(active+' [data-focus-history-toggle]').press('Escape');};
+step='static ribbon and hierarchy';assert.equal(await p.locator('[data-global-focus=go],[data-focus-search],[data-focus-recent],[data-focus-position],[data-word-ribbon-status]').count(),0);assert.deepEqual(await p.locator(active+' .pd-ribbon-commands').evaluate(row=>[...row.children].map(n=>n.matches('[data-global-focus]')?n.dataset.globalFocus:n.matches('[data-shared-focus-hold]')?'hold':n.matches('.pd-focus-history')?'history':'unknown')),['previous','hold','next','history']);assert.equal(await p.locator(active+' [data-shared-focus-status]').count(),0);assert.equal(await p.locator('[data-ribbon-word]').count(),3,'distinct Word caret actions retained');
+await choose(s.chapter1,s.scene1);assert(await p.locator(active+' [data-global-focus=previous]').isDisabled());await choose(s.chapter1,s.scene2);await choose(s.chapter2,s.scene3);await p.waitForFunction(()=>PlotDirectorSharedFocus.held===false);
+const b=await surface(`${base}/Writing/Context?projectId=${s.project}&bookId=${s.book}&sceneId=${s.scene1}`);await b.waitForFunction(s=>document.querySelector('[data-context-workspace]')?.contextController.position.sceneId===s.scene3,s);
+step='history separated from narrative order';let items=await history();assert.equal(items[0],`${s.chapter1}/${s.scene2}`);assert(items.includes(`${s.chapter1}/${s.scene1}`));assert(!items.includes(`${s.chapter2}/${s.scene3}`));await p.locator(active+` [data-focus-history-target="${s.chapter1}/${s.scene1}"]`).click();await waitScene(s.scene1);await p.locator(active+' [data-global-focus=next]').click();await waitScene(s.scene2);await p.waitForFunction(()=>document.querySelector('.pd-ribbon-panel:not([hidden]) [data-global-focus=previous]').disabled===false);await p.locator(active+' [data-global-focus=previous]').click();await waitScene(s.scene1);await choose(s.chapter2,s.scene3);
+const last=await p.evaluate(()=>PlotDirectorNarrativeFocus.state.positions.filter(x=>x.sceneID).at(-1));await choose(last.chapterID,last.sceneID);assert(await p.locator(active+' [data-global-focus=next]').isDisabled());await choose(s.chapter2,s.scene3);
+step='refresh/reconnect do not duplicate visits';const before=await read();await p.reload();await p.waitForFunction(()=>PlotDirectorSharedFocus?.shared?.chapterID);await p.evaluate(async()=>{const c=PlotDirectorPresenceConnection;await c.stop();await c.start();document.dispatchEvent(new Event('pd-presence-ready'));await PlotDirectorSharedFocus.refresh();});assert.deepEqual((await read()).recent,before.recent);await p.waitForFunction(()=>!document.querySelector('.pd-ribbon-panel:not([hidden]) [data-shared-focus-hold]').disabled);
+step='Held history isolates remote visits and retains local visits';await p.locator(active+' [data-shared-focus-hold]').click();assert.equal(await p.locator(active+' [data-shared-focus-hold] span').textContent(),'Resume');assert.match(await p.locator(active+' [data-focus-mode-icon]').getAttribute('d'),/l12 8/);const frozen=await history();await closeHistory();await b.selectOption('[data-context-scene]',String(s.scene1));await b.waitForFunction(s=>PlotDirectorSharedFocus.shared.sceneID===s.scene1,s);await b.selectOption('[data-context-scene]',String(s.scene2));await b.waitForFunction(s=>PlotDirectorSharedFocus.shared.sceneID===s.scene2,s);await p.waitForFunction(s=>PlotDirectorSharedFocus.shared.sceneID===s.scene2,s);await waitScene(s.scene3);assert.deepEqual(await history(),frozen);await closeHistory();const remote=(await read());await choose(s.emptyChapter);await choose(s.chapter1,s.scene1);assert.deepEqual((await read()).recent,remote.recent);items=await history();assert.equal(items[0],`${s.emptyChapter}/`);await closeHistory();await p.reload();await p.waitForFunction(()=>PlotDirectorSharedFocus?.held);await waitScene(s.scene1);assert((await history()).includes(`${s.chapter2}/${s.scene3}`));await closeHistory();await p.locator(active+' [data-shared-focus-hold]').click();await waitScene(s.scene2);assert.equal((await shared()).version,remote.version);assert.equal(await p.locator(active+' [data-shared-focus-hold] span').textContent(),'Hold');assert((await history()).includes(`${s.emptyChapter}/`),'a local held visit remains available after Resume');await closeHistory();
+step='keyboard history';await closeHistory();await p.locator(active+' [data-focus-history-toggle]').press('ArrowDown');await p.waitForTimeout(250);const keyboardTarget=await p.evaluate(()=>document.activeElement.dataset.focusHistoryTarget);assert(keyboardTarget,'history retains keyboard focus after metadata refresh');await p.keyboard.press('Enter');await waitScene(Number(keyboardTarget.split('/')[1]));await p.waitForFunction(()=>document.querySelector('.pd-ribbon-panel:not([hidden]) [data-focus-history-toggle]').getAttribute('aria-expanded')==='false');assert.equal(await p.evaluate(()=>document.activeElement.hasAttribute('data-focus-history-toggle')),true);step='chapter-only and keyboard hierarchy';await choose(s.emptyChapter);assert.equal((await state()).sceneID,null);await p.click('[data-focus-toggle]');const chapter=p.locator(`[data-focus-target="${s.chapter1}/"]`);await chapter.focus();await chapter.press('ArrowRight');assert.equal(await p.locator(`[data-focus-expand="${s.chapter1}"]`).getAttribute('aria-expanded'),'true');await chapter.press('ArrowDown');assert.equal(await p.evaluate(()=>document.activeElement.dataset.focusTarget),`${s.chapter1}/${s.scene1}`);await p.keyboard.press('Enter');await waitScene(s.scene1);await p.click('[data-focus-toggle]');await p.keyboard.press('Escape');assert.equal(await p.evaluate(()=>document.activeElement.hasAttribute('data-focus-toggle')),true);
+step='responsive dark layout, bounded dropdowns and fixed Hold geometry';for(const width of [1500,1000,650,390]){await p.setViewportSize({width,height:900});await p.evaluate(()=>window.PlotDirectorApplyApplicationTheme?.('modern-dark'));await p.locator(active+' [data-focus-history-toggle]').click();await p.waitForTimeout(120);const box=await p.locator(active+' .pd-focus-history-menu').boundingBox();assert(box&&box.x>=-1&&box.x+box.width<=width+1&&box.y+box.height<=901,'history bounds at '+width);await closeHistory();await p.click('[data-focus-toggle]');const picker=await p.locator('.pd-focus-picker').boundingBox();assert(picker.x>=-1&&picker.x+picker.width<=width+1&&picker.y+picker.height<=901);await p.keyboard.press('Escape');assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}
+step='long manuscript hierarchy stays scrollable';const catalog=await read();await p.route('**/NarrativeFocus/Read?*',route=>route.fulfill({json:{...catalog,recent:[...catalog.recent,...catalog.recent,{chapterID:999999,sceneID:999999,sequence:999999}],positions:[...catalog.positions,...Array.from({length:200},(_,i)=>({chapterID:800000+i,chapterNumber:i+100,chapterTitle:'Long synthetic chapter '+('title '.repeat(25)),sceneID:null}))]}}));await p.click('[data-focus-toggle]');await p.waitForTimeout(250);assert(await p.locator('[data-focus-hierarchy]').evaluate(n=>n.scrollHeight>n.clientHeight&&n.clientHeight<600));await p.keyboard.press('Escape');const filtered=await history();assert.equal(new Set(filtered).size,filtered.length);assert(!filtered.includes('999999/999999'),'unresolvable history is never a valid target');await closeHistory();await p.unroute('**/NarrativeFocus/Read?*');await p.setViewportSize({width:1500,height:1000});await p.screenshot({path:`/tmp/focus-refinement-${installed?'pwa':'browser'}.png`});const bounds=await p.locator(active).boundingBox();await p.locator(active+' [data-shared-focus-hold]').click();const heldBounds=await p.locator(active).boundingBox();assert.equal(bounds.width,heldBounds.width);assert.equal(bounds.height,heldBounds.height);await p.locator(active+' [data-shared-focus-hold]').click();
+assert.deepEqual(errors,[]);console.log('PASS real focus ribbon refinement '+(installed?'installed PWA':'browser')+': ordered controls, chapter hierarchy, keyboard/Escape, canonical Previous/Next, server history/reorder/dedupe, refresh/reconnect, independent held history/local visits, Resume without publication, Word caret controls, dark responsive bounded menus and stable Hold size.');
+}catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await persistent?.close();await browser.close();if(profile)fs.rmSync(profile,{recursive:true,force:true});}})();
diff --git a/PlotLine.Tests/Browser/shared-focus-reliability.cjs b/PlotLine.Tests/Browser/shared-focus-reliability.cjs
index 2ba74463..19cf3a34 100644
--- a/PlotLine.Tests/Browser/shared-focus-reliability.cjs
+++ b/PlotLine.Tests/Browser/shared-focus-reliability.cjs
@@ -1,17 +1,17 @@
// Isolated production asset; deterministic transport/read ordering, no account or manuscript.
const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');
const script=fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/shared-manuscript-focus.js'),'utf8');
-(async()=>{const browser=await chromium.launch({channel:'chrome'});try{
+(async()=>{const browser=await chromium.launch(process.env.PD_BROWSER_CHANNEL?{channel:process.env.PD_BROWSER_CHANNEL}:{});try{
const page=await browser.newPage();await page.route('https://fixture.invalid/**',r=>r.fulfill({body:'
',contentType:'text/html'}));await page.goto('https://fixture.invalid/');
await page.evaluate(()=>{window.reads=[];window.posts=[];window.moves=[];window.notices=[];window.PlotDirector={toast:{warning:m=>notices.push(m)}};window.addEventListener('plotdirector:shared-focus',e=>moves.push(e.detail));window.fetch=(url,options={})=>{if(options.method==='POST'){posts.push({url,body:String(options.body)});return Promise.resolve({ok:true,json:async()=>({...fixture,version:10})});}return new Promise(resolve=>reads.push({resolve,signal:options.signal}));};window.handlers={};window.lifecycle={};window.fixture={projectID:3,bookID:12,chapterID:1,sceneID:10,version:1,isValid:true};window.conn={state:'Disconnected',connectionId:null,on:(n,f)=>handlers[n]=f,onreconnecting:f=>lifecycle.reconnecting=f,onclose:f=>lifecycle.close=f,onreconnected:f=>lifecycle.reconnected=f};window.PlotDirectorPresenceConnection=conn;window.respond=(i,p)=>reads[i].resolve({ok:true,json:async()=>({...fixture,...p})});});
await page.addScriptTag({content:script});
assert.equal(await page.evaluate(()=>reads.length),0,'no authoritative read before group join');assert.equal(await page.getByRole('button',{name:'Hold',exact:true}).isEnabled(),false);
await page.evaluate(()=>{conn.state='Connected';conn.connectionId='first';document.dispatchEvent(new Event('pd-presence-ready'));document.dispatchEvent(new Event('pd-presence-ready'));});assert.equal(await page.evaluate(()=>reads.length),1,'first ready rereads once');
await page.evaluate(()=>{handlers.ManuscriptFocusChanged({...fixture,version:3,sceneID:30});respond(0,{version:2,sceneID:20});});await page.waitForFunction(()=>PlotDirectorSharedFocus.shared?.version===3&&document.querySelector('button').disabled===false);assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.local.sceneID),30,'late startup snapshot cannot overwrite notification');console.log('PASS initial connection race, coalescing and revision reconciliation');
- await page.getByRole('button',{name:'Hold',exact:true}).click();assert.equal(await page.getByRole('button',{name:'Release Hold',exact:true}).getAttribute('aria-pressed'),'true');const moves=await page.evaluate(()=>window.moves.length);
- await page.evaluate(()=>{conn.state='Reconnecting';lifecycle.reconnecting();});assert.equal(await page.getByRole('button',{name:'Release Hold',exact:true}).isEnabled(),false);
+ await page.getByRole('button',{name:'Hold',exact:true}).click();assert.equal(await page.getByRole('button',{name:'Resume',exact:true}).getAttribute('aria-pressed'),'true');const moves=await page.evaluate(()=>window.moves.length);
+ await page.evaluate(()=>{conn.state='Reconnecting';lifecycle.reconnecting();});assert.equal(await page.getByRole('button',{name:'Resume',exact:true}).isEnabled(),false);
await page.evaluate(()=>{conn.state='Connected';conn.connectionId='second';lifecycle.reconnected();document.dispatchEvent(new Event('pd-presence-ready'));respond(1,{version:4,sceneID:40});});await page.waitForFunction(()=>PlotDirectorSharedFocus.shared?.version===4&&document.querySelector('button').disabled===false);assert.equal(await page.evaluate(()=>window.moves.length),moves,'held recovery must retain local position');assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.local.sceneID),30);
- await page.getByRole('button',{name:'Release Hold',exact:true}).press('Enter');await page.waitForFunction(()=>reads.length===3);await page.evaluate(()=>respond(2,{version:5,sceneID:50}));await page.waitForFunction(()=>PlotDirectorSharedFocus.local.sceneID===50&&!PlotDirectorSharedFocus.held);assert.equal(await page.evaluate(()=>posts.length),1,'only held reference validation posts; release cannot publish');assert(await page.evaluate(()=>posts.every(p=>!p.url.endsWith('/Publish'))));assert.equal(await page.getByRole('button',{name:'Hold',exact:true}).getAttribute('aria-pressed'),'false');console.log('PASS reconnect preserves Hold; keyboard Release catches latest without publication');
+ await page.getByRole('button',{name:'Resume',exact:true}).press('Enter');await page.waitForFunction(()=>reads.length===3);await page.evaluate(()=>respond(2,{version:5,sceneID:50}));await page.waitForFunction(()=>PlotDirectorSharedFocus.local.sceneID===50&&!PlotDirectorSharedFocus.held);assert.equal(await page.evaluate(()=>posts.length),1,'only held reference validation posts; release cannot publish');assert(await page.evaluate(()=>posts.every(p=>!p.url.endsWith('/Publish'))));assert.equal(await page.getByRole('button',{name:'Hold',exact:true}).getAttribute('aria-pressed'),'false');console.log('PASS reconnect preserves Hold; keyboard Release catches latest without publication');
await page.evaluate(()=>{void PlotDirectorSharedFocus.refresh();conn.state='Reconnecting';lifecycle.reconnecting();conn.state='Connected';conn.connectionId='third';lifecycle.reconnected();respond(3,{version:99,sceneID:99});respond(4,{version:6,sceneID:60});});await page.waitForFunction(()=>PlotDirectorSharedFocus.shared?.version===6);assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.local.sceneID),60,'abandoned transport cannot overwrite new connection');console.log('PASS disconnected read cancellation and new group recovery');
const partial=fs.readFileSync(path.join(__dirname,'../../PlotLine/Views/Shared/_FocusFollowControl.cshtml'),'utf8');assert(!partial.includes('data-shared-focus-status'));assert(!partial.includes('Following'));assert(partial.includes('disabled'));const ribbon=fs.readFileSync(path.join(__dirname,'../../PlotDirector.NativeCompanion/Vsto/Ribbon.xml'),'utf8');assert(!ribbon.includes('PlotDirectorFocusState'));assert(ribbon.includes('getEnabled="CanHoldFocus"'));console.log('PASS concise accessible toggle and no adjacent state controls');
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});
diff --git a/PlotLine/Views/Shared/_ApplicationShell.cshtml b/PlotLine/Views/Shared/_ApplicationShell.cshtml
index d8e4ef62..c7198bf9 100644
--- a/PlotLine/Views/Shared/_ApplicationShell.cshtml
+++ b/PlotLine/Views/Shared/_ApplicationShell.cshtml
@@ -170,12 +170,12 @@
}
@if(category.Key==selectedCategory && book!=null && category.Key is "writer" or "book" or "story"){
-
+
@foreach(var target in new[]{("chapter","Chapter","bible"),("scene","Scene","threads"),("paragraph","Paragraph","point")}){
var destination = "word";
- var tooltip = $"Open current {target.Item1} in Microsoft Word.";
+ var tooltip = $"Move the Word caret to the current {target.Item1}. Shared focus follows the view without moving the caret.";
- }
Open in Word
+ }
Word caret
}
@if (category.Key == selectedCategory)
{
diff --git a/PlotLine/Views/Shared/_FocusFollowControl.cshtml b/PlotLine/Views/Shared/_FocusFollowControl.cshtml
index d7526723..3196527f 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/Shared/_FocusRibbon.cshtml b/PlotLine/Views/Shared/_FocusRibbon.cshtml
index 00affbb5..18fadb0f 100644
--- a/PlotLine/Views/Shared/_FocusRibbon.cshtml
+++ b/PlotLine/Views/Shared/_FocusRibbon.cshtml
@@ -1,9 +1,12 @@
-@* One shared global navigation group; workspace adapters only control Go to Focus. *@
+@* Scene order and recent visits share the existing narrative focus controller. *@
-
- @foreach(var command in new[]{("previous","Previous","chevron-left","Previous scene in manuscript order"),("go","Go to Focus","focus","Display Current Focus in this workspace"),("next","Next","chevron-right","Next scene in manuscript order")}){
-
- }
+
+
+
+
Current narrative location. Saved objectives and local Scene Explorers keep their own targets.
-
-
-
+
@Html.AntiForgeryToken()
diff --git a/PlotLine/wwwroot/css/application-shell.css b/PlotLine/wwwroot/css/application-shell.css
index 1f4583a4..304bf8cc 100644
--- a/PlotLine/wwwroot/css/application-shell.css
+++ b/PlotLine/wwwroot/css/application-shell.css
@@ -857,12 +857,21 @@ html[data-app-theme] .scenario-workspace :is(h1, h2, h3) {
}
.scenario-workspace .attention-list p { grid-column: 1 / -1; }
.scenario-workspace .scenario-warning-badge { justify-self: start; }
-/* Static focus commands reserve their width in both modes; no delayed ribbon insertion. */
-.pd-shell [data-shared-focus-hold]{width:120px;min-width:120px;max-width:120px}
-[data-context-workspace] [data-shared-focus-hold]{width:120px;min-width:120px;max-width:120px}
+/* Stable primary focus commands; diagnostics remain outside the ribbon. */
+.pd-shell .pd-ribbon-focus [data-shared-focus-hold]{width:64px;min-width:64px;max-width:64px}
+[data-context-workspace] [data-shared-focus-hold]{width:100px;min-width:100px}
+.pd-shell .pd-ribbon-focus{border-left:1px solid var(--pd-border-subtle)}
+.pd-focus-picker{min-width:min(430px,calc(100vw - 24px));max-width:calc(100vw - 24px)}
+.pd-focus-hierarchy,.pd-focus-scenes{list-style:none;margin:0;padding:0}
+.pd-focus-hierarchy{max-height:min(60vh,440px);overflow:auto;overscroll-behavior:contain}
+.pd-focus-chapter-row{display:flex;align-items:center}
+.pd-focus-expand{border:0;background:transparent;color:var(--pd-text);flex:0 0 30px;padding:7px}
+.pd-focus-chapter-row>.dropdown-item{white-space:normal;flex:1;min-width:0;font-weight:600}
+.pd-focus-scenes .dropdown-item{white-space:normal;padding-left:40px}
+.pd-focus-hierarchy [aria-current=location]{background:var(--pd-selected);font-weight:650}
+.pd-focus-hierarchy button:focus-visible,.pd-focus-history-menu button:focus-visible{outline:2px solid var(--pd-accent);outline-offset:-2px}
+.pd-focus-history-menu{width:min(390px,calc(100vw - 24px));max-height:min(60vh,440px);overflow:auto;overscroll-behavior:contain}
+.pd-focus-history-menu .dropdown-item{white-space:normal}
+.pd-focus-empty{padding:10px 14px;color:var(--pd-muted);font-size:13px}
-/* Hold remains visible when the PWA compacts Previous/Go/Next into its existing menu. */
-.pd-shell .pd-ribbon-focus{display:grid;grid-template-columns:auto auto;grid-template-rows:1fr auto;column-gap:4px}
-.pd-ribbon-focus-mode{grid-column:1;grid-row:1;display:flex;align-items:flex-start;gap:4px}
-.pd-ribbon-focus>.pd-ribbon-commands,.pd-ribbon-focus>.pd-base-overflow{grid-column:2;grid-row:1}
-.pd-ribbon-focus>.pd-ribbon-group-label{grid-column:1/-1;grid-row:2}
+.pd-focus-hierarchy .dropdown-item,.pd-focus-history-menu .dropdown-item{overflow-wrap:anywhere}
diff --git a/PlotLine/wwwroot/js/application-page-context.js b/PlotLine/wwwroot/js/application-page-context.js
index 7a1935bf..c893e7d3 100644
--- a/PlotLine/wwwroot/js/application-page-context.js
+++ b/PlotLine/wwwroot/js/application-page-context.js
@@ -117,6 +117,7 @@
const row = group.querySelector(':scope > .pd-ribbon-commands');
const label = group.querySelector('.pd-ribbon-group-label').textContent.trim();
const details = make('details', 'pd-context-menu pd-base-overflow');
+ if(group.classList.contains('pd-ribbon-focus'))details.dataset.essential='true';
details.dataset.compact = 'false'; details.dataset.priority = String(-10 + index); details.open = true;
const summary = make('summary', 'pd-ribbon-command');
const svg = row.querySelector('svg')?.cloneNode(true); if (svg) summary.append(svg);
diff --git a/PlotLine/wwwroot/js/narrative-focus-review.js b/PlotLine/wwwroot/js/narrative-focus-review.js
index 1ee62587..10fa8ce5 100644
--- a/PlotLine/wwwroot/js/narrative-focus-review.js
+++ b/PlotLine/wwwroot/js/narrative-focus-review.js
@@ -32,7 +32,7 @@
reader=columns.querySelector('.manuscript-reader');reader._focusFilters=filters;
}
const target=reader.readerResolveFocus?.(focus);if(!target)throw Error('Current Focus is unavailable in the displayed accepted chapter.');
- if(window.PlotDirectorSharedFocus?.held&&(focus.paragraphID||focus.sceneID)&&!target.precise){notice.hidden=false;notice.textContent='The held reference no longer has a precise accepted passage. Your current view is retained. Select another local reference or Release Hold.';return;}
+ if(window.PlotDirectorSharedFocus?.held&&(focus.paragraphID||focus.sceneID)&&!target.precise){notice.hidden=false;notice.textContent='The held reference no longer has a precise accepted passage. Your current view is retained. Select another local reference or Resume.';return;}
await document.querySelector('[data-writer-review]')?.selectNarrativeParagraph?.(target.paragraph?.dataset.paragraphId||null);
if(mine!==generation||!same(focus,current())||!canChange())return;
for(const [name,value]of reader._focusFilters||[]){const select=columns.querySelector(`[data-annotation-filter="${name}"]`);if(select){select.value=value;select.dispatchEvent(new Event('change',{bubbles:true}));}}delete reader._focusFilters;
diff --git a/PlotLine/wwwroot/js/narrative-focus.js b/PlotLine/wwwroot/js/narrative-focus.js
index b1f6ada8..df5067fd 100644
--- a/PlotLine/wwwroot/js/narrative-focus.js
+++ b/PlotLine/wwwroot/js/narrative-focus.js
@@ -1,66 +1,101 @@
-// The only browser commit path for current narrative context. Local explorers never call it implicitly.
+// Presentation for the existing canonical focus controller and its bounded recent-focus history.
(() => {
'use strict';
const root=document.querySelector('[data-narrative-focus]');if(!root)return;
- let state=JSON.parse(root.querySelector('[data-narrative-initial]').textContent),busy=false,epoch=0,refreshQueued=false;
- const select=root.querySelector('[data-focus-position]'),recent=root.querySelector('[data-focus-recent]'),search=root.querySelector('[data-focus-search]'),status=root.querySelector('[data-narrative-status]');
- const bookPicker=root.querySelector('[data-focus-book]'),toggle=root.querySelector('[data-focus-toggle]');
- const dismiss=(restore=false)=>{restore=restore===true||root.querySelector('.pd-focus-picker').contains(document.activeElement);bootstrap.Dropdown.getOrCreateInstance(toggle).hide();if(restore)toggle.focus({preventScroll:true});};
+ let state=JSON.parse(root.querySelector('[data-narrative-initial]').textContent),busy=false,epoch=0,refreshQueued=false,metadataFlight=null,metadataUnavailable=false;
+ const tree=root.querySelector('[data-focus-hierarchy]'),status=root.querySelector('[data-narrative-status]'),bookPicker=root.querySelector('[data-focus-book]'),toggle=root.querySelector('[data-focus-toggle]');
+ const historyLists=[...document.querySelectorAll('[data-focus-history-list]')],historyToggles=[...document.querySelectorAll('[data-focus-history-toggle]')];
+ const expanded=new Set();let renderedBook=null,renderedChapter=null;
const scopeKey=`pd-narrative-book:${document.body.dataset.pdUserId}:${state.projectID}`;
const notificationKey=()=>`pd-narrative-focus:${document.body.dataset.pdUserId}:${state.projectID}:${state.bookID}`;
- async function loadScope(book){if(!book){render();return;}const mine=++epoch;busy=true;render();try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${book}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const result=await response.json();if(mine!==epoch)return;state=result;if(window.PlotDirectorSharedFocus)await window.PlotDirectorSharedFocus.scope(state);publish();status.textContent='';}catch{status.textContent='This focus book is unavailable. Your workspace is unchanged.';}finally{busy=false;render();if(refreshQueued){refreshQueued=false;void refresh();}}}
- bookPicker?.addEventListener('change',()=>void loadScope(Number(bookPicker.value)));
const key=p=>`${p.chapterID||''}/${p.sceneID||''}`;
- const selected=()=>key(state);
+ const point=p=>({chapterID:Number(p.chapterID)||null,sceneID:Number(p.sceneID)||null,...(p.sequence!=null?{sequence:p.sequence}:{})});
+ const recent=items=>{const seen=new Set();return items.filter(p=>p?.chapterID&&!seen.has(key(p))&&seen.add(key(p))).slice(0,20).map(point);};
const entries=()=>{const chapters=new Set(),items=[];for(const p of state.positions){if(!chapters.has(p.chapterID)){chapters.add(p.chapterID);items.push({...p,sceneID:null,label:`Ch ${p.chapterNumber}: ${p.chapterTitle}`});}if(p.sceneID)items.push(p);}return items;};
const currentLabel=()=>`${bookPicker&&state.bookID?([...bookPicker.options].find(o=>Number(o.value)===state.bookID)?.textContent||'Book')+' · ':''}${state.label||'Choose chapter or scene'}`;
+ function dismiss(restore=false){restore=restore===true||root.querySelector('.pd-focus-picker').contains(document.activeElement);bootstrap.Dropdown.getOrCreateInstance(toggle).hide();if(restore)toggle.focus({preventScroll:true});}
+ function validRecent(items){const valid=new Set(entries().map(key));return recent(items.filter(p=>valid.has(key(p))));}
+ function followingHistory(){const frame=window.PlotDirectorSharedFocus?.heldRecent;if(frame?.bookID!==state.bookID||frame.resumeVersion==null)return state.recent;return validRecent([...state.recent.filter(p=>p.sequence>frame.resumeVersion),...frame.items,...state.recent.filter(p=>p.sequence<=frame.resumeVersion)]);}
+ function heldHistory(){
+ const shared=window.PlotDirectorSharedFocus;if(!shared?.held)return null;
+ let snapshot=shared.heldRecent;
+ if(snapshot?.bookID!==state.bookID||snapshot.resumeVersion!=null){const local=shared.local||state,cutoff=local.version||state.version,previous=followingHistory();snapshot={bookID:state.bookID,cutoff,items:recent([local,...previous.filter(p=>p.sequence==null||p.sequence<=cutoff)])};shared.setHeldRecent(snapshot);}
+ return snapshot;
+ }
+ function visitHeld(p){const snapshot=heldHistory();if(snapshot){snapshot.items=recent([p,...snapshot.items]);window.PlotDirectorSharedFocus.setHeldRecent(snapshot);}}
+ function renderTree(){
+ const focused=tree.contains(document.activeElement)?{target:document.activeElement.dataset.focusTarget,expand:document.activeElement.dataset.focusExpand}:null;
+ if(renderedBook!==state.bookID){expanded.clear();renderedChapter=null;renderedBook=state.bookID;}
+ if(renderedChapter!==state.chapterID){if(state.chapterID)expanded.add(state.chapterID);renderedChapter=state.chapterID;}
+ tree.replaceChildren();const all=entries(),chapters=all.filter(p=>!p.sceneID);
+ for(const chapter of chapters){
+ const li=document.createElement('li'),row=document.createElement('div');row.className='pd-focus-chapter-row';
+ const scenes=all.filter(p=>p.chapterID===chapter.chapterID&&p.sceneID),open=expanded.has(chapter.chapterID),group=document.createElement('ul');group.className='pd-focus-scenes';group.id=`focus-scenes-${chapter.chapterID}`;group.hidden=!open;
+ const expand=document.createElement('button');expand.type='button';expand.className='pd-focus-expand';expand.dataset.focusExpand=chapter.chapterID;expand.textContent=open?'▾':'▸';expand.setAttribute('aria-label',`${open?'Collapse':'Expand'} chapter ${chapter.chapterNumber}`);expand.setAttribute('aria-expanded',String(open));expand.setAttribute('aria-controls',group.id);expand.disabled=!scenes.length;
+ row.append(expand,targetButton(chapter));li.append(row,group);for(const scene of scenes){const item=document.createElement('li');item.append(targetButton(scene));group.append(item);}tree.append(li);
+ }
+ if(!chapters.length){const empty=document.createElement('li');empty.className='pd-focus-empty';empty.textContent=metadataUnavailable?'Navigation unavailable. Reopen to retry.':'Choose a book with saved chapters.';tree.append(empty);}
+ if(focused){const match=[...tree.querySelectorAll('button')].find(b=>focused.target?b.dataset.focusTarget===focused.target:b.dataset.focusExpand===focused.expand);match?.focus({preventScroll:true});}
+ }
+ function targetButton(p){const button=document.createElement('button');button.type='button';button.className='dropdown-item';button.dataset.focusTarget=key(p);button.dataset.chapter=p.chapterID;button.textContent=p.sceneID?`Scene ${p.sceneNumber}: ${p.sceneTitle}`:p.label;button.disabled=busy||!state.bookID||metadataUnavailable;if(key(p)===key(state))button.setAttribute('aria-current','location');return button;}
+ function renderHistory(){
+ const snapshot=heldHistory(),all=entries(),items=validRecent(snapshot?snapshot.items:followingHistory()).filter(p=>key(p)!==key(state)).map(p=>all.find(a=>key(a)===key(p))).filter(Boolean);
+ for(const list of historyLists){const focused=list.contains(document.activeElement)?document.activeElement.dataset.focusHistoryTarget:null;list.replaceChildren();if(metadataUnavailable||!items.length){const li=document.createElement('li');li.className='pd-focus-empty';li.textContent=metadataUnavailable?'History unavailable. Reopen to retry.':'No previous positions in this book.';list.append(li);if(focused)list.parentElement.querySelector('[data-focus-history-toggle]').focus({preventScroll:true});continue;}for(const p of items){const li=document.createElement('li'),button=document.createElement('button');button.type='button';button.className='dropdown-item';button.dataset.focusHistoryTarget=key(p);button.textContent=p.label;button.disabled=busy;li.append(button);list.append(li);}if(focused){const button=[...list.querySelectorAll('[data-focus-history-target]')].find(b=>b.dataset.focusHistoryTarget===focused&&!b.disabled);(button||list.parentElement.querySelector('[data-focus-history-toggle]')).focus({preventScroll:true});}}
+ historyToggles.forEach(b=>b.disabled=busy||!state.bookID);
+ }
function render(){
root.querySelector('[data-focus-label]').textContent=`Current Focus: ${currentLabel()}`;root.querySelector('[data-focus-label]').title=`Current narrative focus: ${currentLabel()}`;
- const term=search.value.trim().toLocaleLowerCase();
- select.replaceChildren(new Option('Choose chapter or scene…',''),...entries().filter(p=>!term||p.label.toLocaleLowerCase().includes(term)).map(p=>new Option(p.label,key(p),false,key(p)===selected())));
- const all=entries();recent.replaceChildren(new Option('Recent chapter / scene…',''),...state.recent.map(h=>all.find(p=>key(p)===key(h))).filter(Boolean).map(p=>new Option(p.label,key(p))));
+ renderTree();renderHistory();
const scenes=state.positions.filter(p=>p.sceneID),at=scenes.findIndex(p=>p.sceneID===state.sceneID),chapterAt=state.positions.findIndex(p=>p.chapterID===state.chapterID),hasChapterScenes=scenes.some(p=>p.chapterID===state.chapterID);
- document.querySelectorAll('[data-global-focus=previous],[data-global-focus=next]').forEach(b=>{const direction=(b.dataset.globalFocus==='previous'?-1:1);const available=at>=0?(direction<0?at>0:at=0?(hasChapterScenes||state.positions.some((p,i)=>p.sceneID&&(direction<0?ichapterAt))):scenes.length>0;b.disabled=busy||!available;});
- document.querySelectorAll('[data-global-focus=go]').forEach(b=>{b.disabled=busy||!state.chapterID||!window.PlotDirectorFocusWorkspace?.adapter?.canGo(state);b.title=!state.chapterID?'Choose a chapter or scene in Current Focus':b.disabled&&!busy?(window.PlotDirectorFocusWorkspace?.adapter?.unavailable||'This workspace does not support Go to Focus for the selected chapter or scene'):'Display Current Focus in this workspace';});
- select.disabled=recent.disabled=busy||!state.bookID;if(bookPicker){bookPicker.value=String(state.bookID||'');bookPicker.disabled=busy;}
+ document.querySelectorAll('[data-global-focus=previous],[data-global-focus=next]').forEach(b=>{const direction=b.dataset.globalFocus==='previous'?-1:1;const available=at>=0?(direction<0?at>0:at=0?(hasChapterScenes||state.positions.some((p,i)=>p.sceneID&&(direction<0?ichapterAt))):scenes.length>0;b.disabled=busy||!available;});
+ if(bookPicker){bookPicker.value=String(state.bookID||'');bookPicker.disabled=busy;}
}
function publish(){document.querySelector('[data-focus-workspace-status]')?.remove();render();try{if(state.bookID)localStorage.setItem(scopeKey,String(state.bookID));}catch{}
for(const card of document.querySelectorAll('.timeline-scene-card[data-scene-id]')){const current=Number(card.dataset.sceneId)===state.sceneID;card.classList.toggle('pd-current-narrative-focus',current);if(current)card.setAttribute('aria-current','location');else if(card.getAttribute('aria-current')==='location')card.removeAttribute('aria-current');}
for(const link of document.querySelectorAll('[data-focus-reference-link]')){const url=new URL(link.href);url.searchParams.delete('chapterId');url.searchParams.delete('sceneId');if(state.chapterID)url.searchParams.set('chapterId',state.chapterID);if(state.sceneID)url.searchParams.set('sceneId',state.sceneID);link.href=url;}
- window.dispatchEvent(new CustomEvent('plotdirector:narrative-focus-changed',{detail:state}));}
+ window.dispatchEvent(new CustomEvent('plotdirector:narrative-focus-changed',{detail:state}));
+ }
+ async function metadata(){
+ if(!state.bookID)return;if(metadataFlight?.book===state.bookID)return metadataFlight.promise;
+ const book=state.bookID,project=state.projectID;
+ const promise=(async()=>{try{const response=await fetch(`/NarrativeFocus/Read?projectId=${project}&bookId=${book}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const data=await response.json();if(state.bookID!==book||state.projectID!==project)return;state.positions=data.positions;state.recent=data.recent;metadataUnavailable=false;const snapshot=heldHistory();if(snapshot){snapshot.items=recent([...snapshot.items,...data.recent.filter(p=>p.sequence<=snapshot.cutoff)]);window.PlotDirectorSharedFocus.setHeldRecent(snapshot);}render();status.textContent='';}catch{if(state.bookID===book){metadataUnavailable=true;status.textContent='Navigation history could not be refreshed. Reopen to retry.';render();}}finally{if(metadataFlight?.book===book)metadataFlight=null;}})();metadataFlight={book,promise};return promise;
+ }
+ async function loadScope(book){if(!book){render();return;}const mine=++epoch;busy=true;render();try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${book}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const result=await response.json();if(mine!==epoch)return;state=result;metadataUnavailable=false;if(window.PlotDirectorSharedFocus)await window.PlotDirectorSharedFocus.scope(state);publish();status.textContent='';}catch{status.textContent='This focus book is unavailable. Your workspace is unchanged.';}finally{busy=false;render();if(refreshQueued){refreshQueued=false;void refresh();}}}
async function refresh(){if(window.PlotDirectorSharedFocus){await window.PlotDirectorSharedFocus.refresh();return;}if(!state.bookID)return;if(busy){refreshQueued=true;return;}refreshQueued=false;const mine=++epoch;try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${state.bookID}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const fresh=await response.json();if(mine!==epoch||busy)return;if(fresh.version!==state.version){state=fresh;publish();}else{state=fresh;render();}}catch{if(mine===epoch&&!busy)status.textContent='Current focus could not be refreshed. Your edits are retained.';}}
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;}
- if(window.PlotDirectorSharedFocus?.ownsScope(state)){busy=true;render();try{const result=await window.PlotDirectorSharedFocus.navigate(target);if(result)dismiss();return result;}finally{adapter?.changeFinished?.();busy=false;render();}}
const fromPicker=root.querySelector('.pd-focus-picker').contains(document.activeElement);
+ const adapter=window.PlotDirectorFocusWorkspace?.adapter;if(adapter?.beforeChange&&!adapter.beforeChange(target)){render();return false;}
+ if(window.PlotDirectorSharedFocus?.ownsScope(state)){busy=true;render();try{const result=await window.PlotDirectorSharedFocus.navigate(target);if(result)dismiss(fromPicker);else if(fromPicker)toggle.focus({preventScroll:true});return result;}finally{adapter?.changeFinished?.();busy=false;render();}}
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});
if(target.chapterID)body.set('chapterId',target.chapterID);if(target.sceneID)body.set('sceneId',target.sceneID);if(target.direction)body.set('direction',target.direction);
- try{
- const response=await fetch('/NarrativeFocus/Set',{method:'POST',body});const result=await response.json().catch(()=>null);
- if(!response.ok||response.redirected){if(response.status===409){busy=false;await refresh();}throw Error(result?.message||'Current focus could not be changed.');}
- 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;
+ try{const response=await fetch('/NarrativeFocus/Set',{method:'POST',body});const result=await response.json().catch(()=>null);if(!response.ok||response.redirected){if(response.status===409){busy=false;await refresh();}throw Error(result?.message||'Current focus could not be changed.');}state=result;publish();status.textContent='';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{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));
- function closeRibbonMenu(button){const menu=button.closest('details[data-compact=true]');if(menu){const restore=menu.contains(document.activeElement)||document.activeElement===document.body;menu.open=false;if(restore)menu.querySelector('summary').focus({preventScroll:true});}else if(document.activeElement===document.body){const target=button.disabled?button.closest('.pd-ribbon-focus').querySelector('button:not(:disabled)'):button;target?.focus({preventScroll:true});}}
- document.querySelectorAll('[data-global-focus=previous],[data-global-focus=next]').forEach(b=>b.addEventListener('click',async()=>{if(await set({direction:(b.dataset.globalFocus==='previous'?-1:1)}))closeRibbonMenu(b);}));
+ function choose(value){const p=entries().find(p=>key(p)===value);return p?set(p):Promise.resolve(false);}
+ tree.addEventListener('click',event=>{const expand=event.target.closest('[data-focus-expand]');if(expand){const id=Number(expand.dataset.focusExpand);expanded.has(id)?expanded.delete(id):expanded.add(id);renderTree();return;}const button=event.target.closest('[data-focus-target]');if(button)void choose(button.dataset.focusTarget);});
+ tree.addEventListener('keydown',event=>{const button=event.target.closest('[data-focus-target]');if(!button)return;const chapter=Number(button.dataset.chapter),value=button.dataset.focusTarget;
+ if(['ArrowRight','ArrowLeft'].includes(event.key)){event.preventDefault();if(event.key==='ArrowRight'&&!value.endsWith('/'))return;if(event.key==='ArrowRight')expanded.add(chapter);else if(value.endsWith('/'))expanded.delete(chapter);renderTree();tree.querySelector(`[data-focus-target="${chapter}/"]`)?.focus();return;}
+ if(!['ArrowDown','ArrowUp','Home','End'].includes(event.key))return;event.preventDefault();const targets=[...tree.querySelectorAll('[data-focus-target]')].filter(b=>b.getClientRects().length&&!b.disabled),at=targets.indexOf(button),next=event.key==='Home'?0:event.key==='End'?targets.length-1:Math.max(0,Math.min(targets.length-1,at+(event.key==='ArrowDown'?1:-1)));targets[next]?.focus();
+ });
+ root.addEventListener('keydown',event=>{if(event.key==='Escape'){event.preventDefault();dismiss(true);}});
+ function closeRibbonMenu(button){const menu=button.closest('details[data-compact=true]');if(menu){const restore=menu.contains(document.activeElement)||document.activeElement===document.body;menu.open=false;if(restore)menu.querySelector('summary').focus({preventScroll:true});}}
+ document.querySelectorAll('[data-global-focus=previous],[data-global-focus=next]').forEach(b=>b.addEventListener('click',async()=>{if(await set({direction:b.dataset.globalFocus==='previous'?-1:1}))closeRibbonMenu(b);}));
+ for(const button of historyToggles){bootstrap.Dropdown.getOrCreateInstance(button,{popperConfig:config=>({...config,strategy:'fixed',modifiers:[...(config.modifiers||[]),{name:'preventOverflow',options:{boundary:'viewport',padding:12}}]})});button.parentElement.addEventListener('shown.bs.dropdown',()=>void metadata());}
+ for(const list of historyLists)list.addEventListener('click',async event=>{const button=event.target.closest('[data-focus-history-target]');if(!button)return;if(await choose(button.dataset.focusHistoryTarget)){const toggle=list.parentElement.querySelector('[data-focus-history-toggle]');bootstrap.Dropdown.getOrCreateInstance(toggle).hide();toggle.focus({preventScroll:true});}});
+ root.addEventListener('shown.bs.dropdown',()=>void metadata());bookPicker?.addEventListener('change',()=>void loadScope(Number(bookPicker.value)));
window.addEventListener('plotdirector:focus-adapter-ready',render);
- document.querySelectorAll('[data-global-focus=go]').forEach(b=>b.addEventListener('click',async()=>{const adapter=window.PlotDirectorFocusWorkspace?.adapter;if(busy)return;if(window.PlotDirectorSharedFocus?.ownsScope(state)){await window.PlotDirectorSharedFocus.go();return;}if(!adapter?.canGo(state)){showWorkspaceMessage(adapter?.unavailable||'Current Focus is unavailable in this workspace.');render();return;}document.querySelector('[data-focus-workspace-status]')?.remove();busy=true;render();let succeeded=false;try{await adapter.go(state);succeeded=true;}catch(error){showWorkspaceMessage(error.message||'Current Focus could not be displayed.');}finally{busy=false;render();if(succeeded)closeRibbonMenu(b);if(refreshQueued){refreshQueued=false;void refresh();}}}));
+ window.addEventListener('plotdirector:shared-focus',event=>{const p=event.detail.position;if(p.bookID!==state.bookID||p.projectID!==state.projectID)return;if(window.PlotDirectorSharedFocus?.held)visitHeld(p);const position=state.positions.find(x=>x.chapterID===p.chapterID&&(!p.sceneID||x.sceneID===p.sceneID));state={...state,...p,label:position?(p.sceneID?position.label:`Ch ${position.chapterNumber}: ${position.chapterTitle}`):'Choose chapter or scene'};if(event.detail.reason==='selection')render();else publish();if(!window.PlotDirectorSharedFocus?.held&&historyToggles.some(b=>b.getAttribute('aria-expanded')==='true'))void metadata();});
+ window.addEventListener('plotdirector:focus-mode',()=>{if(window.PlotDirectorSharedFocus?.held){const p=window.PlotDirectorSharedFocus.local;if(p?.bookID===state.bookID){const entry=entries().find(x=>key(x)===key(p));state={...state,...p,label:entry?.label||state.label};}heldHistory();render();void metadata();}else{const shared=window.PlotDirectorSharedFocus,frame=shared?.heldRecent;if(frame?.bookID===state.bookID){frame.items=recent([shared.local,...frame.items]);frame.resumeVersion=shared.shared?.version??state.version;shared.setHeldRecent(frame);}}renderHistory();});
+ window.addEventListener('plotdirector:shared-focus-ready',()=>{heldHistory();renderHistory();});
function showWorkspaceMessage(message){let output=document.querySelector('[data-focus-workspace-status]');if(!output){output=document.createElement('p');output.dataset.focusWorkspaceStatus='';output.setAttribute('role','status');document.querySelector('.pd-shell').after(output);}output.textContent=message;}
- window.addEventListener('pagehide',dismiss);
- document.addEventListener('click',e=>{const b=e.target.closest('[data-go-objective],[data-narrative-scene]');if(!b)return;void set({bookID:Number(b.dataset.narrativeBook)||state.bookID,chapterID:Number(b.dataset.chapter||b.dataset.narrativeChapter)||null,sceneID:Number(b.dataset.scene||b.dataset.narrativeScene)||null});});
- window.addEventListener('storage',e=>{if(e.key===notificationKey())void refresh();});window.addEventListener('focus',()=>void refresh());window.addEventListener('pageshow',()=>void refresh());root.addEventListener('shown.bs.dropdown',()=>void refresh());
- window.addEventListener('plotdirector:shared-focus',event=>{const p=event.detail.position;if(p.bookID!==state.bookID||p.projectID!==state.projectID)return;const position=state.positions.find(x=>x.chapterID===p.chapterID&&(!p.sceneID||x.sceneID===p.sceneID));state={...state,...p,label:position?(p.sceneID?position.label:`Ch ${position.chapterNumber}: ${position.chapterTitle}`):'Choose chapter or scene'};if(event.detail.reason==='selection')render();else publish();});
- root.addEventListener('shown.bs.dropdown',async()=>{if(!state.bookID)return;try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${state.bookID}`,{cache:'no-store'});if(response.ok&&!response.redirected){const data=await response.json();state.positions=data.positions;state.recent=data.recent;render();}}catch{}});
- window.PlotDirectorNarrativeFocus={set,refresh,get state(){return state;}};
- publish();
+ document.addEventListener('click',event=>{const b=event.target.closest('[data-go-objective],[data-narrative-scene]');if(b)void set({bookID:Number(b.dataset.narrativeBook)||state.bookID,chapterID:Number(b.dataset.chapter||b.dataset.narrativeChapter)||null,sceneID:Number(b.dataset.scene||b.dataset.narrativeScene)||null});});
+ window.addEventListener('storage',event=>{if(event.key===notificationKey())void refresh();});window.addEventListener('focus',()=>void refresh());window.addEventListener('pageshow',()=>void refresh());window.addEventListener('pagehide',()=>dismiss());
+ const restored=window.PlotDirectorSharedFocus;
+ if(restored?.held&&restored.local?.bookID===state.bookID&&restored.local?.projectID===state.projectID){const p=restored.local,entry=entries().find(x=>key(x)===key(p));state={...state,...p,label:entry?.label||'Held reference unavailable'};}
+ window.PlotDirectorNarrativeFocus={set,refresh,get state(){return state;}};publish();
if(!state.bookID&&bookPicker){try{const book=localStorage.getItem(scopeKey);if([...bookPicker.options].some(o=>o.value===book))void loadScope(Number(book));}catch{}}
const url=new URL(location.href);if(url.searchParams.has('navigateFocus')){url.searchParams.delete('navigateFocus');history.replaceState(history.state,'',url);}
})();
diff --git a/PlotLine/wwwroot/js/shared-manuscript-focus.js b/PlotLine/wwwroot/js/shared-manuscript-focus.js
index 150448ac..d2952ee3 100644
--- a/PlotLine/wwwroot/js/shared-manuscript-focus.js
+++ b/PlotLine/wwwroot/js/shared-manuscript-focus.js
@@ -1,16 +1,16 @@
// 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;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}));}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;}catch{held=false;}}
+(()=>{'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?'Release Hold':'Hold';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?'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;}
async function navigate(target,forcePublication=false){const priorLocal=local;if(target.localSelection&&Number(target.bookID||book)===book){local=normal({...local,projectID:project,bookID:book,chapterID:target.chapterID,sceneID:target.sceneID||null,paragraphID:target.paragraphID});save();}if(publishing){queuedTarget=target;return true;}const effective=held?priorLocal:latest?.isValid?latest:null;if(!forcePublication&&Number(target.sceneID||target.sceneId)>0&&Number(target.sceneID||target.sceneId)===effective?.sceneID&&!effective.paragraphID&&!target.paragraphID&&!target.paragraphId)return true;if(!forcePublication&&!target.direction&&!target.sceneID&&!target.sceneId&&!target.paragraphID&&!target.paragraphId&&Number(target.chapterID||target.chapterId)>0&&Number(target.chapterID||target.chapterId)===effective?.chapterID&&!effective.sceneID&&!effective.paragraphID)return true;const paragraph=target.paragraphID||target.paragraphId;if(!forcePublication&¶graph&¶graph===effective?.paragraphID&&Number(target.chapterID||target.chapterId)===effective.chapterID)return true;if(publishing)return false;if(target.bookID&&Number(target.bookID)!==book)return false;publishing=true;const localRequest=held;selectionPublishing=target.localSelection===true;try{const normalized={chapterID:target.chapterID||target.chapterId||null,sceneID:target.sceneID||target.sceneId||null,paragraphID:target.paragraphID||target.paragraphId||null,...(target.direction?{direction:target.direction}:{}),...(target.manuscriptID?{manuscriptID:target.manuscriptID}:{})};if(held&&target.direction)Object.assign(normalized,{chapterID:local.chapterID,sceneID:local.sceneID,paragraphID:local.paragraphID});const result=await request(localRequest?'Resolve':'Publish',normalized);if(result.bookID!==book||result.projectID!==project)return false;if(localRequest){if(held)apply(result,selectionPublishing?'selection':'local');else await refresh(true);}else accept(result,true);return true;}catch(error){status(error.message);return false;}finally{publishing=false;selectionPublishing=false;if(queuedTarget){const next=queuedTarget;queuedTarget=null;void navigate(next,true);}}}
async function toggle(){if(!connected||!authoritative||disconnected)return;queuedTarget=null;if(held){if(!await refresh()){status('Hold retained: reconnect before catching up to authoritative shared focus.');return;}held=false;save();if(latest?.isValid&&latest.chapterID)apply(latest,'release');else status('Following · no valid shared focus; local position retained.');}else{held=true;save();status();}window.dispatchEvent(new CustomEvent('plotdirector:focus-mode',{detail:{held}}));}
-async function validateLocal(){if(!held||!local?.chapterID)return;try{const result=await request('Validate',local);if(!result.isValid)status('Held reference is no longer valid. Select another local position or Release Hold.');}catch{status('Held reference cannot be resolved. Select another position; data updates remain connected.');}}
+async function validateLocal(){if(!held||!local?.chapterID)return;try{const result=await request('Validate',local);if(!result.isValid)status('Held reference is no longer valid. Select another local position or Resume.');}catch{status('Held reference cannot be resolved. Select another position; data updates remain connected.');}}
function ready(c,reconnected=false){if(!c||c!==connection||c.state!=='Connected')return;connected=true;const key=c.connectionId||'connected';if(readyKey===key){if(!authoritative)void refresh();return;}readyKey=key;invalidateRead();status();trace('connection',reconnected?'reconnected':'ready');void refresh();}
function wire(c){if(!c||connection===c)return;if(connection)return;connection=c;c.on('ManuscriptFocusChanged',packet=>{trace('notification','received',normal(packet));accept(packet);});c.on('ManuscriptFocusDelivery',packet=>{if(Number(packet.bookID||packet.bookId)===book&&Number(packet.version)===latest?.version)status('Word cannot follow this reference in the background. Save and synchronise Word; other windows remain independent.');});c.on('ContextInvalidated',hint=>{if(hint.bookId&&Number(hint.bookId)!==book||hint.projectId&&Number(hint.projectId)!==project)return;window.dispatchEvent(new CustomEvent('plotdirector:reference-invalidated',{detail:hint}));void validateLocal();});function offline(){connected=false;disconnected=true;readyKey=null;invalidateRead();status('Shared focus disconnected. Your local position is retained.');trace('connection','disconnected');}c.onreconnecting(offline);c.onclose(offline);c.onreconnected(()=>ready(c,true));ready(c);}
const channel=!context&&window.BroadcastChannel?new BroadcastChannel('pd.shared-focus.identity.'+user):null;channel?.addEventListener('message',event=>{const m=event.data;if(m.id!==id||m.page===page)return;if(m.kind==='claim')channel.postMessage({kind:'occupied',id,page,target:m.page});if(m.kind==='occupied'&&m.target===page){id=crypto.randomUUID();sessionStorage.setItem('pd.shared-focus.window',id);held=false;sequence=0;save();status();void refresh(true);}});channel?.postMessage({kind:'claim',id,page});
context?.addEventListener('context-capabilities-changed',()=>{const next=context.contextController?.windowId;if(next&&next!==id){id=next;held=false;sequence=0;save();status();void refresh(true);}});
-restore();status();buttons.forEach(b=>b.addEventListener('click',()=>void toggle()));document.addEventListener('pd-presence-connection',e=>wire(e.detail));document.addEventListener('pd-presence-ready',()=>{const c=window.PlotDirectorPresenceConnection;wire(c);ready(c);});context?.addEventListener('context-connection-ready',()=>{const c=context.contextController?.connection;wire(c);ready(c);});wire(context?.contextController?.connection||window.PlotDirectorPresenceConnection);window.addEventListener('focus',()=>void refresh());window.addEventListener('pagehide',()=>{save();channel?.close();});window.PlotDirectorSharedFocus={navigate,refresh,toggle,validateLocal,get held(){return held;},get local(){return local;},get shared(){return latest;},get windowID(){return id;},async go(){if(await refresh(true)&&held&&latest?.isValid)apply(latest,'local');},ownsScope:p=>Number(p.bookID)===book&&Number(p.projectID)===project,async scope(p){invalidateRead();project=Number(p.projectID);book=Number(p.bookID);queuedTarget=null;latest=null;const wasHeld=held;restore();held=wasHeld;local=normal(p);save();status();if(held)apply(local,'local');await refresh(true);}};document.addEventListener('click',async event=>{if(!event.isTrusted||event.defaultPrevented||event.button!==0||event.ctrlKey||event.metaKey||event.shiftKey||event.altKey)return;const link=event.target.closest('a[href]');if(!link||link.target&&link.target!=='_self'||link.closest('.reader-chapter-navigation'))return;const url=new URL(link.href,location.href);if(url.origin!==location.origin||url.searchParams.get('retainNarrativeFocus')==='true')return;const match=url.pathname.match(/^\/(Scenes\/Edit|Chapters\/(?:Details|Edit)|Writer\/Chapter)\/(\d+)$/i),timeline=/^\/Timeline(?:\/Index)?$/i.test(url.pathname)&&url.searchParams.get('navigateFocus')==='true';if(!match&&!timeline)return;const selectedScene=Number([...url.searchParams].find(([key])=>key.toLowerCase()==='selectedsceneid')?.[1]);const target=timeline?{sceneID:selectedScene}:match[1].toLowerCase()==='scenes/edit'?{sceneID:Number(match[2])}:{chapterID:Number(match[2])};if(timeline&&!selectedScene)return;event.preventDefault();const adapter=window.PlotDirectorFocusWorkspace?.adapter;try{if(adapter?.beforeChange&&await adapter.beforeChange(target)===false)return;await navigate(target);url.searchParams.delete('navigateFocus');url.searchParams.set('retainNarrativeFocus','true');location.assign(url);}finally{adapter?.changeFinished?.();}});window.dispatchEvent(new Event('plotdirector:shared-focus-ready'));void refresh();if(held&&local?.chapterID){apply(local,'restore');void validateLocal();}}
+restore();status();buttons.forEach(b=>b.addEventListener('click',()=>void toggle()));document.addEventListener('pd-presence-connection',e=>wire(e.detail));document.addEventListener('pd-presence-ready',()=>{const c=window.PlotDirectorPresenceConnection;wire(c);ready(c);});context?.addEventListener('context-connection-ready',()=>{const c=context.contextController?.connection;wire(c);ready(c);});wire(context?.contextController?.connection||window.PlotDirectorPresenceConnection);window.addEventListener('focus',()=>void refresh());window.addEventListener('pagehide',()=>{save();channel?.close();});window.PlotDirectorSharedFocus={navigate,refresh,toggle,validateLocal,get heldRecent(){return heldRecent;},setHeldRecent(value){heldRecent=value;save();},get held(){return held;},get local(){return local;},get shared(){return latest;},get windowID(){return id;},async go(){if(await refresh(true)&&held&&latest?.isValid)apply(latest,'local');},ownsScope:p=>Number(p.bookID)===book&&Number(p.projectID)===project,async scope(p){invalidateRead();project=Number(p.projectID);book=Number(p.bookID);queuedTarget=null;latest=null;const wasHeld=held;restore();held=wasHeld;local=normal(p);save();status();if(held)apply(local,'local');await refresh(true);}};document.addEventListener('click',async event=>{if(!event.isTrusted||event.defaultPrevented||event.button!==0||event.ctrlKey||event.metaKey||event.shiftKey||event.altKey)return;const link=event.target.closest('a[href]');if(!link||link.target&&link.target!=='_self'||link.closest('.reader-chapter-navigation'))return;const url=new URL(link.href,location.href);if(url.origin!==location.origin||url.searchParams.get('retainNarrativeFocus')==='true')return;const match=url.pathname.match(/^\/(Scenes\/Edit|Chapters\/(?:Details|Edit)|Writer\/Chapter)\/(\d+)$/i),timeline=/^\/Timeline(?:\/Index)?$/i.test(url.pathname)&&url.searchParams.get('navigateFocus')==='true';if(!match&&!timeline)return;const selectedScene=Number([...url.searchParams].find(([key])=>key.toLowerCase()==='selectedsceneid')?.[1]);const target=timeline?{sceneID:selectedScene}:match[1].toLowerCase()==='scenes/edit'?{sceneID:Number(match[2])}:{chapterID:Number(match[2])};if(timeline&&!selectedScene)return;event.preventDefault();const adapter=window.PlotDirectorFocusWorkspace?.adapter;try{if(adapter?.beforeChange&&await adapter.beforeChange(target)===false)return;await navigate(target);url.searchParams.delete('navigateFocus');url.searchParams.set('retainNarrativeFocus','true');location.assign(url);}finally{adapter?.changeFinished?.();}});window.dispatchEvent(new Event('plotdirector:shared-focus-ready'));void refresh();if(held&&local?.chapterID){apply(local,'restore');void validateLocal();}}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})();
diff --git a/PlotLine/wwwroot/js/writer-word.js b/PlotLine/wwwroot/js/writer-word.js
index ae286aa2..52c7d6c2 100644
--- a/PlotLine/wwwroot/js/writer-word.js
+++ b/PlotLine/wwwroot/js/writer-word.js
@@ -18,7 +18,7 @@ const identity=current&&data.canonical?.manuscriptID===current.manuscriptId;cons
state.textContent=data.unavailable?'Word Companion status unavailable. Your saved work is retained.':!current?(missingSelection?'Selected Word document is disconnected. Choose another document explicitly.':leases.length>1?'Choose the correct Word manuscript.':(data.leases||[]).some(l=>l.wordAvailable)?'The open Word manuscript is for another book.':'Word Companion is not connected to this manuscript.'):!identity?'Word is connected, but this manuscript has not been verified.':`Manuscript: ${current.documentTitle}`;
position.textContent=observed?`Word is showing ${observed.chapterTitle||'the verified chapter'}${observed.sceneId&&observed.sceneTitle?' · '+observed.sceneTitle:''}. ${observed.chapterId!==chapter?(reviewing?'Your review selection is separate.':'Your working focus is separate.'):''}`:current?.wordSaved===false?'Word has unsaved changes. Current positions await verification; no save will be forced.':current?.wordSaved===null?'Word position awaits a fresh observation. Check the intended document in Word; accepted text is retained.':'Word position has not been verified.';
const chapterStatus=window.PlotDirector.wordChapterStatus(data,current,book,chapter);
-freshness.textContent=chapterStatus.text+(current&¤t.canSharedFocus!==true?' Update Word Companion to use shared manuscript focus.':'');for(const ribbon of document.querySelectorAll('[data-word-ribbon-status]')){ribbon.textContent=chapterStatus.label;ribbon.title=chapterStatus.text;}
+freshness.textContent=chapterStatus.text+(current&¤t.canSharedFocus!==true?' Update Word Companion to use shared manuscript focus.':'');
const warning=document.querySelector('[data-review-word-warning]');if(warning)warning.textContent='Showing accepted text. '+(!current?state.textContent:current.wordSaved===false?'Word has unsaved changes; they are not shown here.':chapterStatus.text);
sync.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!(current.canChapterSync||current.canParagraphSync);