diff --git a/Docs/WordCompanion/2026-11-08-writing-context-workspace.md b/Docs/WordCompanion/2026-11-08-writing-context-workspace.md new file mode 100644 index 00000000..dea9abbe --- /dev/null +++ b/Docs/WordCompanion/2026-11-08-writing-context-workspace.md @@ -0,0 +1,70 @@ +# Writing Context workspace — 8 November 2026 + +## Implementation + +Baseline: shared branch `codex/word-companion-native-phase1-20261104`, fast-forwarded to Windows commit `b7fe1e4` (Companion developer version 1.0.0.21). No branch/worktree, native packaging, installation or Production changes. + +The old native Context route rendered a connection/document card and a second Writing Context document in an iframe. Its presence handler changed the iframe URL on scene changes, destroying the inner window's active state. Links within that document could navigate the frame to a complete application page. The inner pinned view also depended on parent-frame theme inheritance. + +Context and Intent now open the existing `/Writing/Context` and `/Writing/Intent` workspaces directly. Legacy `/native-companion/workspace?view=context|intent` entry points redirect to them, retaining book and explicit document-session selection. The native management page retains diagnostics and saved review/import entry points, with no iframe. There is no replacement embedded-document mechanism. + +### Scene navigation and state + +- The existing `writing-follow.js` fetch/abort/generation mechanism updates the expected scene partial only. Redirected responses, complete HTML documents and responses without the expected sole root fragment are rejected; current content survives failure. +- Jump and Previous/Next use the existing authorised Word Companion book structure in manuscript order, including chapter boundaries. They do not use the former selected-first alphabetical scene list. +- The workspace root survives scene changes. Active tab remains local to that window, with the existing preference retained for initial opening. It is read immediately before replacing a fragment, so changing tabs during an outstanding request is respected. +- Plot Lines and Metrics retain their loaded DOM, filter/metric selections, scrub position and viewport rather than refetching the whole book on cursor movement. Maps retain their host and per-map viewport; scene data updates without reloading a document. Existing view-state restoration handles controls, floor zoom, scroll and map SVG view boxes. Keyboard focus is restored only within a focused browser window, never by focusing the window during Word following. +- People retains the existing scene-specific presentation. Relationships, Overview, Story and Intent continue using their existing partials and services. + +### Word connection and two-way navigation + +The existing top-right Word indicator opens a compact connection dialog: current authorised document sessions, active-document following or exact document selection, heartbeat explanation and troubleshooting/display-settings access. Dedicated windows have the same indicator in their compact application bar. Website connectivity remains separate. The former large native connection panel and follow checkbox are absent from the writing workspace. + +Native presence updates use the existing indicator's authenticated refresh and native SignalR notifications. Context follows scene identity changes, not every heartbeat; reconnect restores Word's actual location. Office.js following remains supported. Writing views reuse the existing workspace follow connection instead of creating another when it is available. + +Only explicit scene navigation posts `/Writing/Context/Navigate`, with antiforgery protection. The server checks: + +1. Current user access to the book and requested scene's actual chapter. +2. A uniquely selected live Word document, or the sole/active document when no exact selection was made. +3. Saved Word state and matching manuscript, session and revision in the persisted paragraph snapshot. +4. The first scene prose paragraph's verified assignment, and an independent authoritative position resolution to that same scene/chapter. +5. The lease still being current and no capture/synchronisation/cancellation command being displaced. + +It queues the **existing** revision-bound `navigate` command. Rapid navigation coalesces to the latest navigation command; capture work is protected. Success means **requested**, not that Word has executed the command. Expired, missing or ambiguous mappings produce an explanation while saved scene browsing continues. Superseded browser requests are cancelled and the server checks request cancellation before queueing. + +Word-to-Context updates and exploratory charts/maps never send commands back to Word. The existing VSTO adapter implements navigation through a positional `Range.Select()` on its Word thread; this change adds no prose writes, marker insertion or document save operation. No new Windows command, IPC contract or installer is required. Actual execution and document dirty-state behaviour still require Windows qualification. + +### Plot Lines, recorded metrics, Maps and Floor Plans + +- **Plot Lines:** existing `IPlotLineWorkspaceService`, Focus/Weave membership/contribution projection and canonical manuscript order. Read-only lanes display saved developments, line filters, a current-scene marker, horizontal scrolling and an exploration scrubber. Only “Go to scene” initiates navigation. +- **Metrics:** existing canonical scene ordering, graph view models and scene repository. Both Timeline's SQL projection and graph builder fill missing values with defaults, while Analytics limits the metric names reported. Migration 244 adds one authorised read-only stored procedure to return all active recorded `SceneMetricValues` for the book; missing entries are gaps, genuine zeroes remain values, and the metric's actual configured range is displayed. No new AI assessment, confidence percentages or invented emotional scores. The existing Development constraint only permits stored values 1–10; it was not weakened or reinterpreted. The pure renderer can preserve zero if supplied, while the live SQL regression uses the permitted minimum and proves that missing values stay absent. +- **Maps:** existing `MapRepository`, `IMapStoryService`/location resolver and `maps-engine.js` geometry. Saved map features, reference images and location relationships are shown in a read-only component. Scene, participant, plot-location and all-place lenses use saved projections. Pan, zoom, place inspection and map switching do not navigate Word or edit maps. A missing reliable location association is stated explicitly; it is not inferred from feature names or canvas proximity. +- **Floor Plans:** existing scene/floor/room/occupancy partial. The saved floor grid gains bounded exploration, zoom and a highlight only for an exact saved scene-location room mapping. Unmapped floors remain an empty state. This is a reference preview, not every editing control from the full Floor Plans workspace. + +New read endpoints check project access and relevant book/project/scene boundaries before exposing data. No database identity mappings, import lifecycle, paragraph reconciliation, evidence, manuscript prose, AI jobs or author decisions are modified. + +### Window management and appearance + +The existing named Context and Intent windows, Left/Right display preferences, Detect Screen permission flow and local preference storage are reused. Changing display selections now saves to that existing preference store. Reopening a window for the same book focuses it without reloading its current scene/tab. Switching books changes the destination deliberately. Popup size is bounded by the available display, including narrower screens. Browser permission/pop-up restrictions still apply; no native always-on-top subsystem was added. + +Dedicated windows now share the main application's server-saved appearance bootstrap and the existing non-sensitive cross-window theme setting. They no longer require an iframe parent to inherit a theme. Dark, light and warm variants use existing CSS variables and theme definitions. + +## Verification + +Final portable verification: + +- `dotnet build PlotLine.slnx --no-restore --disable-build-servers -m:1 /p:UseSharedCompilation=false`: passed, zero warnings/errors. +- `dotnet run --project PlotLine.Tests --no-build`: 455 passing regression assertions. +- `dotnet run --project PlotLine.Tests --no-build -- --writing-context-navigation`: 24 passing assertions covering ownership, canonical order, stale/malformed/exact sessions, revision and saved-state races, and capture-command protection. +- Existing `--native-tray`, `--paragraph-manuscripts` and `--native-capture-lifetime` focused regressions passed. No extraction, reconciliation, capture or AI pipeline implementation changed. +- Browser scripts `writing-context-shell.cjs`, `writing-context-navigation.cjs`, `writing-context-components.cjs`, `writing-context-scale.cjs`, `writing-desks.cjs`, `word-companion-regressions.cjs`, `native-companion-workspace.cjs`: passed. Coverage includes real Razor, direct normal/dedicated/PWA layouts, four light/dark/warm themes, 400/760/1600 widths, tab/scroll/focus preservation, document selection, return-to-Word, cross-chapter navigation, no feedback loops, disconnect/reconnect, full-page Timeline-response rejection, recorded metric gaps, map exploration and floor zoom. +- The 400-scene/10-line Chromium fixture loaded its chart in 297 ms and completed four scene changes in 422 ms with one chart read and retained DOM. These are fixture measurements, not Windows/Word performance guarantees. +- `PlotLine.Tests/Sql/WritingContextMetrics.sql`: guarded transactional Development test passed, including custom metric coverage, exact saved values, absent-value gaps and cross-user denial. All fixture mutations rolled back. Application database principal can execute migration 244's procedure. + + Browser fixtures render the actual compiled Razor partials/full pages and run the actual scripts; they do not start application background workers or access author data. Fixture browser success is distinguished from verification against deployed Development and from actual Word execution. + +## Deployment and remaining qualification + +Deployment is pending the normal Development guard and completion of existing analysis. On inspection, analysis was genuinely progressing (pending runs fell from 22 to 18 with two running); it has not been interrupted, restarted or reset. Migration 244 creates a read-only procedure; no tables, author rows or identity mappings change. It has been applied after a verified copy-only Development backup; application deployment is still waiting for active work to finish. Release identity and actual running-application checks will be recorded after safe deployment. + +After rollout, refresh/reopen Context so a previously loaded legacy document uses the new direct workspace. Windows acceptance should check explicit Jump/Previous/Next into Word, cross-chapter positioning, ordinary cursor following without focus theft or loops, stale-map refusal, document selection, Word's unchanged saved/dirty state, and independent Context/Intent windows. Existing Companion 1.0.0.21 remains installed and untouched. diff --git a/PlotLine.Tests/Browser/native-companion-workspace.cjs b/PlotLine.Tests/Browser/native-companion-workspace.cjs index 930e6fa1..46e4c6a0 100644 --- a/PlotLine.Tests/Browser/native-companion-workspace.cjs +++ b/PlotLine.Tests/Browser/native-companion-workspace.cjs @@ -1,16 +1,9 @@ -const {chromium}=require('playwright');const fs=require('node:fs');const path=require('node:path');const assert=require('node:assert/strict'); +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'); (async()=>{const browser=await chromium.launch();try{ - const page=await browser.newPage();await page.goto('about:blank');await page.setContent('

'); - await page.evaluate(()=>{window.polls=[];window.setInterval=f=>{polls.push(f);return 1;};window.live=[{instanceId:'instance',sessionId:'session',bookId:3,chapterId:10,sceneId:20,chapterTitle:'Arrival',sceneTitle:'The letter',documentTitle:'Synthetic manuscript',wordAvailable:true,updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];window.requestCount=0;window.fetch=async()=>(requestCount++,{ok:true,json:async()=>live});window.hubHandlers={};window.signalR={HubConnectionBuilder:class{withUrl(){return this;}withAutomaticReconnect(){return this;}build(){return{on:(name,callback)=>hubHandlers[name]=callback,onreconnected:()=>{},start:async()=>{},stop:async()=>{}};}}};const OriginalURL=URL;window.URL=class extends OriginalURL{constructor(url,base){super(url,base==='null'?'https://fixture.invalid':base);}};}); - await page.addScriptTag({content:fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/native-companion-workspace.js'),'utf8')}); - await assert.doesNotReject(()=>page.waitForFunction(()=>document.querySelector('#native-presence-status').textContent.includes('connected'))); - await page.check('#native-follow');await page.waitForFunction(()=>document.querySelector('iframe').src.includes('sceneId=20'));assert.ok((await page.locator('iframe').getAttribute('src')).includes('pinned=true'));assert.match(await page.locator('#native-current-scene').textContent(),/Live from Word.*Arrival.*The letter/); - await page.evaluate(()=>{document.querySelector('#native-follow').checked=false;live[0].sceneId=21;polls[0]();});await page.waitForTimeout(30);assert.ok((await page.locator('iframe').getAttribute('src')).includes('sceneId=20'),'manual mode does not snap back to Word'); - await page.evaluate(()=>{live=[];polls[0]();});await page.waitForFunction(()=>document.querySelector('#native-presence-status').textContent.includes('disconnected'));assert.equal(await page.isChecked('#native-follow'),false); - await page.evaluate(()=>{live=[{wordAvailable:false,updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];polls[0]();});await page.waitForFunction(()=>document.querySelector('#native-presence-status').textContent.includes('Word unavailable')); - await page.evaluate(()=>{window.beforeEvents=requestCount;for(let i=0;i<20;i++)hubHandlers.NativePresenceChanged();});await page.waitForTimeout(350);assert.equal(await page.evaluate(()=>requestCount-beforeEvents),1,'SignalR burst coalesces to one authorised refresh'); - await page.selectOption('#native-manual-scene','33');await page.waitForFunction(()=>document.querySelector('iframe').src.includes('sceneId=33'));await page.click('#native-return');assert.ok((await page.locator('iframe').getAttribute('src')).includes('sceneId=33'),'return without Word preserves manual exploration'); - console.log('PASS native PWA exact-session following, pinned scope, manual pause, disconnection and Word-unavailable states'); + const page=await browser.newPage();await page.goto('about:blank');await page.setContent('

'); + await page.evaluate(()=>{window.tick=null;window.setInterval=f=>(tick=f,1);window.opens=[];window.PlotDirectorWritingWorkspace={openRoleWindow:(role,scope)=>opens.push([role,scope.bookID])};window.live=[{instanceId:'a',sessionId:'b',bookId:3,sceneId:20,chapterTitle:'Arrival',sceneTitle:'The letter',documentTitle:'Synthetic manuscript',wordAvailable:true,active:true,updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];window.fetch=async()=>({ok:true,json:async()=>live});}); + await page.addScriptTag({path:path.join(__dirname,'../../PlotLine/wwwroot/js/native-companion-workspace.js')});await page.waitForFunction(()=>document.querySelector('#native-presence-status').textContent.includes('Word connected'));assert.match(await page.locator('#native-current-scene').textContent(),/Arrival.*The letter/);await page.click('[data-native-open-role]');assert.deepEqual(await page.evaluate(()=>opens),[['Context',3]]);assert.equal(await page.locator('iframe').count(),0); + await page.evaluate(()=>{live=[];tick();});await page.waitForFunction(()=>document.querySelector('#native-presence-status').textContent.includes('disconnected'));console.log('PASS native management diagnostics reuse real document leases and open direct workspaces without embedded documents'); const badge=await browser.newPage();await badge.goto('about:blank');await badge.setContent('
');await badge.evaluate(()=>{window.tick=null;window.setInterval=f=>(tick=f,1);window.live=[];window.fetch=async()=>({ok:true,json:async()=>live});}); await badge.addScriptTag({content:fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/native-companion-status.js'),'utf8')});assert.equal(await badge.locator('#native-companion-status').getAttribute('data-connected'),null); await badge.evaluate(()=>{live=[{bookId:3,instanceId:'a',sessionId:'b',wordAvailable:true,documentTitle:'Title ',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];tick();});await badge.waitForFunction(()=>document.querySelector('#native-companion-status').dataset.connected==='true');assert.equal(await badge.locator('#native-companion-status script').count(),0); diff --git a/PlotLine.Tests/Browser/native-integration-development.cjs b/PlotLine.Tests/Browser/native-integration-development.cjs index 1d912396..616537fd 100644 --- a/PlotLine.Tests/Browser/native-integration-development.cjs +++ b/PlotLine.Tests/Browser/native-integration-development.cjs @@ -27,7 +27,8 @@ let step='initialise';const analyse=process.argv.includes('--analyse'); fs.appendFileSync('/tmp/native-integration-live-check.sql',`IF NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds WHERE UserID=${identity.UserID} AND PreviewID='${command.id}' AND Status=N'Complete' AND MarkerStatus=N'NotRequested' AND ScenesCreated>0) THROW 51000,'Native server build did not complete independently',1;\nIF NOT EXISTS(SELECT 1 FROM dbo.SceneManuscriptSources WHERE BookID=${bookId} AND HASHBYTES('SHA2_256',LTRIM(RTRIM(REPLACE(SourceText,CHAR(13),N''))))=0x${crypto.createHash('sha256').update(Buffer.from(body.trim(),'utf16le')).digest('hex')}) THROW 51000,'Canonical manuscript prose differs from the accepted source',1;\nIF NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptCaptures WHERE PreviewID='${command.id}' AND EXISTS(SELECT 1 FROM OPENJSON(AnalysisCheckpoints) a WHERE JSON_VALUE(a.value,'$.Success')='true')) THROW 51000,'Successful chapter analysis was not checkpointed',1;\nPRINT 'PASS actual existing AI scene analysis completed after Word disconnection; canonical prose retained and trusted scene mapping resolved';\n`); } step='real dedicated Context and Intent windows';await page.goto(base+'/native-companion/workspace?bookId='+bookId);const opened=[];context.on('page',p=>opened.push(p));await page.locator('[data-native-open-role=Context]').click();await page.waitForTimeout(700);await page.locator('[data-native-open-role=Intent]').click();await page.waitForTimeout(700);await page.locator('[data-native-open-role=Context]').click();await page.locator('[data-native-open-role=Intent]').click();await page.waitForTimeout(400);assert.equal(opened.length,2,'Repeated launches created duplicate windows'); - for(const popup of opened){await popup.waitForSelector('#native-workspace');assert.equal(await popup.locator('.pd-ribbon,.pd-titlebar').count(),0,'Dedicated window contains application chrome');await popup.waitForSelector('#native-story-workspace',{state:'visible'});assert.ok((await popup.locator('#native-story-workspace').boundingBox()).height>=250);assert.match(await popup.locator('#native-presence-status').innerText(),/disconnected|unavailable/);} + for(const popup of opened){await popup.waitForSelector('[data-writing-context],[data-writing-intent]');assert.equal(await popup.locator('.pd-ribbon,.pd-titlebar,iframe').count(),0,'Dedicated workspace must contain neither normal ribbon nor an embedded application document');await popup.waitForSelector('#native-companion-status');assert.match(await popup.locator('[data-writing-context-status-text],[data-writing-intent-status-text]').innerText(),/disconnected|unavailable|waiting|scene/i);} + console.log('PASS live Development: normal account/wizard/book creation, browser-approved sign-in, exact native registration/header, wizard capture routing, durable intake, disconnected chapter review, and two reused chrome-free Context/Intent windows. '+(analyse?'Synthetic source only; explicit existing AI scene analysis and scene mapping verified; run the generated SQL probe for canonical prose integrity.':'Synthetic source only; no AI request or canonical import.')); }finally{if(agent)await agent.dispose();await browser.close();} })().catch(error=>{fs.writeFileSync('/tmp/native-integration-development-smoke-error.txt',String(error.stack),{mode:0o600});console.error('FAIL Development smoke at '+step+'; private diagnostic recorded.');process.exit(1);}); diff --git a/PlotLine.Tests/Browser/writing-context-components.cjs b/PlotLine.Tests/Browser/writing-context-components.cjs new file mode 100644 index 00000000..2b2e3ccb --- /dev/null +++ b/PlotLine.Tests/Browser/writing-context-components.cjs @@ -0,0 +1,23 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('node:path'); +const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; +(async()=>{const browser=await chromium.launch();try{ + for(const width of [430,1440])for(const theme of ['modern-light','modern-dark','warm-light','warm-dark']){ + const page=await browser.newPage({viewport:{width,height:900}});let commands=0;const requests={plots:0,metrics:0,map:0}; + await page.route('**/Writing/Context/Navigate',async r=>{commands++;await r.fulfill({json:{message:'Navigation requested'}});}); + await page.route('**/Writing/Context/Scene?*',async r=>{const id=new URL(r.request().url()).searchParams.get('sceneId');await r.fulfill({response:await r.fetch({url:base+'/writing-desk-fixture/context?fragment=true&floor=true&sceneId='+id})});}); + await page.route(/\/Writing\/Context\/(PlotLines|Metrics|Map)\?/,async r=>{const url=new URL(r.request().url()),kind=url.pathname.endsWith('PlotLines')?'plots':url.pathname.endsWith('Metrics')?'metrics':'map';requests[kind]++;await r.fulfill({response:await r.fetch({url:base+'/writing-context-component/'+kind+url.search})});}); + await page.goto(base+'/writing-desk-fixture/context?floor=true'); + await page.evaluate(theme=>{document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light';const root=document.querySelector('main');root.dataset.writingContext='';root.dataset.contextUrl='/Writing/Context/Scene';root.dataset.scopeProjectId='7';root.dataset.scopeBookId='12';const host=document.createElement('section');host.dataset.writingContextContent='';while(root.firstChild)host.append(root.firstChild);root.append(host);const status=document.createElement('p');status.dataset.writingContextStatusText='';root.prepend(status);const input=document.createElement('input');input.type='hidden';input.name='__RequestVerificationToken';input.value='fixture';root.append(input);},theme); + for(const script of ['story-position','writing-follow','maps-engine','writing-context-map','writing-context-components','writing-context'])await page.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/'+script+'.js')}); + const beat=async id=>{await page.evaluate(id=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[{instanceId:'fixture',sessionId:'word',bookId:12,chapterId:id===23?11:10,sceneId:id,active:true,wordAvailable:true,wordSaved:true,expires:new Date(Date.now()+45000).toISOString()}]})),id);await page.waitForFunction(id=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId===String(id),id);}; + await page.click('[data-writing-context-tab=plots]');await page.waitForSelector('[data-context-line-filter]');assert.ok(await page.getByText('The letter changes hands',{exact:false}).count()); + await page.uncheck('[data-context-line-filter]');await page.locator('[data-context-spacing]').fill('100');await page.locator('[data-context-scrubber]').fill('1');assert.ok(await page.getByRole('heading',{name:'A room above the quay',exact:true}).isVisible());assert.equal(commands,0,'scrubbing cannot navigate Word'); + await page.evaluate(()=>window.savedPlot=document.querySelector('[data-writing-component=plots]'));await beat(23);assert.ok(await page.evaluate(()=>savedPlot===document.querySelector('[data-writing-component=plots]')));assert.equal(await page.isChecked('[data-context-line-filter]'),false);assert.equal(await page.inputValue('[data-context-spacing]'),'100');assert.equal(requests.plots,1,'scene following retains loaded plot data and filters');await page.locator('[data-writing-component=plots] [data-context-refresh]').click();await page.waitForFunction(()=>document.querySelector('[data-writing-component=plots]').dataset.loaded==='true');assert.equal(requests.plots,2);assert.equal(await page.isChecked('[data-context-line-filter]'),false);assert.equal(await page.inputValue('[data-context-scrubber]'),'1');assert.equal(await page.locator('[data-context-chart-scene="23"]').getAttribute('aria-current'),'location'); + await page.click('[data-writing-context-tab=metrics]');await page.waitForSelector('[data-context-metric-select]');await page.selectOption('[data-context-metric-select]','2');await page.locator('[data-writing-component=metrics] [data-context-scrubber]').fill('1');assert.equal(await page.locator('[data-context-metric="1"] circle').count(),1,'missing saved intensity is not a default point');assert.equal(await page.locator('[data-context-metric="2"] circle').count(),1);await beat(22);assert.equal(await page.inputValue('[data-context-metric-select]'),'2');assert.equal(requests.metrics,1);assert.equal(commands,0); + await page.click('[data-writing-context-tab=maps]');await page.waitForSelector('[data-context-map-canvas]');assert.equal(await page.locator('[data-map-feature]').count(),2);await page.selectOption('[data-context-map-feature]','11111111-1111-4111-8111-111111111111');assert.match(await page.locator('[data-context-map-detail]').textContent(),/Ten minutes/);await page.click('[data-context-map-zoom=".8"]');await page.selectOption('[data-context-map-lens]','people');const viewport=await page.locator('[data-context-map-canvas]').getAttribute('viewBox');await beat(23);await page.waitForFunction(()=>document.querySelector('[data-writing-component=map]').dataset.loaded==='true'&&JSON.parse(document.querySelector('[data-context-map-data]').textContent).sceneID===23);assert.equal(await page.locator('[data-context-map-canvas]').getAttribute('viewBox'),viewport,'map viewport survives scene refresh');assert.equal(await page.inputValue('[data-context-map-lens]'),'people');assert.equal(commands,0); + await page.selectOption('[data-context-map-choice]','2');await page.waitForSelector('[data-writing-view-state="map-viewport-2"]');assert.equal(await page.locator('[data-map-feature]').count(),2,'changing maps rebinds read-only canvas controls'); + await page.click('[data-writing-context-tab=place]');assert.equal(await page.locator('.is-current-room').count(),1);await page.locator('[data-context-floor-zoom]').fill('150');await beat(22);assert.equal(await page.inputValue('[data-context-floor-zoom]'),'150');assert.equal(await page.locator('.writing-context-floor').evaluate(n=>n.style.getPropertyValue('--floor-zoom')),'1.5'); + assert.equal(await page.locator('iframe').count(),0);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,`component overflow ${width} ${theme}`);await page.close(); + } + console.log('PASS actual Razor Plot Lines, recorded-only metrics, exploratory scrubbing, stable loaded panels, map lenses/relationships/zoom, map switching, floor room mapping and persistent zoom across scenes, two widths and all four themes; no exploratory Word commands'); +}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);}); diff --git a/PlotLine.Tests/Browser/writing-context-development.cjs b/PlotLine.Tests/Browser/writing-context-development.cjs new file mode 100644 index 00000000..921f9dbb --- /dev/null +++ b/PlotLine.Tests/Browser/writing-context-development.cjs @@ -0,0 +1,39 @@ +// Explicit live Development protocol verification. Requires guarded synthetic account/snapshot files. +// No AI calls, manuscript imports, Windows automation or real Word COM operations. +const {chromium}=require('playwright'); +const fs=require('node:fs'),crypto=require('node:crypto'),assert=require('node:assert/strict'); +const base='https://dev.plotdirector.com';let step='validate fixture files'; +(async()=>{ + const [identityPath,scopePath]=process.argv.slice(2); + assert.ok(identityPath?.startsWith('/tmp/pd-dev-browser-')&&scopePath?.startsWith('/tmp/pd-context-')); + assert.equal(fs.statSync(identityPath).mode&0o077,0); + const identity=JSON.parse(fs.readFileSync(identityPath)),scope=JSON.parse(fs.readFileSync(scopePath)); + assert.equal(identity.Database,'PlotDirector_Development');assert.equal(identity.UserID,scope.User);assert.match(identity.Email,/^pwa-browser-.*@example\.invalid$/);assert.equal(scope.SceneStarts.length,2); + const browser=await chromium.launch();let keepalive; + try{ + const context=await browser.newContext();await context.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')})); + const page=await context.newPage();step='normal login';await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(identity.Email);await page.locator('[name=Password]').fill(identity.Password);await Promise.all([page.waitForURL(u=>u.pathname!='/Account/Login'),page.locator('form:has(input[name=Password]) button[type=submit]').click()]); + step='browser-approved persistent pairing';const verifier=crypto.randomBytes(32).toString('base64url'),connectionId=crypto.randomUUID(); + let response=await page.request.post(base+'/api/native-companion/pair',{data:{challenge:crypto.createHash('sha256').update(verifier).digest('hex').toUpperCase(),persistent:true,connectionId,deviceName:'Atlas Context protocol verification'}});assert.equal(response.status(),200);const {code}=await response.json(); + await page.goto(base+'/native-companion/authorize?code='+code);const csrf=await page.locator('[name=__RequestVerificationToken]').inputValue();response=await page.request.post(base+'/native-companion/authorize',{form:{code,retainImport:'true',__RequestVerificationToken:csrf}});assert.equal(response.status(),200); + response=await page.request.post(base+'/api/native-companion/token',{data:{code,verifier}});assert.equal(response.status(),200);const tokens=await response.json();const headers={Authorization:'Bearer '+tokens.accessToken}; + let sequence=0,cursor=scope.SceneStarts[0],revision=1;const commands=[]; + const presencePath=(instance=scope.Instance,session=scope.Session)=>base+`/api/native-companion/instances/${instance}/documents/${session}/presence`; + async function heartbeat(){const r=await page.request.post(presencePath(),{headers,data:{bookId:scope.Book,manuscriptId:scope.Manuscript,revision,sequence:++sequence,documentTitle:'Synthetic context manuscript.docx',wordRunning:true,wordAvailable:true,wordSaved:true,canCapture:true,canParagraphSync:true,active:true,cursorStart:cursor}});assert.equal(r.status(),200,'Native registration');const data=await r.json();if(data.navigation)commands.push(data.navigation);return data;} + step='live paragraph cursor resolution';let presence=await heartbeat();assert.equal(presence.sceneId,scope.Scenes[0]);assert.equal(presence.chapterId,scope.Chapters[0]); + keepalive=setInterval(()=>void heartbeat().catch(()=>{}),10000); + step='direct Context and compiled fragments';await page.goto(base+`/native-companion/workspace?bookId=${scope.Book}&instanceId=${scope.Instance}&sessionId=${scope.Session}&view=context`);await page.waitForURL(u=>u.pathname==='/Writing/Context');await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[0]}"]`);assert.equal(await page.locator('iframe').count(),0);assert.equal(await page.locator('.pd-ribbon,.pd-titlebar').count(),0);await page.evaluate(()=>window.originalContextShell=document.querySelector('[data-writing-context]')); + await page.click('[data-writing-context-tab=people]');await page.selectOption('[data-writing-context-scene-select]',String(scope.Scenes[1])); + await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[1]}"]`);await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Navigation requested')); + step='existing native navigation command';await heartbeat();assert.equal(commands.length,1);assert.equal(commands[0].kind,'navigate');assert.equal(commands[0].sessionId.toLowerCase(),scope.Session.toLowerCase());assert.equal(commands[0].revision,1);assert.equal(commands[0].chapter.start,scope.SceneStarts[1]); + cursor=commands[0].chapter.start;presence=await heartbeat();assert.equal(presence.sceneId,scope.Scenes[1]);assert.equal(presence.chapterId,scope.Chapters[1]);await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent==='Following Word');assert.equal(commands.length,1,'Following a cursor must not command Word back');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible()); + step='stale Word revision refusal';revision=2;await heartbeat();const body={bookId:String(scope.Book),sceneId:String(scope.Scenes[0]),instanceId:scope.Instance,sessionId:scope.Session,__RequestVerificationToken:await page.locator('[data-writing-context] [name=__RequestVerificationToken]').inputValue()};response=await page.request.post(base+'/Writing/Context/Navigate',{form:body});assert.equal(response.status(),409);assert.match((await response.json()).message,/mapping|synchronise/i);assert.ok(!(await heartbeat()).navigation); + revision=1;await page.request.delete(presencePath(),{headers});sequence=0;await heartbeat(); + step='actual saved metrics and empty plot data';await page.click('[data-writing-context-tab=metrics]');await page.waitForSelector('[data-writing-component=metrics][data-loaded=true]');assert.ok(await page.locator('[data-context-metric-select] option').count()>0);await page.click('[data-writing-context-tab=plots]');await page.waitForSelector('[data-writing-component=plots][data-loaded=true]');assert.ok(await page.getByText('No saved plot-line developments are available for this book.').isVisible()); + step='disconnect and saved navigation';clearInterval(keepalive);keepalive=null;await page.request.delete(presencePath(),{headers});await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('disconnected'),null,{timeout:25000});await page.click('[data-writing-context-tab=people]');await page.selectOption('[data-writing-context-scene-select]',String(scope.Scenes[0]));await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[0]}"]`); + step='reconnect actual cursor wins';cursor=scope.SceneStarts[1];sequence=0;presence=await heartbeat();assert.equal(presence.sceneId,scope.Scenes[1]);await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[1]}"]`);assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.ok(await page.evaluate(()=>originalContextShell===document.querySelector('[data-writing-context]')));assert.equal(commands.length,1,'Reconnect cannot manufacture navigation commands'); + step='anonymous and antiforgery refusal';const bare=await browser.newContext();const unauthorised=await bare.request.get(base+`/Writing/Context/Metrics?projectId=${scope.Project}&bookId=${scope.Book}`,{maxRedirects:0});assert.ok([302,401].includes(unauthorised.status()));await bare.close();response=await page.request.post(base+'/Writing/Context/Navigate',{form:{bookId:String(scope.Book),sceneId:String(scope.Scenes[0])}});assert.equal(response.status(),400); + step='sign out test installation';await page.request.post(base+'/api/native-companion/revoke',{data:{installationId:tokens.installationId,credential:tokens.deviceSecret,connectionId,nextCredential:'',rotationId:crypto.randomUUID()}});response=await page.request.get(base+'/api/native-companion/books',{headers});assert.equal(response.status(),401); + console.log('PASS live Development: normal browser approval, real native presence and persisted paragraph mapping, direct iframe-free Context, cross-chapter explicit command at exact saved position, cursor acknowledgement without loops, stable People tab/shell, stale revision refusal, read-only metrics/plots, disconnected browsing, reconnect precedence, authentication/antiforgery and revocation. Protocol client only; actual Word execution remains unverified.'); + }finally{if(keepalive)clearInterval(keepalive);await browser.close();} +})().catch(error=>{fs.writeFileSync('/tmp/pd-context-development-error.log',String(error.stack),{mode:0o600});console.error('FAIL Development Context verification at '+step+'; private diagnostic saved.');process.exit(1);}); diff --git a/PlotLine.Tests/Browser/writing-context-navigation.cjs b/PlotLine.Tests/Browser/writing-context-navigation.cjs new file mode 100644 index 00000000..67947e8e --- /dev/null +++ b/PlotLine.Tests/Browser/writing-context-navigation.cjs @@ -0,0 +1,36 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('node:path'); +const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; +(async()=>{const browser=await chromium.launch();try{ + for(const width of [400,760,1600]) for(const theme of ['modern-light','modern-dark','warm-light','warm-dark']){ + const page=await browser.newPage({viewport:{width,height:850}});let commands=0,fullPage=false; + await page.route('**/Writing/Context/Navigate',async route=>{commands++;assert.equal(route.request().method(),'POST');await route.fulfill({json:{message:'Navigation requested in Word. Cursor confirmation is still pending.'}});}); + await page.route('**/Writing/Context/Scene?*',async route=>{ + if(fullPage){await route.fulfill({contentType:'text/html',body:''});return;} + const id=new URL(route.request().url()).searchParams.get('sceneId');await new Promise(r=>setTimeout(r,80)); + const response=await route.fetch({url:base+'/writing-desk-fixture/context?fragment=true&sceneId='+id});await route.fulfill({response}); + }); + await page.goto(base+'/writing-desk-fixture/context'); + await page.evaluate(theme=>{ + document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light'; + const root=document.querySelector('main');root.dataset.writingContext='';root.dataset.contextUrl='/Writing/Context/Scene';root.dataset.scopeProjectId='7';root.dataset.scopeBookId='12'; + const host=document.createElement('section');host.dataset.writingContextContent='';while(root.firstChild)host.append(root.firstChild);root.append(host); + const status=document.createElement('p');status.dataset.writingContextStatusText='';root.prepend(status);const input=document.createElement('input');input.type='hidden';input.name='__RequestVerificationToken';input.value='fixture';root.append(input);window.originalWritingShell=root;window.focusCalls=0;window.focus=()=>focusCalls++; + },theme); + for(const script of ['story-position','writing-follow','writing-context'])await page.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/'+script+'.js')}); + assert.equal(await page.locator('iframe').count(),0); + await page.click('[data-writing-context-tab=people]');await page.locator('[data-writing-context-tab=people]').press('ArrowRight');assert.ok(await page.locator('[data-writing-context-panel=relationships]').isVisible());await page.locator('[data-writing-context-tab=relationships]').press('ArrowLeft');await page.selectOption('[data-writing-context-scene-select]','23'); + await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='23');await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Navigation requested')); + assert.equal(commands,1);assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-chapter-id'),'11'); + assert.ok(await page.evaluate(()=>originalWritingShell===document.querySelector('[data-writing-context]'))); + await page.click('[data-writing-scene-step="22"]');await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='22');await page.waitForTimeout(30);assert.equal(commands,2); + const beat=async id=>page.evaluate(id=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[{instanceId:'instance',sessionId:'document',bookId:12,chapterId:id===23?11:10,sceneId:id,active:true,wordAvailable:true,wordSaved:true,expires:new Date(Date.now()+45000).toISOString()}]})),id); + await page.evaluate(()=>{const spacer=document.createElement('div');spacer.style.height='1400px';document.body.append(spacer);window.scrollTo(0,150);});await page.waitForFunction(()=>Math.abs(scrollY-150)<=2); + await beat(23);await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='23');assert.equal(commands,2,'Word follow must not command Word back');assert.ok(Math.abs(await page.evaluate(()=>scrollY)-150)<=2,`Word scene changes retain page scroll where space permits: ${width} ${theme}, actual ${await page.evaluate(()=>scrollY)}`);assert.equal(await page.evaluate(()=>focusCalls),0,'cursor following must not focus the browser window');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible()); + await page.evaluate(()=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[]})));await page.click('[data-writing-scene-step="22"]');await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='22'); + await beat(23);await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='23');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible(),'reconnection follows actual Word scene without resetting view'); + const before=commands;fullPage=true;await page.selectOption('[data-writing-context-scene-select]','22');await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent==='Context unavailable');assert.equal(await page.locator('nav').filter({hasText:'Timeline shell must never appear here'}).count(),0);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'23');assert.equal(commands,before,'invalid fragments cannot trigger Word navigation'); + assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,`overflow ${width} ${theme}`); + await page.close(); + } + console.log('PASS actual Razor fragments, stable shell, cross-chapter Previous/Next and jump, tab persistence, Word follow without feedback, disconnect/reconnect and full-page response rejection at three widths in four themes'); +}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);}); diff --git a/PlotLine.Tests/Browser/writing-context-scale.cjs b/PlotLine.Tests/Browser/writing-context-scale.cjs new file mode 100644 index 00000000..c48c6ea8 --- /dev/null +++ b/PlotLine.Tests/Browser/writing-context-scale.cjs @@ -0,0 +1,11 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('node:path'); +(async()=>{const browser=await chromium.launch();try{const page=await browser.newPage({viewport:{width:1440,height:950}}),base='http://127.0.0.1:5238';let reads=0; + await page.route('**/Writing/Context/PlotLines?*',async r=>{reads++;await r.fulfill({response:await r.fetch({url:base+'/writing-context-component/plots?large=true'})});}); + await page.route('**/Writing/Context/Scene?*',async r=>r.fulfill({response:await r.fetch({url:base+'/writing-desk-fixture/context?fragment=true&large=true&sceneId='+new URL(r.request().url()).searchParams.get('sceneId')})})); + await page.goto(base+'/writing-desk-fixture/context?large=true');await page.evaluate(()=>{const root=document.querySelector('main');root.dataset.writingContext='';root.dataset.contextUrl='/Writing/Context/Scene';root.dataset.scopeProjectId='7';root.dataset.scopeBookId='12';const host=document.createElement('section');host.dataset.writingContextContent='';while(root.firstChild)host.append(root.firstChild);root.append(host);}); + for(const script of ['story-position','writing-follow','writing-context-components','writing-context'])await page.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/'+script+'.js')}); + const began=Date.now();await page.click('[data-writing-context-tab=plots]');await page.waitForSelector('[data-writing-component=plots][data-loaded=true]');const load=Date.now()-began;assert.equal(await page.locator('[data-context-chart-scene]').count(),400);assert.equal(await page.locator('[data-context-line]').count(),10);assert.equal(await page.locator('[data-context-scene-card]').count(),400);await page.evaluate(()=>window.originalPlot=document.querySelector('[data-writing-component=plots]')); + const changes=Date.now();for(const scene of [100,200,300,421]){await page.evaluate(scene=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[{instanceId:'large',sessionId:'large',bookId:12,chapterId:10+Math.floor((scene-22)/8),sceneId:scene,active:true,wordAvailable:true,wordSaved:true,expires:new Date(Date.now()+45000).toISOString()}]})),scene);await page.waitForFunction(scene=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId===String(scene),scene);} + assert.equal(reads,1);const marker=await page.locator('[data-context-current-marker]').boundingBox(),scroll=await page.locator('.writing-story-scroll').boundingBox();assert.ok(marker.x>=scroll.x&&marker.x<=scroll.x+scroll.width,'current scene remains visible until the author explores manually');assert.ok(await page.evaluate(()=>originalPlot===document.querySelector('[data-writing-component=plots]')));assert.equal(await page.locator('[data-context-chart-scene="421"]').getAttribute('aria-current'),'location');assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false); + console.log(`PASS 400-scene, 10-line actual Razor browser fixture: initial chart ${load}ms; four scene changes ${Date.now()-changes}ms; one chart read, retained DOM/current marker and no page overflow. Chromium fixture measurements only, not Word performance.`); +}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);}); diff --git a/PlotLine.Tests/Browser/writing-context-shell.cjs b/PlotLine.Tests/Browser/writing-context-shell.cjs new file mode 100644 index 00000000..6191eefa --- /dev/null +++ b/PlotLine.Tests/Browser/writing-context-shell.cjs @@ -0,0 +1,19 @@ +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'); +const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; +(async()=>{const browser=await chromium.launch();try{ + for(const embedded of [false,true])for(const installed of [false,true]){ + const page=await browser.newPage({viewport:{width:1280,height:900}});await page.addInitScript(installed=>{if(installed){const match=window.matchMedia.bind(window);window.matchMedia=query=>query==='(display-mode: standalone)'?{matches:true,media:query,addEventListener(){},removeEventListener(){},addListener(){},removeListener(){}}:match(query);}},installed); + await page.route('**/native-companion/status',r=>r.fulfill({json:[{instanceId:'fixture',sessionId:'doc',bookId:12,chapterId:10,sceneId:22,active:true,wordAvailable:true,wordSaved:true,documentTitle:'Synthetic manuscript.docx',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}]})); + await page.route('**/Writing/Context/Scene?*',async r=>r.fulfill({response:await r.fetch({url:base+'/writing-desk-fixture/context?fragment=true&sceneId='+new URL(r.request().url()).searchParams.get('sceneId')})})); + await page.route(/\/Writing\/Context\/(PlotLines|Metrics|Map)\?/,async r=>{const url=new URL(r.request().url()),kind=url.pathname.endsWith('PlotLines')?'plots':url.pathname.endsWith('Metrics')?'metrics':'map';await r.fulfill({response:await r.fetch({url:base+'/writing-context-component/'+kind+url.search})});}); + const response=await page.goto(base+'/Writing/Context?bookId=12'+(embedded?'&embedded=true':''));assert.equal(response.status(),200); + await page.waitForSelector('[data-writing-context-fragment][data-scene-id="22"]');assert.equal(await page.locator('iframe').count(),0);assert.equal(await page.locator('#native-companion-status').count(),1);await page.click('#native-companion-status');assert.ok(await page.locator('#writing-connection-details').isVisible());assert.ok(await page.getByRole('option',{name:'Synthetic manuscript.docx · active in Word'}).count());await page.click('[data-close-word-details]'); + await page.click('[data-writing-context-tab=people]');await page.selectOption('[data-writing-context-scene-select]','23');await page.waitForSelector('[data-writing-context-fragment][data-scene-id="23"]');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.equal(await page.locator('iframe').count(),0); + await page.click('#native-companion-status');await page.click('[data-word-return-to-current]');await page.waitForSelector('[data-writing-context-fragment][data-scene-id="22"]');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible()); + if(embedded)assert.equal(await page.locator('.pd-application-header').count(),0,'dedicated workspace has no normal ribbon'); + await page.evaluate(()=>window.dispatchEvent(new StorageEvent('storage',{key:'plotdirector.applicationTheme',newValue:'warm-dark'})));await page.waitForFunction(()=>document.documentElement.dataset.appTheme==='warm-dark'&&document.documentElement.dataset.bsTheme==='dark'); + if(process.env.PD_SCREENSHOT_DIR&&embedded&&!installed){fs.mkdirSync(process.env.PD_SCREENSHOT_DIR,{recursive:true});for(const tab of ['plots','metrics','maps']){await page.click('[data-writing-context-tab='+tab+']');await page.waitForFunction(tab=>document.querySelector('[data-writing-context-panel='+tab+'] [data-writing-component]').dataset.loaded==='true',tab);await page.screenshot({path:process.env.PD_SCREENSHOT_DIR+'/'+tab+'-warm-dark.png',fullPage:true});}} + await page.close(); + } + console.log('PASS full compiled Context page, compact connection dialog/document selection, live native event path, fragment navigation and People tab in browser/PWA and dedicated-window layouts; no iframe'); +}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);}); diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 38c41e5e..520c975a 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -136,6 +136,8 @@ if(args.Contains("--paragraph-chapters")){ParagraphChapterTests.Run();return;} if(args.Contains("--paragraph-manuscripts")){ParagraphChapterTests.Run();ParagraphBackupTests.Run();ParagraphManuscriptTests.Run();await ParagraphWorkflowTests.Run();return;} if(args.Contains("--native-import-corrections")){await NativeImportCorrectionTests.Run();return;} if(args.Contains("--native-captured-evidence")){await NativeImportCorrectionTests.CapturedEvidence(args[1],args[2]);return;} +if(args.Contains("--writing-context-dev-seed")){await WritingContextDevelopmentFixture.Run(args);return;} +if(args.Contains("--writing-context-navigation")){await WritingContextNavigationTests.Run();return;} if(args.Contains("--native-capture-lifetime")){await NativeCaptureLifetimeTests.Run();return;} if(args.Contains("--native-tray")){await NativeTrayIntegrationTests.Run();await NativeManuscriptCaptureTests.Run();Console.WriteLine("PASS native tray presence, expiry, scope and persistent PWA review decisions");return;} if(args.Contains("--native-workflow")){await NativeWorkflowTests.Run();Console.WriteLine("PASS native saved workspace and safe import preview validation");return;} diff --git a/PlotLine.Tests/Sql/WritingContextMetrics.sql b/PlotLine.Tests/Sql/WritingContextMetrics.sql new file mode 100644 index 00000000..396370d0 --- /dev/null +++ b/PlotLine.Tests/Sql/WritingContextMetrics.sql @@ -0,0 +1,31 @@ +-- SQLCMD variables: FixtureUserID, FixtureBookID, FixtureSceneOne, FixtureSceneTwo. +-- Only a guarded pwa-browser synthetic account is permitted. All test writes roll back. +SET NOCOUNT ON; +SET XACT_ABORT ON; +IF DB_NAME()<>N'PlotDirector_Development' THROW 51000,'Development only',1; +DECLARE @User int=$(FixtureUserID),@Book int=$(FixtureBookID),@One int=$(FixtureSceneOne),@Two int=$(FixtureSceneTwo),@Project int; +IF NOT EXISTS(SELECT 1 FROM dbo.AppUser WHERE UserID=@User AND Email LIKE 'pwa-browser-%@example.invalid') THROW 51000,'Synthetic account required',1; +SELECT @Project=b.ProjectID FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@User AND a.AccessRole=N'Owner' AND a.IsActive=1 WHERE b.BookID=@Book; +IF @Project IS NULL OR (SELECT COUNT(*) FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@Book AND s.SceneID IN(@One,@Two))<>2 THROW 51000,'Fixture book/scene boundary mismatch',1; +BEGIN TRY + EXEC dbo.SceneMetric_ListRecordedForBook @BookID=@Book,@UserID=-1; + THROW 51001,'Unauthorised metric read was accepted',1; +END TRY BEGIN CATCH IF ERROR_NUMBER()<>51000 THROW; END CATCH; +BEGIN TRY + BEGIN TRANSACTION; + DECLARE @Metric int,@Inactive int; + INSERT dbo.SceneMetricTypes(ProjectID,MetricName,MinValue,MaxValue,DefaultValue,SortOrder,IsActive) VALUES(@Project,CONCAT(N'Fixture direction ',NEWID()),1,10,3,999,1); + SET @Metric=SCOPE_IDENTITY(); + INSERT dbo.SceneMetricValues(SceneID,MetricTypeID,Value,Notes) VALUES(@One,@Metric,1,N'Explicit recorded minimum; missing second-scene value must remain absent'); + INSERT dbo.SceneMetricTypes(ProjectID,MetricName,MinValue,MaxValue,DefaultValue,SortOrder,IsActive) VALUES(@Project,CONCAT(N'Fixture inactive ',NEWID()),0,10,5,1000,0); + SET @Inactive=SCOPE_IDENTITY(); + INSERT dbo.SceneMetricValues(SceneID,MetricTypeID,Value) VALUES(@Two,@Inactive,8); + DECLARE @Rows table(SceneID int,MetricTypeID int,MetricName nvarchar(200),MinValue int,MaxValue int,DefaultValue int,SortOrder int,IsActive bit,Value int,Notes nvarchar(max)); + INSERT @Rows EXEC dbo.SceneMetric_ListRecordedForBook @BookID=@Book,@UserID=@User; + IF (SELECT COUNT(*) FROM @Rows WHERE MetricTypeID=@Metric)<>1 OR NOT EXISTS(SELECT 1 FROM @Rows WHERE MetricTypeID=@Metric AND SceneID=@One AND Value=1) THROW 51000,'Missing values were filled, a recorded minimum was lost, or custom metrics were omitted',1; + IF EXISTS(SELECT 1 FROM @Rows WHERE MetricTypeID=@Inactive) THROW 51000,'Inactive metric leaked into the active view',1; + IF EXISTS(SELECT SceneID,MetricTypeID,Value,Notes FROM @Rows EXCEPT SELECT v.SceneID,v.MetricTypeID,v.Value,v.Notes FROM dbo.SceneMetricValues v JOIN dbo.Scenes s ON s.SceneID=v.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.SceneMetricTypes t ON t.MetricTypeID=v.MetricTypeID WHERE c.BookID=@Book AND c.IsArchived=0 AND s.IsArchived=0 AND t.IsActive=1 AND (t.ProjectID IS NULL OR t.ProjectID=@Project)) THROW 51000,'Projection invented or cross-scoped metric data',1; + IF EXISTS(SELECT v.SceneID,v.MetricTypeID,v.Value,v.Notes FROM dbo.SceneMetricValues v JOIN dbo.Scenes s ON s.SceneID=v.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.SceneMetricTypes t ON t.MetricTypeID=v.MetricTypeID WHERE c.BookID=@Book AND c.IsArchived=0 AND s.IsArchived=0 AND t.IsActive=1 AND (t.ProjectID IS NULL OR t.ProjectID=@Project) EXCEPT SELECT SceneID,MetricTypeID,Value,Notes FROM @Rows) THROW 51000,'Projection silently omitted recorded values',1; + ROLLBACK; + PRINT 'PASS recorded-only metrics, custom types outside Timeline settings, missing values, genuine minimum, inactive filtering, exact row/value equivalence and cross-user refusal; test writes rolled back'; +END TRY BEGIN CATCH IF XACT_STATE()<>0 ROLLBACK;THROW; END CATCH; diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index ea8a7640..84838091 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -99,7 +99,7 @@ internal static class ToolbarBrowserHost if (!view.Success) throw new Exception(string.Join(",", view.SearchedLocations)); using var writer = new StringWriter(); await view.View.RenderAsync(new ViewContext(action, view.View, - new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }, + new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model, ["WritingEmbedded"] = context.Request.Query["embedded"] == "true" }, new TempDataDictionary(context, context.RequestServices.GetRequiredService()), writer, new HtmlHelperOptions())); context.Response.ContentType = "text/html; charset=utf-8"; await context.Response.WriteAsync(writer.ToString()); @@ -241,14 +241,39 @@ internal static class ToolbarBrowserHost app.MapGet("/writing-desk-fixture/{role}",async context=> { var role=context.Request.RouteValues["role"]?.ToString();var empty=context.Request.Query["empty"]=="true"; - var scene=new SceneEditViewModel{SceneID=22,SceneTitle="A deliberately long scene title for a narrow reference screen",ChapterID=10,ScenePurposeNotes="Reveal the letter",Summary="Saved scene summary",Project=new Project{ProjectID=7,ProjectName="Fixture project"},Book=new Book{BookID=12,BookTitle="Fixture book"},Chapter=new Chapter{ChapterID=10,ChapterTitle="Opening",ChapterNumber=1}}; - var story=new StoryContextViewModel{Position=new StoryPosition(7,12,10,22),Scene=scene}; - object model=role=="evidence"?new IntentAssessmentFrame(22,context.Request.Query["stale"]=="true"?"new-hash":"saved-hash",[new("purpose","Reveal the letter")],"Saved prose",new IntentAssessment{InputHash="saved-hash",CreatedUtc=DateTime.UtcNow,ResultsJson=System.Text.Json.JsonSerializer.Serialize(new[]{new IntentEvidence("purpose","partial","A qualified suggestion","Saved prose","Reveal the letter")}),DecisionsJson="{\"purpose\":\"deferred\"}"}):role=="context"?new WritingContextDisplayViewModel{Context=empty?null:story}:new WritingIntentDisplayViewModel{Context=empty?null:story}; + var scene=new SceneEditViewModel{SceneID=int.TryParse(context.Request.Query["sceneId"],out var selectedScene)?selectedScene:22,SceneTitle="A deliberately long scene title for a narrow reference screen",ChapterID=selectedScene==23?11:10,ScenePurposeNotes="Reveal the letter",Summary="Saved scene summary",Project=new Project{ProjectID=7,ProjectName="Fixture project"},Book=new Book{BookID=12,BookTitle="Fixture book"},Chapter=new Chapter{ChapterID=selectedScene==23?11:10,ChapterTitle=selectedScene==23?"Next chapter":"Opening",ChapterNumber=selectedScene==23?2:1}}; + if(context.Request.Query["large"]=="true"){var index=Math.Max(0,scene.SceneID-22);scene.ChapterID=10+index/8;scene.Chapter=new(){ChapterID=scene.ChapterID,ChapterNumber=index/8+1,ChapterTitle="Chapter "+(index/8+1)};scene.SceneNumber=index%8+1;scene.SceneTitle="Scene "+(index+1);} + var story=new StoryContextViewModel{Position=new StoryPosition(7,12,scene.ChapterID,scene.SceneID),Scene=scene}; + object model=role=="evidence"?new IntentAssessmentFrame(22,context.Request.Query["stale"]=="true"?"new-hash":"saved-hash",[new("purpose","Reveal the letter")],"Saved prose",new IntentAssessment{InputHash="saved-hash",CreatedUtc=DateTime.UtcNow,ResultsJson=System.Text.Json.JsonSerializer.Serialize(new[]{new IntentEvidence("purpose","partial","A qualified suggestion","Saved prose","Reveal the letter")}),DecisionsJson="{\"purpose\":\"deferred\"}"}):role=="context"?new WritingContextDisplayViewModel{Context=empty?null:story,SceneOptions=[new("Chapter one · first scene","22",scene.SceneID==22),new("Chapter two · next scene","23",scene.SceneID==23)]}:new WritingIntentDisplayViewModel{Context=empty?null:story}; + if(model is WritingContextDisplayViewModel reference&&context.Request.Query["large"]=="true")reference.SceneOptions=Enumerable.Range(0,400).Select(i=>new SelectListItem($"Chapter {i/8+1} · Scene {i%8+1}",(i+22).ToString(),scene.SceneID==i+22)).ToArray(); + if(role=="context"&&context.Request.Query["floor"]=="true"){ + scene.PrimaryLocationID=77;scene.FloorPlanID=1;scene.InitialFloorPlanFloorID=8; + ((WritingContextDisplayViewModel)model).FloorPlan=new(){FloorPlan=new(){FloorPlanID=1,Name="The inn"},Floors=[new(){FloorPlanFloorID=8,Name="Upper floor",GridWidth=20,GridHeight=10}],Blocks=[new(){FloorPlanFloorID=8,FloorPlanBlockID=9,LocationID=77,LocationName="Guest room",X=2,Y=2,WidthCells=4,HeightCells=3}]}; + } var writingRoute=new RouteData();writingRoute.Values["controller"]="Writing";var action=new ActionContext(context,writingRoute,new ActionDescriptor());var path=role=="evidence"?"/Views/Writing/_IntentAssessment.cshtml":role=="context"?"/Views/Writing/_WritingContextContent.cshtml":"/Views/Writing/_WritingIntentContent.cshtml"; var view=context.RequestServices.GetRequiredService().GetView(null,path,false);using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model}; await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions())); + if(context.Request.Query["fragment"]=="true"){context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString());return;} context.Response.ContentType="text/html";await context.Response.WriteAsync("
"+writer+"
"); }); + app.MapGet("/writing-context-component/{kind}",async context=>{ + var kind=context.Request.RouteValues["kind"]?.ToString();var mapID=int.TryParse(context.Request.Query["mapId"],out var selectedMap)?selectedMap:1;var sceneId=int.TryParse(context.Request.Query["sceneId"],out var sid)?sid:22; + var scenes=new[]{new Scene{SceneID=22,ChapterID=10,SceneNumber=1,SceneTitle="Harbour arrival"},new Scene{SceneID=23,ChapterID=11,SceneNumber=1,SceneTitle="A room above the quay"}}; + var mapFeature=Guid.Parse("11111111-1111-4111-8111-111111111111");var second=Guid.Parse("22222222-2222-4222-8222-222222222222"); + object model=kind=="plots"?new PlotLineWorkspaceViewModel{Project=new(){ProjectID=7},SelectedBookID=12,PlotLines=[new(){Line=new(){PlotLineID=1,PlotLineName="The missing letter",Colour="#487b70"},IsSelected=true}],AssociationScenes=[new(){SceneID=22,SceneTitle=scenes[0].SceneTitle,ChapterNumber=1,SceneNumber=1,NarrativeOrder=0},new(){SceneID=23,SceneTitle=scenes[1].SceneTitle,ChapterNumber=2,SceneNumber=1,NarrativeOrder=1}],Scenes=[new(){SceneID=22,Memberships=[new(){PlotLineID=1,PlotLineName="The missing letter",Contributions=[new(){ThreadTitle="The arrival",CanonicalTitle="The letter changes hands"}]}]}]}: + kind=="metrics"?WritingContextMetrics.Build(new TimelineData{Project=new(){ProjectID=7},Books=[new(){BookID=12}],Chapters=[new(){ChapterID=10,BookID=12,ChapterNumber=1},new(){ChapterID=11,BookID=12,ChapterNumber=2}],Scenes=scenes,MetricTypes=[new(){MetricTypeID=1,MetricName="Emotional intensity",MinValue=0,MaxValue=10,DefaultValue=5},new(){MetricTypeID=2,MetricName="Emotional direction",MinValue=-5,MaxValue=5}],MetricPoints=[new(){SceneID=22,MetricTypeID=1,Value=8},new(){SceneID=23,MetricTypeID=2,Value=0}]},[new(){SceneID=22,MetricTypeID=1,MetricName="Emotional intensity",MinValue=0,MaxValue=10,Value=8},new(){SceneID=23,MetricTypeID=2,MetricName="Emotional direction",MinValue=-5,MaxValue=5,Value=0}]): + new WritingContextMapViewModel{ProjectID=7,BookID=12,SceneID=sceneId,Maps=[new(){MapID=1,Name="Harbour map"},new(){MapID=2,Name="Neighbouring coast"}],Position=new(){FeatureID=sceneId==22?mapFeature:second,LocationID=77,LocationName="Saved harbour",Status="Mapped"},Document=context.Request.Query["empty"]=="true"?null:new(){Map=new(){MapID=mapID,ProjectID=7,Name="Harbour map"},Features=[new(){FeatureID=mapFeature,Name="Harbour",X=0,Y=0,LocationID=77,IsPlaced=true},new(){FeatureID=second,Name="Inn",X=500,Y=200,IsPlaced=true}],Relationships=[new(){SourceID=mapFeature,TargetID=second,Direction="NE",RelativeDistance="Close",TypicalTravelTime="Ten minutes"}]},Story=new(){Scenes=[new(){SceneID=22,PlotLineIDs=[1],Position=new(){FeatureID=mapFeature}}],Stops=[new(){SceneID=22,Position=new(){FeatureID=second}}]}}; + if(context.Request.Query["large"]=="true"&&model is PlotLineWorkspaceViewModel large){ + large.PlotLines=Enumerable.Range(1,10).Select(i=>new PlotLineWorkspaceLineViewModel{Line=new(){PlotLineID=i,PlotLineName="Plot line "+i,Colour=PlotLineColours.ForLine(i,null)},IsSelected=true}).ToArray(); + large.AssociationScenes=Enumerable.Range(0,400).Select(i=>new PlotLineWorkspaceAttributionRow{SceneID=i+22,SceneTitle="Scene "+(i+1),ChapterNumber=i/8+1,SceneNumber=i%8+1,NarrativeOrder=i}).ToArray(); + large.Scenes=Enumerable.Range(0,400).Select(i=>new PlotLineWorkspaceSceneViewModel{SceneID=i+22,Memberships=[new(){PlotLineID=i%10+1,PlotLineName="Plot line "+(i%10+1),Contributions=[new(){ThreadTitle="Saved thread",CanonicalTitle="Recorded development "+(i+1)}]}]}).ToArray(); + } + var path=kind=="plots"?"_WritingContextPlotLines":kind=="metrics"?"_WritingContextMetrics":"_WritingContextMap"; + var route=new RouteData();route.Values["controller"]="Writing";var action=new ActionContext(context,route,new ActionDescriptor()); + var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Writing/"+path+".cshtml",false);using var writer=new StringWriter(); + await view.View!.RenderAsync(new ViewContext(action,view.View,new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model},new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions())); + context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString()); + }); app.MapGet("/book-recovery-fixture/{step}",async context=>{ var project=new Project{ProjectID=7,ProjectName="Harbour collection"}; var snapshot=new ProjectBackupExport{Project=project,Data=new(){Books=[new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore — long title with notes",SortOrder=1},new(){BookID=13,ProjectID=7,BookTitle="The archived sequel",IsArchived=true,SortOrder=2}]}}; diff --git a/PlotLine.Tests/WritingContextDevelopmentFixture.cs b/PlotLine.Tests/WritingContextDevelopmentFixture.cs new file mode 100644 index 00000000..6757340a --- /dev/null +++ b/PlotLine.Tests/WritingContextDevelopmentFixture.cs @@ -0,0 +1,51 @@ +using System.Diagnostics; +using System.Text.Json; +using Microsoft.Data.SqlClient; +using Microsoft.Extensions.Configuration; +using PlotDirector.Companion.Protocol.Manuscript; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services.Manuscript; +internal static class WritingContextDevelopmentFixture +{ + public sealed class Scope + { + public int User {get;set;}public int Project {get;set;}public int Book {get;set;} + public int[] Chapters {get;set;}=[];public int[] Scenes {get;set;}=[]; + public Guid Instance {get;set;}public Guid Session {get;set;}public Guid Manuscript {get;set;} + public int[] SceneStarts {get;set;}=[]; + } + public static async Task Run(string[] args) + { + if(!OperatingSystem.IsLinux()||args.Length!=3||!args[1].StartsWith("/tmp/pd-dev-browser-",StringComparison.Ordinal)||!args[2].StartsWith("/tmp/pd-context-",StringComparison.Ordinal))throw new Exception("Explicit private Development fixture files required"); + if((File.GetUnixFileMode(args[1])&(UnixFileMode.GroupRead|UnixFileMode.OtherRead))!=0)throw new Exception("Identity file must be private"); + using var identity=JsonDocument.Parse(await File.ReadAllTextAsync(args[1]));var who=identity.RootElement; + var scope=JsonSerializer.Deserialize(await File.ReadAllTextAsync(args[2]))!; + var email=who.GetProperty("Email").GetString()!; + if(who.GetProperty("Database").GetString()!="PlotDirector_Development"||who.GetProperty("UserID").GetInt32()!=scope.User||!email.StartsWith("pwa-browser-")||!email.EndsWith("@example.invalid")||scope.Book<=0||scope.Project<=0||scope.Session==Guid.Empty||scope.Manuscript==Guid.Empty)throw new Exception("Fixture identity mismatch"); + var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true};foreach(var part in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(part); + using var process=Process.Start(start)!;var environment=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new Exception("Development configuration inaccessible"); + var connectionString=environment.Split('\n').Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\''); + if(new SqlConnectionStringBuilder(connectionString).InitialCatalog!="PlotDirector_Development")throw new Exception("Unexpected database"); + var factory=new SqlConnectionFactory(new ConfigurationBuilder().AddInMemoryCollection(new Dictionary{{"ConnectionStrings:DefaultConnection",connectionString}}).Build()); + var user=await new UserRepository(factory).GetByEmailAsync(email);var project=await new ProjectRepository(factory).GetForUserAsync(scope.Project,scope.User);var book=await new BookRepository(factory).GetAsync(scope.Book); + if(user?.UserID!=scope.User||project?.IsOwner!=true||book?.ProjectID!=scope.Project)throw new Exception("Synthetic project ownership mismatch"); + var snapshots=new ParagraphManuscriptRepository(factory);if(await snapshots.Get(scope.User,scope.Book)!=null)throw new Exception("Refusing to overwrite an existing paragraph snapshot"); + var chapters=new ChapterRepository(factory);var scenes=new SceneRepository(factory);var lookup=await new LookupRepository(factory).GetAllAsync(); + for(int i=0;i<2;i++){ + if(scope.Chapters.Length<=i){var created=await chapters.SaveAsync(new(){BookID=scope.Book,ChapterNumber=i+1,ChapterTitle="Context fixture chapter "+(i+1),RevisionStatusID=lookup.RevisionStatuses.First().RevisionStatusID,SortOrder=i+1});scope.Chapters=[..scope.Chapters,created];await File.WriteAllTextAsync(args[2],JsonSerializer.Serialize(scope));} + var chapter=await chapters.GetAsync(scope.Chapters[i]);if(chapter?.BookID!=scope.Book)throw new Exception("Foreign fixture chapter"); + if(scope.Scenes.Length<=i){var created=await scenes.SaveAsync(new(){ChapterID=scope.Chapters[i],SceneNumber=1,SceneTitle="Context fixture scene "+(i+1),RevisionStatusID=lookup.RevisionStatuses.First().RevisionStatusID,TimeModeID=lookup.TimeModes.First().TimeModeID,TimeConfidenceID=lookup.TimeConfidences.First().TimeConfidenceID,SortOrder=1});scope.Scenes=[..scope.Scenes,created];await File.WriteAllTextAsync(args[2],JsonSerializer.Serialize(scope));} + if((await scenes.GetAsync(scope.Scenes[i]))?.ChapterID!=scope.Chapters[i])throw new Exception("Foreign fixture scene"); + } + var structure=await new WordCompanionRepository(factory).GetBookStructureAsync(scope.Book,scope.User); + if(structure?.Chapters.Count!=2||!structure.Chapters.SelectMany(c=>c.Scenes).Select(s=>s.SceneId).SequenceEqual(scope.Scenes))throw new Exception("Unexpected fixture structure; refusing adoption"); + var rows=new List();int position=0;foreach(var text in new[]{"Chapter one\r","First exact synthetic paragraph.\r","More first-scene evidence.\r","Chapter two\r","Second exact synthetic paragraph.\r","More second-scene evidence.\r"}){var outline=rows.Count%3==0?1:10;rows.Add(new(){Ordinal=rows.Count,Start=position,End=position+text.Length,Text=text,Outline=outline});position+=text.Length;} + var state=ParagraphManuscriptEngine.Bootstrap(scope.Book,scope.Project,scope.Manuscript,rows,[new(){ChapterId=scope.Chapters[0],SceneId=scope.Scenes[0],Start=2,End=3,Title="Context fixture scene 1"},new(){ChapterId=scope.Chapters[1],SceneId=scope.Scenes[1],Start=5,End=6,Title="Context fixture scene 2"}]); + state.SessionId=scope.Session;state.WordRevision=1;state.DocumentName="Synthetic context manuscript.docx";state.Mode="Manual";state.SnapshotHash=ParagraphManuscriptEngine.Hash(state.Paragraphs.Select(p=>p.Occurrence).ToArray()); + var saved=await snapshots.Save(scope.User,state,-1,Guid.NewGuid()); + if(saved.Paragraphs.Count!=6||saved.Scenes.Count!=2||saved.Paragraphs.Any(p=>p.Story&&!p.PositionVerified))throw new Exception("Fixture snapshot verification failed"); + scope.SceneStarts=[saved.Paragraphs[1].Occurrence.Start,saved.Paragraphs[4].Occurrence.Start];await File.WriteAllTextAsync(args[2],JsonSerializer.Serialize(scope)); + Console.WriteLine($"PASS guarded Development fixture: book {scope.Book}, two canonical chapters/scenes, six exact paragraphs; no AI, import job or author data changed"); + } +} diff --git a/PlotLine.Tests/WritingContextNavigationTests.cs b/PlotLine.Tests/WritingContextNavigationTests.cs new file mode 100644 index 00000000..3bb9f9f0 --- /dev/null +++ b/PlotLine.Tests/WritingContextNavigationTests.cs @@ -0,0 +1,61 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging.Abstractions; +using PlotDirector.Companion.Protocol; +using PlotLine.Controllers; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services.NativeCompanion; +internal static class WritingContextNavigationTests +{ + public static async Task Run() + { + var instance=Guid.NewGuid();var session=Guid.NewGuid();var manuscript=Guid.NewGuid();var group=Guid.NewGuid(); + var presence=new NativePresenceStore(TimeProvider.System);long sequence=0; + void Beat(long revision=3,bool saved=true)=>presence.Put(7,"installation",DateTimeOffset.UtcNow.AddMinutes(10),instance,session,new(){BookId=12,ManuscriptId=manuscript,Revision=revision,Sequence=++sequence,WordSaved=saved,CanCapture=true,Active=true,DocumentTitle="Synthetic manuscript.docx"}); + Beat(); + var allowed=true;var structure=new WordCompanionBookStructureResponse{BookId=12,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=22}]},new(){ChapterId=11,Scenes=[new(){SceneId=23}]}]}; + var access=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(allowed&&Equals(a![1],7)?structure:null)); + var state=new ParagraphManuscript{BookId=12,ManuscriptId=manuscript,SessionId=session,WordRevision=3,Scenes=[new(){Id=group,ChapterId=11,CanonicalId=23}],Paragraphs=[new(){SceneId=group,ChapterId=11,Story=true,PositionVerified=true,Occurrence=new(){Start=100,End=150,Ordinal=4,Text="Preserved exact prose"}}]}; + int? resolvedScene=23;long? resolvedRevision=null;bool invalidateSaved=false; + var paragraphs=NativeWorkflowTests.Proxy((n,a)=>{ + if(n=="Get")return Task.FromResult(state); + if(n=="Position"){if(invalidateSaved)Beat(3,false);return Task.FromResult(new(){HasSnapshot=true,Revision=resolvedRevision??state.Revision,SceneID=resolvedScene,ChapterID=11});} + throw new Exception(n); + }); + var native=new NativeWorkspaceController(access,NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(new(){BookID=12,ProjectID=7,BookTitle="Fixture book"})),NativeWorkflowTests.Proxy((n,a)=>throw new Exception("Context launch must not load old review/iframe shell")),presence){ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture"))}}}; + var direct=await native.Workspace(12,instance,session,"context") as RedirectToActionResult; + Check(direct?.ActionName=="Context"&&direct.ControllerName=="Writing"&&Equals(direct.RouteValues!["instanceId"],instance),"Native Context opens the existing Writing workspace directly and preserves document selection, with no iframe"); + var controller=new WritingController(null!,null!,null!,null!,NullLogger.Instance){ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture"))}}}; + Task Navigate(Guid? document=null)=>controller.NavigateWord(12,23,document??instance,session,access,paragraphs,presence); + Check(await Navigate() is OkObjectResult,"Explicit cross-chapter navigation accepts an owned scene and current verified paragraph start"); + var command=presence.TakeNavigation(7,"installation",instance,session);Check(command?.Kind=="navigate"&&command.Chapter?.Start==100&&command.Revision==3,"Existing positional command routes to exact session/revision without writing prose or markers"); + Check(state.Paragraphs[0].Occurrence.Text=="Preserved exact prose","Scene navigation preserves manuscript content"); + Check(presence.Navigate(7,12,instance,session,manuscript,3,100)&&presence.Navigate(7,12,instance,session,manuscript,3,110)&&presence.TakeNavigation(7,"installation",instance,session)?.Chapter?.Start==110,"Rapid explicit navigation coalesces to the latest positional command"); + + Check(await controller.NavigateWord(12,23,instance,null,access,paragraphs,presence) is BadRequestObjectResult,"Incomplete document identity cannot silently fall back to the active Word instance"); + controller.ModelState.AddModelError("instanceId","Invalid identifier");Check(await Navigate() is BadRequestObjectResult,"Malformed document identifiers cannot degrade to automatic routing");controller.ModelState.Clear(); + state.Paragraphs[0].PositionVerified=false;Check(await Navigate() is ConflictObjectResult,"Unresolved scene starts never create Word commands");state.Paragraphs[0].PositionVerified=true; + resolvedScene=22;Check(await Navigate() is ConflictObjectResult,"Authoritative position mismatch cannot navigate across scene or chapter boundaries");resolvedScene=23; + resolvedRevision=state.Revision+1;Check(await Navigate() is ConflictObjectResult,"A concurrent scene-boundary revision invalidates the earlier scene-start anchor");resolvedRevision=null; + invalidateSaved=true;Check(await Navigate() is ConflictObjectResult,"Word becoming unsaved during anchor lookup prevents queueing an old position");invalidateSaved=false;Check(presence.Navigate(7,12,instance,session,manuscript,3,100)&&presence.TakeNavigation(7,"installation",instance,session)?.Kind=="navigate","Existing exact-revision review navigation keeps its prior unsaved-snapshot semantics");Beat(); + Beat(4);Check(await Navigate() is ConflictObjectResult,"Changed Word revision refuses stale saved positions"); + presence.Remove(7,"installation",instance,session);sequence=0;Beat(); + Check(await Navigate(Guid.NewGuid()) is ConflictObjectResult,"Explicit document selection never routes to another connected Word instance"); + allowed=false;Check(await Navigate() is ForbidResult,"Book authorisation is required for browser-to-Word navigation");allowed=true; + var lease=presence.Read(7,12).Single();var capture=Guid.NewGuid();Check(presence.RequestCapture(7,lease,capture),"Fixture starts an existing capture command"); + Check(await Navigate() is ConflictObjectResult&&presence.TakeNavigation(7,"installation",instance,session)?.Id==capture,"Navigation cannot overwrite pending capture, synchronisation or maintenance work"); + presence.Remove(7,"installation",instance,session);Check(await Navigate() is ConflictObjectResult,"Disconnected Word is reported honestly; saved scene navigation remains independent"); + var denied=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(false)); + Check(await controller.ContextPlotLines(7,12,null!,denied) is NotFoundResult,"Plot Lines rejects unauthorised projects before loading saved data"); + Check(await controller.ContextMetrics(7,12,null!,denied,null!,null!) is NotFoundResult,"Recorded metrics rejects unauthorised projects before querying raw repositories"); + Check(await controller.ContextMap(7,12,23,null,null!,null!,denied,null!) is NotFoundResult,"Maps rejects unauthorised projects before reading shapes or story locations"); + var metrics=PlotLine.Services.WritingContextMetrics.Build(new TimelineData{Project=new(){ProjectID=1},Books=[new(){BookID=12}],Chapters=[new(){ChapterID=10,BookID=12}],Scenes=[new(){SceneID=22,ChapterID=10,SceneNumber=1},new(){SceneID=23,ChapterID=10,SceneNumber=2}],MetricTypes=[new(){MetricTypeID=1,MetricName="Emotional intensity",MinValue=0,MaxValue=10,DefaultValue=5},new(){MetricTypeID=2,MetricName="Emotional direction",MinValue=-5,MaxValue=5}],MetricPoints=[new(){SceneID=23,MetricTypeID=1,Value=5},new(){SceneID=22,MetricTypeID=1,Value=8},new(){SceneID=23,MetricTypeID=2,Value=0}]},[new(){SceneID=22,MetricTypeID=1,MetricName="Emotional intensity",MinValue=0,MaxValue=10,Value=8},new(){SceneID=23,MetricTypeID=2,MetricName="Emotional direction",MinValue=-5,MaxValue=5,Value=0}]); + Check(metrics.OrderedScenes.Select(s=>s.SceneID).SequenceEqual(new[]{22,23}),"Context metrics reuse canonical scene ordering across recorded and missing values"); + Check(metrics.MetricGraphs.Single(g=>g.MetricTypeID==1).Points.Count==1&&metrics.MetricGraphs.Single(g=>g.MetricTypeID==1).Points.Single().Value==8,"Missing metric values remain gaps instead of Timeline display defaults"); + Check(metrics.MetricGraphs.Single(g=>g.MetricTypeID==2).Points.Single().Value==0,"An actual recorded zero is preserved as evidence, not mistaken for missing data"); + + } + private static void Check(bool ok,string message){if(!ok)throw new Exception(message);Console.WriteLine("PASS "+message);} +} diff --git a/PlotLine/Controllers/NativeWorkspaceController.cs b/PlotLine/Controllers/NativeWorkspaceController.cs index 4eb6778f..7d250124 100644 --- a/PlotLine/Controllers/NativeWorkspaceController.cs +++ b/PlotLine/Controllers/NativeWorkspaceController.cs @@ -14,6 +14,7 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB public async Task Workspace(int bookId,Guid? instanceId,Guid? sessionId,string view="book") { var structure=await access.GetBookStructureAsync(bookId,Author);if(structure==null)return Forbid();var book=await books.GetAsync(bookId);if(book==null)return NotFound(); + if(view is "context" or "intent") return RedirectToAction(view=="context"?"Context":"Intent","Writing",new{projectId=book.ProjectID,bookId,instanceId,sessionId,embedded=true}); return View(new NativeWorkspaceModel(bookId,book.ProjectID,book.BookDisplayTitle,instanceId,sessionId,view is "context" or "intent"?view:"book",await reviews.List(Author,bookId),structure.Chapters)); } [HttpGet("presence")] diff --git a/PlotLine/Controllers/WritingController.cs b/PlotLine/Controllers/WritingController.cs index 99f97344..712ea88b 100644 --- a/PlotLine/Controllers/WritingController.cs +++ b/PlotLine/Controllers/WritingController.cs @@ -1,4 +1,7 @@ using Microsoft.AspNetCore.Authorization; +using System.Security.Claims; +using PlotLine.Data; +using PlotLine.Services.NativeCompanion; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using PlotLine.Models; @@ -9,17 +12,18 @@ namespace PlotLine.Controllers; [Authorize] [Route("Writing")] +[ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] public sealed class WritingController( IStoryContextService storyContext, IRelationshipMapService relationshipMap, IFloorPlanService floorPlans, IWriterWorkspaceService writerWorkspace, - ILogger logger,IStoryCalendarService? calendar=null) : Controller + ILogger logger,IStoryCalendarService? calendar=null,IWordCompanionRepository? companion=null) : Controller { [HttpGet("Context")] - public async Task Context(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false,bool embedded=false) + public async Task Context(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false,bool embedded=false,Guid? instanceId=null,Guid? sessionId=null) { - ViewData["NativeSnapshot"] = pinned;ViewData["WritingEmbedded"]=embedded; + ViewData["NativeSnapshot"] = pinned;ViewData["WritingEmbedded"]=embedded;ViewData["WordInstance"]=instanceId;ViewData["WordSession"]=sessionId; logger.LogInformation( "Opening Writing Context. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID} SceneID={SceneID} DocumentGuidPresent={DocumentGuidPresent}", projectId, @@ -28,6 +32,10 @@ public sealed class WritingController( sceneId, documentGuid.HasValue); + if(!sceneId.HasValue&&bookId.HasValue&&companion!=null) { + var structure=await companion.GetBookStructureAsync(bookId.Value,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)); + sceneId=structure?.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault()?.SceneId; + } var display = sceneId.HasValue ? await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual context") : WaitingContextDisplay(projectId, bookId, documentGuid); @@ -47,9 +55,9 @@ public sealed class WritingController( } [HttpGet("Intent")] - public async Task Intent(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false,bool embedded=false) + public async Task Intent(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false,bool embedded=false,Guid? instanceId=null,Guid? sessionId=null) { - ViewData["NativeSnapshot"] = pinned;ViewData["WritingEmbedded"]=embedded; + ViewData["NativeSnapshot"] = pinned;ViewData["WritingEmbedded"]=embedded;ViewData["WordInstance"]=instanceId;ViewData["WordSession"]=sessionId; logger.LogInformation( "Opening Writing Intent. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID} SceneID={SceneID} DocumentGuidPresent={DocumentGuidPresent}", projectId, @@ -58,6 +66,11 @@ public sealed class WritingController( sceneId, documentGuid.HasValue); + if(!sceneId.HasValue&&!chapterId.HasValue&&bookId.HasValue&&companion!=null) { + var structure=await companion.GetBookStructureAsync(bookId.Value,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)); + var first=structure?.Chapters.FirstOrDefault(c=>c.Scenes.Count>0)??structure?.Chapters.FirstOrDefault(); + chapterId=first?.ChapterId;sceneId=first?.Scenes.FirstOrDefault()?.SceneId; + } var display = sceneId.HasValue || chapterId.HasValue ? await BuildIntentDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual intent") : WaitingIntentDisplay(projectId, bookId, documentGuid); @@ -85,7 +98,7 @@ public sealed class WritingController( return PartialView("~/Views/Writing/_WritingContextContent.cshtml", WaitingContextDisplay(projectId, bookId, null)); } - var model = await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Following Word"); + var model = await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Saved scene"); if (model?.HasScene == true) { return PartialView("~/Views/Writing/_WritingContextContent.cshtml", model); @@ -104,7 +117,7 @@ public sealed class WritingController( return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", WaitingIntentDisplay(projectId, bookId, null)); } - var model = await BuildIntentDisplayAsync(projectId, bookId, chapterId, sceneId, "Following Word"); + var model = await BuildIntentDisplayAsync(projectId, bookId, chapterId, sceneId, "Saved scene"); if (model is not null && (model.HasScene || model.HasChapter)) { return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", model); @@ -143,7 +156,7 @@ public sealed class WritingController( RelationshipMap = relationships, FloorPlan = floorPlan, FollowStatus = followStatus, - SceneOptions = BuildSceneOptions(context.Scene) + SceneOptions = await ContextSceneOptions(context.Scene) }; } @@ -188,11 +201,75 @@ public sealed class WritingController( ChapterWorkflow = chapterWorkflow, FollowStatus = followStatus, SceneOptions = context?.Scene is not null - ? BuildSceneOptions(context.Scene) + ? await ContextSceneOptions(context.Scene) : BuildSceneOptions(chapterWorkflow) }; } + [HttpGet("Context/Map")] + public async Task ContextMap(int projectId,int bookId,int sceneId,int? mapId,[FromServices] MapRepository maps,[FromServices] IMapStoryService storyMaps,[FromServices] IProjectAccessService permissions,[FromServices] IBookRepository books) + { + if(!await permissions.CanAccessProjectAsync(projectId)||(await books.GetAsync(bookId))?.ProjectID!=projectId||companion==null)return NotFound(); + var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); + var structure=await companion.GetBookStructureAsync(bookId,user); + if(structure==null||!structure.Chapters.Any(c=>c.Scenes.Any(s=>s.SceneId==sceneId)))return NotFound(); + var choices=await maps.ListAsync(projectId,user); + var selected=mapId.HasValue?choices.FirstOrDefault(m=>m.MapID==mapId):choices.FirstOrDefault(); + if(mapId.HasValue&&selected==null)return NotFound(); + MapStoryProjection? projection=selected==null?null:await storyMaps.GetAsync(projectId,selected.MapID,user); + var position=projection?.Scenes.FirstOrDefault(s=>s.SceneID==sceneId)?.Position; + if(!mapId.HasValue&&position?.FeatureID==null&&position?.DetailMapID is int mapped&&choices.FirstOrDefault(m=>m.MapID==mapped) is {} linked) { + selected=linked;projection=await storyMaps.GetAsync(projectId,linked.MapID,user);position=projection?.Scenes.FirstOrDefault(s=>s.SceneID==sceneId)?.Position; + } + return PartialView("_WritingContextMap",new WritingContextMapViewModel{ProjectID=projectId,BookID=bookId,SceneID=sceneId,Maps=choices,Document=selected==null?null:await maps.GetAsync(projectId,selected.MapID,user),Story=projection,Position=position}); + } + + [HttpGet("Context/PlotLines")] + public async Task ContextPlotLines(int projectId,int bookId,[FromServices] IPlotLineWorkspaceService plots,[FromServices] IProjectAccessService permissions) + { + if(!await permissions.CanAccessProjectAsync(projectId))return NotFound(); + var initial=await plots.GetAsync(projectId,bookId,null,null,null,false,false);if(initial==null)return NotFound(); + var model=initial.PlotLines.Count>1?await plots.GetAsync(projectId,bookId,initial.PlotLines.Select(l=>l.Line.PlotLineID),null,null,false,false):initial; + return PartialView("_WritingContextPlotLines",model); + } + [HttpGet("Context/Metrics")] + public async Task ContextMetrics(int projectId,int bookId,[FromServices] ITimelineRepository timeline,[FromServices] IProjectAccessService permissions,[FromServices] IBookRepository books,[FromServices] ISceneRepository sceneMetrics) + { + if(!await permissions.CanAccessProjectAsync(projectId)||(await books.GetAsync(bookId))?.ProjectID!=projectId)return NotFound(); + var data=await timeline.GetByProjectAsync(projectId,bookId,false,[],false); + var recorded=await sceneMetrics.ListRecordedMetricsByBookAsync(bookId,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)); + return data.Project==null?NotFound():PartialView("_WritingContextMetrics",WritingContextMetrics.Build(data,recorded)); + } + + private async Task> ContextSceneOptions(SceneEditViewModel scene) + { + if(companion==null)return BuildSceneOptions(scene); + var structure=await companion.GetBookStructureAsync(scene.Book!.BookID,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)); + return structure?.Chapters.SelectMany(c=>c.Scenes.Select(s=>new SelectListItem($"{c.Title} · {s.Title}",s.SceneId.ToString(),s.SceneId==scene.SceneID))).ToList()??[]; + } + + [HttpPost("Context/Navigate"),ValidateAntiForgeryToken] + public async Task NavigateWord(int bookId,int sceneId,Guid? instanceId,Guid? sessionId, + [FromServices] IWordCompanionRepository access,[FromServices] IParagraphManuscriptRepository paragraphs,[FromServices] NativePresenceStore presence) + { + if(!ModelState.IsValid||bookId<=0||sceneId<=0||instanceId.HasValue!=sessionId.HasValue)return BadRequest(new{message="Choose a valid scene and a complete Word document session. No navigation was sent."}); + var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); + var structure=await access.GetBookStructureAsync(bookId,user);if(structure==null)return Forbid(); + var chapter=structure.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==sceneId));if(chapter==null)return NotFound(); + var leases=presence.Read(user,bookId).Where(l=>l.Position.WordAvailable).ToArray(); + var candidates=instanceId.HasValue&&sessionId.HasValue?leases.Where(l=>l.Instance==instanceId&&l.Session==sessionId).ToArray():leases.Where(l=>l.Position.Active).ToArray(); + var lease=candidates.Length==1?candidates[0]:!instanceId.HasValue&&leases.Length==1?leases[0]:null; + if(lease==null)return Conflict(new{message="No single connected Word document is selected. Scene navigation remains available here."}); + var state=await paragraphs.Get(user,bookId); + if(state==null||lease.Position.WordSaved!=true||state.SessionId!=lease.Session||state.WordRevision!=lease.Position.Revision||state.ManuscriptId!=lease.Position.ManuscriptId)return Conflict(new{message="Word has no current saved paragraph mapping. Synchronise from Word before requesting navigation."}); + var target=state.Scenes.FirstOrDefault(s=>!s.Retired&&s.CanonicalId==sceneId&&s.ChapterId==chapter.ChapterId); + var first=target==null?null:state.Paragraphs.Where(p=>p.Story&&p.SceneId==target.Id).OrderBy(p=>p.Occurrence.Ordinal).FirstOrDefault(); + if(first?.PositionVerified!=true)return Conflict(new{message="The scene start is unresolved. Saved scene information remains available."}); + var verified=await paragraphs.Position(user,bookId,state.ManuscriptId,state.SessionId,state.WordRevision,first.Occurrence.Start); + if(HttpContext.RequestAborted.IsCancellationRequested||verified?.HasSnapshot!=true||verified.Revision!=state.Revision||verified.SceneID!=sceneId||verified.ChapterID!=chapter.ChapterId||!presence.Navigate(user,bookId,lease.Instance,lease.Session,state.ManuscriptId,state.WordRevision,first.Occurrence.Start,requireSaved:true))return Conflict(new{message="The Word mapping changed or Word is busy. No navigation was sent."}); + return Ok(new{message="Navigation requested in Word."}); + } + private static IReadOnlyList BuildSceneOptions(SceneEditViewModel scene) { var options = scene.SceneOptions diff --git a/PlotLine/Services/NativeCompanion/NativePresenceStore.cs b/PlotLine/Services/NativeCompanion/NativePresenceStore.cs index a4ecb672..2b127aed 100644 --- a/PlotLine/Services/NativeCompanion/NativePresenceStore.cs +++ b/PlotLine/Services/NativeCompanion/NativePresenceStore.cs @@ -21,8 +21,8 @@ public sealed class NativePresenceStore(TimeProvider clock) leases[key]=new(user,grant,expires,instance,session,new NativePresence{ParagraphRevision=value.ParagraphRevision,CanCapture=value.CanCapture,CanParagraphSync=value.CanParagraphSync,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordRunning=value.WordRunning,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;} } public NativeLease[] Read(int user,int book){lock(gate){Prune();return leases.Values.Where(p=>p.User==user&&(book==0||p.Position.BookId==book)).OrderByDescending(p=>p.Updated).ToArray();}} - public bool Navigate(int user,int book,Guid instance,Guid session,Guid manuscript,long revision,int start) - {lock(gate){Prune();var key=(user,instance,session);if(!leases.TryGetValue(key,out var lease)||!lease.Position.WordAvailable||lease.Position.BookId!=book||lease.Position.ManuscriptId!=manuscript||lease.Position.Revision!=revision||start<0)return false;navigation[key]=new(){Kind="navigate",SessionId=session,Revision=revision,Chapter=new(){Start=start}};return true;}} + public bool Navigate(int user,int book,Guid instance,Guid session,Guid manuscript,long revision,int start,bool requireSaved=false) + {lock(gate){Prune();var key=(user,instance,session);if(!leases.TryGetValue(key,out var lease)||!lease.Position.WordAvailable||lease.Position.BookId!=book||lease.Position.ManuscriptId!=manuscript||lease.Position.Revision!=revision||(requireSaved&&lease.Position.WordSaved!=true)||start<0||(navigation.TryGetValue(key,out var queued)&&queued.Kind!="navigate"))return false;navigation[key]=new(){Kind="navigate",SessionId=session,Revision=revision,Chapter=new(){Start=start}};return true;}} public void RequestCancellation(int user,NativeLease selected){lock(gate){var key=(user,selected.Instance,selected.Session);if(leases.TryGetValue(key,out var current)&¤t.Grant==selected.Grant&¤t.Position.Revision==selected.Position.Revision)navigation[key]=new(){Kind="cancel",SessionId=selected.Session,Revision=selected.Position.Revision};}} public bool RequestCapture(int user,NativeLease selected,Guid request,int book=0,bool paragraphs=false,bool synchronise=false,long baseRevision=0,string baseHash="") {lock(gate){Prune();var key=(user,selected.Instance,selected.Session);if(!leases.TryGetValue(key,out var lease)||lease.Grant!=selected.Grant||lease.Position.Revision!=selected.Position.Revision||lease.Position.ManuscriptId!=selected.Position.ManuscriptId||(book>0&&lease.Position.BookId!=0&&lease.Position.BookId!=book)||!lease.Position.CanCapture||navigation.ContainsKey(key))return false;navigation[key]=new(){Id=request,BaseRevision=baseRevision,BaseSnapshotHash=baseHash,BookId=book,ParagraphTracking=paragraphs,Kind=synchronise?"paragraph-snapshot":"wizard-capture",SessionId=lease.Session,Revision=lease.Position.Revision};return true;}} diff --git a/PlotLine/Services/WritingContextMetrics.cs b/PlotLine/Services/WritingContextMetrics.cs new file mode 100644 index 00000000..9136278c --- /dev/null +++ b/PlotLine/Services/WritingContextMetrics.cs @@ -0,0 +1,17 @@ +using PlotLine.Data; +using Microsoft.AspNetCore.Mvc.Rendering; +using PlotLine.Models; +using PlotLine.ViewModels; +namespace PlotLine.Services; +// Timeline's metric rows include SQL-filled defaults. Only recorded SceneMetricValues are evidence. +public static class WritingContextMetrics +{ + public static TimelineViewModel Build(TimelineData data,IReadOnlyList recorded) + { + var scenes=StoryStateService.OrderScenes(data).ToArray();var byId=scenes.ToDictionary(s=>s.SceneID); + return new(){Project=data.Project!,OrderedScenes=scenes,ChapterOptions=data.Chapters.Select(c=>new SelectListItem($"{c.ChapterNumber:0.##} · {c.ChapterTitle}",c.ChapterID.ToString())).ToArray(),MetricGraphs=recorded.OrderBy(p=>p.SortOrder).ThenBy(p=>p.MetricName).Where(p=>byId.ContainsKey(p.SceneID)).GroupBy(p=>p.MetricTypeID).Select(group=>{ + var metric=group.First();return new MetricGraphViewModel{MetricTypeID=group.Key,MetricName=metric.MetricName,MinValue=metric.MinValue,MaxValue=metric.MaxValue, + Points=group.Select(p=>new MetricGraphPointViewModel{SceneID=p.SceneID,SceneNumber=byId[p.SceneID].SceneNumber,SceneTitle=byId[p.SceneID].SceneTitle,Value=p.Value}).ToArray()}; + }).ToArray()}; + } +} diff --git a/PlotLine/ViewModels/WritingContextMapViewModel.cs b/PlotLine/ViewModels/WritingContextMapViewModel.cs new file mode 100644 index 00000000..d92b4cb5 --- /dev/null +++ b/PlotLine/ViewModels/WritingContextMapViewModel.cs @@ -0,0 +1,12 @@ +using PlotLine.Models; +namespace PlotLine.ViewModels; +public sealed class WritingContextMapViewModel +{ + public int ProjectID {get;init;} + public int BookID {get;init;} + public int SceneID {get;init;} + public IReadOnlyList Maps {get;init;}=[]; + public MapDocument? Document {get;init;} + public MapStoryProjection? Story {get;init;} + public MapStoryLocation? Position {get;init;} +} diff --git a/PlotLine/Views/NativeWorkspace/Workspace.cshtml b/PlotLine/Views/NativeWorkspace/Workspace.cshtml index 1ee352e9..c9aa4173 100644 --- a/PlotLine/Views/NativeWorkspace/Workspace.cshtml +++ b/PlotLine/Views/NativeWorkspace/Workspace.cshtml @@ -6,13 +6,9 @@

Saved workspace · waiting for a current Word scene

Checking Companion presence…

-
-

Manual navigation pauses following. No Word commands or manuscript text are sent by this page. Context and Intent remain available without Word.

+

Connection diagnostics only. Open Context or Intent to follow the manuscript and navigate saved scenes.

- @if(Model.Mode is "context" or "intent"){ - } - @if(Model.Mode=="book"){

AI chapter suggestions

Generated by PlotDirector’s existing chapter-analysis service. Review titles and summaries before any import. Successful chapters remain available for 30 days.

@if(Model.Reviews.Count==0){
No saved AI suggestions yet. Use Import manuscript in PlotDirector to read and review your manuscript.
} diff --git a/PlotLine/Views/Shared/_ApplicationShell.cshtml b/PlotLine/Views/Shared/_ApplicationShell.cshtml index 256edcde..5b8f302c 100644 --- a/PlotLine/Views/Shared/_ApplicationShell.cshtml +++ b/PlotLine/Views/Shared/_ApplicationShell.cshtml @@ -74,7 +74,7 @@
@if (Model.ShowCompanionPresence) { - Offline + } @RenderBody()@await RenderSectionAsync("Scripts",required:false) diff --git a/PlotLine/Views/Shared/_WritingConnectionDetails.cshtml b/PlotLine/Views/Shared/_WritingConnectionDetails.cshtml new file mode 100644 index 00000000..9b0895e4 --- /dev/null +++ b/PlotLine/Views/Shared/_WritingConnectionDetails.cshtml @@ -0,0 +1,13 @@ + +

Word connection

+

Checking the Companion’s authenticated document heartbeat…

+
+ + + +
+

Only current, authorised document sessions are listed. Saved story information remains available when Word is disconnected.

+

+ + Workspace and display settings +
diff --git a/PlotLine/Views/Writing/Context.cshtml b/PlotLine/Views/Writing/Context.cshtml index 904fdf60..15191091 100644 --- a/PlotLine/Views/Writing/Context.cshtml +++ b/PlotLine/Views/Writing/Context.cshtml @@ -7,25 +7,22 @@
+
-
-

Writing Context

-

Writing Context

-
+

Writing Context

+

Writing Context

- @if (ViewData["NativeSnapshot"] is not true) { } @(Model.Display?.FollowStatus ?? "Connected, waiting for scene")
-
- @if (ViewData["NativeSnapshot"] is not true) { } - @(ViewData["NativeSnapshot"] is true ? "Saved PlotDirector snapshot · manual navigation · no automatic save" : "Writing Workspace") -
+
@@ -36,6 +33,9 @@ @section Scripts { + + + + } +
diff --git a/PlotLine/Views/Writing/_WritingContextMetrics.cshtml b/PlotLine/Views/Writing/_WritingContextMetrics.cshtml new file mode 100644 index 00000000..3f3df6c3 --- /dev/null +++ b/PlotLine/Views/Writing/_WritingContextMetrics.cshtml @@ -0,0 +1,22 @@ +@model TimelineViewModel +@using System.Globalization +@{ + var scenes=Model.OrderedScenes.ToArray(); + string N(double value)=>value.ToString("0.###",CultureInfo.InvariantCulture); +} +
+ +

Recorded scene metrics · Missing values are gaps, not zero. These are saved values, not a new AI assessment.

+ @if(Model.MetricGraphs.All(m=>m.Points.Count==0)||scenes.Length==0){

No recorded metrics are available. Enable metrics and record values in the existing scene or Timeline tools.

} + else{ +
+
+
+ +
Manuscript@for(var i=0;i@(scenes[i].SceneNumber.ToString("0.##"))}
+ @foreach(var metric in Model.MetricGraphs){var points=metric.Points.ToDictionary(p=>p.SceneID);

@metric.MetricName · scale @metric.MinValue–@metric.MaxValue

@for(var i=0;i0&&points.TryGetValue(scenes[i-1].SceneID,out var previous)){var oldY=165d-150d*(previous.Value-metric.MinValue)/Math.Max(1,metric.MaxValue-metric.MinValue);}@scenes[i].SceneTitle: @point.Value}}
} +
+ + @for(var i=0;i
diff --git a/PlotLine/Views/Writing/_WritingContextPlace.cshtml b/PlotLine/Views/Writing/_WritingContextPlace.cshtml index 5c063fa9..9475a402 100644 --- a/PlotLine/Views/Writing/_WritingContextPlace.cshtml +++ b/PlotLine/Views/Writing/_WritingContextPlace.cshtml @@ -34,6 +34,9 @@ } else { + +

Saved layout · the scene location is outlined where a room mapping exists. Drag the scrollbars to explore.

+
@@ -42,7 +45,7 @@ var locationTokens = block.LocationID.HasValue && tokensByLocation.TryGetValue(block.LocationID.Value, out var blockTokens) ? blockTokens : []; -
@block.DisplayLabel @if (locationTokens.Any()) @@ -52,6 +55,7 @@
}
+
} diff --git a/PlotLine/Views/Writing/_WritingContextPlotLines.cshtml b/PlotLine/Views/Writing/_WritingContextPlotLines.cshtml new file mode 100644 index 00000000..c8c805ab --- /dev/null +++ b/PlotLine/Views/Writing/_WritingContextPlotLines.cshtml @@ -0,0 +1,24 @@ +@model PlotLineWorkspaceViewModel +@{ + var scenes=Model.AssociationScenes.OrderBy(s=>s.NarrativeOrder).ToArray(); + var byScene=Model.Scenes.ToDictionary(s=>s.SceneID); +} +
+ +

Saved Plot Lines · Focus or Weave using the line filters. Scrubbing explores the story; only “Go to scene” requests Word navigation.

+ @if(scenes.Length==0||Model.PlotLines.Count==0){

No saved plot-line developments are available for this book.

} + else{ +
+
Plot Lines@foreach(var line in Model.PlotLines){}
+
+
+ +
Manuscript@for(var i=0;i@(scene.ChapterNumber.ToString("0.##")) / @(scene.SceneNumber.ToString("0.##"))}
+ @foreach(var line in Model.PlotLines){
@line.Line.PlotLineName@for(var i=0;im.PlotLineID==line.Line.PlotLineID);}
} +
+ +
+ @for(var i=0;i
+ } +
diff --git a/PlotLine/Views/Writing/_WritingIntentContent.cshtml b/PlotLine/Views/Writing/_WritingIntentContent.cshtml index 48d4f9f4..02bcc80e 100644 --- a/PlotLine/Views/Writing/_WritingIntentContent.cshtml +++ b/PlotLine/Views/Writing/_WritingIntentContent.cshtml @@ -38,12 +38,12 @@ @if (chapter is not null) { - Chapter @chapter.ChapterNumber:g + Chapter @(chapter.ChapterNumber.ToString("0.##")) } @if (scene is not null) { - Scene @scene.SceneNumber:g + Scene @(scene.SceneNumber.ToString("0.##")) }

@if (Model.IsChapterOnly) @@ -60,7 +60,7 @@ { } diff --git a/PlotLine/Views/Writing/_WritingIntentPlan.cshtml b/PlotLine/Views/Writing/_WritingIntentPlan.cshtml index daf83563..3a5792c6 100644 --- a/PlotLine/Views/Writing/_WritingIntentPlan.cshtml +++ b/PlotLine/Views/Writing/_WritingIntentPlan.cshtml @@ -10,7 +10,7 @@

Chapter Plan

-

Chapter @chapter?.ChapterNumber:g: @chapter?.ChapterTitle

+

Chapter @(chapter?.ChapterNumber.ToString("0.##")): @chapter?.ChapterTitle

@TextOr(chapter?.Summary, "No chapter summary has been written yet.")

Purpose
@TextOr(chapter?.ChapterPurposeName, "No chapter purpose selected.")
@@ -26,7 +26,7 @@ } else { -

Scene @scene.SceneNumber:g: @scene.SceneTitle

+

Scene @(scene.SceneNumber.ToString("0.##")): @scene.SceneTitle

@TextOr(scene.Summary, "No scene summary has been written yet.")

}
diff --git a/PlotLine/wwwroot/css/site.css b/PlotLine/wwwroot/css/site.css index a58ab8b5..7d241b06 100644 --- a/PlotLine/wwwroot/css/site.css +++ b/PlotLine/wwwroot/css/site.css @@ -7705,3 +7705,34 @@ html[data-standalone="true"] .plotline-shell.location-workspace-shell { .writing-embedded:has(>#native-workspace){padding:0;} .writing-embedded>.native-writing-workspace{display:flex;flex-direction:column;min-height:100dvh;height:100dvh;gap:.4rem;overflow:auto;} .writing-embedded .native-writing-workspace #native-story-workspace{flex:1 0 18rem;height:auto!important;min-height:18rem;} + +/* A scene workspace keeps its shell; only story fragments change. */ +.writing-window-bar{display:flex;justify-content:space-between;align-items:center;gap:1rem;padding:.4rem .6rem;border-bottom:1px solid var(--plotline-line);background:var(--plotline-panel)} +.writing-window-bar>a{font-weight:650;color:var(--plotline-ink);text-decoration:none} +button.pd-presence{font:inherit;cursor:pointer;background:transparent;border:0;color:var(--plotline-ink)} +.writing-connection-dialog{width:min(36rem,calc(100vw - 2rem));max-height:85dvh;overflow:auto;border:1px solid var(--plotline-line);border-radius:1rem;padding:1.3rem;background:var(--plotline-panel);color:var(--plotline-ink);box-shadow:0 1rem 4rem #0005} +.writing-connection-dialog::backdrop{background:#0006} +.writing-embedded .writing-context-page{min-height:calc(100dvh - 3rem);padding:.7rem;} +.writing-context-shell-header{align-items:center;margin-bottom:.6rem;gap:.5rem} +.writing-context-scene-header{gap:.75rem;margin-bottom:.6rem;align-items:center} +.writing-context-scene-header h2{font-size:clamp(1.1rem,2vw,1.6rem);overflow-wrap:anywhere} +.writing-context-scene-header p{margin-bottom:.3rem} +.writing-scene-step{display:flex;gap:.4rem;grid-column:1/-1;justify-content:flex-end} +.writing-context-tabs{flex-wrap:wrap;gap:.3rem} +.writing-context-scene-actions{min-width:0;max-width:28rem} +.writing-context-scene-actions select{min-width:0;max-width:100%} +@media(max-width:700px){.writing-context-scene-actions{width:100%;max-width:none}.writing-scene-step{justify-content:flex-start}.writing-context-tabs button{padding:.4rem .65rem}.writing-context-page .writing-context-scene-header{display:block}} +.writing-chart-controls,.writing-plot-filters{display:flex;flex-wrap:wrap;gap:.6rem;align-items:center;margin:.5rem 0}.writing-plot-filters label{display:flex;align-items:center;gap:.35rem;font-size:.85rem}.writing-chart-controls label{display:flex;align-items:center;gap:.5rem} +.writing-story-scroll{overflow:auto;max-width:100%;border:1px solid var(--plotline-line);border-radius:.7rem;position:relative;isolation:isolate} +.writing-story-chart{--scene-width:64px;position:relative;width:calc(160px + var(--scene-count)*var(--scene-width));min-height:8rem;padding:.5rem 0;background:var(--plotline-panel)} +.writing-plot-row{display:grid;grid-template-columns:160px repeat(var(--scene-count),var(--scene-width));min-height:3rem;align-items:stretch;border-bottom:1px solid var(--plotline-line)} +.writing-plot-row[hidden]{display:none}.writing-plot-row>strong{position:sticky;left:0;z-index:2;background:var(--plotline-panel);padding:.6rem;overflow-wrap:anywhere;font-size:.9rem;border-left:4px solid var(--line-colour,var(--plotline-line))} +.writing-plot-row>button{border:0;border-right:1px solid var(--plotline-line);background:transparent;color:var(--plotline-muted);font-size:.8rem;padding:.25rem;min-width:0}.writing-plot-row>.has-development{color:var(--line-colour,var(--plotline-accent));font-size:1.5rem}.writing-plot-row>button[aria-current=location]{background:var(--plotline-accent);color:white} +.writing-current-marker{position:absolute;top:0;bottom:0;width:2px;background:var(--plotline-accent);pointer-events:none;z-index:1}.writing-scrubber{display:flex;align-items:center;gap:.7rem;margin:1rem 0}.writing-scrubber input{flex:1;min-width:4rem}.writing-chart-evidence{padding:.7rem;background:var(--plotline-panel);border-radius:.7rem}.writing-metric-chart{--scene-width:48px}.writing-metric-chart svg{display:block;overflow:visible}.writing-metric-chart>div[data-context-metric]>p{padding-left:.5rem;position:sticky;left:0;max-width:30rem} +.writing-floor-scroll{overflow:auto;max-width:100%;max-height:65dvh;outline-offset:3px}.writing-floor-scroll .writing-context-floor{width:calc(var(--floor-cols)*2.8rem*var(--floor-zoom,1));min-height:calc(var(--floor-rows)*2.8rem*var(--floor-zoom,1));max-width:none}.writing-context-floor-block.is-current-room{outline:3px solid var(--plotline-accent);outline-offset:-3px;background:color-mix(in srgb,var(--plotline-accent) 15%,var(--plotline-panel))}.writing-floor-zoom{display:flex;gap:.5rem;align-items:center;margin:.4rem 0} +.writing-context-map{width:100%;height:clamp(18rem,55dvh,50rem);border:1px solid var(--plotline-line);border-radius:.7rem;background:var(--plotline-panel);touch-action:none;cursor:grab}.writing-context-map g.is-scene-place>circle,.writing-context-map g.is-scene-place>path{stroke:var(--plotline-accent);stroke-width:5}.writing-context-map g.is-explored>circle,.writing-context-map g.is-explored>path{stroke:var(--plotline-ink);stroke-width:5}.writing-context-map text{pointer-events:none}.writing-context-map g:focus-visible{outline:none;filter:drop-shadow(0 0 6px var(--plotline-accent))} +.writing-chart-controls>label,.writing-plot-filters label{max-width:100%;min-width:0;flex-wrap:wrap;overflow-wrap:anywhere}.writing-chart-controls select{min-width:0;max-width:100%} +.writing-context-scene-actions>label{grid-column:1;grid-row:1;margin:0;align-self:center}.writing-context-scene-actions>.writing-scene-step{grid-column:2;grid-row:1;white-space:nowrap}.writing-context-scene-actions>select{grid-column:1;grid-row:2}.writing-context-scene-actions>a{grid-column:2;grid-row:2;white-space:nowrap} +.writing-context-scene-actions{grid-template-columns:minmax(0,1fr) auto;width:min(27rem,100%)}.writing-context-page input[type=range],.writing-context-page input[type=checkbox]{accent-color:var(--plotline-accent)} +html[data-standalone="true"] .writing-context-tabs{top:var(--pd-sticky-height,0px)} +[data-word-book-links][hidden],[data-word-document-picker][hidden]{display:none!important} diff --git a/PlotLine/wwwroot/js/application-theme-sync.js b/PlotLine/wwwroot/js/application-theme-sync.js index a978f5ad..6643dc8b 100644 --- a/PlotLine/wwwroot/js/application-theme-sync.js +++ b/PlotLine/wwwroot/js/application-theme-sync.js @@ -1,6 +1,6 @@ // Share the existing non-sensitive device theme across application and workspace windows. (() => { - const choices=[...document.querySelectorAll('[data-app-theme-choice]')],valid=new Set(choices.map(node=>node.dataset.appThemeChoice)); + const choices=[...document.querySelectorAll('[data-app-theme-choice]')],valid=new Set([...choices.map(node=>node.dataset.appThemeChoice),...(window.PlotDirectorApplicationThemes||[])]); window.addEventListener('storage',event=>{ if(event.key!=='plotdirector.applicationTheme'||!valid.has(event.newValue))return; if(window.PlotDirectorApplyApplicationTheme){window.PlotDirectorApplyApplicationTheme(event.newValue);return;} diff --git a/PlotLine/wwwroot/js/native-companion-status.js b/PlotLine/wwwroot/js/native-companion-status.js index 45a2d80d..3282eb08 100644 --- a/PlotLine/wwwroot/js/native-companion-status.js +++ b/PlotLine/wwwroot/js/native-companion-status.js @@ -1,17 +1,40 @@ (() => { 'use strict';const root=document.querySelector('#native-companion-status');if(!root)return; const text=root.querySelector('#native-companion-status-text');let pending=false,seen=false; + const details=document.querySelector('#writing-connection-details'), documents=details?.querySelector('#writing-word-document'); + root.addEventListener('click',()=>details?.showModal()); + details?.querySelector('[data-close-word-details]')?.addEventListener('click',()=>details.close()); + details?.querySelector('[data-word-return-to-current]')?.addEventListener('click',()=>{window.dispatchEvent(new Event('plotdirector:word-return-to-current'));details.close();}); + documents?.addEventListener('change',()=>{documents.dataset.userSelected='true';window.dispatchEvent(new CustomEvent('plotdirector:word-document-selected',{detail:documents.value}));const button=details.querySelector('[data-word-return-to-current]');if(button)button.disabled=true;void update();}); + function renderDetails(leases) { + if(!details)return; + const workspace=document.querySelector('[data-writing-context],[data-writing-intent]'),scopeBook=Number(workspace?.dataset.scopeBookId); + const selectable=leases.filter(l=>l.wordAvailable&&(!scopeBook||Number(l.bookId)===scopeBook)); + details.querySelector('[data-word-connection-description]').textContent=workspace&&scopeBook&&!selectable.length?'No live Word document is linked to this book. Saved scenes remain available; use Companion to change a manuscript’s book association.':root.title; + const previousLabel=documents.selectedOptions[0]?.textContent||'Selected manuscript'; + const selected=documents.dataset.userSelected==='true'?documents.value:documents.value || (document.querySelector('[data-word-instance]')?.dataset.wordInstance && document.querySelector('[data-word-session]')?.dataset.wordSession ? document.querySelector('[data-word-instance]').dataset.wordInstance+'/'+document.querySelector('[data-word-session]').dataset.wordSession : ''); + const signature=selectable.map(l=>l.instanceId+'/'+l.sessionId+':'+l.documentTitle).join('|'); + if(documents.dataset.signature!==signature){documents.dataset.signature=signature;documents.replaceChildren(new Option('Follow the active Word manuscript',''));for(const lease of selectable)documents.add(new Option(lease.documentTitle+(lease.active?' · active in Word':''),lease.instanceId+'/'+lease.sessionId));if(selected&&![...documents.options].some(o=>o.value===selected)){const stale=new Option(previousLabel.replace(/ · disconnected$/,'')+' · disconnected',selected);stale.disabled=true;documents.add(stale);}documents.value=selected;} + details.querySelector('[data-word-document-picker]')?.toggleAttribute('hidden',!workspace); + const activeInScope=selectable.filter(l=>l.active),selection=documents.value?selectable.find(l=>l.instanceId+'/'+l.sessionId===documents.value):activeInScope.length===1?activeInScope[0]:selectable.length===1?selectable[0]:null; + const returnButton=details.querySelector('[data-word-return-to-current]');if(returnButton)returnButton.disabled=!selection?.sceneId||selection.wordSaved===false; + const active=leases.filter(l=>l.active&&l.wordAvailable),available=leases.filter(l=>l.wordAvailable); + const current=leases.find(l=>l.instanceId+'/'+l.sessionId===documents.value)||(active.length===1?active[0]:available.length===1?available[0]:null); + const book=Number(workspace?.dataset.scopeBookId||current?.bookId),links=details.querySelector('[data-word-book-links]'); + if(links){links.hidden=!Number.isSafeInteger(book)||book<=0;if(!links.hidden){links.querySelector('[data-word-book-link]').href='/Books/Details/'+book;links.querySelector('[data-word-structure-link]').href='/manuscript/paragraphs?bookId='+book;}} + details.querySelector('[data-word-connection-diagnostics]').textContent=leases.length?'Current authenticated sessions: '+leases.length+'. Heartbeats expire after 45 seconds. Last checked '+new Date().toLocaleTimeString()+'. No manuscript text is transferred by these checks.':'No current Word session. Open Companion, check sign-in and book association, then reopen the manuscript.'; + } function offline(message){root.dataset.nativeAuthority=root.dataset.officeConnected==='true'?'false':'true';root.dataset.connected='false';root.classList.remove('is-connected');root.classList.add('is-offline');text.textContent=message;root.title=message+' · saved PlotDirector information remains available.';} - async function update(){if(pending||document.hidden)return;pending=true;try{ + async function update(reconnected=false){if(pending||document.hidden)return;pending=true;try{ const response=await fetch('/native-companion/status',{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw new Error();const leases=(await response.json()).filter(l=>Date.parse(l.expires)>Date.now());const active=leases.filter(l=>l.active&&l.wordAvailable),words=leases.filter(l=>l.wordAvailable);const lease=active.length===1?active[0]:words.length===1?words[0]:words.length===0?leases[0]:null;if(words.length>1&&active.length!==1){seen=true;offline('Choose an active Word document');} if(lease){leases.connectionState="Connected";leases.known=true;seen=true;root.dataset.nativeAuthority='true';root.dataset.connectionState='Connected';root.dataset.connected='true';root.classList.add('is-connected');root.classList.remove('is-offline');text.textContent=lease.wordAvailable?'Word connected':'Companion connected';root.title=lease.wordAvailable?lease.documentTitle+' · verified document heartbeat · last update '+new Date(lease.updated).toLocaleTimeString():'Companion connected; open a linked manuscript in Word.';} else { const stateResponse=await fetch('/native-companion/connection-state',{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}}); const device=stateResponse.ok?await stateResponse.json():null;leases.connectionState=device?.state||"Disconnected";leases.known=!!device?.known; if(device?.known){seen=true;const label=device.state==='Connected'?'Companion connected · Word not connected':device.state;offline(label);root.dataset.connectionState=device.state;if(device.state==='Connected'){root.dataset.nativeAuthority='true';root.dataset.connected='true';root.classList.add('is-connected');root.classList.remove('is-offline');root.title='Approved Companion is connected. No live Word document is registered.';}} - else if(seen)offline('Word disconnected or stale'); - }window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases})); - }catch{if(seen){offline('Companion status unavailable');}window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[]}));}finally{pending=false;}} + else if(seen)offline('Word disconnected or stale');else if(text.textContent==='Checking Word…')offline('Word disconnected'); + }leases.reconnected=reconnected;renderDetails(leases);window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases})); + }catch{if(seen){offline('Companion status unavailable');}leases.reconnected=reconnected;renderDetails(leases);window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[]}));}finally{pending=false;}} void update();const timer=setInterval(()=>void update(),15000);document.addEventListener('visibilitychange',()=>{if(!document.hidden)void update();});window.addEventListener('pagehide',()=>clearInterval(timer)); - if(window.signalR){let refresh;const connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();connection.on('NativePresenceChanged',()=>{clearTimeout(refresh);refresh=setTimeout(()=>void update(),250);});connection.onreconnected(()=>void update());void connection.start().then(()=>void update()).catch(()=>{});window.addEventListener('pagehide',()=>{clearTimeout(refresh);void connection.stop();});} + if(window.signalR){let refresh;const connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();connection.on('NativePresenceChanged',()=>{clearTimeout(refresh);refresh=setTimeout(()=>void update(),250);});connection.onreconnected(()=>void update(true));void connection.start().then(()=>void update()).catch(()=>{});window.addEventListener('pagehide',()=>{clearTimeout(refresh);void connection.stop();});} })(); diff --git a/PlotLine/wwwroot/js/native-companion-workspace.js b/PlotLine/wwwroot/js/native-companion-workspace.js index 7f2c81e7..f266d18d 100644 --- a/PlotLine/wwwroot/js/native-companion-workspace.js +++ b/PlotLine/wwwroot/js/native-companion-workspace.js @@ -1,37 +1,24 @@ (() => { 'use strict'; const root=document.querySelector('#native-workspace');if(!root)return; - const sessions=root.querySelector('#native-session'),follow=root.querySelector('#native-follow'),status=root.querySelector('#native-presence-status'),frame=root.querySelector('#native-story-workspace'); - let selected=root.dataset.instance&&root.dataset.session?root.dataset.instance+'/'+root.dataset.session:'',generation=0,position='',timer,loading=false,lastLive=null,manual=Boolean(selected); + // Context/Intent use Writing's existing fragment workspace directly, never an embedded document. + const sessions=root.querySelector('#native-session'),status=root.querySelector('#native-presence-status'),scene=root.querySelector('#native-current-scene'); const scope={projectID:Number(root.dataset.project),bookID:Number(root.dataset.book)}; + let selected=root.dataset.instance&&root.dataset.session?root.dataset.instance+'/'+root.dataset.session:'',pending=false; root.querySelectorAll('[data-native-open-role]').forEach(button=>button.addEventListener('click',()=>window.PlotDirectorWritingWorkspace?.openRoleWindow(button.dataset.nativeOpenRole,scope))); - if(['context','intent'].includes(root.dataset.mode)&&window.PlotDirectorWritingWorkspace)void window.PlotDirectorWritingWorkspace.registerWindow({...scope,writingRole:root.dataset.mode==='context'?'Context':'Intent'}).catch(()=>{}); - const sceneIndicator=root.querySelector("#native-current-scene"); - const sceneLabel=lease=>[lease?.chapterTitle,lease?.sceneTitle].filter(Boolean).join(" · ")||root.querySelector(`#native-manual-scene option[value="${Number(lease?.sceneId)||0}"]`)?.textContent||"Current manuscript scene"; - const indicate=(lease,live)=>{if(sceneIndicator)sceneIndicator.textContent=lease?.sceneId?(live?"Live from Word · ":"Saved scene · ")+sceneLabel(lease):"No trustworthy current Word scene · saved information remains available";}; - const setStatus=text=>{if(status.textContent!==text)status.textContent=text;}; - const show=lease=>{ - if(!['context','intent'].includes(root.dataset.mode))return; - const key=lease?[lease.chapterId,lease.sceneId].join(':'):'manual';if(position===key)return;position=key; - const url=new URL('/Writing/'+(root.dataset.mode==='intent'?'Intent':'Context'),location.origin);url.searchParams.set('projectId',root.dataset.project);url.searchParams.set('bookId',root.dataset.book);url.searchParams.set('pinned','true');url.searchParams.set('embedded','true');if(lease?.chapterId)url.searchParams.set('chapterId',lease.chapterId);if(lease?.sceneId)url.searchParams.set('sceneId',lease.sceneId);frame.src=url.pathname+url.search;frame.hidden=false; - }; - root.querySelector('#native-return')?.addEventListener('click',()=>{if(!lastLive?.sceneId||Date.parse(lastLive.expires)<=Date.now()){setStatus('No live Word scene. Your manual selection is kept.');return;}manual=false;position='';follow.checked=true;void poll();}); - root.querySelector('#native-manual-scene')?.addEventListener('change',event=>{const option=event.target.selectedOptions[0];if(!option?.value)return;manual=true;follow.checked=false;position='';const choice={chapterId:Number(option.dataset.chapter),sceneId:Number(option.value),sceneTitle:option.textContent};show(choice);indicate(choice,false);setStatus('Manual scene · following paused');}); - frame.addEventListener('load',()=>{try{const pause=()=>{manual=true;follow.checked=false;setStatus('Manual navigation · following paused');};frame.contentDocument.addEventListener('change',pause);frame.contentDocument.addEventListener('click',event=>{if(event.target.closest('a'))pause();});}catch{follow.checked=false;}}); - sessions.addEventListener('change',()=>{manual=true;selected=sessions.value;position='';follow.checked=false;indicate(null,false);void poll();});follow.addEventListener('change',()=>{if(!follow.checked){manual=true;indicate(lastLive,false);}position='';void poll();}); - async function poll(){ - if(loading||document.hidden)return;loading=true;const current=++generation; + sessions?.addEventListener('change',()=>{selected=sessions.value;void update();}); + async function update(){ + if(pending||document.hidden)return;pending=true; try{ - const response=await fetch('/native-companion/presence?bookId='+encodeURIComponent(root.dataset.book),{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw new Error('unavailable');const leases=await response.json();if(current!==generation)return; - const live=leases.filter(l=>Date.parse(l.expires)>Date.now());const signature=live.map(l=>l.instanceId+'/'+l.sessionId+':'+l.documentTitle).join('|'); - if(sessions.dataset.signature!==signature){sessions.dataset.signature=signature;sessions.replaceChildren(new Option('Choose a connected manuscript',''));for(const lease of live.filter(l=>l.wordAvailable))sessions.add(new Option(lease.documentTitle+(lease.active?' (active in Word)':''),lease.instanceId+'/'+lease.sessionId));sessions.value=selected;} - if(!manual){const active=live.filter(l=>l.active&&l.wordAvailable);if(active.length===1){selected=active[0].instanceId+'/'+active[0].sessionId;sessions.value=selected;follow.checked=true;}} - const lease=live.find(l=>l.instanceId+'/'+l.sessionId===selected);lastLive=lease; - if(lease){setStatus('Companion connected · Word '+(lease.wordAvailable?'available':'unavailable')+' · '+lease.documentTitle+' · last update '+new Date(lease.updated).toLocaleTimeString()+(follow.checked?(lease.sceneId?' · following saved position':' · no trustworthy live scene mapping; saved information only'):' · manual navigation'));if(follow.checked&&lease.wordAvailable&&lease.wordSaved!==false&&lease.sceneId){show(lease);indicate(lease,true);}else{if(follow.checked)indicate(null,false);if(!position)show(null);}} - else{indicate(null,false);setStatus(live.some(l=>!l.wordAvailable)?'Companion connected · Word unavailable. Saved Context and Intent remain available.':'Companion disconnected or stale for the selected manuscript. Saved workspaces remain available.');follow.checked=false;if(!position)show(null);} - }catch{indicate(null,false);setStatus('Connection status unavailable · following paused; saved data remains available');follow.checked=false;} - finally{loading=false;} + const response=await fetch('/native-companion/presence?bookId='+scope.bookID,{signal:AbortSignal.timeout(8000),cache:'no-store',headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw Error(); + const leases=(await response.json()).filter(l=>Date.parse(l.expires)>Date.now()),words=leases.filter(l=>l.wordAvailable),active=words.filter(l=>l.active); + const signature=words.map(l=>l.instanceId+'/'+l.sessionId+':'+l.documentTitle).join('|'); + if(sessions&&sessions.dataset.signature!==signature){sessions.dataset.signature=signature;sessions.replaceChildren(new Option('Active Word manuscript',''));for(const l of words)sessions.add(new Option(l.documentTitle,l.instanceId+'/'+l.sessionId));sessions.value=selected;} + const candidates=selected?words.filter(l=>l.instanceId+'/'+l.sessionId===selected):active.length===1?active:words; + const lease=candidates.length===1?candidates[0]:null; + status.textContent=lease?'Word connected · '+lease.documentTitle:words.length>1?'Choose a Word document':leases.length?'Companion connected · Word unavailable':'Companion disconnected or stale'; + scene.textContent=lease?.sceneId?[lease.chapterTitle,lease.sceneTitle].filter(Boolean).join(' · '):'No trustworthy current Word scene · saved workspaces remain available'; + }catch{status.textContent='Connection status unavailable · saved workspaces remain available';}finally{pending=false;} } - document.addEventListener('visibilitychange',()=>{if(!document.hidden)void poll();});window.addEventListener('pagehide',()=>clearInterval(timer));show(null);void poll();timer=setInterval(()=>void poll(),15000); - if(window.signalR){let refresh;const connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();connection.on('NativePresenceChanged',()=>{clearTimeout(refresh);refresh=setTimeout(()=>void poll(),250);});connection.onreconnected(()=>void poll());void connection.start().then(()=>void poll()).catch(()=>{});window.addEventListener('pagehide',()=>{clearTimeout(refresh);void connection.stop();});} + void update();const timer=setInterval(()=>void update(),15000);window.addEventListener('native-companion-presence',()=>void update());document.addEventListener('visibilitychange',()=>{if(!document.hidden)void update();});window.addEventListener('pagehide',()=>clearInterval(timer)); })(); diff --git a/PlotLine/wwwroot/js/story-position.js b/PlotLine/wwwroot/js/story-position.js new file mode 100644 index 00000000..ea351828 --- /dev/null +++ b/PlotLine/wwwroot/js/story-position.js @@ -0,0 +1,46 @@ +(() => { + if(window.PlotDirectorStoryPosition)return; + const storyPositionChangedEventName = "plotdirector:story-position-changed"; + + const normaliseStoryPositionPayload = (payload, source) => { + const position = payload?.position || payload?.Position || payload || {}; + const readNumber = (...values) => { + for (const value of values) { + const parsed = Number.parseInt(value || "", 10); + if (Number.isInteger(parsed) && parsed > 0) { + return parsed; + } + } + + return null; + }; + + return { + source: source || payload?.source || payload?.Source || "Navigation", + projectId: readNumber(position.projectId, position.ProjectId, payload?.projectId, payload?.ProjectId), + bookId: readNumber(position.bookId, position.BookId, payload?.bookId, payload?.BookId), + chapterId: readNumber(position.chapterId, position.ChapterId, payload?.chapterId, payload?.ChapterId), + sceneId: readNumber(position.sceneId, position.SceneId, payload?.sceneId, payload?.SceneId), + canonicalUrl: payload?.canonicalUrl || payload?.CanonicalUrl || payload?.sceneUrl || payload?.SceneUrl || "" + }; + }; + + const publishStoryPositionChanged = (payload, source) => { + const detail = normaliseStoryPositionPayload(payload, source); + if (!detail.projectId) { + return detail; + } + + document.dispatchEvent(new CustomEvent(storyPositionChangedEventName, { + bubbles: true, + detail + })); + return detail; + }; + + window.PlotDirectorStoryPosition = { + eventName: storyPositionChangedEventName, + normalise: normaliseStoryPositionPayload, + publishChanged: publishStoryPositionChanged + }; +})(); diff --git a/PlotLine/wwwroot/js/writing-context-components.js b/PlotLine/wwwroot/js/writing-context-components.js new file mode 100644 index 00000000..4c26a272 --- /dev/null +++ b/PlotLine/wwwroot/js/writing-context-components.js @@ -0,0 +1,49 @@ +(() => { + 'use strict'; + const root=document.querySelector('[data-writing-context]');if(!root)return; + function explore(host,index){host.querySelectorAll('[data-context-scene-card]').forEach(card=>card.hidden=Number(card.dataset.contextSceneCard)!==index);const range=host.querySelector('[data-context-scrubber]');if(range)range.value=String(index);} + function refresh(host){ + window.PlotDirectorContextMap?.refresh(host); + const current=root.querySelector('[data-writing-context-fragment]')?.dataset.sceneId; + const currentColumn=[...host.querySelectorAll('[data-context-chart-scene]')].find(node=>node.dataset.contextChartScene===current); + host.querySelectorAll('[data-context-chart-scene]').forEach(node=>node.setAttribute('aria-current',node===currentColumn?'location':'false')); + const index=Number(currentColumn?.dataset.sceneIndex),chart=host.querySelector('[data-context-chart]'); + const spacing=host.querySelector('[data-context-spacing]');if(spacing&&chart)chart.style.setProperty('--scene-width',spacing.value+'px'); + const marker=host.querySelector('[data-context-current-marker]');if(marker){marker.hidden=!currentColumn;if(currentColumn)marker.style.left=`calc(160px + (${index} + .5) * var(--scene-width,64px))`;} + host.querySelectorAll('[data-context-line-filter]').forEach(input=>{const lane=host.querySelector(`[data-context-line="${input.dataset.contextLineFilter}"]`);if(lane)lane.hidden=!input.checked;}); + const metric=host.querySelector('[data-context-metric-select]');host.querySelectorAll('[data-context-metric]').forEach(panel=>panel.hidden=metric&&panel.dataset.contextMetric!==metric.value); + if(host.dataset.explored&&host.querySelector('[data-context-scrubber]'))explore(host,Number(host.querySelector('[data-context-scrubber]').value)); + const currentSignature=current+':'+index; + if(currentColumn&&(!host.dataset.explored||host.dataset.currentSignature!==currentSignature)&&host.dataset.exploring!=='true'){ + host.dataset.explored='true';explore(host,index);host.dataset.centerPending='true'; + } + host.dataset.currentSignature=currentSignature; + if(host.dataset.centerPending&&!host.closest('[data-writing-context-panel]')?.hidden){center(host);delete host.dataset.centerPending;} + + } + function center(host){const marker=host.querySelector('[data-context-current-marker]'),scroll=host.querySelector('.writing-story-scroll');if(marker&&!marker.hidden&&scroll)scroll.scrollLeft=Math.max(0,marker.offsetLeft-scroll.clientWidth/2);} + async function load(host){ + if(host.dataset.loaded||host.dataset.loading)return; + host.dataset.loading='true';host.setAttribute('aria-busy','true');const requestedUrl=host.dataset.componentUrl;host.style.minHeight=host.clientHeight+'px'; + let loading=host.querySelector('[data-writing-loading]');if(!loading){loading=document.createElement('p');loading.dataset.writingLoading='';loading.className='small text-muted';loading.setAttribute('role','status');host.prepend(loading);}loading.textContent='Loading saved information…'; + try{ + const response=await fetch(host.dataset.componentUrl,{signal:AbortSignal.timeout(15000),headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok||response.redirected)throw Error(); + const fragment=window.PlotDirectorWritingFollow.fragmentFromHtml(await response.text(),'[data-writing-component-fragment]'); + if(!host.isConnected||host.dataset.componentUrl!==requestedUrl)return;root.dispatchEvent(new CustomEvent('writing-view-before-refresh'));host.replaceChildren(fragment);host.dataset.loaded='true';window.PlotDirectorContextMap?.mount(host);root.dispatchEvent(new CustomEvent('writing-component-loaded'));refresh(host); + }catch{if(host.isConnected&&host.dataset.componentUrl===requestedUrl){const p=document.createElement('p');p.textContent='Saved information could not be loaded. Your current scene is unchanged.';const retry=document.createElement('button');retry.type='button';retry.className='btn btn-sm btn-outline-secondary';retry.textContent='Retry';retry.addEventListener('click',()=>void load(host));host.replaceChildren(p,retry);}} + finally{delete host.dataset.loading;host.removeAttribute('aria-busy');host.style.minHeight='';if(host.isConnected&&host.dataset.componentUrl!==requestedUrl)update();} + } + function update(){for(const zoom of root.querySelectorAll('[data-context-floor-zoom]')){const floor=zoom.closest('article').querySelector('.writing-context-floor');if(floor)floor.style.setProperty('--floor-zoom',Number(zoom.value)/100);} + for(const host of root.querySelectorAll('[data-writing-component]')){if(!host.closest('[data-writing-context-panel]')?.hidden)void load(host);if(host.dataset.loaded)refresh(host);}} + root.addEventListener('writing-view-activated',update);root.addEventListener('writing-fragment-ready',update); + for(const event of ['wheel','pointerdown','keydown'])root.addEventListener(event,e=>{const scroll=e.target.closest('.writing-story-scroll');if(scroll){const host=scroll.closest('[data-writing-component]');if(host)host.dataset.exploring='true';}},{passive:true}); + root.addEventListener('input',event=>{if(event.target.matches('[data-context-floor-zoom]')){update();return;}const host=event.target.closest('[data-writing-component]');if(!host)return;if(event.target.matches('[data-context-scrubber]')){host.dataset.exploring='true';explore(host,Number(event.target.value));}else refresh(host);}); + root.addEventListener('change',event=>{const host=event.target.closest('[data-writing-component]');if(host)refresh(host);}); + root.addEventListener('click',event=>{const host=event.target.closest('[data-writing-component]');if(!host)return; + const target=event.target.closest('button');if(!target)return; + if(target.hasAttribute('data-context-refresh')){root.dispatchEvent(new CustomEvent('writing-view-before-refresh'));delete host.dataset.loaded;void load(host);} + if(target.hasAttribute('data-context-explore')){host.dataset.exploring='true';explore(host,Number(target.dataset.contextExplore));} + if(target.hasAttribute('data-context-center')){delete host.dataset.exploring;delete host.dataset.currentSignature;refresh(host);center(host);} + if(target.hasAttribute('data-context-go-scene')){delete host.dataset.exploring;delete host.dataset.currentSignature;const select=root.querySelector('[data-writing-context-scene-select]');if(select&&[...select.options].some(o=>o.value===target.dataset.contextGoScene)){select.value=target.dataset.contextGoScene;select.dispatchEvent(new Event('change'));}} + }); +})(); diff --git a/PlotLine/wwwroot/js/writing-context-map.js b/PlotLine/wwwroot/js/writing-context-map.js new file mode 100644 index 00000000..dddc7569 --- /dev/null +++ b/PlotLine/wwwroot/js/writing-context-map.js @@ -0,0 +1,40 @@ +(() => { + 'use strict'; + const mounted=new WeakMap(),ns='http://www.w3.org/2000/svg'; + function mount(host){ + const canvas=host.querySelector('[data-context-map-canvas]'),source=host.querySelector('[data-context-map-data]');if(!canvas||!source||mounted.get(host)?.canvas===canvas)return; + const data=JSON.parse(source.textContent),doc=data.document,E=window.PlotDirectorMaps,features=doc.features.filter(f=>f.isPlaced),byId=new Map(features.map(f=>[f.featureID,f])); + const make=(tag,attrs={},text)=>{const node=document.createElementNS(ns,tag);for(const [key,value]of Object.entries(attrs))node.setAttribute(key,String(value));if(text!==undefined)node.textContent=text;return node;}; + const viewport=()=>canvas.viewBox.baseVal; + const setView=(x,y,w,h)=>{const value=[x,y,Math.max(10,Math.min(1e7,w)),Math.max(10,Math.min(1e7,h))].join(' ');if(canvas.getAttribute('viewBox')!==value)canvas.setAttribute('viewBox',value);}; + let reference;try{reference=JSON.parse(doc.map.referenceJson||'{}');}catch{} + if(reference?.isVisible!==false&&/^[0-9a-f-]{36}$/i.test(reference?.imageID||''))canvas.append(make('image',{href:`/Maps/ReferenceImage?projectId=${data.projectID}&imageId=${reference.imageID}`,x:reference.x-reference.width/2,y:reference.y-reference.height/2,width:reference.width,height:reference.height,opacity:Math.max(0,Math.min(1,reference.opacity??.35)),transform:`rotate(${reference.rotation||0} ${reference.x} ${reference.y})`})); + const nodes=new Map(); + for(const f of features){ + const group=make('g',{'data-map-feature':f.featureID,tabindex:0,role:'button','aria-label':f.name});let shape; + if(f.geometryClass==='Path')shape=make('path',{d:E.curve(E.pathPoints(f,features)),fill:'none',stroke:'var(--plotline-muted)','stroke-width':3}); + else if(f.geometryClass==='Area')shape=make('path',{d:E.curve(E.coastline(f).map(p=>[p[0]*f.width,p[1]*f.height]),true),transform:`translate(${f.x} ${f.y}) rotate(${f.rotation})`,fill:'var(--plotline-panel-muted,var(--plotline-panel))',stroke:'var(--plotline-line)','stroke-width':2}); + else{shape=make('circle',{cx:f.x,cy:f.y,r:Math.max(8,f.width/3),fill:'var(--plotline-panel)',stroke:'var(--plotline-muted)','stroke-width':2});group.append(make('text',{x:f.x,y:f.y+5,'text-anchor':'middle','font-size':18,fill:'var(--plotline-ink)'},E.library.find(a=>a.type===f.type)?.symbol||'◇'));} + group.prepend(shape);if(f.showLabel)group.append(make('text',{x:f.x+(f.labelX||0),y:f.y+(f.labelY||0)+(f.geometryClass==='Marker'?36:0),'text-anchor':'middle','font-size':16,fill:'var(--plotline-ink)'},f.name));canvas.append(group);nodes.set(f.featureID,group); + } + function fit(){const bounds=features.flatMap(f=>f.geometryClass==='Path'?E.pathPoints(f,features):f.geometryClass==='Area'?E.coastline(f).map(p=>E.localToWorld(f,p)):[[f.x-f.width,f.y-f.height],[f.x+f.width,f.y+f.height]]);if(reference?.isVisible!==false&&reference?.imageID)bounds.push([reference.x-reference.width/2,reference.y-reference.height/2],[reference.x+reference.width/2,reference.y+reference.height/2]);if(!bounds.length){setView(-300,-200,600,400);return;}const xs=bounds.map(p=>p[0]),ys=bounds.map(p=>p[1]);setView(Math.min(...xs)-80,Math.min(...ys)-80,Math.max(300,Math.max(...xs)-Math.min(...xs)+160),Math.max(250,Math.max(...ys)-Math.min(...ys)+160));} + function focus(){const f=byId.get(data.position?.featureID);if(!f)return;const v=viewport();setView(f.x-v.width/2,f.y-v.height/2,v.width,v.height);} + function zoom(ratio){canvas.dataset.contextManualPan='true';const v=viewport();setView(v.x+v.width*(1-ratio)/2,v.y+v.height*(1-ratio)/2,v.width*ratio,v.height*ratio);} + function refresh(){ + if(canvas.dataset.contextManualPan!=='true')focus(); + const lens=host.querySelector('[data-context-map-lens]').value,selected=host.querySelector('[data-context-map-feature]').value; + const highlighted=new Set(lens==='scene'?[data.position?.featureID]:lens==='people'?(data.story?.stops||[]).filter(p=>p.sceneID===data.sceneID).map(p=>p.position.featureID):lens==='plots'?(data.story?.scenes||[]).filter(s=>s.plotLineIDs.length).map(s=>s.position.featureID):features.map(f=>f.featureID)); + for(const[id,node]of nodes){node.classList.toggle('is-scene-place',id===data.position?.featureID);node.classList.toggle('is-explored',id===selected);node.style.opacity=lens==='all'||highlighted.has(id)||id===selected?'1':'.35';} + const feature=byId.get(selected),detail=host.querySelector('[data-context-map-detail]'); + if(feature){const relationships=doc.relationships.filter(r=>r.sourceID===selected||r.targetID===selected).map(r=>{const other=byId.get(r.sourceID===selected?r.targetID:r.sourceID);return[other?.name,r.direction,r.relativeDistance,r.measuredDistance!=null?r.measuredDistance+' '+(r.unit||''):null,r.typicalTravelTime,r.notes].filter(Boolean).join(' · ');});detail.textContent=[feature.name,feature.notes,...relationships].filter(Boolean).join(' — ');}else detail.textContent='Select a place to inspect its saved relationships.'; + } + host.querySelector('[data-context-map-fit]').addEventListener('click',()=>{canvas.dataset.contextManualPan='true';fit();});host.querySelector('[data-context-map-focus]').addEventListener('click',()=>{delete canvas.dataset.contextManualPan;focus();});host.querySelectorAll('[data-context-map-zoom]').forEach(button=>button.addEventListener('click',()=>zoom(Number(button.dataset.contextMapZoom)))); + host.querySelector('[data-context-map-feature]').addEventListener('change',event=>select(event.target.value));host.querySelector('[data-context-map-lens]').addEventListener('change',refresh); + const select=id=>{host.querySelector('[data-context-map-feature]').value=id;const place=byId.get(id);if(place){canvas.dataset.contextManualPan='true';const v=viewport();setView(place.x-v.width/2,place.y-v.height/2,v.width,v.height);}refresh();};canvas.addEventListener('click',event=>{const f=event.target.closest('[data-map-feature]');if(f)select(f.dataset.mapFeature);});canvas.addEventListener('keydown',event=>{const f=event.target.closest('[data-map-feature]');if(f&&['Enter',' '].includes(event.key)){event.preventDefault();select(f.dataset.mapFeature);}else if(['ArrowLeft','ArrowRight','ArrowUp','ArrowDown'].includes(event.key)){event.preventDefault();canvas.dataset.contextManualPan='true';const v=viewport();setView(v.x+({'ArrowLeft':-.1,'ArrowRight':.1}[event.key]||0)*v.width,v.y+({'ArrowUp':-.1,'ArrowDown':.1}[event.key]||0)*v.height,v.width,v.height);}}); + let drag=null;canvas.addEventListener('pointerdown',event=>{if(event.button!==0)return;const v=viewport();drag={x:event.clientX,y:event.clientY,left:v.x,top:v.y,w:v.width,h:v.height};canvas.setPointerCapture(event.pointerId);});canvas.addEventListener('pointermove',event=>{if(drag){canvas.dataset.contextManualPan='true';setView(drag.left-(event.clientX-drag.x)*drag.w/canvas.clientWidth,drag.top-(event.clientY-drag.y)*drag.h/canvas.clientHeight,drag.w,drag.h);}});canvas.addEventListener('pointerup',()=>drag=null);canvas.addEventListener('pointercancel',()=>drag=null); + host.querySelector('[data-context-map-choice]').addEventListener('change',event=>{const url=new URL(host.dataset.componentUrl,location.origin);url.searchParams.set('mapId',event.target.value);host.dataset.componentUrl=url.pathname+url.search;delete host.dataset.loaded;root(host).dispatchEvent(new CustomEvent('writing-view-activated'));}); + mounted.set(host,{refresh,canvas});fit();focus();refresh(); + } + function root(host){return host.closest('[data-writing-context]');} + window.PlotDirectorContextMap={mount,refresh:host=>mounted.get(host)?.refresh()}; +})(); diff --git a/PlotLine/wwwroot/js/writing-follow.js b/PlotLine/wwwroot/js/writing-follow.js index d49045f7..fd454fee 100644 --- a/PlotLine/wwwroot/js/writing-follow.js +++ b/PlotLine/wwwroot/js/writing-follow.js @@ -24,6 +24,13 @@ return Number.isInteger(parsed) && parsed > 0 ? parsed : null; }; + const fragmentFromHtml = (html, selector) => { + const parsed = new DOMParser().parseFromString(html, 'text/html'); + const fragment = parsed.body.firstElementChild; + if (/]|]|]/i.test(html) || !fragment?.matches(selector) || parsed.body.children.length !== 1) throw new Error('Expected a writing fragment, received a full page or invalid response'); + return fragment; + }; + const initialize = (options) => { const config = { ...defaults, ...options }; const root = document.querySelector(config.rootSelector); @@ -42,10 +49,32 @@ let loadingSceneId = null; let loadingChapterId = null; let requestGeneration = 0; - let pendingRequest = null; + let pendingRequest = null, navigationRequest = null; + let manualGeneration=0; + let selectedDocument = root.dataset.wordInstance && root.dataset.wordSession ? root.dataset.wordInstance + '/' + root.dataset.wordSession : ''; + let nativePositionKey = '', nativeWasConnected = false, nativeLeases = []; + const viewState = new Map(), viewNodeIds=new WeakMap();let viewNodeSequence=0; + const viewIdentity=node=>{if(!viewNodeIds.has(node))viewNodeIds.set(node,++viewNodeSequence);return viewNodeIds.get(node);}; + const saveView = () => { + contentHost?.querySelectorAll('[data-writing-view-state]').forEach(node => viewState.set(node.dataset.writingViewState, { value: node.value, checked: node.checked, instance:viewIdentity(node), manualPan:node.dataset.contextManualPan, left: node.scrollLeft, top: node.scrollTop, viewBox: node.getAttribute("viewBox") })); + }; + const restoreView = () => { + contentHost?.querySelectorAll('[data-writing-view-state]').forEach(node => { + const state = viewState.get(node.dataset.writingViewState); if (!state||state.instance===viewIdentity(node)) return; + if (node.matches('select') && [...node.options].some(o => o.value === state.value) || node.matches('input')) node.value = state.value; + if (node.matches('input[type=checkbox]')) node.checked = state.checked; + node.scrollLeft = state.left; node.scrollTop = state.top; + if(state.viewBox&&node.tagName.toLowerCase()==="svg"){node.setAttribute("viewBox",state.viewBox);if(state.manualPan==='true')node.dataset.contextManualPan='true';else delete node.dataset.contextManualPan;} + state.instance=viewIdentity(node); + }); + root.dispatchEvent(new CustomEvent('writing-fragment-ready')); + }; + + root.addEventListener("writing-component-loaded",restoreView); + root.addEventListener("writing-view-before-refresh",saveView); const setStatus = (value) => { - if (statusText && value) { + if (statusText && value && statusText.textContent!==value) { statusText.textContent = value; } }; @@ -107,17 +136,22 @@ } }; + let selectedTab=readStoredTab(); + const activeTab = () => { const active = contentHost?.querySelector(`${config.tabSelector}.active`)?.dataset[config.tabDataKey]; return active || readStoredTab(); }; const activateTab = (tabName) => { - const nextTab = tabName || config.defaultTab; + const requested = tabName || config.defaultTab; + const nextTab=[...contentHost.querySelectorAll(config.tabSelector)].some(button=>button.dataset[config.tabDataKey]===requested)?requested:config.defaultTab; + selectedTab=nextTab; contentHost?.querySelectorAll(config.tabSelector).forEach((button) => { const active = button.dataset[config.tabDataKey] === nextTab; button.classList.toggle("active", active); button.setAttribute("aria-selected", String(active)); + button.setAttribute("role","tab");button.tabIndex=active?0:-1; }); contentHost?.querySelectorAll(config.panelSelector).forEach((panel) => { const active = panel.dataset[config.panelDataKey] === nextTab; @@ -126,13 +160,14 @@ }); try { localStorage.setItem(config.storageKey, nextTab); + root.dispatchEvent(new CustomEvent("writing-view-activated")); } catch { // Remembering the selected tab is a convenience only. } }; const wireFragment = () => { - activateTab(activeTab()); + activateTab(selectedTab); const fragment = contentHost?.querySelector(config.fragmentSelector); const fragmentStatus = fragment?.dataset.followStatus; if (fragmentStatus) { @@ -152,23 +187,36 @@ contentHost?.querySelectorAll(config.tabSelector).forEach((button) => { button.addEventListener("click", () => activateTab(button.dataset[config.tabDataKey])); + button.closest('nav')?.setAttribute('role','tablist'); + button.addEventListener('keydown',event=>{ + if(!['ArrowLeft','ArrowRight','Home','End'].includes(event.key))return; + event.preventDefault();const tabs=[...contentHost.querySelectorAll(config.tabSelector)],at=tabs.indexOf(button); + const index=event.key==='Home'?0:event.key==='End'?tabs.length-1:(at+(event.key==='ArrowRight'?1:-1)+tabs.length)%tabs.length; + activateTab(tabs[index].dataset[config.tabDataKey]);tabs[index].focus({preventScroll:true}); + }); }); - contentHost?.querySelector(config.selectSelector)?.addEventListener("change", (event) => { - const sceneId = parsePositiveInt(event.target.value); - if (!sceneId) { - return; - } - + const navigate = async (id) => { + const sceneId = parsePositiveInt(id); if (!sceneId) return; + const manual=++manualGeneration;navigationRequest?.abort(); const fragment = contentHost?.querySelector(config.fragmentSelector); - window.PlotDirectorStoryPosition?.publishChanged({ - source: config.source, - projectId: fragment?.dataset.projectId, - bookId: fragment?.dataset.bookId, - chapterId: fragment?.dataset.chapterId, - sceneId - }, config.source); - }); + const position = { source: config.source, projectId: parsePositiveInt(fragment?.dataset.projectId || root.dataset.scopeProjectId), bookId: parsePositiveInt(fragment?.dataset.bookId || root.dataset.scopeBookId), sceneId }; + await loadPosition(position); + if (manual!==manualGeneration || currentSceneId !== sceneId || root.dataset.followMode === 'snapshot') return; + const token = root.querySelector('[name=__RequestVerificationToken]')?.value; + if (!token) return; + const body = new URLSearchParams({bookId: position.bookId, sceneId, __RequestVerificationToken: token}); + if (selectedDocument) { const [instanceId, sessionId] = selectedDocument.split('/'); body.set('instanceId', instanceId); body.set('sessionId', sessionId); } + const beforeNavigation=nativePositionKey; + try { + navigationRequest=new AbortController(); + const response = await fetch('/Writing/Context/Navigate', { method: 'POST', body, signal:navigationRequest.signal, headers: {'X-Requested-With':'XMLHttpRequest'} }); + const result = await response.json(); + if (manual===manualGeneration&¤tSceneId === sceneId&&nativePositionKey===beforeNavigation) setStatus(result.message || 'Saved scene selected; Word navigation unavailable.'); + } catch (error) { if (manual===manualGeneration&&error?.name!=='AbortError'&¤tSceneId === sceneId) setStatus('Saved scene selected. Word navigation is unavailable.'); } + }; + contentHost?.querySelector(config.selectSelector)?.addEventListener('change', event => void navigate(event.target.value)); + contentHost?.querySelectorAll('[data-writing-scene-step]').forEach(button => button.addEventListener('click', () => void navigate(button.dataset.writingSceneStep))); contentHost?.querySelector("[data-writing-intent-chapter-select]")?.addEventListener("change", (event) => { const chapterId = parsePositiveInt(event.target.value); @@ -177,12 +225,12 @@ } const fragment = contentHost?.querySelector(config.fragmentSelector); - window.PlotDirectorStoryPosition?.publishChanged({ + void loadPosition({ source: config.source, - projectId: fragment?.dataset.projectId, - bookId: fragment?.dataset.bookId, + projectId: parsePositiveInt(fragment?.dataset.projectId), + bookId: parsePositiveInt(fragment?.dataset.bookId), chapterId - }, config.source); + }); }); }; @@ -225,7 +273,6 @@ pendingRequest?.abort(); const controller = new AbortController(); pendingRequest = controller; - const tab = activeTab(); loadingSceneId = hasScene ? position.sceneId : null; loadingChapterId = !hasScene ? position.chapterId : null; setStatus(config.updatingStatus); @@ -238,19 +285,39 @@ try { console.info(`[${config.source}] Loading writing position.`, position); const response = await fetch(url, { signal: controller.signal, headers: { "X-Requested-With": "XMLHttpRequest" } }); - if (!response.ok) { + if (!response.ok || response.redirected) { throw new Error(`${config.source} request failed: ${response.status}`); } const html = await response.text(); if (generation !== requestGeneration) return; - contentHost.innerHTML = html; + // Only the expected server-rendered fragment may enter this workspace. Never embed a shell/login/Timeline page. + const fragment = fragmentFromHtml(html, config.fragmentSelector); + const tab = activeTab(), scroll = {x: window.scrollX, y: window.scrollY}; + const focused=document.hasFocus()&&contentHost.contains(document.activeElement)?document.activeElement:null; + const focusedTab=focused?.dataset[config.tabDataKey],focusedSelect=focused?.matches(config.selectSelector); + saveView(); + for(const panel of contentHost.querySelectorAll('[data-writing-stable-panel]')) { + const replacement=[...fragment.querySelectorAll('[data-writing-stable-panel]')].find(p=>p.dataset.writingStablePanel===panel.dataset.writingStablePanel); + if(replacement){ + if(panel.dataset.writingComponent==='map'&&panel.dataset.componentUrl!==replacement.dataset.componentUrl){panel.dataset.componentUrl=replacement.dataset.componentUrl;delete panel.dataset.loaded;} + replacement.replaceWith(panel); + } + } + contentHost.replaceChildren(fragment); + currentFragment = fragment; currentSceneId = hasScene ? position.sceneId : null; if (hasChapter) { currentChapterId = position.chapterId; } wireFragment(); activateTab(tab); + if(root.dataset.followMode!=="snapshot")setStatus(position.source==="WordCompanion"?"Following Word":"Saved scene"); + restoreView(); + if(focused?.isConnected)focused.focus({preventScroll:true}); + else if(focusedTab)[...contentHost.querySelectorAll(config.tabSelector)].find(button=>button.dataset[config.tabDataKey]===focusedTab)?.focus({preventScroll:true}); + else if(focusedSelect)contentHost.querySelector(config.selectSelector)?.focus({preventScroll:true}); + window.scrollTo(scroll.x, scroll.y); } catch (error) { if (generation !== requestGeneration || error?.name === "AbortError") return; console.warn(`${config.source} could not update.`, error); @@ -268,13 +335,44 @@ } }; + const followNative = (leases) => { + nativeLeases = leases; + if(leases.reconnected)nativeWasConnected=false; + const available = leases.filter(l => Date.parse(l.expires) > Date.now() && l.wordAvailable && (!scopedBookId || Number(l.bookId) === scopedBookId)); + if(!available.length&&document.querySelector('[data-word-companion-presence]')?.dataset.officeConnected==='true'){nativeWasConnected=false;nativePositionKey='';return;} + const active = available.filter(l => l.active); + const chosen = selectedDocument ? available.filter(l => l.instanceId + '/' + l.sessionId === selectedDocument) : active.length === 1 ? active : available; + const lease = chosen.length === 1 ? chosen[0] : null; + if (!lease) { nativeWasConnected = false; nativePositionKey = ''; setStatus(available.length > 1 && !selectedDocument ? 'Choose a Word document using the connection indicator' : selectedDocument ? 'Selected Word document is disconnected · saved scene remains available' : leases.some(l=>l.wordAvailable) ? 'Saved scene · no live Word position for this book' : 'Word disconnected · saved scene remains available'); return; } + const key = [lease.instanceId, lease.sessionId, lease.chapterId, lease.sceneId].join(':'); + if ((!lease.sceneId && !(config.allowChapterOnly && lease.chapterId)) || lease.wordSaved === false) { nativeWasConnected = true; nativePositionKey = key; setStatus('No trustworthy current Word scene · saved scene remains available'); return; } + if (!nativeWasConnected || key !== nativePositionKey) { + nativeWasConnected = true; nativePositionKey = key; + void loadPosition({source:'WordCompanion',projectId:scopedProjectId || parsePositiveInt(currentFragment?.dataset.projectId),bookId:Number(lease.bookId),chapterId:Number(lease.chapterId),sceneId:lease.sceneId?Number(lease.sceneId):null}); + setStatus('Following Word'); + } + }; + if (root.dataset.followMode !== 'snapshot') { + window.addEventListener('native-companion-presence', event => followNative(event.detail || [])); + window.addEventListener('plotdirector:word-return-to-current',()=>{nativePositionKey='';nativeWasConnected=false;followNative(nativeLeases);}); + window.addEventListener('plotdirector:word-document-selected', event => { selectedDocument = event.detail || ''; nativePositionKey = ''; nativeWasConnected = false; followNative(nativeLeases); }); + } + if (root.dataset.followMode === "snapshot") { wireFragment(); setStatus("Saved PlotDirector snapshot — manual selection"); return { loadPosition, activateTab }; } document.addEventListener(window.PlotDirectorStoryPosition?.eventName || "plotdirector:story-position-changed", (event) => { void loadPosition(event.detail); }); - if (window.signalR) { + if (typeof window.PlotDirectorWritingWorkspace?.watchWorkspace === 'function') { + const acceptWorkspace = async status => { + if(selectedDocument||nativeLeases.some(l=>l.wordAvailable&&Date.parse(l.expires)>Date.now()&&(!scopedBookId||Number(l.bookId)===scopedBookId)))return; + const position=storyPositionFromWorkspaceStatus(status); + if(position?.sceneId || config.allowChapterOnly&&position?.chapterId)await loadPosition(position); + }; + void window.PlotDirectorWritingWorkspace.watchWorkspace({projectID:scopedProjectId,bookID:scopedBookId}).then(acceptWorkspace).catch(()=>{if(!nativeWasConnected)setStatus(config.disconnectedStatus);}); + document.addEventListener('plotdirector:writing-workspace-reconnected',event=>void acceptWorkspace(event.detail)); + } else if (window.signalR) { const connection = new signalR.HubConnectionBuilder() .withUrl("/hubs/word-companion-follow") .withAutomaticReconnect() @@ -301,6 +399,7 @@ } }) .catch((error) => { + if(nativeWasConnected)return; console.warn(`${config.source} follow connection unavailable.`, error); setStatus(config.disconnectedStatus); setEmptyState( @@ -317,8 +416,9 @@ } wireFragment(); + restoreView(); return { loadPosition, activateTab }; }; - window.PlotDirectorWritingFollow = { initialize }; + window.PlotDirectorWritingFollow = { initialize, fragmentFromHtml }; })(); diff --git a/PlotLine/wwwroot/js/writing-workspace-launcher.js b/PlotLine/wwwroot/js/writing-workspace-launcher.js index 46580d48..b8fde5af 100644 --- a/PlotLine/wwwroot/js/writing-workspace-launcher.js +++ b/PlotLine/wwwroot/js/writing-workspace-launcher.js @@ -25,6 +25,10 @@ projectID: root.dataset.projectId, bookID: root.dataset.bookId }); + const savedDisplays=workspace.readPreferences?.() || {}; + if(contextDisplaySelect&&savedDisplays.contextDisplay){if([...contextDisplaySelect.options].some(o=>o.value===savedDisplays.contextDisplay))contextDisplaySelect.value=savedDisplays.contextDisplay;else contextDisplaySelect.dataset.pendingDisplay=savedDisplays.contextDisplay;} + if(intentDisplaySelect&&savedDisplays.intentDisplay){if([...intentDisplaySelect.options].some(o=>o.value===savedDisplays.intentDisplay))intentDisplaySelect.value=savedDisplays.intentDisplay;else intentDisplaySelect.dataset.pendingDisplay=savedDisplays.intentDisplay;} + for(const select of [contextDisplaySelect,intentDisplaySelect])select?.addEventListener('change',()=>{select.dataset.userChanged='true';delete select.dataset.pendingDisplay;workspace.savePreferences?.(selectedDisplayPreferences());}); let activeScope = { ...fallbackScope }; let latestStatus = null; let latestScreenInfo = null; @@ -45,8 +49,8 @@ const setMessage = (message) => text(statusNodes.message, message || ""); const selectedDisplayPreferences = () => ({ - contextDisplay: contextDisplaySelect?.value || "left", - intentDisplay: intentDisplaySelect?.value || "right" + contextDisplay: contextDisplaySelect?.dataset.pendingDisplay || contextDisplaySelect?.value || "left", + intentDisplay: intentDisplaySelect?.dataset.pendingDisplay || intentDisplaySelect?.value || "right" }); const displayLabel = (display, fallback) => { @@ -62,8 +66,8 @@ return; } - const currentContext = contextDisplaySelect.value; - const currentIntent = intentDisplaySelect.value; + const currentContext = contextDisplaySelect.dataset.userChanged?contextDisplaySelect.value:savedDisplays.contextDisplay||contextDisplaySelect.value; + const currentIntent = intentDisplaySelect.dataset.userChanged?intentDisplaySelect.value:savedDisplays.intentDisplay||intentDisplaySelect.value; const baseContext = [ ["left", "Left display"], ["primary", "Primary display"], diff --git a/PlotLine/wwwroot/js/writing-workspace.js b/PlotLine/wwwroot/js/writing-workspace.js index b8f3671f..1d21e450 100644 --- a/PlotLine/wwwroot/js/writing-workspace.js +++ b/PlotLine/wwwroot/js/writing-workspace.js @@ -81,8 +81,8 @@ }); const buildWritingUrl = (role, scope) => { - const url = new URL("/native-companion/workspace", window.location.origin); - url.searchParams.set("view",role === roles.context ? "context" : "intent"); + const url = new URL(role === roles.context ? "/Writing/Context" : "/Writing/Intent", window.location.origin); + url.searchParams.set("embedded","true"); const projectId = parsePositiveInt(scope?.projectID ?? scope?.projectId); const bookId = parsePositiveInt(scope?.bookID ?? scope?.bookId); const position = parsePositiveInt(latestPosition?.bookId ?? latestPosition?.bookID) === bookId ? latestPosition : {}; @@ -179,11 +179,11 @@ const popupFeatures = (display) => { if (!display) { - return "popup=yes,width=1120,height=900"; + return `popup=yes,width=${Math.min(1120,Math.max(360,(window.screen?.availWidth||1160)-40))},height=${Math.min(900,Math.max(480,(window.screen?.availHeight||940)-40))}`; } - const width = Math.max(900, Math.floor(display.width * 0.92)); - const height = Math.max(760, Math.floor(display.height * 0.92)); + const width = Math.min(display.width, Math.max(360, Math.floor(display.width * 0.92))); + const height = Math.min(display.height, Math.max(480, Math.floor(display.height * 0.92))); const left = Math.floor(display.left + (display.width - width) / 2); const top = Math.floor(display.top + (display.height - height) / 2); return `popup=yes,left=${left},top=${top},width=${width},height=${height}`; @@ -246,7 +246,7 @@ }); connection.onreconnected(() => { if (registration) { - void registerWindow(registration); + void registerWindow(registration).then(()=>watchWorkspace(registration)).then(status=>document.dispatchEvent(new CustomEvent("plotdirector:writing-workspace-reconnected",{detail:status}))).catch(()=>{}); } }); @@ -305,7 +305,7 @@ const url = buildWritingUrl(role, scope); const name = stableWindowName(role, scope); const existing=windowRefs.get(name); - if(existing&&!existing.closed){if(existing.location.pathname+existing.location.search!==url)existing.location.assign(url);existing.focus();return existing;} + if(existing&&!existing.closed){const target=new URL(url,location.origin);if(existing.location.pathname!==target.pathname||new URLSearchParams(existing.location.search).get("bookId")!==target.searchParams.get("bookId"))existing.location.assign(url);existing.focus();return existing;} const opened = window.open(url, name, popupFeatures(display)); if (opened) { windowRefs.set(stableWindowName(role, scope), opened); @@ -322,7 +322,8 @@ const ref = windowRefs.get(stableWindowName(role, scope)); if (ref && !ref.closed) { const target=buildWritingUrl(role,scope); - if(ref.location.pathname+ref.location.search!==target)ref.location.assign(target); + const destination=new URL(target,location.origin); + if(ref.location.pathname!==destination.pathname || new URLSearchParams(ref.location.search).get("bookId")!==destination.searchParams.get("bookId"))ref.location.assign(target); ref.focus(); return true; } @@ -388,6 +389,8 @@ sortScreens, chooseLayout, getScreenLayout, + readPreferences, + savePreferences, scopeFrom, statusScope };