Implement Phase 3A integrated Writer authoring with scoped canonical saves

This commit is contained in:
Nick Beckley 2026-11-16 20:12:16 +00:00
parent e789da6139
commit 024e668978
32 changed files with 717 additions and 11 deletions

View File

@ -94,3 +94,7 @@ Destination Help remains at the heading. The layout tooltip/popup icon is groupe
Phase2C amendment: `writer3.write` explains the single working-focus selection, separate save/record/plan actions, actual objective/session mappings, explicit proofreading recording choice, recording-only activities, active-target differences and optional book-scoped planning. Existing working-context/session/native and planning Help remain authoritative; no data consolidation.
Phase2C qualified: existing micro/quick/full articles, browser popup and PWA drawer verified through targeted and navigation/live suites. Real unified actions and rejection/antiforgery checks passed in Development. See Phase2C-Report.md for full evidence and physical acceptance limits.
## Phase 3A authoring
`writer3.authoring` reuses the Markdown tag helper for tooltip, quick popup and full article/drawer. Covers optional chapter/scene intentions, section Save/Cancel, stale/conflict recovery, navigation guards, scene-note/checklist/workflow scopes, explicit initialisation, deferred attachment/category editors, saved companion references and session/Reader/native isolation. `writer3.write` now describes the integrated surface without changing the unified Current Work actions. Qualification is recorded in Phase3A-Report.md.

View File

@ -1,6 +1,6 @@
# Writer 3.0 implementation tracker
Baseline: `9a8b9a3`, shared branch `codex/word-companion-native-phase1-20261104`, 16 November 2026. The original kickoff authorised Phase 1 implementation and Development deployment; the master specification governs product direction even though its header says Proposed. The subsequent Phase2A kickoff explicitly authorised Home, navigation, destination shells and Development deployment; Phase2B was subsequently explicitly authorised for layout infrastructure and Development deployment; Phase2C is implemented and Development-qualified, including the explicit single-focus workflow amendment; Phase3 remains unauthorised. No feature is retired. Unrelated investigation file is preserved.
Baseline: `9a8b9a3`, shared branch `codex/word-companion-native-phase1-20261104`, 16 November 2026. The original kickoff authorised Phase 1 implementation and Development deployment; the master specification governs product direction even though its header says Proposed. The subsequent Phase2A kickoff explicitly authorised Home, navigation, destination shells and Development deployment; Phase2B was subsequently explicitly authorised for layout infrastructure and Development deployment; Phase2C is implemented and Development-qualified, including the explicit single-focus workflow amendment; Phase3A is now explicitly authorised for integrated authoring and Development qualification; Phase3B remains unauthorised. No feature is retired. Unrelated investigation file is preserved.
## Phase 1 screen and interaction states before implementation
@ -344,3 +344,7 @@ Application `10bf9db9061fdec340acf7ff0df96f3dfd299814`, release `10bf9db-2026111
## Phase 2C / Phase 2 software completion — 16 November 2026
Application `e9402d0c1673d3dc8afcca26bb344b82fa11caf0`, release `e9402d0-20261116T171812Z`. Observed marker wrapping, wide reading lines, Help ambiguity and modified-key interception corrected. User amendment delivered one focus selection with separate save/record/plan actions, explicit activity adapters and active-session target separation. Existing storage/services/native authority retained. Build0warnings/errors; full harness587 PASS; navigation168 cases, isolated/live workspace200 cases each; focused unification, actual Development objective/session/validation/planning, refinement, Reader/Intent/standalone/native-follow/audio/legacy desk coverage passed. Before/after read-only ten-field hashes identical; fixture projects/account removed, private identity removed. DLL hash/metadata match; service active, TLS GET200, actual deployment-to-acceptance warning journal clear. [Report and before/after evidence](Phase2C-Report.md). Physical Windows/installed PWA/real Word/media/multi-monitor and assistive-technology checks remain manual. Phase3 not started.
## Phase3A authorised implementation
[Execution and canonical-data contract](Phase3A-Execution.md). Current Work remains unified; optional chapter/scene intentions, notes, reminders and working details use existing records through pure inspection and scoped concurrency-safe saves. Companion shows only saved references. Full native/context redesign, manuscript editing, new planning and AI engines remain out of scope. Help and regression/transactional/browser qualification in progress; Development release pending. Phase3B not started.

View File

@ -0,0 +1,21 @@
# Phase3A execution and authoring contracts
Authorised3A only after Phase2 completion. Shared branch; unrelated investigation retained. No manuscript editor or3B native changes.
## Authoritative discovery
Chapter purpose is ChapterPurposeID lookup plus existing Summary; chapter intentions are the five ChapterGoals fields, not a new notebook. Scene intent/outcome are ScenePurposeNotes/SceneOutcomeNotes. SceneNotes retain type/pinned/resolved/order; SceneChecklistItems retain independent completion; SceneWorkflow retains separate priority/count/date/blocker/readiness and legacy draft fields. Canonical scene revision state remains Scenes.RevisionStatusID. Session notes, accepted manuscript evidence and story references remain separate systems.
Existing Scene_Get/SceneMetric_ListByScene seed metric defaults, so the new surface uses the pure chapter scene list and location read instead. Existing ChapterGoal_Get creates a row; SceneWorkflow_Get creates workflow and eight default checklist items; SceneService edit/writing loaders call those getters. New inspection therefore uses a bounded, authorised read procedure with no initialisation. Existing canonical goal/note/checklist/workflow saves are reused under a transaction. Chapter summary/purpose and scene intent/outcome use narrow updates to the existing columns rather than broad entity saves that may replace unrelated metadata.
Field-scoped fingerprints plus row/range locks protect stale updates and repeated creates. No new tables. Normal read fingerprints exclude unrelated parent/audit timestamps. Canonical nvarchar(max) text remains unrestricted beyond existing HTTP limits; note titles200 and checklist text300 retain canonical bounds. Optional integer/date controls remain NULL when blank.
## Batches
-3A.1: compact saved focus and existing unified Save/Record/Plan; chapter-only/scene-specific authoring, explicit scene-focus change, optional whole-book/no-focus state.
-3A.2: chapter purpose/summary/goals and scene purpose/outcome; independent editors, Save/Cancel, errors, stale409, retained dirty values and navigation guard.
-3A.3: scene notes/checklist/workflow, explicit creation only, progressive details; canonical revision/readiness preserved. Attachments, deletion and complex category/dependency edits remain labelled existing routes.
-3A.4: saved setting/appearances/threads/verified relationship events and chapter feeling intention; no inference, analysis or replacement standalone windows.
-3A.5: Markdown Help, schema/controller/browser/PWA and transactional SQL coverage, full harness, authenticated Development qualification, snapshots, cleanup and rollback release.
SQL265 introduces procedures;266–270 are forward-only corrections discovered through live-schema/transactional qualification (optional NULLs, long JSON conversion, field-level concurrency, empty collection tokens and canonical text lengths). Already-applied numbered scripts remain immutable. All are additive procedure changes, compatible with the Phase2 application. Verified Development backup precedes application/fixture writes. Final status and deferred editors are recorded in Phase3A-Report.md.

View File

@ -0,0 +1,21 @@
// Explicit writes only to a dedicated disposable Development fixture; no native Word automation.
const{chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
(async()=>{const w=JSON.parse(fs.readFileSync(process.env.PD_WRITER3_IDENTITY));assert(w.Database==='PlotDirector_Development'&&w.Email.endsWith('@example.invalid'));const b=await chromium.launch();try{for(const pwa of[false,true]){
const c=await b.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(id=>localStorage.setItem('plotdirector.desktop.v1.'+id,JSON.stringify({dismissedAt:Date.now()})),w.UserID);if(pwa)await c.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));const base='https://dev.plotdirector.com',url=`${base}/Writer/Write?projectId=${w.project}&bookId=${w.book}`;
await p.goto(base+'/Account/Login');await p.locator('[name=Email]').fill(w.Email);await p.locator('[name=Password]').fill(w.Password);await Promise.all([p.waitForURL('**/Projects'),p.locator('button[type=submit]').click()]);
await p.goto(url);const sceneKey='Scene-'+w.scene,goalKey='Goals-'+w.chapter,chapterKey='Chapter-'+w.chapter,workflowKey='Workflow-'+w.scene;const card=k=>p.locator(`[data-key="${k}"]`),edit=async k=>{await card(k).locator('[data-authoring-edit]').click();},save=async k=>{await card(k).locator('[data-authoring-save]').click();await card(k).locator('[data-authoring-status]').filter({hasText:'Saved.'}).waitFor();};await card(sceneKey).waitFor();assert.equal(await p.locator('[data-writer-work]').count(),1);assert((await p.locator('[data-authoring-references]').textContent()).includes('Recorded reference person'));assert((await p.locator('[data-authoring-references]').textContent()).includes('Recorded reference place'));
await edit(sceneKey);await card(sceneKey).locator('[name=ScenePurposeNotes]').fill('Explicit fixture intention — '+ '界'.repeat(4500));await card(sceneKey).locator('[name=SceneOutcomeNotes]').fill('An explicitly recorded outcome');await save(sceneKey);await edit(sceneKey);assert((await card(sceneKey).locator('[name=ScenePurposeNotes]').inputValue()).length>4500);await card(sceneKey).locator('[name=ScenePurposeNotes]').fill('Establish the next development and give the scene a clear direction.');await save(sceneKey);
await p.getByText('Chapter summary and additional intentions',{exact:true}).click();await edit(chapterKey);await card(chapterKey).locator('[name=Summary]').fill('A chapter summary entered through Write');await save(chapterKey);await edit(goalKey);await card(goalKey).locator('[name=GoalSummary]').fill('A chapter goal entered through Write');await card(goalKey).locator('[name=EmotionalGoal]').fill('A recorded feeling intention');await card(goalKey).locator('[name=MustInclude]').fill('An important detail');await save(goalKey);assert((await p.locator('[data-authoring-references]').textContent()).includes('recorded feeling intention'));
await edit('AddNote-0');await card('AddNote-0').locator('[name=NoteTitle]').fill('Disposable inline note');await card('AddNote-0').locator('[name=NoteText]').fill('Remember this saved scene detail');await save('AddNote-0');const note=p.locator('[data-authoring-new-records] [data-kind=Note]').last();await note.locator('[data-authoring-edit]').click();await note.locator('[name=NoteText]').fill('Edited saved note');await note.locator('[data-authoring-save]').click();await p.locator('[data-authoring-new-records] [data-kind=Note]').last().locator('[data-authoring-status]').filter({hasText:'Saved.'}).waitFor();
await edit('AddChecklist-0');await card('AddChecklist-0').locator('[name=ItemText]').fill('A saved reminder');await save('AddChecklist-0');const reminder=p.locator('[data-authoring-new-records] [data-kind=Checklist]').last();await reminder.locator('[data-authoring-edit]').click();await reminder.locator('[name=IsCompleted]').check();await reminder.locator('[data-authoring-save]').click();await p.locator('[data-authoring-new-records] [data-kind=Checklist]').last().locator('[data-authoring-status]').filter({hasText:'Saved.'}).waitFor();
await p.getByText('All scene notes, reminders and working details',{exact:true}).click();await edit(workflowKey);await card(workflowKey).locator('[name=Priority]').fill('11');await card(workflowKey).locator('[data-authoring-save]').click();await card(workflowKey).locator('[data-authoring-error]:visible').waitFor();assert.equal(await card(workflowKey).locator('[name=Priority]').inputValue(),'11');await card(workflowKey).locator('[name=Priority]').fill('2');await card(workflowKey).locator('[name=IsBlocked]').check();await card(workflowKey).locator('[name=BlockedReason]').fill('An explicitly recorded blocker');await save(workflowKey);
await p.locator('[data-record-focus]:enabled').waitFor();await p.locator('[data-record-focus]').click();await p.locator('[data-work-current]:visible').waitFor();const readSession=async()=>await(await p.request.get(`${base}/Writer/Work/State?bookId=${w.book}`)).json();const active=(await readSession()).session;await p.locator('[data-work-note]').fill('Return note retained during inline save');await edit(sceneKey);await card(sceneKey).locator('[name=SceneOutcomeNotes]').fill('Outcome edited during a real recording');await save(sceneKey);assert.equal((await readSession()).session.sessionID,active.sessionID);assert.equal((await readSession()).session.chapterID,w.chapter);assert.equal(await p.locator('[data-work-note]').inputValue(),'Return note retained during inline save');await p.locator('[data-work-end]').click();await p.locator('[data-work-current]').waitFor({state:'hidden'});
await edit(sceneKey);await card(sceneKey).locator('[name=SceneOutcomeNotes]').fill('Stale unsaved outcome');const q=await c.newPage();await q.goto(url);const other=q.locator(`[data-key="${sceneKey}"]`);await other.locator('[data-authoring-edit]').click();await other.locator('[name=SceneOutcomeNotes]').fill('A concurrent recorded outcome');await other.locator('[data-authoring-save]').click();await other.locator('[data-authoring-status]').filter({hasText:'Saved.'}).waitFor();await q.close();await card(sceneKey).locator('[data-authoring-save]').click();await card(sceneKey).locator('[data-authoring-reload]:visible').waitFor();assert.equal(await card(sceneKey).locator('[name=SceneOutcomeNotes]').inputValue(),'Stale unsaved outcome');await card(sceneKey).locator('[data-authoring-cancel]').click();await p.reload();await card(sceneKey).waitFor();assert((await card(sceneKey).locator('[data-authoring-display]').textContent()).includes('concurrent recorded outcome'));
const token=await card(sceneKey).locator('[name=__RequestVerificationToken]').inputValue();assert.equal((await p.request.post(base+'/WriterAuthoring/Save',{form:{bookId:String(w.book),chapterId:String(w.chapter),sceneId:String(w.scene),kind:'Scene',entityId:String(w.scene),version:'0'.repeat(64),__RequestVerificationToken:token}})).status(),409);assert.equal((await p.request.post(base+'/WriterAuthoring/Save',{form:{bookId:String(w.book),chapterId:String(w.chapter),sceneId:String(w.scene),kind:'Scene',entityId:String(w.scene)}})).status(),400);assert.equal((await p.request.get(`${base}/WriterAuthoring/Inspect?bookId=${w.other}&chapterId=${w.chapter}&sceneId=${w.scene}`)).status(),404);
if(!pwa&&process.env.PD_WRITER3_SCREENSHOTS){fs.mkdirSync(process.env.PD_WRITER3_SCREENSHOTS,{recursive:true});await p.evaluate(()=>window.PlotDirectorApplyApplicationTheme('modern-dark'));await p.locator('.writer3-main').evaluate(n=>n.scrollTop=0);await p.screenshot({path:process.env.PD_WRITER3_SCREENSHOTS+'/Write-authoring.png',animations:'disabled'});await edit(sceneKey);await card(sceneKey).locator('[data-authoring-form]').scrollIntoViewIfNeeded();await p.screenshot({path:process.env.PD_WRITER3_SCREENSHOTS+'/Write-inline-editor.png',animations:'disabled'});await card(sceneKey).locator('[data-authoring-cancel]').click();}
// Chapter-level focus has goals and scene choices without forcing a scene.
await p.goto(url+'&setup=true');await p.locator('[data-objective-scene]').selectOption('');await Promise.all([p.waitForURL(u=>u.pathname==='/Writer/Write'&&!u.searchParams.has('setup')),p.locator('[data-save-focus]').click()]);await card(goalKey).waitFor();assert.equal(await p.locator(`[data-key="${sceneKey}"]`).count(),0);assert(await p.getByRole('button',{name:'Work on this scene'}).isVisible());await Promise.all([p.waitForURL(u=>u.pathname==='/Writer/Write'&&!u.searchParams.has('setup')),p.getByRole('button',{name:'Work on this scene'}).click()]);await card(sceneKey).waitFor();
if(w.emptyChapter){await p.goto(url+'&setup=true');await p.locator('[data-objective-chapter]').selectOption(String(w.emptyChapter));await Promise.all([p.waitForURL(u=>u.pathname==='/Writer/Write'&&!u.searchParams.has('setup')),p.locator('[data-save-focus]').click()]);await p.getByText('There are no scenes yet.',{exact:false}).waitFor();assert.equal(await p.locator('[data-key="Scene-'+w.scene+'"]').count(),0);await p.goto(url+'&setup=true');await p.locator('[data-objective-chapter]').selectOption(String(w.chapter));await p.locator('[data-objective-scene]').selectOption(String(w.scene));await Promise.all([p.waitForURL(u=>u.pathname==='/Writer/Write'&&!u.searchParams.has('setup')),p.locator('[data-save-focus]').click()]);await card(sceneKey).waitFor();}
assert.deepEqual(errors,[]);await c.close();}
console.log('PASS authenticated Development authoring browser/simulated PWA: actual canonical chapter/scene/goals, long Unicode, note/reminder create/edit, workflow validation, explicit session and note isolation, stale409 retained text, chapter focus/scene selection, scope404 and antiforgery400; explicit disposable fixture edits only.');
}finally{await b.close()}})().catch(e=>{console.error(e.message);process.exitCode=1});

View File

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

View File

@ -15,7 +15,7 @@ const base='http://127.0.0.1:5238';
await page.setViewportSize({width,height:1000});await page.addInitScript(theme=>localStorage.setItem('plotdirector.applicationTheme',theme),theme);
for(const destination of ['Index','Write','Explore','Plan','Review','Reflect','Dashboard']){
await page.goto(`${base}/Writer/${destination}?projectId=7&bookId=12&objective=true&populated=true`);
await page.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);
await page.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);await page.screenshot({animations:'disabled'});
const kind=destination==='Index'?'Home':destination;
assert.equal(await page.locator('[data-writer-destination]').getAttribute('data-writer-destination'),kind);
const commands=page.locator('#ribbon-panel-writer [role=group]').first().locator('a');

View File

@ -170,6 +170,7 @@ var tests = new (string Name, Action Test)[]
("Release triage and browser-only onboarding preserve author decisions", ReleaseSprintTests.Run),
("Approved native import source and confirmation remain safe", () => NativeImportTests.Run().GetAwaiter().GetResult()),
("Native installation renewal and revocation remain account/security scoped", () => NativeInstallationTests.Run().GetAwaiter().GetResult()),
("Writer inline authoring validation",()=>WriterAuthoringTests.Run()),
("Writer 3 destination navigation and scope",()=>WriterNavigationTests.Run().GetAwaiter().GetResult()),
("Writer foundation context, queue scope and planning",()=>WriterFoundationTests.Run().GetAwaiter().GetResult()),
("Writer dashboard book scope",()=>WriterDashboardTests.Run().GetAwaiter().GetResult()),

View File

@ -0,0 +1,46 @@
-- Substitute {{UserID}}, {{BookID}}, {{ChapterID}}, {{SceneID}} from a guarded disposable Development fixture.
IF DB_NAME()<>N'PlotDirector_Development' THROW 51000,'Wrong database',1;
DECLARE @u int={{UserID}},@b int={{BookID}},@c int={{ChapterID}},@s int={{SceneID}};
IF NOT EXISTS(SELECT 1 FROM dbo.AppUser WHERE UserID=@u AND Email LIKE N'pwa-browser-%@example.invalid') THROW 51000,'Not a disposable fixture',1;
DECLARE @r table(Kind varchar(20),EntityID int,Data nvarchar(max),Version varchar(64));
DECLARE @originalStatus int=(SELECT RevisionStatusID FROM dbo.Scenes WHERE SceneID=@s),@originalNotes int=(SELECT COUNT(*) FROM dbo.SceneNotes WHERE SceneID=@s),@v varchar(64),@old varchar(64),@id int,@json nvarchar(max),@conflict bit=0;
IF EXISTS(SELECT 1 FROM dbo.SceneWorkflow WHERE SceneID=@s) OR @originalNotes<>0 OR EXISTS(SELECT 1 FROM dbo.SceneChecklistItems WHERE SceneID=@s) OR EXISTS(SELECT 1 FROM dbo.ChapterGoals WHERE ChapterID=@c) THROW 51000,'Fixture must start empty',1;
INSERT @r EXEC dbo.WriterAuthoring_Sections @u,@b,@c,@s;
IF EXISTS(SELECT 1 FROM dbo.SceneWorkflow WHERE SceneID=@s) OR EXISTS(SELECT 1 FROM dbo.ChapterGoals WHERE ChapterID=@c) OR EXISTS(SELECT 1 FROM dbo.SceneChecklistItems WHERE SceneID=@s) THROW 51000,'Inspection seeded records',1;
BEGIN TRANSACTION;
SELECT @v=Version,@old=Version FROM @r WHERE Kind='Scene';
SET @json=N'{"ScenePurposeNotes":"'+REPLICATE(CONVERT(nvarchar(max),N'界'),4500)+N'","SceneOutcomeNotes":"An explicitly entered outcome"}';
EXEC dbo.WriterAuthoring_Save @u,@b,@c,@s,'Scene',@s,@v,@json;
IF (SELECT LEN(ScenePurposeNotes) FROM dbo.Scenes WHERE SceneID=@s)<>4500 THROW 51000,'Long Unicode text was truncated',1;
SELECT @v=Version FROM @r WHERE Kind='Goals';EXEC dbo.WriterAuthoring_Save @u,@b,@c,@s,'Goals',@c,@v,N'{"GoalSummary":"Optional intention","MustInclude":"Remember this"}';
SELECT @v=Version FROM @r WHERE Kind='Chapter';EXEC dbo.WriterAuthoring_Save @u,@b,@c,@s,'Chapter',@c,@v,N'{"Summary":"Explicit chapter summary","ChapterPurposeID":""}';
SELECT @v=Version FROM @r WHERE Kind='Workflow';EXEC dbo.WriterAuthoring_Save @u,@b,@c,@s,'Workflow',@s,@v,N'{"Priority":"2","IsBlocked":"true","BlockedReason":"Author supplied blocker"}';
IF EXISTS(SELECT 1 FROM dbo.SceneChecklistItems WHERE SceneID=@s) THROW 51000,'Workflow save seeded default checklist',1;
DECLARE @t int=(SELECT TOP(1) SceneNoteTypeID FROM dbo.SceneNoteTypes WHERE IsActive=1 ORDER BY SortOrder);
SELECT @v=Version FROM @r WHERE Kind='AddNote';SET @json=N'{"SceneNoteTypeID":"'+CONVERT(nvarchar(20),@t)+N'","NoteText":"An explicit scene note","IsPinned":"true"}';EXEC dbo.WriterAuthoring_Save @u,@b,@c,@s,'AddNote',0,@v,@json;
SELECT @v=Version FROM @r WHERE Kind='AddChecklist';EXEC dbo.WriterAuthoring_Save @u,@b,@c,@s,'AddChecklist',0,@v,N'{"ItemText":"Check this detail","IsCompleted":"false"}';
DELETE @r;INSERT @r EXEC dbo.WriterAuthoring_Sections @u,@b,@c,@s;
SELECT @id=EntityID,@v=Version FROM @r WHERE Kind='Note';SET @json=N'{"SceneNoteTypeID":"'+CONVERT(nvarchar(20),@t)+N'","NoteText":"Edited scene note","IsResolved":"true"}';EXEC dbo.WriterAuthoring_Save @u,@b,@c,@s,'Note',@id,@v,@json;
SELECT @id=EntityID,@v=Version FROM @r WHERE Kind='Checklist';EXEC dbo.WriterAuthoring_Save @u,@b,@c,@s,'Checklist',@id,@v,N'{"ItemText":"Check this detail","IsCompleted":"true"}';
IF (SELECT RevisionStatusID FROM dbo.Scenes WHERE SceneID=@s)<>@originalStatus THROW 51000,'Supporting saves changed canonical scene state',1;
IF (SELECT COUNT(*) FROM dbo.SceneNotes WHERE SceneID=@s)<>1 OR (SELECT COUNT(*) FROM dbo.SceneChecklistItems WHERE SceneID=@s)<>1 THROW 51000,'Unexpected support records',1;
BEGIN TRY EXEC dbo.WriterAuthoring_Save @u,@b,@c,@s,'Scene',@s,@old,N'{"ScenePurposeNotes":"Stale overwrite"}';END TRY BEGIN CATCH IF ERROR_NUMBER()<>51002 THROW;SET @conflict=1;END CATCH;
-- Conflict rolls back the entire outer test transaction: no fixture edits persist.
IF @@TRANCOUNT>0 ROLLBACK;
IF @conflict<>1 THROW 51000,'Stale overwrite was accepted',1;
IF EXISTS(SELECT 1 FROM dbo.SceneNotes WHERE SceneID=@s) OR EXISTS(SELECT 1 FROM dbo.SceneWorkflow WHERE SceneID=@s) OR EXISTS(SELECT 1 FROM dbo.ChapterGoals WHERE ChapterID=@c) THROW 51000,'Transactional fixture leaked',1;
DECLARE @denied bit=0;
BEGIN TRY DELETE @r;INSERT @r EXEC dbo.WriterAuthoring_Sections -1,@b,@c,@s;END TRY BEGIN CATCH IF ERROR_NUMBER()<>51000 THROW;SET @denied=1;END CATCH;
IF @denied<>1 THROW 51000,'Unauthorised read was accepted',1;
SET @denied=0;BEGIN TRY DELETE @r;INSERT @r EXEC dbo.WriterAuthoring_Sections @u,@b,@c,2147483647;END TRY BEGIN CATCH IF ERROR_NUMBER()<>51000 THROW;SET @denied=1;END CATCH;
IF @denied<>1 THROW 51000,'Cross-scope scene was accepted',1;
SELECT N'PASS transactional inline authoring: pure reads, scoped writes, long Unicode, canonical stores, no default checklist, independent status, stale rejection, rollback and access boundaries' Result;
-- A repeated create uses the original collection fingerprint and must not create a duplicate.
DELETE @r;INSERT @r EXEC dbo.WriterAuthoring_Sections @u,@b,@c,@s;SELECT @v=Version FROM @r WHERE Kind='AddNote';
BEGIN TRANSACTION;
SET @json=N'{"SceneNoteTypeID":"'+CONVERT(nvarchar(20),@t)+N'","NoteText":"One explicit note"}';
EXEC dbo.WriterAuthoring_Save @u,@b,@c,@s,'AddNote',0,@v,@json;
SET @conflict=0;BEGIN TRY EXEC dbo.WriterAuthoring_Save @u,@b,@c,@s,'AddNote',0,@v,@json;END TRY BEGIN CATCH IF ERROR_NUMBER()<>51002 THROW;SET @conflict=1;END CATCH;
IF @@TRANCOUNT>0 ROLLBACK;
IF @conflict<>1 OR EXISTS(SELECT 1 FROM dbo.SceneNotes WHERE SceneID=@s) THROW 51000,'Duplicate-create guard failed or leaked fixture',1;
SELECT N'PASS repeated create rejects stale collection token and rolls back cleanly' Result;

View File

@ -100,7 +100,7 @@ internal static class ToolbarBrowserHost
model.Book = new(){BookID=book,ProjectID=7,BookTitle=book==12?"A Distant Shore":"The Return",ChapterCount=book==12?2:0,SceneCount=book==12?2:0,CurrentWordCount=book==12?12400:0};
if(book==12){
model.ObjectiveChoices=[new(){ChapterID=21,ChapterTitle="The crossing",SceneID=31,SceneTitle="Arrival"},new(){ChapterID=22,ChapterTitle="The harbour",SceneID=32,SceneTitle="Departure"}];
if(context.Request.Query["objective"]=="true")model.Objective=new(){BookID=12,ChapterID=21,SceneID=31,Activity="Revising",ChapterTitle="The crossing",SceneTitle="Arrival"};
if(context.Request.Query["objective"]=="true")model.Objective=new(){BookID=12,ChapterID=21,SceneID=context.Request.Query["chapterOnly"]=="true"?null:31,Activity="Revising",ChapterTitle="The crossing",SceneTitle="Arrival"};
if(context.Request.Query["populated"]=="true")model.Activity=new(){BookID=12,Totals=new(){Added=120,Removed=30,HasAcceptedEvidence=true,RecordedEvents=2}};
}else model.WriteNext=[];
return model;
@ -149,7 +149,8 @@ internal static class ToolbarBrowserHost
"GetAsync" => Task.FromResult<Book?>((int)args![0]! is 12 or 13 ? new(){BookID=(int)args[0]!,ProjectID=7,BookTitle=(int)args[0]! == 12?"A Distant Shore":"The Return"} : null),
_ => throw new NotSupportedException(name)
}));
builder.Services.AddSingleton(FixtureProxy<IProjectAccessService>((name,args)=>Task.FromResult(name=="CanAccessProjectAsync"?(int)args![0]! == 7:(int)args![1]! is 12 or 13)));
builder.Services.AddSingleton(FixtureProxy<IProjectAccessService>((name,args)=>Task.FromResult(name=="CanAccessProjectAsync"?(int)args![0]! == 7:(int)args![1]! is 12 or 13 or 21 or 22 or 31 or 32)));
builder.Services.AddSingleton<PlotLine.Services.Writer.IWriterAuthoringService, WriterAuthoringFixture>();
builder.Services.AddScoped<IWriterWorkspaceService>(services => FixtureProxy<IWriterWorkspaceService>((name, args) => name switch {
"GetDashboardAsync" => Task.FromResult(Writer3Fixture(services.GetRequiredService<IHttpContextAccessor>().HttpContext!)),
"GetChapterWorkflowAsync" => Task.FromResult<ChapterWorkflowViewModel?>(new() {

View File

@ -0,0 +1,10 @@
using System.Text.Json;
using PlotLine.Models;
using PlotLine.Services.Writer;
internal sealed class WriterAuthoringFixture:IWriterAuthoringService
{
private readonly object gate=new();private readonly Dictionary<string,AuthoringSection> rows=new();private int next=100;
public WriterAuthoringFixture(){foreach(var kind in new[]{"Chapter","Goals","Scene","Workflow","AddNote","AddChecklist"}){var id=kind.StartsWith("Add")?0:kind is "Chapter" or "Goals"?21:31;rows[$"{kind}-{id}"]=new(){Kind=kind,EntityID=id,Data=kind=="Scene"?"{\"ScenePurposeNotes\":\"A recorded scene intention\",\"SceneOutcomeNotes\":\"A recorded outcome\"}":kind=="Goals"?"{\"GoalSummary\":\"A recorded chapter intention\"}":"{}",Version=Guid.NewGuid().ToString("N")};}}
public Task<WriterAuthoringPage> Read(int actor,int book,int chapter,int? scene){lock(gate){if(book!=12||chapter!=21||scene is not(null or 31))throw new KeyNotFoundException();return Task.FromResult(new WriterAuthoringPage{BookID=12,ChapterID=21,SceneID=scene,Chapter=new(){BookID=12,ChapterID=21,ChapterTitle="The crossing",RevisionStatusName="Outlined"},Scene=scene.HasValue?new(){BookID=12,ChapterID=21,SceneID=31,SceneTitle="Arrival",RevisionStatusName="Outlined",PrimaryLocationName="Recorded harbour"}:null,Scenes=[new(){SceneID=31,ChapterID=21,BookID=12,SceneTitle="Arrival",RevisionStatusName="Outlined"}],Characters=scene.HasValue?[new(){CharacterName="Fixture character"}]:[],Sections=rows.Values.Where(s=>scene.HasValue||s.Kind is "Chapter" or "Goals").Select(s=>new AuthoringSection{BookID=12,ChapterID=21,SceneID=scene,Kind=s.Kind,EntityID=s.EntityID,Data=s.Data,Version=s.Version,Purposes=[("1","Introduce a change")],NoteTypes=[("1","Drafting note")]}).ToArray()});}}
public Task Save(int actor,int book,int chapter,int? scene,string kind,int entity,string version,IReadOnlyDictionary<string,string?> values){lock(gate){if(book!=12||chapter!=21||scene is not(null or 31))throw new KeyNotFoundException();var error=AuthoringSchema.Validate(kind,values);if(error!=null)throw new ArgumentException(error);var key=$"{kind}-{entity}";if(!rows.TryGetValue(key,out var row))throw new KeyNotFoundException();if(row.Version!=version)throw new AuthoringConflictException("Recorded information changed; your text is retained.");if(kind.StartsWith("Add")){var k=kind=="AddNote"?"Note":"Checklist";var id=next++;rows[$"{k}-{id}"]=new(){Kind=k,EntityID=id,Data=JsonSerializer.Serialize(values),Version=Guid.NewGuid().ToString("N")};row.Version=Guid.NewGuid().ToString("N");}else{row.Data=JsonSerializer.Serialize(values);row.Version=Guid.NewGuid().ToString("N");}return Task.CompletedTask;}}
}

View File

@ -0,0 +1,16 @@
using PlotLine.Models;
internal static class WriterAuthoringTests
{
public static void Run(){void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS Writer authoring "+name);}
Check(AuthoringSchema.Validate("Note",new Dictionary<string,string?>{{"SceneNoteTypeID","1"},{"NoteText",""}})!=null,"blank notes are rejected");
Check(AuthoringSchema.Validate("Checklist",new Dictionary<string,string?>{{"ItemText",new string('x',301)}})!=null,"reminder length is bounded");
Check(AuthoringSchema.Validate("Workflow",new Dictionary<string,string?>{{"Priority","11"}})!=null,"priority range is enforced");
Check(AuthoringSchema.Validate("Workflow",new Dictionary<string,string?>{{"DraftedDate","2026-02-30"}})!=null,"invalid calendar dates are rejected");
Check(AuthoringSchema.Validate("Workflow",new Dictionary<string,string?>{{"EstimatedWordCount","-2"}})!=null,"negative counts are rejected");
Check(AuthoringSchema.Validate("Scene",new Dictionary<string,string?>{{"ScenePurposeNotes","<script>untrusted</script> — Unicode"}})==null,"ordinary author text remains text, not generated markup");
Check(AuthoringSchema.Validate("Goals",new Dictionary<string,string?>())==null,"chapter intentions remain optional");
Check(new AuthoringSection{Kind="Goals",Data="[]"}.Value("GoalSummary")=="","missing optional records render as empty values");
Check(AuthoringSchema.Validate("Scene",new Dictionary<string,string?>{{"ScenePurposeNotes",new string('界',25000)}})==null,"canonical unbounded supporting text is not arbitrarily truncated");
Check(AuthoringSchema.Validate("Unknown",new Dictionary<string,string?>())!=null,"unknown editor types are rejected");
}
}

View File

@ -0,0 +1,22 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Models;
using PlotLine.Services.Writer;
namespace PlotLine.Controllers;
[Authorize]
public sealed class WriterAuthoringController(IWriterAuthoringService authoring):Controller
{
private int Actor=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet] public async Task<IActionResult> Inspect(int bookId,int chapterId,int? sceneId){Response.Headers.CacheControl="no-store";try{return PartialView("~/Views/Writer/_WriterAuthoring.cshtml",await authoring.Read(Actor,bookId,chapterId,sceneId));}catch(SqlException e)when(e.Number==51000){return NotFound();}catch(KeyNotFoundException){return NotFound();}}
[HttpPost,ValidateAntiForgeryToken]
public async Task<IActionResult> Save(int bookId,int chapterId,int? sceneId,string kind,int entityId,string version){
var values=AuthoringSchema.Fields(kind).ToDictionary(f=>f.Name,f=>(string?)Request.Form[f.Name].ToString());
try{await authoring.Save(Actor,bookId,chapterId,sceneId,kind,entityId,version,values);return Json(new{success=true});}
catch(AuthoringConflictException e){return Conflict(new{message=e.Message});}
catch(KeyNotFoundException){return NotFound();}
catch(ArgumentException e){return BadRequest(new{message=e.Message});}
catch(SqlException e)when(e.Number is 51000 or 51002 or 51003){return StatusCode(e.Number==51000?404:e.Number==51002?409:400,new{message=e.Message});}
}
}

View File

@ -0,0 +1,38 @@
---
title: Write Intentions and Reminders
category: Workspace
tags: writer, chapter, scene, intentions, notes, checklist, workflow
contextKey: writer3.authoring
micro: Develop your saved chapter or scene without leaving Write; manuscript prose stays in Word.
quickTitle: Intentions and reminders
quickSummary: Edit recorded intentions, notes or reminders, then Save or Cancel. Each section saves independently; opening Write creates no supporting records.
screenshot:
---
# Begin with your working focus
Choose and save an activity, chapter and optional scene through Current Work. A saved chapter opens its existing goals and summary; a saved scene opens its purpose and intended outcome. Whole-manuscript focus remains valid without metadata. Work on this scene explicitly changes your saved focus; it does not move Word or retarget an active session.
# Natural inline editing
Use Edit to record what you want a chapter to accomplish, what needs to happen in a scene, and what should change by its end. Chapter summary and additional intentions are available in the details section. Everything is optional. Nothing is generated or saved to fill an empty panel. Manuscript prose belongs in Word.
Save updates only that section in its canonical record. Cancel restores its recorded values without saving. Saving one editor does not replace text in other open editors. A failed save keeps your text. If someone changed the same fields, the stale save is rejected; copy anything you need before choosing Reload recorded version. Closing a details section cannot hide dirty edits. Navigation and book changes ask before leaving unsaved text; keep the page open if a save is still pending.
# Notes and reminders
Scene notes stay with their scene and retain their note type, pin and resolved flags. Reminders use the existing scene checklist; Done does not change scene revision state or complete a work session. Add note and Add something to remember create records only when explicitly saved. Existing notes can be edited or marked resolved; deleting notes and managing complex dependencies remain in the full scene editor.
At chapter level, Things to include or remember and Concerns to revisit are existing chapter-goal fields. They do not create a separate chapter notebook. Session return notes remain attached to their recorded session.
# Working details and attachments
Priority, estimates, recorded working counts, dates and blockers use the existing scene-workflow record. Opening the panel does not seed workflow or default checklist items. Saving it explicitly creates or updates only the requested workflow record. These counts remain separate from accepted manuscript statistics. The canonical scene revision state and legacy readiness flags are preserved.
Purpose categories, revision state, file upload/deletion and other dependent story information remain in the labelled full chapter/scene editors. Attachments listed here are existing records; Write does not bypass storage permissions or upload validation.
# Companion and other selections
The companion shows saved scene appearances, setting, thread events, verified relationship events and chapter feeling intention when available. Missing records are stated plainly; these are not inferred facts or new manuscript analysis. Open the existing specialist editor or standalone Context/Intent for full references, recorded metrics, display placement and pinned/Word-follow behavior.
Working focus, active session, exploration, pinned reference, Reader and verified Word position remain independent. Inline saves do not navigate Word, synchronise manuscript text, change Reader selection or rebind recordings. Active session controls remain above the authoring sections. Both panels scroll independently; use existing resize, collapse and narrow-overlay controls.

View File

@ -34,3 +34,9 @@ Choose what you are doing, a chapter (or whole manuscript) and optionally a scen
Drafting records as Writing; Revising/Editing as Editing; Researching as Planning. For Proofreading, explicitly choose Editing or Reading review before recording. Planning, Reading review and Audio Review are session-only activities and cannot be saved as objectives. Audio Review requires a chapter and still uses the existing Windows media support and explicit playback controls.
A saved focus is shown on return; use Change working focus to edit it. During an active recording, the actual session activity/chapter and existing timing, note, end and audio controls remain available. No redundant Start form is shown. If the saved focus and session differ, the page says so. Saving/changing focus does not move or rebind the session, Reader or verified Word context. Existing independent recording entry points remain available on the retained Writing desk and Reader.
# Develop your chapter or scene here
With a saved chapter/scene focus, Write now shows existing intentions and optional inline editors for chapter purpose/summary/goals, scene purpose/outcome, scene notes, reminders and working details. Save and Cancel affect one section at a time. Failed or stale saves retain text, and navigation warns about unsaved inline edits. Opening Write does not initialise missing goals, workflow or checklists. Whole-manuscript focus remains supported.
The companion shows concise saved references rather than inferred story facts. Full specialist tools, attachments management and standalone Context/Intent remain available. The Intentions and Reminders Help icon explains field scope, stale-update handling and the distinction between scene notes, chapter goals and session return notes.

View File

@ -0,0 +1,34 @@
using System.Globalization;
using System.Text.Json;
namespace PlotLine.Models;
public sealed record AuthoringField(string Name,string Label,string Type="text",bool Required=false,int Max=int.MaxValue);
public sealed class AuthoringSection
{
public string Kind {get;set;}=""; public int EntityID {get;set;} public string Data {get;set;}="{}";public string Version {get;set;}="";
public int BookID {get;set;} public int ChapterID {get;set;} public int? SceneID {get;set;}
public IReadOnlyList<(string Value,string Label)> Purposes {get;set;}=[]; public IReadOnlyList<(string Value,string Label)> NoteTypes {get;set;}=[];
public IReadOnlyList<AuthoringField> Fields=>AuthoringSchema.Fields(Kind);
public string Title=>Kind switch{"Chapter"=>"Chapter purpose and summary","Goals"=>"What should this chapter accomplish?","Scene"=>"What needs to happen in this scene?","Workflow"=>"Working details and blockers","Note"=>"Scene note","AddNote"=>"Add a scene note","Checklist"=>"Reminder","AddChecklist"=>"Add something to remember",_=>Kind};
public string Value(string key){if(Kind.StartsWith("Add",StringComparison.Ordinal))return key=="SceneNoteTypeID"?NoteTypes.FirstOrDefault().Value??"":"";using var json=JsonDocument.Parse(Data);if(json.RootElement.ValueKind!=JsonValueKind.Object||!json.RootElement.TryGetProperty(key,out var v)||v.ValueKind==JsonValueKind.Null)return "";return v.ValueKind==JsonValueKind.True?"true":v.ValueKind==JsonValueKind.False?"false":v.ToString();}
public string Key=>$"{Kind}-{EntityID}";
}
public static class AuthoringSchema
{
public static IReadOnlyList<AuthoringField> Fields(string kind)=>kind switch{
"Chapter"=>[new("ChapterPurposeID","Optional chapter purpose","purpose"),new("Summary","Chapter summary","textarea")],
"Goals"=>[new("GoalSummary","What would you like this chapter to accomplish?","textarea"),new("EmotionalGoal","How should the reader feel?","textarea"),new("ReaderTakeaway","What should the reader take away?","textarea"),new("MustInclude","Things to include or remember","textarea"),new("RisksOrConcerns","Concerns to revisit","textarea")],
"Scene"=>[new("ScenePurposeNotes","What needs to happen in this scene?","textarea"),new("SceneOutcomeNotes","What should change by the end?","textarea")],
"Note" or "AddNote"=>[new("SceneNoteTypeID","Note type","noteType",true),new("NoteTitle","Optional title","text",false,200),new("NoteText","What do you need to remember?","textarea",true),new("IsPinned","Keep prominent","checkbox"),new("IsResolved","Resolved","checkbox"),new("SortOrder","Optional order","number")],
"Checklist" or "AddChecklist"=>[new("ItemText","Something to remember","text",true,300),new("IsCompleted","Done","checkbox"),new("SortOrder","Optional order","number")],
"Workflow"=>[new("Priority","Priority (1 to 10)","number"),new("EstimatedWordCount","Estimated words","number"),new("ActualWordCount","Recorded working word count","number"),new("DraftedDate","Drafted on","date"),new("LastWorkedOn","Last worked on","date"),new("IsBlocked","Something is blocking this scene","checkbox"),new("BlockedReason","What is in the way?","textarea")],_=>[]};
public static string? Validate(string kind,IReadOnlyDictionary<string,string?> values){var fields=Fields(kind);if(fields.Count==0)return "This editor is unavailable.";foreach(var f in fields){var v=values.GetValueOrDefault(f.Name)??"";if(f.Required&&string.IsNullOrWhiteSpace(v))return $"Enter {f.Label.ToLowerInvariant()}.";if(v.Length>f.Max)return $"{f.Label} allows up to {f.Max} characters.";if(v.Length>0&&f.Type is "number" or "purpose" or "noteType"&&!int.TryParse(v,NumberStyles.Integer,CultureInfo.InvariantCulture,out _))return $"Choose a valid value for {f.Label.ToLowerInvariant()}.";if(v.Length>0&&f.Type=="date"&&!DateOnly.TryParseExact(v,"yyyy-MM-dd",CultureInfo.InvariantCulture,DateTimeStyles.None,out _))return "Use a valid calendar date.";if(v.Length>0&&f.Type=="checkbox"&&v is not("true" or "false"))return "Choose a valid checkbox value.";}
if(kind=="Workflow"){foreach(var name in new[]{"EstimatedWordCount","ActualWordCount"})if(int.TryParse(values.GetValueOrDefault(name),out var n)&&n<0)return "Word counts must be non-negative.";if(int.TryParse(values.GetValueOrDefault("Priority"),out var priority)&&(priority<1||priority>10))return "Priority must be 1 to 10.";}return null;}
}
public sealed class WriterAuthoringPage
{
public int BookID {get;set;} public int ChapterID {get;set;} public int? SceneID {get;set;}
public Chapter Chapter {get;set;}=new();public Scene? Scene {get;set;}
public IReadOnlyList<Scene> Scenes {get;set;}=[];public IReadOnlyList<AuthoringSection> Sections {get;set;}=[];
public IReadOnlyList<SceneCharacter> Characters {get;set;}=[];public IReadOnlyList<ThreadEvent> Threads {get;set;}=[];public IReadOnlyList<RelationshipEvent> Relationships {get;set;}=[];
public IReadOnlyList<SceneAttachment> Attachments {get;set;}=[];
}

View File

@ -199,6 +199,7 @@ public class Program
builder.Services.AddScoped<IImportRepository, ImportRepository>();
builder.Services.AddScoped<IWordCompanionRepository, WordCompanionRepository>();
builder.Services.AddScoped<WritingActivityRepository>();
builder.Services.AddScoped<PlotLine.Services.Writer.IWriterAuthoringService, PlotLine.Services.Writer.WriterAuthoringService>();
builder.Services.AddScoped<WriterObjectiveRepository>();
builder.Services.AddScoped<WriterWorkRepository>();
builder.Services.AddScoped<WriterPlanningRepository>();

View File

@ -85,6 +85,7 @@ public sealed class ProjectAccessFilter(IProjectAccessService access, ICurrentUs
["Scenarios"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "Scenario", ["scenarioId"] = "Scenario", ["projectId"] = "Project", ["bookId"] = "Book", ["sceneId"] = "Scene", ["anchorSceneId"] = "Scene", ["targetChapterId"] = "Chapter" },
["StoryAssets"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "StoryAsset", ["returnAssetId"] = "StoryAsset", ["projectId"] = "Project" },
["Timeline"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "TimelineViewPreset", ["projectId"] = "Project", ["bookId"] = "Book" },
["WriterAuthoring"] = new(StringComparer.OrdinalIgnoreCase) { ["bookId"] = "Book", ["chapterId"] = "Chapter", ["sceneId"] = "Scene" },
["Writer"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "Chapter", ["projectId"] = "Project" },
["Warnings"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "ContinuityWarning", ["projectId"] = "Project", ["bookId"] = "Book", ["sceneId"] = "Scene" },
["Analytics"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project", ["bookId"] = "Book" },

View File

@ -0,0 +1,30 @@
using System.Data;
using Microsoft.Data.SqlClient;
using System.Text.Json;
using Dapper;
using PlotLine.Data;
using PlotLine.Models;
namespace PlotLine.Services.Writer;
public sealed class AuthoringConflictException(string message,Exception? inner=null):Exception(message,inner);
public interface IWriterAuthoringService
{
Task<WriterAuthoringPage> Read(int actor,int book,int chapter,int? scene);
Task Save(int actor,int book,int chapter,int? scene,string kind,int entity,string version,IReadOnlyDictionary<string,string?> values);
}
public sealed class WriterAuthoringService(ISqlConnectionFactory factory,IChapterRepository chapters,ISceneRepository scenes,ILookupRepository lookups,IWriterWorkspaceRepository workspace,ICharacterRepository characters,IPlotRepository plots,IBookRepository books,ILocationRepository locations,IProjectActivityService activity):IWriterAuthoringService
{
public async Task<WriterAuthoringPage> Read(int actor,int book,int chapter,int? scene){
using var db=factory.CreateConnection();var sections=(await db.QueryAsync<AuthoringSection>("dbo.WriterAuthoring_Sections",new{UserID=actor,BookID=book,ChapterID=chapter,SceneID=scene},commandType:CommandType.StoredProcedure)).ToArray();
var lookup=await lookups.GetAllAsync();var noteTypes=await workspace.ListNoteTypesAsync();
foreach(var s in sections){s.BookID=book;s.ChapterID=chapter;s.SceneID=scene;s.Purposes=lookup.ChapterPurposeTypes.Where(x=>!x.IsArchived).Select(x=>(x.ChapterPurposeID.ToString(),x.PurposeName)).ToArray();s.NoteTypes=noteTypes.Where(x=>x.IsActive).Select(x=>(x.SceneNoteTypeID.ToString(),x.TypeName)).ToArray();}
var page=new WriterAuthoringPage{BookID=book,ChapterID=chapter,SceneID=scene,Chapter=await chapters.GetAsync(chapter)??throw new KeyNotFoundException(),Scenes=await scenes.ListByChapterAsync(chapter),Sections=sections};
if(scene.HasValue){page.Scene=page.Scenes.FirstOrDefault(x=>x.SceneID==scene.Value);if(page.Scene==null)throw new KeyNotFoundException();page.Scene.BookID=book;if(page.Scene.PrimaryLocationID.HasValue){var place=await locations.GetAsync(page.Scene.PrimaryLocationID.Value);var selectedBook=await books.GetAsync(book);if(place!=null&&!place.IsArchived&&place.ProjectID==selectedBook?.ProjectID)page.Scene.PrimaryLocationName=place.LocationName;}page.Characters=await characters.ListSceneCharactersAsync(scene.Value);page.Threads=await plots.ListThreadEventsBySceneAsync(scene.Value);page.Relationships=(await characters.ListRelationshipEventsBySceneAsync(scene.Value)).Where(x=>x.EvidenceState=="Verified").ToArray();page.Attachments=await workspace.ListAttachmentsAsync(scene.Value);}
return page;
}
public async Task Save(int actor,int book,int chapter,int? scene,string kind,int entity,string version,IReadOnlyDictionary<string,string?> values){
var error=AuthoringSchema.Validate(kind,values);if(error!=null)throw new ArgumentException(error);
var payload=AuthoringSchema.Fields(kind).ToDictionary(f=>f.Name,f=>values.GetValueOrDefault(f.Name));
using var db=factory.CreateConnection();try{await db.ExecuteAsync("dbo.WriterAuthoring_Save",new{UserID=actor,BookID=book,ChapterID=chapter,SceneID=scene,Kind=kind,EntityID=entity,Version=version,Data=JsonSerializer.Serialize(payload)},commandType:CommandType.StoredProcedure);}catch(SqlException e)when(e.Number==51002){throw new AuthoringConflictException(e.Message,e);}
if(kind is "Chapter" or "Scene"){var selectedBook=await books.GetAsync(book);var title=kind=="Chapter"?(await chapters.GetAsync(chapter))?.ChapterTitle:(await scenes.ListByChapterAsync(chapter)).FirstOrDefault(x=>x.SceneID==scene)?.SceneTitle;if(selectedBook!=null&&title!=null)await activity.RecordAsync(selectedBook.ProjectID,"Updated",kind,entity,title);}
}
}

View File

@ -0,0 +1,76 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
-- No new tables. Inspection never invokes legacy getters that seed goals/workflow/checklists.
CREATE OR ALTER PROCEDURE dbo.WriterAuthoring_Sections
@UserID int,@BookID int,@ChapterID int,@SceneID int=NULL
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID
JOIN dbo.Chapters c ON c.BookID=b.BookID WHERE b.BookID=@BookID AND c.ChapterID=@ChapterID AND b.IsArchived=0 AND c.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1)
THROW 51000,'Working selection unavailable',1;
IF @SceneID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Scenes WHERE SceneID=@SceneID AND ChapterID=@ChapterID AND IsArchived=0) THROW 51000,'Scene unavailable in this chapter',1;
DECLARE @r table(Kind varchar(20),EntityID int,Data nvarchar(max));
INSERT @r SELECT 'Chapter',@ChapterID,(SELECT Summary,ChapterPurposeID,UpdatedDate FROM dbo.Chapters WITH(UPDLOCK,HOLDLOCK) WHERE ChapterID=@ChapterID FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER);
INSERT @r SELECT 'Goals',@ChapterID,(SELECT g.GoalSummary,g.EmotionalGoal,g.ReaderTakeaway,g.MustInclude,g.RisksOrConcerns,g.UpdatedDate FROM (SELECT @ChapterID ID) c LEFT JOIN dbo.ChapterGoals g WITH(UPDLOCK,HOLDLOCK) ON g.ChapterID=c.ID FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER);
IF @SceneID IS NOT NULL BEGIN
INSERT @r SELECT 'Scene',@SceneID,(SELECT ScenePurposeNotes,SceneOutcomeNotes,UpdatedDate FROM dbo.Scenes WITH(UPDLOCK,HOLDLOCK) WHERE SceneID=@SceneID FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER);
INSERT @r SELECT 'Workflow',@SceneID,(SELECT w.Priority,w.EstimatedWordCount,w.ActualWordCount,w.DraftedDate,w.LastWorkedOn,w.IsBlocked,w.BlockedReason,w.UpdatedDate FROM(SELECT @SceneID ID)c LEFT JOIN dbo.SceneWorkflow w WITH(UPDLOCK,HOLDLOCK) ON w.SceneID=c.ID FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER);
INSERT @r SELECT 'Note',n.SceneNoteID,(SELECT n.SceneNoteTypeID,n.NoteTitle,n.NoteText,n.SortOrder,n.IsPinned,n.IsResolved,n.UpdatedDate FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER) FROM dbo.SceneNotes n WITH(UPDLOCK,HOLDLOCK) WHERE n.SceneID=@SceneID;
INSERT @r SELECT 'Checklist',n.SceneChecklistItemID,(SELECT n.ItemText,n.IsCompleted,n.SortOrder,n.UpdatedDate FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER) FROM dbo.SceneChecklistItems n WITH(UPDLOCK,HOLDLOCK) WHERE n.SceneID=@SceneID;
-- Collection fingerprints make a repeated create with its old token conflict instead of duplicating a row.
INSERT @r SELECT 'AddNote',0,(SELECT * FROM dbo.SceneNotes WITH(UPDLOCK,HOLDLOCK) WHERE SceneID=@SceneID ORDER BY SceneNoteID FOR JSON PATH,INCLUDE_NULL_VALUES);
INSERT @r SELECT 'AddChecklist',0,(SELECT * FROM dbo.SceneChecklistItems WITH(UPDLOCK,HOLDLOCK) WHERE SceneID=@SceneID ORDER BY SceneChecklistItemID FOR JSON PATH,INCLUDE_NULL_VALUES);
END;
SELECT Kind,EntityID,Data,CONVERT(varchar(64),HASHBYTES('SHA2_256',Data),2) Version FROM @r;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterAuthoring_Save
@UserID int,@BookID int,@ChapterID int,@SceneID int=NULL,@Kind varchar(20),@EntityID int,@Version varchar(64),@Data nvarchar(max)
AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
IF ISJSON(@Data)<>1 THROW 51003,'Invalid form data',1;
BEGIN TRY
BEGIN TRANSACTION;
DECLARE @r table(Kind varchar(20),EntityID int,Data nvarchar(max),Version varchar(64));
INSERT @r EXEC dbo.WriterAuthoring_Sections @UserID,@BookID,@ChapterID,@SceneID;
IF NOT EXISTS(SELECT 1 FROM @r WHERE Kind=@Kind AND EntityID=@EntityID) THROW 51000,'Editor unavailable in this selection',1;
IF NOT EXISTS(SELECT 1 FROM @r WHERE Kind=@Kind AND EntityID=@EntityID AND Version=ISNULL(@Version,'')) THROW 51002,'This information changed. Your text is retained; reload the editor to compare before saving again.',1;
IF EXISTS(SELECT 1 FROM OPENJSON(@Data) WHERE LEN(CONVERT(nvarchar(max),value))>20000) THROW 51003,'Keep each text field within 20000 characters',1;
DECLARE @summary nvarchar(max)=JSON_VALUE(@Data,'$.Summary'),@purpose int=TRY_CONVERT(int,JSON_VALUE(@Data,'$.ChapterPurposeID')),
@goal nvarchar(max),@emotion nvarchar(max),@takeaway nvarchar(max),@include nvarchar(max),@risk nvarchar(max),
@noteType int=TRY_CONVERT(int,JSON_VALUE(@Data,'$.SceneNoteTypeID')),@title nvarchar(200)=JSON_VALUE(@Data,'$.NoteTitle'),@text nvarchar(max)=JSON_VALUE(@Data,'$.NoteText'),
@sort int=TRY_CONVERT(int,JSON_VALUE(@Data,'$.SortOrder')),@pinned bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsPinned')),0),@resolved bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsResolved')),0),
@item nvarchar(300)=JSON_VALUE(@Data,'$.ItemText'),@done bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsCompleted')),0);
-- OPENJSON WITH nvarchar(max) avoids JSON_VALUE's 4000-character limit on author prose.
SELECT @summary=Summary,@goal=GoalSummary,@emotion=EmotionalGoal,@takeaway=ReaderTakeaway,@include=MustInclude,@risk=RisksOrConcerns,@text=NoteText FROM OPENJSON(@Data) WITH(Summary nvarchar(max),GoalSummary nvarchar(max),EmotionalGoal nvarchar(max),ReaderTakeaway nvarchar(max),MustInclude nvarchar(max),RisksOrConcerns nvarchar(max),NoteText nvarchar(max));
IF @Kind='Chapter' BEGIN
IF @purpose IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.ChapterPurposeTypes WHERE ChapterPurposeID=@purpose AND IsArchived=0) THROW 51003,'Choose an available chapter purpose',1;
UPDATE dbo.Chapters SET Summary=@summary,ChapterPurposeID=@purpose,UpdatedDate=SYSUTCDATETIME() WHERE ChapterID=@ChapterID;
END ELSE IF @Kind='Goals' EXEC dbo.ChapterGoal_Save @ChapterID,@goal,@emotion,@takeaway,@include,@risk;
ELSE IF @Kind='Scene' BEGIN
DECLARE @sp nvarchar(max),@out nvarchar(max);
SELECT @sp=ScenePurposeNotes,@out=SceneOutcomeNotes FROM OPENJSON(@Data) WITH(ScenePurposeNotes nvarchar(max),SceneOutcomeNotes nvarchar(max));
UPDATE dbo.Scenes SET ScenePurposeNotes=@sp,SceneOutcomeNotes=@out,UpdatedDate=SYSUTCDATETIME() WHERE SceneID=@SceneID;
END ELSE IF @Kind IN('Note','AddNote') BEGIN
IF LEN(ISNULL(@text,''))=0 OR NOT EXISTS(SELECT 1 FROM dbo.SceneNoteTypes WHERE SceneNoteTypeID=@noteType AND IsActive=1) THROW 51003,'Choose a note type and enter note text',1;
IF LEN(ISNULL(JSON_VALUE(@Data,'$.NoteTitle'),''))>200 THROW 51003,'Note titles may contain up to 200 characters',1;
EXEC dbo.SceneNote_Save @EntityID,@SceneID,@noteType,@title,@text,@sort,@pinned,@resolved;
END ELSE IF @Kind IN('Checklist','AddChecklist') BEGIN
IF LEN(ISNULL(JSON_VALUE(@Data,'$.ItemText'),''))=0 OR LEN(JSON_VALUE(@Data,'$.ItemText'))>300 THROW 51003,'Enter a reminder of 1 to 300 characters',1;
EXEC dbo.SceneChecklist_Save @EntityID,@SceneID,@item,@done,@sort;
END ELSE IF @Kind='Workflow' BEGIN
DECLARE @priority int=TRY_CONVERT(int,JSON_VALUE(@Data,'$.Priority')),@estimated int=TRY_CONVERT(int,JSON_VALUE(@Data,'$.EstimatedWordCount')),@actual int=TRY_CONVERT(int,JSON_VALUE(@Data,'$.ActualWordCount')),
@drafted date=TRY_CONVERT(date,JSON_VALUE(@Data,'$.DraftedDate')),@worked date=TRY_CONVERT(date,JSON_VALUE(@Data,'$.LastWorkedOn')),@blocked bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsBlocked')),0),@reason nvarchar(max),
@status nvarchar(50)='Planned',@readyDraft bit=0,@readyRevision bit=0,@readyPolish bit=0;
SELECT @reason=BlockedReason FROM OPENJSON(@Data) WITH(BlockedReason nvarchar(max));
IF @priority IS NOT NULL AND @priority NOT BETWEEN 1 AND 10 OR @estimated<0 OR @actual<0 THROW 51003,'Priority must be 1 to 10 and word estimates non-negative',1;
SELECT @status=DraftStatus,@readyDraft=ReadyForDraft,@readyRevision=ReadyForRevision,@readyPolish=ReadyForPolish FROM dbo.SceneWorkflow WHERE SceneID=@SceneID;
EXEC dbo.SceneWorkflow_Save @SceneID,@status,@estimated,@actual,@drafted,@worked,@readyDraft,@readyRevision,@readyPolish,@blocked,@reason,@priority;
END;
COMMIT;
END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH;
END;
GO

View File

@ -0,0 +1,54 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
-- Forward-only correction: SQL converts empty strings to zero/1900 dates; optional controls must stay NULL.
CREATE OR ALTER PROCEDURE dbo.WriterAuthoring_Save
@UserID int,@BookID int,@ChapterID int,@SceneID int=NULL,@Kind varchar(20),@EntityID int,@Version varchar(64),@Data nvarchar(max)
AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
IF ISJSON(@Data)<>1 THROW 51003,'Invalid form data',1;
BEGIN TRY
BEGIN TRANSACTION;
DECLARE @r table(Kind varchar(20),EntityID int,Data nvarchar(max),Version varchar(64));
INSERT @r EXEC dbo.WriterAuthoring_Sections @UserID,@BookID,@ChapterID,@SceneID;
IF NOT EXISTS(SELECT 1 FROM @r WHERE Kind=@Kind AND EntityID=@EntityID) THROW 51000,'Editor unavailable in this selection',1;
IF NOT EXISTS(SELECT 1 FROM @r WHERE Kind=@Kind AND EntityID=@EntityID AND Version=ISNULL(@Version,'')) THROW 51002,'This information changed. Your text is retained; reload the editor to compare before saving again.',1;
IF EXISTS(SELECT 1 FROM OPENJSON(@Data) WHERE LEN(CONVERT(nvarchar(max),value))>20000) THROW 51003,'Keep each text field within 20000 characters',1;
DECLARE @summary nvarchar(max)=JSON_VALUE(@Data,'$.Summary'),@purpose int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.ChapterPurposeID'),'')),
@goal nvarchar(max),@emotion nvarchar(max),@takeaway nvarchar(max),@include nvarchar(max),@risk nvarchar(max),
@noteType int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.SceneNoteTypeID'),'')),@title nvarchar(200)=JSON_VALUE(@Data,'$.NoteTitle'),@text nvarchar(max)=JSON_VALUE(@Data,'$.NoteText'),
@sort int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.SortOrder'),'')),@pinned bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsPinned')),0),@resolved bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsResolved')),0),
@item nvarchar(300)=JSON_VALUE(@Data,'$.ItemText'),@done bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsCompleted')),0);
-- OPENJSON WITH nvarchar(max) avoids JSON_VALUE's 4000-character limit on author prose.
SELECT @summary=Summary,@goal=GoalSummary,@emotion=EmotionalGoal,@takeaway=ReaderTakeaway,@include=MustInclude,@risk=RisksOrConcerns,@text=NoteText FROM OPENJSON(@Data) WITH(Summary nvarchar(max),GoalSummary nvarchar(max),EmotionalGoal nvarchar(max),ReaderTakeaway nvarchar(max),MustInclude nvarchar(max),RisksOrConcerns nvarchar(max),NoteText nvarchar(max));
IF EXISTS(SELECT 1 FROM OPENJSON(@Data) WHERE [key] IN('Priority','EstimatedWordCount','ActualWordCount','SortOrder','ChapterPurposeID','SceneNoteTypeID') AND NULLIF(CONVERT(nvarchar(max),value),'') IS NOT NULL AND TRY_CONVERT(int,value) IS NULL) THROW 51003,'Use valid whole numbers',1;
IF EXISTS(SELECT 1 FROM OPENJSON(@Data) WHERE [key] IN('DraftedDate','LastWorkedOn') AND NULLIF(CONVERT(nvarchar(max),value),'') IS NOT NULL AND TRY_CONVERT(date,value) IS NULL) THROW 51003,'Use valid dates',1;
IF @Kind='Chapter' BEGIN
IF @purpose IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.ChapterPurposeTypes WHERE ChapterPurposeID=@purpose AND IsArchived=0) THROW 51003,'Choose an available chapter purpose',1;
UPDATE dbo.Chapters SET Summary=@summary,ChapterPurposeID=@purpose,UpdatedDate=SYSUTCDATETIME() WHERE ChapterID=@ChapterID;
END ELSE IF @Kind='Goals' EXEC dbo.ChapterGoal_Save @ChapterID,@goal,@emotion,@takeaway,@include,@risk;
ELSE IF @Kind='Scene' BEGIN
DECLARE @sp nvarchar(max),@out nvarchar(max);
SELECT @sp=ScenePurposeNotes,@out=SceneOutcomeNotes FROM OPENJSON(@Data) WITH(ScenePurposeNotes nvarchar(max),SceneOutcomeNotes nvarchar(max));
UPDATE dbo.Scenes SET ScenePurposeNotes=@sp,SceneOutcomeNotes=@out,UpdatedDate=SYSUTCDATETIME() WHERE SceneID=@SceneID;
END ELSE IF @Kind IN('Note','AddNote') BEGIN
IF LEN(ISNULL(@text,''))=0 OR NOT EXISTS(SELECT 1 FROM dbo.SceneNoteTypes WHERE SceneNoteTypeID=@noteType AND IsActive=1) THROW 51003,'Choose a note type and enter note text',1;
IF LEN(ISNULL(JSON_VALUE(@Data,'$.NoteTitle'),''))>200 THROW 51003,'Note titles may contain up to 200 characters',1;
EXEC dbo.SceneNote_Save @EntityID,@SceneID,@noteType,@title,@text,@sort,@pinned,@resolved;
END ELSE IF @Kind IN('Checklist','AddChecklist') BEGIN
IF LEN(ISNULL(JSON_VALUE(@Data,'$.ItemText'),''))=0 OR LEN(JSON_VALUE(@Data,'$.ItemText'))>300 THROW 51003,'Enter a reminder of 1 to 300 characters',1;
EXEC dbo.SceneChecklist_Save @EntityID,@SceneID,@item,@done,@sort;
END ELSE IF @Kind='Workflow' BEGIN
DECLARE @priority int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.Priority'),'')),@estimated int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.EstimatedWordCount'),'')),@actual int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.ActualWordCount'),'')),
@drafted date=TRY_CONVERT(date,NULLIF(JSON_VALUE(@Data,'$.DraftedDate'),'')),@worked date=TRY_CONVERT(date,NULLIF(JSON_VALUE(@Data,'$.LastWorkedOn'),'')),@blocked bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsBlocked')),0),@reason nvarchar(max),
@status nvarchar(50)='Planned',@readyDraft bit=0,@readyRevision bit=0,@readyPolish bit=0;
SELECT @reason=BlockedReason FROM OPENJSON(@Data) WITH(BlockedReason nvarchar(max));
IF @priority IS NOT NULL AND @priority NOT BETWEEN 1 AND 10 OR @estimated<0 OR @actual<0 THROW 51003,'Priority must be 1 to 10 and word estimates non-negative',1;
SELECT @status=DraftStatus,@readyDraft=ReadyForDraft,@readyRevision=ReadyForRevision,@readyPolish=ReadyForPolish FROM dbo.SceneWorkflow WHERE SceneID=@SceneID;
EXEC dbo.SceneWorkflow_Save @SceneID,@status,@estimated,@actual,@drafted,@worked,@readyDraft,@readyRevision,@readyPolish,@blocked,@reason,@priority;
END;
COMMIT;
END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH;
END;
GO

View File

@ -0,0 +1,54 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
-- TRY_CONVERT on nvarchar(max) over 4000 chars can fail before key predicates are applied.
CREATE OR ALTER PROCEDURE dbo.WriterAuthoring_Save
@UserID int,@BookID int,@ChapterID int,@SceneID int=NULL,@Kind varchar(20),@EntityID int,@Version varchar(64),@Data nvarchar(max)
AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
IF ISJSON(@Data)<>1 THROW 51003,'Invalid form data',1;
BEGIN TRY
BEGIN TRANSACTION;
DECLARE @r table(Kind varchar(20),EntityID int,Data nvarchar(max),Version varchar(64));
INSERT @r EXEC dbo.WriterAuthoring_Sections @UserID,@BookID,@ChapterID,@SceneID;
IF NOT EXISTS(SELECT 1 FROM @r WHERE Kind=@Kind AND EntityID=@EntityID) THROW 51000,'Editor unavailable in this selection',1;
IF NOT EXISTS(SELECT 1 FROM @r WHERE Kind=@Kind AND EntityID=@EntityID AND Version=ISNULL(@Version,'')) THROW 51002,'This information changed. Your text is retained; reload the editor to compare before saving again.',1;
IF EXISTS(SELECT 1 FROM OPENJSON(@Data) WHERE LEN(CONVERT(nvarchar(max),value))>20000) THROW 51003,'Keep each text field within 20000 characters',1;
DECLARE @summary nvarchar(max)=JSON_VALUE(@Data,'$.Summary'),@purpose int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.ChapterPurposeID'),'')),
@goal nvarchar(max),@emotion nvarchar(max),@takeaway nvarchar(max),@include nvarchar(max),@risk nvarchar(max),
@noteType int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.SceneNoteTypeID'),'')),@title nvarchar(200)=JSON_VALUE(@Data,'$.NoteTitle'),@text nvarchar(max)=JSON_VALUE(@Data,'$.NoteText'),
@sort int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.SortOrder'),'')),@pinned bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsPinned')),0),@resolved bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsResolved')),0),
@item nvarchar(300)=JSON_VALUE(@Data,'$.ItemText'),@done bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsCompleted')),0);
-- OPENJSON WITH nvarchar(max) avoids JSON_VALUE's 4000-character limit on author prose.
SELECT @summary=Summary,@goal=GoalSummary,@emotion=EmotionalGoal,@takeaway=ReaderTakeaway,@include=MustInclude,@risk=RisksOrConcerns,@text=NoteText FROM OPENJSON(@Data) WITH(Summary nvarchar(max),GoalSummary nvarchar(max),EmotionalGoal nvarchar(max),ReaderTakeaway nvarchar(max),MustInclude nvarchar(max),RisksOrConcerns nvarchar(max),NoteText nvarchar(max));
IF EXISTS(SELECT 1 FROM OPENJSON(@Data) WHERE [key] IN('Priority','EstimatedWordCount','ActualWordCount','SortOrder','ChapterPurposeID','SceneNoteTypeID') AND NULLIF(CONVERT(nvarchar(max),value),'') IS NOT NULL AND TRY_CONVERT(int,CONVERT(nvarchar(4000),value)) IS NULL) THROW 51003,'Use valid whole numbers',1;
IF EXISTS(SELECT 1 FROM OPENJSON(@Data) WHERE [key] IN('DraftedDate','LastWorkedOn') AND NULLIF(CONVERT(nvarchar(max),value),'') IS NOT NULL AND TRY_CONVERT(date,CONVERT(nvarchar(4000),value)) IS NULL) THROW 51003,'Use valid dates',1;
IF @Kind='Chapter' BEGIN
IF @purpose IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.ChapterPurposeTypes WHERE ChapterPurposeID=@purpose AND IsArchived=0) THROW 51003,'Choose an available chapter purpose',1;
UPDATE dbo.Chapters SET Summary=@summary,ChapterPurposeID=@purpose,UpdatedDate=SYSUTCDATETIME() WHERE ChapterID=@ChapterID;
END ELSE IF @Kind='Goals' EXEC dbo.ChapterGoal_Save @ChapterID,@goal,@emotion,@takeaway,@include,@risk;
ELSE IF @Kind='Scene' BEGIN
DECLARE @sp nvarchar(max),@out nvarchar(max);
SELECT @sp=ScenePurposeNotes,@out=SceneOutcomeNotes FROM OPENJSON(@Data) WITH(ScenePurposeNotes nvarchar(max),SceneOutcomeNotes nvarchar(max));
UPDATE dbo.Scenes SET ScenePurposeNotes=@sp,SceneOutcomeNotes=@out,UpdatedDate=SYSUTCDATETIME() WHERE SceneID=@SceneID;
END ELSE IF @Kind IN('Note','AddNote') BEGIN
IF LEN(ISNULL(@text,''))=0 OR NOT EXISTS(SELECT 1 FROM dbo.SceneNoteTypes WHERE SceneNoteTypeID=@noteType AND IsActive=1) THROW 51003,'Choose a note type and enter note text',1;
IF LEN(ISNULL(JSON_VALUE(@Data,'$.NoteTitle'),''))>200 THROW 51003,'Note titles may contain up to 200 characters',1;
EXEC dbo.SceneNote_Save @EntityID,@SceneID,@noteType,@title,@text,@sort,@pinned,@resolved;
END ELSE IF @Kind IN('Checklist','AddChecklist') BEGIN
IF LEN(ISNULL(JSON_VALUE(@Data,'$.ItemText'),''))=0 OR LEN(JSON_VALUE(@Data,'$.ItemText'))>300 THROW 51003,'Enter a reminder of 1 to 300 characters',1;
EXEC dbo.SceneChecklist_Save @EntityID,@SceneID,@item,@done,@sort;
END ELSE IF @Kind='Workflow' BEGIN
DECLARE @priority int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.Priority'),'')),@estimated int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.EstimatedWordCount'),'')),@actual int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.ActualWordCount'),'')),
@drafted date=TRY_CONVERT(date,NULLIF(JSON_VALUE(@Data,'$.DraftedDate'),'')),@worked date=TRY_CONVERT(date,NULLIF(JSON_VALUE(@Data,'$.LastWorkedOn'),'')),@blocked bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsBlocked')),0),@reason nvarchar(max),
@status nvarchar(50)='Planned',@readyDraft bit=0,@readyRevision bit=0,@readyPolish bit=0;
SELECT @reason=BlockedReason FROM OPENJSON(@Data) WITH(BlockedReason nvarchar(max));
IF @priority IS NOT NULL AND @priority NOT BETWEEN 1 AND 10 OR @estimated<0 OR @actual<0 THROW 51003,'Priority must be 1 to 10 and word estimates non-negative',1;
SELECT @status=DraftStatus,@readyDraft=ReadyForDraft,@readyRevision=ReadyForRevision,@readyPolish=ReadyForPolish FROM dbo.SceneWorkflow WHERE SceneID=@SceneID;
EXEC dbo.SceneWorkflow_Save @SceneID,@status,@estimated,@actual,@drafted,@worked,@readyDraft,@readyRevision,@readyPolish,@blocked,@reason,@priority;
END;
COMMIT;
END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH;
END;
GO

View File

@ -0,0 +1,28 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
-- Fingerprint only fields this editor owns. Parent/audit timestamps change on unrelated saves.
CREATE OR ALTER PROCEDURE dbo.WriterAuthoring_Sections
@UserID int,@BookID int,@ChapterID int,@SceneID int=NULL
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID
JOIN dbo.Chapters c ON c.BookID=b.BookID WHERE b.BookID=@BookID AND c.ChapterID=@ChapterID AND b.IsArchived=0 AND c.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1)
THROW 51000,'Working selection unavailable',1;
IF @SceneID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Scenes WHERE SceneID=@SceneID AND ChapterID=@ChapterID AND IsArchived=0) THROW 51000,'Scene unavailable in this chapter',1;
DECLARE @r table(Kind varchar(20),EntityID int,Data nvarchar(max));
INSERT @r SELECT 'Chapter',@ChapterID,(SELECT Summary,ChapterPurposeID FROM dbo.Chapters WITH(UPDLOCK,HOLDLOCK) WHERE ChapterID=@ChapterID FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER);
INSERT @r SELECT 'Goals',@ChapterID,(SELECT g.GoalSummary,g.EmotionalGoal,g.ReaderTakeaway,g.MustInclude,g.RisksOrConcerns FROM (SELECT @ChapterID ID) c LEFT JOIN dbo.ChapterGoals g WITH(UPDLOCK,HOLDLOCK) ON g.ChapterID=c.ID FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER);
IF @SceneID IS NOT NULL BEGIN
INSERT @r SELECT 'Scene',@SceneID,(SELECT ScenePurposeNotes,SceneOutcomeNotes FROM dbo.Scenes WITH(UPDLOCK,HOLDLOCK) WHERE SceneID=@SceneID FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER);
INSERT @r SELECT 'Workflow',@SceneID,(SELECT w.Priority,w.EstimatedWordCount,w.ActualWordCount,w.DraftedDate,w.LastWorkedOn,w.IsBlocked,w.BlockedReason FROM(SELECT @SceneID ID)c LEFT JOIN dbo.SceneWorkflow w WITH(UPDLOCK,HOLDLOCK) ON w.SceneID=c.ID FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER);
INSERT @r SELECT 'Note',n.SceneNoteID,(SELECT n.SceneNoteTypeID,n.NoteTitle,n.NoteText,n.SortOrder,n.IsPinned,n.IsResolved FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER) FROM dbo.SceneNotes n WITH(UPDLOCK,HOLDLOCK) WHERE n.SceneID=@SceneID;
INSERT @r SELECT 'Checklist',n.SceneChecklistItemID,(SELECT n.ItemText,n.IsCompleted,n.SortOrder FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER) FROM dbo.SceneChecklistItems n WITH(UPDLOCK,HOLDLOCK) WHERE n.SceneID=@SceneID;
-- Collection fingerprints make a repeated create with its old token conflict instead of duplicating a row.
INSERT @r SELECT 'AddNote',0,(SELECT * FROM dbo.SceneNotes WITH(UPDLOCK,HOLDLOCK) WHERE SceneID=@SceneID ORDER BY SceneNoteID FOR JSON PATH,INCLUDE_NULL_VALUES);
INSERT @r SELECT 'AddChecklist',0,(SELECT * FROM dbo.SceneChecklistItems WITH(UPDLOCK,HOLDLOCK) WHERE SceneID=@SceneID ORDER BY SceneChecklistItemID FOR JSON PATH,INCLUDE_NULL_VALUES);
END;
SELECT Kind,EntityID,Data,CONVERT(varchar(64),HASHBYTES('SHA2_256',Data),2) Version FROM @r;
END;
GO

View File

@ -0,0 +1,28 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
-- Empty scalar JSON collections may yield NULL; every creatable section needs a stable non-null token.
CREATE OR ALTER PROCEDURE dbo.WriterAuthoring_Sections
@UserID int,@BookID int,@ChapterID int,@SceneID int=NULL
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID
JOIN dbo.Chapters c ON c.BookID=b.BookID WHERE b.BookID=@BookID AND c.ChapterID=@ChapterID AND b.IsArchived=0 AND c.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1)
THROW 51000,'Working selection unavailable',1;
IF @SceneID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Scenes WHERE SceneID=@SceneID AND ChapterID=@ChapterID AND IsArchived=0) THROW 51000,'Scene unavailable in this chapter',1;
DECLARE @r table(Kind varchar(20),EntityID int,Data nvarchar(max));
INSERT @r SELECT 'Chapter',@ChapterID,(SELECT Summary,ChapterPurposeID FROM dbo.Chapters WITH(UPDLOCK,HOLDLOCK) WHERE ChapterID=@ChapterID FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER);
INSERT @r SELECT 'Goals',@ChapterID,(SELECT g.GoalSummary,g.EmotionalGoal,g.ReaderTakeaway,g.MustInclude,g.RisksOrConcerns FROM (SELECT @ChapterID ID) c LEFT JOIN dbo.ChapterGoals g WITH(UPDLOCK,HOLDLOCK) ON g.ChapterID=c.ID FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER);
IF @SceneID IS NOT NULL BEGIN
INSERT @r SELECT 'Scene',@SceneID,(SELECT ScenePurposeNotes,SceneOutcomeNotes FROM dbo.Scenes WITH(UPDLOCK,HOLDLOCK) WHERE SceneID=@SceneID FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER);
INSERT @r SELECT 'Workflow',@SceneID,(SELECT w.Priority,w.EstimatedWordCount,w.ActualWordCount,w.DraftedDate,w.LastWorkedOn,w.IsBlocked,w.BlockedReason FROM(SELECT @SceneID ID)c LEFT JOIN dbo.SceneWorkflow w WITH(UPDLOCK,HOLDLOCK) ON w.SceneID=c.ID FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER);
INSERT @r SELECT 'Note',n.SceneNoteID,(SELECT n.SceneNoteTypeID,n.NoteTitle,n.NoteText,n.SortOrder,n.IsPinned,n.IsResolved FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER) FROM dbo.SceneNotes n WITH(UPDLOCK,HOLDLOCK) WHERE n.SceneID=@SceneID;
INSERT @r SELECT 'Checklist',n.SceneChecklistItemID,(SELECT n.ItemText,n.IsCompleted,n.SortOrder FOR JSON PATH,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER) FROM dbo.SceneChecklistItems n WITH(UPDLOCK,HOLDLOCK) WHERE n.SceneID=@SceneID;
-- Collection fingerprints make a repeated create with its old token conflict instead of duplicating a row.
INSERT @r SELECT 'AddNote',0,(SELECT * FROM dbo.SceneNotes WITH(UPDLOCK,HOLDLOCK) WHERE SceneID=@SceneID ORDER BY SceneNoteID FOR JSON PATH,INCLUDE_NULL_VALUES);
INSERT @r SELECT 'AddChecklist',0,(SELECT * FROM dbo.SceneChecklistItems WITH(UPDLOCK,HOLDLOCK) WHERE SceneID=@SceneID ORDER BY SceneChecklistItemID FOR JSON PATH,INCLUDE_NULL_VALUES);
END;
SELECT Kind,EntityID,ISNULL(Data,N'[]') Data,CONVERT(varchar(64),HASHBYTES('SHA2_256',ISNULL(Data,N'[]')),2) Version FROM @r;
END;
GO

View File

@ -0,0 +1,53 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
-- Match canonical nvarchar(max) fields; retain existing bounded title/reminder and HTTP form limits.
CREATE OR ALTER PROCEDURE dbo.WriterAuthoring_Save
@UserID int,@BookID int,@ChapterID int,@SceneID int=NULL,@Kind varchar(20),@EntityID int,@Version varchar(64),@Data nvarchar(max)
AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
IF ISJSON(@Data)<>1 THROW 51003,'Invalid form data',1;
BEGIN TRY
BEGIN TRANSACTION;
DECLARE @r table(Kind varchar(20),EntityID int,Data nvarchar(max),Version varchar(64));
INSERT @r EXEC dbo.WriterAuthoring_Sections @UserID,@BookID,@ChapterID,@SceneID;
IF NOT EXISTS(SELECT 1 FROM @r WHERE Kind=@Kind AND EntityID=@EntityID) THROW 51000,'Editor unavailable in this selection',1;
IF NOT EXISTS(SELECT 1 FROM @r WHERE Kind=@Kind AND EntityID=@EntityID AND Version=ISNULL(@Version,'')) THROW 51002,'This information changed. Your text is retained; reload the editor to compare before saving again.',1;
DECLARE @summary nvarchar(max)=JSON_VALUE(@Data,'$.Summary'),@purpose int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.ChapterPurposeID'),'')),
@goal nvarchar(max),@emotion nvarchar(max),@takeaway nvarchar(max),@include nvarchar(max),@risk nvarchar(max),
@noteType int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.SceneNoteTypeID'),'')),@title nvarchar(200)=JSON_VALUE(@Data,'$.NoteTitle'),@text nvarchar(max)=JSON_VALUE(@Data,'$.NoteText'),
@sort int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.SortOrder'),'')),@pinned bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsPinned')),0),@resolved bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsResolved')),0),
@item nvarchar(300)=JSON_VALUE(@Data,'$.ItemText'),@done bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsCompleted')),0);
-- OPENJSON WITH nvarchar(max) avoids JSON_VALUE's 4000-character limit on author prose.
SELECT @summary=Summary,@goal=GoalSummary,@emotion=EmotionalGoal,@takeaway=ReaderTakeaway,@include=MustInclude,@risk=RisksOrConcerns,@text=NoteText FROM OPENJSON(@Data) WITH(Summary nvarchar(max),GoalSummary nvarchar(max),EmotionalGoal nvarchar(max),ReaderTakeaway nvarchar(max),MustInclude nvarchar(max),RisksOrConcerns nvarchar(max),NoteText nvarchar(max));
IF EXISTS(SELECT 1 FROM OPENJSON(@Data) WHERE [key] IN('Priority','EstimatedWordCount','ActualWordCount','SortOrder','ChapterPurposeID','SceneNoteTypeID') AND NULLIF(CONVERT(nvarchar(max),value),'') IS NOT NULL AND TRY_CONVERT(int,CONVERT(nvarchar(4000),value)) IS NULL) THROW 51003,'Use valid whole numbers',1;
IF EXISTS(SELECT 1 FROM OPENJSON(@Data) WHERE [key] IN('DraftedDate','LastWorkedOn') AND NULLIF(CONVERT(nvarchar(max),value),'') IS NOT NULL AND TRY_CONVERT(date,CONVERT(nvarchar(4000),value)) IS NULL) THROW 51003,'Use valid dates',1;
IF @Kind='Chapter' BEGIN
IF @purpose IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.ChapterPurposeTypes WHERE ChapterPurposeID=@purpose AND IsArchived=0) THROW 51003,'Choose an available chapter purpose',1;
UPDATE dbo.Chapters SET Summary=@summary,ChapterPurposeID=@purpose,UpdatedDate=SYSUTCDATETIME() WHERE ChapterID=@ChapterID;
END ELSE IF @Kind='Goals' EXEC dbo.ChapterGoal_Save @ChapterID,@goal,@emotion,@takeaway,@include,@risk;
ELSE IF @Kind='Scene' BEGIN
DECLARE @sp nvarchar(max),@out nvarchar(max);
SELECT @sp=ScenePurposeNotes,@out=SceneOutcomeNotes FROM OPENJSON(@Data) WITH(ScenePurposeNotes nvarchar(max),SceneOutcomeNotes nvarchar(max));
UPDATE dbo.Scenes SET ScenePurposeNotes=@sp,SceneOutcomeNotes=@out,UpdatedDate=SYSUTCDATETIME() WHERE SceneID=@SceneID;
END ELSE IF @Kind IN('Note','AddNote') BEGIN
IF LEN(ISNULL(@text,''))=0 OR NOT EXISTS(SELECT 1 FROM dbo.SceneNoteTypes WHERE SceneNoteTypeID=@noteType AND IsActive=1) THROW 51003,'Choose a note type and enter note text',1;
IF LEN(ISNULL(JSON_VALUE(@Data,'$.NoteTitle'),''))>200 THROW 51003,'Note titles may contain up to 200 characters',1;
EXEC dbo.SceneNote_Save @EntityID,@SceneID,@noteType,@title,@text,@sort,@pinned,@resolved;
END ELSE IF @Kind IN('Checklist','AddChecklist') BEGIN
IF LEN(ISNULL(JSON_VALUE(@Data,'$.ItemText'),''))=0 OR LEN(JSON_VALUE(@Data,'$.ItemText'))>300 THROW 51003,'Enter a reminder of 1 to 300 characters',1;
EXEC dbo.SceneChecklist_Save @EntityID,@SceneID,@item,@done,@sort;
END ELSE IF @Kind='Workflow' BEGIN
DECLARE @priority int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.Priority'),'')),@estimated int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.EstimatedWordCount'),'')),@actual int=TRY_CONVERT(int,NULLIF(JSON_VALUE(@Data,'$.ActualWordCount'),'')),
@drafted date=TRY_CONVERT(date,NULLIF(JSON_VALUE(@Data,'$.DraftedDate'),'')),@worked date=TRY_CONVERT(date,NULLIF(JSON_VALUE(@Data,'$.LastWorkedOn'),'')),@blocked bit=COALESCE(TRY_CONVERT(bit,JSON_VALUE(@Data,'$.IsBlocked')),0),@reason nvarchar(max),
@status nvarchar(50)='Planned',@readyDraft bit=0,@readyRevision bit=0,@readyPolish bit=0;
SELECT @reason=BlockedReason FROM OPENJSON(@Data) WITH(BlockedReason nvarchar(max));
IF @priority IS NOT NULL AND @priority NOT BETWEEN 1 AND 10 OR @estimated<0 OR @actual<0 THROW 51003,'Priority must be 1 to 10 and word estimates non-negative',1;
SELECT @status=DraftStatus,@readyDraft=ReadyForDraft,@readyRevision=ReadyForRevision,@readyPolish=ReadyForPolish FROM dbo.SceneWorkflow WHERE SceneID=@SceneID;
EXEC dbo.SceneWorkflow_Save @SceneID,@status,@estimated,@actual,@drafted,@worked,@readyDraft,@readyRevision,@readyPolish,@blocked,@reason,@priority;
END;
COMMIT;
END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH;
END;
GO

View File

@ -22,6 +22,7 @@
<p data-audio-position></p><label><input type="checkbox" data-pause-on-edit checked /> Pause on Edit</label>
<p class="muted">End review stops tracking; Pause first to stop external playback. Actual text changes pause playback when supported by Companion. Scrolling and cursor movement do not. Resume is always explicit. Start again after Companion registers a session for this book if the review began without one.</p>
</div>
<p class="muted">Explicit sessions record browser engagement separately from elapsed time. Audio time requires consecutive player observations; playback does not prove attention. Overlapping browser and audio durations are not added together.</p>
@if(Model.Unified){<details class="writer3-recording-about"><summary>About optional recording</summary><p class="muted">Explicit sessions record browser engagement separately from elapsed time. Audio time requires consecutive player observations; playback does not prove attention. Overlapping browser and audio durations are not added together.</p></details>}else{<p class="muted">Explicit sessions record browser engagement separately from elapsed time. Audio time requires consecutive player observations; playback does not prove attention. Overlapping browser and audio durations are not added together.</p>}
<p role="status" data-work-message></p><a asp-controller="Writer" asp-action="Journey" asp-route-bookId="@Model.BookID">Writing Rhythm &amp; Journey</a>
</section>

View File

@ -26,6 +26,7 @@
<script src="~/js/writing-workspace.js" asp-append-version="true"></script>
<script src="~/js/writing-workspace-launcher.js" asp-append-version="true"></script>
@if(Model.Destination == "Write"){
<script src="~/js/writer-authoring.js" asp-append-version="true"></script>
<script src="~/js/writer-focus.js" asp-append-version="true"></script>
<script src="~/js/writer-objective.js" asp-append-version="true"></script>
<script src="~/js/writer-work.js" asp-append-version="true"></script>

View File

@ -0,0 +1,30 @@
@model PlotLine.Models.AuthoringSection
@{ var add=Model.Kind.StartsWith("Add",StringComparison.Ordinal); var id="authoring-"+Model.Key; }
<section class="writer3-authoring-card" data-authoring-card data-key="@Model.Key" data-kind="@Model.Kind">
<div class="writer3-authoring-heading"><h3>@Model.Title</h3><button type="button" class="btn btn-sm btn-outline-secondary" data-authoring-edit aria-controls="@id" aria-expanded="false">@(add?"Add":"Edit")<span class="visually-hidden"> @Model.Title</span></button></div>
<div data-authoring-display>
@if(add){<p class="muted">Optional — keep a useful detail here when you need it.</p>}
else{
var readable=Model.Fields.Where(x=>!string.IsNullOrWhiteSpace(Model.Value(x.Name)) && Model.Value(x.Name)!="false").ToArray();
@if(readable.Length==0){<p class="muted">Nothing recorded yet. Add this when it helps your writing.</p>}
@foreach(var f in (Model.Kind=="Goals"?readable.Take(1):readable)){var value=Model.Value(f.Name);<div class="writer3-recorded-field">@if(f.Label!=Model.Title){<strong>@f.Label</strong>}@if(f.Type=="textarea"&&value.Length>280){<p>@value[..280]…</p><details><summary>Read complete text</summary><p>@value</p></details>}else{<p>@(f.Type=="checkbox"?"Yes":f.Type=="purpose"?Model.Purposes.FirstOrDefault(x=>x.Value==value).Label??"Recorded purpose":f.Type=="noteType"?Model.NoteTypes.FirstOrDefault(x=>x.Value==value).Label??"Recorded note":value)</p>}</div>}
@if(Model.Kind=="Goals"&&readable.Length>1){<details><summary>More chapter intentions</summary>@foreach(var f in readable.Skip(1)){<div class="writer3-recorded-field"><strong>@f.Label</strong><p>@Model.Value(f.Name)</p></div>}</details>}
}
</div>
<form id="@id" asp-controller="WriterAuthoring" asp-action="Save" method="post" data-authoring-form hidden>
<input type="hidden" name="bookId" value="@Model.BookID" /><input type="hidden" name="chapterId" value="@Model.ChapterID" /><input type="hidden" name="sceneId" value="@Model.SceneID" />
<input type="hidden" name="kind" value="@Model.Kind" /><input type="hidden" name="entityId" value="@Model.EntityID" /><input type="hidden" name="version" value="@Model.Version" />
@foreach(var f in Model.Fields){var fid=id+"-"+f.Name;var value=Model.Value(f.Name);
<div class="writer3-inline-field"><label for="@fid">@f.Label</label>
@if(f.Type=="textarea"){<textarea id="@fid" name="@f.Name" class="form-control" rows="3" maxlength="@(f.Max==int.MaxValue?null:f.Max.ToString())" required="@f.Required">@value</textarea>}
else if(f.Type is "purpose" or "noteType"){var options=f.Type=="purpose"?Model.Purposes:Model.NoteTypes;<select id="@fid" name="@f.Name" class="form-select" required="@f.Required">@if(f.Type=="purpose"){<option value="">No purpose selected</option>}@if(!string.IsNullOrEmpty(value)&&options.All(x=>x.Value!=value)){<option value="@value" selected>Recorded choice (currently unavailable)</option>}@foreach(var option in options){<option value="@option.Value" selected="@(option.Value==value)">@option.Label</option>}</select>}
else if(f.Type=="checkbox"){<input id="@fid" type="checkbox" name="@f.Name" value="true" checked="@(value=="true")" />}
else{<input id="@fid" type="@(f.Type=="number"?"number":f.Type=="date"?"date":"text")" class="form-control" name="@f.Name" value="@(f.Type=="date" && value.Length>=10?value[..10]:value)" maxlength="@(f.Max==int.MaxValue?null:f.Max.ToString())" required="@f.Required" />}
</div>
}
<p role="alert" data-authoring-error hidden></p>
<div class="button-row"><button class="btn btn-primary" type="submit" data-authoring-save>Save<span class="visually-hidden"> @Model.Title</span></button><button class="btn btn-outline-secondary" type="button" data-authoring-cancel>Cancel</button><button class="btn btn-outline-secondary" type="button" data-authoring-reload hidden>Reload recorded version</button></div>
</form>
<p role="status" class="writer3-caption" data-authoring-status></p>
</section>

View File

@ -0,0 +1,48 @@
@model PlotLine.Models.WriterAuthoringPage
<div data-authoring-content>
<div class="writer3-authoring-heading"><h2>What you're trying to achieve</h2><help-icon key="writer3.authoring" /></div>
<p class="writer3-caption">@(Model.Scene?.SceneTitle??Model.Chapter.ChapterTitle) · @(Model.Scene==null?"Chapter focus":"Scene focus") · Recorded state: @(Model.Scene?.RevisionStatusName??Model.Chapter.RevisionStatusName). Manuscript prose stays in Word.</p>
<partial name="~/Views/Writer/_AuthoringSection.cshtml" model="@(Model.Sections.First(x=>x.Kind==(Model.SceneID.HasValue?"Scene":"Goals")))" />
<details class="writer3-authoring-details"><summary>Chapter summary and additional intentions</summary>
<partial name="~/Views/Writer/_AuthoringSection.cshtml" model="@(Model.Sections.First(x=>x.Kind=="Chapter"))" />
@if(Model.SceneID.HasValue){<partial name="~/Views/Writer/_AuthoringSection.cshtml" model="@(Model.Sections.First(x=>x.Kind=="Goals"))" />}
</details>
@if(Model.SceneID.HasValue){
<h2>Notes and things to remember</h2>
<ul class="writer3-reminder-preview">@foreach(var section in Model.Sections.Where(x=>x.Kind=="Note" && x.Value("IsResolved")!="true" || x.Kind=="Checklist" && x.Value("IsCompleted")!="true").OrderByDescending(x=>x.Value("IsPinned")=="true").ThenBy(x=>int.TryParse(x.Value("SortOrder"),out var order)?order:int.MaxValue).Take(3)){<li>@{var text=section.Kind=="Note"?section.Value("NoteText"):section.Value("ItemText");}@(text.Length>240?text[..240]+"…":text)</li>}</ul>
<details class="writer3-authoring-details"><summary>All scene notes, reminders and working details</summary>
@foreach(var section in Model.Sections.Where(x=>x.Kind is "Note" or "Checklist")){<partial name="~/Views/Writer/_AuthoringSection.cshtml" model="section" />}
<partial name="~/Views/Writer/_AuthoringSection.cshtml" model="@(Model.Sections.First(x=>x.Kind=="Workflow"))" />
<p class="writer3-caption">Saving working details does not change scene revision state or checklist completion. Recorded working words are separate from accepted manuscript counts.</p>
</details>
<div data-authoring-new-records></div>
<partial name="~/Views/Writer/_AuthoringSection.cshtml" model="@(Model.Sections.First(x=>x.Kind=="AddNote"))" /><partial name="~/Views/Writer/_AuthoringSection.cshtml" model="@(Model.Sections.First(x=>x.Kind=="AddChecklist"))" />
<details class="writer3-authoring-details"><summary>Attachments and advanced scene information</summary><p>Use the existing editor for uploads, deletion, purpose categories, revision state and other dependent story records.</p>@foreach(var attachment in Model.Attachments){<p>@attachment.Title</p>}<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@Model.SceneID">Open full scene editor</a></details>
}else{
<h2>Scenes in this chapter</h2>
@if(Model.Scenes.Count==0){<p>There are no scenes yet. You can work at chapter level, or add a scene in the chapter editor.</p>}
@foreach(var scene in Model.Scenes){<form asp-controller="Writer" asp-action="SaveObjective" method="post" class="writer3-scene-choice"><input type="hidden" name="BookID" value="@Model.BookID" /><input type="hidden" name="ChapterID" value="@Model.ChapterID" /><input type="hidden" name="SceneID" value="@scene.SceneID" /><input type="hidden" name="Activity" value="@ViewData["WorkingActivity"]" /><span>@scene.SceneTitle · @scene.RevisionStatusName</span><button class="btn btn-sm btn-outline-secondary" type="submit">Work on this scene</button></form>}
<p class="writer3-caption">Chapter reminders live in the existing Things to include and Concerns fields above. Scene notes remain with their scenes; session return notes remain with sessions.</p>
}
<div class="writer3-inset" data-authoring-next-area><h3>Next useful action</h3>
@if(Model.SceneID.HasValue && string.IsNullOrWhiteSpace(Model.Sections.First(x=>x.Kind=="Scene").Value("ScenePurposeNotes"))){<button type="button" class="btn btn-outline-secondary" data-authoring-next="@($"Scene-{Model.SceneID}")">Add what needs to happen</button>}
else if(Model.Chapter.IsLinkedToManuscript){<a asp-controller="ManuscriptReader" asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-chapterId="@Model.ChapterID">Read the accepted chapter</a><p class="writer3-caption">Unsynchronised Word edits are not shown by Reader.</p>}
else if(Model.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@Model.SceneID">Develop this recorded scene</a><p class="writer3-caption">Return to Word for manuscript prose; this workspace edits supporting information.</p>}
else{<a asp-controller="Chapters" asp-action="Edit" asp-route-id="@Model.ChapterID">Develop this chapter or add a scene</a>}
</div>
</div>
<template data-authoring-companion>
<section class="writer3-reference-summary"><h3>Recorded story references</h3>
@if(Model.Scene==null){<p>@Model.Chapter.ChapterTitle</p><p>@Model.Scenes.Count recorded scenes. Select a scene to see its saved people, setting and threads.</p>}
else{
<p><strong>Setting:</strong> @(Model.Scene.PrimaryLocationID.HasValue?Model.Scene.PrimaryLocationName??"Recorded setting unavailable":"No location recorded")</p>
<p><strong>People:</strong> @(Model.Characters.Count==0?"No scene appearances recorded":string.Join(", ",Model.Characters.Take(6).Select(x=>x.CharacterName)))</p>
<p><strong>Threads:</strong> @(Model.Threads.Count==0?"No thread events recorded":string.Join("; ",Model.Threads.Take(4).Select(x=>$"{x.PlotLineName}: {x.ThreadTitle} — {x.EventTypeName}")))</p>
var feeling=Model.Sections.First(x=>x.Kind=="Goals").Value("EmotionalGoal");
@if(!string.IsNullOrWhiteSpace(feeling)){<p><strong>Chapter feeling intention:</strong> @feeling</p>}
<p><strong>Relationships:</strong> @(Model.Relationships.Count==0?"No verified relationship events recorded":string.Join("; ",Model.Relationships.Take(4).Select(x=>$"{x.CharacterAName} / {x.CharacterBName}: {x.RelationshipTypeName}")))</p>
}
<p class="writer3-caption">Saved records only; no manuscript analysis or inferred story facts. Open Context for the full reference categories and recorded metrics.</p>
</section>
</template>

View File

@ -4,7 +4,7 @@
<section class="writer3-panel writer3-main" tabindex="0" id="working-focus" aria-label="Current writing focus" data-writer-focus data-saved-activity="@focus?.Activity" data-saved-session-kind="@PlotLine.Services.Writer.WriterFocusActivities.SessionKind(focus?.Activity)" data-saved-chapter="@focus?.ChapterID" data-book-id="@Model.BookID" data-plan-url="@Url.Action("ScheduleSetup", "Writer", new { bookId = Model.BookID, projectId = Model.ProjectID })">
<p class="eyebrow">Your current work</p>
@if(focus != null && !editing){
<h2>@(focus.SceneTitle ?? focus.ChapterTitle ?? "Your manuscript")</h2><p class="writer3-focus-kind">@focus.Activity</p>@if(focus.ChapterID.HasValue){<p class="writer3-caption">Chapter: @focus.ChapterTitle</p>}<p>Return to this saved task. Write manuscript text in Word, and use the chapter or scene tools for your plan and notes.</p>
<h2>@(focus.SceneTitle ?? focus.ChapterTitle ?? "Your manuscript")</h2><p class="writer3-focus-kind">@focus.Activity</p>@if(focus.ChapterID.HasValue){<p class="writer3-caption">Chapter: @focus.ChapterTitle</p>}<p>Write manuscript prose in Word; use the intentions and reminders below to guide your work.</p>
<div class="button-row">
@if(focus.SceneID.HasValue){<a class="btn btn-primary writer3-cta" asp-controller="Scenes" asp-action="Edit" asp-route-id="@focus.SceneID">Open current scene <span aria-hidden="true">→</span></a>}
else if(focus.ChapterID.HasValue){<a class="btn btn-primary writer3-cta" asp-action="Chapter" asp-route-id="@focus.ChapterID">Open current chapter <span aria-hidden="true">→</span></a>}
@ -15,22 +15,23 @@
<h2>@(editing ? "Choose your working focus" : "Where would you like to begin?")</h2><p>Choose an activity and, if you like, a chapter or scene. You can start without a writing plan.</p>
<div id="objective-setup"><partial name="_WriterFocusForm" model="Model" /></div>
}
@if(!Model.ActivityIsPrivate){
@if(focus != null && !editing){<div class="button-row writer3-focus-actions"><button type="button" class="btn btn-outline-primary" data-record-focus disabled>Record this session</button><button type="button" class="btn btn-outline-secondary" data-plan-focus>Plan writing time</button></div>}
<label data-record-kind-choice hidden>Record proofreading as<select class="form-select" data-record-kind><option value="">Choose a compatible recording activity</option><option value="Editing">Editing</option><option value="Reading">Reading review</option></select></label>
<p class="writer3-caption" data-focus-recording-hint></p><p role="status" data-focus-message></p><p class="writer3-caption" data-focus-session-difference hidden></p>
<div class="writer3-session-block"><h3>Work sessions &amp; Audio Review</h3><partial name="_WriterWorkToolbar" model="new PlotLine.Models.WriterWorkToolbar(Model.BookID!.Value, focus?.ChapterID, focus?.ChapterTitle, Model.ObjectiveChoices, kind, true)" /></div>}
else{<p class="muted">Work-session evidence is private to the book owner. Your chapter and scene tools remain available.</p>}
@if(focus?.ChapterID.HasValue==true && !editing){<div class="writer3-authoring" data-writer-authoring data-inspect-url="@Url.Action("Inspect","WriterAuthoring",new{bookId=Model.BookID,chapterId=focus.ChapterID,sceneId=focus.SceneID})" aria-live="polite"><p>Loading your recorded intentions…</p></div>}
</section>
<aside class="writer3-panel writer3-reference" tabindex="0" aria-label="Writing tools">
<h2>Keep your story close</h2><p>Open the existing tools when you need more detail.</p>
<h2>Keep your story close</h2><div class="button-row writer3-window-actions"><button type="button" class="btn btn-sm btn-outline-secondary" data-open-writing-context>Open Context <span aria-hidden="true">↗</span></button><button type="button" class="btn btn-sm btn-outline-secondary" data-open-writing-intent>Open Intent <span aria-hidden="true">↗</span></button></div><p data-writing-workspace-message role="status"></p><div data-authoring-references></div><p>Open the existing tools when you need more detail.</p>
<div class="writer3-link-list">
<a asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID" asp-fragment="chapters">Chapters &amp; scenes <span aria-hidden="true">↗</span></a>
@if(focus?.ChapterID.HasValue==true){<a asp-action="Chapter" asp-route-id="@focus.ChapterID">Chapter goals &amp; workflow <span aria-hidden="true">↗</span></a>}
<a asp-action="Workspaces" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Scene workspaces <span aria-hidden="true">↗</span></a>
<button type="button" data-open-writing-context>Open Context <span aria-hidden="true">↗</span></button>
<button type="button" data-open-writing-intent>Open Intent <span aria-hidden="true">↗</span></button>
</div>
<p class="writer3-caption">Context and Intent open as standalone reference windows. Their selection is separate from your saved writing focus.</p><p data-writing-workspace-message role="status"></p>
@if(Model.ProjectID.HasValue){<details class="writer3-authoring-details"><summary>Open story reference tools</summary><div class="writer3-link-list"><a asp-controller="Characters" asp-action="Index" asp-route-projectId="@Model.ProjectID">Characters</a><a asp-controller="PlotLineWorkspace" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Plot lines and threads</a><a asp-controller="RelationshipMap" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Relationships</a><a asp-controller="Maps" asp-action="Index" asp-route-projectId="@Model.ProjectID">Maps and locations</a><a asp-controller="ProjectMetrics" asp-action="Index" asp-route-projectId="@Model.ProjectID">Recorded emotion and scene metrics</a></div></details>}
<p class="writer3-caption">Context and Intent open as standalone reference windows. Their selection is separate from your saved writing focus.</p>
</aside>
</div>

View File

@ -58,3 +58,13 @@
.writer3-layout-tooltip{pointer-events:none}
.writer3 [data-save-focus]{background:var(--pd-accent);border-color:var(--pd-accent);color:var(--pd-on-accent)!important}
.writer3 [data-save-focus]:hover{background:var(--pd-accent-hover);border-color:var(--pd-accent-hover)}
.writer3-authoring{margin-top:1.4rem;border-top:1px solid var(--pd-border-subtle);padding-top:1.2rem}
.writer3-authoring-heading{display:flex;gap:.8rem;align-items:baseline;justify-content:space-between}.writer3-authoring-heading h3{margin:0}.writer3-authoring-card{padding:1rem 0;border-bottom:1px solid var(--pd-border-subtle)}
.writer3-recorded-field{margin-top:.7rem}.writer3-recorded-field strong{font-size:.84rem;color:var(--pd-muted);font-weight:500}.writer3-recorded-field p{white-space:pre-wrap;overflow-wrap:anywhere;margin:.3rem 0;max-width:75ch}
.writer3-inline-field{margin:.8rem 0}.writer3-inline-field label{display:block;margin-bottom:.35rem}.writer3-inline-field textarea{resize:vertical;min-height:5rem}.writer3-authoring-details{margin:1rem 0}.writer3-authoring-details>summary{padding:.7rem 0;color:var(--pd-accent);cursor:pointer}
.writer3-reference-summary{padding-bottom:1rem;border-bottom:1px solid var(--pd-border-subtle);font-size:.9rem}.writer3-reminder-preview{padding-left:1.2rem;white-space:pre-wrap}.writer3-reminder-preview li{margin:.5rem 0;max-width:75ch}.writer3-scene-choice{display:flex;flex-wrap:wrap;gap:.6rem;justify-content:space-between;align-items:center;padding:.6rem 0}
.writer3 [data-authoring-save]{background:var(--pd-accent);color:var(--pd-on-accent);border-color:var(--pd-accent)}.writer3 [data-authoring-error]{color:var(--pd-text);border-left:3px solid var(--pd-accent);padding:.7rem}
.writer3-main>.writer3-focus-kind{margin:.4rem 0}.writer3-main>.writer3-caption{margin:.4rem 0}.writer3-recording-about{font-size:.8rem;color:var(--pd-muted);margin:.6rem 0}.writer3-recording-about>summary{cursor:pointer;color:var(--pd-accent)}
/* Contain positioned accessibility labels within each scrolling panel, not the document viewport. */
.writer3-split>.writer3-panel{position:relative}
.writer3-window-actions{margin:.8rem 0 1rem}

View File

@ -0,0 +1,44 @@
// Canonical authoring support only. Never changes Word position, session target or a reference selection.
(() => {
const root=document.querySelector('[data-writer-authoring]');if(!root)return;
const main=root.closest('.writer3-main');
main.addEventListener('plotdirector:work-state',e=>{const block=e.target.closest('.writer3-session-block');if(!block)return;if(e.detail.session){if(block.nextElementSibling!==root)root.before(block);}else if(block.previousElementSibling!==root)root.after(block);});
let allowLeave=false;const dirty=()=>[...root.querySelectorAll('[data-authoring-form]')].some(f=>f.dataset.dirty==='true'||f.dataset.busy==='true');
const cardOf=n=>n.closest('[data-authoring-card]');
const focusEditor=card=>card.querySelector('textarea,select,input:not([type=hidden])')?.focus();
function bind(container){
for(const form of container.querySelectorAll('[data-authoring-form]')){
if(form.dataset.bound)continue;form.dataset.bound='true';
const markDirty=()=>{form.dataset.dirty='true';cardOf(form).querySelector('[data-authoring-status]').textContent='';};form.addEventListener('input',markDirty);form.addEventListener('change',markDirty);
const card=cardOf(form),edit=card.querySelector('[data-authoring-edit]'),display=card.querySelector('[data-authoring-display]'),error=form.querySelector('[data-authoring-error]');
edit.addEventListener('click',()=>{card.querySelector('[data-authoring-status]').textContent='';form.hidden=false;display.hidden=true;edit.hidden=true;edit.setAttribute('aria-expanded','true');focusEditor(card);});
form.querySelector('[data-authoring-cancel]').addEventListener('click',()=>{if(form.dataset.busy==='true')return;form.reset();card.querySelector('[data-authoring-status]').textContent='';form.dataset.dirty='false';form.hidden=true;display.hidden=false;edit.hidden=false;edit.setAttribute('aria-expanded','false');error.hidden=true;edit.focus();});
form.querySelector('[data-authoring-reload]').addEventListener('click',async()=>{if(!confirm('Reload the recorded version? Copy any text you want to keep first.'))return;try{const doc=await read();replaceCard(card,doc);}catch{error.textContent='Could not reload. Your text is still here.';}});
form.addEventListener('submit',async e=>{
e.preventDefault();if(form.dataset.busy==='true')return;form.dataset.busy='true';const save=form.querySelector('[data-authoring-save]'),cancel=form.querySelector('[data-authoring-cancel]'),reload=form.querySelector('[data-authoring-reload]');let committed=false;save.disabled=true;cancel.disabled=true;reload.disabled=true;error.hidden=true;
const data=new FormData(form);for(const input of form.querySelectorAll('input[type=checkbox]'))data.set(input.name,String(input.checked));
try{const response=await fetch(form.action,{method:'POST',body:data,headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok){const body=await response.json().catch(()=>null);error.textContent=body?.message||'Could not save. Your text is still here.';error.hidden=false;if(response.status===409)form.querySelector('[data-authoring-reload]').hidden=false;return;}
// A committed save is not retried if the following read fails (especially for newly created rows).
const result=await response.json().catch(()=>null);if(result?.success!==true)throw Error('Save was not confirmed');
committed=true;form.dataset.dirty='false';const doc=await read();const isAdd=card.dataset.kind.startsWith('Add');replaceCard(card,doc);
const preview=root.querySelector('.writer3-reminder-preview'),freshPreview=doc.querySelector('.writer3-reminder-preview');if(preview&&freshPreview)preview.replaceWith(freshPreview.cloneNode(true));
const next=root.querySelector('[data-authoring-next-area]'),freshNext=doc.querySelector('[data-authoring-next-area]');if(next&&freshNext){const clone=freshNext.cloneNode(true);next.replaceWith(clone);bind(clone);}
const refs=document.querySelector('[data-authoring-references]'),template=doc.querySelector('[data-authoring-companion]');if(refs&&template)refs.replaceChildren(template.content.cloneNode(true));
if(isAdd){for(const fresh of doc.querySelectorAll('[data-authoring-card]'))if(!root.querySelector(`[data-key="${CSS.escape(fresh.dataset.key)}"]`)){const clone=fresh.cloneNode(true);root.querySelector('[data-authoring-new-records]')?.append(clone);bind(clone.parentElement);}}
}catch{error.textContent=committed?'Saved, but the refreshed record could not load. Your text is retained. Reload the recorded version.':'Save was not confirmed. Your text is retained. Reload the recorded version to check before trying again.';error.hidden=false;form.querySelector('[data-authoring-reload]').hidden=false;}
finally{form.dataset.busy='false';save.disabled=committed&&form.isConnected;cancel.disabled=committed&&form.isConnected;reload.disabled=false;}
});
}
for(const details of container.querySelectorAll('details'))if(!details.dataset.authoringBound){details.dataset.authoringBound='true';details.addEventListener('toggle',()=>{if(!details.open&&[...details.querySelectorAll('[data-authoring-form]')].some(f=>f.dataset.dirty==='true')){details.open=true;const pending=details.querySelector('[data-authoring-form][data-dirty="true"]');if(pending)cardOf(pending).querySelector('[data-authoring-status]').textContent='Save or Cancel this editor before closing the section.';}});}
for(const button of container.querySelectorAll('[data-authoring-next]'))button.addEventListener('click',()=>root.querySelector(`[data-key="${CSS.escape(button.dataset.authoringNext)}"] [data-authoring-edit]`)?.click());
for(const input of container.querySelectorAll('.writer3-scene-choice [name=Activity]'))input.value=document.querySelector('[data-writer-focus]').dataset.savedActivity;
}
function replaceCard(card,doc){const fresh=doc.querySelector(`[data-key="${CSS.escape(card.dataset.key)}"]`);if(!fresh)throw Error('Saved record is not available');const clone=fresh.cloneNode(true),parent=card.parentElement;card.replaceWith(clone);bind(parent);clone.querySelector('[data-authoring-status]').textContent='Saved.';clone.querySelector('[data-authoring-edit]')?.focus();}
async function read(){const response=await fetch(root.dataset.inspectUrl,{cache:'no-store'});if(!response.ok)throw Error('Recorded information is unavailable');const doc=new DOMParser().parseFromString(await response.text(),'text/html');if(!doc.querySelector('[data-authoring-content]'))throw Error('Authorisation or recorded information is unavailable');return doc;}
async function load(){try{const doc=await read();root.replaceChildren(...doc.body.childNodes);bind(root);const references=document.querySelector('[data-authoring-references]'),template=root.querySelector('[data-authoring-companion]');if(references&&template)references.replaceChildren(template.content.cloneNode(true));}
catch{root.replaceChildren();const p=document.createElement('p');p.textContent='Recorded information could not load. Your current work and existing editors remain available.';const retry=document.createElement('button');retry.type='button';retry.className='btn btn-outline-secondary';retry.textContent='Try again';retry.addEventListener('click',load);root.append(p,retry);}}
window.addEventListener('beforeunload',e=>{if(dirty()&&!allowLeave){e.preventDefault();e.returnValue='';}});
function guard(e){if(!dirty())return;const target=e.target.closest('a,form,[data-plan-focus]');if(!target||target.matches('[data-authoring-form],[data-work-start]')||target.target==='_blank'||target.hasAttribute('download'))return;if(target.tagName==='A'&&new URL(target.href,location.href).pathname===location.pathname&&new URL(target.href,location.href).search===location.search&&target.hash)return;if(!confirm(root.querySelector('[data-busy="true"]')?'A save is in progress and may finish after you leave. Leave this page?':'Leave without saving your inline edits?')){e.preventDefault();e.stopImmediatePropagation();}else allowLeave=true;}
document.addEventListener('click',e=>{if(e.target.closest('a,[data-plan-focus]'))guard(e);},true);document.addEventListener('submit',guard,true);window.addEventListener('pageshow',()=>allowLeave=false);
load();
})();

View File

@ -15,7 +15,7 @@
root.addEventListener('plotdirector:work-start-finished',()=>{pending=false;render();});
activity?.addEventListener('change',()=>{if(kindChoice)kindChoice.value='';render();});kindChoice?.addEventListener('change',render);
record?.addEventListener('click',()=>{if(active||pending||!known)return;const s=selection(),k=kind();if(!k){message.textContent='Choose a compatible session activity before recording.';kindChoice?.focus();return;}if(k==='AudioReview'&&!s.chapter){message.textContent='Choose a chapter for Audio Review.';chapter?.focus();return;}message.textContent='';pending=true;render();root.querySelector('[data-writer-work]').dispatchEvent(new CustomEvent('plotdirector:record-focus',{detail:{kind:k,chapter:s.chapter}}));});
form?.addEventListener('submit',e=>{if(saving||!objectives.includes(selection().activity)){e.preventDefault();return;}saving=true;render();});
form?.addEventListener('submit',e=>{if(e.defaultPrevented)return;if(saving||!objectives.includes(selection().activity)){e.preventDefault();return;}saving=true;render();});
root.querySelector('[data-plan-focus]')?.addEventListener('click',()=>{const url=new URL(root.dataset.planUrl,location.origin);url.searchParams.set('focusActivity',selection().activity);location.assign(url);});
render();
})();