Add Context Threads scene links and pickup history
This commit is contained in:
parent
3ae4fad2b4
commit
a83aaf6723
86
Docs/Context/Threads-120.md
Normal file
86
Docs/Context/Threads-120.md
Normal file
@ -0,0 +1,86 @@
|
||||
# Context Threads — task 120
|
||||
|
||||
Implementation branch: `feature/context-threads-120`.
|
||||
|
||||
The Threads tab uses canonical Plot Lines, Threads, scene order, events and actual
|
||||
milestones from `IPlotLineWorkspaceRepository`. Direct scene associations live in
|
||||
`dbo.SceneThreads`; they do not create events or additional story entities. The
|
||||
picker captures and displays the target scene, adds multiple threads atomically,
|
||||
and uses the existing Context lifecycle guard and shared save notifications.
|
||||
History includes every earlier associated scene in the selected book, deduplicated
|
||||
in narrative order. Planned resolution alone is not a recorded pickup.
|
||||
|
||||
Knowledge remains in Characters. `ContextCharacterPanels` uses the selected
|
||||
scene's `AtPoint.Characters` knowledge; `_ContextCharacterDetail` shows up to four
|
||||
facts, distinguishes viewpoint knowledge from author reference, and links source
|
||||
scenes. Refining the quantity/display is deferred as permitted by the brief.
|
||||
|
||||
## Required Development schema release
|
||||
|
||||
Migration `PlotLine/Sql/340_SceneThreads.sql` is forward-only and has **not** been
|
||||
applied or database-qualified. Do not deploy these binaries before the migration.
|
||||
No Production change is authorised.
|
||||
|
||||
The code-only adapter in `Tools/Deployment/development_release.py` rejects changed
|
||||
SQL against the approved baseline (the `changed_sql` gate). Follow
|
||||
`Docs/Codex/Database.md`, `Docs/Codex/Deployment.md`, and the shared manifest/history
|
||||
contract for a separately reviewed and qualified Development schema release.
|
||||
Do not remove that gate, apply SQL manually, or edit the baseline to skip review.
|
||||
|
||||
The operator's qualification must:
|
||||
|
||||
1. Verify `PlotDirector_Development`, its current full migration ledger and schema;
|
||||
verify Atlas capacity, take and verify a unique backup, and qualify against an
|
||||
isolated restored copy. Do not restore/reset the live Development database.
|
||||
2. Include the complete current ledger and exactly the new 340 migration in the
|
||||
qualified manifest, using measured before/after fingerprints and real evidence.
|
||||
Prerequisites include `Scenes`, `PlotThreads`, `PlotLines`, `ProjectUserAccess`,
|
||||
`SpatialContext_Scope`, and `ProjectRestore_ApplyFromJson`. The migration fails
|
||||
closed if the current restore procedure differs from its expected markers.
|
||||
3. Verify the composite key, reverse index, cascade cleanup and the three new procedures
|
||||
(`SceneThread_ListByBook`, `SceneThread_Add`, `SceneThread_Backup`), plus the
|
||||
existing scoped procedure dependency. Verify runtime procedure permissions.
|
||||
4. Test atomic multi-select insertion, duplicate/repeated saves, two concurrent
|
||||
inserts, owner/collaborator writes, reader denial, absent/inactive access,
|
||||
cross-project/cross-book/archived threads and scenes, and malformed/oversized
|
||||
selections. Invalid batches must insert nothing. Verify no ThreadEvents are
|
||||
created or changed by a direct association.
|
||||
5. Test export/restore and portable import of the new associations, including ID
|
||||
remapping, omission protection for older backups, cross-book/dangling/duplicate
|
||||
rejection, and permanent scene/thread/book/project cleanup. Existing restore
|
||||
constraints must finish enabled/trusted. The new table contains only the two
|
||||
canonical foreign keys; archiving preserves associations.
|
||||
6. Activate the exact committed application SHA through the existing Development
|
||||
deployment worker, with idle-work checks, manifest admission and authoritative
|
||||
receipt. Verify running full SHA, Development and `PlotDirector_Development`.
|
||||
Reconcile any uncertain result before attempting another release. Updating the
|
||||
code-only baseline is an operator action after successful qualification/release.
|
||||
|
||||
The four procedure names introduced/used by this feature are
|
||||
`SceneThread_ListByBook`, `SceneThread_Add`, `SceneThread_Backup`, and
|
||||
`SpatialContext_Scope` (the last is existing, not newly created).
|
||||
|
||||
## Live acceptance after the schema release
|
||||
|
||||
Use `Docs/Codex/BrowserAcceptance.md` and the permanent locked Development writer
|
||||
helper. Create a registered disposable project with a book containing three
|
||||
ordered scenes, two Plot Lines and at least three Threads through ordinary UI.
|
||||
|
||||
- In scene one, add two Threads from different expanded Plot Lines. Verify the
|
||||
target scene in the dialogue, search retaining the parent Plot Line, selection
|
||||
retention across search, and already-linked disabled state on reopening.
|
||||
- In scene two, add the same Thread and another Thread. Reload and freshly sign in;
|
||||
verify both links persist and that scene one's pickup appears exactly once.
|
||||
- In scene three, link the same Thread, then verify **both** previous scenes appear
|
||||
in narrative order. Return to scene one and verify later scenes are absent.
|
||||
- Repeat in light/dark themes, single/split panes and a second Context window.
|
||||
Verify saved-data invalidation updates the other window, Hold/Follow and the
|
||||
selected scene remain correct, keyboard Cancel/Escape restores focus, and no
|
||||
action moves the Word caret. Native Word verification requires a real connected
|
||||
session; record a limitation rather than claiming a synthetic test proves it.
|
||||
- Verify Characters still shows established knowledge and source scenes. Clean up
|
||||
the disposable project through the documented scoped lifecycle and preserve any
|
||||
pending cleanup journal on failure.
|
||||
|
||||
Record the exact SHA, receipt, URLs, real checks, cleanup and factual effort in CYJ.
|
||||
The isolated browser test uses mocked persistence and is not live acceptance.
|
||||
106
PlotLine.Tests/Browser/context-threads.cjs
Normal file
106
PlotLine.Tests/Browser/context-threads.cjs
Normal file
@ -0,0 +1,106 @@
|
||||
// Isolated browser interaction checks. Mock persistence is not live Development acceptance.
|
||||
const { chromium } = require('playwright');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const script = fs.readFileSync(path.resolve(__dirname, '../../PlotLine/wwwroot/js/context-threads.js'), 'utf8');
|
||||
(async () => {
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
try {
|
||||
const context = await browser.newContext();
|
||||
const links = new Map([[11, new Set([1])], [22, new Set()]]);
|
||||
const errors = [], writes = [], guards = [];
|
||||
let reject = false, readonly = false;
|
||||
const threads = [
|
||||
{ plotThreadID: 1, plotLineID: 10, plotLineName: 'Journey', title: 'A <saved> question' },
|
||||
{ plotThreadID: 2, plotLineID: 10, plotLineName: 'Journey', title: 'Promise' },
|
||||
{ plotThreadID: 3, plotLineID: 20, plotLineName: 'Discovery', title: 'Hidden answer' }
|
||||
];
|
||||
function state(sceneID) {
|
||||
return { scope: { label: `Chapter 1 · Scene ${sceneID}: Saved scene`, canEdit: !readonly },
|
||||
threads: threads.map(t => ({ ...t, linked: links.get(sceneID).has(t.plotThreadID),
|
||||
previousScenes: sceneID === 22 && links.get(11).has(t.plotThreadID)
|
||||
? [{ chapterNumber: 1, chapterTitle: 'Opening', sceneNumber: 1, sceneTitle: 'Earlier scene' }] : [] })) };
|
||||
}
|
||||
await context.route('http://context.test/**', async route => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.pathname === '/ContextThreads/State') return route.fulfill({ json: state(Number(url.searchParams.get('sceneId'))) });
|
||||
if (url.pathname === '/ContextThreads/Add') {
|
||||
const body = route.request().postDataJSON(); writes.push(body);
|
||||
assert.equal(route.request().headers()['requestverificationtoken'], 'fixture-token');
|
||||
if (reject) return route.fulfill({ status: 409, json: { message: 'Thread was archived. Review selection.' } });
|
||||
for (const id of body.threadIDs) links.get(body.sceneID).add(id);
|
||||
return route.fulfill({ json: { saved: true } });
|
||||
}
|
||||
if (url.pathname !== '/') throw Error(`Unexpected navigation: ${url.pathname}`);
|
||||
return route.fulfill({ contentType: 'text/html', body: '<!doctype html><html><body><main></main></body></html>' });
|
||||
});
|
||||
const page = await context.newPage(); page.on('pageerror', e => errors.push(e.message));
|
||||
await page.goto('http://context.test/');
|
||||
await page.addScriptTag({ content: script });
|
||||
async function mount(sceneID, pane = 0) {
|
||||
await page.evaluate(({ sceneID, pane }) => {
|
||||
let host = document.querySelector(`[data-test-pane="${pane}"]`);
|
||||
if (!host) { host = document.createElement('section'); host.dataset.testPane = pane; document.querySelector('main').append(host); }
|
||||
const old = host.firstElementChild;
|
||||
if (old) window.PlotDirectorContextLifecycles.threads.dispose(old);
|
||||
host.innerHTML = `<div data-project-id="7" data-book-id="12" data-scene-id="${sceneID}"><input name="__RequestVerificationToken" value="fixture-token" type="hidden"><button data-thread-add disabled>Add thread</button><p data-thread-error></p><div data-thread-rows></div></div>`;
|
||||
window.guardEvents ??= [];
|
||||
host.firstElementChild.addEventListener('context-panel-state', e => window.guardEvents.push(e.detail.dirty));
|
||||
window.PlotDirectorContextLifecycles.threads.mount(host.firstElementChild);
|
||||
}, { sceneID, pane });
|
||||
await page.locator(`[data-test-pane="${pane}"] [data-thread-add]`).waitFor({ state: 'visible' });
|
||||
if (!readonly) await page.waitForFunction(pane => !document.querySelector(`[data-test-pane="${pane}"] [data-thread-add]`).disabled, pane);
|
||||
}
|
||||
await mount(11);
|
||||
assert.equal(await page.getByText('Journey / A <saved> question', { exact: true }).count(), 1);
|
||||
await page.getByRole('button', { name: 'Add thread', exact: true }).click();
|
||||
await page.getByText('Chapter 1 · Scene 11: Saved scene', { exact: true }).waitFor();
|
||||
const dialog = page.getByRole('dialog');
|
||||
await dialog.locator('summary').filter({ hasText: 'Journey' }).click();
|
||||
assert.equal(await dialog.getByLabel(/A <saved> question.*Already linked/).isDisabled(), true);
|
||||
await dialog.getByLabel('Promise', { exact: true }).check();
|
||||
await dialog.getByRole('searchbox').fill('answer');
|
||||
await dialog.locator('summary').filter({ hasText: 'Discovery' }).waitFor({ state: 'visible' });
|
||||
await dialog.getByLabel('Hidden answer', { exact: true }).check();
|
||||
await dialog.getByRole('button', { name: 'Add to scene', exact: true }).click();
|
||||
await dialog.waitFor({ state: 'detached' });
|
||||
assert.deepEqual(writes[0], { bookID: 12, sceneID: 11, threadIDs: [2, 3] });
|
||||
assert.equal(await page.locator('[data-thread-rows] article').count(), 3);
|
||||
assert.equal(await page.locator('[data-thread-add]').evaluate(n => document.activeElement === n), true);
|
||||
guards.push(...await page.evaluate(() => window.guardEvents));
|
||||
assert.deepEqual(guards, [true, false]);
|
||||
await mount(22);
|
||||
await page.getByRole('button', { name: 'Add thread', exact: true }).click();
|
||||
await dialog.getByRole('searchbox').fill('question');
|
||||
await dialog.getByLabel('A <saved> question', { exact: true }).check();
|
||||
reject = true;
|
||||
await dialog.getByRole('button', { name: 'Add to scene', exact: true }).click();
|
||||
await dialog.getByText('Thread was archived. Review selection.', { exact: true }).waitFor();
|
||||
assert.equal(links.get(22).size, 0);
|
||||
reject = false;
|
||||
await dialog.getByRole('button', { name: 'Add to scene', exact: true }).click();
|
||||
await dialog.waitFor({ state: 'detached' });
|
||||
await page.getByText('Ch 1: Opening · Scene 1: Earlier scene', { exact: true }).waitFor();
|
||||
await mount(22); // Reload saved state through a fresh lifecycle.
|
||||
await page.getByText('Ch 1: Opening · Scene 1: Earlier scene', { exact: true }).waitFor();
|
||||
// An external saved-data hint updates the existing node without stealing focus.
|
||||
links.get(22).add(2);
|
||||
await page.locator('[data-thread-add]').focus();
|
||||
assert.equal(await page.evaluate(() => window.PlotDirectorContextLifecycles.threads.onInvalidation(document.querySelector('[data-test-pane="0"]').firstElementChild)), true);
|
||||
await page.waitForFunction(() => document.querySelectorAll('[data-test-pane="0"] [data-thread-rows] article').length === 2);
|
||||
assert.equal(await page.locator('[data-thread-add]').evaluate(n => document.activeElement === n), true);
|
||||
await mount(11, 1);
|
||||
assert.equal(await page.locator('[data-test-pane="0"] [data-thread-rows] article').count(), 2);
|
||||
assert.equal(await page.locator('[data-test-pane="1"] [data-thread-rows] article').count(), 3);
|
||||
await page.locator('[data-test-pane="1"] [data-thread-add]').click();
|
||||
await page.keyboard.press('Escape');
|
||||
await dialog.waitFor({ state: 'detached' });
|
||||
readonly = true;
|
||||
await mount(11, 1);
|
||||
await page.waitForFunction(() => document.querySelector('[data-test-pane="1"] [data-thread-rows] article'));
|
||||
assert.equal(await page.locator('[data-test-pane="1"] [data-thread-add]').isDisabled(), true);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS Context Threads nested search, parent context, linked state, multi-select, explicit target, guards, failure recovery, history, reload, split panes and read-only state (isolated fixtures)');
|
||||
} finally { await browser.close(); }
|
||||
})().catch(e => { console.error(e); process.exitCode = 1; });
|
||||
68
PlotLine.Tests/ContextThreadsTests.cs
Normal file
68
PlotLine.Tests/ContextThreadsTests.cs
Normal file
@ -0,0 +1,68 @@
|
||||
using System.Reflection;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlotLine.Controllers;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services.Context;
|
||||
using PlotLine.Services;
|
||||
|
||||
internal static class ContextThreadsTests
|
||||
{
|
||||
public static void Run()
|
||||
{
|
||||
var scope = new SpatialScope { ProjectID = 7, BookID = 12, SceneID = 90 };
|
||||
var data = new PlotLineWorkspaceData
|
||||
{
|
||||
PlotLines = [new() { PlotLineID = 1, ProjectID = 7, BookID = 12, PlotLineName = "Main" },
|
||||
new() { PlotLineID = 2, ProjectID = 7, PlotLineName = "Shared" },
|
||||
new() { PlotLineID = 3, ProjectID = 7, BookID = 13 }, new() { PlotLineID = 4, ProjectID = 8 }],
|
||||
Threads = [new() { PlotThreadID = 10, PlotLineID = 1, ThreadTitle = "Question", IntroducedSceneID = 15 },
|
||||
new() { PlotThreadID = 11, PlotLineID = 2, ThreadTitle = "Promise", ActualResolutionSceneID = 90 },
|
||||
new() { PlotThreadID = 12, PlotLineID = 3 }, new() { PlotThreadID = 13, PlotLineID = 4 },
|
||||
new() { PlotThreadID = 14, PlotLineID = 1, PlannedResolutionSceneID = 90 }],
|
||||
AttributionScenes = [new() { SceneID = 15, BookID = 12, NarrativeOrder = 1 },
|
||||
new() { SceneID = 7, BookID = 12, NarrativeOrder = 2 }, new() { SceneID = 90, BookID = 12, NarrativeOrder = 3 },
|
||||
new() { SceneID = 2, BookID = 12, NarrativeOrder = 4 }, new() { SceneID = 44, BookID = 13, NarrativeOrder = 0 }],
|
||||
Contributions = [new() { PlotThreadID = 10, SceneID = 7, BookID = 12 }, new() { PlotThreadID = 10, SceneID = 7, BookID = 12 },
|
||||
new() { PlotThreadID = 10, SceneID = 44, BookID = 13 }]
|
||||
};
|
||||
SceneThread[] links = [new() { SceneID = 90, PlotThreadID = 10 }, new() { SceneID = 7, PlotThreadID = 10 },
|
||||
new() { SceneID = 2, PlotThreadID = 10 }, new() { SceneID = 44, PlotThreadID = 10 }];
|
||||
var panel = ContextThreads.Build(scope, data, links);
|
||||
Check(panel.Threads.Count == 3, "Exclude other books and projects; include project-wide lines.");
|
||||
var question = panel.Threads.Single(t => t.PlotThreadID == 10);
|
||||
Check(question.Linked, "A direct scene link needs no event.");
|
||||
Check(question.PreviousScenes.Select(s => s.SceneID).SequenceEqual([15, 7]), "Keep every previous pickup in narrative order; deduplicate events, milestones and direct links; exclude future/other-book scenes.");
|
||||
Check(panel.Threads.Single(t => t.PlotThreadID == 11).Linked, "An actual resolution is a recorded association.");
|
||||
Check(!panel.Threads.Single(t => t.PlotThreadID == 14).Linked, "A planned resolution alone is not an actual pickup.");
|
||||
var earlier = ContextThreads.Build(new() { ProjectID = 7, BookID = 12, SceneID = 7 }, data, links);
|
||||
Check(earlier.Threads.Single(t => t.PlotThreadID == 10).PreviousScenes.Single().SceneID == 15, "History follows the selected scene, not IDs or latest saved scene.");
|
||||
var backup = new ProjectBackupExport
|
||||
{
|
||||
Project = new() { ProjectID = 7 },
|
||||
Data = new()
|
||||
{
|
||||
Books = [new() { BookID = 12, ProjectID = 7 }, new() { BookID = 13, ProjectID = 7 }],
|
||||
Chapters = [new() { ChapterID = 3, BookID = 12 }],
|
||||
Scenes = [new() { SceneID = 90, ChapterID = 3 }],
|
||||
PlotLines = [new() { PlotLineID = 1, ProjectID = 7, BookID = 12 }],
|
||||
PlotThreads = [new() { PlotThreadID = 10, PlotLineID = 1 }],
|
||||
SceneThreads = [new() { SceneID = 90, PlotThreadID = 10 }]
|
||||
}
|
||||
};
|
||||
Check(ValidateBackup(backup) == null, "Scene links participate in the canonical backup graph.");
|
||||
backup.Data.SceneThreads = [new() { SceneID = 90, PlotThreadID = 10 }, new() { SceneID = 90, PlotThreadID = 10 }];
|
||||
Check(ValidateBackup(backup)?.Contains("duplicate scene/thread") == true, "Reject duplicate backup associations before restore.");
|
||||
backup.Data.SceneThreads = [new() { SceneID = 90, PlotThreadID = 10 }];
|
||||
backup.Data.PlotLines[0].BookID = 13;
|
||||
Check(ValidateBackup(backup)?.Contains("another book") == true, "Reject a scene/thread association crossing books.");
|
||||
backup.Data.SceneThreads = [new() { SceneID = 90, PlotThreadID = 999 }];
|
||||
Check(ValidateBackup(backup)?.Contains("missing or foreign") == true, "Reject foreign threads before restore.");
|
||||
Check(typeof(ContextThreadsController).IsDefined(typeof(AuthorizeAttribute), true), "Thread endpoints require authentication.");
|
||||
Check(typeof(ContextThreadsController).GetMethod("Add")!.IsDefined(typeof(ValidateAntiForgeryTokenAttribute), true), "Thread saves require antiforgery.");
|
||||
}
|
||||
private static string? ValidateBackup(ProjectBackupExport backup) =>
|
||||
(string?)typeof(ImportService).Assembly.GetType("PlotLine.Services.ProjectBackupGraphValidation")!
|
||||
.GetMethod("Validate", BindingFlags.Public | BindingFlags.Static)!.Invoke(null, [backup, false]);
|
||||
private static void Check(bool condition, string message) { if (!condition) throw new Exception(message); }
|
||||
}
|
||||
@ -217,6 +217,7 @@ if(args.Contains("--discretionary-ai-database")){await DiscretionaryAiDatabaseTe
|
||||
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-threads")){ContextThreadsTests.Run();Console.WriteLine("PASS Context Threads narrative history, optional events and scope");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;}
|
||||
@ -239,6 +240,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 Threads narrative history and scope",ContextThreadsTests.Run),
|
||||
("Context character narrative projection and focused editing",()=>ContextCharacterTests.Run().GetAwaiter().GetResult()),
|
||||
("Context Intent deterministic text preparation",ContextIntentTextTests.Run),
|
||||
("Context My Windows routing and lifecycle",ContextWindowsTests.Run),
|
||||
|
||||
31
PlotLine/Controllers/ContextThreadsController.cs
Normal file
31
PlotLine/Controllers/ContextThreadsController.cs
Normal file
@ -0,0 +1,31 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using PlotLine.Services.Context;
|
||||
|
||||
namespace PlotLine.Controllers;
|
||||
|
||||
[Authorize, ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public sealed class ContextThreadsController(ContextThreads threads) : Controller
|
||||
{
|
||||
private async Task<IActionResult> Guard(Func<Task<IActionResult>> action)
|
||||
{
|
||||
try { return await action(); }
|
||||
catch (UnauthorizedAccessException) { return Forbid(); }
|
||||
catch (SqlException e) when (e.Number is 51010 or 51011 or 51012)
|
||||
{ return StatusCode(e.Number == 51010 ? 403 : 409, new { message = e.Message }); }
|
||||
catch (ArgumentException e) { return BadRequest(new { message = e.Message }); }
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public Task<IActionResult> State(int bookId, int sceneId) => Guard(async () =>
|
||||
ModelState.IsValid && bookId > 0 && sceneId > 0 ? Json(await threads.Read(bookId, sceneId)) : BadRequest());
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public Task<IActionResult> Add([FromBody] ContextThreadSelection input) => Guard(async () =>
|
||||
{
|
||||
if (!ModelState.IsValid || input == null || input.BookID <= 0 || input.SceneID <= 0) return BadRequest();
|
||||
await threads.Add(input);
|
||||
return Json(new { saved = true });
|
||||
});
|
||||
}
|
||||
@ -119,6 +119,23 @@ public sealed class WritingController(
|
||||
ViewData["ContextTabPartial"]="_ContextNames";return PartialView("_ContextTab",model);
|
||||
}
|
||||
|
||||
[HttpGet("Context/Threads")]
|
||||
public async Task<IActionResult> ContextThreadsTab(int? projectId, int? bookId, int? chapterId, int? sceneId,
|
||||
Guid? instanceId, Guid? sessionId, [FromServices] PlotLine.Services.Context.ContextSpatial spatial)
|
||||
{
|
||||
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 scope = await spatial.Scope(bookId.Value, sceneId.Value);
|
||||
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("_ContextThreads", scope);
|
||||
}
|
||||
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);
|
||||
|
||||
@ -158,6 +158,10 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
|
||||
|
||||
}
|
||||
|
||||
data.SceneThreads = (await connection.QueryAsync<SceneThread>(
|
||||
"dbo.SceneThread_Backup", new { ProjectID = projectId },
|
||||
commandType: CommandType.StoredProcedure, transaction: transaction)).ToList();
|
||||
|
||||
var bookMetadata = (await connection.QueryAsync<Book>(
|
||||
"dbo.ProjectBackup_BookMetadata_List",
|
||||
new { ProjectID = projectId },
|
||||
|
||||
@ -95,6 +95,7 @@ public sealed class ProjectBackupData
|
||||
public IReadOnlyList<PlotLineItem> PlotLines { get; init; } = [];
|
||||
public IReadOnlyList<PlotThread> PlotThreads { get; init; } = [];
|
||||
public IReadOnlyList<ThreadEvent> ThreadEvents { get; init; } = [];
|
||||
public IReadOnlyList<SceneThread> SceneThreads { get; set; } = [];
|
||||
public IReadOnlyList<StoryAsset> StoryAssets { get; init; } = [];
|
||||
public IReadOnlyList<AssetState> AssetStates { get; init; } = [];
|
||||
public IReadOnlyList<AssetEvent> AssetEvents { get; init; } = [];
|
||||
|
||||
8
PlotLine/Models/SceneThread.cs
Normal file
8
PlotLine/Models/SceneThread.cs
Normal file
@ -0,0 +1,8 @@
|
||||
namespace PlotLine.Models;
|
||||
|
||||
// A canonical association, independent of optional thread events.
|
||||
public sealed class SceneThread
|
||||
{
|
||||
public int SceneID { get; set; }
|
||||
public int PlotThreadID { get; set; }
|
||||
}
|
||||
@ -309,6 +309,7 @@ public class Program
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextCharacterPanels>();
|
||||
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.ContextRelationshipEditing>();
|
||||
builder.Services.AddScoped<PlotLine.Data.IContextRelationshipReader,PlotLine.Data.ContextRelationshipReader>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextRelationshipLenses>();
|
||||
|
||||
61
PlotLine/Services/Context/ContextThreads.cs
Normal file
61
PlotLine/Services/Context/ContextThreads.cs
Normal file
@ -0,0 +1,61 @@
|
||||
using System.Data;
|
||||
using System.Text.Json;
|
||||
using Dapper;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
|
||||
namespace PlotLine.Services.Context;
|
||||
|
||||
public sealed record ContextThreadRow(int PlotThreadID, int PlotLineID, string Title, string PlotLineName,
|
||||
bool Linked, IReadOnlyList<PlotLineWorkspaceAttributionRow> PreviousScenes);
|
||||
public sealed record ContextThreadsPanel(SpatialScope Scope, IReadOnlyList<ContextThreadRow> Threads);
|
||||
public sealed record ContextThreadSelection(int BookID, int SceneID, int[] ThreadIDs);
|
||||
|
||||
public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRepository workspace,
|
||||
ISqlConnectionFactory connections, ICurrentUserService user, ContextWorkspaceNotifications notifications)
|
||||
{
|
||||
public async Task<ContextThreadsPanel> Read(int book, int scene)
|
||||
{
|
||||
var scope = await spatial.Scope(book, scene);
|
||||
var data = await workspace.GetAsync(scope.ProjectID, book, null);
|
||||
using var db = connections.CreateConnection();
|
||||
var links = await db.QueryAsync<SceneThread>("dbo.SceneThread_ListByBook",
|
||||
new { BookID = book, UserID = user.UserId!.Value }, commandType: CommandType.StoredProcedure);
|
||||
return Build(scope, data, links);
|
||||
}
|
||||
|
||||
public static ContextThreadsPanel Build(SpatialScope scope, PlotLineWorkspaceData data, IEnumerable<SceneThread> links)
|
||||
{
|
||||
var scenes = data.AttributionScenes.Where(s => s.BookID == scope.BookID).ToDictionary(s => s.SceneID);
|
||||
if (!scenes.TryGetValue(scope.SceneID, out var current)) throw new ArgumentException("Scene order is unavailable.");
|
||||
var lines = data.PlotLines.Where(l => l.ProjectID == scope.ProjectID && (l.BookID == null || l.BookID == scope.BookID)).ToDictionary(l => l.PlotLineID);
|
||||
var associations = links.Select(l => (l.PlotThreadID, l.SceneID))
|
||||
.Concat(data.Contributions.Where(c => c.BookID == scope.BookID).Select(c => (c.PlotThreadID, c.SceneID)))
|
||||
.ToHashSet();
|
||||
// Established milestones are authoritative associations too. A planned resolution
|
||||
// alone is a future intention, not a scene where the thread has been picked up.
|
||||
foreach (var thread in data.Threads)
|
||||
{
|
||||
if (thread.IntroducedSceneID is int introduced) associations.Add((thread.PlotThreadID, introduced));
|
||||
if (thread.ActualResolutionSceneID is int resolved) associations.Add((thread.PlotThreadID, resolved));
|
||||
}
|
||||
var rows = data.Threads.Where(t => lines.ContainsKey(t.PlotLineID)).Select(t => new ContextThreadRow(
|
||||
t.PlotThreadID, t.PlotLineID, t.ThreadTitle, lines[t.PlotLineID].PlotLineName,
|
||||
associations.Contains((t.PlotThreadID, scope.SceneID)),
|
||||
scenes.Values.Where(s => s.NarrativeOrder < current.NarrativeOrder && associations.Contains((t.PlotThreadID, s.SceneID)))
|
||||
.OrderBy(s => s.NarrativeOrder).ToArray())).OrderBy(t => t.PlotLineName).ThenBy(t => t.Title).ToArray();
|
||||
return new(scope, rows);
|
||||
}
|
||||
|
||||
public async Task Add(ContextThreadSelection input)
|
||||
{
|
||||
if (input.ThreadIDs is not { Length: > 0 and <= 200 } || input.ThreadIDs.Any(id => id <= 0))
|
||||
throw new ArgumentException("Choose between 1 and 200 threads.");
|
||||
using var db = connections.CreateConnection();
|
||||
var project = await db.QuerySingleAsync<int>("dbo.SceneThread_Add",
|
||||
new { input.BookID, input.SceneID, UserID = user.UserId ?? throw new UnauthorizedAccessException(), ThreadIDs = JsonSerializer.Serialize(input.ThreadIDs.Distinct()) },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
// Any earlier scene can affect history in all later scenes of the same book.
|
||||
await notifications.Invalidate(user.UserId!.Value, projectId: project, bookId: input.BookID, kind: "threads");
|
||||
}
|
||||
}
|
||||
@ -1215,6 +1215,12 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
thread.ActualResolutionSceneID = ExistingOrNewNullable("Scenes", thread.ActualResolutionSceneID);
|
||||
}
|
||||
|
||||
foreach (var link in backup.Data.SceneThreads)
|
||||
{
|
||||
link.SceneID = ExistingOrNew("Scenes", link.SceneID);
|
||||
link.PlotThreadID = ExistingOrNew("PlotThreads", link.PlotThreadID);
|
||||
}
|
||||
|
||||
foreach (var threadEvent in backup.Data.ThreadEvents)
|
||||
{
|
||||
var narrativeSource=narrativeSources.GetValueOrDefault(threadEvent.ThreadEventID);
|
||||
|
||||
@ -109,6 +109,7 @@ internal static class ProjectBackupGraphValidation
|
||||
new("Scenes", "SceneID", new Link("ChapterID", "Chapters", "ChapterID"), new Link("FloorPlanID", "FloorPlans", "FloorPlanID"), new Link("InitialFloorPlanFloorID", "FloorPlanFloors", "FloorPlanFloorID"), new Link("ManuscriptDocumentID", "ManuscriptDocuments", "ManuscriptDocumentID"), new Link("POVCharacterID", "Characters", "CharacterID"), new Link("PrimaryLocationID", "Locations", "LocationID")),
|
||||
new("StoryAssets", "StoryAssetID", new Link("CurrentLocationID", "Locations", "LocationID"), new Link("CurrentStateID", "AssetStates", "AssetStateID"), new Link("ProjectID", "Project", "ProjectID")),
|
||||
new("StoryMaps", "MapID", new Link("ParentMapID", "StoryMaps", "MapID"), new Link("ProjectID", "Project", "ProjectID")),
|
||||
new("SceneThreads", null, new Link("PlotThreadID", "PlotThreads", "PlotThreadID"), new Link("SceneID", "Scenes", "SceneID")),
|
||||
new("ThreadEvents", "ThreadEventID", new Link("PlotLineID", "PlotLines", "PlotLineID"), new Link("PlotThreadID", "PlotThreads", "PlotThreadID"), new Link("SceneID", "Scenes", "SceneID"), new Link("TargetPlotLineID", "PlotLines", "PlotLineID")),
|
||||
new("TimelineViewPresets", "TimelineViewPresetID", new Link("BookID", "Books", "BookID"), new Link("ProjectID", "Project", "ProjectID")),
|
||||
new("UserFiles", "UserFileID", new Link("ProjectID", "Project", "ProjectID")),
|
||||
@ -140,6 +141,17 @@ internal static class ProjectBackupGraphValidation
|
||||
return $"Project backup {entity.Collection}.{link.Column} references a missing or foreign {link.TargetCollection} record.";
|
||||
}
|
||||
}
|
||||
if (backup.Data.SceneThreads.Select(x => (x.SceneID, x.PlotThreadID)).Distinct().Count() != backup.Data.SceneThreads.Count)
|
||||
return "Project backup contains duplicate scene/thread associations.";
|
||||
if (backup.Data.SceneThreads.Count > 0)
|
||||
{
|
||||
var chapters = backup.Data.Chapters.ToDictionary(c => c.ChapterID, c => c.BookID);
|
||||
var lines = backup.Data.PlotLines.ToDictionary(l => l.PlotLineID);
|
||||
var sceneBooks = backup.Data.Scenes.ToDictionary(s => s.SceneID, s => chapters[s.ChapterID]);
|
||||
var threadLines = backup.Data.PlotThreads.ToDictionary(t => t.PlotThreadID, t => lines[t.PlotLineID]);
|
||||
if (backup.Data.SceneThreads.Any(x => threadLines[x.PlotThreadID].BookID is int book && book != sceneBooks[x.SceneID]))
|
||||
return "Project backup contains a thread associated with another book's scene.";
|
||||
}
|
||||
if(backup.Data.StoryIntelligenceRuns.Count>0 && backup.Data.Scenes.Any(scene=>scene.ImportRunID.HasValue && !backup.Data.StoryIntelligenceRuns.Any(run=>run.StoryIntelligenceRunID==scene.ImportRunID)))
|
||||
return "Project backup scene analysis provenance references a missing or foreign run.";
|
||||
return ProjectBackupNarrative.Validate(backup) ?? ProjectBackupEntityReview.Validate(backup) ?? ProjectBackupStoryMemory.Validate(backup) ?? ProjectBackupTimelineState.Validate(backup);
|
||||
|
||||
@ -101,6 +101,7 @@ internal static partial class ProjectBackupStoredFieldContract
|
||||
["StoryMemoryLocations"]=("StoryMemoryLocationID,ImportSessionID,ProjectID,BookID,CanonicalIdentityKey,DisplayName,SemanticType,Subtype,InteriorExterior,ParentLocationID,FirstSeenSceneResultID,LastSeenSceneResultID,CreatedUtc,UpdatedUtc","Subtype,InteriorExterior,ParentLocationID,FirstSeenSceneResultID,LastSeenSceneResultID"),
|
||||
["StoryMemoryProcessedSceneResults"]=("StoryMemoryProcessedSceneResultID,ImportSessionID,SceneResultID,ProcessorVersion,SnapshotHash,ProcessedUtc","SnapshotHash"),
|
||||
["StoryMemoryRelationships"]=("StoryMemoryRelationshipID,ImportSessionID,SourceEntityType,SourceEntityID,TargetEntityType,TargetEntityID,RelationshipType,Confidence,IsExplicit,FirstSeenSceneResultID,LastUpdatedSceneResultID,Active,CreatedUtc,UpdatedUtc","FirstSeenSceneResultID,LastUpdatedSceneResultID"),
|
||||
["SceneThreads"]=("SceneID,PlotThreadID",""),
|
||||
["ThreadEvents"]=("ThreadEventID,PlotThreadID,SceneID,EventTypeID,EventTitle,EventDescription,CreatedDate,UpdatedDate,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,PlotEventTypeID,TargetPlotLineID,Source,SourceReferenceID,SourceKey,Confidence","EventDescription,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,TargetPlotLineID,SourceReferenceID,SourceKey,Confidence"),
|
||||
["TimelineMetricSettings"]=("ProjectID,MetricTypeID,SortOrder,CreatedDate",""),
|
||||
["TimelineSettings"]=("ProjectTimelineSettingsID,ProjectID,ShowSceneCards,ShowMetricShape,ShowPlotLines,ShowStoryAssets,ShowCharacterAppearances,ShowWarnings,CreatedDate,UpdatedDate",""),
|
||||
|
||||
90
PlotLine/Sql/340_SceneThreads.sql
Normal file
90
PlotLine/Sql/340_SceneThreads.sql
Normal file
@ -0,0 +1,90 @@
|
||||
SET ANSI_NULLS ON;
|
||||
GO
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
IF OBJECT_ID(N'dbo.SpatialContext_Scope',N'P') IS NULL
|
||||
OR OBJECT_ID(N'dbo.ProjectRestore_ApplyFromJson',N'P') IS NULL
|
||||
THROW 51012,'The scoped scene and project restore procedures must be qualified first.',1;
|
||||
GO
|
||||
-- Canonical many-to-many scene associations. Events remain optional and unchanged.
|
||||
-- Cascades remove only associations when their owning scene/thread is permanently
|
||||
-- deleted; archiving preserves them for restoration. No new story entities.
|
||||
IF OBJECT_ID(N'dbo.SceneThreads',N'U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.SceneThreads(
|
||||
SceneID int NOT NULL,
|
||||
PlotThreadID int NOT NULL,
|
||||
CONSTRAINT PK_SceneThreads PRIMARY KEY(SceneID,PlotThreadID),
|
||||
CONSTRAINT FK_SceneThreads_Scenes FOREIGN KEY(SceneID) REFERENCES dbo.Scenes(SceneID) ON DELETE CASCADE,
|
||||
CONSTRAINT FK_SceneThreads_PlotThreads FOREIGN KEY(PlotThreadID) REFERENCES dbo.PlotThreads(PlotThreadID) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IX_SceneThreads_Thread ON dbo.SceneThreads(PlotThreadID,SceneID);
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.SceneThread_ListByBook @BookID int,@UserID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.IsArchived=0 AND p.IsArchived=0) THROW 51010,'Book unavailable.',1;
|
||||
SELECT x.SceneID,x.PlotThreadID FROM dbo.SceneThreads x
|
||||
JOIN dbo.Scenes s ON s.SceneID=x.SceneID AND s.IsArchived=0
|
||||
JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID AND c.IsArchived=0
|
||||
JOIN dbo.Books b ON b.BookID=c.BookID
|
||||
JOIN dbo.PlotThreads t ON t.PlotThreadID=x.PlotThreadID AND t.IsArchived=0
|
||||
JOIN dbo.PlotLines l ON l.PlotLineID=t.PlotLineID AND l.IsArchived=0
|
||||
WHERE b.BookID=@BookID AND l.ProjectID=b.ProjectID AND (l.BookID IS NULL OR l.BookID=@BookID);
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.SceneThread_Add @BookID int,@SceneID int,@UserID int,@ThreadIDs nvarchar(max)
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
IF ISJSON(@ThreadIDs)<>1 OR LEFT(LTRIM(@ThreadIDs),1)<>N'[' THROW 51012,'Choose valid threads.',1;
|
||||
IF (SELECT COUNT(*) FROM OPENJSON(@ThreadIDs)) NOT BETWEEN 1 AND 200 OR EXISTS(SELECT 1 FROM OPENJSON(@ThreadIDs) WHERE type<>2 OR TRY_CONVERT(int,value) IS NULL OR TRY_CONVERT(int,value)<=0) THROW 51012,'Choose between 1 and 200 valid threads.',1;
|
||||
DECLARE @ids TABLE(ID int PRIMARY KEY);
|
||||
INSERT @ids SELECT DISTINCT CONVERT(int,value) FROM OPENJSON(@ThreadIDs);
|
||||
BEGIN TRY
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @project int,@locked int;
|
||||
SELECT @locked=SceneID FROM dbo.Scenes WITH(UPDLOCK,HOLDLOCK) WHERE SceneID=@SceneID;
|
||||
EXEC dbo.SpatialContext_Scope @UserID,@BookID,@SceneID,0;
|
||||
SELECT @project=b.ProjectID FROM dbo.Books b WITH(HOLDLOCK) WHERE b.BookID=@BookID;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WITH(HOLDLOCK) WHERE ProjectID=@project AND UserID=@UserID AND IsActive=1 AND AccessRole IN(N'Owner',N'Collaborator')) THROW 51010,'Editing unavailable.',1;
|
||||
IF (SELECT COUNT(*) FROM @ids i JOIN dbo.PlotThreads t WITH(UPDLOCK,HOLDLOCK) ON t.PlotThreadID=i.ID AND t.IsArchived=0 JOIN dbo.PlotLines l WITH(HOLDLOCK) ON l.PlotLineID=t.PlotLineID AND l.IsArchived=0 AND l.ProjectID=@project AND(l.BookID IS NULL OR l.BookID=@BookID))<>(SELECT COUNT(*) FROM @ids) THROW 51012,'A selected thread is unavailable in this book. Review the selection.',1;
|
||||
INSERT dbo.SceneThreads(SceneID,PlotThreadID)
|
||||
SELECT @SceneID,i.ID FROM @ids i WHERE NOT EXISTS(SELECT 1 FROM dbo.SceneThreads WITH(UPDLOCK,HOLDLOCK) WHERE SceneID=@SceneID AND PlotThreadID=i.ID);
|
||||
COMMIT;
|
||||
SELECT @project;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF XACT_STATE()<>0 ROLLBACK;
|
||||
THROW;
|
||||
END CATCH;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.SceneThread_Backup @ProjectID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
SELECT x.SceneID,x.PlotThreadID FROM dbo.SceneThreads x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.SceneID,x.PlotThreadID;
|
||||
END;
|
||||
GO
|
||||
-- Extend the current restore definition narrowly, retaining its existing recovery
|
||||
-- and omission safeguards. Refuse unexpected definitions during qualification.
|
||||
DECLARE @restore nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.ProjectRestore_ApplyFromJson'));
|
||||
IF @restore IS NULL THROW 51012,'The authoritative project restore procedure is required.',1;
|
||||
IF @restore NOT LIKE N'%SceneThreads%'
|
||||
BEGIN
|
||||
DECLARE @table nvarchar(max)=N'(N''ThreadEvents'')',
|
||||
@insert nvarchar(max)=N'EXEC dbo.ProjectRestore_InsertJsonTable N''ThreadEvents'', N''$.Data.ThreadEvents'', @JsonData, @ProjectID, 0;',
|
||||
@delete nvarchar(max)=N'DELETE te FROM dbo.ThreadEvents te';
|
||||
IF CHARINDEX(@table,@restore)=0 OR CHARINDEX(@insert,@restore)=0 OR CHARINDEX(@delete,@restore)=0 THROW 51012,'Review project restore before adding scene threads.',1;
|
||||
SET @restore=REPLACE(@restore,@table,@table+N', (N''SceneThreads'')');
|
||||
SET @restore=REPLACE(@restore,@delete,N'DELETE x FROM dbo.SceneThreads x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID;
|
||||
'+@delete);
|
||||
SET @restore=REPLACE(@restore,@insert,@insert+N'
|
||||
EXEC dbo.ProjectRestore_InsertJsonTable N''SceneThreads'', N''$.Data.SceneThreads'', @JsonData, @ProjectID, 0;');
|
||||
SET @restore=STUFF(@restore,1,CHARINDEX(N'PROCEDURE',@restore)-1,N'CREATE OR ALTER ');
|
||||
EXEC sys.sp_executesql @restore;
|
||||
END;
|
||||
GO
|
||||
@ -5,6 +5,7 @@
|
||||
ViewData["Title"] = "Context";
|
||||
var position = Model.Display?.Context?.Position;
|
||||
var tabs = new[] {
|
||||
new { id = "threads", displayName = "Threads", endpoint = Url.Action("ContextThreadsTab", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "threads", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty<string>() },
|
||||
new { id = "overview", displayName = "Overview", endpoint = Url.Action("ContextScene", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "reference", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "scene.focus" } },
|
||||
new { id = "characters", displayName = "Characters in Scene", endpoint = Url.Action("ContextCharacters", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "characters", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "character.focus" } },
|
||||
new { id = "names", displayName = "Names", endpoint = Url.Action("ContextNamesTab", "Writing"), scope = "Book", contentRefresh = "relevant-scope", lifecycle = "names", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty<string>() },
|
||||
@ -70,6 +71,7 @@
|
||||
<script src="~/js/location-picker.js" asp-append-version="true"></script>
|
||||
<script src="~/js/location-types.js" asp-append-version="true"></script>
|
||||
<script src="~/js/floor-plan-renderer.js" asp-append-version="true"></script>
|
||||
<script src="~/js/context-threads.js" asp-append-version="true"></script>
|
||||
<script src="~/js/context-spatial.js" asp-append-version="true"></script>
|
||||
<script src="~/js/context-calendar-model.js" asp-append-version="true"></script>
|
||||
<script src="~/js/context-calendar.js" asp-append-version="true"></script>
|
||||
|
||||
9
PlotLine/Views/Writing/_ContextThreads.cshtml
Normal file
9
PlotLine/Views/Writing/_ContextThreads.cshtml
Normal file
@ -0,0 +1,9 @@
|
||||
@{ Layout = null; }
|
||||
@model PlotLine.Services.Context.SpatialScope
|
||||
<div data-context-tab-fragment data-context-threads data-project-id="@Model.ProjectID" data-book-id="@Model.BookID" data-chapter-id="@Model.ChapterID" data-scene-id="@Model.SceneID">
|
||||
<h2 class="h5">Threads · @Model.Label</h2>
|
||||
<form hidden>@Html.AntiForgeryToken()</form>
|
||||
<button type="button" class="btn btn-outline-primary btn-sm" data-thread-add disabled>Add thread</button>
|
||||
<p role="alert" class="text-danger" data-thread-error></p>
|
||||
<div data-thread-rows><p>Loading saved threads…</p></div>
|
||||
</div>
|
||||
146
PlotLine/wwwroot/js/context-threads.js
Normal file
146
PlotLine/wwwroot/js/context-threads.js
Normal file
@ -0,0 +1,146 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
const instances = new WeakMap();
|
||||
const el = (tag, text, cls) => {
|
||||
const node = document.createElement(tag);
|
||||
if (text != null) node.textContent = text;
|
||||
if (cls) node.className = cls;
|
||||
return node;
|
||||
};
|
||||
const button = (text, action) => {
|
||||
const node = el('button', text, 'btn btn-outline-secondary btn-sm');
|
||||
node.type = 'button'; node.addEventListener('click', action); return node;
|
||||
};
|
||||
const sceneLabel = s => `Ch ${s.chapterNumber}: ${s.chapterTitle} · Scene ${s.sceneNumber}: ${s.sceneTitle}`;
|
||||
function mount(node) {
|
||||
if (instances.has(node)) return;
|
||||
const bookID = Number(node.dataset.bookId), sceneID = Number(node.dataset.sceneId);
|
||||
const add = node.querySelector('[data-thread-add]'), rows = node.querySelector('[data-thread-rows]');
|
||||
const error = node.querySelector('[data-thread-error]');
|
||||
let alive = true, busy = false, dialog, data, readVersion = 0;
|
||||
const controller = new AbortController();
|
||||
const guard = (value, deferRefresh = false) => {
|
||||
busy = value;
|
||||
node.dispatchEvent(new CustomEvent('context-panel-state', { bubbles: true, detail: { dirty: value, busy: false, deferRefresh } }));
|
||||
};
|
||||
const fail = e => { if (alive) { error.textContent = e.message; window.PlotDirector?.toast?.error(e.message); } };
|
||||
async function read() {
|
||||
const version = ++readVersion;
|
||||
const response = await fetch(`/ContextThreads/State?bookId=${bookID}&sceneId=${sceneID}`, { cache: 'no-store', signal: controller.signal });
|
||||
if (!response.ok || response.redirected) throw Error('Threads are unavailable. Check book access and refresh saved data.');
|
||||
const result = await response.json();
|
||||
if (!alive || version !== readVersion) return;
|
||||
data = result;
|
||||
const linked = data.threads.filter(t => t.linked);
|
||||
rows.replaceChildren();
|
||||
if (!linked.length) rows.append(el('p', 'No threads linked to this scene.'));
|
||||
for (const thread of linked) {
|
||||
const article = el('article', null, 'writing-context-card');
|
||||
article.append(el('h3', `${thread.plotLineName} / ${thread.title}`, 'h6'));
|
||||
if (!thread.previousScenes.length) article.append(el('p', 'First picked up here.'));
|
||||
else {
|
||||
article.append(el('p', 'Previously picked up in:'));
|
||||
const list = el('ol');
|
||||
for (const scene of thread.previousScenes) list.append(el('li', sceneLabel(scene)));
|
||||
article.append(list);
|
||||
}
|
||||
rows.append(article);
|
||||
}
|
||||
add.disabled = !data.scope.canEdit;
|
||||
}
|
||||
function picker() {
|
||||
if (!alive || busy || !data?.scope.canEdit) return;
|
||||
guard(true); error.textContent = '';
|
||||
dialog = el('dialog', null, 'pd-location-picker-dialog');
|
||||
const heading = el('h2', 'Add threads to scene');
|
||||
const target = el('p', data.scope.label);
|
||||
const search = el('input', null, 'form-control');
|
||||
search.type = 'search'; search.placeholder = 'Search Plot Lines and Threads'; search.setAttribute('aria-label', 'Search Plot Lines and Threads');
|
||||
const tree = el('div', null, 'pd-location-picker-tree');
|
||||
const message = el('p'); message.setAttribute('role', 'status');
|
||||
const selected = new Set(), expanded = new Set();
|
||||
let saving = false;
|
||||
const submit = button('Add to scene', save), cancel = button('Cancel', () => dialog.close());
|
||||
submit.className = 'btn btn-primary btn-sm'; submit.disabled = true;
|
||||
function render() {
|
||||
tree.replaceChildren();
|
||||
const term = search.value.trim().toLocaleLowerCase();
|
||||
const groups = new Map();
|
||||
for (const thread of data.threads) {
|
||||
if (!groups.has(thread.plotLineID)) groups.set(thread.plotLineID, []);
|
||||
groups.get(thread.plotLineID).push(thread);
|
||||
}
|
||||
for (const [lineID, threads] of groups) {
|
||||
const matches = term ? threads.filter(t => `${t.plotLineName} ${t.title}`.toLocaleLowerCase().includes(term)) : threads;
|
||||
if (!matches.length) continue;
|
||||
const group = el('details'); group.open = !!term || expanded.has(lineID);
|
||||
group.append(el('summary', threads[0].plotLineName));
|
||||
group.addEventListener('toggle', () => { if (!term) { if (group.open) expanded.add(lineID); else expanded.delete(lineID); } });
|
||||
for (const thread of matches) {
|
||||
const label = el('label', null, 'pd-location-picker-row');
|
||||
label.style.setProperty('--picker-depth', '1');
|
||||
const input = el('input'); input.type = 'checkbox'; input.value = String(thread.plotThreadID);
|
||||
input.disabled = thread.linked || saving; input.checked = thread.linked || selected.has(thread.plotThreadID);
|
||||
input.addEventListener('change', () => {
|
||||
if (input.checked) selected.add(thread.plotThreadID); else selected.delete(thread.plotThreadID);
|
||||
submit.disabled = !selected.size; message.textContent = `${selected.size} selected`;
|
||||
});
|
||||
label.append(input, el('span', thread.title));
|
||||
if (thread.linked) label.append(el('small', ' · Already linked'));
|
||||
group.append(label);
|
||||
}
|
||||
tree.append(group);
|
||||
}
|
||||
if (!tree.children.length) tree.append(el('p', 'No matching threads.'));
|
||||
}
|
||||
async function save() {
|
||||
if (saving || !selected.size) return;
|
||||
saving = true; submit.disabled = true; cancel.disabled = true; search.disabled = true; render();
|
||||
message.textContent = 'Saving threads…';
|
||||
try {
|
||||
const response = await fetch('/ContextThreads/Add', {
|
||||
method: 'POST', credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/json', RequestVerificationToken: node.querySelector('[name="__RequestVerificationToken"]').value },
|
||||
body: JSON.stringify({ bookID, sceneID, threadIDs: [...selected] })
|
||||
});
|
||||
if (!response.ok || response.redirected) {
|
||||
const body = await response.json().catch(() => null);
|
||||
throw Error(body?.message || 'Threads could not be saved. Review access and try again.');
|
||||
}
|
||||
// Keep the dialog and panel guarded until the saved data has reloaded.
|
||||
try { await read(); }
|
||||
catch { error.textContent = 'Threads were saved. Refresh saved data to reload the scene.'; }
|
||||
window.PlotDirector?.toast?.success('Threads added to scene');
|
||||
saving = false; dialog.close();
|
||||
} catch (e) {
|
||||
message.textContent = e.message; window.PlotDirector?.toast?.error(e.message);
|
||||
saving = false; submit.disabled = false; cancel.disabled = false; search.disabled = false; render();
|
||||
}
|
||||
}
|
||||
search.addEventListener('input', render);
|
||||
dialog.addEventListener('cancel', event => { if (saving) event.preventDefault(); });
|
||||
dialog.addEventListener('close', () => {
|
||||
dialog.remove(); dialog = null;
|
||||
if (alive) {
|
||||
add.focus(); guard(false, true);
|
||||
node.closest('[data-context-workspace]')?.contextController?.invalidate({ bookId: bookID, kind: 'threads' });
|
||||
}
|
||||
}, { once: true });
|
||||
dialog.append(heading, target, search, tree, message, submit, cancel);
|
||||
dialog.setAttribute('aria-label', 'Add threads to scene');
|
||||
document.body.append(dialog); render(); dialog.showModal(); search.focus();
|
||||
}
|
||||
add.addEventListener('click', picker);
|
||||
instances.set(node, { busy: () => busy, refresh: () => read().catch(fail), dispose() { alive = false; controller.abort(); dialog?.remove(); add.removeEventListener('click', picker); } });
|
||||
read().catch(e => { if (e.name !== 'AbortError') fail(e); });
|
||||
}
|
||||
window.PlotDirectorContextLifecycles = { ...(window.PlotDirectorContextLifecycles || {}), threads: {
|
||||
mount, canRefresh: node => !instances.get(node)?.busy(),
|
||||
onInvalidation(node) {
|
||||
const instance = instances.get(node);
|
||||
if (!instance || instance.busy()) return false;
|
||||
instance.refresh(); return true;
|
||||
},
|
||||
dispose(node) { instances.get(node)?.dispose(); instances.delete(node); }
|
||||
} };
|
||||
})();
|
||||
Loading…
x
Reference in New Issue
Block a user