Refresh Context from scoped committed saves

This commit is contained in:
Atlas Development Worker 2026-11-30 23:20:12 +00:00
parent 8bc5410c78
commit 7aa70c4529
28 changed files with 460 additions and 77 deletions

View File

@ -0,0 +1,44 @@
// Real Development UI, normal writer authentication, and registered disposable data only.
const assert=require('node:assert/strict'),{open}=require('./dev-acceptance.cjs');
let session,stage='login';
(async()=>{try{
session=await open();const p=session.page;const project=await session.project();
const place=await session.create('Locations','?projectId='+project,{LocationName:'Acceptance room',Description:'Original description'});
const book=await session.create('Books','?projectId='+project,{BookTitle:'Context acceptance one',BookNumber:1});
const otherBook=await session.create('Books','?projectId='+project,{BookTitle:'Context acceptance two',BookNumber:2});
const chapter=await session.create('Chapters','?bookId='+book,{ChapterTitle:'Context chapter one',ChapterNumber:1});
const otherChapter=await session.create('Chapters','?bookId='+otherBook,{ChapterTitle:'Context chapter two',ChapterNumber:1});
async function scene(chapter,title){await session.goto('/Scenes/Create?chapterId='+chapter);await p.locator('#SceneTitle').fill(title);await p.locator('#PrimaryLocationID').selectOption(String(place));await p.getByRole('button',{name:'Create scene',exact:true}).click();await p.waitForURL('**/Scenes/Edit/*');return Number(new URL(p.url()).pathname.split('/').at(-1));}
const sceneId=await scene(chapter,'Held acceptance scene'),otherScene=await scene(otherChapter,'Isolated acceptance scene');
stage='map creation';await session.goto('/Maps?projectId='+project);await p.locator('#mapsWelcomeNew').click();await p.locator('#mapsNewForm [name=Name]').fill('Acceptance geometry');await p.locator('#mapsNewForm [name=Starter]').selectOption('land');await p.locator('#mapsNewForm button[type=submit]').click();await p.waitForFunction(()=>window.PlotDirectorMapWorkspace?.document?.features.length>0&&!window.PlotDirectorMapWorkspace.busy);const map=await p.evaluate(()=>PlotDirectorMapWorkspace.document.map.mapID);
stage='floor plan creation';await session.goto('/FloorPlans?projectId='+project);const create=p.locator('form[action="/FloorPlans/Create"]');await create.locator('[name=Name]').fill('Acceptance plan');await create.locator('[name=LocationID]').selectOption(String(place));await create.locator('button[type=submit]').click();await p.waitForURL('**/FloorPlans/Edit/*');const plan=Number(new URL(p.url()).pathname.split('/').at(-1));
const context=p.context(),a=await context.newPage(),b=await context.newPage(),c=await context.newPage(),reads=[];
for(const page of [a,b,c])page.on('request',r=>{const path=new URL(r.url()).pathname;if(path.startsWith('/SpatialContext/')||path.includes('/Context/Tabs/'))reads.push({page,path});});
const url=(bk,ch,sc)=>`https://dev.plotdirector.com/Writing/Context?projectId=${project}&bookId=${bk}&chapterId=${ch}&sceneId=${sc}&pinned=true`;
const setTab=(page,i,tool)=>page.selectOption(`[data-context-pane="${i}"] [data-context-tab]`,tool);
await a.goto(url(book,chapter,sceneId));await a.selectOption('[data-context-layout]','columns');await setTab(a,0,'maps');await setTab(a,1,'floorplans');
await a.locator('[data-context-pane="0"] [data-spatial-resource]').selectOption(String(map));await a.locator('[data-context-pane="1"] [data-spatial-resource]').selectOption(String(plan));
await a.waitForFunction(()=>document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.document);
await a.locator('[data-floor-grid]').first().waitFor();
await b.goto(url(book,chapter,sceneId));await b.selectOption('[data-context-layout]','columns');await setTab(b,0,'locations');await setTab(b,1,'overview');await b.getByRole('heading',{name:'Acceptance room',exact:true}).waitFor();
await c.goto(url(otherBook,otherChapter,otherScene));await c.locator('[data-context-tab-fragment]').waitFor();
await Promise.all([a,b,c].map(page=>page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected')));
await a.locator('[data-context-pane="0"] [data-spatial-zoom="in"]').click();await a.locator('[data-context-pane="1"] [data-spatial-zoom="in"]').click();await a.waitForTimeout(400);
const snapshot=()=>a.evaluate(()=>({position:{...document.querySelector('[data-context-workspace]').contextController.position},view:{...document.querySelector('iframe').contentWindow.PlotDirectorMapWorkspace.view},floor:document.querySelector('[data-spatial-floor]').value,transform:document.querySelector('[data-spatial-floor-world]').style.transform}));
const before=await snapshot();
stage='committed geometry save and relevant refresh';await session.goto(`/Maps?projectId=${project}&id=${map}`);await p.locator('[data-feature-id]').first().click();const width=p.locator('[data-field=width]').first();const savedWidth=Number(await width.inputValue())+37;reads.length=0;await width.fill(String(savedWidth));await p.waitForTimeout(300);assert.equal(reads.length,0,'unsaved geometry emits no saved-data read');
await p.locator('#mapsSave').click();await p.waitForFunction(()=>!PlotDirectorMapWorkspace.dirty&&!PlotDirectorMapWorkspace.busy);
await a.waitForFunction(w=>document.querySelector('iframe')?.contentWindow.PlotDirectorMapWorkspace?.document.features[0].width===w,savedWidth);await a.waitForTimeout(300);
assert.equal(reads.filter(r=>r.path==='/SpatialContext/Floor').length,0);assert.equal(reads.filter(r=>r.page===c).length,0,'project-wide geometry does not refresh unrelated Overview');assert.deepEqual(await snapshot(),before);
stage='failed save does not invalidate';reads.length=0;const failed=await p.evaluate(async()=>{const doc=structuredClone(PlotDirectorMapWorkspace.document);doc.map.revision=-1;const token=document.querySelector('[name=__RequestVerificationToken]').value;return (await fetch('/Maps/Save',{method:'POST',headers:{'Content-Type':'application/json','RequestVerificationToken':token},body:JSON.stringify(doc)})).status;});assert(failed>=400);await a.waitForTimeout(400);assert.equal(reads.length,0);
stage='floor layout persistence and viewport retention';await session.goto('/FloorPlans/Edit/'+plan);const floorWidth=p.locator('[data-floor-width]').first();await floorWidth.evaluate(e=>{for(let node=e.parentElement;node;node=node.parentElement)if(node.tagName==='DETAILS')node.open=true;});const savedFloorWidth=Number(await floorWidth.inputValue())+1;await floorWidth.fill(String(savedFloorWidth));reads.length=0;await Promise.all([p.waitForResponse(r=>r.url().includes('/FloorPlans/SaveLayout')&&r.status()===200),p.locator('[data-save-layout-button]').first().click()]);await a.waitForFunction(w=>Number(document.querySelector('[data-floor-grid]').dataset.gridWidth)===w,savedFloorWidth);await a.waitForTimeout(300);assert.equal(reads.filter(r=>r.path==='/SpatialContext/Map').length,0);assert.equal(reads.filter(r=>r.page===b||r.page===c).length,0);assert.deepEqual(await snapshot(),before);
stage='held location saved-data update';await session.goto('/Locations/Edit/'+place);await p.locator('[name=Description]').fill('Saved description after refresh');await p.locator('form.pd-record-form button[type=submit]').first().click();await p.waitForURL('**/Locations/Details/*');await b.getByText('Saved description after refresh',{exact:true}).waitFor();assert.equal(await b.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),sceneId);
stage='date-only save targets Overview and preserves book isolation';await session.goto('/Scenes/SceneDetailsEditor?sceneId='+sceneId);const exact=await p.locator('[name=TimeModeID] option').evaluateAll(options=>options.find(o=>/exact/i.test(o.textContent))?.value);assert(exact);await p.locator('[name=TimeModeID]').selectOption(exact);await p.locator('[name=StartDateTime]').fill('2030-05-06T10:00');reads.length=0;await Promise.all([p.waitForResponse(r=>r.url().includes('/Scenes/SaveSceneDetails')&&r.status()===200),p.getByRole('button',{name:'Save details',exact:true}).click()]);await b.waitForFunction(()=>document.querySelector('[data-context-pane="1"]').textContent.includes('2030'));await b.waitForTimeout(300);assert.equal(reads.filter(r=>r.page===a||r.page===c).length,0,'date-only save does not refresh spatial or other-book panes');
stage='book-scoped intent and isolation';await session.goto('/Scenes/Edit/'+sceneId);reads.length=0;await session.post('/Scenes/SaveScenePurpose',{SceneID:sceneId,ScenePurposeNotes:'Saved acceptance purpose',SceneOutcomeNotes:'Saved acceptance outcome'});await b.waitForTimeout(700);assert.equal(reads.filter(r=>r.page===c).length,0);assert.equal(reads.filter(r=>r.page===a).length,0,'intent does not refresh spatial panes');
stage='existing main window navigation';await p.waitForTimeout(600);const held=b.url();await b.getByRole('link',{name:'Location Details',exact:true}).click();await p.waitForURL('**/Locations/Details/'+place);assert.equal(b.url(),held);assert.equal(await b.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),sceneId);
await session.close();session=null;
stage='fresh normal login and durable reload';session=await open();await session.goto(`/Maps?projectId=${project}&id=${map}`);await session.page.waitForFunction(w=>window.PlotDirectorMapWorkspace?.document.features[0].width===w,savedWidth);await session.goto('/FloorPlans/Edit/'+plan);assert.equal(Number(await session.page.locator('[data-floor-width]').first().inputValue()),savedFloorWidth);await session.goto('/Locations/Edit/'+place);assert.equal(await session.page.locator('[name=Description]').inputValue(),'Saved description after refresh');await session.goto('/Scenes/SceneDetailsEditor?sceneId='+sceneId);assert.match(await session.page.locator('[name=StartDateTime]').inputValue(),/^2030-05-06T10:00/);await session.goto('/Scenes/ScenePurposeEditor?sceneId='+sceneId);assert.equal(await session.page.locator('[name=ScenePurposeNotes]').inputValue(),'Saved acceptance purpose');
console.log(JSON.stringify({passed:true,project,book,otherBook,sceneId,map,plan,checks:['real committed map geometry','unsaved and failed saves silent','floor layout and map/floor viewport retention','held saved location refresh','book isolation','date-only targeting','relevant panels only','existing main navigation','fresh-login persistence'],featureUrl:`https://dev.plotdirector.com/Writing/Context?bookId=${book}&sceneId=${sceneId}&pinned=true`}));
}catch{console.error('Development Context acceptance failed at '+stage+'; no credentials logged.');process.exitCode=1;}
finally{if(session){try{await session.cleanup();console.log('PASS disposable project cleanup');}catch{console.error('Cleanup incomplete; preserve journal and resume documented scoped cleanup.');process.exitCode=1;}finally{await session.close();}}}
})();

View File

@ -0,0 +1,45 @@
// Actual Context shell, reusable spatial partials and renderers; synthetic read-only fixtures.
const {chromium}=require('playwright'),assert=require('node:assert/strict');
const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{
const browser=await chromium.launch();let step='setup';
try{
const context=await browser.newContext({viewport:{width:1440,height:1000}}),reads=[],writes=[],errors=[];
await context.route('**/native-companion/**',r=>r.fulfill({json:[]}));
await context.route('**/SharedFocus/**',r=>r.fulfill({json:{}}));
await context.route('**/Writing/Context/Position*',r=>r.fulfill({json:{connected:false}}));
await context.route('**/Writing/Context/MyWindows*',r=>r.fulfill({json:[]}));
await context.route('**/Writing/Context/Tabs/*',r=>{
const u=new URL(r.request().url());return r.fulfill({contentType:'text/html',body:`<div data-context-tab-fragment data-project-id="7" data-book-id="12" data-chapter-id="${u.searchParams.get('chapterId')}" data-scene-id="${u.searchParams.get('sceneId')}">Saved ${u.pathname.split('/').at(-1)}</div>`});
});
context.on('request',r=>{const path=new URL(r.url()).pathname;if(r.method()==='POST'&&!path.startsWith('/hubs/')&&path!=='/NarrativeFocus/Shared/Validate')writes.push(path);if(path.startsWith('/SpatialContext/')||path.includes('/Context/Tabs/'))reads.push({page:r.frame().page(),path});});
const page=await context.newPage();page.on('pageerror',e=>errors.push(e.message));
const tab=(p,i,value)=>p.selectOption(`[data-context-pane="${i}"] [data-context-tab]`,value);
const stable=()=>page.waitForTimeout(250);
const notify=(p,hints)=>p.evaluate(hints=>{for(const hint of hints)document.querySelector('[data-context-workspace]').contextController.invalidate(hint);},hints);
const hint=kind=>({projectId:7,bookId:12,kind,entityId:1});
await page.goto(base+'/Writing/Context?pinned=true');await page.locator('[data-context-pane="0"] [data-context-tab-fragment]').waitFor();
await page.selectOption('[data-context-layout]','columns');await tab(page,1,'maps');await page.locator('iframe').waitFor();await stable();
const before=await page.evaluate(()=>({...document.querySelector('[data-context-workspace]').contextController.position}));
step='map bursts only refresh map, one state read';reads.length=0;
await notify(page,Array.from({length:8},()=>hint('maps')));await stable();
assert.equal(reads.filter(r=>r.path.includes('/Tabs/')).length,0);
assert.equal(reads.filter(r=>r.path==='/SpatialContext/State').length,1);
step='scope isolation';reads.length=0;
await notify(page,[{...hint('maps'),projectId:8},{...hint('maps'),bookId:13}]);await stable();assert.equal(reads.length,0);
step='unrelated dates do not refresh spatial pane';reads.length=0;
await notify(page,[hint('dates')]);await stable();assert.equal(reads.filter(r=>r.path.startsWith('/SpatialContext/')).length,0);assert.equal(reads.filter(r=>r.path.toLowerCase().includes('/tabs/overview')).length,1);
step='hidden panel deferred until shown';await tab(page,1,'characters');await stable();reads.length=0;
await notify(page,[hint('maps')]);await stable();assert.equal(reads.length,0);
await tab(page,1,'maps');await stable();assert.equal(reads.filter(r=>r.path==='/SpatialContext/State').length,1);
step='two visible map panes share state read';await tab(page,0,'maps');await page.locator('[data-context-pane="0"] iframe').waitFor();await stable();reads.length=0;
await notify(page,[hint('maps'),hint('maps')]);await stable();assert.equal(reads.filter(r=>r.path==='/SpatialContext/State').length,1);
step='separate windows independently refresh while held';const second=await context.newPage();second.on('pageerror',e=>errors.push(e.message));await second.goto(base+'/Writing/Context?pinned=true');await tab(second,0,'locations');await second.getByRole('heading',{name:'Bedroom',exact:true}).waitFor();await stable();reads.length=0;
await Promise.all([notify(page,[hint('locations')]),notify(second,[hint('locations')])]);await stable();
assert.equal(reads.filter(r=>r.path==='/SpatialContext/State'&&r.page===page).length,1);
assert.equal(reads.filter(r=>r.path==='/SpatialContext/State'&&r.page===second).length,1);
assert.deepEqual(await page.evaluate(()=>({...document.querySelector('[data-context-workspace]').contextController.position})),before);
assert.deepEqual(writes,[],'passive refresh never posts a manuscript/Word navigation');assert.deepEqual(errors,[]);
console.log('PASS saved-data refresh: category targeting, burst coalescing, project/book isolation, deferred hidden panels, shared split reads, independent held windows, no narrative writes.');
}catch(e){console.error('FAIL '+step,e);process.exitCode=1;}finally{await browser.close();}
})();

View File

@ -0,0 +1,65 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging.Abstractions;
using PlotLine.Hubs;
using PlotLine.Services;
using System.Text.Json;
internal static class ContextSavedDataTests
{
public static async Task Run()
{
var packets = new List<string>();
var client = NativeWorkflowTests.Proxy<IClientProxy>((_, args) =>
{
if ((string)args![0]! != "ContextInvalidated") throw new Exception("Saved data must not change manuscript position.");
packets.Add(JsonSerializer.Serialize(((object?[])args[1]!)[0]));
return Task.CompletedTask;
});
var clients = NativeWorkflowTests.Proxy<IHubClients>((_, args) =>
{
if ((string)args![0]! != NativeCompanionPresenceHub.UserGroup(7)) throw new Exception("Wrong account group.");
return client;
});
var hub = NativeWorkflowTests.Proxy<IHubContext<NativeCompanionPresenceHub>>((_, _) => clients);
var accessor = new HttpContextAccessor();
var notices = new ContextWorkspaceNotifications(hub, NullLogger<ContextWorkspaceNotifications>.Instance, accessor);
var filter = new ContextReferenceInvalidationFilter(notices);
foreach (var outcome in new[] { "preview", "saved", "badrequest", "invalid", "response400", "exception" })
{
accessor.HttpContext = new DefaultHttpContext();
var action = new ActionContext(accessor.HttpContext, new RouteData(), new ActionDescriptor());
var filters = new List<IFilterMetadata>();
var controller = new object();
var executing = new ActionExecutingContext(action, filters, new Dictionary<string, object?>(), controller);
var before = packets.Count;
await filter.OnActionExecutionAsync(executing, async () =>
{
if (outcome != "preview")
{
await notices.Invalidate(7, bookId:12, projectId:3, kind:"maps", entityId:44, entityType:"Map");
await notices.Invalidate(7, bookId:12, projectId:3, kind:"maps", entityId:44, entityType:"Map");
if (packets.Count != before) throw new Exception("Hint escaped before action completed.");
}
if (outcome == "invalid") action.ModelState.AddModelError("Name", "Invalid");
if (outcome == "response400") accessor.HttpContext.Response.StatusCode = 400;
return new ActionExecutedContext(action, filters, controller)
{
Result = outcome == "badrequest" ? new BadRequestResult() : new JsonResult(new { saved = true }),
Exception = outcome == "exception" ? new InvalidOperationException("Synthetic failed save") : null
};
});
if (packets.Count - before != (outcome == "saved" ? 1 : 0)) throw new Exception("Save/failed/preview notification boundary: " + outcome);
}
using var json = JsonDocument.Parse(packets.Single());
var hint = json.RootElement;
if (hint.GetProperty("projectId").GetInt32()!=3 || hint.GetProperty("bookId").GetInt32()!=12 ||
hint.GetProperty("kind").GetString()!="maps" || hint.GetProperty("entityId").GetInt32()!=44 ||
hint.EnumerateObject().Count()!=7) throw new Exception("Hints must contain scoped identifiers only.");
accessor.HttpContext = null;
}
}

View File

@ -217,6 +217,7 @@ if(args.Contains("--discretionary-ai")){await DiscretionaryAiTests.Run();return;
if(args.Contains("--context-names")){await ContextNamesTests.Run();return;}
if(args.Contains("--context-relationships")){await ContextRelationshipTests.Run();return;}
if(args.Contains("--context-characters")){await ContextCharacterTests.Run();return;}
if(args.Contains("--context-saved-data")){await ContextSavedDataTests.Run();return;}
if(args.Contains("--context-windows")){ContextWindowsTests.Run();return;}
if(args.Contains("--focus-diagnostics")){SharedFocusDiagnosticsTests.Run();return;}
@ -239,6 +240,7 @@ var tests = new (string Name, Action Test)[]
("Context relationship state and focused editing",()=>ContextRelationshipTests.Run().GetAwaiter().GetResult()),
("Context character narrative projection and focused editing",()=>ContextCharacterTests.Run().GetAwaiter().GetResult()),
("Context My Windows routing and lifecycle",ContextWindowsTests.Run),
("Context committed-save notifications and scope",()=>ContextSavedDataTests.Run().GetAwaiter().GetResult()),
("Context main-page navigation safety and delegated link coverage",ContextWorkspaceNavigationTests.Run),
("Bounded opt-in shared focus diagnostics",SharedFocusDiagnosticsTests.Run),
("Settlement boundaries preserve anchors, routes and backup/import contracts",MapSettlementTests.Run),

View File

@ -6,7 +6,7 @@ using PlotLine.ViewModels;
namespace PlotLine.Controllers;
[Authorize]
public sealed class ChaptersController(IChapterService chapters) : Controller
public sealed class ChaptersController(IChapterService chapters, ContextSavedData savedData) : Controller
{
public async Task<IActionResult> Details(int id)
{
@ -41,6 +41,7 @@ public sealed class ChaptersController(IChapterService chapters) : Controller
try
{
chapterId = await chapters.SaveAsync(model);
await savedData.Chapter(chapterId);
}
catch (SubscriptionLimitException ex) when (model.ChapterID == 0)
{
@ -67,6 +68,7 @@ public sealed class ChaptersController(IChapterService chapters) : Controller
public async Task<IActionResult> SetScenesPov(int chapterId, int? povCharacterId, bool overwriteAuthor)
{
var updated = await chapters.SetScenesPovAsync(chapterId, povCharacterId, overwriteAuthor);
if (updated > 0) await savedData.Chapter(chapterId, "characters");
TempData["ChapterMessage"] = $"POV updated on {updated:N0} scene{(updated == 1 ? string.Empty : "s")}.";
return RedirectToAction(nameof(Details), new { id = chapterId });
}
@ -77,6 +79,7 @@ public sealed class ChaptersController(IChapterService chapters) : Controller
{
try
{
await savedData.Chapter(id);
await chapters.ArchiveAsync(id);
}
catch (InvalidOperationException ex)

View File

@ -71,7 +71,7 @@ public sealed class CharacterAttributesController(IProjectRepository projects,IC
{
var versions=rows.ToDictionary(c=>c.CharacterID,c=>c.UpdatedDate.ToString("O"));
undoToken=protection.CreateProtector("CharacterQuickAttributes.Undo.v1").Protect(JsonSerializer.Serialize(new UndoReceipt(author,projectId,attribute,before.Select(c=>new UndoChange(c.Id,c.Value,c.Sex,versions[c.Id])).ToArray(),DateTime.UtcNow.AddMinutes(10))));
await notifications.Invalidate(author,projectId:projectId,kind:"characters");
foreach(var row in rows) await notifications.Invalidate(author,projectId:projectId,kind:"characters",entityId:row.CharacterID,entityType:"Character");
}
return Json(new {saved=true,characters=rows.Select(CharacterQuickAttributes.Snapshot),undoToken});
}

View File

@ -6,7 +6,7 @@ using PlotLine.ViewModels;
namespace PlotLine.Controllers;
[Authorize]
public sealed class FloorPlansController(IFloorPlanService floorPlans) : Controller
public sealed class FloorPlansController(IFloorPlanService floorPlans, ContextSavedData savedData) : Controller
{
public async Task<IActionResult> Index(int projectId)
{
@ -30,6 +30,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
}
var floorPlanId = await floorPlans.SavePlanAsync(model);
await savedData.FloorPlan(floorPlanId);
return RedirectToAction(nameof(Edit), new { id = floorPlanId });
}
@ -50,6 +51,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
}
var floorPlanId = await floorPlans.SavePlanAsync(model);
await savedData.FloorPlan(floorPlanId);
TempData["FloorPlanMessage"] = "Floor plan saved.";
return RedirectToAction(nameof(Edit), new { id = floorPlanId });
}
@ -62,6 +64,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
try
{
await floorPlans.SaveLayoutAsync(model);
await savedData.FloorPlan(model.FloorPlan.FloorPlanID);
if (isAsyncSave)
{
return Json(new { ok = true, message = "Saved" });
@ -87,6 +90,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeletePlan(int id, int projectId)
{
await savedData.FloorPlan(id);
await floorPlans.DeletePlanAsync(id);
TempData["FloorPlanMessage"] = "Floor plan deleted.";
return RedirectToAction(nameof(Index), new { projectId });
@ -99,6 +103,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
if (ModelState.IsValid)
{
await floorPlans.SaveFloorAsync(model);
await savedData.FloorPlan(model.FloorPlanID);
TempData["FloorPlanMessage"] = "Floor added.";
}
@ -110,6 +115,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
public async Task<IActionResult> DeleteFloor(int floorPlanId, int floorPlanFloorId)
{
await floorPlans.DeleteFloorAsync(floorPlanFloorId);
await savedData.FloorPlan(floorPlanId);
TempData["FloorPlanMessage"] = "Floor deleted.";
return RedirectToAction(nameof(Edit), new { id = floorPlanId });
}
@ -125,6 +131,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
}
var result = await floorPlans.UploadBackgroundAsync(floorPlanId, floorPlanFloorId, backgroundImage);
if (result.Succeeded) await savedData.FloorPlan(floorPlanId);
TempData[result.Succeeded ? "FloorPlanMessage" : "FloorPlanError"] = result.Succeeded
? "Background image uploaded."
: result.ErrorMessage ?? "Background image could not be uploaded.";
@ -139,6 +146,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
try
{
await floorPlans.SaveBackgroundSettingsAsync(model);
await savedData.FloorPlan(model.FloorPlanID);
if (isAsyncSave)
{
return Json(new { ok = true, message = "Saved" });
@ -165,6 +173,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
public async Task<IActionResult> ResetBackground(int floorPlanId, int floorPlanFloorId)
{
await floorPlans.ResetBackgroundAsync(floorPlanId, floorPlanFloorId);
await savedData.FloorPlan(floorPlanId);
TempData["FloorPlanMessage"] = "Background position reset.";
return RedirectToAction(nameof(Edit), new { id = floorPlanId });
}
@ -174,6 +183,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
public async Task<IActionResult> RemoveBackground(int floorPlanId, int floorPlanFloorId)
{
await floorPlans.RemoveBackgroundAsync(floorPlanId, floorPlanFloorId);
await savedData.FloorPlan(floorPlanId);
TempData["FloorPlanMessage"] = "Background image removed.";
return RedirectToAction(nameof(Edit), new { id = floorPlanId });
}
@ -187,6 +197,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
if (ModelState.IsValid)
{
await floorPlans.SaveTransitionAsync(floorPlanId, model);
await savedData.FloorPlan(floorPlanId);
TempData["FloorPlanMessage"] = model.FloorPlanTransitionID == 0 ? "Transition created." : "Transition updated.";
}
}
@ -205,6 +216,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
try
{
await floorPlans.DeleteTransitionAsync(floorPlanId, floorPlanTransitionId);
await savedData.FloorPlan(floorPlanId);
TempData["FloorPlanMessage"] = "Transition deleted.";
}
catch (InvalidOperationException ex)
@ -225,6 +237,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
if (ModelState.IsValid)
{
var floorPlanBlockId = await floorPlans.SaveBlockAsync(model);
await savedData.FloorPlan(floorPlanId);
if (isAsyncSave)
{
var block = await floorPlans.GetBlockAsync(floorPlanBlockId);
@ -288,6 +301,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
try
{
await floorPlans.LinkBlockLocationAsync(floorPlanId, blockId, roomName);
await savedData.FloorPlan(floorPlanId);
return Json(new { ok = true });
}
catch (InvalidOperationException ex)
@ -301,6 +315,7 @@ public sealed class FloorPlansController(IFloorPlanService floorPlans) : Control
public async Task<IActionResult> DeleteBlock(int floorPlanId, int floorPlanBlockId)
{
await floorPlans.DeleteBlockAsync(floorPlanBlockId);
await savedData.FloorPlan(floorPlanId);
TempData["FloorPlanMessage"] = "Block deleted.";
return RedirectToAction(nameof(Edit), new { id = floorPlanId });
}

View File

@ -115,7 +115,7 @@ public sealed class LocationWorkspaceController(ISqlConnectionFactory connection
UserID = user.UserId, input.Attribute, Changes = JsonSerializer.Serialize(input.Changes), Restore = restore }, commandType: CommandType.StoredProcedure)).ToArray();
string? undoToken = previous.Length == 0 ? null : Protector.Protect(JsonSerializer.Serialize(new Receipt(user.UserId!.Value,
input.ProjectId, input.Attribute, previous, DateTime.UtcNow.AddMinutes(10))));
if (previous.Length > 0) await notifications.Invalidate(user.UserId!.Value, projectId: input.ProjectId, kind: "locations");
foreach (var change in previous) await notifications.Invalidate(user.UserId!.Value, projectId: input.ProjectId, kind: "locations", entityId: change.Id, entityType: "Location");
return Json(new { saved = true, undoToken, changes = previous.Select(c => new { c.Id, c.Version, value = input.Attribute == "type" && int.TryParse(input.Changes.Single(i => i.Id == c.Id).Value, out var typeId) ? typeId.ToString() : input.Changes.Single(i => i.Id == c.Id).Value }), attribute = input.Attribute });
}
catch (SqlException e) when (e.Number is 51010 or 51011 or 51012)
@ -138,7 +138,7 @@ public sealed class LocationWorkspaceController(ISqlConnectionFactory connection
parameters.Add("SourceVersion", sourceVersion, DbType.DateTime2);
parameters.Add("TargetVersion", targetVersion, DbType.DateTime2);
await db.QuerySingleAsync<EntityMergeResult>("dbo.Location_WorkspaceMerge", parameters, commandType: CommandType.StoredProcedure);
await notifications.Invalidate(author, projectId: input.ProjectId, kind: "locations");
await notifications.Invalidate(author, projectId: input.ProjectId, kind: "locations", entityId: input.TargetId, entityType: "Location");
return Json(new { id = input.TargetId });
}
catch (SqlException e) when (e.Number is 51000 or 51010 or 51011 or 51012)
@ -154,7 +154,7 @@ public sealed class LocationWorkspaceController(ISqlConnectionFactory connection
{
using var db = connections.CreateConnection();
var id = await db.QuerySingleAsync<int>("dbo.Location_WorkspaceCreate", new { ProjectID = input.ProjectId, UserID = author, input.Name, ParentID = input.ParentId }, commandType: CommandType.StoredProcedure);
await notifications.Invalidate(author, projectId: input.ProjectId, kind: "locations");
await notifications.Invalidate(author, projectId: input.ProjectId, kind: "locations", entityId: id, entityType: "Location");
return Json(new { id });
}
catch (SqlException e) when (e.Number is 51010 or 51012)

View File

@ -7,7 +7,7 @@ using PlotLine.ViewModels;
namespace PlotLine.Controllers;
[Authorize]
public sealed class LocationsController(ILocationService locations, GeographicHierarchyService geography, IProjectRepository projects, ICurrentUserService currentUser) : Controller
public sealed class LocationsController(ILocationService locations, GeographicHierarchyService geography, IProjectRepository projects, ICurrentUserService currentUser, ContextSavedData savedData) : Controller
{
public async Task<IActionResult> Index(int projectId)
{
@ -77,6 +77,7 @@ public sealed class LocationsController(ILocationService locations, GeographicHi
try
{
await locations.ReparentAsync(projectId, locationId, parentLocationId, expectedParentLocationId);
await savedData.Project(projectId, "locations", locationId, "Location");
TempData["GeographyMessage"] = await geography.SubmitAsync(projectId, locationId);
if (IsAjaxRequest())
{
@ -198,7 +199,9 @@ public sealed class LocationsController(ILocationService locations, GeographicHi
[ValidateAntiForgeryToken]
public async Task<IActionResult> ArchiveRelationship(int id, int returnLocationId)
{
var location = await locations.GetEditAsync(returnLocationId);
await locations.ArchiveRelationshipAsync(id);
if (location is not null) await savedData.Project(location.ProjectID, "locations", id, "Location Relationship");
TempData["ArchiveMessage"] = "Location relationship archived.";
return RedirectToAction(nameof(Details), new { id = returnLocationId });
}

View File

@ -8,7 +8,7 @@ namespace PlotLine.Controllers;
[Authorize]
public sealed class MapsController(MapRepository maps, IProjectRepository projects, ILocationRepository locations,
IFloorPlanRepository floorPlans, IProjectAccessService access, ICurrentUserService currentUser) : Controller
IFloorPlanRepository floorPlans, IProjectAccessService access, ICurrentUserService currentUser, ContextSavedData? savedData = null) : Controller
{
private int UserID => currentUser.UserId!.Value;
public async Task<IActionResult> Index(int projectId, int? id, bool detached = false, Guid? featureId = null)
@ -37,7 +37,9 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec
{
if (!await access.CanAccessProjectAsync(model.ProjectID)) return NotFound();
if (!ModelState.IsValid || !MapValidation.Kinds.Contains(model.Kind)) return BadRequest("Choose a map name and kind.");
try { return Json(new { id = await maps.CreateAsync(model, UserID) }); }
try { var id = await maps.CreateAsync(model, UserID);
if (savedData is not null) await savedData.Project(model.ProjectID, "maps", id, "Map");
return Json(new { id }); }
catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); }
}
[HttpPost, ValidateAntiForgeryToken, RequestSizeLimit(8_000_000)]
@ -51,7 +53,12 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec
try
{
await maps.SaveAsync(document, UserID);
return Json(await maps.GetAsync(document.Map.ProjectID, document.Map.MapID, UserID));
if (savedData is not null) await savedData.Project(document.Map.ProjectID, "maps", document.Map.MapID, "Map");
var saved = await maps.GetAsync(document.Map.ProjectID, document.Map.MapID, UserID);
if (savedData is not null && saved is not null)
foreach (var feature in saved.Features.Where(f => f.LocationID.HasValue && document.Features.Any(before => before.FeatureID == f.FeatureID && before.CreateLocation)))
await savedData.Project(document.Map.ProjectID, "locations", feature.LocationID, "Location");
return Json(saved);
}
catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); }
}
@ -59,7 +66,8 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec
public async Task<IActionResult> Delete(int projectId, int id, int revision)
{
if (!await access.CanAccessProjectAsync(projectId)) return NotFound();
try { await maps.DeleteAsync(projectId, id, revision, UserID); return Json(new { ok = true }); }
try { await maps.DeleteAsync(projectId, id, revision, UserID);
if (savedData is not null) await savedData.Project(projectId, "maps", id, "Map"); return Json(new { ok = true }); }
catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); }
}
[HttpGet]
@ -77,7 +85,8 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec
if (!ModelState.IsValid || note is null || note.TravelMethod?.Length > 80 || note.TypicalMinutes is < 1 or > 525600) return BadRequest(new { message = "Check journey annotations." });
var projection = await story.GetAsync(projectId, note.MapID, UserID, scenarioId);
if (projection is null || !projection.Legs.Any(l => l.CharacterID == note.CharacterID && l.FromSceneID == note.FromSceneID && l.ToSceneID == note.ToSceneID)) return NotFound();
try { await repository.SaveJourneyAsync(projectId, UserID, note); return Json(new { ok = true }); }
try { await repository.SaveJourneyAsync(projectId, UserID, note);
if (savedData is not null) await savedData.Project(projectId, "maps", note.MapID, "Map"); return Json(new { ok = true }); }
catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); }
}

View File

@ -8,7 +8,7 @@ using PlotLine.ViewModels;
namespace PlotLine.Controllers;
[Authorize]
public sealed class RelationshipMapController(IRelationshipMapService relationshipMap, ICharacterRepository repository, ICharacterService characters, IProjectRepository projectAccess, ICurrentUserService user, ContextWorkspaceNotifications notifications) : Controller
public sealed class RelationshipMapController(IRelationshipMapService relationshipMap, ICharacterRepository repository, ICharacterService characters, IProjectRepository projectAccess, ICurrentUserService user, ContextWorkspaceNotifications notifications, ContextSavedData? savedData = null) : Controller
{
public async Task<IActionResult> Index(int projectId, int? bookId, int? chapterId, int? sceneId, int? focusCharacterId, bool showFullNetwork = false)
{
@ -120,7 +120,8 @@ public sealed class RelationshipMapController(IRelationshipMapService relationsh
InitialIntensity = model.Intensity, IsReciprocal = model.Mutual, ReaderInitiallyKnows = model.Known, Notes = model.Notes
});
}
if (user.UserId is int author) await notifications.Invalidate(author, projectId: model.ProjectID, kind: "relationships");
if (model.SceneID is int scene && savedData is not null) await savedData.Scene(scene, "relationships");
else if (user.UserId is int author) await notifications.Invalidate(author, projectId: model.ProjectID, kind: "relationships", entityId: existing?.CharacterRelationshipID ?? model.SourceID, entityType: existing is null ? "Character" : "Relationship");
return Ok();
}
}

View File

@ -20,7 +20,7 @@ public sealed class ScenesController(
IUploadStorageService uploadStorage,
ICompositeViewEngine viewEngine,
SharedManuscriptFocus? sharedFocus = null,
ICurrentUserService? currentUser = null) : Controller
ICurrentUserService? currentUser = null, ContextSavedData? savedData = null) : Controller
{
private const long MaxAttachmentBytes = 25 * 1024 * 1024;
@ -58,6 +58,7 @@ public sealed class ScenesController(
try
{
sceneId = await scenes.SaveAsync(model);
if (savedData is not null) await savedData.Scene(sceneId, "structure");
}
catch (SubscriptionLimitException ex) when (model.SceneID == 0)
{
@ -271,6 +272,16 @@ public sealed class ScenesController(
return NotFound();
}
var changedKinds = new HashSet<string>();
if (current.SceneNumber != model.SceneNumber || current.SceneTitle != model.SceneTitle) changedKinds.Add("structure");
if (current.Summary != model.Summary || current.RevisionStatusID != model.RevisionStatusID) changedKinds.Add("overview");
if (current.PrimaryLocationID != model.PrimaryLocationID) changedKinds.Add("locations");
if (current.POVCharacterID != model.POVCharacterID) changedKinds.Add("characters");
if (current.TimeModeID != model.TimeModeID || current.TimeConfidenceID != model.TimeConfidenceID ||
current.StartDateTime != model.StartDateTime || current.EndDateTime != model.EndDateTime ||
current.DurationAmount != model.DurationAmount || current.DurationUnitID != model.DurationUnitID ||
current.RelativeTimeText != model.RelativeTimeText) changedKinds.Add("dates");
current.SceneNumber = model.SceneNumber;
current.SceneTitle = model.SceneTitle;
current.RevisionStatusID = model.RevisionStatusID;
@ -286,6 +297,7 @@ public sealed class ScenesController(
await scenes.SaveAsync(current);
await scenes.UpdatePovCharacterAsync(model.SceneID, model.POVCharacterID);
if (savedData is not null) foreach (var kind in changedKinds) await savedData.Scene(model.SceneID, kind);
var updated = await scenes.GetEditAsync(model.SceneID);
if (updated is null)
@ -328,6 +340,7 @@ public sealed class ScenesController(
current.SceneOutcomeNotes = model.SceneOutcomeNotes;
await scenes.SaveAsync(current);
if (savedData is not null) await savedData.Scene(model.SceneID, "intent");
var updated = await scenes.GetEditAsync(model.SceneID);
if (updated is null)
@ -366,6 +379,7 @@ public sealed class ScenesController(
}
await scenes.SaveAsync(current);
if (savedData is not null) await savedData.Scene(model.SceneID, "metrics");
var updated = await scenes.GetEditAsync(model.SceneID);
if (updated is null)
@ -424,6 +438,7 @@ public sealed class ScenesController(
if (row.Remove)
{
await characters.DeleteSceneCharacterAsync(row.SceneCharacterID);
if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
continue;
}
@ -443,6 +458,7 @@ public sealed class ScenesController(
EmotionalState = row.EmotionalState,
KnowledgeNotes = row.KnowledgeNotes
});
if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
}
if (addCharacterId > 0)
@ -452,6 +468,7 @@ public sealed class ScenesController(
model.NewCharacter.ReturnProjectID = current.ReturnProjectID;
model.NewCharacter.ReturnBookID = current.ReturnBookID;
await characters.AddSceneCharacterAsync(model.NewCharacter);
if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
}
var updatedBeforePov = await scenes.GetEditAsync(model.SceneID);
@ -467,6 +484,7 @@ public sealed class ScenesController(
}
await scenes.UpdatePovCharacterAsync(model.SceneID, model.POVCharacterID);
if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
var updated = await scenes.GetEditAsync(model.SceneID);
if (updated is null)
@ -510,6 +528,7 @@ public sealed class ScenesController(
current.PrimaryLocationID = model.PrimaryLocationID;
await scenes.SaveAsync(current);
if (savedData is not null) await savedData.Scene(model.SceneID, "locations");
var updated = await scenes.GetEditAsync(model.SceneID);
if (updated is null)
@ -582,6 +601,7 @@ public sealed class ScenesController(
if (row.Remove)
{
await assets.DeleteAssetEventAsync(row.AssetEventID);
if (savedData is not null) await savedData.Scene(model.SceneID, "assets");
}
}
@ -593,6 +613,7 @@ public sealed class ScenesController(
model.NewAssetEvent.ReturnProjectID = current.ReturnProjectID;
model.NewAssetEvent.ReturnBookID = current.ReturnBookID;
await assets.AddAssetEventAsync(model.NewAssetEvent);
if (savedData is not null) await savedData.Scene(model.SceneID, "assets");
}
var updated = await scenes.GetEditAsync(model.SceneID);
@ -642,6 +663,7 @@ public sealed class ScenesController(
if (note.Remove)
{
await writerWorkspace.DeleteNoteAsync(note.SceneNoteID);
if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
continue;
}
@ -667,6 +689,7 @@ public sealed class ScenesController(
IsPinned = note.IsPinned,
IsResolved = note.IsResolved
});
if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
}
var hasNewNoteContent = !string.IsNullOrWhiteSpace(model.NewNote.NoteTitle)
@ -685,6 +708,7 @@ public sealed class ScenesController(
model.NewNote.SceneID = model.SceneID;
await writerWorkspace.SaveNoteAsync(model.NewNote);
if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
}
var updated = await scenes.GetEditAsync(model.SceneID);
@ -729,6 +753,7 @@ public sealed class ScenesController(
if (item.Remove)
{
await writerWorkspace.DeleteChecklistItemAsync(item.SceneChecklistItemID);
if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
continue;
}
@ -746,12 +771,14 @@ public sealed class ScenesController(
IsCompleted = item.IsCompleted,
SortOrder = item.SortOrder
});
if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
}
if (!string.IsNullOrWhiteSpace(model.NewChecklistItem.ItemText))
{
model.NewChecklistItem.SceneID = model.SceneID;
await writerWorkspace.SaveChecklistItemAsync(model.NewChecklistItem);
if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
}
var updated = await scenes.GetEditAsync(model.SceneID);
@ -786,6 +813,7 @@ public sealed class ScenesController(
}
await writerWorkspace.SaveSceneWorkflowAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
var updated = await scenes.GetEditAsync(model.SceneID);
if (updated is null)
@ -816,6 +844,7 @@ public sealed class ScenesController(
try
{
await scenes.ArchiveAsync(id);
if (savedData is not null) await savedData.Chapter(chapterId, "structure");
}
catch (InvalidOperationException ex)
{
@ -837,6 +866,7 @@ public sealed class ScenesController(
public async Task<IActionResult> MoveUp(int id, int chapterId)
{
await scenes.MoveAsync(id, "Up");
if (savedData is not null) await savedData.Chapter(chapterId, "structure");
return RedirectToAction("Details", "Chapters", new { id = chapterId });
}
@ -845,6 +875,7 @@ public sealed class ScenesController(
public async Task<IActionResult> MoveDown(int id, int chapterId)
{
await scenes.MoveAsync(id, "Down");
if (savedData is not null) await savedData.Chapter(chapterId, "structure");
return RedirectToAction("Details", "Chapters", new { id = chapterId });
}
@ -855,6 +886,7 @@ public sealed class ScenesController(
try
{
await plots.AddThreadEventAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "threads");
}
catch (InvalidOperationException ex)
{
@ -881,6 +913,7 @@ public sealed class ScenesController(
try
{
await plots.UpdateThreadEventAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "threads");
}
catch (InvalidOperationException ex)
{
@ -905,6 +938,7 @@ public sealed class ScenesController(
public async Task<IActionResult> DeleteThreadEvent(int id, int sceneId, int? projectId, int? bookId)
{
await plots.DeleteThreadEventAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "threads");
if (IsAjaxRequest())
{
return await SceneStoryRefreshJsonAsync(sceneId);
@ -918,6 +952,7 @@ public sealed class ScenesController(
public async Task<IActionResult> AddAssetEvent(AssetEventCreateViewModel model)
{
await assets.AddAssetEventAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "assets");
return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID);
}
@ -926,6 +961,7 @@ public sealed class ScenesController(
public async Task<IActionResult> DeleteAssetEvent(int id, int sceneId, int? projectId, int? bookId)
{
await assets.DeleteAssetEventAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "assets");
return RedirectForScene(sceneId, projectId, bookId);
}
@ -934,6 +970,7 @@ public sealed class ScenesController(
public async Task<IActionResult> AddAssetCustodyEvent(AssetCustodyCreateViewModel model)
{
await assets.AddCustodyEventAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "assets");
return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID);
}
@ -942,6 +979,7 @@ public sealed class ScenesController(
public async Task<IActionResult> AddSceneAssetLocation(SceneAssetLocationCreateViewModel model)
{
await locations.SaveSceneAssetLocationAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "locations");
return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID);
}
@ -950,6 +988,7 @@ public sealed class ScenesController(
public async Task<IActionResult> DeleteSceneAssetLocation(int id, int sceneId, int? projectId, int? bookId)
{
await locations.DeleteSceneAssetLocationAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "locations");
return RedirectForScene(sceneId, projectId, bookId);
}
@ -958,6 +997,7 @@ public sealed class ScenesController(
public async Task<IActionResult> DeleteAssetCustodyEvent(int id, int sceneId, int? projectId, int? bookId)
{
await assets.DeleteCustodyEventAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "assets");
return RedirectForScene(sceneId, projectId, bookId);
}
@ -968,6 +1008,7 @@ public sealed class ScenesController(
try
{
await characters.AddSceneCharacterAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
}
catch (InvalidOperationException ex)
{
@ -982,6 +1023,7 @@ public sealed class ScenesController(
public async Task<IActionResult> UpdateSceneCharacter(SceneCharacterEditViewModel model)
{
await characters.UpdateSceneCharacterAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID);
}
@ -990,6 +1032,7 @@ public sealed class ScenesController(
public async Task<IActionResult> DeleteSceneCharacter(int id, int sceneId, int? projectId, int? bookId)
{
await characters.DeleteSceneCharacterAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "characters");
return RedirectForScene(sceneId, projectId, bookId);
}
@ -1000,6 +1043,7 @@ public sealed class ScenesController(
try
{
await characters.AcceptSceneCharacterSuggestionAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "characters");
if (IsAjaxRequest())
{
return await SceneSuggestionsRefreshJsonAsync(sceneId, refreshPeople: true, refreshWorld: false);
@ -1025,6 +1069,7 @@ public sealed class ScenesController(
try
{
await characters.RejectSceneCharacterSuggestionAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "characters");
if (IsAjaxRequest())
{
return await SceneSuggestionsRefreshJsonAsync(sceneId, refreshPeople: true, refreshWorld: false);
@ -1050,6 +1095,7 @@ public sealed class ScenesController(
try
{
await assets.AcceptSceneAssetSuggestionAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "assets");
if (IsAjaxRequest())
{
return await SceneSuggestionsRefreshJsonAsync(sceneId, refreshPeople: true, refreshWorld: true);
@ -1075,6 +1121,7 @@ public sealed class ScenesController(
try
{
await assets.RejectSceneAssetSuggestionAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "assets");
if (IsAjaxRequest())
{
return await SceneSuggestionsRefreshJsonAsync(sceneId, refreshPeople: true, refreshWorld: true);
@ -1100,6 +1147,7 @@ public sealed class ScenesController(
try
{
await locations.AcceptSceneLocationSuggestionAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "locations");
if (IsAjaxRequest())
{
return await SceneSuggestionsRefreshJsonAsync(sceneId, refreshPeople: true, refreshWorld: true);
@ -1125,6 +1173,7 @@ public sealed class ScenesController(
try
{
await locations.RejectSceneLocationSuggestionAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "locations");
if (IsAjaxRequest())
{
return await SceneSuggestionsRefreshJsonAsync(sceneId, refreshPeople: true, refreshWorld: true);
@ -1148,6 +1197,7 @@ public sealed class ScenesController(
public async Task<IActionResult> AddSceneDependency(SceneDependencyCreateViewModel model)
{
await scenes.AddDependencyAsync(model);
if (savedData is not null) await savedData.Scene(model.CurrentSceneID, "structure");
if (IsAjaxRequest())
{
return await SceneStoryRefreshJsonAsync(model.CurrentSceneID);
@ -1161,6 +1211,7 @@ public sealed class ScenesController(
public async Task<IActionResult> DeleteSceneDependency(int id, int sceneId, int? projectId, int? bookId)
{
await scenes.DeleteDependencyAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "structure");
if (IsAjaxRequest())
{
return await SceneStoryRefreshJsonAsync(sceneId);
@ -1183,6 +1234,7 @@ public sealed class ScenesController(
public async Task<IActionResult> ConfirmMove(SceneMoveRequestViewModel model)
{
await scenes.MoveToChapterAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
if (TryGetLocalReturnUrl(model.ReturnUrl, out var returnUrl))
{
return LocalRedirect(returnUrl);
@ -1196,6 +1248,7 @@ public sealed class ScenesController(
public async Task<IActionResult> RenumberChapter(int chapterId, int? projectId, int? bookId, int? sceneId)
{
await scenes.RenumberChapterAsync(chapterId);
if (savedData is not null) await savedData.Chapter(chapterId, "structure");
return sceneId.HasValue
? RedirectForScene(sceneId.Value, projectId, bookId)
: RedirectToAction("Details", "Chapters", new { id = chapterId });
@ -1244,6 +1297,7 @@ public sealed class ScenesController(
}
await characters.AddAttributeEventAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
if (IsAjaxRequest())
{
return await SceneCharacterAttributesRefreshJsonAsync(model.SceneID);
@ -1277,6 +1331,7 @@ public sealed class ScenesController(
}
await characters.UpdateAttributeEventAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
if (IsAjaxRequest())
{
return await SceneCharacterAttributesRefreshJsonAsync(model.SceneID);
@ -1290,6 +1345,7 @@ public sealed class ScenesController(
public async Task<IActionResult> AddCharacterKnowledge(CharacterKnowledgeCreateViewModel model)
{
await characters.AddKnowledgeAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
if (IsAjaxRequest())
{
return await SceneKnowledgeRefreshJsonAsync(model.SceneID);
@ -1303,6 +1359,7 @@ public sealed class ScenesController(
public async Task<IActionResult> UpdateCharacterKnowledge(CharacterKnowledgeCreateViewModel model)
{
await characters.UpdateKnowledgeAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "characters");
if (IsAjaxRequest())
{
return await SceneKnowledgeRefreshJsonAsync(model.SceneID);
@ -1316,6 +1373,7 @@ public sealed class ScenesController(
public async Task<IActionResult> DeleteCharacterKnowledge(int id, int sceneId, int? projectId, int? bookId)
{
await characters.DeleteKnowledgeAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "characters");
if (IsAjaxRequest())
{
return await SceneKnowledgeRefreshJsonAsync(sceneId);
@ -1331,6 +1389,7 @@ public sealed class ScenesController(
try
{
await characters.AddRelationshipEventAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "relationships");
}
catch (InvalidOperationException ex)
{
@ -1355,6 +1414,7 @@ public sealed class ScenesController(
public async Task<IActionResult> UpdateRelationshipEvent(RelationshipEventCreateViewModel model)
{
await characters.UpdateRelationshipEventAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "relationships");
if (IsAjaxRequest())
{
return await ScenePeopleContinuityRefreshJsonAsync(model.SceneID);
@ -1368,6 +1428,7 @@ public sealed class ScenesController(
public async Task<IActionResult> DeleteRelationshipEvent(int id, int sceneId, int? projectId, int? bookId)
{
await characters.DeleteRelationshipEventAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "relationships");
if (IsAjaxRequest())
{
return await ScenePeopleContinuityRefreshJsonAsync(sceneId);
@ -1381,6 +1442,7 @@ public sealed class ScenesController(
public async Task<IActionResult> SaveWorkflow(SceneWorkflowEditViewModel model)
{
await writerWorkspace.SaveSceneWorkflowAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID);
}
@ -1395,6 +1457,7 @@ public sealed class ScenesController(
}
await writerWorkspace.SaveNoteAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID);
}
@ -1403,6 +1466,7 @@ public sealed class ScenesController(
public async Task<IActionResult> DeleteNote(int id, int sceneId, int? projectId, int? bookId)
{
await writerWorkspace.DeleteNoteAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "structure");
return RedirectForScene(sceneId, projectId, bookId);
}
@ -1417,6 +1481,7 @@ public sealed class ScenesController(
}
await writerWorkspace.SaveChecklistItemAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
return RedirectForScene(model.SceneID, model.ReturnProjectID, model.ReturnBookID);
}
@ -1425,6 +1490,7 @@ public sealed class ScenesController(
public async Task<IActionResult> DeleteChecklistItem(int id, int sceneId, int? projectId, int? bookId)
{
await writerWorkspace.DeleteChecklistItemAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "structure");
return RedirectForScene(sceneId, projectId, bookId);
}
@ -1497,6 +1563,7 @@ public sealed class ScenesController(
}
var attachmentId = await writerWorkspace.SaveAttachmentAsync(model);
if (savedData is not null) await savedData.Scene(model.SceneID, "structure");
if (fileSizeBytes > 0 && !string.IsNullOrWhiteSpace(model.FilePath))
{
await storage.TrackSceneAttachmentAsync(
@ -1528,6 +1595,7 @@ public sealed class ScenesController(
public async Task<IActionResult> DeleteAttachment(int id, int sceneId, int? projectId, int? bookId, string? filePath)
{
await writerWorkspace.DeleteAttachmentAsync(id);
if (savedData is not null) await savedData.Scene(sceneId, "structure");
await storage.MarkDeletedByStoragePathAsync(filePath);
uploadStorage.TryDeleteFile(filePath, "uploads/scenes");
if (IsAjaxRequest())

View File

@ -7,7 +7,7 @@ using PlotLine.ViewModels;
namespace PlotLine.Controllers;
[Authorize]
public sealed class TimelineController(ITimelineService timeline) : Controller
public sealed class TimelineController(ITimelineService timeline, ContextSavedData savedData) : Controller
{
public async Task<IActionResult> Index([FromQuery] TimelineFilterViewModel filter)
{
@ -103,6 +103,7 @@ public sealed class TimelineController(ITimelineService timeline) : Controller
public async Task<IActionResult> DropMoveScene(TimelineSceneDropMoveViewModel model)
{
var summary = await timeline.MoveSceneByDropAsync(model);
if (summary is not null) await savedData.Scene(model.SceneID);
if (summary is not null)
{
TempData["TimelineDragMessage"] = $"Scene moved. Validation found {summary.WarningCount} warning{(summary.WarningCount == 1 ? "" : "s")}.";
@ -115,15 +116,21 @@ public sealed class TimelineController(ITimelineService timeline) : Controller
public async Task<IActionResult> DropCharacter(TimelineSceneCharacterDropViewModel model)
{
if (Request.Headers.Accept.ToString().Contains("application/json"))
return await SaveSceneDropAsync(() => timeline.AddCharacterByDropAsync(model));
await RunDropActionAsync(() => timeline.AddCharacterByDropAsync(model), "Character added to scene.");
return await SaveSceneDropAsync(() => SaveAndNotify(() => timeline.AddCharacterByDropAsync(model), model.SceneID, "characters"));
await RunDropActionAsync(() => SaveAndNotify(() => timeline.AddCharacterByDropAsync(model), model.SceneID, "characters"), "Character added to scene.");
return RedirectToAction(nameof(Index), new { projectId = model.ReturnProjectID, bookId = model.ReturnBookID, selectedSceneId = model.SceneID });
}
[HttpPost]
[ValidateAntiForgeryToken]
public Task<IActionResult> DropLocation(TimelineSceneLocationDropViewModel model) =>
SaveSceneDropAsync(() => timeline.AddLocationByDropAsync(model));
SaveSceneDropAsync(() => SaveAndNotify(() => timeline.AddLocationByDropAsync(model), model.SceneID, "locations"));
private async Task SaveAndNotify(Func<Task> action, int sceneId, string kind)
{
await action();
await savedData.Scene(sceneId, kind);
}
private async Task<IActionResult> SaveSceneDropAsync(Func<Task> action)
{
@ -144,7 +151,7 @@ public sealed class TimelineController(ITimelineService timeline) : Controller
[ValidateAntiForgeryToken]
public async Task<IActionResult> DropAssetEvent(TimelineAssetEventDropViewModel model)
{
await RunDropActionAsync(() => timeline.AddAssetEventByDropAsync(model), "Asset event added to scene.");
await RunDropActionAsync(() => SaveAndNotify(() => timeline.AddAssetEventByDropAsync(model), model.SceneID, "assets"), "Asset event added to scene.");
return RedirectToAction(nameof(Index), new { projectId = model.ReturnProjectID, bookId = model.ReturnBookID, selectedSceneId = model.SceneID });
}
@ -160,7 +167,7 @@ public sealed class TimelineController(ITimelineService timeline) : Controller
[ValidateAntiForgeryToken]
public async Task<IActionResult> DropLocationRelationship(TimelineLocationRelationshipDropViewModel model)
{
await RunDropActionAsync(() => timeline.AddLocationRelationshipByDropAsync(model), "Location relationship saved.");
await RunDropActionAsync(async () => { await timeline.AddLocationRelationshipByDropAsync(model); await savedData.Project(model.ProjectID, "locations", model.FromLocationID, "Location"); }, "Location relationship saved.");
return RedirectToAction(nameof(Index), new { projectId = model.ProjectID, bookId = model.ReturnBookID });
}

View File

@ -4,16 +4,17 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Models;
using PlotLine.Services.Writer;
using PlotLine.Services;
namespace PlotLine.Controllers;
[Authorize]
public sealed class WriterAuthoringController(IWriterAuthoringService authoring):Controller
public sealed class WriterAuthoringController(IWriterAuthoringService authoring, ContextSavedData savedData):Controller
{
private int Actor=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet] public async Task<IActionResult> Inspect(int bookId,int chapterId,int? sceneId){Response.Headers.CacheControl="no-store";try{return PartialView("~/Views/Writer/_WriterAuthoring.cshtml",await authoring.Read(Actor,bookId,chapterId,sceneId));}catch(SqlException e)when(e.Number==51000){return NotFound();}catch(KeyNotFoundException){return NotFound();}}
[HttpPost,ValidateAntiForgeryToken]
public async Task<IActionResult> Save(int bookId,int chapterId,int? sceneId,string kind,int entityId,string version){
var values=AuthoringSchema.Fields(kind).ToDictionary(f=>f.Name,f=>(string?)Request.Form[f.Name].ToString());
try{await authoring.Save(Actor,bookId,chapterId,sceneId,kind,entityId,version,values);return Json(new{success=true});}
try{await authoring.Save(Actor,bookId,chapterId,sceneId,kind,entityId,version,values);await savedData.Chapter(chapterId, kind is "Chapter" or "Scene" or "Goals" ? "intent" : "structure", sceneId);return Json(new{success=true});}
catch(AuthoringConflictException e){return Conflict(new{message=e.Message});}
catch(KeyNotFoundException){return NotFound();}
catch(ArgumentException e){return BadRequest(new{message=e.Message});}

View File

@ -12,7 +12,7 @@ namespace PlotLine.Controllers;
public sealed class WriterController(
IWriterWorkspaceService writerWorkspace,
IWritingScheduleService writingSchedule,
IBookRepository? bookRepository=null, IProjectAccessService? access=null, WritingActivityRepository? activity=null, WriterObjectiveRepository? objectives=null, WriterWorkRepository? work=null, PlotLine.Services.Writer.IWriterSuggestionProvider? suggestions=null, WriterPlanningRepository? planning=null, INarrativeFocus? narrativeFocus=null) : Controller
IBookRepository? bookRepository=null, IProjectAccessService? access=null, WritingActivityRepository? activity=null, WriterObjectiveRepository? objectives=null, WriterWorkRepository? work=null, PlotLine.Services.Writer.IWriterSuggestionProvider? suggestions=null, WriterPlanningRepository? planning=null, INarrativeFocus? narrativeFocus=null, ContextSavedData? savedData=null) : Controller
{
public Task<IActionResult> Index(int? projectId, int? bookId = null, string? workspace = null, bool journey = false, int? year = null, int? month = null, DateTime? day = null, bool setup = false)
{
@ -480,6 +480,7 @@ public sealed class WriterController(
public async Task<IActionResult> SaveChapterGoal(ChapterGoalEditViewModel model)
{
await writerWorkspace.SaveChapterGoalAsync(model);
if (savedData is not null) await savedData.Chapter(model.ChapterID, "intent");
if (string.Equals(Request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.OrdinalIgnoreCase))
return Json(new { ok = true });
return RedirectToAction(nameof(Chapter), new { id = model.ChapterID });

View File

@ -304,6 +304,7 @@ public class Program
builder.Services.AddSingleton<IWordCompanionPresenceService, WordCompanionPresenceService>();
builder.Services.Configure<Microsoft.AspNetCore.SignalR.HubOptions<PlotLine.Hubs.NativeCompanionPresenceHub>>(options => options.MaximumReceiveMessageSize = 16384);
builder.Services.AddSingleton<ContextWorkspaceNotifications>();
builder.Services.AddScoped<ContextSavedData>();
builder.Services.AddSingleton<PlotLine.Services.Context.ContextWindows>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextCharacterPanels>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextNames>();

View File

@ -58,10 +58,10 @@ public sealed class CharacterWorkspace(ICharacterRepository characters,IProjectR
var frame=await Operation(input.CharacterID,input.RelationshipID,input.EventID,input.Action,ct);if(input.Version!=frame.Version)throw new InvalidOperationException("This relationship or its history changed. Cancel and reopen to review current values.");if(input.Action is "archive" or "event-remove"&&!input.Confirmed)throw new ArgumentException("Confirm the identified removal.");if(input.Notes?.Length>4000||input.Intensity is <1 or >10)throw new ArgumentException("Use valid notes and intensity.");
if(input.Action.StartsWith("event-")&&frame.Event?.ProtectedSource==true)throw new ArgumentException("This event has source/review dependencies. Manage it through its source workflow.");
try{await reader.Change(input,user.UserId!.Value,ct);}catch(SqlException ex)when(ex.Number==51020){throw new UnauthorizedAccessException();}catch(SqlException ex)when(ex.Number==51021){throw new InvalidOperationException(ex.Message);}catch(SqlException ex)when(ex.Number==51022){throw new ArgumentException(ex.Message);}
var scope=await Scope(input.CharacterID);await activity.RecordAsync(scope.Project.ProjectID,input.Action=="archive"?"Archived":input.Action=="event-remove"?"Deleted":"Updated","Relationship",input.RelationshipID,"Character workspace relationship operation");await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID,kind:"relationships");
var scope=await Scope(input.CharacterID);await activity.RecordAsync(scope.Project.ProjectID,input.Action=="archive"?"Archived":input.Action=="event-remove"?"Deleted":"Updated","Relationship",input.RelationshipID,"Character workspace relationship operation");await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID,kind:"relationships",entityId:input.RelationshipID,entityType:"Relationship");
}
public async Task<CharacterDetailViewModel> AddForm(int id,CancellationToken ct,InitialRelationshipEditViewModel? input=null)
{var model=await Header(id,null,ct);if(!model.WorkspaceCanEdit)throw new UnauthorizedAccessException();var lookup=await characters.GetLookupsAsync(model.Project.ProjectID);model.RelationshipTypeOptions=lookup.RelationshipTypes.Select(t=>new SelectListItem(t.RelationshipCategoryName+" · "+t.TypeName,t.RelationshipTypeID.ToString())).ToArray();model.RelationshipStateOptions=lookup.RelationshipStates.Select(t=>new SelectListItem(t.StateName,t.RelationshipStateID.ToString())).ToArray();model.BookOptions=(await books.ListByProjectAsync(model.Project.ProjectID)).Select(b=>new SelectListItem(b.BookDisplayTitle,b.BookID.ToString())).ToArray();if(input!=null){model.NewInitialRelationship=input;var target=await characters.GetReferenceCharacterAsync(input.RelatedCharacterID,user.UserId!.Value);if(target?.ProjectID==model.Project.ProjectID)model.CharacterOptions=[new(target.CharacterName,target.CharacterID.ToString())];}return model;}
public async Task Add(int id,InitialRelationshipEditViewModel input,CancellationToken ct)
{var scope=await Scope(id);if(!scope.CanEdit||input.CharacterID!=id||input.CharacterRelationshipID!=0)throw new UnauthorizedAccessException();if((await characters.GetReferenceCharacterAsync(input.RelatedCharacterID,user.UserId!.Value))?.ProjectID!=scope.Project.ProjectID||input.RelatedCharacterID==id)throw new ArgumentException("Choose another character in this project.");if(input.Notes?.Length>4000||input.InitialIntensity is <1 or >10)throw new ArgumentException("Use valid notes and intensity.");var lookups=await characters.GetLookupsAsync(scope.Project.ProjectID);if(!lookups.RelationshipTypes.Any(t=>t.RelationshipTypeID==input.RelationshipTypeID)||(input.InitialRelationshipStateID.HasValue&&!lookups.RelationshipStates.Any(t=>t.RelationshipStateID==input.InitialRelationshipStateID)))throw new ArgumentException("Choose a recorded relationship type and state.");if(input.InitialBookID.HasValue&&!(await books.ListByProjectAsync(scope.Project.ProjectID)).Any(b=>b.BookID==input.InitialBookID))throw new UnauthorizedAccessException();input.ProjectID=scope.Project.ProjectID;input.ReturnCharacterID=id;await canonical.SaveInitialRelationshipAsync(input);await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID,kind:"relationships");}
{var scope=await Scope(id);if(!scope.CanEdit||input.CharacterID!=id||input.CharacterRelationshipID!=0)throw new UnauthorizedAccessException();if((await characters.GetReferenceCharacterAsync(input.RelatedCharacterID,user.UserId!.Value))?.ProjectID!=scope.Project.ProjectID||input.RelatedCharacterID==id)throw new ArgumentException("Choose another character in this project.");if(input.Notes?.Length>4000||input.InitialIntensity is <1 or >10)throw new ArgumentException("Use valid notes and intensity.");var lookups=await characters.GetLookupsAsync(scope.Project.ProjectID);if(!lookups.RelationshipTypes.Any(t=>t.RelationshipTypeID==input.RelationshipTypeID)||(input.InitialRelationshipStateID.HasValue&&!lookups.RelationshipStates.Any(t=>t.RelationshipStateID==input.InitialRelationshipStateID)))throw new ArgumentException("Choose a recorded relationship type and state.");if(input.InitialBookID.HasValue&&!(await books.ListByProjectAsync(scope.Project.ProjectID)).Any(b=>b.BookID==input.InitialBookID))throw new UnauthorizedAccessException();input.ProjectID=scope.Project.ProjectID;input.ReturnCharacterID=id;var relationshipID=await canonical.SaveInitialRelationshipAsync(input);await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID,kind:"relationships",entityId:relationshipID,entityType:"Relationship");}
}

View File

@ -108,7 +108,7 @@ public sealed class ContextCharacterEditing(ICharacterService characters,IStoryC
}
await characters.UpdateSceneCharacterAsync(edit);
}
await notifications.Invalidate(user.UserId!.Value,frame.Appearance==null?null:input.BookID,projectId:frame.Character.ProjectID);
await notifications.Invalidate(user.UserId!.Value,frame.Appearance==null?null:input.BookID,projectId:frame.Character.ProjectID,kind:"characters",entityId:input.CharacterID,entityType:"Character");
}finally{mutex.Release();}
}
}

View File

@ -57,12 +57,13 @@ public sealed class ContextRelationshipEditing(ICharacterRepository repository,I
if(input.Intensity is <1 or >10||input.Notes?.Length>4000)throw new ArgumentException("Intensity must be 1–10 and notes at most 4,000 characters.");
if(r!=null&&(r.CharacterAID!=input.SourceID||r.CharacterBID!=input.TargetID||r.RelationshipTypeID!=input.TypeID||r.IsReciprocal!=input.Mutual))throw new ArgumentException("Use the full Relationships Editor to change the pair, type or direction of an existing relationship.");
if(r==null&&frame.Data.Relationships.Any(x=>!x.IsArchived&&x.RelationshipTypeID==input.TypeID&&((x.CharacterAID==input.SourceID&&x.CharacterBID==input.TargetID)||(x.IsReciprocal&&x.CharacterAID==input.TargetID&&x.CharacterBID==input.SourceID))))throw new ArgumentException("This relationship already exists. Correct its recorded state or use the full editor.");
if(input.Mode=="initial")await characters.SaveInitialRelationshipAsync(new(){CharacterRelationshipID=r?.CharacterRelationshipID??0,ProjectID=frame.ProjectID,CharacterID=input.SourceID,RelatedCharacterID=input.TargetID,RelationshipTypeID=input.TypeID,InitialBookID=r?.InitialBookID,InitialRelationshipStateID=input.StateID,InitialIntensity=input.Intensity,IsReciprocal=input.Mutual,ReaderInitiallyKnows=input.Known,Notes=input.Notes});
int changedID;
if(input.Mode=="initial")changedID=await characters.SaveInitialRelationshipAsync(new(){CharacterRelationshipID=r?.CharacterRelationshipID??0,ProjectID=frame.ProjectID,CharacterID=input.SourceID,RelatedCharacterID=input.TargetID,RelationshipTypeID=input.TypeID,InitialBookID=r?.InitialBookID,InitialRelationshipStateID=input.StateID,InitialIntensity=input.Intensity,IsReciprocal=input.Mutual,ReaderInitiallyKnows=input.Known,Notes=input.Notes});
else{
var edit=new RelationshipEventCreateViewModel{RelationshipEventID=frame.Event?.RelationshipEventID??0,CharacterRelationshipID=r?.CharacterRelationshipID,SceneID=input.SceneID,CharacterAID=input.SourceID,CharacterBID=input.TargetID,RelationshipTypeID=input.TypeID,RelationshipStateID=input.StateID,Intensity=input.Intensity,IsReciprocal=input.Mutual,IsKnownToOtherCharacter=input.Known,Description=input.Notes,ReturnProjectID=frame.ProjectID,ReturnBookID=input.BookID};
if(frame.Event==null)await characters.AddRelationshipEventAsync(edit);else await characters.UpdateRelationshipEventAsync(edit);
changedID=frame.Event==null?await characters.AddRelationshipEventAsync(edit):await characters.UpdateRelationshipEventAsync(edit);
}
await notifications.Invalidate(user.UserId!.Value,projectId:frame.ProjectID,kind:"relationships");
await notifications.Invalidate(user.UserId!.Value,bookId:input.Mode=="initial"?null:input.BookID,projectId:frame.ProjectID,kind:"relationships",entityId:changedID,entityType:input.Mode=="initial"?"Relationship":"Relationship Event");
}finally{mutex.Release();}
}
}

View File

@ -60,14 +60,14 @@ public sealed class ContextSpatial(ISqlConnectionFactory connections,ICurrentUse
private async Task<object> Accepted(SpatialMutation input,SpatialMutationResult result)
{
string? undo=null;if(result.Changed&&result.Previous!=null)undo=Protector.Protect(JsonSerializer.Serialize(new SpatialReceipt(Author,input with{Expected=result.Version,GeometryID=result.GeometryID},result.Previous,DateTime.UtcNow.AddMinutes(10))));
if(result.Changed){await notifications.Invalidate(Author,projectId:result.ProjectID,bookId:input.Kind=="scene"?input.BookID:(int?)null,kind:input.Kind is "map"?"maps":input.Kind is "room" or "plan"?"floorplans":"locations");}
if(result.Changed){await notifications.Invalidate(Author,projectId:result.ProjectID,bookId:input.Kind=="scene"?input.BookID:(int?)null,kind:input.Kind is "map"?"maps":input.Kind is "room" or "plan"?"floorplans":"locations",entityId:input.ResourceID??input.LocationID??input.SceneID,entityType:input.Kind);}
return new{saved=true,result,undoToken=undo};
}
public async Task<object> Undo(string token)
{
SpatialReceipt receipt;try{receipt=JsonSerializer.Deserialize<SpatialReceipt>(Protector.Unprotect(token))??throw new Exception();}catch{throw new ArgumentException("Undo is unavailable.");}
if(receipt.User!=Author||receipt.Expires<DateTime.UtcNow)throw new ArgumentException("Undo expired. Existing work is unchanged.");
using var db=connections.CreateConnection();var result=await Apply(db,receipt.Target,previous:receipt.Previous);if(result.Changed){await notifications.Invalidate(Author,projectId:result.ProjectID,bookId:receipt.Target.Kind=="scene"?receipt.Target.BookID:(int?)null,kind:receipt.Target.Kind=="map"?"maps":receipt.Target.Kind=="scene"?"locations":"floorplans");}return new{saved=true,result};
using var db=connections.CreateConnection();var result=await Apply(db,receipt.Target,previous:receipt.Previous);if(result.Changed){await notifications.Invalidate(Author,projectId:result.ProjectID,bookId:receipt.Target.Kind=="scene"?receipt.Target.BookID:(int?)null,kind:receipt.Target.Kind=="map"?"maps":receipt.Target.Kind=="scene"?"locations":"floorplans",entityId:receipt.Target.ResourceID??receipt.Target.LocationID??receipt.Target.SceneID,entityType:receipt.Target.Kind);}return new{saved=true,result};
}
public async Task<object> Create(SpatialCreation input)
{
@ -76,7 +76,7 @@ public sealed class ContextSpatial(ISqlConnectionFactory connections,ICurrentUse
var id=await db.QuerySingleAsync<int>("dbo.Location_WorkspaceCreate",new{scope.ProjectID,UserID=Author,input.Name,ParentID=input.ParentID},tx,commandType:CommandType.StoredProcedure);
SpatialMutationResult? changed=null;SpatialMutation? target=null;
if(input.Expected!=null){target=new(input.BookID,input.SceneID,input.BlockID!=null?"room":"scene",id,input.PlanID,input.BlockID,input.Expected,Replace:input.Replace);changed=await Apply(db,target,tx);}
tx.Commit();await notifications.Invalidate(Author,projectId:scope.ProjectID,kind:"locations");
tx.Commit();await notifications.Invalidate(Author,projectId:scope.ProjectID,kind:"locations",entityId:id,entityType:"Location");
return new{id,assignment=changed==null?null:await Accepted(target!,changed)};
}
public async Task<SpatialFloorCanvas> Floor(int book,int scene,int plan)

View File

@ -2,18 +2,23 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace PlotLine.Services;
// Existing editor saves invalidate reference reads; no capture, analysis or navigation is started.
public sealed class ContextReferenceInvalidationFilter(ContextWorkspaceNotifications notifications, ICurrentUserService currentUser) : IAsyncActionFilter
// A successful POST is not proof of a save (previews and handled failures also return 200).
// Canonical save paths explicitly queue hints; this filter never infers a mutation.
public sealed class ContextReferenceInvalidationFilter(ContextWorkspaceNotifications notifications) : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var result = await next();
var controller = context.RouteData.Values["controller"]?.ToString();
if (controller == "Writer" && context.RouteData.Values["action"]?.ToString() != "SaveChapterGoal") return;
if (!HttpMethods.IsPost(context.HttpContext.Request.Method) || controller is not ("Scenes" or "Writer" or "Characters" or "CharacterWorkspace" or "RelationshipMap" or "Chapters" or "PlotLines" or "PlotLineWorkspace" or "Timeline" or "Locations" or "WriterAuthoring" or "WriterReview" or "IntelligenceReview" or "ParagraphManuscript" or "Maps" or "FloorPlans") ||
currentUser.UserId is not int user || result.Exception != null || !context.ModelState.IsValid) return;
if (result.Result is ForbidResult or ChallengeResult) return;
var status = result.Result switch { ObjectResult value => value.StatusCode ?? 200, StatusCodeResult value => value.StatusCode, _ => 200 };
if(status<400&&!notifications.AlreadyInvalidated){var kind=controller switch{"RelationshipMap"=>"relationships","Characters"=>context.RouteData.Values["action"]?.ToString()?.Contains("Relationship")==true?"relationships":"characters","Chapters" or "Scenes"=>"structure","Maps"=>"maps","FloorPlans"=>"floorplans",_=>null};await notifications.Invalidate(user,kind:kind);}
if (!notifications.AlreadyInvalidated || result.Exception != null || !context.ModelState.IsValid ||
result.Result is ForbidResult or ChallengeResult || context.HttpContext.Response.StatusCode >= 400) return;
var status = result.Result switch
{
ObjectResult value => value.StatusCode ?? 200,
StatusCodeResult value => value.StatusCode,
JsonResult value => value.StatusCode ?? 200,
_ => 200
};
if (context.Controller is Controller controller && controller.TempData.Keys.Any(key => key.EndsWith("Error", StringComparison.OrdinalIgnoreCase))) return;
if (status < 400) await notifications.PublishPending();
}
}

View File

@ -0,0 +1,53 @@
using PlotLine.Data;
namespace PlotLine.Services;
// Called only after a canonical mutation succeeds. Scope comes from saved records,
// never from a navigation return URL or an unverified project/book form field.
public sealed class ContextSavedData(ContextWorkspaceNotifications notifications, ICurrentUserService user,
ISceneRepository scenes, IChapterRepository chapters, IBookRepository books,
IFloorPlanRepository plans, ILogger<ContextSavedData> logger)
{
private readonly HashSet<(int Id,string Kind)> recordedScenes=[];
public async Task Scene(int id, string kind = "structure") => await Safely(async () =>
{
if (!recordedScenes.Add((id,kind))) return;
var scene = await scenes.GetAsync(id);
if (scene is not null) await Chapter(scene.ChapterID, kind, id);
});
public async Task Chapter(int id, string kind = "structure", int? sceneId = null) => await Safely(async () =>
{
var chapter = await chapters.GetAsync(id);
var book = chapter is null ? null : await books.GetAsync(chapter.BookID);
if (book is not null && user.UserId is int author)
await notifications.Invalidate(author, book.BookID, id, sceneId, book.ProjectID, kind,
entityId: sceneId ?? id, entityType: sceneId.HasValue ? "Scene" : "Chapter");
});
public async Task FloorPlan(int id) => await Safely(async () =>
{
var plan = await plans.GetAsync(id);
if (plan is not null) await Project(plan.ProjectID, "floorplans", id, "Floor Plan");
});
public Task Project(int projectId, string kind, int? id, string entityType) =>
user.UserId is int author ? notifications.Invalidate(author, projectId: projectId, kind: kind, entityId: id, entityType: entityType) : Task.CompletedTask;
public Task Activity(int projectId, string entityType, int? entityId)
{
// Scene editors supply the changed category explicitly after their mutation.
if (entityType == "Scene") return Task.CompletedTask;
if (entityType == "Chapter") return Task.CompletedTask;
var kind = entityType switch
{
"Character" => "characters", "Relationship" => "relationships",
"Location" or "Location Relationship" => "locations",
"Plot Line" => "plotlines", "Thread" or "Thread Event" => "threads",
"Floor Plan" or "Floor Plan Transition" or "Floor Plan Background" => "floorplans",
"Asset" or "Asset Event" => "assets", _ => null
};
return kind is null ? Task.CompletedTask : Project(projectId, kind, entityId, entityType);
}
private async Task Safely(Func<Task> action)
{
try { await action(); }
catch (Exception exception) { logger.LogWarning("Context saved-data scope unavailable: {Category}", exception.GetType().Name); }
}
}

View File

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.SignalR;
using System.Text.Json.Serialization;
using PlotLine.Hubs;
namespace PlotLine.Services;
@ -6,10 +7,35 @@ namespace PlotLine.Services;
public sealed class ContextWorkspaceNotifications(IHubContext<NativeCompanionPresenceHub> hub, ILogger<ContextWorkspaceNotifications> logger,IHttpContextAccessor? accessor=null)
{
private const string Marker="PlotDirector.ContextInvalidated";
private const string Pending="PlotDirector.ContextPending";
public bool AlreadyInvalidated=>accessor?.HttpContext?.Items.ContainsKey(Marker)==true;
public Task Position(int user) => Send(user, "ContextPositionChanged", new { });
public Task Invalidate(int user,int? bookId=null,int? chapterId=null,int? sceneId=null,int? projectId=null,string? kind=null)
{if(AlreadyInvalidated)return Task.CompletedTask;if(accessor?.HttpContext is {} context)context.Items[Marker]=true;return Send(user,"ContextInvalidated",new{bookId,chapterId,sceneId,projectId,kind});}
public Task Invalidate(int user,int? bookId=null,int? chapterId=null,int? sceneId=null,int? projectId=null,string? kind=null,
int? entityId=null,string? entityType=null)
{
var hint=new SavedHint(bookId,chapterId,sceneId,projectId,kind,entityId,entityType);
if(accessor?.HttpContext is not {} context)return Send(user,"ContextInvalidated",hint);
context.Items[Marker]=true;
if(context.Items[Pending] is not HashSet<(int User,SavedHint Hint)> pending)
context.Items[Pending]=pending=[];
pending.Add((user,hint));
return Task.CompletedTask;
}
// The action filter publishes explicit save hints only after the whole action succeeds.
public async Task PublishPending()
{
if(accessor?.HttpContext?.Items[Pending] is not HashSet<(int User,SavedHint Hint)> pending)return;
foreach(var item in pending)await Send(item.User,"ContextInvalidated",item.Hint);
pending.Clear();
}
private sealed record SavedHint(
[property: JsonPropertyName("bookId")] int? BookId,
[property: JsonPropertyName("chapterId")] int? ChapterId,
[property: JsonPropertyName("sceneId")] int? SceneId,
[property: JsonPropertyName("projectId")] int? ProjectId,
[property: JsonPropertyName("kind")] string? Kind,
[property: JsonPropertyName("entityId")] int? EntityId,
[property: JsonPropertyName("entityType")] string? EntityType);
private async Task Send(int user, string name, object hint)
{
try { await hub.Clients.Group(NativeCompanionPresenceHub.UserGroup(user)).SendAsync(name, hint); }

View File

@ -72,7 +72,7 @@ public sealed class EntityImageUploadException(string message, int entityId) : I
public sealed class ProjectActivityService(
IProjectRepository projects,
IProjectActivityRepository activity,
ICurrentUserService currentUser) : IProjectActivityService
ICurrentUserService currentUser, ContextSavedData? savedData = null) : IProjectActivityService
{
public async Task<ProjectActivityViewModel?> GetActivityAsync(int projectId)
{
@ -88,14 +88,15 @@ public sealed class ProjectActivityService(
};
}
public Task RecordAsync(int projectId, string activityType, string entityType, int? entityId, string? entityName, string? description = null)
public async Task RecordAsync(int projectId, string activityType, string entityType, int? entityId, string? entityName, string? description = null)
{
if (projectId <= 0 || string.IsNullOrWhiteSpace(activityType) || string.IsNullOrWhiteSpace(entityType))
{
return Task.CompletedTask;
return;
}
return activity.RecordAsync(projectId, currentUser.UserId, activityType, entityType, entityId, entityName, description);
await activity.RecordAsync(projectId, currentUser.UserId, activityType, entityType, entityId, entityName, description);
if (savedData is not null) await savedData.Activity(projectId, entityType, entityId);
}
}
@ -8471,7 +8472,7 @@ public sealed class LocationService(
CanTravelDirectly = model.CanTravelDirectly,
Notes = model.Notes
});
await activity.RecordAsync(model.ProjectID, isNew ? "Created" : "Updated", "Relationship", relationshipId, "Location relationship");
await activity.RecordAsync(model.ProjectID, isNew ? "Created" : "Updated", "Location Relationship", relationshipId, "Location relationship");
return relationshipId;
}
@ -9488,13 +9489,15 @@ public sealed class FloorPlanService(
return existing.LocationID;
}
return await locations.SaveAsync(new LocationItem
var locationId = await locations.SaveAsync(new LocationItem
{
ProjectID = projectId,
ParentLocationID = parentLocationId,
LocationName = name,
ShowInQuickAddBar = false
});
await activity.RecordAsync(projectId, "Created", "Location", locationId, name);
return locationId;
}
private static void ValidateFloor(FloorPlanFloorEditViewModel model)

View File

@ -97,7 +97,7 @@ public sealed class NameVerification(IProjectRepository projects,INameManuscript
await results.Fail(user,job.NameVerificationID,request.RequestID);throw;
}
// This is reference data only: no character/alias writes and no manuscript-focus commands.
await notifications.Invalidate(user,projectId:confirmation.ProjectID,kind:"names");
await notifications.Invalidate(user,projectId:confirmation.ProjectID,kind:"names",entityId:job.NameVerificationID,entityType:"NameVerification");
return new(job.NameVerificationID,false,false,result.Complete);
}
}

View File

@ -14,7 +14,7 @@
dialog.addEventListener('input',()=>{dirty=true;state();});dialog.addEventListener('change',()=>{dirty=true;state();});
dialog.addEventListener('submit',async event=>{const form=event.target.closest('[data-context-edit-form]');if(!form)return;event.preventDefault();if(busy)return;busy=true;state();status.textContent='Saving correction…';form.querySelectorAll('button').forEach(button=>button.disabled=true);
try{const response=await fetch(form.action,{method:'POST',body:new URLSearchParams(new FormData(form)),headers:{'X-Requested-With':'XMLHttpRequest'},credentials:'same-origin'});
if(response.ok&&!response.redirected&&response.headers.get('content-type')?.includes('application/json')){const result=await response.json();if(!result.saved)throw Error('The save was not confirmed.');busy=false;close(true);root.contextController.invalidate({bookId:result.bookId});window.PlotDirector?.toast?.success('Correction saved.');return;}
if(response.ok&&!response.redirected&&response.headers.get('content-type')?.includes('application/json')){const result=await response.json();if(!result.saved)throw Error('The save was not confirmed.');busy=false;close(true);root.contextController.invalidate({bookId:result.bookId,kind:new URL(form.action,location.origin).pathname.endsWith("EditRelationship")?"relationships":"characters"});window.PlotDirector?.toast?.success('Correction saved.');return;}
if(response.status===422&&!response.redirected){install(await response.text());dirty=true;status.textContent='Correct the inline error and retry. Your entered value is retained.';window.PlotDirector?.toast?.error('Correction could not be saved.');}
else throw Error('Correction could not be saved. Check sign-in and editing permission; your draft is retained.');
}catch(error){status.textContent=error.message;dirty=true;window.PlotDirector?.toast?.error(error.message);}

View File

@ -24,8 +24,8 @@
async function reload(refresh=false){const current=++epoch,p={...position},location=bus.location;try{status.textContent='Loading spatial context…';const result=await state(p,location,refresh);if(disposed||current!==epoch||!same(position,p))return;data=result;loadedInspection=location??result.scope.primaryLocationID;if(bus.scene!==`${p.bookId}/${p.sceneId}`){bus.scene=`${p.bookId}/${p.sceneId}`;bus.select(data.scope.primaryLocationID,context.paneId);}selection=bus.location;status.textContent='';draw();}catch(e){if(current===epoch)fail(e);}}
async function select(location){bus.select(location,context.paneId);if(selection===location)return;selection=location;if(data?.locations.some(l=>id(l)===location)&&loadedInspection===location)draw();else await reload();}
const listener=message=>{if(disposed||busy||message.source===context.paneId)return;selection=message.location;if(data?.locations.some(l=>id(l)===selection)&&loadedInspection===selection)draw();else void reload();};bus.listeners.add(listener);
async function finish(result,route='/SpatialContext/Undo',inspection){if(result.assignment){if(result.assignment.result?.kind==='scene')inspection=result.id;result=result.assignment;}undo=result.undoToken?{token:result.undoToken,route}:null;q('[data-spatial-undo]').hidden=!undo;window.PlotDirector?.toast?.success('Spatial information saved.');guard(false,true);if(inspection!==undefined&&root.contextController.position.sceneId===position.sceneId){bus.location=inspection;bus.revision++;}root.contextController.invalidate({projectId:position.projectId,bookId:position.bookId,kind:'spatial'});}
q('[data-spatial-undo]').onclick=async()=>{try{const saved=undo;if(!saved)return;if(busy)throw Error('Finish or cancel the current operation before Undo.');await post(saved.route,{token:saved.token});undo=null;q('[data-spatial-undo]').hidden=true;root.contextController.invalidate({kind:'spatial',projectId:position.projectId,bookId:position.bookId});}catch(e){fail(e);}};
async function finish(result,route='/SpatialContext/Undo',inspection){if(result.assignment){if(result.assignment.result?.kind==='scene')inspection=result.id;result=result.assignment;}undo=result.undoToken?{token:result.undoToken,route}:null;q('[data-spatial-undo]').hidden=!undo;window.PlotDirector?.toast?.success('Spatial information saved.');guard(false,true);if(inspection!==undefined&&root.contextController.position.sceneId===position.sceneId){bus.location=inspection;bus.revision++;}root.contextController.invalidate({projectId:position.projectId,bookId:position.bookId,kind:result.result?.kind==='map'?'maps':['room','plan'].includes(result.result?.kind)?'floorplans':'locations'});}
q('[data-spatial-undo]').onclick=async()=>{try{const saved=undo;if(!saved)return;if(busy)throw Error('Finish or cancel the current operation before Undo.');const result=await post(saved.route,{token:saved.token});undo=null;q('[data-spatial-undo]').hidden=true;root.contextController.invalidate({kind:result.result?.kind==='map'?'maps':['room','plan'].includes(result.result?.kind)?'floorplans':'locations',projectId:position.projectId,bookId:position.bookId});}catch(e){fail(e);}};
function clearOperation(){operation=null;q('[data-spatial-operation]').replaceChildren();q('[data-spatial-operation]').hidden=true;renderer?.command?.('placement',{active:false});guard(false);}
async function form(title,build,commit){if(busy)throw Error('Finish or cancel the current operation first.');const panel=q('[data-spatial-operation]');panel.hidden=false;panel.replaceChildren(el('strong',title));guard(true);const controls=await build(panel);panel.append(btn('Save',async()=>{try{const result=await commit(controls);clearOperation();await finish(result,result.attribute?'/LocationWorkspace/Undo':'/SpatialContext/Undo');}catch(e){fail(e);}}),btn('Cancel',clearOperation));controls?.focus?.();}
async function picker(title,selected,allowRoot=false){const content=el('div'),dialog=el('dialog',null,'pd-location-picker-dialog');dialog.append(el('h2',title),content);document.body.append(dialog);const wasBusy=busy;guard(true);try{const result=await window.PlotDirectorLocationPicker.data(position.projectId);const picker=window.PlotDirectorLocationPicker.mount(content,{...result,selected: selected==null?undefined:String(selected),allowRoot,rootLabel:allowRoot?'No assigned location':undefined});return await new Promise(resolve=>{let value;dialog.append(btn('Choose',()=>{if(picker.value===undefined)return;value=picker.value===''?null:Number(picker.value);dialog.close();}),btn('Cancel',()=>dialog.close()));dialog.addEventListener('close',()=>resolve(value),{once:true});dialog.showModal();picker.focus();});}finally{dialog.remove();guard(wasBusy);}}
@ -42,19 +42,19 @@
function details(){const host=q('[data-spatial-details]');host.replaceChildren();const current=data.scope,location=data.locations.find(l=>id(l)===selection);const actions=el('div',null,'spatial-toolbar');if(current.canEdit)actions.append(btn(`Change current scene location`,chooseAssignment),btn('New location for current scene',()=>createLocation(true,null)));host.append(actions);if(!location){host.append(el('p',selection?'The assigned or inspected location is unavailable. Choose an active location explicitly; the recorded assignment has not been changed.':'This scene has no assigned location. Inspect adjacent scenes or explicitly choose a location.'));if(current.canEdit){host.append(btn('Create new location for current scene',()=>createLocation(true,null)));for(const adjacent of data.scenes.filter(s=>s.position!==0&&s.locationID))host.append(btn(`Use ${adjacent.position<0?'previous':'next'} scene location`,()=>assign(adjacent.locationID)));}return;}const header=el('h2',location.locationName);header.prepend(icon(data,location));draggable(header,id(location));host.append(header,el('p',`${location.locationTypeName||'Unclassified'} · ${location.classification||'Unclassified'}`));const trail=el('nav',null,'spatial-path');trail.setAttribute('aria-label','Containing locations');for(const a of ancestors(data,id(location)).reverse())trail.append(btn(a.locationName,()=>select(id(a))));host.append(trail);const description=el('div',location.description||'No description recorded.','spatial-description');host.append(description);if(current.canEdit){const tools=el('div',null,'spatial-toolbar');tools.append(btn('Edit description',()=>edit('description',location)),btn('Rename',()=>edit('name',location)),btn('Type',()=>discrete('type',location)),btn('Classification',()=>discrete('classification',location)),btn('Create child',()=>createLocation(false,id(location))));host.append(tools);}const links=el('div',null,'spatial-toolbar');for(const [label,url]of [['Location Details',`/Locations/Details/${id(location)}`],['Edit Location',`/Locations/Edit/${id(location)}`]]){const a=el('a',label);a.href=url;links.append(a);}host.append(links);const children=data.locations.filter(l=>l.parentLocationID===id(location));if(children.length){const section=el('details');section.open=preferences.children!==false;section.append(el('summary',`Contained locations (${location.childCount})`));section.ontoggle=()=>{preferences.children=section.open;save();};for(const child of children)section.append(btn(child.locationName,()=>select(id(child))));if(location.childCount>children.length)section.append(el('small',`Showing ${children.length} immediate locations. Open Locations for the complete directory.`));host.append(section);}if(data.relationships.length){const section=el('details');section.append(el('summary','Recorded relationships'));for(const r of data.relationships)section.append(el('p',`${r.fromName} · ${r.typeName} · ${r.toName}${r.notes?' — '+r.notes:''}`));host.append(section);}const spatial=el('div',null,'spatial-toolbar');for(const tool of ['maps','floorplans']){const found=resolution(data,id(location),tool);spatial.append(btn(`Show ${tool==='maps'?'map':'floor plan'}${found.some(f=>f.depth)?' (containing location)':''}`,()=>showTool(tool)));if(tool==='maps'&&current.canEdit&&!found.some(f=>f.depth===0))spatial.append(btn('Place on map',()=>{bus.pendingPlacement=selection;return showTool('maps');}));}host.append(spatial);}
function catalog(){return kind==='maps'?data.mapCatalog:data.planCatalog;}
function relevant(){const found=resolution(data,selection,kind);if(found.length)return found.sort((a,b)=>data.scenes.filter(s=>resolution(data,s.locationID,kind).some(l=>l.resourceID===b.resourceID)).length-data.scenes.filter(s=>resolution(data,s.locationID,kind).some(l=>l.resourceID===a.resourceID)).length||a.name.localeCompare(b.name));return data.scenes.flatMap(s=>resolution(data,s.locationID,kind));}
function draw(){if(!data||disposed)return;error.textContent='';scenes();if(kind==='maps')q('[data-spatial-feature]').replaceChildren();q('[data-spatial-return]').disabled=selection===data.scope.primaryLocationID;q('[data-spatial-return]').onclick=()=>select(data.scope.primaryLocationID);if(kind==='locations'){details();return;}const options=catalog(),links=relevant(),available=new Set(links.map(l=>l.resourceID));const preferred=Number(preferences.resource);const next=resource&&available.has(resource)?resource:available.has(preferred)?preferred:links[0]?.resourceID||resource&&options.some(x=>x.id===resource)&&resource||null;const menu=q('[data-spatial-resource]');menu.replaceChildren(new Option('Choose existing resource',''),...options.map(r=>new Option(r.name,String(r.id))));menu.value=next||'';menu.onchange=()=>{resource=Number(menu.value)||null;preferences.resource=resource;save();void renderResource();};q('[data-spatial-resolution]').textContent=resourceCaption(next);if(resource!==next){resource=next;void renderResource();}else if(renderer){if(renderer.revision!==String(catalog().find(c=>c.id===resource)?.modifiedDate)){void renderResource();}else highlight();}else void renderResource();q('[data-spatial-place]').disabled=!data.scope.canEdit||!resource||(kind==='maps'&&!selection);q('[data-spatial-place]').onclick=()=>kind==='maps'?startPlacement(selection):chooseRoom();updateAdvanced();}
function draw(){if(!data||disposed)return;error.textContent='';scenes();if(kind==='maps')q('[data-spatial-feature]').replaceChildren();q('[data-spatial-return]').disabled=selection===data.scope.primaryLocationID;q('[data-spatial-return]').onclick=()=>select(data.scope.primaryLocationID);if(kind==='locations'){details();return;}const options=catalog(),links=relevant(),available=new Set(links.map(l=>l.resourceID));const preferred=Number(preferences.resource);const next=resource&&options.some(x=>x.id===resource)?resource:available.has(preferred)?preferred:links[0]?.resourceID||resource&&options.some(x=>x.id===resource)&&resource||null;const menu=q('[data-spatial-resource]');menu.replaceChildren(new Option('Choose existing resource',''),...options.map(r=>new Option(r.name,String(r.id))));menu.value=next||'';menu.onchange=()=>{resource=Number(menu.value)||null;preferences.resource=resource;save();void renderResource();};q('[data-spatial-resolution]').textContent=resourceCaption(next);if(resource!==next){resource=next;void renderResource();}else if(renderer){if(renderer.revision!==String(catalog().find(c=>c.id===resource)?.modifiedDate)){void renderResource();}else highlight();}else void renderResource();q('[data-spatial-place]').disabled=!data.scope.canEdit||!resource||(kind==='maps'&&!selection);q('[data-spatial-place]').onclick=()=>kind==='maps'?startPlacement(selection):chooseRoom();updateAdvanced();}
function updateAdvanced(){const advanced=q('[data-spatial-advanced]');const represented=resolution(data,selection,kind).find(l=>l.resourceID===resource);advanced.href=kind==='maps'?`/Maps?projectId=${position.projectId}&id=${resource}${represented?.featureID?'&featureId='+encodeURIComponent(represented.featureID):''}`:`/FloorPlans/Edit/${resource}${represented?.blockID?'?selectedBlockId='+represented.blockID:''}`;advanced.hidden=!resource;}
function resourceCaption(target=resource){const found=resolution(data,selection,kind).filter(x=>x.resourceID===target);return found.length?(found[0].depth?`Represented through containing location: ${path(data,found[0].represented)}. This is not an exact position for the inspected location.`:'Directly associated with the inspected location.'):'No authoritative representation of the inspected location on this resource.';}
function sceneHighlights(){const grouped=new Map();for(const s of data.scenes){const found=resolution(data,s.locationID,kind).filter(l=>l.resourceID===resource);for(const f of found){const key=kind==='maps'?f.featureID:f.blockID;if(!key)continue;if(!grouped.has(key))grouped.set(key,{featureID:key,roles:[],label:[]});const value=grouped.get(key);value.roles.push(s.position);value.label.push(`${['Previous','Current','Next'][s.position+1]}: ${path(data,s.locationID)}${f.depth?' (containing location)':''}`);}}return [...grouped.values()].map(x=>({...x,label:x.label.join(' · ')}));}
function annotate(){if(kind==='locations'||!data)return;for(const scene of data.scenes){const row=q(`[data-scene-position="${scene.position}"]`);if(!row)continue;row.querySelector('.spatial-elsewhere')?.remove();const resolved=resolution(data,scene.locationID,kind),here=resolved.filter(l=>l.resourceID===resource);let label='';if(scene.locationID){if(!resolved.length)label=kind==='maps'?'No mapped representation':'No associated plan';else if(!here.length)label=kind==='maps'?'On another map':'On another plan';else if(kind==='floorplans'&&here.every(l=>l.floorID&&l.floorID!==renderer?.getFloor?.()))label='On another level';else if(kind==='floorplans'&&!here.some(l=>l.blockID))label='Plan available; no associated room';else if(here.some(l=>l.depth))label='Containing location represented';}if(label)row.append(el('small',label,'spatial-elsewhere'));}}
function highlight(){if(!renderer)return;annotate();renderer.highlight(sceneHighlights());const target=resolution(data,selection,kind).find(x=>x.resourceID===resource);if(renderer.selection!==selection){renderer.selection=selection;if(target){if(kind==='floorplans'&&!target.blockID&&target.floorID)renderer.floor?.(target.floorID);else renderer.centre(kind==='maps'?target.featureID:target.blockID,false);}}if(kind==='maps'&&bus.pendingPlacement&&renderer.map?.()){const target=bus.pendingPlacement;bus.pendingPlacement=null;void startPlacement(target).catch(fail);}}
async function renderResource(){if(!canvas)return;updateAdvanced();q('[data-spatial-feature]').replaceChildren();q('[data-spatial-resolution]').textContent=resourceCaption();const item=catalog().find(c=>c.id===resource);if(!item){renderer?.dispose();renderer=null;canvas.replaceChildren(el('p',`No suitable ${kind==='maps'?'map':'floor plan'} is associated. Choose an existing resource above or open the main World workspace.`));return;}if(kind==='maps'&&renderer?.id===resource){renderer.revision=String(item.modifiedDate);renderer.command('reload');return;}if(kind==='floorplans'&&renderer)floorSnapshot={id:renderer.id,floor:renderer.getFloor?.(),selection:renderer.selection};renderer?.dispose();renderer=null;canvas.replaceChildren();const target=resource,scope={...position};if(kind==='maps'){const frame=el('iframe');frame.title='Context map';frame.src=`/SpatialContext/Map?bookId=${scope.bookId}&sceneId=${scope.sceneId}&id=${target}`;const channel=crypto.randomUUID();let features=[],map,ready=false;const command=(action,args={})=>frame.contentWindow?.postMessage({type:'plotdirector.spatial.command',channel,action,...args},location.origin);const receive=e=>{if(e.origin!==location.origin||e.source!==frame.contentWindow||e.data?.channel!==channel||e.data.type!=='plotdirector.spatial.renderer')return;const m=e.data;if(m.action==='ready'){features=m.features;map=m.map;ready=true;highlight();if(bus.pendingPlacement){const target=bus.pendingPlacement;bus.pendingPlacement=null;void startPlacement(target).catch(fail);}}if(m.action==='viewport'){preferences.views??={};preferences.views[target]=m.view;save();}if(m.action==='select'&&m.feature)void(async()=>{if(m.feature.locationID)await select(m.feature.locationID);if(disposed||renderer?.id!==target)return;const detail=q('[data-spatial-feature]');detail.replaceChildren(el('strong',m.feature.name),el('small',m.feature.locationID?'Associated story location':'No associated location; inspection does not assign this feature to a scene.'));if(m.feature.notes)detail.append(el('p',m.feature.notes));q('[data-spatial-advanced]').href=`/Maps?projectId=${position.projectId}&id=${target}&featureId=${encodeURIComponent(m.feature.featureID)}`;})().catch(fail);if(m.action==='cancel'&&operation)clearOperation();if(m.action==='place'&&operation)void savePlacement(m.point);if(m.action==='drop'&&validDrop(m.payload))void dropPlacement(m.payload.locationId,m.point);if(m.action==='error')fail(Error(m.message));};window.addEventListener('message',receive);renderer={id:target,revision:String(item.modifiedDate),command,highlight:items=>command('highlight',{highlights:items}),centre:(id,force)=>{if(ready)command('centre',{id,force});},fit:()=>command('fit',{ids:sceneHighlights().map(h=>h.featureID)}),zoom:factor=>command('zoom',{factor}),features:()=>features,map:()=>map,dispose:()=>window.removeEventListener('message',receive)};frame.onload=()=>command('init',{view:preferences.views?.[target]});canvas.append(frame);}else{const request=++epoch;try{const response=await fetch(`/SpatialContext/Floor?bookId=${scope.bookId}&sceneId=${scope.sceneId}&id=${target}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error('Floor plan unavailable.');const html=await response.text();if(disposed||request!==epoch||resource!==target)return;canvas.innerHTML=html;renderer=floorRenderer(canvas,item);if(floorSnapshot?.id===item.id){renderer.floor?.(floorSnapshot.floor);renderer.selection=floorSnapshot.selection;}highlight();}catch(e){fail(e);}}}
function floorRenderer(host,item){const container=host.querySelector('[data-spatial-floor-canvas]'),world=container.querySelector('[data-spatial-floor-world]'),viewport=container.querySelector('.spatial-floor-viewport'),level=container.querySelector('[data-spatial-floor]'),versions=JSON.parse(container.querySelector('[data-room-versions]').textContent);const engine=window.PlotDirectorFloorPlanRenderer.create(container);let view={x:0,y:0,scale:1},drag=null;const panels=[...container.querySelectorAll('[data-floor-panel]')],blocks=[...container.querySelectorAll('[data-block]')];const signal=new AbortController();function current(){return panels.find(p=>p.dataset.floorPanel===level.value);}function transform(){world.style.transform=`translate(${view.x}px,${view.y}px) scale(${view.scale})`;preferences.floorViews??={};preferences.floorViews[`${item.id}/${level.value}`]={...view};save();}function fit(){const grid=current()?.querySelector('[data-floor-grid]');if(!grid)return;const w=grid.offsetWidth||Number(grid.dataset.gridWidth)*34,h=grid.offsetHeight||Number(grid.dataset.gridHeight)*34;view={scale:Math.min((viewport.clientWidth-24)/w,(viewport.clientHeight-24)/h,1.5),x:12,y:12};transform();}function change(){queueMicrotask(annotate);if(!current()){viewport.replaceChildren(el('p','This plan has no floors yet. Open Floor Plans to add a level.'));return;}for(const p of panels)p.classList.toggle('active',p===current());const visibleBlocks=engine.refreshSharedWalls(current());engine.refreshHiddenLocationStyles(visibleBlocks);engine.positionTransitions(current(),visibleBlocks);view=preferences.floorViews?.[`${item.id}/${level.value}`]||{x:0,y:0,scale:1};transform();if(!preferences.floorViews?.[`${item.id}/${level.value}`])fit();}level.onchange=change;function centre(blockId,force){const block=blocks.find(b=>Number(b.dataset.block)===Number(blockId));if(!block)return;const panel=block.closest('[data-floor-panel]');if(level.value!==panel.dataset.floorPanel){level.value=panel.dataset.floorPanel;change();}blocks.forEach(b=>b.classList.toggle('spatial-selected',b===block));if(force){const x=block.offsetLeft,y=block.offsetTop;view.x=viewport.clientWidth/2-(x+block.offsetWidth/2)*view.scale;view.y=viewport.clientHeight/2-(y+block.offsetHeight/2)*view.scale;transform();}}
function floorRenderer(host,item){const container=host.querySelector('[data-spatial-floor-canvas]'),world=container.querySelector('[data-spatial-floor-world]'),viewport=container.querySelector('.spatial-floor-viewport'),level=container.querySelector('[data-spatial-floor]'),versions=JSON.parse(container.querySelector('[data-room-versions]').textContent);const engine=window.PlotDirectorFloorPlanRenderer.create(container);let view={x:0,y:0,scale:1},drag=null;const panels=[...container.querySelectorAll('[data-floor-panel]')],blocks=[...container.querySelectorAll('[data-block]')];const signal=new AbortController();function current(){return panels.find(p=>p.dataset.floorPanel===level.value);}function transform(){world.style.transform=`translate(${view.x}px,${view.y}px) scale(${view.scale})`;preferences.floorViews??={};preferences.floorViews[`${item.id}/${level.value}`]={...view};save();}function fit(){const grid=current()?.querySelector('[data-floor-grid]');if(!grid)return;const w=grid.offsetWidth||Number(grid.dataset.gridWidth)*34,h=grid.offsetHeight||Number(grid.dataset.gridHeight)*34;view={scale:Math.min((viewport.clientWidth-24)/w,(viewport.clientHeight-24)/h,1.5),x:12,y:12};transform();}function change(){preferences.floorLevels??={};preferences.floorLevels[item.id]=level.value;save();queueMicrotask(annotate);if(!current()){viewport.replaceChildren(el('p','This plan has no floors yet. Open Floor Plans to add a level.'));return;}for(const p of panels)p.classList.toggle('active',p===current());const visibleBlocks=engine.refreshSharedWalls(current());engine.refreshHiddenLocationStyles(visibleBlocks);engine.positionTransitions(current(),visibleBlocks);view=preferences.floorViews?.[`${item.id}/${level.value}`]||{x:0,y:0,scale:1};transform();if(!preferences.floorViews?.[`${item.id}/${level.value}`])fit();}level.onchange=change;function centre(blockId,force){const block=blocks.find(b=>Number(b.dataset.block)===Number(blockId));if(!block)return;const panel=block.closest('[data-floor-panel]');if(level.value!==panel.dataset.floorPanel){level.value=panel.dataset.floorPanel;change();}blocks.forEach(b=>b.classList.toggle('spatial-selected',b===block));if(force){const x=block.offsetLeft,y=block.offsetTop;view.x=viewport.clientWidth/2-(x+block.offsetWidth/2)*view.scale;view.y=viewport.clientHeight/2-(y+block.offsetHeight/2)*view.scale;transform();}}
for(const b of blocks){b.tabIndex=0;b.setAttribute('role','button');b.setAttribute('aria-label',b.textContent.trim());b.addEventListener('click',()=>{if(drag?.moved)return;const location=Number(b.dataset.locationId);if(location)void select(location);showRoom(b);},{signal:signal.signal});b.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();b.click();}},{signal:signal.signal});b.addEventListener('dragover',e=>{if(e.dataTransfer.types.includes(mime)){e.preventDefault();b.classList.add('spatial-drop');}},{signal:signal.signal});b.addEventListener('dragleave',()=>b.classList.remove('spatial-drop'),{signal:signal.signal});b.addEventListener('drop',e=>{e.preventDefault();b.classList.remove('spatial-drop');try{const p=JSON.parse(e.dataTransfer.getData(mime));if(validDrop(p))void associateRoom(b,p.locationId);}catch(error){fail(error);}},{signal:signal.signal});}
viewport.addEventListener('wheel',e=>{e.preventDefault();const r=viewport.getBoundingClientRect(),x=e.clientX-r.left,y=e.clientY-r.top,scale=Math.max(.08,Math.min(4,view.scale*Math.exp(-e.deltaY*.001)));view.x=x-(x-view.x)*scale/view.scale;view.y=y-(y-view.y)*scale/view.scale;view.scale=scale;transform();},{passive:false,signal:signal.signal});viewport.addEventListener('pointerdown',e=>{if(e.button!==0)return;drag={x:e.clientX,y:e.clientY,vx:view.x,vy:view.y,moved:false};if(!e.target.closest('[data-block]'))viewport.setPointerCapture(e.pointerId);},{signal:signal.signal});viewport.addEventListener('pointermove',e=>{if(!drag||!viewport.hasPointerCapture(e.pointerId))return;drag.moved=Math.hypot(e.clientX-drag.x,e.clientY-drag.y)>4;view.x=drag.vx+e.clientX-drag.x;view.y=drag.vy+e.clientY-drag.y;transform();},{signal:signal.signal});viewport.addEventListener('pointerup',e=>{if(viewport.hasPointerCapture(e.pointerId))viewport.releasePointerCapture(e.pointerId);setTimeout(()=>drag=null,0);},{signal:signal.signal});
function showRoom(b){const feature=q('[data-spatial-feature]');feature.replaceChildren(el('span',`Room: ${b.textContent.trim()}`));if(data.scope.canEdit)feature.append(btn('Associate existing location',async()=>{const chosen=await picker('Associate existing location with this room',Number(b.dataset.locationId));if(chosen!==undefined&&chosen!==null)await associateRoom(b,chosen);}),btn('Create location and associate',()=>{const version=versions.find(v=>v.id===Number(b.dataset.block));return createLocation(false,data.planCatalog.find(p=>p.id===resource)?.locationID,{id:Number(b.dataset.block),version:version.version});}));}
async function associateRoom(b,location){if(busy)throw Error('Finish or cancel the current operation first.');if(Number(b.dataset.locationId)===location)return;const version=versions.find(v=>v.id===Number(b.dataset.block));const old=Number(b.dataset.locationId);const target={bookID:position.bookId,sceneID:position.sceneId,kind:'room',locationID:location,resourceID:item.id,geometryID:b.dataset.block,expected:version.version,replace:!!old};await confirmOperation(`Replace the recorded room association? Geometry and location parents will stay unchanged. Connected transition identities must be reviewed in the main editor.`,async()=>finish(await post('/SpatialContext/Mutate',target)));}
change();return {id:item.id,revision:String(item.modifiedDate),blocks,showRoom,highlight:items=>{for(const b of blocks){b.querySelectorAll('.spatial-room-badge').forEach(n=>n.remove());b.classList.remove('spatial-position-0','spatial-position-1','spatial-position-2');const h=items.find(h=>Number(h.featureID)===Number(b.dataset.block));if(h){h.roles.forEach(r=>b.classList.add(`spatial-position-${r+1}`));b.append(el('span',h.roles.map(r=>['Previous','Current','Next'][r+1]).join(' · '),'spatial-room-badge'));b.title=h.label;b.setAttribute('aria-description',h.label);}}},centre,fit,getFloor:()=>Number(level.value),floor:id=>{if(panels.some(p=>Number(p.dataset.floorPanel)===id)){level.value=String(id);change();}},zoom:factor=>{view.scale=Math.max(.08,Math.min(4,view.scale*factor));transform();},dispose:()=>signal.abort()};
if(panels.some(p=>p.dataset.floorPanel===preferences.floorLevels?.[item.id]))level.value=preferences.floorLevels[item.id];change();return {id:item.id,revision:String(item.modifiedDate),blocks,showRoom,highlight:items=>{for(const b of blocks){b.querySelectorAll('.spatial-room-badge').forEach(n=>n.remove());b.classList.remove('spatial-position-0','spatial-position-1','spatial-position-2');const h=items.find(h=>Number(h.featureID)===Number(b.dataset.block));if(h){h.roles.forEach(r=>b.classList.add(`spatial-position-${r+1}`));b.append(el('span',h.roles.map(r=>['Previous','Current','Next'][r+1]).join(' · '),'spatial-room-badge'));b.title=h.label;b.setAttribute('aria-description',h.label);}}},centre,fit,getFloor:()=>Number(level.value),floor:id=>{if(panels.some(p=>Number(p.dataset.floorPanel)===id)){level.value=String(id);change();}},zoom:factor=>{view.scale=Math.max(.08,Math.min(4,view.scale*factor));transform();},dispose:()=>signal.abort()};
}
async function confirmOperation(message,commit){if(busy)throw Error('Finish or cancel the current operation first.');const target={...position};const panel=q('[data-spatial-operation]');panel.hidden=false;panel.replaceChildren(el('p',message));guard(true);panel.append(btn('Confirm',async()=>{try{if(await commit(target)!=='continue')clearOperation();}catch(e){fail(e);}}),btn('Cancel',clearOperation));}
async function startPlacement(location){if(!renderer?.map?.())throw Error('Choose and load a map first.');const existing=renderer.features().find(f=>f.locationID===location);if(existing&&(!existing.isLocked&&existing.geometryClass==='Marker')){await confirmOperation('This location already has a marker on this map. Reposition it explicitly?',()=>beginPlacement(location,existing));return;}if(existing){renderer.centre(existing.featureID,true);throw Error('A representation already exists. Edit complex or locked geometry in Maps.');}beginPlacement(location);}
@ -63,7 +63,7 @@
async function dropPlacement(location,point){try{const existing=renderer?.features().find(f=>f.locationID===location);if(existing)throw Error('This location already has a representation on this map. Use Place location to reveal or explicitly reposition it.');const map=renderer.map(),target={bookID:position.bookId,sceneID:position.sceneId,kind:'map',locationID:location,resourceID:resource,expected:String(map.revision),x:point.x,y:point.y};await confirmOperation('Place this existing location at the dropped map position?',async()=>finish(await post('/SpatialContext/Mutate',target)));}catch(e){fail(e);}}
function chooseRoom(){if(!renderer?.blocks)return;const feature=q('[data-spatial-feature]');feature.replaceChildren(el('p','Select a room to associate an existing location. No geometry or parent location will be changed.'));const plan=data.planCatalog.find(p=>p.id===resource);if(plan)feature.append(btn('Associate this plan with a location',async()=>{const chosen=await picker('Associate floor plan with existing location',plan.locationID);if(chosen===undefined||chosen===null||chosen===plan.locationID)return;const target={bookID:position.bookId,sceneID:position.sceneId,kind:'plan',locationID:chosen,resourceID:resource,expected:plan.version,replace:!!plan.locationID};await confirmOperation('Associate this plan with the selected existing location?',async()=>finish(await post('/SpatialContext/Mutate',target)));}));}
for(const b of node.querySelectorAll('[data-spatial-zoom]'))b.onclick=()=>renderer?.zoom(b.dataset.spatialZoom==='in'?1.25:.8);q('[data-spatial-fit]')?.addEventListener('click',()=>renderer?.fit());q('[data-spatial-centre]')?.addEventListener('click',()=>{const found=resolution(data,selection,kind).find(l=>l.resourceID===resource);if(found)renderer?.centre(kind==='maps'?found.featureID:found.blockID,true);});
instances.set(node,{position(next){if(busy)return false;position=next;void reload();return true;},invalidate(hint){if(busy)return false;if(!['locations','maps','floorplans','spatial','structure','characters','relationships','assets',undefined].includes(hint.kind))return true;if(kind==='floorplans'&&renderer&&['locations','spatial',undefined].includes(hint.kind))renderer.revision=null;invalidateCache();void reload();return true;},dispose(){disposed=true;epoch++;bus.listeners.delete(listener);renderer?.dispose();abort.abort();},busy:()=>busy});void reload();
instances.set(node,{position(next){if(busy)return false;position=next;void reload();return true;},invalidate(hint){if(busy)return false;if(kind==='floorplans'&&renderer&&(hint.kinds||[hint.kind]).some(k=>['floorplans','locations','spatial',undefined].includes(k)))renderer.revision=null;invalidateCache();void reload();return true;},dispose(){disposed=true;epoch++;bus.listeners.delete(listener);renderer?.dispose();abort.abort();},busy:()=>busy});void reload();
}
window.PlotDirectorContextLifecycles??={};window.PlotDirectorContextLifecycles.spatial={mount,onCacheInvalidation:invalidateCache,dispose:node=>{instances.get(node)?.dispose();instances.delete(node);},canRefresh:node=>!instances.get(node)?.busy(),onPosition:(node,next)=>instances.get(node)?.position(next)===true,onInvalidation:(node,hint)=>instances.get(node)?.invalidate(hint)===true};
window.PlotDirectorSpatialContext=Object.freeze({ancestors,resolution,path,subscribe(root,listener){const s=session(root);s.listeners.add(listener);return()=>s.listeners.delete(listener);},inspect(root,location,source){if(location!==null&&(!Number.isSafeInteger(location)||location<=0))throw TypeError('A canonical location identifier is required.');session(root).select(location,source);}});

View File

@ -20,7 +20,8 @@
let navigationRequest, manualGeneration = 0, recoveryPending = false, recoveryAgain = false;
let windowBusy=false;
root.addEventListener("context-window-state",event=>{windowBusy=!!event.detail?.busy;announce();});
const requests = new Map();
const requests = new Map(), tabVersions = new Map();
let invalidationTimer; const pendingHints=[];
const lifecycles = { reference: { mount() {}, dispose() {} }, ...(window.PlotDirectorContextLifecycles || {}) };
const read = (name,key) => { try { return window[name].getItem(key); } catch { return null; } };
const write = (name,key,value) => { try { window[name].setItem(key,value); return true; } catch { return false; } };
@ -69,7 +70,7 @@
const url=new URL(tab.endpoint,location.origin);
for(const field of fields)if(position[field]!=null)url.searchParams.set(field,position[field]);
if(position.instanceId&&position.sessionId&&!pinned){url.searchParams.set('instanceId',position.instanceId);url.searchParams.set('sessionId',position.sessionId);}
const key=`${generation}:${url.href}`;
const key=`${generation}:${tabVersions.get(tab.id)||0}:${url.href}`;
if(!requests.has(key)){
const controller=new AbortController();
const timer=setTimeout(()=>controller.abort(),20000);
@ -79,7 +80,7 @@
if(!response.ok)throw Error('Saved reference unavailable. Check book access and choose a saved scene, or retry.');
return await response.text();
}).finally(()=>{clearTimeout(timer);if(requests.get(key)?.controller===controller)requests.delete(key);});
requests.set(key,{controller,promise});
requests.set(key,{controller,promise,tabId:tab.id});
}
return requests.get(key).promise;
}
@ -122,21 +123,50 @@
const count=level===1?2:level===2?3:level===3?4:5;
return fields.slice(0,count).some(field=>before[field]!==after[field]);
};
const affectedPanels = {
overview:['overview'], maps:['maps'], floorplans:['floorplans'], locations:['overview','locations','maps','floorplans'],
spatial:['locations','maps','floorplans'], names:['names'],
characters:['overview','characters','relationships','names','maps','floorplans'],
relationships:['overview','characters','relationships'],
dates:['overview','calendar'], intent:['overview','intent'],
plotlines:['overview','intent','plotlines','threads'], threads:['overview','intent','threads'],
metrics:['overview','metrics'], assets:['overview','assets','maps','floorplans']
};
function inScope(hint) {
return !(hint.projectId&&scope.projectId&&Number(hint.projectId)!==scope.projectId) &&
!(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId);
}
function affects(tab,hint) {
return tab.contentRefresh!=='none' && (!affectedPanels[hint.kind] || affectedPanels[hint.kind].includes(tab.id));
}
function invalidate(hint={}) {
if(hint.projectId&&scope.projectId&&Number(hint.projectId)!==scope.projectId)return;
if(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId)return;
generation++;cancelRequests();
for(const pane of panes){for(const record of pane.records.values()){
if(record.tab.contentRefresh==='none')continue;
lifecycles[record.tab.lifecycle]?.onCacheInvalidation?.(hint,record.node);
const customInvalidation=lifecycles[record.tab.lifecycle]?.onInvalidation;
if(customInvalidation){if(record.mounted&&visible(pane)&&!guarded(record)&&!scopeChanged(record.tab,record.position||position,position)&&customInvalidation(record.node,hint)===true){record.stale=false;continue;}record.stale=true;continue;}
if(hint.kind==='names'&&record.tab.id!=='names')continue;
if(hint.kind==='relationships'&&!['overview','characters','relationships'].includes(record.tab.id))continue;
if(hint.kind==='characters'&&!['overview','characters','relationships','names'].includes(record.tab.id))continue;
// Scene projections can depend on established earlier records: book-level is conservative.
record.stale=true;
}void refreshPane(pane);}
if(!inScope(hint))return;
pendingHints.push(hint);
// One burst can contain several canonical writes and the local save receipt.
// Hold controls narrative position only; it does not suppress saved-data refresh.
if(!invalidationTimer)invalidationTimer=setTimeout(flushInvalidations,60);
}
function flushInvalidations() {
invalidationTimer=null;
const hints=pendingHints.splice(0);
if(hints.some(h=>h.kind==='structure'))void refreshStructure();
const affected=new Set([...registry.values()].filter(tab=>hints.some(h=>affects(tab,h))).map(tab=>tab.id));
for(const id of affected)tabVersions.set(id,(tabVersions.get(id)||0)+1);
for(const [key,item] of requests)if(affected.has(item.tabId)){item.controller.abort();requests.delete(key);}
for(const pane of panes){
for(const record of pane.records.values()){
if(!affected.has(record.tab.id))continue;
const relevant=hints.filter(h=>affects(record.tab,h)),hint={...relevant[0],kinds:[...new Set(relevant.map(h=>h.kind))]};
lifecycles[record.tab.lifecycle]?.onCacheInvalidation?.(hint,record.node);
const customInvalidation=lifecycles[record.tab.lifecycle]?.onInvalidation;
if(customInvalidation&&record.mounted&&visible(pane)&&!guarded(record)&&!scopeChanged(record.tab,record.position||position,position)&&customInvalidation(record.node,hint)===true){record.stale=false;continue;}
record.stale=true;
}
if(affected.has(state.panes[pane.index].tab)){
pane.revision++;pane.host.removeAttribute('aria-busy');
void refreshPane(pane);
}
}
}
function setPosition(next,force=false) {
if((scope.bookId&&number(next.bookId)!==scope.bookId)||(scope.projectId&&number(next.projectId)&&number(next.projectId)!==scope.projectId))return;
@ -206,7 +236,7 @@
connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();
connection.on('NativePresenceChanged',hint=>{window.dispatchEvent(new CustomEvent('plotdirector:native-presence-changed',{detail:hint}));wakeStatus();});
connection.on('ContextPositionChanged',()=>void recoverOffice());
connection.on('ContextInvalidated',hint=>{invalidate(hint);if(hint.kind==='structure')void refreshStructure();wakeStatus();});
connection.on('ContextInvalidated',(hint={})=>{if(!inScope(hint))return;invalidate(hint);});
connection.onreconnecting(()=>{status.hidden=false;status.textContent='Context notifications reconnecting · saved reference may be stale';});
connection.onreconnected(()=>{wakeStatus(true);void recoverOffice(true);invalidate();root.dispatchEvent(new Event('context-connection-ready'));});
connection.onclose(()=>{status.hidden=false;status.textContent='Context notifications disconnected · saved browsing remains available';});
@ -236,7 +266,7 @@
const observer=new ResizeObserver(()=>applyLayout());observer.observe(grid);
window.addEventListener('beforeunload',event=>{if(panes.some(p=>[...p.records.values()].some(guarded))){event.preventDefault();event.returnValue='';}});
root.contextController={openTool:(id,source,destination)=>{if(!registry.has(id))return false;const existing=panes.find(p=>visible(p)&&state.panes[p.index].tab===id);if(existing)return true;const index=destination==='current'?Number(source):1-Number(source);const pane=panes[index];if(!pane||guarded(current(pane)))return false;if(index===1&&state.layout==='single')state.layout='columns';remember(pane);dispose(current(pane));state.panes[index].tab=id;applyLayout();return true;}, get windowId(){return windowId;}, get position(){return {...position};}, invalidate,setPosition,get connection(){return connection;},get announcement(){return {version:1,bookID:position.bookId,windowID:windowId,panes:panes.filter(visible).map(pane=>({paneID:String(pane.index),toolID:state.panes[pane.index].tab,actions:registry.get(state.panes[pane.index].tab).actions||[],available:!windowBusy&&!!current(pane)?.node&&!current(pane).stale&&!guarded(current(pane))}))};},receiveInteraction:async delivery=>{if(windowBusy)return 'busy';const pane=panes.find(p=>String(p.index)===delivery.paneID);if(!pane||!visible(pane))return 'not-visible';const record=current(pane);if(guarded(record))return 'busy';if(!record?.node||record.stale)return 'unavailable';record.stale=true;await refreshPane(pane);if(record.stale||guarded(record))return 'unavailable';return await lifecycles[record.tab.lifecycle]?.onInteraction?.(record.node,delivery.command,{position:{...position},pane})||'not-visible';},registerLifecycle:(name,hooks)=>lifecycles[name]=hooks };
window.addEventListener('pagehide',()=>{stopped=true;panes.forEach(pane=>{remember(pane);dispose(current(pane));});save();cancelRequests();navigationRequest?.abort();clearInterval(timer);observer.disconnect();channel?.close();void connection?.stop();});
window.addEventListener('pagehide',()=>{stopped=true;clearTimeout(invalidationTimer);panes.forEach(pane=>{remember(pane);dispose(current(pane));});save();cancelRequests();navigationRequest?.abort();clearInterval(timer);observer.disconnect();channel?.close();void connection?.stop();});
save();applyLayout();
status.textContent='';status.hidden=true;
})();