Consolidate global narrative focus navigation in contextual ribbons

This commit is contained in:
Nick Beckley 2026-11-20 16:06:32 +00:00
parent ef4abda5fa
commit a209f35610
23 changed files with 181 additions and 42 deletions

View File

@ -0,0 +1,42 @@
# Focus ribbon consolidation
## Navigation audit
| Surface | Existing operation | Treatment |
| --- | --- | --- |
| Current Focus popup Previous/Next | Authoritative scene stepping, including chapter boundaries | Removed from popup; same service and boundary logic now power shared ribbon commands. Search, selection and history remain. |
| Review Reading & Review Previous/Next | GET chapter links; reader-specific chapter navigation, not scene stepping | Removed ribbon contributions. Retained local chapter controls only in Focus Reading; normal integrated Review hides redundant chapter picker and links. Standalone Reader retains chapter controls. |
| Review chapter picker | Explicit reader chapter choice; preserves reading/focus query state and no-script GET navigation | Retained for specialised Focus Reading and standalone Reader. Normal Review uses global selection, with the existing dirty-annotation guard and stable partial refresh. |
| Relationships | Local scene scrubber/Previous Scene/Next Scene; separate Previous/Next relationship change markers | Retained. Go explicitly selects the global scene through the existing local explorer. Global stepping never moves it. |
| Maps | Local scene Previous/Next, or dated-event stepping in Time lens; six independent lenses | Retained, including journey/travel context. Go explicitly enters Scene lens and selects global scene. Missing scene/scenario reports unavailability, without changing scenario. |
| Floor Plans | Local occupancy Previous Scene/Next Scene and eligible scene picker | Retained. Go enters occupancy and selects an eligible global scene. Unavailable scenes disable Go. Existing floor/occupancy edit mechanisms remain. |
| At This Point | Read-only local book/chapter/scene snapshot controls | Retained. Go selects global scene and loads via existing snapshot AJAX. Local selection never writes focus. |
| Timeline | Local jump/search/reveal controls; explicit scene-opening links | Retained. Go opens focused scene inspector through existing same-workspace navigation, preserving current filters. Hidden/absent scenes offer an explicit unfiltered reveal. |
| Plot Lines | Find a Scene, intersections-only filter, Next intersection, inspector links | Retained. Go pans/scrolls and highlights visible scene. Missing/filtered scene offers explicit inspection, preserving selected plot lines and filters. |
| Calendar / Writer Reflect | Previous/Next month and story-month navigation | Retained: time-window filters, not narrative stepping. |
| Review annotations | Previous annotations / More annotations | Retained: pagination, not narrative stepping. |
| Threads, Writer objectives, recordings, comparison/reference selectors | Entity editing, independent task/session targets, or local inspection | Retained. No implicit global retargeting. |
## Shared implementation
`_FocusRibbon` renders the same three buttons in every contextual category. Existing ribbon overflow fitting treats it as a normal group. Flex ordering places it last, before an existing contextual Help group; no Help group is created. Disabled buttons render with the group before initialization, so command availability does not insert or shift layout.
`narrative-focus.js` remains the sole focus commit path. Previous/Next reuse the existing canonical scene sequence, boundary calculations, versioned service writes, history and multi-window notifications. Chapter-only focus uses the already-qualified server semantics: an available scene within its chapter or the neighbouring canonical scene; empty books have no enabled stepping. Go never calls Set.
`PlotDirectorFocusWorkspace` supplies one presentation adapter for the current workspace. Scene Explorer adapters call the same local `choose` callback as manual exploration. Other adapters use existing reader, snapshot, chapter destination, Timeline or weave mechanisms. Unsupported pages disable Go. Chapter-only focus supports chapter destinations/Review; scene-specific views require a scene.
Review reuses `narrative-focus-review.js`: guard open/dirty editors, reuse current chapter without fetching, otherwise replace only read-only sections in stable columns; preserve focus reading, accepted identity, annotations, update state, recording and verified Word objects. Scene focus can select an existing accepted mapping only; no paragraph association is manufactured. Chapter-oriented Book destinations use `retainNarrativeFocus=true`, so they do not erase global scene focus.
Timeline's Go uses existing document navigation within Timeline, retaining query filters and normal unsaved-navigation protection. Plot Lines' excluded-scene action opens the existing inspector without replacing line selection. These choices preserve existing contracts rather than adding another inspector renderer or filter system. No database or synchronisation changes are required.
Compact Focus menus close after successful commands and retain sensible keyboard focus. Failed focus writes remain visible and retryable. Go refuses to switch dirty/busy map editing or unsaved floor-plan layouts; it leaves the existing draft and local position intact. Cross-window refreshes queued during an asynchronous Go are processed afterwards.
## Qualification
- Solution build: zero warnings/errors; full executable regression harness: 632 passing checks.
- `Browser/focus-ribbon.cjs`: Chromium and CDP-installed standalone Chromium PWA; shared ordering before existing Help/at end, no Review ribbon duplicates, one-click canonical stepping, guarded reader following, aligned no-op Go, Focus Reading preservation/exit, real chapter destination retaining scene context, real Timeline inspector and explicit filtered reveal, AJAX snapshot isolation, weave highlight/explicit inspection, unsaved floor-plan protection, disabled unsupported pages, light/dark at 1666/950/650px.
- Updated `Browser/narrative-focus.cjs`: browser and installed PWA; global/local isolation and explicit Go for Floor Plans, Relationships and Maps, objective/editor/session/Word boundaries, protected Review annotations, canonical boundaries/empty chapter, persistence/history/scope, cross-window conflicts, search and project-wide context.
- Updated popup and icon suites: browser and installed PWA; no header stepping controls, selection/search/history/dismissal/error behaviour, existing Reader commands, stateful icons and Word badges. Matching chevrons are compared in the same enabled state.
- Updated manuscript-reader suite: real Razor/controllers, three widths × four themes × browser/PWA, specialised chapter controls in Focus Reading, selectable accepted text, private responses and scope/empty/error handling.
Browser qualification uses the compiled application test host with isolated repositories and representative synthetic author data; Word transport is simulated. No real author story records were changed by these tests. Timeline Go intentionally reuses document navigation; other adapters use existing local/partial-render mechanisms. Unavailable local scenes remain unavailable rather than changing scenarios, selected plot lines, filters or verified paragraph associations implicitly.

View File

@ -1,5 +1,7 @@
# Narrative focus and Scene Explorer: audit, architecture and qualification
Follow-up: global stepping now lives in the shared Focus ribbon; see [Focus ribbon consolidation](FocusRibbonConsolidation.md) for the navigation inventory and workspace adapters.
Status: implemented on the established development branch; final qualification and deployment results are recorded below. The first table preserves the initial audit; the completed classification follows it. The unrelated CanonicalManuscriptArchitectureAssessment.md is not part of this work.
## Findings and evidence

View File

@ -0,0 +1,39 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
const base=process.env.PD_NARRATIVE_TEST_URL||'http://127.0.0.1:5238';
(async()=>{
const installed=process.argv.includes('--installed'),profile=fs.mkdtempSync('/tmp/pd-narrative-pwa-');
const c=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1666,height:1050}}):await(await chromium.launch()).newContext({viewport:{width:1666,height:1050}}),b=c.browser();
try{
await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:null,defaultPauseOnEdit:true}}));
await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false,state:'Disconnected',wordConnected:false}}));
await c.route('**/native-companion/status*',r=>r.fulfill({json:{leases:[]}}));
await c.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')}));
await c.route('**/hubs/**',r=>r.abort());
await c.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()})));
let p;
if(installed){const tab=c.pages()[0];await tab.goto(base+'/fixture');const d=await b.newBrowserCDPSession(),manifestId=base+'/Projects';await d.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture'});await d.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=c.waitForEvent('page');await d.send('PWA.launch',{manifestId,url:base+'/fixture'});p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else p=await c.newPage();
const active='.pd-ribbon-panel:not([hidden])',button=kind=>p.locator(`${active} [data-global-focus=${kind}]`);
const state=()=>p.evaluate(()=>window.PlotDirectorNarrativeFocus.state),set=t=>p.evaluate(t=>window.PlotDirectorNarrativeFocus.set(t),t);
async function placement(){const result=await p.locator(active).evaluate(panel=>{const focus=panel.querySelector('.pd-ribbon-focus'),groups=[...panel.querySelectorAll('.pd-ribbon-group')].filter(n=>n.getClientRects().length),help=groups.find(n=>n.getAttribute('aria-label')==='Help');return {count:panel.querySelectorAll('.pd-ribbon-focus').length,commands:[...focus.querySelectorAll('[data-global-focus]')].map(n=>n.dataset.globalFocus),order:Number(getComputedStyle(focus).order),helpOrder:help?Number(getComputedStyle(help).order):null,focusRight:focus.getBoundingClientRect().right,helpLeft:help?.getBoundingClientRect().left};});assert.equal(result.count,1);assert.deepEqual(result.commands,['previous','go','next']);assert.equal(result.order,90);if(result.helpOrder!==null){assert.equal(result.helpOrder,100);assert(result.focusRight<=result.helpLeft+2);}}
await p.goto(base+'/Writer/Review?projectId=7&bookId=12&chapterId=21');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);
await set({chapterID:21,sceneID:31});await placement();assert.equal(await p.locator('.pd-focus-picker [data-focus-step]').count(),0);
assert.equal(await p.locator(`${active} [data-pwa-binding*="reader-prev"],${active} [data-pwa-binding*="reader-next"]`).count(),0);
assert(!await p.locator('#reader-chapter').isVisible());assert(await p.locator('#reader-focus').count());assert(await p.locator('#reader-audio').count());
assert(await button('previous').isDisabled());await button('next').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===101);await button('next').click();await p.waitForFunction(()=>document.querySelector('.manuscript-reader').dataset.chapterId==='22');assert.equal((await state()).sceneID,32);assert(await button('next').isDisabled());
let loads=0;const count=r=>{if(r.url().includes('/Writer/ReviewContent'))loads++;};p.on('request',count);const before=(await state()).version;await button('go').click();await p.waitForTimeout(100);assert.equal(loads,0,'aligned Review Go does not reload');assert.equal((await state()).version,before);p.off('request',count);
await p.locator('#reader-focus').evaluate(n=>n.click());assert(await p.locator('#reader-chapter').isVisible(),'specialised chapter picker retained when header is inaccessible');await set({chapterID:21,sceneID:31});await p.waitForFunction(()=>document.querySelector('.manuscript-reader').dataset.chapterId==='21');assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true','focus reading survives global chapter navigation');await p.locator('#reader-focus').evaluate(n=>n.click());assert(await p.locator('.pd-application-header').evaluate(n=>!n.inert),'application header becomes interactive after exiting Focus Reading');
for(const width of [1666,950,650])for(const theme of ['modern-light','modern-dark']){await p.setViewportSize({width,height:1050});await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme?.(t),theme);await p.screenshot({path:`/tmp/pd-focus-ribbon-${installed?'pwa':'browser'}-${width}-${theme}.png`});assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}
await p.setViewportSize({width:1666,height:1050});
await p.goto(base+'/Timeline/Index?projectId=7&bookId=12');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await set({chapterID:21,sceneID:31});const timelineVersion=(await state()).version;await button('go').click();await p.waitForURL(/selectedSceneId=31/);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);assert.equal((await state()).version,timelineVersion);assert(await p.locator('[data-inspector-drawer] [data-scene-id="31"]').count(),'existing Timeline inspector opens');
await p.locator('.timeline-scene-card[data-scene-id="31"]').evaluate(n=>n.hidden=true);await button('go').click();assert.match(await p.locator('[data-focus-workspace-status]').textContent(),/filters are retained/);assert(await p.locator('[data-focus-workspace-status] button').count());
await p.goto(base+'/fixture?desktop=Books');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await set({chapterID:21,sceneID:31});const bookVersion=(await state()).version;const destination=p.waitForRequest(r=>r.isNavigationRequest()&&r.url().includes('/Chapters/Details/21'));await button('go').click();const request=await destination;assert(new URL(request.url()).searchParams.get('retainNarrativeFocus')==='true');await p.waitForURL(/Chapters\/Details\/21/);await p.waitForLoadState();assert.match(await p.locator('main').innerText(),/Focused chapter/);const read=await(await c.request.get(base+'/NarrativeFocus/Read?projectId=7&bookId=12')).json();assert.equal(read.version,bookVersion);assert.equal(read.sceneID,31);
await p.goto(base+'/fixture?desktop=StoryPoint');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus&&window.PlotDirectorFocusWorkspace?.adapter);await placement();await p.route('**/StoryPoint?*',r=>r.fulfill({contentType:'text/html',body:'<p>Snapshot loaded</p>'}));await p.route('**/StoryPoint/Index?*',r=>r.fulfill({contentType:'text/html',body:'<p>Snapshot loaded</p>'}));
await set({chapterID:22,sceneID:32});assert.notEqual(await p.locator('[data-point-scene]').inputValue(),'32');const pointVersion=(await state()).version;await button('go').click();assert.equal(await p.locator('[data-point-scene]').inputValue(),'32');assert.equal((await state()).version,pointVersion);await p.locator('[data-point-chapter]').selectOption('21');assert.equal((await state()).version,pointVersion,'local snapshot selection stays local');
await p.goto(base+'/fixture?desktop=PlotLineWorkspace');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus&&window.PlotDirectorFocusWorkspace?.adapter);await set({chapterID:21,sceneID:31});const plotVersion=(await state()).version;await button('go').click();assert(await p.locator('[data-plot-scene]').evaluate(n=>n.classList.contains('plot-weave-focus')));assert.equal((await state()).version,plotVersion);await p.locator('#plot-scene-search').fill('No matching scene');await button('go').click();assert.match(await p.locator('[data-focus-workspace-status]').textContent(),/selected plot lines and search are retained/);await p.route('**/PlotLineWorkspace/Inspector?*',r=>r.fulfill({contentType:'text/html',body:'<p>Focused scene details</p>'}));await p.locator('[data-focus-workspace-status] button').click();await p.waitForFunction(()=>document.querySelector('#plot-inspector-content').textContent.includes('Focused scene'));assert.equal(await p.locator('#plot-scene-search').inputValue(),'No matching scene');assert.equal((await state()).version,plotVersion);
await p.goto(base+'/fixture?page=floorplans');await p.waitForFunction(()=>document.querySelector('[data-floor-plan-initialized=true]'));await set({chapterID:21,sceneID:31});await p.route('**/FloorPlans/SaveLayout',r=>r.fulfill({status:400,json:{ok:false,message:'Synthetic save failure'}}));await p.locator('[data-save-layout-button]').evaluate(n=>n.click());await p.waitForFunction(()=>document.querySelector('[data-save-status]').dataset.saveState==='failed');const floorBefore=await p.locator('[data-occupancy-scene-select]').inputValue();const menu=p.locator(`${active} .pd-ribbon-focus details[data-compact=true]`);if(await menu.count()&&!await menu.evaluate(n=>n.open))await menu.locator('summary').click();await button('go').click();assert.match(await p.locator('[data-focus-workspace-status]').textContent(),/Save or discard/);assert.equal(await p.locator('[data-occupancy-scene-select]').inputValue(),floorBefore);assert.equal(await p.locator('[data-save-status]').getAttribute('data-save-state'),'failed','Go preserves unsaved floor-plan state');p.once('dialog',d=>d.accept());
await p.goto(base+'/fixture?desktop=Characters');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);assert(await button('go').isDisabled(),'unsupported workspace disables Go');await placement();
console.log(`PASS ${installed?'installed PWA':'Chromium'} Focus ribbon order/placement, consolidated Review, one-click scene stepping across chapters, reader follow/Go/no-op/focus-mode controls, Timeline inspector and explicit filtered reveal, Book chapter destination retains scene focus, local snapshot alignment/isolation, unsupported states, responsive light/dark.`);
}finally{await c.close();await b?.close();fs.rmSync(profile,{recursive:true,force:true});}
})().catch(e=>{console.error(e.stack);process.exitCode=1;});

View File

@ -41,19 +41,19 @@ const base = process.env.PD_BROWSER_FIXTURE_URL || 'http://127.0.0.1:5238';
assert.equal(await page.locator('body').evaluate(n=>n.classList.contains('reader-focused')),true);
await page.keyboard.press('Escape');
assert.equal(await page.locator('#reader-focus').getAttribute('aria-pressed'),'false');
await readingControls();
// Integrated Review retains chapter-level navigation specifically inside Focus Reading.
await page.locator('#reader-focus').evaluate(n=>n.click());
await page.getByTitle('Read the next chapter',{exact:true}).filter({visible:true}).click();
await page.waitForURL(/chapterId=22/);
assert.match(await page.locator('.reader-page').textContent(),/Another chapter only/);
assert.doesNotMatch(await page.locator('.reader-page').textContent(),/First paragraph/);
// The chapter GET form deliberately stays inline; close the command menu before using it.
if (pwa) { const menu=await readingControls();await menu.locator('summary').click(); }
// The specialised chapter GET form stays inline within Focus Reading.
assert.equal(await page.locator('.manuscript-reader').getAttribute('data-focus'),'true');
await page.getByLabel('Chapter',{exact:true}).filter({visible:true}).selectOption('23');
await page.getByRole('button',{name:'Read',exact:true}).click();
await page.waitForURL(/chapterId=23/);
assert.match(await page.locator('.reader-empty').textContent(),/No accepted manuscript text/);
assert.equal(await page.getByRole('link',{name:'Next chapter →',exact:true}).count(),0);
await readingControls();
await page.getByTitle('Read the previous chapter',{exact:true}).filter({visible:true}).click();
await page.waitForURL(/chapterId=22/);
}

View File

@ -27,15 +27,14 @@ const base=process.env.PD_NARRATIVE_TEST_URL||'http://127.0.0.1:5238';
await p.locator('[data-focus-label]').evaluate(n=>n.textContent='Current Focus: Short');
assert(await toggle.evaluate(n=>{const label=n.querySelector('[data-focus-label]'),b=n.getBoundingClientRect(),l=label.getBoundingClientRect();return b.right-l.right<30;}),'chevron follows short label without unused width');
await open();await p.locator('[data-focus-search]').fill('Departure');await expectOpen();assert.equal(await p.locator('[data-focus-position] option').count(),2);
assert(await p.locator('[data-focus-step="-1"]').isDisabled());assert.equal(await p.locator('[data-focus-step="-1"]').getAttribute('aria-label'),'Previous Scene');
assert.equal(await p.locator('[data-focus-step="1"]').getAttribute('aria-label'),'Next Scene');
assert.equal(await p.locator('.pd-focus-picker [data-focus-step],.pd-focus-picker [data-global-focus]').count(),0);
let release;const gate=new Promise(r=>release=r);await p.route('**/NarrativeFocus/Set',async r=>{await gate;await r.continue();});
await p.locator('[data-focus-position]').selectOption('22/32');await expectOpen();assert.match(await p.locator('[data-narrative-status]').textContent(),/Updating/);release();await closed();await p.unroute('**/NarrativeFocus/Set');assert.match(await toggle.textContent(),/Departure/);
await open();await p.locator('[data-focus-search]').fill('');await p.locator('[data-focus-step="-1"]').click();await closed();
await open();await p.locator('[data-focus-step="1"]').click();await closed();
await open();await p.locator('[data-focus-search]').fill('');await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus=previous]').click();await closed();
await open();await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus=next]').click();await closed();
await open();await p.locator('[data-focus-recent]').selectOption('21/101');await closed();
await open();await p.locator('[data-focus-position]').selectOption('21/');await closed();
await open();await p.route('**/NarrativeFocus/Set',r=>r.fulfill({status:503,json:{message:'Temporary navigation failure. Please retry.'}}));await p.locator('[data-focus-step="1"]').click();await p.waitForFunction(()=>document.querySelector('[data-narrative-status]').textContent.includes('Temporary'));await expectOpen();assert(await p.locator('[data-focus-step="1"]').isEnabled());await p.unroute('**/NarrativeFocus/Set');await p.locator('[data-focus-step="1"]').click();await closed();
await open();await p.route('**/NarrativeFocus/Set',r=>r.fulfill({status:503,json:{message:'Temporary navigation failure. Please retry.'}}));await p.locator('[data-focus-position]').selectOption('21/31');await p.waitForFunction(()=>document.querySelector('[data-narrative-status]').textContent.includes('Temporary'));await expectOpen();assert(await p.locator('[data-focus-position]').isEnabled());await p.unroute('**/NarrativeFocus/Set');await p.locator('[data-focus-position]').selectOption('21/31');await closed();
assert(await toggle.evaluate(n=>n===document.activeElement),'successful selection returns keyboard focus');
await open();await p.locator('[data-focus-search]').focus();await p.keyboard.press('Escape');await closed();assert(await toggle.evaluate(n=>n===document.activeElement));
await open();await toggle.click();await closed();
@ -46,8 +45,8 @@ const base=process.env.PD_NARRATIVE_TEST_URL||'http://127.0.0.1:5238';
const after=await toggle.boundingBox();assert.equal(after.height,before.height);assert(after.width<=Math.max(before.width,448));
assert(await p.locator('[data-focus-label]').evaluate(n=>n.scrollWidth>n.clientWidth&&getComputedStyle(n).textOverflow==='ellipsis'));
await open();const box=await popup.boundingBox();assert(box.x>=0&&box.x+box.width<=width+1,'popup fits viewport');
const layout=await popup.evaluate(n=>{const elements=['[data-focus-search]','[data-focus-position]','.pd-focus-navigation','[data-focus-recent]'].map(s=>n.querySelector(s).getBoundingClientRect());const buttons=[...n.querySelectorAll('[data-focus-step]')].map(b=>{const r=b.getBoundingClientRect(),i=b.querySelector('svg').getBoundingClientRect();return {top:r.top,height:r.height,iconWidth:i.width,iconHeight:i.height};});return {aligned:elements.every(r=>Math.abs(r.left-elements[0].left)<1&&Math.abs(r.right-elements[0].right)<1),buttons};});
assert(layout.aligned,'popup fields and navigation row share horizontal edges');assert.equal(layout.buttons[0].top,layout.buttons[1].top);assert.equal(layout.buttons[0].height,layout.buttons[1].height);for(const b of layout.buttons){assert.equal(b.iconWidth,16);assert.equal(b.iconHeight,16);}
const layout=await popup.evaluate(n=>{const elements=['[data-focus-search]','[data-focus-position]','[data-focus-recent]'].map(s=>n.querySelector(s).getBoundingClientRect());const buttons=[...n.querySelectorAll('[data-focus-step]')].map(b=>{const r=b.getBoundingClientRect(),i=b.querySelector('svg').getBoundingClientRect();return {top:r.top,height:r.height,iconWidth:i.width,iconHeight:i.height};});return {aligned:elements.every(r=>Math.abs(r.left-elements[0].left)<1&&Math.abs(r.right-elements[0].right)<1),buttons};});
assert(layout.aligned,'popup fields and navigation row share horizontal edges');for(const b of layout.buttons){assert.equal(b.iconWidth,16);assert.equal(b.iconHeight,16);}
await p.screenshot({path:`/tmp/pd-focus-popup-${installed?'pwa':'browser'}-${width}-${theme}.png`});await p.keyboard.press('Escape');await closed();
}
await open();await p.goto(base+'/Timeline/Index?ProjectID=7&BookID=12');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await closed();

View File

@ -20,6 +20,7 @@ const base=process.env.PD_NARRATIVE_TEST_URL||'http://127.0.0.1:5238';
await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);
assert.equal(await p.evaluate(()=>window.PlotDirectorNarrativeFocus.state.sceneID),32,'Writer shares the scene explicitly opened in Timeline');
const openFocus=async()=>{if(await p.locator('[data-focus-toggle]').getAttribute('aria-expanded')!=='true')await p.locator('[data-focus-toggle]').click();};
const go=async()=>{const menu=p.locator('.pd-ribbon-panel:not([hidden]) .pd-ribbon-focus details[data-compact=true]');if(await menu.count()&&!await menu.evaluate(n=>n.open))await menu.locator('summary').click();await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus=go]').click();};
const state=()=>p.evaluate(()=>window.PlotDirectorNarrativeFocus.state);
const set=t=>p.evaluate(t=>window.PlotDirectorNarrativeFocus.set(t),t);
assert(await set({chapterID:21,sceneID:31}));
@ -34,8 +35,8 @@ const base=process.env.PD_NARRATIVE_TEST_URL||'http://127.0.0.1:5238';
await p.locator('#appBookMenu').click();const leaveDialog=p.waitForEvent('dialog');const leaveClick=p.locator('[data-app-book-choice="13"]').click().catch(error=>{if(!error.message.includes('ERR_ABORTED'))throw error;});const dialog=await leaveDialog;assert.equal(dialog.type(),'beforeunload');await dialog.dismiss();await leaveClick;assert.equal(new URL(p.url()).searchParams.get('bookId'),'12','unsaved objective protects a full book switch');assert.deepEqual(await p.locator('[data-focus-wizard]').evaluate(f=>Object.fromEntries(new FormData(f))),beforeEditor);
await p.locator('[data-focus-cancel]').click();await p.locator('[data-go-objective]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===31);
assert.equal(await p.locator('[data-objective-location]').textContent(),original);
await p.locator('[data-focus-toggle]').click();await openFocus();await p.locator('button[data-focus-step="1"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===101);await openFocus();await p.locator('button[data-focus-step="1"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32,'cross-chapter forward');
await openFocus();await p.locator('button[data-focus-step="-1"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===101);
await p.locator('[data-focus-toggle]').click();await openFocus();await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="next"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===101);await openFocus();await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="next"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32,'cross-chapter forward');
await openFocus();await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="previous"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===101);
await openFocus();await p.locator('[data-focus-search]').fill('Departure');assert.equal(await p.locator('[data-focus-position] option').count(),2);await p.locator('[data-focus-position]').selectOption('22/32');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32);await openFocus();await p.locator('[data-focus-search]').fill('');
await openFocus();await p.locator('[data-focus-recent]').selectOption('21/101');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===101);
const other=await c.newPage();await other.goto(url);await other.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await other.evaluate(()=>window.PlotDirectorNarrativeFocus.set({chapterID:22,sceneID:32}));await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32);
@ -49,6 +50,7 @@ const base=process.env.PD_NARRATIVE_TEST_URL||'http://127.0.0.1:5238';
await p.goto(base+'/fixture?page=floorplans');await p.waitForFunction(()=>document.querySelector('[data-floor-plan-initialized=true]'));
const focusBefore=await state();await p.locator('#floorPlanOccupancy').evaluate(n=>n.click());await p.locator('[data-occupancy-scene-select]').selectOption('101');await p.locator('[data-occupancy-next]').click();const scrubber=p.locator('.pd-scene-explorer input[type=range]');await scrubber.focus();await scrubber.press('ArrowLeft');assert.equal(await p.locator('[data-occupancy-scene-select]').inputValue(),'101');await scrubber.press('ArrowRight');assert.equal(await p.locator('[data-occupancy-scene-select]').inputValue(),'32');assert.equal((await state()).version,focusBefore.version,'floor-plan local scene navigation never writes focus');
const local=await p.locator('[data-occupancy-scene-select]').inputValue();await set({chapterID:21,sceneID:31});assert.equal(await p.locator('[data-occupancy-scene-select]').inputValue(),local,'global focus leaves local explorer alone');
const floorVersion=(await state()).version;await go();assert.equal(await p.locator('[data-occupancy-scene-select]').inputValue(),'31');assert.equal((await state()).version,floorVersion,'Go aligns local occupancy without writing focus');await p.locator('[data-occupancy-scene-select]').selectOption('32');
await p.locator('.pd-scene-explorer button').filter({hasText:'Set Current Focus Here'}).click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32);
await p.reload();await p.waitForFunction(()=>document.querySelector('[data-floor-plan-initialized=true]'));assert.equal(await p.locator('[data-occupancy-scene-select]').inputValue(),'32','local explorer restore');
for(const width of [1666,950])for(const theme of ['modern-light','modern-dark']){await p.setViewportSize({width,height:1050});await p.evaluate(theme=>window.PlotDirectorApplyApplicationTheme?.(theme),theme);await p.locator('#floorPlanOccupancy').evaluate(n=>n.click());await p.screenshot({path:`/tmp/pd-narrative-${installed?'pwa':'browser'}-${width}-${theme}.png`});}
@ -82,17 +84,18 @@ const base=process.env.PD_NARRATIVE_TEST_URL||'http://127.0.0.1:5238';
await p.locator('#rwTimeline').fill('31');await p.waitForTimeout(250);assert.equal((await state()).version,versionBefore,'Relationships scrubber is local');
const relationshipPosition=await p.locator('#rwTimeline').inputValue();await set({chapterID:22,sceneID:32});assert.equal(await p.locator('#rwTimeline').inputValue(),relationshipPosition);
const explorerBox=await p.locator('.rw-timeline .pd-scene-explorer').boundingBox(),timelineBox=await p.locator('.rw-timeline').boundingBox();assert(explorerBox.y+explorerBox.height<=timelineBox.y+timelineBox.height+1,'all Relationship Scene Explorer controls fit the timeline row');
const relationshipVersion=(await state()).version;await go();assert.equal(await p.locator('.pd-scene-explorer select').inputValue(),'32');assert.equal((await state()).version,relationshipVersion);
await p.screenshot({path:`/tmp/pd-narrative-${installed?'pwa':'browser'}-Relationships.png`});
for(const width of [950,650]){await p.setViewportSize({width,height:1050});await p.waitForTimeout(80);const fit=await p.locator('.rw-timeline').evaluate(row=>{const controls=row.querySelector('.pd-scene-explorer').getBoundingClientRect(),box=row.getBoundingClientRect();return controls.bottom<=box.bottom+1&&controls.right<=box.right+1;});assert(fit,'responsive Relationship Scene Explorer fits');await p.screenshot({path:`/tmp/pd-narrative-${installed?'pwa':'browser'}-Relationships-${width}.png`});}await p.setViewportSize({width:1666,height:1050});
const mapFixture=await(await c.request.get(base+'/map-story-fixture')).json();await p.route('**/Maps/Story?**',r=>r.fulfill({json:mapFixture}));
const mapFixture=await(await c.request.get(base+'/map-story-fixture')).json();mapFixture.scenes.push({...mapFixture.scenes[0],sceneID:31,bookID:12});await p.route('**/Maps/Story?**',r=>r.fulfill({json:mapFixture}));
await p.goto(base+'/fixture?page=maps&story=true');await p.waitForFunction(()=>window.PlotDirectorMapWorkspace);await p.locator('button[data-mode=story]').evaluate(n=>n.click());await p.waitForFunction(()=>window.PlotDirectorStoryOverlay?.data&&window.PlotDirectorNarrativeFocus);
const mapVersion=(await state()).version;await p.locator('#mapStoryLens').evaluate(n=>{n.value='scene';n.dispatchEvent(new Event('change',{bubbles:true}));});
await p.locator('#mapStoryScene').evaluate(n=>{n.value='90';n.dispatchEvent(new Event('change',{bubbles:true}));});assert.equal((await state()).version,mapVersion,'Maps scene selection is local');
const mapScene=await p.locator('#mapStoryScene').inputValue();await set({chapterID:21,sceneID:31});assert.equal(await p.locator('#mapStoryScene').inputValue(),mapScene,'global focus retains map position and journey context');
const mapScene=await p.locator('#mapStoryScene').inputValue();await set({chapterID:21,sceneID:31});assert.equal(await p.locator('#mapStoryScene').inputValue(),mapScene,'global focus retains map position and journey context');const mapFocusVersion=(await state()).version;await go();assert.equal(await p.locator('#mapStoryScene').inputValue(),'31');assert.equal((await state()).version,mapFocusVersion);
assert.match(await p.locator('#mapsDetailContent').innerText(),/Harbour morning/);
await p.screenshot({path:`/tmp/pd-narrative-${installed?'pwa':'browser'}-Maps.png`});
await p.goto(base+'/Timeline/Index?ProjectID=7');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.bookID===12);assert.match(await p.locator('[data-focus-label]').textContent(),/A Distant Shore/);await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-book]').selectOption('13');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.bookID===13);assert.equal((await state()).sceneID,null);assert.equal(await p.locator('.timeline-scene-card').count(),3,'focus book selection preserves project-wide Timeline');assert(!new URL(p.url()).searchParams.has('BookID'));await p.locator('[data-focus-book]').selectOption('12');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.bookID===12);
await p.locator('[data-focus-position]').selectOption('23/');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.chapterID===23);assert(await p.locator('button[data-focus-step="1"]').isDisabled(),'no following scene after the final empty chapter');assert(await p.locator('button[data-focus-step="-1"]').isEnabled());await openFocus();await p.locator('button[data-focus-step="-1"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32);await set({chapterID:21,sceneID:31});
await p.locator('[data-focus-position]').selectOption('23/');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.chapterID===23);assert(await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="next"]').isDisabled(),'no following scene after the final empty chapter');assert(await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="previous"]').isEnabled());await openFocus();await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="previous"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32);await set({chapterID:21,sceneID:31});
let reopened;if(installed){const d=await b.newBrowserCDPSession(),opened=c.waitForEvent('page');await d.send('PWA.launch',{manifestId:base+'/Projects',url:base+'/Timeline/Index?ProjectID=7'});reopened=await opened;await reopened.waitForLoadState();assert(await reopened.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else{reopened=await c.newPage();await reopened.goto(base+'/Timeline/Index?ProjectID=7');}await reopened.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.bookID===12);assert.equal(await reopened.evaluate(()=>window.PlotDirectorNarrativeFocus.state.sceneID),31,'reopened workspace restores its authorised focus book and location');await reopened.close();
const searchMilliseconds=await p.evaluate(()=>{const focus=window.PlotDirectorNarrativeFocus.state,original=focus.positions,input=document.querySelector('[data-focus-search]');focus.positions=Array.from({length:5000},(_,i)=>({chapterID:Math.floor(i/50)+1,chapterNumber:Math.floor(i/50)+1,chapterTitle:'Synthetic chapter',sceneID:20000+i,sceneNumber:i%50+1,label:`Chapter ${Math.floor(i/50)+1} · Scene ${i+1}`}));const start=performance.now();for(const value of ['Scene 499','']){input.value=value;input.dispatchEvent(new Event('input'));}const elapsed=performance.now()-start;focus.positions=original;input.value='';input.dispatchEvent(new Event('input'));return elapsed;});assert(searchMilliseconds<1500,'5000-scene header search remains responsive');console.log(`Focus search, 5000 scenes: ${searchMilliseconds.toFixed(1)}ms`);
assert.deepEqual(errors,[]);console.log(`PASS ${installed?'installed Chromium PWA':'Chromium'} narrative focus: independent objective/editor, Go to objective, manuscript neighbours across chapters, search, recency, windows, persistence, book/security scope, antiforgery, floor-plan local isolation/promotion/persistence unsaved inline/Review editor protection, stable Review refresh, local Relationships/Maps positions, keyboard scene stepping and themed responsive rendering`);

View File

@ -12,7 +12,7 @@ for(const [id,key]of [['reader-focus','minimise'],['reader-pause-toggle','play-c
await p.locator('#reader-focus').evaluate(n=>n.click());
assert.equal(await p.locator('[data-review-record]').evaluate(n=>window.PlotDirectorCommands.iconKey(n)),'comment-add');
if(installed)await p.locator('#ribbon-panel-writer [data-ribbon-icon=comment-add]').waitFor();
if(installed){const pair=p.locator('#ribbon-panel-writer [data-ribbon-icon^=chevron-] svg');await pair.first().waitFor();const styles=await pair.evaluateAll(ns=>ns.map(n=>{const s=getComputedStyle(n);return[s.width,s.height,s.strokeWidth,s.color]}));assert.equal(styles.length,2);assert.deepEqual(styles[0],styles[1]);}
if(installed){await p.evaluate(()=>window.PlotDirectorNarrativeFocus.set({chapterID:21,sceneID:101}));await p.waitForFunction(()=>{const icons=[...document.querySelectorAll('#ribbon-panel-writer [data-global-focus=previous] svg,#ribbon-panel-writer [data-global-focus=next] svg')];return icons.length===2&&getComputedStyle(icons[0]).color===getComputedStyle(icons[1]).color;});const pair=p.locator('#ribbon-panel-writer [data-global-focus=previous] svg,#ribbon-panel-writer [data-global-focus=next] svg');await pair.first().waitFor();const styles=await pair.evaluateAll(ns=>ns.map(n=>{const s=getComputedStyle(n);return[s.width,s.height,s.strokeWidth,s.color]}));assert.equal(styles.length,2);assert.deepEqual(styles[0],styles[1]);}
for(const theme of ['modern-light','modern-dark'])for(const width of [1666,800]){await p.setViewportSize({width,height:1050});await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);await p.evaluate(()=>new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r))));assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));fs.mkdirSync('/tmp/pd-icon-evidence',{recursive:true});await p.locator('[data-ribbon-shell]').screenshot({path:`/tmp/pd-icon-evidence/${installed?'pwa':'browser'}-${theme}-${width}.png`});}
console.log('PASS '+(installed?'installed PWA':'browser')+' icon mappings, stateful icons, scoped Help removal, Word badges, themes and widths');
}finally{await c.close();await b.close();fs.rmSync(profile,{recursive:true,force:true});}})().catch(e=>{console.error(e);process.exitCode=1});

View File

@ -145,10 +145,14 @@ internal static class ToolbarBrowserHost
if(name!="GetAsync")throw new NotSupportedException(name);
var filter=(TimelineFilterViewModel)args![0]!;
IReadOnlyList<Scene> scenes=[new(){SceneID=31,ChapterID=21,SceneNumber=1,SortOrder=1,SceneTitle="Arrival"},new(){SceneID=101,ChapterID=21,SceneNumber=2,SortOrder=2,SceneTitle="Second scene"},new(){SceneID=32,ChapterID=22,SceneNumber=1,SortOrder=1,SceneTitle="Departure"}];
return Task.FromResult<TimelineViewModel?>(new(){Project=new(){ProjectID=7,ProjectName="The Glass Harbour"},SelectedBookID=filter.BookID,SelectedSceneID=filter.SelectedSceneID,Filter=filter,
return Task.FromResult<TimelineViewModel?>(new(){Project=new(){ProjectID=7,ProjectName="The Glass Harbour"},SelectedBookID=filter.BookID,SelectedSceneID=filter.SelectedSceneID,SelectedScene=filter.SelectedSceneID is int selectedScene?new(){SceneID=selectedScene,ChapterID=scenes.First(s=>s.SceneID==selectedScene).ChapterID,SceneTitle=scenes.First(s=>s.SceneID==selectedScene).SceneTitle}:null,Filter=filter,
Settings=new(){ShowSceneCards=true},OrderedScenes=scenes,MatchingSceneIDs=scenes.Select(s=>s.SceneID).ToHashSet(),
Books=[new(){Book=new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore"},Chapters=[new(){Chapter=new(){ChapterID=21,BookID=12,ChapterNumber=1,ChapterTitle="The crossing"},Scenes=scenes.Where(s=>s.ChapterID==21).ToArray()},new(){Chapter=new(){ChapterID=22,BookID=12,ChapterNumber=2,ChapterTitle="The harbour"},Scenes=scenes.Where(s=>s.ChapterID==22).ToArray()}]}]});
}));
builder.Services.AddSingleton(FixtureProxy<IChapterService>((name,args)=>{
if(name!="GetDetailAsync")throw new NotSupportedException(name);
var id=(int)args![0]!;return Task.FromResult<ChapterDetailViewModel?>(new(){Project=new(){ProjectID=7,ProjectName="The Glass Harbour"},Book=new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore"},Chapter=new(){ChapterID=id,BookID=12,ChapterNumber=id==21?1:2,ChapterTitle="Focused chapter"}});
}));
builder.Services.AddSingleton<IToolbarPreferenceRepository, ToolbarMemoryPreferences>();
builder.Services.AddScoped(services => ManuscriptReaderTests.FixtureService(() =>
services.GetRequiredService<IHttpContextAccessor>().HttpContext!.Request.Query["reader-error"] == "true"
@ -541,12 +545,12 @@ internal static class ToolbarBrowserHost
new() { LocationID = 4, ProjectID = 7, LocationName = "Annex", ParentLocationID = 2, ParentLocationName = "Building", Depth = 1, LocationPath = "Building / Annex" }
] },
"FloorPlans" => new FloorPlanListViewModel { Project = project },
"PlotLineWorkspace" => new PlotLineWorkspaceViewModel { Project = project },
"PlotLineWorkspace" => new PlotLineWorkspaceViewModel { Project = project,SelectedBookID=12,PlotLines=[new(){Line=new(){PlotLineID=1,PlotLineName="Fixture line",Colour="#487b70"},IsSelected=true}],AssociationScenes=[new(){SceneID=31,BookID=12,SceneTitle="Arrival",ChapterNumber=1,SceneNumber=1,NarrativeOrder=1}],Scenes=[new(){SceneID=31,SceneTitle="Arrival",ChapterNumber=1,SceneNumber=1,Memberships=[new(){PlotLineID=1,PlotLineName="Fixture line",Colour="#487b70",Contributions=[new(){ThreadTitle="Fixture thread",CanonicalTitle="Fixture contribution"}]}]}] },
"Warnings" => new WarningDashboardViewModel { Project = project },
"Archives" => new ArchivedItemsViewModel { ProjectID = project.ProjectID, Items = context.Request.Query["context"] == "objects" ? [new ArchivedItem { EntityType = "Character", EntityID = 71, DisplayName = "Archived context fixture", UpdatedDate = DateTime.UtcNow }] : [] },
"PlotThreads" => new PlotThreadListViewModel { Project = project },
"StoryCalendar" => calendar,
"StoryPoint" => new StoryPointViewModel { Project = project },
"StoryPoint" => new StoryPointViewModel { Project = project, Books=[model.Book!], Chapters=[new(){ChapterID=21,BookID=12,ChapterNumber=1,ChapterTitle="The crossing"},new(){ChapterID=22,BookID=12,ChapterNumber=2,ChapterTitle="The harbour"}], Scenes=[new(){SceneID=31,ChapterID=21,SceneNumber=1,SceneTitle="Arrival"},new(){SceneID=101,ChapterID=21,SceneNumber=2,SceneTitle="Second scene"},new(){SceneID=32,ChapterID=22,SceneNumber=1,SceneTitle="Departure"}] },
"ProjectMetrics" => new ProjectSceneMetricsViewModel { Project = project },
"Analytics" => new AnalyticsViewModel { Project = project },
"Dynamics" => new StoryDynamicsViewModel { Project = project },
@ -562,6 +566,8 @@ internal static class ToolbarBrowserHost
route.Values["action"] = viewAction;
model.ActiveSection = desktopPage switch { "StoryBible" => "Story Bible", "PlotLineWorkspace" => "Plot Lines", "PlotThreads" => "Threads", "StoryCalendar" => "Calendar", "StoryPoint" => "At This Point", "ProjectMetrics" => "Metrics", "Analytics" or "Dynamics" => "Health", _ => desktopPage };
surface = await Render($"{viewController}/{viewAction}", pageModel);
if(desktopPage=="PlotLineWorkspace")writerScripts+="<script src='/js/plot-line-workspace.js'></script>";
if(desktopPage=="StoryPoint")writerScripts+="<script src='/js/story-point.js'></script>";
menu = await Render("Shared/_ApplicationShell");
}
var record = context.Request.Query["record"].ToString();
@ -637,7 +643,7 @@ internal static class ToolbarBrowserHost
PlotLine.TagHelpers.RibbonContributionTagHelper.Snapshot(context).WriteTo(contributionWriter, System.Text.Encodings.Web.HtmlEncoder.Default);
var contributions = contributionWriter.ToString();
context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.WriteAsync("<!doctype html><html lang='en' data-app-theme='" + initialTheme + "' data-theme='" + (initialTheme.EndsWith("dark") ? "dark" : "light") + "'><head><script src='/js/application-display-mode.js'></script><link rel='manifest' href='/site.webmanifest'><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-navigation.css'><link rel='stylesheet' href='/css/application-shell.css'><link rel='stylesheet' href='/css/record-workspace.css'><link rel='stylesheet' href='/css/application-context-menu.css'><link rel='stylesheet' href='/css/plot-line-workspace.css'><link rel='stylesheet' href='/css/onboarding.css'></head><body data-pd-user-id='" + context.User.FindFirstValue(ClaimTypes.NameIdentifier) + "' data-pd-project-id='7' class='app-layout'><header class='pd-application-header'>" + menu + toolbar + "</header><template data-pwa-initial-contributions>" + contributions + "</template><link rel='stylesheet' href='/css/scene-explorer.css'><script src='/js/scene-explorer.js'></script><script src='/js/narrative-focus.js' defer></script><script src='/js/application-page-context.js'></script><div class='plotline-help-main'><div class='container-fluid plotline-shell " + (recordLayout is null ? "pd-dashboard-shell" : $"pd-record-canvas pd-record-canvas--{recordLayout}") + "'><main data-pwa-page-content class='pb-3'>" + surface + "</main><script>window.PlotDirectorPageContext?.activate();</script></div></div><script src='/lib/bootstrap/dist/js/bootstrap.bundle.min.js'></script><script src='/js/application-navigation.js'></script><script src='/js/application-toolbar.js'></script>" + appearanceScript + "<script src='/js/application-shell.js'></script><script src='/js/application-theme-sync.js'></script><script src='/js/site.js'></script><script src='/js/application-pwa.js'></script><script src='/js/application-context-menu.js'></script>" + writerScripts + "</body></html>");
await context.Response.WriteAsync("<!doctype html><html lang='en' data-app-theme='" + initialTheme + "' data-theme='" + (initialTheme.EndsWith("dark") ? "dark" : "light") + "'><head><script src='/js/application-display-mode.js'></script><link rel='manifest' href='/site.webmanifest'><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-navigation.css'><link rel='stylesheet' href='/css/application-shell.css'><link rel='stylesheet' href='/css/record-workspace.css'><link rel='stylesheet' href='/css/application-context-menu.css'><link rel='stylesheet' href='/css/plot-line-workspace.css'><link rel='stylesheet' href='/css/onboarding.css'></head><body data-pd-user-id='" + context.User.FindFirstValue(ClaimTypes.NameIdentifier) + "' data-pd-project-id='7' class='app-layout'><header class='pd-application-header'>" + menu + toolbar + "</header><template data-pwa-initial-contributions>" + contributions + "</template><link rel='stylesheet' href='/css/scene-explorer.css'><script src='/js/scene-explorer.js'></script><script src='/js/narrative-focus.js' defer></script><script src='/js/narrative-focus-workspaces.js' defer></script><script src='/js/application-page-context.js'></script><div class='plotline-help-main'><div class='container-fluid plotline-shell " + (recordLayout is null ? "pd-dashboard-shell" : $"pd-record-canvas pd-record-canvas--{recordLayout}") + "'><main data-pwa-page-content class='pb-3'>" + surface + "</main><script>window.PlotDirectorPageContext?.activate();</script></div></div><script src='/lib/bootstrap/dist/js/bootstrap.bundle.min.js'></script><script src='/js/application-navigation.js'></script><script src='/js/application-toolbar.js'></script>" + appearanceScript + "<script src='/js/application-shell.js'></script><script src='/js/application-theme-sync.js'></script><script src='/js/site.js'></script><script src='/js/application-pwa.js'></script><script src='/js/application-context-menu.js'></script>" + writerScripts + "</body></html>");
});
app.MapHub<PlotLine.Hubs.WordCompanionFollowHub>("/hubs/word-companion-follow");
await app.RunAsync();

View File

@ -2548,7 +2548,7 @@
const sceneStorageKey=`pd.scene-explorer.floorplan:${document.body.dataset.pdUserId}:${workspace.dataset.floorPlanId}`;
try{const saved=sessionStorage.getItem(sceneStorageKey);if(saved&&[...occupancySceneSelect.options].some(o=>o.value===saved)&&!new URLSearchParams(location.search).has('storySceneId'))occupancySceneSelect.value=saved;}catch{}
occupancyExplorer=window.PlotDirectorSceneExplorer.create({host:occupancySceneSelect.closest('.floor-plan-occupancy-scene-row'),select:occupancySceneSelect,previous:occupancyPrev,next:occupancyNext,listenButtons:false,
positions:()=>[...occupancySceneSelect.options].map(o=>({id:o.value,label:o.textContent})),selected:()=>occupancySceneSelect.value,
reveal:()=>{if(layoutNeedsSave)throw Error('Save or discard the current floor-plan edits before displaying Current Focus.');setFloorPlanMode('occupancy');},positions:()=>[...occupancySceneSelect.options].map(o=>({id:o.value,label:o.textContent})),selected:()=>occupancySceneSelect.value,
change:p=>{occupancySceneSelect.value=String(p.id);try{sessionStorage.setItem(sceneStorageKey,String(p.id));}catch{}applyOccupancySceneFloor();refreshOccupancyTrays();}});
}
occupancyPrev?.addEventListener("click", () => moveOccupancyScene(-1));

View File

@ -21,10 +21,11 @@
}
<div class="reader-mode-controls"><a data-pwa-context="Reading &amp; Review" data-pwa-label="Reading mode" title="Switch between reading and review mode" asp-controller="Writer" asp-action="Review" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@Model.Chapter?.ChapterID" asp-route-reading="@(!Model.ReadingMode)">@(Model.ReadingMode?"Review mode":"Reading mode")</a></div>
<a data-reader-exit-focus hidden="@(!Model.FocusReading)" class="btn btn-outline-secondary" asp-controller="Writer" asp-action="Review" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@Model.Chapter?.ChapterID" asp-route-reading="@Model.ReadingMode">Exit Focus Reading</a>
<nav class="reader-controls" aria-label="Chapter navigation">
<nav class="reader-controls" aria-label="Reading controls">
<div class="reader-chapter-navigation" aria-label="Chapter navigation in focused reading">
@if (Model.PreviousId is int previous)
{ <a id="reader-prev" data-pwa-context="Reading &amp; Review" data-pwa-label="Previous" title="Read the previous chapter" class="btn btn-outline-secondary" asp-controller="@routeController" asp-action="@routeAction" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@previous" asp-route-focus="@Model.FocusReading" asp-route-reading="@Model.ReadingMode" rel="prev">← Previous chapter</a> }
else { <button id="reader-prev" type="button" data-pwa-context="Reading &amp; Review" data-pwa-label="Previous" title="Read the previous chapter" class="btn btn-outline-secondary" disabled>← Previous chapter</button> }
{ <a id="reader-prev" data-pwa-label="Previous" title="Read the previous chapter" class="btn btn-outline-secondary" asp-controller="@routeController" asp-action="@routeAction" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@previous" asp-route-focus="@Model.FocusReading" asp-route-reading="@Model.ReadingMode" rel="prev">← Previous chapter</a> }
else { <button id="reader-prev" type="button" data-pwa-label="Previous" title="Read the previous chapter" class="btn btn-outline-secondary" disabled>← Previous chapter</button> }
<form method="get" asp-controller="@routeController" asp-action="@routeAction">
<input type="hidden" name="reading" value="@Model.ReadingMode.ToString().ToLowerInvariant()" />
<input type="hidden" name="focus" value="@Model.FocusReading.ToString().ToLowerInvariant()" />
@ -37,8 +38,9 @@
<button class="btn btn-outline-secondary" type="submit">Read</button>
</form>
@if (Model.NextId is int next)
{ <a id="reader-next" data-pwa-context="Reading &amp; Review" data-pwa-label="Next" title="Read the next chapter" class="btn btn-outline-secondary" asp-controller="@routeController" asp-action="@routeAction" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@next" asp-route-focus="@Model.FocusReading" asp-route-reading="@Model.ReadingMode" rel="next">Next chapter →</a> }
else { <button id="reader-next" type="button" data-pwa-context="Reading &amp; Review" data-pwa-label="Next" title="Read the next chapter" class="btn btn-outline-secondary" disabled>Next chapter →</button> }
{ <a id="reader-next" data-pwa-label="Next" title="Read the next chapter" class="btn btn-outline-secondary" asp-controller="@routeController" asp-action="@routeAction" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@next" asp-route-focus="@Model.FocusReading" asp-route-reading="@Model.ReadingMode" rel="next">Next chapter →</a> }
else { <button id="reader-next" type="button" data-pwa-label="Next" title="Read the next chapter" class="btn btn-outline-secondary" disabled>Next chapter →</button> }
</div>
<button type="button" class="btn btn-outline-secondary" id="reader-focus" data-pwa-context="Reading &amp; Review" data-pwa-keep-visible="true" title="Enter or exit Focused Reading" aria-pressed="@Model.FocusReading.ToString().ToLowerInvariant()" hidden>Focus reading</button>
</nav>
@if(Model.IntegratedReview){<button type="button" class="btn btn-outline-primary" data-review-record data-pwa-context="Annotations" data-pwa-label="Add annotation" title="Record a chapter, verified scene or selected passage annotation">Record an observation</button>}

View File

@ -8,7 +8,7 @@
var selectedCategory = ApplicationRibbon.ActiveCategory(controller, Model.ActiveSection);
var appearance = ViewData["ApplicationAppearance"] as ApplicationAppearance ?? new();
}
<section class="pd-shell" aria-label="Application commands" data-app-navigation data-ribbon-shell data-collapsed="@appearance.RibbonCollapsed.ToString().ToLowerInvariant()">
<section class="pd-shell" aria-label="Application commands" data-app-navigation data-ribbon-shell data-workspace-controller="@controller" data-workspace-action="@action" data-collapsed="@appearance.RibbonCollapsed.ToString().ToLowerInvariant()">
<div class="pd-titlebar">
<a class="pd-brand" asp-controller="Projects" asp-action="Index">PlotDirector<span class="pd-brand-mark" aria-hidden="true">.</span></a>
<partial name="_ApplicationToolbar" model="Model" />
@ -187,6 +187,7 @@
<div class="pd-page-context-controls" data-pwa-context-controls></div>
</div>
}
<partial name="_FocusRibbon" />
</div>
}
</div>

View File

@ -0,0 +1,8 @@
@* One shared global navigation group; workspace adapters only control Go to Focus. *@
<div class="pd-ribbon-group pd-ribbon-focus" role="group" aria-label="Focus">
<div class="pd-ribbon-commands">
@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")}){
<button type="button" class="pd-ribbon-command" data-global-focus="@command.Item1" data-ribbon-icon="@command.Item3" title="@command.Item4" aria-label="@command.Item4" disabled><svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon(command.Item3).IconPath" /></svg><span>@command.Item2</span></button>
}
</div><span class="pd-ribbon-group-label">Focus</span>
</div>

View File

@ -189,6 +189,7 @@
<template data-pwa-initial-contributions>@PlotLine.TagHelpers.RibbonContributionTagHelper.Snapshot(Context)</template>
<script src="~/js/scene-explorer.js" asp-append-version="true"></script>
<script src="~/js/narrative-focus.js" asp-append-version="true" defer></script>
<script src="~/js/narrative-focus-workspaces.js" asp-append-version="true" defer></script>
<script src="~/js/application-page-context.js" asp-append-version="true"></script>
}
@if (User.Identity?.IsAuthenticated == true)

View File

@ -7,7 +7,6 @@
<p class="small">Current narrative location. Saved objectives and local Scene Explorers keep their own targets.</p>
<label>Find chapter or scene<input type="search" data-focus-search placeholder="Search this book" autocomplete="off" /></label>
<label>Chapter / scene<select data-focus-position aria-label="Current narrative chapter or scene"></select></label>
<div class="button-row pd-focus-navigation" role="group" aria-label="Navigate scenes"><button class="btn btn-outline-secondary btn-sm" type="button" data-focus-step="-1" aria-label="Previous Scene" title="Previous scene in manuscript order"><svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@RibbonPresentation.Icons.Single(x=>x.Key=="chevron-left").IconPath" /></svg> Previous</button><button class="btn btn-outline-secondary btn-sm" type="button" data-focus-step="1" aria-label="Next Scene" title="Next scene in manuscript order">Next <svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@RibbonPresentation.Icons.Single(x=>x.Key=="chevron-right").IconPath" /></svg></button></div>
<label>Recent focus<select data-focus-recent><option value="">Recent chapter / scene…</option></select></label>
<p role="status" data-narrative-status></p>
@Html.AntiForgeryToken()

View File

@ -368,7 +368,7 @@ html[data-app-theme] .app-layout :is(
background-color: var(--pd-section);
border-color: var(--pd-border);
}
html[data-app-theme] .app-layout :is(.workspace-heading .button-row, .timeline-filter, .pd-focus-navigation) .btn {
html[data-app-theme] .app-layout :is(.workspace-heading .button-row, .timeline-filter) .btn {
--bs-btn-color: var(--pd-text);
--bs-btn-bg: transparent;
--bs-btn-border-color: var(--pd-border);
@ -385,17 +385,17 @@ html[data-app-theme] .app-layout :is(.workspace-heading .button-row, .timeline-f
border-color: var(--bs-btn-border-color);
color: var(--bs-btn-color);
}
html[data-app-theme] .app-layout :is(.workspace-heading .button-row, .timeline-filter, .pd-focus-navigation) .btn:is(:hover, :focus-visible) {
html[data-app-theme] .app-layout :is(.workspace-heading .button-row, .timeline-filter) .btn:is(:hover, :focus-visible) {
background: var(--bs-btn-hover-bg);
border-color: var(--bs-btn-hover-border-color);
color: var(--bs-btn-hover-color);
}
html[data-app-theme] .app-layout :is(.workspace-heading .button-row, .timeline-filter, .pd-focus-navigation) .btn:is(:active, .active, .show) {
html[data-app-theme] .app-layout :is(.workspace-heading .button-row, .timeline-filter) .btn:is(:active, .active, .show) {
background: var(--bs-btn-active-bg);
border-color: var(--bs-btn-active-border-color);
color: var(--bs-btn-active-color);
}
html[data-app-theme] .app-layout :is(.workspace-heading .button-row, .timeline-filter, .pd-focus-navigation) .btn:disabled {
html[data-app-theme] .app-layout :is(.workspace-heading .button-row, .timeline-filter) .btn:disabled {
background: var(--bs-btn-disabled-bg);
border-color: var(--bs-btn-disabled-border-color);
color: var(--bs-btn-disabled-color);

View File

@ -30,3 +30,7 @@ body:has(.manuscript-reader[data-focus="true"]) { overflow: hidden; }
.manuscript-reader{container-type:inline-size}
@container(max-width:800px){.reader-controls{grid-template-columns:1fr 1fr}.reader-controls form{grid-column:1/-1;grid-row:1}.reader-controls #reader-focus{grid-column:1/-1}}
.manuscript-reader[data-focus=true] .reader-live-controls label,.manuscript-reader[data-focus=true] .reader-live-controls:has(#reader-apply-update[hidden]){display:none}
.reader-chapter-navigation{display:contents;}
.manuscript-reader[data-integrated-review=true][data-focus=false] .reader-chapter-navigation{display:none;}
.manuscript-reader[data-integrated-review=true][data-focus=false]>.reader-controls{display:flex;margin-block:.5rem;}

View File

@ -9,9 +9,8 @@
.pd-narrative-focus>.dropdown-toggle::after{flex-shrink:0;}
.pd-focus-picker{width:min(32rem,88vw);padding:1rem;}
.pd-focus-picker label{display:block;margin-block:.75rem;}
.pd-focus-navigation{flex-wrap:nowrap;gap:.5rem;margin-block:.75rem;}
.pd-focus-navigation .btn{display:inline-flex;align-items:center;justify-content:center;gap:.25rem;}
.pd-focus-navigation .pd-icon{width:16px;height:16px;}
.pd-ribbon-focus{order:90;}
.pd-ribbon-panel .pd-ribbon-group[aria-label="Help"]{order:100;}
.pd-focus-picker select,.pd-focus-picker input{display:block;width:100%;min-width:0;background:var(--bs-body-bg);color:var(--bs-body-color);border:1px solid var(--bs-border-color);border-radius:.25rem;padding:.3rem;}
@media(max-width:900px){.pd-narrative-focus{max-width:12rem;}}

View File

@ -172,11 +172,12 @@
if(!response.ok||response.redirected)throw Error('Travel context could not be saved. Check access/subscription, then try again.');await load(true);
}catch(error){const message=document.createElement('p');message.setAttribute('role','alert');message.textContent=error.message;e.target.append(message);}finally{button.disabled=false;}
});
const sceneExplorer = window.PlotDirectorSceneExplorer.create({host:$('mapStoryScrubberRow'),
const sceneExplorer = window.PlotDirectorSceneExplorer.create({focusAdapter:false,host:$('mapStoryScrubberRow'),
positions:()=>visibleScenes().map(s=>({id:s.sceneID,label:sceneLabel(s)})),selected:()=>state.sceneID,
change:p=>chooseScene(Number(p.id)),select:$('mapStoryScene'),range:$('mapStoryScrubber'),
previous:$('mapStoryPrevious'),next:$('mapStoryNext'),output:$('mapStoryScrubberContext'),
listenSelect:false,listenButtons:false,enabled:()=>active()&&!!data&&state.lens==='scene'});
window.PlotDirectorFocusWorkspace.register({canGo:focus=>focus.projectID===Number(boot.projectId)&&!!focus.sceneID,go:async focus=>{if(W.dirty||W.busy||window.PlotDirectorMapAppearance?.adjusting||svg.classList.contains('placing'))throw Error('Finish or save the current map edit before displaying Current Focus.');W.setMode('story');if(W.mode!=='story')throw Error('Finish the current map operation before displaying Current Focus.');await load();if(!scenes.has(focus.sceneID))throw Error('The focused scene is not available on this map or scenario. Your map filters and journey context are retained.');state.lens='scene';state.bookID=focus.bookID;state.chapterID=0;state.sceneID=focus.sceneID;$('mapStoryLens').value='scene';$('mapStoryBook').value=String(focus.bookID);$('mapStorySceneSearch').value='';controls();scopeOptions();chooseScene(focus.sceneID);}});
$('mapStoryCoverage').onclick=()=>{state.selection={kind:'gaps'};renderDetails();};
$('mapStoryPrevious').onclick=()=>navigateStep(-1);$('mapStoryNext').onclick=()=>navigateStep(1);$('mapStoryLayer').onclick=()=>{state.visible=!state.visible;refresh();};$('mapStoryGaps').onclick=()=>{state.selection={kind:'gaps'};renderDetails();document.querySelector('#mapsStoryToolbar details').open=false;};$('mapStoryObservations').onclick=()=>{state.selection={kind:'observations'};renderDetails();document.querySelector('#mapsStoryToolbar details').open=false;};$('mapStoryRefresh').onclick=()=>load(true);
window.addEventListener('pd-map-saved',()=>{requestVersion++;loadRequest=null;data=null;loading=false;error='';});

View File

@ -41,5 +41,6 @@
if(!canChange()){offer('Current focus changed. Your open editors retain their original target.');return;}
void apply(focus);
});
window.PlotDirectorFocusWorkspace.register({canGo:focus=>focus.bookID===Number(document.querySelector('.manuscript-reader')?.dataset.bookId)&&!!focus.chapterID,go:async focus=>{pending=focus;if(!canChange()){offer('Save or cancel open editors and close dialogs before changing the displayed chapter.');return;}await apply(focus);}});
window.addEventListener('pagehide',()=>{++generation;request?.abort();});
})();

View File

@ -0,0 +1,23 @@
// Explicit presentation adapters. None of these actions writes narrative focus.
(() => {
'use strict';
const registry=window.PlotDirectorFocusWorkspace,shell=document.querySelector('[data-workspace-controller]');if(!registry||!shell)return;
const controller=shell.dataset.workspaceController,action=shell.dataset.workspaceAction;
function offer(message,label,perform){let output=document.querySelector('[data-focus-workspace-status]');if(!output){output=document.createElement('p');output.dataset.focusWorkspaceStatus='';output.setAttribute('role','status');shell.after(output);}output.replaceChildren(document.createTextNode(message+' '));if(perform){const button=document.createElement('button');button.type='button';button.className='btn btn-sm btn-outline-secondary';button.textContent=label;button.addEventListener('click',perform);output.append(button);}}
const sceneURL=focus=>{const url=new URL('/Timeline/Index',location.origin);url.search=new URLSearchParams({projectId:focus.projectID,bookId:focus.bookID,selectedSceneId:focus.sceneID,retainNarrativeFocus:true});return url;};
if(controller==='Books'&&action==='Details')registry.register({canGo:focus=>!!focus.chapterID,go:focus=>location.assign(`/Chapters/Details/${focus.chapterID}?retainNarrativeFocus=true`)});
if(controller==='Timeline'&&action==='Index')registry.register({canGo:focus=>!!focus.sceneID,go:focus=>{
const card=document.querySelector(`.timeline-scene-card[data-scene-id="${focus.sceneID}"]`);
if(!card||card.hidden||!card.getClientRects().length){offer('Current Focus is hidden by this Timeline view. Your filters are retained.','Reveal focused scene',()=>location.assign(sceneURL(focus)));return;}
card.scrollIntoView({block:'center',inline:'center'});
const url=new URL(location.href);for(const key of [...url.searchParams.keys()])if(['selectedsceneid','navigatefocus','retainnarrativefocus'].includes(key.toLowerCase()))url.searchParams.delete(key);
url.searchParams.set('selectedSceneId',focus.sceneID);url.searchParams.set('retainNarrativeFocus','true');location.assign(url);
}});
const plotForm=document.getElementById('plot-workspace-form');
if(plotForm)registry.register({canGo:focus=>!!focus.sceneID&&Number(plotForm.querySelector('[name=projectId]')?.value)===focus.projectID,go:focus=>{
const book=Number(plotForm.querySelector('[name=bookId]')?.value);if(book&&book!==focus.bookID){offer('Current Focus belongs to another book. Your weave scope is retained.','Reveal in Timeline',()=>location.assign(sceneURL(focus)));return;}
const card=[...document.querySelectorAll('[data-plot-scene]')].find(n=>n.querySelector(`[data-scene-inspector="${focus.sceneID}"]`));
if(!card||card.hidden){offer('Current Focus is outside the visible weave or hidden by its filters. Your selected plot lines and search are retained.','Inspect focused scene',()=>{const trigger=document.createElement('button');trigger.type='button';trigger.dataset.sceneInspector=focus.sceneID;trigger.hidden=true;document.body.append(trigger);trigger.click();trigger.remove();});return;}
document.querySelectorAll('.plot-weave-focus').forEach(n=>n.classList.remove('plot-weave-focus'));card.classList.add('plot-weave-focus');card.scrollIntoView({block:'nearest',inline:'center'});card.querySelector('[data-scene-inspector]')?.focus({preventScroll:true});
}});
})();

View File

@ -20,10 +20,11 @@
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))));
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);
root.querySelectorAll('[data-focus-step]').forEach(b=>{const direction=Number(b.dataset.focusStep);const available=at>=0?(direction<0?at>0:at<scenes.length-1):chapterAt>=0?(hasChapterScenes||state.positions.some((p,i)=>p.sceneID&&(direction<0?i<chapterAt:i>chapterAt))):scenes.length>0;b.disabled=busy||!available;});
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<scenes.length-1):chapterAt>=0?(hasChapterScenes||state.positions.some((p,i)=>p.sceneID&&(direction<0?i<chapterAt:i>chapterAt))):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);});
select.disabled=recent.disabled=busy||!state.bookID;if(bookPicker){bookPicker.value=String(state.bookID||'');bookPicker.disabled=busy;}
}
function publish(){render();try{if(state.bookID)localStorage.setItem(scopeKey,String(state.bookID));}catch{}
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');}
const locationLabel=document.querySelector('[data-writer-global-location]');if(locationLabel)locationLabel.textContent='Current narrative location: '+currentLabel();
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;}
@ -42,11 +43,15 @@
state=result;publish();status.textContent='Current focus updated. Your workspace and saved targets are retained.';
try{localStorage.setItem(notificationKey(),String(state.version));}catch{}
dismiss(fromPicker&&document.activeElement===document.body);return true;
}catch(error){status.textContent=error.message;return false;}finally{busy=false;render();if(refreshQueued){refreshQueued=false;void refresh();}}
}catch(error){status.textContent=error.message;if(toggle.getAttribute('aria-expanded')!=='true')showWorkspaceMessage(error.message);return false;}finally{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));
root.querySelectorAll('[data-focus-step]').forEach(b=>b.addEventListener('click',()=>void set({direction:Number(b.dataset.focusStep)})));
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);}));
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||!adapter?.canGo(state))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();}}}));
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',e=>{if(e.persisted)void refresh();});root.addEventListener('shown.bs.dropdown',()=>void refresh());

View File

@ -1,9 +1,11 @@
// Local presentation only. The optional promotion callback is the sole explicit global write path.
(() => {
'use strict';
let adapter=null;
window.PlotDirectorFocusWorkspace={register(value){adapter=value;window.dispatchEvent(new Event('plotdirector:focus-adapter-ready'));},get adapter(){return adapter;}};
window.PlotDirectorSceneExplorer = {
create({ host, positions, selected, change, select = null, range = null, previous = null, next = null,
output = null, enabled = () => true, listenSelect = true, listenRange = true, listenButtons = true }) {
output = null, enabled = () => true, focusAdapter = true, reveal = () => {}, listenSelect = true, listenRange = true, listenButtons = true }) {
const controls = document.createElement('div'); controls.className = 'pd-scene-explorer';
controls.setAttribute('role', 'group'); controls.setAttribute('aria-label', 'Local Scene Explorer');
const make = (tag, text) => { const node = document.createElement(tag); if (text) node.textContent = text; controls.append(node); return node; };
@ -48,6 +50,7 @@
if (listenSelect) select.addEventListener('change', () => choose(select.value));
if (listenRange) range.addEventListener('input', () => { const item = positions()[Number(range.value)]; if (item) choose(item.id); });
if (listenButtons) { previous.addEventListener('click', () => step(-1)); next.addEventListener('click', () => step(1)); }
if(focusAdapter)window.PlotDirectorFocusWorkspace.register({canGo:focus=>host.isConnected&&positions().some(p=>p.isScene!==false&&String(p.id)===String(focus.sceneID)),go:focus=>{reveal();choose(focus.sceneID);}});
sync();
return { sync, choose, step, destroy:()=>events.abort(), get position() { return items[index] || null; }, controls, hint };
}

View File

@ -63,5 +63,6 @@
filterScenes(); scene.value = id;
load(false);
});
window.PlotDirectorFocusWorkspace.register({canGo:focus=>scenes.some(s=>Number(s.value)===focus.sceneID),go:async focus=>{const target=scenes.find(s=>Number(s.value)===focus.sceneID),parent=chapters.find(c=>c.value===target?.dataset.chapter);if(!parent)throw Error('The focused scene is unavailable in this snapshot.');book.value=parent.dataset.book;filterChapters();chapter.value=parent.value;filterScenes();scene.value=target.value;await load();}});
filterChapters();
})();