Add editable Context Metrics panels and nearby Timeline curves

This commit is contained in:
Atlas Development Worker 2026-12-02 15:26:20 +00:00
parent a83aaf6723
commit e2d6794804
17 changed files with 379 additions and 50 deletions

View File

@ -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();}}}
})();

View File

@ -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:'<html><body><main></main></body></html>'});
});
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=`<div data-scene-id="2"><input name="__RequestVerificationToken" value="fixture"><canvas></canvas><label><output>Unset</output><input type="range" min="0" max="10" value="0" data-metric-slider="1" data-saved-value=""></label><p data-metrics-error></p><p data-metrics-status></p><button data-metrics-retry hidden>Retry</button><button data-metrics-cancel hidden>Cancel</button><script type="application/json" data-metrics-payload>{"scenes":[{"sceneId":1},{"sceneId":2}],"metrics":[{"metricTypeId":1,"metricName":"Test","minValue":0,"maxValue":10,"points":[{"sceneId":1,"value":0}]}]}</script></div>`;
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;});

View File

@ -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 => {

View File

@ -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);}
}

View File

@ -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),

View File

@ -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<PlotLine.Services.IProjectAccessService>((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");

View File

@ -300,12 +300,28 @@ public sealed class WritingController(
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)
public async Task<IActionResult> 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<IReadOnlyList<SelectListItem>> ContextSceneOptions(SceneEditViewModel scene,StoryPointViewModel? narrative=null)

View File

@ -0,0 +1,2 @@
namespace PlotLine.Services.Context;
public sealed record ContextMetricsFrame(SpatialScope Scope, PlotLine.ViewModels.TimelineViewModel Timeline);

View File

@ -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<int> 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;
}
}

View File

@ -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<SceneMetricValue> recorded,
IReadOnlyList<SceneMetricType> 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;
}
}

View File

@ -356,6 +356,7 @@
<script src="~/js/application-dialogs.js" asp-append-version="true"></script>
<script src="~/js/workspace-bridge.js" asp-append-version="true"></script>
<script src="~/js/context-panels.js" asp-append-version="true"></script>
<script src="~/js/metric-curves.js" asp-append-version="true"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<script src="~/js/ai-actions.js" asp-append-version="true"></script>
@if (User.Identity?.IsAuthenticated == true)

View File

@ -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<string>() },
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<string>() },
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 @@
<link rel="stylesheet" href="~/css/context-workspace.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/location-picker.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/context-calendar.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/context-metrics.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/context-spatial.css" asp-append-version="true" />
<main class="context-workspace" data-context-workspace data-user="@User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value"
data-scope-project-id="@Model.ProjectID" data-scope-book-id="@Model.BookID"
@ -71,6 +73,9 @@
<script src="~/js/location-picker.js" asp-append-version="true"></script>
<script src="~/js/location-types.js" asp-append-version="true"></script>
<script src="~/js/floor-plan-renderer.js" asp-append-version="true"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.9/dist/chart.umd.min.js"></script>
<script src="~/js/metric-curves.js" asp-append-version="true"></script>
<script src="~/js/context-metrics.js" asp-append-version="true"></script>
<script src="~/js/context-threads.js" asp-append-version="true"></script>
<script src="~/js/context-spatial.js" asp-append-version="true"></script>
<script src="~/js/context-calendar-model.js" asp-append-version="true"></script>

View File

@ -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}) })
};
}
<div data-context-tab-fragment data-context-metrics data-project-id="@scope.ProjectID" data-book-id="@scope.BookID" data-chapter-id="@scope.ChapterID" data-scene-id="@scope.SceneID">
<h2 class="h5">Metrics · @scope.Label</h2>
<form hidden>@Html.AntiForgeryToken()</form>
<p class="small text-muted">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.</p>
@if (!timeline.MetricGraphs.Any()) { <p>No active metrics are enabled for this project.</p> }
else {
<div class="context-metrics-panels">
<section class="context-metrics-curve" aria-label="Nearby Timeline metric curves"><h3 class="h6">Timeline curves</h3><div class="context-metrics-canvas"><canvas aria-label="Metrics around the current scene" role="img"></canvas></div></section>
<section class="context-metrics-controls" aria-label="Current scene metric controls"><h3 class="h6">Current scene</h3>
@foreach(var metric in timeline.MetricGraphs) {
var value=metric.Points.FirstOrDefault(p=>p.SceneID==scope.SceneID)?.Value;
<label class="context-metric-control" data-metric-row="@metric.MetricTypeID"><span>@metric.MetricName</span><output>@(value?.ToString() ?? "Unset")</output>
<input type="range" min="@metric.MinValue" max="@metric.MaxValue" step="1" value="@(value ?? metric.MinValue)" data-metric-slider="@metric.MetricTypeID" data-saved-value="@value" disabled="@(!scope.CanEdit)" aria-label="@metric.MetricName" aria-valuetext="@(value?.ToString() ?? "Unset")" />
<small>@metric.MinValue–@metric.MaxValue</small>
</label>
}
</section>
</div>
<p role="status" data-metrics-status></p>
<p role="alert" class="text-danger" data-metrics-error></p>
<button type="button" class="btn btn-outline-secondary btn-sm" data-metrics-retry hidden>Retry save</button>
<button type="button" class="btn btn-outline-secondary btn-sm" data-metrics-cancel hidden>Discard preview</button>
<script type="application/json" data-metrics-payload>@Html.Raw(JsonSerializer.Serialize(payload))</script>
}
</div>

View File

@ -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}}

View File

@ -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); }
} };
})();

View File

@ -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 };
})();

View File

@ -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;