Replace Context plot matrix with saved before now and after cards

This commit is contained in:
Nick Beckley 2026-11-09 21:31:27 +00:00
parent 0ef2e9cf62
commit 09449a9aab
14 changed files with 314 additions and 34 deletions

View File

@ -8,11 +8,11 @@ const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
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')});
for(const script of ['story-position','writing-follow','maps-engine','writing-context-map','writing-context-plots','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=plots]');await page.waitForSelector('[data-plot-line]');assert.ok(await page.getByText('The letter changes hands',{exact:false}).count());
await page.click('[data-plot-category=elsewhere]');await page.locator('[data-plot-scrubber]').fill('1');assert.match(await page.locator('[data-plot-position]').textContent(),/Exploring/);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.locator('[data-plot-category=elsewhere]').getAttribute('aria-pressed'),'true');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.locator('[data-plot-category=elsewhere]').getAttribute('aria-pressed'),'true');assert.equal(await page.locator('[data-plot-scene="1"]').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');

View File

@ -0,0 +1,37 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('node:path');
const base='http://127.0.0.1:5238';
(async()=>{const browser=await chromium.launch();try{
for(const pwa of [false,true])for(const embedded of [false,true]){
const ctx=await browser.newContext({viewport:{width:1440,height:1000}});if(pwa)await ctx.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));const page=await ctx.newPage();let reads=0,mutations=0,navigation=0;
page.on('request',r=>{if(!['GET','HEAD'].includes(r.method())&&!r.url().includes('/hubs/'))mutations++;});
await page.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:require('fs').readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')}));
await page.route('**/Writing/Context/Navigate',r=>{navigation++;return r.fulfill({json:{message:'Navigation requested'}});});
await page.route('**/native-companion/status',r=>r.fulfill({json:[]}));
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?*',async r=>{reads++;await r.fulfill({response:await r.fetch({url:base+'/writing-context-component/plots?contextCases=true'})});});
await page.goto(base+'/Writing/Context?bookId=12'+(embedded?'&embedded=true':''));
await page.evaluate(()=>{const root=document.querySelector('[data-writing-context]');root.dataset.followMode='live';});
// The normal Context fragment and presence event path choose a saved scene.
const beat=async id=>{await page.evaluate(id=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[{instanceId:'fixture',sessionId:'doc',bookId:12,chapterId:10,sceneId:id,active:true,wordSaved:true,wordAvailable: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 beat(23);await page.click('[data-writing-context-tab=plots]');await page.waitForSelector('[data-plot-context-data]',{state:'attached'});await page.waitForFunction(()=>document.querySelectorAll('[data-plot-line]').length===6);
assert.equal(await page.locator('[data-plot-count=active]').textContent(),'(3)');assert.equal(await page.locator('[data-plot-count=nearby]').textContent(),'(3)');assert.equal(await page.locator('[data-plot-count=elsewhere]').textContent(),'(1)');
assert.equal(await page.locator('[data-plot-line="6"]').count(),0);assert.equal(await page.locator('[data-plot-line="5"] .is-now').textContent().then(s=>s.includes('No recorded development')),true);
const active=page.locator('[data-plot-line="1"]');await active.getByText('Current first',{exact:true}).waitFor();await active.getByText('Current second',{exact:true}).waitFor();assert.match(await active.locator('.is-before').textContent(),/Earlier active development/);assert.match(await active.locator('.is-after').textContent(),/Upcoming in manuscript order.*Upcoming active development/);
assert.match(await page.locator('[data-plot-line="2"] .is-after').textContent(),/No later recorded development/);assert.match(await page.locator('[data-plot-line="3"] .is-before').textContent(),/No earlier recorded development/);
assert.match(await page.locator('[data-plot-line="4"] .writing-plot-status').textContent(),/previous 1 scene ago.*next in 5 scenes/);
await page.click('[data-plot-all]');assert.equal(await page.locator('[data-plot-line]').count(),7);assert.equal(await page.locator('[data-plot-scene-strip] button').count(),6);
for(const theme of ['modern-light','modern-dark','warm-light','warm-dark'])for(const width of [390,768,1710]){
await page.evaluate(t=>{document.documentElement.dataset.appTheme=t;document.documentElement.dataset.theme=t.endsWith('dark')?'dark':'light';document.documentElement.dataset.bsTheme=document.documentElement.dataset.theme;},theme);await page.setViewportSize({width,height:1000});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,`${theme} ${width}`);
const colors=await active.locator('.is-now').evaluate(el=>{const probe=document.createElement('span');el.append(probe);probe.style.color='var(--pd-selected)';const expected=getComputedStyle(probe).color;probe.remove();return [getComputedStyle(el).backgroundColor,expected];});assert.equal(colors[0],colors[1]);const stripColors=await page.locator('[data-plot-scene-strip] [aria-current]').evaluate(el=>{const p=document.createElement('i');el.append(p);p.style.color='var(--pd-accent)';const accent=getComputedStyle(p).color;p.style.color='var(--pd-on-accent)';const foreground=getComputedStyle(p).color;p.remove();return [getComputedStyle(el).backgroundColor,accent,getComputedStyle(el).color,foreground];});assert.equal(stripColors[0],stripColors[1]);assert.equal(stripColors[2],stripColors[3]);
if(process.env.PD_PLOT_SCREENSHOTS&&width===1710&&!pwa&&embedded)await page.screenshot({path:process.env.PD_PLOT_SCREENSHOTS+'/'+theme+'.png',fullPage:true});
}
const priorMutations=mutations;await page.locator('[data-plot-scrubber]').fill('8');assert.match(await page.locator('[data-plot-position]').textContent(),/Exploring: Ch 12 · Sc 9/);assert.equal(await page.locator('[data-plot-step="1"]').isDisabled(),true);assert.equal(reads,1);assert.equal(mutations,priorMutations,'Exploring cannot mutate saved data or request Word navigation');
await page.click('[data-plot-return]');assert.match(await page.locator('[data-plot-position]').textContent(),/Current scene: Ch 3 · Sc 2.5/);
await page.click('[data-context-go-scene]');await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent==='Navigation requested');assert.equal(navigation,1,'Only the explicit Word action requests navigation');
await page.evaluate(()=>window.retainedPlot=document.querySelector('[data-writing-component=plots]'));for(const id of [22,900,47,23])await beat(id);assert(await page.evaluate(()=>retainedPlot===document.querySelector('[data-writing-component=plots]')));assert.equal(reads,1);assert.equal(await page.locator('[data-plot-category=elsewhere]').getAttribute('aria-pressed'),'true');
await page.evaluate(()=>{for(const sceneId of [22,47,23,900])window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[{instanceId:'fixture',sessionId:'doc',bookId:12,chapterId:10,sceneId,active:true,wordSaved:true,wordAvailable:true,expires:new Date(Date.now()+45000).toISOString()}]}));});
await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='900');await page.waitForFunction(()=>document.querySelector('[data-plot-position]').textContent.includes('Saved scene 900'));assert.equal(reads,1,'Burst cursor events reuse the book payload and the latest scene wins');
await page.locator('[data-plot-scrubber]').fill('0');assert.equal(await page.locator('[data-plot-step="-1"]').isDisabled(),true);await ctx.close();
}
console.log('PASS canonical contextual cards: every development, association-only, previous/future/both/empty, real numbering and distances, category counts, 4 themes x 3 widths, browser/PWA/embedded, rapid following, local exploration/return, single read, read-only controls.');
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});

View File

@ -3,9 +3,9 @@ const {chromium}=require('playwright'),assert=require('node:assert/strict'),path
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]'));
for(const script of ['story-position','writing-follow','writing-context-plots','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.ok(await page.locator('[data-plot-scene-strip] button').count()<=7);assert.equal(await page.locator('[data-plot-line]').count(),10);assert.equal(await page.locator('[data-context-chart-scene]').count(),0);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.`);
assert.equal(reads,1);assert.ok(await page.evaluate(()=>originalPlot===document.querySelector('[data-writing-component=plots]')));assert.equal(await page.locator('[data-plot-scene="399"]').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 panel/compact scene strip and no page overflow. Chromium fixture measurements only, not Word performance.`);
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);});

View File

@ -501,6 +501,7 @@ var tests = new (string Name, Action Test)[]
("Toolbar preferences, authorisation and contextual routes", ToolbarTests.PreferencesAndRoutes),
("Application navigation resolves authorised project and book context", ApplicationNavigationTests.ContextAndPermissions),
("Writing pair shares canonical follow infrastructure", WritingPairSharesCanonicalFollowInfrastructure),
("Writing Context Plot Lines preserves canonical associations, developments and book access", () => WritingContextPlotLinesTests.Run().GetAwaiter().GetResult()),
("Writing workspace presence scopes browser windows", WritingWorkspacePresenceScopesBrowserWindows),
("Writing workspace client uses session window identity and stable names", WritingWorkspaceClientUsesSessionIdentityAndStableNames),
("Writing workspace launcher uses progressive screen placement", WritingWorkspaceLauncherUsesProgressiveScreenPlacement),

View File

@ -254,7 +254,7 @@ internal static class ToolbarBrowserHost
var view=context.RequestServices.GetRequiredService<ICompositeViewEngine>().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<ITempDataProvider>()),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("<html data-theme='light'><head><meta name='viewport' content='width=device-width'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'></head><body class='writing-embedded'><main class='writing-context-page'>"+writer+"</main><script src='/js/intent-assessment.js'></script></body></html>");
context.Response.ContentType="text/html";await context.Response.WriteAsync("<html data-theme='light'><head><meta name='viewport' content='width=device-width'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-shell.css'><link rel='stylesheet' href='/css/writing-context-plots.css'></head><body class='app-layout writing-embedded'><main class='writing-context-page'>"+writer+"</main><script src='/js/intent-assessment.js'></script></body></html>");
});
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;
@ -268,6 +268,20 @@ internal static class ToolbarBrowserHost
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();
}
if(kind=="plots"&&context.Request.Query["contextCases"]=="true") {
var ids=new[]{22,900,23,47,1001,35,4,61,88};
var positions=ids.Select((id,i)=>new PlotLineWorkspaceAttributionRow{SceneID=id,BookID=12,NarrativeOrder=i*3+1,ChapterNumber=i<2?1:i<5?3:i<6?4:i<8?9:12,SceneNumber=i==2?2.5m:i+1,SceneTitle="Saved scene "+id}).ToArray();
var lines=Enumerable.Range(1,7).Select(i=>new PlotLineWorkspaceLineViewModel{Line=new(){PlotLineID=i,PlotLineName="Saved line "+i,Description=i==6?null:"Saved description "+i,Colour=i==1?"#ba5365":"#487b70"}}).ToArray();
PlotLineWorkspaceSceneMembershipViewModel Member(int line,params string[] titles)=>new(){PlotLineID=line,PlotLineName="Saved line "+line,Contributions=titles.Select((title,i)=>new PlotLineWorkspaceContributionRow{ThreadEventID=line*10+i,ThreadTitle="Saved thread "+line,CanonicalTitle=title,CanonicalDescription=title.Length>0?"Saved detail for "+title:null}).ToArray()};
model=new PlotLineWorkspaceViewModel{AssociationScenes=positions,PlotLines=lines,Scenes=[
new(){SceneID=22,Memberships=[Member(1,"Earlier active development"),Member(2,"Previous only")]},
new(){SceneID=900,Memberships=[Member(4,"Before both")]},
new(){SceneID=23,Memberships=[Member(1,"Current first","Current second"),Member(5),Member(7,"")]},
new(){SceneID=4,Memberships=[Member(1,"Upcoming active development")]},
new(){SceneID=61,Memberships=[Member(4,"After both")]},
new(){SceneID=88,Memberships=[Member(3,"Future only")]}
]};
}
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<ICompositeViewEngine>().GetView(null,"/Views/Writing/"+path+".cshtml",false);using var writer=new StringWriter();

View File

@ -59,7 +59,7 @@ internal static class WritingContextNavigationTests
var diagnosticJson=System.Text.Json.JsonSerializer.Serialize(diagnostics?.Value);
Check(diagnosticJson.Contains("Word reopened or changed"),"Reopened-session mapping is explained without reassigning paragraph identities");
var denied=NativeWorkflowTests.Proxy<PlotLine.Services.IProjectAccessService>((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.ContextPlotLines(7,12,null!,denied,null!) 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}]);

View File

@ -0,0 +1,41 @@
using Microsoft.AspNetCore.Mvc;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
using Microsoft.Extensions.Logging.Abstractions;
internal static class WritingContextPlotLinesTests
{
public static async Task Run()
{
var data=new PlotLineWorkspaceData {
PlotLines=[new(){PlotLineID=1,ProjectID=7,BookID=12,PlotLineName="Saved name",Description="Saved description"},new(){PlotLineID=2,ProjectID=7},new(){PlotLineID=3,ProjectID=7,BookID=13}],
AttributionScenes=[new(){SceneID=90,BookID=12,NarrativeOrder=20,ChapterNumber=3,SceneNumber=2},new(){SceneID=15,BookID=12,NarrativeOrder=10,ChapterNumber=1,SceneNumber=4},new(){SceneID=44,BookID=13,NarrativeOrder=1}],
Contributions=[new(){ThreadEventID=1,PlotLineID=1,SceneID=15,BookID=12,CanonicalTitle="Saved title",CanonicalDescription="Saved detail"},new(){ThreadEventID=2,PlotLineID=1,SceneID=15,BookID=12,CanonicalTitle="Second development"},new(){ThreadEventID=3,PlotLineID=3,SceneID=44,BookID=13}],
Threads=[new(){PlotLineID=2,IntroducedSceneID=90,PlannedResolutionSceneID=44}],
Targets=[new(){ThreadEventID=1,SourcePlotLineID=1,TargetPlotLineID=2}]
};
var model=WritingContextPlotLines.Build(data,7,12);
Check(model.AssociationScenes.Select(s=>s.SceneID).SequenceEqual([15,90]),"Use saved book manuscript order, never IDs or invented chapter sizes");
Check(model.PlotLines.Count==2&&model.PlotLines[0].Line.Description=="Saved description","Keep saved identities and exclude other-book lines");
var current=model.Scenes.Single(s=>s.SceneID==15);
Check(current.Memberships.Single(m=>m.PlotLineID==1).Contributions.Count==2,"Keep every canonical development in the same scene");
Check(current.Memberships.Single(m=>m.PlotLineID==1).Contributions[0].CanonicalDescription=="Saved detail","Do not replace saved prose with inferred context");
Check(current.Memberships.Single(m=>m.PlotLineID==2).Contributions.Count==0,"Cross-line targets remain associations without invented target developments");
Check(model.Scenes.Single(s=>s.SceneID==90).Memberships.Single().Contributions.Count==0,"Saved milestones remain visible without pretending they contain prose");
var reads=0;var allowed=false;
var repository=NativeWorkflowTests.Proxy<IPlotLineWorkspaceRepository>((n,a)=>{reads++;return Task.FromResult(data);});
var permissions=NativeWorkflowTests.Proxy<IProjectAccessService>((n,a)=>Task.FromResult(allowed));
var book= new Book{BookID=12,ProjectID=7};
var books=NativeWorkflowTests.Proxy<IBookRepository>((n,a)=>Task.FromResult<Book?>(book));
var controller=new WritingController(null!,null!,null!,null!,NullLogger<WritingController>.Instance);
Check(await controller.ContextPlotLines(7,12,repository,permissions,books) is NotFoundResult&&reads==0,"Unauthorised requests must not read saved plot data");
allowed=true;book.ProjectID=8;
Check(await controller.ContextPlotLines(7,12,repository,permissions,books) is NotFoundResult&&reads==0,"A book in another project must not leak saved developments");
book.ProjectID=7;
Check(await controller.ContextPlotLines(7,12,repository,permissions,books) is PartialViewResult{Model:PlotLineWorkspaceViewModel}&&reads==1,"One read-only book request; no workspace-wide health or second query");
}
static void Check(bool value,string message){if(!value)throw new Exception(message);}
}

View File

@ -225,12 +225,12 @@ public sealed class WritingController(
}
[HttpGet("Context/PlotLines")]
public async Task<IActionResult> ContextPlotLines(int projectId,int bookId,[FromServices] IPlotLineWorkspaceService plots,[FromServices] IProjectAccessService permissions)
public async Task<IActionResult> ContextPlotLines(int projectId,int bookId,[FromServices] IPlotLineWorkspaceRepository plots,[FromServices] IProjectAccessService permissions,[FromServices] IBookRepository books)
{
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);
var book=await books.GetAsync(bookId);if(book?.ProjectID!=projectId)return NotFound();
var data=await plots.GetAsync(projectId,bookId,null);
return PartialView("_WritingContextPlotLines",WritingContextPlotLines.Build(data,projectId,bookId));
}
[HttpGet("Context/Metrics")]
public async Task<IActionResult> ContextMetrics(int projectId,int bookId,[FromServices] ITimelineRepository timeline,[FromServices] IProjectAccessService permissions,[FromServices] IBookRepository books,[FromServices] ISceneRepository sceneMetrics)

View File

@ -0,0 +1,52 @@
using PlotLine.Models;
using PlotLine.ViewModels;
namespace PlotLine.Services;
// Read-only projection of the canonical workspace data, scoped to one book.
public static class WritingContextPlotLines
{
public static PlotLineWorkspaceViewModel Build(PlotLineWorkspaceData data, int projectId, int bookId)
{
var scenes = data.AttributionScenes.Where(s => s.BookID == bookId).OrderBy(s => s.NarrativeOrder).ToArray();
var sceneIds = scenes.Select(s => s.SceneID).ToHashSet();
var lines = data.PlotLines.Where(l => l.ProjectID == projectId && (l.BookID == null || l.BookID == bookId)).ToArray();
foreach (var line in lines) line.Colour = PlotLineColours.ForLine(line.PlotLineID, line.Colour);
var lineIds = lines.Select(l => l.PlotLineID).ToHashSet();
var events = data.Contributions.Where(c => c.BookID == bookId && sceneIds.Contains(c.SceneID) && lineIds.Contains(c.PlotLineID)).ToArray();
var memberships = events.GroupBy(c => c.SceneID).ToDictionary(g => g.Key,
g => PlotLineWorkspaceComposer.ComposeMemberships(data, g).ToDictionary(m => m.PlotLineID));
void Associate(int? sceneId, int lineId)
{
if (sceneId is not int id || !sceneIds.Contains(id) || !lineIds.Contains(lineId)) return;
if (!memberships.TryGetValue(id, out var byLine)) memberships[id] = byLine = [];
if (!byLine.ContainsKey(lineId))
{
var line = lines.First(l => l.PlotLineID == lineId);
byLine[lineId] = new() { PlotLineID = lineId, PlotLineName = line.PlotLineName, Colour = line.Colour };
}
}
// Saved thread milestones and cross-line targets are associations, not invented developments.
foreach (var thread in data.Threads)
{
Associate(thread.IntroducedSceneID, thread.PlotLineID);
Associate(thread.PlannedResolutionSceneID, thread.PlotLineID);
Associate(thread.ActualResolutionSceneID, thread.PlotLineID);
}
var eventScenes = events.ToDictionary(e => e.ThreadEventID, e => e.SceneID);
foreach (var target in data.Targets)
if (eventScenes.TryGetValue(target.ThreadEventID, out var scene)) Associate(scene, target.TargetPlotLineID);
return new()
{
Project = new() { ProjectID = projectId }, SelectedBookID = bookId,
AssociationScenes = scenes,
PlotLines = lines.Select(l => new PlotLineWorkspaceLineViewModel { Line = l }).ToArray(),
Scenes = scenes.Where(s => memberships.ContainsKey(s.SceneID)).Select(s => new PlotLineWorkspaceSceneViewModel
{
SceneID = s.SceneID, NarrativeOrder = s.NarrativeOrder, ChapterNumber = s.ChapterNumber,
SceneNumber = s.SceneNumber, SceneTitle = s.SceneTitle,
Memberships = memberships[s.SceneID].Values.ToArray()
}).ToArray()
};
}
}

View File

@ -5,6 +5,8 @@
ViewData["ProjectSection"] = "Writer";
}
<link rel="stylesheet" href="~/css/writing-context-plots.css" asp-append-version="true" />
<main class="writing-context-page"
data-follow-mode="@(ViewData["NativeSnapshot"] is true ? "snapshot" : "live")"
data-word-instance="@ViewData["WordInstance"]"
@ -35,6 +37,7 @@
<script src="~/js/writing-follow.js" asp-append-version="true"></script>
<script src="~/js/maps-engine.js" asp-append-version="true"></script>
<script src="~/js/writing-context-map.js" asp-append-version="true"></script>
<script src="~/js/writing-context-plots.js" asp-append-version="true"></script>
<script src="~/js/writing-context-components.js" asp-append-version="true"></script>
<script src="~/js/writing-context.js" asp-append-version="true"></script>
<script>

View File

@ -1,24 +1,41 @@
@model PlotLineWorkspaceViewModel
@using System.Text.Json
@{
var scenes=Model.AssociationScenes.OrderBy(s=>s.NarrativeOrder).ToArray();
var byScene=Model.Scenes.ToDictionary(s=>s.SceneID);
var scenes = Model.AssociationScenes.OrderBy(s => s.NarrativeOrder).ToArray();
var payload = new {
scenes = scenes.Select(s => new { id = s.SceneID, chapter = s.ChapterNumber, number = s.SceneNumber, title = s.SceneTitle }),
lines = Model.PlotLines.Select(l => new { id = l.Line.PlotLineID, name = l.Line.PlotLineName, description = l.Line.Description, colour = l.Line.Colour }),
memberships = Model.Scenes.SelectMany(s => s.Memberships.Select(m => new {
scene = s.SceneID, line = m.PlotLineID,
developments = m.Contributions.Select(c => new { id = c.ThreadEventID, thread = c.ThreadTitle, title = c.CanonicalTitle, detail = c.CanonicalDescription, role = c.CanonicalRole })
}))
};
}
<div data-writing-component-fragment data-context-story-chart="plots">
<button type="button" class="btn btn-link btn-sm float-end" data-context-refresh title="Read updated saved information; does not request AI">Refresh saved data</button>
<p class="text-muted small">Saved Plot Lines · Focus or Weave using the line filters. Scrubbing explores the story; only “Go to scene” requests Word navigation.</p>
@if(scenes.Length==0||Model.PlotLines.Count==0){<p>No saved plot-line developments are available for this book.</p>}
else{
<div class="writing-chart-controls"><button type="button" class="btn btn-sm btn-outline-secondary" data-context-center>Show current scene</button><label>Spacing <input type="range" min="28" max="120" value="64" data-context-spacing data-writing-view-state="plot-spacing" /></label></div>
<fieldset class="writing-plot-filters"><legend class="small">Plot Lines</legend>@foreach(var line in Model.PlotLines){<label><input type="checkbox" checked data-context-line-filter="@line.Line.PlotLineID" data-writing-view-state="plot-line-@line.Line.PlotLineID" /> @line.Line.PlotLineName</label>}</fieldset>
<div class="writing-story-scroll" tabindex="0" aria-label="Plot developments in manuscript order" data-writing-view-state="plot-scroll">
<div class="writing-story-chart" style="--scene-count:@scenes.Length" data-context-chart>
<div class="writing-current-marker" data-context-current-marker aria-hidden="true"></div>
<div class="writing-plot-row writing-plot-index"><strong>Manuscript</strong>@for(var i=0;i<scenes.Length;i++){var scene=scenes[i];<button type="button" data-context-explore="@i" data-context-chart-scene="@scene.SceneID" data-scene-index="@i" title="@scene.SceneTitle">@(scene.ChapterNumber.ToString("0.##")) / @(scene.SceneNumber.ToString("0.##"))</button>}</div>
@foreach(var line in Model.PlotLines){<div class="writing-plot-row" data-context-line="@line.Line.PlotLineID" style="--line-colour:@line.Line.Colour"><strong>@line.Line.PlotLineName</strong>@for(var i=0;i<scenes.Length;i++){var scene=scenes[i];var membership=byScene.GetValueOrDefault(scene.SceneID)?.Memberships.FirstOrDefault(m=>m.PlotLineID==line.Line.PlotLineID);<button type="button" data-context-explore="@i" class="@(membership!=null?"has-development":"")" title="@(membership!=null?string.Join(" · ",membership.Contributions.Select(c=>c.CanonicalTitle)):"No saved development")">@(membership!=null?"●":"·")</button>}</div>}
</div></div>
<label class="writing-scrubber">Explore scenes <input type="range" min="0" max="@(scenes.Length-1)" value="0" data-context-scrubber data-writing-view-state="plot-scrub" /></label>
<div class="writing-chart-evidence" data-context-exploration>
@for(var i=0;i<scenes.Length;i++){var scene=scenes[i];<article data-context-scene-card="@i" hidden="@(i!=0)"><h3 class="h5">@scene.SceneTitle</h3><p>Chapter @(scene.ChapterNumber.ToString("0.##")) · Scene @(scene.SceneNumber.ToString("0.##"))</p>@if(byScene.GetValueOrDefault(scene.SceneID) is {} detail){@foreach(var membership in detail.Memberships){<h4 class="h6">@membership.PlotLineName</h4><ul>@foreach(var contribution in membership.Contributions){<li>@contribution.ThreadTitle · @contribution.CanonicalTitle</li>}</ul>}}else{<p>No saved plot developments in this scene.</p>}<button type="button" class="btn btn-sm btn-outline-primary" data-context-go-scene="@scene.SceneID">Go to scene</button></article>}
</div>
}
<div data-writing-component-fragment data-context-plot-cards class="writing-plot-context">
<div class="writing-plot-toolbar">
<p>Plot line context for the current scene, showing the previous, current and next developments.</p>
<div class="writing-plot-categories" role="group" aria-label="Show plot lines">
<span>Show:</span>
<button type="button" class="btn btn-sm btn-outline-secondary" data-plot-category="active" aria-pressed="true">Active here <span data-plot-count="active">0</span></button>
<button type="button" class="btn btn-sm btn-outline-secondary" data-plot-category="nearby" aria-pressed="true">Nearby <span data-plot-count="nearby">0</span></button>
<button type="button" class="btn btn-sm btn-outline-secondary" data-plot-category="elsewhere" aria-pressed="false">Elsewhere <span data-plot-count="elsewhere">0</span></button>
<button type="button" class="btn btn-link btn-sm" data-plot-all>Show all</button>
</div>
</div>
@if (scenes.Length > 0)
{
<div class="writing-plot-explore">
<label>Explore scenes <input type="range" min="0" max="@(scenes.Length - 1)" value="0" data-plot-scrubber /></label>
<button type="button" class="btn btn-sm btn-outline-secondary" data-plot-return>Show current scene</button>
</div>
<div class="writing-plot-scene-nav" aria-label="Explore manuscript scenes">
<button type="button" class="btn btn-outline-secondary" data-plot-step="-1" aria-label="Previous scene">‹</button>
<div class="writing-plot-scene-strip" data-plot-scene-strip tabindex="0" aria-label="Nearby scenes in manuscript order"></div>
<button type="button" class="btn btn-outline-secondary" data-plot-step="1" aria-label="Next scene">›</button>
</div>
<div class="writing-plot-position"><p class="small text-muted" role="status" data-plot-position></p><button type="button" class="btn btn-sm btn-outline-primary" data-context-go-scene>Go to scene in Word</button></div>
}
<div data-plot-rows aria-label="Plot line developments"></div>
<button type="button" class="btn btn-link btn-sm" data-context-refresh title="Read updated saved information; does not request AI">Refresh saved data</button>
<script type="application/json" data-plot-context-data>@Html.Raw(JsonSerializer.Serialize(payload))</script>
</div>

View File

@ -0,0 +1,29 @@
/* Writing Context only: the shared application palette owns all UI colours. */
.writing-plot-context { color: var(--pd-text); min-width: 0; font-family:var(--pd-font-ui); }
.writing-plot-toolbar, .writing-plot-explore, .writing-plot-position { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:.75rem; margin-block:.75rem; }
.writing-plot-toolbar > p, .writing-plot-position > p { margin:0; }
.writing-plot-categories { display:flex; align-items:center; flex-wrap:wrap; gap:.4rem; }
.writing-context-page .writing-plot-context .writing-plot-categories button[aria-pressed="true"] { background:var(--pd-selected); border-color:var(--pd-accent); color:var(--pd-text); }
.writing-plot-explore > label { display:flex; align-items:center; gap:1rem; flex:1; min-width:12rem; }
.writing-plot-explore input { flex:1; min-width:4rem; }
.writing-plot-scene-nav { display:flex; gap:.5rem; align-items:stretch; }
.writing-plot-scene-strip { display:flex; overflow-x:auto; gap:.4rem; flex:1; min-width:0; position:relative; }
.writing-plot-scene-strip button { display:flex; flex:1 0 7rem; flex-direction:column; justify-content:center; gap:.2rem; padding:.55rem; white-space:normal; border-radius:var(--pd-radius); }
.writing-context-page .writing-plot-context .writing-plot-scene-strip button[aria-current="location"] { background:var(--pd-accent); border-color:var(--pd-accent); color:var(--pd-on-accent); flex-basis:12rem; }
.writing-plot-context-row { display:grid; grid-template-columns:minmax(12rem,1fr) repeat(3,minmax(0,1fr)); gap:.7rem; padding:.55rem; margin-block:.6rem; border:1px solid var(--pd-border); border-inline-start:7px solid var(--line-colour,var(--pd-border)); border-radius:var(--pd-radius); background:var(--pd-surface); }
.writing-plot-identity, .writing-plot-development { min-width:0; padding:.7rem; overflow-wrap:anywhere; }
.writing-plot-identity h3 { font-size:1rem; font-weight:700; margin:0 0 .4rem; }
.writing-plot-identity > p { font-size:.9rem; margin-bottom:.5rem; }
.writing-plot-status { display:inline-block; padding:.2rem .5rem; background:var(--pd-surface-2); border:1px solid var(--pd-border); border-radius:1rem; color:var(--pd-muted); }
.writing-plot-development { border:1px solid var(--pd-border); background:var(--pd-surface-2); border-radius:var(--pd-radius); }
.writing-plot-development.is-now { border-color:var(--pd-accent); background:var(--pd-selected); }
.writing-plot-development h4 { font-size:.75rem; font-weight:700; text-transform:uppercase; letter-spacing:.04em; margin:0 0 .4rem; }
.writing-plot-reference { font-weight:650; font-size:.9rem; }
.writing-plot-developments { list-style:none; margin:0; padding:0; }
.writing-plot-developments li + li { border-top:1px solid var(--pd-border); padding-top:.6rem; margin-top:.6rem; }
.writing-plot-developments p { margin-block:.3rem; }
.writing-plot-detail { white-space:pre-wrap; }
@media(max-width:1100px) { .writing-plot-context-row { grid-template-columns:repeat(3,minmax(0,1fr)); } .writing-plot-identity { grid-column:1/-1; } }
@media(max-width:700px) { .writing-plot-context-row { grid-template-columns:minmax(0,1fr); } .writing-plot-scene-nav { gap:.25rem; } .writing-plot-scene-strip button { flex-basis:6rem; } }
.writing-plot-context :is(h3,h4) { font-family:inherit; }
.writing-plot-context .btn { transition:none; }

View File

@ -3,6 +3,7 @@
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){
if(host.querySelector('[data-context-plot-cards]')){window.PlotDirectorContextPlots?.refresh(host);return;}
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);

View File

@ -0,0 +1,85 @@
// Read-only book projection. Exploring changes this view only; Word navigation stays explicit.
(() => {
'use strict';
const states=new WeakMap();
const node=(tag,text,cls)=>{const el=document.createElement(tag);if(text!==undefined)el.textContent=text;if(cls)el.className=cls;return el;};
const reference=scene=>`Ch ${scene.chapter} · Sc ${scene.number}`;
function nearest(entries,index){
let lo=0,hi=entries.length;
while(lo<hi){const mid=(lo+hi)>>1;if(entries[mid].index<index)lo=mid+1;else hi=mid;}
return {before:entries[lo-1],now:entries[lo]?.index===index?entries[lo]:null,after:entries[lo]?.index===index?entries[lo+1]:entries[lo]};
}
function mount(fragment){
const data=JSON.parse(fragment.querySelector('[data-plot-context-data]').textContent);
const indices=new Map(data.scenes.map((s,i)=>[s.id,i])),byLine=new Map(data.lines.map(l=>[l.id,{line:l,associations:new Set(),entries:[]}]));
for(const item of data.memberships){const line=byLine.get(item.line),index=indices.get(item.scene);if(!line||index===undefined)continue;line.associations.add(index);const developments=item.developments.filter(d=>d.title?.trim()||d.detail?.trim());if(developments.length)line.entries.push({index,developments});}
for(const line of byLine.values())line.entries.sort((a,b)=>a.index-b.index);
const state={fragment,data,indices,lines:[...byLine.values()],selected:null,current:null,filters:new Set(JSON.parse(fragment.closest('[data-writing-component]').dataset.plotCategories||'["active","nearby"]'))};states.set(fragment,state);
fragment.addEventListener('click',event=>{
const button=event.target.closest('button');if(!button)return;
if(button.hasAttribute('data-plot-category')){const key=button.dataset.plotCategory;if(state.filters.has(key))state.filters.delete(key);else state.filters.add(key);render(state);}
if(button.hasAttribute('data-plot-all')){state.filters=new Set(['active','nearby','elsewhere']);render(state);}
if(button.hasAttribute('data-plot-scene')){state.selected=Number(button.dataset.plotScene);render(state);}
if(button.hasAttribute('data-plot-step')){state.selected=Math.max(0,Math.min(data.scenes.length-1,state.selected+Number(button.dataset.plotStep)));render(state);}
if(button.hasAttribute('data-plot-return')){state.selected=state.current;render(state);window.dispatchEvent(new CustomEvent('plotdirector:word-return-to-current'));}
});
fragment.querySelector('[data-plot-scrubber]')?.addEventListener('input',event=>{state.selected=Number(event.target.value);render(state);});
return state;
}
function developmentCard(state,entry,label,cls,associated=false){
const card=node('section',undefined,'writing-plot-development '+cls);card.append(node('h4',label));
if(!entry){card.append(node('strong',label.startsWith('Now')?'No recorded development':label==='Before'?'No earlier recorded development':'No later recorded development'));
if(associated)card.append(node('p','Saved association with this scene; no development text is recorded.','small text-muted'));
return card;
}
const scene=state.data.scenes[entry.index];card.append(node('p',`${reference(scene)} — ${scene.title}`,'writing-plot-reference'));
if(label==='After')card.append(node('p','Upcoming in manuscript order','small text-muted'));
const list=node('ul',undefined,'writing-plot-developments');
for(const development of entry.developments){const item=node('li');if(development.thread)item.append(node('p',development.thread,'small text-muted'));
if(development.title)item.append(node('strong',development.title));
if(development.detail){const detail=node('p',development.detail,'writing-plot-detail');if(development.detail.length>240){item.append(node('p',development.detail.slice(0,240)+'…'));const more=node('details');more.append(node('summary','Full saved detail'),detail);item.append(more);}else item.append(detail);}
if(!development.title&&!development.detail)item.append(node('p',development.role||'Saved association; no development text recorded.'));
list.append(item);
}
card.append(list);return card;
}
function render(state){
const {fragment,data,selected,current}=state,scene=data.scenes[selected];
fragment.closest('[data-writing-component]').dataset.plotCategories=JSON.stringify([...state.filters]);
const counts={active:0,nearby:0,elsewhere:0};
const rows=state.lines.map(line=>{const context=nearest(line.entries,selected);const category=line.associations.has(selected)?'active':context.before||context.after?'nearby':'elsewhere';counts[category]++;return {...line,context,category};});
fragment.querySelectorAll('[data-plot-category]').forEach(b=>b.setAttribute('aria-pressed',String(state.filters.has(b.dataset.plotCategory))));
fragment.querySelectorAll('[data-plot-count]').forEach(n=>n.textContent=`(${counts[n.dataset.plotCount]})`);
if(scene){
const range=fragment.querySelector('[data-plot-scrubber]');range.value=selected;range.setAttribute('aria-valuetext',`${reference(scene)} — ${scene.title}`);
const status=fragment.querySelector('[data-plot-position]');status.textContent=`${selected===current?'Current scene':'Exploring'}: ${reference(scene)} — ${scene.title}${selected!==current&&data.scenes[current]?` · Word/current scene: ${reference(data.scenes[current])}`:''}`;
const go=fragment.querySelector('[data-context-go-scene]');go.dataset.contextGoScene=scene.id;
fragment.querySelectorAll('[data-plot-step]').forEach(b=>b.disabled=Number(b.dataset.plotStep)<0?selected===0:selected===data.scenes.length-1);
const strip=fragment.querySelector('[data-plot-scene-strip]'),focused=strip.contains(document.activeElement),buttons=[];
for(let i=Math.max(0,selected-3);i<=Math.min(data.scenes.length-1,selected+3);i++){
const s=data.scenes[i],button=node('button',undefined,'btn btn-outline-secondary');button.type='button';button.dataset.plotScene=i;button.setAttribute('aria-label',`${reference(s)} — ${s.title}`);if(i===selected)button.setAttribute('aria-current','location');button.append(node('span',reference(s)));if(i===selected)button.append(node('strong',s.title));buttons.push(button);
}
strip.replaceChildren(...buttons);if(focused)strip.querySelector('[aria-current]')?.focus({preventScroll:true});
const active=strip.querySelector('[aria-current]');if(active)strip.scrollLeft=Math.max(0,active.offsetLeft-strip.offsetLeft-(strip.clientWidth-active.clientWidth)/2);
}
const output=fragment.querySelector('[data-plot-rows]'),rendered=[];
for(const category of ['active','nearby','elsewhere'])for(const row of rows.filter(r=>r.category===category&&state.filters.has(category))){
const article=node('article',undefined,'writing-plot-context-row');article.dataset.plotLine=row.line.id;article.dataset.plotStatus=category;
// Validate the saved colour before using it as a CSS value; all prose uses textContent.
if(CSS.supports('color',row.line.colour))article.style.setProperty('--line-colour',row.line.colour);
const identity=node('div',undefined,'writing-plot-identity');identity.append(node('h3',row.line.name));if(row.line.description)identity.append(node('p',row.line.description));
let status=category==='active'?'Active here':category==='nearby'?'Nearby':'Elsewhere';
if(category==='nearby'){const distances=[];if(row.context.before)distances.push(`previous ${selected-row.context.before.index} scene${selected-row.context.before.index===1?'':'s'} ago`);if(row.context.after)distances.push(`next in ${row.context.after.index-selected} scene${row.context.after.index-selected===1?'':'s'}`);status+=` · ${distances.join(' · ')}`;}
identity.append(node('p',status,'writing-plot-status'));article.append(identity);
article.append(developmentCard(state,row.context.before,'Before','is-before'),developmentCard(state,row.context.now,'Now — This Scene','is-now',row.associations.has(selected)),developmentCard(state,row.context.after,'After','is-after'));
rendered.push(article);
}
if(!scene)output.replaceChildren(node('p',data.scenes.length?'Select a recognised scene to show plot line context.':'No manuscript scenes are available for this book.'));
else if(!rendered.length)output.replaceChildren(node('p',data.lines.length?'No plot lines in the selected categories. Use Show all to include every saved plot line.':'No saved plot lines are available for this book.'));
else output.replaceChildren(...rendered);
}
function refresh(host){const fragment=host.querySelector('[data-context-plot-cards]');if(!fragment)return;const state=states.get(fragment)||mount(fragment);const id=Number(host.closest('[data-writing-context]').querySelector('[data-writing-context-fragment]')?.dataset.sceneId),current=state.indices.get(id)??null;
if(current!==state.current||state.selected===null){state.current=current;state.selected=current;render(state);}
}
window.PlotDirectorContextPlots={refresh};
})();