Synchronise chapter and accepted Review focus targets reliably
This commit is contained in:
parent
f6850d5f7a
commit
e2fd8d455b
44
Docs/Navigation/FocusSynchronisationCorrection.md
Normal file
44
Docs/Navigation/FocusSynchronisationCorrection.md
Normal file
@ -0,0 +1,44 @@
|
||||
# Focus synchronisation correction — audit before behavioural changes
|
||||
|
||||
## Authoritative path
|
||||
|
||||
`NarrativeFocus` and its Dapper stored procedures remain authoritative per user/project/book. `NarrativeFocus_Set` in migration 294 steps via stable SceneID and `NarrativeSceneOrder.BookSceneIndex`, including chapter boundaries; it does not index accepted paragraphs. Header selection, recent selection and ribbon Previous/Next all call the same browser `set`, POST once, publish the returned stable IDs/version once after success, and notify other windows. Read refreshes use an epoch guard and queue behind commits. Explicit document navigation is adopted by `NarrativeNavigationFilter`; presentation-only chapter destinations must retain focus.
|
||||
|
||||
## Findings
|
||||
|
||||
- **Chapter Details:** no adapter or focus-change subscriber was implemented. The adapter file covers Books/Details but not Chapters/Details. Writer/Chapter is a separate workflow with chapter-bound forms; Chapters/Edit is an editing target and must not be retargeted. Details has a bulk POV form, so following must defer when that form is dirty or submitting. Existing chapter navigation is document navigation, not an AJAX chapter renderer.
|
||||
- **Review:** every initiating control reaches the same `showScene` and selects the same first accepted DOM paragraph carrying the SceneID. There is no scene-to-paragraph index arithmetic to correct. The accepted projection orders paragraphs by occurrence ordinal and exposes a scene only through an active canonical scene association in the accepted chapter.
|
||||
- Review's positioning is not coordinated with layout. `showScene` scrolls before hiding/updating the notice and before asynchronous note/context replacements finish. `writer-review.js` captures a previous reading anchor when a context request starts, then restores it in a later animation frame even if explicit scene navigation intervened. Initial context loading and older scene requests can therefore move the reader after navigation. A later Go scrolls again after the layout settles. Header dismissal also calls focus without `preventScroll`, which can move the document back to the header. Initial-load, same-chapter, cross-chapter and accepted-update timing are not unified.
|
||||
- Reproduced before modification in Chromium using the real compiled Review and its accepted SceneID 31 paragraph, delayed context response and expanded fixture geometry: the **same paragraph ID** appeared at viewport Y 612 after focus selection, Y 286 after context completion, and Y 145 after Go. This demonstrates layout/anchor timing, not an off-by-one or a different canonical scene. Fixture geometry is deliberately synthetic; these measurements are not an assertion about a particular author's manuscript.
|
||||
- **Other enabled no-ops:** Scene Explorer's adapter checks membership but `choose` silently returns when exploration is disabled. Story Point catches failed loads without rejecting its Go operation. Maps can select a scene while its story layer or local mapping/planning filters still hide it. Unsupported adapters disable Go without an explanatory tooltip. Filtered Timeline/Plot Lines already have explicit reveal/inspect feedback and must retain filters.
|
||||
- **Focus/Help border:** Focus is DOM-last but visually ordered before Help. The generic `:last-child { border:0 }` therefore removes its divider despite Help being visually next. Restore the shared border only when the active panel has a Help group.
|
||||
|
||||
## Workspace contracts
|
||||
|
||||
| Behaviour | Pages | Contract |
|
||||
| --- | --- | --- |
|
||||
| Follow focus when safe | Chapter Details, chapter workflow, integrated Review | Stable ChapterID; preserve SceneID, defer dirty/busy editing, Go explicitly resynchronises. Chapter editing forms remain independent targets. |
|
||||
| Independent visualisation | Relationships, Maps, Floor Plans | No automatic local movement. Go explicitly aligns an eligible local scene; unavailable/disabled/dirty operations explain or disable. Preserve specialised markers, journeys and occupancy editing. |
|
||||
| Exploratory | Timeline, Plot Lines, At This Point | Preserve filters/snapshots until Go; locate/reveal/inspect through existing mechanisms. |
|
||||
| Chapter destination | Book Overview | Go opens focused chapter with retainNarrativeFocus, preserving scene focus. |
|
||||
| Other editing/unsupported pages | Chapter Edit and unrelated workspaces | Disable Go with explanation; never retarget forms, objectives, sessions or verified Word state. |
|
||||
|
||||
## Correction plan
|
||||
|
||||
Add a guarded chapter adapter using existing document routes. Give Review one cancellable navigation path for initial load, events and Go: await its accepted-context selection, invalidate obsolete reader-anchor restorations, settle layout, resolve again against the current accepted revision, then position a stable accepted paragraph (or show a precise-position-unavailable chapter fallback). Keep the service and SQL unchanged. Qualify delayed/out-of-order responses, control equivalence, initial load, revisions, sticky/narrow layouts, unsaved forms and all existing independent adapters. Add the scoped Focus/Help divider correction.
|
||||
|
||||
## Implemented and qualified correction
|
||||
|
||||
Chapter Details and Writer chapter workflow now carry explicit scope/ChapterID markers and share a focus-following adapter. Clean chapter changes use the existing document route with `retainNarrativeFocus=true`; scene rows are located by stable SceneID. Dirty/busy forms defer following and explain how to resynchronise. Aligned Go confirms the location without changing focus. Refresh/reveal actions also retain narrative focus. Chapter Edit remains a fixed editing target and has disabled Go with an explanation.
|
||||
|
||||
Review now has one version/generation-checked, cancellable pipeline for initial focus, every successful focus event, accepted-content updates and explicit Go. It awaits accepted-context selection and layout frames before resolving and positioning the first accepted paragraph carrying the stable SceneID. Resolution repeats against the current displayed accepted version. Missing mappings produce a chapter-level fallback and an explicit precision-unavailable notice. Reader anchor callbacks captured before explicit navigation cannot restore an older position afterwards. Header dismissal preserves keyboard focus without scrolling back to the header. Page-show reconciliation reads the authoritative focus after document navigation; it does not write or infer a location.
|
||||
|
||||
Local explorers keep independent positions. Disabled/outdated explorer targets are explained; no-op selection is no longer reported as successful Go. Snapshot failures propagate an explicit failure. Maps reveals its story layer, checks mapping/planning eligibility before changing the local target, and explains missing data or unmapped locations while retaining local filters. Timeline and Plot Lines retain their existing reveal/inspect contracts. Unsupported pages have explanatory disabled tooltips.
|
||||
|
||||
The Focus/Help separator reuses the standard ribbon border variable and dimensions, overriding the DOM-last exception only when a Help group is present. No extra Help group or gap was added.
|
||||
|
||||
Qualification uses compiled MVC/Razor and production JavaScript with isolated representative accepted manuscripts. The new accepted fixture has multiple mapped scenes/chapters, deliberately different scene-record order, coherent accepted heading/paragraph windows and a missing-mapping variant. Automated coverage checks stable-ID/accepted-order resolution, all control paths yielding the same paragraph/viewport offset, initial load, refresh, chapter boundaries, rapid clicks, late chapter responses, obsolete anchor callbacks, dirty chapter forms, missing mappings, sticky/narrow layouts, unsupported explanations and the Focus/Help divider. Existing objective/session/annotation/Word safeguards and local visualisation isolation remain covered by the regression suites. No SQL/schema or synchronisation changes were needed.
|
||||
|
||||
Qualification results: solution build passed with zero warnings/errors; full executable regression harness passed all 632 checks, including new stable-ID accepted-projection assertions. `focus-synchronisation.cjs` passed in Chromium and a CDP-installed standalone Chromium PWA, at 1666/950/650px in light/dark themes. It also verifies an editor opened during an in-flight context load is retained. Existing Focus ribbon, narrative-focus architecture/local explorer, popup and manuscript-reader browser suites passed; architecture checks additionally cover map-filter refusal and revealing a hidden story layer. Reader regression covers three widths × four themes × browser/PWA. These are isolated fixture tests, not a claim of live physical Word-device qualification.
|
||||
|
||||
Remaining boundaries are deliberate: Chapter pages reuse document navigation because they have no in-place chapter renderer; dirty editing defers following until the author saves/cancels and resynchronises. Exact Review scene positioning requires an accepted canonical association. Unsupported editing pages, unavailable local scenes and mismatched workspace scopes stay disabled or report the reason rather than guessing, changing filters or retargeting edits.
|
||||
50
PlotLine.Tests/Browser/focus-synchronisation.cjs
Normal file
50
PlotLine.Tests/Browser/focus-synchronisation.cjs
Normal file
@ -0,0 +1,50 @@
|
||||
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
|
||||
const base=process.env.PD_NARRATIVE_TEST_URL||'http://127.0.0.1:5238';
|
||||
(async()=>{
|
||||
const installed=process.argv.includes('--installed'),profile=fs.mkdtempSync('/tmp/pd-narrative-pwa-');
|
||||
const c=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1666,height:1050}}):await(await chromium.launch()).newContext({viewport:{width:1666,height:1050}}),b=c.browser();
|
||||
try{
|
||||
await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:null,defaultPauseOnEdit:true}}));
|
||||
await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false,state:'Disconnected',wordConnected:false}}));
|
||||
await c.route('**/native-companion/status*',r=>r.fulfill({json:{leases:[]}}));
|
||||
await c.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')}));
|
||||
await c.route('**/hubs/**',r=>r.abort());
|
||||
await c.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()})));
|
||||
let p;
|
||||
if(installed){const tab=c.pages()[0];await tab.goto(base+'/fixture');const d=await b.newBrowserCDPSession(),manifestId=base+'/Projects';await d.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture'});await d.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=c.waitForEvent('page');await d.send('PWA.launch',{manifestId,url:base+'/fixture'});p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else p=await c.newPage();
|
||||
|
||||
|
||||
|
||||
await c.addCookies([{name:'fixture-focus-reader',value:'mapped',url:base}]);
|
||||
await c.addInitScript(()=>{window.__focusEvents=[];window.__positions=[];window.addEventListener('plotdirector:narrative-focus-changed',e=>window.__focusEvents.push({chapterID:e.detail.chapterID,sceneID:e.detail.sceneID,version:e.detail.version}));document.addEventListener('reader:focus-positioned',e=>window.__positions.push(e.detail));});
|
||||
const active='.pd-ribbon-panel:not([hidden])',command=async kind=>{const menu=p.locator(active+' .pd-ribbon-focus details[data-compact=true]');if(await menu.count()&&!await menu.evaluate(n=>n.open))await menu.locator('summary').click();await p.locator(active+' [data-global-focus='+kind+']').click();},go=()=>command('go'),state=()=>p.evaluate(()=>window.PlotDirectorNarrativeFocus.state),set=t=>p.evaluate(t=>window.PlotDirectorNarrativeFocus.set(t),t);
|
||||
const clear=()=>p.evaluate(()=>{window.__positions=[];window.__focusEvents=[];});
|
||||
async function positioned(scene){await p.waitForFunction(id=>window.__positions.some(e=>e.sceneID===id),scene);}
|
||||
async function position(){return p.evaluate(()=>{const r=document.querySelector('.manuscript-reader'),n=r.querySelector(`[data-paragraph-id="${r.dataset.focusParagraph}"]`);return {id:r.dataset.focusParagraph,top:n?.getBoundingClientRect().top,revision:r.dataset.revision,version:r.dataset.version,chapter:r.dataset.chapterId};});}
|
||||
async function choose(value){await clear();await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-position]').selectOption(value);await positioned(Number(value.split('/')[1]));}
|
||||
await p.goto(base+'/Chapters/Details/21');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);
|
||||
await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-position]').selectOption('22/32');await p.waitForURL(/Chapters\/Details\/22/);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.sceneID===32);assert.equal(await p.locator('[data-focus-chapter]').getAttribute('data-chapter'),'22');
|
||||
await command('previous');await p.waitForURL(/Chapters\/Details\/21/);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.sceneID===101);assert.equal(await p.locator('[data-pd-context=scene][aria-current=location]').getAttribute('data-pd-context-id'),'101');
|
||||
const form=p.locator('[data-focus-chapter] form:has(input[name=overwriteAuthor])');await form.locator('input[type=checkbox]').check();await set({chapterID:22,sceneID:32});assert.equal(await p.locator('[data-focus-chapter]').getAttribute('data-chapter'),'21');await go();assert.match(await p.locator('[data-focus-workspace-status]').textContent(),/Save or cancel/);await form.evaluate(n=>n.reset());await go();await p.waitForURL(/Chapters\/Details\/22/);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.sceneID===32);
|
||||
const version=(await state()).version;await go();assert.equal((await state()).version,version,'aligned Chapter Go retains scene and version');
|
||||
await p.goto(base+'/Writer/Review?projectId=7&bookId=12');await positioned(32);let baseline=await position();assert(baseline.id,'initial Review load positions verified scene');await clear();await go();await positioned(32);assert.deepEqual(await position(),baseline,'initial load and Go use identical accepted target and offset');
|
||||
for(const scene of [31,101,32]){const chapter=scene===32?22:21;await choose(chapter+'/'+scene);baseline=await position();assert.equal((await p.evaluate(()=>window.__focusEvents.length)),1,'one authoritative event per successful selection');assert.equal(baseline.id,await p.locator(`[data-paragraph-id][data-scene-id="${scene}"]`).first().getAttribute('data-paragraph-id'));await clear();await go();await positioned(scene);assert.deepEqual(await position(),baseline,'Go leaves identical scene position unchanged');}
|
||||
// Return to the same scene through canonical ribbon stepping and recent history.
|
||||
await choose('21/101');baseline=await position();await clear();await command('previous');await positioned(31);await clear();await command('next');await positioned(101);assert.deepEqual(await position(),baseline);await choose('22/32');await clear();await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-recent]').selectOption('21/101');await positioned(101);assert.deepEqual(await position(),baseline,'recent, header and ribbon target the same paragraph/offset');
|
||||
// A late context response must not replace an editor opened while navigation is loading.
|
||||
await choose('21/31');let releaseContext;const contextGate=new Promise(r=>releaseContext=r);await p.route('**/WriterReview/Panel?*',async route=>{const response=await route.fetch();await contextGate;await route.fulfill({response}).catch(()=>{});});const contextRequest=p.waitForRequest('**/WriterReview/Panel?*');await set({chapterID:21,sceneID:101});await contextRequest;await p.locator('[data-authoring-edit]').first().click();const draft=p.locator('[data-authoring-form]:not([hidden]) textarea').first();await draft.fill('Unsaved chapter note during focus navigation');releaseContext();await p.unroute('**/WriterReview/Panel?*');await p.waitForFunction(()=>document.querySelector('[data-review-message]').textContent.includes('edits are retained'));assert.equal(await draft.inputValue(),'Unsaved chapter note during focus navigation');await p.locator('[data-authoring-form]:not([hidden]) [data-authoring-cancel]').click();await clear();await go();await positioned(101);
|
||||
// A callback captured before navigation cannot undo a newer explicit target.
|
||||
await p.evaluate(()=>window.__oldReadingAnchor=document.querySelector('.manuscript-reader').readerPreserveView());await choose('21/31');const beforeOldRestore=await position();await p.evaluate(()=>window.__oldReadingAnchor());assert.deepEqual(await position(),beforeOldRestore);
|
||||
// Hold a chapter response, return to the displayed chapter, then deliver the stale response.
|
||||
let release;const held=new Promise(r=>release=r);await p.route('**/Writer/ReviewContent?*',async route=>{const response=await route.fetch();await held;await route.fulfill({response}).catch(()=>{});});const requested=p.waitForRequest('**/Writer/ReviewContent?*');await set({chapterID:22,sceneID:32});await requested;await clear();await set({chapterID:21,sceneID:101});await positioned(101);release();await p.unroute('**/Writer/ReviewContent?*');await p.waitForTimeout(150);assert.equal((await position()).chapter,'21');assert.equal(await p.locator('[data-paragraph-id][data-scene-id="101"]').first().getAttribute('data-paragraph-id'),(await position()).id,'older chapter response cannot overwrite newer scene');
|
||||
await choose('21/31');await clear();await p.locator(active+' [data-global-focus=next]').evaluate(n=>{n.click();n.click();});await positioned(101);assert.equal((await state()).sceneID,101);assert.equal(await p.evaluate(()=>window.__focusEvents.length),1,'rapid clicks accept one scoped update while the command is busy');assert.deepEqual(await p.evaluate(()=>window.__focusEvents.map(e=>[e.chapterID,e.sceneID])),[[21,101]]);
|
||||
for(const width of [1666,950,650])for(const theme of ['modern-light','modern-dark']){await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);await p.setViewportSize({width,height:1050});await choose('21/101');const before=await position();await clear();await go();await positioned(101);const after=await position();assert.equal(after.id,before.id);assert(Math.abs(after.top-before.top)<1,'sticky/narrow reader offset is repeatable');await p.screenshot({path:`/tmp/pd-focus-sync-${installed?'pwa':'browser'}-${width}-${theme}.png`});}
|
||||
await p.reload();await positioned(101);assert.equal((await position()).id,baseline.id,'refresh resolves the same accepted paragraph identity');
|
||||
await c.addCookies([{name:'fixture-focus-reader',value:'unmapped',url:base}]);await p.goto(base+'/Writer/Review?projectId=7&bookId=12');await choose('22/32');assert.equal((await position()).id,'');assert.match(await p.locator('[data-review-focus-notice]').textContent(),/Precise scene positioning is unavailable/);assert.equal((await position()).chapter,'22');
|
||||
await p.goto(base+'/fixture?desktop=StoryPoint');await p.waitForFunction(()=>document.querySelector('.pd-ribbon-panel:not([hidden]) .pd-ribbon-group[aria-label=Help]')||!matchMedia('(display-mode: standalone)').matches);
|
||||
if(installed){const divider=await p.locator(active+' .pd-ribbon-focus').evaluate(n=>{const s=getComputedStyle(n);return {width:s.borderRightWidth,style:s.borderRightStyle,color:s.borderRightColor};});assert.equal(divider.width,'1px');assert.equal(divider.style,'solid');}
|
||||
await p.route('**/StoryPoint?*',r=>r.fulfill({status:503,body:'Synthetic unavailable snapshot'}));await p.route('**/StoryPoint/Index?*',r=>r.fulfill({status:503,body:'Synthetic unavailable snapshot'}));await go();assert.match(await p.locator('[data-focus-workspace-status]').textContent(),/could not be loaded/);
|
||||
await p.goto(base+'/fixture?desktop=Characters');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);assert(await p.locator(active+' [data-global-focus=go]').isDisabled());assert.match(await p.locator(active+' [data-global-focus=go]').getAttribute('title'),/does not support/);
|
||||
console.log(`PASS ${installed?'installed Chromium PWA':'Chromium'} focus synchronisation: stable-ID chapter follow/dirty guard/Go, identical initial/header/recent/ribbon/Go/refresh accepted positions, canonical boundaries, stale anchor/response rejection, missing-map fallback, repeatable sticky/narrow offsets, disabled explanations and Focus/Help divider.`);
|
||||
}finally{await c.close();await b?.close();fs.rmSync(profile,{recursive:true,force:true});}
|
||||
})().catch(e=>{console.error(e.stack);process.exitCode=1;});
|
||||
@ -93,6 +93,8 @@ const base=process.env.PD_NARRATIVE_TEST_URL||'http://127.0.0.1:5238';
|
||||
await p.locator('#mapStoryScene').evaluate(n=>{n.value='90';n.dispatchEvent(new Event('change',{bubbles:true}));});assert.equal((await state()).version,mapVersion,'Maps scene selection is local');
|
||||
const mapScene=await p.locator('#mapStoryScene').inputValue();await set({chapterID:21,sceneID:31});assert.equal(await p.locator('#mapStoryScene').inputValue(),mapScene,'global focus retains map position and journey context');const mapFocusVersion=(await state()).version;await go();assert.equal(await p.locator('#mapStoryScene').inputValue(),'31');assert.equal((await state()).version,mapFocusVersion);
|
||||
assert.match(await p.locator('#mapsDetailContent').innerText(),/Harbour morning/);
|
||||
await p.locator('#mapStoryScene').evaluate(n=>{n.value='90';n.dispatchEvent(new Event('change',{bubbles:true}));});const filteredPosition=await p.locator('#mapStoryScene').inputValue();const excludedMapping=mapFixture.scenes.find(s=>s.sceneID===31).position.featureID?'unmapped':'mapped';await p.locator('#mapStoryMapping').evaluate((n,value)=>{n.value=value;n.dispatchEvent(new Event('change',{bubbles:true}));},excludedMapping);await go();assert.match(await p.locator('[data-focus-workspace-status]').textContent(),/mapping or planning filters/);assert.equal(await p.locator('#mapStoryScene').inputValue(),filteredPosition,'filtered Go preserves the existing local map target');assert.equal(await p.locator('#mapStoryMapping').inputValue(),excludedMapping);await p.locator('#mapStoryMapping').evaluate(n=>{n.value='all';n.dispatchEvent(new Event('change',{bubbles:true}));});await p.locator('#mapStoryLayer').evaluate(n=>n.click());assert.equal(await p.evaluate(()=>window.PlotDirectorStoryOverlay.state.visible),false);await go();assert.equal(await p.evaluate(()=>window.PlotDirectorStoryOverlay.state.visible),true,'Go reveals a hidden story layer');assert.equal((await state()).version,mapFocusVersion);
|
||||
|
||||
await p.screenshot({path:`/tmp/pd-narrative-${installed?'pwa':'browser'}-Maps.png`});
|
||||
await p.goto(base+'/Timeline/Index?ProjectID=7');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.bookID===12);assert.match(await p.locator('[data-focus-label]').textContent(),/A Distant Shore/);await p.locator('[data-focus-toggle]').click();await p.locator('[data-focus-book]').selectOption('13');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.bookID===13);assert.equal((await state()).sceneID,null);assert.equal(await p.locator('.timeline-scene-card').count(),3,'focus book selection preserves project-wide Timeline');assert(!new URL(p.url()).searchParams.has('BookID'));await p.locator('[data-focus-book]').selectOption('12');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.bookID===12);
|
||||
await p.locator('[data-focus-position]').selectOption('23/');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.chapterID===23);assert(await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="next"]').isDisabled(),'no following scene after the final empty chapter');assert(await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="previous"]').isEnabled());await openFocus();await p.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus="previous"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32);await set({chapterID:21,sceneID:31});
|
||||
|
||||
@ -32,6 +32,19 @@ internal static class ManuscriptReaderTests
|
||||
]
|
||||
};
|
||||
}
|
||||
internal static ParagraphManuscript FocusSnapshot(bool unmapped=false)
|
||||
{
|
||||
var state=Snapshot();state.Paragraphs.Clear();state.Chapters.Clear();state.Scenes.Clear();state.Revision=7;
|
||||
// Scene-record order differs from canonical scene order; accepted paragraph/heading windows remain coherent.
|
||||
foreach(var pair in new[]{(22,new[]{32}),(21,new[]{101,31})}){
|
||||
var heading=Guid.NewGuid();state.Chapters.Add(new(){CanonicalId=pair.Item1,HeadingId=heading});
|
||||
state.Paragraphs.Add(new(){ChapterId=pair.Item1,Occurrence=new(){Id=heading,Ordinal=pair.Item1==21?0:100,Outline=1,Text="Synthetic chapter "+pair.Item1}});
|
||||
foreach(var id in pair.Item2){var scene=Guid.NewGuid();state.Scenes.Add(new(){Id=scene,CanonicalId=id,ChapterId=pair.Item1});
|
||||
for(var i=0;i<25;i++)state.Paragraphs.Add(new(){ChapterId=pair.Item1,SceneId=unmapped&&id==32?null:scene,Story=true,Occurrence=new(){Id=Guid.NewGuid(),Ordinal=(id==31?1:id==101?30:101)+i,Outline=10,Text=$"Scene {id}, accepted paragraph {i}. "+string.Join(" ",Enumerable.Repeat("Synthetic accepted prose for stable position regression.",8))}});
|
||||
}
|
||||
}
|
||||
state.Paragraphs=state.Paragraphs.OrderBy(p=>p.Occurrence.Ordinal).ToList();return state;
|
||||
}
|
||||
internal static ManuscriptReaderService FixtureService(Func<ParagraphManuscript?>? snapshot = null, Action? onRead = null,bool allowSecondBook=false)
|
||||
{
|
||||
var fixture = Snapshot();
|
||||
@ -66,6 +79,10 @@ internal static class ManuscriptReaderTests
|
||||
public static async Task Run()
|
||||
{
|
||||
void Check(bool value, string message) { if (!value) throw new Exception(message); }
|
||||
var focused=FocusSnapshot();var focusedReader=FixtureService(()=>focused);var mapped=(await focusedReader.Read(4,12,21))!;
|
||||
Check(mapped.Paragraphs.Where(p=>p.SceneID.HasValue).Select(p=>p.SceneID).Distinct().SequenceEqual(new int?[]{31,101}),"Accepted scene targets resolve stable canonical IDs in accepted paragraph order, independently of scene-record order");
|
||||
var firstScene=mapped.Paragraphs.First(p=>p.SceneID==101);Check(firstScene.Id==focused.Paragraphs.OrderBy(p=>p.Occurrence.Ordinal).First(p=>p.SceneId==focused.Scenes.Single(s=>s.CanonicalId==101).Id).Occurrence.Id,"Scene positioning uses the first accepted mapped paragraph identity rather than a scene or paragraph index");
|
||||
var missing=(await FixtureService(()=>FocusSnapshot(true)).Read(4,12,22))!;Check(missing.Paragraphs.All(p=>p.SceneID is null),"Missing accepted scene associations remain unverified rather than being inferred from narrative focus");
|
||||
var state = Snapshot(); var reads = 0; var service = FixtureService(() => state, () => reads++);
|
||||
var first = (await service.Read(4, 12, null))!;
|
||||
Check(first.Chapters.Count == 3 && first.Chapter!.ChapterID == 21, "Book context and canonical chapter ordering");
|
||||
|
||||
@ -21,6 +21,8 @@ internal static class ToolbarBrowserHost
|
||||
{
|
||||
private static readonly ParagraphManuscript readerFixture = ReviewSnapshot();
|
||||
private static ParagraphManuscript ReviewSnapshot(){var state=ManuscriptReaderTests.Snapshot();var scene=Guid.NewGuid();state.Scenes=[new(){Id=scene,CanonicalId=31,ChapterId=21}];foreach(var p in state.Paragraphs.Where(p=>p.ChapterId==21&&p.Story))p.SceneId=scene;return state;}
|
||||
private static readonly ParagraphManuscript readerFocusFixture=ManuscriptReaderTests.FocusSnapshot();
|
||||
private static readonly ParagraphManuscript readerUnmappedFixture=ManuscriptReaderTests.FocusSnapshot(true);
|
||||
private static readonly ParagraphManuscript readerLongFixture = ManuscriptReaderTests.LongSnapshot();
|
||||
private static readonly System.Collections.Concurrent.ConcurrentDictionary<(int User, int Chapter), ChapterGoal> writerGoals = new();
|
||||
|
||||
@ -151,12 +153,12 @@ internal static class ToolbarBrowserHost
|
||||
}));
|
||||
builder.Services.AddSingleton(FixtureProxy<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"}});
|
||||
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"},Scenes=(id==21?new[]{31,101}:new[]{32}).Select(scene=>new Scene{SceneID=scene,ChapterID=id,SceneTitle="Scene "+scene,SceneNumber=scene==101?2:1}).ToArray()});
|
||||
}));
|
||||
builder.Services.AddSingleton<IToolbarPreferenceRepository, ToolbarMemoryPreferences>();
|
||||
builder.Services.AddScoped(services => ManuscriptReaderTests.FixtureService(() =>
|
||||
services.GetRequiredService<IHttpContextAccessor>().HttpContext!.Request.Query["reader-error"] == "true"
|
||||
? throw new TimeoutException("Synthetic unavailable manuscript") : services.GetRequiredService<IHttpContextAccessor>().HttpContext!.Request.Query["reader-long"] == "true" ? readerLongFixture : readerFixture,allowSecondBook:true));
|
||||
? throw new TimeoutException("Synthetic unavailable manuscript") : services.GetRequiredService<IHttpContextAccessor>().HttpContext!.Request.Cookies["fixture-focus-reader"]=="mapped"?readerFocusFixture:services.GetRequiredService<IHttpContextAccessor>().HttpContext!.Request.Cookies["fixture-focus-reader"]=="unmapped"?readerUnmappedFixture:services.GetRequiredService<IHttpContextAccessor>().HttpContext!.Request.Query["reader-long"] == "true" ? readerLongFixture : readerFixture,allowSecondBook:true));
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddSingleton<IAppearanceRepository, AppearanceMemoryPreferences>();
|
||||
builder.Services.AddSingleton<INarrativeFocus,NarrativeFocusFixture>();
|
||||
@ -179,7 +181,7 @@ internal static class ToolbarBrowserHost
|
||||
"GetChapterWorkflowAsync" => Task.FromResult<ChapterWorkflowViewModel?>(new() {
|
||||
Project = new() { ProjectID = 7, ProjectName = "The Glass Harbour" },
|
||||
Book = new() { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" },
|
||||
Chapter = new() { ChapterID = 21, BookID = 12, ChapterNumber = 1, ChapterTitle = "The crossing" },
|
||||
Chapter = new() { ChapterID = (int)args![0]!, BookID = 12, ChapterNumber = (int)args[0]! ==21?1:2, ChapterTitle = "The crossing" },
|
||||
Goal = writerGoals.GetOrAdd((services.GetRequiredService<ICurrentUserService>().UserId!.Value, 21), _ => new() { ChapterID = 21, GoalSummary = "Reveal the consequence" })
|
||||
}),
|
||||
"SaveChapterGoalAsync" => SaveFixtureGoal(services.GetRequiredService<ICurrentUserService>().UserId!.Value, (ChapterGoalEditViewModel)args![0]!),
|
||||
|
||||
@ -4,7 +4,7 @@ using PlotLine.Models;
|
||||
internal sealed class WriterReviewFixture(ManuscriptReaderService reader,IWriterAuthoringService intentions):IWriterReviewService
|
||||
{
|
||||
private static readonly object gate=new();private static readonly Dictionary<Guid,ReviewObservation> rows=[];
|
||||
public async Task<ReviewPanel> Read(int actor,int book,int chapter,Guid? paragraph,string? version,int page,Guid? endParagraph=null){var source=await reader.Read(actor,book,chapter)??throw new KeyNotFoundException();var selected=source.ContentVersion==version?source.Paragraphs.FirstOrDefault(p=>p.Id==paragraph):null;var context=await intentions.Read(actor,12,21,selected?.SceneID);if(chapter!=21)context=new(){BookID=12,ChapterID=chapter,Chapter=source.Chapter!,Sections=context.Sections.Where(x=>x.Kind is "Chapter" or "Goals").ToArray()};lock(gate){var found=rows.Values.Where(r=>r.UserID==actor&&r.BookID==book&&r.ChapterID==chapter).OrderByDescending(x=>x.CreatedUtc).Skip((page-1)*50).Take(51).ToArray();foreach(var row in found)row.AnchorState=WriterReviewService.AnchorState(row,source);return new(context,found.Take(50).ToArray(),page,found.Length>50,selected?.SceneID!=null?"Scene context comes from accepted paragraph assignments.":"No verified scene assignment; chapter intentions remain available.");}}
|
||||
public async Task<ReviewPanel> Read(int actor,int book,int chapter,Guid? paragraph,string? version,int page,Guid? endParagraph=null){var source=await reader.Read(actor,book,chapter)??throw new KeyNotFoundException();var selected=source.ContentVersion==version?source.Paragraphs.FirstOrDefault(p=>p.Id==paragraph):null;var context=await intentions.Read(actor,12,21,selected?.SceneID==31?31:null);if(chapter!=21||selected?.SceneID is int scene&&scene!=31)context=new(){BookID=12,ChapterID=chapter,SceneID=selected?.SceneID,Chapter=source.Chapter!,Scene=selected?.SceneID is int id?new(){SceneID=id,ChapterID=chapter,SceneTitle="Mapped scene "+id}:null,Sections=context.Sections.Where(x=>x.Kind is "Chapter" or "Goals").ToArray()};lock(gate){var found=rows.Values.Where(r=>r.UserID==actor&&r.BookID==book&&r.ChapterID==chapter).OrderByDescending(x=>x.CreatedUtc).Skip((page-1)*50).Take(51).ToArray();foreach(var row in found)row.AnchorState=WriterReviewService.AnchorState(row,source);return new(context,found.Take(50).ToArray(),page,found.Length>50,selected?.SceneID!=null?"Scene context comes from accepted paragraph assignments.":"No verified scene assignment; chapter intentions remain available.");}}
|
||||
public async Task<ReviewObservation> Save(int actor,ReviewSave r){var source=await reader.Read(actor,r.BookID,r.ChapterID)??throw new KeyNotFoundException();var error=WriterReviewService.Validate(r);if(error.Length>0)throw new ArgumentException(error);lock(gate){if(r.Version==0){if(rows.TryGetValue(r.ID,out var existing)){if(existing.UserID==actor&&existing.Observation==r.Observation)return existing;throw new AuthoringConflictException("Observation changed; your text is retained.");}if(source.ContentVersion!=r.ContentVersion)throw new AuthoringConflictException("Accepted chapter changed; your text is retained.");var anchors=WriterReviewService.Anchor(source,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset);var row=new ReviewObservation{ID=r.ID,UserID=actor,BookID=r.BookID,ChapterID=r.ChapterID,ContentVersion=r.ContentVersion,ManuscriptID=source.ManuscriptID,SnapshotRevision=source.Revision,StartParagraph=r.StartParagraph,EndParagraph=r.EndParagraph,StartOffset=r.StartOffset,EndOffset=r.EndOffset,AnchorHash=anchors.Length>0?WriterReviewService.Hash(anchors):null,SceneID=r.Scope=="Scene"?r.SceneID:anchors.FirstOrDefault()?.SceneID,Scope=string.IsNullOrEmpty(r.Scope)?null:r.Scope,Classification=r.Classification,Observation=r.Observation,Decision=r.Decision,Status=r.Status,Version=1,CreatedUtc=DateTime.UtcNow,UpdatedUtc=DateTime.UtcNow};rows[r.ID]=row;return row;}
|
||||
if(!rows.TryGetValue(r.ID,out var saved)||saved.UserID!=actor||saved.BookID!=r.BookID||saved.ChapterID!=r.ChapterID||saved.Version!=r.Version)throw new AuthoringConflictException("Another window changed this observation; your text is retained.");saved.Observation=r.Observation;saved.Decision=r.Decision;saved.Status=r.Status;saved.Classification=r.Classification;saved.Version++;saved.UpdatedUtc=DateTime.UtcNow;return saved;}}
|
||||
}
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
ViewData["ProjectSection"] = "Overview";
|
||||
}
|
||||
|
||||
<div data-focus-chapter data-project="@Model.Project.ProjectID" data-book="@Model.Book.BookID" data-chapter="@Model.Chapter.ChapterID">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
@ -184,3 +185,5 @@
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
</div>
|
||||
|
||||
@ -8,6 +8,7 @@
|
||||
var polishCount = Model.Scenes.Count(x => x.RevisionStatusName == "Revised");
|
||||
}
|
||||
|
||||
<div data-focus-chapter data-project="@Model.Project.ProjectID" data-book="@Model.Book.BookID" data-chapter="@Model.Chapter.ChapterID">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
@ -74,7 +75,7 @@
|
||||
<div class="writer-queue-list">
|
||||
@foreach (var scene in Model.Scenes)
|
||||
{
|
||||
<article class="writer-queue-card">
|
||||
<article class="writer-queue-card" data-pd-context="scene" data-pd-context-id="@scene.SceneID">
|
||||
<div class="writer-queue-title">
|
||||
<h3>Scene @scene.SceneNumber: @scene.SceneTitle</h3>
|
||||
<span class="status-pill">@scene.RevisionStatusName</span>
|
||||
@ -100,6 +101,8 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
</div>
|
||||
|
||||
@section Scripts {
|
||||
<script src="~/js/form-navigation-guard.js" asp-append-version="true"></script>
|
||||
}
|
||||
|
||||
@ -15,3 +15,6 @@
|
||||
@media(max-width:900px){.pd-narrative-focus{max-width:12rem;}}
|
||||
|
||||
.timeline-scene-card.pd-current-narrative-focus{outline:2px solid var(--pd-accent);outline-offset:2px;}
|
||||
|
||||
/* Focus is DOM-last but visually precedes contextual Help. */
|
||||
.pd-ribbon-panel:has(.pd-ribbon-group[aria-label="Help"])>.pd-ribbon-focus{border-right:1px solid var(--pd-border-subtle);}
|
||||
|
||||
@ -93,7 +93,27 @@ function initialiseManuscriptReader() {
|
||||
break;
|
||||
}
|
||||
};
|
||||
root.readerPreserveView=()=>{const anchors=rememberPosition();return ()=>restorePosition(anchors);};
|
||||
let narrativePosition=0;
|
||||
root.readerPreserveView=()=>{const mine=narrativePosition,anchors=rememberPosition();return ()=>{if(root.isConnected&&mine===narrativePosition)restorePosition(anchors);};};
|
||||
root.readerResolveFocus=target=>{
|
||||
if(Number(bookId)!==target.bookID||Number(chapterId)!==target.chapterID)return null;
|
||||
const paragraph=target.sceneID?[...content.querySelectorAll('[data-paragraph-id][data-scene-id]')].find(n=>Number(n.dataset.sceneId)===target.sceneID):null;
|
||||
return {paragraph,precise:!!paragraph,version:root.dataset.version,revision:root.dataset.revision};
|
||||
};
|
||||
root.readerLocateFocus=target=>{
|
||||
const resolved=root.readerResolveFocus(target);if(!resolved)return null;
|
||||
++narrativePosition;
|
||||
const row=resolved.paragraph||content.querySelector('[data-paragraph-id],h2,.reader-empty');
|
||||
root.dataset.focusParagraph=resolved.paragraph?.dataset.paragraphId||'';
|
||||
if(!row)return resolved;
|
||||
const focused=root.dataset.focus==='true',container=focused?root:scrollPanel;
|
||||
const header=document.querySelector('.pd-application-header'),sticky=header&&['sticky','fixed'].includes(getComputedStyle(header).position);
|
||||
let top=container?container.getBoundingClientRect().top:sticky?Math.max(0,header.getBoundingClientRect().bottom):0;
|
||||
if(focused)top+=root.querySelector('.reader-controls')?.getBoundingClientRect().height||0;
|
||||
else {const columns=root.closest('[data-review-columns]');if(columns?.dataset.compact==='true')top+=Math.max(...[...columns.querySelectorAll(':scope>.writer21-notes')].map(n=>n.getBoundingClientRect().height),0)+12;}
|
||||
(container||window).scrollBy({top:row.getBoundingClientRect().top-top-12,behavior:'instant'});
|
||||
return resolved;
|
||||
};
|
||||
const fetchJson = async url => {
|
||||
request = new AbortController();
|
||||
const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store', signal: request.signal });
|
||||
|
||||
@ -177,7 +177,7 @@
|
||||
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);}});
|
||||
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(!data)throw Error(error||'Story data could not be loaded. Your local map position is retained.');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.');if(!E.filterScenes(data,{...state,lens:'scene',bookID:focus.bookID}).some(s=>s.sceneID===focus.sceneID))throw Error('Current Focus is hidden by the map mapping or planning filters. Adjust those local filters to reveal it; their values have been retained.');state.lens='scene';state.visible=true;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);if(!E.mapped(scenes.get(focus.sceneID).position))throw Error('Current Focus is selected, but this scene has no verified position on this map. The scene details remain available.');}});
|
||||
$('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='';});
|
||||
|
||||
@ -1,46 +1,53 @@
|
||||
// Refresh only the read-only Review content. Stable columns, media/session controls and Word state survive.
|
||||
// One accepted-target/layout pipeline for initial load, focus events and explicit Go.
|
||||
(() => {
|
||||
const columns=document.querySelector('[data-review-columns]');if(!columns)return;
|
||||
const notice=document.createElement('p');notice.className='writer3-caption';notice.dataset.reviewFocusNotice='true';notice.hidden=true;columns.before(notice);
|
||||
let pending=null,request=null,generation=0;
|
||||
let request=null,generation=0;
|
||||
const canChange=()=>document.querySelector('[data-writer-review]')?.canChangeNarrative?.()!==false&&!columns.querySelector('[data-authoring-form]:not([hidden]),[data-busy="true"]');
|
||||
function showScene(focus){const reader=document.querySelector('.manuscript-reader');const paragraph=focus.sceneID?reader?.querySelector(`[data-paragraph-id][data-scene-id="${focus.sceneID}"]`):null;
|
||||
if(paragraph){paragraph.scrollIntoView({block:'center'});paragraph.click();notice.hidden=true;}
|
||||
else if(focus.sceneID){notice.hidden=false;notice.textContent='Current Focus: '+focus.label+'. No accepted paragraph is mapped to that scene here; verified Review references are unchanged.';}
|
||||
}
|
||||
function offer(text){notice.hidden=false;notice.replaceChildren(document.createTextNode(text+' '));const button=document.createElement('button');button.type='button';button.className='btn btn-sm btn-link';button.textContent='Show current focus';button.addEventListener('click',()=>{if(!canChange()){offer('Save or cancel open editors and close dialogs before changing the displayed chapter.');return;}void apply(pending);});notice.append(button);}
|
||||
const current=()=>window.PlotDirectorNarrativeFocus?.state;
|
||||
const same=(a,b)=>a&&b&&a.projectID===b.projectID&&a.bookID===b.bookID&&a.chapterID===b.chapterID&&a.sceneID===b.sceneID&&a.version===b.version;
|
||||
const frame=()=>new Promise(resolve=>requestAnimationFrame(resolve));
|
||||
function offer(text){notice.hidden=false;notice.replaceChildren(document.createTextNode(text+' '));const button=document.createElement('button');button.type='button';button.className='btn btn-sm btn-link';button.textContent='Show current focus';button.addEventListener('click',()=>void apply(current()));notice.append(button);}
|
||||
async function apply(focus){
|
||||
if(!focus?.chapterID||!canChange())return;if(focus.chapterID===Number(document.querySelector('.manuscript-reader')?.dataset.chapterId)){showScene(focus);pending=null;return;}
|
||||
const reader=document.querySelector('.manuscript-reader'),mine=++generation;request?.abort();request=new AbortController();
|
||||
if(!focus?.chapterID)return;
|
||||
const mine=++generation;request?.abort();
|
||||
let reader=document.querySelector('.manuscript-reader');if(focus.bookID!==Number(reader?.dataset.bookId))return;
|
||||
if(!canChange()){offer('Save or cancel open editors, clear any text selection and close dialogs before changing the displayed chapter or scene. Your original references are retained.');return;}
|
||||
try{
|
||||
const url=new URL('/Writer/ReviewContent',location.origin);url.search=new URLSearchParams({projectId:focus.projectID,bookId:focus.bookID,version:focus.version,focus:reader?.dataset.focus==='true',reading:reader?.dataset.reading==='true'});
|
||||
const response=await fetch(url,{cache:'no-store',signal:request.signal});if(!response.ok||response.redirected)throw Error();
|
||||
const doc=new DOMParser().parseFromString(await response.text(),'text/html');const fresh=doc.querySelector('[data-review-columns]');
|
||||
if(!fresh||!doc.querySelector('.manuscript-reader'))throw Error();
|
||||
if(mine!==generation||pending?.version!==focus.version)return;
|
||||
if(!canChange()){offer('Current focus changed. Your open editors retain their original target.');return;}
|
||||
const sections=['#review-chapter-notes','.writer21-manuscript','#review-scene-notes'].map(selector=>({old:columns.querySelector(selector),next:fresh.querySelector(selector)}));
|
||||
if(sections.some(part=>!part.old||!part.next))throw Error();
|
||||
// Retain exact session and verified Word objects; changing narrative intention does not rebind them.
|
||||
const oldWord=columns.querySelector('[data-writer-word]'),newWord=fresh.querySelector('[data-writer-word]');if(oldWord&&newWord)newWord.replaceWith(oldWord);
|
||||
const work=[...columns.querySelectorAll('[data-writer-work]')],newWork=[...fresh.querySelectorAll('[data-writer-work]')];work.forEach((node,i)=>newWork[i]?.replaceWith(node));
|
||||
const filters=[...columns.querySelectorAll('[data-annotation-filter]')].map(n=>[n.dataset.annotationFilter,n.value]);
|
||||
const updatesPaused=reader?.querySelector('#reader-pause')?.checked===true;
|
||||
document.querySelector('[data-writer-review]')?.reviewDispose?.();reader?.readerCleanup?.();
|
||||
for(const {old,next}of sections)old.replaceChildren(...next.childNodes);
|
||||
const pause=document.querySelector('.manuscript-reader #reader-pause');if(pause)pause.checked=updatesPaused;
|
||||
window.PlotDirectorManuscriptReader?.mount();window.PlotDirectorReview?.mount();window.dispatchEvent(new CustomEvent('review:narrative-applied',{detail:{...focus,sceneID:null}}));
|
||||
window.addEventListener('review:context-loaded',()=>{for(const [name,value]of filters){const select=columns.querySelector(`[data-annotation-filter="${name}"]`);if(select){select.value=value;select.dispatchEvent(new Event('change',{bubbles:true}));}}},{once:true});
|
||||
notice.hidden=true;pending=null;showScene(focus);window.dispatchEvent(new Event('plotdirector:context-changed'));
|
||||
}catch(error){if(error.name!=='AbortError'&&mine===generation)offer('The chapter could not be refreshed. Your displayed content and edits are retained.');}
|
||||
if(focus.chapterID!==Number(reader.dataset.chapterId)){
|
||||
request=new AbortController();const url=new URL('/Writer/ReviewContent',location.origin);url.search=new URLSearchParams({projectId:focus.projectID,bookId:focus.bookID,version:focus.version,focus:reader.dataset.focus==='true',reading:reader.dataset.reading==='true'});
|
||||
const response=await fetch(url,{cache:'no-store',signal:request.signal});if(!response.ok||response.redirected)throw Error('The chapter could not be refreshed.');
|
||||
const doc=new DOMParser().parseFromString(await response.text(),'text/html'),fresh=doc.querySelector('[data-review-columns]'),nextReader=fresh?.querySelector('.manuscript-reader');
|
||||
if(!nextReader||Number(nextReader.dataset.bookId)!==focus.bookID||Number(nextReader.dataset.chapterId)!==focus.chapterID)throw Error('The requested chapter is unavailable.');
|
||||
if(mine!==generation||!same(focus,current()))return;
|
||||
if(!canChange()){offer('Current focus changed. Your open editors retain their original target.');return;}
|
||||
const sections=['#review-chapter-notes','.writer21-manuscript','#review-scene-notes'].map(selector=>({old:columns.querySelector(selector),next:fresh.querySelector(selector)}));if(sections.some(p=>!p.old||!p.next))throw Error('The chapter could not be refreshed.');
|
||||
const oldWord=columns.querySelector('[data-writer-word]'),newWord=fresh.querySelector('[data-writer-word]');if(oldWord&&newWord)newWord.replaceWith(oldWord);
|
||||
const work=[...columns.querySelectorAll('[data-writer-work]')],newWork=[...fresh.querySelectorAll('[data-writer-work]')];work.forEach((node,i)=>newWork[i]?.replaceWith(node));
|
||||
const filters=[...columns.querySelectorAll('[data-annotation-filter]')].map(n=>[n.dataset.annotationFilter,n.value]),paused=reader.querySelector('#reader-pause')?.checked===true;
|
||||
document.querySelector('[data-writer-review]')?.reviewDispose?.();reader.readerCleanup?.();for(const {old,next}of sections)old.replaceChildren(...next.childNodes);
|
||||
const pause=columns.querySelector('#reader-pause');if(pause)pause.checked=paused;
|
||||
window.PlotDirectorManuscriptReader?.mount();window.PlotDirectorReview?.mount();window.dispatchEvent(new CustomEvent('review:narrative-applied',{detail:{...focus,sceneID:null}}));
|
||||
// Context loading below completes before positioning; no old reading-anchor callback may win.
|
||||
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.');
|
||||
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;
|
||||
const resolved=reader.readerResolveFocus(focus);
|
||||
notice.hidden=!focus.sceneID||resolved.precise;
|
||||
if(!notice.hidden)notice.textContent='Current Focus: '+focus.label+'. Precise scene positioning is unavailable: no accepted paragraph is mapped to this scene. Verified Review references are unchanged.';
|
||||
window.dispatchEvent(new Event('plotdirector:context-changed'));
|
||||
await frame();await frame();
|
||||
if(mine!==generation||!same(focus,current())||!reader.isConnected||!canChange())return;
|
||||
reader.readerLocateFocus(focus);
|
||||
reader.dispatchEvent(new CustomEvent('reader:focus-positioned',{bubbles:true,detail:{chapterID:focus.chapterID,sceneID:focus.sceneID,paragraphID:reader.dataset.focusParagraph||null,version:reader.dataset.version}}));
|
||||
}catch(error){if(error.name!=='AbortError'&&mine===generation)offer((error.message||'Current Focus could not be displayed.')+' Your content and edits are retained.');}
|
||||
}
|
||||
window.addEventListener('plotdirector:narrative-focus-changed',event=>{
|
||||
const focus=event.detail,reader=document.querySelector('.manuscript-reader');if(focus.bookID!==Number(reader?.dataset.bookId))return;
|
||||
pending=focus;
|
||||
if(focus.chapterID===Number(reader?.dataset.chapterId)){if(canChange())showScene(focus);else offer('Current focus changed. Your open editors and verified references retain their original target.');return;}
|
||||
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('plotdirector:narrative-focus-changed',event=>void apply(event.detail));
|
||||
window.PlotDirectorFocusWorkspace.register({canGo:focus=>focus.bookID===Number(document.querySelector('.manuscript-reader')?.dataset.bookId)&&!!focus.chapterID,unavailable:'Choose a chapter in this Review book to display Current Focus',go:apply});
|
||||
document.addEventListener('reader:updated',()=>void apply(current()));
|
||||
if(current())void apply(current());
|
||||
window.addEventListener('pagehide',()=>{++generation;request?.abort();});
|
||||
})();
|
||||
|
||||
@ -5,6 +5,32 @@
|
||||
const controller=shell.dataset.workspaceController,action=shell.dataset.workspaceAction;
|
||||
function offer(message,label,perform){let output=document.querySelector('[data-focus-workspace-status]');if(!output){output=document.createElement('p');output.dataset.focusWorkspaceStatus='';output.setAttribute('role','status');shell.after(output);}output.replaceChildren(document.createTextNode(message+' '));if(perform){const button=document.createElement('button');button.type='button';button.className='btn btn-sm btn-outline-secondary';button.textContent=label;button.addEventListener('click',perform);output.append(button);}}
|
||||
const sceneURL=focus=>{const url=new URL('/Timeline/Index',location.origin);url.search=new URLSearchParams({projectId:focus.projectID,bookId:focus.bookID,selectedSceneId:focus.sceneID,retainNarrativeFocus:true});return url;};
|
||||
const chapterPage=document.querySelector('[data-focus-chapter]');
|
||||
if(chapterPage){
|
||||
let submitting=false;
|
||||
chapterPage.addEventListener('input',e=>{const form=e.target.closest('form');if(form)form.dataset.focusDirty='true';});
|
||||
chapterPage.addEventListener('change',e=>{const form=e.target.closest('form');if(form)form.dataset.focusDirty='true';});
|
||||
chapterPage.addEventListener('reset',e=>delete e.target.dataset.focusDirty);
|
||||
chapterPage.addEventListener('submit',()=>{submitting=true;});
|
||||
const blocked=()=>submitting||chapterPage.querySelector('form[data-focus-dirty=true],[data-busy=true],form[aria-busy=true]')||document.querySelector('dialog[open],.modal.show');
|
||||
const scope=focus=>focus?.projectID===Number(chapterPage.dataset.project)&&focus.bookID===Number(chapterPage.dataset.book)&&!!focus.chapterID;
|
||||
function align(focus){
|
||||
if(!scope(focus))return;
|
||||
if(blocked()){offer('Current Focus changed. Save or cancel the current chapter edits before following it.','Go to Focus',()=>align(window.PlotDirectorNarrativeFocus.state));return;}
|
||||
if(focus.chapterID!==Number(chapterPage.dataset.chapter)){
|
||||
const path=controller==='Writer'?'/Writer/Chapter/':'/Chapters/Details/';location.assign(path+focus.chapterID+'?retainNarrativeFocus=true');return;
|
||||
}
|
||||
chapterPage.querySelectorAll('[aria-current=location]').forEach(n=>n.removeAttribute('aria-current'));
|
||||
const scene=focus.sceneID?chapterPage.querySelector(`[data-pd-context="scene"][data-pd-context-id="${focus.sceneID}"]`):null;
|
||||
if(focus.sceneID&&!scene){offer('The focused scene is not present in this chapter view.','Refresh chapter',()=>{const url=new URL(location.href);url.searchParams.set('retainNarrativeFocus','true');location.assign(url);});return;}
|
||||
offer('Displaying Current Focus: '+focus.label);
|
||||
const target=scene||chapterPage.querySelector('h1');if(scene)scene.setAttribute('aria-current','location');target?.scrollIntoView({block:'center',behavior:'instant'});
|
||||
}
|
||||
registry.register({canGo:scope,unavailable:'Choose a chapter in this chapter page’s book',go:align});
|
||||
window.addEventListener('plotdirector:narrative-focus-changed',e=>align(e.detail));
|
||||
const initial=window.PlotDirectorNarrativeFocus?.state;if(initial)align(initial);
|
||||
window.addEventListener('beforeunload',e=>{if(chapterPage.querySelector('form[data-focus-dirty=true]')&&!submitting){e.preventDefault();e.returnValue='';}});
|
||||
}
|
||||
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}"]`);
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
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();};
|
||||
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});};
|
||||
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;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();}}}
|
||||
@ -21,7 +21,7 @@
|
||||
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);
|
||||
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);});
|
||||
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;}
|
||||
}
|
||||
function publish(){document.querySelector('[data-focus-workspace-status]')?.remove();render();try{if(state.bookID)localStorage.setItem(scopeKey,String(state.bookID));}catch{}
|
||||
@ -50,11 +50,11 @@
|
||||
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();}}}));
|
||||
document.querySelectorAll('[data-global-focus=go]').forEach(b=>b.addEventListener('click',async()=>{const adapter=window.PlotDirectorFocusWorkspace?.adapter;if(busy)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();}}}));
|
||||
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());
|
||||
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.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{}}
|
||||
|
||||
@ -41,16 +41,16 @@
|
||||
select.disabled = !items.length; promotion();
|
||||
}
|
||||
function choose(id) {
|
||||
if (!enabled()) return;
|
||||
if (!enabled()) return false;
|
||||
items = positions(); const found = items.find(p => String(p.id) === String(id));
|
||||
if (!found) return;
|
||||
change(found); sync();
|
||||
if (!found) return false;
|
||||
change(found); sync();return true;
|
||||
}
|
||||
function step(direction) { sync();const candidates=items.map((p,i)=>({p,i})).filter(({p,i})=>p.isScene!==false&&(direction<0?i<index:i>index));const target=direction<0?candidates.at(-1):candidates[0];if(target)choose(target.p.id); }
|
||||
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);}});
|
||||
if(focusAdapter)window.PlotDirectorFocusWorkspace.register({canGo:focus=>host.isConnected&&enabled()&&positions().some(p=>p.isScene!==false&&String(p.id)===String(focus.sceneID)),unavailable:'The focused scene is not available in this local Scene Explorer',go:focus=>{if(!enabled())throw Error('This Scene Explorer is unavailable during the current workspace operation.');reveal();if(!choose(focus.sceneID))throw Error('The focused scene is unavailable in this Scene Explorer.');}});
|
||||
sync();
|
||||
return { sync, choose, step, destroy:()=>events.abort(), get position() { return items[index] || null; }, controls, hint };
|
||||
}
|
||||
|
||||
@ -18,7 +18,7 @@
|
||||
}
|
||||
function filterScenes() { filter(scene, scenes, 'chapter', chapter.value); }
|
||||
function filterChapters() { filter(chapter, chapters, 'book', book.value); filterScenes(); }
|
||||
async function load(push = true) {
|
||||
async function load(push = true, reportFailure = false) {
|
||||
const current = ++request;
|
||||
pending?.abort();
|
||||
if (!scene.value) {
|
||||
@ -45,7 +45,7 @@
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError' && current === request) {
|
||||
snapshot.replaceChildren();
|
||||
feedback.textContent = 'Story state could not be loaded. Use Show state to retry.';
|
||||
feedback.textContent = 'Story state could not be loaded. Use Show state to retry.';if(reportFailure)throw Error(feedback.textContent);
|
||||
}
|
||||
} finally { if (current === request) snapshot.removeAttribute('aria-busy'); }
|
||||
}
|
||||
@ -63,6 +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();}});
|
||||
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(true,true);}});
|
||||
filterChapters();
|
||||
})();
|
||||
|
||||
@ -4,12 +4,13 @@ root.reviewDispose?.();const events=new AbortController();const onWindow=(name,h
|
||||
const editor=root.querySelector('[data-review-editor]');const editorial=root.closest('.writer21-editorial')||root;const form=root.querySelector('[data-review-form]'),context=root.querySelector('[data-review-context]'),message=root.querySelector('[data-review-message]'),reference=root.querySelector('[data-review-reference]'),error=root.querySelector('[data-review-error]'),newButton=root.querySelector('[data-review-new]');
|
||||
let anchor=null,selected=null,page=1,dirty=false,busy=false,loading=false,allowLeave=false,pauseBefore=false,controller=null,generation=0,selectionTimer=null,lastContext='';
|
||||
root.canChangeNarrative=()=>!dirty&&!busy&&!editorial.querySelector('[data-authoring-form]:not([hidden]),[data-busy="true"]')&&!document.querySelector('dialog[open]')&&(getSelection()?.isCollapsed!==false);root.reviewDispose=()=>{events.abort();++generation;clearTimeout(selectionTimer);controller?.abort();};
|
||||
root.selectNarrativeParagraph=async id=>{if(!root.canChangeNarrative())return false;clearTimeout(selectionTimer);if(id){const paragraph=reader.querySelector(`[data-paragraph-id="${CSS.escape(id)}"]`);if(!paragraph)return false;selected=id;anchor={StartParagraph:id,EndParagraph:id,StartOffset:0,EndOffset:paragraph.textContent.length};wordReference(id);reference.textContent='Accepted paragraph selected; nothing is saved until you record an observation.';}await load(true,true);return true;};
|
||||
const field=n=>form.elements.namedItem(n),readerContent=reader.querySelector('#reader-content'),word=document.querySelector('[data-writer-word]');
|
||||
const nodeParagraph=n=>(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest('[data-paragraph-id]');
|
||||
function capture(){const s=getSelection();if(!s||s.isCollapsed||s.rangeCount!==1)return null;const r=s.getRangeAt(0),first=nodeParagraph(r.startContainer),last=nodeParagraph(r.endContainer);if(!first||!last||!readerContent.contains(first)||!readerContent.contains(last))return null;const before=document.createRange();before.selectNodeContents(first);before.setEnd(r.startContainer,r.startOffset);const after=document.createRange();after.selectNodeContents(last);after.setEnd(r.endContainer,r.endOffset);return{StartParagraph:first.dataset.paragraphId,EndParagraph:last.dataset.paragraphId,StartOffset:before.toString().length,EndOffset:after.toString().length};}
|
||||
function wordReference(id){if(!word)return;word.dataset.paragraphId=id||'';word.dataset.acceptedRevision=reader.dataset.revision;window.dispatchEvent(new Event('review-reference-changed'));}
|
||||
function queueContext(){clearTimeout(selectionTimer);selectionTimer=setTimeout(()=>void load(false),180);}
|
||||
async function load(force=true){if(editorial.querySelector('[data-authoring-form][data-dirty="true"]')){message.textContent="Save or Cancel your chapter/scene note editor before changing review context.";return;}clearTimeout(selectionTimer);const key=[selected,anchor?.EndParagraph,reader.dataset.version,page].join(':');if(!force&&key===lastContext)return;const preserve=reader.readerPreserveView?.();const mine=++generation;controller?.abort();controller=new AbortController();loading=true;const url=new URL(root.dataset.panelUrl,location.href);url.search=new URLSearchParams({bookId:root.dataset.book,chapterId:root.dataset.chapter,version:reader.dataset.version,page:String(page),...(selected?{paragraphId:selected,endParagraphId:anchor?.EndParagraph||selected}:{})});try{const response=await fetch(url,{cache:'no-store',signal:controller.signal});if(!response.ok)throw Error();const doc=new DOMParser().parseFromString(await response.text(),'text/html'),panel=doc.querySelector('[data-review-panel]');if(!panel)throw Error();if(mine===generation){context.replaceChildren(panel);const slot=document.querySelector('[data-review-intentions-slot]');if(slot&&panel.querySelector('[data-review-intentions]'))slot.replaceChildren(panel.querySelector('[data-review-intentions]'));
|
||||
async function load(force=true,protectEditor=false){if(editorial.querySelector('[data-authoring-form][data-dirty="true"]')){message.textContent="Save or Cancel your chapter/scene note editor before changing review context.";return;}clearTimeout(selectionTimer);const key=[selected,anchor?.EndParagraph,reader.dataset.version,page].join(':');if(!force&&key===lastContext)return;const preserve=reader.readerPreserveView?.();const mine=++generation;controller?.abort();controller=new AbortController();loading=true;const url=new URL(root.dataset.panelUrl,location.href);url.search=new URLSearchParams({bookId:root.dataset.book,chapterId:root.dataset.chapter,version:reader.dataset.version,page:String(page),...(selected?{paragraphId:selected,endParagraphId:anchor?.EndParagraph||selected}:{})});try{const response=await fetch(url,{cache:'no-store',signal:controller.signal});if(!response.ok)throw Error();const doc=new DOMParser().parseFromString(await response.text(),'text/html'),panel=doc.querySelector('[data-review-panel]');if(!panel)throw Error();if(mine===generation){if(protectEditor&&!root.canChangeNarrative()){message.textContent='Current Focus context update was deferred. Your open edits are retained.';return;}context.replaceChildren(panel);const slot=document.querySelector('[data-review-intentions-slot]');if(slot&&panel.querySelector('[data-review-intentions]'))slot.replaceChildren(panel.querySelector('[data-review-intentions]'));
|
||||
const sceneSlot=document.querySelector('[data-review-scene-context]');if(sceneSlot)sceneSlot.replaceChildren(panel.querySelector('[data-review-scene-intentions]'));
|
||||
const chapterAnnotations=document.querySelector('[data-chapter-annotations]');if(chapterAnnotations){chapterAnnotations.replaceChildren();for(const note of panel.querySelectorAll('[data-observation][data-scope="Chapter"]'))chapterAnnotations.append(note);}
|
||||
const sceneID=panel.dataset.selectedScene||'';if(word){word.dataset.sceneId=sceneID;window.dispatchEvent(new Event('review-reference-changed'));}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user