`;
+ 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;
+
+ }
+
+