Add Context Warnings previews and project validation feedback
This commit is contained in:
parent
e2d6794804
commit
c9847210aa
68
Docs/Codex/ContextWarnings-122.md
Normal file
68
Docs/Codex/ContextWarnings-122.md
Normal file
@ -0,0 +1,68 @@
|
||||
# Context Warnings — task 122
|
||||
|
||||
Implementation uses existing persisted `ContinuityWarnings`, canonical Timeline
|
||||
order, Context partial lifecycle, shared main-window delegation and existing
|
||||
`MarkIntentionalAsync` review action. Scene tile selection is local preview state;
|
||||
it does not navigate shared focus or Word. Information remains opt-in. Detection
|
||||
evidence is historical; a changed manuscript predecessor is labelled “now”.
|
||||
|
||||
## Development migration review required
|
||||
|
||||
`PlotLine/Sql/341_ContextWarningCheckpoints.sql` adds one SELECT-only stored
|
||||
procedure over existing `ValidationRuns`. It creates no tables, modifies no
|
||||
records and changes no existing numbered migration. Only a completed project or
|
||||
matching book validation establishes coverage, including scenes with no findings.
|
||||
Legacy scene-only runs cannot identify zero-finding scene coverage and are
|
||||
intentionally excluded. Changes since the run started mark results conservatively
|
||||
stale, including cross-book predecessor/structure edits. Unsaved Word changes
|
||||
remain outside saved validation coverage.
|
||||
|
||||
The standard code-only Development orchestrator explicitly rejects changed SQL
|
||||
(`Tools/Deployment/development_release.py`). Before deployment an operator must
|
||||
review/qualify migration 341 using the manifest/history procedure in
|
||||
`Docs/Codex/Database.md` and `Docs/Codex/Deployment.md`, verify the Development
|
||||
database identity, take the required backup, apply only the approved migration,
|
||||
and reconcile the code-only baseline as appropriate. Do not deploy dependent code
|
||||
before the procedure exists. No direct SQL application or deployment was attempted
|
||||
by the worker. Production is excluded.
|
||||
|
||||
Qualification should exercise the procedure against an isolated fixture for no
|
||||
completed run, completed project run, matching/mismatched book run, incomplete run,
|
||||
and scene-only run; it must not mutate author data. The procedure's result is
|
||||
null when no project/book check covers the selected book.
|
||||
|
||||
## Acceptance after authorised Development deployment
|
||||
|
||||
Verify the full deployed commit/environment/database identity. Use the permanent
|
||||
Development browser identity and a registered disposable project through
|
||||
`Tools/BrowserAcceptance/run.py` and the reusable `dev-acceptance.cjs` helper.
|
||||
Create adjacent dated scenes (including a chapter boundary), deliberately validate
|
||||
through the real Warnings toolbar, verify immediate running state, duplicate
|
||||
suppression, completion/error feedback and refreshed summary/results. Open Context
|
||||
Warnings; check numbered tiles/current focus, information toggle, date comparison,
|
||||
evidence and scene-filtered main-window links in light/dark, single/split panes and
|
||||
a second window. Mark a finding intentional and verify counts and persistence after
|
||||
reload and fresh login. Edit a scene date and confirm stale status; revalidation
|
||||
must refresh the checkpoint. Clean up via ordinary scoped project deletion.
|
||||
|
||||
Prepared live script: `PlotLine.Tests/Browser/context-warnings-acceptance.cjs`
|
||||
(run through the launcher after deployment). It has not been executed. Theme,
|
||||
split-window, stale-edit and cross-chapter checks above remain additional live
|
||||
acceptance requirements.
|
||||
|
||||
Offline focused checks: `node PlotLine.Tests/Browser/context-warnings.cjs` and
|
||||
`node PlotLine.Tests/Browser/warning-validation.cjs`. These use synthetic responses
|
||||
and do not establish Development persistence or physical Word acceptance.
|
||||
|
||||
|
||||
## Local verification (2 December 2026)
|
||||
|
||||
The solution build passed with zero warnings/errors. The full executable
|
||||
regression harness passed after correcting the new controller fixture to register
|
||||
MVC view services (the initial run stopped on that fixture setup error). Both
|
||||
focused browser scripts passed. C# regressions cover canonical chapter order,
|
||||
cross-book predecessor evidence, intentional/dismissed filtering, zero-finding
|
||||
checkpoint coverage, stale edits during validation, read-only navigation allowlist,
|
||||
server-side duplicate validation suppression and failure lock release. SQL
|
||||
qualification and authenticated Development acceptance remain outstanding; these
|
||||
results must not be reported as deployed acceptance.
|
||||
49
PlotLine.Tests/Browser/context-warnings-acceptance.cjs
Normal file
49
PlotLine.Tests/Browser/context-warnings-acceptance.cjs
Normal file
@ -0,0 +1,49 @@
|
||||
// Run only after migration qualification and authorised Development deployment.
|
||||
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:'Warnings acceptance',BookNumber:1});
|
||||
const chapter=await session.create('Chapters','?bookId='+book,{ChapterTitle:'Warning dates',ChapterNumber:1});
|
||||
const scenes=[];
|
||||
for(const [n,date] of [[1,'2026-12-02T12:00'],[2,'2026-12-01T12:00']]){
|
||||
stage='dated scene fixture';await session.goto('/Scenes/Create?chapterId='+chapter);
|
||||
const page=session.page;await page.locator('#SceneTitle').fill('Warning scene '+n);
|
||||
const mode=await page.locator('#TimeModeID option').filter({hasText:/Exact/i}).first().getAttribute('value');
|
||||
assert(mode);await page.locator('#TimeModeID').selectOption(mode);await page.locator('#StartDateTime').fill(date);
|
||||
await page.getByRole('button',{name:'Create scene',exact:true}).click();await page.waitForURL('**/Scenes/Edit/*');
|
||||
scenes.push(Number(new URL(page.url()).pathname.split('/').pop()));
|
||||
}
|
||||
stage='real project validation';await session.goto('/Warnings?projectId='+project+'&bookId='+book);
|
||||
const page=session.page;await page.getByRole('button',{name:'Validate project',exact:true}).click();
|
||||
await page.waitForFunction(()=>document.querySelector('[data-validation-status]').textContent.includes('Validation complete.'));
|
||||
assert(await page.locator('.validation-summary').count());
|
||||
const route='/Writing/Context?'+new URLSearchParams({projectId:project,bookId:book,sceneId:scenes[1]});
|
||||
stage='context warnings';await session.goto(route);
|
||||
const pane=page.locator('[data-context-pane="0"]');await pane.locator('[data-context-tab]').selectOption('warnings');
|
||||
await pane.locator('[data-context-warnings]').waitFor();
|
||||
let navigationWrites=0;page.on('request',r=>{if(/\/(Writing\/Context|WriterWord)\/Navigate/.test(new URL(r.url()).pathname))navigationWrites++;});
|
||||
assert.match(await pane.locator('[data-warning-cards]').innerText(),/1 day earlier/);
|
||||
assert(!/No completed/.test(await pane.locator('[data-warning-checked]').innerText()));
|
||||
const current=await pane.locator('[aria-current=true]').getAttribute('data-warning-scene');
|
||||
await pane.locator(`[data-warning-scene="${scenes[0]}"]`).click();
|
||||
assert.equal(await pane.locator('[aria-current=true]').getAttribute('data-warning-scene'),current);
|
||||
await pane.locator('[data-warning-information]').check();
|
||||
assert(await pane.locator('.context-information-count').count());
|
||||
await pane.locator(`[data-warning-scene="${scenes[1]}"]`).click();
|
||||
assert.match(await pane.locator('[data-warning-open]').getAttribute('href'),new RegExp('sceneId='+scenes[1]));
|
||||
const card=pane.locator('article').filter({hasText:'Scene Date Order Conflict'});
|
||||
stage='intentional review';await card.getByRole('button',{name:'Mark as intentional'}).click();await card.waitFor({state:'detached'});
|
||||
stage='reload persistence';await page.reload();await pane.locator('[data-context-warnings]').waitFor();
|
||||
assert.equal(await pane.locator('article').filter({hasText:'Scene Date Order Conflict'}).count(),0);
|
||||
assert.equal(navigationWrites,0);
|
||||
await session.close();session=await open();stage='fresh login persistence';await session.goto(route);
|
||||
await session.page.locator('[data-context-pane="0"] [data-context-tab]').selectOption('warnings');
|
||||
await session.page.locator('[data-context-warnings]').waitFor();
|
||||
assert.equal(await session.page.locator('article').filter({hasText:'Scene Date Order Conflict'}).count(),0);
|
||||
console.log(JSON.stringify({status:'passed',featureUrl:'https://dev.plotdirector.com'+route,checks:['real project validation and summary','completed checkpoint','recorded date comparison','local preview preserves focus','information toggle','scene-filtered link','intentional review persisted after reload and fresh login','no Word navigation writes']}));
|
||||
}catch{console.error('Context Warnings 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();}}}
|
||||
})();
|
||||
44
PlotLine.Tests/Browser/context-warnings.cjs
Normal file
44
PlotLine.Tests/Browser/context-warnings.cjs
Normal file
@ -0,0 +1,44 @@
|
||||
const {chromium}=require('playwright');
|
||||
const fs=require('node:fs'),assert=require('node:assert/strict');
|
||||
(async()=>{
|
||||
const browser=await chromium.launch({headless:true});
|
||||
try {
|
||||
const page=await browser.newPage();let posts=0,release;
|
||||
const frame={scope:{bookID:1,projectID:1,sceneID:2,canEdit:true},lastChecked:'2026-12-02T12:00:00',stale:true,scenes:[
|
||||
{sceneID:1,sceneNumber:1,sceneTitle:'Preceding',findings:[{continuityWarningID:5,severityName:'Info',warningTypeName:'Missing outcome',message:'Information only',lastDetectedDate:'2026-12-02T12:00:00'}]},
|
||||
{sceneID:2,sceneNumber:2,sceneTitle:'Selected',previousSceneID:1,previousTitle:'Preceding',findings:[{continuityWarningID:6,severityName:'Warning',warningTypeName:'Scene Date Order Conflict',message:'Earlier date',details:'Previous date: 2026-12-02 12:00:00. Current date: 2026-12-01 12:00:00.',lastDetectedDate:'2026-12-02T12:00:00'}]}]};
|
||||
await page.route('http://warnings.test/**',async route=>{
|
||||
if(route.request().method()==='POST'){posts++;await new Promise(r=>release=r);frame.scenes[1].findings=[];return route.fulfill({json:{saved:true}});}
|
||||
if(route.request().url().includes('/State?'))return route.fulfill({json:frame});
|
||||
return route.fulfill({contentType:'text/html',body:'<main></main>'});
|
||||
});
|
||||
await page.goto('http://warnings.test');
|
||||
await page.addScriptTag({content:fs.readFileSync('PlotLine/wwwroot/js/context-warnings.js','utf8')});
|
||||
await page.evaluate(data=>{
|
||||
document.querySelector('main').innerHTML='<div data-context-tab-fragment><input name="__RequestVerificationToken" value="fixture"><input type="checkbox" data-warning-information><div data-warning-tiles></div><h3 data-warning-title></h3><p data-warning-checked></p><a data-warning-open></a><div data-warning-cards></div><p data-warning-error></p><script type="application/json" data-warnings-payload></script></div>';
|
||||
const node=document.querySelector('main>div');node.querySelector('script').textContent=JSON.stringify(data);window.node=node;
|
||||
window.focusChanges=0;document.addEventListener('plotdirector:shared-focus',()=>focusChanges++);
|
||||
PlotDirectorContextLifecycles.warnings.mount(node);
|
||||
},frame);
|
||||
assert.match(await page.locator('[data-warning-cards]').innerText(),/1 day earlier/);
|
||||
assert.equal(await page.locator('[data-warning-cards] details').getAttribute('open'),null);
|
||||
assert.match(await page.locator('[data-warning-checked]').innerText(),/Stale/);
|
||||
await page.locator('[data-warning-scene="1"]').click();
|
||||
assert.equal(await page.locator('[aria-current=true]').getAttribute('data-warning-scene'),'2');
|
||||
assert.equal(await page.locator('[data-warning-cards] article').count(),0);
|
||||
await page.locator('[data-warning-information]').check();
|
||||
assert.equal(await page.locator('.context-information-count').innerText(),'ⓘ 1');
|
||||
assert.equal(await page.locator('[data-warning-cards] article').count(),1);
|
||||
assert.match(await page.locator('[data-warning-open]').getAttribute('href'),/sceneId=1/);
|
||||
await page.locator('[data-warning-scene="2"]').click();
|
||||
await page.getByRole('button',{name:'Mark as intentional'}).click();
|
||||
assert.equal(await page.evaluate(()=>PlotDirectorContextLifecycles.warnings.canRefresh(node)),false);
|
||||
await page.waitForFunction(()=>document.querySelector('[data-warning-tiles] button').disabled);
|
||||
release();
|
||||
await page.waitForFunction(()=>document.querySelectorAll('[data-warning-cards] article').length===0);
|
||||
assert.equal(posts,1);assert.equal(await page.evaluate(()=>focusChanges),0);
|
||||
assert.equal(await page.locator('.context-warning-count').count(),0);
|
||||
await page.evaluate(()=>PlotDirectorContextLifecycles.warnings.dispose(node));
|
||||
console.log('PASS Context Warnings preview isolation, information toggle, dates, stale status, review guard/count refresh and disposal');
|
||||
}finally{await browser.close();}
|
||||
})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
29
PlotLine.Tests/Browser/warning-validation.cjs
Normal file
29
PlotLine.Tests/Browser/warning-validation.cjs
Normal file
@ -0,0 +1,29 @@
|
||||
const {chromium}=require('playwright');
|
||||
const fs=require('node:fs'),assert=require('node:assert/strict');
|
||||
(async()=>{
|
||||
const browser=await chromium.launch({headless:true});
|
||||
try {
|
||||
const page=await browser.newPage();let posts=0,release,fail=false;
|
||||
await page.route('http://validation.test/**',async route=>{
|
||||
if(route.request().method()==='POST'){
|
||||
posts++;await new Promise(r=>release=r);
|
||||
return fail?route.fulfill({status:500,json:{message:'Validation could not finish.'}}):route.fulfill({contentType:'text/html',body:'<div data-warning-results><section class="validation-summary">Validation complete. 0 errors 1 warnings 2 info</section><p>Updated findings</p></div>'});
|
||||
}
|
||||
return route.fulfill({contentType:'text/html',body:'<form action="/Warnings/ValidateProject" method="post" data-warning-validation><input name="projectId" value="1"><button>Validate project</button></form><p data-validation-status role="status"></p><div data-warning-results>Old findings</div>'});
|
||||
});
|
||||
await page.goto('http://validation.test');
|
||||
await page.addScriptTag({content:fs.readFileSync('PlotLine/wwwroot/js/warning-validation.js','utf8')});
|
||||
const button=page.getByRole('button');await button.click();
|
||||
assert.equal(await button.isDisabled(),true);assert.match(await page.locator('[data-validation-status]').innerText(),/running/);
|
||||
await page.locator('form').evaluate(f=>f.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true})));
|
||||
await page.waitForTimeout(50);assert.equal(posts,1);
|
||||
release();await page.waitForFunction(()=>!document.querySelector('button').disabled);
|
||||
assert.match(await page.locator('[data-validation-status]').innerText(),/0 errors 1 warnings 2 info/);
|
||||
assert.match(await page.locator('[data-warning-results]').innerText(),/Updated findings/);
|
||||
fail=true;await button.click();await page.waitForFunction(()=>document.querySelector('button').disabled);await page.waitForTimeout(50);release();
|
||||
await page.waitForFunction(()=>!document.querySelector('button').disabled);
|
||||
assert.equal(await page.locator('[data-validation-status]').innerText(),'Validation could not finish.');
|
||||
assert.equal(await button.innerText(),'Validate project');
|
||||
console.log('PASS Validate project immediate running state, duplicate prevention, refreshed results/summary, failure feedback and retry controls');
|
||||
}finally{await browser.close();}
|
||||
})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
73
PlotLine.Tests/ContextWarningsTests.cs
Normal file
73
PlotLine.Tests/ContextWarningsTests.cs
Normal file
@ -0,0 +1,73 @@
|
||||
using System.Reflection;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PlotLine.Controllers;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services.Context;
|
||||
internal static class ContextWarningsTests
|
||||
{
|
||||
public static void Run()
|
||||
{
|
||||
var started = new DateTime(2026, 12, 2, 12, 0, 0, DateTimeKind.Utc);
|
||||
var data = new TimelineData { Books = [new(){BookID=1,BookNumber=1},new(){BookID=2,BookNumber=2}],
|
||||
Chapters = [new(){ChapterID=10,BookID=1,ChapterNumber=1},new(){ChapterID=20,BookID=2,ChapterNumber=1}],
|
||||
Scenes = [new(){SceneID=3,ChapterID=20,SceneNumber=2},new(){SceneID=1,ChapterID=10,SceneNumber=1},new(){SceneID=2,ChapterID=20,SceneNumber=1}] };
|
||||
var scope = new SpatialScope { ProjectID=1,BookID=2,ChapterID=20,SceneID=2 };
|
||||
ContinuityWarning[] findings = [new(){SceneID=2,ContinuityWarningID=1,SeverityName="Info"},
|
||||
new(){SceneID=2,ContinuityWarningID=2,WarningTypeName="Scene Date Order Conflict"},
|
||||
new(){SceneID=3,ContinuityWarningID=3,IsIntentional=true},new(){SceneID=2,ContinuityWarningID=4,IsDismissed=true}];
|
||||
var checkedFrame = ContextWarnings.Build(scope,data,findings,new(started,started.AddSeconds(5)));
|
||||
Check(checkedFrame.Scenes.Select(s=>s.SceneID).SequenceEqual(new[]{2,3}),"Chapter strip follows canonical manuscript order");
|
||||
Check(checkedFrame.Scenes[0].PreviousSceneID==1,"Date evidence preserves predecessor across book/chapter boundaries");
|
||||
Check(checkedFrame.Scenes[0].Findings.Select(w=>w.ContinuityWarningID).SequenceEqual(new[]{2,1}),"Date evidence first; dismissed excluded; information retained for toggle");
|
||||
Check(checkedFrame.Scenes[1].Findings.Count==0,"Intentional review removes active finding counts");
|
||||
Check(!checkedFrame.Stale && checkedFrame.LastChecked==started.AddSeconds(5),"Completed checkpoint covers zero-finding scenes");
|
||||
data.Scenes[1].UpdatedDate=started.AddSeconds(1);
|
||||
Check(ContextWarnings.Build(scope,data,findings,new(started,started.AddSeconds(5))).Stale,"Cross-book predecessor edit during validation conservatively marks stale");
|
||||
Check(ContextWarnings.Build(scope,data,[],null).Stale,"No completed checkpoint never claims a clean/current check");
|
||||
Check(ContextWorkspaceNavigation.IsAllowed("/Warnings?projectId=1&sceneId=2"),"Main window accepts scene-filtered warning route");
|
||||
Check(ContextWorkspaceNavigation.IsAllowed("/Timeline?projectId=1&selectedSceneId=2"),"Main window accepts evidence scene route");
|
||||
Check(!ContextWorkspaceNavigation.IsAllowed("/Warnings/ValidateProject?projectId=1"),"Validation actions are never delegated as read navigation");
|
||||
ValidationConcurrency().GetAwaiter().GetResult();
|
||||
Console.WriteLine("PASS Context warnings ordering, recorded decisions, checkpoint coverage and stale evidence");
|
||||
}
|
||||
private static async Task ValidationConcurrency()
|
||||
{
|
||||
var pending = new TaskCompletionSource<ContinuityValidationSummary>();
|
||||
var validation = DispatchProxy.Create<IContinuityValidationService, ValidationProxy>();
|
||||
var proxy = (ValidationProxy)(object)validation; proxy.Pending = pending.Task;
|
||||
var collection = new ServiceCollection().AddLogging().AddSingleton<ICurrentUserService>(new NoCurrentUser());
|
||||
collection.AddControllersWithViews();
|
||||
var services = collection.BuildServiceProvider();
|
||||
WarningsController Controller() => new(validation, null!, null!) { ControllerContext = new() { HttpContext = new DefaultHttpContext { RequestServices = services } } };
|
||||
var first = Controller().ValidateProject(991122, null);
|
||||
var duplicate = await Controller().ValidateBook(991122, 1);
|
||||
Check(duplicate is ConflictObjectResult && proxy.Calls==1,"Overlapping project/book checks share a server gate");
|
||||
pending.SetResult(new(){WarningCount=2});
|
||||
Check(await first is ViewResult,"First validation returns completed dashboard");
|
||||
proxy.Pending = Task.FromException<ContinuityValidationSummary>(new InvalidOperationException("Synthetic failure"));
|
||||
Check(await Controller().ValidateProject(991122,null) is ObjectResult { StatusCode:500 },"Validation failures produce explicit failure response");
|
||||
proxy.Pending = Task.FromResult(new ContinuityValidationSummary());
|
||||
Check(await Controller().ValidateProject(991122,null) is ViewResult,"Failed checks release the gate for deliberate retry");
|
||||
}
|
||||
public class ValidationProxy : DispatchProxy
|
||||
{
|
||||
public Task<ContinuityValidationSummary> Pending = null!;
|
||||
public int Calls;
|
||||
protected override object? Invoke(MethodInfo? method, object?[]? args)
|
||||
{
|
||||
if(method!.Name is "ValidateProjectAsync" or "ValidateBookAsync") { Calls++; return Pending; }
|
||||
if(method.Name=="GetDashboardAsync") return Task.FromResult<PlotLine.ViewModels.WarningDashboardViewModel?>(new());
|
||||
throw new NotSupportedException(method.Name);
|
||||
}
|
||||
}
|
||||
private sealed class NoCurrentUser : ICurrentUserService
|
||||
{
|
||||
public int? UserId=>null;public string? Email=>null;public string? DisplayName=>null;public bool IsAuthenticated=>false;
|
||||
}
|
||||
private static void Check(bool value,string message) { if(!value) throw new InvalidOperationException(message); }
|
||||
}
|
||||
@ -15,6 +15,7 @@ using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.ViewModels;
|
||||
|
||||
if(args.Contains("--context-warnings")){ContextWarningsTests.Run();return;}
|
||||
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;}
|
||||
@ -241,6 +242,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 warnings recorded evidence and freshness",ContextWarningsTests.Run),
|
||||
("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()),
|
||||
|
||||
36
PlotLine/Controllers/ContextWarningsController.cs
Normal file
36
PlotLine/Controllers/ContextWarningsController.cs
Normal file
@ -0,0 +1,36 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Services.Context;
|
||||
namespace PlotLine.Controllers;
|
||||
|
||||
[Authorize, ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public sealed class ContextWarningsController(ContextWarnings warnings, ContextSpatial spatial,
|
||||
IContinuityValidationService validation, ContextWorkspaceNotifications notifications, ICurrentUserService user) : Controller
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> State(int bookId, int sceneId)
|
||||
{
|
||||
if (!ModelState.IsValid || bookId <= 0 || sceneId <= 0) return BadRequest();
|
||||
try { return Json(await warnings.Read(bookId, sceneId)); }
|
||||
catch (SqlException e) when (e.Number == 51010) { return Forbid(); }
|
||||
}
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Intentional(int bookId, int sceneId, int warningId)
|
||||
{
|
||||
if (!ModelState.IsValid || bookId <= 0 || sceneId <= 0 || warningId <= 0) return BadRequest();
|
||||
try
|
||||
{
|
||||
var scope = await spatial.Scope(bookId, sceneId);
|
||||
if (!scope.CanEdit) return Forbid();
|
||||
var frame = await warnings.Read(bookId, sceneId);
|
||||
if (!frame.Scenes.Any(s => s.SceneID == sceneId && s.Findings.Any(w => w.ContinuityWarningID == warningId))) return NotFound();
|
||||
await validation.MarkIntentionalAsync(warningId);
|
||||
await notifications.Invalidate(user.UserId!.Value, projectId: scope.ProjectID, bookId: bookId, kind: "warnings");
|
||||
return Json(new { saved = true });
|
||||
}
|
||||
catch (SqlException e) when (e.Number == 51010) { return Forbid(); }
|
||||
}
|
||||
}
|
||||
@ -1,3 +1,4 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc.Rendering;
|
||||
@ -15,6 +16,8 @@ public sealed class WarningsController(
|
||||
ISceneService scenes,
|
||||
ICompositeViewEngine viewEngine) : Controller
|
||||
{
|
||||
private static readonly ConcurrentDictionary<int, byte> RunningValidations = new();
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> SceneContinuityEditor(int sceneId)
|
||||
{
|
||||
@ -45,18 +48,41 @@ public sealed class WarningsController(
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> ValidateProject(int projectId, int? bookId)
|
||||
{
|
||||
var summary = await validation.ValidateProjectAsync(projectId);
|
||||
var model = await validation.GetDashboardAsync(projectId, bookId, null, null, null, null, null, null, false, false, false, summary);
|
||||
return model is null ? NotFound() : View("Index", model);
|
||||
return await RunValidation(projectId, bookId, () => validation.ValidateProjectAsync(projectId));
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> ValidateBook(int projectId, int bookId)
|
||||
{
|
||||
var summary = await validation.ValidateBookAsync(bookId);
|
||||
var model = await validation.GetDashboardAsync(projectId, bookId, null, null, null, null, null, null, false, false, false, summary);
|
||||
return model is null ? NotFound() : View("Index", model);
|
||||
return await RunValidation(projectId, bookId, () => validation.ValidateBookAsync(bookId));
|
||||
}
|
||||
|
||||
private Task NotifyWarnings(int projectId)
|
||||
{
|
||||
var current = HttpContext.RequestServices.GetRequiredService<ICurrentUserService>();
|
||||
return current.UserId.HasValue
|
||||
? HttpContext.RequestServices.GetRequiredService<ContextWorkspaceNotifications>().Invalidate(current.UserId.Value, projectId: projectId, kind: "warnings")
|
||||
: Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task<IActionResult> RunValidation(int projectId, int? bookId, Func<Task<ContinuityValidationSummary>> run)
|
||||
{
|
||||
if (!RunningValidations.TryAdd(projectId, 0))
|
||||
return Conflict(new { message = "Validation is already running for this project. Wait for it to finish before checking again." });
|
||||
try
|
||||
{
|
||||
var summary = await run();
|
||||
await NotifyWarnings(projectId);
|
||||
var model = await validation.GetDashboardAsync(projectId, bookId, null, null, null, null, null, null, false, false, false, summary);
|
||||
return model is null ? NotFound() : View("Index", model);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
HttpContext.RequestServices.GetRequiredService<ILogger<WarningsController>>().LogError(e, "Project validation failed. ProjectID={ProjectID}", projectId);
|
||||
return StatusCode(500, new { message = "Validation could not finish. Refresh saved data before retrying; some findings may have been updated." });
|
||||
}
|
||||
finally { RunningValidations.TryRemove(projectId, out _); }
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
@ -102,6 +128,7 @@ public sealed class WarningsController(
|
||||
{
|
||||
var continuityWarningId = warningId > 0 ? warningId : id;
|
||||
await validation.MarkIntentionalAsync(continuityWarningId);
|
||||
await NotifyWarnings(projectId);
|
||||
if (sceneId.HasValue && IsSceneInspectorAjaxRequest())
|
||||
{
|
||||
return await SceneContinuityRefreshJsonAsync(sceneId.Value);
|
||||
|
||||
@ -119,6 +119,23 @@ public sealed class WritingController(
|
||||
ViewData["ContextTabPartial"]="_ContextNames";return PartialView("_ContextTab",model);
|
||||
}
|
||||
|
||||
[HttpGet("Context/Warnings")]
|
||||
public async Task<IActionResult> ContextWarningsTab(int? projectId, int? bookId, int? chapterId, int? sceneId,
|
||||
Guid? instanceId, Guid? sessionId, [FromServices] PlotLine.Services.Context.ContextWarnings warnings)
|
||||
{
|
||||
if (!ModelState.IsValid || bookId is not > 0 || sceneId is not > 0 || InvalidNativeSelection(instanceId, sessionId)) return BadRequest();
|
||||
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 frame = await warnings.Read(bookId.Value, sceneId.Value);
|
||||
if (projectId.HasValue && projectId != frame.Scope.ProjectID || chapterId.HasValue && chapterId != frame.Scope.ChapterID) return BadRequest();
|
||||
if (instanceId.HasValue && !SameNativeTarget(native, await NativeTarget(bookId, instanceId, sessionId))) return Conflict();
|
||||
return PartialView("_ContextWarnings", frame);
|
||||
}
|
||||
catch (Microsoft.Data.SqlClient.SqlException e) when (e.Number == 51010) { return Forbid(); }
|
||||
}
|
||||
|
||||
[HttpGet("Context/Threads")]
|
||||
public async Task<IActionResult> ContextThreadsTab(int? projectId, int? bookId, int? chapterId, int? sceneId,
|
||||
Guid? instanceId, Guid? sessionId, [FromServices] PlotLine.Services.Context.ContextSpatial spatial)
|
||||
|
||||
@ -310,6 +310,7 @@ public class Program
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextNames>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextSpatial>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextThreads>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextWarnings>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextRelationshipEditing>();
|
||||
builder.Services.AddScoped<PlotLine.Data.IContextRelationshipReader,PlotLine.Data.ContextRelationshipReader>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextRelationshipLenses>();
|
||||
|
||||
44
PlotLine/Services/Context/ContextWarnings.cs
Normal file
44
PlotLine/Services/Context/ContextWarnings.cs
Normal file
@ -0,0 +1,44 @@
|
||||
using System.Data;
|
||||
using Dapper;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Services.Context;
|
||||
|
||||
public sealed record ContextWarningScene(int SceneID, decimal SceneNumber, string SceneTitle,
|
||||
DateTime? Date, DateTime Updated, int? PreviousSceneID, string? PreviousTitle, DateTime? PreviousDate,
|
||||
IReadOnlyList<ContinuityWarning> Findings);
|
||||
public sealed record ContextWarningCheckpoint(DateTime StartedDate, DateTime CompletedDate);
|
||||
public sealed record ContextWarningsFrame(SpatialScope Scope, IReadOnlyList<ContextWarningScene> Scenes, DateTime? LastChecked, bool Stale);
|
||||
|
||||
// Recorded validation findings only. Browsing Context must never run validation or
|
||||
// rebuild generated Story State warnings. Timeline supplies canonical manuscript order.
|
||||
public sealed class ContextWarnings(ContextSpatial spatial, ITimelineRepository timeline, IWarningRepository warnings, ISqlConnectionFactory connections)
|
||||
{
|
||||
public async Task<ContextWarningsFrame> Read(int bookId, int sceneId)
|
||||
{
|
||||
var scope = await spatial.Scope(bookId, sceneId);
|
||||
var data = await timeline.GetByProjectAsync(scope.ProjectID, null, false, [], false);
|
||||
var recorded = await warnings.ListAsync(scope.ProjectID, bookId, null, null, null, null, false, false);
|
||||
using var connection = connections.CreateConnection();
|
||||
var checkpoint = await connection.QuerySingleOrDefaultAsync<ContextWarningCheckpoint>("dbo.ContextWarnings_Checkpoint",
|
||||
new { scope.ProjectID, scope.BookID }, commandType: CommandType.StoredProcedure);
|
||||
return Build(scope, data, recorded, checkpoint);
|
||||
}
|
||||
|
||||
public static ContextWarningsFrame Build(SpatialScope scope, TimelineData data,
|
||||
IReadOnlyList<ContinuityWarning> recorded, ContextWarningCheckpoint? checkpoint)
|
||||
{
|
||||
var ordered = StoryStateService.OrderScenes(data).ToArray();
|
||||
var scenes = ordered.Select((scene, index) => (scene, previous: index > 0 ? ordered[index - 1] : null))
|
||||
.Where(x => x.scene.ChapterID == scope.ChapterID)
|
||||
.Select(x => new ContextWarningScene(x.scene.SceneID, x.scene.SceneNumber, x.scene.SceneTitle,
|
||||
x.scene.StartDateTime, x.scene.UpdatedDate, x.previous?.SceneID, x.previous?.SceneTitle, x.previous?.StartDateTime,
|
||||
recorded.Where(w => w.SceneID == x.scene.SceneID && !w.IsDismissed && !w.IsIntentional)
|
||||
.OrderByDescending(w => w.WarningTypeName == "Scene Date Order Conflict").ThenBy(w => w.ContinuityWarningID).ToArray())).ToArray();
|
||||
// Use the start of the check conservatively: edits made while validation
|
||||
// ran might not have been included. Cross-book predecessors also matter.
|
||||
var stale = checkpoint == null || ordered.Any(s => s.UpdatedDate > checkpoint.StartedDate)
|
||||
|| data.Chapters.Any(c => c.UpdatedDate > checkpoint.StartedDate);
|
||||
return new(scope, scenes, checkpoint?.CompletedDate, stale);
|
||||
}
|
||||
}
|
||||
@ -13,6 +13,6 @@ public static partial class ContextWorkspaceNavigation
|
||||
return MainPage().IsMatch(path);
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"^/(?:Characters(?:/(?:Details|Edit)/[1-9][0-9]*)?|Locations(?:/(?:Details|Edit)/[1-9][0-9]*)?|Maps|FloorPlans(?:/Edit/[1-9][0-9]*)?|Scenes/Edit/[1-9][0-9]*|Names|RelationshipMap|StoryCalendar|PlotLineWorkspace|PlotThreads/Edit/[1-9][0-9]*|Writer|Books/Details/[1-9][0-9]*|manuscript/paragraphs)/?$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
|
||||
[GeneratedRegex(@"^/(?:Characters(?:/(?:Details|Edit)/[1-9][0-9]*)?|Locations(?:/(?:Details|Edit)/[1-9][0-9]*)?|Maps|FloorPlans(?:/Edit/[1-9][0-9]*)?|Scenes/Edit/[1-9][0-9]*|Names|RelationshipMap|StoryCalendar|PlotLineWorkspace|PlotThreads/Edit/[1-9][0-9]*|Warnings|Timeline|Writer|Books/Details/[1-9][0-9]*|manuscript/paragraphs)/?$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
|
||||
private static partial Regex MainPage();
|
||||
}
|
||||
|
||||
20
PlotLine/Sql/341_ContextWarningCheckpoints.sql
Normal file
20
PlotLine/Sql/341_ContextWarningCheckpoints.sql
Normal file
@ -0,0 +1,20 @@
|
||||
-- Read-only checkpoint for Context's recorded warnings. Existing ValidationRuns
|
||||
-- cannot identify a scene checked with zero findings, so only completed full
|
||||
-- project/book runs establish coverage. No historical timestamp is fabricated.
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.ContextWarnings_Checkpoint
|
||||
@ProjectID int,
|
||||
@BookID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
SELECT TOP (1) StartedDate, CompletedDate
|
||||
FROM dbo.ValidationRuns
|
||||
WHERE ProjectID = @ProjectID AND CompletedDate IS NOT NULL
|
||||
AND ((BookID IS NULL AND ScopeDescription = N'Project validation')
|
||||
OR (BookID = @BookID AND ScopeDescription = N'Book validation'))
|
||||
ORDER BY CompletedDate DESC, ValidationRunID DESC;
|
||||
END;
|
||||
GO
|
||||
@ -28,14 +28,14 @@
|
||||
<h1>@Model.Project.ProjectName <help-icon key="warnings.overview" /></h1>
|
||||
</div>
|
||||
<div class="button-row">
|
||||
<form asp-action="ValidateProject" method="post">
|
||||
<form asp-action="ValidateProject" method="post" data-warning-validation>
|
||||
<input type="hidden" name="projectId" value="@Model.Project.ProjectID" />
|
||||
<input type="hidden" name="bookId" value="@Model.BookID" />
|
||||
<button class="btn btn-primary" type="submit">Validate project</button>
|
||||
</form>
|
||||
@if (Model.BookID.HasValue)
|
||||
{
|
||||
<form asp-action="ValidateBook" method="post">
|
||||
<form asp-action="ValidateBook" method="post" data-warning-validation>
|
||||
<input type="hidden" name="projectId" value="@Model.Project.ProjectID" />
|
||||
<input type="hidden" name="bookId" value="@Model.BookID" />
|
||||
<button class="btn btn-outline-primary" type="submit">Validate book</button>
|
||||
@ -44,6 +44,8 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p data-validation-status role="status" class="mb-2"></p>
|
||||
<div data-warning-results>
|
||||
@if (Model.LastValidationSummary is not null)
|
||||
{
|
||||
<section class="validation-summary">
|
||||
@ -336,4 +338,5 @@
|
||||
}
|
||||
</section>
|
||||
|
||||
@section Scripts {<script src="~/js/warning-triage.js" asp-append-version="true"></script>}
|
||||
</div>
|
||||
@section Scripts {<script src="~/js/warning-validation.js" asp-append-version="true"></script><script src="~/js/warning-triage.js" asp-append-version="true"></script>}
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
ViewData["Title"] = "Context";
|
||||
var position = Model.Display?.Context?.Position;
|
||||
var tabs = new[] {
|
||||
new { id = "warnings", displayName = "Warnings", endpoint = Url.Action("ContextWarningsTab", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "warnings", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty<string>() },
|
||||
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" } },
|
||||
@ -20,6 +21,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-warnings.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"
|
||||
@ -76,6 +78,7 @@
|
||||
<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-warnings.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>
|
||||
|
||||
16
PlotLine/Views/Writing/_ContextWarnings.cshtml
Normal file
16
PlotLine/Views/Writing/_ContextWarnings.cshtml
Normal file
@ -0,0 +1,16 @@
|
||||
@model PlotLine.Services.Context.ContextWarningsFrame
|
||||
@using System.Text.Json
|
||||
@{ Layout = null; var scope = Model.Scope; }
|
||||
<div data-context-tab-fragment data-context-warnings data-project-id="@scope.ProjectID" data-book-id="@scope.BookID" data-chapter-id="@scope.ChapterID" data-scene-id="@scope.SceneID">
|
||||
<h2 class="h5">Warnings · Chapter @scope.ChapterNumber</h2>
|
||||
<form hidden>@Html.AntiForgeryToken()</form>
|
||||
<p class="small text-muted">Recorded findings only. Previewing a tile keeps Current Focus and your manuscript caret in place.</p>
|
||||
<label><input type="checkbox" data-warning-information /> Show information</label>
|
||||
<div class="context-warning-strip" data-warning-tiles aria-label="Chapter scene warnings"></div>
|
||||
<h3 class="h6" data-warning-title></h3>
|
||||
<p class="small" data-warning-checked></p>
|
||||
<a data-warning-open target="_blank" rel="noopener">Open Warnings</a>
|
||||
<div data-warning-cards></div>
|
||||
<p role="alert" data-warning-error></p>
|
||||
<script type="application/json" data-warnings-payload>@Html.Raw(JsonSerializer.Serialize(Model, new JsonSerializerOptions(JsonSerializerDefaults.Web)))</script>
|
||||
</div>
|
||||
12
PlotLine/wwwroot/css/context-warnings.css
Normal file
12
PlotLine/wwwroot/css/context-warnings.css
Normal file
@ -0,0 +1,12 @@
|
||||
.context-warning-strip { display:flex; flex-wrap:wrap; gap:.4rem; margin:.75rem 0; }
|
||||
.context-warning-tile { display:flex; flex-direction:column; gap:.15rem; align-items:center; padding:.4rem .65rem; border:1px solid var(--bs-border-color,#888); background:var(--bs-body-bg); color:var(--bs-body-color); border-radius:.4rem; }
|
||||
.context-warning-tile.current-focus { outline:2px solid var(--bs-primary,#0d6efd); outline-offset:2px; }
|
||||
.context-warning-tile[aria-pressed=true] { background:var(--bs-secondary-bg,#e9ecef); font-weight:600; }
|
||||
.context-warning-count { color:var(--bs-warning-text-emphasis,#946200); background:var(--bs-warning-bg-subtle,#fff3cd); border-radius:.3rem; padding:0 .3rem; }
|
||||
.context-information-count { color:var(--bs-info-text-emphasis,#055160); background:var(--bs-info-bg-subtle,#cff4fc); border-radius:.3rem; padding:0 .3rem; }
|
||||
.context-warning-card { border:1px solid var(--bs-border-color,#888); border-radius:.4rem; padding:.65rem; margin:.6rem 0; }
|
||||
.context-warning-card p { margin:.35rem 0; }
|
||||
.context-warning-card details { margin:.5rem 0; }
|
||||
.context-warning-dates { display:flex; gap:.6rem; flex-wrap:wrap; margin:.5rem 0; }
|
||||
.context-warning-dates span { white-space:pre-line; padding:.35rem; background:var(--bs-tertiary-bg); }
|
||||
.context-warning-dates mark { align-self:center; }
|
||||
86
PlotLine/wwwroot/js/context-warnings.js
Normal file
86
PlotLine/wwwroot/js/context-warnings.js
Normal file
@ -0,0 +1,86 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
const instances = new WeakMap();
|
||||
const el = (tag, text, cls) => { const n = document.createElement(tag); if (text != null) n.textContent = text; if (cls) n.className = cls; return n; };
|
||||
const information = w => !['Critical', 'Error', 'Warning'].includes(w.severityName);
|
||||
function mount(node) {
|
||||
if (instances.has(node)) return;
|
||||
let data = JSON.parse(node.querySelector('[data-warnings-payload]').textContent), selected = data.scope.sceneID, busy = false, alive = true, version = 0;
|
||||
const abort = new AbortController(), info = node.querySelector('[data-warning-information]'), error = node.querySelector('[data-warning-error]');
|
||||
const guard = value => { busy = value; node.dispatchEvent(new CustomEvent('context-panel-state', { bubbles: true, detail: { busy: value, dirty: false, deferRefresh: true } })); };
|
||||
const fail = message => { error.textContent = message; window.PlotDirector?.toast?.error(message); };
|
||||
const link = (id, title) => { const a = el('a', title); a.href = `/Timeline?projectId=${data.scope.projectID}&selectedSceneId=${id}`; a.target = '_blank'; a.rel = 'noopener'; a.dataset.contextOpenScene = id; return a; };
|
||||
const visible = scene => scene.findings.filter(w => info.checked || !information(w));
|
||||
async function read() {
|
||||
const current = ++version;
|
||||
const response = await fetch(`/ContextWarnings/State?bookId=${data.scope.bookID}&sceneId=${data.scope.sceneID}`, { cache: 'no-store', signal: abort.signal });
|
||||
if (!response.ok || response.redirected) throw Error('Warnings could not be refreshed. Refresh saved data to retry.');
|
||||
const result = await response.json();
|
||||
if (!alive || current !== version) return;
|
||||
data = result; render();
|
||||
}
|
||||
function render() {
|
||||
const tiles = node.querySelector('[data-warning-tiles]'); tiles.replaceChildren();
|
||||
for (const scene of data.scenes) {
|
||||
const tile = el('button', null, 'context-warning-tile'); tile.type = 'button'; tile.disabled = busy;
|
||||
tile.dataset.warningScene = scene.sceneID;
|
||||
tile.setAttribute('aria-pressed', String(scene.sceneID === selected));
|
||||
if (scene.sceneID === data.scope.sceneID) { tile.classList.add('current-focus'); tile.setAttribute('aria-current', 'true'); }
|
||||
tile.append(el('span', `Scene ${scene.sceneNumber}`));
|
||||
if (scene.sceneID === data.scope.sceneID) tile.append(el('small', 'Current Focus'));
|
||||
const attention = scene.findings.filter(w => !information(w)).length, extra = scene.findings.filter(information).length;
|
||||
if (attention) tile.append(el('span', `⚠ ${attention}`, 'context-warning-count'));
|
||||
if (info.checked && extra) tile.append(el('span', `ⓘ ${extra}`, 'context-information-count'));
|
||||
tile.title = scene.sceneTitle;
|
||||
tile.addEventListener('click', () => { selected = scene.sceneID; render(); node.querySelector(`[data-warning-scene="${selected}"]`)?.focus({preventScroll:true}); }); tiles.append(tile);
|
||||
}
|
||||
const scene = data.scenes.find(s => s.sceneID === selected) || data.scenes.find(s => s.sceneID === data.scope.sceneID);
|
||||
if (!scene) return;
|
||||
selected = scene.sceneID;
|
||||
node.querySelector('[data-warning-title]').textContent = `Scene ${scene.sceneNumber}: ${scene.sceneTitle}`;
|
||||
node.querySelector('[data-warning-checked]').textContent = `Last checked: ${data.lastChecked ? data.lastChecked.replace('T', ' ') + ' UTC' : 'No completed project or book check recorded'}. ${data.stale ? 'Stale or unchecked: dates or manuscript structure may have changed. Validate project in the main window.' : 'Recorded project/book check. Manuscript text and unsaved Word changes are not checked here.'}`;
|
||||
const open = node.querySelector('[data-warning-open]'); open.href = `/Warnings?projectId=${data.scope.projectID}&bookId=${data.scope.bookID}&sceneId=${selected}`; open.dataset.contextOpenScene = selected;
|
||||
const cards = node.querySelector('[data-warning-cards]'); cards.replaceChildren();
|
||||
const findings = visible(scene);
|
||||
if (!findings.length) cards.append(el('p', scene.findings.length ? 'No warnings needing attention. Information is hidden.' : 'No recorded active findings. This does not confirm the scene has been checked.'));
|
||||
for (const warning of findings) {
|
||||
const card = el('article', null, 'context-warning-card');
|
||||
card.append(el('strong', `${information(warning) ? 'Information' : warning.severityName} · ${warning.warningTypeName}`), el('p', warning.message));
|
||||
if (warning.warningTypeName === 'Scene Date Order Conflict') {
|
||||
const match = warning.details?.match(/Previous date: (\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)\. Current date: (\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)/);
|
||||
if (match) {
|
||||
const dates = el('div', null, 'context-warning-dates');
|
||||
dates.append(el('span', `Preceding date\n${match[1]}`), el('span', `Selected date\n${match[2]}`));
|
||||
const days = (Date.parse(match[1].replace(' ', 'T') + 'Z') - Date.parse(match[2].replace(' ', 'T') + 'Z')) / 86400000;
|
||||
dates.append(el('mark', `${Number(days.toFixed(2))} ${days === 1 ? 'day' : 'days'} earlier`)); card.append(dates);
|
||||
}
|
||||
if (scene.previousSceneID) card.append(link(scene.previousSceneID, `Preceding scene now: ${scene.previousTitle}`), document.createTextNode(' · '));
|
||||
}
|
||||
card.append(link(selected, 'Selected scene'));
|
||||
const details = el('details'); details.append(el('summary', 'Details'), el('p', warning.details || 'No further evidence was recorded.'), el('small', `Detected ${warning.lastDetectedDate.replace('T', ' ')} UTC. Scene order or dates may have changed since detection.`)); card.append(details);
|
||||
if (data.scope.canEdit) {
|
||||
const intentional = el('button', 'Mark as intentional', 'btn btn-outline-secondary btn-sm'); intentional.type = 'button'; intentional.disabled = busy;
|
||||
intentional.addEventListener('click', async () => {
|
||||
if (busy) return; guard(true); error.textContent = ''; render();
|
||||
try {
|
||||
const body = new URLSearchParams({ bookId: data.scope.bookID, sceneId: scene.sceneID, warningId: warning.continuityWarningID, __RequestVerificationToken: node.querySelector('[name="__RequestVerificationToken"]').value });
|
||||
const response = await fetch('/ContextWarnings/Intentional', { method: 'POST', body });
|
||||
if (!response.ok || response.redirected) throw Error('The review could not be saved. Refresh saved data before retrying.');
|
||||
window.PlotDirector?.toast?.success('Marked as intentional');
|
||||
try { await read(); } catch { fail('Review saved. Refresh saved data to reload counts.'); }
|
||||
} catch (e) { if (alive) fail(e.message); }
|
||||
finally { if (alive) { guard(false); render(); } }
|
||||
}); card.append(intentional);
|
||||
}
|
||||
cards.append(card);
|
||||
}
|
||||
}
|
||||
const change = () => render(); info.addEventListener('change', change); render();
|
||||
instances.set(node, { busy: () => busy, refresh: () => read().catch(e => { if (alive && e.name !== 'AbortError') fail(e.message); }), dispose() { alive = false; abort.abort(); info.removeEventListener('change', change); } });
|
||||
}
|
||||
window.PlotDirectorContextLifecycles = { ...(window.PlotDirectorContextLifecycles || {}), warnings: {
|
||||
mount, canRefresh: node => !instances.get(node)?.busy(),
|
||||
onInvalidation(node) { const i = instances.get(node); if (!i || i.busy()) return false; i.refresh(); return true; },
|
||||
dispose(node) { instances.get(node)?.dispose(); instances.delete(node); }
|
||||
} };
|
||||
})();
|
||||
@ -128,7 +128,7 @@
|
||||
spatial:['locations','maps','floorplans'], names:['names'],
|
||||
characters:['overview','characters','relationships','names','locations','maps','floorplans'],
|
||||
relationships:['overview','characters','relationships'],
|
||||
dates:['overview','calendar'], intent:['overview','intent'],
|
||||
warnings:['warnings'], dates:['overview','calendar','warnings'], intent:['overview','intent'],
|
||||
plotlines:['overview','intent','plotlines','threads'], threads:['overview','intent','threads'],
|
||||
metrics:['overview','metrics'], assets:['overview','assets','maps','floorplans']
|
||||
};
|
||||
@ -137,7 +137,7 @@
|
||||
!(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId&&!['dates','structure'].includes(hint.kind));
|
||||
}
|
||||
function affects(tab,hint) {
|
||||
if(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId&&tab.id!=='calendar')return false;
|
||||
if(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId&&!['calendar','warnings'].includes(tab.id))return false;
|
||||
return tab.contentRefresh!=='none' && (!affectedPanels[hint.kind] || affectedPanels[hint.kind].includes(tab.id));
|
||||
}
|
||||
function invalidate(hint={}) {
|
||||
|
||||
@ -1,5 +1,8 @@
|
||||
(()=>{
|
||||
function mount(){
|
||||
const search=document.querySelector('#warning-evidence-search'),state=document.querySelector('#warning-review-state'),groups=[...document.querySelectorAll('[data-warning-cluster]')];if(!search||!state)return;
|
||||
const update=()=>{const query=search.value.trim().toLocaleLowerCase();let total=0;for(const group of groups){let matches=0;for(const row of group.querySelectorAll('[data-warning-evidence]')){const decided=row.dataset.decided==='true';row.hidden=!!query&&!row.textContent.toLocaleLowerCase().includes(query)||state.value==='active'&&decided||state.value==='decided'&&!decided;if(!row.hidden)matches++;}group.hidden=!matches;if(query&&matches)group.open=true;total+=matches;}document.querySelector('#warning-match-count').textContent=total+' matching warnings in loaded results';};
|
||||
search.addEventListener('input',update);state.addEventListener('change',update);document.querySelector('#warning-expand')?.addEventListener('click',()=>groups.filter(g=>!g.hidden).forEach(g=>g.open=true));document.querySelector('#warning-collapse')?.addEventListener('click',()=>groups.forEach(g=>g.open=false));update();
|
||||
}
|
||||
mount();document.addEventListener('warnings-results-updated',mount);
|
||||
})();
|
||||
|
||||
34
PlotLine/wwwroot/js/warning-validation.js
Normal file
34
PlotLine/wwwroot/js/warning-validation.js
Normal file
@ -0,0 +1,34 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
const forms = [...document.querySelectorAll('[data-warning-validation]')], status = document.querySelector('[data-validation-status]');
|
||||
if (!forms.length || !status) return;
|
||||
let running = false;
|
||||
for (const form of forms) form.addEventListener('submit', async event => {
|
||||
event.preventDefault(); if (running) return;
|
||||
running = true;
|
||||
// Capture successful controls before disabling any controls.
|
||||
const body = new FormData(form), buttons = forms.flatMap(f => [...f.querySelectorAll('button')]);
|
||||
buttons.forEach(b => { b.disabled = true; });
|
||||
const button = form.querySelector('button'), title = button.textContent;
|
||||
button.textContent = 'Validating…'; status.textContent = 'Validation running. This may take a little while.';
|
||||
status.setAttribute('aria-busy', 'true');
|
||||
try {
|
||||
const response = await fetch(form.action, { method: 'POST', body, headers: { 'X-Requested-With': 'XMLHttpRequest' } });
|
||||
if (!response.ok || response.redirected) {
|
||||
const result = await response.json().catch(() => null);
|
||||
throw Error(result?.message || 'Validation could not finish. Check sign-in and refresh before retrying.');
|
||||
}
|
||||
const page = new DOMParser().parseFromString(await response.text(), 'text/html');
|
||||
const results = page.querySelector('[data-warning-results]'), summary = results?.querySelector('.validation-summary');
|
||||
if (!summary) throw Error('Validation response was incomplete. Refresh warnings before retrying.');
|
||||
document.querySelector('[data-warning-results]').replaceWith(results);
|
||||
document.dispatchEvent(new Event('warnings-results-updated'));
|
||||
status.textContent = summary.textContent.replace(/\s+/g, ' ').trim();
|
||||
window.PlotDirector?.toast?.success('Validation complete');
|
||||
} catch (e) {
|
||||
status.textContent = e.message; window.PlotDirector?.toast?.error(e.message);
|
||||
} finally {
|
||||
running = false; buttons.forEach(b => { b.disabled = false; }); button.textContent = title; status.removeAttribute('aria-busy');
|
||||
}
|
||||
});
|
||||
})();
|
||||
Loading…
x
Reference in New Issue
Block a user