Integrate canonical manuscript review and anchored author observations
This commit is contained in:
parent
55bdce3025
commit
b4a1d4472d
@ -106,3 +106,7 @@ Phase3A qualification exercises the dynamically loaded authoring Help icon in br
|
||||
`writer3.word` uses existing micro/quick/full Markdown Help in the Write companion. It covers exact manuscript selection, verified position, working-focus/session/Reader independence, acknowledged chapter and optional verified-scene navigation, accepted-content freshness, bounded saved-manuscript checks, recovery, multiple documents and return/adopt. Check controls and additional explanation use optional Connection and update options. Updated `writer3.write` links the concepts; existing native/Reader/standalone Help remains authoritative. Qualification and physical Windows limits are recorded in Phase3B-Report.md.
|
||||
|
||||
Phase3B qualified: quick popup, More drawer and full writer3.word article verified in authenticated Development browser/simulated PWA. Current Word status/navigation fixtures also cover hidden title-bar presence and cached return. Physical installed PWA/Word and assistive-technology acceptance remain manual; see Phase3B-Report.md.
|
||||
|
||||
## Phase3C integrated Review
|
||||
|
||||
`writer3.reviewing` covers accepted reading, independent selection, chapter/verified scene context, author-private observations, explicit Save/Cancel/edit/resolve/reopen, original version/paragraph references, missing/changed anchors, verified paragraph-start versus chapter handoff, Audio Review and provenance. `writer3.review` describes the integrated Reader and `writer3.explore` describes the corrected authenticated tools rather than public Solver journeys. Existing micro/quick/full Help infrastructure is reused. Qualification and physical acceptance limits are recorded in Phase3C-Report.md.
|
||||
|
||||
@ -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; Phase3A integrated authoring is implemented and Development-qualified; Phase3B verified Word continuity is implemented and Development-qualified, with physical Windows acceptance outstanding; Phase3C 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 integrated authoring is implemented and Development-qualified; Phase3B verified Word continuity is implemented and Development-qualified, with physical Windows acceptance outstanding; Phase3C is explicitly authorised for integrated Review; Phase4 remains unauthorised. No feature is retired. Unrelated investigation file is preserved.
|
||||
|
||||
## Phase 1 screen and interaction states before implementation
|
||||
|
||||
@ -355,3 +355,8 @@ Application `e9402d0c1673d3dc8afcca26bb344b82fa11caf0`, release `e9402d0-2026111
|
||||
Batches3B.1–3B.6: native contract audit, shared Word status presentation, explicit acknowledged chapter/scene navigation, accepted Reader freshness, return/recovery, Help/qualification/Development. Existing native identity/range/checkpoint/Reader/session/follow contracts remain authoritative. Additive read-only metadata procedure271 and negotiated acknowledged-navigation-v1; matched native developer source1.0.0.37, no Windows installation. Writer companion shows Word status without displacing intentions or active-session controls. Detailed qualification and final release are in Phase3B-Report.md. Phase3C/4 not started by this authorisation.
|
||||
|
||||
Phase3B software qualification complete: application/native source9969c9b, Development release9969c9b-20261116T210203Z;599 web,288 native and453 chapter-sync assertions; authenticated read-only data hashes unchanged and disposable fixture removed. Matched1.0.0.37 Windows build/install/physical acceptance remains manual. Phase3C not started.
|
||||
|
||||
|
||||
## Phase3C authorised implementation
|
||||
|
||||
Batches3C.1–3C.6 integrate the canonical Reader, pure chapter/scene intentions, author observations and decisions, existing acknowledged Word handoff, Audio Review and optional saved finding tools. Baseline55bdce3 includes Windows1.0.0.40 and Return to Writer/recording fixes; native source is unchanged in3C. Observations use a new author-private anchored store only because scene/session notes and machine findings cannot represent chapter/accepted-version references. Shared compact viewport geometry and bounded authenticated Explore routing are separate corrections. See Phase3C-Execution.md and Phase3C-Report.md for contracts, qualification and release. Phase4 is not started.
|
||||
|
||||
27
Docs/Writer/Writer3/Phase3C-Execution.md
Normal file
27
Docs/Writer/Writer3/Phase3C-Execution.md
Normal file
@ -0,0 +1,27 @@
|
||||
# Phase3C execution and persistence contract
|
||||
|
||||
Scope: Phase3C only. Fetched and fast-forwarded81b57a5 to55bdce3 before editing, preserving merged Windows ribbon/Audio Review, typed authenticated Return to Writer and independent recording-control corrections. Native source version1.0.0.40; this phase changes no native binaries/contracts or Windows installation.
|
||||
|
||||
## 3C.1–3C.2
|
||||
|
||||
Review previously linked to Reader. The existing canonical Reader is now a shared Razor partial embedded in Review, keeping its controller, accepted-version requests, selectable text, paragraph renderer, Focused Reading, refresh/pause/selection/anchor policy and session toolbar. Review URL chapters remain separate from saved objectives and session/Word/pinned/Intent targets. Scene context comes only from accepted paragraph assignments, with chapter fallback for unknown, mixed, stale or unavailable scenes. Existing Phase3A pure authoring service provides intentions, notes/reminders and workflow. Full editing uses existing canonical editors in another window rather than reproducing Write.
|
||||
|
||||
## 3C.3 storage decision
|
||||
|
||||
SceneNotes cannot represent chapter-level observations, accepted version or paragraph ranges. Session return notes require a real session and have separate retention/lifecycle. Story Intelligence/native suggestions carry machine provenance and author approval semantics; they are not free-form reader annotations. No existing suitable anchored author-review store was found. New author-private WriterReviewObservations therefore holds only entered observation/decision, its own Open/Working/Resolved state, immutable accepted manuscript/version/paragraph/offset/hash references and timestamps. No copied quote, manuscript-specific logic or inferred fact is stored.
|
||||
|
||||
Migration272 adds scoped stored procedures, the observation table and a pure paragraph-position lookup reusing existing current checkpoint/hash/identity joins. Chapter/user cascades and book foreign key support existing guarded deletion. Author/book/chapter checks, optimistic versions, client-generated idempotency IDs and canonical-revision locking protect writes. Creation validates the displayed chapter fingerprint and exact range; update cannot change original references. Resolving never changes canonical scene status, sessions or prose. Pagination bounds list payloads. Reads do not seed rows.
|
||||
|
||||
## 3C.4–3C.5
|
||||
|
||||
Review reuses Phase3B acknowledged navigation. Optional paragraph handoff uses exact current accepted revision/paragraph plus live proof and targets the paragraph start, not an assumed character range. Rejection never automatically falls back; the separate verified chapter action remains explicit. Native identity/session/revision/expiry/ack fences stay intact. Reader metadata-only changes update its revision without replacing text. No observation is resolved by accepted text changing. Missing references never search for similar text.
|
||||
|
||||
Existing Audio Review controls, target/UUID, timing, native media safeguards and return notes remain in the shared Reader toolbar. Observation saves replace only the companion's recorded context/list. Dirty editors pause Reader replacement and restore the prior pause preference on Save/Cancel. Existing findings remain distinct optional Intent/book tool routes; opening Review invokes no analysis.
|
||||
|
||||
## 3C.6 bounded follow-ups
|
||||
|
||||
Five-destination geometry captures at1440,1024 and390 showed normal viewport-bottom fit before changes, with a large header consuming work area. Shared compact header/tools reclaim height; viewport measurement uses rendered rather than document-relative top, fixing scrolled-shell subtraction. Reader is not constrained by a second fixed-height scrollport. Resizing/collapse/overlay/short-window flow remain authoritative.
|
||||
|
||||
Explore's first two choices pointed at public Problem Solver routes. They now use authenticated scoped Write and Plot Lines/threads, with honest tool labels. Timeline remains the distinct authenticated shape tool. No iframe or Phase5 guided engine is introduced.
|
||||
|
||||
Qualification, deployment, data hashes, screenshots, native baseline and remaining physical acceptance are recorded in Phase3C-Report.md. Phase4 is not started.
|
||||
@ -15,7 +15,7 @@ const{chromium}=require('playwright'),assert=require('node:assert/strict');
|
||||
// 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);
|
||||
const session={sessionID:'33333333-3333-3333-3333-333333333333',kind:'AudioReview',bookID:12,chapterID:22,chapterTitle:'Bound audio chapter',startedUtc:new Date().toISOString(),engagedSeconds:60,playbackSeconds:20,uniqueSeconds:10,pauseOnEdit:true,live:true,playbackState:'playing',capabilities:'play,pause,back15,forward15',sequence:1};await p.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session}}));await p.goto(url);await p.locator('[data-work-audio]:visible').waitFor();await card('Scene-31').waitFor();assert(await p.locator('.writer3-session-block').evaluate(n=>n.nextElementSibling?.matches('[data-writer-authoring]')),'active controls remain above authoring');const work=await p.locator('[data-writer-work]').elementHandle();await p.locator('[data-work-note]').fill('Unsaved audio return note');await edit('Scene-31');await card('Scene-31').locator('[name=SceneOutcomeNotes]').fill('An explicit outcome during audio review');await save('Scene-31');assert(await work.evaluate(n=>n===document.querySelector('[data-writer-work]')));assert.equal(await p.locator('[data-work-note]').inputValue(),'Unsaved audio return note');assert((await p.locator('[data-work-bound]').textContent()).includes('Bound audio chapter'));assert.equal(await p.locator('[data-work-start] select').count(),2,'Windows baseline retains independent recording activity and chapter controls');
|
||||
await p.setViewportSize({width:390,height:844});await p.locator('.writer3-layout-tools button').first().click();assert(await p.locator('[data-authoring-references]').isVisible());await p.keyboard.press('Escape');assert(await p.locator('.writer3-reference').isHidden());assert(await p.locator('[data-authoring-content]').isVisible());
|
||||
await p.goto(url+'&chapterOnly=true');await p.locator('[data-key="Goals-21"]').waitFor();assert.equal(await p.locator('[data-key="Scene-31"]').count(),0);assert(await p.getByRole('button',{name:'Work on this scene'}).isVisible());
|
||||
await p.goto('http://127.0.0.1:5238/Writer/Write?projectId=7&bookId=13');assert.equal(await p.locator('[data-writer-authoring]').count(),0,'book switching cannot keep old support fields');assert.equal((await p.request.get('http://127.0.0.1:5238/WriterAuthoring/Inspect?bookId=13&chapterId=21&sceneId=31')).status(),404);assert.deepEqual(errors,[]);await c.close();}
|
||||
|
||||
3
PlotLine.Tests/Browser/writer3-layout-explore.cjs
Normal file
3
PlotLine.Tests/Browser/writer3-layout-explore.cjs
Normal file
@ -0,0 +1,3 @@
|
||||
const{chromium}=require('playwright'),assert=require('node:assert/strict');
|
||||
(async()=>{const b=await chromium.launch();try{const p=await b.newPage({viewport:{width:1440,height:1000}});for(const destination of['Write','Explore','Plan','Review','Reflect']){const r=await p.goto(`http://127.0.0.1:5238/Writer/${destination}?projectId=7&bookId=12`);assert.equal(r.status(),200);await p.waitForFunction(()=>document.querySelector('.writer3')?.classList.contains('writer3-viewport'));await p.evaluate(async()=>{await document.fonts.ready;await new Promise(r=>setTimeout(r,50))});const normal=await p.evaluate(()=>({header:document.querySelector('.writer3-header').getBoundingClientRect().height,bottom:document.querySelector('.writer3-workspace').getBoundingClientRect().bottom,height:innerHeight}));assert(normal.header<85,'compact shared header');assert(normal.height-normal.bottom<12,'uses available viewport');await p.evaluate(()=>{document.documentElement.style.overflow='auto';document.documentElement.style.height='auto';document.body.style.overflow='visible';document.body.style.height='auto';document.body.style.minHeight='1800px';document.body.style.paddingTop='180px';window.scrollTo({top:150,behavior:'instant'});window.dispatchEvent(new Event('resize'));});await p.waitForFunction(()=>{const w=document.querySelector('.writer3-workspace');return Math.abs(innerHeight-w.getBoundingClientRect().bottom)<12});assert(await p.evaluate(()=>window.scrollY>100),'scrolled shell fixture');}
|
||||
await p.goto('http://127.0.0.1:5238/Writer/Explore?projectId=7&bookId=12');const links=await p.locator('.writer3-explore-paths>a').evaluateAll(ns=>ns.map(n=>n.href));assert.equal(links.length,3);for(const href of links){const u=new URL(href);assert(!u.pathname.includes('problem-solver'));assert.equal(u.searchParams.get('projectId'),'7');assert.equal(u.searchParams.get('bookId'),'12');}assert.equal(new Set(links.map(x=>new URL(x).pathname)).size,3);assert.equal(await p.locator('iframe').count(),0);console.log('PASS five destinations compact viewport use and controlled scrolled-shell geometry; Explore has three distinct authenticated scoped tool routes and no public solver/iframe.');}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1});
|
||||
@ -13,7 +13,7 @@ const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('nod
|
||||
assert.equal(await p.locator('[data-writer-destination]').getAttribute('data-writer-destination'),action==='Index'?'Home':action);
|
||||
if(action==='Write'&&book===w.book)assert((await p.getByRole('link',{name:'Open current scene',exact:true}).getAttribute('href')).includes('/'+w.scene));
|
||||
if(action==='Write'&&book===w.other)assert.equal(await p.getByRole('heading',{name:'Where would you like to begin?',exact:true}).isVisible(),true);
|
||||
if(action==='Review'&&book===w.other)assert.equal(await p.getByRole('heading',{name:'No chapters to read yet',exact:true}).isVisible(),true);
|
||||
if(action==='Review'&&book===w.other)assert.equal(await p.getByRole('heading',{name:'No chapters yet',exact:true}).isVisible(),true);
|
||||
if(!pwa&&book===w.book&&process.env.PD_WRITER3_SCREENSHOTS){await p.evaluate(()=>window.PlotDirectorApplyApplicationTheme('modern-dark'));fs.mkdirSync(process.env.PD_WRITER3_SCREENSHOTS,{recursive:true});await p.screenshot({path:`${process.env.PD_WRITER3_SCREENSHOTS}/${action==='Index'?'Home':action}-Development.png`,fullPage:true});}
|
||||
}
|
||||
for(const [index,action]of[[0,'Write'],[1,'Explore'],[2,'Dashboard']]){await p.goto(`${base}/Writer?projectId=${w.project}&bookId=${w.book}`);await p.locator('.writer3-home-choices>a').nth(index).click();await p.waitForURL(`**/Writer/${action}?*`);assert.equal(new URL(p.url()).searchParams.get('bookId'),String(w.book));}
|
||||
|
||||
@ -21,7 +21,7 @@ const base='http://127.0.0.1:5238';
|
||||
const commands=page.locator('#ribbon-panel-writer [role=group]').first().locator('a');
|
||||
assert.deepEqual((await commands.locator('span:not([aria-hidden])').allTextContents()).map(x=>x.trim()),['Home','Write','Explore','Plan','Review','Reflect']);
|
||||
assert((await page.locator('#ribbon-panel-writer a[aria-current=page]').allTextContents()).some(t=>t.trim()===(destination==='Index'?'Home':destination==='Dashboard'?'Writing Dashboard':destination)));
|
||||
assert.equal(await page.locator('.writer3 nav').count(),0,'No duplicate destination navigation bar');
|
||||
assert.equal(await page.locator('.writer3 nav:not(.reader-controls)').count(),0,'No duplicate destination navigation bar; canonical Reader chapter navigation is independent');
|
||||
const contrasts=await page.locator('a.writer3-cta').evaluateAll(nodes=>{const lum=s=>{const rgb=s.match(/[\d.]+/g).slice(0,3).map(Number).map(x=>{x/=255;return x<=.04045?x/12.92:((x+.055)/1.055)**2.4});return rgb[0]*.2126+rgb[1]*.7152+rgb[2]*.0722};return nodes.map(n=>{const c=getComputedStyle(n),a=lum(c.color),b=lum(c.backgroundColor);return (Math.max(a,b)+.05)/(Math.min(a,b)+.05)})});assert(contrasts.every(x=>x>=4.5),'Primary action labels must have readable contrast');
|
||||
const overflow=await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2);assert.equal(overflow,false,`${pwa}/${theme}/${width}/${kind} horizontal overflow`);
|
||||
if(kind==='Home'){
|
||||
|
||||
17
PlotLine.Tests/Browser/writer3-review.cjs
Normal file
17
PlotLine.Tests/Browser/writer3-review.cjs
Normal file
@ -0,0 +1,17 @@
|
||||
const{chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
|
||||
(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('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'))}));
|
||||
const lease={instanceId:'11111111-1111-1111-1111-111111111111',sessionId:'22222222-2222-2222-2222-222222222222',manuscriptId:'33333333-3333-3333-3333-333333333333',bookId:12,wordAvailable:true,wordSaved:true,canAcknowledgeNavigation:true,canChapterSync:true,revision:2,documentTitle:'Simulated review manuscript',chapterId:22,chapterTitle:'Other Word chapter',expires:new Date(Date.now()+3600000).toISOString(),updated:new Date().toISOString()};await c.route('**/native-companion/status*',r=>r.fulfill({json:{leases:[lease],canonical:{manuscriptID:lease.manuscriptId},verifiedPositions:[{instanceId:lease.instanceId,sessionId:lease.sessionId,chapterId:22,chapterTitle:'Other Word chapter'}]}}));await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:{sessionID:'55555555-5555-5555-5555-555555555555',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},defaultPauseOnEdit:true}}));
|
||||
let nativePosts=[],rejectParagraph=false,savePosts=0;await c.route('**/WriterWord/Navigate',r=>{const values=Object.fromEntries(new URLSearchParams(r.request().postData()));nativePosts.push(values);return r.fulfill(rejectParagraph&&values.paragraphId?{status:409,json:{message:'Paragraph is no longer verified; use the separate chapter action.'}}:{status:202,json:{message:'requested'}})});await c.route('**/WriterWord/Navigation?*',r=>r.fulfill({json:{state:'completed'}}));
|
||||
const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));p.on('request',r=>{if(r.method()==='POST'&&new URL(r.url()).pathname==='/WriterReview/Save')savePosts++});const url='http://127.0.0.1:5238/Writer/Review?projectId=7&bookId=12';const initialResponse=await p.goto(url);assert.equal(initialResponse.status(),200);assert.match(initialResponse.headers()['cache-control'],/no-store/);assert.match(initialResponse.headers()['x-robots-tag'],/noindex/);await p.locator('[data-review-panel]').waitFor();assert(await p.locator('.reader-page').isVisible());assert.equal(nativePosts.length,0);assert.equal(savePosts,0);
|
||||
await p.getByText('Reading & Audio Review',{exact:true}).click();await p.locator('[data-work-audio]:visible').waitFor();await p.locator('[data-work-note]').fill('Retained review return note');const work=await p.locator('[data-writer-work]').elementHandle();
|
||||
const passage=p.locator('[data-paragraph-id][data-scene-id="31"]').first();const id=await passage.getAttribute('data-paragraph-id');await passage.evaluate(n=>{const r=document.createRange();r.selectNodeContents(n);r.setStart(n.firstChild,3);r.setEnd(n.firstChild,15);getSelection().removeAllRanges();getSelection().addRange(r)});await p.locator('[data-review-record]').click();const form=p.locator('[data-review-form]');assert(await form.isVisible());assert.equal(await form.locator('[name=StartParagraph]').inputValue(),id);assert.equal(await form.locator('[name=StartOffset]').inputValue(),'3');assert(await p.locator('#reader-pause').isChecked());await p.locator('[data-review-context]').getByText('Scene context comes from accepted paragraph assignments.',{exact:true}).waitFor();assert.equal(savePosts,0,'selection and editor opening never persist');
|
||||
await form.locator('[name=Observation]').fill('A review observation — 界 <script>text only</script>');await form.locator('[name=Decision]').fill('I want to clarify this detail.');const observationID=await form.locator('[name=ID]').inputValue();await form.evaluate(n=>{n.requestSubmit();n.requestSubmit()});await p.locator('[data-review-message]').filter({hasText:'Observation saved.'}).waitFor();assert.equal(savePosts,1);const row=()=>p.locator(`[data-observation][data-id="${observationID}"]`);await row().waitFor();assert.equal(await row().getAttribute('data-first'),id);assert((await row().textContent()).includes('<script>text only</script>'));assert(await work.evaluate(n=>n===document.querySelector('[data-writer-work]')));assert.equal(await p.locator('[data-work-note]').inputValue(),'Retained review return note');assert((await p.locator('[data-work-bound]').textContent()).includes('Bound audio chapter'));
|
||||
for(const state of['Working','Resolved','Open']){await row().locator('[data-review-edit]').click();await form.waitFor({state:'visible'}).catch(async e=>{throw Error(`${e.message}; ${await p.locator('[data-review-message]').textContent()}; hidden=${await form.getAttribute('hidden')}`)});await form.locator('[name=Status]').selectOption(state);await form.locator('[data-review-save]').click();await form.waitFor({state:'hidden'});await row().locator(`[data-review-edit][data-state="${state}"]`).waitFor();assert.equal(await row().getAttribute('data-first'),id);}
|
||||
await row().locator('[data-review-edit]').click();await form.locator('[name=Observation]').fill('Keep this stale draft');const q=await c.newPage();await q.goto(url);const other=q.locator(`[data-observation][data-id="${observationID}"]`);await other.locator('[data-review-edit]').click();await q.locator('[data-review-form] [name=Observation]').fill('Saved by the other review window');await q.locator('[data-review-save]').click();await q.locator('[data-review-form]').waitFor({state:'hidden'}).catch(async e=>{throw Error(`${e.message}; ${await q.locator('[data-review-error]').textContent()}`)});await q.close();await form.locator('[data-review-save]').click();await form.locator('[data-review-error]:visible').waitFor();assert.equal(await form.locator('[name=Observation]').inputValue(),'Keep this stale draft');await form.locator('[data-review-cancel]').click();await p.locator('[data-review-reload]').click();await row().getByText('Saved by the other review window',{exact:true}).waitFor();
|
||||
await p.locator('[data-review-new]').click();await form.locator('[name=Observation]').fill('Draft retained on navigation and failure');p.once('dialog',d=>d.dismiss());await p.locator('a[rel=next]').first().click();assert(new URL(p.url()).pathname==='/Writer/Review'&&!new URL(p.url()).searchParams.has('chapterId'));await p.route('**/WriterReview/Save',r=>r.fulfill({status:503,json:{message:'Temporarily unavailable; text retained.'}}));await form.locator('[data-review-save]').click();await form.locator('[data-review-error]:visible').waitFor();assert.equal(await form.locator('[name=Observation]').inputValue(),'Draft retained on navigation and failure');await p.unroute('**/WriterReview/Save');await form.locator('[data-review-cancel]').click();
|
||||
await row().locator('[data-review-revisit]').click();await p.getByText('Return to Word',{exact:true}).click();await p.locator('[data-word-paragraph]:enabled').waitFor();await p.locator('[data-word-paragraph]').click();await p.locator('[data-word-command]').filter({hasText:'paragraph start'}).waitFor();assert.equal(nativePosts.at(-1).paragraphId,id);assert.equal(nativePosts.at(-1).chapterId,'21');rejectParagraph=true;await p.locator('[data-word-paragraph]').click();await p.locator('[data-word-command]').filter({hasText:'no longer verified'}).waitFor();const count=nativePosts.length;await p.locator('[data-word-navigate]').click();await p.locator('[data-word-command]').filter({hasText:'Word confirmed navigation.'}).waitFor();assert.equal(nativePosts.length,count+1);assert(!nativePosts.at(-1).paragraphId);
|
||||
await p.locator('[data-help-key="writer3.reviewing"] button').click();await p.locator('.plotline-help-popover').waitFor();await p.locator('.plotline-help-more').click();await p.locator('[data-help-content] .help-drawer-article').waitFor();await p.locator('[data-help-close]').click();
|
||||
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.screenshot({path:process.env.PD_WRITER3_SCREENSHOTS+'/Review-fixture.png',animations:'disabled'});}
|
||||
await p.locator('#reader-focus').click();assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');await p.locator('a[rel=next]').first().click();await p.waitForURL(/chapterId=22/);assert.equal(new URL(p.url()).pathname,'/Writer/Review');assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');await p.locator('a[rel=prev]').first().click();await p.waitForURL(/chapterId=21/);assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');await p.locator('#reader-focus').click();await p.setViewportSize({width:390,height:844});await p.locator('[data-review-record]').click();assert(await form.isVisible());assert(await p.locator('.writer3-reference').isVisible());await form.locator('[data-review-cancel]').click();await p.keyboard.press('Escape');assert(await p.locator('.writer3-reference').isHidden());assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));
|
||||
await p.goto('http://127.0.0.1:5238/Writer/Review?projectId=7&bookId=13');assert.equal(await p.locator('[data-review-form]').count(),0);assert.equal((await p.request.get('http://127.0.0.1:5238/WriterReview/Panel?bookId=13&chapterId=21')).status(),404);assert.deepEqual(errors,[]);await c.close();}
|
||||
console.log('PASS integrated Review browser/simulated PWA: canonical Reader, accepted scene context, selection-only no writes, anchored create/edit/resolve/reopen, repeat guard, stale multi-window retained draft, network/navigation guards, paragraph versus explicit chapter handoff and acknowledgement, Audio Review DOM/target/note preservation, Focused Reading Previous/Next, Help, narrow overlay and book isolation. Native and media telemetry simulated.');}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1});
|
||||
@ -32,20 +32,21 @@ internal static class ManuscriptReaderTests
|
||||
]
|
||||
};
|
||||
}
|
||||
internal static ManuscriptReaderService FixtureService(Func<ParagraphManuscript?>? snapshot = null, Action? onRead = null)
|
||||
internal static ManuscriptReaderService FixtureService(Func<ParagraphManuscript?>? snapshot = null, Action? onRead = null,bool allowSecondBook=false)
|
||||
{
|
||||
var fixture = Snapshot();
|
||||
var repository = NativeWorkflowTests.Proxy<IParagraphManuscriptRepository>((name, args) => {
|
||||
if (name is not ("Get" or "Status")) throw new Exception("Reader attempted manuscript mutation: " + name);
|
||||
if(allowSecondBook&&(int)args![0]! ==4&&(int)args[1]! ==13)return name=="Get"?Task.FromResult<ParagraphManuscript?>(null):Task.FromResult<ParagraphSyncStatus?>(null);
|
||||
if ((int)args![0]! != 4 || (int)args[1]! != 12) throw new UnauthorizedAccessException();
|
||||
if (name == "Get") onRead?.Invoke();
|
||||
var current = snapshot is null ? fixture : snapshot();
|
||||
return name == "Get" ? Task.FromResult(current) : Task.FromResult(current is null ? null : new ParagraphSyncStatus { Revision = current.Revision });
|
||||
});
|
||||
var books = NativeWorkflowTests.Proxy<IBookRepository>((name, _) => name == "GetAsync"
|
||||
? Task.FromResult<Book?>(new() { BookID = 12, BookTitle = "A Distant Shore", ProjectID = 7 }) : throw new Exception(name));
|
||||
var books = NativeWorkflowTests.Proxy<IBookRepository>((name, args) => name == "GetAsync"
|
||||
? Task.FromResult<Book?>(new() { BookID = allowSecondBook?(int)args![0]!:12, BookTitle = "A Distant Shore", ProjectID = 7 }) : throw new Exception(name));
|
||||
var chapters = NativeWorkflowTests.Proxy<IChapterRepository>((name, args) => name switch {
|
||||
"ListByBookAsync" => Task.FromResult<IReadOnlyList<Chapter>>(Chapters),
|
||||
"ListByBookAsync" => Task.FromResult<IReadOnlyList<Chapter>>(allowSecondBook&&(int)args![0]! ==13?[]:Chapters),
|
||||
"GetAsync" => Task.FromResult(Chapters.FirstOrDefault(c => c.ChapterID == (int)args![0]!)),
|
||||
_ => throw new Exception(name)
|
||||
});
|
||||
|
||||
@ -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()),
|
||||
("Review accepted anchors, immutable provenance and author decisions",()=>WriterReviewTests.Run()),
|
||||
("Writer Word verified navigation and acknowledgement",()=>WriterWordTests.Run().GetAwaiter().GetResult()),
|
||||
("Writer inline authoring validation",()=>WriterAuthoringTests.Run()),
|
||||
("Writer 3 destination navigation and scope",()=>WriterNavigationTests.Run().GetAwaiter().GetResult()),
|
||||
|
||||
@ -19,7 +19,8 @@ using PlotLine.ViewModels;
|
||||
// Isolated, loopback-only host: renders real compiled Razor chrome, never starts app workers or connects to a database.
|
||||
internal static class ToolbarBrowserHost
|
||||
{
|
||||
private static readonly ParagraphManuscript readerFixture = ManuscriptReaderTests.Snapshot();
|
||||
private static readonly ParagraphManuscript readerFixture = ReviewSnapshot();
|
||||
private static ParagraphManuscript ReviewSnapshot(){var state=ManuscriptReaderTests.Snapshot();var scene=Guid.NewGuid();state.Scenes=[new(){Id=scene,CanonicalId=31,ChapterId=21}];foreach(var p in state.Paragraphs.Where(p=>p.ChapterId==21&&p.Story))p.SceneId=scene;return state;}
|
||||
private static readonly ParagraphManuscript readerLongFixture = ManuscriptReaderTests.LongSnapshot();
|
||||
private static readonly System.Collections.Concurrent.ConcurrentDictionary<(int User, int Chapter), ChapterGoal> writerGoals = new();
|
||||
|
||||
@ -135,7 +136,7 @@ internal static class ToolbarBrowserHost
|
||||
builder.Services.AddSingleton<IToolbarPreferenceRepository, ToolbarMemoryPreferences>();
|
||||
builder.Services.AddScoped(services => ManuscriptReaderTests.FixtureService(() =>
|
||||
services.GetRequiredService<IHttpContextAccessor>().HttpContext!.Request.Query["reader-error"] == "true"
|
||||
? throw new TimeoutException("Synthetic unavailable manuscript") : services.GetRequiredService<IHttpContextAccessor>().HttpContext!.Request.Query["reader-long"] == "true" ? readerLongFixture : readerFixture));
|
||||
? throw new TimeoutException("Synthetic unavailable manuscript") : services.GetRequiredService<IHttpContextAccessor>().HttpContext!.Request.Query["reader-long"] == "true" ? readerLongFixture : readerFixture,allowSecondBook:true));
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddSingleton<IAppearanceRepository, AppearanceMemoryPreferences>();
|
||||
builder.Services.AddScoped<ApplicationNavigation>(services => new ApplicationNavigation(
|
||||
@ -151,6 +152,7 @@ internal static class ToolbarBrowserHost
|
||||
}));
|
||||
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<PlotLine.Services.Writer.IWriterReviewService,WriterReviewFixture>();
|
||||
builder.Services.AddScoped<IWriterWorkspaceService>(services => FixtureProxy<IWriterWorkspaceService>((name, args) => name switch {
|
||||
"GetDashboardAsync" => Task.FromResult(Writer3Fixture(services.GetRequiredService<IHttpContextAccessor>().HttpContext!)),
|
||||
"GetChapterWorkflowAsync" => Task.FromResult<ChapterWorkflowViewModel?>(new() {
|
||||
|
||||
@ -26,7 +26,7 @@ internal static class WriterNavigationTests
|
||||
_=>throw new Exception(n)});
|
||||
var schedules=NativeWorkflowTests.Proxy<IWritingScheduleService>((n,a)=>n=="GetTodayDashboardAsync"?Task.FromResult(new WritingScheduleDashboardViewModel()):throw new Exception("Navigation attempted schedule mutation "+n));
|
||||
var access=NativeWorkflowTests.Proxy<IProjectAccessService>((n,a)=>Task.FromResult(allowed));
|
||||
var controller=new WriterController(workspace,schedules,books,access);
|
||||
var controller=new WriterController(workspace,schedules,books,access){ControllerContext=new(){HttpContext=new Microsoft.AspNetCore.Http.DefaultHttpContext{User=new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity([new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.NameIdentifier,"4")],"Fixture"))}}};
|
||||
var routes=new Dictionary<string,Func<int,Task<IActionResult>>>{
|
||||
["Home"]=b=>controller.Index(7,b),["Write"]=b=>controller.Write(7,b),["Explore"]=b=>controller.Explore(7,b),
|
||||
["Plan"]=b=>controller.Plan(7,b),["Review"]=b=>controller.Review(7,b),["Reflect"]=b=>controller.Reflect(7,b),["Dashboard"]=b=>controller.Dashboard(7,b)};
|
||||
|
||||
10
PlotLine.Tests/WriterReviewFixture.cs
Normal file
10
PlotLine.Tests/WriterReviewFixture.cs
Normal file
@ -0,0 +1,10 @@
|
||||
using PlotLine.Services.Writer;
|
||||
using PlotLine.Services.Manuscript;
|
||||
using PlotLine.Models;
|
||||
internal sealed class WriterReviewFixture(ManuscriptReaderService reader,IWriterAuthoringService intentions):IWriterReviewService
|
||||
{
|
||||
private static readonly object gate=new();private static readonly Dictionary<Guid,ReviewObservation> rows=[];
|
||||
public async Task<ReviewPanel> Read(int actor,int book,int chapter,Guid? paragraph,string? version,int page,Guid? endParagraph=null){var source=await reader.Read(actor,book,chapter)??throw new KeyNotFoundException();var selected=source.ContentVersion==version?source.Paragraphs.FirstOrDefault(p=>p.Id==paragraph):null;var context=await intentions.Read(actor,12,21,selected?.SceneID);if(chapter!=21)context=new(){BookID=12,ChapterID=chapter,Chapter=source.Chapter!,Sections=context.Sections.Where(x=>x.Kind is "Chapter" or "Goals").ToArray()};lock(gate){var found=rows.Values.Where(r=>r.UserID==actor&&r.BookID==book&&r.ChapterID==chapter).OrderByDescending(x=>x.CreatedUtc).Skip((page-1)*50).Take(51).ToArray();foreach(var row in found)row.AnchorState=WriterReviewService.AnchorState(row,source);return new(context,found.Take(50).ToArray(),page,found.Length>50,selected?.SceneID!=null?"Scene context comes from accepted paragraph assignments.":"No verified scene assignment; chapter intentions remain available.");}}
|
||||
public async Task<ReviewObservation> Save(int actor,ReviewSave r){var source=await reader.Read(actor,r.BookID,r.ChapterID)??throw new KeyNotFoundException();var error=WriterReviewService.Validate(r);if(error.Length>0)throw new ArgumentException(error);lock(gate){if(r.Version==0){if(rows.TryGetValue(r.ID,out var existing)){if(existing.UserID==actor&&existing.Observation==r.Observation)return existing;throw new AuthoringConflictException("Observation changed; your text is retained.");}if(source.ContentVersion!=r.ContentVersion)throw new AuthoringConflictException("Accepted chapter changed; your text is retained.");var anchors=WriterReviewService.Anchor(source,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset);var row=new ReviewObservation{ID=r.ID,UserID=actor,BookID=r.BookID,ChapterID=r.ChapterID,ContentVersion=r.ContentVersion,ManuscriptID=source.ManuscriptID,SnapshotRevision=source.Revision,StartParagraph=r.StartParagraph,EndParagraph=r.EndParagraph,StartOffset=r.StartOffset,EndOffset=r.EndOffset,AnchorHash=anchors.Length>0?WriterReviewService.Hash(anchors):null,SceneID=anchors.FirstOrDefault()?.SceneID,Observation=r.Observation,Decision=r.Decision,Status=r.Status,Version=1,CreatedUtc=DateTime.UtcNow,UpdatedUtc=DateTime.UtcNow};rows[r.ID]=row;return row;}
|
||||
if(!rows.TryGetValue(r.ID,out var saved)||saved.UserID!=actor||saved.BookID!=r.BookID||saved.ChapterID!=r.ChapterID||saved.Version!=r.Version)throw new AuthoringConflictException("Another window changed this observation; your text is retained.");saved.Observation=r.Observation;saved.Decision=r.Decision;saved.Status=r.Status;saved.Version++;saved.UpdatedUtc=DateTime.UtcNow;return saved;}}
|
||||
}
|
||||
18
PlotLine.Tests/WriterReviewTests.cs
Normal file
18
PlotLine.Tests/WriterReviewTests.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services.Writer;
|
||||
using PlotLine.Services.Manuscript;
|
||||
internal static class WriterReviewTests
|
||||
{
|
||||
public static void Run(){void Check(bool ok,string message){if(!ok)throw new Exception(message);}void Reject(Action action){try{action();}catch(ArgumentException){return;}throw new Exception("Invalid accepted reference was accepted");}
|
||||
var first=Guid.NewGuid();var last=Guid.NewGuid();var manuscript=Guid.NewGuid();var rows=new ReaderParagraph[]{new(first,"A saved paragraph",false,31),new(last,"Another saved paragraph",false,31)};
|
||||
var source=new ManuscriptReaderModel{Book=new(){BookID=12,ProjectID=7},Chapter=new(){ChapterID=21,BookID=12},Chapters=[],Paragraphs=rows,ManuscriptID=manuscript,Revision=4};
|
||||
Check(WriterReviewService.Anchor(source,first,last,2,7).Length==2,"multi-paragraph accepted range");Reject(()=>WriterReviewService.Anchor(source,Guid.NewGuid(),last,0,3));Reject(()=>WriterReviewService.Anchor(source,last,first,0,3));Reject(()=>WriterReviewService.Anchor(source,first,first,-1,3));Reject(()=>WriterReviewService.Anchor(source,first,first,6,2));Reject(()=>WriterReviewService.Anchor(source,first,last,0,1000));Check(WriterReviewService.Anchor(source,null,null,null,null).Length==0,"chapter observation claims no passage");
|
||||
var row=new ReviewObservation{ManuscriptID=manuscript,SnapshotRevision=4,ContentVersion=source.ContentVersion,StartParagraph=first,EndParagraph=last,StartOffset=2,EndOffset=7,AnchorHash=WriterReviewService.Hash(rows)};
|
||||
Check(WriterReviewService.AnchorState(row,source)=="Current","same accepted IDs and paragraph content retain anchor");var original=row.ContentVersion;
|
||||
var changed=new ManuscriptReaderModel{Book=source.Book,Chapter=source.Chapter,Chapters=[],Paragraphs=[new(first,"Changed saved paragraph",false,31),rows[1]],ManuscriptID=manuscript,Revision=5};Check(WriterReviewService.AnchorState(row,changed)=="Changed"&&row.ContentVersion==original&&row.SnapshotRevision==4,"changed prose preserves original accepted reference");
|
||||
var replaced=new ManuscriptReaderModel{Book=source.Book,Chapter=source.Chapter,Chapters=[],Paragraphs=[new(Guid.NewGuid(),rows[0].Text,false),rows[1]],ManuscriptID=manuscript};Check(WriterReviewService.AnchorState(row,replaced)=="Missing or changed","same prose under another identity is never silently reanchored");
|
||||
var other=new ManuscriptReaderModel{Book=source.Book,Chapter=source.Chapter,Chapters=[],Paragraphs=rows,ManuscriptID=Guid.NewGuid()};Check(WriterReviewService.AnchorState(row,other)=="Different manuscript","document replacement invalidates precise anchor");
|
||||
foreach(var state in new[]{"Open","Working","Resolved"})Check(WriterReviewService.Validate(new(){ID=Guid.NewGuid(),Observation="An author observation",Status=state})=="","author lifecycle state");Check(WriterReviewService.Validate(new(){ID=Guid.NewGuid(),Observation=" "}).Length>0,"empty observations rejected");Check(WriterReviewService.Validate(new(){ID=Guid.NewGuid(),Observation="Valid",Status="Drafted"}).Length>0,"scene revision status is not an observation status");
|
||||
Check(ManuscriptReaderModel.Fingerprint(rows)!=ManuscriptReaderModel.Fingerprint([new(first,rows[0].Text,false,32),rows[1]]),"scene remapping refreshes accepted Reader context even without changed prose");
|
||||
}
|
||||
}
|
||||
@ -25,6 +25,8 @@ internal static class WriterWordTests
|
||||
Check(!await service.Navigate(7,12,99,null,instance,session,manuscript,2,Guid.NewGuid()),"foreign chapter rejected before native queue");Check(!await service.Navigate(7,12,21,999,instance,session,manuscript,2,Guid.NewGuid()),"foreign scene rejected");Check(await service.Navigate(7,12,21,null,instance,session,manuscript,2,Guid.NewGuid()),"authorised exact canonical chapter heading navigates without scene guesses");
|
||||
var queued=store.TakeNavigation(7,"grant",instance,session)!;var completed=State();completed.NavigationAcknowledgedId=queued.Id;completed.NavigationResult="completed";Put(completed);
|
||||
var sceneRequest=Guid.NewGuid();Check(await service.Navigate(7,12,21,31,instance,session,manuscript,2,sceneRequest),"verified canonical scene start navigates without title matching");store.TakeNavigation(7,"grant",instance,session);completed=State();completed.NavigationAcknowledgedId=sceneRequest;completed.NavigationResult="completed";Put(completed);
|
||||
snapshot.Paragraphs[1].ChapterId=21;var paragraph=snapshot.Paragraphs[1].Occurrence.Id;
|
||||
Check(!await service.Navigate(7,12,21,null,instance,session,manuscript,2,Guid.NewGuid(),paragraph,4),"stale accepted paragraph version cannot navigate");var paragraphRequest=Guid.NewGuid();Check(await service.Navigate(7,12,21,null,instance,session,manuscript,2,paragraphRequest,paragraph,5),"exact accepted paragraph reuses acknowledged navigation without offset guessing");store.TakeNavigation(7,"grant",instance,session);completed=State();completed.NavigationAcknowledgedId=paragraphRequest;completed.NavigationResult="completed";Put(completed);
|
||||
var modern=State();modern.CanChapterSync=true;Put(modern);bool currentCheckpoint=false;
|
||||
var liveCheckpoints=NativeWorkflowTests.Proxy<IChapterSyncRepository>((n,a)=>n switch{
|
||||
"List"=>Task.FromResult<IReadOnlyList<ChapterLiveValidation>>([new(){ChapterID=21,SessionID=session,WordRevision=2,StartPosition=200}]),
|
||||
|
||||
@ -52,7 +52,7 @@ public sealed class ManuscriptReaderController(ManuscriptReaderService reader, I
|
||||
{
|
||||
bookId, chapterId, revision = model.Revision.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
version = model.ContentVersion, title = model.Chapter!.ChapterTitle,
|
||||
paragraphs = model.Paragraphs.Select(p => new { id = p.Id, text = p.Text, isHeading = p.IsHeading }),
|
||||
paragraphs = model.Paragraphs.Select(p => new { id = p.Id, text = p.Text, isHeading = p.IsHeading, sceneId=p.SceneID }),
|
||||
lastSuccessfulSyncUtc = model.LastSuccessfulSyncUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ"),
|
||||
snapshotCapturedUtc = model.SnapshotCapturedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ")
|
||||
});
|
||||
|
||||
@ -19,7 +19,19 @@ public sealed class WriterController(
|
||||
public Task<IActionResult> Write(int? projectId, int? bookId = null) => LoadDestination("Write", projectId, bookId);
|
||||
public Task<IActionResult> Explore(int? projectId, int? bookId = null) => LoadDestination("Explore", projectId, bookId);
|
||||
public Task<IActionResult> Plan(int? projectId, int? bookId = null) => LoadDestination("Plan", projectId, bookId);
|
||||
public Task<IActionResult> Review(int? projectId, int? bookId = null) => LoadDestination("Review", projectId, bookId);
|
||||
[ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
|
||||
public async Task<IActionResult> Review(int? projectId,int? bookId=null,int? chapterId=null,bool focus=false,[FromServices] PlotLine.Services.Manuscript.ManuscriptReaderService? reader=null)
|
||||
{
|
||||
Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive";
|
||||
var result=await LoadDestination("Review",projectId,bookId);
|
||||
if(result is ViewResult {Model:WriterDashboardViewModel model}&&model.BookID.HasValue&&reader!=null){
|
||||
try{model.ReviewReader=await reader.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),model.BookID.Value,chapterId);if(model.ReviewReader==null)return NotFound();model.ReviewReader.FocusReading=focus;model.ReviewReader.IntegratedReview=true;}
|
||||
catch(UnauthorizedAccessException){return NotFound();}
|
||||
catch(SqlException e)when(e.Number==51000){return NotFound();}
|
||||
catch(Exception e)when(e is SqlException or TimeoutException or System.Text.Json.JsonException){Response.StatusCode=503;return View("~/Views/ManuscriptReader/Unavailable.cshtml",new{BookId=model.BookID,ChapterId=chapterId});}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
public Task<IActionResult> Reflect(int? projectId, int? bookId = null) => LoadDestination("Reflect", projectId, bookId);
|
||||
public Task<IActionResult> Dashboard(int? projectId, int? bookId = null) => LoadDestination("Dashboard", projectId, bookId);
|
||||
public Task<IActionResult> Overview(int? projectId, int? bookId = null) => LoadDestination("Legacy", projectId, bookId);
|
||||
|
||||
15
PlotLine/Controllers/WriterReviewController.cs
Normal file
15
PlotLine/Controllers/WriterReviewController.cs
Normal file
@ -0,0 +1,15 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlotLine.Services.Writer;
|
||||
namespace PlotLine.Controllers;
|
||||
[Authorize]
|
||||
public sealed class WriterReviewController(IWriterReviewService review):Controller
|
||||
{
|
||||
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
[HttpGet]
|
||||
public Task<IActionResult> Panel(int bookId,int chapterId,Guid? paragraphId,string? version,int page=1,Guid? endParagraphId=null)=>Run(async()=>PartialView("~/Views/Writer/_ReviewContext.cshtml",await review.Read(Author,bookId,chapterId,paragraphId,version,page,endParagraphId)));
|
||||
[HttpPost,ValidateAntiForgeryToken]
|
||||
public Task<IActionResult> Save(ReviewSave request)=>Run(async()=>{if(!ModelState.IsValid)return BadRequest(new{message="Review details are invalid. Your text is retained."});var row=await review.Save(Author,request);return Json(new{success=true,id=row.ID,version=row.Version});});
|
||||
private async Task<IActionResult> Run(Func<Task<IActionResult>> work){Response.Headers.CacheControl="no-store";Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive";try{return await work();}catch(AuthoringConflictException e){return Conflict(new{message=e.Message});}catch(ArgumentException e){return BadRequest(new{message=e.Message});}catch(Exception e)when(e is UnauthorizedAccessException or KeyNotFoundException){return NotFound();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51000){return NotFound();}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){return StatusCode(503,new{message="Review information is temporarily unavailable. Your text is retained."});}}
|
||||
}
|
||||
@ -10,12 +10,12 @@ public sealed class WriterWordController(WriterWordService words,IWordCompanionR
|
||||
{
|
||||
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
[HttpPost,ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Navigate(int bookId,int chapterId,int? sceneId,Guid instanceId,Guid sessionId,Guid manuscriptId,long revision,Guid navigationId)
|
||||
public async Task<IActionResult> Navigate(int bookId,int chapterId,int? sceneId,Guid instanceId,Guid sessionId,Guid manuscriptId,long revision,Guid navigationId,Guid? paragraphId=null,long? acceptedRevision=null)
|
||||
{
|
||||
Response.Headers.CacheControl="no-store";
|
||||
if(!ModelState.IsValid||bookId<=0||chapterId<=0||sceneId is <=0||instanceId==Guid.Empty||sessionId==Guid.Empty||manuscriptId==Guid.Empty||navigationId==Guid.Empty||revision<0)return BadRequest();
|
||||
if(await access.GetBookStructureAsync(bookId,Author)==null)return NotFound();
|
||||
try { return await words.Navigate(Author,bookId,chapterId,sceneId,instanceId,sessionId,manuscriptId,revision,navigationId)?Accepted(new{navigationId,message="Requested in Word; waiting for confirmation."}):Conflict(new{message="This Word document or chapter position is not currently verified, or Word is busy. Check Companion and try again. Nothing was moved."}); }
|
||||
try { return await words.Navigate(Author,bookId,chapterId,sceneId,instanceId,sessionId,manuscriptId,revision,navigationId,paragraphId,acceptedRevision)?Accepted(new{navigationId,message="Requested in Word; waiting for confirmation."}):Conflict(new{message="This Word document or chapter position is not currently verified, or Word is busy. Check Companion and try again. Nothing was moved."}); }
|
||||
catch(UnauthorizedAccessException){return NotFound();}
|
||||
catch(Microsoft.Data.SqlClient.SqlException e) when(e.Number==51000){return NotFound();}
|
||||
catch(Exception e) when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){return StatusCode(503,new{message="Word navigation is temporarily unavailable. Your saved work is retained."});}
|
||||
|
||||
@ -11,12 +11,16 @@ screenshot:
|
||||
|
||||
# Overview
|
||||
|
||||
Explore offers real entry points to the existing Problem Solver questionnaire, its browsable guidance and the story Timeline. It does not generate a new creative analysis merely by opening this page.
|
||||
Explore offers three distinct entry points to your authenticated writing, plot/thread and timeline workspaces. Project and book context stay visible. If you have no project, choose one before developing its plot; Write can help you begin with a book.
|
||||
|
||||
You can use the Problem Solver before you have a project or scenes. Its questions and editorial guidance are separate from manuscript-aware evidence assessment. Saved character, relationship, plot, map, floor-plan and metric tools are linked directly when a project is selected. Some of those tools are project-wide and may include other books.
|
||||
Saved character, relationship, plot, map, floor-plan and metric tools remain directly available. Some tools are project-wide and may include other books. Existing editing, permissions and source records remain authoritative. Opening Explore runs no manuscript analysis and saves no suggested interpretation as a story fact.
|
||||
|
||||
The full specialist workspaces retain their existing editing, permissions and source records. No suggested interpretation silently updates a story fact. Guided idea capture and richer manuscript-aware journeys are later work, not simulated controls here.
|
||||
Guided idea capture and manuscript-aware exploration remain later work; these links open the actual existing tools.
|
||||
|
||||
# Arrange your workspace
|
||||
|
||||
Drag the divider or focus it and use Left/Right arrow keys to resize the contextual companion. Hide companion gives your main task the full width; Show companion restores it. Each destination remembers its width and desktop visibility on this browser. In narrow windows the companion opens as an overlay; use Back to workspace or Escape to return. Workspace Layout Help beside Show/Hide companion explains keyboard controls, storage and the independent standalone Context/Intent windows.
|
||||
|
||||
# Authenticated tools
|
||||
|
||||
Develop a chapter or scene opens Write with the selected project/book; Develop your plot and threads opens the existing authenticated plot workspace; Look at your story's shape opens its timeline. These are distinct existing tools, not the public Problem Solver or a new guided ideation engine. Guided exploration remains a later phase. No analysis runs merely by choosing Explore.
|
||||
|
||||
@ -1,26 +1,22 @@
|
||||
---
|
||||
title: Review Your Writing
|
||||
category: Workspace
|
||||
tags: writer, navigation, review
|
||||
tags: writer, review, manuscript, audio
|
||||
contextKey: writer3.review
|
||||
micro: Read accepted text, revisit intentions and choose revision work.
|
||||
quickTitle: Review Your Writing
|
||||
quickSummary: Read accepted text, revisit intentions and choose revision work.
|
||||
micro: Read accepted manuscript text, inspect intentions and record your own review decisions.
|
||||
quickTitle: Review your writing
|
||||
quickSummary: Read in the integrated canonical Reader, select a passage and explicitly record an observation. Your review selection, writing focus, Word position and recording target remain independent.
|
||||
screenshot:
|
||||
---
|
||||
|
||||
# Overview
|
||||
# Read, notice, decide and return
|
||||
|
||||
Review opens the read-only Manuscript Reader and Focused reading, using your saved focus chapter or the first available chapter. The Reader shows accepted server text, not unsynchronised Word edits. Empty/new chapters explain the need to save and synchronise; no source text is invented.
|
||||
Review begins with the accepted manuscript using the existing Reader. Previous/Next, chapter selection, Focused Reading, selected text, paragraph identities and update controls remain available. Unsynchronised Word changes are not shown. Empty chapters explain how to connect and synchronise Word rather than inventing text.
|
||||
|
||||
# Audio Review
|
||||
The resizable companion shows recorded chapter intentions and scene details only when accepted paragraph assignments support them. Record an observation about what needs attention and optionally what you want to change. Save, edit, resolve or reopen it explicitly. Original accepted-version references remain unchanged when the manuscript changes; missing or changed paragraphs are not silently reanchored by text matching.
|
||||
|
||||
Open the Reader and expand Reading & Audio Review. Select/start the activity explicitly. Playback requires compatible Windows Companion and a supported player. Opening Review or Reader does not play audio. Pause stops external playback when supported; End review stops tracking and saves your note.
|
||||
Return to Word uses the existing verified, acknowledged chapter/paragraph handoff. Paragraph navigation targets its start, not an assumed exact character range. A rejected precise handoff offers a separate chapter action. Reader changes never move Word, retarget a recording or save a working objective.
|
||||
|
||||
# Intent and evidence
|
||||
Reading & Audio Review uses the existing session/media controls and return notes. Observations are separate from session notes, canonical scene revision state and automated findings. Opening Review runs no manuscript analysis.
|
||||
|
||||
Open Intent uses the existing standalone reference window. Its Evidence tab loads saved evidence or explicitly assesses saved scene prose and saved intentions when permitted. Intentions, AI interpretation and author-confirmed checklist completion remain separate. Scenes marked for revision opens the existing Revision workspace. No synchronisation or evidence contract is replaced by this shell.
|
||||
|
||||
# Arrange your workspace
|
||||
|
||||
Drag the divider or focus it and use Left/Right arrow keys to resize the contextual companion. Hide companion gives your main task the full width; Show companion restores it. Each destination remembers its width and desktop visibility on this browser. In narrow windows the companion opens as an overlay; use Back to workspace or Escape to return. Workspace Layout Help beside Show/Hide companion explains keyboard controls, storage and the independent standalone Context/Intent windows.
|
||||
Use Show/Hide companion and keyboard/pointer resizing. On narrow screens the companion opens as an overlay. Each pane scrolls only when its content exceeds the available viewport. See Read, Notice and Decide for observation capture, original references and recovery.
|
||||
|
||||
40
PlotLine/Help/Articles/Workspace/Writer3-reviewing.md
Normal file
40
PlotLine/Help/Articles/Workspace/Writer3-reviewing.md
Normal file
@ -0,0 +1,40 @@
|
||||
---
|
||||
title: Read, Notice and Decide
|
||||
category: Workspace
|
||||
tags: review, reader, observations, revisions, Word, audio
|
||||
contextKey: writer3.reviewing
|
||||
micro: Read accepted writing, record what you notice and choose what to change; Word and your working focus stay independent.
|
||||
quickTitle: Review observations
|
||||
quickSummary: Select a paragraph or passage, then explicitly record an observation. Save its decision separately from scene revision state. Changed or missing references retain their original accepted-version context.
|
||||
screenshot:
|
||||
---
|
||||
|
||||
# Read accepted writing
|
||||
|
||||
Review embeds the same canonical Manuscript Reader. Choose a chapter, use Previous/Next or enter Focused Reading. These retain Review mode and do not change your saved working focus, actual session target or Word position. Reader contains accepted text, not every unsaved Word keystroke. Accepted manuscript details show available synchronisation times. If there is no accepted text, connect and synchronise the correct manuscript through Word Companion; you can still inspect recorded intentions.
|
||||
|
||||
Reader uses its existing update policy. Selected text and paused updates defer content replacement. Surviving paragraph anchors preserve reading position where possible. While an observation editor is open, automatic content updates pause; Save or Cancel restores your previous pause preference. An update never resolves an observation automatically.
|
||||
|
||||
# Inspect intentions
|
||||
|
||||
The companion shows recorded chapter intentions. A selected accepted passage can show scene intentions, outcome, notes, reminders and state only when its paragraph assignments identify one scene reliably. Otherwise chapter context remains available. Details and editing opens the existing canonical chapter/scene editors in another window; this does not adopt a new working focus. No story facts are invented to fill an empty panel.
|
||||
|
||||
# Record an observation
|
||||
|
||||
Select text or click an accepted paragraph, then choose Record an observation or Something here needs attention. Enter what you noticed and, optionally, what you want to change. Selection alone saves nothing. Use a chapter-level reference explicitly if no precise passage is appropriate.
|
||||
|
||||
Each observation retains its original accepted version and stable paragraph identities, with selection offsets when available. It does not store a duplicate quote. Save records your text; Cancel saves nothing. Failures and stale saves retain your draft. Save or Cancel before changing observation pages or reloading the list. Navigation warns before leaving unsaved work. Observations are private to their author within an accessible book.
|
||||
|
||||
Needs attention, Working on it and Resolved describe your observation, not the scene's canonical revision status. Edit / change decision lets you resolve or reopen it explicitly. Changes to prose, checklist completion or an ended session never resolve it automatically.
|
||||
|
||||
# Revisit or return to Word
|
||||
|
||||
Revisit reference uses the original paragraph identity, never a search for similar text. If it changed or disappeared, the original reference remains recorded. Review explains the limitation instead of attaching it to another passage.
|
||||
|
||||
Return to Word reuses the verified, acknowledged Companion handoff. Open paragraph in Word means the start of a verified current paragraph; it does not claim an exact selected-character location. If that reference is missing, changed or unverified, use the separate chapter action after checking the correct document. A rejected paragraph request does not automatically move Word elsewhere. Only Word confirmed navigation indicates an acknowledgement; requested or timed out is not completion. No save, session start/end, objective update or document replacement is forced.
|
||||
|
||||
# Listen and distinguish sources
|
||||
|
||||
Expand Reading & Audio Review to use the existing recording and supported native playback controls. Record observations while preserving the actual session target, playback and return note. Audio time is not a paragraph anchor. Native pause-on-edit and media safeguards are unchanged.
|
||||
|
||||
Your observations are distinct from recorded intentions and saved automated findings. Saved assessments & other tools opens existing Intent evidence, Context and the book's analysis/review tools. Opening Review starts no analysis. Assessments remain explicit actions with their original provenance and freshness.
|
||||
@ -200,6 +200,7 @@ public class Program
|
||||
builder.Services.AddScoped<IWordCompanionRepository, WordCompanionRepository>();
|
||||
builder.Services.AddScoped<WritingActivityRepository>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Writer.WriterWordService>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Writer.IWriterReviewService,PlotLine.Services.Writer.WriterReviewService>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Writer.IWriterAuthoringService, PlotLine.Services.Writer.WriterAuthoringService>();
|
||||
builder.Services.AddScoped<WriterObjectiveRepository>();
|
||||
builder.Services.AddScoped<WriterWorkRepository>();
|
||||
|
||||
@ -5,26 +5,30 @@ using PlotLine.Models;
|
||||
|
||||
namespace PlotLine.Services.Manuscript;
|
||||
|
||||
public sealed record ReaderParagraph(Guid Id, string Text, bool IsHeading);
|
||||
public sealed record ReaderParagraph(Guid Id, string Text, bool IsHeading,int? SceneID=null);
|
||||
public sealed class ManuscriptReaderModel
|
||||
{
|
||||
public PlotLine.Services.Writer.WriterContext WorkingContext => new PlotLine.Services.Writer.WriterContext(Book.ProjectID, Book.BookID)
|
||||
.Select(PlotLine.Services.Writer.WriterFocusRole.Reader, new(Book.ProjectID, Book.BookID, Chapter?.ChapterID));
|
||||
public long Revision { get; init; } = -1;
|
||||
public bool FocusReading { get; set; }
|
||||
public string ContentVersion => Fingerprint(Paragraphs);
|
||||
public bool IntegratedReview {get;set;}
|
||||
public Guid? ManuscriptID {get;init;}
|
||||
public string ContentVersion => Fingerprint(Paragraphs,ManuscriptID);
|
||||
|
||||
public static string Fingerprint(IReadOnlyList<ReaderParagraph> paragraphs)
|
||||
public static string Fingerprint(IReadOnlyList<ReaderParagraph> paragraphs,Guid? manuscript=null)
|
||||
{
|
||||
using var buffer = new MemoryStream();
|
||||
using (var writer = new BinaryWriter(buffer, Encoding.UTF8, leaveOpen: true))
|
||||
{
|
||||
writer.Write(manuscript.GetValueOrDefault().ToByteArray());
|
||||
writer.Write(paragraphs.Count);
|
||||
foreach (var paragraph in paragraphs)
|
||||
{
|
||||
writer.Write(paragraph.Id.ToByteArray());
|
||||
writer.Write(paragraph.Text);
|
||||
writer.Write(paragraph.IsHeading);
|
||||
writer.Write(paragraph.SceneID??0);
|
||||
}
|
||||
}
|
||||
return Convert.ToHexString(SHA256.HashData(buffer.GetBuffer().AsSpan(0, (int)buffer.Length)));
|
||||
@ -96,12 +100,12 @@ public sealed class ManuscriptReaderService(
|
||||
}
|
||||
}
|
||||
var rows = source.OrderBy(p => p.Occurrence.Ordinal)
|
||||
.Select(p => new ReaderParagraph(p.Occurrence.Id, p.Occurrence.Text, p.Occurrence.Id == heading || p.Occurrence.Outline is >= 1 and <= 6))
|
||||
.Select(p => new ReaderParagraph(p.Occurrence.Id, p.Occurrence.Text, p.Occurrence.Id == heading || p.Occurrence.Outline is >= 1 and <= 6, state?.Scenes.FirstOrDefault(s=>s.Id==p.SceneId&&!s.Retired&&s.CanonicalId>0&&s.ChapterId==selected?.ChapterID)?.CanonicalId))
|
||||
.ToArray();
|
||||
var checkpoint = state?.ChapterCheckpoints.FirstOrDefault(c => c.ChapterId == selected?.ChapterID);
|
||||
return new()
|
||||
{
|
||||
Revision = state?.Revision ?? -1,
|
||||
Revision = state?.Revision ?? -1, ManuscriptID=state?.ManuscriptId,
|
||||
Book = book, Chapters = ordered, Chapter = selected, Paragraphs = rows,
|
||||
PreviousId = index > 0 ? ordered[index - 1].ChapterID : null,
|
||||
NextId = index >= 0 && index + 1 < ordered.Count ? ordered[index + 1].ChapterID : null,
|
||||
|
||||
@ -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" },
|
||||
["WriterReview"] = new(StringComparer.OrdinalIgnoreCase) { ["bookId"]="Book",["chapterId"]="Chapter" },
|
||||
["WriterWord"] = new(StringComparer.OrdinalIgnoreCase) { ["bookId"] = "Book", ["chapterId"] = "Chapter", ["sceneId"] = "Scene" },
|
||||
["WriterAuthoring"] = new(StringComparer.OrdinalIgnoreCase) { ["bookId"] = "Book", ["chapterId"] = "Chapter", ["sceneId"] = "Scene" },
|
||||
["Writer"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "Chapter", ["projectId"] = "Project" },
|
||||
|
||||
62
PlotLine/Services/Writer/WriterReviewService.cs
Normal file
62
PlotLine/Services/Writer/WriterReviewService.cs
Normal file
@ -0,0 +1,62 @@
|
||||
using System.Data;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Dapper;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services.Manuscript;
|
||||
namespace PlotLine.Services.Writer;
|
||||
public sealed class ReviewObservation
|
||||
{
|
||||
public Guid ID{get;set;}public int UserID{get;set;}public int BookID{get;set;}public int ChapterID{get;set;}
|
||||
public Guid? ManuscriptID{get;set;}public long SnapshotRevision{get;set;}public string ContentVersion{get;set;}="";
|
||||
public Guid? StartParagraph{get;set;}public Guid? EndParagraph{get;set;}public int? StartOffset{get;set;}public int? EndOffset{get;set;}public string? AnchorHash{get;set;}public int? SceneID{get;set;}
|
||||
public string Observation{get;set;}="";public string? Decision{get;set;}public string Status{get;set;}="Open";public int Version{get;set;}public DateTime CreatedUtc{get;set;}public DateTime UpdatedUtc{get;set;}
|
||||
public string AnchorState{get;set;}="Chapter";
|
||||
}
|
||||
public sealed class ReviewSave
|
||||
{
|
||||
public int BookID{get;set;}public int ChapterID{get;set;}public Guid ID{get;set;}public int Version{get;set;}
|
||||
public string ContentVersion{get;set;}="";public Guid? StartParagraph{get;set;}public Guid? EndParagraph{get;set;}public int? StartOffset{get;set;}public int? EndOffset{get;set;}
|
||||
public string Observation{get;set;}="";public string? Decision{get;set;}public string Status{get;set;}="Open";
|
||||
}
|
||||
public sealed record ReviewPanel(WriterAuthoringPage Intentions,IReadOnlyList<ReviewObservation> Observations,int Page,bool HasMore,string ReferenceMessage);
|
||||
public interface IWriterReviewService
|
||||
{
|
||||
Task<ReviewPanel> Read(int actor,int book,int chapter,Guid? paragraph,string? version,int page,Guid? endParagraph=null);
|
||||
Task<ReviewObservation> Save(int actor,ReviewSave request);
|
||||
}
|
||||
public sealed class WriterReviewService(ISqlConnectionFactory factory,ManuscriptReaderService reader,IWriterAuthoringService intentions):IWriterReviewService
|
||||
{
|
||||
public static string Hash(IEnumerable<ReaderParagraph> paragraphs){using var buffer=new MemoryStream();using(var writer=new BinaryWriter(buffer,Encoding.UTF8,true))foreach(var p in paragraphs){writer.Write(p.Id.ToByteArray());writer.Write(p.Text);}return Convert.ToHexString(SHA256.HashData(buffer.ToArray()));}
|
||||
public static string Validate(ReviewSave r)=>r.ID==Guid.Empty||r.Version<0?"Choose a valid observation.":r.Status is not("Open" or "Working" or "Resolved")?"Choose a valid observation state.":string.IsNullOrWhiteSpace(r.Observation)?"Record what you noticed before saving.":r.Observation.Length>10000||(r.Decision?.Length??0)>10000?"Keep each observation and decision within 10,000 characters.":"";
|
||||
public static ReaderParagraph[] Anchor(ManuscriptReaderModel model,Guid? first,Guid? last,int? start,int? end){
|
||||
if(first==null&&last==null&&start==null&&end==null)return [];
|
||||
var rows=model.Paragraphs.ToArray();var from=Array.FindIndex(rows,p=>p.Id==first);var to=Array.FindIndex(rows,p=>p.Id==last);
|
||||
if(from<0||to<from||start is null or <0||end is null or <0||start>rows[from].Text.Length||end>rows[to].Text.Length||from==to&&end<start)throw new ArgumentException("The selected passage is unavailable. Keep your text and explicitly choose a chapter observation or refresh the accepted chapter.");
|
||||
return rows[from..(to+1)];
|
||||
}
|
||||
public static string AnchorState(ReviewObservation row,ManuscriptReaderModel current){
|
||||
if(row.StartParagraph==null)return "Chapter";
|
||||
if(row.ManuscriptID!=current.ManuscriptID)return "Different manuscript";
|
||||
try{var rows=Anchor(current,row.StartParagraph,row.EndParagraph,row.StartOffset,row.EndOffset);return Hash(rows)==row.AnchorHash?"Current":"Changed";}catch(ArgumentException){return "Missing or changed";}
|
||||
}
|
||||
public async Task<ReviewPanel> Read(int actor,int book,int chapter,Guid? paragraph,string? version,int page,Guid? endParagraph=null){
|
||||
if(page<1||page>100000)throw new ArgumentException("Choose a valid observations page.");var source=await reader.Read(actor,book,chapter)??throw new KeyNotFoundException();
|
||||
var selected=source.ContentVersion==version?source.Paragraphs.SingleOrDefault(p=>p.Id==paragraph):null;
|
||||
int? selectedScene=selected?.SceneID;
|
||||
if(selected!=null&&endParagraph.HasValue){var all=source.Paragraphs.ToArray();var first=Array.FindIndex(all,p=>p.Id==selected.Id);var last=Array.FindIndex(all,p=>p.Id==endParagraph);if(last<first||all[first..(last+1)].Any(p=>p.SceneID!=selectedScene))selectedScene=null;}
|
||||
WriterAuthoringPage context;
|
||||
try{context=await intentions.Read(actor,book,chapter,selectedScene);}
|
||||
catch(Exception e)when(selectedScene.HasValue&&(e is KeyNotFoundException||e is Microsoft.Data.SqlClient.SqlException {Number:51000})){selectedScene=null;context=await intentions.Read(actor,book,chapter,null);}
|
||||
using var db=factory.CreateConnection();var rows=(await db.QueryAsync<ReviewObservation>("dbo.WriterReview_Observations",new{Action="list",UserID=actor,BookID=book,ChapterID=chapter,Page=page},commandType:CommandType.StoredProcedure)).ToArray();foreach(var row in rows)row.AnchorState=AnchorState(row,source);
|
||||
return new(context,rows.Take(50).ToArray(),page,rows.Length>50,selectedScene!=null?"Scene context comes from accepted paragraph assignments.":paragraph.HasValue?"No current verified scene assignment for this passage. Chapter intentions remain available.":"Chapter intentions; choose a recorded passage for verified scene context.");
|
||||
}
|
||||
public async Task<ReviewObservation> Save(int actor,ReviewSave r){
|
||||
var error=Validate(r);if(error.Length>0)throw new ArgumentException(error);
|
||||
ManuscriptReaderModel? source=null;ReaderParagraph[] rows=[];
|
||||
if(r.Version==0){source=await reader.Read(actor,r.BookID,r.ChapterID)??throw new KeyNotFoundException();if(r.ContentVersion!=source.ContentVersion)throw new AuthoringConflictException("The accepted chapter changed. Your observation text is retained. Refresh the manuscript before choosing its reference again.");rows=Anchor(source,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset);}
|
||||
int? scene=rows.Length>0&&rows[0].SceneID.HasValue&&rows.All(p=>p.SceneID==rows[0].SceneID)?rows[0].SceneID:null;
|
||||
using var db=factory.CreateConnection();try{return await db.QuerySingleAsync<ReviewObservation>("dbo.WriterReview_Observations",new{Action=r.Version==0?"create":"update",UserID=actor,r.BookID,r.ChapterID,r.ID,r.Version,ManuscriptID=source?.ManuscriptID,SnapshotRevision=source?.Revision,ContentVersion=source?.ContentVersion,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset,AnchorHash=rows.Length>0?Hash(rows):null,SceneID=scene,r.Observation,r.Decision,r.Status},commandType:CommandType.StoredProcedure);}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){throw new AuthoringConflictException("The observation or accepted manuscript changed. Your text is retained. Reload the recorded observations before retrying.",e);}
|
||||
}
|
||||
}
|
||||
@ -13,14 +13,19 @@ public sealed class WriterWordService(ISqlConnectionFactory factory,IWordCompani
|
||||
private static T? One<T>(IEnumerable<T> rows) where T:class {var candidates=rows.Take(2).ToArray();return candidates.Length==1?candidates[0]:null;}
|
||||
public async Task<WriterWordMetadata?> Metadata(int user,int book,int? chapter){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<WriterWordMetadata>("dbo.WriterWord_Status",new{UserID=user,BookID=book,ChapterID=chapter},commandType:CommandType.StoredProcedure);}
|
||||
public async Task<ParagraphPosition?> Position(int user,NativeLease lease,WriterWordMetadata? metadata){var p=lease.Position;if(p.WordSaved!=true||!p.WordAvailable||!p.CursorStart.HasValue||metadata?.ManuscriptID!=p.ManuscriptId)return null;var position=p.CanChapterSync?await chapters.Position(user,p.BookId,p.ManuscriptId,lease.Session,p.Revision,p.CursorStart.Value):await paragraphs.Position(user,p.BookId,p.ManuscriptId,lease.Session,p.Revision,p.CursorStart.Value);return position?.HasSnapshot==true&&position.Revision==metadata.Revision?position:null;}
|
||||
public async Task<bool> Navigate(int user,int book,int chapter,int? scene,Guid instance,Guid session,Guid manuscript,long revision,Guid id)
|
||||
public async Task<bool> Navigate(int user,int book,int chapter,int? scene,Guid instance,Guid session,Guid manuscript,long revision,Guid id,Guid? paragraphId=null,long? acceptedRevision=null)
|
||||
{
|
||||
var structure=await access.GetBookStructureAsync(book,user);var target=structure==null?null:One(structure.Chapters.Where(c=>c.ChapterId==chapter));if(target==null||scene.HasValue&&!target.Scenes.Any(s=>s.SceneId==scene))return false;
|
||||
var lease=One(presence.Read(user,book).Where(l=>l.Instance==instance&&l.Session==session&&l.Position.ManuscriptId==manuscript&&l.Position.Revision==revision&&l.Position.WordAvailable&&l.Position.WordSaved==true&&l.Position.CanAcknowledgeNavigation));
|
||||
if(lease==null)return false;
|
||||
var state=await paragraphs.Get(user,book);if(state==null||state.ManuscriptId!=manuscript)return false;
|
||||
int? start=null;
|
||||
if(scene.HasValue){
|
||||
if(paragraphId.HasValue){
|
||||
if(acceptedRevision!=state.Revision)return false;
|
||||
var targetParagraph=One(state.Paragraphs.Where(p=>p.Occurrence.Id==paragraphId&&p.ChapterId==chapter&&p.PositionVerified));if(targetParagraph==null)return false;
|
||||
if(lease.Position.CanChapterSync){using var db=factory.CreateConnection();var anchors=await db.QueryAsync<ChapterSceneAnchor>("dbo.WriterReview_ParagraphStart",new{UserID=user,BookID=book,ChapterID=chapter,ParagraphID=paragraphId,ManuscriptID=manuscript,SessionID=session,WordRevision=revision,AcceptedRevision=acceptedRevision},commandType:CommandType.StoredProcedure);var anchor=One(anchors);if(anchor?.Revision==state.Revision&&anchor.ChapterID==chapter)start=anchor.StartPosition;}
|
||||
else if(state.SessionId==session&&state.WordRevision==revision)start=targetParagraph.Occurrence.Start;
|
||||
}else if(scene.HasValue){
|
||||
var saved=One(state.Scenes.Where(s=>!s.Retired&&s.CanonicalId==scene&&s.ChapterId==chapter));var first=saved==null?null:state.Paragraphs.Where(p=>p.Story&&p.SceneId==saved.Id).OrderBy(p=>p.Occurrence.Ordinal).FirstOrDefault();
|
||||
if(first?.PositionVerified!=true)return false;
|
||||
if(lease.Position.CanChapterSync){var anchor=await chapters.SceneStart(user,book,scene.Value,first.Occurrence.Id,manuscript,session,revision);if(anchor?.Revision==state.Revision&&anchor.ChapterID==chapter&&anchor.SceneID==scene)start=anchor.StartPosition;}
|
||||
|
||||
70
PlotLine/Sql/272_WriterReviewObservations.sql
Normal file
70
PlotLine/Sql/272_WriterReviewObservations.sql
Normal file
@ -0,0 +1,70 @@
|
||||
-- Author-private review observations: accepted-version/paragraph references are immutable.
|
||||
-- Existing scene/session notes have neither chapter-level scope nor accepted-version anchors.
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
IF OBJECT_ID('dbo.WriterReviewObservations','U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.WriterReviewObservations(
|
||||
ID uniqueidentifier NOT NULL PRIMARY KEY,UserID int NOT NULL,BookID int NOT NULL,ChapterID int NOT NULL,
|
||||
ManuscriptID uniqueidentifier NULL,SnapshotRevision bigint NOT NULL,ContentVersion char(64) NOT NULL,
|
||||
StartParagraph uniqueidentifier NULL,EndParagraph uniqueidentifier NULL,StartOffset int NULL,EndOffset int NULL,
|
||||
AnchorHash char(64) NULL,SceneID int NULL,Observation nvarchar(max) NOT NULL,Decision nvarchar(max) NULL,
|
||||
Status varchar(16) NOT NULL DEFAULT 'Open',Version int NOT NULL DEFAULT 1,
|
||||
CreatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),UpdatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),
|
||||
CONSTRAINT FK_WriterReview_User FOREIGN KEY(UserID) REFERENCES dbo.AppUser(UserID) ON DELETE CASCADE,
|
||||
CONSTRAINT FK_WriterReview_Chapter FOREIGN KEY(ChapterID) REFERENCES dbo.Chapters(ChapterID) ON DELETE CASCADE,
|
||||
CONSTRAINT FK_WriterReview_Book FOREIGN KEY(BookID) REFERENCES dbo.Books(BookID),
|
||||
CONSTRAINT CK_WriterReview_Status CHECK(Status IN('Open','Working','Resolved')),
|
||||
CONSTRAINT CK_WriterReview_Anchor CHECK((StartParagraph IS NULL AND EndParagraph IS NULL AND StartOffset IS NULL AND EndOffset IS NULL AND AnchorHash IS NULL) OR (StartParagraph IS NOT NULL AND EndParagraph IS NOT NULL AND StartOffset>=0 AND EndOffset>=0 AND AnchorHash IS NOT NULL))
|
||||
);
|
||||
CREATE INDEX IX_WriterReview_Scope ON dbo.WriterReviewObservations(UserID,BookID,ChapterID,CreatedUtc DESC,ID);
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.WriterReview_Observations @Action varchar(12),@UserID int,@BookID int,@ChapterID int,@ID uniqueidentifier=NULL,@Version int=0,
|
||||
@ManuscriptID uniqueidentifier=NULL,@SnapshotRevision bigint=NULL,@ContentVersion char(64)=NULL,
|
||||
@StartParagraph uniqueidentifier=NULL,@EndParagraph uniqueidentifier=NULL,@StartOffset int=NULL,@EndOffset int=NULL,@AnchorHash char(64)=NULL,@SceneID int=NULL,
|
||||
@Observation nvarchar(max)=NULL,@Decision nvarchar(max)=NULL,@Status varchar(16)='Open',@Page int=1
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Chapters c ON c.BookID=b.BookID AND c.ChapterID=@ChapterID AND c.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.IsArchived=0) THROW 51000,'Review scope unavailable',1;
|
||||
IF @Action='list' BEGIN
|
||||
IF @Page<1 OR @Page>100000 THROW 51000,'Invalid review page',1;
|
||||
SELECT * FROM dbo.WriterReviewObservations WHERE UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID ORDER BY CreatedUtc DESC,ID OFFSET ((@Page-1)*50) ROWS FETCH NEXT 51 ROWS ONLY;RETURN;
|
||||
END;
|
||||
IF @Action NOT IN('create','update') OR @ID IS NULL OR @Status NOT IN('Open','Working','Resolved') OR LEN(TRIM(COALESCE(@Observation,N'')))=0 OR LEN(@Observation)>10000 OR LEN(COALESCE(@Decision,N''))>10000 THROW 51000,'Invalid observation',1;
|
||||
BEGIN TRANSACTION;
|
||||
IF @Action='create'
|
||||
BEGIN
|
||||
IF EXISTS(SELECT 1 FROM dbo.WriterReviewObservations WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID)
|
||||
BEGIN
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.WriterReviewObservations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID AND Observation=@Observation AND ISNULL(Decision,N'')=ISNULL(@Decision,N'') AND ContentVersion=@ContentVersion AND Status=@Status AND ISNULL(CONVERT(varchar(36),StartParagraph),'')=ISNULL(CONVERT(varchar(36),@StartParagraph),'') AND ISNULL(CONVERT(varchar(36),EndParagraph),'')=ISNULL(CONVERT(varchar(36),@EndParagraph),'') AND ISNULL(StartOffset,-1)=ISNULL(@StartOffset,-1) AND ISNULL(EndOffset,-1)=ISNULL(@EndOffset,-1)) THROW 51002,'This observation changed; reload before retrying',1;
|
||||
END ELSE BEGIN
|
||||
DECLARE @CurrentRevision bigint,@CurrentManuscript uniqueidentifier;
|
||||
SELECT @CurrentRevision=Revision,@CurrentManuscript=ManuscriptID FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
|
||||
IF ISNULL(@CurrentRevision,-1)<>@SnapshotRevision OR ISNULL(@CurrentManuscript,'00000000-0000-0000-0000-000000000000')<>ISNULL(@ManuscriptID,'00000000-0000-0000-0000-000000000000') THROW 51002,'Accepted manuscript changed; your text has been retained',1;
|
||||
INSERT dbo.WriterReviewObservations(ID,UserID,BookID,ChapterID,ManuscriptID,SnapshotRevision,ContentVersion,StartParagraph,EndParagraph,StartOffset,EndOffset,AnchorHash,SceneID,Observation,Decision,Status)
|
||||
VALUES(@ID,@UserID,@BookID,@ChapterID,@ManuscriptID,@SnapshotRevision,@ContentVersion,@StartParagraph,@EndParagraph,@StartOffset,@EndOffset,@AnchorHash,@SceneID,@Observation,@Decision,@Status);
|
||||
END;
|
||||
END ELSE BEGIN
|
||||
UPDATE dbo.WriterReviewObservations SET Observation=@Observation,Decision=@Decision,Status=@Status,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID AND Version=@Version;
|
||||
IF @@ROWCOUNT<>1 THROW 51002,'Another window changed this observation; your text has been retained',1;
|
||||
END;
|
||||
SELECT * FROM dbo.WriterReviewObservations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID;
|
||||
COMMIT;
|
||||
END;
|
||||
GO
|
||||
-- The existing verified scene-start join, scoped to any accepted paragraph (including chapter-only prose).
|
||||
CREATE OR ALTER PROCEDURE dbo.WriterReview_ParagraphStart @UserID int,@BookID int,@ChapterID int,@ParagraphID uniqueidentifier,@ManuscriptID uniqueidentifier,@SessionID uniqueidentifier,@WordRevision bigint,@AcceptedRevision bigint
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.IsArchived=0) THROW 51000,'Book access denied',1;
|
||||
SELECT m.Revision,pos.ChapterID,pos.StartPosition
|
||||
FROM dbo.BookParagraphManuscripts m JOIN dbo.BookChapterValidations v ON v.BookID=m.BookID
|
||||
CROSS APPLY OPENJSON(m.Payload,'$.ChapterCheckpoints') WITH(ChapterID int '$.ChapterId',ContentHash char(64),IdentityHash char(64),MappingHash char(64)) c
|
||||
CROSS APPLY OPENJSON(v.Positions) WITH(ParagraphID uniqueidentifier '$.ParagraphId',StartPosition int '$.Start',ChapterID int '$.ChapterId',Verified bit) pos
|
||||
JOIN dbo.Chapters ch ON ch.ChapterID=pos.ChapterID AND ch.BookID=m.BookID AND ch.IsArchived=0
|
||||
WHERE m.BookID=@BookID AND m.ManuscriptID=@ManuscriptID AND m.Revision=@AcceptedRevision AND v.ChapterID=c.ChapterID AND pos.ChapterID=c.ChapterID AND pos.ChapterID=@ChapterID AND v.UserID=@UserID AND v.SessionID=@SessionID AND v.ManuscriptID=@ManuscriptID AND v.WordRevision=@WordRevision AND v.ExpiresUtc>SYSUTCDATETIME() AND v.ContentHash=c.ContentHash AND v.IdentityHash=c.IdentityHash AND v.MappingHash=c.MappingHash AND pos.Verified=1 AND pos.ParagraphID=@ParagraphID;
|
||||
END;
|
||||
@ -927,6 +927,8 @@ public sealed class ChapterWorkflowViewModel
|
||||
|
||||
public sealed class WriterDashboardViewModel
|
||||
{
|
||||
public PlotLine.Services.Manuscript.ManuscriptReaderModel? ReviewReader {get;set;}
|
||||
public string WordNavigationContext {get;set;}="working";
|
||||
public string Destination { get; set; } = "Legacy";
|
||||
public PlotLine.Services.Writer.WriterContext? WorkingContext { get; set; }
|
||||
public IReadOnlyList<WriterPlanActivity> PlannedActivities { get; set; } = [];
|
||||
|
||||
@ -1,81 +1,4 @@
|
||||
@model PlotLine.Services.Manuscript.ManuscriptReaderModel
|
||||
@{
|
||||
ViewData["Title"] = $"Manuscript Reader · {Model.Book.BookTitle}";
|
||||
ViewData["DesktopLayout"] = "details";
|
||||
var reviewToolbar = new PlotLine.Models.WriterWorkToolbar(Model.Book.BookID, Model.Chapter?.ChapterID, Model.Chapter?.ChapterTitle, DefaultKind: "Reading");
|
||||
}
|
||||
<link rel="stylesheet" href="~/css/writer-work.css" asp-append-version="true" />
|
||||
<link rel="stylesheet" href="~/css/manuscript-reader.css" asp-append-version="true" />
|
||||
<div class="manuscript-reader" data-focus="@(Model.FocusReading ? "true" : "false")"
|
||||
data-book-id="@Model.Book.BookID" data-chapter-id="@Model.Chapter?.ChapterID" data-chapter-number="@Model.Chapter?.ChapterNumber"
|
||||
data-revision="@Model.Revision" data-version="@Model.ContentVersion"
|
||||
data-check-url="@Url.Action("Changes")" data-chapter-url="@Url.Action("Chapter")">
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Books" asp-action="Details" asp-route-id="@Model.Book.BookID">@Model.Book.BookTitle · Chapters</a>
|
||||
<span>Manuscript Reader</span>
|
||||
</nav>
|
||||
<header data-pwa-header class="page-heading">
|
||||
<div><p class="eyebrow">@Model.Book.BookTitle</p><h1>Manuscript Reader</h1><span class="status-pill">Read only</span></div>
|
||||
</header>
|
||||
<nav class="reader-controls" aria-label="Chapter navigation">
|
||||
@if (Model.PreviousId is int previous)
|
||||
{ <a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@previous" asp-route-focus="@Model.FocusReading" rel="prev">← Previous chapter</a> }
|
||||
else { <span class="btn btn-outline-secondary disabled" aria-disabled="true">← Previous chapter</span> }
|
||||
<form method="get" asp-action="Index">
|
||||
<input type="hidden" name="focus" value="@Model.FocusReading.ToString().ToLowerInvariant()" />
|
||||
<input type="hidden" name="bookId" value="@Model.Book.BookID" />
|
||||
<label for="reader-chapter">Chapter</label>
|
||||
<select id="reader-chapter" name="chapterId" class="form-select">
|
||||
@foreach (var chapter in Model.Chapters)
|
||||
{ <option value="@chapter.ChapterID" selected="@(chapter.ChapterID == Model.Chapter?.ChapterID)">@chapter.ChapterNumber: @chapter.ChapterTitle</option> }
|
||||
</select>
|
||||
<button class="btn btn-outline-secondary" type="submit">Read</button>
|
||||
</form>
|
||||
@if (Model.NextId is int next)
|
||||
{ <a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@next" asp-route-focus="@Model.FocusReading" rel="next">Next chapter →</a> }
|
||||
else { <span class="btn btn-outline-secondary disabled" aria-disabled="true">Next chapter →</span> }
|
||||
<button type="button" class="btn btn-outline-secondary" id="reader-focus" aria-pressed="@Model.FocusReading.ToString().ToLowerInvariant()" hidden>Focus reading</button>
|
||||
</nav>
|
||||
<p class="reader-status" role="status" id="reader-loading" hidden>Loading chapter…</p>
|
||||
<div class="reader-status reader-live-controls" hidden>
|
||||
<label><input type="checkbox" id="reader-pause" /> Pause automatic updates while listening</label>
|
||||
<span role="status" aria-live="polite" id="reader-update-status"></span>
|
||||
<button type="button" id="reader-apply-update" class="btn btn-outline-secondary btn-sm" hidden>Show updated chapter</button>
|
||||
</div>
|
||||
<div class="reader-status muted" id="reader-timestamps">
|
||||
@if (Model.LastSuccessfulSyncUtc is DateTime sync)
|
||||
{ <p>Last successful chapter synchronisation: <time datetime="@sync.ToString("yyyy-MM-ddTHH:mm:ssZ")">@sync.ToString("dd MMM yyyy HH:mm:ss") UTC</time></p> }
|
||||
else { <p>No successful chapter synchronisation timestamp is recorded.</p> }
|
||||
@if (Model.SnapshotCapturedUtc is DateTime captured)
|
||||
{ <p>Accepted manuscript snapshot captured: <time datetime="@captured.ToString("yyyy-MM-ddTHH:mm:ssZ")">@captured.ToString("dd MMM yyyy HH:mm:ss") UTC</time></p> }
|
||||
<p>Showing accepted server text. Changes are checked automatically while this page is visible.</p>
|
||||
</div>
|
||||
<details><summary>Reading & Audio Review</summary><partial name="_WriterWorkToolbar" model="reviewToolbar" /></details>
|
||||
<a asp-controller="Writer" asp-action="Index" asp-route-bookId="@Model.Book.BookID">Return to Writing</a>
|
||||
<div id="reader-content">
|
||||
@if (Model.Paragraphs.Count == 0)
|
||||
{
|
||||
<section class="reader-empty" role="status"><h2>@(Model.Chapter?.ChapterTitle ?? "No chapters yet")</h2>
|
||||
<p>No accepted manuscript text is available for this chapter. Save and successfully synchronise it using Word Companion, then refresh this page.</p>
|
||||
<a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@Model.Chapter?.ChapterID" asp-route-focus="@Model.FocusReading">Refresh manuscript</a>
|
||||
</section>
|
||||
}
|
||||
else
|
||||
{
|
||||
<article class="reader-page" aria-label="Chapter manuscript">
|
||||
<header><p class="eyebrow">Chapter @Model.Chapter?.ChapterNumber</p>
|
||||
@if (!Model.Paragraphs[0].IsHeading)
|
||||
{ <h2>@Model.Chapter?.ChapterTitle</h2> }
|
||||
</header>
|
||||
<partial name="_Paragraphs" model="Model.Paragraphs" />
|
||||
</article>
|
||||
}
|
||||
</div>
|
||||
<footer class="reader-status muted"><p>Captured paragraph text and headings are preserved. Word formatting such as bold, italics, images and page layout is not available in this capture.</p>
|
||||
<a asp-controller="Books" asp-action="Details" asp-route-id="@Model.Book.BookID">Return to Chapters</a>
|
||||
<a asp-action="Index" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@Model.Chapter?.ChapterID" asp-route-focus="@Model.FocusReading">Refresh manuscript</a>
|
||||
</footer>
|
||||
</div>
|
||||
<partial name="_Reader" model="Model" />
|
||||
<script src="~/js/manuscript-reader.js" asp-append-version="true" defer></script>
|
||||
|
||||
<script src="~/js/writer-work.js" asp-append-version="true" defer></script>
|
||||
|
||||
@ -3,9 +3,9 @@
|
||||
{
|
||||
var paragraph = Model[index];
|
||||
if (paragraph.IsHeading && index == 0)
|
||||
{ <h2 class="reader-paragraph reader-heading" data-paragraph-id="@paragraph.Id">@paragraph.Text</h2> }
|
||||
{ <h2 class="reader-paragraph reader-heading" data-paragraph-id="@paragraph.Id" data-scene-id="@paragraph.SceneID">@paragraph.Text</h2> }
|
||||
else if (paragraph.IsHeading)
|
||||
{ <h3 class="reader-paragraph reader-heading" data-paragraph-id="@paragraph.Id">@paragraph.Text</h3> }
|
||||
{ <h3 class="reader-paragraph reader-heading" data-paragraph-id="@paragraph.Id" data-scene-id="@paragraph.SceneID">@paragraph.Text</h3> }
|
||||
else
|
||||
{ <p class="reader-paragraph" data-paragraph-id="@paragraph.Id">@paragraph.Text</p> }
|
||||
{ <p class="reader-paragraph" data-paragraph-id="@paragraph.Id" data-scene-id="@paragraph.SceneID">@paragraph.Text</p> }
|
||||
}
|
||||
|
||||
85
PlotLine/Views/ManuscriptReader/_Reader.cshtml
Normal file
85
PlotLine/Views/ManuscriptReader/_Reader.cshtml
Normal file
@ -0,0 +1,85 @@
|
||||
@model PlotLine.Services.Manuscript.ManuscriptReaderModel
|
||||
@{
|
||||
if(!Model.IntegratedReview){ViewData["Title"] = $"Manuscript Reader · {Model.Book.BookTitle}";ViewData["DesktopLayout"] = "details";}
|
||||
var routeAction=Model.IntegratedReview?"Review":"Index";var routeController=Model.IntegratedReview?"Writer":"ManuscriptReader";
|
||||
var reviewToolbar = new PlotLine.Models.WriterWorkToolbar(Model.Book.BookID, Model.Chapter?.ChapterID, Model.Chapter?.ChapterTitle, DefaultKind: "Reading");
|
||||
}
|
||||
<link rel="stylesheet" href="~/css/writer-work.css" asp-append-version="true" />
|
||||
<link rel="stylesheet" href="~/css/manuscript-reader.css" asp-append-version="true" />
|
||||
<div class="manuscript-reader" data-focus="@(Model.FocusReading ? "true" : "false")"
|
||||
data-book-id="@Model.Book.BookID" data-chapter-id="@Model.Chapter?.ChapterID" data-chapter-number="@Model.Chapter?.ChapterNumber"
|
||||
data-revision="@Model.Revision" data-version="@Model.ContentVersion"
|
||||
data-integrated-review="@Model.IntegratedReview.ToString().ToLowerInvariant()" data-check-url="@Url.Action("Changes","ManuscriptReader")" data-chapter-url="@Url.Action("Chapter","ManuscriptReader")">
|
||||
@if(!Model.IntegratedReview){
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Books" asp-action="Details" asp-route-id="@Model.Book.BookID">@Model.Book.BookTitle · Chapters</a>
|
||||
<span>Manuscript Reader</span>
|
||||
</nav>
|
||||
<header data-pwa-header class="page-heading">
|
||||
<div><p class="eyebrow">@Model.Book.BookTitle</p><h1>Manuscript Reader</h1><span class="status-pill">Read only</span></div>
|
||||
</header>
|
||||
}
|
||||
<nav class="reader-controls" aria-label="Chapter navigation">
|
||||
@if (Model.PreviousId is int previous)
|
||||
{ <a class="btn btn-outline-secondary" asp-controller="@routeController" asp-action="@routeAction" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@previous" asp-route-focus="@Model.FocusReading" rel="prev">← Previous chapter</a> }
|
||||
else { <span class="btn btn-outline-secondary disabled" aria-disabled="true">← Previous chapter</span> }
|
||||
<form method="get" asp-controller="@routeController" asp-action="@routeAction">
|
||||
<input type="hidden" name="focus" value="@Model.FocusReading.ToString().ToLowerInvariant()" />
|
||||
<input type="hidden" name="bookId" value="@Model.Book.BookID" />
|
||||
<label for="reader-chapter">Chapter</label>
|
||||
<select id="reader-chapter" name="chapterId" class="form-select">
|
||||
@foreach (var chapter in Model.Chapters)
|
||||
{ <option value="@chapter.ChapterID" selected="@(chapter.ChapterID == Model.Chapter?.ChapterID)">@chapter.ChapterNumber: @chapter.ChapterTitle</option> }
|
||||
</select>
|
||||
<button class="btn btn-outline-secondary" type="submit">Read</button>
|
||||
</form>
|
||||
@if (Model.NextId is int next)
|
||||
{ <a class="btn btn-outline-secondary" asp-controller="@routeController" asp-action="@routeAction" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@next" asp-route-focus="@Model.FocusReading" rel="next">Next chapter →</a> }
|
||||
else { <span class="btn btn-outline-secondary disabled" aria-disabled="true">Next chapter →</span> }
|
||||
<button type="button" class="btn btn-outline-secondary" id="reader-focus" aria-pressed="@Model.FocusReading.ToString().ToLowerInvariant()" hidden>Focus reading</button>
|
||||
</nav>
|
||||
@if(Model.IntegratedReview){<button type="button" class="btn btn-outline-primary" data-review-record>Record an observation</button>}
|
||||
<p class="reader-status" role="status" id="reader-loading" hidden>Loading chapter…</p>
|
||||
<div class="reader-status reader-live-controls" hidden>
|
||||
<label><input type="checkbox" id="reader-pause" /> Pause automatic updates while listening</label>
|
||||
<span role="status" aria-live="polite" id="reader-update-status"></span>
|
||||
<button type="button" id="reader-apply-update" class="btn btn-outline-secondary btn-sm" hidden>Show updated chapter</button>
|
||||
</div>
|
||||
<details class="reader-metadata" open="@(!Model.IntegratedReview)"><summary>Accepted manuscript details</summary><div class="reader-status muted" id="reader-timestamps">
|
||||
@if (Model.LastSuccessfulSyncUtc is DateTime sync)
|
||||
{ <p>Last successful chapter synchronisation: <time datetime="@sync.ToString("yyyy-MM-ddTHH:mm:ssZ")">@sync.ToString("dd MMM yyyy HH:mm:ss") UTC</time></p> }
|
||||
else { <p>No successful chapter synchronisation timestamp is recorded.</p> }
|
||||
@if (Model.SnapshotCapturedUtc is DateTime captured)
|
||||
{ <p>Accepted manuscript snapshot captured: <time datetime="@captured.ToString("yyyy-MM-ddTHH:mm:ssZ")">@captured.ToString("dd MMM yyyy HH:mm:ss") UTC</time></p> }
|
||||
<p>Showing accepted server text. Changes are checked automatically while this page is visible.</p>
|
||||
</div>
|
||||
</details>
|
||||
<details><summary>Reading & Audio Review</summary><partial name="_WriterWorkToolbar" model="reviewToolbar" /></details>
|
||||
@if(!Model.IntegratedReview){<a asp-controller="Writer" asp-action="Write" asp-route-bookId="@Model.Book.BookID">Return to Writing</a>}
|
||||
<div id="reader-content">
|
||||
@if (Model.Paragraphs.Count == 0)
|
||||
{
|
||||
<section class="reader-empty" role="status"><h2>@(Model.Chapter?.ChapterTitle ?? "No chapters yet")</h2>
|
||||
<p>No accepted manuscript text is available for this chapter. Save and successfully synchronise it using Word Companion, then refresh this page.</p>
|
||||
<a class="btn btn-outline-secondary" asp-controller="@routeController" asp-action="@routeAction" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@Model.Chapter?.ChapterID" asp-route-focus="@Model.FocusReading">Refresh manuscript</a>
|
||||
</section>
|
||||
}
|
||||
else
|
||||
{
|
||||
<article class="reader-page" aria-label="Chapter manuscript">
|
||||
<header><p class="eyebrow">Chapter @Model.Chapter?.ChapterNumber</p>
|
||||
@if (!Model.Paragraphs[0].IsHeading)
|
||||
{ <h2>@Model.Chapter?.ChapterTitle</h2> }
|
||||
</header>
|
||||
<partial name="~/Views/ManuscriptReader/_Paragraphs.cshtml" model="Model.Paragraphs" />
|
||||
</article>
|
||||
}
|
||||
</div>
|
||||
<footer class="reader-status muted"><p>Captured paragraph text and headings are preserved. Word formatting such as bold, italics, images and page layout is not available in this capture.</p>
|
||||
<a asp-controller="Books" asp-action="Details" asp-route-id="@Model.Book.BookID">Return to Chapters</a>
|
||||
<a asp-controller="@routeController" asp-action="@routeAction" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@Model.Chapter?.ChapterID" asp-route-focus="@Model.FocusReading">Refresh manuscript</a>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
@ -25,6 +25,7 @@
|
||||
<script src="~/js/writer3-workspace.js" asp-append-version="true"></script>
|
||||
<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=="Review"){<script src="~/js/manuscript-reader.js" asp-append-version="true"></script><script src="~/js/writer-review.js" asp-append-version="true"></script><script src="~/js/writer-word.js" asp-append-version="true"></script><script src="~/js/writer-work.js" asp-append-version="true"></script>}
|
||||
@if(Model.Destination == "Write"){
|
||||
<script src="~/js/writer-word.js" asp-append-version="true"></script>
|
||||
<script src="~/js/writer-authoring.js" asp-append-version="true"></script>
|
||||
|
||||
25
PlotLine/Views/Writer/_ReviewContext.cshtml
Normal file
25
PlotLine/Views/Writer/_ReviewContext.cshtml
Normal file
@ -0,0 +1,25 @@
|
||||
@model PlotLine.Services.Writer.ReviewPanel
|
||||
@{var data=Model.Intentions;var goal=data.Sections.First(x=>x.Kind=="Goals");var scene=data.Sections.FirstOrDefault(x=>x.Kind=="Scene");string Compact(string value)=>value.Length>360?value[..360]+"…":value;}
|
||||
<div data-review-panel>
|
||||
<section class="writer3-inset"><h3>What did I want this to achieve?</h3><p class="writer3-caption">@Model.ReferenceMessage</p>
|
||||
@if(scene!=null){<h4>@data.Scene?.SceneTitle</h4><p class="review-recorded">@(string.IsNullOrWhiteSpace(scene.Value("ScenePurposeNotes"))?"No scene intention recorded.":Compact(scene.Value("ScenePurposeNotes")))</p><p class="review-recorded">@Compact(scene.Value("SceneOutcomeNotes"))</p><p class="writer3-caption">Recorded scene state: @data.Scene?.RevisionStatusName</p>}
|
||||
<p class="review-recorded">@(string.IsNullOrWhiteSpace(goal.Value("GoalSummary"))?"No chapter intention recorded. You can review without one.":Compact(goal.Value("GoalSummary")))</p>
|
||||
<details><summary>Chapter details, reminders & editing</summary>
|
||||
@foreach(var section in data.Sections.Where(x=>x.Kind is "Chapter" or "Goals")){@foreach(var field in section.Fields){var value=section.Value(field.Name);if(field.Type=="purpose"&&!string.IsNullOrWhiteSpace(value))value=section.Purposes.FirstOrDefault(p=>p.Value==value).Label??"Recorded purpose is unavailable";@if(!string.IsNullOrWhiteSpace(value)){<p><strong>@field.Label</strong><span class="review-recorded">@value</span></p>}}}
|
||||
@foreach(var note in data.Sections.Where(x=>x.Kind=="Note"&&x.Value("IsResolved")!="true"||x.Kind=="Checklist"&&x.Value("IsCompleted")!="true").Take(10)){<p class="review-recorded">@(note.Kind=="Note"?note.Value("NoteText"):note.Value("ItemText"))</p>}
|
||||
@{var flow=data.Sections.FirstOrDefault(x=>x.Kind=="Workflow");}@if(flow!=null){<p>Priority: @flow.Value("Priority"). @flow.Value("BlockedReason")</p>}
|
||||
<a asp-controller="Chapters" asp-action="Edit" asp-route-id="@data.ChapterID" target="_blank" rel="noopener">Edit chapter intentions in the existing editor</a>
|
||||
@if(data.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@data.SceneID" target="_blank" rel="noopener">Edit scene intentions, notes and working details</a>}
|
||||
</details></section>
|
||||
<section class="writer3-inset"><div class="writer3-authoring-heading"><h3>Your observations</h3><button type="button" class="btn btn-sm btn-link" data-review-reload>Reload</button></div>
|
||||
@if(Model.Observations.Count==0){<p>No observations on this page. Record something when it helps your review.</p>}
|
||||
@foreach(var row in Model.Observations){
|
||||
<article class="writer3-authoring-card" data-observation data-id="@row.ID" data-version="@row.Version" data-first="@row.StartParagraph" data-anchor="@row.AnchorState">
|
||||
<p class="writer3-focus-kind">@(row.Status=="Open"?"Needs attention":row.Status=="Working"?"Working on it":"Resolved")</p>
|
||||
<p class="review-recorded" data-observation-text>@row.Observation</p><p class="review-recorded" data-decision-text>@row.Decision</p>
|
||||
<p class="writer3-caption">@row.AnchorState reference · @(row.SnapshotRevision<0?"No accepted version at capture":"Accepted version "+row.SnapshotRevision) · created @row.CreatedUtc.ToString("dd MMM yyyy HH:mm:ss") UTC · updated @row.UpdatedUtc.ToString("dd MMM yyyy HH:mm:ss") UTC</p>
|
||||
<div class="button-row"><button type="button" class="btn btn-sm btn-outline-secondary" data-review-edit data-state="@row.Status">Edit / change decision</button>@if(row.StartParagraph.HasValue){<button type="button" class="btn btn-sm btn-outline-secondary" data-review-revisit>Revisit reference</button>}</div>
|
||||
</article>}
|
||||
<div class="button-row">@if(Model.Page>1){<button type="button" class="btn btn-sm btn-link" data-review-page="@(Model.Page-1)">Previous observations</button>}@if(Model.HasMore){<button type="button" class="btn btn-sm btn-link" data-review-page="@(Model.Page+1)">More observations</button>}</div>
|
||||
</section>
|
||||
</div>
|
||||
@ -3,11 +3,11 @@
|
||||
<section class="writer3-panel writer3-main" tabindex="0">
|
||||
<p class="eyebrow">Start with your question</p><h2>What would you like to explore?</h2><p>You do not need a finished outline or a linked manuscript. Choose a starting point.</p>
|
||||
<div class="writer3-explore-paths">
|
||||
<a asp-controller="WritingProblems" asp-action="Index"><span class="writer3-path-mark" aria-hidden="true">01</span><div><h3>Find a way forward</h3><p>Answer the Problem Solver’s questions about what is making your writing difficult.</p></div><span aria-hidden="true">→</span></a>
|
||||
<a asp-controller="WritingProblems" asp-action="Browse"><span class="writer3-path-mark" aria-hidden="true">02</span><div><h3>Develop an idea or untangle a concern</h3><p>Browse practical guidance about characters, plot, pacing and structure.</p></div><span aria-hidden="true">→</span></a>
|
||||
<a asp-controller="Writer" asp-action="Write" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID"><span class="writer3-path-mark" aria-hidden="true">01</span><div><h3>Develop a chapter or scene</h3><p>Work with your saved chapter intentions, scene ideas and reminders.</p></div><span aria-hidden="true">→</span></a>
|
||||
<a asp-controller="@(Model.ProjectID.HasValue?"PlotLineWorkspace":"Projects")" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID"><span class="writer3-path-mark" aria-hidden="true">02</span><div><h3>Develop your plot and threads</h3><p>Use your existing plot lines and threads to develop an idea or untangle a concern.</p></div><span aria-hidden="true">→</span></a>
|
||||
@if(Model.BookID.HasValue){<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID"><span class="writer3-path-mark" aria-hidden="true">03</span><div><h3>Look at your story’s shape</h3><p>Inspect your saved chapters, scenes and story timeline.</p></div><span aria-hidden="true">→</span></a>}
|
||||
</div>
|
||||
<p class="writer3-caption">The Problem Solver offers structured guidance. It does not automatically analyse your manuscript.</p>
|
||||
<p class="writer3-caption">These open your authenticated writing and story tools. Guided exploration is planned for a later update; no manuscript analysis runs here.</p>
|
||||
</section>
|
||||
<aside class="writer3-panel writer3-reference" tabindex="0" aria-label="Existing story references">
|
||||
<h2>Your story references</h2>
|
||||
@ -19,6 +19,6 @@
|
||||
<a asp-controller="FloorPlans" asp-action="Index" asp-route-projectId="@Model.ProjectID">Floor Plans <span aria-hidden="true">↗</span></a>
|
||||
<a asp-controller="ProjectMetrics" asp-action="Index" asp-route-projectId="@Model.ProjectID">Emotion & scene metrics <span aria-hidden="true">↗</span></a>
|
||||
</div><p class="writer3-caption">These open the existing Story, Characters and World workspaces. Project-wide tools may include other books in this project.</p>}
|
||||
else{<p>Select a project in the application bar to inspect its characters, plot and world. The Problem Solver is available now.</p><a asp-controller="Projects" asp-action="Index">Open your projects</a>}
|
||||
else{<p>Select a project in the application bar to inspect its characters, plot and world. Your existing writing tools will use the selected project and book.</p><a asp-controller="Projects" asp-action="Index">Open your projects</a>}
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
@ -1,18 +1,29 @@
|
||||
@model WriterDashboardViewModel
|
||||
@{var chapter = Model.Objective?.ChapterID ?? Model.ObjectiveChoices.FirstOrDefault()?.ChapterID;}
|
||||
@{var reader=Model.ReviewReader;var word=new WriterDashboardViewModel{BookID=Model.BookID,ProjectID=Model.ProjectID,WordNavigationContext="review",Objective=reader?.Chapter==null?null:new(){ChapterID=reader.Chapter.ChapterID,ChapterTitle=reader.Chapter.ChapterTitle,Activity="Revising"}};}
|
||||
<div class="writer3-workspace" aria-label="Manuscript review">
|
||||
<section class="writer3-panel writer3-main" tabindex="0">
|
||||
<p class="eyebrow">Read with a purpose</p><h2>Review your writing</h2><p>The Manuscript Reader shows accepted server text. Unsynchronised Word edits are not shown; save and synchronise the linked manuscript to update it.</p>
|
||||
@if(chapter.HasValue){<div class="button-row"><a class="btn btn-primary writer3-cta" asp-controller="ManuscriptReader" asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-chapterId="@chapter">Open Manuscript Reader <span aria-hidden="true">→</span></a><a asp-controller="ManuscriptReader" asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-chapterId="@chapter" asp-route-focus="true">Focused reading</a></div>}
|
||||
else{<div class="writer3-inset"><h3>No chapters to read yet</h3><p>Add a chapter or import your manuscript from the book’s existing tools.</p><a class="btn btn-primary writer3-cta" asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID" asp-fragment="chapters">Open your book <span aria-hidden="true">→</span></a></div>}
|
||||
<div class="writer3-inset"><h3>Listen and review</h3><p>In the Reader, expand <strong>Reading & Audio Review</strong> to start a review session. Playback controls require compatible Windows Companion and a supported player. Opening the Reader does not start playback.</p></div>
|
||||
</section>
|
||||
<aside class="writer3-panel writer3-reference" tabindex="0">
|
||||
<h2>Intentions & revision</h2><div class="writer3-link-list">
|
||||
<button type="button" data-open-writing-intent>Open Intent & saved evidence <span aria-hidden="true">↗</span></button>
|
||||
<button type="button" data-open-writing-context>Open Context <span aria-hidden="true">↗</span></button>
|
||||
<a asp-action="Workspaces" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID" asp-route-workspace="Revision">Scenes marked for revision <span aria-hidden="true">↗</span></a>
|
||||
<a asp-action="Write" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Return to your writing focus <span aria-hidden="true">↗</span></a>
|
||||
</div><p class="writer3-caption">Recorded intentions, AI evidence and author-confirmed completion remain separate. Assessments are explicit actions in Intent’s Evidence tab.</p><p data-writing-workspace-message role="status"></p>
|
||||
</aside>
|
||||
<section class="writer3-panel writer3-main" tabindex="0" aria-label="Accepted manuscript">
|
||||
@if(reader!=null){<partial name="~/Views/ManuscriptReader/_Reader.cshtml" model="reader" />}
|
||||
else{<h2>Read the accepted manuscript</h2><p>Select a book with chapters to review your accepted writing.</p><a asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID">Open your book</a>}
|
||||
</section>
|
||||
<aside class="writer3-panel writer3-reference" tabindex="0" aria-label="Review intentions and observations">
|
||||
<div class="writer3-authoring-heading"><h2>Notice & decide</h2><help-icon key="writer3.reviewing" /></div>
|
||||
@if(reader?.Chapter!=null){
|
||||
<div data-writer-review data-book="@Model.BookID" data-chapter="@reader.Chapter.ChapterID" data-panel-url="@Url.Action("Panel","WriterReview")">
|
||||
<p data-review-reference>Chapter observation · select text or a paragraph for a passage reference.</p><p data-review-message role="status"></p>
|
||||
<button type="button" class="btn btn-sm btn-outline-primary" data-review-new>Something here needs attention</button>
|
||||
<form asp-controller="WriterReview" asp-action="Save" method="post" data-review-form hidden>
|
||||
<input type="hidden" name="BookID" value="@Model.BookID"/><input type="hidden" name="ChapterID" value="@reader.Chapter.ChapterID"/><input type="hidden" name="ID"/><input type="hidden" name="Version" value="0"/><input type="hidden" name="ContentVersion"/>
|
||||
<input type="hidden" name="StartParagraph"/><input type="hidden" name="EndParagraph"/><input type="hidden" name="StartOffset"/><input type="hidden" name="EndOffset"/>
|
||||
<div class="writer3-inline-field"><label for="review-observation">What have you noticed?</label><textarea id="review-observation" name="Observation" class="form-control" maxlength="10000" rows="4" required></textarea></div>
|
||||
<div class="writer3-inline-field"><label for="review-decision">What would you like to change? (optional)</label><textarea id="review-decision" name="Decision" class="form-control" maxlength="10000" rows="3"></textarea></div>
|
||||
<label for="review-status">Your decision</label><select name="Status" id="review-status" class="form-select"><option value="Open">Needs attention</option><option value="Working">Working on it</option><option value="Resolved">Resolved</option></select>
|
||||
<p data-review-error role="alert" hidden></p><div class="button-row"><button class="btn btn-primary" type="submit" data-review-save>Save observation</button><button type="button" class="btn btn-outline-secondary" data-review-cancel>Cancel</button></div>
|
||||
</form>
|
||||
<button type="button" class="btn btn-sm btn-link" data-review-chapter>Use a chapter-level reference</button>
|
||||
<div data-review-context aria-live="polite"><p>Loading recorded intentions and observations…</p></div>
|
||||
</div>
|
||||
<details class="writer3-authoring-details"><summary>Return to Word</summary><partial name="_WriterWord" model="word" /></details>
|
||||
}
|
||||
<details class="writer3-authoring-details"><summary>Saved assessments & other tools</summary><p>Author observations above are separate from automated findings. Opening Review runs no analysis.</p><div class="writer3-link-list"><button type="button" data-open-writing-intent>Open Intent & saved assessment evidence</button><button type="button" data-open-writing-context>Open standalone Context</button><a asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID">Open the book’s saved analysis and review tools</a><a asp-action="Write" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Return to saved writing focus</a></div><p data-writing-workspace-message role="status"></p></details>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
@ -1,16 +1,17 @@
|
||||
@model WriterDashboardViewModel
|
||||
@{var focus=Model.Objective;}
|
||||
<section class="writer3-word writer3-inset" data-writer-word data-book-id="@Model.BookID" data-chapter-id="@focus?.ChapterID" data-scene-id="@focus?.SceneID" data-status-url="/native-companion/status?writerBookId=@Model.BookID&writerChapterId=@focus?.ChapterID" aria-label="Word Companion">
|
||||
@{var focus=Model.Objective;var reviewing=Model.WordNavigationContext=="review";}
|
||||
<section class="writer3-word writer3-inset" data-writer-word data-word-context="@Model.WordNavigationContext" data-book-id="@Model.BookID" data-chapter-id="@focus?.ChapterID" data-scene-id="@focus?.SceneID" data-status-url="/native-companion/status?writerBookId=@Model.BookID&writerChapterId=@focus?.ChapterID" aria-label="Word Companion">
|
||||
<div class="writer3-authoring-heading"><h3>Your manuscript in Word</h3><help-icon key="writer3.word" /></div>
|
||||
<p data-word-state role="status">Checking Word Companion…</p>
|
||||
<label data-word-choose hidden>Choose the manuscript in Word<select class="form-select" data-word-document><option value="">Choose a document</option></select></label>
|
||||
<p class="writer3-caption" data-word-position>Word position has not been verified.</p>
|
||||
<p class="writer3-caption" data-word-freshness>Your latest changes have not yet been confirmed in PlotDirector.</p>
|
||||
<div class="button-row">
|
||||
@if(reviewing){<button type="button" class="btn btn-sm btn-outline-secondary" data-word-paragraph disabled>Open paragraph in Word</button>}
|
||||
@if(focus?.ChapterID.HasValue==true){<button type="button" class="btn btn-sm btn-outline-primary" data-word-navigate disabled>Open this chapter in Word</button>@if(focus.SceneID.HasValue){<button type="button" class="btn btn-sm btn-outline-secondary" data-word-scene disabled>Open this scene in Word</button>}}
|
||||
|
||||
</div>
|
||||
<details><summary>Connection and update options</summary><p class="writer3-caption">Working focus and Word position can differ. Navigation does not save Word or change your session. Reader shows accepted content.</p><div class="button-row"><button type="button" class="btn btn-sm btn-outline-secondary" data-word-sync disabled>Check saved manuscript</button><button type="button" class="btn btn-sm btn-outline-secondary" data-word-check>Check connection & updates</button></div></details>
|
||||
<details><summary>Connection and update options</summary><p class="writer3-caption">@(reviewing?"Review selection":"Working focus") and Word position can differ. Navigation does not save Word or change your session. Reader shows accepted content.</p><div class="button-row"><button type="button" class="btn btn-sm btn-outline-secondary" data-word-sync disabled>Check saved manuscript</button><button type="button" class="btn btn-sm btn-outline-secondary" data-word-check>Check connection & updates</button></div></details>
|
||||
<p data-word-command role="status" aria-live="polite"></p>
|
||||
<form method="post" asp-action="SaveObjective" asp-controller="Writer" data-word-adopt hidden>
|
||||
<input type="hidden" name="BookID" value="@Model.BookID"/><input type="hidden" name="ChapterID"/><input type="hidden" name="SceneID"/><input type="hidden" name="Activity" value="@(focus?.Activity??"Drafting")"/>
|
||||
|
||||
@ -68,3 +68,21 @@
|
||||
/* 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}
|
||||
/* Compact shared destination chrome reclaims reading/work area at every viewport. */
|
||||
.writer3-viewport{padding-top:.4rem;padding-bottom:.3rem}
|
||||
.writer3-viewport>.writer3-header{gap:.7rem;margin-bottom:.35rem}
|
||||
.writer3-viewport .writer3-cover{width:32px;height:46px;font-size:1.2rem}
|
||||
.writer3-viewport .writer3-title h1{font-size:1.5rem}
|
||||
.writer3-viewport .writer3-header .eyebrow{font-size:.68rem;margin-bottom:.1rem}
|
||||
.writer3-viewport .writer3-header .muted{font-size:.82rem;margin-top:.15rem}
|
||||
.writer3-viewport .writer3-layout-tools{padding-bottom:.3rem}
|
||||
.writer3-viewport .writer3-layout-tools button{min-height:32px}
|
||||
.writer3-destination[data-writer-destination=Review] .writer3-main{padding:.7rem clamp(.6rem,1.5vw,1.3rem)}
|
||||
.writer3 .manuscript-reader:not([data-focus=true]) .reader-controls{margin:.25rem 0;gap:.4rem}
|
||||
.writer3 .manuscript-reader:not([data-focus=true]) .reader-status{margin:.6rem 0}
|
||||
.writer3 .manuscript-reader:not([data-focus=true]) .reader-page,.writer3 .manuscript-reader:not([data-focus=true]) .reader-empty{margin:.8rem auto;padding:clamp(.8rem,2vw,1.6rem)}
|
||||
.writer3 .manuscript-reader:not([data-focus=true]) .reader-page header{margin-bottom:.8rem}
|
||||
.review-recorded{display:block;white-space:pre-wrap;overflow-wrap:anywhere;max-width:75ch}
|
||||
[data-review-form]{margin:.8rem 0;padding:.7rem 0;border-block:1px solid var(--pd-border-subtle)}
|
||||
[data-review-error]{border-left:3px solid var(--pd-accent);padding:.6rem}
|
||||
.writer3 .reader-metadata summary{font-size:.82rem;color:var(--pd-muted)}
|
||||
|
||||
@ -58,7 +58,8 @@
|
||||
? 'Updated chapter available. It will appear after you clear the text selection.'
|
||||
: pause.checked ? 'Updated chapter available. Automatic updates are paused.' : 'Updated chapter available.';
|
||||
};
|
||||
const viewportTop = () => root.dataset.focus === 'true' ? root.getBoundingClientRect().top : 0;
|
||||
const scrollPanel=root.closest('.writer3-main');
|
||||
const viewportTop = () => root.dataset.focus === 'true' ? root.getBoundingClientRect().top : scrollPanel?.getBoundingClientRect().top||0;
|
||||
const rememberPosition = () => {
|
||||
const top = viewportTop();
|
||||
const rows = [...content.querySelectorAll('[data-paragraph-id]')];
|
||||
@ -78,10 +79,11 @@
|
||||
if (!row) continue;
|
||||
const delta = row.getBoundingClientRect().top - viewportTop() - anchor.offset;
|
||||
if (root.dataset.focus === 'true') root.scrollBy({ top: delta, behavior: 'instant' });
|
||||
else window.scrollBy({ top: delta, behavior: 'instant' });
|
||||
else if(scrollPanel)scrollPanel.scrollBy({top:delta,behavior:'instant'});else window.scrollBy({ top: delta, behavior: 'instant' });
|
||||
break;
|
||||
}
|
||||
};
|
||||
root.readerPreserveView=()=>{const anchors=rememberPosition();return ()=>restorePosition(anchors);};
|
||||
const fetchJson = async url => {
|
||||
request = new AbortController();
|
||||
const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store', signal: request.signal });
|
||||
@ -118,7 +120,7 @@
|
||||
data.paragraphs.forEach((paragraph, index) => {
|
||||
const node = document.createElement(paragraph.isHeading ? index === 0 ? 'h2' : 'h3' : 'p');
|
||||
node.className = 'reader-paragraph' + (paragraph.isHeading ? ' reader-heading' : '');
|
||||
node.dataset.paragraphId = paragraph.id;
|
||||
node.dataset.paragraphId = paragraph.id;node.dataset.sceneId=paragraph.sceneId||'';
|
||||
node.textContent = paragraph.text;
|
||||
article.append(node);
|
||||
});
|
||||
@ -167,6 +169,7 @@
|
||||
root.dataset.version = displayedVersion;
|
||||
root.dataset.revision = revision;
|
||||
restorePosition(anchors);
|
||||
root.dispatchEvent(new CustomEvent('reader:updated',{bubbles:true,detail:{revision,version:displayedVersion}}));
|
||||
apply.hidden = true;
|
||||
message.textContent = 'Chapter updated.';
|
||||
};
|
||||
@ -188,7 +191,7 @@
|
||||
const data = await fetchJson(url);
|
||||
if (stopped || document.hidden) return;
|
||||
revision = data.revision; observedVersion = data.version;
|
||||
if (!pending() && (data.lastSuccessfulSyncUtc || data.snapshotCapturedUtc)) timestamps(data);
|
||||
if (!pending()) {root.dataset.revision=revision;root.dispatchEvent(new CustomEvent('reader:metadata',{bubbles:true}));if(data.lastSuccessfulSyncUtc || data.snapshotCapturedUtc)timestamps(data);}
|
||||
indicate();
|
||||
await update();
|
||||
} catch (error) {
|
||||
|
||||
29
PlotLine/wwwroot/js/writer-review.js
Normal file
29
PlotLine/wwwroot/js/writer-review.js
Normal file
@ -0,0 +1,29 @@
|
||||
// Author actions only. Selection never navigates Word, creates a record or changes working/session focus.
|
||||
(()=>{'use strict';const root=document.querySelector('[data-writer-review]'),reader=document.querySelector('.manuscript-reader');if(!root||!reader)return;
|
||||
const form=root.querySelector('[data-review-form]'),context=root.querySelector('[data-review-context]'),message=root.querySelector('[data-review-message]'),reference=root.querySelector('[data-review-reference]'),error=root.querySelector('[data-review-error]'),newButton=root.querySelector('[data-review-new]');
|
||||
let anchor=null,selected=null,page=1,dirty=false,busy=false,loading=false,allowLeave=false,pauseBefore=false,controller=null,generation=0,selectionTimer=null,lastContext='';
|
||||
const field=n=>form.elements.namedItem(n),readerContent=reader.querySelector('#reader-content'),word=document.querySelector('[data-writer-word]');
|
||||
const nodeParagraph=n=>(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest('[data-paragraph-id]');
|
||||
function capture(){const s=getSelection();if(!s||s.isCollapsed||s.rangeCount!==1)return null;const r=s.getRangeAt(0),first=nodeParagraph(r.startContainer),last=nodeParagraph(r.endContainer);if(!first||!last||!readerContent.contains(first)||!readerContent.contains(last))return null;const before=document.createRange();before.selectNodeContents(first);before.setEnd(r.startContainer,r.startOffset);const after=document.createRange();after.selectNodeContents(last);after.setEnd(r.endContainer,r.endOffset);return{StartParagraph:first.dataset.paragraphId,EndParagraph:last.dataset.paragraphId,StartOffset:before.toString().length,EndOffset:after.toString().length};}
|
||||
function wordReference(id){if(!word)return;word.dataset.paragraphId=id||'';word.dataset.acceptedRevision=reader.dataset.revision;window.dispatchEvent(new Event('review-reference-changed'));}
|
||||
function queueContext(){clearTimeout(selectionTimer);selectionTimer=setTimeout(()=>void load(false),180);}
|
||||
async function load(force=true){clearTimeout(selectionTimer);const key=[selected,anchor?.EndParagraph,reader.dataset.version,page].join(':');if(!force&&key===lastContext)return;const mine=++generation;controller?.abort();controller=new AbortController();loading=true;const url=new URL(root.dataset.panelUrl,location.href);url.search=new URLSearchParams({bookId:root.dataset.book,chapterId:root.dataset.chapter,version:reader.dataset.version,page:String(page),...(selected?{paragraphId:selected,endParagraphId:anchor?.EndParagraph||selected}:{})});try{const response=await fetch(url,{cache:'no-store',signal:controller.signal});if(!response.ok)throw Error();const doc=new DOMParser().parseFromString(await response.text(),'text/html'),panel=doc.querySelector('[data-review-panel]');if(!panel)throw Error();if(mine===generation){context.replaceChildren(panel);lastContext=key;}}catch(e){if(e.name!=='AbortError'&&mine===generation){message.textContent='Recorded review information could not load. Your observation text is retained.';}}finally{if(mine===generation)loading=false;}}
|
||||
function pause(enabled){const input=reader.querySelector('#reader-pause');if(enabled){pauseBefore=input.checked;input.checked=true;}else input.checked=pauseBefore;input.dispatchEvent(new Event('change'));}
|
||||
function showEditor(){if(reader.dataset.focus==='true'){const restore=reader.readerPreserveView?.();reader.querySelector('#reader-focus').click();restore?.();}const aside=root.closest('.writer3-reference');if(aside.hidden)document.querySelector('.writer3-layout-tools button').click();form.hidden=false;newButton.hidden=true;field('Observation').focus();}
|
||||
function begin(){if(busy)return;if(dirty){field('Observation').focus();return;}anchor=capture()||anchor;selected=anchor?.StartParagraph||null;wordReference(selected);void load();field('ID').value=crypto.randomUUID();field('Version').value='0';field('ContentVersion').value=reader.dataset.version;for(const n of['StartParagraph','EndParagraph','StartOffset','EndOffset'])field(n).value=anchor?.[n]??'';field('Observation').value='';field('Decision').value='';field('Status').value='Open';error.hidden=true;pause(true);dirty=true;reference.textContent=anchor?'Observation linked to the selected accepted paragraph(s).':'Chapter-level observation; no exact passage is claimed.';showEditor();}
|
||||
reader.querySelector('#reader-focus').addEventListener('click',e=>{if(dirty&&reader.dataset.focus!=='true'){e.preventDefault();e.stopImmediatePropagation();message.textContent='Save or Cancel the observation before entering Focused Reading.';}},true);
|
||||
function finish(){form.hidden=true;newButton.hidden=false;dirty=false;error.hidden=true;pause(false);newButton.focus();}
|
||||
newButton.addEventListener('click',begin);document.querySelector('[data-review-record]')?.addEventListener('click',begin);
|
||||
const markDirty=()=>{if(!form.hidden&&!busy)dirty=true;};form.addEventListener('input',markDirty);form.addEventListener('change',markDirty);root.querySelector('[data-review-cancel]').addEventListener('click',()=>{if(!busy){finish();message.textContent='Observation cancelled; no changes saved.';}});
|
||||
root.querySelector('[data-review-chapter]').addEventListener('click',()=>{if(busy)return;if(dirty&&Number(field('Version').value)>0){message.textContent='A saved observation keeps its original reference. Create a new chapter observation instead.';return;}anchor=null;selected=null;wordReference(null);for(const n of['StartParagraph','EndParagraph','StartOffset','EndOffset'])field(n).value='';reference.textContent='Chapter-level reference; no exact passage is claimed.';if(!dirty)void load();});
|
||||
form.addEventListener('submit',async e=>{e.preventDefault();if(busy)return;const data=new FormData(form),creating=Number(field('Version').value)===0;busy=true;for(const input of form.querySelectorAll('textarea,select'))input.disabled=true;const button=root.querySelector('[data-review-save]'),cancel=root.querySelector('[data-review-cancel]');button.disabled=true;cancel.disabled=true;error.hidden=true;try{const response=await fetch(form.action,{method:'POST',body:data,headers:{'X-Requested-With':'XMLHttpRequest'}});const result=await response.json().catch(()=>null);if(!response.ok||result?.success!==true){error.textContent=result?.message||'Save was not confirmed. Your text is retained. Reload observations to check before retrying.';error.hidden=false;return;}finish();if(creating)page=1;message.textContent='Observation saved. Manuscript and scene revision state are unchanged.';await load();}catch{error.textContent='Save was not confirmed. Your text is retained; reload recorded observations before retrying.';error.hidden=false;}finally{busy=false;for(const input of form.querySelectorAll('textarea,select'))input.disabled=false;button.disabled=false;cancel.disabled=false;}});
|
||||
root.addEventListener('click',e=>{const row=e.target.closest('[data-observation]');if(e.target.closest('[data-review-reload]')){if(dirty){message.textContent='Save or Cancel the editor before reloading observations.';return;}void load();}const pager=e.target.closest('[data-review-page]');if(pager){if(dirty){message.textContent='Save or Cancel before changing observation pages.';return;}page=Number(pager.dataset.reviewPage);void load();}
|
||||
if(!row)return;if(e.target.closest('[data-review-edit]')){if(dirty){message.textContent='Save or Cancel your current observation first.';return;}field('ContentVersion').value=reader.dataset.version;field('ID').value=row.dataset.id;field('Version').value=row.dataset.version;field('Observation').value=row.querySelector('[data-observation-text]').textContent;field('Decision').value=row.querySelector('[data-decision-text]').textContent;field('Status').value=row.querySelector('[data-review-edit]').dataset.state;pause(true);dirty=true;reference.textContent='Editing a recorded observation; its original accepted-version reference is retained.';showEditor();}
|
||||
if(e.target.closest('[data-review-revisit]')){if(dirty){message.textContent='Save or Cancel before revisiting another reference.';return;}const target=readerContent.querySelector(`[data-paragraph-id="${CSS.escape(row.dataset.first)}"]`);if(!target){wordReference(null);message.textContent='The original paragraph is missing. Its reference is retained; use the verified chapter action in Word.';return;}target.scrollIntoView({block:'center'});selected=row.dataset.first;anchor=null;wordReference(row.dataset.anchor==='Current'?selected:null);message.textContent=row.dataset.anchor==='Current'?'Original paragraph reference selected. Word has not moved.':'The referenced paragraph changed. Its original reference is retained; exact Word handoff is unavailable. Use the chapter action.';void load();}});
|
||||
readerContent.addEventListener('click',e=>{if(dirty||busy)return;const p=e.target.closest('[data-paragraph-id]');if(!p)return;anchor=capture()||{StartParagraph:p.dataset.paragraphId,EndParagraph:p.dataset.paragraphId,StartOffset:0,EndOffset:p.textContent.length};selected=anchor.StartParagraph;reference.textContent='Accepted paragraph selected; nothing is saved until you record an observation.';wordReference(selected);queueContext();});
|
||||
readerContent.addEventListener('keyup',()=>{if(dirty||busy)return;const choice=capture();if(choice){anchor=choice;selected=choice.StartParagraph;wordReference(selected);queueContext();}});
|
||||
reader.addEventListener('reader:metadata',()=>{if(!dirty)wordReference(selected);});
|
||||
reader.addEventListener('reader:updated',()=>{if(dirty)return;if(selected&&!readerContent.querySelector(`[data-paragraph-id="${CSS.escape(selected)}"]`)){selected=null;anchor=null;wordReference(null);message.textContent='The selected paragraph is no longer in the accepted chapter. Original observation references remain recorded.';}else wordReference(selected);void load();});
|
||||
function guard(e){if(!dirty&&!busy)return;const target=e.target.closest('a,form');if(!target||target===form||target.matches('[data-work-start]')||target.target==='_blank'||target.matches('.plotline-help-more')&&window.PlotLineHelpDrawer)return;if(!confirm(busy?'An observation save may still finish. Leave this Review page?':'Leave without saving your review observation?')){e.preventDefault();e.stopImmediatePropagation();}else allowLeave=true;}
|
||||
document.addEventListener('click',e=>{if(e.target.closest('a'))guard(e);},true);document.addEventListener('submit',guard,true);window.addEventListener('beforeunload',e=>{if((dirty||busy)&&!allowLeave){e.preventDefault();e.returnValue='';}});window.addEventListener('pageshow',e=>{allowLeave=false;if(e.persisted&&!dirty)void load();});window.addEventListener('pagehide',()=>{clearTimeout(selectionTimer);controller?.abort();});void load();
|
||||
})();
|
||||
@ -1,6 +1,7 @@
|
||||
// Consumes the existing native presence/status stream. No second background poller or global selection.
|
||||
(()=>{'use strict';const root=document.querySelector('[data-writer-word]');if(!root)return;
|
||||
const book=Number(root.dataset.bookId),chapter=Number(root.dataset.chapterId),scene=Number(root.dataset.sceneId),state=root.querySelector('[data-word-state]'),position=root.querySelector('[data-word-position]'),freshness=root.querySelector('[data-word-freshness]'),message=root.querySelector('[data-word-command]'),choose=root.querySelector('[data-word-choose]'),select=root.querySelector('[data-word-document]'),nav=root.querySelector('[data-word-navigate]'),sceneNav=root.querySelector('[data-word-scene]'),adopt=root.querySelector('[data-word-adopt]');
|
||||
const reviewing=root.dataset.wordContext==='review',paragraphButton=root.querySelector('[data-word-paragraph]');
|
||||
let packet=null,current=null,busy=false,abort=null,checkBusy=false,syncPending=null;const sync=root.querySelector('[data-word-sync]');
|
||||
const key=l=>l.instanceId+'/'+l.sessionId;
|
||||
const verified=l=>(packet?.verifiedPositions||[]).find(p=>key(p)===key(l));
|
||||
@ -10,18 +11,20 @@ if(old&&(!current||key(old)!==key(current)||old.revision!==current.revision||old
|
||||
if(syncPending&&(!current||syncPending.key!==key(current)||Date.now()-syncPending.started>120000||(syncPending.requestId&¤t.paragraphTransfer?.requestId===syncPending.requestId&&['accepted','needs-review','failed','cancelled'].includes(current.paragraphTransfer.state))))syncPending=null;
|
||||
const identity=current&&data.canonical?.manuscriptID===current.manuscriptId;const observed=current&&verified(current);
|
||||
state.textContent=data.unavailable?'Word Companion status unavailable. Your saved work is retained.':!current?(leases.length>1?'Choose the correct Word manuscript.':(data.leases||[]).some(l=>l.wordAvailable)?'The open Word manuscript is for another book.':'Word Companion is not connected to this manuscript.'):!identity?'Word is connected, but this manuscript has not been verified.':`Manuscript: ${current.documentTitle}`;
|
||||
position.textContent=observed?`Word is showing ${observed.chapterTitle||'the verified chapter'}${observed.sceneId&&observed.sceneTitle?' · '+observed.sceneTitle:''}. ${observed.chapterId!==chapter?'Your working focus is separate.':''}`:current?.wordSaved===false?'Word has unsaved changes. Current positions await verification; no save will be forced.':'Word position has not been verified.';
|
||||
position.textContent=observed?`Word is showing ${observed.chapterTitle||'the verified chapter'}${observed.sceneId&&observed.sceneTitle?' · '+observed.sceneTitle:''}. ${observed.chapterId!==chapter?(reviewing?'Your review selection is separate.':'Your working focus is separate.'):''}`:current?.wordSaved===false?'Word has unsaved changes. Current positions await verification; no save will be forced.':'Word position has not been verified.';
|
||||
let status=!identity?'Your latest changes have not yet been confirmed in PlotDirector.':current.chapterProgress?.state==='Needs review'||current.chapterIssue==='needs_review'?'Manuscript checking needs attention in Companion. Accepted content is retained.':current.paragraphTransfer?.state==='failed'?'Manuscript update failed. Accepted content is retained.':current.chapterProgress?.state==='Synchronised'&¤t.wordSaved===true?'The last manuscript check completed. Later edits may still be pending.':current.chapterProgress?.state?`${current.chapterProgress.state}: ${current.chapterProgress.message||'Latest changes are not yet confirmed.'}`:'Latest changes are not yet confirmed. Check synchronisation in Companion.';
|
||||
if(data.canonical?.chapterAcceptedUtc)status+=' This chapter last accepted: '+new Date(data.canonical.chapterAcceptedUtc).toLocaleString()+'.';else if(data.canonical?.snapshotUtc)status+=' Accepted snapshot recorded: '+new Date(data.canonical.snapshotUtc).toLocaleString()+'.';freshness.textContent=status;
|
||||
sync.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!(current.canChapterSync||current.canParagraphSync);
|
||||
for(const button of [nav,sceneNav])if(button)button.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!current.canAcknowledgeNavigation;
|
||||
for(const button of [nav,sceneNav,paragraphButton])if(button)button.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!current.canAcknowledgeNavigation;
|
||||
if(identity&&!current.canAcknowledgeNavigation)position.textContent+=' Update the Word add-in and Companion together to enable confirmed navigation.';
|
||||
if(paragraphButton)paragraphButton.disabled ||= !root.dataset.paragraphId;
|
||||
const params=new URLSearchParams(location.search),origin=current&¶ms.get('wordInstanceId')===current.instanceId&¶ms.get('wordSessionId')===current.sessionId;
|
||||
adopt.hidden=!(origin&&observed&&observed.chapterId!==chapter);if(!adopt.hidden){adopt.querySelector('[name=ChapterID]').value=observed.chapterId;adopt.querySelector('[name=SceneID]').value=observed.sceneId||'';adopt.querySelector('[data-word-origin]').textContent='Opened from verified Word chapter '+(observed.chapterTitle||'in this manuscript')+'. Your saved working focus is unchanged.';}
|
||||
adopt.hidden=reviewing||!(origin&&observed&&observed.chapterId!==chapter);if(!adopt.hidden){adopt.querySelector('[name=ChapterID]').value=observed.chapterId;adopt.querySelector('[name=SceneID]').value=observed.sceneId||'';adopt.querySelector('[data-word-origin]').textContent='Opened from verified Word chapter '+(observed.chapterTitle||'in this manuscript')+'. Your saved working focus is unchanged.';}
|
||||
}
|
||||
select.addEventListener('change',()=>render(packet));
|
||||
async function navigate(toScene){if(busy||!current||!chapter)return;if(Date.parse(current.expires)<=Date.now()){message.textContent='Word connection expired. Check the connection before navigating.';render({...packet,leases:[]});requestStatus();return;}busy=true;abort=new AbortController();const selected={...current},id=crypto.randomUUID();render(packet);message.textContent='Requesting navigation in Word…';const form=new URLSearchParams({bookId:String(book),chapterId:String(chapter),instanceId:selected.instanceId,sessionId:selected.sessionId,manuscriptId:selected.manuscriptId,revision:String(selected.revision),navigationId:id,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});if(toScene)form.set('sceneId',String(scene));try{const response=await fetch('/WriterWord/Navigate',{method:'POST',body:form,signal:abort.signal});const data=await response.json().catch(()=>null);if(!response.ok)throw Error(data?.message||'Navigation could not be requested. Check your connection and sign-in.');message.textContent='Requested in Word; waiting for confirmation.';const start=Date.now();let done=false;while(Date.now()-start<30000){await new Promise((resolve,reject)=>{const signal=abort.signal;const cancel=()=>{clearTimeout(timer);reject(new Error('Navigation was not confirmed. Word changed or disconnected.'));};const timer=setTimeout(()=>{signal.removeEventListener('abort',cancel);resolve();},1000);signal.addEventListener('abort',cancel,{once:true});});const receipt=await fetch(`/WriterWord/Navigation?bookId=${book}&instanceId=${selected.instanceId}&sessionId=${selected.sessionId}&navigationId=${id}`,{signal:abort.signal,cache:'no-store'});if(!receipt.ok)throw Error('Navigation confirmation unavailable.');const result=await receipt.json();if(result.state!=='requested'){message.textContent=result.state==='completed'?'Word confirmed navigation.':result.state==='failed'?'Word could not navigate. Your work was retained.':'Navigation expired or the document changed. No completion was confirmed.';done=true;break;}}if(!done)message.textContent='Word did not confirm navigation in time. Check the manuscript before retrying.';}catch(error){message.textContent=error.name==='AbortError'?'Navigation was not confirmed. Check Word before retrying.':error.message;}finally{busy=false;abort=null;if(packet)render(packet);requestStatus();}}
|
||||
async function navigate(toScene,toParagraph=false){if(busy||!current||!chapter)return;if(Date.parse(current.expires)<=Date.now()){message.textContent='Word connection expired. Check the connection before navigating.';render({...packet,leases:[]});requestStatus();return;}busy=true;abort=new AbortController();const selected={...current},id=crypto.randomUUID();render(packet);message.textContent='Requesting navigation in Word…';const form=new URLSearchParams({bookId:String(book),chapterId:String(chapter),instanceId:selected.instanceId,sessionId:selected.sessionId,manuscriptId:selected.manuscriptId,revision:String(selected.revision),navigationId:id,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});if(toScene)form.set('sceneId',String(scene));if(toParagraph){form.set('paragraphId',root.dataset.paragraphId);form.set('acceptedRevision',root.dataset.acceptedRevision);}try{const response=await fetch('/WriterWord/Navigate',{method:'POST',body:form,signal:abort.signal});const data=await response.json().catch(()=>null);if(!response.ok)throw Error(data?.message||'Navigation could not be requested. Check your connection and sign-in.');message.textContent='Requested in Word; waiting for confirmation.';const start=Date.now();let done=false;while(Date.now()-start<30000){await new Promise((resolve,reject)=>{const signal=abort.signal;const cancel=()=>{clearTimeout(timer);reject(new Error('Navigation was not confirmed. Word changed or disconnected.'));};const timer=setTimeout(()=>{signal.removeEventListener('abort',cancel);resolve();},1000);signal.addEventListener('abort',cancel,{once:true});});const receipt=await fetch(`/WriterWord/Navigation?bookId=${book}&instanceId=${selected.instanceId}&sessionId=${selected.sessionId}&navigationId=${id}`,{signal:abort.signal,cache:'no-store'});if(!receipt.ok)throw Error('Navigation confirmation unavailable.');const result=await receipt.json();if(result.state!=='requested'){message.textContent=result.state==='completed'?(toParagraph?'Word confirmed navigation to the paragraph start.':'Word confirmed navigation.'):result.state==='failed'?'Word could not navigate. Your work was retained.':'Navigation expired or the document changed. No completion was confirmed.';done=true;break;}}if(!done)message.textContent='Word did not confirm navigation in time. Check the manuscript before retrying.';}catch(error){message.textContent=error.name==='AbortError'?'Navigation was not confirmed. Check Word before retrying.':error.message;}finally{busy=false;abort=null;if(packet)render(packet);requestStatus();}}
|
||||
sync.addEventListener('click',async()=>{if(sync.disabled||!current)return;const selected={...current};syncPending={key:key(selected),started:Date.now()};sync.disabled=true;const body=new URLSearchParams({bookId:String(book),instanceId:selected.instanceId,sessionId:selected.sessionId,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});try{const response=await fetch('/manuscript/paragraphs/snapshot',{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)});const result=await response.json();if(!response.ok||response.redirected)throw Error(result.message||'Manuscript check unavailable.');if(syncPending)syncPending.requestId=result.requestId;message.textContent='Saved manuscript check requested; acceptance has not yet been confirmed. '+(result.message||'');}catch(error){syncPending=null;message.textContent=error.message||'Could not request manuscript check.';}finally{requestStatus();}});
|
||||
paragraphButton?.addEventListener('click',()=>void navigate(false,true));window.addEventListener('review-reference-changed',()=>{if(packet)render(packet);});
|
||||
nav?.addEventListener('click',()=>void navigate(false));sceneNav?.addEventListener('click',()=>void navigate(true));
|
||||
root.querySelector('[data-word-check]').addEventListener('click',()=>{if(checkBusy)return;checkBusy=true;message.textContent='Checking reported connection and accepted updates. Use Synchronise in Companion to request a bounded manuscript check.';requestStatus();setTimeout(()=>checkBusy=false,2000);});
|
||||
window.addEventListener('writer-word-state',event=>render(event.detail));window.addEventListener('native-companion-presence',event=>{if(!event.detail.length&&packet&&!packet.leases?.length&&event.detail.connectionState==='Connected')state.textContent='Companion is connected; open and verify this manuscript in Word.';});window.addEventListener('pagehide',()=>abort?.abort());const initial=document.querySelector('#native-companion-status')?.writerWordState;if(initial)render(initial);
|
||||
|
||||
@ -94,7 +94,7 @@
|
||||
frame = 0;
|
||||
const viewport = window.visualViewport;
|
||||
const bottom = viewport ? viewport.height + viewport.offsetTop : innerHeight;
|
||||
const top = root.getBoundingClientRect().top + window.scrollY;
|
||||
const top = root.getBoundingClientRect().top;
|
||||
// Read the actual shell/header position, including ribbon, banners and PWA chrome; no fixed offset.
|
||||
const available = bottom - top;
|
||||
// At very high text scaling / very short windows use document flow, never clip the heading/tools.
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user