Add Context Assets panel with historical possession and location evidence

This commit is contained in:
Atlas Development Worker 2026-12-02 19:57:26 +00:00
parent c9847210aa
commit 5692df353a
14 changed files with 292 additions and 12 deletions

View File

@ -0,0 +1,33 @@
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
(async()=>{
const browser=await chromium.launch({headless:true});
try{
const page=await browser.newPage({viewport:{width:1280,height:850}});
await page.route('http://assets.test/**',r=>r.fulfill({contentType:'text/html',body:'<main data-context-workspace data-user="fixture"></main>'}));
await page.goto('http://assets.test');
await page.addStyleTag({content:fs.readFileSync('PlotLine/wwwroot/css/context-spatial.css','utf8')+' main {height:750px}'});
for(const name of ['context-spatial','context-assets'])await page.addScriptTag({content:fs.readFileSync(`PlotLine/wwwroot/js/${name}.js`,'utf8')});
const frame={scope:{projectID:7,sceneID:3},assets:[1,2].map(id=>({asset:{storyAssetID:id,assetName:`Parcel ${id}`,kindName:'Object',description:'Saved description'},presence:id===1?'Mentioned':'Present',openingHolder:{value:id===1?'Recipient':'Unknown',sceneID:id===1?1:null,sceneLabel:'Handover'},openingLocation:{value:'Office',sceneID:2,sceneLabel:'Move'},changes:['Mentioned: parcel']}))};
async function mount(data,pane=0){await page.evaluate(({data,pane})=>{
const previous=document.querySelector(`[data-pane="${pane}"]`);if(previous){PlotDirectorContextLifecycles.assets.dispose(previous);previous.remove();}
const node=document.createElement('div');node.dataset.pane=pane;node.className='context-spatial';node.style.height='700px';node.innerHTML='<select data-spatial-orientation><option value="horizontal">Side by side</option><option value="vertical">Stacked</option></select><div class="spatial-split-layout" data-spatial-layout><nav data-asset-list></nav><div data-spatial-splitter></div><section data-asset-detail></section></div><script type="application/json" data-assets-payload></script>';
node.querySelector('script').textContent=JSON.stringify(data);document.querySelector('main').append(node);PlotDirectorContextLifecycles.assets.mount(node,{windowId:'window1',paneId:pane});
},{data,pane});}
await mount(frame);
assert.equal(await page.locator('[data-spatial-splitter]').getAttribute('aria-valuenow'),'30');
assert.match(await page.locator('[data-asset-detail]').innerText(),/Recipient/);
assert.deepEqual(await page.locator('[data-asset-detail] a').evaluateAll(nodes=>nodes.map(n=>n.getAttribute('href'))),['/StoryAssets/Details/1','/Scenes/Edit/1','/Scenes/Edit/2']);
await page.getByRole('button',{name:'Parcel 2 · Present'}).click();
const next=structuredClone(frame);next.scope.sceneID=4;await mount(next);
assert.equal(await page.locator('[data-asset-detail] h3').first().innerText(),'Parcel 2');
assert.match(await page.locator('[data-asset-detail]').innerText(),/Unknown/);
await page.locator('[data-spatial-splitter]').focus();await page.keyboard.press('ArrowRight');assert.equal(await page.locator('[data-spatial-splitter]').getAttribute('aria-valuenow'),'32');
await page.setViewportSize({width:460,height:850});await page.waitForFunction(()=>document.querySelector('[data-spatial-layout]').dataset.orientation==='vertical');
assert.equal(await page.locator('[data-spatial-splitter]').getAttribute('aria-orientation'),'horizontal');
const boxes=await page.locator('[data-spatial-layout]').evaluate(n=>[...n.children].map(x=>x.getBoundingClientRect().toJSON()));assert(boxes[2].y>boxes[0].y);assert(boxes.every(b=>b.width>0&&b.height>0));
await page.setViewportSize({width:1280,height:850});await page.waitForFunction(()=>document.querySelector('[data-spatial-layout]').dataset.orientation==='horizontal');assert.equal(await page.locator('[data-spatial-splitter]').getAttribute('aria-valuenow'),'32');
await mount(frame,1);assert.equal(await page.locator('[data-pane="1"] [data-spatial-splitter]').getAttribute('aria-valuenow'),'30');assert.equal(await page.locator('[data-pane="1"] [data-asset-detail] h3').first().innerText(),'Parcel 1');
next.assets=[];await mount(next);assert.match(await page.locator('[data-pane="0"] [data-asset-list]').innerText(),/No assets linked/);
console.log('PASS Context Assets source links, selection across scenes, unknown possession, shared splitter keyboard, narrow stacking, pane isolation and empty scene');
}finally{await browser.close();}
})().catch(e=>{console.error(e);process.exitCode=1;});

View File

@ -0,0 +1,39 @@
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services.Context;
internal static class ContextAssetsTests
{
public static void Run()
{
var scenes = new Scene[] { new(){SceneID=10}, new(){SceneID=20}, new(){SceneID=30}, new(){SceneID=40} };
var asset = new StoryAsset { StoryAssetID=1, ProjectID=7, AssetName="Parcel", CurrentLocationName="Future metadata" };
var scope = new SpatialScope { ProjectID=7, SceneID=30 };
var history = new StoryPointHistory {
AssetLocations=[new(){StoryAssetID=1,SceneID=10,LocationPath="Depot"},new(){StoryAssetID=1,SceneID=20,LocationPath="Office"},new(){StoryAssetID=1,SceneID=40,LocationPath="Future"}],
Custody=[new(){StoryAssetID=1,SceneID=10,AssetCustodyEventID=1},new(){StoryAssetID=1,SceneID=20,AssetCustodyEventID=2},new(){StoryAssetID=1,SceneID=40,AssetCustodyEventID=3}],
Custodians=[new(){AssetCustodyEventID=1,RoleName="Has Custody",CharacterName="First"},new(){AssetCustodyEventID=2,RoleName="Transfers From",CharacterName="First"},new(){AssetCustodyEventID=2,RoleName="Transfers To",CharacterName="Second"},new(){AssetCustodyEventID=2,RoleName="Observes",CharacterName="Witness"},new(){AssetCustodyEventID=3,RoleName="Has Custody",CharacterName="Future"}]
};
var mention = new AssetEvent {StoryAssetID=1, SceneID=30, AssetEventTypeName="Mentioned", ToStateName="Legacy state"};
var row = ContextAssets.Build(scope,scenes,[asset],[mention],history).Assets.Single();
Check(row.Presence=="Mentioned" && row.OpeningHolder.Value=="Second" && row.OpeningHolder.SceneID==20,"Handover uses recipient, not sender/observer or future holder");
Check(row.OpeningLocation.Value=="Office" && row.OpeningLocation.SceneID==20,"Opening uses historical location, independently of holder and metadata");
Check(!row.Changes.Any(c=>c.Contains("Legacy state")),"Mention does not present a state transition");
var moveOnly = new StoryPointHistory {AssetLocations=history.AssetLocations, Custody=[history.Custody[0]], Custodians=history.Custodians};
row=ContextAssets.Build(scope,scenes,[asset],[mention],moveOnly).Assets.Single();
Check(row.OpeningHolder.Value=="First" && row.OpeningHolder.SceneID==10 && row.OpeningLocation.SceneID==20,"Location-only move retains independent holder source");
row=ContextAssets.Build(scope,scenes,[asset],[mention],new(){AssetLocations=history.AssetLocations}).Assets.Single();
Check(row.OpeningHolder.Value=="Unknown" && row.OpeningHolder.SceneID==null && row.OpeningLocation.Value=="Office","Move with no holder evidence stays unknown");
Check(ContextAssets.Holder(new(){AssetCustodyEventID=2,CustodyEventTypeName="Lost By"},history.Custodians)=="Unknown","Explicit loss clears holder despite participants");
Check(ContextAssets.Holder(new(){AssetCustodyEventID=99},[])=="Unknown","Explicit empty custody clears holder");
Check(ContextAssets.Holder(new(){AssetCustodyEventID=4},[new(){AssetCustodyEventID=4,RoleName="Observes",CharacterName="Witness"}])==null,"Observer is not possession");
Check(ContextAssets.Holder(new(){AssetCustodyEventID=4},[new(){AssetCustodyEventID=4,RoleName="Transfers To"}])=="Unknown","Unnamed recipient clears stale known possession");
mention.AssetEventTypeName="Present";
Check(ContextAssets.Build(scope,scenes,[asset],[mention],history).Assets.Single().Presence=="Present","Explicit presence recorded");
mention.AssetEventTypeName="Used";
Check(ContextAssets.Build(scope,scenes,[asset],[mention],history).Assets.Single().Presence=="Unrecorded","Legacy action does not imply presence");
Check(ContextAssets.Build(scope,scenes,[asset],[],new()).Assets.Count==0,"Unlinked asset omitted");
Check(ContextWorkspaceNavigation.IsAllowed("/StoryAssets/Details/1"),"Asset uses permitted main-window navigation");
Check(!ContextWorkspaceNavigation.IsAllowed("/StoryAssets/Delete/1"),"No destructive destination added");
}
private static void Check(bool value,string message){if(!value)throw new Exception(message);}
}

View File

@ -15,6 +15,7 @@ using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
if(args.Contains("--context-assets")){ContextAssetsTests.Run();Console.WriteLine("PASS Context Assets historical custody and location");return;}
if(args.Contains("--context-warnings")){ContextWarningsTests.Run();return;}
if(args.Contains("--context-metrics")){ContextMetricsTests.Run();return;}
if(args.Contains("--scene-creation")){await SceneCreationTests.Run();return;}
@ -242,6 +243,7 @@ var tests = new (string Name, Action Test)[]
("Context Family/Story projection and bounded reads",()=>ContextRelationshipLensTests.Run().GetAwaiter().GetResult()),
("Context Names Library query parity and bounded identities",()=>ContextNamesTests.Run().GetAwaiter().GetResult()),
("Context relationship state and focused editing",()=>ContextRelationshipTests.Run().GetAwaiter().GetResult()),
("Context Assets historical custody and location",ContextAssetsTests.Run),
("Context warnings recorded evidence and freshness",ContextWarningsTests.Run),
("Context Metrics window and recorded values",ContextMetricsTests.Run),
("Context Threads narrative history and scope",ContextThreadsTests.Run),

View File

@ -153,6 +153,24 @@ public sealed class WritingController(
catch (Microsoft.Data.SqlClient.SqlException e) when (e.Number == 51010) { return Forbid(); }
}
[HttpGet("Context/Assets")]
public async Task<IActionResult> ContextAssetsTab(int? projectId, int? bookId, int? chapterId, int? sceneId,
Guid? instanceId, Guid? sessionId, [FromServices] PlotLine.Services.Context.ContextAssets assets)
{
if (!ModelState.IsValid || bookId is not > 0 || sceneId is not > 0 || InvalidNativeSelection(instanceId, sessionId)) return BadRequest();
var native = instanceId.HasValue ? await NativeTarget(bookId, instanceId, sessionId) : null;
if (instanceId.HasValue && (native == null || native.SceneId != sceneId || chapterId.HasValue && native.ChapterId != chapterId)) return Conflict();
try
{
var frame = await assets.Read(bookId.Value, sceneId.Value);
var scope = frame.Scope;
if (projectId.HasValue && projectId != scope.ProjectID || chapterId.HasValue && chapterId != scope.ChapterID) return BadRequest();
if (instanceId.HasValue && !SameNativeTarget(native, await NativeTarget(bookId, instanceId, sessionId))) return Conflict();
return PartialView("_ContextAssets", frame);
}
catch (Microsoft.Data.SqlClient.SqlException e) when (e.Number == 51010) { return Forbid(); }
}
[HttpGet("Context/Locations")]
public Task<IActionResult> ContextLocations(int? projectId,int? bookId,int? chapterId,int? sceneId,Guid? instanceId,Guid? sessionId,[FromServices] PlotLine.Services.Context.ContextSpatial spatial)
=>RenderSpatial("locations",projectId,bookId,chapterId,sceneId,instanceId,sessionId,spatial);

View File

@ -310,6 +310,7 @@ public class Program
builder.Services.AddScoped<PlotLine.Services.Context.ContextNames>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextSpatial>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextThreads>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextAssets>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextWarnings>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextRelationshipEditing>();
builder.Services.AddScoped<PlotLine.Data.IContextRelationshipReader,PlotLine.Data.ContextRelationshipReader>();

View File

@ -0,0 +1,76 @@
using PlotLine.Data;
using PlotLine.Models;
namespace PlotLine.Services.Context;
public sealed record ContextAssetEvidence(string Value, int? SceneID, string? SceneLabel);
public sealed record ContextAssetRow(StoryAsset Asset, string Presence, ContextAssetEvidence OpeningHolder,
ContextAssetEvidence OpeningLocation, IReadOnlyList<string> Changes);
public sealed record ContextAssetsFrame(SpatialScope Scope, IReadOnlyList<ContextAssetRow> Assets);
// A projection of canonical events, never a persisted second continuity model.
public sealed class ContextAssets(ContextSpatial spatial, ITimelineRepository timeline,
IAssetRepository assets, IStoryPointRepository history)
{
public async Task<ContextAssetsFrame> Read(int bookId, int sceneId)
{
var scope = await spatial.Scope(bookId, sceneId);
var order = StoryStateService.OrderScenes(await timeline.GetByProjectAsync(scope.ProjectID, null, false, [], false)).ToArray();
var catalog = await assets.ListAssetsAsync(scope.ProjectID);
var events = await assets.ListEventsBySceneAsync(sceneId);
var point = await history.GetHistoryAsync(scope.ProjectID, sceneId);
return Build(scope, order, catalog, events, point);
}
public static bool IsMention(string type) => type is "Mentioned" or "First Mentioned";
public static bool IsReferenceOnly(string type) => IsMention(type) || type == "Present";
public static ContextAssetsFrame Build(SpatialScope scope, IReadOnlyList<Scene> order,
IReadOnlyList<StoryAsset> assets, IReadOnlyList<AssetEvent> events, StoryPointHistory history)
{
var indexes = order.Select((s, i) => (s.SceneID, i)).ToDictionary(x => x.SceneID, x => x.i);
if (!indexes.TryGetValue(scope.SceneID, out var boundary)) throw new ArgumentException("Scene order unavailable.");
var labels = order.ToDictionary(s => s.SceneID, s => $"Scene {s.SceneNumber:0.##}: {s.SceneTitle}");
bool Before(int scene) => indexes.TryGetValue(scene, out var index) && index < boundary;
ContextAssetEvidence Evidence(string? value, int? scene) => new(string.IsNullOrWhiteSpace(value) ? "Unknown" : value,
scene, scene.HasValue ? labels.GetValueOrDefault(scene.Value) : null);
var linked = events.Where(e => e.SceneID == scope.SceneID).Select(e => e.StoryAssetID)
.Concat(history.AssetLocations.Where(e => e.SceneID == scope.SceneID).Select(e => e.StoryAssetID))
.Concat(history.Custody.Where(e => e.SceneID == scope.SceneID).Select(e => e.StoryAssetID)).ToHashSet();
var rows = new List<ContextAssetRow>();
foreach (var asset in assets.Where(a => a.ProjectID == scope.ProjectID && !a.IsArchived && linked.Contains(a.StoryAssetID)).OrderByDescending(a => a.Importance).ThenBy(a => a.AssetName))
{
var current = events.Where(e => e.StoryAssetID == asset.StoryAssetID && e.SceneID == scope.SceneID).OrderBy(e => e.UpdatedDate).ThenBy(e => e.AssetEventID).ToArray();
var presence = current.Any(e => e.AssetEventTypeName == "Present") ? "Present"
: current.Any(e => IsMention(e.AssetEventTypeName)) ? "Mentioned" : "Unrecorded";
var location = history.AssetLocations.Where(e => e.StoryAssetID == asset.StoryAssetID && Before(e.SceneID))
.OrderBy(e => indexes[e.SceneID]).ThenBy(e => e.UpdatedDate).ThenBy(e => e.SceneAssetLocationID).LastOrDefault();
var holder = Evidence(null, null);
foreach (var custody in history.Custody.Where(e => e.StoryAssetID == asset.StoryAssetID && Before(e.SceneID))
.OrderBy(e => indexes[e.SceneID]).ThenBy(e => e.UpdatedDate).ThenBy(e => e.AssetCustodyEventID))
{
var value = Holder(custody, history.Custodians);
if (value != null) holder = Evidence(value, custody.SceneID);
}
var changes = current.Select(e => $"{e.AssetEventTypeName}: {e.EventTitle}" +
(string.IsNullOrWhiteSpace(e.EventDescription) ? "" : $" · {e.EventDescription}") +
(!IsReferenceOnly(e.AssetEventTypeName) && !string.IsNullOrWhiteSpace(e.ToStateName) ? $" · state: {e.ToStateName}" : "")).ToList();
changes.AddRange(history.AssetLocations.Where(e => e.StoryAssetID == asset.StoryAssetID && e.SceneID == scope.SceneID)
.OrderBy(e => e.UpdatedDate).ThenBy(e => e.SceneAssetLocationID).Select(e => $"Location recorded: {e.LocationPath ?? e.LocationName ?? "Unknown"}"));
changes.AddRange(history.Custody.Where(e => e.StoryAssetID == asset.StoryAssetID && e.SceneID == scope.SceneID)
.OrderBy(e => e.UpdatedDate).ThenBy(e => e.AssetCustodyEventID).Select(e => $"{e.CustodyEventTypeName}: " + (Holder(e, history.Custodians) ?? "No possession change recorded")));
rows.Add(new(asset, presence, holder, Evidence(location?.LocationPath ?? location?.LocationName, location?.SceneID), changes));
}
return new(scope, rows);
}
// null means no transition; Unknown means an explicit clearing of possession.
public static string? Holder(AssetCustodyEvent custody, IReadOnlyList<AssetCustodyCharacter> participants)
{
var rows = participants.Where(p => p.AssetCustodyEventID == custody.AssetCustodyEventID).ToArray();
if (custody.CustodyEventTypeName == "Lost By" || rows.Length == 0) return "Unknown";
var holders = rows.Where(p => p.RoleName is "Has Custody" or "Shared Custody" or "Transfers To")
.Select(p => string.IsNullOrWhiteSpace(p.CharacterName) ? p.CharacterNameText : p.CharacterName)
.Select(n => string.IsNullOrWhiteSpace(n) ? "Unknown" : n).Distinct().ToArray();
return holders.Length == 0 ? null : string.Join(", ", holders);
}
}

View File

@ -13,6 +13,6 @@ public static partial class ContextWorkspaceNavigation
return MainPage().IsMatch(path);
}
[GeneratedRegex(@"^/(?:Characters(?:/(?:Details|Edit)/[1-9][0-9]*)?|Locations(?:/(?:Details|Edit)/[1-9][0-9]*)?|Maps|FloorPlans(?:/Edit/[1-9][0-9]*)?|Scenes/Edit/[1-9][0-9]*|Names|RelationshipMap|StoryCalendar|PlotLineWorkspace|PlotThreads/Edit/[1-9][0-9]*|Warnings|Timeline|Writer|Books/Details/[1-9][0-9]*|manuscript/paragraphs)/?$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
[GeneratedRegex(@"^/(?:Characters(?:/(?:Details|Edit)/[1-9][0-9]*)?|StoryAssets/Details/[1-9][0-9]*|Locations(?:/(?:Details|Edit)/[1-9][0-9]*)?|Maps|FloorPlans(?:/Edit/[1-9][0-9]*)?|Scenes/Edit/[1-9][0-9]*|Names|RelationshipMap|StoryCalendar|PlotLineWorkspace|PlotThreads/Edit/[1-9][0-9]*|Warnings|Timeline|Writer|Books/Details/[1-9][0-9]*|manuscript/paragraphs)/?$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
private static partial Regex MainPage();
}

View File

@ -0,0 +1,63 @@
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Canonical, explicit presence. Never infer it from legacy action/state events.
IF NOT EXISTS (SELECT 1 FROM dbo.AssetEventTypes WHERE TypeName = N'Present')
INSERT dbo.AssetEventTypes (TypeName, MarkerText, SortOrder, IsActive)
VALUES (N'Present', N'P', 5, 1);
GO
CREATE OR ALTER PROCEDURE dbo.AssetEvent_Save
@AssetEventID int = NULL,
@StoryAssetID int,
@SceneID int,
@AssetEventTypeID int,
@FromStateID int = NULL,
@ToStateID int = NULL,
@EventTitle nvarchar(200),
@EventDescription nvarchar(max) = NULL
AS
BEGIN
SET NOCOUNT ON;
-- Presence/mention records describe a scene link, not a narrative transition.
-- Discard stale state controls from every existing event editor.
IF EXISTS (SELECT 1 FROM dbo.AssetEventTypes WHERE AssetEventTypeID = @AssetEventTypeID
AND TypeName IN (N'Present', N'Mentioned', N'First Mentioned'))
BEGIN
SET @FromStateID = NULL;
SET @ToStateID = NULL;
END;
IF @AssetEventID IS NULL OR @AssetEventID = 0
BEGIN
INSERT dbo.AssetEvents (StoryAssetID, SceneID, AssetEventTypeID, FromStateID, ToStateID, EventTitle, EventDescription)
VALUES (@StoryAssetID, @SceneID, @AssetEventTypeID, @FromStateID, @ToStateID, @EventTitle, @EventDescription);
SET @AssetEventID = CAST(SCOPE_IDENTITY() AS int);
END
ELSE
BEGIN
UPDATE dbo.AssetEvents
SET StoryAssetID = @StoryAssetID,
SceneID = @SceneID,
AssetEventTypeID = @AssetEventTypeID,
FromStateID = @FromStateID,
ToStateID = @ToStateID,
EventTitle = @EventTitle,
EventDescription = @EventDescription,
UpdatedDate = SYSUTCDATETIME()
WHERE AssetEventID = @AssetEventID;
END
IF @ToStateID IS NOT NULL
BEGIN
UPDATE dbo.StoryAssets
SET CurrentStateID = @ToStateID,
IsResolved = CASE WHEN EXISTS (SELECT 1 FROM dbo.AssetStates WHERE AssetStateID = @ToStateID AND IsResolvedState = 1) THEN 1 ELSE IsResolved END,
UpdatedDate = SYSUTCDATETIME()
WHERE StoryAssetID = @StoryAssetID;
END
SELECT @AssetEventID;
END;
GO

View File

@ -75,8 +75,9 @@
<div class="scene-inspector-editor-grid">
<div class="form-group">
<label for="NewAssetEvent_AssetEventTypeID">Event type</label>
<label for="NewAssetEvent_AssetEventTypeID">Event type / presence</label>
<select class="form-control form-control-sm" id="NewAssetEvent_AssetEventTypeID" name="NewAssetEvent.AssetEventTypeID" asp-items="Model.AssetEventTypeOptions"></select>
<small class="muted">Choose Present or Mentioned explicitly. Neither changes narrative state.</small>
</div>
<div class="form-group">
<label for="NewAssetEvent_ToStateID">To state</label>

View File

@ -5,6 +5,7 @@
ViewData["Title"] = "Context";
var position = Model.Display?.Context?.Position;
var tabs = new[] {
new { id = "assets", displayName = "Assets", endpoint = Url.Action("ContextAssetsTab", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "assets", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty<string>() },
new { id = "warnings", displayName = "Warnings", endpoint = Url.Action("ContextWarningsTab", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "warnings", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty<string>() },
new { id = "metrics", displayName = "Metrics", endpoint = Url.Action("ContextMetrics", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "metrics", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty<string>() },
new { id = "threads", displayName = "Threads", endpoint = Url.Action("ContextThreadsTab", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "threads", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty<string>() },
@ -81,6 +82,7 @@
<script src="~/js/context-warnings.js" asp-append-version="true"></script>
<script src="~/js/context-threads.js" asp-append-version="true"></script>
<script src="~/js/context-spatial.js" asp-append-version="true"></script>
<script src="~/js/context-assets.js" asp-append-version="true"></script>
<script src="~/js/context-calendar-model.js" asp-append-version="true"></script>
<script src="~/js/context-calendar.js" asp-append-version="true"></script>
<script src="~/js/context-workspace.js" asp-append-version="true"></script>

View File

@ -0,0 +1,12 @@
@using System.Text.Json
@{ Layout = null; }
@model PlotLine.Services.Context.ContextAssetsFrame
<div data-context-tab-fragment data-context-assets data-project-id="@Model.Scope.ProjectID" data-book-id="@Model.Scope.BookID" data-chapter-id="@Model.Scope.ChapterID" data-scene-id="@Model.Scope.SceneID" class="context-spatial">
<h2>Assets · @Model.Scope.Label</h2>
<div class="spatial-toolbar"><label>Layout <select data-spatial-orientation aria-label="Assets panel layout"><option value="horizontal">Side by side</option><option value="vertical">Stacked</option></select></label></div>
<div class="spatial-split-layout" data-spatial-layout>
<nav data-asset-list aria-label="Scene-linked assets"></nav><div data-spatial-splitter></div>
<section data-asset-detail aria-label="Selected asset"></section>
</div>
<script type="application/json" data-assets-payload>@Html.Raw(JsonSerializer.Serialize(Model, new JsonSerializerOptions(JsonSerializerDefaults.Web)))</script>
</div>

View File

@ -0,0 +1,31 @@
(() => {
'use strict';
const instances = new WeakMap();
const el = (tag, text, cls) => { const n = document.createElement(tag); if(text != null)n.textContent=text; if(cls)n.className=cls; return n; };
function mount(node, context) {
if(instances.has(node))return;
const data=JSON.parse(node.querySelector('[data-assets-payload]').textContent), root=node.closest('[data-context-workspace]'), abort=new AbortController();
const key=`plotdirector.assets.v1.${root.dataset.user}.${context.windowId}.${data.scope.projectID}.${context.paneId}`;
let selected;try{selected=Number(localStorage.getItem(key));}catch{}
window.PlotDirectorSpatialContext.layout(node,`${key}.layout`,abort.signal,true);
const list=node.querySelector('[data-asset-list]'),detail=node.querySelector('[data-asset-detail]');
function link(text,url,scene){const a=el('a',text);a.href=url;if(scene)a.dataset.contextOpenScene=scene;return a;}
function evidence(title,value){const section=el('section');section.append(el('h4',title,'h6'),el('p',value.value));if(value.sceneID)section.append(link(`Source: ${value.sceneLabel}`,`/Scenes/Edit/${value.sceneID}`,value.sceneID));else section.append(el('small','No earlier evidence recorded.'));return section;}
function render(){
list.replaceChildren();detail.replaceChildren();
if(!data.assets.length){list.append(el('p','No assets linked to this scene.'));detail.append(el('p','Record asset events, locations or custody in the scene editor.'));return;}
const row=data.assets.find(r=>r.asset.storyAssetID===selected)||data.assets[0]; selected=row.asset.storyAssetID;
try{localStorage.setItem(key,String(selected));}catch{}
for(const item of data.assets){const b=el('button',`${item.asset.assetName} · ${item.presence}`,'w-100 text-start mb-1');b.type='button';b.classList.toggle('active',item===row);b.setAttribute('aria-pressed',String(item===row));b.addEventListener('click',()=>{selected=item.asset.storyAssetID;try{localStorage.setItem(key,String(selected));}catch{}render();},{signal:abort.signal});list.append(b);}
const a=row.asset;
detail.append(el('h3',a.assetName,'h5'),el('p',`${a.kindName} · ${row.presence}`),link('Open Asset',`/StoryAssets/Details/${a.storyAssetID}`));
detail.append(el('h3','At scene opening','h6'),evidence('Holder (possession)',row.openingHolder),evidence('Location',row.openingLocation),el('small','Ownership: unrecorded. Possession does not establish ownership.'));
detail.append(el('h3','Current-scene records','h6'));
const changes=el('ul');for(const change of row.changes)changes.append(el('li',change));detail.append(changes);
detail.append(el('small','Mentions and Present records do not change continuity. Legacy action events alone do not establish presence.'),el('h3','Description','h6'),el('p',a.description||'No description recorded.','spatial-description'));
if(a.imagePath){const image=el('img');image.src=a.imagePath;image.alt=a.assetName;image.loading='lazy';image.style.maxWidth='100%';detail.append(image);}
}
render();instances.set(node,{dispose:()=>abort.abort()});
}
window.PlotDirectorContextLifecycles={...(window.PlotDirectorContextLifecycles||{}),assets:{mount,dispose(node){instances.get(node)?.dispose();instances.delete(node);}}};
})();

View File

@ -16,22 +16,24 @@
function icon(data,location){const t=data.types.find(t=>t.assignable!==false&&String(t.value)===String(location?.locationTypeID??''));const n=el('span',null,`spatial-type text-${t?.tone||'secondary'}`);if(t?.path){const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('aria-hidden','true');const p=document.createElementNS(svg.namespaceURI,'path');p.setAttribute('d',t.path);p.setAttribute('fill',t.filled?'currentColor':'none');svg.append(p);n.append(svg);}n.title=t?.label||'Unclassified';return n;}
// One splitter implementation for all spatial tools. Layout preferences belong to a pane,
// independently of renderer preferences and of the currently inspected scene.
function spatialLayout(node,key,signal){
function spatialLayout(node,key,signal,stackNarrow=false){
const layout=node.querySelector('[data-spatial-layout]'),handle=node.querySelector('[data-spatial-splitter]'),menu=node.querySelector('[data-spatial-orientation]');
let saved={};try{saved=JSON.parse(localStorage.getItem(key))||{};}catch{}
let orientation=saved.orientation==='vertical'?'vertical':'horizontal';
const effective=()=>stackNarrow&&node.clientWidth<=580?'vertical':orientation;
const clamp=n=>Math.max(10,Math.min(90,n));
const ratio=()=>Number.isFinite(saved[orientation])?clamp(saved[orientation]):30;
const ratio=()=>Number.isFinite(saved[effective()])?clamp(saved[effective()]):30;
const persist=()=>{try{localStorage.setItem(key,JSON.stringify({...saved,orientation}));}catch{}};
function apply(){layout.dataset.orientation=orientation;layout.style.setProperty('--spatial-split',`${ratio()}%`);menu.value=orientation;handle.setAttribute('aria-orientation',orientation==='horizontal'?'vertical':'horizontal');handle.setAttribute('aria-valuenow',String(Math.round(ratio())));handle.setAttribute('aria-valuetext',`${Math.round(ratio())}% information, ${Math.round(100-ratio())}% detail`);}
function apply(){layout.dataset.orientation=effective();layout.style.setProperty('--spatial-split',`${ratio()}%`);menu.value=orientation;handle.setAttribute('aria-orientation',effective()==='horizontal'?'vertical':'horizontal');handle.setAttribute('aria-valuenow',String(Math.round(ratio())));handle.setAttribute('aria-valuetext',`${Math.round(ratio())}% information, ${Math.round(100-ratio())}% detail`);}
handle.className='spatial-splitter';handle.tabIndex=0;handle.setAttribute('role','separator');handle.setAttribute('aria-label','Resize information and detail panels');handle.setAttribute('aria-valuemin','10');handle.setAttribute('aria-valuemax','90');
menu.addEventListener('change',()=>{orientation=menu.value;apply();persist();},{signal});
handle.addEventListener('keydown',e=>{const back=orientation==='horizontal'?'ArrowLeft':'ArrowUp',forward=orientation==='horizontal'?'ArrowRight':'ArrowDown';if(![back,forward,'Home','End'].includes(e.key))return;e.preventDefault();saved[orientation]=e.key==='Home'?10:e.key==='End'?90:clamp(ratio()+(e.key===back?-1:1)*(e.shiftKey?10:2));apply();persist();},{signal});
handle.addEventListener('keydown',e=>{const back=effective()==='horizontal'?'ArrowLeft':'ArrowUp',forward=effective()==='horizontal'?'ArrowRight':'ArrowDown';if(![back,forward,'Home','End'].includes(e.key))return;e.preventDefault();saved[effective()]=e.key==='Home'?10:e.key==='End'?90:clamp(ratio()+(e.key===back?-1:1)*(e.shiftKey?10:2));apply();persist();},{signal});
let pointer=null;
handle.addEventListener('pointerdown',e=>{if(e.button!==0)return;e.preventDefault();pointer=e.pointerId;handle.setPointerCapture(pointer);handle.focus({preventScroll:true});layout.classList.add('spatial-resizing');},{signal});
handle.addEventListener('pointermove',e=>{if(e.pointerId!==pointer)return;const box=layout.getBoundingClientRect(),size=orientation==='horizontal'?box.width:box.height;if(size<=0)return;saved[orientation]=clamp(100*(orientation==='horizontal'?e.clientX-box.left:e.clientY-box.top)/size);apply();},{signal});
handle.addEventListener('pointermove',e=>{if(e.pointerId!==pointer)return;const box=layout.getBoundingClientRect(),size=effective()==='horizontal'?box.width:box.height;if(size<=0)return;saved[effective()]=clamp(100*(effective()==='horizontal'?e.clientX-box.left:e.clientY-box.top)/size);apply();},{signal});
const end=e=>{if(e.pointerId!==pointer)return;pointer=null;layout.classList.remove('spatial-resizing');persist();};
for(const event of ['pointerup','pointercancel','lostpointercapture'])handle.addEventListener(event,end,{signal});
if(stackNarrow){const observer=new ResizeObserver(apply);observer.observe(node);signal.addEventListener('abort',()=>observer.disconnect(),{once:true});}
apply();
}
function mount(node,context){if(instances.has(node))return;const root=node.closest('[data-context-workspace]'),bus=session(root),kind=node.dataset.spatialContext,abort=new AbortController();let position=context.position,data,selection,loadedInspection,epoch=0,disposed=false,busy=false,resource=null,renderer=null,floorSnapshot=null,floorRoom=null,visibility=false,audibility=false,operation=null,undo=null;
@ -124,5 +126,5 @@
instances.set(node,{position(next){if(busy)return false;if(kind!=='locations'&&position.sceneId!==next.sceneId){resource=null;floorRoom=null;floorSnapshot=null;}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);}});
window.PlotDirectorSpatialContext=Object.freeze({layout:spatialLayout,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

@ -124,9 +124,9 @@
return fields.slice(0,count).some(field=>before[field]!==after[field]);
};
const affectedPanels = {
overview:['overview'], maps:['maps'], floorplans:['floorplans'], locations:['overview','locations','maps','floorplans'],
overview:['overview'], maps:['maps'], floorplans:['floorplans'], locations:['overview','locations','maps','floorplans','assets'],
spatial:['locations','maps','floorplans'], names:['names'],
characters:['overview','characters','relationships','names','locations','maps','floorplans'],
characters:['overview','characters','relationships','names','locations','maps','floorplans','assets'],
relationships:['overview','characters','relationships'],
warnings:['warnings'], dates:['overview','calendar','warnings'], intent:['overview','intent'],
plotlines:['overview','intent','plotlines','threads'], threads:['overview','intent','threads'],
@ -134,10 +134,10 @@
};
function inScope(hint) {
return !(hint.projectId&&scope.projectId&&Number(hint.projectId)!==scope.projectId) &&
!(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId&&!['dates','structure'].includes(hint.kind));
!(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId&&!['dates','structure','assets','locations','characters'].includes(hint.kind));
}
function affects(tab,hint) {
if(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId&&!['calendar','warnings'].includes(tab.id))return false;
if(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId&&!['calendar','warnings','assets'].includes(tab.id))return false;
return tab.contentRefresh!=='none' && (!affectedPanels[hint.kind] || affectedPanels[hint.kind].includes(tab.id));
}
function invalidate(hint={}) {