Unify narrative focus without retargeting Writer objectives

This commit is contained in:
Nick Beckley 2026-11-20 14:24:04 +00:00
parent c2914db194
commit 6d2c51a651
66 changed files with 1277 additions and 125 deletions

View File

@ -0,0 +1,109 @@
# Narrative focus and Scene Explorer: audit, architecture and qualification
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
| Surface | Current mechanism | Classification and migration direction |
| --- | --- | --- |
| Relationships | `RelationshipMapController.Index/State`, `relationship-workspace.js`: range input, Initial/End endpoints, relationship-change markers; debounced state fetch with cancellation. The scene sequence comes from server-provided options. | Local exploration. Preserve Initial/End snapshots and change markers as extensions; scene explorer must not write global focus. Verify ordering and book scope of the State request before replacement: the inspected refresh passes projectId/sceneId, not bookId. |
| Maps | `maps-story.js` maintains scene, chapter, plot, character and time lenses. Scene scrubber uses filtered scene indices; Previous/Next changes to dated-event navigation in Time lens. Session storage key includes user/project/map. `MapStoryService` composes NarrativeOrder and can substitute scenario attribution order. | Local exploration and local filters. Extract scene navigation without conflating Time events, map selection, scenario order or character journeys with global manuscript order. |
| Maps right panel | `renderDetails`, `sceneDetails`, `legDetails`, feature/overview details: scene endpoints, repeated journeys, dates, location coverage and editable travel context. `maps-workspace.js` separately maintains map-edit undo/redo history. | Retain and adapt the detail/history panel. It is not redundant with a scene dropdown. Neither journey history nor edit undo history is recent global-focus history. |
| Floor Plans | `FloorPlans/Edit.cshtml` contains inline occupancy navigation: scene dropdown, Previous/Next by option index, initial-floor selection and occupancy trays. `Scene_ListByFloorPlan` is the data contract (`082_FloorPlanOccupancySceneOrdering.sql`). | Local exploration plus specialised floor/occupancy editing. Preserve edit targets, floors and trays. Validate whether the eligible-scene subset can represent all book positions before attaching a full-book explorer. |
| Writer | `WriterObjectiveRepository`, `WriterController.SaveObjective`, `dbo.WriterObjective` (`280_WriterFocusIntention.sql`) persist chapter/scene together with activity and intention. Review falls back to objective chapter. `WriterContext` explicitly separates Working, SavedObjective, Exploration, PinnedReference, Reader, Session and VerifiedWord. | Existing persisted location is coupled to task data. Requires the decision below before introducing an authoritative global service. |
| Timeline | `Timeline/Index.cshtml` exposes selectedSceneId links, jump-scene controls, scene inspectors and filter-selected scene fields. | Provisional: explicit scene-opening navigation should commit focus; filter matches and inspection must be classified separately before wiring. |
| Plot Lines / Threads | Plot Line workspace exposes scene-inspector controls and attribution/scenario projections. | Provisional: inspection, scenario attribution, filtering and explicit opening are different actions. Do not treat every scene ID as navigation. Trace Thread handlers before consolidation. |
| At This Point | `StoryPoint/Index.cshtml` has book/chapter/scene controls tied to its snapshot. | Provisional: separate deliberate navigation from local reference snapshots before conversion. |
| Reader / Review | `_Reader.cshtml`, `manuscript-reader.js`: chapter Previous/Next, reading mode, focus mode, accepted manuscript and paragraph selections. | Explicit chapter navigation may commit global focus. Reading-mode toggles, scrolling, annotation selection and rendering must not. Preserve specialised manuscript controls where the header is hidden or insufficient. |
| Reflect / Calendar / planning | Not yet fully traced. | Inventory pending. Scheduling, recording-session binding, comparison and activity filters must not be converted by selector-name heuristics. |
| Word | `writer-word.js` reacts to explicit focus-saved events but does not move Word automatically. Navigate/Availability use verified instance, document session, manuscript, revision and accepted paragraph identity; document-position adoption is explicit. | Keep observed Word position separate. Global context may supply intended navigation targets, never manufacture verified paragraph or scene associations. |
## Approved objective boundary
Saved Writer objectives remain independent task targets. The author approved this boundary before implementation. Activity, intention, chapter and scene remain unchanged until explicitly edited. The new focus is seeded once from a valid existing Writer location; later reads never use the objective as a fallback. Go to objective navigates without saving an objective. Objective editors retain explicitly selected targets while global focus changes.
## Shared architecture
1. A read-only, authorised narrative-position provider returns stable BookID/ChapterID/SceneID, display text and manuscript sequence. Use authoritative SortOrder with stable ID tie-breakers; audit existing ordering procedures before selecting one provider. Do not order by fictional timestamps. Scenario order remains an explicitly local alternative.
2. A small Scene Explorer view/component plus JS controller accepts positions, selected ID and a local selection callback. It supplies scrubber, grouped chapter/scene dropdown, mirrored Previous/Next, boundary-disabled states and accessible current-position text. Optional slots retain relationship markers and workspace detail panels. No focus writes occur in its default callbacks.
3. Each visual workspace retains an independent, user/book/workspace-scoped position. Floor-plan occupancy and map filters are not rewritten by header events. Initial/End relationship snapshots remain explicit non-scene positions and cannot be promoted as fabricated scene IDs.
4. One narrative-focus repository/service/API persists current location and bounded deduplicated recency (proposed bound: 20) per authenticated user/project/book, using Dapper and stored procedures. Membership and scene/chapter/book relationships are checked server-side. Changes use a version token; stale multi-window writes are rejected rather than silently overwriting a newer selection.
5. Header selection/search, explicit scene-opening links, global Previous/Next and the explorer's explicit Set Current Focus Here are deliberate commit paths. Global stepping uses the manuscript sequence; recent-history selection uses recency, never scene chronology.
6. Deleted/moved scene identifiers are revalidated on read/commit. Prefer retaining a valid chapter-only focus when a scene disappears; do not jump into another book. Reordering changes neighbour calculations, not stable focus identity. Revalidate and prune invalid recent entries.
7. Successful commits publish a scoped presentation event. Cross-window updates carry scope/version, trigger authorised refresh, and do not navigate the document. Workspace adapters update only safe dependent read-only regions; dirty editors retain their fields and offer explicit application of the new target. No blanket form replacement or synthetic change events.
8. Reader and verified Word adapters keep accepted manuscript identity, paragraph revision checks and recording-session binding independent. A global scene ID is a navigation intention, not proof of a Word position. Scrolling and visualisation selection never invoke Word navigation.
## Staged delivery and qualification
* Stage 1: finish ordering/scope checks; implement the local Scene Explorer and adapters for Relationships, Maps scene lens and Floor Plans. Retain specialised panels and Time lens. Prove no focus writes on local events.
* Stage 2: after resolving the objective boundary, implement focus persistence/history and the header; migrate current-location consumers atomically to one authority. Forward-only SQL after Development backup and live schema verification.
* Stage 3: complete the page inventory, tracing every commit-capable selector. Remove only controls made genuinely redundant; keep local filters, comparisons, edit targets and focus-mode fallbacks.
* Stage 4: integrate explicit Reader/Word navigation using existing verification gates. Retain unsaved editors and active session bindings.
* Stage 5: SQL/service/controller tests for ownership, scope, neighbour order, deleted/reordered/moved scenes and concurrent versions; Chromium and installed PWA across workspaces, refresh, project/book switches, dirty editors, independent local positions and verified/unverified Word targets.
Only qualified changes may deploy to Development. Production is excluded. See the implementation and qualification record below.
## Approved boundary and completed selector classification
The author approved independent saved objectives. The alternative that retargets objectives is rejected. Saving an objective does **not** commit global navigation; Go to objective does. Existing task editors retain their selected fields when the header changes. Recording, observed/verified Word positions and accepted paragraph references are separate bindings.
Inventory was extended before removing any page selector. Classifications below describe semantics, not automatic conversion based on field names:
| Surface / implementation | Classification | Retain / integrate |
| --- | --- | --- |
| Timeline scene-card destination (`SelectedSceneID`, `FocusType`, `FocusID`) | Explicit narrative navigation | Commit when the author follows a scene card; filter restoration, scrolling, search, jump-to-visible-position and drag/reorder do not commit. |
| Timeline controls: BookID, SelectedSceneID, FocusType, FocusID, saved presets | Local filter/highlight | Retain; applying a preset is not narrative navigation. |
| PlotLineWorkspace scene inspector and scenario attribution | Local inspection/comparison and scenario editing | Retain; explicit Open Scene destinations commit through Scenes/Edit. |
| PlotThreads introduced/planned-resolution/actual-resolution scene fields | Persisted entity editing | Retain unchanged; never retarget on navigation. |
| StoryPoint/Index book/chapter/scene and Show state (`story-point.js`) | Local snapshot exploration | Retain and label as snapshot position, not current focus. Its AJAX updates do not write focus. |
| StoryCalendar book/month/date controls | Local chronological filtering | Retain; dates are fictional chronology, not manuscript ordering. Explicit Open Scene commits. |
| Writer Plan / WritingActivity chapter/scene destinations | Explicit navigation from independent task/session records | Retain useful links; preserve schedule/session target IDs. |
| Writer Reflect calendar, date, session and activity controls | Historical filters | Retain; never move recorded sessions. |
| Writer focus wizard and legacy objective form | Independent objective editing | Retain explicit target selectors. Do not subscribe form fields to header events. |
| Writer work toolbar chapter and activity fields / Audio Review | New-session binding or specialised media operation | Retain. Existing sessions keep original binding. |
| Writer authoring chapter/scene intent forms | Explicit editing targets | Retain while editing; header changes defer replacement and offer explicit application after Save/Cancel. |
| Reader chapter picker / Previous / Next | Global chapter navigation | Integrate explicit destinations. Retain in Focus Reading because the normal header is inert/hidden. Reading/focus-mode toggles, paragraph selection and automatic accepted-content refresh never commit focus. |
| Writing Context / Intent jump controls (`writing-follow.js`) | Specialised pinned/snapshot/document-follow reference navigation | Retain and distinguish from global focus. Existing explicit verified Word navigation is a separate operation; following observations is never authoritative global navigation. |
| NativeWorkspace Review scene index and Word-session picker | Verified manuscript repair/navigation | Retain; preserve exact live document/revision checks, no inferred scene mappings. |
| Warnings chapter filter; ContinuityExplorer chapter/start/end/selected scene | Local diagnostic filters/ranges/comparison | Retain; explicit scene-opening links commit independently. |
| Chapters/Edit IDs and nested SceneInspector dependency/character/note/attachment selects | Entity editing | Retain; identifiers bind edits, not global navigation. |
| Admin Story Intelligence chapter selectors | Administrative test/analysis targets | Retain; outside narrative navigation. |
| Scenarios timeline ordering and attribution selectors | Alternative-order editing/comparison | Retain. Never rewrite canonical focus order. |
| Relationships scene position | Local Scene Explorer | Shared controls; retain Initial/End and separately labelled relationship-change stepping. |
| Maps scene position, scene/chapter/character/plot/time lenses | Local Scene Explorer + filters | Shared scene controls; retain time-event navigation and journey/scene/travel-context panel. |
| Floor Plans occupancy scene | Local Scene Explorer + occupancy edit target | Shared controls; retain eligible-scene subset and floor/tray editing. Local events no longer publish to writing-window position bus. |
No page-level selector has been removed on the assumption that a scene ID implies global navigation. Useful specialised controls remain; the header supplies the single normal-workspace global selector.
## Final implementation
- `INarrativeFocus` / `NarrativeFocus` is the sole persistent current-location authority. All database calls use Dapper and stored procedures. `WriterContext.Working`, header display and Writer’s intended Word targets project this service; Review keeps its accepted Reader/paragraph target independently. Saved objectives occupy only `SavedObjective`.
- Migration **292** creates `NarrativeFocus` and `NarrativeFocusHistory`, plus `NarrativeFocus_Read`, `NarrativeFocus_Set` and `NarrativeFocus_Locate`. It also changes `WriterObjective` reads to retain saved target metadata when its chapter/scene becomes unavailable, without modifying the objective. Migration **293** ensures position results follow `NarrativeSceneOrder.BookSceneIndex`, including tied chapter numbers/orders. Migration **294** inserts empty chapters at their chapter position and steps from them to real neighbouring scenes; a moved scene is never followed implicitly into another chapter.
- Current records are keyed by authenticated user/book; every procedure validates the requested project/book against active user access and non-archived entities. A book belongs to one project. Chapter/scene identifiers are revalidated against that book. Deleting a book/user cascades only its focus/history; chapter/scene deletion is handled by read-time validation, retaining a valid chapter where possible. No story entity is modified by navigation.
- Initialisation is locked and transactional. Only a missing focus row can be seeded from a valid Writer objective location. An explicitly empty focus remains empty on subsequent reads. Automatic invalidation increases the version. Commits use an expected version, so stale windows receive HTTP 409 and refresh before retrying. No-op navigation does not add history or write another version. Personal focus navigation remains available in read-only accounts without granting story-content editing.
- History contains at most **20 distinct chapter/scene pairs**, ordered by recency, separate from manuscript neighbours. Invalid/moved history entries are pruned. Reordering changes neighbours, not stable identities.
- `_NarrativeFocus` and `narrative-focus.js` provide header selection, search, previous/next and recent focus. Scoped storage notifications and window-focus/disclosure refresh reconcile windows through the authorised service. Client storage never stores an authoritative chapter/scene fallback. Project-wide pages retain their all-books filters: their focus picker can select a focus book independently. Device storage remembers only that picker’s book scope, not narrative location. Background refreshes queue behind scope selections/commits, so a late disclosure or cross-window refresh cannot revert them.
- `NarrativeNavigationFilter` commits only successful, deliberate chapter/scene destinations. Background fetches, AJAX inspection and prefetches do not commit. Timeline scene-card/scene-link destinations explicitly identify navigation; filters, presets, scrolling, entity back-links and edit cancellation do not. The one-use navigation marker is removed from the displayed URL after navigation.
- Writer shows current narrative location separately from the saved objective and offers **Go to objective**. Its chapter-only **Go to scene** shortcut now navigates through the focus service; it no longer posts to `SaveObjective` and cannot clear an intention. The objective wizard and legacy form keep explicit target fields, including unavailable saved targets that require explicit replacement. Unsaved wizard edits protect full-page navigation; Cancel restores the last confirmed target. Post-edit return redirects retain the independently selected global focus.
- `scene-explorer.js` composes shared native dropdown/range controls, matched chevrons, manuscript stepping, accessible output and an explicit promotion action. There are no implicit focus writes. Relationships retains Initial/End snapshots and change-marker navigation; scene buttons skip non-scene snapshots. Maps retains its six lenses, journey/scene/travel-context detail panel and separate dated-event navigation. Default/global scene order is canonical manuscript order; explicitly selected scenarios retain their existing local projected manuscript order, never fictional-event chronology. Floor Plans retains its eligible-scene subset, floors and occupancy editing; its sequence now follows manuscript sort order. Local positions remain independent and are retained using workspace-scoped session storage (Maps keeps its existing storage mechanism).
- Promotion is available only for a real scene in the header’s current book. For another book, choose that focus book first. Initial/End snapshots cannot be promoted as fabricated scene IDs.
- Writer’s inline editors defer content changes while open/dirty/busy. Review changes chapter within its stable three-column container and preserves divider elements, Word state objects and recording controls. Unsaved annotations retain their original chapter/reference; authors apply pending focus after saving or cancelling. Annotation filters and the existing Pause/Resume updates checkbox state survive the refresh; the label/icon use that same state immediately. A global scene can select an already accepted, mapped paragraph; missing mappings remain explicit and never create scene associations.
- Verified Word observations, accepted paragraph identities and recording-session bindings remain independent. The verified Word-origin adoption action changes global focus, not objectives. A default Reader preview does not set global focus, and its Word target remains the displayed accepted chapter rather than an invented global location. Word navigation/synchronisation still uses the existing document/session/manuscript/revision and availability checks; global navigation never moves Word automatically.
## Qualification record
Development database backup: `COPY_ONLY`, checksum, compression and `RESTORE VERIFYONLY` succeeded before migrations. Only Development was used. SQL regressions create disposable synthetic books/scenes and roll back every fixture; existing author story/objective records are not edited by the tests.
Qualification commands and results follow. The deployment identifier is recorded in the task completion report and the Development release archive. Screenshots are generated under `/tmp/pd-narrative-*` by `PlotLine.Tests/Browser/narrative-focus.cjs`. The browser host renders real compiled Razor and production JavaScript using isolated fixture repositories; Word transport is simulated. No physical Word Companion acceptance is implied.
- `dotnet build PlotLine.slnx`: successful, zero warnings/errors.
- `dotnet run --no-build --project PlotLine.Tests`: full executable regression harness, 632 PASS checks.
- `PlotLine.Tests/Sql/NarrativeFocus.sql`: six rollback-only phases passed as both Development administrator and application principal. Covers one-time seed/no fallback, author/project/book scope, CAS, canonical order across chapters, empty chapters, bounded/deduplicated history, reordered/moved/deleted/archived targets, objective preservation and fixture cleanup.
- `sudo -n dotnet PlotLine.Tests/bin/Debug/net10.0/PlotLine.Tests.dll --narrative-focus-database /etc/plotdirector/plotdirector.env`: actual Dapper repository integration passed. Verifies multi-result DTO mapping, Read/Set/Open, expected book scope, history, independent objective fields and complete ambient-transaction rollback. Connections close before chained repository operations to avoid pool starvation.
- `node PlotLine.Tests/Browser/narrative-focus.cjs` and `xvfb-run -a node PlotLine.Tests/Browser/narrative-focus.cjs --installed`: real compiled MVC/Razor/JavaScript passed in Chromium and installed Chromium PWA (CDP-installed app; standalone display mode asserted). Includes Timeline → Writer, header scene stepping/search/recency, independent objective fields and editors, explicit Go actions, stale-window conflict, account/book isolation, antiforgery, full book-switch cancellation with unsaved work, stable Review updates, Pause/Resume preservation, local exploration/promotion, local position persistence, project-wide focus-book selection, reopen, light/dark and narrower widths. A synthetic 5,000-scene header search/render took under 60 ms in measured runs.
- Existing Maps Story browser/PWA suite passed: six lenses, canonical navigation, repeated journeys, travel context, stable canvas and 500 scenes/5,000 appearances; 50 scene changes took about one second.
- Existing Relationships suite passed: 75 characters/300 scenes, local timeline, change markers, editing, layout and PWA controls. Visual inspection found and fixed clipping by replacing the fixed timeline-row height with content sizing; all controls are visible at 1666, 950 and 650 px.
- Floor Plan save regression passed: failed/redirected/invalid saves, retained blocks, overlapping edits and navigation protection in browser/PWA.
- Writer Word, Writer authoring and Manuscript Reader suites passed. Word transport/receipts are simulated. Authoring covers save/cancel, concurrent edits, retained unsaved text and scoped fields; obsolete test selectors were updated to the existing ribbon command and current labels. Reader covers real Razor/controllers, private responses, chapter navigation/empty chapters, focus mode and three widths × four themes × browser/PWA.
Reader’s chapter picker and chapter-level shortcuts remain for Focus Reading, native GET/no-script navigation and chapter-level operations; the central scene navigator does not duplicate those specialised contracts. Reference-window selectors, calendar/history filters, diagnostic comparisons and persisted editing targets remain local. No physical Word device was available: live hardware acceptance remains outside these fixture-based checks. No other implementation limitation is known.

View File

@ -50,6 +50,12 @@ internal static class ApplicationNavigationTests
request.QueryString = QueryString.Empty;
var writing = await navigation.BuildAsync(new WritingContextPageViewModel { ProjectID = 7, BookID = 12 }, "Writer", request);
Check(writing.Project == project && writing.Book == book, "Writing window scope should resolve without changing it.");
var focus = Proxy<INarrativeFocus>((name,args)=>name=="Read"?Task.FromResult(new NarrativeFocusState{ProjectID=7,BookID=12,ChapterID=22,SceneID=32,Version=6}):throw new Exception("Navigation rendering must not commit focus"));
var shared = new ApplicationNavigation(projects,books,user,focus);
var writer = await shared.BuildAsync(new WriterDashboardViewModel{ProjectID=7,BookID=12,Destination="Write",Objective=new(){ChapterID=21,SceneID=31}},"Writer",request);
Check(writer.WordChapterID==22&&writer.WordSceneID==32,"Word intention comes from authoritative navigation, never a saved objective.");
var explorer = await shared.BuildAsync(new {ProjectID=7,BookID=12,SceneID=999,ChapterID=999},"Relationships",request);
Check(explorer.WordChapterID==22&&explorer.WordSceneID==32,"Local visualisation position cannot become a global or Word target.");
var before = bookCalls;
var denied = await navigation.BuildAsync(new WritingIntentPageViewModel { ProjectID = 88, BookID = 12 }, "Writer", request);
Check(denied.Project is null && denied.Books.Count == 0 && bookCalls == before, "Unauthorised scope must not expose books or project actions.");

View File

@ -0,0 +1,99 @@
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 errors=[];p.on('pageerror',e=>errors.push(e.message));let objectiveWrites=0;p.on('request',r=>{if(r.method()==='POST'&&r.url().includes('/Writer/SaveObjective'))objectiveWrites++;});
await p.goto(base+'/Timeline/Index?ProjectID=7&BookID=12');await p.locator('.timeline-scene-card[data-scene-id="32"]').click();
await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.sceneID===32);assert.equal(await p.locator('.timeline-scene-card[aria-current=location]').getAttribute('data-scene-id'),'32');
assert(!new URL(p.url()).searchParams.has('navigateFocus'),'one-use navigation marker removed');
const url=base+'/Writer/Write?projectId=7&bookId=12&objective=true';await p.goto(url+'&setup=true');
await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);
assert.equal(await p.evaluate(()=>window.PlotDirectorNarrativeFocus.state.sceneID),32,'Writer shares the scene explicitly opened in Timeline');
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}));
const original=await p.locator('[data-objective-location]').textContent();
await p.locator('[data-focus-wizard]').waitFor({state:'visible'});
await p.locator('[data-focus-next]').click();await p.locator('[data-objective-chapter]').selectOption('21');await p.locator('[data-objective-scene]').selectOption('31');
const beforeEditor=await p.locator('[data-focus-wizard]').evaluate(f=>Object.fromEntries(new FormData(f)));
assert(await set({chapterID:22,sceneID:32}));assert.equal((await state()).sceneID,32);
assert.equal(await p.locator('[data-objective-location]').textContent(),original);
assert.deepEqual(await p.locator('[data-focus-wizard]').evaluate(f=>Object.fromEntries(new FormData(f))),beforeEditor,'open objective editor keeps explicit targets');
assert.equal(objectiveWrites,0,'global navigation never writes the objective');
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-narrative-focus]>summary').click();await p.locator('button[data-focus-step="1"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===101);await p.locator('button[data-focus-step="1"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===32,'cross-chapter forward');
await p.locator('button[data-focus-step="-1"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===101);
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 p.locator('[data-focus-search]').fill('');
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);
const stale=await state(),token=await p.locator('[data-narrative-focus] [name=__RequestVerificationToken]').inputValue();
const staleResponse=await c.request.post(base+'/NarrativeFocus/Set',{form:{projectId:7,bookId:12,chapterId:21,sceneId:31,version:stale.version-1,__RequestVerificationToken:token}});assert.equal(staleResponse.status(),409);
assert.equal((await c.request.post(base+'/NarrativeFocus/Set',{form:{projectId:7,bookId:12,chapterId:21,sceneId:31,version:stale.version}})).status(),400,'antiforgery required');
assert.equal((await c.request.get(base+'/NarrativeFocus/Read?projectId=8&bookId=12')).status(),404,'scope isolation');
const isolated=await require('playwright').request.newContext({extraHTTPHeaders:{Cookie:'fixture-user=5'}});const isolatedState=await(await isolated.get(base+'/NarrativeFocus/Read?projectId=7&bookId=12')).json();assert.equal(isolatedState.sceneID,31,'another author has independent focus');await isolated.dispose();
await other.close();await p.reload();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus?.state.sceneID===32);assert.equal(await p.locator('[data-objective-location]').textContent(),original);
await p.goto(base+'/Writer/Write?projectId=7&bookId=13');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);assert.equal((await state()).sceneID,null,'book focus never leaks');
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');
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`});}
await p.setViewportSize({width:1666,height:1050});
await p.goto(url);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await set({chapterID:21,sceneID:31});
const sceneCard=p.locator('[data-key="Scene-31"]');await sceneCard.waitFor();await sceneCard.locator('[data-authoring-edit]').click();await sceneCard.locator('[name=ScenePurposeNotes]').fill('Unsaved scene 31 intention');
const editorNode=await sceneCard.locator('[data-authoring-form]').elementHandle();await set({chapterID:21});
assert.equal(await sceneCard.locator('[name=ScenePurposeNotes]').inputValue(),'Unsaved scene 31 intention');assert(await editorNode.evaluate(n=>n.isConnected),'unsaved inline editor stays mounted');assert.equal(await sceneCard.locator('[name=sceneId]').inputValue(),'31','inline save remains bound to original scene');
await sceneCard.locator('[data-authoring-cancel]').click();await p.getByRole('button',{name:'Show current focus',exact:true}).click();await p.waitForFunction(()=>!document.querySelector('[data-key="Scene-31"]')&&document.querySelector('[data-key="Goals-21"]'));
await p.locator('[data-narrative-scene="31"]').click();await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus.state.sceneID===31);assert.equal(objectiveWrites,0,'Go to scene does not edit an objective');
await set({});await p.goto(base+'/Writer/Review?projectId=7&bookId=12');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus&&document.querySelector('[data-writer-word]'));assert.equal((await state()).chapterID,null,'displaying the Reader default does not set global focus');assert.equal(await p.locator('[data-writer-word]').getAttribute('data-chapter-id'),'21','Reader Word target remains its accepted chapter independently of an empty global focus');
await p.goto(base+'/Writer/Review?projectId=7&bookId=12&chapterId=21');
await p.waitForFunction(()=>document.querySelector('[data-writer-review]')?.canChangeNarrative);
await p.waitForFunction(()=>document.querySelector('[data-review-panel]'));
await p.evaluate(()=>{window.__columns=document.querySelector('[data-review-columns]');window.__left=document.getElementById('review-chapter-notes');window.__word=document.querySelector('[data-writer-word]');window.__work=document.querySelector('[data-writer-work]');});
let documentLoads=0;const countNavigation=request=>{if(request.isNavigationRequest()&&request.resourceType()==='document')documentLoads++;};p.on('request',countNavigation);
await p.locator('#reader-pause-toggle').evaluate(n=>n.click());assert(await p.locator('#reader-pause').isChecked());
assert(await set({chapterID:22,sceneID:32}));
await p.waitForFunction(()=>document.querySelector('.manuscript-reader')?.dataset.chapterId==='22');
assert(await p.locator('#reader-pause').isChecked(),'existing pause state survives in-place navigation');assert.equal(await p.locator('#reader-pause-toggle').textContent(),'Resume updates');
assert.equal(documentLoads,0,'global chapter navigation refreshes Review without page navigation');p.off('request',countNavigation);
assert(await p.evaluate(()=>window.__columns===document.querySelector('[data-review-columns]')&&window.__left===document.getElementById('review-chapter-notes')&&window.__word===document.querySelector('[data-writer-word]')&&window.__work===document.querySelector('[data-writer-work]')),'stable columns, session bindings and Word object');
await p.locator('[data-review-scope-new="Chapter"]').evaluate(n=>n.click());await p.locator('[data-review-form] textarea[name=Observation]').fill('Unsaved review on chapter 22');
assert(await set({chapterID:21,sceneID:31}));assert.equal(await p.locator('.manuscript-reader').getAttribute('data-chapter-id'),'22');assert.equal(await p.locator('[data-review-form] textarea[name=Observation]').inputValue(),'Unsaved review on chapter 22');assert.equal(await p.locator('[data-review-form] [name=ChapterID]').inputValue(),'22','annotation stays bound to original chapter');
await p.locator('[data-review-cancel]').click();await p.locator('[data-review-focus-notice] button').click();await p.waitForFunction(()=>document.querySelector('.manuscript-reader')?.dataset.chapterId==='21');
await p.waitForFunction(()=>document.querySelector('[data-review-panel]'));
await p.screenshot({path:`/tmp/pd-narrative-${installed?'pwa':'browser'}-Review.png`});
await p.goto(base+'/fixture?page=relationships');await p.waitForFunction(()=>window.PlotDirectorRelationshipWorkspace&&window.PlotDirectorNarrativeFocus);
const relationshipState=await p.evaluate(()=>{const w=window.PlotDirectorRelationshipWorkspace;return {cast:w.cast,relationships:w.relationships(),links:w.cy.edges().map(e=>({characterRelationshipID:e.data('relationshipID'),sourceCharacterID:Number(e.data('source').slice(2)),targetCharacterID:Number(e.data('target').slice(2)),relationshipLabel:e.data('label'),cssClass:e.classes().join(' '),intensity:e.data('intensity')}))};});
await p.route('**/RelationshipMap/State?**',r=>r.fulfill({json:relationshipState}));const versionBefore=(await state()).version;
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');
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}));
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');
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-narrative-focus]>summary').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 p.locator('button[data-focus-step="-1"]').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`);
}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

@ -1,7 +1,7 @@
const{chromium}=require('playwright'),assert=require('node:assert/strict');
(async()=>{const b=await chromium.launch();try{for(const pwa of[false,true]){
const c=await b.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()})));if(pwa)await c.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:null,defaultPauseOnEdit:true}}));
const p=await c.newPage(),errors=[];let posts=0;p.on('request',r=>{if(r.method()==='POST'&&new URL(r.url()).pathname==='/WriterAuthoring/Save')posts++;});p.on('pageerror',e=>errors.push(e.message));const url='http://127.0.0.1:5238/Writer/Write?projectId=7&bookId=12&objective=true';await p.goto(url);await p.locator('[data-key="Scene-31"]').waitFor();assert((await p.locator('[data-authoring-references]').textContent()).includes('Fixture character'));
const p=await c.newPage(),errors=[];let posts=0;p.on('request',r=>{if(r.method()==='POST'&&new URL(r.url()).pathname==='/WriterAuthoring/Save')posts++;});p.on('pageerror',e=>errors.push(e.message));const url='http://127.0.0.1:5238/Writer/Write?projectId=7&bookId=12&objective=true';await p.goto(url);await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await p.evaluate(()=>window.PlotDirectorNarrativeFocus.set({chapterID:21,sceneID:31}));await p.locator('[data-key="Scene-31"]').waitFor();assert((await p.locator('[data-authoring-references]').textContent()).includes('Fixture character'));
const help=p.locator('[data-help-key="writer3.authoring"] button');await help.click();await p.locator('.plotline-help-popover').waitFor();assert((await p.locator('.plotline-help-popover').textContent()).includes('More...'));await p.locator('.plotline-help-more').click();await p.locator('[data-help-content] .help-drawer-article').waitFor();assert((await p.locator('[data-help-content]').textContent()).includes('Cancel'));await p.locator('[data-help-close]').click();
const card=k=>p.locator(`[data-key="${k}"]`),edit=async k=>{await card(k).getByRole('button',{name:/^Edit|^Add/}).first().click();},save=async k=>{const before=posts;await card(k).locator('[data-authoring-form]').evaluate(n=>{n.requestSubmit();n.requestSubmit();});await card(k).locator('[data-authoring-status]').filter({hasText:'Saved.'}).waitFor();assert.equal(posts,before+1,'duplicate submit is ignored');};
await edit('Scene-31');await card('Scene-31').locator('[name=ScenePurposeNotes]').fill('Unsaved cancellation');await card('Scene-31').locator('[data-authoring-cancel]').click();assert(!(await card('Scene-31').textContent()).includes('Unsaved cancellation'));
@ -10,14 +10,14 @@ const{chromium}=require('playwright'),assert=require('node:assert/strict');
await edit('Chapter-21');await card('Chapter-21').locator('[name=Summary]').fill('Chapter summary inline');await card('Chapter-21').locator('[name=ChapterPurposeID]').selectOption('1');await save('Chapter-21');
await edit('AddNote-0');await card('AddNote-0').locator('[name=NoteText]').fill('Remember the recorded detail');await card('AddNote-0').locator('[name=NoteTitle]').fill('Inline note');await save('AddNote-0');const note=p.locator('[data-authoring-new-records] [data-kind=Note]').last();await note.getByRole('button',{name:/^Edit/}).click();await note.locator('[name=NoteText]').fill('Edited note');await note.locator('[data-authoring-save]').click();await p.locator('[data-authoring-new-records] [data-kind=Note]').last().locator('[data-authoring-status]').filter({hasText:'Saved.'}).waitFor();
await edit('AddChecklist-0');await card('AddChecklist-0').locator('[name=ItemText]').fill('A reminder');await save('AddChecklist-0');
await p.getByText('All scene notes, reminders and working details',{exact:true}).click();await edit('Workflow-31');await card('Workflow-31').locator('[name=Priority]').fill('11');await card('Workflow-31').locator('[data-authoring-save]').click();await card('Workflow-31').locator('[data-authoring-error]:visible').waitFor();assert.equal(await card('Workflow-31').locator('[name=Priority]').inputValue(),'11');await card('Workflow-31').locator('[name=Priority]').fill('2');await card('Workflow-31').locator('[name=IsBlocked]').check();await save('Workflow-31');
await p.getByText('Scene notes, reminders and working details',{exact:true}).click();await edit('Workflow-31');await card('Workflow-31').locator('[name=Priority]').fill('11');await card('Workflow-31').locator('[data-authoring-save]').click();await card('Workflow-31').locator('[data-authoring-error]:visible').waitFor();assert.equal(await card('Workflow-31').locator('[name=Priority]').inputValue(),'11');await card('Workflow-31').locator('[name=Priority]').fill('2');await card('Workflow-31').locator('[name=IsBlocked]').check();await save('Workflow-31');
await edit('Scene-31');await card('Scene-31').locator('[name=ScenePurposeNotes]').fill('Retain after network failure');await p.route('**/WriterAuthoring/Save',r=>r.fulfill({status:503,body:'temporarily unavailable'}));await card('Scene-31').locator('[data-authoring-save]').click();await card('Scene-31').locator('[data-authoring-error]:visible').waitFor();assert.equal(await card('Scene-31').locator('[name=ScenePurposeNotes]').inputValue(),'Retain after network failure');await p.unroute('**/WriterAuthoring/Save');await card('Scene-31').locator('[data-authoring-cancel]').click();
// A second page commits first; the original editor must retain its stale unsaved text with409.
await edit('Scene-31');await card('Scene-31').locator('[name=ScenePurposeNotes]').fill('Stale unsaved intention');const q=await c.newPage();await q.goto(url);const other=q.locator('[data-key="Scene-31"]');await other.locator('[data-authoring-edit]').click();await other.locator('[name=ScenePurposeNotes]').fill('Concurrent author change');await other.locator('[data-authoring-save]').click();await other.locator('[data-authoring-status]').filter({hasText:'Saved.'}).waitFor();await q.close();await card('Scene-31').locator('[data-authoring-save]').click();await card('Scene-31').locator('[data-authoring-reload]:visible').waitFor();assert.equal(await card('Scene-31').locator('[name=ScenePurposeNotes]').inputValue(),'Stale unsaved intention');
p.once('dialog',d=>d.dismiss());await p.locator('#ribbon-panel-writer').getByRole('link',{name:'Explore',exact:true}).click();assert(new URL(p.url()).pathname==='/Writer/Write');await card('Scene-31').locator('[data-authoring-cancel]').click();
const session={sessionID:'33333333-3333-3333-3333-333333333333',kind:'AudioReview',bookID:12,chapterID:22,chapterTitle:'Bound audio chapter',startedUtc:new Date().toISOString(),engagedSeconds:60,playbackSeconds:20,uniqueSeconds:10,pauseOnEdit:true,live:true,playbackState:'playing',capabilities:'play,pause,back15,forward15',sequence:1};await p.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session}}));await p.goto(url);await p.locator('[data-work-audio]:visible').waitFor();await card('Scene-31').waitFor();assert(await p.locator('.writer3-session-block').evaluate(n=>n.nextElementSibling?.matches('[data-writer-authoring]')),'active controls remain above authoring');const work=await p.locator('[data-writer-work]').elementHandle();await p.locator('[data-work-note]').fill('Unsaved audio return note');await edit('Scene-31');await card('Scene-31').locator('[name=SceneOutcomeNotes]').fill('An explicit outcome during audio review');await save('Scene-31');assert(await work.evaluate(n=>n===document.querySelector('[data-writer-work]')));assert.equal(await p.locator('[data-work-note]').inputValue(),'Unsaved audio return note');assert((await p.locator('[data-work-bound]').textContent()).includes('Bound audio chapter'));assert.equal(await p.locator('[data-work-start] select').count(),2,'Windows baseline retains independent recording activity and chapter controls');
await p.setViewportSize({width:390,height:844});await p.locator('.writer3-layout-tools button').first().click();assert(await p.locator('[data-authoring-references]').isVisible());await p.keyboard.press('Escape');assert(await p.locator('.writer3-reference').isHidden());assert(await p.locator('[data-authoring-content]').isVisible());
await p.goto(url+'&chapterOnly=true');await p.locator('[data-key="Goals-21"]').waitFor();assert.equal(await p.locator('[data-key="Scene-31"]').count(),0);assert(await p.getByRole('button',{name:'Work on this scene'}).isVisible());
await p.goto('http://127.0.0.1:5238/Writer/Write?projectId=7&bookId=13');assert.equal(await p.locator('[data-writer-authoring]').count(),0,'book switching cannot keep old support fields');assert.equal((await p.request.get('http://127.0.0.1:5238/WriterAuthoring/Inspect?bookId=13&chapterId=21&sceneId=31')).status(),404);assert.deepEqual(errors,[]);await c.close();}
await p.setViewportSize({width:390,height:844});const companionToggle=p.locator('[data-writer-companion-toggle]');for(const menu of await companionToggle.locator('xpath=ancestor::details').all()){if(!await menu.evaluate(n=>n.open))await menu.locator(':scope > summary').click();}await companionToggle.click();assert(await p.locator('[data-authoring-references]').isVisible());await p.keyboard.press('Escape');assert(await p.locator('.writer3-reference').isHidden());assert(await p.locator('[data-authoring-content]').isVisible());
await p.goto(url+'&chapterOnly=true');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await p.evaluate(()=>window.PlotDirectorNarrativeFocus.set({chapterID:21}));await p.locator('[data-key="Goals-21"]').waitFor();assert.equal(await p.locator('[data-key="Scene-31"]').count(),0);assert(await p.getByRole('button',{name:'Go to scene'}).isVisible());
await p.goto('http://127.0.0.1:5238/Writer/Write?projectId=7&bookId=13');assert(await p.locator('[data-writer-authoring]').isHidden(),'book switching hides unavailable support fields');assert.equal(await p.locator('[data-writer-authoring] [data-authoring-form]').count(),0,'book switching cannot keep old support fields');assert.equal((await p.request.get('http://127.0.0.1:5238/WriterAuthoring/Inspect?bookId=13&chapterId=21&sceneId=31')).status(),404);assert.deepEqual(errors,[]);await c.close();}
console.log('PASS Writer3 authoring browser/simulated PWA: scene/chapter/goal editing, Cancel, escaped Unicode, unrelated dirty fields, note/reminder creation/edit, workflow validation, stale409 retention, navigation guard, chapter-only focus, scope and companion overlay.');
}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1});

View File

@ -0,0 +1,41 @@
using System.Data;
using System.Transactions;
using Dapper;
using Microsoft.Data.SqlClient;
using PlotLine.Data;
using PlotLine.Services;
internal static class NarrativeFocusDatabaseTests
{
private sealed record Fixture(int UserID,int ProjectID,int BookID,int ChapterID,int SceneID);
private sealed class Factory(string connectionString):ISqlConnectionFactory
{public IDbConnection CreateConnection()=>new SqlConnection(connectionString);}
public static async Task Run(string environmentFile)
{
var line=File.ReadLines(environmentFile).Single(x=>x.StartsWith("ConnectionStrings__DefaultConnection="));
var value=line[(line.IndexOf('=')+1)..].Trim();
if(value.Length>1&&((value[0]=='"'&&value[^1]=='"')||(value[0]=='\''&&value[^1]=='\'')))value=value[1..^1];
var builder=new SqlConnectionStringBuilder(value);
if(builder.InitialCatalog!="PlotDirector_Development")throw new InvalidOperationException("Refusing a non-Development database");
var sql=File.ReadAllText(Path.Combine("PlotLine.Tests","Sql","NarrativeFocusRepositoryFixture.sql"));
Fixture fixture;
// Sequential pooled connections enlist in one ambient transaction. Never Complete it.
using(var rollback=new TransactionScope(TransactionScopeOption.RequiresNew,new TransactionOptions{IsolationLevel=System.Transactions.IsolationLevel.ReadCommitted,Timeout=TimeSpan.FromMinutes(2)},TransactionScopeAsyncFlowOption.Enabled))
{
using(var db=new SqlConnection(builder.ConnectionString))fixture=await db.QuerySingleAsync<Fixture>(sql,new{ExistingBook=(int?)null});
var factory=new Factory(builder.ConnectionString);var focus=new NarrativeFocus(factory);var objectives=new WriterObjectiveRepository(factory);
var before=(await objectives.Read(fixture.UserID,fixture.BookID)).Objective!;
var state=await focus.Read(fixture.UserID,fixture.ProjectID,fixture.BookID);
if(state.SceneID!=fixture.SceneID||state.Positions.Count!=1||state.Recent.Single().SceneID!=fixture.SceneID)throw new Exception("Repository seed/position/history mapping failed");
state=await focus.Set(fixture.UserID,fixture.ProjectID,fixture.BookID,fixture.ChapterID,null,state.Version);
if(state.SceneID!=null||state.ChapterID!=fixture.ChapterID)throw new Exception("Repository chapter navigation failed");
if(await focus.Open(fixture.UserID,null,fixture.SceneID,fixture.ProjectID,fixture.BookID+1)!=null)throw new Exception("Repository accepted an explicit destination in the wrong book");
state=(await focus.Open(fixture.UserID,null,fixture.SceneID,fixture.ProjectID,fixture.BookID))!;
if(state.SceneID!=fixture.SceneID||state.Recent.Count!=2)throw new Exception("Repository explicit destination/history deduplication failed");
var after=(await objectives.Read(fixture.UserID,fixture.BookID)).Objective!;
if(before.Activity!=after.Activity||before.Intention!=after.Intention||before.ChapterID!=after.ChapterID||before.SceneID!=after.SceneID)throw new Exception("Navigation altered an objective");
}
using(var db=new SqlConnection(builder.ConnectionString))
if(await db.QuerySingleAsync<int>(sql,new{ExistingBook=fixture.BookID})!=0)throw new Exception("Repository fixture did not roll back");
Console.WriteLine("PASS Development Dapper repository: seed and mapped results, Set/Open, scope validation, history, independent objectives and fixture rollback");
}
}

View File

@ -0,0 +1,31 @@
using PlotLine.Services;
// Isolated browser-host repository. Production persistence/security is tested against SQL separately.
internal sealed class NarrativeFocusFixture : INarrativeFocus
{
private readonly object gate=new();
private readonly Dictionary<(int,int),NarrativeFocusState> states=new();
public Task<NarrativeFocusState> Read(int user,int project,int book)
{
lock(gate){if(user is not (4 or 5)||project!=7||book is not (12 or 13))throw new UnauthorizedAccessException();
if(!states.TryGetValue((user,book),out var state))states[(user,book)]=state=new(){ProjectID=project,BookID=book,ChapterID=book==12?21:null,SceneID=book==12?31:null,Version=1,Positions=book==12?[
new(){ChapterID=21,ChapterNumber=1,ChapterTitle="The crossing",SceneID=31,SceneNumber=1,SceneTitle="Arrival",BookSceneIndex=1},
new(){ChapterID=21,ChapterNumber=1,ChapterTitle="The crossing",SceneID=101,SceneNumber=2,SceneTitle="A second scene",BookSceneIndex=2},
new(){ChapterID=22,ChapterNumber=2,ChapterTitle="The harbour",SceneID=32,SceneNumber=1,SceneTitle="Departure",BookSceneIndex=3},
new(){ChapterID=23,ChapterNumber=3,ChapterTitle="Unwritten"}]:[]};return Task.FromResult(state);}
}
public async Task<NarrativeFocusState> Set(int user,int project,int book,int? chapter,int? scene,long version,int direction=0)
{
var state=await Read(user,project,book);
lock(gate){state=states[(user,book)];if(state.Version!=version)throw new NarrativeFocusConflictException();
if(direction!=0){var scenes=state.Positions.Where(p=>p.SceneID.HasValue).ToArray();var index=Array.FindIndex(scenes,p=>p.SceneID==state.SceneID);NarrativePosition? target;
if(index>=0)target=scenes.ElementAtOrDefault(index+direction);
else {var chapterScenes=scenes.Where(p=>p.ChapterID==state.ChapterID).ToArray();var chapterIndex=state.Positions.ToList().FindIndex(p=>p.ChapterID==state.ChapterID);var candidates=chapterScenes.Length>0?chapterScenes:chapterIndex<0?scenes:state.Positions.Where((p,i)=>p.SceneID.HasValue&&(direction<0?i<chapterIndex:i>chapterIndex)).ToArray();target=direction<0?candidates.LastOrDefault():candidates.FirstOrDefault();}
if(target is null)return state;scene=target.SceneID;chapter=target.ChapterID;}
var found=state.Positions.FirstOrDefault(p=>scene.HasValue?p.SceneID==scene:p.ChapterID==chapter);
if((scene.HasValue||chapter.HasValue)&&found is null)throw new UnauthorizedAccessException();
chapter=found?.ChapterID;if(chapter==state.ChapterID&&scene==state.SceneID)return state;var history=state.Recent.Where(p=>p.ChapterID!=chapter||p.SceneID!=scene).ToList();
if(chapter.HasValue)history.Insert(0,new(chapter.Value,scene,state.Version+1));
return states[(user,book)]=state with{ChapterID=chapter,SceneID=scene,Version=state.Version+1,Recent=history.Take(20).ToArray()};}
}
public async Task<NarrativeFocusState?> Open(int user,int? chapter,int? scene,int? expectedProject=null,int? expectedBook=null){if(expectedProject.HasValue&&expectedProject!=7||expectedBook.HasValue&&expectedBook!=12)return null;var state=await Read(user,7,12);return await Set(user,7,12,chapter,scene,state.Version);}
}

View File

@ -0,0 +1,48 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using PlotLine.Services;
internal static class NarrativeNavigationTests
{
public static async Task Run()
{
int writes=0;
var focus=NativeWorkflowTests.Proxy<INarrativeFocus>((name,args)=>{
if(name!="Open"||args![0] is not int actor||actor!=4)throw new Exception("Unexpected focus operation");
writes++;return Task.FromResult<NarrativeFocusState?>(new(){ProjectID=7,BookID=12,ChapterID=21,SceneID=(int?)args[2],Version=2});
});
var user=NativeWorkflowTests.Proxy<ICurrentUserService>((_,_) => (int?)4);
foreach(var item in new[]{
("Scenes","Edit","GET","",true,true), ("Chapters","Details","GET","",true,true),
("Writer","Chapter","GET","",true,true), ("RelationshipMap","State","GET","?sceneId=31",true,false),
("Maps","Story","GET","?sceneId=31",true,false), ("FloorPlans","Edit","GET","?sceneId=31",true,false),
("Timeline","Index","GET","?SelectedSceneID=31",true,false),
("Timeline","Index","GET","?SelectedSceneID=31&navigateFocus=true",true,true),
("Scenes","Edit","GET","?retainNarrativeFocus=true",true,false), ("Scenes","Edit","GET","?ajax",true,false), ("Scenes","Edit","GET","?prefetch",true,false),
("Scenes","Edit","GET","",false,false), ("Scenes","Edit","POST","",true,false)})
{
var http=new DefaultHttpContext();http.Request.Method=item.Item3;http.Request.QueryString=new(item.Item4);
if(item.Item4=="?ajax")http.Request.Headers["Sec-Fetch-Mode"]="cors";if(item.Item4=="?prefetch")http.Request.Headers["Sec-Purpose"]="prefetch";
var route=new RouteData();route.Values["controller"]=item.Item1;route.Values["action"]=item.Item2;
var action=new ActionContext(http,route,new ActionDescriptor());var filter=new NarrativeNavigationFilter(focus,user);
var executing=new ActionExecutingContext(action,[],new Dictionary<string,object?>{{"id",31}},new object());
var executed=new ActionExecutedContext(action,[],new object()){Result=item.Item5?new ViewResult():new NotFoundResult()};
var before=writes;await filter.OnActionExecutionAsync(executing,()=>Task.FromResult(executed));
if(writes-before!=(item.Item6?1:0))throw new Exception($"Narrative navigation classification failed: {item}");
}
var savedContext=new DefaultHttpContext();savedContext.Request.Method="POST";var savedRoute=new RouteData();savedRoute.Values["controller"]="Scenes";
var saveAction=new ActionContext(savedContext,savedRoute,new ActionDescriptor());var redirect=new RedirectToActionResult("Edit","Scenes",new{id=31});
var savedResult=new ActionExecutedContext(saveAction,[],new object()){Result=redirect};
await new NarrativeNavigationFilter(focus,user).OnActionExecutionAsync(new(saveAction,[],new Dictionary<string,object?>(),new object()),()=>Task.FromResult(savedResult));
if(redirect.RouteValues?["retainNarrativeFocus"] is not true)throw new Exception("Saving an editor must preserve independently navigated focus");
var navigationController=new PlotLine.Controllers.NarrativeFocusController(focus,user);
var navigationAction=new ActionExecutingContext(saveAction,[],new Dictionary<string,object?>(),navigationController);
bool allowedNavigation=false;
await new SubscriptionEnforcementFilter(user,NativeWorkflowTests.Proxy<ISubscriptionService>((_,_)=>throw new Exception("Narrative navigation must not require content-edit entitlement")))
.OnActionExecutionAsync(navigationAction,()=>{allowedNavigation=true;return Task.FromResult(new ActionExecutedContext(saveAction,[],navigationController));});
if(!allowedNavigation)throw new Exception("Read-only accounts must retain narrative navigation");
Console.WriteLine("PASS deliberate narrative destinations commit focus; local visualisation, filtering, failed opens and edits submitted by POST do not");
}
}

View File

@ -15,6 +15,7 @@ using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
if(args.Contains("--narrative-focus-database")){await NarrativeFocusDatabaseTests.Run(args.Last());return;}
if(args.Contains("--production-investigation")){ProductionInvestigationTests.Run(args.Last());return;}
if(args.Contains("--writer-investigation-diagnostics")){if(args.Contains("--acceptance"))InvestigationDiagnosticTests.Run();InvestigationDiagnosticTests.Export(args[^2],args[^1]);return;}
if(args.Contains("--writer-investigation-sim")){InvestigationTests.Run();var output=args.SkipWhile(x=>x!="--writer-investigation-sim").Skip(1).FirstOrDefault();var report=InvestigationTests.Simulate(output);Console.WriteLine($"PASS investigation simulation: {report.Paths} paths, {report.Steps} answers; all hypotheses and destinations reachable; no loops/repeats/premature/invalid/non-deterministic outcomes.");return;}
@ -197,6 +198,7 @@ var tests = new (string Name, Action Test)[]
("Review accepted anchors, immutable provenance and author decisions",()=>WriterReviewTests.Run()),
("Writer Word verified navigation and acknowledgement",()=>WriterWordTests.Run().GetAwaiter().GetResult()),
("Writer inline authoring validation",()=>WriterAuthoringTests.Run()),
("Narrative navigation action boundary",()=>NarrativeNavigationTests.Run().GetAwaiter().GetResult()),
("Writer 3 destination navigation and scope",()=>WriterNavigationTests.Run().GetAwaiter().GetResult()),
("Writer foundation context, queue scope and planning",()=>WriterFoundationTests.Run().GetAwaiter().GetResult()),
("Writer dashboard book scope",()=>WriterDashboardTests.Run().GetAwaiter().GetResult()),

View File

@ -0,0 +1,106 @@
-- Development only. Fresh synthetic books/scenes; every fixture is rolled back.
SET NOCOUNT ON;
IF DB_NAME()<>'PlotDirector_Development' THROW 51999,'Wrong database',1;
DECLARE @user int,@project int,@revision int,@time int,@confidence int;
SELECT TOP(1) @user=a.UserID,@project=p.ProjectID FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.IsActive=1 WHERE p.IsArchived=0 ORDER BY p.ProjectID;
SELECT TOP(1) @revision=RevisionStatusID,@time=TimeModeID,@confidence=TimeConfidenceID FROM dbo.Scenes;
IF @user IS NULL OR @revision IS NULL THROW 51999,'No fixture scope',1;
DECLARE @phase int=0;
WHILE @phase<6
BEGIN
DECLARE @book int,@otherBook int,@chapter int,@otherChapter int,@empty int,@tail int,@first int,@last int,@version bigint,@i int=1;
BEGIN TRY
BEGIN TRANSACTION;
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@project,N'Disposable narrative focus fixture',99999,99999);SET @book=SCOPE_IDENTITY();
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@project,N'Disposable other scope',99999,99999);SET @otherBook=SCOPE_IDENTITY();
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,1,N'Fixture first chapter',1,@revision);SET @chapter=SCOPE_IDENTITY();
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,2,N'Fixture second chapter',2,@revision);SET @otherChapter=SCOPE_IDENTITY();
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,1.5,N'Empty middle fixture chapter',1,@revision);SET @empty=SCOPE_IDENTITY();
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,3,N'Empty final fixture chapter',3,@revision);SET @tail=SCOPE_IDENTITY();
WHILE @i<=25
BEGIN
DECLARE @targetChapter int=CASE WHEN @i<=2 THEN @chapter ELSE @otherChapter END;
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID)
VALUES(@targetChapter,26-@i,CONCAT(N'Fixture scene ',@i),@i,@time,@confidence,@revision);
IF @i=1 SET @first=SCOPE_IDENTITY();IF @i=25 SET @last=SCOPE_IDENTITY();SET @i+=1;
END;
INSERT dbo.WriterWorkingObjectives(UserID,BookID,ChapterID,SceneID,Activity,Intention) VALUES(@user,@book,@chapter,@first,N'Revising',N'Independent original objective');
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@book;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@chapter AND SceneID=@first) THROW 51999,'Initial valid objective was not seeded',1;
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@otherBook;
IF @phase IN(1,2,3)
BEGIN
DECLARE @wrongUser int=CASE WHEN @phase=1 THEN -1 ELSE @user END,@wrongProject int=CASE WHEN @phase=2 THEN -1 ELSE @project END,@wrongBook int=CASE WHEN @phase=3 THEN @otherBook ELSE @book END;
EXEC dbo.NarrativeFocus_Set @UserID=@wrongUser,@ProjectID=@wrongProject,@BookID=@wrongBook,@SceneID=@first,@ExpectedVersion=1;
THROW 51999,'Unauthorised focus accepted',1;
END;
IF @phase=4
BEGIN
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@SceneID=@last,@ExpectedVersion=0;
THROW 51999,'Stale window focus accepted',1;
END;
SET @i=1;
WHILE @i<25
BEGIN
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@ExpectedVersion=@version,@Direction=1;
SET @i+=1;
END;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@otherChapter AND SceneID=@last) THROW 51999,'Manuscript order/boundary navigation failed',1;
IF (SELECT COUNT(*) FROM dbo.NarrativeFocusHistory WHERE UserID=@user AND BookID=@book)<>20 THROW 51999,'History is not bounded',1;
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@ChapterID=@empty,@ExpectedVersion=@version;
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@ExpectedVersion=@version,@Direction=1;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND SceneID=(SELECT TOP(1) SceneID FROM dbo.NarrativeSceneOrder WHERE ChapterID=@otherChapter ORDER BY BookSceneIndex)) THROW 51999,'Forward navigation from empty chapter failed',1;
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@ChapterID=@empty,@ExpectedVersion=@version;
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@ExpectedVersion=@version,@Direction=-1;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND SceneID=(SELECT TOP(1) SceneID FROM dbo.NarrativeSceneOrder WHERE ChapterID=@chapter ORDER BY BookSceneIndex DESC)) THROW 51999,'Reverse navigation from empty chapter failed',1;
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@ChapterID=@tail,@ExpectedVersion=@version;
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@ExpectedVersion=@version,@Direction=1;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@tail AND SceneID IS NULL) THROW 51999,'Final empty chapter crossed the book boundary',1;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@ExpectedVersion=@version,@Direction=-1;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND SceneID=@last) THROW 51999,'Final empty chapter has no previous scene',1;
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@SceneID=@first,@ExpectedVersion=@version;
IF (SELECT COUNT(*) FROM dbo.NarrativeFocusHistory WHERE UserID=@user AND BookID=@book AND SceneID=@first)<>1 THROW 51999,'Recent history duplicated',1;
-- Reorder does not retarget either persistent record.
UPDATE dbo.Scenes SET SortOrder=999 WHERE SceneID=@first;
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@book;
IF NOT EXISTS(SELECT 1 FROM dbo.WriterWorkingObjectives WHERE UserID=@user AND BookID=@book AND ChapterID=@chapter AND SceneID=@first AND Activity=N'Revising' AND Intention=N'Independent original objective') THROW 51999,'Navigation retargeted objective',1;
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@ExpectedVersion=@version;
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@book;
IF EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND(ChapterID IS NOT NULL OR SceneID IS NOT NULL)) THROW 51999,'Objective reused as implicit fallback',1;
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@SceneID=@first,@ExpectedVersion=@version;
UPDATE dbo.Scenes SET ChapterID=@otherChapter WHERE SceneID=@first;
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@book;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@chapter AND SceneID IS NULL) THROW 51999,'Moved scene was silently followed',1;
IF EXISTS(SELECT 1 FROM dbo.NarrativeFocusHistory WHERE UserID=@user AND BookID=@book AND ChapterID=@chapter AND SceneID=@first) THROW 51999,'Invalid history survived',1;
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@SceneID=@last,@ExpectedVersion=@version;
DELETE dbo.Scenes WHERE SceneID=@last;
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@book;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@otherChapter AND SceneID IS NULL) THROW 51999,'Deleted scene retained or silently retargeted',1;
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@ChapterID=@chapter,@ExpectedVersion=@version;
UPDATE dbo.Chapters SET IsArchived=1 WHERE ChapterID=@chapter;
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@book;
IF EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID IS NOT NULL) THROW 51999,'Archived chapter retained',1;
EXEC dbo.WriterObjective @UserID=@user,@BookID=@book;
IF NOT EXISTS(SELECT 1 FROM dbo.WriterWorkingObjectives WHERE UserID=@user AND BookID=@book AND SceneID=@first AND ChapterID=@chapter) THROW 51999,'Invalid objective target mutated',1;
ROLLBACK;
END TRY
BEGIN CATCH
DECLARE @error int=ERROR_NUMBER();IF XACT_STATE()<>0 ROLLBACK;
IF @phase IN(0,5) OR (@phase IN(1,2,3) AND @error<>51000) OR(@phase=4 AND @error<>51001) THROW;
END CATCH;
IF EXISTS(SELECT 1 FROM dbo.Books WHERE BookID IN(@book,@otherBook)) THROW 51999,'Fixture leaked',1;
PRINT CONCAT('PASS NarrativeFocus SQL phase ',@phase);
SET @phase+=1;
END;

View File

@ -0,0 +1,17 @@
-- Used only by the rollback-only Dapper repository integration test.
SET NOCOUNT ON;
IF DB_NAME()<>'PlotDirector_Development' THROW 51999,'Wrong database',1;
IF @ExistingBook IS NOT NULL
BEGIN
SELECT COUNT(*) Remaining FROM dbo.Books WHERE BookID=@ExistingBook;
RETURN;
END;
DECLARE @user int,@project int,@book int,@chapter int,@scene int,@revision int,@time int,@confidence int;
SELECT TOP(1) @user=a.UserID,@project=p.ProjectID FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.IsActive=1 WHERE p.IsArchived=0 ORDER BY p.ProjectID;
SELECT TOP(1) @revision=RevisionStatusID,@time=TimeModeID,@confidence=TimeConfidenceID FROM dbo.Scenes;
IF @user IS NULL OR @revision IS NULL THROW 51999,'No fixture scope',1;
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@project,N'Disposable repository focus fixture',99999,99999);SET @book=SCOPE_IDENTITY();
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,1,N'Repository fixture chapter',1,@revision);SET @chapter=SCOPE_IDENTITY();
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@chapter,1,N'Repository fixture scene',1,@time,@confidence,@revision);SET @scene=SCOPE_IDENTITY();
INSERT dbo.WriterWorkingObjectives(UserID,BookID,ChapterID,SceneID,Activity,Intention) VALUES(@user,@book,@chapter,@scene,N'Revising',N'Independent fixture objective');
SELECT @user UserID,@project ProjectID,@book BookID,@chapter ChapterID,@scene SceneID;

View File

@ -104,6 +104,7 @@ internal static class ToolbarBrowserHost
if(context.Request.Query["objective"]=="true")model.Objective=new(){BookID=12,ChapterID=21,SceneID=context.Request.Query["chapterOnly"]=="true"?null:31,Activity="Revising",ChapterTitle="The crossing",SceneTitle="Arrival"};
if(context.Request.Query["populated"]=="true")model.Activity=new(){BookID=12,Totals=new(){Added=120,Removed=30,HasAcceptedEvidence=true,RecordedEvents=2}};
}else model.WriteNext=[];
model.NarrativeFocus=context.RequestServices.GetRequiredService<INarrativeFocus>().Read(context.RequestServices.GetRequiredService<ICurrentUserService>().UserId!.Value,7,book).GetAwaiter().GetResult();
return model;
}
@ -125,7 +126,7 @@ internal static class ToolbarBrowserHost
public static async Task RunAsync()
{
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { EnvironmentName = "Development", ApplicationName = typeof(ToolbarController).Assembly.FullName, ContentRootPath = Path.GetFullPath("PlotLine") });
builder.Services.AddControllersWithViews().AddApplicationPart(typeof(ToolbarController).Assembly);
builder.Services.AddControllersWithViews(options=>options.Filters.Add<NarrativeNavigationFilter>()).AddApplicationPart(typeof(ToolbarController).Assembly);
builder.Services.AddSignalR();
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationAccess>();
builder.Services.AddSingleton<IInvestigationRepository,InvestigationMemoryRepository>();
@ -140,18 +141,27 @@ internal static class ToolbarBrowserHost
builder.Services.AddSingleton(FixtureProxy<IOnboardingBuildRepository>((name, args) => throw new NotSupportedException(name)));
builder.Services.AddSingleton(FixtureProxy<IManuscriptScanPreviewStore>((name, args) => throw new NotSupportedException(name)));
builder.Services.AddSingleton(FixtureProxy<ITimelineService>((name,args)=>{
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,
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<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));
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton<IAppearanceRepository, AppearanceMemoryPreferences>();
builder.Services.AddSingleton<INarrativeFocus,NarrativeFocusFixture>();
builder.Services.AddScoped<ApplicationNavigation>(services => new ApplicationNavigation(
FixtureProxy<IProjectRepository>((name, args) => name == "GetForUserAsync"
? Task.FromResult<Project?>(new Project { ProjectID = 7, ProjectName = "The Glass Harbour", AccessRole = "Owner" }) : throw new NotSupportedException(name)),
FixtureProxy<IBookRepository>((name, args) => name == "ListByProjectAsync"
? Task.FromResult<IReadOnlyList<Book>>([new() { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" }, new() { BookID = 13, ProjectID = 7, BookTitle = "The Return" }]) : throw new NotSupportedException(name)),
services.GetRequiredService<ICurrentUserService>()));
services.GetRequiredService<ICurrentUserService>(), services.GetRequiredService<INarrativeFocus>()));
builder.Services.AddSingleton(FixtureProxy<IBookRepository>((name,args)=>name switch {
"ListByProjectAsync" => Task.FromResult<IReadOnlyList<Book>>([new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore"},new(){BookID=13,ProjectID=7,BookTitle="The Return"}]),
"GetAsync" => Task.FromResult<Book?>((int)args![0]! is 12 or 13 ? new(){BookID=(int)args[0]!,ProjectID=7,BookTitle=(int)args[0]! == 12?"A Distant Shore":"The Return"} : null),
@ -366,6 +376,7 @@ internal static class ToolbarBrowserHost
model.Project = new Project { ProjectID = 7, ProjectName = "The Glass Harbour", AccessRole = context.Request.Query["owner"] == "false" ? "Editor" : "Owner" };
model.Book = new Book { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore", BookNumber = 1 };
model.Books = [model.Book, new Book { BookID = 13, ProjectID = 7, BookTitle = "The Return", BookNumber = 2 }];
model.NarrativeFocus=await context.RequestServices.GetRequiredService<INarrativeFocus>().Read(context.RequestServices.GetRequiredService<ICurrentUserService>().UserId!.Value,7,12);
}
var fullLayout = context.Request.Query["layout"] == "full";
string? fullView = null;
@ -605,6 +616,7 @@ internal static class ToolbarBrowserHost
surface = await Render("FloorPlans/Edit", new FloorPlanEditorViewModel {
Project = model.Project!,
FloorPlan = new() { ProjectID = 7, FloorPlanID = 31, Name = "Fixture building" },
OccupancyScenes=[new(){SceneID=31,Label="Chapter 1 · Scene 1: Arrival"},new(){SceneID=101,Label="Chapter 1 · Scene 2: Second scene"},new(){SceneID=32,Label="Chapter 2 · Scene 1: Departure"}],
Floors = [new() { FloorPlanFloorID = 41, FloorPlanID = 31, Name = "Ground floor" }],
Blocks = [new() { FloorPlanBlockID = 51, FloorPlanFloorID = 41, LocationName = "Study", X = 2, Y = 2, WidthCells = 3, HeightCells = 2 }]
});
@ -625,7 +637,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='1' data-pd-project-id='7' class='app-layout'><header class='pd-application-header'>" + menu + toolbar + "</header><template data-pwa-initial-contributions>" + contributions + "</template><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/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

@ -26,15 +26,16 @@ internal static class WriterNavigationTests
_=>throw new Exception(n)});
var schedules=NativeWorkflowTests.Proxy<IWritingScheduleService>((n,a)=>n=="GetTodayDashboardAsync"?Task.FromResult(new WritingScheduleDashboardViewModel()):throw new Exception("Navigation attempted schedule mutation "+n));
var access=NativeWorkflowTests.Proxy<IProjectAccessService>((n,a)=>Task.FromResult(allowed));
var controller=new WriterController(workspace,schedules,books,access){ControllerContext=new(){HttpContext=new Microsoft.AspNetCore.Http.DefaultHttpContext{User=new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity([new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.NameIdentifier,"4")],"Fixture"))}}};
var focus=NativeWorkflowTests.Proxy<INarrativeFocus>((name,args)=>name=="Read"?Task.FromResult(new NarrativeFocusState{ProjectID=7,BookID=(int)args![2]!,ChapterID=(int)args[2]! ==12?22:null,SceneID=(int)args[2]! ==12?99:null,Version=5}):throw new Exception("Page display must not write focus: "+name));
var controller=new WriterController(workspace,schedules,books,access,narrativeFocus:focus){ControllerContext=new(){HttpContext=new Microsoft.AspNetCore.Http.DefaultHttpContext{User=new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity([new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.NameIdentifier,"4")],"Fixture"))}}};
var routes=new Dictionary<string,Func<int,Task<IActionResult>>>{
["Home"]=b=>controller.Index(7,b),["Write"]=b=>controller.Write(7,b),["Explore"]=b=>controller.Explore(7,b),
["Plan"]=b=>controller.Plan(7,b),["Review"]=b=>controller.Review(7,b),["Reflect"]=b=>controller.Reflect(7,b),["Dashboard"]=b=>controller.Dashboard(7,b)};
foreach(var (destination,load) in routes){
var first=(ViewResult)await load(12);var model=(WriterDashboardViewModel)first.Model!;
Check(model.Destination==destination&&model.BookID==12&&model.WorkingContext?.Working?.SceneID==31,"destination "+destination+" preserves authorised book and saved working focus");
Check(model.Destination==destination&&model.BookID==12&&model.WorkingContext?.Working?.SceneID==99&&model.WorkingContext.SavedObjective?.SceneID==31&&model.Objective?.SceneID==31,"destination "+destination+" uses shared current location while preserving the independent objective");
var second=(ViewResult)await load(13);model=(WriterDashboardViewModel)second.Model!;
Check(model.BookID==13&&model.Objective==null&&model.WorkingContext?.Working==null,"destination "+destination+" never carries a focus into another book");
Check(model.BookID==13&&model.Objective==null&&model.WorkingContext?.Working?.SceneID==null&&model.WorkingContext?.SavedObjective==null,"destination "+destination+" never carries a focus into another book");
Check(await load(999) is NotFoundResult,"destination "+destination+" refuses unavailable book");
}
Check((await controller.Index(7,12,workspace:"Revision") is RedirectToActionResult queueAlias&&queueAlias.ActionName=="Workspaces"&&(string?)queueAlias.RouteValues!["workspace"]=="Revision")&&(await controller.Index(7,12,journey:true) is RedirectToActionResult reflection&&reflection.ActionName=="Reflect"),"legacy query routes still reach their actual workspaces/calendar");

View File

@ -0,0 +1,23 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Services;
namespace PlotLine.Controllers;
[Authorize,ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public sealed class NarrativeFocusController(INarrativeFocus focus,ICurrentUserService currentUser) : Controller
{
[HttpGet]
public Task<IActionResult> Read(int projectId,int bookId) => Execute(() => focus.Read(currentUser.UserId!.Value,projectId,bookId));
[HttpPost,ValidateAntiForgeryToken]
public Task<IActionResult> Set(int projectId,int bookId,int? chapterId,int? sceneId,long version,int direction=0) =>
Execute(() => focus.Set(currentUser.UserId!.Value,projectId,bookId,chapterId,sceneId,version,direction));
private async Task<IActionResult> Execute(Func<Task<NarrativeFocusState>> operation)
{
if(currentUser.UserId is null)return Challenge();
if(!ModelState.IsValid)return BadRequest(new{message="Choose a valid chapter or scene."});
try{return Json(await operation());}
catch(UnauthorizedAccessException){return NotFound();}
catch(SqlException e)when(e.Number==51000){return NotFound(new{message="This narrative position is no longer available in this book."});}
catch(NarrativeFocusConflictException){return Conflict(new{message="Current focus changed in another window. Review it and try again."});}
}
}

View File

@ -12,7 +12,7 @@ namespace PlotLine.Controllers;
public sealed class WriterController(
IWriterWorkspaceService writerWorkspace,
IWritingScheduleService writingSchedule,
IBookRepository? bookRepository=null, IProjectAccessService? access=null, WritingActivityRepository? activity=null, WriterObjectiveRepository? objectives=null, WriterWorkRepository? work=null, PlotLine.Services.Writer.IWriterSuggestionProvider? suggestions=null, WriterPlanningRepository? planning=null) : Controller
IBookRepository? bookRepository=null, IProjectAccessService? access=null, WritingActivityRepository? activity=null, WriterObjectiveRepository? objectives=null, WriterWorkRepository? work=null, PlotLine.Services.Writer.IWriterSuggestionProvider? suggestions=null, WriterPlanningRepository? planning=null, INarrativeFocus? narrativeFocus=null) : Controller
{
public Task<IActionResult> Index(int? projectId, int? bookId = null, string? workspace = null, bool journey = false, int? year = null, int? month = null, DateTime? day = null, bool setup = false)
{
@ -30,14 +30,32 @@ public sealed class WriterController(
Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive";
var result=await LoadDestination("Review",projectId,bookId);
if(result is ViewResult {Model:WriterDashboardViewModel model}&&model.BookID.HasValue&&reader!=null){
if(!chapterId.HasValue&&model.Objective?.ChapterID is int workingChapter&&model.ObjectiveChoices.Any(x=>x.ChapterID==workingChapter))chapterId=workingChapter;
try{model.ReviewReader=await reader.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),model.BookID.Value,chapterId);if(model.ReviewReader==null)return NotFound();model.ReviewReader.FocusReading=focus;model.ReviewReader.IntegratedReview=true;model.ReviewReader.ReadingMode=reading;}
try{
if(chapterId.HasValue && narrativeFocus != null && model.ProjectID is int project && int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var author))
{
var current=model.NarrativeFocus!;
if(current.ChapterID!=chapterId) {model.NarrativeFocus=await narrativeFocus.Set(author,project,model.BookID.Value,chapterId,null,current.Version);if(model.WorkingContext!=null)model.WorkingContext=model.WorkingContext.Select(PlotLine.Services.Writer.WriterFocusRole.Working,new(project,model.BookID.Value,model.NarrativeFocus.ChapterID,model.NarrativeFocus.SceneID));}
}
chapterId ??= model.NarrativeFocus?.ChapterID;
model.ReviewReader=await reader.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),model.BookID.Value,chapterId);if(model.ReviewReader==null)return NotFound();model.ReviewReader.FocusReading=focus;model.ReviewReader.IntegratedReview=true;model.ReviewReader.ReadingMode=reading;}
catch(UnauthorizedAccessException){return NotFound();}
catch(SqlException e)when(e.Number==51000){return NotFound();}
catch(NarrativeFocusConflictException){return Conflict(new{message="Current focus changed in another window. Retry this navigation."});}
catch(Exception e)when(e is SqlException or TimeoutException or System.Text.Json.JsonException){Response.StatusCode=503;return View("~/Views/ManuscriptReader/Unavailable.cshtml",new{BookId=model.BookID,ChapterId=chapterId});}
}
return result;
}
[HttpGet,ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public async Task<IActionResult> ReviewContent(int projectId,int bookId,long version,bool focus=false,bool reading=false,[FromServices] PlotLine.Services.Manuscript.ManuscriptReaderService? reader=null)
{
var result=await Review(projectId,bookId,null,focus,reading,reader);
if(result is ViewResult {Model:WriterDashboardViewModel model})
{
if(model.NarrativeFocus?.Version!=version)return Conflict(new{message="Current focus changed. Retry the current location."});
return PartialView("_WriterReview",model);
}
return result;
}
public Task<IActionResult> Reflect(int? projectId, int? bookId = null, int? year=null, int? month=null, DateTime? day=null) => LoadDestination("Reflect", projectId, bookId, journey:true, year:year, month:month, day:day);
public Task<IActionResult> Dashboard(int? projectId, int? bookId = null) => LoadDestination("Dashboard", projectId, bookId);
public Task<IActionResult> Overview(int? projectId, int? bookId = null) => LoadDestination("Legacy", projectId, bookId);
@ -86,6 +104,8 @@ public sealed class WriterController(
model.Objective = working.Objective;
model.ObjectiveChoices = working.Choices;
}
if(narrativeFocus != null && model.ProjectID is int focusProject && model.BookID is int focusBook && int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var focusUser))
model.NarrativeFocus=await narrativeFocus.Read(focusUser,focusProject,focusBook);
model.Workspace=workspace is "InProgress" or "Revision" or "FinalPass" or "StoryHealth"?workspace:"WriteNext";
model.Journey=journey;
model.WritingSchedule = await writingSchedule.GetTodayDashboardAsync(projectId,model.BookID);
@ -106,10 +126,12 @@ public sealed class WriterController(
if (model.Objective is {} focus)
{
var selected = new PlotLine.Services.Writer.WriterSelection(model.ProjectID.Value, model.BookID.Value, focus.ChapterID, focus.SceneID);
model.WorkingContext = model.WorkingContext.Select(PlotLine.Services.Writer.WriterFocusRole.SavedObjective, selected)
.Select(PlotLine.Services.Writer.WriterFocusRole.Working, selected);
model.WorkingContext = model.WorkingContext.Select(PlotLine.Services.Writer.WriterFocusRole.SavedObjective, selected);
}
}
if(model.NarrativeFocus is {} currentFocus && model.WorkingContext != null)
model.WorkingContext=model.WorkingContext.Select(PlotLine.Services.Writer.WriterFocusRole.Working,
new(currentFocus.ProjectID,currentFocus.BookID,currentFocus.ChapterID,currentFocus.SceneID));
model.Suggestions = (suggestions ?? new PlotLine.Services.Writer.WriterSuggestionProvider()).Suggest(model);
model.Destination = destination;
return View(destination == "Home" ? "Index" : destination == "Legacy" ? "Legacy" : "Destination", model);

View File

@ -28,6 +28,7 @@ public class Program
builder.Services.AddControllersWithViews(options =>
{
options.Filters.Add<ProjectAccessFilter>();
options.Filters.Add<NarrativeNavigationFilter>();
options.Filters.Add<SubscriptionEnforcementFilter>();
});
builder.Services.AddSignalR(options =>
@ -214,6 +215,7 @@ public class Program
builder.Services.AddScoped<PlotLine.Services.Writer.IWriterReviewService,PlotLine.Services.Writer.WriterReviewService>();
builder.Services.AddScoped<PlotLine.Services.Writer.IWriterAuthoringService, PlotLine.Services.Writer.WriterAuthoringService>();
builder.Services.AddScoped<WriterObjectiveRepository>();
builder.Services.AddScoped<INarrativeFocus, NarrativeFocus>();
builder.Services.AddScoped<WriterWorkRepository>();
builder.Services.AddScoped<WriterPlanningRepository>();
builder.Services.AddScoped<WriterActivityRepository>();

View File

@ -6,7 +6,7 @@ namespace PlotLine.Services;
// Request-scoped: existing project partials register their already-authorised context
// while the body renders, before the shared layout renders the application menu.
public sealed class ApplicationNavigation(IProjectRepository projects, IBookRepository books, ICurrentUserService currentUser)
public sealed class ApplicationNavigation(IProjectRepository projects, IBookRepository books, ICurrentUserService currentUser, INarrativeFocus? narrativeFocus = null)
{
public Project? Project { get; set; }
@ -55,8 +55,13 @@ public sealed class ApplicationNavigation(IProjectRepository projects, IBookRepo
result.Project = project;
result.Books = projectBooks.Where(x => !x.IsArchived).ToList();
result.Book = result.Books.FirstOrDefault(x => x.BookID == selectedBookId);
result.WordChapterID = (model as WriterDashboardViewModel)?.ReviewReader?.Chapter?.ChapterID ?? ((model as WriterDashboardViewModel)?.Destination=="Write" ? (model as WriterDashboardViewModel)?.Objective?.ChapterID : null) ?? PositiveId(Property(model,"ChapterID")) ?? PositiveId(Property(Property(model,"Scene"),"ChapterID"));
result.WordSceneID = ((model as WriterDashboardViewModel)?.Destination=="Write" ? (model as WriterDashboardViewModel)?.Objective?.SceneID : null) ?? PositiveId(Property(model,"SceneID")) ?? PositiveId(Property(Property(model,"Scene"),"SceneID"));
if (narrativeFocus != null && result.Book is {} selectedBook)
result.NarrativeFocus = await narrativeFocus.Read(userId, project.ProjectID, selectedBook.BookID);
if(result.Book is null && request.HttpContext.Items["NarrativeFocus.Navigation"] is NarrativeFocusState opened && opened.ProjectID==project.ProjectID && result.Books.Any(b=>b.BookID==opened.BookID))
result.NarrativeFocus=opened;
// Current navigation never falls back to the saved objective or a local visualisation.
result.WordChapterID = result.NarrativeFocus?.ChapterID;
result.WordSceneID = result.NarrativeFocus?.SceneID;
return result;
}

View File

@ -8675,12 +8675,11 @@ public sealed class FloorPlanService(
OccupancyScenes = occupancyScenes
.OrderBy(x => x.BookSortOrder)
.ThenBy(x => x.BookNumber)
.ThenBy(x => x.BookDisplayTitle)
.ThenBy(x => x.ChapterSortOrder)
.ThenBy(x => x.ChapterNumber)
.ThenBy(x => x.SceneNumber)
.ThenBy(x => x.SortOrder)
.ThenBy(x => x.SceneTitle)
.ThenBy(x => x.SceneNumber)
.ThenBy(x => x.SceneID)
.Select(x => new FloorPlanOccupancySceneViewModel
{
SceneID = x.SceneID,

View File

@ -0,0 +1,64 @@
using System.Data;
using Dapper;
using PlotLine.Data;
namespace PlotLine.Services;
public sealed record NarrativePosition
{
public int ChapterID { get; init; }
public string ChapterTitle { get; init; } = "";
public decimal ChapterNumber { get; init; }
public int? SceneID { get; init; }
public string? SceneTitle { get; init; }
public decimal? SceneNumber { get; init; }
public long? BookSceneIndex { get; init; }
public string Label => $"Ch {ChapterNumber:0.##}: {ChapterTitle}" + (SceneID.HasValue ? $" · Scene {SceneNumber:0.##}: {SceneTitle}" : "");
}
public sealed record NarrativeRecent(int ChapterID, int? SceneID, long Sequence);
public sealed record NarrativeFocusState
{
public int ProjectID { get; init; }
public int BookID { get; init; }
public int? ChapterID { get; init; }
public int? SceneID { get; init; }
public long Version { get; init; }
public IReadOnlyList<NarrativePosition> Positions { get; init; } = [];
public IReadOnlyList<NarrativeRecent> Recent { get; init; } = [];
public NarrativePosition? Position => Positions.FirstOrDefault(p => p.ChapterID == ChapterID && (!SceneID.HasValue || p.SceneID == SceneID));
public string Label => Position is {} p ? SceneID.HasValue ? p.Label : $"Ch {p.ChapterNumber:0.##}: {p.ChapterTitle}" : "Choose chapter or scene";
}
public sealed class NarrativeFocusConflictException() : Exception("Current focus changed in another window. Review it and try again.");
public interface INarrativeFocus
{
Task<NarrativeFocusState?> Open(int user, int? chapter, int? scene, int? expectedProject=null, int? expectedBook=null);
Task<NarrativeFocusState> Read(int user, int project, int book);
Task<NarrativeFocusState> Set(int user, int project, int book, int? chapter, int? scene, long version, int direction = 0);
}
public sealed class NarrativeFocus(ISqlConnectionFactory factory) : INarrativeFocus
{
public async Task<NarrativeFocusState?> Open(int user,int? chapter,int? scene,int? expectedProject=null,int? expectedBook=null)
{
NarrativeFocusState? target;
using(var db=factory.CreateConnection())
target=await db.QuerySingleOrDefaultAsync<NarrativeFocusState>("dbo.NarrativeFocus_Locate",new{UserID=user,ChapterID=chapter,SceneID=scene},commandType:CommandType.StoredProcedure);
if(target is null || expectedProject.HasValue&&target.ProjectID!=expectedProject || expectedBook.HasValue&&target.BookID!=expectedBook)return null;
var current=await Read(user,target.ProjectID,target.BookID);
return await Set(user,target.ProjectID,target.BookID,target.ChapterID,target.SceneID,current.Version);
}
public async Task<NarrativeFocusState> Read(int user, int project, int book)
{
using var db = factory.CreateConnection();
using var rows = await db.QueryMultipleAsync("dbo.NarrativeFocus_Read", new { UserID=user, ProjectID=project, BookID=book }, commandType:CommandType.StoredProcedure);
var state = await rows.ReadSingleAsync<NarrativeFocusState>();
return state with { Positions=(await rows.ReadAsync<NarrativePosition>()).ToArray(), Recent=(await rows.ReadAsync<NarrativeRecent>()).ToArray() };
}
public async Task<NarrativeFocusState> Set(int user,int project,int book,int? chapter,int? scene,long version,int direction=0)
{
using(var db = factory.CreateConnection())
{
try{await db.ExecuteAsync("dbo.NarrativeFocus_Set", new { UserID=user,ProjectID=project,BookID=book,ChapterID=chapter,SceneID=scene,ExpectedVersion=version,Direction=direction },commandType:CommandType.StoredProcedure);}
catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51001){throw new NarrativeFocusConflictException();}
}
return await Read(user,project,book);
}
}

View File

@ -0,0 +1,44 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Data.SqlClient;
namespace PlotLine.Services;
// Only successfully opened narrative destinations commit focus. Inspection, filters,
// partial rendering, Word observation and visualisation requests are deliberately absent.
public sealed class NarrativeNavigationFilter(INarrativeFocus focus,ICurrentUserService currentUser) : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context,ActionExecutionDelegate next)
{
var result=await next();
var request=context.HttpContext.Request;
if(currentUser.UserId is not int user||result.Exception!=null)return;
if(!HttpMethods.IsGet(request.Method))
{
// Saving an editor must not turn its return redirect into fresh narrative navigation.
if(result.Result is RedirectToActionResult redirect && IsEditorDestination(redirect.ControllerName??context.RouteData.Values["controller"]?.ToString(),redirect.ActionName))
{redirect.RouteValues??=new RouteValueDictionary();redirect.RouteValues["retainNarrativeFocus"]=true;}
else if(result.Result is LocalRedirectResult local && Uri.TryCreate(new Uri("https://plotdirector.invalid"),local.Url,out var uri) && uri.Host=="plotdirector.invalid")
{var parts=uri.AbsolutePath.Split('/',StringSplitOptions.RemoveEmptyEntries);if(parts.Length>=2&&IsEditorDestination(parts[0],parts[1])&&!QueryHelpers.ParseQuery(uri.Query).ContainsKey("retainNarrativeFocus"))local.Url=QueryHelpers.AddQueryString(local.Url,"retainNarrativeFocus","true");}
return;
}
if(result.Result is not ViewResult||request.Query["retainNarrativeFocus"].Any(v=>string.Equals(v,"true",StringComparison.OrdinalIgnoreCase))||
!HttpMethods.IsGet(request.Method)||request.Headers["X-Requested-With"]=="XMLHttpRequest"||
(request.Headers["Sec-Fetch-Mode"].Count>0&&request.Headers["Sec-Fetch-Mode"]!="navigate")||request.Headers["Sec-Purpose"].ToString().Contains("prefetch",StringComparison.OrdinalIgnoreCase))return;
var controller=context.RouteData.Values["controller"]?.ToString();
var action=context.RouteData.Values["action"]?.ToString();
int? chapter=null,scene=null;
int? ID(string name)=>context.ActionArguments.TryGetValue(name,out var value)&&int.TryParse(value?.ToString(),out var id)&&id>0?id:null;
if(controller=="Scenes"&&action=="Edit")scene=ID("id");
else if((controller=="Chapters"&&action is ("Details" or "Edit"))||(controller=="Writer"&&action=="Chapter"))chapter=ID("id");
else if(controller=="Timeline"&&action=="Index"&&request.Query["navigateFocus"]=="true"&&int.TryParse(request.Query["SelectedSceneID"],out var selected))scene=selected;
if(chapter is null&&scene is null)return;
var scope=controller=="Timeline"&&context.ActionArguments.TryGetValue("filter",out var value)?value as PlotLine.ViewModels.TimelineFilterViewModel:null;
try{var selectedFocus=await focus.Open(user,chapter,scene,scope?.ProjectID,scope?.BookID);if(selectedFocus is null)result.Result=new NotFoundResult();else context.HttpContext.Items["NarrativeFocus.Navigation"]=selectedFocus;}
catch(SqlException e)when(e.Number==51000){result.Result=new NotFoundResult();}
catch(NarrativeFocusConflictException){result.Result=new ConflictObjectResult(new{message="Current focus changed in another window. Reopen this destination to navigate explicitly."});}
}
private static bool IsEditorDestination(string? controller,string? action) =>
(controller?.ToLowerInvariant(),action?.ToLowerInvariant()) is ("scenes","edit") or ("chapters","edit" or "details") or ("writer","chapter");
}

View File

@ -10,7 +10,8 @@ public sealed class SubscriptionEnforcementFilter(
{
private static readonly HashSet<string> ReadOnlySafeControllers = new(StringComparer.OrdinalIgnoreCase)
{
"Account", "ManageAccount", "Pricing", "Exports", "Admin", "StripeWebhook"
"Account", "ManageAccount", "Pricing", "Exports", "Admin", "StripeWebhook",
"NarrativeFocus" // Personal navigation context, never story-content editing.
};
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)

View File

@ -8,7 +8,7 @@ public sealed class WriterSuggestionProvider:IWriterSuggestionProvider
public IReadOnlyList<WriterSuggestion> Suggest(WriterDashboardViewModel model)
{
var result=new List<WriterSuggestion>();
if(model.Objective is {} objective)result.Add(new("focus",$"Your saved activity is {objective.Activity.ToLowerInvariant()}.","Return to your current focus",objective.SceneID.HasValue?"Scenes":"Writer",objective.SceneID.HasValue?"Edit":objective.ChapterID.HasValue?"Chapter":"Write",objective.SceneID??objective.ChapterID));
if(model.Objective is {} objective)result.Add(new("focus",$"Your saved activity is {objective.Activity.ToLowerInvariant()}.","Open your saved objective",objective.SceneID.HasValue?"Scenes":"Writer",objective.SceneID.HasValue?"Edit":objective.ChapterID.HasValue?"Chapter":"Write",objective.SceneID??objective.ChapterID));
if(model.PlannedActivities.FirstOrDefault() is {} reviewed)result.Add(new("reviewed",$"Your reviewed plan includes {reviewed.Title} on {reviewed.ScheduledDate:d MMM}.","Open your next planned activity",reviewed.SceneID.HasValue?"Scenes":"Writer",reviewed.SceneID.HasValue?"Edit":"Chapter",reviewed.SceneID??reviewed.ChapterID));
var planned=model.WritingSchedule.TodayTasks.Concat(model.WritingSchedule.UpcomingTasks).FirstOrDefault();
if(planned!=null)result.Add(new("planned",$"Your plan includes {planned.SceneTitle} on {planned.ScheduledDate:d MMM}.","Open this planned scene","Scenes","Edit",planned.SceneID));
@ -19,7 +19,7 @@ public sealed class WriterSuggestionProvider:IWriterSuggestionProvider
var next=model.WriteNext.FirstOrDefault();
if(next!=null)result.Add(new("draft",$"{next.SceneTitle} is marked Outlined.","Work on the next outlined scene","Scenes","Edit",next.SceneID));
if(model.Activity?.Totals is {Removed:>0} totals)result.Add(new("changes",$"Accepted changes record {totals.Added:N0} additions and {totals.Removed:N0} removals in 30 days.","Review the change evidence","WritingActivity","Index",Interpretation:"Revision may be substantial even when net growth is small."));
var chapter=model.ObjectiveChoices.FirstOrDefault(x=>x.ChapterID==model.Objective?.ChapterID)??model.ObjectiveChoices.FirstOrDefault();
var chapter=model.ObjectiveChoices.FirstOrDefault(x=>x.ChapterID==model.NarrativeFocus?.ChapterID)??model.ObjectiveChoices.FirstOrDefault();
if(chapter!=null)result.Add(new("listen",$"{chapter.ChapterTitle} is available in this book.","Read or start Audio Review","ManuscriptReader","Index",ChapterID:chapter.ChapterID,Interpretation:"Listening is an alternative review activity; media controls require updated Windows Companion."));
var note=model.StoryHealthReminders.FirstOrDefault(x=>x.SceneID.HasValue&&x.Category=="Writer Note");
if(note!=null)result.Add(new("note",note.Detail??"A note is available for this scene.","Review this captured note","Scenes","Edit",note.SceneID));

View File

@ -0,0 +1,150 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
-- Current navigation is independent of WriterWorkingObjectives and manuscript positions.
IF OBJECT_ID('dbo.NarrativeFocus','U') IS NULL
CREATE TABLE dbo.NarrativeFocus(
UserID int NOT NULL REFERENCES dbo.AppUser(UserID) ON DELETE CASCADE,
BookID int NOT NULL REFERENCES dbo.Books(BookID) ON DELETE CASCADE,
ChapterID int NULL, SceneID int NULL, Version bigint NOT NULL DEFAULT 1,
CONSTRAINT PK_NarrativeFocus PRIMARY KEY(UserID,BookID));
IF OBJECT_ID('dbo.NarrativeFocusHistory','U') IS NULL
CREATE TABLE dbo.NarrativeFocusHistory(
UserID int NOT NULL, BookID int NOT NULL, Sequence bigint NOT NULL,
ChapterID int NOT NULL, SceneID int NULL,
CONSTRAINT PK_NarrativeFocusHistory PRIMARY KEY(UserID,BookID,Sequence),
CONSTRAINT FK_NarrativeFocusHistory_Focus FOREIGN KEY(UserID,BookID) REFERENCES dbo.NarrativeFocus(UserID,BookID) ON DELETE CASCADE);
GO
CREATE OR ALTER PROCEDURE dbo.NarrativeFocus_Read
@UserID int,@ProjectID int,@BookID int
AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID
JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1
WHERE b.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0 AND p.IsArchived=0)
THROW 51000,'Narrative focus is unavailable in this book.',1;
BEGIN TRANSACTION;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID)
BEGIN
-- One-time migration only. Never consult an objective after this row exists.
DECLARE @chapter int,@scene int;
SELECT @chapter=c.ChapterID,@scene=s.SceneID FROM dbo.WriterWorkingObjectives o
JOIN dbo.Chapters c ON c.ChapterID=o.ChapterID AND c.BookID=@BookID AND c.IsArchived=0
LEFT JOIN dbo.Scenes s ON s.SceneID=o.SceneID AND s.ChapterID=c.ChapterID AND s.IsArchived=0
WHERE o.UserID=@UserID AND o.BookID=@BookID;
INSERT dbo.NarrativeFocus(UserID,BookID,ChapterID,SceneID) VALUES(@UserID,@BookID,@chapter,@scene);
IF @chapter IS NOT NULL INSERT dbo.NarrativeFocusHistory VALUES(@UserID,@BookID,1,@chapter,@scene);
END;
-- A deleted/moved scene downgrades to its still-valid chapter. Never follow it into another book.
UPDATE f SET ChapterID=c.ChapterID,SceneID=s.SceneID,Version=Version+1
FROM dbo.NarrativeFocus f
LEFT JOIN dbo.Chapters c ON c.ChapterID=f.ChapterID AND c.BookID=@BookID AND c.IsArchived=0
LEFT JOIN dbo.Scenes s ON s.SceneID=f.SceneID AND s.ChapterID=c.ChapterID AND s.IsArchived=0
WHERE f.UserID=@UserID AND f.BookID=@BookID
AND ((f.ChapterID IS NOT NULL AND c.ChapterID IS NULL) OR(f.SceneID IS NOT NULL AND s.SceneID IS NULL));
DELETE h FROM dbo.NarrativeFocusHistory h
WHERE h.UserID=@UserID AND h.BookID=@BookID AND
(NOT EXISTS(SELECT 1 FROM dbo.Chapters c WHERE c.ChapterID=h.ChapterID AND c.BookID=@BookID AND c.IsArchived=0)
OR(h.SceneID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Scenes s WHERE s.SceneID=h.SceneID AND s.ChapterID=h.ChapterID AND s.IsArchived=0)));
COMMIT;
SELECT @ProjectID ProjectID,BookID,ChapterID,SceneID,Version FROM dbo.NarrativeFocus WHERE UserID=@UserID AND BookID=@BookID;
SELECT c.ChapterID,c.ChapterTitle,c.ChapterNumber,n.SceneID,n.SceneTitle,n.SceneNumber,n.BookSceneIndex
FROM dbo.Chapters c LEFT JOIN dbo.NarrativeSceneOrder n ON n.ChapterID=c.ChapterID
WHERE c.BookID=@BookID AND c.IsArchived=0
ORDER BY c.SortOrder,c.ChapterNumber,c.ChapterID,n.BookSceneIndex;
SELECT TOP(20) h.ChapterID,h.SceneID,h.Sequence FROM dbo.NarrativeFocusHistory h
WHERE h.UserID=@UserID AND h.BookID=@BookID ORDER BY h.Sequence DESC;
END;
GO
CREATE OR ALTER PROCEDURE dbo.NarrativeFocus_Set
@UserID int,@ProjectID int,@BookID int,@ChapterID int=NULL,@SceneID int=NULL,@ExpectedVersion bigint,@Direction int=0
AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID
JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1
WHERE b.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0 AND p.IsArchived=0)
THROW 51000,'Narrative focus is unavailable in this book.',1;
IF @Direction NOT IN(-1,0,1) THROW 51000,'Invalid narrative direction.',1;
BEGIN TRANSACTION;
DECLARE @version bigint,@oldChapter int,@oldScene int;
SELECT @version=Version,@oldChapter=ChapterID,@oldScene=SceneID FROM dbo.NarrativeFocus WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID;
IF @version IS NULL OR @version<>@ExpectedVersion THROW 51001,'Current focus changed in another window. Review it and try again.',1;
IF @Direction<>0
BEGIN
DECLARE @index bigint=(SELECT BookSceneIndex FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID AND SceneID=@oldScene);
SET @ChapterID=NULL;SET @SceneID=NULL;
IF @index IS NOT NULL
SELECT @ChapterID=ChapterID,@SceneID=SceneID FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID AND BookSceneIndex=@index+@Direction;
ELSE IF @Direction=1
SELECT TOP(1) @ChapterID=ChapterID,@SceneID=SceneID FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID AND(@oldChapter IS NULL OR ChapterID=@oldChapter) ORDER BY BookSceneIndex;
ELSE
SELECT TOP(1) @ChapterID=ChapterID,@SceneID=SceneID FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID AND(@oldChapter IS NULL OR ChapterID=@oldChapter) ORDER BY BookSceneIndex DESC;
IF @SceneID IS NULL BEGIN COMMIT;RETURN;END;
END;
IF @SceneID IS NOT NULL
BEGIN
DECLARE @actualChapter int=(SELECT ChapterID FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID AND SceneID=@SceneID);
IF @actualChapter IS NULL OR(@ChapterID IS NOT NULL AND @actualChapter<>@ChapterID) THROW 51000,'Scene is unavailable in this book and chapter.',1;
SET @ChapterID=@actualChapter;
END;
IF @ChapterID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChapterID AND BookID=@BookID AND IsArchived=0)
THROW 51000,'Chapter is unavailable in this book.',1;
IF ISNULL(@ChapterID,0)<>ISNULL(@oldChapter,0) OR ISNULL(@SceneID,0)<>ISNULL(@oldScene,0)
BEGIN
UPDATE dbo.NarrativeFocus SET ChapterID=@ChapterID,SceneID=@SceneID,Version=Version+1 WHERE UserID=@UserID AND BookID=@BookID;
DELETE dbo.NarrativeFocusHistory WHERE UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID AND ISNULL(SceneID,0)=ISNULL(@SceneID,0);
IF @ChapterID IS NOT NULL INSERT dbo.NarrativeFocusHistory VALUES(@UserID,@BookID,@version+1,@ChapterID,@SceneID);
DELETE h FROM dbo.NarrativeFocusHistory h WHERE UserID=@UserID AND BookID=@BookID AND Sequence NOT IN
(SELECT TOP(20) Sequence FROM dbo.NarrativeFocusHistory WHERE UserID=@UserID AND BookID=@BookID ORDER BY Sequence DESC);
END;
COMMIT;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterObjective
@UserID int, @BookID int, @Action varchar(10)='read', @ChapterID int=NULL, @SceneID int=NULL, @Activity nvarchar(20)=NULL, @Intention nvarchar(2000)=NULL
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID
WHERE b.BookID=@BookID AND b.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1)
THROW 51000,'Book access denied',1;
IF @Action='read'
BEGIN
SELECT o.BookID,o.Activity,o.Intention,o.ChapterID,o.SceneID,CASE WHEN o.ChapterID IS NOT NULL AND c.ChapterID IS NULL THEN N'Unavailable saved chapter' ELSE c.ChapterTitle END ChapterTitle,CASE WHEN o.SceneID IS NOT NULL AND s.SceneID IS NULL THEN N'Unavailable saved scene' ELSE s.SceneTitle END SceneTitle
FROM dbo.WriterWorkingObjectives o
LEFT JOIN dbo.Chapters c ON c.ChapterID=o.ChapterID AND c.BookID=@BookID AND c.IsArchived=0
LEFT JOIN dbo.Scenes s ON s.SceneID=o.SceneID AND s.ChapterID=c.ChapterID AND s.IsArchived=0
WHERE o.BookID=@BookID AND o.UserID=@UserID;
SELECT c.ChapterID,c.ChapterTitle,s.SceneID,s.SceneTitle FROM dbo.Chapters c
LEFT JOIN dbo.Scenes s ON s.ChapterID=c.ChapterID AND s.IsArchived=0
WHERE c.BookID=@BookID AND c.IsArchived=0 ORDER BY c.SortOrder,c.ChapterID,s.SortOrder,s.SceneID;
RETURN;
END;
IF @Action<>'save' THROW 51000,'Unknown objective action',1;
IF @Activity IS NULL OR @Activity NOT IN(N'Drafting',N'Revising',N'Editing',N'Researching',N'Proofreading') THROW 51000,'Choose a working activity',1;
IF @ChapterID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChapterID AND BookID=@BookID AND IsArchived=0) THROW 51000,'Chapter is unavailable in this book',1;
IF @SceneID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Scenes WHERE SceneID=@SceneID AND ChapterID=@ChapterID AND IsArchived=0) THROW 51000,'Scene is unavailable in this chapter',1;
SET XACT_ABORT ON;
BEGIN TRANSACTION;
IF EXISTS(SELECT 1 FROM dbo.WriterWorkingObjectives WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID AND UserID=@UserID)
UPDATE dbo.WriterWorkingObjectives SET ChapterID=@ChapterID,SceneID=@SceneID,Activity=@Activity,Intention=@Intention,UpdatedUtc=SYSUTCDATETIME() WHERE BookID=@BookID AND UserID=@UserID;
ELSE INSERT dbo.WriterWorkingObjectives(BookID,UserID,ChapterID,SceneID,Activity,Intention) VALUES(@BookID,@UserID,@ChapterID,@SceneID,@Activity,@Intention);
COMMIT;
END;
GO
CREATE OR ALTER PROCEDURE dbo.NarrativeFocus_Locate
@UserID int,@ChapterID int=NULL,@SceneID int=NULL
AS
BEGIN
SET NOCOUNT ON;
SELECT b.ProjectID,b.BookID,c.ChapterID,s.SceneID FROM dbo.Chapters c
JOIN dbo.Books b ON b.BookID=c.BookID AND b.IsArchived=0
JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0
JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1
LEFT JOIN dbo.Scenes s ON s.ChapterID=c.ChapterID AND s.IsArchived=0 AND s.SceneID=@SceneID
WHERE c.IsArchived=0 AND(@SceneID IS NULL AND c.ChapterID=@ChapterID OR @SceneID IS NOT NULL AND s.SceneID=@SceneID AND(@ChapterID IS NULL OR c.ChapterID=@ChapterID));
END;
GO

View File

@ -0,0 +1,46 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
-- Preserve the authoritative view sequence even when chapter numbers/sort orders tie.
CREATE OR ALTER PROCEDURE dbo.NarrativeFocus_Read
@UserID int,@ProjectID int,@BookID int
AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID
JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1
WHERE b.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0 AND p.IsArchived=0)
THROW 51000,'Narrative focus is unavailable in this book.',1;
BEGIN TRANSACTION;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID)
BEGIN
-- One-time migration only. Never consult an objective after this row exists.
DECLARE @chapter int,@scene int;
SELECT @chapter=c.ChapterID,@scene=s.SceneID FROM dbo.WriterWorkingObjectives o
JOIN dbo.Chapters c ON c.ChapterID=o.ChapterID AND c.BookID=@BookID AND c.IsArchived=0
LEFT JOIN dbo.Scenes s ON s.SceneID=o.SceneID AND s.ChapterID=c.ChapterID AND s.IsArchived=0
WHERE o.UserID=@UserID AND o.BookID=@BookID;
INSERT dbo.NarrativeFocus(UserID,BookID,ChapterID,SceneID) VALUES(@UserID,@BookID,@chapter,@scene);
IF @chapter IS NOT NULL INSERT dbo.NarrativeFocusHistory VALUES(@UserID,@BookID,1,@chapter,@scene);
END;
-- A deleted/moved scene downgrades to its still-valid chapter. Never follow it into another book.
UPDATE f SET ChapterID=c.ChapterID,SceneID=s.SceneID,Version=Version+1
FROM dbo.NarrativeFocus f
LEFT JOIN dbo.Chapters c ON c.ChapterID=f.ChapterID AND c.BookID=@BookID AND c.IsArchived=0
LEFT JOIN dbo.Scenes s ON s.SceneID=f.SceneID AND s.ChapterID=c.ChapterID AND s.IsArchived=0
WHERE f.UserID=@UserID AND f.BookID=@BookID
AND ((f.ChapterID IS NOT NULL AND c.ChapterID IS NULL) OR(f.SceneID IS NOT NULL AND s.SceneID IS NULL));
DELETE h FROM dbo.NarrativeFocusHistory h
WHERE h.UserID=@UserID AND h.BookID=@BookID AND
(NOT EXISTS(SELECT 1 FROM dbo.Chapters c WHERE c.ChapterID=h.ChapterID AND c.BookID=@BookID AND c.IsArchived=0)
OR(h.SceneID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Scenes s WHERE s.SceneID=h.SceneID AND s.ChapterID=h.ChapterID AND s.IsArchived=0)));
COMMIT;
SELECT @ProjectID ProjectID,BookID,ChapterID,SceneID,Version FROM dbo.NarrativeFocus WHERE UserID=@UserID AND BookID=@BookID;
SELECT c.ChapterID,c.ChapterTitle,c.ChapterNumber,n.SceneID,n.SceneTitle,n.SceneNumber,n.BookSceneIndex
FROM dbo.Chapters c LEFT JOIN dbo.NarrativeSceneOrder n ON n.ChapterID=c.ChapterID
WHERE c.BookID=@BookID AND c.IsArchived=0
ORDER BY CASE WHEN n.SceneID IS NULL THEN 1 ELSE 0 END,n.BookSceneIndex,c.SortOrder,c.ChapterNumber,c.ChapterID;
SELECT TOP(20) h.ChapterID,h.SceneID,h.Sequence FROM dbo.NarrativeFocusHistory h
WHERE h.UserID=@UserID AND h.BookID=@BookID ORDER BY h.Sequence DESC;
END;
GO

View File

@ -0,0 +1,102 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
-- Chapter-only positions include empty chapters; scene stepping always uses real manuscript scenes.
CREATE OR ALTER PROCEDURE dbo.NarrativeFocus_Read
@UserID int,@ProjectID int,@BookID int
AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID
JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1
WHERE b.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0 AND p.IsArchived=0)
THROW 51000,'Narrative focus is unavailable in this book.',1;
BEGIN TRANSACTION;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID)
BEGIN
-- One-time migration only. Never consult an objective after this row exists.
DECLARE @chapter int,@scene int;
SELECT @chapter=c.ChapterID,@scene=s.SceneID FROM dbo.WriterWorkingObjectives o
JOIN dbo.Chapters c ON c.ChapterID=o.ChapterID AND c.BookID=@BookID AND c.IsArchived=0
LEFT JOIN dbo.Scenes s ON s.SceneID=o.SceneID AND s.ChapterID=c.ChapterID AND s.IsArchived=0
WHERE o.UserID=@UserID AND o.BookID=@BookID;
INSERT dbo.NarrativeFocus(UserID,BookID,ChapterID,SceneID) VALUES(@UserID,@BookID,@chapter,@scene);
IF @chapter IS NOT NULL INSERT dbo.NarrativeFocusHistory VALUES(@UserID,@BookID,1,@chapter,@scene);
END;
-- A deleted/moved scene downgrades to its still-valid chapter. Never follow it into another book.
UPDATE f SET ChapterID=c.ChapterID,SceneID=s.SceneID,Version=Version+1
FROM dbo.NarrativeFocus f
LEFT JOIN dbo.Chapters c ON c.ChapterID=f.ChapterID AND c.BookID=@BookID AND c.IsArchived=0
LEFT JOIN dbo.Scenes s ON s.SceneID=f.SceneID AND s.ChapterID=c.ChapterID AND s.IsArchived=0
WHERE f.UserID=@UserID AND f.BookID=@BookID
AND ((f.ChapterID IS NOT NULL AND c.ChapterID IS NULL) OR(f.SceneID IS NOT NULL AND s.SceneID IS NULL));
DELETE h FROM dbo.NarrativeFocusHistory h
WHERE h.UserID=@UserID AND h.BookID=@BookID AND
(NOT EXISTS(SELECT 1 FROM dbo.Chapters c WHERE c.ChapterID=h.ChapterID AND c.BookID=@BookID AND c.IsArchived=0)
OR(h.SceneID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Scenes s WHERE s.SceneID=h.SceneID AND s.ChapterID=h.ChapterID AND s.IsArchived=0)));
COMMIT;
SELECT @ProjectID ProjectID,BookID,ChapterID,SceneID,Version FROM dbo.NarrativeFocus WHERE UserID=@UserID AND BookID=@BookID;
SELECT c.ChapterID,c.ChapterTitle,c.ChapterNumber,n.SceneID,n.SceneTitle,n.SceneNumber,n.BookSceneIndex
FROM dbo.Chapters c LEFT JOIN dbo.NarrativeSceneOrder n ON n.ChapterID=c.ChapterID
WHERE c.BookID=@BookID AND c.IsArchived=0
ORDER BY c.SortOrder,c.ChapterNumber,CASE WHEN n.SceneID IS NULL THEN 1 ELSE 0 END,n.BookSceneIndex,c.ChapterID;
SELECT TOP(20) h.ChapterID,h.SceneID,h.Sequence FROM dbo.NarrativeFocusHistory h
WHERE h.UserID=@UserID AND h.BookID=@BookID ORDER BY h.Sequence DESC;
END;
GO
CREATE OR ALTER PROCEDURE dbo.NarrativeFocus_Set
@UserID int,@ProjectID int,@BookID int,@ChapterID int=NULL,@SceneID int=NULL,@ExpectedVersion bigint,@Direction int=0
AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID
JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1
WHERE b.BookID=@BookID AND b.ProjectID=@ProjectID AND b.IsArchived=0 AND p.IsArchived=0)
THROW 51000,'Narrative focus is unavailable in this book.',1;
IF @Direction NOT IN(-1,0,1) THROW 51000,'Invalid narrative direction.',1;
BEGIN TRANSACTION;
DECLARE @version bigint,@oldChapter int,@oldScene int;
SELECT @version=Version,@oldChapter=ChapterID,@oldScene=SceneID FROM dbo.NarrativeFocus WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID;
IF @version IS NULL OR @version<>@ExpectedVersion THROW 51001,'Current focus changed in another window. Review it and try again.',1;
IF @Direction<>0
BEGIN
DECLARE @index bigint=(SELECT BookSceneIndex FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID AND SceneID=@oldScene AND ChapterID=@oldChapter);
SET @ChapterID=NULL;SET @SceneID=NULL;
IF @index IS NOT NULL
SELECT @ChapterID=ChapterID,@SceneID=SceneID FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID AND BookSceneIndex=@index+@Direction;
ELSE IF @Direction=1
SELECT TOP(1) @ChapterID=n.ChapterID,@SceneID=n.SceneID FROM dbo.NarrativeSceneOrder n
LEFT JOIN dbo.Chapters currentChapter ON currentChapter.ChapterID=@oldChapter AND currentChapter.BookID=@BookID AND currentChapter.IsArchived=0
WHERE n.BookID=@BookID AND(currentChapter.ChapterID IS NULL OR n.ChapterID=currentChapter.ChapterID OR
(NOT EXISTS(SELECT 1 FROM dbo.NarrativeSceneOrder present WHERE present.BookID=@BookID AND present.ChapterID=currentChapter.ChapterID)
AND(n.ChapterSortOrder>currentChapter.SortOrder OR(n.ChapterSortOrder=currentChapter.SortOrder AND n.ChapterNumber>currentChapter.ChapterNumber))))
ORDER BY n.BookSceneIndex;
ELSE
SELECT TOP(1) @ChapterID=n.ChapterID,@SceneID=n.SceneID FROM dbo.NarrativeSceneOrder n
LEFT JOIN dbo.Chapters currentChapter ON currentChapter.ChapterID=@oldChapter AND currentChapter.BookID=@BookID AND currentChapter.IsArchived=0
WHERE n.BookID=@BookID AND(currentChapter.ChapterID IS NULL OR n.ChapterID=currentChapter.ChapterID OR
(NOT EXISTS(SELECT 1 FROM dbo.NarrativeSceneOrder present WHERE present.BookID=@BookID AND present.ChapterID=currentChapter.ChapterID)
AND(n.ChapterSortOrder<currentChapter.SortOrder OR(n.ChapterSortOrder=currentChapter.SortOrder AND n.ChapterNumber<=currentChapter.ChapterNumber))))
ORDER BY n.BookSceneIndex DESC;
IF @SceneID IS NULL BEGIN COMMIT;RETURN;END;
END;
IF @SceneID IS NOT NULL
BEGIN
DECLARE @actualChapter int=(SELECT ChapterID FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID AND SceneID=@SceneID);
IF @actualChapter IS NULL OR(@ChapterID IS NOT NULL AND @actualChapter<>@ChapterID) THROW 51000,'Scene is unavailable in this book and chapter.',1;
SET @ChapterID=@actualChapter;
END;
IF @ChapterID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChapterID AND BookID=@BookID AND IsArchived=0)
THROW 51000,'Chapter is unavailable in this book.',1;
IF ISNULL(@ChapterID,0)<>ISNULL(@oldChapter,0) OR ISNULL(@SceneID,0)<>ISNULL(@oldScene,0)
BEGIN
UPDATE dbo.NarrativeFocus SET ChapterID=@ChapterID,SceneID=@SceneID,Version=Version+1 WHERE UserID=@UserID AND BookID=@BookID;
DELETE dbo.NarrativeFocusHistory WHERE UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID AND ISNULL(SceneID,0)=ISNULL(@SceneID,0);
IF @ChapterID IS NOT NULL INSERT dbo.NarrativeFocusHistory VALUES(@UserID,@BookID,@version+1,@ChapterID,@SceneID);
DELETE h FROM dbo.NarrativeFocusHistory h WHERE UserID=@UserID AND BookID=@BookID AND Sequence NOT IN
(SELECT TOP(20) Sequence FROM dbo.NarrativeFocusHistory WHERE UserID=@UserID AND BookID=@BookID ORDER BY Sequence DESC);
END;
COMMIT;
END;
GO

View File

@ -4,6 +4,7 @@ namespace PlotLine.ViewModels;
public sealed class ApplicationNavigationViewModel
{
public PlotLine.Services.NarrativeFocusState? NarrativeFocus { get; set; }
public int? WordChapterID { get; set; }
public int? WordSceneID { get; set; }
public bool IsAdmin { get; set; }

View File

@ -927,6 +927,7 @@ public sealed class ChapterWorkflowViewModel
public sealed class WriterDashboardViewModel
{
public PlotLine.Services.NarrativeFocusState? NarrativeFocus { get; set; }
public PlotLine.Services.Manuscript.ManuscriptReaderModel? ReviewReader {get;set;}
public string WordNavigationContext {get;set;}="working";
public string Destination { get; set; } = "Legacy";

View File

@ -148,7 +148,7 @@
asp-route-BookID="@point.BookID"
asp-route-SelectedSceneID="@point.SceneID"
asp-route-FocusType="scene"
asp-route-FocusID="@point.SceneID">
asp-route-FocusID="@point.SceneID" asp-route-navigateFocus="true">
<span>@point.Value</span>
</a>
}
@ -192,7 +192,7 @@
<h3>Needs attention</h3>
@foreach (var scene in Model.RevisionAttentionScenes.Take(8))
{
<a class="analytics-link-row" asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-BookID="@scene.BookID" asp-route-SelectedSceneID="@scene.SceneID" asp-route-FocusType="scene" asp-route-FocusID="@scene.SceneID">
<a class="analytics-link-row" asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-BookID="@scene.BookID" asp-route-SelectedSceneID="@scene.SceneID" asp-route-FocusType="scene" asp-route-FocusID="@scene.SceneID" asp-route-navigateFocus="true">
<span>@scene.RevisionStatusName</span>
<strong>Ch @scene.ChapterNumber / Scene @scene.SceneNumber: @scene.SceneTitle</strong>
</a>
@ -212,7 +212,7 @@
<h3>Missing purpose/outcome</h3>
@foreach (var gap in Model.SceneGaps.Take(8))
{
<a class="analytics-link-row" asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-BookID="@gap.BookID" asp-route-SelectedSceneID="@gap.SceneID" asp-route-FocusType="scene" asp-route-FocusID="@gap.SceneID">
<a class="analytics-link-row" asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-BookID="@gap.BookID" asp-route-SelectedSceneID="@gap.SceneID" asp-route-FocusType="scene" asp-route-FocusID="@gap.SceneID" asp-route-navigateFocus="true">
<span>@(gap.MissingPurpose ? "No purpose" : "") @(gap.MissingOutcome ? "No outcome" : "")</span>
<strong>Ch @gap.ChapterNumber / Scene @gap.SceneNumber: @gap.SceneTitle</strong>
</a>

View File

@ -169,7 +169,7 @@
</div>
</td>
<td class="text-end">
<a class="btn btn-outline-secondary btn-sm" asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-bookId="@Model.Book.BookID" asp-route-selectedSceneId="@scene.SceneID">Open in timeline</a>
<a class="btn btn-outline-secondary btn-sm" asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-bookId="@Model.Book.BookID" asp-route-selectedSceneId="@scene.SceneID" asp-route-navigateFocus="true">Open in timeline</a>
<a class="btn btn-outline-secondary btn-sm" asp-controller="Scenes" asp-action="Edit" asp-route-id="@scene.SceneID">Edit</a>
<form asp-controller="Scenes" asp-action="Archive" method="post" class="archive-button-form" data-confirm-message="Archive this scene?&#10;&#10;This will hide it from active lists and timelines, but the data will be kept and can be restored later.">
<input type="hidden" name="id" value="@scene.SceneID" />

View File

@ -459,7 +459,7 @@
{
<span>@item.Description</span>
}
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@item.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID">Open scene</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@item.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID" asp-route-navigateFocus="true">Open scene</a>
</div>
}
<div class="asset-mini-item">
@ -494,7 +494,7 @@
{
<span>@item.Description</span>
}
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@item.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID">Open in timeline</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@item.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID" asp-route-navigateFocus="true">Open in timeline</a>
<a asp-action="Details" asp-route-id="@(item.CharacterAID == Model.Character.CharacterID ? item.CharacterBID : item.CharacterAID)">Open related character</a>
</div>
}
@ -517,7 +517,7 @@
<strong>@appearance.BookDisplayTitle / Ch @appearance.ChapterNumber / Scene @appearance.SceneNumber: @appearance.SceneTitle</strong>
<span>@appearance.RoleInSceneTypeName / @appearance.PresenceTypeName</span>
<span>@appearance.OutfitDescription @appearance.PhysicalCondition @appearance.EmotionalState</span>
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@appearance.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID">Open in timeline</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@appearance.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID" asp-route-navigateFocus="true">Open in timeline</a>
</div>
}
</div>
@ -539,7 +539,7 @@
<strong>@item.AttributeName: @item.AttributeValue</strong>
<span>@item.BookDisplayTitle / Ch @item.ChapterNumber / Scene @item.SceneNumber: @item.SceneTitle</span>
<span>@item.Description</span>
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@item.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID">Open in timeline</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@item.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID" asp-route-navigateFocus="true">Open in timeline</a>
</div>
}
</div>
@ -561,7 +561,7 @@
<strong>@item.KnowledgeStateName: @(item.AssetName ?? item.ThreadTitle)</strong>
<span>@item.BookDisplayTitle / Ch @item.ChapterNumber / Scene @item.SceneNumber: @item.SceneTitle</span>
<span>@item.Description</span>
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@item.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID">Open in timeline</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@item.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID" asp-route-navigateFocus="true">Open in timeline</a>
</div>
}
</div>

View File

@ -195,7 +195,7 @@
<td>
@if (row.LastConfirmedSceneID.HasValue)
{
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@row.LastConfirmedSceneID">@row.LastConfirmed</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@row.LastConfirmedSceneID" asp-route-navigateFocus="true">@row.LastConfirmed</a>
}
else
{
@ -225,7 +225,7 @@
<td>
@if (row.LastConfirmedSceneID.HasValue)
{
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@row.LastConfirmedSceneID">@row.LastConfirmed</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@row.LastConfirmedSceneID" asp-route-navigateFocus="true">@row.LastConfirmed</a>
}
else
{
@ -306,7 +306,7 @@ else if (Model.Filter.DisplayMode == "Journey")
{
<td>@row.ChapterDisplayName</td>
}
<td><a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@row.SceneID">@row.SceneDisplayName</a></td>
<td><a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@row.SceneID" asp-route-navigateFocus="true">@row.SceneDisplayName</a></td>
<td>@row.Location</td>
</tr>
}
@ -346,7 +346,7 @@ else if (Model.Filter.DisplayMode == "Journey")
{
<td>@row.ChapterDisplayName</td>
}
<td><a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@row.SceneID">@row.SceneDisplayName</a></td>
<td><a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@row.SceneID" asp-route-navigateFocus="true">@row.SceneDisplayName</a></td>
<td>@row.HolderOrLocation</td>
</tr>
}
@ -398,7 +398,7 @@ else
{
<td>@row.ChapterDisplayName</td>
}
<td><a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@row.SceneID">@row.SceneDisplayName</a></td>
<td><a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@row.SceneID" asp-route-navigateFocus="true">@row.SceneDisplayName</a></td>
<td>
@if (!row.Characters.Any())
{
@ -418,7 +418,7 @@ else
Last confirmed:
@if (character.LastConfirmedSceneID.HasValue)
{
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@character.LastConfirmedSceneID">@character.LastConfirmedSceneDisplayName</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@character.LastConfirmedSceneID" asp-route-navigateFocus="true">@character.LastConfirmedSceneDisplayName</a>
}
else
{
@ -454,7 +454,7 @@ else
Last confirmed:
@if (asset.LastConfirmedSceneID.HasValue)
{
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@asset.LastConfirmedSceneID">@asset.LastConfirmedSceneDisplayName</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@asset.LastConfirmedSceneID" asp-route-navigateFocus="true">@asset.LastConfirmedSceneDisplayName</a>
}
else
{

View File

@ -1065,6 +1065,7 @@
const referenceFloorSelect = workspace.querySelector("[data-reference-floor-select]");
const modeButtons = [...workspace.querySelectorAll("[data-floor-plan-mode]")];
const occupancyControls = [...workspace.querySelectorAll("[data-occupancy-controls]")];
let occupancyExplorer;
const occupancySceneSelect = workspace.querySelector("[data-occupancy-scene-select]");
const occupancyPrev = workspace.querySelector("[data-occupancy-prev]");
const occupancyNext = workspace.querySelector("[data-occupancy-next]");
@ -1161,6 +1162,7 @@
}
function refreshOccupancyTrays() {
occupancyExplorer?.sync();
const sceneId = selectedOccupancySceneId();
const showOccupancy = editor.classList.contains("floor-plan-editor--occupancy");
const activeFloorId = tabs.find(tab => tab.classList.contains("active"))?.dataset.floorTab || "";
@ -1206,16 +1208,8 @@
refreshOccupancyTrays();
}
function moveOccupancyScene(direction) {
if (!occupancySceneSelect || occupancySceneSelect.options.length === 0) {
return;
}
const nextIndex = Math.max(0, Math.min(occupancySceneSelect.options.length - 1, occupancySceneSelect.selectedIndex + direction));
occupancySceneSelect.selectedIndex = nextIndex;
applyOccupancySceneFloor();
refreshOccupancyTrays();
}
function moveOccupancyScene(direction) { occupancyExplorer?.step(direction); }
function applyStoryPosition(position) {
if (!occupancySceneSelect || !position?.sceneId) {
@ -2550,14 +2544,13 @@
tabs.forEach(tab => tab.addEventListener("click", () => setActiveFloor(tab.dataset.floorTab)));
toolboxTabs.forEach(tab => tab.addEventListener("click", () => setToolboxTab(tab.dataset.toolboxTab)));
modeButtons.forEach(button => button.addEventListener("click", () => setFloorPlanMode(button.dataset.floorPlanMode)));
occupancySceneSelect?.addEventListener("change", () => {
window.PlotDirectorStoryPosition?.publishChanged({
projectId: @Model.Project.ProjectID,
sceneId: selectedOccupancySceneId()
}, "FloorPlan");
applyOccupancySceneFloor();
refreshOccupancyTrays();
});
if(occupancySceneSelect){
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,
change:p=>{occupancySceneSelect.value=String(p.id);try{sessionStorage.setItem(sceneStorageKey,String(p.id));}catch{}applyOccupancySceneFloor();refreshOccupancyTrays();}});
}
occupancyPrev?.addEventListener("click", () => moveOccupancyScene(-1));
occupancyNext?.addEventListener("click", () => moveOccupancyScene(1));
editor.querySelectorAll("[data-transition-type-select],[data-transition-from-select]").forEach(input => {
@ -2594,10 +2587,11 @@
addBlockForm?.addEventListener("submit", addBlockAsync);
editor.addEventListener("floor-plan-restore-state", event => restoreWorkspaceState(event.detail || {}));
const storyPositionEvent = window.PlotDirectorStoryPosition?.eventName || "plotdirector:story-position-changed";
const onStoryPosition = event => applyStoryPosition(event.detail);
const onStoryPosition = event => { if(event.detail?.source==='FloorPlanOpen')applyStoryPosition(event.detail); };
document.addEventListener(storyPositionEvent, onStoryPosition);
workspace.addEventListener("floor-plan-dispose", () => {
window.PlotLineHelpIcons?.dispose(workspace);
occupancyExplorer?.destroy();
document.removeEventListener(storyPositionEvent, onStoryPosition);
window.clearTimeout(saveTimer);
backgroundTimers.forEach(timer => window.clearTimeout(timer));

View File

@ -189,7 +189,7 @@
<h3>Scenes</h3>
@foreach (var scene in Model.Scenes)
{
<p><strong>@SceneLabel(scene.ChapterNumber, scene.SceneNumber)</strong> <a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@scene.SceneID" asp-route-FocusType="location" asp-route-FocusID="@Model.Location.LocationID">@scene.SceneTitle</a></p>
<p><strong>@SceneLabel(scene.ChapterNumber, scene.SceneNumber)</strong> <a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@scene.SceneID" asp-route-FocusType="location" asp-route-FocusID="@Model.Location.LocationID" asp-route-navigateFocus="true">@scene.SceneTitle</a></p>
}
@if (!Model.Scenes.Any()) { <p class="muted">No scenes set here.</p> }
</div>

View File

@ -63,8 +63,8 @@
<p id="rwStatus" role="status" aria-live="polite" class="muted"></p>
</div>
<div class="rw-timeline">
<div class="rw-timeline-heading"><label for="rwTimeline">Relationship Timeline</label><output id="rwPoint">@Model.StoryPointLabel</output>
<div><button type="button" class="btn btn-outline-secondary btn-sm" id="rwPrevious" aria-label="Previous change" title="Previous change">‹</button><button type="button" class="btn btn-outline-secondary btn-sm" id="rwNext" aria-label="Next change" title="Next change">›</button></div>
<div class="rw-timeline-heading"><label for="rwTimeline">Scene Explorer</label><output id="rwPoint">@Model.StoryPointLabel</output>
<div><button type="button" class="btn btn-outline-secondary btn-sm" id="rwPrevious" aria-label="Previous change" title="Previous relationship change">Previous change</button><button type="button" class="btn btn-outline-secondary btn-sm" id="rwNext" aria-label="Next change" title="Next relationship change">Next change</button></div>
</div>
<div class="rw-timeline-track"><button type="button" class="btn btn-outline-secondary btn-sm" id="rwInitial">Initial</button><div class="rw-scrubber">
<div id="rwTimelineMarkers" class="rw-timeline-markers" aria-label="Relationship changes"></div>

View File

@ -71,6 +71,7 @@
}
</ul>
}
@if(Model.Project!=null&&Model.Books.Count>0){<partial name="_NarrativeFocus" model="Model" />}
<div class="pd-titlebar-end">
@if (Model.ShowCompanionPresence)
{
@ -217,4 +218,4 @@
</div>
</div>
@if(book!=null && selectedCategory is "writer" or "book" or "story"){<template data-word-fallback><partial name="~/Views/Writer/_WriterWord.cshtml" model="new WriterDashboardViewModel{BookID=book.BookID,ProjectID=book.ProjectID,Objective=new(){ChapterID=Model.WordChapterID,SceneID=Model.WordSceneID}}" /></template>}
@if(book!=null && selectedCategory is "writer" or "book" or "story"){<template data-word-fallback><partial name="~/Views/Writer/_WriterWord.cshtml" model="new WriterDashboardViewModel{BookID=book.BookID,ProjectID=book.ProjectID,NarrativeFocus=Model.NarrativeFocus}" /></template>}

View File

@ -146,6 +146,7 @@
<script src="~/js/application-context-menu.js" asp-append-version="true" defer></script>
}
<link rel="stylesheet" href="~/css/scene-explorer.css" asp-append-version="true" />
</head>
<body data-pd-project-id="@appNavigation.Project?.ProjectID" data-pd-scene-id="@(ViewContext.RouteData.Values["controller"]?.ToString() == "Scenes" ? ViewContext.RouteData.Values["id"] : null)" data-pd-user-id="@userId" data-desktop-eligible="@(isApplication && appNavigation.Project is not null && appNavigation.Books.Count > 0 ? "true" : "false")" data-desktop-user="@(isApplication ? userId : null)" class="@(User.Identity?.IsAuthenticated == true && !isMarketingPage ? "app-layout" : null)">
<header class="@(isApplication ? "pd-application-header" : null)">
@ -186,6 +187,8 @@
@if (isApplication)
{
<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/application-page-context.js" asp-append-version="true"></script>
}
@if (User.Identity?.IsAuthenticated == true)

View File

@ -0,0 +1,16 @@
@model ApplicationNavigationViewModel
@{var focus=Model.NarrativeFocus??new PlotLine.Services.NarrativeFocusState{ProjectID=Model.Project!.ProjectID};}
<details class="pd-narrative-focus" data-narrative-focus data-project="@focus.ProjectID" data-book="@focus.BookID">
<summary title="Current narrative focus" data-focus-label>Current Focus: @focus.Label</summary>
<div class="pd-focus-picker">
@if(Model.Book==null){<label>Focus book<select data-focus-book><option value="">Choose a book…</option>@foreach(var book in Model.Books){<option value="@book.BookID">@book.BookDisplayTitle</option>}</select></label>}
<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"><button type="button" data-focus-step="-1" 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 Scene</button><button type="button" data-focus-step="1" title="Next scene in manuscript order">Next Scene <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()
</div>
<script type="application/json" data-narrative-initial>@Html.Raw(System.Text.Json.JsonSerializer.Serialize(focus,new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web)))</script>
</details>

View File

@ -135,7 +135,7 @@
<strong>@assetEvent.EventTitle</strong>
<span>@assetEvent.BookDisplayTitle / Ch @assetEvent.ChapterNumber / Scene @assetEvent.SceneNumber: @assetEvent.SceneTitle</span>
<span>@assetEvent.FromStateName -> @assetEvent.ToStateName</span>
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@assetEvent.SceneID" asp-route-FocusType="asset" asp-route-FocusID="@Model.Asset.StoryAssetID">Open in timeline</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@assetEvent.SceneID" asp-route-FocusType="asset" asp-route-FocusID="@Model.Asset.StoryAssetID" asp-route-navigateFocus="true">Open in timeline</a>
</div>
</div>
}
@ -158,7 +158,7 @@
<strong>@custody.CustodyEventTypeName</strong>
<span>@custody.CustodianSummary</span>
<span>@custody.BookDisplayTitle / Ch @custody.ChapterNumber / Scene @custody.SceneNumber: @custody.SceneTitle</span>
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@custody.SceneID" asp-route-FocusType="asset" asp-route-FocusID="@Model.Asset.StoryAssetID">Open in timeline</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@custody.SceneID" asp-route-FocusType="asset" asp-route-FocusID="@Model.Asset.StoryAssetID" asp-route-navigateFocus="true">Open in timeline</a>
</div>
}
</div>

View File

@ -340,7 +340,7 @@
}
@if (item.SceneID.HasValue)
{
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@item.SceneID">Open scene</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@item.SceneID" asp-route-navigateFocus="true">Open scene</a>
}
</article>
}

View File

@ -47,7 +47,7 @@ else
asp-action="Index"
asp-route-projectId="@Model.ProjectID"
asp-route-bookId="@scene.BookID"
asp-route-selectedSceneId="@scene.SceneID">Open in Timeline</a>
asp-route-selectedSceneId="@scene.SceneID" asp-route-navigateFocus="true">Open in Timeline</a>
</div>
</article>
}

View File

@ -11,7 +11,7 @@
</nav>
<partial name="_ProjectSectionNav" model="Model.Project" />
<div data-pwa-header class="page-heading"><div><p class="eyebrow">Writing context</p><h1>AT THIS POINT IN THE STORY <help-icon key="storyPoint.overview" /></h1>
<p class="lead-text">Known state through the selected scene, including events in this scene.</p></div></div>
<p class="lead-text">Snapshot through the selected scene, including its events. Exploring a snapshot does not change Current Focus.</p></div></div>
<form asp-action="Index" method="get" class="story-point-selectors" data-story-point-form>
<input type="hidden" name="projectId" value="@Model.Project.ProjectID" />
<div><label for="point-book" class="form-label">Book</label><select id="point-book" class="form-select" data-point-book>

View File

@ -24,7 +24,7 @@ else
<p>POV: <strong>@(Model.PovName ?? "Not recorded")</strong> · Location: <strong>@(Model.Location?.LocationPath ?? scene.PrimaryLocationName ?? "Not recorded")</strong></p>
<div class="d-flex flex-wrap gap-2">
<a class="btn btn-sm btn-outline-primary" asp-controller="Scenes" asp-action="Edit" asp-route-id="@scene.SceneID">Open Scene</a>
<a class="btn btn-sm btn-outline-secondary" asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.Book.BookID" asp-route-selectedSceneId="@scene.SceneID">Timeline</a>
<a class="btn btn-sm btn-outline-secondary" asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.Book.BookID" asp-route-selectedSceneId="@scene.SceneID" asp-route-navigateFocus="true">Timeline</a>
@if (scene.StartDateTime.HasValue) { <a class="btn btn-sm btn-outline-secondary" asp-controller="StoryCalendar" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.Book.BookID" asp-route-date="@scene.StartDateTime.Value.ToString("yyyy-MM-dd")" asp-route-month="@scene.StartDateTime.Value.ToString("yyyy-MM")">Calendar</a> }
</div>
</header>

View File

@ -38,7 +38,7 @@
sceneNumber = column.Scene?.SceneNumber.ToString("g"),
sceneTitle = column.Scene?.SceneTitle ?? column.PlaceholderLabel,
bookTitle = column.Book.Book.BookDisplayTitle,
timelineUrl = column.Scene is null ? null : Url.Action("Index", "Timeline", new { projectId = Model.Project.ProjectID, bookId = column.Book.Book.BookID, selectedSceneId = column.Scene.SceneID })
timelineUrl = column.Scene is null ? null : Url.Action("Index", "Timeline", new { projectId = Model.Project.ProjectID, bookId = column.Book.Book.BookID, selectedSceneId = column.Scene.SceneID, navigateFocus=true })
}).ToList();
var timelineMetricShapePayload = new
{
@ -798,6 +798,7 @@ else
asp-route-ProjectID="@Model.Project.ProjectID"
asp-route-BookID="@Model.SelectedBookID"
asp-route-SelectedSceneID="@scene.SceneID"
asp-route-navigateFocus="true"
asp-route-FocusType="scene"
asp-route-FocusID="@scene.SceneID"
title="Scene @scene.SceneNumber: @scene.SceneTitle&#10;POV: @povLabel&#10;Location: @(scene.PrimaryLocationName ?? "No location")&#10;@scene.Summary">
@ -1005,7 +1006,7 @@ else
asp-action="Index"
asp-route-projectId="@Model.Project.ProjectID"
asp-route-bookId="@Model.SelectedBookID"
asp-route-selectedSceneId="@point.SceneID"
asp-route-selectedSceneId="@point.SceneID" asp-route-navigateFocus="true"
class="metric-point"
style="--metric-height:@point.Percent%"
title="Scene @point.SceneNumber: @point.SceneTitle - @point.Value">
@ -1067,7 +1068,7 @@ else
asp-action="Index"
asp-route-ProjectID="@Model.Project.ProjectID"
asp-route-BookID="@Model.SelectedBookID"
asp-route-SelectedSceneID="@realAssetScene.SceneID"
asp-route-SelectedSceneID="@realAssetScene.SceneID" asp-route-navigateFocus="true"
asp-route-FocusType="asset"
asp-route-FocusID="@assetEvent.StoryAssetID"
title="@assetMarkerTooltip"

View File

@ -201,17 +201,17 @@
@if (warning.PreviousSceneId.HasValue)
{
<small class="text-muted d-block">Previous</small>
<a class="d-block mb-2" asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@warning.PreviousSceneId">@warning.PreviousContextSceneDisplayName</a>
<a class="d-block mb-2" asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@warning.PreviousSceneId" asp-route-navigateFocus="true">@warning.PreviousContextSceneDisplayName</a>
}
@if (warning.CurrentSceneId.HasValue)
{
<small class="text-muted d-block">Current</small>
<a class="d-block" asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@warning.CurrentSceneId">@warning.CurrentContextSceneDisplayName</a>
<a class="d-block" asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@warning.CurrentSceneId" asp-route-navigateFocus="true">@warning.CurrentContextSceneDisplayName</a>
}
}
else if (warning.SceneID.HasValue)
{
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@warning.SceneID">@warning.ContextSceneDisplayName</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-selectedSceneId="@warning.SceneID" asp-route-navigateFocus="true">@warning.ContextSceneDisplayName</a>
}
else
{

View File

@ -92,7 +92,7 @@
}
<div class="story-bible-actions">
<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@scene.SceneID">Open scene</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-bookId="@Model.Book.BookID" asp-route-selectedSceneId="@scene.SceneID">Timeline</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-bookId="@Model.Book.BookID" asp-route-selectedSceneId="@scene.SceneID" asp-route-navigateFocus="true">Timeline</a>
<a asp-controller="Warnings" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-bookId="@Model.Book.BookID" asp-route-sceneId="@scene.SceneID">Warnings</a>
</div>
</article>

View File

@ -29,7 +29,7 @@
<script src="~/js/writing-workspace-launcher.js" asp-append-version="true"></script>
@if(Model.Destination=="Plan"){<script src="~/js/writer-planner.js" asp-append-version="true"></script>}
@if(Model.Destination=="Explore"){<script src="~/js/writer-explore-layout.js" asp-append-version="true"></script><script src="~/js/writer-explore.js" asp-append-version="true"></script>}
@if(Model.Destination=="Review"){<link rel="stylesheet" href="~/css/writer-review-layout.css" asp-append-version="true" /><script src="~/js/writer-review-layout.js" asp-append-version="true"></script><script src="~/js/manuscript-reader.js" asp-append-version="true"></script><script src="~/js/review-authoring.js" asp-append-version="true"></script><script src="~/js/writer-review.js" asp-append-version="true"></script><script src="~/js/writer-work.js" asp-append-version="true"></script>}
@if(Model.Destination=="Review"){<link rel="stylesheet" href="~/css/writer-review-layout.css" asp-append-version="true" /><script src="~/js/writer-review-layout.js" asp-append-version="true"></script><script src="~/js/manuscript-reader.js" asp-append-version="true"></script><script src="~/js/review-authoring.js" asp-append-version="true"></script><script src="~/js/writer-review.js" asp-append-version="true"></script><script src="~/js/narrative-focus-review.js" asp-append-version="true"></script><script src="~/js/writer-work.js" asp-append-version="true"></script>}
@if(Model.Destination is "Write" or "Plan"){
<script src="~/js/writer-authoring.js" asp-append-version="true"></script>

View File

@ -3,7 +3,7 @@
ViewData["Title"] = "Writer Home";
ViewData["ProjectSection"] = "Writer";
ViewData["ShellClass"] = "pd-writer writer3-shell";
var focus = Model.Objective?.SceneTitle ?? Model.Objective?.ChapterTitle;
var focus = Model.NarrativeFocus?.Label;
}
<link rel="stylesheet" href="~/css/writer3.css" asp-append-version="true" />
<div class="writer3 writer3-home" data-writer-destination="Home" data-writer-queues-url="@Url.Action("Workspaces",new{projectId=Model.ProjectID,bookId=Model.BookID})" data-writer-legacy-url="@Url.Action("Overview",new{projectId=Model.ProjectID,bookId=Model.BookID})" data-writer-write-url="@Url.Action("Write",new{projectId=Model.ProjectID,bookId=Model.BookID})" data-writing-workspace-launcher data-compact-writer="true" data-project-id="@Model.ProjectID" data-book-id="@Model.BookID">
@ -13,7 +13,7 @@
<a class="writer3-choice" asp-action="Write" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">
<svg class="writer3-choice-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon("writer").IconPath" /></svg>
<h2>Continue Writing</h2><p>Work on your chapters, scenes<br class="writer3-desktop-break" /> and manuscript.</p>
<small>@(focus != null ? $"{Model.Objective!.Activity} · {focus}" : Model.Objective != null ? $"{Model.Objective.Activity} · Whole manuscript" : "Choose your first writing focus.")</small>
<small>@(focus != null ? $"Current Focus: {focus}" : "Choose your narrative location in Current Focus.")</small>
<span class="writer3-cta">Go to Write <span aria-hidden="true">→</span></span>
</a>
<a class="writer3-choice" asp-action="Explore" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">

View File

@ -3,7 +3,7 @@
<form asp-action="SaveObjective" method="post" class="writer-objective-form">
<input type="hidden" name="BookID" value="@Model.BookID" />
<label>Working activity<select class="form-select" name="Activity">@foreach(var activity in new[]{"Drafting","Revising","Editing","Researching","Proofreading"}){<option selected="@(objective?.Activity==activity)" value="@activity">@activity</option>}</select></label>
<label>Begin with<select class="form-select" name="ChapterID" data-objective-chapter><option value="">Whole manuscript</option>@foreach(var chapter in Model.ObjectiveChoices.DistinctBy(x=>x.ChapterID)){<option value="@chapter.ChapterID" selected="@(objective?.ChapterID==chapter.ChapterID)">@chapter.ChapterTitle</option>}</select></label>
<label>Scene (optional)<select class="form-select" name="SceneID" data-objective-scene><option value="">Chapter workspace</option>@foreach(var scene in Model.ObjectiveChoices.Where(x=>x.SceneID.HasValue)){<option value="@scene.SceneID" data-chapter="@scene.ChapterID" selected="@(objective?.SceneID==scene.SceneID)">@scene.SceneTitle</option>}</select></label>
<label>Begin with<select class="form-select" name="ChapterID" data-objective-chapter><option value="">Whole manuscript</option>@if(objective?.ChapterID is int savedChapter&&!Model.ObjectiveChoices.Any(x=>x.ChapterID==savedChapter)){<option value="@savedChapter" selected>Unavailable saved chapter — choose an explicit replacement</option>}@foreach(var chapter in Model.ObjectiveChoices.DistinctBy(x=>x.ChapterID)){<option value="@chapter.ChapterID" selected="@(objective?.ChapterID==chapter.ChapterID)">@chapter.ChapterTitle</option>}</select></label>
<label>Scene (optional)<select class="form-select" name="SceneID" data-objective-scene><option value="">Chapter workspace</option>@if(objective?.SceneID is int savedScene&&!Model.ObjectiveChoices.Any(x=>x.SceneID==savedScene)){<option value="@savedScene" data-chapter="@objective.ChapterID" selected>Unavailable saved scene — choose an explicit replacement</option>}@foreach(var scene in Model.ObjectiveChoices.Where(x=>x.SceneID.HasValue)){<option value="@scene.SceneID" data-chapter="@scene.ChapterID" selected="@(objective?.SceneID==scene.SceneID)">@scene.SceneTitle</option>}</select></label>
<div class="button-row"><button class="btn btn-primary" name="scheduleNow" value="false">Save objective · start without a schedule</button><button class="btn btn-outline-secondary" name="scheduleNow" value="true">Save &amp; plan writing time</button></div>
</form>

View File

@ -22,7 +22,7 @@
}else{
<h2>Scenes in this chapter</h2>
@if(Model.Scenes.Count==0){<p>There are no scenes yet. You can work at chapter level, or add a scene in the chapter editor.</p>}
@foreach(var scene in Model.Scenes){<form asp-controller="Writer" asp-action="SaveObjective" method="post" class="writer3-scene-choice"><input type="hidden" name="BookID" value="@Model.BookID" /><input type="hidden" name="ChapterID" value="@Model.ChapterID" /><input type="hidden" name="SceneID" value="@scene.SceneID" /><input type="hidden" name="Activity" value="@ViewData["WorkingActivity"]" /><span>@scene.SceneTitle · @scene.RevisionStatusName</span><button class="btn btn-sm btn-outline-secondary" type="submit">Work on this scene</button></form>}
@foreach(var scene in Model.Scenes){<div class="writer3-scene-choice"><span>@scene.SceneTitle · @scene.RevisionStatusName</span><button class="btn btn-sm btn-outline-secondary" type="button" data-narrative-scene="@scene.SceneID" data-narrative-chapter="@Model.ChapterID" data-narrative-book="@Model.BookID">Go to scene</button></div>}
<p class="writer3-caption">Chapter reminders live in the existing Things to include and Concerns fields above. Scene notes remain with their scenes; session return notes remain with sessions.</p>
}
<div class="writer3-inset" data-authoring-next-area><h3>Next useful action</h3>

View File

@ -6,10 +6,10 @@
<fieldset data-focus-step="0"><legend>What are you doing?</legend>
<label>Activity<select class="form-select" name="Activity" data-focus-activity>@foreach(var activity in PlotLine.Services.Writer.WriterFocusActivities.ObjectiveKinds){<option value="@activity" data-session-kind="@PlotLine.Services.Writer.WriterFocusActivities.SessionKind(activity)" selected="@(objective?.Activity==activity)">@activity</option>}</select></label>
<p>Choose your intended work. This does not start a recording.</p></fieldset>
<fieldset data-focus-step="1" hidden><legend>Where are you working?</legend>
<label>Chapter<select class="form-select" name="ChapterID" data-objective-chapter><option value="">Across the book</option>@foreach(var chapter in Model.ObjectiveChoices.DistinctBy(x=>x.ChapterID)){<option value="@chapter.ChapterID" selected="@(objective?.ChapterID==chapter.ChapterID)">@chapter.ChapterTitle</option>}</select></label>
<label>Scene (optional)<select class="form-select" name="SceneID" data-objective-scene><option value="">Across this chapter</option>@foreach(var scene in Model.ObjectiveChoices.Where(x=>x.SceneID.HasValue)){<option value="@scene.SceneID" data-chapter="@scene.ChapterID" selected="@(objective?.SceneID==scene.SceneID)">@scene.SceneTitle</option>}</select></label>
<fieldset data-focus-step="1" hidden><legend>Choose the objective target</legend>
<label>Chapter<select class="form-select" name="ChapterID" data-objective-chapter><option value="">Across the book</option>@if(objective?.ChapterID is int savedChapter&&!Model.ObjectiveChoices.Any(x=>x.ChapterID==savedChapter)){<option value="@savedChapter" selected>Unavailable saved chapter — choose an explicit replacement</option>}@foreach(var chapter in Model.ObjectiveChoices.DistinctBy(x=>x.ChapterID)){<option value="@chapter.ChapterID" selected="@(objective?.ChapterID==chapter.ChapterID)">@chapter.ChapterTitle</option>}</select></label>
<label>Scene (optional)<select class="form-select" name="SceneID" data-objective-scene><option value="">Across this chapter</option>@if(objective?.SceneID is int savedScene&&!Model.ObjectiveChoices.Any(x=>x.SceneID==savedScene)){<option value="@savedScene" data-chapter="@objective.ChapterID" selected>Unavailable saved scene — choose an explicit replacement</option>}@foreach(var scene in Model.ObjectiveChoices.Where(x=>x.SceneID.HasValue)){<option value="@scene.SceneID" data-chapter="@scene.ChapterID" selected="@(objective?.SceneID==scene.SceneID)">@scene.SceneTitle</option>}</select></label>
@if(Model.ObjectiveChoices.Count==0){<p>You can work across the book now, or <a asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID" asp-fragment="chapters">add a chapter or scene</a> when you need one.</p>}</fieldset>
<fieldset data-focus-step="2" hidden><legend>What do you want to achieve?</legend><label>Intention (optional)<textarea class="form-control" name="Intention" maxlength="2000" rows="3">@objective?.Intention</textarea></label><p>A short reminder of what matters in this piece of work.</p><p data-focus-confirmation></p></fieldset>
<p data-focus-error role="alert"></p><div class="button-row"><button type="button" class="btn btn-outline-secondary" data-focus-back hidden>Back</button><button type="button" class="btn btn-primary" data-focus-next>Continue</button><button type="submit" class="btn btn-primary" data-save-focus hidden>Save focus</button><button type="button" class="btn btn-link" data-focus-cancel>Cancel</button></div>
<p data-focus-error role="alert"></p><div class="button-row"><button type="button" class="btn btn-outline-secondary" data-focus-back hidden>Back</button><button type="button" class="btn btn-primary" data-focus-next>Continue</button><button type="submit" class="btn btn-primary" data-save-focus hidden>Save objective</button><button type="button" class="btn btn-link" data-focus-cancel>Cancel</button></div>
</form>

View File

@ -1,5 +1,5 @@
@model WriterDashboardViewModel
@{var reader=Model.ReviewReader;var word=new WriterDashboardViewModel{BookID=Model.BookID,ProjectID=Model.ProjectID,WordNavigationContext="review",Objective=reader?.Chapter==null?null:new(){ChapterID=reader.Chapter.ChapterID,ChapterTitle=reader.Chapter.ChapterTitle,Activity="Revising"}};}
@{var reader=Model.ReviewReader;var word=new WriterDashboardViewModel{BookID=Model.BookID,ProjectID=Model.ProjectID,WordNavigationContext="review",NarrativeFocus=Model.NarrativeFocus,ReviewReader=reader};}
<div class="writer3-workspace writer2-single" aria-label="Manuscript review">
<section class="writer3-panel writer3-main review-editorial-main" aria-label="Editorial review">
<div class="writer21-editorial" data-review-columns data-layout-owner="@User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value">

View File

@ -47,7 +47,7 @@ else
<div class="story-bible-actions">
<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@scene.SceneID">Open scene</a>
<a asp-controller="Exports" asp-action="WritingSession" asp-route-sceneId="@scene.SceneID">Session brief</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@scene.ProjectID" asp-route-bookId="@scene.BookID" asp-route-selectedSceneId="@scene.SceneID">Timeline</a>
<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@scene.ProjectID" asp-route-bookId="@scene.BookID" asp-route-selectedSceneId="@scene.SceneID" asp-route-navigateFocus="true">Timeline</a>
<a asp-controller="Warnings" asp-action="Index" asp-route-projectId="@scene.ProjectID" asp-route-bookId="@scene.BookID" asp-route-sceneId="@scene.SceneID">Warnings</a>
</div>
</article>

View File

@ -1,6 +1,6 @@
@model WriterDashboardViewModel
@{var focus=Model.Objective;var reviewing=Model.WordNavigationContext=="review";}
<section class="writer3-word writer3-inset" data-writer-word data-word-context="@Model.WordNavigationContext" data-book-id="@Model.BookID" data-chapter-id="@focus?.ChapterID" data-scene-id="@focus?.SceneID" data-status-url="/native-companion/status?writerBookId=@Model.BookID&amp;writerChapterId=@focus?.ChapterID" aria-label="Word Companion">
@{var focus=Model.NarrativeFocus;var reviewing=Model.WordNavigationContext=="review";var chapter=reviewing?Model.ReviewReader?.Chapter?.ChapterID:focus?.ChapterID;var scene=reviewing?(int?)null:focus?.SceneID;}
<section class="writer3-word writer3-inset" data-writer-word data-word-context="@Model.WordNavigationContext" data-book-id="@Model.BookID" data-chapter-id="@chapter" data-scene-id="@scene" data-status-url="/native-companion/status?writerBookId=@Model.BookID&amp;writerChapterId=@chapter" aria-label="Word Companion">
<div class="writer3-authoring-heading"><h3>Your manuscript in Word</h3><help-icon key="writer3.word" /></div>
<p data-word-state role="status">Checking Word Companion…</p>
<label data-word-choose hidden>Choose the manuscript in Word<select class="form-select" data-word-document><option value="">Choose a document</option></select></label>
@ -11,9 +11,9 @@
</div>
<details><summary>Connection and update options</summary><p class="writer3-caption">@(reviewing?"Review selection":"Working focus") and Word position can differ. Navigation does not save Word or change your session. Reader shows accepted content.</p><div class="button-row"><button type="button" class="btn btn-sm btn-outline-secondary" data-word-sync disabled>Check saved manuscript</button><button type="button" class="btn btn-sm btn-outline-secondary" data-word-check>Check connection &amp; updates</button></div></details>
<p data-word-command role="status" aria-live="polite"></p>
<form method="post" asp-action="SaveObjective" asp-controller="Writer" data-word-adopt hidden>
<input type="hidden" name="BookID" value="@Model.BookID"/><input type="hidden" name="ChapterID"/><input type="hidden" name="SceneID"/><input type="hidden" name="Activity" value="@(focus?.Activity??"Drafting")"/>
<p data-word-origin></p><button type="submit" class="btn btn-sm btn-outline-secondary">Use Word chapter as working focus</button>
<form method="post" asp-action="Set" asp-controller="NarrativeFocus" data-word-adopt hidden>
<input type="hidden" name="BookID" value="@Model.BookID"/><input type="hidden" name="ChapterID"/><input type="hidden" name="SceneID"/><input type="hidden" name="projectId" value="@Model.ProjectID"/><input type="hidden" name="version" value="@focus?.Version"/>
<p data-word-origin></p><button type="submit" class="btn btn-sm btn-outline-secondary">Use verified Word chapter as Current Focus</button>
</form>
<div hidden data-word-token>@Html.AntiForgeryToken()</div>
</section>

View File

@ -1,38 +1,41 @@
@model WriterDashboardViewModel
@{var focus = Model.Objective; var editing = Context.Request.Query["setup"] == "true"; var kind = focus?.Activity is "Revising" or "Editing" or "Proofreading" ? "Editing" : focus?.Activity == "Researching" ? "Planning" : "Writing";}
<div class="writer3-workspace" aria-label="Writing workspace">
<section class="writer3-panel writer3-main" tabindex="0" id="working-focus" aria-label="Current writing focus" data-writer-focus data-focus-url="@Url.Action("Focus","Writer",new{bookId=Model.BookID})" data-saved-activity="@focus?.Activity" data-saved-session-kind="@PlotLine.Services.Writer.WriterFocusActivities.SessionKind(focus?.Activity)" data-saved-chapter="@focus?.ChapterID" data-book-id="@Model.BookID" data-plan-url="@Url.Action("ScheduleSetup", "Writer", new { bookId = Model.BookID, projectId = Model.ProjectID })">
<p class="eyebrow">Your current work</p>
<section class="writer3-panel writer3-main" tabindex="0" id="working-focus" aria-label="Saved Writer objective" data-writer-focus data-focus-url="@Url.Action("Focus","Writer",new{bookId=Model.BookID})" data-saved-activity="@focus?.Activity" data-saved-session-kind="@PlotLine.Services.Writer.WriterFocusActivities.SessionKind(focus?.Activity)" data-saved-chapter="@focus?.ChapterID" data-book-id="@Model.BookID" data-plan-url="@Url.Action("ScheduleSetup", "Writer", new { bookId = Model.BookID, projectId = Model.ProjectID })">
<p class="eyebrow">Saved Writer objective</p>
<p data-writer-global-location>Current narrative location: @(Model.NarrativeFocus?.Label ?? "Choose in Current Focus")</p>
<p class="writer3-caption" data-objective-location data-chapter="@focus?.ChapterID" data-scene="@focus?.SceneID">Objective target: @(focus?.SceneTitle ?? focus?.ChapterTitle ?? "Across the book"). This target changes only when you edit the objective.</p>
<button type="button" class="btn btn-sm btn-outline-secondary" data-go-objective data-chapter="@focus?.ChapterID" data-scene="@focus?.SceneID" hidden="@(focus?.ChapterID==null)">Go to objective</button>
<div data-focus-summary>
@if(focus != null && !editing){
<h2>@(focus.SceneTitle ?? focus.ChapterTitle ?? "Your manuscript")</h2><p class="writer3-focus-kind">@focus.Activity</p>@if(focus.ChapterID.HasValue){<p class="writer3-caption">Chapter: @focus.ChapterTitle</p>}@if(!string.IsNullOrWhiteSpace(focus.Intention)){<p class="review-recorded">@focus.Intention</p>}<p>Keep your intention here; write manuscript prose in Word.</p>
<div class="button-row">
@if(focus.SceneID.HasValue){<a class="btn btn-primary writer3-cta" asp-controller="Scenes" asp-action="Edit" asp-route-id="@focus.SceneID">Open selected scene workspace <span aria-hidden="true">→</span></a>}
else if(focus.ChapterID.HasValue){<a class="btn btn-primary writer3-cta" asp-action="Chapter" asp-route-id="@focus.ChapterID">Open current chapter <span aria-hidden="true">→</span></a>}
else if(focus.ChapterID.HasValue){<a class="btn btn-primary writer3-cta" asp-action="Chapter" asp-route-id="@focus.ChapterID">Open objective chapter <span aria-hidden="true">→</span></a>}
else{<a class="btn btn-primary writer3-cta" asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID" asp-fragment="chapters">Open your chapters <span aria-hidden="true">→</span></a>}
</div>
}else{
<h2>@(editing ? "Choose your working focus" : "Where would you like to begin?")</h2><p>Choose an activity and, if you like, a chapter or scene. You can start without a writing plan.</p>
<h2>@(editing ? "Edit your saved objective" : "Where would you like to begin?")</h2><p>Choose an activity and, if you like, a chapter or scene. You can start without a writing plan.</p>
}
</div>
<button type="button" class="btn btn-link" hidden="@(focus==null||editing)" data-change-focus>Change activity, chapter or scene</button><p class="writer3-caption">Focus selects your working context. It does not change the manuscript or start recording.</p>
<button type="button" class="btn btn-link" hidden="@(focus==null||editing)" data-change-focus>Edit objective activity, intention or target</button><p class="writer3-caption">The objective is an independent task target. Changing Current Focus does not retarget it or its recording sessions.</p>
<div id="objective-setup" hidden="@(focus!=null&&!editing)">@if(focus==null||editing){<partial name="_WriterFocusForm" model="Model" />}</div>
<div class="writer3-authoring" data-writer-authoring data-inspect-url="@(focus?.ChapterID.HasValue==true?Url.Action("Inspect","WriterAuthoring",new{bookId=Model.BookID,chapterId=focus.ChapterID,sceneId=focus.SceneID}):null)" aria-live="polite"><p>Loading your recorded intentions…</p></div>
<div class="writer3-authoring" data-writer-authoring data-inspect-url="@(Model.NarrativeFocus?.ChapterID.HasValue==true?Url.Action("Inspect","WriterAuthoring",new{bookId=Model.BookID,chapterId=Model.NarrativeFocus.ChapterID,sceneId=Model.NarrativeFocus.SceneID}):null)" aria-live="polite"><p>Loading your recorded intentions…</p></div>
@if(!Model.ActivityIsPrivate){
<p class="writer3-caption" data-focus-session-difference hidden></p>
<div class="writer3-session-block"><h3>Work sessions &amp; Audio Review</h3><p class="writer3-caption">Recording keeps your saved working focus. Audio Review is recorded for a chapter.</p><partial name="_WriterWorkToolbar" model="new PlotLine.Models.WriterWorkToolbar(Model.BookID!.Value, focus?.ChapterID, focus?.ChapterTitle, Model.ObjectiveChoices, kind, true)" /></div>}
<div class="writer3-session-block"><h3>Work sessions &amp; Audio Review</h3><p class="writer3-caption">Recording keeps its explicitly selected objective or session target. Audio Review is recorded for a chapter.</p><partial name="_WriterWorkToolbar" model="new PlotLine.Models.WriterWorkToolbar(Model.BookID!.Value, focus?.ChapterID, focus?.ChapterTitle, Model.ObjectiveChoices, kind, true)" /></div>}
else{<p class="muted">Work-session evidence is private to the book owner. Your chapter and scene tools remain available.</p>}
</section>
<aside class="writer3-panel writer3-reference" tabindex="0" aria-label="Writing tools">
<h2>Keep your story close</h2><div class="button-row"><a class="btn btn-outline-secondary" data-focus-reference-link asp-controller="Writing" asp-action="Context" asp-route-bookId="@Model.BookID" asp-route-chapterId="@focus?.ChapterID" asp-route-sceneId="@focus?.SceneID">Context</a><a class="btn btn-outline-secondary" data-focus-reference-link asp-controller="Writing" asp-action="Intent" asp-route-bookId="@Model.BookID" asp-route-chapterId="@focus?.ChapterID" asp-route-sceneId="@focus?.SceneID">Intent</a></div><p data-writing-workspace-message role="status"></p><partial name="_WriterWord" model="Model" /><div data-authoring-references></div><p>Open the existing tools when you need more detail.</p>
<h2>Keep your story close</h2><div class="button-row"><a class="btn btn-outline-secondary" data-focus-reference-link asp-controller="Writing" asp-action="Context" asp-route-bookId="@Model.BookID" asp-route-chapterId="@Model.NarrativeFocus?.ChapterID" asp-route-sceneId="@Model.NarrativeFocus?.SceneID">Context</a><a class="btn btn-outline-secondary" data-focus-reference-link asp-controller="Writing" asp-action="Intent" asp-route-bookId="@Model.BookID" asp-route-chapterId="@Model.NarrativeFocus?.ChapterID" asp-route-sceneId="@Model.NarrativeFocus?.SceneID">Intent</a></div><p data-writing-workspace-message role="status"></p><partial name="_WriterWord" model="Model" /><div data-authoring-references></div><p>Open the existing tools when you need more detail.</p>
<div class="writer3-link-list">
<a asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID" asp-fragment="chapters">Chapters &amp; scenes <span aria-hidden="true">↗</span></a>
@if(focus?.ChapterID.HasValue==true){<a asp-action="Chapter" asp-route-id="@focus.ChapterID">Chapter goals &amp; workflow <span aria-hidden="true">↗</span></a>}
<a asp-action="Workspaces" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Scene workspaces <span aria-hidden="true">↗</span></a>
</div>
@if(Model.ProjectID.HasValue){<details class="writer3-authoring-details"><summary>Open story reference tools</summary><div class="writer3-link-list"><a asp-controller="Characters" asp-action="Index" asp-route-projectId="@Model.ProjectID">Characters</a><a asp-controller="PlotLineWorkspace" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Plot lines and threads</a><a asp-controller="RelationshipMap" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Relationships</a><a asp-controller="Maps" asp-action="Index" asp-route-projectId="@Model.ProjectID">Maps and locations</a><a asp-controller="ProjectMetrics" asp-action="Index" asp-route-projectId="@Model.ProjectID">Recorded emotion and scene metrics</a></div></details>}
<p class="writer3-caption">Context and Intent are reference tools. Their selection is separate from your saved writing focus; use Back to return.</p>
<p class="writer3-caption">Context and Intent are reference tools. Their selection is separate from your saved objective; use Back to return.</p>
</aside>
</div>

View File

@ -170,3 +170,8 @@ body.rw-page [data-pwa-context-controls] .pd-context-group[aria-label="Focus"] .
.rw-board.palettes-hidden { grid-template-columns: minmax(0,1fr); grid-template-rows: minmax(0,1fr) 92px; }
.rw-board.palettes-hidden .rw-rail { grid-column: 1; grid-row: 1/3; }
}
/* Scene Explorer includes local navigation as well as relationship-change markers. */
.rw-board{grid-template-rows:76px minmax(0,1fr) auto 72px;}
.rw-timeline{overflow:visible;}
.rw-board.palettes-hidden{grid-template-rows:minmax(0,1fr) auto;}
@media(max-width:800px){.rw-board{grid-template-rows:minmax(0,1fr) auto;}}

View File

@ -0,0 +1,13 @@
.pd-scene-explorer{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap;min-width:0;padding:.5rem 0}
.pd-scene-explorer select{max-width:100%;min-width:0;flex:1 1 14rem;background:var(--pd-surface);color:var(--pd-text);border:1px solid var(--pd-border);border-radius:4px;padding:.35rem}
.pd-scene-explorer button{border:1px solid var(--pd-border);border-radius:4px;padding:.35rem .6rem;background:var(--pd-surface);color:var(--pd-text)}
.pd-scene-explorer input[type=range]{flex:1 1 12rem;min-width:0}
.pd-scene-explorer small{flex-basis:100%;color:var(--pd-muted)}
.pd-narrative-focus{position:relative;width:clamp(10rem,26vw,28rem);min-width:10rem;max-width:28rem;font-size:.82rem;margin-inline:.4rem;}
.pd-narrative-focus>summary{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:pointer;}
.pd-focus-picker{position:absolute;z-index:1100;inset-block-start:100%;inset-inline-start:0;width:min(32rem,88vw);padding:1rem;background:var(--bs-body-bg);color:var(--bs-body-color);border:1px solid var(--bs-border-color);border-radius:.4rem;box-shadow:0 .4rem 1rem #0003;}
.pd-focus-picker label{display:block;margin-block:.5rem;}
.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;}.pd-focus-picker{position:fixed;inset-inline-start:1rem;inset-block-start:4rem;}}
.timeline-scene-card.pd-current-narrative-focus{outline:2px solid var(--pd-accent);outline-offset:2px;}

View File

@ -1,4 +1,4 @@
(() => {
function initialiseManuscriptReader() {
const root = document.querySelector('.manuscript-reader');
if (!root) return;
root.readerCleanup?.();
@ -218,7 +218,7 @@
finally { finish(); }
};
const stop = () => { stopped = true; clearTimeout(timer); request?.abort(); };
root.readerCleanup = () => { stop(); listeners.abort(); };
root.readerCleanup = () => { stop(); listeners.abort(); for(const [node,previous] of subdued)node.inert=previous;subdued.clear();document.body.classList.remove('reader-focused'); };
on(document, 'selectionchange', () => { if (pending() && !hasSelection()) void tryUpdate(); });
on(pause, 'change', () => { indicate(); if (!pause.checked) void tryUpdate(); });
on(apply, 'click', () => { pause.checked = false; window.getSelection()?.removeAllRanges(); void tryUpdate(true); });
@ -234,8 +234,10 @@
loading.hidden = true;
if (event.persisted) { stopped = false; void check(); }
});
indicate();
if (chapterId) {
root.querySelector('.reader-live-controls').hidden = false;
void check();
}
})();
}
window.PlotDirectorManuscriptReader={mount:initialiseManuscriptReader};initialiseManuscriptReader();

View File

@ -77,7 +77,7 @@
const context=current?`${index+1} / ${selected.length} · Ch ${current.chapterNumber} · ${current.position.locationName||'No Location'} · ${current.position.status}`:'No scenes in this scope';scrubber.setAttribute('aria-valuetext',context);$('mapStoryScrubberContext').textContent=context;
$('mapStoryCoverage').hidden=!unmapped;$('mapStoryCoverage').title='Story Mode can only place scenes whose Locations are represented on this map.';
if(mapped<selected.length&&state.lens!=='time')$('mapsStory').textContent+=' Story Mode can only place scenes whose Locations are represented on this map.';
redraw();renderDetails(W.selected[0]);remember();
redraw();renderDetails(W.selected[0]);remember();sceneExplorer?.sync();
if(active())window.dispatchEvent(new CustomEvent('pd-map-story-state',{detail:{...state,selection:undefined,mapID:W.document.map.mapID}}));
}
function position(f){return [f.x,f.y];}
@ -141,7 +141,7 @@
const pane=$('mapsDetails'),scroll=pane.scrollTop;$('mapsDetailContent').innerHTML=`<div class="maps-story-details">${html}</div>`;pane.scrollTop=scroll;return true;
}
function chooseScene(id,characterID=0){const s=scenes.get(id);if(!s)return;state.sceneID=id;state.selection={kind:'scene',sceneID:id,characterID};if(![...$('mapStoryScene').options].some(o=>Number(o.value)===id)){$('mapStorySceneSearch').value='';scopeOptions();}$('mapStoryScene').value=String(id);const stop=characterID?data.stops.find(x=>x.characterID===characterID&&x.sceneID===id):null,p=stop?.position||s.position;internalSelect=true;if(p.featureID){W.select(p.featureID);W.focus(p.featureID);}else W.clearSelection();internalSelect=false;refresh();}
function navigateStep(direction){if(!data)return;const sequence=state.lens==='time'?E.timeEvents(data,state.bookID):visibleScenes(),index=state.lens==='time'?sequence.findIndex(s=>s.startDateTime===state.at):sequence.findIndex(s=>s.sceneID===state.sceneID),next=sequence[index+direction];if(!next)return;if(state.lens==='time'){state.at=next.startDateTime;$('mapStoryTime').value=state.at;state.selection={kind:'overview'};refresh();}else chooseScene(next.sceneID);}
function navigateStep(direction){if(!data)return;if(state.lens==='scene'){sceneExplorer.step(direction);return;}const sequence=state.lens==='time'?E.timeEvents(data,state.bookID):visibleScenes(),index=state.lens==='time'?sequence.findIndex(s=>s.startDateTime===state.at):sequence.findIndex(s=>s.sceneID===state.sceneID),next=sequence[index+direction];if(!next)return;if(state.lens==='time'){state.at=next.startDateTime;$('mapStoryTime').value=state.at;state.selection={kind:'overview'};refresh();}else chooseScene(next.sceneID);}
svg.addEventListener('pointerdown',e=>{if(active()&&e.target.closest('[data-feature-id]')&&!internalSelect)state.selection={kind:'feature'};},true);
document.addEventListener('click',e=>{if(active()&&e.target.closest('[data-search-feature]'))state.selection={kind:'feature'};},true);
document.addEventListener('click',e=>{
@ -172,10 +172,11 @@
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;}
});
let scrubFrame=null,scrubValue=0;
function scrub(){scrubFrame=null;const s=visibleScenes()[scrubValue];if(s)chooseScene(s.sceneID);}
$('mapStoryScrubber').addEventListener('input',e=>{scrubValue=Number(e.target.value);if(!scrubFrame)scrubFrame=requestAnimationFrame(scrub);});
$('mapStoryScrubber').addEventListener('change',e=>{scrubValue=Number(e.target.value);if(scrubFrame)cancelAnimationFrame(scrubFrame);scrub();});
const sceneExplorer = window.PlotDirectorSceneExplorer.create({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'});
$('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

@ -0,0 +1,45 @@
// Refresh only the read-only Review content. Stable columns, media/session controls and Word state survive.
(() => {
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;
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);}
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();
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.');}
}
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.addEventListener('pagehide',()=>{++generation;request?.abort();});
})();

View File

@ -0,0 +1,55 @@
// The only browser commit path for current narrative context. Local explorers never call it implicitly.
(() => {
'use strict';
const root=document.querySelector('[data-narrative-focus]');if(!root)return;
let state=JSON.parse(root.querySelector('[data-narrative-initial]').textContent),busy=false,epoch=0,refreshQueued=false;
const select=root.querySelector('[data-focus-position]'),recent=root.querySelector('[data-focus-recent]'),search=root.querySelector('[data-focus-search]'),status=root.querySelector('[data-narrative-status]');
const bookPicker=root.querySelector('[data-focus-book]');
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();}}}
bookPicker?.addEventListener('change',()=>void loadScope(Number(bookPicker.value)));
const key=p=>`${p.chapterID||''}/${p.sceneID||''}`;
const selected=()=>key(state);
const entries=()=>{const chapters=new Set(),items=[];for(const p of state.positions){if(!chapters.has(p.chapterID)){chapters.add(p.chapterID);items.push({...p,sceneID:null,label:`Ch ${p.chapterNumber}: ${p.chapterTitle}`});}if(p.sceneID)items.push(p);}return items;};
const currentLabel=()=>`${bookPicker&&state.bookID?([...bookPicker.options].find(o=>Number(o.value)===state.bookID)?.textContent||'Book')+' · ':''}${state.label||'Choose chapter or scene'}`;
function render(){
root.querySelector('[data-focus-label]').textContent=`Current Focus: ${currentLabel()}`;root.querySelector('[data-focus-label]').title=`Current narrative focus: ${currentLabel()}`;
const term=search.value.trim().toLocaleLowerCase();
select.replaceChildren(new Option('Choose chapter or scene…',''),...entries().filter(p=>!term||p.label.toLocaleLowerCase().includes(term)).map(p=>new Option(p.label,key(p),false,key(p)===selected())));
const all=entries();recent.replaceChildren(new Option('Recent chapter / scene…',''),...state.recent.map(h=>all.find(p=>key(p)===key(h))).filter(Boolean).map(p=>new Option(p.label,key(p))));
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;});
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{}
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;}
window.dispatchEvent(new CustomEvent('plotdirector:narrative-focus-changed',{detail:state}));}
async function refresh(){if(!state.bookID)return;if(busy){refreshQueued=true;return;}refreshQueued=false;const mine=++epoch;try{const response=await fetch(`/NarrativeFocus/Read?projectId=${state.projectID}&bookId=${state.bookID}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const fresh=await response.json();if(mine!==epoch||busy)return;if(fresh.version!==state.version){state=fresh;publish();}else{state=fresh;render();}}catch{if(mine===epoch&&!busy)status.textContent='Current focus could not be refreshed. Your edits are retained.';}}
async function set(target={}){
if(busy||!state.bookID){status.textContent='Choose a focus book first.';return false;}
if(target.bookID&&Number(target.bookID)!==state.bookID||target.projectID&&Number(target.projectID)!==state.projectID){status.textContent='Choose this book in the header before setting its focus.';return false;}
busy=true;++epoch;render();status.textContent='Updating current focus…';
const body=new URLSearchParams({projectId:state.projectID,bookId:state.bookID,version:state.version,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});
if(target.chapterID)body.set('chapterId',target.chapterID);if(target.sceneID)body.set('sceneId',target.sceneID);if(target.direction)body.set('direction',target.direction);
try{
const response=await fetch('/NarrativeFocus/Set',{method:'POST',body});const result=await response.json().catch(()=>null);
if(!response.ok||response.redirected){if(response.status===409){busy=false;await refresh();}throw Error(result?.message||'Current focus could not be changed.');}
state=result;publish();status.textContent='Current focus updated. Your workspace and saved targets are retained.';
try{localStorage.setItem(notificationKey(),String(state.version));}catch{}
return true;
}catch(error){status.textContent=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)})));
root.addEventListener('keydown',e=>{if(e.key==='Escape'){root.open=false;root.querySelector('summary').focus();}});
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('toggle',()=>{if(root.open)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{}}
const url=new URL(location.href);if(url.searchParams.has('navigateFocus')){url.searchParams.delete('navigateFocus');history.replaceState(history.state,'',url);}
})();

View File

@ -45,6 +45,7 @@
const castById = new Map(cast.map(c => [c.characterID, c]));
const storageKey = `pd.relationship-workspace.v1.${projectId}.${workspace.bookId || 'project'}`;
let focus = workspace.focusCharacterId, source = null, saveTimer, request = null, loading = false, stateLoaded = true;
const sceneStorageKey=`pd.scene-explorer.relationships:${document.body.dataset.pdUserId}:${projectId}:${workspace.bookId||'project'}`;
let currentScene = workspace.sceneId;
let editorRelationships = workspace.relationships(), editorRequest = null, activeRelationship = null;
let editorReady = true;
@ -278,6 +279,7 @@
// Ordinary scrolling remains available; zoom with Ctrl/Cmd + wheel, buttons or pinch.
cy.userZoomingEnabled(false);
graph.addEventListener('wheel', event => { if (!event.ctrlKey && !event.metaKey) return; event.preventDefault(); cy.zoom(Math.max(.05, Math.min(2.5, cy.zoom() * (event.deltaY < 0 ? 1.1 : .9)))); }, { passive: false });
let sceneExplorer = null;
let changes = workspace.changeSceneIDs.map(id => scenes.findIndex(s => Number(s.value) === id) + 1).filter(n => n > 0).sort((a,b) => a-b);
const changeMarks = document.getElementById('rwChanges');
function renderMarkers() {
@ -291,6 +293,8 @@
renderMarkers();
changes.forEach(n => { const option = document.createElement('option'); option.value = n; option.label = scenes[n-1].text; changeMarks.append(option); });
timeline.value = currentScene ? scenes.findIndex(s => Number(s.value) === currentScene) + 1 : workspace.bookId ? scenes.length + 1 : 0;
const initialPoint=String(timeline.value);
try{const saved=sessionStorage.getItem(sceneStorageKey);if(!workspace.sceneId&&saved){const index=scenes.findIndex(s=>String(s.value)===saved);if(saved==='initial')timeline.value=0;else if(saved==='end')timeline.value=scenes.length+1;else if(index>=0)timeline.value=index+1;}}catch{}
function labelPoint() {
const index = Number(timeline.value);
point.textContent = index === 0 ? 'Initial' : index > scenes.length ? 'End' : scenes[index - 1].text;
@ -298,6 +302,7 @@
currentScene = index === 0 ? null : Number(scenes[Math.min(index, scenes.length) - 1]?.value) || null;
timeline.style.setProperty('--rw-progress', `${index / Math.max(1, Number(timeline.max)) * 100}%`);
document.getElementById('rwDetailPoint').textContent = `At: ${point.textContent}`;
sceneExplorer?.sync();
}
labelPoint();
function navigatePoint(value) { timeline.value = value; timeline.dispatchEvent(new Event('input')); }
@ -318,6 +323,7 @@
loading = true;
try {
const params = new URLSearchParams({ projectId });
if (workspace.bookId) params.set('bookId',workspace.bookId);
if (currentScene) params.set('sceneId', currentScene);
const response = await fetch(`/RelationshipMap/State?${params}`, { signal: active.signal });
if (!response.ok) throw new Error('Could not load relationship state.');
@ -338,7 +344,12 @@
} catch (error) { if (error.name !== 'AbortError') { stateLoaded = false; status.textContent = error.message; } }
finally { if (active === request) loading = false; }
}
timeline.addEventListener('input', () => { labelPoint(); loading = true; stateLoaded = false; clearTimeout(scrubTimer); scrubTimer = setTimeout(refresh, 160); });
const explorerPositions = () => [{id:'initial',label:'Initial relationships',isScene:false},...scenes.map(s=>({id:s.value,label:s.text})),{id:'end',label:'End relationships',isScene:false}];
sceneExplorer = window.PlotDirectorSceneExplorer.create({host:document.querySelector('.rw-timeline'),positions:explorerPositions,
selected:()=>explorerPositions()[Number(timeline.value)]?.id,range:timeline,output:point,
change:p=>{try{sessionStorage.setItem(sceneStorageKey,String(p.id));}catch{}timeline.value=explorerPositions().findIndex(s=>String(s.id)===String(p.id));labelPoint();loading=true;stateLoaded=false;clearTimeout(scrubTimer);scrubTimer=setTimeout(refresh,160);}});
if(String(timeline.value)!==initialPoint)void refresh();
function jump(next) { const n = Number(timeline.value); timeline.value = next ? changes.find(i => i > n) ?? scenes.length + 1 : [...changes].reverse().find(i => i < n) ?? 0; timeline.dispatchEvent(new Event('input')); }
document.getElementById('rwPrevious').addEventListener('click', () => jump(false));
document.getElementById('rwNext').addEventListener('click', () => jump(true));

View File

@ -0,0 +1,55 @@
// Local presentation only. The optional promotion callback is the sole explicit global write path.
(() => {
'use strict';
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 }) {
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; };
const ownedSelect = !select;
select ||= make('select'); select.setAttribute('aria-label', 'Scene to visualise');
if (!previous) { previous = make('button', '‹ Previous Scene'); previous.type = 'button'; }
if (!next) { next = make('button', 'Next Scene ›'); next.type = 'button'; }
previous.dataset.ribbonIcon = 'chevron-left'; next.dataset.ribbonIcon = 'chevron-right';
for(const [button,key]of [[previous,'chevron-left'],[next,'chevron-right']]){const svg=document.querySelector('[data-pwa-icon-catalog]')?.content.querySelector(`[data-icon-key="${key}"]`)?.cloneNode(true);if(svg&&!button.querySelector('svg')){svg.removeAttribute('data-icon-key');button.textContent=key==='chevron-left'?'Previous Scene':'Next Scene';button.prepend(svg);}}
previous.title = 'Visualise the previous scene'; next.title = 'Visualise the next scene';
if (!range) { range = make('input'); range.type = 'range'; }
range.setAttribute('aria-label', 'Scene position in manuscript order'); range.step = '1';
output ||= make('output'); output.setAttribute('aria-live', 'polite');
const hint = make('small', 'Scene Explorer changes this visualisation only.');
const promote=make('button','Set Current Focus Here');promote.type='button';promote.hidden=true;
controls.append(hint);
promote.addEventListener('click',async()=>{const item=items[index];const focus=window.PlotDirectorNarrativeFocus;if(!item||!focus)return;const target=focus.state.positions.find(p=>String(p.sceneID)===String(item.id));if(target)await focus.set(target);});
function promotion(){const focus=window.PlotDirectorNarrativeFocus;promote.hidden=!focus;promote.disabled=!focus||!items[index]||!focus.state.positions.some(p=>String(p.sceneID)===String(items[index].id));promote.title=promote.disabled?'Choose a scene from the current book to set global focus':'Set current narrative focus without changing this visualisation';}
const events=new AbortController();window.addEventListener('plotdirector:narrative-focus-changed',promotion,{signal:events.signal});
host.append(controls);
let items = [], index = -1, signature = '';
function sync() {
if (!enabled()) return;
items = positions(); index = items.findIndex(p => String(p.id) === String(selected()));
const nextSignature = items.map(p => `${p.id}:${p.label}`).join('|');
if (ownedSelect && signature !== nextSignature) {
select.replaceChildren(...items.map(p => new Option(p.label, String(p.id)))); signature = nextSignature;
}
select.value = index >= 0 ? String(items[index].id) : '';
range.min = '0'; range.max = String(Math.max(0, items.length - 1)); range.value = String(Math.max(0, index));
range.disabled = !items.length; previous.disabled = !items.some((p,i)=>p.isScene!==false&&i<index); next.disabled = !items.some((p,i)=>p.isScene!==false&&i>index);
output.textContent = index >= 0 ? items[index].label : 'No scene selected'; range.setAttribute('aria-valuetext', output.textContent);
select.disabled = !items.length; promotion();
}
function choose(id) {
if (!enabled()) return;
items = positions(); const found = items.find(p => String(p.id) === String(id));
if (!found) return;
change(found); sync();
}
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)); }
sync();
return { sync, choose, step, destroy:()=>events.abort(), get position() { return items[index] || null; }, controls, hint };
}
};
})();

View File

@ -39,7 +39,6 @@
}
for(const details of container.querySelectorAll('details'))if(!details.dataset.authoringBound){details.dataset.authoringBound='true';details.addEventListener('toggle',()=>{if(!details.open&&[...details.querySelectorAll('[data-authoring-form]')].some(f=>f.dataset.dirty==='true')){details.open=true;const pending=details.querySelector('[data-authoring-form][data-dirty="true"]');if(pending)cardOf(pending).querySelector('[data-authoring-status]').textContent='Save or Cancel this editor before closing the section.';}});}
for(const button of container.querySelectorAll('[data-authoring-next]'))button.addEventListener('click',()=>root.querySelector(`[data-key="${CSS.escape(button.dataset.authoringNext)}"] [data-authoring-edit]`)?.click());
for(const input of container.querySelectorAll('.writer3-scene-choice [name=Activity]'))input.value=document.querySelector('[data-writer-focus]').dataset.savedActivity;
}
function replaceCard(card,doc){if(!card.isConnected)return;const fresh=doc.querySelector(`[data-key="${CSS.escape(card.dataset.key)}"]`);if(!fresh)throw Error('Saved record is not available');const clone=fresh.cloneNode(true),parent=card.parentElement;card.replaceWith(clone);bind(parent);clone.querySelector('[data-authoring-status]').textContent='Saved.';clone.querySelector('[data-authoring-edit]')?.focus();}
async function read(){const response=await fetch(root.dataset.inspectUrl,{cache:'no-store'});if(!response.ok)throw Error('Recorded information is unavailable');const doc=new DOMParser().parseFromString(await response.text(),'text/html');if(!doc.querySelector('[data-authoring-content]'))throw Error('Authorisation or recorded information is unavailable');return doc;}
@ -49,6 +48,11 @@
window.addEventListener('beforeunload',e=>{if(dirty()&&!allowLeave){e.preventDefault();e.returnValue='';}});
function guard(e){if(!dirty())return;const target=e.target.closest('a,form,[data-plan-focus]');if(!target||target.matches('[data-authoring-form],[data-work-start]')||target.target==='_blank'||target.hasAttribute('download'))return;if(target.tagName==='A'&&new URL(target.href,location.href).pathname===location.pathname&&new URL(target.href,location.href).search===location.search&&target.hash)return;if(!confirm(root.querySelector('[data-busy="true"]')?'A save is in progress and may finish after you leave. Leave this page?':'Leave without saving your inline edits?')){e.preventDefault();e.stopImmediatePropagation();}else allowLeave=true;}
document.addEventListener('click',e=>{if(e.target.closest('a,[data-plan-focus]'))guard(e);},true);document.addEventListener('submit',guard,true);window.addEventListener('pageshow',()=>allowLeave=false);
window.addEventListener('plotdirector:focus-saved',e=>{root.dataset.inspectUrl=e.detail.inspectUrl||'';void load();});
const navigationNotice=document.createElement('p');navigationNotice.className='writer3-caption';navigationNotice.hidden=true;root.before(navigationNotice);
let pendingFocus=null;
function applyFocus(focus){root.dataset.inspectUrl=focus.chapterID?`/WriterAuthoring/Inspect?bookId=${focus.bookID}&chapterId=${focus.chapterID}${focus.sceneID?'&sceneId='+focus.sceneID:''}`:'';pendingFocus=null;navigationNotice.hidden=true;void load();}
window.addEventListener('plotdirector:narrative-focus-changed',e=>{const focus=e.detail;if(focus.bookID!==Number(document.querySelector('[data-writer-focus]')?.dataset.bookId))return;
if(dirty()||root.querySelector('[data-authoring-form]:not([hidden])')){pendingFocus=focus;navigationNotice.hidden=false;navigationNotice.replaceChildren(document.createTextNode('Current focus changed. These editors retain their original target. '));const button=document.createElement('button');button.type='button';button.className='btn btn-sm btn-link';button.textContent='Show current focus';button.addEventListener('click',()=>{if(dirty()||root.querySelector('[data-authoring-form]:not([hidden])')){button.textContent='Save or cancel the open editor first';return;}applyFocus(pendingFocus);});navigationNotice.append(button);}else applyFocus(focus);
});
load();
})();

View File

@ -9,7 +9,7 @@
if(choice)choice.hidden=s.activity!=='Proofreading'||!!active;
if(record){record.hidden=!!active;record.disabled=!known||pending;}
if(hint)hint.textContent=active?'':s.activity==='Proofreading'?'Choose Editing or Reading review explicitly to record proofreading.':`Optional recording uses the existing ${k} session type. Saving and planning remain separate.`;
const difference=root.querySelector('[data-focus-session-difference]');if(difference){difference.hidden=!active;difference.textContent=active?`Active recording: ${active.kind} · ${active.chapterTitle||'Whole manuscript'}. ${!root.dataset.savedActivity?'No working focus has been saved. ':String(active.chapterID||'')!==String(root.dataset.savedChapter||'')||root.dataset.savedSessionKind!==active.kind?'This differs from your saved working focus. ':''}Changing or saving focus does not retarget this session.`:'';}
const difference=root.querySelector('[data-focus-session-difference]');if(difference){difference.hidden=!active;difference.textContent=active?`Active recording: ${active.kind} · ${active.chapterTitle||'Whole manuscript'}. ${!root.dataset.savedActivity?'No objective has been saved. ':String(active.chapterID||'')!==String(root.dataset.savedChapter||'')||root.dataset.savedSessionKind!==active.kind?'This differs from your saved objective. ':''}Editing an objective or navigating does not retarget this session.`:'';}
}
root.addEventListener('plotdirector:work-state',e=>{known=true;active=e.detail.session;render();});
root.addEventListener('plotdirector:work-start-finished',()=>{pending=false;render();});

View File

@ -1,17 +1,21 @@
(() => {
const root=document.querySelector('[data-writer-focus]'); if(!root)return;
const host=root.querySelector('#objective-setup');let loading=false;
function initialise(){const form=host.querySelector('[data-focus-wizard]');if(!form)return;let step=0,busy=false;
window.addEventListener('beforeunload',event=>{const form=host.querySelector('[data-focus-wizard]');if(!host.hidden&&form&&(form.dataset.dirty==='true'||form.dataset.busy==='true')){event.preventDefault();event.returnValue='';}});
function initialise(){const form=host.querySelector('[data-focus-wizard]');if(!form)return;let step=0,busy=false;const fields=['Activity','ChapterID','SceneID','Intention'];let savedFields=Object.fromEntries(fields.map(name=>[name,form.elements[name].value]));
form.addEventListener('input',()=>form.dataset.dirty='true');form.addEventListener('change',()=>form.dataset.dirty='true');
const chapter=form.querySelector('[data-objective-chapter]'),scene=form.querySelector('[data-objective-scene]');
function filter(){for(const o of scene.options){o.hidden=!!o.value&&o.dataset.chapter!==chapter.value;o.disabled=o.hidden;}if(scene.selectedOptions[0]?.disabled)scene.value='';scene.disabled=!chapter.value;}
function render(){form.querySelectorAll('[data-focus-step]').forEach((x,i)=>x.hidden=i!==step);form.querySelector('[data-focus-back]').hidden=step===0;form.querySelector('[data-focus-next]').hidden=step===2;form.querySelector('[data-save-focus]').hidden=step!==2;form.querySelector('[data-focus-step-label]').textContent=`Step ${step+1} of 3`;form.querySelector('[data-focus-confirmation]').textContent=`Save ${form.elements.Activity.value.toLowerCase()} · ${scene.value?scene.selectedOptions[0].textContent:chapter.selectedOptions[0].textContent}. No session will be recorded.`;}
chapter.addEventListener('change',filter);filter();render();
for(const [selector,direction] of [['[data-focus-next]',1],['[data-focus-back]',-1]])form.querySelector(selector).addEventListener('click',()=>{step+=direction;render();form.querySelector('[data-focus-step]:not([hidden]) select, [data-focus-step]:not([hidden]) textarea')?.focus();});
form.querySelector('[data-focus-cancel]').addEventListener('click',()=>{host.hidden=true;const change=root.querySelector('[data-change-focus]');if(change)change.hidden=false;root.querySelector('[data-change-focus]')?.focus();});
form.addEventListener('submit',async e=>{e.preventDefault();if(e.defaultPrevented&&e.cancelBubble)return;if(busy)return;if(step!==2){step++;render();return;}busy=true;const button=form.querySelector('[data-save-focus]');button.disabled=true;form.querySelector('[data-focus-error]').textContent='';try{const response=await fetch(form.action,{method:'POST',body:new FormData(form),headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw Error();const data=await response.json();if(!data.saved)throw Error();
form.querySelector('[data-focus-cancel]').addEventListener('click',()=>{if(busy)return;for(const name of fields)form.elements[name].value=savedFields[name];filter();step=0;render();form.dataset.dirty='false';host.hidden=true;const change=root.querySelector('[data-change-focus]');if(change)change.hidden=false;root.querySelector('[data-change-focus]')?.focus();});
form.addEventListener('submit',async e=>{e.preventDefault();if(e.defaultPrevented&&e.cancelBubble)return;if(busy)return;if(step!==2){step++;render();return;}busy=true;form.dataset.busy='true';form.querySelector('[data-focus-cancel]').disabled=true;const button=form.querySelector('[data-save-focus]');button.disabled=true;form.querySelector('[data-focus-error]').textContent='';try{const response=await fetch(form.action,{method:'POST',body:new FormData(form),headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw Error();const data=await response.json();if(!data.saved)throw Error();
savedFields={Activity:data.activity,ChapterID:String(data.chapterID||''),SceneID:String(data.sceneID||''),Intention:data.intention||''};
root.dataset.savedActivity=data.activity;root.dataset.savedChapter=data.chapterID||'';root.dataset.savedSessionKind=data.sessionKind||'';
let summary=root.querySelector('[data-focus-summary]');if(!summary){summary=document.createElement('div');host.before(summary);}summary.replaceChildren();const h=document.createElement('h2');h.textContent=data.activity+' · '+data.title;const p=document.createElement('p');p.textContent=data.intention||'Your focus is saved. No recording has started.';const a=document.createElement('a');a.href=data.continueUrl;a.className='btn btn-primary';a.textContent=data.sceneID?'Open selected scene workspace':data.chapterID?'Open selected chapter workspace':'Open chapters';summary.append(h,p,a);host.hidden=true;const change=root.querySelector('[data-change-focus]');if(change)change.hidden=false;busy=false;button.disabled=false;
for(const link of document.querySelectorAll('[data-focus-reference-link]')){const target=new URL(link.href);target.searchParams.delete('chapterId');target.searchParams.delete('sceneId');if(data.chapterID)target.searchParams.set('chapterId',data.chapterID);if(data.sceneID)target.searchParams.set('sceneId',data.sceneID);link.href=target;}window.dispatchEvent(new CustomEvent('plotdirector:focus-saved',{detail:data}));summary.tabIndex=-1;summary.focus();}catch{form.querySelector('[data-focus-error]').textContent='Your focus could not be confirmed. Your choices are retained; please try again.';busy=false;button.disabled=false;}});
let summary=root.querySelector('[data-focus-summary]');if(!summary){summary=document.createElement('div');host.before(summary);}summary.replaceChildren();const h=document.createElement('h2');h.textContent=data.activity+' · '+data.title;const p=document.createElement('p');p.textContent=data.intention||'Your objective is saved. No recording has started.';const a=document.createElement('a');a.href=data.continueUrl;a.className='btn btn-primary';a.textContent=data.sceneID?'Open selected scene workspace':data.chapterID?'Open selected chapter workspace':'Open chapters';summary.append(h,p,a);form.dataset.dirty='false';host.hidden=true;const change=root.querySelector('[data-change-focus]');if(change)change.hidden=false;busy=false;form.dataset.busy='false';form.querySelector('[data-focus-cancel]').disabled=false;button.disabled=false;
const target=root.querySelector('[data-objective-location]');if(target){target.dataset.chapter=data.chapterID||'';target.dataset.scene=data.sceneID||'';target.textContent='Objective target: '+data.title+'. This target changes only when you edit the objective.';}const go=root.querySelector('[data-go-objective]');if(go){go.dataset.chapter=data.chapterID||'';go.dataset.scene=data.sceneID||'';go.hidden=!data.chapterID;}
window.dispatchEvent(new CustomEvent('plotdirector:focus-saved',{detail:data}));summary.tabIndex=-1;summary.focus();}catch{form.querySelector('[data-focus-error]').textContent='Your objective could not be confirmed. Your choices are retained; please try again.';busy=false;form.dataset.busy='false';form.querySelector('[data-focus-cancel]').disabled=false;button.disabled=false;}});
}
root.querySelector('[data-change-focus]')?.addEventListener('click',async e=>{e.preventDefault();if(loading)return;e.currentTarget.hidden=true;if(host.querySelector('form')){host.hidden=false;return;}loading=true;host.hidden=false;host.textContent='Loading your focus…';try{const r=await fetch(root.dataset.focusUrl);if(!r.ok)throw Error();host.innerHTML=await r.text();initialise();}catch{host.textContent='Focus is temporarily unavailable. Try Change focus again.';const change=root.querySelector('[data-change-focus]');if(change)change.hidden=false;}finally{loading=false;}});
initialise();

View File

@ -1,7 +1,9 @@
// Author actions only. Selection never navigates Word, creates a record or changes working/session focus.
(()=>{'use strict';const root=document.querySelector('[data-writer-review]'),reader=document.querySelector('.manuscript-reader');if(!root||!reader)return;
function initialiseReview(){'use strict';const root=document.querySelector('[data-writer-review]'),reader=document.querySelector('.manuscript-reader');if(!root||!reader)return;
root.reviewDispose?.();const events=new AbortController();const onWindow=(name,handler,options)=>window.addEventListener(name,handler,{capture:options===true,signal:events.signal});const onDocument=(name,handler,options)=>document.addEventListener(name,handler,{capture:options===true,signal:events.signal});
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();};
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};}
@ -33,5 +35,6 @@ readerContent.addEventListener('keyup',()=>{if(dirty||busy)return;const choice=c
reader.addEventListener('reader:metadata',()=>{if(!dirty)wordReference(selected);});
reader.addEventListener('reader:updated',()=>{if(dirty)return;if(selected&&!readerContent.querySelector(`[data-paragraph-id="${CSS.escape(selected)}"]`)){selected=null;anchor=null;wordReference(null);message.textContent='The selected paragraph is no longer in the accepted chapter. Original observation references remain recorded.';}else wordReference(selected);void load();});
function guard(e){if(!dirty&&!busy)return;const target=e.target.closest('a,form');if(!target||target===form||target.matches('[data-work-start]')||target.target==='_blank'||target.matches('.plotline-help-more')&&window.PlotLineHelpDrawer)return;if(!confirm(busy?'An observation save may still finish. Leave this Review page?':'Leave without saving your review observation?')){e.preventDefault();e.stopImmediatePropagation();}else allowLeave=true;}
document.addEventListener('click',e=>{if(e.target.closest('a'))guard(e);},true);document.addEventListener('submit',guard,true);window.addEventListener('beforeunload',e=>{if((dirty||busy)&&!allowLeave){e.preventDefault();e.returnValue='';}});window.addEventListener('pageshow',e=>{allowLeave=false;if(e.persisted&&!dirty)void load();});window.addEventListener('pagehide',()=>{clearTimeout(selectionTimer);controller?.abort();});for(const b of document.querySelectorAll('[data-review-scope-new]'))b.addEventListener('click',()=>{begin(b.dataset.reviewScopeNew);});window.addEventListener('review:notes-saved',()=>void load());void load();
})();
onDocument('click',e=>{if(e.target.closest('a'))guard(e);},true);onDocument('submit',guard,true);onWindow('beforeunload',e=>{if((dirty||busy)&&!allowLeave){e.preventDefault();e.returnValue='';}});onWindow('pageshow',e=>{allowLeave=false;if(e.persisted&&!dirty)void load();});onWindow('pagehide',()=>{clearTimeout(selectionTimer);controller?.abort();});for(const b of document.querySelectorAll('[data-review-scope-new]'))b.addEventListener('click',()=>{begin(b.dataset.reviewScopeNew);});onWindow('review:notes-saved',()=>void load());void load();
}
window.PlotDirectorReview={mount:initialiseReview};initialiseReview();

View File

@ -27,10 +27,14 @@ if(nav)nav.disabled ||= availability.chapter!==true;if(sceneNav)sceneNav.disable
if(nav)nav.disabled ||= !chapter;if(sceneNav)sceneNav.disabled ||= !scene;if(paragraphButton)paragraphButton.disabled ||= !root.dataset.paragraphId;
for(const button of document.querySelectorAll('[data-ribbon-word]')){const original=button.dataset.ribbonWord==='chapter'?nav:button.dataset.ribbonWord==='scene'?sceneNav:paragraphButton;button.disabled=!original||original.disabled;button.title=button.dataset.navigationTitle+(button.disabled?' Select a verified target, connect and synchronise its Word manuscript.':'');}
const params=new URLSearchParams(location.search),origin=current&&params.get('wordInstanceId')===current.instanceId&&params.get('wordSessionId')===current.sessionId;
adopt.hidden=reviewing||!(origin&&observed&&observed.chapterId!==chapter);if(!adopt.hidden){adopt.querySelector('[name=ChapterID]').value=observed.chapterId;adopt.querySelector('[name=SceneID]').value=observed.sceneId||'';adopt.querySelector('[data-word-origin]').textContent='Opened from verified Word chapter '+(observed.chapterTitle||'in this manuscript')+'. Your saved working focus is unchanged.';}
adopt.hidden=reviewing||!(origin&&observed&&observed.chapterId!==chapter);if(!adopt.hidden){adopt.querySelector('[name=ChapterID]').value=observed.chapterId;adopt.querySelector('[name=SceneID]').value=observed.sceneId||'';adopt.querySelector('[data-word-origin]').textContent='Opened from verified Word chapter '+(observed.chapterTitle||'in this manuscript')+'. Your saved objective is unchanged.';}
}
select.addEventListener('change',()=>render(packet));
window.addEventListener('plotdirector:focus-saved',event=>{abort?.abort();message.textContent='Working target changed. Word has not moved.';chapter=Number(event.detail.chapterID)||0;scene=Number(event.detail.sceneID)||0;root.dataset.chapterId=chapter||'';root.dataset.sceneId=scene||'';root.dataset.paragraphId='';root.dataset.statusUrl='/native-companion/status?writerBookId='+book+'&writerChapterId='+chapter;if(packet)render(packet);requestStatus();});
adopt.addEventListener('submit',async event=>{event.preventDefault();if(adopt.hidden||!window.PlotDirectorNarrativeFocus)return;await window.PlotDirectorNarrativeFocus.set({bookID:book,chapterID:Number(adopt.querySelector('[name=ChapterID]').value),sceneID:Number(adopt.querySelector('[name=SceneID]').value)||null});});
window.addEventListener('plotdirector:narrative-focus-changed',event=>{if(event.detail.bookID!==book||reviewing)return;applyNarrative(event);});
window.addEventListener('review:narrative-applied',event=>{if(reviewing&&event.detail.bookID===book)applyNarrative(event);});
function applyNarrative(event){const targetChapter=Number(event.detail.chapterID)||0,targetScene=Number(event.detail.sceneID)||0;if(chapter===targetChapter&&scene===targetScene)return;abort?.abort();message.textContent=busy?'Navigation was not confirmed because the intended target changed. Check Word before retrying.':'';chapter=targetChapter;scene=targetScene;root.dataset.chapterId=chapter||'';root.dataset.sceneId=scene||'';root.dataset.paragraphId='';root.dataset.statusUrl='/native-companion/status?writerBookId='+book+'&writerChapterId='+chapter;if(packet)render(packet);requestStatus();}
for(const button of document.querySelectorAll('[data-ribbon-word]'))button.addEventListener('click',()=>{if(button.disabled)return;(button.dataset.ribbonWord==='chapter'?nav:button.dataset.ribbonWord==='scene'?sceneNav:paragraphButton)?.click();});
async function navigate(toScene,toParagraph=false){if(busy||!current||!chapter)return;if(Date.parse(current.expires)<=Date.now()){message.textContent='Word connection expired. Check the connection before navigating.';render({...packet,leases:[]});requestStatus();return;}busy=true;abort=new AbortController();const selected={...current},id=crypto.randomUUID(),dispatch=performance.now();render(packet);message.textContent='Requesting navigation in Word…';const form=new URLSearchParams({bookId:String(book),chapterId:String(chapter),instanceId:selected.instanceId,sessionId:selected.sessionId,manuscriptId:selected.manuscriptId,revision:String(selected.revision),navigationId:id,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});if(toScene)form.set('sceneId',String(scene));if(toParagraph){form.set('paragraphId',root.dataset.paragraphId);form.set('acceptedRevision',root.dataset.acceptedRevision);}try{const response=await fetch('/WriterWord/Navigate',{method:'POST',body:form,signal:abort.signal});const data=await response.json().catch(()=>null);if(!response.ok)throw Error(data?.message||'Navigation could not be requested. Check your connection and sign-in.');message.textContent='Requested in Word; waiting for confirmation.';console.debug('Word navigation',id,'server request ms',Math.round(performance.now()-dispatch));const start=Date.now();let done=false;while(Date.now()-start<30000){await new Promise((resolve,reject)=>{const signal=abort.signal;const cancel=()=>{clearTimeout(timer);reject(new Error('Navigation was not confirmed. Word changed or disconnected.'));};const timer=setTimeout(()=>{signal.removeEventListener('abort',cancel);resolve();},1000);signal.addEventListener('abort',cancel,{once:true});});const receipt=await fetch(`/WriterWord/Navigation?bookId=${book}&instanceId=${selected.instanceId}&sessionId=${selected.sessionId}&navigationId=${id}`,{signal:abort.signal,cache:'no-store'});if(!receipt.ok)throw Error('Navigation confirmation unavailable.');const result=await receipt.json();if(result.state!=='requested'){console.debug('Word navigation',id,'confirmation ms',Math.round(performance.now()-dispatch),result.state);message.textContent=result.state==='completed'?(toParagraph?'Word confirmed navigation to the paragraph start.':'Word confirmed navigation.'):result.state==='failed'?'Word could not navigate. Your work was retained.':'Navigation expired or the document changed. No completion was confirmed.';done=true;break;}}if(!done)message.textContent='Word did not confirm navigation in time. Check the manuscript before retrying.';}catch(error){availabilityKey='';availability={};message.textContent=error.name==='AbortError'?'Navigation was not confirmed. Check Word before retrying.':error.message;}finally{busy=false;abort=null;if(packet)render(packet);requestStatus();}}