From 6d2c51a651619c779d5cfb1b4da40ad80e3f5f7e Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Fri, 20 Nov 2026 14:24:04 +0000 Subject: [PATCH] Unify narrative focus without retargeting Writer objectives --- Docs/Navigation/NarrativeFocusArchitecture.md | 109 +++++++++++++ PlotLine.Tests/ApplicationNavigationTests.cs | 6 + PlotLine.Tests/Browser/narrative-focus.cjs | 99 ++++++++++++ PlotLine.Tests/Browser/writer3-authoring.cjs | 10 +- PlotLine.Tests/NarrativeFocusDatabaseTests.cs | 41 +++++ PlotLine.Tests/NarrativeFocusFixture.cs | 31 ++++ PlotLine.Tests/NarrativeNavigationTests.cs | 48 ++++++ PlotLine.Tests/Program.cs | 2 + PlotLine.Tests/Sql/NarrativeFocus.sql | 106 +++++++++++++ .../Sql/NarrativeFocusRepositoryFixture.sql | 17 ++ PlotLine.Tests/ToolbarBrowserHost.cs | 18 ++- PlotLine.Tests/WriterNavigationTests.cs | 7 +- .../Controllers/NarrativeFocusController.cs | 23 +++ PlotLine/Controllers/WriterController.cs | 32 +++- PlotLine/Program.cs | 2 + PlotLine/Services/ApplicationNavigation.cs | 11 +- PlotLine/Services/CoreServices.cs | 5 +- PlotLine/Services/NarrativeFocus.cs | 64 ++++++++ .../Services/NarrativeNavigationFilter.cs | 44 +++++ .../Services/SubscriptionEnforcementFilter.cs | 3 +- PlotLine/Services/Writer/WriterSuggestions.cs | 4 +- PlotLine/Sql/292_NarrativeFocus.sql | 150 ++++++++++++++++++ .../Sql/293_NarrativeFocusCanonicalOrder.sql | 46 ++++++ .../294_NarrativeFocusChapterBoundaries.sql | 102 ++++++++++++ .../ApplicationNavigationViewModel.cs | 1 + PlotLine/ViewModels/CoreViewModels.cs | 1 + PlotLine/Views/Analytics/Index.cshtml | 6 +- PlotLine/Views/Chapters/Details.cshtml | 2 +- PlotLine/Views/Characters/Details.cshtml | 10 +- .../Views/ContinuityExplorer/Index.cshtml | 14 +- PlotLine/Views/FloorPlans/Edit.cshtml | 30 ++-- PlotLine/Views/Locations/Details.cshtml | 2 +- .../Views/RelationshipMap/_Workspace.cshtml | 4 +- .../Views/Shared/_ApplicationShell.cshtml | 3 +- PlotLine/Views/Shared/_Layout.cshtml | 3 + PlotLine/Views/Shared/_NarrativeFocus.cshtml | 16 ++ PlotLine/Views/StoryAssets/Details.cshtml | 4 +- PlotLine/Views/StoryBible/Index.cshtml | 2 +- .../_StoryCalendarDayDetails.cshtml | 2 +- PlotLine/Views/StoryPoint/Index.cshtml | 2 +- PlotLine/Views/StoryPoint/_Snapshot.cshtml | 2 +- PlotLine/Views/Timeline/Index.cshtml | 7 +- PlotLine/Views/Warnings/Index.cshtml | 6 +- PlotLine/Views/Writer/Chapter.cshtml | 2 +- PlotLine/Views/Writer/Destination.cshtml | 2 +- PlotLine/Views/Writer/Index.cshtml | 4 +- PlotLine/Views/Writer/_ObjectiveForm.cshtml | 4 +- PlotLine/Views/Writer/_WriterAuthoring.cshtml | 2 +- PlotLine/Views/Writer/_WriterFocusForm.cshtml | 8 +- PlotLine/Views/Writer/_WriterReview.cshtml | 2 +- .../Views/Writer/_WriterSceneQueue.cshtml | 2 +- PlotLine/Views/Writer/_WriterWord.cshtml | 10 +- PlotLine/Views/Writer/_WriterWrite.cshtml | 21 +-- .../wwwroot/css/relationship-workspace.css | 5 + PlotLine/wwwroot/css/scene-explorer.css | 13 ++ PlotLine/wwwroot/js/manuscript-reader.js | 8 +- PlotLine/wwwroot/js/maps-story.js | 13 +- PlotLine/wwwroot/js/narrative-focus-review.js | 45 ++++++ PlotLine/wwwroot/js/narrative-focus.js | 55 +++++++ PlotLine/wwwroot/js/relationship-workspace.js | 13 +- PlotLine/wwwroot/js/scene-explorer.js | 55 +++++++ PlotLine/wwwroot/js/writer-authoring.js | 8 +- PlotLine/wwwroot/js/writer-focus.js | 2 +- PlotLine/wwwroot/js/writer-objective.js | 14 +- PlotLine/wwwroot/js/writer-review.js | 9 +- PlotLine/wwwroot/js/writer-word.js | 8 +- 66 files changed, 1277 insertions(+), 125 deletions(-) create mode 100644 Docs/Navigation/NarrativeFocusArchitecture.md create mode 100644 PlotLine.Tests/Browser/narrative-focus.cjs create mode 100644 PlotLine.Tests/NarrativeFocusDatabaseTests.cs create mode 100644 PlotLine.Tests/NarrativeFocusFixture.cs create mode 100644 PlotLine.Tests/NarrativeNavigationTests.cs create mode 100644 PlotLine.Tests/Sql/NarrativeFocus.sql create mode 100644 PlotLine.Tests/Sql/NarrativeFocusRepositoryFixture.sql create mode 100644 PlotLine/Controllers/NarrativeFocusController.cs create mode 100644 PlotLine/Services/NarrativeFocus.cs create mode 100644 PlotLine/Services/NarrativeNavigationFilter.cs create mode 100644 PlotLine/Sql/292_NarrativeFocus.sql create mode 100644 PlotLine/Sql/293_NarrativeFocusCanonicalOrder.sql create mode 100644 PlotLine/Sql/294_NarrativeFocusChapterBoundaries.sql create mode 100644 PlotLine/Views/Shared/_NarrativeFocus.cshtml create mode 100644 PlotLine/wwwroot/css/scene-explorer.css create mode 100644 PlotLine/wwwroot/js/narrative-focus-review.js create mode 100644 PlotLine/wwwroot/js/narrative-focus.js create mode 100644 PlotLine/wwwroot/js/scene-explorer.js diff --git a/Docs/Navigation/NarrativeFocusArchitecture.md b/Docs/Navigation/NarrativeFocusArchitecture.md new file mode 100644 index 00000000..8d1d05f9 --- /dev/null +++ b/Docs/Navigation/NarrativeFocusArchitecture.md @@ -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. diff --git a/PlotLine.Tests/ApplicationNavigationTests.cs b/PlotLine.Tests/ApplicationNavigationTests.cs index 4d6733f0..c572ddcb 100644 --- a/PlotLine.Tests/ApplicationNavigationTests.cs +++ b/PlotLine.Tests/ApplicationNavigationTests.cs @@ -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((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."); diff --git a/PlotLine.Tests/Browser/narrative-focus.cjs b/PlotLine.Tests/Browser/narrative-focus.cjs new file mode 100644 index 00000000..6b88c733 --- /dev/null +++ b/PlotLine.Tests/Browser/narrative-focus.cjs @@ -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;}); diff --git a/PlotLine.Tests/Browser/writer3-authoring.cjs b/PlotLine.Tests/Browser/writer3-authoring.cjs index e18983f0..fec1d443 100644 --- a/PlotLine.Tests/Browser/writer3-authoring.cjs +++ b/PlotLine.Tests/Browser/writer3-authoring.cjs @@ -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}); diff --git a/PlotLine.Tests/NarrativeFocusDatabaseTests.cs b/PlotLine.Tests/NarrativeFocusDatabaseTests.cs new file mode 100644 index 00000000..b4b1e028 --- /dev/null +++ b/PlotLine.Tests/NarrativeFocusDatabaseTests.cs @@ -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(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(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"); + } +} diff --git a/PlotLine.Tests/NarrativeFocusFixture.cs b/PlotLine.Tests/NarrativeFocusFixture.cs new file mode 100644 index 00000000..34c383e3 --- /dev/null +++ b/PlotLine.Tests/NarrativeFocusFixture.cs @@ -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 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 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?ichapterIndex)).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 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);} +} diff --git a/PlotLine.Tests/NarrativeNavigationTests.cs b/PlotLine.Tests/NarrativeNavigationTests.cs new file mode 100644 index 00000000..b13c55aa --- /dev/null +++ b/PlotLine.Tests/NarrativeNavigationTests.cs @@ -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((name,args)=>{ + if(name!="Open"||args![0] is not int actor||actor!=4)throw new Exception("Unexpected focus operation"); + writes++;return Task.FromResult(new(){ProjectID=7,BookID=12,ChapterID=21,SceneID=(int?)args[2],Version=2}); + }); + var user=NativeWorkflowTests.Proxy((_,_) => (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{{"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(),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(),navigationController); + bool allowedNavigation=false; + await new SubscriptionEnforcementFilter(user,NativeWorkflowTests.Proxy((_,_)=>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"); + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 71fa04e6..a0ce4653 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -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()), diff --git a/PlotLine.Tests/Sql/NarrativeFocus.sql b/PlotLine.Tests/Sql/NarrativeFocus.sql new file mode 100644 index 00000000..adc82412 --- /dev/null +++ b/PlotLine.Tests/Sql/NarrativeFocus.sql @@ -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; diff --git a/PlotLine.Tests/Sql/NarrativeFocusRepositoryFixture.sql b/PlotLine.Tests/Sql/NarrativeFocusRepositoryFixture.sql new file mode 100644 index 00000000..1b49e6f0 --- /dev/null +++ b/PlotLine.Tests/Sql/NarrativeFocusRepositoryFixture.sql @@ -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; diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 8bb4935a..dc3ffe05 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -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().Read(context.RequestServices.GetRequiredService().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()).AddApplicationPart(typeof(ToolbarController).Assembly); builder.Services.AddSignalR(); builder.Services.AddScoped(); builder.Services.AddSingleton(); @@ -140,18 +141,27 @@ internal static class ToolbarBrowserHost builder.Services.AddSingleton(FixtureProxy((name, args) => throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((name, args) => throw new NotSupportedException(name))); + builder.Services.AddSingleton(FixtureProxy((name,args)=>{ + if(name!="GetAsync")throw new NotSupportedException(name); + var filter=(TimelineFilterViewModel)args![0]!; + IReadOnlyList 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(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(); builder.Services.AddScoped(services => ManuscriptReaderTests.FixtureService(() => services.GetRequiredService().HttpContext!.Request.Query["reader-error"] == "true" ? throw new TimeoutException("Synthetic unavailable manuscript") : services.GetRequiredService().HttpContext!.Request.Query["reader-long"] == "true" ? readerLongFixture : readerFixture,allowSecondBook:true)); builder.Services.AddHttpContextAccessor(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddScoped(services => new ApplicationNavigation( FixtureProxy((name, args) => name == "GetForUserAsync" ? Task.FromResult(new Project { ProjectID = 7, ProjectName = "The Glass Harbour", AccessRole = "Owner" }) : throw new NotSupportedException(name)), FixtureProxy((name, args) => name == "ListByProjectAsync" ? Task.FromResult>([new() { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" }, new() { BookID = 13, ProjectID = 7, BookTitle = "The Return" }]) : throw new NotSupportedException(name)), - services.GetRequiredService())); + services.GetRequiredService(), services.GetRequiredService())); builder.Services.AddSingleton(FixtureProxy((name,args)=>name switch { "ListByProjectAsync" => Task.FromResult>([new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore"},new(){BookID=13,ProjectID=7,BookTitle="The Return"}]), "GetAsync" => Task.FromResult((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().Read(context.RequestServices.GetRequiredService().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("
" + menu + toolbar + "
" + surface + "
" + appearanceScript + "" + writerScripts + ""); + await context.Response.WriteAsync("
" + menu + toolbar + "
" + surface + "
" + appearanceScript + "" + writerScripts + ""); }); app.MapHub("/hubs/word-companion-follow"); await app.RunAsync(); diff --git a/PlotLine.Tests/WriterNavigationTests.cs b/PlotLine.Tests/WriterNavigationTests.cs index 5d636107..5b3354d7 100644 --- a/PlotLine.Tests/WriterNavigationTests.cs +++ b/PlotLine.Tests/WriterNavigationTests.cs @@ -26,15 +26,16 @@ internal static class WriterNavigationTests _=>throw new Exception(n)}); var schedules=NativeWorkflowTests.Proxy((n,a)=>n=="GetTodayDashboardAsync"?Task.FromResult(new WritingScheduleDashboardViewModel()):throw new Exception("Navigation attempted schedule mutation "+n)); var access=NativeWorkflowTests.Proxy((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((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>>{ ["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"); diff --git a/PlotLine/Controllers/NarrativeFocusController.cs b/PlotLine/Controllers/NarrativeFocusController.cs new file mode 100644 index 00000000..d4a44f8f --- /dev/null +++ b/PlotLine/Controllers/NarrativeFocusController.cs @@ -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 Read(int projectId,int bookId) => Execute(() => focus.Read(currentUser.UserId!.Value,projectId,bookId)); + [HttpPost,ValidateAntiForgeryToken] + public Task 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 Execute(Func> 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."});} + } +} diff --git a/PlotLine/Controllers/WriterController.cs b/PlotLine/Controllers/WriterController.cs index 0844b2f8..141f66a6 100644 --- a/PlotLine/Controllers/WriterController.cs +++ b/PlotLine/Controllers/WriterController.cs @@ -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 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 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 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 Dashboard(int? projectId, int? bookId = null) => LoadDestination("Dashboard", projectId, bookId); public Task 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); diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 4916c1af..1c05ef75 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -28,6 +28,7 @@ public class Program builder.Services.AddControllersWithViews(options => { options.Filters.Add(); + options.Filters.Add(); options.Filters.Add(); }); builder.Services.AddSignalR(options => @@ -214,6 +215,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/PlotLine/Services/ApplicationNavigation.cs b/PlotLine/Services/ApplicationNavigation.cs index 07a34ab0..a5459f1c 100644 --- a/PlotLine/Services/ApplicationNavigation.cs +++ b/PlotLine/Services/ApplicationNavigation.cs @@ -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; } diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index 7e853c49..91727225 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -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, diff --git a/PlotLine/Services/NarrativeFocus.cs b/PlotLine/Services/NarrativeFocus.cs new file mode 100644 index 00000000..c8998cfd --- /dev/null +++ b/PlotLine/Services/NarrativeFocus.cs @@ -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 Positions { get; init; } = []; + public IReadOnlyList 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 Open(int user, int? chapter, int? scene, int? expectedProject=null, int? expectedBook=null); + Task Read(int user, int project, int book); + Task 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 Open(int user,int? chapter,int? scene,int? expectedProject=null,int? expectedBook=null) + { + NarrativeFocusState? target; + using(var db=factory.CreateConnection()) + target=await db.QuerySingleOrDefaultAsync("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 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(); + return state with { Positions=(await rows.ReadAsync()).ToArray(), Recent=(await rows.ReadAsync()).ToArray() }; + } + public async Task 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); + } +} diff --git a/PlotLine/Services/NarrativeNavigationFilter.cs b/PlotLine/Services/NarrativeNavigationFilter.cs new file mode 100644 index 00000000..288e4615 --- /dev/null +++ b/PlotLine/Services/NarrativeNavigationFilter.cs @@ -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"); +} diff --git a/PlotLine/Services/SubscriptionEnforcementFilter.cs b/PlotLine/Services/SubscriptionEnforcementFilter.cs index 070be9d9..0037dd69 100644 --- a/PlotLine/Services/SubscriptionEnforcementFilter.cs +++ b/PlotLine/Services/SubscriptionEnforcementFilter.cs @@ -10,7 +10,8 @@ public sealed class SubscriptionEnforcementFilter( { private static readonly HashSet 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) diff --git a/PlotLine/Services/Writer/WriterSuggestions.cs b/PlotLine/Services/Writer/WriterSuggestions.cs index b025bb22..95f21313 100644 --- a/PlotLine/Services/Writer/WriterSuggestions.cs +++ b/PlotLine/Services/Writer/WriterSuggestions.cs @@ -8,7 +8,7 @@ public sealed class WriterSuggestionProvider:IWriterSuggestionProvider public IReadOnlyList Suggest(WriterDashboardViewModel model) { var result=new List(); - 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)); diff --git a/PlotLine/Sql/292_NarrativeFocus.sql b/PlotLine/Sql/292_NarrativeFocus.sql new file mode 100644 index 00000000..2a1ae0a6 --- /dev/null +++ b/PlotLine/Sql/292_NarrativeFocus.sql @@ -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 diff --git a/PlotLine/Sql/293_NarrativeFocusCanonicalOrder.sql b/PlotLine/Sql/293_NarrativeFocusCanonicalOrder.sql new file mode 100644 index 00000000..2c38b32b --- /dev/null +++ b/PlotLine/Sql/293_NarrativeFocusCanonicalOrder.sql @@ -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 diff --git a/PlotLine/Sql/294_NarrativeFocusChapterBoundaries.sql b/PlotLine/Sql/294_NarrativeFocusChapterBoundaries.sql new file mode 100644 index 00000000..c0aedcc6 --- /dev/null +++ b/PlotLine/Sql/294_NarrativeFocusChapterBoundaries.sql @@ -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@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 diff --git a/PlotLine/ViewModels/ApplicationNavigationViewModel.cs b/PlotLine/ViewModels/ApplicationNavigationViewModel.cs index 0b5400ae..1e681264 100644 --- a/PlotLine/ViewModels/ApplicationNavigationViewModel.cs +++ b/PlotLine/ViewModels/ApplicationNavigationViewModel.cs @@ -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; } diff --git a/PlotLine/ViewModels/CoreViewModels.cs b/PlotLine/ViewModels/CoreViewModels.cs index d03f07f0..75e0baed 100644 --- a/PlotLine/ViewModels/CoreViewModels.cs +++ b/PlotLine/ViewModels/CoreViewModels.cs @@ -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"; diff --git a/PlotLine/Views/Analytics/Index.cshtml b/PlotLine/Views/Analytics/Index.cshtml index e5798f73..9381eecf 100644 --- a/PlotLine/Views/Analytics/Index.cshtml +++ b/PlotLine/Views/Analytics/Index.cshtml @@ -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"> @point.Value } @@ -192,7 +192,7 @@

Needs attention

@foreach (var scene in Model.RevisionAttentionScenes.Take(8)) { - + @scene.RevisionStatusName Ch @scene.ChapterNumber / Scene @scene.SceneNumber: @scene.SceneTitle @@ -212,7 +212,7 @@

Missing purpose/outcome

@foreach (var gap in Model.SceneGaps.Take(8)) { - + @(gap.MissingPurpose ? "No purpose" : "") @(gap.MissingOutcome ? "No outcome" : "") Ch @gap.ChapterNumber / Scene @gap.SceneNumber: @gap.SceneTitle diff --git a/PlotLine/Views/Chapters/Details.cshtml b/PlotLine/Views/Chapters/Details.cshtml index c7e857b8..52273d2c 100644 --- a/PlotLine/Views/Chapters/Details.cshtml +++ b/PlotLine/Views/Chapters/Details.cshtml @@ -169,7 +169,7 @@ - Open in timeline + Open in timeline Edit
diff --git a/PlotLine/Views/Characters/Details.cshtml b/PlotLine/Views/Characters/Details.cshtml index 9f428a2c..2f1eb8aa 100644 --- a/PlotLine/Views/Characters/Details.cshtml +++ b/PlotLine/Views/Characters/Details.cshtml @@ -459,7 +459,7 @@ { @item.Description } - Open scene + Open scene }
@@ -494,7 +494,7 @@ { @item.Description } - Open in timeline + Open in timeline Open related character
} @@ -517,7 +517,7 @@ @appearance.BookDisplayTitle / Ch @appearance.ChapterNumber / Scene @appearance.SceneNumber: @appearance.SceneTitle @appearance.RoleInSceneTypeName / @appearance.PresenceTypeName @appearance.OutfitDescription @appearance.PhysicalCondition @appearance.EmotionalState - Open in timeline + Open in timeline } @@ -539,7 +539,7 @@ @item.AttributeName: @item.AttributeValue @item.BookDisplayTitle / Ch @item.ChapterNumber / Scene @item.SceneNumber: @item.SceneTitle @item.Description - Open in timeline + Open in timeline } @@ -561,7 +561,7 @@ @item.KnowledgeStateName: @(item.AssetName ?? item.ThreadTitle) @item.BookDisplayTitle / Ch @item.ChapterNumber / Scene @item.SceneNumber: @item.SceneTitle @item.Description - Open in timeline + Open in timeline } diff --git a/PlotLine/Views/ContinuityExplorer/Index.cshtml b/PlotLine/Views/ContinuityExplorer/Index.cshtml index db9ed61b..5982eefc 100644 --- a/PlotLine/Views/ContinuityExplorer/Index.cshtml +++ b/PlotLine/Views/ContinuityExplorer/Index.cshtml @@ -195,7 +195,7 @@ @if (row.LastConfirmedSceneID.HasValue) { - @row.LastConfirmed + @row.LastConfirmed } else { @@ -225,7 +225,7 @@ @if (row.LastConfirmedSceneID.HasValue) { - @row.LastConfirmed + @row.LastConfirmed } else { @@ -306,7 +306,7 @@ else if (Model.Filter.DisplayMode == "Journey") { @row.ChapterDisplayName } - @row.SceneDisplayName + @row.SceneDisplayName @row.Location } @@ -346,7 +346,7 @@ else if (Model.Filter.DisplayMode == "Journey") { @row.ChapterDisplayName } - @row.SceneDisplayName + @row.SceneDisplayName @row.HolderOrLocation } @@ -398,7 +398,7 @@ else { @row.ChapterDisplayName } - @row.SceneDisplayName + @row.SceneDisplayName @if (!row.Characters.Any()) { @@ -418,7 +418,7 @@ else Last confirmed: @if (character.LastConfirmedSceneID.HasValue) { - @character.LastConfirmedSceneDisplayName + @character.LastConfirmedSceneDisplayName } else { @@ -454,7 +454,7 @@ else Last confirmed: @if (asset.LastConfirmedSceneID.HasValue) { - @asset.LastConfirmedSceneDisplayName + @asset.LastConfirmedSceneDisplayName } else { diff --git a/PlotLine/Views/FloorPlans/Edit.cshtml b/PlotLine/Views/FloorPlans/Edit.cshtml index 52e2ce18..ed43e1fc 100644 --- a/PlotLine/Views/FloorPlans/Edit.cshtml +++ b/PlotLine/Views/FloorPlans/Edit.cshtml @@ -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)); diff --git a/PlotLine/Views/Locations/Details.cshtml b/PlotLine/Views/Locations/Details.cshtml index ac344e89..d6fc9927 100644 --- a/PlotLine/Views/Locations/Details.cshtml +++ b/PlotLine/Views/Locations/Details.cshtml @@ -189,7 +189,7 @@

Scenes

@foreach (var scene in Model.Scenes) { -

@SceneLabel(scene.ChapterNumber, scene.SceneNumber) @scene.SceneTitle

+

@SceneLabel(scene.ChapterNumber, scene.SceneNumber) @scene.SceneTitle

} @if (!Model.Scenes.Any()) {

No scenes set here.

} diff --git a/PlotLine/Views/RelationshipMap/_Workspace.cshtml b/PlotLine/Views/RelationshipMap/_Workspace.cshtml index b30d5e5c..c3352060 100644 --- a/PlotLine/Views/RelationshipMap/_Workspace.cshtml +++ b/PlotLine/Views/RelationshipMap/_Workspace.cshtml @@ -63,8 +63,8 @@

-
@Model.StoryPointLabel -
+
@Model.StoryPointLabel +
diff --git a/PlotLine/Views/Shared/_ApplicationShell.cshtml b/PlotLine/Views/Shared/_ApplicationShell.cshtml index 1f1378f1..c06653f8 100644 --- a/PlotLine/Views/Shared/_ApplicationShell.cshtml +++ b/PlotLine/Views/Shared/_ApplicationShell.cshtml @@ -71,6 +71,7 @@ } } + @if(Model.Project!=null&&Model.Books.Count>0){}
@if (Model.ShowCompanionPresence) { @@ -217,4 +218,4 @@
-@if(book!=null && selectedCategory is "writer" or "book" or "story"){} +@if(book!=null && selectedCategory is "writer" or "book" or "story"){} diff --git a/PlotLine/Views/Shared/_Layout.cshtml b/PlotLine/Views/Shared/_Layout.cshtml index 35108567..f116a0e3 100644 --- a/PlotLine/Views/Shared/_Layout.cshtml +++ b/PlotLine/Views/Shared/_Layout.cshtml @@ -146,6 +146,7 @@ } +
@@ -186,6 +187,8 @@ @if (isApplication) { + + } @if (User.Identity?.IsAuthenticated == true) diff --git a/PlotLine/Views/Shared/_NarrativeFocus.cshtml b/PlotLine/Views/Shared/_NarrativeFocus.cshtml new file mode 100644 index 00000000..5f647519 --- /dev/null +++ b/PlotLine/Views/Shared/_NarrativeFocus.cshtml @@ -0,0 +1,16 @@ +@model ApplicationNavigationViewModel +@{var focus=Model.NarrativeFocus??new PlotLine.Services.NarrativeFocusState{ProjectID=Model.Project!.ProjectID};} +
+ Current Focus: @focus.Label +
+ @if(Model.Book==null){} +

Current narrative location. Saved objectives and local Scene Explorers keep their own targets.

+ + +
+ +

+ @Html.AntiForgeryToken() +
+ +
diff --git a/PlotLine/Views/StoryAssets/Details.cshtml b/PlotLine/Views/StoryAssets/Details.cshtml index 684e85ec..216fd1ab 100644 --- a/PlotLine/Views/StoryAssets/Details.cshtml +++ b/PlotLine/Views/StoryAssets/Details.cshtml @@ -135,7 +135,7 @@ @assetEvent.EventTitle @assetEvent.BookDisplayTitle / Ch @assetEvent.ChapterNumber / Scene @assetEvent.SceneNumber: @assetEvent.SceneTitle @assetEvent.FromStateName -> @assetEvent.ToStateName - Open in timeline + Open in timeline
} @@ -158,7 +158,7 @@ @custody.CustodyEventTypeName @custody.CustodianSummary @custody.BookDisplayTitle / Ch @custody.ChapterNumber / Scene @custody.SceneNumber: @custody.SceneTitle - Open in timeline + Open in timeline
} diff --git a/PlotLine/Views/StoryBible/Index.cshtml b/PlotLine/Views/StoryBible/Index.cshtml index 38c02642..b000713a 100644 --- a/PlotLine/Views/StoryBible/Index.cshtml +++ b/PlotLine/Views/StoryBible/Index.cshtml @@ -340,7 +340,7 @@ } @if (item.SceneID.HasValue) { - Open scene + Open scene } } diff --git a/PlotLine/Views/StoryCalendar/_StoryCalendarDayDetails.cshtml b/PlotLine/Views/StoryCalendar/_StoryCalendarDayDetails.cshtml index da6e6a51..d00da135 100644 --- a/PlotLine/Views/StoryCalendar/_StoryCalendarDayDetails.cshtml +++ b/PlotLine/Views/StoryCalendar/_StoryCalendarDayDetails.cshtml @@ -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 + asp-route-selectedSceneId="@scene.SceneID" asp-route-navigateFocus="true">Open in Timeline } diff --git a/PlotLine/Views/StoryPoint/Index.cshtml b/PlotLine/Views/StoryPoint/Index.cshtml index 85948177..5319b04c 100644 --- a/PlotLine/Views/StoryPoint/Index.cshtml +++ b/PlotLine/Views/StoryPoint/Index.cshtml @@ -11,7 +11,7 @@

Writing context

AT THIS POINT IN THE STORY

-

Known state through the selected scene, including events in this scene.

+

Snapshot through the selected scene, including its events. Exploring a snapshot does not change Current Focus.

- - + +
diff --git a/PlotLine/Views/Writer/_WriterAuthoring.cshtml b/PlotLine/Views/Writer/_WriterAuthoring.cshtml index d3cfd635..109ba451 100644 --- a/PlotLine/Views/Writer/_WriterAuthoring.cshtml +++ b/PlotLine/Views/Writer/_WriterAuthoring.cshtml @@ -22,7 +22,7 @@ }else{

Scenes in this chapter

@if(Model.Scenes.Count==0){

There are no scenes yet. You can work at chapter level, or add a scene in the chapter editor.

} - @foreach(var scene in Model.Scenes){
@scene.SceneTitle · @scene.RevisionStatusName
} + @foreach(var scene in Model.Scenes){
@scene.SceneTitle · @scene.RevisionStatusName
}

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.

}

Next useful action

diff --git a/PlotLine/Views/Writer/_WriterFocusForm.cshtml b/PlotLine/Views/Writer/_WriterFocusForm.cshtml index af315fb7..e4093702 100644 --- a/PlotLine/Views/Writer/_WriterFocusForm.cshtml +++ b/PlotLine/Views/Writer/_WriterFocusForm.cshtml @@ -6,10 +6,10 @@
What are you doing?

Choose your intended work. This does not start a recording.

-