From e2d67948045640f50cd081ec823b834a98a47a0a Mon Sep 17 00:00:00 2001 From: Atlas Development Worker Date: Wed, 2 Dec 2026 15:26:20 +0000 Subject: [PATCH] Add editable Context Metrics panels and nearby Timeline curves --- .../Browser/context-metrics-acceptance.cjs | 65 +++++++++++ PlotLine.Tests/Browser/context-metrics.cjs | 44 ++++++++ .../Browser/timeline-metric-layout.cjs | 2 +- PlotLine.Tests/ContextMetricsTests.cs | 23 ++++ PlotLine.Tests/Program.cs | 2 + .../WritingContextNavigationTests.cs | 2 +- PlotLine/Controllers/WritingController.cs | 26 ++++- .../Services/Context/ContextMetricsFrame.cs | 2 + PlotLine/Services/CoreServices.cs | 3 +- PlotLine/Services/WritingContextMetrics.cs | 14 +++ PlotLine/Views/Shared/_Layout.cshtml | 1 + PlotLine/Views/Writing/Context.cshtml | 5 + PlotLine/Views/Writing/_ContextMetrics.cshtml | 36 ++++++ PlotLine/wwwroot/css/context-metrics.css | 8 ++ PlotLine/wwwroot/js/context-metrics.js | 103 ++++++++++++++++++ PlotLine/wwwroot/js/metric-curves.js | 49 +++++++++ PlotLine/wwwroot/js/site.js | 44 +------- 17 files changed, 379 insertions(+), 50 deletions(-) create mode 100644 PlotLine.Tests/Browser/context-metrics-acceptance.cjs create mode 100644 PlotLine.Tests/Browser/context-metrics.cjs create mode 100644 PlotLine.Tests/ContextMetricsTests.cs create mode 100644 PlotLine/Services/Context/ContextMetricsFrame.cs create mode 100644 PlotLine/Views/Writing/_ContextMetrics.cshtml create mode 100644 PlotLine/wwwroot/css/context-metrics.css create mode 100644 PlotLine/wwwroot/js/context-metrics.js create mode 100644 PlotLine/wwwroot/js/metric-curves.js diff --git a/PlotLine.Tests/Browser/context-metrics-acceptance.cjs b/PlotLine.Tests/Browser/context-metrics-acceptance.cjs new file mode 100644 index 00000000..032539eb --- /dev/null +++ b/PlotLine.Tests/Browser/context-metrics-acceptance.cjs @@ -0,0 +1,65 @@ +// Run through Tools/BrowserAcceptance/run.py against the committed Development release. +const {open}=require('./dev-acceptance.cjs'); +const assert=require('node:assert/strict'); +let session,stage='login'; +(async()=>{ + try{ + session=await open(); const project=await session.project(); + const book=await session.create('Books','?projectId='+project,{BookTitle:'Metrics acceptance',BookNumber:1}); + const chapters=[]; const scenes=[]; + for(let ch=1;ch<=2;ch++){ + stage='chapter fixture';const chapter=await session.create('Chapters','?bookId='+book,{ChapterTitle:'Metrics chapter '+ch,ChapterNumber:ch});chapters.push(chapter); + for(let n=1;n<=6;n++){ + stage='scene fixture'; await session.goto('/Scenes/Create?chapterId='+chapter); + await session.page.locator('#SceneTitle').fill(`Metric scene ${ch}.${n}`); + await session.page.getByRole('button',{name:'Create scene',exact:true}).click(); + await session.page.waitForURL('**/Scenes/Edit/*'); + scenes.push(Number(new URL(session.page.url()).pathname.split('/').pop())); + } + } + stage='metric fixture'; await session.goto('/ProjectMetrics/Index?projectId='+project); + const form=session.page.locator('form[action="/ProjectMetrics/Save"]'); + await form.locator('[name=MetricName]').fill('Acceptance zero scale'); + await form.locator('[name=MinValue]').fill('0');await form.locator('[name=MaxValue]').fill('10');await form.locator('[name=DefaultValue]').fill('5'); + await form.getByRole('button',{name:'Add Metric',exact:true}).click();await session.page.waitForURL(url=>url.pathname==='/ProjectMetrics'||url.pathname==='/ProjectMetrics/Index'); + const route='/Writing/Context?'+new URLSearchParams({projectId:project,bookId:book,sceneId:scenes[6]}); + await session.goto(route);let page=session.page; + let navigationWrites=0;page.on('request',r=>{if(/\/(Writing\/Context|WriterWord)\/Navigate/.test(new URL(r.url()).pathname))navigationWrites++;}); + const select=page.locator('[data-context-pane="0"] [data-context-tab]');await select.selectOption('metrics'); + const row=()=>page.locator('[data-context-pane="0"] [data-metric-row]').filter({hasText:'Acceptance zero scale'}); + await row().waitFor();const metricId=Number(await row().getAttribute('data-metric-row')); + assert.equal(await row().locator('output').innerText(),'Unset'); + const payload=await page.locator('[data-metrics-payload]').evaluate(el=>JSON.parse(el.textContent)); + assert.deepEqual(payload.scenes.map(s=>s.sceneId),scenes.slice(1)); + assert.equal(payload.metrics.find(m=>m.metricTypeId===metricId).points.length,0); + stage='keyboard save';await row().locator('input').focus();await page.keyboard.press('ArrowRight'); + await page.waitForFunction(id=>document.querySelector(`[data-metric-row="${id}"] input`).dataset.savedValue==='1',metricId); + stage='zero save';await row().locator('input').focus();await page.keyboard.press('Home'); + await page.waitForFunction(id=>document.querySelector(`[data-metric-row="${id}"] input`).dataset.savedValue==='0',metricId); + stage='reload';await page.reload();await row().waitFor();assert.equal(await row().locator('output').innerText(),'0'); + stage='pointer save';const range=row().locator('input');const box=await range.boundingBox(); + await page.mouse.move(box.x+box.width*.3,box.y+box.height/2);await page.mouse.down();await page.mouse.move(box.x+box.width*.7,box.y+box.height/2,{steps:4});await page.mouse.up(); + await page.waitForFunction(id=>Number(document.querySelector(`[data-metric-row="${id}"] input`).dataset.savedValue)>1,metricId); + const saved=Number(await row().locator('input').getAttribute('data-saved-value')); + stage='narrow layout';await page.setViewportSize({width:580,height:1000}); + const layout=await page.locator('[data-context-pane="0"] .context-metrics-panels').evaluate(el=>{const [a,b]=el.children;return {stacked:b.getBoundingClientRect().top>=a.getBoundingClientRect().bottom,overflow:el.scrollWidth>el.clientWidth+2};}); + assert(layout.stacked&&!layout.overflow); + await page.setViewportSize({width:1440,height:1000}); + stage='split panes';await page.locator('[data-context-layout]').selectOption('columns');await page.locator('[data-context-pane="1"] [data-context-tab]').selectOption('metrics'); + await page.locator('[data-context-pane="1"] [data-metric-slider]').first().waitFor(); + assert.equal(await page.locator('[data-context-pane="1"] [data-metric-row="'+metricId+'"] input').getAttribute('data-saved-value'),String(saved)); + stage='second window';const second=await page.context().newPage();await second.goto('https://dev.plotdirector.com'+route+'&contextWindow=12100000-0000-4000-8000-000000000001'); + await second.locator('[data-context-pane="0"] [data-context-tab]').selectOption('metrics');await second.locator('[data-metric-row="'+metricId+'"] input').waitFor(); + assert.equal(await second.locator('[data-metric-row="'+metricId+'"] input').getAttribute('data-saved-value'),String(saved));await second.close(); + assert.equal(navigationWrites,0); + stage='Timeline agreement';await session.goto('/Timeline?projectId='+project+'&bookId='+book); + const timeline=await page.locator('[data-metric-shape-chart] script[type="application/json"]').evaluate(el=>JSON.parse(el.textContent)); + assert.equal(timeline.metrics.find(m=>m.metricTypeId===metricId).points.find(p=>p.sceneId===scenes[6]).value,saved); + await session.close();session=await open();page=session.page; + stage='fresh login';await session.goto(route);await page.locator('[data-context-pane="0"] [data-context-tab]').selectOption('metrics'); + await page.locator('[data-context-pane="0"] [data-metric-row="'+metricId+'"] input').waitFor(); + assert.equal(await page.locator('[data-context-pane="0"] [data-metric-row="'+metricId+'"] input').getAttribute('data-saved-value'),String(saved)); + console.log(JSON.stringify({status:'passed',featureUrl:'https://dev.plotdirector.com'+route,checks:['cross-chapter eleven-scene window','unset versus saved zero','keyboard and pointer commits','reload and fresh-login persistence','Timeline agreement','narrow stacking','split panes','two windows','no Word navigation']})); + }catch{console.error('Context Metrics Development acceptance failed at '+stage+'; no credentials logged.');process.exitCode=1;} + finally{if(session){try{await session.cleanup();console.log('Disposable fixture cleanup confirmed');}finally{await session.close();}}} +})(); diff --git a/PlotLine.Tests/Browser/context-metrics.cjs b/PlotLine.Tests/Browser/context-metrics.cjs new file mode 100644 index 00000000..d053b336 --- /dev/null +++ b/PlotLine.Tests/Browser/context-metrics.cjs @@ -0,0 +1,44 @@ +// Focused interaction/race checks; live persistence is tested separately in Development. +const {chromium}=require('playwright'); +const fs=require('node:fs'); +const assert=require('node:assert/strict'); +(async()=>{ + const browser=await chromium.launch({headless:true}); + try { + const page=await browser.newPage(); let reject=false; const writes=[]; + await page.route('http://metrics.test/**',route=>{ + if(route.request().method()==='POST'){ + const body=route.request().postDataJSON(); writes.push(body); + return route.fulfill({status:reject?400:200,json:reject?{message:'Save rejected'}:{success:true,value:body.value}}); + } + return route.fulfill({contentType:'text/html',body:'
'}); + }); + await page.goto('http://metrics.test'); + await page.evaluate(()=>{window.Chart=class{constructor(c,config){window.chartConfig=config;}update(){}destroy(){window.destroyed=true;}};window.guards=[];document.addEventListener('context-panel-state',e=>guards.push(e.detail));}); + for(const file of ['metric-curves','context-metrics'])await page.addScriptTag({content:fs.readFileSync(`PlotLine/wwwroot/js/${file}.js`,'utf8')}); + await page.evaluate(()=>{ + document.querySelector('main').innerHTML=`

`; + PlotDirectorContextLifecycles.metrics.mount(document.querySelector('main>div')); + }); + assert.deepEqual(await page.evaluate(()=>chartConfig.data.datasets[0].data.map(p=>p.y)),[0,null]); + const input=page.locator('[type=range]'); + await input.focus(); await page.keyboard.press('ArrowRight'); + await page.waitForFunction(()=>document.querySelector('[data-metrics-status]').textContent==='Saved'); + assert.equal(writes[0].value,1); assert.equal(writes[0].sceneID,2); + reject=true; + await input.focus();await page.keyboard.press('ArrowRight'); + await page.waitForFunction(()=>document.querySelector('[data-metrics-error]').textContent==='Save rejected'); + assert.equal(await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.canRefresh(document.querySelector('main>div'))),false); + await page.locator('[data-metrics-cancel]').click(); + assert.equal(await input.inputValue(),'1'); + assert.equal(await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.canRefresh(document.querySelector('main>div'))),true); + // A pointer commit on the minimum must record zero even if the range value did not change. + reject=false; + await input.evaluate(el=>{el.value='0';el.dispatchEvent(new PointerEvent('pointerdown',{bubbles:true}));document.dispatchEvent(new PointerEvent('pointerup'));}); + await page.waitForFunction(()=>document.querySelector('[data-metrics-status]').textContent==='Saved'); + assert.equal(writes.at(-1).value,0); + await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.dispose(document.querySelector('main>div'))); + assert.equal(await page.evaluate(()=>destroyed),true); + console.log('PASS Context metric zero/unset, keyboard and pointer commit, failed save guard/discard and disposal'); + }finally{await browser.close();} +})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/Browser/timeline-metric-layout.cjs b/PlotLine.Tests/Browser/timeline-metric-layout.cjs index 2d3ae389..cb805f28 100644 --- a/PlotLine.Tests/Browser/timeline-metric-layout.cjs +++ b/PlotLine.Tests/Browser/timeline-metric-layout.cjs @@ -7,7 +7,7 @@ const assert = require('node:assert/strict'); const repo = path.resolve(__dirname, '../..'); const source = fs.readFileSync(path.join(repo, 'PlotLine/wwwroot/js/site.js'), 'utf8'); const start = source.indexOf('(() => {\n const chartRoots ='); -const chartScript = source.slice(start, source.indexOf('\n})();', start) + 6); +const chartScript = fs.readFileSync(path.join(repo, 'PlotLine/wwwroot/js/metric-curves.js'), 'utf8') + '\n' + source.slice(start, source.indexOf('\n})();', start) + 6); const css = fs.readFileSync(path.join(repo, 'PlotLine/wwwroot/css/site.css'), 'utf8'); const chartJs = path.join(path.dirname(require.resolve('chart.js')), 'chart.umd.js'); const settle = async page => { diff --git a/PlotLine.Tests/ContextMetricsTests.cs b/PlotLine.Tests/ContextMetricsTests.cs new file mode 100644 index 00000000..bbd598d2 --- /dev/null +++ b/PlotLine.Tests/ContextMetricsTests.cs @@ -0,0 +1,23 @@ +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; +internal static class ContextMetricsTests +{ + public static void Run() + { + var windowData = new TimelineData { Project = new(){ProjectID=1}, Books=[new(){BookID=12}], + Chapters=[new(){ChapterID=10,BookID=12,ChapterNumber=1},new(){ChapterID=11,BookID=12,ChapterNumber=2}], + Scenes=Enumerable.Range(1,16).Reverse().Select(i=>new Scene{SceneID=i,ChapterID=i<=8?10:11,SceneNumber=i<=8?i:i-8}).ToArray() }; + var window = WritingContextMetrics.BuildWindow(windowData, [new(){SceneID=9,MetricTypeID=1,Value=0}], + [new(){MetricTypeID=1,MetricName="Recorded",IsActive=true,IsEnabledForProject=true,MinValue=0,MaxValue=10}, + new(){MetricTypeID=2,MetricName="Empty",IsActive=true,IsEnabledForProject=true,MinValue=-5,MaxValue=5}],9); + Check(window.OrderedScenes.Select(s=>s.SceneID).SequenceEqual(Enumerable.Range(4,11)),"Metric window crosses chapters in manuscript order with five neighbours on each side"); + Check(window.MetricGraphs.Count==2&&window.MetricGraphs.Single(m=>m.MetricTypeID==2).Points.Count==0,"Enabled metrics without any recorded values still have controls"); + Check(window.MetricGraphs.Single(m=>m.MetricTypeID==1).Points.Single().Value==0,"Window retains recorded zero"); + + var start = WritingContextMetrics.BuildWindow(windowData, [], [], 1); + Check(start.OrderedScenes.Select(s=>s.SceneID).SequenceEqual(Enumerable.Range(1,6)),"First scene window does not invent predecessors"); + Check(WritingContextMetrics.BuildWindow(windowData, [], [], 999).OrderedScenes.Count==0,"Missing current scene has no fabricated window"); + } + private static void Check(bool ok,string message){if(!ok)throw new Exception(message);Console.WriteLine("PASS "+message);} +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 044767b7..08ebf8d1 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -15,6 +15,7 @@ using PlotLine.Models; using PlotLine.Services; using PlotLine.ViewModels; +if(args.Contains("--context-metrics")){ContextMetricsTests.Run();return;} if(args.Contains("--scene-creation")){await SceneCreationTests.Run();return;} if(args.Contains("--help-visibility")){HelpVisibilityTests.Run();return;} if(args.Contains("--context-intent-text")){ContextIntentTextTests.Run();Console.WriteLine("PASS Context Intent paste preview, identity deduplication and deterministic passage matching");return;} @@ -240,6 +241,7 @@ var tests = new (string Name, Action Test)[] ("Context Family/Story projection and bounded reads",()=>ContextRelationshipLensTests.Run().GetAwaiter().GetResult()), ("Context Names Library query parity and bounded identities",()=>ContextNamesTests.Run().GetAwaiter().GetResult()), ("Context relationship state and focused editing",()=>ContextRelationshipTests.Run().GetAwaiter().GetResult()), + ("Context Metrics window and recorded values",ContextMetricsTests.Run), ("Context Threads narrative history and scope",ContextThreadsTests.Run), ("Context character narrative projection and focused editing",()=>ContextCharacterTests.Run().GetAwaiter().GetResult()), ("Context Intent deterministic text preparation",ContextIntentTextTests.Run), diff --git a/PlotLine.Tests/WritingContextNavigationTests.cs b/PlotLine.Tests/WritingContextNavigationTests.cs index 0b4ec29f..fef3dbe2 100644 --- a/PlotLine.Tests/WritingContextNavigationTests.cs +++ b/PlotLine.Tests/WritingContextNavigationTests.cs @@ -60,7 +60,7 @@ internal static class WritingContextNavigationTests Check(diagnosticJson.Contains("Word reopened or changed"),"Reopened-session mapping is explained without reassigning paragraph identities"); var denied=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(false)); 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.ContextMetrics(7,12,23,null,null,null,null!,null!,null!,denied,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"); diff --git a/PlotLine/Controllers/WritingController.cs b/PlotLine/Controllers/WritingController.cs index f0e72cb3..3ba53341 100644 --- a/PlotLine/Controllers/WritingController.cs +++ b/PlotLine/Controllers/WritingController.cs @@ -300,12 +300,28 @@ public sealed class WritingController( return PartialView("_WritingContextPlotLines",WritingContextPlotLines.Build(data,projectId,bookId)); } [HttpGet("Context/Metrics")] - public async Task ContextMetrics(int projectId,int bookId,[FromServices] ITimelineRepository timeline,[FromServices] IProjectAccessService permissions,[FromServices] IBookRepository books,[FromServices] ISceneRepository sceneMetrics) + public async Task ContextMetrics(int projectId, int bookId, int sceneId, int? chapterId, + Guid? instanceId, Guid? sessionId, [FromServices] ITimelineRepository timeline, + [FromServices] ISceneRepository scenes, [FromServices] ISceneMetricTypeRepository metrics, + [FromServices] IProjectAccessService permissions, + [FromServices] PlotLine.Services.Context.ContextSpatial spatial) { - 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)); + if (!ModelState.IsValid || InvalidNativeSelection(instanceId, sessionId)) return BadRequest(); + if (!await permissions.CanAccessProjectAsync(projectId)) return NotFound(); + var native = instanceId.HasValue ? await NativeTarget(bookId, instanceId, sessionId) : null; + if (instanceId.HasValue && (native == null || native.SceneId != sceneId || chapterId.HasValue && native.ChapterId != chapterId)) return Conflict(); + try + { + var scope = await spatial.Scope(bookId, sceneId); + if (scope.ProjectID != projectId || chapterId.HasValue && scope.ChapterID != chapterId) return BadRequest(); + var data = await timeline.GetByProjectAsync(projectId, bookId, false, [], false); + var recorded = await scenes.ListRecordedMetricsByBookAsync(bookId, int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)); + var types = await metrics.ListForManagementAsync(projectId); + if (instanceId.HasValue && !SameNativeTarget(native, await NativeTarget(bookId, instanceId, sessionId))) return Conflict(); + return PartialView("_ContextMetrics", new PlotLine.Services.Context.ContextMetricsFrame(scope, + WritingContextMetrics.BuildWindow(data, recorded, types, sceneId))); + } + catch (Microsoft.Data.SqlClient.SqlException e) when (e.Number == 51010) { return Forbid(); } } private async Task> ContextSceneOptions(SceneEditViewModel scene,StoryPointViewModel? narrative=null) diff --git a/PlotLine/Services/Context/ContextMetricsFrame.cs b/PlotLine/Services/Context/ContextMetricsFrame.cs new file mode 100644 index 00000000..feece5d4 --- /dev/null +++ b/PlotLine/Services/Context/ContextMetricsFrame.cs @@ -0,0 +1,2 @@ +namespace PlotLine.Services.Context; +public sealed record ContextMetricsFrame(SpatialScope Scope, PlotLine.ViewModels.TimelineViewModel Timeline); diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index f91ccd63..2e288323 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -5759,7 +5759,7 @@ public sealed class SceneMetricValueService( ISceneRepository scenes, IChapterRepository chapters, IBookRepository books, - ISceneMetricTypeRepository metricTypes) : ISceneMetricValueService + ISceneMetricTypeRepository metricTypes, ContextSavedData? savedData = null) : ISceneMetricValueService { public async Task UpdateSceneMetricValueAsync(SceneMetricValueUpdateViewModel model) { @@ -5790,6 +5790,7 @@ public sealed class SceneMetricValueService( var value = Math.Clamp(model.Value, metric.MinValue, metric.MaxValue); await scenes.SaveMetricValueAsync(model.SceneID, metricTypeId, value); + if (savedData != null) await savedData.Scene(model.SceneID, "metrics"); return value; } } diff --git a/PlotLine/Services/WritingContextMetrics.cs b/PlotLine/Services/WritingContextMetrics.cs index 9136278c..0abffd5f 100644 --- a/PlotLine/Services/WritingContextMetrics.cs +++ b/PlotLine/Services/WritingContextMetrics.cs @@ -14,4 +14,18 @@ public static class WritingContextMetrics Points=group.Select(p=>new MetricGraphPointViewModel{SceneID=p.SceneID,SceneNumber=byId[p.SceneID].SceneNumber,SceneTitle=byId[p.SceneID].SceneTitle,Value=p.Value}).ToArray()}; }).ToArray()}; } + public static TimelineViewModel BuildWindow(TimelineData data, IReadOnlyList recorded, + IReadOnlyList types, int sceneId) + { + var model = Build(data, recorded); + var ordered = model.OrderedScenes.ToArray(); + var index = Array.FindIndex(ordered, s => s.SceneID == sceneId); + model.OrderedScenes = index < 0 ? [] : ordered.Skip(Math.Max(0, index - 5)).Take(Math.Min(ordered.Length, index + 6) - Math.Max(0, index - 5)).ToArray(); + var ids = model.OrderedScenes.Select(s => s.SceneID).ToHashSet(); + model.MetricGraphs = types.Where(t => t.IsActive && t.IsEnabledForProject).OrderBy(t => t.SortOrder).ThenBy(t => t.MetricName) + .Select(t => new MetricGraphViewModel { MetricTypeID = t.MetricTypeID, MetricName = t.MetricName, + MinValue = t.MinValue, MaxValue = t.MaxValue, + Points = model.MetricGraphs.FirstOrDefault(g => g.MetricTypeID == t.MetricTypeID)?.Points.Where(p => ids.Contains(p.SceneID)).ToArray() ?? [] }).ToArray(); + return model; + } } diff --git a/PlotLine/Views/Shared/_Layout.cshtml b/PlotLine/Views/Shared/_Layout.cshtml index 1b6703bc..84391f7b 100644 --- a/PlotLine/Views/Shared/_Layout.cshtml +++ b/PlotLine/Views/Shared/_Layout.cshtml @@ -356,6 +356,7 @@ + @if (User.Identity?.IsAuthenticated == true) diff --git a/PlotLine/Views/Writing/Context.cshtml b/PlotLine/Views/Writing/Context.cshtml index 1286e22b..0ca2cc31 100644 --- a/PlotLine/Views/Writing/Context.cshtml +++ b/PlotLine/Views/Writing/Context.cshtml @@ -5,6 +5,7 @@ ViewData["Title"] = "Context"; var position = Model.Display?.Context?.Position; var tabs = new[] { + new { id = "metrics", displayName = "Metrics", endpoint = Url.Action("ContextMetrics", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "metrics", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty() }, new { id = "threads", displayName = "Threads", endpoint = Url.Action("ContextThreadsTab", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "threads", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty() }, new { id = "overview", displayName = "Overview", endpoint = Url.Action("ContextScene", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "reference", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "scene.focus" } }, new { id = "characters", displayName = "Characters in Scene", endpoint = Url.Action("ContextCharacters", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "characters", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "character.focus" } }, @@ -19,6 +20,7 @@ +
+ + + diff --git a/PlotLine/Views/Writing/_ContextMetrics.cshtml b/PlotLine/Views/Writing/_ContextMetrics.cshtml new file mode 100644 index 00000000..67ed3865 --- /dev/null +++ b/PlotLine/Views/Writing/_ContextMetrics.cshtml @@ -0,0 +1,36 @@ +@model PlotLine.Services.Context.ContextMetricsFrame +@using System.Text.Json +@{ Layout = null; + var scope = Model.Scope; + var timeline = Model.Timeline; + var scenes = timeline.OrderedScenes.ToArray(); + var payload = new { + scenes = scenes.Select(s => new { sceneId=s.SceneID, axisLabel=$"Ch {timeline.ChapterOptions.FirstOrDefault(c=>c.Value==s.ChapterID.ToString())?.Text.Split('·')[0].Trim()}.{s.SceneNumber:g}", sceneTitle=s.SceneTitle }), + metrics = timeline.MetricGraphs.Select(m=>new { metricTypeId=m.MetricTypeID, metricName=m.MetricName, minValue=m.MinValue, maxValue=m.MaxValue, points=m.Points.Select(p=>new {sceneId=p.SceneID,value=p.Value}) }) + }; +} +
+

Metrics · @scope.Label

+ +

Current scene and up to five scenes either side in manuscript order. Unset values are gaps. Adjust a slider to preview; release or finish a keyboard adjustment to save.

+ @if (!timeline.MetricGraphs.Any()) {

No active metrics are enabled for this project.

} + else { +
+

Timeline curves

+

Current scene

+ @foreach(var metric in timeline.MetricGraphs) { + var value=metric.Points.FirstOrDefault(p=>p.SceneID==scope.SceneID)?.Value; + + } +
+
+

+ + + + + } +
diff --git a/PlotLine/wwwroot/css/context-metrics.css b/PlotLine/wwwroot/css/context-metrics.css new file mode 100644 index 00000000..81b12b0b --- /dev/null +++ b/PlotLine/wwwroot/css/context-metrics.css @@ -0,0 +1,8 @@ +.context-metrics-panels{display:flex;gap:1rem;align-items:stretch;flex-wrap:wrap} +.context-metrics-curve,.context-metrics-controls{border:1px solid var(--bs-border-color);border-radius:.4rem;padding:.75rem;overflow:auto;resize:both;min-width:250px;max-width:100%;min-height:240px} +.context-metrics-curve{flex:2 1 auto;width:60%}.context-metrics-controls{flex:1 1 auto;width:30%} +.context-metrics-canvas{position:relative;height:280px;min-width:230px} +.context-metric-control{display:grid;grid-template-columns:1fr auto;gap:.3rem;margin-bottom:.75rem} +.context-metric-control input{grid-column:1/-1;width:100%;accent-color:var(--metric-colour)} +.context-metric-control output{font-variant-numeric:tabular-nums}.context-metric-control small{grid-column:1/-1;color:var(--bs-secondary-color)} +@media(max-width:650px){.context-metrics-curve,.context-metrics-controls{width:100%;min-width:0;flex-basis:100%;resize:vertical}} diff --git a/PlotLine/wwwroot/js/context-metrics.js b/PlotLine/wwwroot/js/context-metrics.js new file mode 100644 index 00000000..543067e1 --- /dev/null +++ b/PlotLine/wwwroot/js/context-metrics.js @@ -0,0 +1,103 @@ +(() => { + 'use strict'; + const instances = new WeakMap(); + function mount(node) { + if (instances.has(node)) return; + const script = node.querySelector('[data-metrics-payload]'); + if (!script) return; + const payload = JSON.parse(script.textContent), sceneId = Number(node.dataset.sceneId); + const index = payload.scenes.findIndex(s => s.sceneId === sceneId); + const error = node.querySelector('[data-metrics-error]'), status = node.querySelector('[data-metrics-status]'); + const retry = node.querySelector('[data-metrics-retry]'), cancel = node.querySelector('[data-metrics-cancel]'); + const sliders = [...node.querySelectorAll('[data-metric-slider]')]; + const abort = new AbortController(); + let chart, dirty = null, busy = false, alive = true, pointing = false; + // Cached fragments can be remounted after a successful edit before a server refresh. + for (const input of sliders) { + const metric = payload.metrics.find(m => m.metricTypeId === Number(input.dataset.metricSlider)); + metric.points = metric.points.filter(p => p.sceneId !== sceneId); + if (input.dataset.savedValue !== '') metric.points.push({ sceneId, value: Number(input.dataset.savedValue) }); + } + const datasets = window.PlotDirectorMetricCurves.datasets(node, payload); + datasets.forEach(d => { d.spanGaps = false; }); + const guard = () => node.dispatchEvent(new CustomEvent('context-panel-state', { bubbles: true, detail: { dirty: !!dirty, busy, deferRefresh: !!dirty || busy } })); + function display(input, value, preview = false) { + const text = value == null ? 'Unset' : `${value}${preview ? ' · preview' : ''}`; + input.closest('label').querySelector('output').textContent = text; + input.setAttribute('aria-valuetext', text); + const dataset = datasets.find(d => d.metricTypeId === Number(input.dataset.metricSlider)); + dataset.data[index].y = value; + chart?.update('none'); + } + function preview(input) { + if (busy || dirty && dirty !== input) return; + dirty = input; guard(); error.textContent = ''; status.textContent = 'Preview · not saved'; + cancel.hidden = false; retry.hidden = true; + sliders.forEach(s => { if (s !== input) s.disabled = true; }); + display(input, Number(input.value), true); + } + async function save() { + if (!dirty || busy) return; + const input = dirty; + busy = true; guard(); sliders.forEach(s => s.disabled = true); retry.hidden = cancel.hidden = true; + status.textContent = 'Saving…'; error.textContent = ''; + try { + const response = await fetch('/SceneMetrics/UpdateSceneMetricValue', { + method: 'POST', headers: { 'Content-Type': 'application/json', 'RequestVerificationToken': node.querySelector('[name="__RequestVerificationToken"]').value }, + body: JSON.stringify({ sceneID: sceneId, metricTypeID: Number(input.dataset.metricSlider), value: Number(input.value) }) + }); + const result = await response.json().catch(() => null); + if (!response.ok || response.redirected || !result?.success) throw Error(result?.message || 'Save could not be confirmed. Check saved data before retrying.'); + if (!alive) return; + input.dataset.savedValue = String(result.value); input.value = result.value; + display(input, result.value); dirty = null; status.textContent = 'Saved'; + window.PlotDirector?.toast?.success('Metric saved.'); + } catch (e) { + if (!alive) return; + error.textContent = e.message; status.textContent = 'Preview retained · save not confirmed'; retry.hidden = cancel.hidden = false; + window.PlotDirector?.toast?.error(e.message); + } finally { + busy = false; + if (alive) { sliders.forEach(s => s.disabled = !!dirty && dirty !== s); guard(); } + } + } + if (window.Chart) { + chart = new Chart(node.querySelector('canvas'), { + type: 'line', data: { datasets }, + options: { responsive: true, maintainAspectRatio: false, animation: false, + scales: { x: { type: 'linear', min: 0, max: payload.scenes.length, ticks: { stepSize: .5, callback: v => payload.scenes[v - .5]?.axisLabel || '' } }, + y: { min: Math.min(1, ...payload.metrics.map(m => m.minValue)), max: Math.max(10, ...payload.metrics.map(m => m.maxValue)), ticks: { stepSize: 1 } } }, + plugins: { tooltip: { callbacks: { title: items => payload.scenes[Math.floor(items[0].parsed.x)]?.sceneTitle || '' } } } + }, + plugins: [{ id: 'contextCurrentScene', beforeDatasetsDraw(c) { + const {ctx, chartArea, scales} = c; + ctx.save(); ctx.fillStyle = getComputedStyle(node).getPropertyValue('--pd-data-1').trim() || '#2f6f63'; ctx.globalAlpha = .12; + ctx.fillRect(scales.x.getPixelForValue(index), chartArea.top, scales.x.getPixelForValue(index + 1) - scales.x.getPixelForValue(index), chartArea.height); ctx.restore(); + } }] + }); + } else error.textContent = 'Chart unavailable. Saved metric controls remain available.'; + sliders.forEach((input, i) => { + input.closest('label').style.setProperty('--metric-colour', window.PlotDirectorMetricCurves.colour(node, i)); + input.addEventListener('pointerdown', () => { pointing = true; preview(input); }, { signal: abort.signal }); + input.addEventListener('input', () => preview(input), { signal: abort.signal }); + input.addEventListener('change', () => { if (!pointing) void save(); }, { signal: abort.signal }); + input.addEventListener('blur', () => { if (!pointing && dirty === input) void save(); }, { signal: abort.signal }); + }); + document.addEventListener('pointerup', () => { if (pointing) { pointing = false; void save(); } }, { signal: abort.signal }); + document.addEventListener('pointercancel', () => { pointing = false; }, { signal: abort.signal }); + retry.addEventListener('click', save, { signal: abort.signal }); + cancel.addEventListener('click', () => { + if (!dirty || busy) return; + const input = dirty, value = input.dataset.savedValue === '' ? null : Number(input.dataset.savedValue); + input.value = value ?? input.min; display(input, value); dirty = null; + sliders.forEach(s => s.disabled = false); retry.hidden = cancel.hidden = true; error.textContent = ''; status.textContent = ''; guard(); + }, { signal: abort.signal }); + const theme = new MutationObserver(() => { datasets.forEach((d, i) => { d.borderColor = d.backgroundColor = d.pointBackgroundColor = window.PlotDirectorMetricCurves.colour(node, i); }); chart?.update('none'); }); + theme.observe(document.documentElement, {attributes: true, attributeFilter: ['data-theme', 'data-bs-theme', 'data-app-theme']}); + instances.set(node, { guarded: () => !!dirty || busy, dispose() { alive = false; abort.abort(); theme.disconnect(); chart?.destroy(); } }); + } + window.PlotDirectorContextLifecycles = { ...(window.PlotDirectorContextLifecycles || {}), metrics: { + mount, canRefresh: node => !instances.get(node)?.guarded(), + dispose(node) { instances.get(node)?.dispose(); instances.delete(node); } + } }; +})(); diff --git a/PlotLine/wwwroot/js/metric-curves.js b/PlotLine/wwwroot/js/metric-curves.js new file mode 100644 index 00000000..0e7a1552 --- /dev/null +++ b/PlotLine/wwwroot/js/metric-curves.js @@ -0,0 +1,49 @@ +// Canonical Timeline curve presentation, also used by Context Metrics. +(() => { + const colours = [ + "#2f6f63", + "#b35f3b", + "#6750a4", + "#c58b2b", + "#7d3f52", + "#33759b", + "#9c4d8f", + "#a33d3d", + "#6f8f3d", + "#d08a2f", + "#444b57" + ]; + const colour = (root, index) => getComputedStyle(root).getPropertyValue(`--pd-data-${index % colours.length + 1}`).trim() || colours[index % colours.length]; + function datasets(root, payload, defaults) { + const seriesColour = index => colour(root, index); + const defaultMetrics = defaults || new Set(payload.metrics.map(m => m.metricName)); + return payload.metrics.map((metric, metricIndex) => { + const pointMap = new Map(metric.points.map((point) => [point.sceneId, point.value])); + const colour = seriesColour(metricIndex); + return { + label: metric.metricName, + metricTypeId: metric.metricTypeId, + minValue: Number.isFinite(metric.minValue) ? metric.minValue : 1, + maxValue: Number.isFinite(metric.maxValue) ? metric.maxValue : 10, + data: payload.scenes.map((scene, columnIndex) => { + const value = pointMap.get(scene.sceneId); + return value == null + ? { x: columnIndex + 0.5, y: null, sceneId: scene.sceneId } + : { x: columnIndex + 0.5, y: value, sceneId: scene.sceneId }; + }), + borderColor: colour, + backgroundColor: colour, + pointBackgroundColor: colour, + pointBorderColor: "#fff", + pointBorderWidth: 1.5, + pointRadius: 3, + pointHoverRadius: 5, + borderWidth: 2, + tension: 0.35, + spanGaps: true, + hidden: !defaultMetrics.has(metric.metricName) + }; + }); + } + window.PlotDirectorMetricCurves = { colour, datasets }; +})(); diff --git a/PlotLine/wwwroot/js/site.js b/PlotLine/wwwroot/js/site.js index 9e55c76f..85b1fd94 100644 --- a/PlotLine/wwwroot/js/site.js +++ b/PlotLine/wwwroot/js/site.js @@ -491,20 +491,6 @@ return; } - const legacyColours = [ - "#2f6f63", - "#b35f3b", - "#6750a4", - "#c58b2b", - "#7d3f52", - "#33759b", - "#9c4d8f", - "#a33d3d", - "#6f8f3d", - "#d08a2f", - "#444b57" - ]; - const globalDefaultMetrics = new Set(["Overall Intensity", "Tension", "Emotional Weight", "Action"]); const metricCharts = []; const maxMetricCanvasDimension = 30000; @@ -665,37 +651,11 @@ } const defaultMetrics = new Set(payload.defaultMetrics?.length ? payload.defaultMetrics : globalDefaultMetrics); const chartTokens = () => getComputedStyle(root); - const seriesColour = index => chartTokens().getPropertyValue(`--pd-data-${index % legacyColours.length + 1}`).trim() || legacyColours[index % legacyColours.length]; + const seriesColour = index => window.PlotDirectorMetricCurves.colour(root, index); const columnCount = payload.scenes.length; root.dataset.sceneCount = String(columnCount); const tickLabelInterval = columnCount > 80 ? 10 : columnCount > 40 ? 5 : columnCount > 24 ? 4 : columnCount > 14 ? 2 : 1; - const datasets = payload.metrics.map((metric, metricIndex) => { - const pointMap = new Map(metric.points.map((point) => [point.sceneId, point.value])); - const colour = seriesColour(metricIndex); - return { - label: metric.metricName, - metricTypeId: metric.metricTypeId, - minValue: Number.isFinite(metric.minValue) ? metric.minValue : 1, - maxValue: Number.isFinite(metric.maxValue) ? metric.maxValue : 10, - data: payload.scenes.map((scene, columnIndex) => { - const value = pointMap.get(scene.sceneId); - return value == null - ? { x: columnIndex + 0.5, y: null, sceneId: scene.sceneId } - : { x: columnIndex + 0.5, y: value, sceneId: scene.sceneId }; - }), - borderColor: colour, - backgroundColor: colour, - pointBackgroundColor: colour, - pointBorderColor: "#fff", - pointBorderWidth: 1.5, - pointRadius: 3, - pointHoverRadius: 5, - borderWidth: 2, - tension: 0.35, - spanGaps: true, - hidden: !defaultMetrics.has(metric.metricName) - }; - }); + const datasets = window.PlotDirectorMetricCurves.datasets(root, payload, defaultMetrics); let activeMetricDrag = null; let suppressMetricClick = false;