Complete desktop workspaces, context menus and plot health
Commit the pending application, help and browser regression work. Pin the patched PKCS dependency for the production release.
This commit is contained in:
parent
340c5e3021
commit
e48889ac05
40
Docs/Codex/EditSceneWorkspace.md
Normal file
40
Docs/Codex/EditSceneWorkspace.md
Normal file
@ -0,0 +1,40 @@
|
||||
# Edit Scene workspace
|
||||
|
||||
Edit Scene uses one instance of the six existing SceneInspectorV2 cards and one existing editor host. The Timeline inspector retains its existing presentation. Specialist cards become full workspaces: preview limits are removed, Story adds event/dependency detail, World adds asset/custody/location detail, and existing dropdown editor commands become a visible command row. Overview remains the six-area dashboard; its cards and Open buttons enter the relevant specialist area. Scene details remain editable directly from Overview.
|
||||
|
||||
## Capability inventory
|
||||
|
||||
| Area | Existing editors and actions preserved |
|
||||
| --- | --- |
|
||||
| Overview | Scene details, synopsis, position, POV, timing, revision status, text balance |
|
||||
| Story | Purpose/outcome, metrics, thread events, dependencies |
|
||||
| People | Characters/roles/POV, attributes, suggestions, knowledge, relationships |
|
||||
| World | Locations, assets, custody command and summary records |
|
||||
| Writer | Notes, checklist, workflow, attachments and attachment links |
|
||||
| Continuity | Warning review, revalidation, existing dismissal/review actions |
|
||||
| Page commands | Scene brief, Markdown export, writing-session preparation, archive |
|
||||
|
||||
The separate Custody editor command was already a placeholder without an endpoint. It remains a placeholder; this redesign does not implement missing business functionality. Existing asset/location editors and visible custody records are retained.
|
||||
|
||||
## Shared state and shell integration
|
||||
|
||||
`data-scene-workspace` opts the Edit Scene page into the workspace behavior in `scene-inspector-v2.js`. The `sceneArea` query parameter is the selected area; absent or invalid values display Overview. Selection uses History API navigation; popstate and refresh restore the area. Each area's canvas scroll position is retained while switching in the page. Existing AJAX saves replace their usual card fragments, then reapply the current area and restore canvas scroll. The identity strip refreshes from the returned Overview fragment.
|
||||
|
||||
The browser rail declares a normal `data-pwa-context="Edit Scene"` contribution, with six buttons. The existing page-context ribbon binds to those same buttons in installed mode. The shared binding copies pressed/current/selected state, and respects a contribution's declared priority when fitting groups. There is no second PWA state implementation or PWA-only editor.
|
||||
|
||||
Opening an inspector changes the workbench's available width, not its content topology. Overview retains three columns and two rows within the desktop workbench, with independently scrolling long summary cards (horizontal canvas scrolling when necessary); specialist areas retain a single column. The existing draggable editor separator is reused, with keyboard arrow resizing added on this page. Closing removes the entire editor column. Below 900px the inspector covers the workbench, with an independent scrolling editor body; the underlying canvas keeps its geometry and scroll position. Theme tokens style all new surfaces.
|
||||
|
||||
## Verification
|
||||
|
||||
Run the normal build and executable regression harness serially. For focused browser coverage:
|
||||
|
||||
```sh
|
||||
dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj -- --toolbar-browser-host
|
||||
# In a second terminal:
|
||||
cd PlotLine.Tests/Browser
|
||||
npm run test:scene-workspace
|
||||
```
|
||||
|
||||
The suite renders the real Razor page and editor fragments in the isolated host. It tests a normal browser and a Chromium-installed PWA, history/refresh, six cards and areas, stable grid topology, width recovery/resizing, Story and Relationships AJAX workflows, validation and cancel, editor accessibility, all migrated editor modes, continuity, all six themes and responsive widths. Fixture AJAX writes are intercepted; tests do not alter a live manuscript.
|
||||
|
||||
For visual inspection only, the isolated host accepts `PD_SCENE_VISUAL_FIXTURE` pointing to a private, locally exported `SceneEditViewModel` JSON file. The host reads that snapshot and never connects to a database. Do not commit manuscript snapshots or credentials. The deterministic test suite uses its default fixture without this environment variable.
|
||||
80
Docs/PWA/Completion-Audit.md
Normal file
80
Docs/PWA/Completion-Audit.md
Normal file
@ -0,0 +1,80 @@
|
||||
# PWA ribbon completion audit
|
||||
|
||||
This extends the original page/action audit in Desktop-Experience.md. The single active ribbon, shell-owned groups, measured overflow and original handler/form ownership are retained.
|
||||
|
||||
## Composition findings
|
||||
|
||||
The old all-category route map used the last equivalent it found. Books/Create exists in both Project and Book categories; on Project Overview it could borrow the inactive Book copy even though Project already displayed Add Book. Review Centre, Overview and other shared destinations were susceptible to the same error. Composition now seeds its operation set from the active category and always prefers active-category equivalents before considering an inactive category. Repeated contextual requests are suppressed during composition, not with CSS. The redundant Add Book action beside the dashboard Books-section heading is also declared as a contribution, accounted for by the existing base command, and decluttered only in PWA mode; book cards and per-record actions remain.
|
||||
|
||||
`data-command-operation` is emitted centrally for MVC anchors/forms and base ribbon commands, using controller/action rather than captions. The composer combines it with normalized route/query scope, HTTP method and relevant hidden form fields (excluding antiforgery). Standard `/Controller/Action/id` and `?id=` representations normalize to the same scope. Book/project/format/focus/scenario/query differences remain distinct; unrelated local JavaScript buttons retain handler identity. Existing equivalent shell command nodes are reused once and restored to their home category/order.
|
||||
|
||||
## Icons and search
|
||||
|
||||
Broad “any Exports or StoryBible URL means open book” lookup was removed. Shared semantic metadata distinguishes print, Markdown, text, timeline export, research pack, general export, backup, restore, settings, validation, retry, merge and removal. Established navigation/Add Book/Archive/Warnings icons remain associated with their operations. Contextual fragment jumps also use their section meaning (attention=warning, revision=review), not a generic edit pencil. Group Export uses an export icon, and Manage Lines uses a list icon distinct from the narrative-map command. Source form/anchor and ribbon reuse share the same metadata.
|
||||
|
||||
Search is one labelled ribbon input with an integrated magnifier submit button; no second full-sized Search card is produced. Enter and the integrated affordance invoke the original form's submit button/handler, using its existing route, values and antiforgery behavior. Selector-only scope forms retain their distinct View/Apply operation. Coupled local filters and editor fields stay in their workspace.
|
||||
|
||||
## Classification
|
||||
|
||||
A = redundant PWA identity; B = existing ribbon operation; C = missing contextual command/help; D = page-wide scope/search/jump; E = actual content/workspace/editor/security controls retained. Every migrated Actions/More item continues through its original route/handler/confirmation and server/Razor permission conditions.
|
||||
|
||||
| Area / routes | Classification and decision |
|
||||
| --- | --- |
|
||||
| Projects Index, Details, Activity | A: breadcrumbs/category/title; B: Edit, Add Book, Activity, Collaborators, Backup, Restore; C: checklist/archive/help; E: trial notices, statistics, books and activity tables. |
|
||||
| Projects Edit/Create | E: meaningful New/Edit task heading, fields, validation and Save; A: redundant eyebrow; B/C: Back to projects and page Help. |
|
||||
| ProjectCollaborators Index | A: header/breadcrumb; B/C: Back; E: invite form, roles, pending invitations and per-member removal. |
|
||||
| ProjectRestorePoints Index | A: header/breadcrumb; B: backup/back; C: Help; E: named snapshot creation, limits, per-record restore/download/delete confirmations. |
|
||||
| Acceptance Phase1 | A: report identity; D: project/report scope; E: diagnostics and checklist evidence. |
|
||||
| Books Details | A: redundant identity; B: Edit/Add Chapter/Overview; C: scoped Health/archive/help; E: author description, metadata, chapters and analysis state. |
|
||||
| Books Edit/Create | E: task heading, begin mode, cover/metadata form, validation and Save; B/C: Back to project and Help. |
|
||||
| Chapters Details | E: chapter title/summary/metadata and scene list; A: breadcrumb/eyebrow; C: edit/workflow/brief/Add Scene/archive/help; E: bulk scene POV operation stays next to scene list. |
|
||||
| Chapters Edit/Create | E: task heading, chapter fields/revision/save; B/C: Back to book and Help. |
|
||||
| Scenes Edit/Create | E: scene editor identity/fields/save, inspector/local tabs and manuscript content; A: breadcrumb/eyebrow; C: briefs/Markdown/writing-session/archive/help. |
|
||||
| Scenes MovePreview | E: affected scene, before/after order, safety confirmation and submission; A: redundant eyebrow only. |
|
||||
| Timeline Index | A/B/C/D: unchanged prior complete audit; E: Filters/Focus, View, Jump, Saved Views, Drag Sources, chapters, scene cards and visual layers. Settings gets a semantic settings icon; validation gets check icons. |
|
||||
| Timeline Settings | E: meaningful settings task heading, section/metric options and Save/Back; A: breadcrumb/eyebrow. No settings form is transplanted. |
|
||||
| StoryCalendar Index/surface | A: redundant Calendar H1/eyebrow/breadcrumb; C: Help; E: story date range/counts, coupled book/month query, calendar navigation/day content. Fragment refresh remains supported. |
|
||||
| PlotLineWorkspace Index; PlotLines/PlotThreads Index | A/B/C: workspace prior audit retained; management lists newly integrated (the prior audit had listed them but their declarations were missing). E: map/filter/association/inspector behavior and row operations. |
|
||||
| PlotLines/PlotThreads Edit/Create | E: meaningful task title, full editor fields/validation/Save; A: breadcrumb/eyebrow; B/C: Cancel/back/archive/help. |
|
||||
| StoryPoint Index | A/C: prior audit; E: coupled book/chapter/scene selectors, snapshot, state feedback. |
|
||||
| Scenarios Index, Timeline, Compare, Create | List identity A and Create/Help C; sandbox safety banners and scenario identity E; navigation/validation/archive C; comparison evidence, Apply confirmation, creation form and scene moves E. |
|
||||
| ContinuityExplorer Index | A: generic page furniture; E: coupled entity/range filters and investigation surface. |
|
||||
| Writer Index | A/C/D: prior audit; E: Word/workstation controls and writing queues. |
|
||||
| Writer WritingPlans | Newly A/C: list heading, Create Schedule/Preview; E: plan cards, per-plan edit/activate/deactivate/regenerate/delete and confirmations. |
|
||||
| Writer SchedulePreview | Newly A/C: redundant heading and plan management navigation; D: writing-plan scope selector; E: selected-plan summary, rebalance controls, plan/schedule tables and item actions. |
|
||||
| Writer ScheduleSetup, EditWritingPlan | E: meaningful planning task heading and explanatory constraints, form fields, validation and submit/cancel; A: breadcrumb/eyebrow. |
|
||||
| Writer Chapter | E: chapter identity and author workflow content; A: breadcrumb/eyebrow; C: scoped Timeline/Warnings and brief formats/help; E: goals/readiness/checklists and scene links. |
|
||||
| Review Centre | Newly A/C: only redundant Review Centre heading/help and footer book/workspace navigation; E: character gate instructions, locked/enabled category tiles, saved review state and pipeline data. No review/analysis logic changes. |
|
||||
| IntelligenceReview Index | E: module identity, observation counts, review instructions, scope tabs, Assess/paging and evidence; C: Review Centre/tracked module/Book navigation, keeping paging in place. |
|
||||
| Characters Index/Details; Names Index | Prior A/B/C retained. Meaningful profile/avatar/description E; library query/pagination and character section navigation E. |
|
||||
| Characters Edit/Merge/CropAvatar | Newly task model: E entity/edit/merge/crop headings, forms, destructive acknowledgement and image tools; A breadcrumb/eyebrow; B/C page Help, back/cancel. |
|
||||
| RelationshipMap Index | A redundant map title/eyebrow, C Help; E current story-point description, coupled map filters/legend/network. |
|
||||
| Dynamics Story | Newly A/C: redundant project heading, Run Checks, Help; E diagnostics/pairings/evidence. |
|
||||
| Dynamics Character, Relationship, Knowledge | Newly E meaningful entity/relationship headings; A breadcrumb/eyebrow; C cross-navigation/focused Timeline/help where present; E histories, charts and knowledge evidence. |
|
||||
| Locations and StoryAssets Index/Details/Edit/Merge | List/detail prior audit retained. Editors/merges newly integrate Help and header navigation/archive; E entity descriptions, field validation, merge confirmations, tree/drag/dependencies/custody/local operations. |
|
||||
| FloorPlans Index/Edit | Index prior audit. Editor newly contributes Help/back; E actual floor-plan identity, floors/blocks/transitions, create/delete/drag/occupancy controls. |
|
||||
| StoryBible Index | A/C/D retained, semantic export icons and single search added; B exact existing Relationships command reused; E sections, findings, clear/export search results. |
|
||||
| ProjectMetrics Index/Edit | Index prior audit; E metric definitions/add/default controls. Edit is a task with Save/Cancel and field explanations retained, Help/identity integrated. |
|
||||
| Analytics, Warnings, Archives Index | Prior audit retained. E coupled analytical/filter ranges, validation summary and item-level dismiss/restore operations; C validation/help. |
|
||||
| Imports Index/Result | Newly C header navigation/sample/help; A generic import identity in Index; E preview/upload/schema/dry-run/confirmation, result identity and per-result counts/errors remain. |
|
||||
| Help Index | Newly A/C/D for authenticated PWA: redundant heading, page Help, one integrated global help search. Public/normal browser stays unchanged. |
|
||||
| Help Category/Article | E meaningful category/article title, authored summary/content/counts; C breadcrumb destinations become Navigation commands so category access is retained, not discarded. |
|
||||
| FeatureRequests Index/Roadmap | Newly A/C list identity and roadmap/create/navigation. E request lists/statuses and empty-state affordances. No feedback is sent by verification. |
|
||||
| FeatureRequests Details/Create | E authored request title/conversation and submission task instructions/forms; A breadcrumb/eyebrow; C Back; replies/submission/Cancel stay local. |
|
||||
| ManageAccount Index/Subscription | Newly A/C duplicate generic identity/email and Back; E actual account/security/subscription/usage/billing data and security/payment operations stay beside their explanations. |
|
||||
| ChangePassword, Enable/DisableTwoFactor, RecoveryCodes | Deliberately retain E: security task headings, credential/recovery data, confirmation and forms. No ribbon projection of passwords, tokens or recovery codes; no screenshots of secrets. |
|
||||
| Onboarding setup/import/review-edit stages | Deliberately retain E: progress, workflow stage identity, explanatory gates, field/accept/ignore controls and irreversible submission context. Review Centre and module navigation integrated above; no intelligence read/write model or analysis changed. |
|
||||
| WordCompanionHost / Writing panes | Deliberately retain E: dedicated companion/editor surfaces, cross-window presence/context/intent and manuscript/inspector interactions. These are not conventional page furniture in the main shell. |
|
||||
| Admin, diagnostics, auth/public/marketing/export output pages | Deliberately retain meaningful maintenance, diagnostic, credential, marketing or printable-document layouts. Privileged tools and standalone output are not regular author-workspace chrome. Anonymous pages have no application ribbon; declarations never suppress their content. |
|
||||
|
||||
## Final verification — 30 October 2026
|
||||
|
||||
- Normal solution build and all **374** executable regression checks pass. Publish succeeds; the existing NU1903 dependency advisory remains outside this UI pass.
|
||||
- Installed-PWA browser suite passes on **20 actual Razor views**, all six registered themes and 2560/1440/900 widths. Checks cover final composed semantic uniqueness (including Add Book), scoped route/handler identity, original node reuse, single search, Enter/integrated-button submission, keyboard focus/Escape, disabled controls, permissions, antiforgery/confirmation, partial refresh and collapsed/expanded access. Existing toolbar and sticky-shell suites also pass.
|
||||
- Live authenticated Dev smoke passes on **42 routes** in normal browser and a real installed Chromium PWA. Story Bible `beth` Enter search and integrated submission, section jumps, correct Help, Timeline scope and archive cancellation pass. Single-row layout is verified at 2560/1920/900. Theme verification sets the same app/theme/Bootstrap attributes as the application's real theme switcher.
|
||||
- Visually inspected the mandatory Project, Book, Timeline, Plot Lines, Story Bible, Calendar, Threads, At This Point, Characters, World, Metrics, Health, Warnings and Archive pages; also inspected Review Centre, project editing and scheduling fixtures. Story Bible was visually checked in all six themes. Review Centre/gated analysis coverage uses rendered fixtures rather than starting manuscript analysis. Security/recovery secrets are excluded from screenshots.
|
||||
- Header Actions/More contributions retain original handlers, form submission, permission filtering and destructive confirmation. Local row menus, editor Save/Cancel, coupled workspace filters, security controls and staged onboarding remain alongside their content as classified above.
|
||||
- Deployed **Dev only**: `340c5e3-pwa-completion-v1-worktree-20261030T145830Z`. Published/deployed DLL hashes and served contextual JS/CSS hashes match; service active, local/public TLS GET 200 and no service warnings/errors during smoke. Production is untouched.
|
||||
- Verification uses normal authentication with a dedicated temporary Dev identity and owned project/book, followed by the normal complete account-deletion workflow. No interactive login, production identity change or authentication bypass is introduced.
|
||||
|
||||
The classification table records the intentional exceptions. No outstanding contextual-ribbon blocker was found in this pass.
|
||||
59
Docs/PWA/Context-Menus.md
Normal file
59
Docs/PWA/Context-Menus.md
Normal file
@ -0,0 +1,59 @@
|
||||
# Installed desktop context menus — V2
|
||||
|
||||
## Shared command surface
|
||||
|
||||
`application-context-menu.js` uses the established `PlotDirectorPwa.standalone` state. A normal browser event returns untouched. Ctrl+right-click returns before any target processing or `preventDefault`; touch context events are not mapped to this desktop feature. Ordinary PWA right-click is owned consistently, even when there is no useful actionable menu.
|
||||
|
||||
Components declare `data-pd-context`, an object ID/label where available, and optionally a bounded command scope. The nearest component owns the target. Only that component's rendered controls are considered; nested objects are excluded. Timeline chapters restrict discovery to their immediate title region rather than scanning all scene cards. No network/database work is needed to open a menu and no global card discovery pass is performed.
|
||||
|
||||
The ribbon's shared `PlotDirectorCommands` adapter exposes its existing semantic identity, icon lookup and original-control invocation. Context menus deduplicate scoped operations and invoke the **original** anchor/button, retaining server/Razor permission decisions, live disabled state, hidden form fields, antiforgery, subscriptions, confirmations and existing handlers. They do not construct archive/delete POSTs or independently infer permissions. Controls in a form requiring field input are deliberately left to that workflow. Dynamic source removal closes the menu, and command execution rechecks that the source remains connected/enabled.
|
||||
|
||||
An object is bound when right-clicked; previous scene/map selection is never used to choose its commands. Opening a menu does not synthesize primary clicks, start drags or introduce multi-selection. Selecting an existing Inspect/Select command performs its normal selection behavior. Object menus stay bound to that object; unrelated current-page edits are not appended to an object menu. Background actions are drawn only from useful current contextual ribbon controls and current create/edit/settings commands, not the complete global ribbon. Exports, jumps and secondary actions use one submenu level. Limits keep rare/secondary operations compact; all original UI remains accessible.
|
||||
|
||||
## Editing and accessibility
|
||||
|
||||
Text/search inputs and textareas offer Cut, Copy, Paste and Select All with applicable disabled states. Clipboard access uses secure `navigator.clipboard` APIs; denied access is caught and announces the normal keyboard alternative. No credential or clipboard content is logged. Cut/paste preserve the captured range, emit cancellable `beforeinput` plus normal input/change events, respect current read-only/disabled state and maximum length, and abandon an asynchronous edit if focus/value changed. Password Cut/Copy are excluded; input types without a selection-range API keep unsupported clipboard operations disabled, with Ctrl+right-click/native keyboard editing available. Readable selected text offers Copy/Select All without adding editing clutter to unselected cards.
|
||||
|
||||
Menus use the existing theme tokens and SVG catalog (plus semantic editing icons), compact rows, destructive styling, ARIA menus/menuitems/separators, named submenu state and visible keyboard focus. Shift+F10/Context Menu key opens at the focused component; arrows/Home/End, Enter/Space, submenu Right/Left, Escape and Tab are supported. Focus returns to the originating control on dismissal/execution. Mouse and keyboard submenus flip left and clamp vertically at viewport edges. Click-away, another right-click, scroll outside the menu, context changes, resize, blur and navigation dismiss menus.
|
||||
|
||||
## Coverage inventory
|
||||
|
||||
Commands below are conditional on the original rendered UI; no missing/forbidden operation is manufactured.
|
||||
|
||||
| Context / audited area | Useful commands and semantic owners / deliberate limits |
|
||||
| --- | --- |
|
||||
| Project gallery, Overview | Project cards expose existing Open/Edit/Archive; archived project cards use their existing Restore/delete-dialog triggers. Overview background uses current Project ribbon/context commands. Counts/activity summaries are content, not new object commands. |
|
||||
| Project restore points, Activity, Collaborators | Restore-point rows reuse Download and Restore/Delete **dialog triggers**, not their modal submit buttons. Activity remains readable evidence; collaborator invitation/removal stays in its existing management UI (a right-clicked control can still invoke itself). No new sharing operation. |
|
||||
| Book cards and Overview | Book cards reuse Open/Edit/Archive. Chapter rows reuse Open/Edit/Archive. Background uses Book ribbon and page actions. Import/analysis/manuscript-link lifecycle is unchanged. |
|
||||
| Chapters / scene lists | Chapter task header reuses Edit, workflow, Add Scene, brief and Archive. Scene rows reuse Timeline/Edit, existing ordering buttons and Archive with their original IDs/confirmations. Bulk POV form remains local. |
|
||||
| Timeline | Scene cards invoke their own existing inspector/focus route. Chapter context offers its Chapter Details link; that title is also a conventional discoverable link. Scene overview inspector context invokes its existing Edit Details modal. Page menus reuse existing Settings/create/validation/navigation commands. No new move/duplicate/archive operation is manufactured on a card which did not expose it. No Plot Line lanes are reintroduced. |
|
||||
| Calendar | Day navigation keeps its normal links; selected/unplaced scene cards reuse Open Scene/Timeline. Calendar query/date controls remain local. |
|
||||
| Plot Lines narrative map | Scene callouts reuse Inspect Scene; tray scenes reuse their own selection-for-association command. Line labels reuse Edit Colour, health inspection and Add Selected Scene when available. Inspector action row reuses Open Scene/Writer. Health markers can invoke their own existing inspection control. Association and direct-drop workflows stay unchanged. |
|
||||
| Plot line / thread management | Rows reuse Edit, Focus scenes, Add Thread and Archive, as available. Thread boundaries/plot-event evidence with no existing action remain evidence; no invented event mutation. |
|
||||
| At This Point | Scene header reuses Open Scene/Timeline/Calendar, asset/thread rows reuse their editor/source-scene links. Coupled book/chapter/scene selectors remain local and never imply a previous target. |
|
||||
| Review Centre / review observations | Module tiles use their currently rendered review/view/retry controls. Locked tiles gain no review/retry capability. Observation cards reuse Review This Observation only where already offered. Decisions/reasons/gated analysis remain in their normal workflows. |
|
||||
| Scenarios | Cards reuse Open Timeline/Compare/Archive. Sandbox scene cards reuse their own Move Up/Down forms; destination selection stays local. Apply Scenario keeps its existing confirmation. No cross-over into main manuscript chronology. |
|
||||
| Continuity | Evidence rows reuse their own Timeline/source-scene route. Coupled investigation filters and analytical cards stay local; no invented continuity resolutions. |
|
||||
| Characters | Cards reuse Open/Edit/Archive; detail header reuses its existing edit/merge/reanalyse/export/archive controls and navigation. Reanalyse keeps the original running/disabled state. No analysis is launched during verification. |
|
||||
| Relationships / Dynamics | Relationship-list items reuse Select Relationship; existing Arc/Knowledge/relationship links and page commands remain available. SVG graph geometry and chart points with no separately exposed operation receive only appropriate page context. No invented graph editing or relationship mutation. |
|
||||
| World / Locations / Story Assets | Location tree rows and asset cards reuse Open/Edit/Archive. Detail headers reuse their normal navigation/merge/export/management actions. Reparenting, dependencies and custody fields remain in their own forms. |
|
||||
| Floor plans | List objects reuse Open Editor and the existing Delete dialog trigger. Canvas blocks/geometry retain existing tools; no new block mutation API. |
|
||||
| Story Bible | Character/thread/asset/location cards reuse their exact existing profile/editor/focused-Timeline links. Background reuses scoped exports and section jumps. Relationship aggregates/read-only summaries are not given speculative edit actions. |
|
||||
| Metrics / Health / Warnings | Metric rows reuse existing order/Edit/activate/remove controls where fieldless and available. Warnings reuse item navigation and supported original controls; reason/choice forms stay local. Health charts/counts are analytical content, with only existing page validation/navigation context. |
|
||||
| Archive | Archived objects expose only original Restore/Delete Forever commands, including typed permanent-delete confirmation. Active-object edit/association commands are not synthesized. |
|
||||
| Writer / schedules | Plan rows reuse existing View Schedule/Edit/activate/deactivate/regenerate/delete controls. Planning fields and coupled schedule operations remain local. The external Word manuscript workflow is unchanged; no manuscript editor is introduced. |
|
||||
| Help / imports / feedback / account / security | Existing focused controls and useful page actions; readable selection and normal editable fields get editing commands. Credentials/recovery data gain no domain shortcuts and are excluded from screenshots. No feedback is sent by verification. |
|
||||
| Empty workspace / application chrome | A small relevant current-page menu, the right-clicked control itself, or no actionable presentation. Native browser menu is still suppressed only in desktop PWA; Ctrl+right-click remains the deliberate fallback. |
|
||||
|
||||
Normal browser pages, existing visible commands, mobile long-press and Production remain unchanged. Help describes right-click and the advanced Ctrl override.
|
||||
|
||||
## Verification — 30 October 2026
|
||||
|
||||
- Solution build and Release publish pass; all **374** executable regressions pass. Existing unrelated dependency advisories are unchanged.
|
||||
- Focused installed-PWA suite passes: untouched browser/Ctrl events (including inputs/buttons), a physical right-click, Shift+F10/Context Menu key, A/B scene routing, original archive and typed permanent-delete confirmation, disabled buttons/fieldsets, archived/read-only contexts, real Cut/Copy/Paste/Select All, clipboard denial, submenu mouse/keyboard operation, all four viewport corners including scrollbar clearance, all six current themes, 1440/900 widths and dismissal/source lifecycle. Original scene click and drag attributes remain intact.
|
||||
- The **20 actual Razor view** desktop suite passes with six themes at 2560/1440/900, representative menu captures, semantic command reuse, original forms/permissions/confirmations, responsive/collapsed ribbon, fragment replacement and search. First-paint cold/navigation/reload guards continue to measure **0 px** of activation movement.
|
||||
- Authenticated live Dev verification passes on the existing **42-route** browser/installed-PWA suite, now checking native/Ctrl/menu behavior on each route. Additional owned-data checks exercise two real scene targets, chapter edit, character/location/asset/plot-line/thread routes, character detail, sandbox and relationship pages, original archive cancellation, map inspection, Association-mode scene selection and real clipboard access. No association or manuscript edit is saved by these checks. Review Centre/gated review coverage uses actual rendered fixtures; no Story Intelligence run is started.
|
||||
- Menus are composed synchronously without network/database requests. Final live samples: **30** opens, **1.56 ms mean / 2.8 ms maximum** on this host. These are observed local timings, not a universal performance guarantee.
|
||||
- Visually inspected menu treatment in all six current themes, narrow desktop, left-opening submenus, editing/read-only/disabled/destructive states and representative page contexts. The coverage table records deliberate non-actions and field-dependent workflows left in place.
|
||||
- Dev release: `340c5e3-pwa-context-v2-worktree-20261030T163622Z`. Published/deployed DLL and served menu JS/CSS/shared-adapter hashes match. Service active, local/public GET 200, no warning/error service entries during final verification.
|
||||
- The dedicated Dev identity used normal authentication. Its sample project (imported using the normal preview/acknowledgement/confirmation flow), books/scenes/entities and sandbox were removed through the normal complete account-deletion workflow; the private credential file is deleted. Production is untouched.
|
||||
78
Docs/PWA/Desktop-Experience.md
Normal file
78
Docs/PWA/Desktop-Experience.md
Normal file
@ -0,0 +1,78 @@
|
||||
# Installed desktop experience V1
|
||||
|
||||
## Audit before implementation
|
||||
|
||||
The application shell uses ApplicationRibbon's route/scope registry, _ApplicationShell and application-shell.js. Full page navigation is normal; Calendar replaces its surface using fetch/history, so contextual ownership must also refresh on fragment replacement. application-pwa.js already detects standalone display mode and navigator.standalone, but sticky offsets used only the former. The theme registry currently contains six themes.
|
||||
|
||||
| Page | Identity and command inventory | Reconciliation / workspace retained |
|
||||
| --- | --- | --- |
|
||||
| Projects/Details | Breadcrumb, Series Dashboard, title/description, help; Edit, Add book; Actions: Activity, Collaborators, ProjectBackup, Restore Points, Acceptance/Phase1, Archive POST | Reuse existing Project routes with exact scope; add Checklist and Archive via original controls, owner conditions and confirmation intact. Statistics and book cards remain. |
|
||||
| Books/Details | Breadcrumb, project/title/subtitle/tagline/description, help; Edit, Add chapter; Actions: Analytics with bookId, Archive POST | Reuse Book Edit/Create routes; Analytics book scope is distinct from project health. Preserve metadata/descriptions as substantive book content. |
|
||||
| Timeline/Index | Breadcrumb, Story timeline, project H1/help, Book filter GET/View; ValidateProject and conditional ValidateBook POST; Warnings and Analytics with bookId, Settings, Scenarios/Create with bookId, Archives | Book selector and all page commands contributed. Filter/focus, View, Jump, Saved Views, Drag Sources, scene/chapter operations remain. |
|
||||
| PlotLineWorkspace/Index | Breadcrumb, Story map/mode, H1/help, description; PlotLines/Index, PlotThreads/Index | Thread route reuses Story ribbon; Manage lines is distinct from the PlotLineWorkspace route. Entire filter panel, map and association workflow retained. |
|
||||
| StoryBible/Index | Breadcrumb, Reference, H1/help, GET search q; Exports/StoryBible (three formats), NarrativeTimeline, ResearchPack, RelationshipMap; eight fragment jumps | Context Search, Export and Jump groups. First content is Characters, or search results when searching. |
|
||||
| Characters/Index | Breadcrumb, category/project H1/help; Characters/Create | Context Create and Help; character cards/row operations remain. |
|
||||
| Characters/Details | Identity/avatar/description/help; Back to characters/timeline with focus; Actions Edit, Merge, Reanalyse POST (disabled while active), Character exports (two formats), Archive POST; section navigation | Keep meaningful profile header/avatar/description. Contribute action row and page help. Section tabs and analysis content stay local. |
|
||||
| Names/Index | Breadcrumb, category/H1/description/help | Context Help; search/locale/era/gender and pagination are a coupled library query workspace and stay. |
|
||||
| Locations/Index | Breadcrumb, category/project H1/help; Create | Context Create/Help; drag mode, tree/reparent/relationships remain. |
|
||||
| Locations/Details | Breadcrumb, entity/title/path/help; All locations; Tools Edit, Merge, Archive POST | Keep path/identity, contribute actions/help. Local names, relationships and forms remain. |
|
||||
| StoryAssets/Index and Details | List identity/help/Create; detail avatar/description/help; Tools Edit, Merge, Archive POST | List header consolidated; detail identity retained, actions/help contributed. Dependencies/custody/event forms remain. |
|
||||
| FloorPlans/Index | Breadcrumb, category/project H1/help | Context Help. Create form, plans and per-plan Delete modals remain. Editor heading and canvas controls stay. |
|
||||
| RelationshipMap/Index | Breadcrumb, Relationships, H1/help; story-point description | Context Help; retain current story-point status and all coupled map filters/legend/canvas. |
|
||||
| StoryCalendar/Index and surface | Breadcrumb, Story time/H1/help, story range, dated/unplaced counts | Context Help, retain range/counts; coupled month/book/date navigation remains beside calendar. Refresh context on surface replacement. |
|
||||
| Scenarios/Index | Breadcrumb, Planning sandbox, H1/description/help, Create | Context Create/Help; scenario cards and their operations stay. Timeline/Compare retain scenario identity and canvas controls. |
|
||||
| ContinuityExplorer/Index | Breadcrumb, category/H1/description; no page help | Consolidate identity only; entity/multi-select filters and investigation remain. |
|
||||
| ProjectMetrics/Index | Breadcrumb, settings/H1/description/help | Context Help; metric creation/default installation and per-metric edit forms remain substantive content. |
|
||||
| Analytics/Index | Breadcrumb, Analytics/project H1/help | Context Help; coupled book/chapter/scene range query remains with charts. |
|
||||
| Warnings/Index | Breadcrumb, category/project H1/help; ValidateProject / conditional ValidateBook POST | Context validation and Help; filters, last-validation summary and item operations remain. |
|
||||
| Archives/Index | Breadcrumb, Archive/H1/description/help | Context Help; project/entity filtering and per-record restore remain. |
|
||||
| Projects/Index and Activity | List title/help, Import, New project; activity breadcrumb/title/back link | Reuse Import route; contribute New project/Help or Back. Trial/onboarding/status content remains. |
|
||||
| Writer/Index | Today/title/description/help; WritingPlans, ScheduleSetup, SchedulePreview, project GET/Focus | Context commands and project scope; actual writing workstation and queue controls remain. |
|
||||
| Editors, merge/confirmation pages, onboarding, settings, account, import/review child flows | Task identity, explanatory instructions, validation, Save/Cancel/destructive operations | Deliberately retain meaningful task headings/forms; no blanket H1/breadcrumb suppression. These are workflows, not redundant dashboard furniture. |
|
||||
|
||||
## Contribution contract
|
||||
|
||||
Audited views declare `data-pwa-header` for redundant identity plus its page commands, `data-pwa-context="Group"` for additional command regions, and `data-pwa-identity` for redundant breadcrumbs. `data-pwa-help` contributes only a meaningful header's page Help without suppressing its content. `data-pwa-priority` orders contributions (lower numbers first); `data-pwa-context-status` contributes compact live status. Form checkboxes retain toggle behavior, short selectors use native compact selects, and long selectors use searchable keyboard-operable popovers. Only declarations are considered; headings are never globally hidden.
|
||||
|
||||
The shared shell owns contextual rendering within the layout's explicit `data-pwa-page-content` boundary. The source remains the canonical command owner: contextual controls bind to existing rendered page sources without relocating page DOM, copying event handlers, copying IDs, reproducing permission checks or changing routes. POST actions invoke the original submit button, preserving antiforgery and application confirmation handlers. Select/search bindings synchronise the original form, then invoke its existing submit path. Exact route/query identity, not captions, resolves existing ribbon equivalents; differing book/format/focus scope is retained. An equivalent already in the active category remains there. An equivalent in another category is reused as the exact same shell-owned command node in the contextual group, with a marker restoring its original category/order on tab or mode changes. No duplicate command or generic category-link substitute is created.
|
||||
|
||||
A contribution is suppressed only after its supported controls have been accounted for. Unsupported control types leave their entire region visible. Changes to disabled/hidden state and replaced contributions refresh the projection. Context can be explicitly refreshed through `plotdirector:context-changed`. Context controls share the existing ribbon surface and collapse/expand control; selecting any ribbon tab reopens it as before. The contribution host and controls use display:contents inside the active panel: they create no toolbar/title box, row or additional ribbon height. Context groups use the existing pd-ribbon-group / pd-ribbon-command / pd-ribbon-group-label styles. Compact icon-led selectors and Find forms remain in scope groups. A measured width budget exposes groups directly when they fit; lower-priority context groups, and then lower-priority shell navigation groups, use native keyboard-operable menus only when required. Archive/delete commands retain a compact Manage menu. The ribbon remains one 84px panel; there is no contextual title. Fixed-position menus escape the horizontal panel clipping and stay inside the viewport. No domain or authentication behavior is changed.
|
||||
|
||||
## Unattended verification
|
||||
|
||||
Use the existing `--toolbar-browser-host` executable test mode, bound only to 127.0.0.1:5238. Its authenticated Fixture identity and memory repositories never connect to a database, run application background workers or ship an authentication endpoint with the web application. Browser tests use actual compiled Razor views and shared production assets. This is the preferred existing automated authentication mechanism; no credentials or user login are needed. Live Dev smoke checks additionally use a dedicated Dev identity through normal account registration, verification and login, if needed; no production identity or authentication configuration is changed.
|
||||
|
||||
Additional child-page audit: At This Point uses a redundant identity/help heading followed by coupled book/chapter/scene selectors; consolidate only the heading, retaining the snapshot selector chain and feedback. Collaborators has a heading/back link followed by its invitation form and per-person access operations; consolidate only the header. Restore Points has heading/help/back/backup links (existing Project ribbon equivalents), with manual-snapshot creation and restore/delete records retained as content. Scenario Timeline and Compare have a meaningful safety banner distinguishing sandbox from main; retain that banner and instructions, contribute their navigation/validation/archive action row and page Help, and leave Apply Scenario confirmation beside the comparison evidence.
|
||||
|
||||
## Initial delivery — 30 October 2026 (visual host superseded below)
|
||||
|
||||
- Development release: `340c5e3-pwa-desktop-v1-worktree-20261030T055803Z`; no Production deployment or schema changes.
|
||||
- `dotnet build PlotLine.slnx` succeeds. All 373 executable regression checks pass. Existing package vulnerability advisories for System.Security.Cryptography.Pkcs and pre-existing nullable warnings remain outside this presentation task.
|
||||
- Actual installed Chromium PWA vs ordinary browser: ten compiled Razor page fixtures, all six registry themes at 1440/1024/900 pixels. Existing toolbar, sticky chrome, narrative map, association/auto-scroll/hover, Timeline retirement and Health browser suites pass.
|
||||
- Behavioral checks include exact scoped-route reuse, owner-only commands, original POST/antiforgery/confirmation paths, cancellation, live disabled state, ordinary and searchable scope selectors, search submission, jump focus, correct page Help, collapsed/expanded navigation and fragment replacement. Meaningful profile/scenario content remains visible while nested command contributions are consolidated.
|
||||
- The test host now mirrors the real layout boundary: `data-pwa-page-content`. Live smoke testing caught and corrected the original fixture/main-wrapper mismatch before final delivery.
|
||||
- Live authenticated Dev smoke: 19 routes in ordinary browser and a real installed PWA, plus deployed Story Bible search/jump/Help drawer, Timeline scope, archive cancellation and six theme screenshots. The dedicated Dev account used normal login with antiforgery; no human interaction was required.
|
||||
- Temporary account, its owned fixture project/book and private credential file were removed through the application's complete authenticated account-deletion workflow. No permanent test identity, production authentication change, universal login or credential in source/artifacts was introduced. The test executable retains the guarded provisioning/cleanup command for repeatable future Dev verification.
|
||||
- Service active; local and public TLS GETs return 200; published/deployed DLL SHA-256 and changed asset hashes match; no service warnings/errors during the final smoke test.
|
||||
|
||||
## Single-ribbon correction
|
||||
|
||||
The contextual host is now a non-layout container inside the existing active ribbon panel. Context groups follow the original groups horizontally, with the same icons, command typography, hover states, separators and footer captions. No contextual page title, toolbar strip, second panel or extra row is rendered. Timeline declares scope, tools and management group labels; Story Bible contributes Find, Export, Jump to and Help groups. `data-pwa-tools` and `data-pwa-scope` label header contributions, while `data-pwa-group` assigns an audited command to a specific group.
|
||||
|
||||
Width is measured against the active panel, not guessed from a breakpoint. Groups are shown directly when they fit. Low-frequency context groups collapse first; lower-priority existing navigation groups can also collapse in PWA mode to keep every command reachable within one row at narrow desktop widths. Re-expansion uses released space, and fixed-position menus stay inside the viewport. Browser groups are restored to their original structure on leaving standalone mode. Native ribbon collapse, tab keyboard handling, page fragment updates, original route/handler ownership and permissions remain intact.
|
||||
|
||||
Equivalent commands from another category reuse the original shell command node, restored with an ownership marker on category/mode changes. This replaces generic category-link substitutes while ensuring only one instance of each command exists. Page DOM is not moved.
|
||||
|
||||
Correction verification: release `340c5e3-pwa-ribbon-v1-worktree-20261030T063525Z` deployed to Dev only. Build and all 373 regressions pass; the installed-PWA fixture suite verifies one 84px ribbon across ten pages and six themes at 2560/1440/900, direct wide groups, measured overflow, unclipped keyboard-operable menus, original-node command reuse, destructive management treatment and all prior form/navigation behavior. Existing toolbar and sticky-shell suites also pass. Live authenticated browser/PWA smoke passes on 19 Dev routes, with visual captures of Timeline, Plot Lines, Story Bible, Project and Book at wide/narrow widths (2560/1920/900), six themes, no title strip and no second row. Normal browser layout is retained. Published/deployed DLL and served contextual-script hashes match; service active, HTTPS GET 200 and no warning/error entries during verification. Temporary Dev identity and its owned fixtures are removed after smoke testing. Production is untouched.
|
||||
|
||||
## Application-wide completion
|
||||
|
||||
See [Completion-Audit.md](Completion-Audit.md) for the full page classification, active-command deduplication, shared semantic icon metadata, integrated search, newly integrated child pages, deliberate workspace/security exceptions and final Dev verification.
|
||||
|
||||
## First-paint lifecycle
|
||||
|
||||
See [First-Paint.md](First-Paint.md) for pre-paint standalone state, declarative snapshot activation, original source binding, timing and cold/navigation/reload verification. This supersedes deferred initial mode detection and full-main discovery for initial presentation.
|
||||
|
||||
## Desktop context menus — V2
|
||||
|
||||
See [Context-Menus.md](Context-Menus.md) for the reusable original-command surface, object/page coverage inventory, native browser/Ctrl behavior, text editing, keyboard access and verification. This complements the existing ribbon and first-paint lifecycle.
|
||||
35
Docs/PWA/DesktopPromotion.md
Normal file
35
Docs/PWA/DesktopPromotion.md
Normal file
@ -0,0 +1,35 @@
|
||||
# Desktop promotion
|
||||
|
||||
Browser-only enhancement in `desktop-promotion.js`, using the existing parser-blocking `PlotDirectorPwa.standalone` state and `application-pwa.js` captured install prompt. No new database schema, analytics service or right-click/ribbon changes.
|
||||
|
||||
Eligibility uses the navigation service's already-authorised project and non-archived books, on Timeline, Plot Lines, Story Bible or another substantive workspace. A short delay avoids interrupting initial rendering; visible dialogs, a hidden tab or active Story Intelligence progress suppress automatic opening on that navigation. The manual account-menu entry works without automatic eligibility.
|
||||
|
||||
State is account-scoped in device/browser localStorage (`plotdirector.desktop.v1.<userId>`): first presentation, dismissal, manual reopen, reminder and installation detection. First automatic presentation is recorded before opening, preventing repeats even if navigation interrupts it. After 30 days from the latest presentation/dismissal/reminder, only a smaller reminder appears. Its timestamp is persisted immediately. Storage errors disable automatic promotion; manual access remains available. Browser storage clearing resets this state.
|
||||
|
||||
Standalone overrides everything and does not create the overlay or request screenshots. A detected installation also suppresses future automatic promotions locally. Browsers cannot reliably detect all installed copies from a tab: the manifest does not declare a related installed app, and `getInstalledRelatedApps` cannot supply a portable universal signal. We use actual standalone state and `appinstalled`; a prompt's accepted outcome alone never displays success. Local installed suppression may outlive an uninstall; manual access remains available in a browser tab.
|
||||
|
||||
Chrome and Edge desktop are the established install-help paths. Official browser documentation was checked for those menus and Safari's macOS Sonoma+ Add to Dock flow; iOS/Android receive manual guidance. Other browsers receive current Chrome/Edge guidance without a one-click promise. No additional browser support contract is introduced. Private browsing and organisation policy can prevent installation.
|
||||
|
||||
The two supplied PNG files are preserved byte-for-byte. Their widths match (1710); the one-pixel source height difference (919 vs 920) is normalised to the same 1710:920 frame. Both images always have identical geometry. They are only fetched when the comparison is opened. Narrow screens retain a larger scrollable comparison plus a full-width accessible slider rather than tiny UI text.
|
||||
|
||||
The native HTML dialog supplies modal semantics and inert background, with explicit boundary Tab cycling, Escape dismissal and focus restoration. Reduced motion disables the single first-presentation hint. Palette tokens support all six themes. No first-Desktop-launch welcome was added: the requested comparison and install flow remain the scope. No new analytics/admin persistence was introduced for device-local promotion state.
|
||||
|
||||
## Verification — 30 October 2026
|
||||
|
||||
Dev release: `340c5e3-desktop-promotion-worktree-20261030T212452Z` (existing worktree preserved). Published/deployed DLL SHA-256: `5a58fce18c75cc6dc011cab2b003a49a857e08e4895c2c07a67c2aaed9d248b9`. Release archive includes the source patch and untracked files; timestamped prior-directory backup retained. Production untouched.
|
||||
|
||||
- `dotnet build PlotLine.slnx`: passed (existing dependency vulnerability/nullable warnings remain).
|
||||
- Executable regression harness: passed.
|
||||
- Focused `desktop-promotion.cjs` and existing `application-pwa.cjs`: passed.
|
||||
- Authenticated public Dev Chromium checks: passed; all six theme previews inspected, 1440×1100 and 390×844; sticky Install/Continue actions remain within the viewport. Genuine supplied screenshots decoded, mouse/keyboard divider, persisted dismissal, manual account-menu reopen and Help verified.
|
||||
- Real Chromium CDP app install/standalone launch/uninstall: passed. No promotion or install entry in installed mode. Parser-paused first paint checks report zero workspace shift for cold launch, navigation, reload and browser stale-state cases.
|
||||
- Native prompt mechanism tested with controlled browser events in the isolated fixture. Non-promptable fallback exercised deterministically in Dev; real installation completion verified through Chromium CDP. Automated tests cannot confirm the user's operating-system installation consent UI across Edge/Safari/mobile. Those platforms receive documented manual guidance when no captured prompt exists.
|
||||
- Service active, local/public GET 200, published/deployed hashes match. Preflight verified Development database and no active/queued background runs before deployment. Isolated Dev identity uses normal account/project/book workflows and is removed through the established cleanup command.
|
||||
|
||||
Private operational logs and publish output live under `/var/tmp/pd-desktop-promotion-work`; theme previews under `/tmp/pd-desktop-promotion-*.png`. No credential files are committed.
|
||||
|
||||
## Divider scroll correction — 30 October 2026
|
||||
|
||||
Pointer dragging now focuses the keyboard range with `preventScroll: true` and prevents the pointer's default focus handling. Previously that range, below the screenshot, scrolled into view and moved the dialog 227 pixels in a 1440×900 reproduction. Focus and keyboard adjustment are preserved. Both isolated and authenticated Dev regression checks assert unchanged dialog scroll position after dragging. Both passed; installed-app first-paint checks still measured zero shift.
|
||||
|
||||
Deployed only the static JavaScript atomically to Dev without a service restart; previous script retained at `/var/tmp/pd-desktop-divider-fix/previous.js`. Source, deployed and HTTPS-served script SHA-256 match: `9a90902d27fba4bd1e979b21042f69405df9b20bade2b4371b8edf0c7cfddcdf`. No application DLL or Production changes. Verification log: `/var/tmp/pd-desktop-divider-fix/browser.log`. Dedicated test identity and fixture project/book removed through the established cleanup workflow.
|
||||
25
Docs/PWA/First-Paint.md
Normal file
25
Docs/PWA/First-Paint.md
Normal file
@ -0,0 +1,25 @@
|
||||
# PWA first paint and contextual ribbon activation
|
||||
|
||||
## Cause
|
||||
|
||||
Previously `_Layout` loaded both `application-pwa.js` and `application-page-context.js` with `defer`. The first established `data-standalone` only after HTML parsing. The second discovered declared regions by querying the completed main subtree, built their controls and only then marked browser furniture as accounted for. Until both ran, PWA CSS could not suppress that furniture. Content volume increased parser time and full-subtree discovery/observation work before this transition. There was no persistent display-mode state. Each full navigation repeated this lifecycle; individual page declarations were not themselves performing standalone detection.
|
||||
|
||||
## Corrected lifecycle
|
||||
|
||||
- `application-display-mode.js` is a small parser-blocking head bootstrap with no body/layout dependency. It seeds the shared shell state from window-scoped `sessionStorage` (`plotdirector.displayMode`) and immediately verifies it synchronously using `display-mode: standalone` / iOS `navigator.standalone`, before body paint. Authoritative detection always wins, even when storage is denied or a browser tab inherits a stale standalone hint. Media changes and `pageshow` revalidate; unchanged state does not reconstruct the ribbon. There is no unknown-mode content guard, spinner, animation or delay.
|
||||
- Razor already renders a view before its layout. `RibbonContributionTagHelper` records only explicitly declared contribution/identity regions during that render. The layout emits their inert snapshot immediately after the application header, and preloads/runs the existing composer there, before the workspace. No second command framework, database mode, auth cookie or second ribbon is introduced.
|
||||
- The same validation/composition logic prepares the snapshot's commands, semantic deduplication, icons, responsive sizing and exact CSS selectors for furniture positively accounted for. Those selectors are PWA-only and exist before the real workspace nodes are parsed. Unsupported forms and meaningful task content stay visible; browser mode never hides its headers while waiting for a reveal pass.
|
||||
- Actual contribution regions register themselves as they parse. At the end of main, the composer binds to these small source regions, retains original routes/forms/handlers/confirmations and removes the inert snapshot/temporary selector rules. It does not need to traverse manuscript/card content to discover initial commands. Early interactions resolve to the actual registered source when available. Existing explicit context events and mutation handling remain for partial replacement, with the existing fallback discovery for newly inserted regions.
|
||||
- Timing entries `pd-ribbon-initial-compose` and `pd-ribbon-activate` expose shell composition and binding time to browser tooling. No telemetry or user data is emitted.
|
||||
|
||||
## Verification
|
||||
|
||||
The focused first-paint browser check pauses the parser after real Story Bible content plus 2,500 additional fixture cards, before main activation, deferred scripts and DOM-ready. It samples and screenshots that otherwise exposed intermediate paint, checks hidden browser identity/actions and an already composed visible ribbon/search, then releases parsing and compares command identity/order and workspace position. Scenarios cover cleared session state, subsequent PWA navigation, real reload, a stale standalone hint in a normal browser and browser reload. Separate display-mode checks cover denied storage, media changes and unchanged `pageshow` restoration. The existing 20-view/six-theme/responsive/form/permission/collapse suite remains the regression guard.
|
||||
|
||||
Final results (30 October 2026):
|
||||
|
||||
- Solution build, Release publish and all **374** executable regressions pass. Existing package advisories remain unchanged.
|
||||
- Focused display-mode checks pass. Parser-paused checks pass in both the isolated Razor host and the real authenticated Dev layout. Live initial PWA composition measured **17.7–32 ms**; cold, navigation and reload each measured **0 px** of workspace movement across activation. Normal browser cold loads, stale-hint correction, navigation and reload retain conventional headers/actions with no reverse flash. These are targeted shell-transition measurements, not a claim of zero cumulative layout shift from every asynchronous workspace/image operation.
|
||||
- Existing **20-view**, all-six-theme, 2560/1440/900 installed-PWA suite passes, including search, semantic deduplication, fragments, keyboard, forms, permissions, confirmations and collapse. Toolbar and sticky-shell suites pass.
|
||||
- Live normal-browser/installed-PWA smoke passes on **42 Dev routes**, with 2560/1920/900 layout and all-six-theme checks. Inspected the actual parser-paused PWA/browser captures; the PWA ribbon is already visible while the document is still loading.
|
||||
- Dev release: `340c5e3-pwa-firstpaint-v1-worktree-20261030T152631Z`. Published/deployed DLL hash matches. Temporary verification identity and owned project/book are removed with the normal account-deletion workflow. Production remains untouched.
|
||||
90
Docs/PWA/RecordWorkspaceLayouts.md
Normal file
90
Docs/PWA/RecordWorkspaceLayouts.md
Normal file
@ -0,0 +1,90 @@
|
||||
# Desktop record workspace layout audit
|
||||
|
||||
## Contract and implementation
|
||||
|
||||
This pass uses the existing parser-blocking `html[data-standalone]` state, explicit per-view `DesktopLayout` declarations, and static CSS in `record-workspace.css`. No form elements move after paint. Browser retains existing widths, Bootstrap columns, fields and actions. Additional Desktop group labels are hidden in Browser. Shared models, routes, permission checks, validation and handlers are unchanged.
|
||||
|
||||
Desktop has several deliberate compositions: compact task canvases (76rem maximum, aligned to the working edge, controls capped), broad grouped forms (106rem working panel within the 110rem canvas), existing main/secondary details grids, and wide management tables. Ultra-wide expansion is bounded. Grid changes start at 1000px; existing responsive Bootstrap rows handle medium/narrow widths. Long text stays wide; names/selectors/dates/numbers have independent sensible maximum widths. Character and asset descriptions use eight columns beside four-column image editors. Desktop task headings are compact rather than website-sized, and the existing 2:3 book-cover thumbnail dimensions are reserved before image load. Layout and DOM order match; CSS does not use `order`, dense placement or delayed columnisation.
|
||||
|
||||
Save/Create actions on audited main domain forms and writing-plan forms use an explicit `Record` contribution to the existing contextual ribbon. That system captures contributions in Razor, composes before content paint, binds to the original button, and hides the page duplicate only after accounting for it. Added save/close icons extend the established icon catalogue. No new submission or dirty-state system: ordinary MVC forms retain their existing validation/disabled semantics; specialised scene editors keep their own dirty-state behaviour. Archive/Delete confirmations remain with their original owners, without additional promotion. Security, subscription and irreversible actions stay on their page.
|
||||
|
||||
## Inventory
|
||||
|
||||
Classes: A compact form; B grouped two-column/multi-field form; C main + secondary content; D sectioned wide workspace; E existing composition appropriate. “Browser same” means layout changes are exclusively gated by early standalone CSS; shared action wrappers preserve the original spacing and submit controls.
|
||||
|
||||
| Pages / routes | Existing composition and excess width | Desktop choice / change | Record actions | Browser |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Projects Create/Edit | Few fields; 980px panel inside centred shell | A; working-edge compact canvas, bounded name, wide description | Save in ribbon; existing Back retained through header | Same |
|
||||
| Books Create/Edit | Many metadata/date fields, cover and description constrained to 980px | D; identity/cover, publishing/context and dates; same-row dates, broad descriptions, bounded short fields | Save in ribbon | Same |
|
||||
| Chapters Create/Edit | Existing quarter-width fields, 980px cap; short title slot | B; number/title 3:9, revision/purpose/POV trio, full summary | Save in ribbon | Same |
|
||||
| Characters Create/Edit | Profile, aliases, image all vertically constrained | C/D; names pair; profile groups; story use; description beside image | Save/Cancel in ribbon; alias and crop actions stay local | Same |
|
||||
| Locations Create/Edit | Type and hierarchy stacked, Companion matching nested card | B/D; name/aliases, type/parent paired; description broad; existing matching rules intact | Save/Cancel in ribbon | Same |
|
||||
| Story Assets Create/Edit | State fields and image in 980px panel | C/D; names, state/location groups, description beside image | Save/Cancel in ribbon | Same |
|
||||
| Plot Lines Create/Edit | Existing scope/parent/emergence fields constrained | D; explicit identity, connections, ordering and long description | Save in ribbon; existing Archive flow unchanged | Same |
|
||||
| Plot Threads Create/Edit | Parent/title, type/status, summary, scene references constrained | D; explicit identity and introduction/resolution groups; broad summary | Save in ribbon; original archive confirmation | Same |
|
||||
| Project Metrics Edit | Small settings record, numeric row | A/B; bounded name and numeric controls; existing min/max/default/order row remains coherent | Save/Cancel in ribbon | Same |
|
||||
| Scenarios Create | Three-field task, otherwise broad website section | A; compact deliberate task canvas; broad notes | Create/Cancel in ribbon | Same |
|
||||
| Writer ScheduleSetup/EditWritingPlan | Existing paired fields and availability table inside nested cards | D; broad form with existing pairs/table; bounded selectors; no new boxes | Existing Create/Save/Cancel footer contribution | Same |
|
||||
| Timeline Settings | Existing section toggles and metrics grid | D; broader canvas; keep current grouped settings and Save semantics | No new move; settings controls remain local | Same |
|
||||
| Project Details | Books, overview/activity and attention cards already grouped | D/E; broader bounded record canvas; retain meaningful card composition | Existing contextual actions | Same |
|
||||
| Book Details | Metadata multi-column row, chapters table | D; broader bounded canvas; retain metadata grouping and chapters table | Existing actions; manuscript unlink safety unchanged | Same |
|
||||
| Chapter Details | Suggestions and scene table | D; broader canvas, preserve scene commands | Existing actions | Same |
|
||||
| Character Details | Existing profile/analysis main-secondary grid; related names/images/relationships | C/E; broad canvas, responsive one-column grid in narrow Desktop window | Existing contextual operations | Same |
|
||||
| Story Asset Details | Existing state/dependencies and event/custody groups | C/E; broad canvas; preserve actual associations | Existing contextual operations | Same |
|
||||
| Location Details | Summary already uncapped by location-page rules; related tables | D; retain the uncapped summary in a broader bounded details canvas | Existing relationship form stays local | Same |
|
||||
| Characters/Locations/Assets Index | Record lists, drag/relationship panels | D/E; broader management canvas; no new columns/data | Existing commands and drag handlers | Same |
|
||||
| Plot Lines/Threads Index | List tables | D; broader canvas for lists | Existing commands | Same |
|
||||
| Scenarios Index | Record table | D; broader management canvas | Existing sandbox actions | Same |
|
||||
| Project Metrics Index | Metric table and compact creation form | D; wider table canvas; inline create form remains task-sized | Existing inline actions | Same |
|
||||
| Collaborators | Compact invite form plus access/invitation tables | D; wide tables, invite stays compact deliberately | No move; permissions and role changes local | Same |
|
||||
| Restore Points / Project Activity | Management/history tables | D; broad bounded canvas | Existing confirmations/download/restore actions | Same |
|
||||
| Archives / Warnings | Management tables and filters | D; broader canvas; row controls retain associations | Existing contextual and row actions | Same |
|
||||
| Dynamics Character/Relationship/Knowledge | Analysis/history tables and charts | D/E; broader bounded details canvas; chart data/logic untouched | Existing controls | Same |
|
||||
| Manage Account | Security, subscription, dangerous closure panels in vertical stack | D; security/subscription side by side at wide widths; danger full row | Security/destructive controls remain local | Same |
|
||||
| Account password / 2FA / recovery | Short security tasks, codes and confirmations | A/E; compact task canvas; no width inflation | No promotion of security actions | Same |
|
||||
| Feature Requests Create/Details | Short suggestion/reply task; paragraph content | A; compact canvas preserves prose readability | Submit/reply stay local | Same |
|
||||
| Feature Requests Index | Filters/list | D; broader management canvas | Existing actions | Same |
|
||||
| Character/Location/Asset Merge | Small but consequential identity decision | A/E; compact deliberate canvas; retain selection/help | No move; original confirmations retained | Same |
|
||||
| Floor Plans Index | Compact creation task plus plans table | D; broader management canvas; creation stays compact | Local creation/delete controls retained | Same |
|
||||
| Floor Plans Edit | Bespoke drawing canvas, selected-block/background/transition panels | E; existing wide dedicated editor already appropriate | No changes | Same |
|
||||
| Scene Edit and inspector editors | Recently implemented workspace areas and focused editor with resize control | E; existing sectioned working surface already appropriate; no arbitrary grid over specialised editors | Existing Save/dirty/area navigation retained | Same |
|
||||
| Timeline / Plot Line workspace / Calendar / Story Point | Existing large working surfaces and docked inspectors | E; no form-layout redesign | Existing ribbon/right-click behaviour | Same |
|
||||
| Relationship Map | Dedicated visual graph, selectors and side panels | E; graph already uses a working surface, no forced form columns | Existing controls | Same |
|
||||
| Names | Wide search/library panels and appropriate filters | E; explicit library width already uncapped | Existing filter/add actions | Same |
|
||||
| Writer Index/Chapter / Writing Context/Intent | Purpose-built writing queues/editor/context panes | E; avoid imposing generic record CSS | Existing actions/dirty handling | Same |
|
||||
| Story Bible / Continuity Explorer / Analytics | Dedicated grouped workspaces | E; no indiscriminate container override | Existing context/filter commands | Same |
|
||||
| Import and Story Intelligence review pages | Staged tasks, category grids, review-specific panels | E; no changes to operational/review workflows or resizing rules | Existing scoped actions | Same |
|
||||
| Admin | Dashboard summary grid, subscription/feature-request tables, diagnostic tools | E; admin feature-request pages already explicitly uncap edit panels; other diagnostics intentionally task-scoped | No new admin functionality or action moves | Same |
|
||||
| Help / HelpDiagnostics / Acceptance | Reading/reference and diagnostic screens | E; reading width intentional; no record editing gap | No changes | Same |
|
||||
| Public/Account sign-in/Pricing / Word Companion host | Public or external-host experiences | E / out of Desktop record scope | No changes | Same |
|
||||
|
||||
## Modal and association audit
|
||||
|
||||
Existing association forms in Scenes' focused editors, Locations relationships, Assets dependencies, Character relationships/gallery, Continuity filters and Timeline scene operations remain with their owners. They use appropriate task-specific dimensions. Tiny confirmations (archive/delete/account closure/plan deletion) retain their existing size. No global modal-width rule is introduced. Inline alias Add/Remove and character custom-sex enablement retain the same elements and handlers.
|
||||
|
||||
## Verification
|
||||
|
||||
The complete replacement attachment is the authoritative source. Its sections 44–50 add representative width/domain/automated/Dev verification and completion-report requirements.
|
||||
|
||||
Completed 31 October 2026. Dev release: `340c5e3-record-workspaces-worktree-20261031T085959Z`. Published and deployed DLL SHA-256: `18933b17d01672e1c81c28cdbd97d7ca24d5be9cabfeea51e36499814bddfbbf`. Source and deployed record CSS SHA-256: `db25630441524a8f8bec738961b52b83c39702267120bcda77d767168953d0cf`. The release archive and timestamped prior-directory backup are retained. Existing dirty-worktree changes were preserved. No migrations or business-model changes were needed. Production was untouched.
|
||||
|
||||
| Gate | Result |
|
||||
| --- | --- |
|
||||
| `dotnet build PlotLine.slnx` | Passed, zero errors; existing dependency-vulnerability and nullable warnings remain |
|
||||
| `dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj` | Full executable regression harness passed |
|
||||
| `record-workspaces.cjs` with isolated compiled-Razor host | Nine forms passed Browser widths/actions, Desktop grid/Save icon/single action, existing jQuery validation, original multipart form POST/IDs/antiforgery, Enter submission, 1920/1440/800/390 responsive checks, 3200px upper-bound check, all six theme states, parser-paused layout stability |
|
||||
| Browser resize baseline comparison | Character form geometry identical with and without the Desktop stylesheet at 1440/800/390; no Desktop grid leaks |
|
||||
| `record-workspaces-dev.cjs` | Passed against authenticated public Dev in normal Chromium and an actual CDP-installed/launched standalone app |
|
||||
| Representative domains | Project, Book, Chapter, Character, Location, Asset, Plot Line, Thread created through normal forms; all eight editors checked; Book changed through ribbon Save and reloaded to verify persisted value |
|
||||
| Details/settings/management | Browser and standalone GET checks for Book/Chapter/Character/Location/Asset Details, Collaborators, Timeline Settings, Manage Account and Threads; standalone main content fits 1920/800/390 |
|
||||
| Keyboard and context behaviour | Existing alias removal/input and profile tab sequence, Shift+Tab, one accessible ribbon Save, field-associated validation feedback, original context menu, and Ctrl+right-click native fallback passed |
|
||||
| Themes | Warm Light, Modern Light, Modern Dark, Warm Dark, Rose Pink and Baby Blue rendered and visually inspected; tests set the same app/theme/Bootstrap state as the existing theme mechanism |
|
||||
| Initial layout | Real HTML paused before activation for Book, Chapter, Character, Location and Plot Line: identical form/field geometry before and after activation, zero measured shift |
|
||||
| Operational checks | No active/queued background work before deployment; service active; local and public GET 200; hashes match; no recent service warning/error entries |
|
||||
| Cleanup | Real Chromium test installations removed; dedicated identity and all owned fixture projects/books/records removed through normal HardDeleteAccount workflow; private identity file deleted |
|
||||
|
||||
One inherited Browser limitation was deliberately retained: the character image editor can overflow at 390px. The baseline comparison proves that the new Desktop stylesheet neither creates nor changes that Browser overflow. The Desktop image editor wraps correctly and all checked Desktop forms fit at 390px. No claim is made that this pass redesigns or repairs every pre-existing Browser layout.
|
||||
|
||||
The new production layout infrastructure is a small static stylesheet (approximately 4.4KB) plus explicit view metadata/classes. It adds no layout observers, scans or client-side form reconstruction. Existing ribbon composition handles the new action contributions; save/validation ownership stays on the original forms. Measurements cover representative Chromium routes rather than every browser/route combination.
|
||||
|
||||
Operational artifacts: `/var/tmp/pd-record-workspaces/` (publish/deploy/live-browser logs); final local browser log `/var/tmp/pd-record-browser-final.log`; final build `/var/tmp/pd-record-build-final.log`; regression `/var/tmp/pd-record-regression-complete.log`. Visual previews: `/tmp/pd-record-dev-*.png`, including all six themes. No credential material is stored in the repository.
|
||||
@ -7,7 +7,7 @@ internal static class AppearanceTests
|
||||
{
|
||||
public static void RegistryAndPersistence()
|
||||
{
|
||||
if (ApplicationAppearance.Themes.Count != 4 || ApplicationAppearance.IsValid("dark")) throw new Exception("Four explicit theme identifiers required.");
|
||||
if (ApplicationAppearance.Themes.Count != 6 || ApplicationAppearance.IsValid("dark")) throw new Exception("All six explicit theme identifiers required.");
|
||||
var store = new AppearanceMemoryPreferences();
|
||||
var controller = new AppearanceController(new ToolbarTestUser(4), store);
|
||||
controller.Theme("modern-dark").GetAwaiter().GetResult();
|
||||
|
||||
@ -22,3 +22,51 @@ When scene cards are collapsed after measurement, the last measured geometry rem
|
||||
|
||||
Run `npm run test:locations` (with `CHROMIUM_PATH` if using an existing Chromium).
|
||||
This loads the full production site script and Bootstrap confirmation modal in an isolated location-tree fixture. AJAX responses are mocked. It checks parent assignment/reassignment, cancellation, cycle/no-op rejection, repeated dragging after tree replacement, scroll preservation, server-error display, and relationship modal/AJAX saves. Database behavior is covered separately by `PlotLine.Tests/Sql/LocationReparent.sql`, whose fixtures always roll back.
|
||||
|
||||
## Plot Lines narrative map
|
||||
|
||||
Run the isolated Razor host from the repository root:
|
||||
|
||||
```sh
|
||||
dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --toolbar-browser-host
|
||||
```
|
||||
|
||||
Then run `npm run test:plot-lines` from this directory. The test renders the actual narrative-map partial and production CSS/JavaScript with generated data. Inspector/editor requests and association saves are mocked; no database writes occur. It checks Focus/Weave route counts and positions, shared-scene deduplication, thread introductions, per-line gaps, explicit connections, three themes, selection and association submission, narrow-screen scrolling, direct route drops, repeated saves without navigation, stable page/strip/map scroll positions, refreshed counts and attribution markers, and card clearance from all routes. Screenshots are saved under `/tmp/plot-map-*.png`.
|
||||
|
||||
The focused composition gate is `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --plot-lines`.
|
||||
|
||||
Run `npm run test:associate-scenes` against the same isolated host for sticky-tray/filter behaviour, page drag auto-scroll in both directions, edge exit/end/cancellation, and downward keyboard/hover previews.
|
||||
|
||||
Run `npm run test:timeline-plot-retirement` against the isolated Razor host for actual Timeline/Settings rendering without plot lanes, health markers, lane controls or plot jumps. It preserves scene membership focus/search and supplied scenario ordering, including stale saved lane preferences. `PLOT_ASSET_ORIGIN=https://dev.plotdirector.com` exercises deployed frontend assets against the fixture.
|
||||
|
||||
Run `npm run test:plot-health` against the isolated host for lazy Health evidence, stored-status separation, Focus/Weave, annotation clearance, three themes, contribution navigation, and association drop/save preservation. `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --plot-health` runs the pure H001–H012 evaluator tests, including partial scenarios, cross-book chapters and 12,000 contributions. No database is required for these tests.
|
||||
|
||||
## Installed desktop contextual ribbon
|
||||
|
||||
With the loopback Razor host running, run `xvfb-run -a node PlotLine.Tests/Browser/pwa-desktop.cjs` from the repository root (or `npm run test:pwa-desktop` here). This installs and launches a real Chromium standalone PWA via CDP, rather than assuming viewport width means installed mode. Its Fixture identity is test-executable-only; no human sign-in, database access or authentication endpoint in the web application is involved. It checks browser preservation, actual Razor contributions, six themes, desktop widths, contextual menu keyboard/focus, original form submission, exact route/scope equivalence, jumps, Help and fragment replacement. See `Docs/PWA/Desktop-Experience.md` for the page/command inventory and declarative contribution contract.
|
||||
|
||||
For live **Dev-only** smoke tests, the executable's `--dev-browser-identity create /tmp/pd-dev-browser-<unique>.json` operational command provisions a dedicated identity through the normal user/password and email-verification repositories. It validates the configured database is `PlotDirector_Development`, takes/verifies a unique copy-only backup before provisioning, and writes credentials only into a newly created owner-readable file. The browser must still log in through the normal antiforgery-protected login page; no cookie forging or authentication changes occur. Do not trace/screenshot login, print the file or commit credentials. Run the same command with `cleanup` to sign in normally and invoke the complete account-deletion workflow, removing the exact identity, its owned fixture projects/files and the private credential file. The helper is compiled only in the test executable and is never part of the deployed web application.
|
||||
|
||||
After provisioning a dedicated fixture project/book through normal Dev forms, the private identity file may include `ProjectID` and `BookID`. Run `xvfb-run -a node PlotLine.Tests/Browser/pwa-desktop-dev.cjs /tmp/pd-dev-browser-<unique>.json` for real authenticated browser/installed-PWA Dev smoke coverage. It is pinned to `https://dev.plotdirector.com`, never records login screenshots/traces, and uses only the dedicated fixture project. Clean up the identity afterwards with the command above.
|
||||
|
||||
The contextual-ribbon regression now asserts one 84px active ribbon panel, with context groups to the right of the original groups and no contextual title/toolbar box. All six themes run at 2560/1440/900 px. Wide groups must remain direct when they fit; narrow groups use measured native-menu overflow with keyboard dismissal and unclipped hit targets. Existing equivalent commands are checked by DOM identity across category switches, not just by matching labels/URLs. Mixed management groups retain a compact destructive-action menu.
|
||||
|
||||
PWA first-paint checks: `node pwa-display-mode.cjs` verifies head bootstrap behavior, including stale hints and unavailable storage. `pwa-desktop.cjs` and the dedicated-identity `pwa-desktop-dev.cjs` also invoke `pwa-first-paint.cjs`: a real installed window, parser-paused intermediate screenshots, 2,500 additional content cards, cold/navigation/reload and browser stale-hint tests, composition timing and workspace-movement assertions. The gate is test-response injection only; application pages have no guard/delay. See `Docs/PWA/First-Paint.md`.
|
||||
|
||||
Desktop context menus: `npm run test:pwa-context` (with the isolated toolbar browser host running) uses a real installed PWA and actual Razor scenes/cards/forms. It verifies browser/Ctrl escape behavior, physical right-click and keyboard invocation, A/B targeting, original and typed-delete confirmations, unavailable/archived/read-only states, real Clipboard API editing and denied access, submenu keyboard/mouse behavior, all six themes and corners at 1440/900, source lifecycle and original primary/drag behavior. `pwa-desktop.cjs` captures representative contextual menus across the 20-view audit. The Dev suite checks native/PWA menu behavior on every existing smoke route and, when the private test scope contains owned sample IDs, exercises actual scene/entity routes, map inspector/association selection, clipboard and entity details without human login. Passwords, sessions and external/user clipboard content are not captured; screenshots use controlled fixture text.
|
||||
|
||||
Edit Scene workspace: with the isolated toolbar browser host running, use `npm run test:scene-workspace`. This checks the real Razor page/editor fragments in browser and installed-PWA windows, including shared area navigation/history, inspector stability and width recovery, Story/Relationships save flows, themes and responsive layouts. See `Docs/Codex/EditSceneWorkspace.md` for the capability inventory and optional read-only visual snapshot workflow.
|
||||
|
||||
|
||||
### Desktop promotion
|
||||
|
||||
Run `npm run test:desktop-promotion` for isolated browser coverage of eligibility, suppression/reminders, real screenshot geometry, pointer/keyboard interaction, modal focus, install prompting/fallback, themes and standalone exclusion. `npm run test:pwa` also checks the shared install mechanism and service worker.
|
||||
|
||||
For Dev verification, provision a private identity using the existing `--dev-browser-identity create /tmp/pd-dev-browser-<unique>.json` harness command, then run `xvfb-run -a node desktop-promotion-dev.cjs /tmp/pd-dev-browser-<unique>.json`. This uses normal authentication and creates an isolated project/book, captures theme previews under `/tmp`, installs a real Chromium app and checks first paint. Always run `--dev-browser-identity cleanup` afterwards. Never pass real user credentials or run against Production.
|
||||
|
||||
|
||||
### Desktop record workspaces
|
||||
|
||||
Run the isolated fixture host with `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --toolbar-browser-host`, then `npm run test:record-workspaces`. The suite renders nine real Razor forms and checks Browser preservation, Desktop composition, responsive widths, ribbon Save/icons, existing unobtrusive validation, multipart/antiforgery submission, themes and parser-paused first paint.
|
||||
|
||||
For Dev-only verification, provision an identity with `--dev-browser-identity create /tmp/pd-dev-browser-<unique>.json`, then run `xvfb-run -a node record-workspaces-dev.cjs /tmp/pd-dev-browser-<unique>.json`. It creates isolated records via their normal forms, installs/launches a real Chromium app, verifies eight record types plus details/settings/management, saves and reloads a changed book, checks keyboard/context behaviour, and measures initial geometry. Always finish with `--dev-browser-identity cleanup` to remove the account and all owned fixture data. Production is never a test target.
|
||||
|
||||
@ -9,7 +9,7 @@ const server = http.createServer((req, res) => {
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
if (req.url === '/fixture') {
|
||||
res.setHeader('Content-Type', 'text/html');
|
||||
res.end(`<html data-app-theme="modern-light"><head><meta charset="utf-8"><meta name="theme-color" content="#fff"><link rel="manifest" href="/site.webmanifest"><link rel="stylesheet" href="/css/application-shell.css"></head><body><input id="editor"><div hidden data-pwa-install-item><button data-pwa-install>Install</button></div><span data-pwa-status></span><script src="/js/application-pwa.js"></script></body></html>`);
|
||||
res.end(`<html data-app-theme="modern-light"><head><meta charset="utf-8"><meta name="theme-color" content="#fff"><link rel="manifest" href="/site.webmanifest"><link rel="stylesheet" href="/css/application-shell.css"></head><body data-desktop-user="fixture"><input id="editor"><div hidden data-pwa-install-item><button data-pwa-install>Install</button></div><span data-pwa-status></span><script src="/js/application-display-mode.js"></script><script src="/js/desktop-promotion.js"></script><script src="/js/application-pwa.js"></script></body></html>`);
|
||||
} else if (req.url === '/service-worker.js') {
|
||||
res.setHeader('Content-Type', 'application/javascript');
|
||||
res.end(fs.readFileSync(path.join(root, 'service-worker.js'), 'utf8') + `\n// test deployment ${workerRevision}`);
|
||||
@ -61,7 +61,7 @@ const server = http.createServer((req, res) => {
|
||||
assert.equal(await page.evaluate(() => fetch('/private-data', { cache: 'no-store' }).then(() => false, () => true)), true);
|
||||
await context.setOffline(false);
|
||||
assert.equal(await page.locator('[data-pwa-install-item]').isVisible(), true);
|
||||
assert.equal(await page.locator('[data-pwa-install]').textContent(), 'App installation…');
|
||||
assert.equal(await page.locator('[data-pwa-install]').textContent(), 'PlotDirector Desktop');
|
||||
// Browser supplies this event only when installable; exercise one-shot UI handling.
|
||||
await page.evaluate(() => {
|
||||
const event = new Event('beforeinstallprompt', { cancelable: true });
|
||||
@ -71,9 +71,10 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
assert.equal(await page.locator('[data-pwa-install-item]').isVisible(), true);
|
||||
await page.click('[data-pwa-install]');
|
||||
await page.click('[data-desktop-install]');
|
||||
assert.equal(await page.evaluate(() => window.prompted), true);
|
||||
assert.equal(await page.locator('[data-pwa-install-item]').isVisible(), true);
|
||||
assert.equal(await page.locator('[data-pwa-install]').textContent(), 'App installation…');
|
||||
assert.equal(await page.locator('[data-pwa-install]').textContent(), 'PlotDirector Desktop');
|
||||
await page.evaluate(() => window.dispatchEvent(new Event('appinstalled')));
|
||||
assert.equal(await page.locator('[data-pwa-install-item]').isVisible(), false);
|
||||
console.log('PASS PWA: manifest/icons, four theme metadata values, real worker activation/update without lost edits, no Cache Storage, private data unavailable offline, install action.');
|
||||
|
||||
@ -23,7 +23,7 @@ const assert = require('node:assert/strict');
|
||||
await open();
|
||||
await page.getByRole('button', { name: 'Restore defaults', exact: true }).click();
|
||||
await close('Save');
|
||||
assert.deepEqual(await visible(), ['overview','timeline','calendar','characters','threads','relationships','review']);
|
||||
assert.deepEqual(await visible(), ['overview','timeline','calendar','characters','threads','plotlines','relationships','review']);
|
||||
assert.equal(await page.locator('[data-toolbar-key="calendar"]').getAttribute('aria-current'), 'page');
|
||||
assert.match(await page.locator('[data-toolbar-key="calendar"]').getAttribute('href'), /projectId=7/);
|
||||
assert.match(await page.locator('[data-toolbar-key="review"]').getAttribute('href'), /book\/12\/review-centre/);
|
||||
@ -78,13 +78,13 @@ const assert = require('node:assert/strict');
|
||||
await page.locator('[data-command-key="calendar"] [data-move="-1"]').click();
|
||||
await page.screenshot({ path: '/tmp/plotdirector-toolbar-dialog.png' });
|
||||
await close('Cancel');
|
||||
assert.deepEqual(await visible(), ['overview','timeline','calendar','characters','threads','relationships','review']);
|
||||
assert.deepEqual(await visible(), ['overview','timeline','calendar','characters','threads','plotlines','relationships','review']);
|
||||
await open();
|
||||
await page.locator('[data-command-key="timeline"] input').uncheck();
|
||||
await page.locator('[data-command-key="locations"] input').check();
|
||||
await page.locator('[data-command-key="calendar"] [data-move="-1"]').click();
|
||||
await close('Save');
|
||||
assert.deepEqual(await visible(), ['calendar','overview','characters','threads','relationships','review','locations']);
|
||||
assert.deepEqual(await visible(), ['calendar','overview','characters','threads','plotlines','relationships','review','locations']);
|
||||
await page.reload();
|
||||
assert.equal((await visible())[0], 'calendar');
|
||||
const fresh = await browser.newContext();
|
||||
@ -170,12 +170,10 @@ const assert = require('node:assert/strict');
|
||||
await page.keyboard.press('Escape');
|
||||
const actual = await page.evaluate(() => ['.timeline-workspace', '.timeline-shell', '.timeline-chapter-title', '.timeline-scene-card'].map(selector => getComputedStyle(document.querySelector(selector)).backgroundColor));
|
||||
assert.deepEqual(actual, expected.slice(0, 4), `${theme} must preserve the canvas, section, nested-panel, and card hierarchy`);
|
||||
assert.equal(await page.locator('.future-lane-placeholder').evaluate(element => getComputedStyle(element).backgroundColor), expected[2], `${theme} empty lanes must use the nested-panel surface`);
|
||||
const actionStyles = await page.locator('.workspace-heading .btn').evaluateAll(elements => elements.map(element => { const style = getComputedStyle(element); return [style.color, style.backgroundColor, style.borderColor]; }));
|
||||
assert(actionStyles.every(style => JSON.stringify(style) === JSON.stringify(actionStyles[0])), `${theme} Timeline peer actions must share one treatment`);
|
||||
assert.equal(await page.locator('.inspector-header').evaluate(element => getComputedStyle(element).backgroundColor), expected[2], `${theme} inspector header must use the nested-panel surface`);
|
||||
assert.equal(await page.locator('.timeline-scene-card.focus-dim').evaluate(element => getComputedStyle(element).opacity), '0.68', `${theme} focused-scene dimming must remain legible`);
|
||||
assert.equal(await page.locator('.lane-dim').evaluate(element => getComputedStyle(element).opacity), '0.72', `${theme} dimmed lanes must remain legible`);
|
||||
assert.equal(await page.locator('.timeline-metric-edit-status').textContent(), 'Select a single metric to edit its curve.');
|
||||
assert.equal(await page.locator('.timeline-metric-edit-status').evaluate(element => getComputedStyle(element).backgroundColor), 'rgba(0, 0, 0, 0)', `${theme} metric guidance must read as guidance, not a disabled button`);
|
||||
const markerContrasts = await page.locator('.thread-marker, .asset-marker, .character-marker').evaluateAll(elements => {
|
||||
|
||||
109
PlotLine.Tests/Browser/associate-scenes.cjs
Normal file
109
PlotLine.Tests/Browser/associate-scenes.cjs
Normal file
@ -0,0 +1,109 @@
|
||||
const { chromium } = require('playwright');
|
||||
const assert = require('node:assert/strict');
|
||||
(async () => {
|
||||
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROMIUM_PATH });
|
||||
const page = await browser.newPage({ viewport: { width: 1100, height: 760 } });
|
||||
if (process.env.PLOT_ASSET_ORIGIN) {
|
||||
await page.route(/\/(?:css|js)\/plot-line-workspace\.(?:css|js)(?:\?.*)?$/, async route => {
|
||||
const response = await route.fetch({ url: process.env.PLOT_ASSET_ORIGIN + new URL(route.request().url()).pathname });
|
||||
await route.fulfill({ response });
|
||||
});
|
||||
}
|
||||
const errors = [];
|
||||
page.on('pageerror', e => errors.push(e.message));
|
||||
await page.route('**/Scenes/SceneThreadsEditor?**', route => route.fulfill({ body: '<form action="/Scenes/AddThreadEvent"><select name="PlotThreadID"><option value="">Choose thread</option></select><div><button type="submit">Add thread event</button></div></form>' }));
|
||||
await page.goto('http://127.0.0.1:5238/plot-map-fixture');
|
||||
// Extend the existing three-line fixture to exercise dragging through a long page.
|
||||
await page.evaluate(() => {
|
||||
const filter = document.getElementById('plot-workspace-form');
|
||||
filter.classList.add('plot-workspace-controls'); filter.style.height = '180px';
|
||||
document.querySelector('.plot-narrative-map').style.height = '2400px';
|
||||
const strip = document.querySelector('.plot-scene-strip');
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const item = document.createElement('button'); item.textContent = 'Manuscript scene ' + i; strip.append(item);
|
||||
}
|
||||
});
|
||||
await page.locator('[data-map-mode="associate"]').click();
|
||||
await page.evaluate(() => {
|
||||
document.querySelector('.plot-scene-strip').scrollLeft = 90;
|
||||
window.scrollTo({ top: 900, behavior: 'instant' });
|
||||
});
|
||||
const tray = page.locator('#plot-association-strip');
|
||||
assert.equal(await page.locator('#plot-workspace-form').evaluate(el => getComputedStyle(el).position), 'static');
|
||||
assert.ok(await page.locator('#plot-workspace-form').evaluate(el => el.getBoundingClientRect().bottom < 0));
|
||||
assert.ok(Math.abs((await tray.boundingBox()).y - 6) < 2);
|
||||
assert.equal(await page.locator('.plot-scene-strip').evaluate(el => el.scrollLeft), 90);
|
||||
assert.equal(await page.locator('.plot-map-scroll').evaluate(el => el.scrollHeight > el.clientHeight), false);
|
||||
await page.evaluate(() => {
|
||||
window.fixtureDrag = new DataTransfer();
|
||||
document.querySelector('[data-associate-scene="103"]').dispatchEvent(new DragEvent('dragstart', { bubbles: true, dataTransfer: window.fixtureDrag }));
|
||||
});
|
||||
const edge = async y => page.evaluate(y => {
|
||||
clearInterval(window.fixtureDragTimer);
|
||||
const emit = () => (document.elementFromPoint(600, y) || document.body).dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, clientX: 600, clientY: y, dataTransfer: window.fixtureDrag }));
|
||||
emit(); window.fixtureDragTimer = setInterval(emit, 70);
|
||||
}, y);
|
||||
const position = () => page.evaluate(() => scrollY);
|
||||
const start = await position();
|
||||
await edge(750);
|
||||
await page.waitForTimeout(450);
|
||||
assert.ok(await position() > start + 90, 'Bottom edge should scroll the page downward during the drag');
|
||||
await edge(400);
|
||||
const middle = await position();
|
||||
await page.waitForTimeout(160);
|
||||
assert.ok(Math.abs(await position() - middle) < 2, 'Leaving the edge zone must stop scrolling');
|
||||
const top = Math.round((await tray.boundingBox()).y + (await tray.boundingBox()).height + 8);
|
||||
await edge(top);
|
||||
await page.waitForTimeout(400);
|
||||
assert.ok(await position() < middle - 80, 'Upper usable edge should scroll upward');
|
||||
await edge(750);
|
||||
await page.waitForTimeout(150);
|
||||
await page.evaluate(() => { clearInterval(window.fixtureDragTimer); document.dispatchEvent(new DragEvent('dragend', { bubbles: true })); });
|
||||
const ended = await position();
|
||||
await page.waitForTimeout(180);
|
||||
assert.ok(Math.abs(await position() - ended) < 2, 'Drag end must stop scrolling');
|
||||
assert.equal(await page.locator('.plot-scene-strip').evaluate(el => el.scrollLeft), 90);
|
||||
// Escape cancels an active scrolling drag, even if dragover events continue briefly.
|
||||
await page.evaluate(() => document.querySelector('[data-associate-scene="103"]').dispatchEvent(new DragEvent('dragstart', { bubbles: true, dataTransfer: window.fixtureDrag })));
|
||||
await edge(750);
|
||||
await page.waitForTimeout(100);
|
||||
await page.keyboard.press('Escape');
|
||||
const cancelled = await position();
|
||||
await page.waitForTimeout(180);
|
||||
assert.ok(Math.abs(await position() - cancelled) < 2);
|
||||
await page.evaluate(() => clearInterval(window.fixtureDragTimer));
|
||||
// Reach a lower route which starts below the viewport, then drop on the route itself.
|
||||
await page.evaluate(() => {
|
||||
const map = document.querySelector('.plot-narrative-map').getBoundingClientRect();
|
||||
document.querySelector('.plot-horizontal-route[data-drop-line="3"]').style.top = `${innerHeight + 100 - map.top}px`;
|
||||
document.querySelector('[data-associate-scene="103"]').dispatchEvent(new DragEvent('dragstart', { bubbles: true, dataTransfer: window.fixtureDrag }));
|
||||
});
|
||||
await edge(750);
|
||||
await page.waitForFunction(() => document.querySelector('.plot-horizontal-route[data-drop-line="3"]').getBoundingClientRect().bottom < innerHeight - 20);
|
||||
await page.evaluate(() => clearInterval(window.fixtureDragTimer));
|
||||
const lower = page.locator('.plot-horizontal-route[data-drop-line="3"]');
|
||||
const lowerRect = await lower.boundingBox();
|
||||
const transfer = await page.evaluateHandle(() => window.fixtureDrag);
|
||||
await lower.dispatchEvent('dragover', { dataTransfer: transfer, clientX: 600, clientY: lowerRect.y + 15 });
|
||||
assert.ok(await lower.evaluate(el => el.classList.contains('is-drop-target')));
|
||||
await lower.dispatchEvent('drop', { dataTransfer: transfer, clientX: 600, clientY: lowerRect.y + 15 });
|
||||
await page.locator('#plot-association-dialog form').waitFor();
|
||||
assert.equal(await page.locator('#plot-association-dialog [name="PlotLineID"]').inputValue(), '3');
|
||||
await page.locator('[data-association-close]').click();
|
||||
await page.locator('[data-map-mode="view"]').dispatchEvent('click');
|
||||
assert.equal(await tray.isVisible(), false);
|
||||
assert.equal(await page.locator('#plot-workspace-form').evaluate(el => getComputedStyle(el).position), 'sticky');
|
||||
const card = page.locator('.plot-map-callout button').first();
|
||||
await card.focus();
|
||||
const cardRect = await card.boundingBox();
|
||||
const preview = card.locator('.plot-callout-preview');
|
||||
const previewRect = await preview.boundingBox();
|
||||
assert.ok(previewRect.y >= cardRect.y + cardRect.height - 2, 'Focus preview should extend below the card');
|
||||
assert.ok(Math.abs(previewRect.x - cardRect.x) < 2, 'Preview should align with its originating card');
|
||||
assert.equal(await preview.evaluate(el => el.scrollHeight > el.clientHeight), false, 'Short previews should not have an internal scrollbar');
|
||||
await card.hover();
|
||||
assert.ok(await preview.isVisible());
|
||||
assert.deepEqual(errors, []);
|
||||
await browser.close();
|
||||
console.log('PASS: sticky association tray, normal filters, proportional page drag scrolling, stop/cancel, downward hover/focus previews');
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
52
PlotLine.Tests/Browser/desktop-promotion-dev.cjs
Normal file
52
PlotLine.Tests/Browser/desktop-promotion-dev.cjs
Normal file
@ -0,0 +1,52 @@
|
||||
// Dev only; provision/clean the isolated identity using --dev-browser-identity.
|
||||
const {chromium}=require('playwright');
|
||||
const fs=require('node:fs'); const os=require('node:os'); const path=require('node:path'); const assert=require('node:assert/strict');
|
||||
const base='https://dev.plotdirector.com';
|
||||
(async()=>{
|
||||
const file=process.argv[2];assert(file?.startsWith('/tmp/pd-dev-browser-'));
|
||||
const identity=JSON.parse(fs.readFileSync(file,'utf8'));assert.equal(identity.Database,'PlotDirector_Development');assert(identity.Email.startsWith('pwa-browser-'));
|
||||
const profile=fs.mkdtempSync(path.join(os.tmpdir(),'pd-promotion-dev-'));
|
||||
const context=await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1440,height:1100},reducedMotion:'reduce'});
|
||||
const cdp=await context.browser().newBrowserCDPSession();const manifestId=base+'/Projects';let installed=false;
|
||||
try{
|
||||
const page=context.pages()[0];
|
||||
await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(identity.Email);await page.locator('[name=Password]').fill(identity.Password);await page.locator('form button[type=submit]').click();await page.waitForURL(base+'/Projects');
|
||||
if(!identity.BookID){
|
||||
if(!identity.ProjectID){await page.goto(base+'/Projects/Create');console.log('Creating project');await page.locator('[name=ProjectName]').fill('Desktop promotion verification');await page.locator('form.edit-panel button[type=submit]').click();await page.waitForURL(/\/Projects\/Details\//);
|
||||
identity.ProjectID=Number(new URL(page.url()).pathname.split('/').at(-1));fs.writeFileSync(file,JSON.stringify(identity),{mode:0o600});console.log('Project fixture created');}
|
||||
const response=await page.goto(base+`/Books/Create?projectId=${identity.ProjectID}`);assert.equal(response.status(),200,'book creation route');assert(await page.locator('[name=BookTitle]').count(),'book fixture form');await page.locator('[name=BookTitle]').fill('Comparison verification');await page.locator('[name=BookNumber]').fill('1');await page.locator('form.edit-panel button[type=submit]').click();await page.waitForURL(/\/Books\/Details\//);
|
||||
identity.BookID=Number(page.url().split('/').at(-1));fs.writeFileSync(file,JSON.stringify(identity),{mode:0o600});
|
||||
}
|
||||
const url=base+`/Timeline?projectId=${identity.ProjectID}&bookId=${identity.BookID}`;
|
||||
await page.goto(url);await page.locator('dialog.pd-desktop-promotion').waitFor();
|
||||
await page.waitForFunction(()=>[...document.querySelectorAll('dialog img')].every(i=>i.complete&&i.naturalWidth===1710));
|
||||
await page.setViewportSize({width:1440,height:900});
|
||||
await page.locator('dialog').evaluate(d=>{d.querySelector('.pd-desktop-close').focus({preventScroll:true});d.scrollTop=0;});
|
||||
const scrollBefore=await page.locator('dialog').evaluate(d=>d.scrollTop);
|
||||
const imageBox=await page.locator('.pd-desktop-comparison').boundingBox();assert(imageBox.width>1100);
|
||||
await page.locator('dialog input').focus();await page.keyboard.press('ArrowLeft');assert.equal(await page.inputValue('dialog input'),'67');
|
||||
await page.locator('dialog').evaluate(d=>{d.querySelector('.pd-desktop-close').focus({preventScroll:true});d.scrollTop=0;});
|
||||
await page.mouse.move(imageBox.x+imageBox.width*.68,imageBox.y+90);await page.mouse.down();await page.mouse.move(imageBox.x+imageBox.width*.35,imageBox.y+90);await page.mouse.up();assert(Math.abs(Number(await page.inputValue('dialog input'))-35)<2);
|
||||
assert.equal(await page.locator('dialog').evaluate(d=>d.scrollTop),scrollBefore,'divider drag must not scroll the modal');
|
||||
await page.setViewportSize({width:1440,height:1100});
|
||||
// Deterministically exercise the non-promptable environment; real installation is checked below through Chromium CDP.
|
||||
await page.evaluate(()=>{window.savedInstallRequest=window.PlotDirectorInstall.request;window.PlotDirectorInstall.request=async()=>'unavailable';});
|
||||
await page.click('[data-desktop-install]');await page.waitForFunction(()=>document.querySelector('[data-install-status]').textContent.length>10);
|
||||
await page.evaluate(()=>window.PlotDirectorInstall.request=window.savedInstallRequest);
|
||||
for(const theme of ['warm-light','modern-light','modern-dark','warm-dark','rose-pink','baby-blue']){
|
||||
await page.evaluate(t=>document.documentElement.dataset.appTheme=t,theme);await page.screenshot({path:`/tmp/pd-desktop-promotion-${theme}.png`});
|
||||
assert(await page.locator('dialog').evaluate(d=>d.scrollWidth<=d.clientWidth+1));
|
||||
}
|
||||
await page.setViewportSize({width:390,height:844});const actions=await page.locator('dialog footer').boundingBox();assert(actions.y+actions.height<=844,'actions stay visible on narrow screens');await page.screenshot({path:'/tmp/pd-desktop-promotion-mobile.png'});assert(await page.locator('dialog').evaluate(d=>d.scrollWidth<=d.clientWidth+1));await page.setViewportSize({width:1440,height:1100});
|
||||
await page.click('[data-desktop-continue]');await page.reload();await page.waitForTimeout(2200);assert.equal(await page.locator('dialog[open]').count(),0);
|
||||
await page.click('#accountMenuButton');await page.click('[data-pwa-install]');assert(await page.locator('dialog').isVisible());await page.keyboard.press('Escape');
|
||||
assert.equal((await page.request.get(base+'/help/workspace/desktop')).status(),200);
|
||||
await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/Projects'});installed=true;
|
||||
await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});
|
||||
const opened=context.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url});const app=await opened;await app.waitForLoadState();
|
||||
assert(await app.evaluate(()=>window.PlotDirectorPwa.standalone));await app.waitForTimeout(2200);assert.equal(await app.locator('dialog.pd-desktop-promotion').count(),0);assert(await app.locator('[data-pwa-install-item]').isHidden());
|
||||
await require('./pwa-first-paint.cjs')(app,page,{url:base+`/StoryBible?projectId=${identity.ProjectID}`});
|
||||
await app.screenshot({path:'/tmp/pd-desktop-promotion-standalone.png'});
|
||||
console.log('PASS authenticated Dev: genuine screenshots, divider pointer/keyboard, themes/mobile, install fallback, dismissal persistence/manual reopen, Help, real installed PWA exclusion and first-paint checks.');
|
||||
}finally{if(installed)await cdp.send('PWA.uninstall',{manifestId}).catch(()=>{});await context.close();fs.rmSync(profile,{recursive:true,force:true});}
|
||||
})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
83
PlotLine.Tests/Browser/desktop-promotion.cjs
Normal file
83
PlotLine.Tests/Browser/desktop-promotion.cjs
Normal file
@ -0,0 +1,83 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const http = require('node:http');
|
||||
const { chromium } = require('playwright');
|
||||
const root = path.resolve(__dirname, '../../PlotLine/wwwroot');
|
||||
const server = http.createServer((req,res) => {
|
||||
if (req.url.startsWith('/Timeline')) {
|
||||
res.setHeader('Content-Type','text/html');
|
||||
res.end(`<html data-app-theme="modern-dark"><head><script src="/js/application-display-mode.js"></script><link rel="stylesheet" href="/css/application-shell.css"><link rel="stylesheet" href="/css/desktop-promotion.css"></head><body data-desktop-user="42" data-desktop-eligible="${!req.url.includes('new')}"><button id="accountMenuButton" data-pwa-install>Desktop</button><div id="workspace" style="height:500px">Workspace</div><script src="/js/desktop-promotion.js"></script><script src="/js/application-pwa.js"></script></body></html>`);
|
||||
} else {
|
||||
const file = path.join(root,req.url.split('?')[0]);
|
||||
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return res.writeHead(404).end();
|
||||
res.setHeader('Content-Type',file.endsWith('.js')?'application/javascript':file.endsWith('.css')?'text/css':'image/png');
|
||||
res.end(fs.readFileSync(file));
|
||||
}
|
||||
});
|
||||
(async()=>{
|
||||
await new Promise(r=>server.listen(0,'127.0.0.1',r));
|
||||
const browser=await chromium.launch();
|
||||
const base=`http://127.0.0.1:${server.address().port}`;
|
||||
try {
|
||||
const context=await browser.newContext({reducedMotion:'reduce',viewport:{width:1440,height:1100}});
|
||||
const page=await context.newPage();
|
||||
await page.goto(base+'/Timeline?new');
|
||||
await page.waitForTimeout(2000);
|
||||
assert.equal(await page.locator('dialog').count(),0,'new users are not interrupted');
|
||||
await page.goto(base+'/Timeline');
|
||||
await page.locator('#accountMenuButton').focus();
|
||||
await page.locator('dialog').waitFor();
|
||||
await page.waitForFunction(()=>[...document.querySelectorAll('dialog img')].every(i=>i.complete&&i.naturalWidth===1710));
|
||||
assert.equal(await page.inputValue('dialog input'), '68');
|
||||
const geometry=await page.locator('dialog img').evaluateAll(imgs=>imgs.map(i=>{const r=i.getBoundingClientRect();return [r.x,r.y,r.width,r.height]}));
|
||||
assert.deepEqual(geometry[0],geometry[1]);
|
||||
await page.locator('dialog input').focus(); await page.keyboard.press('ArrowRight');
|
||||
assert.equal(await page.inputValue('dialog input'),'69');
|
||||
// The keyboard slider sits below the image at shorter heights. Pointer focus must not reveal it by scrolling.
|
||||
await page.setViewportSize({width:1440,height:900});
|
||||
await page.locator('dialog').evaluate(d=>{d.querySelector('.pd-desktop-close').focus({preventScroll:true});d.scrollTop=0;});
|
||||
const scrollBefore=await page.locator('dialog').evaluate(d=>d.scrollTop);
|
||||
const box=await page.locator('.pd-desktop-comparison').boundingBox();
|
||||
await page.mouse.move(box.x+box.width*.7,box.y+80); await page.mouse.down(); await page.mouse.move(box.x+box.width*.3,box.y+80); await page.mouse.up();
|
||||
assert.equal(await page.locator('dialog').evaluate(d=>d.scrollTop),scrollBefore,'dragging must preserve modal scroll position');
|
||||
assert(await page.locator('dialog input').evaluate(e=>document.activeElement===e),'divider keeps keyboard focus');
|
||||
assert(Math.abs(Number(await page.inputValue('dialog input'))-30)<2);
|
||||
await page.click('[data-desktop-install]');
|
||||
assert.match(await page.locator('[data-install-status]').textContent(),/Chrome|browser/);
|
||||
await page.evaluate(()=>{const e=new Event('beforeinstallprompt',{cancelable:true});e.prompt=async()=>window.prompted=true;e.userChoice=Promise.resolve({outcome:'accepted'});dispatchEvent(e)});
|
||||
await page.click('[data-desktop-install]');
|
||||
assert(await page.evaluate(()=>window.prompted));
|
||||
assert(!/Desktop is ready/.test(await page.locator('[data-install-status]').textContent()));
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await page.evaluate(()=>document.activeElement.id),'accountMenuButton');
|
||||
await page.reload(); await page.waitForTimeout(2000); assert.equal(await page.locator('dialog[open]').count(),0);
|
||||
await page.click('#accountMenuButton'); assert(await page.locator('dialog').isVisible());
|
||||
// Native modal tab cycling keeps focus inside.
|
||||
for(let i=0;i<12;i++){await page.keyboard.press('Tab');assert(await page.evaluate(()=>!!document.activeElement.closest('dialog')))}
|
||||
for(const theme of ['warm-light','modern-light','modern-dark','warm-dark','rose-pink','baby-blue']){
|
||||
await page.evaluate(t=>document.documentElement.dataset.appTheme=t,theme);
|
||||
assert.equal(await page.locator('dialog').evaluate(d=>d.scrollWidth<=d.clientWidth+1),true);
|
||||
}
|
||||
await page.setViewportSize({width:390,height:844});const actions=await page.locator('dialog footer').boundingBox();assert(actions.y+actions.height<=844,'actions stay visible on narrow screens');
|
||||
assert(await page.locator('.pd-desktop-viewport').evaluate(e=>e.scrollWidth>e.clientWidth));
|
||||
assert(await page.locator('dialog').evaluate(e=>e.scrollWidth<=e.clientWidth+1));
|
||||
await page.evaluate(()=>{window.closedDialog=new Promise(r=>document.querySelector('dialog').addEventListener('close',r,{once:true}));});
|
||||
await page.keyboard.press('Escape');await page.evaluate(()=>window.closedDialog);
|
||||
await page.evaluate(()=>localStorage.setItem('plotdirector.desktop.v1.42',JSON.stringify({shownAt:Date.now()-31*86400000,dismissedAt:Date.now()-31*86400000})));
|
||||
await page.reload(); assert(await page.locator('.pd-desktop-reminder').isVisible()); assert.equal(await page.locator('dialog').count(),0);
|
||||
await page.locator('.pd-desktop-reminder .btn-primary').click();
|
||||
await page.evaluate(()=>dispatchEvent(new Event('appinstalled')));
|
||||
assert.match(await page.locator('[data-install-status]').textContent(),/Desktop is ready/);
|
||||
assert(await page.locator('[data-desktop-install]').isHidden());
|
||||
await context.close();
|
||||
const standalone=await browser.newContext();
|
||||
await standalone.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
|
||||
const app=await standalone.newPage(); let screenshots=0;
|
||||
app.on('request',r=>{if(r.url().includes('/images/desktop/'))screenshots++});
|
||||
await app.goto(base+'/Timeline'); await app.waitForTimeout(2100);
|
||||
await app.evaluate(()=>window.PlotDirectorDesktop.open(true));
|
||||
assert.equal(await app.locator('dialog').count(),0); assert.equal(screenshots,0);
|
||||
console.log('PASS desktop promotion: eligibility, assets/alignment, pointer/keyboard, reduced motion, focus/Escape, native install/fallback, persistence/reminder, themes/narrow viewport, standalone exclusion.');
|
||||
} finally {await browser.close();await new Promise(r=>server.close(r));}
|
||||
})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@ -5,7 +5,16 @@
|
||||
"test:locations": "node location-reparent.cjs",
|
||||
"test:characters": "node character-enrichment-detail.cjs",
|
||||
"test:toolbar": "node application-toolbar.cjs",
|
||||
"test:pwa": "node application-pwa.cjs"
|
||||
"test:pwa": "node application-pwa.cjs",
|
||||
"test:plot-lines": "node plot-line-map.cjs",
|
||||
"test:associate-scenes": "node associate-scenes.cjs",
|
||||
"test:timeline-plot-retirement": "node timeline-plot-retirement.cjs",
|
||||
"test:plot-health": "node plot-health.cjs",
|
||||
"test:pwa-desktop": "xvfb-run -a node pwa-desktop.cjs",
|
||||
"test:pwa-context": "xvfb-run -a node pwa-context-menu.cjs",
|
||||
"test:scene-workspace": "xvfb-run -a node scene-workspace.cjs",
|
||||
"test:desktop-promotion": "node desktop-promotion.cjs",
|
||||
"test:record-workspaces": "node record-workspaces.cjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"chart.js": "4.4.9",
|
||||
|
||||
70
PlotLine.Tests/Browser/plot-health.cjs
Normal file
70
PlotLine.Tests/Browser/plot-health.cjs
Normal file
@ -0,0 +1,70 @@
|
||||
const { chromium } = require('playwright');
|
||||
const assert = require('node:assert/strict');
|
||||
(async () => {
|
||||
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROMIUM_PATH });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
const errors = [];
|
||||
page.on('pageerror', e => errors.push(e.message));
|
||||
if (process.env.PLOT_ASSET_ORIGIN) await page.route(/\/(?:css|js)\/plot-line-workspace\.(?:css|js)(?:\?.*)?$/, async r => r.fulfill({ response: await r.fetch({ url: process.env.PLOT_ASSET_ORIGIN + new URL(r.request().url()).pathname }) }));
|
||||
let healthLoads = 0;
|
||||
await page.route('**/PlotLineWorkspace/Health?**', async r => {
|
||||
healthLoads++;
|
||||
await r.fulfill({ response: await r.fetch({ url: 'http://127.0.0.1:5238/plot-map-fixture?healthDetail=true&focus=true' }) });
|
||||
});
|
||||
await page.route('**/PlotLineWorkspace/Inspector?**', r => r.fulfill({ body: '<h2>Canonical contribution inspector</h2>' }));
|
||||
await page.route('**/Scenes/SceneThreadsEditor?**', r => r.fulfill({ body: '<form action="/Scenes/AddThreadEvent"><select name="PlotThreadID"><option value="11">Book thread</option></select><div><button type="submit">Add thread event</button></div></form>' }));
|
||||
await page.route('**/Scenes/AddThreadEvent', r => r.fulfill({ contentType: 'application/json', body: '{"success":true}' }));
|
||||
await page.route('**/plot-map-fixture*', async r => {
|
||||
if (r.request().headers()['x-plot-map'] === 'true') return r.fulfill({ response: await r.fetch({ url: 'http://127.0.0.1:5238/plot-map-fixture?health=true' }) });
|
||||
return r.continue();
|
||||
});
|
||||
await page.goto('http://127.0.0.1:5238/plot-map-fixture?health=true');
|
||||
assert.equal(healthLoads, 0, 'Verbose health detail must be lazy loaded');
|
||||
assert.equal(await page.locator('.plot-horizontal-route').count(), 2);
|
||||
assert.equal(await page.locator('.plot-health-summary').count(), 2);
|
||||
assert.ok(await page.locator('.plot-health-position').count());
|
||||
const clear = await page.locator('.plot-health-position').evaluateAll(markers => markers.every(marker => {
|
||||
const box = marker.getBoundingClientRect();
|
||||
return Array.from(document.querySelectorAll('.plot-map-callout,.plot-thread-section,.plot-map-marker')).every(item => {
|
||||
const other = item.getBoundingClientRect();
|
||||
return box.right <= other.left || box.left >= other.right || box.bottom <= other.top || box.top >= other.bottom;
|
||||
});
|
||||
}));
|
||||
assert.ok(clear, 'Health annotations must not obscure cards, thread labels or contribution nodes');
|
||||
await page.locator('.plot-health-summary[data-health-line="1"]').click();
|
||||
await page.locator('[data-health-rule="H002"]').first().waitFor();
|
||||
assert.equal(healthLoads, 1);
|
||||
assert.match(await page.locator('#plot-inspector-content').textContent(), /Stored author status:\s*Planned/);
|
||||
assert.match(await page.locator('#plot-inspector-content').textContent(), /Observed activity:/);
|
||||
assert.match(await page.locator('[data-health-rule="H002"]').first().textContent(), /10 scenes/);
|
||||
assert.ok(await page.locator('a[href*="PlotThreads/Edit/11"]').count());
|
||||
await page.locator('[data-health-rule="H002"] [data-scene-inspector]').first().click();
|
||||
await page.locator('#plot-inspector-content h2').filter({ hasText: 'Canonical contribution inspector' }).waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
await page.locator('[data-map-mode="associate"]').click();
|
||||
assert.equal(await page.locator('.plot-health-position').first().evaluate(el => getComputedStyle(el).pointerEvents), 'none');
|
||||
const drag = await page.evaluateHandle(() => new DataTransfer());
|
||||
await page.locator('[data-associate-scene="2"]').dispatchEvent('dragstart', { dataTransfer: drag });
|
||||
await page.locator('.plot-horizontal-route[data-drop-line="1"]').dispatchEvent('dragover', { dataTransfer: drag });
|
||||
assert.ok(await page.locator('.plot-horizontal-route[data-drop-line="1"]').evaluate(el => el.classList.contains('is-drop-target')));
|
||||
await page.locator('.plot-horizontal-route[data-drop-line="1"]').dispatchEvent('drop', { dataTransfer: drag });
|
||||
await page.locator('#plot-association-dialog form').waitFor();
|
||||
await page.locator('#plot-association-dialog [type="submit"]').click();
|
||||
await page.getByText('Association saved. Continue adding scenes.').waitFor();
|
||||
assert.ok(await page.locator('#plot-association-strip').isVisible());
|
||||
assert.equal(await page.locator('.plot-health-summary').count(), 2);
|
||||
await page.locator('[data-map-mode="view"]').click();
|
||||
await page.goto('http://127.0.0.1:5238/plot-map-fixture?health=true&focus=true');
|
||||
assert.equal(await page.locator('.plot-health-summary').count(), 1);
|
||||
for (const theme of ['modern-dark', 'warm-dark', 'modern-light']) {
|
||||
await page.evaluate(theme => document.documentElement.dataset.appTheme = theme, theme);
|
||||
await page.locator('.plot-health-summary').click();
|
||||
await page.locator('[data-health-rule="H002"]').first().waitFor();
|
||||
await page.waitForTimeout(240);
|
||||
await page.screenshot({ path: `/tmp/plot-health-${theme}.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
await browser.close();
|
||||
console.log('PASS: restrained lazy health inspector, evidence navigation, Focus/Weave, marker clearance, three themes and association refresh/drop preservation');
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
114
PlotLine.Tests/Browser/plot-line-map.cjs
Normal file
114
PlotLine.Tests/Browser/plot-line-map.cjs
Normal file
@ -0,0 +1,114 @@
|
||||
const { chromium } = require('playwright');
|
||||
const assert = require('node:assert/strict');
|
||||
(async () => {
|
||||
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROMIUM_PATH });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1050 } });
|
||||
if (process.env.PLOT_ASSET_ORIGIN) {
|
||||
await page.route(/\/(?:css|js)\/plot-line-workspace\.(?:css|js)(?:\?.*)?$/, async route => {
|
||||
const response = await route.fetch({ url: process.env.PLOT_ASSET_ORIGIN + new URL(route.request().url()).pathname });
|
||||
await route.fulfill({ response });
|
||||
});
|
||||
}
|
||||
const errors = [];
|
||||
page.on('pageerror', e => errors.push(e.message));
|
||||
await page.route('**/PlotLineWorkspace/Inspector?**', r => r.fulfill({ body: '<h2>Selected scene inspector</h2>' }));
|
||||
await page.route('**/Scenes/SceneThreadsEditor?**', r => r.fulfill({ body: '<form action="/Scenes/AddThreadEvent" method="post"><select name="PlotThreadID"><option value="">Choose</option><option value="11">First phase</option><option value="12">Other line</option></select><input name="SceneID" value="103"><input name="PlotEventTypeID" value="1"><button type="submit">Add thread event</button></form>' }));
|
||||
let saved = false;
|
||||
let saveCount = 0;
|
||||
let navigationCount = 0;
|
||||
page.on('framenavigated', frame => { if (frame === page.mainFrame()) navigationCount++; });
|
||||
await page.route('**/plot-map-fixture*', async route => {
|
||||
if (route.request().headers()['x-plot-map'] !== 'true') return route.continue();
|
||||
const response = await route.fetch();
|
||||
let html = await response.text();
|
||||
html = html.replace(/data-map-line-count="1" value="0"/, `data-map-line-count="1" value="${2 + saveCount}"`);
|
||||
html = html.replace('data-map-columns="2"', `data-map-columns="2" data-refreshed="${saveCount}"`);
|
||||
html = html.replace('○ Unattributed</small>', '✓ Selected line</small>');
|
||||
await route.fulfill({ response, body: html });
|
||||
});
|
||||
await page.route('**/Scenes/AddThreadEvent', r => {
|
||||
assert.match(r.request().postData(), /name="PlotLineID"\r\n\r\n1/);
|
||||
saved = true; saveCount++;
|
||||
return r.fulfill({ contentType: 'application/json', body: '{"success":true}' });
|
||||
});
|
||||
await page.goto('http://127.0.0.1:5238/plot-map-fixture');
|
||||
assert.equal(await page.locator('.plot-horizontal-route').count(), 3);
|
||||
assert.equal(await page.locator('.plot-map-callout').count(), 2);
|
||||
assert.equal(await page.locator('.plot-scene-stem.is-shared').count(), 2);
|
||||
assert.equal(await page.locator('.plot-membership-overlay path.is-shared').count(), 2);
|
||||
assert.equal(await page.locator('.plot-map-scroll').evaluate(el => el.scrollHeight > el.clientHeight), false);
|
||||
assert.equal(await page.locator('.plot-map-marker').count(), 3);
|
||||
assert.equal(await page.locator('.plot-thread-section').count(), 1);
|
||||
assert.equal(await page.locator('.plot-map-gap').count(), 1);
|
||||
assert.equal(await page.locator('.plot-explicit-target').count(), 1);
|
||||
assert.equal(await page.locator('.plot-dependency-overlay path').count(), 1);
|
||||
const labels = await page.locator('.plot-lane-label').evaluateAll(items => items.map(i => i.getBoundingClientRect().top));
|
||||
assert.equal(labels[1] - labels[0], 240);
|
||||
await page.locator('[data-scene-inspector="101"]').click();
|
||||
await page.locator('#plot-inspector-content h2').waitFor();
|
||||
assert.equal(await page.locator('#plot-inspector').getAttribute('aria-hidden'), 'false');
|
||||
await page.keyboard.press('Escape');
|
||||
for (const theme of ['modern-dark', 'warm-dark', 'modern-light']) {
|
||||
await page.evaluate(theme => { document.documentElement.dataset.appTheme = theme; document.documentElement.dataset.theme = theme.endsWith('dark') ? 'dark' : 'light'; }, theme);
|
||||
const colors = await page.locator('.plot-map-callout button').first().evaluate(el => ({ bg: getComputedStyle(el).backgroundColor, fg: getComputedStyle(el).color }));
|
||||
assert.notEqual(colors.bg, colors.fg);
|
||||
await page.screenshot({ path: `/tmp/plot-map-${theme}.png` });
|
||||
}
|
||||
await page.setViewportSize({ width: 800, height: 700 });
|
||||
await page.locator('[data-map-mode="associate"]').click();
|
||||
assert.equal(await page.locator('[data-associate-scene]').count(), 2);
|
||||
await page.locator('[data-associate-scene="103"]').click();
|
||||
await page.evaluate(() => {
|
||||
const strip = document.querySelector('.plot-scene-strip');
|
||||
for (let i = 0; i < 30; i++) {
|
||||
const item = document.createElement('button'); item.textContent = 'Sequence scene ' + i; strip.append(item);
|
||||
}
|
||||
strip.scrollLeft = 50;
|
||||
document.querySelector('.plot-map-scroll').scrollLeft = 60;
|
||||
window.scrollTo({ top: 100, behavior: "instant" });
|
||||
const count = document.createElement('small'); count.dataset.lineCount = '1'; count.textContent = '2 scenes'; document.getElementById('plot-workspace-form').append(count);
|
||||
});
|
||||
const before = await page.evaluate(() => ({ strip: document.querySelector('.plot-scene-strip').scrollLeft, map: document.querySelector('.plot-map-scroll').scrollLeft, page: scrollY }));
|
||||
await page.locator('[data-add-line="1"]').dispatchEvent('click');
|
||||
await page.locator('#plot-association-dialog form').waitFor();
|
||||
assert.equal(await page.locator('#plot-association-dialog [name="PlotThreadID"]').inputValue(), '11');
|
||||
await page.locator('#plot-association-dialog [type="submit"]').click();
|
||||
await page.getByText('Association saved. Continue adding scenes.').waitFor();
|
||||
assert.equal(await page.locator('#plot-association-dialog').evaluate(el => el.open), false);
|
||||
assert.equal(await page.locator('#plot-association-strip').isVisible(), true);
|
||||
assert.equal(await page.locator('[data-refreshed="1"]').count(), 1);
|
||||
assert.equal(navigationCount, 1);
|
||||
assert.equal(await page.locator('[data-line-count="1"]').textContent(), '3 scenes');
|
||||
assert.match(await page.locator('[data-associate-scene="103"] [data-association-state]').textContent(), /Selected line/);
|
||||
const after = await page.evaluate(() => ({ strip: document.querySelector('.plot-scene-strip').scrollLeft, map: document.querySelector('.plot-map-scroll').scrollLeft, page: scrollY }));
|
||||
assert.deepEqual(after, before);
|
||||
// Drop on the route itself and save a second association in the same session.
|
||||
const transfer = await page.evaluateHandle(() => new DataTransfer());
|
||||
await page.locator('[data-associate-scene="103"]').dispatchEvent('dragstart', { dataTransfer: transfer });
|
||||
await page.locator('.plot-horizontal-route[data-drop-line="1"]').dispatchEvent('dragover', { dataTransfer: transfer });
|
||||
assert.ok(await page.locator('.plot-horizontal-route[data-drop-line="1"]').evaluate(el => el.classList.contains('is-drop-target')));
|
||||
await page.locator('.plot-horizontal-route[data-drop-line="1"]').dispatchEvent('drop', { dataTransfer: transfer });
|
||||
await page.locator('#plot-association-dialog form').waitFor();
|
||||
await page.locator('#plot-association-dialog [type="submit"]').click();
|
||||
await page.locator('[data-refreshed="2"]').waitFor();
|
||||
assert.equal(saveCount, 2);
|
||||
assert.equal(navigationCount, 1);
|
||||
assert.equal(await page.locator('#plot-association-strip').isVisible(), true);
|
||||
const clearances = await page.locator('.plot-map-callout').evaluateAll(cards => cards.every(card => {
|
||||
const rect = card.getBoundingClientRect();
|
||||
return Array.from(document.querySelectorAll('.plot-horizontal-route')).every(route => {
|
||||
const y = route.getBoundingClientRect().top + 15;
|
||||
return rect.bottom < y || rect.top > y;
|
||||
});
|
||||
}));
|
||||
assert.ok(clearances);
|
||||
assert.ok(saved);
|
||||
await page.goto('http://127.0.0.1:5238/plot-map-fixture?focus=true');
|
||||
assert.equal(await page.locator('.plot-horizontal-route').count(), 1);
|
||||
assert.equal(await page.locator('.plot-scene-stem.is-shared').count(), 0);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
assert.ok(await page.locator('.plot-map-scroll').evaluate(el => el.scrollWidth > el.clientWidth));
|
||||
assert.deepEqual(errors, []);
|
||||
await browser.close();
|
||||
console.log('PASS: narrative map Focus/Weave, shared scenes, threads, gaps, connections, themes, inspector and association workflow');
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
76
PlotLine.Tests/Browser/pwa-context-dev-checks.cjs
Normal file
76
PlotLine.Tests/Browser/pwa-context-dev-checks.cjs
Normal file
@ -0,0 +1,76 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const timings=[];
|
||||
async function dispatch(target, ctrlKey = false) {
|
||||
return target.evaluate((node, ctrlKey) => { const event = new MouseEvent('contextmenu',{bubbles:true,cancelable:true,clientX:120,clientY:260,ctrlKey});node.dispatchEvent(event);return event.defaultPrevented; },ctrlKey);
|
||||
}
|
||||
const menu = page => page.locator('body > .pd-context-popup').first();
|
||||
async function checkMode(page, standalone) {
|
||||
const main=page.locator('[data-pwa-page-content]');
|
||||
assert.equal(await dispatch(main),standalone);
|
||||
if(standalone && await menu(page).count()) {
|
||||
assert(await menu(page).isVisible());
|
||||
const duration=await page.evaluate(()=>performance.getEntriesByName('pd-context-menu-open').at(-1)?.duration); if(Number.isFinite(duration))timings.push(duration);
|
||||
const rect=await menu(page).boundingBox(), viewport=page.viewportSize();
|
||||
assert(rect.x>=0&&rect.y>=0&&rect.x+rect.width<=viewport.width&&rect.y+rect.height<=viewport.height);
|
||||
await page.keyboard.press('Escape');
|
||||
}
|
||||
for(const selector of ['[data-pwa-page-content]','main button','main input:not([type=hidden])','main textarea','main select','main a']) {
|
||||
const target=page.locator(selector).first(); if(await target.count())assert.equal(await dispatch(target,true),false,'Ctrl override');
|
||||
}
|
||||
assert.equal(await page.locator('body > .pd-context-popup').count(),0);
|
||||
}
|
||||
async function checkObjects(page, base, id) {
|
||||
const scope=`projectId=${id.ProjectID}`;
|
||||
// Use only the dedicated owned import; invocation continues through the actual controls.
|
||||
for(const sceneID of id.SceneIDs.slice(0,2)) {
|
||||
await page.goto(base+`/Timeline?${scope}&bookId=${id.BookID}`);
|
||||
const card=page.locator(`.timeline-scene-card[data-scene-id="${sceneID}"]`);
|
||||
assert(await dispatch(card)); await menu(page).getByRole('menuitem',{name:'Inspect scene',exact:true}).click();
|
||||
await page.waitForURL(url=>[...url.searchParams].some(([key,value])=>key.toLowerCase()==='selectedsceneid'&&value===String(sceneID)));
|
||||
}
|
||||
for(const [route,kind] of [['Characters','character'],['Locations','location'],['StoryAssets','asset'],['PlotLines','plot line'],['PlotThreads','thread']]) {
|
||||
await page.goto(base+`/${route}?${scope}`);
|
||||
const object=page.locator(`[data-pd-context="${kind}"]`).first(); if(!await object.count())continue;
|
||||
const source=object.locator('a[data-command-operation]').first(), href=await source.getAttribute('href');
|
||||
await dispatch(object); const action=menu(page).getByRole('menuitem',{name:new RegExp(`^(Open|Edit) ${kind}$`)}).first();
|
||||
await action.click(); await page.waitForURL(new URL(href,base).href); assert.equal((await page.request.get(page.url())).status(),200);
|
||||
}
|
||||
await page.goto(base+`/Books/Details/${id.BookID}`);
|
||||
const chapter=page.locator('[data-pd-context=chapter]').first();
|
||||
if(await chapter.count()) { const chapterID=await chapter.getAttribute('data-pd-context-id');await dispatch(chapter);await menu(page).getByRole('menuitem',{name:'Edit',exact:true}).click();await page.waitForURL(base+'/Chapters/Edit/'+chapterID); }
|
||||
await page.goto(base+`/Characters?${scope}`);const character=page.locator('[data-pd-context=character]').first();
|
||||
await dispatch(character);await menu(page).getByRole('menuitem',{name:'Archive',exact:true}).click();
|
||||
await page.locator('#plotlineConfirmModal.show').waitFor();await page.locator('#plotlineConfirmModal [data-bs-dismiss=modal]').first().click();
|
||||
await page.locator('#plotlineConfirmModal').waitFor({state:'hidden'});
|
||||
await page.goto(base+`/PlotLineWorkspace?${scope}&bookId=${id.BookID}&plotLineId=${id.PlotLineID}`);
|
||||
const callout=page.locator('.plot-map-callout[data-pd-context=scene]').first();
|
||||
if(await callout.count()) {
|
||||
const sceneID=await callout.getAttribute('data-pd-context-id');await dispatch(callout);await menu(page).getByRole('menuitem',{name:'Inspect scene',exact:true}).click();
|
||||
await page.locator(`.plot-inspector [data-pd-context-id="${sceneID}"]`).waitFor();
|
||||
await page.locator('[data-inspector-close]').click();
|
||||
}
|
||||
await page.locator('[data-map-mode=associate]').click();
|
||||
const tray=page.locator('[data-associate-scene]').first();if(await tray.count()){
|
||||
await dispatch(tray);await menu(page).getByRole('menuitem',{name:'Select scene for association',exact:true}).click();assert.equal(await tray.getAttribute('aria-pressed'),'true');
|
||||
}
|
||||
await page.goto(base+`/Projects/Edit/${id.ProjectID}`);const field=page.locator('textarea[name=Description]');
|
||||
await field.fill('Context verification text');await field.evaluate(node=>{node.focus();node.setSelectionRange(0,7);});
|
||||
await dispatch(field);await menu(page).getByRole('menuitem',{name:'Copy',exact:true}).click();
|
||||
assert.equal(await page.evaluate(()=>navigator.clipboard.readText()),'Context');
|
||||
await dispatch(field);await menu(page).getByRole('menuitem',{name:'Select All',exact:true}).click();
|
||||
assert.deepEqual(await field.evaluate(node=>[node.selectionStart,node.selectionEnd]),[0,25]);
|
||||
// Local edit remains unsaved. Text APIs are exercised in the isolated suite too.
|
||||
for(const route of [`/Characters/Details/${id.CharacterIDs[0]}`,`/Scenarios/Timeline/${id.ScenarioID}`,`/RelationshipMap?${scope}`,`/Books/Details/${id.BookID}`]){
|
||||
await page.goto(base+route);await checkMode(page,true);
|
||||
if(route.startsWith('/Characters/Details/')) {
|
||||
await dispatch(page.locator('[data-pd-context=character]').first());
|
||||
assert.equal(await menu(page).getByRole('menuitem',{name:'Edit character',exact:true}).count(),1);
|
||||
const pages=menu(page).getByRole('menuitem',{name:'Page actions',exact:true});
|
||||
if(await pages.count()) { await pages.focus();await page.keyboard.press('ArrowRight');assert.equal(await page.locator('body > .pd-context-popup').nth(1).getByRole('menuitem',{name:'Edit character',exact:true}).count(),0); }
|
||||
await page.keyboard.press('Escape');
|
||||
}
|
||||
}
|
||||
console.log('Live context-menu timing ' + JSON.stringify({samples:timings.length,meanMs:timings.reduce((a,b)=>a+b,0)/timings.length,maxMs:Math.max(...timings)}));
|
||||
console.log('PASS live context targeting: owned scenes A/B, character/location/asset/line/thread original routes, archive cancellation, map inspector and association selection, real clipboard and detail/sandbox/relationship contexts.');
|
||||
}
|
||||
module.exports={checkMode,checkObjects,dispatch,menu};
|
||||
148
PlotLine.Tests/Browser/pwa-context-menu.cjs
Normal file
148
PlotLine.Tests/Browser/pwa-context-menu.cjs
Normal file
@ -0,0 +1,148 @@
|
||||
const { chromium } = require('playwright');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const base = 'http://127.0.0.1:5238';
|
||||
const rootMenu = page => page.locator('body > .pd-context-popup').first();
|
||||
async function right(page, target, modifiers = {}) {
|
||||
return target.evaluate((node, keys) => { const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 130, clientY: 240, ...keys }); node.dispatchEvent(event); return event.defaultPrevented; }, modifiers);
|
||||
}
|
||||
async function open(page, target) { assert.equal(await right(page, target), true); await rootMenu(page).waitFor(); }
|
||||
(async () => {
|
||||
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-context-'));
|
||||
const context = await chromium.launchPersistentContext(profile, { headless: false, viewport: { width: 1440, height: 1000 } });
|
||||
const cdp = await context.browser().newBrowserCDPSession();
|
||||
const errors = []; context.on('page', page => page.on('pageerror', error => errors.push(error.message)));
|
||||
try {
|
||||
await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin: base });
|
||||
const tab = context.pages()[0]; await tab.goto(base + '/fixture?desktop=StoryBible');
|
||||
assert.equal(await right(tab, tab.locator('[data-pwa-page-content]')), false, 'browser right-click untouched');
|
||||
assert.equal(await tab.locator('.pd-context-popup').count(), 0);
|
||||
const manifestId = base + '/Projects';
|
||||
await cdp.send('PWA.install', { manifestId, installUrlOrBundleUrl: base + '/fixture' });
|
||||
await cdp.send('PWA.changeAppUserSettings', { manifestId, displayMode: 'standalone' });
|
||||
const opened = context.waitForEvent('page'); await cdp.send('PWA.launch', { manifestId, url: base + '/fixture?desktop=StoryBible' });
|
||||
const app = await opened; await app.waitForLoadState();
|
||||
assert(await app.evaluate(() => window.PlotDirectorPwa.standalone));
|
||||
if (await app.locator('#ribbon-surface').isHidden()) { await app.locator('[data-ribbon-collapse]').click(); await app.locator('[data-ribbon-collapse]:not([disabled])').waitFor(); }
|
||||
for (const url of ['/fixture?desktop=StoryBible','/fixture?desktop=Characters&context=objects','/fixture?page=timeline-render']) {
|
||||
await app.goto(base + url);
|
||||
for (const target of [app.locator('[data-pwa-page-content]'), app.locator('main a').first(), app.locator('button').first()]) {
|
||||
assert.equal(await right(app, target, { ctrlKey: true }), false, 'Ctrl native override');
|
||||
assert.equal(await app.locator('.pd-context-popup').count(), 0);
|
||||
}
|
||||
}
|
||||
await app.locator('.timeline-scene-card').first().click({button:'right'});
|
||||
await rootMenu(app).waitFor();await app.keyboard.press('Escape');
|
||||
// Original route / target selection, not any prior selected scene.
|
||||
await app.goto(base + '/fixture?page=timeline-render');
|
||||
await app.locator('.timeline-scene-card[data-scene-id="101"]').evaluate(node => node.classList.add('selected'));
|
||||
for (const id of [102, 101]) {
|
||||
const card = app.locator(`.timeline-scene-card[data-scene-id="${id}"]`);
|
||||
const href = await card.getAttribute('href');
|
||||
await app.route('**/Timeline?**', route => route.fulfill({ contentType: 'text/html', body: '<p>Original route reached</p>' }));
|
||||
if (id === 101) { await card.focus(); await app.keyboard.press('Shift+F10'); await rootMenu(app).waitFor(); await app.keyboard.press('Enter'); }
|
||||
else { await open(app, card); await rootMenu(app).getByRole('menuitem', { name: 'Inspect scene', exact: true }).click(); }
|
||||
await app.waitForURL(new URL(href, base).href);
|
||||
assert.equal(new URL(app.url()).searchParams.get('FocusID'), String(id));
|
||||
await app.unroute('**/Timeline?**'); await app.goto(base + '/fixture?page=timeline-render');
|
||||
}
|
||||
// Actual Razor cards: original confirmations, per-object ID and disabled state.
|
||||
await app.goto(base + '/fixture?desktop=Characters&context=objects');
|
||||
const cardB = app.locator('[data-pd-context="character"][data-pd-context-id="72"]');
|
||||
await cardB.locator('button[type=submit]').evaluate(node=>node.addEventListener('click',()=>window.contextArchiveTarget=node.form.querySelector('[name=id]').value));
|
||||
await open(app, cardB);
|
||||
assert(await rootMenu(app).getByRole('menuitem', { name: 'Open character', exact: true }).count());
|
||||
await rootMenu(app).getByRole('menuitem', { name: 'Archive', exact: true }).click();
|
||||
await app.locator('#plotlineConfirmModal.show').waitFor();
|
||||
assert.equal(await app.evaluate(()=>window.contextArchiveTarget),'72');
|
||||
assert.equal(await app.locator('form[data-confirm-message] input[name=id][value="72"]').count(), 1);
|
||||
await app.locator('#plotlineConfirmModal [data-bs-dismiss=modal]').first().click();
|
||||
await app.locator('#plotlineConfirmModal').waitFor({ state: 'hidden' });
|
||||
await cardB.locator('button[type=submit]').evaluate(node => node.disabled = true);
|
||||
await open(app, cardB);
|
||||
const unavailable = rootMenu(app).getByRole('menuitem', { name: 'Archive', exact: true });
|
||||
assert.equal(await unavailable.getAttribute('aria-disabled'), 'true'); await app.screenshot({path:'/tmp/pd-context-disabled-archive.png'}); await unavailable.dispatchEvent('click');
|
||||
assert.equal(await app.locator('#plotlineConfirmModal.show').count(), 0);
|
||||
await app.keyboard.press('Escape');
|
||||
// Keyboard context invocation and focus restoration.
|
||||
const edit = cardB.locator('a.btn'); await edit.focus(); await app.keyboard.press('Shift+F10');
|
||||
await rootMenu(app).waitFor(); await app.keyboard.press('ArrowDown'); await app.keyboard.press('Escape');
|
||||
assert(await edit.evaluate(node => node === document.activeElement));
|
||||
await app.keyboard.press('ContextMenu');await rootMenu(app).waitFor();await app.keyboard.press('Escape');
|
||||
await app.goto(base + '/fixture?desktop=Archives&context=objects');
|
||||
await open(app,app.locator('[data-pd-context="archived item"]'));
|
||||
assert.equal(await rootMenu(app).getByRole('menuitem',{name:/Edit|Associate/}).count(),0);
|
||||
await rootMenu(app).getByRole('menuitem',{name:'Delete Forever',exact:true}).click();
|
||||
await app.locator('#plotlineConfirmModal.show').waitFor();
|
||||
assert.equal(await app.locator('#plotlineConfirmModal input[data-confirm-delete-input]').count() || await app.locator('#plotlineConfirmModal input').count(),1);
|
||||
await app.locator('#plotlineConfirmModal [data-bs-dismiss=modal]').first().click();
|
||||
await app.locator('#plotlineConfirmModal').waitFor({state:'hidden'});
|
||||
// Clipboard uses the real API and real fields; read-only and disabled remain restricted.
|
||||
await app.goto(base + '/fixture?desktop=ProjectEdit');
|
||||
const field = app.locator('textarea[name=Description]');
|
||||
await field.fill('alpha beta'); await field.evaluate(node => { node.focus(); node.setSelectionRange(6,10); });
|
||||
assert.equal(await right(app, field, { ctrlKey: true }), false);
|
||||
await open(app, field); await rootMenu(app).getByRole('menuitem', { name: 'Copy', exact: true }).click();
|
||||
assert.equal(await app.evaluate(() => navigator.clipboard.readText()), 'beta');
|
||||
await field.evaluate(node => node.setSelectionRange(6,10));
|
||||
await open(app, field); await rootMenu(app).getByRole('menuitem', { name: 'Cut', exact: true }).click();
|
||||
await app.waitForFunction(() => document.querySelector('textarea[name=Description]').value === 'alpha ');
|
||||
await field.evaluate(node => { node.focus(); node.setSelectionRange(6,6); });
|
||||
await open(app, field); await rootMenu(app).getByRole('menuitem', { name: 'Paste', exact: true }).click();
|
||||
await app.waitForFunction(() => document.querySelector('textarea[name=Description]').value === 'alpha beta');
|
||||
await open(app, field); await rootMenu(app).getByRole('menuitem', { name: 'Select All', exact: true }).click();
|
||||
assert.deepEqual(await field.evaluate(node => [node.selectionStart,node.selectionEnd]), [0,10]);
|
||||
await field.evaluate(node => node.readOnly=true); await open(app, field);
|
||||
assert.equal(await rootMenu(app).getByRole('menuitem',{name:'Cut',exact:true}).getAttribute('aria-disabled'), 'true');
|
||||
assert.equal(await rootMenu(app).getByRole('menuitem',{name:'Paste',exact:true}).getAttribute('aria-disabled'), 'true');
|
||||
await app.screenshot({path:'/tmp/pd-context-readonly.png'});
|
||||
await app.keyboard.press('Escape');
|
||||
await field.evaluate(node=>{node.readOnly=false;const group=document.createElement('fieldset');group.disabled=true;node.before(group);group.append(node);});
|
||||
await open(app,field);assert.equal(await rootMenu(app).getByRole('menuitem',{name:'Paste',exact:true}).getAttribute('aria-disabled'),'true');await app.keyboard.press('Escape');
|
||||
await field.evaluate(node=>node.parentElement.disabled=false);
|
||||
await field.evaluate(node => { node.readOnly=false; Object.defineProperty(navigator, 'clipboard', { configurable:true, value: { readText:()=>Promise.reject(new DOMException('Denied','NotAllowedError')), writeText:()=>Promise.reject(new DOMException('Denied','NotAllowedError')) } }); });
|
||||
await open(app, field); await rootMenu(app).getByRole('menuitem',{name:'Paste',exact:true}).click();
|
||||
await app.locator('.pd-context-feedback').waitFor();
|
||||
assert.equal(await field.inputValue(),'alpha beta');
|
||||
// Scene/card primary and drag handlers are not invoked by opening a menu.
|
||||
await app.goto(base + '/fixture?page=timeline-render');
|
||||
await app.evaluate(() => { window.primaryClicks=0; document.querySelector('.timeline-scene-card').addEventListener('click',()=>window.primaryClicks++); });
|
||||
await open(app, app.locator('.timeline-scene-card').first());
|
||||
assert.equal(await app.evaluate(() => window.primaryClicks), 0);
|
||||
await app.keyboard.press('Escape');
|
||||
assert.equal(await app.locator('.timeline-scene-card').first().getAttribute('draggable'), 'true');
|
||||
// One-level submenus and all corners, real themes and narrow desktop.
|
||||
await app.goto(base + '/fixture?desktop=StoryBible');
|
||||
const themes = await app.locator('[data-app-theme-choice]').evaluateAll(nodes=>nodes.map(node=>node.dataset.appThemeChoice));
|
||||
for (const width of [1440,900]) for (const theme of themes) {
|
||||
await app.setViewportSize({width,height:900});
|
||||
await app.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));
|
||||
await app.evaluate(theme=>{const root=document.documentElement;root.dataset.appTheme=theme;root.dataset.theme=root.dataset.bsTheme=theme.endsWith('-dark')?'dark':'light';},theme);
|
||||
for (const [x,y] of [[1,1],[width-1,1],[1,899],[width-1,899]]) {
|
||||
await app.locator('[data-pwa-page-content]').evaluate((node,p)=>node.dispatchEvent(new MouseEvent('contextmenu',{bubbles:true,cancelable:true,clientX:p[0],clientY:p[1]})),[x,y]);
|
||||
const menu=rootMenu(app); const rect=await menu.boundingBox(); const usableWidth=await app.evaluate(()=>document.documentElement.clientWidth);
|
||||
assert(rect.x>=0&&rect.y>=0&&rect.x+rect.width<=usableWidth&&rect.y+rect.height<=900);
|
||||
const exp=menu.getByRole('menuitem',{name:'Export',exact:true});
|
||||
await exp.focus(); await app.keyboard.press('ArrowRight');
|
||||
const sub=app.locator('body > .pd-context-popup').nth(1); await sub.waitFor();
|
||||
const subRect=await sub.boundingBox(); assert(subRect.x>=0&&subRect.x+subRect.width<=usableWidth&&subRect.y+subRect.height<=900);
|
||||
assert.equal(await exp.getAttribute('aria-expanded'),'true'); await app.keyboard.press('ArrowLeft');
|
||||
assert(await exp.evaluate(node=>node===document.activeElement));
|
||||
if(x===width-1&&y===899) { await app.mouse.move(10,400); await exp.hover(); await sub.waitFor(); await app.screenshot({path:`/tmp/pd-context-${theme}-${width}.png`}); }
|
||||
await app.keyboard.press('Escape');
|
||||
}
|
||||
}
|
||||
// Lifecycle and no stale menus through updates/scroll/navigation.
|
||||
await open(app,app.locator('[data-pwa-page-content]')); await app.mouse.click(800,400); assert.equal(await app.locator('.pd-context-popup').count(),0);
|
||||
await open(app,app.locator('[data-pwa-page-content]')); await right(app,app.locator('[data-pwa-page-content]')); assert.equal(await app.locator('body > .pd-context-popup').count(),1);
|
||||
await app.evaluate(()=>window.dispatchEvent(new Event('plotdirector:context-changed'))); assert.equal(await app.locator('.pd-context-popup').count(),0);
|
||||
await open(app,app.locator('[data-pwa-page-content]')); await app.evaluate(()=>document.dispatchEvent(new Event('scroll'))); assert.equal(await app.locator('.pd-context-popup').count(),0);
|
||||
const timing = await app.evaluate(()=>{const samples=performance.getEntriesByName('pd-context-menu-open').map(entry=>entry.duration); return { count:samples.length, meanMs:samples.reduce((a,b)=>a+b,0)/samples.length, maxMs:Math.max(...samples) };});
|
||||
console.log('Context-menu timings ' + JSON.stringify(timing));
|
||||
await open(app,app.locator('[data-pwa-page-content]')); await app.goto(base+'/fixture?desktop=Characters'); assert.equal(await app.locator('.pd-context-popup').count(),0);
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('PASS PWA context menus: native browser and Ctrl override; exact A/B scene routes; original archive confirmation; disabled/read-only commands; real clipboard Cut/Copy/Paste/Select All; keyboard/focus; all six themes/corners/1440+900 submenu direction; click-away, second context, scroll, update and navigation dismissal; primary click/drag preserved.');
|
||||
} finally { await context.close(); fs.rmSync(profile,{recursive:true,force:true}); }
|
||||
})().catch(error=>{console.error(error);process.exitCode=1;});
|
||||
159
PlotLine.Tests/Browser/pwa-desktop-dev.cjs
Normal file
159
PlotLine.Tests/Browser/pwa-desktop-dev.cjs
Normal file
@ -0,0 +1,159 @@
|
||||
// Operational smoke test: dedicated Dev identity only. No traces, login screenshots or credential output.
|
||||
const { chromium } = require('playwright');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const assert = require('node:assert/strict');
|
||||
const base = 'https://dev.plotdirector.com';
|
||||
const contextChecks = require('./pwa-context-dev-checks.cjs');
|
||||
let stage = 'setup';
|
||||
async function ready(page) {
|
||||
await page.locator('[data-pwa-context-host]:not([hidden])').waitFor({ state: 'attached' });
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
}
|
||||
async function openGroup(page, name) {
|
||||
await ready(page);
|
||||
const menu = page.locator(`.pd-context-group[aria-label="${name}"] > details[data-compact="true"]`);
|
||||
if (await menu.count() && await menu.getAttribute('open') === null) await menu.locator(':scope > summary').click();
|
||||
}
|
||||
async function oneRibbon(page) {
|
||||
await ready(page);
|
||||
assert(await page.evaluate(() => {
|
||||
const panel = document.querySelector('.pd-ribbon-panel:not([hidden])');
|
||||
const host = document.querySelector('[data-pwa-context-host]');
|
||||
return host.parentElement === panel && !document.querySelector('[data-pwa-context-title]') &&
|
||||
host.getBoundingClientRect().height === 0 && panel.getBoundingClientRect().height <= 86 && panel.scrollWidth <= panel.clientWidth + 1;
|
||||
}));
|
||||
}
|
||||
(async () => {
|
||||
const file = process.argv[2];
|
||||
if (!file?.startsWith('/tmp/pd-dev-browser-')) throw Error('Private Dev identity file required');
|
||||
const identity = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
assert.equal(identity.Database, 'PlotDirector_Development');
|
||||
assert(identity.Email.startsWith('pwa-browser-') && identity.Email.endsWith('@example.invalid'));
|
||||
assert(identity.ProjectID && identity.BookID);
|
||||
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-dev-desktop-'));
|
||||
const context = await chromium.launchPersistentContext(profile, { headless: false, viewport: { width: 1440, height: 1000 } });
|
||||
await context.grantPermissions(['clipboard-read','clipboard-write'],{origin:base});
|
||||
const cdp = await context.browser().newBrowserCDPSession();
|
||||
const manifestId = base + '/Projects';
|
||||
try {
|
||||
stage = 'normal authenticated Dev login';
|
||||
const tab = context.pages()[0];
|
||||
await tab.goto(base + '/Account/Login');
|
||||
await tab.locator('[name=Email]').fill(identity.Email);
|
||||
await tab.locator('[name=Password]').fill(identity.Password);
|
||||
await tab.locator('form button[type=submit]').click();
|
||||
await tab.waitForURL(base + '/Projects');
|
||||
const q = `projectId=${identity.ProjectID}`;
|
||||
const routes = [
|
||||
`/Projects/Details/${identity.ProjectID}`, `/Books/Details/${identity.BookID}`,
|
||||
`/Timeline?${q}&bookId=${identity.BookID}`, `/PlotLineWorkspace?${q}&bookId=${identity.BookID}`,
|
||||
`/StoryBible?${q}`, `/Characters?${q}`, `/Locations?${q}`, `/StoryAssets?${q}`, `/FloorPlans?${q}`,
|
||||
`/Names?${q}`, `/Scenarios?${q}`, `/ContinuityExplorer?${q}`, `/ProjectMetrics?${q}`, `/Analytics?${q}`,
|
||||
`/Warnings?${q}`, `/Archives?${q}`, `/StoryPoint?${q}`, `/ProjectCollaborators?${q}`, `/ProjectRestorePoints?${q}`,
|
||||
`/StoryCalendar?${q}`, `/PlotThreads?${q}`, `/PlotLines?${q}`, `/Writer?${q}`, '/Writer/WritingPlans', '/Writer/SchedulePreview',
|
||||
`/Projects/Edit/${identity.ProjectID}`, `/Books/Edit/${identity.BookID}`, `/Chapters/Create?bookId=${identity.BookID}`,
|
||||
`/Characters/Create?${q}`, `/Locations/Create?${q}`, `/StoryAssets/Create?${q}`, `/PlotThreads/Create?${q}`, `/PlotLines/Create?${q}`,
|
||||
`/Timeline/Settings?${q}`, `/Dynamics/Story?${q}`, '/Imports', '/FeatureRequests', '/FeatureRequests/Roadmap', '/FeatureRequests/Create', '/help', '/ManageAccount', '/ManageAccount/Subscription'
|
||||
|
||||
];
|
||||
for (const route of routes) {
|
||||
stage = 'browser ' + route.split('?')[0];
|
||||
const response = await tab.goto(base + route);
|
||||
assert.equal(response.status(), 200);
|
||||
await contextChecks.checkMode(tab, false);
|
||||
assert(!tab.url().includes('/Account/'));
|
||||
if (await tab.locator('main .breadcrumb-trail').count()) assert(await tab.locator('main .breadcrumb-trail').first().isVisible());
|
||||
assert(await tab.locator('main h1').first().isVisible());
|
||||
assert(await tab.locator('[data-pwa-context-host]').isHidden());
|
||||
}
|
||||
stage = 'real Dev PWA installation';
|
||||
await tab.goto(base + '/Projects');
|
||||
await cdp.send('PWA.install', { manifestId, installUrlOrBundleUrl: base + '/Projects' });
|
||||
await cdp.send('PWA.changeAppUserSettings', { manifestId, displayMode: 'standalone' });
|
||||
const opened = context.waitForEvent('page');
|
||||
await cdp.send('PWA.launch', { manifestId, url: base + routes[0] });
|
||||
const app = await opened; await app.waitForLoadState();
|
||||
assert(await app.evaluate(() => matchMedia('(display-mode: standalone)').matches));
|
||||
await require('./pwa-first-paint.cjs')(app, tab, { url: base + '/StoryBible?' + q });
|
||||
for (const route of routes) {
|
||||
stage = 'installed ' + route.split('?')[0];
|
||||
const response = await app.goto(base + route);
|
||||
assert.equal(response.status(), 200);
|
||||
if (await app.locator('#ribbon-surface').isHidden()) await app.locator('[data-ribbon-tab=story]').click();
|
||||
await oneRibbon(app);
|
||||
await contextChecks.checkMode(app,true);
|
||||
if (await app.locator('main [data-pwa-header]').count()) assert(await app.locator('main [data-pwa-header]').first().isHidden());
|
||||
if (await app.locator('main [data-pwa-task]').count()) assert(await app.locator('main [data-pwa-task] h1').first().isVisible());
|
||||
if (await app.locator('main .breadcrumb-trail:not([data-pwa-context])').count()) assert(await app.locator('main .breadcrumb-trail:not([data-pwa-context])').first().isHidden());
|
||||
const ids = await app.locator('.pd-ribbon-panel:not([hidden]) .pd-ribbon-command[data-command-identity]').evaluateAll(nodes => nodes.map(node => node.dataset.commandIdentity));
|
||||
assert.equal(ids.length, new Set(ids).size);
|
||||
assert(await app.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
|
||||
if (await app.locator('main h1 [data-help-url]').count()) assert.equal(await app.locator('.pd-context-help').count(), 1);
|
||||
const pathname = route.split('?')[0];
|
||||
if (/^\/(Projects\/Details|Books\/Details|Timeline$|PlotLineWorkspace$|StoryBible$|StoryCalendar$|PlotThreads$|StoryPoint$|Characters$|Locations$|ProjectMetrics$|Analytics$|Warnings$|Archives$)/.test(pathname)) {
|
||||
await app.setViewportSize({ width: 1920, height: 1000 }); await oneRibbon(app);
|
||||
const name = pathname.split('/').filter(Boolean).slice(0,2).join('-');
|
||||
await app.screenshot({ path: `/tmp/pwa-completion-dev-${name}.png` });
|
||||
}
|
||||
}
|
||||
stage = 'deployed Story Bible search/jump/help behavior';
|
||||
await app.goto(base + `/StoryBible?${q}`);
|
||||
if (await app.locator('#ribbon-surface').isHidden()) await app.locator('[data-ribbon-tab=tools]').click();
|
||||
const search = app.locator('.pd-context-search input');
|
||||
await search.fill('beth');
|
||||
assert.equal(await app.locator('.pd-context-search .pd-context-submit').count(), 0);
|
||||
await Promise.all([app.waitForURL(url => url.searchParams.get('q') === 'beth'), search.press('Enter')]);
|
||||
await app.locator('.pd-context-search input').fill('beth integrated');
|
||||
await Promise.all([app.waitForURL(url => url.searchParams.get('q') === 'beth integrated'), app.locator('.pd-context-search-submit').click()]);
|
||||
await openGroup(app, 'Jump to');
|
||||
await app.locator('[data-pwa-context-controls] a[href="#revision"]').click();
|
||||
assert.equal(await app.evaluate(() => document.activeElement.id), 'revision');
|
||||
await app.locator('.pd-context-help').click();
|
||||
await app.waitForFunction(() => document.querySelector('[data-help-layout]')?.classList.contains('help-open'));
|
||||
await app.waitForFunction(() => /Story Bible/i.test(document.querySelector('[data-help-drawer-heading]')?.textContent || ''));
|
||||
await app.locator('[data-help-close]').click();
|
||||
for (const theme of await app.locator('[data-app-theme-choice]').evaluateAll(nodes => nodes.map(node => node.dataset.appThemeChoice))) {
|
||||
await app.evaluate(theme => { const root = document.documentElement; root.dataset.appTheme = theme; root.dataset.theme = root.dataset.bsTheme = theme.endsWith('-dark') ? 'dark' : 'light'; window.dispatchEvent(new Event('plotdirector:theme-changed')); }, theme);
|
||||
await app.setViewportSize({ width: 2560, height: 1000 }); await oneRibbon(app);
|
||||
await app.screenshot({ path: `/tmp/pwa-completion-story-bible-${theme}.png` });
|
||||
}
|
||||
stage = 'deployed Timeline scope';
|
||||
await app.goto(base + `/Timeline?${q}`);
|
||||
if (await app.locator('#ribbon-surface').isHidden()) await app.locator('[data-ribbon-tab=story]').click();
|
||||
await app.locator('[data-pwa-context-controls] select').selectOption(String(identity.BookID));
|
||||
await Promise.all([app.waitForURL(url => (url.searchParams.get('BookID') || url.searchParams.get('bookId')) === String(identity.BookID)), app.locator('[data-pwa-context-controls] button', { hasText: 'View' }).click()]);
|
||||
stage = 'deployed archive cancellation';
|
||||
await app.goto(base + `/Books/Details/${identity.BookID}`);
|
||||
if (await app.locator('#ribbon-surface').isHidden()) await app.locator('[data-ribbon-tab=book]').click();
|
||||
await openGroup(app, 'Manage');
|
||||
await app.locator('[data-pwa-context-controls]').getByRole('button', { name: 'Archive Book', exact: true }).click();
|
||||
await app.locator('#plotlineConfirmModal').waitFor({ state: 'visible' });
|
||||
await app.locator('#plotlineConfirmModal button[data-bs-dismiss]').first().click();
|
||||
await app.locator('#plotlineConfirmModal').waitFor({ state: 'hidden' });
|
||||
assert.equal(new URL(app.url()).pathname, `/Books/Details/${identity.BookID}`);
|
||||
for (const theme of await app.locator('[data-app-theme-choice]').evaluateAll(nodes => nodes.map(node => node.dataset.appThemeChoice))) {
|
||||
await app.evaluate(theme => { const root = document.documentElement; root.dataset.appTheme = theme; root.dataset.theme = root.dataset.bsTheme = theme.endsWith('-dark') ? 'dark' : 'light'; window.dispatchEvent(new Event('plotdirector:theme-changed')); }, theme);
|
||||
for (const width of [2560, 900]) {
|
||||
await app.setViewportSize({ width, height: 1000 }); await oneRibbon(app);
|
||||
assert(await app.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
|
||||
await app.screenshot({ path: `/tmp/pwa-ribbon-dev-book-${theme}-${width}.png` });
|
||||
}
|
||||
}
|
||||
for (const [name, route] of [['timeline', `/Timeline?${q}&bookId=${identity.BookID}`], ['plot-lines', `/PlotLineWorkspace?${q}`], ['story-bible', `/StoryBible?${q}`], ['project', `/Projects/Details/${identity.ProjectID}`]]) {
|
||||
await app.goto(base + route);
|
||||
if (await app.locator('#ribbon-surface').isHidden()) await app.locator('[data-ribbon-tab][aria-selected=true]').click();
|
||||
for (const width of [2560, 1920, 900]) {
|
||||
await app.setViewportSize({ width, height: 1000 }); await oneRibbon(app);
|
||||
await app.screenshot({ path: `/tmp/pwa-ribbon-dev-${name}-${width}.png` });
|
||||
}
|
||||
}
|
||||
stage = 'live contextual object verification';
|
||||
if (identity.SceneIDs?.length) await contextChecks.checkObjects(app, base, identity);
|
||||
console.log('PASS authenticated Dev browser + real installed PWA: ' + routes.length + ' routes; deployed search, jump, correct Help drawer, Timeline scope, archive cancellation, one ribbon with no title strip at 2560/1920/900, all six themes; no human login or existing manuscript changes.');
|
||||
} finally {
|
||||
await cdp.send('PWA.uninstall', { manifestId }).catch(() => {});
|
||||
await context.close(); fs.rmSync(profile, { recursive: true, force: true });
|
||||
}
|
||||
})().catch(() => { console.error('FAIL Dev PWA smoke at ' + stage + '; credentials withheld.'); process.exitCode = 1; });
|
||||
227
PlotLine.Tests/Browser/pwa-desktop.cjs
Normal file
227
PlotLine.Tests/Browser/pwa-desktop.cjs
Normal file
@ -0,0 +1,227 @@
|
||||
const { chromium } = require('playwright');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const base = 'http://127.0.0.1:5238';
|
||||
async function settled(page) { await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); }
|
||||
async function openGroup(page, label) {
|
||||
await ready(page);
|
||||
const menu = page.locator(`.pd-context-group[aria-label="${label}"] > details[data-compact="true"]`);
|
||||
if (await menu.count() && await menu.getAttribute('open') === null) await menu.locator(':scope > summary').click();
|
||||
}
|
||||
async function ready(page) {
|
||||
await page.locator('[data-pwa-context-host]:not([hidden])').waitFor({ state: 'attached' });
|
||||
await settled(page);
|
||||
}
|
||||
(async () => {
|
||||
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-desktop-'));
|
||||
const context = await chromium.launchPersistentContext(profile, { headless: false, viewport: { width: 1440, height: 1000 } });
|
||||
const cdp = await context.browser().newBrowserCDPSession();
|
||||
const manifestId = base + '/Projects';
|
||||
const failures = [];
|
||||
context.on('page', page => page.on('pageerror', error => failures.push(error.message)));
|
||||
const urls = ['/fixture?page=dashboard', '/fixture?desktop=Books', '/fixture?desktop=StoryBible', '/fixture?desktop=PlotLineWorkspace', '/fixture?desktop=Characters', '/fixture?desktop=Locations', '/fixture?desktop=FloorPlans', '/fixture?desktop=Warnings', '/fixture?desktop=Archives', '/fixture?page=timeline-render', ...['PlotThreads','StoryCalendar','StoryPoint','ProjectMetrics','Analytics','Dynamics','WritingPlans','SchedulePreview','ReviewCentre','ProjectEdit'].map(name => '/fixture?desktop=' + name)];
|
||||
try {
|
||||
const tab = context.pages()[0];
|
||||
const browserPositions = new Map();
|
||||
for (const url of urls) {
|
||||
await tab.goto(base + url);
|
||||
assert(await tab.locator('main h1').first().isVisible(), url + ' browser title');
|
||||
if (await tab.locator('main .breadcrumb-trail').count()) assert(await tab.locator('main .breadcrumb-trail').first().isVisible(), url + ' browser breadcrumb');
|
||||
assert(await tab.locator('[data-pwa-context-host]').isHidden());
|
||||
browserPositions.set(url, (await tab.locator('[data-pwa-page-content]').boundingBox()).height);
|
||||
const header = tab.locator('main [data-pwa-header], main [data-pwa-task]').first();
|
||||
assert(await header.isVisible(), url + ' browser header');
|
||||
}
|
||||
await cdp.send('PWA.install', { manifestId, installUrlOrBundleUrl: base + '/fixture' });
|
||||
await cdp.send('PWA.changeAppUserSettings', { manifestId, displayMode: 'standalone' });
|
||||
const opened = context.waitForEvent('page');
|
||||
await cdp.send('PWA.launch', { manifestId, url: base + '/fixture?desktop=StoryBible' });
|
||||
const app = await opened; await app.waitForLoadState();
|
||||
assert(await app.evaluate(() => matchMedia('(display-mode: standalone)').matches));
|
||||
const themes = await app.locator('[data-app-theme-choice]').evaluateAll(nodes => nodes.map(node => node.dataset.appThemeChoice));
|
||||
assert.equal(themes.length, 6);
|
||||
await require('./pwa-first-paint.cjs')(app, tab);
|
||||
for (const url of urls) {
|
||||
await app.goto(base + url);
|
||||
if (await app.locator('#ribbon-surface').isHidden()) await app.locator('[data-ribbon-tab][aria-selected=true]').click();
|
||||
await ready(app);
|
||||
const identities = await app.locator('.pd-ribbon-panel:not([hidden]) .pd-ribbon-command[data-command-identity]').evaluateAll(nodes => nodes.map(node => node.dataset.commandIdentity));
|
||||
assert.equal(new Set(identities).size, identities.length, url + ' composed ribbon duplicates');
|
||||
if (await app.locator('main [data-pwa-header]').count()) assert(await app.locator('main [data-pwa-header]').first().isHidden(), url + ' PWA header');
|
||||
if (await app.locator('main [data-pwa-task]').count()) assert(await app.locator('main [data-pwa-task] h1').first().isVisible(), url + ' meaningful task heading');
|
||||
if (await app.locator('main .breadcrumb-trail').count()) assert(await app.locator('main .breadcrumb-trail').first().isHidden(), url + ' PWA breadcrumb');
|
||||
// The primary workspace now begins within a few pixels of the sticky shell.
|
||||
const reclaimed = await app.evaluate(() => {
|
||||
const main = document.querySelector('main');
|
||||
const first = [...main.querySelectorAll(':scope > *')].find(el => getComputedStyle(el).display !== 'none');
|
||||
return first ? first.getBoundingClientRect().top - main.getBoundingClientRect().top : 0;
|
||||
});
|
||||
assert(reclaimed < 70, `${url} content starts ${reclaimed}px below main`);
|
||||
for (const theme of themes) {
|
||||
await app.evaluate(theme => { const root = document.documentElement; root.dataset.appTheme = theme; root.dataset.theme = root.dataset.bsTheme = theme.endsWith('-dark') ? 'dark' : 'light'; window.dispatchEvent(new Event('plotdirector:theme-changed')); }, theme);
|
||||
for (const width of [2560, 1440, 900]) {
|
||||
await app.setViewportSize({ width, height: 1000 }); await settled(app);
|
||||
const geometry = await app.evaluate(() => {
|
||||
const panel = document.querySelector('.pd-ribbon-panel:not([hidden])');
|
||||
const groups = [...panel.querySelectorAll('.pd-ribbon-group')].filter(node => node.getBoundingClientRect().width);
|
||||
return { height: panel.getBoundingClientRect().height, fits: panel.scrollWidth <= panel.clientWidth + 1,
|
||||
tops: groups.map(node => node.getBoundingClientRect().top),
|
||||
parent: document.querySelector('[data-pwa-context-host]').parentElement === panel,
|
||||
titleCount: document.querySelectorAll('[data-pwa-context-title]').length,
|
||||
stripHeight: document.querySelector('[data-pwa-context-host]').getBoundingClientRect().height,
|
||||
pageFits: document.documentElement.scrollWidth <= innerWidth };
|
||||
});
|
||||
assert(geometry.parent && geometry.titleCount === 0 && geometry.stripHeight === 0, `${url} context must be groups inside active panel, without a title/toolbar box`);
|
||||
assert(geometry.height <= 86, `${url}/${width} ribbon grew to ${geometry.height}px`);
|
||||
assert(geometry.fits && geometry.pageFits, `${url}/${theme}/${width} overflow`);
|
||||
assert(Math.max(...geometry.tops) - Math.min(...geometry.tops) < 1, `${url}/${width} created a second ribbon row`);
|
||||
const summary = app.locator('.pd-ribbon-panel:not([hidden]) details[data-compact="true"] > summary').first();
|
||||
if (await summary.count()) {
|
||||
await summary.click();
|
||||
await app.waitForFunction(() => document.querySelector('.pd-ribbon-panel:not([hidden]) details[data-compact="true"][open] summary')?.getAttribute('aria-expanded') === 'true');
|
||||
const panel = app.locator('.pd-ribbon-panel:not([hidden]) details[data-compact="true"][open] > .pd-context-menu-content').last();
|
||||
assert(await panel.evaluate(el => { const r = el.getBoundingClientRect(); return r.right <= innerWidth + 1 && el.contains(document.elementFromPoint(r.left + 12, r.top + 12)); }));
|
||||
await app.keyboard.press('Escape');
|
||||
assert(await summary.evaluate(el => document.activeElement === el));
|
||||
}
|
||||
}
|
||||
}
|
||||
await app.setViewportSize({ width: 2560, height: 1000 }); await settled(app);
|
||||
assert.equal(await app.locator('.pd-context-group > details[data-compact="true"]:not([data-always-compact="true"])').count(), 0, `${url} prematurely collapsed contextual groups at wide desktop width`);
|
||||
await app.screenshot({ path: `/tmp/pwa-desktop-${url.includes('desktop=') ? url.split('desktop=')[1] : url.split('page=')[1]}.png` });
|
||||
const contextTarget = app.locator('[data-pwa-page-content] [data-pd-context]').first();
|
||||
const contextMain = app.locator('[data-pwa-page-content]');
|
||||
await require('./pwa-context-dev-checks.cjs').dispatch(await contextTarget.count() ? contextTarget : contextMain);
|
||||
if (await app.locator('body > .pd-context-popup').count()) {
|
||||
await app.screenshot({path:`/tmp/pd-context-page-${url.includes('desktop=') ? url.split('desktop=')[1] : url.split('page=')[1]}.png`});
|
||||
await app.keyboard.press('Escape');
|
||||
}
|
||||
await app.locator('[data-ribbon-collapse]').click();
|
||||
assert(await app.locator('#ribbon-surface').isHidden());
|
||||
await app.locator('[data-ribbon-tab=story]').click();
|
||||
await ready(app);
|
||||
}
|
||||
await app.goto(base + '/fixture?page=dashboard');
|
||||
if (await app.locator('#ribbon-surface').isHidden()) await app.locator('[data-ribbon-tab=project]').click();
|
||||
await openGroup(app, 'Manage');
|
||||
assert.equal(await app.locator('[data-pwa-context-controls] a[href*="Projects/Edit"]').count(), 0);
|
||||
assert.equal(await app.locator('.pd-ribbon-panel:not([hidden]) a[data-command-operation="books.create"]').count(), 1, 'Add Book must appear once, preferring the active base command');
|
||||
assert.equal(await app.locator('main a[data-command-operation="books.create"]:visible').count(), 0, 'The Books-section duplicate is also accounted for');
|
||||
assert.equal(await app.locator('[data-pwa-context-controls] a[href*="ProjectBackup"]').count(), 0);
|
||||
assert.equal(await app.locator('[data-pwa-context-controls]').getByRole('link', { name: 'Phase 1 Checklist' }).count(), 1);
|
||||
assert.equal(await app.locator('[data-pwa-context-controls]').getByRole('button', { name: 'Archive Project', exact: true }).count(), 1);
|
||||
// The original confirmation modal must cancel without posting, then submit unchanged data.
|
||||
let archived = null;
|
||||
await app.route('**/Projects/Archive', route => { archived = new URLSearchParams(route.request().postData()); return route.fulfill({ contentType: 'text/html', body: '<html>Archived fixture</html>' }); });
|
||||
await app.locator('[data-pwa-context-controls]').getByRole('button', { name: 'Archive Project', exact: true }).click();
|
||||
await app.locator('#plotlineConfirmModal').waitFor({ state: 'visible' });
|
||||
assert.equal(archived, null);
|
||||
await app.locator('#plotlineConfirmModal button[data-bs-dismiss]').first().click();
|
||||
await app.locator('#plotlineConfirmModal').waitFor({ state: 'hidden' });
|
||||
assert.equal(archived, null);
|
||||
await openGroup(app, 'Manage');
|
||||
await app.locator('[data-pwa-context-controls]').getByRole('button', { name: 'Archive Project', exact: true }).click();
|
||||
await app.locator('#plotlineConfirmModal [data-confirm-submit]').click();
|
||||
await app.waitForURL('**/Projects/Archive');
|
||||
assert.equal(archived.get('id'), '7');
|
||||
assert(archived.get('__RequestVerificationToken'));
|
||||
await app.goto(base + '/fixture?page=dashboard&owner=false');
|
||||
if (await app.locator('#ribbon-surface').isHidden()) await app.locator('[data-ribbon-tab=project]').click();
|
||||
assert.equal(await app.locator('[data-pwa-context-controls]').getByRole('button', { name: 'Archive Project', exact: true }).count(), 0);
|
||||
assert.equal(await app.locator('.pd-ribbon-command[href*="ProjectBackup"]').count(), 0);
|
||||
await app.goto(base + '/fixture?page=dashboard');
|
||||
if (await app.locator('#ribbon-surface').isHidden()) await app.locator('[data-ribbon-tab=project]').click();
|
||||
await openGroup(app, 'Manage');
|
||||
// Reuse the exact original ribbon node, without creating a duplicate or generic category link.
|
||||
await app.evaluate(() => window.originalEditCommand = document.querySelector('#ribbon-panel-project a[href*="Projects/Edit"]'));
|
||||
await app.locator('[data-ribbon-tab=world]').click(); await ready(app);
|
||||
assert.equal(await app.locator('.pd-ribbon-command[href*="Projects/Edit"]').count(), 1);
|
||||
assert(await app.evaluate(() => document.querySelector('[data-pwa-context-controls] a[href*="Projects/Edit"]') === window.originalEditCommand));
|
||||
await app.locator('[data-ribbon-tab=project]').click(); await ready(app);
|
||||
assert(await app.evaluate(() => document.querySelector('#ribbon-panel-project > .pd-ribbon-group a[href*="Projects/Edit"]') === window.originalEditCommand));
|
||||
await app.goto(base + '/fixture?desktop=Books');
|
||||
if (await app.locator('#ribbon-surface').isHidden()) await app.locator('[data-ribbon-tab=book]').click();
|
||||
await openGroup(app, 'Manage');
|
||||
assert(await app.locator('[data-pwa-context-controls]').getByRole('link', { name: 'Story health', exact: true }).getAttribute('href').then(href => href.includes('bookId=12')));
|
||||
await app.goto(base + '/fixture?page=timeline-render');
|
||||
if (await app.locator('#ribbon-surface').isHidden()) await app.locator('[data-ribbon-tab=story]').click();
|
||||
await app.evaluate(() => {
|
||||
const select = document.querySelector('main .timeline-filter select');
|
||||
select.add(new Option('Another book', '13'));
|
||||
window.dispatchEvent(new Event('plotdirector:context-changed'));
|
||||
select.form.addEventListener('submit', event => { event.preventDefault(); window.scopeSubmitted = Object.fromEntries(new FormData(event.target)); });
|
||||
});
|
||||
await app.locator('[data-pwa-context-controls] select').selectOption('13');
|
||||
await app.locator('[data-pwa-context-controls] button', { hasText: 'View' }).click();
|
||||
assert.equal(await app.evaluate(() => window.scopeSubmitted.BookID), '13');
|
||||
assert.equal(await app.evaluate(() => window.scopeSubmitted.ProjectID), '7');
|
||||
await app.goto(base + '/fixture?desktop=StoryBible');
|
||||
if (await app.locator('#ribbon-surface').isHidden()) await app.locator('[data-ribbon-tab=tools]').click();
|
||||
await app.evaluate(() => document.querySelector('main form.story-bible-search').addEventListener('submit', event => {
|
||||
event.preventDefault(); window.submitted = Object.fromEntries(new FormData(event.target));
|
||||
}));
|
||||
const search = app.locator('[data-pwa-context-controls] input');
|
||||
await search.fill('beth');
|
||||
assert.equal(await app.locator('[data-pwa-context-controls] .pd-context-submit').count(), 0, 'No separate full-sized Search card');
|
||||
assert.equal(await app.locator('.pd-context-search input[type=search]').count(), 1);
|
||||
await search.press('Enter');
|
||||
assert.equal(await app.evaluate(() => window.submitted.q), 'beth');
|
||||
await search.fill('beth integrated');
|
||||
await app.locator('.pd-context-search-submit').click();
|
||||
assert.equal(await app.evaluate(() => window.submitted.q), 'beth integrated');
|
||||
const exportIcons = await app.locator('.pd-context-group[aria-label=Export] .pd-context-command').evaluateAll(nodes => nodes.map(node => node.dataset.ribbonIcon).filter(Boolean));
|
||||
assert(exportIcons.includes('print') && exportIcons.includes('markdown') && exportIcons.includes('text-export') && exportIcons.includes('research') && exportIcons.includes('timeline-export'));
|
||||
assert(!exportIcons.includes('bible'));
|
||||
assert.equal(await app.evaluate(() => window.submitted.projectId), '7');
|
||||
await openGroup(app, 'Jump to');
|
||||
await app.locator('[data-pwa-context-controls] a[href="#revision"]').click();
|
||||
assert.equal(await app.evaluate(() => document.activeElement.id), 'revision');
|
||||
assert.equal(await app.locator('[data-pwa-context-controls] details[data-compact="true"][open]').count(), 0);
|
||||
assert(await app.locator('.pd-context-help').getAttribute('href').then(href => /^\/help\//i.test(href)));
|
||||
assert.equal(await app.locator('.pd-context-help').getAttribute('data-help-open'), 'storyBible.overview');
|
||||
const helpUrl = await app.locator('.pd-context-help').getAttribute('href');
|
||||
await app.route('**' + helpUrl, route => route.fulfill({ contentType: 'text/html', body: '<html>Story Bible help</html>' }));
|
||||
await app.locator('.pd-context-help').click();
|
||||
await app.waitForURL('**' + helpUrl);
|
||||
await app.goto(base + '/fixture?desktop=StoryBible');
|
||||
if (await app.locator('#ribbon-surface').isHidden()) await app.locator('[data-ribbon-tab=tools]').click();
|
||||
// Calendar-style partial replacement must discard disconnected commands immediately.
|
||||
await app.evaluate(() => { document.querySelector('main').innerHTML = '<div data-pwa-header><h1>Replacement</h1><a class="btn" href="/Locations?projectId=99">New scope</a></div>'; });
|
||||
await app.waitForFunction(() => document.querySelector('[data-pwa-context-controls] a[href*="projectId=99"]'));
|
||||
assert.equal(await app.locator('[data-pwa-context-controls] input').count(), 0);
|
||||
assert.equal(await app.locator('[data-pwa-context-controls] a[href*="projectId=99"]').count(), 1);
|
||||
// Large scope selector uses a searchable popover; state changes stay owned by the source.
|
||||
await app.evaluate(() => {
|
||||
document.querySelector('main').innerHTML = '<div data-pwa-header><h1>Scope fixture</h1><form><label>Book<select name="bookId">' + Array.from({length: 20}, (_, i) => `<option value="${i}">Book ${i}</option>`).join('') + '</select></label><button class="btn" type="submit">Apply scope</button></form><button class="btn" type="button" disabled id="state-command">Waiting</button></div>';
|
||||
document.querySelector('main form').addEventListener('submit', event => { event.preventDefault(); window.largeScope = new FormData(event.target).get('bookId'); });
|
||||
});
|
||||
await app.locator('.pd-context-selector').waitFor({ state: 'visible' });
|
||||
await app.locator('.pd-context-selector summary').click();
|
||||
await app.locator('.pd-context-selector input').fill('Book 19');
|
||||
assert.equal(await app.locator('.pd-context-selector option:not([hidden])').count(), 1);
|
||||
await app.locator('.pd-context-selector select').selectOption('19');
|
||||
await app.keyboard.press('Escape');
|
||||
await app.locator('[data-pwa-context-controls] button', { hasText: 'Apply scope' }).click();
|
||||
assert.equal(await app.evaluate(() => window.largeScope), '19');
|
||||
await openGroup(app, 'Page tools');
|
||||
assert(await app.locator('[data-pwa-context-controls]').getByRole('button', { name: 'Waiting', exact: true }).isDisabled());
|
||||
await app.evaluate(() => { const source = document.getElementById('state-command'); source.disabled = false; source.textContent = 'Ready'; });
|
||||
await app.waitForFunction(() => [...document.querySelectorAll('[data-pwa-context-controls] button')].some(node => node.textContent === 'Ready' && !node.disabled));
|
||||
await app.evaluate(() => {
|
||||
document.querySelector('main').innerHTML = '<section data-pwa-help><h1>Meaningful profile</h1><p id="profile-description">Author profile content</p><div data-pwa-context="Manage"><a class="btn" href="/Characters/Edit/99">Edit profile</a><button class="btn btn-outline-danger" type="button">Archive profile</button></div></section>';
|
||||
});
|
||||
await app.waitForFunction(() => document.querySelector('[data-pwa-context-controls] a[href="/Characters/Edit/99"]'));
|
||||
assert(await app.locator('#profile-description').isVisible());
|
||||
assert(await app.locator('main [data-pwa-context="Manage"]').isHidden());
|
||||
assert.equal(await app.locator('[data-pwa-context-controls] a[href="/Characters/Edit/99"]').count(), 1);
|
||||
await ready(app);
|
||||
assert.equal(await app.locator('.pd-context-group[aria-label="Manage"] > details').getAttribute('data-always-compact'), 'true');
|
||||
assert.deepEqual(failures, []);
|
||||
console.log('PASS PWA desktop: real installed/browser separation; 20 real Razor pages; semantic composed-command uniqueness and single Enter/integrated-button search; all six themes at 2560/1440/900; one active ribbon row without title strip; direct wide commands and measured responsive overflow; compact menus, keyboard Escape/focus, collapsed ribbon, route/scope deduplication, search form behavior, section jump focus, page help, fragment lifecycle.');
|
||||
} finally {
|
||||
await cdp.send('PWA.uninstall', { manifestId }).catch(() => {});
|
||||
await context.close(); fs.rmSync(profile, { recursive: true, force: true });
|
||||
}
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
23
PlotLine.Tests/Browser/pwa-display-mode.cjs
Normal file
23
PlotLine.Tests/Browser/pwa-display-mode.cjs
Normal file
@ -0,0 +1,23 @@
|
||||
const vm = require('node:vm');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const assert = require('node:assert/strict');
|
||||
const source = fs.readFileSync(path.join(__dirname, '../../PlotLine/wwwroot/js/application-display-mode.js'), 'utf8');
|
||||
for (const storageThrows of [false, true]) for (const standalone of [false, true]) {
|
||||
const root = { dataset: {} }, listeners = {}, changes = [];
|
||||
const media = { matches: standalone, addEventListener(name, fn) { listeners.media = fn; } };
|
||||
let stored = standalone ? 'browser' : 'standalone';
|
||||
const window = { matchMedia: () => media, addEventListener(name, fn) { listeners[name] = fn; }, dispatchEvent(event) { changes.push(event.detail.standalone); } };
|
||||
vm.runInNewContext(source, { window, document: { documentElement: root }, navigator: {}, CustomEvent: function(name, options) { this.detail = options.detail; }, sessionStorage: {
|
||||
getItem() { if (storageThrows) throw Error('storage denied'); return stored; },
|
||||
setItem(key, value) { if (storageThrows) throw Error('storage denied'); stored = value; }
|
||||
} });
|
||||
assert.equal(root.dataset.standalone, String(standalone));
|
||||
assert.equal(window.PlotDirectorPwa.standalone, standalone);
|
||||
listeners.pageshow(); assert.equal(changes.length, 1, 'same-mode restoration does not reconstruct ribbon');
|
||||
media.matches = !standalone; listeners.media();
|
||||
assert.equal(root.dataset.standalone, String(!standalone));
|
||||
assert.equal(window.PlotDirectorPwa.standalone, !standalone);
|
||||
if (!storageThrows) assert.equal(stored, standalone ? 'browser' : 'standalone');
|
||||
}
|
||||
console.log('PASS early display mode: authoritative stale-hint correction, storage denial, media change and pageshow stability.');
|
||||
63
PlotLine.Tests/Browser/pwa-first-paint.cjs
Normal file
63
PlotLine.Tests/Browser/pwa-first-paint.cjs
Normal file
@ -0,0 +1,63 @@
|
||||
const assert = require('node:assert/strict');
|
||||
// Stall the HTML parser after real content, before activation/deferred scripts.
|
||||
// This deliberately exposes the intermediate paint that previously leaked web chrome.
|
||||
module.exports = async function verifyFirstPaint(app, browser, options = {}) {
|
||||
const target = options.url || 'http://127.0.0.1:5238/fixture?desktop=StoryBible';
|
||||
const targetUrl = new URL(target);
|
||||
const matchesPage = url => url.origin === targetUrl.origin && url.pathname === targetUrl.pathname && url.searchParams.has('firstpaint');
|
||||
process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY = '1';
|
||||
if (await app.locator('#ribbon-surface').isHidden()) {
|
||||
await app.locator('[data-ribbon-collapse]').click();
|
||||
await app.locator('[data-ribbon-collapse]:not([disabled])').waitFor();
|
||||
}
|
||||
const results = [];
|
||||
for (const [page, standalone, label] of [[app, true, 'cold PWA'], [app, true, 'PWA navigation'], [app, true, 'PWA reload'], [browser, false, 'browser stale standalone hint'], [browser, false, 'browser reload']]) {
|
||||
if (label === 'cold PWA') await page.evaluate(() => sessionStorage.removeItem('plotdirector.displayMode'));
|
||||
if (!standalone) await page.evaluate(() => sessionStorage.setItem('plotdirector.displayMode', 'standalone'));
|
||||
let release, reached;
|
||||
const gate = new Promise(resolve => { release = resolve; });
|
||||
const blocked = new Promise(resolve => { reached = resolve; });
|
||||
await page.route('**/pwa-parser-gate.js', async route => { reached(); await gate; await route.fulfill({ contentType: 'application/javascript', body: '' }); });
|
||||
await page.route(matchesPage, async route => {
|
||||
const response = await route.fetch();
|
||||
const largeContent = '<section data-volume-fixture>' + '<article><span>Manuscript scene fixture</span></article>'.repeat(2500) + '</section>';
|
||||
const body = (await response.text()).replace('</main>', largeContent + '<div data-firstpaint-marker></div><script src="/pwa-parser-gate.js"></script></main>');
|
||||
await route.fulfill({ response, body });
|
||||
});
|
||||
console.log('First paint checking ' + label);
|
||||
const navigation = label.includes('reload') ? page.reload() : page.goto(target + (target.includes('?') ? '&' : '?') + 'firstpaint=' + encodeURIComponent(label));
|
||||
navigation.catch(() => {});
|
||||
try {
|
||||
await Promise.race([blocked, new Promise((_, reject) => setTimeout(() => reject(new Error('Parser gate not reached')), 10000))]);
|
||||
console.log('Parser gate reached ' + label);
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
const sample = () => page.evaluate(() => ({
|
||||
mode: document.documentElement.dataset.standalone,
|
||||
loading: document.readyState,
|
||||
ribbonHeight: document.querySelector('#ribbon-surface').getBoundingClientRect().height,
|
||||
header: !!document.querySelector('main [data-pwa-header]')?.getBoundingClientRect().height,
|
||||
identity: [...document.querySelectorAll('main [data-pwa-identity]')].some(node => !!node.getBoundingClientRect().height),
|
||||
y: document.querySelector('[data-firstpaint-marker]').getBoundingClientRect().top,
|
||||
commands: [...document.querySelectorAll('.pd-ribbon-panel:not([hidden]) .pd-ribbon-command')].map(node => node.textContent.trim()).join('|'),
|
||||
search: document.querySelectorAll('[data-pwa-context-controls] input[type=search]').length,
|
||||
persisted: sessionStorage.getItem('plotdirector.displayMode'),
|
||||
composeMs: performance.getEntriesByName('pd-ribbon-initial-compose').at(-1)?.duration
|
||||
}));
|
||||
const before = await sample();
|
||||
assert.equal(before.loading, 'loading');
|
||||
assert.equal(before.mode, String(standalone), label);
|
||||
assert.equal(before.header, !standalone, label + ' first visible header');
|
||||
if (standalone) { assert.equal(before.identity, false); assert.equal(before.search, 1, label + ' early search'); assert(before.ribbonHeight > 0, label + ' ribbon visible before activation'); }
|
||||
assert.equal(before.persisted, standalone ? 'standalone' : 'browser');
|
||||
console.log('First-paint assertions passed ' + label);
|
||||
await page.screenshot({ timeout: 3000, path: `/tmp/pwa-firstpaint-${label.replaceAll(' ', '-')}.png` });
|
||||
release(); await navigation;
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
const after = await sample();
|
||||
assert.equal(after.commands, before.commands, label + ' commands stable across activation');
|
||||
assert(Math.abs(after.y - before.y) < 1, label + ' no workspace movement');
|
||||
results.push({ label, workspaceShift: Math.abs(after.y - before.y), composeMs: before.composeMs });
|
||||
} finally { release(); await page.unroute('**/pwa-parser-gate.js'); await page.unroute(matchesPage); }
|
||||
}
|
||||
console.log('PASS parser-paused first paint: ' + JSON.stringify(results));
|
||||
};
|
||||
58
PlotLine.Tests/Browser/record-workspaces-dev.cjs
Normal file
58
PlotLine.Tests/Browser/record-workspaces-dev.cjs
Normal file
@ -0,0 +1,58 @@
|
||||
// Explicit Dev-only operational check. Credentials remain in the private identity file.
|
||||
const {chromium}=require('playwright');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const assert=require('node:assert/strict');
|
||||
const base='https://dev.plotdirector.com';let stage='setup';
|
||||
async function frames(p){await p.evaluate(()=>new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r))))}
|
||||
async function group(p,label='Record'){const menu=p.locator(`.pd-context-group[aria-label="${label}"] details[data-compact=true]`);if(await menu.count()&&await menu.getAttribute('open')===null)await menu.locator('summary').click()}
|
||||
(async()=>{
|
||||
const file=process.argv[2];assert(file?.startsWith('/tmp/pd-dev-browser-'));const identity=JSON.parse(fs.readFileSync(file,'utf8'));assert.equal(identity.Database,'PlotDirector_Development');assert(identity.Email.startsWith('pwa-browser-'));
|
||||
const profile=fs.mkdtempSync(path.join(os.tmpdir(),'pd-record-dev-'));const context=await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1920,height:1080}});const cdp=await context.browser().newBrowserCDPSession();let installed=false;
|
||||
const failures=[];context.on('page',p=>p.on('pageerror',e=>failures.push(e.message)));
|
||||
try{
|
||||
const tab=context.pages()[0];await tab.goto(base+'/Account/Login');await tab.locator('[name=Email]').fill(identity.Email);await tab.locator('[name=Password]').fill(identity.Password);await tab.locator('form button[type=submit]').click();await tab.waitForURL(base+'/Projects');
|
||||
const ids=identity.Records||{};const write=()=>{identity.Records=ids;fs.writeFileSync(file,JSON.stringify(identity),{mode:0o600})};
|
||||
async function create(area,query,fields){
|
||||
if(ids[area])return ids[area];stage='create '+area;assert.equal((await tab.goto(base+`/${area}/Create${query}`)).status(),200);
|
||||
for(const [name,value]of Object.entries(fields)){const el=tab.locator(`[name="${name}"]`);if(await el.evaluate(e=>e.tagName)==='SELECT')await el.selectOption(String(value));else await el.fill(String(value))}
|
||||
await Promise.all([tab.waitForNavigation(),tab.locator('main form.pd-record-form button[type=submit]').filter({hasText:/Save/}).click()]);
|
||||
assert(!new URL(tab.url()).pathname.endsWith('/Save'),area+' validation: '+await tab.locator('main .validation-summary-errors, main .field-validation-error').allTextContents());
|
||||
let id=Number(new URL(tab.url()).pathname.match(/\/Details\/(\d+)/)?.[1]);
|
||||
if(!id){const href=await tab.locator(`main a[href*="/${area}/Edit/"],main a[href*="/${area}/Details/"]`).first().getAttribute('href');id=Number(href.match(/\/(?:Edit|Details)\/(\d+)/)[1])}
|
||||
assert(id>0);ids[area]=id;write();return id;
|
||||
}
|
||||
const project=await create('Projects','',{ProjectName:'Desktop record layout verification',Description:'An isolated fixture for desktop workspace checks.'});
|
||||
const book=await create('Books',`?projectId=${project}`,{BookTitle:'Record layout verification',BookNumber:1});
|
||||
const chapter=await create('Chapters',`?bookId=${book}`,{ChapterTitle:'Opening chapter',ChapterNumber:1});
|
||||
const character=await create('Characters',`?projectId=${project}`,{CharacterName:'Verification character',DefaultDescription:'A record with profile information and a broad description.\n\nThe image editor should sit alongside this text in a wide Desktop window.'});
|
||||
const location=await create('Locations',`?projectId=${project}`,{LocationName:'Verification location',Description:'A location used only by the automated record-layout check.'});
|
||||
const asset=await create('StoryAssets',`?projectId=${project}`,{AssetName:'Verification object',Description:'An object record with state and location metadata.'});
|
||||
const line=await create('PlotLines',`?projectId=${project}`,{PlotLineName:'Verification plot line'});
|
||||
const thread=await create('PlotThreads',`?projectId=${project}`,{ThreadTitle:'Verification thread',PlotLineID:line});
|
||||
const editors=[['Projects',project],['Books',book],['Chapters',chapter],['Characters',character],['Locations',location],['StoryAssets',asset],['PlotLines',line],['PlotThreads',thread]];
|
||||
for(const [area,id]of editors){stage='browser '+area;assert.equal((await tab.goto(base+`/${area}/Edit/${id}`)).status(),200);assert(await tab.locator('main form.pd-record-form button[type=submit]').filter({hasText:/Save/}).isVisible());assert((await tab.locator('form.pd-record-form').boundingBox()).width<=980.5);}
|
||||
stage='install and launch';const manifestId=base+'/Projects';await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/Projects'});installed=true;await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=context.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:base+`/Books/Edit/${book}`});const app=await opened;await app.waitForLoadState();assert(await app.evaluate(()=>window.PlotDirectorPwa.standalone));
|
||||
for(const [area,id]of editors){
|
||||
stage='desktop '+area;assert.equal((await app.goto(base+`/${area}/Edit/${id}`)).status(),200);await frames(app);await group(app);
|
||||
assert.equal(await app.locator('[data-pwa-context-controls] button').filter({hasText:/^Save /}).count(),1);assert(await app.locator('main form.pd-record-form button[type=submit]').filter({hasText:/Save/}).isHidden());
|
||||
for(const width of [1920,1440,800,390]){await app.setViewportSize({width,height:1080});await frames(app);assert(await app.locator('form.pd-record-form').evaluate(e=>e.scrollWidth<=e.clientWidth+1),area+' overflow '+width)}
|
||||
await app.setViewportSize({width:1920,height:1080});await app.screenshot({path:`/tmp/pd-record-dev-${area}.png`,fullPage:true});
|
||||
}
|
||||
stage='validation and save';await app.goto(base+`/Books/Edit/${book}`);await app.locator('[name=BookTitle]').fill('');await group(app);await app.locator('[data-pwa-context-controls] button').filter({hasText:'Save book'}).click();await app.locator('[data-valmsg-for=BookTitle].field-validation-error').waitFor();
|
||||
await app.locator('[name=BookTitle]').fill('Updated layout verification');await group(app);await Promise.all([app.waitForURL(base+`/Books/Details/${book}`),app.locator('[data-pwa-context-controls] button').filter({hasText:'Save book'}).click()]);
|
||||
await app.goto(base+`/Books/Edit/${book}`);assert.equal(await app.inputValue('[name=BookTitle]'),'Updated layout verification');
|
||||
stage='themes and keyboard';await app.goto(base+`/Characters/Edit/${character}`);for(const theme of ['warm-light','modern-light','modern-dark','warm-dark','rose-pink','baby-blue']){await app.evaluate(t=>{const r=document.documentElement;r.dataset.appTheme=t;r.dataset.theme=t.endsWith('-dark')?'dark':'light';r.dataset.bsTheme=r.dataset.theme;dispatchEvent(new CustomEvent('plotdirector:theme-changed',{detail:{theme:t}}));},theme);await app.screenshot({path:`/tmp/pd-record-dev-theme-${theme}.png`,fullPage:true});}
|
||||
await app.bringToFront();await app.locator('[name=CharacterName]').press('Tab');assert(await app.locator('[data-remove-alias]').first().evaluate(e=>document.activeElement===e),'existing alias actions follow the name');await app.keyboard.press('Tab');assert(await app.locator('[data-alias-input]').evaluate(e=>document.activeElement===e),'alias input follows existing alias');
|
||||
await app.locator('[name=Height]').press('Tab');assert(await app.locator('[name=EyeColour]').evaluate(e=>document.activeElement===e),'logical profile tab sequence');await app.keyboard.press('Shift+Tab');assert(await app.locator('[name=Height]').evaluate(e=>document.activeElement===e),'reverse tab sequence');
|
||||
await app.locator('[name=CharacterName]').click({button:'right'});assert(await app.locator('.pd-context-popup').isVisible(),'existing edit context menu');await app.keyboard.press('Escape');
|
||||
await app.keyboard.down('Control');await app.locator('[name=CharacterName]').click({button:'right'});await app.keyboard.up('Control');assert.equal(await app.locator('.pd-context-popup').count(),0,'Ctrl+right-click native fallback');await app.keyboard.press('Escape');
|
||||
const other=[`/Books/Details/${book}`,`/Chapters/Details/${chapter}`,`/Characters/Details/${character}`,`/Locations/Details/${location}`,`/StoryAssets/Details/${asset}`,`/ProjectCollaborators?projectId=${project}`,`/Timeline/Settings?projectId=${project}`,'/ManageAccount',`/PlotThreads?projectId=${project}`];
|
||||
for(const route of other){stage='details/management '+route.split('?')[0];assert.equal((await tab.goto(base+route)).status(),200);assert.equal((await app.goto(base+route)).status(),200);for(const width of [1920,800,390]){await app.setViewportSize({width,height:1080});assert(await app.locator('main').evaluate(e=>e.scrollWidth<=e.clientWidth+1),'main overflow '+route+' '+width)}await app.setViewportSize({width:1920,height:1080});}
|
||||
// Pause real HTML before activation, compare key geometry on several domain shapes.
|
||||
for(const [area,id]of editors.filter(([a])=>['Books','Characters','Chapters','Locations','PlotLines'].includes(a))){
|
||||
stage='first paint '+area;let release,reached;const gate=new Promise(r=>release=r),blocked=new Promise(r=>reached=r);const url=base+`/${area}/Edit/${id}?recordpaint=1`;
|
||||
await app.route('**/record-parser-gate.js',async r=>{reached();await gate;await r.fulfill({contentType:'application/javascript',body:''})});
|
||||
await app.route(url,async r=>{const response=await r.fetch();await r.fulfill({response,body:(await response.text()).replace('</main>','<script src="/record-parser-gate.js"></script></main>')})});
|
||||
const loading=app.goto(url);try{await Promise.race([blocked,new Promise((_,reject)=>setTimeout(()=>reject(Error('Parser gate not reached')),10000))]);await frames(app);const sample=()=>app.locator('form.pd-record-form').evaluate(e=>{const r=e.getBoundingClientRect();return[r.x,r.y,r.width,...[...e.querySelectorAll('.pd-record-fields>div')].flatMap(n=>{const x=n.getBoundingClientRect();return[x.x,x.y,x.width,x.height]})]});const before=await sample();release();await loading;await frames(app);assert.deepEqual(await sample(),before,area+' initial layout shift');console.log('PASS zero record layout shift '+area)}finally{release();await app.unroute(url);await app.unroute('**/record-parser-gate.js')}
|
||||
}
|
||||
assert.deepEqual(failures,[]);console.log('PASS real authenticated Dev record workspaces: eight domains, real standalone install, four widths, Browser controls, validation/round-trip Save, six themes, keyboard/context menus, details/settings/management and first paint.');
|
||||
}finally{if(installed)await cdp.send('PWA.uninstall',{manifestId:base+'/Projects'}).catch(()=>{});await context.close();fs.rmSync(profile,{recursive:true,force:true})}
|
||||
})().catch(e=>{console.error('Stage:',stage,e);process.exitCode=1});
|
||||
74
PlotLine.Tests/Browser/record-workspaces.cjs
Normal file
74
PlotLine.Tests/Browser/record-workspaces.cjs
Normal file
@ -0,0 +1,74 @@
|
||||
// Real compiled Razor forms; loopback fixture has no database/workers.
|
||||
const { chromium }=require('playwright');
|
||||
const assert=require('node:assert/strict');
|
||||
const base='http://127.0.0.1:5238';
|
||||
const records=['Projects','Books','Chapters','Characters','Locations','StoryAssets','PlotLines','PlotThreads','ProjectMetrics'];
|
||||
async function frames(page){await page.evaluate(()=>new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r))))}
|
||||
async function recordGroup(page){const group=page.locator('.pd-context-group[aria-label="Record"] details[data-compact="true"]');if(await group.count()&&await group.getAttribute('open')===null)await group.locator('summary').click()}
|
||||
(async()=>{
|
||||
const browser=await chromium.launch();const failures=[];
|
||||
try{
|
||||
const web=await browser.newContext({viewport:{width:1920,height:1080}});const tab=await web.newPage();tab.on('pageerror',e=>failures.push(e.message));
|
||||
for(const record of records){
|
||||
const response=await tab.goto(`${base}/fixture?record=${record}`);assert.equal(response.status(),200,record);await frames(tab);
|
||||
assert.equal(await tab.evaluate(()=>window.PlotDirectorPwa.standalone),false);
|
||||
assert(await tab.locator('main button[type=submit]').filter({hasText:/Save/}).isVisible(),record+' browser Save remains');
|
||||
if(await tab.locator('.pd-record-fields').count())assert.equal(await tab.locator('.pd-record-fields').evaluate(e=>getComputedStyle(e).display),'flex');
|
||||
const width=await tab.locator('main form.pd-record-form').first().evaluate(e=>e.getBoundingClientRect().width);assert(width<=980.5,record+' browser width unchanged');
|
||||
}
|
||||
// Compare against the existing Browser CSS at resized widths, rather than treating Desktop rules as a Browser redesign.
|
||||
await tab.goto(base+'/fixture?record=Characters');await tab.addStyleTag({content:'.pd-record-group-label{display:none}'});
|
||||
for(const width of [1440,800,390]){
|
||||
await tab.setViewportSize({width,height:1080});await frames(tab);
|
||||
const sample=()=>tab.locator('main form.pd-record-form').evaluate(e=>({width:e.clientWidth,scroll:e.scrollWidth,fields:[...e.querySelectorAll('.form-control,.form-select')].map(n=>{const r=n.getBoundingClientRect();return[r.x,r.y,r.width,r.height]})}));
|
||||
const before=await sample();await tab.locator('link[href="/css/record-workspace.css"]').evaluate(e=>e.disabled=true);await frames(tab);assert.deepEqual(await sample(),before,'Browser layout unchanged at '+width);await tab.locator('link[href="/css/record-workspace.css"]').evaluate(e=>e.disabled=false);
|
||||
if(before.scroll>before.width+1)console.log('Existing Browser character-image panel overflow retained at '+width+'px; Desktop collapse verified separately.');
|
||||
}
|
||||
const desktop=await browser.newContext({viewport:{width:1920,height:1080}});await desktop.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));const app=await desktop.newPage();app.on('pageerror',e=>failures.push(e.message));
|
||||
for(const record of records){
|
||||
assert.equal((await app.goto(`${base}/fixture?record=${record}`)).status(),200,record);await frames(app);
|
||||
await recordGroup(app);
|
||||
const save=app.locator('[data-pwa-context-controls] button').filter({hasText:/^Save /});assert.equal(await save.count(),1,record+' single Save');assert(await save.isVisible());assert(await save.locator('svg').count());
|
||||
assert(await app.locator('main button[type=submit]').filter({hasText:/Save/}).isHidden(),record+' source accounted for');
|
||||
if(await app.locator('.pd-record-fields').count()){
|
||||
assert.equal(await app.locator('.pd-record-fields').evaluate(e=>getComputedStyle(e).display),'grid');
|
||||
assert((await app.locator('main form.pd-record-form').first().boundingBox()).width>1200,record+' canvas uses available space');
|
||||
}
|
||||
for(const width of [1440,800,390]){
|
||||
await app.setViewportSize({width,height:1000});await frames(app);
|
||||
assert(await app.locator('main form.pd-record-form').first().evaluate(e=>e.scrollWidth<=e.clientWidth+1),record+' no ordinary form overflow at '+width);
|
||||
}
|
||||
await app.setViewportSize({width:1920,height:1080});
|
||||
}
|
||||
await app.goto(base+'/fixture?record=Books');await recordGroup(app);
|
||||
// Invalid submit reaches existing unobtrusive field validation, and a valid submit reaches the original form/antiforgery fields.
|
||||
await app.locator('[name=BookTitle]').fill('');await app.locator('[data-pwa-context-controls] button').filter({hasText:'Save book'}).click();
|
||||
await app.locator('[data-valmsg-for=BookTitle].field-validation-error').waitFor();
|
||||
assert(await app.locator('[data-valmsg-for=BookTitle]').isVisible());
|
||||
await app.locator('[name=BookTitle]').fill('Revised book');
|
||||
const posted=app.waitForRequest(r=>r.method()==='POST'&&new URL(r.url()).pathname==='/Books/Save');
|
||||
await app.route('**/Books/Save',r=>r.fulfill({contentType:'text/html',body:'Saved fixture'}));
|
||||
await recordGroup(app);await app.locator('[data-pwa-context-controls] button').filter({hasText:'Save book'}).click();
|
||||
const body=(await posted).postData();assert.match(body,/name="BookTitle"\r\n\r\nRevised book/);assert.match(body,/name="BookID"\r\n\r\n12/);assert(body.includes('name="__RequestVerificationToken"'));
|
||||
await app.goto(base+'/fixture?record=Books');await app.locator('[name=BookTitle]').fill('Enter-saved book');
|
||||
const enterPost=app.waitForRequest(r=>r.method()==='POST'&&new URL(r.url()).pathname==='/Books/Save');await app.locator('[name=BookTitle]').press('Enter');assert((await enterPost).postData().includes('Enter-saved book'));
|
||||
await app.goto(base+'/fixture?record=Characters');await app.setViewportSize({width:3200,height:1080});
|
||||
assert(await app.locator('form.pd-record-form').evaluate(e=>e.getBoundingClientRect().width<=parseFloat(getComputedStyle(e).maxWidth)+1),'ultra-wide bounded form');
|
||||
await app.setViewportSize({width:1920,height:1080});
|
||||
for(const theme of ['warm-light','modern-light','modern-dark','warm-dark','rose-pink','baby-blue']){
|
||||
await app.evaluate(t=>{const r=document.documentElement;r.dataset.appTheme=t;r.dataset.theme=t.endsWith('-dark')?'dark':'light';r.dataset.bsTheme=r.dataset.theme;dispatchEvent(new CustomEvent('plotdirector:theme-changed',{detail:{theme:t}}));},theme);await app.screenshot({path:`/tmp/pd-record-characters-${theme}.png`,fullPage:true});
|
||||
assert(await app.locator('[name=CharacterName]').evaluate(e=>getComputedStyle(e).backgroundColor!=='rgba(0, 0, 0, 0)'));
|
||||
}
|
||||
// New layouts are stable before activation, not assembled by a late DOM pass.
|
||||
let release, reached;const gate=new Promise(r=>release=r),blocked=new Promise(r=>reached=r);
|
||||
await app.route('**/record-parser-gate.js',async r=>{reached();await gate;await r.fulfill({contentType:'application/javascript',body:''})});
|
||||
await app.route('**/fixture?record=Books&paint=1',async r=>{const response=await r.fetch();await r.fulfill({response,body:(await response.text()).replace('</main>','<script src="/record-parser-gate.js"></script></main>')})});
|
||||
const loading=app.goto(base+'/fixture?record=Books&paint=1');await blocked;await frames(app);
|
||||
const geometry=()=>app.locator('main form.pd-record-form').first().evaluate(e=>({width:e.getBoundingClientRect().width,fields:[...e.querySelectorAll('.pd-record-fields>div')].map(n=>{const r=n.getBoundingClientRect();return[r.x,r.y,r.width,r.height]})}));
|
||||
const before=await geometry();assert.equal(await app.evaluate(()=>document.readyState),'loading');
|
||||
assert.equal(await app.locator('[data-pwa-context-controls] button').filter({hasText:'Save book'}).count(),1);
|
||||
release();await loading;await frames(app);assert.deepEqual(await geometry(),before,'record layout unchanged across activation');
|
||||
assert.deepEqual(failures,[]);
|
||||
console.log('PASS record workspaces: nine real Razor forms, Browser widths/actions, Desktop grid/ribbon icons, 1920/1440/800/390 widths, validation and original form POST, all six themes, stable parser-paused first paint.');
|
||||
}finally{await browser.close()}
|
||||
})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
197
PlotLine.Tests/Browser/scene-workspace.cjs
Normal file
197
PlotLine.Tests/Browser/scene-workspace.cjs
Normal file
@ -0,0 +1,197 @@
|
||||
// Start the isolated --toolbar-browser-host; run with xvfb-run -a node scene-workspace.cjs.
|
||||
const { chromium } = require('playwright');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const base = 'http://127.0.0.1:5238';
|
||||
const url = base + '/fixture?page=scene-edit';
|
||||
const areas = ['overview', 'story', 'people', 'world', 'writer', 'continuity'];
|
||||
const editors = { SceneDetailsEditor: 'scene-details', ScenePurposeEditor: 'purpose', SceneMetricsEditor: 'metrics', SceneThreadsEditor: 'threads', SceneDependenciesEditor: 'dependencies', SceneCharactersEditor: 'characters', SceneCharacterAttributesEditor: 'attributes', SceneSuggestionsEditor: 'suggestions', SceneKnowledgeEditor: 'knowledge', SceneRelationshipsEditor: 'relationships', SceneLocationsEditor: 'locations', SceneAssetsEditor: 'assets', SceneNotesEditor: 'notes', SceneChecklistEditor: 'checklist', SceneWorkflowEditor: 'workflow', SceneAttachmentsEditor: 'attachments', SceneContinuityEditor: 'warnings' };
|
||||
const settle = page => page.waitForTimeout(100);
|
||||
async function installRoutes(page) {
|
||||
// Load actual compiled Razor editor fragments without touching any database.
|
||||
await page.route(/\/(Scenes|Warnings)\/Scene\w+Editor\?/, async route => {
|
||||
const name = new URL(route.request().url()).pathname.split('/').pop();
|
||||
const response = await page.request.get(url + '&editor=' + editors[name]);
|
||||
assert.equal(response.status(), 200, name);
|
||||
await route.fulfill({ response });
|
||||
});
|
||||
}
|
||||
async function select(page, area, pwa) {
|
||||
if (pwa) {
|
||||
if (await page.locator('#ribbon-surface').isHidden()) await page.locator('[data-ribbon-tab][aria-selected="true"]').click();
|
||||
const group = page.locator('.pd-context-group[aria-label="Edit Scene"]');
|
||||
const collapsed = group.locator('details[data-compact="true"]');
|
||||
if (await collapsed.count() && !await collapsed.getAttribute('open')) await collapsed.locator('summary').click();
|
||||
await group.locator('button.pd-context-command').filter({ hasText: new RegExp('^' + area + '$', 'i') }).click();
|
||||
} else await page.locator(`[data-scene-area-command="${area}"]`).click();
|
||||
await settle(page);
|
||||
assert.equal(await page.locator('[data-scene-workspace]').getAttribute('data-scene-area'), area);
|
||||
}
|
||||
async function verify(page, pwa) {
|
||||
const errors = []; page.on('pageerror', error => errors.push(error.message));
|
||||
await installRoutes(page);
|
||||
await page.goto(url);
|
||||
await page.locator('[data-scene-workspace]').waitFor();
|
||||
if (pwa) {
|
||||
if (await page.locator('#ribbon-surface').isHidden()) await page.locator('[data-ribbon-tab][aria-selected="true"]').click();
|
||||
await page.locator('.pd-context-group[aria-label="Edit Scene"]').waitFor();
|
||||
}
|
||||
assert.equal(await page.locator('.scene-workspace-nav').isVisible(), !pwa);
|
||||
assert.equal(await page.locator('.scene-edit-heading h1').isVisible(), !pwa);
|
||||
assert(await page.locator('[data-scene-identity]').isVisible());
|
||||
assert.equal(await page.locator('[data-scene-summary-part]:visible').count(), 6);
|
||||
const overviewBounds = await page.locator('#scene-workspace-canvas').boundingBox();
|
||||
for (const card of await page.locator('[data-scene-summary-part]').all()) {
|
||||
const bounds = await card.boundingBox();
|
||||
assert(bounds.y >= overviewBounds.y - 1 && bounds.y + bounds.height <= overviewBounds.y + overviewBounds.height + 1, 'both summary rows stay within the desktop workbench');
|
||||
}
|
||||
if (pwa) {
|
||||
assert.equal(await page.locator('.pd-context-group[aria-label="Edit Scene"] .pd-context-command').count(), 6);
|
||||
assert.equal(await page.locator('.pd-context-group[aria-label="Edit Scene"] > .pd-ribbon-group-label').textContent(), 'Edit Scene');
|
||||
}
|
||||
const prefix = pwa ? 'pwa' : 'browser';
|
||||
await page.screenshot({ path: `/tmp/scene-workspace-${prefix}-overview.png`, fullPage: true });
|
||||
const dashboardColumns = await page.locator('.scene-inspector-v2-grid').evaluate(e => getComputedStyle(e).gridTemplateColumns);
|
||||
await page.locator('[data-scene-editor="scene-details"]').click();
|
||||
await page.locator('[data-scene-editor-body] form').waitFor();
|
||||
assert.equal(await page.locator('.scene-inspector-v2-grid').evaluate(e => getComputedStyle(e).gridTemplateColumns.split(' ').length), dashboardColumns.split(' ').length, 'Overview keeps its three-column arrangement with inspector');
|
||||
await page.locator('[data-scene-editor-close]').first().click();
|
||||
for (const area of areas) {
|
||||
await select(page, area, pwa);
|
||||
assert.equal(await page.locator('[data-scene-summary-part]:visible').count(), area === 'overview' ? 6 : 1);
|
||||
if (pwa) assert.equal(await page.locator('.pd-context-group[aria-label="Edit Scene"] [aria-pressed="true"]').count(), 1);
|
||||
await page.reload(); await settle(page);
|
||||
assert.equal(await page.locator('[data-scene-workspace]').getAttribute('data-scene-area'), area, 'refresh retains workspace');
|
||||
}
|
||||
await select(page, 'overview', pwa);
|
||||
for (const area of areas.slice(1)) {
|
||||
await page.locator(`[data-scene-card-area="${area}"]`).click();
|
||||
assert.equal(await page.locator('[data-scene-workspace]').getAttribute('data-scene-area'), area);
|
||||
await select(page, 'overview', pwa);
|
||||
}
|
||||
// History retains the area, and dashboard editing enters its specialist workspace first.
|
||||
await page.locator('[data-scene-summary-part="people"] [data-scene-editor="characters"]').first().click();
|
||||
assert.equal(await page.locator('[data-scene-workspace]').getAttribute('data-scene-area'), 'people');
|
||||
assert(await page.locator('[data-scene-editor-overlay]').isHidden());
|
||||
await select(page, 'story', pwa); await page.goBack(); await settle(page);
|
||||
assert.equal(await page.locator('[data-scene-workspace]').getAttribute('data-scene-area'), 'people');
|
||||
await page.goForward(); await settle(page);
|
||||
assert.equal(await page.locator('[data-scene-workspace]').getAttribute('data-scene-area'), 'story');
|
||||
await select(page, 'people', pwa);
|
||||
assert.equal(await page.locator('.scene-inspector-v2-character-list > li:visible').count(), 8, 'focused area shows complete list');
|
||||
const canvas = page.locator('#scene-workspace-canvas');
|
||||
const before = await canvas.boundingBox();
|
||||
const columnsBefore = await page.locator('.scene-inspector-v2-grid').evaluate(e => getComputedStyle(e).gridTemplateColumns.split(' ').length);
|
||||
await page.screenshot({ path: `/tmp/scene-workspace-${prefix}-people.png`, fullPage: true });
|
||||
await page.locator('[data-scene-editor="relationships"]').click();
|
||||
await page.locator('[data-scene-editor-body] form').first().waitFor();
|
||||
assert.equal(await page.locator('[data-scene-workspace]').getAttribute('data-scene-area'), 'people');
|
||||
const opened = await canvas.boundingBox();
|
||||
assert.equal(opened.x, before.x); assert.equal(opened.y, before.y);
|
||||
assert(opened.width < before.width - 300, 'inspector consumes width');
|
||||
assert.equal(await page.locator('.scene-inspector-v2-grid').evaluate(e => getComputedStyle(e).gridTemplateColumns.split(' ').length), columnsBefore);
|
||||
assert.equal(await page.locator('[data-scene-summary-part]:visible').count(), 1);
|
||||
assert(await page.locator('[data-scene-editor-body] input[name="__RequestVerificationToken"]').count());
|
||||
await page.screenshot({ path: `/tmp/scene-workspace-${prefix}-relationships.png`, fullPage: true });
|
||||
await page.locator('[data-scene-editor-resizer]').press('ArrowLeft');
|
||||
assert((await page.locator('[data-scene-editor-overlay]').boundingBox()).width >= 520, 'keyboard resizing retains usable editor');
|
||||
await page.locator('#RelationshipCharacterAID').selectOption('1');
|
||||
await page.locator('#RelationshipCharacterBID').selectOption('2');
|
||||
await page.locator('#RelationshipDescription').fill('A shared discovery');
|
||||
await page.route('**/Scenes/AddRelationshipEvent', async route => {
|
||||
assert.match(route.request().postData(), /A shared discovery/);
|
||||
assert.match(route.request().postData(), /__RequestVerificationToken/);
|
||||
const response = await page.request.get(url + '&editor=relationships');
|
||||
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ success: true, editorHtml: await response.text() }) });
|
||||
});
|
||||
await page.getByRole('button', { name: 'Add relationship event' }).click();
|
||||
await page.waitForFunction(() => !document.querySelector('[data-scene-editor-save]')?.disabled);
|
||||
assert.equal(await page.locator('[data-scene-workspace]').getAttribute('data-scene-area'), 'people');
|
||||
assert(await page.locator('[data-scene-editor-overlay]').isVisible(), 'relationship workflow stays open after adding');
|
||||
await page.locator('[data-scene-editor-close]').first().click();
|
||||
assert(Math.abs((await canvas.boundingBox()).width - before.width) < 2, 'closing returns all width');
|
||||
await select(page, 'story', pwa);
|
||||
await page.locator('[data-scene-editor="purpose"]').last().click();
|
||||
await page.locator('textarea[name="ScenePurposeNotes"]').fill('Updated purpose');
|
||||
let valid = false;
|
||||
await page.route('**/Scenes/SaveScenePurpose', async route => {
|
||||
assert.match(route.request().postData(), /Updated purpose/);
|
||||
await route.fulfill({ status: valid ? 200 : 400, contentType: 'application/json', body: JSON.stringify(valid ? { success: true, html: { story: '<article class="scene-inspector-v2-card" data-scene-summary-part="story"><p class="eyebrow">Story</p><h3>Saved purpose</h3></article>' } } : { success: false, message: 'Please review the purpose.' }) });
|
||||
});
|
||||
await page.locator('[data-scene-editor-save]').click();
|
||||
await page.getByText('Please review the purpose.').waitFor();
|
||||
assert(await page.locator('[data-scene-editor-overlay]').isVisible());
|
||||
valid = true; await page.locator('[data-scene-editor-save]').click();
|
||||
await page.locator('[data-scene-editor-overlay]').waitFor({ state: 'hidden' });
|
||||
assert.equal(await page.locator('[data-scene-workspace]').getAttribute('data-scene-area'), 'story');
|
||||
assert(await page.getByText('Saved purpose').isVisible(), 'AJAX summary refresh keeps selected area');
|
||||
// Reload restores the unmodified fixture; Cancel sends no write.
|
||||
await page.reload(); await select(page, 'story', pwa);
|
||||
await page.locator('[data-scene-editor="purpose"]').last().click();
|
||||
await page.locator('textarea[name="ScenePurposeNotes"]').fill('Discard me');
|
||||
await page.locator('[data-scene-editor-close]').first().click();
|
||||
await page.locator('[data-scene-editor="purpose"]').last().click();
|
||||
await page.locator('textarea[name="ScenePurposeNotes"]').waitFor();
|
||||
assert.equal(await page.locator('textarea[name="ScenePurposeNotes"]').inputValue(), 'Establish the mystery');
|
||||
await page.locator('[data-scene-editor-close]').first().click();
|
||||
await select(page, 'continuity', pwa);
|
||||
assert.equal(await page.locator('[data-scene-summary-part="continuity"] li:visible').count(), 6);
|
||||
await page.locator('[data-scene-editor="warnings"]').click();
|
||||
await page.locator('[data-scene-editor-body] .scene-inspector-editor-form').waitFor();
|
||||
assert.equal(await page.getByRole('button', { name: 'Dismiss', exact: true }).count(), 6, 'existing per-warning actions remain accessible');
|
||||
assert(await page.getByRole('button', { name: 'Revalidate scene' }).isVisible());
|
||||
await page.locator('[data-scene-editor-close]').first().click();
|
||||
for (const [area, keys] of Object.entries({ story: ['purpose', 'metrics', 'threads', 'dependencies'], people: ['characters', 'attributes', 'suggestions', 'knowledge', 'relationships'], world: ['locations', 'assets'], writer: ['notes', 'checklist', 'workflow', 'attachments'] })) {
|
||||
await select(page, area, pwa);
|
||||
for (const key of keys) {
|
||||
await page.locator(`[data-scene-summary-part="${area}"] [data-scene-editor="${key}"]`).last().click();
|
||||
await page.locator('[data-scene-editor-body] .scene-inspector-editor-form').waitFor();
|
||||
assert.equal(await page.locator('[data-scene-workspace]').getAttribute('data-scene-area'), area);
|
||||
await page.locator('[data-scene-editor-close]').first().click();
|
||||
}
|
||||
}
|
||||
for (const theme of ['modern-dark', 'warm-dark', 'modern-light', 'warm-light', 'rose-pink', 'baby-blue']) {
|
||||
await page.evaluate(theme => { document.documentElement.dataset.appTheme = theme; document.documentElement.dataset.theme = theme.endsWith('dark') ? 'dark' : 'light'; }, theme);
|
||||
await select(page, 'people', pwa);
|
||||
await page.locator('[data-scene-editor="relationships"]').click();
|
||||
await page.locator('[data-scene-editor-body] form').first().waitFor();
|
||||
const colours = await page.locator('[data-scene-summary-part="people"]').evaluate(e => ({ colour: getComputedStyle(e).color, background: getComputedStyle(e).backgroundColor }));
|
||||
assert.notEqual(colours.colour, colours.background);
|
||||
await page.screenshot({ path: `/tmp/scene-workspace-${prefix}-${theme}.png`, fullPage: true });
|
||||
await page.locator('[data-scene-editor-close]').first().click();
|
||||
}
|
||||
for (const width of [1100, 820, 390]) {
|
||||
await page.setViewportSize({ width, height: 900 }); await settle(page);
|
||||
assert(await page.locator('[data-scene-summary-part="people"]').isVisible());
|
||||
await page.locator('[data-scene-editor="relationships"]').click();
|
||||
await page.locator('[data-scene-editor-body] form').first().waitFor();
|
||||
assert(await page.locator('[data-scene-editor-close]').first().isVisible());
|
||||
const bounds = await page.locator('[data-scene-editor-overlay]').boundingBox();
|
||||
assert(bounds.width <= width && bounds.x >= 0 && bounds.x + bounds.width <= width + 1);
|
||||
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'no document horizontal overflow');
|
||||
if (width <= 900) assert(await page.locator('[data-scene-editor-overlay]').evaluate(e => {
|
||||
const rect = e.getBoundingClientRect();
|
||||
return !!document.elementFromPoint(rect.left + rect.width / 2, rect.top + 100)?.closest('[data-scene-editor-overlay]');
|
||||
}), 'canvas commands cannot show through mobile inspector');
|
||||
await page.screenshot({ path: `/tmp/scene-workspace-${prefix}-${width}.png`, fullPage: true });
|
||||
await page.locator('[data-scene-editor-close]').first().click();
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
(async () => {
|
||||
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-scene-workspace-'));
|
||||
const context = await chromium.launchPersistentContext(profile, { headless: false, viewport: { width: 1600, height: 1000 } });
|
||||
try {
|
||||
const browserPage = context.pages()[0]; await verify(browserPage, false);
|
||||
const cdp = await context.browser().newBrowserCDPSession(); const manifestId = base + '/Projects';
|
||||
await cdp.send('PWA.install', { manifestId, installUrlOrBundleUrl: url });
|
||||
await cdp.send('PWA.changeAppUserSettings', { manifestId, displayMode: 'standalone' });
|
||||
const opened = context.waitForEvent('page'); await cdp.send('PWA.launch', { manifestId, url });
|
||||
const app = await opened; await app.waitForLoadState();
|
||||
assert(await app.evaluate(() => matchMedia('(display-mode: standalone)').matches));
|
||||
await verify(app, true);
|
||||
console.log('PASS Edit Scene: browser and installed PWA, six areas/cards, shared ribbon state/history, stable inspectors, width recovery, real Story/Relationships/Continuity forms, AJAX validation/save/cancel, six themes and responsive layouts.');
|
||||
} finally { await context.close(); }
|
||||
})().catch(error => { console.error(error); process.exit(1); });
|
||||
43
PlotLine.Tests/Browser/timeline-plot-retirement.cjs
Normal file
43
PlotLine.Tests/Browser/timeline-plot-retirement.cjs
Normal file
@ -0,0 +1,43 @@
|
||||
const { chromium } = require('playwright');
|
||||
const assert = require('node:assert/strict');
|
||||
(async () => {
|
||||
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROMIUM_PATH });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
const errors = [];
|
||||
page.on('pageerror', e => errors.push(e.message));
|
||||
if (process.env.PLOT_ASSET_ORIGIN) {
|
||||
await page.route(/\/(?:css\/(?:site|plotline-theme|application-shell)\.css|js\/site\.js)(?:\?.*)?$/, async route => {
|
||||
await route.fulfill({ response: await route.fetch({ url: process.env.PLOT_ASSET_ORIGIN + new URL(route.request().url()).pathname }) });
|
||||
});
|
||||
}
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem('plotline.timeline.visibility', JSON.stringify({ 'plot-lines': false, 'scene-cards': true }));
|
||||
localStorage.setItem('plotline.timeline.collapsed', JSON.stringify(['plot-lines', 'plot-group-legacy']));
|
||||
});
|
||||
await page.goto('http://127.0.0.1:5238/fixture?page=timeline-render');
|
||||
assert.equal(await page.locator('.timeline-scene-card').count(), 2);
|
||||
assert.ok(await page.locator('.timeline-book-title').count());
|
||||
assert.ok(await page.locator('.timeline-chapter-title').count());
|
||||
assert.equal(await page.locator('.plot-lane-board,.plot-lane-row,.thread-marker,[data-plot-line-svg],[data-plot-line-health-svg],.character-lane-board').count(), 0);
|
||||
assert.equal(await page.locator('[name="ShowPlotLines"],[data-timeline-toggle="plot-lines"],[data-collapse-toggle="plot-lines"]').count(), 0);
|
||||
assert.equal(await page.locator('[data-timeline-entity-jump] option').filter({ hasText: 'Plot line:' }).count(), 0);
|
||||
assert.equal(await page.locator('select[name="PlotLineID"]').count(), 1);
|
||||
assert.equal(await page.locator('select[name="PlotThreadID"]').count(), 1);
|
||||
assert.equal(await page.locator('.timeline-scene-card[data-scene-id="101"]').evaluate(el => el.classList.contains('filter-match') && el.classList.contains('focus-match')), true);
|
||||
assert.equal(await page.locator('.timeline-scene-card[data-scene-id="102"]').evaluate(el => el.classList.contains('filter-dim') && el.classList.contains('focus-dim')), true);
|
||||
await page.locator('[data-timeline-search]').evaluate(el => el.closest('details').open = true);
|
||||
await page.locator('[data-timeline-search]').fill('First clues');
|
||||
assert.ok(await page.locator('.timeline-scene-card[data-scene-id="101"]').isVisible());
|
||||
assert.equal(await page.locator('.timeline-scene-card[data-scene-id="102"]').evaluate(el => el.classList.contains('search-dim')), true);
|
||||
await page.locator('[data-timeline-search]').fill('');
|
||||
assert.ok(await page.locator('.timeline-scene-card[data-scene-id="102"]').isVisible());
|
||||
const href = await page.locator('.timeline-scene-card[data-scene-id="101"]').getAttribute('href');
|
||||
assert.match(href, /SelectedSceneID=101/i);
|
||||
await page.goto('http://127.0.0.1:5238/fixture?page=timeline-render&scenario=true');
|
||||
assert.deepEqual(await page.locator('.timeline-scene-card').evaluateAll(items => items.map(el => el.dataset.sceneId)), ['102', '101']);
|
||||
assert.equal(await page.locator('.plot-lane-board').count(), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
await page.screenshot({ path: '/tmp/timeline-plot-retirement.png', fullPage: true });
|
||||
await browser.close();
|
||||
console.log('PASS: real Timeline Razor renders scenes/books/chapters, membership focus/search and supplied scenario order; no plot lanes/health/controls/jumps; legacy preferences ignored');
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
94
PlotLine.Tests/DevBrowserIdentity.cs
Normal file
94
PlotLine.Tests/DevBrowserIdentity.cs
Normal file
@ -0,0 +1,94 @@
|
||||
using System.Diagnostics;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Services;
|
||||
|
||||
// Explicit operational test command, never registered in or deployed with the web application.
|
||||
// Uses normal user repositories and password verification; does not issue cookies or change authentication.
|
||||
internal static class DevBrowserIdentity
|
||||
{
|
||||
private sealed record Identity(int UserID, string Email, string Password, string Database);
|
||||
public static async Task RunAsync(string[] args)
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) throw new PlatformNotSupportedException("Development provisioning runs only on the Linux development host");
|
||||
if (args.Length != 3 || args[1] is not ("create" or "cleanup") || !Path.GetFullPath(args[2]).StartsWith("/tmp/pd-dev-browser-", StringComparison.Ordinal))
|
||||
throw new InvalidOperationException("Use --dev-browser-identity create|cleanup /tmp/pd-dev-browser-<unique>.json");
|
||||
var start = new ProcessStartInfo("sudo") { RedirectStandardOutput = true, RedirectStandardError = true };
|
||||
foreach (var part in new[] { "-n", "cat", "/etc/plotdirector/plotdirector.env" }) start.ArgumentList.Add(part);
|
||||
using var process = Process.Start(start)!;
|
||||
var environment = await process.StandardOutput.ReadToEndAsync();
|
||||
await process.WaitForExitAsync();
|
||||
if (process.ExitCode != 0) throw new InvalidOperationException("Development configuration unavailable");
|
||||
var connectionString = environment.Split('\n').Single(line => line.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=', 2)[1].Trim().Trim('"', '\'');
|
||||
if (new SqlConnectionStringBuilder(connectionString).InitialCatalog != "PlotDirector_Development") throw new InvalidOperationException("Only the development database is permitted");
|
||||
using var connection = new SqlConnection(connectionString);
|
||||
await connection.OpenAsync();
|
||||
using var verify = connection.CreateCommand(); verify.CommandText = "SELECT DB_NAME()";
|
||||
if ((string?)await verify.ExecuteScalarAsync() != "PlotDirector_Development") throw new InvalidOperationException("Development database verification failed");
|
||||
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?> { ["ConnectionStrings:DefaultConnection"] = connectionString }).Build();
|
||||
var factory = new SqlConnectionFactory(config);
|
||||
var users = new UserRepository(factory);
|
||||
var path = Path.GetFullPath(args[2]);
|
||||
if (args[1] == "create")
|
||||
{
|
||||
if (File.Exists(path)) throw new InvalidOperationException("Refusing to overwrite an identity file");
|
||||
// A uniquely named copy-only backup precedes all provisioning writes.
|
||||
var backup = $"/var/opt/mssql/backup/pwa-desktop-{DateTime.UtcNow:yyyyMMddTHHmmss}-{Guid.NewGuid():N}.bak";
|
||||
using var command = connection.CreateCommand(); command.CommandTimeout = 300;
|
||||
command.CommandText = "BACKUP DATABASE [PlotDirector_Development] TO DISK = @path WITH COPY_ONLY, CHECKSUM;";
|
||||
command.Parameters.AddWithValue("@path", backup);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
var checkBackup = new ProcessStartInfo("sudo") { RedirectStandardOutput = true, RedirectStandardError = true };
|
||||
foreach (var part in new[] { "-n", "docker", "exec", "atlas-sql-server", "test", "-s", backup }) checkBackup.ArgumentList.Add(part);
|
||||
using var backupCheck = Process.Start(checkBackup)!;
|
||||
await backupCheck.WaitForExitAsync();
|
||||
if (backupCheck.ExitCode != 0) throw new InvalidOperationException("Development backup file verification failed");
|
||||
var email = $"pwa-browser-{Guid.NewGuid():N}@example.invalid";
|
||||
var password = Convert.ToBase64String(RandomNumberGenerator.GetBytes(36)) + "aA1!";
|
||||
var user = await users.CreateAsync(email, "Desktop Verification Author", new PasswordService().HashPassword(password), emailConfirmed: false);
|
||||
// Exercise the same verification token/confirmation repositories as the normal account flow.
|
||||
// The Dev-only mailbox belongs to this isolated test; no external email or token logging is needed.
|
||||
var token = Guid.NewGuid();
|
||||
await new AuthenticationRepository(factory).CreateEmailVerificationTokenAsync(user.UserID, token, DateTime.UtcNow.AddMinutes(30));
|
||||
if (!await users.ConfirmEmailAsync(user.UserID, token)) throw new InvalidOperationException("Test mailbox verification failed");
|
||||
await using var stream = new FileStream(path, new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite });
|
||||
await JsonSerializer.SerializeAsync(stream, new Identity(user.UserID, email, password, "PlotDirector_Development"));
|
||||
Console.WriteLine("Dedicated development browser identity provisioned through normal account repositories; credentials stored privately. No production access.");
|
||||
}
|
||||
else
|
||||
{
|
||||
var identity = JsonSerializer.Deserialize<Identity>(await File.ReadAllTextAsync(path))!;
|
||||
var user = await users.GetByEmailAsync(identity.Email);
|
||||
if (identity.Database != "PlotDirector_Development" || !identity.Email.StartsWith("pwa-browser-") || !identity.Email.EndsWith("@example.invalid") || user?.UserID != identity.UserID)
|
||||
throw new InvalidOperationException("Refusing cleanup: identity scope mismatch");
|
||||
// Use the complete application workflow: it removes owned projects/files before the user.
|
||||
// The low-level user repository deliberately refuses accounts which still own projects.
|
||||
using var handler = new HttpClientHandler { CookieContainer = new CookieContainer(), AllowAutoRedirect = false };
|
||||
using var client = new HttpClient(handler) { BaseAddress = new Uri("https://dev.plotdirector.com"), Timeout = TimeSpan.FromMinutes(2) };
|
||||
static string Token(string html)
|
||||
{
|
||||
var match = Regex.Match(html, "<input\\b(?=[^>]*\\bname=\"__RequestVerificationToken\")[^>]*\\bvalue=\"([^\"]+)\"");
|
||||
return match.Success ? WebUtility.HtmlDecode(match.Groups[1].Value) : throw new InvalidOperationException("Development antiforgery token unavailable");
|
||||
}
|
||||
var login = await client.GetStringAsync("/Account/Login");
|
||||
using var signedIn = await client.PostAsync("/Account/Login", new FormUrlEncodedContent(new Dictionary<string, string> {
|
||||
["Email"] = identity.Email, ["Password"] = identity.Password, ["__RequestVerificationToken"] = Token(login)
|
||||
}));
|
||||
if (signedIn.StatusCode != HttpStatusCode.Found || signedIn.Headers.Location?.OriginalString != "/Projects")
|
||||
throw new InvalidOperationException("Normal development login failed during cleanup");
|
||||
var account = await client.GetStringAsync("/ManageAccount");
|
||||
using var deleted = await client.PostAsync("/ManageAccount/HardDeleteAccount", new FormUrlEncodedContent(new Dictionary<string, string> {
|
||||
["confirmationEmail"] = identity.Email, ["__RequestVerificationToken"] = Token(account)
|
||||
}));
|
||||
if (deleted.StatusCode != HttpStatusCode.Found || await users.GetByEmailAsync(identity.Email) is not null)
|
||||
throw new InvalidOperationException("Normal development account cleanup failed");
|
||||
File.Delete(path);
|
||||
Console.WriteLine("Dedicated development identity and its fixture data removed; private credential file deleted.");
|
||||
}
|
||||
}
|
||||
}
|
||||
173
PlotLine.Tests/PlotHealthTests.cs
Normal file
173
PlotLine.Tests/PlotHealthTests.cs
Normal file
@ -0,0 +1,173 @@
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using System.Text.Json;
|
||||
|
||||
internal static class PlotHealthTests
|
||||
{
|
||||
public static void RolesAndClocks()
|
||||
{
|
||||
foreach (var role in new[] { "Introduced", "Developed", "Complicated", "Clue Planted", "Question Raised", "Question Answered", "False Lead", "Revealed", "Payoff", "Resolved", "Contradicted", "Retconned" })
|
||||
Check(PlotHealthProgressPolicy.IsMeaningful(role), $"Meaningful role omitted: {role}");
|
||||
Check(!PlotHealthProgressPolicy.IsMeaningful("Mentioned") && !PlotHealthProgressPolicy.IsMeaningful("Note"), "Non-progress policy changed");
|
||||
var f = new Fixture();
|
||||
var empty = f.Run();
|
||||
Check(Find(empty, "H001").All(x => x.Level == PlotHealthLevel.Information), "Unstarted threads are informational");
|
||||
Check(!Find(empty, "H002").Any(), "Planned unstarted thread must not be called quiet");
|
||||
f.Add(11, 1, "Introduced"); f.Add(11, 5, "Developed"); f.Add(11, 25, "Mentioned"); f.Add(11, 29, "Note");
|
||||
var before = JsonSerializer.Serialize(f.Data());
|
||||
var result = f.Run();
|
||||
var thread = result.Lines[0].Threads[0];
|
||||
Check(thread.ScenesSinceTouch == 1 && thread.ScenesSinceProgress == 25, "Mention and Note must change touch, not progress");
|
||||
Check(thread.LastProgress?.SceneID == 5 && thread.LastTouch?.SceneID == 29, "Clock evidence must identify its own event");
|
||||
Check(Find(result, "H002").Any(x => x.ScenesWithoutProgress == 25), "Trailing progress silence missing");
|
||||
Check(Find(result, "H007").Any(), "Planned activity mismatch missing");
|
||||
Check(JsonSerializer.Serialize(f.Data()) == before, "Evaluation must not mutate canonical data");
|
||||
f.Add(11, 28, "Developed");
|
||||
Check(f.Run().Lines[0].Threads[0].ScenesSinceProgress == 2, "Developed must reset progress clock");
|
||||
f = new Fixture(); f.Add(11, 1, "Introduced");
|
||||
Check(!Find(f.Run(cutoff: 10), "H003").Any(), "Recent introduction should not need review");
|
||||
Check(Find(f.Run(cutoff: 11), "H003").Any(), "Introduction without development should use the same 10-scene threshold");
|
||||
f.Add(11, 20, "Introduced");
|
||||
Check(Find(f.Run(), "H003").Any(), "Repeated introduction is not development");
|
||||
f = new Fixture(); f.Add(11, 1, "Introduced"); f.Add(11, 1, "Resolved");
|
||||
Check(!Find(f.Run(), "H002").Any(), "Same-scene resolution should stop trailing progress silence");
|
||||
Check(!Find(f.Run(), "H003").Any(), "Same-scene closure must not be labelled undeveloped merely because event order is unknown");
|
||||
f = new Fixture(); f.Add(11, 1, "Mentioned"); f.Add(11, 28, "Note");
|
||||
Check(Find(f.Run(), "H002").Any(), "Non-progress touches must not hide absence of meaningful progress");
|
||||
}
|
||||
|
||||
public static void QuestionsClosureAndStatus()
|
||||
{
|
||||
var f = new Fixture(); f.Add(11, 3, "Question Raised");
|
||||
Check(Find(f.Run(), "H004").Any(), "Open question missing");
|
||||
f.Add(11, 6, "Revealed");
|
||||
Check(Find(f.Run(), "H004").Single().Evidence.Any(e => e.Signal.Contains("Revealed")), "Reveal evidence must be shown without treating it as an answer");
|
||||
f.Add(11, 8, "Question Answered"); Check(!Find(f.Run(), "H004").Any(), "Later answer should satisfy coarse question check");
|
||||
f.Add(11, 9, "Question Raised"); Check(Find(f.Run(), "H004").Any(), "Earlier answer must not answer a later question");
|
||||
foreach (var closure in new[] { "Payoff", "Revealed", "Question Answered", "Resolved" })
|
||||
{
|
||||
f = new Fixture(); f.Add(11, 2, "Clue Planted");
|
||||
Check(Find(f.Run(), "H005").Any(), "Unclosed clue missing");
|
||||
f.Add(11, 3, closure); Check(!Find(f.Run(), "H005").Any(), $"Clue closure role ignored: {closure}");
|
||||
}
|
||||
f = new Fixture(); f.Threads[0].ThreadStatusName = "Ready For Payoff"; f.Add(11, 1, "Developed");
|
||||
Check(Find(f.Run(), "H006").Any(), "Ready status without payoff missing");
|
||||
f.Add(11, 4, "Payoff"); Check(!Find(f.Run(), "H006").Any(), "Payoff evidence ignored");
|
||||
f = new Fixture(); f.Threads[0].ThreadStatusName = "Resolved"; f.Add(11, 2, "Resolved"); f.Add(11, 3, "Mentioned"); f.Add(11, 5, "Developed");
|
||||
Check(Find(f.Run(), "H008").Any(x => x.Level == PlotHealthLevel.Warning), "Development after explicit resolution should be visible");
|
||||
Check(Find(f.Run(), "H007").Any(), "Closed status with positioned later activity should be reviewed");
|
||||
f = new Fixture(); f.Threads[0].ThreadStatusName = "Abandoned"; f.Add(11, 2, "Note", "Abandon"); f.Add(11, 4, "Developed");
|
||||
Check(Find(f.Run(), "H007").Any() && Find(f.Run(), "H008").Any(), "Positioned abandonment and later progress missing");
|
||||
f = new Fixture(); f.Threads[0].ThreadStatusName = "Introduced"; f.Add(11, 2, "Introduced"); f.Add(11, 3, "Developed");
|
||||
Check(Find(f.Run(), "H007").Any(), "Introduced/later development mismatch missing");
|
||||
f = new Fixture(); f.Add(11, 2, "Payoff"); f.Add(11, 5, "Introduced");
|
||||
Check(Find(f.Run(), "H009").Single().Level == PlotHealthLevel.Warning, "Payoff before introduction missing");
|
||||
f = new Fixture(); f.Threads[0].IntroducedSceneID = 5; f.Threads[0].ActualResolutionSceneID = 10;
|
||||
f.Add(11, 2, "Introduced"); f.Add(11, 12, "Developed");
|
||||
Check(Find(f.Run(), "H010").Single().Evidence.Any(e => e.SceneID == 12), "Outside-boundary evidence missing");
|
||||
f.Add(11, 8, "Resolved");
|
||||
Check(Find(f.Run(), "H008").Any(x => x.Title == "Resolution/boundary review"), "Competing resolution positions should be shown");
|
||||
// Discovery-style contradictions are fixtures only; evaluator has no manuscript-specific paths.
|
||||
f = new Fixture(); f.Threads[0].ThreadTitle = "Proof and Belonging"; f.Threads[0].IntroducedSceneID = 8; f.Threads[0].ActualResolutionSceneID = 9;
|
||||
f.Add(11, 6, "Developed"); f.Add(11, 8, "Revealed"); f.Add(11, 9, "Payoff");
|
||||
Check(Find(f.Run(), "H007").Any() && Find(f.Run(), "H010").Any(), "Discovery Planned/payoff/boundary contradiction lost");
|
||||
}
|
||||
|
||||
public static void TargetsScopeAndRollup()
|
||||
{
|
||||
var f = new Fixture(); var branch = f.Add(11, 2, "Developed", "Branch"); f.Targets.Add(new() { ThreadEventID = branch.ThreadEventID, TargetPlotLineID = 2, SourcePlotLineID = 1, StructuralType = "Branch" });
|
||||
Check(Find(f.Run(), "H011").Any(), "Missing target continuation missing");
|
||||
f.Add(22, 4, "Mentioned"); Check(!Find(f.Run(), "H011").Any(), "Recorded target continuation should satisfy branch check");
|
||||
f.Lines.Add(new() { PlotLineID = 3, ProjectID = 7, PlotLineName = "Third route" });
|
||||
branch.CanonicalStructuralType = "Split"; f.Targets.Add(new() { ThreadEventID = branch.ThreadEventID, TargetPlotLineID = 3, SourcePlotLineID = 1, StructuralType = "Split" });
|
||||
Check(Find(f.Run(), "H011").Single().Explanation.Contains("Third route"), "Each split target must be checked separately");
|
||||
branch.CanonicalStructuralType = "Merge"; f.Targets.Clear(); f.Targets.Add(new() { ThreadEventID = branch.ThreadEventID, TargetPlotLineID = 999, SourcePlotLineID = 1, StructuralType = "Merge" });
|
||||
Check(Find(f.Run(), "H011").Single().Level == PlotHealthLevel.Warning, "Missing explicit merge target must be distinguished from hidden target");
|
||||
f.Targets.Clear(); Check(Find(f.Run(), "H011").Any(x => x.Level == PlotHealthLevel.Warning), "Absent target record must be detected");
|
||||
f = new Fixture(); f.Add(11, 2, "Developed"); f.Add(22, 2, "Developed"); f.Add(22, 25, "Developed");
|
||||
var book = f.Run(book: 10);
|
||||
Check(Find(book, "H012").Single(x => x.PlotLineID == 1).Level == PlotHealthLevel.Review, "Book-owned open thread should be review");
|
||||
Check(Find(book, "H012").Single(x => x.PlotLineID == 2).Level == PlotHealthLevel.Information, "Project thread at book end should be informational despite later-book activity");
|
||||
Check(Find(f.Run(), "H012").All(x => x.Level == PlotHealthLevel.Information), "Current project end is not intended final ending");
|
||||
Check(f.Run(selected: [1]).Lines.Count == 1 && f.Run(selected: [1, 2]).Lines.Count == 2, "Focus/Weave must evaluate selected lines");
|
||||
var weave = f.Run(selected: [1, 2]);
|
||||
Check(weave.Lines.Sum(l => l.Findings.Count) == weave.Findings.Count, "Line rollup should aggregate findings, not invent status");
|
||||
f.Add(11, 2, "Note"); f.Add(11, 2, "Complicated");
|
||||
Check(f.Run().Lines[0].Threads[0].ScenesSinceProgress == 28, "Shared scenes and multiple same-scene events must not inflate narrative distance");
|
||||
}
|
||||
|
||||
public static void OrderingAndCoverage()
|
||||
{
|
||||
var f = new Fixture(); f.Add(11, 19, "Developed");
|
||||
var thread = f.Run(cutoff: 21).Lines[0].Threads[0];
|
||||
Check(thread.ChaptersSinceProgress == 1, "Cross-book restarted chapter numbers must count chapter identities");
|
||||
f.Scenes[20].ChapterNumber = 1000; f.Scenes[18].ChapterNumber = 9999;
|
||||
Check(f.Run(cutoff: 21).Lines[0].Threads[0].ChaptersSinceProgress == 1, "Unusual chapter numbers must not affect distance");
|
||||
f = new Fixture(); f.Add(11, 1, "Introduced"); f.Add(11, 3, "Resolved");
|
||||
Check(!Find(f.Run(), "H009").Any(), "Canonical resolution follows introduction");
|
||||
f.Threads[0].ThreadStatusName = "Resolved";
|
||||
Check(Find(f.Run(cutoff: 2), "H012").Any(), "Global closed status must not leak back before positioned resolution");
|
||||
var reordered = f.Run(order: Enumerable.Range(1, 30).Reverse().ToArray(), scenario: 5);
|
||||
Check(Find(reordered, "H009").Any(), "Scenario ordering must drive rule positions");
|
||||
Check(reordered.Findings.All(x => x.Scope.ScenarioID == 5), "Order labels must identify scenario");
|
||||
f = new Fixture(); f.Add(11, 1, "Question Raised"); f.Add(11, 2, "Question Answered");
|
||||
var partial = f.Run(order: [1, 3, 20], scenario: 5);
|
||||
Check(!partial.Scope.EvidenceComplete && partial.Scope.MissingSceneCount == 27, "Scenario omissions must be explicit");
|
||||
Check(Find(partial, "H004").Single().Level == PlotHealthLevel.Information && !Find(partial, "H004").Single().EvidenceComplete, "Incomplete scenario must not manufacture a definitive absence claim");
|
||||
Check(partial.Findings.SelectMany(x => x.Evidence).All(x => x.Position <= 3), "Never substitute canonical positions into scenario evidence");
|
||||
f = new Fixture(); f.Add(11, 1, "Introduced"); f.Add(11, 2, "Payoff"); f.Add(11, 18, "Developed");
|
||||
Check(Find(f.Run(), "H002").Any(x => x.ScenesWithoutProgress == 15), "Internal progress silence should remain inspectable after a later event");
|
||||
}
|
||||
|
||||
public static void DiscoveryContradictions()
|
||||
{
|
||||
var f = new Fixture(); f.Threads[0].ThreadTitle = "First Sparks: Recognition Before Proof";
|
||||
f.Threads[0].ThreadStatusName = "Introduced"; f.Threads[0].IntroducedSceneID = 5; f.Threads[0].ActualResolutionSceneID = 10;
|
||||
f.Add(11, 1, "Introduced"); f.Add(11, 10, "Payoff"); f.Add(11, 15, "Developed"); f.Add(11, 25, "Introduced");
|
||||
Check(Find(f.Run(), "H007").Any() && Find(f.Run(), "H008").Any() && Find(f.Run(), "H010").Any(), "First Sparks evidence must remain separate from stored status");
|
||||
f = new Fixture(); f.Threads[0].ThreadTitle = "Edges of Tenderness"; f.Threads[0].ThreadStatusName = "Resolved";
|
||||
f.Threads[0].IntroducedSceneID = 5; f.Threads[0].ActualResolutionSceneID = 29;
|
||||
f.Add(11, 1, "Introduced"); f.Add(11, 15, "Developed"); f.Add(11, 29, "Resolved");
|
||||
Check(Find(f.Run(), "H010").Any() && !Find(f.Run(), "H009").Any(), "Earlier introduction boundary mismatch is distinct from closure-before-introduction");
|
||||
f = new Fixture(); f.Threads[0].ThreadTitle = "Bent Lines, Straight Cop";
|
||||
f.Add(11, 5, "Developed"); f.Add(11, 8, "Clue Planted"); f.Add(11, 16, "Developed");
|
||||
Check(Find(f.Run(), "H002").Any(x => x.ScenesWithoutProgress == 14) && Find(f.Run(), "H005").Any() && Find(f.Run(), "H007").Any(), "Bent Lines should show quiet/clue/status evidence without modifying Planned");
|
||||
Check(f.Threads[0].ThreadStatusName == "Planned", "Stored author status must never be auto-changed");
|
||||
}
|
||||
|
||||
public static void GeneratedScale()
|
||||
{
|
||||
var lines = Enumerable.Range(1, 40).Select(id => new PlotLineWorkspaceLineRow { PlotLineID = id, ProjectID = 7 }).ToList();
|
||||
var threads = lines.Select(l => new PlotLineWorkspaceThreadRow { PlotThreadID = l.PlotLineID, PlotLineID = l.PlotLineID, ThreadStatusName = "Developing" }).ToList();
|
||||
var scenes = Enumerable.Range(1, 1200).Select(i => new PlotLineWorkspaceAttributionRow { SceneID = i, NarrativeOrder = i, BookID = 10, ChapterID = (i-1)/10+1 }).ToList();
|
||||
var events = lines.SelectMany(l => Enumerable.Range(0, 300).Select(i => new PlotLineWorkspaceContributionRow {
|
||||
ThreadEventID = l.PlotLineID * 1000 + i, PlotLineID = l.PlotLineID, PlotThreadID = l.PlotLineID,
|
||||
SceneID = (i * 7 + l.PlotLineID * 13) % 1200 + 1, CanonicalRole = "Developed", CanonicalStructuralType = "Progress" })).ToList();
|
||||
var data = new PlotLineWorkspaceData { PlotLines = lines, Threads = threads, AttributionScenes = scenes, Contributions = events };
|
||||
var result = new PlotHealthEvaluator().Evaluate(new(7, null, null, lines.Select(l => l.PlotLineID).ToArray(), data, data));
|
||||
Check(result.Lines.Count == 40 && result.Findings.SelectMany(f => f.Evidence).All(e => e.Position <= 1200), "12,000-contribution weave must use scene positions, not event counts");
|
||||
}
|
||||
|
||||
internal sealed class Fixture
|
||||
{
|
||||
public List<PlotLineWorkspaceLineRow> Lines = [new() { PlotLineID = 1, ProjectID = 7, BookID = 10, PlotLineName = "Book route" }, new() { PlotLineID = 2, ProjectID = 7, PlotLineName = "Project route" }];
|
||||
public List<PlotLineWorkspaceThreadRow> Threads = [new() { PlotThreadID = 11, PlotLineID = 1, ThreadTitle = "Book thread", ThreadStatusName = "Planned" }, new() { PlotThreadID = 22, PlotLineID = 2, ThreadTitle = "Project thread", ThreadStatusName = "Developing" }];
|
||||
public List<PlotLineWorkspaceContributionRow> Events = [];
|
||||
public List<PlotLineWorkspaceTargetRow> Targets = [];
|
||||
public List<PlotLineWorkspaceAttributionRow> Scenes = Enumerable.Range(1, 30).Select(i => new PlotLineWorkspaceAttributionRow { SceneID = i, NarrativeOrder = i, SceneTitle = $"Scene {i}", BookID = i <= 20 ? 10 : 20, ChapterID = ((i - 1) / 5) + 1, ChapterNumber = ((i - 1) % 20) / 5 + 1 }).ToList();
|
||||
public PlotLineWorkspaceContributionRow Add(int thread, int scene, string role, string structure = "Progress")
|
||||
{
|
||||
var s = Scenes.Single(x => x.SceneID == scene);
|
||||
var e = new PlotLineWorkspaceContributionRow { ThreadEventID = Events.Count + 1, PlotThreadID = thread, PlotLineID = Threads.Single(t => t.PlotThreadID == thread).PlotLineID, SceneID = scene, BookID = s.BookID, ChapterID = s.ChapterID, ChapterNumber = s.ChapterNumber, SceneNumber = scene, NarrativeOrder = s.NarrativeOrder, ThreadTitle = Threads.Single(t => t.PlotThreadID == thread).ThreadTitle, SceneTitle = s.SceneTitle, CanonicalRole = role, CanonicalStructuralType = structure };
|
||||
Events.Add(e); return e;
|
||||
}
|
||||
public PlotLineWorkspaceData Data(IReadOnlyList<PlotLineWorkspaceAttributionRow>? order = null) => new() { PlotLines = Lines, Threads = Threads, Contributions = Events, Targets = Targets, AttributionScenes = order ?? Scenes };
|
||||
public PlotHealthResult Run(int? cutoff = null, int? book = null, int[]? selected = null, int[]? order = null, int? scenario = null)
|
||||
{
|
||||
var ordered = (order is null ? Scenes : order.Select(id => Scenes.Single(s => s.SceneID == id))).Where(s => !book.HasValue || s.BookID == book).Select((s, i) => new PlotLineWorkspaceAttributionRow { SceneID = s.SceneID, BookID = s.BookID, ChapterID = s.ChapterID, NarrativeOrder = i + 1, SceneTitle = s.SceneTitle }).ToList();
|
||||
return new PlotHealthEvaluator().Evaluate(new(7, book, scenario, selected ?? [1, 2], Data(ordered), Data(), cutoff));
|
||||
}
|
||||
}
|
||||
private static IEnumerable<PlotHealthFinding> Find(PlotHealthResult result, string rule) => result.Findings.Where(x => x.RuleID == rule);
|
||||
private static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
|
||||
}
|
||||
@ -5,6 +5,8 @@ internal static class PlotLineWorkspaceTests
|
||||
{
|
||||
public static void FocusWeaveGapsAndSharedScenes()
|
||||
{
|
||||
Check(PlotLineColours.ForLine(1, "#2f6f63") != PlotLineColours.ForLine(2, "#2f6f63"), "Legacy default colours should distinguish line identities.");
|
||||
Check(PlotLineColours.ForLine(1, "#123456") == "#123456", "Explicit line colours must be preserved.");
|
||||
var data = Fixture();
|
||||
var focus = PlotLineWorkspaceComposer.Compose(data, [1]);
|
||||
Check(focus.Count == 2, "Focus mode should contain the selected line's two scenes.");
|
||||
@ -26,13 +28,27 @@ internal static class PlotLineWorkspaceTests
|
||||
Check(filtered.Count == 1 && filtered[0].SceneID == 101, "Thread filtering should retain only contributions from selected threads.");
|
||||
Check(filtered[0].Memberships.Single().PlotLineID == 2, "Thread filtering must not leak another line's events.");
|
||||
|
||||
// Scenario order is supplied by the read model, rather than inferred from chapter labels.
|
||||
foreach (var contribution in data.Contributions) contribution.NarrativeOrder = contribution.SceneID == 102 ? 1 : 9;
|
||||
var scenario = PlotLineWorkspaceComposer.Compose(data, [1, 2]);
|
||||
Check(scenario[0].SceneID == 102 && scenario[1].SceneID == 101, "Map must preserve supplied scenario ordering.");
|
||||
|
||||
var root = RepositoryRoot();
|
||||
var workspaceView = File.ReadAllText(Path.Combine(root, "PlotLine/Views/PlotLineWorkspace/Index.cshtml"));
|
||||
Check(workspaceView.Contains("plotline-shell-wide", StringComparison.Ordinal), "Workspace should use the established full-width shell.");
|
||||
var lineEditor = File.ReadAllText(Path.Combine(root, "PlotLine/Views/PlotLines/Edit.cshtml"));
|
||||
Check(lineEditor.Contains("asp-for=\"Colour\" type=\"color\"", StringComparison.Ordinal), "Line colour should use the existing persisted editor field.");
|
||||
var timeline = File.ReadAllText(Path.Combine(root, "PlotLine/Views/Timeline/Index.cshtml"));
|
||||
var settings = File.ReadAllText(Path.Combine(root, "PlotLine/Views/Timeline/Settings.cshtml"));
|
||||
var characterEditor = File.ReadAllText(Path.Combine(root, "PlotLine/Views/Shared/SceneInspectorV2/_SceneCharactersEditor.cshtml"));
|
||||
var controller = File.ReadAllText(Path.Combine(root, "PlotLine/Controllers/ScenesController.cs"));
|
||||
var sql = File.ReadAllText(Path.Combine(root, "PlotLine/Sql/204_PlotLineWorkspaceV1.sql"));
|
||||
|
||||
Check(!timeline.Contains("Model.PlotLanes", StringComparison.Ordinal) && !timeline.Contains("data-plot-line-svg", StringComparison.Ordinal), "Timeline must not render legacy plot lanes or SVGs.");
|
||||
Check(!settings.Contains("ShowPlotLines", StringComparison.Ordinal), "Timeline must not offer obsolete plot lane visibility.");
|
||||
var script = File.ReadAllText(Path.Combine(root, "PlotLine/wwwroot/js/site.js"));
|
||||
Check(!script.Contains("renderPlotLineSvg", StringComparison.Ordinal) && !script.Contains("const healthFor", StringComparison.Ordinal), "Retired Timeline health rules must not remain executable.");
|
||||
Check(timeline.Contains("name=\"PlotLineID\"", StringComparison.Ordinal) && timeline.Contains("name=\"PlotThreadID\"", StringComparison.Ordinal), "Timeline must retain chronological membership filters.");
|
||||
Check(!timeline.Contains("character-lane-board", StringComparison.Ordinal), "Timeline must not render Character lane presentation.");
|
||||
Check(!settings.Contains("ShowCharacterAppearances", StringComparison.Ordinal), "Timeline settings must not offer Character lanes.");
|
||||
Check(characterEditor.Contains("Knowledge notes", StringComparison.Ordinal) && controller.Contains("KnowledgeNotes = row.KnowledgeNotes", StringComparison.Ordinal),
|
||||
@ -68,13 +84,18 @@ internal static class PlotLineWorkspaceTests
|
||||
Check(composed.Zip(composed.Skip(1), (left, right) => left.NarrativeOrder <= right.NarrativeOrder).All(x => x), "Large weave lost narrative ordering.");
|
||||
}
|
||||
|
||||
private static PlotLineWorkspaceData Fixture() => new()
|
||||
internal static PlotLineWorkspaceData Fixture() => new()
|
||||
{
|
||||
PlotLines =
|
||||
[
|
||||
new() { PlotLineID = 1, PlotLineName = "Line A", Colour = "#111111", SortOrder = 1 },
|
||||
new() { PlotLineID = 2, PlotLineName = "Line B", Colour = "#222222", SortOrder = 2 }
|
||||
new() { PlotLineID = 1, PlotLineName = "Line A", Colour = "#5bada0", SortOrder = 1 },
|
||||
new() { PlotLineID = 2, PlotLineName = "Line B", Colour = "#b36f43", SortOrder = 2 },
|
||||
new() { PlotLineID = 3, PlotLineName = "Line C", Colour = "#527bcc", SortOrder = 3 }
|
||||
],
|
||||
Threads = [new() { PlotThreadID = 11, PlotLineID = 1, ThreadTitle = "First phase", IntroducedSceneID = 101 }],
|
||||
Targets = [new() { ThreadEventID = 1011, SourcePlotLineID = 1, TargetPlotLineID = 2, StructuralType = "Branch" }],
|
||||
AttributionScenes = [new() { SceneID = 101, SceneTitle = "Shared scene", NarrativeOrder = 2, CanonicalPlotLineCount = 2 }, new() { SceneID = 103, SceneTitle = "Unattributed scene", NarrativeOrder = 3 }],
|
||||
Dependencies = [new() { SceneDependencyID = 1, SourceSceneID = 101, TargetSceneID = 102, DependencyType = "Requires" }],
|
||||
Contributions =
|
||||
[
|
||||
Contribution(1, 11, 101, 2, 1, "Canonical event", "Supporting imported detail"),
|
||||
|
||||
@ -17,16 +17,50 @@ using PlotLine.ViewModels;
|
||||
|
||||
#pragma warning disable CS8321
|
||||
|
||||
if (args.Contains("--dev-browser-identity"))
|
||||
{
|
||||
await DevBrowserIdentity.RunAsync(args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.Contains("--toolbar-browser-host"))
|
||||
{
|
||||
await ToolbarBrowserHost.RunAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.Contains("--plot-health"))
|
||||
{
|
||||
PlotHealthTests.RolesAndClocks();
|
||||
PlotHealthTests.QuestionsClosureAndStatus();
|
||||
PlotHealthTests.TargetsScopeAndRollup();
|
||||
PlotHealthTests.OrderingAndCoverage();
|
||||
PlotHealthTests.DiscoveryContradictions();
|
||||
PlotHealthTests.GeneratedScale();
|
||||
Console.WriteLine("PASS Plot Health H001–H012, role clocks, scoped ordering, partial coverage, targets and non-mutation");
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.Contains("--plot-lines"))
|
||||
{
|
||||
PlotLineWorkspaceTests.FocusWeaveGapsAndSharedScenes();
|
||||
PlotLineWorkspaceTests.ThreadFilteringAndInspectorContracts();
|
||||
PlotLineWorkspaceTests.GeneratedScale();
|
||||
Console.WriteLine("PASS Plot Lines Focus/Weave, shared scenes, gaps, scenario ordering and 12,000-contribution scale");
|
||||
return;
|
||||
}
|
||||
|
||||
var tests = new (string Name, Action Test)[]
|
||||
{
|
||||
("Ribbon operation identity and semantic icons stay consistent", RibbonPresentationTests.SemanticMetadata),
|
||||
("Subscription entitlement evaluates trials, paid access, overrides and real plan limits", SubscriptionEntitlementTests.EffectiveStateAndLimits),
|
||||
("Subscription enforcement is concurrent, audited and admin-authorised", SubscriptionEntitlementTests.EnforcementAndAdminSecurity),
|
||||
("Plot Health stays scene-based with 12,000 contributions", PlotHealthTests.GeneratedScale),
|
||||
("Plot Health preserves Discovery planning and boundary contradictions", PlotHealthTests.DiscoveryContradictions),
|
||||
("Plot Health separates stored status and meaningful-progress clocks", PlotHealthTests.RolesAndClocks),
|
||||
("Plot Health explains question, payoff, closure and boundary evidence", PlotHealthTests.QuestionsClosureAndStatus),
|
||||
("Plot Health evaluates explicit targets and scoped line rollups", PlotHealthTests.TargetsScopeAndRollup),
|
||||
("Plot Health respects scenario coverage and ordered chapter identities", PlotHealthTests.OrderingAndCoverage),
|
||||
("Plot Lines Focus and Weave preserve gaps and shared-scene identity", PlotLineWorkspaceTests.FocusWeaveGapsAndSharedScenes),
|
||||
("Plot Lines thread, enrichment and Timeline inspector contracts hold", PlotLineWorkspaceTests.ThreadFilteringAndInspectorContracts),
|
||||
("Plot Lines composition remains bounded with a large generated weave", PlotLineWorkspaceTests.GeneratedScale),
|
||||
|
||||
26
PlotLine.Tests/RibbonPresentationTests.cs
Normal file
26
PlotLine.Tests/RibbonPresentationTests.cs
Normal file
@ -0,0 +1,26 @@
|
||||
using PlotLine.Services;
|
||||
internal static class RibbonPresentationTests
|
||||
{
|
||||
public static void SemanticMetadata()
|
||||
{
|
||||
if (RibbonPresentation.Operation("Books", "Create") != RibbonPresentation.Operation("books", "create")) throw new Exception("Operation identity must be stable across route casing.");
|
||||
var exports = new[] { RibbonPresentation.IconFor("Exports.StoryBible"), RibbonPresentation.IconFor("exports.storybible", "markdown"), RibbonPresentation.IconFor("exports.storybible", "text"), RibbonPresentation.IconFor("exports.narrativetimeline"), RibbonPresentation.IconFor("exports.researchpack") };
|
||||
if (exports.Distinct().Count() != exports.Length || exports.Any(key => key == "bible")) throw new Exception("Export operations need distinct semantic icon metadata, not the Story Bible navigation icon.");
|
||||
foreach (var key in exports.Append("settings").Append("validate").Append("help")) _ = ApplicationRibbon.Icon(key!);
|
||||
if (RibbonPresentation.IconFor("timeline.settings") == RibbonPresentation.IconFor("warnings.validateproject")) throw new Exception("Settings and validation are different operations.");
|
||||
if (RibbonPresentation.IconFor("books.create") is not null) throw new Exception("Preserve the established Add Book icon association.");
|
||||
var root = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (root is not null && !Directory.Exists(Path.Combine(root.FullName, "PlotLine", "Views"))) root = root.Parent;
|
||||
if (root is null) throw new Exception("Ribbon source coverage requires the repository.");
|
||||
foreach (var command in ApplicationRibbon.Categories.SelectMany(category => category.Groups).SelectMany(group => group.Commands))
|
||||
{
|
||||
var action = command.Controller is "Books" or "Chapters" && command.Action == "Create" ? "Edit"
|
||||
: command.Controller == "Onboarding" && command.Action == "StoryIntelligenceBookReviewCentre" ? "StoryIntelligenceReviewCentre" : command.Action;
|
||||
var view = Path.Combine(root.FullName, "PlotLine", "Views", command.Controller, action + ".cshtml");
|
||||
if (!File.Exists(view)) continue; // Downloads and controller redirects have no page furniture.
|
||||
var markup = File.ReadAllText(view);
|
||||
if (!markup.Contains("data-pwa-") && !markup.Contains("_StoryCalendarSurface")) throw new Exception($"Navigation destination has no contextual classification: {command.Controller}/{action}");
|
||||
}
|
||||
if (RibbonPresentation.Icons.Select(icon => icon.Key).Distinct().Count() != RibbonPresentation.Icons.Count()) throw new Exception("Icon catalog keys must be unique.");
|
||||
}
|
||||
}
|
||||
@ -19,9 +19,55 @@ using PlotLine.ViewModels;
|
||||
// Isolated, loopback-only host: renders real compiled Razor chrome, never starts app workers or connects to a database.
|
||||
internal static class ToolbarBrowserHost
|
||||
{
|
||||
private static PlotLineWorkspaceData HealthFixture()
|
||||
{
|
||||
var f = new PlotHealthTests.Fixture();
|
||||
f.Add(11, 1, "Introduced"); f.Add(11, 20, "Mentioned"); f.Add(11, 29, "Note");
|
||||
f.Add(22, 1, "Developed");
|
||||
return f.Data();
|
||||
}
|
||||
|
||||
private static SceneEditViewModel SceneWorkspaceFixture()
|
||||
{
|
||||
// Optional read-only export for visual checks. This host never accesses the database.
|
||||
var snapshot = Environment.GetEnvironmentVariable("PD_SCENE_VISUAL_FIXTURE");
|
||||
if (!string.IsNullOrEmpty(snapshot))
|
||||
return System.Text.Json.JsonSerializer.Deserialize<SceneEditViewModel>(File.ReadAllText(snapshot))!;
|
||||
return new() {
|
||||
SceneID = 101, SceneTitle = "Arrival at the harbour", ChapterID = 21, SceneNumber = 1,
|
||||
Project = new Project { ProjectID = 7, ProjectName = "The Glass Harbour" },
|
||||
Book = new Book { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" },
|
||||
Chapter = new Chapter { ChapterID = 21, ChapterNumber = 1, ChapterTitle = "The crossing" },
|
||||
RevisionStatusID = 1, RevisionStatuses = [new SelectListItem("Planned", "1")],
|
||||
POVCharacterID = 1, CharacterOptions = [new SelectListItem("Mara Vale", "1"), new SelectListItem("Elias", "2")],
|
||||
RelativeTimeText = "Before dawn", Summary = "Mara reaches the harbour carrying a letter she cannot explain.",
|
||||
ScenePurposeTypes = [new() { ScenePurposeTypeID = 1, PurposeName = "Setup" }], SelectedPurposeTypeIds = [1],
|
||||
ScenePurposeNotes = "Establish the mystery", SceneOutcomeNotes = "Mara decides to stay",
|
||||
Metrics = [new() { MetricName = "Tension", MinValue = 1, MaxValue = 10, Value = 7 }],
|
||||
SceneCharacters = Enumerable.Range(1, 8).Select(i => new SceneCharacter { CharacterID = i, CharacterName = i == 1 ? "Mara Vale" : $"Harbour character {i}", RoleInSceneTypeName = i == 1 ? "POV" : "Supporting" }).ToList(),
|
||||
ThreadEvents = [new() { EventTitle = "The letter", ThreadTitle = "Missing sender", PlotLineName = "Harbour mystery", EventDescription = "A clue at the water's edge." }],
|
||||
Warnings = Enumerable.Range(1, 6).Select(i => new ContinuityWarning { ContinuityWarningID = i, WarningTypeName = "Location", Message = $"Review location evidence {i}." }).ToList(),
|
||||
Notes = [new() { NoteTitle = "Atmosphere", NoteText = "Keep the harbour quiet." }],
|
||||
ChecklistItems = [new() { ItemText = "Check the tide", IsCompleted = false }]
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
private static SceneContinuityEditorViewModel SceneContinuityFixture()
|
||||
{
|
||||
var scene = SceneWorkspaceFixture();
|
||||
return new() { Scene = scene, Dashboard = new WarningDashboardViewModel {
|
||||
Project = scene.Project!, BookID = scene.Book?.BookID,
|
||||
ProjectWarnings = scene.Warnings.Select(w => new ProjectWarningViewModel {
|
||||
ContinuityWarningID = w.ContinuityWarningID, Source = "Persisted", WarningTypeDisplayName = w.WarningTypeName,
|
||||
Message = w.Message, Severity = "Warning", SceneID = scene.SceneID
|
||||
}).ToList()
|
||||
}};
|
||||
}
|
||||
|
||||
public static async Task RunAsync()
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { ApplicationName = typeof(ToolbarController).Assembly.FullName });
|
||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { ApplicationName = typeof(ToolbarController).Assembly.FullName, ContentRootPath = Path.GetFullPath("PlotLine") });
|
||||
builder.Services.AddControllersWithViews().AddApplicationPart(typeof(ToolbarController).Assembly);
|
||||
builder.Services.AddSingleton<IToolbarPreferenceRepository, ToolbarMemoryPreferences>();
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
@ -42,15 +88,40 @@ internal static class ToolbarBrowserHost
|
||||
app.UseAuthorization();
|
||||
app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
|
||||
app.MapGet("/Projects", () => Results.Redirect("/fixture"));
|
||||
app.MapGet("/plot-map-fixture", async context =>
|
||||
{
|
||||
var data = context.Request.Query["health"] == "true" || context.Request.Query["healthDetail"] == "true"
|
||||
? HealthFixture() : PlotLineWorkspaceTests.Fixture();
|
||||
var ids = context.Request.Query["focus"] == "true" ? new[] { 1 } : new[] { 1, 2, 3 };
|
||||
var model = new PlotLineWorkspaceViewModel {
|
||||
Project = new Project { ProjectID = 7 },
|
||||
PlotLines = data.PlotLines.Where(l => ids.Contains(l.PlotLineID)).Select(l => new PlotLineWorkspaceLineViewModel { Line = l, IsSelected = true, Threads = data.Threads.Where(t => t.PlotLineID == l.PlotLineID).ToList() }).ToList(),
|
||||
SelectedPlotLineIDs = ids,
|
||||
Mode = ids.Length == 1 ? "Focus" : "Weave",
|
||||
Scenes = PlotLineWorkspaceComposer.Compose(data, ids),
|
||||
MapTargets = data.Targets,
|
||||
AssociationScenes = data.AttributionScenes,
|
||||
Health = new PlotHealthEvaluator().Evaluate(new(7, null, null, ids, data, data))
|
||||
};
|
||||
var action = new ActionContext(context, new RouteData(), new ActionDescriptor());
|
||||
var view = context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null, context.Request.Query["healthDetail"] == "true" ? "/Views/PlotLineWorkspace/_Health.cshtml" : "/Views/PlotLineWorkspace/_NarrativeMap.cshtml", false);
|
||||
using var writer = new StringWriter();
|
||||
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model };
|
||||
await view.View.RenderAsync(new ViewContext(action, view.View, viewData, new TempDataDictionary(context, context.RequestServices.GetRequiredService<ITempDataProvider>()), writer, new HtmlHelperOptions()));
|
||||
context.Response.ContentType = "text/html; charset=utf-8";
|
||||
if (context.Request.Query["healthDetail"] == "true") { await context.Response.WriteAsync(writer.ToString()); return; }
|
||||
await context.Response.WriteAsync("<html data-app-theme='modern-dark' data-theme='dark'><head><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-shell.css'><link rel='stylesheet' href='/css/record-workspace.css'><link rel='stylesheet' href='/css/application-context-menu.css'><link rel='stylesheet' href='/css/plot-line-workspace.css'></head><body class='app-layout'><form id='plot-workspace-form'><input type='hidden' name='projectId' value='7'></form>" + writer + "<div id='plot-inspector-backdrop' hidden></div><aside class='plot-inspector' id='plot-inspector' aria-hidden='true'><div id='plot-inspector-content'></div></aside><script src='/js/plot-line-workspace.js'></script></body></html>");
|
||||
});
|
||||
app.MapGet("/fixture", async context =>
|
||||
{
|
||||
var model = new ApplicationNavigationViewModel { ActiveSection = "Calendar", ShowCompanionPresence = true };
|
||||
if (context.Request.Query["project"] != "none")
|
||||
{
|
||||
model.Project = new Project { ProjectID = 7, ProjectName = "The Glass Harbour", AccessRole = "Owner" };
|
||||
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 }];
|
||||
}
|
||||
string? recordLayout = null;
|
||||
var dashboardPage = context.Request.Query["page"] == "dashboard";
|
||||
var timelinePage = context.Request.Query["page"] == "timeline";
|
||||
if (dashboardPage) model.ActiveSection = "Overview";
|
||||
@ -67,8 +138,24 @@ internal static class ToolbarBrowserHost
|
||||
data["ApplicationAppearance"] = appearance;
|
||||
var temp = new TempDataDictionary(context, context.RequestServices.GetRequiredService<ITempDataProvider>());
|
||||
await view.View.RenderAsync(new ViewContext(action, view.View, data, temp, writer, new HtmlHelperOptions()));
|
||||
|
||||
return writer.ToString();
|
||||
}
|
||||
if (context.Request.Query["page"] == "scene-edit" && context.Request.Query.TryGetValue("editor", out var requestedEditor))
|
||||
{
|
||||
var editors = new Dictionary<string, string> { ["purpose"] = "Purpose", ["relationships"] = "Relationships", ["characters"] = "Characters", ["metrics"] = "Metrics", ["threads"] = "Threads", ["dependencies"] = "Dependencies", ["locations"] = "Locations", ["assets"] = "Assets", ["notes"] = "Notes", ["checklist"] = "Checklist", ["workflow"] = "Workflow", ["attachments"] = "Attachments", ["warnings"] = "Continuity", ["scene-details"] = "Details", ["knowledge"] = "Knowledge", ["attributes"] = "CharacterAttributes", ["suggestions"] = "Suggestions" };
|
||||
if (!editors.TryGetValue(requestedEditor.ToString(), out var editorName)) { context.Response.StatusCode = 404; return; }
|
||||
context.Response.ContentType = "text/html";
|
||||
await context.Response.WriteAsync(await Render($"Shared/SceneInspectorV2/_Scene{editorName}Editor", editorName == "Continuity" ? SceneContinuityFixture() : SceneWorkspaceFixture()));
|
||||
return;
|
||||
}
|
||||
if (context.Request.Query["page"] == "scene-edit")
|
||||
{
|
||||
var scene = SceneWorkspaceFixture();
|
||||
model.Project = scene.Project;
|
||||
model.Book = scene.Book;
|
||||
model.Books = scene.Book is null ? [] : [scene.Book];
|
||||
}
|
||||
var menu = await Render("Shared/_ApplicationShell");
|
||||
var toolbar = "";
|
||||
var calendar = new StoryCalendarViewModel { Project = model.Project ?? new(), SelectedBookID = model.Book?.BookID,
|
||||
@ -87,9 +174,30 @@ internal static class ToolbarBrowserHost
|
||||
<div class="workspace-heading"><form class="timeline-filter"><button class="btn btn-outline-primary">View</button></form><div class="button-row"><button class="btn btn-outline-primary">Validate project</button><button class="btn btn-outline-secondary">Warnings</button><button class="btn btn-outline-secondary">Story health</button><button class="btn btn-outline-secondary">Timeline Settings</button><button class="btn btn-outline-primary">Create Scenario</button><button class="btn btn-outline-secondary">Archived Items</button></div></div>
|
||||
<section class="timeline-control-panel"><details class="timeline-filter-drawer"><summary>Filters</summary></details><details class="timeline-control-group"><summary>View</summary></details><details class="timeline-control-group"><summary>Jump</summary></details><details class="timeline-control-group"><summary>Saved views</summary></details></section>
|
||||
<details class="timeline-drag-palette"><summary>Drag sources</summary><span class="drag-chip">Mara Vale</span></details>
|
||||
<div class="workspace-layout"><main class="timeline-workspace"><section class="timeline-shell"><div class="timeline-section-header">Scene timeline</div><div class="timeline-project-title">The Glass Harbour</div><div class="timeline-book-title"><strong>A Distant Shore</strong><span>Book one</span></div><div class="timeline-chapter"><div class="timeline-chapter-title"><strong>Chapter 1</strong><span>The crossing</span></div><a class="timeline-scene-card"><strong>Arrival</strong><span class="scene-summary">Mara reaches the harbour before dawn.</span><span class="scene-pov-label">Mara</span><span class="location-pill">North Pier</span><span class="purpose-chip">Inciting event</span></a><a class="timeline-scene-card focus-dim"><strong>Departure</strong><span class="scene-summary">The ship leaves at dusk.</span></a></div><div class="lane-board-heading">Plot line lanes</div><div class="plot-lane-row lane-dim" style="--plot-colour:#4f8bc9"><a class="plot-lane-label"><strong>Harbour mystery</strong></a><div class="plot-lane-slot"><a class="thread-marker">Revelation</a></div></div><div class="lane-board-heading">Story asset lanes</div><div class="asset-lane-label"><strong>Brass key</strong><span>Object / 8</span></div><div class="asset-lane-slot"><a class="asset-marker">Found</a></div><div class="lane-board-heading">Character appearances</div><div class="character-lane-label"><strong>Mara Vale</strong></div><div class="character-lane-slot"><a class="character-marker">POV</a></div><div class="metric-shape-controls"><div class="metric-toggle-row"><label class="metric-toggle-pill" style="--metric-colour:#2f6f63"><input type="checkbox" checked><span>Overall Intensity</span></label><label class="metric-toggle-pill" style="--metric-colour:#b35f3b"><input type="checkbox"><span>Tension</span></label></div><span class="timeline-metric-edit-status">Select a single metric to edit its curve.</span></div><div class="future-lane-placeholder">Add characters to scenes to see appearance lanes.</div><div class="timeline-minimap"><button class="is-active">Chapter 1</button></div></section></main><aside class="scene-inspector-panel"><div class="inspector-header"><div><p class="eyebrow">Scene inspector</p><h2>Arrival</h2></div><a class="btn btn-outline-secondary">Close</a></div><div class="scene-inspector-body">Scene details</div></aside></div>
|
||||
<div class="workspace-layout"><main class="timeline-workspace"><section class="timeline-shell"><div class="timeline-section-header">Scene timeline</div><div class="timeline-project-title">The Glass Harbour</div><div class="timeline-book-title"><strong>A Distant Shore</strong><span>Book one</span></div><div class="timeline-chapter"><div class="timeline-chapter-title"><strong>Chapter 1</strong><span>The crossing</span></div><a class="timeline-scene-card"><strong>Arrival</strong><span class="scene-summary">Mara reaches the harbour before dawn.</span><span class="scene-pov-label">Mara</span><span class="location-pill">North Pier</span><span class="purpose-chip">Inciting event</span></a><a class="timeline-scene-card focus-dim"><strong>Departure</strong><span class="scene-summary">The ship leaves at dusk.</span></a></div><div class="lane-board-heading">Story asset lanes</div><div class="asset-lane-label"><strong>Brass key</strong><span>Object / 8</span></div><div class="asset-lane-slot"><a class="asset-marker">Found</a></div><div class="metric-shape-controls"><div class="metric-toggle-row"><label class="metric-toggle-pill" style="--metric-colour:#2f6f63"><input type="checkbox" checked><span>Overall Intensity</span></label><label class="metric-toggle-pill" style="--metric-colour:#b35f3b"><input type="checkbox"><span>Tension</span></label></div><span class="timeline-metric-edit-status">Select a single metric to edit its curve.</span></div><div class="timeline-minimap"><button class="is-active">Chapter 1</button></div></section></main><aside class="scene-inspector-panel"><div class="inspector-header"><div><p class="eyebrow">Scene inspector</p><h2>Arrival</h2></div><a class="btn btn-outline-secondary">Close</a></div><div class="scene-inspector-body">Scene details</div></aside></div>
|
||||
""";
|
||||
}
|
||||
if (context.Request.Query["page"] == "timeline-render")
|
||||
{
|
||||
var scenes = new List<Scene> {
|
||||
new() { SceneID = 101, ChapterID = 21, SceneNumber = 1, SceneTitle = "Arrival", Summary = "The crossing begins." },
|
||||
new() { SceneID = 102, ChapterID = 21, SceneNumber = 2, SceneTitle = "Departure", Summary = "The crossing ends." }
|
||||
};
|
||||
var scenario = context.Request.Query["scenario"] == "true";
|
||||
if (scenario) scenes.Reverse();
|
||||
surface = await Render("Timeline/Index", new TimelineViewModel {
|
||||
Project = model.Project!, SelectedBookID = 12,
|
||||
Settings = new ProjectTimelineSettings { ShowPlotLines = true, ShowSceneCards = true, ShowMetricShape = false, ShowStoryAssets = false },
|
||||
Filter = new TimelineFilterViewModel { ProjectID = 7, PlotLineID = 1, FocusType = "plotline", FocusID = 1 },
|
||||
Books = [new() { Book = model.Book!, Chapters = [new() { Chapter = new Chapter { ChapterID = 21, ChapterNumber = 1, ChapterTitle = "The crossing" }, Scenes = scenes }] }],
|
||||
OrderedScenes = scenes, MatchingSceneIDs = new HashSet<int> { 101 }, FocusSceneIDs = new HashSet<int> { 101 }, FocusLabel = "Harbour mystery",
|
||||
ScenePlotSearchText = new Dictionary<int,string> { [101] = "Harbour mystery First clues Revelation" },
|
||||
PlotLineOptions = [new SelectListItem("Harbour mystery", "1", true)],
|
||||
PlotThreadOptions = [new SelectListItem("First clues", "11")]
|
||||
});
|
||||
surface += await Render("Timeline/Settings", new TimelineSettingsViewModel { ProjectID = 7, ProjectName = "The Glass Harbour" });
|
||||
|
||||
}
|
||||
if (dashboardPage)
|
||||
{
|
||||
surface = await Render("Projects/Details", new ProjectDetailViewModel {
|
||||
@ -101,10 +209,77 @@ internal static class ToolbarBrowserHost
|
||||
NeedsAttention = new() { Warnings = [new() { SeverityName = "Review", WarningTypeName = "Chronology", Message = "Check the order of events at the harbour.", LocationLabel = "Book 1 · Chapter 12" }] }
|
||||
});
|
||||
}
|
||||
var desktopPage = context.Request.Query["desktop"].ToString();
|
||||
if (!string.IsNullOrEmpty(desktopPage))
|
||||
{
|
||||
var project = model.Project ?? new Project { ProjectID = 7, ProjectName = "Fixture project" };
|
||||
if (context.Request.Query["owner"] == "false") project.AccessRole = "Editor";
|
||||
object pageModel = desktopPage switch
|
||||
{
|
||||
"StoryBible" => new StoryBibleViewModel { Project = project, Query = context.Request.Query["q"] },
|
||||
"Books" => new BookDetailViewModel { Project = project, Book = model.Book! },
|
||||
"Characters" => new CharacterListViewModel { Project = project, Characters = context.Request.Query["context"] == "objects" ? [new Character { CharacterID = 71, CharacterName = "Context A" }, new Character { CharacterID = 72, CharacterName = "Context B" }] : [] },
|
||||
"Locations" => new LocationListViewModel { Project = project },
|
||||
"FloorPlans" => new FloorPlanListViewModel { Project = project },
|
||||
"PlotLineWorkspace" => new PlotLineWorkspaceViewModel { Project = project },
|
||||
"Warnings" => new WarningDashboardViewModel { Project = project },
|
||||
"Archives" => new ArchivedItemsViewModel { ProjectID = project.ProjectID, Items = context.Request.Query["context"] == "objects" ? [new ArchivedItem { EntityType = "Character", EntityID = 71, DisplayName = "Archived context fixture", UpdatedDate = DateTime.UtcNow }] : [] },
|
||||
"PlotThreads" => new PlotThreadListViewModel { Project = project },
|
||||
"StoryCalendar" => calendar,
|
||||
"StoryPoint" => new StoryPointViewModel { Project = project },
|
||||
"ProjectMetrics" => new ProjectSceneMetricsViewModel { Project = project },
|
||||
"Analytics" => new AnalyticsViewModel { Project = project },
|
||||
"Dynamics" => new StoryDynamicsViewModel { Project = project },
|
||||
"ReviewCentre" => new StoryIntelligenceProgressViewModel { ProjectID = 7, BookID = 12 },
|
||||
"ProjectEdit" => new ProjectEditViewModel { ProjectID = 7, ProjectName = project.ProjectName },
|
||||
"WritingPlans" => new WritingPlansManagementViewModel(),
|
||||
"SchedulePreview" => new WritingSchedulePreviewViewModel(),
|
||||
_ => throw new InvalidOperationException("Unknown desktop fixture")
|
||||
};
|
||||
var viewController = desktopPage switch { "ReviewCentre" => "Onboarding", "ProjectEdit" => "Projects", "WritingPlans" or "SchedulePreview" => "Writer", _ => desktopPage };
|
||||
var viewAction = desktopPage switch { "ReviewCentre" => "StoryIntelligenceReviewCentre", "ProjectEdit" => "Edit", "WritingPlans" or "SchedulePreview" => desktopPage, "Dynamics" => "Story", "Books" => "Details", _ => "Index" };
|
||||
route.Values["controller"] = viewController;
|
||||
route.Values["action"] = viewAction;
|
||||
model.ActiveSection = desktopPage switch { "StoryBible" => "Story Bible", "PlotLineWorkspace" => "Plot Lines", "PlotThreads" => "Threads", "StoryCalendar" => "Calendar", "StoryPoint" => "At This Point", "ProjectMetrics" => "Metrics", "Analytics" or "Dynamics" => "Health", _ => desktopPage };
|
||||
surface = await Render($"{viewController}/{viewAction}", pageModel);
|
||||
menu = await Render("Shared/_ApplicationShell");
|
||||
}
|
||||
var record = context.Request.Query["record"].ToString();
|
||||
if (!string.IsNullOrEmpty(record))
|
||||
{
|
||||
recordLayout = record is "Projects" or "ProjectMetrics" ? "compact" : "wide";
|
||||
var project = model.Project!;
|
||||
object recordModel = record switch {
|
||||
"Projects" => new ProjectEditViewModel { ProjectID = 7, ProjectName = project.ProjectName },
|
||||
"Books" => new BookEditViewModel { BookID = 12, BookNumber = 1, ProjectID = 7, BookTitle = model.Book!.BookTitle, StatusOptions = [new SelectListItem("Planning", "Planning", true)], Project = project },
|
||||
"Chapters" => new ChapterEditViewModel { ChapterID = 21, BookID = 12, ChapterTitle = "The crossing", Book = model.Book },
|
||||
"Characters" => new CharacterEditViewModel { CharacterID = 71, ProjectID = 7, CharacterName = "Mara Vale", Project = project },
|
||||
"Locations" => new LocationEditViewModel { LocationID = 81, ProjectID = 7, LocationName = "The harbour", Project = project },
|
||||
"StoryAssets" => new StoryAssetEditViewModel { StoryAssetID = 91, ProjectID = 7, AssetName = "The letter", Project = project },
|
||||
"PlotLines" => new PlotLineEditViewModel { PlotLineID = 1, ProjectID = 7, PlotLineName = "The missing letter", Project = project },
|
||||
"PlotThreads" => new PlotThreadEditViewModel { PlotThreadID = 2, ProjectID = 7, ThreadTitle = "Arrival", Project = project },
|
||||
"ProjectMetrics" => new SceneMetricTypeEditViewModel { ProjectID = 7 },
|
||||
_ => throw new InvalidOperationException("Unknown record fixture")
|
||||
};
|
||||
route.Values["controller"] = record; route.Values["action"] = "Edit";
|
||||
surface = await Render($"{record}/Edit", recordModel);
|
||||
surface += "<script src='/lib/jquery/dist/jquery.min.js'></script><script src='/lib/jquery-validation/dist/jquery.validate.min.js'></script><script src='/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js'></script>";
|
||||
menu = await Render("Shared/_ApplicationShell");
|
||||
}
|
||||
if (context.Request.Query["page"] == "scene-edit")
|
||||
{
|
||||
surface = await Render("Scenes/Edit", SceneWorkspaceFixture());
|
||||
// The fixture renders a partial page; include its normal Scripts section explicitly.
|
||||
surface += "<script src='/js/scene-inspector-v2.js'></script>";
|
||||
}
|
||||
surface += await Render("Shared/_ConfirmationDialog");
|
||||
var initialTheme = appearance.ThemeKey ?? "warm-light";
|
||||
var appearanceScript = "<script>window.plotdirectorAppearance=" + System.Text.Json.JsonSerializer.Serialize(new { theme = initialTheme, migrate = false, collapsed = appearance.RibbonCollapsed }) + ";</script>";
|
||||
using var contributionWriter = new StringWriter();
|
||||
PlotLine.TagHelpers.RibbonContributionTagHelper.Snapshot(context).WriteTo(contributionWriter, System.Text.Encodings.Web.HtmlEncoder.Default);
|
||||
var contributions = contributionWriter.ToString();
|
||||
context.Response.ContentType = "text/html; charset=utf-8";
|
||||
await context.Response.WriteAsync("<!doctype html><html lang='en' data-app-theme='" + initialTheme + "' data-theme='" + (initialTheme.EndsWith("dark") ? "dark" : "light") + "'><head><link rel='manifest' href='/site.webmanifest'><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-navigation.css'><link rel='stylesheet' href='/css/application-shell.css'></head><body class='app-layout'><header class='pd-application-header'>" + menu + toolbar + "</header><main class='plotline-help-main container-fluid plotline-shell pd-dashboard-shell'>" + surface + "</main><script src='/lib/bootstrap/dist/js/bootstrap.bundle.min.js'></script><script src='/js/application-navigation.js'></script><script src='/js/application-toolbar.js'></script>" + appearanceScript + "<script src='/js/application-shell.js'></script><script src='/js/application-pwa.js'></script></body></html>");
|
||||
await context.Response.WriteAsync("<!doctype html><html lang='en' data-app-theme='" + initialTheme + "' data-theme='" + (initialTheme.EndsWith("dark") ? "dark" : "light") + "'><head><script src='/js/application-display-mode.js'></script><link rel='manifest' href='/site.webmanifest'><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-navigation.css'><link rel='stylesheet' href='/css/application-shell.css'><link rel='stylesheet' href='/css/record-workspace.css'><link rel='stylesheet' href='/css/application-context-menu.css'><link rel='stylesheet' href='/css/plot-line-workspace.css'><link rel='stylesheet' href='/css/onboarding.css'></head><body class='app-layout'><header class='pd-application-header'>" + menu + toolbar + "</header><template data-pwa-initial-contributions>" + contributions + "</template><script src='/js/application-page-context.js'></script><div class='plotline-help-main'><div class='container-fluid plotline-shell " + (recordLayout is null ? "pd-dashboard-shell" : $"pd-record-canvas pd-record-canvas--{recordLayout}") + "'><main data-pwa-page-content class='pb-3'>" + surface + "</main><script>window.PlotDirectorPageContext?.activate();</script></div></div><script src='/lib/bootstrap/dist/js/bootstrap.bundle.min.js'></script><script src='/js/application-navigation.js'></script><script src='/js/application-toolbar.js'></script>" + appearanceScript + "<script src='/js/application-shell.js'></script><script src='/js/site.js'></script><script src='/js/application-pwa.js'></script><script src='/js/application-context-menu.js'></script></body></html>");
|
||||
});
|
||||
await app.RunAsync();
|
||||
}
|
||||
|
||||
@ -16,7 +16,7 @@ public sealed class PlotLineWorkspaceController(IPlotLineWorkspaceService worksp
|
||||
bool showSuggestions = false)
|
||||
{
|
||||
var model = await workspace.GetAsync(projectId, bookId, plotLineIds, threadIds, scenarioId, showSuggestions, false);
|
||||
return model is null ? NotFound() : View(model);
|
||||
return model is null ? NotFound() : Request.Headers["X-Plot-Map"] == "true" ? PartialView("_NarrativeMap", model) : View(model);
|
||||
}
|
||||
|
||||
public async Task<IActionResult> Unattributed(int projectId, int? bookId, int? scenarioId)
|
||||
@ -31,6 +31,13 @@ public sealed class PlotLineWorkspaceController(IPlotLineWorkspaceService worksp
|
||||
return model is null ? NotFound() : PartialView("_Inspector", model);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Health(int projectId, int? bookId, int plotLineId, int? scenarioId)
|
||||
{
|
||||
var model = await workspace.GetAsync(projectId, bookId, [plotLineId], [], scenarioId, false, false);
|
||||
return model is null || !model.SelectedPlotLineIDs.Contains(plotLineId) ? NotFound() : PartialView("_Health", model);
|
||||
}
|
||||
|
||||
public async Task<IActionResult> Manuscript(int projectId, int? bookId, int sceneId)
|
||||
{
|
||||
var model = await workspace.GetManuscriptAsync(projectId, bookId, sceneId);
|
||||
|
||||
@ -45,7 +45,6 @@ public sealed class TimelineController(ITimelineService timeline) : Controller
|
||||
|
||||
current.ShowSceneCards = model.ShowSceneCards;
|
||||
current.ShowMetricShape = model.ShowMetricShape;
|
||||
current.ShowPlotLines = model.ShowPlotLines;
|
||||
current.ShowStoryAssets = model.ShowStoryAssets;
|
||||
current.ShowWarnings = model.ShowWarnings;
|
||||
current.SelectedMetricTypeIDs = model.SelectedMetricTypeIDs;
|
||||
|
||||
@ -57,3 +57,7 @@ Give each book a promise. Even in a series, every instalment should offer the re
|
||||
- [Chapters](/Help/Article/chapters.overview)
|
||||
- [Scenes](/Help/Article/scenes.overview)
|
||||
- [Plot Lines](/Help/Article/timeline.plotLines)
|
||||
|
||||
# Installed app ribbon
|
||||
|
||||
In the installed PlotDirector app, page Help and page-level commands are available in the contextual ribbon. Existing Project and Book ribbon commands are reused. Scope selectors, page-wide search and section jumps appear there when appropriate; workspace controls remain beside the content. If the ribbon is collapsed, choose **Expand ribbon** or select a ribbon category. The normal browser version keeps its existing page headings, buttons and Actions menus.
|
||||
|
||||
@ -29,7 +29,6 @@ If the concern is a smaller strand inside a larger arc, create a Plot Thread und
|
||||
| Book / scope | Whether the line belongs to one book or the whole project. | Project-wide for a series mystery; one book for a local subplot. |
|
||||
| Parent plot line | A larger Plot Line this one sits beneath. | A relationship arc inside a wider family mystery. |
|
||||
| Main plot | Marks this as central to the project's main story drive. | The central mystery or protagonist arc. |
|
||||
| Visible on timeline | Controls whether this line appears in planning/timeline displays. | Hide a background theme; show a mystery lane you actively track. |
|
||||
|
||||
# Related Guides
|
||||
|
||||
|
||||
@ -3,14 +3,14 @@ title: Plot Line Visibility
|
||||
category: Plot Lines
|
||||
tags: plot lines, fields, visibility, timeline
|
||||
contextKey: plotLines.fields.visibility
|
||||
micro: Choose whether this Plot Line appears in timeline planning views.
|
||||
quickTitle: Visible on timeline
|
||||
quickSummary: Visibility controls whether the Plot Line appears in timeline and planning displays.
|
||||
micro: Use the dedicated Plot Lines workspace for narrative routes.
|
||||
quickTitle: Plot Line visibility
|
||||
quickSummary: Legacy Timeline lane visibility is no longer an editing control.
|
||||
screenshot:
|
||||
---
|
||||
|
||||
# Visible On Timeline
|
||||
# Plot Line Visibility
|
||||
|
||||
Turn this on when you want the Plot Line visible in planning displays, especially while checking setup, development and payoff across scenes.
|
||||
Timeline no longer displays Plot Line lanes. Use the dedicated **Plot Lines** workspace to select the lines you want to follow. The old visibility value is retained for compatibility and is not an active lane control.
|
||||
|
||||
Turn it off for background themes or dormant lines that you want to keep in the project without crowding the timeline.
|
||||
- [Plot Lines Workspace](/Help/Article/plotLines.workspace)
|
||||
|
||||
@ -15,13 +15,25 @@ The Plot Lines workspace is a story map of scenes that contribute to selected pl
|
||||
|
||||
# Focus And Weave
|
||||
|
||||
Select one plot line for **Focus** mode. Select two or more for **Weave** mode. In Weave, a scene that contributes to several selected lines appears once as a shared junction, with each line's contribution shown inside the card.
|
||||
Select one plot line for **Focus** mode. Select two or more for **Weave** mode. In Weave, a scene that contributes to several selected lines appears once as a shared junction, connected to each participating route. Each line retains its own contribution role.
|
||||
|
||||
Use the thread filter when you need to isolate a smaller strand inside the selected lines. Use the book selector to narrow a series, or choose a scenario to inspect the same contributions in that scenario's proposed order. The workspace does not apply a scenario.
|
||||
|
||||
# Reading The Map
|
||||
|
||||
Manuscript order runs left to right. Each selected line has a separate horizontal route and a pinned name and number. Use **Edit colour** beside a line to change its saved colour. Legacy default colours use a stable colour derived from line identity. Scroll within the map or change Spacing to follow longer stories. Callouts alternate above and below routes; hover or keyboard focus reveals a short preview. Warnings remain small markers, with details in the inspector.
|
||||
|
||||
Thread labels mark known introduction scenes; missing boundaries are left unspecified. Dashed breaks show intervening scene and chapter counts for each line. Shared scenes appear once, with separate coloured connectors ending at the scene card. Explicit structural targets and visible scene dependencies are drawn only from stored connections.
|
||||
|
||||
# Associate Scenes
|
||||
|
||||
Switch from **View** to **Associate Scenes** to browse the manuscript sequence. Markers distinguish selected-line membership, other-line membership, pending suggestions and unattributed scenes. Select a scene and choose **Add selected scene** on a line, or drag it directly onto its horizontal route. The route highlights while it is a drop target.
|
||||
|
||||
The existing thread-event editor opens in a dialog. Choose a thread and event type, refine the title or description, and save. The editor closes after saving and the map updates in place, preserving Association mode and scroll positions. Less common structural fields are under **Connections / Advanced**. Switch back to View for the clean contribution map.
|
||||
|
||||
# Inspecting A Contribution
|
||||
|
||||
Select a scene card to open its inspector. The Contribution section keeps the canonical event and thread role primary. When a canonical event came from an imported narrative candidate and has an exact source-and-scene match, the Evidence section shows the imported title, description and evidence as supporting detail.
|
||||
Select a compact scene callout to open its inspector. The Contribution section keeps the canonical event and thread role primary. When a canonical event came from an imported narrative candidate and has an exact source-and-scene match, the Evidence section shows the imported title, description and evidence as supporting detail.
|
||||
|
||||
The Scene section shows scene context and loads manuscript text only when requested. Other Lines shows every canonical plot line represented in the scene.
|
||||
|
||||
@ -40,3 +52,23 @@ Open **Unattributed scenes** to distinguish:
|
||||
- [Plot Threads](/Help/Article/plotThreads.index)
|
||||
- [Scene Inspector Threads](/Help/Article/sceneInspector.threads)
|
||||
- [Timeline Plot Lines](/Help/Article/timeline.plotLines)
|
||||
|
||||
# Health Review
|
||||
|
||||
A small summary beside a line opens Health in the existing inspector. Diamond markers link to positioned evidence; a quiet-stretch marker at the route end covers trailing silence. No summary is shown when there are no findings.
|
||||
|
||||
**Stored author status** is the thread's saved planning/current status. **Observed activity** is what canonical scene contributions record. **Health** highlights Information, Review or Warning findings; it never changes status or fixes the manuscript automatically.
|
||||
|
||||
Mentions and notes count as touches, but do not reset meaningful progress. V1 reviews progress silence after **10 scenes**. Internal stretches count intervening scenes; trailing stretches count scenes after the last progress through the evaluated cutoff. Chapter distances count distinct ordered chapter identities after the source chapter, including across books; they do not subtract chapter numbers. Leading silence is factual, and an unstarted planned thread is informational.
|
||||
|
||||
Health also reviews recorded introductions without later development, open questions/clues, payoff readiness without evidence, status/boundary disagreements, closure ordering, contributions outside boundaries and explicit structural targets. Open at a book/project cutoff does not mean the author should have resolved the thread there. A payoff is recorded closure evidence, not proof that every thread in the line is resolved.
|
||||
|
||||
Select a finding to see its role, scenes, positions, stored status, scope and order, or open the existing thread/scene editor. Questions and clues use coarse recorded roles; these checks cannot judge whether a creative payoff is satisfying.
|
||||
|
||||
Focus and Weave evaluate whole selected lines, independently of scene search/thread filters. Scenario findings use scenario positions only. Partial coverage is labelled; absence-based findings become informational because omitted scenes may contain relevant events. Association mode remains unchanged; positioned health annotations do not compete with drop targets. Evidence is loaded only when requested.
|
||||
|
||||
Positioned resolution/abandonment and actual-resolution boundaries delimit ordinary quiet-stretch review. A later contribution is still shown as evidence of a possible disagreement. Undated stored status is never used to move a resolution backward to an earlier evaluated cutoff.
|
||||
|
||||
# Installed app ribbon
|
||||
|
||||
In the installed PlotDirector app, page Help and page-level commands are available in the contextual ribbon. Existing Project and Book ribbon commands are reused. Scope selectors, page-wide search and section jumps appear there when appropriate; workspace controls remain beside the content. If the ribbon is collapsed, choose **Expand ribbon** or select a ribbon category. The normal browser version keeps its existing page headings, buttons and Actions menus.
|
||||
|
||||
@ -50,3 +50,7 @@ Name projects for recognition, not perfection. A clear working title is more use
|
||||
- [Books](/Help/Article/books.overview)
|
||||
- [Characters](/Help/Article/characters.overview)
|
||||
- [Imports](/Help/Article/imports.overview)
|
||||
|
||||
# Installed app ribbon
|
||||
|
||||
In the installed PlotDirector app, page Help and page-level commands are available in the contextual ribbon. Existing Project and Book ribbon commands are reused. Scope selectors, page-wide search and section jumps appear there when appropriate; workspace controls remain beside the content. If the ribbon is collapsed, choose **Expand ribbon** or select a ribbon category. The normal browser version keeps its existing page headings, buttons and Actions menus.
|
||||
|
||||
@ -50,3 +50,7 @@ Make the Story Bible part of revision, not only planning. It becomes strongest w
|
||||
- [Story Assets](/Help/Article/storyAssets.overview)
|
||||
- [Locations](/Help/Article/locations.overview)
|
||||
- [Warnings](/Help/Article/warnings.overview)
|
||||
|
||||
# Installed app ribbon
|
||||
|
||||
In the installed PlotDirector app, page Help and page-level commands are available in the contextual ribbon. Existing Project and Book ribbon commands are reused. Scope selectors, page-wide search and section jumps appear there when appropriate; workspace controls remain beside the content. If the ribbon is collapsed, choose **Expand ribbon** or select a ribbon category. The normal browser version keeps its existing page headings, buttons and Actions menus.
|
||||
|
||||
@ -11,7 +11,7 @@ screenshot:
|
||||
|
||||
# Overview
|
||||
|
||||
Character appearances remain available through character filters, focus, scene search, scene cards and the Scene Inspector. The general Timeline no longer renders a separate lane for every character; this keeps the planning view centred on scenes, plot lines, assets, metrics and warnings.
|
||||
Character appearances remain available through character filters, focus, scene search, scene cards and the Scene Inspector. The general Timeline no longer renders a separate lane for every character; this keeps the planning view centred on scenes, chronology, assets, metrics and warnings.
|
||||
|
||||
Use a character filter or character focus to narrow the Timeline. Open a scene's inspector to review role, presence, location, entry and exit, appearance, outfit, physical and emotional state, and knowledge notes.
|
||||
|
||||
|
||||
@ -11,4 +11,4 @@ screenshot:
|
||||
|
||||
# Overview
|
||||
|
||||
Use scene jump when you know the scene. Use warning jump during continuity review. Use lane item jump when you want the first visible occurrence of a character, asset or plot line.
|
||||
Use scene jump when you know the scene. Use warning jump during continuity review. Use asset or location jump for the first matching scene when entries are available. Plot Line and Plot Thread filters focus ordinary scenes; use the dedicated Plot Lines workspace for narrative routes.
|
||||
|
||||
@ -5,15 +5,13 @@ tags: timeline, scenes, continuity, planning, pacing
|
||||
contextKey: timeline.overview
|
||||
micro: Understand the Timeline as the planning spine for scenes, continuity and story shape.
|
||||
quickTitle: What is the Timeline?
|
||||
quickSummary: The Timeline shows how books, chapters and scenes connect to plot threads, characters, assets, metrics and continuity checks.
|
||||
quickSummary: Timeline shows when scenes occur and how books, chapters and manuscript scenes are ordered.
|
||||
screenshot:
|
||||
---
|
||||
|
||||
# Overview
|
||||
|
||||
The Timeline is the central planning view for a project. It lays out the story from project to book to chapter to scene, then adds the evidence that helps you see whether the story is developing cleanly: plot threads, character appearances, important assets, scene metrics, locations, warnings and story health signals.
|
||||
|
||||
Use it when you want to step back from individual scene editing and ask, "What is happening across the whole story?" A mystery writer might follow the clue trail, a romance writer might watch emotional closeness build and break, and a series writer might check whether an object or secret has stayed consistent across books.
|
||||
Timeline is the chronology and manuscript structure view: books, chapters, scenes, dates, metrics, dependencies and navigation. Use **Plot Lines** to understand how narrative threads develop and interact through the manuscript.
|
||||
|
||||
# The Timeline Hierarchy
|
||||
|
||||
@ -27,11 +25,11 @@ A scene is the basic unit of story movement. Scene cards are where PlotDirector
|
||||
|
||||
# How Timeline Connects To Other Systems
|
||||
|
||||
Plot Threads appear as thread event markers so you can see where questions start, develop, twist, branch and resolve.
|
||||
Plot Line and Plot Thread filters select ordinary scenes. Focus highlights matching scenes; narrative routes and contribution editing belong to the dedicated Plot Lines workspace.
|
||||
|
||||
Metrics turn individual scene ratings into a visible pacing shape. They help you spot long flat stretches, repeated peaks or scenes that need a quieter beat.
|
||||
|
||||
Characters appear in lanes and scene cards so you can follow presence, point of view, activity and continuity.
|
||||
Characters appear in scene cards and the Scene Inspector so you can follow presence, point of view, activity and continuity.
|
||||
|
||||
Assets appear when important objects, clues, weapons, documents or evidence change state, location or custody.
|
||||
|
||||
@ -55,6 +53,10 @@ For pacing, compare intensity, tension, action, hope, comedy or mystery across t
|
||||
|
||||
- [Scene Cards](/Help/Article/timeline.sceneCards)
|
||||
- [Filters and Focus](/Help/Article/timeline.filters)
|
||||
- [Plot Thread Lanes](/Help/Article/timeline.plotThreadLanes)
|
||||
- [Plot Lines Workspace](/Help/Article/plotLines.workspace)
|
||||
- [Scene Inspector](/Help/Article/sceneInspector.overview)
|
||||
- [Story Health](/Help/Article/storyHealth.overview)
|
||||
|
||||
# Installed app ribbon
|
||||
|
||||
In the installed PlotDirector app, page Help and page-level commands are available in the contextual ribbon. Existing Project and Book ribbon commands are reused. Scope selectors, page-wide search and section jumps appear there when appropriate; workspace controls remain beside the content. If the ribbon is collapsed, choose **Expand ribbon** or select a ribbon category. The normal browser version keeps its existing page headings, buttons and Actions menus.
|
||||
|
||||
@ -11,6 +11,8 @@ screenshot:
|
||||
|
||||
# Overview
|
||||
|
||||
Timeline uses Plot Line membership to filter or focus ordinary scenes. Open the dedicated [Plot Lines workspace](/Help/Article/plotLines.workspace) to follow narrative routes, threads and scene contributions.
|
||||
|
||||
Plot Lines are broad story lanes that help you follow unresolved material across scenes, chapters and books. They are useful for mysteries, subplots, relationship arcs, political schemes, investigations, emotional promises, clue chains and long-range series questions.
|
||||
|
||||
A plot line is not necessarily the same thing as the main plot. A book may have one central plot line and several smaller ones. For example, a mystery novel might track "Who killed Arthur?", "Rebecca's family history", "Beth's hidden loyalty" and "The missing railway timetable" as separate plot lines.
|
||||
|
||||
@ -1,52 +1,19 @@
|
||||
---
|
||||
title: Plot Thread Lanes
|
||||
title: Plot Line Scene Filtering
|
||||
category: Timeline
|
||||
tags: timeline, plot threads, events, reveals, continuity
|
||||
tags: timeline, plot threads
|
||||
contextKey: timeline.plotThreadLanes
|
||||
micro: Follow plot thread events across scenes.
|
||||
quickTitle: Plot thread lanes
|
||||
quickSummary: Plot thread lanes show where story questions begin, develop, twist, branch, merge, resolve or are intentionally abandoned.
|
||||
micro: Filter Timeline scenes by Plot Line or Plot Thread; use Plot Lines for narrative routes.
|
||||
quickTitle: Plot Line Scene Filtering
|
||||
quickSummary: Filter Timeline scenes by Plot Line or Plot Thread; use Plot Lines for narrative routes.
|
||||
screenshot:
|
||||
---
|
||||
|
||||
# Overview
|
||||
|
||||
Plot thread lanes turn scattered story promises into a visible path. A lane helps you see whether a mystery, relationship question, political scheme, secret, clue chain or emotional promise is being carried through the scenes.
|
||||
Timeline displays chronology and manuscript structure. Its Plot Line and Plot Thread filters select ordinary scene cards; focus highlights their scenes. Timeline does not draw Plot Line or Plot Thread lanes.
|
||||
|
||||
Each marker is a thread event attached to a scene. The marker is not just a button; it records what the scene does for the reader's expectation.
|
||||
Open **Plot Lines** for narrative routes, scene contributions, threads, gaps, shared scenes and association editing.
|
||||
|
||||
# Thread Events
|
||||
|
||||
Start begins a thread. Use it when the reader first receives a question or promise, such as "Who sent the letter?"
|
||||
|
||||
Progress develops the thread without solving it. A suspect lies, a clue deepens the question, or a relationship takes a meaningful step.
|
||||
|
||||
Reveal gives the reader or a character new truth. For example, the locked room was opened from inside.
|
||||
|
||||
Twist changes the reader's interpretation. The friendly witness is connected to the victim.
|
||||
|
||||
Branch creates a new related thread from an existing one. A missing key leads to a second question about who had access.
|
||||
|
||||
Split divides one thread into multiple concerns. A conspiracy thread might split into motive, method and cover-up.
|
||||
|
||||
Merge brings related threads together. Two apparently separate clues point to the same culprit.
|
||||
|
||||
Resolve pays off the thread. The question is answered or the emotional promise is fulfilled.
|
||||
|
||||
Abandon marks an intentional drop. Use it when a character gives up, a false trail is deliberately left unresolved, or the story chooses not to answer because that is the point.
|
||||
|
||||
# Common Uses
|
||||
|
||||
Track a mystery from clue to reveal.
|
||||
|
||||
Track a romance from attraction to rupture to reconciliation.
|
||||
|
||||
Track a character arc promise from wound to choice to change.
|
||||
|
||||
Track a series question that should not vanish between books.
|
||||
|
||||
# Related Guides
|
||||
|
||||
- [Thread Health](/Help/Article/timeline.threadHealth)
|
||||
- [Plot Threads](/Help/Article/sceneInspector.threads)
|
||||
- [Plot Lines](/Help/Article/timeline.plotLines)
|
||||
- [Plot Lines Workspace](/Help/Article/plotLines.workspace)
|
||||
- [Filters and Focus](/Help/Article/timeline.filters)
|
||||
|
||||
@ -21,7 +21,7 @@ A character-focused view shows one character's scenes, appearances and relevant
|
||||
|
||||
A romance view can combine the couple, relationship events, romance metrics and emotional weight.
|
||||
|
||||
A mystery view can focus on the investigation plot line, thread events, asset evidence and Mystery metric.
|
||||
A mystery view can focus on scenes associated with the investigation plot line or thread, asset evidence and the Mystery metric.
|
||||
|
||||
A revision view can show warnings, revision status, purpose and pacing while hiding lanes you do not need for that pass.
|
||||
|
||||
|
||||
@ -1,36 +1,22 @@
|
||||
---
|
||||
title: Thread Health
|
||||
title: Plot Thread Review
|
||||
category: Timeline
|
||||
tags: timeline, plot threads, story health, warnings
|
||||
tags: timeline, plot threads
|
||||
contextKey: timeline.threadHealth
|
||||
micro: Use thread health warnings to find storylines that may have been forgotten.
|
||||
quickTitle: Thread health
|
||||
quickSummary: Thread health helps you spot neglected, dangling, questionably resolved or abandoned plot threads before readers feel the gap.
|
||||
micro: Use existing Story Health and Continuity tools to review thread concerns.
|
||||
quickTitle: Plot Thread Review
|
||||
quickSummary: Use existing Story Health and Continuity tools to review thread concerns.
|
||||
screenshot:
|
||||
---
|
||||
|
||||
# Overview
|
||||
|
||||
Thread health is a revision aid. It looks for plot threads that may have gone quiet for too long, resolved too weakly, or been left dangling after the story promised the reader attention.
|
||||
Timeline no longer calculates or draws Plot Line lane health markers.
|
||||
|
||||
A healthy thread has a clear start, meaningful development and an intentional outcome. It does not need constant activity, but its silence should feel deliberate.
|
||||
Existing **Story Health** analytics and **Continuity** warnings remain available. Persisted Continuity warnings may still appear beside affected Timeline scenes. These are distinct from the retired lane heuristics.
|
||||
|
||||
# Warning Types
|
||||
Use **Plot Lines** to inspect narrative contributions.
|
||||
|
||||
Neglected threads have not appeared for a while. This may be fine for a slow-burn mystery, but it may also mean the thread was forgotten.
|
||||
|
||||
Dangling threads have no satisfying resolution yet. They are useful during drafting and risky near the end of a book.
|
||||
|
||||
Questionable resolutions suggest the payoff may not have enough setup or may occur in an odd place.
|
||||
|
||||
Abandoned threads are marked as intentionally dropped. This can be right for false leads, character failures or unresolved series questions, but the choice should be conscious.
|
||||
|
||||
# How To Use It
|
||||
|
||||
Use warnings as prompts, not verdicts. If the story intentionally withholds a thread for ten chapters, keep it. If you forgot the thread existed, add a progress, reveal or resolution event where the draft needs one.
|
||||
|
||||
# Related Guides
|
||||
|
||||
- [Plot Thread Lanes](/Help/Article/timeline.plotThreadLanes)
|
||||
- [Story Health Plot Thread Health](/Help/Article/storyHealth.plotThreadHealth)
|
||||
- [Continuity Warnings](/Help/Article/warnings.overview)
|
||||
- [Plot Lines Workspace](/Help/Article/plotLines.workspace)
|
||||
|
||||
39
PlotLine/Help/Articles/Workspace/Desktop.md
Normal file
39
PlotLine/Help/Articles/Workspace/Desktop.md
Normal file
@ -0,0 +1,39 @@
|
||||
---
|
||||
title: PlotDirector Desktop
|
||||
slug: desktop
|
||||
category: Workspace
|
||||
tags: desktop, installation, browser, app
|
||||
contextKey: workspace.desktop
|
||||
micro: More room for your story, with the same projects and data.
|
||||
quickTitle: What is PlotDirector Desktop?
|
||||
quickSummary: Install PlotDirector in its own application window for more workspace and contextual desktop controls. An internet connection is required.
|
||||
screenshot:
|
||||
---
|
||||
|
||||
# The same PlotDirector. Less browser.
|
||||
|
||||
PlotDirector Desktop opens in a dedicated application window. It gives your workspace more room, puts relevant page controls in the contextual ribbon and offers right-click actions for scenes, chapters, characters and other objects. Hold Ctrl while right-clicking to open the browser's own menu.
|
||||
|
||||
Your projects and data are the same. There is nothing to move or transfer, and updates arrive through PlotDirector without a traditional software update cycle. **An internet connection is still required.** Browser use remains fully available.
|
||||
|
||||
# Install or compare
|
||||
|
||||
In the account menu, choose **PlotDirector Desktop** to reopen the genuine Browser/Desktop comparison, then choose **Install PlotDirector Desktop**. When available, this opens your browser's own installation prompt. Otherwise it shows instructions for your browser.
|
||||
|
||||
- **Chrome desktop:** ⋮ → Cast, save, and share → Install page as app… The address bar may also offer an install icon.
|
||||
- **Edge desktop:** … → More tools → Apps → Install this site as an app.
|
||||
- **Safari on macOS Sonoma or later:** File → Add to Dock → Add.
|
||||
- **iPhone or iPad:** in Safari, Share → Add to Home Screen. Enable Open as Web App if offered, then Add.
|
||||
- **Android:** use the browser menu's Install app or Add to Home screen option if offered.
|
||||
|
||||
Menu names and availability vary by browser version, operating system and organisation policy. Private browsing may prevent installation. If no installation option is available, try current Chrome or Edge on desktop. Other browsers can continue using PlotDirector normally; a programmatic install prompt is not available everywhere.
|
||||
|
||||
If PlotDirector is already installed, open it from your Start menu, taskbar, Dock or application launcher. A browser tab cannot reliably detect every existing installation. Cancelling a prompt does not install the app.
|
||||
|
||||
# Your choice
|
||||
|
||||
Choose **Continue in browser**, the close button or Escape to dismiss the comparison. Automatic promotion is reserved for project workspaces with a book. Dismissal is saved for this account in this browser on this device. After 30 days a small reminder may offer Compare; the full takeover does not repeat automatically. The account-menu entry remains available in browser mode. Clearing browser storage resets these preferences.
|
||||
|
||||
The installed app never shows its own install promotion.
|
||||
|
||||
Installation menu references: [Chrome Help](https://support.google.com/chrome/answer/9658361), [Edge Help](https://support.microsoft.com/en-us/edge/install-manage-or-uninstall-apps-in-microsoft-edge), [Safari Help](https://support.apple.com/en-gb/104996).
|
||||
@ -56,3 +56,20 @@ Use the workspace to protect momentum. If you have low energy, pick a polishing
|
||||
- [Scenes](/Help/Article/scenes.overview)
|
||||
- [Chapters](/Help/Article/chapters.overview)
|
||||
- [Project Settings](/Help/Article/projectSettings.overview)
|
||||
|
||||
# Installed desktop app
|
||||
|
||||
In the installed PlotDirector app, the ribbon also provides controls for the current page. Page tools, exports, scope selectors, page-wide search, section jumps and Help appear there when appropriate. The content area begins closer to the workspace. Contextual groups continue to the right of the existing ribbon groups, without another toolbar or title strip. Existing ribbon commands are reused. At wider widths, commands appear directly; as space narrows, related groups collapse into ribbon menus.
|
||||
|
||||
**Help** in the contextual ribbon opens help for the current page. **Jump to** navigates through long reference pages such as the Story Bible, and its Search control remains available as you scroll. Use **Expand ribbon**, or select a command category, to reach these controls when the ribbon is collapsed.
|
||||
|
||||
The normal browser version keeps its breadcrumbs, headings, page buttons and Actions menus. Workspace controls, editors and item-level commands remain beside the content they operate on in both versions. No functionality has been removed.
|
||||
|
||||
|
||||
# Desktop context menus
|
||||
|
||||
In the installed desktop app, right-click scenes, chapters, characters and other PlotDirector objects for context-specific actions. These are shortcuts to the same actions available through the ribbon and normal page controls. Right-click blank workspace space for useful page actions; editable text fields offer Cut, Copy, Paste and Select All where applicable. Clipboard access follows your browser's permissions.
|
||||
|
||||
Use Shift+F10 or the Context Menu key on a focused object to open its menu. Use arrow keys to move, Right/Left to enter or leave a submenu, Enter to choose and Escape to close.
|
||||
|
||||
Advanced fallback: **Ctrl + right-click opens the browser's native context menu**, including inside text fields. Normal website tabs retain their usual browser right-click behavior.
|
||||
|
||||
48
PlotLine/Models/PlotHealthModels.cs
Normal file
48
PlotLine/Models/PlotHealthModels.cs
Normal file
@ -0,0 +1,48 @@
|
||||
namespace PlotLine.Models;
|
||||
|
||||
public enum PlotHealthLevel { Information, Review, Warning }
|
||||
|
||||
public sealed record PlotHealthScope(int ProjectID, int? BookID, int? ScenarioID, int CutoffPosition,
|
||||
int SceneCount, bool EvidenceComplete, int MissingSceneCount)
|
||||
{
|
||||
public string OrderLabel => ScenarioID.HasValue ? $"Scenario {ScenarioID}" : "Canonical manuscript";
|
||||
public string ScopeLabel => BookID.HasValue ? $"Book {BookID}" : "Current project";
|
||||
}
|
||||
|
||||
public sealed record PlotHealthEvidence(int SceneID, int Position, int BookID, int ChapterID,
|
||||
string SceneTitle, string Signal, int? ThreadEventID = null);
|
||||
|
||||
public sealed record PlotHealthFinding(string RuleID, PlotHealthLevel Level, int PlotLineID, int? PlotThreadID,
|
||||
string Title, string Explanation, string StoredStatus, IReadOnlyList<PlotHealthEvidence> Evidence,
|
||||
PlotHealthScope Scope, int? MarkerSceneID, int? ScenesWithoutProgress = null, int? ChaptersWithoutProgress = null)
|
||||
{
|
||||
public string EntityType => PlotThreadID.HasValue ? "PlotThread" : "PlotLine";
|
||||
public bool EvidenceComplete => Scope.EvidenceComplete;
|
||||
}
|
||||
|
||||
public sealed record PlotThreadHealth(int PlotLineID, int PlotThreadID, string ThreadTitle, string StoredStatus,
|
||||
IReadOnlyList<string> ObservedSignals, PlotHealthEvidence? FirstTouch, PlotHealthEvidence? LastTouch,
|
||||
PlotHealthEvidence? LastProgress, int LeadingScenes, int? ScenesSinceTouch, int? ChaptersSinceTouch,
|
||||
int? ScenesSinceProgress, int? ChaptersSinceProgress, IReadOnlyList<PlotHealthFinding> Findings);
|
||||
|
||||
public sealed record PlotLineHealth(int PlotLineID, IReadOnlyList<PlotThreadHealth> Threads,
|
||||
IReadOnlyList<PlotHealthFinding> Findings)
|
||||
{
|
||||
public int InformationCount => Findings.Count(f => f.Level == PlotHealthLevel.Information);
|
||||
public int ReviewCount => Findings.Count(f => f.Level == PlotHealthLevel.Review);
|
||||
public int WarningCount => Findings.Count(f => f.Level == PlotHealthLevel.Warning);
|
||||
public string Summary => string.Join(" · ", new[] {
|
||||
WarningCount > 0 ? $"{WarningCount} warning" : null,
|
||||
ReviewCount > 0 ? $"{ReviewCount} review" : null,
|
||||
InformationCount > 0 ? $"{InformationCount} info" : null }.Where(x => x is not null));
|
||||
}
|
||||
|
||||
public sealed record PlotHealthResult(PlotHealthScope Scope, IReadOnlyList<PlotLineHealth> Lines)
|
||||
{
|
||||
public static PlotHealthResult Empty { get; } = new(new(0, null, null, 0, 0, true, 0), []);
|
||||
public IReadOnlyList<PlotHealthFinding> Findings => Lines.SelectMany(l => l.Findings).ToList();
|
||||
}
|
||||
|
||||
public sealed record PlotHealthContext(int ProjectID, int? BookID, int? ScenarioID,
|
||||
IReadOnlyCollection<int> SelectedLineIDs, PlotLineWorkspaceData Data,
|
||||
PlotLineWorkspaceData ReferenceData, int? CutoffPosition = null);
|
||||
@ -10,6 +10,8 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Dapper" Version="2.1.79" />
|
||||
<PackageReference Include="Microsoft.Data.SqlClient" Version="7.0.1" />
|
||||
<!-- Patch the SQL client transitive CMS dependency (October 2026 security advisories). -->
|
||||
<PackageReference Include="System.Security.Cryptography.Pkcs" Version="9.0.21" />
|
||||
<PackageReference Include="QRCoder" Version="1.6.0" />
|
||||
<PackageReference Include="SkiaSharp" Version="3.119.4" />
|
||||
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="3.119.4" />
|
||||
|
||||
@ -187,6 +187,7 @@ public class Program
|
||||
builder.Services.AddScoped<ISceneMetricValueService, SceneMetricValueService>();
|
||||
builder.Services.AddScoped<IPlotService, PlotService>();
|
||||
builder.Services.AddScoped<IPlotLineWorkspaceService, PlotLineWorkspaceService>();
|
||||
builder.Services.AddSingleton<IPlotHealthEvaluator, PlotHealthEvaluator>();
|
||||
builder.Services.AddScoped<IAssetService, AssetService>();
|
||||
builder.Services.AddScoped<ICharacterService, CharacterService>();
|
||||
builder.Services.AddScoped<ILocationService, LocationService>();
|
||||
|
||||
@ -49,7 +49,7 @@ public static class ApplicationRibbon
|
||||
"Story Bible" or "Metrics" or "Health" or "Warnings" or "Archive" => "tools", _ => "project"
|
||||
}
|
||||
};
|
||||
public static ToolbarCommand Icon(string key) => ToolbarCommands.All.Single(x => x.Key == key);
|
||||
public static RibbonIcon Icon(string key) => RibbonPresentation.Icons.Single(x => x.Key == key);
|
||||
public static string Tone(string key) => key switch
|
||||
{
|
||||
"calendar" or "point" => "calendar", "characters" or "names" => "characters", "locations" or "floorplans" => "locations",
|
||||
|
||||
@ -2568,7 +2568,8 @@ public sealed class TimelineService(
|
||||
.OrderBy(x => x.SortOrder)
|
||||
.Select(x => x.MetricTypeID)
|
||||
.ToList();
|
||||
var needsPlotTimelineData = settings.ShowPlotLines || filter.PlotLineID.HasValue || filter.PlotThreadID.HasValue || filter.FocusType is "plotline" or "plotthread";
|
||||
// Canonical memberships still support ordinary scene search, filters and focus.
|
||||
var needsPlotTimelineData = settings.ShowSceneCards || filter.PlotLineID.HasValue || filter.PlotThreadID.HasValue || filter.FocusType is "plotline" or "plotthread";
|
||||
var needsMetricTimelineData = settings.ShowMetricShape && selectedMetricIds.Any();
|
||||
var needsAssetTimelineData = settings.ShowStoryAssets || filter.StoryAssetID.HasValue || filter.FocusType == "asset";
|
||||
// Character data remains available for filters, POV chips, quick-add and inspector behaviour,
|
||||
@ -2632,15 +2633,6 @@ public sealed class TimelineService(
|
||||
var sceneOverviewRows = settings.ShowSceneCards
|
||||
? await TimeTimelineLoadAsync("dbo.Timeline_SceneOverviews", () => timelineRepository.GetSceneOverviewsAsync(projectId, bookId), projectId, bookId)
|
||||
: [];
|
||||
var plotThreadDetailsById = plotThreads.ToDictionary(x => x.PlotThreadID);
|
||||
foreach (var threadEvent in timeline.ThreadEvents)
|
||||
{
|
||||
if (plotThreadDetailsById.TryGetValue(threadEvent.PlotThreadID, out var thread))
|
||||
{
|
||||
threadEvent.ThreadStatusName = thread.ThreadStatusName;
|
||||
threadEvent.Importance = thread.Importance;
|
||||
}
|
||||
}
|
||||
var scenePovLabels = characterTimeline.Appearances
|
||||
.Where(x => x.RoleInSceneTypeName?.Contains("POV", StringComparison.OrdinalIgnoreCase) == true)
|
||||
.GroupBy(x => x.SceneID)
|
||||
@ -2654,9 +2646,6 @@ public sealed class TimelineService(
|
||||
var metricGraphs = settings.ShowMetricShape
|
||||
? await TimeTimelineLoadAsync("TimelineService.BuildMetricGraphs", () => Task.FromResult(BuildMetricGraphs(timeline, orderedScenes)), projectId, bookId)
|
||||
: [];
|
||||
var plotLanes = settings.ShowPlotLines
|
||||
? await TimeTimelineLoadAsync("TimelineService.BuildPlotLanes", () => Task.FromResult(BuildPlotLanes(timeline, orderedScenes)), projectId, bookId)
|
||||
: [];
|
||||
var assetLanes = settings.ShowStoryAssets
|
||||
? await TimeTimelineLoadAsync("TimelineService.BuildAssetLanes", () => Task.FromResult(BuildAssetLanes(assetTimeline.Assets, assetTimeline.Events, orderedScenes)), projectId, bookId)
|
||||
: [];
|
||||
@ -2736,7 +2725,9 @@ public sealed class TimelineService(
|
||||
}).ToList(),
|
||||
OrderedScenes = orderedScenes,
|
||||
MetricGraphs = metricGraphs,
|
||||
PlotLanes = plotLanes,
|
||||
ScenePlotSearchText = timeline.ThreadEvents.GroupBy(x => x.SceneID).ToDictionary(
|
||||
group => group.Key,
|
||||
group => string.Join(" ", group.Select(evt => $"{evt.PlotLineName} {evt.ThreadTitle} {evt.EventTitle}"))),
|
||||
AssetLanes = assetLanes,
|
||||
CharacterLanes = [],
|
||||
SceneOverviews = sceneOverviews,
|
||||
@ -2770,7 +2761,6 @@ public sealed class TimelineService(
|
||||
ProjectName = project.ProjectName,
|
||||
ShowSceneCards = settings.ShowSceneCards,
|
||||
ShowMetricShape = settings.ShowMetricShape,
|
||||
ShowPlotLines = settings.ShowPlotLines,
|
||||
ShowStoryAssets = settings.ShowStoryAssets,
|
||||
ShowWarnings = settings.ShowWarnings,
|
||||
SelectedMetricTypeIDs = selectedMetricIds.ToList(),
|
||||
@ -2801,7 +2791,8 @@ public sealed class TimelineService(
|
||||
ProjectID = model.ProjectID,
|
||||
ShowSceneCards = model.ShowSceneCards,
|
||||
ShowMetricShape = model.ShowMetricShape,
|
||||
ShowPlotLines = model.ShowPlotLines,
|
||||
// Preserve the harmless legacy preference without exposing or using it for rendering.
|
||||
ShowPlotLines = (await timelineSettings.GetAsync(model.ProjectID))?.ShowPlotLines ?? true,
|
||||
ShowStoryAssets = model.ShowStoryAssets,
|
||||
ShowCharacterAppearances = false,
|
||||
ShowWarnings = model.ShowWarnings
|
||||
@ -3130,34 +3121,6 @@ public sealed class TimelineService(
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
private static IReadOnlyList<PlotLineLaneViewModel> BuildPlotLanes(TimelineData timeline, IReadOnlyList<Scene> orderedScenes)
|
||||
{
|
||||
var eventsByPlotLineAndScene = timeline.ThreadEvents
|
||||
.GroupBy(x => x.PlotLineID)
|
||||
.ToDictionary(
|
||||
lineGroup => lineGroup.Key,
|
||||
lineGroup => lineGroup.GroupBy(x => x.SceneID).ToDictionary(sceneGroup => sceneGroup.Key, sceneGroup => sceneGroup.ToList()));
|
||||
|
||||
return timeline.PlotLines
|
||||
.OrderBy(x => x.SortOrder)
|
||||
.ThenBy(x => x.PlotLineName)
|
||||
.Select(plotLine =>
|
||||
{
|
||||
eventsByPlotLineAndScene.TryGetValue(plotLine.PlotLineID, out var sceneEvents);
|
||||
return new PlotLineLaneViewModel
|
||||
{
|
||||
PlotLine = plotLine,
|
||||
SceneSlots = orderedScenes.Select(scene => new PlotLaneSceneViewModel
|
||||
{
|
||||
Scene = scene,
|
||||
Events = sceneEvents is not null && sceneEvents.TryGetValue(scene.SceneID, out var events)
|
||||
? events
|
||||
: []
|
||||
}).ToList()
|
||||
};
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
private static IReadOnlyList<AssetLaneViewModel> BuildAssetLanes(IReadOnlyList<StoryAsset> assets, IReadOnlyList<AssetEvent> events, IReadOnlyList<Scene> orderedScenes)
|
||||
{
|
||||
var eventsByAssetAndScene = events
|
||||
@ -4785,7 +4748,7 @@ public sealed class PlotService(IProjectRepository projects, IBookRepository boo
|
||||
ParentPlotLineID = plotLine.ParentPlotLineID,
|
||||
EmergesFromPlotLineID = plotLine.EmergesFromPlotLineID,
|
||||
SortOrder = plotLine.SortOrder,
|
||||
Colour = plotLine.Colour,
|
||||
Colour = PlotLineColours.ForLine(plotLine.PlotLineID, plotLine.Colour),
|
||||
IsVisibleOnTimeline = plotLine.IsVisibleOnTimeline,
|
||||
Project = project
|
||||
}, lookupData, plotLines.Where(x => x.PlotLineID != plotLine.PlotLineID));
|
||||
|
||||
183
PlotLine/Services/PlotHealthEvaluator.cs
Normal file
183
PlotLine/Services/PlotHealthEvaluator.cs
Normal file
@ -0,0 +1,183 @@
|
||||
using PlotLine.Models;
|
||||
|
||||
namespace PlotLine.Services;
|
||||
|
||||
/// <summary>Workspace V1 policy. A touch is any canonical event; these roles alone reset progress.</summary>
|
||||
public static class PlotHealthProgressPolicy
|
||||
{
|
||||
public const int QuietSceneThreshold = 10;
|
||||
private static readonly HashSet<string> Roles = new(StringComparer.OrdinalIgnoreCase) {
|
||||
"Introduced", "Developed", "Complicated", "Clue Planted", "Question Raised", "Question Answered",
|
||||
"False Lead", "Revealed", "Payoff", "Resolved", "Contradicted", "Retconned" };
|
||||
public static bool IsMeaningful(string role) => Roles.Contains(role);
|
||||
}
|
||||
|
||||
public interface IPlotHealthEvaluator
|
||||
{
|
||||
PlotHealthResult Evaluate(PlotHealthContext context);
|
||||
}
|
||||
|
||||
/// <summary>Pure canonical-data evaluation; never saves status, warnings, or inferred intent.</summary>
|
||||
public sealed class PlotHealthEvaluator : IPlotHealthEvaluator
|
||||
{
|
||||
public PlotHealthResult Evaluate(PlotHealthContext context)
|
||||
{
|
||||
var ordered = context.Data.AttributionScenes.DistinctBy(s => s.SceneID).OrderBy(s => s.NarrativeOrder).ToList();
|
||||
var positions = ordered.Select((s, i) => (s.SceneID, Position: i + 1)).ToDictionary(x => x.SceneID, x => x.Position);
|
||||
var cutoff = Math.Clamp(context.CutoffPosition ?? ordered.Count, 0, ordered.Count);
|
||||
var scopeScenes = ordered.Take(cutoff).ToDictionary(s => s.SceneID);
|
||||
var expected = context.ReferenceData.AttributionScenes.Where(s => !context.BookID.HasValue || s.BookID == context.BookID).Select(s => s.SceneID).ToHashSet();
|
||||
var missing = expected.Except(positions.Keys).Count();
|
||||
var scope = new PlotHealthScope(context.ProjectID, context.BookID, context.ScenarioID, cutoff, ordered.Count, missing == 0, missing);
|
||||
var cutoffEvidence = cutoff > 0 ? SceneEvidence(ordered[cutoff - 1].SceneID, "Evaluated cutoff") : null;
|
||||
var eventsByThread = context.Data.Contributions.Where(e => scopeScenes.ContainsKey(e.SceneID))
|
||||
.DistinctBy(e => e.ThreadEventID).GroupBy(e => e.PlotThreadID).ToDictionary(g => g.Key, g => g.OrderBy(e => positions[e.SceneID]).ThenBy(e => e.ThreadEventID).ToList());
|
||||
var selected = context.SelectedLineIDs.ToHashSet();
|
||||
var targetLookup = context.ReferenceData.PlotLines.ToDictionary(l => l.PlotLineID);
|
||||
var lineEvents = context.Data.Contributions.Where(e => scopeScenes.ContainsKey(e.SceneID)).ToLookup(e => e.PlotLineID);
|
||||
var targetsByEvent = context.Data.Targets.ToLookup(t => t.ThreadEventID);
|
||||
var lines = new List<PlotLineHealth>();
|
||||
foreach (var line in context.Data.PlotLines.Where(l => selected.Contains(l.PlotLineID) && (!context.BookID.HasValue || !l.BookID.HasValue || l.BookID == context.BookID)))
|
||||
{
|
||||
var threads = new List<PlotThreadHealth>();
|
||||
foreach (var thread in context.Data.Threads.Where(t => t.PlotLineID == line.PlotLineID))
|
||||
{
|
||||
var events = eventsByThread.GetValueOrDefault(thread.PlotThreadID, []);
|
||||
var progress = events.Where(e => PlotHealthProgressPolicy.IsMeaningful(e.CanonicalRole)).ToList();
|
||||
var introduced = events.Where(e => Role(e, "Introduced")).ToList();
|
||||
var closures = events.Where(e => Role(e, "Resolved", "Payoff") || Structural(e, "Resolve", "Abandon")).ToList();
|
||||
var resolutions = events.Where(e => Role(e, "Resolved") || Structural(e, "Resolve")).ToList();
|
||||
var abandonments = events.Where(e => Structural(e, "Abandon")).ToList();
|
||||
var first = events.FirstOrDefault();
|
||||
var last = events.LastOrDefault();
|
||||
var lastProgress = progress.LastOrDefault();
|
||||
var actual = SceneEvidence(thread.ActualResolutionSceneID, "Actual resolution boundary");
|
||||
var intro = SceneEvidence(thread.IntroducedSceneID, "Introduction boundary");
|
||||
var findings = new List<PlotHealthFinding>();
|
||||
PlotHealthEvidence Evidence(PlotLineWorkspaceContributionRow e) => SceneEvidence(e.SceneID,
|
||||
$"{e.CanonicalRole} · {e.CanonicalStructuralType}", e.ThreadEventID)!;
|
||||
void Add(string rule, PlotHealthLevel level, string title, string explanation,
|
||||
IEnumerable<PlotHealthEvidence?> evidence, int? marker = null, bool absence = false,
|
||||
int? silence = null, int? chapters = null)
|
||||
{
|
||||
if (!scope.EvidenceComplete)
|
||||
{
|
||||
explanation += $" Partial order: {scope.MissingSceneCount} scope scenes are omitted; no conclusion is made about their events.";
|
||||
if (absence) { level = PlotHealthLevel.Information; title += " (partial evidence)"; }
|
||||
}
|
||||
findings.Add(new(rule, level, line.PlotLineID, thread.PlotThreadID, title, explanation,
|
||||
thread.ThreadStatusName, evidence.Where(e => e is not null).Cast<PlotHealthEvidence>().Distinct().ToList(), scope,
|
||||
marker ?? last?.SceneID ?? cutoffEvidence?.SceneID, silence, chapters));
|
||||
}
|
||||
if (events.Count == 0)
|
||||
Add("H001", PlotHealthLevel.Information, "No recorded contributions", "No canonical contribution events are recorded for this thread in the evaluated scope through the cutoff. This does not mean it should already have started.", [intro, cutoffEvidence], absence: true);
|
||||
|
||||
// Internal silence uses intervening scenes; trailing silence includes every scene after progress through the cutoff.
|
||||
var progressScenes = progress.DistinctBy(e => e.SceneID).ToList();
|
||||
for (var i = 0; i < progressScenes.Count; i++)
|
||||
{
|
||||
var previous = progressScenes[i];
|
||||
var next = i + 1 < progressScenes.Count ? progressScenes[i + 1] : null;
|
||||
var end = next is null ? cutoff : positions[next.SceneID] - 1;
|
||||
var start = positions[previous.SceneID];
|
||||
var terminal = resolutions.Concat(abandonments).Any(e => e.SceneID == previous.SceneID);
|
||||
var closedBeforeEnd = (actual is not null && actual.Position >= start && actual.Position <= end) || resolutions.Concat(abandonments).Any(e => positions[e.SceneID] >= start && positions[e.SceneID] <= end);
|
||||
if (terminal || closedBeforeEnd) continue;
|
||||
if (end - start < PlotHealthProgressPolicy.QuietSceneThreshold) continue;
|
||||
var touch = events.LastOrDefault(e => positions[e.SceneID] >= start && positions[e.SceneID] <= end) ?? previous;
|
||||
var chapterCount = Chapters(start, end);
|
||||
Add("H002", PlotHealthLevel.Review, "Quiet stretch",
|
||||
$"No meaningful progress across {end - start} scenes in {chapterCount} ordered chapters. Last progress: {previous.CanonicalRole}. Most recent touch in this stretch: {touch.CanonicalRole}. Review threshold: {PlotHealthProgressPolicy.QuietSceneThreshold} scenes; a quiet stretch may be intentional.",
|
||||
[Evidence(previous), Evidence(touch), next is null ? cutoffEvidence : Evidence(next)], next?.SceneID ?? cutoffEvidence?.SceneID,
|
||||
absence: true, silence: end - start, chapters: chapterCount);
|
||||
}
|
||||
if (first is not null && progress.Count == 0 && closures.Count == 0 && actual is null && cutoff - positions[first.SceneID] >= PlotHealthProgressPolicy.QuietSceneThreshold)
|
||||
Add("H002", PlotHealthLevel.Review, "No recorded meaningful progress", "Only non-progress touches are recorded after activity begins. Mentioned and Note do not reset the 10-scene progress review clock; no last meaningful event can be identified.",
|
||||
[Evidence(first), Evidence(last!), cutoffEvidence], absence: true,
|
||||
silence: cutoff - positions[first.SceneID], chapters: Chapters(positions[first.SceneID], cutoff));
|
||||
if (introduced.Count > 0 && !progress.Any(e => !Role(e, "Introduced") && positions[e.SceneID] >= positions[introduced[0].SceneID])
|
||||
&& cutoff - positions[introduced[0].SceneID] >= PlotHealthProgressPolicy.QuietSceneThreshold)
|
||||
Add("H003", PlotHealthLevel.Review, "No later recorded development", "Introduction is recorded, but no later meaningful contribution beyond introduction was found by the cutoff. The same 10-scene review threshold applies.", [Evidence(introduced[0]), cutoffEvidence], absence: true);
|
||||
|
||||
// Coarse thread-level predicates, ordered as in Continuity; these do not match individual questions or clues.
|
||||
foreach (var (role, rule, title, closing) in new[] {
|
||||
("Question Raised", "H004", "Open recorded question", new[] { "Question Answered" }),
|
||||
("Clue Planted", "H005", "Apparent unresolved clue", new[] { "Payoff", "Question Answered", "Revealed", "Resolved" }) })
|
||||
{
|
||||
var unmatched = events.LastOrDefault(e => Role(e, role) && !events.Any(later => positions[later.SceneID] > positions[e.SceneID] && Role(later, closing)));
|
||||
if (unmatched is null) continue;
|
||||
var otherClosure = events.Where(e => positions[e.SceneID] > positions[unmatched.SceneID] && Role(e, "Revealed", "Payoff", "Resolved"));
|
||||
Add(rule, PlotHealthLevel.Review, title, role == "Question Raised"
|
||||
? "No later recorded answer was found in this thread. Any later reveal/payoff/resolution is shown as evidence, not assumed to answer this question."
|
||||
: "No later recorded payoff/reveal/answer/resolution was found for this thread. This is a coarse role check, not a judgement of the story's payoff.",
|
||||
new[] { Evidence(unmatched), cutoffEvidence }.Concat(otherClosure.Select(Evidence)), unmatched.SceneID, absence: true);
|
||||
}
|
||||
if (Status(thread, "Ready For Payoff") && !events.Any(e => Role(e, "Payoff", "Resolved") || Structural(e, "Resolve")))
|
||||
Add("H006", PlotHealthLevel.Review, "Payoff evidence review", "Stored status is Ready For Payoff, but no recorded payoff/resolution evidence exists by this cutoff. The status has no narrative effective date; readiness remains the author's judgement.", [last is null ? null : Evidence(last), cutoffEvidence], absence: true);
|
||||
|
||||
var laterDevelopment = introduced.Count > 0 ? progress.FirstOrDefault(e => !Role(e, "Introduced") && positions[e.SceneID] > positions[introduced[0].SceneID]) : progress.FirstOrDefault(e => !Role(e, "Introduced"));
|
||||
if ((Status(thread, "Planned") && progress.Count > 0) || (Status(thread, "Introduced") && laterDevelopment is not null))
|
||||
Add("H007", PlotHealthLevel.Review, "Status review", $"Stored status is {thread.ThreadStatusName}, while canonical contributions record meaningful {(Status(thread, "Planned") ? "activity" : "later development/payoff/resolution")}. No replacement status has been inferred or saved.",
|
||||
[Evidence(laterDevelopment ?? progress[0]), cutoffEvidence]);
|
||||
var positionedClosures = resolutions.Concat(abandonments).Select(Evidence).Concat(actual is null ? [] : new[] { actual }).OrderBy(e => e.Position).ToList();
|
||||
var afterClosure = positionedClosures.Select(c => (Closure: c, Later: progress.FirstOrDefault(e => positions[e.SceneID] > c.Position) ?? events.FirstOrDefault(e => positions[e.SceneID] > c.Position))).FirstOrDefault(pair => pair.Later is not null);
|
||||
if (afterClosure.Later is not null)
|
||||
{
|
||||
if (Status(thread, "Resolved", "Abandoned") && PlotHealthProgressPolicy.IsMeaningful(afterClosure.Later.CanonicalRole))
|
||||
Add("H007", PlotHealthLevel.Review, "Status and later activity review", $"Stored status is {thread.ThreadStatusName}, but meaningful activity occurs after a positioned closure signal. This may be intentional.", [afterClosure.Closure, Evidence(afterClosure.Later)], afterClosure.Later.SceneID);
|
||||
var explicitClosure = resolutions.Concat(abandonments).Any(e => positions[e.SceneID] == afterClosure.Closure.Position);
|
||||
Add("H008", explicitClosure && PlotHealthProgressPolicy.IsMeaningful(afterClosure.Later.CanonicalRole) ? PlotHealthLevel.Warning : PlotHealthLevel.Review, "Contribution after closure evidence", "A contribution occurs after recorded closure evidence. Stored status, boundary and explicit events remain separate signals; V1 does not automatically reconcile them.", [afterClosure.Closure, Evidence(afterClosure.Later)], afterClosure.Later.SceneID);
|
||||
}
|
||||
var resolutionPositions = resolutions.Select(e => positions[e.SceneID]).Distinct().ToList();
|
||||
if ((actual is not null && resolutionPositions.Any(p => p != actual.Position)) ||
|
||||
(Status(thread, "Resolved") && actual is null && resolutions.Count == 0) ||
|
||||
(!Status(thread, "Resolved") && resolutions.Count > 0))
|
||||
Add("H008", PlotHealthLevel.Review, "Resolution/boundary review", "Stored status, actual-resolution boundary and explicit Resolved/Resolve events do not all provide agreeing evidence in this evaluated order. Missing or different signals are shown without choosing a universal authority.",
|
||||
new PlotHealthEvidence?[] { actual, cutoffEvidence }.Concat(resolutions.Select(Evidence)), absence: resolutions.Count == 0 && actual is null);
|
||||
var earlyClosure = closures.FirstOrDefault(e => !Structural(e, "Abandon") && introduced.Count > 0 && positions[e.SceneID] < positions[introduced[0].SceneID]);
|
||||
if (earlyClosure is not null && !Structural(earlyClosure, "Abandon"))
|
||||
Add("H009", PlotHealthLevel.Warning, "Closure before introduction", "Explicit payoff/resolution evidence precedes explicit introduction in this selected order.", [Evidence(earlyClosure), Evidence(introduced[0])], earlyClosure.SceneID);
|
||||
var outside = events.Where(e => (intro is not null && positions[e.SceneID] < intro.Position) || (actual is not null && positions[e.SceneID] > actual.Position)).ToList();
|
||||
if (outside.Count > 0)
|
||||
Add("H010", PlotHealthLevel.Review, "Contribution outside declared boundaries", $"{outside.Select(e => e.SceneID).Distinct().Count()} scene(s) contribute before the introduction boundary or after the actual-resolution boundary. This is a review observation, not invalid membership.",
|
||||
new PlotHealthEvidence?[] { intro, actual }.Concat(outside.Select(Evidence)), outside[0].SceneID);
|
||||
foreach (var e in events.Where(e => Structural(e, "Branch", "Split", "Merge")))
|
||||
{
|
||||
var targets = targetsByEvent[e.ThreadEventID].Select(t => t.TargetPlotLineID).Distinct().ToList();
|
||||
if (targets.Count == 0)
|
||||
Add("H011", PlotHealthLevel.Warning, "Explicit target unavailable", $"The explicit {e.CanonicalStructuralType} event has no recorded target.", [Evidence(e)], e.SceneID);
|
||||
foreach (var target in targets)
|
||||
{
|
||||
if (!targetLookup.TryGetValue(target, out var targetLine) || targetLine.ProjectID != context.ProjectID)
|
||||
Add("H011", PlotHealthLevel.Warning, "Explicit target unavailable", $"Target Plot Line {target} is missing, archived or outside the project in the active canonical read model.", [Evidence(e)], e.SceneID);
|
||||
else if (!Structural(e, "Merge") && !lineEvents[target].Any(later => positions[later.SceneID] > positions[e.SceneID]))
|
||||
Add("H011", PlotHealthLevel.Review, "No recorded continuation", $"{e.CanonicalStructuralType} target “{targetLine.PlotLineName}” has no later recorded contribution in this evaluated scope. Activity outside this scope is not judged.", [Evidence(e), cutoffEvidence], e.SceneID, absence: true);
|
||||
}
|
||||
}
|
||||
if (progress.Count > 0 && closures.Count == 0 && actual is null)
|
||||
Add("H012", context.BookID.HasValue && line.BookID == context.BookID ? PlotHealthLevel.Review : PlotHealthLevel.Information,
|
||||
Status(thread, "Resolved", "Abandoned") ? "No positioned closure at evaluated cutoff" : context.BookID.HasValue ? "Open at end of evaluated book scope" : "Open at current project cutoff",
|
||||
"Recorded activity has begun, but no positioned closure evidence is recorded by the evaluated cutoff. Stored status has no narrative effective date and is shown separately. Current scope end is not necessarily the author's intended final ending; no sequel intent is inferred.",
|
||||
[Evidence(last!), cutoffEvidence], absence: true);
|
||||
var signals = events.Select(e => e.CanonicalRole).Concat(events.Where(e => Structural(e, "Resolve", "Abandon")).Select(e => $"Structural {e.CanonicalStructuralType}")).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
|
||||
threads.Add(new(line.PlotLineID, thread.PlotThreadID, thread.ThreadTitle, thread.ThreadStatusName,
|
||||
signals, first is null ? null : Evidence(first), last is null ? null : Evidence(last), lastProgress is null ? null : Evidence(lastProgress),
|
||||
first is null ? cutoff : positions[first.SceneID] - 1,
|
||||
last is null ? null : cutoff - positions[last.SceneID], last is null ? null : Chapters(positions[last.SceneID], cutoff),
|
||||
lastProgress is null ? null : cutoff - positions[lastProgress.SceneID], lastProgress is null ? null : Chapters(positions[lastProgress.SceneID], cutoff), findings));
|
||||
}
|
||||
lines.Add(new(line.PlotLineID, threads, threads.SelectMany(t => t.Findings).OrderByDescending(f => f.Level).ThenBy(f => f.RuleID).ToList()));
|
||||
}
|
||||
return new(scope, lines);
|
||||
|
||||
PlotHealthEvidence? SceneEvidence(int? sceneID, string signal, int? eventID = null) =>
|
||||
sceneID.HasValue && scopeScenes.TryGetValue(sceneID.Value, out var scene)
|
||||
? new(scene.SceneID, positions[scene.SceneID], scene.BookID, scene.ChapterID, scene.SceneTitle, signal, eventID) : null;
|
||||
// Distinct identities in the traversed scenes, excluding the source chapter; chapter numbers never participate.
|
||||
int Chapters(int from, int through) => ordered.Skip(from).Take(Math.Max(0, through - from))
|
||||
.Select(s => (s.BookID, s.ChapterID)).Where(key => key != (ordered[from - 1].BookID, ordered[from - 1].ChapterID)).Distinct().Count();
|
||||
}
|
||||
private static bool Role(PlotLineWorkspaceContributionRow e, params string[] roles) => roles.Contains(e.CanonicalRole, StringComparer.OrdinalIgnoreCase);
|
||||
private static bool Structural(PlotLineWorkspaceContributionRow e, params string[] types) => types.Contains(e.CanonicalStructuralType, StringComparer.OrdinalIgnoreCase);
|
||||
private static bool Status(PlotLineWorkspaceThreadRow t, params string[] statuses) => statuses.Contains(t.ThreadStatusName, StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
24
PlotLine/Services/PlotLineColours.cs
Normal file
24
PlotLine/Services/PlotLineColours.cs
Normal file
@ -0,0 +1,24 @@
|
||||
namespace PlotLine.Services;
|
||||
|
||||
/// <summary>Stable defaults for older lines which all inherited the original green.</summary>
|
||||
public static class PlotLineColours
|
||||
{
|
||||
public static string ForLine(int plotLineId, string? colour)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(colour) && !colour.Equals("#2f6f63", StringComparison.OrdinalIgnoreCase)) return colour;
|
||||
// Identity, never selection order, determines the default. Explicit choices are preserved.
|
||||
var hue = ((uint)plotLineId * 137.508) % 360 / 60;
|
||||
const double chroma = .48;
|
||||
var secondary = chroma * (1 - Math.Abs(hue % 2 - 1));
|
||||
var (r, g, b) = hue switch
|
||||
{
|
||||
< 1 => (chroma, secondary, 0d),
|
||||
< 2 => (secondary, chroma, 0d),
|
||||
< 3 => (0d, chroma, secondary),
|
||||
< 4 => (0d, secondary, chroma),
|
||||
< 5 => (secondary, 0d, chroma),
|
||||
_ => (chroma, 0d, secondary)
|
||||
};
|
||||
return $"#{(int)((r + .30) * 255):x2}{(int)((g + .30) * 255):x2}{(int)((b + .30) * 255):x2}";
|
||||
}
|
||||
}
|
||||
@ -17,7 +17,8 @@ public sealed class PlotLineWorkspaceService(
|
||||
IBookRepository books,
|
||||
IScenarioRepository scenarios,
|
||||
IStoryContextService storyContext,
|
||||
IManuscriptTextStatisticsRepository manuscriptSources) : IPlotLineWorkspaceService
|
||||
IManuscriptTextStatisticsRepository manuscriptSources,
|
||||
IPlotHealthEvaluator health) : IPlotLineWorkspaceService
|
||||
{
|
||||
public async Task<PlotLineWorkspaceViewModel?> GetAsync(
|
||||
int projectId,
|
||||
@ -50,6 +51,7 @@ public sealed class PlotLineWorkspaceService(
|
||||
}
|
||||
|
||||
var data = await workspace.GetAsync(projectId, bookId, selectedScenario?.ScenarioID);
|
||||
foreach (var line in data.PlotLines) line.Colour = PlotLineColours.ForLine(line.PlotLineID, line.Colour);
|
||||
var availableIds = data.PlotLines.Select(x => x.PlotLineID).ToHashSet();
|
||||
var selectedLineIds = (plotLineIds ?? []).Where(availableIds.Contains).Distinct().ToList();
|
||||
if (!unattributed && selectedLineIds.Count == 0 && data.PlotLines.Count > 0)
|
||||
@ -57,6 +59,11 @@ public sealed class PlotLineWorkspaceService(
|
||||
selectedLineIds.Add(data.PlotLines.OrderByDescending(x => x.ContributionSceneCount).ThenBy(x => x.SortOrder).First().PlotLineID);
|
||||
}
|
||||
|
||||
// Reference data identifies scenario omissions and targets outside the chosen book; its positions are never used for health.
|
||||
var referenceData = !unattributed && (bookId.HasValue || selectedScenario is not null)
|
||||
? await workspace.GetAsync(projectId, null, null) : data;
|
||||
var healthResult = unattributed ? PlotHealthResult.Empty : health.Evaluate(new PlotHealthContext(
|
||||
projectId, bookId ?? selectedScenario?.BookID, selectedScenario?.ScenarioID, selectedLineIds, data, referenceData));
|
||||
var selectedThreads = (threadIds ?? []).Where(id => data.Threads.Any(x => x.PlotThreadID == id && selectedLineIds.Contains(x.PlotLineID))).Distinct().ToList();
|
||||
var composedScenes = unattributed ? [] : PlotLineWorkspaceComposer.Compose(data, selectedLineIds, selectedThreads);
|
||||
var suggestionsByScene = showSuggestions
|
||||
@ -84,6 +91,10 @@ public sealed class PlotLineWorkspaceService(
|
||||
SelectedPlotLineIDs = selectedLineIds,
|
||||
SelectedThreadIDs = selectedThreads,
|
||||
Scenes = composedScenes,
|
||||
Health = healthResult,
|
||||
AssociatedSelectedSceneIDs = data.Contributions.Where(x => selectedLineIds.Contains(x.PlotLineID)).Select(x => x.SceneID).ToHashSet(),
|
||||
AssociationScenes = data.AttributionScenes.OrderBy(x => x.NarrativeOrder).ToList(),
|
||||
MapTargets = data.Targets,
|
||||
SuggestedScenes = showSuggestions
|
||||
? data.AttributionScenes.Where(x => suggestionsByScene.ContainsKey(x.SceneID)).Select(x => new PlotLineWorkspaceSuggestionSceneViewModel
|
||||
{
|
||||
@ -105,6 +116,7 @@ public sealed class PlotLineWorkspaceService(
|
||||
}
|
||||
|
||||
var data = await workspace.GetAsync(projectId, bookId, scenarioId);
|
||||
foreach (var line in data.PlotLines) line.Colour = PlotLineColours.ForLine(line.PlotLineID, line.Colour);
|
||||
if (data.AttributionScenes.All(x => x.SceneID != sceneId))
|
||||
{
|
||||
return null;
|
||||
|
||||
71
PlotLine/Services/RibbonPresentation.cs
Normal file
71
PlotLine/Services/RibbonPresentation.cs
Normal file
@ -0,0 +1,71 @@
|
||||
namespace PlotLine.Services;
|
||||
|
||||
public sealed record RibbonIcon(string Key, string IconPath, string Tone);
|
||||
|
||||
// Presentation metadata only. Routes, permissions and command execution stay with their owners.
|
||||
public static class RibbonPresentation
|
||||
{
|
||||
public static string Operation(string controller, string action) => $"{controller}.{action}".ToLowerInvariant();
|
||||
public static string? IconFor(string operation, string? format = null)
|
||||
{
|
||||
operation = operation.ToLowerInvariant(); format = format?.ToLowerInvariant();
|
||||
if (operation.StartsWith("exports."))
|
||||
{
|
||||
if (format == "markdown") return "markdown";
|
||||
if (format == "text") return "text-export";
|
||||
return operation switch {
|
||||
"exports.storybible" => "print", "exports.narrativetimeline" => "timeline-export",
|
||||
"exports.researchpack" => "research", "exports.projectbackup" => "backup",
|
||||
"exports.writingsession" => "session", _ => "export"
|
||||
};
|
||||
}
|
||||
if (operation == "timeline.settings" || operation is "manageaccount.index" or "manageaccount.subscription") return "settings";
|
||||
if (operation == "plotlines.index") return "list";
|
||||
if (operation == "acceptance.phase1") return "validate";
|
||||
if (operation == "imports.sample") return "export";
|
||||
if (operation == "dynamics.knowledge") return "knowledge";
|
||||
if (operation == "dynamics.character") return "metrics";
|
||||
if (operation == "dynamics.story") return "health";
|
||||
if (operation.StartsWith("warnings.validate") || operation == "dynamics.runchecks") return "validate";
|
||||
if (operation == "projectrestorepoints.index") return "restore";
|
||||
var action = operation.Split('.').Last();
|
||||
if (action.StartsWith("reanalyse") || action.StartsWith("retry") || action.StartsWith("regenerate")) return "refresh";
|
||||
if (action == "save") return "save";
|
||||
if (action == "edit") return "writer";
|
||||
if (action.StartsWith("merge")) return "merge";
|
||||
if (action.StartsWith("delete") || action.StartsWith("remove")) return "remove";
|
||||
if (action.StartsWith("restore")) return "restore";
|
||||
if (action.StartsWith("archive")) return "archive";
|
||||
if (action == "create" && operation is not ("books.create" or "chapters.create")) return "add";
|
||||
if (action.StartsWith("schedule") || action == "writingplans") return "calendar";
|
||||
return null;
|
||||
}
|
||||
public static IReadOnlyList<RibbonIcon> AdditionalIcons { get; } = [
|
||||
new("save", "M4 3h13l4 4v14H3V3z M7 3v6h10V3 M7 21v-7h10v7", "planning"),
|
||||
new("close", "M5 5l14 14 M19 5L5 19", "planning"),
|
||||
new("cut", "M4 3l16 18 M20 3L9 14 M8 17a3 3 0 1 0-6 0 3 3 0 0 0 6 0 M22 17a3 3 0 1 0-6 0 3 3 0 0 0 6 0", "planning"),
|
||||
new("copy", "M8 8h13v13H8z M3 16V3h13", "planning"),
|
||||
new("paste", "M8 5H4v16h16V5h-4 M8 3h8v5H8z M8 12h8 M8 16h6", "planning"),
|
||||
new("select-all", "M3 8V3h5 M16 3h5v5 M21 16v5h-5 M8 21H3v-5 M7 7h10v10H7z", "planning"),
|
||||
new("search", "M20 20l-5-5 M17 10a7 7 0 1 0-14 0 7 7 0 0 0 14 0", "planning"),
|
||||
new("help", "M21 12a9 9 0 1 0-18 0 9 9 0 0 0 18 0 M9.5 9a2.5 2.5 0 0 1 5 0c0 2-2.5 2-2.5 4 M12 17v.01", "books"),
|
||||
new("print", "M6 8V3h12v5 M6 17H3V8h18v9h-3 M6 14h12v7H6z M17 11h1", "planning"),
|
||||
new("markdown", "M4 3h11l5 5v13H4z M15 3v6h5 M7 13l-2 2 2 2 M16 13l2 2-2 2 M12 12l-2 6", "planning"),
|
||||
new("text-export", "M5 3h10l5 5v13H5z M15 3v6h5 M8 12h9 M8 15h9 M8 18h6", "books"),
|
||||
new("timeline-export", "M3 5h14 M3 10h14 M3 15h7 M7 3v4 M12 8v4 M17 13v8 M13 17l4 4 4-4", "calendar"),
|
||||
new("research", "M3 6l8-3 8 3v8 M3 6v12l8 3 M3 6l8 4 8-4 M11 10v6 M22 22l-4-4 M20 16a4 4 0 1 0-8 0 4 4 0 0 0 8 0", "locations"),
|
||||
new("export", "M4 3h10v7 M4 3v18h13v-7 M10 14L21 3 M15 3h6v6", "planning"),
|
||||
new("backup", "M4 3h16v18H4z M8 3v6h8V3 M8 21v-7h8v7", "planning"),
|
||||
new("restore", "M4 8a9 9 0 1 1-1 7 M4 3v5h5 M12 7v6l4 2", "calendar"),
|
||||
new("settings", "M10 3h4l.6 3 2 .9 2.6-1.3 2 3.4-2.3 1.8v2.4l2.3 1.8-2 3.4-2.6-1.3-2 .9-.6 3h-4l-.6-3-2-.9-2.6 1.3-2-3.4L5 13.2v-2.4L2.7 9l2-3.4 2.6 1.3 2-.9z M15 12a3 3 0 1 0-6 0 3 3 0 0 0 6 0", "planning"),
|
||||
new("validate", "M4 3h13v18H4z M8 12l3 3 9-9 M8 6h5", "review"),
|
||||
new("refresh", "M20 9a8 8 0 0 0-14-4 L3 8 M3 3v5h5 M4 15a8 8 0 0 0 14 4l3-3 M16 16h5v5", "review"),
|
||||
new("merge", "M4 3v4l8 7 M20 3v4l-8 7v7 M8 17l4 4 4-4", "relationships"),
|
||||
new("remove", "M3 6h18 M9 6V3h6v3 M5 6l1 15h12l1-15 M10 10v7 M14 10v7", "warning"),
|
||||
new("add", "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18 M12 7v10 M7 12h10", "planning"),
|
||||
new("list", "M8 5h13 M8 12h13 M8 19h13 M3 5h.01 M3 12h.01 M3 19h.01", "planning"),
|
||||
new("knowledge", "M9 18h6 M10 21h4 M8 14a7 7 0 1 1 8 0l-1 4H9z", "review"),
|
||||
new("session", "M3 4h12v16H3z M7 8h4 M7 12h4 M17 10l4 3-4 3z", "review")
|
||||
];
|
||||
public static IEnumerable<RibbonIcon> Icons => ToolbarCommands.All.Select(command => new RibbonIcon(command.Key, command.IconPath, ApplicationRibbon.Tone(command.Key))).Concat(AdditionalIcons);
|
||||
}
|
||||
22
PlotLine/TagHelpers/RibbonCommandMetadataTagHelper.cs
Normal file
22
PlotLine/TagHelpers/RibbonCommandMetadataTagHelper.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using Microsoft.AspNetCore.Mvc.Rendering;
|
||||
using Microsoft.AspNetCore.Mvc.ViewFeatures;
|
||||
using Microsoft.AspNetCore.Razor.TagHelpers;
|
||||
using PlotLine.Services;
|
||||
namespace PlotLine.TagHelpers;
|
||||
|
||||
[HtmlTargetElement("a", Attributes = "asp-action")]
|
||||
[HtmlTargetElement("form", Attributes = "asp-action")]
|
||||
public sealed class RibbonCommandMetadataTagHelper : TagHelper
|
||||
{
|
||||
[ViewContext, HtmlAttributeNotBound] public ViewContext ViewContext { get; set; } = null!;
|
||||
public override int Order => 1000;
|
||||
public override void Process(TagHelperContext context, TagHelperOutput output)
|
||||
{
|
||||
var controller = context.AllAttributes["asp-controller"]?.Value?.ToString() ?? ViewContext.RouteData.Values["controller"]?.ToString() ?? "";
|
||||
var action = context.AllAttributes["asp-action"].Value?.ToString() ?? ViewContext.RouteData.Values["action"]?.ToString() ?? "Index";
|
||||
var operation = RibbonPresentation.Operation(controller, action);
|
||||
output.Attributes.SetAttribute("data-command-operation", operation);
|
||||
var icon = RibbonPresentation.IconFor(operation, context.AllAttributes["asp-route-format"]?.Value?.ToString());
|
||||
if (icon is not null && !context.AllAttributes.ContainsName("data-pwa-icon")) output.Attributes.SetAttribute("data-pwa-icon", icon);
|
||||
}
|
||||
}
|
||||
43
PlotLine/TagHelpers/RibbonContributionTagHelper.cs
Normal file
43
PlotLine/TagHelpers/RibbonContributionTagHelper.cs
Normal file
@ -0,0 +1,43 @@
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Html;
|
||||
using Microsoft.AspNetCore.Mvc.Rendering;
|
||||
using Microsoft.AspNetCore.Mvc.ViewFeatures;
|
||||
using Microsoft.AspNetCore.Razor.TagHelpers;
|
||||
|
||||
namespace PlotLine.TagHelpers;
|
||||
|
||||
// Razor renders the body before its layout. Capture only explicitly declared command
|
||||
// regions during that render, so the shell need not wait for the workspace DOM.
|
||||
[HtmlTargetElement(Attributes = "data-pwa-header")]
|
||||
[HtmlTargetElement(Attributes = "data-pwa-context")]
|
||||
[HtmlTargetElement(Attributes = "data-pwa-help")]
|
||||
[HtmlTargetElement(Attributes = "data-pwa-task")]
|
||||
[HtmlTargetElement(Attributes = "data-pwa-identity")]
|
||||
public sealed class RibbonContributionTagHelper : TagHelper
|
||||
{
|
||||
private static readonly object RegistryKey = new();
|
||||
private static readonly object ParentKey = new();
|
||||
[ViewContext, HtmlAttributeNotBound] public ViewContext ViewContext { get; set; } = null!;
|
||||
public override int Order => 2000;
|
||||
|
||||
public static IHtmlContent Snapshot(Microsoft.AspNetCore.Http.HttpContext context) =>
|
||||
context.Items.TryGetValue(RegistryKey, out var value) && value is List<string> regions
|
||||
? new HtmlString(string.Concat(regions)) : HtmlString.Empty;
|
||||
|
||||
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
|
||||
{
|
||||
var nested = context.Items.ContainsKey(ParentKey);
|
||||
context.Items[ParentKey] = true;
|
||||
var content = await output.GetChildContentAsync();
|
||||
output.Content.SetHtmlContent(content);
|
||||
if (nested) return;
|
||||
if (!ViewContext.HttpContext.Items.TryGetValue(RegistryKey, out var value))
|
||||
ViewContext.HttpContext.Items[RegistryKey] = value = new List<string>();
|
||||
var regions = (List<string>)value!;
|
||||
output.Attributes.SetAttribute("data-pwa-source", $"region-{regions.Count}");
|
||||
using var writer = new StringWriter();
|
||||
output.WriteTo(writer, HtmlEncoder.Default);
|
||||
regions.Add(writer.ToString());
|
||||
output.PostElement.AppendHtml("<script>window.PlotDirectorPageContext?.register(document.currentScript.previousElementSibling);</script>");
|
||||
}
|
||||
}
|
||||
@ -1248,7 +1248,7 @@ public sealed class TimelineViewModel
|
||||
public IReadOnlyList<TimelineViewPreset> ViewPresets { get; set; } = [];
|
||||
public IReadOnlyList<Scene> OrderedScenes { get; set; } = [];
|
||||
public IReadOnlyList<MetricGraphViewModel> MetricGraphs { get; set; } = [];
|
||||
public IReadOnlyList<PlotLineLaneViewModel> PlotLanes { get; set; } = [];
|
||||
public IReadOnlyDictionary<int, string> ScenePlotSearchText { get; set; } = new Dictionary<int, string>();
|
||||
public IReadOnlyList<AssetLaneViewModel> AssetLanes { get; set; } = [];
|
||||
public IReadOnlyList<CharacterLaneViewModel> CharacterLanes { get; set; } = [];
|
||||
public IReadOnlyDictionary<int, TimelineSceneOverviewViewModel> SceneOverviews { get; set; } = new Dictionary<int, TimelineSceneOverviewViewModel>();
|
||||
@ -1360,7 +1360,6 @@ public sealed class TimelineSettingsViewModel
|
||||
public string ProjectName { get; set; } = string.Empty;
|
||||
public bool ShowSceneCards { get; set; } = true;
|
||||
public bool ShowMetricShape { get; set; } = true;
|
||||
public bool ShowPlotLines { get; set; } = true;
|
||||
public bool ShowStoryAssets { get; set; }
|
||||
public bool ShowWarnings { get; set; } = true;
|
||||
public List<int> SelectedMetricTypeIDs { get; set; } = [];
|
||||
@ -1478,7 +1477,6 @@ public sealed class TimelineFilterViewModel
|
||||
public string? FocusType { get; set; }
|
||||
public int? FocusID { get; set; }
|
||||
public bool ShowSceneCards { get; set; } = true;
|
||||
public bool ShowPlotLines { get; set; } = true;
|
||||
public bool ShowAssets { get; set; } = true;
|
||||
public bool ShowCharacters { get; set; } = true;
|
||||
public bool ShowLocations { get; set; } = true;
|
||||
@ -1749,18 +1747,6 @@ public sealed class ThreadEventEditViewModel
|
||||
public int? ReturnBookID { get; set; }
|
||||
}
|
||||
|
||||
public sealed class PlotLineLaneViewModel
|
||||
{
|
||||
public PlotLineItem PlotLine { get; set; } = new();
|
||||
public IReadOnlyList<PlotLaneSceneViewModel> SceneSlots { get; set; } = [];
|
||||
}
|
||||
|
||||
public sealed class PlotLaneSceneViewModel
|
||||
{
|
||||
public Scene Scene { get; set; } = new();
|
||||
public IReadOnlyList<ThreadEvent> Events { get; set; } = [];
|
||||
}
|
||||
|
||||
public sealed class StoryAssetListViewModel
|
||||
{
|
||||
public Project Project { get; set; } = new();
|
||||
|
||||
@ -9,6 +9,10 @@ public sealed class PlotLineWorkspaceViewModel
|
||||
public int? SelectedScenarioID { get; set; }
|
||||
public string? SelectedScenarioName { get; set; }
|
||||
public string Mode { get; set; } = "Focus";
|
||||
public IReadOnlySet<int> AssociatedSelectedSceneIDs { get; set; } = new HashSet<int>();
|
||||
public IReadOnlyList<PlotLineWorkspaceAttributionRow> AssociationScenes { get; set; } = [];
|
||||
public IReadOnlyList<PlotLineWorkspaceTargetRow> MapTargets { get; set; } = [];
|
||||
public PlotHealthResult Health { get; set; } = PlotHealthResult.Empty;
|
||||
public bool ShowSuggestions { get; set; }
|
||||
public IReadOnlyList<Book> Books { get; set; } = [];
|
||||
public IReadOnlyList<Scenario> Scenarios { get; set; } = [];
|
||||
|
||||
@ -7,7 +7,7 @@
|
||||
: null;
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
@if (Model.ProjectID.HasValue)
|
||||
{
|
||||
@ -21,7 +21,7 @@
|
||||
<partial name="_ProjectSectionNav" model="projectNavigation" />
|
||||
}
|
||||
|
||||
<div class="page-heading">
|
||||
<div data-pwa-header class="page-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Phase 1U</p>
|
||||
<h1>Phase 1 Acceptance Checklist</h1>
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
@model AnalyticsViewModel
|
||||
@{
|
||||
ViewData["Title"] = "Story Health";
|
||||
ViewData["ShellClass"] = "plotline-shell-wide";
|
||||
ViewData["ProjectSection"] = "Health";
|
||||
var openThreads = Model.ThreadHealth.Where(x => x.IsOpenStatus).ToList();
|
||||
var dormantThreads = Model.ThreadHealth.Where(x => x.IsDormant).ToList();
|
||||
@ -32,7 +33,7 @@
|
||||
};
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<span>Story Health</span>
|
||||
@ -40,7 +41,7 @@
|
||||
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-header class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Analytics / Story health</p>
|
||||
<h1>@Model.Project.ProjectName <help-icon key="storyHealth.overview" /></h1>
|
||||
@ -85,7 +86,20 @@
|
||||
<article class="plain-card"><span class="eyebrow">Warning hotspots</span><strong>@Model.WarningHotspots.Count</strong></article>
|
||||
</section>
|
||||
|
||||
<section class="analytics-section">
|
||||
<div class="story-health-tabs" data-story-health-tabs>
|
||||
<nav class="story-health-tab-list" role="tablist" aria-label="Story health panels">
|
||||
<button type="button" role="tab" id="health-tab-metrics" aria-controls="health-panel-metrics" aria-selected="true" tabindex="0">Scene metric shape</button>
|
||||
<button type="button" role="tab" id="health-tab-pacing" aria-controls="health-panel-pacing" aria-selected="false" tabindex="-1">Pacing review</button>
|
||||
<button type="button" role="tab" id="health-tab-revisions" aria-controls="health-panel-revisions" aria-selected="false" tabindex="-1">Revision summary</button>
|
||||
<button type="button" role="tab" id="health-tab-purpose" aria-controls="health-panel-purpose" aria-selected="false" tabindex="-1">Scene purpose balance</button>
|
||||
<button type="button" role="tab" id="health-tab-warnings" aria-controls="health-panel-warnings" aria-selected="false" tabindex="-1">Warning hotspots</button>
|
||||
<button type="button" role="tab" id="health-tab-threads" aria-controls="health-panel-threads" aria-selected="false" tabindex="-1">Plot thread health</button>
|
||||
<button type="button" role="tab" id="health-tab-assets" aria-controls="health-panel-assets" aria-selected="false" tabindex="-1">Story asset health</button>
|
||||
<button type="button" role="tab" id="health-tab-pov" aria-controls="health-panel-pov" aria-selected="false" tabindex="-1">POV distribution</button>
|
||||
<button type="button" role="tab" id="health-tab-characters" aria-controls="health-panel-characters" aria-selected="false" tabindex="-1">Character appearances</button>
|
||||
<button type="button" role="tab" id="health-tab-locations" aria-controls="health-panel-locations" aria-selected="false" tabindex="-1">Location usage</button>
|
||||
</nav>
|
||||
<section class="analytics-section" role="tabpanel" id="health-panel-metrics" aria-labelledby="health-tab-metrics" tabindex="0">
|
||||
<div class="analytics-section-heading">
|
||||
<h2>Scene metric shape <help-icon key="storyHealth.sceneMetricShape" /></h2>
|
||||
<span class="muted">@Model.MetricGraphs.Count metric@(Model.MetricGraphs.Count == 1 ? "" : "s")</span>
|
||||
@ -99,10 +113,19 @@
|
||||
<div class="metric-shape-chart" data-metric-shape-chart>
|
||||
<p class="metric-shape-intro">Compare selected pacing and emotional metrics across scenes in narrative order. Click a point to open that scene on the timeline.</p>
|
||||
<div class="metric-toggle-row" data-metric-toggles></div>
|
||||
<div class="metric-chart-frame">
|
||||
<div class="story-health-zoom">
|
||||
<label for="health-metric-zoom">Scene spacing</label>
|
||||
<input id="health-metric-zoom" data-metric-zoom type="range" min="8" max="80" value="32" step="4" />
|
||||
<output for="health-metric-zoom" data-metric-zoom-label>32 px / scene</output>
|
||||
<button type="button" class="btn btn-outline-primary btn-sm" data-metric-fit>Fit all</button>
|
||||
<span class="muted">Scroll horizontally to explore the story.</span>
|
||||
</div>
|
||||
<div class="story-health-chart-scroll" tabindex="0" role="region" aria-label="Scrollable scene metrics">
|
||||
<div class="metric-chart-frame" style="width:var(--health-chart-width, 100%)">
|
||||
<canvas aria-label="Comparative scene metric line graph"></canvas>
|
||||
<p class="muted d-none" data-chart-fallback>Metric chart could not load. The raw metric rows are still available below.</p>
|
||||
</div>
|
||||
</div>
|
||||
<script type="application/json">@Html.Raw(System.Text.Json.JsonSerializer.Serialize(metricShapePayload))</script>
|
||||
</div>
|
||||
|
||||
@ -137,8 +160,7 @@
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="analytics-grid-two">
|
||||
<article class="plain-card">
|
||||
<article class="plain-card" role="tabpanel" id="health-panel-pacing" aria-labelledby="health-tab-pacing" tabindex="0" hidden>
|
||||
<h2>Pacing review <help-icon key="storyHealth.pacingReview" /></h2>
|
||||
@if (!Model.PacingReviewNotes.Any())
|
||||
{
|
||||
@ -158,7 +180,7 @@
|
||||
}
|
||||
</article>
|
||||
|
||||
<article class="plain-card">
|
||||
<article class="plain-card" role="tabpanel" id="health-panel-revisions" aria-labelledby="health-tab-revisions" tabindex="0" hidden>
|
||||
<h2>Revision summary <help-icon key="storyHealth.revisionSummary" /></h2>
|
||||
@foreach (var status in Model.RevisionSummary.Where(x => x.SceneCount > 0 || x.ChapterCount > 0))
|
||||
{
|
||||
@ -176,10 +198,8 @@
|
||||
</a>
|
||||
}
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="analytics-grid-two">
|
||||
<article class="plain-card">
|
||||
<article class="plain-card" role="tabpanel" id="health-panel-purpose" aria-labelledby="health-tab-purpose" tabindex="0" hidden>
|
||||
<h2>Scene purpose balance <help-icon key="storyHealth.scenePurposeBalance" /></h2>
|
||||
@foreach (var purpose in Model.PurposeSummary)
|
||||
{
|
||||
@ -199,7 +219,7 @@
|
||||
}
|
||||
</article>
|
||||
|
||||
<article class="plain-card">
|
||||
<article class="plain-card" role="tabpanel" id="health-panel-warnings" aria-labelledby="health-tab-warnings" tabindex="0" hidden>
|
||||
<h2>Warning hotspots <help-icon key="storyHealth.warningHotspots" /></h2>
|
||||
@foreach (var count in Model.WarningSeverityCounts)
|
||||
{
|
||||
@ -213,10 +233,8 @@
|
||||
</a>
|
||||
}
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="analytics-grid-two">
|
||||
<article class="plain-card">
|
||||
<article class="plain-card" role="tabpanel" id="health-panel-threads" aria-labelledby="health-tab-threads" tabindex="0" hidden>
|
||||
<h2>Plot thread health <help-icon key="storyHealth.plotThreadHealth" /></h2>
|
||||
@foreach (var thread in Model.ThreadHealth.Where(x => x.IsHighImportanceOpen || x.IsDormant || x.HasClueWithoutPayoff || x.HasQuestionWithoutAnswer).Take(12))
|
||||
{
|
||||
@ -233,7 +251,7 @@
|
||||
}
|
||||
</article>
|
||||
|
||||
<article class="plain-card">
|
||||
<article class="plain-card" role="tabpanel" id="health-panel-assets" aria-labelledby="health-tab-assets" tabindex="0" hidden>
|
||||
<h2>Story asset health <help-icon key="storyHealth.storyAssetHealth" /></h2>
|
||||
@foreach (var asset in Model.AssetHealth.Where(x => !x.IsResolved || x.HasDependencies || x.Importance >= 8).Take(12))
|
||||
{
|
||||
@ -244,10 +262,8 @@
|
||||
</a>
|
||||
}
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="analytics-grid-three">
|
||||
<article class="plain-card">
|
||||
<article class="plain-card" role="tabpanel" id="health-panel-pov" aria-labelledby="health-tab-pov" tabindex="0" hidden>
|
||||
<h2>POV distribution</h2>
|
||||
@foreach (var pov in Model.PovSummary)
|
||||
{
|
||||
@ -259,7 +275,7 @@
|
||||
}
|
||||
</article>
|
||||
|
||||
<article class="plain-card">
|
||||
<article class="plain-card" role="tabpanel" id="health-panel-characters" aria-labelledby="health-tab-characters" tabindex="0" hidden>
|
||||
<h2>Character appearances</h2>
|
||||
@foreach (var character in Model.CharacterAppearances.Take(10))
|
||||
{
|
||||
@ -274,7 +290,7 @@
|
||||
}
|
||||
</article>
|
||||
|
||||
<article class="plain-card">
|
||||
<article class="plain-card" role="tabpanel" id="health-panel-locations" aria-labelledby="health-tab-locations" tabindex="0" hidden>
|
||||
<h2>Location usage</h2>
|
||||
@foreach (var location in Model.LocationUsage.Take(10))
|
||||
{
|
||||
@ -291,4 +307,5 @@
|
||||
}
|
||||
}
|
||||
</article>
|
||||
</section>
|
||||
|
||||
</div>
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
@model ArchivedItemsViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "management";
|
||||
ViewData["Title"] = "Archived Items";
|
||||
ViewData["ProjectSection"] = "Archive";
|
||||
var selectedProject = Model.ProjectID.HasValue
|
||||
@ -10,7 +11,7 @@
|
||||
: null;
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
@if (projectNavigation is not null)
|
||||
{
|
||||
@ -24,7 +25,7 @@
|
||||
<partial name="_ProjectSectionNav" model="projectNavigation" />
|
||||
}
|
||||
|
||||
<div class="page-heading">
|
||||
<div data-pwa-header class="page-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Archive</p>
|
||||
<h1>Archived Items <help-icon key="archive.overview" /></h1>
|
||||
@ -70,7 +71,7 @@
|
||||
<div class="archive-item-list">
|
||||
@foreach (var item in Model.Items)
|
||||
{
|
||||
<article class="archive-item-card">
|
||||
<article data-pd-context="archived item" data-pd-context-id="@item.EntityID" class="archive-item-card">
|
||||
<div>
|
||||
<span class="archived-badge">@item.EntityType</span>
|
||||
<h3>@item.DisplayName</h3>
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
@model BookDetailViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "details";
|
||||
ViewData["Title"] = Model.Book.BookTitle;
|
||||
ViewData["ProjectSection"] = "Overview";
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<span>@Model.Book.BookTitle</span>
|
||||
@ -25,7 +26,7 @@
|
||||
<div class="alert alert-info">@manuscriptMessage</div>
|
||||
}
|
||||
|
||||
<div class="page-heading">
|
||||
<div data-pwa-header class="page-heading">
|
||||
<div>
|
||||
<p class="eyebrow"><a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a></p>
|
||||
<h1>Book @Model.Book.BookNumber: @Model.Book.BookTitle <help-icon key="books.overview" /></h1>
|
||||
@ -99,6 +100,15 @@
|
||||
</section>
|
||||
}
|
||||
|
||||
@if (!string.IsNullOrWhiteSpace(Model.Book.Subtitle) || !string.IsNullOrWhiteSpace(Model.Book.Tagline) || !string.IsNullOrWhiteSpace(Model.Book.Description))
|
||||
{
|
||||
<section class="pwa-content-only list-section" aria-label="Book description">
|
||||
@if (!string.IsNullOrWhiteSpace(Model.Book.Subtitle)) { <p class="lead-text">@Model.Book.Subtitle</p> }
|
||||
@if (!string.IsNullOrWhiteSpace(Model.Book.Tagline)) { <p class="muted">@Model.Book.Tagline</p> }
|
||||
@if (!string.IsNullOrWhiteSpace(Model.Book.Description)) { <p>@Model.Book.Description</p> }
|
||||
</section>
|
||||
}
|
||||
|
||||
<section class="list-section">
|
||||
<h2>Book metadata</h2>
|
||||
<div class="row g-3">
|
||||
@ -185,7 +195,7 @@
|
||||
<tbody>
|
||||
@foreach (var chapter in Model.Chapters)
|
||||
{
|
||||
<tr>
|
||||
<tr data-pd-context="chapter" data-pd-context-id="@chapter.ChapterID" data-pd-context-label="@chapter.ChapterTitle">
|
||||
<td class="narrow">@chapter.ChapterNumber</td>
|
||||
<td><a asp-controller="Chapters" asp-action="Details" asp-route-id="@chapter.ChapterID">@chapter.ChapterTitle</a></td>
|
||||
<td>
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
@model BookEditViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "wide";
|
||||
ViewData["Title"] = Model.BookID == 0 ? "New Book" : "Edit Book";
|
||||
}
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-task class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">@Model.Project?.ProjectName</p>
|
||||
<h1>@ViewData["Title"] <help-icon key="books.edit" /></h1>
|
||||
@ -11,7 +12,7 @@
|
||||
<a class="btn btn-outline-secondary" asp-controller="Projects" asp-action="Details" asp-route-id="@Model.ProjectID">Back to project</a>
|
||||
</div>
|
||||
|
||||
<form asp-action="Save" method="post" enctype="multipart/form-data" class="edit-panel">
|
||||
<form asp-action="Save" method="post" enctype="multipart/form-data" class="edit-panel pd-record-form">
|
||||
<input asp-for="BookID" type="hidden" />
|
||||
<input asp-for="ProjectID" type="hidden" />
|
||||
@if (Model.BookID != 0)
|
||||
@ -46,86 +47,89 @@
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
<div class="row g-3">
|
||||
<div class="col-md-3">
|
||||
<div class="row g-3 pd-record-fields">
|
||||
<div class="pd-record-group-label" role="heading" aria-level="2">Identity and cover</div>
|
||||
<div class="col-md-3 pd-record-span-3">
|
||||
<label asp-for="BookNumber" class="form-label">Book number <help-icon key="books.fields.bookNumber" mode="inline" /></label>
|
||||
<input asp-for="BookNumber" class="form-control" />
|
||||
<input asp-for="BookNumber" class="form-control pd-record-number" />
|
||||
</div>
|
||||
<div class="col-md-9">
|
||||
<div class="col-md-9 pd-record-span-9">
|
||||
<label asp-for="BookTitle" class="form-label"></label>
|
||||
<input asp-for="BookTitle" class="form-control" />
|
||||
<span asp-validation-for="BookTitle" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="col-md-4 pd-record-span-4">
|
||||
<label asp-for="CoverUpload" class="form-label"></label>
|
||||
<div class="mb-2">
|
||||
<img src="@Model.CoverThumbnailPath" alt="Current book cover" class="img-fluid border" style="max-width:160px;" />
|
||||
<img src="@Model.CoverThumbnailPath" width="160" height="240" alt="Current book cover" class="img-fluid border" style="max-width:160px;" />
|
||||
</div>
|
||||
<input asp-for="CoverUpload" class="form-control" type="file" accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp" />
|
||||
<div class="form-text">JPG, PNG or WebP. Maximum 10 MB.</div>
|
||||
<span asp-validation-for="CoverUpload" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-md-8">
|
||||
<div class="col-md-8 pd-record-span-8">
|
||||
<label asp-for="ShortDescription" class="form-label"></label>
|
||||
<textarea asp-for="ShortDescription" class="form-control" rows="6"></textarea>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="col-md-6 pd-record-span-6">
|
||||
<label asp-for="Subtitle" class="form-label"></label>
|
||||
<input asp-for="Subtitle" class="form-control" />
|
||||
<span asp-validation-for="Subtitle" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="col-md-6 pd-record-span-6">
|
||||
<label asp-for="Tagline" class="form-label"></label>
|
||||
<input asp-for="Tagline" class="form-control" />
|
||||
<span asp-validation-for="Tagline" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="pd-record-group-label" role="heading" aria-level="2">Publishing and story context</div>
|
||||
<div class="col-md-4 pd-record-span-4">
|
||||
<label asp-for="Status" class="form-label"></label>
|
||||
<select asp-for="Status" asp-items="Model.StatusOptions" class="form-select"></select>
|
||||
<span asp-validation-for="Status" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="col-md-4 pd-record-span-4">
|
||||
<div class="form-check mt-4">
|
||||
<input asp-for="UsesExplicitScenes" class="form-check-input" />
|
||||
<label asp-for="UsesExplicitScenes" class="form-check-label"></label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="col-md-4 pd-record-span-4">
|
||||
<label asp-for="TargetWordCount" class="form-label"></label>
|
||||
<input asp-for="TargetWordCount" class="form-control" min="1" />
|
||||
<input asp-for="TargetWordCount" class="form-control pd-record-number" min="1" />
|
||||
<span asp-validation-for="TargetWordCount" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="col-md-4 pd-record-span-6">
|
||||
<label asp-for="StoryEra" class="form-label"></label>
|
||||
<select asp-for="StoryEra" asp-items="Model.StoryEraOptions" class="form-select"></select>
|
||||
<span asp-validation-for="StoryEra" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="col-md-4 pd-record-span-6">
|
||||
<label asp-for="PrimaryLocaleCode" class="form-label"></label>
|
||||
<select asp-for="PrimaryLocaleCode" asp-items="Model.PrimaryLocaleOptions" class="form-select"></select>
|
||||
<span asp-validation-for="PrimaryLocaleCode" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="pd-record-group-label" role="heading" aria-level="2">Dates</div>
|
||||
<div class="col-md-4 pd-record-span-4">
|
||||
<label asp-for="WritingStartDate" class="form-label"></label>
|
||||
<input asp-for="WritingStartDate" class="form-control" />
|
||||
<span asp-validation-for="WritingStartDate" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="col-md-6 pd-record-span-4">
|
||||
<label asp-for="TargetCompletionDate" class="form-label"></label>
|
||||
<input asp-for="TargetCompletionDate" class="form-control" />
|
||||
<span asp-validation-for="TargetCompletionDate" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="col-md-6 pd-record-span-4">
|
||||
<label asp-for="PublicationDate" class="form-label"></label>
|
||||
<input asp-for="PublicationDate" class="form-control" />
|
||||
<span asp-validation-for="PublicationDate" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<div class="col-12 pd-record-span-12">
|
||||
<label asp-for="Description" class="form-label"></label>
|
||||
<textarea asp-for="Description" class="form-control" rows="4"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn btn-primary mt-3" type="submit">Save book</button>
|
||||
<div data-pwa-context="Record" data-pwa-priority="0" class="button-row mt-3"><button class="btn btn-primary" data-pwa-icon="save" type="submit">Save book</button></div>
|
||||
</form>
|
||||
|
||||
@section Scripts {
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
@model ChapterDetailViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "details";
|
||||
ViewData["Title"] = Model.Chapter.ChapterTitle;
|
||||
ViewData["ProjectSection"] = "Overview";
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<a asp-controller="Books" asp-action="Details" asp-route-id="@Model.Book.BookID">@Model.Book.BookTitle</a>
|
||||
@ -22,7 +23,7 @@
|
||||
<div class="alert alert-info">@chapterMessage</div>
|
||||
}
|
||||
|
||||
<div class="page-heading">
|
||||
<div data-pd-context="chapter" data-pd-context-id="@Model.Chapter.ChapterID" data-pd-context-label="@Model.Chapter.ChapterTitle" data-pwa-task class="page-heading">
|
||||
<div>
|
||||
<p class="eyebrow">
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
@ -125,7 +126,7 @@
|
||||
<tbody>
|
||||
@foreach (var scene in Model.Scenes)
|
||||
{
|
||||
<tr>
|
||||
<tr data-pd-context="scene" data-pd-context-id="@scene.SceneID" data-pd-context-label="@scene.SceneTitle">
|
||||
<td class="narrow">@scene.SceneNumber</td>
|
||||
<td>
|
||||
<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@scene.SceneID">@scene.SceneTitle</a>
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
@model ChapterEditViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "wide";
|
||||
ViewData["Title"] = Model.ChapterID == 0 ? "New Chapter" : "Edit Chapter";
|
||||
}
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-task class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">@Model.Book?.BookTitle</p>
|
||||
<h1>@ViewData["Title"] <help-icon key="chapters.edit" /></h1>
|
||||
@ -11,31 +12,33 @@
|
||||
<a class="btn btn-outline-secondary" asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID">Back to book</a>
|
||||
</div>
|
||||
|
||||
<form asp-action="Save" method="post" class="edit-panel">
|
||||
<form asp-action="Save" method="post" class="edit-panel pd-record-form">
|
||||
<input asp-for="ChapterID" type="hidden" />
|
||||
<input asp-for="BookID" type="hidden" />
|
||||
<input asp-for="OriginalDerivedPOVCharacterID" type="hidden" />
|
||||
<input asp-for="HasCanonicalScenes" type="hidden" />
|
||||
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
|
||||
<div class="row g-3">
|
||||
<div class="col-md-3">
|
||||
<div class="row g-3 pd-record-fields">
|
||||
<div class="pd-record-group-label" role="heading" aria-level="2">Chapter</div>
|
||||
<div class="col-md-3 pd-record-span-3">
|
||||
<label asp-for="ChapterNumber" class="form-label">Chapter number <help-icon key="chapters.fields.chapterNumber" mode="inline" /></label>
|
||||
<input asp-for="ChapterNumber" class="form-control" />
|
||||
<input asp-for="ChapterNumber" class="form-control pd-record-number" />
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="col-md-3 pd-record-span-9">
|
||||
<label asp-for="ChapterTitle" class="form-label"></label>
|
||||
<input asp-for="ChapterTitle" class="form-control" />
|
||||
<span asp-validation-for="ChapterTitle" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="pd-record-group-label" role="heading" aria-level="2">Story and revision</div>
|
||||
<div class="col-md-3 pd-record-span-4">
|
||||
<label asp-for="RevisionStatusID" class="form-label">Revision status <help-icon key="chapters.fields.revisionStatus" mode="inline" /></label>
|
||||
<select asp-for="RevisionStatusID" asp-items="Model.RevisionStatuses" class="form-select"></select>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="col-md-3 pd-record-span-4">
|
||||
<label asp-for="ChapterPurposeID" class="form-label"></label>
|
||||
<select asp-for="ChapterPurposeID" asp-items="Model.ChapterPurposes" class="form-select"></select>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="col-md-3 pd-record-span-4">
|
||||
<label asp-for="POVCharacterID" class="form-label"></label>
|
||||
<select asp-for="POVCharacterID" asp-items="Model.CharacterOptions" class="form-select"></select>
|
||||
@if (Model.HasCanonicalScenes)
|
||||
@ -43,12 +46,12 @@
|
||||
<span class="form-text">Current scene POV: @Model.PovDisplayLabel</span>
|
||||
}
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<div class="col-12 pd-record-span-12">
|
||||
<label asp-for="Summary" class="form-label"></label>
|
||||
<textarea asp-for="Summary" class="form-control" rows="4"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn btn-primary mt-3" type="submit">Save chapter</button>
|
||||
<div data-pwa-context="Record" data-pwa-priority="0" class="button-row mt-3"><button class="btn btn-primary" data-pwa-icon="save" type="submit">Save chapter</button></div>
|
||||
</form>
|
||||
|
||||
@section Scripts {
|
||||
|
||||
@ -3,12 +3,12 @@
|
||||
ViewData["Title"] = "Create Avatar";
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-action="Details" asp-route-id="@Model.CharacterID">@Model.CharacterName</a>
|
||||
<span>Create Avatar</span>
|
||||
</nav>
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-task class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Character Avatar</p>
|
||||
<h1>Create Avatar</h1>
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
@model CharacterDetailViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "details";
|
||||
ViewData["Title"] = Model.Character.CharacterName;
|
||||
ViewData["ProjectSection"] = "Characters";
|
||||
var firstAppearance = Model.Appearances.FirstOrDefault();
|
||||
@ -31,7 +32,7 @@
|
||||
var lastAnalysed = analysis.LastAnalysedUtc?.ToLocalTime().ToString("d MMMM yyyy, HH:mm");
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<a asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Characters</a>
|
||||
@ -40,14 +41,14 @@
|
||||
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<div class="page-heading pw-page-heading">
|
||||
<div data-pd-context="character" data-pd-context-id="@Model.Character.CharacterID" data-pd-context-label="@Model.Character.CharacterName" data-pwa-help class="page-heading pw-page-heading">
|
||||
<partial name="_Avatar" model="@(new AvatarViewModel { DisplayName = Model.Character.CharacterName, ImagePath = Model.Character.AvatarImagePath ?? Model.Character.ImagePath, ThumbnailPath = Model.Character.AvatarThumbnailPath ?? Model.Character.ThumbnailPath, Size = "xl", Lazy = false })" />
|
||||
<div>
|
||||
<p class="eyebrow">Character</p>
|
||||
<h1>@Model.Character.CharacterName <help-icon key="characters.details" /></h1>
|
||||
<p class="lead-text">@Model.Character.DefaultDescription</p>
|
||||
</div>
|
||||
<div class="button-row">
|
||||
<div data-pwa-context="Manage" class="button-row">
|
||||
<a class="btn btn-outline-secondary" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Back to characters</a>
|
||||
<a class="btn btn-outline-secondary" asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@firstAppearance?.SceneID" asp-route-FocusType="character" asp-route-FocusID="@Model.Character.CharacterID">Back to timeline</a>
|
||||
<div class="dropdown pw-actions">
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
@model CharacterEditViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "wide";
|
||||
ViewData["Title"] = Model.CharacterID == 0 ? "New Character" : "Edit Character";
|
||||
}
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-task class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Character</p>
|
||||
<h1>@ViewData["Title"] <help-icon key="characters.edit" /></h1>
|
||||
@ -15,7 +16,7 @@
|
||||
<div class="alert alert-warning">@imageError</div>
|
||||
}
|
||||
|
||||
<form asp-action="Save" method="post" class="edit-panel" enctype="multipart/form-data">
|
||||
<form asp-action="Save" method="post" class="edit-panel pd-record-form" enctype="multipart/form-data">
|
||||
<input asp-for="CharacterID" type="hidden" />
|
||||
<input asp-for="ProjectID" type="hidden" />
|
||||
<input asp-for="ImagePath" type="hidden" />
|
||||
@ -24,13 +25,14 @@
|
||||
<input asp-for="AvatarThumbnailPath" type="hidden" />
|
||||
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
|
||||
|
||||
<div class="row g-3">
|
||||
<div class="col-md-8">
|
||||
<div class="row g-3 pd-record-fields">
|
||||
<div class="pd-record-group-label" role="heading" aria-level="2">Names</div>
|
||||
<div class="col-md-8 pd-record-span-6">
|
||||
<label asp-for="CharacterName" class="form-label"></label>
|
||||
<input asp-for="CharacterName" class="form-control" />
|
||||
<span asp-validation-for="CharacterName" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<div class="col-12 pd-record-span-6">
|
||||
<label class="form-label">Known names</label>
|
||||
<div class="d-flex flex-wrap gap-2 mb-2" data-alias-list>
|
||||
@for (var i = 0; i < Model.Aliases.Count; i++)
|
||||
@ -47,52 +49,55 @@
|
||||
<button class="btn btn-outline-secondary" type="button" data-add-alias>Add</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="pd-record-group-label" role="heading" aria-level="2">Profile</div>
|
||||
<div class="col-md-4 pd-record-span-3">
|
||||
<label asp-for="SexValueID" class="form-label"></label>
|
||||
<select asp-for="SexValueID" asp-items="Model.SexOptions" class="form-select" data-sex-select data-custom-sex-value="@CharacterEditViewModel.CustomSexValue"></select>
|
||||
<input asp-for="Sex" type="hidden" />
|
||||
<div class="form-text">Choose a saved value, or select Add new... to create one.</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="col-md-4 pd-record-span-3">
|
||||
<label asp-for="CustomSex" class="form-label"></label>
|
||||
<input asp-for="CustomSex" class="form-control" placeholder="Custom value" data-custom-sex-input />
|
||||
<span asp-validation-for="CustomSex" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="col-md-4 pd-record-span-3">
|
||||
<label asp-for="BirthDate" class="form-label"></label>
|
||||
<input asp-for="BirthDate" type="date" asp-format="{0:yyyy-MM-dd}" class="form-control" />
|
||||
<span asp-validation-for="BirthDate" class="text-danger"></span>
|
||||
<div class="form-text">Optional. Enter a date only; no birth time is needed.</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="col-md-4 pd-record-span-3">
|
||||
<label asp-for="AgeAtSeriesStart" class="form-label"></label>
|
||||
<input asp-for="AgeAtSeriesStart" class="form-control" />
|
||||
<input asp-for="AgeAtSeriesStart" class="form-control pd-record-number" />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="col-md-6 pd-record-span-6">
|
||||
<label asp-for="Height" class="form-label"></label>
|
||||
<input asp-for="Height" class="form-control" />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="col-md-6 pd-record-span-6">
|
||||
<label asp-for="EyeColour" class="form-label"></label>
|
||||
<input asp-for="EyeColour" class="form-control" />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="pd-record-group-label" role="heading" aria-level="2">Story use</div>
|
||||
<div class="col-md-6 pd-record-span-6">
|
||||
<label asp-for="CharacterImportance" class="form-label">Story importance <help-icon key="characters.fields.storyImportance" mode="inline" /></label>
|
||||
<select asp-for="CharacterImportance" asp-items="Model.ImportanceOptions" class="form-select"></select>
|
||||
<div class="form-text">Controls timeline grouping for major, secondary/supporting, and minor characters.</div>
|
||||
</div>
|
||||
<div class="col-md-6 d-flex align-items-end">
|
||||
<div class="col-md-6 d-flex align-items-end pd-record-span-6">
|
||||
<div class="form-check mb-2">
|
||||
<input asp-for="ShowInQuickAddBar" class="form-check-input" />
|
||||
<label asp-for="ShowInQuickAddBar" class="form-check-label"></label>
|
||||
<div class="form-text">Makes this item available as a draggable shortcut on the Timeline page.</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<div class="pd-record-group-label" role="heading" aria-level="2">Description and image</div>
|
||||
<div class="col-12 pd-record-span-8">
|
||||
<label asp-for="DefaultDescription" class="form-label"></label>
|
||||
<textarea asp-for="DefaultDescription" class="form-control" rows="5"></textarea>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<div class="col-12 pd-record-span-4">
|
||||
<div class="visual-image-editor">
|
||||
<div>
|
||||
<p class="eyebrow">Character Image</p>
|
||||
@ -118,9 +123,9 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="button-row mt-3">
|
||||
<button class="btn btn-primary" type="submit">Save character</button>
|
||||
<a class="btn btn-outline-secondary" asp-action="Index" asp-route-projectId="@Model.ProjectID">Cancel</a>
|
||||
<div data-pwa-context="Record" data-pwa-priority="0" class="button-row mt-3">
|
||||
<button class="btn btn-primary" data-pwa-icon="save" type="submit">Save character</button>
|
||||
<a class="btn btn-outline-secondary" data-pwa-icon="close" asp-action="Index" asp-route-projectId="@Model.ProjectID">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
@model CharacterListViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "management";
|
||||
ViewData["Title"] = "Characters";
|
||||
ViewData["ProjectSection"] = "Characters";
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<span>Characters</span>
|
||||
@ -12,7 +13,7 @@
|
||||
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<div class="page-heading">
|
||||
<div data-pwa-header class="page-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Characters</p>
|
||||
<h1>@Model.Project.ProjectName <help-icon key="characters.overview" /></h1>
|
||||
@ -32,7 +33,7 @@
|
||||
<div class="asset-card-grid character-card-grid">
|
||||
@foreach (var character in Model.Characters)
|
||||
{
|
||||
<article class="asset-card character-card character-card--span-@CharacterCardLayout.ColumnSpan(character)" draggable="true" data-drag-type="character" data-drag-id="@character.CharacterID" data-drag-label="@character.CharacterName">
|
||||
<article data-pd-context="character" data-pd-context-id="@character.CharacterID" data-pd-context-label="@character.CharacterName" class="asset-card character-card character-card--span-@CharacterCardLayout.ColumnSpan(character)" draggable="true" data-drag-type="character" data-drag-id="@character.CharacterID" data-drag-label="@character.CharacterName">
|
||||
<div class="visual-card-heading">
|
||||
<partial name="_Avatar" model="@(new AvatarViewModel { DisplayName = character.CharacterName, ImagePath = character.AvatarImagePath ?? character.ImagePath, ThumbnailPath = character.AvatarThumbnailPath ?? character.ThumbnailPath })" />
|
||||
<div>
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
@model CharacterMergeViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "compact";
|
||||
ViewData["Title"] = $"Merge {Model.SourceCharacter.CharacterName}";
|
||||
ViewData["ProjectSection"] = "Characters";
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<a asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Characters</a>
|
||||
@ -14,7 +15,7 @@
|
||||
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-task class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Character identity</p>
|
||||
<h1>Merge @Model.SourceCharacter.CharacterName</h1>
|
||||
|
||||
@ -23,7 +23,7 @@
|
||||
Model.Filter.EntityTypes.Contains(entityType, StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<span>Continuity Explorer</span>
|
||||
@ -31,7 +31,7 @@
|
||||
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<div class="page-heading">
|
||||
<div data-pwa-header class="page-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Continuity</p>
|
||||
<h1>Continuity Explorer</h1>
|
||||
@ -297,7 +297,7 @@ else if (Model.Filter.DisplayMode == "Journey")
|
||||
<tbody>
|
||||
@foreach (var row in group)
|
||||
{
|
||||
<tr>
|
||||
<tr data-pd-context="scene evidence" data-pd-context-id="@row.SceneID">
|
||||
@if (Model.ShowBookContext)
|
||||
{
|
||||
<td>@row.BookDisplayName</td>
|
||||
@ -337,7 +337,7 @@ else if (Model.Filter.DisplayMode == "Journey")
|
||||
<tbody>
|
||||
@foreach (var row in group)
|
||||
{
|
||||
<tr>
|
||||
<tr data-pd-context="scene evidence" data-pd-context-id="@row.SceneID">
|
||||
@if (Model.ShowBookContext)
|
||||
{
|
||||
<td>@row.BookDisplayName</td>
|
||||
@ -388,7 +388,7 @@ else
|
||||
<tbody>
|
||||
@foreach (var row in Model.LocationActivity)
|
||||
{
|
||||
<tr>
|
||||
<tr data-pd-context="scene evidence" data-pd-context-id="@row.SceneID">
|
||||
<td>@row.LocationName</td>
|
||||
@if (Model.ShowBookContext)
|
||||
{
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
@model CharacterArcViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "details";
|
||||
ViewData["Title"] = $"{Model.Character.CharacterName} Arc";
|
||||
var arcScenes = Model.ArcPoints
|
||||
.OrderBy(point => point.GlobalSceneIndex)
|
||||
@ -41,13 +42,13 @@
|
||||
};
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<a asp-controller="Characters" asp-action="Details" asp-route-id="@Model.Character.CharacterID">@Model.Character.CharacterName</a>
|
||||
<span>Character arc</span>
|
||||
</nav>
|
||||
|
||||
<div class="page-heading">
|
||||
<div data-pwa-task class="page-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Character Arc</p>
|
||||
<h1>@Model.Character.CharacterName</h1>
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
@model KnowledgeTimelineViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "details";
|
||||
ViewData["Title"] = $"{Model.Character.CharacterName} Knowledge";
|
||||
}
|
||||
|
||||
<div class="page-heading">
|
||||
<div data-pwa-task class="page-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Knowledge Timeline</p>
|
||||
<h1>@Model.Character.CharacterName</h1>
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
@model RelationshipEvolutionViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "details";
|
||||
ViewData["Title"] = "Relationship Evolution";
|
||||
var maxIndex = Math.Max(Model.Events.Any() ? Model.Events.Max(x => x.GlobalSceneIndex) : 1, 1);
|
||||
}
|
||||
|
||||
<div class="page-heading">
|
||||
<div data-pwa-task class="page-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Relationship Evolution</p>
|
||||
<h1>@Model.Relationship.CharacterAName -> @Model.Relationship.CharacterBName</h1>
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
ViewData["ProjectSection"] = "Health";
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<a asp-controller="Analytics" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Story Health</a>
|
||||
@ -13,7 +13,7 @@
|
||||
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<div class="page-heading">
|
||||
<div data-pwa-header class="page-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Story Dynamics</p>
|
||||
<h1>@Model.Project.ProjectName <help-icon key="storyDynamics.overview" /></h1>
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
@model FeatureRequestCreateViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "compact";
|
||||
ViewData["Title"] = "Submit Feature Request";
|
||||
}
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-task class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Feedback</p>
|
||||
<h1>Submit Feature Request</h1>
|
||||
@ -11,7 +12,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav class="mb-3" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="mb-3" aria-label="Breadcrumb">
|
||||
<a asp-action="Index">Feature Requests</a>
|
||||
<span class="muted"> / Submit</span>
|
||||
</nav>
|
||||
|
||||
@ -2,11 +2,12 @@
|
||||
@using Microsoft.AspNetCore.Html
|
||||
@using System.Text.Encodings.Web
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "compact";
|
||||
ViewData["Title"] = Model.Request.Title;
|
||||
var request = Model.Request;
|
||||
}
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-task class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Feature Request</p>
|
||||
<h1>@request.Title</h1>
|
||||
@ -16,7 +17,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav class="mb-3" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="mb-3" aria-label="Breadcrumb">
|
||||
<a asp-action="Index">Feature Requests</a>
|
||||
<span class="muted"> / Details</span>
|
||||
</nav>
|
||||
|
||||
@ -2,10 +2,11 @@
|
||||
@using Microsoft.AspNetCore.Html
|
||||
@using System.Text.Encodings.Web
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "management";
|
||||
ViewData["Title"] = "Feature Requests";
|
||||
}
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-header class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Feedback</p>
|
||||
<h1>Feature Requests</h1>
|
||||
@ -17,7 +18,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav class="mb-3" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="mb-3" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<span class="muted"> / Feature Requests</span>
|
||||
</nav>
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
ViewData["Title"] = "Feature Roadmap";
|
||||
}
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-header class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Feedback</p>
|
||||
<h1>Feature Roadmap</h1>
|
||||
@ -17,7 +17,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav class="mb-3" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="mb-3" aria-label="Breadcrumb">
|
||||
<a asp-action="Index">Feature Requests</a>
|
||||
<span class="muted"> / Roadmap</span>
|
||||
</nav>
|
||||
|
||||
@ -77,7 +77,7 @@
|
||||
.ToList();
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<a asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Floor Plans</a>
|
||||
@ -86,7 +86,7 @@
|
||||
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-task class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Location floor plan</p>
|
||||
<h1>@Model.FloorPlan.Name <help-icon key="floorPlans.overview" /></h1>
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
@model FloorPlanListViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "management";
|
||||
ViewData["Title"] = "Floor Plans";
|
||||
ViewData["ProjectSection"] = "Floor Plans";
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<span>Floor Plans</span>
|
||||
@ -12,7 +13,7 @@
|
||||
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-header class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Location plans</p>
|
||||
<h1>@Model.Project.ProjectName <help-icon key="floorPlans.overview" /></h1>
|
||||
@ -59,7 +60,7 @@ else
|
||||
<div class="floor-plan-list">
|
||||
@foreach (var floorPlan in Model.FloorPlans)
|
||||
{
|
||||
<article class="floor-plan-list-item">
|
||||
<article data-pd-context="floor plan" data-pd-context-id="@floorPlan.FloorPlanID" data-pd-context-label="@floorPlan.Name" class="floor-plan-list-item">
|
||||
<div>
|
||||
<h2><a asp-action="Edit" asp-route-id="@floorPlan.FloorPlanID">@floorPlan.Name</a></h2>
|
||||
@if (!string.IsNullOrWhiteSpace(floorPlan.Description))
|
||||
|
||||
@ -3,13 +3,13 @@
|
||||
ViewData["Title"] = $"Help - {Model.Article.Title}";
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-context="Navigation" class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a href="/help">Help</a>
|
||||
<a href="@Model.Article.CategoryUrl">@Model.Article.Category</a>
|
||||
<span>@Model.Article.Title</span>
|
||||
</nav>
|
||||
|
||||
<div class="page-heading">
|
||||
<div data-pwa-task class="page-heading">
|
||||
<div>
|
||||
<p class="eyebrow">@Model.Article.Category</p>
|
||||
<h1>@Model.Article.Title</h1>
|
||||
|
||||
@ -3,12 +3,12 @@
|
||||
ViewData["Title"] = $"Help - {Model.CategoryName}";
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-context="Navigation" class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a href="/help">Help</a>
|
||||
<span>@Model.CategoryName</span>
|
||||
</nav>
|
||||
|
||||
<div class="page-heading">
|
||||
<div data-pwa-task class="page-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Help category</p>
|
||||
<h1>@Model.CategoryName</h1>
|
||||
|
||||
@ -3,11 +3,11 @@
|
||||
ViewData["Title"] = "Help";
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<span>Help</span>
|
||||
</nav>
|
||||
|
||||
<div class="page-heading">
|
||||
<div data-pwa-header class="page-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Guidance</p>
|
||||
<h1>Help Centre <help-icon key="helpCentre.overview" /></h1>
|
||||
@ -15,7 +15,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section class="plain-card mb-4">
|
||||
<section data-pwa-context="Find" class="plain-card mb-4">
|
||||
<form method="get" asp-action="Index" class="row g-2 align-items-end">
|
||||
<div class="col-md-9">
|
||||
<label class="form-label" for="q">Search help articles</label>
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
var preview = Model.Preview;
|
||||
}
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-header class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Tools</p>
|
||||
<h1>JSON Import <help-icon key="imports.overview" /></h1>
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
ViewData["Title"] = Model.IsDryRun ? "Dry Run Complete" : "Import Complete";
|
||||
}
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-task class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Import result</p>
|
||||
<h1>@(Model.IsDryRun ? "Dry run complete" : "Import complete")</h1>
|
||||
|
||||
@ -33,7 +33,7 @@
|
||||
<div class="story-character-card-grid">
|
||||
@foreach (var item in Model.Items)
|
||||
{
|
||||
<details class="story-character-card" open>
|
||||
<details data-pd-context="review observation" data-pd-context-id="@item.Row.StableKey" data-pd-context-label="@item.Row.DisplayName" class="story-character-card" open>
|
||||
<summary class="story-review-card-header"><span><strong>@item.Row.DisplayName</strong><small>@item.Status</small></span></summary>
|
||||
<div class="story-character-card__body">
|
||||
@if (!string.IsNullOrWhiteSpace(item.Direction)) { <p><strong>@item.Direction</strong> · @item.State</p> }
|
||||
@ -67,9 +67,11 @@
|
||||
@if (Model.Page > 1) { <a class="btn btn-outline-secondary" asp-action="Index" asp-route-batchId="@Model.BatchID" asp-route-module="@Model.Module" asp-route-scope="@Model.Scope" asp-route-page="@(Model.Page - 1)">Previous</a> }
|
||||
<span>Page @Model.Page of @Model.PageCount</span>
|
||||
@if (Model.Page < Model.PageCount) { <a class="btn btn-outline-secondary" asp-action="Index" asp-route-batchId="@Model.BatchID" asp-route-module="@Model.Module" asp-route-scope="@Model.Scope" asp-route-page="@(Model.Page + 1)">Next</a> }
|
||||
<div data-pwa-context="Navigation">
|
||||
<a class="btn btn-outline-secondary" asp-controller="Onboarding" asp-action="StoryIntelligenceReviewCentre" asp-route-batchId="@Model.BatchID">Back to Review Centre</a>
|
||||
<a class="btn btn-outline-primary" asp-controller="@Model.CanonicalController" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">View tracked @Model.Module.ToLowerInvariant()</a>
|
||||
<a class="btn btn-primary" asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID">Return to Book</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
@model LocationDetailViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "details";
|
||||
ViewData["Title"] = Model.Location.LocationName;
|
||||
ViewData["ProjectSection"] = "Locations";
|
||||
var firstScene = Model.Scenes.FirstOrDefault();
|
||||
@ -13,7 +14,7 @@
|
||||
.ToList();
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<a asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Locations</a>
|
||||
@ -23,13 +24,13 @@
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<div class="location-page">
|
||||
<div class="page-heading compact">
|
||||
<div data-pd-context="location" data-pd-context-id="@Model.Location.LocationID" data-pd-context-label="@Model.Location.LocationName" data-pwa-help class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Location detail</p>
|
||||
<h1>@Model.Location.LocationName <help-icon key="locations.details" /></h1>
|
||||
<p class="muted">@Model.Location.LocationPath</p>
|
||||
</div>
|
||||
<div class="button-row">
|
||||
<div data-pwa-context="Manage" class="button-row">
|
||||
<a class="btn btn-outline-primary" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">All locations</a>
|
||||
<div class="dropdown pw-actions">
|
||||
<button class="btn pw-actions__toggle dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Tools</button>
|
||||
@ -47,7 +48,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section class="edit-panel">
|
||||
<section class="edit-panel pd-record-panel">
|
||||
<div class="row g-3">
|
||||
<div class="col-md-4">
|
||||
<p class="eyebrow">Type</p>
|
||||
|
||||
@ -1,12 +1,13 @@
|
||||
@model LocationEditViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "wide";
|
||||
ViewData["Title"] = Model.LocationID == 0 ? "New Location" : "Edit Location";
|
||||
ViewData["ProjectSection"] = "Locations";
|
||||
}
|
||||
|
||||
@if (Model.Project is not null)
|
||||
{
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<a asp-action="Index" asp-route-projectId="@Model.ProjectID">Locations</a>
|
||||
@ -16,24 +17,25 @@
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
}
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-task class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Location</p>
|
||||
<h1>@ViewData["Title"] <help-icon key="locations.edit" /></h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form asp-action="Save" method="post" class="edit-panel">
|
||||
<form asp-action="Save" method="post" class="edit-panel pd-record-form">
|
||||
<input asp-for="LocationID" type="hidden" />
|
||||
<input asp-for="ProjectID" type="hidden" />
|
||||
|
||||
<div class="row g-3">
|
||||
<div class="col-md-8">
|
||||
<div class="row g-3 pd-record-fields">
|
||||
<div class="pd-record-group-label" role="heading" aria-level="2">Names</div>
|
||||
<div class="col-md-8 pd-record-span-6">
|
||||
<label asp-for="LocationName" class="form-label"></label>
|
||||
<input asp-for="LocationName" class="form-control" />
|
||||
<span asp-validation-for="LocationName" class="text-danger"></span>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<div class="col-12 pd-record-span-6">
|
||||
<label class="form-label">Known names</label>
|
||||
<div class="d-flex flex-wrap gap-2 mb-2" data-alias-list>
|
||||
@for (var i = 0; i < Model.Aliases.Count; i++)
|
||||
@ -50,26 +52,28 @@
|
||||
<button class="btn btn-outline-secondary" type="button" data-add-alias>Add</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="pd-record-group-label" role="heading" aria-level="2">Hierarchy</div>
|
||||
<div class="col-md-4 pd-record-span-6">
|
||||
<label asp-for="LocationTypeID" class="form-label">Location type <help-icon key="locations.fields.locationType" mode="inline" /></label>
|
||||
<select asp-for="LocationTypeID" asp-items="Model.LocationTypeOptions" class="form-select">
|
||||
<option value="">Not set</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<div class="col-12 pd-record-span-6">
|
||||
<label asp-for="ParentLocationID" class="form-label">Parent location <help-icon key="locations.fields.parentLocation" mode="inline" /></label>
|
||||
<select asp-for="ParentLocationID" asp-items="Model.ParentLocationOptions" class="form-select">
|
||||
<option value="">Top level</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<div class="col-12 pd-record-span-12">
|
||||
<div class="form-check">
|
||||
<input asp-for="ShowInQuickAddBar" class="form-check-input" />
|
||||
<label asp-for="ShowInQuickAddBar" class="form-check-label">Show in Quick Add Bar <help-icon key="locations.fields.quickAdd" mode="inline" /></label>
|
||||
<div class="form-text">Makes this item available as a draggable shortcut on the Timeline page.</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<div class="pd-record-group-label" role="heading" aria-level="2">Companion matching</div>
|
||||
<div class="col-12 pd-record-span-12">
|
||||
<section class="list-section p-3">
|
||||
<h2 class="h5">Companion Detection</h2>
|
||||
<div class="form-check mb-3">
|
||||
@ -83,15 +87,15 @@
|
||||
<div class="form-text">Higher values make this location stronger evidence in future Word Companion detection. The default is 50.</div>
|
||||
</section>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<div class="col-12 pd-record-span-12">
|
||||
<label asp-for="Description" class="form-label"></label>
|
||||
<textarea asp-for="Description" class="form-control" rows="5"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="button-row mt-3">
|
||||
<button class="btn btn-primary" type="submit">Save location</button>
|
||||
<a class="btn btn-outline-secondary" asp-action="Index" asp-route-projectId="@Model.ProjectID">Cancel</a>
|
||||
<div data-pwa-context="Record" data-pwa-priority="0" class="button-row mt-3">
|
||||
<button class="btn btn-primary" data-pwa-icon="save" type="submit">Save location</button>
|
||||
<a class="btn btn-outline-secondary" data-pwa-icon="close" asp-action="Index" asp-route-projectId="@Model.ProjectID">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
@model LocationListViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "management";
|
||||
ViewData["Title"] = "Locations";
|
||||
ViewData["ProjectSection"] = "Locations";
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<span>Locations</span>
|
||||
@ -13,7 +14,7 @@
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<div class="location-page">
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-header class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Locations</p>
|
||||
<h1>@Model.Project.ProjectName <help-icon key="locations.overview" /></h1>
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
@model EntityMergeViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "compact";
|
||||
ViewData["Title"] = $"Merge {Model.SourceName}";
|
||||
ViewData["ProjectSection"] = "Locations";
|
||||
}
|
||||
|
||||
<nav class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<a asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Locations</a>
|
||||
@ -14,7 +15,7 @@
|
||||
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<div class="page-heading compact">
|
||||
<div data-pwa-task class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Location identity</p>
|
||||
<h1>Merge @Model.SourceName</h1>
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
<section class="edit-panel location-tree" data-location-tree>
|
||||
@foreach (var location in Model.Locations)
|
||||
{
|
||||
<div class="location-tree-row" draggable="true" data-drag-type="location" data-drag-id="@location.LocationID" data-drag-label="@location.LocationName" data-parent-location-id="@location.ParentLocationID" data-parent-location-name="@location.ParentLocationName" style="--location-depth:@location.Depth">
|
||||
<div data-pd-context="location" data-pd-context-id="@location.LocationID" data-pd-context-label="@location.LocationName" class="location-tree-row" draggable="true" data-drag-type="location" data-drag-id="@location.LocationID" data-drag-label="@location.LocationName" data-parent-location-id="@location.ParentLocationID" data-parent-location-name="@location.ParentLocationName" style="--location-depth:@location.Depth">
|
||||
<div>
|
||||
<a asp-action="Details" asp-route-id="@location.LocationID"><strong>@location.LocationName</strong></a>
|
||||
@if (!string.IsNullOrWhiteSpace(location.LocationTypeName))
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
@model ChangePasswordViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "compact";
|
||||
ViewData["Title"] = "Change Password";
|
||||
}
|
||||
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
@model DisableTwoFactorViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "compact";
|
||||
ViewData["Title"] = "Disable Two Factor";
|
||||
}
|
||||
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
@model EnableTwoFactorViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "compact";
|
||||
ViewData["Title"] = "Enable Two Factor";
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user