Redesign Context Intent and Threads around chapter planning

This commit is contained in:
Atlas Development Worker 2026-12-06 17:57:40 +00:00
parent 493ad57969
commit 429acb4e0a
31 changed files with 1108 additions and 242 deletions

View File

@ -1,131 +1,115 @@
// Isolated browser interaction checks. Mock persistence is not live Development acceptance.
// Isolated interaction coverage. The in-memory fixture does not verify SQL persistence.
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), canRemove: !readonly && links.get(sceneID).has(t.plotThreadID),
previousScenes: sceneID === 22 && links.get(11).has(t.plotThreadID)
? [{ chapterID: 1, sceneID: 11, chapterNumber: 1, chapterTitle: 'Opening', sceneNumber: 1, sceneTitle: 'Earlier scene' }] : [] })) };
}
await context.route('http://context.test/**', async route => {
const page = await browser.newPage();
const errors = [];
page.on('pageerror', error => errors.push(error.message));
const writes = [];
const invalidations = [];
const placements = new Map([[1, { sceneID: 11 }]]);
let reject = true;
let canEdit = true;
const threads = ['A <saved> question', 'Promise', 'Hidden answer'];
await page.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);
if (url.pathname === '/ContextThreads/State') {
const sceneID = Number(url.searchParams.get('sceneId'));
return route.fulfill({ json: {
scope: { label: `Chapter 1 · Scene ${sceneID}`, canEdit },
threads: threads.map((title, index) => {
const plotThreadID = index + 1;
const target = placements.get(plotThreadID);
const includedInChapter = target?.chapterID === 101;
const includedInScene = target?.sceneID === sceneID;
return {
plotThreadID, title, plotLineName: 'Journey', includedInChapter, includedInScene,
canRemove: canEdit && (includedInChapter || includedInScene), assigned: !!target,
assignedElsewhere: !!target && !includedInChapter && !includedInScene,
assignmentLabel: target?.sceneID ? `Scene ${target.sceneID}` : null,
hasManuscriptAssociation: plotThreadID === 1 && sceneID === 11,
previousScenes: plotThreadID === 1 && sceneID === 22
? [{ chapterID: 101, sceneID: 11, chapterNumber: 1, chapterTitle: 'Opening', sceneNumber: 1, sceneTitle: 'Earlier scene' }] : [],
chapterBlock: plotThreadID === 3 ? 'Place Promise earlier in this book.' : null
};
})
} });
}
if (['/ContextThreads/Add', '/ContextThreads/Remove'].includes(url.pathname)) {
const body = route.request().postDataJSON();
writes.push(body);
assert.equal(route.request().headers().requestverificationtoken, 'fixture-token');
if (url.pathname.endsWith('/Add')) {
if (reject) return route.fulfill({ status: 409, json: { message: 'The saved assignment changed.' } });
for (const id of body.threadIDs)
placements.set(id, body.chapter ? { chapterID: body.chapterID } : { sceneID: body.sceneID });
} else {
placements.delete(body.threadID);
}
return route.fulfill({ json: { saved: true } });
}
if (url.pathname === '/ContextThreads/Remove') {
const body = route.request().postDataJSON(); writes.push(body);
assert.equal(route.request().headers()['requestverificationtoken'], 'fixture-token');
links.get(body.sceneID).delete(body.threadID);
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>' });
assert.equal(url.pathname, '/');
return route.fulfill({ contentType: 'text/html', body: '<!doctype html><main data-context-workspace></main>' });
});
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));
await page.evaluate(() => {
window.invalidations = [];
document.querySelector('main').contextController = { invalidate: hint => window.invalidations.push(hint) };
});
async function mount(sceneID) {
await page.evaluate(scene => {
const host = document.querySelector('main');
if (host.firstElementChild) window.PlotDirectorContextLifecycles.threads.dispose(host.firstElementChild);
host.innerHTML = `<div data-book-id="12" data-chapter-id="101" data-scene-id="${scene}">
<input name="__RequestVerificationToken" value="fixture-token" type="hidden">
<button data-thread-add disabled>Include threads</button><p data-thread-error></p><div data-thread-rows></div></div>`;
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);
}, sceneID);
await page.getByRole('heading', { name: 'Included here' }).waitFor();
}
await mount(11);
assert.equal(await page.getByRole('heading', {name: '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 add = page.getByRole('button', { name: 'Include threads', exact: true });
await page.getByRole('button', { name: 'Remove A <saved> question from scene' }).waitFor();
await add.click();
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);
assert.equal(await dialog.getByRole('checkbox', { name: /A <saved> question/ }).count(), 0);
assert.equal(await dialog.getByRole('checkbox', { name: /Hidden answer/ }).isDisabled(), true);
await dialog.getByRole('searchbox').fill('promise');
await dialog.getByRole('checkbox', { name: /Promise · Journey/ }).check();
const include = dialog.getByRole('button', { name: 'Include selected' });
await include.click();
await dialog.getByText('The saved assignment changed.').waitFor();
assert.equal(placements.has(2), false);
reject = false;
await dialog.getByRole('button', { name: 'Add to scene', exact: true }).click();
await include.click();
await dialog.waitFor({ state: 'detached' });
await page.getByRole('link', {name: 'Scene 1: Earlier scene'}).waitFor();
await mount(22); // Reload saved state through a fresh lifecycle.
await page.getByRole('link', {name: 'Scene 1: Earlier scene'}).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);
readonly = false;
assert.deepEqual(writes.at(-1), { bookID: 12, chapterID: 101, sceneID: 11, threadIDs: [2], chapter: true });
assert.equal(await add.evaluate(button => document.activeElement === button), true);
await mount(22);
const later = page.locator('[data-test-pane="0"]');
const previous = later.getByRole('link', {name: 'Scene 1: Earlier scene'}).first();
assert.equal(await previous.getAttribute('href'), '/Scenes/Edit/11?retainNarrativeFocus=true');
assert.equal(await previous.getAttribute('data-context-narrative'), 'author');
assert.equal(await later.getByText('Last pickup', {exact: true}).first().isVisible(), true);
await later.locator('summary').first().click();
assert.equal(await later.locator('details').first().getAttribute('open'), null);
await later.getByRole('button', {name: 'Remove A <saved> question from scene', exact: true}).click();
await later.getByRole('heading', {name: 'A <saved> question', exact: true}).waitFor({state: 'detached'});
assert.deepEqual(writes.at(-1), {bookID: 12, sceneID: 22, threadID: 1});
assert.equal(links.get(11).has(1), true);
assert.equal(await later.locator('[data-thread-add]').evaluate(n => document.activeElement === n), true);
await later.getByRole('button', { name: 'Add thread', exact: true }).click();
await dialog.getByRole('searchbox').fill('question');
assert.equal(await dialog.getByLabel('A <saved> question', {exact: true}).isEnabled(), true);
await dialog.getByRole("button", {name: "Cancel", exact: true}).click();
await dialog.waitFor({state: 'detached'});
await page.getByRole('button', { name: 'Remove Promise from chapter' }).waitFor();
await page.locator('summary', { hasText: 'Assigned elsewhere and scene history' }).click();
const earlier = page.getByRole('link', { name: 'Scene 1: Earlier scene' });
assert.equal(await earlier.getAttribute('href'), '/Scenes/Edit/11?retainNarrativeFocus=true');
await page.getByRole('button', { name: 'Remove Promise from chapter' }).click();
await page.getByText('No threads included here.').waitFor();
assert.deepEqual(writes.at(-1), { bookID: 12, chapterID: 101, sceneID: 22, threadID: 2, chapter: true });
assert.deepEqual([...placements.keys()], [1]);
invalidations.push(...await page.evaluate(() => window.invalidations));
assert.deepEqual(invalidations, [{ bookId: 12, kind: 'threads' }, { bookId: 12, kind: 'threads' }]);
canEdit = false;
await mount(11);
assert.equal(await add.isDisabled(), true);
assert.equal(await page.getByRole('button', { name: 'Remove A <saved> question from scene' }).count(), 0);
assert.deepEqual(errors, []);
console.log('PASS Context Threads nested search, parent context, linked state, multi-select, explicit target, guards, failure recovery, history, unlink, reload, split panes and read-only state (isolated fixtures)');
} finally { await browser.close(); }
})().catch(e => { console.error(e); process.exitCode = 1; });
console.log('PASS Context Threads search, blocked selection, exclusive assignment, chapter persistence across scenes, invalidation, history, and read-only controls (mocked)');
} finally {
await browser.close();
}
})().catch(error => { console.error(error); process.exitCode = 1; });

View File

@ -35,7 +35,7 @@ internal static class ContextThreadsTests
"Historical links remain visible after unassigning a thread.");
Check(panel.Threads.Single(t => t.PlotThreadID == 14).AssignedElsewhere, "A chapter assignment prevents a competing scene assignment.");
var planOnly = ContextThreads.Build(scope, data, [], plan);
Check(planOnly.Threads.Single(t => t.PlotThreadID == 10) is { Linked: true, CanRemove: true },
Check(planOnly.Threads.Single(t => t.PlotThreadID == 10) is { Linked: true, CanRemove: true, HasManuscriptAssociation: false },
"A planning assignment appears in Context without generating a historical link.");
Check(panel.Threads.Count == 3, "Exclude other books and projects; include project-wide lines.");
var question = panel.Threads.Single(t => t.PlotThreadID == 10);
@ -47,6 +47,14 @@ internal static class ContextThreadsTests
Check(earlier.Threads.Single(t => t.PlotThreadID == 10).PreviousScenes.Single().SceneID == 15, "History follows the selected scene, not IDs or latest saved scene.");
Check(!earlier.Threads.Single(t => t.PlotThreadID == 10).CanRemove, "Read-only scopes cannot offer removal.");
Check(typeof(ContextThreadsController).GetMethod("Remove")!.IsDefined(typeof(ValidateAntiForgeryTokenAttribute), true), "Thread removal requires antiforgery.");
var chapterScope = new SpatialScope { ProjectID = 7, BookID = 12, ChapterID = 3, CanEdit = true };
var chapterPanel = ContextThreads.Build(chapterScope, data, links,
[.. plan, new(11, null, null, "Requires Question", "Requires Question")]);
Check(chapterPanel.Threads.Single(t => t.PlotThreadID == 14) is
{ IncludedInChapter: true, IncludedInScene: false, CanRemove: true, AssignedElsewhere: false },
"Chapter placement is editable without a scene and does not create a manuscript association.");
Check(chapterPanel.Threads.Single(t => t.PlotThreadID == 11) is { Assigned: false, ChapterBlock: "Requires Question" },
"An unassigned prerequisite-blocked thread carries its eligibility explanation.");
var backup = new ProjectBackupExport
{
Project = new() { ProjectID = 7 },

View File

@ -8,7 +8,7 @@ namespace PlotLine.Controllers;
[Authorize]
[Route("Writing/Context/Intent")]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class ContextIntentController(ContextIntentPalette palette, ContextIntentChecklist checklist) : Controller
public sealed class ContextIntentController(ContextIntentPalette palette, ContextIntentChecklist checklist, ContextIntentMaterial material) : Controller
{
// Reusable read endpoint for both Context and the docked Writer component.
// It takes an explicit held scope and never follows or changes the Word caret.
@ -18,12 +18,31 @@ public sealed class ContextIntentController(ContextIntentPalette palette, Contex
if (!ModelState.IsValid || projectId <= 0 || bookId <= 0 || chapterId <= 0 || sceneId <= 0)
return BadRequest();
// The fragment contains only caller-supplied IDs. The palette read
// below authorises the exact scope before returning saved information.
// Data endpoints authorise the exact scope before returning saved information.
return PartialView("~/Views/Writing/_ContextIntentPanel.cshtml",
new IntentPaletteScope(projectId, bookId, chapterId, sceneId));
}
[HttpGet("Material")]
public async Task<IActionResult> Material(int bookId, int chapterId, int? sceneId)
{
if (!ModelState.IsValid) return BadRequest();
try { return PartialView("~/Views/Writing/_ContextIntentMaterial.cshtml", await material.Read(bookId, chapterId, sceneId)); }
catch (SqlException e) when (e.Number == 51010) { return StatusCode(StatusCodes.Status403Forbidden); }
}
[HttpPost("Notes")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Notes([FromBody] IntentNotesSave? request)
{
if (!ModelState.IsValid || request is null) return BadRequest();
try { await material.SaveNotes(request); return NoContent(); }
catch (ArgumentException e) { return BadRequest(new { message = e.Message }); }
catch (UnauthorizedAccessException) { return StatusCode(StatusCodes.Status403Forbidden); }
catch (SqlException e) when (e.Number == 51010) { return StatusCode(StatusCodes.Status403Forbidden); }
catch (SqlException e) when (e.Number == 51011) { return Conflict(new { message = e.Message }); }
}
[HttpGet("Checklist")]
public Task<IActionResult> Checklist(int bookId, int chapterId, int? sceneId) =>
ReadChecklist(bookId, chapterId, sceneId);

View File

@ -18,13 +18,13 @@ public sealed class ContextThreadsController(ContextThreads threads) : Controlle
}
[HttpGet]
public Task<IActionResult> State(int bookId, int sceneId) => Guard(async () =>
ModelState.IsValid && bookId > 0 && sceneId > 0 ? Json(await threads.Read(bookId, sceneId)) : BadRequest());
public Task<IActionResult> State(int bookId, int? sceneId, int? chapterId) => Guard(async () =>
ModelState.IsValid && bookId > 0 && (sceneId is > 0 || chapterId is > 0 && sceneId is null) ? Json(await threads.Read(bookId, sceneId, chapterId)) : 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();
if (!ModelState.IsValid || input == null || input.BookID <= 0 || (input.SceneID is not > 0 && !(input.SceneID is null && input.Chapter && input.ChapterID is > 0))) return BadRequest();
await threads.Add(input);
return Json(new { saved = true });
});
@ -32,7 +32,7 @@ public sealed class ContextThreadsController(ContextThreads threads) : Controlle
[HttpPost, ValidateAntiForgeryToken]
public Task<IActionResult> Remove([FromBody] ContextThreadRemoval input) => Guard(async () =>
{
if (!ModelState.IsValid || input == null || input.BookID <= 0 || input.SceneID <= 0 || input.ThreadID <= 0) return BadRequest();
if (!ModelState.IsValid || input == null || input.BookID <= 0 || (input.SceneID is not > 0 && !(input.SceneID is null && input.Chapter && input.ChapterID is > 0)) || input.ThreadID <= 0) return BadRequest();
await threads.Remove(input);
return Json(new { saved = true });
});

View File

@ -65,12 +65,13 @@ public sealed class StoryElementReferencesController(
{
if (!ModelState.IsValid || currentUser.UserId is not int userId) return NotFound();
var scope = new StoryElementReferenceScope(entityType, entityId);
if (entityType is StoryElementType.Chapter or StoryElementType.Scene && !WantsJson) return BadRequest();
var list = await references.ListAsync(userId, scope);
if (list?.Access.CanEdit != true) return NotFound();
note = (note ?? "").Trim();
if (note.Length > 500) return Return(scope, "Use 500 characters or fewer.");
if (kind == "Characteristic" && scope.EntityType != StoryElementType.PlotThread && upload is null && note.Length > 0)
if (kind == "Characteristic" && !scope.AttachmentsOnly && upload is null && note.Length > 0)
{
return await Finish(scope, await references.ChangeAsync(userId, scope, "add", null, null, kind, note));
}
@ -147,6 +148,7 @@ public sealed class StoryElementReferencesController(
if (!ModelState.IsValid || currentUser.UserId is not int userId ||
operation is not ("edit" or "delete" or "caption" or "primary" or "clear")) return NotFound();
var scope = new StoryElementReferenceScope(entityType, entityId);
if (entityType is StoryElementType.Chapter or StoryElementType.Scene && !WantsJson) return BadRequest();
note = (note ?? "").Trim();
if (note.Length > 500) return Return(scope, "Use 500 characters or fewer.");
title = title?.Trim();
@ -169,7 +171,12 @@ public sealed class StoryElementReferencesController(
if (change.QuotaExceeded) return Return(scope, "This upload would exceed the account storage allowance.");
if (!change.Changed)
return Return(scope, "The reference changed or the note is empty. Review the saved references and try again.");
await savedData.Activity(change.ProjectID, scope.EntityType.ToString(), scope.EntityID);
await (scope.EntityType switch
{
StoryElementType.Chapter => savedData.Chapter(scope.EntityID, "intent"),
StoryElementType.Scene => savedData.Scene(scope.EntityID, "intent"),
_ => savedData.Activity(change.ProjectID, scope.EntityType.ToString(), scope.EntityID)
});
return Success(scope);
}

View File

@ -138,18 +138,20 @@ public sealed class WritingController(
[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)
Guid? instanceId, Guid? sessionId, [FromServices] PlotLine.Services.Context.ContextThreads threads)
{
if (!ModelState.IsValid || bookId is not > 0 || sceneId is not > 0 || InvalidNativeSelection(instanceId, sessionId)) return BadRequest();
if (!ModelState.IsValid || bookId is not > 0 || (sceneId is not > 0 && !(sceneId is null && chapterId is > 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);
var scope = await threads.Scope(bookId.Value, sceneId, chapterId);
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 (UnauthorizedAccessException) { return Forbid(); }
catch (ArgumentException) { return BadRequest(); }
catch (Microsoft.Data.SqlClient.SqlException e) when (e.Number == 51010) { return Forbid(); }
}

View File

@ -3,10 +3,12 @@ using Dapper;
namespace PlotLine.Data;
public enum StoryElementType { Character, Location, Asset, PlotThread }
public enum StoryElementType { Character, Location, Asset, PlotThread, Chapter, Scene }
public sealed record StoryElementReferenceScope(StoryElementType EntityType, int EntityID)
{
public bool AttachmentsOnly => EntityType is StoryElementType.PlotThread or StoryElementType.Chapter or StoryElementType.Scene;
public string DetailsController => EntityType switch
{
StoryElementType.Character => "Characters",

View File

@ -314,6 +314,10 @@ public sealed class ProjectBackupStoryElementReference
{
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
public int? PlotThreadID { get; set; }
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
public int? ChapterID { get; set; }
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
public int? SceneID { get; set; }
public int ReferenceID { get; set; }
public int? CharacterID { get; set; }
public int? LocationID { get; set; }

View File

@ -316,6 +316,7 @@ public class Program
builder.Services.AddScoped<PlotLine.Services.Context.ContextAssets>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextIntentPalette>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextIntentChecklist>();
builder.Services.AddScoped<PlotLine.Services.Context.ContextIntentMaterial>();
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

@ -35,6 +35,9 @@ public static class BookBackupGraph
if (!removed) break;
}
var scenes = b.Data.Scenes.Select(s => s.SceneID).ToHashSet();
var chapters = b.Data.Chapters.Select(c => c.ChapterID).ToHashSet();
b.Data.StoryElementReferences = b.Data.StoryElementReferences?.Where(r => (!r.ChapterID.HasValue || chapters.Contains(r.ChapterID.Value))
&& (!r.SceneID.HasValue || scenes.Contains(r.SceneID.Value))).ToList();
if (source.Data.SceneDependencies.Any(d => scenes.Contains(d.SourceSceneID) != scenes.Contains(d.TargetSceneID))) throw new ArgumentException("These books have a cross-book scene dependency. Include the connected books to preserve it.");
if (source.Data.MapJourneyNotes.Any(n => scenes.Contains(n.FromSceneID) != scenes.Contains(n.ToSceneID))) throw new ArgumentException("A saved map journey connects these books. Include the connected books to preserve it.");
b.Recovery.ExternalReferences = b.Recovery.ExternalReferences.Where(r => Identity(r.Collection) is string identity && Rows(b, r.Collection).Any(owner => Equals(Value(owner, identity), r.OwnerID))).ToList();

View File

@ -0,0 +1,46 @@
using System.Data;
using System.Text.Json;
using Dapper;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.ViewModels;
namespace PlotLine.Services.Context;
public sealed record IntentNotesSave(int BookID, int ChapterID, int? SceneID, string? Original, string? Notes);
public sealed record IntentSourceNote(string ThreadTitle, string? WritingNotes, string? PlanningChecklist, int? SceneID)
{
public IReadOnlyList<ThreadChecklistItem> Items => PlanningChecklist is null ? []
: JsonSerializer.Deserialize<List<ThreadChecklistItem>>(PlanningChecklist) ?? [];
}
public sealed record IntentSourceReference(int ReferenceID, string EntityType, int EntityID,
string Kind, string Note, string? Title, string? OriginalFileName, string Source, int? SceneID);
public sealed record IntentMaterial(IReadOnlyList<IntentSourceNote> Notes, IReadOnlyList<IntentSourceReference> References);
public sealed class ContextIntentMaterial(ISqlConnectionFactory connections, ICurrentUserService user,
ContextWorkspaceNotifications notifications)
{
public async Task<IntentMaterial> Read(int bookId, int chapterId, int? sceneId)
{
using var db = connections.CreateConnection();
using var result = await db.QueryMultipleAsync("dbo.ContextIntent_Material",
new { UserID = user.UserId!.Value, BookID = bookId, ChapterID = chapterId, SceneID = sceneId },
commandType: CommandType.StoredProcedure);
var notes = (await result.ReadAsync<IntentSourceNote>()).AsList();
var references = (await result.ReadAsync<IntentSourceReference>()).DistinctBy(row => row.ReferenceID).ToArray();
return new(notes, references);
}
public async Task SaveNotes(IntentNotesSave request)
{
ContextIntentPalette.Validate(new(request.BookID, request.ChapterID, request.SceneID));
if (request.Notes?.Length > 100_000)
throw new ArgumentException("Use 100,000 characters or fewer.");
var author = user.UserId ?? throw new UnauthorizedAccessException();
using var db = connections.CreateConnection();
var project = await db.QuerySingleAsync<int>("dbo.ContextIntent_SaveNotes",
new { UserID = author, request.BookID, request.ChapterID, request.SceneID, request.Original, request.Notes },
commandType: CommandType.StoredProcedure);
await notifications.Invalidate(author, request.BookID, request.ChapterID, request.SceneID, project, kind: "intent");
}
}

View File

@ -7,24 +7,40 @@ using PlotLine.Models;
namespace PlotLine.Services.Context;
public sealed record ContextThreadRow(int PlotThreadID, int PlotLineID, string Title, string PlotLineName,
bool Linked, bool CanRemove, IReadOnlyList<PlotLineWorkspaceAttributionRow> PreviousScenes, bool AssignedElsewhere);
public sealed record ContextThreadPlacement(int PlotThreadID, int? AssignedSceneID, int? AssignedChapterID);
bool Linked, bool CanRemove, IReadOnlyList<PlotLineWorkspaceAttributionRow> PreviousScenes, bool AssignedElsewhere, bool IncludedInChapter, bool IncludedInScene,
string? SceneBlock, string? ChapterBlock, bool Assigned, string? AssignmentLabel, bool HasManuscriptAssociation);
public sealed record ContextThreadPlacement(int PlotThreadID, int? AssignedSceneID, int? AssignedChapterID,
string? SceneBlock = null, string? ChapterBlock = null, string? AssignmentLabel = null);
public sealed record ContextThreadsPanel(SpatialScope Scope, IReadOnlyList<ContextThreadRow> Threads);
public sealed record ContextThreadSelection(int BookID, int SceneID, int[] ThreadIDs);
public sealed record ContextThreadRemoval(int BookID, int SceneID, int ThreadID);
public sealed record ContextThreadSelection(int BookID, int? SceneID, int[] ThreadIDs, bool Chapter = false, int? ChapterID = null);
public sealed record ContextThreadRemoval(int BookID, int? SceneID, int ThreadID, bool Chapter = false, int? ChapterID = null);
public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRepository workspace,
ISqlConnectionFactory connections, ICurrentUserService user, ContextWorkspaceNotifications notifications)
{
public async Task<ContextThreadsPanel> Read(int book, int scene)
public async Task<SpatialScope> Scope(int book, int? scene, int? chapter)
{
var scope = await spatial.Scope(book, scene);
if (scene.HasValue)
{
var scope = await spatial.Scope(book, scene.Value);
if (chapter.HasValue && scope.ChapterID != chapter) throw new ArgumentException("Choose a scene in this chapter.");
return scope;
}
using var db = connections.CreateConnection();
return await db.QuerySingleOrDefaultAsync<SpatialScope>("dbo.ContextThreads_Chapter",
new { BookID = book, ChapterID = chapter, UserID = user.UserId!.Value },
commandType: CommandType.StoredProcedure) ?? throw new UnauthorizedAccessException();
}
public async Task<ContextThreadsPanel> Read(int book, int? scene, int? chapter)
{
var scope = await Scope(book, scene, chapter);
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);
var placements = await db.QueryAsync<ContextThreadPlacement>("dbo.PlotThreadPlanning_ListByBook",
new { BookID = book, UserID = user.UserId!.Value }, commandType: CommandType.StoredProcedure);
var placements = await db.QueryAsync<ContextThreadPlacement>("dbo.ContextThreads_List",
new { BookID = book, SceneID = scene, ChapterID = scope.ChapterID, UserID = user.UserId!.Value }, commandType: CommandType.StoredProcedure);
return Build(scope, data, links, placements);
}
@ -32,12 +48,10 @@ public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRep
IEnumerable<ContextThreadPlacement> planning)
{
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.");
if (!scenes.TryGetValue(scope.SceneID, out var current) && scope.SceneID > 0) 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 plans = planning.ToDictionary(p => p.PlotThreadID);
var associations = links.Select(l => (l.PlotThreadID, l.SceneID)).ToHashSet();
associations.UnionWith(plans.Values.Where(p => p.AssignedSceneID.HasValue)
.Select(p => (p.PlotThreadID, p.AssignedSceneID!.Value)));
associations.UnionWith(data.Contributions.Where(c => c.BookID == scope.BookID).Select(c => (c.PlotThreadID, c.SceneID)));
// Established milestones are authoritative associations too. A planned resolution
// alone is a future intention, not a scene where the thread has been picked up.
@ -46,14 +60,22 @@ public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRep
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)),
scope.CanEdit && plans.GetValueOrDefault(t.PlotThreadID)?.AssignedSceneID == scope.SceneID,
scenes.Values.Where(s => s.NarrativeOrder < current.NarrativeOrder && associations.Contains((t.PlotThreadID, s.SceneID)))
.OrderBy(s => s.NarrativeOrder).ToArray(),
plans.GetValueOrDefault(t.PlotThreadID) is { } plan
&& (plan.AssignedChapterID.HasValue || (plan.AssignedSceneID.HasValue && plan.AssignedSceneID != scope.SceneID)))).OrderBy(t => t.PlotLineName, StringComparer.CurrentCultureIgnoreCase).ThenBy(t => t.Title, StringComparer.CurrentCultureIgnoreCase).ToArray();
var rows = data.Threads.Where(t => lines.ContainsKey(t.PlotLineID)).Select(t =>
{
var placement = plans.GetValueOrDefault(t.PlotThreadID);
var includedInScene = placement?.AssignedSceneID == scope.SceneID;
var includedInChapter = scope.ChapterID > 0 && placement?.AssignedChapterID == scope.ChapterID;
var assigned = placement?.AssignedChapterID is not null || placement?.AssignedSceneID is not null;
var recordedHere = associations.Contains((t.PlotThreadID, scope.SceneID));
var history = scenes.Values.Where(s => current is not null && s.NarrativeOrder < current.NarrativeOrder
&& associations.Contains((t.PlotThreadID, s.SceneID)))
.OrderBy(s => s.NarrativeOrder).ToArray();
return new ContextThreadRow(t.PlotThreadID, t.PlotLineID, t.ThreadTitle, lines[t.PlotLineID].PlotLineName,
recordedHere || includedInScene, scope.CanEdit && (includedInScene || includedInChapter), history,
assigned && !includedInScene && !includedInChapter, includedInChapter, includedInScene,
placement?.SceneBlock, placement?.ChapterBlock, assigned, placement?.AssignmentLabel, recordedHere);
}).OrderBy(t => t.PlotLineName, StringComparer.CurrentCultureIgnoreCase)
.ThenBy(t => t.Title, StringComparer.CurrentCultureIgnoreCase).ToArray();
return new(scope, rows);
}
@ -62,8 +84,8 @@ public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRep
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.PlotThreadPlanning_ChangeScene",
new { input.BookID, input.SceneID, UserID = user.UserId ?? throw new UnauthorizedAccessException(), ThreadIDs = JsonSerializer.Serialize(input.ThreadIDs.Distinct()), Remove = false },
var project = await db.QuerySingleAsync<int>("dbo.ContextThreads_Change",
new { input.BookID, input.SceneID, input.ChapterID, input.Chapter, UserID = user.UserId ?? throw new UnauthorizedAccessException(), ThreadIDs = JsonSerializer.Serialize(input.ThreadIDs.Distinct()), Remove = false },
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");
@ -73,8 +95,8 @@ public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRep
{
var userId = user.UserId ?? throw new UnauthorizedAccessException();
using var db = connections.CreateConnection();
var project = await db.QuerySingleAsync<int>("dbo.PlotThreadPlanning_ChangeScene",
new { input.BookID, input.SceneID, UserID = userId, ThreadIDs = JsonSerializer.Serialize(new[] { input.ThreadID }), Remove = true },
var project = await db.QuerySingleAsync<int>("dbo.ContextThreads_Change",
new { input.BookID, input.SceneID, input.ChapterID, input.Chapter, UserID = userId, ThreadIDs = JsonSerializer.Serialize(new[] { input.ThreadID }), Remove = true },
commandType: CommandType.StoredProcedure);
await notifications.Invalidate(userId, projectId: project, bookId: input.BookID, kind: "threads");
}

View File

@ -39,7 +39,7 @@ public sealed class ContextSavedData(ContextWorkspaceNotifications notifications
{
"Character" => "characters", "Relationship" => "relationships",
"Location" or "Location Relationship" => "locations",
"Plot Line" => "plotlines", "Thread" or "Thread Event" => "threads",
"Plot Line" => "plotlines", "PlotThread" or "Thread" or "Thread Event" => "threads",
"Floor Plan" or "Floor Plan Transition" or "Floor Plan Background" => "floorplans",
"Asset" or "Asset Event" => "assets", _ => null
};

View File

@ -47,7 +47,8 @@ internal static class ProjectBackupGraphValidation
new("OnboardingManuscriptBuildCharacterMap",null,new Link("OnboardingManuscriptBuildID","OnboardingManuscriptBuilds","OnboardingManuscriptBuildID"),new Link("CharacterID","Characters","CharacterID")),
new("StoryElementReferences", "ReferenceID", new Link("CharacterID", "Characters", "CharacterID"),
new Link("LocationID", "Locations", "LocationID"), new Link("StoryAssetID", "StoryAssets", "StoryAssetID"),
new Link("PlotThreadID", "PlotThreads", "PlotThreadID")),
new Link("PlotThreadID", "PlotThreads", "PlotThreadID"),
new Link("ChapterID", "Chapters", "ChapterID"), new Link("SceneID", "Scenes", "SceneID")),
new("CharacterImages","CharacterImageID",new Link("CharacterID","Characters","CharacterID"),new Link("ProjectID","Project","ProjectID")),
new("WordCompanionSceneAssets","WordCompanionSceneAssetID",new Link("SceneID","Scenes","SceneID"),new Link("StoryAssetID","StoryAssets","StoryAssetID")),
new("WordCompanionSceneLocations","WordCompanionSceneLocationID",new Link("SceneID","Scenes","SceneID"),new Link("LocationID","Locations","LocationID")),
@ -148,16 +149,17 @@ internal static class ProjectBackupGraphValidation
var primaryReferenceOwners = new HashSet<(int? LocationID, int? StoryAssetID)>();
foreach (var reference in backup.Data.StoryElementReferences ?? [])
{
var intentAttachment = reference.ChapterID.HasValue || reference.SceneID.HasValue;
if (reference.Title?.Length > 160 ||
(reference.IsPrimary.HasValue && (reference.IsPrimary != true || reference.Kind != "Image" ||
reference.CharacterID.HasValue || reference.PlotThreadID.HasValue || !primaryReferenceOwners.Add((reference.LocationID, reference.StoryAssetID)))))
reference.CharacterID.HasValue || reference.PlotThreadID.HasValue || intentAttachment || !primaryReferenceOwners.Add((reference.LocationID, reference.StoryAssetID)))))
return "Project backup contains invalid attachment metadata.";
if (new[] { reference.CharacterID, reference.LocationID, reference.StoryAssetID, reference.PlotThreadID }.Count(id => id.HasValue) != 1 ||
if (new[] { reference.CharacterID, reference.LocationID, reference.StoryAssetID, reference.PlotThreadID, reference.ChapterID, reference.SceneID }.Count(id => id.HasValue) != 1 ||
reference.Note is null || reference.Note.Length > 500)
return "Project backup contains an invalid story element reference.";
if (reference.Kind == "Characteristic")
{
if (string.IsNullOrWhiteSpace(reference.Note) || reference.StoragePath is not null || reference.OriginalFileName is not null)
if (intentAttachment || string.IsNullOrWhiteSpace(reference.Note) || reference.StoragePath is not null || reference.OriginalFileName is not null)
return "Project backup contains an invalid key characteristic.";
}
else if (reference.Kind is not ("Image" or "Attachment") ||

View File

@ -22,7 +22,7 @@ internal static partial class ProjectBackupStoredFieldContract
["CharacterAttributeTypes"]=("CharacterAttributeTypeID,ProjectID,AttributeName,DataType,IsNormallyStable,SortOrder,IsActive","ProjectID"),
["CharacterEnrichmentEvidence"]=("CharacterEnrichmentEvidenceID,CharacterEnrichmentRunID,CharacterID,SceneID,FieldName,Value,Evidence,Confidence,Source,CreatedUtc","SceneID,Value,Evidence"),
["CharacterEnrichmentRuns"]=("CharacterEnrichmentRunID,ProjectID,BookID,UserID,StoryIntelligenceBookPipelineID,CharacterResolutionVersion,Status,TotalCharacters,ProcessedCharacters,CurrentStage,CurrentMessage,QueuedUtc,StartedUtc,CompletedUtc,FailedUtc,AttemptCount,Model,InputTokens,OutputTokens,TotalTokens,DurationMs,ErrorMessage,ErrorDetail,IsCurrent,UpdatedUtc,CharacterID","StoryIntelligenceBookPipelineID,CurrentStage,CurrentMessage,StartedUtc,CompletedUtc,FailedUtc,Model,InputTokens,OutputTokens,TotalTokens,DurationMs,ErrorMessage,ErrorDetail,CharacterID"),
["StoryElementReferences"]=("ReferenceID,CharacterID,LocationID,StoryAssetID,PlotThreadID,Kind,Note,StoragePath,OriginalFileName,Title,IsPrimary","CharacterID,LocationID,StoryAssetID,PlotThreadID,StoragePath,OriginalFileName,Title,IsPrimary"),
["StoryElementReferences"]=("ReferenceID,CharacterID,LocationID,StoryAssetID,PlotThreadID,ChapterID,SceneID,Kind,Note,StoragePath,OriginalFileName,Title,IsPrimary","CharacterID,LocationID,StoryAssetID,PlotThreadID,ChapterID,SceneID,StoragePath,OriginalFileName,Title,IsPrimary"),
["CharacterImages"]=("CharacterImageID,CharacterID,ProjectID,ImagePath,ThumbnailPath,Caption,SortOrder,UploadedDateUTC,IsDeleted,DeletedDateUTC","Caption,DeletedDateUTC"),
["CharacterIntelligenceEvidenceEvents"]=("CharacterIntelligenceEvidenceEventID,CharacterIntelligenceProfileID,SceneResultID,FieldName,PreviousValue,NewValue,Evidence,Confidence,IsContradiction,Source,CreatedUtc","PreviousValue,NewValue,Evidence"),
["CharacterIntelligenceProfiles"]=("CharacterIntelligenceProfileID,ImportSessionID,ProjectID,BookID,CanonicalIdentityKey,CanonicalName,ProfileJson,Confidence,NarrativeImportance,IsRecurring,EvidenceVersion,LastUpdatedSceneResultID,CreatedUtc,UpdatedUtc","NarrativeImportance,LastUpdatedSceneResultID"),

View File

@ -0,0 +1,207 @@
CREATE OR ALTER PROCEDURE dbo.ContextIntent_Material
@UserID int, @BookID int, @ChapterID int, @SceneID int = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE @ProjectID int;
SELECT @ProjectID = p.ProjectID
FROM dbo.Chapters c
JOIN dbo.Books b ON b.BookID = c.BookID AND b.IsArchived = 0
JOIN dbo.Projects p ON p.ProjectID = b.ProjectID AND p.IsArchived = 0
JOIN dbo.ProjectUserAccess a ON a.ProjectID = p.ProjectID AND a.UserID = @UserID AND a.IsActive = 1
WHERE c.ChapterID = @ChapterID AND c.BookID = @BookID AND c.IsArchived = 0;
IF @ProjectID IS NULL OR (@SceneID IS NOT NULL AND NOT EXISTS
(SELECT 1 FROM dbo.Scenes WHERE SceneID = @SceneID AND ChapterID = @ChapterID AND IsArchived = 0))
THROW 51010, 'This Intent scope is unavailable.', 1;
SELECT t.PlotThreadID, t.ThreadTitle, t.WritingNotes, t.PlanningChecklist,
p.SceneID, p.AssignmentOrder
INTO #Included
FROM dbo.PlotThreadPlacements p
JOIN dbo.PlotThreads t ON t.PlotThreadID = p.PlotThreadID
WHERE p.ProjectID = @ProjectID AND p.BookID = @BookID AND p.ChapterID = @ChapterID
AND (p.SceneID IS NULL OR p.SceneID = @SceneID);
SELECT ThreadTitle, WritingNotes, PlanningChecklist, SceneID
FROM #Included ORDER BY SceneID, AssignmentOrder, PlotThreadID;
SELECT r.ReferenceID, 'PlotThread' AS EntityType, i.PlotThreadID AS EntityID,
r.Kind, r.Note, r.Title, r.OriginalFileName, i.ThreadTitle AS Source, i.SceneID
FROM #Included i JOIN dbo.StoryElementReferences r ON r.PlotThreadID = i.PlotThreadID
UNION ALL
SELECT r.ReferenceID, CASE e.ElementType WHEN 'C' THEN 'Character' WHEN 'L' THEN 'Location' ELSE 'Asset' END,
e.ElementID, r.Kind, r.Note, r.Title, r.OriginalFileName, e.Label, i.SceneID
FROM #Included i
JOIN dbo.PlotThreadPlannedElements l ON l.PlotThreadID = i.PlotThreadID
JOIN dbo.PlotThreadPlanningElements e ON e.ProjectID = @ProjectID AND e.IsArchived = 0
AND e.ElementType = l.ElementType AND e.ElementID = l.ElementID
JOIN dbo.StoryElementReferences r ON (e.ElementType = 'C' AND r.CharacterID = e.ElementID)
OR (e.ElementType = 'L' AND r.LocationID = e.ElementID)
OR (e.ElementType = 'A' AND r.StoryAssetID = e.ElementID)
ORDER BY ReferenceID, SceneID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.ContextIntent_SaveNotes
@UserID int, @BookID int, @ChapterID int, @SceneID int = NULL,
@Original nvarchar(max), @Notes nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRANSACTION;
DECLARE @ProjectID int, @Saved nvarchar(max);
SELECT @ProjectID = b.ProjectID FROM dbo.Chapters c WITH (HOLDLOCK)
JOIN dbo.Books b WITH (HOLDLOCK) ON b.BookID = c.BookID AND b.IsArchived = 0
JOIN dbo.Projects p WITH (HOLDLOCK) ON p.ProjectID = b.ProjectID AND p.IsArchived = 0
JOIN dbo.ProjectUserAccess a WITH (HOLDLOCK) ON a.ProjectID = p.ProjectID AND a.UserID = @UserID
AND a.IsActive = 1 AND a.AccessRole IN ('Owner', 'Collaborator')
WHERE c.ChapterID = @ChapterID AND c.BookID = @BookID AND c.IsArchived = 0;
IF @ProjectID IS NULL OR (@SceneID IS NOT NULL AND NOT EXISTS
(SELECT 1 FROM dbo.Scenes WITH (UPDLOCK, HOLDLOCK) WHERE SceneID = @SceneID AND ChapterID = @ChapterID AND IsArchived = 0))
THROW 51010, 'This Intent scope is unavailable.', 1;
IF @SceneID IS NULL
SELECT @Saved = GoalSummary FROM dbo.ChapterGoals WITH (UPDLOCK, HOLDLOCK) WHERE ChapterID = @ChapterID;
ELSE
SELECT @Saved = ScenePurposeNotes FROM dbo.Scenes WITH (UPDLOCK, HOLDLOCK) WHERE SceneID = @SceneID;
IF CONVERT(varbinary(max), COALESCE(@Saved, N'')) <> CONVERT(varbinary(max), COALESCE(@Original, N''))
THROW 51011, 'The saved notes changed. Your draft is still here.', 1;
IF @SceneID IS NOT NULL
UPDATE dbo.Scenes SET ScenePurposeNotes = CASE WHEN DATALENGTH(@Notes) = 0 THEN NULL ELSE @Notes END WHERE SceneID = @SceneID;
ELSE
BEGIN
UPDATE dbo.ChapterGoals SET GoalSummary = CASE WHEN DATALENGTH(@Notes) = 0 THEN NULL ELSE @Notes END, UpdatedDate = SYSUTCDATETIME()
WHERE ChapterID = @ChapterID;
IF @@ROWCOUNT = 0 AND DATALENGTH(@Notes) > 0
INSERT dbo.ChapterGoals (ChapterID, GoalSummary) VALUES (@ChapterID, @Notes);
END;
COMMIT TRANSACTION;
SELECT @ProjectID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.SceneWorkflow_Get @SceneID int
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRANSACTION;
IF NOT EXISTS (SELECT 1 FROM dbo.SceneWorkflow WITH (UPDLOCK, HOLDLOCK) WHERE SceneID = @SceneID)
INSERT dbo.SceneWorkflow (SceneID) VALUES (@SceneID);
COMMIT TRANSACTION;
SELECT SceneWorkflowID, SceneID, DraftStatus, EstimatedWordCount, ActualWordCount, DraftedDate, LastWorkedOn,
ReadyForDraft, ReadyForRevision, ReadyForPolish, IsBlocked, BlockedReason, Priority, CreatedDate, UpdatedDate
FROM dbo.SceneWorkflow WHERE SceneID = @SceneID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.ContextThreads_List
@BookID int, @UserID int, @SceneID int = NULL, @ChapterID int = NULL
AS
BEGIN
SET NOCOUNT ON;
SELECT t.PlotThreadID, t.AssignedSceneID, t.AssignedChapterID,
sceneBlock.Reason AS SceneBlock, chapterBlock.Reason AS ChapterBlock, placement.Label AS AssignmentLabel
FROM dbo.PlotPlanningTargets currentScene
JOIN dbo.PlotPlanningTargets currentChapter ON currentChapter.BookID = currentScene.BookID
AND currentChapter.ChapterID = currentScene.ChapterID AND currentChapter.SceneID IS NULL
JOIN dbo.PlotLines l ON l.ProjectID = currentScene.ProjectID AND l.IsArchived = 0
AND (l.BookID IS NULL OR l.BookID = @BookID)
JOIN dbo.PlotThreads t ON t.PlotLineID = l.PlotLineID AND t.IsArchived = 0
LEFT JOIN dbo.PlotThreadPlacements placement ON placement.PlotThreadID = t.PlotThreadID
OUTER APPLY (
SELECT TOP (1) CONCAT(N'Place “', COALESCE(r.ThreadTitle, N'deleted thread'), N'” earlier in this book.') AS Reason
FROM dbo.PlotThreadPrerequisites e
LEFT JOIN dbo.PlotThreads r ON r.PlotThreadID = e.PrerequisiteID
LEFT JOIN dbo.PlotThreadPlacements p ON p.PlotThreadID = e.PrerequisiteID
WHERE e.PlotThreadID = t.PlotThreadID AND
(p.BookID IS NULL OR p.BookID <> @BookID OR p.NarrativeOrder >= currentScene.NarrativeOrder)
ORDER BY e.PrerequisiteID
) sceneBlock
OUTER APPLY (
SELECT TOP (1) CONCAT(N'Place “', COALESCE(r.ThreadTitle, N'deleted thread'), N'” earlier in this book.') AS Reason
FROM dbo.PlotThreadPrerequisites e
LEFT JOIN dbo.PlotThreads r ON r.PlotThreadID = e.PrerequisiteID
LEFT JOIN dbo.PlotThreadPlacements p ON p.PlotThreadID = e.PrerequisiteID
WHERE e.PlotThreadID = t.PlotThreadID AND
(p.BookID IS NULL OR p.BookID <> @BookID OR p.NarrativeOrder >= currentChapter.NarrativeOrder)
ORDER BY e.PrerequisiteID
) chapterBlock
WHERE currentScene.BookID = @BookID
AND (currentScene.SceneID = @SceneID OR (@SceneID IS NULL AND currentScene.SceneID IS NULL AND currentScene.ChapterID = @ChapterID))
AND EXISTS (SELECT 1 FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID = a.ProjectID AND p.IsArchived = 0
WHERE a.ProjectID = currentScene.ProjectID AND a.UserID = @UserID AND a.IsActive = 1);
END;
GO
CREATE OR ALTER PROCEDURE dbo.ContextThreads_Change
@BookID int, @SceneID int, @UserID int, @ThreadIDs nvarchar(max), @Remove bit, @Chapter bit, @ChapterID int = NULL
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRANSACTION;
DECLARE @ProjectID int, @TargetChapterID int, @TargetOrder bigint;
SELECT @ProjectID = ProjectID, @TargetChapterID = ChapterID, @TargetOrder = NarrativeOrder
FROM dbo.PlotPlanningTargets WHERE BookID = @BookID
AND (SceneID = @SceneID OR (@Chapter = 1 AND @SceneID IS NULL AND SceneID IS NULL AND ChapterID = @ChapterID))
AND (@ChapterID IS NULL OR ChapterID = @ChapterID);
IF @ProjectID IS NULL OR NOT EXISTS (SELECT 1 FROM dbo.ProjectUserAccess a WITH (HOLDLOCK)
JOIN dbo.Projects p WITH (HOLDLOCK) ON p.ProjectID = a.ProjectID AND p.IsArchived = 0
WHERE a.ProjectID = @ProjectID AND a.UserID = @UserID AND a.IsActive = 1 AND a.AccessRole IN ('Owner', 'Collaborator'))
THROW 51100, 'Edit access to this scene is required.', 1;
DECLARE @LockResult int, @Resource nvarchar(255) = CONCAT(N'PlotThreadPlanning:', @ProjectID);
EXEC @LockResult = sys.sp_getapplock @Resource, 'Exclusive', 'Transaction', 10000;
IF @LockResult < 0 THROW 51101, 'Planning is busy. Try again.', 1;
IF @Chapter = 1
SELECT @TargetOrder = NarrativeOrder FROM dbo.PlotPlanningTargets
WHERE BookID = @BookID AND ChapterID = @TargetChapterID AND SceneID IS NULL;
IF @Remove = 0 AND EXISTS (
SELECT 1 FROM dbo.PlotThreadPrerequisites e
LEFT JOIN dbo.PlotThreadPlacements p ON p.PlotThreadID = e.PrerequisiteID
WHERE e.PlotThreadID IN (SELECT TRY_CONVERT(int, value) FROM OPENJSON(@ThreadIDs))
AND (p.BookID IS NULL OR p.BookID <> @BookID OR p.NarrativeOrder >= @TargetOrder))
THROW 51101, 'Place the prerequisite threads earlier in this book before including this thread.', 1;
DECLARE @ThreadCount int = (SELECT COUNT(DISTINCT TRY_CONVERT(int, value)) FROM OPENJSON(@ThreadIDs));
UPDATE t SET AssignedSceneID = CASE WHEN @Remove = 0 AND @Chapter = 0 THEN @SceneID END,
AssignedChapterID = CASE WHEN @Remove = 0 AND @Chapter = 1 THEN @TargetChapterID END,
AssignmentOrder = CASE WHEN @Remove = 0 THEN t.AssignmentOrder ELSE 0 END,
UpdatedDate = SYSUTCDATETIME()
FROM dbo.PlotThreads t
JOIN dbo.PlotLines l ON l.PlotLineID = t.PlotLineID AND l.ProjectID = @ProjectID AND l.IsArchived = 0
WHERE t.IsArchived = 0 AND (l.BookID IS NULL OR l.BookID = @BookID)
AND t.PlotThreadID IN (SELECT TRY_CONVERT(int, value) FROM OPENJSON(@ThreadIDs))
AND ((@Remove = 1 AND ((@Chapter = 0 AND t.AssignedSceneID = @SceneID)
OR (@Chapter = 1 AND t.AssignedChapterID = @TargetChapterID)))
OR (@Remove = 0 AND t.AssignedChapterID IS NULL AND t.AssignedSceneID IS NULL));
IF @@ROWCOUNT <> @ThreadCount
THROW 51101, 'An assignment changed or is outside this book. Open the thread editor to move it.', 1;
EXEC dbo.PlotThreadPlanning_Validate @ProjectID;
COMMIT;
SELECT @ProjectID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.ContextThreads_Chapter
@BookID int, @ChapterID int, @UserID int
AS
BEGIN
SET NOCOUNT ON;
SELECT b.ProjectID, b.BookID, c.ChapterID, c.ChapterTitle, c.ChapterNumber,
CONVERT(bit, CASE WHEN a.AccessRole IN ('Owner', 'Collaborator') THEN 1 ELSE 0 END) AS CanEdit
FROM dbo.Chapters c
JOIN dbo.Books b ON b.BookID = c.BookID AND b.IsArchived = 0
JOIN dbo.Projects p ON p.ProjectID = b.ProjectID AND p.IsArchived = 0
JOIN dbo.ProjectUserAccess a ON a.ProjectID = p.ProjectID AND a.UserID = @UserID AND a.IsActive = 1
WHERE b.BookID = @BookID AND c.ChapterID = @ChapterID AND c.IsArchived = 0;
END;
GO

View File

@ -0,0 +1,249 @@
IF COL_LENGTH('dbo.StoryElementReferences', 'ChapterID') IS NULL
ALTER TABLE dbo.StoryElementReferences ADD ChapterID int NULL REFERENCES dbo.Chapters(ChapterID) ON DELETE CASCADE;
IF COL_LENGTH('dbo.StoryElementReferences', 'SceneID') IS NULL
ALTER TABLE dbo.StoryElementReferences ADD SceneID int NULL REFERENCES dbo.Scenes(SceneID) ON DELETE CASCADE;
GO
IF OBJECT_ID('dbo.CK_StoryElementReferences_IntentFile', 'C') IS NULL
BEGIN
ALTER TABLE dbo.StoryElementReferences DROP CONSTRAINT CK_StoryElementReferences_Entity;
ALTER TABLE dbo.StoryElementReferences WITH CHECK ADD CONSTRAINT CK_StoryElementReferences_Entity CHECK
((CASE WHEN CharacterID IS NULL THEN 0 ELSE 1 END +
CASE WHEN LocationID IS NULL THEN 0 ELSE 1 END +
CASE WHEN StoryAssetID IS NULL THEN 0 ELSE 1 END +
CASE WHEN PlotThreadID IS NULL THEN 0 ELSE 1 END +
CASE WHEN ChapterID IS NULL THEN 0 ELSE 1 END +
CASE WHEN SceneID IS NULL THEN 0 ELSE 1 END) = 1);
ALTER TABLE dbo.StoryElementReferences WITH CHECK ADD CONSTRAINT CK_StoryElementReferences_IntentFile
CHECK ((ChapterID IS NULL AND SceneID IS NULL) OR (Kind IN ('Image', 'Attachment') AND IsPrimary IS NULL));
CREATE INDEX IX_StoryElementReferences_Chapter ON dbo.StoryElementReferences(ChapterID, ReferenceID) WHERE ChapterID IS NOT NULL;
CREATE INDEX IX_StoryElementReferences_Scene ON dbo.StoryElementReferences(SceneID, ReferenceID) WHERE SceneID IS NOT NULL;
END;
GO
CREATE OR ALTER PROCEDURE dbo.StoryElementReference_Access
@UserID int, @EntityType varchar(12), @EntityID int, @Action varchar(12),
@ReferenceID int = NULL, @Version binary(8) = NULL, @Kind varchar(14) = NULL,
@Note nvarchar(500) = NULL, @StoragePath nvarchar(1000) = NULL,
@OriginalFileName nvarchar(300) = NULL, @FileSizeBytes bigint = NULL,
@Title nvarchar(160) = NULL, @StorageLimitBytes bigint = NULL
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
DECLARE @ProjectID int, @EntityName nvarchar(300), @CanEdit bit, @OwnerID int,
@CharacterID int, @LocationID int, @AssetID int, @ThreadID int, @ChapterID int, @SceneID int, @LegacyImagePath nvarchar(1000);
BEGIN TRY
BEGIN TRANSACTION;
IF @EntityType = 'Character'
BEGIN
SET @CharacterID = @EntityID;
SELECT @ProjectID = ProjectID, @EntityName = CharacterName
FROM dbo.Characters WITH (HOLDLOCK) WHERE CharacterID = @EntityID AND IsArchived = 0;
END
ELSE IF @EntityType = 'Location'
BEGIN
SET @LocationID = @EntityID;
SELECT @ProjectID = ProjectID, @EntityName = LocationName
FROM dbo.Locations WITH (HOLDLOCK) WHERE LocationID = @EntityID AND IsArchived = 0;
END
ELSE IF @EntityType = 'Asset'
BEGIN
SET @AssetID = @EntityID;
SELECT @ProjectID = ProjectID, @EntityName = AssetName, @LegacyImagePath = ImagePath
FROM dbo.StoryAssets WITH (HOLDLOCK) WHERE StoryAssetID = @EntityID AND IsArchived = 0;
END
ELSE IF @EntityType = 'PlotThread'
BEGIN
SET @ThreadID = @EntityID;
SELECT @ProjectID = l.ProjectID, @EntityName = t.ThreadTitle
FROM dbo.PlotThreads t WITH (HOLDLOCK)
JOIN dbo.PlotLines l WITH (HOLDLOCK) ON l.PlotLineID = t.PlotLineID
WHERE t.PlotThreadID = @EntityID AND t.IsArchived = 0 AND l.IsArchived = 0;
END
ELSE IF @EntityType IN ('Chapter', 'Scene')
BEGIN
SELECT @ProjectID = t.ProjectID, @EntityName = t.Label,
@ChapterID = CASE WHEN @EntityType = 'Chapter' THEN t.ChapterID END,
@SceneID = t.SceneID
FROM dbo.PlotPlanningTargets t
WHERE (@EntityType = 'Chapter' AND t.ChapterID = @EntityID AND t.SceneID IS NULL)
OR (@EntityType = 'Scene' AND t.SceneID = @EntityID);
END
SELECT @CanEdit = CONVERT(bit, MAX(CASE WHEN a.AccessRole IN (N'Owner', N'Collaborator') THEN 1 ELSE 0 END))
FROM dbo.ProjectUserAccess a WITH (HOLDLOCK)
INNER JOIN dbo.Projects p WITH (HOLDLOCK) ON p.ProjectID = a.ProjectID AND p.IsArchived = 0
WHERE a.ProjectID = @ProjectID AND a.UserID = @UserID AND a.IsActive = 1;
IF @CanEdit IS NULL OR (@Action NOT IN ('list', 'file') AND @CanEdit = 0)
BEGIN
IF @Action = 'list'
SELECT @ProjectID AS ProjectID, @EntityName AS EntityName, @CanEdit AS CanEdit,
@LegacyImagePath AS LegacyImagePath WHERE 1 = 0;
COMMIT;
RETURN;
END
IF @Action = 'list'
BEGIN
SELECT @ProjectID AS ProjectID, @EntityName AS EntityName, @CanEdit AS CanEdit, @LegacyImagePath AS LegacyImagePath;
SELECT ReferenceID, Kind, Note, OriginalFileName, Version, Title, CONVERT(bit, COALESCE(IsPrimary, 0)) AS IsPrimary
FROM dbo.StoryElementReferences
WHERE CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID OR PlotThreadID = @ThreadID OR ChapterID = @ChapterID OR SceneID = @SceneID
ORDER BY ReferenceID;
END
ELSE IF @Action = 'file'
BEGIN
SELECT Kind, StoragePath, OriginalFileName
FROM dbo.StoryElementReferences
WHERE ReferenceID = @ReferenceID AND StoragePath IS NOT NULL
AND (CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID OR PlotThreadID = @ThreadID OR ChapterID = @ChapterID OR SceneID = @SceneID);
END
ELSE IF @Action = 'add'
BEGIN
IF @StoragePath IS NOT NULL
BEGIN
SELECT TOP (1) @OwnerID = UserID FROM dbo.ProjectUserAccess WITH (HOLDLOCK)
WHERE ProjectID = @ProjectID AND AccessRole = N'Owner' AND IsActive = 1
ORDER BY ProjectUserAccessID;
IF @OwnerID IS NULL THROW 51010, 'Project owner unavailable.', 1;
IF @StorageLimitBytes IS NOT NULL AND @FileSizeBytes >
@StorageLimitBytes - (SELECT COALESCE(SUM(FileSizeBytes), 0)
FROM dbo.UserFile WITH (UPDLOCK, HOLDLOCK) WHERE UserID = @OwnerID AND IsDeleted = 0)
BEGIN
SELECT @ProjectID AS ProjectID, CONVERT(bit, 0) AS Changed, CONVERT(bit, 1) AS QuotaExceeded;
COMMIT;
RETURN;
END
END
INSERT dbo.StoryElementReferences (CharacterID, LocationID, StoryAssetID, PlotThreadID, ChapterID, SceneID, Kind, Note, StoragePath, OriginalFileName)
VALUES (@CharacterID, @LocationID, @AssetID, @ThreadID, @ChapterID, @SceneID, @Kind, @Note, @StoragePath, @OriginalFileName);
IF @StoragePath IS NOT NULL
INSERT dbo.UserFile (UserID, ProjectID, EntityType, EntityID, FileName, OriginalFileName, ContentType, FileSizeBytes, StoragePath)
VALUES (@OwnerID, @ProjectID, N'StoryElementReference', CONVERT(int, SCOPE_IDENTITY()),
RIGHT(@StoragePath, CHARINDEX('/', REVERSE(@StoragePath)) - 1), @OriginalFileName,
CASE @Kind WHEN 'Image' THEN N'image/webp' ELSE N'application/octet-stream' END, @FileSizeBytes, @StoragePath);
SELECT @ProjectID AS ProjectID, CONVERT(bit, 1) AS Changed;
END
ELSE IF @Action = 'caption'
BEGIN
UPDATE dbo.CharacterImages SET Caption = NULLIF(@Note, N'')
WHERE CharacterImageID = @ReferenceID AND CharacterID = @CharacterID AND ProjectID = @ProjectID AND IsDeleted = 0;
SELECT @ProjectID AS ProjectID, CONVERT(bit, @@ROWCOUNT) AS Changed;
END
ELSE IF @Action IN ('primary', 'clear')
BEGIN
DECLARE @LockResult int, @Resource nvarchar(255) = CONCAT(N'StoryReferencePrimary:', @EntityType, N':', @EntityID);
EXEC @LockResult = sys.sp_getapplock @Resource = @Resource, @LockMode = 'Exclusive',
@LockOwner = 'Transaction', @LockTimeout = 5000;
IF @LockResult < 0 THROW 51010, 'Primary image selection is busy.', 1;
DECLARE @ImageID int;
SELECT @ImageID = ReferenceID FROM dbo.StoryElementReferences WITH (UPDLOCK)
WHERE ReferenceID = @ReferenceID AND Version = @Version AND Kind = 'Image'
AND (@Action = 'primary' OR IsPrimary = 1)
AND (LocationID = @LocationID OR StoryAssetID = @AssetID);
IF @ImageID IS NOT NULL
BEGIN
UPDATE dbo.StoryElementReferences
SET IsPrimary = NULL
WHERE IsPrimary = 1 AND (LocationID = @LocationID OR StoryAssetID = @AssetID);
IF @Action = 'primary'
UPDATE dbo.StoryElementReferences SET IsPrimary = 1 WHERE ReferenceID = @ImageID;
END
SELECT @ProjectID AS ProjectID, CONVERT(bit, CASE WHEN @ImageID IS NULL THEN 0 ELSE 1 END) AS Changed;
END
ELSE IF @Action = 'edit'
BEGIN
UPDATE dbo.StoryElementReferences SET Note = @Note, Title = @Title
WHERE ReferenceID = @ReferenceID AND Version = @Version
AND (Kind <> 'Characteristic' OR LEN(@Note) > 0)
AND (CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID OR PlotThreadID = @ThreadID OR ChapterID = @ChapterID OR SceneID = @SceneID);
SELECT @ProjectID AS ProjectID, CONVERT(bit, @@ROWCOUNT) AS Changed;
END
ELSE IF @Action = 'delete'
BEGIN
DECLARE @Removed TABLE (StoragePath nvarchar(1000));
DELETE dbo.StoryElementReferences
OUTPUT deleted.StoragePath INTO @Removed
WHERE ReferenceID = @ReferenceID AND Version = @Version
AND (CharacterID = @CharacterID OR LocationID = @LocationID OR StoryAssetID = @AssetID OR PlotThreadID = @ThreadID OR ChapterID = @ChapterID OR SceneID = @SceneID);
SELECT @ProjectID AS ProjectID, CONVERT(bit, COUNT(*)) AS Changed, MAX(StoragePath) AS StoragePath
FROM @Removed;
END
COMMIT;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 ROLLBACK;
THROW;
END CATCH
END;
GO
CREATE OR ALTER PROCEDURE dbo.StoryElementReference_Backup @ProjectID int
AS
BEGIN
SET NOCOUNT ON;
SELECT r.ReferenceID, r.CharacterID, r.LocationID, r.StoryAssetID, r.PlotThreadID, r.ChapterID, r.SceneID,
r.Kind, r.Note, r.StoragePath, r.OriginalFileName, r.Title, r.IsPrimary
FROM dbo.StoryElementReferences r
LEFT JOIN dbo.Characters c ON c.CharacterID = r.CharacterID
LEFT JOIN dbo.Locations l ON l.LocationID = r.LocationID
LEFT JOIN dbo.StoryAssets a ON a.StoryAssetID = r.StoryAssetID
LEFT JOIN dbo.PlotThreads t ON t.PlotThreadID = r.PlotThreadID
LEFT JOIN dbo.PlotLines pl ON pl.PlotLineID = t.PlotLineID
LEFT JOIN dbo.Scenes sc ON sc.SceneID = r.SceneID
LEFT JOIN dbo.Chapters ch ON ch.ChapterID = COALESCE(r.ChapterID, sc.ChapterID)
LEFT JOIN dbo.Books b ON b.BookID = ch.BookID
WHERE COALESCE(c.ProjectID, l.ProjectID, a.ProjectID, pl.ProjectID, b.ProjectID) = @ProjectID
ORDER BY r.ReferenceID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.StoryElementReference_Restore @ProjectID int, @JsonData nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS (
SELECT 1
FROM OPENJSON(@JsonData, '$.Data.StoryElementReferences') WITH
(
ReferenceID int, CharacterID int, LocationID int, StoryAssetID int, PlotThreadID int, ChapterID int, SceneID int, StoragePath nvarchar(1000)
) r
LEFT JOIN dbo.Characters c ON c.CharacterID = r.CharacterID
LEFT JOIN dbo.Locations l ON l.LocationID = r.LocationID
LEFT JOIN dbo.StoryAssets a ON a.StoryAssetID = r.StoryAssetID
LEFT JOIN dbo.PlotThreads t ON t.PlotThreadID = r.PlotThreadID
LEFT JOIN dbo.PlotLines pl ON pl.PlotLineID = t.PlotLineID
LEFT JOIN dbo.Scenes sc ON sc.SceneID = r.SceneID
LEFT JOIN dbo.Chapters ch ON ch.ChapterID = COALESCE(r.ChapterID, sc.ChapterID)
LEFT JOIN dbo.Books b ON b.BookID = ch.BookID
WHERE COALESCE(c.ProjectID, l.ProjectID, a.ProjectID, pl.ProjectID, b.ProjectID, -1) <> @ProjectID
OR (r.StoragePath IS NOT NULL AND NOT EXISTS (
SELECT 1 FROM dbo.UserFile f
WHERE f.ProjectID = @ProjectID AND f.EntityType = N'StoryElementReference'
AND f.EntityID = r.ReferenceID AND f.StoragePath = r.StoragePath AND f.IsDeleted = 0
AND f.FileSizeBytes BETWEEN 1 AND 10485760
AND f.StoragePath LIKE N'/uploads/story-element-references/%.blob'
AND CHARINDEX(N'/', f.StoragePath, LEN(N'/uploads/story-element-references/') + 1) = 0
))
)
THROW 51005, 'Story element reference has an invalid project link or missing staged file.', 1;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryElementReferences',
N'$.Data.StoryElementReferences', @JsonData, @ProjectID, 0;
UPDATE f SET OriginalFileName = r.OriginalFileName,
ContentType = CASE r.Kind WHEN 'Image' THEN N'image/webp' ELSE N'application/octet-stream' END
FROM dbo.UserFile f
INNER JOIN dbo.StoryElementReferences r ON r.ReferenceID = f.EntityID AND r.StoragePath = f.StoragePath
WHERE f.ProjectID = @ProjectID AND f.EntityType = N'StoryElementReference' AND f.IsDeleted = 0;
END;
GO

View File

@ -15,11 +15,12 @@
string? FileUrl(StoryElementReference item, bool save = false) => Url.Action("Download", "StoryElementReferences",
new { entityType = scope.EntityType, entityId = scope.EntityID, referenceId = item.ReferenceID, save });
var editable = references.Access.CanEdit;
var threadAttachments = scope.EntityType == StoryElementType.PlotThread;
var attachmentsOnly = scope.AttachmentsOnly;
var attachmentId = $"reference-attachments-{scope.EntityType}-{scope.EntityID}";
var tabs = new[] { "Images", "Audio", "Documents" };
var primary = references.Items.FirstOrDefault(item => item.IsPrimary);
}
<section id="story-element-references" class="reference-workspace"
<section id="@(scope.EntityType is StoryElementType.Chapter or StoryElementType.Scene ? $"intent-references-{scope.EntityType}-{scope.EntityID}" : "story-element-references")" class="reference-workspace"
data-story-element-references data-project-id="@references.Access.ProjectID"
data-reference-key="@scope.EntityType-@scope.EntityID" data-refresh-url="@refreshUrl"
data-primary-image="@(primary is null ? null : FileUrl(primary))"
@ -37,8 +38,8 @@
<p class="alert alert-warning" role="alert">@legacyError</p>
}
<p class="alert alert-warning" role="alert" data-reference-error hidden="@(TempData.Peek("ReferenceError") is null)">@TempData["ReferenceError"]</p>
<div class="@(threadAttachments ? "mt-3" : "reference-workspace__panes")">
@if (!threadAttachments)
<div class="@(attachmentsOnly ? "mt-3" : "reference-workspace__panes")">
@if (!attachmentsOnly)
{
<section class="reference-workspace__pane" data-reference-scroll aria-labelledby="reference-characteristics">
<h2 id="reference-characteristics">Key characteristics</h2>
@ -71,9 +72,9 @@
aria-orientation="vertical" tabindex="0" aria-valuemin="25" aria-valuemax="70"
aria-valuenow="40" data-reference-divider></div>
}
<section class="reference-workspace__pane" data-reference-scroll aria-labelledby="reference-attachments">
<section class="reference-workspace__pane" data-reference-scroll aria-labelledby="@attachmentId">
<div class="d-flex flex-wrap align-items-baseline justify-content-between gap-2">
<h2 id="reference-attachments">Attachments</h2>
<h2 id="@attachmentId">Attachments</h2>
@if (Model.Storage is not null)
{
<small class="muted" title="Account storage used and subscription allowance">Storage @Model.Storage.DisplayLabel</small>
@ -82,8 +83,8 @@
<div class="reference-workspace__tabs" role="tablist" aria-label="Attachment type">
@foreach (var tab in tabs)
{
<button type="button" class="btn btn-sm" role="tab" id="reference-tab-@tab"
aria-controls="reference-panel-@tab" aria-selected="@(tab == "Images" ? "true" : "false")"
<button type="button" class="btn btn-sm" role="tab" id="@(attachmentId + "-tab-" + tab)"
aria-controls="@(attachmentId + "-panel-" + tab)" aria-selected="@(tab == "Images" ? "true" : "false")"
tabindex="@(tab == "Images" ? 0 : -1)" data-reference-tab="@tab">@tab</button>
}
</div>
@ -92,7 +93,7 @@
var items = references.Items.Where(item => item.Kind != "Characteristic" &&
tab == (item.Kind == "Image" ? "Images" :
StoryElementAttachmentPolicy.AudioType(item.OriginalFileName ?? "") is not null ? "Audio" : "Documents")).ToList();
<section role="tabpanel" id="reference-panel-@tab" aria-labelledby="reference-tab-@tab"
<section role="tabpanel" id="@(attachmentId + "-panel-" + tab)" aria-labelledby="@(attachmentId + "-tab-" + tab)"
data-reference-tab-panel="@tab" hidden="@(tab != "Images")">
@if (editable)
{

View File

@ -33,6 +33,8 @@
@if(Model.Destination is "Write" or "Plan"){
<script src="~/js/context-intent-checklist.js" asp-append-version="true"></script>
<link rel="stylesheet" href="~/css/story-element-references.css" asp-append-version="true" />
<script src="~/js/story-element-references.js" asp-append-version="true"></script>
<script src="~/js/context-intent-palette.js" asp-append-version="true"></script>
<script src="~/js/writer-authoring.js" asp-append-version="true"></script>
<script src="~/js/writer-focus.js" asp-append-version="true"></script>

View File

@ -46,8 +46,6 @@
}
<p class="writer3-caption">Saved records only; no manuscript analysis or inferred story facts. Open Context for the full reference categories and recorded metrics.</p>
</section>
<partial name="~/Views/Writing/_ContextIntentChecklist.cshtml"
model="@(new PlotLine.Services.Context.IntentPaletteScope(0, Model.BookID, Model.ChapterID, Model.SceneID))" />
<partial name="~/Views/Writing/_ContextIntentPalette.cshtml"
<partial name="~/Views/Writing/_ContextIntentPanel.cshtml"
model="@(new PlotLine.Services.Context.IntentPaletteScope(0, Model.BookID, Model.ChapterID, Model.SceneID))" />
</template>

View File

@ -9,7 +9,7 @@
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>() },
new { id = "threads", displayName = "Threads", endpoint = Url.Action("ContextThreadsTab", "Writing"), scope = "Chapter", 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>() },
@ -87,6 +87,8 @@
<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-intent-checklist.js" asp-append-version="true"></script>
<link rel="stylesheet" href="~/css/story-element-references.css" asp-append-version="true" />
<script src="~/js/story-element-references.js" asp-append-version="true"></script>
<script src="~/js/context-intent-palette.js" asp-append-version="true"></script>
<script src="~/js/context-workspace.js" asp-append-version="true"></script>
<script src="~/js/context-environment.js" asp-append-version="true"></script>

View File

@ -1,13 +1,14 @@
@model PlotLine.Services.Context.IntentPaletteScope
<section class="border rounded p-2 mb-2" data-intent-checklist
@{ var fixedScope = ViewData["IntentChecklistScope"] as string; }
<section data-fixed-scope="@fixedScope" class="border rounded p-2 mb-2" data-intent-checklist
data-url="@Url.Action("Checklist", "ContextIntent")"
data-passages-url="@Url.Action("Passages", "ContextIntent")"
data-preview-url="@Url.Action("Preview", "ContextIntent")"
data-book-id="@Model.BookID" data-chapter-id="@Model.ChapterID" data-scene-id="@Model.SceneID">
@Html.AntiForgeryToken()
<h3 class="h6">Intent checklist</h3>
<label class="small" data-checklist-scope-label hidden="@(!Model.SceneID.HasValue)">
<input type="checkbox" data-checklist-scene /> Scene checklist
@if (fixedScope is null) { <h3 class="h6">Intent checklist</h3> }
<label class="small" data-checklist-scope-label hidden="@(fixedScope is not null || !Model.SceneID.HasValue)">
<input type="checkbox" data-checklist-scene checked="@(fixedScope == "scene")" /> Scene checklist
</label>
<p class="small text-body-secondary mb-1" data-checklist-objective hidden></p>
<p class="small text-body-secondary mb-1" data-checklist-outcome hidden></p>
@ -19,6 +20,10 @@
<button type="button" class="btn btn-sm btn-primary" data-checklist-save>Save checklist</button>
<button type="button" class="btn btn-sm btn-outline-secondary" data-checklist-discard>Discard draft</button>
</div>
@if (fixedScope == "scene")
{
<button type="button" class="btn btn-sm btn-outline-secondary mb-2" data-checklist-review-template>Add scene review template</button>
}
<details data-checklist-paste-panel>
<summary>Paste a checklist</summary>
<label class="d-block mt-2">Checklist text
@ -30,7 +35,7 @@
</details>
</div>
<details data-checklist-passages hidden>
<summary>Changed Word passages</summary>
<summary>Review evidence from changed Word passages</summary>
<p class="small text-body-secondary m-1">Drag a passage onto an item to attach evidence and complete it.</p>
<ul class="list-group list-group-flush" data-checklist-passage-list></ul>
</details>

View File

@ -0,0 +1,50 @@
@model PlotLine.Services.Context.IntentMaterial
@foreach (var scope in new[] { false, true })
{
var notes = Model.Notes.Where(n => n.SceneID.HasValue == scope && (!string.IsNullOrWhiteSpace(n.WritingNotes) || n.Items.Count > 0));
var references = Model.References.Where(r => r.SceneID.HasValue == scope);
if (!notes.Any() && !references.Any()) { continue; }
<section class="mb-3">
<h3 class="h6">@(scope ? "Scene planning material" : "Chapter planning material")</h3>
@foreach (var note in notes)
{
<div class="mb-2">
@if (!string.IsNullOrWhiteSpace(note.WritingNotes))
{
<div style="white-space: pre-wrap">@note.WritingNotes</div>
}
@if (note.Items.Count > 0)
{
<ul class="mb-1">
@foreach (var item in note.Items)
{
<li>@item.Title @if (item.Completed) { <small class="text-body-secondary">Completed</small> }</li>
}
</ul>
}
<small class="text-body-secondary">@note.ThreadTitle</small>
</div>
}
<ul class="list-unstyled mb-0">
@foreach (var reference in references)
{
var url = Url.Action("Download", "StoryElementReferences", new { reference.EntityType, reference.EntityID, reference.ReferenceID });
<li class="mb-2">
@if (reference.Kind == "Image")
{
<a href="@url" target="_blank" rel="noopener"><img src="@url" alt="@(reference.Title ?? reference.OriginalFileName)" class="img-fluid d-block" style="max-height: 10rem" loading="lazy" /></a>
}
else if (reference.OriginalFileName is not null)
{
<a href="@url" target="_blank" rel="noopener">@(reference.Title ?? reference.OriginalFileName)</a>
}
@if (!string.IsNullOrWhiteSpace(reference.Note))
{
<div>@reference.Note</div>
}
<small class="text-body-secondary">@reference.Source</small>
</li>
}
</ul>
</section>
}

View File

@ -1,7 +1,43 @@
@using PlotLine.Data
@model PlotLine.Services.Context.IntentPaletteScope
@{ Layout = null; }
@{
var chapterChecklist = new ViewDataDictionary(ViewData) { ["IntentChecklistScope"] = "chapter" };
var sceneChecklist = new ViewDataDictionary(ViewData) { ["IntentChecklistScope"] = "scene" };
}
<div data-context-tab-fragment data-context-intent data-project-id="@Model.ProjectID"
data-book-id="@Model.BookID" data-chapter-id="@Model.ChapterID" data-scene-id="@Model.SceneID">
<partial name="~/Views/Writing/_ContextIntentChecklist.cshtml" model="Model" />
<partial name="~/Views/Writing/_ContextIntentPalette.cshtml" model="Model" />
<div data-intent-material data-material-url="@Url.Action("Material", "ContextIntent")"
data-notes-url="@Url.Action("Notes", "ContextIntent")" data-checklist-url="@Url.Action("Checklist", "ContextIntent")">
@foreach (var scope in new[] { "Chapter", "Scene" })
{
<form class="mb-2" data-intent-notes="@scope" hidden>
@Html.AntiForgeryToken()
<label class="d-block">@scope writing notes
<textarea class="form-control form-control-sm" rows="3" maxlength="100000" readonly></textarea>
</label>
<button class="btn btn-sm btn-outline-primary mt-1" type="submit" disabled>Save notes</button>
<button class="btn btn-sm btn-outline-secondary mt-1" type="button" data-notes-discard disabled>Discard</button>
<span class="small text-body-secondary" role="status"></span>
</form>
}
@foreach (var scope in new[] { StoryElementType.Chapter, StoryElementType.Scene })
{
<details class="mb-2" data-intent-attachments="@scope"
data-attachments-url="@Url.Action("List", "StoryElementReferences", new { entityType = scope })"
hidden="@(scope == StoryElementType.Scene && !Model.SceneID.HasValue)">
<summary>@scope attachments</summary>
<div data-intent-attachment-content></div>
</details>
}
<div data-intent-material-rows></div>
<p class="small text-body-secondary" data-intent-material-status role="status"></p>
</div>
<details class="mb-2">
<summary>Chapter checklist</summary>
<partial name="~/Views/Writing/_ContextIntentChecklist.cshtml" model="Model" view-data="chapterChecklist" />
</details>
<details class="mb-2" data-intent-scene-checklist hidden="@(!Model.SceneID.HasValue)">
<summary>Scene checklist</summary>
<partial name="~/Views/Writing/_ContextIntentChecklist.cshtml" model="Model" view-data="sceneChecklist" />
</details>
</div>

View File

@ -2,9 +2,9 @@
@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</h2>
<p><strong>Current scene</strong><br />@Model.Label</p>
<p>@(Model.SceneID > 0 ? Model.Label : $"Ch {Model.ChapterNumber:0.##}: {Model.ChapterTitle}")</p>
<form hidden>@Html.AntiForgeryToken()</form>
<button type="button" class="btn btn-outline-primary btn-sm" data-thread-add disabled>Add thread</button>
<button type="button" class="btn btn-outline-primary btn-sm" data-thread-add disabled>Include threads</button>
<p role="alert" class="text-danger" data-thread-error></p>
<div class="d-grid gap-2" data-thread-rows><p>Loading saved threads…</p></div>
</div>

View File

@ -5,6 +5,7 @@
function mount(root) {
if (!root || instances.has(root)) return;
const get = name => root.querySelector('[data-checklist-' + name + ']');
const fixedScope = root.dataset.fixedScope;
const scene = get('scene');
const status = get('status');
const rows = get('items');
@ -19,7 +20,7 @@
const entityType = "application/x-plotdirector-intent-element";
function updateControls() {
scene.disabled = dirty || busy;
scene.disabled = !!fixedScope || dirty || busy;
get('save').disabled = !dirty || busy;
get('discard').disabled = !dirty || busy;
rows.inert = busy;
@ -203,7 +204,7 @@
controls.hidden = !next.canEdit;
const objective = get('objective');
objective.textContent = next.objective || '';
objective.hidden = !next.objective;
objective.hidden = !!fixedScope || !next.objective;
const outcome = get('outcome');
outcome.textContent = next.outcome ? 'Outcome: ' + next.outcome : '';
outcome.hidden = !next.outcome;
@ -214,7 +215,7 @@
const scope = () => ({
bookId: Number(root.dataset.bookId),
chapterId: Number(root.dataset.chapterId),
sceneId: scene.checked ? Number(root.dataset.sceneId) : null
sceneId: scene.checked ? Number(root.dataset.sceneId) || null : null
});
async function request(url, body, signal) {
@ -293,6 +294,7 @@
}
async function load(preserve = false) {
if (fixedScope === 'scene' && !root.dataset.sceneId) return;
if (busy || dirty) {
refreshAfterSave ||= preserve;
return;
@ -414,6 +416,15 @@
if (!events.signal.aborted) status.textContent = error.message;
}
});
if (get('review-template')) listen(get('review-template'), 'click', () => {
const template = ['Purpose clear', 'Emotional payoff clear', 'Continuity checked', 'POV consistent',
'Dialogue pass complete', 'Sensory detail pass complete', 'Character motivation clear', 'Ending hook strong'];
const existing = new Set(items.map(item => item.text.toLocaleLowerCase()));
const additions = template.filter(text => !existing.has(text.toLocaleLowerCase()))
.map(text => ({ id: null, text, completed: false, changed: false, notes: '' }));
if (additions.length) append(additions);
});
listen(get('apply'), 'click', () => {
if (prepared.some(item => !item.text.trim())) {
status.textContent = 'Fill in each preview item before adding it.';
@ -432,6 +443,14 @@
status.textContent = 'Choose an item for ' + entity.name + '.';
},
setScene(id) {
if (fixedScope === 'chapter') return;
if (fixedScope === 'scene') {
root.closest('[data-intent-scene-checklist]').hidden = !id;
root.dataset.sceneId = id || '';
if (id) void load();
else { pending?.abort(); readingPassages?.abort(); }
return;
}
const wasSceneScope = scene.checked;
root.dataset.sceneId = id || '';
get('scope-label').hidden = !id;
@ -441,11 +460,12 @@
dispose() { pending?.abort(); readingPassages?.abort(); events.abort(); instances.delete(root); }
};
instances.set(root, instance);
void load();
if (fixedScope !== 'scene' || root.dataset.sceneId) void load();
}
window.PlotDirectorIntentChecklist = {
mountWithin(node) { node.querySelectorAll('[data-intent-checklist]').forEach(mount); },
within(node) { return instances.get(node.querySelector('[data-intent-checklist]')); }
within(node) { return instances.get(node.querySelector('[data-intent-checklist]')); },
allWithin(node) { return [...node.querySelectorAll('[data-intent-checklist]')].map(root => instances.get(root)).filter(Boolean); }
};
})();

View File

@ -3,6 +3,7 @@
const instances = new WeakMap();
function mount(root) {
if (!root) return;
if (instances.has(root)) return instances.get(root);
const search = root.querySelector('[data-palette-search]');
@ -135,32 +136,198 @@
return instance;
}
const checklist = node => window.PlotDirectorIntentChecklist?.within(node);
const materials = new WeakMap();
function mountMaterial(node) {
const root = node.querySelector('[data-intent-material]');
if (!root || materials.has(node)) return;
const abort = new AbortController();
const { signal } = abort;
const bookID = Number(node.dataset.bookId), chapterID = Number(node.dataset.chapterId);
let sceneID = Number(node.dataset.sceneId) || null;
let revision = 0;
const status = root.querySelector('[data-intent-material-status]');
const rows = root.querySelector('[data-intent-material-rows]');
const editors = [...root.querySelectorAll('form')].map(form => ({
form, field: form.querySelector('textarea'), save: form.querySelector('button'),
discard: form.querySelector('[data-notes-discard]'),
message: form.querySelector('[role="status"]'), scene: form.dataset.intentNotes === 'Scene',
saved: '', busy: false, loaded: false
}));
const attachmentSections = [...root.querySelectorAll('[data-intent-attachments]')];
async function loadAttachments(section) {
const content = section.querySelector('[data-intent-attachment-content]');
const panel = content.querySelector('[data-story-element-references]');
if (panel) {
await window.PlotDirectorStoryReferences?.refresh(panel).catch(() => {});
return;
}
const sceneScope = section.dataset.intentAttachments === 'Scene';
const id = sceneScope ? sceneID : chapterID;
if (!id || !section.open || section.dataset.loading === String(id)) return;
section.dataset.loading = String(id);
try {
const url = new URL(section.dataset.attachmentsUrl, location.origin);
url.searchParams.set('entityId', id);
const response = await fetch(url, { cache: 'no-store', signal });
if (!response.ok || response.redirected) throw Error('Attachments are unavailable.');
const html = await response.text();
if (!signal.aborted && (!sceneScope || sceneID === id)) {
content.innerHTML = html;
const workspace = content.querySelector('[data-story-element-references]');
if (workspace) window.PlotDirectorStoryReferences?.mount(workspace);
}
} catch (error) {
if (!signal.aborted && (!sceneScope || sceneID === id)) content.textContent = error.message;
} finally {
if (section.dataset.loading === String(id)) delete section.dataset.loading;
}
}
for (const section of attachmentSections)
section.addEventListener('toggle', () => { if (section.open) void loadAttachments(section); }, { signal });
const dirty = editor => editor.field.value !== editor.saved;
const guarded = () => editors.some(editor => editor.busy || dirty(editor)) || !!root.querySelector("[data-upload-busy]");
const announce = () => node.dispatchEvent(new CustomEvent('context-panel-state', {
bubbles: true, detail: { dirty: guarded() || checklists(node).some(instance => instance.guarded()) }
}));
const params = id => new URLSearchParams({ bookId: bookID, chapterId: chapterID, ...(id ? { sceneId: id } : {}) });
async function refresh() {
const version = ++revision;
const request = async (url, id, read) => {
const response = await fetch(url + '?' + params(id), { cache: 'no-store', signal });
if (!response.ok || response.redirected) throw Error('Writing material is unavailable.');
return response[read]();
};
try {
await Promise.all([
request(root.dataset.materialUrl, sceneID, 'text').then(html => {
if (version === revision) rows.innerHTML = html;
}),
...editors.map(async editor => {
const id = editor.scene ? sceneID : null;
if ((editor.scene && !id) || editor.busy || dirty(editor)) return;
const frame = await request(root.dataset.checklistUrl, id, 'json');
if (version !== revision || editor.busy || dirty(editor)) return;
editor.field.value = editor.saved = (frame.objective || '').replace(/\r\n?/g, '\n');
editor.original = frame.objective;
editor.field.readOnly = !frame.canEdit;
editor.save.disabled = editor.discard.disabled = true;
editor.loaded = true;
editor.form.hidden = false;
})
]);
if (version === revision) status.textContent = '';
} catch (error) {
if (!signal.aborted && version === revision) status.textContent = error.message;
}
}
for (const editor of editors) {
editor.field.addEventListener('input', () => {
editor.save.disabled = editor.discard.disabled = !dirty(editor) || editor.busy;
announce();
}, { signal });
editor.discard.addEventListener('click', () => {
editor.field.value = editor.saved;
editor.message.textContent = '';
editor.save.disabled = editor.discard.disabled = true;
announce();
void refresh();
}, { signal });
editor.form.addEventListener('submit', async event => {
event.preventDefault();
if (!editor.loaded || editor.field.readOnly || editor.busy || !dirty(editor)) return;
editor.busy = true;
editor.save.disabled = editor.discard.disabled = true;
editor.field.readOnly = true;
announce();
try {
const notes = editor.field.value;
const response = await fetch(root.dataset.notesUrl, {
method: 'POST', signal,
headers: { 'Content-Type': 'application/json', RequestVerificationToken: editor.form.querySelector('[name="__RequestVerificationToken"]').value },
body: JSON.stringify({ bookID, chapterID, sceneID: editor.scene ? sceneID : null, original: editor.original, notes })
});
if (!response.ok || response.redirected) {
const body = await response.json().catch(() => null);
throw Error(body?.message || 'Writing notes could not be saved.');
}
editor.original = editor.saved = notes;
editor.message.textContent = '';
window.PlotDirector?.toast?.success('Writing notes saved');
} catch (error) {
if (!signal.aborted) editor.message.textContent = error.message;
} finally {
if (!signal.aborted) {
editor.busy = false;
editor.field.readOnly = false;
editor.save.disabled = editor.discard.disabled = !dirty(editor);
announce();
}
}
}, { signal });
}
materials.set(node, {
refresh() {
for (const section of attachmentSections.filter(section => section.open)) void loadAttachments(section);
return refresh();
},
guarded,
setScene(id) {
const next = Number(id) || null;
if (next === sceneID) return;
sceneID = next;
const attachments = attachmentSections.find(section => section.dataset.intentAttachments === 'Scene');
attachments.hidden = !next;
attachments.querySelector('[data-intent-attachment-content]').replaceChildren();
if (next && attachments.open) void loadAttachments(attachments);
rows.replaceChildren();
const editor = editors.find(entry => entry.scene);
editor.form.hidden = true;
editor.loaded = false;
editor.message.textContent = '';
editor.field.value = editor.saved = '';
void refresh();
},
dispose() { abort.abort(); materials.delete(node); }
});
void refresh();
}
const checklists = node => window.PlotDirectorIntentChecklist?.allWithin(node) ?? [];
const mountChecklist = node => window.PlotDirectorIntentChecklist?.mountWithin(node);
const palette = node => node.querySelector('[data-intent-palette]');
window.PlotDirectorIntentPalette = {
mountWithin(node) { mountChecklist(node); node.querySelectorAll('[data-intent-palette]').forEach(mount); },
mountWithin(node) {
node.querySelectorAll('[data-context-intent]').forEach(mountMaterial);
mountChecklist(node);
node.querySelectorAll('[data-intent-palette]').forEach(mount);
},
guardedWithin(node) {
return checklists(node).some(instance => instance.guarded()) ||
[...node.querySelectorAll('[data-context-intent]')].some(root => materials.get(root)?.guarded());
},
disposeWithin(node) {
checklist(node)?.dispose();
node.querySelectorAll('[data-context-intent]').forEach(root => materials.get(root)?.dispose());
checklists(node).forEach(instance => instance.dispose());
node.querySelectorAll('[data-intent-palette]').forEach(root => instances.get(root)?.dispose());
}
};
window.PlotDirectorContextLifecycles = {
...window.PlotDirectorContextLifecycles,
intent: {
mount(node) { mountChecklist(node); mount(palette(node)); },
canRefresh(node) { return !checklist(node)?.guarded(); },
dispose(node) { checklist(node)?.dispose(); instances.get(palette(node))?.dispose(); },
mount(node) { mountMaterial(node); mountChecklist(node); mount(palette(node)); },
canRefresh(node) { return !checklists(node).some(instance => instance.guarded()) && !materials.get(node)?.guarded(); },
dispose(node) { materials.get(node)?.dispose(); checklists(node).forEach(instance => instance.dispose()); instances.get(palette(node))?.dispose(); },
onPosition(node, next, previous) {
if (next.chapterId !== previous.chapterId) return false;
if (next.chapterId !== previous.chapterId || materials.get(node)?.guarded()) return false;
materials.get(node)?.setScene(next.sceneId);
instances.get(palette(node))?.setScene(next.sceneId);
checklist(node)?.setScene(next.sceneId);
checklists(node).forEach(instance => instance.setScene(next.sceneId));
return true;
},
refreshWhileGuarded: true,
onInvalidation(node) {
void materials.get(node)?.refresh();
void instances.get(palette(node))?.refresh();
void checklist(node)?.refresh();
checklists(node).forEach(instance => void instance.refresh());
return true;
}
}

View File

@ -14,7 +14,7 @@
const sceneLabel = s => `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 bookID = Number(node.dataset.bookId), sceneID = Number(node.dataset.sceneId) || null, chapterID = Number(node.dataset.chapterId);
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;
@ -26,22 +26,43 @@
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 });
const query = new URLSearchParams({ bookId: bookID, chapterId: chapterID, ...(sceneID ? { sceneId: sceneID } : {}) });
const response = await fetch('/ContextThreads/State?' + query, { 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);
const included = data.threads.filter(t => t.includedInChapter || t.includedInScene);
const historical = data.threads.filter(t => t.hasManuscriptAssociation || t.previousScenes.length || (t.assigned && !t.includedInChapter && !t.includedInScene));
const focusKey = rows.contains(document.activeElement) ? document.activeElement.dataset.threadFocus : null;
const openChapters = new Map([...rows.querySelectorAll('details')].map(group => [group.dataset.threadChapter, group.open]));
rows.replaceChildren();
if (!linked.length) rows.append(el('p', 'No threads linked to this scene.'));
for (const thread of linked) {
rows.append(el('h3', 'Included here', 'h6 mb-0'));
if (!included.length) rows.append(el('p', 'No threads included here.', 'small mb-1'));
for (const thread of included) {
const article = el('div', null, 'd-flex gap-2 align-items-center justify-content-between');
const label = el('div', thread.title);
label.append(el('small', ` · ${thread.plotLineName} · ${thread.includedInChapter ? 'Chapter' : 'Scene'}`, 'text-body-secondary'));
article.append(label);
if (thread.canRemove) {
const remove = button('Remove', () => removeLink(thread.plotThreadID, thread.includedInChapter));
remove.dataset.threadFocus = `remove:${thread.plotThreadID}`;
remove.setAttribute('aria-label', `Remove ${thread.title} from ${thread.includedInChapter ? 'chapter' : 'scene'}`);
article.append(remove);
}
rows.append(article);
}
const history = el('details');
history.dataset.threadChapter = 'history';
history.open = openChapters.get('history') ?? false;
history.append(el('summary', 'Assigned elsewhere and scene history'));
for (const thread of historical) {
const article = el('article', null, 'writing-context-card');
article.append(el('p', thread.plotLineName, 'small text-body-secondary mb-1'),
el('h3', thread.title, 'h6'));
if (!thread.previousScenes.length) article.append(el('p', 'First picked up here.', 'small mb-2'));
else {
if (thread.assignedElsewhere && thread.assignmentLabel) article.append(el('p', thread.assignmentLabel, 'small mb-2'));
else if (!thread.previousScenes.length && thread.hasManuscriptAssociation) article.append(el('p', 'Linked in this scene.', 'small mb-2'));
if (thread.previousScenes.length) {
const chapters = new Map();
const lastPickup = thread.previousScenes.at(-1);
for (const scene of thread.previousScenes) {
@ -68,28 +89,23 @@
chapters.get(key).append(item);
}
}
if (thread.canRemove) {
const remove = button('Unassign from scene', () => removeLink(thread.plotThreadID));
remove.dataset.threadFocus = `remove:${thread.plotThreadID}`;
remove.setAttribute('aria-label', `Unassign ${thread.title} from scene`);
article.append(remove);
}
rows.append(article);
history.append(article);
}
if (historical.length) rows.append(history);
add.disabled = !data.scope.canEdit;
if (focusKey) {
const nextFocus = [...rows.querySelectorAll('[data-thread-focus]')].find(control => control.dataset.threadFocus === focusKey);
(nextFocus || add).focus({ preventScroll: true });
}
}
async function removeLink(threadID) {
async function removeLink(threadID, chapter) {
if (!alive || busy || !data?.scope.canEdit) return;
guard(true); error.textContent = '';
try {
const response = await fetch('/ContextThreads/Remove', {
method: 'POST', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', RequestVerificationToken: node.querySelector('[name="__RequestVerificationToken"]').value },
body: JSON.stringify({ bookID, sceneID, threadID })
body: JSON.stringify({ bookID, sceneID, chapterID, threadID, chapter })
});
if (!response.ok || response.redirected) {
const body = await response.json().catch(() => null);
@ -110,57 +126,58 @@
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 heading = el('h2', 'Include threads');
const target = el('p', sceneID ? data.scope.label : data.scope.chapterTitle);
const chapter = el('input');
chapter.type = 'checkbox'; chapter.checked = true; chapter.disabled = !sceneID;
const scopeLabel = el('label', null, 'd-block mb-2');
scopeLabel.append(chapter, ' Include in chapter');
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();
const selected = new Set();
let saving = false;
const submit = button('Add to scene', save), cancel = button('Cancel', () => dialog.close());
const submit = button('Include selected', 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 matches = data.threads.filter(thread => !thread.assigned &&
`${thread.plotLineName} ${thread.title}`.toLocaleLowerCase().includes(term));
const reason = thread => chapter.checked ? thread.chapterBlock : thread.sceneBlock;
for (const [title, items] of [
['Available', matches.filter(thread => !reason(thread))],
['Blocked', matches.filter(thread => reason(thread))]
]) {
if (!items.length) continue;
tree.append(el('h3', title, 'h6 mt-2'));
for (const thread of items) {
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 || thread.assignedElsewhere || saving; input.checked = thread.linked || selected.has(thread.plotThreadID);
const input = el('input');
input.type = 'checkbox';
input.disabled = !!reason(thread) || saving;
input.checked = 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`;
submit.disabled = !selected.size;
});
label.append(input, el('span', thread.title));
if (thread.linked) label.append(el('small', ' · Already linked'));
else if (thread.assignedElsewhere) label.append(el('small', ' · Assigned elsewhere'));
group.append(label);
label.append(input, el('span', `${thread.title} · ${thread.plotLineName}`));
if (reason(thread)) label.append(el('small', reason(thread)));
tree.append(label);
}
tree.append(group);
}
if (!tree.children.length) tree.append(el('p', 'No matching threads.'));
if (!tree.children.length) tree.append(el('p', 'No matching unassigned threads.'));
}
async function save() {
if (saving || !selected.size) return;
saving = true; submit.disabled = true; cancel.disabled = true; search.disabled = true; render();
saving = true; submit.disabled = true; cancel.disabled = true; search.disabled = true; chapter.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] })
body: JSON.stringify({ bookID, sceneID, chapterID, threadIDs: [...selected], chapter: chapter.checked })
});
if (!response.ok || response.redirected) {
const body = await response.json().catch(() => null);
@ -169,14 +186,15 @@
// 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');
window.PlotDirector?.toast?.success('Threads included');
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();
saving = false; submit.disabled = false; cancel.disabled = false; search.disabled = false; chapter.disabled = !sceneID; render();
}
}
search.addEventListener('input', render);
chapter.addEventListener('change', () => { selected.clear(); submit.disabled = true; render(); });
dialog.addEventListener('cancel', event => { if (saving) event.preventDefault(); });
dialog.addEventListener('close', () => {
dialog.remove(); dialog = null;
@ -185,8 +203,8 @@
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');
dialog.append(heading, target, scopeLabel, search, tree, message, submit, cancel);
dialog.setAttribute('aria-label', 'Include threads');
document.body.append(dialog); render(); dialog.showModal(); search.focus();
}
add.addEventListener('click', picker);

View File

@ -125,7 +125,7 @@
const scopeChanged = (tab,before,after) => {
const level=scopes.indexOf(tab.scope);
if(level<=0)return false;
const count=tab.id==='intent'?4:level+1;
const count=['intent','threads'].includes(tab.id)?4:level+1;
return fields.slice(0,count).some(field=>before[field]!==after[field]);
};
const affectedPanels = {

View File

@ -29,7 +29,7 @@
const width = Math.round(Math.max(25, Math.min(70, value)));
states.get(panel).width = width;
panel.style.setProperty('--reference-divider', width + '%');
panel.querySelector('[data-reference-divider]').setAttribute('aria-valuenow', String(width));
panel.querySelector('[data-reference-divider]')?.setAttribute('aria-valuenow', String(width));
}
function mount(panel) {
@ -107,6 +107,11 @@
if (state.busy) return;
state.busy = true;
panel.setAttribute('aria-busy', 'true');
const intent = panel.closest('[data-intent-attachments]');
if (intent) {
intent.dataset.uploadBusy = 'true';
intent.dispatchEvent(new CustomEvent('context-panel-state', { bubbles: true, detail: { busy: true } }));
}
error(panel, '');
let saved = 0;
let current = panel;
@ -146,6 +151,10 @@
}
state.busy = false;
panel.removeAttribute('aria-busy');
if (intent) {
delete intent.dataset.uploadBusy;
intent.dispatchEvent(new CustomEvent('context-panel-state', { bubbles: true, detail: { busy: false } }));
}
if (issues.length) error(current, issues.join(' '));
}
@ -230,6 +239,8 @@
void save(form.closest(workspace), form, null, [...event.dataTransfer.files]);
});
window.PlotDirectorStoryReferences = { mount, refresh };
function mountVisible() {
document.querySelectorAll(workspace).forEach(mount);
}

View File

@ -3,13 +3,13 @@
const root=document.querySelector('[data-writer-authoring]');if(!root)return;
const main=root.closest('.writer3-main');
main.addEventListener('plotdirector:work-state',e=>{const block=e.target.closest('.writer3-session-block');if(!block)return;if(e.detail.session){if(block.nextElementSibling!==root)root.before(block);}else if(block.previousElementSibling!==root)root.after(block);});
const intent=()=>window.PlotDirectorIntentChecklist?.within(document);
let allowLeave=false;const dirty=()=>intent()?.guarded()||[...root.querySelectorAll('[data-authoring-form]')].some(f=>f.dataset.dirty==='true'||f.dataset.busy==='true');
const intentGuarded=()=>window.PlotDirectorIntentPalette?.guardedWithin(document);
let allowLeave=false;const dirty=()=>intentGuarded()||[...root.querySelectorAll('[data-authoring-form]')].some(f=>f.dataset.dirty==='true'||f.dataset.busy==='true');
const cardOf=n=>n.closest('[data-authoring-card]');
const focusEditor=card=>card.querySelector('textarea,select,input:not([type=hidden])')?.focus();
function replaceReferences(template){
const references=document.querySelector('[data-authoring-references]');
if(!references||!template||intent()?.guarded())return;
if(!references||!template||intentGuarded())return;
window.PlotDirectorIntentPalette?.disposeWithin(references);
references.replaceChildren(template.content.cloneNode(true));
window.PlotDirectorIntentPalette?.mountWithin(references);